@xochi/signer
v0.10.0
Published
Network-free EIP-712 signing and pre-sign checks for Xochi intents: ERC-3009, Permit2, ERC-5564, ERC-4337, escrow.
Maintainers
Readme
@xochi/signer
Network-free signing and pre-sign checks for Xochi intents, origin pulls (ERC-3009, Permit2), deposit attestations, stealth claims, ERC-4337 v0.8 UserOps and escrow hashes. Implements SPEC.md and ESCROW-RFC.md. These sign bytes that move real funds: follow the safety rules.
Install
npm install @xochi/signerESM + CommonJS with types. Direct deps: ethers v6, @noble/curves ^1.9.0, @noble/hashes 1.8.0, @zkpassport/poseidon2 0.6.2.
Usage
import {
assertIntentMatchesRequest,
assertPullMatchesIntent,
signPullAuthorization,
signXochiIntent,
} from "@xochi/signer";
const request = { wallet, fromChainId: 8453, toChainId: 10, fromToken, toToken, fromAmount };
const quote = await fetchQuote(request); // your transport
assertIntentMatchesRequest(request, quote); // the intent's values are the ones you asked for
assertPullMatchesIntent(quote, { expectedPullRecipients }); // the pull moves only that intent
const intentSignature = await signXochiIntent(quote.eip712, privateKey);
const pullSignature = await signPullAuthorization(quote.pull_authorization, privateKey);Checks throw on mismatch. Deposit-address routes use verifyDepositAttestation, assertDepositQuoteMatchesRequest and recordDepositAddress; stealth claims use deriveStealthPrivateKey, assertPreparedClaimMatchesRequest and signUserOpHash. A claimant holding the scanned announcement uses verifyClaimUserOp instead: it returns {ok: false, reason} rather than throwing, refuses every gap, and also binds the token, factory, owner and salt to the announcement and the signing key. See the TSDoc.
The receive side of stealth (stealth-receive.ts) derives a wallet's keys from its signature over STEALTH_DERIVE_MESSAGE (deriveStealthKeys), its ERC-6538 meta-address (computeMetaAddressFromKeys, encodeMetaAddress), and filters and derives announcements (checkViewTag, deriveStealthOwner, decodeAnnouncementMetadata, decodeStandardAnnouncementMetadata). A standard scheme-1 payment announces address(P') itself: it matches when deriveStealthOwner(...).stealthEOA equals the announced address, and its metadata is the 57-byte ERC-5564 layout. A legacy Xochi payment announces the counterfactual account that EOA owns, with the 109-byte layout; matching it is a getAddress(owner, salt) read on a factory you trust, so it stays with the caller. Decode with the layout of the address that matched (announcedPayout), not by length. An address(P') payment is claimed with an EIP-7702 UserOp: check it with verifyEip7702ClaimUserOp against your own pinned delegates, and sign only the authorization it returns. deriveStealthKeys accepts only a 65-byte signature: a smart account's answer (0x from a Safe, an ERC-6492 or ERC-1271 envelope) is not a stable seed, and 0x gives every such wallet the same public keys. Check a meta-address you did not just derive with isCompromisedStealthSpendingPubKey.
Safety rules
- Run the value checks before signing. The signers check schema only (off-schema typed data refuses);
assertIntentMatchesRequestandassertPullMatchesIntentcheck values. - Keep pins where the server can't reach (build constant, reviewed config). Never read them, or the deposit attestation signer, from
/xochi/capabilities(Capabilities). expectedPullRecipientsis the only recipient check, and an absent pin skips it (Pull verification).- Quotes with an
escrowenvelope sign only throughassertEscrowQuoteMatchesRequest, against your escrow pin (Escrow quotes). exact_outputrequiresmax_from_amount, for pulls and deposit routes alike.signERC3009is USDC-only; usesignPermit2for other tokens.signUserOpHashsigns raw (no EIP-191 prefix); only sign a hashassertPreparedClaimMatchesRequestorverifyClaimUserOprecomputed.- Deposit routes verify against your pinned attestation signer and a store you supply (Deposit-address routes).
- Passkey recipients: confirm a new passkey's PRF with a second ceremony, and refuse one whose derived address differs from the one you recorded (both checks are the caller's; Passkey recipients).
Pull verification
assertPullMatchesIntent(quote, opts) holds the origin pull (pull_authorization) to the intent assertIntentMatchesRequest already verified. It is offline and pure: it takes the recipient pin and the escrow pin, never a chain reader or a settlement pin. signPullAuthorization checks shape only (the two real pull schemas); value checks need an intent, so they live here.
Binding the pull to the intent:
- The pull's domain is as load-bearing as its message.
domain.chainIdmust equalintent.fromChainId, unconditionally: an intent missingfromChainIdrefuses with no pin at all. The check is bound to the intent, not a chain-registry lookup, so a chain the server adds does not fail closed. ERC-3009:verifyingContract==intent.fromToken. Permit2:verifyingContract==PERMIT2_ADDRESSandpermitted.token==intent.fromToken. Token identity, amount and expiry are compared as well. - A quote with a non-null
escrowenvelope refuses here (assertNoEscrowEnvelope, also run byassertDepositQuoteMatchesRequest). Who an escrow pays is theorderIdthe pull binds (ERC-3009nonce, Permit2 witness), checked only by the SPEC §2.3 binding; verify such a quote withassertEscrowQuoteMatchesRequest(Escrow quotes). A recipient pin naming the escrow is not sufficient. - A pull to a caller-pinned escrow is escrow-bearing with or without the envelope (SPEC.md §6).
expectedEscrows({ [originChainId]: address }, either spelling) refuses ato/spendernaming the escrow pinned forintent.fromChainId; a blank pin refuses. Never merge it intoexpectedPullRecipients. One resolver,resolvePinnedEscrow, reads it for this guard and forassertEscrowBinding: keys are positive chain ids in decimal or0xhex, trimmed; any other key, or two keys for one chain with different escrows, refuses.
Expiry bound:
- Expiry is bounded by
intent.deadline + pullExpiryBoundSeconds(advertised): the tighter of the advertisedpull_deadline_buffer_secondsand the localMAX_PULL_EXPIRY_AFTER_INTENT_SECONDSceiling (3600 s; prod advertises 300 s). Reading a served number is sound only because it is a minimum: the local ceiling still caps it. An advertised0is an outage; an absent or malformed value falls through to the ceiling, never to zero. The intent's own deadline is held toMAX_INTENT_DEADLINE_AHEAD_OF_NOW_SECONDS. - Do not tighten
MAX_PULL_EXPIRY_AFTER_INTENT_SECONDSto a number read off a live deployment. The advertised buffer changes between deploys; a ceiling below a future value refuses every honest quote. - The advertised value is opt-in and never auto-fetched (
advertisedPullDeadlineBufferSeconds, either spelling): nothing on the signing path reads/xochi/capabilities; absent means the ceiling.
The recipient pin:
to/spenderis checked only againstexpectedPullRecipients({ [fromChainId]: { erc3009?, permit2? } }, either spelling). Riddler advertises the matrix per chain and method on/xochi/capabilities(pull_recipients; on prod ERC-3009 is a different solver EOA per chain, Permit2 one universal proxy). That is discovery, never the pin.- Absence of a pin skips the check; an attacker can drop a field from the quote but not an entry from your pin. Drop an outgoing address once a rollover completes. The chain and method axes grade differently: a chain absent from the pin is unchecked; a chain present but missing the method in use refuses. The pin is keyed on
intent.fromChainIdonly, never the pull'sdomain.chainId; an intent with no chain refuses, as does a blank pin entry. - A method may name a set of accepted values (
erc3009: [outgoing, incoming];MethodPin,pinAccepts,describePin) to cross a solver rollover (Riddler rotates the ERC-3009 EOA per chain). A set is a window, not a configuration: the outgoing value keeps verifying until removed, so a long-lived two-value pin is weaker. An empty list, blank entry or non-string entry refuses, like{}and"";pinnedForrefuses anullmethod too. - An ERC-3009
tois the payee; a Permit2spenderonly may pull.SignatureTransferDetails.tois not in the signed struct (OriginPullWitnessbinds anorderId), so the refusals say different things.
Escrow quotes
On an escrow corridor (SPEC.md §5.2) the origin pull opens a RiddlerEscrow lock: its to/spender is the escrow and its ERC-3009 nonce / Permit2 witness is the order's orderId. assertEscrowQuoteMatchesRequest(request, quote, opts) is the only check that admits such a quote. It returns the VerifiedEscrowOrder (orderId, terms, opening, fill deadline, OpenAuth signer); keep it as recovery evidence.
const order = assertEscrowQuoteMatchesRequest(request, quote, {
expectedEscrows: { 8453: "0x4438a8b3EE5AAf58343B18629040a4BCB8b0feCb" }, // your reviewed manifest
minOut, // your own floor: the signed toAmount less your slippage, never min_to_amount
expectedOpenAuthSigners, // optional
});
const pullSignature = await signPullAuthorization(quote.pull_authorization, privateKey);- The escrow is a pin, never a quoted value.
expectedEscrowscomes from a deployment manifest you reviewed (the example is Base MainNet'sRiddlerEscrowproxy), never fromescrow.address,order_terms.escrowor/xochi/capabilities. An absent pin, or an origin chain it does not cover, refuses. - What it runs, in order:
assertIntentMatchesRequest, withwallet,to_chain_id,to_tokenand the recipient required;- the Canton destination rule (below);
- the pull held to the intent: chain, token, amount, Permit2 contract, expiry;
assertEscrowBinding: recipient, token, chain andminOutagainst the request;destCommitmentandorderIdrecomputed;terms.escrow== pullto/spender== pin; depositor ==wallet; nonce / witness ==orderId;order_terms.from_chain_id== the intent's, envelopefill_deadline== the terms', the opening'sintent_id== the signedintentId;- a 65-byte
open_authrecovering over the pinned escrow's domain, to one ofexpectedOpenAuthSignerswhen given.
- Canton is reached through its synthetic chain id only (
CANTON_MAINNET_CHAIN_ID, 253340876), with a party recipient (isCantonPartyId, never case-folded) and that network's instrument (CANTON_INSTRUMENTS; Canton Coin today). A party or instrument on any other chain id refuses, and the gateway facade ids 31337 and 30337 are named as such (assertCantonDestination). - A refund needs no one. Without an attested delivery, anyone may call
refund(orderId)oncerefundableAt = fillDeadline + claimWindowpasses; the principal returns to the depositor.
Deposit-address routes
A non-EVM origin (Tron) cannot be pulled: the server allocates a per-intent deposit_address, attests it, and the user sends the TRC-20. A quote carries either pull_authorization or deposit_address, never both, and this route makes no /xochi/execute call. deposit-verify.ts holds the primitives; whoever wraps them (Riddler's harness xochiDepositQuote, @xochi/client's machine) is bound by these rules:
- The attestation is verified against YOUR pinned signer. The server signs an EIP-191 message over the quote's binding fields with
capabilities.deposit_attestation_signer;verifyDepositAttestationrebuilds it byte-exactly and throws on mismatch. A missing attestation is a failure, not a skip. The pin is required: a fallback to/xochi/capabilitieschecks the key against the channel that served it. Trust-on-first-use means fetching the advertised signer yourself, once, and pinning it. - Every semantic guard lives in
assertDepositQuoteMatchesRequest, the seam integrators call, not in a wrapper: the attested fields are held to the request; a non-nullescrowenvelope refuses (see Pull verification); the attesteddeposit_deadlinemust leave at leastDEPOSIT_MIN_WINDOW_SECONDS(60 s), and an absent deadline is malformed, not "no expiry". There is nonowinjection point: an optional clock on a security assertion is a bypass; tests move the clock. - A
recipient,walletorrefund_addressstarting0xthat is not0x+ hex refuses (a0x-hint Canton party id). Riddler encodesto_tokenandrecipientcase-exactly unless they are entirely0x+ hex (axol-io/Riddler#1254), and the message builder mirrors that (other fields keep the plain0xfold).deposit_attestation_versiondoes not tell that encoding from the older lowercasing one, under which an attestation for0xalice::...verifies a request for0xAlice::...(recipient_addressis unsigned), so the refusal holds until that version moves. No served deposit route carries such a value. recipientIsDestinationTokenrefuses a payout to the destination token contract (raxol#869: real funds settled there unspendably and were reportedcompleted). It checks the caller's own inputs, so run it before requesting the quote;assertDepositQuoteMatchesRequestruns it again on the attested fields.recordDepositAddressrefuses an address re-issued under a different intent (Riddler#853: an HD-cursor rewind re-derived a live address for another user), keyed throughnormalizeAddress. It needs theseenAddressesstore you inject and sees only this client's quotes.attestationSignerConsistencyis advisory (checkAdvertisedSigner): it compares the pin with the advertised key so a half-rotated pair reads as such, never as tampering. The pin decides either way; never promote it to a refusal.- The attestation vectors (
packages/reference/test/vectors/deposit_attestation.json) are server-generated; never recompute them here.
Capabilities
parseCapabilities and its accessors (originPullMethod, advertisedTokenAddress, advertisedConversionPairs, advertisedRoute, routeSupportsPrivacyMode, servedChainKeys, chainUnservedReason, depositAttestationVersionSkew, orderBoundsViolation, stealthNotionalFloor, narrowStealthChains, stealthFactoryFor) model GET /xochi/capabilities. The matrix arrives over the quote's channel, so it is not a trust anchor: nothing in capabilities.ts is named assert*, verify* or check*, nothing there may relax a check, and pull_recipients is discovery data, never a pin. advertisedTokenAddress is advertised data, not a pinned token address. Read originPullMethod per chain: the top-level pull_method is EVM-representative and wrong for Tron.
Stealth is per chain. stealthChains lists where the server quotes stealth ([]: nowhere; null: it did not say); narrowStealthChains intersects it with your own set and never adds a chain to it. stealthFactoryFor reads chains[].stealth_factory_address for a single EVM chain listed in stealth_chains, with no fallback to the deprecated top-level stealth_factory_address. The factory decides who can claim, so hold the advertised one against your own pinned factory allowlist and never widen that allowlist from it. executeOwnership is true only while the server serves execute_ownership: true, i.e. /xochi/execute refuses every kid but the quote's requester, and absent reads false. When a details.funds_moved: false refusal may be treated as "nothing moved" is SPEC.md §3.5's sole-caller exception, which needs more than this flag.
Parsing is tolerant (unknown keys dropped, absent optionals null, an unusable payload null), with these fail-closed readings, each explained in the source: an unadvertised, duplicated or unknown-VM chain is unserved (null, never evm / hex20 / first-wins; a duplicate token symbol likewise); an absent vm_type means evm, a present but unrecognised one keeps the row unaddressable so the duplicate check still sees it (served cvm, Canton, is not hex20); chain-id keys must be canonical decimal ("08453" collapses onto 8453); and Canton party ids (hint::1220<64 hex>) are case-sensitive even when the hint starts 0x, so sameAddressish folds case only for 0x + hex.
routes[] is the producer's authoritative exact-route contract: { origin: { chain_id, token }, destination: { kind: "chain", chain_id, token } | { kind: "zk_money", token }, privacy_modes }. parseCapabilities drops a malformed route entry atomically, preserves valid entries in served order, and ignores unknown additive object keys. advertisedRoute returns null for an absent or duplicated endpoint; routeSupportsPrivacyMode is true only for a named mode on that one route. A present list, including [], decides route selection. An absent top-level routes becomes null, triggering the documented legacy downgrade; a present malformed value fails closed to []. conversionPairs[].sameChain keeps its existing per-pair meaning and is not an exclusive-route marker.
Shielded recipient and readiness
Inert: nothing in the signing path calls shielded*.ts, and shielded settlement is off. These modules only verify; no key is held or accepted. Signature recovery alone never proves current authorization.
verifyRecipientAcktrusts only your inputs.bindingis the one you accepted from the source-wallet ceremony,descriptorthe one it names,environmentandnetworkyour corridor record's, andprofiletheAZTEC_RECIPIENT_PROFILESentry your corridor record pins for that network. Never take any of them from the recipient. The descriptor is checked against the profile you pass, not against the network: nothing maps aNetworkIdentityto a profile for you.expectedis the subject you hold: the backup commitment you stored, the sender set you registered, or the receipt challenge nonce and expiry you issued plus the settlement you recorded. The enrollment acknowledgements are held to the binding's own nonce and expiry; a receipt is held to both members of its separately issued challenge.expected.backupFormatIdselects the backup mode. Absent ornull(a legacy row's NULL column), only the sealed-file format verifies, and a passkey-mode acknowledgement refuses withbackup_format_mismatch. Buildpolicy.expectedfrom your own trusted storage, never from the signed acknowledgement. For a passkey recipient,passkeyBackupAckExpected(storedDescriptor)computes both the trusted credential commitment andBACKUP_FORMAT_PASSKEY_V1_ID; pass its result asexpected. Only a passkey-derived recipient may use passkey mode; an imported one keeps the sealed-file format.lookupAcceptanceandcommitAcceptancereceive only fully verified acknowledgement state.lookupAcceptance(replayKey)reads the durable{ digest, result }for an expired exact retry; an absent or different digest failschallenge_expired, and no post-expiry commit is attempted.commitAcceptancereceives an unexpired acknowledgement, includingrecipientAckReplayKey(primaryType, bindingDigest, nonce)and its digest. It MUST atomically commit replay consumption with the complete application acceptance/result and return{ status: "committed", result }, or return the previously stored{ status: "existing", digest, result }. An exact-digest retry returns that same result withreplayed: true; a different digest under the replay key refuses withnonce_replayed. Neither callback may commit a consumed key alone. A malformed callback outcome throwsTypeError; it never becomes an accepted acknowledgement.- Refusals are
AckEncodingError, malformed input included; an unknownprimaryType(untrusted wire input, any non-string included) refuses asunknown_primary_type, never a bareTypeError. A descriptor or profile of yours that fails its own check throwsRecipientEncodingError. verifyReadinessRecordrebuilds the domain from your corridor record and pinsexpectedSignerto the corridor's dedicated attestation key. Pinexpected.rooton aMembershipcheck whenever you hold the latest attested root; without it,minBlockmust be that root'srootBlock, or a member record under a superseded root verifies until it ages out. ARootUpdateis how a new root is learned, so its root is usually unpinned.maxAgeSecondsandmaxFutureSkewSecondsare capped at 86 400 and 300; choose stricter values per consumer.recoverReadinessSignerreturns an address, not a verdict: compare it with your pin, or useverifyReadinessRecord.
Passkey recipients
APPROVED by product-owner sign-off on 2026-11-09 (@xochi/spec PASSKEY-RECIPIENT.md).
Deployment remains default-off. Passkey claims MUST NOT be enabled until every xochi.fi host is inventoried, serves only Xochi code, and serves every document with the spec's strict CSP (including 'wasm-unsafe-eval', excluding 'unsafe-inline' and 'unsafe-eval'), and no WebAuthn, Apple or Android association file widens the RP ID boundary. The current app CSP fails this gate.
derivePasskeyRecipientKeys({ first, second }) turns the two PRF outputs of one WebAuthn ceremony into the recipient CLI's AccountSecrets, a 32-byte wrapKey and a 32-byte pxeStoreKey. Evaluate with passkeyPrfInputBytes() (the 32 raw bytes; never encode the hex text of PASSKEY_PRF_INPUTS), RP ID PASSKEY_RP_ID and userVerification: "required". Pass results.first / results.second as returned (ArrayBuffer) or as any 32-byte view; they are copied, never written. The ceremony itself is the caller's; this package only derives.
- A missing or short PRF output refuses (
PasskeyDerivationError,prf_output_invalid). The authenticator did not evaluate PRF: refuse the claim and show the supported list. Never fall back to a passphrase or a random key.secondequal tofirstrefuses too (the same result passed twice). - Confirm a new passkey before deriving anything. Run a second ceremony on the new credential and require byte-identical
firstandsecond(constant-time); otherwise refuse (prf_unstablein the spec) and enroll nothing. A passkey whose PRF changes per ceremony would bind an address no later ceremony can spend from. - The derived account must be the recorded one. A passkey that answers with different PRF bytes in another browser derives a different, empty account, not an error. Compare the derived address with the address you recorded, and refuse on a mismatch.
wrapKeyis raw key material: import it as a non-extractable AES-GCMCryptoKeyand zero the array. Errors never carry PRF or derived bytes; do not logPasskeyRecipientKeys.
Changes: CHANGELOG.md.
License
MIT
