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.

test: rebuild stale route test doubles on the real modules so handlers stop 500ing in tests

nirholas025a9474c469
diff --git a/tests/agent-guard-endpoint.test.js b/tests/agent-guard-endpoint.test.js
index 04d914609..d1cf97a13 100644
--- a/tests/agent-guard-endpoint.test.js
+++ b/tests/agent-guard-endpoint.test.js
@@ -3,7 +3,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
// The endpoint is pure policy evaluation over the request body; the only
// impure edges are the rate limiter and the env-backed http helpers.
const agentGuardIp = vi.fn();
-vi.mock('../api/_lib/rate-limit.js', () => ({
+vi.mock('../api/_lib/rate-limit.js', async (importOriginal) => ({
+ ...(await importOriginal()),
limits: { agentGuardIp: (...a) => agentGuardIp(...a) },
}));
vi.mock('../api/_lib/env.js', () => ({
diff --git a/tests/agent-wallet-withdraw.test.js b/tests/agent-wallet-withdraw.test.js
index 9d77a22e0..3344acb59 100644
--- a/tests/agent-wallet-withdraw.test.js
+++ b/tests/agent-wallet-withdraw.test.js
@@ -42,10 +42,15 @@ vi.mock('../api/_lib/csrf.js', () => ({
}));
// ── db ──────────────────────────────────────────────────────────────────────
-const sqlState = { queue: [], calls: [] };
+// `listing` answers the marketplace check (is this balance promised to a listing
+// with open bids?) by query text, so the ordered queue only feeds the custody
+// reads and writes each case cares about.
+const sqlState = { queue: [], calls: [], listing: null };
vi.mock('../api/_lib/db.js', () => ({
sql: vi.fn(async (strings, ...values) => {
- sqlState.calls.push({ query: strings.join('?'), values });
+ const query = strings.join('?');
+ sqlState.calls.push({ query, values });
+ if (/from agent_listings/i.test(query)) return sqlState.listing ? [sqlState.listing] : [];
return sqlState.queue.length ? sqlState.queue.shift() : [];
}),
isDbUnavailableError: () => false,
@@ -167,6 +172,7 @@ function queueAgentRow() {
beforeEach(() => {
sqlState.queue = [];
sqlState.calls = [];
+ sqlState.listing = null;
connState.sent = 0;
connState.confirmErr = null;
recoverState.calls = 0;
@@ -221,6 +227,30 @@ describe('handleWithdraw — validation + safety', () => {
});
});
+describe('handleWithdraw: marketplace listing hold', () => {
+ it('refuses to withdraw a balance promised to a listing with open bids, before touching the key', async () => {
+ queueAgentRow();
+ sqlState.listing = { id: 'listing-1' };
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 0.1, destination: Keypair.generate().publicKey.toBase58() }), res, 'agent-1');
+ expect(res.statusCode).toBe(409);
+ expect(parse(res).error).toBe('balance_listed');
+ expect(recoverState.calls).toBe(0);
+ expect(connState.sent).toBe(0);
+ });
+
+ it('still previews a simulated withdrawal while the balance is listed', async () => {
+ queueAgentRow();
+ sqlState.listing = { id: 'listing-1' };
+ sqlState.queue.push([]); // idempotency lookup: none
+ const res = mockRes();
+ await handleWithdraw(mockReq({ asset: 'SOL', amount: 'max', destination: Keypair.generate().publicKey.toBase58(), simulate: true }), res, 'agent-1');
+ expect(res.statusCode).toBe(200);
+ expect(parse(res).data.simulated).toBe(true);
+ expect(connState.sent).toBe(0);
+ });
+});
+
describe('handleWithdraw — idempotency', () => {
it('replays a confirmed withdrawal for the same idempotency key without re-sending', async () => {
queueAgentRow();
diff --git a/tests/api/forge-nim.test.js b/tests/api/forge-nim.test.js
index c20834418..5c443d598 100644
--- a/tests/api/forge-nim.test.js
+++ b/tests/api/forge-nim.test.js
@@ -16,6 +16,21 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
clientIp: () => '127.0.0.1',
}));
+// A caller-supplied NIM is reached through the DNS-resolving, IP-pinned fetch,
+// which opens its own socket and so never sees the fetch double below. The
+// fixtures use offline `.example.com` hosts, so the pinned transport delegates to
+// globalThis.fetch here; DNS pinning and redirect re-validation are covered on
+// their own in tests/ssrf-hardening-guards.test.js. The handler's own baseUrl
+// guard (https only, no private or metadata hosts) still runs for real.
+const pinnedCalls = [];
+vi.mock('../../api/_lib/ssrf-guard.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ fetchSafePublicUrlPinned: async (url, init = {}, opts = {}) => {
+ pinnedCalls.push({ url, init, opts });
+ return globalThis.fetch(url, init);
+ },
+}));
+
const ORIGINAL_FETCH = globalThis.fetch;
// MODEL_TRELLIS_URL is cleared too, and never set: it points at our own async
// Cloud Run TRELLIS worker, and api/forge-nim.js deliberately does not read it.
@@ -25,6 +40,7 @@ const ENV_KEYS = ['NIM_TRELLIS_URL', 'MODEL_TRELLIS_URL', 'NVIDIA_API_KEY'];
const saved = {};
beforeEach(() => {
+ pinnedCalls.length = 0;
for (const k of ENV_KEYS) {
saved[k] = process.env[k];
delete process.env[k];
@@ -274,7 +290,8 @@ describe('POST /api/forge-nim — configuration & SSRF', () => {
expect(calls.length).toBe(0); // never reached the network
});
- it('accepts a public https baseUrl override', async () => {
+ it('accepts a public https baseUrl override through the pinned fetch, without the platform key', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-platform-secret';
const glb = fakeGlb(16);
const fetchMock = vi.fn(async () => jsonResponse({ artifacts: [{ base64: glb.toString('base64') }] }));
globalThis.fetch = fetchMock;
@@ -285,7 +302,12 @@ describe('POST /api/forge-nim — configuration & SSRF', () => {
makeRes(),
);
expect(body.ok).toBe(true);
+ expect(pinnedCalls.length).toBe(1);
+ expect(pinnedCalls[0].url).toBe('https://my-nim.example.com/v1/infer');
+ expect(Number.isFinite(pinnedCalls[0].opts.maxBytes)).toBe(true);
expect(fetchMock.mock.calls[0][0]).toBe('https://my-nim.example.com/v1/infer');
+ const headers = fetchMock.mock.calls[0][1].headers || {};
+ expect(Object.keys(headers).map((k) => k.toLowerCase())).not.toContain('authorization');
});
});
diff --git a/tests/api/marketplace-agents-csrf.test.js b/tests/api/marketplace-agents-csrf.test.js
index c37b59454..e05b354b3 100644
--- a/tests/api/marketplace-agents-csrf.test.js
+++ b/tests/api/marketplace-agents-csrf.test.js
@@ -15,7 +15,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { Readable } from 'node:stream';
const authState = { session: { id: 'aaaa0000-0000-0000-0000-000000000001' }, bearer: null };
-vi.mock('../../api/_lib/auth.js', () => ({
+vi.mock('../../api/_lib/auth.js', async (importOriginal) => ({
+ ...(await importOriginal()),
getSessionUser: vi.fn(async () => authState.session),
authenticateBearer: vi.fn(async () => authState.bearer),
extractBearer: vi.fn((req) => {
diff --git a/tests/api/mcp-memory.test.js b/tests/api/mcp-memory.test.js
index 255d14593..47cc1f79f 100644
--- a/tests/api/mcp-memory.test.js
+++ b/tests/api/mcp-memory.test.js
@@ -180,12 +180,12 @@ function makeRes() {
};
}
-async function call(name, args, { scope = 'memory:read memory:write' } = {}) {
+async function call(name, args, { scope = 'memory:read memory:write', headers = {} } = {}) {
authState.extracted = 'valid-token';
authState.bearer = { userId: 'user-1', scope, source: 'oauth' };
const req = makeReq({
body: { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } },
- headers: { authorization: 'Bearer valid-token' },
+ headers: { authorization: 'Bearer valid-token', ...headers },
});
const res = makeRes();
await handler(req, res);
@@ -195,6 +195,24 @@ async function call(name, args, { scope = 'memory:read memory:write' } = {}) {
const AGENT_ID = '11111111-1111-4111-8111-111111111111';
const MEM_ID = '22222222-2222-4222-8222-222222222222';
+// `forget` cannot be undone, so the tool policy (@three-ws/mcp-policy) keeps it
+// off by default and requires a fresh `recall` preview for the same agent plus
+// confirm_delete: true. A connection turns it on with the X-Three-Tools header,
+// exactly as `npx three-ws tools` does.
+const FORGET_ON = { 'x-three-tools': 'default,forget' };
+
+/** Run the recall that authorizes a forget and return the preview id it issues. */
+async function recallPreviewId() {
+ sqlState.queue = [
+ [{ user_id: 'user-1' }], // ownsAgent
+ [], // candidates
+ ];
+ const { body } = await call('recall', { agent_id: AGENT_ID, query: 'mcp' }, { headers: FORGET_ON });
+ const id = body.result?._meta?.['three.ws/preview']?.preview_id;
+ expect(typeof id).toBe('string');
+ return id;
+}
+
beforeEach(() => {
authState.extracted = null;
authState.bearer = null;
@@ -270,10 +288,39 @@ describe('ownership', () => {
});
it('forget refuses a memory owned by another user', async () => {
+ const previewId = await recallPreviewId();
sqlState.queue = [[{ id: MEM_ID, user_id: 'someone-else' }]];
- const { body } = await call('forget', { memory_id: MEM_ID });
+ const { body } = await call(
+ 'forget',
+ { memory_id: MEM_ID, agent_id: AGENT_ID, preview_id: previewId, confirm_delete: true },
+ { headers: FORGET_ON },
+ );
expect(body.result.isError).toBe(true);
expect(body.result.content[0].text).toMatch(/does not belong to you/i);
+ expect(sqlState.calls.some((c) => /delete from agent_memories/i.test(c.query))).toBe(false);
+ });
+});
+
+// ── Tool policy on the destructive tool ──────────────────────────────────────
+describe('forget policy', () => {
+ it('is off for a connection that has not turned it on, before any query runs', async () => {
+ const { body } = await call('forget', { memory_id: MEM_ID });
+ expect(body.result.isError).toBe(true);
+ expect(body.result.structuredContent.reason).toBe('tool_disabled');
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('needs confirm_delete and a recall preview even when turned on', async () => {
+ const { body: noConfirm } = await call('forget', { memory_id: MEM_ID, agent_id: AGENT_ID }, { headers: FORGET_ON });
+ expect(noConfirm.result.structuredContent.reason).toBe('confirmation_required');
+
+ const { body: noPreview } = await call(
+ 'forget',
+ { memory_id: MEM_ID, agent_id: AGENT_ID, confirm_delete: true },
+ { headers: FORGET_ON },
+ );
+ expect(noPreview.result.structuredContent.reason).toBe('preview_required');
+ expect(sqlState.calls).toHaveLength(0);
});
});
@@ -356,11 +403,16 @@ describe('round trip', () => {
});
it('forgets a memory the caller owns', async () => {
+ const previewId = await recallPreviewId();
sqlState.queue = [
[{ id: MEM_ID, user_id: 'user-1' }], // ownership join
[], // DELETE
];
- const { body } = await call('forget', { memory_id: MEM_ID });
+ const { body } = await call(
+ 'forget',
+ { memory_id: MEM_ID, agent_id: AGENT_ID, preview_id: previewId, confirm_delete: true },
+ { headers: FORGET_ON },
+ );
expect(body.error).toBeUndefined();
expect(body.result.structuredContent).toEqual({ ok: true, id: MEM_ID });
expect(body.result.content[0].text).toContain(MEM_ID);
diff --git a/tests/api/onboarding-actions.test.js b/tests/api/onboarding-actions.test.js
index 6dfc3391a..b765fe36c 100644
--- a/tests/api/onboarding-actions.test.js
+++ b/tests/api/onboarding-actions.test.js
@@ -18,7 +18,8 @@ const csrfState = { rows: [] };
const dbState = { avatars: [], agents: [], updates: [] };
const rlState = { upload: true, authIp: true, avatarLink: true };
-vi.mock('../../api/_lib/auth.js', () => ({
+vi.mock('../../api/_lib/auth.js', async (importOriginal) => ({
+ ...(await importOriginal()),
getSessionUser: vi.fn(async () => authState.session),
authenticateBearer: vi.fn(async () => authState.bearer),
extractBearer: vi.fn((req) => {
diff --git a/tests/api/security-csrf-gates.test.js b/tests/api/security-csrf-gates.test.js
index 2943c370b..bb64889e6 100644
--- a/tests/api/security-csrf-gates.test.js
+++ b/tests/api/security-csrf-gates.test.js
@@ -160,9 +160,19 @@ vi.mock('../../api/_lib/validate.js', async (importOriginal) => ({
parse: vi.fn((schema, data) => schema.parse(data)),
}));
-vi.mock('../../api/_lib/env.js', () => ({
- env: { APP_ORIGIN: 'http://localhost:3000', ADMIN_ADDRESSES: new Set() },
-}));
+// Pin only the fields these gates read; every other getter (the $THREE mint and
+// decimals the token layer reads at module scope, among others) keeps its real
+// default, so a newly imported module never meets an `undefined` config value.
+vi.mock('../../api/_lib/env.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ env: Object.create(actual.env, {
+ APP_ORIGIN: { value: 'http://localhost:3000' },
+ ADMIN_ADDRESSES: { value: new Set() },
+ }),
+ };
+});
vi.mock('../../api/_lib/sentry.js', () => ({
captureException: vi.fn(),