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): require wallet:write before a bearer token moves an agent's funds

nirholas77ac91c58428
diff --git a/api/agents/a2a-call.js b/api/agents/a2a-call.js
index 384326832..9cf41b124 100644
--- a/api/agents/a2a-call.js
+++ b/api/agents/a2a-call.js
@@ -29,7 +29,7 @@
// rail — USDC SPL TransferChecked, partially signed by the platform payer and
// co-signed by the peer's facilitator fee payer — with EVM EIP-3009 as fallback.
-import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { authenticateBearer, extractBearer, getSessionUser, assertBearerMaySpend } from '../_lib/auth.js';
import { cors, error, json, method, rateLimited, readJson, respondError, serverError, wrap } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { env } from '../_lib/env.js';
@@ -132,7 +132,7 @@ 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));
+ const bearer = session ? null : assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
const userId = session?.id ?? bearer?.userId;
diff --git a/api/agents/a2a-hire.js b/api/agents/a2a-hire.js
index 8bf6ffb18..2f1558bc1 100644
--- a/api/agents/a2a-hire.js
+++ b/api/agents/a2a-hire.js
@@ -23,7 +23,7 @@
// 6. Finalize the hire + custody ledger so both wallets show the income/outlay and
// the marketplace's completion stats update from real data only.
-import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { authenticateBearer, extractBearer, getSessionUser, assertBearerMaySpend } from '../_lib/auth.js';
import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
@@ -77,7 +77,7 @@ 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));
+ const bearer = session ? null : assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required to hire an agent');
const userId = session?.id ?? bearer?.userId;
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index 1146ad8da..ecc2b1c8c 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -19,7 +19,7 @@
// SNIPER_MODE=simulate or { simulate: true } runs the full real-quote path but
// skips the broadcast (paper mode) — an ops/test toggle, never the default.
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
@@ -55,18 +55,21 @@ function normNetwork(n) {
return n === 'devnet' ? 'devnet' : 'mainnet';
}
-async function resolveAuth(req) {
+// A bearer must hold wallet:write to trade; the read-only quote passes
+// `spendCheck: false` because a preview moves nothing.
+async function resolveAuth(req, { spendCheck = true } = {}) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
+ if (!bearer) return null;
+ if (spendCheck) assertBearerMaySpend(bearer, req);
+ return { userId: bearer.userId };
}
// Owner gate shared by every route here. On any failure it writes the response
// and returns { error: true }; on success returns the owner + agent row + meta.
-async function loadOwnedAgent(req, res, id) {
- const auth = await resolveAuth(req);
+async function loadOwnedAgent(req, res, id, authOpts) {
+ const auth = await resolveAuth(req, authOpts);
if (!auth) { error(res, 401, 'unauthorized', 'sign in required'); return { error: true }; }
const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
@@ -724,7 +727,7 @@ async function handleQuote(req, res, id) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- const owned = await loadOwnedAgent(req, res, id);
+ const owned = await loadOwnedAgent(req, res, id, { spendCheck: false });
if (owned.error) return;
const { auth, meta } = owned;
diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].js
index e04263901..380a0035e 100644
--- a/api/agents/pumpfun/[action].js
+++ b/api/agents/pumpfun/[action].js
@@ -12,7 +12,7 @@
* One bundle so Vercel doesn't re-bundle @solana/web3.js + @pump-fun/* per file.
*/
-import { getSessionUser, authenticateBearer, extractBearer, isSameSiteOrigin } from '../../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, isSameSiteOrigin, assertBearerMaySpend } from '../../_lib/auth.js';
import {
cors,
json,
@@ -53,7 +53,7 @@ async function resolveAuth(req) {
}
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/recovery.js b/api/agents/recovery.js
index 5c9af850f..37a44689b 100644
--- a/api/agents/recovery.js
+++ b/api/agents/recovery.js
@@ -14,7 +14,7 @@
// POST /recovery/requests/:rid/complete finalize a ready recovery → transfer ownership
// POST /recovery/inheritance/arm beneficiary/guardian: arm the dead-man once eligible
-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 @@ 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/agents/solana-trade.js b/api/agents/solana-trade.js
index 5fb6e6011..f95d3e7f0 100644
--- a/api/agents/solana-trade.js
+++ b/api/agents/solana-trade.js
@@ -18,7 +18,7 @@
// state. $THREE is the only coin three.ws promotes; this surface is coin-agnostic
// plumbing that trades whatever mint the owner supplies at runtime.
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
@@ -64,7 +64,7 @@ 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;
}
@@ -274,6 +274,9 @@ export async function handleTrade(req, res, id) {
// CSRF on the state-changing path only: a live preview/quote moves no funds and
// would otherwise burn a single-use token on every keystroke. Bearer callers exempt.
+ // A bearer may quote with any owner grant, but executing spends the wallet and
+ // needs wallet:write (a quote moves nothing, so v1 /swap/quote stays agents:read).
+ if (!parsed.preview) assertBearerMaySpend(auth.bearer, req);
if (!parsed.preview && !(await requireRealFundsAgreement(req, res, { userId: auth.userId, network: parsed.network, context: 'trade' }))) return;
if (!parsed.preview && !(await requireCsrf(req, res, auth.userId))) return;
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index ce66cde4a..b7e7d9ab3 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -1,7 +1,7 @@
// /api/agents/:id/solana — wallet, activity, and airdrop handlers.
// Dispatched from api/agents/[id].js with the `action` sub-path.
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { sql } from '../_lib/db.js';
import { confirmOrThrow, pollConfirmation } from '../_lib/solana/confirm.js';
@@ -171,12 +171,16 @@ async function _reverseSnsCached(address) {
// salt); recoverSolanaAgentKeypair still reads those legacy records.
const _encryptSecret = (plaintext) => encryptSecret(plaintext);
-async function resolveAuth(req) {
+// A bearer needs wallet:write for any write here (import/wipe a key, withdraw,
+// policy edits). `spendCheck: false` defers that to a handler that first learns
+// whether the request is a no-funds simulation (the withdraw preview).
+async function resolveAuth(req, { spendCheck = true } = {}) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
+ if (!bearer) return null;
+ if (spendCheck) assertBearerMaySpend(bearer, req);
+ return { userId: bearer.userId, bearer };
}
// A deposit address is safe to advertise only when the stored custodial key can
@@ -543,8 +547,8 @@ async function handleWallet(req, res, id) {
// Shared loader for the owner-only custody handlers: auth → load agent → verify
// ownership → return the custodial wallet's address + encrypted secret + meta.
// Returns { error } (already-shaped) on any failure so callers can early-return.
-async function loadOwnedWallet(req, res, id) {
- const auth = await resolveAuth(req);
+async function loadOwnedWallet(req, res, id, authOpts) {
+ const auth = await resolveAuth(req, authOpts);
if (!auth) { error(res, 401, 'unauthorized', 'sign in required'); return { error: true }; }
const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
@@ -564,7 +568,7 @@ async function handleWithdraw(req, res, id) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const owned = await loadOwnedWallet(req, res, id);
+ const owned = await loadOwnedWallet(req, res, id, { spendCheck: false });
if (owned.error) return;
const { auth, meta, address: fromAddress, encryptedSecret } = owned;
@@ -615,6 +619,7 @@ async function handleWithdraw(req, res, id) {
// Real funds leave a custodial wallet only for an account that has signed
// the real-funds agreements. Checked before CSRF so a refusal does not burn
// the owner's single-use token.
+ if (!simulate) assertBearerMaySpend(auth.bearer, req);
if (!simulate && !(await requireRealFundsAgreement(req, res, { userId: auth.userId, network, context: 'withdraw' }))) return;
if (!simulate && !(await requireCsrf(req, res, auth.userId))) return;
diff --git a/api/agents/wallet-intents.js b/api/agents/wallet-intents.js
index a9a60655c..54d58c18d 100644
--- a/api/agents/wallet-intents.js
+++ b/api/agents/wallet-intents.js
@@ -18,7 +18,7 @@
*/
import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { limits } from '../_lib/rate-limit.js';
import { requireCsrf } from '../_lib/csrf.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
@@ -45,7 +45,7 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
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/launch/mm.js b/api/launch/mm.js
index 933e45599..8d5cd656c 100644
--- a/api/launch/mm.js
+++ b/api/launch/mm.js
@@ -16,7 +16,7 @@
// the owner to the agent wallet's audited withdraw flow for funds.
import { cors, json, method, error, readJson, rateLimited, 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 { requireCsrf } from '../_lib/csrf.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
@@ -64,7 +64,7 @@ function mintFrom(url, bodyMint) {
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id, session: true };
- const bearer = await authenticateBearer(extractBearer(req));
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId, session: false };
return null;
}
diff --git a/api/marketplace/purchase-as-agent.js b/api/marketplace/purchase-as-agent.js
index d7eddb952..1ffdfd7af 100644
--- a/api/marketplace/purchase-as-agent.js
+++ b/api/marketplace/purchase-as-agent.js
@@ -30,7 +30,7 @@ import {
} from '@solana/spl-token';
import { sql } from '../_lib/db.js';
-import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { authenticateBearer, extractBearer, getSessionUser, assertBearerMaySpend } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap, rateLimited, respondError } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
@@ -52,7 +52,7 @@ 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));
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId, fromSession: false };
return null;
}
diff --git a/api/monetization/wallet.js b/api/monetization/wallet.js
index f2ba5c44d..52b16d1f6 100644
--- a/api/monetization/wallet.js
+++ b/api/monetization/wallet.js
@@ -5,7 +5,7 @@
import { z } from 'zod';
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, wrap, error, readJson, rateLimited } from '../_lib/http.js';
import { parse, isValidSolanaAddress, isValidEvmAddress, isUuid } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -21,7 +21,7 @@ const putBody = 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;
}
diff --git a/api/monetization/withdrawals.js b/api/monetization/withdrawals.js
index a83c93a00..a07b54bf3 100644
--- a/api/monetization/withdrawals.js
+++ b/api/monetization/withdrawals.js
@@ -8,7 +8,7 @@
import { z } from 'zod';
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, wrap, error, readJson, rateLimited } from '../_lib/http.js';
import { parse, isUuid } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -60,7 +60,7 @@ function pickPayoutWallet(wallets, network) {
async function resolveUser(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id, source: 'session' };
- const bearer = await authenticateBearer(extractBearer(req));
+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);
if (bearer) return { userId: bearer.userId, source: 'bearer' };
return null;
}
diff --git a/api/sniper/strategy.js b/api/sniper/strategy.js
index 436aee730..640ad125c 100644
--- a/api/sniper/strategy.js
+++ b/api/sniper/strategy.js
@@ -15,7 +15,7 @@
*/
import { cors, json, method, readJson, wrap, error, 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 { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -40,7 +40,7 @@ async function getSolBalance(address) {
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;
}
diff --git a/api/x402-pay.js b/api/x402-pay.js
index 2129a0a02..c1edc47cf 100644
--- a/api/x402-pay.js
+++ b/api/x402-pay.js
@@ -47,7 +47,7 @@ import { getRedis as _getSharedRedis } from './_lib/redis.js';
import { sql } from './_lib/db.js';
import { thumbnailUrl } from './_lib/r2.js';
import { logger } from './_lib/usage.js';
-import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from './_lib/auth.js';
import { recoverSolanaAgentKeypair } from './_lib/agent-wallet.js';
import { requireRealFundsAgreement } from './_lib/real-funds-agreement.js';
import { SpendLimitError, reserveSpendUsd, updateCustodyEvent, releaseSpendReservation } from './_lib/agent-trade-guards.js';
@@ -175,15 +175,17 @@ async function readCall(tx) {
// ---- User auth + agent wallet loading ----------------------------------
async function requireAuth(req) {
+ let bearer = null;
try {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
+ bearer = await authenticateBearer(extractBearer(req));
} catch (err) {
log.warn('require_auth_failed', { message: err?.message });
}
- return null;
+ if (!bearer) return null;
+ assertBearerMaySpend(bearer, req);
+ return { userId: bearer.userId };
}
// Decide which wallet signs an x402 payment. An agent context — an `agentId`
diff --git a/api/x402/pay-by-name.js b/api/x402/pay-by-name.js
index 4dd2b4004..f029b3d38 100644
--- a/api/x402/pay-by-name.js
+++ b/api/x402/pay-by-name.js
@@ -35,7 +35,7 @@ import {
createAssociatedTokenAccountIdempotentInstruction,
} from '@solana/spl-token';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, assertBearerMaySpend } from '../_lib/auth.js';
import { submitProtected } from '../_lib/execution-engine.js';
import { sql } from '../_lib/db.js';
import { env } from '../_lib/env.js';
@@ -176,7 +176,7 @@ async function handlePaidNameResolve(req, res, body) {
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;
}