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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(pay): add blocked hosts, approval threshold, and per-rail daily caps to payment sessions, with signed verdicts
nirholas655b5a491f23
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 99dfdbbd8..6d7283f8f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-10-15++- **Payment sessions gain blocked hosts, an approval threshold, and a per-rail daily cap, all with tamper-evident verdicts**: Agent payment sessions get three new governance knobs, settable at creation and editable while a session is active: blocked_hosts (a denylist checked after the allowlist, so an explicit block always wins over a broad allow, even with no allowlist set), approval_threshold_usd (a call priced above this amount now gets a distinct requires_approval verdict instead of either settling or silently failing), and per_rail_daily_usd (a rolling 24h spend cap per settlement network, reserved atomically the same way the session budget already is, closing the race a naive sum-of-past-executions check would leave open). Every governance verdict, allow or reject, now carries a policy_digest (a sha256 hash of the exact policy it was judged against) and an HMAC signature over the verdict, digest, request, and timestamp, stored with the execution: editing a session's policy after the fact changes the digest and breaks the signature on every verdict that preceded the edit, so a verdict record can be trusted even after the policy it was judged against has since moved. The dry-run simulator at /api/pay/simulate now predicts all three new rules through the exact same shared policy module the real enforcer calls, so a simulated verdict and an enforced one can never disagree; that parity is pinned by a new test running both over identical scenarios. The payments page gained matching fields in both the session creation and edit modals, with inline validation and a collapsed 'Advanced spend policy' section so the common case (budget, expiry, host allowlist) stays uncluttered. (`/docs/payment-sessions`) `[feature, security]`+## 2026-10-14- **8 keyless live-data services join the x402 paid API: weather, grid carbon, domains, research, books, news, transit, places**: three.ws's x402 surface grows 17 new routes, each needing no API key anywhere in the chain (not an upstream key, not a three.ws key), ported natively onto three.ws's own Solana facilitator so they settle, receipt, and discover exactly like every other paid endpoint: Weather Guard (24h forecast + severe alerts from Open-Meteo, NWS fallback), Carbon (UK grid carbon intensity + lowest-carbon scheduling window), Domains (live RDAP registration lookups, single and bulk), Research (paper search across arXiv/Crossref/Semantic Scholar, metadata, bibliographies), Books (OpenLibrary + Project Gutenberg search and full-text reads), News Wire (global news search and polling over GDELT DOC 2.0), Transit (MBTA GTFS trip planning and realtime delay snapshots), and Places (OpenStreetMap Overpass point-of-interest search and detail). Each service's discovery route runs a free daily per-IP quota before falling through to the x402 pay-per-call lane, fails closed to the paid rail rather than opening an unmetered proxy if the quota store is unreachable, and every upstream call sends an identifying User-Agent. No fixture or mocked fallback anywhere in the set: an upstream outage answers 502, and the one route whose source suite offers a fake-data fallback when unconfigured (Places Detail's review enrichment) ships without that fallback, returning only the real OpenStreetMap record. All 17 routes appear in GET /openapi.json and GET /.well-known/x402.json with Solana listed first in every payment challenge. (`/docs/x402-endpoints`) `[feature]`diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 2e40b85b0..e72cbf862 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -455,6 +455,19 @@ export const env = {return opt('PAYMENT_SESSION_SECRET') || this.WALLET_CAPABILITY_SECRET;},+ // HMAC key that signs Spend Governor verdicts (api/_lib/pay/spend-governor.js).+ // Every verdict (allow or reject) is signed over {verdict code, policy digest,+ // request hash, timestamp} and stored with its execution, so a verdict cannot+ // be edited after the fact without the signature breaking. Kept separate from+ // PAYMENT_SESSION_SECRET: rotating the token secret (which revokes every live+ // session) must not also invalidate the historical verdict record, and vice+ // versa. Falls back through it (and so through WALLET_CAPABILITY_SECRET /+ // WALLET_ENCRYPTION_KEY / JWT_SECRET) so the feature works in every+ // environment. NEVER log this value.+ get PAY_VERDICT_HMAC_KEY() {+ return opt('PAY_VERDICT_HMAC_KEY') || this.PAYMENT_SESSION_SECRET;+ },+// Long-lived Ed25519 signing seed for the provably-fair vanity grinder// (api/_lib/vanity-service-key.js). Stored as a secret-box ciphertext (v2:…)// or a raw 32-byte seed in hex/Base58. Signs every verifiable-grind receipt;diff --git a/api/_lib/migrations/20261015100000_payment_session_policy_upgrades.sql b/api/_lib/migrations/20261015100000_payment_session_policy_upgrades.sqlnew file mode 100644index 000000000..a6ee7e25f--- /dev/null+++ b/api/_lib/migrations/20261015100000_payment_session_policy_upgrades.sql@@ -0,0 +1,51 @@+-- Spend policy upgrades for Agent Payment Sessions.+--+-- Three new policy knobs on payment_sessions, enforced atomically by+-- api/_lib/pay/spend-governor.js and predicted in parity by api/pay/simulate.js+-- (both share api/_lib/pay/policy.js):+--+-- approval_threshold_usdc: a payment above this amount gets a distinct+-- requires_approval verdict instead of settling.+-- blocked_hosts: a denylist checked after the allowlist so an explicit+-- block always wins over a broad allow.+-- per_rail_daily_usdc: a rolling 24h spend cap, keyed by the CAIP-2+-- network id the x402 challenge actually quoted+-- (payment_session_executions.network already+-- stores this), so the cap survives a session+-- later settling on more than one rail.+--+-- payment_session_rail_reservations backs the rolling-window cap with the+-- same eager reserve-then-roll-back-on-failure pattern spent_usdc already+-- uses, instead of summing payment_session_executions: an execution row is+-- only written after the downstream x402 call finishes, so two concurrent+-- calls on the same rail would both read "nothing in flight yet" and both+-- pass. A reservation row lands atomically (one advisory-locked statement)+-- before the call starts, closing that window.+--+-- payment_session_executions gains the signed-verdict columns: every+-- verdict (allow or reject) carries a sha256 digest of the policy it was+-- judged against and an HMAC over {verdict, digest, request hash,+-- timestamp}, so a verdict stored next to an execution is tamper-evident:+-- editing the policy afterward changes the digest and breaks the signature.++alter table payment_sessions+ add column if not exists approval_threshold_usdc bigint check (approval_threshold_usdc > 0),+ add column if not exists blocked_hosts text[] not null default '{}',+ add column if not exists per_rail_daily_usdc jsonb not null default '{}'::jsonb;++alter table payment_session_executions+ add column if not exists policy_digest text,+ add column if not exists verdict_code text,+ add column if not exists verdict_signature text,+ add column if not exists verdict_signed_at timestamptz;++create table if not exists payment_session_rail_reservations (+ id uuid primary key default gen_random_uuid(),+ session_id uuid not null references payment_sessions(id) on delete cascade,+ network text not null, -- CAIP-2 id, e.g. 'solana:5eykt...' or 'eip155:8453'+ amount_usdc bigint not null check (amount_usdc > 0),+ created_at timestamptz not null default now()+);++create index if not exists psrr_session_network_window+ on payment_session_rail_reservations (session_id, network, created_at desc);diff --git a/api/_lib/pay/payment-session.js b/api/_lib/pay/payment-session.jsindex 9e2b5ac2a..c62b61fbc 100644--- a/api/_lib/pay/payment-session.js+++ b/api/_lib/pay/payment-session.js@@ -25,7 +25,7 @@ import {atomicsToUsd,normalizeHost,} from './spend-governor.js';-import { SESSION_LIMITS } from './policy.js';+import { SESSION_LIMITS, canonicalizePerRailDaily } from './policy.js';const {MAX_LABEL_LEN,@@ -78,6 +78,32 @@ function normalizeMaxPerTx(maxPerTxUsd) {return n;}+function normalizeApprovalThreshold(approvalThresholdUsd) {+ if (approvalThresholdUsd == null) return null;+ const n = Number(approvalThresholdUsd);+ if (!Number.isFinite(n) || n < 0.000001) throw bad('approval_threshold_usd must be > $0.000001');+ return n;+}++function normalizeBlockedHosts(raw) {+ if (!raw) return [];+ const arr = Array.isArray(raw) ? raw : String(raw).split(/[\s,]+/);+ const hosts = arr.map(normalizeHost).filter(Boolean);+ if (hosts.length > MAX_ALLOWED_HOSTS)+ throw bad(`blocked_hosts may contain at most ${MAX_ALLOWED_HOSTS} entries`);+ return [...new Set(hosts)];+}++function normalizePerRailDaily(raw) {+ if (raw == null) return {};+ if (typeof raw !== 'object' || Array.isArray(raw)) throw bad('per_rail_daily_usd must be an object keyed by network');+ for (const value of Object.values(raw)) {+ const n = Number(value);+ if (!Number.isFinite(n) || n <= 0) throw bad('per_rail_daily_usd values must be positive numbers');+ }+ return canonicalizePerRailDaily(raw);+}+/*** Create a new payment session.*@@ -88,6 +114,9 @@ function normalizeMaxPerTx(maxPerTxUsd) {* @param {number} opts.budgetUsd - Total budget in USD* @param {number} [opts.maxPerTxUsd] - Per-payment ceiling in USD* @param {string[]} [opts.allowedHosts] - If set, only pay endpoints at these hosts+ * @param {string[]} [opts.blockedHosts] - Hosts this session must never pay, even if allowlisted+ * @param {number} [opts.approvalThresholdUsd] - A payment above this needs human approval instead of settling+ * @param {object} [opts.perRailDailyUsd] - Rolling 24h spend cap per settlement rail, keyed by network ('solana'/'base') or CAIP-2 id* @param {string} [opts.network] - 'solana' | 'base' (default: 'solana')* @param {number} [opts.expirySeconds] - Session lifetime in seconds (default: 3600)* @param {object} [opts.metadata] - Arbitrary caller metadata@@ -100,6 +129,9 @@ export async function createPaymentSession({budgetUsd,maxPerTxUsd,allowedHosts,+ blockedHosts,+ approvalThresholdUsd,+ perRailDailyUsd,network = 'solana',expirySeconds,metadata = {},@@ -110,6 +142,10 @@ export async function createPaymentSession({const budgetAtomics = usdToAtomics(budgetN);const maxPerTxAtomics = maxPerTxUsd != null ? usdToAtomics(normalizeMaxPerTx(maxPerTxUsd)) : null;const hosts = normalizeAllowedHosts(allowedHosts);+ const blocked = normalizeBlockedHosts(blockedHosts);+ const approvalThresholdAtomics =+ approvalThresholdUsd != null ? usdToAtomics(normalizeApprovalThreshold(approvalThresholdUsd)) : null;+ const perRailDaily = normalizePerRailDaily(perRailDailyUsd);const ttl = normalizeTtl(expirySeconds);const net = network === 'base' ? 'base' : 'solana';const cleanLabel = String(label ?? '').trim().slice(0, MAX_LABEL_LEN);@@ -137,15 +173,21 @@ export async function createPaymentSession({const [row] = await sql`INSERT INTO payment_sessions(id, user_id, agent_id, label, budget_usdc, max_per_tx_usdc,- allowed_hosts, network, status, expires_at, token_hash, session_metadata)+ allowed_hosts, blocked_hosts, approval_threshold_usdc, per_rail_daily_usdc,+ network, status, expires_at, token_hash, session_metadata)VALUES(${sessionId}, ${userId}, ${agentId ?? null},${cleanLabel}, ${budgetAtomics.toString()},${maxPerTxAtomics != null ? maxPerTxAtomics.toString() : null},- ${hosts}, ${net}, 'active', ${expiresAt.toISOString()},+ ${hosts}, ${blocked},+ ${approvalThresholdAtomics != null ? approvalThresholdAtomics.toString() : null},+ ${JSON.stringify(perRailDaily)}::jsonb,+ ${net}, 'active', ${expiresAt.toISOString()},${tokenHash}, ${JSON.stringify(metadata)}::jsonb)RETURNING id, user_id, agent_id, label, budget_usdc, spent_usdc,- max_per_tx_usdc, allowed_hosts, network, status, expires_at,+ max_per_tx_usdc, allowed_hosts, blocked_hosts,+ approval_threshold_usdc, per_rail_daily_usdc,+ network, status, expires_at,session_metadata, created_at`;@@ -167,7 +209,9 @@ export async function createPaymentSession({export async function getPaymentSession(sessionId, userId) {const [row] = await sql`SELECT id, user_id, agent_id, label, budget_usdc, spent_usdc,- max_per_tx_usdc, allowed_hosts, network, status, expires_at,+ max_per_tx_usdc, allowed_hosts, blocked_hosts,+ approval_threshold_usdc, per_rail_daily_usdc,+ network, status, expires_at,session_metadata, created_at, updated_atFROM payment_sessionsWHERE id = ${sessionId}@@ -184,7 +228,9 @@ export async function listPaymentSessions(userId, { status, limit = 20, cursor }const lim = Math.min(Math.max(Math.floor(Number(limit)) || 20, 1), 100);const rows = await sql`SELECT id, user_id, agent_id, label, budget_usdc, spent_usdc,- max_per_tx_usdc, allowed_hosts, network, status, expires_at,+ max_per_tx_usdc, allowed_hosts, blocked_hosts,+ approval_threshold_usdc, per_rail_daily_usdc,+ network, status, expires_at,session_metadata, created_at, updated_atFROM payment_sessionsWHERE user_id = ${userId}@@ -207,7 +253,11 @@ export async function listPaymentSessions(userId, { status, limit = 20, cursor }* Only label, allowed_hosts, and max_per_tx_usd can be changed after creation.* Returns the updated session row or null if not found / not owned / not active.*/-export async function updatePaymentSession(sessionId, userId, { label, allowedHosts, maxPerTxUsd } = {}) {+export async function updatePaymentSession(+ sessionId,+ userId,+ { label, allowedHosts, maxPerTxUsd, blockedHosts, approvalThresholdUsd, perRailDailyUsd } = {},+) {const params = { id: sessionId, userId };if (label !== undefined) {@@ -219,6 +269,16 @@ export async function updatePaymentSession(sessionId, userId, { label, allowedHoif (maxPerTxUsd !== undefined) {params.maxPerTxAtomics = maxPerTxUsd != null ? usdToAtomics(normalizeMaxPerTx(maxPerTxUsd)).toString() : null;}+ if (blockedHosts !== undefined) {+ params.blockedHosts = normalizeBlockedHosts(blockedHosts);+ }+ if (approvalThresholdUsd !== undefined) {+ params.approvalThresholdAtomics =+ approvalThresholdUsd != null ? usdToAtomics(normalizeApprovalThreshold(approvalThresholdUsd)).toString() : null;+ }+ if (perRailDailyUsd !== undefined) {+ params.perRailDaily = normalizePerRailDaily(perRailDailyUsd);+ }const [row] = await sql`UPDATE payment_sessions@@ -226,10 +286,15 @@ export async function updatePaymentSession(sessionId, userId, { label, allowedHolabel = CASE WHEN ${params.label !== undefined}::boolean THEN ${params.label ?? null} ELSE label END,allowed_hosts = CASE WHEN ${params.allowedHosts !== undefined}::boolean THEN ${params.allowedHosts ?? []} ELSE allowed_hosts END,max_per_tx_usdc = CASE WHEN ${params.maxPerTxAtomics !== undefined}::boolean THEN ${params.maxPerTxAtomics ?? null}::bigint ELSE max_per_tx_usdc END,+ blocked_hosts = CASE WHEN ${params.blockedHosts !== undefined}::boolean THEN ${params.blockedHosts ?? []} ELSE blocked_hosts END,+ approval_threshold_usdc = CASE WHEN ${params.approvalThresholdAtomics !== undefined}::boolean THEN ${params.approvalThresholdAtomics ?? null}::bigint ELSE approval_threshold_usdc END,+ per_rail_daily_usdc = CASE WHEN ${params.perRailDaily !== undefined}::boolean THEN ${params.perRailDaily != null ? JSON.stringify(params.perRailDaily) : '{}'}::jsonb ELSE per_rail_daily_usdc END,updated_at = now()WHERE id = ${sessionId} AND user_id = ${userId} AND status = 'active'RETURNING id, user_id, agent_id, label, budget_usdc, spent_usdc,- max_per_tx_usdc, allowed_hosts, network, status, expires_at,+ max_per_tx_usdc, allowed_hosts, blocked_hosts,+ approval_threshold_usdc, per_rail_daily_usdc,+ network, status, expires_at,session_metadata, created_at, updated_at`;return row ? formatSession(row) : null;@@ -274,7 +339,8 @@ export async function listSessionExecutions(sessionId, userId, { limit = 20, curconst rows = await sql`SELECT id, endpoint_url, endpoint_host, method, amount_usdc,network, tx_hash, payer_address, payee_address,- status, error_code, duration_ms, created_at+ status, error_code, duration_ms, created_at,+ policy_digest, verdict_code, verdict_signature, verdict_signed_atFROM payment_session_executionsWHERE session_id = ${sessionId}AND user_id = ${userId}@@ -344,6 +410,9 @@ function formatSession(row) {remaining_usd: atomicsToUsd(BigInt(row.budget_usdc) - BigInt(row.spent_usdc)),max_per_tx_usd: row.max_per_tx_usdc != null ? atomicsToUsd(row.max_per_tx_usdc) : null,allowed_hosts: row.allowed_hosts ?? [],+ blocked_hosts: row.blocked_hosts ?? [],+ approval_threshold_usd: row.approval_threshold_usdc != null ? atomicsToUsd(row.approval_threshold_usdc) : null,+ per_rail_daily_usd: row.per_rail_daily_usdc ?? {},network: row.network,status: row.status,expires_at: row.expires_at,@@ -368,5 +437,9 @@ function formatExecution(row) {error_code: row.error_code ?? null,duration_ms: row.duration_ms ?? null,created_at: row.created_at,+ policy_digest: row.policy_digest ?? null,+ verdict_code: row.verdict_code ?? null,+ verdict_signature: row.verdict_signature ?? null,+ verdict_signed_at: row.verdict_signed_at ?? null,};}diff --git a/api/_lib/pay/policy.js b/api/_lib/pay/policy.jsindex 071d72cd6..2caf0dcc2 100644--- a/api/_lib/pay/policy.js+++ b/api/_lib/pay/policy.js@@ -20,7 +20,11 @@// The authoritative check is the SQL `UPDATE ... WHERE (budget - spent) >= amt`// in the governor. This module exposes `budgetVerdict()` for prediction and for// building the error message, and the governor calls it only to describe a-// failure the database already decided.+// failure the database already decided. The same split applies to+// `railDailyVerdict()` below: authoritative enforcement is an atomic reserve+// against payment_session_rail_reservations, this is the advisory prediction.++import { createHash } from 'node:crypto';/*** The limits session creation enforces (api/_lib/pay/payment-session.js).@@ -50,6 +54,48 @@ export function atomicsToUsd(atomics) {return Number(atomics) / USDC_SCALE;}+// CAIP-2 chain identifiers for the two networks sessions settle on, matching+// the literal strings x402 challenges quote in `accept.network` (and what+// payment_session_executions.network stores). per_rail_daily_usdc is keyed by+// these, not by the session's short 'solana'/'base' network name, so the cap+// still means the right thing if a session ever settles on more than one rail.+export const CAIP2_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';+export const CAIP2_BASE_MAINNET = 'eip155:8453';+export const NETWORK_TO_CAIP2 = Object.freeze({+ solana: CAIP2_SOLANA_MAINNET,+ base: CAIP2_BASE_MAINNET,+});++/**+ * Normalize a caller-supplied per-rail-daily-cap map to CAIP-2 keys.+ * Accepts either a short network name ('solana', 'base') or a literal CAIP-2+ * id as a key; drops anything that is not a positive number.+ */+export function canonicalizePerRailDaily(raw) {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};+ const out = {};+ for (const [key, value] of Object.entries(raw)) {+ const n = Number(value);+ if (!Number.isFinite(n) || n <= 0) continue;+ const caip2 = NETWORK_TO_CAIP2[key] ?? (key.includes(':') ? key : null);+ if (!caip2) continue;+ out[caip2] = n;+ }+ return out;+}++/** The per_rail_daily_usdc cap for the session's own settlement network, in atomics, or null if unset. */+export function resolveRailDailyCapAtomics(network, perRailDailyUsd) {+ if (!perRailDailyUsd || typeof perRailDailyUsd !== 'object') return null;+ const caip2 = NETWORK_TO_CAIP2[network] ?? null;+ if (!caip2) return null;+ const usd = perRailDailyUsd[caip2];+ if (usd == null) return null;+ const n = Number(usd);+ if (!Number.isFinite(n) || n <= 0) return null;+ return usdToAtomics(n);+}+/** Bare lowercase hostname from a URL or an already-bare host. Never throws. */export function normalizeHost(raw) {const s = String(raw || '').trim().toLowerCase();@@ -170,19 +216,95 @@ export function budgetVerdict(amountAtomics, remainingAtomics) {};}+/**+ * Rule (denylist): the target host must NOT be on the session's blocked list.+ *+ * Checked right after the allowlist, and wins over it: a host that somehow+ * matches both an allow entry and a block entry is blocked. An operator who+ * explicitly denylists a merchant expects that to be the final word even if+ * the allowlist was written broadly (e.g. `*.example.com` allowed, one bad+ * sub-merchant blocked).+ */+export function blockedHostVerdict(url, blockedHosts) {+ const canonical = canonicalizeAllowlist(blockedHosts);+ if (canonical.length === 0) return null;++ let targetHost;+ try {+ targetHost = new URL(url).hostname.toLowerCase();+ } catch {+ return null; // an unparseable URL is already reported by allowlistVerdict when an allowlist is set+ }++ if (!canonical.some((entry) => hostMatches(targetHost, entry))) return null;++ return {+ code: 'host_blocked',+ message: `Host ${targetHost} is on this session's blocked list`,+ detail: { host: targetHost, blocked_hosts: canonical },+ };+}++/**+ * Rule: this payment must not push the session's rolling 24h spend on its+ * settlement rail over `railDailyCapAtomics`.+ *+ * Advisory here (see the module header): the authoritative check is an+ * atomic reserve in the governor. `railSpentAtomics` is spend already+ * reserved in the current window, passed in so this stays a pure function.+ */+export function railDailyVerdict(amountAtomics, railSpentAtomics, railDailyCapAtomics) {+ if (railDailyCapAtomics == null) return null;+ const cap = BigInt(railDailyCapAtomics);+ const spent = BigInt(railSpentAtomics ?? 0);+ const amount = BigInt(amountAtomics);+ if (spent + amount <= cap) return null;+ return {+ code: 'rail_daily_exceeded',+ message: `Payment would push this rail's 24h spend to $${atomicsToUsd(spent + amount)}, over the $${atomicsToUsd(cap)} daily cap`,+ detail: {+ would_spend_usd: atomicsToUsd(spent + amount),+ spent_so_far_usd: atomicsToUsd(spent),+ cap_usd: atomicsToUsd(cap),+ },+ };+}++/**+ * Rule (last): a payment over the approval threshold does not settle on its+ * own, it needs a human to approve it first.+ *+ * Deliberately evaluated last: a call that is going to be rejected anyway+ * (bad host, expired session, insufficient budget) should fail with that+ * reason, not interrupt a human for an approval that would not have mattered.+ */+export function approvalVerdict(amountAtomics, approvalThresholdAtomics) {+ if (approvalThresholdAtomics == null) return null;+ const threshold = BigInt(approvalThresholdAtomics);+ const amount = BigInt(amountAtomics);+ if (amount <= threshold) return null;+ return {+ code: 'requires_approval',+ message: `Payment $${atomicsToUsd(amount)} exceeds the $${atomicsToUsd(threshold)} approval threshold and needs human approval`,+ detail: { amount_usd: atomicsToUsd(amount), threshold_usd: atomicsToUsd(threshold) },+ };+}+/*** Run every rule in enforcement order and return the first rejection, or null.** Order matters and mirrors the governor exactly: state, then expiry, then- * allowlist, then ceiling, then budget. A caller that reordered these would- * report "insufficient budget" for a call that is actually blocked by the- * allowlist, which sends the user off to fund a session that still would not- * work.+ * allowlist, then the block denylist, then the per-transaction ceiling, then+ * the rolling rail cap, then budget, then approval last. A caller that+ * reordered these would report "insufficient budget" for a call that is+ * actually blocked by the allowlist, which sends the user off to fund a+ * session that still would not work, or would interrupt a human for+ * approval on a call that was always going to be refused for another reason.** @param {object} call* @param {string} call.url target endpoint* @param {bigint|string|number} call.amountAtomics price in USDC atomics- * @param {object} call.policy { status, expiresAt, allowedHosts, maxPerTxAtomics }+ * @param {object} call.policy { status, expiresAt, allowedHosts, blockedHosts, maxPerTxAtomics, railSpentAtomics, railDailyCapAtomics, approvalThresholdAtomics }* @param {bigint|string|number} call.remainingAtomics budget left before this call* @param {Date} [call.now]* @returns {{code: string, message: string, detail: object} | null}@@ -192,8 +314,11 @@ export function evaluateCall({ url, amountAtomics, policy, remainingAtomics, nowstatusVerdict(policy.status ?? 'active') ??expiryVerdict(policy.expiresAt ?? null, now) ??allowlistVerdict(url, policy.allowedHosts) ??+ blockedHostVerdict(url, policy.blockedHosts) ??perTxVerdict(amountAtomics, policy.maxPerTxAtomics ?? null) ??- budgetVerdict(amountAtomics, remainingAtomics)+ railDailyVerdict(amountAtomics, policy.railSpentAtomics ?? 0, policy.railDailyCapAtomics ?? null) ??+ budgetVerdict(amountAtomics, remainingAtomics) ??+ approvalVerdict(amountAtomics, policy.approvalThresholdAtomics ?? null));}@@ -210,12 +335,17 @@ export function evaluateCall({ url, amountAtomics, policy, remainingAtomics, now* failure path either never reserved or rolled back.** @param {Array<{url: string, amountAtomics: bigint|string|number, [k: string]: any}>} calls- * @param {object} policy { budgetAtomics, maxPerTxAtomics, allowedHosts, status, expiresAt }+ * @param {object} policy { budgetAtomics, maxPerTxAtomics, allowedHosts, blockedHosts, status, expiresAt, railDailyCapAtomics, railSpentAtomics, approvalThresholdAtomics }* @param {Date} [now]*/export function replay(calls, policy, now = new Date()) {const budget = BigInt(policy.budgetAtomics ?? 0);+ const railCap = policy.railDailyCapAtomics != null ? BigInt(policy.railDailyCapAtomics) : null;let spent = 0n;+ // Starting point is whatever the rail already spent in the current window+ // before this replay began, so a simulation can model "half the daily cap+ // is already used" the same way the governor's own pre-check does.+ let railSpent = BigInt(policy.railSpentAtomics ?? 0);const steps = [];for (const call of calls) {@@ -224,12 +354,18 @@ export function replay(calls, policy, now = new Date()) {const rejection = evaluateCall({url: call.url,amountAtomics: amount,- policy,+ policy: { ...policy, railDailyCapAtomics: railCap, railSpentAtomics: railSpent },remainingAtomics: remainingBefore,now,});- if (!rejection) spent += amount;+ // A denied call (including one that only needs approval) consumes+ // nothing, matching the enforcer: budget and the rail reservation are+ // only taken on the success path.+ if (!rejection) {+ spent += amount;+ railSpent += amount;+ }steps.push({call,@@ -238,8 +374,52 @@ export function replay(calls, policy, now = new Date()) {amountAtomics: amount,remainingBeforeAtomics: remainingBefore,remainingAfterAtomics: budget - spent,+ railSpentAfterAtomics: railSpent,});}- return { steps, spentAtomics: spent, remainingAtomics: budget - spent };+ return { steps, spentAtomics: spent, remainingAtomics: budget - spent, railSpentAtomics: railSpent };+}++// ── Signed verdicts ─────────────────────────────────────────────────────────+// Every verdict the governor produces (allow or reject) is stored next to its+// execution with a digest of the policy it was judged against and an HMAC+// over {verdict, digest, request hash, timestamp}. Hashing is pure and lives+// here so the digest a simulator shows and the one the governor signs are+// computed by the same code; the HMAC itself needs a server secret and lives+// in spend-governor.js, the only place in this module graph allowed to touch one.++/** Deterministic JSON: object keys sorted, so the same policy always hashes the same way. */+function stableStringify(value) {+ if (value === null || typeof value !== 'object') return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;+ const keys = Object.keys(value).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;+}++/** The exact fields that govern a verdict, normalized so unrelated row noise (timestamps, ids) can't shift the digest. */+export function canonicalPolicySnapshot(session) {+ return {+ status: session.status,+ expires_at: session.expires_at ? new Date(session.expires_at).toISOString() : null,+ budget_usdc: String(session.budget_usdc ?? '0'),+ max_per_tx_usdc: session.max_per_tx_usdc != null ? String(session.max_per_tx_usdc) : null,+ allowed_hosts: canonicalizeAllowlist(session.allowed_hosts),+ blocked_hosts: canonicalizeAllowlist(session.blocked_hosts),+ approval_threshold_usdc: session.approval_threshold_usdc != null ? String(session.approval_threshold_usdc) : null,+ per_rail_daily_usdc: session.per_rail_daily_usdc ?? {},+ network: session.network,+ };+}++/** sha256 hex digest of the canonical policy snapshot. Tampering with any governed field changes this. */+export function computePolicyDigest(session) {+ return createHash('sha256').update(stableStringify(canonicalPolicySnapshot(session))).digest('hex');+}++/** sha256 hex digest binding a verdict to the specific call it was judged for. */+export function computeRequestHash({ sessionId, url, amountAtomics }) {+ return createHash('sha256')+ .update(stableStringify({ session_id: sessionId, url, amount_atomics: String(amountAtomics) }))+ .digest('hex');}diff --git a/api/_lib/pay/spend-governor.js b/api/_lib/pay/spend-governor.jsindex c82dbaa28..3c1e75ea3 100644--- a/api/_lib/pay/spend-governor.js+++ b/api/_lib/pay/spend-governor.js@@ -22,18 +22,21 @@// rollbackReservation() if the downstream x402 payment fails after the budget has// been reserved — otherwise the session bleeds budget on failed payments.-import { createHmac, randomBytes } from 'node:crypto';+import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';import { sql } from '../db.js';+import { runLocked } from '../locked-sql.js';import { env } from '../env.js';import {usdToAtomics,atomicsToUsd,normalizeHost,- statusVerdict,- expiryVerdict,- allowlistVerdict,- perTxVerdict,+ evaluateCall,budgetVerdict,+ railDailyVerdict,+ resolveRailDailyCapAtomics,+ computePolicyDigest,+ computeRequestHash,+ NETWORK_TO_CAIP2,} from './policy.js';// The policy predicates below are shared with the dry-run simulator@@ -54,8 +57,11 @@ export class SpendGovernorError extends Error {session_inactive: 403,session_expired: 403,allowlist_blocked: 403,+ host_blocked: 403,per_tx_exceeded: 402,+ rail_daily_exceeded: 402,insufficient_budget: 402,+ requires_approval: 403,invalid_token: 401,}[code] ?? 403;}@@ -75,6 +81,34 @@ function hmacKey() {return k;}+// Verdict signing. The HMAC needs its own key (PAY_VERDICT_HMAC_KEY), not+// PAYMENT_SESSION_SECRET: rotating the token secret must not also quietly+// invalidate every previously stored verdict signature, and vice versa.+function verdictHmacKey() {+ const k = env.PAY_VERDICT_HMAC_KEY;+ if (!k) throw new Error('PAY_VERDICT_HMAC_KEY is not configured');+ return k;+}++function verdictPayload({ verdictCode, policyDigest, requestHash, timestamp }) {+ return `${verdictCode}|${policyDigest}|${requestHash}|${timestamp}`;+}++/** HMAC-SHA256 over {verdict, policy digest, request hash, timestamp}, so a stored verdict is tamper-evident. */+export function signVerdict({ verdictCode, policyDigest, requestHash, timestamp }) {+ return createHmac('sha256', verdictHmacKey())+ .update(verdictPayload({ verdictCode, policyDigest, requestHash, timestamp }))+ .digest('hex');+}++/** Constant-time check that `signature` is what signVerdict() would produce for these exact fields. */+export function verifyVerdictSignature({ verdictCode, policyDigest, requestHash, timestamp, signature }) {+ const expected = Buffer.from(signVerdict({ verdictCode, policyDigest, requestHash, timestamp }), 'hex');+ const given = Buffer.from(String(signature ?? ''), 'hex');+ if (expected.length !== given.length) return false;+ return timingSafeEqual(expected, given);+}+export function generateSessionToken(sessionId) {const rand = randomBytes(16).toString('hex');return `${TOKEN_PREFIX}${sessionId}_${rand}`;@@ -108,9 +142,19 @@ export function extractSessionId(token) {return isSessionId(id) ? id : null;}-/** Turn a policy rejection from policy.js into the thrown governance error. */-function throwVerdict(verdict) {- if (verdict) throw new SpendGovernorError(verdict.code, verdict.message, verdict.detail);+/**+ * Turn a policy rejection from policy.js into the thrown governance error,+ * carrying a signature over the verdict so it can be stored tamper-evidently+ * alongside whatever execution record the caller writes.+ */+function throwSigned(verdict, { policyDigest, requestHash, timestamp }) {+ const signature = signVerdict({ verdictCode: verdict.code, policyDigest, requestHash, timestamp });+ throw new SpendGovernorError(verdict.code, verdict.message, {+ ...verdict.detail,+ policy_digest: policyDigest,+ verdict_signature: signature,+ verdict_signed_at: timestamp,+ });}/**@@ -124,7 +168,9 @@ export async function verifySessionToken(token) {const hash = hashToken(token);const [row] = await sql`SELECT id, user_id, agent_id, label, budget_usdc, spent_usdc,- max_per_tx_usdc, allowed_hosts, network, connector_ref,+ max_per_tx_usdc, allowed_hosts, blocked_hosts,+ approval_threshold_usdc, per_rail_daily_usdc,+ network, connector_ref,status, expires_at, session_metadataFROM payment_sessionsWHERE id = ${sessionId} AND token_hash = ${hash}@@ -138,43 +184,110 @@ export async function verifySessionToken(token) {/*** Enforce governance policy and atomically reserve budget for a payment.*+ * Every advisory rule (status, expiry, allowlist, blocked hosts, per-tx+ * ceiling, rolling rail cap, budget, approval threshold) runs through the+ * exact same evaluateCall() the simulator calls, in the exact same order, so+ * a verdict here and a predicted one can never disagree (that parity is+ * covered by tests/payment-session-governor.test.js). Only the two atomic+ * reservations after that, the rail-daily insert and the budget UPDATE,+ * are enforcement-only; evaluateCall's budget/rail checks above were already+ * advisory predictions of what those statements are about to decide for real.+ ** @param {object} opts* @param {string} opts.token - Session bearer token* @param {string} opts.url - Target endpoint URL (for allowlist check)* @param {bigint} opts.amountAtomics - Payment amount in USDC atomics (6 decimals)- * @returns {Promise<{ session: object, reservationId: string }>}+ * @returns {Promise<{ session: object, reservationId: string, railReservationId: string|null, policyDigest: string, verdictCode: string, verdictSignature: string, verdictSignedAt: string }>}* @throws {SpendGovernorError} on any policy violation*/export async function reserveSessionSpend({ token, url, amountAtomics }) {- // Phase 1: token verificationconst session = await verifySessionToken(token);+ const now = new Date();+ const amount = BigInt(amountAtomics);- // Phase 2: status check- throwVerdict(statusVerdict(session.status));+ const railCaip2 = NETWORK_TO_CAIP2[session.network] ?? null;+ const railCapAtomics = resolveRailDailyCapAtomics(session.network, session.per_rail_daily_usdc);- // Phase 3: time expiry (belt-and-suspenders; DB sweep also marks expired rows)- const now = new Date();- const expired = expiryVerdict(session.expires_at, now);- if (expired) {- // Mark it expired so future checks skip the DB read+ let railSpentAtomics = 0n;+ if (railCapAtomics != null && railCaip2) {+ const [row] = await sql`+ SELECT coalesce(sum(amount_usdc), 0) AS spent+ FROM payment_session_rail_reservations+ WHERE session_id = ${session.id}+ AND network = ${railCaip2}+ AND created_at > now() - interval '24 hours'+ `;+ railSpentAtomics = BigInt(row?.spent ?? 0);+ }++ const remainingAtomics = BigInt(session.budget_usdc) - BigInt(session.spent_usdc);+ const policy = {+ status: session.status,+ expiresAt: session.expires_at,+ allowedHosts: session.allowed_hosts,+ blockedHosts: session.blocked_hosts,+ maxPerTxAtomics: session.max_per_tx_usdc,+ railDailyCapAtomics: railCapAtomics,+ railSpentAtomics,+ approvalThresholdAtomics: session.approval_threshold_usdc,+ };++ const verdict = evaluateCall({ url, amountAtomics: amount, policy, remainingAtomics, now });++ const policyDigest = computePolicyDigest(session);+ const requestHash = computeRequestHash({ sessionId: session.id, url, amountAtomics: amount });+ const timestamp = now.toISOString();++ if (verdict?.code === 'session_expired') {+ // Belt-and-suspenders; a DB sweep also marks expired rows. Mark it now+ // so the next call skips straight to this same rejection.await sql`UPDATE payment_sessions SET status = 'expired', updated_at = now()WHERE id = ${session.id} AND status = 'active'`.catch(() => {});- throwVerdict(expired);}- // Phase 4: URL allowlist enforcement- throwVerdict(allowlistVerdict(url, session.allowed_hosts));+ if (verdict) throwSigned(verdict, { policyDigest, requestHash, timestamp });- // Phase 5: per-transaction ceiling- throwVerdict(perTxVerdict(amountAtomics, session.max_per_tx_usdc));+ // Atomic rail-daily reservation, ahead of the budget reservation so a+ // rail-cap miss never touches spent_usdc. The advisory lock is taken in+ // its own statement (see api/_lib/locked-sql.js) so a request that waited+ // on it re-reads the window sum fresh, after the winner's reservation+ // landed, instead of against a stale pre-commit snapshot.+ let railReservationId = null;+ if (railCapAtomics != null && railCaip2) {+ const rows = await runLocked(+ [`pay_rail:${session.id}:${railCaip2}`],+ sql`+ WITH window_spend AS (+ SELECT coalesce(sum(amount_usdc), 0) AS spent+ FROM payment_session_rail_reservations+ WHERE session_id = ${session.id}+ AND network = ${railCaip2}+ AND created_at > now() - interval '24 hours'+ )+ INSERT INTO payment_session_rail_reservations (session_id, network, amount_usdc)+ SELECT ${session.id}, ${railCaip2}, ${amount.toString()}+ FROM window_spend+ WHERE window_spend.spent + ${amount.toString()}::bigint <= ${railCapAtomics.toString()}::bigint+ RETURNING id+ `,+ );+ if (!rows[0]) {+ const failVerdict = railDailyVerdict(amount, railSpentAtomics, railCapAtomics) ?? {+ code: 'rail_daily_exceeded',+ message: "This rail's 24h spend cap was reached by a concurrent payment",+ detail: {},+ };+ throwSigned(failVerdict, { policyDigest, requestHash, timestamp });+ }+ railReservationId = rows[0].id;+ }- // Phase 6: atomic budget reservation- // The WHERE clause ensures (budget_usdc - spent_usdc) >= amountAtomics before- // incrementing — race-safe: two concurrent requests cannot both succeed if- // only one fits in the remaining budget.- const amount = BigInt(amountAtomics);+ // Atomic budget reservation. The WHERE clause ensures+ // (budget_usdc - spent_usdc) >= amountAtomics before incrementing,+ // race-safe: two concurrent requests cannot both succeed if only one fits+ // in the remaining budget.const [updated] = await sql`UPDATE payment_sessionsSET spent_usdc = spent_usdc + ${amount.toString()},@@ -186,6 +299,9 @@ export async function reserveSessionSpend({ token, url, amountAtomics }) {`;if (!updated) {+ if (railReservationId) {+ await sql`DELETE FROM payment_session_rail_reservations WHERE id = ${railReservationId}`.catch(() => {});+ }// Could be exhausted mid-race; check to give a precise errorconst [fresh] = await sql`SELECT budget_usdc, spent_usdc FROM payment_sessions WHERE id = ${session.id}@@ -193,13 +309,12 @@ export async function reserveSessionSpend({ token, url, amountAtomics }) {const remaining = fresh ? BigInt(fresh.budget_usdc) - BigInt(fresh.spent_usdc) : 0n;// The SQL predicate already decided; budgetVerdict only phrases the failure,// using the same wording the simulator shows for a predicted shortfall.- throwVerdict(- budgetVerdict(amount, remaining) ?? {- code: 'insufficient_budget',- message: 'Session was not active when the payment was reserved',- detail: { need_usd: atomicsToUsd(amount), remaining_usd: atomicsToUsd(remaining) },- },- );+ const failVerdict = budgetVerdict(amount, remaining) ?? {+ code: 'insufficient_budget',+ message: 'Session was not active when the payment was reserved',+ detail: { need_usd: atomicsToUsd(amount), remaining_usd: atomicsToUsd(remaining) },+ };+ throwSigned(failVerdict, { policyDigest, requestHash, timestamp });}// If the session is now fully consumed, mark it exhausted@@ -210,15 +325,27 @@ export async function reserveSessionSpend({ token, url, amountAtomics }) {`.catch(() => {});}+ const verdictCode = 'allowed';+ const verdictSignature = signVerdict({ verdictCode, policyDigest, requestHash, timestamp });const reservationId = `res_${session.id}_${Date.now()}`;- return { session: { ...session, spent_usdc: updated.spent_usdc }, reservationId };+ return {+ session: { ...session, spent_usdc: updated.spent_usdc },+ reservationId,+ railReservationId,+ policyDigest,+ verdictCode,+ verdictSignature,+ verdictSignedAt: timestamp,+ };}/**- * Roll back a budget reservation after a failed payment.- * Decrements spent_usdc by the reserved amount and restores 'active' if exhausted.+ * Roll back a reservation after a failed payment.+ * Decrements spent_usdc by the reserved amount and restores 'active' if+ * exhausted, and releases the rail-daily reservation (if any) so a failed+ * call never permanently eats into the next day's rail budget.*/-export async function rollbackReservation(sessionId, amountAtomics) {+export async function rollbackReservation(sessionId, amountAtomics, { railReservationId } = {}) {const amount = BigInt(amountAtomics);await sql`UPDATE payment_sessions@@ -228,6 +355,9 @@ export async function rollbackReservation(sessionId, amountAtomics) {WHERE id = ${sessionId}AND status IN ('active', 'exhausted')`;+ if (railReservationId) {+ await sql`DELETE FROM payment_session_rail_reservations WHERE id = ${railReservationId}`.catch(() => {});+ }}/**@@ -249,6 +379,10 @@ export async function recordExecution({responseBody,durationMs,idempotencyKey,+ policyDigest,+ verdictCode,+ verdictSignature,+ verdictSignedAt,}) {const host = (() => {try { return new URL(endpointUrl).hostname; }@@ -260,14 +394,17 @@ export async function recordExecution({(session_id, user_id, endpoint_url, endpoint_host, method,amount_usdc, network, tx_hash, payer_address, payee_address,status, error_code, error_message, response_body,- duration_ms, idempotency_key)+ duration_ms, idempotency_key,+ policy_digest, verdict_code, verdict_signature, verdict_signed_at)VALUES(${sessionId}, ${userId}, ${endpointUrl}, ${host}, ${method ?? 'GET'},${amountAtomics.toString()}, ${network}, ${txHash ?? null},${payerAddress ?? null}, ${payeeAddress ?? null},${status}, ${errorCode ?? null}, ${errorMessage ?? null},${responseBody != null ? JSON.stringify(responseBody) : null},- ${durationMs ?? null}, ${idempotencyKey ?? null})+ ${durationMs ?? null}, ${idempotencyKey ?? null},+ ${policyDigest ?? null}, ${verdictCode ?? null},+ ${verdictSignature ?? null}, ${verdictSignedAt ?? null})ON CONFLICT (idempotency_key) DO NOTHING`;}diff --git a/api/pay/execute.js b/api/pay/execute.jsindex 7c21e5ed4..549758875 100644--- a/api/pay/execute.js+++ b/api/pay/execute.js@@ -317,7 +317,7 @@ export default wrap(async (req, res) => {const amountUsd = atomicsToUsd(amountAtomics);// Phase 2: governance enforcement (check session, allowlist, budget) is atomic- let sessionRecord, reservationId;+ let sessionRecord, reservationId, railReservationId, policyDigest, verdictCode, verdictSignature, verdictSignedAt;try {const reservation = await reserveSessionSpend({token: sessionToken,@@ -326,6 +326,11 @@ export default wrap(async (req, res) => {});sessionRecord = reservation.session;reservationId = reservation.reservationId;+ railReservationId = reservation.railReservationId;+ policyDigest = reservation.policyDigest;+ verdictCode = reservation.verdictCode;+ verdictSignature = reservation.verdictSignature;+ verdictSignedAt = reservation.verdictSignedAt;} catch (err) {if (err instanceof SpendGovernorError) {return error(res, err.status, err.code, err.message, err.detail);@@ -341,7 +346,7 @@ export default wrap(async (req, res) => {try {keypair = loadSolanaKeypair();} catch (err) {- await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});+ await rollbackReservation(sessionRecord.id, amountAtomics, { railReservationId }).catch(() => {});// loadSolanaKeypair separates "no key configured" from "key present but// undecodable". Collapsing both into wallet_unconfigured sent an operator// looking for a missing env var that was in fact already set.@@ -363,7 +368,7 @@ export default wrap(async (req, res) => {resourceUrl: resource.url || targetUrl,});} catch (err) {- await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});+ await rollbackReservation(sessionRecord.id, amountAtomics, { railReservationId }).catch(() => {});if (isRpcUnavailable(err)) {// No funds moved: the chain could not be read and nothing was cached.// Typed + retryable so the agent backs off instead of treating it as a@@ -401,6 +406,10 @@ export default wrap(async (req, res) => {errorMessage: err?.message,durationMs: Date.now() - t0,idempotencyKey,+ policyDigest,+ verdictCode,+ verdictSignature,+ verdictSignedAt,}).catch(() => {});return error(res, 502, 'settle_uncertain','Payment was submitted but confirmation was not received. Do not retry immediately.');@@ -414,7 +423,7 @@ export default wrap(async (req, res) => {// Explicit pre-settlement rejection: no funds moved, safe to roll backif (paid.status === 402) {- await rollbackReservation(sessionRecord.id, amountAtomics).catch(() => {});+ await rollbackReservation(sessionRecord.id, amountAtomics, { railReservationId }).catch(() => {});await recordExecution({sessionId: sessionRecord.id,userId: sessionRecord.user_id,@@ -430,6 +439,10 @@ export default wrap(async (req, res) => {errorMessage: 'Service rejected the payment before settlement',durationMs,idempotencyKey,+ policyDigest,+ verdictCode,+ verdictSignature,+ verdictSignedAt,}).catch(() => {});return error(res, 402, 'payment_rejected','Service rejected the payment before settlement. Budget has been restored.',@@ -454,6 +467,10 @@ export default wrap(async (req, res) => {responseBody: typeof paidJson === 'object' ? paidJson : null,durationMs,idempotencyKey,+ policyDigest,+ verdictCode,+ verdictSignature,+ verdictSignedAt,}).catch(() => {});return error(res, 502, 'upstream_error',`Endpoint returned HTTP ${paid.status} after payment. Check wallet activity before retrying.`);@@ -474,6 +491,10 @@ export default wrap(async (req, res) => {responseBody: typeof paidJson === 'object' ? paidJson : null,durationMs,idempotencyKey,+ policyDigest,+ verdictCode,+ verdictSignature,+ verdictSignedAt,}).catch(() => {});return json(res, 200, {diff --git a/api/pay/session.js b/api/pay/session.jsindex 475d2bc06..64646ecbd 100644--- a/api/pay/session.js+++ b/api/pay/session.js@@ -106,6 +106,9 @@ export default wrap(async (req, res) => {budgetUsd: body.budget_usd,maxPerTxUsd: body.max_per_tx_usd ?? null,allowedHosts: body.allowed_hosts ?? [],+ blockedHosts: body.blocked_hosts ?? [],+ approvalThresholdUsd: body.approval_threshold_usd ?? null,+ perRailDailyUsd: body.per_rail_daily_usd ?? null,network: body.network ?? 'solana',expirySeconds: body.expiry_seconds ?? 3600,metadata: body.metadata ?? {},@@ -193,8 +196,16 @@ export default wrap(async (req, res) => {if (typeof body.label === 'string') updates.label = body.label.trim();if (Array.isArray(body.allowed_hosts)) updates.allowedHosts = body.allowed_hosts;if (body.max_per_tx_usd !== undefined) updates.maxPerTxUsd = body.max_per_tx_usd;+ if (Array.isArray(body.blocked_hosts)) updates.blockedHosts = body.blocked_hosts;+ if (body.approval_threshold_usd !== undefined) updates.approvalThresholdUsd = body.approval_threshold_usd;+ if (body.per_rail_daily_usd !== undefined) updates.perRailDailyUsd = body.per_rail_daily_usd;if (Object.keys(updates).length === 0) {- return error(res, 400, 'nothing_to_update', 'Provide at least one of: label, allowed_hosts, max_per_tx_usd');+ return error(+ res,+ 400,+ 'nothing_to_update',+ 'Provide at least one of: label, allowed_hosts, max_per_tx_usd, blocked_hosts, approval_threshold_usd, per_rail_daily_usd',+ );}const result = await updatePaymentSession(id, user.id, updates);diff --git a/api/pay/simulate.js b/api/pay/simulate.jsindex cfaf23488..26448e71d 100644--- a/api/pay/simulate.js+++ b/api/pay/simulate.js@@ -34,6 +34,8 @@ import {canonicalizeAllowlist,normalizeHost,hostMatches,+ canonicalizePerRailDaily,+ resolveRailDailyCapAtomics,} from '../_lib/pay/policy.js';// A simulation fans out one request per unique endpoint. These bounds keep a@@ -178,6 +180,35 @@ export function parsePolicy(raw = {}) {allowedHosts = allowedHosts.slice(0, MAX_ALLOWED_HOSTS);}+ const rawBlocked = Array.isArray(raw.blocked_hosts)+ ? raw.blocked_hosts+ : String(raw.blocked_hosts ?? '').split(/[\s,]+/);+ let blockedHosts = [...new Set(canonicalizeAllowlist(rawBlocked))];+ if (blockedHosts.length > MAX_ALLOWED_HOSTS) {+ notes.push(`blocked_hosts truncated to the ${MAX_ALLOWED_HOSTS}-entry maximum`);+ blockedHosts = blockedHosts.slice(0, MAX_ALLOWED_HOSTS);+ }++ let approvalThresholdUsd =+ raw.approval_threshold_usd == null || raw.approval_threshold_usd === ''+ ? null+ : Number(raw.approval_threshold_usd);+ if (approvalThresholdUsd !== null && (!Number.isFinite(approvalThresholdUsd) || approvalThresholdUsd < 0.000001)) {+ approvalThresholdUsd = null;+ notes.push('approval_threshold_usd ignored: not a positive number');+ }++ // canonicalizePerRailDaily silently drops non-positive or unrecognized-network+ // entries; this mirrors that leniency (matching what session creation itself+ // does) but surfaces it as a note so a caller's typo is not silent here either.+ const rawPerRailDaily = raw.per_rail_daily_usd && typeof raw.per_rail_daily_usd === 'object'+ ? raw.per_rail_daily_usd+ : {};+ const perRailDailyUsd = canonicalizePerRailDaily(rawPerRailDaily);+ if (Object.keys(rawPerRailDaily).length > 0 && Object.keys(perRailDailyUsd).length === 0) {+ notes.push('per_rail_daily_usd ignored: no valid network/amount entries');+ }+let expirySeconds = Number(raw.expiry_seconds ?? 3600);if (!Number.isFinite(expirySeconds)) expirySeconds = 3600;expirySeconds = Math.min(MAX_TTL_SECONDS, Math.max(MIN_TTL_SECONDS, Math.round(expirySeconds)));@@ -188,6 +219,9 @@ export function parsePolicy(raw = {}) {budgetUsd,maxPerTxUsd,allowedHosts,+ blockedHosts,+ approvalThresholdUsd,+ perRailDailyUsd,expirySeconds,network,notes,@@ -405,6 +439,11 @@ export default wrap(async (req, res) => {budgetAtomics: usdToAtomics(policy.budgetUsd),maxPerTxAtomics: policy.maxPerTxUsd == null ? null : usdToAtomics(policy.maxPerTxUsd),allowedHosts: policy.allowedHosts,+ blockedHosts: policy.blockedHosts,+ approvalThresholdAtomics: policy.approvalThresholdUsd == null ? null : usdToAtomics(policy.approvalThresholdUsd),+ // A dry run has no live session, so the rolling rail window starts+ // empty: railSpentAtomics defaults to 0 inside replay().+ railDailyCapAtomics: resolveRailDailyCapAtomics(policy.network, policy.perRailDailyUsd),status: 'active',expiresAt,},@@ -462,6 +501,9 @@ export default wrap(async (req, res) => {budget_usd: policy.budgetUsd,max_per_tx_usd: policy.maxPerTxUsd,allowed_hosts: policy.allowedHosts,+ blocked_hosts: policy.blockedHosts,+ approval_threshold_usd: policy.approvalThresholdUsd,+ per_rail_daily_usd: policy.perRailDailyUsd,expiry_seconds: policy.expirySeconds,network: policy.network,notes: policy.notes,@@ -492,6 +534,13 @@ export default wrap(async (req, res) => {budget_usd: suggestion.budget_usd,max_per_tx_usd: suggestion.max_per_tx_usd,allowed_hosts: suggestion.allowed_hosts,+ // recommend() only infers budget/cap/hosts from the priced call list.+ // Blocked hosts, the approval threshold, and the rail cap are opt-in+ // safety limits with no signal in the call list to infer them from,+ // so the create call simply carries through whatever was simulated.+ blocked_hosts: policy.blockedHosts,+ approval_threshold_usd: policy.approvalThresholdUsd,+ per_rail_daily_usd: policy.perRailDailyUsd,expiry_seconds: suggestion.expiry_seconds,network: suggestion.network,},diff --git a/data/changelog.json b/data/changelog.jsonindex d33749e8b..9e0a8187a 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-15",+ "title": "Payment sessions gain blocked hosts, an approval threshold, and a per-rail daily cap, all with tamper-evident verdicts",+ "summary": "Agent payment sessions get three new governance knobs, settable at creation and editable while a session is active: blocked_hosts (a denylist checked after the allowlist, so an explicit block always wins over a broad allow, even with no allowlist set), approval_threshold_usd (a call priced above this amount now gets a distinct requires_approval verdict instead of either settling or silently failing), and per_rail_daily_usd (a rolling 24h spend cap per settlement network, reserved atomically the same way the session budget already is, closing the race a naive sum-of-past-executions check would leave open). Every governance verdict, allow or reject, now carries a policy_digest (a sha256 hash of the exact policy it was judged against) and an HMAC signature over the verdict, digest, request, and timestamp, stored with the execution: editing a session's policy after the fact changes the digest and breaks the signature on every verdict that preceded the edit, so a verdict record can be trusted even after the policy it was judged against has since moved. The dry-run simulator at /api/pay/simulate now predicts all three new rules through the exact same shared policy module the real enforcer calls, so a simulated verdict and an enforced one can never disagree; that parity is pinned by a new test running both over identical scenarios. The payments page gained matching fields in both the session creation and edit modals, with inline validation and a collapsed 'Advanced spend policy' section so the common case (budget, expiry, host allowlist) stays uncluttered.",+ "tags": [+ "feature",+ "security"+ ],+ "link": "/docs/payment-sessions"+ },{"date": "2026-10-14","title": "x402 agent buyers now pay v1 sellers, not just v2",diff --git a/docs/payment-sessions.md b/docs/payment-sessions.mdindex bc9a7f563..f429425e2 100644--- a/docs/payment-sessions.md+++ b/docs/payment-sessions.md@@ -252,6 +252,9 @@ curl -s https://three.ws/api/pay/session \"budget_usd": 1.00,"max_per_tx_usd": 0.01,"allowed_hosts": ["three.ws"],+ "blocked_hosts": ["untrusted.example.com"],+ "approval_threshold_usd": 0.50,+ "per_rail_daily_usd": { "solana": 5.00 },"expiry_seconds": 86400}'```@@ -264,6 +267,9 @@ Body fields:| `label` | string | Optional, trimmed to 120 chars. || `max_per_tx_usd` | number | Optional per-payment ceiling, must be above $0.000001. `null` means no cap. || `allowed_hosts` | string[] | Optional, max 50 entries, deduplicated. Empty means any host. |+| `blocked_hosts` | string[] | Optional, max 50 entries, deduplicated. Checked after the allowlist, so an explicit block always wins over a broad allow, even on a session with no allowlist set. |+| `approval_threshold_usd` | number | Optional. A call priced above this amount gets a `requires_approval` verdict instead of settling. `null` means no threshold. |+| `per_rail_daily_usd` | object | Optional, keyed by network name (`"solana"`, `"base"`) or CAIP-2 id. A rolling 24h spend cap on that settlement rail, enforced with the same atomic reserve-then-roll-back pattern as the budget. || `agent_id` | string | Optional agent to associate with the session. || `network` | string | `"solana"` (default) or `"base"`. Stored on the session; execution settles on Solana (see below). || `expiry_seconds` | number | Default 3600. Min 60, max 7776000 (90 days). |@@ -284,6 +290,9 @@ once**:"remaining_usd": 1,"max_per_tx_usd": 0.01,"allowed_hosts": ["three.ws"],+ "blocked_hosts": [],+ "approval_threshold_usd": null,+ "per_rail_daily_usd": {},"network": "solana","status": "active","expires_at": "2026-07-31T00:00:00.000Z",@@ -357,8 +366,10 @@ execute error table below).### `PATCH /api/pay/session/:id`Update the mutable fields of an **active** session: `label`, `allowed_hosts`,-`max_per_tx_usd` (pass `null` to remove the cap). Budget, network, and expiry-cannot be changed after creation.+`max_per_tx_usd` (pass `null` to remove the cap), `blocked_hosts`,+`approval_threshold_usd` (pass `null` to remove the threshold), and+`per_rail_daily_usd` (pass `{}` to remove the cap). Budget, network, and+expiry cannot be changed after creation.```bashcurl -s -X PATCH https://three.ws/api/pay/session/<id> \@@ -417,13 +428,20 @@ What happens, in order:asset USDC, and a `feePayer` in `extra`). Sessions created with`network: "base"` store that preference, but execute settles on Solanaonly; a challenge with no Solana option fails with `no_solana_accept`.-4. **Governance.** Five checks in order: session is active, not expired, host+4. **Governance.** Checks run in order: session is active, not expired, hostis in the allowlist (exact hostname or a subdomain of an allowed host),- amount is within `max_per_tx_usd`, and remaining budget covers the amount.- The budget reservation is a single atomic SQL update, so concurrent calls- can never collectively overspend a session; when two racing calls both fit+ host is not in the denylist (checked even with no allowlist set), amount is+ within `max_per_tx_usd`, amount fits the rolling `per_rail_daily_usd` cap+ for the settlement network, remaining budget covers the amount, and amount+ is at or below `approval_threshold_usd`. The budget and rail-cap+ reservations are atomic SQL statements, so concurrent calls can never+ collectively overspend a session or a rail; when two racing calls both fitindividually but not together, exactly one wins and the other gets- `insufficient_budget`.+ `insufficient_budget` or `rail_daily_exceeded`. Every verdict (allow or+ reject) carries a `policy_digest` (sha256 of the policy it was judged+ against) and an HMAC signature over the verdict, digest, request, and+ timestamp, stored with the execution: editing session policy after the+ fact changes the digest and breaks the signature on that old verdict.5. **Sign and pay.** The platform Solana payer wallet signs a USDC transfermatching the accept and re-requests the endpoint with the `X-PAYMENT`header. The service's fee payer covers the transaction fee; your budget is@@ -482,7 +500,10 @@ Free endpoint (no 402 challenge):| 401 | `invalid_token` | Token is malformed, unknown, or does not match its stored hash. | untouched || 403 | `session_inactive`, `session_expired` | Session is exhausted, cancelled, or past its expiry. | untouched || 403 | `allowlist_blocked` | Target host is not in the session's allowlist. `detail` carries the host and the allowlist. | untouched |+| 403 | `host_blocked` | Target host is in the session's `blocked_hosts` denylist. `detail` carries the host. | untouched |+| 403 | `requires_approval` | The call's price exceeds `approval_threshold_usd`. `detail` carries `amount_usd` and `threshold_usd`. A human must approve the call before it can execute. | untouched || 402 | `per_tx_exceeded` | The endpoint's price exceeds `max_per_tx_usd`. `detail` carries `amount_usd` and `cap_usd`. | untouched |+| 402 | `rail_daily_exceeded` | The call would exceed the rolling 24h `per_rail_daily_usd` cap for the session's settlement network. `detail` carries the would-spend, spent-so-far, and cap amounts. | untouched || 402 | `insufficient_budget` | Remaining budget cannot cover the price. `detail` carries `need_usd` and `remaining_usd`. | untouched || 402 | `payment_rejected` | The service rejected the payment before settlement. | rolled back || 422 | `no_solana_accept`, `unsupported_asset`, `missing_fee_payer` | The challenge offers no payable Solana USDC option. | untouched |diff --git a/pages/payments.html b/pages/payments.htmlindex cd2c2cb90..1bd880624 100644--- a/pages/payments.html+++ b/pages/payments.html@@ -224,6 +224,17 @@.f-hint { font-size: 11.5px; color: rgba(255,255,255,0.35); margin-top: 5px; line-height: 1.45; }.f-row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; }+ /* Advanced policy disclosure */+ .adv-policy { margin-bottom: 1.25rem; border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; padding: 0.1rem 0.9rem; background: rgba(255,255,255,0.02); }+ .adv-policy[open] { padding-bottom: 0.9rem; }+ .adv-policy summary { list-style: none; cursor: pointer; font-size: 12px; font-weight: 600; color: rgba(255,255,255,0.55); text-transform: uppercase; letter-spacing: 0.06em; padding: 0.8rem 0; display: flex; align-items: center; gap: 6px; user-select: none; }+ .adv-policy summary::-webkit-details-marker { display: none; }+ .adv-policy summary::before { content: '›'; display: inline-block; font-size: 14px; transition: transform var(--duration-fast); }+ .adv-policy[open] summary::before { transform: rotate(90deg); }+ .adv-policy summary:hover { color: rgba(255,255,255,0.8); }+ .adv-policy summary:focus-visible { outline: 2px solid rgba(124,92,255,0.6); outline-offset: 3px; border-radius: 6px; }+ .adv-policy .f-row:last-child { margin-bottom: 0; }+/* Budget preview */.budget-preview { display: flex; align-items: center; justify-content: space-between; background: rgba(47,191,113,0.07); border: 1px solid rgba(47,191,113,0.2); border-radius: 10px; padding: 0.75rem 1rem; margin-bottom: 1.25rem; font-size: 13px; }.budget-preview .bp-label { color: rgba(255,255,255,0.55); }@@ -422,6 +433,28 @@<div class="f-hint" id="fHostsHint">If set, the session can only pay endpoints at these domains. Empty = any host.</div></div>+ <details class="adv-policy" id="fAdvPolicy">+ <summary data-i18n="payments.advanced_spend_policy">Advanced spend policy</summary>++ <div class="f-row">+ <label for="fBlockedHosts" data-i18n-html="payments.blocked_hosts_optional_comma_separated">Blocked hosts <span>optional, comma-separated</span></label>+ <input type="text" id="fBlockedHosts" placeholder="untrusted.example.com" autocomplete="off" aria-describedby="fBlockedHostsHint" />+ <div class="f-hint" id="fBlockedHostsHint">Denylist wins over the allowlist. Checked on every call even with no allowlist set.</div>+ </div>++ <div class="f-row-2">+ <div class="f-row">+ <label for="fApprovalThreshold" data-i18n-html="payments.requires_approval_above_optional">Requires approval above <span>optional, USD</span></label>+ <input type="number" id="fApprovalThreshold" min="0.000001" max="1000" step="0.0001" placeholder="No threshold" />+ </div>+ <div class="f-row">+ <label for="fRailDaily" data-i18n-html="payments.per_rail_daily_cap_optional">Per-rail daily cap <span>optional, USD</span></label>+ <input type="number" id="fRailDaily" min="0.000001" max="1000" step="0.0001" placeholder="No cap" />+ </div>+ </div>+ <div class="f-hint" style="margin-top:-0.4rem;margin-bottom:0.25rem">A call above the approval threshold is held for manual review instead of executing. The daily cap is a rolling 24h limit on this session's settlement network.</div>+ </details>+<div class="budget-preview" id="budgetPreview"><span class="bp-label" data-i18n="payments.credit_charge">Credit charge</span><span class="bp-val" id="previewVal">$1.0000</span>@@ -478,6 +511,19 @@<label for="editMaxTx" data-i18n="payments.max_per_tx_usd">Max per tx (USD)</label><input type="number" id="editMaxTx" min="0.000001" step="0.0001" placeholder="No limit" /></div>+ <div class="f-row">+ <label for="editBlockedHosts" data-i18n-html="payments.blocked_hosts_comma_separated">Blocked hosts <span style="text-transform:none;letter-spacing:0;font-weight:400;font-size:11px;color:rgba(255,255,255,.3)">comma-separated</span></label>+ <input type="text" id="editBlockedHosts" placeholder="None (leave empty)" />+ </div>+ <div class="f-row">+ <label for="editApprovalThreshold" data-i18n="payments.requires_approval_above_usd">Requires approval above (USD)</label>+ <input type="number" id="editApprovalThreshold" min="0.000001" step="0.0001" placeholder="No threshold" />+ </div>+ <div class="f-row">+ <label for="editRailDaily" data-i18n="payments.per_rail_daily_cap_usd">Per-rail daily cap (USD)</label>+ <input type="number" id="editRailDaily" min="0.000001" step="0.0001" placeholder="No cap" />+ </div>+ <div class="f-error" id="editError" role="alert" hidden></div><div class="modal-footer"><button class="f-cancel" id="editClose" data-i18n="payments.cancel_2">Cancel</button><button class="f-primary" id="editSave" data-i18n="payments.save_changes">Save changes</button>@@ -658,6 +704,9 @@const netLabel = 'Solana';const hosts = s.allowed_hosts?.length ? s.allowed_hosts.join(', ') : 'Any host';const maxTx = s.max_per_tx_usd != null ? `$${s.max_per_tx_usd}` : 'No limit';+ const blockedHosts = s.blocked_hosts?.length ? s.blocked_hosts.join(', ') : null;+ const approvalThreshold = s.approval_threshold_usd != null ? `$${s.approval_threshold_usd}` : null;+ const railDailyCap = Object.values(s.per_rail_daily_usd || {})[0];return `<div class="sc" data-id="${s.id}">@@ -703,6 +752,18 @@<div class="k">Expires</div><div class="v muted">${fmtDate(s.expires_at)}</div></div>` : ''}+ ${blockedHosts ? `<div class="sc-mi">+ <div class="k">Blocked hosts</div>+ <div class="v muted" style="font-size:12px">${esc(blockedHosts)}</div>+ </div>` : ''}+ ${approvalThreshold ? `<div class="sc-mi">+ <div class="k">Requires approval above</div>+ <div class="v">${approvalThreshold}</div>+ </div>` : ''}+ ${railDailyCap != null ? `<div class="sc-mi">+ <div class="k">Per-rail daily cap</div>+ <div class="v">$${railDailyCap}</div>+ </div>` : ''}</div><!-- Actions -->@@ -874,13 +935,21 @@}// ── Edit modal ─────────────────────────────────────────────+ let editingNetwork = 'solana';+function openEdit(id) {const s = sessions.find(x => x.id === id);if (!s) return;editingId = id;+ editingNetwork = s.network || 'solana';$('editLabel').value = s.label || '';$('editHosts').value = (s.allowed_hosts || []).join(', ');$('editMaxTx').value = s.max_per_tx_usd != null ? s.max_per_tx_usd : '';+ $('editBlockedHosts').value = (s.blocked_hosts || []).join(', ');+ $('editApprovalThreshold').value = s.approval_threshold_usd != null ? s.approval_threshold_usd : '';+ const railCap = Object.values(s.per_rail_daily_usd || {})[0];+ $('editRailDaily').value = railCap != null ? railCap : '';+ $('editError').hidden = true;$('editModal').classList.add('show');setTimeout(() => $('editLabel').focus(), 50);}@@ -892,10 +961,32 @@const label = $('editLabel').value.trim();const hostsRaw = $('editHosts').value.trim();const maxTxRaw = $('editMaxTx').value.trim();+ const blockedHostsRaw = $('editBlockedHosts').value.trim();+ const approvalThresholdRaw = $('editApprovalThreshold').value.trim();+ const railDailyRaw = $('editRailDaily').value.trim();++ const editErr = $('editError');+ editErr.hidden = true;+ if (approvalThresholdRaw && (!Number.isFinite(parseFloat(approvalThresholdRaw)) || parseFloat(approvalThresholdRaw) <= 0)) {+ editErr.textContent = 'Approval threshold must be a positive number.';+ editErr.hidden = false;+ $('editApprovalThreshold').focus();+ return;+ }+ if (railDailyRaw && (!Number.isFinite(parseFloat(railDailyRaw)) || parseFloat(railDailyRaw) <= 0)) {+ editErr.textContent = 'Per-rail daily cap must be a positive number.';+ editErr.hidden = false;+ $('editRailDaily').focus();+ return;+ }+const body = {label,allowed_hosts: hostsRaw ? hostsRaw.split(/[\s,]+/).map(h => h.trim()).filter(Boolean) : [],max_per_tx_usd: maxTxRaw ? parseFloat(maxTxRaw) : null,+ blocked_hosts: blockedHostsRaw ? blockedHostsRaw.split(/[\s,]+/).map(h => h.trim()).filter(Boolean) : [],+ approval_threshold_usd: approvalThresholdRaw ? parseFloat(approvalThresholdRaw) : null,+ per_rail_daily_usd: railDailyRaw ? { [editingNetwork]: parseFloat(railDailyRaw) } : {},};try {$('editSave').disabled = true;@@ -1043,6 +1134,10 @@$('tokenReveal').style.display = 'none';$('mCreate').disabled = false;$('mCreate').textContent = 'Create session →';+ $('fBlockedHosts').value = '';+ $('fApprovalThreshold').value = '';+ $('fRailDaily').value = '';+ $('fAdvPolicy').open = false;$('createModal').classList.add('show');setTimeout(() => $('fLabel').focus(), 50);}@@ -1063,6 +1158,23 @@const hostsRaw = $('fHosts').value.trim();const maxTxRaw = $('fMaxTx').value.trim();+ const blockedHostsRaw = $('fBlockedHosts').value.trim();+ const approvalThresholdRaw = $('fApprovalThreshold').value.trim();+ const railDailyRaw = $('fRailDaily').value.trim();+ const network = $('fNetwork').value;++ if (approvalThresholdRaw && (!Number.isFinite(parseFloat(approvalThresholdRaw)) || parseFloat(approvalThresholdRaw) <= 0)) {+ showCreateError('Approval threshold must be a positive number.');+ $('fAdvPolicy').open = true;+ $('fApprovalThreshold').focus();+ return;+ }+ if (railDailyRaw && (!Number.isFinite(parseFloat(railDailyRaw)) || parseFloat(railDailyRaw) <= 0)) {+ showCreateError('Per-rail daily cap must be a positive number.');+ $('fAdvPolicy').open = true;+ $('fRailDaily').focus();+ return;+ }clearCreateError();$('mCreate').disabled = true;@@ -1077,7 +1189,10 @@expiry_seconds: parseInt($('fExpiry').value, 10),max_per_tx_usd: maxTxRaw ? parseFloat(maxTxRaw) : null,allowed_hosts: hostsRaw ? hostsRaw.split(/[\s,]+/).map(h => h.trim()).filter(Boolean) : [],- network: $('fNetwork').value,+ blocked_hosts: blockedHostsRaw ? blockedHostsRaw.split(/[\s,]+/).map(h => h.trim()).filter(Boolean) : [],+ approval_threshold_usd: approvalThresholdRaw ? parseFloat(approvalThresholdRaw) : null,+ per_rail_daily_usd: railDailyRaw ? { [network]: parseFloat(railDailyRaw) } : null,+ network,}),});diff --git a/public/changelog-recent.json b/public/changelog-recent.jsonindex 19ffdcfee..ec2e47ee2 100644--- a/public/changelog-recent.json+++ b/public/changelog-recent.json@@ -1,14 +1,25 @@{- "generated_at": "2026-10-14T23:56:00.129Z",+ "generated_at": "2026-10-15T00:43:42.304Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},- "total": 4096,+ "total": 4097,"complete": false,"full_feed": "/changelog.json","entries": [+ {+ "date": "2026-10-15",+ "type": "update",+ "title": "Payment sessions gain blocked hosts, an approval threshold, and a per-rail daily cap, all with tamper-evident verdicts",+ "summary": "Agent payment sessions get three new governance knobs, settable at creation and editable while a session is active: blocked_hosts (a denylist checked after the allowlist, so an explicit block always wins over a broad allow, even with no allowlist set), approval_threshold_usd (a call priced above this amount now gets a distinct requires_approval verdict instead of either settling or silently failing), and per_rail_daily_usd (a rolling 24h spend cap per settlement network, reserved atomically the same way the session budget already is, closing the race a naive sum-of-past-executions check would leave open). Every governance verdict, allow or reject, now carries a policy_digest (a sha256 hash of the exact policy it was judged against) and an HMAC signature over the verdict, digest, request, and timestamp, stored with the execution: editing a session's policy after the fact changes the digest and breaks the signature on every verdict that preceded the edit, so a verdict record can be trusted even after the policy it was judged against has since moved. The dry-run simulator at /api/pay/simulate now predicts all three new rules through the exact same shared policy module the real enforcer calls, so a simulated verdict and an enforced one can never disagree; that parity is pinned by a new test running both over identical scenarios. The payments page gained matching fields in both the session creation and edit modals, with inline validation and a collapsed 'Advanced spend policy' section so the common case (budget, expiry, host allowlist) stays uncluttered.",+ "link": "/docs/payment-sessions",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-10-14","type": "update",@@ -1546,17 +1557,6 @@"feature","sdk"]- },- {- "date": "2026-10-10",- "type": "update",- "title": "Agents can compare every Solana swap route and see why one wins",- "summary": "Ten trading tools are now available to agents in Claude or any MCP client, and over the API at /api/v1/trading. Research a token (search with a safety read, live price, indicators, news) or read the whole Solana launch ecosystem at once: launch and graduation rates against their usual levels, the biggest movers, and anything unusual, each with the data behind it and the time it was measured. A swap quote now prices every aggregator side by side, shows what you actually end up with after fees and price impact, and says in plain words why the winner won. Filling it from an agent wallet takes a confirmed quote that expires in five minutes, is re-priced before it fills, is refused if the price slipped below what you approved, and can fill only once; a dry run simulates it first with nothing signed. Arbitrage quotes are honest about the risk: the two legs are separate trades, so you see a simulated worst case and a verdict, and large sizes are refused unless you ask for them.",- "link": "/docs/trading-tools",- "tags": [- "feature",- "sdk"- ]}]}diff --git a/public/changelog.json b/public/changelog.jsonindex 5c0fab5c0..2cb8c044d 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,22 @@{- "generated_at": "2026-10-14T23:56:00.107Z",+ "generated_at": "2026-10-15T00:43:42.282Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-10-15",+ "type": "update",+ "title": "Payment sessions gain blocked hosts, an approval threshold, and a per-rail daily cap, all with tamper-evident verdicts",+ "summary": "Agent payment sessions get three new governance knobs, settable at creation and editable while a session is active: blocked_hosts (a denylist checked after the allowlist, so an explicit block always wins over a broad allow, even with no allowlist set), approval_threshold_usd (a call priced above this amount now gets a distinct requires_approval verdict instead of either settling or silently failing), and per_rail_daily_usd (a rolling 24h spend cap per settlement network, reserved atomically the same way the session budget already is, closing the race a naive sum-of-past-executions check would leave open). Every governance verdict, allow or reject, now carries a policy_digest (a sha256 hash of the exact policy it was judged against) and an HMAC signature over the verdict, digest, request, and timestamp, stored with the execution: editing a session's policy after the fact changes the digest and breaks the signature on every verdict that preceded the edit, so a verdict record can be trusted even after the policy it was judged against has since moved. The dry-run simulator at /api/pay/simulate now predicts all three new rules through the exact same shared policy module the real enforcer calls, so a simulated verdict and an enforced one can never disagree; that parity is pinned by a new test running both over identical scenarios. The payments page gained matching fields in both the session creation and edit modals, with inline validation and a collapsed 'Advanced spend policy' section so the common case (budget, expiry, host allowlist) stays uncluttered.",+ "link": "/docs/payment-sessions",+ "tags": [+ "feature",+ "security"+ ]+ },{"date": "2026-10-14","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 90743310e..a7442eb06 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws: features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Payment sessions gain blocked hosts, an approval threshold, and a per-rail daily cap, all with tamper-evident verdicts</title>+ <link>https://three.ws/docs/payment-sessions</link>+ <guid isPermaLink="false">2026-10-15:Payment sessions gain blocked hosts, an approval threshold, and a per-rail daily cap, all with tamper-evident verdicts</guid>+ <pubDate>Thu, 15 Oct 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Agent payment sessions get three new governance knobs, settable at creation and editable while a session is active: blocked_hosts (a denylist checked after the allowlist, so an explicit block always wins over a broad allow, even with no allowlist set), approval_threshold_usd (a call priced above this amount now gets a distinct requires_approval verdict instead of either settling or silently failing), and per_rail_daily_usd (a rolling 24h spend cap per settlement network, reserved atomically the same way the session budget already is, closing the race a naive sum-of-past-executions check would leave open). Every governance verdict, allow or reject, now carries a policy_digest (a sha256 hash of the exact policy it was judged against) and an HMAC signature over the verdict, digest, request, and timestamp, stored with the execution: editing a session's policy after the fact changes the digest and breaks the signature on every verdict that preceded the edit, so a verdict record can be trusted even after the policy it was judged against has since moved. The dry-run simulator at /api/pay/simulate now predicts all three new rules through the exact same shared policy module the real enforcer calls, so a simulated verdict and an enforced one can never disagree; that parity is pinned by a new test running both over identical scenarios. The payments page gained matching fields in both the session creation and edit modals, with inline validation and a collapsed 'Advanced spend policy' section so the common case (budget, expiry, host allowlist) stays uncluttered.</description>+ </item><item><title>8 keyless live-data services join the x402 paid API: weather, grid carbon, domains, research, books, news, transit, places</title><link>https://three.ws/docs/x402-endpoints</link>diff --git a/public/features.json b/public/features.jsonindex 18498ca78..369db06a6 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-10-14T23:56:00.094Z",+ "generated_at": "2026-10-15T00:43:42.269Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/payment-policy-simulator.test.js b/tests/payment-policy-simulator.test.jsindex 119d71981..52d94a8ed 100644--- a/tests/payment-policy-simulator.test.js+++ b/tests/payment-policy-simulator.test.js@@ -427,6 +427,32 @@ describe('simulator policy parsing', () => {expect(parsePolicy({ network: 'base' }).network).toBe('base');expect(parsePolicy({ network: 'ethereum' }).network).toBe('solana');});++ it('accepts a denylist as an array or a delimited string, deduplicated', () => {+ expect(parsePolicy({ blocked_hosts: ['Evil.com', 'https://evil.com/x'] }).blockedHosts)+ .toEqual(['evil.com']);+ expect(parsePolicy({ blocked_hosts: 'evil.com, bad.com' }).blockedHosts)+ .toEqual(['evil.com', 'bad.com']);+ });++ it('accepts an approval threshold and ignores a non-positive one', () => {+ expect(parsePolicy({ approval_threshold_usd: 0.5 }).approvalThresholdUsd).toBe(0.5);+ expect(parsePolicy({}).approvalThresholdUsd).toBeNull();+ const p = parsePolicy({ approval_threshold_usd: -1 });+ expect(p.approvalThresholdUsd).toBeNull();+ expect(p.notes.join(' ')).toMatch(/ignored/);+ });++ it('canonicalizes a per-rail daily cap to CAIP-2 keys', () => {+ const p = parsePolicy({ per_rail_daily_usd: { solana: 5 } });+ expect(p.perRailDailyUsd).toEqual({ 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp': 5 });+ });++ it('notes when every per-rail-daily entry is dropped as invalid', () => {+ const p = parsePolicy({ per_rail_daily_usd: { ethereum: 5, solana: -1 } });+ expect(p.perRailDailyUsd).toEqual({});+ expect(p.notes.join(' ')).toMatch(/ignored/);+ });});describe('simulator step construction', () => {@@ -574,11 +600,13 @@ describe('the enforcer and the simulator share one rule set', () => {const governor = read('api/_lib/pay/spend-governor.js');const flat = governor.replace(/\s+/g, ' ');- it('imports its predicates from policy.js', () => {+ it('judges every call through the one evaluateCall() policy.js exports', () => {+ // reserveSessionSpend calls evaluateCall() exactly once rather than+ // threading individual predicates (statusVerdict, allowlistVerdict, ...)+ // by hand: that is what makes the enforcer and replay() in simulate.js+ // structurally unable to diverge, instead of merely unlikely to.expect(governor).toMatch(/from '\.\/policy\.js'/);- for (const fn of ['statusVerdict', 'expiryVerdict', 'allowlistVerdict', 'perTxVerdict']) {- expect(governor, `the governor no longer uses ${fn}`).toContain(fn);- }+ expect(governor, 'the governor no longer calls the shared evaluateCall()').toContain('evaluateCall');});it('does not reimplement the allowlist suffix rule inline', () => {diff --git a/tests/payment-session-governor.test.js b/tests/payment-session-governor.test.jsindex 14c5dc906..1b5580e88 100644--- a/tests/payment-session-governor.test.js+++ b/tests/payment-session-governor.test.js@@ -40,7 +40,7 @@ process.env.PAYMENT_SESSION_SECRET = 'test-payment-session-secret';// issues and applies that statement's real semantics to the store. Statements run// one at a time (JS is single-threaded between awaits), which is precisely the// serialization Postgres row locking provides for the reservation UPDATE.-const store = { sessions: new Map(), executions: [] };+const store = { sessions: new Map(), executions: [], railReservations: [] };function normalizeSql(strings) {return strings.join(' ? ').replace(/\s+/g, ' ').trim();@@ -102,7 +102,8 @@ function runStatement(text, values) {// recordExecutionif (text.startsWith('INSERT INTO payment_session_executions')) {const [sessionId, userId, endpointUrl, host, method, amount, network, txHash,- payer, payee, status, errorCode, errorMessage, responseBody, durationMs, idem] = values;+ payer, payee, status, errorCode, errorMessage, responseBody, durationMs, idem,+ policyDigest, verdictCode, verdictSignature, verdictSignedAt] = values;if (idem != null && store.executions.some((e) => e.idempotency_key === idem)) return [];store.executions.push({session_id: sessionId, user_id: userId, endpoint_url: endpointUrl,@@ -110,24 +111,72 @@ function runStatement(text, values) {payer_address: payer, payee_address: payee, status, error_code: errorCode,error_message: errorMessage, response_body: responseBody,duration_ms: durationMs, idempotency_key: idem,+ policy_digest: policyDigest, verdict_code: verdictCode,+ verdict_signature: verdictSignature, verdict_signed_at: verdictSignedAt,});return [];}+ // reserveSessionSpend: advisory lock taken ahead of the rail-daily reserve+ // (api/_lib/locked-sql.js). A no-op here: JS runs single-threaded between+ // awaits, which already serializes the statements that follow it.+ if (text.includes('pg_advisory_xact_lock')) return [];++ // reserveSessionSpend: rail-daily pre-check (advisory read before the atomic reserve)+ if (text.startsWith('SELECT coalesce(sum(amount_usdc), 0) AS spent')) {+ const [id, network] = values;+ const cutoff = Date.now() - 24 * HOUR;+ const spent = store.railReservations+ .filter((r) => r.session_id === id && r.network === network && r.created_at > cutoff)+ .reduce((acc, r) => acc + BigInt(r.amount_usdc), 0n);+ return [{ spent: spent.toString() }];+ }++ // reserveSessionSpend: the atomic rail-daily reservation (lock statement, then this,+ // inside one sql.transaction, see api/_lib/locked-sql.js)+ if (text.includes('INSERT INTO payment_session_rail_reservations')) {+ const [id, network, , , amount, , capAtomics] = values;+ const cutoff = Date.now() - 24 * HOUR;+ const spent = store.railReservations+ .filter((r) => r.session_id === id && r.network === network && r.created_at > cutoff)+ .reduce((acc, r) => acc + BigInt(r.amount_usdc), 0n);+ if (spent + BigInt(amount) > BigInt(capAtomics)) return [];+ const resId = `rail_${store.railReservations.length}_${Date.now()}_${Math.random()}`;+ store.railReservations.push({ id: resId, session_id: id, network, amount_usdc: amount, created_at: Date.now() });+ return [{ id: resId }];+ }++ // reserveSessionSpend (budget-reservation failure) / rollbackReservation: release a rail reservation+ if (text.startsWith('DELETE FROM payment_session_rail_reservations')) {+ const [id] = values;+ store.railReservations = store.railReservations.filter((r) => r.id !== id);+ return [];+ }+throw new Error(`unrouted SQL in test fake: ${text.slice(0, 90)}`);}-vi.mock('../api/_lib/db.js', () => ({- sql: (strings, ...values) => Promise.resolve(runStatement(normalizeSql(strings), values)),- isDbUnavailableError: () => false,- isDbCapacityError: () => false,-}));+vi.mock('../api/_lib/db.js', () => {+ const sqlFn = (strings, ...values) => Promise.resolve(runStatement(normalizeSql(strings), values));+ // Each element of `queries` is already an invoked (and thus already-pending)+ // sql`` call under this mock, mirroring tests/advisory-lock-snapshot.test.js's+ // convention for exercising api/_lib/locked-sql.js's runLocked().+ sqlFn.transaction = async (queries) => Promise.all(queries);+ return {+ sql: sqlFn,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ };+});const {usdToAtomics, atomicsToUsd, hashToken, extractSessionId, normalizeHost,generateSessionToken, verifySessionToken, reserveSessionSpend,- rollbackReservation, recordExecution, SpendGovernorError,+ rollbackReservation, recordExecution, signVerdict, verifyVerdictSignature,+ SpendGovernorError,} = await import('../api/_lib/pay/spend-governor.js');+const { replay, resolveRailDailyCapAtomics, computePolicyDigest, computeRequestHash, NETWORK_TO_CAIP2 } =+ await import('../api/_lib/pay/policy.js');const SESSION_ID = '11111111-2222-4333-8444-555555555555';const HOUR = 3600 * 1000;@@ -143,7 +192,10 @@ function seedSession(partial = {}) {spent_usdc: String(partial.spent_usdc ?? 0),max_per_tx_usdc: partial.max_per_tx_usdc ?? null,allowed_hosts: partial.allowed_hosts ?? [],- network: 'solana',+ blocked_hosts: partial.blocked_hosts ?? [],+ approval_threshold_usdc: partial.approval_threshold_usdc ?? null,+ per_rail_daily_usdc: partial.per_rail_daily_usdc ?? {},+ network: partial.network ?? 'solana',connector_ref: null,status: partial.status ?? 'active',expires_at: new Date(Date.now() + (partial.ttlMs ?? HOUR)).toISOString(),@@ -162,6 +214,7 @@ async function expectGovernorError(promise, code) {beforeEach(() => {store.sessions.clear();store.executions.length = 0;+ store.railReservations.length = 0;});// ── Money arithmetic ─────────────────────────────────────────────────────────@@ -363,7 +416,7 @@ describe('per-transaction ceiling', () => {await reserveSessionSpend({token, url: 'https://api.example.com/x', amountAtomics: 60_000n,}).catch((err) => {- expect(err.detail).toEqual({ amount_usd: 0.06, cap_usd: 0.05 });+ expect(err.detail).toMatchObject({ amount_usd: 0.06, cap_usd: 0.05 });});});@@ -396,7 +449,7 @@ describe('atomic budget reservation', () => {await reserveSessionSpend({token, url: 'https://a.test/x', amountAtomics: 200_000n,}).catch((err) => {- expect(err.detail).toEqual({ need_usd: 0.2, remaining_usd: 0.1 });+ expect(err.detail).toMatchObject({ need_usd: 0.2, remaining_usd: 0.1 });});});@@ -541,6 +594,277 @@ describe('recordExecution', () => {status: 'failed', error_code: 'settle_uncertain',});});++ it('stores the signed verdict alongside the execution', async () => {+ const { token, row } = seedSession({ budget_usdc: '1000000' });+ const reservation = await reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 50_000n,+ });+ await recordExecution({+ ...base, sessionId: row.id, endpointUrl: 'https://a.test/x',+ policyDigest: reservation.policyDigest,+ verdictCode: reservation.verdictCode,+ verdictSignature: reservation.verdictSignature,+ verdictSignedAt: reservation.verdictSignedAt,+ });+ expect(store.executions[0]).toMatchObject({+ policy_digest: reservation.policyDigest,+ verdict_code: 'allowed',+ verdict_signature: reservation.verdictSignature,+ verdict_signed_at: reservation.verdictSignedAt,+ });+ });+});++// ── Denylist ─────────────────────────────────────────────────────────────────++describe('blocked hosts', () => {+ it('refuses a call to a host on the denylist', async () => {+ const { token } = seedSession({ blocked_hosts: ['evil.test'] });+ await expectGovernorError(reserveSessionSpend({+ token, url: 'https://evil.test/x', amountAtomics: 10_000n,+ }), 'host_blocked');+ });++ it('allows a host that is not on the denylist', async () => {+ const { token } = seedSession({ blocked_hosts: ['evil.test'] });+ await expect(reserveSessionSpend({+ token, url: 'https://fine.test/x', amountAtomics: 10_000n,+ })).resolves.toBeTruthy();+ });++ it('blocks a host even when it also matches a broad allowlist entry', async () => {+ // An operator who denylists one bad sub-merchant under a wildcard allow+ // expects the denylist to be the final word.+ const { token } = seedSession({+ allowed_hosts: ['example.com'],+ blocked_hosts: ['bad.example.com'],+ });+ await expectGovernorError(reserveSessionSpend({+ token, url: 'https://bad.example.com/x', amountAtomics: 10_000n,+ }), 'host_blocked');+ await expect(reserveSessionSpend({+ token, url: 'https://good.example.com/x', amountAtomics: 10_000n,+ })).resolves.toBeTruthy();+ });+});++// ── Human-approval threshold ─────────────────────────────────────────────────++describe('approval threshold', () => {+ it('returns a distinct requires_approval verdict above the threshold', async () => {+ const { token } = seedSession({ approval_threshold_usdc: '50000' }); // $0.05+ await expectGovernorError(reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 60_000n,+ }), 'requires_approval');+ });++ it('reports the amount and the threshold so a caller can decide', async () => {+ const { token } = seedSession({ approval_threshold_usdc: '50000' });+ await reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 60_000n,+ }).catch((err) => {+ expect(err.detail).toMatchObject({ amount_usd: 0.06, threshold_usd: 0.05 });+ });+ });++ it('settles normally at or below the threshold', async () => {+ const { token, row } = seedSession({ approval_threshold_usdc: '50000' });+ const reservation = await reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 50_000n,+ });+ expect(reservation.verdictCode).toBe('allowed');+ expect(store.sessions.get(row.id).spent_usdc).toBe('50000');+ });++ it('treats a null threshold as no approval requirement', async () => {+ const { token } = seedSession({ approval_threshold_usdc: null });+ await expect(reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 999_999n,+ })).resolves.toBeTruthy();+ });+});++// ── Per-rail rolling 24h cap ─────────────────────────────────────────────────++describe('per-rail daily cap', () => {+ it('refuses a payment that would push the rolling 24h rail spend over the cap', async () => {+ const { token } = seedSession({ per_rail_daily_usdc: { [NETWORK_TO_CAIP2.solana]: 0.05 } });+ await expectGovernorError(reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 60_000n,+ }), 'rail_daily_exceeded');+ });++ it('allows a payment within the cap and reserves it against the window', async () => {+ const { token } = seedSession({ per_rail_daily_usdc: { [NETWORK_TO_CAIP2.solana]: 0.05 } });+ await expect(reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 30_000n,+ })).resolves.toBeTruthy();+ expect(store.railReservations.filter((r) => r.network === NETWORK_TO_CAIP2.solana)).toHaveLength(1);+ });++ it('lets a second payment through once the first is within the cap, and refuses what would overflow it', async () => {+ const { token } = seedSession({ per_rail_daily_usdc: { [NETWORK_TO_CAIP2.solana]: 0.05 } });+ await reserveSessionSpend({ token, url: 'https://a.test/x', amountAtomics: 30_000n });+ await expectGovernorError(reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 30_000n, // 30k + 30k > 50k cap+ }), 'rail_daily_exceeded');+ });++ it('lets exactly one of two concurrent payments win when only one fits the rail cap', async () => {+ const { token } = seedSession({ budget_usdc: '1000000', per_rail_daily_usdc: { [NETWORK_TO_CAIP2.solana]: 0.05 } });+ const pay = () => reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 40_000n,+ }).then(() => 'ok', (err) => err.code);++ const results = await Promise.all([pay(), pay()]);+ expect(results.filter((r) => r === 'ok')).toHaveLength(1);+ expect(results.filter((r) => r === 'rail_daily_exceeded')).toHaveLength(1);+ });++ it('releases the rail reservation on rollback, so a failed call does not eat into the next cap check', async () => {+ const { token, row } = seedSession({ budget_usdc: '1000000', per_rail_daily_usdc: { [NETWORK_TO_CAIP2.solana]: 0.05 } });+ const reservation = await reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 40_000n,+ });+ await rollbackReservation(row.id, 40_000n, { railReservationId: reservation.railReservationId });+ expect(store.railReservations).toHaveLength(0);+ // The rail window is clear again, so a call that would otherwise have+ // collided with the rolled-back reservation now fits.+ await expect(reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 40_000n,+ })).resolves.toBeTruthy();+ });++ it('treats an empty per_rail_daily_usdc as no cap', async () => {+ const { token } = seedSession({ per_rail_daily_usdc: {} });+ await expect(reserveSessionSpend({+ token, url: 'https://a.test/x', amountAtomics: 999_999n,+ })).resolves.toBeTruthy();+ });+});++// ── Signed verdicts ──────────────────────────────────────────────────────────++describe('signed verdicts', () => {+ it('signs an allowed verdict with a signature that verifies', async () => {+ const { token, row } = seedSession({ budget_usdc: '1000000' });+ const url = 'https://a.test/x';+ const amountAtomics = 10_000n;+ const r = await reserveSessionSpend({ token, url, amountAtomics });+ expect(r.verdictCode).toBe('allowed');++ const requestHash = computeRequestHash({ sessionId: row.id, url, amountAtomics });+ expect(verifyVerdictSignature({+ verdictCode: r.verdictCode,+ policyDigest: r.policyDigest,+ requestHash,+ timestamp: r.verdictSignedAt,+ signature: r.verdictSignature,+ })).toBe(true);+ });++ it('fails verification when any signed field is altered', async () => {+ const { token, row } = seedSession({ budget_usdc: '1000000' });+ const url = 'https://a.test/x';+ const amountAtomics = 10_000n;+ const r = await reserveSessionSpend({ token, url, amountAtomics });+ const requestHash = computeRequestHash({ sessionId: row.id, url, amountAtomics });++ expect(verifyVerdictSignature({+ verdictCode: r.verdictCode, policyDigest: 'tampered', requestHash,+ timestamp: r.verdictSignedAt, signature: r.verdictSignature,+ })).toBe(false);+ expect(verifyVerdictSignature({+ verdictCode: 'rejected', policyDigest: r.policyDigest, requestHash,+ timestamp: r.verdictSignedAt, signature: r.verdictSignature,+ })).toBe(false);+ });++ it('a rejection verdict is signed too, over its own policy digest', async () => {+ const { token } = seedSession({ blocked_hosts: ['evil.test'] });+ await reserveSessionSpend({+ token, url: 'https://evil.test/x', amountAtomics: 10_000n,+ }).catch((err) => {+ expect(err.detail.policy_digest).toBeTruthy();+ expect(err.detail.verdict_signature).toBeTruthy();+ expect(err.detail.verdict_signed_at).toBeTruthy();+ });+ });++ it('changes the policy digest when a governed field changes, so a tampered policy cannot reuse an old signature', async () => {+ const { row } = seedSession({ budget_usdc: '1000000' });+ const before = computePolicyDigest(row);+ const tampered = { ...row, approval_threshold_usdc: '1' };+ const after = computePolicyDigest(tampered);+ expect(after).not.toBe(before);+ });++ it('rejects a signature computed against the original digest once the policy (and so the digest) changes', async () => {+ const { token, row } = seedSession({ budget_usdc: '1000000' });+ const r = await reserveSessionSpend({ token, url: 'https://a.test/x', amountAtomics: 10_000n });++ // The policy actually governing this session changes after the verdict was signed.+ const tamperedDigest = computePolicyDigest({ ...row, budget_usdc: '2000000' });+ expect(tamperedDigest).not.toBe(r.policyDigest);++ // Re-signing with the tampered digest produces a different signature than+ // the one that was actually stored, so a verifier comparing against the+ // tampered digest catches the edit.+ const forgedSignature = signVerdict({+ verdictCode: r.verdictCode,+ policyDigest: tamperedDigest,+ requestHash: 'whatever-request-hash',+ timestamp: r.verdictSignedAt,+ });+ expect(forgedSignature).not.toBe(r.verdictSignature);+ });+});++// ── Parity with the dry-run simulator ────────────────────────────────────────++describe('parity: a simulated verdict and an enforced one never disagree', () => {+ // api/pay/simulate.js's replay() and this governor's reserveSessionSpend()+ // both resolve to policy.js's evaluateCall(). This test builds the same+ // policy object both callers build from a session row and runs it through+ // both paths, so a future change that lets them diverge fails here first.+ const cases = [+ { name: 'plain allow', amountAtomics: 10_000n, expect: 'allowed' },+ { name: 'blocked host', amountAtomics: 10_000n, url: 'https://evil.test/x',+ seed: { blocked_hosts: ['evil.test'] }, expect: 'host_blocked' },+ { name: 'per-tx ceiling', amountAtomics: 60_000n,+ seed: { max_per_tx_usdc: '50000' }, expect: 'per_tx_exceeded' },+ { name: 'approval threshold', amountAtomics: 60_000n,+ seed: { approval_threshold_usdc: '50000' }, expect: 'requires_approval' },+ { name: 'rail daily cap', amountAtomics: 60_000n,+ seed: { per_rail_daily_usdc: { [NETWORK_TO_CAIP2.solana]: 0.05 } }, expect: 'rail_daily_exceeded' },+ { name: 'insufficient budget', amountAtomics: 2_000_000n, expect: 'insufficient_budget' },+ ];++ for (const c of cases) {+ it(`agrees on "${c.name}"`, async () => {+ const url = c.url ?? 'https://a.test/x';+ const { token, row } = seedSession({ budget_usdc: '1000000', ...c.seed });++ const enforced = await reserveSessionSpend({ token, url, amountAtomics: c.amountAtomics })+ .then(() => 'allowed', (err) => err.code);++ const simulated = replay([{ url, amountAtomics: c.amountAtomics }], {+ budgetAtomics: BigInt(row.budget_usdc),+ maxPerTxAtomics: row.max_per_tx_usdc,+ allowedHosts: row.allowed_hosts,+ blockedHosts: row.blocked_hosts,+ status: row.status,+ expiresAt: row.expires_at,+ railDailyCapAtomics: resolveRailDailyCapAtomics(row.network, row.per_rail_daily_usdc),+ approvalThresholdAtomics: row.approval_threshold_usdc,+ }).steps[0];+ const simulatedCode = simulated.allowed ? 'allowed' : simulated.rejection.code;++ expect(enforced).toBe(c.expect);+ expect(simulatedCode).toBe(c.expect);+ });+ }});// ── The atomicity guarantee itself ───────────────────────────────────────────