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(api): track the intentional contract changes behind 12 failing API suites

nirholasfce389783acc
diff --git a/tests/agent-guard-endpoint.test.js b/tests/agent-guard-endpoint.test.js
index 04d914609..82aa86633 100644
--- a/tests/agent-guard-endpoint.test.js
+++ b/tests/agent-guard-endpoint.test.js
@@ -5,6 +5,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const agentGuardIp = vi.fn();
vi.mock('../api/_lib/rate-limit.js', () => ({
limits: { agentGuardIp: (...a) => agentGuardIp(...a) },
+ clientIp: (req) => req.socket?.remoteAddress || '0.0.0.0',
}));
vi.mock('../api/_lib/env.js', () => ({
env: { APP_ORIGIN: 'http://localhost:3000', ISSUER: 'http://t', MCP_RESOURCE: 'http://t' },
diff --git a/tests/agent-wallet-withdraw.test.js b/tests/agent-wallet-withdraw.test.js
index 9d77a22e0..ebbeb4519 100644
--- a/tests/agent-wallet-withdraw.test.js
+++ b/tests/agent-wallet-withdraw.test.js
@@ -42,10 +42,14 @@ vi.mock('../api/_lib/csrf.js', () => ({
}));
// ── db ──────────────────────────────────────────────────────────────────────
-const sqlState = { queue: [], calls: [] };
+// The marketplace "balance is promised to bidders" lookup is answered from its
+// own slot so it never consumes a row a test queued for the idempotency path.
+const sqlState = { queue: [], calls: [], listing: [] };
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 (query.includes('FROM agent_listings')) return sqlState.listing;
return sqlState.queue.length ? sqlState.queue.shift() : [];
}),
isDbUnavailableError: () => false,
@@ -167,6 +171,7 @@ function queueAgentRow() {
beforeEach(() => {
sqlState.queue = [];
sqlState.calls = [];
+ sqlState.listing = [];
connState.sent = 0;
connState.confirmErr = null;
recoverState.calls = 0;
@@ -212,6 +217,17 @@ describe('handleWithdraw — validation + safety', () => {
expect(connState.sent).toBe(0);
});
+ it('refuses with 409 while the balance is promised to an open marketplace bid, without 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('forbids withdrawing from an agent the caller does not own', async () => {
sqlState.queue.push([{ id: 'agent-1', user_id: 'someone-else', meta: AGENT_META }]);
const res = mockRes();
diff --git a/tests/api/forge-nim.test.js b/tests/api/forge-nim.test.js
index c20834418..d93737743 100644
--- a/tests/api/forge-nim.test.js
+++ b/tests/api/forge-nim.test.js
@@ -16,6 +16,16 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
clientIp: () => '127.0.0.1',
}));
+// A caller-supplied NIM host is reached only through the DNS-pinned SSRF fetch,
+// never the global fetch. The guard itself stays real (private targets are still
+// refused below); only the outbound pinned call is captured so the suite stays
+// offline and can assert what a caller's host receives.
+const pinnedFetch = vi.fn();
+vi.mock('../../api/_lib/ssrf-guard.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ fetchSafePublicUrlPinned: (...a) => pinnedFetch(...a),
+}));
+
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.
@@ -274,10 +284,12 @@ 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') }] }));
+ const fetchMock = vi.fn();
globalThis.fetch = fetchMock;
+ pinnedFetch.mockReset().mockResolvedValue(jsonResponse({ artifacts: [{ base64: glb.toString('base64') }] }));
const { body } = await dispatch(
makeReq({
body: { mode: 'image', image: 'data:image/png;base64,iVBORw0KGgo=', baseUrl: 'https://my-nim.example.com' },
@@ -285,7 +297,12 @@ describe('POST /api/forge-nim — configuration & SSRF', () => {
makeRes(),
);
expect(body.ok).toBe(true);
- expect(fetchMock.mock.calls[0][0]).toBe('https://my-nim.example.com/v1/infer');
+ expect(fetchMock).not.toHaveBeenCalled();
+ const [url, init] = pinnedFetch.mock.calls[0];
+ expect(url).toBe('https://my-nim.example.com/v1/infer');
+ const headerNames = Object.keys(init.headers || {}).map((k) => k.toLowerCase());
+ expect(headerNames).not.toContain('authorization');
+ expect(JSON.stringify(init)).not.toContain('nvapi-platform-secret');
});
});
diff --git a/tests/api/leaderboard-rollup-cron.test.js b/tests/api/leaderboard-rollup-cron.test.js
index 72ba73e81..f60527b39 100644
--- a/tests/api/leaderboard-rollup-cron.test.js
+++ b/tests/api/leaderboard-rollup-cron.test.js
@@ -10,11 +10,16 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+// Ranking queries answer from sqlMock; composable fragments (the `launches`
+// metric builds its `limit N` clause with sql`...` before the main query, via
+// api/_lib/launch-counts.js) are inert and must not consume a queued result.
const sqlMock = vi.fn(async () => []);
+const isFragment = (strings) => !/^\s*(with|select)\b/i.test(strings.join(''));
+const sql = (strings, ...values) => (isFragment(strings) ? { fragment: true } : sqlMock(strings, ...values));
const unlockBadge = vi.fn(async () => true);
vi.mock('../../api/_lib/db.js', () => ({
- sql: sqlMock,
+ sql,
isDbUnavailableError: () => false,
isDbCapacityError: () => false,
isStoragePressured: async () => ({ pressured: false }),
diff --git a/tests/api/marketplace-agents-csrf.test.js b/tests/api/marketplace-agents-csrf.test.js
index c37b59454..8128079ef 100644
--- a/tests/api/marketplace-agents-csrf.test.js
+++ b/tests/api/marketplace-agents-csrf.test.js
@@ -22,6 +22,9 @@ vi.mock('../../api/_lib/auth.js', () => ({
const h = req?.headers?.authorization || '';
return h.startsWith('Bearer ') ? h.slice(7) : null;
}),
+ // Mirrors api/_lib/auth.js: csrf.js keys the bearer exemption on whether a
+ // session cookie is present to ride along on a cross-site request.
+ hasSessionCookie: vi.fn((req) => /(?:^|;\s*)(?:__Host-)?sid=/.test(req?.headers?.cookie || '')),
}));
const sqlQueue = [];
@@ -164,4 +167,17 @@ describe('/api/marketplace/agents writes require a CSRF token', () => {
expect(res.statusCode).toBe(200);
expect(json.data).toEqual({ bookmarked: true });
});
+
+ it('does not exempt a session cookie that carries a junk bearer header alongside it', async () => {
+ authState.bearer = null; // the bearer authenticates as nobody
+ const { res, json } = await invoke(
+ makeReq('POST', `/api/marketplace/agents/${AGENT_ID}/bookmark`, {
+ headers: { cookie: '__Host-sid=victim-session', authorization: 'Bearer x' },
+ }),
+ makeRes(),
+ );
+ expect(res.statusCode).toBe(403);
+ expect(json.error).toBe('csrf_missing');
+ expect(sqlCalls).toHaveLength(0);
+ });
});
diff --git a/tests/api/onboarding-actions.test.js b/tests/api/onboarding-actions.test.js
index 6dfc3391a..07a29c8ee 100644
--- a/tests/api/onboarding-actions.test.js
+++ b/tests/api/onboarding-actions.test.js
@@ -25,6 +25,9 @@ vi.mock('../../api/_lib/auth.js', () => ({
const header = req?.headers?.authorization || '';
return header.startsWith('Bearer ') ? header.slice(7) : null;
}),
+ // Mirrors api/_lib/auth.js: csrf.js keys the bearer exemption on whether a
+ // session cookie is present to ride along on a cross-site request.
+ hasSessionCookie: vi.fn((req) => /(?:^|;\s*)(?:__Host-)?sid=/.test(req?.headers?.cookie || '')),
hasScope: vi.fn((scope, want) => String(scope || '').split(/[\s,]+/).includes(want)),
}));
diff --git a/tests/api/pump.test.js b/tests/api/pump.test.js
index ea453efef..725936582 100644
--- a/tests/api/pump.test.js
+++ b/tests/api/pump.test.js
@@ -18,10 +18,16 @@ vi.mock('../../api/_lib/auth.js', async () => {
});
// ── SQL mock ──────────────────────────────────────────────────────────────
-const sqlState = { queue: [], calls: [] };
+// by-agent also reads the agent's non-Solana launches from
+// fixed_supply_launches (the main query plus its where/join fragment). Those
+// answer from their own slot so they never consume a row queued for the
+// pump.fun mint, stats, or burns reads.
+const sqlState = { queue: [], calls: [], fixedSupply: [] };
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 (/fixed_supply_launches|\bf\.agent_id\b/.test(query)) return sqlState.fixedSupply;
if (sqlState.queue.length === 0) return [];
return sqlState.queue.shift();
}),
@@ -155,7 +161,7 @@ function pumpAction(action) {
}
function resetAll() {
authState.session = null; authState.bearer = null;
- sqlState.queue = []; sqlState.calls = [];
+ sqlState.queue = []; sqlState.calls = []; sqlState.fixedSupply = [];
mockPumpAgentOffline.create.mockClear();
mockPumpAgentOffline.acceptPayment.mockClear();
mockPumpAgentOffline.withdraw.mockClear();
diff --git a/tests/api/security-csrf-gates.test.js b/tests/api/security-csrf-gates.test.js
index 2943c370b..8c2c4b520 100644
--- a/tests/api/security-csrf-gates.test.js
+++ b/tests/api/security-csrf-gates.test.js
@@ -160,8 +160,15 @@ vi.mock('../../api/_lib/validate.js', async (importOriginal) => ({
parse: vi.fn((schema, data) => schema.parse(data)),
}));
+// api/agents.js bills inference through credits.js, which reaches the $THREE
+// token config at import time, so the mint + decimals must be present here.
vi.mock('../../api/_lib/env.js', () => ({
- env: { APP_ORIGIN: 'http://localhost:3000', ADMIN_ADDRESSES: new Set() },
+ env: {
+ APP_ORIGIN: 'http://localhost:3000',
+ ADMIN_ADDRESSES: new Set(),
+ THREE_TOKEN_MINT: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ THREE_TOKEN_DECIMALS: 6,
+ },
}));
vi.mock('../../api/_lib/sentry.js', () => ({
diff --git a/tests/api/x402-pay-routing.test.js b/tests/api/x402-pay-routing.test.js
index 36172b9c6..6acaa61b5 100644
--- a/tests/api/x402-pay-routing.test.js
+++ b/tests/api/x402-pay-routing.test.js
@@ -36,12 +36,17 @@ vi.mock('../../api/_lib/db.js', () => ({ sql: vi.fn(async () => []), isDbUnavail
// No shared platform wallet configured + no dev keypair file → loadAgentKeypair()
// throws config-missing, which is the deterministic outcome we assert for the
-// fallback path (the warn must already have fired before this throws).
-vi.mock('node:fs', () => ({
- readFileSync: () => {
- throw new Error('no dev keypair');
- },
-}));
+// fallback path (the warn must already have fired before this throws). Only the
+// dev test-wallet read is refused: repo data the import graph loads at module
+// time (data/plans.json via api/payments/_config.js) still reads from disk.
+vi.mock('node:fs', async (importOriginal) => {
+ const actual = await importOriginal();
+ const readFileSync = (file, ...rest) => {
+ if (String(file).includes('x402-test-wallets')) throw new Error('no dev keypair');
+ return actual.readFileSync(file, ...rest);
+ };
+ return { ...actual, readFileSync, default: { ...actual, readFileSync } };
+});
delete process.env.X402_AGENT_SOLANA_SECRET_BASE58;
diff --git a/tests/pump-alert-eval.test.js b/tests/pump-alert-eval.test.js
index a7c3c09ae..747045229 100644
--- a/tests/pump-alert-eval.test.js
+++ b/tests/pump-alert-eval.test.js
@@ -13,6 +13,7 @@ import {
deriveRuleLabel,
MINT_TARGETED_KINDS,
AGENT_TARGETED_KINDS,
+ MARKET_TARGETED_KINDS,
THRESHOLD_KINDS,
} from '../api/_lib/pump-alert-eval.js';
@@ -205,6 +206,12 @@ describe('kind classification constants', () => {
it('partitions kinds correctly', () => {
expect(MINT_TARGETED_KINDS).toEqual(['price_above', 'price_below', 'whale_buy']);
expect(AGENT_TARGETED_KINDS).toEqual(['new_mint']);
- expect(THRESHOLD_KINDS).toEqual(['price_above', 'price_below', 'whale_buy']);
+ // A prediction-market outcome crossing a probability threshold targets a
+ // market, not a mint or an agent, and carries a threshold like the price kinds.
+ expect(MARKET_TARGETED_KINDS).toEqual(['market_price']);
+ expect(THRESHOLD_KINDS).toEqual(['price_above', 'price_below', 'whale_buy', 'market_price']);
+ // Every targeted kind belongs to exactly one target family.
+ const targeted = [...MINT_TARGETED_KINDS, ...AGENT_TARGETED_KINDS, ...MARKET_TARGETED_KINDS];
+ expect(new Set(targeted).size).toBe(targeted.length);
});
});
diff --git a/tests/vanity-grinder-batch.test.js b/tests/vanity-grinder-batch.test.js
index 255723cab..1ae1aca05 100644
--- a/tests/vanity-grinder-batch.test.js
+++ b/tests/vanity-grinder-batch.test.js
@@ -20,7 +20,7 @@
// tests/vanity-wasm-grinder.test.js covers the grind loop itself (stop signal,
// exhaustion). This file covers the orchestration around it.
-import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest';
import { execFile } from 'node:child_process';
import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -283,13 +283,48 @@ describe('GCE MIG shard resolution', () => {
expect(new Set(names.map((n) => hashShardIndex(n, 8))).size).toBeGreaterThan(1);
});
- it('falls back to shard 0 off GCE rather than blocking on the metadata server', async () => {
+ // The metadata server is simulated: this suite also runs on Google-hosted
+ // machines (Cloud Workstations, Cloud Build), where the real one answers and
+ // the "off GCE" branch would never be exercised.
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('falls back to shard 0 off GCE, where the metadata host does not resolve', async () => {
const { resolveGceShardIndex } = await import('../workers/vanity-grinder/gce-shard.mjs');
+ vi.stubGlobal('fetch', vi.fn(async () => {
+ throw new TypeError('fetch failed');
+ }));
+ const resolved = await resolveGceShardIndex(4, () => {});
+ expect(resolved).toEqual({ index: 0, source: 'unavailable', instance: '' });
+ });
+
+ it('bounds a hung metadata probe instead of blocking the run', async () => {
+ const { resolveGceShardIndex } = await import('../workers/vanity-grinder/gce-shard.mjs');
+ vi.stubGlobal('fetch', vi.fn((url, init) => new Promise((_, reject) => {
+ init.signal.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')));
+ })));
const t0 = performance.now();
const resolved = await resolveGceShardIndex(4, () => {});
expect(resolved.source).toBe('unavailable');
expect(resolved.index).toBe(0);
- // The metadata probe is bounded; a hung DNS lookup must not stall a run.
expect(performance.now() - t0).toBeLessThan(15_000);
});
+
+ it('degrades to the name hash on GCE when the group listing is refused', async () => {
+ const { resolveGceShardIndex, hashShardIndex } = await import('../workers/vanity-grinder/gce-shard.mjs');
+ const name = 'vanity-grinder-x7k2';
+ const metadata = {
+ 'instance/name': name,
+ 'instance/attributes/created-by': 'projects/1/zones/us-central1-a/instanceGroupManagers/vanity-grinder',
+ 'instance/service-accounts/default/token': JSON.stringify({ access_token: 'sa-token' }),
+ };
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ const key = String(url).split('/computeMetadata/v1/')[1];
+ if (key in metadata) return new Response(metadata[key], { status: 200 });
+ return new Response('permission denied', { status: 403 });
+ }));
+ const resolved = await resolveGceShardIndex(4, () => {});
+ expect(resolved).toEqual({ index: hashShardIndex(name, 4), source: 'name-hash', instance: name });
+ });
});