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 arena tournament routes, vanity escrow gating, and widgets

nirholas31348e1c5bba
diff --git a/tests/api/widgets.test.js b/tests/api/widgets.test.js
index 0eafd0733..d289ff0a3 100644
--- a/tests/api/widgets.test.js
+++ b/tests/api/widgets.test.js
@@ -108,6 +108,7 @@ const transcriptsHandler = (await import('../../api/widgets/[id]/transcripts.js'
const knowledgeHandler = (await import('../../api/widgets/[id]/knowledge.js')).default;
const { getAvatar } = await import('../../api/_lib/avatars.js');
+const { requireCsrf } = await import('../../api/_lib/csrf.js');
// ── Helpers ──────────────────────────────────────────────────────────────────
@@ -164,9 +165,18 @@ function parseJson(res) {
return res._body ? JSON.parse(res._body) : null;
}
+// `sql` is invoked both as a tagged template (strings array + values) and
+// positionally (text + params). Flatten either form back to the SQL text so a
+// test can assert on the statement a handler actually issued.
+function sqlText(call) {
+ if (!call) return '';
+ return Array.isArray(call[0]) ? call[0].join(' ') : String(call[0]);
+}
+
function resetState() {
sqlQueue.length = 0;
sqlMock.mockClear();
+ requireCsrf.mockClear();
authState.session = null;
authState.bearer = null;
rlState.success = true;
@@ -447,6 +457,56 @@ describe('POST /api/widgets/:id/duplicate', () => {
expect(res.statusCode).toBe(201);
expect(parseJson(res).widget.name).toBe('Original (copy)');
});
+
+ // Regression: the clone INSERT once omitted the `id` column. widgets.id is
+ // `text not null` with no database default, so every real Duplicate click
+ // died on a not-null violation and returned a bare 500 while the mocked
+ // test above still passed. Assert on the statement, not just the canned row.
+ it('supplies a generated wdgt_ id to the clone INSERT', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([
+ {
+ id: 'wdgt_src',
+ type: 'turntable',
+ name: 'Original',
+ config: { a: 1 },
+ avatar_id: null,
+ is_public: true,
+ },
+ ]);
+ sqlQueue.push([{ id: 'wdgt_copy', user_id: 'user-1', type: 'turntable', name: 'Original (copy)' }]);
+
+ const req = mockReq({ method: 'POST', url: '/api/widgets/wdgt_src/duplicate' });
+ await duplicateHandler(req, mockRes());
+
+ const insert = sqlMock.mock.calls.find((call) => /insert into widgets/i.test(sqlText(call)));
+ expect(insert, 'duplicate must issue an INSERT into widgets').toBeDefined();
+ expect(sqlText(insert)).toMatch(/insert into widgets\s*\(\s*id\s*,/i);
+ // First interpolated value is the freshly minted id.
+ expect(insert[1]).toMatch(/^wdgt_[A-Za-z0-9_-]+$/);
+ });
+
+ it('requires a CSRF token for cookie-session callers', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([
+ { id: 'wdgt_src', type: 'turntable', name: 'Original', config: {}, avatar_id: null, is_public: true },
+ ]);
+ sqlQueue.push([{ id: 'wdgt_copy', user_id: 'user-1', type: 'turntable', name: 'Original (copy)' }]);
+
+ const req = mockReq({ method: 'POST', url: '/api/widgets/wdgt_src/duplicate' });
+ await duplicateHandler(req, mockRes());
+
+ expect(requireCsrf).toHaveBeenCalledWith(req, expect.anything(), 'user-1');
+ });
+
+ it('400s on a widget id the frontend never should have sent', async () => {
+ authState.session = { id: 'user-1' };
+ const req = mockReq({ method: 'POST', url: '/api/widgets/undefined/duplicate' });
+ const res = mockRes();
+ await duplicateHandler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseJson(res).error).toBe('invalid_request');
+ });
});
// ── GET /api/widgets/:id/stats ───────────────────────────────────────────────
@@ -758,6 +818,28 @@ describe('GET /api/widgets/:id/transcripts', () => {
expect(body.messages).toHaveLength(2);
expect(body.messages[1].provider).toBe('anthropic');
});
+
+ // getTranscript() returns null for a thread that is not on this widget, and
+ // the handler has to turn that into a clean 404 rather than an empty 200 or
+ // a crash on `data.thread`. This is the one cross-widget leak the transcript
+ // reader could have: the thread lookup is scoped by widget_id, so a guessed
+ // thread id from someone else's widget must read as not-found.
+ it('404s when the thread is not on this widget', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([{ id: 'wdgt_x' }]); // ownership ok
+ sqlQueue.push([]); // thread lookup: nothing on this widget
+
+ const req = mockReq({
+ method: 'GET',
+ url: '/api/widgets/wdgt_x/transcripts?id=wdgt_x&thread_id=wct_someone_else',
+ });
+ const res = mockRes();
+ await transcriptsHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ expect(parseJson(res).error).toBe('not_found');
+ // The message query must never run once the thread lookup came back empty.
+ expect(sqlMock.mock.calls.some((c) => /from widget_chat_messages/i.test(sqlText(c)))).toBe(false);
+ });
});
// ── /api/widgets/:id/knowledge ──────────────────────────────────────────────
diff --git a/tests/arena-tournament-api.test.js b/tests/arena-tournament-api.test.js
new file mode 100644
index 000000000..d2ec33b26
--- /dev/null
+++ b/tests/arena-tournament-api.test.js
@@ -0,0 +1,113 @@
+// Two guards on the Social Trading Arena's HTTP surface.
+//
+// 1. ROUTING. Filesystem routing matches a `[param].js` file only on the LAST
+// path segment, so `api/tournaments/[id].js` answered /api/tournaments/:id
+// and nothing under it. Join, withdraw, close, settle, and the SSE standings
+// stream all 404'd in production while the handler that implements them sat
+// right there, fully written, with a header comment documenting all five.
+// The Arena's Join button reported a failure and the live board's EventSource
+// reconnected against a 404 forever. Nothing in a diff shows this: the file
+// exists, the code is correct, and only the path shape decides whether it is
+// ever reached. So the URLs are asserted against the REAL resolver.
+//
+// 2. PRIZE PARSING. `prize_pool_three` arrives as JSON from the request body, and
+// the atomics conversion used to run through String(Number(x)). JS renders
+// anything past 1e21 or below 1e-6 in exponential notation, which BigInt
+// refuses, so `1e21` and `0.0000001` reached the handler as a 500 with a
+// support ref instead of a 400 telling the caller what was wrong.
+
+// 3. RE-ENTRY. `joinTournament` inserts with `on conflict do nothing`, so an entry
+// the user had withdrawn stayed withdrawn on re-join while the API answered
+// `joined: true` and the UI toasted "Entered the arena". The agent then sat out
+// the rest of the bracket, scored nothing, and never appeared in the standings.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { fileURLToPath } from 'node:url';
+import { join, relative } from 'node:path';
+
+import { resolveApi } from '../server/route-resolve.mjs';
+import { threeToAtomics } from '../api/tournaments/index.js';
+
+const db = vi.hoisted(() => ({ queries: [], conflict: true }));
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings) => {
+ const text = strings.join(' ? ');
+ db.queries.push(text);
+ if (/insert into tournament_entries/i.test(text)) {
+ return Promise.resolve(db.conflict ? [] : [{ agent_id: 'a1', status: 'active' }]);
+ }
+ if (/update tournament_entries[\s\S]*status = 'active'/i.test(text)) {
+ return Promise.resolve([{ agent_id: 'a1', status: 'active', wallet: 'W1' }]);
+ }
+ return Promise.resolve([]);
+ },
+}));
+
+const { joinTournament } = await import('../api/_lib/tournament-store.js');
+
+const REPO = fileURLToPath(new URL('..', import.meta.url));
+const API_ROOT = join(REPO, 'api');
+const ID = '53a2d208-92df-4e75-9cd7-a3c459f17bd6';
+
+/** Resolve an /api/... pathname the way server/index.mjs does. */
+function resolve(pathname) {
+ const segments = pathname.replace(/^\/api\//, '').split('/').filter(Boolean);
+ const hit = resolveApi(API_ROOT, segments, {});
+ return hit ? relative(REPO, hit.file) : null;
+}
+
+describe('Arena tournament routes reach a handler', () => {
+ it('resolves the collection endpoint', () => {
+ expect(resolve('/api/tournaments')).toBe('api/tournaments/index.js');
+ });
+
+ it('resolves a single tournament', () => {
+ expect(resolve(`/api/tournaments/${ID}`)).toBe('api/tournaments/[id].js');
+ });
+
+ it.each(['stream', 'join', 'withdraw', 'close', 'settle'])('resolves the %s action', (action) => {
+ expect(resolve(`/api/tournaments/${ID}/${action}`)).toBe('api/tournaments/[id]/[action].js');
+ });
+
+ it('passes the id and action through as route params', () => {
+ const hit = resolveApi(API_ROOT, ['tournaments', ID, 'join'], {});
+ expect(hit.params).toEqual({ id: ID, action: 'join' });
+ });
+});
+
+describe('threeToAtomics', () => {
+ it('converts a decimal amount at the token decimals', () => {
+ expect(threeToAtomics(1.5, 6)).toBe(1_500_000n);
+ expect(threeToAtomics(0, 6)).toBe(0n);
+ expect(threeToAtomics(250, 6)).toBe(250_000_000n);
+ });
+
+ it('reads a numeric string as written, past double precision', () => {
+ expect(threeToAtomics('123456789.123456', 6)).toBe(123_456_789_123_456n);
+ expect(threeToAtomics(' 10.5 ', 6)).toBe(10_500_000n);
+ });
+
+ it('truncates below one atomic instead of rounding up', () => {
+ expect(threeToAtomics('0.0000019', 6)).toBe(1n);
+ });
+
+ it('answers null for exponential-notation numbers it cannot back', () => {
+ expect(threeToAtomics(1e21, 6)).toBeNull();
+ expect(threeToAtomics('1e6', 6)).toBeNull();
+ });
+
+ it('flattens a small exponential number rather than crashing on it', () => {
+ expect(threeToAtomics(0.0000001, 6)).toBe(0n);
+ });
+
+ it('answers null for anything that is not a non-negative decimal', () => {
+ expect(threeToAtomics(-5, 6)).toBeNull();
+ expect(threeToAtomics(Number.NaN, 6)).toBeNull();
+ expect(threeToAtomics(Number.POSITIVE_INFINITY, 6)).toBeNull();
+ expect(threeToAtomics('abc', 6)).toBeNull();
+ expect(threeToAtomics(true, 6)).toBeNull();
+ expect(threeToAtomics({ a: 1 }, 6)).toBeNull();
+ expect(threeToAtomics(null, 6)).toBeNull();
+ expect(threeToAtomics(undefined, 6)).toBeNull();
+ });
+});
diff --git a/tests/vanity-escrow-gating.test.js b/tests/vanity-escrow-gating.test.js
new file mode 100644
index 000000000..1998a3baa
--- /dev/null
+++ b/tests/vanity-escrow-gating.test.js
@@ -0,0 +1,216 @@
+// The money gate on the two x402-paid vanity markets: a bounty or a drop only
+// becomes real once its payment actually SETTLED on-chain.
+//
+// 2026-08-15 audit of api/vanity/*: both create handlers persisted a live record
+// BEFORE settlePayment(). x402 verify and settle are two separate round-trips, so
+// a proof that verifies can still fail to settle (facilitator error, the payer
+// spending the authorization in between). When that happened:
+// • bounties: the bounty was already `open` and indexed, so a worker could grind
+// it and payWinner() would send real USDC out of the platform payout wallet
+// for escrow that was never collected. After expiry the same record could be
+// self-service refunded to the requester's own address instead.
+// • drops: the drop wallet was already funded on-chain from the platform funding
+// wallet, and a direct-seal recipient could still reveal + drain it for free.
+// Both handlers now record the row as `escrow_pending` (unindexed, refused by
+// every transition) and only activate it after settle; a failed settle voids it,
+// and for drops sweeps the funding back first.
+//
+// These run against each store's in-process fallback (no Redis in CI), which is
+// the same state machine the Lua paths implement.
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ createBounty,
+ activateBounty,
+ voidBounty,
+ claimBounty,
+ markRefundable,
+ queryBounties,
+ listClaimable,
+ bountyStats,
+ getBountyRecord,
+ __resetMemoryStore as resetBounties,
+} from '../api/_lib/vanity-bounty-store.js';
+import {
+ createDrop,
+ activateDrop,
+ voidDrop,
+ claimDrop,
+ markReclaimable,
+ listBySender,
+ dropStats,
+ isTransientDrop,
+ getDropRecord,
+ __resetMemoryStore as resetDrops,
+} from '../api/_lib/sealed-drop-store.js';
+
+const HOUR = 3600_000;
+
+function bountyRecord(over = {}) {
+ const now = Date.now();
+ return {
+ id: 'a1b2c3d4e5f60718',
+ protocol: 'three-vanity-bounty/v1',
+ pattern: { prefix: 'THREE', suffix: null, ignoreCase: false },
+ recipient: 'SoLXXXrecipientXXXpubkeyXXXbase58XXX',
+ refundAddress: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ amountAtomics: 500_000,
+ asset: 'USDC',
+ network: 'solana',
+ label: 'audit fixture',
+ createdAt: now,
+ expiresAt: now + 48 * HOUR,
+ status: 'escrow_pending',
+ ...over,
+ };
+}
+
+function dropRecord(over = {}) {
+ const now = Date.now();
+ return {
+ id: 'a1b2c3d4e5f607182930a1b2',
+ protocol: 'three-drop/v1',
+ address: 'THREEsynthetic1111111111111111111111111111',
+ asset: 'SOL',
+ amount: '0.01',
+ amountAtomics: '10000000',
+ network: 'solana',
+ sealMode: 'claim-time',
+ claimTokenHash: 'f'.repeat(64),
+ sealedSecret: { scheme: 'x25519-hkdf-sha256-aes256gcm/v1', ct: 'opaque' },
+ senderTag: 'audit-tag',
+ createdAt: now,
+ expiresAt: now + 24 * HOUR,
+ status: 'escrow_pending',
+ ...over,
+ };
+}
+
+describe('grind bounties: escrow settles before the bounty is real', () => {
+ beforeEach(() => resetBounties());
+
+ it('keeps a pending bounty off the board, the claim queue, and the stats', async () => {
+ await createBounty(bountyRecord());
+
+ expect(await listClaimable(30)).toEqual([]);
+ expect((await queryBounties({ status: 'open' })).total).toBe(0);
+ // status=all must hide it too: an unfunded row is not a bounty in any view.
+ expect((await queryBounties({ status: 'all' })).total).toBe(0);
+ expect(await bountyStats()).toMatchObject({ open: 0, openEscrowAtomics: 0, total: 0 });
+ });
+
+ it('refuses to settle a pending bounty to a worker', async () => {
+ const rec = bountyRecord();
+ await createBounty(rec);
+
+ const outcome = await claimBounty({
+ id: rec.id,
+ claimDigest: 'deadbeef',
+ winnerAddress: 'THREEsynthetic1111111111111111111111111111',
+ workerId: 'worker-1',
+ sealedSecret: { ct: 'opaque' },
+ });
+
+ expect(outcome).toBe('closed');
+ expect((await getBountyRecord(rec.id)).status).toBe('escrow_pending');
+ });
+
+ it('refuses to refund a pending bounty, even once it has expired', async () => {
+ const rec = bountyRecord({ expiresAt: Date.now() - HOUR });
+ await createBounty(rec);
+
+ expect(await markRefundable(rec.id)).toBe('ineligible');
+ expect((await getBountyRecord(rec.id)).status).toBe('escrow_pending');
+ });
+
+ it('goes live, indexed, with its settlement tx once the escrow lands', async () => {
+ const rec = bountyRecord();
+ await createBounty(rec);
+
+ expect(await activateBounty({ id: rec.id, escrowTx: 'tx-escrow-1', escrowNetwork: 'solana' })).toBe('live');
+
+ const stored = await getBountyRecord(rec.id);
+ expect(stored.status).toBe('open');
+ expect(stored.escrowTx).toBe('tx-escrow-1');
+ expect((await listClaimable(30)).map((b) => b.id)).toEqual([rec.id]);
+ expect(await bountyStats()).toMatchObject({ open: 1, openEscrowAtomics: 500_000, total: 1 });
+ // Idempotent: a retried activation does not disturb a live bounty.
+ expect(await activateBounty({ id: rec.id, escrowTx: 'tx-escrow-1' })).toBe('live');
+ });
+
+ it('voids a bounty whose escrow never settled, permanently', async () => {
+ const rec = bountyRecord();
+ await createBounty(rec);
+
+ expect(await voidBounty({ id: rec.id, reason: 'settle failed' })).toBe('void');
+ expect(await voidBounty({ id: rec.id })).toBe('void'); // idempotent
+ // A voided bounty can never be resurrected into a live one.
+ expect(await activateBounty({ id: rec.id, escrowTx: 'tx-late' })).toBe('ineligible');
+ expect(await listClaimable(30)).toEqual([]);
+ expect((await getBountyRecord(rec.id)).voidReason).toBe('settle failed');
+ });
+
+ it('never activates or voids a bounty that does not exist', async () => {
+ expect(await activateBounty({ id: 'ffffffff', escrowTx: 'x' })).toBe('missing');
+ expect(await voidBounty({ id: 'ffffffff' })).toBe('missing');
+ });
+});
+
+describe('sealed drops: the create fee settles before the drop is claimable', () => {
+ beforeEach(() => resetDrops());
+
+ it('hides a pending drop from the sender list and the stats', async () => {
+ const rec = dropRecord();
+ await createDrop(rec);
+
+ expect(isTransientDrop(await getDropRecord(rec.id))).toBe(true);
+ expect(await listBySender('audit-tag')).toEqual([]);
+ expect(await dropStats()).toMatchObject({ funded: 0, total: 0 });
+ });
+
+ it('refuses to release a pending drop to a claimant', async () => {
+ const rec = dropRecord();
+ await createDrop(rec);
+
+ expect(await claimDrop({ id: rec.id, claimerTag: 'f'.repeat(64) })).toBe('closed');
+ expect((await getDropRecord(rec.id)).status).toBe('escrow_pending');
+ });
+
+ it('refuses to reclaim a pending drop, even once it has expired', async () => {
+ const rec = dropRecord({ expiresAt: Date.now() - HOUR });
+ await createDrop(rec);
+
+ expect(await markReclaimable(rec.id)).toBe('ineligible');
+ });
+
+ it('goes live and claimable once the fee lands', async () => {
+ const rec = dropRecord();
+ await createDrop(rec);
+
+ expect(await activateDrop({ id: rec.id, escrowTx: 'tx-fee-1' })).toBe('live');
+
+ const stored = await getDropRecord(rec.id);
+ expect(stored.status).toBe('funded');
+ expect(stored.escrowTx).toBe('tx-fee-1');
+ expect(isTransientDrop(stored)).toBe(false);
+ expect((await listBySender('audit-tag')).map((d) => d.id)).toEqual([rec.id]);
+ expect(await dropStats()).toMatchObject({ funded: 1, total: 1 });
+ expect(await claimDrop({ id: rec.id, claimerTag: 'f'.repeat(64) })).toBe('won');
+ });
+
+ it('voids a drop whose fee never settled, permanently', async () => {
+ const rec = dropRecord();
+ await createDrop(rec);
+
+ expect(await voidDrop({ id: rec.id, reason: 'settle failed' })).toBe('void');
+ expect(await voidDrop({ id: rec.id })).toBe('void'); // idempotent
+ expect(await activateDrop({ id: rec.id, escrowTx: 'tx-late' })).toBe('ineligible');
+ expect(await claimDrop({ id: rec.id, claimerTag: 'f'.repeat(64) })).toBe('closed');
+ expect(await dropStats()).toMatchObject({ funded: 0, total: 0 });
+ });
+
+ it('never activates or voids a drop that does not exist', async () => {
+ expect(await activateDrop({ id: 'a'.repeat(24) })).toBe('missing');
+ expect(await voidDrop({ id: 'a'.repeat(24) })).toBe('missing');
+ });
+});