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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(legal): gate vault and programmable-order money paths, guard every key route in tests, and load the agreements page script as a module
nirholasbc1ec4e9fe93
diff --git a/api/agents/orders.js b/api/agents/orders.jsindex 6b35af225..63fcd23b3 100644--- a/api/agents/orders.js+++ b/api/agents/orders.js@@ -20,6 +20,7 @@ import { cors, json, method, error, readJson, rateLimited, serverError } from '.import { getSessionUser, authenticateBearer, extractBearer } 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';import { sql } from '../_lib/db.js';import { getSolanaAddressBalances } from '../_lib/agent-wallet.js';import { getSpendLimits, getTradeLimits } from '../_lib/agent-trade-guards.js';@@ -128,6 +129,8 @@ async function handleGetOne(req, res, id, orderId) {async function handleCreate(req, res, id) {const owned = await loadOwned(req, res, id);if (owned.error) 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;const rl = await limits.tradePerUser(owned.auth.userId);if (!rl.success) return rateLimited(res, rl);@@ -216,6 +219,9 @@ async function handleUpdate(req, res, id, orderId) {let body;try { body = await readJson(req); } catch (e) { return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body'); }+ // Resuming a paused order re-arms it; pausing and other edits never need a signature.+ if (body?.paused === false && !(await requireRealFundsAgreement(req, res, { userId: owned.auth.userId, network: netOf(req), context: 'order-resume' }))) return;+try {const result = await updateOrder(id, orderId, body);if (!result) return error(res, 404, 'not_found', 'order not found');diff --git a/api/vaults/claim-fees.js b/api/vaults/claim-fees.jsindex 1dc817e4f..5eed495c1 100644--- a/api/vaults/claim-fees.js+++ b/api/vaults/claim-fees.js@@ -6,6 +6,7 @@import { randomUUID } from 'node:crypto';import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';import { limits } from '../_lib/rate-limit.js';import { authWrite, loadOwnedAgent } from '../_lib/vault-auth.js';import { getVault } from '../_lib/vault-store.js';@@ -40,6 +41,8 @@ export default wrap(async (req, res) => {let toAgent;try { toAgent = await loadOwnedAgent(toAgentId, userId); } catch (e) { return error(res, e.status || 400, e.code || 'bad_request', e.message); }+ if (!(await requireRealFundsAgreement(req, res, { userId, network: vault.network, context: 'vault-claim-fees' }))) return;+const result = await claimVaultFees({vaultId, ownerUserId: userId, toAgent,idempotencyKey: String(body.idempotency_key || `vault-fee-claim:${vaultId}:${randomUUID()}`).slice(0, 128),diff --git a/api/vaults/deposit.js b/api/vaults/deposit.jsindex 294d8ce29..12fd06ddc 100644--- a/api/vaults/deposit.js+++ b/api/vaults/deposit.js@@ -7,6 +7,7 @@import { randomUUID } from 'node:crypto';import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';import { limits } from '../_lib/rate-limit.js';import { authWrite, loadOwnedAgent } from '../_lib/vault-auth.js';import { getVault } from '../_lib/vault-store.js';@@ -40,6 +41,8 @@ export default wrap(async (req, res) => {const vault = await getVault(vaultId);if (!vault) return error(res, 404, 'not_found', 'vault not found');+ if (!(await requireRealFundsAgreement(req, res, { userId, network: vault.network, context: 'vault-deposit' }))) return;+let backerAgent;try { backerAgent = await loadOwnedAgent(backerAgentId, userId); } catch (e) { return error(res, e.status || 400, e.code || 'bad_request', e.message); }if (!backerAgent.meta?.solana_address || !backerAgent.meta?.encrypted_solana_secret) {diff --git a/api/vaults/redeem.js b/api/vaults/redeem.jsindex 935a5b3b6..f40b143d3 100644--- a/api/vaults/redeem.js+++ b/api/vaults/redeem.js@@ -7,6 +7,7 @@import { randomUUID } from 'node:crypto';import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';import { limits } from '../_lib/rate-limit.js';import { authWrite } from '../_lib/vault-auth.js';import { redeemFromVault } from '../_lib/vault-transfer.js';@@ -38,6 +39,8 @@ export default wrap(async (req, res) => {sharesIn = String(parsed);}+ if (!(await requireRealFundsAgreement(req, res, { userId, context: 'vault-redeem' }))) return;+const result = await redeemFromVault({vaultId, userId, shares: sharesIn,idempotencyKey: String(body.idempotency_key || `vault-redeem:${vaultId}:${userId}:${randomUUID()}`).slice(0, 128),diff --git a/api/vaults/trade.js b/api/vaults/trade.jsindex 9c7556e0d..93be96b07 100644--- a/api/vaults/trade.js+++ b/api/vaults/trade.js@@ -9,6 +9,7 @@import { randomUUID } from 'node:crypto';import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';import { limits } from '../_lib/rate-limit.js';import { authWrite } from '../_lib/vault-auth.js';import { getVault } from '../_lib/vault-store.js';@@ -57,6 +58,8 @@ export default wrap(async (req, res) => {if (amountRaw == null) return error(res, 400, 'validation_error', 'amount must be a positive number or "max"');}+ if (!(await requireRealFundsAgreement(req, res, { userId, network: vault.network, context: 'vault-trade' }))) return;+const result = await vaultTrade({vaultId, userId, side, mint, usdcInAtomics, amountRaw, slippageBps,idempotencyKey: String(body.idempotency_key || `vault-trade:${vaultId}:${side}:${mint}:${randomUUID()}`).slice(0, 128),diff --git a/public/legal/agreements.html b/public/legal/agreements.htmlindex 35c430a1c..bc542eff1 100644--- a/public/legal/agreements.html+++ b/public/legal/agreements.html@@ -146,123 +146,7 @@</main><div id="footer-container"></div><script src="/footer.js"></script>- <script type="module">- import { ensureRiskAck, hasRiskAck, AGREEMENT_DOCUMENTS, RISK_ACK_VERSION, RISK_ACK_ENDPOINT } from '/risk-ack.js';-- const statusEl = document.getElementById('status');- const docsEl = document.getElementById('docs');- const historySection = document.getElementById('history-section');- const historyBody = document.getElementById('history');-- const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);- const fmtDate = (iso) => {- try {- return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });- } catch {- return iso;- }- };-- docsEl.innerHTML = AGREEMENT_DOCUMENTS.map(- (d) => `<li><a href="${esc(d.path)}">${esc(d.title)}</a><span class="ver">Version ${d.version}</span></li>`,- ).join('');-- function renderStatus({ pill, tone, title, copy, actions }) {- statusEl.setAttribute('aria-busy', 'false');- statusEl.innerHTML = `- <div class="status-head fade-in"><span class="pill" data-tone="${tone}">${esc(pill)}</span></div>- <p class="status-title fade-in">${esc(title)}</p>- <p class="status-copy fade-in">${copy}</p>- <div class="actions fade-in">${actions}</div>`;- }-- function renderHistory(rows) {- if (!Array.isArray(rows) || rows.length === 0) {- historySection.hidden = true;- return;- }- historyBody.innerHTML = rows- .map(- (r) => `<tr>- <td>${esc(fmtDate(r.signedAt))}</td>- <td><em>${esc(r.signatureName)}</em></td>- <td>${r.version}${r.current ? '' : ' <span class="muted">(superseded)</span>'}</td>- <td class="muted">${esc(r.path || r.context || 'three.ws')}</td>- </tr>`,- )- .join('');- historySection.hidden = false;- }-- async function load() {- statusEl.setAttribute('aria-busy', 'true');- let status;- try {- const res = await fetch(`${RISK_ACK_ENDPOINT}?history=1`, { credentials: 'same-origin', headers: { accept: 'application/json' } });- if (!res.ok) throw new Error(`HTTP ${res.status}`);- status = await res.json();- } catch {- renderStatus({- pill: 'Unavailable',- tone: 'danger',- title: 'We could not load your agreement status.',- copy: 'Check your connection and try again. Your existing signatures are unaffected.',- actions: '<button class="btn btn-primary" type="button" data-retry>Try again</button>',- });- statusEl.querySelector('[data-retry]').addEventListener('click', load);- return;- }-- renderHistory(status.history);- const next = encodeURIComponent('/legal/agreements');-- if (!status.authenticated && hasRiskAck()) {- renderStatus({- pill: 'Signed in this browser',- tone: 'ok',- title: 'You signed the real-funds agreements in this browser.',- copy: 'That covers this browser only. Sign in and your account will ask you to sign once more, so the signature is attached to your account for the app and the API.',- actions: `<a class="btn btn-primary" href="/login?next=${next}">Sign in</a>`,- });- } else if (!status.authenticated) {- renderStatus({- pill: 'Not signed in',- tone: 'warn',- title: 'Sign in to attach your signature to your account.',- copy: 'A signature made while signed in covers your account everywhere, including the API. You can also sign here without an account, for example before funding someone else’s agent; that signature covers this browser.',- actions: `<a class="btn btn-primary" href="/login?next=${next}">Sign in</a><button class="btn" type="button" data-sign>Sign without an account</button>`,- });- } else if (status.signed) {- renderStatus({- pill: 'Signed',- tone: 'ok',- title: `Signed by ${status.signatureName || 'you'} on ${fmtDate(status.signedAt)}.`,- copy: `Your account has signed version ${RISK_ACK_VERSION} of the real-funds agreements. Real-funds features are unlocked. If any document changes materially, you will be asked to sign again.`,- actions: '<a class="btn" href="/dashboard">Go to dashboard</a>',- });- } else {- renderStatus({- pill: 'Signature required',- tone: 'warn',- title: 'Your account has not signed the current agreements.',- copy: 'Until you sign, three.ws refuses real-funds actions from your account, in the app and through the API. Read each document, then sign once.',- actions: '<button class="btn btn-primary" type="button" data-sign>Review and sign</button>',- });- }-- const signBtn = statusEl.querySelector('[data-sign]');- if (signBtn) {- signBtn.addEventListener('click', async () => {- signBtn.disabled = true;- const signed = await ensureRiskAck({ context: 'agreements-page', force: true });- signBtn.disabled = false;- if (signed) load();- });- }- }-- load();- </script>+ <script type="module" src="/legal/agreements.js"></script><script type="module" src="/i18n.js"></script></body></html>diff --git a/public/legal/agreements.js b/public/legal/agreements.jsnew file mode 100644index 000000000..1c280f1d0--- /dev/null+++ b/public/legal/agreements.js@@ -0,0 +1,119 @@+// /legal/agreements: shows the visitor's real-funds signature status and history,+// and opens the signing dialog. Loaded as a plain module from public/ so it can+// import the canonical gate at /risk-ack.js in dev and production alike.++import { ensureRiskAck, hasRiskAck, AGREEMENT_DOCUMENTS, RISK_ACK_VERSION, RISK_ACK_ENDPOINT } from '/risk-ack.js';++const statusEl = document.getElementById('status');+const docsEl = document.getElementById('docs');+const historySection = document.getElementById('history-section');+const historyBody = document.getElementById('history');++const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+const fmtDate = (iso) => {+ try {+ return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });+ } catch {+ return iso;+ }+};++docsEl.innerHTML = AGREEMENT_DOCUMENTS.map(+ (d) => `<li><a href="${esc(d.path)}">${esc(d.title)}</a><span class="ver">Version ${d.version}</span></li>`,+).join('');++function renderStatus({ pill, tone, title, copy, actions }) {+ statusEl.setAttribute('aria-busy', 'false');+ statusEl.innerHTML = `+ <div class="status-head fade-in"><span class="pill" data-tone="${tone}">${esc(pill)}</span></div>+ <p class="status-title fade-in">${esc(title)}</p>+ <p class="status-copy fade-in">${copy}</p>+ <div class="actions fade-in">${actions}</div>`;+}++function renderHistory(rows) {+ if (!Array.isArray(rows) || rows.length === 0) {+ historySection.hidden = true;+ return;+ }+ historyBody.innerHTML = rows+ .map(+ (r) => `<tr>+ <td>${esc(fmtDate(r.signedAt))}</td>+ <td><em>${esc(r.signatureName)}</em></td>+ <td>${r.version}${r.current ? '' : ' <span class="muted">(superseded)</span>'}</td>+ <td class="muted">${esc(r.path || r.context || 'three.ws')}</td>+ </tr>`,+ )+ .join('');+ historySection.hidden = false;+}++async function load() {+ statusEl.setAttribute('aria-busy', 'true');+ let status;+ try {+ const res = await fetch(`${RISK_ACK_ENDPOINT}?history=1`, { credentials: 'same-origin', headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ status = await res.json();+ } catch {+ renderStatus({+ pill: 'Unavailable',+ tone: 'danger',+ title: 'We could not load your agreement status.',+ copy: 'Check your connection and try again. Your existing signatures are unaffected.',+ actions: '<button class="btn btn-primary" type="button" data-retry>Try again</button>',+ });+ statusEl.querySelector('[data-retry]').addEventListener('click', load);+ return;+ }++ renderHistory(status.history);+ const next = encodeURIComponent('/legal/agreements');++ if (!status.authenticated && hasRiskAck()) {+ renderStatus({+ pill: 'Signed in this browser',+ tone: 'ok',+ title: 'You signed the real-funds agreements in this browser.',+ copy: 'That covers this browser only. Sign in and your account will ask you to sign once more, so the signature is attached to your account for the app and the API.',+ actions: `<a class="btn btn-primary" href="/login?next=${next}">Sign in</a>`,+ });+ } else if (!status.authenticated) {+ renderStatus({+ pill: 'Not signed in',+ tone: 'warn',+ title: 'Sign in to attach your signature to your account.',+ copy: 'A signature made while signed in covers your account everywhere, including the API. You can also sign here without an account, for example before funding someone else’s agent; that signature covers this browser.',+ actions: `<a class="btn btn-primary" href="/login?next=${next}">Sign in</a><button class="btn" type="button" data-sign>Sign without an account</button>`,+ });+ } else if (status.signed) {+ renderStatus({+ pill: 'Signed',+ tone: 'ok',+ title: `Signed by ${status.signatureName || 'you'} on ${fmtDate(status.signedAt)}.`,+ copy: `Your account has signed version ${RISK_ACK_VERSION} of the real-funds agreements. Real-funds features are unlocked. If any document changes materially, you will be asked to sign again.`,+ actions: '<a class="btn" href="/dashboard">Go to dashboard</a>',+ });+ } else {+ renderStatus({+ pill: 'Signature required',+ tone: 'warn',+ title: 'Your account has not signed the current agreements.',+ copy: 'Until you sign, three.ws refuses real-funds actions from your account, in the app and through the API. Read each document, then sign once.',+ actions: '<button class="btn btn-primary" type="button" data-sign>Review and sign</button>',+ });+ }++ const signBtn = statusEl.querySelector('[data-sign]');+ if (signBtn) {+ signBtn.addEventListener('click', async () => {+ signBtn.disabled = true;+ const signed = await ensureRiskAck({ context: 'agreements-page', force: status.authenticated === true });+ signBtn.disabled = false;+ if (signed) load();+ });+ }+}++load();diff --git a/tests/api-labor-endpoints.test.js b/tests/api-labor-endpoints.test.jsindex 5260dfac7..f833087d4 100644--- a/tests/api-labor-endpoints.test.js+++ b/tests/api-labor-endpoints.test.js@@ -42,6 +42,8 @@ vi.mock('../api/_lib/auth.js', () => ({extractBearer: vi.fn(() => null),}));vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));+// The real-funds agreement gate has its own suite (tests/real-funds-agreement.test.js).+vi.mock('../api/_lib/real-funds-agreement.js', () => ({ requireRealFundsAgreement: vi.fn(async () => true) }));vi.mock('../api/_lib/db.js', () => ({sql: vi.fn(async (...args) => {sqlState.calls.push(args);diff --git a/tests/api/mcp-agent.test.js b/tests/api/mcp-agent.test.jsindex e0b73264c..c6322da56 100644--- a/tests/api/mcp-agent.test.js+++ b/tests/api/mcp-agent.test.js@@ -9,6 +9,12 @@ const payerState = {payResult: null,payError: null,};+// The real-funds agreement gate has its own suite (tests/real-funds-agreement.test.js).+vi.mock('../../api/_lib/real-funds-agreement.js', () => ({+ currentSignatureFor: vi.fn(async () => ({ signedAt: '2026-09-17T00:00:00.000Z', signatureName: 'Test Signer', context: null })),+ agreementRequirement: () => ({ version: 2, sign_url: 'https://three.ws/legal/agreements', documents: [] }),+}));+vi.mock('../../api/_lib/x402-user-payer.js', () => ({resolveSpendEnabled: () => payerState.spendEnabled,getUserWalletStatus: vi.fn(async () => payerState.walletStatus),diff --git a/tests/real-funds-agreement-coverage.test.js b/tests/real-funds-agreement-coverage.test.jsnew file mode 100644index 000000000..b65fa53f8--- /dev/null+++ b/tests/real-funds-agreement-coverage.test.js@@ -0,0 +1,98 @@+// Coverage guard for the real-funds agreement.+//+// Every route under api/ (outside api/_lib and api/cron) that decrypts a+// custodial key, or imports an api/_lib module that does, must either enforce+// the signed agreements (requireRealFundsAgreement, or currentSignatureFor in+// tool handlers that have no HTTP response) or be listed in EXEMPT below with+// the reason no path in it moves a user's real funds on request. A new money+// endpoint that forgets the gate fails here instead of shipping.++import { describe, it, expect } from 'vitest';+import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';+import { join, relative, dirname, resolve } from 'node:path';++const ROOT = resolve(import.meta.dirname, '..');+const API = join(ROOT, 'api');++const KEY_USE = /\b(recoverSolanaAgentKeypair|recoverAgentKey|loadAgentKeypairForUser|loadAgentForSigning)\b/;+// Engines a route arms and a cron later executes with a decrypted key: the+// route itself never touches the key, so it is matched by what it imports.+const ARMS_ENGINE = /['"][./]+_lib\/orders\.js['"]/;+const GATE = /\b(requireRealFundsAgreement|currentSignatureFor)\b/;++const EXEMPT = {+ 'api/agents.js': 'creates agents and their empty wallets; no funds move',+ 'api/genome/breed.js': 'provisions a fresh empty wallet for the child agent',+ 'api/launcher/me.js': 'reads wallet balances only',+ 'api/stage/index.js': 'ensures a wallet exists for a stage; no funds move',+ 'api/user/wallet/index.js': 'creates the master wallet and reads balances; sends go through the gated send.js',+ 'api/agent-memory.js': 'signs memory records with the agent key; no transfer',+ 'api/agents/_id/_sub.js': 'config, reads, and message signing; no transfer',+ 'api/agents/_id/brain.js': 'agent key signs a digest; anchor gas is paid by the platform validator key',+ 'api/agents/alpha.js': 'read-only candidates and analysis',+ 'api/agents/copilot.js': 'renders proposal cards; execution happens on gated endpoints',+ 'api/autopilot/activity.js': 'read-only activity feed',+ 'api/avatars/fork.js': 'creates a fresh empty wallet for the fork; no funds move',+ 'api/irl/world-lines.js': 'agent key signs a proof-of-presence message; no transfer',+ 'api/labor/bid.js': 'bids move no money',+ 'api/labor/deliver.js': 'settlement pays the worker; the payer signed when posting',+ 'api/labor/release.js': 'moderator-only admin path',+ 'api/labor/tick.js': 'cron-only (requireCron)',+ 'api/swarms/[id].js': 'read-only state and stream',+ 'api/trading/scan.js': 'read-only candidate preview; never loads a key',+ 'api/user/wallet/history.js': 'read-only history',+};++function walk(dir, out = []) {+ for (const name of readdirSync(dir)) {+ const full = join(dir, name);+ if (statSync(full).isDirectory()) walk(full, out);+ else if (name.endsWith('.js')) out.push(full);+ }+ return out;+}++const all = walk(API);+const rel = (f) => relative(ROOT, f).split('\\').join('/');+const libKeyModules = new Set(+ all.filter((f) => rel(f).startsWith('api/_lib/') && KEY_USE.test(readFileSync(f, 'utf8'))).map((f) => resolve(f)),+);++function importsKeyModule(file, src) {+ for (const m of src.matchAll(/(?:from\s+|import\s*\(\s*)['"](\.[^'"]+)['"]/g)) {+ const target = resolve(dirname(file), m[1]);+ if (libKeyModules.has(target) || libKeyModules.has(`${target}.js`)) return true;+ }+ return false;+}++const routes = all.filter((f) => {+ const r = rel(f);+ return !r.startsWith('api/_lib/') && !r.startsWith('api/cron/');+});++const keyRoutes = routes+ .map((f) => ({ file: rel(f), src: readFileSync(f, 'utf8'), abs: f }))+ .filter(({ abs, src }) => KEY_USE.test(src) || ARMS_ENGINE.test(src) || importsKeyModule(abs, src));++describe('real-funds agreement coverage', () => {+ it('finds the custodial key routes it is guarding', () => {+ expect(keyRoutes.length).toBeGreaterThan(20);+ expect(keyRoutes.map((r) => r.file)).toContain('api/agents/solana-wallet.js');+ });++ it.each(keyRoutes.map((r) => [r.file, r]))('%s enforces the signed agreements or is exempt with a reason', (file, { src }) => {+ if (EXEMPT[file]) return;+ expect(GATE.test(src), `${file} uses a custodial key but never calls requireRealFundsAgreement. Gate its money paths, or add it to EXEMPT with the reason none move funds.`).toBe(true);+ });++ it('has no stale exemptions', () => {+ const keyFiles = new Set(keyRoutes.map((r) => r.file));+ for (const [file, reason] of Object.entries(EXEMPT)) {+ expect(existsSync(join(ROOT, file)), `${file} no longer exists`).toBe(true);+ expect(reason.length).toBeGreaterThan(8);+ expect(keyFiles.has(file), `${file} no longer touches a custodial key; drop the exemption`).toBe(true);+ expect(GATE.test(readFileSync(join(ROOT, file), 'utf8')), `${file} is gated now; drop the exemption`).toBe(false);+ }+ });+});