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.

security: SSRF guard, CSRF gates, header-origin pinning, fail-closed crons

nirholas65ca0552f0a6
diff --git a/api/_lib/ssrf-guard.js b/api/_lib/ssrf-guard.js
new file mode 100644
index 000000000..80a00add1
--- /dev/null
+++ b/api/_lib/ssrf-guard.js
@@ -0,0 +1,112 @@
+// SSRF guard for fetches that follow a user- or DB-supplied URL.
+//
+// Resolves the hostname to every A/AAAA record and rejects if any address lands
+// in RFC1918, loopback, link-local, unique-local, multicast, reserved, or cloud
+// metadata ranges. Caller fetches normally after the check. This does NOT pin
+// the resolved IP — a hostile DNS server could swap the record between the
+// check and the connect (DNS rebinding). The TOCTOU window is tiny for one-shot
+// fetches and the upside of staying on the platform fetch path outweighs it for
+// our use cases (image/glb fetch from random user URLs).
+
+import { promises as dns } from 'node:dns';
+import net from 'node:net';
+
+// Cloud metadata services we never want a server-side fetch to reach.
+const METADATA_IPS = new Set([
+ '169.254.169.254', // AWS / Azure / GCP / Oracle / Alibaba IMDS
+ 'fd00:ec2::254', // AWS IMDSv2 IPv6
+ '100.100.100.200', // Alibaba
+]);
+
+function isPrivateIPv4(ip) {
+ const o = ip.split('.').map(Number);
+ if (o.length !== 4 || o.some((n) => Number.isNaN(n) || n < 0 || n > 255)) return true;
+ if (o[0] === 10) return true; // 10.0.0.0/8
+ if (o[0] === 172 && o[1] >= 16 && o[1] <= 31) return true; // 172.16.0.0/12
+ if (o[0] === 192 && o[1] === 168) return true; // 192.168.0.0/16
+ if (o[0] === 127) return true; // loopback
+ if (o[0] === 169 && o[1] === 254) return true; // link-local + metadata
+ if (o[0] === 0) return true; // 0.0.0.0/8
+ if (o[0] >= 224) return true; // multicast 224/4 + reserved 240/4
+ if (o[0] === 100 && o[1] >= 64 && o[1] <= 127) return true; // CGNAT 100.64/10
+ if (o[0] === 198 && (o[1] === 18 || o[1] === 19)) return true; // benchmarking 198.18/15
+ return false;
+}
+
+function isPrivateIPv6(ip) {
+ const lower = ip.toLowerCase();
+ if (lower === '::1' || lower === '::' || lower === '0:0:0:0:0:0:0:1') return true; // loopback / unspecified
+ if (lower.startsWith('fe80:') || lower.startsWith('fe8') || lower.startsWith('fe9') ||
+ lower.startsWith('fea') || lower.startsWith('feb')) return true; // link-local fe80::/10
+ if (lower.startsWith('fc') || lower.startsWith('fd')) return true; // unique-local fc00::/7
+ if (lower.startsWith('ff')) return true; // multicast ff00::/8
+ if (lower.startsWith('::ffff:')) {
+ const v4 = lower.slice(7);
+ return isPrivateIPv4(v4);
+ }
+ return false;
+}
+
+function isBlockedAddress(ip) {
+ if (METADATA_IPS.has(ip.toLowerCase())) return true;
+ const fam = net.isIP(ip);
+ if (fam === 4) return isPrivateIPv4(ip);
+ if (fam === 6) return isPrivateIPv6(ip);
+ return true; // unparseable → reject
+}
+
+export class SsrfBlockedError extends Error {
+ constructor(reason) {
+ super(reason);
+ this.code = 'ssrf_blocked';
+ this.status = 400;
+ }
+}
+
+// Parse + protocol-check + DNS-resolve + per-address allowlist check. Throws
+// `SsrfBlockedError` on any failure. Returns the parsed URL on success.
+export async function assertSafePublicUrl(input, { allowHttp = false } = {}) {
+ if (!input || typeof input !== 'string') throw new SsrfBlockedError('url must be a string');
+ let url;
+ try {
+ url = new URL(input);
+ } catch {
+ throw new SsrfBlockedError('url is not a valid URL');
+ }
+ if (url.protocol === 'http:' && !allowHttp) {
+ throw new SsrfBlockedError('http:// not allowed — use https://');
+ }
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ throw new SsrfBlockedError(`unsupported protocol ${url.protocol}`);
+ }
+ const host = url.hostname;
+ if (!host) throw new SsrfBlockedError('url missing hostname');
+ // Literal IP in the URL? Check directly without DNS.
+ const literal = net.isIP(host);
+ if (literal) {
+ if (isBlockedAddress(host)) {
+ throw new SsrfBlockedError(`host ${host} resolves to a blocked range`);
+ }
+ return url;
+ }
+ let records;
+ try {
+ records = await dns.lookup(host, { all: true, verbatim: true });
+ } catch (err) {
+ throw new SsrfBlockedError(`dns lookup failed for ${host}: ${err.code || err.message}`);
+ }
+ if (!records?.length) throw new SsrfBlockedError(`no addresses for ${host}`);
+ for (const r of records) {
+ if (isBlockedAddress(r.address)) {
+ throw new SsrfBlockedError(`host ${host} resolves to a blocked range`);
+ }
+ }
+ return url;
+}
+
+// Convenience: assert + fetch. Uses the global fetch. Same options as fetch,
+// minus that the URL must pass `assertSafePublicUrl`.
+export async function fetchSafePublicUrl(input, init = {}, opts = {}) {
+ const url = await assertSafePublicUrl(input, opts);
+ return fetch(url.toString(), init);
+}
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index b1e4ff9a1..a9562a7c0 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -637,9 +637,11 @@ export function send402(res, opts = {}) {
// Resolve the canonical resource URL the client hit, so the facilitator can
// match the payer's signed payload against the same string we advertise.
-export function resolveResourceUrl(req, path) {
- const proto = (req.headers['x-forwarded-proto'] || 'https').toString().split(',')[0].trim();
- const host = (req.headers['x-forwarded-host'] || req.headers.host || '').toString();
- if (host) return `${proto}://${host}${path}`;
+//
+// We always anchor on env.APP_ORIGIN (set via PUBLIC_APP_ORIGIN) rather than
+// trusting `x-forwarded-host` / `host`. Trusting those headers lets a caller
+// craft a 402 challenge that advertises an attacker-controlled `resource.url`,
+// which agents may then call or display.
+export function resolveResourceUrl(_req, path) {
return `${env.APP_ORIGIN}${path}`;
}
diff --git a/api/a-og.js b/api/a-og.js
index 9506d1a06..5ac852cd1 100644
--- a/api/a-og.js
+++ b/api/a-og.js
@@ -8,6 +8,7 @@
* accept image/svg+xml for OG images, so we avoid canvas/sharp at edge.
*/
+import { env } from './_lib/env.js';
import { cors, wrap, error } from './_lib/http.js';
import { resolveOnChainAgent, shortenAddr } from './_lib/onchain.js';
@@ -29,7 +30,11 @@ export default wrap(async (req, res) => {
const agent = await resolveOnChainAgent({ chainId, agentId });
if (format === 'json') {
- const origin = url.searchParams.get('origin') || 'https://three.ws/';
+ // Anchor on env.APP_ORIGIN. A previous version honored an `origin` query
+ // param, which let a caller inject arbitrary URLs into `url` and `image`
+ // in the returned JSON. Consumers of this oEmbed-style endpoint trust
+ // those fields, so we never echo a caller-supplied origin.
+ const origin = env.APP_ORIGIN;
const pageUrl = `${origin}/a/${chainId}/${agentId}`;
const imageUrl = `${origin}/api/a-og?chain=${chainId}&id=${encodeURIComponent(agentId)}`;
const status = agent.error && !agent.name ? 404 : 200;
diff --git a/api/admin/rider-passes.js b/api/admin/rider-passes.js
index 8b08e1bc8..376fd4ebe 100644
--- a/api/admin/rider-passes.js
+++ b/api/admin/rider-passes.js
@@ -1,10 +1,16 @@
import { sql } from '../_lib/db.js';
import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
import { requireAdmin } from '../_lib/admin.js';
+import { requireCsrf } from '../_lib/csrf.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
- if (!(await requireAdmin(req, res))) return;
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+
+ if (req.method === 'POST' || req.method === 'DELETE') {
+ if (!(await requireCsrf(req, res, admin.id))) return;
+ }
if (req.method === 'GET') {
const passes = await sql`
diff --git a/api/admin/user/[id].js b/api/admin/user/[id].js
index 070195d30..b15c20545 100644
--- a/api/admin/user/[id].js
+++ b/api/admin/user/[id].js
@@ -5,6 +5,7 @@ import { z } from 'zod';
import { sql } from '../../_lib/db.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { requireAdmin } from '../../_lib/admin.js';
+import { requireCsrf } from '../../_lib/csrf.js';
import { parse } from '../../_lib/validate.js';
const patchSchema = z.object({
@@ -16,11 +17,16 @@ const patchSchema = z.object({
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,PATCH,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'PATCH'])) return;
- if (!await requireAdmin(req, res)) return;
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
const id = req.url.split('/').pop().split('?')[0];
if (!id) return error(res, 400, 'bad_request', 'missing user id');
+ if (req.method === 'PATCH') {
+ if (!(await requireCsrf(req, res, admin.id))) return;
+ }
+
if (req.method === 'GET') {
const [user] = await sql`
select
diff --git a/api/admin/withdrawals/[id].js b/api/admin/withdrawals/[id].js
index 4db99dd9c..c35707e60 100644
--- a/api/admin/withdrawals/[id].js
+++ b/api/admin/withdrawals/[id].js
@@ -4,6 +4,7 @@
import { z } from 'zod';
import { sql } from '../../_lib/db.js';
import { requireAdmin } from '../../_lib/admin.js';
+import { requireCsrf } from '../../_lib/csrf.js';
import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
import { parse } from '../../_lib/validate.js';
import { insertNotification } from '../../_lib/notify.js';
@@ -21,7 +22,9 @@ const patchBody = z.object({
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'PATCH,OPTIONS', credentials: true })) return;
if (!method(req, res, ['PATCH'])) return;
- if (!(await requireAdmin(req, res))) return;
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+ if (!(await requireCsrf(req, res, admin.id))) return;
const id = req.query?.id;
const body = parse(patchBody, await readJson(req));
diff --git a/api/agents.js b/api/agents.js
index e85ab3322..e84000280 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -11,9 +11,10 @@
* DELETE /api/agents/:id/wallet — unlink wallet
*/
-import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from './_lib/auth.js';
import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
+import { requireCsrf } from './_lib/csrf.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { generateAgentWallet, generateSolanaAgentWallet } from './_lib/agent-wallet.js';
import { publicUrl } from './_lib/r2.js';
@@ -165,6 +166,8 @@ async function handleGetOrCreateMe(req, res, auth) {
async function handleCreate(req, res) {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');
+ const scopeErr = requireScopeForMutation(auth, res, 'avatars:write');
+ if (scopeErr) return scopeErr;
const body = await readJson(req);
const name = String(body.name || 'Agent')
@@ -267,18 +270,21 @@ export async function handleGetOne(req, res, id) {
if (req.method === 'PUT') {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
return handleUpdate(req, res, id, auth);
}
if (req.method === 'PATCH') {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
return handlePatchEdits(req, res, id, auth);
}
if (req.method === 'DELETE') {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
return handleDelete(req, res, id, auth);
}
}
@@ -286,6 +292,8 @@ export async function handleGetOne(req, res, id) {
// ── Update ────────────────────────────────────────────────────────────────
async function handleUpdate(req, res, id, auth) {
+ const scopeErr = requireScopeForMutation(auth, res, 'avatars:write');
+ if (scopeErr) return scopeErr;
const [existing] = await sql`
SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
`;
@@ -316,6 +324,8 @@ async function handlePatchEdits(req, res, id, auth) {
// ── Delete ────────────────────────────────────────────────────────────────
async function handleDelete(req, res, id, auth) {
+ const scopeErr = requireScopeForMutation(auth, res, 'avatars:delete');
+ if (scopeErr) return scopeErr;
const [existing] = await sql`
SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
`;
@@ -340,6 +350,7 @@ export async function handleWallet(req, res, id) {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
const [existing] = await sql`
SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
@@ -394,9 +405,20 @@ async function healStaleAvatarId(row) {
async function resolveAuth(req) {
const session = await getSessionUser(req);
- if (session) return { userId: session.id, source: 'session' };
+ if (session) return { userId: session.id, source: 'session', scope: null };
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId, source: 'bearer' };
+ if (bearer) return { userId: bearer.userId, source: 'bearer', scope: bearer.scope || '' };
+ return null;
+}
+
+// Bearer-token callers must hold the matching avatars:* scope before they can
+// mutate an agent. Session callers (browser cookies) are not constrained by
+// scope. Returns null when authorized, or an error response otherwise.
+function requireScopeForMutation(auth, res, requiredScope) {
+ if (!auth || auth.source !== 'bearer') return null;
+ if (!hasScope(auth.scope, requiredScope)) {
+ return error(res, 403, 'insufficient_scope', `${requiredScope} required`);
+ }
return null;
}
diff --git a/api/auth/siwe/[action].js b/api/auth/siwe/[action].js
index 0f421befb..81d6cbb9b 100644
--- a/api/auth/siwe/[action].js
+++ b/api/auth/siwe/[action].js
@@ -137,6 +137,18 @@ async function handleVerify(req, res) {
if (fields.notBefore && Date.parse(fields.notBefore) > now) {
return error(res, 400, 'not_yet_valid', 'message not yet valid');
}
+ // Defense-in-depth: reject messages whose `issuedAt` is far in the past or
+ // future. The nonce table caps replay too, but a stale signature paired
+ // with a long-lived nonce should still fail closed. 10 min window matches
+ // the EIP-4361 spec recommendation.
+ if (fields.issuedAt) {
+ const issued = Date.parse(fields.issuedAt);
+ if (Number.isFinite(issued)) {
+ const skew = 10 * 60 * 1000;
+ if (issued < now - skew) return error(res, 400, 'stale_message', 'issuedAt too old');
+ if (issued > now + skew) return error(res, 400, 'future_message', 'issuedAt in the future');
+ }
+ }
// 4. Nonce must exist, be unconsumed, and not expired. Burn on success.
const [nonceRow] = await sql`
diff --git a/api/avatar-og.js b/api/avatar-og.js
index 774245501..368819fa6 100644
--- a/api/avatar-og.js
+++ b/api/avatar-og.js
@@ -22,6 +22,7 @@
import { sql } from './_lib/db.js';
import { getAvatar } from './_lib/avatars.js';
import { DEMO_AVATARS } from './_lib/demo-avatars.js';
+import { env } from './_lib/env.js';
import { cors, wrap } from './_lib/http.js';
import { publicUrl, putObject } from './_lib/r2.js';
import { renderGlbToPng } from './_lib/render-glb.js';
@@ -182,13 +183,11 @@ function extractIdFromPath(pathname) {
return m ? m[1] : null;
}
-function sendFallbackLogo(req, res) {
- // 302 to the static brand logo. The crawler then fetches
- // /assets/og-image.png directly from Vercel's edge.
- const proto = String(req.headers['x-forwarded-proto'] || 'https').split(',')[0].trim();
- const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';
+function sendFallbackLogo(_req, res) {
+ // 302 to the static brand logo. Anchor on env.APP_ORIGIN so a caller can't
+ // craft an `x-forwarded-host` that redirects this 302 to an attacker site.
res.statusCode = 302;
- res.setHeader('location', `${proto}://${host}/assets/og-image.png`);
+ res.setHeader('location', `${env.APP_ORIGIN}/assets/og-image.png`);
res.setHeader('cache-control', CACHE_FALLBACK);
res.end();
}
diff --git a/api/chat/proxy.js b/api/chat/proxy.js
index 7af38cbe5..03b663402 100644
--- a/api/chat/proxy.js
+++ b/api/chat/proxy.js
@@ -1,5 +1,6 @@
import { env } from '../_lib/env.js';
import { cors, error, json, method, wrap, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
const UPGRADE_URL = `${env.APP_ORIGIN}/pricing`;
@@ -10,6 +11,16 @@ export default wrap(async (req, res) => {
if (!env.OPENROUTER_API_KEY)
return error(res, 503, 'not_configured', 'Built-in model not available');
+ // Anonymous proxy — only :free models pass the gate below, but the upstream
+ // free-tier quota is shared across our OpenRouter key. Cap per-IP to prevent
+ // a single client from draining the free quota and rate-limiting everyone.
+ const ip = clientIp(req);
+ const rl = await limits.chatIp(ip);
+ if (!rl.success) {
+ res.setHeader('retry-after', '60');
+ return error(res, 429, 'rate_limited', 'too many requests');
+ }
+
let body;
try {
body = await readJson(req);
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 3de97dfab..cf04ce55b 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -111,7 +111,7 @@ async function handleErc8004Crawl(req, res) {
const auth = req.headers['authorization'] || '';
const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
@@ -400,7 +400,7 @@ async function handleIndexDelegations(req, res) {
const auth = req.headers['authorization'] || '';
const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
@@ -835,7 +835,7 @@ async function handlePumpfunMonitor(req, res) {
const auth = req.headers['authorization'] || '';
const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
@@ -984,7 +984,7 @@ async function handlePumpfunSignals(req, res) {
const auth = req.headers['authorization'] || '';
const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
@@ -2187,7 +2187,7 @@ async function handleSolanaAttestEventCleanup(req, res) {
const auth = req.headers['authorization'] || '';
const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
@@ -2217,7 +2217,7 @@ async function handleSolanaAttestationsCrawl(req, res) {
const auth = req.headers['authorization'] || '';
const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
@@ -2578,7 +2578,7 @@ async function handleRunXScheduledPosts(req, res) {
const auth = req.headers['authorization'] || '';
const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
@@ -2646,7 +2646,7 @@ async function handleRunXTriggers(req, res) {
const auth = req.headers['authorization'] || '';
const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
@@ -2864,7 +2864,7 @@ async function handleFetchXMetrics(req, res) {
const auth = req.headers['authorization'] || '';
const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
@@ -2951,7 +2951,7 @@ async function handleRunCoinCycle(req, res) {
const auth = req.headers['authorization'] || '';
const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
@@ -3054,7 +3054,7 @@ async function handleRunCoinPayouts(req, res) {
const auth = req.headers['authorization'] || '';
const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
+ if (!fromCron && (!expected || auth !== expected)) {
return error(res, 401, 'unauthorized', 'cron secret required');
}
diff --git a/api/keys/[id].js b/api/keys/[id].js
index 315b38451..5cadaa93d 100644
--- a/api/keys/[id].js
+++ b/api/keys/[id].js
@@ -4,6 +4,7 @@ import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { logAudit } from '../_lib/audit.js';
import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { limits } from '../_lib/rate-limit.js';
export default wrap(async (req, res) => {
@@ -13,6 +14,8 @@ export default wrap(async (req, res) => {
const user = await getSessionUser(req);
if (!user) return error(res, 401, 'unauthorized', 'sign in to manage API keys');
+ if (!(await requireCsrf(req, res, user.id))) return;
+
const rl = await limits.apiKeyManage(user.id);
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
diff --git a/api/keys/index.js b/api/keys/index.js
index 4bb74b724..1142f69e7 100644
--- a/api/keys/index.js
+++ b/api/keys/index.js
@@ -6,6 +6,7 @@ import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { randomToken, sha256 } from '../_lib/crypto.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { limits } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
import { z } from 'zod';
@@ -41,6 +42,8 @@ export default wrap(async (req, res) => {
return json(res, 200, { keys: rows });
}
+ if (!(await requireCsrf(req, res, user.id))) return;
+
const body = parse(createSchema, await readJson(req));
const requestedScopes = body.scope.split(/\s+/).filter(Boolean);
diff --git a/api/payments/solana/[action].js b/api/payments/solana/[action].js
index b451107e3..e4e891c14 100644
--- a/api/payments/solana/[action].js
+++ b/api/payments/solana/[action].js
@@ -80,8 +80,11 @@ async function handleConfirm(req, res) {
if (!tx) return error(res, 422, 'tx_not_found', 'transaction not found');
if (tx.meta?.err) return error(res, 422, 'tx_failed', 'transaction failed on-chain');
const memoIx = tx.transaction.message.instructions.find((ix) => ix.programId?.toString() === 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
- const memo = memoIx?.parsed;
- if (memo && memo !== intent.nonce) return error(res, 422, 'memo_mismatch', 'transaction memo does not match intent nonce');
+ // Memo carries the per-intent nonce. Require it: a tx without a memo (or
+ // with a memo of any non-string type) is a replay or wrong-intent attempt
+ // even if the on-chain transfer numbers happen to line up.
+ const memo = typeof memoIx?.parsed === 'string' ? memoIx.parsed : null;
+ if (!memo || memo !== intent.nonce) return error(res, 422, 'memo_mismatch', 'transaction memo does not match intent nonce');
const expectedRecipient = intent.recipient;
const expectedAtomics = BigInt(Math.round(Number(intent.amount_usdc) * 1_000_000));
const tokenBalances = tx.meta?.postTokenBalances || [];
diff --git a/api/pump/helius-webhook.js b/api/pump/helius-webhook.js
index 70a59bc28..0ae4eb876 100644
--- a/api/pump/helius-webhook.js
+++ b/api/pump/helius-webhook.js
@@ -15,17 +15,23 @@
// webhookURL: `${env.APP_ORIGIN}/api/pump/helius-webhook`,
// });
+import { timingSafeEqual } from 'node:crypto';
import { sql } from '../_lib/db.js';
import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
import { parsePumpTrades } from '../_lib/helius.js';
+function safeEqual(a, b) {
+ if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false;
+ return timingSafeEqual(Buffer.from(a), Buffer.from(b));
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
const expected = process.env.HELIUS_WEBHOOK_AUTH;
if (!expected) return error(res, 503, 'not_configured', 'helius webhook auth not set');
- if (req.headers.authorization !== expected) {
+ if (!safeEqual(String(req.headers.authorization || ''), expected)) {
return error(res, 401, 'unauthorized', 'bad auth header');
}
diff --git a/api/rider/webhook.js b/api/rider/webhook.js
index bbbfdded2..6deba4453 100644
--- a/api/rider/webhook.js
+++ b/api/rider/webhook.js
@@ -1,3 +1,4 @@
+import { timingSafeEqual } from 'node:crypto';
import { sql } from '../_lib/db.js';
import { json, method, wrap, error, readJson } from '../_lib/http.js';
import { env } from '../_lib/env.js';
@@ -5,11 +6,21 @@ import { env } from '../_lib/env.js';
const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
const REQUIRED_AMOUNT = 8000;
+function safeEqual(a, b) {
+ if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false;
+ return timingSafeEqual(Buffer.from(a), Buffer.from(b));
+}
+
export default wrap(async (req, res) => {
if (!method(req, res, ['POST'])) return;
+ // Fail closed: when the webhook secret isn't configured this endpoint must
+ // not accept anonymous writes — it inserts rider_passes rows that grant
+ // access. (Previous form: `if (secret && ...)` silently accepted anything.)
const secret = env.RIDER_HELIUS_WEBHOOK_SECRET;
- if (secret && req.headers.authorization !== `Bearer ${secret}`) {
+ if (!secret) return error(res, 503, 'not_configured', 'rider webhook secret not set');
+ const presented = String(req.headers.authorization || '');
+ if (!safeEqual(presented, `Bearer ${secret}`)) {
return error(res, 401, 'unauthorized', 'invalid webhook secret');
}
diff --git a/api/x402/model-check.js b/api/x402/model-check.js
index 59b9bcb2d..3224e8e9f 100644
--- a/api/x402/model-check.js
+++ b/api/x402/model-check.js
@@ -24,6 +24,7 @@ import {
} from '../_lib/x402-spec.js';
import { env } from '../_lib/env.js';
import { inspectModel, suggestOptimizations } from '../_lib/model-inspect.js';
+import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
const ROUTE = '/api/x402/model-check';
const MAX_FETCH_BYTES = 16 * 1024 * 1024;
@@ -170,17 +171,14 @@ function buildRequirements(resourceUrl) {
async function fetchAndInspect(targetUrl) {
let parsed;
try {
- parsed = new URL(targetUrl);
- } catch {
- const err = new Error('url is not a valid URL');
- err.code = 'invalid_url';
- err.status = 400;
- throw err;
- }
- if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
- const err = new Error('url must be http(s)');
- err.code = 'invalid_url';
- err.status = 400;
+ parsed = await assertSafePublicUrl(targetUrl, { allowHttp: true });
+ } catch (err) {
+ if (err instanceof SsrfBlockedError) {
+ const e = new Error(err.message);
+ e.code = 'invalid_url';
+ e.status = 400;
+ throw e;
+ }
throw err;
}
let upstream;
diff --git a/public/admin/index.html b/public/admin/index.html
index 69cae1f2f..d30c52276 100644
--- a/public/admin/index.html
+++ b/public/admin/index.html
@@ -124,9 +124,42 @@
</div>
<script>
+// Single-use CSRF token: server burns it on every state-changing call. The
+// cache is invalidated immediately after we read it so the next mutation pulls
+// a fresh one.
+let _csrfToken = null;
+async function getCsrfToken() {
+ if (_csrfToken) return _csrfToken;
+ const r = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) return null;
+ const j = await r.json();
+ _csrfToken = j?.data?.token || null;
+ return _csrfToken;
+}
+
const api = {
get: (url) => fetch(url, { credentials: 'include' }).then((r) => r.json()),
- patch: (url, body) => fetch(url, { method: 'PATCH', credentials: 'include', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }).then((r) => r.json()),
+ patch: async (url, body) => {
+ const csrf = await getCsrfToken();
+ _csrfToken = null;
+ const headers = { 'content-type': 'application/json' };
+ if (csrf) headers['x-csrf-token'] = csrf;
+ return fetch(url, { method: 'PATCH', credentials: 'include', headers, body: JSON.stringify(body) }).then((r) => r.json());
+ },
+ post: async (url, body) => {
+ const csrf = await getCsrfToken();
+ _csrfToken = null;
+ const headers = { 'content-type': 'application/json' };
+ if (csrf) headers['x-csrf-token'] = csrf;
+ return fetch(url, { method: 'POST', credentials: 'include', headers, body: body == null ? undefined : JSON.stringify(body) }).then((r) => r.json());
+ },
+ delete: async (url, body) => {
+ const csrf = await getCsrfToken();
+ _csrfToken = null;
+ const headers = body ? { 'content-type': 'application/json' } : {};
+ if (csrf) headers['x-csrf-token'] = csrf;
+ return fetch(url, { method: 'DELETE', credentials: 'include', headers, body: body ? JSON.stringify(body) : undefined }).then((r) => r.json());
+ },
};
let state = { tab: 'overview', usersPage: 1, usersQ: '', usersPlan: '', statsData: null };
diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.js
index e608d0bfd..134448ee1 100644
--- a/public/dashboard/dashboard.js
+++ b/public/dashboard/dashboard.js
@@ -58,11 +58,30 @@ export const api = {
},
};
+// Single-use CSRF token: fetched lazily, invalidated on consumption. Re-issued
+// on the next mutating call.
+let _csrfToken = null;
+async function getCsrfToken() {
+ if (_csrfToken) return _csrfToken;
+ const r = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) return null;
+ const j = await r.json();
+ _csrfToken = j?.data?.token || null;
+ return _csrfToken;
+}
+
async function j(method, path, body) {
+ const headers = body ? { 'content-type': 'application/json' } : {};
+ // State-changing methods: attach CSRF token (single-use, server burns it).
+ if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') {
+ const csrf = await getCsrfToken();
+ if (csrf) headers['x-csrf-token'] = csrf;
+ _csrfToken = null;
+ }
const res = await fetch(path, {
method,
credentials: 'include',
- headers: body ? { 'content-type': 'application/json' } : {},
+ headers,
body: body ? JSON.stringify(body) : undefined,
});
const data = res.headers.get('content-type')?.includes('application/json')
diff --git a/src/agent-identity.js b/src/agent-identity.js
index cdc217c35..9aa82356a 100644
--- a/src/agent-identity.js
+++ b/src/agent-identity.js
@@ -13,6 +13,28 @@ import { AgentMemory } from './agent-memory.js';
const STORAGE_KEY = 'agent_identity';
+// Single-use CSRF token cache. Required by /api/agents PUT/PATCH/DELETE +
+// /api/agents/:id/wallet on the server. Token is burned on consumption.
+let _csrfToken = null;
+async function getCsrfToken() {
+ if (_csrfToken) return _csrfToken;
+ try {
+ const r = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) return null;
+ const j = await r.json();
+ _csrfToken = j?.data?.token || null;
+ return _csrfToken;
+ } catch {
+ return null;
+ }
+}
+
+async function csrfHeaders() {
+ const csrf = await getCsrfToken();
+ _csrfToken = null;
+ return csrf ? { 'x-csrf-token': csrf } : {};
+}
+
/**
* @typedef {Object} AgentRecord
* @property {string} id
@@ -95,9 +117,10 @@ export class AgentIdentity {
if (!this._record) return;
this._persist();
try {
+ const csrf = await csrfHeaders();
const resp = await fetch(`/api/agents/${this._record.id}`, {
method: 'PUT',
- headers: { 'content-type': 'application/json' },
+ headers: { 'content-type': 'application/json', ...csrf },
credentials: 'include',
body: JSON.stringify({
name: this._record.name,
@@ -132,9 +155,10 @@ export class AgentIdentity {
async linkWallet(address, chainId) {
await this.update({ walletAddress: address, chainId });
try {
+ const csrf = await csrfHeaders();
await fetch(`/api/agents/${this.id}/wallet`, {
method: 'POST',
- headers: { 'content-type': 'application/json' },
+ headers: { 'content-type': 'application/json', ...csrf },
credentials: 'include',
body: JSON.stringify({ wallet_address: address, chain_id: chainId }),
});
@@ -144,8 +168,10 @@ export class AgentIdentity {
async unlinkWallet() {
await this.update({ walletAddress: null, chainId: null });
try {
+ const csrf = await csrfHeaders();
await fetch(`/api/agents/${this.id}/wallet`, {
method: 'DELETE',
+ headers: csrf,
credentials: 'include',
});
} catch {}
diff --git a/tests/api/avatar-og.test.js b/tests/api/avatar-og.test.js
index f174b3ca9..7f882e648 100644
--- a/tests/api/avatar-og.test.js
+++ b/tests/api/avatar-og.test.js
@@ -263,7 +263,11 @@ describe('GET /api/avatar/:id/og — server render path', () => {
expect(res2.statusCode).toBe(200);
});
- it('uses forwarded host + proto for the fallback redirect origin', async () => {
+ it('ignores forwarded host and anchors the fallback redirect on APP_ORIGIN', async () => {
+ // Previously this endpoint built the redirect from `x-forwarded-host`,
+ // which let a caller redirect OG crawlers (or end users) to an
+ // attacker-controlled host by spoofing the header. The handler now
+ // always uses env.APP_ORIGIN.
getAvatarMock.mockResolvedValueOnce({
id: 'a7',
name: 'X',
@@ -283,6 +287,6 @@ describe('GET /api/avatar/:id/og — server render path', () => {
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(302);
- expect(res._h.location).toBe('https://staging.three.ws/assets/og-image.png');
+ expect(res._h.location).toBe('http://localhost:3000/assets/og-image.png');
});
});
diff --git a/tests/api/chat-proxy-ratelimit.test.js b/tests/api/chat-proxy-ratelimit.test.js
new file mode 100644
index 000000000..00422994e
--- /dev/null
+++ b/tests/api/chat-proxy-ratelimit.test.js
@@ -0,0 +1,134 @@
+// /api/chat/proxy.js forwards requests to OpenRouter using our shared API key.
+// The endpoint is intentionally unauthenticated (it's the in-browser fallback
+// chat used by anonymous visitors), but only :free upstream models are allowed.
+// Without per-IP rate limiting, a single client could drain the shared free
+// quota for everyone — this test pins the rate-limit behavior.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const rateLimitState = {
+ chatIp: { success: true },
+};
+
+vi.mock('../../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://localhost:3000', OPENROUTER_API_KEY: 'sk-or-test' },
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ chatIp: vi.fn(async () => rateLimitState.chatIp),
+ },
+ clientIp: vi.fn(() => '203.0.113.7'),
+}));
+
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));
+vi.mock('../../api/_lib/zauth.js', () => ({
+ instrument: vi.fn(() => null),
+ drain: vi.fn(async () => {}),
+}));
+
+// Stub global fetch — we never want to hit OpenRouter from a unit test.
+const fetchMock = vi.fn();
+globalThis.fetch = fetchMock;
+
+const { default: handler } = await import('../../api/chat/proxy.js');
+
+function makeReq({ method = 'POST', headers = {}, body = null } = {}) {
+ const stream = body
+ ? Readable.from([Buffer.from(JSON.stringify(body))])
+ : Readable.from([]);
+ stream.method = method;
+ stream.url = '/api/chat/proxy';
+ stream.headers = {
+ host: 'localhost',
+ ...(body ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ };
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += String(chunk);
+ this.writableEnded = true;
+ },
+ write(chunk) {
+ if (chunk !== undefined) this.body += String(chunk);
+ },
+ };
+}
+
+beforeEach(() => {
+ rateLimitState.chatIp = { success: true };
+ fetchMock.mockReset();
+});
+
+describe('POST /api/chat/proxy — per-IP rate limit', () => {
+ it('returns 429 when the per-IP limiter rejects the request', async () => {
+ rateLimitState.chatIp = { success: false };
+ const req = makeReq({ body: { model: 'meta-llama/llama-3-8b-instruct:free', messages: [] } });
+ const res = makeRes();
+
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(429);
+ const body = JSON.parse(res.body);
+ expect(body.error).toBe('rate_limited');
+ expect(res.getHeader('retry-after')).toBe('60');
+ // Upstream fetch must NOT have been called.
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rate-limit runs before upstream, even with valid free-tier model', async () => {
+ rateLimitState.chatIp = { success: false };
+ fetchMock.mockResolvedValue({
+ status: 200,
+ body: null,
+ text: async () => '',
+ headers: { get: () => null },
+ });
+ const req = makeReq({ body: { model: 'mistral:free', messages: [{ role: 'user', content: 'hi' }] } });
+ const res = makeRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(429);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('passes through when limiter approves the request', async () => {
+ rateLimitState.chatIp = { success: true };
+ fetchMock.mockResolvedValue({
+ status: 200,
+ body: null,
+ text: async () => '{"id":"x"}',
+ headers: { get: (k) => (k === 'content-type' ? 'application/json' : null) },
+ });
+ const req = makeReq({ body: { model: 'mistral:free', messages: [] } });
+ const res = makeRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0][0]).toContain('openrouter.ai');
+ });
+
+ it('rejects non-:free models without calling upstream', async () => {
+ rateLimitState.chatIp = { success: true };
+ const req = makeReq({ body: { model: 'gpt-4', messages: [] } });
+ const res = makeRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('invalid_model');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/api/security-csrf-gates.test.js b/tests/api/security-csrf-gates.test.js
new file mode 100644
index 000000000..829f2b3a3
--- /dev/null
+++ b/tests/api/security-csrf-gates.test.js
@@ -0,0 +1,466 @@
+// Verify that state-changing API endpoints reject requests missing a valid
+// CSRF token. Each endpoint is exercised with the same shared mock harness so
+// the gates are checked uniformly. Bearer-auth callers are exempt (bearers
+// aren't auto-attached by browsers, so CSRF can't be forged with them).
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// ── Shared mock state ─────────────────────────────────────────────────────
+
+const authState = {
+ session: null, // { id, is_admin?, wallet_address? }
+ bearer: null, // { userId, scope, source }
+};
+
+const sqlState = {
+ queue: [], // FIFO of mock results
+ calls: [], // captured (query, values) pairs
+ csrfRows: new Map(), // token → { user_id, expires_at }
+};
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn((req) => {
+ const h = req?.headers?.authorization || '';
+ if (!h.toLowerCase().startsWith('bearer ')) return null;
+ return h.slice(7).trim();
+ }),
+ hasScope: vi.fn(() => true),
+}));
+
+vi.mock('../../api/_lib/admin.js', () => ({
+ requireAdmin: vi.fn(async (req, res) => {
+ if (!authState.session?.is_admin) {
+ res.statusCode = 403;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ error: 'forbidden' }));
+ return null;
+ }
+ return authState.session;
+ }),
+}));
+
+// The csrf.js module reads/writes the csrf_tokens table via `sql`. We intercept
+// those calls by inspecting the tagged-template strings the module sends and
+// serving from sqlState.csrfRows for SELECTs.
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: Object.assign(
+ vi.fn(async (strings, ...values) => {
+ const q = typeof strings === 'string' ? strings : strings.join('?');
+ sqlState.calls.push({ query: q, values });
+
+ // CSRF lookup: `SELECT user_id FROM csrf_tokens WHERE token = ${sent} AND expires_at > now()`
+ if (/from csrf_tokens/i.test(q) && /^\s*select/i.test(q)) {
+ const submitted = values[0];
+ const row = sqlState.csrfRows.get(submitted);
+ if (row && row.expires_at > Date.now()) return [{ user_id: row.user_id }];
+ return [];
+ }
+ // CSRF burn: `DELETE FROM csrf_tokens WHERE token = ${sent}`
+ if (/from csrf_tokens/i.test(q) && /^\s*delete/i.test(q)) {
+ sqlState.csrfRows.delete(values[0]);
+ return [];
+ }
+
+ if (sqlState.queue.length === 0) return [];
+ return sqlState.queue.shift();
+ }),
+ {
+ transaction: vi.fn(async (queries) => {
+ for (const q of queries) await q;
+ return [];
+ }),
+ },
+ ),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: new Proxy(
+ {},
+ {
+ get: () => async () => ({ success: true }),
+ },
+ ),
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../../api/_lib/agent-wallet.js', () => ({
+ generateAgentWallet: vi.fn(async () => ({ address: '0xaa', encrypted_key: 'k' })),
+ generateSolanaAgentWallet: vi.fn(async () => ({ address: 'sol', encrypted_secret: 's' })),
+}));
+
+vi.mock('../../api/_lib/notify.js', () => ({
+ insertNotification: vi.fn(() => {}),
+}));
+
+vi.mock('../../api/_lib/validate.js', () => ({
+ parse: vi.fn((schema, data) => schema.parse(data)),
+}));
+
+vi.mock('../../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://localhost:3000', ADMIN_ADDRESSES: new Set() },
+}));
+
+vi.mock('../../api/_lib/sentry.js', () => ({
+ captureException: vi.fn(),
+}));
+
+vi.mock('../../api/_lib/zauth.js', () => ({
+ instrument: vi.fn(() => null),
+ drain: vi.fn(async () => {}),
+}));
+
+vi.mock('../../api/_lib/r2.js', () => ({
+ publicUrl: vi.fn((key) => `https://r2.example/${key}`),
+}));
+
+// Import the handlers under test AFTER mocks are wired.
+const { default: agentsRoot, handleGetOne, handleWallet } = await import(
+ '../../api/agents.js'
+);
+const { default: keysHandler } = await import('../../api/keys/index.js');
+const { default: keyByIdHandler } = await import('../../api/keys/[id].js');
+const { default: adminUserHandler } = await import('../../api/admin/user/[id].js');
+const { default: adminWithdrawalsHandler } = await import(
+ '../../api/admin/withdrawals/[id].js'
+);
+const { default: adminRiderPassesHandler } = await import('../../api/admin/rider-passes.js');
+
+// ── helpers ───────────────────────────────────────────────────────────────
+
+function makeReq({ method = 'GET', url = '/', headers = {}, body = null, query = {} } = {}) {
+ const stream = body
+ ? Readable.from([Buffer.from(JSON.stringify(body))])
+ : Readable.from([]);
+ stream.method = method;
+ stream.url = url;
+ stream.query = query;
+ stream.headers = {
+ host: 'localhost',
+ ...(body ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ };
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += String(chunk);
+ this.writableEnded = true;
+ },
+ write(chunk) {
+ if (chunk !== undefined) this.body += String(chunk);
+ },
+ };
+}
+
+function parseRes(res) {
+ if (!res.body) return null;
+ try {
+ return JSON.parse(res.body);
+ } catch {
+ return null;
+ }
+}
+
+function issueCsrfFor(userId, token = 'tok-' + Math.random().toString(36).slice(2)) {
+ sqlState.csrfRows.set(token, { user_id: userId, expires_at: Date.now() + 60_000 });
+ return token;
+}
+
+beforeEach(() => {
+ authState.session = null;
+ authState.bearer = null;
+ sqlState.queue = [];
+ sqlState.calls = [];
+ sqlState.csrfRows.clear();
+});
+
+// ── /api/keys POST ────────────────────────────────────────────────────────
+
+describe('POST /api/keys — CSRF gate', () => {
+ it('rejects POST without X-CSRF-Token (403 csrf_missing)', async () => {
+ authState.session = { id: 'user-1' };
+ const req = makeReq({
+ method: 'POST',
+ url: '/api/keys',
+ body: { name: 'My key' },
+ });
+ const res = makeRes();
+ await keysHandler(req, res);
+ const body = parseRes(res);
+ expect(res.statusCode).toBe(403);
+ expect(body.error).toBe('csrf_missing');
+ });
+
+ it('rejects POST with an unknown token (403 csrf_invalid)', async () => {
+ authState.session = { id: 'user-1' };
+ const req = makeReq({
+ method: 'POST',
+ url: '/api/keys',
+ headers: { 'x-csrf-token': 'not-a-real-token' },
+ body: { name: 'My key' },
+ });
+ const res = makeRes();
+ await keysHandler(req, res);
+ const body = parseRes(res);
+ expect(res.statusCode).toBe(403);
+ expect(body.error).toBe('csrf_invalid');
+ });
+
+ it('proceeds when a valid CSRF token is presented', async () => {
+ authState.session = { id: 'user-2' };
+ const token = issueCsrfFor('user-2');
+ // The handler reads CSRF, then INSERTs the key — queue one row.
+ sqlState.queue.push([
+ {
+ id: 'k1',
+ name: 'My key',
+ prefix: 'sk_live_xx',
+ scope: 'avatars:read',
+ expires_at: null,
+ created_at: '2024-01-01T00:00:00Z',
+ },
+ ]);
+ const req = makeReq({
+ method: 'POST',
+ url: '/api/keys',
+ headers: { 'x-csrf-token': token },
+ body: { name: 'My key' },
+ });
+ const res = makeRes();
+ await keysHandler(req, res);
+ const body = parseRes(res);
+ expect(res.statusCode).toBe(201);
+ expect(body.key.id).toBe('k1');
+ });
+
+ it('burns the CSRF token (single-use)', async () => {
+ authState.session = { id: 'user-3' };
+ const token = issueCsrfFor('user-3');
+ sqlState.queue.push([{ id: 'k1', name: 'k', prefix: 'sk_live_x', scope: 'avatars:read', expires_at: null, created_at: '2024-01-01T00:00:00Z' }]);
+
+ const req1 = makeReq({ method: 'POST', url: '/api/keys', headers: { 'x-csrf-token': token }, body: { name: 'k' } });
+ await keysHandler(req1, makeRes());
+
+ // Give the fire-and-forget DELETE a tick to settle.
+ await new Promise((r) => setImmediate(r));
+
+ // Second use of the same token must be rejected.
+ const req2 = makeReq({ method: 'POST', url: '/api/keys', headers: { 'x-csrf-token': token }, body: { name: 'k' } });
+ const res2 = makeRes();
+ await keysHandler(req2, res2);
+ expect(res2.statusCode).toBe(403);
+ expect(parseRes(res2).error).toBe('csrf_invalid');
+ });
+
+ it('bearer authorization bypasses CSRF (stateless auth)', async () => {
+ authState.bearer = { userId: 'user-4', scope: 'profile', source: 'apikey' };
+ // /api/keys requires getSessionUser for now; bearer alone returns 401.
+ // Skip: this endpoint is session-only by design.
+ });
+});
+
+// ── /api/agents — single-resource mutations ───────────────────────────────
+
+describe('PUT/DELETE /api/agents/:id — CSRF gate', () => {
+ const AGENT_ID = '11111111-1111-1111-1111-111111111111';
+
+ it('PUT rejects without CSRF (403 csrf_missing)', async () => {
+ authState.session = { id: 'user-5' };
+ const req = makeReq({
+ method: 'PUT',
+ url: `/api/agents/${AGENT_ID}`,
+ body: { name: 'updated' },
+ });
+ const res = makeRes();
+ await handleGetOne(req, res, AGENT_ID);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+
+ it('DELETE rejects without CSRF (403 csrf_missing)', async () => {
+ authState.session = { id: 'user-5' };
+ const req = makeReq({
+ method: 'DELETE',
+ url: `/api/agents/${AGENT_ID}`,
+ });
+ const res = makeRes();
+ await handleGetOne(req, res, AGENT_ID);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+
+ it('PATCH rejects without CSRF (403 csrf_missing)', async () => {
+ authState.session = { id: 'user-5' };
+ const req = makeReq({
+ method: 'PATCH',
+ url: `/api/agents/${AGENT_ID}`,
+ body: { name: 'updated' },
+ });
+ const res = makeRes();
+ await handleGetOne(req, res, AGENT_ID);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+});
+
+describe('POST/DELETE /api/agents/:id/wallet — CSRF gate', () => {
+ const AGENT_ID = '22222222-2222-2222-2222-222222222222';
+
+ it('POST rejects without CSRF', async () => {
+ authState.session = { id: 'user-6' };
+ const req = makeReq({
+ method: 'POST',
+ url: `/api/agents/${AGENT_ID}/wallet`,
+ body: { wallet_address: '0xdead' },
+ });
+ const res = makeRes();
+ await handleWallet(req, res, AGENT_ID);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+
+ it('DELETE rejects without CSRF', async () => {
+ authState.session = { id: 'user-6' };
+ const req = makeReq({
+ method: 'DELETE',
+ url: `/api/agents/${AGENT_ID}/wallet`,
+ });
+ const res = makeRes();
+ await handleWallet(req, res, AGENT_ID);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+});
+
+// ── /api/admin/user/:id ───────────────────────────────────────────────────
+
+describe('PATCH /api/admin/user/:id — CSRF gate', () => {
+ it('rejects PATCH without CSRF (admin auth alone is not enough)', async () => {
+ authState.session = { id: 'admin-1', is_admin: true };
+ const req = makeReq({
+ method: 'PATCH',
+ url: '/api/admin/user/abc',
+ body: { plan: 'pro' },
+ });
+ const res = makeRes();
+ await adminUserHandler(req, res);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+
+ it('proceeds when a valid CSRF token is presented', async () => {
+ authState.session = { id: 'admin-1', is_admin: true };
+ const token = issueCsrfFor('admin-1');
+ sqlState.queue.push([
+ { id: 'u1', email: '[email protected]', plan: 'pro', is_admin: false, deleted_at: null },
+ ]);
+ const req = makeReq({
+ method: 'PATCH',
+ url: '/api/admin/user/u1',
+ headers: { 'x-csrf-token': token },
+ body: { plan: 'pro' },
+ });
+ const res = makeRes();
+ await adminUserHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ expect(parseRes(res).user.id).toBe('u1');
+ });
+});
+
+// ── /api/admin/withdrawals/:id ────────────────────────────────────────────
+
+describe('PATCH /api/admin/withdrawals/:id — CSRF gate', () => {
+ it('rejects PATCH without CSRF', async () => {
+ authState.session = { id: 'admin-2', is_admin: true };
+ const req = makeReq({
+ method: 'PATCH',
+ url: '/api/admin/withdrawals/w1',
+ query: { id: 'w1' },
+ body: { status: 'processing', tx_signature: 'tx-123' },
+ });
+ const res = makeRes();
+ await adminWithdrawalsHandler(req, res);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+});
+
+// ── /api/admin/rider-passes ───────────────────────────────────────────────
+
+describe('POST/DELETE /api/admin/rider-passes — CSRF gate', () => {
+ it('POST rejects without CSRF', async () => {
+ authState.session = { id: 'admin-3', is_admin: true };
+ const req = makeReq({
+ method: 'POST',
+ url: '/api/admin/rider-passes',
+ body: { wallet_address: '0xabc' },
+ });
+ const res = makeRes();
+ await adminRiderPassesHandler(req, res);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+
+ it('DELETE rejects without CSRF', async () => {
+ authState.session = { id: 'admin-3', is_admin: true };
+ const req = makeReq({
+ method: 'DELETE',
+ url: '/api/admin/rider-passes',
+ body: { wallet_address: '0xabc' },
+ });
+ const res = makeRes();
+ await adminRiderPassesHandler(req, res);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+
+ it('GET is not gated (read-only)', async () => {
+ authState.session = { id: 'admin-3', is_admin: true };
+ sqlState.queue.push([]);
+ const req = makeReq({ method: 'GET', url: '/api/admin/rider-passes' });
+ const res = makeRes();
+ await adminRiderPassesHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ });
+});
+
+// ── /api/agents (root) is unaffected ──────────────────────────────────────
+
+describe('POST /api/agents — creation path remains unchanged', () => {
+ it('POST without CSRF still works (root endpoint not gated)', async () => {
+ authState.session = { id: 'user-7' };
+ sqlState.queue.push([
+ {
+ id: 'a1',
+ user_id: 'user-7',
+ name: 'A',
+ skills: [],
+ meta: {},
+ created_at: '2024-01-01T00:00:00Z',
+ },
+ ]);
+ const req = makeReq({
+ method: 'POST',
+ url: '/api/agents',
+ body: { name: 'A' },
+ });
+ const res = makeRes();
+ await agentsRoot(req, res);
+ expect(res.statusCode).toBe(201);
+ });
+});
diff --git a/tests/api/siwe-handler.test.js b/tests/api/siwe-handler.test.js
index 7b09f1b88..36e0b48b3 100644
--- a/tests/api/siwe-handler.test.js
+++ b/tests/api/siwe-handler.test.js
@@ -111,6 +111,8 @@ async function invoke(opts) {
// verifyMessage mock returns the same address so signer === claimed.
const WALLET_ADDR = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045';
const TEST_NONCE = 'testNonce1234567890ab';
+// Use a fresh issuedAt so the handler's anti-stale freshness check accepts it.
+const ISSUED_AT = new Date().toISOString();
const SIWE_MESSAGE = [
'localhost wants you to sign in with your Ethereum account:',
WALLET_ADDR,
@@ -119,7 +121,7 @@ const SIWE_MESSAGE = [
'Version: 1',
'Chain ID: 1',
`Nonce: ${TEST_NONCE}`,
- 'Issued At: 2024-01-01T00:00:00.000Z',
+ `Issued At: ${ISSUED_AT}`,
].join('\n');
const FUTURE = new Date(Date.now() + 300_000).toISOString();
diff --git a/tests/pumpfun-signals.test.js b/tests/pumpfun-signals.test.js
index 77d14a6e8..b0a5d8d37 100644
--- a/tests/pumpfun-signals.test.js
+++ b/tests/pumpfun-signals.test.js
@@ -74,7 +74,9 @@ describe('pumpfun-signals cron', () => {
// Subsequent sql calls: insert returning [{id}] for each insert.
sqlMock.mockResolvedValue([{ id: 1 }]);
- const req = { headers: {}, method: 'POST' };
+ // Real Vercel cron requests carry `x-vercel-cron: 1`; without it the
+ // handler now fails closed when CRON_SECRET is unset.
+ const req = { headers: { 'x-vercel-cron': '1' }, method: 'POST' };
const res = mockRes();
await handler(req, res);