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
fix(objects): tighten the library endpoint's input handling and cover it with tests
nirholas3405d8258a47
diff --git a/api/objects/library.js b/api/objects/library.jsindex ad66b4713..260a97162 100644--- a/api/objects/library.js+++ b/api/objects/library.js@@ -1,4 +1,4 @@-// GET /api/objects/library — the CC0 3D object/prop library.+// GET /api/objects/library: the CC0 3D object/prop library.//// Free, commercial-OK 3D props (Poly Haven and other CC0 sources) staged as// web GLB on the R2 CDN. Mirrors api/avatars/library.js exactly: the GLBs are@@ -38,18 +38,50 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;+ // Cursors are validated BEFORE the manifest fetch. A request that is going to+ // 400 must not cost an R2 round trip first: the answer cannot change based on+ // what storage returns, so paying for the read is pure latency and pure spend.+ const url = new URL(req.url, 'http://x');+ const rawLimit = url.searchParams.get('limit');+ const rawOffset = url.searchParams.get('offset');+ let limit = null;+ let offset = 0;+ if (rawLimit == null) {+ if (rawOffset != null) {+ return error(res, 400, 'invalid_offset', 'offset is only meaningful with limit; pass ?limit=N too');+ }+ } else {+ const parsedLimit = parseCursor(rawLimit);+ if (!Number.isInteger(parsedLimit) || parsedLimit < 1) {+ return error(res, 400, 'invalid_limit', `limit must be a whole number from 1 to ${MAX_PAGE}`);+ }+ const parsedOffset = rawOffset == null ? 0 : parseCursor(rawOffset);+ if (!Number.isInteger(parsedOffset)) {+ return error(res, 400, 'invalid_offset', 'offset must be a whole number of 0 or more');+ }+ // Oversized limits clamp rather than fail: the documented contract is a page+ // of at most MAX_PAGE, and a caller asking for "everything" simply omits limit.+ limit = Math.min(parsedLimit, MAX_PAGE);+ offset = parsedOffset;+ }+let objects = [];let generatedAt = null;let degraded = false;try {const buf = await getObjectBuffer(MANIFEST_KEY);const parsed = JSON.parse(buf.toString('utf8'));- objects = Array.isArray(parsed) ? parsed : Array.isArray(parsed.objects) ? parsed.objects : [];+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.objects) ? parsed.objects : null;+ // A manifest that parses but carries no object list is corrupt, not empty.+ // Routing it through the catch below is what keeps it out of the edge cache:+ // a published-cache "no objects" would outlive the bad upload by 5 minutes.+ if (!list) throw new Error('manifest carries no object list');+ objects = list;generatedAt = parsed.generated_at || null;} catch (err) {// Not uploaded yet (NoSuchKey/404) is the expected pre-launch state; anything- // else is a real storage error worth logging and worth keeping out of the- // edge cache.+ // else (a storage outage, a corrupt or truncated manifest) is real and worth+ // logging and worth keeping out of the edge cache.const code = err?.$metadata?.httpStatusCode;if (err?.name !== 'NoSuchKey' && code !== 404) {degraded = true;@@ -58,30 +90,11 @@ export default wrap(async (req, res) => {}const total = objects.length;- const url = new URL(req.url, 'http://x');-- const rawLimit = url.searchParams.get('limit');- const rawOffset = url.searchParams.get('offset');- if (rawLimit == null) {- if (rawOffset != null) {- return error(res, 400, 'invalid_offset', 'offset is only meaningful with limit; pass ?limit=N too');- }+ if (limit == null) {res.setHeader('Cache-Control', degraded ? DEGRADED_CACHE : PUBLISHED_CACHE);return json(res, 200, { objects, total, generated_at: generatedAt });}- const parsedLimit = parseCursor(rawLimit);- if (!Number.isInteger(parsedLimit) || parsedLimit < 1) {- return error(res, 400, 'invalid_limit', `limit must be a whole number from 1 to ${MAX_PAGE}`);- }- const offset = rawOffset == null ? 0 : parseCursor(rawOffset);- if (!Number.isInteger(offset)) {- return error(res, 400, 'invalid_offset', 'offset must be a whole number of 0 or more');- }-- // Oversized limits clamp rather than fail: the documented contract is a page- // of at most MAX_PAGE, and a caller asking for "everything" simply omits limit.- const limit = Math.min(parsedLimit, MAX_PAGE);const page = objects.slice(offset, offset + limit);const nextOffset = offset + limit < total ? offset + limit : null;res.setHeader('Cache-Control', degraded ? DEGRADED_CACHE : PUBLISHED_CACHE);diff --git a/docs/object-library.md b/docs/object-library.mdindex dc4117888..ef307acb7 100644--- a/docs/object-library.md+++ b/docs/object-library.md@@ -35,7 +35,7 @@ Gallery controls:## API: `GET /api/objects/library`-Public, no authentication, CORS-open to GET from web origins. The endpoint proxies a small manifest JSON from the R2 CDN (`objects/library/manifest.json`) with an edge cache (`Cache-Control: public, s-maxage=300, stale-while-revalidate=3600`). The GLB and thumbnail bytes never pass through the API: every entry carries absolute CDN URLs the browser loads directly. It mirrors the [Character Library API](./character-library.md) exactly, with `objects` in place of `avatars`.+Public, no authentication, `GET` and `OPTIONS` only (`HEAD` is answered like `GET`). Browser `fetch` from a third-party origin is not enabled: like the [Character Library API](./character-library.md), the endpoint sends `Access-Control-Allow-Origin` only for three.ws and its partner origins, and the R2 CDN holding the GLBs is scoped the same way. Call it server-side, or from a three.ws page, and the assets it points at are still yours to download and redistribute anywhere (a download or a server-side fetch is not CORS-gated; only in-browser cross-origin reads are). The endpoint proxies a small manifest JSON from the R2 CDN (`objects/library/manifest.json`) with an edge cache (`Cache-Control: public, s-maxage=300, stale-while-revalidate=3600`). The GLB and thumbnail bytes never pass through the API: every entry carries absolute CDN URLs the browser loads directly. It mirrors the [Character Library API](./character-library.md) exactly, with `objects` in place of `avatars`.### Query parametersdiff --git a/tests/objects-library-endpoint.test.js b/tests/objects-library-endpoint.test.jsindex c2fcf99d5..1dd0b873d 100644--- a/tests/objects-library-endpoint.test.js+++ b/tests/objects-library-endpoint.test.js@@ -178,4 +178,63 @@ describe('GET /api/objects/library', () => {expect(body.error).toBe('invalid_offset');expect(body.error_description).toContain('limit');});++ // A doomed request must not pay for an upstream read first. The 400 cannot+ // change based on what R2 returns, so fetching the manifest anyway is pure+ // added latency on every client-side pagination bug.+ it('rejects a malformed cursor without touching storage', async () => {+ publish();+ getObjectBuffer.mockClear();+ const { res } = await get('?limit=abc');+ expect(res.statusCode).toBe(400);+ expect(getObjectBuffer).not.toHaveBeenCalled();+ });++ // ── Corrupt manifests are an outage, not an empty library ────────────────+ it('degrades without caching when the manifest is not valid JSON', async () => {+ getObjectBuffer.mockResolvedValue(Buffer.from('{"objects": [truncated'));+ const { res, body } = await get();+ expect(res.statusCode).toBe(200);+ expect(body.objects).toEqual([]);+ expect(res.getHeader('cache-control')).toBe('no-store');+ });++ it('degrades without caching when the manifest carries no object list', async () => {+ // Parses fine, but a `null` / wrong-shape body means a bad upload, and+ // caching "no objects" for 300s would outlive the bad upload.+ for (const bad of ['null', '{"objects":"nope"}', '"a string"']) {+ getObjectBuffer.mockResolvedValue(Buffer.from(bad));+ const { res, body } = await get();+ expect(res.statusCode).toBe(200);+ expect(body.objects).toEqual([]);+ expect(body.total).toBe(0);+ expect(res.getHeader('cache-control')).toBe('no-store');+ }+ });++ it('keeps the normal cache for a manifest that is legitimately empty', async () => {+ getObjectBuffer.mockResolvedValue(Buffer.from('{"objects":[]}'));+ const { res, body } = await get();+ expect(body.objects).toEqual([]);+ expect(res.getHeader('cache-control')).toContain('s-maxage=300');+ });++ it('does not cache a degraded response on the paginated path either', async () => {+ getObjectBuffer.mockRejectedValue(new Error('socket hang up'));+ const { res, body } = await get('?limit=2');+ expect(res.statusCode).toBe(200);+ expect(body.objects).toEqual([]);+ expect(body.next_offset).toBe(null);+ expect(res.getHeader('cache-control')).toBe('no-store');+ });++ // HEAD must behave like GET (api/_lib/http.js normalizes it); Node strips the+ // body. A handler that fell through on HEAD would hang until the timeout.+ it('answers HEAD like GET', async () => {+ publish();+ const res = fakeRes();+ await handler(fakeReq('HEAD'), res);+ expect(res.statusCode).toBe(200);+ expect(res.getHeader('cache-control')).toContain('s-maxage=300');+ });});