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): require wallet:write before a bearer can place orders or issue spending mandates

nirholas6f8cdadb5d5a
diff --git a/api/agents/a2a-mandate.js b/api/agents/a2a-mandate.js
index 34a5a9c76..2d4905f7e 100644
--- a/api/agents/a2a-mandate.js
+++ b/api/agents/a2a-mandate.js
@@ -12,6 +12,7 @@
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, rateLimited, readJson, respondError, wrap } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import { DEFAULT_NETWORK, issueIntentMandate, MandateError, MAX_TTL_SECONDS, SUPPORTED_NETWORKS } from '../_lib/a2a/mandate.js';
export default wrap(async (req, res) => {
@@ -21,6 +22,9 @@ export default wrap(async (req, res) => {
const session = await getSessionUser(req);
const bearer = session ? null : await authenticateBearer(extractBearer(req));
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ // A mandate lets an agent pay peers with no human in the loop, so issuing
+ // one is a spend: a bearer needs wallet:write, exactly as paying does.
+ assertBearerMaySpend(bearer, req);
const userId = session?.id ?? bearer?.userId;
const rl = await limits.mcpAgent(userId || 'anon');
diff --git a/api/agents/orders.js b/api/agents/orders.js
index 3ed28a83e..0ca94c675 100644
--- a/api/agents/orders.js
+++ b/api/agents/orders.js
@@ -21,6 +21,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.
import { limits } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
+import { assertBearerMaySpend } from '../_lib/spend-scope.js';
import { sql } from '../_lib/db.js';
import { getSolanaAddressBalances } from '../_lib/agent-wallet.js';
import { getSpendLimits, getTradeLimits } from '../_lib/agent-trade-guards.js';
@@ -40,10 +41,23 @@ async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
+ if (bearer) return { userId: bearer.userId, bearer };
return null;
}
+// A live order trades from the agent wallet on its own when it fires, so a
+// bearer (API key, or an app the owner connected over OAuth) needs the spend
+// scope to create or edit one. Cancelling stays open to any owner credential.
+function bearerMaySpend(req, res, auth) {
+ try {
+ assertBearerMaySpend(auth.bearer, req);
+ return true;
+ } catch (e) {
+ error(res, e.status, e.code, e.message);
+ return false;
+ }
+}
+
async function loadOwned(req, res, id) {
const auth = await resolveAuth(req);
if (!auth) { error(res, 401, 'unauthorized', 'sign in to manage this agent’s orders'); return { error: true }; }
@@ -129,6 +143,7 @@ async function handleGetOne(req, res, id, orderId) {
async function handleCreate(req, res, id) {
const owned = await loadOwned(req, res, id);
if (owned.error) return;
+ if (!bearerMaySpend(req, res, owned.auth)) return;
// A live order trades from the agent wallet on its own when it fires.
if (!(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: netOf(req), context: 'order-create' }))) return;
if (!(await requireCsrf(req, res, owned.auth.userId))) return;
@@ -223,6 +238,7 @@ function previewLimits(meta) {
async function handleUpdate(req, res, id, orderId) {
const owned = await loadOwned(req, res, id);
if (owned.error) return;
+ if (!bearerMaySpend(req, res, owned.auth)) return;
if (!(await requireCsrf(req, res, owned.auth.userId))) return;
let body;
diff --git a/tests/a2a-mandate-spend-scope.test.js b/tests/a2a-mandate-spend-scope.test.js
new file mode 100644
index 000000000..44ca54ec4
--- /dev/null
+++ b/tests/a2a-mandate-spend-scope.test.js
@@ -0,0 +1,99 @@
+// api/agents/a2a-mandate.js: issuing an Intent Mandate is a spend.
+//
+// A mandate lets an agent pay its peers with no human in the loop, up to a
+// budget. The route accepted any bearer, so an app a person connected over
+// OAuth for "See your avatars" (a cloud connector such as Grok Bot, holding the
+// token unattended) could arm the agent wallet to spend. It now needs the same
+// wallet:write scope every other spend route demands; a session is the owner,
+// present, and is unaffected.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
+
+vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => []),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: () => false,
+}));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { mcpAgent: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const principal = { session: null, bearer: null };
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => principal.session),
+ authenticateBearer: vi.fn(async () => principal.bearer),
+ extractBearer: vi.fn(() => (principal.bearer ? 'bearer-token' : null)),
+}));
+
+const issueIntentMandate = vi.fn(async (args) => ({ jws: 'signed.mandate.jws', mandate: { owner: args.ownerUserId } }));
+vi.mock('../api/_lib/a2a/mandate.js', () => ({
+ DEFAULT_NETWORK: 'solana',
+ SUPPORTED_NETWORKS: ['solana'],
+ MAX_TTL_SECONDS: 86_400,
+ MandateError: class MandateError extends Error {},
+ issueIntentMandate: (args) => issueIntentMandate(args),
+}));
+
+const { default: handler } = await import('../api/agents/a2a-mandate.js');
+
+function makeRes() {
+ const r = { statusCode: 200, _h: {}, _b: '' };
+ r.setHeader = (k, v) => { r._h[k.toLowerCase()] = v; };
+ r.getHeader = (k) => r._h[k.toLowerCase()];
+ r.end = (b) => { r._b = b ?? ''; };
+ return r;
+}
+
+async function post(body = { subjectAgentId: 'agent-1', maxAtomics: '1000000', perCallAtomics: '100000' }) {
+ const req = {
+ method: 'POST',
+ url: '/api/agents/a2a-mandate',
+ headers: { 'content-type': 'application/json', origin: 'https://three.ws' },
+ body: JSON.stringify(body),
+ socket: { remoteAddress: '127.0.0.1' },
+ };
+ const res = makeRes();
+ await handler(req, res);
+ return { status: res.statusCode, body: res._b ? JSON.parse(res._b) : null };
+}
+
+beforeEach(() => {
+ principal.session = null;
+ principal.bearer = null;
+ issueIntentMandate.mockClear();
+});
+
+describe('POST /api/agents/a2a-mandate spend scope', () => {
+ it('refuses a connected app that was not granted wallet:write', async () => {
+ principal.bearer = { userId: 'user-1', scope: 'avatars:read agents:write wallet:read', source: 'oauth', clientId: 'mcp_grok' };
+ const { status, body } = await post();
+ expect(status).toBe(403);
+ expect(body.error).toBe('insufficient_scope');
+ expect(issueIntentMandate).not.toHaveBeenCalled();
+ });
+
+ it('issues the mandate for a bearer that holds wallet:write', async () => {
+ principal.bearer = { userId: 'user-1', scope: 'wallet:read wallet:write', source: 'oauth', clientId: 'mcp_desktop' };
+ const { status, body } = await post();
+ expect(status).toBe(201);
+ expect(body.mandate).toBe('signed.mandate.jws');
+ expect(issueIntentMandate).toHaveBeenCalledWith(expect.objectContaining({ ownerUserId: 'user-1' }));
+ });
+
+ it('issues the mandate for the signed-in owner', async () => {
+ principal.session = { id: 'user-1' };
+ const { status } = await post();
+ expect(status).toBe(201);
+ });
+
+ it('still asks an anonymous caller to sign in', async () => {
+ const { status } = await post();
+ expect(status).toBe(401);
+ });
+});
diff --git a/tests/agents-subresource-handlers.test.js b/tests/agents-subresource-handlers.test.js
index bb2d4f1d4..17427eb1d 100644
--- a/tests/agents-subresource-handlers.test.js
+++ b/tests/agents-subresource-handlers.test.js
@@ -12,7 +12,7 @@
* orders, portfolio, or perk ladder.
*/
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
const OWNER = 'user-owner';
const AGENT = '11111111-2222-4333-8444-555555555555';
@@ -141,6 +141,7 @@ vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));
const ordersHandler = (await import('../api/agents/orders.js')).default;
const portfolioHandler = (await import('../api/agents/portfolio.js')).default;
const patronageHandler = (await import('../api/agents/patronage.js')).default;
+const { authenticateBearer, extractBearer } = await import('../api/_lib/auth.js');
function mkReq(method = 'GET', url = `/api/agents/${AGENT}/orders`, body) {
return { method, url, headers: {}, body, on: () => {} };
@@ -207,6 +208,50 @@ describe('api/agents/orders.js dispatch', () => {
});
});
+// An app the owner connected over OAuth, or an API key, holds only the scopes
+// it was granted. Creating or editing a live order commits the agent wallet to
+// a trade, so without wallet:write it is refused; reading and cancelling are not.
+describe('api/agents/orders.js with a bearer credential', () => {
+ const asBearer = (scope) => {
+ sessionUser = null;
+ extractBearer.mockReturnValue('bearer-token');
+ authenticateBearer.mockResolvedValue({ userId: OWNER, scope, source: 'oauth', clientId: 'mcp_grok' });
+ };
+ afterEach(() => {
+ extractBearer.mockReturnValue(null);
+ authenticateBearer.mockResolvedValue(null);
+ });
+
+ it('refuses to create an order for a connector that cannot spend', async () => {
+ asBearer('avatars:read agents:write wallet:read');
+ const res = mkRes();
+ await ordersHandler(mkReq('POST', `/api/agents/${AGENT}/orders`, { type: 'limit' }), res, AGENT, undefined);
+ expect(res._json.status).toBe(403);
+ expect(res._json.body.error).toBe('insufficient_scope');
+ });
+
+ it('refuses to edit an order for a connector that cannot spend', async () => {
+ asBearer('avatars:read');
+ const res = mkRes();
+ await ordersHandler(mkReq('PUT', `/api/agents/${AGENT}/orders/${ORDER}`, { slippage_bps: 5000 }), res, AGENT, ORDER);
+ expect(res._json.status).toBe(403);
+ });
+
+ it('still lets that connector read the orders', async () => {
+ asBearer('wallet:read');
+ const res = mkRes();
+ await ordersHandler(mkReq('GET'), res, AGENT, undefined);
+ expect(res._json.status).toBe(200);
+ });
+
+ it('lets a credential holding wallet:write reach validation', async () => {
+ asBearer('wallet:read wallet:write');
+ const res = mkRes();
+ await ordersHandler(mkReq('POST', `/api/agents/${AGENT}/orders`, { type: 'limit' }), res, AGENT, undefined);
+ expect(res._json.status).toBe(422);
+ });
+});
+
describe('api/agents/portfolio.js dispatch', () => {
it('returns the owner snapshot when no action is given (main path)', async () => {
const res = mkRes();