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.

feat(api): add CSRF protection to memory-seed and avatar actions

nirholaseb91b43d362d
diff --git a/api/agents/_id/memory-seed.js b/api/agents/_id/memory-seed.js
index 814139bd7..a5b7069b1 100644
--- a/api/agents/_id/memory-seed.js
+++ b/api/agents/_id/memory-seed.js
@@ -15,6 +15,7 @@
import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
import { cors, json, method, readJson, error, rateLimited, serverError } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
import { llmComplete } from '../../_lib/llm.js';
import { limits } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
@@ -49,6 +50,12 @@ export default async function handleMemorySeed(req, res, agentId) {
`;
if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ // CSRF on state-changing session-cookie requests; bearer tokens are exempt
+ // inside requireCsrf. The sibling providers (memory-seed-x, -farcaster) gate
+ // the same way; this preset route deletes and rewrites the agent's memories,
+ // so a cross-site form post must not be able to drive it.
+ if (!(await requireCsrf(req, res, userId))) return;
+
const [conn] = await sql`
SELECT access_token, username FROM social_connections
WHERE user_id = ${userId} AND provider = 'github'
diff --git a/api/avatars/[id]/[action].js b/api/avatars/[id]/[action].js
index cf9d09452..e05871053 100644
--- a/api/avatars/[id]/[action].js
+++ b/api/avatars/[id]/[action].js
@@ -413,39 +413,46 @@ async function handleStorageMode(req, res) {
const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
if (!id) return error(res, 400, 'validation_error', 'avatar id required');
+ // PUT is owner-only: authenticate BEFORE any avatar lookup so an anonymous
+ // caller can't use the 404-vs-401 split to probe whether an id exists.
+ if (req.method === 'PUT') {
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, session.id))) return;
+
+ const [row] = await sql`
+ SELECT id, owner_id FROM avatars WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!row) return error(res, 404, 'not_found', 'avatar not found');
+ if (session.id !== row.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
+
+ const body = parse(storageModeSchema, await readJson(req));
+
+ // Read current stored mode to preserve attestation fields — clients must not
+ // be able to forge tx_hash / chain_id / attested_at from the UI.
+ const current = await readStorageMode(id);
+ const safeBody = {
+ ...body,
+ attestation: current?.attestation ?? defaultStorageMode().attestation,
+ };
+
+ await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(safeBody)}::jsonb WHERE id = ${id}`;
+ return json(res, 200, { storage_mode: safeBody });
+ }
+
+ // GET — public/unlisted anyone; private owner only.
const [row] = await sql`
SELECT id, owner_id, visibility FROM avatars WHERE id = ${id} AND deleted_at IS NULL
`;
if (!row) return error(res, 404, 'not_found', 'avatar not found');
- if (req.method === 'GET') {
- if (row.visibility === 'private') {
- const session = await getSessionUser(req);
- if (!session || session.id !== row.owner_id)
- return error(res, 403, 'forbidden', 'private avatar');
- }
- const mode = await readStorageMode(id);
- return json(res, 200, { storage_mode: mode });
+ if (row.visibility === 'private') {
+ const session = await getSessionUser(req);
+ if (!session || session.id !== row.owner_id)
+ return error(res, 403, 'forbidden', 'private avatar');
}
-
- // PUT — owner only
- const session = await getSessionUser(req);
- if (!session) return error(res, 401, 'unauthorized', 'sign in required');
- if (!(await requireCsrf(req, res, session.id))) return;
- if (session.id !== row.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
-
- const body = parse(storageModeSchema, await readJson(req));
-
- // Read current stored mode to preserve attestation fields — clients must not
- // be able to forge tx_hash / chain_id / attested_at from the UI.
- const current = await readStorageMode(id);
- const safeBody = {
- ...body,
- attestation: current?.attestation ?? defaultStorageMode().attestation,
- };
-
- await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(safeBody)}::jsonb WHERE id = ${id}`;
- return json(res, 200, { storage_mode: safeBody });
+ const mode = await readStorageMode(id);
+ return json(res, 200, { storage_mode: mode });
}
// ── versions ───────────────────────────────────────────────────────────────
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index f23447e2d..19df1e4ac 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -7,7 +7,7 @@ import { storageKeyFor, enforceQuotas, searchPublicAvatars, stripOwnerFor } from
import { listAvatars } from '../_lib/avatars.js';
import { env } from '../_lib/env.js';
import { sql } from '../_lib/db.js';
-import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { cors, json, method, readJson, readBody, wrap, error, rateLimited } from '../_lib/http.js';
import { parse, presignUploadBody, slug as slugSchema, createAvatarBody } from '../_lib/validate.js';
import { recordEvent } from '../_lib/usage.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -154,6 +154,17 @@ const handleUpload = wrap(async (req, res) => {
} catch (err) {
return error(res, err.status || 502, err.code || 'fetch_failed', err.message || 'failed to fetch source URL');
}
+ // Cloud Run's Express layer pre-drains the request stream and stashes the
+ // bytes on req.rawBody / req.body (see readBody in api/_lib/http.js). The
+ // raw-stream listener below never fires for those requests — its 'data' and
+ // 'end' events already emitted — so production uploads must prefer the
+ // captured buffer over the stream, exactly like readBody does.
+ } else if (Buffer.isBuffer(req.rawBody) || req.body !== undefined) {
+ try {
+ buffer = await readBody(req, MAX_PROXY_UPLOAD_BYTES);
+ } catch (err) {
+ return error(res, err.status || 400, err.code || 'invalid_body', err.message || 'failed to read body');
+ }
} else {
const declaredLength = Number(req.headers['content-length']);
if (Number.isFinite(declaredLength) && declaredLength > MAX_PROXY_UPLOAD_BYTES) {
diff --git a/public/changelog.json b/public/changelog.json
index aa2167475..d7ab70783 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T06:41:08.444Z",
+ "generated_at": "2026-08-12T07:03:01.311Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/features.json b/public/features.json
index e40c850f2..83503e287 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-12T06:41:08.432Z",
+ "generated_at": "2026-08-12T07:03:01.293Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/locales/localized-pages.json b/public/locales/localized-pages.json
index fc7ed8c86..f2eae9954 100644
--- a/public/locales/localized-pages.json
+++ b/public/locales/localized-pages.json
@@ -1,6 +1,6 @@
{
"generated": true,
- "count": 242,
+ "count": 354,
"paths": [
"/",
"/3d",
@@ -156,6 +156,118 @@
"/mocap-studio",
"/motion-swap",
"/my-agents",
+ "/news",
+ "/news/",
+ "/news/2045242891350814835",
+ "/news/2049397875935989970",
+ "/news/2049406826719137937",
+ "/news/2049412062837928202",
+ "/news/2049447738434339171",
+ "/news/2049458671139336613",
+ "/news/2049476546285740512",
+ "/news/2049557523330638269",
+ "/news/2049573582247022869",
+ "/news/2049576603324411933",
+ "/news/2049576641127682430",
+ "/news/2049577291957899336",
+ "/news/2049762836881301865",
+ "/news/2049765915575914834",
+ "/news/2049997615421649363",
+ "/news/2050016695897706885",
+ "/news/2050049239301165535",
+ "/news/2050221269732425928",
+ "/news/2050226678321102975",
+ "/news/2050229144676675999",
+ "/news/2050284562069266616",
+ "/news/2050585585191186781",
+ "/news/2050627547394916768",
+ "/news/2050753406109880576",
+ "/news/2050758788186353723",
+ "/news/2050800140295049308",
+ "/news/2050886334261391686",
+ "/news/2051140736201175323",
+ "/news/2051261108506558901",
+ "/news/2051616708482498843",
+ "/news/2051689230997618690",
+ "/news/2051690803203105230",
+ "/news/2051774915876098063",
+ "/news/2051858035862335505",
+ "/news/2051858503523066283",
+ "/news/2051893054584553680",
+ "/news/2052037977556287723",
+ "/news/2052167399399735476",
+ "/news/2052181307002929363",
+ "/news/2052189491801284690",
+ "/news/2052402481024667887",
+ "/news/2052402580266098813",
+ "/news/2052418108837781511",
+ "/news/2052418482269254040",
+ "/news/2052426446073983267",
+ "/news/2052588973466484922",
+ "/news/2052603250524967045",
+ "/news/2052685648377913671",
+ "/news/2052790746256920583",
+ "/news/2052791935585407403",
+ "/news/2053025259645981078",
+ "/news/2053698115203743922",
+ "/news/2053698387263008827",
+ "/news/2053730856339144932",
+ "/news/2053801703355629587",
+ "/news/2053804700609458214",
+ "/news/2053832201176027583",
+ "/news/2054404663802483072",
+ "/news/2054675701132132736",
+ "/news/2055140064070717618",
+ "/news/2055307440921702738",
+ "/news/2055309846556401735",
+ "/news/2055310365588922872",
+ "/news/2055517252964024561",
+ "/news/2055967730495586477",
+ "/news/2055985494606106821",
+ "/news/2056556899403997450",
+ "/news/2057721370310775223",
+ "/news/2057780453709648200",
+ "/news/2057782522994684413",
+ "/news/2057786164862730704",
+ "/news/2058076885805085111",
+ "/news/2058287578227577039",
+ "/news/2059456289789657537",
+ "/news/2059456294189498830",
+ "/news/2059456295825223723",
+ "/news/2059457822941978723",
+ "/news/2059675892981633179",
+ "/news/2059712761622675776",
+ "/news/2059821472156446844",
+ "/news/2059894004771418220",
+ "/news/2060178868305326413",
+ "/news/2060186881636422038",
+ "/news/2061418285896269952",
+ "/news/2061488909264040194",
+ "/news/2061523804405616642",
+ "/news/2061713039624405062",
+ "/news/aws-agentic-economy-three-ws",
+ "/news/aws-builder-center-3d-agents-onchain-payments",
+ "/news/aws-builder-center-blog",
+ "/news/aws-marketplace-live-may29",
+ "/news/bybit-alpha-listing",
+ "/news/cmc-mcp-registry-article",
+ "/news/cmc-memecoin-3d-world",
+ "/news/ibm-collaboration-showcase",
+ "/news/ibm-showcase-may31",
+ "/news/joined-aws-partner-network",
+ "/news/listed-on-bnb-chain-dappbay",
+ "/news/live-on-alibaba-cloud-marketplace",
+ "/news/live-on-aws-marketplace",
+ "/news/mcp-servers-x402-bazaar-coinbase",
+ "/news/monetize-mcp-server-x402-paid-tools",
+ "/news/moonshot-verified",
+ "/news/partnered-with-hackernoon",
+ "/news/quicknode-startup-program",
+ "/news/text-to-3d-is-live",
+ "/news/three-ws-dextools-social-boost-buyback",
+ "/news/three-ws-featured-on-alibaba-cloud-marketplace-blog",
+ "/news/three-ws-first-month-3d-agent-layer",
+ "/news/threews-play-coin-communities",
"/nim-forge",
"/notifications",
"/nvidia",
diff --git a/public/mcp-catalog.json b/public/mcp-catalog.json
index f025f45cc..ffe9127e0 100644
--- a/public/mcp-catalog.json
+++ b/public/mcp-catalog.json
@@ -4570,7 +4570,7 @@
{
"name": "enlist_faction",
"title": "Enlist in a Coin Clash faction",
- "description": "Enlist the signer's wallet as a soldier in a Coin Clash faction and return a war pass. Requires the wallet to hold the faction coin: the tool requests a challenge, signs it with the wallet's Solana key (from the `secret` arg, or SOLANA_SECRET_KEY env), and the backend verifies the signature then checks a live on-chain holding. Returns `{ eligible, wallet, faction, amount, usd, warPass }`. If `eligible` is false the wallet does not currently hold the coin (`reason: \"not_a_holder\"`) and `warPass` is null — buy/hold the coin and retry. Keep the `warPass`: pass it to rally_faction to spend taps as battle power. No funds move; the pass expires after ~30 minutes.",
+ "description": "Enlist the signer's wallet as a soldier in a Coin Clash faction and return a war pass. Requires the wallet to hold the faction coin: the tool requests a challenge, signs it with the wallet's Solana key (from the `secret` arg, or SOLANA_SECRET_KEY env), and the backend verifies the signature then checks a live on-chain holding. Returns `{ eligible, wallet, faction, amount, usd, warPass, reason, challengeExpiresAt }`. If `eligible` is false the wallet does not currently hold the coin (`reason: \"not_a_holder\"`) and `warPass` is null — buy/hold the coin and retry. Keep the `warPass`: pass it to rally_faction to spend taps as battle power. No funds move; the pass expires after ~30 minutes.",
"server": {
"id": "clash-mcp",
"title": "@three-ws/clash-mcp",
@@ -4824,7 +4824,7 @@
{
"name": "concierge_embed",
"title": "Generate a Concierge embed snippet for a website",
- "description": "Generate ready-to-paste embed code for adding a three.ws Concierge (an AI chat widget with a talking 3D avatar) to a website. Returns the one-tag <script> install by default, or the <three-concierge> web component / npm snippet / all of them. Configure the accent color, avatar, greeting, curated knowledge, suggested prompts, position and theme. Offline: this only composes the code, it installs nothing.",
+ "description": "Generate ready-to-paste embed code for adding a three.ws Concierge (an AI chat widget with a talking 3D avatar) to a website. Returns every install flavor by default (flavor \"all\"): the one-tag <script> install, the <three-concierge> web component, the npm snippet, and the imperative mount() call; pass `flavor` to get just one. Configure the accent color, avatar, greeting, curated knowledge, suggested prompts, position and theme. Offline: this only composes the code, it installs nothing.",
"server": {
"id": "concierge-mcp",
"title": "@three-ws/concierge-mcp",
@@ -11349,7 +11349,7 @@
{
"name": "pose_model",
"title": "Resolve a text prompt to a pose-studio seed + joint rotations",
- "description": "Map a natural-language pose description to a deterministic pose-studio seed and the full Euler joint-rotation map for the three.ws humanoid mannequin, picked from the in-repo preset library. Returns the preset id, the complete pose (radians per joint), a stable seed, and a previewUrl on three.ws/pose. Deterministic and free — the same prompt always yields the same pose. Pair with auto_rig_model to pose a rigged character.",
+ "description": "Map a natural-language pose description to a deterministic pose-studio seed and the full Euler joint-rotation map for the three.ws humanoid mannequin, picked from the in-repo preset library. Returns the preset id, the complete pose (radians per joint), a stable seed, and a previewUrl on three.ws/pose. Deterministic: the same prompt always yields the same pose. Same engine as the free local @three-ws/pose npm package. Pair with auto_rig_model to pose a rigged character.",
"server": {
"id": "threews-3d-studio",
"title": "3D Studio",
diff --git a/tests/api/agents-achievements-endpoint.test.js b/tests/api/agents-achievements-endpoint.test.js
new file mode 100644
index 000000000..fe1a71e7b
--- /dev/null
+++ b/tests/api/agents-achievements-endpoint.test.js
@@ -0,0 +1,91 @@
+// Tests for GET /api/agents/:id/achievements (api/agents/_id/achievements.js).
+//
+// The handler is a thin public shell over api/_lib/agent-achievements-data.js:
+// rate-limit, uuid guard, then the shared gather+cache loader whose scoring is
+// covered by tests/agent-achievements.test.js. What this pins at the boundary:
+// a real agent returns the loader's body verbatim (with the cache marker
+// stripped and surfaced as X-Cache), a missing agent is a 404, a non-uuid id is
+// a 404 (never a Postgres 22P02 500), and non-GET methods are 405.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { makeReq, makeRes } from '../_helpers/monetization.js';
+
+const AGENT_ID = '00000000-0000-4000-8000-0000000000a1';
+
+let loaderBody = null;
+const loadMock = vi.fn(async () => loaderBody);
+vi.mock('../../api/_lib/agent-achievements-data.js', () => ({
+ loadAgentAchievements: (...a) => loadMock(...a),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ agentProfileIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const { handleAchievements } = await import('../../api/agents/_id/achievements.js');
+
+async function invoke({ method = 'GET', id = AGENT_ID } = {}) {
+ const req = makeReq({ method, url: `/api/agents/${id}/achievements` });
+ const res = makeRes();
+ await handleAchievements(req, res, id);
+ return res;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ loaderBody = {
+ agent_id: AGENT_ID,
+ name: 'Audit Bot',
+ achievements: [{ id: 'trailblazer', earned: true }],
+ summary: { earned: 1, total: 12 },
+ _cache: 'HIT',
+ };
+});
+
+describe('GET /api/agents/:id/achievements', () => {
+ it('returns the loader body with the cache marker stripped and X-Cache set', async () => {
+ const res = await invoke();
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.agent_id).toBe(AGENT_ID);
+ expect(body.achievements).toHaveLength(1);
+ expect(body._cache).toBeUndefined();
+ expect(res.headers['x-cache']).toBe('HIT');
+ expect(res.headers['cache-control']).toContain('public');
+ expect(loadMock).toHaveBeenCalledWith(AGENT_ID);
+ });
+
+ it('404s when the agent does not exist', async () => {
+ loaderBody = null;
+ const res = await invoke();
+ expect(res.statusCode).toBe(404);
+ expect(JSON.parse(res.body).error).toBe('not_found');
+ });
+
+ it('404s on a non-uuid id instead of leaking a Postgres error', async () => {
+ const res = await invoke({ id: 'not-a-uuid' });
+ expect(res.statusCode).toBe(404);
+ expect(loadMock).not.toHaveBeenCalled();
+ });
+
+ it('405s on POST', async () => {
+ const res = await invoke({ method: 'POST' });
+ expect(res.statusCode).toBe(405);
+ });
+
+ it('429s when the rate limiter trips', async () => {
+ const { limits } = await import('../../api/_lib/rate-limit.js');
+ limits.agentProfileIp.mockResolvedValueOnce({
+ success: false,
+ reset: Date.now() + 60_000,
+ limit: 60,
+ remaining: 0,
+ });
+ const res = await invoke();
+ expect(res.statusCode).toBe(429);
+ expect(loadMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/api/agents-activate-endpoint.test.js b/tests/api/agents-activate-endpoint.test.js
new file mode 100644
index 000000000..a828fd88d
--- /dev/null
+++ b/tests/api/agents-activate-endpoint.test.js
@@ -0,0 +1,124 @@
+// Tests for /api/agents/:id/activate (api/agents/_id/activate.js), the
+// owner-only activation-grant endpoint.
+//
+// The grant itself (treasury transfer, custody recording, eligibility rules)
+// lives in api/_lib/agent-activation.js and is covered by
+// tests/agent-activation.test.js. What this pins at the HTTP boundary: auth is
+// enforced before anything else, a bearer POST without avatars:write scope is a
+// 403, GET hands the caller the status payload, and the POST result-to-status
+// mapping never lets a business failure (cap reached, treasury low) surface as
+// a bare 500.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { makeReq, makeRes } from '../_helpers/monetization.js';
+
+const AGENT_ID = '00000000-0000-4000-8000-0000000000a2';
+const OWNER_ID = 'user-owner';
+
+let agentRow = { id: AGENT_ID, user_id: OWNER_ID, name: 'Audit Bot', meta: {} };
+const sqlMock = vi.fn(async () => (agentRow ? [agentRow] : []));
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+let sessionUser = { id: OWNER_ID };
+let bearerResult = null;
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => sessionUser),
+ authenticateBearer: vi.fn(async () => bearerResult),
+ extractBearer: vi.fn(() => null),
+ hasScope: vi.fn((scope, need) => String(scope || '').split(/[\s,]+/).includes(need)),
+}));
+
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const statusMock = vi.fn(async () => ({ enabled: false, eligible: false, reason: 'not_configured' }));
+const activateMock = vi.fn(async () => ({ ok: true, tx: 'sig' }));
+vi.mock('../../api/_lib/agent-activation.js', () => ({
+ getActivationStatus: (...a) => statusMock(...a),
+ activateAgent: (...a) => activateMock(...a),
+}));
+
+const { default: handler } = await import('../../api/agents/_id/activate.js');
+
+async function invoke({ method = 'GET', headers = {} } = {}) {
+ const req = makeReq({ method, url: `/api/agents/${AGENT_ID}/activate`, headers, body: method === 'POST' ? {} : null });
+ const res = makeRes();
+ await handler(req, res, AGENT_ID);
+ return res;
+}
+
+beforeEach(() => {
+ sessionUser = { id: OWNER_ID };
+ bearerResult = null;
+ agentRow = { id: AGENT_ID, user_id: OWNER_ID, name: 'Audit Bot', meta: {} };
+ activateMock.mockResolvedValue({ ok: true, tx: 'sig' });
+ vi.clearAllMocks();
+});
+
+describe('/api/agents/:id/activate', () => {
+ it('GET returns the activation status for the owner', async () => {
+ const res = await invoke();
+ expect(res.statusCode).toBe(200);
+ expect(JSON.parse(res.body).data.reason).toBe('not_configured');
+ expect(statusMock).toHaveBeenCalledOnce();
+ });
+
+ it('GET 401s without auth', async () => {
+ sessionUser = null;
+ const res = await invoke();
+ expect(res.statusCode).toBe(401);
+ expect(statusMock).not.toHaveBeenCalled();
+ });
+
+ it('GET 404s for an agent the caller does not own', async () => {
+ agentRow = null;
+ const res = await invoke();
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('POST 403s for an authenticated non-owner', async () => {
+ sessionUser = { id: 'user-other' };
+ const res = await invoke({ method: 'POST' });
+ expect(res.statusCode).toBe(403);
+ expect(activateMock).not.toHaveBeenCalled();
+ });
+
+ it('POST 403s for a bearer token without avatars:write scope', async () => {
+ sessionUser = null;
+ bearerResult = { userId: OWNER_ID, scope: 'read' };
+ const res = await invoke({ method: 'POST', headers: { authorization: 'Bearer tok' } });
+ expect(res.statusCode).toBe(403);
+ expect(JSON.parse(res.body).error).toBe('insufficient_scope');
+ expect(activateMock).not.toHaveBeenCalled();
+ });
+
+ it('POST activates for the owner and returns the result', async () => {
+ const res = await invoke({ method: 'POST' });
+ expect(res.statusCode).toBe(200);
+ expect(JSON.parse(res.body).data.ok).toBe(true);
+ expect(activateMock).toHaveBeenCalledWith({ agentId: AGENT_ID, userId: OWNER_ID });
+ });
+
+ it('POST maps business failures to their status codes, never a 500', async () => {
+ activateMock.mockResolvedValue({ ok: false, code: 'cap_reached', message: 'daily cap' });
+ const res = await invoke({ method: 'POST' });
+ expect(res.statusCode).toBe(429);
+ expect(JSON.parse(res.body).error).toBe('cap_reached');
+
+ activateMock.mockResolvedValue({ ok: false, code: 'treasury_low', message: 'treasury low' });
+ const res2 = await invoke({ method: 'POST' });
+ expect(res2.statusCode).toBe(503);
+ });
+
+ it('rejects unsupported methods with 405', async () => {
+ const res = await invoke({ method: 'DELETE' });
+ expect(res.statusCode).toBe(405);
+ });
+});
diff --git a/tests/api/agents-livekit-token.test.js b/tests/api/agents-livekit-token.test.js
new file mode 100644
index 000000000..7c8e0a496
--- /dev/null
+++ b/tests/api/agents-livekit-token.test.js
@@ -0,0 +1,114 @@
+// Tests for GET /api/agents/:id/livekit-token (api/agents/_id/livekit-token.js).
+//
+// The handler mints a short-lived LiveKit room JWT with jose. What this pins:
+// the unconfigured state is a designed 503 (never a crash), auth is required,
+// only the agent's owner may mint a publish-capable token for the agent's room
+// (any signed-in stranger must not get one), and the minted JWT actually
+// verifies against the configured secret with the right room, issuer, and
+// grants.
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { jwtVerify } from 'jose';
+import { makeReq, makeRes } from '../_helpers/monetization.js';
+
+const AGENT_ID = '00000000-0000-4000-8000-0000000000a3';
+const OWNER_ID = 'user-owner';
+const KEY = 'audit-livekit-key';
+const SECRET = 'audit-livekit-secret-0123456789abcdef';
+
+let agentRow = { id: AGENT_ID };
+const sqlMock = vi.fn(async () => (agentRow ? [agentRow] : []));
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+let sessionUser = { id: OWNER_ID };
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => sessionUser),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+function setLiveKitEnv() {
+ process.env.LIVEKIT_API_KEY = KEY;
+ process.env.LIVEKIT_API_SECRET = SECRET;
+ process.env.LIVEKIT_SERVER_URL = 'wss://livekit.example.test';
+}
+
+// The handler snapshots env at module load, so set it before import.
+setLiveKitEnv();
+const { handleLiveKitToken } = await import('../../api/agents/_id/livekit-token.js');
+
+async function invoke(id = AGENT_ID) {
+ const req = makeReq({ method: 'GET', url: `/api/agents/${id}/livekit-token` });
+ const res = makeRes();
+ await handleLiveKitToken(req, res, id);
+ return res;
+}
+
+beforeEach(() => {
+ sessionUser = { id: OWNER_ID };
+ agentRow = { id: AGENT_ID };
+ vi.clearAllMocks();
+});
+
+afterAll(() => {
+ delete process.env.LIVEKIT_API_KEY;
+ delete process.env.LIVEKIT_API_SECRET;
+ delete process.env.LIVEKIT_SERVER_URL;
+});
+
+describe('GET /api/agents/:id/livekit-token', () => {
+ it('mints a verifiable room JWT for the owner', async () => {
+ const res = await invoke();
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.serverUrl).toBe('wss://livekit.example.test');
+
+ const { payload } = await jwtVerify(
+ body.token,
+ new TextEncoder().encode(SECRET),
+ { issuer: KEY },
+ );
+ expect(payload.sub).toBe(`user-${OWNER_ID}`);
+ expect(payload.video.room).toBe(`agent-${AGENT_ID}`);
+ expect(payload.video.roomJoin).toBe(true);
+ expect(payload.video.canPublish).toBe(true);
+ expect(payload.exp - payload.nbf).toBe(3600);
+ });
+
+ it('401s without auth', async () => {
+ sessionUser = null;
+ const res = await invoke();
+ expect(res.statusCode).toBe(401);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('404s for an agent the caller does not own (no token leaks)', async () => {
+ sessionUser = { id: 'user-stranger' };
+ agentRow = null;
+ const res = await invoke();
+ expect(res.statusCode).toBe(404);
+ expect(JSON.parse(res.body).token).toBeUndefined();
+ });
+
+ it('404s on a non-uuid agent id', async () => {
+ const res = await invoke('not-a-uuid');
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('503s by design when LiveKit is not configured', async () => {
+ delete process.env.LIVEKIT_API_SECRET;
+ // The handler reads the module-level snapshot, so re-import with env unset.
+ vi.resetModules();
+ const { handleLiveKitToken: fresh } = await import('../../api/agents/_id/livekit-token.js');
+ const req = makeReq({ method: 'GET', url: `/api/agents/${AGENT_ID}/livekit-token` });
+ const res = makeRes();
+ await fresh(req, res, AGENT_ID);
+ expect(res.statusCode).toBe(503);
+ expect(JSON.parse(res.body).error).toBe('livekit_not_configured');
+ setLiveKitEnv();
+ });
+});
diff --git a/tests/api/agents-memory-seed.test.js b/tests/api/agents-memory-seed.test.js
new file mode 100644
index 000000000..8475bcab0
--- /dev/null
+++ b/tests/api/agents-memory-seed.test.js
@@ -0,0 +1,148 @@
+// Tests for POST /api/agents/:id/memory-seed (api/agents/_id/memory-seed.js),
+// the preset GitHub seed.
+//
+// The catalog/selection/facts logic lives in api/_lib/github-seed.js and is
+// covered by tests/github-memory-seed.test.js. What this pins at the boundary:
+// auth and ownership are enforced before any GitHub token is touched, a user
+// without a GitHub connection gets the actionable 412 (never a crash), the
+// happy path distills facts and writes them through ONE transaction that first
+// clears the previous seed, and the CSRF gate runs on session-cookie writes.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { makeReq, makeRes } from '../_helpers/monetization.js';
+
+const AGENT_ID = '00000000-0000-4000-8000-0000000000a4';
+const OWNER_ID = 'user-owner';
+
+let agentRow = { id: AGENT_ID };
+let connRow = { access_token: 'encrypted', username: 'auditagent02' };
+const txCalls = [];
+const sqlMock = vi.fn((strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ const fragment = { strings, values, q };
+ if (/from agent_identities/i.test(q)) Object.assign(fragment, { _rows: agentRow ? [agentRow] : [] });
+ if (/from social_connections/i.test(q)) Object.assign(fragment, { _rows: connRow ? [connRow] : [] });
+ return Object.assign(Promise.resolve(fragment._rows ?? []), fragment);
+});
+sqlMock.transaction = vi.fn(async (fragments) => {
+ txCalls.push(fragments.map((f) => f.q || String(f.strings?.join(' ') || f)));
+ return [];
+});
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: sqlMock,
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+let sessionUser = { id: OWNER_ID };
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => sessionUser),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+const csrfMock = vi.fn(async () => true);
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: (...a) => csrfMock(...a) }));
+
+// The real requireCsrf writes the 403 itself and returns false; the mock must
+// do the same so the handler's early return leaves a faithful response.
+function csrfReject(_req, res) {
+ res.statusCode = 403;
+ res.end(JSON.stringify({ error: 'csrf_invalid', error_description: 'CSRF token invalid or expired' }));
+ return false;
+}
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { memorySeed: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../../api/_lib/github-token.js', () => ({
+ decryptGithubToken: vi.fn(async () => 'ghp_plain'),
+}));
+
+vi.mock('../../api/_lib/github-api.js', () => ({
+ fetchProfile: vi.fn(async () => ({ login: 'auditagent02', name: 'Audit', bio: 'probe', public_repos: 1 })),
+ fetchPinnedRepos: vi.fn(async () => [{ full_name: 'auditagent02/pinned-one', name: 'pinned-one', description: 'd', html_url: 'https://github.com/auditagent02/pinned-one' }]),
+ fetchRepos: vi.fn(async () => [{ full_name: 'auditagent02/repo-one', name: 'repo-one', description: 'd', html_url: 'https://github.com/auditagent02/repo-one' }]),
+ fetchReadme: vi.fn(async () => '# pinned-one\na readme'),
+}));
+
+const llmMock = vi.fn(async () => ({ text: '["ships TypeScript CLI tools","maintains the audit harness"]' }));
+vi.mock('../../api/_lib/llm.js', () => ({ llmComplete: (...a) => llmMock(...a) }));
+
+const { default: handleMemorySeed } = await import('../../api/agents/_id/memory-seed.js');
+
+async function invoke(body = {}) {
+ const req = makeReq({ method: 'POST', url: `/api/agents/${AGENT_ID}/memory-seed`, body });
+ const res = makeRes();
+ await handleMemorySeed(req, res, AGENT_ID);
+ return res;
+}
+
+beforeEach(() => {
+ sessionUser = { id: OWNER_ID };
+ agentRow = { id: AGENT_ID };
+ connRow = { access_token: 'encrypted', username: 'auditagent02' };
+ txCalls.length = 0;
+ vi.clearAllMocks();
+ sqlMock.transaction.mockClear();
+});
+
+describe('POST /api/agents/:id/memory-seed', () => {
+ it('seeds memories from the default catalog through one atomic transaction', async () => {
+ const res = await invoke();
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.seeded).toBe(2);
+ expect(body.facts).toEqual(['ships TypeScript CLI tools', 'maintains the audit harness']);
+ expect(body.selection).toBeDefined();
+
+ // The previous seed is cleared and the new rows inserted atomically.
+ expect(sqlMock.transaction).toHaveBeenCalledOnce();
+ const statements = txCalls[0];
+ expect(statements[0]).toMatch(/delete from agent_memories/i);
+ expect(statements.length).toBe(1 + 2);
+ expect(statements.slice(1).every((s) => /insert into agent_memories/i.test(s))).toBe(true);
+ });
+
+ it('runs the CSRF gate for session-cookie writes', async () => {
+ await invoke();
+ expect(csrfMock).toHaveBeenCalled();
+ });
+
+ it('aborts before touching GitHub when CSRF fails', async () => {
+ csrfMock.mockImplementationOnce(csrfReject);
+ const res = await invoke();
+ expect(res.statusCode).toBe(403);
+ expect(JSON.parse(res.body).error).toBe('csrf_invalid');
+ const { decryptGithubToken } = await import('../../api/_lib/github-token.js');
+ expect(decryptGithubToken).not.toHaveBeenCalled();
+ });
+
+ it('401s without auth', async () => {
+ sessionUser = null;
+ const res = await invoke();
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('404s for an agent the caller does not own', async () => {
+ agentRow = null;
+ const res = await invoke();
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('412s with an actionable error when GitHub is not connected', async () => {
+ connRow = null;
+ const res = await invoke();
+ expect(res.statusCode).toBe(412);
+ expect(JSON.parse(res.body).error).toBe('not_connected');
+ });
+
+ it('405s on GET', async () => {
+ const req = makeReq({ method: 'GET', url: `/api/agents/${AGENT_ID}/memory-seed` });
+ const res = makeRes();
+ await handleMemorySeed(req, res, AGENT_ID);
+ expect(res.statusCode).toBe(405);
+ });
+});
diff --git a/tests/api/avatars-upload-proxy.test.js b/tests/api/avatars-upload-proxy.test.js
index 618278cd3..f9eac19ae 100644
--- a/tests/api/avatars-upload-proxy.test.js
+++ b/tests/api/avatars-upload-proxy.test.js
@@ -189,4 +189,31 @@ describe('POST /api/avatars/upload', () => {
expect(res.statusCode).toBe(200);
expect(body.storage_key).toBe('u/user-test-1/my-cool-avatar/abc123.glb');
});
+
+ // Regression: Cloud Run's Express layer pre-drains the request stream and
+ // stashes the bytes on req.rawBody/req.body before the handler runs (see
+ // server/index.mjs captureRawBody). A raw-stream reader that ignores those
+ // buffers resolves with zero bytes and 400s every production upload with
+ // `empty_body`. Simulate the Express-shaped request and assert the captured
+ // body is used.
+ it('uses the pre-drained req.rawBody/req.body when the stream is already consumed', async () => {
+ const glbBytes = makeFakeGlb(128);
+ const req = makeReq({ body: Buffer.alloc(0) }); // ended empty stream
+ req.rawBody = glbBytes;
+ req.body = glbBytes;
+ const { res, body } = await dispatchUpload(req, makeRes());
+ expect(res.statusCode).toBe(200);
+ expect(body.size_bytes).toBe(glbBytes.length);
+ expect(putObjectMock).toHaveBeenCalledOnce();
+ expect(putObjectMock.mock.calls[0][0].body).toEqual(glbBytes);
+ });
+
+ it('still 400s empty_body when the pre-drained body is empty', async () => {
+ const req = makeReq({ body: Buffer.alloc(0) });
+ req.rawBody = Buffer.alloc(0);
+ req.body = Buffer.alloc(0);
+ const { res, body } = await dispatchUpload(req, makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('empty_body');
+ });
});