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(spend): stop API keys without wallet:write from arming spenders or moving payout addresses

nirholas51bfdacccaf9
diff --git a/api/agent-collab.js b/api/agent-collab.js
index 72d98cdca..700a7a6be 100644
--- a/api/agent-collab.js
+++ b/api/agent-collab.js
@@ -17,6 +17,7 @@
// every spend guard (owner gate, spend policy, kill switch) still runs there.
import { authenticateBearer, extractBearer, getSessionUser, mintAccessToken } from './_lib/auth.js';
+import { assertBearerMaySpend } from './_lib/spend-scope.js';
import { cors, error, json, method, rateLimited, readJson, wrap } from './_lib/http.js';
import { requireCsrf } from './_lib/csrf.js';
import { isUuid } from './_lib/validate.js';
@@ -70,7 +71,8 @@ export default wrap(async (req, res) => {
if (!method(req, res, ['POST'])) return;
const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ // A team task hires and pays teammate agents over x402.
+ const bearer = session ? null : assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in to run a team task');
const userId = session?.id ?? bearer?.userId;
diff --git a/api/agent-subscriptions.js b/api/agent-subscriptions.js
index be20051d1..6ed01801a 100644
--- a/api/agent-subscriptions.js
+++ b/api/agent-subscriptions.js
@@ -21,6 +21,7 @@
import { sql } from './_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { assertBearerMaySpend } from './_lib/spend-scope.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from './_lib/http.js';
import { requireCsrf } from './_lib/csrf.js';
import { requireRealFundsAgreement } from './_lib/real-funds-agreement.js';
@@ -159,6 +160,10 @@ export default wrap(async (req, res) => {
const bearer = session ? null : await authenticateBearer(extractBearer(req));
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
const userId = session?.id ?? bearer.userId;
+ // Creating a schedule arms a recurring on-chain charge (resume is gated
+ // below, once the body says which action it is). Pausing and cancelling
+ // stop money moving, so any bearer that owns the schedule may do them.
+ if (req.method === 'POST') assertBearerMaySpend(bearer, req);
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
@@ -366,6 +371,8 @@ export default wrap(async (req, res) => {
return error(res, err.status ?? 400, err.code ?? 'validation_error', err.message);
}
+ if (body.action === 'resume') assertBearerMaySpend(bearer, req);
+
// Only the payer controls the schedule: it spends their delegation.
const [current] = await sql`
SELECT s.status, s.next_charge_at, s.period_seconds,
diff --git a/api/agent/launcher.js b/api/agent/launcher.js
index 9681ac481..743e9346e 100644
--- a/api/agent/launcher.js
+++ b/api/agent/launcher.js
@@ -25,6 +25,7 @@
import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { isUuid } from '../_lib/validate.js';
import { sql } from '../_lib/db.js';
@@ -36,7 +37,8 @@ async function resolveUserId(req) {
if (session?.id) return session.id;
const bearer = extractBearer(req);
if (bearer) {
- const auth = await authenticateBearer(bearer).catch(() => null);
+ // The launcher config carries the initial buy and can trigger a launch.
+ const auth = assertBearerMaySpend(await authenticateBearer(bearer).catch(() => null), req);
if (auth?.userId) return auth.userId;
}
return null;
diff --git a/api/agent/market-maker.js b/api/agent/market-maker.js
index 35735c00d..528bcd9ec 100644
--- a/api/agent/market-maker.js
+++ b/api/agent/market-maker.js
@@ -10,6 +10,7 @@
import { cors, error, json, method, readJson, rateLimited, wrap } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { isUuid } from '../_lib/validate.js';
import { sql } from '../_lib/db.js';
@@ -19,7 +20,8 @@ import { sql } from '../_lib/db.js';
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
+ // Arming the market maker commits SOL from the agent wallet.
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId };
return null;
}
diff --git a/api/agents.js b/api/agents.js
index 296eef00e..2cfea72d5 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -13,6 +13,7 @@
*/
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from './_lib/auth.js';
+import { assertBearerMaySpend } from './_lib/spend-scope.js';
import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error, serverError, rateLimited } from './_lib/http.js';
import { requireCsrf } from './_lib/csrf.js';
@@ -471,6 +472,12 @@ async function handleUpdate(req, res, id, auth) {
const clientMeta = { ...body.meta };
delete clientMeta.encrypted_wallet_key;
delete clientMeta.encrypted_solana_secret;
+ // The money keys arm autonomous spending, raise its limits, or say where
+ // the agent is paid. A bearer may send them back unchanged (a client's
+ // read-modify-write does), but changing one needs the spend scope.
+ if (auth.source === 'bearer' && changesMoneyMeta(existingMeta, clientMeta)) {
+ assertBearerMaySpend({ scope: auth.scope }, req);
+ }
mergedMeta = { ...existingMeta, ...clientMeta };
if ('encrypted_wallet_key' in existingMeta) {
mergedMeta.encrypted_wallet_key = existingMeta.encrypted_wallet_key;
@@ -571,6 +578,9 @@ export async function handleWallet(req, res, id, action = null) {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ // Provisioning, setting or clearing the wallet decides where the agent's
+ // payouts land (api/_lib/payout.js falls back to wallet_address).
+ if (auth.source === 'bearer') assertBearerMaySpend({ scope: auth.scope }, req);
// CSRF check before any DB lookups for state-mutating methods.
if (req.method !== 'GET') {
@@ -703,6 +713,21 @@ async function resolveAuth(req) {
return null;
}
+// meta keys that move or route money: the treasury autopilot (the cron arms on
+// meta.autopilot.armed), spend and trade limits, policy rules, and the deposit
+// and payTo fallbacks.
+const MONEY_META_KEYS = ['autopilot', 'spend_limits', 'trade_limits', 'policy_rules', 'solana_address', 'payments'];
+
+function stableJson(v) {
+ if (Array.isArray(v)) return `[${v.map(stableJson).join(',')}]`;
+ if (v && typeof v === 'object') return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stableJson(v[k])}`).join(',')}}`;
+ return JSON.stringify(v ?? null);
+}
+
+export function changesMoneyMeta(existingMeta, clientMeta) {
+ return MONEY_META_KEYS.some((k) => k in clientMeta && stableJson(clientMeta[k]) !== stableJson(existingMeta?.[k]));
+}
+
// 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.
diff --git a/api/agents/autopilot.js b/api/agents/autopilot.js
index 9c86d342c..ab71a9c88 100644
--- a/api/agents/autopilot.js
+++ b/api/agents/autopilot.js
@@ -15,6 +15,7 @@
import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { limits } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
@@ -31,7 +32,8 @@ import { validateSolanaAddress, getSpendLimits } from '../_lib/agent-trade-guard
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
+ // Arming the autopilot or running a live cycle spends from the treasury.
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId };
return null;
}
diff --git a/api/animations/sell.js b/api/animations/sell.js
index 629d17fc5..c6e73caf8 100644
--- a/api/animations/sell.js
+++ b/api/animations/sell.js
@@ -20,6 +20,7 @@
// (agent_payout_wallets) when omitted; a paid listing needs at least one.
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
@@ -99,6 +100,11 @@ async function handleList(req, res, auth, raw) {
// Resolve payout addresses: explicit overrides win, else fall back to the
// seller's default payout wallets. A paid listing needs somewhere to settle.
+ // An explicit payout address decides who is paid for every sale; the
+ // account's own payout wallets (the default) need no extra grant.
+ if (auth.source !== 'session' && (input.payto_base || input.payto_solana || input.payto_bsc)) {
+ assertBearerMaySpend(auth, req);
+ }
const payto = await resolvePayto(auth.userId, input);
if (priced && !payto.base && !payto.solana) {
return error(
diff --git a/api/launchpad/publish.js b/api/launchpad/publish.js
index fffa82b90..6948a6577 100644
--- a/api/launchpad/publish.js
+++ b/api/launchpad/publish.js
@@ -30,6 +30,7 @@
import { createHash, randomBytes } from 'node:crypto';
import { sql } from '../_lib/db.js';
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { env } from '../_lib/env.js';
@@ -112,11 +113,28 @@ async function resolveAuth(req) {
} catch {}
try {
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
+ if (bearer) return { userId: bearer.userId, bearer };
} catch {}
return null;
}
+function sameJson(a, b) {
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
+}
+
+// An edit by a bearer may change the page's copy, scene and skills, but moving
+// its payout wallet or pricing redirects what visitors pay, which needs the
+// spend scope (api/_lib/spend-scope.js). A session or the owner secret is the
+// owner and passes.
+async function assertPayoutEditAllowed(auth, data, req) {
+ if (!auth?.bearer) return;
+ const [row] = await sql`SELECT owner_wallet, config FROM launchpad_pages WHERE slug = ${data.slug}`;
+ if (!row) return;
+ if (row.owner_wallet !== data.identity.wallet || !sameJson(row.config?.monetize, data.monetize)) {
+ assertBearerMaySpend(auth.bearer, req);
+ }
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
@@ -188,6 +206,8 @@ export default wrap(async (req, res) => {
return json(res, 200, out);
}
+ if (!providedHash) await assertPayoutEditAllowed(auth, data, req);
+
// Edit auth, re-asserted inside the statement so it cannot go stale between a
// read and the write: (a) matching secret, or (b) same session user. The row's
// payout wallet is public (returned by /api/launchpad/get), so knowing it
diff --git a/api/marketplace/set-skill-price.js b/api/marketplace/set-skill-price.js
index e729b0868..ba31ca5ab 100644
--- a/api/marketplace/set-skill-price.js
+++ b/api/marketplace/set-skill-price.js
@@ -6,6 +6,7 @@
*/
import { sql } from '../_lib/db.js';
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
@@ -38,7 +39,8 @@ const bodySchema = z.object({
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id, fromSession: true };
- const bearer = await authenticateBearer(extractBearer(req));
+ // A listing's proceeds split names who gets paid.
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId, fromSession: false };
return null;
}
diff --git a/api/oracle/watch.js b/api/oracle/watch.js
index 2bd5730a4..c54213188 100644
--- a/api/oracle/watch.js
+++ b/api/oracle/watch.js
@@ -16,6 +16,7 @@
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { isUuid } from '../_lib/validate.js';
@@ -51,7 +52,8 @@ const WATCH_SCHEMA = z.object({
async function resolveUserId(req) {
const session = await getSessionUser(req);
if (session) return session.id;
- const bearer = await authenticateBearer(extractBearer(req));
+ // A live watch makes real buys from the agent's custodial wallet.
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return bearer.userId;
return null;
}
diff --git a/api/pump/autopilot.js b/api/pump/autopilot.js
index 76e2aab0e..34c1e5340 100644
--- a/api/pump/autopilot.js
+++ b/api/pump/autopilot.js
@@ -21,6 +21,7 @@ import {
isSameSiteOrigin,
} from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import { sql } from '../_lib/db.js';
import { z } from 'zod';
@@ -36,7 +37,8 @@ import { z } from 'zod';
async function resolveCaller(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id, viaCookie: true };
- const bearer = await authenticateBearer(extractBearer(req));
+ // The policy drives buyback swaps and distributions from the creator wallet.
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId, viaCookie: false };
return null;
}
diff --git a/api/signals/_common.js b/api/signals/_common.js
index 317f58be1..e6d07b6d1 100644
--- a/api/signals/_common.js
+++ b/api/signals/_common.js
@@ -16,7 +16,7 @@ export async function requireUser(req, res) {
const session = await getSessionUser(req);
const bearer = session ? null : await authenticateBearer(extractBearer(req));
if (!session && !bearer) { error(res, 401, 'unauthorized', 'sign in required'); return null; }
- return { userId: session?.id ?? bearer.userId, viaSession: !!session };
+ return { userId: session?.id ?? bearer.userId, viaSession: !!session, bearer };
}
/**
diff --git a/api/signals/subscribe.js b/api/signals/subscribe.js
index 6f030e1df..e33c188b9 100644
--- a/api/signals/subscribe.js
+++ b/api/signals/subscribe.js
@@ -27,6 +27,7 @@ import {
setSignalSubscriptionStatus, setSignalSubscriptionKilled,
} from '../_lib/signal-subscription-control.js';
import { requireUser, loadOwnedAgent, normNetwork, parseRowId } from './_common.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
// A live subscription pays x402 USDC and mirrors trades from the subscriber
// agent's custodial wallet. Turning one on (or delivering it now) needs the
@@ -44,6 +45,9 @@ export default wrap(async (req, res) => {
const auth = await requireUser(req, res);
if (!auth) return;
const { userId } = auth;
+ // Subscribing (or a sync) pays x402 USDC and mirrors trades. Unsubscribing
+ // stops both, so any owning bearer may do it.
+ if (req.method === 'POST') assertBearerMaySpend(auth.bearer, req);
if (req.method === 'GET') {
return json(res, 200, { subscriptions: await listSignalSubscriptions(userId) });
diff --git a/api/vaults/[id].js b/api/vaults/[id].js
index f458ef795..06e3fe80b 100644
--- a/api/vaults/[id].js
+++ b/api/vaults/[id].js
@@ -9,6 +9,7 @@
import { cors, json, method, error, readJson, wrap } from '../_lib/http.js';
import { authWrite, resolveUserId, loadAgent, traderBadge } from '../_lib/vault-auth.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import {
getVault, getOpenPositions, getBacker, listBackers,
setVaultStatus, updateVaultTerms, recordVaultEvent,
@@ -115,6 +116,9 @@ async function handlePatch(req, res, id) {
let body;
try { body = (await readJson(req)) || {}; } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid body'); }
const action = String(body.action || 'terms');
+ // Resume restarts trading with backers' funds and terms raises its budgets
+ // and fee; pause and close only stop trading, so they need no spend grant.
+ if (!who.session && action !== 'pause' && action !== 'close') assertBearerMaySpend({ scope: who.scope }, req);
if (action === 'pause') {
if (vault.status === 'closed') return error(res, 409, 'closed', 'vault is closed');
diff --git a/api/vaults/index.js b/api/vaults/index.js
index e8e98f2e2..be34be518 100644
--- a/api/vaults/index.js
+++ b/api/vaults/index.js
@@ -77,7 +77,8 @@ async function handleList(req, res) {
}
async function handleOpen(req, res) {
- const who = await authWrite(req, res);
+ // Opening a vault sets the trading budgets and fee that spend backers' USDC.
+ const who = await authWrite(req, res, { spend: true });
if (!who) return;
const { userId } = who;
diff --git a/tests/api/launchpad-publish-edit-auth.test.js b/tests/api/launchpad-publish-edit-auth.test.js
index 5c706be86..891030174 100644
--- a/tests/api/launchpad-publish-edit-auth.test.js
+++ b/tests/api/launchpad-publish-edit-auth.test.js
@@ -29,8 +29,9 @@ import { invoke } from '../_helpers/monetization.js';
let insertClaims = true;
let updateReturns = null; // null = no authorized row matched
let calls = [];
+let storedPage = null; // what the payout check reads for an existing slug
-const sqlMock = vi.fn((strings, ...values) => {
+const baseSql = (strings, ...values) => {
const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
calls.push({ q, values });
if (/INSERT INTO launchpad_pages/i.test(q)) {
@@ -39,8 +40,12 @@ const sqlMock = vi.fn((strings, ...values) => {
if (/UPDATE launchpad_pages/i.test(q)) {
return Promise.resolve(updateReturns ? [updateReturns] : []);
}
+ if (/SELECT owner_wallet, config FROM launchpad_pages/i.test(q)) {
+ return Promise.resolve(storedPage ? [storedPage] : []);
+ }
return Promise.resolve([]);
-});
+};
+const sqlMock = vi.fn(baseSql);
sqlMock.transaction = (queries) => Promise.all(queries);
vi.mock('../../api/_lib/db.js', () => ({
sql: sqlMock,
@@ -49,10 +54,11 @@ vi.mock('../../api/_lib/db.js', () => ({
}));
let sessionUser = null;
+let bearerUser = null;
vi.mock('../../api/_lib/auth.js', () => ({
getSessionUser: vi.fn(async () => sessionUser),
- authenticateBearer: vi.fn(async () => null),
- extractBearer: vi.fn(() => null),
+ authenticateBearer: vi.fn(async () => bearerUser),
+ extractBearer: vi.fn(() => (bearerUser ? 'sk_live_test' : null)),
}));
vi.mock('../../api/_lib/rate-limit.js', () => ({
@@ -94,6 +100,8 @@ beforeEach(() => {
insertClaims = true;
updateReturns = null;
sessionUser = null;
+ bearerUser = null;
+ storedPage = null;
});
describe('POST /api/launchpad/publish: claiming a slug', () => {
@@ -223,3 +231,48 @@ describe('POST /api/launchpad/publish: input boundary', () => {
expect(calls).toHaveLength(0);
});
});
+
+// A connector key (x-grok order 026) may edit a page it owns, but moving where
+// visitors' payments land needs the spend scope.
+describe('POST /api/launchpad/publish: payout edits by an API key', () => {
+ const CONNECTOR = { userId: USER_ID, scope: 'avatars:read avatars:write agents:read agents:write connector' };
+
+ beforeEach(() => {
+ // An earlier case swaps the implementation to race two publishes.
+ sqlMock.mockImplementation(baseSql);
+ insertClaims = false;
+ updateReturns = { owner_secret_hash: 'h' };
+ const page = draft();
+ storedPage = { owner_wallet: page.identity.wallet, config: { monetize: page.monetize } };
+ });
+
+ it('lets a connector key edit the copy while the payout stays put', async () => {
+ bearerUser = CONNECTOR;
+ const { status } = await post(draft({ copy: { headline: 'New', tagline: 'Copy', cta: 'Go' } }));
+ expect(status).toBe(200);
+ expect(findCall(/UPDATE launchpad_pages/i)).toBeTruthy();
+ });
+
+ it('refuses a connector key that moves the payout wallet, before any write', async () => {
+ bearerUser = CONNECTOR;
+ const page = draft();
+ const { status, body } = await post({ ...page, identity: { ...page.identity, wallet: '0x00000000000000000000000000000000000000bb' } });
+ expect(status).toBe(403);
+ expect(body.error).toBe('insufficient_scope');
+ expect(body.error_description).toContain('wallet:write');
+ expect(findCall(/UPDATE launchpad_pages/i)).toBeUndefined();
+ });
+
+ it('refuses a connector key that changes the price', async () => {
+ bearerUser = CONNECTOR;
+ const { status } = await post(draft({ monetize: { kind: 'per-question', price: 9, currency: 'USDC', chain: 'base' } }));
+ expect(status).toBe(403);
+ });
+
+ it('lets a key that holds wallet:write move the payout', async () => {
+ bearerUser = { userId: USER_ID, scope: 'avatars:write wallet:write' };
+ const page = draft();
+ const { status } = await post({ ...page, identity: { ...page.identity, wallet: '0x00000000000000000000000000000000000000bb' } });
+ expect(status).toBe(200);
+ });
+});
diff --git a/tests/api/pump-autopilot.test.js b/tests/api/pump-autopilot.test.js
index c889396dc..3a77d952e 100644
--- a/tests/api/pump-autopilot.test.js
+++ b/tests/api/pump-autopilot.test.js
@@ -110,7 +110,7 @@ describe('/api/pump/autopilot', () => {
});
it('does not gate bearer-authed writes', async () => {
- authState.bearer = { userId: 'user-1' };
+ authState.bearer = { userId: 'user-1', scope: 'wallet:write' };
const { res } = await invoke({
method: 'POST',
headers: { origin: 'https://evil.example' },
@@ -121,6 +121,12 @@ describe('/api/pump/autopilot', () => {
expect(res.statusCode).toBe(404);
});
+ it('refuses a bearer without wallet:write, since the policy drives buyback swaps', async () => {
+ authState.bearer = { userId: 'user-1', scope: 'avatars:read agents:write connector' };
+ const { res } = await invoke({ method: 'POST', body: { mint: MINT } });
+ expect(res.statusCode).toBe(403);
+ });
+
it('leaves reads open to a cookie session with no Origin', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [[]];
diff --git a/tests/bearer-spend-scope.test.js b/tests/bearer-spend-scope.test.js
index 4f3e1dfed..936a5e0c0 100644
--- a/tests/bearer-spend-scope.test.js
+++ b/tests/bearer-spend-scope.test.js
@@ -113,6 +113,21 @@ describe('every bearer-accepting spend route calls the gate', () => {
'api/marketplace/buy-asset.js',
'api/tournaments/[id].js',
'api/agent-wallet-bridge.js',
+ // Closed by x-grok order 026: arming autonomous spenders, recurring
+ // charges and paid hires, and redirecting where an agent is paid.
+ 'api/agents/autopilot.js',
+ 'api/agent/launcher.js',
+ 'api/agent/market-maker.js',
+ 'api/oracle/watch.js',
+ 'api/pump/autopilot.js',
+ 'api/agent-subscriptions.js',
+ 'api/marketplace/set-skill-price.js',
+ 'api/agent-collab.js',
+ 'api/signals/subscribe.js',
+ 'api/launchpad/publish.js',
+ 'api/animations/sell.js',
+ 'api/agents.js',
+ 'api/vaults/[id].js',
];
for (const rel of ROUTES) {
@@ -125,12 +140,19 @@ describe('every bearer-accepting spend route calls the gate', () => {
it('labor, Agora and vault money writes ask authWrite for the spend gate', () => {
for (const rel of ['api/labor/post.js', 'api/labor/award.js', 'api/labor/policy.js', 'api/agora/act.js',
- 'api/vaults/deposit.js', 'api/vaults/redeem.js', 'api/vaults/trade.js', 'api/vaults/claim-fees.js']) {
+ 'api/vaults/deposit.js', 'api/vaults/redeem.js', 'api/vaults/trade.js', 'api/vaults/claim-fees.js',
+ 'api/vaults/index.js']) {
const src = readFileSync(path.join(ROOT, rel), 'utf8');
expect(src, rel).toMatch(/authWrite\(req, res, \{ spend: true \}\)/);
}
});
+ it('agent edits need the spend scope only to change a money key, and wallet edits always', () => {
+ const agents = readFileSync(path.join(ROOT, 'api/agents.js'), 'utf8');
+ expect(agents).toMatch(/if \(auth\.source === 'bearer' && changesMoneyMeta\(existingMeta, clientMeta\)\)/);
+ expect(agents).toMatch(/if \(auth\.source === 'bearer'\) assertBearerMaySpend\(\{ scope: auth\.scope \}, req\)/);
+ });
+
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, \{ kind: 'trade' \}\)/);
diff --git a/tests/vaults-api-guards.test.js b/tests/vaults-api-guards.test.js
index 53e21636c..23233b0c9 100644
--- a/tests/vaults-api-guards.test.js
+++ b/tests/vaults-api-guards.test.js
@@ -121,7 +121,8 @@ const OPEN_VAULT = {
beforeEach(() => {
vi.clearAllMocks();
- authWriteMock.mockResolvedValue({ userId: USER, session: false });
+ // A bearer that holds the spend grant; the connector case below holds none.
+ authWriteMock.mockResolvedValue({ userId: USER, session: false, scope: 'wallet:read wallet:write' });
resolveUserIdMock.mockResolvedValue({ userId: USER, session: false });
loadOwnedAgentMock.mockResolvedValue({
id: AGENT, user_id: USER, name: 'Anchor',
@@ -219,6 +220,17 @@ describe('caller-supplied amounts are parsed at the boundary', () => {
describe('PATCH /api/vaults/:id terms', () => {
const patchReq = (body) => mkReq({ method: 'PATCH', url: `/api/vaults/${VAULT}`, body });
+ it('refuses a terms change from a bearer without wallet:write, and still lets it pause', async () => {
+ authWriteMock.mockResolvedValue({ userId: USER, session: false, scope: 'avatars:read agents:write connector' });
+ const { res, out } = await call(vaultDetailHandler, patchReq({ action: 'terms', maxPerTradeUsdc: 10 }));
+ expect(res.statusCode).toBe(403);
+ expect(out.error).toBe('insufficient_scope');
+ expect(out.error_description).toContain('wallet:write');
+ expect(updateVaultTermsMock).not.toHaveBeenCalled();
+ const paused = await call(vaultDetailHandler, patchReq({ action: 'pause' }));
+ expect(paused.res.statusCode).not.toBe(403);
+ });
+
it('refuses a non-numeric bps term instead of writing NaN into an integer column', async () => {
const a = await call(vaultDetailHandler, patchReq({ action: 'terms', performanceFeeBps: 'abc' }));
expect(a.res.statusCode).toBe(400);