Skip to content

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

test(x402): cover per-network settlement cost and point the proof runner at its log

nirholas429217898063
diff --git a/scripts/cron-local-proof.mjs b/scripts/cron-local-proof.mjs
index a2f0cfc6e..dcf3570f5 100644
--- a/scripts/cron-local-proof.mjs
+++ b/scripts/cron-local-proof.mjs
@@ -44,6 +44,7 @@ import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { spawn } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -51,10 +52,18 @@ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const PG_URL = process.env.CRON_PROOF_DATABASE_URL
|| 'postgresql://b05:[email protected]:55705/b05';
-// A local-only secret. The gate compares it in constant time against whatever
-// the caller presents, so a value generated here exercises the identical path a
-// Cloud Scheduler OIDC bearer takes in production.
-const CRON_SECRET = process.env.CRON_PROOF_SECRET || 'local-cron-proof-secret';
+// A local-only secret, unique per run. The gate compares it in constant time
+// against whatever the caller presents, so a value generated here exercises the
+// identical path a Cloud Scheduler OIDC bearer takes in production.
+//
+// Unique per run, not a fixed string, because several audits run this harness at
+// once in a shared worktree. A constant secret let a run whose port had been
+// taken by a NEIGHBOUR's server probe that server and read its answers as its
+// own: the neighbour's crons, the neighbour's database. With a per-run secret a
+// stray server can only ever answer 401, which the identity check below turns
+// into a loud failure instead of a plausible-looking result.
+const CRON_SECRET = process.env.CRON_PROOF_SECRET
+ || `local-cron-proof-${process.pid}-${randomUUID()}`;
const DEFAULT_CRONS = [
'irl-reap',
@@ -85,8 +94,16 @@ async function shutdown() {
}
process.on('SIGINT', async () => { await shutdown(); process.exit(130); });
-async function freePort(start) {
- for (let p = start; p < start + 200; p++) {
+// Probing a port frees it again before the caller can bind it, so two runs that
+// probe at the same moment both get the same "free" port. Spreading the scan
+// start across runs makes that collision vanishingly unlikely; the identity
+// check on the started server catches the remainder.
+function scanStart(base, span = 200) {
+ return base + ((process.pid * 7) % span);
+}
+
+async function freePort(start, span = 200) {
+ for (let p = start; p < start + span; p++) {
const ok = await new Promise((resolve) => {
const s = net.createServer();
s.once('error', () => resolve(false));
@@ -178,7 +195,7 @@ async function runBatch(pool, queries, headers) {
}
async function startShim(pool) {
- const port = await freePort(54800);
+ const port = await freePort(scanStart(54800, 400), 400);
const server = http.createServer(async (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return; }
let body = '';
@@ -322,7 +339,8 @@ async function bootstrapSchema(pool, { passes = 4 } = {}) {
// ── server ───────────────────────────────────────────────────────────────────
async function startServer(preload) {
- const port = await freePort(8410);
+ const port = await freePort(scanStart(8410, 400), 400);
+ let exited = null;
const child = spawn('node', [path.join(root, 'server/index.mjs')], {
cwd: root,
env: {
@@ -339,12 +357,36 @@ async function startServer(preload) {
child.stdout.pipe(log);
child.stderr.pipe(log);
cleanup.push(() => { child.kill('SIGKILL'); });
+ // A server that loses the bind (port taken between the probe and the spawn)
+ // or dies on boot must stop the run here. Without this the readiness probe
+ // below is answered by whoever DOES hold the port, and every cron result
+ // afterwards describes a server this run never started.
+ child.on('exit', (code, signal) => { exited = signal ? `signal ${signal}` : `code ${code}`; });
const base = `http://127.0.0.1:${port}`;
await waitFor(async () => {
+ if (exited) throw new Error(`server exited (${exited}), see ${logPath}`);
const r = await fetch(`${base}/api/healthz`).catch(() => null);
return r && r.status < 600;
}, { label: `server on :${port}`, tries: 120 });
+ if (exited) throw new Error(`server exited (${exited}), see ${logPath}`);
+
+ // Identity check. Our child binds the wildcard address, but a process already
+ // bound to 127.0.0.1 specifically keeps winning loopback connections, so
+ // "the child started" does not prove the child is who answers. The per-run
+ // CRON_SECRET is known only to this run's server: anyone else returns 401,
+ // which must read as a harness fault, never as "the cron refused the
+ // scheduler". Costs one real tick of the probe cron against this run's own
+ // throwaway database.
+ const probe = await fetch(`${base}/api/cron/uptime-check`, {
+ headers: { authorization: `Bearer ${CRON_SECRET}` },
+ }).catch(() => null);
+ if (probe && probe.status === 401) {
+ throw new Error(
+ `port ${port} is served by a different process (it rejects this run's cron secret). `
+ + 'Another cron-local-proof run is probably using it; re-run to pick a new port.',
+ );
+ }
return { base, logPath, child };
}
diff --git a/tests/api/forge-nim.test.js b/tests/api/forge-nim.test.js
index bd978518b..56e17ea8a 100644
--- a/tests/api/forge-nim.test.js
+++ b/tests/api/forge-nim.test.js
@@ -17,7 +17,11 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
}));
const ORIGINAL_FETCH = globalThis.fetch;
-const ENV_KEYS = ['MODEL_TRELLIS_URL', 'NVIDIA_API_KEY'];
+// MODEL_TRELLIS_URL is cleared too, and never set: it points at our own async
+// Cloud Run TRELLIS worker, and api/forge-nim.js deliberately does not read it.
+// Clearing it keeps an ambient value out of these cases and lets the last case
+// below prove the handler still reports unconfigured when only it is set.
+const ENV_KEYS = ['NIM_TRELLIS_URL', 'MODEL_TRELLIS_URL', 'NVIDIA_API_KEY'];
const saved = {};
beforeEach(() => {
@@ -106,8 +110,20 @@ describe('GET /api/forge-nim?action=health', () => {
expect(body.reachable).toBe(false);
});
+ it('still reports unconfigured when only MODEL_TRELLIS_URL is set', async () => {
+ // MODEL_TRELLIS_URL points at our own async Cloud Run TRELLIS worker, which
+ // speaks /infer + /tasks/{id}, not the NIM's synchronous /v1/infer. Reading it
+ // here reported a configured, unreachable NIM and 404ed every generation.
+ process.env.MODEL_TRELLIS_URL = 'https://trellis-worker.example.run.app';
+ const fetchMock = vi.fn(async () => jsonResponse({ status: 'ready' }));
+ globalThis.fetch = fetchMock;
+ const { body } = await dispatch(makeReq({ method: 'GET', url: '/api/forge-nim?action=health' }), makeRes());
+ expect(body.configured).toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
it('reports live when the configured NIM ready check passes', async () => {
- process.env.MODEL_TRELLIS_URL = 'https://nim.example.run.app';
+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';
const fetchMock = vi.fn(async () => jsonResponse({ status: 'ready' }));
globalThis.fetch = fetchMock;
const { body } = await dispatch(makeReq({ method: 'GET', url: '/api/forge-nim?action=health' }), makeRes());
@@ -118,7 +134,7 @@ describe('GET /api/forge-nim?action=health', () => {
});
it('reports down when the ready check is unreachable', async () => {
- process.env.MODEL_TRELLIS_URL = 'https://nim.example.run.app';
+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';
globalThis.fetch = vi.fn(async () => {
throw new Error('ECONNREFUSED');
});
@@ -131,7 +147,7 @@ describe('GET /api/forge-nim?action=health', () => {
describe('POST /api/forge-nim — image mode', () => {
it('forwards a data-uri image to /v1/infer and returns the synchronous GLB', async () => {
- process.env.MODEL_TRELLIS_URL = 'https://nim.example.run.app/';
+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app/';
const glb = fakeGlb(96);
const fetchMock = vi.fn(async () => jsonResponse({ artifacts: [{ base64: glb.toString('base64') }] }));
globalThis.fetch = fetchMock;
@@ -161,7 +177,7 @@ describe('POST /api/forge-nim — image mode', () => {
});
it('decodes a raw binary (model/gltf-binary) NIM response', async () => {
- process.env.MODEL_TRELLIS_URL = 'https://nim.example.run.app';
+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';
const glb = fakeGlb(48);
globalThis.fetch = vi.fn(async () => binaryResponse(glb));
const { body } = await dispatch(
@@ -173,7 +189,7 @@ describe('POST /api/forge-nim — image mode', () => {
});
it('rejects image mode with no image', async () => {
- process.env.MODEL_TRELLIS_URL = 'https://nim.example.run.app';
+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';
const { res, body } = await dispatch(makeReq({ body: { mode: 'image' } }), makeRes());
expect(res.statusCode).toBe(400);
expect(body.error || body.code).toBeTruthy();
@@ -182,7 +198,7 @@ describe('POST /api/forge-nim — image mode', () => {
describe('POST /api/forge-nim — text mode', () => {
it('shapes the prompt and posts a text invoke', async () => {
- process.env.MODEL_TRELLIS_URL = 'https://nim.example.run.app';
+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';
const glb = fakeGlb(32);
const fetchMock = vi.fn(async () => jsonResponse({ artifacts: [{ base64: glb.toString('base64') }] }));
globalThis.fetch = fetchMock;
@@ -195,7 +211,7 @@ describe('POST /api/forge-nim — text mode', () => {
});
it('rejects a too-short prompt', async () => {
- process.env.MODEL_TRELLIS_URL = 'https://nim.example.run.app';
+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';
const { res } = await dispatch(makeReq({ body: { mode: 'text', prompt: 'a' } }), makeRes());
expect(res.statusCode).toBe(400);
});
@@ -244,7 +260,7 @@ describe('POST /api/forge-nim — configuration & SSRF', () => {
describe('POST /api/forge-nim — upstream failures', () => {
it('maps a 401 from the NIM to an auth boundary error', async () => {
- process.env.MODEL_TRELLIS_URL = 'https://nim.example.run.app';
+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';
globalThis.fetch = vi.fn(async () => ({
ok: false,
status: 401,
@@ -261,7 +277,7 @@ describe('POST /api/forge-nim — upstream failures', () => {
});
it('surfaces an empty-artifact response as a clean error', async () => {
- process.env.MODEL_TRELLIS_URL = 'https://nim.example.run.app';
+ process.env.NIM_TRELLIS_URL = 'https://nim.example.run.app';
globalThis.fetch = vi.fn(async () => jsonResponse({ artifacts: [] }));
const { res, body } = await dispatch(
makeReq({ body: { mode: 'image', image: 'data:image/png;base64,iVBORw0KGgo=' } }),
diff --git a/tests/x402-network-cost.test.js b/tests/x402-network-cost.test.js
new file mode 100644
index 000000000..57e313065
--- /dev/null
+++ b/tests/x402-network-cost.test.js
@@ -0,0 +1,170 @@
+/**
+ * GET /api/x402/network-cost: the settlement-rail recommendation.
+ *
+ * Free operational read over the snapshots the cross-chain-cost loop writes
+ * hourly. Two things make it worth pinning rather than eyeballing:
+ *
+ * - It steers real money. `recommended_network` is what the app reads to pick
+ * the cheaper rail, so an empty table must return null rather than a default
+ * that looks like a measurement nobody took.
+ * - Its degraded path is deliberately not an error page. A table that does not
+ * exist yet (the loop has never run) is "no samples", answered 200, while a
+ * genuine read failure is a 503. Collapsing those two states would either
+ * alarm on a cold start or hide a real outage.
+ *
+ * A local DATABASE_URL is not available to this suite, so the query layer is
+ * substituted and the handler runs otherwise untouched.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Queue of results the handler's sequential queries drain, in order:
+// latest snapshot, then the rolling-window aggregate.
+let queue = [];
+let failure = null;
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: async () => {
+ if (failure) throw failure;
+ return queue.shift() ?? [];
+ },
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const { default: handler } = await import('../api/x402/network-cost.js');
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(payload) { this.headersSent = true; this.writableEnded = true; this.body = payload; },
+ get json() { return this.body ? JSON.parse(this.body) : null; },
+ };
+}
+
+const req = (url = '/api/x402/network-cost') => ({ method: 'GET', url, headers: {}, socket: {} });
+
+const SNAPSHOT = {
+ checked_at: '2026-08-14T04:00:00.000Z',
+ amount_usd: '0.001',
+ solana_advertised: true,
+ solana_settled: true,
+ solana_gas_usd: '0.0000241',
+ solana_total_usd: '0.0010241',
+ solana_fee_lamports: '5000',
+ solana_fee_source: 'onchain',
+ solana_tx: 'THREEsyntheticSignature1111111111111111111111',
+ base_advertised: true,
+ base_gas_usd: '0.0031',
+ base_total_usd: '0.0041',
+ base_gas_price_wei: '12000000',
+ base_gas_units: '65000',
+ gas_premium_ratio: '128.6',
+ cheapest_network: 'solana',
+ sol_price_usd: '182.4',
+ eth_price_usd: '3120.5',
+};
+
+const ROLLUP = {
+ samples: '48',
+ avg_gas_premium_ratio: '121.7',
+ avg_solana_gas_usd: '0.0000239',
+ avg_base_gas_usd: '0.0029',
+ solana_wins: '47',
+ base_wins: '1',
+};
+
+beforeEach(() => {
+ queue = [];
+ failure = null;
+});
+
+describe('GET /api/x402/network-cost', () => {
+ it('returns the latest snapshot, the rolling stats, and a recommendation', async () => {
+ queue.push([SNAPSHOT], [ROLLUP]);
+ const res = mockRes();
+ await handler(req(), res);
+
+ expect(res.statusCode).toBe(200);
+ const b = res.json;
+ expect(b.ok).toBe(true);
+ expect(b.recommended_network).toBe('solana');
+ expect(b.window_hours).toBe(168);
+ // Numerics arrive from Postgres as strings; the client gets numbers.
+ expect(b.latest.solana.gas_usd).toBe(0.0000241);
+ expect(b.latest.solana.fee_lamports).toBe(5000);
+ expect(b.latest.base.gas_price_gwei).toBe(0.012);
+ expect(b.latest.base.settled).toBe(false);
+ expect(b.rolling.samples).toBe(48);
+ expect(b.rolling.solana_cheapest_count).toBe(47);
+ expect(b.rolling.avg_gas_premium_ratio).toBe(121.7);
+ });
+
+ it('clamps the window instead of trusting the query string', async () => {
+ queue.push([SNAPSHOT], [ROLLUP]);
+ const res = mockRes();
+ await handler(req('/api/x402/network-cost?window=99999'), res);
+ expect(res.json.window_hours).toBe(720);
+
+ queue.push([SNAPSHOT], [ROLLUP]);
+ const res2 = mockRes();
+ await handler(req('/api/x402/network-cost?window=abc'), res2);
+ expect(res2.json.window_hours).toBe(168);
+ });
+
+ it('recommends nothing when no snapshot has ever been taken', async () => {
+ queue.push([], [{ samples: '0' }]);
+ const res = mockRes();
+ await handler(req(), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.json.recommended_network).toBeNull();
+ expect(res.json.latest).toBeNull();
+ expect(res.json.rolling.samples).toBe(0);
+ });
+
+ it('falls back to the window majority when the latest row has no verdict', async () => {
+ queue.push(
+ [{ ...SNAPSHOT, cheapest_network: null }],
+ [{ ...ROLLUP, solana_wins: '2', base_wins: '30' }],
+ );
+ const res = mockRes();
+ await handler(req(), res);
+
+ expect(res.json.recommended_network).toBe('base');
+ });
+
+ it('answers 200 no_samples_yet when the loop has never created the table', async () => {
+ failure = new Error('relation "cross_chain_cost_comparison" does not exist');
+ const res = mockRes();
+ await handler(req(), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.json.note).toBe('no_samples_yet');
+ expect(res.json.recommended_network).toBeNull();
+ expect(res.json.error).toBeUndefined();
+ });
+
+ it('answers 503 on a real read failure rather than pretending it is empty', async () => {
+ failure = new Error('connection terminated unexpectedly');
+ const res = mockRes();
+ await handler(req(), res);
+
+ expect(res.statusCode).toBe(503);
+ expect(res.json.ok).toBe(false);
+ expect(res.json.error).toBe('network_cost_read_failed');
+ expect(res.json.note).toBeUndefined();
+ });
+
+ it('refuses a method other than GET', async () => {
+ const res = mockRes();
+ await handler({ ...req(), method: 'POST' }, res);
+ expect(res.statusCode).toBe(405);
+ });
+});