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.

fix(memory): 400 a non-uuid agentId instead of letting Postgres 500 the graph

nirholas9419cc5741ed
diff --git a/api/memory/graph.js b/api/memory/graph.js
index 1a9c37731..cf03458df 100644
--- a/api/memory/graph.js
+++ b/api/memory/graph.js
@@ -15,6 +15,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { sql } from '../_lib/db.js';
import { cors, json, method, wrap, error } from '../_lib/http.js';
import { buildGraph, memoriesForEntity } from '../_lib/memory-store.js';
+import { isUuid } from '../_lib/validate.js';
async function resolveAuth(req) {
const session = await getSessionUser(req);
@@ -24,6 +25,8 @@ async function resolveAuth(req) {
return null;
}
+const EMPTY_GRAPH = { nodes: [], edges: [], stats: { entities: 0, edges: 0 } };
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET'])) return;
@@ -32,16 +35,18 @@ export default wrap(async (req, res) => {
const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
const entityId = url.searchParams.get('entityId');
if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+ // Both ids address uuid columns: reject unparseable input here rather than
+ // letting Postgres raise 22P02 and turn a caller mistake into a 500.
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');
+ if (entityId && !isUuid(entityId)) return error(res, 400, 'validation_error', 'entityId must be a uuid');
const auth = await resolveAuth(req);
- if (!auth) return json(res, 200, { nodes: [], edges: [], stats: { entities: 0, edges: 0 } });
+ if (!auth) return json(res, 200, EMPTY_GRAPH);
const [row] = await sql`
SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
`;
- if (!row || row.user_id !== auth.userId) {
- return json(res, 200, { nodes: [], edges: [], stats: { entities: 0, edges: 0 } });
- }
+ if (!row || row.user_id !== auth.userId) return json(res, 200, EMPTY_GRAPH);
if (entityId) {
const memories = await memoriesForEntity(agentId, entityId);
diff --git a/data/pages.json b/data/pages.json
index 17971e429..3e1e79b1b 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -2422,6 +2422,38 @@
"changefreq": "monthly",
"added": "2026-08-12"
},
+ {
+ "path": "/docs/agent-tokens",
+ "title": "Docs · Agent tokens",
+ "description": "Turn an agent into an economic object: a Solana coin whose identity belongs to the agent rather than to whoever filled in the launch form. Covers configuring a coin before it exists, rehearsing the launch for free, and the single command that launches it for real.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-08-11"
+ },
+ {
+ "path": "/docs/analytics-retention",
+ "title": "Docs · Week-2 retention on minted agents",
+ "description": "How three.ws measures the one number that gates phase 2 of the roadmap: whether users come back to converse with the agent they minted. Defines the cohort, the return event, and the query behind the reported figure.",
+ "priority": 0.5,
+ "changefreq": "monthly",
+ "added": "2026-08-11"
+ },
+ {
+ "path": "/docs/github-memory-seeding",
+ "title": "Docs · GitHub memory seeding",
+ "description": "Give an agent your work: your public GitHub profile plus the repositories and READMEs you pick, distilled into long-term memory so the agent speaks concretely about what you build instead of guessing. Consent is explicit and revoking it deletes every memory the grant produced.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-08-12"
+ },
+ {
+ "path": "/docs/reputation-staking-market",
+ "title": "Docs · Reputation Staking Market",
+ "description": "Stake conviction on an agent and earn from its attested action history. Principal sits in a market escrow, yield is derived per epoch from the agent's signed on-chain attestations, and positions build on the existing threews.stake.v1 conviction signal.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-08-12"
+ },
{
"path": "/docs/ibm-community",
"title": "Docs · IBM Community post catalog",
diff --git a/tests/api/mcp-bazaar-challenge.test.js b/tests/api/mcp-bazaar-challenge.test.js
new file mode 100644
index 000000000..ffb302780
--- /dev/null
+++ b/tests/api/mcp-bazaar-challenge.test.js
@@ -0,0 +1,170 @@
+/**
+ * The x402 Bazaar MCP endpoint (api/mcp-bazaar.js) must issue its OWN
+ * auth/payment challenge: resource URL /api/mcp-bazaar, a discovery-server
+ * description, and a bazaar example that calls search_services. Before
+ * BAZAAR_CHALLENGE existed it passed neither resourcePath nor challenge to
+ * authenticateRequest, so every 402 and 401 it issued advertised
+ * https://three.ws/api/mcp and the main server's avatar/validation envelope.
+ * Verified against production on 2026-08-13: the live 402 named /api/mcp on
+ * all five accepts.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// Env the real 402 challenge builder reads. Set before importing the handler.
+process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
+process.env.X402_PAY_TO_BASE ||= '0x0000000000000000000000000000000000000001';
+process.env.X402_ASSET_ADDRESS_BASE ||= '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+
+// Bearer path is out of scope: no token is ever presented in these tests.
+vi.mock('../../api/_lib/auth.js', () => ({
+ extractBearer: () => null,
+ authenticateBearer: vi.fn(async () => null),
+ hasScope: () => true,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ mcpIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ mcpUser: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ mcpBazaar: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ },
+ clientIp: vi.fn(() => '203.0.113.11'),
+}));
+
+vi.mock('../../api/_lib/usage.js', () => ({
+ recordEvent: vi.fn(),
+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),
+}));
+
+const { default: handler } = await import('../../api/mcp-bazaar.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(name, value) {
+ this.headers[String(name).toLowerCase()] = value;
+ },
+ end(body) {
+ this.body = body ?? null;
+ },
+ };
+}
+
+function makeReq({ method = 'POST', headers = {}, body = null } = {}) {
+ const payload = body == null ? '' : JSON.stringify(body);
+ const req = Readable.from(payload ? [Buffer.from(payload, 'utf8')] : []);
+ req.method = method;
+ req.url = '/api/mcp-bazaar';
+ req.headers = {
+ 'content-type': 'application/json',
+ 'x-forwarded-for': '203.0.113.11',
+ ...headers,
+ };
+ return req;
+}
+
+const TOOLS_LIST = { jsonrpc: '2.0', id: 1, method: 'tools/list' };
+const searchCall = {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'search_services', arguments: { query: 'weather' } },
+};
+
+describe('POST /api/mcp-bazaar — unauthenticated challenge identity', () => {
+ it('plain x402 clients get a 402 naming the bazaar resource', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: searchCall }), res);
+ expect(res.statusCode).toBe(402);
+ const challenge = JSON.parse(res.body);
+ expect(challenge.resource.url).toBe('https://three.ws/api/mcp-bazaar');
+ expect(challenge.resource.description).toContain('search_services');
+ expect(challenge.resource.serviceName).toBe('three.ws x402 Bazaar MCP');
+ expect(challenge.resource.tags).toContain('discovery');
+ for (const accept of challenge.accepts) {
+ expect(accept.resource).toBe('https://three.ws/api/mcp-bazaar');
+ }
+ });
+
+ it('bazaar discovery example calls search_services, not a main-server tool', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: searchCall }), res);
+ const { extensions } = JSON.parse(res.body);
+ expect(extensions.bazaar.discoverable).toBe(true);
+ expect(extensions.bazaar.info.input.body.params.name).toBe('search_services');
+ expect(extensions.bazaar.info.output.example.result.structuredContent.count).toBe(1);
+ });
+
+ it('MCP protocol clients get a 401 with the same bazaar envelope', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({ body: searchCall, headers: { accept: 'application/json, text/event-stream' } }),
+ res,
+ );
+ expect(res.statusCode).toBe(401);
+ expect(res.headers['www-authenticate']).toContain('oauth-protected-resource');
+ const challenge = JSON.parse(res.body);
+ expect(challenge.resource.url).toBe('https://three.ws/api/mcp-bazaar');
+ expect(challenge.resource.serviceName).toBe('three.ws x402 Bazaar MCP');
+ });
+
+ it('GET (SSE probe) advertises the bazaar resource as well', async () => {
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', body: null }), res);
+ expect(res.statusCode).toBe(402);
+ const challenge = JSON.parse(res.body);
+ expect(challenge.resource.url).toBe('https://three.ws/api/mcp-bazaar');
+ expect(challenge.resource.description).toContain('x402 Bazaar');
+ });
+});
+
+describe('POST /api/mcp-bazaar — free discovery for plain clients', () => {
+ it('initialize with no credentials advertises the bazaar server', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({
+ body: { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } },
+ }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ expect(JSON.parse(res.body).result.serverInfo.name).toBe('three-ws-x402-bazaar');
+ });
+
+ it('tools/list with no credentials returns the discovery toolset', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: TOOLS_LIST }), res);
+ expect(res.statusCode).toBe(200);
+ const names = JSON.parse(res.body).result.tools.map((t) => t.name);
+ expect(names).toEqual([
+ 'getting_started',
+ 'search_services',
+ 'browse_services',
+ 'get_service',
+ 'bazaar_service_details',
+ ]);
+ });
+
+ it('the free public getting_started tool is served with no credentials', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({
+ body: { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'getting_started', arguments: {} } },
+ }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ const out = JSON.parse(res.body);
+ expect(out.error).toBeUndefined();
+ expect(out.result.structuredContent.server).toBe('three.ws x402 Bazaar');
+ });
+
+ it('a batch mixing discovery with a priced call is NOT free', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: [TOOLS_LIST, searchCall] }), res);
+ expect(res.statusCode).toBe(402);
+ });
+});
diff --git a/tests/marketplace-trial-status.test.js b/tests/marketplace-trial-status.test.js
new file mode 100644
index 000000000..3870f2182
--- /dev/null
+++ b/tests/marketplace-trial-status.test.js
@@ -0,0 +1,251 @@
+// GET /api/marketplace/trial-status is the marketplace's conversion surface, and
+// the number a seller acts on is the money sitting in the trial queue. That
+// number used to be summed across every mint at once and then labelled with
+// whichever mint happened to head the queue, so a seller pricing one skill in
+// USDC and another in an 8-decimal token read a headline that was wrong by
+// orders of magnitude. These tests pin the per-mint totals, the trial lifecycle
+// states the buyer view renders against, the atomic formatter (token amounts
+// overflow a JS number, so they never go through Number()), and the auth wall.
+
+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();
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: (...a) => authenticateBearerMock(...a),
+ extractBearer: (req) => {
+ const h = req?.headers?.authorization || '';
+ return h.startsWith('Bearer ') ? h.slice(7) : null;
+ },
+}));
+
+const rlOk = { value: true };
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { authedReadIp: vi.fn(async () => ({ success: rlOk.value, reset: 1_000 })) },
+ clientIp: () => '203.0.113.9',
+}));
+
+const mod = await import('../api/marketplace/trial-status.js');
+const { trialState, formatAtomic, potentialsByMint, buyerView, sellerView, default: handler } = mod;
+
+const USER = '11111111-1111-4111-8111-111111111111';
+const AGENT = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+function mkReq({ url = '/api/marketplace/trial-status', headers = {}, method = 'GET' } = {}) {
+ return { method, url, headers };
+}
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+const parseBody = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+let sqlQueue = [];
+beforeEach(() => {
+ sqlQueue = [];
+ sqlMock.mockReset();
+ sqlMock.mockImplementation(async () => (sqlQueue.length ? sqlQueue.shift() : []));
+ getSessionUserMock.mockReset().mockResolvedValue(null);
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+ rlOk.value = true;
+});
+
+describe('trialState', () => {
+ it('calls a spent trial exhausted, the highest-intent state in the funnel', () => {
+ expect(trialState(0, 5)).toBe('exhausted');
+ expect(trialState(null, 5)).toBe('exhausted');
+ });
+
+ it('warns at or below a third of the grant, and on the final run of any grant', () => {
+ expect(trialState(1, 3)).toBe('running-low');
+ expect(trialState(2, 6)).toBe('running-low');
+ expect(trialState(1, 100)).toBe('running-low');
+ expect(trialState(1, null)).toBe('running-low');
+ });
+
+ it('leaves a barely-used trial fresh', () => {
+ expect(trialState(5, 5)).toBe('fresh');
+ expect(trialState(3, 6)).toBe('fresh');
+ });
+});
+
+describe('formatAtomic', () => {
+ it('formats atomic token amounts without going through Number()', () => {
+ expect(formatAtomic('1500000', 6)).toBe('1.5');
+ expect(formatAtomic('1000000', 6)).toBe('1');
+ expect(formatAtomic('1234567890123', 6)).toBe('1,234,567.890123');
+ expect(formatAtomic('0', 6)).toBe('0');
+ });
+
+ it('survives amounts past 2^53, where a float would silently round', () => {
+ const huge = '90071992547409910000';
+ expect(formatAtomic(huge, 6)).toBe('90,071,992,547,409.91');
+ });
+
+ it('groups thousands for a zero-decimal mint too', () => {
+ expect(formatAtomic('1234567', 0)).toBe('1,234,567');
+ });
+
+ it('clamps a nonsense decimals argument instead of throwing', () => {
+ expect(formatAtomic('1000000', 'x')).toBe('1');
+ expect(formatAtomic('1000000', -4)).toBe('1,000,000');
+ });
+});
+
+describe('potentialsByMint', () => {
+ it('totals each mint separately and leads with the largest', () => {
+ const out = potentialsByMint([
+ { price: { mint: USDC, decimals: 6 }, potential: { atomic: '2000000' } },
+ { price: { mint: USDC, decimals: 6 }, potential: { atomic: '3000000' } },
+ { price: { mint: THREE, decimals: 9 }, potential: { atomic: '900000000' } },
+ ]);
+ expect(out).toHaveLength(2);
+ expect(out[0]).toMatchObject({ mint: USDC, decimals: 6, atomic: '5000000', display: '5' });
+ expect(out[1]).toMatchObject({ mint: THREE, decimals: 9, atomic: '900000000', display: '0.9' });
+ });
+
+ it('skips unpriced rows rather than counting them as zero-decimal dust', () => {
+ expect(potentialsByMint([{ price: null, potential: null }])).toEqual([]);
+ });
+});
+
+describe('sellerView', () => {
+ it('reports one total per mint and never blends two currencies into one number', async () => {
+ sqlQueue = [
+ [
+ {
+ agent_id: AGENT, skill: 'icon-set', agent_name: 'Ink', profile_image_url: null,
+ agent_image: null, active_trials: 4, exhausted: 2, last_run: 1,
+ last_activity: '2026-08-01T00:00:00.000Z',
+ trial_uses: 3, amount: '2000000', currency_mint: USDC, chain: 'solana', mint_decimals: 6,
+ },
+ {
+ agent_id: AGENT, skill: 'lore', agent_name: 'Ink', profile_image_url: null,
+ agent_image: null, active_trials: 1, exhausted: 1, last_run: 0,
+ last_activity: '2026-08-02T00:00:00.000Z',
+ trial_uses: 2, amount: '500000000', currency_mint: THREE, chain: 'solana', mint_decimals: 9,
+ },
+ ],
+ [{ agent_id: AGENT, skill: 'icon-set', sold: 2 }],
+ ];
+
+ const out = await sellerView(USER);
+
+ expect(out.role).toBe('seller');
+ expect(out.summary.warmLeads).toBe(3);
+ expect(out.summary.sold).toBe(2);
+ // USDC: 2 exhausted x 2 USDC. $THREE: 1 exhausted x 0.5.
+ expect(out.summary.potentials).toEqual([
+ { mint: USDC, decimals: 6, atomic: '4000000', display: '4' },
+ { mint: THREE, decimals: 9, atomic: '500000000', display: '0.5' },
+ ]);
+ expect(out.summary.potential).toMatchObject({ mint: USDC, atomic: '4000000', display: '4' });
+ expect(out.queue[0]).toMatchObject({ skill: 'icon-set', sold: 2, exhausted: 2 });
+ expect(out.queue[0].conversionRate).toBeCloseTo(2 / 6, 10);
+ expect(out.queue[1].sold).toBe(0);
+ });
+
+ it('answers an empty queue with a zeroed headline rather than an undefined read', async () => {
+ sqlQueue = [[], []];
+ const out = await sellerView(USER);
+ expect(out.queue).toEqual([]);
+ expect(out.summary.potential).toEqual({ atomic: '0', decimals: 6, display: '0', mint: null });
+ expect(out.summary.potentials).toEqual([]);
+ });
+});
+
+describe('buyerView', () => {
+ it('returns each trial with its state, price and agent link', async () => {
+ sqlQueue = [[
+ {
+ id: 'p1', agent_id: AGENT, skill: 'icon-set', trial_remaining: 0,
+ created_at: '2026-08-01T00:00:00.000Z', updated_at: '2026-08-03T00:00:00.000Z',
+ agent_name: 'Ink', agent_image: null,
+ trial_uses: 3, amount: '2000000', currency_mint: USDC, chain: 'solana', mint_decimals: 6,
+ },
+ {
+ id: 'p2', agent_id: AGENT, skill: 'lore', trial_remaining: 3,
+ created_at: '2026-08-01T00:00:00.000Z', updated_at: '2026-08-02T00:00:00.000Z',
+ agent_name: 'Ink', agent_image: null,
+ trial_uses: 3, amount: null, currency_mint: null, chain: null, mint_decimals: null,
+ },
+ ]];
+
+ const out = await buyerView(USER);
+
+ expect(out.role).toBe('buyer');
+ expect(out.summary).toEqual({ active: 2, fresh: 1, runningLow: 0, exhausted: 1 });
+ expect(out.trials[0]).toMatchObject({
+ purchaseId: 'p1', skill: 'icon-set', state: 'exhausted', agentUrl: `/agent/${AGENT}`,
+ });
+ expect(out.trials[0].price).toEqual({
+ atomic: '2000000', decimals: 6, display: '2', mint: USDC, chain: 'solana',
+ });
+ // A delisted skill still shows its trial, just without a price to convert at.
+ expect(out.trials[1].price).toBeNull();
+ });
+});
+
+describe('GET /api/marketplace/trial-status', () => {
+ it('refuses an anonymous caller', async () => {
+ const res = mkRes();
+ await handler(mkReq(), res);
+ expect(res.statusCode).toBe(401);
+ expect(parseBody(res).error).toBe('unauthorized');
+ });
+
+ it('rejects a role the two fixed queries do not cover', async () => {
+ getSessionUserMock.mockResolvedValue({ id: USER });
+ const res = mkRes();
+ await handler(mkReq({ url: '/api/marketplace/trial-status?role=everyone' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(parseBody(res).error).toBe('validation_error');
+ });
+
+ it('rejects a write method', async () => {
+ const res = mkRes();
+ await handler(mkReq({ method: 'POST' }), res);
+ expect(res.statusCode).toBe(405);
+ });
+
+ it('serves the buyer view to a session caller and forbids caching it', async () => {
+ getSessionUserMock.mockResolvedValue({ id: USER });
+ sqlQueue = [[]];
+ const res = mkRes();
+ await handler(mkReq(), res);
+ expect(res.statusCode).toBe(200);
+ expect(parseBody(res).data.role).toBe('buyer');
+ expect(res.headers['cache-control']).toBe('private, no-store');
+ });
+
+ it('serves the seller view to a bearer caller', async () => {
+ authenticateBearerMock.mockResolvedValue({ userId: USER });
+ sqlQueue = [[], []];
+ const res = mkRes();
+ await handler(mkReq({ url: '/api/marketplace/trial-status?role=seller', headers: { authorization: 'Bearer k' } }), res);
+ expect(res.statusCode).toBe(200);
+ expect(parseBody(res).data.role).toBe('seller');
+ });
+
+ it('answers a throttled caller with 429, not a query', async () => {
+ getSessionUserMock.mockResolvedValue({ id: USER });
+ rlOk.value = false;
+ const res = mkRes();
+ await handler(mkReq(), res);
+ expect(res.statusCode).toBe(429);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/objects-library-endpoint.test.js b/tests/objects-library-endpoint.test.js
new file mode 100644
index 000000000..a7b02a14a
--- /dev/null
+++ b/tests/objects-library-endpoint.test.js
@@ -0,0 +1,181 @@
+/**
+ * GET /api/objects/library — CC0 prop manifest proxy.
+ *
+ * The endpoint proxies the R2-hosted object manifest (published by
+ * scripts/build-object-library.mjs). Contract under test:
+ * - pre-launch (manifest object missing) → 200 { objects: [], total: 0 },
+ * never an error, so /objects and the AR Studio Objects tray feature-detect
+ * by emptiness;
+ * - a real storage outage also degrades to empty, but with no-store so the
+ * edge cache cannot pin "no objects" for the next 300s;
+ * - published manifest ({ objects: [...] } shape) → passed through with total
+ * derived server-side; bare-array manifests (legacy shape) also accepted;
+ * - opt-in pagination via ?limit / ?offset, with a malformed cursor rejected
+ * as 400 JSON rather than silently coerced into a page nobody asked for;
+ * - non-GET → 405.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+
+const getObjectBuffer = vi.fn();
+vi.mock('../api/_lib/r2.js', () => ({ getObjectBuffer: (...a) => getObjectBuffer(...a) }));
+
+const { default: handler } = await import('../api/objects/library.js');
+
+function fakeReq(method = 'GET', url = '/api/objects/library') {
+ return { method, url, headers: {} };
+}
+
+function fakeRes() {
+ const headers = {};
+ return {
+ statusCode: 0,
+ body: undefined,
+ ended: false,
+ setHeader(k, v) { headers[String(k).toLowerCase()] = v; },
+ getHeader(k) { return headers[String(k).toLowerCase()]; },
+ end(b) { this.body = b; this.ended = true; },
+ _headers: headers,
+ };
+}
+
+async function get(query = '') {
+ const res = fakeRes();
+ await handler(fakeReq('GET', `/api/objects/library${query}`), res);
+ return { res, body: JSON.parse(res.body) };
+}
+
+const OBJECT = {
+ name: 'adjustable_wrench',
+ label: 'Adjustable Wrench',
+ url: 'https://cdn.example/objects/polyhaven/glb/adjustable_wrench.glb',
+ thumb: 'https://cdn.example/objects/polyhaven/thumbs/adjustable_wrench.png',
+ bytes: 2639744,
+ categories: ['props', 'tools'],
+ tags: ['vintage', 'hand tool'],
+ license: 'CC0',
+ source: 'polyhaven',
+};
+
+// No beforeEach reset: every test installs its own mockResolvedValue/
+// mockRejectedValue, which fully replaces the previous implementation.
+describe('GET /api/objects/library', () => {
+ it('returns an empty library when the manifest has not been uploaded yet', async () => {
+ const missing = Object.assign(new Error('no such key'), { name: 'NoSuchKey' });
+ getObjectBuffer.mockRejectedValue(missing);
+ const { res, body } = await get();
+ expect(res.statusCode).toBe(200);
+ expect(body).toEqual({ objects: [], total: 0, generated_at: null });
+ // A library that simply has not launched yet is a steady state, so it keeps
+ // the normal edge cache.
+ expect(res.getHeader('cache-control')).toContain('s-maxage=300');
+ });
+
+ it('degrades to an empty library on storage errors without caching the emptiness', async () => {
+ getObjectBuffer.mockRejectedValue(new Error('socket hang up'));
+ const { res, body } = await get();
+ expect(res.statusCode).toBe(200);
+ expect(body.objects).toEqual([]);
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ });
+
+ it('passes through a published { objects } manifest and derives total', async () => {
+ getObjectBuffer.mockResolvedValue(Buffer.from(JSON.stringify({
+ generated_at: '2026-07-21T13:16:14.305Z',
+ total: 1,
+ objects: [OBJECT],
+ })));
+ const { res, body } = await get();
+ expect(res.statusCode).toBe(200);
+ expect(body.objects).toEqual([OBJECT]);
+ expect(body.total).toBe(1);
+ expect(body.generated_at).toBe('2026-07-21T13:16:14.305Z');
+ expect(res.getHeader('cache-control')).toContain('s-maxage=300');
+ });
+
+ it('accepts a bare-array manifest shape', async () => {
+ getObjectBuffer.mockResolvedValue(Buffer.from(JSON.stringify([OBJECT])));
+ const { body } = await get();
+ expect(body.objects).toEqual([OBJECT]);
+ });
+
+ it('rejects non-GET methods', async () => {
+ getObjectBuffer.mockResolvedValue(Buffer.from('[]'));
+ const res = fakeRes();
+ await handler(fakeReq('POST'), res);
+ expect(res.statusCode).toBe(405);
+ });
+
+ // ── Bounded pagination (opt-in via ?limit) ──────────────────────────────
+ const OBJECTS = Array.from({ length: 5 }, (_, i) => ({ ...OBJECT, name: `prop-${i}` }));
+ const publish = () => getObjectBuffer.mockResolvedValue(Buffer.from(JSON.stringify({ objects: OBJECTS })));
+
+ it('pages a large manifest with ?limit and exposes next_offset', async () => {
+ publish();
+ const { body } = await get('?limit=2');
+ expect(body.total).toBe(5); // full catalog size, not the page size
+ expect(body.objects.map((o) => o.name)).toEqual(['prop-0', 'prop-1']);
+ expect(body.offset).toBe(0);
+ expect(body.next_offset).toBe(2);
+ });
+
+ it('honors ?offset and returns next_offset=null on the final page', async () => {
+ publish();
+ const { body } = await get('?limit=2&offset=4');
+ expect(body.objects.map((o) => o.name)).toEqual(['prop-4']);
+ expect(body.offset).toBe(4);
+ expect(body.next_offset).toBe(null);
+ });
+
+ it('returns an empty page (not an error) when offset runs past the end', async () => {
+ publish();
+ const { body } = await get('?limit=2&offset=99');
+ expect(body.objects).toEqual([]);
+ expect(body.total).toBe(5);
+ expect(body.next_offset).toBe(null);
+ });
+
+ it('clamps an oversized limit to the documented maximum instead of failing', async () => {
+ publish();
+ const { res, body } = await get('?limit=99999');
+ expect(res.statusCode).toBe(200);
+ expect(body.objects).toHaveLength(5);
+ expect(body.next_offset).toBe(null);
+ });
+
+ it('omits pagination fields entirely when ?limit is absent (legacy contract)', async () => {
+ publish();
+ const { body } = await get();
+ expect(body).toEqual({ objects: OBJECTS, total: 5, generated_at: null });
+ expect('next_offset' in body).toBe(false);
+ });
+
+ // ── Malformed cursors are the caller's bug, not a silently coerced page ──
+ for (const bad of ['abc', '', '0', '-5', '2.7', '1e3', 'NaN']) {
+ it(`rejects ?limit=${JSON.stringify(bad)} with a 400 JSON error`, async () => {
+ publish();
+ const { res, body } = await get(`?limit=${encodeURIComponent(bad)}`);
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('invalid_limit');
+ expect(body.error_description).toContain('1 to 1000');
+ expect(res.getHeader('cache-control')).toBe('no-store');
+ });
+ }
+
+ for (const bad of ['abc', '-3', '1.5', '']) {
+ it(`rejects ?offset=${JSON.stringify(bad)} with a 400 JSON error`, async () => {
+ publish();
+ const { res, body } = await get(`?limit=2&offset=${encodeURIComponent(bad)}`);
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('invalid_offset');
+ });
+ }
+
+ it('rejects ?offset without ?limit rather than ignoring it', async () => {
+ publish();
+ const { res, body } = await get('?offset=2');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('invalid_offset');
+ expect(body.error_description).toContain('limit');
+ });
+});