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: route every cookie-session mutation through the CSRF-carrying client

nirholasb62c5e5bd9f5
diff --git a/public/dashboard/memory.html b/public/dashboard/memory.html
index 00d9e1737..c0a4e1e26 100644
--- a/public/dashboard/memory.html
+++ b/public/dashboard/memory.html
@@ -267,6 +267,7 @@
<script type="module">
import { mountAgentPicker } from '/src/dashboard/_agent-picker.js';
+ import { apiFetch } from '/src/api.js';
const TYPES = ['user', 'feedback', 'project', 'reference'];
const TYPE_LABELS = { user: 'User', feedback: 'Feedback', project: 'Project', reference: 'Reference' };
@@ -329,7 +330,7 @@
}
async function deleteMemory(id) {
- const r = await fetch(`/api/agent-memory/${encodeURIComponent(id)}`, {
+ const r = await apiFetch(`/api/agent-memory/${encodeURIComponent(id)}`, {
method: 'DELETE',
credentials: 'include',
});
@@ -338,7 +339,7 @@
}
async function saveMemory(agentId, entry) {
- const r = await fetch('/api/agent-memory', {
+ const r = await apiFetch('/api/agent-memory', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/public/dashboard/sessions.html b/public/dashboard/sessions.html
index 7abb7e652..80089905f 100644
--- a/public/dashboard/sessions.html
+++ b/public/dashboard/sessions.html
@@ -247,6 +247,20 @@
mountHeaderUser({ slot: '#header-user-slot', activePath: '/dashboard/sessions' });
</script>
<script>
+ // Cookie-session mutations need the double-submit CSRF token: fetch a
+ // single-use token from /api/csrf-token and echo it in x-csrf-token.
+ // (Classic script block, so it can't import apiFetch from /src/api.js.)
+ async function csrfToken() {
+ try {
+ const r = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) return '';
+ const j = await r.json();
+ return (j && j.data && j.data.token) || '';
+ } catch {
+ return '';
+ }
+ }
+
function showToast(message, isError = false) {
const toast = document.createElement('div');
toast.className = 'toast' + (isError ? ' error' : '');
@@ -393,6 +407,7 @@
const res = await fetch(`/api/auth/sessions/${sessionId}`, {
method: 'DELETE',
credentials: 'include',
+ headers: { 'x-csrf-token': await csrfToken() },
});
if (!res.ok) {
@@ -434,6 +449,7 @@
const res = await fetch('/api/auth/sessions', {
method: 'DELETE',
credentials: 'include',
+ headers: { 'x-csrf-token': await csrfToken() },
});
if (!res.ok) throw new Error('Failed to sign out');
diff --git a/public/dashboard/sns.html b/public/dashboard/sns.html
index bb2b5d1f3..f240269a5 100644
--- a/public/dashboard/sns.html
+++ b/public/dashboard/sns.html
@@ -23,6 +23,7 @@
<script type="module">
import { mountAgentPicker } from '/src/dashboard/_agent-picker.js';
+ import { apiFetch } from '/src/api.js';
const statusEl = document.getElementById('status');
const contentEl = document.getElementById('content');
@@ -91,7 +92,7 @@
}
async function registerWithAgent(agentId, domain) {
- const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/sns/register`, {
+ const r = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/sns/register`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -129,7 +130,7 @@
const walletAddress = provider.publicKey?.toBase58?.();
if (!walletAddress) throw new Error('Wallet did not return a public key');
- const prepRes = await fetch(
+ const prepRes = await apiFetch(
`/api/agents/${encodeURIComponent(agentId)}/sns/register-prep`,
{
method: 'POST',
@@ -183,7 +184,7 @@
// Poll for confirmation up to ~30s, then ask the API to mark it attached.
for (let i = 0; i < 15; i++) {
await new Promise((r) => setTimeout(r, 2000));
- const confirmRes = await fetch(
+ const confirmRes = await apiFetch(
`/api/agents/${encodeURIComponent(agentId)}/sns/register-confirm`,
{
method: 'POST',
diff --git a/public/dashboard/strategy.html b/public/dashboard/strategy.html
index e4d686916..3916af5ed 100644
--- a/public/dashboard/strategy.html
+++ b/public/dashboard/strategy.html
@@ -23,6 +23,7 @@
<script type="module">
import { mountAgentPicker } from '/src/dashboard/_agent-picker.js';
+ import { apiFetch } from '/src/api.js';
const statusEl = document.getElementById('status');
const contentEl = document.getElementById('content');
@@ -50,7 +51,7 @@
}
async function saveStrategy(agentId, strategy) {
- const r = await fetch(`/api/agent-strategy?id=${encodeURIComponent(agentId)}`, {
+ const r = await apiFetch(`/api/agent-strategy?id=${encodeURIComponent(agentId)}`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/public/dashboard/voice.html b/public/dashboard/voice.html
index 2f686d092..f363ab3dd 100644
--- a/public/dashboard/voice.html
+++ b/public/dashboard/voice.html
@@ -22,6 +22,7 @@
<script type="module">
import { mountAgentPicker } from '/src/dashboard/_agent-picker.js';
+ import { apiFetch } from '/src/api.js';
const statusEl = document.getElementById('status');
const contentEl = document.getElementById('content');
@@ -47,7 +48,7 @@
}
async function deleteVoice(agentId) {
- const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/voice`, {
+ const r = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/voice`, {
method: 'DELETE',
credentials: 'include',
});
@@ -105,7 +106,7 @@
}
async function uploadClone(agentId, blob, durationSec) {
- const r = await fetch(
+ const r = await apiFetch(
`/api/agents/${encodeURIComponent(agentId)}/voice/clone?name=${encodeURIComponent(
(document.getElementById('voice-name').value || 'Agent Voice').slice(0, 100),
)}`,
diff --git a/public/demos/usdz-ar.html b/public/demos/usdz-ar.html
index 7416b9791..be5212186 100644
--- a/public/demos/usdz-ar.html
+++ b/public/demos/usdz-ar.html
@@ -106,6 +106,7 @@
<script src="/nav.js" defer></script>
<script type="module">
import { glbBlobToUsdzBlob } from '/src/usdz-pipeline.js';
+ import { apiFetch } from '/src/api.js';
const $ = (id) => document.getElementById(id);
const log = $('log');
@@ -195,7 +196,7 @@
logLine('upload ok', 'ok');
logLine('PATCHing avatar with usdz_key…', 'info');
- const patch = await fetch(`/api/avatars/${encodeURIComponent(avatarId)}`, {
+ const patch = await apiFetch(`/api/avatars/${encodeURIComponent(avatarId)}`, {
method: 'PATCH',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/public/eth-vanity.html b/public/eth-vanity.html
index 018db4616..7cd50c594 100644
--- a/public/eth-vanity.html
+++ b/public/eth-vanity.html
@@ -285,6 +285,7 @@
<script type="module">
import { keccak_256 } from '@noble/hashes/sha3';
+ import { apiFetch } from '/src/api.js';
import { grindCreate2Vanity } from '/src/eth/vanity/grinder.js';
import {
validatePattern, validateAddress, validateInitCodeHash,
@@ -786,7 +787,7 @@
deployer_label: presetLabel,
};
try {
- let r = await fetch(`/api/agents/${encodeURIComponent(sel.value)}/eth-vanity`, {
+ let r = await apiFetch(`/api/agents/${encodeURIComponent(sel.value)}/eth-vanity`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -797,13 +798,13 @@
if (!confirm('This agent already has a CREATE2 vanity record. Replace it?')) {
btn.disabled = false; status.textContent = ''; return;
}
- const del = await fetch(`/api/agents/${encodeURIComponent(sel.value)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });
+ const del = await apiFetch(`/api/agents/${encodeURIComponent(sel.value)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });
if (!del.ok) {
const dd = await del.json().catch(() => ({}));
status.innerHTML = `<span style="color:var(--bad-fg)">Could not remove existing record: ${esc(dd.error_description || del.status)}</span>`;
btn.disabled = false; return;
}
- r = await fetch(`/api/agents/${encodeURIComponent(sel.value)}/eth-vanity`, {
+ r = await apiFetch(`/api/agents/${encodeURIComponent(sel.value)}/eth-vanity`, {
method: 'POST', credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
diff --git a/public/first-meet/first-meet.js b/public/first-meet/first-meet.js
index 9a2d18c76..cb43aa990 100644
--- a/public/first-meet/first-meet.js
+++ b/public/first-meet/first-meet.js
@@ -1,5 +1,9 @@
// First meet onboarding flow for newly created avatars
+// apiFetch, not raw fetch, for mutations: cookie sessions need the single-use
+// CSRF token it attaches. Loaded as a module script, so /src/api.js resolves.
+import { apiFetch } from '/src/api.js';
+
const STEPS = ['name', 'bio', 'voice', 'greet', 'done'];
let currentStep = 0;
let state = {
@@ -265,7 +269,7 @@ function findVoice(voiceId) {
async function persistState() {
// 1. PATCH avatar name + description
- await fetch(`/api/avatars/${state.avatarId}`, {
+ await apiFetch(`/api/avatars/${state.avatarId}`, {
method: 'PATCH',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -282,7 +286,7 @@ async function persistState() {
const agentMeta = { voice: state.voice, bodyType: state.bodyType };
if (!state.agent) {
// POST new agent
- const res = await fetch('/api/agents', {
+ const res = await apiFetch('/api/agents', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -298,7 +302,7 @@ async function persistState() {
state.agent = data.agent;
} else {
// PATCH existing agent
- const res = await fetch(`/api/agents/${state.agent.id}`, {
+ const res = await apiFetch(`/api/agents/${state.agent.id}`, {
method: 'PATCH',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/public/notifications.js b/public/notifications.js
index 78b2fe786..3906ea191 100644
--- a/public/notifications.js
+++ b/public/notifications.js
@@ -422,14 +422,27 @@
});
}
+ // Cookie-session mutations need the double-submit CSRF token: fetch a
+ // single-use token from /api/csrf-token and echo it in x-csrf-token.
+ // (Kept inline so this file stays a self-contained nav-injected script.)
+ function csrfToken() {
+ return fetch('/api/csrf-token', { credentials: 'include' })
+ .then(function (r) { return r.ok ? r.json() : null; })
+ .then(function (j) { return (j && j.data && j.data.token) || ''; })
+ .catch(function () { return ''; });
+ }
+
function markOneRead(n) {
if (n.read_at) return;
n.read_at = new Date().toISOString();
unread = Math.max(0, unread - 1);
updateBadge();
if (open) render();
- fetch('/api/notifications/' + encodeURIComponent(n.id) + '/read', {
- method: 'POST', credentials: 'include', keepalive: true,
+ csrfToken().then(function (token) {
+ return fetch('/api/notifications/' + encodeURIComponent(n.id) + '/read', {
+ method: 'POST', credentials: 'include', keepalive: true,
+ headers: { 'x-csrf-token': token },
+ });
}).catch(function () {});
}
@@ -439,8 +452,12 @@
unread = 0;
updateBadge();
render();
- fetch('/api/notifications/read-all', { method: 'POST', credentials: 'include', keepalive: true })
- .catch(function () {});
+ csrfToken().then(function (token) {
+ return fetch('/api/notifications/read-all', {
+ method: 'POST', credentials: 'include', keepalive: true,
+ headers: { 'x-csrf-token': token },
+ });
+ }).catch(function () {});
}
// ── Polling (badge upkeep while signed in) ─────────────────────────────────
diff --git a/public/pay/index.html b/public/pay/index.html
index f52f9745c..40f2f6aff 100644
--- a/public/pay/index.html
+++ b/public/pay/index.html
@@ -857,6 +857,7 @@
</div>
<script type="module">
+import { apiFetch } from '/src/api.js';
const $ = (id) => document.getElementById(id);
const conv = $('conv'), stepsEl = $('steps'), receiptEl = $('receipt');
const promptEl = $('prompt'), sendBtn = $('send'), quickEl = $('quick');
@@ -1013,7 +1014,7 @@ genBtn.addEventListener('click', async () => {
genSpinner.style.display = '';
genBtn.childNodes[1].textContent = ' Generating…';
try {
- const r = await fetch(`/api/agents/${pendingGenAgentId}/solana`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
+ const r = await apiFetch(`/api/agents/${pendingGenAgentId}/solana`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}', allowAnonymous: true });
if (!r.ok) throw new Error((await r.json()).error || 'gen_failed');
genOverlay.classList.remove('show');
// reload agents to get the new address
@@ -1777,11 +1778,14 @@ async function run(call, displayLabel) {
window.addEventListener('pagehide', onUnload, { once: true });
try {
- const res = await fetch('/api/x402-pay', {
+ // allowAnonymous: platform-mode demo calls work signed out; a 401 must
+ // render in the console below, not bounce the page to /login.
+ const res = await apiFetch('/api/x402-pay', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'text/event-stream' },
body: JSON.stringify(selectedAgent ? { ...call, agentId: selectedAgent.id } : call),
signal: ctrl.signal,
+ allowAnonymous: true,
});
if (!res.ok || !res.body) {
const text = await res.text();
diff --git a/public/settings/index.html b/public/settings/index.html
index 827d2a6dc..543b847d2 100644
--- a/public/settings/index.html
+++ b/public/settings/index.html
@@ -704,7 +704,13 @@
document.getElementById('sign-out-everywhere-btn').addEventListener('click', async () => {
const btn = document.getElementById('sign-out-everywhere-btn');
btn.disabled = true;
- await fetch('/api/auth/logout-everywhere', { method: 'POST', credentials: 'include' }).finally(() => {
+ // Cookie-session mutation: attach the single-use double-submit CSRF
+ // token (this page's local apiFetch helper does not carry one).
+ const csrf = await fetch('/api/csrf-token', { credentials: 'include' })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j) => j?.data?.token || '')
+ .catch(() => '');
+ await fetch('/api/auth/logout-everywhere', { method: 'POST', credentials: 'include', headers: { 'x-csrf-token': csrf } }).finally(() => {
try { localStorage.removeItem('3dagent:auth-hint'); } catch {}
location.href = '/login';
});
diff --git a/public/skills/dca/skill.js b/public/skills/dca/skill.js
index e1880205e..7ae730718 100644
--- a/public/skills/dca/skill.js
+++ b/public/skills/dca/skill.js
@@ -1,6 +1,22 @@
// DCA skill — client-side setup and execute handlers.
// Server-side execution (onPeriod) lives in api/cron/run-dca.js.
+// Cookie-session mutations need the double-submit CSRF token: fetch a
+// single-use token from /api/csrf-token and echo it in x-csrf-token. Inlined
+// (not imported from /src/api.js) because this file is also loaded outside
+// the page module graph (skill sandbox worker, server-side cron import).
+async function csrfToken(fetchImpl) {
+ const f = fetchImpl || fetch;
+ try {
+ const r = await f('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) return '';
+ const j = await r.json();
+ return j?.data?.token || '';
+ } catch {
+ return '';
+ }
+}
+
// ── Per-chain config ──────────────────────────────────────────────────────────
const CHAIN_CONFIG = {
@@ -133,7 +149,7 @@ export async function execute({ agent, host, args = {} }) {
// Store strategy server-side
const res = await fetch('/api/dca-strategies', {
method: 'POST',
- headers: { 'content-type': 'application/json' },
+ headers: { 'content-type': 'application/json', 'x-csrf-token': await csrfToken() },
credentials: 'include',
body: JSON.stringify({
agent_id: agent.id,
@@ -182,6 +198,7 @@ export async function stop_dca(args, ctx) {
const res = await ctx.fetch(`/api/dca-strategies/${encodeURIComponent(strategy_id)}`, {
method: 'DELETE',
+ headers: { 'x-csrf-token': await csrfToken(ctx.fetch) },
});
if (!res.ok) return { ok: false, error: `HTTP ${res.status}` };
return { ok: true };
diff --git a/public/skills/subscription/skill.js b/public/skills/subscription/skill.js
index 2211fb4e8..816e71351 100644
--- a/public/skills/subscription/skill.js
+++ b/public/skills/subscription/skill.js
@@ -90,9 +90,16 @@ export async function execute({ agent, host, args }) {
const periodSeconds = 7 * 24 * 3600;
try {
+ // Cookie-session mutation: attach the single-use double-submit CSRF token.
+ // Inlined (not imported from /src/api.js) because this file is also
+ // dynamically imported server-side by api/cron/run-subscriptions.js.
+ const csrf = await fetch('/api/csrf-token', { credentials: 'include' })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j) => j?.data?.token || '')
+ .catch(() => '');
const res = await fetch('/api/subscriptions', {
method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ headers: { 'Content-Type': 'application/json', 'x-csrf-token': csrf },
credentials: 'include',
body: JSON.stringify({
agentId,
diff --git a/public/strategy-lab.html b/public/strategy-lab.html
index d8582772c..db3d609cd 100644
--- a/public/strategy-lab.html
+++ b/public/strategy-lab.html
@@ -408,6 +408,7 @@
<div id="toasts"></div>
<script type="module">
+ import { apiFetch } from '/src/api.js';
// ── Presets ─────────────────────────────────────────────────────────────
const PRESETS = {
momentum: {
@@ -714,8 +715,8 @@
provisionBtn.onclick = async () => {
if (!agentSel.value) return;
provisionBtn.disabled = true; provisionBtn.textContent = 'Provisioning…';
- const r = await fetch(`/api/agents/${agentSel.value}/solana?network=${netSel.value}`, {
- method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' }, body: '{}',
+ const r = await apiFetch(`/api/agents/${agentSel.value}/solana?network=${netSel.value}`, {
+ method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' }, body: '{}', allowAnonymous: true,
}).then((r) => r.json()).catch((e) => ({ error: e.message }));
if (r?.data?.address) {
currentWallet = { address: r.data.address, sol: r.data.sol ?? 0 };
diff --git a/public/studio/studio.js b/public/studio/studio.js
index b6f3aa8ad..9d105cac8 100644
--- a/public/studio/studio.js
+++ b/public/studio/studio.js
@@ -5,6 +5,7 @@
// /public/* is served verbatim by Vercel — the build doesn't transform it.
// Keep this list in sync with src/widget-types.js as new types light up.
+import { apiFetch } from '/src/api.js';
import { mountLaunchPanel } from './launch-panel.js';
import { mountKnowledgePanel } from './knowledge-panel.js';
@@ -1880,7 +1881,7 @@ async function deleteWidget() {
if (!state.editingId) return;
if (!confirm('Delete this widget permanently? This cannot be undone.')) return;
try {
- const res = await fetch(`/api/widgets/${encodeURIComponent(state.editingId)}`, {
+ const res = await apiFetch(`/api/widgets/${encodeURIComponent(state.editingId)}`, {
method: 'DELETE',
credentials: 'include',
});
diff --git a/public/vanity-wallet.html b/public/vanity-wallet.html
index 98cc8deb3..0265fd5f7 100644
--- a/public/vanity-wallet.html
+++ b/public/vanity-wallet.html
@@ -573,6 +573,7 @@
</footer>
<script type="module">
+ import { apiFetch } from '/src/api.js';
import { grindVanity } from '/src/solana/vanity/grinder.js';
import { validatePattern, expectedAttempts, effectiveLength, formatTimeEstimate, MAX_PATTERN_LENGTH } from '/src/solana/vanity/validation.js';
@@ -1013,7 +1014,7 @@
// Replacing an existing wallet: detach it first so the POST below
// provisions cleanly instead of being rejected with a 409.
if (replacing) {
- const del = await fetch(`/api/agents/${encodeURIComponent(sel.value)}/solana`, {
+ const del = await apiFetch(`/api/agents/${encodeURIComponent(sel.value)}/solana`, {
method: 'DELETE',
credentials: 'include',
});
@@ -1024,7 +1025,7 @@
return;
}
}
- const r = await fetch(`/api/agents/${encodeURIComponent(sel.value)}/solana`, {
+ const r = await apiFetch(`/api/agents/${encodeURIComponent(sel.value)}/solana`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/src/agent-eth-vanity-card.js b/src/agent-eth-vanity-card.js
index bda91a6d6..893e70c0e 100644
--- a/src/agent-eth-vanity-card.js
+++ b/src/agent-eth-vanity-card.js
@@ -22,6 +22,7 @@
*/
import { keccak_256 } from '@noble/hashes/sha3';
+import { apiFetch } from './api.js';
import { grindCreate2Vanity } from './eth/vanity/grinder.js';
import {
validatePattern, validateAddress, validateInitCodeHash,
@@ -351,14 +352,14 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {
root.querySelector('[data-act="replace"]').addEventListener('click', async () => {
if (!confirm('Replace the saved CREATE2 vanity record? The address above and any deploy history will no longer be associated with this agent.')) return;
try {
- await fetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });
+ await apiFetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });
state.record = null; state.mode = 'form'; state.err = null; state.deployStatusByChain = {}; render();
} catch (e) { state.err = e.message; render(); }
});
root.querySelector('[data-act="remove"]').addEventListener('click', async () => {
if (!confirm('Remove the saved CREATE2 vanity record?')) return;
try {
- await fetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });
+ await apiFetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });
state.record = null; state.err = null; state.deployStatusByChain = {}; render();
} catch (e) { state.err = e.message; render(); }
});
@@ -403,7 +404,7 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {
onProgress: (p) => { state.progress = p; render(); },
});
- const res = await fetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, {
+ const res = await apiFetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -422,7 +423,7 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {
const data = await res.json().catch(() => ({}));
if (!res.ok) {
if (res.status === 409) {
- await fetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });
+ await apiFetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity`, { method: 'DELETE', credentials: 'include' });
return onGrindAndAssign();
}
throw new Error(data.error_description || `save failed (${res.status})`);
@@ -496,7 +497,7 @@ export function mountAgentEthVanityCard({ panel, identity, onAssigned }) {
const receipt = await tx.wait();
if (receipt?.status !== 1) throw new Error('deploy reverted');
- const mark = await fetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity/deployed`, {
+ const mark = await apiFetch(`/api/agents/${encodeURIComponent(identity.id)}/eth-vanity/deployed`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/src/agent-home.js b/src/agent-home.js
index 1979780ba..d11ffde35 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -8,6 +8,7 @@
* Embeddable anywhere: main page identity card, /agent/:id home page.
*/
+import { apiFetch } from './api.js';
import { ACTION_TYPES } from './agent-protocol.js';
import { MEMORY_TYPES } from './agent-memory.js';
import { mountPumpFunCard } from './agent-home-pumpfun.js';
@@ -457,11 +458,14 @@ export class AgentHome {
el.classList.add('is-saving');
try {
- const resp = await fetch(`/api/agents/${this.identity.id}`, {
+ // apiFetch carries the single-use CSRF token this cookie-session PUT
+ // needs; allowAnonymous keeps the 401 local-save branch below reachable.
+ const resp = await apiFetch(`/api/agents/${this.identity.id}`, {
method: 'PUT',
credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ [field]: next }),
+ allowAnonymous: true,
});
// Not authenticated — save is local-only, don't treat as an error.
diff --git a/src/app.js b/src/app.js
index 818f2a4da..6fcb59504 100644
--- a/src/app.js
+++ b/src/app.js
@@ -14,6 +14,7 @@ import { AvatarCreator } from './avatar-creator.js';
import { resolveURI, isDecentralizedURI } from './ipfs.js';
import { resolveDevR2Url } from './shared/dev-r2-proxy.js';
import { isSafeQueryModelUrl } from './shared/safe-model-url.js';
+import { apiFetch } from './api.js';
// Resolve a model URL for loading: expand decentralized URIs (ipfs:/ar:) via the
// gateway, then route r2.dev assets through the dev /r2-proxy so cross-origin
@@ -952,7 +953,7 @@ class App {
if (this._editingAgentId) {
// Update existing agent's avatar
if (avatarId) {
- await fetch(`/api/agents/${this._editingAgentId}`, {
+ await apiFetch(`/api/agents/${this._editingAgentId}`, {
method: 'PUT',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -970,7 +971,7 @@ class App {
let agentId = data?.agent?.id;
if (!agentId) {
- const created = await fetch('/api/agents', {
+ const created = await apiFetch('/api/agents', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -981,7 +982,7 @@ class App {
}
if (agentId && avatarId) {
- await fetch(`/api/agents/${agentId}`, {
+ await apiFetch(`/api/agents/${agentId}`, {
method: 'PUT',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/src/brain.js b/src/brain.js
index 730f5ba0b..0facd88ee 100644
--- a/src/brain.js
+++ b/src/brain.js
@@ -1,6 +1,7 @@
// ── brain.js — Persona builder + multi-model playground ─────────────────────
import { sanitizeUrl } from './shared/sanitize-url.js';
+import { apiFetch } from './api.js';
// ── Provider registry ────────────────────────────────────────────────────────
const PROVIDERS = [
@@ -367,7 +368,7 @@ async function autoSavePersonaToAgent(label) {
...(state.persona.interests || []),
],
};
- const res = await fetch(`/api/agents/${agentId}`, {
+ const res = await apiFetch(`/api/agents/${agentId}`, {
method: 'PUT',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -567,7 +568,7 @@ async function savePersonaToAgent() {
...(state.persona.interests || []),
],
};
- const res = await fetch(`/api/agents/${agentId}`, {
+ const res = await apiFetch(`/api/agents/${agentId}`, {
method: 'PUT',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/src/create-review.js b/src/create-review.js
index 8188a4d78..d51224e2c 100644
--- a/src/create-review.js
+++ b/src/create-review.js
@@ -13,6 +13,7 @@
*/
import { saveRemoteGlbToAccount } from './account.js';
+import { apiFetch } from './api.js';
import { attachAvatarToAgent } from './attach-avatar-to-agent.js';
import { load as loadGuest, clear as clearGuest } from './guest-avatar.js';
import { TalkScene } from './voice/talk-scene.js';
@@ -636,7 +637,7 @@ async function generateAndUploadUsdz(avatarId, glbBlob) {
body: usdzBlob,
});
if (!put.ok) return;
- await fetch(`/api/avatars/${encodeURIComponent(avatarId)}`, {
+ await apiFetch(`/api/avatars/${encodeURIComponent(avatarId)}`, {
method: 'PATCH',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/src/dashboard-next/pages/api.js b/src/dashboard-next/pages/api.js
index 172fd36f0..fb02cdb5f 100644
--- a/src/dashboard-next/pages/api.js
+++ b/src/dashboard-next/pages/api.js
@@ -20,6 +20,7 @@
import { mountShell } from '../shell.js';
import { requireUser, get, post, del, put, esc, relTime, ApiError } from '../api.js';
+import { apiFetch } from '../../api.js';
import { errorStateHTML, emptyStateHTML, skeletonHTML, ensureStateKitStyles } from '../../shared/state-kit.js';
// Scopes accepted by /api/keys — match api/keys/index.js ALLOWED_SCOPES exactly.
@@ -822,7 +823,7 @@ async function runMcpTest(host, key) {
// The plaintext key is hashed server-side and can't be replayed, so the
// test endpoint validates this key by id (ownership, revoked, expired) and
// runs the initialize → tools/list handshake with its real scope.
- const res = await fetch('/api/developer/mcp-test', {
+ const res = await apiFetch('/api/developer/mcp-test', {
method: 'POST',
credentials: 'include',
headers: { accept: 'application/json', 'content-type': 'application/json' },
diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.js
index d83cf0c0c..e9bc5057e 100644
--- a/src/dashboard/dashboard.js
+++ b/src/dashboard/dashboard.js
@@ -1,6 +1,7 @@
// Dashboard single-file app. Uses native DOM — no framework.
// Keeps bundle small and ensures anything rendering <model-viewer> works without bundler.
+import { apiFetch } from '/src/api.js';
import { mountAgentSolanaWalletCard } from '/src/agent-solana-wallet.js';
import { mountAgentVanityGrinderCard } from '/src/agent-vanity-grinder.js';
import { onchainBadgeHTML } from '/src/shared/onchain-badge.js';
@@ -1166,7 +1167,7 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
append_link: linkEl.checked,
}
: { text, agent_id: avatar.agent_id || avatar.id, append_link: linkEl.checked };
- const r = await fetch('/api/x/post', {
+ const r = await apiFetch('/api/x/post', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -1208,7 +1209,7 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
if (isNaN(when.getTime())) return setMsg('Could not parse that date.', '#ffb3b3');
setMsg('Scheduling…');
try {
- const r = await fetch('/api/x/schedule', {
+ const r = await apiFetch('/api/x/schedule', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -1232,7 +1233,7 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
disconnectBtn.addEventListener('click', async () => {
if (!confirm('Disconnect your X account from three.ws?')) return;
try {
- await fetch('/api/x/status', { method: 'DELETE', credentials: 'include' });
+ await apiFetch('/api/x/status', { method: 'DELETE', credentials: 'include' });
loadXPanel({ host, meterEl, bodyEl, avatar });
} catch (err) {
setMsg(err.message, '#ffb3b3');
@@ -1276,7 +1277,7 @@ async function loadXReviews(host) {
const id = btn.getAttribute('data-approve');
btn.disabled = true;
try {
- const r = await fetch(`/api/x/reviews?id=${encodeURIComponent(id)}`, {
+ const r = await apiFetch(`/api/x/reviews?id=${encodeURIComponent(id)}`, {
method: 'PATCH',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -1300,7 +1301,7 @@ async function loadXReviews(host) {
const id = btn.getAttribute('data-reject');
btn.disabled = true;
try {
- await fetch(`/api/x/reviews?id=${encodeURIComponent(id)}`, {
+ await apiFetch(`/api/x/reviews?id=${encodeURIComponent(id)}`, {
method: 'DELETE',
credentials: 'include',
});
@@ -1451,7 +1452,7 @@ async function loadXTriggers(host, avatar) {
const config = readConfigFromUI(kind);
const existing = byKind[kind];
if (existing) {
- const r = await fetch(`/api/x/triggers?id=${encodeURIComponent(existing.id)}`, {
+ const r = await apiFetch(`/api/x/triggers?id=${encodeURIComponent(existing.id)}`, {
method: 'PATCH',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -1461,7 +1462,7 @@ async function loadXTriggers(host, avatar) {
byKind[kind] = (await r.json()).trigger;
} else {
const autoPublish = !host.querySelector('[data-trig-review-all]')?.checked;
- const r = await fetch('/api/x/triggers', {
+ const r = await apiFetch('/api/x/triggers', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -1485,7 +1486,7 @@ async function loadXTriggers(host, avatar) {
const ids = Object.values(byKind).map((t) => t.id);
for (const id of ids) {
try {
- const r = await fetch(`/api/x/triggers?id=${encodeURIComponent(id)}`, {
+ const r = await apiFetch(`/api/x/triggers?id=${encodeURIComponent(id)}`, {
method: 'PATCH',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -1570,7 +1571,7 @@ async function loadScheduledPosts(host) {
const id = btn.getAttribute('data-cancel');
btn.disabled = true;
try {
- await fetch(`/api/x/schedule?id=${encodeURIComponent(id)}`, {
+ await apiFetch(`/api/x/schedule?id=${encodeURIComponent(id)}`, {
method: 'DELETE',
credentials: 'include',
});
@@ -1999,7 +2000,7 @@ async function attachAvatarToDefaultAgent(avatarId) {
if (!meRes.ok) return;
const { agent } = await meRes.json();
if (!agent) return;
- await fetch(`/api/agents/${agent.id}`, {
+ await apiFetch(`/api/agents/${agent.id}`, {
method: 'PUT',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -2714,7 +2715,7 @@ function bindOnchainDeploy(body, agent) {
const chainId =
Number((await window.ethereum?.request?.({ method: 'eth_chainId' })) || 0) ||
undefined;
- await fetch(`/api/agents/${encodeURIComponent(agent.id)}/wallet`, {
+ await apiFetch(`/api/agents/${encodeURIComponent(agent.id)}/wallet`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -3146,7 +3147,7 @@ async function renderMonetization(root) {
msg.style.color = '#888';
msg.textContent = 'Removing…';
try {
- const r = await fetch(
+ const r = await apiFetch(
`/api/agents/${agentId}/pricing/${encodeURIComponent(skill)}?hard=true`,
{ method: 'DELETE', credentials: 'include' },
);
@@ -3204,7 +3205,7 @@ async function renderMonetization(root) {
msg.style.color = '#888';
msg.textContent = 'Saving…';
try {
- const r = await fetch(
+ const r = await apiFetch(
`/api/agents/${agentId}/pricing/${encodeURIComponent(skill)}`,
{
method: 'PUT',
@@ -3287,7 +3288,7 @@ async function renderMonetization(root) {
msgEl.style.color = '#888';
msgEl.textContent = 'Saving…';
try {
- const r = await fetch('/api/billing/payout-wallets', {
+ const r = await apiFetch('/api/billing/payout-wallets', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -3433,7 +3434,7 @@ async function renderSubscriptions(root) {
btn.disabled = true;
let r = null;
try {
- r = await fetch(`/api/subscriptions/plans/${btn.dataset.id}`, {
+ r = await apiFetch(`/api/subscriptions/plans/${btn.dataset.id}`, {
method: 'DELETE',
credentials: 'include',
});
@@ -3453,7 +3454,7 @@ async function renderSubscriptions(root) {
btn.disabled = true;
let r = null;
try {
- r = await fetch(`/api/subscriptions/${btn.dataset.id}`, {
+ r = await apiFetch(`/api/subscriptions/${btn.dataset.id}`, {
method: 'DELETE',
credentials: 'include',
});
@@ -3491,7 +3492,7 @@ async function renderSubscriptions(root) {
msg.textContent = 'Creating…';
let r = null;
try {
- r = await fetch('/api/subscriptions/plans', {
+ r = await apiFetch('/api/subscriptions/plans', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -4017,7 +4018,7 @@ let _remotePrefsTimer = null;
function scheduleRemotePrefsSync(prefs) {
clearTimeout(_remotePrefsTimer);
_remotePrefsTimer = setTimeout(() => {
- fetch('/api/dashboard/prefs', {
+ apiFetch('/api/dashboard/prefs', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -4122,7 +4123,7 @@ async function renderAccount(root) {
return;
}
try {
- const res = await fetch('/api/auth/profile', {
+ const res = await apiFetch('/api/auth/profile', {
method: 'PATCH',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/src/editor/save-back.js b/src/editor/save-back.js
index 87a60e0e7..cf0ac78e3 100644
--- a/src/editor/save-back.js
+++ b/src/editor/save-back.js
@@ -1,4 +1,5 @@
import { exportEditedGLB } from './glb-export.js';
+import { apiFetch } from '../api.js';
const MAX_BYTES = 25 * 1024 * 1024;
@@ -84,11 +85,14 @@ export async function saveEditedAvatar(session, { avatarId, onStep = () => {} }
const glbUrl = parsed.origin + parsed.pathname;
let patchRes;
try {
- const res = await fetch(`/api/avatars/${avatarId}`, {
+ // allowAnonymous: a 401 here must surface as SaveError('auth'), not a
+ // redirect, so the editor can show its own sign-in prompt.
+ const res = await apiFetch(`/api/avatars/${avatarId}`, {
method: 'PATCH',
credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ glbUrl, storage_key: presign.storage_key }),
+ allowAnonymous: true,
});
if (res.status === 401) throw new SaveError('auth', 'Not signed in');
if (!res.ok) {
diff --git a/src/editor/voice-recorder.js b/src/editor/voice-recorder.js
index 907688365..32ebc6431 100644
--- a/src/editor/voice-recorder.js
+++ b/src/editor/voice-recorder.js
@@ -5,6 +5,8 @@
// recorder.mount(); // renders into containerEl
// recorder.destroy(); // removes listeners + DOM
+import { apiFetch } from '../api.js';
+
const MIN_DURATION = 30; // seconds — warn if below this
const SAMPLE_TEXT = "Hello, I'm your agent. How can I help you today?";
@@ -349,7 +351,7 @@ export class VoiceRecorder {
if (!confirm('Remove this agent\'s cloned voice? It will revert to browser TTS.')) return;
this._setStatus('spin', 'Removing voice…');
try {
- const res = await fetch(`/api/agents/${this._agentId}/voice`, {
+ const res = await apiFetch(`/api/agents/${this._agentId}/voice`, {
method: 'DELETE',
credentials: 'include',
});
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index f548e796f..877d39d1c 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -62,6 +62,7 @@ import {
BSC_TESTNET_CHAIN_ID,
} from './gasless-register.js';
import { onchainBadgeHTML, ensureOnchainBadgeStyles } from '../shared/onchain-badge.js';
+import { apiFetch } from '../api.js';
import { log } from '../shared/log.js';
ensureOnchainBadgeStyles();
@@ -864,7 +865,7 @@ export class RegisterUI {
return;
}
try {
- const res = await fetch(
+ const res = await apiFetch(
`/api/agents/${encodeURIComponent(this._backendAgentId)}/wallet`,
{
method: 'POST',
diff --git a/src/memory-seed.js b/src/memory-seed.js
index ce8cebe0f..7f8959f88 100644
--- a/src/memory-seed.js
+++ b/src/memory-seed.js
@@ -10,6 +10,8 @@
* mountMemorySeed(document.getElementById('container'), { agentId: '...' });
*/
+import { apiFetch } from './api.js';
+
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, c =>
({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
@@ -92,7 +94,7 @@ export async function saveMemoryToAgent(agentId, content, opts = {}) {
synthesized_at: new Date().toISOString(),
},
};
- const r = await fetch('/api/agent-memory', {
+ const r = await apiFetch('/api/agent-memory', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
@@ -115,7 +117,7 @@ export async function loadAgentMemories(agentId, opts = {}) {
}
export async function deleteAgentMemory(agentId, memoryId) {
- await fetch(`/api/agent-memory/${memoryId}?agentId=${encodeURIComponent(agentId)}`, {
+ await apiFetch(`/api/agent-memory/${memoryId}?agentId=${encodeURIComponent(agentId)}`, {
method: 'DELETE',
credentials: 'include',
});
@@ -129,7 +131,7 @@ export async function addAgentMemory(agentId, entry) {
tags: entry.tags || [],
salience: entry.salience ?? 0.5,
};
- const r = await fetch('/api/agent-memory', {
+ const r = await apiFetch('/api/agent-memory', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/src/memory/index.js b/src/memory/index.js
index 35bd21060..1b322f0c1 100644
--- a/src/memory/index.js
+++ b/src/memory/index.js
@@ -13,6 +13,7 @@
// or typo'd config never breaks <agent-3d> boot.
import { encryptBlob, bytesToBase64, base64ToBytes } from './crypto.js';
+import { apiFetch } from '../api.js';
import { log } from '../shared/log.js';
const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;
@@ -389,11 +390,14 @@ export class Memory {
const existingId = this._remoteIds.get(file);
if (existingId) entry.id = existingId;
try {
- const resp = await fetch('/api/agent-memory', {
+ // allowAnonymous: this background sync swallows failures silently; a 401
+ // must stay a silent no-op, not a login redirect.
+ const resp = await apiFetch('/api/agent-memory', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ agentId: this.namespace, entry }),
+ allowAnonymous: true,
});
if (!resp.ok) return;
const { entry: saved } = await resp.json();
diff --git a/src/notifications-page.js b/src/notifications-page.js
index 9f9944c52..28c2a02fb 100644
--- a/src/notifications-page.js
+++ b/src/notifications-page.js
@@ -5,6 +5,7 @@
// "hundreds of items" overflow case the dropdown never has to handle.
import { TYPE_ICON, notifLabel, notifLink, escNotif, relTime, trackInApp } from './notifications.js';
+import { apiFetch } from './api.js';
const AUTH_HINT_KEY = '3dagent:auth-hint';
const PAGE_SIZE = 30;
@@ -129,7 +130,7 @@ function markOneRead(id, rowEl) {
unread = Math.max(0, unread - 1);
rowEl?.classList.remove('is-unread');
rowEl?.querySelector('.n-dot')?.remove();
- fetch(`/api/notifications/${encodeURIComponent(id)}/read`, { method: 'POST', credentials: 'include' }).catch(() => {});
+ apiFetch(`/api/notifications/${encodeURIComponent(id)}/read`, { method: 'POST', credentials: 'include', allowAnonymous: true }).catch(() => {});
}
async function markAllRead() {
@@ -139,7 +140,7 @@ async function markAllRead() {
unread = 0;
render();
try {
- await fetch('/api/notifications/read-all', { method: 'POST', credentials: 'include' });
+ await apiFetch('/api/notifications/read-all', { method: 'POST', credentials: 'include', allowAnonymous: true });
} catch { /* fire-and-forget */ }
}
@@ -150,7 +151,7 @@ function deleteOne(id) {
all = all.filter((n) => n.id !== id);
if (wasUnread) unread = Math.max(0, unread - 1);
if (!filtered().length) renderEmpty();
- fetch(`/api/notifications/${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include' }).catch(() => {});
+ apiFetch(`/api/notifications/${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include', allowAnonymous: true }).catch(() => {});
}
async function loadPage(before) {
diff --git a/src/notifications.js b/src/notifications.js
index b12afbb22..2a5742f3a 100644
--- a/src/notifications.js
+++ b/src/notifications.js
@@ -8,6 +8,7 @@
// means the user is not signed in — the badge stays hidden.
import { isPushSupported, getPushState, getPushConfig, enablePush } from './push-notifications.js';
+import { apiFetch } from './api.js';
const POLL_INTERVAL = 30_000;
const AUTH_HINT_KEY = '3dagent:auth-hint';
@@ -566,7 +567,7 @@ class NotificationInbox {
this._updateBadge();
rowEl?.classList.remove('is-unread');
rowEl?.querySelector('.notif-unread-dot')?.remove();
- fetch(`/api/notifications/${encodeURIComponent(id)}/read`, { method: 'POST', credentials: 'include' }).catch(() => {});
+ apiFetch(`/api/notifications/${encodeURIComponent(id)}/read`, { method: 'POST', credentials: 'include', allowAnonymous: true }).catch(() => {});
}
async _markAllRead() {
@@ -577,7 +578,7 @@ class NotificationInbox {
this._updateBadge();
this._renderBody();
try {
- await fetch('/api/notifications/read-all', { method: 'POST', credentials: 'include' });
+ await apiFetch('/api/notifications/read-all', { method: 'POST', credentials: 'include', allowAnonymous: true });
} catch { /* fire-and-forget */ }
}
}
diff --git a/src/onchain/vanity/index.js b/src/onchain/vanity/index.js
index 2fed82468..37605ee93 100644
--- a/src/onchain/vanity/index.js
+++ b/src/onchain/vanity/index.js
@@ -20,6 +20,7 @@
import { grindVanity } from '../../solana/vanity/grinder.js';
import { Keypair } from '@solana/web3.js';
import bs58 from 'bs58';
+import { apiFetch } from '../../api.js';
/**
* @param {object} opts
@@ -56,7 +57,7 @@ export async function provisionVanityForAgent(opts) {
// base58-encoded secret_key and (optional) vanity_prefix — see
// api/agents/solana-wallet.js for the contract.
const secretBase58 = bs58.encode(ground.secretKey);
- const resp = await fetch(`/api/agents/${encodeURIComponent(opts.agentId)}/solana`, {
+ const resp = await apiFetch(`/api/agents/${encodeURIComponent(opts.agentId)}/solana`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
diff --git a/src/payment-modal.js b/src/payment-modal.js
index fd6ed834a..c6ead0e6b 100644
--- a/src/payment-modal.js
+++ b/src/payment-modal.js
@@ -13,6 +13,7 @@ import { formatUsdcEq, formatSolEq } from './shared/usd-price.js';
import { buildReceiptHTML, buildReceiptText } from './shared/payment-receipt.js';
import { showAddFunds } from './shared/add-funds.js';
import { ensureRiskAck } from './shared/risk-ack.js';
+import { apiFetch } from './api.js';
import { log } from './shared/log.js';
const USDC_DECIMALS = 6;
@@ -600,7 +601,7 @@ export class SkillPaymentModal {
this._setStatus('Creating purchase…');
let purchase;
try {
- const r = await fetch('/api/marketplace/purchase', {
+ const r = await apiFetch('/api/marketplace/purchase', {
method: 'POST',
headers: { 'content-type': 'application/json' },
credentials: 'include',
@@ -736,7 +737,7 @@ export class SkillPaymentModal {
async _pollConfirm(reference, maxMs = 60_000) {
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
- const r = await fetch(`/api/marketplace/purchase/${reference}/confirm`, {
+ const r = await apiFetch(`/api/marketplace/purchase/${reference}/confirm`, {
method: 'POST',
credentials: 'include',
});
@@ -871,7 +872,7 @@ export class PaymentChip {
setStatus('Creating purchase…');
let purch;
try {
- const r = await fetch('/api/marketplace/purchase', {
+ const r = await apiFetch('/api/marketplace/purchase', {
method: 'POST',
headers: { 'content-type': 'application/json' },
credentials: 'include',
@@ -1030,7 +1031,7 @@ export class PaymentChip {
async _pollConfirm(reference, maxMs = 60_000) {
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
- const r = await fetch(`/api/marketplace/purchase/${reference}/confirm`, {
+ const r = await apiFetch(`/api/marketplace/purchase/${reference}/confirm`, {
method: 'POST',
credentials: 'include',
});
diff --git a/src/permissions/grant-modal.js b/src/permissions/grant-modal.js
index 7b740b0a7..00b943847 100644
--- a/src/permissions/grant-modal.js
+++ b/src/permissions/grant-modal.js
@@ -9,6 +9,7 @@
*/
import { AbiCoder, getAddress } from 'ethers';
+import { apiFetch } from '../api.js';
import { ensureWallet } from '../erc8004/agent-registry.js';
import { encodeScopedDelegation, signDelegation } from './toolkit.js';
import { CAVEAT_ENFORCERS } from '../erc7710/abi.js';
@@ -941,7 +942,7 @@ export class GrantPermissionsModal {
let data;
try {
- const res = await fetch('/api/permissions/grant', {
+ const res = await apiFetch('/api/permissions/grant', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
diff --git a/src/permissions/manage-panel.js b/src/permissions/manage-panel.js
index e512d073b..739b7983e 100644
--- a/src/permissions/manage-panel.js
+++ b/src/permissions/manage-panel.js
@@ -9,6 +9,7 @@
*/
import { BrowserProvider, Contract } from 'ethers';
+import { apiFetch } from '../api.js';
import { CHAIN_META, addressExplorerUrl, txExplorerUrl } from '../erc8004/chain-meta.js';
import { DELEGATION_MANAGER_DEPLOYMENTS, DELEGATION_MANAGER_ABI } from '../erc7710/abi.js';
import { GrantPermissionsModal } from './grant-modal.js';
@@ -311,7 +312,7 @@ class ManagePanel {
// Mirror to server
try {
- const res = await fetch('/api/permissions/revoke', {
+ const res = await apiFetch('/api/permissions/revoke', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
diff --git a/src/scene-compose.js b/src/scene-compose.js
index c57e933ef..d56a86982 100644
--- a/src/scene-compose.js
+++ b/src/scene-compose.js
@@ -23,6 +23,7 @@
*/
import * as THREE from 'three';
+import { apiFetch } from './api.js';
import { createLogger } from './shared/log.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { getMeshoptDecoder } from './viewer/internal.js';
@@ -1335,7 +1336,7 @@ async function saveOutfit() {
if (!avatarApiId) { toast('Use Export GLB to save this scene'); return; }
showLoading('Saving outfit…');
try {
- const res = await fetch(`/api/avatars/${encodeURIComponent(avatarApiId)}`, {
+ const res = await apiFetch(`/api/avatars/${encodeURIComponent(avatarApiId)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...CH },
body: JSON.stringify({ accessories: attached }),
diff --git a/tests/memory-modes.test.js b/tests/memory-modes.test.js
index e9ac00d7c..144a1b440 100644
--- a/tests/memory-modes.test.js
+++ b/tests/memory-modes.test.js
@@ -100,11 +100,13 @@ describe('Memory.load — remote', () => {
.mockResolvedValueOnce({ ok: true, json: async () => ({ entries: [] }) });
const mem = await Memory.load({ mode: 'remote', namespace: 'agent-uuid', fetchFn });
- // Subsequent write hits the global fetch (the upsert path is hard-wired
- // to it). Stub it for the assertion.
- const upsert = vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ entry: { id: 'srv-id-1' } }),
+ // Subsequent write goes through apiFetch on the global fetch: first a
+ // single-use CSRF token issue, then the upsert carrying that token.
+ const upsert = vi.fn(async (url) => {
+ if (String(url).startsWith('/api/csrf-token')) {
+ return { ok: true, json: async () => ({ data: { token: 'tok-1' } }) };
+ }
+ return { ok: true, json: async () => ({ entry: { id: 'srv-id-1' } }) };
});
globalThis.fetch = upsert;
@@ -115,13 +117,17 @@ describe('Memory.load — remote', () => {
body: 'hit a real DB',
});
- // _remoteUpsert is fire-and-forget — flush it.
+ // _remoteUpsert is fire-and-forget; flush it (token fetch + upsert are
+ // two chained awaits, so drain the timer queue twice).
+ await new Promise((r) => setTimeout(r, 0));
await new Promise((r) => setTimeout(r, 0));
- expect(upsert).toHaveBeenCalledOnce();
- const [url, init] = upsert.mock.calls[0];
+ expect(upsert).toHaveBeenCalledTimes(2);
+ expect(upsert.mock.calls[0][0]).toBe('/api/csrf-token');
+ const [url, init] = upsert.mock.calls[1];
expect(url).toBe('/api/agent-memory');
expect(init.method).toBe('POST');
+ expect(new Headers(init.headers).get('x-csrf-token')).toBe('tok-1');
const sent = JSON.parse(init.body);
expect(sent.agentId).toBe('agent-uuid');
expect(sent.entry.type).toBe('feedback');