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.

feat: integrate CSRF token handling in Solana wallet and x402 payment processes; enhance avatar page with wallet chip component

roundtripped428190b581f7
diff --git a/chat/src/tools.js b/chat/src/tools.js
index e38ee61b5..91ece12fe 100644
--- a/chat/src/tools.js
+++ b/chat/src/tools.js
@@ -9,9 +9,18 @@
const X402_PAY_BODY = `const agentId = (() => { try { return localStorage.getItem('payAgentId') || null; } catch { return null; } })();
const body = { tool: TOOL_NAME, args: ARGS_BUILDER };
if (agentId) body.agentId = agentId;
+const headers = { 'content-type': 'application/json' };
+// Agent-mode pay spends the owner's custodial wallet via the session cookie, so it
+// requires a single-use CSRF token. The shared-wallet path (no agentId) does not.
+if (agentId) {
+ try {
+ const ct = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (ct.ok) { const cj = await ct.json().catch(() => null); const tok = cj && cj.data && cj.data.token; if (tok) headers['x-csrf-token'] = tok; }
+ } catch (e) { /* fall through — server will 403 if the token is truly required */ }
+}
const r = await fetch('/api/x402-pay', {
method: 'POST',
- headers: { 'content-type': 'application/json' },
+ headers,
credentials: 'include',
body: JSON.stringify(body),
});
diff --git a/data/changelog.json b/data/changelog.json
index fb6bbaf06..622ce57db 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-19",
+ "title": "Drop agents on your real floor with AR precision",
+ "summary": "On Android phones that support AR, placing an agent in your room is now pinpoint: point at the floor, a reticle locks onto the real ground, and you tap to drop the agent exactly where you're looking \u2014 feet on the actual floor, not floating at a guess. It anchors into the same shared room as the rest of your agents, so everyone who opens IRL at that spot \u2014 including iPhones \u2014 sees it in the same place, and you can re-tap \u201cRefine on floor\u201d on one of your agents to sharpen just its spot without nudging the others. iPhones and phones without AR keep the aim-and-distance flow they already had, with no extra buttons and nothing that doesn't work \u2014 every device gets the best placement it can do.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/irl"
+ },
{
"date": "2026-06-19",
"title": "AR agents hold their place and size when you rotate your phone",
diff --git a/public/avatar-actions.js b/public/avatar-actions.js
index a4a9a4f42..c3e9ed9f6 100644
--- a/public/avatar-actions.js
+++ b/public/avatar-actions.js
@@ -235,10 +235,19 @@ class AvatarActions extends HTMLElement {
<button class="copy" data-copy="${a}" title="Copy ${chain} address">Copy</button>
<span class="bal" data-bal="${balKey}"></span></div>`
: '';
+ const VTAG = 'font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#a78bfa;border:1px solid rgba(139,92,246,.45);border-radius:999px;padding:1px 6px;';
+ const solRow = sol
+ ? `<div class="addr"><span class="chain">SOL</span><code>${short(sol)}</code>
+ <button class="copy" data-copy="${sol}" title="Copy SOL address">Copy</button>
+ ${solVanity
+ ? `<span title="Custom vanity address" style="${VTAG}">vanity</span>`
+ : `<a class="manage" href="/agent/${ag.id}/wallet#vanity" title="Grind a custom vanity address">✦ Vanity</a>`}
+ <span class="bal" data-bal="sol"></span></div>`
+ : '';
return `<div class="wallet">
<div class="row spread"><h4>Agent wallet</h4>${manage}</div>
${addr('EVM', evm, 'eth')}
- ${addr('SOL', sol, 'sol')}
+ ${solRow}
${evm && sol ? '' : `<button data-act="create-wallet">Provision missing chain</button>`}
</div>`;
}
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 4115e48ad..00e4f613f 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -1696,7 +1696,15 @@ function bindWalletActions(agent) {
deposit.className = 'ad-btn';
deposit.href = `/agent/${encodeURIComponent(agentId)}/wallet#deposit`;
deposit.textContent = 'Deposit';
- actions.append(manage, deposit);
+ // Opt-in vanity: grind a custom address for this agent's custodial wallet.
+ const meta = agent?.rawMetadata?.meta || {};
+ const isVanity = !!(meta.solana_vanity_prefix || meta.solana_vanity_suffix);
+ const vanity = document.createElement('a');
+ vanity.className = 'ad-btn';
+ vanity.href = `/agent/${encodeURIComponent(agentId)}/wallet#vanity`;
+ vanity.textContent = isVanity ? '✦ Vanity address' : '✦ Make it vanity';
+ vanity.setAttribute('aria-label', 'Grind a custom vanity address for this agent wallet');
+ actions.append(manage, deposit, vanity);
}
function renderNotFound(id, reason) {
diff --git a/src/agent-solana-wallet.js b/src/agent-solana-wallet.js
index 8bd00b0f5..d6f2acf90 100644
--- a/src/agent-solana-wallet.js
+++ b/src/agent-solana-wallet.js
@@ -16,6 +16,7 @@
*/
import { grindVanity } from './solana/vanity/grinder.js';
+import { consumeCsrfToken } from './api.js';
const ENDPOINT = (id, qs = '') =>
`/api/agents/${encodeURIComponent(id)}/solana${qs ? `?${qs}` : ''}`;
@@ -135,12 +136,19 @@ export class TradeError extends Error {
async function postTrade(agentId, body) {
const url = `/api/agents/${encodeURIComponent(agentId)}/solana/trade`;
+ const headers = { 'Content-Type': 'application/json' };
+ // A live quote (`preview: true`) moves no funds — only the real trade carries a
+ // single-use CSRF token, matching the server's preview-exempt gate.
+ if (body?.preview !== true) {
+ const token = await consumeCsrfToken();
+ if (token) headers['x-csrf-token'] = token;
+ }
let resp;
try {
resp = await fetch(url, {
method: 'POST',
credentials: 'include',
- headers: { 'Content-Type': 'application/json' },
+ headers,
body: JSON.stringify(body),
});
} catch {
diff --git a/src/agent-x402-pay.js b/src/agent-x402-pay.js
index a66a6f193..6901f9222 100644
--- a/src/agent-x402-pay.js
+++ b/src/agent-x402-pay.js
@@ -12,6 +12,8 @@
* Solana wallet (api/x402-pay.js). The shared platform wallet is never used here.
*/
+import { consumeCsrfToken } from './api.js';
+
// Browse / search the x402 bazaar, scoped to services payable in Solana USDC
// (the only network an agent's Solana wallet can settle). Returns normalized
// resources from api/_lib/x402/bazaar-client.js.
@@ -56,10 +58,15 @@ export async function previewX402({ agentId, url, method = 'GET', body = undefin
// 'result'|'error'). Resolves with the final result envelope, or rejects with an
// Error carrying `.code`/`.envelope` from the 'error' event.
export async function payX402Stream({ agentId, url, method = 'GET', body = undefined, serviceLabel = null }, on = () => {}) {
+ // Settle moves USDC + signs with the agent key → single-use CSRF token required
+ // (the preview path above is exempt server-side). Bearer SDK callers are exempt.
+ const headers = { 'content-type': 'application/json', accept: 'text/event-stream' };
+ const token = await consumeCsrfToken();
+ if (token) headers['x-csrf-token'] = token;
const resp = await fetch('/api/x402-pay', {
method: 'POST',
credentials: 'include',
- headers: { 'content-type': 'application/json', accept: 'text/event-stream' },
+ headers,
body: JSON.stringify({ agentId, url, method, body, service_label: serviceLabel, stream: true }),
});
diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.js
index 3cd340040..4d79bb623 100644
--- a/src/dashboard-next/pages/agents.js
+++ b/src/dashboard-next/pages/agents.js
@@ -18,6 +18,7 @@ import { openAvatarPicker } from '../../avatar-gallery-picker.js';
import { openLaunchTokenModal } from '../../pump/launch-token-modal.js';
import { onchainBadgeHTML } from '../../shared/onchain-badge.js';
import { coinChipHTML } from '../../shared/agent-coin.js';
+import { walletChipHTML, wireWalletChips } from '../../shared/agent-wallet-chip.js';
import { skeletonHTML, emptyStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';
ensureStateKitStyles();
@@ -49,12 +50,6 @@ function toast(msg) {
}, 1800);
}
-function truncMid(s, head = 6, tail = 4) {
- const str = String(s || '');
- if (str.length <= head + tail + 1) return str;
- return `${str.slice(0, head)}…${str.slice(-tail)}`;
-}
-
(async function boot() {
try {
const main = await mountShell();
@@ -210,6 +205,7 @@ function renderAgents(host, agents, avatars, root) {
}
host.innerHTML = agents.map((a) => agentCard(a, avatars)).join('');
+ wireWalletChips(host);
host.querySelectorAll('[data-action="edit-agent"]').forEach((btn) => {
btn.addEventListener('click', () => {
@@ -431,7 +427,6 @@ function brainLabel(agent) {
function agentCard(a, avatars) {
const name = esc(a.name || a.display_name || 'Unnamed agent');
- const wallet = a.wallet_address || a.solana_address || '';
const avatar = avatars.find((av) => av.id === a.avatar_id);
const avatarThumb = avatar?.thumbnail_url || avatar?.url || '';
const created = a.created_at ? relTime(a.created_at) : '—';
@@ -460,7 +455,7 @@ function agentCard(a, avatars) {
${onchainBadge || `<span class="dn-tag" style="font-size:11px">off-chain</span>`}
${coinChipHTML(a, { launchable: false })}
</div>
- ${wallet ? `<div style="font-family:${MONO};font-size:12px;color:var(--nxt-ink-fade);margin-bottom:6px">${esc(truncMid(wallet, 8, 6))}</div>` : ''}
+ <div style="margin-bottom:6px">${walletChipHTML(a, { isOwner: true, showPending: false })}</div>
<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;font-size:12.5px;color:var(--nxt-ink-dim)">
<span>Created ${esc(created)}</span>
<span style="display:inline-flex;align-items:center;gap:4px">
diff --git a/src/dashboard-next/pages/avatars.js b/src/dashboard-next/pages/avatars.js
index fb1cd6d7f..82c3d407e 100644
--- a/src/dashboard-next/pages/avatars.js
+++ b/src/dashboard-next/pages/avatars.js
@@ -11,6 +11,7 @@ import { openSelfieModal } from '../../selfie-modal.js';
import { openAvatarPicker } from '../../avatar-gallery-picker.js';
import { createFromTemplate } from '../../shared/template-picker.js';
import { onchainBadgeHTML, ensureOnchainBadgeStyles } from '../../shared/onchain-badge.js';
+import { walletChipHTML, wireWalletChips } from '../../shared/agent-wallet-chip.js';
const PAGE_SIZE = 24;
const VISIBILITIES = ['public', 'unlisted', 'private'];
@@ -760,11 +761,13 @@ function avatarCard(root, a) {
${visibilityTag(a.visibility)}
<span class="dn-av-rel">${esc(relTime(a.updated_at || a.created_at))}</span>
</div>
+ ${avatarWalletChip(a)}
</div>
`;
wireRename(root, el, a);
wireMoreMenu(root, el, a);
+ wireWalletChips(el);
return el;
}
@@ -775,6 +778,20 @@ function visibilityTag(v) {
return `<span class="dn-tag ${cls}" data-vis-tag>${esc(label)}</span>`;
}
+// The owner's avatar-linked agent wallet (with vanity status + "make vanity"
+// entry point). Renders a "Wallet pending" chip while provisioning so every
+// avatar communicates that it has a custodial wallet.
+function avatarWalletChip(a) {
+ if (!a.agent_id) return '';
+ const agent = {
+ id: a.agent_id,
+ solana_address: a.agent_solana_address || null,
+ solana_vanity_prefix: a.agent_solana_vanity_prefix || null,
+ solana_vanity_suffix: a.agent_solana_vanity_suffix || null,
+ };
+ return `<div class="dn-av-wallet" style="margin-top:8px;">${walletChipHTML(agent, { isOwner: true, showPending: true })}</div>`;
+}
+
// ── Inline rename ────────────────────────────────────────────────────────
function wireRename(root, card, a) {
diff --git a/tests/api/security-csrf-gates.test.js b/tests/api/security-csrf-gates.test.js
index a93b1b9dc..fa8c5f7de 100644
--- a/tests/api/security-csrf-gates.test.js
+++ b/tests/api/security-csrf-gates.test.js
@@ -100,6 +100,21 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
vi.mock('../../api/_lib/agent-wallet.js', () => ({
generateAgentWallet: vi.fn(async () => ({ address: '0xaa', encrypted_key: 'k' })),
generateSolanaAgentWallet: vi.fn(async () => ({ address: 'sol', encrypted_secret: 's' })),
+ recoverSolanaAgentKeypair: vi.fn(async () => ({ publicKey: { toBase58: () => 'sol' } })),
+ recoverAgentKey: vi.fn(async () => '0x' + '11'.repeat(32)),
+ ensureAgentWallet: vi.fn(async () => ({ address: 'sol', created: false })),
+}));
+
+// solana-wallet.js / solana-trade.js touch Solana RPC + SNS at module scope via
+// these helpers; stub them so the CSRF-gate path (which short-circuits before any
+// RPC) can be exercised without a live cluster.
+vi.mock('../../api/_lib/agent-pumpfun.js', () => ({
+ solanaConnection: vi.fn(() => ({})),
+ solanaPublicConnection: vi.fn(() => ({})),
+}));
+
+vi.mock('../../src/solana/sns.js', () => ({
+ reverseLookupAddress: vi.fn(async () => null),
}));
vi.mock('../../api/_lib/notify.js', () => ({
@@ -139,6 +154,8 @@ const { default: agentActionsHandler } = await import('../../api/agent-actions.j
const { default: agentMemoryHandler } = await import('../../api/agent-memory.js');
const { default: subscriptionsHandler } = await import('../../api/subscriptions.js');
const { default: dcaHandler } = await import('../../api/dca-strategies.js');
+const { handleWithdraw } = await import('../../api/agents/solana-wallet.js');
+const { handleTrade } = await import('../../api/agents/solana-trade.js');
// ── helpers ───────────────────────────────────────────────────────────────
@@ -608,3 +625,83 @@ describe('POST/DELETE /api/dca-strategies — CSRF gate', () => {
expect(parseRes(res).error).toBe('csrf_missing');
});
});
+
+// ── Custodial fund-moving endpoints ────────────────────────────────────────
+// Withdraw and discretionary trade move real funds out of a custodial agent
+// wallet. They must be CSRF-gated at least as strongly as message-signing.
+// A valid (non-WSOL) base58 mint so the trade handler reaches the CSRF check
+// rather than failing input validation first.
+const VALID_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+describe('POST /api/agents/:id/solana/withdraw — CSRF gate', () => {
+ const AGENT_ID = '44444444-4444-4444-4444-444444444444';
+
+ it('rejects session-authed withdraw without X-CSRF-Token (403 csrf_missing)', async () => {
+ authState.session = { id: 'owner-1' };
+ // loadOwnedWallet's ownership SELECT — owner matches the session.
+ sqlState.queue.push([
+ { id: AGENT_ID, user_id: 'owner-1', meta: { solana_address: 'sol', encrypted_solana_secret: 's' } },
+ ]);
+ const req = makeReq({
+ method: 'POST',
+ url: `/api/agents/${AGENT_ID}/solana/withdraw`,
+ body: { asset: 'SOL', amount: '0.1', destination: VALID_MINT, network: 'mainnet' },
+ });
+ const res = makeRes();
+ await handleWithdraw(req, res, AGENT_ID);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+
+ it('does NOT reach the CSRF check for a non-owner (403 forbidden first)', async () => {
+ authState.session = { id: 'not-owner' };
+ sqlState.queue.push([
+ { id: AGENT_ID, user_id: 'owner-1', meta: { solana_address: 'sol', encrypted_solana_secret: 's' } },
+ ]);
+ const req = makeReq({
+ method: 'POST',
+ url: `/api/agents/${AGENT_ID}/solana/withdraw`,
+ body: { asset: 'SOL', amount: '0.1', destination: VALID_MINT, network: 'mainnet' },
+ });
+ const res = makeRes();
+ await handleWithdraw(req, res, AGENT_ID);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('forbidden');
+ });
+});
+
+describe('POST /api/agents/:id/solana/trade — CSRF gate', () => {
+ const AGENT_ID = '55555555-5555-5555-5555-555555555555';
+
+ it('rejects a session-authed real trade without X-CSRF-Token (403 csrf_missing)', async () => {
+ authState.session = { id: 'owner-2' };
+ sqlState.queue.push([
+ { id: AGENT_ID, user_id: 'owner-2', meta: { solana_address: 'sol', encrypted_solana_secret: 's' } },
+ ]);
+ const req = makeReq({
+ method: 'POST',
+ url: `/api/agents/${AGENT_ID}/solana/trade`,
+ body: { side: 'buy', mint: VALID_MINT, sol_amount: 0.05, network: 'mainnet' },
+ });
+ const res = makeRes();
+ await handleTrade(req, res, AGENT_ID);
+ expect(res.statusCode).toBe(403);
+ expect(parseRes(res).error).toBe('csrf_missing');
+ });
+
+ it('exempts a live preview (preview:true never burns a token)', async () => {
+ authState.session = { id: 'owner-2' };
+ sqlState.queue.push([
+ { id: AGENT_ID, user_id: 'owner-2', meta: { solana_address: 'sol', encrypted_solana_secret: 's' } },
+ ]);
+ const req = makeReq({
+ method: 'POST',
+ url: `/api/agents/${AGENT_ID}/solana/trade`,
+ body: { side: 'buy', mint: VALID_MINT, sol_amount: 0.05, network: 'mainnet', preview: true },
+ });
+ const res = makeRes();
+ await handleTrade(req, res, AGENT_ID);
+ // Preview is exempt: whatever the quote path returns, it must NOT be the CSRF 403.
+ expect(parseRes(res)?.error).not.toBe('csrf_missing');
+ });
+});