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(api): cover the pinning endpoint and the github memory seed route contract
nirholas792150f3a4d7
diff --git a/tests/github-memory-seed-endpoint.test.js b/tests/github-memory-seed-endpoint.test.jsnew file mode 100644index 000000000..9c165835c--- /dev/null+++ b/tests/github-memory-seed-endpoint.test.js@@ -0,0 +1,264 @@+// Route-level tests for POST/DELETE /api/agents/:id/memory/seed/github.+//+// The pure narrowing (catalog, selection, seed document, memory rows) is covered+// in tests/github-memory-seed.test.js. What is covered here is the ordering the+// route imposes around it, which is where three defects lived: a cookie POST+// that carried no CSRF token, a rejected selection that still spent the agent's+// 6-hour seed budget, and an exhausted LLM chain that surfaced as a bare+// internal error while the budget stayed spent.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const sqlMock = vi.fn();+sqlMock.transaction = vi.fn(async () => []);+vi.mock('../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const getSessionUserMock = vi.fn();+const authenticateBearerMock = vi.fn();+const extractBearerMock = vi.fn();+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: (...a) => getSessionUserMock(...a),+ authenticateBearer: (...a) => authenticateBearerMock(...a),+ extractBearer: (...a) => extractBearerMock(...a),+}));++const requireCsrfMock = vi.fn();+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: (...a) => requireCsrfMock(...a) }));++vi.mock('../api/_lib/env.js', () => ({+ env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://t', MCP_RESOURCE: 'http://t' },+}));++const githubSeedLimit = vi.fn();+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { githubSeed: (...a) => githubSeedLimit(...a) },+ clientIp: () => '127.0.0.1',+}));++const llmCompleteMock = vi.fn();+vi.mock('../api/_lib/llm.js', () => ({ llmComplete: (...a) => llmCompleteMock(...a) }));++vi.mock('../api/_lib/github-token.js', () => ({ decryptGithubToken: async () => 'gh-token' }));++const fetchProfileMock = vi.fn();+const fetchReposMock = vi.fn();+const fetchPinnedReposMock = vi.fn();+const fetchReadmeMock = vi.fn();+vi.mock('../api/_lib/github-api.js', () => ({+ fetchProfile: (...a) => fetchProfileMock(...a),+ fetchRepos: (...a) => fetchReposMock(...a),+ fetchPinnedRepos: (...a) => fetchPinnedReposMock(...a),+ fetchReadme: (...a) => fetchReadmeMock(...a),+}));++const { default: handler } = await import('../api/agents/[id]/memory-seed-github.js');++const AGENT = '11111111-1111-4111-8111-111111111111';+const USER = '55555555-5555-4555-8555-555555555555';++function mkReq({ method = 'POST', headers = {}, body = null } = {}) {+ return {+ method,+ url: `/api/agents/${AGENT}/memory/seed/github`,+ query: { id: AGENT },+ headers: { ...headers },+ on(event, cb) {+ if (event === 'data' && body != null) {+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));+ queueMicrotask(() => {+ cb(buf);+ this._endCb?.();+ });+ } else if (event === 'end') {+ this._endCb = cb;+ if (body == null) queueMicrotask(() => cb());+ }+ },+ destroy() {},+ };+}+function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(b) {+ this.body = b;+ this.writableEnded = true;+ },+ };+}+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);+const post = (body, headers = {}) =>+ mkReq({ method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body });++beforeEach(() => {+ // Owned-agent lookup, then the github social_connection row.+ sqlMock.mockReset().mockImplementation(() => Promise.resolve([]));+ sqlMock.transaction.mockReset().mockResolvedValue([]);+ getSessionUserMock.mockReset().mockResolvedValue({ id: USER });+ authenticateBearerMock.mockReset().mockResolvedValue(null);+ extractBearerMock.mockReset().mockReturnValue(null);+ requireCsrfMock.mockReset().mockResolvedValue(true);+ githubSeedLimit.mockReset().mockResolvedValue({ success: true, limit: 1, remaining: 0, reset: Date.now() + 21_600_000 });+ llmCompleteMock.mockReset().mockResolvedValue({ text: '["A fact about the owner."]' });+ fetchProfileMock.mockReset().mockResolvedValue({ login: 'dev', name: 'Dev', public_repos: 2, followers: 3 });+ fetchPinnedReposMock.mockReset().mockResolvedValue([+ { full_name: 'dev/kit', name: 'kit', description: 'A kit', language: 'JavaScript', stargazers_count: 5 },+ ]);+ fetchReposMock.mockReset().mockResolvedValue([]);+ fetchReadmeMock.mockReset().mockResolvedValue('# kit\n\nWhat the kit does.');+});++/** Agent-owned + connected: the two queries every mutation makes first. */+function connected() {+ let call = 0;+ sqlMock.mockImplementation(() => {+ call += 1;+ if (call === 1) return Promise.resolve([{ id: AGENT }]);+ if (call === 2) return Promise.resolve([{ id: 'conn', username: 'dev', access_token: 'enc', connected_at: null }]);+ return Promise.resolve([]);+ });+}++describe('CSRF on the seeding mutations', () => {+ it('POST is refused when the CSRF gate fails, before GitHub is read', async () => {+ connected();+ requireCsrfMock.mockImplementation(async (req, res) => {+ res.statusCode = 403;+ res.end(JSON.stringify({ error: 'csrf_missing' }));+ return false;+ });+ const res = mkRes();+ await handler(post({ include_profile: true, repos: [], readmes: [] }), res);+ expect(res.statusCode).toBe(403);+ expect(fetchProfileMock).not.toHaveBeenCalled();+ expect(llmCompleteMock).not.toHaveBeenCalled();+ expect(sqlMock.transaction).not.toHaveBeenCalled();+ });++ it('DELETE is refused when the CSRF gate fails, and deletes nothing', async () => {+ connected();+ requireCsrfMock.mockImplementation(async (req, res) => {+ res.statusCode = 403;+ res.end(JSON.stringify({ error: 'csrf_missing' }));+ return false;+ });+ const res = mkRes();+ await handler(mkReq({ method: 'DELETE' }), res);+ expect(res.statusCode).toBe(403);+ // Only the ownership lookup ran; the DELETE … RETURNING never did.+ expect(sqlMock).toHaveBeenCalledTimes(1);+ });++ it('a valid token lets the seed through', async () => {+ connected();+ const res = mkRes();+ await handler(post({ include_profile: true, repos: ['dev/kit'], readmes: [] }), res);+ expect(res.statusCode).toBe(200);+ expect(parse(res).seeded).toBe(1);+ expect(requireCsrfMock).toHaveBeenCalled();+ });+});++describe('the 6-hour seed budget', () => {+ it('is not spent by an empty selection', async () => {+ connected();+ const res = mkRes();+ await handler(post({ include_profile: false, repos: [], readmes: [] }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('empty_selection');+ expect(githubSeedLimit).not.toHaveBeenCalled();+ });++ it('is not spent by a selection naming a repo outside the catalog', async () => {+ connected();+ const res = mkRes();+ await handler(post({ include_profile: true, repos: ['someone/else'], readmes: [] }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('invalid_selection');+ expect(parse(res).rejected).toEqual([{ key: 'someone/else', reason: 'not_in_catalog' }]);+ expect(githubSeedLimit).not.toHaveBeenCalled();+ });++ it('is spent once the selection is good, and blocks the next run', async () => {+ connected();+ githubSeedLimit.mockResolvedValue({ success: false, limit: 1, remaining: 0, reset: Date.now() + 60_000 });+ const res = mkRes();+ await handler(post({ include_profile: true, repos: ['dev/kit'], readmes: [] }), res);+ expect(res.statusCode).toBe(429);+ expect(githubSeedLimit).toHaveBeenCalledWith(AGENT);+ // Refused before anything was read or written.+ expect(fetchReadmeMock).not.toHaveBeenCalled();+ expect(llmCompleteMock).not.toHaveBeenCalled();+ expect(sqlMock.transaction).not.toHaveBeenCalled();+ });+});++describe('when every model provider is busy', () => {+ it('answers 503 distill_unavailable and leaves the existing memories alone', async () => {+ connected();+ llmCompleteMock.mockRejectedValue(+ Object.assign(new Error('chain exhausted'), {+ status: 502,+ code: 'upstream_error',+ attempts: [{ provider: 'ovh' }, { provider: 'pollinations' }],+ }),+ );+ const res = mkRes();+ await handler(post({ include_profile: true, repos: ['dev/kit'], readmes: [] }), res);+ expect(res.statusCode).toBe(503);+ const body = parse(res);+ expect(body.error).toBe('distill_unavailable');+ expect(body.error_description).toMatch(/nothing was seeded/);+ expect(body.providers_tried).toEqual(['ovh', 'pollinations']);+ expect(typeof body.retry_at).toBe('string');+ expect(sqlMock.transaction).not.toHaveBeenCalled();+ });++ it('still answers distill_error when the material yields no facts', async () => {+ connected();+ llmCompleteMock.mockResolvedValue({ text: '[]' });+ const res = mkRes();+ await handler(post({ include_profile: true, repos: ['dev/kit'], readmes: [] }), res);+ expect(res.statusCode).toBe(502);+ expect(parse(res).error).toBe('distill_error');+ expect(sqlMock.transaction).not.toHaveBeenCalled();+ });+});++describe('the README narrowing survives the route', () => {+ it('reads a README only for a repo that was also ticked', async () => {+ connected();+ const res = mkRes();+ await handler(post({ include_profile: false, repos: ['dev/kit'], readmes: ['dev/kit'] }), res);+ expect(res.statusCode).toBe(200);+ expect(fetchReadmeMock).toHaveBeenCalledTimes(1);+ expect(fetchReadmeMock).toHaveBeenCalledWith('gh-token', 'dev/kit');+ expect(parse(res).readmes_read).toEqual(['dev/kit']);+ });++ it('refuses a README for a repo that was not ticked, reading nothing', async () => {+ connected();+ fetchReposMock.mockResolvedValue([+ { full_name: 'dev/other', name: 'other', description: null, pushed_at: '2026-01-01T00:00:00Z' },+ ]);+ const res = mkRes();+ await handler(post({ include_profile: false, repos: ['dev/kit'], readmes: ['dev/other'] }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).rejected).toEqual([{ key: 'dev/other', reason: 'readme_without_repo' }]);+ expect(fetchReadmeMock).not.toHaveBeenCalled();+ });+});diff --git a/tests/pinning-endpoint.test.js b/tests/pinning-endpoint.test.jsnew file mode 100644index 000000000..8d26b3e51--- /dev/null+++ b/tests/pinning-endpoint.test.js@@ -0,0 +1,230 @@+// POST /api/pinning/pin is the only way a browser can put bytes on IPFS here:+// the Pinata credential is server-held, so avatar-studio base64s the whole GLB+// into this endpoint (character-studio/src/library/mint-utils.js).+//+// That makes the body limit part of the endpoint's contract rather than a+// detail. The handler advertised a 10 MB inline cap while taking readJson's+// 1,000,000-byte default, and base64 inflates raw bytes by 4/3, so every inline+// pin above roughly 730 KB was refused with a bare `413 bad_request` that named+// no limit. These tests pin the two halves of that contract: a payload inside+// the cap reaches the provider, one above it is refused with this endpoint's own+// `payload_too_large` code, and a caller's filename survives the trip instead of+// being replaced by a constant.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const sqlMock = vi.fn(async () => []);+vi.mock('../api/_lib/db.js', () => ({+ sql: (...a) => sqlMock(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false }),+}));++const sessionUser = { value: { id: 'user-1' } };+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: async () => sessionUser.value,+ authenticateBearer: async () => null,+ extractBearer: () => null,+}));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ pinUser: async () => ({ success: true, reset: 1_000 }),+ pinStatusIp: async () => ({ success: true, reset: 1_000 }),+ },+ clientIp: () => '203.0.113.9',+}));++vi.mock('../api/_lib/env.js', () => ({+ env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://t', MCP_RESOURCE: 'http://t' },+}));++const { default: handler } = await import('../api/pinning/[action].js');++function mkReq({ body = null, method = 'POST', action = 'pin', url } = {}) {+ const raw = body == null ? null : Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));+ return {+ method,+ url: url || `/api/pinning/${action}`,+ query: { action },+ headers: raw ? { 'content-type': 'application/json' } : {},+ socket: { remoteAddress: '127.0.0.1' },+ on(event, cb) {+ if (event === 'data' && raw) queueMicrotask(() => { cb(raw); this._end?.(); });+ else if (event === 'end') { this._end = cb; if (!raw) queueMicrotask(cb); }+ return this;+ },+ destroy() {},+ };+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ writableEnded: false,+ headersSent: false,+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(b) { this.body = b; this.writableEnded = true; },+ };+}++const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);++// A data: URL carrying `bytes` of raw payload, the exact shape saveFileToPinata builds.+const inlineGlb = (bytes) =>+ 'data:model/gltf-binary;base64,' + Buffer.alloc(bytes, 0x41).toString('base64');++let pinataCalls = [];+const realFetch = globalThis.fetch;+const realJwt = process.env.PINATA_JWT;++beforeEach(() => {+ pinataCalls = [];+ sqlMock.mockClear();+ sessionUser.value = { id: 'user-1' };+ process.env.PINATA_JWT = 'test-jwt';+ // Stub only the third-party boundary: the handler, http helpers, size+ // accounting and the real pinToIPFS all run unmodified above it.+ globalThis.fetch = vi.fn(async (url, init) => {+ pinataCalls.push({ url: String(url), init });+ return new Response(JSON.stringify({ IpfsHash: 'QmTestCid00000000000000000000000000000000000000' }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+ });+});++afterEach(() => {+ globalThis.fetch = realFetch;+ if (realJwt === undefined) delete process.env.PINATA_JWT;+ else process.env.PINATA_JWT = realJwt;+});++describe('POST /api/pinning/pin', () => {+ it('pins an inline payload well above the old 1 MB body default', async () => {+ const res = mkRes();+ // 1.5 MB raw is ~2 MB of base64: comfortably inside the stated cap, and+ // exactly the size that used to be rejected before it reached any check.+ await handler(mkReq({ body: { sourceUrl: inlineGlb(1_500 * 1024), kind: 'glb' } }), res);++ expect(res.statusCode).toBe(200);+ const out = parse(res);+ expect(out.ok).toBe(true);+ expect(out.cid).toBe('QmTestCid00000000000000000000000000000000000000');+ expect(out.provider).toBe('pinata');+ expect(out.gatewayUrl).toContain(out.cid);+ expect(out.gatewayUrls.length).toBeGreaterThan(1);+ expect(pinataCalls).toHaveLength(1);+ expect(pinataCalls[0].url).toContain('api.pinata.cloud');+ // The row that records the pin never stores the inline bytes back.+ expect(sqlMock).toHaveBeenCalled();+ });++ it('refuses an inline payload over the decoded cap with a named limit', async () => {+ const res = mkRes();+ await handler(mkReq({ body: { sourceUrl: inlineGlb(Math.floor(5.4 * 1024 * 1024)), kind: 'glb' } }), res);++ expect(res.statusCode).toBe(413);+ expect(parse(res).error).toBe('payload_too_large');+ expect(parse(res).error_description).toMatch(/exceeds 5 MB/);+ expect(pinataCalls).toHaveLength(0);+ });++ it("forwards the caller's filename to the provider", async () => {+ const res = mkRes();+ await handler(+ mkReq({ body: { sourceUrl: inlineGlb(64), kind: 'glb', filename: 'knight-v2.glb' } }),+ res,+ );++ expect(res.statusCode).toBe(200);+ const form = pinataCalls[0].init.body;+ expect(form.get('file').name).toBe('knight-v2.glb');+ });++ it('sanitizes a hostile filename rather than forwarding it', async () => {+ const res = mkRes();+ await handler(+ mkReq({ body: { sourceUrl: inlineGlb(64), kind: 'glb', filename: '../../etc/passwd\r\nX: y' } }),+ res,+ );++ expect(res.statusCode).toBe(200);+ expect(pinataCalls[0].init.body.get('file').name).toBe('....etcpasswdXy');+ });++ it('falls back to the kind default when the filename is not a string', async () => {+ const res = mkRes();+ await handler(mkReq({ body: { sourceUrl: inlineGlb(64), kind: 'manifest', filename: { a: 1 } } }), res);++ expect(res.statusCode).toBe(200);+ expect(pinataCalls[0].init.body.get('file').name).toBe('manifest.json');+ });++ it('rejects a source URL the platform does not own', async () => {+ const res = mkRes();+ await handler(mkReq({ body: { sourceUrl: 'https://evil.example.com/x.glb', kind: 'glb' } }), res);++ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('validation_error');+ expect(pinataCalls).toHaveLength(0);+ });++ it('answers a malformed request with 4xx even when no provider is configured', async () => {+ delete process.env.PINATA_JWT;+ const res = mkRes();+ await handler(mkReq({ body: { sourceUrl: 'https://evil.example.com/x.glb', kind: 'glb' } }), res);++ // The deployment being unconfigured must not mask a request the caller+ // could have fixed, so the 400 wins over the 503.+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('validation_error');+ });++ it('reports an unconfigured deployment as 503 once the request is valid', async () => {+ delete process.env.PINATA_JWT;+ const res = mkRes();+ await handler(mkReq({ body: { sourceUrl: inlineGlb(64), kind: 'manifest' } }), res);++ expect(res.statusCode).toBe(503);+ expect(parse(res).error).toBe('pinning_unconfigured');+ });++ it('requires a signed-in caller', async () => {+ sessionUser.value = null;+ const res = mkRes();+ await handler(mkReq({ body: { sourceUrl: inlineGlb(64), kind: 'manifest' } }), res);++ expect(res.statusCode).toBe(401);+ expect(parse(res).error).toBe('unauthorized');+ });+});++describe('GET /api/pinning/status', () => {+ it('separates an unreachable provider from a genuinely unpinned CID', async () => {+ globalThis.fetch = vi.fn(async () => new Response('unauthorized', { status: 401 }));+ const res = mkRes();+ await handler(+ mkReq({ method: 'GET', action: 'status', url: '/api/pinning/status?cid=QmTestCid00000000000000000000000000000000000000', body: null }),+ res,+ );++ expect(res.statusCode).toBe(503);+ expect(parse(res).error).toBe('pinning_check_failed');+ });++ it('rejects a CID outside the length and charset bounds', async () => {+ const res = mkRes();+ await handler(+ mkReq({ method: 'GET', action: 'status', url: '/api/pinning/status?cid=' + 'a'.repeat(500), body: null }),+ res,+ );++ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('validation_error');+ });+});