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(api): cover the hardened error envelopes, provider aliases, and subpath route table

nirholas78115ff8cd8d
diff --git a/tests/agent-trade-x402.test.js b/tests/agent-trade-x402.test.js
new file mode 100644
index 000000000..8ad2132bc
--- /dev/null
+++ b/tests/agent-trade-x402.test.js
@@ -0,0 +1,284 @@
+// The agent-to-agent x402 pair: the Oracle's paid skill endpoint and the demo
+// orchestrator that buys from it.
+//
+// Both move real SOL in production, so the paths that MUST NOT spend are the
+// ones worth pinning:
+// • skill.js rejects a malformed signature before it ever reaches an RPC
+// (a junk `sig` used to cost three getTransaction round-trips plus two
+// seconds of back-off, and tripped the shared RPC pool's method breaker).
+// • a verified signature buys exactly one call, and is released again when
+// the analysis the buyer paid for could not be produced.
+// • demo.js never signs a transfer when the buyer is short, and never when
+// no analysis lane is configured to deliver what the payment buys.
+//
+// Every chain, model, cache, and rate-limit dependency is mocked: this suite
+// touches no network and signs nothing.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import bs58 from 'bs58';
+
+const BUYER = 'BuyerAgentAddress111111111111111111111111111';
+const SELLER = 'SellerAgentAddress111111111111111111111111111';
+const GOOD_SIG = bs58.encode(Buffer.alloc(64, 7));
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => []),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: () => false,
+}));
+
+const getTransaction = vi.fn();
+const getSolBalance = vi.fn();
+const sendSol = vi.fn();
+vi.mock('../api/_lib/avatar-wallet.js', () => ({
+ LAMPORTS_PER_SOL: 1_000_000_000,
+ loadAvatarKeypair: (secret) => {
+ if (secret === 'buyer-secret') return { publicKey: { toBase58: () => BUYER } };
+ if (secret === 'seller-secret') return { publicKey: { toBase58: () => SELLER } };
+ throw new Error('bad secret');
+ },
+ getConnection: () => ({ getTransaction: (...a) => getTransaction(...a) }),
+ getSolBalance: (...a) => getSolBalance(...a),
+ sendSol: (...a) => sendSol(...a),
+ solUsdPrice: async () => 150,
+ explorerTxUrl: (sig) => `https://solscan.io/tx/${sig}`,
+}));
+
+const watsonxConfig = vi.fn(() => ({ configured: false }));
+vi.mock('../api/_lib/watsonx.js', () => ({
+ watsonxConfig: (...a) => watsonxConfig(...a),
+ watsonxChatComplete: vi.fn(),
+}));
+
+const llmComplete = vi.fn();
+const providerChain = vi.fn(() => [{ name: 'openrouter', model: 'free/model-a' }]);
+vi.mock('../api/_lib/llm.js', () => ({
+ llmComplete: (...a) => llmComplete(...a),
+ providerChain: (...a) => providerChain(...a),
+ LlmUnavailableError: class extends Error {},
+}));
+
+const cache = new Map();
+vi.mock('../api/_lib/cache.js', () => ({
+ cacheGet: async (k) => (cache.has(k) ? cache.get(k) : null),
+ cacheSet: async (k, v) => { cache.set(k, v); },
+ cacheDel: async (k) => { cache.delete(k); },
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ clientIp: () => '198.51.100.7',
+ limits: {
+ publicIp: async () => ({ success: true }),
+ authedReadIp: async () => ({ success: true }),
+ avatarPayoutDaily: async () => ({ success: true }),
+ },
+}));
+
+const { default: skillHandler } = await import('../api/agent-trade/skill.js');
+const { default: demoHandler } = await import('../api/agent-trade/demo.js');
+
+function mkReq(url) {
+ return { method: 'GET', url, headers: {}, on() {}, destroy() {} };
+}
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ chunks: [],
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ flushHeaders() {},
+ write(chunk) { this.chunks.push(String(chunk)); },
+ end(b) { if (b != null) this.body = String(b); this.writableEnded = true; },
+ };
+}
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+// Every SSE frame the handler wrote, decoded back into objects.
+const events = (res) =>
+ res.chunks
+ .join('')
+ .split('\n\n')
+ .filter((f) => f.startsWith('data: '))
+ .map((f) => JSON.parse(f.slice(6)));
+
+// A confirmed transfer of `lamports` from BUYER to SELLER, fresh enough to pass
+// the freshness window.
+function paidTx({ lamports = 1_000_000, blockTime = Math.floor(Date.now() / 1000) } = {}) {
+ return {
+ blockTime,
+ meta: { preBalances: [5_000_000_000, 0], postBalances: [5_000_000_000 - lamports, lamports] },
+ transaction: {
+ message: {
+ staticAccountKeys: [{ toString: () => BUYER }, { toString: () => SELLER }],
+ },
+ },
+ };
+}
+
+beforeEach(() => {
+ cache.clear();
+ getTransaction.mockReset();
+ getSolBalance.mockReset();
+ sendSol.mockReset();
+ llmComplete.mockReset().mockResolvedValue({
+ text: 'SOL liquidity is thinning into the weekly close.',
+ model: 'free/model-a',
+ provider: 'openrouter',
+ });
+ watsonxConfig.mockReset().mockReturnValue({ configured: false });
+ providerChain.mockReset().mockReturnValue([{ name: 'openrouter', model: 'free/model-a' }]);
+ process.env.AGENT_SELLER_SECRET = 'seller-secret';
+ process.env.AGENT_BUYER_SECRET = 'buyer-secret';
+ process.env.AGENT_TRADE_NETWORK = 'mainnet';
+ process.env.AGENT_TRADE_PRICE_SOL = '0.001';
+});
+
+describe('GET /api/agent-trade/skill', () => {
+ it('503s when the Oracle wallet is not configured', async () => {
+ delete process.env.AGENT_SELLER_SECRET;
+ const res = mkRes();
+ await skillHandler(mkReq('/api/agent-trade/skill'), res);
+ expect(res.statusCode).toBe(503);
+ expect(parse(res).error).toBe('not_configured');
+ });
+
+ it('answers a payment-less call with the x402 price manifest', async () => {
+ const res = mkRes();
+ await skillHandler(mkReq('/api/agent-trade/skill?topic=solana'), res);
+ expect(res.statusCode).toBe(402);
+ expect(parse(res)).toMatchObject({
+ x402: true,
+ currency: 'SOL',
+ recipient: SELLER,
+ price: { sol: 0.001, lamports: 1_000_000 },
+ });
+ expect(getTransaction).not.toHaveBeenCalled();
+ });
+
+ it('rejects a malformed signature without touching the chain', async () => {
+ for (const sig of ['not-a-signature', '0OIl', 'A'.repeat(200), bs58.encode(Buffer.alloc(32, 3))]) {
+ const res = mkRes();
+ await skillHandler(mkReq(`/api/agent-trade/skill?sig=${encodeURIComponent(sig)}`), res);
+ expect(res.statusCode).toBe(402);
+ expect(parse(res).error).toBe('bad_payment');
+ }
+ expect(getTransaction).not.toHaveBeenCalled();
+ });
+
+ it('delivers the analysis for a verified payment', async () => {
+ getTransaction.mockResolvedValue(paidTx());
+ const res = mkRes();
+ await skillHandler(
+ mkReq(`/api/agent-trade/skill?sig=${GOOD_SIG}&buyer=${BUYER}&topic=solana%20liquidity`),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toMatchObject({
+ ok: true,
+ topic: 'solana liquidity',
+ provider: 'openrouter',
+ payment: { sig: GOOD_SIG, lamports: 1_000_000 },
+ });
+ expect(llmComplete).toHaveBeenCalledTimes(1);
+ });
+
+ it('lets one signature buy exactly one call', async () => {
+ getTransaction.mockResolvedValue(paidTx());
+ const first = mkRes();
+ await skillHandler(mkReq(`/api/agent-trade/skill?sig=${GOOD_SIG}`), first);
+ expect(first.statusCode).toBe(200);
+
+ const replay = mkRes();
+ await skillHandler(mkReq(`/api/agent-trade/skill?sig=${GOOD_SIG}`), replay);
+ expect(replay.statusCode).toBe(402);
+ expect(parse(replay).error).toBe('payment_replayed');
+ expect(llmComplete).toHaveBeenCalledTimes(1);
+ });
+
+ it('rejects an underpayment', async () => {
+ getTransaction.mockResolvedValue(paidTx({ lamports: 10_000 }));
+ const res = mkRes();
+ await skillHandler(mkReq(`/api/agent-trade/skill?sig=${GOOD_SIG}`), res);
+ expect(res.statusCode).toBe(402);
+ expect(parse(res).error).toBe('bad_payment');
+ expect(llmComplete).not.toHaveBeenCalled();
+ });
+
+ it('rejects a payment whose buyer is not in the transaction', async () => {
+ getTransaction.mockResolvedValue(paidTx());
+ const res = mkRes();
+ await skillHandler(
+ mkReq(`/api/agent-trade/skill?sig=${GOOD_SIG}&buyer=SomeoneElse111111111111111111111111111111`),
+ res,
+ );
+ expect(res.statusCode).toBe(402);
+ expect(parse(res).error).toBe('bad_payment');
+ });
+
+ it('rejects a stale payment', async () => {
+ getTransaction.mockResolvedValue(paidTx({ blockTime: Math.floor(Date.now() / 1000) - 3600 }));
+ const res = mkRes();
+ await skillHandler(mkReq(`/api/agent-trade/skill?sig=${GOOD_SIG}`), res);
+ expect(res.statusCode).toBe(402);
+ expect(parse(res).error).toBe('payment_expired');
+ });
+
+ it('releases the signature when the analysis the buyer paid for fails', async () => {
+ getTransaction.mockResolvedValue(paidTx());
+ llmComplete.mockRejectedValueOnce(new Error('every provider is down'));
+ const failed = mkRes();
+ await skillHandler(mkReq(`/api/agent-trade/skill?sig=${GOOD_SIG}`), failed);
+ expect(failed.statusCode).toBe(502);
+ expect(parse(failed).error).toBe('analysis_failed');
+
+ // The buyer's SOL is spent, so their retry must not be read as a replay.
+ const retry = mkRes();
+ await skillHandler(mkReq(`/api/agent-trade/skill?sig=${GOOD_SIG}`), retry);
+ expect(retry.statusCode).toBe(200);
+ });
+});
+
+describe('GET /api/agent-trade/demo', () => {
+ it('reports wallet configuration without opening a stream', async () => {
+ const res = mkRes();
+ await demoHandler(mkReq('/api/agent-trade/demo?check=1'), res);
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toMatchObject({ configured: true, buyer: { address: BUYER } });
+ expect(res.chunks).toHaveLength(0);
+ });
+
+ it('names the missing secrets when the demo wallets are unset', async () => {
+ delete process.env.AGENT_BUYER_SECRET;
+ delete process.env.AGENT_SELLER_SECRET;
+ const res = mkRes();
+ await demoHandler(mkReq('/api/agent-trade/demo'), res);
+ const [ev] = events(res);
+ expect(ev.code).toBe('not_configured');
+ expect(ev.message).toContain('AGENT_BUYER_SECRET');
+ expect(ev.message).toContain('AGENT_SELLER_SECRET');
+ expect(sendSol).not.toHaveBeenCalled();
+ });
+
+ it('never signs a transfer the buyer cannot cover', async () => {
+ getSolBalance.mockResolvedValue({ sol: 0, lamports: 0 });
+ const res = mkRes();
+ await demoHandler(mkReq('/api/agent-trade/demo'), res);
+ const codes = events(res).map((e) => e.code).filter(Boolean);
+ expect(codes).toContain('insufficient_funds');
+ expect(sendSol).not.toHaveBeenCalled();
+ });
+
+ it('never spends SOL when no analysis lane can deliver the skill', async () => {
+ getSolBalance.mockResolvedValue({ sol: 1, lamports: 1_000_000_000 });
+ watsonxConfig.mockReturnValue({ configured: false });
+ providerChain.mockReturnValue([]);
+ const res = mkRes();
+ await demoHandler(mkReq('/api/agent-trade/demo'), res);
+ const codes = events(res).map((e) => e.code).filter(Boolean);
+ expect(codes).toContain('analysis_unavailable');
+ expect(sendSol).not.toHaveBeenCalled();
+ expect(events(res).map((e) => e.type)).not.toContain('paying');
+ });
+});
diff --git a/tests/agi-state.test.js b/tests/agi-state.test.js
new file mode 100644
index 000000000..28a536187
--- /dev/null
+++ b/tests/agi-state.test.js
@@ -0,0 +1,178 @@
+import { describe, it, expect } from 'vitest';
+import { deriveCognition, shapeDecision, DOCTRINE } from '../api/agi/state.js';
+
+const NOW = 1_800_000_000_000;
+
+const perf = (over = {}) => ({
+ closed_count: 8,
+ open_count: 0,
+ realized_pnl_sol: 0,
+ unrealized_pnl_sol: 0,
+ ...over,
+});
+
+const decision = (over = {}) => ({
+ id: 'dec-1',
+ seq: 12,
+ kind: 'buy',
+ subject_ref: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ rationale: 'fresh launch, clean wallet graph',
+ confidence: '0.72',
+ prediction: { direction: 'up' },
+ decided_at: new Date(NOW - 30_000).toISOString(),
+ observed: null,
+ was_correct: null,
+ pnl_sol: null,
+ impact: null,
+ outcome_status: null,
+ ...over,
+});
+
+describe('shapeDecision', () => {
+ it('marks an unreconciled decision pending and coerces numerics', () => {
+ const out = shapeDecision(decision(), 'mainnet');
+ expect(out.seq).toBe(12);
+ expect(out.confidence).toBe(0.72);
+ expect(out.mint).toBe('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');
+ expect(out.outcome).toEqual({ status: 'pending' });
+ });
+
+ it('attaches the on-chain proof url once an outcome is reconciled', () => {
+ const out = shapeDecision(
+ decision({
+ outcome_status: 'reconciled',
+ was_correct: true,
+ pnl_sol: '1.25',
+ impact: '0.4',
+ observed: { sell_sig: 'SIG123' },
+ }),
+ 'mainnet',
+ );
+ expect(out.outcome.status).toBe('reconciled');
+ expect(out.outcome.was_correct).toBe(true);
+ expect(out.outcome.pnl_sol).toBe(1.25);
+ expect(out.outcome.proof_url).toBe('https://solscan.io/tx/SIG123');
+ });
+
+ it('points the proof url at the devnet cluster on devnet', () => {
+ const out = shapeDecision(
+ decision({ outcome_status: 'reconciled', was_correct: false, observed: { sell_sig: 'SIG9' } }),
+ 'devnet',
+ );
+ expect(out.outcome.proof_url).toBe('https://solscan.io/tx/SIG9?cluster=devnet');
+ });
+
+ it('leaves the proof url null when no sell signature was observed', () => {
+ const out = shapeDecision(
+ decision({ outcome_status: 'reconciled', was_correct: true, observed: {} }),
+ 'mainnet',
+ );
+ expect(out.outcome.proof_url).toBeNull();
+ });
+});
+
+describe('deriveCognition', () => {
+ it('awakens when there is no track record and no decisions', () => {
+ const cog = deriveCognition({ reputation: null, perf: null, decisions: [], now: NOW });
+ expect(cog.state).toBe('awakening');
+ expect(cog.conviction).toBeNull();
+ expect(cog.emotion).toBeNull();
+ expect(cog.valence).toBeGreaterThanOrEqual(-1);
+ expect(cog.arousal).toBeLessThanOrEqual(1);
+ });
+
+ it('reads conviction off the most recent decision and fires curiosity', () => {
+ const decisions = [shapeDecision(decision({ decided_at: new Date(NOW - 20_000).toISOString() }), 'mainnet')];
+ const cog = deriveCognition({ reputation: null, perf: perf(), decisions, now: NOW });
+ expect(cog.state).toBe('conviction');
+ expect(cog.conviction).toBe(0.72);
+ expect(cog.emotion.trigger).toBe('curiosity');
+ });
+
+ it('celebrates a call that just paid off', () => {
+ const decisions = [
+ shapeDecision(
+ decision({
+ decided_at: new Date(NOW - 10 * 60_000).toISOString(),
+ outcome_status: 'reconciled',
+ was_correct: true,
+ pnl_sol: '2.0',
+ observed: { sell_sig: 'SIGWIN' },
+ }),
+ 'mainnet',
+ ),
+ ];
+ const cog = deriveCognition({ reputation: { score: 80 }, perf: perf(), decisions, now: NOW });
+ expect(cog.state).toBe('vindicated');
+ expect(cog.emotion.trigger).toBe('celebration');
+ expect(cog.valence).toBeGreaterThan(0);
+ });
+
+ it('is humbled by a recent call that went against it', () => {
+ const decisions = [
+ shapeDecision(
+ decision({
+ decided_at: new Date(NOW - 10 * 60_000).toISOString(),
+ outcome_status: 'reconciled',
+ was_correct: false,
+ pnl_sol: '-1.5',
+ observed: { sell_sig: 'SIGLOSS' },
+ }),
+ 'mainnet',
+ ),
+ ];
+ const cog = deriveCognition({ reputation: { score: 20 }, perf: perf(), decisions, now: NOW });
+ expect(cog.state).toBe('humbled');
+ expect(cog.emotion.trigger).toBe('concern');
+ expect(cog.valence).toBeLessThan(0);
+ });
+
+ it('goes dormant when the last call is stale and nothing is open', () => {
+ const decisions = [shapeDecision(decision({ decided_at: new Date(NOW - 3 * 3_600_000).toISOString() }), 'mainnet')];
+ const cog = deriveCognition({ reputation: null, perf: perf({ realized_pnl_sol: -0.014 }), decisions, now: NOW });
+ expect(cog.state).toBe('dormant');
+ expect(cog.summary).toContain('-0.014 SOL realized');
+ });
+
+ it('reports how many positions it is managing when holding', () => {
+ const decisions = [shapeDecision(decision({ decided_at: new Date(NOW - 20 * 60_000).toISOString() }), 'mainnet')];
+ const cog = deriveCognition({
+ reputation: null,
+ perf: perf({ open_count: 3, unrealized_pnl_sol: 0.5 }),
+ decisions,
+ now: NOW,
+ });
+ expect(cog.state).toBe('holding');
+ expect(cog.label).toBe('Managing 3 open positions');
+ expect(cog.arousal).toBeGreaterThan(0.3);
+ });
+
+ it('keeps every scalar inside its declared range on extreme inputs', () => {
+ const decisions = [shapeDecision(decision({ confidence: '9.9' }), 'mainnet')];
+ const cog = deriveCognition({
+ reputation: { score: 100 },
+ perf: perf({ unrealized_pnl_sol: 10_000, open_count: 99 }),
+ decisions,
+ now: NOW,
+ });
+ expect(cog.valence).toBeLessThanOrEqual(1);
+ expect(cog.arousal).toBeLessThanOrEqual(1);
+ expect(cog.conviction).toBe(1);
+ });
+
+ it('survives a decision with no timestamp instead of emitting NaN', () => {
+ const decisions = [shapeDecision(decision({ decided_at: null }), 'mainnet')];
+ const cog = deriveCognition({ reputation: null, perf: perf(), decisions, now: NOW });
+ expect(Number.isFinite(cog.valence)).toBe(true);
+ expect(Number.isFinite(cog.arousal)).toBe(true);
+ expect(cog.state).toBe('hunting');
+ });
+});
+
+describe('DOCTRINE', () => {
+ it('states a narrow domain and is frozen', () => {
+ expect(DOCTRINE.is_narrow).toBe(true);
+ expect(DOCTRINE.refusals.length).toBeGreaterThan(0);
+ expect(Object.isFrozen(DOCTRINE)).toBe(true);
+ });
+});
diff --git a/tests/aixbt-error-envelope.test.js b/tests/aixbt-error-envelope.test.js
new file mode 100644
index 000000000..d45ebb6e1
--- /dev/null
+++ b/tests/aixbt-error-envelope.test.js
@@ -0,0 +1,99 @@
+/**
+ * api/aixbt/_shared.js: the error envelope every /api/aixbt/* handler responds
+ * through.
+ *
+ * The classification here is the difference between an actionable empty state
+ * and a dead end, so it is pinned:
+ *
+ * - A missing key is a 503 carrying a `setup` hint the UI renders verbatim.
+ * - aixbt REJECTING our key (401/403) is the same class of deployment fault,
+ * not a client-auth failure. Regression guard: it used to relay the raw
+ * 401 to a caller of a public, credential-free endpoint, telling them to
+ * authenticate against a door they hold no key to (and with no
+ * WWW-Authenticate header, which RFC 9110 requires of any 401).
+ * - Upstream throttling / outages keep their descriptive code + status.
+ * - Anything genuinely internal is sanitized to a 500 with a support ref.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { respondAixbtError } from '../api/aixbt/_shared.js';
+import { AixbtNotConfiguredError } from '../api/_lib/aixbt.js';
+
+// Minimal ServerResponse stand-in: case-insensitive header store + end capture.
+function fakeRes() {
+ const headers = {};
+ return {
+ statusCode: 0,
+ body: undefined,
+ setHeader(k, v) { headers[String(k).toLowerCase()] = v; },
+ getHeader(k) { return headers[String(k).toLowerCase()]; },
+ end(b) { this.body = b; },
+ get payload() { return JSON.parse(this.body); },
+ };
+}
+
+/** The shape api/_lib/aixbt.js throws for a non-2xx upstream response. */
+function upstreamError(message, status, code) {
+ return Object.assign(new Error(message), { status, code });
+}
+
+describe('respondAixbtError', () => {
+ it('answers a missing key with 503 and the setup hint', () => {
+ const res = fakeRes();
+ respondAixbtError(res, new AixbtNotConfiguredError());
+ expect(res.statusCode).toBe(503);
+ expect(res.payload.error).toBe('aixbt_not_configured');
+ expect(res.payload.setup).toContain('AIXBT_API_KEY');
+ });
+
+ for (const status of [401, 403]) {
+ it(`treats an upstream ${status} as a deployment fault, not a client one`, () => {
+ const res = fakeRes();
+ respondAixbtError(res, upstreamError('aixbt /intel failed: Unauthorized', status, 'aixbt_unauthorized'));
+ expect(res.statusCode).toBe(503);
+ // The code is preserved so existing clients keep their typed branch.
+ expect(res.payload.error).toBe('aixbt_unauthorized');
+ expect(res.payload.setup).toContain('AIXBT_API_KEY');
+ });
+ }
+
+ it('relays upstream throttling with its own status and code', () => {
+ const res = fakeRes();
+ respondAixbtError(res, upstreamError('aixbt /projects failed: rate limited', 429, 'aixbt_rate_limited'));
+ expect(res.statusCode).toBe(429);
+ expect(res.payload.error).toBe('aixbt_rate_limited');
+ expect(res.payload.error_description).toContain('rate limited');
+ });
+
+ it('relays an upstream outage as 504 without sanitizing the reason', () => {
+ const res = fakeRes();
+ respondAixbtError(res, upstreamError('aixbt unreachable: fetch failed', 504, 'aixbt_upstream_error'));
+ expect(res.statusCode).toBe(504);
+ expect(res.payload.error).toBe('aixbt_upstream_error');
+ expect(res.payload.error_description).toContain('unreachable');
+ });
+
+ it('relays an upstream 404 so an unknown project id stays legible', () => {
+ const res = fakeRes();
+ respondAixbtError(res, upstreamError('aixbt /projects/nope failed: HTTP 404', 404, 'aixbt_upstream_error'));
+ expect(res.statusCode).toBe(404);
+ expect(res.payload.error).toBe('aixbt_upstream_error');
+ });
+
+ it('sanitizes an untyped internal fault to a 500 with a support ref', () => {
+ const res = fakeRes();
+ respondAixbtError(res, new TypeError('cannot read properties of undefined'));
+ expect(res.statusCode).toBe(500);
+ expect(res.payload.error).toBe('aixbt_error');
+ expect(res.payload.ref).toBeTruthy();
+ // The internal message must never reach the client.
+ expect(res.body).not.toContain('cannot read properties');
+ });
+
+ it('never lets an error response be cached', () => {
+ const res = fakeRes();
+ res.setHeader('cache-control', 'public, s-maxage=600');
+ respondAixbtError(res, new AixbtNotConfiguredError());
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ });
+});
diff --git a/tests/api-agents-recovery-handler.test.js b/tests/api-agents-recovery-handler.test.js
new file mode 100644
index 000000000..006b9b36d
--- /dev/null
+++ b/tests/api-agents-recovery-handler.test.js
@@ -0,0 +1,226 @@
+// Tests for api/agents/recovery.js — the HTTP dispatcher behind
+// /api/agents/:id/recovery. It is not a routable file of its own: the
+// vercel.json rule sends the path to api/agents/[id].js, which imports this
+// module and calls it with (req, res, id, action, parts). So nothing exercises
+// its authorization gates unless a test does it directly.
+//
+// tests/agent-recovery.test.js covers the pure state machine in
+// api/_lib/agent-recovery.js; this file covers the layer above it: who is
+// allowed to read the status, and what an unknown sub-resource answers.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const getSessionUserMock = vi.fn();
+const authenticateBearerMock = vi.fn();
+const extractBearerMock = vi.fn();
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: (...a) => authenticateBearerMock(...a),
+ extractBearer: (...a) => extractBearerMock(...a),
+}));
+
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+vi.mock('../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'http://localhost:3000' } }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ clientIp: () => '127.0.0.1',
+ limits: new Proxy({}, { get: () => async () => ({ success: true, limit: 60, remaining: 59, reset: 0 }) }),
+}));
+
+const listGuardiansMock = vi.fn();
+const getActiveRequestMock = vi.fn();
+const getOwnerActivityMock = vi.fn();
+vi.mock('../api/_lib/agent-recovery.js', () => ({
+ getRecoveryConfig: () => ({ threshold: 2, dead_man: { enabled: false, inactivity_days: 90, grace_days: 14 } }),
+ effectiveThreshold: (_c, n) => Math.min(2, n),
+ listGuardians: (...a) => listGuardiansMock(...a),
+ setGuardiansAndConfig: vi.fn(),
+ getOwnerActivity: (...a) => getOwnerActivityMock(...a),
+ deadManStatus: () => ({ enabled: false, eligible: false }),
+ getActiveRequest: (...a) => getActiveRequestMock(...a),
+ decorateRequest: vi.fn(),
+ listRequests: vi.fn(async () => []),
+ createRecoveryRequest: vi.fn(),
+ recordVote: vi.fn(),
+ cancelRequest: vi.fn(),
+ completeIfReady: vi.fn(),
+ ownerCheckIn: vi.fn(),
+ armInheritance: vi.fn(),
+ confirmInheritance: vi.fn(),
+ resolveUserHandle: vi.fn(),
+ isUuid: (v) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(String(v)),
+ MAX_GUARDIANS: 7,
+}));
+
+const { default: recoveryHandler } = await import('../api/agents/recovery.js');
+
+const AGENT = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+const OWNER = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
+const STRANGER = 'cccccccc-cccc-cccc-cccc-cccccccccccc';
+
+function mkReq({ method = 'GET', url = `/api/agents/${AGENT}/recovery` } = {}) {
+ return { method, url, headers: {}, on() {}, destroy() {} };
+}
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false, headersSent: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(b) { this.body = b; this.writableEnded = true; this.headersSent = true; },
+ };
+}
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+// loadContext issues exactly two queries: the agent row, then the caller's roles.
+function queueContext({ agent, roles }) {
+ let call = 0;
+ sqlMock.mockImplementation(() => {
+ call += 1;
+ if (call === 1) return Promise.resolve(agent ? [agent] : []);
+ return Promise.resolve(roles);
+ });
+}
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ getSessionUserMock.mockReset().mockResolvedValue({ id: OWNER });
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+ extractBearerMock.mockReset().mockReturnValue(null);
+ listGuardiansMock.mockReset().mockResolvedValue([]);
+ getActiveRequestMock.mockReset().mockResolvedValue(null);
+ getOwnerActivityMock.mockReset().mockResolvedValue({ lastActiveAt: new Date(0), signals: [] });
+});
+
+describe('GET /api/agents/:id/recovery', () => {
+ it('returns the full circle to the owner, with the unredacted guardian roster', async () => {
+ queueContext({
+ agent: { id: AGENT, user_id: OWNER, name: 'Recoverable', meta: {}, avatar_id: null, avatar_url: null },
+ roles: [],
+ });
+ listGuardiansMock.mockResolvedValue([
+ { user_id: STRANGER, role: 'guardian', label: 'ke•••@three.ws', avatar_url: null, email_masked: 'ke•••@three.ws' },
+ ]);
+
+ const res = mkRes();
+ await recoveryHandler(mkReq(), res, AGENT, null, ['api', 'agents', AGENT, 'recovery']);
+
+ expect(res.statusCode).toBe(200);
+ const body = parse(res).data;
+ expect(body.viewer).toMatchObject({ is_owner: true, is_guardian: false, is_beneficiary: false });
+ expect(body.guardian_count).toBe(1);
+ // Owners get the raw rows (email_masked included); non-owners get the
+ // projected shape asserted below.
+ expect(body.guardians[0]).toHaveProperty('email_masked');
+ expect(body.dead_man).toHaveProperty('signals');
+ expect(body.max_guardians).toBe(7);
+ });
+
+ it('redacts the roster and hides the owner-activity signals from a guardian', async () => {
+ getSessionUserMock.mockResolvedValue({ id: STRANGER });
+ queueContext({
+ agent: { id: AGENT, user_id: OWNER, name: 'Recoverable', meta: {}, avatar_id: null, avatar_url: null },
+ roles: [{ role: 'guardian' }],
+ });
+ listGuardiansMock.mockResolvedValue([
+ { user_id: STRANGER, role: 'guardian', label: 'ke•••@three.ws', avatar_url: null, email_masked: 'ke•••@three.ws' },
+ ]);
+
+ const res = mkRes();
+ await recoveryHandler(mkReq(), res, AGENT, null, ['api', 'agents', AGENT, 'recovery']);
+
+ expect(res.statusCode).toBe(200);
+ const body = parse(res).data;
+ expect(body.viewer).toMatchObject({ is_owner: false, is_guardian: true });
+ expect(body.guardians[0]).not.toHaveProperty('email_masked');
+ expect(body.guardians[0]).toMatchObject({ role: 'guardian', is_you: true });
+ expect(body.dead_man).not.toHaveProperty('signals');
+ });
+
+ it('401s an anonymous caller before touching the agent row', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ sqlMock.mockResolvedValue([]);
+
+ const res = mkRes();
+ await recoveryHandler(mkReq(), res, AGENT, null, ['api', 'agents', AGENT, 'recovery']);
+
+ expect(res.statusCode).toBe(401);
+ expect(parse(res).error).toBe('unauthorized');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('403s a signed-in caller who is not in the recovery circle', async () => {
+ getSessionUserMock.mockResolvedValue({ id: STRANGER });
+ queueContext({
+ agent: { id: AGENT, user_id: OWNER, name: 'Recoverable', meta: {}, avatar_id: null, avatar_url: null },
+ roles: [],
+ });
+
+ const res = mkRes();
+ await recoveryHandler(mkReq(), res, AGENT, null, ['api', 'agents', AGENT, 'recovery']);
+
+ expect(res.statusCode).toBe(403);
+ expect(parse(res).error).toBe('forbidden');
+ });
+
+ it('404s an agent that does not exist', async () => {
+ queueContext({ agent: null, roles: [] });
+
+ const res = mkRes();
+ await recoveryHandler(mkReq(), res, AGENT, null, ['api', 'agents', AGENT, 'recovery']);
+
+ expect(res.statusCode).toBe(404);
+ expect(parse(res).error).toBe('not_found');
+ });
+});
+
+describe('recovery sub-resource dispatch', () => {
+ it('405s a method the /recovery resource does not implement', async () => {
+ queueContext({
+ agent: { id: AGENT, user_id: OWNER, name: 'Recoverable', meta: {}, avatar_id: null, avatar_url: null },
+ roles: [],
+ });
+
+ const res = mkRes();
+ await recoveryHandler(mkReq({ method: 'DELETE' }), res, AGENT, null, ['api', 'agents', AGENT, 'recovery']);
+
+ expect(res.statusCode).toBe(405);
+ expect(parse(res).error).toBe('method_not_allowed');
+ });
+
+ it('404s an unknown sub-resource instead of falling through to the status payload', async () => {
+ queueContext({
+ agent: { id: AGENT, user_id: OWNER, name: 'Recoverable', meta: {}, avatar_id: null, avatar_url: null },
+ roles: [],
+ });
+
+ const res = mkRes();
+ await recoveryHandler(mkReq({ url: `/api/agents/${AGENT}/recovery/bogus` }), res, AGENT, 'bogus', [
+ 'api', 'agents', AGENT, 'recovery', 'bogus',
+ ]);
+
+ expect(res.statusCode).toBe(404);
+ expect(parse(res).error_description).toBe('unknown recovery resource');
+ });
+
+ it('404s a non-uuid request id on an approve without querying for the vote', async () => {
+ queueContext({
+ agent: { id: AGENT, user_id: OWNER, name: 'Recoverable', meta: {}, avatar_id: null, avatar_url: null },
+ roles: [{ role: 'guardian' }],
+ });
+
+ const res = mkRes();
+ await recoveryHandler(
+ mkReq({ method: 'POST', url: `/api/agents/${AGENT}/recovery/requests/not-a-uuid/approve` }),
+ res, AGENT, 'requests',
+ ['api', 'agents', AGENT, 'recovery', 'requests', 'not-a-uuid', 'approve'],
+ );
+
+ expect(res.statusCode).toBe(404);
+ expect(parse(res).error_description).toBe('recovery request not found');
+ });
+});
diff --git a/tests/api/3d-generate.test.js b/tests/api/3d-generate.test.js
index c836f252a..2830ca8c3 100644
--- a/tests/api/3d-generate.test.js
+++ b/tests/api/3d-generate.test.js
@@ -409,6 +409,49 @@ describe('GET /api/3d/generate?job= — poll lifecycle', () => {
expect(res.statusCode).toBe(200);
expect(body.status).toBe('pending');
});
+
+ it('503s instead of looping forever when the lane is unconfigured here', async () => {
+ // A deployment with no 3D lane answers the poll 503 unconfigured. Reporting
+ // that as 'pending' would hand the agent a poll loop that can never finish,
+ // so it has to surface as the same terminal not_configured the submit path
+ // returns.
+ globalThis.fetch = vi.fn(async () =>
+ jsonResponse({ error: 'unconfigured', message: 'Set NVIDIA_API_KEY.' }, { status: 503 }),
+ );
+ const { res, body } = await dispatch(
+ makeReq({ method: 'GET', url: `/api/3d/generate?job=${SUBMIT_QUEUED.job_id}` }),
+ makeRes(),
+ );
+ expect(res.statusCode).toBe(503);
+ expect(body.error).toBe('not_configured');
+ expect(body.status).toBeUndefined();
+ });
+
+ it('501 backend_unconfigured is terminal too, not pending', async () => {
+ globalThis.fetch = vi.fn(async () =>
+ jsonResponse(
+ { error: 'backend_unconfigured', message: 'no NIM lane here' },
+ { status: 501 },
+ ),
+ );
+ const { res, body } = await dispatch(
+ makeReq({ method: 'GET', url: `/api/3d/generate?job=${SUBMIT_QUEUED.job_id}` }),
+ makeRes(),
+ );
+ expect(res.statusCode).toBe(503);
+ expect(body.error).toBe('not_configured');
+ });
+
+ it('keeps an unlabelled upstream 5xx as pending so the loop retries', async () => {
+ // Only an explicit unconfigured verdict is terminal; a bare 502 stays a blip.
+ globalThis.fetch = vi.fn(async () => jsonResponse({ error: 'boom' }, { status: 502 }));
+ const { res, body } = await dispatch(
+ makeReq({ method: 'GET', url: `/api/3d/generate?job=${SUBMIT_QUEUED.job_id}` }),
+ makeRes(),
+ );
+ expect(res.statusCode).toBe(200);
+ expect(body.status).toBe('pending');
+ });
});
describe('catalog entry', () => {
diff --git a/tests/api/api-keys.test.js b/tests/api/api-keys.test.js
index b0de33407..535e8773a 100644
--- a/tests/api/api-keys.test.js
+++ b/tests/api/api-keys.test.js
@@ -218,9 +218,13 @@ describe('method routing', () => {
});
});
+// api_keys.id is a uuid column and the handler rejects anything else with a
+// 400 before it reaches Postgres, so the revoke tests use real uuids.
+const KEY_ID = '9f2b6d41-6c1b-4a0e-9a5f-2f0c9c4d7b31';
+
describe('DELETE /api/api-keys/:id — revoke 200', () => {
it('returns 401 when unauthenticated', async () => {
- const { status, body } = await invokeRevoke({ id: 'k1' });
+ const { status, body } = await invokeRevoke({ id: KEY_ID });
expect(status).toBe(401);
expect(body.error).toBe('unauthorized');
});
@@ -228,12 +232,12 @@ describe('DELETE /api/api-keys/:id — revoke 200', () => {
it('revokes the owner’s live key and returns { id, revoked: true }', async () => {
authState.session = { id: 'user-1' };
// UPDATE ... returning id — one row means the live key was found + revoked.
- sqlState.queue.push([{ id: 'k1' }]);
+ sqlState.queue.push([{ id: KEY_ID }]);
- const { status, body } = await invokeRevoke({ id: 'k1' });
+ const { status, body } = await invokeRevoke({ id: KEY_ID });
expect(status).toBe(200);
- expect(body.data).toEqual({ id: 'k1', revoked: true });
+ expect(body.data).toEqual({ id: KEY_ID, revoked: true });
// The UPDATE must scope to the owner and only touch live keys, so a key
// can't be revoked by a non-owner or revoked twice.
@@ -242,7 +246,7 @@ describe('DELETE /api/api-keys/:id — revoke 200', () => {
expect(updateCall.query).toMatch(/set revoked_at = now\(\)/i);
expect(updateCall.query).toMatch(/user_id =/i);
expect(updateCall.query).toMatch(/revoked_at is null/i);
- expect(updateCall.values).toContain('k1');
+ expect(updateCall.values).toContain(KEY_ID);
expect(updateCall.values).toContain('user-1');
});
@@ -250,8 +254,8 @@ describe('DELETE /api/api-keys/:id — revoke 200', () => {
authState.session = { id: 'user-1' };
// Revoke the live key.
- sqlState.queue.push([{ id: 'k1' }]);
- const revoke = await invokeRevoke({ id: 'k1' });
+ sqlState.queue.push([{ id: KEY_ID }]);
+ const revoke = await invokeRevoke({ id: KEY_ID });
expect(revoke.status).toBe(200);
// The list endpoint filters on `revoked_at is null`, so the revoked key
@@ -270,25 +274,53 @@ describe('DELETE /api/api-keys/:id — revoke 200', () => {
authState.session = { id: 'user-1' };
// First revoke succeeds.
- sqlState.queue.push([{ id: 'k1' }]);
- const first = await invokeRevoke({ id: 'k1' });
+ sqlState.queue.push([{ id: KEY_ID }]);
+ const first = await invokeRevoke({ id: KEY_ID });
expect(first.status).toBe(200);
// Second revoke: the `revoked_at is null` guard matches nothing → no row.
sqlState.queue.push([]);
- const second = await invokeRevoke({ id: 'k1' });
+ const second = await invokeRevoke({ id: KEY_ID });
expect(second.status).toBe(404);
expect(second.body.error).toBe('not_found');
});
});
+describe('DELETE /api/api-keys/:id — malformed id', () => {
+ // api_keys.id is a uuid column, so a non-uuid segment used to reach Postgres
+ // and come back as 22P02 → 500 with a support ref. Bad input is a 400.
+ it.each(['not-a-uuid', ' ', '', "'; drop table api_keys; --"])(
+ 'returns 400 for %j without touching the database',
+ async (id) => {
+ authState.session = { id: 'user-1' };
+
+ const { status, body } = await invokeRevoke({ id });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_id');
+ expect(sqlState.calls.find((c) => /update api_keys/i.test(c.query))).toBeUndefined();
+ },
+ );
+
+ it('returns 400 when the id segment is missing entirely', async () => {
+ authState.session = { id: 'user-1' };
+ const req = makeReq({ method: 'DELETE', url: '/api/api-keys/' });
+ req.query = {};
+ const res = makeRes();
+ await revokeHandler(req, res);
+
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('invalid_id');
+ });
+});
+
describe('DELETE /api/api-keys/:id — 404 unknown id', () => {
it('returns 404 for a well-formed but non-existent id', async () => {
authState.session = { id: 'user-1' };
// UPDATE matches no row → empty result.
sqlState.queue.push([]);
- const { status, body } = await invokeRevoke({ id: 'does-not-exist' });
+ const { status, body } = await invokeRevoke({ id: '00000000-0000-4000-8000-000000000000' });
expect(status).toBe(404);
expect(body.error).toBe('not_found');
});
@@ -299,7 +331,7 @@ describe('DELETE /api/api-keys/:id — 404 unknown id', () => {
authState.session = { id: 'user-2' };
sqlState.queue.push([]);
- const { status, body } = await invokeRevoke({ id: 'k1' });
+ const { status, body } = await invokeRevoke({ id: KEY_ID });
expect(status).toBe(404);
expect(body.error).toBe('not_found');
diff --git a/tests/api/assets.test.js b/tests/api/assets.test.js
index a957e1a84..a59117631 100644
--- a/tests/api/assets.test.js
+++ b/tests/api/assets.test.js
@@ -1,4 +1,4 @@
-// Tests for /api/assets — public asset library REST API. Reads on-disk
+// Tests for /api/assets: public asset library REST API. Reads on-disk
// manifests from /public/* via fs; no mocking needed for those (the real
// committed files are stable for the test).
@@ -8,6 +8,7 @@ import { Readable } from 'node:stream';
process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
const { default: handler } = await import('../../api/assets/index.js');
+const { environments } = await import('../../src/environments.js');
function makeReq(qs = '') {
const req = Readable.from([]);
@@ -74,6 +75,25 @@ describe('GET /api/assets', () => {
const res = makeRes();
await handler(req, res);
expect(res.statusCode).toBe(405);
+ expect(res.headers.allow).toContain('GET');
+ });
+
+ it('answers HEAD like GET (CDNs and uptime probes send it)', async () => {
+ const req = makeReq();
+ req.method = 'HEAD';
+ const res = makeRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('answers the CORS preflight with an allow-origin header', async () => {
+ const req = makeReq();
+ req.method = 'OPTIONS';
+ req.headers.origin = 'https://example.com';
+ const res = makeRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(204);
+ expect(res.headers['access-control-allow-origin']).toBe('*');
});
it('filters by type=accessory', async () => {
@@ -120,6 +140,37 @@ describe('GET /api/assets', () => {
expect(body.items.length).toBeLessThanOrEqual(500);
});
+ it('rejects an unknown type instead of serving an empty catalog', async () => {
+ const { status, body, res } = await invoke('type=bogus');
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_type');
+ // A 400 must never be cached: the next caller may send a valid filter.
+ expect(res.headers['cache-control']).toBe('no-store');
+ // …and must still be readable cross-origin, like the success path.
+ expect(res.headers['access-control-allow-origin']).toBe('*');
+ });
+
+ it('rejects an unknown accessory kind', async () => {
+ const { status, body } = await invoke('kind=fedora');
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_kind');
+ expect(body.error_description).toContain('hat');
+ });
+
+ it('rejects a non-boolean loop value', async () => {
+ const { status, body } = await invoke('loop=yes');
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_loop');
+ });
+
+ it('rejects a non-integer or non-positive limit rather than silently defaulting', async () => {
+ for (const qs of ['limit=abc', 'limit=0', 'limit=-5', 'limit=2.5']) {
+ const { status, body } = await invoke(qs);
+ expect(status, qs).toBe(400);
+ expect(body.error, qs).toBe('invalid_limit');
+ }
+ });
+
it('sets a long-lived cache-control header', async () => {
const { res } = await invoke();
const cc = res.headers['cache-control'];
@@ -132,11 +183,17 @@ describe('GET /api/assets', () => {
expect(res.headers['access-control-allow-origin']).toBe('*');
});
- it('environments include the named "Venice Sunset" and "Footprint Court"', () => {
+ it('publishes exactly the viewer environments from src/environments.js', () => {
const envs = all.items.filter((i) => i.type === 'environment');
- const names = envs.map((e) => e.name);
- expect(names).toContain('Venice Sunset');
- expect(names).toContain('Footprint Court');
+ expect(envs.length).toBe(environments.length);
+ for (const source of environments) {
+ // The viewer's "no environment" entry has an empty id; the catalog
+ // publishes it as `none` so every item carries a usable id.
+ const published = envs.find((e) => e.id === (source.id || 'none'));
+ expect(published, `no catalog entry for environment "${source.name}"`).toBeTruthy();
+ expect(published.name).toBe(source.name);
+ expect(published.path).toBe(source.path ?? null);
+ }
});
it('accessories include the seven committed accessory ids', () => {
diff --git a/tests/api/brain-provider-alias.test.js b/tests/api/brain-provider-alias.test.js
new file mode 100644
index 000000000..f7af46f9f
--- /dev/null
+++ b/tests/api/brain-provider-alias.test.js
@@ -0,0 +1,126 @@
+// A retired provider key must resolve to its successor model, not 400.
+//
+// api/brain/chat.js carries a PROVIDER_ALIASES table for exactly that ("gpt-4o"
+// and friends were deprecated upstream and still sit in saved client prefs), but
+// POST /api/brain/chat looked the raw key up in PROVIDERS *before* resolveBrain()
+// ran, so every aliased key died with `unknown_provider` and the table was dead
+// code on the only surface that mattered. packages/brain-mcp advertises "gpt-4o"
+// as a valid provider in its chat tool schema, so an MCP client following the
+// documented schema got a 400.
+//
+// These tests pin both halves: the alias resolves, and an actually-unknown key
+// still fails at the boundary with a 400.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { invoke } from '../_helpers/monetization.js';
+
+let sessionUser = null;
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => sessionUser),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+// The limiter talks to Redis/Postgres in production; here every bucket passes so
+// the tests exercise routing, not throttling.
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ brainChatUser: vi.fn(async () => ({ success: true })),
+ brainChatIp: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const ENV_KEYS = ['OPENAI_API_KEY', 'OPENROUTER_API_KEY', 'OPENROUTER_FALLBACK_KEYS'];
+const saved = {};
+
+beforeEach(() => {
+ sessionUser = null;
+ for (const k of ENV_KEYS) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env.OPENAI_API_KEY = 'sk-test';
+});
+
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+});
+
+const ask = (provider) => ({
+ method: 'POST',
+ url: '/api/brain/chat',
+ body: { provider, messages: [{ role: 'user', content: 'hi' }] },
+});
+
+describe('canonicalProviderKey', () => {
+ it('maps every retired key onto a live one in the provider menu', async () => {
+ const { canonicalProviderKey, getAvailableProviders } = await import('../../api/brain/chat.js');
+ const menu = new Set(getAvailableProviders().map((p) => p.key));
+ for (const retired of ['gpt-4o', 'gpt-4o-mini', 'o3-mini']) {
+ const live = canonicalProviderKey(retired);
+ expect(live).not.toBe(retired);
+ expect(menu.has(live)).toBe(true);
+ }
+ });
+
+ it('passes a live key through untouched', async () => {
+ const { canonicalProviderKey } = await import('../../api/brain/chat.js');
+ expect(canonicalProviderKey('gpt-oss-120b')).toBe('gpt-oss-120b');
+ expect(canonicalProviderKey('claude-sonnet-5')).toBe('claude-sonnet-5');
+ });
+});
+
+describe('resolveBrain on a retired key', () => {
+ it('plans the successor model instead of reporting unknown_provider', async () => {
+ const { resolveBrain } = await import('../../api/brain/chat.js');
+ const plan = resolveBrain('gpt-4o');
+ expect(plan.ok).toBe(true);
+ expect(plan.spec.label).toBe('GPT-5.6 Sol');
+ });
+
+ it('still rejects a key that is not a provider and not an alias', async () => {
+ const { resolveBrain } = await import('../../api/brain/chat.js');
+ const plan = resolveBrain('totally-not-a-model');
+ expect(plan.ok).toBe(false);
+ expect(plan.status).toBe(400);
+ expect(plan.code).toBe('unknown_provider');
+ });
+});
+
+describe('POST /api/brain/chat provider gate', () => {
+ it('does not 400 a retired key: it is judged as the successor model', async () => {
+ const handler = (await import('../../api/brain/chat.js')).default;
+ const { status, body } = await invoke(handler, ask('gpt-4o'));
+ // gpt-5.6-sol is a paid first-party lane, so an anonymous caller is turned
+ // away by the sign-in gate. The point is the error: `unauthorized`, meaning
+ // the alias resolved, not `unknown_provider`, meaning it never did.
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('still 400s an unknown provider key', async () => {
+ const handler = (await import('../../api/brain/chat.js')).default;
+ const { status, body } = await invoke(handler, ask('totally-not-a-model'));
+ expect(status).toBe(400);
+ expect(body.error).toBe('unknown_provider');
+ expect(Array.isArray(body.available)).toBe(true);
+ });
+
+ // A malformed message list is the caller's error to fix. When the requested
+ // provider ALSO has no configured route, the caller must still be told about
+ // their own bad input rather than being sent after a missing API key.
+ it('validates the message list before reporting an unconfigured provider', async () => {
+ const handler = (await import('../../api/brain/chat.js')).default;
+ const { status, body } = await invoke(handler, {
+ method: 'POST',
+ url: '/api/brain/chat',
+ body: { provider: 'gpt-oss-120b', messages: [{ role: 'system', content: 'hi' }] },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('bad_request');
+ });
+});
diff --git a/tests/api/ca2x402-resolve.test.js b/tests/api/ca2x402-resolve.test.js
new file mode 100644
index 000000000..4c921d2a0
--- /dev/null
+++ b/tests/api/ca2x402-resolve.test.js
@@ -0,0 +1,177 @@
+// GET /api/ca2x402/resolve: the free resolver behind the CA to x402 tool.
+//
+// The load-bearing property here is that `service.endpoint` (and therefore every
+// copy-paste snippet a visitor is invited to run and PAY for) is anchored on
+// env.APP_ORIGIN, never on the caller-controlled `host` / `x-forwarded-host`
+// headers. Before this was pinned, `curl -H 'x-forwarded-host: evil.example.com'`
+// came back advertising an attacker-owned 402 challenge, and because the 200 is
+// CDN-cacheable that poisoned copy could be served on to other visitors.
+//
+// DexScreener is the only upstream, stubbed here so the suite stays offline and
+// deterministic. The validation paths below never reach it at all.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+// One deepest-liquidity Solana pair, shaped exactly like a DexScreener
+// /latest/dex/tokens/<addr> response.
+const DEX_PAIR = {
+ chainId: 'solana',
+ dexId: 'pumpswap',
+ url: 'https://dexscreener.com/solana/5byl7mzolabynwmpzkpkjf4mgkz7febzranos19pre2z',
+ pairAddress: '5byl7mzolabynwmpzkpkjf4mgkz7febzranos19pre2z',
+ baseToken: { address: MINT, symbol: 'three', name: 'three.ws' },
+ quoteToken: { address: 'So11111111111111111111111111111111111111112', symbol: 'SOL', name: 'Wrapped SOL' },
+ info: { imageUrl: 'https://cdn.dexscreener.com/cms/images/j22gRd6Z2GowwOvM' },
+ priceUsd: '0.001517',
+ priceChange: { m5: 0.09, h1: 1.31, h6: -5.68, h24: -13.61 },
+ marketCap: 1516533,
+ fdv: 1516533,
+ liquidity: { usd: 213949.3 },
+ volume: { h24: 113187.16 },
+ pairCreatedAt: 1_760_000_000_000,
+ txns: { h24: { buys: 720, sells: 280 } },
+};
+
+let dexBody = { pairs: [DEX_PAIR] };
+let dexOk = true;
+
+vi.stubGlobal('fetch', (url) => {
+ const u = String(url);
+ if (u.startsWith('https://api.dexscreener.com/')) {
+ return Promise.resolve({ ok: dexOk, status: dexOk ? 200 : 502, json: async () => dexBody });
+ }
+ throw new Error(`Unexpected upstream fetch: ${u}`);
+});
+
+const { default: handler } = await import('../../api/ca2x402/resolve.js');
+const { env } = await import('../../api/_lib/env.js');
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ writableEnded: false,
+ headersSent: false,
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(b) {
+ this.body = b;
+ this.writableEnded = true;
+ },
+ };
+}
+
+let ip = 0;
+
+async function call({ method = 'GET', query = '', headers = {} } = {}) {
+ const res = mkRes();
+ // A fresh client IP per call so the public rate limiter never colours a case.
+ ip += 1;
+ await handler(
+ {
+ method,
+ url: `/api/ca2x402/resolve${query}`,
+ headers: { 'x-forwarded-for': `203.0.113.${ip % 254}`, ...headers },
+ socket: { remoteAddress: `203.0.113.${ip % 254}` },
+ },
+ res,
+ );
+ return res;
+}
+
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+beforeEach(() => {
+ dexBody = { pairs: [DEX_PAIR] };
+ dexOk = true;
+});
+
+describe('GET /api/ca2x402/resolve', () => {
+ it('resolves a live token into its identity plus the generated x402 service', async () => {
+ const res = await call({ query: `?mint=${MINT}` });
+ expect(res.statusCode).toBe(200);
+
+ const body = parse(res);
+ expect(body.ok).toBe(true);
+ expect(body.token.mint).toBe(MINT);
+ expect(body.token.symbol).toBe('three');
+ expect(body.token.chain).toBe('solana');
+ expect(body.token.price_usd).toBe(0.001517);
+ expect(body.token.signal).toBeTruthy();
+ expect(body.token.risk.level).toBeTruthy();
+
+ expect(body.service.method).toBe('GET');
+ expect(body.service.asset).toBe('USDC');
+ expect(body.service.networks).toEqual(['solana', 'base']);
+ expect(body.service.price_usd).toBeGreaterThan(0);
+ expect(body.service.output_schema).toBeTruthy();
+ expect(res.headers['cache-control']).toContain('max-age=20');
+ });
+
+ it('anchors the advertised endpoint and every paid snippet on APP_ORIGIN, not on the request host', async () => {
+ const res = await call({
+ query: `?mint=${MINT}`,
+ headers: { host: 'evil.example.com', 'x-forwarded-host': 'evil.example.com', 'x-forwarded-proto': 'http' },
+ });
+ expect(res.statusCode).toBe(200);
+
+ const { service } = parse(res);
+ const expected = `${env.APP_ORIGIN}/api/x402/token-intel?mint=${MINT}`;
+ expect(service.endpoint).toBe(expected);
+
+ for (const snippet of Object.values(service.snippets)) {
+ expect(snippet).toContain(expected);
+ expect(snippet).not.toContain('evil.example.com');
+ }
+ });
+
+ it('answers a well-formed address with no market with a designed, uncacheable 404', async () => {
+ dexBody = { pairs: [] };
+ const res = await call({ query: '?mint=THREEsynthetic1111111111111111111111111111' });
+ expect(res.statusCode).toBe(404);
+
+ const body = parse(res);
+ expect(body.ok).toBe(false);
+ expect(body.error).toBe('token_not_found');
+ expect(body.chain).toBe('solana');
+ expect(res.headers['cache-control']).toBe('no-store');
+ });
+
+ it('reports the same designed 404 when DexScreener itself is failing', async () => {
+ dexOk = false;
+ const res = await call({ query: `?mint=${MINT}` });
+ expect(res.statusCode).toBe(404);
+ expect(parse(res).error).toBe('token_not_found');
+ });
+
+ it('rejects a missing mint with 400 and a malformed one with 422', async () => {
+ const missing = await call();
+ expect(missing.statusCode).toBe(400);
+ expect(parse(missing).error).toBe('missing_mint');
+
+ const blank = await call({ query: '?mint=' });
+ expect(blank.statusCode).toBe(400);
+
+ const bad = await call({ query: '?mint=notanaddress' });
+ expect(bad.statusCode).toBe(422);
+ expect(parse(bad).error).toBe('invalid_mint');
+ });
+
+ it('rejects writes with 405 and short-circuits a CORS preflight', async () => {
+ const post = await call({ method: 'POST' });
+ expect(post.statusCode).toBe(405);
+ expect(parse(post).error).toBe('method_not_allowed');
+
+ const preflight = await call({ method: 'OPTIONS', headers: { origin: 'https://example.com' } });
+ expect(preflight.statusCode).toBe(204);
+ expect(preflight.headers['access-control-allow-origin']).toBe('*');
+ expect(preflight.headers['access-control-allow-methods']).toBe('GET,OPTIONS');
+ });
+});
diff --git a/tests/api/chat-plugin-tool.test.js b/tests/api/chat-plugin-tool.test.js
index c02d16c1c..b9c1859dc 100644
--- a/tests/api/chat-plugin-tool.test.js
+++ b/tests/api/chat-plugin-tool.test.js
@@ -3,7 +3,7 @@
// agent id from the Sperax-Plugin-Settings header, and returns the concise tool
// result the model reads back. Rate-limit is mocked so the test stays offline.
-import { describe, it, expect, vi } from 'vitest';
+import { describe, it, expect, vi, beforeEach } from 'vitest';
import { Readable } from 'node:stream';
vi.mock('../../api/_lib/rate-limit.js', () => ({
@@ -11,6 +11,13 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
clientIp: () => '127.0.0.1',
}));
+// render-agent confirms a UUID agentId against agent_identities before it tells
+// the model the panel is bound. Default: the agent exists.
+const sqlMock = vi.fn(async () => [{ name: 'Nova' }]);
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+const REAL_UUID = '3f1c0b6a-7d21-4c8e-9a55-0b2e1d4f7a90';
+
const { default: handler } = await import('../../api/chat-plugin/[tool].js');
function makeReq({ method = 'POST', tool, body, headers = {} } = {}) {
@@ -54,6 +61,11 @@ async function call(opts) {
}
describe('/api/chat-plugin/[tool]', () => {
+ beforeEach(() => {
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([{ name: 'Nova' }]);
+ });
+
it('speak returns ok and clamps sentiment to [-1,1]', async () => {
const { res, body } = await call({ tool: 'speak', body: { text: 'gm', sentiment: 5 } });
expect(res.statusCode).toBe(200);
@@ -106,6 +118,51 @@ describe('/api/chat-plugin/[tool]', () => {
expect((await call({ tool: 'render-agent', body: {} })).res.statusCode).toBe(400);
});
+ it('render-agent 400s on a whitespace-only agentId', async () => {
+ expect((await call({ tool: 'render-agent', body: { agentId: ' ' } })).res.statusCode).toBe(
+ 400,
+ );
+ });
+
+ it('render-agent resolves a UUID agentId and names the agent', async () => {
+ const { res, body } = await call({ tool: 'render-agent', body: { agentId: REAL_UUID } });
+ expect(res.statusCode).toBe(200);
+ expect(sqlMock).toHaveBeenCalledTimes(1);
+ expect(body).toMatchObject({ ok: true, agentId: REAL_UUID, agentName: 'Nova' });
+ expect(body.message).toContain('Nova');
+ });
+
+ it('render-agent trims a padded agentId from the settings header', async () => {
+ const { body } = await call({
+ tool: 'render-agent',
+ body: {},
+ headers: { 'sperax-plugin-settings': JSON.stringify({ agentId: ` ${REAL_UUID} ` }) },
+ });
+ expect(body).toMatchObject({ ok: true, agentId: REAL_UUID });
+ });
+
+ it('render-agent 404s when the UUID names no agent', async () => {
+ sqlMock.mockResolvedValue([]);
+ const { res, body } = await call({ tool: 'render-agent', body: { agentId: REAL_UUID } });
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ expect(body.error_description).toContain('three.ws/dashboard');
+ });
+
+ it('render-agent binds unverified when the agent lookup fails', async () => {
+ sqlMock.mockRejectedValue(new Error('connection terminated'));
+ const { res, body } = await call({ tool: 'render-agent', body: { agentId: REAL_UUID } });
+ expect(res.statusCode).toBe(200);
+ expect(body).toMatchObject({ ok: true, agentId: REAL_UUID, agentName: null });
+ });
+
+ it('render-agent passes a non-UUID handle through without a DB read', async () => {
+ const { res, body } = await call({ tool: 'render-agent', body: { agentId: '@nova' } });
+ expect(res.statusCode).toBe(200);
+ expect(sqlMock).not.toHaveBeenCalled();
+ expect(body).toMatchObject({ ok: true, agentId: '@nova', agentName: null });
+ });
+
it('unknown tool returns 404', async () => {
expect((await call({ tool: 'frobnicate', body: {} })).res.statusCode).toBe(404);
});
diff --git a/tests/api/coin-news-gate.test.js b/tests/api/coin-news-gate.test.js
index d1553b414..9d5b1652f 100644
--- a/tests/api/coin-news-gate.test.js
+++ b/tests/api/coin-news-gate.test.js
@@ -72,6 +72,17 @@ describe('/api/coin/news outage gate', () => {
expect(body.error).toBe('upstream_error');
});
+ it('maps a hard aggregator reject to the same 502, not a generic 500', async () => {
+ // Before this was caught here it bubbled to wrap(), which answers a generic
+ // `internal_error` AND pages ops with an "unhandled 5xx" alert for what is
+ // an ordinary publisher-feed outage.
+ searchNews.mockRejectedValue(new Error('fan-out failed: getaddrinfo ENOTFOUND'));
+ const { res, body } = await call('q=Solana&limit=8');
+ expect(res.statusCode).toBe(502);
+ expect(body.error).toBe('upstream_error');
+ expect(body.ref).toBeUndefined();
+ });
+
it('still rejects a missing query', async () => {
const { res, body } = await call('limit=8');
expect(res.statusCode).toBe(400);
diff --git a/tests/api/coin-tickers-page.test.js b/tests/api/coin-tickers-page.test.js
new file mode 100644
index 000000000..1623ff242
--- /dev/null
+++ b/tests/api/coin-tickers-page.test.js
@@ -0,0 +1,162 @@
+// /api/coin/tickers: the `page` contract must be one rule, not two.
+//
+// The handler advertises "page must be an integer between 1 and 10" and returns
+// 400 bad_page for anything outside it. But it derived the value with
+// `parseInt(v, 10) || 1`, which rewrites every falsy parse to 1 BEFORE the range
+// check runs. So `page=11` was rejected while `page=0`, `page=abc`, and
+// `page=2.9` quietly answered 200 with a page the caller never asked for, and
+// the `page < 1` half of the guard was unreachable for 0. These tests pin the
+// single rule: absent means page 1, anything else is an integer in 1..10 or a
+// 400. The upstream-failover contract is pinned alongside it so tightening the
+// parse can't silently cost the CoinPaprika fallback.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { marketDataIp: async () => ({ success: true }) },
+ clientIp: () => '203.0.113.1',
+}));
+
+const geckoFetch = vi.fn();
+vi.mock('../../api/_lib/coingecko.js', () => ({
+ geckoFetch: (...a) => geckoFetch(...a),
+ isPlausibleCoinId: (id) => /^[a-z0-9][a-z0-9-]*$/.test(id),
+}));
+
+const fetchFallbackTickers = vi.fn();
+vi.mock('../../api/_lib/coin-fallbacks.js', () => ({
+ fetchFallbackTickers: (...a) => fetchFallbackTickers(...a),
+}));
+
+const tickers = (await import('../../api/coin/tickers.js')).default;
+
+const upstreamTicker = {
+ base: 'BTC',
+ target: 'USDT',
+ market: { identifier: 'binance', name: 'Binance', logo: 'https://example.com/l.png' },
+ converted_last: { usd: 64000 },
+ converted_volume: { usd: 1_000_000 },
+ trust_score: 'green',
+ trade_url: 'https://example.com/trade',
+};
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; },
+ };
+}
+async function call(query) {
+ const res = makeRes();
+ await tickers({ url: `/api/coin/tickers?${query}`, method: 'GET', headers: {} }, res);
+ return { res, body: JSON.parse(res._body) };
+}
+
+describe('/api/coin/tickers page contract', () => {
+ beforeEach(() => {
+ geckoFetch.mockReset();
+ fetchFallbackTickers.mockReset();
+ geckoFetch.mockResolvedValue({ tickers: [upstreamTicker] });
+ });
+
+ it('defaults an absent page to 1 and asks upstream for it', async () => {
+ const { res, body } = await call('id=bitcoin');
+ expect(res.statusCode).toBe(200);
+ expect(body.page).toBe(1);
+ expect(body.source).toBe('coingecko');
+ expect(geckoFetch.mock.calls[0][0]).toContain('page=1');
+ });
+
+ it('passes a valid in-range page straight through', async () => {
+ const { res, body } = await call('id=bitcoin&page=7');
+ expect(res.statusCode).toBe(200);
+ expect(body.page).toBe(7);
+ expect(geckoFetch.mock.calls[0][0]).toContain('page=7');
+ });
+
+ for (const [label, query] of [
+ ['zero', 'id=bitcoin&page=0'],
+ ['negative zero', 'id=bitcoin&page=-0'],
+ ['negative', 'id=bitcoin&page=-3'],
+ ['above the ceiling', 'id=bitcoin&page=11'],
+ ['non-numeric', 'id=bitcoin&page=abc'],
+ ['fractional', 'id=bitcoin&page=2.9'],
+ ]) {
+ it(`rejects a ${label} page with 400 bad_page and never calls upstream`, async () => {
+ const { res, body } = await call(query);
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('bad_page');
+ expect(geckoFetch).not.toHaveBeenCalled();
+ });
+ }
+
+ it('shapes the row the Markets table renders', async () => {
+ const { body } = await call('id=bitcoin&page=1');
+ expect(body.tickers[0]).toMatchObject({
+ exchange: { id: 'binance', name: 'Binance' },
+ pair: 'BTC/USDT',
+ price_usd: 64000,
+ trust: 'green',
+ trade_url: 'https://example.com/trade',
+ });
+ expect(body.count).toBe(1);
+ });
+
+ it('truncates a contract-address pair symbol so the table stays legible', async () => {
+ geckoFetch.mockResolvedValue({
+ tickers: [{ ...upstreamTicker, base: '0xdeadbeefcafebabe1234', target: 'SOL' }],
+ });
+ const { body } = await call('id=bitcoin&page=1');
+ expect(body.tickers[0].base).toBe('0xdead…');
+ });
+
+ it('drops a non-http trade_url rather than handing it to the client', async () => {
+ geckoFetch.mockResolvedValue({
+ tickers: [{ ...upstreamTicker, trade_url: 'javascript:alert(1)' }],
+ });
+ const { body } = await call('id=bitcoin&page=1');
+ expect(body.tickers[0].trade_url).toBeNull();
+ });
+
+ it('rejects an implausible coin id before any upstream call', async () => {
+ const { res, body } = await call('id=NOT%20AN%20ID&page=1');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('bad_id');
+ expect(geckoFetch).not.toHaveBeenCalled();
+ });
+
+ it('404s an unknown coin without reaching for the fallback', async () => {
+ const err = new Error('not found');
+ err.status = 404;
+ geckoFetch.mockRejectedValue(err);
+ const { res, body } = await call('id=no-such-coin-anywhere&page=1');
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ expect(fetchFallbackTickers).not.toHaveBeenCalled();
+ });
+
+ it('serves CoinPaprika for the validated page when CoinGecko is throttled', async () => {
+ const err = new Error('CoinGecko 429');
+ err.status = 429;
+ geckoFetch.mockRejectedValue(err);
+ fetchFallbackTickers.mockResolvedValue([{ pair: 'BTC/USD', price_usd: 64000 }]);
+ const { res, body } = await call('id=bitcoin&page=3');
+ expect(res.statusCode).toBe(200);
+ expect(body.source).toBe('coinpaprika');
+ expect(body.page).toBe(3);
+ expect(fetchFallbackTickers).toHaveBeenCalledWith('bitcoin', { page: 3 });
+ });
+
+ it('502s when both sources are down', async () => {
+ geckoFetch.mockRejectedValue(new Error('gateway timeout'));
+ fetchFallbackTickers.mockResolvedValue(null);
+ const { res, body } = await call('id=bitcoin&page=1');
+ expect(res.statusCode).toBe(502);
+ expect(body.error).toBe('upstream_error');
+ });
+});
diff --git a/tests/bnb-block-time-endpoint.test.js b/tests/bnb-block-time-endpoint.test.js
new file mode 100644
index 000000000..5277a3b92
--- /dev/null
+++ b/tests/bnb-block-time-endpoint.test.js
@@ -0,0 +1,142 @@
+/**
+ * GET /api/bnb/block-time integration tests.
+ *
+ * `probeBlockTime` (api/_lib/bnb/chains.js) and `api/_lib/rate-limit.js` are
+ * mocked so the suite runs deterministically without a live BSC RPC. The
+ * probe's own sampling math is covered in tests/bnb-chains.test.js; this file
+ * exercises the HTTP boundary only: network validation, the per-network TTL
+ * cache, RPC-failure mapping, rate limiting, and method/CORS handling.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const rl = { ok: true };
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000, reason: rl.ok ? undefined : 'quota' })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const probeState = { calls: 0, fail: false };
+vi.mock('../api/_lib/bnb/chains.js', async () => {
+ const actual = await vi.importActual('../api/_lib/bnb/chains.js');
+ return {
+ ...actual,
+ probeBlockTime: vi.fn(async (network, sampleBlocks) => {
+ probeState.calls += 1;
+ if (probeState.fail) {
+ throw new actual.BnbRpcError('every RPC refused', { tried: ['https://bsc-dataseed.bnbchain.org'] });
+ }
+ return {
+ network,
+ avgBlockTimeMs: network === 'bscMainnet' ? 450 : 1500,
+ latestBlock: 115_000_000,
+ sampleBlocks,
+ target: network === 'bscMainnet' ? 450 : null,
+ measuredAt: new Date().toISOString(),
+ };
+ }),
+ };
+});
+
+const { default: handler } = await import('../api/bnb/block-time.js');
+
+function makeRes() {
+ const r = { statusCode: 200, _h: {}, _b: null };
+ r.setHeader = (k, v) => { r._h[k] = v; };
+ r.getHeader = (k) => r._h[k];
+ r.end = (b) => { r._b = b; };
+ Object.defineProperty(r, '_s', { get() { return this.statusCode; } });
+ Object.defineProperty(r, 'json', { value: () => JSON.parse(r._b) });
+ return r;
+}
+async function call(qs = '', { method = 'GET' } = {}) {
+ const req = {
+ method,
+ url: `/api/bnb/block-time${qs}`,
+ headers: { origin: 'https://three.ws', host: 'three.ws' },
+ socket: { remoteAddress: '127.0.0.1' },
+ };
+ const res = makeRes();
+ await handler(req, res);
+ return res;
+}
+
+beforeEach(() => {
+ rl.ok = true;
+ probeState.calls = 0;
+ probeState.fail = false;
+});
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('GET /api/bnb/block-time measured response', () => {
+ it('200 with a measured mainnet interval and its published target', async () => {
+ const r = await call('?network=mainnet');
+ expect(r._s).toBe(200);
+ const body = r.json();
+ expect(body.network).toBe('bscMainnet');
+ expect(body.avgBlockTimeMs).toBe(450);
+ expect(body.target).toBe(450);
+ expect(body.latestBlock).toBeGreaterThan(0);
+ expect(typeof body.measuredAt).toBe('string');
+ });
+
+ it('probes the testnet lane on request, where no published target exists', async () => {
+ const r = await call('?network=testnet');
+ expect(r._s).toBe(200);
+ expect(r.json().network).toBe('bscTestnet');
+ expect(r.json().target).toBe(null);
+ });
+
+ it('accepts the chain-id and bscMainnet spellings the /bnb page sends', async () => {
+ expect((await call('?network=bscMainnet')).json().network).toBe('bscMainnet');
+ expect((await call('?network=97')).json().network).toBe('bscTestnet');
+ });
+
+ it('400 on an unknown network instead of silently answering about mainnet', async () => {
+ const r = await call('?network=polygon');
+ expect(r._s).toBe(400);
+ expect(r.json().error).toBe('bad_request');
+ expect(probeState.calls).toBe(0);
+ });
+
+ it('caches per network, so a second call inside the TTL does not re-probe', async () => {
+ await call('?network=mainnet');
+ const before = probeState.calls;
+ await call('?network=mainnet');
+ expect(probeState.calls).toBe(before);
+ await call('?network=testnet');
+ expect(probeState.calls).toBe(before + 1);
+ });
+});
+
+describe('GET /api/bnb/block-time failure paths', () => {
+ it('502 with the tried endpoints when every RPC is unreachable', async () => {
+ probeState.fail = true;
+ const r = await call('?network=mainnet');
+ expect(r._s).toBe(502);
+ const body = r.json();
+ expect(body.error).toBe('upstream_error');
+ expect(body.tried).toEqual(['https://bsc-dataseed.bnbchain.org']);
+ });
+
+ it('429 carries retry-after so the polling /bnb page can back off', async () => {
+ rl.ok = false;
+ const r = await call('?network=mainnet');
+ expect(r._s).toBe(429);
+ expect(r.json().error).toBe('rate_limited');
+ expect(Number(r.getHeader('retry-after'))).toBeGreaterThan(0);
+ });
+
+ it('405 on a non-GET method', async () => {
+ const r = await call('', { method: 'POST' });
+ expect(r._s).toBe(405);
+ });
+
+ it('204 on the CORS preflight', async () => {
+ const r = await call('', { method: 'OPTIONS' });
+ expect(r._s).toBe(204);
+ expect(r.getHeader('access-control-allow-methods')).toContain('GET');
+ });
+});
diff --git a/tests/creator-pricing-rules-isolation.test.js b/tests/creator-pricing-rules-isolation.test.js
index eaccd69c8..d9df954df 100644
--- a/tests/creator-pricing-rules-isolation.test.js
+++ b/tests/creator-pricing-rules-isolation.test.js
@@ -88,6 +88,33 @@ describe('pricing-rules owner isolation', () => {
expect(sqlState.calls.some((c) => /INSERT INTO skill_pricing_rules/i.test(c.query))).toBe(true);
});
+ it('rejects an unauthenticated list with 401', async () => {
+ authState.session = null;
+ const { status, body } = await invoke(pricingRulesHandler, {
+ method: 'GET',
+ url: `/api/agents/${AGENT_ID}/pricing-rules`,
+ query: { id: AGENT_ID },
+ });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ // A rule set names scheduled and deactivated prices — never read it for an
+ // anonymous caller.
+ expect(sqlState.calls.some((c) => /FROM skill_pricing_rules/i.test(c.query))).toBe(false);
+ });
+
+ it('returns 403 when a non-owner tries to list rules', async () => {
+ authState.session = { id: 'attacker-user' };
+ sqlState.queue = [[]]; // ownership lookup → empty
+ const { status, body } = await invoke(pricingRulesHandler, {
+ method: 'GET',
+ url: `/api/agents/${AGENT_ID}/pricing-rules`,
+ query: { id: AGENT_ID },
+ });
+ expect(status).toBe(403);
+ expect(body.error).toBe('forbidden');
+ expect(sqlState.calls.some((c) => /FROM skill_pricing_rules/i.test(c.query))).toBe(false);
+ });
+
it('returns 403 when a non-owner tries to delete a rule', async () => {
authState.session = { id: 'attacker-user' };
sqlState.queue = [[]]; // ownership lookup → empty
@@ -102,3 +129,57 @@ describe('pricing-rules owner isolation', () => {
expect(sqlState.calls.some((c) => /UPDATE skill_pricing_rules/i.test(c.query))).toBe(false);
});
});
+
+// A PATCH body distinguishes three intents per timestamp: omit the key (keep the
+// current value), send a timestamp (set it), send null (clear it). COALESCE alone
+// collapses the last two, so the clear used to return 200 and change nothing.
+describe('pricing-rules PATCH timestamp clearing', () => {
+ const RULE_ID = '00000000-0000-4000-8000-0000000000bb';
+
+ async function patch(body) {
+ authState.session = { id: 'owner-user' };
+ sqlState.queue = [
+ [{ id: AGENT_ID }], // ownership lookup
+ [{ id: RULE_ID }], // existing-rule lookup
+ [], // UPDATE
+ ];
+ const result = await invoke(pricingRulesHandler, {
+ method: 'PATCH',
+ url: `/api/agents/${AGENT_ID}/pricing-rules/${RULE_ID}`,
+ query: { id: AGENT_ID, rule_id: RULE_ID },
+ body,
+ });
+ const update = sqlState.calls.find((c) => /UPDATE skill_pricing_rules/i.test(c.query));
+ return { ...result, update };
+ }
+
+ it('clears start_at when the caller sends an explicit null', async () => {
+ const { status, update } = await patch({ start_at: null });
+ expect(status).toBe(200);
+ // [threshold, price_amount, clearStart, start_at, clearEnd, end_at, …]
+ expect(update.values[2]).toBe(true);
+ expect(update.values[4]).toBe(false);
+ });
+
+ it('clears end_at when the caller sends an explicit null', async () => {
+ const { status, update } = await patch({ end_at: null });
+ expect(status).toBe(200);
+ expect(update.values[2]).toBe(false);
+ expect(update.values[4]).toBe(true);
+ });
+
+ it('keeps both timestamps when neither key is sent', async () => {
+ const { status, update } = await patch({ price_amount: 650 });
+ expect(status).toBe(200);
+ expect(update.values[1]).toBe(650);
+ expect(update.values[2]).toBe(false);
+ expect(update.values[4]).toBe(false);
+ });
+
+ it('sets start_at when the caller sends a timestamp', async () => {
+ const { status, update } = await patch({ start_at: '2026-10-01T00:00:00.000Z' });
+ expect(status).toBe(200);
+ expect(update.values[2]).toBe(false);
+ expect(update.values[3]).toBe('2026-10-01T00:00:00.000Z');
+ });
+});
diff --git a/tests/pump-alert-rules-validation.test.js b/tests/pump-alert-rules-validation.test.js
index 1e5c125db..f79124d7d 100644
--- a/tests/pump-alert-rules-validation.test.js
+++ b/tests/pump-alert-rules-validation.test.js
@@ -4,6 +4,7 @@ import {
updateRuleSchema,
validateUpdate,
normalizeForKind,
+ rulesMissingWebhookSecret,
serializeRule,
} from '../api/alerts/_rules.js';
@@ -129,6 +130,41 @@ describe('validateUpdate (merge + re-validate)', () => {
const r = validateUpdate(current, { deliver_in_app: false });
expect(r.ok).toBe(false);
});
+
+ // The update path must report failures exactly the way the create path does
+ // (api/_lib/validate.js `parse()`): "<field>: <message>", joined by "; ".
+ // A bare message here made PATCH and POST disagree on the same rule.
+ it('formats issues with the same field prefix the create path uses', () => {
+ const r = validateUpdate(current, { kind: 'graduation', target_agent: AGENT });
+ expect(r.ok).toBe(false);
+ expect(r.message).toBe('target_agent: set either target_mint or target_agent, not both');
+ });
+
+ it('joins multiple issues into one message', () => {
+ const grad = { ...current, kind: 'graduation', target_mint: null, threshold: null };
+ const r = validateUpdate(grad, { kind: 'price_below' });
+ expect(r.ok).toBe(false);
+ expect(r.message).toBe(
+ 'target_mint: price_below requires a target_mint; threshold: price_below requires a positive threshold',
+ );
+ });
+});
+
+describe('rulesMissingWebhookSecret', () => {
+ const row = (over) => ({ id: 'r', webhook_url: null, webhook_secret: null, ...over });
+
+ it('flags a rule that has a webhook but no signing secret', () => {
+ const rows = [row({ id: 'legacy', webhook_url: 'https://example.com/hook' })];
+ expect(rulesMissingWebhookSecret(rows).map((r) => r.id)).toEqual(['legacy']);
+ });
+
+ it('ignores rules with no webhook and rules already carrying a secret', () => {
+ const rows = [
+ row({ id: 'in-app-only' }),
+ row({ id: 'signed', webhook_url: 'https://example.com/hook', webhook_secret: 'whsec_abc' }),
+ ];
+ expect(rulesMissingWebhookSecret(rows)).toEqual([]);
+ });
});
describe('serializeRule', () => {
diff --git a/tests/vercel-agents-subpath-routes.test.js b/tests/vercel-agents-subpath-routes.test.js
index 3713392fc..555a3fea3 100644
--- a/tests/vercel-agents-subpath-routes.test.js
+++ b/tests/vercel-agents-subpath-routes.test.js
@@ -154,6 +154,69 @@ describe('nested /api/agents handlers are reachable, not shadowed by the [id] ca
);
});
+ // Same outage class one level down: api/agents/solana/[action].js is a
+ // dispatcher keyed on ?action=, so an action is only reachable if some route
+ // names it. Two never did, and both were load-bearing: api/_lib/skill-nft.js
+ // bakes /api/agents/solana/skill-nft-metadata and
+ // /api/agents/solana/skill-collection-metadata into the on-chain URI of every
+ // skill NFT it mints. Those URIs are immutable once minted, and both paths were
+ // swallowed by the [id] catch-all, so every skill license ever sold pointed at
+ // {"error":"not_found"} in every wallet and marketplace that read it.
+ //
+ // Derived from the dispatch table on disk so the next action added is covered
+ // the moment it lands.
+ const actionDispatcher = '/api/agents/solana/[action]';
+ const solanaActions = (() => {
+ const src = readFileSync(new URL('../api/agents/solana/[action].js', import.meta.url), 'utf8');
+ const table = src.slice(src.indexOf('const DISPATCH = {'), src.indexOf('export default'));
+ return [...table.matchAll(/^\t'?([a-z0-9-]+)'?:\s*handle/gm)].map((m) => m[1]);
+ })();
+
+ it('reads the solana action dispatch table', () => {
+ // An empty parse would make the sweep below vacuously pass.
+ expect(solanaActions.length).toBeGreaterThan(10);
+ expect(solanaActions).toContain('skill-nft-metadata');
+ });
+
+ it.each(solanaActions)('solana action %s is reachable', (action) => {
+ const candidates = routes
+ .slice(0, fsPhase)
+ .filter(
+ (r) =>
+ typeof r.src === 'string' &&
+ String(r.dest || '').split('?')[0] === actionDispatcher &&
+ new URLSearchParams(String(r.dest).split('?')[1] || '').get('action') === action,
+ );
+
+ expect(
+ candidates.length,
+ `no route in vercel.json dispatches action=${action}, so it can never run`,
+ ).toBeGreaterThan(0);
+
+ const reachable = candidates.filter((r) => {
+ const dest = resolve(samplePath(r.src));
+ return (
+ dest?.split('?')[0] === actionDispatcher &&
+ new URLSearchParams(dest.split('?')[1] || '').get('action') === action
+ );
+ });
+ expect(
+ reachable.length,
+ `every route for action=${action} is shadowed by a broader route above it (likely ${DISPATCHER}); move it up`,
+ ).toBeGreaterThan(0);
+ });
+
+ it('routes the exact skill-NFT metadata URIs that are minted on-chain', () => {
+ // These two strings are built by api/_lib/skill-nft.js and written into the
+ // asset's immutable `uri` field. They must resolve verbatim, forever.
+ expect(resolve('/api/agents/solana/skill-nft-metadata')).toBe(
+ '/api/agents/solana/[action]?action=skill-nft-metadata',
+ );
+ expect(resolve('/api/agents/solana/skill-collection-metadata')).toBe(
+ '/api/agents/solana/[action]?action=skill-collection-metadata',
+ );
+ });
+
it('keeps the ens route above the catch-all', () => {
const ens = routes.findIndex((r) => r.src === '/api/agents/ens/([^/]+)');
const catchAll = routes.findIndex((r) => r.src === '/api/agents/([^/]+)(?:/.*)?');