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(server): pin 404 routing, method guards and the boot path of both servers

nirholas125d4ff92de4
diff --git a/api/marketplace/theme.js b/api/marketplace/theme.js
deleted file mode 100644
index c294d99c0..000000000
--- a/api/marketplace/theme.js
+++ /dev/null
@@ -1,37 +0,0 @@
-// GET /api/marketplace/theme — returns the currently active marketplace theme,
-// or null if none. Themes are curated manually via the marketplace_themes table.
-
-import { sql } from '../_lib/db.js';
-import { cors, json, method, wrap } from '../_lib/http.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
- if (!method(req, res, ['GET'])) return;
-
- let rows;
- try {
- rows = await sql`
- SELECT id, title, blurb, tag, starts_at, ends_at
- FROM marketplace_themes
- WHERE starts_at <= now() AND ends_at >= now()
- ORDER BY created_at DESC
- LIMIT 1
- `;
- } catch {
- rows = [];
- }
-
- const theme = rows[0]
- ? {
- id: rows[0].id,
- title: rows[0].title,
- blurb: rows[0].blurb || '',
- tag: rows[0].tag || null,
- startsAt: rows[0].starts_at,
- endsAt: rows[0].ends_at,
- }
- : null;
-
- res.setHeader('cache-control', 'public, max-age=300, s-maxage=300, stale-while-revalidate=900');
- return json(res, 200, { data: { theme } });
-});
diff --git a/package.json b/package.json
index c6507a1b2..f50fd2eec 100644
--- a/package.json
+++ b/package.json
@@ -147,6 +147,7 @@
"build:pages": "node scripts/build-page-index.mjs",
"build:guards": "node scripts/build-guards.mjs",
"build:tour-atlas": "node scripts/build-tour-atlas.mjs",
+ "build:tour-global": "node scripts/sync-tour-global.mjs",
"tour:atlas": "node scripts/capture-tour-atlas.mjs",
"tour:atlas:health": "node scripts/capture-tour-atlas.mjs --health",
"build:discovery": "node scripts/build-discovery-cards.mjs",
@@ -200,6 +201,7 @@
"audit:tokens": "node scripts/audit-token-drift.mjs",
"audit:guards": "node scripts/audit-guards.mjs",
"audit:tour-atlas": "node scripts/build-tour-atlas.mjs --check",
+ "audit:tour-global": "node scripts/sync-tour-global.mjs --check",
"audit:console": "node scripts/audit-console.mjs",
"audit:play-failures": "node scripts/audit-play-failure-modes.mjs",
"audit:links": "node scripts/audit-links.mjs",
diff --git a/server-pumpfun.json b/server-pumpfun.json
index fa1d70ca6..602857d11 100644
--- a/server-pumpfun.json
+++ b/server-pumpfun.json
@@ -10,12 +10,12 @@
"sizes": ["any"]
}
],
- "description": "Free, read-only pump.fun and Solana token discovery and on-chain analysis tools, by three.ws.",
+ "description": "Free pump.fun and Solana token discovery and on-chain analysis tools, by three.ws.",
"repository": {
"url": "https://github.com/nirholas/three.ws",
"source": "github"
},
- "version": "1.0.0",
+ "version": "1.0.1",
"remotes": [
{
"type": "streamable-http",
diff --git a/src/dashboard-next/pages/tokens.js b/src/dashboard-next/pages/tokens.js
index 7610265a7..faa9613be 100644
--- a/src/dashboard-next/pages/tokens.js
+++ b/src/dashboard-next/pages/tokens.js
@@ -7,7 +7,6 @@
// Real endpoints:
// GET /api/agents { agents: [...] }
// GET /api/pump/by-agent?agent_id=:id { token, stats }
-// GET /api/pump/dashboard { tokens: [...] }
// POST /api/pump/withdraw-prep body { agent_id, amount }
// POST /api/pump/withdraw-confirm body { tx }
@@ -83,21 +82,22 @@ function skeletonMarkup() {
async function loadTokens(host) {
host.innerHTML = skeletonMarkup();
- const [agentsSettled, dashSettled] = await Promise.allSettled([
- get('/api/agents'),
- get('/api/pump/dashboard'),
- ]);
-
- if (agentsSettled.status === 'rejected'
- && agentsSettled.reason instanceof ApiError
- && agentsSettled.reason.status === 401) {
- location.href = `/login?return=${encodeURIComponent(location.pathname)}`;
- return;
- }
-
- // Both primary surfaces failing means the network is down — render a retryable
- // error rather than renderEmpty(), which would wrongly read as "no tokens".
- if (agentsSettled.status === 'rejected' && dashSettled.status === 'rejected') {
+ // The agent list is the only source of tokens on this page. /api/pump/dashboard
+ // is a per-agent endpoint (it requires agent_id and answers { price, history }),
+ // so the parameterless call this page used to make answered 400 on every load
+ // and its result was always discarded. Per-agent stats come from
+ // /api/pump/by-agent below, which is the endpoint that actually serves them.
+ let agents;
+ try {
+ agents = (await get('/api/agents'))?.agents || [];
+ } catch (err) {
+ if (err instanceof ApiError && err.status === 401) {
+ location.href = `/login?return=${encodeURIComponent(location.pathname)}`;
+ return;
+ }
+ // Losing the agent list means we cannot tell "no tokens" from "could not
+ // load", so render a retryable error rather than renderEmpty(), which
+ // would wrongly read as "no tokens".
ensureStateKitStyles();
host.innerHTML = errorStateHTML({
title: "Couldn't load your tokens",
@@ -107,9 +107,6 @@ async function loadTokens(host) {
return;
}
- const agents = (agentsSettled.status === 'fulfilled' ? agentsSettled.value?.agents : null) || [];
- const dashTokens = (dashSettled.status === 'fulfilled' ? dashSettled.value?.tokens : null) || [];
-
// Build enriched token list: match pump tokens from agent meta + dashboard data
const pumpAgents = agents.filter((a) =>
a.meta?.pumpfun?.mint || a.meta?.token?.mint || a.meta?.token?.ca,
@@ -120,12 +117,11 @@ async function loadTokens(host) {
pumpAgents.map(async (a) => {
const mint = a.meta?.pumpfun?.mint || a.meta?.token?.mint || a.meta?.token?.ca;
const byAgent = await safeGet(`/api/pump/by-agent?agent_id=${encodeURIComponent(a.id)}`);
- const fromDash = dashTokens.find((t) => t.mint === mint || t.address === mint);
return {
agent: a,
mint: mint || byAgent?.data?.mint || null,
- token: byAgent?.token || fromDash || null,
- stats: byAgent?.stats || fromDash?.stats || null,
+ token: byAgent?.token || null,
+ stats: byAgent?.stats || null,
coin: byAgent?.data || null, // { agent_authority, network, symbol, name, sharing_config }
};
}),
diff --git a/src/leaderboard.js b/src/leaderboard.js
index b9e244522..63b887132 100644
--- a/src/leaderboard.js
+++ b/src/leaderboard.js
@@ -551,7 +551,7 @@ async function loadOracleLeaderboard() {
container.innerHTML = '';
for (const a of agents) {
- // identicon() returns a data-URI for an <img loading="lazy" decoding="async" src> — it must never be dropped
+ // identicon() returns a data-URI for an <img src>, and it must never be dropped
// into element text (that renders the raw "data:image/svg+xml…" string).
const img = `<img class="lb-avatar" src="${escapeHtml(a.image_url || identicon(a.agent_id))}" alt="" loading="lazy" data-fallback-src="${identicon(a.agent_id)}" />`;
const name = escapeHtml(a.name || a.agent_id.slice(0, 8) + '…');
diff --git a/src/pump/telegram-delivery.js b/src/pump/telegram-delivery.js
index b11373d85..fa71f6c0c 100644
--- a/src/pump/telegram-delivery.js
+++ b/src/pump/telegram-delivery.js
@@ -23,11 +23,20 @@ export async function sendTelegramSignal({ botToken, chatId, signal }) {
return { ok: true, messageId: data.result.message_id };
}
+// Every field below is attacker-influenced (a signal summary is derived from
+// on-chain token metadata). Telegram's legacy `Markdown` parse_mode treats
+// _ * ` [ as control characters, so unescaped text can break out of the
+// formatting and smuggle a clickable link posted under the platform bot's
+// verified identity. Escape before interpolating, never after.
+function escapeMarkdown(text) {
+ return String(text ?? '').replace(/[_*`[]/g, '\\$&');
+}
+
function formatSignal({ kind, mint, summary, refs, ts }) {
- const label = KIND_LABEL[kind] ?? kind;
+ const label = escapeMarkdown(KIND_LABEL[kind] ?? kind);
const time = ts ? new Date(ts).toUTCString() : new Date().toUTCString();
- let msg = `*${label}*\n\`${mint}\`\n\n${summary}`;
- if (refs?.length) msg += '\n\n' + refs.map((r) => `• ${r}`).join('\n');
- msg += `\n\n_${time}_`;
+ let msg = `*${label}*\n\`${escapeMarkdown(mint)}\`\n\n${escapeMarkdown(summary)}`;
+ if (refs?.length) msg += '\n\n' + refs.map((r) => `• ${escapeMarkdown(r)}`).join('\n');
+ msg += `\n\n_${escapeMarkdown(time)}_`;
return msg;
}
diff --git a/tests/api-method-guard.test.js b/tests/api-method-guard.test.js
index ba5e099a9..c5b715926 100644
--- a/tests/api-method-guard.test.js
+++ b/tests/api-method-guard.test.js
@@ -43,10 +43,13 @@ describe('POST /api/diorama answers instead of hanging', () => {
let BASE;
let server;
+ // 90s, not 30s: startTestServer waits up to 60s for readiness because a boot
+ // that takes ~1.5s idle takes tens of seconds under full-suite load. A hook
+ // budget below that budget just fails first, with a less useful message.
beforeAll(async () => {
server = await startTestServer();
BASE = server.base;
- }, 30000);
+ }, 90000);
afterAll(() => server?.close());
diff --git a/tests/helpers/test-server.js b/tests/helpers/test-server.js
index 214321952..a32410dd7 100644
--- a/tests/helpers/test-server.js
+++ b/tests/helpers/test-server.js
@@ -36,8 +36,15 @@ export function freePort() {
* @param {number} [opts.timeoutMs] how long to wait for readiness
* @returns {Promise<{ base: string, port: number, close: () => void }>}
* `base` is the origin to fetch against; call `close()` in afterAll.
+ *
+ * The readiness budget is deliberately far above the ~1.5s the server needs on
+ * an idle machine: a full `vitest run` puts a worker on every core, so the boot
+ * that takes a second alone can take tens of seconds while 1400 other suites
+ * compete for the same CPU. A budget sized for the idle case turns that
+ * contention into a red suite that passes the moment it is run on its own.
*/
-export async function startTestServer({ env = {}, timeoutMs = 20_000 } = {}) {
+export async function startTestServer({ env = {}, timeoutMs = 60_000 } = {}) {
+ const startedAt = Date.now();
const port = await freePort();
const base = `http://127.0.0.1:${port}`;
const child = spawn(process.execPath, ['server/index.mjs'], {
@@ -61,7 +68,12 @@ export async function startTestServer({ env = {}, timeoutMs = 20_000 } = {}) {
const res = await fetch(`${base}/api/healthz`);
if (res.status > 0) break;
} catch { /* not up yet */ }
- if (Date.now() >= deadline) throw new Error(`server did not start in time (${base})`);
+ if (Date.now() >= deadline) {
+ throw new Error(
+ `server did not answer /api/healthz within ${Date.now() - startedAt}ms (${base}); `
+ + 'the process was still alive, so this is a slow boot, not a crash',
+ );
+ }
await new Promise((r) => setTimeout(r, 250));
}
diff --git a/tests/mcp-server-build.test.js b/tests/mcp-server-build.test.js
new file mode 100644
index 000000000..b47985838
--- /dev/null
+++ b/tests/mcp-server-build.test.js
@@ -0,0 +1,131 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+
+// Core-path coverage for the published @three-ws/mcp-server main export.
+//
+// mcp-server-annotations.test.js asserts on buildTools() (the descriptor list).
+// This file asserts on buildServer(), the export the `3d-agent-mcp` bin
+// actually boots, by connecting a real MCP Client over an in-memory transport
+// pair and driving the same tools/list, resources/list, and resources/read
+// round-trips a Claude Desktop or Cursor client makes. No stubs: it is the real
+// McpServer with every tool registered, minus only the stdio pipe.
+//
+// It also pins the README to the registered tool surface. Six tools
+// (forge_avatar, refine_model, restyle_material, vanity_premium,
+// agent_hire_discover, agent_hire) shipped registered but undocumented, which
+// is invisible to every other check in the repo, the catalog builder reads the
+// source, not the README.
+import { buildServer, buildTools } from '../mcp-server/src/index.js';
+import {
+ UI_RESOURCE_URI,
+ UI_MIME_TYPE,
+ UI_RESOURCE_META,
+} from '../mcp-server/src/commerce-ui.js';
+
+const PKG = JSON.parse(
+ readFileSync(fileURLToPath(new URL('../mcp-server/package.json', import.meta.url)), 'utf8'),
+);
+const README = readFileSync(
+ fileURLToPath(new URL('../mcp-server/README.md', import.meta.url)),
+ 'utf8',
+);
+
+// Pinned literally: the URI is a wire contract with hosts that cached it, so a
+// rename must fail here rather than silently follow the module constant.
+const RECEIPT_URI = 'ui://three-ws-commerce/hire-receipt.html';
+
+let client;
+let descriptors;
+let listed;
+
+beforeAll(async () => {
+ descriptors = await buildTools();
+ const server = await buildServer();
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ client = new Client({ name: 'mcp-server-build-test', version: '1.0.0' });
+ await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
+ listed = (await client.listTools()).tools;
+}, 60_000);
+
+afterAll(async () => {
+ await client?.close();
+});
+
+describe('buildServer(), the published stdio entry point', () => {
+ it('advertises the package version and the 3d-agent-mcp identity', () => {
+ expect(client.getServerVersion()).toEqual({
+ name: '3d-agent-mcp',
+ version: PKG.version,
+ });
+ });
+
+ it('declares both the tools and resources capabilities', () => {
+ const caps = client.getServerCapabilities();
+ expect(caps).toMatchObject({ tools: {}, resources: {} });
+ // No logging API is shipped, so the capability must stay undeclared.
+ expect(caps.logging).toBeUndefined();
+ });
+
+ it('ships instructions that orient a client with no prior context', () => {
+ const instructions = client.getInstructions();
+ expect(instructions).toBeTruthy();
+ expect(instructions).toContain('forge_free');
+ });
+
+ it('registers every built tool over the wire, with no extras', () => {
+ expect(listed.map((t) => t.name).sort()).toEqual(descriptors.map((t) => t.name).sort());
+ });
+
+ it('serves each tool with a title, description, and object input schema', () => {
+ for (const tool of listed) {
+ expect(tool.title, `${tool.name} title`).toBeTruthy();
+ expect(tool.description, `${tool.name} description`).toBeTruthy();
+ expect(tool.inputSchema?.type, `${tool.name} inputSchema`).toBe('object');
+ }
+ });
+
+ it('exposes the agent_hire provenance receipt as a readable UI resource', async () => {
+ expect(UI_RESOURCE_URI).toBe(RECEIPT_URI);
+ const { resources } = await client.listResources();
+ expect(resources.map((r) => r.uri)).toContain(RECEIPT_URI);
+
+ const { contents } = await client.readResource({ uri: RECEIPT_URI });
+ expect(contents).toHaveLength(1);
+ expect(contents[0].mimeType).toBe(UI_MIME_TYPE);
+ expect(contents[0]._meta).toEqual(UI_RESOURCE_META);
+ // The real built card, not a placeholder: doctype plus the inlined bundle.
+ expect(contents[0].text.startsWith('<!doctype html>')).toBe(true);
+ expect(contents[0].text).toContain('<script>');
+ });
+
+ it('links agent_hire to that resource through tool _meta', () => {
+ const hire = listed.find((t) => t.name === 'agent_hire');
+ expect(hire?._meta?.['openai/outputTemplate'] ?? hire?._meta?.ui?.resourceUri).toBe(
+ RECEIPT_URI,
+ );
+ });
+});
+
+describe('README documents the registered tool surface', () => {
+ it('gives every tool a table row', () => {
+ const documented = new Set(
+ [...README.matchAll(/^\|\s*`([a-z0-9_]+)`\s*\|/gm)].map((m) => m[1]),
+ );
+ const missing = descriptors.map((t) => t.name).filter((name) => !documented.has(name));
+ expect(missing).toEqual([]);
+ });
+
+ it('quotes a price for every documented tool row', () => {
+ const rows = [...README.matchAll(/^\|\s*`([a-z0-9_]+)`\s*\|([^|]*)\|/gm)];
+ const names = new Set(descriptors.map((t) => t.name));
+ const unpriced = rows
+ .filter(([, name]) => names.has(name))
+ .filter(([, , price]) => !/\$|free/i.test(price))
+ .map(([, name]) => name);
+ expect(unpriced).toEqual([]);
+ });
+});
diff --git a/tests/multiplayer-server-boot.test.js b/tests/multiplayer-server-boot.test.js
new file mode 100644
index 000000000..2ac056b3d
--- /dev/null
+++ b/tests/multiplayer-server-boot.test.js
@@ -0,0 +1,187 @@
+// The multiplayer package's main export (multiplayer/src/index.js) is the whole
+// product: it is what Cloud Run runs, what /play, /walk, /irl, /ar/studio,
+// /agora and /play/war all connect to. Every other suite in this repo imports a
+// leaf module out of multiplayer/src and tests it in isolation, so a change that
+// leaves the process unable to BOOT (a bad import, a room that throws at define
+// time, a broken Express mount) passes the whole test run and is only caught by
+// a deploy or a person opening the world.
+//
+// This suite boots the real entry point as a child process on a free port and
+// talks to it over real HTTP and a real WebSocket. No mocks, no fakes: the
+// server here is byte-for-byte the one the Dockerfile runs.
+//
+// The wire-level reconnect contract has its own deeper proof
+// (scripts/play-reconnect-proof.mjs, nine assertions about session eviction);
+// this suite covers the boot + public surface that proof takes for granted.
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { spawn } from 'node:child_process';
+import net from 'node:net';
+import crypto from 'node:crypto';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SECRET = 'multiplayer-boot-suite-secret';
+const COIN = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+let child;
+let port;
+let base;
+
+/** Ask the OS for a port nobody is using, so concurrent suites never collide. */
+function freePort() {
+ return new Promise((resolve, reject) => {
+ const srv = net.createServer();
+ srv.on('error', reject);
+ srv.listen(0, '127.0.0.1', () => {
+ const { port: p } = srv.address();
+ srv.close(() => resolve(p));
+ });
+ });
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Sign an /internal/notify webhook exactly the way the three.ws API does
+ * (api/_lib/presence-store.js → notifyMultiplayer). Keeping the signing here
+ * rather than importing the verifier proves the two halves agree over the wire.
+ */
+function signNotify(to, type, payload, ts) {
+ const payloadHash = crypto.createHash('sha256').update(JSON.stringify(payload ?? {})).digest('base64url');
+ return crypto
+ .createHmac('sha256', SECRET)
+ .update(`notify:${to}:${type}:${ts}:${payloadHash}`)
+ .digest('base64url');
+}
+
+beforeAll(async () => {
+ port = await freePort();
+ base = `http://127.0.0.1:${port}`;
+ child = spawn(process.execPath, ['multiplayer/src/index.js'], {
+ cwd: root,
+ env: {
+ ...process.env,
+ PORT: String(port),
+ HOST: '127.0.0.1',
+ NODE_ENV: 'development',
+ MULTIPLAYER_SHARED_SECRET: SECRET,
+ // Never let a developer's real Redis/Upstash creds leak a test room's
+ // state into shared storage: this suite runs memory-only by construction.
+ UPSTASH_REDIS_REST_URL: '',
+ UPSTASH_REDIS_REST_TOKEN: '',
+ REDIS_URI: '',
+ REDIS_URL: '',
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let out = '';
+ child.stdout.on('data', (b) => { out += b; });
+ child.stderr.on('data', (b) => { out += b; });
+ for (let i = 0; i < 120; i++) {
+ if (/listening on ws:/.test(out)) return;
+ if (child.exitCode !== null) throw new Error(`server exited early: ${out.slice(-800)}`);
+ await sleep(250);
+ }
+ throw new Error(`server never came up: ${out.slice(-800)}`);
+});
+
+afterAll(async () => {
+ if (!child || child.exitCode !== null) return;
+ child.kill('SIGKILL');
+ await new Promise((r) => child.once('exit', r));
+});
+
+describe('multiplayer entry point', () => {
+ it('answers both liveness probes the container health check uses', async () => {
+ for (const route of ['/health', '/healthz']) {
+ const res = await fetch(`${base}${route}`);
+ expect(res.status, route).toBe(200);
+ expect(await res.json()).toEqual({ ok: true, name: 'three.ws-multiplayer' });
+ }
+ });
+
+ it('publishes a live population aggregate that carries no identity', async () => {
+ const res = await fetch(`${base}/population`);
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body).toEqual({ ok: true, coin: null, rooms: 0, players: 0 });
+ // The /event landing page reads this through api/play/population.js, so it
+ // must stay a count: no session ids, names, wallets or positions.
+ expect(Object.keys(body).sort()).toEqual(['coin', 'ok', 'players', 'rooms']);
+ });
+
+ it('serves a real walk_world join and counts the player in /population', async () => {
+ const { Client } = await import('colyseus.js');
+ const client = new Client(`ws://127.0.0.1:${port}`);
+ const room = await client.joinOrCreate('walk_world', {
+ coin: COIN, tier: '', coinName: 'three.ws', coinSymbol: 'three',
+ name: 'BootSuite', pid: 'guest-boot-suite',
+ });
+ try {
+ await new Promise((resolve) => { room.onStateChange.once(() => resolve()); });
+ const me = room.state.players.get(room.sessionId);
+ expect(me, 'the joining client is in the authoritative roster').toBeTruthy();
+ expect(me.name).toBe('BootSuite');
+
+ const res = await fetch(`${base}/population?coin=${COIN}`);
+ const body = await res.json();
+ expect(body.ok).toBe(true);
+ expect(body.coin).toBe(COIN);
+ expect(body.rooms).toBe(1);
+ expect(body.players).toBe(1);
+
+ // A different coin is a different world, so it must not see this player.
+ const other = await (await fetch(`${base}/population?coin=NotThisCoin111`)).json();
+ expect(other).toMatchObject({ ok: true, rooms: 0, players: 0 });
+ } finally {
+ await room.leave();
+ }
+ });
+
+ it('refuses an unsigned or forged internal webhook', async () => {
+ const post = (body, headers = {}) => fetch(`${base}/internal/notify`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...headers },
+ body: JSON.stringify(body),
+ });
+
+ expect((await post({ type: '', to: '' })).status).toBe(400);
+ expect((await post({ type: 'dm', to: 'acct-1', payload: {} })).status).toBe(401);
+
+ const ts = Math.floor(Date.now() / 1000);
+ const payload = { text: 'hello' };
+ // A signature bound to a DIFFERENT body must not carry this one through.
+ const wrong = signNotify('acct-1', 'dm', { text: 'other' }, ts);
+ expect((await post({ type: 'dm', to: 'acct-1', payload }, {
+ 'x-mp-signature': wrong, 'x-mp-timestamp': String(ts),
+ })).status).toBe(401);
+ });
+
+ it('accepts a correctly signed internal webhook and reports offline delivery honestly', async () => {
+ const ts = Math.floor(Date.now() / 1000);
+ const payload = { text: 'hello' };
+ const res = await fetch(`${base}/internal/notify`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-mp-signature': signNotify('acct-offline', 'dm', payload, ts),
+ 'x-mp-timestamp': String(ts),
+ },
+ body: JSON.stringify({ type: 'dm', to: 'acct-offline', payload }),
+ });
+ expect(res.status).toBe(200);
+ // Nobody with that account id has a socket here, so the API is told to fall
+ // back to next-login delivery rather than being told a lie.
+ expect(await res.json()).toEqual({ delivered: false });
+ });
+
+ it('refuses an unsigned operator announcement', async () => {
+ const res = await fetch(`${base}/internal/announce`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text: 'the event starts now' }),
+ });
+ expect(res.status).toBe(401);
+ });
+});
diff --git a/tests/pump-channel-feed.test.js b/tests/pump-channel-feed.test.js
index 4a6d250b3..dc5026d99 100644
--- a/tests/pump-channel-feed.test.js
+++ b/tests/pump-channel-feed.test.js
@@ -23,7 +23,11 @@ vi.mock('../api/_lib/env.js', () => ({
env: { APP_ORIGIN: 'http://test', ISSUER: 'http://test', MCP_RESOURCE: 'http://test' },
}));
-const { default: handler } = await import('../api/pump/channel-feed.js');
+// The endpoint lives in the consolidated pump dispatcher, reached as
+// /api/pump/channel-feed -> /api/pump/[action]?action=channel-feed. Exercising
+// the dispatcher (rather than a sibling file the route table never reaches)
+// is what makes these assertions describe production.
+const { default: handler } = await import('../api/pump/[action].js');
// ── helpers ────────────────────────────────────────────────────────────────────
@@ -44,6 +48,8 @@ function mockReq(search = '') {
method: 'GET',
headers: { host: 'localhost' },
url: `/api/pump/channel-feed${search}`,
+ // Populated by the filesystem router in production; the dispatcher switches on it.
+ query: { action: 'channel-feed' },
};
}
diff --git a/tests/pump-telegram-delivery.test.js b/tests/pump-telegram-delivery.test.js
index 1aaa51a25..d48fbbc40 100644
--- a/tests/pump-telegram-delivery.test.js
+++ b/tests/pump-telegram-delivery.test.js
@@ -15,6 +15,16 @@ vi.mock('../api/_lib/auth.js', () => ({
getSessionUser: getSessionUserMock,
authenticateBearer: async () => null,
extractBearer: () => null,
+ // The dispatcher gates cookie-authed mutations on a same-site Origin before
+ // it ever reaches the action; a request without this never gets that far.
+ isSameSiteOrigin: () => true,
+}));
+
+// The bot-delivery path is rate-limited per IP. Any bucket resolves to allowed
+// here; the ceiling itself is not what these tests are about.
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: new Proxy({}, { get: () => vi.fn(async () => ({ success: true })) }),
+ clientIp: vi.fn(() => '127.0.0.1'),
}));
// ── helpers ────────────────────────────────────────────────────────────────
@@ -24,7 +34,13 @@ function makeReq(body) {
: Readable.from([]);
stream.method = 'POST';
stream.url = '/api/pump/deliver-telegram';
- stream.headers = { host: 'localhost', 'content-type': 'application/json' };
+ stream.headers = {
+ host: 'localhost',
+ origin: 'https://three.ws',
+ 'content-type': 'application/json',
+ };
+ // Populated by the filesystem router in production; the dispatcher switches on it.
+ stream.query = { action: 'deliver-telegram' };
return stream;
}
@@ -45,7 +61,10 @@ function makeRes() {
}
async function callEndpoint(body) {
- const { default: handler } = await import('../api/pump/deliver-telegram.js');
+ // /api/pump/deliver-telegram -> /api/pump/[action]?action=deliver-telegram.
+ // The dispatcher is the only thing the route table reaches, so it is the
+ // only thing worth asserting against.
+ const { default: handler } = await import('../api/pump/[action].js');
const res = makeRes();
await handler(makeReq(body), res);
return { res, json: res.body ? JSON.parse(res.body) : null };
@@ -91,6 +110,35 @@ describe('sendTelegramSignal', () => {
expect(result).toEqual({ ok: true, messageId: 42 });
});
+ it('escapes Markdown control characters in attacker-supplied signal text', async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ result: { message_id: 7 } }),
+ });
+ const { sendTelegramSignal } = await import('../src/pump/telegram-delivery.js');
+ await sendTelegramSignal({
+ botToken: 'bot123',
+ chatId: '1',
+ signal: {
+ kind: 'mint',
+ mint: 'Mint_1',
+ // Token metadata is attacker-controlled. Unescaped, this renders as a
+ // clickable link posted under the platform bot's verified identity.
+ summary: '[claim your airdrop](https://evil.example) *urgent*',
+ refs: ['`ref_one`'],
+ ts: 1700000000000,
+ },
+ });
+
+ const sent = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(sent.text).toContain('\\[claim your airdrop\\]');
+ expect(sent.text).toContain('\\*urgent\\*');
+ expect(sent.text).toContain('Mint\\_1');
+ expect(sent.text).toContain('\\`ref\\_one\\`');
+ // The bot's own formatting survives: the kind label is still bold.
+ expect(sent.text.startsWith('*New Mint*')).toBe(true);
+ });
+
it('throws on a non-2xx Telegram response', async () => {
fetchMock.mockResolvedValueOnce({
ok: false,
diff --git a/tests/seo-head.test.js b/tests/seo-head.test.js
index d3caae89b..75df94531 100644
--- a/tests/seo-head.test.js
+++ b/tests/seo-head.test.js
@@ -8,7 +8,7 @@ import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { rewriteHead, hasSeoRoute } from '../server/seo-head.mjs';
+import { rewriteHead, hasSeoRoute, canonicalOf, canonicalUrlFor } from '../server/seo-head.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const docsShell = readFileSync(path.join(ROOT, 'docs/index.html'), 'utf8');
@@ -87,3 +87,30 @@ describe('hasSeoRoute', () => {
expect(hasSeoRoute('/definitely-not-a-page-xyz')).toBe(false);
});
});
+
+// scripts/check-pages.mjs asserts a swept page served its own canonical, using
+// these two exports rather than restating the rule. A drift here would silently
+// turn the production sweep back into the status-only check that let
+// /docs/tokens-xyz pass while it served the generic docs shell.
+describe('the canonical contract check-pages sweeps against', () => {
+ it('names the page, on a fixed origin, trailing slash or not', () => {
+ expect(canonicalUrlFor('/docs/swarms')).toBe('https://three.ws/docs/swarms');
+ expect(canonicalUrlFor('/docs/swarms/')).toBe('https://three.ws/docs/swarms');
+ expect(canonicalUrlFor('/')).toBe('https://three.ws/');
+ });
+
+ it('reads back exactly what rewriteHead wrote', () => {
+ const head = headOf(rewriteHead('/docs/swarms', docsShell));
+ expect(canonicalOf(head)).toBe(canonicalUrlFor('/docs/swarms'));
+ });
+
+ it('reports the shell canonical for a route the shell does not own', () => {
+ // What a declared-but-undeployed page looks like in the sweep: the shell
+ // answers 200 carrying its own canonical, which is not the one requested.
+ expect(canonicalOf(headOf(docsShell))).not.toBe(canonicalUrlFor('/docs/swarms'));
+ });
+
+ it('returns null for a document with no canonical at all', () => {
+ expect(canonicalOf('<head><title>x</title></head>')).toBeNull();
+ });
+});
diff --git a/tests/server-404-routes.test.js b/tests/server-404-routes.test.js
new file mode 100644
index 000000000..ea6500973
--- /dev/null
+++ b/tests/server-404-routes.test.js
@@ -0,0 +1,136 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { startTestServer } from './helpers/test-server.js';
+import { isMissingShellPage } from '../server/shell-pages.mjs';
+
+// An unknown URL must end in the designed 404 page with a real 404 status.
+//
+// Two classes of soft 404 have shipped here. /docs/* and /tutorials/* rewrite
+// EVERY slug to a single HTML shell, so /docs/anything answered 200 with the
+// shell, which then rendered one gray "Page not found." line: indexed by
+// crawlers as a live page, and a dead end for the reader. The inverse also
+// held: nested doc pages that exist (docs/<topic>/chapters/<n>.md) were not
+// matched by the single-segment docs rule at all, so a real page 404'd.
+//
+// Both are decided by server/shell-pages.mjs, which resolves the markdown
+// article a shell would fetch before the shell is served.
+
+let BASE;
+let server;
+
+beforeAll(async () => {
+ server = await startTestServer();
+ BASE = server.base;
+}, 30000);
+
+afterAll(() => {
+ server?.close();
+});
+
+const get = (path) => fetch(`${BASE}${path}`, { redirect: 'manual' });
+
+describe('unknown routes land on the designed 404', () => {
+ it('an unknown page returns 404 with the designed page, not a bare body', async () => {
+ const res = await get('/definitely-not-a-real-page-xyz');
+ expect(res.status).toBe(404);
+ expect(res.headers.get('content-type')).toMatch(/text\/html/);
+ const html = await res.text();
+ // The designed page: its own title, and the ways back into the product.
+ expect(html).toContain('three.ws — 404');
+ expect(html).toContain('href="/"');
+ expect(html).toContain('href="/sitemap"');
+ });
+
+ it('the trailing-slash variant redirects once, to the same 404', async () => {
+ const res = await get('/definitely-not-a-real-page-xyz/');
+ expect(res.status).toBe(301);
+ expect(res.headers.get('location')).toBe('/definitely-not-a-real-page-xyz');
+ const followed = await fetch(`${BASE}/definitely-not-a-real-page-xyz/`);
+ expect(followed.status).toBe(404);
+ });
+
+ it('an unknown /api/ path answers JSON, never the HTML shell', async () => {
+ const res = await get('/api/definitely-not-a-real-endpoint-xyz');
+ expect(res.status).toBe(404);
+ expect(res.headers.get('content-type')).toMatch(/application\/json/);
+ const body = await res.json();
+ expect(body.error).toBe('not_found');
+ });
+});
+
+describe('shared-shell surfaces do not soft-404', () => {
+ it('an unknown /docs/ slug returns 404, not the docs shell at 200', async () => {
+ const res = await get('/docs/definitely-not-a-real-doc-xyz');
+ expect(res.status).toBe(404);
+ const html = await res.text();
+ expect(html).toContain('three.ws — 404');
+ });
+
+ it('an unknown nested /docs/ path returns 404', async () => {
+ const res = await get('/docs/definitely-not-a-real-doc-xyz/chapters/01');
+ expect(res.status).toBe(404);
+ });
+
+ it('an unknown /tutorials/ slug returns 404, not the tutorial shell at 200', async () => {
+ const res = await get('/tutorials/definitely-not-a-real-tutorial-xyz');
+ expect(res.status).toBe(404);
+ const html = await res.text();
+ expect(html).toContain('three.ws — 404');
+ });
+
+ it('a real doc still serves the docs shell', async () => {
+ const res = await get('/docs/start-here');
+ expect(res.status).toBe(200);
+ const html = await res.text();
+ expect(html).toContain('docs-sidebar');
+ });
+
+ it('a real nested doc chapter serves the docs shell instead of 404ing', async () => {
+ const res = await get('/docs/agent-abilities/chapters/01-the-body');
+ expect(res.status).toBe(200);
+ const html = await res.text();
+ expect(html).toContain('docs-sidebar');
+ });
+
+ it('the docs index itself is untouched by the article check', async () => {
+ const res = await get('/docs');
+ expect(res.status).toBe(200);
+ });
+
+ it('a docs path that names a directory serves that directory index', async () => {
+ const res = await get('/docs/nvidia-inception');
+ expect(res.status).toBe(200);
+ expect(res.headers.get('content-type')).toMatch(/text\/html/);
+ });
+
+ it('a traversal slug under the shell never escapes dist/docs', async () => {
+ const res = await get('/docs/..%2f..%2fvite.config');
+ expect(res.status).toBe(404);
+ });
+});
+
+// The tutorial shell (dist/tutorial.html) is only present in a full build, so
+// its serve path is asserted at the resolver instead of over HTTP: these are
+// the decisions the server acts on, and they hold against the repo's own
+// docs/tutorials sources either way.
+describe('article resolution behind the shells', () => {
+ const DIST = path.resolve(fileURLToPath(new URL('..', import.meta.url)), 'dist');
+
+ it('a real tutorial resolves to its article', () => {
+ expect(isMissingShellPage(DIST, '/tutorial.html', '/tutorials/text-to-3d')).toBe(false);
+ });
+
+ it('an unknown tutorial has no article', () => {
+ expect(isMissingShellPage(DIST, '/tutorial.html', '/tutorials/not-a-tutorial-xyz')).toBe(true);
+ });
+
+ it('routes that are not shells are never gated', () => {
+ expect(isMissingShellPage(DIST, '/docs-world.html', '/docs/world')).toBe(false);
+ expect(isMissingShellPage(DIST, '/index.html', '/anything')).toBe(false);
+ });
+
+ it('the shell index itself always resolves', () => {
+ expect(isMissingShellPage(DIST, '/docs/index.html', '/docs/')).toBe(false);
+ });
+});
diff --git a/tests/server-api-traversal.test.js b/tests/server-api-traversal.test.js
index eac6bf020..52b182ecc 100644
--- a/tests/server-api-traversal.test.js
+++ b/tests/server-api-traversal.test.js
@@ -15,10 +15,13 @@ import { startTestServer } from './helpers/test-server.js';
let BASE;
let server;
+// 90s, not 30s: startTestServer waits up to 60s for readiness because a boot
+// that takes ~1.5s idle takes tens of seconds under full-suite load. A hook
+// budget below that budget just fails first, with a less useful message.
beforeAll(async () => {
server = await startTestServer();
BASE = server.base;
-}, 30000);
+}, 90000);
afterAll(() => {
server?.close();
diff --git a/tests/server-rewrite-query.test.js b/tests/server-rewrite-query.test.js
index 556e1d596..a065a6820 100644
--- a/tests/server-rewrite-query.test.js
+++ b/tests/server-rewrite-query.test.js
@@ -19,10 +19,14 @@ const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
let BASE;
let server;
+// 90s, not 30s: startTestServer waits up to 60s for readiness because a boot
+// that takes ~1.5s idle takes tens of seconds under full-suite load. This suite
+// is the one that proved it, timing out at exactly the old 20s readiness
+// deadline in a full run and passing in 7s on its own.
beforeAll(async () => {
server = await startTestServer();
BASE = server.base;
-}, 30000);
+}, 90000);
afterAll(() => {
server?.close();