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(wallet): extend the wallet:write bearer check to pump, sniper, autopilot and guard routes

nirholase8799a804d97
diff --git a/api/agents/agent-strategy-objects.js b/api/agents/agent-strategy-objects.js
index 612bbf91a..8c326fc05 100644
--- a/api/agents/agent-strategy-objects.js
+++ b/api/agents/agent-strategy-objects.js
@@ -12,7 +12,7 @@
// POST /api/agents/:id/strategies/sweep evaluate this agent's equips now (owner "Run now")
// POST /api/agents/:id/strategies/close force-close ONE open position now { position_id } (owner "Sell now")
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
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';
@@ -29,7 +29,7 @@ const netOf = (v) => (NETWORKS.has(v) ? v : 'mainnet');
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId };
return null;
}
diff --git a/api/agents/sns.js b/api/agents/sns.js
index b20ffdb56..505d1882a 100644
--- a/api/agents/sns.js
+++ b/api/agents/sns.js
@@ -24,7 +24,7 @@
// Confirms on-chain owner = wallet_address, then sets meta.sns_domain
// (the user owns the domain; we only store the alias against the agent).
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
@@ -93,7 +93,7 @@ async function buildRegisterIxs({ connection, domain, buyer, space }) {
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId };
return null;
}
diff --git a/api/agents/solana-guard.js b/api/agents/solana-guard.js
index 2b4fb5c2d..b685c7cfd 100644
--- a/api/agents/solana-guard.js
+++ b/api/agents/solana-guard.js
@@ -11,7 +11,7 @@
// PUT → update config (sensitivity | enabled | safe_address | clear_learned) [CSRF]
// POST → adjudicate { event_id, action: approve|deny|mark_swept } | { action: unfreeze } [CSRF]
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
@@ -26,7 +26,7 @@ import {
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId };
return null;
}
diff --git a/api/autopilot/config.js b/api/autopilot/config.js
index 282917df8..4abd44a72 100644
--- a/api/autopilot/config.js
+++ b/api/autopilot/config.js
@@ -9,7 +9,7 @@
// without a scope the owner granted here. $THREE is the only coin referenced.
import { sql } from '../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
@@ -19,7 +19,7 @@ import { isUuid } from '../_lib/validate.js';
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId };
return null;
}
diff --git a/api/autopilot/proposals.js b/api/autopilot/proposals.js
index a649f46a3..1b13b9ca1 100644
--- a/api/autopilot/proposals.js
+++ b/api/autopilot/proposals.js
@@ -16,7 +16,7 @@
// action = 'adjust' → { proposalId, params } edit a pending proposal's params.
import { sql } from '../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
@@ -33,7 +33,7 @@ export const maxDuration = 60;
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId };
return null;
}
diff --git a/api/launcher/me.js b/api/launcher/me.js
index 178b73782..5c67f0460 100644
--- a/api/launcher/me.js
+++ b/api/launcher/me.js
@@ -28,7 +28,7 @@
*/
import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { rankNarratives } from '../_lib/launcher-trends.js';
@@ -44,7 +44,7 @@ async function resolveUserId(req) {
if (session?.id) return session.id;
const bearer = extractBearer(req);
if (bearer) {
- const auth = await authenticateBearer(bearer).catch(() => null);
+ const auth = assertBearerMaySpend(await authenticateBearer(bearer).catch(() => null), req);
if (auth?.userId) return auth.userId;
}
return null;
diff --git a/api/pump/[action].js b/api/pump/[action].js
index db24e2ef6..70c71ff1e 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -56,7 +56,7 @@ import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';
import { sql } from '../_lib/db.js';
import { resolveSocialReward } from '../_lib/github-reward.js';
import { submitProtected } from '../_lib/execution-engine.js';
-import { getSessionUser, authenticateBearer, extractBearer, isSameSiteOrigin } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, isSameSiteOrigin, assertBearerMaySpend } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error, rateLimited, respondError } from '../_lib/http.js';
import { putObject, publicUrl as r2PublicUrl, thumbnailUrl } from '../_lib/r2.js';
import { env } from '../_lib/env.js';
@@ -168,7 +168,9 @@ function readLimit(url, fallback, max) {
return Math.min(Math.max(1, n), max);
}
-async function resolveAuth(req) {
+// `spend: true` marks a handler that signs with an agent's custodial key; a
+// bearer must then hold wallet:write, not just any grant on the account.
+async function resolveAuth(req, { spend = false } = {}) {
const session = await getSessionUser(req);
if (session) {
// CSRF defense-in-depth for the cookie path: these handlers sign real
@@ -183,8 +185,9 @@ async function resolveAuth(req) {
return { userId: session.id };
}
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
+ if (!bearer) return null;
+ if (spend) assertBearerMaySpend(bearer, req);
+ return { userId: bearer.userId };
}
/**
@@ -3657,7 +3660,7 @@ async function handleStrategyCloseAll(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const auth = await resolveAuth(req);
+ const auth = await resolveAuth(req, { spend: true });
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
const rl = await limits.authIp(clientIp(req));
@@ -3759,7 +3762,14 @@ async function handleStrategyRun(req, res) {
walletAddress = null,
agentMeta = null;
if (mode === 'live') {
- const auth = await resolveAuth(req);
+ // This handler is not behind wrap(), so a refusal thrown by resolveAuth
+ // (cross-site cookie, bearer without wallet:write) is answered here.
+ let auth;
+ try {
+ auth = await resolveAuth(req, { spend: true });
+ } catch (e) {
+ return error(res, e.status || 403, e.code || 'forbidden', e.message);
+ }
if (!auth) return error(res, 401, 'unauthorized', 'sign in required for live mode');
if (!body.agentId)
return error(res, 400, 'validation_error', 'agentId required for live mode');
diff --git a/api/sniper/close.js b/api/sniper/close.js
index c16813e46..4cf06cb4f 100644
--- a/api/sniper/close.js
+++ b/api/sniper/close.js
@@ -23,7 +23,7 @@
*/
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
@@ -45,7 +45,7 @@ const BODY = z.object({
async function resolveUserId(req) {
const session = await getSessionUser(req);
if (session) return session.id;
- const bearer = await authenticateBearer(extractBearer(req));
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return bearer.userId;
return null;
}
@@ -54,7 +54,13 @@ export default async function handler(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const userId = await resolveUserId(req);
+ // Not behind wrap(): answer a bearer without wallet:write here.
+ let userId;
+ try {
+ userId = await resolveUserId(req);
+ } catch (e) {
+ return error(res, e.status || 403, e.code || 'forbidden', e.message);
+ }
if (!userId) return error(res, 401, 'unauthorized', 'sign in to manage the sniper');
const rlUser = await limits.tradePerUser(userId);
diff --git a/tests/bearer-spend-scope.test.js b/tests/bearer-spend-scope.test.js
new file mode 100644
index 000000000..f2b70ce1c
--- /dev/null
+++ b/tests/bearer-spend-scope.test.js
@@ -0,0 +1,107 @@
+// A bearer credential must carry `wallet:write` before a REST route spends from a
+// custodial wallet.
+//
+// The MCP tools behind these actions already demanded `wallet:write`, but the REST
+// routes accepted ANY valid bearer: an `inference`-only API key, or an OAuth token
+// a self-registered client got for "Read your avatars", could withdraw an agent
+// wallet to its own address, hire and pay other agents, arm the sniper or the
+// autopilot, or launch coins. assertBearerMaySpend is the single gate; this suite
+// pins its semantics and that every spending route still calls it.
+
+import { describe, it, expect, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));
+
+const { assertBearerMaySpend, SPEND_SCOPE } = await import('../api/_lib/auth.js');
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+describe('assertBearerMaySpend', () => {
+ const post = { method: 'POST' };
+
+ it('names wallet:write as the spend scope', () => {
+ expect(SPEND_SCOPE).toBe('wallet:write');
+ });
+
+ it('passes a missing bearer through untouched (the session path never reaches it)', () => {
+ expect(assertBearerMaySpend(null, post)).toBeNull();
+ });
+
+ it('refuses a write from a bearer that lacks wallet:write with a 403 insufficient_scope', () => {
+ for (const scope of ['', 'inference', 'avatars:read', 'profile agents:write wallet:read']) {
+ let thrown = null;
+ try {
+ assertBearerMaySpend({ userId: 'u', scope }, post);
+ } catch (e) {
+ thrown = e;
+ }
+ expect(thrown, scope).not.toBeNull();
+ expect(thrown.status).toBe(403);
+ expect(thrown.code).toBe('insufficient_scope');
+ expect(thrown.expose).toBe(true);
+ }
+ });
+
+ it('allows a write from a bearer that holds wallet:write', () => {
+ const b = { userId: 'u', scope: 'avatars:read wallet:write' };
+ expect(assertBearerMaySpend(b, post)).toBe(b);
+ expect(assertBearerMaySpend(b, { method: 'DELETE' })).toBe(b);
+ });
+
+ it('lets safe methods through so a wallet:read key still reads', () => {
+ const b = { userId: 'u', scope: 'wallet:read' };
+ for (const method of ['GET', 'HEAD', 'OPTIONS', 'get']) {
+ expect(assertBearerMaySpend(b, { method })).toBe(b);
+ }
+ });
+
+ it('treats a request with no method as a write (fail closed)', () => {
+ expect(() => assertBearerMaySpend({ userId: 'u', scope: 'inference' }, {})).toThrow(/wallet:write/);
+ });
+});
+
+describe('every bearer-accepting spend route calls the gate', () => {
+ const ROUTES = [
+ 'api/x402-pay.js',
+ 'api/x402/pay-by-name.js',
+ 'api/marketplace/purchase-as-agent.js',
+ 'api/monetization/withdrawals.js',
+ 'api/monetization/wallet.js',
+ 'api/agents/pumpfun/[action].js',
+ 'api/agents/wallet-intents.js',
+ 'api/agents/recovery.js',
+ 'api/agents/agent-trade.js',
+ 'api/agents/solana-trade.js',
+ 'api/agents/solana-wallet.js',
+ 'api/agents/a2a-hire.js',
+ 'api/agents/a2a-call.js',
+ 'api/agents/agent-strategy-objects.js',
+ 'api/agents/sns.js',
+ 'api/agents/solana-guard.js',
+ 'api/sniper/strategy.js',
+ 'api/sniper/close.js',
+ 'api/launch/mm.js',
+ 'api/launcher/me.js',
+ 'api/autopilot/proposals.js',
+ 'api/autopilot/config.js',
+ 'api/pump/[action].js',
+ ];
+
+ for (const rel of ROUTES) {
+ it(rel, () => {
+ const src = readFileSync(path.join(ROOT, rel), 'utf8');
+ expect(src).toMatch(/import \{[^}]*\bassertBearerMaySpend\b[^}]*\} from '[./]*_lib\/auth\.js'/);
+ expect(src.match(/assertBearerMaySpend\(/g)?.length || 0).toBeGreaterThanOrEqual(1);
+ });
+ }
+
+ it('the trade and withdraw executors check scope only once the request is known to spend', () => {
+ const trade = readFileSync(path.join(ROOT, 'api/agents/solana-trade.js'), 'utf8');
+ expect(trade).toMatch(/if \(!parsed\.preview\) assertBearerMaySpend\(auth\.bearer, req\)/);
+ const wallet = readFileSync(path.join(ROOT, 'api/agents/solana-wallet.js'), 'utf8');
+ expect(wallet).toMatch(/if \(!simulate\) assertBearerMaySpend\(auth\.bearer, req\)/);
+ });
+});