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 wallet x402 guards, CAIP agent lookups, and tokenized launches

nirholasef316fecf47a
diff --git a/tests/api-user-wallet-x402-guards.test.js b/tests/api-user-wallet-x402-guards.test.js
new file mode 100644
index 000000000..17c38ea8e
--- /dev/null
+++ b/tests/api-user-wallet-x402-guards.test.js
@@ -0,0 +1,337 @@
+// Boundary tests for the api/user batch: the guards that decide whether a
+// request is allowed to change a credential or move funds, and the malformed
+// input that used to escape as a 5xx.
+//
+// What is covered here, and why each case exists:
+//
+// 1. /api/user/x402-subscriptions POST (rotate + revoke) permanently changes
+// a live API credential on nothing but a session cookie. It shipped with
+// no CSRF proof while every sibling session-auth writer required one, so a
+// cross-site form POST could revoke a paying customer's key. The attacker
+// never reads the response; the write is the damage.
+// 2. A native rotate mints the replacement BEFORE revoking the old key.
+// Revoking first meant any mint failure left the caller with nothing.
+// 3. /api/user/wallet/fund-agent read the destination out of agent_identities
+// meta and handed it straight to `new PublicKey()`. A row whose stored
+// address is not decodable threw past every boundary as an opaque 500.
+// 4. /api/user/wallet/history clamped `?limit` only at the top, so a negative
+// limit reached the RPC and came back as a 502 blamed on Solana.
+
+import { Readable } from 'node:stream';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const USER_ID = 'user-1';
+const AGENT_ID = '11111111-1111-4111-8111-111111111111';
+// Synthetic, deliberately: these cases assert address handling only, so a real
+// third-party account would add a claim we do not mean.
+const MASTER_WALLET = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
+const AGENT_WALLET = 'GDfnEsia2WLAW5t8yx2X5j2mkfA74i5kK8vY6C4nGRQe';
+
+const authState = { session: { id: USER_ID } };
+const csrfState = { ok: true };
+const sqlState = { queue: [] };
+const rpcState = { sigLimit: null, balanceLamports: 5_000_000n, tokenAmount: '2500000', destAtaExists: true };
+const keysState = { calls: [], createThrows: null };
+
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+}));
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => (sqlState.queue.length ? sqlState.queue.shift() : [])),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: async () => ({ pressured: false }),
+}));
+
+vi.mock('../api/_lib/csrf.js', () => ({
+ requireCsrf: vi.fn(async (_req, res) => {
+ if (csrfState.ok) return true;
+ res.statusCode = 403;
+ res.end(JSON.stringify({ error: 'csrf_missing' }));
+ return false;
+ }),
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authIp: vi.fn(async () => ({ success: true })),
+ walletRead: vi.fn(async () => ({ success: true })),
+ walletSimulate: vi.fn(async () => ({ success: true })),
+ withdrawalPerUser: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../api/_lib/usage.js', () => ({ recordEvent: vi.fn(async () => {}) }));
+vi.mock('../api/_lib/cache.js', () => ({
+ cacheGet: vi.fn(async () => null),
+ cacheSet: vi.fn(async () => {}),
+}));
+
+// A recovered keypair would mean a real signature. Every case below stops at
+// simulate or at a guard, so reaching this mock at all is a test bug.
+vi.mock('../api/_lib/agent-wallet.js', () => ({
+ recoverSolanaAgentKeypair: vi.fn(async () => {
+ throw new Error('test reached key recovery: no case here may sign');
+ }),
+}));
+
+const connection = {
+ getBalance: vi.fn(async () => Number(rpcState.balanceLamports)),
+ getMinimumBalanceForRentExemption: vi.fn(async () => 2_039_280),
+ getTokenAccountBalance: vi.fn(async () => ({ value: { amount: rpcState.tokenAmount } })),
+ getAccountInfo: vi.fn(async () => (rpcState.destAtaExists ? { lamports: 1 } : null)),
+ getSignaturesForAddress: vi.fn(async (_pk, opts) => {
+ rpcState.sigLimit = opts?.limit ?? null;
+ return [];
+ }),
+ getParsedTransactions: vi.fn(async () => []),
+};
+
+vi.mock('../api/_lib/agent-pumpfun.js', () => ({
+ solanaConnection: vi.fn(() => connection),
+ solanaPublicConnection: vi.fn(() => connection),
+}));
+
+vi.mock('../api/_lib/x402/api-keys.js', () => ({
+ createSubscription: vi.fn(async (args) => {
+ keysState.calls.push('create');
+ if (keysState.createThrows) throw keysState.createThrows;
+ return {
+ id: 'sub_new',
+ key_prefix: 'x402_newprefix',
+ token: 'x402_newplaintext',
+ rate_limit_per_minute: args.rateLimitPerMinute,
+ };
+ }),
+ revokeSubscription: vi.fn(async () => {
+ keysState.calls.push('revoke');
+ return { id: 'sub_old' };
+ }),
+}));
+
+vi.mock('../api/_lib/aws-marketplace-bridge.js', () => ({
+ issueSubscriptionForCustomer: vi.fn(async () => ({
+ subscriptionId: 'sub_aws',
+ keyPrefix: 'x402_aws',
+ token: 'x402_awsplaintext',
+ rateLimitPerMinute: 600,
+ })),
+ revokeSubscriptionForCustomer: vi.fn(async () => 'sub_old'),
+}));
+
+const subscriptionsHandler = (await import('../api/user/x402-subscriptions.js')).default;
+const fundAgentHandler = (await import('../api/user/wallet/fund-agent.js')).default;
+const historyHandler = (await import('../api/user/wallet/history.js')).default;
+
+function makeReq({ method, url, body = null }) {
+ const raw = body === null ? null : JSON.stringify(body);
+ const req = Readable.from(raw === null ? [] : [Buffer.from(raw)]);
+ req.method = method;
+ req.url = url;
+ req.headers = { host: 'localhost', ...(raw === null ? {} : { 'content-type': 'application/json' }) };
+ return req;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ headersSent: false,
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ };
+}
+
+async function call(handler, { method = 'GET', url, body = null } = {}) {
+ const req = makeReq({ method, url, body });
+ const res = makeRes();
+ await handler(req, res);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+const NATIVE_SUB = {
+ id: 'sub_old',
+ name: 'my key',
+ rate_limit_per_minute: 120,
+ expires_at: null,
+ revoked_at: null,
+ meta: { source: 'native' },
+ created_by: USER_ID,
+};
+
+beforeEach(() => {
+ authState.session = { id: USER_ID };
+ csrfState.ok = true;
+ sqlState.queue = [];
+ keysState.calls = [];
+ keysState.createThrows = null;
+ rpcState.sigLimit = null;
+ rpcState.balanceLamports = 5_000_000n;
+ rpcState.tokenAmount = '2500000';
+ rpcState.destAtaExists = true;
+});
+
+describe('x402-subscriptions: CSRF on the write path', () => {
+ it('refuses a revoke that carries no CSRF token, before touching the key', async () => {
+ csrfState.ok = false;
+ const { status } = await call(subscriptionsHandler, {
+ method: 'POST',
+ url: '/api/user/x402-subscriptions',
+ body: { action: 'revoke', id: 'sub_old' },
+ });
+ expect(status).toBe(403);
+ expect(keysState.calls).toEqual([]);
+ });
+
+ it('refuses a rotate that carries no CSRF token', async () => {
+ csrfState.ok = false;
+ const { status } = await call(subscriptionsHandler, {
+ method: 'POST',
+ url: '/api/user/x402-subscriptions',
+ body: { action: 'rotate', id: 'sub_old' },
+ });
+ expect(status).toBe(403);
+ expect(keysState.calls).toEqual([]);
+ });
+
+ it('leaves the read path ungated: listing works without a CSRF token', async () => {
+ csrfState.ok = false;
+ sqlState.queue.push([{ ...NATIVE_SUB, key_prefix: 'x402_old', created_at: '2026-08-01T00:00:00Z' }]);
+ const { status, body } = await call(subscriptionsHandler, {
+ method: 'GET',
+ url: '/api/user/x402-subscriptions',
+ });
+ expect(status).toBe(200);
+ expect(body.subscriptions).toHaveLength(1);
+ expect(body.subscriptions[0].status).toBe('active');
+ });
+
+ it('still refuses a caller who is not signed in', async () => {
+ authState.session = null;
+ const { status, body } = await call(subscriptionsHandler, {
+ method: 'POST',
+ url: '/api/user/x402-subscriptions',
+ body: { action: 'revoke', id: 'sub_old' },
+ });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthenticated');
+ });
+});
+
+describe('x402-subscriptions: native rotate ordering', () => {
+ it('mints the replacement before revoking the old key', async () => {
+ sqlState.queue.push([NATIVE_SUB]);
+ const { status, body } = await call(subscriptionsHandler, {
+ method: 'POST',
+ url: '/api/user/x402-subscriptions',
+ body: { action: 'rotate', id: 'sub_old' },
+ });
+ expect(status).toBe(200);
+ expect(keysState.calls).toEqual(['create', 'revoke']);
+ expect(body.subscription.token).toBe('x402_newplaintext');
+ });
+
+ it('leaves the old key alive when the mint fails', async () => {
+ keysState.createThrows = new Error('subscription name is required');
+ sqlState.queue.push([NATIVE_SUB]);
+ const { status, body } = await call(subscriptionsHandler, {
+ method: 'POST',
+ url: '/api/user/x402-subscriptions',
+ body: { action: 'rotate', id: 'sub_old' },
+ });
+ expect(status).toBe(502);
+ expect(body.error).toBe('rotate_failed');
+ expect(keysState.calls).toEqual(['create']);
+ });
+
+ it('404s a subscription owned by somebody else rather than acting on it', async () => {
+ sqlState.queue.push([{ ...NATIVE_SUB, created_by: 'someone-else' }]);
+ const { status, body } = await call(subscriptionsHandler, {
+ method: 'POST',
+ url: '/api/user/x402-subscriptions',
+ body: { action: 'revoke', id: 'sub_old' },
+ });
+ expect(status).toBe(404);
+ expect(body.error).toBe('subscription_not_found');
+ expect(keysState.calls).toEqual([]);
+ });
+});
+
+describe('wallet/fund-agent: the agent address it was handed', () => {
+ function primeWalletAndAgent(agentMeta) {
+ sqlState.queue.push([{ solana_address: MASTER_WALLET, encrypted_solana_secret: 'enc' }]);
+ sqlState.queue.push([{ id: AGENT_ID, meta: agentMeta }]);
+ }
+
+ it('names an undecodable stored address instead of throwing a 500', async () => {
+ primeWalletAndAgent({ solana_address: 'not-a-real-solana-address' });
+ const { status, body } = await call(fundAgentHandler, {
+ method: 'POST',
+ url: '/api/user/wallet/fund-agent',
+ body: { agent_id: AGENT_ID, amount: 1, asset: 'USDC', simulate: true },
+ });
+ expect(status).toBe(422);
+ expect(body.error).toBe('agent_wallet_invalid');
+ });
+
+ it('still simulates a real USDC transfer against a valid agent wallet', async () => {
+ primeWalletAndAgent({ solana_address: AGENT_WALLET });
+ const { status, body } = await call(fundAgentHandler, {
+ method: 'POST',
+ url: '/api/user/wallet/fund-agent',
+ body: { agent_id: AGENT_ID, amount: 1.5, asset: 'USDC', simulate: true },
+ });
+ expect(status).toBe(200);
+ expect(body.simulation.agent_wallet).toBe(AGENT_WALLET);
+ expect(body.simulation.human_amount).toBe(1.5);
+ expect(body.simulation.creates_token_account).toBe(false);
+ });
+
+ it('rejects an agent that has no wallet at all', async () => {
+ primeWalletAndAgent({});
+ const { status, body } = await call(fundAgentHandler, {
+ method: 'POST',
+ url: '/api/user/wallet/fund-agent',
+ body: { agent_id: AGENT_ID, amount: 1, asset: 'USDC', simulate: true },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('no_agent_wallet');
+ });
+});
+
+describe('wallet/history: limit clamping', () => {
+ it('clamps a negative limit instead of passing it to the RPC', async () => {
+ sqlState.queue.push([{ solana_address: MASTER_WALLET }]);
+ const { status } = await call(historyHandler, {
+ method: 'GET',
+ url: '/api/user/wallet/history?limit=-5',
+ });
+ expect(status).toBe(200);
+ expect(rpcState.sigLimit).toBe(1);
+ });
+
+ it('still caps an oversized limit at 50', async () => {
+ sqlState.queue.push([{ solana_address: MASTER_WALLET }]);
+ const { status } = await call(historyHandler, {
+ method: 'GET',
+ url: '/api/user/wallet/history?limit=9999',
+ });
+ expect(status).toBe(200);
+ expect(rpcState.sigLimit).toBe(50);
+ });
+
+ it('answers an empty history for a user with no master wallet', async () => {
+ sqlState.queue.push([]);
+ const { status, body } = await call(historyHandler, {
+ method: 'GET',
+ url: '/api/user/wallet/history',
+ });
+ expect(status).toBe(200);
+ expect(body.history).toEqual([]);
+ });
+});
diff --git a/tests/api/v1-agents-caip.test.js b/tests/api/v1-agents-caip.test.js
new file mode 100644
index 000000000..217980f41
--- /dev/null
+++ b/tests/api/v1-agents-caip.test.js
@@ -0,0 +1,210 @@
+// GET /api/v1/agents/:caip, the ERC-8004 / Card v1 agent resolver.
+//
+// The first block is the regression guard that matters most: the ref carries a
+// "/" before the tokenId, and the API dispatcher rejects any path segment that
+// percent-decodes to contain a separator (the guard that stops
+// "%2f..%2f..%2fvite.config" traversal). A whole-ref encodeURIComponent
+// therefore produces "%2F" and 404s before any handler runs, which is what the
+// docs used to tell callers to send and what src/erc8004/badge.js used to
+// build. These tests resolve through the REAL production resolver
+// (server/route-resolve.mjs, the same module server/index.mjs dispatches with)
+// so a rename back to a single-segment [caip].js fails here instead of in
+// production.
+//
+// The rest exercises the handler itself against a stubbed chain read: the
+// success path, an unparseable ref (400), an unsupported chain (400), a
+// registry that differs from the canonical deployment (400), a chain-read miss
+// (404), and the rate limit (429).
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { Readable } from 'node:stream';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { apiSegments, resolveApi } from '../../server/route-resolve.mjs';
+
+const API_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../api');
+
+const REGISTRY = '0x8004A169Ff0A8Ff2Ea3b5D0a3F4a1E3D3f6a1e3D';
+const OWNER = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045';
+const REF = `eip155:8453:${REGISTRY}/1`;
+
+// ── Routing: does the documented URL actually reach a handler? ───────────────
+
+function resolvePath(pathname) {
+ const segments = apiSegments(pathname);
+ if (!segments) return null;
+ return resolveApi(API_ROOT, segments, {});
+}
+
+describe('/api/v1/agents/:caip routing', () => {
+ it('routes a ref whose "/" is a real path separator', () => {
+ const hit = resolvePath(`/api/v1/agents/${REF}`);
+ expect(hit).not.toBeNull();
+ expect(path.basename(hit.file)).toBe('[...caip].js');
+ expect(hit.params.caip).toBe(REF);
+ });
+
+ it('routes the ref with percent-encoded colons, decoding them back', () => {
+ const hit = resolvePath(`/api/v1/agents/eip155%3A8453%3A${REGISTRY}/1`);
+ expect(hit).not.toBeNull();
+ expect(hit.params.caip).toBe(REF);
+ });
+
+ it('still refuses a percent-encoded slash, so the traversal guard holds', () => {
+ // This is the shape a whole-ref encodeURIComponent produces. It must stay
+ // unroutable: the same rule stops "%2f..%2f..%2fvite.config".
+ expect(apiSegments(`/api/v1/agents/${encodeURIComponent(REF)}`)).toBeNull();
+ expect(apiSegments('/api/v1/agents/%2e%2e%2f%2e%2e%2fvite.config')).toBeNull();
+ });
+});
+
+// ── Handler ─────────────────────────────────────────────────────────────────
+
+let quotaOk = true;
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ mcpIp: async () =>
+ quotaOk
+ ? { success: true, limit: 60, remaining: 59, reset: Date.now() + 60_000 }
+ : { success: false, limit: 60, remaining: 0, reset: Date.now() + 60_000 },
+ },
+ clientIp: () => '203.0.113.9',
+}));
+
+let chainResult = null;
+vi.mock('../../api/_lib/onchain.js', () => ({
+ resolveOnChainAgent: async () => chainResult,
+ resolveURI: (uri) => uri,
+}));
+
+// The card's model.uri is attacker-authored, so the handler fetches it through
+// the SSRF guard. Stub that boundary so no test opens a socket.
+let modelBytes = null;
+vi.mock('../../api/_lib/ssrf-guard.js', () => ({
+ fetchSafePublicUrl: async () =>
+ modelBytes
+ ? { ok: true, arrayBuffer: async () => modelBytes }
+ : { ok: false, arrayBuffer: async () => new ArrayBuffer(0) },
+}));
+
+beforeEach(() => {
+ quotaOk = true;
+ modelBytes = null;
+ chainResult = {
+ chainId: 8453,
+ agentId: '1',
+ registry: REGISTRY,
+ owner: OWNER,
+ tokenURI: 'ipfs://bafyagentcard',
+ manifest: {
+ type: ['https://three.ws/specs/3d-agent-card-v1'],
+ name: 'Test Agent',
+ },
+ };
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function makeReq(caip, { method = 'GET' } = {}) {
+ const stream = Readable.from([]);
+ stream.method = method;
+ stream.url = `/api/v1/agents/${caip}`;
+ stream.headers = { host: 'three.ws' };
+ stream.query = { caip };
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; this.writableEnded = true; },
+ };
+}
+
+async function dispatch(req, res) {
+ const mod = await import('../../api/v1/agents/[...caip].js');
+ await mod.default(req, res);
+ return { res, body: res._body ? JSON.parse(res._body) : null };
+}
+
+describe('GET /api/v1/agents/:caip handler', () => {
+ it('resolves an agent and reports the card schema', async () => {
+ const { res, body } = await dispatch(makeReq(REF), makeRes());
+ expect(res.statusCode).toBe(200);
+ expect(body.ref).toBe(`eip155:8453:${REGISTRY}/1`);
+ expect(body.chainId).toBe(8453);
+ expect(body.agentId).toBe('1');
+ expect(body.owner).toBe(OWNER);
+ expect(body.card.name).toBe('Test Agent');
+ expect(body.verified).toEqual({ modelSha256: null, cardSchema: '3d-agent-card-v1' });
+ expect(res.getHeader('cache-control')).toMatch(/s-maxage=300/);
+ });
+
+ it('accepts the array form a catch-all param can take', async () => {
+ const req = makeReq(REF);
+ req.query = { caip: [`eip155:8453:${REGISTRY}`, '1'] };
+ const { res } = await dispatch(req, makeRes());
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('verifies the card model hash against the fetched bytes', async () => {
+ const bytes = new TextEncoder().encode('glb-bytes');
+ const digest = await crypto.subtle.digest('SHA-256', bytes);
+ const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
+ modelBytes = bytes.buffer;
+ chainResult.manifest.model = { uri: 'https://cdn.three.ws/a.glb', sha256: hex };
+
+ const { body } = await dispatch(makeReq(REF), makeRes());
+ expect(body.verified.modelSha256).toBe(true);
+ });
+
+ it('reports a mismatched model hash as false rather than failing the request', async () => {
+ modelBytes = new TextEncoder().encode('different-bytes').buffer;
+ chainResult.manifest.model = { uri: 'https://cdn.three.ws/a.glb', sha256: 'deadbeef' };
+
+ const { res, body } = await dispatch(makeReq(REF), makeRes());
+ expect(res.statusCode).toBe(200);
+ expect(body.verified.modelSha256).toBe(false);
+ });
+
+ it('rejects a ref that is not a CAIP agent ref with 400', async () => {
+ const { res, body } = await dispatch(makeReq('notacaip'), makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('invalid_caip');
+ });
+
+ it('rejects an unsupported chain with 400', async () => {
+ chainResult = { error: 'unsupported_chain' };
+ const { res, body } = await dispatch(makeReq(`eip155:999999:${REGISTRY}/1`), makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('unsupported_chain');
+ });
+
+ it('returns 404 (never 500) when the chain read finds no such agent', async () => {
+ chainResult = { error: 'chain_read: execution reverted' };
+ const { res, body } = await dispatch(makeReq(REF), makeRes());
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('rejects a registry that differs from the canonical deployment with 400', async () => {
+ const { res, body } = await dispatch(
+ makeReq('eip155:8453:0x00000000000000000000000000000000deadbeef/1'),
+ makeRes(),
+ );
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('registry_mismatch');
+ });
+
+ it('rate-limits per IP with 429', async () => {
+ quotaOk = false;
+ const { res } = await dispatch(makeReq(REF), makeRes());
+ expect(res.statusCode).toBe(429);
+ });
+});
diff --git a/tests/api/v1-tokenized-launches.test.js b/tests/api/v1-tokenized-launches.test.js
new file mode 100644
index 000000000..21627ae6e
--- /dev/null
+++ b/tests/api/v1-tokenized-launches.test.js
@@ -0,0 +1,161 @@
+// GET /api/v1/tokenized/launches - the free, paginated directory of 3D assets
+// minted as Metaplex Core NFTs THROUGH three.ws (the NFT analogue of
+// /api/v1/pump/launches).
+//
+// The SQL lives in api/_lib/tokenized-launches.js `queryTokenizedLaunches` and
+// is shared with api/creations-leaderboard.js, so it is mocked at the module
+// boundary here: these tests pin the handler's OWN contract, which is the part
+// a caller sees. Namely that it clamps and normalizes pagination before the
+// query ever runs (a scripted crawler cannot ask for 9999 rows or a negative
+// offset), rejects a malformed agent_id with a 400 instead of handing a junk
+// value to Postgres, enforces the per-IP quota, and surfaces a database outage
+// as an honest 503 rather than an empty-looking "no launches yet" page.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+let quotaOk = true;
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ apiV1: async () => ({ success: true, limit: 120, remaining: 119, reset: Date.now() + 60_000 }),
+ publicIp: async () =>
+ quotaOk
+ ? { success: true, limit: 60, remaining: 59, reset: Date.now() + 60_000 }
+ : { success: false, limit: 60, remaining: 0, reset: Date.now() + 60_000 },
+ },
+ clientIp: () => '203.0.113.21',
+}));
+
+let queryImpl = async () => ({ launches: [], has_more: false });
+const queryCalls = [];
+vi.mock('../../api/_lib/tokenized-launches.js', () => ({
+ queryTokenizedLaunches: (args) => {
+ queryCalls.push(args);
+ return queryImpl(args);
+ },
+}));
+
+// One row in the shape queryTokenizedLaunches actually returns (mint, network,
+// glb/image/viewer urls, royalty terms, provenance, and the creating agent).
+const ROW = {
+ mint: 'AhTQ4rN9k9c7iqDs3Vb3T8kqz1oV3Q1oQ4L5s7pWmR2t',
+ network: 'mainnet',
+ name: 'Knight Avatar',
+ glb_url: 'https://three.ws/api/asset/knight.glb',
+ image_url: 'https://three.ws/api/asset/knight.png',
+ viewer_url: 'https://three.ws/viewer?mint=AhTQ4rN9k9c7iqDs3Vb3T8kqz1oV3Q1oQ4L5s7pWmR2t',
+ royalty_bps: 500,
+ royalty_recipient: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU',
+ parent_mint: null,
+ provenance: 'forge',
+ remix_royalty: null,
+ created_at: '2026-08-01T12:00:00.000Z',
+ agent_id: '3f1c8a52-6b6f-4b4a-9a0a-1f2d3c4b5a60',
+ agent_name: 'Knight',
+ agent_solana_address: '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU',
+};
+
+beforeEach(() => {
+ quotaOk = true;
+ queryCalls.length = 0;
+ queryImpl = async () => ({ launches: [], has_more: false });
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function makeReq({ url, host = 'three.ws' } = {}) {
+ const stream = Readable.from([]);
+ stream.method = 'GET';
+ stream.url = url;
+ stream.headers = { host };
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; this.writableEnded = true; },
+ };
+}
+
+async function dispatch(url) {
+ const mod = await import('../../api/v1/tokenized/launches.js');
+ const res = makeRes();
+ await mod.default(makeReq({ url }), res);
+ return { res, body: res._body ? JSON.parse(res._body) : null };
+}
+
+describe('GET /api/v1/tokenized/launches', () => {
+ it('returns the minted-asset feed with its pagination echo', async () => {
+ queryImpl = async () => ({ launches: [ROW], has_more: true });
+ const { res, body } = await dispatch('/api/v1/tokenized/launches?limit=1');
+ expect(res.statusCode).toBe(200);
+ expect(body.data.launches).toHaveLength(1);
+ expect(body.data.launches[0].mint).toBe(ROW.mint);
+ expect(body.data.has_more).toBe(true);
+ expect(body.data.limit).toBe(1);
+ expect(body.data.offset).toBe(0);
+ expect(body.data.network).toBe('mainnet');
+ expect(res.getHeader('cache-control')).toMatch(/max-age=15/);
+ });
+
+ it('clamps limit and offset before they reach the query', async () => {
+ await dispatch('/api/v1/tokenized/launches?limit=9999&offset=-5');
+ expect(queryCalls[0]).toMatchObject({ limit: 100, offset: 0 });
+ await dispatch('/api/v1/tokenized/launches?limit=abc&offset=abc');
+ expect(queryCalls[1]).toMatchObject({ limit: 24, offset: 0 });
+ await dispatch('/api/v1/tokenized/launches?limit=0');
+ expect(queryCalls[2]).toMatchObject({ limit: 1 });
+ });
+
+ it('accepts devnet and treats every other network value as mainnet', async () => {
+ await dispatch('/api/v1/tokenized/launches?network=devnet');
+ expect(queryCalls[0].network).toBe('devnet');
+ const { body } = await dispatch('/api/v1/tokenized/launches?network=testnet');
+ expect(queryCalls[1].network).toBe('mainnet');
+ expect(body.data.network).toBe('mainnet');
+ });
+
+ it('passes a valid agent_id through and rejects a malformed one with 400', async () => {
+ await dispatch(`/api/v1/tokenized/launches?agent_id=${ROW.agent_id}`);
+ expect(queryCalls[0].agentId).toBe(ROW.agent_id);
+
+ const { res, body } = await dispatch('/api/v1/tokenized/launches?agent_id=not-a-uuid');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ // The bad request never reached the database.
+ expect(queryCalls).toHaveLength(1);
+ });
+
+ it('surfaces a database outage as 503, never as an empty feed', async () => {
+ queryImpl = async () => {
+ throw new Error('Missing required env var: DATABASE_URL');
+ };
+ const { res, body } = await dispatch('/api/v1/tokenized/launches');
+ expect(res.statusCode).toBe(503);
+ expect(body.error).toBe('service_unavailable');
+ expect(body.data).toBeUndefined();
+ });
+
+ it('returns 429 when the per-IP quota is exhausted', async () => {
+ quotaOk = false;
+ const { res, body } = await dispatch('/api/v1/tokenized/launches');
+ expect(res.statusCode).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ expect(queryCalls).toHaveLength(0);
+ });
+
+ it('is registered in the /api/v1 catalog as a free public GET', async () => {
+ const { CATALOG } = await import('../../api/v1/_catalog.js');
+ const entry = CATALOG.find((e) => e.id === 'v1.tokenized.launches');
+ expect(entry, 'v1.tokenized.launches missing from catalog').toBeTruthy();
+ expect(entry.method).toBe('GET');
+ expect(entry.auth).toBe('public');
+ });
+});