Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
test(animations): cover clip access, presigns, thumbnails, sales, and the avatar subpath routes
nirholas1a390df196f6
diff --git a/tests/api/animation-clips.test.js b/tests/api/animation-clips.test.jsindex c96f7e241..6340a4c08 100644--- a/tests/api/animation-clips.test.js+++ b/tests/api/animation-clips.test.js@@ -92,6 +92,13 @@ describe('cursor round-trip', () => {it('returns null for a garbage cursor', () => {expect(decodeCursor('@@@not-base64@@@')).toBeNull();});+ it('returns null for a well-formed cursor carrying an unparsable date', () => {+ // Regression: an Invalid Date reached Postgres as "0NaN-NaN-NaN..." and+ // turned a mangled query string into a 500 instead of an ignored cursor.+ const cur = Buffer.from(JSON.stringify({ c: 'garbage' })).toString('base64url');+ expect(decodeCursor(cur)).toBeNull();+ expect(decodeCursor(Buffer.from(JSON.stringify({})).toString('base64url'))).toBeNull();+ });});describe('listItem projection', () => {diff --git a/tests/api/animations-clip-access.test.js b/tests/api/animations-clip-access.test.jsnew file mode 100644index 000000000..ef4ad4f84--- /dev/null+++ b/tests/api/animations-clip-access.test.js@@ -0,0 +1,219 @@+/**+ * GET /api/animations/clips/:id access tests.+ *+ * Two things this endpoint has to get right, both regressions:+ *+ * 1. The route pattern (vercel.json) admits any hex-and-dash string, but the+ * column is a uuid. A looser id used to reach Postgres as an invalid uuid+ * literal and come back as a 500 with a support ref, when the caller had+ * earned a 400.+ * 2. A clip listed for sale sells its motion through the x402 paid download+ * (api/x402/animation-download.js), and the marketplace feed publishes the+ * clip id to every browser. Handing the baked tracks back here for free+ * would give away exactly what the paywall charges for. `public` visibility+ * is the creator publishing to the free gallery, so it is never gated.+ *+ * The db, auth and R2 boundaries are stubbed; the handler, its http envelope+ * and the real gate logic run.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const db = { rows: [] };+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async () => db.rows),+}));++const session = { user: null };+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => session.user),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+ hasScope: vi.fn(() => true),+}));++vi.mock('../../api/_lib/r2.js', () => ({+ getObjectBuffer: vi.fn(async () => Buffer.from('{"name":"offloaded","duration":1,"tracks":[]}')),+ putObject: vi.fn(async () => ({})),+ thumbnailUrl: vi.fn((key) => (key ? `https://cdn.test/${key}` : null)),+}));++const { default: handler } = await import('../../api/animations/[id].js');+const { getObjectBuffer } = await import('../../api/_lib/r2.js');++const OWNER = '11111111-1111-4111-8111-111111111111';+const CLIP_ID = '22222222-2222-4222-8222-222222222222';++const bakedClip = {+ name: 'Spin',+ duration: 1,+ tracks: [{ name: 'Hips.quaternion', type: 'quaternion', times: [0], values: [0, 0, 0, 1] }],+};++function row(overrides = {}) {+ return {+ id: CLIP_ID,+ owner_id: OWNER,+ avatar_id: null,+ slug: 'spin',+ name: 'Spin',+ description: null,+ kind: 'loop',+ format: 'three.ws.animation.v1',+ duration_ms: 1000,+ frame_count: 1,+ fps: 30,+ loop: true,+ clip: bakedClip,+ storage_key: null,+ editor_doc: { duration: 1, keyframes: [] },+ thumbnail_key: null,+ tags: [],+ visibility: 'unlisted',+ price_amount: null,+ price_currency: null,+ listed: false,+ play_count: 0,+ purchase_count: 0,+ created_at: 'now',+ updated_at: 'now',+ ...overrides,+ };+}++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; };+ r.json = () => JSON.parse(r._b);+ return r;+}++async function get(id, query = '') {+ const res = makeRes();+ const req = {+ method: 'GET',+ url: `/api/animations/clips/${id}${query}`,+ query: { id },+ headers: { origin: 'https://three.ws' },+ socket: { remoteAddress: '127.0.0.1' },+ };+ await handler(req, res);+ return res;+}++beforeEach(() => {+ db.rows = [row()];+ session.user = null;+ vi.clearAllMocks();+});++describe('clip id validation', () => {+ it('rejects a hex-but-not-uuid id with a 400 instead of a database 500', async () => {+ const res = await get('aaaaaaaa');+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('invalid_request');+ });++ it('rejects an empty id', async () => {+ const res = await get('');+ expect(res.statusCode).toBe(400);+ });++ it('accepts a well-formed uuid', async () => {+ const res = await get(CLIP_ID);+ expect(res.statusCode).toBe(200);+ });+});++describe('private clips', () => {+ it('404s for a non-owner rather than admitting the clip exists', async () => {+ db.rows = [row({ visibility: 'private' })];+ const res = await get(CLIP_ID);+ expect(res.statusCode).toBe(404);+ });++ it('serves the owner their own private clip with the editing source', async () => {+ db.rows = [row({ visibility: 'private' })];+ session.user = { id: OWNER };+ const { clip } = (await get(CLIP_ID)).json();+ expect(clip.clip).toEqual(bakedClip);+ expect(clip.editable).toBe(true);+ expect(clip.paywalled).toBe(false);+ });+});++describe('paid listings stay behind the x402 paywall', () => {+ const paid = { listed: true, price_amount: '2.500000000', price_currency: 'USDC' };++ it('withholds the baked tracks from a non-owner and points at the paid download', async () => {+ db.rows = [row(paid)];+ const { clip } = (await get(CLIP_ID)).json();+ expect(clip.clip).toBeNull();+ expect(clip.paywalled).toBe(true);+ expect(clip.download_url).toBe(`/api/x402/animation-download?id=${CLIP_ID}`);+ });++ it('still ships the metadata a listing card renders', async () => {+ db.rows = [row({ ...paid, thumbnail_key: 'anim-thumb/x.png' })];+ const { clip } = (await get(CLIP_ID)).json();+ expect(clip.name).toBe('Spin');+ expect(clip.duration_ms).toBe(1000);+ expect(clip.price).toEqual({ amount: '2.500000000', currency: 'USDC' });+ expect(clip.thumbnail_url).toBe('https://cdn.test/anim-thumb/x.png');+ });++ it('never pays the R2 round-trip for an offloaded clip it will not return', async () => {+ db.rows = [row({ ...paid, clip: null, storage_key: 'u/x/animations/big.json' })];+ const { clip } = (await get(CLIP_ID)).json();+ expect(clip.clip).toBeNull();+ expect(getObjectBuffer).not.toHaveBeenCalled();+ });++ it('does not count a play for a fetch that delivered no motion', async () => {+ db.rows = [row(paid)];+ const { sql } = await import('../../api/_lib/db.js');+ await get(CLIP_ID, '?play=1');+ await new Promise((r) => queueMicrotask(r));+ expect(sql).toHaveBeenCalledTimes(1);+ });++ it('lets the owner keep working on their own listed clip', async () => {+ db.rows = [row(paid)];+ session.user = { id: OWNER };+ const { clip } = (await get(CLIP_ID)).json();+ expect(clip.paywalled).toBe(false);+ expect(clip.clip).toEqual(bakedClip);+ });++ it('leaves a public clip free: publishing to the gallery is the creator giving it away', async () => {+ db.rows = [row({ ...paid, visibility: 'public' })];+ const { clip } = (await get(CLIP_ID)).json();+ expect(clip.paywalled).toBe(false);+ expect(clip.clip).toEqual(bakedClip);+ });++ it('leaves a free listing playable', async () => {+ db.rows = [row({ listed: true, price_amount: null })];+ const { clip } = (await get(CLIP_ID)).json();+ expect(clip.paywalled).toBe(false);+ expect(clip.clip).toEqual(bakedClip);+ });++ it('resolves an offloaded clip from R2 when it is not paywalled', async () => {+ db.rows = [row({ clip: null, storage_key: 'u/x/animations/big.json' })];+ const { clip } = (await get(CLIP_ID)).json();+ expect(clip.clip.name).toBe('offloaded');+ expect(getObjectBuffer).toHaveBeenCalledWith('u/x/animations/big.json');+ });+});++describe('editing source', () => {+ it('never leaves the owner: editor_doc is null for everyone else', async () => {+ db.rows = [row()];+ const { clip } = (await get(CLIP_ID)).json();+ expect(clip.editor_doc).toBeNull();+ expect(clip.editable).toBe(false);+ });+});diff --git a/tests/api/animations-presign.test.js b/tests/api/animations-presign.test.jsnew file mode 100644index 000000000..78028b073--- /dev/null+++ b/tests/api/animations-presign.test.js@@ -0,0 +1,145 @@+/**+ * POST /api/animations/presign tests.+ *+ * The presign is what decides where a creator's animation upload lands, and+ * api/animations/sell.js trusts that decision: it refuses any artifact_key+ * outside `u/<caller>/`. So the key this endpoint mints has to stay inside the+ * caller's own namespace no matter what the body asks for, and the request has+ * to be rejected outright when there is no caller.+ *+ * The auth, R2 and rate-limit boundaries are stubbed; the handler, its schema+ * and its key construction run for real.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const session = { user: null };+const bearer = { auth: null, scope: 'avatars:write' };+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => session.user),+ authenticateBearer: vi.fn(async () => bearer.auth),+ extractBearer: vi.fn(() => (bearer.auth ? 'token' : null)),+ hasScope: vi.fn((scope, required) => String(scope || '').split(/\s+/).includes(required)),+}));++const r2 = { calls: [] };+vi.mock('../../api/_lib/r2.js', () => ({+ presignUpload: vi.fn(async (args) => {+ r2.calls.push(args);+ return `https://r2.test/${args.key}?signed=1`;+ }),+}));++const rl = { ok: true };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { upload: vi.fn(async () => ({ success: rl.ok, reset: 0, limit: 10, remaining: 0 })) },+ clientIp: () => '127.0.0.1',+}));++const { default: handler } = await import('../../api/animations/presign.js');++const OWNER = '11111111-1111-4111-8111-111111111111';++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; };+ r.json = () => JSON.parse(r._b);+ return r;+}++async function post(body) {+ const res = makeRes();+ await handler(+ {+ method: 'POST',+ url: '/api/animations/presign',+ headers: { origin: 'https://three.ws', 'content-type': 'application/json' },+ body,+ socket: { remoteAddress: '127.0.0.1' },+ },+ res,+ );+ return res;+}++beforeEach(() => {+ session.user = { id: OWNER };+ bearer.auth = null;+ bearer.scope = 'avatars:write';+ r2.calls = [];+ rl.ok = true;+ vi.clearAllMocks();+});++describe('auth', () => {+ it('401s an anonymous caller', async () => {+ session.user = null;+ expect((await post({ size_bytes: 1024 })).statusCode).toBe(401);+ });++ it('401s a bearer token without avatars:write', async () => {+ session.user = null;+ bearer.auth = { userId: OWNER, scope: 'avatars:read' };+ expect((await post({ size_bytes: 1024 })).statusCode).toBe(401);+ });++ it('accepts a bearer token that carries the scope', async () => {+ session.user = null;+ bearer.auth = { userId: OWNER, scope: 'avatars:read avatars:write' };+ expect((await post({ size_bytes: 1024 })).statusCode).toBe(200);+ });++ it('429s when the upload rate limit is spent', async () => {+ rl.ok = false;+ expect((await post({ size_bytes: 1024 })).statusCode).toBe(429);+ });+});++describe('key scoping', () => {+ it('mints the key inside the caller own namespace, which sell.js then enforces', async () => {+ const { storage_key } = (await post({ size_bytes: 1024, slug: 'spin-kick' })).json();+ expect(storage_key.startsWith(`u/${OWNER}/animations/`)).toBe(true);+ expect(storage_key).toMatch(/^u\/[0-9a-f-]+\/animations\/spin-kick-\d+\.glb$/);+ expect(r2.calls[0].key).toBe(storage_key);+ });++ it('cannot be steered out of that namespace by a traversal slug', async () => {+ const res = await post({ size_bytes: 1024, slug: '../../other/evil' });+ expect(res.statusCode).toBe(400);+ expect(r2.calls).toHaveLength(0);+ });++ it('generates a slug when the caller supplies none', async () => {+ const { storage_key } = (await post({ size_bytes: 1024 })).json();+ expect(storage_key).toMatch(new RegExp(`^u/${OWNER}/animations/anim-[a-z0-9]{6}-\\d+\\.glb$`));+ });+});++describe('body validation', () => {+ it('rejects a non-positive or oversized size', async () => {+ expect((await post({ size_bytes: 0 })).statusCode).toBe(400);+ expect((await post({ size_bytes: -1 })).statusCode).toBe(400);+ expect((await post({ size_bytes: 200 * 1024 * 1024 })).statusCode).toBe(400);+ });++ it('rejects a content type that is not glTF', async () => {+ expect((await post({ size_bytes: 1024, content_type: 'image/png' })).statusCode).toBe(400);+ });++ it('rejects a malformed checksum and passes a well-formed one through to R2', async () => {+ expect((await post({ size_bytes: 1024, checksum_sha256: 'nope' })).statusCode).toBe(400);+ const sum = 'a'.repeat(64);+ await post({ size_bytes: 1024, checksum_sha256: sum });+ expect(r2.calls.at(-1).checksumSha256).toBe(sum);+ });++ it('answers with the upload contract the browser needs', async () => {+ const body = (await post({ size_bytes: 1024 })).json();+ expect(body.method).toBe('PUT');+ expect(body.headers['content-type']).toBe('model/gltf-binary');+ expect(body.expires_in).toBe(300);+ expect(body.upload_url).toContain(body.storage_key);+ });+});diff --git a/tests/api/animations-sell.test.js b/tests/api/animations-sell.test.jsindex e88e74669..ddcacf256 100644--- a/tests/api/animations-sell.test.js+++ b/tests/api/animations-sell.test.js@@ -1,7 +1,7 @@import { describe, it, expect } from 'vitest';import { __test__ } from '../../api/animations/sell.js';-const { listSchema, delistSchema, shape, resolvePayto } = __test__;+const { listSchema, delistSchema, shape, resolvePayto, resolveArtifactBytes } = __test__;const UUID = '11111111-2222-3333-4444-555555555555';const NS_KEY = `u/${UUID}/animations/spin-kick-12.glb`;@@ -82,3 +82,25 @@ describe('animations/sell resolvePayto', () => {expect(out).toEqual({ base: BASE_ADDR, solana: SOL_ADDR, bsc: BASE_ADDR });});});++describe('animations/sell resolveArtifactBytes', () => {+ const KEY = 'u/owner/animations/spin-1.glb';++ it('takes the size the caller measured', () => {+ expect(resolveArtifactBytes({ artifact_key: KEY, artifact_bytes: 4096 }, { artifact_key: KEY, artifact_bytes: 1024 })).toBe(4096);+ });++ it('keeps the stored size when a re-price re-sends the same key without one', () => {+ // Regression: a bare re-price blanked artifact_bytes, so the marketplace+ // card lost the download size a buyer decides on.+ expect(resolveArtifactBytes({ artifact_key: KEY }, { artifact_key: KEY, artifact_bytes: 1024 })).toBe(1024);+ });++ it('drops a stale size when the artifact itself changed', () => {+ expect(resolveArtifactBytes({ artifact_key: 'u/owner/animations/spin-2.glb' }, { artifact_key: KEY, artifact_bytes: 1024 })).toBeNull();+ });++ it('reports null when nothing has ever been measured', () => {+ expect(resolveArtifactBytes({ artifact_key: KEY }, { artifact_key: KEY, artifact_bytes: null })).toBeNull();+ });+});diff --git a/tests/api/animations-thumbnail.test.js b/tests/api/animations-thumbnail.test.jsnew file mode 100644index 000000000..2382e4192--- /dev/null+++ b/tests/api/animations-thumbnail.test.js@@ -0,0 +1,173 @@+/**+ * POST /api/animations/thumbnail tests.+ *+ * The poster upload is the one write that takes a raw image from the browser,+ * so every way the body can be wrong needs its own honest answer: a bad id used+ * to reach Postgres as an invalid uuid literal and come back as a 500 with a+ * support ref. Ownership is enforced here too, since the clip row is looked up+ * before the R2 write rather than joined into it.+ *+ * The db, auth, R2 and rate-limit boundaries are stubbed; the handler and its+ * http envelope run for real.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const db = { rows: [], calls: [] };+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings) => {+ db.calls.push(String(strings?.[0] || '').trim());+ return db.rows;+ }),+}));++const session = { user: null };+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => session.user),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+ hasScope: vi.fn(() => true),+}));++const r2 = { put: [], deleted: [] };+vi.mock('../../api/_lib/r2.js', () => ({+ putObject: vi.fn(async (args) => { r2.put.push(args); }),+ deleteObject: vi.fn(async (key) => { r2.deleted.push(key); }),+ publicUrl: vi.fn((key) => `https://cdn.test/${key}`),+}));++const rl = { ok: true };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { upload: vi.fn(async () => ({ success: rl.ok, reset: 0, limit: 10, remaining: 0 })) },+ clientIp: () => '127.0.0.1',+}));++const { default: handler } = await import('../../api/animations/thumbnail.js');++const OWNER = '11111111-1111-4111-8111-111111111111';+const OTHER = '33333333-3333-4333-8333-333333333333';+const CLIP_ID = '22222222-2222-4222-8222-222222222222';++// A real 1x1 PNG, so the magic-number check runs against genuine bytes.+const PNG_B64 =+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';++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; };+ r.json = () => JSON.parse(r._b);+ return r;+}++async function post(body) {+ const res = makeRes();+ await handler(+ {+ method: 'POST',+ url: '/api/animations/thumbnail',+ headers: { origin: 'https://three.ws', 'content-type': 'application/json' },+ body,+ socket: { remoteAddress: '127.0.0.1' },+ },+ res,+ );+ return res;+}++beforeEach(() => {+ db.rows = [{ id: CLIP_ID, owner_id: OWNER, thumbnail_key: null }];+ db.calls = [];+ session.user = { id: OWNER };+ r2.put = [];+ r2.deleted = [];+ rl.ok = true;+ vi.clearAllMocks();+});++describe('auth', () => {+ it('401s an anonymous caller', async () => {+ session.user = null;+ const res = await post({ id: CLIP_ID, png_base64: PNG_B64 });+ expect(res.statusCode).toBe(401);+ });++ it('403s a signed-in caller who does not own the clip', async () => {+ db.rows = [{ id: CLIP_ID, owner_id: OTHER, thumbnail_key: null }];+ const res = await post({ id: CLIP_ID, png_base64: PNG_B64 });+ expect(res.statusCode).toBe(403);+ expect(r2.put).toHaveLength(0);+ });+});++describe('body validation', () => {+ it('rejects a hex-but-not-uuid id with a 400 instead of a database 500', async () => {+ const res = await post({ id: 'aaaaaaaa', png_base64: PNG_B64 });+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('invalid_request');+ expect(db.calls).toHaveLength(0);+ });++ it('rejects a missing id and a missing image', async () => {+ expect((await post({ png_base64: PNG_B64 })).statusCode).toBe(400);+ expect((await post({ id: CLIP_ID })).statusCode).toBe(400);+ });++ it('rejects bytes that are not a PNG', async () => {+ const res = await post({ id: CLIP_ID, png_base64: Buffer.from('hello').toString('base64') });+ expect(res.statusCode).toBe(400);+ expect(res.json().error_description).toMatch(/not a PNG/);+ });++ it('accepts a poster the declared cap allows (the JSON envelope used to eat it first)', async () => {+ const ok = Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ Buffer.alloc(1_000_000),+ ]);+ const res = await post({ id: CLIP_ID, png_base64: ok.toString('base64') });+ expect(res.statusCode).toBe(200);+ });++ it('names the size when the image is over the cap, rather than blaming the id', async () => {+ const big = Buffer.concat([+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),+ Buffer.alloc(1_600_000),+ ]);+ const res = await post({ id: CLIP_ID, png_base64: big.toString('base64') });+ expect(res.statusCode).toBe(413);+ expect(res.json().error).toBe('too_large');+ });++ it('404s when the clip does not exist', async () => {+ db.rows = [];+ const res = await post({ id: CLIP_ID, png_base64: PNG_B64 });+ expect(res.statusCode).toBe(404);+ });++ it('429s when the upload rate limit is spent', async () => {+ rl.ok = false;+ const res = await post({ id: CLIP_ID, png_base64: PNG_B64 });+ expect(res.statusCode).toBe(429);+ });+});++describe('successful upload', () => {+ it('stores the poster under the clip id and returns its public url', async () => {+ const res = await post({ id: CLIP_ID, png_base64: `data:image/png;base64,${PNG_B64}` });+ expect(res.statusCode).toBe(200);+ expect(res.json().data).toMatchObject({+ id: CLIP_ID,+ thumbnail_key: `anim-thumb/${CLIP_ID}.png`,+ thumbnail_url: `https://cdn.test/anim-thumb/${CLIP_ID}.png`,+ });+ expect(r2.put[0].contentType).toBe('image/png');+ });++ it('sweeps a superseded poster object instead of orphaning it', async () => {+ db.rows = [{ id: CLIP_ID, owner_id: OWNER, thumbnail_key: 'anim-thumb/old.png' }];+ await post({ id: CLIP_ID, png_base64: PNG_B64 });+ await new Promise((r) => queueMicrotask(r));+ expect(r2.deleted).toEqual(['anim-thumb/old.png']);+ });+});diff --git a/tests/api/avatars-popular-searches.test.js b/tests/api/avatars-popular-searches.test.jsnew file mode 100644index 000000000..9512c9a6f--- /dev/null+++ b/tests/api/avatars-popular-searches.test.js@@ -0,0 +1,124 @@+// GET /api/avatars/popular-searches: the read side of the Avatar Search Index+// Warmup pipeline, powering the gallery's popular-search chips.+//+// Both branches matter and neither is obvious from the code: the warm branch+// must expose `top_results` ONLY when ?with_thumbnails=true (the slice is the+// heaviest part of the payload and the chips do not need it), and the cold+// branch must still answer 200 with usable queries so a gallery on a fresh+// database renders chips instead of an empty row.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Readable } from 'node:stream';++let rlOk = true;+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ publicIp: async () =>+ rlOk+ ? { success: true, limit: 240, remaining: 239, reset: Date.now() + 60_000 }+ : { success: false, limit: 240, remaining: 0, reset: Date.now() + 60_000 },+ },+ clientIp: () => '203.0.113.11',+}));++let warmed = [];+vi.mock('../../api/_lib/avatar-search-warm.js', () => ({+ getPopularSearches: async ({ limit, withThumbnails }) =>+ warmed.slice(0, limit).map((w) => ({ ...w, top_results: withThumbnails ? w.top_results : [] })),+}));++const WARM_ROW = {+ query: 'robot',+ result_count: 5,+ thumbnails: ['https://cdn.example/thumb/a.png'],+ sample_thumbnail: 'https://cdn.example/thumb/a.png',+ top_results: [{ id: 'a', name: 'Robot', slug: 'robot-a', thumbnail_url: 'https://cdn.example/thumb/a.png' }],+ warmed_at: '2026-08-10T10:00:00.000Z',+};++function makeReq({ method = 'GET', url = '/api/avatars/popular-searches' } = {}) {+ const stream = Readable.from([]);+ stream.method = method;+ stream.url = url;+ stream.headers = { host: 'three.ws' };+ 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; },+ };+}+const body = (res) => JSON.parse(res._body);++async function call(url, method = 'GET') {+ const mod = await import('../../api/avatars/popular-searches.js');+ const res = makeRes();+ await mod.default(makeReq({ url, method }), res);+ return res;+}++beforeEach(() => {+ rlOk = true;+ warmed = [];+});++describe('warm cache present', () => {+ beforeEach(() => { warmed = [WARM_ROW, { ...WARM_ROW, query: 'anime', result_count: 2 }]; });++ it('serves the warmed queries with their sample thumbnail', async () => {+ const res = await call('/api/avatars/popular-searches');+ expect(res.statusCode).toBe(200);+ const out = body(res);+ expect(out.source).toBe('warm_cache');+ expect(out.searches.map((s) => s.query)).toEqual(['robot', 'anime']);+ expect(out.searches[0].sample_thumbnail).toBe('https://cdn.example/thumb/a.png');+ expect(out.searches[0].result_count).toBe(5);+ });++ it('withholds the heavy top_results slice unless asked for it', async () => {+ expect(body(await call('/api/avatars/popular-searches')).searches[0]).not.toHaveProperty('top_results');+ const withThumbs = body(await call('/api/avatars/popular-searches?with_thumbnails=true'));+ expect(withThumbs.searches[0].top_results).toHaveLength(1);+ });++ it('honours ?limit and caches at the edge', async () => {+ const res = await call('/api/avatars/popular-searches?limit=1');+ expect(body(res).searches).toHaveLength(1);+ expect(res.getHeader('cache-control')).toMatch(/s-maxage=600/);+ });+});++describe('cold start and guards', () => {+ it('falls back to seed queries when nothing is warmed yet', async () => {+ const res = await call('/api/avatars/popular-searches');+ expect(res.statusCode).toBe(200);+ const out = body(res);+ expect(out.source).toBe('seed');+ expect(out.searches.length).toBeGreaterThan(0);+ // Seed rows are shaped like warm rows so the client needs no branch.+ for (const s of out.searches) {+ expect(typeof s.query).toBe('string');+ expect(s.result_count).toBeNull();+ expect(s.thumbnails).toEqual([]);+ }+ // Short TTL so warmed data takes over as soon as the pipeline lands it.+ expect(res.getHeader('cache-control')).toMatch(/max-age=30/);+ });++ it('rejects non-GET methods', async () => {+ const res = await call('/api/avatars/popular-searches', 'POST');+ expect(res.statusCode).toBe(405);+ });++ it('returns 429 when the per-IP bucket is exhausted', async () => {+ rlOk = false;+ const res = await call('/api/avatars/popular-searches');+ expect(res.statusCode).toBe(429);+ });+});diff --git a/tests/api/avatars-view.test.js b/tests/api/avatars-view.test.jsnew file mode 100644index 000000000..bb9de1b44--- /dev/null+++ b/tests/api/avatars-view.test.js@@ -0,0 +1,126 @@+// POST /api/avatars/view: the gallery view tracker.+//+// Two behaviours are worth pinning because both were wrong in production. An+// avatar_id that is not a uuid used to reach Postgres as `WHERE id = $1`, raise+// 22P02, and surface to the caller as a 500 for what is a plain typo. And the+// "one view per IP per avatar" the file documented was never implemented: the+// handler drew on the shared 240/min publicIp bucket, so a single reader could+// move view_count 240 times a minute.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Readable } from 'node:stream';++let floodOk = true;+let dedupeOk = true;+const dedupeKeys = [];+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ publicIp: async () => ({ success: floodOk, limit: 240, remaining: 239, reset: Date.now() + 60_000 }),+ avatarViewIp: async (key) => {+ dedupeKeys.push(key);+ return { success: dedupeOk, limit: 1, remaining: 0, reset: Date.now() + 1_800_000 };+ },+ },+ clientIp: () => '203.0.113.7',+}));++const queries = [];+vi.mock('../../api/_lib/db.js', () => ({+ sql: (strings, ...values) => {+ queries.push({ text: strings.join('?'), values });+ return Promise.resolve([]);+ },+}));++const AVATAR_ID = '6a3f1b0c-2b6e-4f1a-9d5b-8c7e2f0a1d34';++function makeReq(payload, method = 'POST') {+ const raw = typeof payload === 'string' ? payload : JSON.stringify(payload);+ const stream = Readable.from([Buffer.from(raw)]);+ stream.method = method;+ stream.url = '/api/avatars/view';+ stream.headers = { host: 'three.ws', 'content-type': 'application/json' };+ 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; },+ };+}+const body = (res) => JSON.parse(res._body);++async function call(payload, method = 'POST') {+ const mod = await import('../../api/avatars/view.js');+ const res = makeRes();+ await mod.default(makeReq(payload, method), res);+ return res;+}++beforeEach(() => {+ floodOk = true;+ dedupeOk = true;+ queries.length = 0;+ dedupeKeys.length = 0;+});++describe('counting a view', () => {+ it('increments the counter once and reports it counted', async () => {+ const res = await call({ avatar_id: AVATAR_ID });+ expect(res.statusCode).toBe(200);+ expect(body(res)).toEqual({ ok: true, counted: true });+ expect(queries).toHaveLength(1);+ expect(queries[0].text).toMatch(/UPDATE avatars/);+ expect(queries[0].values).toContain(AVATAR_ID);+ });++ it('scopes the dedupe bucket to the viewer AND the avatar', async () => {+ await call({ avatar_id: AVATAR_ID });+ expect(dedupeKeys).toEqual([`203.0.113.7:${AVATAR_ID}`]);+ });++ it('skips the write on a repeat view inside the window, without erroring', async () => {+ dedupeOk = false;+ const res = await call({ avatar_id: AVATAR_ID });+ expect(res.statusCode).toBe(200);+ expect(body(res)).toEqual({ ok: true, counted: false });+ expect(queries).toHaveLength(0);+ });+});++describe('input guards', () => {+ it.each([+ ['a slug instead of an id', { avatar_id: 'not-a-uuid' }],+ ['an empty body', {}],+ ['a non-string id', { avatar_id: 12345 }],+ ])('rejects %s with 400 and never touches the database', async (_label, payload) => {+ const res = await call(payload);+ expect(res.statusCode).toBe(400);+ expect(body(res).error).toBe('invalid_request');+ expect(queries).toHaveLength(0);+ });++ it('rejects malformed JSON with 400, not a 500', async () => {+ const res = await call('not json');+ expect(res.statusCode).toBe(400);+ expect(queries).toHaveLength(0);+ });++ it('rejects non-POST methods', async () => {+ const res = await call({ avatar_id: AVATAR_ID }, 'GET');+ expect(res.statusCode).toBe(405);+ });++ it('sheds load with a soft 200 when the per-IP flood guard trips', async () => {+ floodOk = false;+ const res = await call({ avatar_id: AVATAR_ID });+ expect(res.statusCode).toBe(200);+ expect(body(res)).toEqual({ ok: false, reason: 'rate_limited' });+ expect(queries).toHaveLength(0);+ });+});diff --git a/tests/vercel-avatars-subpath-routes.test.js b/tests/vercel-avatars-subpath-routes.test.jsnew file mode 100644index 000000000..945d72e2e--- /dev/null+++ b/tests/vercel-avatars-subpath-routes.test.js@@ -0,0 +1,70 @@+/**+ * Route-shadowing guard for `/api/avatars/*`, the sibling of+ * vercel-agents-subpath-routes.test.js.+ *+ * `routes` is ordered and the first terminal match wins, so a handler can exist,+ * be correct, and still never run: `/api/avatars/([^/]+)` → `/api/avatars/[id]`+ * sits pre-filesystem and swallows every single-segment path under+ * /api/avatars/, the filesystem phase included. A shadowed handler does not 404+ * in a way anyone notices either, because the dispatcher answers with its own+ * `{"error":"not_found","error_description":"avatar not found"}`.+ *+ * `api/avatars/popular-searches.js` was dead in production exactly this way. It+ * is the read side of the Avatar Search Index Warmup pipeline, which pays per+ * call to warm `avatar_search_warm_cache`, so the shadowing burned real money+ * producing data no request could reach.+ *+ * The handler list is derived from disk, never hand-written: a hand-list only+ * covers the outage someone already found, and the point is to catch the NEXT+ * handler that lands in this directory without a route above the catch-all.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync, readdirSync } from 'node:fs';++const routes = JSON.parse(readFileSync(new URL('../vercel.json', import.meta.url), 'utf8')).routes;+const fsPhase = routes.findIndex((r) => r.handle === 'filesystem');++/** First terminal pre-filesystem match, resolved the way the server resolves it. */+function resolve(path) {+ for (const route of routes.slice(0, fsPhase)) {+ if (typeof route.src !== 'string') continue;+ let m;+ try {+ m = new RegExp(`^(?:${route.src})$`).exec(path);+ } catch {+ continue;+ }+ if (!m || route.continue) continue;+ return String(route.dest || '').replace(/\$(\d)/g, (_, d) => m[Number(d)] ?? '');+ }+ return null;+}++// Literal-named handlers directly under api/avatars/. `_`-prefixed files are+// shared library modules (never routable) and `[`-prefixed ones are the dynamic+// dispatchers doing the shadowing.+const handlers = readdirSync(new URL('../api/avatars', import.meta.url))+ .filter((f) => f.endsWith('.js') && !f.startsWith('_') && !f.startsWith('['))+ .map((f) => f.replace(/\.js$/, ''))+ // index.js is reached through `/api/avatars/?`, not by its filename.+ .filter((f) => f !== 'index');++describe('/api/avatars/* literal handlers are reachable', () => {+ it('finds the handlers on disk', () => {+ expect(handlers.length).toBeGreaterThan(5);+ expect(handlers).toContain('popular-searches');+ });++ it.each(handlers)('GET /api/avatars/%s reaches its own handler, not the [id] dispatcher', (name) => {+ expect(resolve(`/api/avatars/${name}`)).toBe(`/api/avatars/${name}`);+ });++ it('still routes a real avatar id to the [id] dispatcher', () => {+ expect(resolve('/api/avatars/6a3f1b0c-2b6e-4f1a-9d5b-8c7e2f0a1d34')).toBe('/api/avatars/[id]');+ });++ it('routes the index listing to api/avatars/index.js', () => {+ expect(resolve('/api/avatars/')).toBe('/api/avatars/index');+ });+});