@haven_ai/signer 0.1.23-alpha.0 → 0.1.23-alpha.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core.ts","../src/capabilities.ts","../src/credentials.ts","../src/audit.ts","../src/sign-context.ts","../src/tools.ts","../src/consent.ts","../src/server.ts"],"names":["addressFromKey","HavenSigningError","signHash","verifySignature","privateKeyToAccount","randomUUID","hashTypedData","selectStandardPaymentOption","HavenApiError","toStandardPaymentRequirements","exact","decodeBase64Json","encodeBase64Json","buildSweepTypedData","recoverTypedDataAddress","buildSweepAuthorizationMessage","hashMessage","x402AuthorizationAmount","SignerRefusalCode","SIGNER_UPDATE_FALLBACK","HavenUnsupportedSignerVersionError","buildX402ExpectedMessage","HavenError","AgentPaymentFailureCode","readFile","stat","resolve","homedir","path","mkdir","dirname","appendFile","createHash","join","z","signature","AgentPaymentNextAction","writeFile","McpServer","isSupportedNodeVersion","unsupportedNodeVersionMessage","StdioServerTransport"],"mappings":";;;;;;;;;;;;;;;AAqJO,SAAS,gBAAA,CACd,WAAA,EACA,OAAA,GAA6B,EAAC,EAClB;AACZ,EAAA,IAAI,eAAA;AACJ,EAAA,IAAI;AACF,IAAA,eAAA,GAAkBA,mBAAe,WAAW,CAAA;AAAA,EAC9C,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAIC,qBAAA;AAAA,MACR,yBAAyB,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,KAC3E;AAAA,EACF;AACA,EAAA,MAAM,YAAA,uBAAmB,GAAA,EAAiC;AAE1D,EAAA,SAAS,cAAc,IAAA,EAAsB;AAC3C,IAAA,MAAM,SAAA,GAAYC,YAAA,CAAS,WAAA,EAAa,IAAI,CAAA;AAE5C,IAAA,IAAI,CAACC,mBAAA,CAAgB,IAAA,EAAM,SAAA,EAAW,eAAe,CA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AAa,OAAA;AAAA,MACtB,SAAS,WAAA,EAAa,OAAA;AAAA,MACtB,WAAW,yBAAA;AAA0B,KACvC;AAAA,IACA;AAAA,MACE,eAAA,EAAiB,OAAA,CAAQ,eAAA,IAAmB,WAAA,EAAa,UAAA;AAAA,MACzD,UAAU,OAAA,CAAQ,QAAA;AAAA,MAClB,KAAK,OAAA,CAAQ,UAAA;AAAA,MACb,KAAK,OAAA,CAAQ;AAAA;AACf,GACF;AACF;AAEA,SAAS,YAAY,OAAA,EAAsB;AACzC,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,CAAC,OAAA,CAAQ,OAAA;AAAA,IAClB,OAAA,EAAS,CAAC,EAAE,IAAA,EAAM,MAAA,EAAiB,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,OAAA,EAAS,IAAA,EAAM,CAAC,CAAA,EAAG;AAAA,GAC7E;AACF","file":"index.cjs","sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { hashMessage, hashTypedData, recoverTypedDataAddress } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { exact } from 'x402/schemes'\nimport {\n addressFromKey,\n buildX402ExpectedMessage,\n buildSweepAuthorizationMessage,\n buildSweepTypedData,\n signHash,\n verifySignature,\n selectStandardPaymentOption,\n toStandardPaymentRequirements,\n x402AuthorizationAmount,\n decodeBase64Json,\n encodeBase64Json,\n AgentPaymentFailureCode,\n HavenError,\n HavenSigningError,\n HavenApiError,\n HavenUnsupportedSignerVersionError,\n SignerRefusalCode,\n SIGNER_UPDATE_FALLBACK,\n type SweepAuthorization,\n type SweepExpectedAuth,\n type X402ExpectedAuth,\n type X402PaymentRequired,\n type X402PaymentOption,\n} from '@haven_ai/sdk'\n\n/**\n * The edge signer core.\n *\n * Holds the delegate key in this process and exposes the two signing\n * operations a hosted-MCP flow needs. It performs no network I/O and never\n * returns the key — only signatures and the standard x402 header. See\n * docs/architecture/07-edge-signer.md.\n */\nexport interface EdgeSigner {\n /** Address derived from the delegate key. */\n readonly delegateAddress: string\n /** Sign an AllowanceModule funding/transfer hash (raw ECDSA, 65 bytes). */\n signPaymentHash(hash: string): string\n /**\n * Sign a DIRECT delegation-rail payment's EIP-712 typed data (#1254) — the\n * non-x402 counterpart of `signX402FundingTypedData`. The Hybrid account\n * validates the typed data, not the bare ERC-4337 hash; raw-signing the\n * hash produced AA24 on-chain (found live, #908 mainnet canary). Signed\n * VERBATIM (#829): the exact structure the hosted result carried — and,\n * unlike a blind hash, a structure whose recipient/amount/account are\n * visible to this process's audit log.\n */\n signDelegationTypedData(typedData: Record<string, unknown>): Promise<string>\n /** Sign an x402 funding hash and remember the funded merchant-header context. */\n signX402FundingHash(hash: string, expected: X402ExpectedPayment): X402FundingSignatureResult\n /**\n * Sign a delegation-rail x402 funding intent's EIP-712 typed data (#1138) and\n * remember the funded merchant-header context, exactly as the hash path does.\n *\n * The account validates this typed data, NOT the bare ERC-4337 hash, so the\n * expected context must be v2 and commit to its digest — see\n * `assertExpectedBinding`.\n */\n signX402FundingTypedData(\n typedData: X402FundingTypedData,\n expected: X402ExpectedPayment,\n ): Promise<X402FundingSignatureResult>\n /** Build + sign the EIP-3009 X-PAYMENT header for the merchant leg of x402. */\n buildX402PaymentHeader(\n paymentRequired: X402PaymentRequired,\n x402Binding: string,\n ): Promise<X402HeaderResult>\n /**\n * Sign a Haven-prepared EIP-3009 sweep authorization (gasless USDC recovery\n * delegate → Safe). Verifies the authorization came from Haven and pays out to\n * the delegate's own Safe before signing; the relayer broadcasts it and pays\n * gas. Never broadcasts — pure signing.\n */\n signSweepAuthorization(input: SweepSignatureInput): Promise<SweepSignatureResult>\n}\n\nexport interface SweepSignatureInput {\n /** The authorization fields prepared by the backend. */\n authorization: SweepAuthorization\n /** Haven's signature over the authorization context (binding). */\n expectedAuth: SweepExpectedAuth\n /** Optional Safe address from the local credential, cross-checked against `to`. */\n expectedSafe?: string\n}\n\nexport interface SweepSignatureResult {\n /** EIP-712 signature over the TransferWithAuthorization, by the delegate key. */\n signature: string\n}\n\n/** EIP-712 payload the delegation-rail account validates (#1138). */\nexport interface X402FundingTypedData {\n domain: Record<string, unknown>\n types: Record<string, unknown>\n primaryType: string\n message: Record<string, unknown>\n}\n\nexport interface X402ExpectedPayment {\n /** Haven payment id for the funding transfer. */\n paymentId: string\n /** Funding hash this expected context authenticates. */\n payloadHash: string\n /**\n * EIP-712 digest of the typed data the account validates (#1138). Present ⇒\n * the binding is v2 and the delegation-rail typed-data path is the ONLY\n * signing path allowed for this intent.\n */\n typedDataHash?: string\n /** Resource URL that was funded by hosted haven_x402_authorize. */\n resourceUrl: string\n /** Merchant recipient that was funded by hosted haven_x402_authorize. */\n merchantTo: string\n /** Atomic amount funded for the merchant header. */\n amount: string\n /** Token contract funded for the merchant header. */\n asset: string\n /** x402 network funded for the merchant header. */\n network: string\n /** ISO expiry for the funding/quote window. When present, the signer refuses stale merchant headers. */\n expiresAt?: string\n /** Haven signature over the expected funding context. */\n auth: X402ExpectedAuth\n}\n\nexport interface X402HeaderResult {\n /** The merchant-verifiable X-PAYMENT header value. */\n paymentHeader: string\n /** The x402 option this header pays. */\n accepted: X402PaymentOption\n}\n\nexport interface X402FundingSignatureResult {\n /** Raw ECDSA signature over the Haven funding hash. */\n signature: string\n /** Opaque process-local binding for the later merchant header signing step. */\n x402Binding: string\n}\n\nexport interface EdgeSignerOptions {\n /** Address allowed to authenticate x402 expected-context messages from Haven. */\n x402BindingSigner?: string\n}\n\nexport function createEdgeSigner(\n delegateKey: string,\n options: EdgeSignerOptions = {},\n): EdgeSigner {\n let delegateAddress: string\n try {\n delegateAddress = addressFromKey(delegateKey)\n } catch (err) {\n throw new HavenSigningError(\n `Invalid delegate key: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n const x402Bindings = new Map<string, X402ExpectedPayment>()\n\n function signAndVerify(hash: string): string {\n const signature = signHash(delegateKey, hash)\n // Verify locally before handing the signature back, mirroring the SDK.\n if (!verifySignature(hash, signature, delegateAddress)) {\n throw new HavenSigningError(\n 'Local signature verification failed — recovered address does not match the delegate key.',\n )\n }\n return signature\n }\n\n return {\n delegateAddress,\n\n signPaymentHash(hash: string): string {\n return signAndVerify(hash)\n },\n\n async signDelegationTypedData(typedData: Record<string, unknown>): Promise<string> {\n const account = privateKeyToAccount(delegateKey as `0x${string}`)\n // Signed VERBATIM (#829/#1254): the exact structure Haven sent, never\n // one reconstructed from components — a re-derived payload is a\n // different payload, and the account validates the original.\n return account.signTypedData(typedData as Parameters<typeof account.signTypedData>[0])\n },\n\n signX402FundingHash(hash: string, expected: X402ExpectedPayment): X402FundingSignatureResult {\n assertExpectedBinding(hash, expected, options.x402BindingSigner, 'hash')\n const signature = signAndVerify(hash)\n const x402Binding = randomUUID()\n x402Bindings.set(x402Binding, { ...expected })\n return { signature, x402Binding }\n },\n\n async signX402FundingTypedData(\n typedData: X402FundingTypedData,\n expected: X402ExpectedPayment,\n ): Promise<X402FundingSignatureResult> {\n assertExpectedBinding(expected.payloadHash, expected, options.x402BindingSigner, 'typed-data')\n // Recompute the digest from the typed data actually in hand and require it\n // to equal Haven's commitment. Everything upstream is untrusted input; this\n // equality is what makes the binding cover the bytes being signed rather\n // than a hash that merely travels alongside them.\n const digest = hashTypedData(typedData as Parameters<typeof hashTypedData>[0])\n if (digest.toLowerCase() !== expected.typedDataHash?.toLowerCase()) {\n throw new HavenSigningError(\n 'x402 typed data does not match the digest Haven committed to in the expected context. ' +\n 'Refusing to sign — the payload was altered in transit or Haven declared a different one. ' +\n 'The most common cause is the typed data being truncated or reshaped while being copied ' +\n 'between tool calls (#1255): re-run the hosted quote and pass its typed_data_b64 string ' +\n 'through UNCHANGED instead of re-emitting the nested JSON.',\n )\n }\n const account = privateKeyToAccount(delegateKey as `0x${string}`)\n // Signed VERBATIM (#829): the exact structure Haven sent, never one\n // reconstructed from components — a re-derived payload is a different\n // payload, and the account validates the original.\n const signature = await account.signTypedData(\n typedData as Parameters<typeof account.signTypedData>[0],\n )\n const x402Binding = randomUUID()\n x402Bindings.set(x402Binding, { ...expected })\n return { signature, x402Binding }\n },\n\n async buildX402PaymentHeader(\n paymentRequired: X402PaymentRequired,\n x402Binding: string,\n ): Promise<X402HeaderResult> {\n const expected = x402Bindings.get(x402Binding)\n if (!expected) {\n throw new HavenSigningError(\n 'x402 funding binding is required before signing a merchant header. Sign the hosted funding hash with x402_expected first.',\n )\n }\n try {\n assertX402PaymentWindowOpen(expected)\n } catch (err) {\n x402Bindings.delete(x402Binding)\n throw err\n }\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n assertX402MatchesExpected(paymentRequired, option, expected)\n\n const account = privateKeyToAccount(delegateKey as `0x${string}`)\n const requirements = toStandardPaymentRequirements(paymentRequired, option)\n const header = await exact.evm.createPaymentHeader(\n account,\n paymentRequired.x402Version,\n requirements,\n )\n\n if (paymentRequired.x402Version < 2) {\n x402Bindings.delete(x402Binding)\n return { paymentHeader: header, accepted: option }\n }\n\n // Always delete the binding — even if encode/decode throws — to prevent the\n // in-process Map from accumulating stale X402ExpectedPayment entries (memory\n // leak + data-retention violation for user payment context).\n try {\n const payment = decodeBase64Json<{ payload: unknown }>(header)\n const wrapped = encodeBase64Json({\n x402Version: paymentRequired.x402Version,\n accepted: option,\n payload: payment.payload,\n })\n return { paymentHeader: wrapped, accepted: option }\n } finally {\n x402Bindings.delete(x402Binding)\n }\n },\n\n async signSweepAuthorization({\n authorization,\n expectedAuth,\n expectedSafe,\n }: SweepSignatureInput): Promise<SweepSignatureResult> {\n // 1. The authorization must have come from Haven (binding), so a malicious\n // hosted server can't get the delegate to sign a transfer to an attacker.\n assertSweepBinding(authorization, expectedAuth, options.x402BindingSigner)\n\n // 2. Funds can only leave the delegate's own key, and only to its own Safe.\n if (!sameAddress(authorization.from, delegateAddress)) {\n throw new HavenSigningError(\n 'Sweep authorization `from` does not match this delegate address.',\n )\n }\n if (expectedSafe && !sameAddress(authorization.to, expectedSafe)) {\n throw new HavenSigningError(\n 'Sweep authorization `to` does not match the Safe in the local credential.',\n )\n }\n\n // 3. Build the EIP-712 typed data (asserts token/chain are canonical USDC),\n // sign it locally, and verify the recovered signer is the delegate.\n const typedData = buildSweepTypedData(authorization)\n // The SDK keeps addresses framework-neutral (`string`); viem wants its\n // `0x`-branded template type. Narrow at the call boundary only.\n const viemTypedData = {\n domain: {\n ...typedData.domain,\n verifyingContract: typedData.domain.verifyingContract as `0x${string}`,\n },\n types: typedData.types,\n primaryType: typedData.primaryType,\n message: {\n ...typedData.message,\n from: typedData.message.from as `0x${string}`,\n to: typedData.message.to as `0x${string}`,\n nonce: typedData.message.nonce as `0x${string}`,\n },\n } as const\n const account = privateKeyToAccount(delegateKey as `0x${string}`)\n const signature = await account.signTypedData(viemTypedData)\n const recovered = await recoverTypedDataAddress({ ...viemTypedData, signature })\n if (!sameAddress(recovered, delegateAddress)) {\n throw new HavenSigningError(\n 'Local sweep signature verification failed — recovered address does not match the delegate key.',\n )\n }\n return { signature }\n },\n }\n}\n\n/**\n * Verify Haven signed the sweep authorization context. Mirrors\n * `assertExpectedBinding` for x402: re-derive the canonical message from the\n * authorization fields, require it match the binding, require the binding signer\n * be the trusted Haven address, and verify the signature. Reuses the x402\n * binding signer — the message namespace differs so the two can't cross-replay.\n */\nfunction assertSweepBinding(\n authorization: SweepAuthorization,\n expectedAuth: SweepExpectedAuth,\n trustedSigner: string | undefined,\n): void {\n if (!expectedAuth || typeof expectedAuth !== 'object') {\n throw new HavenSigningError('Sweep authorization binding is required before signing.')\n }\n if (!trustedSigner) {\n throw new HavenSigningError(\n 'Sweep binding verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing sweep authorizations.',\n )\n }\n // Before any content comparison: an unrecognised version means we cannot\n // reason about this binding at all, so a mismatch below would be a symptom\n // reported as a cause (#1143).\n assertSupportedBindingVersion(\n expectedAuth.version,\n SUPPORTED_SWEEP_BINDING_VERSIONS,\n 'sweep authorization binding',\n )\n const message = buildSweepAuthorizationMessage(authorization)\n if (expectedAuth.message !== message) {\n throw new HavenSigningError('Sweep authorization binding does not match the authorization being signed.')\n }\n if (!sameAddress(expectedAuth.signer, trustedSigner)) {\n throw new HavenSigningError('Sweep authorization binding was not signed by the configured Haven signer.')\n }\n if (!verifySignature(hashMessage(message), expectedAuth.signature, trustedSigner)) {\n throw new HavenSigningError('Sweep authorization binding signature could not be verified.')\n }\n}\n\nexport function assertX402MatchesExpected(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n expected: X402ExpectedPayment,\n): void {\n assertExpectedShape(expected)\n const headerResource = option.resource ?? paymentRequired.resource.url\n if (headerResource !== expected.resourceUrl) {\n throw new HavenSigningError('x402 payment_required resource does not match the funded intent.')\n }\n if (!sameAddress(option.payTo, expected.merchantTo)) {\n throw new HavenSigningError('x402 merchant recipient does not match the funded intent.')\n }\n if (x402AuthorizationAmount(option) !== expected.amount) {\n throw new HavenSigningError('x402 amount does not match the funded intent.')\n }\n if (!sameAddress(option.asset, expected.asset)) {\n throw new HavenSigningError('x402 asset does not match the funded intent.')\n }\n if (option.network !== expected.network) {\n throw new HavenSigningError('x402 network does not match the funded intent.')\n }\n}\n\nfunction assertExpectedShape(expected: X402ExpectedPayment): void {\n if (!expected || typeof expected !== 'object') {\n throw new HavenSigningError('x402 expected funding context is required before signing a merchant header.')\n }\n}\n\n/**\n * Expected-context binding versions THIS signer understands (#1143).\n *\n * The backend deploys continuously from `dev`; a signer reaches users only on a\n * merge to `main` (the publish workflow). So a signer that is one release behind\n * a context bump is a structural state, not an accident, and it needs to report\n * itself as one. These sets are the signer's authority on what it will sign —\n * the tool schemas deliberately accept any positive integer so an unknown\n * version arrives *here* instead of dying at the schema boundary with a raw\n * validation string.\n *\n * **Adding a version here is not sufficient to support it.** The mode rules in\n * `assertExpectedBinding` derive the expected version from the context's\n * *contents* (`typedDataHash` present ⇒ 2), not from `auth.version`, so a v3\n * that carries anything new needs that derivation extended in the same change.\n * Widening this array alone would admit a v3 context to the v1/v2 rule set:\n * the array announces what this signer can evaluate, it does not define it.\n */\nexport const SUPPORTED_X402_EXPECTED_VERSIONS: readonly number[] = [1, 2]\nexport const SUPPORTED_SWEEP_BINDING_VERSIONS: readonly number[] = [1]\n\n/**\n * Fail closed on a binding version this signer does not understand, with an\n * error that names the received version, the ceiling this signer supports, and\n * the fix — both as PROSE (`message`, unchanged since #1143) and, since #1309,\n * as MACHINE-READABLE fields on the thrown error itself\n * (`HavenUnsupportedSignerVersionError`): `code`, `supportedVersions`,\n * `receivedVersion`, `fallback`. The tool boundary (`normalizeError` in\n * `tools.ts`) relays those fields verbatim instead of leaving an agent to\n * regex-parse this prose, which is the diagnosability gap\n * `docs/operations/mcp-runtime-compatibility.md` documents.\n *\n * `supportedVersions`/`receivedVersion` are DERIVED from this call's own\n * arguments — never a second literal — so they cannot drift from\n * `SUPPORTED_X402_EXPECTED_VERSIONS` / `SUPPORTED_SWEEP_BINDING_VERSIONS`,\n * which is what the signing path always passes in.\n *\n * The version travels inside the Haven-signed binding message, so the message\n * also tells the caller not to \"fix\" it by rewriting the field — an agent that\n * does would invalidate the signature and misrepresent what Haven authorised.\n * That instruction is NOT weakened by structuring the refusal: this function\n * still throws before any content check runs, and nothing is ever signed.\n *\n * Exported so a test can pin the historical case (a v2 context against a signer\n * whose set was `{1}`) that this signer can no longer produce on its own. The\n * signing path always passes the module constants above.\n */\nexport function assertSupportedBindingVersion(\n received: number,\n supported: readonly number[],\n context: 'x402 expected context' | 'sweep authorization binding',\n): void {\n if (supported.includes(received)) return\n const highest = Math.max(...supported)\n // The else-branch (\"updating will not restore it\") assumes versions retire\n // MONOTONICALLY from the oldest end — true for how SUPPORTED_* is maintained\n // (append new, drop old). If a future change ever makes the supported set\n // non-contiguous, a gap version would hit that branch and the wording needs\n // revisiting (#1322 review).\n const outOfDate = received > highest\n const code =\n context === 'x402 expected context'\n ? SignerRefusalCode.UnsupportedExpectedContextVersion\n : SignerRefusalCode.UnsupportedSweepBindingVersion\n const ceiling = outOfDate\n ? `This signer is out of date: it supports ${context} versions up to ${highest}, ` +\n `and Haven sent version ${received}. Update @haven_ai/signer — rerun the Haven ` +\n 'connector (`npx @haven_ai/connect@alpha`), which reinstalls the pinned MCP runtime.'\n : `Unsupported ${context} version ${received}: this signer supports ` +\n `${supported.join(', ')}.`\n // Below-floor is the opposite skew (this signer is NEWER than what sent the\n // context, e.g. a retired version) — updating cannot fix it, so the shared\n // \"update the signer\" fallback would be actively wrong here. Only the\n // out-of-date branch, which is the case seen in the field (#1143), uses the\n // canonical single-source fallback shared with the hosted quote's advisory\n // signer_compatibility.fallback (#1155, #1309).\n const fallback = outOfDate\n ? SIGNER_UPDATE_FALLBACK\n : `This ${context} version (${received}) is older than what this signer enforces ` +\n `(${supported.join(', ')}) — updating @haven_ai/signer will not restore it. Nothing ` +\n 'was signed or spent; stop and tell the user rather than retrying.'\n throw new HavenUnsupportedSignerVersionError(\n `${ceiling} Nothing was signed. Do not rewrite the version field to a supported ` +\n 'value: it is part of the Haven-signed binding message, so changing it invalidates ' +\n 'the signature and would misrepresent what Haven authorised.',\n code,\n supported,\n received,\n fallback,\n )\n}\n\n/**\n * Verify Haven's expected-context binding before signing anything.\n *\n * `mode` is what closes the #1138 downgrade in BOTH directions, and neither\n * half is optional:\n *\n * - `'hash'` (legacy rail, raw ECDSA) refuses a **v2** context. A v2 binding\n * means the account validates typed data; raw-signing its 4337 hash would\n * produce a signature the account rejects on-chain, after the intent is\n * claimed.\n * - `'typed-data'` (delegation rail) refuses a **v1** context. Without the\n * `typedDataHash` commitment, Haven's declaration covers only a hash that is\n * NOT what gets signed — the signer would be endorsing a payload it cannot\n * check, which is the whole property this binding exists to provide.\n *\n * The version is derived from the context inside `buildX402ExpectedMessage`, so\n * a tampered `auth.version` cannot select a different rule than the signed\n * message encodes: the recomputed message simply stops matching.\n */\nfunction assertExpectedBinding(\n payloadHash: string,\n expected: X402ExpectedPayment,\n trustedSigner: string | undefined,\n mode: 'hash' | 'typed-data' = 'hash',\n): void {\n assertExpectedShape(expected)\n if (!trustedSigner) {\n throw new HavenSigningError(\n 'x402 expected-context verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing x402 funding hashes.',\n )\n }\n // Skew check first (#1143). Every content check below — the hash comparison,\n // the mode rules, the recomputed message — assumes we understand the context's\n // shape. Under an unknown version they are symptoms, and reporting one as the\n // cause is what sent a live debugging session after the wrong string. A missing\n // `auth` is left to the message check below, which already fails closed on it.\n if (expected.auth) {\n assertSupportedBindingVersion(\n expected.auth.version,\n SUPPORTED_X402_EXPECTED_VERSIONS,\n 'x402 expected context',\n )\n }\n if (expected.payloadHash.toLowerCase() !== payloadHash.toLowerCase()) {\n throw new HavenSigningError('x402 expected context does not match the funding hash being signed.')\n }\n if (mode === 'hash' && expected.typedDataHash) {\n throw new HavenSigningError(\n 'This x402 funding intent commits to EIP-712 typed data, so its bare hash must not be ' +\n 'raw-signed — the account would reject that signature on-chain. Sign sign_data.typed_data instead.',\n )\n }\n if (mode === 'typed-data' && !expected.typedDataHash) {\n throw new HavenSigningError(\n 'Refusing to sign typed data under an expected context that does not commit to it. ' +\n 'Haven must return a v2 x402 expected context (with typedDataHash) for a delegation-rail intent.',\n )\n }\n const message = buildX402ExpectedMessage({\n paymentId: expected.paymentId,\n payloadHash: expected.payloadHash,\n resourceUrl: expected.resourceUrl,\n merchantTo: expected.merchantTo,\n amount: expected.amount,\n asset: expected.asset,\n network: expected.network,\n expiresAt: expected.expiresAt,\n typedDataHash: expected.typedDataHash,\n })\n const expectedVersion = expected.typedDataHash ? 2 : 1\n if (expected.auth?.version !== expectedVersion || expected.auth.message !== message) {\n throw new HavenSigningError('x402 expected context authentication message is invalid.')\n }\n if (!sameAddress(expected.auth.signer, trustedSigner)) {\n throw new HavenSigningError('x402 expected context was not signed by the configured Haven signer.')\n }\n if (!verifySignature(hashMessage(message), expected.auth.signature, trustedSigner)) {\n throw new HavenSigningError('x402 expected context signature could not be verified.')\n }\n}\n\nfunction assertX402PaymentWindowOpen(expected: X402ExpectedPayment): void {\n if (!expected.expiresAt) return\n const expiresAtMs = Date.parse(expected.expiresAt)\n if (Number.isNaN(expiresAtMs)) {\n throw new HavenSigningError('x402 expected context expiresAt is not a valid ISO timestamp.')\n }\n if (expiresAtMs <= Date.now()) {\n throw new HavenError(\n '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.',\n AgentPaymentFailureCode.PaymentWindowExpired,\n 410,\n expected.paymentId,\n )\n }\n}\n\nfunction sameAddress(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase()\n}\n","import {\n SUPPORTED_SWEEP_BINDING_VERSIONS,\n SUPPORTED_X402_EXPECTED_VERSIONS,\n} from './core.js'\n\n/**\n * Pre-payment skew detection (#1155).\n *\n * #1143 made a stale signer say so — but only at the signing step, after the\n * agent had already quoted and was one call away from funding. This module\n * moves the same information to the `initialize` handshake, so the set of\n * expected-context versions this signer understands is observable *before* a\n * payment is attempted.\n *\n * **The check is necessarily agent-mediated.** The signer and the hosted Haven\n * MCP are two separate servers connected to the same client; neither can\n * introspect the other, and the signer never calls the Haven API. Only the\n * agent sees both handshakes, so what ships here is the *information* plus the\n * prompt to compare it — never a server-side gate. A mismatch is advisory: the\n * enforcement point remains the #1143 signing-time guard, which is unchanged.\n *\n * Everything below is DERIVED from the two constants in `core.ts` that the\n * signing path actually enforces. A second hand-maintained literal is the one\n * way this feature could become a lie, so there isn't one — including inside\n * the human-readable `instructions` string, which renders the same arrays.\n */\n\n/**\n * Vendor-prefixed key under MCP's `capabilities.experimental`.\n *\n * `experimental` rather than the newer `extensions` field deliberately: both are\n * `Record<string, object>` in `@modelcontextprotocol/sdk@1.29`, but a client on\n * an older SDK parses the `initialize` result with a `ServerCapabilities` schema\n * that has no `extensions` key, and Zod's default object behaviour would strip\n * it. `experimental` has been in the schema since the beginning, so it survives\n * an old client — which is precisely the population this feature exists for.\n */\nexport const SIGNER_CAPABILITY_KEY = 'haven/signer-compatibility'\n\nexport interface SignerCompatibility {\n /** Expected-context versions this signer will verify (`SUPPORTED_X402_EXPECTED_VERSIONS`). */\n x402_expected_context_versions: number[]\n /** Sweep-binding versions this signer will verify (`SUPPORTED_SWEEP_BINDING_VERSIONS`). */\n sweep_binding_versions: number[]\n}\n\n/** The supported sets this signer enforces, as a plain serialisable object. */\nexport function signerCompatibility(): SignerCompatibility {\n return {\n x402_expected_context_versions: [...SUPPORTED_X402_EXPECTED_VERSIONS],\n sweep_binding_versions: [...SUPPORTED_SWEEP_BINDING_VERSIONS],\n }\n}\n\n/**\n * The machine-readable half: `capabilities.experimental['haven/signer-compatibility']`,\n * returned verbatim in the `initialize` result.\n *\n * `ServerCapabilities.experimental` is typed `z.record(z.string(), <any object>)`\n * and the SDK's `mergeCapabilities` deep-merges per top-level key, so declaring\n * this at construction survives the `tools` capability `McpServer` registers\n * when the first tool is added.\n */\nexport function signerCapabilityAdvertisement(): {\n experimental: Record<string, SignerCompatibility>\n} {\n return { experimental: { [SIGNER_CAPABILITY_KEY]: signerCompatibility() } }\n}\n\n/**\n * The agent-readable half: MCP `instructions`, which clients surface to the\n * model. The machine-readable capability above is the precise statement, but\n * most agent runtimes never expose `capabilities.experimental` to the model —\n * this string is what actually reaches the reader who has to make the call.\n *\n * It names the same fix as #1143 so an agent that hits either surface — the\n * handshake here or the signing-time error there — tells the user the same\n * thing.\n */\nexport function signerInstructions(): string {\n const compatibility = signerCompatibility()\n return [\n 'Haven edge signer: sign-only tools bound to the local delegate key. It never emits the',\n 'key. Its one network capability is an authenticated READ of a signing context from',\n 'Haven by payment_id — pass payment_id to haven_sign / haven_sign_x402 (preferred for',\n 'delegation-rail x402) instead of relaying bulky typed-data payloads yourself.',\n '',\n 'Version compatibility (check this BEFORE signing, not after):',\n `- x402 expected-context versions supported: ${compatibility.x402_expected_context_versions.join(', ')}`,\n `- sweep authorization binding versions supported: ${compatibility.sweep_binding_versions.join(', ')}`,\n '',\n 'Haven quote and prepare results report the expected-context version they will emit',\n '(signer_compatibility.x402_expected_context_version). If that version is not in the list',\n 'above, this signer is out of date: STOP before signing, and tell the user to update',\n '@haven_ai/signer by rerunning `npx @haven_ai/connect@alpha`, which reinstalls the pinned',\n 'MCP runtime. Do not edit the version field to a supported value — it is part of the',\n 'Haven-signed binding message, so changing it invalidates the signature.',\n '',\n 'A version-mismatch refusal from haven_sign / haven_sign_x402 / haven_sign_sweep_delegate is',\n 'machine-readable, not just prose: it carries code, supported_versions, received_version, and',\n 'fallback fields alongside the message, so you can branch on it directly.',\n ].join('\\n')\n}\n","import { readFile, stat } from 'node:fs/promises'\n\n/**\n * The edge signer only needs the delegate key — it signs, it does not call the\n * Haven API. Identity (the `api_key`) lives with the hosted MCP connection, not\n * here. So unlike `@haven_ai/mcp`, this loader requires *only* `delegate_key`.\n */\nexport interface SignerCredentials {\n delegateKey: string\n agentId?: string\n safeAddress?: string\n chainId?: number\n network?: string\n x402BindingSigner?: string\n /** Absolute path the key was loaded from, if a file was used. */\n sourcePath?: string\n}\n\ninterface RawCredentialFile {\n delegate_key?: unknown\n delegateKey?: unknown\n agent_id?: unknown\n agentId?: unknown\n safe_address?: unknown\n safeAddress?: unknown\n chain_id?: unknown\n chainId?: unknown\n network?: unknown\n x402_binding_signer?: unknown\n x402BindingSigner?: unknown\n}\n\n/**\n * Resolve the delegate key for the edge signer.\n *\n * Order — earlier wins:\n * 1. Explicit `path` (e.g. `--credentials <path>`).\n * 2. `HAVEN_CREDENTIALS` env var pointing at a credential JSON file.\n * 3. `HAVEN_DELEGATE_KEY` env var.\n *\n * The same credential JSON the dashboard emits works here — we just read its\n * `delegate_key` and ignore the rest.\n */\nexport async function loadSignerCredentials(\n path: string | undefined = process.env.HAVEN_CREDENTIALS,\n): Promise<SignerCredentials> {\n if (path) return loadFromFile(path)\n\n const envKey = stringField(process.env.HAVEN_DELEGATE_KEY)\n if (envKey) {\n return {\n delegateKey: envKey,\n agentId: stringField(process.env.HAVEN_AGENT_ID),\n safeAddress: stringField(process.env.HAVEN_SAFE_ADDRESS),\n chainId: chainIdField(process.env.HAVEN_CHAIN_ID, 'HAVEN_CHAIN_ID'),\n network: stringField(process.env.HAVEN_NETWORK),\n x402BindingSigner: stringField(process.env.HAVEN_X402_BINDING_SIGNER),\n }\n }\n\n throw new Error(\n 'No delegate key found. Set HAVEN_DELEGATE_KEY, pass --credentials <path>, ' +\n 'or set HAVEN_CREDENTIALS to a Haven agent credential JSON file.',\n )\n}\n\nasync function loadFromFile(path: string): Promise<SignerCredentials> {\n let rawText: string\n try {\n rawText = await readFile(path, 'utf8')\n } catch (err) {\n throw new Error(\n `Could not read Haven credentials at ${path}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n await warnIfCredentialFilePermissive(path)\n\n let raw: RawCredentialFile\n try {\n raw = JSON.parse(rawText) as RawCredentialFile\n } catch {\n throw new Error('Haven credentials must be JSON with a delegate_key field.')\n }\n\n const delegateKey = stringField(raw.delegate_key ?? raw.delegateKey)\n if (!delegateKey) {\n throw new Error('Haven credentials are missing delegate_key — the edge signer needs it to sign.')\n }\n\n return {\n delegateKey,\n agentId: stringField(raw.agent_id ?? raw.agentId),\n safeAddress: stringField(raw.safe_address ?? raw.safeAddress),\n chainId: chainIdField(raw.chain_id ?? raw.chainId, 'chain_id'),\n network: stringField(raw.network),\n x402BindingSigner: stringField(\n raw.x402_binding_signer ??\n raw.x402BindingSigner ??\n process.env.HAVEN_X402_BINDING_SIGNER,\n ),\n sourcePath: path,\n }\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\nfunction chainIdField(value: unknown, label: string): number | undefined {\n if (value === undefined || value === null) return undefined\n\n if (typeof value === 'number') {\n if (Number.isSafeInteger(value) && value > 0) return value\n throw invalidChainIdError(label)\n }\n\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (/^[1-9]\\d*$/.test(trimmed)) {\n const parsed = Number(trimmed)\n if (Number.isSafeInteger(parsed)) return parsed\n }\n throw invalidChainIdError(label)\n }\n\n throw invalidChainIdError(label)\n}\n\nfunction invalidChainIdError(label: string): Error {\n return new Error(`Haven signer credentials ${label} must be a positive integer.`)\n}\n\n/**\n * Warn (best-effort, POSIX only) when the credential file is readable beyond\n * its owner. Mirrors `@haven_ai/mcp`'s check — the delegate key is the most\n * sensitive thing on the machine.\n *\n * Exported for testing.\n */\nexport async function warnIfCredentialFilePermissive(\n path: string,\n log: (message: string) => void = (message) => process.stderr.write(`${message}\\n`),\n platform: NodeJS.Platform = process.platform,\n): Promise<void> {\n if (platform === 'win32') return\n let mode: number\n try {\n mode = (await stat(path)).mode\n } catch {\n return\n }\n if ((mode & 0o077) !== 0) {\n const octal = (mode & 0o777).toString(8).padStart(4, '0')\n log(\n `haven-signer: warning: credential file at ${path} is readable beyond the owner ` +\n `(mode ${octal}). Run: chmod 600 ${path}`,\n )\n }\n}\n","import { createHash } from 'node:crypto'\nimport { appendFile, mkdir } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname, resolve } from 'node:path'\nimport type { SignerToolName } from './tools.js'\n\nexport interface SigningAuditEntry {\n version: 1\n timestamp: string\n tool: SignerToolName\n payload_hash: string\n delegate_address: string\n safe_address?: string\n chain_id?: number\n}\n\nexport interface SigningAuditContext {\n delegateAddress: string\n safeAddress?: string\n chainId?: number\n auditPath?: string\n}\n\nexport function defaultSigningAuditPath(credentialsPath?: string): string {\n if (credentialsPath) return resolve(`${credentialsPath}.signer-audit.jsonl`)\n return resolve(homedir(), '.haven', 'signer-audit.jsonl')\n}\n\nexport async function appendSigningAuditEntry(\n entry: SigningAuditEntry,\n path: string,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await appendFile(path, `${JSON.stringify(entry)}\\n`, 'utf8')\n}\n\nexport function createSigningAuditEntry(\n tool: SignerToolName,\n payloadHash: string,\n context: SigningAuditContext,\n now: Date = new Date(),\n): SigningAuditEntry {\n const entry: SigningAuditEntry = {\n version: 1,\n timestamp: now.toISOString(),\n tool,\n payload_hash: payloadHash,\n delegate_address: context.delegateAddress,\n }\n if (context.safeAddress) entry.safe_address = context.safeAddress\n if (typeof context.chainId === 'number') entry.chain_id = context.chainId\n return entry\n}\n\nexport function hashPayloadForAudit(payload: unknown): string {\n return `0x${createHash('sha256').update(stableStringify(payload)).digest('hex')}`\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n const primitive = JSON.stringify(value)\n return primitive === undefined ? 'undefined' : primitive\n }\n if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`\n const object = value as Record<string, unknown>\n return `{${Object.keys(object)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`)\n .join(',')}}`\n}\n","/**\n * Byte-free signing handoff (#1263): fetch a delegation-rail x402 intent's\n * EXACT signing payload from Haven by `payment_id`, instead of asking a\n * language model to re-emit multi-KB EIP-712 bytes between tool calls (the\n * #1255 failure mode — runtimes that elide long tool results structurally\n * cannot copy them).\n *\n * Layering: this module lives in the local MCP SERVER layer, not the signer\n * core. The core (`core.ts`) remains pure and network-free; what it signs\n * still goes through the SAME digest re-derivation and Haven-binding\n * verification (#1138) whether the bytes arrived by tool argument or by this\n * fetch. The fetch is a strictly better byte source than model relay — TLS to\n * Haven versus a model's context window — and it uses the agent credential\n * (`identity.json`) the connector already stores next to the signer\n * credential. The delegate key is never sent anywhere.\n */\nimport { readFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { HavenSigningError } from '@haven_ai/sdk'\n\nexport interface HavenIdentity {\n apiUrl: string\n apiKey: string\n}\n\n/**\n * Resolve the agent identity from `identity.json` in the same directory as\n * the signer credential file. Returns null (never throws) when unavailable —\n * the caller decides how to phrase the fallback.\n */\nexport async function loadHavenIdentity(\n credentialsPath: string | undefined,\n): Promise<HavenIdentity | null> {\n if (!credentialsPath) return null\n try {\n const raw = JSON.parse(\n await readFile(join(dirname(credentialsPath), 'identity.json'), 'utf8'),\n ) as Record<string, unknown>\n const apiKey = typeof raw.api_key === 'string' ? raw.api_key : undefined\n const apiUrl = typeof raw.api_url === 'string' ? raw.api_url : undefined\n if (!apiKey || !apiUrl) return null\n return { apiKey, apiUrl: apiUrl.replace(/\\/+$/, '') }\n } catch {\n return null\n }\n}\n\nexport interface FetchedSignContext {\n paymentId: string\n payloadHash: string\n typedData: Record<string, unknown>\n /** The COMPLETE snake_case expected context, verbatim from Haven. */\n x402Expected: Record<string, unknown>\n /**\n * #1355: the 402 PaymentRequired persisted at authorize time, when the\n * backend carries it — lets haven_sign_x402 build the merchant header from\n * `{ payment_id }` alone. Null on pre-#1355 backends/rows; the caller then\n * requires the agent-supplied copy. Untrusted like every other fetched\n * field: header building verifies it against the Haven-signed expected\n * context either way.\n */\n paymentRequired: Record<string, unknown> | null\n}\n\n/**\n * GET /x402/:id/sign-context. Read-only; refusals from the backend\n * (expired/executed/legacy/unknown) surface as clear signing errors that name\n * the next step. The returned payload is UNTRUSTED input exactly like a tool\n * argument would be — the signing path's binding verification and digest\n * equality are what make it safe to use, not its provenance.\n */\nexport async function fetchX402SignContext(\n identity: HavenIdentity,\n paymentId: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<FetchedSignContext> {\n let response: Response\n try {\n response = await fetchImpl(\n `${identity.apiUrl}/x402/${encodeURIComponent(paymentId)}/sign-context`,\n { headers: { Authorization: `Bearer ${identity.apiKey}` } },\n )\n } catch (err) {\n throw new HavenSigningError(\n `Could not reach Haven to fetch the signing context for ${paymentId}: ` +\n `${err instanceof Error ? err.message : String(err)}. ` +\n 'Retry, or pass typed_data_b64 from the quote result instead.',\n )\n }\n const body = (await response.json().catch(() => ({}))) as Record<string, unknown>\n if (!response.ok) {\n const detail =\n typeof body.error === 'string' ? body.error : `HTTP ${response.status}`\n throw new HavenSigningError(\n `Haven refused the signing-context fetch for ${paymentId}: ${detail}` +\n (response.status === 404\n ? ' — check the payment_id came from this agent’s own quote.'\n : response.status === 410\n ? ' Re-run the quote with the same idempotency key, then sign the fresh payment_id.'\n : ''),\n )\n }\n const signData = body.sign_data as Record<string, unknown> | undefined\n const x402Expected = body.x402_expected as Record<string, unknown> | undefined\n if (\n !signData ||\n typeof signData.hash !== 'string' ||\n !signData.typed_data ||\n typeof signData.typed_data !== 'object' ||\n !x402Expected\n ) {\n throw new HavenSigningError(\n 'The Haven sign-context response is missing sign_data.typed_data or x402_expected — ' +\n 'the backend may predate #1263. Pass typed_data_b64 from the quote result instead.',\n )\n }\n const paymentRequired = body.payment_required\n return {\n paymentId: String(body.payment_id ?? paymentId),\n payloadHash: signData.hash,\n typedData: signData.typed_data as Record<string, unknown>,\n x402Expected,\n paymentRequired:\n paymentRequired && typeof paymentRequired === 'object' && !Array.isArray(paymentRequired)\n ? (paymentRequired as Record<string, unknown>)\n : null,\n }\n}\n","import {\n AgentPaymentFailureCode,\n AgentPaymentNextAction,\n HavenApiError,\n HavenError,\n HavenSigningError,\n HavenUnsupportedSignerVersionError,\n type X402PaymentRequired,\n} from '@haven_ai/sdk'\nimport { z } from 'zod/v3'\nimport {\n appendSigningAuditEntry,\n createSigningAuditEntry,\n hashPayloadForAudit,\n type SigningAuditContext,\n} from './audit.js'\nimport type {\n EdgeSigner,\n X402ExpectedPayment,\n X402FundingSignatureResult,\n X402FundingTypedData,\n} from './core.js'\nimport {\n fetchX402SignContext,\n type HavenIdentity,\n type FetchedSignContext,\n} from './sign-context.js'\n\n/**\n * Local signer tool set. These run on the agent's machine, next to the key,\n * and pair with the hosted server's construct/relay tools (#183). They sign;\n * they never call the Haven API and never emit the key.\n */\nexport type SignerToolName =\n | 'haven_sign'\n | 'haven_x402_sign_header'\n | 'haven_sign_x402'\n | 'haven_sign_sweep_delegate'\n\nconst sweepAuthorizationSchema = z.object({\n from: z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'from must be a 0x address'),\n to: z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'to must be a 0x address'),\n value: z.string().regex(/^[0-9]+$/, 'value must be a decimal atomic amount'),\n validAfter: z.string().regex(/^[0-9]+$/, 'validAfter must be a decimal unix time'),\n validBefore: z.string().regex(/^[0-9]+$/, 'validBefore must be a decimal unix time'),\n nonce: z.string().regex(/^0x[0-9a-fA-F]{64}$/, 'nonce must be a 0x-prefixed 32-byte hex string'),\n token: z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'token must be a 0x address'),\n chainId: z.number().int().positive(),\n})\n\n/**\n * Binding version at the tool boundary (#1143).\n *\n * Open on purpose. A literal (or literal union) here is validated by the MCP\n * server *before* any handler runs, so a signer one release behind the backend\n * rejected the payment with `Invalid literal value, expected 1 at\n * x402_expected.auth.version` — a message that names neither the cause (your\n * signer is stale) nor the fix (update it), and which no Haven code wrote.\n * Accept any positive integer here and let the signer decide semantically:\n * `SUPPORTED_X402_EXPECTED_VERSIONS` / `SUPPORTED_SWEEP_BINDING_VERSIONS` in\n * `core.ts` still fail closed on anything they do not know, so this widens the\n * *error path*, never what can be signed.\n */\nconst bindingVersionSchema = z.number().int().positive()\n\nconst sweepExpectedAuthSchema = z.object({\n version: bindingVersionSchema,\n message: z.string().min(1),\n signature: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'signature must be a 0x-prefixed hex string'),\n signer: z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'signer must be a 0x address'),\n})\n\nconst x402ExpectedShape = {\n payment_id: z.string().min(1),\n payload_hash: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'payload_hash must be a 0x-prefixed hex string'),\n resource_url: z.string().url(),\n merchant_to: z.string().min(1),\n amount: z.string().min(1),\n asset: z.string().min(1),\n network: z.string().min(1),\n // Required: expires_at is folded into the Haven-signed binding message, so the\n // signer must receive the exact same value to reconstruct a matching message.\n // Omitting it used to fail downstream with a cryptic \"authentication message is\n // invalid\" — making it required surfaces a clear INVALID_INPUT at the boundary.\n expires_at: z.string().min(1),\n // #1138: present on a delegation-rail (v2) context. It commits to the EIP-712\n // typed data the account validates; the signer refuses to raw-sign the bare\n // hash when it is present, and refuses to sign typed data when it is absent.\n typed_data_hash: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'typed_data_hash must be a 0x-prefixed hex string')\n .optional(),\n auth: z.object({\n // Open at the boundary, enforced in the signer — see bindingVersionSchema.\n version: bindingVersionSchema,\n message: z.string().min(1),\n signature: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'signature must be a 0x-prefixed hex string'),\n signer: z.string().min(1),\n }),\n}\n\nconst x402ExpectedSchema = z.object(x402ExpectedShape)\n\nexport const toolSchemas: Record<SignerToolName, z.ZodRawShape> = {\n haven_sign_sweep_delegate: {\n // The authorization fields prepared by Haven's POST /sweep/prepare. Passed\n // through verbatim from the hosted haven_sweep_delegate tool — the signer\n // re-derives the binding message from these exact values.\n authorization: sweepAuthorizationSchema,\n // Haven's signature over the authorization context (the binding).\n expected_auth: sweepExpectedAuthSchema,\n },\n haven_sign: {\n // #1263: THE preferred x402 input — the signer fetches the exact signing\n // payload + expected context from Haven itself (authenticated with the\n // locally-stored agent credential), so no bulky bytes ever cross the\n // model. Pass payment_id ALONE for a delegation-rail x402 funding intent.\n payment_id: z.string().min(1).optional(),\n // The unsigned hash from haven_pay / haven_pay_x402_quote (payload_hash).\n // Optional when payment_id is supplied (the fetch carries it).\n payload_hash: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'payload_hash must be a 0x-prefixed hex string')\n .optional(),\n // Pass x402.expected from hosted haven_pay_x402_quote when this hash funds\n // a standard x402 merchant retry. The signer records it locally and returns\n // an opaque x402_binding for the later header-signing step.\n x402_expected: x402ExpectedSchema.optional(),\n // #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed\n // (not z.unknown()) so MCP clients embed it as JSON rather than a string.\n typed_data: z.record(z.string(), z.unknown()).optional(),\n // #1255: the same payload as ONE opaque base64 string, exactly as returned\n // by the hosted tools. Preferred over typed_data when both are present —\n // an agent re-emitting multi-KB nested JSON between tool calls is the\n // failure mode this field removes (a truncated/reshaped payload fails the\n // digest check and the payment refuses, correctly but pointlessly).\n // Bounded: a realistic redemption payload is ~10KB encoded; 256KB is\n // generous headroom while keeping the offline signer from materializing\n // arbitrarily large caller input.\n typed_data_b64: z.string().min(1).max(262144).optional(),\n },\n haven_x402_sign_header: {\n // The parsed HTTP 402 PaymentRequired from the merchant. Typed as an object\n // (not z.unknown(), which becomes empty JSON Schema `{}`) so MCP clients\n // embed it as JSON rather than serialising the object to a string.\n payment_required: z.record(z.string(), z.unknown()),\n // Opaque binding returned by haven_sign when x402_expected was supplied.\n x402_binding: z.string().min(1),\n },\n haven_sign_x402: {\n // #1263: preferred — pass payment_id (plus payment_required) and the\n // signer fetches the exact signing payload + expected context itself.\n payment_id: z.string().min(1).optional(),\n // One-shot x402 signing: funding hash + merchant header in one local call.\n // Both optional when payment_id is supplied (the fetch carries them).\n payload_hash: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'payload_hash must be a 0x-prefixed hex string')\n .optional(),\n x402_expected: x402ExpectedSchema.optional(),\n // #1355: optional when payment_id is supplied — the signer's context fetch\n // carries the stored 402 PaymentRequired, so `{ payment_id }` alone is the\n // preferred call. Still required (via the runtime check in the handler)\n // for the quote-based fallback path without a payment_id.\n payment_required: z.record(z.string(), z.unknown()).optional(),\n // #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed\n // (not z.unknown()) so MCP clients embed it as JSON rather than a string.\n typed_data: z.record(z.string(), z.unknown()).optional(),\n // #1255: see haven_sign.typed_data_b64 — the copy-through-safe form.\n typed_data_b64: z.string().min(1).max(262144).optional(),\n },\n}\n\nconst SIGN_DESCRIPTION = [\n 'Sign an unsigned Haven payment hash with the local delegate key. The delegate key never leaves',\n 'this process. Pass the payload_hash returned by haven_pay or haven_pay_x402_quote.',\n 'For x402, also pass x402_expected from haven_pay_x402_quote; the signer records it locally',\n 'and returns { signature, x402_binding }. x402_expected includes expires_at; sign before that',\n 'window closes. DELEGATION-RAIL x402 accounts (#1263): pass payment_id ALONE (preferred) — this',\n 'signer fetches the exact signing payload and expected context from Haven itself, so nothing',\n 'bulky ever crosses your context. Fallback: pass typed_data_b64 through UNCHANGED (never re-type',\n 'the nested typed_data JSON); the account validates that EIP-712 payload, not payload_hash.',\n 'Next: call mcp__haven__haven_submit with signature, then pass x402_binding',\n 'to mcp__haven-signer__haven_x402_sign_header. For plain SafeTransfer payments, just pass payload_hash and',\n 'relay the returned signature via mcp__haven__haven_submit.',\n].join(' ')\n\nconst X402_SIGN_HEADER_DESCRIPTION = [\n 'Build and sign the EIP-3009 X-PAYMENT header for the merchant leg of an x402 payment.',\n 'The delegate key stays local — only the signed header crosses any boundary.',\n 'Pass the payment_required from the original merchant 402 response and the x402_binding',\n 'returned by haven_sign. The signer validates the merchant, amount, resource, asset, and',\n 'network against the recorded funding context before signing, checks expires_at when present,',\n 'and rejects mismatches or expired payment windows.',\n 'Returns { payment_header, accepted }. Set X-PAYMENT: <payment_header> on your retry to the',\n 'merchant. Only call after haven_submit has confirmed the funding step (nextAction=none or',\n 'the funding tx has a confirmed status). Next for paid MCP tools: call mcp__haven__haven_complete_mcp_tool.',\n].join(' ')\n\nconst SIGN_X402_DESCRIPTION = [\n 'One-shot x402 signing for the fast 3-call flow: sign the funding hash AND build the EIP-3009',\n 'X-PAYMENT header in a single local call (equivalent to haven_sign followed by',\n 'haven_x402_sign_header). The delegate key never leaves this process. From the haven_pay_mcp_tool',\n 'result pass JUST payment_id — PREFERRED (#1263, #1355): this signer fetches the exact signing',\n 'payload, expected context, and merchant payment_required from Haven itself, so nothing bulky',\n 'crosses your context. If the signer reports the context carried no payment_required (older',\n 'backend), re-call with payment_id plus payment_required verbatim from the pay result.',\n 'Fallback for older backends: pass payload_hash, x402_expected (the nested x402.expected object —',\n 'passing the whole x402 object is also accepted and unwrapped for you), and typed_data_b64',\n 'through UNCHANGED; the signer',\n 'signs the typed data instead of payload_hash and refuses the bare hash when the context commits to typed data.',\n 'Returns',\n '{ signature, x402_binding, payment_header, accepted }; hand signature + payment_header to',\n 'mcp__haven__haven_settle_mcp_tool to fund and settle in one hosted call. The header is built now (before',\n 'funding confirms), so its short validity window starts here — call mcp__haven__haven_settle_mcp_tool promptly,',\n 'and re-run mcp__haven__haven_pay_mcp_tool with the same idempotency_key if a tool returns PAYMENT_WINDOW_EXPIRED.',\n 'Next: call mcp__haven__haven_settle_mcp_tool.',\n].join(' ')\n\nconst SIGN_SWEEP_DELEGATE_DESCRIPTION = [\n 'Sign a Haven-prepared gasless USDC sweep that recovers stranded funds from the delegate',\n 'wallet back to your Haven wallet. The delegate key never leaves this process and this tool',\n 'never broadcasts — it returns only an EIP-3009 signature that Haven\\'s relayer submits and',\n 'pays gas for. Pass the authorization and expected_auth returned by the hosted',\n 'haven_sweep_delegate tool. The signer verifies Haven authored the authorization and that it',\n 'pays out to your own Safe before signing, then returns { signature } to hand back to',\n 'mcp__haven__haven_sweep_delegate to complete recovery.',\n].join(' ')\n\nexport const toolDescriptions: Record<SignerToolName, string> = {\n haven_sign: SIGN_DESCRIPTION,\n haven_x402_sign_header: X402_SIGN_HEADER_DESCRIPTION,\n haven_sign_x402: SIGN_X402_DESCRIPTION,\n haven_sign_sweep_delegate: SIGN_SWEEP_DELEGATE_DESCRIPTION,\n}\n\n/** Map the wire-shaped x402_expected (snake_case) to the EdgeSigner's camelCase context. */\n/**\n * Sign the x402 funding leg on whichever rail the Haven-signed context declares\n * (#1138).\n *\n * The **context** selects the path, never the caller's arguments: a v2 context\n * (one that commits to a typed-data digest) requires typed data, a v1 context\n * requires the bare hash, and `assertExpectedBinding` rejects the mismatch. So\n * an agent that passes `typed_data` on a legacy-rail intent — or omits it on a\n * delegation-rail one — gets a clear refusal here rather than a signature the\n * chain rejects later.\n */\nasync function signFundingLeg(\n signer: EdgeSigner,\n expected: X402ExpectedPayment,\n payloadHash: string,\n typedData: Record<string, unknown> | undefined,\n): Promise<X402FundingSignatureResult> {\n if (!expected.typedDataHash) {\n return signer.signX402FundingHash(payloadHash, expected)\n }\n if (!typedData) {\n throw new HavenSigningError(\n 'This x402 funding intent is on the delegation rail: it commits to EIP-712 typed data, ' +\n 'which was not supplied. Pass typed_data_b64 from haven_pay_mcp_tool / ' +\n 'haven_pay_x402_quote through unchanged (or typed_data verbatim) — the bare ' +\n 'payload_hash is not what the account validates.',\n )\n }\n return signer.signX402FundingTypedData(typedData as unknown as X402FundingTypedData, expected)\n}\n\nfunction toExpectedX402(raw: {\n payment_id: string\n payload_hash: string\n resource_url: string\n merchant_to: string\n amount: string\n asset: string\n network: string\n // Required at the tool boundary (see x402ExpectedSchema): it's folded into the\n // Haven-signed binding message. The EdgeSigner's internal type keeps it\n // optional because it skips the window check when absent.\n expires_at: string\n typed_data_hash?: string\n auth: X402ExpectedPayment['auth']\n}): X402ExpectedPayment {\n return {\n paymentId: raw.payment_id,\n payloadHash: raw.payload_hash,\n typedDataHash: raw.typed_data_hash,\n resourceUrl: raw.resource_url,\n merchantTo: raw.merchant_to,\n amount: raw.amount,\n asset: raw.asset,\n network: raw.network,\n expiresAt: raw.expires_at,\n auth: raw.auth,\n }\n}\n\n/**\n * Validate a FETCHED expected context (#1263) against the same boundary schema\n * a tool argument passes through — provenance does not skip validation. A\n * malformed response names the fallback instead of leaking a Zod stack.\n */\nfunction parseFetchedExpected(\n fetched: FetchedSignContext,\n): Parameters<typeof toExpectedX402>[0] {\n const parsed = z.object(x402ExpectedShape).safeParse(fetched.x402Expected)\n if (!parsed.success) {\n throw new HavenSigningError(\n 'The Haven sign-context response carried a malformed x402_expected — the backend may ' +\n 'predate #1263. Pass payload_hash + x402_expected from the quote result instead. ' +\n `Underlying: ${parsed.error.issues[0]?.message ?? 'schema mismatch'}`,\n )\n }\n return parsed.data as Parameters<typeof toExpectedX402>[0]\n}\n\nexport interface ToolSuccess<T> {\n success: true\n data: T\n}\n\nexport interface ToolFailure {\n success: false\n code: string\n message: string\n statusCode?: number\n paymentId?: string\n next_action?: string\n retry_with_new_quote?: boolean\n suggested_tool?: string\n /**\n * #1309: present on `UNSUPPORTED_EXPECTED_CONTEXT_VERSION` /\n * `UNSUPPORTED_SWEEP_BINDING_VERSION` refusals — the exact version set this\n * signer install enforces, derived from `SUPPORTED_X402_EXPECTED_VERSIONS` /\n * `SUPPORTED_SWEEP_BINDING_VERSIONS` at the throw site.\n */\n supported_versions?: number[]\n /** #1309: the version Haven sent that triggered the refusal above. */\n received_version?: number\n /**\n * #1309: precise recovery guidance as DATA, not just prose inside `message`\n * — the same text the hosted quote's advisory `signer_compatibility.fallback`\n * carries when the refusal is an out-of-date signer.\n */\n fallback?: string\n}\n\nexport type ToolPayload<T = unknown> = ToolSuccess<T> | ToolFailure\n\nexport interface ToolHandlerOptions {\n audit?: SigningAuditContext & { auditPath: string }\n /**\n * #1263: how the payment_id signing path reaches Haven. Lives at the MCP\n * server layer (the core stays network-free); absent → payment_id calls\n * refuse with a message naming the typed_data_b64 fallback.\n */\n signContext?: {\n loadIdentity: () => Promise<HavenIdentity | null>\n fetchImpl?: typeof fetch\n }\n}\n\n/**\n * Resolve the delegation-rail signing payload from the tool arguments (#1255).\n *\n * `typed_data_b64` wins over `typed_data`: it is the copy-through-safe form —\n * one opaque string the agent relays unchanged, instead of re-emitting multi-KB\n * nested JSON (a redemption UserOp's callData) between two tool calls. The live\n * #1255 failure was exactly that: the payload arrived altered, the digest check\n * refused (correctly), and the purchase died with no defect anywhere in the\n * chain. The decoded object goes through the SAME digest verification as a\n * plain typed_data — this changes the transport, never the trust model.\n */\nfunction resolveTypedData(args: {\n typed_data?: Record<string, unknown>\n typed_data_b64?: string\n}): Record<string, unknown> | undefined {\n if (!args.typed_data_b64) return args.typed_data\n try {\n const decoded = JSON.parse(\n Buffer.from(args.typed_data_b64, 'base64').toString('utf8'),\n ) as unknown\n if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) {\n throw new Error('decoded value is not an object')\n }\n return decoded as Record<string, unknown>\n } catch (err) {\n throw new HavenSigningError(\n 'typed_data_b64 did not decode to a JSON object. Pass the exact string returned by the ' +\n 'hosted Haven tool, unchanged — do not re-encode, trim, or reformat it. ' +\n `Underlying error: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\nexport function createToolHandlers(\n signer: EdgeSigner,\n options: ToolHandlerOptions = {},\n): Record<SignerToolName, (input: unknown) => Promise<ToolPayload>> {\n /**\n * #1263: resolve the signing inputs for a payment_id call by fetching the\n * exact bytes from Haven. Returns null when the caller did not use the\n * payment_id path. The fetched payload is untrusted input like any tool\n * argument — it still goes through the binding verification and digest\n * re-derivation downstream; this only changes HOW the bytes arrive.\n */\n async function resolveSignContext(args: {\n payment_id?: string\n payload_hash?: string\n }): Promise<FetchedSignContext | null> {\n if (!args.payment_id) return null\n const identity = (await options.signContext?.loadIdentity()) ?? null\n if (!identity) {\n throw new HavenSigningError(\n 'payment_id signing needs the agent identity (identity.json next to the signer ' +\n 'credentials), which this signer could not load. Re-run `npx @haven_ai/connect@alpha` ' +\n 'to restore it, or pass typed_data_b64 from the quote result instead.',\n )\n }\n const ctx = await fetchX402SignContext(\n identity,\n args.payment_id,\n options.signContext?.fetchImpl,\n )\n if (\n args.payload_hash &&\n args.payload_hash.toLowerCase() !== ctx.payloadHash.toLowerCase()\n ) {\n throw new HavenSigningError(\n 'The supplied payload_hash does not match the signing context Haven serves for ' +\n `payment ${args.payment_id}. Pass payment_id alone, or check which quote the ` +\n 'hash came from.',\n )\n }\n return ctx\n }\n\n return {\n haven_sign: async (input) =>\n runTool(async () => {\n const args = parse('haven_sign', coerceX402Expected(input))\n const fetched = await resolveSignContext(args)\n const typedData = fetched?.typedData ?? resolveTypedData(args)\n const payloadHash = fetched?.payloadHash ?? args.payload_hash\n if (!payloadHash) {\n throw new HavenSigningError(\n 'Pass payment_id (preferred for delegation-rail x402) or payload_hash.',\n )\n }\n const expectedRaw = fetched\n ? parseFetchedExpected(fetched)\n : args.x402_expected\n const x402Expected = expectedRaw ? toExpectedX402(expectedRaw) : null\n const result = x402Expected\n ? await signFundingLeg(signer, x402Expected, payloadHash, typedData)\n : null\n if (!result) {\n // #1254: a DIRECT delegation-rail payment carries typed_data and no\n // x402 context — the account validates the TYPED DATA, and a raw\n // signature over payload_hash is rejected on-chain (AA24, found\n // live). When typed_data is present it is what gets signed; the\n // raw-hash path below is the legacy AllowanceModule rail only.\n if (typedData) {\n const signature = await signer.signDelegationTypedData(typedData)\n await auditSigning('haven_sign', payloadHash)\n return { signature }\n }\n const signature = signer.signPaymentHash(payloadHash)\n await auditSigning('haven_sign', payloadHash)\n return { signature }\n }\n await auditSigning('haven_sign', payloadHash)\n return { signature: result.signature, x402_binding: result.x402Binding }\n }),\n\n haven_x402_sign_header: async (input) =>\n runTool(async () => {\n // Defensive: the object-typed schema makes conformant MCP clients embed\n // payment_required as JSON, but some transports still serialise it to a\n // string. Coerce it back to an object BEFORE Zod validation so the\n // tightened schema doesn't reject it (else `.accepts` would be undefined\n // → \"No compatible payment option found\").\n const args = parse('haven_x402_sign_header', coercePaymentRequired(input))\n const result = await signer.buildX402PaymentHeader(\n args.payment_required as X402PaymentRequired,\n args.x402_binding,\n )\n await auditSigning(\n 'haven_x402_sign_header',\n hashPayloadForAudit(args.payment_required),\n )\n return { payment_header: result.paymentHeader, accepted: result.accepted }\n }),\n\n haven_sign_x402: async (input) =>\n runTool(async () => {\n // Coerce a stringified payment_required (same transport guard as\n // haven_x402_sign_header) and unwrap a whole-`x402`-object x402_expected\n // before validation.\n const args = parse('haven_sign_x402', coerceX402Expected(coercePaymentRequired(input)))\n const fetched = await resolveSignContext(args)\n const payloadHash = fetched?.payloadHash ?? args.payload_hash\n const expectedRaw = fetched ? parseFetchedExpected(fetched) : args.x402_expected\n if (!payloadHash || !expectedRaw) {\n throw new HavenSigningError(\n 'Pass payment_id (preferred — the signer fetches the signing context itself) ' +\n 'or payload_hash + x402_expected from the quote result.',\n )\n }\n // 1. Sign the funding leg (records the binding + checks expiry/context).\n // Which payload that is — bare hash or the account's typed data — is\n // decided by the Haven-signed context, not by the caller (#1138).\n const funding = await signFundingLeg(\n signer,\n toExpectedX402(expectedRaw),\n payloadHash,\n fetched?.typedData ?? resolveTypedData(args),\n )\n // 2. Build the merchant EIP-3009 header against that binding — local, no network.\n // #1355: prefer the PaymentRequired the context fetch carried (same\n // Haven read the signing bytes came from — one less blob an agent\n // relays); the caller-supplied copy is the fallback for pre-#1355\n // backends. Either copy passes the SAME expected-context\n // verification inside buildX402PaymentHeader — provenance is not\n // what makes it safe (#1263 discipline).\n const paymentRequired = (fetched?.paymentRequired ?? args.payment_required) as\n | X402PaymentRequired\n | undefined\n if (!paymentRequired) {\n throw new HavenSigningError(\n fetched\n ? 'The Haven sign-context for this payment_id carried no payment_required ' +\n '(backend predates #1355). Pass payment_required from the pay result ' +\n 'explicitly, verbatim.'\n : 'payment_required is required on the quote-based path (no payment_id to fetch ' +\n 'it by). Pass it verbatim from the quote result.',\n )\n }\n const header = await signer.buildX402PaymentHeader(\n paymentRequired,\n funding.x402Binding,\n )\n // Two audit entries — one per signing operation — matching the\n // decomposed haven_sign + haven_x402_sign_header trail, so the funding\n // signature and the merchant header remain distinguishable in the log.\n await auditSigning('haven_sign_x402', payloadHash)\n await auditSigning('haven_sign_x402', hashPayloadForAudit(paymentRequired))\n return {\n signature: funding.signature,\n x402_binding: funding.x402Binding,\n payment_header: header.paymentHeader,\n accepted: header.accepted,\n }\n }),\n\n haven_sign_sweep_delegate: async (input) =>\n runTool(async () => {\n const args = parse('haven_sign_sweep_delegate', input)\n const result = await signer.signSweepAuthorization({\n authorization: args.authorization,\n expectedAuth: args.expected_auth,\n // Cross-check `to` against the Safe in the local credential when present.\n expectedSafe: options.audit?.safeAddress,\n })\n await auditSigning(\n 'haven_sign_sweep_delegate',\n hashPayloadForAudit(args.authorization),\n )\n return { signature: result.signature }\n }),\n }\n\n async function auditSigning(tool: SignerToolName, payloadHash: string): Promise<void> {\n if (!options.audit) return\n const { auditPath, ...context } = options.audit\n await appendSigningAuditEntry(\n createSigningAuditEntry(tool, payloadHash, {\n ...context,\n delegateAddress: signer.delegateAddress,\n }),\n auditPath,\n )\n }\n}\n\nfunction parse<TName extends SignerToolName>(name: TName, input: unknown): Record<string, any> {\n return z.object(toolSchemas[name]).parse(input ?? {})\n}\n\n/**\n * Tolerate the agent passing the whole `x402` object from haven_pay_mcp_tool /\n * haven_pay_x402_quote where only the nested `x402.expected` signing context is\n * wanted. The wrapper looks like `{ accepted, resource_url, merchant_to,\n * funding_to, expected: {...} }` and lacks the top-level `auth` binding the\n * schema requires — so when `x402_expected.auth` is absent but\n * `x402_expected.expected` is an object, unwrap to `.expected`. Also parses a\n * JSON-stringified value back to an object first (some transports stringify\n * object args). This removes the easiest-to-make handoff mistake without a\n * breaking parameter rename.\n */\nfunction coerceX402Expected(input: unknown): unknown {\n if (!input || typeof input !== 'object') return input\n const record = input as Record<string, unknown>\n let value: unknown = record.x402_expected\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value)\n } catch {\n return input\n }\n }\n if (!value || typeof value !== 'object') return input\n const obj = value as Record<string, unknown>\n if (obj.auth === undefined && obj.expected && typeof obj.expected === 'object') {\n return { ...record, x402_expected: obj.expected }\n }\n // Parsed-from-string but already the right shape: keep the parsed object.\n if (value !== record.x402_expected) return { ...record, x402_expected: value }\n return input\n}\n\n/**\n * If a caller's transport serialised `payment_required` to a JSON string,\n * parse it back to an object before schema validation. Leaves a real object\n * (or anything that isn't valid JSON) untouched.\n */\nfunction coercePaymentRequired(input: unknown): unknown {\n if (!input || typeof input !== 'object') return input\n const record = input as Record<string, unknown>\n if (typeof record.payment_required !== 'string') return input\n try {\n return { ...record, payment_required: JSON.parse(record.payment_required) }\n } catch {\n return input\n }\n}\n\nasync function runTool<T>(fn: () => Promise<T>): Promise<ToolPayload<T>> {\n try {\n return { success: true, data: await fn() }\n } catch (err) {\n return normalizeError(err)\n }\n}\n\nfunction normalizeError(err: unknown): ToolFailure {\n if (err instanceof z.ZodError) {\n return {\n success: false,\n code: 'INVALID_INPUT',\n message: err.errors.map((e) => `${e.path.join('.') || '(root)'}: ${e.message}`).join('; '),\n statusCode: 400,\n }\n }\n if (err instanceof HavenUnsupportedSignerVersionError) {\n // #1309: the structured signer refusal. `code` is one of\n // SignerRefusalCode's two values (not the generic 'SIGNING_ERROR'\n // HavenSigningError hard-codes), so an agent can route on it directly\n // instead of matching prose. next_action reuses the EXISTING\n // AgentPaymentNextAction taxonomy (StopAndTellUser) rather than inventing\n // a parallel vocabulary — this refusal is exactly that: stop, don't retry\n // as-is, tell the user what fallback says.\n return {\n success: false,\n code: err.code,\n message: err.message,\n supported_versions: [...err.supportedVersions],\n received_version: err.receivedVersion,\n fallback: err.fallback,\n next_action: AgentPaymentNextAction.StopAndTellUser,\n }\n }\n if (err instanceof HavenSigningError) {\n return { success: false, code: err.code, message: err.message }\n }\n if (err instanceof HavenApiError) {\n return { success: false, code: err.code, message: err.message, statusCode: err.statusCode }\n }\n if (err instanceof HavenError) {\n return {\n success: false,\n code: err.code,\n message: err.message,\n statusCode: err.statusCode,\n paymentId: err.paymentId,\n ...(err.code === AgentPaymentFailureCode.PaymentWindowExpired\n ? {\n next_action: AgentPaymentNextAction.PaymentWindowExpired,\n retry_with_new_quote: true,\n suggested_tool: 'haven_pay_mcp_tool',\n }\n : {}),\n }\n }\n return {\n success: false,\n code: 'UNKNOWN_ERROR',\n message: err instanceof Error ? err.message : String(err),\n }\n}\n","import { createHash } from 'node:crypto'\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport { toolDescriptions, toolSchemas, type SignerToolName } from './tools.js'\n\nexport interface SignerConsentInput {\n delegateAddress: string\n safeAddress?: string\n agentId?: string\n chainId?: number\n network?: string\n toolNames: readonly SignerToolName[]\n}\n\nexport interface SignerConsentDecision {\n ok: boolean\n hash: string\n reason:\n | 'env_var_match'\n | 'ack_file_match'\n | 'wrote_ack_file'\n | 'env_var_mismatch'\n | 'no_acknowledgement'\n}\n\nexport interface SignerConsentOptions {\n credentialsPath?: string\n writeAck?: boolean\n env?: Record<string, string | undefined>\n out?: { write: (chunk: string) => unknown }\n}\n\nexport const SIGNER_ACK_ENV = 'HAVEN_SIGNER_ACK'\n\n/**\n * The consent SURFACE version, folded into the acknowledgement hash. Bump it\n * when what the signer can DO changes in a way the consent text describes —\n * not for copy edits. Tool names alone cannot carry this: #1263 added the\n * signer's first network capability (the read-only signing-context fetch)\n * without changing any tool name, and a consent acknowledged under the old\n * \"does not call the Haven API\" text must not silently cover the new\n * behavior. Bumping this re-prompts every existing install exactly once,\n * with the corrected text.\n *\n * v2: the #1263 read-only signing-context fetch.\n */\nexport const SIGNER_CONSENT_SURFACE_VERSION = 2\n\nexport function computeSignerConsentHash(input: SignerConsentInput): string {\n const identity = [\n input.delegateAddress.toLowerCase(),\n (input.safeAddress ?? '').toLowerCase(),\n input.agentId ?? '',\n input.chainId ?? '',\n input.network ?? '',\n ].join('|')\n const toolCanonical = [...input.toolNames].sort().join(',')\n return createHash('sha256')\n .update(`${identity}\\n${toolCanonical}\\nsurface:v${SIGNER_CONSENT_SURFACE_VERSION}`)\n .digest('hex')\n .slice(0, 16)\n}\n\nexport function renderSignerConsentBlock(input: SignerConsentInput, hash: string): string {\n const lines: string[] = [\n '',\n '------------------------------------------------------------',\n 'Haven edge signer - first-launch consent',\n '------------------------------------------------------------',\n '',\n `Delegate address: ${input.delegateAddress}`,\n ]\n lines.push(`Haven wallet: ${input.safeAddress ?? 'not provided to this signer'}`)\n if (input.agentId) lines.push(`Agent ID: ${input.agentId}`)\n if (typeof input.chainId === 'number') lines.push(`Chain ID: ${input.chainId}`)\n if (input.network) lines.push(`Network: ${input.network}`)\n lines.push('')\n lines.push('This local signer holds the delegate key on this machine and signs')\n lines.push('payment payloads or x402 merchant headers for the delegate address above.')\n lines.push(\"Its one network use is a read-only fetch of a pending payment's signing\")\n lines.push('payload from Haven, authenticated with the agent credential stored next to')\n lines.push(\"this signer's key file - it never sends the key, a signature, or anything\")\n lines.push('else outbound, and it cannot show a live allowance summary.')\n lines.push('On-chain Safe rules remain the real spend gate, and the wallet owner can')\n lines.push('pause or revoke agent authority outside this signer.')\n lines.push('')\n lines.push('Tools this signer will expose to your agent runtime:')\n for (const name of input.toolNames) {\n lines.push(` - ${name}`)\n lines.push(` ${toolDescriptions[name]}`)\n }\n lines.push('')\n lines.push('A local audit entry is appended for every signing operation. Audit entries')\n lines.push('record timestamp, tool, payload hash, and delegate address; never the key,')\n lines.push('signature, or x402 payment header.')\n lines.push('')\n lines.push(`Consent hash: ${hash}`)\n lines.push('')\n lines.push('To acknowledge, EITHER:')\n lines.push(` - set ${SIGNER_ACK_ENV}=${hash} in this process's environment, OR`)\n lines.push(' - re-run with --ack to write the acknowledgement next to your')\n lines.push(' credential file (sidecar <credentials>.signer-ack.json).')\n lines.push('')\n lines.push('------------------------------------------------------------')\n lines.push('')\n return lines.join('\\n')\n}\n\nexport async function ensureSignerConsent(\n input: SignerConsentInput,\n options: SignerConsentOptions = {},\n): Promise<SignerConsentDecision> {\n const env = options.env ?? process.env\n const out = options.out ?? process.stderr\n const hash = computeSignerConsentHash(input)\n const envAck = env[SIGNER_ACK_ENV]\n\n if (typeof envAck === 'string' && envAck.length > 0) {\n if (envAck === hash) return { ok: true, hash, reason: 'env_var_match' }\n out.write(renderSignerConsentBlock(input, hash))\n out.write(\n `${SIGNER_ACK_ENV} was set but did not match the current signer consent hash.\\n` +\n `Expected: ${hash}\\n` +\n `Got: ${envAck}\\n` +\n `Re-acknowledge with the new hash above, or run with --ack.\\n\\n`,\n )\n return { ok: false, hash, reason: 'env_var_mismatch' }\n }\n\n const ackPath = sidecarPath(options.credentialsPath)\n if (ackPath) {\n const stored = await readAckFile(ackPath)\n if (stored?.ack === hash) return { ok: true, hash, reason: 'ack_file_match' }\n }\n\n if (options.writeAck && ackPath) {\n out.write(renderSignerConsentBlock(input, hash))\n await writeAckFile(ackPath, hash)\n out.write(`Wrote acknowledgement to ${ackPath}\\n\\n`)\n return { ok: true, hash, reason: 'wrote_ack_file' }\n }\n\n out.write(renderSignerConsentBlock(input, hash))\n return { ok: false, hash, reason: 'no_acknowledgement' }\n}\n\nexport function registeredSignerToolNames(): SignerToolName[] {\n return Object.keys(toolSchemas) as SignerToolName[]\n}\n\nfunction sidecarPath(credentialsPath?: string): string | null {\n if (!credentialsPath) return null\n return resolve(`${credentialsPath}.signer-ack.json`)\n}\n\nasync function readAckFile(path: string): Promise<{ ack?: string } | null> {\n try {\n const raw = await readFile(path, 'utf8')\n const parsed = JSON.parse(raw) as { ack?: unknown }\n return { ack: typeof parsed.ack === 'string' ? parsed.ack : undefined }\n } catch {\n return null\n }\n}\n\nasync function writeAckFile(path: string, hash: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(\n path,\n JSON.stringify({ ack: hash, at: new Date().toISOString() }, null, 2),\n 'utf8',\n )\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { defaultSigningAuditPath } from './audit.js'\nimport { signerCapabilityAdvertisement, signerInstructions } from './capabilities.js'\nimport {\n ensureSignerConsent,\n registeredSignerToolNames,\n type SignerConsentDecision,\n} from './consent.js'\nimport { isSupportedNodeVersion, unsupportedNodeVersionMessage } from '@haven_ai/sdk'\nimport { createEdgeSigner, type EdgeSigner } from './core.js'\nimport { loadSignerCredentials, type SignerCredentials } from './credentials.js'\nimport {\n createToolHandlers,\n toolDescriptions,\n toolSchemas,\n type SignerToolName,\n type ToolPayload,\n} from './tools.js'\nimport { loadHavenIdentity } from './sign-context.js'\n\nexport const SIGNER_NAME = '@haven_ai/signer'\nexport const SIGNER_VERSION = '0.1.23-alpha.0'\n\nexport interface SignerOptions {\n /** Path to a Haven credential JSON file (delegate_key is read from it). */\n credentialsPath?: string\n /** Pre-resolved delegate key (skips credential loading). */\n delegateKey?: string\n /** Append local signing audit entries here. Defaults to a credential sidecar or ~/.haven. */\n auditPath?: string\n /** Overridable so the Node-floor refusal is testable without spawning a Node. */\n nodeVersion?: string\n /**\n * When true, write the consent sidecar file (`<credentials>.signer-ack.json`)\n * with the current consent hash and proceed. Surfaced via the `--ack` CLI flag.\n */\n writeAck?: boolean\n /**\n * When true, skip the consent gate entirely. Reserved for tests and controlled\n * embedding — production CLIs should not set this.\n */\n skipConsent?: boolean\n /** Override consent environment lookup. Reserved for tests and controlled embedding. */\n consentEnv?: Record<string, string | undefined>\n /** Override the stream the consent block is printed to. Reserved for tests. */\n consentOut?: { write: (chunk: string) => unknown }\n /** Trusted Haven signer address for x402 expected-context bindings. */\n x402BindingSigner?: string\n}\n\nexport async function resolveEdgeSigner(options: SignerOptions = {}): Promise<EdgeSigner> {\n const { signer } = await resolveSignerRuntime(options)\n return signer\n}\n\nexport interface ResolvedSignerRuntime {\n signer: EdgeSigner\n credentials?: SignerCredentials\n}\n\nexport async function resolveSignerRuntime(\n options: SignerOptions = {},\n): Promise<ResolvedSignerRuntime> {\n // The choke point, deliberately (#1161 review). Every public way to obtain a\n // key-bound EdgeSigner from this package funnels through here —\n // `runSignerStdioServer`, `resolveEdgeSigner`, and any embedder calling it\n // directly (the `skipConsent` docs invite controlled embedding, so that is a\n // supported surface, not just a test seam). Asserting only in the stdio\n // entrypoint would have reproduced the exact bug this issue fixes: a guard\n // that exists but sits on one path while another reaches the delegate key\n // unchecked.\n //\n // First statement, before the `delegateKey` fast path and before credentials\n // are read, so an unsupported runtime never touches a key by either route.\n assertSupportedNodeVersion(options.nodeVersion)\n\n if (options.delegateKey) {\n return {\n signer: createEdgeSigner(options.delegateKey, {\n x402BindingSigner: options.x402BindingSigner ?? process.env.HAVEN_X402_BINDING_SIGNER,\n }),\n }\n }\n const creds = await loadSignerCredentials(options.credentialsPath)\n return {\n signer: createEdgeSigner(creds.delegateKey, {\n x402BindingSigner:\n options.x402BindingSigner ?? creds.x402BindingSigner ?? process.env.HAVEN_X402_BINDING_SIGNER,\n }),\n credentials: creds,\n }\n}\n\n/**\n * Build a local stdio MCP server exposing the sign-only tools, bound to an\n * edge signer that holds the delegate key. It exposes no construct/relay\n * tools — it only signs. Its ONE network capability (#1263) is an\n * authenticated READ: fetching a payment's exact signing context from Haven\n * by payment_id, so agents never have to relay multi-KB signing payloads\n * through a model context. The signer CORE below it stays network-free, and\n * fetched bytes pass the same verification as tool-argument bytes.\n */\nexport function buildSignerMcpServer(\n signer: EdgeSigner,\n options: Pick<SignerOptions, 'auditPath'> & { credentials?: SignerCredentials } = {},\n): McpServer {\n // #1155: the handshake states what this signer can verify, so an agent can\n // detect expected-context skew before it quotes rather than after it signs.\n // `SIGNER_VERSION` is a *package* version and nothing derives capability from\n // it — both fields below are derived from the constants the signing path\n // enforces. Advisory only: no refusal is added here, the #1143 signing-time\n // guard remains the enforcement point.\n const server = new McpServer(\n { name: SIGNER_NAME, version: SIGNER_VERSION },\n {\n capabilities: signerCapabilityAdvertisement(),\n instructions: signerInstructions(),\n },\n )\n\n const credentialsPath = options.credentials?.sourcePath\n const handlers = createToolHandlers(signer, {\n audit: {\n auditPath: options.auditPath ?? defaultSigningAuditPath(credentialsPath),\n delegateAddress: signer.delegateAddress,\n safeAddress: options.credentials?.safeAddress,\n chainId: options.credentials?.chainId,\n },\n // #1263: the payment_id signing path — the ONLY network call this server\n // can make, an authenticated read of a signing context from Haven, using\n // the agent identity the connector stores next to the signer credential.\n // The signer CORE stays network-free; fetched bytes still pass the same\n // binding verification + digest re-derivation as tool-argument bytes.\n signContext: {\n loadIdentity: () => loadHavenIdentity(credentialsPath),\n },\n })\n const registerTool = (server as unknown as {\n tool: (\n name: string,\n description: string,\n schema: unknown,\n handler: (args: unknown) => Promise<unknown>,\n ) => void\n }).tool.bind(server)\n\n for (const name of Object.keys(toolSchemas) as SignerToolName[]) {\n registerTool(name, toolDescriptions[name], toolSchemas[name], async (args: unknown) =>\n toMcpResult(await handlers[name](args)),\n )\n }\n\n return server\n}\n\n/**\n * Refuse to start on an unsupported Node (#1161).\n *\n * Asserted at STARTUP, not only at install, because the two can diverge: a user\n * upgrades Node, connects successfully, then downgrades — or a version manager\n * hands the agent runtime a different Node than the shell that ran setup. Only a\n * startup check sees the version this process is actually running on.\n *\n * This is the signer, so refusing is the conservative answer rather than the\n * aggressive one. It holds the delegate key and produces every payment\n * signature; on an unsupported runtime the plausible failure is a wrong or\n * absent signature, which is worse than not starting. The consent gate below\n * takes the same posture for the same reason.\n */\nexport function assertSupportedNodeVersion(nodeVersion: string = process.versions.node): void {\n if (isSupportedNodeVersion(nodeVersion)) return\n const err: NodeJS.ErrnoException = new Error(\n unsupportedNodeVersionMessage({ subject: 'The Haven signer', nodeVersion }),\n )\n err.code = 'HAVEN_SIGNER_UNSUPPORTED_NODE'\n throw err\n}\n\nexport async function runSignerStdioServer(options: SignerOptions = {}): Promise<void> {\n // The Node floor is asserted inside resolveSignerRuntime — the choke point\n // every key-bound path shares — so it is enforced here too, before\n // credentials are read, without a second call site to keep in sync.\n const { signer, credentials } = await resolveSignerRuntime(options)\n\n if (!options.skipConsent) {\n const decision = await runSignerConsentGate(signer, credentials, options)\n if (!decision.ok) {\n const err: NodeJS.ErrnoException = new Error(\n decision.reason === 'env_var_mismatch'\n ? 'Haven edge signer consent acknowledgement does not match the current configuration.'\n : 'Haven edge signer requires a one-time consent acknowledgement before starting.',\n )\n err.code = 'HAVEN_SIGNER_NO_CONSENT'\n throw err\n }\n }\n\n const server = buildSignerMcpServer(signer, { credentials, auditPath: options.auditPath })\n await server.connect(new StdioServerTransport())\n}\n\nexport async function runSignerConsentGate(\n signer: EdgeSigner,\n credentials: SignerCredentials | undefined,\n options: SignerOptions,\n): Promise<SignerConsentDecision> {\n return ensureSignerConsent(\n {\n delegateAddress: signer.delegateAddress,\n safeAddress: credentials?.safeAddress,\n agentId: credentials?.agentId,\n chainId: credentials?.chainId,\n network: credentials?.network,\n toolNames: registeredSignerToolNames(),\n },\n {\n credentialsPath: options.credentialsPath ?? credentials?.sourcePath,\n writeAck: options.writeAck,\n env: options.consentEnv,\n out: options.consentOut,\n },\n )\n}\n\nfunction toMcpResult(payload: ToolPayload) {\n return {\n isError: !payload.success,\n content: [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }],\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/core.ts","../src/capabilities.ts","../src/credentials.ts","../src/audit.ts","../src/sign-context.ts","../src/tools.ts","../src/consent.ts","../src/server.ts"],"names":["addressFromKey","HavenSigningError","signHash","verifySignature","privateKeyToAccount","randomUUID","hashTypedData","selectStandardPaymentOption","HavenApiError","toStandardPaymentRequirements","exact","decodeBase64Json","encodeBase64Json","buildSweepTypedData","recoverTypedDataAddress","buildSweepAuthorizationMessage","hashMessage","x402AuthorizationAmount","SignerRefusalCode","SIGNER_UPDATE_FALLBACK","HavenUnsupportedSignerVersionError","buildX402ExpectedMessage","HavenError","AgentPaymentFailureCode","readFile","stat","resolve","homedir","path","mkdir","dirname","appendFile","createHash","join","z","signature","AgentPaymentNextAction","writeFile","McpServer","isSupportedNodeVersion","unsupportedNodeVersionMessage","StdioServerTransport"],"mappings":";;;;;;;;;;;;;;;AAqJO,SAAS,gBAAA,CACd,WAAA,EACA,OAAA,GAA6B,EAAC,EAClB;AACZ,EAAA,IAAI,eAAA;AACJ,EAAA,IAAI;AACF,IAAA,eAAA,GAAkBA,mBAAe,WAAW,CAAA;AAAA,EAC9C,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAIC,qBAAA;AAAA,MACR,yBAAyB,GAAA,YAAe,KAAA,GAAQ,IAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,KAC3E;AAAA,EACF;AACA,EAAA,MAAM,YAAA,uBAAmB,GAAA,EAAiC;AAE1D,EAAA,SAAS,cAAc,IAAA,EAAsB;AAC3C,IAAA,MAAM,SAAA,GAAYC,YAAA,CAAS,WAAA,EAAa,IAAI,CAAA;AAE5C,IAAA,IAAI,CAACC,mBAAA,CAAgB,IAAA,EAAM,SAAA,EAAW,eAAe,CAAA,EAAG;AACtD,MAAA,MAAM,IAAIF,qBAAA;AAAA,QACR;AAAA,OACF;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,yBAAA;AAA0B,KACvC;AAAA,IACA;AAAA,MACE,eAAA,EAAiB,OAAA,CAAQ,eAAA,IAAmB,WAAA,EAAa,UAAA;AAAA,MACzD,UAAU,OAAA,CAAQ,QAAA;AAAA,MAClB,KAAK,OAAA,CAAQ,UAAA;AAAA,MACb,KAAK,OAAA,CAAQ;AAAA;AACf,GACF;AACF;AAEA,SAAS,YAAY,OAAA,EAAsB;AACzC,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,CAAC,OAAA,CAAQ,OAAA;AAAA,IAClB,OAAA,EAAS,CAAC,EAAE,IAAA,EAAM,MAAA,EAAiB,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,OAAA,EAAS,IAAA,EAAM,CAAC,CAAA,EAAG;AAAA,GAC7E;AACF","file":"index.cjs","sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { hashMessage, hashTypedData, recoverTypedDataAddress } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { exact } from 'x402/schemes'\nimport {\n addressFromKey,\n buildX402ExpectedMessage,\n buildSweepAuthorizationMessage,\n buildSweepTypedData,\n signHash,\n verifySignature,\n selectStandardPaymentOption,\n toStandardPaymentRequirements,\n x402AuthorizationAmount,\n decodeBase64Json,\n encodeBase64Json,\n AgentPaymentFailureCode,\n HavenError,\n HavenSigningError,\n HavenApiError,\n HavenUnsupportedSignerVersionError,\n SignerRefusalCode,\n SIGNER_UPDATE_FALLBACK,\n type SweepAuthorization,\n type SweepExpectedAuth,\n type X402ExpectedAuth,\n type X402PaymentRequired,\n type X402PaymentOption,\n} from '@haven_ai/sdk'\n\n/**\n * The edge signer core.\n *\n * Holds the delegate key in this process and exposes the two signing\n * operations a hosted-MCP flow needs. It performs no network I/O and never\n * returns the key — only signatures and the standard x402 header. See\n * docs/architecture/07-edge-signer.md.\n */\nexport interface EdgeSigner {\n /** Address derived from the delegate key. */\n readonly delegateAddress: string\n /** Sign an AllowanceModule funding/transfer hash (raw ECDSA, 65 bytes). */\n signPaymentHash(hash: string): string\n /**\n * Sign a DIRECT delegation-rail payment's EIP-712 typed data (#1254) — the\n * non-x402 counterpart of `signX402FundingTypedData`. The Hybrid account\n * validates the typed data, not the bare ERC-4337 hash; raw-signing the\n * hash produced AA24 on-chain (found live, #908 mainnet canary). Signed\n * VERBATIM (#829): the exact structure the hosted result carried — and,\n * unlike a blind hash, a structure whose recipient/amount/account are\n * visible to this process's audit log.\n */\n signDelegationTypedData(typedData: Record<string, unknown>): Promise<string>\n /** Sign an x402 funding hash and remember the funded merchant-header context. */\n signX402FundingHash(hash: string, expected: X402ExpectedPayment): X402FundingSignatureResult\n /**\n * Sign a delegation-rail x402 funding intent's EIP-712 typed data (#1138) and\n * remember the funded merchant-header context, exactly as the hash path does.\n *\n * The account validates this typed data, NOT the bare ERC-4337 hash, so the\n * expected context must be v2 and commit to its digest — see\n * `assertExpectedBinding`.\n */\n signX402FundingTypedData(\n typedData: X402FundingTypedData,\n expected: X402ExpectedPayment,\n ): Promise<X402FundingSignatureResult>\n /** Build + sign the EIP-3009 X-PAYMENT header for the merchant leg of x402. */\n buildX402PaymentHeader(\n paymentRequired: X402PaymentRequired,\n x402Binding: string,\n ): Promise<X402HeaderResult>\n /**\n * Sign a Haven-prepared EIP-3009 sweep authorization (gasless USDC recovery\n * delegate → Safe). Verifies the authorization came from Haven and pays out to\n * the delegate's own Safe before signing; the relayer broadcasts it and pays\n * gas. Never broadcasts — pure signing.\n */\n signSweepAuthorization(input: SweepSignatureInput): Promise<SweepSignatureResult>\n}\n\nexport interface SweepSignatureInput {\n /** The authorization fields prepared by the backend. */\n authorization: SweepAuthorization\n /** Haven's signature over the authorization context (binding). */\n expectedAuth: SweepExpectedAuth\n /** Optional Safe address from the local credential, cross-checked against `to`. */\n expectedSafe?: string\n}\n\nexport interface SweepSignatureResult {\n /** EIP-712 signature over the TransferWithAuthorization, by the delegate key. */\n signature: string\n}\n\n/** EIP-712 payload the delegation-rail account validates (#1138). */\nexport interface X402FundingTypedData {\n domain: Record<string, unknown>\n types: Record<string, unknown>\n primaryType: string\n message: Record<string, unknown>\n}\n\nexport interface X402ExpectedPayment {\n /** Haven payment id for the funding transfer. */\n paymentId: string\n /** Funding hash this expected context authenticates. */\n payloadHash: string\n /**\n * EIP-712 digest of the typed data the account validates (#1138). Present ⇒\n * the binding is v2 and the delegation-rail typed-data path is the ONLY\n * signing path allowed for this intent.\n */\n typedDataHash?: string\n /** Resource URL that was funded by hosted haven_x402_authorize. */\n resourceUrl: string\n /** Merchant recipient that was funded by hosted haven_x402_authorize. */\n merchantTo: string\n /** Atomic amount funded for the merchant header. */\n amount: string\n /** Token contract funded for the merchant header. */\n asset: string\n /** x402 network funded for the merchant header. */\n network: string\n /** ISO expiry for the funding/quote window. When present, the signer refuses stale merchant headers. */\n expiresAt?: string\n /** Haven signature over the expected funding context. */\n auth: X402ExpectedAuth\n}\n\nexport interface X402HeaderResult {\n /** The merchant-verifiable X-PAYMENT header value. */\n paymentHeader: string\n /** The x402 option this header pays. */\n accepted: X402PaymentOption\n}\n\nexport interface X402FundingSignatureResult {\n /** Raw ECDSA signature over the Haven funding hash. */\n signature: string\n /** Opaque process-local binding for the later merchant header signing step. */\n x402Binding: string\n}\n\nexport interface EdgeSignerOptions {\n /** Address allowed to authenticate x402 expected-context messages from Haven. */\n x402BindingSigner?: string\n}\n\nexport function createEdgeSigner(\n delegateKey: string,\n options: EdgeSignerOptions = {},\n): EdgeSigner {\n let delegateAddress: string\n try {\n delegateAddress = addressFromKey(delegateKey)\n } catch (err) {\n throw new HavenSigningError(\n `Invalid delegate key: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n const x402Bindings = new Map<string, X402ExpectedPayment>()\n\n function signAndVerify(hash: string): string {\n const signature = signHash(delegateKey, hash)\n // Verify locally before handing the signature back, mirroring the SDK.\n if (!verifySignature(hash, signature, delegateAddress)) {\n throw new HavenSigningError(\n 'Local signature verification failed — recovered address does not match the delegate key.',\n )\n }\n return signature\n }\n\n return {\n delegateAddress,\n\n signPaymentHash(hash: string): string {\n return signAndVerify(hash)\n },\n\n async signDelegationTypedData(typedData: Record<string, unknown>): Promise<string> {\n const account = privateKeyToAccount(delegateKey as `0x${string}`)\n // Signed VERBATIM (#829/#1254): the exact structure Haven sent, never\n // one reconstructed from components — a re-derived payload is a\n // different payload, and the account validates the original.\n return account.signTypedData(typedData as Parameters<typeof account.signTypedData>[0])\n },\n\n signX402FundingHash(hash: string, expected: X402ExpectedPayment): X402FundingSignatureResult {\n assertExpectedBinding(hash, expected, options.x402BindingSigner, 'hash')\n const signature = signAndVerify(hash)\n const x402Binding = randomUUID()\n x402Bindings.set(x402Binding, { ...expected })\n return { signature, x402Binding }\n },\n\n async signX402FundingTypedData(\n typedData: X402FundingTypedData,\n expected: X402ExpectedPayment,\n ): Promise<X402FundingSignatureResult> {\n assertExpectedBinding(expected.payloadHash, expected, options.x402BindingSigner, 'typed-data')\n // Recompute the digest from the typed data actually in hand and require it\n // to equal Haven's commitment. Everything upstream is untrusted input; this\n // equality is what makes the binding cover the bytes being signed rather\n // than a hash that merely travels alongside them.\n const digest = hashTypedData(typedData as Parameters<typeof hashTypedData>[0])\n if (digest.toLowerCase() !== expected.typedDataHash?.toLowerCase()) {\n throw new HavenSigningError(\n 'x402 typed data does not match the digest Haven committed to in the expected context. ' +\n 'Refusing to sign — the payload was altered in transit or Haven declared a different one. ' +\n 'The most common cause is the typed data being truncated or reshaped while being copied ' +\n 'between tool calls (#1255): re-run the hosted quote and pass its typed_data_b64 string ' +\n 'through UNCHANGED instead of re-emitting the nested JSON.',\n )\n }\n const account = privateKeyToAccount(delegateKey as `0x${string}`)\n // Signed VERBATIM (#829): the exact structure Haven sent, never one\n // reconstructed from components — a re-derived payload is a different\n // payload, and the account validates the original.\n const signature = await account.signTypedData(\n typedData as Parameters<typeof account.signTypedData>[0],\n )\n const x402Binding = randomUUID()\n x402Bindings.set(x402Binding, { ...expected })\n return { signature, x402Binding }\n },\n\n async buildX402PaymentHeader(\n paymentRequired: X402PaymentRequired,\n x402Binding: string,\n ): Promise<X402HeaderResult> {\n const expected = x402Bindings.get(x402Binding)\n if (!expected) {\n throw new HavenSigningError(\n 'x402 funding binding is required before signing a merchant header. Sign the hosted funding hash with x402_expected first.',\n )\n }\n try {\n assertX402PaymentWindowOpen(expected)\n } catch (err) {\n x402Bindings.delete(x402Binding)\n throw err\n }\n const option = selectStandardPaymentOption(paymentRequired.accepts)\n if (!option) {\n throw new HavenApiError(\n 'No compatible payment option found in x402 requirements. ' +\n 'Haven supports standard x402 exact payments on Base USDC.',\n 400,\n )\n }\n assertX402MatchesExpected(paymentRequired, option, expected)\n\n const account = privateKeyToAccount(delegateKey as `0x${string}`)\n const requirements = toStandardPaymentRequirements(paymentRequired, option)\n const header = await exact.evm.createPaymentHeader(\n account,\n paymentRequired.x402Version,\n requirements,\n )\n\n if (paymentRequired.x402Version < 2) {\n x402Bindings.delete(x402Binding)\n return { paymentHeader: header, accepted: option }\n }\n\n // Always delete the binding — even if encode/decode throws — to prevent the\n // in-process Map from accumulating stale X402ExpectedPayment entries (memory\n // leak + data-retention violation for user payment context).\n try {\n const payment = decodeBase64Json<{ payload: unknown }>(header)\n const wrapped = encodeBase64Json({\n x402Version: paymentRequired.x402Version,\n accepted: option,\n payload: payment.payload,\n })\n return { paymentHeader: wrapped, accepted: option }\n } finally {\n x402Bindings.delete(x402Binding)\n }\n },\n\n async signSweepAuthorization({\n authorization,\n expectedAuth,\n expectedSafe,\n }: SweepSignatureInput): Promise<SweepSignatureResult> {\n // 1. The authorization must have come from Haven (binding), so a malicious\n // hosted server can't get the delegate to sign a transfer to an attacker.\n assertSweepBinding(authorization, expectedAuth, options.x402BindingSigner)\n\n // 2. Funds can only leave the delegate's own key, and only to its own Safe.\n if (!sameAddress(authorization.from, delegateAddress)) {\n throw new HavenSigningError(\n 'Sweep authorization `from` does not match this delegate address.',\n )\n }\n if (expectedSafe && !sameAddress(authorization.to, expectedSafe)) {\n throw new HavenSigningError(\n 'Sweep authorization `to` does not match the Safe in the local credential.',\n )\n }\n\n // 3. Build the EIP-712 typed data (asserts token/chain are canonical USDC),\n // sign it locally, and verify the recovered signer is the delegate.\n const typedData = buildSweepTypedData(authorization)\n // The SDK keeps addresses framework-neutral (`string`); viem wants its\n // `0x`-branded template type. Narrow at the call boundary only.\n const viemTypedData = {\n domain: {\n ...typedData.domain,\n verifyingContract: typedData.domain.verifyingContract as `0x${string}`,\n },\n types: typedData.types,\n primaryType: typedData.primaryType,\n message: {\n ...typedData.message,\n from: typedData.message.from as `0x${string}`,\n to: typedData.message.to as `0x${string}`,\n nonce: typedData.message.nonce as `0x${string}`,\n },\n } as const\n const account = privateKeyToAccount(delegateKey as `0x${string}`)\n const signature = await account.signTypedData(viemTypedData)\n const recovered = await recoverTypedDataAddress({ ...viemTypedData, signature })\n if (!sameAddress(recovered, delegateAddress)) {\n throw new HavenSigningError(\n 'Local sweep signature verification failed — recovered address does not match the delegate key.',\n )\n }\n return { signature }\n },\n }\n}\n\n/**\n * Verify Haven signed the sweep authorization context. Mirrors\n * `assertExpectedBinding` for x402: re-derive the canonical message from the\n * authorization fields, require it match the binding, require the binding signer\n * be the trusted Haven address, and verify the signature. Reuses the x402\n * binding signer — the message namespace differs so the two can't cross-replay.\n */\nfunction assertSweepBinding(\n authorization: SweepAuthorization,\n expectedAuth: SweepExpectedAuth,\n trustedSigner: string | undefined,\n): void {\n if (!expectedAuth || typeof expectedAuth !== 'object') {\n throw new HavenSigningError('Sweep authorization binding is required before signing.')\n }\n if (!trustedSigner) {\n throw new HavenSigningError(\n 'Sweep binding verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing sweep authorizations.',\n )\n }\n // Before any content comparison: an unrecognised version means we cannot\n // reason about this binding at all, so a mismatch below would be a symptom\n // reported as a cause (#1143).\n assertSupportedBindingVersion(\n expectedAuth.version,\n SUPPORTED_SWEEP_BINDING_VERSIONS,\n 'sweep authorization binding',\n )\n const message = buildSweepAuthorizationMessage(authorization)\n if (expectedAuth.message !== message) {\n throw new HavenSigningError('Sweep authorization binding does not match the authorization being signed.')\n }\n if (!sameAddress(expectedAuth.signer, trustedSigner)) {\n throw new HavenSigningError('Sweep authorization binding was not signed by the configured Haven signer.')\n }\n if (!verifySignature(hashMessage(message), expectedAuth.signature, trustedSigner)) {\n throw new HavenSigningError('Sweep authorization binding signature could not be verified.')\n }\n}\n\nexport function assertX402MatchesExpected(\n paymentRequired: X402PaymentRequired,\n option: X402PaymentOption,\n expected: X402ExpectedPayment,\n): void {\n assertExpectedShape(expected)\n const headerResource = option.resource ?? paymentRequired.resource.url\n if (headerResource !== expected.resourceUrl) {\n throw new HavenSigningError('x402 payment_required resource does not match the funded intent.')\n }\n if (!sameAddress(option.payTo, expected.merchantTo)) {\n throw new HavenSigningError('x402 merchant recipient does not match the funded intent.')\n }\n if (x402AuthorizationAmount(option) !== expected.amount) {\n throw new HavenSigningError('x402 amount does not match the funded intent.')\n }\n if (!sameAddress(option.asset, expected.asset)) {\n throw new HavenSigningError('x402 asset does not match the funded intent.')\n }\n if (option.network !== expected.network) {\n throw new HavenSigningError('x402 network does not match the funded intent.')\n }\n}\n\nfunction assertExpectedShape(expected: X402ExpectedPayment): void {\n if (!expected || typeof expected !== 'object') {\n throw new HavenSigningError('x402 expected funding context is required before signing a merchant header.')\n }\n}\n\n/**\n * Expected-context binding versions THIS signer understands (#1143).\n *\n * The backend deploys continuously from `dev`; a signer reaches users only on a\n * merge to `main` (the publish workflow). So a signer that is one release behind\n * a context bump is a structural state, not an accident, and it needs to report\n * itself as one. These sets are the signer's authority on what it will sign —\n * the tool schemas deliberately accept any positive integer so an unknown\n * version arrives *here* instead of dying at the schema boundary with a raw\n * validation string.\n *\n * **Adding a version here is not sufficient to support it.** The mode rules in\n * `assertExpectedBinding` derive the expected version from the context's\n * *contents* (`typedDataHash` present ⇒ 2), not from `auth.version`, so a v3\n * that carries anything new needs that derivation extended in the same change.\n * Widening this array alone would admit a v3 context to the v1/v2 rule set:\n * the array announces what this signer can evaluate, it does not define it.\n */\nexport const SUPPORTED_X402_EXPECTED_VERSIONS: readonly number[] = [1, 2]\nexport const SUPPORTED_SWEEP_BINDING_VERSIONS: readonly number[] = [1]\n\n/**\n * Fail closed on a binding version this signer does not understand, with an\n * error that names the received version, the ceiling this signer supports, and\n * the fix — both as PROSE (`message`, unchanged since #1143) and, since #1309,\n * as MACHINE-READABLE fields on the thrown error itself\n * (`HavenUnsupportedSignerVersionError`): `code`, `supportedVersions`,\n * `receivedVersion`, `fallback`. The tool boundary (`normalizeError` in\n * `tools.ts`) relays those fields verbatim instead of leaving an agent to\n * regex-parse this prose, which is the diagnosability gap\n * `docs/operations/mcp-runtime-compatibility.md` documents.\n *\n * `supportedVersions`/`receivedVersion` are DERIVED from this call's own\n * arguments — never a second literal — so they cannot drift from\n * `SUPPORTED_X402_EXPECTED_VERSIONS` / `SUPPORTED_SWEEP_BINDING_VERSIONS`,\n * which is what the signing path always passes in.\n *\n * The version travels inside the Haven-signed binding message, so the message\n * also tells the caller not to \"fix\" it by rewriting the field — an agent that\n * does would invalidate the signature and misrepresent what Haven authorised.\n * That instruction is NOT weakened by structuring the refusal: this function\n * still throws before any content check runs, and nothing is ever signed.\n *\n * Exported so a test can pin the historical case (a v2 context against a signer\n * whose set was `{1}`) that this signer can no longer produce on its own. The\n * signing path always passes the module constants above.\n */\nexport function assertSupportedBindingVersion(\n received: number,\n supported: readonly number[],\n context: 'x402 expected context' | 'sweep authorization binding',\n): void {\n if (supported.includes(received)) return\n const highest = Math.max(...supported)\n // The else-branch (\"updating will not restore it\") assumes versions retire\n // MONOTONICALLY from the oldest end — true for how SUPPORTED_* is maintained\n // (append new, drop old). If a future change ever makes the supported set\n // non-contiguous, a gap version would hit that branch and the wording needs\n // revisiting (#1322 review).\n const outOfDate = received > highest\n const code =\n context === 'x402 expected context'\n ? SignerRefusalCode.UnsupportedExpectedContextVersion\n : SignerRefusalCode.UnsupportedSweepBindingVersion\n const ceiling = outOfDate\n ? `This signer is out of date: it supports ${context} versions up to ${highest}, ` +\n `and Haven sent version ${received}. Update @haven_ai/signer — rerun the Haven ` +\n 'connector (`npx @haven_ai/connect@alpha`), which reinstalls the pinned MCP runtime.'\n : `Unsupported ${context} version ${received}: this signer supports ` +\n `${supported.join(', ')}.`\n // Below-floor is the opposite skew (this signer is NEWER than what sent the\n // context, e.g. a retired version) — updating cannot fix it, so the shared\n // \"update the signer\" fallback would be actively wrong here. Only the\n // out-of-date branch, which is the case seen in the field (#1143), uses the\n // canonical single-source fallback shared with the hosted quote's advisory\n // signer_compatibility.fallback (#1155, #1309).\n const fallback = outOfDate\n ? SIGNER_UPDATE_FALLBACK\n : `This ${context} version (${received}) is older than what this signer enforces ` +\n `(${supported.join(', ')}) — updating @haven_ai/signer will not restore it. Nothing ` +\n 'was signed or spent; stop and tell the user rather than retrying.'\n throw new HavenUnsupportedSignerVersionError(\n `${ceiling} Nothing was signed. Do not rewrite the version field to a supported ` +\n 'value: it is part of the Haven-signed binding message, so changing it invalidates ' +\n 'the signature and would misrepresent what Haven authorised.',\n code,\n supported,\n received,\n fallback,\n )\n}\n\n/**\n * Verify Haven's expected-context binding before signing anything.\n *\n * `mode` is what closes the #1138 downgrade in BOTH directions, and neither\n * half is optional:\n *\n * - `'hash'` (legacy rail, raw ECDSA) refuses a **v2** context. A v2 binding\n * means the account validates typed data; raw-signing its 4337 hash would\n * produce a signature the account rejects on-chain, after the intent is\n * claimed.\n * - `'typed-data'` (delegation rail) refuses a **v1** context. Without the\n * `typedDataHash` commitment, Haven's declaration covers only a hash that is\n * NOT what gets signed — the signer would be endorsing a payload it cannot\n * check, which is the whole property this binding exists to provide.\n *\n * The version is derived from the context inside `buildX402ExpectedMessage`, so\n * a tampered `auth.version` cannot select a different rule than the signed\n * message encodes: the recomputed message simply stops matching.\n */\nfunction assertExpectedBinding(\n payloadHash: string,\n expected: X402ExpectedPayment,\n trustedSigner: string | undefined,\n mode: 'hash' | 'typed-data' = 'hash',\n): void {\n assertExpectedShape(expected)\n if (!trustedSigner) {\n throw new HavenSigningError(\n 'x402 expected-context verifier is not configured. Set HAVEN_X402_BINDING_SIGNER before signing x402 funding hashes.',\n )\n }\n // Skew check first (#1143). Every content check below — the hash comparison,\n // the mode rules, the recomputed message — assumes we understand the context's\n // shape. Under an unknown version they are symptoms, and reporting one as the\n // cause is what sent a live debugging session after the wrong string. A missing\n // `auth` is left to the message check below, which already fails closed on it.\n if (expected.auth) {\n assertSupportedBindingVersion(\n expected.auth.version,\n SUPPORTED_X402_EXPECTED_VERSIONS,\n 'x402 expected context',\n )\n }\n if (expected.payloadHash.toLowerCase() !== payloadHash.toLowerCase()) {\n throw new HavenSigningError('x402 expected context does not match the funding hash being signed.')\n }\n if (mode === 'hash' && expected.typedDataHash) {\n throw new HavenSigningError(\n 'This x402 funding intent commits to EIP-712 typed data, so its bare hash must not be ' +\n 'raw-signed — the account would reject that signature on-chain. Sign sign_data.typed_data instead.',\n )\n }\n if (mode === 'typed-data' && !expected.typedDataHash) {\n throw new HavenSigningError(\n 'Refusing to sign typed data under an expected context that does not commit to it. ' +\n 'Haven must return a v2 x402 expected context (with typedDataHash) for a delegation-rail intent.',\n )\n }\n const message = buildX402ExpectedMessage({\n paymentId: expected.paymentId,\n payloadHash: expected.payloadHash,\n resourceUrl: expected.resourceUrl,\n merchantTo: expected.merchantTo,\n amount: expected.amount,\n asset: expected.asset,\n network: expected.network,\n expiresAt: expected.expiresAt,\n typedDataHash: expected.typedDataHash,\n })\n const expectedVersion = expected.typedDataHash ? 2 : 1\n if (expected.auth?.version !== expectedVersion || expected.auth.message !== message) {\n throw new HavenSigningError('x402 expected context authentication message is invalid.')\n }\n if (!sameAddress(expected.auth.signer, trustedSigner)) {\n throw new HavenSigningError('x402 expected context was not signed by the configured Haven signer.')\n }\n if (!verifySignature(hashMessage(message), expected.auth.signature, trustedSigner)) {\n throw new HavenSigningError('x402 expected context signature could not be verified.')\n }\n}\n\nfunction assertX402PaymentWindowOpen(expected: X402ExpectedPayment): void {\n if (!expected.expiresAt) return\n const expiresAtMs = Date.parse(expected.expiresAt)\n if (Number.isNaN(expiresAtMs)) {\n throw new HavenSigningError('x402 expected context expiresAt is not a valid ISO timestamp.')\n }\n if (expiresAtMs <= Date.now()) {\n throw new HavenError(\n '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.',\n AgentPaymentFailureCode.PaymentWindowExpired,\n 410,\n expected.paymentId,\n )\n }\n}\n\nfunction sameAddress(a: string, b: string): boolean {\n return a.toLowerCase() === b.toLowerCase()\n}\n","import {\n SUPPORTED_SWEEP_BINDING_VERSIONS,\n SUPPORTED_X402_EXPECTED_VERSIONS,\n} from './core.js'\n\n/**\n * Pre-payment skew detection (#1155).\n *\n * #1143 made a stale signer say so — but only at the signing step, after the\n * agent had already quoted and was one call away from funding. This module\n * moves the same information to the `initialize` handshake, so the set of\n * expected-context versions this signer understands is observable *before* a\n * payment is attempted.\n *\n * **The check is necessarily agent-mediated.** The signer and the hosted Haven\n * MCP are two separate servers connected to the same client; neither can\n * introspect the other, and the signer never calls the Haven API. Only the\n * agent sees both handshakes, so what ships here is the *information* plus the\n * prompt to compare it — never a server-side gate. A mismatch is advisory: the\n * enforcement point remains the #1143 signing-time guard, which is unchanged.\n *\n * Everything below is DERIVED from the two constants in `core.ts` that the\n * signing path actually enforces. A second hand-maintained literal is the one\n * way this feature could become a lie, so there isn't one — including inside\n * the human-readable `instructions` string, which renders the same arrays.\n */\n\n/**\n * Vendor-prefixed key under MCP's `capabilities.experimental`.\n *\n * `experimental` rather than the newer `extensions` field deliberately: both are\n * `Record<string, object>` in `@modelcontextprotocol/sdk@1.29`, but a client on\n * an older SDK parses the `initialize` result with a `ServerCapabilities` schema\n * that has no `extensions` key, and Zod's default object behaviour would strip\n * it. `experimental` has been in the schema since the beginning, so it survives\n * an old client — which is precisely the population this feature exists for.\n */\nexport const SIGNER_CAPABILITY_KEY = 'haven/signer-compatibility'\n\nexport interface SignerCompatibility {\n /** Expected-context versions this signer will verify (`SUPPORTED_X402_EXPECTED_VERSIONS`). */\n x402_expected_context_versions: number[]\n /** Sweep-binding versions this signer will verify (`SUPPORTED_SWEEP_BINDING_VERSIONS`). */\n sweep_binding_versions: number[]\n}\n\n/** The supported sets this signer enforces, as a plain serialisable object. */\nexport function signerCompatibility(): SignerCompatibility {\n return {\n x402_expected_context_versions: [...SUPPORTED_X402_EXPECTED_VERSIONS],\n sweep_binding_versions: [...SUPPORTED_SWEEP_BINDING_VERSIONS],\n }\n}\n\n/**\n * The machine-readable half: `capabilities.experimental['haven/signer-compatibility']`,\n * returned verbatim in the `initialize` result.\n *\n * `ServerCapabilities.experimental` is typed `z.record(z.string(), <any object>)`\n * and the SDK's `mergeCapabilities` deep-merges per top-level key, so declaring\n * this at construction survives the `tools` capability `McpServer` registers\n * when the first tool is added.\n */\nexport function signerCapabilityAdvertisement(): {\n experimental: Record<string, SignerCompatibility>\n} {\n return { experimental: { [SIGNER_CAPABILITY_KEY]: signerCompatibility() } }\n}\n\n/**\n * The agent-readable half: MCP `instructions`, which clients surface to the\n * model. The machine-readable capability above is the precise statement, but\n * most agent runtimes never expose `capabilities.experimental` to the model —\n * this string is what actually reaches the reader who has to make the call.\n *\n * It names the same fix as #1143 so an agent that hits either surface — the\n * handshake here or the signing-time error there — tells the user the same\n * thing.\n */\nexport function signerInstructions(): string {\n const compatibility = signerCompatibility()\n return [\n 'Haven edge signer: sign-only tools bound to the local delegate key. It never emits the',\n 'key. Its one network capability is an authenticated READ of a signing context from',\n 'Haven by payment_id — pass payment_id to haven_sign / haven_sign_x402 (preferred for',\n 'delegation-rail x402) instead of relaying bulky typed-data payloads yourself.',\n '',\n 'Version compatibility (check this BEFORE signing, not after):',\n `- x402 expected-context versions supported: ${compatibility.x402_expected_context_versions.join(', ')}`,\n `- sweep authorization binding versions supported: ${compatibility.sweep_binding_versions.join(', ')}`,\n '',\n 'Haven quote and prepare results report the expected-context version they will emit',\n '(signer_compatibility.x402_expected_context_version). If that version is not in the list',\n 'above, this signer is out of date: STOP before signing, and tell the user to update',\n '@haven_ai/signer by rerunning `npx @haven_ai/connect@alpha`, which reinstalls the pinned',\n 'MCP runtime. Do not edit the version field to a supported value — it is part of the',\n 'Haven-signed binding message, so changing it invalidates the signature.',\n '',\n 'A version-mismatch refusal from haven_sign / haven_sign_x402 / haven_sign_sweep_delegate is',\n 'machine-readable, not just prose: it carries code, supported_versions, received_version, and',\n 'fallback fields alongside the message, so you can branch on it directly.',\n ].join('\\n')\n}\n","import { readFile, stat } from 'node:fs/promises'\n\n/**\n * The edge signer only needs the delegate key — it signs, it does not call the\n * Haven API. Identity (the `api_key`) lives with the hosted MCP connection, not\n * here. So unlike `@haven_ai/mcp`, this loader requires *only* `delegate_key`.\n */\nexport interface SignerCredentials {\n delegateKey: string\n agentId?: string\n safeAddress?: string\n chainId?: number\n network?: string\n x402BindingSigner?: string\n /** Absolute path the key was loaded from, if a file was used. */\n sourcePath?: string\n}\n\ninterface RawCredentialFile {\n delegate_key?: unknown\n delegateKey?: unknown\n agent_id?: unknown\n agentId?: unknown\n safe_address?: unknown\n safeAddress?: unknown\n chain_id?: unknown\n chainId?: unknown\n network?: unknown\n x402_binding_signer?: unknown\n x402BindingSigner?: unknown\n}\n\n/**\n * Resolve the delegate key for the edge signer.\n *\n * Order — earlier wins:\n * 1. Explicit `path` (e.g. `--credentials <path>`).\n * 2. `HAVEN_CREDENTIALS` env var pointing at a credential JSON file.\n * 3. `HAVEN_DELEGATE_KEY` env var.\n *\n * The same credential JSON the dashboard emits works here — we just read its\n * `delegate_key` and ignore the rest.\n */\nexport async function loadSignerCredentials(\n path: string | undefined = process.env.HAVEN_CREDENTIALS,\n): Promise<SignerCredentials> {\n if (path) return loadFromFile(path)\n\n const envKey = stringField(process.env.HAVEN_DELEGATE_KEY)\n if (envKey) {\n return {\n delegateKey: envKey,\n agentId: stringField(process.env.HAVEN_AGENT_ID),\n safeAddress: stringField(process.env.HAVEN_SAFE_ADDRESS),\n chainId: chainIdField(process.env.HAVEN_CHAIN_ID, 'HAVEN_CHAIN_ID'),\n network: stringField(process.env.HAVEN_NETWORK),\n x402BindingSigner: stringField(process.env.HAVEN_X402_BINDING_SIGNER),\n }\n }\n\n throw new Error(\n 'No delegate key found. Set HAVEN_DELEGATE_KEY, pass --credentials <path>, ' +\n 'or set HAVEN_CREDENTIALS to a Haven agent credential JSON file.',\n )\n}\n\nasync function loadFromFile(path: string): Promise<SignerCredentials> {\n let rawText: string\n try {\n rawText = await readFile(path, 'utf8')\n } catch (err) {\n throw new Error(\n `Could not read Haven credentials at ${path}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n await warnIfCredentialFilePermissive(path)\n\n let raw: RawCredentialFile\n try {\n raw = JSON.parse(rawText) as RawCredentialFile\n } catch {\n throw new Error('Haven credentials must be JSON with a delegate_key field.')\n }\n\n const delegateKey = stringField(raw.delegate_key ?? raw.delegateKey)\n if (!delegateKey) {\n throw new Error('Haven credentials are missing delegate_key — the edge signer needs it to sign.')\n }\n\n return {\n delegateKey,\n agentId: stringField(raw.agent_id ?? raw.agentId),\n safeAddress: stringField(raw.safe_address ?? raw.safeAddress),\n chainId: chainIdField(raw.chain_id ?? raw.chainId, 'chain_id'),\n network: stringField(raw.network),\n x402BindingSigner: stringField(\n raw.x402_binding_signer ??\n raw.x402BindingSigner ??\n process.env.HAVEN_X402_BINDING_SIGNER,\n ),\n sourcePath: path,\n }\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\nfunction chainIdField(value: unknown, label: string): number | undefined {\n if (value === undefined || value === null) return undefined\n\n if (typeof value === 'number') {\n if (Number.isSafeInteger(value) && value > 0) return value\n throw invalidChainIdError(label)\n }\n\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (/^[1-9]\\d*$/.test(trimmed)) {\n const parsed = Number(trimmed)\n if (Number.isSafeInteger(parsed)) return parsed\n }\n throw invalidChainIdError(label)\n }\n\n throw invalidChainIdError(label)\n}\n\nfunction invalidChainIdError(label: string): Error {\n return new Error(`Haven signer credentials ${label} must be a positive integer.`)\n}\n\n/**\n * Warn (best-effort, POSIX only) when the credential file is readable beyond\n * its owner. Mirrors `@haven_ai/mcp`'s check — the delegate key is the most\n * sensitive thing on the machine.\n *\n * Exported for testing.\n */\nexport async function warnIfCredentialFilePermissive(\n path: string,\n log: (message: string) => void = (message) => process.stderr.write(`${message}\\n`),\n platform: NodeJS.Platform = process.platform,\n): Promise<void> {\n if (platform === 'win32') return\n let mode: number\n try {\n mode = (await stat(path)).mode\n } catch {\n return\n }\n if ((mode & 0o077) !== 0) {\n const octal = (mode & 0o777).toString(8).padStart(4, '0')\n log(\n `haven-signer: warning: credential file at ${path} is readable beyond the owner ` +\n `(mode ${octal}). Run: chmod 600 ${path}`,\n )\n }\n}\n","import { createHash } from 'node:crypto'\nimport { appendFile, mkdir } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { dirname, resolve } from 'node:path'\nimport type { SignerToolName } from './tools.js'\n\nexport interface SigningAuditEntry {\n version: 1\n timestamp: string\n tool: SignerToolName\n payload_hash: string\n delegate_address: string\n safe_address?: string\n chain_id?: number\n}\n\nexport interface SigningAuditContext {\n delegateAddress: string\n safeAddress?: string\n chainId?: number\n auditPath?: string\n}\n\nexport function defaultSigningAuditPath(credentialsPath?: string): string {\n if (credentialsPath) return resolve(`${credentialsPath}.signer-audit.jsonl`)\n return resolve(homedir(), '.haven', 'signer-audit.jsonl')\n}\n\nexport async function appendSigningAuditEntry(\n entry: SigningAuditEntry,\n path: string,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await appendFile(path, `${JSON.stringify(entry)}\\n`, 'utf8')\n}\n\nexport function createSigningAuditEntry(\n tool: SignerToolName,\n payloadHash: string,\n context: SigningAuditContext,\n now: Date = new Date(),\n): SigningAuditEntry {\n const entry: SigningAuditEntry = {\n version: 1,\n timestamp: now.toISOString(),\n tool,\n payload_hash: payloadHash,\n delegate_address: context.delegateAddress,\n }\n if (context.safeAddress) entry.safe_address = context.safeAddress\n if (typeof context.chainId === 'number') entry.chain_id = context.chainId\n return entry\n}\n\nexport function hashPayloadForAudit(payload: unknown): string {\n return `0x${createHash('sha256').update(stableStringify(payload)).digest('hex')}`\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n const primitive = JSON.stringify(value)\n return primitive === undefined ? 'undefined' : primitive\n }\n if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(',')}]`\n const object = value as Record<string, unknown>\n return `{${Object.keys(object)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`)\n .join(',')}}`\n}\n","/**\n * Byte-free signing handoff (#1263): fetch a delegation-rail x402 intent's\n * EXACT signing payload from Haven by `payment_id`, instead of asking a\n * language model to re-emit multi-KB EIP-712 bytes between tool calls (the\n * #1255 failure mode — runtimes that elide long tool results structurally\n * cannot copy them).\n *\n * Layering: this module lives in the local MCP SERVER layer, not the signer\n * core. The core (`core.ts`) remains pure and network-free; what it signs\n * still goes through the SAME digest re-derivation and Haven-binding\n * verification (#1138) whether the bytes arrived by tool argument or by this\n * fetch. The fetch is a strictly better byte source than model relay — TLS to\n * Haven versus a model's context window — and it uses the agent credential\n * (`identity.json`) the connector already stores next to the signer\n * credential. The delegate key is never sent anywhere.\n */\nimport { readFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { HavenSigningError } from '@haven_ai/sdk'\n\nexport interface HavenIdentity {\n apiUrl: string\n apiKey: string\n}\n\n/**\n * Resolve the agent identity from `identity.json` in the same directory as\n * the signer credential file. Returns null (never throws) when unavailable —\n * the caller decides how to phrase the fallback.\n */\nexport async function loadHavenIdentity(\n credentialsPath: string | undefined,\n): Promise<HavenIdentity | null> {\n if (!credentialsPath) return null\n try {\n const raw = JSON.parse(\n await readFile(join(dirname(credentialsPath), 'identity.json'), 'utf8'),\n ) as Record<string, unknown>\n const apiKey = typeof raw.api_key === 'string' ? raw.api_key : undefined\n const apiUrl = typeof raw.api_url === 'string' ? raw.api_url : undefined\n if (!apiKey || !apiUrl) return null\n return { apiKey, apiUrl: apiUrl.replace(/\\/+$/, '') }\n } catch {\n return null\n }\n}\n\nexport interface FetchedSignContext {\n paymentId: string\n payloadHash: string\n typedData: Record<string, unknown>\n /** The COMPLETE snake_case expected context, verbatim from Haven. */\n x402Expected: Record<string, unknown>\n /**\n * #1355: the 402 PaymentRequired persisted at authorize time, when the\n * backend carries it — lets haven_sign_x402 build the merchant header from\n * `{ payment_id }` alone. Null on pre-#1355 backends/rows; the caller then\n * requires the agent-supplied copy. Untrusted like every other fetched\n * field: header building verifies it against the Haven-signed expected\n * context either way.\n */\n paymentRequired: Record<string, unknown> | null\n}\n\n/**\n * GET /x402/:id/sign-context. Read-only; refusals from the backend\n * (expired/executed/legacy/unknown) surface as clear signing errors that name\n * the next step. The returned payload is UNTRUSTED input exactly like a tool\n * argument would be — the signing path's binding verification and digest\n * equality are what make it safe to use, not its provenance.\n */\nexport async function fetchX402SignContext(\n identity: HavenIdentity,\n paymentId: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<FetchedSignContext> {\n let response: Response\n try {\n response = await fetchImpl(\n `${identity.apiUrl}/x402/${encodeURIComponent(paymentId)}/sign-context`,\n { headers: { Authorization: `Bearer ${identity.apiKey}` } },\n )\n } catch (err) {\n throw new HavenSigningError(\n `Could not reach Haven to fetch the signing context for ${paymentId}: ` +\n `${err instanceof Error ? err.message : String(err)}. ` +\n 'Retry, or pass typed_data_b64 from the quote result instead.',\n )\n }\n const body = (await response.json().catch(() => ({}))) as Record<string, unknown>\n if (!response.ok) {\n const detail =\n typeof body.error === 'string' ? body.error : `HTTP ${response.status}`\n throw new HavenSigningError(\n `Haven refused the signing-context fetch for ${paymentId}: ${detail}` +\n (response.status === 404\n ? ' — check the payment_id came from this agent’s own quote.'\n : response.status === 410\n ? ' Re-run the quote with the same idempotency key, then sign the fresh payment_id.'\n : ''),\n )\n }\n const signData = body.sign_data as Record<string, unknown> | undefined\n const x402Expected = body.x402_expected as Record<string, unknown> | undefined\n if (\n !signData ||\n typeof signData.hash !== 'string' ||\n !signData.typed_data ||\n typeof signData.typed_data !== 'object' ||\n !x402Expected\n ) {\n throw new HavenSigningError(\n 'The Haven sign-context response is missing sign_data.typed_data or x402_expected — ' +\n 'the backend may predate #1263. Pass typed_data_b64 from the quote result instead.',\n )\n }\n const paymentRequired = body.payment_required\n return {\n paymentId: String(body.payment_id ?? paymentId),\n payloadHash: signData.hash,\n typedData: signData.typed_data as Record<string, unknown>,\n x402Expected,\n paymentRequired:\n paymentRequired && typeof paymentRequired === 'object' && !Array.isArray(paymentRequired)\n ? (paymentRequired as Record<string, unknown>)\n : null,\n }\n}\n","import {\n AgentPaymentFailureCode,\n AgentPaymentNextAction,\n HavenApiError,\n HavenError,\n HavenSigningError,\n HavenUnsupportedSignerVersionError,\n type X402PaymentRequired,\n} from '@haven_ai/sdk'\nimport { z } from 'zod/v3'\nimport {\n appendSigningAuditEntry,\n createSigningAuditEntry,\n hashPayloadForAudit,\n type SigningAuditContext,\n} from './audit.js'\nimport type {\n EdgeSigner,\n X402ExpectedPayment,\n X402FundingSignatureResult,\n X402FundingTypedData,\n} from './core.js'\nimport {\n fetchX402SignContext,\n type HavenIdentity,\n type FetchedSignContext,\n} from './sign-context.js'\n\n/**\n * Local signer tool set. These run on the agent's machine, next to the key,\n * and pair with the hosted server's construct/relay tools (#183). They sign;\n * they never call the Haven API and never emit the key.\n */\nexport type SignerToolName =\n | 'haven_sign'\n | 'haven_x402_sign_header'\n | 'haven_sign_x402'\n | 'haven_sign_sweep_delegate'\n\nconst sweepAuthorizationSchema = z.object({\n from: z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'from must be a 0x address'),\n to: z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'to must be a 0x address'),\n value: z.string().regex(/^[0-9]+$/, 'value must be a decimal atomic amount'),\n validAfter: z.string().regex(/^[0-9]+$/, 'validAfter must be a decimal unix time'),\n validBefore: z.string().regex(/^[0-9]+$/, 'validBefore must be a decimal unix time'),\n nonce: z.string().regex(/^0x[0-9a-fA-F]{64}$/, 'nonce must be a 0x-prefixed 32-byte hex string'),\n token: z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'token must be a 0x address'),\n chainId: z.number().int().positive(),\n})\n\n/**\n * Binding version at the tool boundary (#1143).\n *\n * Open on purpose. A literal (or literal union) here is validated by the MCP\n * server *before* any handler runs, so a signer one release behind the backend\n * rejected the payment with `Invalid literal value, expected 1 at\n * x402_expected.auth.version` — a message that names neither the cause (your\n * signer is stale) nor the fix (update it), and which no Haven code wrote.\n * Accept any positive integer here and let the signer decide semantically:\n * `SUPPORTED_X402_EXPECTED_VERSIONS` / `SUPPORTED_SWEEP_BINDING_VERSIONS` in\n * `core.ts` still fail closed on anything they do not know, so this widens the\n * *error path*, never what can be signed.\n */\nconst bindingVersionSchema = z.number().int().positive()\n\nconst sweepExpectedAuthSchema = z.object({\n version: bindingVersionSchema,\n message: z.string().min(1),\n signature: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'signature must be a 0x-prefixed hex string'),\n signer: z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'signer must be a 0x address'),\n})\n\nconst x402ExpectedShape = {\n payment_id: z.string().min(1),\n payload_hash: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'payload_hash must be a 0x-prefixed hex string'),\n resource_url: z.string().url(),\n merchant_to: z.string().min(1),\n amount: z.string().min(1),\n asset: z.string().min(1),\n network: z.string().min(1),\n // Required: expires_at is folded into the Haven-signed binding message, so the\n // signer must receive the exact same value to reconstruct a matching message.\n // Omitting it used to fail downstream with a cryptic \"authentication message is\n // invalid\" — making it required surfaces a clear INVALID_INPUT at the boundary.\n expires_at: z.string().min(1),\n // #1138: present on a delegation-rail (v2) context. It commits to the EIP-712\n // typed data the account validates; the signer refuses to raw-sign the bare\n // hash when it is present, and refuses to sign typed data when it is absent.\n typed_data_hash: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'typed_data_hash must be a 0x-prefixed hex string')\n .optional(),\n auth: z.object({\n // Open at the boundary, enforced in the signer — see bindingVersionSchema.\n version: bindingVersionSchema,\n message: z.string().min(1),\n signature: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'signature must be a 0x-prefixed hex string'),\n signer: z.string().min(1),\n }),\n}\n\nconst x402ExpectedSchema = z.object(x402ExpectedShape)\n\nexport const toolSchemas: Record<SignerToolName, z.ZodRawShape> = {\n haven_sign_sweep_delegate: {\n // The authorization fields prepared by Haven's POST /sweep/prepare. Passed\n // through verbatim from the hosted haven_sweep_delegate tool — the signer\n // re-derives the binding message from these exact values.\n authorization: sweepAuthorizationSchema,\n // Haven's signature over the authorization context (the binding).\n expected_auth: sweepExpectedAuthSchema,\n },\n haven_sign: {\n // #1263: THE preferred x402 input — the signer fetches the exact signing\n // payload + expected context from Haven itself (authenticated with the\n // locally-stored agent credential), so no bulky bytes ever cross the\n // model. Pass payment_id ALONE for a delegation-rail x402 funding intent.\n payment_id: z.string().min(1).optional(),\n // The unsigned hash from haven_pay / haven_pay_x402_quote (payload_hash).\n // Optional when payment_id is supplied (the fetch carries it).\n payload_hash: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'payload_hash must be a 0x-prefixed hex string')\n .optional(),\n // Pass x402.expected from hosted haven_pay_x402_quote when this hash funds\n // a standard x402 merchant retry. The signer records it locally and returns\n // an opaque x402_binding for the later header-signing step.\n x402_expected: x402ExpectedSchema.optional(),\n // #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed\n // (not z.unknown()) so MCP clients embed it as JSON rather than a string.\n typed_data: z.record(z.string(), z.unknown()).optional(),\n // #1255: the same payload as ONE opaque base64 string, exactly as returned\n // by the hosted tools. Preferred over typed_data when both are present —\n // an agent re-emitting multi-KB nested JSON between tool calls is the\n // failure mode this field removes (a truncated/reshaped payload fails the\n // digest check and the payment refuses, correctly but pointlessly).\n // Bounded: a realistic redemption payload is ~10KB encoded; 256KB is\n // generous headroom while keeping the offline signer from materializing\n // arbitrarily large caller input.\n typed_data_b64: z.string().min(1).max(262144).optional(),\n },\n haven_x402_sign_header: {\n // The parsed HTTP 402 PaymentRequired from the merchant. Typed as an object\n // (not z.unknown(), which becomes empty JSON Schema `{}`) so MCP clients\n // embed it as JSON rather than serialising the object to a string.\n payment_required: z.record(z.string(), z.unknown()),\n // Opaque binding returned by haven_sign when x402_expected was supplied.\n x402_binding: z.string().min(1),\n },\n haven_sign_x402: {\n // #1263: preferred — pass payment_id (plus payment_required) and the\n // signer fetches the exact signing payload + expected context itself.\n payment_id: z.string().min(1).optional(),\n // One-shot x402 signing: funding hash + merchant header in one local call.\n // Both optional when payment_id is supplied (the fetch carries them).\n payload_hash: z\n .string()\n .regex(/^0x[0-9a-fA-F]+$/, 'payload_hash must be a 0x-prefixed hex string')\n .optional(),\n x402_expected: x402ExpectedSchema.optional(),\n // #1355: optional when payment_id is supplied — the signer's context fetch\n // carries the stored 402 PaymentRequired, so `{ payment_id }` alone is the\n // preferred call. Still required (via the runtime check in the handler)\n // for the quote-based fallback path without a payment_id.\n payment_required: z.record(z.string(), z.unknown()).optional(),\n // #1138: delegation-rail intents sign THIS, not payload_hash. Object-typed\n // (not z.unknown()) so MCP clients embed it as JSON rather than a string.\n typed_data: z.record(z.string(), z.unknown()).optional(),\n // #1255: see haven_sign.typed_data_b64 — the copy-through-safe form.\n typed_data_b64: z.string().min(1).max(262144).optional(),\n },\n}\n\nconst SIGN_DESCRIPTION = [\n 'Sign an unsigned Haven payment hash with the local delegate key. The delegate key never leaves',\n 'this process. Pass the payload_hash returned by haven_pay or haven_pay_x402_quote.',\n 'For x402, also pass x402_expected from haven_pay_x402_quote; the signer records it locally',\n 'and returns { signature, x402_binding }. x402_expected includes expires_at; sign before that',\n 'window closes. DELEGATION-RAIL x402 accounts (#1263): pass payment_id ALONE (preferred) — this',\n 'signer fetches the exact signing payload and expected context from Haven itself, so nothing',\n 'bulky ever crosses your context. Fallback: pass typed_data_b64 through UNCHANGED (never re-type',\n 'the nested typed_data JSON); the account validates that EIP-712 payload, not payload_hash.',\n 'Next: call mcp__haven__haven_submit with signature, then pass x402_binding',\n 'to mcp__haven-signer__haven_x402_sign_header. For plain SafeTransfer payments, just pass payload_hash and',\n 'relay the returned signature via mcp__haven__haven_submit.',\n].join(' ')\n\nconst X402_SIGN_HEADER_DESCRIPTION = [\n 'Build and sign the EIP-3009 X-PAYMENT header for the merchant leg of an x402 payment.',\n 'The delegate key stays local — only the signed header crosses any boundary.',\n 'Pass the payment_required from the original merchant 402 response and the x402_binding',\n 'returned by haven_sign. The signer validates the merchant, amount, resource, asset, and',\n 'network against the recorded funding context before signing, checks expires_at when present,',\n 'and rejects mismatches or expired payment windows.',\n 'Returns { payment_header, accepted }. Set X-PAYMENT: <payment_header> on your retry to the',\n 'merchant. Only call after haven_submit has confirmed the funding step (nextAction=none or',\n 'the funding tx has a confirmed status). Next for paid MCP tools: call mcp__haven__haven_complete_mcp_tool.',\n].join(' ')\n\nconst SIGN_X402_DESCRIPTION = [\n 'One-shot x402 signing for the fast 3-call flow: sign the funding hash AND build the EIP-3009',\n 'X-PAYMENT header in a single local call (equivalent to haven_sign followed by',\n 'haven_x402_sign_header). The delegate key never leaves this process. From the haven_pay_mcp_tool',\n 'result pass JUST payment_id — PREFERRED (#1263, #1355): this signer fetches the exact signing',\n 'payload, expected context, and merchant payment_required from Haven itself, so nothing bulky',\n 'crosses your context. If the signer reports the context carried no payment_required (older',\n 'backend), re-call with payment_id plus payment_required verbatim from the pay result.',\n 'Fallback for older backends: pass payload_hash, x402_expected (the nested x402.expected object —',\n 'passing the whole x402 object is also accepted and unwrapped for you), and typed_data_b64',\n 'through UNCHANGED; the signer',\n 'signs the typed data instead of payload_hash and refuses the bare hash when the context commits to typed data.',\n 'Returns',\n '{ signature, x402_binding, payment_header, accepted }; hand signature + payment_header to',\n 'mcp__haven__haven_settle_mcp_tool to fund and settle in one hosted call. The header is built now (before',\n 'funding confirms), so its short validity window starts here — call mcp__haven__haven_settle_mcp_tool promptly,',\n 'and re-run mcp__haven__haven_pay_mcp_tool with the same idempotency_key if a tool returns PAYMENT_WINDOW_EXPIRED.',\n 'Next: call mcp__haven__haven_settle_mcp_tool.',\n].join(' ')\n\nconst SIGN_SWEEP_DELEGATE_DESCRIPTION = [\n 'Sign a Haven-prepared gasless USDC sweep that recovers stranded funds from the delegate',\n 'wallet back to your Haven wallet. The delegate key never leaves this process and this tool',\n 'never broadcasts — it returns only an EIP-3009 signature that Haven\\'s relayer submits and',\n 'pays gas for. Pass the authorization and expected_auth returned by the hosted',\n 'haven_sweep_delegate tool. The signer verifies Haven authored the authorization and that it',\n 'pays out to your own Safe before signing, then returns { signature } to hand back to',\n 'mcp__haven__haven_sweep_delegate to complete recovery.',\n].join(' ')\n\nexport const toolDescriptions: Record<SignerToolName, string> = {\n haven_sign: SIGN_DESCRIPTION,\n haven_x402_sign_header: X402_SIGN_HEADER_DESCRIPTION,\n haven_sign_x402: SIGN_X402_DESCRIPTION,\n haven_sign_sweep_delegate: SIGN_SWEEP_DELEGATE_DESCRIPTION,\n}\n\n/** Map the wire-shaped x402_expected (snake_case) to the EdgeSigner's camelCase context. */\n/**\n * Sign the x402 funding leg on whichever rail the Haven-signed context declares\n * (#1138).\n *\n * The **context** selects the path, never the caller's arguments: a v2 context\n * (one that commits to a typed-data digest) requires typed data, a v1 context\n * requires the bare hash, and `assertExpectedBinding` rejects the mismatch. So\n * an agent that passes `typed_data` on a legacy-rail intent — or omits it on a\n * delegation-rail one — gets a clear refusal here rather than a signature the\n * chain rejects later.\n */\nasync function signFundingLeg(\n signer: EdgeSigner,\n expected: X402ExpectedPayment,\n payloadHash: string,\n typedData: Record<string, unknown> | undefined,\n): Promise<X402FundingSignatureResult> {\n if (!expected.typedDataHash) {\n return signer.signX402FundingHash(payloadHash, expected)\n }\n if (!typedData) {\n throw new HavenSigningError(\n 'This x402 funding intent is on the delegation rail: it commits to EIP-712 typed data, ' +\n 'which was not supplied. Pass typed_data_b64 from haven_pay_mcp_tool / ' +\n 'haven_pay_x402_quote through unchanged (or typed_data verbatim) — the bare ' +\n 'payload_hash is not what the account validates.',\n )\n }\n return signer.signX402FundingTypedData(typedData as unknown as X402FundingTypedData, expected)\n}\n\nfunction toExpectedX402(raw: {\n payment_id: string\n payload_hash: string\n resource_url: string\n merchant_to: string\n amount: string\n asset: string\n network: string\n // Required at the tool boundary (see x402ExpectedSchema): it's folded into the\n // Haven-signed binding message. The EdgeSigner's internal type keeps it\n // optional because it skips the window check when absent.\n expires_at: string\n typed_data_hash?: string\n auth: X402ExpectedPayment['auth']\n}): X402ExpectedPayment {\n return {\n paymentId: raw.payment_id,\n payloadHash: raw.payload_hash,\n typedDataHash: raw.typed_data_hash,\n resourceUrl: raw.resource_url,\n merchantTo: raw.merchant_to,\n amount: raw.amount,\n asset: raw.asset,\n network: raw.network,\n expiresAt: raw.expires_at,\n auth: raw.auth,\n }\n}\n\n/**\n * Validate a FETCHED expected context (#1263) against the same boundary schema\n * a tool argument passes through — provenance does not skip validation. A\n * malformed response names the fallback instead of leaking a Zod stack.\n */\nfunction parseFetchedExpected(\n fetched: FetchedSignContext,\n): Parameters<typeof toExpectedX402>[0] {\n const parsed = z.object(x402ExpectedShape).safeParse(fetched.x402Expected)\n if (!parsed.success) {\n throw new HavenSigningError(\n 'The Haven sign-context response carried a malformed x402_expected — the backend may ' +\n 'predate #1263. Pass payload_hash + x402_expected from the quote result instead. ' +\n `Underlying: ${parsed.error.issues[0]?.message ?? 'schema mismatch'}`,\n )\n }\n return parsed.data as Parameters<typeof toExpectedX402>[0]\n}\n\nexport interface ToolSuccess<T> {\n success: true\n data: T\n}\n\nexport interface ToolFailure {\n success: false\n code: string\n message: string\n statusCode?: number\n paymentId?: string\n next_action?: string\n retry_with_new_quote?: boolean\n suggested_tool?: string\n /**\n * #1309: present on `UNSUPPORTED_EXPECTED_CONTEXT_VERSION` /\n * `UNSUPPORTED_SWEEP_BINDING_VERSION` refusals — the exact version set this\n * signer install enforces, derived from `SUPPORTED_X402_EXPECTED_VERSIONS` /\n * `SUPPORTED_SWEEP_BINDING_VERSIONS` at the throw site.\n */\n supported_versions?: number[]\n /** #1309: the version Haven sent that triggered the refusal above. */\n received_version?: number\n /**\n * #1309: precise recovery guidance as DATA, not just prose inside `message`\n * — the same text the hosted quote's advisory `signer_compatibility.fallback`\n * carries when the refusal is an out-of-date signer.\n */\n fallback?: string\n}\n\nexport type ToolPayload<T = unknown> = ToolSuccess<T> | ToolFailure\n\nexport interface ToolHandlerOptions {\n audit?: SigningAuditContext & { auditPath: string }\n /**\n * #1263: how the payment_id signing path reaches Haven. Lives at the MCP\n * server layer (the core stays network-free); absent → payment_id calls\n * refuse with a message naming the typed_data_b64 fallback.\n */\n signContext?: {\n loadIdentity: () => Promise<HavenIdentity | null>\n fetchImpl?: typeof fetch\n }\n}\n\n/**\n * Resolve the delegation-rail signing payload from the tool arguments (#1255).\n *\n * `typed_data_b64` wins over `typed_data`: it is the copy-through-safe form —\n * one opaque string the agent relays unchanged, instead of re-emitting multi-KB\n * nested JSON (a redemption UserOp's callData) between two tool calls. The live\n * #1255 failure was exactly that: the payload arrived altered, the digest check\n * refused (correctly), and the purchase died with no defect anywhere in the\n * chain. The decoded object goes through the SAME digest verification as a\n * plain typed_data — this changes the transport, never the trust model.\n */\nfunction resolveTypedData(args: {\n typed_data?: Record<string, unknown>\n typed_data_b64?: string\n}): Record<string, unknown> | undefined {\n if (!args.typed_data_b64) return args.typed_data\n try {\n const decoded = JSON.parse(\n Buffer.from(args.typed_data_b64, 'base64').toString('utf8'),\n ) as unknown\n if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) {\n throw new Error('decoded value is not an object')\n }\n return decoded as Record<string, unknown>\n } catch (err) {\n throw new HavenSigningError(\n 'typed_data_b64 did not decode to a JSON object. Pass the exact string returned by the ' +\n 'hosted Haven tool, unchanged — do not re-encode, trim, or reformat it. ' +\n `Underlying error: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n}\n\nexport function createToolHandlers(\n signer: EdgeSigner,\n options: ToolHandlerOptions = {},\n): Record<SignerToolName, (input: unknown) => Promise<ToolPayload>> {\n /**\n * #1263: resolve the signing inputs for a payment_id call by fetching the\n * exact bytes from Haven. Returns null when the caller did not use the\n * payment_id path. The fetched payload is untrusted input like any tool\n * argument — it still goes through the binding verification and digest\n * re-derivation downstream; this only changes HOW the bytes arrive.\n */\n async function resolveSignContext(args: {\n payment_id?: string\n payload_hash?: string\n }): Promise<FetchedSignContext | null> {\n if (!args.payment_id) return null\n const identity = (await options.signContext?.loadIdentity()) ?? null\n if (!identity) {\n throw new HavenSigningError(\n 'payment_id signing needs the agent identity (identity.json next to the signer ' +\n 'credentials), which this signer could not load. Re-run `npx @haven_ai/connect@alpha` ' +\n 'to restore it, or pass typed_data_b64 from the quote result instead.',\n )\n }\n const ctx = await fetchX402SignContext(\n identity,\n args.payment_id,\n options.signContext?.fetchImpl,\n )\n if (\n args.payload_hash &&\n args.payload_hash.toLowerCase() !== ctx.payloadHash.toLowerCase()\n ) {\n throw new HavenSigningError(\n 'The supplied payload_hash does not match the signing context Haven serves for ' +\n `payment ${args.payment_id}. Pass payment_id alone, or check which quote the ` +\n 'hash came from.',\n )\n }\n return ctx\n }\n\n return {\n haven_sign: async (input) =>\n runTool(async () => {\n const args = parse('haven_sign', coerceX402Expected(input))\n const fetched = await resolveSignContext(args)\n const typedData = fetched?.typedData ?? resolveTypedData(args)\n const payloadHash = fetched?.payloadHash ?? args.payload_hash\n if (!payloadHash) {\n throw new HavenSigningError(\n 'Pass payment_id (preferred for delegation-rail x402) or payload_hash.',\n )\n }\n const expectedRaw = fetched\n ? parseFetchedExpected(fetched)\n : args.x402_expected\n const x402Expected = expectedRaw ? toExpectedX402(expectedRaw) : null\n const result = x402Expected\n ? await signFundingLeg(signer, x402Expected, payloadHash, typedData)\n : null\n if (!result) {\n // #1254: a DIRECT delegation-rail payment carries typed_data and no\n // x402 context — the account validates the TYPED DATA, and a raw\n // signature over payload_hash is rejected on-chain (AA24, found\n // live). When typed_data is present it is what gets signed; the\n // raw-hash path below is the legacy AllowanceModule rail only.\n if (typedData) {\n const signature = await signer.signDelegationTypedData(typedData)\n await auditSigning('haven_sign', payloadHash)\n return { signature }\n }\n const signature = signer.signPaymentHash(payloadHash)\n await auditSigning('haven_sign', payloadHash)\n return { signature }\n }\n await auditSigning('haven_sign', payloadHash)\n return { signature: result.signature, x402_binding: result.x402Binding }\n }),\n\n haven_x402_sign_header: async (input) =>\n runTool(async () => {\n // Defensive: the object-typed schema makes conformant MCP clients embed\n // payment_required as JSON, but some transports still serialise it to a\n // string. Coerce it back to an object BEFORE Zod validation so the\n // tightened schema doesn't reject it (else `.accepts` would be undefined\n // → \"No compatible payment option found\").\n const args = parse('haven_x402_sign_header', coercePaymentRequired(input))\n const result = await signer.buildX402PaymentHeader(\n args.payment_required as X402PaymentRequired,\n args.x402_binding,\n )\n await auditSigning(\n 'haven_x402_sign_header',\n hashPayloadForAudit(args.payment_required),\n )\n return { payment_header: result.paymentHeader, accepted: result.accepted }\n }),\n\n haven_sign_x402: async (input) =>\n runTool(async () => {\n // Coerce a stringified payment_required (same transport guard as\n // haven_x402_sign_header) and unwrap a whole-`x402`-object x402_expected\n // before validation.\n const args = parse('haven_sign_x402', coerceX402Expected(coercePaymentRequired(input)))\n const fetched = await resolveSignContext(args)\n const payloadHash = fetched?.payloadHash ?? args.payload_hash\n const expectedRaw = fetched ? parseFetchedExpected(fetched) : args.x402_expected\n if (!payloadHash || !expectedRaw) {\n throw new HavenSigningError(\n 'Pass payment_id (preferred — the signer fetches the signing context itself) ' +\n 'or payload_hash + x402_expected from the quote result.',\n )\n }\n // 1. Sign the funding leg (records the binding + checks expiry/context).\n // Which payload that is — bare hash or the account's typed data — is\n // decided by the Haven-signed context, not by the caller (#1138).\n const funding = await signFundingLeg(\n signer,\n toExpectedX402(expectedRaw),\n payloadHash,\n fetched?.typedData ?? resolveTypedData(args),\n )\n // 2. Build the merchant EIP-3009 header against that binding — local, no network.\n // #1355: prefer the PaymentRequired the context fetch carried (same\n // Haven read the signing bytes came from — one less blob an agent\n // relays); the caller-supplied copy is the fallback for pre-#1355\n // backends. Either copy passes the SAME expected-context\n // verification inside buildX402PaymentHeader — provenance is not\n // what makes it safe (#1263 discipline).\n const paymentRequired = (fetched?.paymentRequired ?? args.payment_required) as\n | X402PaymentRequired\n | undefined\n if (!paymentRequired) {\n throw new HavenSigningError(\n fetched\n ? 'The Haven sign-context for this payment_id carried no payment_required ' +\n '(backend predates #1355). Pass payment_required from the pay result ' +\n 'explicitly, verbatim.'\n : 'payment_required is required on the quote-based path (no payment_id to fetch ' +\n 'it by). Pass it verbatim from the quote result.',\n )\n }\n const header = await signer.buildX402PaymentHeader(\n paymentRequired,\n funding.x402Binding,\n )\n // Two audit entries — one per signing operation — matching the\n // decomposed haven_sign + haven_x402_sign_header trail, so the funding\n // signature and the merchant header remain distinguishable in the log.\n await auditSigning('haven_sign_x402', payloadHash)\n await auditSigning('haven_sign_x402', hashPayloadForAudit(paymentRequired))\n return {\n signature: funding.signature,\n x402_binding: funding.x402Binding,\n payment_header: header.paymentHeader,\n accepted: header.accepted,\n }\n }),\n\n haven_sign_sweep_delegate: async (input) =>\n runTool(async () => {\n const args = parse('haven_sign_sweep_delegate', input)\n const result = await signer.signSweepAuthorization({\n authorization: args.authorization,\n expectedAuth: args.expected_auth,\n // Cross-check `to` against the Safe in the local credential when present.\n expectedSafe: options.audit?.safeAddress,\n })\n await auditSigning(\n 'haven_sign_sweep_delegate',\n hashPayloadForAudit(args.authorization),\n )\n return { signature: result.signature }\n }),\n }\n\n async function auditSigning(tool: SignerToolName, payloadHash: string): Promise<void> {\n if (!options.audit) return\n const { auditPath, ...context } = options.audit\n await appendSigningAuditEntry(\n createSigningAuditEntry(tool, payloadHash, {\n ...context,\n delegateAddress: signer.delegateAddress,\n }),\n auditPath,\n )\n }\n}\n\nfunction parse<TName extends SignerToolName>(name: TName, input: unknown): Record<string, any> {\n return z.object(toolSchemas[name]).parse(input ?? {})\n}\n\n/**\n * Tolerate the agent passing the whole `x402` object from haven_pay_mcp_tool /\n * haven_pay_x402_quote where only the nested `x402.expected` signing context is\n * wanted. The wrapper looks like `{ accepted, resource_url, merchant_to,\n * funding_to, expected: {...} }` and lacks the top-level `auth` binding the\n * schema requires — so when `x402_expected.auth` is absent but\n * `x402_expected.expected` is an object, unwrap to `.expected`. Also parses a\n * JSON-stringified value back to an object first (some transports stringify\n * object args). This removes the easiest-to-make handoff mistake without a\n * breaking parameter rename.\n */\nfunction coerceX402Expected(input: unknown): unknown {\n if (!input || typeof input !== 'object') return input\n const record = input as Record<string, unknown>\n let value: unknown = record.x402_expected\n if (typeof value === 'string') {\n try {\n value = JSON.parse(value)\n } catch {\n return input\n }\n }\n if (!value || typeof value !== 'object') return input\n const obj = value as Record<string, unknown>\n if (obj.auth === undefined && obj.expected && typeof obj.expected === 'object') {\n return { ...record, x402_expected: obj.expected }\n }\n // Parsed-from-string but already the right shape: keep the parsed object.\n if (value !== record.x402_expected) return { ...record, x402_expected: value }\n return input\n}\n\n/**\n * If a caller's transport serialised `payment_required` to a JSON string,\n * parse it back to an object before schema validation. Leaves a real object\n * (or anything that isn't valid JSON) untouched.\n */\nfunction coercePaymentRequired(input: unknown): unknown {\n if (!input || typeof input !== 'object') return input\n const record = input as Record<string, unknown>\n if (typeof record.payment_required !== 'string') return input\n try {\n return { ...record, payment_required: JSON.parse(record.payment_required) }\n } catch {\n return input\n }\n}\n\nasync function runTool<T>(fn: () => Promise<T>): Promise<ToolPayload<T>> {\n try {\n return { success: true, data: await fn() }\n } catch (err) {\n return normalizeError(err)\n }\n}\n\nfunction normalizeError(err: unknown): ToolFailure {\n if (err instanceof z.ZodError) {\n return {\n success: false,\n code: 'INVALID_INPUT',\n message: err.errors.map((e) => `${e.path.join('.') || '(root)'}: ${e.message}`).join('; '),\n statusCode: 400,\n }\n }\n if (err instanceof HavenUnsupportedSignerVersionError) {\n // #1309: the structured signer refusal. `code` is one of\n // SignerRefusalCode's two values (not the generic 'SIGNING_ERROR'\n // HavenSigningError hard-codes), so an agent can route on it directly\n // instead of matching prose. next_action reuses the EXISTING\n // AgentPaymentNextAction taxonomy (StopAndTellUser) rather than inventing\n // a parallel vocabulary — this refusal is exactly that: stop, don't retry\n // as-is, tell the user what fallback says.\n return {\n success: false,\n code: err.code,\n message: err.message,\n supported_versions: [...err.supportedVersions],\n received_version: err.receivedVersion,\n fallback: err.fallback,\n next_action: AgentPaymentNextAction.StopAndTellUser,\n }\n }\n if (err instanceof HavenSigningError) {\n return { success: false, code: err.code, message: err.message }\n }\n if (err instanceof HavenApiError) {\n return { success: false, code: err.code, message: err.message, statusCode: err.statusCode }\n }\n if (err instanceof HavenError) {\n return {\n success: false,\n code: err.code,\n message: err.message,\n statusCode: err.statusCode,\n paymentId: err.paymentId,\n ...(err.code === AgentPaymentFailureCode.PaymentWindowExpired\n ? {\n next_action: AgentPaymentNextAction.PaymentWindowExpired,\n retry_with_new_quote: true,\n suggested_tool: 'haven_pay_mcp_tool',\n }\n : {}),\n }\n }\n return {\n success: false,\n code: 'UNKNOWN_ERROR',\n message: err instanceof Error ? err.message : String(err),\n }\n}\n","import { createHash } from 'node:crypto'\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport { toolDescriptions, toolSchemas, type SignerToolName } from './tools.js'\n\nexport interface SignerConsentInput {\n delegateAddress: string\n safeAddress?: string\n agentId?: string\n chainId?: number\n network?: string\n toolNames: readonly SignerToolName[]\n}\n\nexport interface SignerConsentDecision {\n ok: boolean\n hash: string\n reason:\n | 'env_var_match'\n | 'ack_file_match'\n | 'wrote_ack_file'\n | 'env_var_mismatch'\n | 'no_acknowledgement'\n}\n\nexport interface SignerConsentOptions {\n credentialsPath?: string\n writeAck?: boolean\n env?: Record<string, string | undefined>\n out?: { write: (chunk: string) => unknown }\n}\n\nexport const SIGNER_ACK_ENV = 'HAVEN_SIGNER_ACK'\n\n/**\n * The consent SURFACE version, folded into the acknowledgement hash. Bump it\n * when what the signer can DO changes in a way the consent text describes —\n * not for copy edits. Tool names alone cannot carry this: #1263 added the\n * signer's first network capability (the read-only signing-context fetch)\n * without changing any tool name, and a consent acknowledged under the old\n * \"does not call the Haven API\" text must not silently cover the new\n * behavior. Bumping this re-prompts every existing install exactly once,\n * with the corrected text.\n *\n * v2: the #1263 read-only signing-context fetch.\n */\nexport const SIGNER_CONSENT_SURFACE_VERSION = 2\n\nexport function computeSignerConsentHash(input: SignerConsentInput): string {\n const identity = [\n input.delegateAddress.toLowerCase(),\n (input.safeAddress ?? '').toLowerCase(),\n input.agentId ?? '',\n input.chainId ?? '',\n input.network ?? '',\n ].join('|')\n const toolCanonical = [...input.toolNames].sort().join(',')\n return createHash('sha256')\n .update(`${identity}\\n${toolCanonical}\\nsurface:v${SIGNER_CONSENT_SURFACE_VERSION}`)\n .digest('hex')\n .slice(0, 16)\n}\n\nexport function renderSignerConsentBlock(input: SignerConsentInput, hash: string): string {\n const lines: string[] = [\n '',\n '------------------------------------------------------------',\n 'Haven edge signer - first-launch consent',\n '------------------------------------------------------------',\n '',\n `Delegate address: ${input.delegateAddress}`,\n ]\n lines.push(`Haven wallet: ${input.safeAddress ?? 'not provided to this signer'}`)\n if (input.agentId) lines.push(`Agent ID: ${input.agentId}`)\n if (typeof input.chainId === 'number') lines.push(`Chain ID: ${input.chainId}`)\n if (input.network) lines.push(`Network: ${input.network}`)\n lines.push('')\n lines.push('This local signer holds the delegate key on this machine and signs')\n lines.push('payment payloads or x402 merchant headers for the delegate address above.')\n lines.push(\"Its one network use is a read-only fetch of a pending payment's signing\")\n lines.push('payload from Haven, authenticated with the agent credential stored next to')\n lines.push(\"this signer's key file - it never sends the key, a signature, or anything\")\n lines.push('else outbound, and it cannot show a live allowance summary.')\n lines.push('On-chain Safe rules remain the real spend gate, and the wallet owner can')\n lines.push('pause or revoke agent authority outside this signer.')\n lines.push('')\n lines.push('Tools this signer will expose to your agent runtime:')\n for (const name of input.toolNames) {\n lines.push(` - ${name}`)\n lines.push(` ${toolDescriptions[name]}`)\n }\n lines.push('')\n lines.push('A local audit entry is appended for every signing operation. Audit entries')\n lines.push('record timestamp, tool, payload hash, and delegate address; never the key,')\n lines.push('signature, or x402 payment header.')\n lines.push('')\n lines.push(`Consent hash: ${hash}`)\n lines.push('')\n lines.push('To acknowledge, EITHER:')\n lines.push(` - set ${SIGNER_ACK_ENV}=${hash} in this process's environment, OR`)\n lines.push(' - re-run with --ack to write the acknowledgement next to your')\n lines.push(' credential file (sidecar <credentials>.signer-ack.json).')\n lines.push('')\n lines.push('------------------------------------------------------------')\n lines.push('')\n return lines.join('\\n')\n}\n\nexport async function ensureSignerConsent(\n input: SignerConsentInput,\n options: SignerConsentOptions = {},\n): Promise<SignerConsentDecision> {\n const env = options.env ?? process.env\n const out = options.out ?? process.stderr\n const hash = computeSignerConsentHash(input)\n const envAck = env[SIGNER_ACK_ENV]\n\n if (typeof envAck === 'string' && envAck.length > 0) {\n if (envAck === hash) return { ok: true, hash, reason: 'env_var_match' }\n out.write(renderSignerConsentBlock(input, hash))\n out.write(\n `${SIGNER_ACK_ENV} was set but did not match the current signer consent hash.\\n` +\n `Expected: ${hash}\\n` +\n `Got: ${envAck}\\n` +\n `Re-acknowledge with the new hash above, or run with --ack.\\n\\n`,\n )\n return { ok: false, hash, reason: 'env_var_mismatch' }\n }\n\n const ackPath = sidecarPath(options.credentialsPath)\n if (ackPath) {\n const stored = await readAckFile(ackPath)\n if (stored?.ack === hash) return { ok: true, hash, reason: 'ack_file_match' }\n }\n\n if (options.writeAck && ackPath) {\n out.write(renderSignerConsentBlock(input, hash))\n await writeAckFile(ackPath, hash)\n out.write(`Wrote acknowledgement to ${ackPath}\\n\\n`)\n return { ok: true, hash, reason: 'wrote_ack_file' }\n }\n\n out.write(renderSignerConsentBlock(input, hash))\n return { ok: false, hash, reason: 'no_acknowledgement' }\n}\n\nexport function registeredSignerToolNames(): SignerToolName[] {\n return Object.keys(toolSchemas) as SignerToolName[]\n}\n\nfunction sidecarPath(credentialsPath?: string): string | null {\n if (!credentialsPath) return null\n return resolve(`${credentialsPath}.signer-ack.json`)\n}\n\nasync function readAckFile(path: string): Promise<{ ack?: string } | null> {\n try {\n const raw = await readFile(path, 'utf8')\n const parsed = JSON.parse(raw) as { ack?: unknown }\n return { ack: typeof parsed.ack === 'string' ? parsed.ack : undefined }\n } catch {\n return null\n }\n}\n\nasync function writeAckFile(path: string, hash: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(\n path,\n JSON.stringify({ ack: hash, at: new Date().toISOString() }, null, 2),\n 'utf8',\n )\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { defaultSigningAuditPath } from './audit.js'\nimport { signerCapabilityAdvertisement, signerInstructions } from './capabilities.js'\nimport {\n ensureSignerConsent,\n registeredSignerToolNames,\n type SignerConsentDecision,\n} from './consent.js'\nimport { isSupportedNodeVersion, unsupportedNodeVersionMessage } from '@haven_ai/sdk'\nimport { createEdgeSigner, type EdgeSigner } from './core.js'\nimport { loadSignerCredentials, type SignerCredentials } from './credentials.js'\nimport {\n createToolHandlers,\n toolDescriptions,\n toolSchemas,\n type SignerToolName,\n type ToolPayload,\n} from './tools.js'\nimport { loadHavenIdentity } from './sign-context.js'\n\nexport const SIGNER_NAME = '@haven_ai/signer'\nexport const SIGNER_VERSION = '0.1.23-alpha.2'\n\nexport interface SignerOptions {\n /** Path to a Haven credential JSON file (delegate_key is read from it). */\n credentialsPath?: string\n /** Pre-resolved delegate key (skips credential loading). */\n delegateKey?: string\n /** Append local signing audit entries here. Defaults to a credential sidecar or ~/.haven. */\n auditPath?: string\n /** Overridable so the Node-floor refusal is testable without spawning a Node. */\n nodeVersion?: string\n /**\n * When true, write the consent sidecar file (`<credentials>.signer-ack.json`)\n * with the current consent hash and proceed. Surfaced via the `--ack` CLI flag.\n */\n writeAck?: boolean\n /**\n * When true, skip the consent gate entirely. Reserved for tests and controlled\n * embedding — production CLIs should not set this.\n */\n skipConsent?: boolean\n /** Override consent environment lookup. Reserved for tests and controlled embedding. */\n consentEnv?: Record<string, string | undefined>\n /** Override the stream the consent block is printed to. Reserved for tests. */\n consentOut?: { write: (chunk: string) => unknown }\n /** Trusted Haven signer address for x402 expected-context bindings. */\n x402BindingSigner?: string\n}\n\nexport async function resolveEdgeSigner(options: SignerOptions = {}): Promise<EdgeSigner> {\n const { signer } = await resolveSignerRuntime(options)\n return signer\n}\n\nexport interface ResolvedSignerRuntime {\n signer: EdgeSigner\n credentials?: SignerCredentials\n}\n\nexport async function resolveSignerRuntime(\n options: SignerOptions = {},\n): Promise<ResolvedSignerRuntime> {\n // The choke point, deliberately (#1161 review). Every public way to obtain a\n // key-bound EdgeSigner from this package funnels through here —\n // `runSignerStdioServer`, `resolveEdgeSigner`, and any embedder calling it\n // directly (the `skipConsent` docs invite controlled embedding, so that is a\n // supported surface, not just a test seam). Asserting only in the stdio\n // entrypoint would have reproduced the exact bug this issue fixes: a guard\n // that exists but sits on one path while another reaches the delegate key\n // unchecked.\n //\n // First statement, before the `delegateKey` fast path and before credentials\n // are read, so an unsupported runtime never touches a key by either route.\n assertSupportedNodeVersion(options.nodeVersion)\n\n if (options.delegateKey) {\n return {\n signer: createEdgeSigner(options.delegateKey, {\n x402BindingSigner: options.x402BindingSigner ?? process.env.HAVEN_X402_BINDING_SIGNER,\n }),\n }\n }\n const creds = await loadSignerCredentials(options.credentialsPath)\n return {\n signer: createEdgeSigner(creds.delegateKey, {\n x402BindingSigner:\n options.x402BindingSigner ?? creds.x402BindingSigner ?? process.env.HAVEN_X402_BINDING_SIGNER,\n }),\n credentials: creds,\n }\n}\n\n/**\n * Build a local stdio MCP server exposing the sign-only tools, bound to an\n * edge signer that holds the delegate key. It exposes no construct/relay\n * tools — it only signs. Its ONE network capability (#1263) is an\n * authenticated READ: fetching a payment's exact signing context from Haven\n * by payment_id, so agents never have to relay multi-KB signing payloads\n * through a model context. The signer CORE below it stays network-free, and\n * fetched bytes pass the same verification as tool-argument bytes.\n */\nexport function buildSignerMcpServer(\n signer: EdgeSigner,\n options: Pick<SignerOptions, 'auditPath'> & { credentials?: SignerCredentials } = {},\n): McpServer {\n // #1155: the handshake states what this signer can verify, so an agent can\n // detect expected-context skew before it quotes rather than after it signs.\n // `SIGNER_VERSION` is a *package* version and nothing derives capability from\n // it — both fields below are derived from the constants the signing path\n // enforces. Advisory only: no refusal is added here, the #1143 signing-time\n // guard remains the enforcement point.\n const server = new McpServer(\n { name: SIGNER_NAME, version: SIGNER_VERSION },\n {\n capabilities: signerCapabilityAdvertisement(),\n instructions: signerInstructions(),\n },\n )\n\n const credentialsPath = options.credentials?.sourcePath\n const handlers = createToolHandlers(signer, {\n audit: {\n auditPath: options.auditPath ?? defaultSigningAuditPath(credentialsPath),\n delegateAddress: signer.delegateAddress,\n safeAddress: options.credentials?.safeAddress,\n chainId: options.credentials?.chainId,\n },\n // #1263: the payment_id signing path — the ONLY network call this server\n // can make, an authenticated read of a signing context from Haven, using\n // the agent identity the connector stores next to the signer credential.\n // The signer CORE stays network-free; fetched bytes still pass the same\n // binding verification + digest re-derivation as tool-argument bytes.\n signContext: {\n loadIdentity: () => loadHavenIdentity(credentialsPath),\n },\n })\n const registerTool = (server as unknown as {\n tool: (\n name: string,\n description: string,\n schema: unknown,\n handler: (args: unknown) => Promise<unknown>,\n ) => void\n }).tool.bind(server)\n\n for (const name of Object.keys(toolSchemas) as SignerToolName[]) {\n registerTool(name, toolDescriptions[name], toolSchemas[name], async (args: unknown) =>\n toMcpResult(await handlers[name](args)),\n )\n }\n\n return server\n}\n\n/**\n * Refuse to start on an unsupported Node (#1161).\n *\n * Asserted at STARTUP, not only at install, because the two can diverge: a user\n * upgrades Node, connects successfully, then downgrades — or a version manager\n * hands the agent runtime a different Node than the shell that ran setup. Only a\n * startup check sees the version this process is actually running on.\n *\n * This is the signer, so refusing is the conservative answer rather than the\n * aggressive one. It holds the delegate key and produces every payment\n * signature; on an unsupported runtime the plausible failure is a wrong or\n * absent signature, which is worse than not starting. The consent gate below\n * takes the same posture for the same reason.\n */\nexport function assertSupportedNodeVersion(nodeVersion: string = process.versions.node): void {\n if (isSupportedNodeVersion(nodeVersion)) return\n const err: NodeJS.ErrnoException = new Error(\n unsupportedNodeVersionMessage({ subject: 'The Haven signer', nodeVersion }),\n )\n err.code = 'HAVEN_SIGNER_UNSUPPORTED_NODE'\n throw err\n}\n\nexport async function runSignerStdioServer(options: SignerOptions = {}): Promise<void> {\n // The Node floor is asserted inside resolveSignerRuntime — the choke point\n // every key-bound path shares — so it is enforced here too, before\n // credentials are read, without a second call site to keep in sync.\n const { signer, credentials } = await resolveSignerRuntime(options)\n\n if (!options.skipConsent) {\n const decision = await runSignerConsentGate(signer, credentials, options)\n if (!decision.ok) {\n const err: NodeJS.ErrnoException = new Error(\n decision.reason === 'env_var_mismatch'\n ? 'Haven edge signer consent acknowledgement does not match the current configuration.'\n : 'Haven edge signer requires a one-time consent acknowledgement before starting.',\n )\n err.code = 'HAVEN_SIGNER_NO_CONSENT'\n throw err\n }\n }\n\n const server = buildSignerMcpServer(signer, { credentials, auditPath: options.auditPath })\n await server.connect(new StdioServerTransport())\n}\n\nexport async function runSignerConsentGate(\n signer: EdgeSigner,\n credentials: SignerCredentials | undefined,\n options: SignerOptions,\n): Promise<SignerConsentDecision> {\n return ensureSignerConsent(\n {\n delegateAddress: signer.delegateAddress,\n safeAddress: credentials?.safeAddress,\n agentId: credentials?.agentId,\n chainId: credentials?.chainId,\n network: credentials?.network,\n toolNames: registeredSignerToolNames(),\n },\n {\n credentialsPath: options.credentialsPath ?? credentials?.sourcePath,\n writeAck: options.writeAck,\n env: options.consentEnv,\n out: options.consentOut,\n },\n )\n}\n\nfunction toMcpResult(payload: ToolPayload) {\n return {\n isError: !payload.success,\n content: [{ type: 'text' as const, text: JSON.stringify(payload, null, 2) }],\n }\n}\n"]}