Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(x402): let a paying agent check an endpoint before it spends on it

nirholas41217bea9194
diff --git a/api/_lib/x402/preflight.js b/api/_lib/x402/preflight.js
new file mode 100644
index 000000000..a5eb6cca9
--- /dev/null
+++ b/api/_lib/x402/preflight.js
@@ -0,0 +1,414 @@
+// @ts-check
+// api/_lib/x402/preflight.js
+//
+// x402 Preflight — a signed, time-bounded statement that an endpoint can
+// actually take your money and finish the job.
+//
+// The problem it exists for
+// -------------------------
+// x402 tells a client WHAT a resource costs. It says nothing about whether the
+// server is currently able to SETTLE what it charges. Those are different
+// questions with the same happy path and completely different failure modes,
+// and the gap between them is paid for by the buyer:
+//
+// 1. client GETs a paid route, receives 402 with a price and accepts
+// 2. client signs a transfer and retries with X-PAYMENT
+// 3. server cannot settle (its fee sponsor is empty, its facilitator is down,
+// its RPC is over quota) and answers 502
+//
+// The client burned a signature, a blockhash and a round trip on a service that
+// could not have completed at step 1. Worse, in the sponsored-fee model the
+// buyer's own funds are fine: the thing that is broken belongs to the SELLER,
+// and the buyer has no way to see it. On 2026-08-28 three.ws was that seller for
+// three hours. 95 payment attempts, 0 settled, every one of them predictable
+// from state the server already had.
+//
+// Preflight closes that gap the way CORS preflight closes its own: one cheap,
+// cacheable request BEFORE the expensive one, answered from state the server
+// already computes.
+//
+// Why it is signed, and why that is the interesting part
+// -----------------------------------------------------
+// An unsigned health endpoint is a courtesy. A signed, time-bounded, replay-
+// resistant one is EVIDENCE. Three properties follow, and none of them are
+// available from a plain status page:
+//
+// ATTRIBUTABLE A client that paid after reading `payable: true` holds a
+// statement signed by the seller's own attester key saying the
+// seller believed it could settle, at a stated instant. In a
+// marketplace of autonomous agents transacting with strangers,
+// that is the difference between "it broke" and "you said it
+// would work". Disputes stop being he-said-she-said.
+// UNREPLAYABLE Every attestation carries `expires_at` and verification
+// REJECTS an expired one. A seller cannot serve a cached
+// healthy attestation through an outage, and an attacker who
+// captures one cannot replay it later.
+// RELAYABLE Because it verifies offline against a public key, a registry,
+// an index or a peer can cache and forward attestations without
+// becoming trusted. Discovery services can rank by measured
+// settleability instead of by self-description.
+//
+// Honesty rules the format enforces
+// ---------------------------------
+// * `payable` is a THREE-valued field: true, false, or unknown. A server that
+// cannot determine its own state must say `unknown`, never `true`. Every
+// code path here fails to `unknown`, so a crashed sensor degrades to "I do
+// not know" rather than to a lie.
+// * Every rate carries the window and the sample size it was measured over. A
+// rate without its window is a rumour; `confidence` is derived from the
+// sample, so a 100% settle rate over 3 attempts cannot masquerade as proof.
+// * `alternates` names the other networks on the same origin that ARE payable,
+// so a client whose preferred rail is down can re-route in the same round
+// trip instead of discovering the outage one failed payment at a time.
+// * `retry_after` is advisory back-off, so a fleet of agents meeting an
+// unpayable seller backs off instead of synchronising into a retry storm.
+//
+// This module is deliberately pure: no DB, no fetch, no chain, no clock except
+// what the caller injects. The I/O that feeds it lives in api/x402/preflight.js,
+// and the same verify() below is what runs inside the browser SDK and the CLI.
+//
+// Spec: specs/x402-preflight.md
+
+import { createHash } from 'node:crypto';
+import { ed25519 } from '@noble/curves/ed25519.js';
+import bs58 from 'bs58';
+
+/** Body profile emitted by this module. Bump on a breaking body change. */
+export const PREFLIGHT_SPEC = 'x402-preflight/1';
+
+/**
+ * Envelope version, and the domain separator mixed into the signed bytes.
+ * Domain separation is what stops a preflight signature from ever being
+ * replayable as an agent-manifest signature or any other three.ws statement
+ * signed by the same attester identity.
+ */
+export const PREFLIGHT_ENVELOPE_VERSION = 'threews.x402.preflight.v1';
+
+/** Default validity. Short enough that a stale copy cannot outlive an incident. */
+export const PREFLIGHT_TTL_SECONDS = 60;
+
+/** Hard ceiling on requested TTL: an hour-long assurance is not an assurance. */
+export const PREFLIGHT_MAX_TTL_SECONDS = 300;
+
+/**
+ * Machine-readable reasons an endpoint is not payable. Clients switch on these,
+ * so they are part of the wire contract: add, never repurpose.
+ *
+ * `sponsor_below_floor` is the one that produced this whole module. It means the
+ * SELLER's fee wallet cannot pay network fees, so nothing the buyer does can
+ * make the payment settle.
+ */
+export const PREFLIGHT_REASONS = Object.freeze([
+ 'ok',
+ 'sponsor_below_floor',
+ 'settlement_degraded',
+ 'facilitator_unreachable',
+ 'network_not_configured',
+ 'rail_unavailable',
+ 'unknown',
+]);
+
+const REASON_SET = new Set(PREFLIGHT_REASONS);
+
+/**
+ * Back-off hint per reason, in seconds. A dry sponsor needs a human with a
+ * wallet, so the hint is minutes; a degraded rail usually clears itself, so the
+ * hint is short enough to retry within the same task.
+ */
+const RETRY_AFTER = Object.freeze({
+ sponsor_below_floor: 300,
+ settlement_degraded: 60,
+ facilitator_unreachable: 60,
+ rail_unavailable: 60,
+ network_not_configured: 3600,
+ unknown: 30,
+});
+
+// Deterministic JSON: keys sorted recursively, undefined dropped. The signer and
+// every verifier must hash byte-identical input regardless of property insertion
+// order, so this is the one representation that may be hashed.
+function canonicalize(value) {
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;
+ if (value && typeof value === 'object') {
+ const keys = Object.keys(value)
+ .filter((k) => value[k] !== undefined)
+ .sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`;
+ }
+ return JSON.stringify(value === undefined ? null : value);
+}
+
+/** sha256 of a string as lowercase hex. */
+export function sha256Hex(input) {
+ return createHash('sha256').update(Buffer.from(String(input), 'utf8')).digest('hex');
+}
+
+/**
+ * Statistical confidence in a measured rate, on 0..1.
+ *
+ * A settle rate is only as trustworthy as the sample behind it, and the failure
+ * this guards against is real: a ring that settled 3 of 3 payments overnight
+ * reports 100%, which reads identically to a proven rail. Confidence rises with
+ * the sample and is capped below 1 because no finite sample proves the next
+ * payment settles.
+ *
+ * Deliberately a simple saturating curve rather than a Wilson interval: the
+ * number is a hint for routing, and a hint an operator can predict in their head
+ * beats a statistically tighter one nobody can sanity-check.
+ * @param {number} attempts
+ * @returns {number} 0..0.99, two decimals
+ */
+export function sampleConfidence(attempts) {
+ const n = Math.max(0, Math.floor(Number(attempts) || 0));
+ if (n <= 0) return 0;
+ // 20 attempts is the same threshold the settle sensor uses before it will
+ // judge a window at all, and lands here at ~0.66.
+ return Math.round(Math.min(0.99, n / (n + 10)) * 100) / 100;
+}
+
+/**
+ * Decide one network's payability from the platform's own measurements.
+ *
+ * Every branch that cannot prove payability returns `unknown` rather than
+ * guessing, and `payable: true` is only ever returned on positive evidence. That
+ * asymmetry is the whole point: a buyer acting on this makes an irreversible
+ * transfer, so the expensive mistake is a false `true`, never a false `unknown`.
+ *
+ * Pure. The caller supplies every input; nothing is read from the environment.
+ *
+ * @param {object} p
+ * @param {boolean} p.configured is this network wired up to accept at all
+ * @param {boolean|null} [p.sponsorBelowFloor] null when unmeasured
+ * @param {'ok'|'degraded'|'down'|'unknown'|null} [p.settleStatus]
+ * @param {number|null} [p.settleRate] 0..1, null when unmeasured
+ * @param {number} [p.attempts] sample behind settleRate
+ * @param {number} [p.windowHours]
+ * @param {boolean} [p.facilitatorReachable]
+ * @returns {{ payable: boolean|'unknown', reason: string, retry_after: number|null,
+ * settle: { rate: number|null, attempts: number, window_hours: number|null, confidence: number } }}
+ */
+export function decideNetworkPayability({
+ configured,
+ sponsorBelowFloor = null,
+ settleStatus = null,
+ settleRate = null,
+ attempts = 0,
+ windowHours = null,
+ facilitatorReachable = true,
+}) {
+ const settle = {
+ rate: settleRate == null || !Number.isFinite(Number(settleRate)) ? null : Number(settleRate),
+ attempts: Math.max(0, Math.floor(Number(attempts) || 0)),
+ window_hours: windowHours == null ? null : Number(windowHours),
+ confidence: sampleConfidence(attempts),
+ };
+ const out = (payable, reason) => ({
+ payable,
+ reason,
+ retry_after: payable === true ? null : (RETRY_AFTER[reason] ?? RETRY_AFTER.unknown),
+ settle,
+ });
+
+ if (!configured) return out(false, 'network_not_configured');
+ // The seller's fee wallet is empty. Nothing the buyer does can fix this, which
+ // is exactly why it has to be said BEFORE the buyer signs anything.
+ if (sponsorBelowFloor === true) return out(false, 'sponsor_below_floor');
+ if (!facilitatorReachable) return out('unknown', 'facilitator_unreachable');
+ if (settleStatus === 'down') return out(false, 'settlement_degraded');
+ if (settleStatus === 'degraded') return out(false, 'settlement_degraded');
+ // Configured, nothing known to be broken, but nothing measured either: a
+ // quiet rail is not a proven one.
+ if (settleStatus === 'unknown' || settleStatus == null) return out('unknown', 'unknown');
+ return out(true, 'ok');
+}
+
+/**
+ * Assemble the report body. Networks are sorted by id so the canonical bytes do
+ * not depend on the order the caller happened to gather them in.
+ *
+ * @param {object} p
+ * @param {string} p.subject origin the report speaks for
+ * @param {Record<string, ReturnType<typeof decideNetworkPayability> & {asset?:string, pay_to?:string}>} p.networks
+ * @param {string} [p.issuedAt] ISO
+ * @param {number} [p.ttlSeconds]
+ * @param {object} [p.endpoint] optional per-route detail
+ * @returns {object}
+ */
+export function buildPreflightReport({ subject, networks, issuedAt, ttlSeconds, endpoint }) {
+ if (!subject) throw new Error('buildPreflightReport: subject is required');
+ const at = issuedAt || new Date().toISOString();
+ const ttl = Math.min(
+ PREFLIGHT_MAX_TTL_SECONDS,
+ Math.max(1, Math.floor(Number(ttlSeconds) || PREFLIGHT_TTL_SECONDS)),
+ );
+
+ /** @type {Record<string, object>} */
+ const sorted = {};
+ for (const key of Object.keys(networks || {}).sort()) {
+ const n = networks[key];
+ sorted[key] = {
+ payable: n.payable,
+ reason: REASON_SET.has(n.reason) ? n.reason : 'unknown',
+ retry_after: n.retry_after ?? null,
+ settle: n.settle,
+ ...(n.asset ? { asset: n.asset } : {}),
+ ...(n.pay_to ? { pay_to: n.pay_to } : {}),
+ };
+ }
+
+ // Alternates are computed here rather than left to the client so that every
+ // consumer (SDK, CLI, a registry relaying the envelope) agrees on the same
+ // fallback set, and so the set is inside the signature.
+ const payableIds = Object.keys(sorted).filter((k) => sorted[k].payable === true);
+ for (const key of Object.keys(sorted)) {
+ sorted[key].alternates = payableIds.filter((k) => k !== key);
+ }
+
+ const body = {
+ $schema: 'https://three.ws/schemas/x402-preflight/1.json',
+ spec: PREFLIGHT_SPEC,
+ subject: String(subject),
+ issued_at: at,
+ expires_at: new Date(new Date(at).getTime() + ttl * 1000).toISOString(),
+ networks: sorted,
+ payable_any: payableIds.length > 0,
+ };
+ if (endpoint) body.endpoint = endpoint;
+ return body;
+}
+
+/** The exact bytes run through ed25519, domain-separated by envelope version. */
+export function signingMessage(digest) {
+ return Buffer.from(`${PREFLIGHT_ENVELOPE_VERSION}:${digest}`, 'utf8');
+}
+
+/** Digest over the report plus the issuer and instant it was signed at. */
+export function reportDigest({ report, issuer, signedAt }) {
+ return sha256Hex(canonicalize({ report, issuer, signedAt }));
+}
+
+/**
+ * Sign a report with an ed25519 secret key (a Solana Keypair's 64-byte
+ * secretKey, or a raw 32-byte seed). Pure crypto: no DB, no network.
+ * @param {object} report from buildPreflightReport
+ * @param {Uint8Array} secretKey
+ * @param {{signedAt?: string}} [opts]
+ * @returns {object} the signed envelope
+ */
+export function signPreflight(report, secretKey, { signedAt } = {}) {
+ const seed = secretKey.slice(0, 32);
+ const issuer = bs58.encode(ed25519.getPublicKey(seed));
+ const at = signedAt || report.issued_at || new Date().toISOString();
+ const digest = reportDigest({ report, issuer, signedAt: at });
+ return {
+ spec: PREFLIGHT_ENVELOPE_VERSION,
+ report,
+ issuer,
+ signedAt: at,
+ digest,
+ algorithm: 'ed25519',
+ signature: bs58.encode(ed25519.sign(signingMessage(digest), seed)),
+ };
+}
+
+/**
+ * Verify a signed envelope. Pure and offline: this is what an outside party runs
+ * on bytes it fetched, and what the browser SDK runs before trusting a report.
+ *
+ * Expiry is checked as part of verification, not left to the caller. An expired
+ * attestation is not a valid one that happens to be old: treating it as valid is
+ * precisely the replay this format exists to prevent, and making it the caller's
+ * job would mean every consumer has to remember. `clockSkewMs` allows for honest
+ * clock drift between two machines without opening a replay window.
+ *
+ * @param {object} envelope
+ * @param {{issuer?: string, now?: number, clockSkewMs?: number, subject?: string}} [expect]
+ * @returns {{ valid: boolean, reason: string, issuer: string|null, digest: string|null, expired: boolean }}
+ */
+export function verifyPreflight(envelope, { issuer: expectedIssuer, now, clockSkewMs = 30_000, subject } = {}) {
+ const fail = (reason, extra = {}) => ({
+ valid: false,
+ reason,
+ issuer: envelope?.issuer || null,
+ digest: null,
+ expired: false,
+ ...extra,
+ });
+
+ if (!envelope || typeof envelope !== 'object' || !envelope.report) return fail('not_an_envelope');
+ if (envelope.spec !== PREFLIGHT_ENVELOPE_VERSION) return fail('unsupported_envelope_version');
+ if (envelope.algorithm && envelope.algorithm !== 'ed25519') return fail('unsupported_algorithm');
+ if (!envelope.issuer || !envelope.signature || !envelope.signedAt) return fail('unsigned');
+ if (envelope.report.spec !== PREFLIGHT_SPEC) return fail('unsupported_report_spec');
+
+ const digest = reportDigest({
+ report: envelope.report,
+ issuer: envelope.issuer,
+ signedAt: envelope.signedAt,
+ });
+ if (envelope.digest && String(envelope.digest).toLowerCase() !== digest) {
+ return { ...fail('digest_mismatch'), digest };
+ }
+ if (expectedIssuer && expectedIssuer !== envelope.issuer) {
+ return { ...fail('issuer_mismatch'), digest };
+ }
+ // A report is only about the origin it names. Without this check a valid
+ // attestation for one seller could be presented as covering another.
+ if (subject && normalizeOrigin(subject) !== normalizeOrigin(envelope.report.subject)) {
+ return { ...fail('subject_mismatch'), digest };
+ }
+
+ let ok = false;
+ try {
+ ok = ed25519.verify(bs58.decode(envelope.signature), signingMessage(digest), bs58.decode(envelope.issuer));
+ } catch {
+ return { ...fail('malformed_signature'), digest };
+ }
+ if (!ok) return { ...fail('bad_signature'), digest };
+
+ const at = typeof now === 'number' ? now : Date.now();
+ const expiresAt = Date.parse(envelope.report.expires_at || '');
+ if (!Number.isFinite(expiresAt)) return { ...fail('no_expiry'), digest };
+ if (at - clockSkewMs > expiresAt) {
+ return { valid: false, reason: 'expired', issuer: envelope.issuer, digest, expired: true };
+ }
+ // A report stamped in the future is either a broken clock or a forgery
+ // attempt to extend an assurance window. Neither is safe to act on.
+ const issuedAt = Date.parse(envelope.report.issued_at || '');
+ if (Number.isFinite(issuedAt) && issuedAt - clockSkewMs > at) {
+ return { ...fail('issued_in_future'), digest };
+ }
+
+ return { valid: true, reason: 'ok', issuer: envelope.issuer, digest, expired: false };
+}
+
+/** Compare origins without being defeated by a trailing slash or a case change. */
+export function normalizeOrigin(value) {
+ try {
+ const u = new URL(String(value));
+ return `${u.protocol}//${u.host}`.toLowerCase();
+ } catch {
+ return String(value || '').trim().replace(/\/+$/, '').toLowerCase();
+ }
+}
+
+/**
+ * Read one network's verdict out of a VERIFIED envelope.
+ *
+ * Takes the envelope rather than the report so a caller cannot skip
+ * verification by reaching for the body directly, and returns `unknown` for a
+ * network the report does not mention rather than treating silence as a no.
+ * @param {object} envelope
+ * @param {string} network e.g. 'solana:mainnet'
+ * @returns {{ payable: boolean|'unknown', reason: string, retry_after: number|null, alternates: string[] }}
+ */
+export function networkVerdict(envelope, network) {
+ const n = envelope?.report?.networks?.[network];
+ if (!n) return { payable: 'unknown', reason: 'network_not_configured', retry_after: null, alternates: [] };
+ return {
+ payable: n.payable,
+ reason: n.reason,
+ retry_after: n.retry_after ?? null,
+ alternates: Array.isArray(n.alternates) ? n.alternates : [],
+ };
+}
diff --git a/api/x402/preflight.js b/api/x402/preflight.js
new file mode 100644
index 000000000..35104a45c
--- /dev/null
+++ b/api/x402/preflight.js
@@ -0,0 +1,230 @@
+// GET /api/x402/preflight — signed proof that this seller can settle right now.
+// Also served at /.well-known/x402-preflight (see vercel.json).
+//
+// GET /api/x402/preflight all networks
+// GET /api/x402/preflight?network=solana:mainnet one network
+// GET /api/x402/preflight?endpoint=/api/x402/echo plus that route's price
+// GET /api/x402/preflight?ttl=30 shorter validity
+//
+// This is the I/O half of x402 Preflight; the format, the signing and the
+// verification are pure and live in api/_lib/x402/preflight.js. See
+// specs/x402-preflight.md for the wire contract and packages/x402-preflight for
+// the client that consumes it.
+//
+// Every field is measured, never declared:
+// * settle rate + window + sample come from gatherX402SettleHealth(), the same
+// sensor healthz uses, reading real rows out of x402_autonomous_log.
+// * sponsor state comes from the live floor guard in self-facilitator.js.
+// * network configuration comes from the same env the 402 challenge builder
+// reads, so preflight cannot claim an accept the challenge would not offer.
+//
+// It is deliberately CHEAP and public: no auth, no payment, aggressively
+// cacheable for its own lifetime. An assurance endpoint that is expensive or
+// gated is one nobody calls, and one nobody calls prevents nothing. The whole
+// value is that a client can afford to ask before every purchase.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { loadAttesterKeypair } from '../_lib/attest-event.js';
+import { gatherX402SettleHealth } from '../_lib/ops/x402-settle-health.js';
+import {
+ SPONSOR_SOL_FLOOR_LAMPORTS,
+ sponsorKnownBelowFloor,
+ refreshSponsorFloorState,
+} from '../_lib/x402/self-facilitator.js';
+import {
+ buildPreflightReport,
+ decideNetworkPayability,
+ signPreflight,
+ PREFLIGHT_TTL_SECONDS,
+ PREFLIGHT_MAX_TTL_SECONDS,
+ PREFLIGHT_SPEC,
+} from '../_lib/x402/preflight.js';
+
+// Network ids are CAIP-2, the same identifiers the 402 challenge uses, so a
+// client can match a preflight verdict to an accept without a translation table.
+const SOLANA = 'solana:mainnet';
+const BASE = 'eip155:8453';
+
+// USDC, the only asset the platform settles. Named in the report so a client can
+// check it is being quoted the asset it holds before it prepares a transfer.
+const USDC_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+
+// One signed report is reused for its whole validity window rather than re-signed
+// per request. Signing is cheap but the sensor behind it runs a DB aggregation,
+// and a fleet of agents preflighting every purchase would otherwise turn an
+// assurance check into its own load problem. The cache can never outlive the
+// attestation because both expire off the same instant.
+let _cache = null;
+
+function cacheKey(ttl, endpoint) {
+ return `${ttl}|${endpoint || ''}`;
+}
+
+/**
+ * Read the live settle sensor, degrading to `unknown` rather than throwing.
+ * A preflight that cannot measure must say so; it must never assume health.
+ */
+async function readSettle() {
+ try {
+ const h = await gatherX402SettleHealth();
+ const m = h?.metrics || {};
+ return {
+ status: h?.status ?? 'unknown',
+ rate: typeof m.rate === 'number' ? m.rate : null,
+ attempts: Number(m.attempts) || 0,
+ windowHours: Number(m.windowHours) || null,
+ cause: m.cause ?? null,
+ floorSignals: Number(m.floorSignals) || 0,
+ };
+ } catch {
+ return { status: 'unknown', rate: null, attempts: 0, windowHours: null, cause: null, floorSignals: 0 };
+ }
+}
+
+/**
+ * Is the Solana fee sponsor under its floor?
+ *
+ * Two independent sources, because on 2026-08-28 the first one alone was wrong
+ * for three hours: the cached floor guard is only written by a balance read, and
+ * the RPC lanes that answer balance reads were all over quota. The settle
+ * sensor's own diagnosis is the second opinion, derived from failures the chain
+ * already returned, and it is available exactly when the balance read is not.
+ * Either one saying "below floor" is enough to withhold a payable verdict.
+ * @param {{cause: string|null, floorSignals: number}} settle
+ * @returns {boolean|null} null when neither source can tell
+ */
+function sponsorBelowFloor(settle) {
+ // Warm the cached guard without blocking: it refreshes at most once per
+ // balance-cache window and swallows RPC errors by design.
+ try {
+ refreshSponsorFloorState();
+ } catch {
+ /* the guard is advisory; an unreadable balance must not fail preflight */
+ }
+ if (sponsorKnownBelowFloor()) return true;
+ if (settle.cause === 'sponsor_floor' || settle.floorSignals > 0) return true;
+ // Not proven below. Only claim "above floor" when the platform is actually
+ // configured to sponsor at all; otherwise the answer is genuinely unknown.
+ return env.X402_FEE_PAYER_SOLANA ? false : null;
+}
+
+async function buildEnvelope({ ttl, endpointPath, origin }) {
+ const settle = await readSettle();
+ const belowFloor = sponsorBelowFloor(settle);
+
+ const solanaConfigured = !!(
+ (env.X402_PAY_TO_SOLANA || process.env.X402_PAY_TO) && env.X402_FEE_PAYER_SOLANA
+ );
+ const baseConfigured = !!process.env.X402_PAY_TO_BASE;
+
+ /** @type {Record<string, object>} */
+ const networks = {};
+ if (solanaConfigured || env.X402_PAY_TO_SOLANA) {
+ networks[SOLANA] = {
+ ...decideNetworkPayability({
+ configured: solanaConfigured,
+ sponsorBelowFloor: belowFloor,
+ settleStatus: settle.status,
+ settleRate: settle.rate,
+ attempts: settle.attempts,
+ windowHours: settle.windowHours,
+ }),
+ asset: USDC_SOLANA,
+ pay_to: env.X402_PAY_TO_SOLANA || process.env.X402_PAY_TO || undefined,
+ };
+ }
+ if (baseConfigured) {
+ networks[BASE] = {
+ // Base settles through the buyer's own fee payment, so our Solana
+ // sponsor's balance says nothing about it. Passing the Solana floor in
+ // here would have marked Base unpayable for three hours on 2026-08-28
+ // for a reason that never applied to it.
+ ...decideNetworkPayability({
+ configured: true,
+ sponsorBelowFloor: null,
+ settleStatus: settle.status,
+ settleRate: settle.rate,
+ attempts: settle.attempts,
+ windowHours: settle.windowHours,
+ }),
+ asset: USDC_BASE,
+ pay_to: process.env.X402_PAY_TO_BASE,
+ };
+ }
+
+ const report = buildPreflightReport({
+ subject: origin,
+ networks,
+ ttlSeconds: ttl,
+ endpoint: endpointPath ? { path: endpointPath } : undefined,
+ });
+
+ const keypair = loadAttesterKeypair();
+ return signPreflight(report, keypair.secretKey);
+}
+
+export default wrap(async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, `https://${req.headers.host || 'three.ws'}`);
+ const ttl = Math.min(
+ PREFLIGHT_MAX_TTL_SECONDS,
+ Math.max(1, Number(url.searchParams.get('ttl')) || PREFLIGHT_TTL_SECONDS),
+ );
+ const network = url.searchParams.get('network');
+ const endpointPath = url.searchParams.get('endpoint');
+ const origin = `https://${req.headers.host || 'three.ws'}`;
+
+ const key = cacheKey(ttl, endpointPath);
+ const now = Date.now();
+ let envelope = null;
+ if (_cache && _cache.key === key && _cache.until > now) envelope = _cache.envelope;
+
+ if (!envelope) {
+ try {
+ envelope = await buildEnvelope({ ttl, endpointPath, origin });
+ } catch (err) {
+ // The attester key is the one hard dependency. Without it the honest
+ // answer is that no assurance is available, NOT an unsigned report a
+ // client might mistake for one. 503 so a client backs off and retries.
+ return json(res, 503, {
+ error: 'preflight_unavailable',
+ error_description:
+ 'This origin cannot sign a preflight attestation right now. An unsigned report ' +
+ 'is not an assurance, so none is returned.',
+ spec: PREFLIGHT_SPEC,
+ detail: err?.message || String(err),
+ }, { 'cache-control': 'no-store', 'retry-after': '60' });
+ }
+ // Expire the cache a beat BEFORE the attestation does, so a client can
+ // never be handed a copy that dies in flight.
+ _cache = { key, envelope, until: now + Math.max(1, ttl - 2) * 1000 };
+ }
+
+ if (network) {
+ const n = envelope.report.networks[network];
+ if (!n) {
+ return json(res, 404, {
+ error: 'network_not_offered',
+ error_description: `this origin does not offer ${network}`,
+ offered: Object.keys(envelope.report.networks),
+ }, { 'cache-control': 'no-store' });
+ }
+ }
+
+ // Cacheable for exactly as long as the attestation is valid and no longer.
+ // `must-revalidate` keeps a shared cache from serving it one second past
+ // expiry, which would hand a client an attestation that fails verification.
+ const remaining = Math.max(0, Math.floor((Date.parse(envelope.report.expires_at) - Date.now()) / 1000));
+ return json(res, 200, envelope, {
+ 'cache-control': `public, max-age=${remaining}, must-revalidate`,
+ 'x-preflight-spec': PREFLIGHT_SPEC,
+ 'x-preflight-expires': envelope.report.expires_at,
+ // Named so a reader of the raw response knows what the floor is measured
+ // against without having to find it in the source.
+ 'x-preflight-sponsor-floor-lamports': String(SPONSOR_SOL_FLOOR_LAMPORTS),
+ });
+});
diff --git a/packages/x402-preflight/LICENSE b/packages/x402-preflight/LICENSE
new file mode 100644
index 000000000..dff21b7f4
--- /dev/null
+++ b/packages/x402-preflight/LICENSE
@@ -0,0 +1,20 @@
+Copyright 2026 nirholas
+
+All rights reserved.
+
+This software is proprietary and may not be used, copied, modified, distributed,
+translated, or made available to any third party without the express written
+permission of the copyright owner.
+
+No rights are granted by implication, estoppel, or otherwise. Use of this
+software is subject to the terms of a separate license agreement with the
+copyright owner.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
+
+IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,
+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/packages/x402-preflight/README.md b/packages/x402-preflight/README.md
new file mode 100644
index 000000000..483733f03
--- /dev/null
+++ b/packages/x402-preflight/README.md
@@ -0,0 +1,216 @@
+# @three-ws/x402-preflight
+
+**Ask an x402 seller whether it can actually settle, before you sign anything.**
+
+x402 tells your agent what a resource *costs*. It says nothing about whether the
+seller can currently *settle* what it charges. Those look identical right up
+until your agent has already signed, and the difference is paid for by the buyer:
+a burned signature, a consumed blockhash, a `502`, and no service.
+
+```bash
+npm i @three-ws/x402-preflight
+```
+
+```js
+import { guardedFetch } from '@three-ws/x402-preflight';
+
+// A drop-in fetch that will not spend your money on a seller who cannot deliver.
+const fetch402 = guardedFetch({ prefer: ['solana:mainnet'] });
+
+const res = await fetch402('https://three.ws/api/x402/echo');
+```
+
+That's it. Before the request that could trigger payment, the seller's signed
+payability attestation is fetched once (cached for its own lifetime), verified
+offline, and either the request goes through on a rail that works, or it throws
+before your agent signs anything.
+
+---
+
+## Why this exists
+
+On 2026-08-28, three.ws was the broken seller. Its fee sponsor held 0.000899107
+SOL against a 0.02 SOL floor, so every transaction it fee-paid died at simulation
+with `InsufficientFundsForRent`. **95 payment attempts, 0 settled, three hours.**
+
+Every one of those buyers could have known before signing, from state the server
+already had. So we published the state, signed it, and wrote the client that
+reads it.
+
+## What you get
+
+### `preflight(origin, opts?)`
+
+Fetch and verify a seller's attestation. Throws `PreflightError` on transport
+failure, a malformed body, or any check that does not pass.
+
+```js
+import { preflight } from '@three-ws/x402-preflight';
+
+const { report } = await preflight('https://three.ws');
+console.log(report.networks['solana:mainnet']);
+// { payable: false, reason: 'sponsor_below_floor', retry_after: 300,
+// settle: { rate: 0, attempts: 95, window_hours: 3, confidence: 0.9 },
+// alternates: ['eip155:8453'] }
+```
+
+### `assertPayable(origin, network, opts?)`
+
+Throw unless that rail can settle right now. The error carries everything you
+need to recover without another round trip.
+
+```js
+import { assertPayable, PreflightError } from '@three-ws/x402-preflight';
+
+try {
+ await assertPayable('https://three.ws', 'solana:mainnet');
+} catch (err) {
+ if (err instanceof PreflightError) {
+ err.reason; // 'sponsor_below_floor'
+ err.alternates; // ['eip155:8453'] <- pay here instead
+ err.retryAfter; // 300 <- or come back in 5 minutes
+ }
+}
+```
+
+`unknown` counts as **not** payable. Your agent is about to make an irreversible
+transfer, so the safe reading of "I cannot tell" is to not pay. Pass
+`allowUnknown: true` to take the other trade-off, which is a decision worth
+writing down at the call site.
+
+### `guardedFetch(opts?)`
+
+A `fetch` you can pass anywhere a `fetch` is accepted.
+
+```js
+const fetch402 = guardedFetch({
+ prefer: ['solana:mainnet', 'eip155:8453'],
+ onSkip: (info) => log.warn('seller unpayable', info),
+});
+```
+
+- Preflights each origin once, cached for the attestation's lifetime.
+- Picks your preferred rail when it works, the best alternative when it doesn't.
+- Sets `x-preflight-network` so a seller can answer its `402` with only the
+ accept you can actually pay, removing a negotiation round trip. Sellers that
+ ignore it are unaffected.
+- **Passes through origins that don't publish an attestation.** That's the entire
+ existing x402 ecosystem, and refusing it would make this unusable on day one.
+ Set `requirePreflight: true` to fail closed instead.
+
+### `verifyPreflight(envelope, expect?)`
+
+The trust boundary, exported on its own from `@three-ws/x402-preflight/verify`.
+No I/O, no Node built-ins: it runs unchanged in a browser, a service worker and
+on an edge runtime.
+
+```js
+import { verifyPreflight } from '@three-ws/x402-preflight/verify';
+
+verifyPreflight(envelope, { subject: 'https://three.ws', issuer: KNOWN_KEY });
+// { valid: true, reason: 'ok', issuer: '...', digest: '...', expired: false }
+```
+
+It checks all of this, so you cannot forget one:
+
+- the ed25519 signature against the issuer key in the envelope
+- the digest, re-derived from the report bytes, so a body edited after signing is
+ caught before any curve arithmetic runs
+- **expiry**, because an expired attestation is not a valid one that happens to
+ be old (see below)
+- that the report was not stamped in the future
+- that `subject` is the origin you asked about, when you say which
+
+It never throws. A hostile seller must not be able to crash a paying agent's
+loop, so every input returns a verdict.
+
+## The CLI
+
+```bash
+npx @three-ws/x402-preflight https://three.ws
+```
+
+```
+https://three.ws signed by 8k2n…Wq4
+ attestation verified, valid for another 47s
+
+ NOT PAYABLE solana:mainnet
+ reason sponsor_below_floor
+ settle 0.0% of 95 attempts over 3h (confidence 0.9)
+ retry after 300s
+ instead eip155:8453
+
+ PAYABLE eip155:8453
+ reason ok
+ settle 98.0% of 412 attempts over 3h (confidence 0.98)
+```
+
+Exit codes are the point, so it composes:
+
+| Code | Meaning |
+|---|---|
+| `0` | Payable |
+| `1` | Verified, and **not** payable |
+| `2` | Could not be verified (no attestation, bad signature, expired, timeout) |
+
+```bash
+npx @three-ws/x402-preflight https://three.ws --network solana:mainnet && ./pay.sh
+```
+
+`--json` prints the raw envelope for `jq`. `--issuer <pubkey>` pins the signer
+you trust. `--timeout <ms>` bounds a slow seller.
+
+## Why the attestation is signed
+
+An unsigned health endpoint is a courtesy. A signed, time-bounded one is
+evidence, and three properties follow that a status page cannot give you:
+
+**Attributable.** A client that paid after reading `payable: true` holds a
+statement signed by the seller's own key saying the seller believed it could
+settle, at a stated instant. Between autonomous agents transacting with
+strangers, that is the difference between "it broke" and "you said it would
+work".
+
+**Unreplayable.** Every attestation carries `expires_at`, and verification
+*rejects* an expired one. A seller cannot serve a cached healthy attestation
+through an outage, and an attacker who captures one cannot replay it later.
+
+**Relayable.** Because it verifies offline against a public key, a registry or an
+index can cache and forward attestations without becoming trusted. Discovery
+services can rank sellers by measured settleability instead of by
+self-description.
+
+## Honesty rules the format enforces
+
+- `payable` is **three-valued**: `true`, `false`, `"unknown"`. A seller that
+ cannot determine its own state must say `"unknown"`, never `true`. Every
+ failure path degrades to `"unknown"` rather than to a lie.
+- Every rate carries its window and sample size. A seller that settled 3 of 3
+ payments overnight reports 100%, which is indistinguishable from a proven rail
+ unless `attempts` travels with it, so `confidence` is derived from the sample
+ and capped below `1`.
+
+## What it does not promise
+
+- **Not a guarantee.** It is the seller's signed, timestamped best assessment. A
+ rail can fail in the seconds after it signs.
+- **Not a reputation system.** It reports current settleability, not honesty or
+ history. It is an input a reputation system could use.
+- **It does not stop a seller lying.** It makes lying attributable.
+
+## Serving one yourself
+
+The wire format is public and unencumbered. Any x402 seller can publish an
+attestation and any client can verify it; nothing routes through three.ws.
+
+Full contract, including the canonicalization rules and the normative
+verification steps: [specs/x402-preflight.md][spec].
+
+If you measure nothing yet, report `"unknown"`. That is honest and still useful:
+a client learns you are not claiming health you cannot back up.
+
+[spec]: https://github.com/nirholas/three.ws/blob/main/specs/x402-preflight.md
+
+## License
+
+Apache-2.0
diff --git a/packages/x402-preflight/bin/x402-preflight.mjs b/packages/x402-preflight/bin/x402-preflight.mjs
new file mode 100755
index 000000000..894b27c2c
--- /dev/null
+++ b/packages/x402-preflight/bin/x402-preflight.mjs
@@ -0,0 +1,117 @@
+#!/usr/bin/env node
+// x402-preflight — ask any x402 seller whether it can settle, from a terminal.
+//
+// npx @three-ws/x402-preflight https://three.ws
+// npx @three-ws/x402-preflight https://three.ws --network solana:mainnet
+// npx @three-ws/x402-preflight https://three.ws --json
+// npx @three-ws/x402-preflight https://three.ws --issuer <pubkey>
+//
+// Exit codes are the point of the tool, so it composes in a shell and in CI:
+// 0 payable (on the requested network, or on any network)
+// 1 verified, and NOT payable
+// 2 could not be verified (no attestation, bad signature, expired, timeout)
+//
+// That means `x402-preflight $URL && pay` is a correct one-liner, and a
+// monitoring job can alert on exit 1 without parsing anything.
+
+import { preflight, networkVerdict, payableNetworks, PreflightError } from '../src/index.js';
+
+const argv = process.argv.slice(2);
+// Flags that take a value, so the positional scan below cannot mistake a flag's
+// argument for the origin.
+const VALUED = new Set(['network', 'issuer', 'timeout']);
+const flag = (name) => {
+ const i = argv.indexOf(`--${name}`);
+ return i >= 0 ? argv[i + 1] : undefined;
+};
+const has = (name) => argv.includes(`--${name}`);
+
+let origin;
+for (let i = 0; i < argv.length; i += 1) {
+ const a = argv[i];
+ if (a.startsWith('--')) {
+ if (VALUED.has(a.slice(2))) i += 1;
+ continue;
+ }
+ origin = a;
+ break;
+}
+const asJson = has('json');
+const network = flag('network');
+const issuer = flag('issuer');
+const timeoutMs = Number(flag('timeout')) || 5000;
+
+if (!origin || has('help') || has('h')) {
+ process.stdout.write(
+ `x402-preflight — can this seller actually settle?\n\n` +
+ ` x402-preflight <origin> [--network <caip2>] [--issuer <pubkey>]\n` +
+ ` [--timeout <ms>] [--json]\n\n` +
+ `Exit codes: 0 payable, 1 not payable, 2 unverifiable.\n\n` +
+ `Examples:\n` +
+ ` x402-preflight https://three.ws\n` +
+ ` x402-preflight https://three.ws --network solana:mainnet && echo "safe to pay"\n`,
+ );
+ process.exit(origin ? 0 : 2);
+}
+
+// ANSI only when a human is looking. Piped output stays clean for grep and jq.
+const tty = process.stdout.isTTY && !asJson;
+const ESC = '\u001b[';
+const c = (code, s) => (tty ? `${ESC}${code}m${s}${ESC}0m` : s);
+const green = (s) => c('32', s);
+const red = (s) => c('31', s);
+const yellow = (s) => c('33', s);
+const dim = (s) => c('2', s);
+
+function mark(payable) {
+ if (payable === true) return green('PAYABLE');
+ if (payable === false) return red('NOT PAYABLE');
+ return yellow('UNKNOWN');
+}
+
+function describeSettle(s) {
+ if (!s || s.rate == null) return dim('no settle sample in window');
+ const pct = (s.rate * 100).toFixed(1);
+ return `${pct}% of ${s.attempts} attempts over ${s.window_hours}h ` + dim(`(confidence ${s.confidence})`);
+}
+
+try {
+ const { envelope, report } = await preflight(origin, { issuer, timeoutMs, cache: false });
+
+ if (asJson) {
+ process.stdout.write(JSON.stringify(envelope, null, 2) + '\n');
+ } else {
+ const secondsLeft = Math.max(0, Math.round((Date.parse(report.expires_at) - Date.now()) / 1000));
+ process.stdout.write(`\n${report.subject} ${dim(`signed by ${envelope.issuer}`)}\n`);
+ process.stdout.write(dim(` attestation verified, valid for another ${secondsLeft}s\n\n`));
+ for (const [id, n] of Object.entries(report.networks)) {
+ process.stdout.write(` ${mark(n.payable).padEnd(tty ? 20 : 11)} ${id}\n`);
+ process.stdout.write(` reason ${n.reason}\n`);
+ process.stdout.write(` settle ${describeSettle(n.settle)}\n`);
+ if (n.payable !== true && n.retry_after) {
+ process.stdout.write(` retry after ${n.retry_after}s\n`);
+ }
+ if (n.payable !== true && n.alternates?.length) {
+ process.stdout.write(` instead ${green(n.alternates.join(', '))}\n`);
+ }
+ process.stdout.write('\n');
+ }
+ }
+
+ if (network) {
+ const v = networkVerdict(envelope, network);
+ process.exit(v.payable === true ? 0 : 1);
+ }
+ process.exit(payableNetworks(envelope).length > 0 ? 0 : 1);
+} catch (err) {
+ const info = err instanceof PreflightError ? { code: err.code, reason: err.reason } : { code: 'error' };
+ if (asJson) {
+ process.stdout.write(JSON.stringify({ error: info.code, reason: info.reason, message: err.message }, null, 2) + '\n');
+ } else {
+ process.stderr.write(`${red('unverifiable')} ${origin}\n ${err.message}\n`);
+ if (info.code === 'not_supported') {
+ process.stderr.write(dim(` This origin does not publish /.well-known/x402-preflight.\n`));
+ }
+ }
+ process.exit(2);
+}
diff --git a/packages/x402-preflight/package.json b/packages/x402-preflight/package.json
new file mode 100644
index 000000000..6e03ddde4
--- /dev/null
+++ b/packages/x402-preflight/package.json
@@ -0,0 +1,67 @@
+{
+ "name": "@three-ws/x402-preflight",
+ "version": "0.1.0",
+ "description": "Ask an x402 seller whether it can actually settle, before you sign anything. Fetches and verifies a signed, time-bounded payability attestation, then routes you to a rail that works. The missing reliability layer for agent payments.",
+ "type": "module",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "exports": {
+ ".": {
+ "import": "./src/index.js",
+ "default": "./src/index.js"
+ },
+ "./verify": {
+ "import": "./src/verify.js",
+ "default": "./src/verify.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "bin": {
+ "x402-preflight": "./bin/x402-preflight.mjs"
+ },
+ "files": [
+ "src",
+ "bin",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "test": "node --test test/*.test.js"
+ },
+ "keywords": [
+ "x402",
+ "agent-payments",
+ "micropayments",
+ "preflight",
+ "attestation",
+ "ed25519",
+ "solana",
+ "base",
+ "usdc",
+ "agent",
+ "reliability",
+ "three.ws"
+ ],
+ "author": "nirholas <[email protected]>",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws/preflight",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/x402-preflight"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "dependencies": {
+ "@noble/curves": "^2.2.0",
+ "@noble/hashes": "^1.8.0",
+ "bs58": "^6.0.0"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/packages/x402-preflight/src/index.js b/packages/x402-preflight/src/index.js
new file mode 100644
index 000000000..5f74f9a8d
--- /dev/null
+++ b/packages/x402-preflight/src/index.js
@@ -0,0 +1,295 @@
+// @three-ws/x402-preflight — ask an x402 seller whether it can settle, before
+// you sign anything.
+//
+// x402 tells you what a resource COSTS. It does not tell you whether the seller
+// can currently complete the transaction it is charging for. Those look
+// identical until you have already signed, and the difference is paid for by the
+// buyer: a burned signature, a consumed blockhash, a 502, and no service.
+//
+// This is the client half of x402 Preflight. It fetches a seller's signed
+// attestation, verifies it offline, and gives you three levels of use depending
+// on how much control you want:
+//
+// preflight(origin) fetch + verify, get the verdict yourself
+// assertPayable(origin, net) throw a typed error if that rail cannot settle
+// guardedFetch() a drop-in fetch that refuses unpayable sellers
+// and re-routes to a rail that works
+//
+// Nothing here trusts the network. Every response is verified against the
+// issuer's key, checked for expiry, and pinned to the origin you asked about
+// before a single field is read.
+
+export {
+ verifyPreflight,
+ networkVerdict,
+ payableNetworks,
+ normalizeOrigin,
+ PREFLIGHT_SPEC,
+ PREFLIGHT_ENVELOPE_VERSION,
+ DEFAULT_CLOCK_SKEW_MS,
+} from './verify.js';
+
+import { verifyPreflight, networkVerdict, payableNetworks, normalizeOrigin } from './verify.js';
+
+/** Where a compliant seller publishes its attestation. */
+export const PREFLIGHT_WELL_KNOWN = '/.well-known/x402-preflight';
+
+/**
+ * A seller could not be shown to be able to settle. Carries the machine reason,
+ * the back-off the seller asked for, and the rails that WOULD work, so a caller
+ * can recover without re-fetching anything.
+ */
+export class PreflightError extends Error {
+ /**
+ * @param {string} message
+ * @param {{ code: string, reason?: string, retryAfter?: number|null,
+ * alternates?: string[], origin?: string, network?: string }} info
+ */
+ constructor(message, info) {
+ super(message);
+ this.name = 'PreflightError';
+ this.code = info.code;
+ this.reason = info.reason ?? null;
+ this.retryAfter = info.retryAfter ?? null;
+ this.alternates = info.alternates ?? [];
+ this.origin = info.origin ?? null;
+ this.network = info.network ?? null;
+ }
+}
+
+// Attestations are short-lived and self-describing, so the cache key is the
+// origin and the eviction time is the attestation's own expiry. Nothing is ever
+// served past that instant, which means the cache cannot do what the format
+// exists to prevent.
+const _cache = new Map();
+
+/** Drop every cached attestation. Useful in tests and after a network change. */
+export function clearPreflightCache() {
+ _cache.clear();
+}
+
+function cached(origin, now) {
+ const hit = _cache.get(origin);
+ if (!hit) return null;
+ if (hit.expiresAt <= now) {
+ _cache.delete(origin);
+ return null;
+ }
+ return hit.envelope;
+}
+
+/**
+ * Fetch and verify a seller's preflight attestation.
+ *
+ * @param {string} origin seller origin, e.g. 'https://three.ws'
+ * @param {object} [opts]
+ * @param {string} [opts.issuer] pin the signer's public key you trust
+ * @param {number} [opts.timeoutMs] default 5000
+ * @param {boolean} [opts.cache] default true
+ * @param {typeof fetch} [opts.fetch] inject a fetch (tests, proxies, edge)
+ * @param {number} [opts.now] injected clock, for tests
+ * @returns {Promise<{ envelope: object, verification: object, report: object }>}
+ * @throws {PreflightError} on transport failure, a malformed body, or a
+ * signature/expiry/subject check that does not pass
+ */
+export async function preflight(origin, opts = {}) {
+ const {
+ issuer,
+ timeoutMs = 5000,
+ cache = true,
+ fetch: fetchImpl = globalThis.fetch,
+ now = Date.now(),
+ } = opts;
+
+ if (typeof fetchImpl !== 'function') {
+ throw new PreflightError('no fetch implementation available; pass opts.fetch', { code: 'no_fetch', origin });
+ }
+ const base = normalizeOrigin(origin);
+ if (!base.startsWith('http')) {
+ throw new PreflightError(`not an origin: ${origin}`, { code: 'bad_origin', origin });
+ }
+
+ if (cache) {
+ const hit = cached(base, now);
+ if (hit) return { envelope: hit, verification: { valid: true, reason: 'cached' }, report: hit.report };
+ }
+
+ // A hung seller must not hang the buyer. Every request is deadlined, and the
+ // abort is surfaced as its own code so a caller can tell "slow" from "broken".
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
+ let res;
+ try {
+ res = await fetchImpl(`${base}${PREFLIGHT_WELL_KNOWN}`, {
+ headers: { accept: 'application/json' },
+ signal: controller.signal,
+ });
+ } catch (err) {
+ const aborted = err?.name === 'AbortError';
+ throw new PreflightError(
+ aborted ? `preflight timed out after ${timeoutMs}ms` : `preflight request failed: ${err?.message || err}`,
+ { code: aborted ? 'timeout' : 'transport_error', origin: base },
+ );
+ } finally {
+ clearTimeout(timer);
+ }
+
+ if (!res.ok) {
+ // 503 is the documented "I cannot sign right now" answer, and it is a
+ // meaningful signal rather than an error to swallow: a seller that cannot
+ // attest is a seller you should not assume is fine.
+ const retryAfter = Number(res.headers?.get?.('retry-after')) || null;
+ throw new PreflightError(`seller returned HTTP ${res.status} for preflight`, {
+ code: res.status === 404 ? 'not_supported' : 'unavailable',
+ retryAfter,
+ origin: base,
+ });
+ }
+
+ let envelope;
+ try {
+ envelope = await res.json();
+ } catch {
+ throw new PreflightError('preflight response was not JSON', { code: 'malformed', origin: base });
+ }
+
+ const verification = verifyPreflight(envelope, { issuer, subject: base, now });
+ if (!verification.valid) {
+ throw new PreflightError(`preflight attestation did not verify: ${verification.reason}`, {
+ code: 'verification_failed',
+ reason: verification.reason,
+ origin: base,
+ });
+ }
+
+ if (cache) {
+ const expiresAt = Date.parse(envelope.report.expires_at);
+ if (Number.isFinite(expiresAt)) _cache.set(base, { envelope, expiresAt });
+ }
+ return { envelope, verification, report: envelope.report };
+}
+
+/**
+ * Throw unless the seller can settle on the given network right now.
+ *
+ * `unknown` is treated as NOT payable on purpose. The caller is about to make an
+ * irreversible transfer, so the safe reading of "I cannot tell" is to not pay.
+ * Pass `allowUnknown: true` to opt into the other trade-off explicitly, which is
+ * a decision worth writing down at the call site.
+ *
+ * @param {string} origin
+ * @param {string} network CAIP-2 id, e.g. 'solana:mainnet'
+ * @param {object} [opts] everything preflight() takes, plus allowUnknown
+ * @returns {Promise<{ verdict: object, envelope: object }>}
+ * @throws {PreflightError}
+ */
+export async function assertPayable(origin, network, opts = {}) {
+ const { envelope } = await preflight(origin, opts);
+ const verdict = networkVerdict(envelope, network);
+ const acceptable = verdict.payable === true || (opts.allowUnknown && verdict.payable === 'unknown');
+ if (!acceptable) {
+ throw new PreflightError(
+ `${origin} cannot settle on ${network} right now (${verdict.reason})` +
+ (verdict.alternates.length ? `; payable on ${verdict.alternates.join(', ')}` : ''),
+ {
+ code: 'not_payable',
+ reason: verdict.reason,
+ retryAfter: verdict.retry_after,
+ alternates: verdict.alternates,
+ origin,
+ network,
+ },
+ );
+ }
+ return { verdict, envelope };
+}
+
+/**
+ * Pick the rail to pay on: your preference when it works, otherwise the best
+ * alternative the seller attested to.
+ *
+ * Returns null when nothing is payable, rather than throwing, because "pay on
+ * nothing" is a routing outcome a scheduler handles, not an exception.
+ * @param {object} envelope a VERIFIED envelope
+ * @param {string[]} [prefer] your ranked network preference
+ * @returns {string|null}
+ */
+export function chooseNetwork(envelope, prefer = []) {
+ const payable = payableNetworks(envelope);
+ if (!payable.length) return null;
+ for (const p of prefer) if (payable.includes(p)) return p;
+ return payable[0];
+}
+
+/**
+ * A drop-in `fetch` that will not let you pay a seller who cannot settle.
+ *
+ * Wraps any fetch-shaped function. Before a request that could trigger payment,
+ * it preflights the origin once (cached for the attestation's lifetime) and
+ * refuses if no rail is payable. The check costs one small cacheable GET and
+ * saves a signature, a blockhash and a round trip every time a seller is down.
+ *
+ * Requests to origins that do not publish an attestation pass through
+ * unchanged: this is an enhancement to the ecosystem, not a gate on it, and
+ * refusing every non-adopting seller would make the SDK unusable on day one.
+ * Set `requirePreflight: true` when you would rather fail closed.
+ *
+ * @param {object} [opts]
+ * @param {typeof fetch} [opts.fetch]
+ * @param {string[]} [opts.prefer] ranked network preference
+ * @param {boolean} [opts.requirePreflight] fail closed on non-adopting sellers
+ * @param {string} [opts.issuer]
+ * @param {(info: object) => void} [opts.onSkip] called when a seller is refused
+ * @returns {typeof fetch}
+ */
+export function guardedFetch(opts = {}) {
+ const {
+ fetch: fetchImpl = globalThis.fetch,
+ prefer = ['solana:mainnet'],
+ requirePreflight = false,
+ issuer,
+ onSkip,
+ } = opts;
+
+ return async function guarded(input, init) {
+ const url = typeof input === 'string' ? input : input?.url || String(input);
+ let origin;
+ try {
+ origin = new URL(url).origin;
+ } catch {
+ return fetchImpl(input, init);
+ }
+
+ let envelope = null;
+ try {
+ ({ envelope } = await preflight(origin, { issuer, fetch: fetchImpl }));
+ } catch (err) {
+ // A seller that does not publish an attestation is the entire existing
+ // x402 ecosystem. Passing through is what makes adoption incremental.
+ if (!requirePreflight && (err.code === 'not_supported' || err.code === 'transport_error')) {
+ return fetchImpl(input, init);
+ }
+ throw err;
+ }
+
+ const chosen = chooseNetwork(envelope, prefer);
+ if (!chosen) {
+ const first = Object.values(envelope.report.networks || {})[0] || {};
+ onSkip?.({ origin, url, reason: first.reason || 'unknown', retryAfter: first.retry_after ?? null });
+ throw new PreflightError(`${origin} cannot settle on any network right now`, {
+ code: 'not_payable',
+ reason: first.reason || 'unknown',
+ retryAfter: first.retry_after ?? null,
+ alternates: [],
+ origin,
+ });
+ }
+
+ // Tell the seller which rail we intend to use. A server that reads this can
+ // answer its 402 with only the accept we can actually pay, which removes a
+ // negotiation round trip; one that ignores it is unaffected.
+ const headers = new Headers(init?.headers || (typeof input === 'object' ? input?.headers : undefined));
+ headers.set('x-preflight-network', chosen);
+ return fetchImpl(input, { ...init, headers });
+ };
+}
diff --git a/packages/x402-preflight/src/verify.js b/packages/x402-preflight/src/verify.js
new file mode 100644
index 000000000..169115329
--- /dev/null
+++ b/packages/x402-preflight/src/verify.js
@@ -0,0 +1,171 @@
+// Offline verification of an x402 Preflight attestation.
+//
+// This file is the trust boundary of the whole SDK, so it is kept small,
+// dependency-light and free of I/O. It runs unchanged in Node, in a browser, in
+// a service worker and on an edge runtime: nothing here touches the filesystem,
+// the network, or any Node built-in.
+//
+// Everything the format needs to be safe is enforced HERE rather than left to
+// the caller, because a verification step a caller can forget is one that will
+// be forgotten:
+//
+// * the signature must check out against the issuer key in the envelope
+// * the digest must match a re-derivation from the report bytes, so a report
+// edited after signing is caught even before the signature is examined
+// * the attestation must not be expired, and must not be stamped in the future
+// * the subject must be the origin you asked about, when you say which
+//
+// Spec: https://three.ws/docs/x402-preflight
+
+import { ed25519 } from '@noble/curves/ed25519.js';
+import { sha256 } from '@noble/hashes/sha2.js';
+import bs58 from 'bs58';
+
+/** Report profile this SDK understands. */
+export const PREFLIGHT_SPEC = 'x402-preflight/1';
+
+/** Envelope version, and the domain separator mixed into the signed bytes. */
+export const PREFLIGHT_ENVELOPE_VERSION = 'threews.x402.preflight.v1';
+
+/** Tolerated clock difference between the signer's machine and yours. */
+export const DEFAULT_CLOCK_SKEW_MS = 30_000;
+
+const enc = new TextEncoder();
+
+// Deterministic JSON, byte-identical to the signer's. Keys sorted recursively,
+// undefined dropped. Any divergence here breaks every signature, so this
+// function and its counterpart in the server are the same algorithm on purpose.
+function canonicalize(value) {
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;
+ if (value && typeof value === 'object') {
+ const keys = Object.keys(value)
+ .filter((k) => value[k] !== undefined)
+ .sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`;
+ }
+ return JSON.stringify(value === undefined ? null : value);
+}
+
+function toHex(bytes) {
+ let out = '';
+ for (const b of bytes) out += b.toString(16).padStart(2, '0');
+ return out;
+}
+
+/** sha256 as lowercase hex, with no Node dependency. */
+export function sha256Hex(input) {
+ return toHex(sha256(enc.encode(String(input))));
+}
+
+/** The exact bytes run through ed25519, domain-separated by envelope version. */
+export function signingMessage(digest) {
+ return enc.encode(`${PREFLIGHT_ENVELOPE_VERSION}:${digest}`);
+}
+
+/** Digest over the report plus the issuer and instant it was signed at. */
+export function reportDigest({ report, issuer, signedAt }) {
+ return sha256Hex(canonicalize({ report, issuer, signedAt }));
+}
+
+/** Compare origins without being defeated by a trailing slash or a case change. */
+export function normalizeOrigin(value) {
+ try {
+ const u = new URL(String(value));
+ return `${u.protocol}//${u.host}`.toLowerCase();
+ } catch {
+ return String(value || '').trim().replace(/\/+$/, '').toLowerCase();
+ }
+}
+
+/**
+ * Verify a signed preflight envelope. Pure, offline, and total: it returns a
+ * verdict for every input rather than throwing, so a malformed response from a
+ * hostile server cannot crash a paying agent's loop.
+ *
+ * @param {object} envelope the parsed JSON body from a preflight endpoint
+ * @param {object} [expect]
+ * @param {string} [expect.issuer] pin the accepted signer's public key
+ * @param {string} [expect.subject] pin the origin the report must speak for
+ * @param {number} [expect.now] injected clock, for tests
+ * @param {number} [expect.clockSkewMs]
+ * @returns {{ valid: boolean, reason: string, issuer: string|null, digest: string|null, expired: boolean }}
+ */
+export function verifyPreflight(envelope, { issuer: expectedIssuer, subject, now, clockSkewMs = DEFAULT_CLOCK_SKEW_MS } = {}) {
+ const fail = (reason, digest = null) => ({
+ valid: false,
+ reason,
+ issuer: envelope?.issuer || null,
+ digest,
+ expired: false,
+ });
+
+ if (!envelope || typeof envelope !== 'object' || !envelope.report) return fail('not_an_envelope');
+ if (envelope.spec !== PREFLIGHT_ENVELOPE_VERSION) return fail('unsupported_envelope_version');
+ if (envelope.algorithm && envelope.algorithm !== 'ed25519') return fail('unsupported_algorithm');
+ if (!envelope.issuer || !envelope.signature || !envelope.signedAt) return fail('unsigned');
+ if (envelope.report.spec !== PREFLIGHT_SPEC) return fail('unsupported_report_spec');
+
+ const digest = reportDigest({
+ report: envelope.report,
+ issuer: envelope.issuer,
+ signedAt: envelope.signedAt,
+ });
+ if (envelope.digest && String(envelope.digest).toLowerCase() !== digest) return fail('digest_mismatch', digest);
+ if (expectedIssuer && expectedIssuer !== envelope.issuer) return fail('issuer_mismatch', digest);
+ if (subject && normalizeOrigin(subject) !== normalizeOrigin(envelope.report.subject)) {
+ return fail('subject_mismatch', digest);
+ }
+
+ let ok = false;
+ try {
+ ok = ed25519.verify(bs58.decode(envelope.signature), signingMessage(digest), bs58.decode(envelope.issuer));
+ } catch {
+ return fail('malformed_signature', digest);
+ }
+ if (!ok) return fail('bad_signature', digest);
+
+ const at = typeof now === 'number' ? now : Date.now();
+ const expiresAt = Date.parse(envelope.report.expires_at || '');
+ if (!Number.isFinite(expiresAt)) return fail('no_expiry', digest);
+ // An expired attestation is not a valid one that happens to be old. Serving a
+ // cached healthy report through an outage is the exact replay this format
+ // exists to prevent, so expiry is checked here and not left to the caller.
+ if (at - clockSkewMs > expiresAt) {
+ return { valid: false, reason: 'expired', issuer: envelope.issuer, digest, expired: true };
+ }
+ const issuedAt = Date.parse(envelope.report.issued_at || '');
+ if (Number.isFinite(issuedAt) && issuedAt - clockSkewMs > at) return fail('issued_in_future', digest);
+
+ return { valid: true, reason: 'ok', issuer: envelope.issuer, digest, expired: false };
+}
+
+/**
+ * Read one network's verdict from an envelope.
+ *
+ * Takes the envelope rather than the report so a caller cannot reach past
+ * verification, and answers `unknown` for a network the report never mentions:
+ * silence is not a denial, and treating it as one would route traffic away from
+ * rails that are fine.
+ * @param {object} envelope
+ * @param {string} network CAIP-2 id, e.g. 'solana:mainnet'
+ * @returns {{ payable: boolean|'unknown', reason: string, retry_after: number|null, alternates: string[], settle: object|null }}
+ */
+export function networkVerdict(envelope, network) {
+ const n = envelope?.report?.networks?.[network];
+ if (!n) {
+ return { payable: 'unknown', reason: 'network_not_configured', retry_after: null, alternates: [], settle: null };
+ }
+ return {
+ payable: n.payable,
+ reason: n.reason,
+ retry_after: n.retry_after ?? null,
+ alternates: Array.isArray(n.alternates) ? n.alternates : [],
+ settle: n.settle ?? null,
+ };
+}
+
+/** Every network the report says is payable right now, in report order. */
+export function payableNetworks(envelope) {
+ const nets = envelope?.report?.networks || {};
+ return Object.keys(nets).filter((k) => nets[k]?.payable === true);
+}
diff --git a/pages/preflight.html b/pages/preflight.html
new file mode 100644
index 000000000..57102748b
--- /dev/null
+++ b/pages/preflight.html
@@ -0,0 +1,142 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>x402 Preflight · three.ws</title>
+ <meta name="description" content="Check whether any x402 seller can actually settle before you pay it. Fetches the seller's signed payability attestation and verifies the signature and expiry in your browser." />
+ <link rel="canonical" href="https://three.ws/preflight" />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/preflight" />
+ <meta property="og:title" content="x402 Preflight · three.ws" />
+ <meta property="og:description" content="x402 tells you what a resource costs. Preflight tells you whether the seller can actually take your money. Signed, time-bounded, verified in your browser." />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=x402+Preflight&amp;d=x402+tells+you+what+a+resource+costs.+Preflight+tells+you+whether+the+seller+can+actually+take+your+money.&amp;p=%2Fpreflight" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="x402 Preflight · three.ws" />
+ <meta name="twitter:description" content="x402 tells you what a resource costs. Preflight tells you whether the seller can actually take your money. Signed, time-bounded, verified in your browser." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=x402+Preflight&amp;d=x402+tells+you+what+a+resource+costs.+Preflight+tells+you+whether+the+seller+can+actually+take+your+money.&amp;p=%2Fpreflight" />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <style>
+ .pf-shell { max-width: 860px; margin: 0 auto; padding: clamp(20px, 5vw, 44px) 18px 80px; }
+ .pf-hero { margin-bottom: 26px; }
+ .pf-kicker { display: inline-flex; align-items: center; gap: 8px; font-size: .72rem; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--ink-dim, #888); margin: 0 0 10px; }
+ .pf-kicker::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: var(--success, #3fb950); box-shadow: 0 0 8px color-mix(in srgb, var(--success, #3fb950) 60%, transparent); }
+ .pf-title { font-family: var(--font-display, system-ui); font-size: clamp(1.6rem, 4vw, 2.3rem); font-weight: 700; color: var(--ink-bright, #fff); margin: 0 0 10px; line-height: 1.1; }
+ .pf-sub { color: var(--ink-dim, #888); font-size: .95rem; line-height: 1.65; margin: 0; max-width: 64ch; }
+ .pf-sub code { font-size: .86em; padding: 1px 5px; border-radius: 4px; background: var(--surface-2, #1a1a1a); }
+
+ .pf-form { display: flex; gap: 10px; margin: 26px 0 8px; flex-wrap: wrap; }
+ .pf-input { flex: 1 1 320px; min-width: 0; padding: 11px 14px; border-radius: 10px; font: inherit; font-size: .95rem; color: var(--ink-bright, #fff); background: var(--surface-1, #121212); border: 1px solid var(--line, #2a2a2a); transition: border-color .16s ease, box-shadow .16s ease; }
+ .pf-input:hover { border-color: var(--line-bright, #3a3a3a); }
+ .pf-input:focus-visible { outline: none; border-color: var(--accent, #6ea8fe); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent, #6ea8fe) 25%, transparent); }
+ .pf-go { padding: 11px 20px; border-radius: 10px; font: inherit; font-weight: 600; font-size: .92rem; cursor: pointer; color: #06121f; background: var(--accent, #6ea8fe); border: 1px solid transparent; transition: transform .12s ease, filter .16s ease; }
+ .pf-go:hover { filter: brightness(1.08); }
+ .pf-go:active { transform: translateY(1px); }
+ .pf-go:focus-visible { outline: none; box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent, #6ea8fe) 35%, transparent); }
+ .pf-go[disabled] { opacity: .55; cursor: progress; }
+ .pf-examples { display: flex; gap: 8px; flex-wrap: wrap; font-size: .8rem; color: var(--ink-dim, #888); align-items: center; }
+ .pf-chip { padding: 3px 9px; border-radius: 999px; cursor: pointer; font: inherit; font-size: .78rem; color: var(--ink, #ddd); background: var(--surface-2, #1a1a1a); border: 1px solid var(--line, #2a2a2a); transition: border-color .16s ease, color .16s ease; }
+ .pf-chip:hover { border-color: var(--accent, #6ea8fe); color: var(--ink-bright, #fff); }
+ .pf-chip:focus-visible { outline: none; box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent, #6ea8fe) 30%, transparent); }
+
+ #pf-out { margin-top: 26px; }
+ .pf-card { border: 1px solid var(--line, #2a2a2a); border-radius: 14px; background: var(--surface-1, #121212); padding: 18px 18px 6px; margin-bottom: 14px; animation: pf-in .22s ease both; }
+ @keyframes pf-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
+ @media (prefers-reduced-motion: reduce) { .pf-card { animation: none; } }
+ .pf-cardhead { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 4px; }
+ .pf-origin { font-weight: 650; color: var(--ink-bright, #fff); font-size: 1.02rem; word-break: break-all; }
+ .pf-meta { font-size: .76rem; color: var(--ink-dim, #888); font-family: var(--font-mono, ui-monospace, monospace); word-break: break-all; }
+ .pf-verified { display: inline-flex; align-items: center; gap: 6px; font-size: .76rem; font-weight: 600; color: var(--success, #3fb950); }
+ .pf-net { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px 14px; padding: 13px 0; border-top: 1px solid var(--line, #2a2a2a); align-items: center; }
+ .pf-netid { font-family: var(--font-mono, ui-monospace, monospace); font-size: .86rem; color: var(--ink-bright, #fff); }
+ .pf-netwhy { grid-column: 1 / -1; font-size: .82rem; color: var(--ink-dim, #888); line-height: 1.5; }
+ .pf-badge { font-size: .7rem; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; padding: 4px 10px; border-radius: 999px; white-space: nowrap; }
+ .pf-yes { color: #0b2a13; background: var(--success, #3fb950); }
+ .pf-no { color: #2b0d0d; background: var(--danger, #f85149); }
+ .pf-maybe { color: #2b1f04; background: var(--warning, #d29922); }
+ .pf-alt { color: var(--success, #3fb950); }
+ .pf-err { border-color: color-mix(in srgb, var(--danger, #f85149) 45%, var(--line, #2a2a2a)); }
+ .pf-empty { color: var(--ink-dim, #888); font-size: .9rem; line-height: 1.6; border: 1px dashed var(--line, #2a2a2a); border-radius: 14px; padding: 22px; text-align: center; }
+ .pf-empty strong { color: var(--ink, #ddd); font-weight: 600; }
+ .pf-skel { height: 92px; border-radius: 14px; border: 1px solid var(--line, #2a2a2a); background: linear-gradient(100deg, var(--surface-1, #121212) 30%, var(--surface-2, #1a1a1a) 50%, var(--surface-1, #121212) 70%); background-size: 220% 100%; animation: pf-shim 1.1s linear infinite; }
+ @keyframes pf-shim { to { background-position: -220% 0; } }
+ @media (prefers-reduced-motion: reduce) { .pf-skel { animation: none; } }
+
+ .pf-how { margin-top: 40px; border-top: 1px solid var(--line, #2a2a2a); padding-top: 26px; }
+ .pf-how h2 { font-size: 1.05rem; color: var(--ink-bright, #fff); margin: 0 0 10px; }
+ .pf-how p { color: var(--ink-dim, #888); font-size: .9rem; line-height: 1.7; margin: 0 0 12px; max-width: 68ch; }
+ .pf-how pre { overflow-x: auto; background: var(--surface-1, #121212); border: 1px solid var(--line, #2a2a2a); border-radius: 10px; padding: 14px 16px; font-size: .82rem; line-height: 1.6; }
+ .pf-how code { font-family: var(--font-mono, ui-monospace, monospace); }
+ .pf-how a { color: var(--accent, #6ea8fe); }
+ </style>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="pf-shell">
+ <section class="pf-hero">
+ <p class="pf-kicker">Don't trust · verify</p>
+ <h1 class="pf-title">Can this seller actually take your money?</h1>
+ <p class="pf-sub">
+ x402 tells an agent what a resource <em>costs</em>. It says nothing about whether the seller
+ can currently <em>settle</em> what it charges, and the gap is paid for by the buyer: a signed
+ transfer, a consumed blockhash, a 502, and no service. Preflight closes it. Paste any origin
+ below and this page fetches its <code>/.well-known/x402-preflight</code> attestation and
+ verifies the ed25519 signature, the expiry and the subject entirely in your browser. Nothing
+ is taken on our word.
+ </p>
+ </section>
+
+ <form class="pf-form" id="pf-form">
+ <label class="pf-input-label" for="pf-origin" hidden>Seller origin</label>
+ <input class="pf-input" id="pf-origin" name="origin" type="url" inputmode="url"
+ placeholder="https://three.ws" autocomplete="off" spellcheck="false" required />
+ <button class="pf-go" id="pf-go" type="submit">Check</button>
+ </form>
+ <div class="pf-examples">
+ <span>Try:</span>
+ <button class="pf-chip" type="button" data-origin="https://three.ws">three.ws</button>
+ </div>
+
+ <div id="pf-out" aria-live="polite"></div>
+
+ <section class="pf-how">
+ <h2>Use it from your own agent</h2>
+ <p>
+ The client is a package. It fetches, verifies, and refuses to let you pay a seller that cannot
+ settle, re-routing to a rail that works when one is available.
+ </p>
+ <pre><code>npm i @three-ws/x402-preflight
+
+import { guardedFetch } from '@three-ws/x402-preflight';
+
+// A drop-in fetch that will not spend your money on a seller who cannot deliver.
+const fetch402 = guardedFetch({ prefer: ['solana:mainnet'] });
+await fetch402('https://three.ws/api/x402/echo');</code></pre>
+ <p>Or from a terminal, where the exit code is the answer:</p>
+ <pre><code>npx @three-ws/x402-preflight https://three.ws --network solana:mainnet &amp;&amp; echo "safe to pay"</code></pre>
+ <p>
+ The wire format is public and unencumbered: any x402 seller can publish one and any client can
+ verify it. Read the <a href="/docs/x402-preflight">documentation</a> for the format, the
+ verification rules, and how to serve an attestation from your own endpoint.
+ </p>
+ </section>
+ </main>
+
+ <script type="module" src="/src/preflight-page.js"></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/i18n.js"></script>
+</body>
+</html>
diff --git a/src/preflight-page.js b/src/preflight-page.js
new file mode 100644
index 000000000..44e0d202a
--- /dev/null
+++ b/src/preflight-page.js
@@ -0,0 +1,225 @@
+// /preflight — check whether any x402 seller can actually settle, and verify the
+// answer here rather than believing it.
+//
+// The verification runs in the visitor's browser against the seller's own
+// signature. That is the whole point of the page: a status page you have to
+// trust is worth nothing, and this one can be checked by anyone who opens
+// devtools. The same verify() shipped in @three-ws/x402-preflight runs here, so
+// what a reader sees is what their agent would compute.
+//
+// A cross-origin fetch to a third-party seller may be blocked by that seller's
+// CORS policy. That is not our failure to hide: it is reported plainly, with the
+// header the seller would need to add, because a silent "unknown" would teach
+// people the format is unreliable when the format is fine.
+
+import { verifyPreflight, normalizeOrigin } from '../packages/x402-preflight/src/verify.js';
+
+const PREFLIGHT_PATH = '/.well-known/x402-preflight';
+
+const form = document.getElementById('pf-form');
+const input = /** @type {HTMLInputElement} */ (document.getElementById('pf-origin'));
+const button = /** @type {HTMLButtonElement} */ (document.getElementById('pf-go'));
+const out = document.getElementById('pf-out');
+
+function el(tag, cls, text) {
+ const n = document.createElement(tag);
+ if (cls) n.className = cls;
+ if (text != null) n.textContent = String(text);
+ return n;
+}
+
+function badge(payable) {
+ if (payable === true) return el('span', 'pf-badge pf-yes', 'payable');
+ if (payable === false) return el('span', 'pf-badge pf-no', 'not payable');
+ return el('span', 'pf-badge pf-maybe', 'unknown');
+}
+
+// Plain-language rendering of each machine reason. The wire format is for
+// agents; a person reading this page deserves the sentence, not the enum.
+const REASON_COPY = {
+ ok: 'Settling normally.',
+ sponsor_below_floor:
+ 'The seller\'s own fee wallet cannot cover network fees, so nothing you sign can settle. Only the seller can fix this.',
+ settlement_degraded: 'Recent settlements are failing. Payments may not complete.',
+ facilitator_unreachable: 'The seller cannot reach its settlement facilitator, so it cannot vouch for this rail.',
+ network_not_configured: 'The seller does not accept payment on this network.',
+ rail_unavailable: 'The payment rail itself is unavailable.',
+ unknown: 'The seller could not measure this rail, so it will not claim it works.',
+};
+
+function describeSettle(s) {
+ if (!s || s.rate == null) return 'no settled payments measured in the window';
+ const pct = (s.rate * 100).toFixed(1);
+ return `${pct}% of ${s.attempts} attempt${s.attempts === 1 ? '' : 's'} over ${s.window_hours}h (confidence ${s.confidence})`;
+}
+
+function renderNetwork(id, n) {
+ const row = el('div', 'pf-net');
+ row.append(el('span', 'pf-netid', id), badge(n.payable));
+
+ const why = el('div', 'pf-netwhy');
+ why.append(el('span', null, REASON_COPY[n.reason] || n.reason));
+ why.append(document.createElement('br'));
+ why.append(el('span', null, describeSettle(n.settle)));
+ if (n.payable !== true && Array.isArray(n.alternates) && n.alternates.length) {
+ why.append(document.createElement('br'));
+ const alt = el('span', 'pf-alt', `Payable instead on ${n.alternates.join(', ')}`);
+ why.append(alt);
+ }
+ if (n.payable !== true && n.retry_after) {
+ why.append(document.createElement('br'));
+ why.append(el('span', null, `Seller suggests retrying in ${n.retry_after}s.`));
+ }
+ row.append(why);
+ return row;
+}
+
+function renderError(origin, title, detail, hint) {
+ const card = el('div', 'pf-card pf-err');
+ const head = el('div', 'pf-cardhead');
+ head.append(el('span', 'pf-origin', origin), el('span', 'pf-badge pf-no', 'unverified'));
+ card.append(head, el('div', 'pf-netwhy', title));
+ if (detail) card.append(el('div', 'pf-meta', detail));
+ if (hint) card.append(el('div', 'pf-netwhy', hint));
+ card.append(el('div', 'pf-net'));
+ return card;
+}
+
+function renderReport(envelope, verification) {
+ const report = envelope.report;
+ const card = el('div', 'pf-card');
+
+ const head = el('div', 'pf-cardhead');
+ head.append(el('span', 'pf-origin', report.subject));
+ const v = el('span', 'pf-verified');
+ v.append(el('span', null, '✓'), el('span', null, 'signature verified in your browser'));
+ head.append(v);
+ card.append(head);
+
+ const secondsLeft = Math.max(0, Math.round((Date.parse(report.expires_at) - Date.now()) / 1000));
+ card.append(
+ el('div', 'pf-meta', `issuer ${envelope.issuer} · digest ${verification.digest.slice(0, 16)}… · valid ${secondsLeft}s longer`),
+ );
+
+ const entries = Object.entries(report.networks || {});
+ if (!entries.length) {
+ card.append(el('div', 'pf-netwhy', 'This seller publishes an attestation but offers no payment networks.'));
+ }
+ for (const [id, n] of entries) card.append(renderNetwork(id, n));
+ return card;
+}
+
+function emptyState() {
+ const box = el('div', 'pf-empty');
+ box.append(el('strong', null, 'Nothing checked yet.'));
+ box.append(document.createElement('br'));
+ box.append(
+ el(
+ 'span',
+ null,
+ 'Enter any x402 seller\'s origin above. If it publishes an attestation you will see its signature verified here, network by network.',
+ ),
+ );
+ return box;
+}
+
+async function check(rawOrigin) {
+ const origin = normalizeOrigin(rawOrigin);
+ out.replaceChildren(el('div', 'pf-skel'));
+ button.disabled = true;
+ button.textContent = 'Checking…';
+
+ // A hung seller must not hang the page.
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 8000);
+ try {
+ let res;
+ try {
+ res = await fetch(`${origin}${PREFLIGHT_PATH}`, {
+ headers: { accept: 'application/json' },
+ signal: controller.signal,
+ });
+ } catch (err) {
+ const aborted = err?.name === 'AbortError';
+ out.replaceChildren(
+ renderError(
+ origin,
+ aborted ? 'The seller did not answer in time.' : 'Could not reach the seller from your browser.',
+ err?.message || String(err),
+ aborted
+ ? null
+ : 'If the origin is reachable, it is most likely a CORS policy: the seller must send access-control-allow-origin on its preflight response for browsers to read it. Agents calling it server-side are unaffected.',
+ ),
+ );
+ return;
+ }
+
+ if (!res.ok) {
+ out.replaceChildren(
+ renderError(
+ origin,
+ res.status === 404
+ ? 'This origin does not publish an x402 preflight attestation.'
+ : `The seller answered HTTP ${res.status}.`,
+ null,
+ res.status === 404
+ ? 'That is not a fault: preflight is opt-in and most x402 sellers have not adopted it yet. It does mean you cannot know whether this one can settle before you pay.'
+ : 'A seller that cannot sign an attestation is a seller you should not assume is healthy.',
+ ),
+ );
+ return;
+ }
+
+ let envelope;
+ try {
+ envelope = await res.json();
+ } catch {
+ out.replaceChildren(renderError(origin, 'The seller\'s response was not valid JSON.'));
+ return;
+ }
+
+ const verification = verifyPreflight(envelope, { subject: origin });
+ if (!verification.valid) {
+ out.replaceChildren(
+ renderError(
+ origin,
+ `The attestation did not verify: ${verification.reason}.`,
+ null,
+ verification.reason === 'expired'
+ ? 'The seller served an attestation that has already expired. Expiry is what stops a healthy report being replayed through an outage, so an expired one carries no assurance at all.'
+ : 'The document is signed, but the signature does not match its contents. Treat this seller as unverified.',
+ ),
+ );
+ return;
+ }
+
+ out.replaceChildren(renderReport(envelope, verification));
+ } finally {
+ clearTimeout(timer);
+ button.disabled = false;
+ button.textContent = 'Check';
+ }
+}
+
+form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const value = input.value.trim();
+ if (value) check(value);
+});
+
+for (const chip of document.querySelectorAll('.pf-chip')) {
+ chip.addEventListener('click', () => {
+ input.value = chip.dataset.origin || '';
+ check(input.value);
+ });
+}
+
+out.replaceChildren(emptyState());
+
+// Deep link: /preflight?origin=https://example.com checks on load, so the page
+// can be linked from an incident report or a status dashboard.
+const fromQuery = new URLSearchParams(location.search).get('origin');
+if (fromQuery) {
+ input.value = fromQuery;
+ check(fromQuery);
+}
diff --git a/tests/x402-preflight.test.js b/tests/x402-preflight.test.js
new file mode 100644
index 000000000..8a69d614e
--- /dev/null
+++ b/tests/x402-preflight.test.js
@@ -0,0 +1,396 @@
+// x402 Preflight: the signed assurance that a seller can settle before you pay.
+//
+// Every case here is written against the incident that produced the format. On
+// 2026-08-28 three.ws was a seller whose fee sponsor held 0.000899107 SOL
+// against a 0.02 floor, so every payment it was handed failed at simulation with
+// InsufficientFundsForRent. 95 attempts, 0 settled, three hours. Each of those
+// buyers could have known before signing, from state the server already had.
+//
+// The properties under test are the ones a buyer's money rests on:
+// * a tampered report does not verify
+// * an expired attestation does not verify, at any layer
+// * an attestation for one origin cannot be presented as covering another
+// * "cannot tell" is never reported as "payable"
+// * the client half and the server half agree byte-for-byte on the signature,
+// which is what makes the browser SDK able to check the server's work
+//
+// The cross-implementation case at the end is the load-bearing one: the server
+// signs with node crypto and @noble/curves, the SDK verifies with @noble/hashes
+// and @noble/curves, and if their canonical JSON ever diverged every signature
+// in the ecosystem would break silently.
+
+import { describe, it, expect } from 'vitest';
+import { Keypair } from '@solana/web3.js';
+
+import {
+ buildPreflightReport,
+ decideNetworkPayability,
+ signPreflight,
+ verifyPreflight,
+ networkVerdict,
+ sampleConfidence,
+ normalizeOrigin,
+ PREFLIGHT_SPEC,
+ PREFLIGHT_ENVELOPE_VERSION,
+ PREFLIGHT_MAX_TTL_SECONDS,
+} from '../api/_lib/x402/preflight.js';
+
+import { verifyPreflight as sdkVerify, networkVerdict as sdkVerdict, payableNetworks } from '../packages/x402-preflight/src/verify.js';
+import { preflight, assertPayable, chooseNetwork, guardedFetch, PreflightError, clearPreflightCache } from '../packages/x402-preflight/src/index.js';
+
+const SIGNER = Keypair.generate();
+const ORIGIN = 'https://three.ws';
+const SOLANA = 'solana:mainnet';
+const BASE = 'eip155:8453';
+
+// The exact shape of the 2026-08-28 outage: Solana unpayable because the
+// seller's sponsor is empty, Base healthy because it never used that sponsor.
+function outageNetworks() {
+ return {
+ [SOLANA]: decideNetworkPayability({ configured: true, sponsorBelowFloor: true }),
+ [BASE]: decideNetworkPayability({
+ configured: true,
+ settleStatus: 'ok',
+ settleRate: 0.98,
+ attempts: 412,
+ windowHours: 3,
+ }),
+ };
+}
+
+function sign(networks = outageNetworks(), opts = {}) {
+ const report = buildPreflightReport({ subject: ORIGIN, networks, ...opts });
+ return signPreflight(report, SIGNER.secretKey);
+}
+
+describe('decideNetworkPayability: never guess in the buyer\'s disfavour', () => {
+ it('names a dry sponsor as the reason, which no buyer action can fix', () => {
+ const v = decideNetworkPayability({ configured: true, sponsorBelowFloor: true });
+ expect(v.payable).toBe(false);
+ expect(v.reason).toBe('sponsor_below_floor');
+ // A human with a wallet has to act, so the back-off is minutes, not seconds.
+ expect(v.retry_after).toBeGreaterThanOrEqual(300);
+ });
+
+ it('reports unknown, never payable, when nothing could be measured', () => {
+ // The expensive mistake is a false `true`: the buyer makes an irreversible
+ // transfer on the strength of it. A false `unknown` costs a retry.
+ expect(decideNetworkPayability({ configured: true }).payable).toBe('unknown');
+ expect(decideNetworkPayability({ configured: true, settleStatus: 'unknown' }).payable).toBe('unknown');
+ expect(
+ decideNetworkPayability({ configured: true, settleStatus: 'ok', facilitatorReachable: false }).payable,
+ ).toBe('unknown');
+ });
+
+ it('only says payable on positive evidence', () => {
+ const v = decideNetworkPayability({
+ configured: true,
+ sponsorBelowFloor: false,
+ settleStatus: 'ok',
+ settleRate: 0.99,
+ attempts: 300,
+ windowHours: 3,
+ });
+ expect(v.payable).toBe(true);
+ expect(v.retry_after).toBe(null);
+ });
+
+ it('treats a degraded rail as not payable rather than probably fine', () => {
+ expect(decideNetworkPayability({ configured: true, settleStatus: 'degraded' }).payable).toBe(false);
+ expect(decideNetworkPayability({ configured: true, settleStatus: 'down' }).payable).toBe(false);
+ });
+
+ it('carries the window and sample with every rate, so a rate is never a rumour', () => {
+ const v = decideNetworkPayability({
+ configured: true, sponsorBelowFloor: false, settleStatus: 'ok',
+ settleRate: 1, attempts: 3, windowHours: 3,
+ });
+ // A 100% rate over 3 attempts must not read like a proven rail.
+ expect(v.settle.attempts).toBe(3);
+ expect(v.settle.window_hours).toBe(3);
+ expect(v.settle.confidence).toBeLessThan(0.3);
+ });
+});
+
+describe('sampleConfidence', () => {
+ it('rises with the sample and never reaches certainty', () => {
+ expect(sampleConfidence(0)).toBe(0);
+ expect(sampleConfidence(10)).toBeLessThan(sampleConfidence(100));
+ expect(sampleConfidence(1e9)).toBeLessThanOrEqual(0.99);
+ });
+});
+
+describe('buildPreflightReport', () => {
+ it('computes alternates so a client re-routes without a second round trip', () => {
+ const env = sign();
+ expect(networkVerdict(env, SOLANA).alternates).toEqual([BASE]);
+ expect(networkVerdict(env, BASE).alternates).toEqual([]);
+ expect(env.report.payable_any).toBe(true);
+ });
+
+ it('sorts networks so the signed bytes do not depend on gather order', () => {
+ const a = buildPreflightReport({ subject: ORIGIN, networks: outageNetworks(), issuedAt: '2026-08-28T00:00:00.000Z' });
+ const flipped = {};
+ for (const k of Object.keys(outageNetworks()).reverse()) flipped[k] = outageNetworks()[k];
+ const b = buildPreflightReport({ subject: ORIGIN, networks: flipped, issuedAt: '2026-08-28T00:00:00.000Z' });
+ expect(JSON.stringify(a)).toBe(JSON.stringify(b));
+ });
+
+ it('caps the validity window, because an hour-long assurance is not one', () => {
+ const env = sign(outageNetworks(), { ttlSeconds: 86_400 });
+ const life = (Date.parse(env.report.expires_at) - Date.parse(env.report.issued_at)) / 1000;
+ expect(life).toBe(PREFLIGHT_MAX_TTL_SECONDS);
+ });
+});
+
+describe('verifyPreflight: the trust boundary', () => {
+ it('accepts a well-formed attestation for the origin it names', () => {
+ const v = verifyPreflight(sign(), { subject: 'https://three.ws/' });
+ expect(v.valid).toBe(true);
+ expect(v.issuer).toBe(SIGNER.publicKey.toBase58());
+ });
+
+ it('rejects a report edited after signing', () => {
+ // The whole point: a seller cannot flip its own verdict to payable, and a
+ // man in the middle cannot flip it either.
+ const env = JSON.parse(JSON.stringify(sign()));
+ env.report.networks[SOLANA].payable = true;
+ expect(verifyPreflight(env).valid).toBe(false);
+ });
+
+ it('rejects a re-signed digest that no longer matches the body', () => {
+ const env = JSON.parse(JSON.stringify(sign()));
+ env.report.networks[SOLANA].payable = true;
+ delete env.digest; // force the check onto the signature itself
+ expect(verifyPreflight(env).reason).toBe('bad_signature');
+ });
+
+ it('rejects an expired attestation, which is the replay this format prevents', () => {
+ const env = sign();
+ const past = Date.parse(env.report.expires_at) + 120_000;
+ const v = verifyPreflight(env, { now: past });
+ expect(v.valid).toBe(false);
+ expect(v.reason).toBe('expired');
+ expect(v.expired).toBe(true);
+ });
+
+ it('tolerates honest clock drift without opening a replay window', () => {
+ const env = sign();
+ const barelyPast = Date.parse(env.report.expires_at) + 10_000;
+ expect(verifyPreflight(env, { now: barelyPast }).valid).toBe(true);
+ expect(verifyPreflight(env, { now: barelyPast + 60_000 }).valid).toBe(false);
+ });
+
+ it('rejects an attestation presented as covering a different origin', () => {
+ const v = verifyPreflight(sign(), { subject: 'https://not-three.example' });
+ expect(v.reason).toBe('subject_mismatch');
+ });
+
+ it('rejects a signature from an issuer the caller did not pin', () => {
+ expect(verifyPreflight(sign(), { issuer: Keypair.generate().publicKey.toBase58() }).reason).toBe('issuer_mismatch');
+ });
+
+ it('rejects an attestation stamped in the future', () => {
+ const env = sign(outageNetworks(), { issuedAt: new Date(Date.now() + 600_000).toISOString() });
+ expect(verifyPreflight(env).reason).toBe('issued_in_future');
+ });
+
+ it('returns a verdict for garbage instead of throwing', () => {
+ // A hostile seller must not be able to crash a paying agent's loop.
+ for (const bad of [null, undefined, 42, 'nope', {}, { report: {} }, { spec: 'x', report: {} }]) {
+ expect(() => verifyPreflight(bad)).not.toThrow();
+ expect(verifyPreflight(bad).valid).toBe(false);
+ }
+ });
+
+ it('rejects an unsupported envelope or report version outright', () => {
+ const a = { ...sign(), spec: 'threews.x402.preflight.v99' };
+ expect(verifyPreflight(a).reason).toBe('unsupported_envelope_version');
+ const b = JSON.parse(JSON.stringify(sign()));
+ b.report.spec = 'x402-preflight/99';
+ expect(verifyPreflight(b).reason).toBe('unsupported_report_spec');
+ });
+});
+
+describe('the SDK verifies exactly what the server signed', () => {
+ // Load-bearing. The server hashes with node crypto, the SDK with
+ // @noble/hashes, and they canonicalize JSON independently. If those two ever
+ // disagreed, every signature would fail in browsers and nowhere else.
+ it('agrees with the server implementation, digest for digest', () => {
+ const env = sign();
+ const mine = verifyPreflight(env, { subject: ORIGIN });
+ const theirs = sdkVerify(env, { subject: ORIGIN });
+ expect(theirs.valid).toBe(true);
+ expect(theirs.digest).toBe(mine.digest);
+ });
+
+ it('agrees on every rejection too', () => {
+ const env = JSON.parse(JSON.stringify(sign()));
+ env.report.networks[SOLANA].payable = true;
+ expect(sdkVerify(env).valid).toBe(false);
+ expect(sdkVerify(env).reason).toBe(verifyPreflight(env).reason);
+ });
+
+ it('reads the same verdicts and payable set', () => {
+ const env = sign();
+ expect(sdkVerdict(env, SOLANA).reason).toBe('sponsor_below_floor');
+ expect(payableNetworks(env)).toEqual([BASE]);
+ });
+
+ it('constants match across the two halves', () => {
+ expect(PREFLIGHT_SPEC).toBe('x402-preflight/1');
+ expect(PREFLIGHT_ENVELOPE_VERSION).toBe('threews.x402.preflight.v1');
+ });
+});
+
+describe('normalizeOrigin', () => {
+ it('ignores a trailing slash, a path and a case change', () => {
+ expect(normalizeOrigin('https://Three.WS/')).toBe('https://three.ws');
+ expect(normalizeOrigin('https://three.ws/api/x402/echo')).toBe('https://three.ws');
+ });
+});
+
+// A fetch that serves one prepared envelope, so the client half is exercised
+// end to end without a network or a live server.
+function fetchServing(envelope, { status = 200, headers = {} } = {}) {
+ return async () => ({
+ ok: status >= 200 && status < 300,
+ status,
+ headers: { get: (k) => headers[k.toLowerCase()] ?? null },
+ json: async () => envelope,
+ });
+}
+
+describe('the client half, end to end', () => {
+ it('fetches, verifies and returns the report', async () => {
+ clearPreflightCache();
+ const env = sign();
+ const { report, verification } = await preflight(ORIGIN, { fetch: fetchServing(env), cache: false });
+ expect(verification.valid).toBe(true);
+ expect(report.subject).toBe(ORIGIN);
+ });
+
+ it('refuses to pay a seller whose rail cannot settle, and names the way out', async () => {
+ clearPreflightCache();
+ const err = await assertPayable(ORIGIN, SOLANA, { fetch: fetchServing(sign()), cache: false }).catch((e) => e);
+ expect(err).toBeInstanceOf(PreflightError);
+ expect(err.code).toBe('not_payable');
+ expect(err.reason).toBe('sponsor_below_floor');
+ expect(err.alternates).toEqual([BASE]);
+ expect(err.retryAfter).toBeGreaterThan(0);
+ });
+
+ it('passes when the rail is healthy', async () => {
+ clearPreflightCache();
+ const { verdict } = await assertPayable(ORIGIN, BASE, { fetch: fetchServing(sign()), cache: false });
+ expect(verdict.payable).toBe(true);
+ });
+
+ it('treats unknown as not payable unless the caller opts in at the call site', async () => {
+ clearPreflightCache();
+ const env = sign({ [SOLANA]: decideNetworkPayability({ configured: true }) });
+ const f = fetchServing(env);
+ await expect(assertPayable(ORIGIN, SOLANA, { fetch: f, cache: false })).rejects.toThrow(PreflightError);
+ const ok = await assertPayable(ORIGIN, SOLANA, { fetch: f, cache: false, allowUnknown: true });
+ expect(ok.verdict.payable).toBe('unknown');
+ });
+
+ it('rejects a seller serving an expired attestation', async () => {
+ clearPreflightCache();
+ const env = sign();
+ const err = await preflight(ORIGIN, {
+ fetch: fetchServing(env),
+ cache: false,
+ now: Date.parse(env.report.expires_at) + 120_000,
+ }).catch((e) => e);
+ expect(err.code).toBe('verification_failed');
+ expect(err.reason).toBe('expired');
+ });
+
+ it('surfaces a seller that cannot sign as unavailable, not as healthy', async () => {
+ clearPreflightCache();
+ const err = await preflight(ORIGIN, {
+ fetch: fetchServing(null, { status: 503, headers: { 'retry-after': '60' } }),
+ cache: false,
+ }).catch((e) => e);
+ expect(err.code).toBe('unavailable');
+ expect(err.retryAfter).toBe(60);
+ });
+
+ it('distinguishes a seller that has not adopted preflight from one that is broken', async () => {
+ clearPreflightCache();
+ const err = await preflight(ORIGIN, { fetch: fetchServing(null, { status: 404 }), cache: false }).catch((e) => e);
+ expect(err.code).toBe('not_supported');
+ });
+});
+
+describe('chooseNetwork', () => {
+ it('honours the caller preference when it is payable', () => {
+ const env = sign({
+ [SOLANA]: decideNetworkPayability({ configured: true, sponsorBelowFloor: false, settleStatus: 'ok', settleRate: 1, attempts: 99, windowHours: 3 }),
+ [BASE]: decideNetworkPayability({ configured: true, settleStatus: 'ok', settleRate: 1, attempts: 99, windowHours: 3 }),
+ });
+ expect(chooseNetwork(env, [SOLANA])).toBe(SOLANA);
+ });
+
+ it('falls back to a rail that works when the preferred one is down', () => {
+ expect(chooseNetwork(sign(), [SOLANA])).toBe(BASE);
+ });
+
+ it('returns null rather than throwing when nothing is payable', () => {
+ const env = sign({ [SOLANA]: decideNetworkPayability({ configured: true, sponsorBelowFloor: true }) });
+ expect(chooseNetwork(env, [SOLANA])).toBe(null);
+ });
+});
+
+describe('guardedFetch', () => {
+ it('stops the request that would have burned a signature', async () => {
+ clearPreflightCache();
+ const env = sign({ [SOLANA]: decideNetworkPayability({ configured: true, sponsorBelowFloor: true }) });
+ let paidCalls = 0;
+ const inner = async (url) => {
+ if (String(url).includes('.well-known')) return (await fetchServing(env)())
+ paidCalls += 1;
+ return { ok: true, status: 200, headers: { get: () => null }, json: async () => ({}) };
+ };
+ const skips = [];
+ const f = guardedFetch({ fetch: inner, prefer: [SOLANA], onSkip: (i) => skips.push(i) });
+ await expect(f('https://three.ws/api/x402/echo')).rejects.toThrow(PreflightError);
+ expect(paidCalls).toBe(0);
+ expect(skips[0].reason).toBe('sponsor_below_floor');
+ });
+
+ it('re-routes to a payable rail and tells the seller which one', async () => {
+ clearPreflightCache();
+ const env = sign();
+ let seen = null;
+ const inner = async (url, init) => {
+ if (String(url).includes('.well-known')) return (await fetchServing(env)());
+ seen = init?.headers?.get?.('x-preflight-network');
+ return { ok: true, status: 200, headers: { get: () => null }, json: async () => ({}) };
+ };
+ const f = guardedFetch({ fetch: inner, prefer: [SOLANA] });
+ await f('https://three.ws/api/x402/echo');
+ expect(seen).toBe(BASE);
+ });
+
+ it('passes through a seller that has not adopted preflight', async () => {
+ clearPreflightCache();
+ let through = 0;
+ const inner = async (url) => {
+ if (String(url).includes('.well-known')) return { ok: false, status: 404, headers: { get: () => null }, json: async () => ({}) };
+ through += 1;
+ return { ok: true, status: 200, headers: { get: () => null }, json: async () => ({}) };
+ };
+ await guardedFetch({ fetch: inner })('https://legacy.example/api/paid');
+ expect(through).toBe(1);
+ });
+
+ it('fails closed for a non-adopting seller when the caller asks it to', async () => {
+ clearPreflightCache();
+ const inner = async () => ({ ok: false, status: 404, headers: { get: () => null }, json: async () => ({}) });
+ await expect(
+ guardedFetch({ fetch: inner, requirePreflight: true })('https://legacy.example/api/paid'),
+ ).rejects.toThrow(PreflightError);
+ });
+});