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(pump): require same-site intent before a cookie session can rewrite coin autopilot

nirholas87797fa44c0d
diff --git a/api/pump/autopilot.js b/api/pump/autopilot.js
index db302ff77..76e2aab0e 100644
--- a/api/pump/autopilot.js
+++ b/api/pump/autopilot.js
@@ -14,16 +14,30 @@
*/
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import {
+ getSessionUser,
+ authenticateBearer,
+ extractBearer,
+ isSameSiteOrigin,
+} from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { z } from 'zod';
-async function resolveUserId(req) {
+/**
+ * Resolve the caller to { userId, viaCookie }, or null when unauthenticated.
+ *
+ * `viaCookie` drives the CSRF gate below. A POST here rewrites the policy that
+ * gates the buyback and payout crons, so a cross-site form riding the session
+ * cookie could pause an owner's buyback or flip it to full-swap without them
+ * ever seeing it. Bearer callers are exempt: the token itself is the proof of
+ * intent. Same rule the pump dispatcher applies to its cookie-borne writes.
+ */
+async function resolveCaller(req) {
const session = await getSessionUser(req);
- if (session) return session.id;
+ if (session) return { userId: session.id, viaCookie: true };
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return bearer.userId;
+ if (bearer) return { userId: bearer.userId, viaCookie: false };
return null;
}
@@ -56,14 +70,17 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const userId = await resolveUserId(req);
- if (!userId) return error(res, 401, 'unauthorized', 'sign in to manage autopilot');
+ const caller = await resolveCaller(req);
+ if (!caller) return error(res, 401, 'unauthorized', 'sign in to manage autopilot');
+ if (req.method === 'POST' && caller.viaCookie && !isSameSiteOrigin(req)) {
+ return error(res, 403, 'forbidden', 'cross-site request blocked');
+ }
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- if (req.method === 'POST') return upsertPolicy(req, res, userId);
- return listCoins(req, res, userId);
+ if (req.method === 'POST') return upsertPolicy(req, res, caller.userId);
+ return listCoins(req, res, caller.userId);
});
// ── GET — coins + policy + activity ──────────────────────────────────────────
diff --git a/prompts/swarm-100/api-pump-01.md b/prompts/swarm-100/api-pump-01.md
deleted file mode 100644
index 629e3686d..000000000
--- a/prompts/swarm-100/api-pump-01.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# API audit: api/pump batch 01 (10 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/pump/[action].js
-- api/pump/accept-payment-confirm.js
-- api/pump/accept-payment-prep.js
-- api/pump/autopilot.js
-- api/pump/balances.js
-- api/pump/by-agent.js
-- api/pump/channel-feed.js
-- api/pump/check-three-balance.js
-- api/pump/coin-intel.js
-- api/pump/curve.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-pump-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/tests/api/pump-autopilot.test.js b/tests/api/pump-autopilot.test.js
new file mode 100644
index 000000000..c889396dc
--- /dev/null
+++ b/tests/api/pump-autopilot.test.js
@@ -0,0 +1,145 @@
+// Tests for GET/POST /api/pump/autopilot: the per-coin policy that gates the
+// run-buyback and run-distribute-payments crons.
+//
+// The DB, auth, and rate limiter are mocked: no network, no chain. The focus is
+// the CSRF gate on the write path. A POST here rewrites money-moving automation
+// (pause a buyback, flip it to full-swap), so a cross-site form riding the
+// session cookie must never reach the policy write, while bearer callers (agent
+// keys, workers) stay exempt because the token itself proves intent.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const authState = { session: null, bearer: null };
+vi.mock('../../api/_lib/auth.js', async () => {
+ const actual = await vi.importActual('../../api/_lib/auth.js');
+ return {
+ ...actual,
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn(() => null),
+ };
+});
+
+const sqlState = { queue: [], calls: [] };
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ return sqlState.queue.length ? sqlState.queue.shift() : [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: new Proxy({}, { get: () => vi.fn(async () => ({ success: true })) }),
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+function makeReq({ method = 'GET', url = '/api/pump/autopilot', headers = {}, body = null } = {}) {
+ const req = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
+ req.method = method;
+ req.url = url;
+ req.headers = {
+ host: 'localhost',
+ origin: 'https://three.ws',
+ ...(body ? { 'content-type': 'application/json' } : {}),
+ ...headers,
+ };
+ return req;
+}
+function makeRes() {
+ return {
+ statusCode: 200, headers: {}, body: '', writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ };
+}
+async function invoke(opts) {
+ const { default: handler } = await import('../../api/pump/autopilot.js');
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ return { res, json: res.body ? JSON.parse(res.body) : null };
+}
+
+const MINT = 'MintPubkey1111111111111111111111111111';
+
+describe('/api/pump/autopilot', () => {
+ beforeEach(() => {
+ authState.session = null;
+ authState.bearer = null;
+ sqlState.queue = [];
+ sqlState.calls = [];
+ });
+
+ it('401s an unauthenticated read', async () => {
+ const { res, json } = await invoke({ method: 'GET' });
+ expect(res.statusCode).toBe(401);
+ expect(json.error).toBe('unauthorized');
+ });
+
+ it('serves the caller their own coins on a session read', async () => {
+ authState.session = { id: 'user-1' };
+ sqlState.queue = [[]];
+ const { res, json } = await invoke({ method: 'GET' });
+ expect(res.statusCode).toBe(200);
+ expect(json).toEqual({ coins: [], activity: [] });
+ });
+
+ it('rejects a cross-site POST riding the session cookie, before any write', async () => {
+ authState.session = { id: 'user-1' };
+ const { res, json } = await invoke({
+ method: 'POST',
+ headers: { origin: 'https://evil.example' },
+ body: { mint: MINT, buyback_full_swap: true },
+ });
+ expect(res.statusCode).toBe(403);
+ expect(json.error).toBe('forbidden');
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('rejects a cookie-authed POST carrying neither Origin nor Referer', async () => {
+ authState.session = { id: 'user-1' };
+ const { res } = await invoke({
+ method: 'POST',
+ headers: { origin: undefined },
+ body: { mint: MINT },
+ });
+ expect(res.statusCode).toBe(403);
+ });
+
+ it('does not gate bearer-authed writes', async () => {
+ authState.bearer = { userId: 'user-1' };
+ const { res } = await invoke({
+ method: 'POST',
+ headers: { origin: 'https://evil.example' },
+ body: { mint: MINT },
+ });
+ // Past the gate: the coin lookup returns nothing, so this 404s on data,
+ // never on the CSRF gate.
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('leaves reads open to a cookie session with no Origin', async () => {
+ authState.session = { id: 'user-1' };
+ sqlState.queue = [[]];
+ const { res } = await invoke({ method: 'GET', headers: { origin: undefined } });
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('404s a same-site write for a coin the caller does not own', async () => {
+ authState.session = { id: 'user-1' };
+ sqlState.queue = [[]];
+ const { res, json } = await invoke({ method: 'POST', body: { mint: MINT } });
+ expect(res.statusCode).toBe(404);
+ expect(json.error).toBe('not_found');
+ });
+
+ it('400s a write whose mint is too short to be a pubkey', async () => {
+ authState.session = { id: 'user-1' };
+ const { res, json } = await invoke({ method: 'POST', body: { mint: 'short' } });
+ expect(res.statusCode).toBe(400);
+ expect(json.error).toBe('bad_request');
+ });
+});
diff --git a/tests/api/pump.test.js b/tests/api/pump.test.js
index 36aec3568..4e669e5a1 100644
--- a/tests/api/pump.test.js
+++ b/tests/api/pump.test.js
@@ -539,6 +539,27 @@ describe('GET /api/pump/by-agent', () => {
const { res } = await invoke(handler, { method: 'GET', url: '/api/pump/by-agent' });
expect(res.statusCode).toBe(400);
});
+
+ it('scopes last_burn_at to confirmed runs, not every attempt', async () => {
+ // A bare max(created_at) reported the last time the buyback cron ran at
+ // all. An agent with thousands of `skipped` rows and zero burns then
+ // answered {runs: 0, total_burned: '0', last_burn_at: <minutes ago>},
+ // and the dashboard rendered a burn that never happened.
+ sqlState.queue = [
+ [{ id: 'mint-1', mint: mintB58, network: 'mainnet', name: 'Foo', symbol: 'FOO', buyback_bps: 500, agent_authority: walletB58 }],
+ [{ confirmed_payments: 0, unique_payers: 0, total_atomics: '0', last_payment_at: null }],
+ [{ runs: 0, total_burned: '0', last_burn_at: null }],
+ ];
+ const handler = pumpAction('by-agent');
+ const { res } = await invoke(handler, {
+ method: 'GET',
+ url: '/api/pump/by-agent?agent_id=00000000-0000-0000-0000-000000000001',
+ });
+ expect(res.statusCode).toBe(200);
+ const burnQuery = sqlState.calls.find((c) => /pump_buyback_runs/.test(String(c.query)) && /last_burn_at/.test(String(c.query)));
+ expect(burnQuery).toBeTruthy();
+ expect(String(burnQuery.query)).toMatch(/max\(created_at\)\s*filter\s*\(where status='confirmed'\)/);
+ });
});
describe('POST /api/pump/withdraw-confirm', () => {
@@ -752,4 +773,36 @@ describe('cookie-CSRF gate on pump mutations (2026-07-23 audit)', () => {
// Past the gate; may fail later on input validation, never on the CSRF gate.
expect(res.statusCode).not.toBe(403);
});
+
+ // The invoice pair authenticated with a bare getSessionUser(), so it took the
+ // cookie without ever asking for same-site intent: a cross-site POST could
+ // write pending invoice rows under the victim's identity, or drive an invoice
+ // to 'failed'. Both now share resolveAuth() with the rest of the dispatcher.
+ for (const action of ['accept-payment-prep', 'accept-payment-confirm']) {
+ it(`rejects a cross-site cookie-authed POST to ${action}`, async () => {
+ authState.session = { id: 'user-1' };
+ const handler = pumpAction(action);
+ const { res, json } = await invoke(handler, {
+ method: 'POST', url: `/api/pump/${action}`,
+ headers: { origin: 'https://evil.example' },
+ body: {},
+ });
+ expect(res.statusCode).toBe(403);
+ expect(json.error).toBe('forbidden');
+ expect(
+ sqlState.calls.every((c) => !/\b(insert|update|delete)\b/i.test(String(c.query))),
+ ).toBe(true);
+ });
+
+ it(`still admits a bearer-authed POST to ${action}`, async () => {
+ authState.bearer = { userId: 'user-1' };
+ const handler = pumpAction(action);
+ const { res } = await invoke(handler, {
+ method: 'POST', url: `/api/pump/${action}`,
+ headers: { origin: 'https://evil.example' },
+ body: {},
+ });
+ expect(res.statusCode).not.toBe(403);
+ });
+ }
});