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(agents-api): answer a malformed id with a 400 instead of a Postgres 500, and require CSRF to mint a session

nirholas05ebc17485f4
diff --git a/api/agent/session.js b/api/agent/session.js
index 1d1ddab2c..0a1ebb6df 100644
--- a/api/agent/session.js
+++ b/api/agent/session.js
@@ -12,12 +12,14 @@
// commands: { node, docker } // ready-to-run launch strings
// }
//
-// Auth: requires a signed-in session or an existing bearer token.
+// Auth: requires a signed-in session (plus an X-CSRF-Token header) or an
+// existing bearer token.
import { SignJWT } from 'jose';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { isUuid } from '../_lib/validate.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { env } from '../_lib/env.js';
import { sql } from '../_lib/db.js';
@@ -64,6 +66,12 @@ export default wrap(async (req, res) => {
|| null;
if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
+ // Minting a 7-day bearer token is a state-changing POST, and a cookie rides
+ // along automatically on a cross-site request. requireCsrf exempts bearer
+ // callers (the token is its own proof of intent), so only the browser path
+ // pays for it, exactly as the other cookie-authenticated mutations do.
+ if (!(await requireCsrf(req, res, userId))) return;
+
// Bound the body: this is a two-field request, and passing `res` here as the
// limit disabled the size cap entirely (every comparison against an object
// is false), letting one caller stream an unbounded body into memory.
diff --git a/api/agents/balances.js b/api/agents/balances.js
index cc838f7a3..2cc1ccc64 100644
--- a/api/agents/balances.js
+++ b/api/agents/balances.js
@@ -188,8 +188,9 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
+ // getSessionUser returns the user row, so the id lives on `.id` (not `.userId`).
const auth = await getSessionUser(req).catch(() => null);
- const rl = await limits.walletRead(auth?.userId || clientIp(req));
+ const rl = await limits.walletRead(auth?.id || clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const body = await readJson(req).catch(() => null);
@@ -209,7 +210,7 @@ export default wrap(async (req, res) => {
const entries = rows.map((row) => ({
agentId: row.id,
address: row.meta?.solana_address || null,
- isOwner: !!(auth && row.user_id === auth.userId),
+ isOwner: !!(auth && row.user_id === auth.id),
ownerId: row.user_id,
forkedFrom: row.meta?.forked_from || null,
summary: null,
diff --git a/api/agents/by-wallet.js b/api/agents/by-wallet.js
index eceff2f91..932b681af 100644
--- a/api/agents/by-wallet.js
+++ b/api/agents/by-wallet.js
@@ -24,7 +24,14 @@ export default wrap(async (req, res) => {
return error(res, 400, 'validation_error', 'invalid wallet address');
}
const address = raw.toLowerCase();
- const chainId = Number(url.searchParams.get('chain_id')) || null;
+ // A non-numeric chain_id used to coerce to NaN and then to null, silently
+ // dropping the filter and returning every chain's agents as if the caller had
+ // asked for that. A filter that cannot be honored is a 400, not a wider result.
+ const rawChainId = (url.searchParams.get('chain_id') || '').trim();
+ if (rawChainId && !/^[0-9]+$/.test(rawChainId)) {
+ return error(res, 400, 'validation_error', 'chain_id must be a positive integer');
+ }
+ const chainId = rawChainId ? Number(rawChainId) : null;
const rows = chainId
? await sql`
diff --git a/api/agents/capabilities.js b/api/agents/capabilities.js
index 82f82d446..2e27d294e 100644
--- a/api/agents/capabilities.js
+++ b/api/agents/capabilities.js
@@ -18,6 +18,7 @@ import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { isUuid } from '../_lib/validate.js';
import { solUsdPrice } from '../_lib/avatar-wallet.js';
import { getSpendLimits, setSpendLimits, SpendLimitError } from '../_lib/agent-trade-guards.js';
import {
@@ -155,6 +156,9 @@ async function handleSettings(req, res, id, userId) {
// ── POST revoke / revoke-all ────────────────────────────────────────────────────
async function handleRevoke(req, res, id, userId, cid) {
+ // The capability id is a uuid column; a malformed one reaches Postgres as
+ // error 22P02 and would surface as a 500. An unknown grant is a 404 either way.
+ if (!isUuid(cid)) return error(res, 404, 'not_found', 'capability not found');
const existing = await getCapability(cid);
if (!existing || String(existing.agent_id) !== String(id)) {
return error(res, 404, 'not_found', 'capability not found');
diff --git a/api/agents/check-name.js b/api/agents/check-name.js
index 28ad959bd..0c7f55404 100644
--- a/api/agents/check-name.js
+++ b/api/agents/check-name.js
@@ -3,6 +3,7 @@
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
+import { isUuid } from '../_lib/validate.js';
import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -34,7 +35,12 @@ export default wrap(async (req, res) => {
const url = new URL(req.url, 'http://x');
const name = (url.searchParams.get('name') || '').trim();
+ // agent_id feeds a `WHERE id != $1` against a uuid column. A malformed value
+ // otherwise surfaces Postgres 22P02 to the caller as a 500; reject it here.
const agentId = (url.searchParams.get('agent_id') || '').trim() || null;
+ if (agentId && !isUuid(agentId)) {
+ return error(res, 400, 'validation_error', 'agent_id must be a uuid');
+ }
if (!name) return json(res, 200, { available: false, reason: 'invalid' });
diff --git a/api/agents/economy.js b/api/agents/economy.js
index 2bc56187c..84f06e562 100644
--- a/api/agents/economy.js
+++ b/api/agents/economy.js
@@ -13,6 +13,7 @@
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { isUuid } from '../_lib/validate.js';
import {
agentEconomySummary,
getHireById,
@@ -23,6 +24,15 @@ import {
rateHire,
} from '../_lib/agent-economy.js';
+// Every id below lands in a `WHERE col = $1` against a uuid column. Without this
+// gate a malformed id reaches Postgres and comes back as error 22P02, which the
+// wrap boundary can only render as a 500. A caller typo has to be a 400 instead.
+function badId(res, field, value) {
+ if (value == null || isUuid(value)) return false;
+ error(res, 400, 'validation_error', `${field} must be a uuid`);
+ return true;
+}
+
async function handleGet(req, res) {
const url = new URL(req.url, 'http://x');
const view = url.searchParams.get('view') || 'offers';
@@ -30,6 +40,7 @@ async function handleGet(req, res) {
if (view === 'offers') {
const limit = Number(url.searchParams.get('limit')) || 60;
const providerAgentId = url.searchParams.get('agentId') || null;
+ if (badId(res, 'agentId', providerAgentId)) return;
const offers = await listOffersWithStats({ limit, providerAgentId });
return json(res, 200, { data: { offers } }, { 'cache-control': 'public, max-age=15' });
}
@@ -45,9 +56,11 @@ async function handleGet(req, res) {
if (view === 'hires') {
const agentId = url.searchParams.get('agentId');
if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');
+ if (badId(res, 'agentId', agentId)) return;
const role = url.searchParams.get('role') || 'all';
const limit = Number(url.searchParams.get('limit')) || 40;
const beforeId = url.searchParams.get('beforeId') || null;
+ if (badId(res, 'beforeId', beforeId)) return;
const hires = await listHiresForAgent(agentId, { role, limit, beforeId });
const next_cursor = hires.length === limit ? hires[hires.length - 1].id : null;
return json(res, 200, { data: { hires, next_cursor } });
@@ -56,6 +69,7 @@ async function handleGet(req, res) {
if (view === 'summary') {
const agentId = url.searchParams.get('agentId');
if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');
+ if (badId(res, 'agentId', agentId)) return;
const [summary, reputation] = await Promise.all([
agentEconomySummary(agentId),
providerStats(agentId),
@@ -78,6 +92,7 @@ async function handlePost(req, res) {
const { hireId, rating } = body;
if (!hireId) return error(res, 400, 'validation_error', 'hireId is required');
+ if (badId(res, 'hireId', hireId)) return;
const hire = await getHireById(hireId);
if (!hire) return error(res, 404, 'not_found', 'hire not found');