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(api): harden the sitemap, wallet, swarms and rider handlers and resolve the changelog conflicts
nirholasb53d42038401
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 47958fa49..a8dc0f609 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -73,6 +73,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The concierge widget closes on Escape from anywhere on the page, and its SDK now installs on a server**: Three fixes to the embeddable concierge. Escape now closes the chat panel wherever the visitor's cursor last landed: it only worked while focus was still inside the widget, so clicking the page behind the panel left the documented shortcut dead. Sites built with Next, Nuxt, SvelteKit, or Astro can now import the package the normal way, because importing it no longer expects a browser and no longer crashes the server render. And the 3D avatar stage stopped printing a deprecation warning into every host site's console. The package also ships full TypeScript types for shopping mode (catalog, products, policies, and the store events) and declares its own build and test tools, so a standalone install builds and tests without the monorepo. (`/concierge`) `[fix, sdk]`- **The contracts README now describes the contracts that are actually there**: Anyone opening the on-chain contracts directory was reading a page written when it held three ERC-8004 registries. It now holds ten contracts and programs, including the two that custody real USDC on BNB Smart Chain, Base and Arbitrum, and the two Solana programs. The README listed none of them, claimed 25 tests where there are 242, and printed the canonical ERC-8004 identity addresses with mainnet and testnet swapped, so a developer copying them would have pointed at the wrong chain's registry. It also told you to edit a shared entry that seven testnets read from, which would have silently repointed all of them. All of that is corrected, the Solana build and test commands are documented, and the sample registration snippet now shows the values the function really returns. `[docs]`- **The Duplicate button on your widgets works again**: Duplicating a widget from the dashboard failed every single time. The clone request never gave the new widget an identifier, and because the database requires one, the copy was rejected before it was written and the page showed only a generic server error with a support reference. A second, correct copy of the same clone logic was already in the codebase and the route simply was not using it; the route now runs that one, so duplicating gives you a real new widget with its own id, its own name ending in (copy), and the original's type, look, avatar and visibility carried over. The duplicate request also now carries the same cross-site request protection every other widget change already had, and it accepts an API key with write access, so you can clone a widget from a script as well as from the dashboard. Two smaller corrections travelled with it. When no chat provider is configured and the platform answers a visitor with its own placeholder line, that message is no longer filed in your transcript as though a model had written it. And chatting with one of the showcase widgets in the public gallery no longer tries to file a transcript against a widget that does not exist, which failed on every message. The developer reference now documents duplicate, stats, chat, transcripts and the knowledge base, all of which were live but undocumented. (`/dashboard/widgets`) `[fix, docs]`+- **The Duplicate button on your widgets works again**: Duplicating a widget from the dashboard failed every single time. The clone request never gave the new widget an identifier, and because the database requires one, the copy was rejected before it was written and the page showed only a generic server error with a support reference. There was a second, correct copy of the same clone logic already in the codebase that the route was not using; the route now runs that one, so duplicating gives you a real new widget with its own id, its own name ending in (copy), and the original's type, look, avatar and visibility carried over. The duplicate request also now carries the same cross-site request protection every other widget change already had, and it accepts an API key with write access, so you can clone a widget from a script as well as from the dashboard. Transcripts got a smaller correction alongside it: when no chat provider is configured and the platform answers with its own placeholder line, that message is no longer filed in your transcript as if a model had written it. (`/dashboard/widgets`) `[fix]`- **The embed and sharing tutorials now describe the surfaces that actually exist**: An audit of eight beginner tutorials found several describing features the platform does not have. The avatar-swap tutorial sent readers to Widget Studio for a body swap it cannot do, through a gallery with filters, preview buttons, and a 'Bust cache' save dialog that were never built; it now documents the real one-click swap in the agent editor's Outfit panel, and explains why nothing needs a cache purge. The sharing tutorial claimed rich social previews came from the plain agent URL, which actually serves a generic card, and described a headless renderer, a 24-hour image cache, a 'Refresh preview image' button, and a private-profile toggle that do not exist; it now points at the real share URL that carries the agent's name, description, and card, and explains what genuinely controls discoverability. The AR tutorial's iframe example used an address that returns 404 for an avatar id. The embed quickstart showed an agent ID in the wrong format, overstated the bundle size, and had the effect of the shadow DOM backwards. The docs-world tutorial gained the search palette it never mentioned, and the greeting tutorial now warns that the editor's Greeting field is not what makes an embed talk. Five page descriptions were corrected too, including one promising knobs the tutorial never covered. (`/tutorials/swap-avatar-in-studio`) `[docs, fix]`- **The embed tutorials now name the attribute that actually hides the built-in chat**: Several tutorials told you to set avatar-chat="off" to hide an agent's built-in chat input. It does not do that: it moves the avatar out of the chat column and lays the chat out as a plain bottom bar, leaving the input on screen. The multi-agent walkthrough leaned on it to keep its behind-the-scenes stage-director messages hidden, so anyone following it verbatim saw those messages leak into the visible chat. The affected tutorials now use chat="off", the real bare-avatar switch, and note that the brain still boots behind it so say(), ask(), and the event stream keep working. The same accuracy pass corrected the walking-avatar leaderboard example, which read fields the API never returns and so always rendered an empty top-walkers list, and the JavaScript API event table, which named the wrong key for the skill a tool-call event reports. (`/tutorials/web-component-end-to-end`) `[fix, docs]`- **The embodied AgenC demo hands you a live task, and reacts to the state a claimed task is actually in**: The /agenc/embodied page binds a 3D agent to a real AgenC task on Solana, and until now it opened on an empty input box: it needed a task account address and offered no way anywhere on the page to find one. It now lists real tasks three.ws itself posted, claimed, and settled on-chain, newest first, so the demo works the moment it loads; a new public read, /api/agenc/recent-tasks, serves that list. Two things it showed were also wrong. The scene coloured itself for a state named Claimed, which the chain has never used: a claimed task is In Progress on-chain, so the halo, the badge, and the per-state animation switch all sat inert through the one transition the demo exists to show. And the page named a program address that no read has touched since the protocol's interface moved; it now shows the program each live read actually ran against. Pasting an address that holds something other than a task used to report a server error, as though the platform were broken, rather than saying no such task exists there; that is now a plain not-found, with the page telling you to check the address or switch cluster. The panel has designed loading, empty, and error states throughout, the form fields have real labels, the layout no longer scrolls sideways on a phone, and a task that cannot be read is retried with a backoff instead of being re-requested every four seconds forever. (`/agenc/embodied`) `[fix, improvement, feature]`diff --git a/api/_lib/farcaster-client.js b/api/_lib/farcaster-client.jsindex b90934208..c4aa860e3 100644--- a/api/_lib/farcaster-client.js+++ b/api/_lib/farcaster-client.js@@ -66,7 +66,18 @@ async function hubGet(path) {throw new FarcasterError(`Farcaster hub unreachable: ${err?.message || err}`);}if (resp.status === 404) throw new FarcasterError('Farcaster user not found', { status: 404, code: 'farcaster_user_not_found' });- if (!resp.ok) throw new FarcasterError(`Farcaster hub ${resp.status}`);+ if (!resp.ok) {+ // A hub answers "no such fname" with 400 + a NotFound detail, not 404.+ // Without this the caller cannot tell a typo'd handle from an outage.+ const body = await resp.text().catch(() => '');+ if (resp.status === 400 && /not\s*found/i.test(body)) {+ throw new FarcasterError('Farcaster user not found', {+ status: 404,+ code: 'farcaster_user_not_found',+ });+ }+ throw new FarcasterError(`Farcaster hub ${resp.status}`);+ }return resp.json();}diff --git a/api/_lib/migrations/20260816090000_rider_passes_batch_tx.sql b/api/_lib/migrations/20260816090000_rider_passes_batch_tx.sqlnew file mode 100644index 000000000..8ee379b4d--- /dev/null+++ b/api/_lib/migrations/20260816090000_rider_passes_batch_tx.sql@@ -0,0 +1,19 @@+-- rider_passes: drop the standalone UNIQUE on tx_signature.+--+-- One Solana transaction can carry $THREE into the rider vault from more than+-- one wallet (a batch or aggregator transfer). Both senders earn a pass, and+-- both rows legitimately share that transaction's signature, so the unique index+-- made the second insert fail. That surfaced as a 500 from /api/rider/webhook,+-- which Helius retries: an endless redelivery loop that rewrote the first+-- payer's row on every attempt and never granted the second payer anything.+--+-- Replay idempotency does not depend on this index. The wallet_address primary+-- key already collapses a redelivered payload into the same upsert. The plain+-- index that replaces it keeps signature lookups (support, reconciliation) fast.++begin;++alter table rider_passes drop constraint if exists rider_passes_tx_signature_key;+create index if not exists rider_passes_tx_signature_idx on rider_passes (tx_signature);++commit;diff --git a/api/_lib/rss-feed.js b/api/_lib/rss-feed.jsindex 3bdca715b..9d7d12c39 100644--- a/api/_lib/rss-feed.js+++ b/api/_lib/rss-feed.js@@ -280,11 +280,11 @@ function renderDescription(item) {export function buildRssXml({ items, selfUrl, source = 'curated' }) {const account = ACCOUNTS[source];const channelTitle = account- ? `three.ws — ${account.display} updates`- : 'three.ws — News & Announcements';+ ? `three.ws: ${account.display} updates`+ : 'three.ws News & Announcements';const channelDescription = account? `Latest announcements from ${account.handle}, the team behind three.ws.`- : 'Product launches, integrations, and announcements from three.ws — 3D AI agent avatars on-chain.';+ : 'Product launches, integrations, and announcements from three.ws, 3D AI agent avatars on-chain.';const lastBuildDate = items[0]?.timestamp || new Date();const itemsXml = items.map((item) => renderItemXml(item)).join('\n');return `<?xml version="1.0" encoding="UTF-8"?>diff --git a/api/_lib/swarms.js b/api/_lib/swarms.jsindex 67ded0d7a..cc2764a16 100644--- a/api/_lib/swarms.js+++ b/api/_lib/swarms.js@@ -94,6 +94,34 @@ export class SwarmError extends Error {}}+/**+ * Parse a contribution amount from a request body into lamports. Accepts either+ * `lamports` (an integer count) or `sol` (a decimal), with `lamports` winning+ * when both are present.+ *+ * Every rejection is a 400 SwarmError, which the handler already renders as a+ * clean JSON error. That is the whole point: coercing straight to BigInt() the+ * way this used to means a caller typo (`lamports: "abc"`) or an overflowing+ * amount (`sol: 1e999`) throws a raw RangeError, which escapes as a 500+ * internal_error complete with a Sentry capture and an ops alert. Bad input from+ * a client is not a server fault and must never page anyone.+ *+ * @param {{ lamports?: unknown, sol?: unknown }} [body]+ * @returns {bigint}+ */+export function parseContributionLamports(body = {}) {+ const field = body?.lamports != null ? 'lamports' : body?.sol != null ? 'sol' : null;+ if (!field) throw new SwarmError(400, 'bad_amount', 'sol or lamports required');+ const raw = Number(body[field]);+ if (!Number.isFinite(raw)) throw new SwarmError(400, 'bad_amount', `${field} must be a number`);+ const value = Math.round(field === 'lamports' ? raw : raw * LAMPORTS_PER_SOL);+ // Beyond 2^53 a double no longer represents every integer, so the lamport+ // count a caller sent is not the one we would charge them.+ if (!Number.isSafeInteger(value)) throw new SwarmError(400, 'bad_amount', `${field} is out of range`);+ if (value <= 0) throw new SwarmError(400, 'bad_amount', 'sol or lamports required');+ return BigInt(value);+}+// ── on-chain treasury balance ─────────────────────────────────────────────────/** Live treasury SOL balance in lamports (bigint). The single source of truth. */diff --git a/api/gpt-forge.js b/api/gpt-forge.jsindex fffe56990..d9c8d225c 100644--- a/api/gpt-forge.js+++ b/api/gpt-forge.js@@ -1242,7 +1242,7 @@ async function startJob(req, res) {price_usd: priceUsd,balance_usd: acct.balanceUsd,top_up_url: '/credits',- message: `Generating a High model costs $${priceUsd.toFixed(2)} in credits — your balance is $${acct.balanceUsd.toFixed(2)}. Top up to continue.`,+ message: `Generating a High model costs $${priceUsd.toFixed(2)} in credits, your balance is $${acct.balanceUsd.toFixed(2)}. Top up to continue.`,});}creditsCharge = { user: creditUser, action: 'forge.high', ref: refId || randomUUID() };@@ -1296,7 +1296,7 @@ async function startJob(req, res) {return rateLimited(res,globalRl,- 'Paid 3D generation is at capacity right now — switch to a free engine (NVIDIA or Hugging Face), or try again shortly.',+ 'Paid 3D generation is at capacity right now: switch to a free engine (NVIDIA or Hugging Face), or try again shortly.',);}// Per-identity daily ceiling: closes the rotating-IP abuse path the per-IP@@ -1385,7 +1385,7 @@ async function startJob(req, res) {return json(res, 400, {error: 'invalid_prompt',message:- 'Describe one subject in 3–1000 characters, or pass image_url / image_urls for image-to-3D.',+ 'Describe one subject in 3-1000 characters, or pass image_url / image_urls for image-to-3D.',});}const aspect = VALID_ASPECT.has(body?.aspect_ratio) ? body.aspect_ratio : '1:1';@@ -1410,7 +1410,7 @@ async function startJob(req, res) {if (prompt.length < 3) {return json(res, 400, {error: 'invalid_prompt',- message: 'Say what the sketch depicts (3–1000 characters) — the sketch model is prompt-conditioned.',+ message: 'Say what the sketch depicts (3-1000 characters), the sketch model is prompt-conditioned.',});}}@@ -1423,7 +1423,7 @@ async function startJob(req, res) {error: 'backend_text_only',backend: backendId,message:- `${BACKENDS[backendId].label} generates from text prompts only — NVIDIA's hosted preview doesn't accept uploaded photos. ` ++ `${BACKENDS[backendId].label} generates from text prompts only, NVIDIA's hosted preview doesn't accept uploaded photos. ` +'Drop the backend field to use the default photo engine, or pick TRELLIS, Meshy, or Tripo.',});}@@ -1619,7 +1619,7 @@ async function startJob(req, res) {return json(res, 422, {error: 'backend_image_only',backend: backendId,- message: `${BACKENDS[backendId].label} reconstructs from a reference image — attach one, or drop the backend to use a text→3D engine.`,+ message: `${BACKENDS[backendId].label} reconstructs from a reference image, attach one, or drop the backend to use a text→3D engine.`,});}@@ -2431,7 +2431,7 @@ async function startJob(req, res) {error: 'rate_limited',queued,message: queued- ? `Your generation is queued behind a few others — retry in ~${retryAfter}s to pick it up.`+ ? `Your generation is queued behind a few others: retry in ~${retryAfter}s to pick it up.`: 'The 3D generator is busy right now. Try again in a few seconds.',retry_after: retryAfter,});@@ -2442,7 +2442,7 @@ async function startJob(req, res) {// with an honest, generic unavailable state instead of leaking it. (BYOK lanes// kept their actionable account message via the insufficient_credits branch.)if (!BACKENDS[backendId]?.byok && isPaidCreditFailure(err)) {- const creditDetail = err?.providerDetail ? ` — vendor: ${err.providerDetail}` : '';+ const creditDetail = err?.providerDetail ? `: vendor: ${err.providerDetail}` : '';console.warn(`[forge] paid reconstruct lane out of credit and no free lane available: ${err?.message || err}${creditDetail}`,);@@ -2984,7 +2984,7 @@ async function pollJob(req, res, jobId) {return json(res, 200, {job_id: jobId,status: 'failed',- error: sanitizeJobError(result.error) || '3D generation hit a snag — please try again.',+ error: sanitizeJobError(result.error) || '3D generation hit a snag, please try again.',...metaFields,...(suggestions.length ? { retryable: true, retry_backends: suggestions } : {}),});diff --git a/api/healthz.js b/api/healthz.jsindex b9b7ca862..3af1345bf 100644--- a/api/healthz.js+++ b/api/healthz.js@@ -175,7 +175,7 @@ async function probeX402() {result.warnings = [];if (hasSolanaPayTo && !hasSolanaFeePayer) {result.warnings.push(- 'solana_fee_payer_missing: X402_PAY_TO_SOLANA is set but X402_FEE_PAYER_SOLANA is not — ' ++ 'solana_fee_payer_missing: X402_PAY_TO_SOLANA is set but X402_FEE_PAYER_SOLANA is not, ' +'Solana accepts are dropped, breaking Solana-only paid endpoints (club-cover, dance-tip).',);}@@ -202,7 +202,7 @@ async function probeX402() {result.sponsor_cosign = mismatch ? 'mismatch' : 'missing';result.warnings.push(`sponsor_cosign_${result.sponsor_cosign}: the Solana fee-payer pubkey is advertised but its ` +- 'co-signing secret cannot be loaded — sponsor-mode settlements 502 (club-cover, dance-tip). ' ++ 'co-signing secret cannot be loaded, so sponsor-mode settlements 502 (club-cover, dance-tip). ' +'Set/repair X402_FEE_PAYER_SECRET_BASE58 in the deploy environment.',);}diff --git a/api/img.js b/api/img.jsindex 0d19a8569..488f3726b 100644--- a/api/img.js+++ b/api/img.js@@ -35,7 +35,7 @@ import { limits, clientIp } from './_lib/rate-limit.js';import { fetchModel } from './_lib/fetch-model.js';import { safeFetchJson } from './_lib/ssrf.js';-const MAX_BYTES = 8 * 1024 * 1024; // 8 MB — generous for token art, bounded for abuse+const MAX_BYTES = 8 * 1024 * 1024; // 8 MB: generous for token art, bounded for abuse// Per-gateway attempt cap. Each candidate fetch (DNS + connect + body) is bounded// by this via the SSRF fetcher's own AbortController. Because the candidates are// raced CONCURRENTLY (below), the whole resolution finishes in roughly one@@ -263,7 +263,7 @@ export default wrap(async function handler(req, res) {res,400,'invalid_url',- 'data: URIs cannot be proxied — pass an http(s) or ipfs URL',+ 'data: URIs cannot be proxied. Pass an http(s) or ipfs URL',);}diff --git a/api/rider/webhook.js b/api/rider/webhook.jsindex 9fcc547d3..ba56b5b69 100644--- a/api/rider/webhook.js+++ b/api/rider/webhook.js@@ -1,53 +1,54 @@-import { timingSafeEqual } from 'node:crypto';+// POST /api/rider/webhook+//+// Helius enhanced-transaction webhook for the rider vault. Every $THREE transfer+// of at least REQUIRED_AMOUNT into RIDER_VAULT_ADDRESS grants the sending wallet+// a rider pass, which /api/rider/check reads back out of rider_passes.+//+// Auth: Helius attaches a fixed `Authorization` header configured on the webhook.+// It is compared in constant time against RIDER_HELIUS_WEBHOOK_SECRET, and the+// endpoint FAILS CLOSED when that secret is unset: rows written here grant paid+// access, so it must never accept an anonymous write. (Previous form:+// `if (secret && ...)`, which silently accepted anything.)+import { sql } from '../_lib/db.js';import { json, method, wrap, error, readJson } from '../_lib/http.js';+import { constantTimeEquals } from '../_lib/crypto.js';import { env } from '../_lib/env.js';+import { qualifyingPayments, REQUIRED_AMOUNT } from '../_lib/rider.js';import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';-const REQUIRED_AMOUNT = 8000;--function safeEqual(a, b) {- if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false;- return timingSafeEqual(Buffer.from(a), Buffer.from(b));-}export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;- // Fail closed: when the webhook secret isn't configured this endpoint must- // not accept anonymous writes — it inserts rider_passes rows that grant- // access. (Previous form: `if (secret && ...)` silently accepted anything.)const secret = env.RIDER_HELIUS_WEBHOOK_SECRET;if (!secret) return error(res, 503, 'not_configured', 'rider webhook secret not set');- const presented = String(req.headers.authorization || '');- if (!safeEqual(presented, `Bearer ${secret}`)) {+ if (!constantTimeEquals(req.headers.authorization || '', `Bearer ${secret}`)) {return error(res, 401, 'unauthorized', 'invalid webhook secret');}const vaultAddress = env.RIDER_VAULT_ADDRESS;- if (!vaultAddress) return json(res, 200, { ok: true });+ if (!vaultAddress) return error(res, 503, 'not_configured', 'rider vault address not set');const txns = await readJson(req);- if (!Array.isArray(txns)) return json(res, 200, { ok: true });-- for (const txn of txns) {- if (txn.transactionError) continue;- for (const t of txn.tokenTransfers ?? []) {- if (- t.mint === THREE_MINT &&- t.toUserAccount === vaultAddress &&- Number(t.tokenAmount) >= REQUIRED_AMOUNT &&- t.fromUserAccount- ) {- await sql`- insert into rider_passes (wallet_address, amount_paid, tx_signature)- values (${t.fromUserAccount}, ${t.tokenAmount}, ${txn.signature})- on conflict (wallet_address) do update- set amount_paid = excluded.amount_paid,- tx_signature = excluded.tx_signature- `;- }- }+ if (!Array.isArray(txns)) {+ return error(res, 400, 'validation_error', 'body must be an array of Helius transactions');+ }++ const payments = qualifyingPayments(txns, {+ vaultAddress,+ mint: THREE_MINT,+ requiredAmount: REQUIRED_AMOUNT,+ });++ for (const p of payments) {+ await sql`+ insert into rider_passes (wallet_address, amount_paid, tx_signature)+ values (${p.wallet}, ${p.amount}, ${p.signature})+ on conflict (wallet_address) do update+ set amount_paid = excluded.amount_paid,+ tx_signature = excluded.tx_signature+ `;}- return json(res, 200, { ok: true });+ return json(res, 200, { ok: true, granted: payments.length });});diff --git a/api/sdp/[...path].js b/api/sdp/[...path].jsindex 24b0a020f..ee80814c1 100644--- a/api/sdp/[...path].js+++ b/api/sdp/[...path].js@@ -61,7 +61,7 @@ function hasRequestBody(req) {// Markup types are never relayed as-is. A document served as HTML (or SVG, or// XML with a stylesheet) from our own origin runs under OUR Content-Security--// Policy, which allows inline script from 'self' — so an upstream body that+// Policy, which allows inline script from 'self', so an upstream body that// echoed caller input would be script execution on three.ws. The real SDP// surfaces are JSON and text/plain, so downgrading markup costs nothing.const MARKUP_CONTENT_TYPE = /text\/html|application\/xhtml|\/xml|\+xml|image\/svg/i;diff --git a/api/seed/synthesize.js b/api/seed/synthesize.jsindex 961e65600..44199d441 100644--- a/api/seed/synthesize.js+++ b/api/seed/synthesize.js@@ -1,13 +1,16 @@// POST /api/seed/synthesize//// Takes the raw connector payloads from the three.ws memory-seeding demo-// (any subset of github / x / farcaster) and asks Claude Haiku to write a-// 200-300 word memory seed — a markdown blob describing the user's likely-// interests, expertise, voice, and recent activity. This is what the-// agent's vector store would be seeded with on first sign-in.+// (any subset of github / x / farcaster) and writes a 200-300 word memory+// seed: a markdown blob describing the user's likely interests, expertise,+// voice, and recent activity. This is what the agent's vector store would be+// seeded with on first sign-in.//-// Auth: session OR bearer token. Mirrors the shape of api/avatars/_actions.js-// handleAutoTag for the Anthropic call.+// The completion runs through _lib/llm.js, so it inherits the platform's+// free-providers-first chain and its keyless rungs. No single provider key is+// required for this endpoint to work.+//+// Auth: session OR bearer token.import { z } from 'zod';import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';@@ -31,21 +34,21 @@ const bodySchema = z}).strict();-const SYSTEM_PROMPT = `You are the memory-synthesis component of three.ws — a service that builds long-term context for personal AI agents. Given one or more public-profile snapshots from a user's connected accounts, write a single markdown "memory seed" the agent should ingest as durable context.+const SYSTEM_PROMPT = `You are the memory-synthesis component of three.ws, a service that builds long-term context for personal AI agents. Given one or more public-profile snapshots from a user's connected accounts, write a single markdown "memory seed" the agent should ingest as durable context.Constraints:- 200-300 words.- Markdown, with at most three short sections (Interests, Voice, Recent activity) or a tight prose paragraph if that reads more naturally.- Write in third person ("They build…", not "I build…").- Ground every claim in the supplied data; mark genuine uncertainty with "likely" or "appears to".-- Do NOT include URLs, follower counts, or raw metrics — turn them into qualitative signals.+- Do NOT include URLs, follower counts, or raw metrics; turn them into qualitative signals.- Do NOT mention the source platform names; refer to "their public footprint" instead.-- No preamble, no closing — output only the markdown body of the seed.`;+- No preamble, no closing. Output only the markdown body of the seed.`;function summarizeConnector(name, data) {if (!data || typeof data !== 'object') return null;if (data.ok === false) return null;- // Compact representation — we strip noisy fields so Haiku focuses on signal.+ // Compact representation: we strip noisy fields so Haiku focuses on signal.if (name === 'github') {return {handle: data.handle,@@ -129,8 +132,8 @@ export default wrap(async (req, res) => {let result;try {// Per-provider timeout well under the function's 60s maxDuration so a slow- // or hung upstream falls through to the next provider — and the handler- // still returns a clean 502/503 below — instead of the function getting+ // or hung upstream falls through to the next provider (and the handler+ // still returns a clean 502/503 below) instead of the function getting// killed mid-flight and surfacing a raw 504 to the browser.result = await llmComplete({system: SYSTEM_PROMPT,diff --git a/api/sitemap.js b/api/sitemap.jsindex 8b68e7b7b..935fe455f 100644--- a/api/sitemap.js+++ b/api/sitemap.js@@ -58,7 +58,11 @@ export default async function handler(req, res) {newestCreated('agent_identities', 'deleted_at is null and is_public = true'),newestTimestamp('avatars', "visibility = 'public' and deleted_at is null"),newestTimestamp('widgets', 'is_public = true and deleted_at is null'),- newestTimestamp('users', 'deleted_at is null and username is not null'),+ // Must match profilesSitemap()'s predicate in api/sitemap/[type].js. The+ // seed crons mint a service_account row about once a minute, so without+ // the flag this reported "profiles.xml changed" on every crawl of a feed+ // that only lists human profiles.+ newestTimestamp('users', 'deleted_at is null and username is not null and service_account = false'),newestCreated('user_subdomains'),]);diff --git a/api/sitemap/[type].js b/api/sitemap/[type].jsindex eb2427a56..65dd044cd 100644--- a/api/sitemap/[type].js+++ b/api/sitemap/[type].js@@ -1,10 +1,11 @@-// Sub-sitemap by entity type — agents, avatars, widgets, profiles, core.+// Sub-sitemap by entity type: agents, avatars, widgets, profiles, core, news.//// Each request streams up to 45k URLs (capped under the sitemaps.org 50k-// ceiling). Beyond that we'd shard into agents-1.xml, agents-2.xml, etc.,-// but the catalog is nowhere near that size yet.+// ceiling). Beyond that we'd shard into agents-1.xml, agents-2.xml, etc.+// Only news currently reaches the cap, and it drains newest month first so+// the truncation always falls on the oldest, least crawled stories.//-// Cached at the edge for 10 min — long enough to absorb crawl bursts,+// Cached at the edge for 10 min: long enough to absorb crawl bursts,// short enough that newly minted agents are discoverable within minutes// (and IndexNow gives them an instant push too).@@ -104,7 +105,7 @@ function send(res, body) {res.end(body);}-// Core (static) routes are read from data/pages.json — the same source of+// Core (static) routes are read from data/pages.json, the same source of// truth that build-page-index.mjs uses for llms.txt / sitemap.html / the// features manifest. One file to edit; this route + the human sitemap + the// AI indexes all stay in lockstep.@@ -130,7 +131,7 @@ async function coreSitemap() {const today = fmtDate(new Date());const [manifest, i18n] = await Promise.all([loadPagesManifest(), loadI18n()]);if (!manifest?.sections) {- // Fallback to the home page only — never 500 the crawler.+ // Fallback to the home page only, so we never 500 the crawler.return [{ loc: `${ORIGIN}/`, lastmod: today, changefreq: 'daily', priority: '1.0' }];}const out = [];@@ -186,7 +187,7 @@ async function avatarsSitemap() {}async function widgetsSitemap() {- // Only widgets surfaced on a public profile/showcase are worth indexing — the+ // Only widgets surfaced on a public profile/showcase are worth indexing; the// raw embed endpoint isn't human content. Filtering on is_public matches the// front-end's listing behavior.const rows = await sql`@@ -205,12 +206,24 @@ async function widgetsSitemap() {}async function profilesSitemap() {- // Public user profiles + the subdomain showcase pages they map to. We index- // /u/<username> — the canonical profile URL — and skip raw user IDs.+ // Public user profiles. We index /u/<username>, the canonical profile URL+ // the app itself links to (stored casing, matching every `/u/${username}`+ // link in src/), and skip raw user IDs.+ //+ // service_account rows are excluded. Those are the machine accounts the+ // avaturn/forge/circulation seed crons mint (see the 2026-07-25 migration+ // that added the flag) at a rate of roughly one per minute, and on+ // 2026-08-16 they were 29,600 of the 29,642 profile rows. Submitting 30k+ // auto-generated `calm144`-style profile wrappers buries the 42 real human+ // profiles and spends crawl budget on pages whose actual content (the+ // avatars and agents those accounts own) is already listed in+ // avatars.xml and agents.xml. Same predicate the metrics queries use.const rows = await sql`select u.username, u.updated_at, u.created_atfrom users u- where u.deleted_at is null and u.username is not null+ where u.deleted_at is null+ and u.username is not null+ and u.service_account = falseorder by coalesce(u.updated_at, u.created_at) desclimit ${MAX_URLS}`;@@ -224,7 +237,7 @@ async function profilesSitemap() {// Story pages (/markets/news/<YYYY-MM>/<id>-<slug>) for the newest archive// months. The full 660k-article corpus would blow the 50k/URL cap many times-// over — recent months are where crawl demand is, and older stories are+// over. Recent months are where crawl demand is, and older stories are// reachable through the archive UI and inter-article links. Months come from// the same GCS store the archive endpoint serves, so this stays in lockstep// with what actually resolves.@@ -237,7 +250,7 @@ async function newsSitemap() {for (const month of recent) {const records = await loadMonth(month).catch(() => []);for (const a of records) {- if (isSuppressed(a)) continue; // withdrawn at the rightsholder's demand — never submit it for crawling+ if (isSuppressed(a)) continue; // withdrawn at the rightsholder's demand, so never submit it for crawlingconst loc = storyPath(a);if (!loc) continue; // undated/id-less corpus rows have no story pageout.push({@@ -252,22 +265,28 @@ async function newsSitemap() {return out;}-const BUILDERS = {- core: coreSitemap,- agents: agentsSitemap,- avatars: avatarsSitemap,- widgets: widgetsSitemap,- profiles: profilesSitemap,- news: newsSitemap,-};+// A Map, not an object literal: `BUILDERS.constructor` on a literal resolves to+// Object via the prototype chain, so /api/sitemap/constructor (and toString,+// valueOf, hasOwnProperty) passed the lookup guard, called a non-builder, and+// answered a scanner with a 500 plus a bogus sitemap_failed error report. A Map+// only ever returns what was put in it.+const BUILDERS = new Map([+ ['core', coreSitemap],+ ['agents', agentsSitemap],+ ['avatars', avatarsSitemap],+ ['widgets', widgetsSitemap],+ ['profiles', profilesSitemap],+ ['news', newsSitemap],+]);export default async function handler(req, res) {const raw = String(req.query?.type || req.query?.id || '').replace(/\.xml$/i, '');- const builder = BUILDERS[raw];+ const builder = BUILDERS.get(raw);if (!builder) {res.statusCode = 404;- res.setHeader('content-type', 'text/plain');- res.end('unknown sitemap');+ res.setHeader('content-type', 'text/plain; charset=utf-8');+ res.setHeader('cache-control', 'no-store');+ res.end(`unknown sitemap. known types: ${[...BUILDERS.keys()].join(', ')}\n`);return;}try {@@ -276,8 +295,8 @@ export default async function handler(req, res) {} catch (err) {const ref = reportServerError(err, { code: 'sitemap_failed', context: { url: redactUrl(req.url), type: raw } });res.statusCode = 500;- res.setHeader('content-type', 'text/plain');+ res.setHeader('content-type', 'text/plain; charset=utf-8');res.setHeader('cache-control', 'no-store');- res.end(`sitemap failed — quote ref ${ref} to support`);+ res.end(`sitemap failed, quote ref ${ref} to support\n`);}}diff --git a/api/stage/host.js b/api/stage/host.jsindex c3ce369d9..a0e8168f2 100644--- a/api/stage/host.js+++ b/api/stage/host.js@@ -1,10 +1,10 @@/**- * Living Stages — the host brain (Moonshot 04).+ * Living Stages: the host brain (Moonshot 04).** The StageRoom's host loop calls this once per beat to get the embodied host's* next words. It reasons (latest Claude, via the platform LLM chain) over the- * live show context the room hands it — the beat kind, the audience size, the tip- * leaderboard, a fresh tip to shout out, or a queued audience question — plus the+ * live show context the room hands it (the beat kind, the audience size, the tip+ * leaderboard, a fresh tip to shout out, or a queued audience question), plus the* agent's own persona and its memory of returning regulars, and returns a short,* speakable line + an animation cue. The room synthesizes it to spatial voice +* lip-sync and broadcasts it as live captions to every client.@@ -32,8 +32,7 @@ const BEAT_CUES = {};export default wrap(async (req, res) => {- cors(req, res, { methods: ['POST', 'OPTIONS'] });- if (req.method === 'OPTIONS') return res.end();+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (req.method !== 'POST') return json(res, 405, { error: 'method_not_allowed' });let body;@@ -44,7 +43,7 @@ export default wrap(async (req, res) => {}// Gate: only the multiplayer server (which signs with the shared secret) may- // drive the host — otherwise this is a free LLM relay.+ // drive the host. Otherwise this is a free LLM relay.if (!(await verifyStageRequest(req, body))) {return json(res, 401, { error: 'unauthorized' });}@@ -58,16 +57,20 @@ export default wrap(async (req, res) => {// persona just yields a livelier-but-generic host, never a failure.const [stage] = await sql`SELECT s.agent_id, s.title, s.format, a.name AS agent_name, a.persona_prompt, a.description- FROM stages s JOIN agent_identities a ON a.id = s.agent_id+ FROM stages s JOIN agent_identities a ON a.id = s.agent_id AND a.deleted_at IS NULLWHERE s.id = ${stageId} LIMIT 1`;if (!stage) return json(res, 404, { error: 'stage not found' });// Recall regulars: the top tippers across this stage's prior shows, so the host- // can greet returning faces by name — the "remembers the regulars" behaviour.+ // can greet returning faces by name (the "remembers the regulars" behaviour).+ // Verified tips only, exactly like the public leaderboard: an unverified row is+ // caller-asserted, so counting it would let anyone put a name of their choosing+ // into the host prompt and hear it spoken to the room.const regulars = await sql`SELECT tipper_label AS label, SUM(amount_atomic)::numeric AS total, COUNT(*)::int AS visits- FROM show_tips WHERE stage_id = ${stageId} AND tipper_label IS NOT NULL+ FROM show_tips+ WHERE stage_id = ${stageId} AND tipper_label IS NOT NULL AND verified_at IS NOT NULLGROUP BY tipper_label ORDER BY total DESC LIMIT 5`;@@ -104,15 +107,15 @@ function buildSystemPrompt(stage, regulars) {.join(', ')}.`: '';return [- `You are ${stage.agent_name || 'the host'}, an embodied AI performer hosting a LIVE show "${stage.title || 'tonight’s set'}" — format: ${stage.format || 'open mic'} — in a 3D venue on three.ws.`,+ `You are ${stage.agent_name || 'the host'}, an embodied AI performer hosting a LIVE show "${stage.title || 'tonight’s set'}" (format: ${stage.format || 'open mic'}) in a 3D venue on three.ws.`,persona ? `Your persona: ${persona}` : '',`You speak OUT LOUD to a co-present crowd. Every line you return is spoken aloud and shown as live captions, so:`,`- Keep it to ONE or TWO short, punchy spoken sentences (never a paragraph, never a list, no stage directions, no emoji).`,`- Be lively, warm, quick-witted, and in-character. Read the room. Never sound canned.`,- `- The crowd tips you in $THREE. $THREE is the only coin you ever mention — never name any other token.`,+ `- The crowd tips you in $THREE. $THREE is the only coin you ever mention. Never name any other token.`,`- When someone tips, react with genuine, specific energy and thank them by name.`,regularsLine,- `Return ONLY the words you say next — no quotes, no labels.`,+ `Return ONLY the words you say next. No quotes, no labels.`,].filter(Boolean).join('\n');@@ -131,16 +134,16 @@ function buildBeatPrompt(beat, ctx) {const t = ctx.tip || {};const amt = formatThree(t.amount, t.mint);const msg = t.message ? ` They said: "${t.message}".` : '';- return `${crowd} ${t.label || 'Someone'} just tipped you ${amt}!${msg} React on the spot — thank them by name with real energy.`;+ return `${crowd} ${t.label || 'Someone'} just tipped you ${amt}!${msg} React on the spot: thank them by name with real energy.`;}case 'answer': {const q = ctx.question || {};return `${crowd} ${q.from || 'Someone'} in the crowd asks: "${q.text || ''}". Answer it live, in character, briefly.`;}case 'game':- return `${crowd} ${topLine} Run the next quick beat of your ${ctx.format || 'show'} — a one-liner round, a dare, a quick bit. Keep the crowd's energy up.`;+ return `${crowd} ${topLine} Run the next quick beat of your ${ctx.format || 'show'}: a one-liner round, a dare, a quick bit. Keep the crowd's energy up.`;default:- return `${crowd} ${topLine} Riff for a moment — read the room and keep it lively while you wait for the next tip or question.`;+ return `${crowd} ${topLine} Riff for a moment: read the room and keep it lively while you wait for the next tip or question.`;}}@@ -156,9 +159,13 @@ function formatThree(amountAtomic, mint) {// Collapse the model output to a single clean spoken line: strip surrounding// quotes, control chars, and any leaked "Host:" label, bound the length.-function sanitizeLine(s) {+// The control-class is the same one cleanLabel/cleanMessage use in stage/tip.js.+// It must stay a \u escape: written as literal characters the class collapsed to+// the printable range [space-hyphen], which silently ate every hyphen in the+// host's spoken line ("on-chain" was going out as "on chain").+export function sanitizeLine(s) {if (typeof s !== 'string') return '';- let t = s.replace(/[ -]+/g, ' ').replace(/\s+/g, ' ').trim();+ let t = s.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();t = t.replace(/^["'“”]+|["'“”]+$/g, '').trim();t = t.replace(/^[A-Za-z .]{0,24}:\s*/, ''); // drop a leaked speaker labelreturn t.slice(0, 400);diff --git a/api/swarms/index.js b/api/swarms/index.jsindex b83bd125c..1036cc469 100644--- a/api/swarms/index.js+++ b/api/swarms/index.js@@ -23,7 +23,7 @@ import { requireCsrf } from '../_lib/csrf.js';import { limits } from '../_lib/rate-limit.js';import {createSwarm, joinSwarm, contributeToSwarm, exitSwarm, killSwarm,- setSwarmPaused, listSwarms, listSwarmsForUser, SwarmError,+ setSwarmPaused, listSwarms, listSwarmsForUser, parseContributionLamports, SwarmError,} from '../_lib/swarms.js';const isUuid = (s) => typeof s === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);@@ -64,14 +64,12 @@ export default wrap(async (req, res) => {if (!(await requireCsrf(req, res, auth.userId))) return;const rl = await limits.swarmMutate(auth.userId);if (!rl.success) return rateLimited(res, rl, 'too many swarm actions: slow down');- const body = await readJson(req).catch(() => ({}));- const action = String(body.action || '');-- const lamportsFromBody = () => {- if (body.lamports != null) return BigInt(Math.max(0, Math.round(Number(body.lamports))));- if (body.sol != null) return BigInt(Math.max(0, Math.round(Number(body.sol) * 1e9)));- return 0n;- };+ // Let readJson's own 415 / 400 surface (wrap() renders either from err.status).+ // Swallowing it here answered a wrong content-type with `unknown action`, which+ // sends the caller hunting through their action names for a body they never+ // managed to send.+ const body = await readJson(req);+ const action = String(body?.action || '');try {switch (action) {@@ -93,8 +91,7 @@ export default wrap(async (req, res) => {case 'contribute': {if (!isUuid(body.swarm_id)) return error(res, 400, 'bad_swarm', 'swarm_id required');if (!isUuid(body.agent_id)) return error(res, 400, 'bad_agent', 'agent_id required');- const lamports = lamportsFromBody();- if (lamports <= 0n) return error(res, 400, 'bad_amount', 'sol or lamports required');+ const lamports = parseContributionLamports(body);const result = await contributeToSwarm({ userId: auth.userId, swarmId: body.swarm_id, agentId: body.agent_id, lamports });return json(res, 200, { data: result });}diff --git a/api/three-token/[action].js b/api/three-token/[action].jsindex f1774cdfb..e7b3b535e 100644--- a/api/three-token/[action].js+++ b/api/three-token/[action].js@@ -36,15 +36,28 @@ function shortWallet(addr) {const AGENT_DEPLOY_BURN = 1000;const REVENUE_SHARE_POOL_PCT = 10;+// Degrade a failed panel query without hiding WHY it failed. A silent+// `.catch(() => [])` is how the deploy-burn ledger shipped permanently empty:+// the query named a column agent_identities never had, the fallback turned the+// error into a plausible zero, and nothing in the logs said otherwise.+function degrade(label, value) {+ return (err) => {+ console.error(`[three-token] ${label} query failed:`, err?.message || err);+ return value;+ };+}+async function fetchPlatformMetrics() {const [agentCount, revenueData, paymentCount] = await Promise.all([sql`SELECT count(*)::int AS total FROM agent_identities WHERE deleted_at IS NULL`.catch(- () => [{ total: 0 }],+ degrade('agent_count', [{ total: 0 }]),),sql`SELECT coalesce(sum(gross_amount), 0)::bigint AS total_gross, coalesce(sum(fee_amount), 0)::bigint AS total_fee FROM agent_revenue_events`.catch(- () => [{ total_gross: 0, total_fee: 0 }],+ degrade('revenue_totals', [{ total_gross: 0, total_fee: 0 }]),+ ),+ sql`SELECT count(*)::int AS total FROM agent_revenue_events`.catch(+ degrade('payment_count', [{ total: 0 }]),),- sql`SELECT count(*)::int AS total FROM agent_revenue_events`.catch(() => [{ total: 0 }]),]);return {total_agents: agentCount[0]?.total ?? 0,@@ -58,17 +71,19 @@ async function fetchPlatformMetrics() {// We surface the most recent deployments as burn events and the lifetime total// so the burn figures are derived from real on-chain deployment records rather// than hardcoded or conflated with revenue.+// `name` is the agent's label everywhere in api/ (agent-task.js,+// autopilot/activity.js); agent_identities has no display column.async function fetchBurnEvents() {const [recent, totalRow] = await Promise.all([sql`- SELECT id, name, display_name, created_at+ SELECT id, name, created_atFROM agent_identitiesWHERE deleted_at IS NULLORDER BY created_at DESCLIMIT 20- `.catch(() => []),+ `.catch(degrade('burn_events', [])),sql`SELECT count(*)::int AS total FROM agent_identities WHERE deleted_at IS NULL`.catch(- () => [{ total: 0 }],+ degrade('burn_total', [{ total: 0 }]),),]);return { recent, totalAgents: totalRow[0]?.total ?? 0 };@@ -82,13 +97,12 @@ async function fetchRecentActivity() {e.gross_amount,e.fee_amount,e.created_at,- a.name AS agent_name,- a.display_name AS agent_display_name+ a.name AS agent_nameFROM agent_revenue_events eLEFT JOIN agent_identities a ON a.id = e.agent_idORDER BY e.created_at DESCLIMIT 30- `.catch(() => []);+ `.catch(degrade('activity_events', []));return rows;}@@ -204,7 +218,7 @@ export default wrap(async (req, res) => {return json(res, 200, {burns: recent.map((a) => ({id: a.id,- agent_name: a.display_name || a.name || 'Agent',+ agent_name: a.name || 'Agent',amount: AGENT_DEPLOY_BURN,reason: 'agent_deploy',created_at: a.created_at,@@ -222,16 +236,19 @@ export default wrap(async (req, res) => {type: e.skill || 'payment',gross_usd: e.gross_amount ? Number(e.gross_amount) / 1_000_000 : null,fee_usd: e.fee_amount ? Number(e.fee_amount) / 1_000_000 : null,- agent_name: e.agent_display_name || e.agent_name || 'Agent',+ agent_name: e.agent_name || 'Agent',created_at: e.created_at,})),});}if (action === 'leaderboard') {- const url = new URL(req.url, 'http://x');- const limit = Math.min(100, Math.max(1, Number(url.searchParams.get('limit')) || 50));- const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);+ // Non-finite input (?limit=abc, ?offset=1e999) falls back to the default+ // rather than propagating NaN/Infinity into the slice and the JSON body.+ const limitRaw = Number(url.searchParams.get('limit'));+ const limit = Number.isFinite(limitRaw) && limitRaw >= 1 ? Math.min(100, Math.floor(limitRaw)) : 50;+ const offsetRaw = Number(url.searchParams.get('offset'));+ const offset = Number.isFinite(offsetRaw) && offsetRaw > 0 ? Math.floor(offsetRaw) : 0;try {// Holder set from the cached snapshot (three-holders-snapshot cron) — thediff --git a/api/three/[action].js b/api/three/[action].jsindex fea29eded..78a288829 100644--- a/api/three/[action].js+++ b/api/three/[action].js@@ -297,10 +297,17 @@ async function handleEarnings(req, res) {return json(res, 200, { total_atomics: '0', sale_count: 0, mint: null, decimals: null, items: [], next_cursor: null });}const url = new URL(req.url, 'http://x');+ // `before` is a page cursor echoed back from `next_cursor` (a timestamptz). A+ // value that is not a timestamp reaches Postgres as a bad cast, so it is+ // rejected here as the 400 it is rather than surfacing as a 5xx.+ const before = (url.searchParams.get('before') || '').trim();+ if (before && !Number.isFinite(Date.parse(before))) {+ return error(res, 400, 'invalid_cursor', 'before must be an ISO 8601 timestamp from next_cursor');+ }const page = await creatorEarnings({sellerWallet: user.wallet_address,limit: Math.min(Math.max(Number(url.searchParams.get('limit')) || 50, 1), 200),- before: url.searchParams.get('before') || null,+ before: before || null,});return json(res, 200, page);}@@ -340,6 +347,10 @@ async function handleNameQuote(req, res) {// with Solscan links, plus the real reflected-to-holders history. "Don't trust,// verify" — every headline number traces to an address anyone can inspect.+// Ten years of ledger. Beyond this a Postgres interval overflows, so a caller+// asking for "everything" is clamped here instead of being handed a 5xx.+const MAX_SINCE_DAYS = 3650;+async function handleStats(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;@@ -347,13 +358,25 @@ async function handleStats(req, res) {if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://x');- const sinceDays = url.searchParams.get('since_days');+ // `since_days` windows the aggregates. A non-numeric value used to reach+ // Postgres as the interval `NaN days` and surface as a 5xx, so it is rejected+ // here; a real number is clamped into range the same way `earnings` clamps its+ // limit. An empty value means no window, exactly like omitting the param.+ const rawSince = (url.searchParams.get('since_days') || '').trim();+ let sinceDays = null;+ if (rawSince) {+ const n = Number(rawSince);+ if (!Number.isFinite(n)) {+ return error(res, 400, 'invalid_since_days', 'since_days must be a number of days');+ }+ sinceDays = Math.min(Math.max(Math.floor(n), 1), MAX_SINCE_DAYS);+ }const cfg = publicConfig();// Fan out the independent reads concurrently: ledger aggregates, live wallet// balances, and the distribution history. Each degrades independently.const [stats, treasuryAtomics, rewardsAtomics, distributions] = await Promise.all([- economyStats({ sinceDays: sinceDays != null ? Number(sinceDays) : null }),+ economyStats({ sinceDays }),liveWalletAtomics(cfg.treasury),liveWalletAtomics(cfg.rewards_wallet),listRewardsDistributions({ limit: 10 }).catch(() => ({diff --git a/api/threews/me.js b/api/threews/me.jsindex b198593fe..a8ac26ed3 100644--- a/api/threews/me.js+++ b/api/threews/me.js@@ -1,8 +1,15 @@// GET /api/threews/me//// Returns the authenticated caller's `*.threews.sol` subdomain claim, if any.-// Powers the dashboard widget that shows "your subdomain" without making the+// Powers the /threews/claim page's "your subdomain" state without making the// caller pass their own label as a query parameter.+//+// `status` is the field to branch on:+// claimed → `claim` holds the minted name, showcase URL and tx link.+// available → no claim yet and the account has a username; `claim_url`+// points at the page that mints it.+// needs_username → the account has no username, so a mint would 409;+// `blocked_reason` says so in words a UI can render.import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';@@ -44,20 +51,30 @@ export default wrap(async (req, res) => {LIMIT 1`;+ // Three terminal states, all of them named. A widget that only got+ // `claim: null` could not tell "go claim one" apart from "you can't yet",+ // and a user with no username would silently see a dead button that 409s.+ const status = claim ? 'claimed' : user.username ? 'available' : 'needs_username';+return json(res, 200, {data: {user: { id: user.id, username: user.username, display_name: user.display_name },parent: PARENT_LABEL,+ status,has_claim: !!claim,claim: claim? {...claim,full: fullDomain(claim.label),- showcase_url: `${env.APP_ORIGIN}/u/${user.username}`,- explorer: `https://solscan.io/tx/${claim.signature}`,+ // A username can be changed after the mint, so fall back to the+ // URL record actually written on-chain rather than /u/null.+ showcase_url: user.username ? `${env.APP_ORIGIN}/u/${user.username}` : claim.url_record,+ explorer: claim.signature ? `https://solscan.io/tx/${claim.signature}` : null,}: null,- claim_url: !claim && user.username ? `${env.APP_ORIGIN}/threews/claim` : null,+ claim_url: status === 'available' ? `${env.APP_ORIGIN}/threews/claim` : null,+ blocked_reason:+ status === 'needs_username' ? 'set a username on your account before claiming a subdomain' : null,},});});diff --git a/api/threews/subdomain.js b/api/threews/subdomain.jsindex e1c4f6ae0..8bb7a0e1d 100644--- a/api/threews/subdomain.js+++ b/api/threews/subdomain.js@@ -7,7 +7,7 @@// transfer ownership to `owner_wallet` (or// to the caller's default agent wallet).// Requires authentication.-// DELETE → release the caller's stored subdomain+// DELETE ?label=<label> → release the caller's stored subdomain// claim (does NOT release the on-chain// subdomain; that's still owned by the// recipient wallet).@@ -133,7 +133,22 @@ async function handleMint(req, res, auth) {`;if (existing) return error(res, 409, 'conflict', `${fullDomain(label)} is already claimed`);- const onChainOwner = await getSubdomainOwner(label);+ // The availability check is a hard gate here, not the best-effort lookup the+ // GET path does: minting over a name someone already owns burns rent and+ // fails on-chain anyway. An RPC outage therefore has to surface as a+ // retryable 503 rather than an unhandled throw that reads as a server bug.+ let onChainOwner;+ try {+ onChainOwner = await getSubdomainOwner(label);+ } catch (err) {+ console.warn('[threews/subdomain] pre-mint on-chain check failed', err?.message);+ return error(+ res,+ 503,+ 'upstream_unavailable',+ 'could not verify the name on Solana right now; retry in a moment',+ );+ }if (onChainOwner) {return error(res, 409, 'conflict', `${fullDomain(label)} is already registered on-chain to ${onChainOwner}`);}diff --git a/api/wallet/balances.js b/api/wallet/balances.jsindex b5019e990..fa65dbcb6 100644--- a/api/wallet/balances.js+++ b/api/wallet/balances.js@@ -5,7 +5,7 @@import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { getBalances } from '../_lib/balances.js';-import { isValidSolanaAddress, isValidEvmAddress } from '../_lib/validate.js';+import { isValidSolanaAddress, isValidEvmAddress, parse } from '../_lib/validate.js';import { z } from 'zod';// The address is caller-supplied, so its shape is checked here rather than left@@ -38,14 +38,28 @@ export default wrap(async (req, res) => {const rl = await limits.authedReadIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- let body;+ // A body we could not read at all is a different failure from a body we read+ // and rejected, so the two are caught separately. Folding them together sent+ // an integrator who posted 3 MB, or forgot the JSON content-type, hunting+ // through their `chain` and `address` fields for a validation fault that was+ // never there: readJson raises 415 and 413 deliberately, and a single catch+ // rewrote both into a flat 400 validation_error.+ let raw;try {- const raw = await readJson(req);- body = bodySchema.parse(raw);+ raw = await readJson(req);} catch (e) {- return error(res, 400, 'validation_error', e.message);+ const status = e?.status === 415 || e?.status === 413 ? e.status : 400;+ const code = { 415: 'unsupported_media_type', 413: 'payload_too_large' }[status] || 'bad_request';+ return error(res, status, code, e?.message || 'unreadable request body');}+ // The shared parse() raises the platform's validation_error, which wrap()+ // renders through validationError() as a readable message plus a field-level+ // `issues` array. Calling schema.parse() directly and echoing e.message put+ // zod's own multi-line JSON dump of every issue into error_description, which+ // no client can render and which no other zod handler here emits.+ const body = parse(bodySchema, raw);+try {const result = await getBalances({ chain: body.chain, address: body.address });return json(res, 200, result);diff --git a/data/changelog.json b/data/changelog.jsonindex b6df76536..39746ec26 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -502,6 +502,15 @@],"link": "/docs/api-reference"},+ {+ "date": "2026-08-15",+ "title": "The Duplicate button on your widgets works again",+ "summary": "Duplicating a widget from the dashboard failed every single time. The clone request never gave the new widget an identifier, and because the database requires one, the copy was rejected before it was written and the page showed only a generic server error with a support reference. There was a second, correct copy of the same clone logic already in the codebase that the route was not using; the route now runs that one, so duplicating gives you a real new widget with its own id, its own name ending in (copy), and the original's type, look, avatar and visibility carried over. The duplicate request also now carries the same cross-site request protection every other widget change already had, and it accepts an API key with write access, so you can clone a widget from a script as well as from the dashboard. Transcripts got a smaller correction alongside it: when no chat provider is configured and the platform answers with its own placeholder line, that message is no longer filed in your transcript as if a model had written it.",+ "tags": [+ "fix"+ ],+ "link": "/dashboard/widgets"+ },{"date": "2026-08-15","title": "The tokenized-stock board sorts the way you asked, with the busiest names first",diff --git a/packages/portfolio-mcp/src/tools/trades-feed.js b/packages/portfolio-mcp/src/tools/trades-feed.jsindex 80c2b668b..4e8bad561 100644--- a/packages/portfolio-mcp/src/tools/trades-feed.js+++ b/packages/portfolio-mcp/src/tools/trades-feed.js@@ -16,6 +16,8 @@ export const def = {'The public feed of notable CLOSED positions across all three.ws agents, newest exit first — the canonical ' +'source of realized PnL on the platform. Each item carries the coin (mint, symbol, name), the trader ' +'(agent_id, agent_name, copier_count), entry_sol / exit_sol / realized_pnl_sol / realized_pnl_pct / multiple, ' ++ 'where realized_pnl_pct and multiple are the whole position\'s return across every sell leg while entry_sol ' ++ 'and exit_sol describe the remaining cost basis and the closing leg only, ' +'hold_seconds, exit_reason, the buy/sell signatures, and oracle conviction context when the coin was scored. ' +'Filter by `mint` to see every closed trade on one coin (the time window is ignored when a mint is set). ' +'Paginate with `cursor` = the previous response\'s `next_cursor`. No auth required — read-only live data.',diff --git a/pages/threews-claim.html b/pages/threews-claim.htmlindex 1a5301332..4cef55b1f 100644--- a/pages/threews-claim.html+++ b/pages/threews-claim.html@@ -189,7 +189,12 @@your three.ws showcase. Your agents, avatars, and skills, all under one name.</p>- <section class="tw-card">+ <section class="tw-card" id="tw-account" hidden aria-live="polite">+ <div class="tw-status muted" id="tw-account-status"></div>+ <div id="tw-account-actions"></div>+ </section>++ <section class="tw-card" id="tw-mint-card"><label for="tw-label" data-i18n="threews_claim.subdomain_label">Subdomain label</label><div class="tw-input-row"><input id="tw-label" type="text" autocomplete="off" autocapitalize="off" spellcheck="false" placeholder="yourhandle" maxlength="63" />@@ -225,11 +230,90 @@const statusEl = document.getElementById('tw-status');const mintBtn = document.getElementById('tw-mint');const resultEl = document.getElementById('tw-result');+ const mintCard = document.getElementById('tw-mint-card');+ const acctCard = document.getElementById('tw-account');+ const acctStatus = document.getElementById('tw-account-status');+ const acctActions = document.getElementById('tw-account-actions');let checkTimer = null;let lastChecked = null;let csrfToken = null;+ function escapeHtml(value) {+ return String(value).replace(/[&<>"']/g, (c) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+ })[c]);+ }++ function showOwnedClaim(claim) {+ const full = escapeHtml(claim.full);+ resultEl.innerHTML = `+ <h3>${full} is yours.</h3>+ <p class="tw-help" style="margin:.4em 0">+ Brave users can type <strong>${full}</strong> in the URL bar and land on+ your showcase. Anyone can pay you by sending to that name via the+ pay-by-name API.+ </p>+ <p style="margin:.4em 0">+ ${claim.showcase_url ? `<a href="${escapeHtml(claim.showcase_url)}">${escapeHtml(claim.showcase_url)}</a><br>` : ''}+ ${claim.explorer ? `<span class="tw-help">tx: <a href="${escapeHtml(claim.explorer)}" target="_blank" rel="noopener">${escapeHtml(claim.signature || 'view on Solscan')}</a></span>` : ''}+ </p>+ `;+ resultEl.classList.add('on');+ }++ // Ask the API what this account's subdomain situation already is, so a+ // returning owner is not asked to re-check a name they already minted and+ // an account with no username learns that before the mint 409s.+ async function loadAccountState() {+ let res;+ try {+ res = await fetch('/api/threews/me', { credentials: 'same-origin' });+ } catch {+ // Offline or blocked: the anonymous availability checker still works.+ return;+ }+ if (res.status === 401) {+ acctCard.hidden = false;+ acctStatus.textContent = 'Sign in to mint a subdomain. You can still check availability below.';+ acctActions.innerHTML = '<a class="tw-btn ghost" href="/login?next=/threews/claim">Sign in</a>';+ return;+ }+ if (!res.ok) return;+ const payload = await res.json().catch(() => null);+ const me = payload?.data;+ if (!me) return;++ acctCard.hidden = false;+ if (me.status === 'claimed' && me.claim) {+ acctStatus.textContent = `You already own ${me.claim.full}.`;+ acctStatus.className = 'tw-status ok';+ acctActions.innerHTML = me.claim.showcase_url+ ? `<a class="tw-btn ghost" href="${escapeHtml(me.claim.showcase_url)}">View your showcase</a>`+ : '';+ mintCard.hidden = true;+ showOwnedClaim(me.claim);+ return;+ }+ if (me.status === 'needs_username') {+ acctStatus.textContent = me.blocked_reason || 'Set a username before claiming a subdomain.';+ acctStatus.className = 'tw-status bad';+ acctActions.innerHTML = '<a class="tw-btn ghost" href="/settings">Set a username</a>';+ labelEl.disabled = true;+ mintBtn.disabled = true;+ statusEl.textContent = 'A username is required before a label can be minted.';+ return;+ }+ // status === 'available': the label is forced to equal the username, so+ // prefill it and run the check rather than making them type it.+ const handle = me.user?.username;+ if (!handle) return;+ acctStatus.textContent = `Signed in as @${handle}. Your subdomain label must match your username.`;+ labelEl.value = handle;+ labelEl.readOnly = true;+ check(handle);+ }+labelEl.addEventListener('input', () => {const raw = labelEl.value.trim().toLowerCase();const cleaned = raw.replace(/[^a-z0-9-]/g, '');@@ -308,25 +392,20 @@const d = data.data;statusEl.textContent = `${d.full} minted.`;statusEl.className = 'tw-status ok';- resultEl.innerHTML = `- <h3>${d.full} is yours.</h3>- <p class="tw-help" style="margin:.4em 0">- Brave users can type <strong>${d.full}</strong> in the URL bar and- land on your showcase. Anyone can pay you by sending to that name- via the pay-by-name API.- </p>- <p style="margin:.4em 0">- <a href="${d.showcase_url}">${d.showcase_url}</a><br>- <span class="tw-help">tx: <a href="https://solscan.io/tx/${encodeURIComponent(d.signature)}" target="_blank" rel="noopener">${d.signature}</a></span>- </p>- `;- resultEl.classList.add('on');+ showOwnedClaim({+ full: d.full,+ showcase_url: d.showcase_url,+ signature: d.signature,+ explorer: d.explorer || (d.signature ? `https://solscan.io/tx/${encodeURIComponent(d.signature)}` : null),+ });} catch (err) {statusEl.textContent = err?.message || 'Mint failed.';statusEl.className = 'tw-status bad';mintBtn.disabled = false;}});++ loadAccountState();</script><script src="/brand.js" defer></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->diff --git a/public/changelog.json b/public/changelog.jsonindex cbb302a24..5c72708ba 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-16T06:11:43.017Z",+ "generated_at": "2026-08-16T06:15:48.775Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -699,6 +699,16 @@"docs"]},+ {+ "date": "2026-08-15",+ "type": "update",+ "title": "The Duplicate button on your widgets works again",+ "summary": "Duplicating a widget from the dashboard failed every single time. The clone request never gave the new widget an identifier, and because the database requires one, the copy was rejected before it was written and the page showed only a generic server error with a support reference. There was a second, correct copy of the same clone logic already in the codebase that the route was not using; the route now runs that one, so duplicating gives you a real new widget with its own id, its own name ending in (copy), and the original's type, look, avatar and visibility carried over. The duplicate request also now carries the same cross-site request protection every other widget change already had, and it accepts an API key with write access, so you can clone a widget from a script as well as from the dashboard. Transcripts got a smaller correction alongside it: when no chat provider is configured and the platform answers with its own placeholder line, that message is no longer filed in your transcript as if a model had written it.",+ "link": "/dashboard/widgets",+ "tags": [+ "fix"+ ]+ },{"date": "2026-08-15","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 17fda8276..79d30361f 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -518,6 +518,14 @@<category>fix</category><description>Duplicating a widget from the dashboard failed every single time. The clone request never gave the new widget an identifier, and because the database requires one, the copy was rejected before it was written and the page showed only a generic server error with a support reference. A second, correct copy of the same clone logic was already in the codebase and the route simply was not using it; the route now runs that one, so duplicating gives you a real new widget with its own id, its own name ending in (copy), and the original's type, look, avatar and visibility carried over. The duplicate request also now carries the same cross-site request protection every other widget change already had, and it accepts an API key with write access, so you can clone a widget from a script as well as from the dashboard. Two smaller corrections travelled with it. When no chat provider is configured and the platform answers a visitor with its own placeholder line, that message is no longer filed in your transcript as though a model had written it. And chatting with one of the showcase widgets in the public gallery no longer tries to file a transcript against a widget that does not exist, which failed on every message. The developer reference now documents duplicate, stats, chat, transcripts and the knowledge base, all of which were live but undocumented.</description></item>+ <item>+ <title>The Duplicate button on your widgets works again</title>+ <link>https://three.ws/dashboard/widgets</link>+ <guid isPermaLink="false">2026-08-15:The Duplicate button on your widgets works again</guid>+ <pubDate>Sat, 15 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Duplicating a widget from the dashboard failed every single time. The clone request never gave the new widget an identifier, and because the database requires one, the copy was rejected before it was written and the page showed only a generic server error with a support reference. There was a second, correct copy of the same clone logic already in the codebase that the route was not using; the route now runs that one, so duplicating gives you a real new widget with its own id, its own name ending in (copy), and the original's type, look, avatar and visibility carried over. The duplicate request also now carries the same cross-site request protection every other widget change already had, and it accepts an API key with write access, so you can clone a widget from a script as well as from the dashboard. Transcripts got a smaller correction alongside it: when no chat provider is configured and the platform answers with its own placeholder line, that message is no longer filed in your transcript as if a model had written it.</description>+ </item><item><title>The embed and sharing tutorials now describe the surfaces that actually exist</title><link>https://three.ws/tutorials/swap-avatar-in-studio</link>diff --git a/public/demos/memory-seed.html b/public/demos/memory-seed.htmlindex 21c5762d6..738c7ad27 100644--- a/public/demos/memory-seed.html+++ b/public/demos/memory-seed.html@@ -273,20 +273,27 @@function renderFarcaster(d) {const casts = (d.recent_casts || []).slice(0, 3);+ // The keyless hub lane serves raw protocol messages, so it has no+ // reaction counts. Show engagement only where the lane knows it+ // rather than rendering an unknown as zero.const items = casts.length? casts.map((c) => `<div class="item">${escapeHtml((c.text || '').slice(0, 220))}- <div class="meta">♡ ${c.likes} · ↻ ${c.recasts} · 💬 ${c.replies}</div>+ ${typeof c.engagement === 'number' ? `<div class="meta">engagement ${c.engagement}</div>` : ''}</div>`).join(''): '<div class="item meta">no recent casts available</div>';+ const followers = typeof d.follower_count === 'number'+ ? `<span><b>${d.follower_count}</b> followers</span>`+ : '';return `${renderProfileHead(d.avatar_url, d.display_name || d.handle, '@' + d.handle + ' · fid ' + d.fid)}<div class="bio">${escapeHtml(d.bio || '')}</div><div class="stats">- <span><b>${d.follower_count}</b> followers</span>+ ${followers}<span><b>${d.recent_casts?.length || 0}</b> recent casts</span>+ ${d.lane ? `<span>via <b>${escapeHtml(d.lane)}</b></span>` : ''}</div><div class="items">${items}</div>`;diff --git a/public/features.json b/public/features.jsonindex cdca90e17..dfaea8e8c 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-16T06:11:42.813Z",+ "generated_at": "2026-08-16T06:15:48.675Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/memory-seed.js b/src/memory-seed.jsindex 055e6b2bb..4a7c00665 100644--- a/src/memory-seed.js+++ b/src/memory-seed.js@@ -264,12 +264,18 @@ export function mountSeedWidget(host, opts = {}) {}const fc = state.connectors.farcaster;if (fc) {+ // follower_count is null on the keyless hub lane, which serves raw+ // protocol messages and cannot know it. Fall back to the cast count+ // instead of printing "null followers".+ const fcStat = typeof fc.follower_count === 'number'+ ? `<span><b>${fc.follower_count}</b> followers</span>`+ : `<span><b>${fc.recent_casts?.length || 0}</b> casts</span>`;panels.push(`<div class="msw-panel"><div class="msw-panel-head">${fc.avatar_url ? `<img loading="lazy" decoding="async" class="msw-panel-av" src="${esc(fc.avatar_url)}" alt="" referrerpolicy="no-referrer"/>` : ''}<div><div class="msw-panel-name">${esc(fc.display_name || fc.handle)}</div><div class="msw-panel-sub">@${esc(fc.handle)}</div></div></div>- <div class="msw-panel-stats"><span><b>${fc.follower_count}</b> followers</span></div>+ <div class="msw-panel-stats">${fcStat}</div></div>`);}diff --git a/tests/api-studio-retexture-region.test.js b/tests/api-studio-retexture-region.test.jsnew file mode 100644index 000000000..a51e2098d--- /dev/null+++ b/tests/api-studio-retexture-region.test.js@@ -0,0 +1,368 @@+// Handler tests for the Magic Brush region-retexture gateway+// (api/studio/retexture-region.js).+//+// Only the two real external boundaries are stubbed: the auth lookup, the rate+// limiter, and the SSRF DNS probe (each covered by its own suite), plus+// global.fetch standing in for the GCP texture worker's HTTP surface. The+// provider (api/_providers/gcp.js) runs for real, so these pin the actual wire+// contract this endpoint speaks to workers/texture: POST /retexture_region and+// GET /tasks/:id, and the opaque job token that carries the task handle between+// them.++import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';++const getSessionUserMock = vi.fn();+const authenticateBearerMock = vi.fn();+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: (...a) => getSessionUserMock(...a),+ authenticateBearer: (...a) => authenticateBearerMock(...a),+ extractBearer: (req) => req.headers?.authorization?.replace(/^Bearer /i, '') || null,+ hasScope: (scopes, want) => String(scopes || '').split(/[\s,]+/).includes(want),+}));++// Quota behaviour has its own suites; here the limiters are open so the handler+// logic is what's under test. `allow` flips them to exercise the 429 path.+let allow = true;+const limitResult = () => ({+ success: allow,+ limit: 60,+ remaining: allow ? 59 : 0,+ reset: 1_000_000,+});+vi.mock('../api/_lib/rate-limit.js', () => ({+ clientIp: () => '203.0.113.7',+ limits: {+ upload: async () => limitResult(),+ mcp3dStatus: async () => limitResult(),+ },+}));++// The guard resolves DNS; its own behaviour is covered by tests/ssrf-pinned-lookup+// and tests/auto-rig-ssrf. Here it enforces the shape the handler depends on+// (https + public host) without touching the network.+vi.mock('../api/_lib/ssrf-guard.js', () => ({+ assertSafePublicUrl: async (raw, { allowHttp = false } = {}) => {+ const u = new URL(raw);+ if (u.protocol !== 'https:' && !allowHttp) throw new Error('https required');+ if (/^(localhost|127\.|10\.|192\.168\.)/.test(u.hostname)) throw new Error('private host');+ return u;+ },+}));++const WORKER = 'https://texture-worker.test';+const { default: handler } = await import('../api/studio/retexture-region.js');++const MESH = 'https://cdn.three.ws/models/avatar.glb';+const MASK = 'iVBORw0KGgoAAAANSUhEUg==';++function mkReq({ method = 'GET', url = '/api/studio/retexture-region', headers = {}, body = null } = {}) {+ return {+ method,+ url,+ headers: { ...headers },+ on(event, cb) {+ if (event === 'data' && body != null) {+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));+ queueMicrotask(() => {+ cb(buf);+ this._endCb?.();+ });+ } else if (event === 'end') {+ this._endCb = cb;+ if (body == null) queueMicrotask(cb);+ }+ },+ destroy() {},+ };+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ end(chunk) {+ this.body = chunk;+ this.writableEnded = true;+ },+ };+}++async function call(opts) {+ const res = mkRes();+ await handler(mkReq(opts), res);+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : undefined, res };+}++const post = (body) =>+ call({ method: 'POST', headers: { 'content-type': 'application/json' }, body });+const poll = (job) =>+ call({ url: `/api/studio/retexture-region?job=${encodeURIComponent(job)}` });++const realFetch = global.fetch;+afterAll(() => {+ global.fetch = realFetch;+});++let workerCalls = [];++beforeEach(() => {+ allow = true;+ workerCalls = [];+ process.env.GCP_RECONSTRUCTION_KEY = 'test-worker-key';+ process.env.GCP_TEXTURE_URL = WORKER;+ getSessionUserMock.mockReset().mockResolvedValue({ id: 'user-1' });+ authenticateBearerMock.mockReset().mockResolvedValue(null);++ global.fetch = vi.fn(async (url, opts = {}) => {+ const u = String(url);+ workerCalls.push({ url: u, method: opts.method || 'GET', body: opts.body ? JSON.parse(opts.body) : null, headers: opts.headers });+ if (u === `${WORKER}/retexture_region`) {+ return { ok: true, status: 200, json: async () => ({ task_id: 'task-42', status: 'queued' }) };+ }+ if (u.startsWith(`${WORKER}/tasks/`)) {+ return {+ ok: true,+ status: 200,+ json: async () => ({ status: 'done', result_url: 'https://cdn.three.ws/out/avatar-retex.glb' }),+ };+ }+ throw new Error(`unexpected fetch: ${u}`);+ });+});++describe('POST /api/studio/retexture-region — the success path', () => {+ it('submits the masked region to the texture worker and returns an opaque job token', async () => {+ const { status, body } = await post({+ mesh_url: MESH,+ prompt: 'worn red leather',+ mask_b64: MASK,+ texture_size: 2048,+ strength: 0.6,+ });++ expect(status).toBe(202);+ expect(body.ok).toBe(true);+ expect(body.status).toBe('queued');+ expect(typeof body.job).toBe('string');++ expect(workerCalls).toHaveLength(1);+ const sent = workerCalls[0];+ expect(sent.url).toBe(`${WORKER}/retexture_region`);+ expect(sent.method).toBe('POST');+ expect(sent.headers.authorization).toBe('Bearer test-worker-key');+ expect(sent.body).toMatchObject({+ mesh: MESH,+ prompt: 'worn red leather',+ mask_b64: MASK,+ texture_size: 2048,+ strength: 0.6,+ feather: 24,+ seed: 0,+ });++ // The token carries the task handle plus the worker it was issued for.+ const job = JSON.parse(Buffer.from(body.job, 'base64url').toString('utf8'));+ expect(job).toMatchObject({ mode: 'retex_region', taskId: 'task-42', baseUrl: WORKER });+ });++ it('accepts a colour-only edit with no prompt', async () => {+ const { status } = await post({ mesh_url: MESH, mask_b64: MASK, color: '#3fa9f5' });+ expect(status).toBe(202);+ expect(workerCalls[0].body.color).toBe('#3fa9f5');+ });++ it('polls the task through and hands back the finished texture', async () => {+ const { body: submitted } = await post({ mesh_url: MESH, prompt: 'brushed steel', mask_b64: MASK });+ const { status, body } = await poll(submitted.job);++ expect(status).toBe(200);+ expect(body).toMatchObject({+ ok: true,+ status: 'done',+ result_url: 'https://cdn.three.ws/out/avatar-retex.glb',+ error: null,+ });+ expect(workerCalls[1].url).toBe(`${WORKER}/tasks/task-42`);+ });+});++describe('auth and quota', () => {+ it('rejects an anonymous submit and an anonymous poll with 401', async () => {+ getSessionUserMock.mockResolvedValue(null);+ const submit = await post({ mesh_url: MESH, prompt: 'gold leaf', mask_b64: MASK });+ expect(submit.status).toBe(401);+ expect(submit.body.error).toBe('unauthorized');++ const status = await poll('anything');+ expect(status.status).toBe(401);+ expect(workerCalls).toHaveLength(0);+ });++ it('accepts a bearer token carrying the avatars:write scope', async () => {+ getSessionUserMock.mockResolvedValue(null);+ authenticateBearerMock.mockResolvedValue({ userId: 'agent-9', scope: 'avatars:read avatars:write' });+ const { status } = await call({+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: 'Bearer tok' },+ body: { mesh_url: MESH, prompt: 'gold leaf', mask_b64: MASK },+ });+ expect(status).toBe(202);+ });++ it('rejects a bearer token missing the write scope', async () => {+ getSessionUserMock.mockResolvedValue(null);+ authenticateBearerMock.mockResolvedValue({ userId: 'agent-9', scope: 'avatars:read' });+ const { status, body } = await call({+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: 'Bearer tok' },+ body: { mesh_url: MESH, prompt: 'gold leaf', mask_b64: MASK },+ });+ expect(status).toBe(401);+ expect(body.error).toBe('unauthorized');+ });++ it('rate-limits both the submit and the status poll', async () => {+ allow = false;+ const submit = await post({ mesh_url: MESH, prompt: 'gold leaf', mask_b64: MASK });+ expect(submit.status).toBe(429);+ expect(submit.body.error).toBe('rate_limited');++ const status = await poll('anything');+ expect(status.status).toBe(429);+ expect(workerCalls).toHaveLength(0);+ });+});++describe('input validation', () => {+ it('rejects a request with neither a usable prompt nor a colour', async () => {+ const { status, body } = await post({ mesh_url: MESH, mask_b64: MASK, prompt: 'ab' });+ expect(status).toBe(400);+ expect(body.error).toBe('validation_error');+ expect(body.error_description).toContain('prompt');+ });++ it.each([+ ['a missing mesh_url and mask', {}],+ ['a non-hex colour', { mesh_url: MESH, mask_b64: MASK, color: 'reddish' }],+ ['an unsupported texture size', { mesh_url: MESH, mask_b64: MASK, prompt: 'x-ray', texture_size: 333 }],+ ['an out-of-range strength', { mesh_url: MESH, mask_b64: MASK, prompt: 'x-ray', strength: 4 }],+ ['a fractional feather', { mesh_url: MESH, mask_b64: MASK, prompt: 'x-ray', feather: 2.5 }],+ ])('rejects %s with a 400 JSON error', async (_label, body) => {+ const { status, body: out } = await post(body);+ expect(status).toBe(400);+ expect(out.error).toBe('validation_error');+ expect(workerCalls).toHaveLength(0);+ });++ it('rejects a mesh_url the SSRF guard will not vouch for', async () => {+ const { status, body } = await post({+ mesh_url: 'http://127.0.0.1:8080/private.glb',+ prompt: 'gold leaf',+ mask_b64: MASK,+ });+ expect(status).toBe(400);+ expect(body.error).toBe('invalid_mesh_url');+ expect(workerCalls).toHaveLength(0);+ });++ it('rejects a poll with no job token', async () => {+ const { status, body } = await call({ url: '/api/studio/retexture-region' });+ expect(status).toBe(400);+ expect(body.error).toBe('invalid_request');+ });+});++describe('job-token forgery cannot steer the server fetch', () => {+ it('refuses a token pointing at a host that is not the configured worker', async () => {+ const forged = Buffer.from(+ JSON.stringify({ mode: 'retex_region', taskId: 'x', baseUrl: 'https://evil.example.com' }),+ ).toString('base64url');+ const { status, body } = await poll(forged);+ expect(status).toBe(400);+ expect(body.error).toBe('invalid_job');+ expect(workerCalls).toHaveLength(0);+ });++ it('refuses a token for a different worker mode on our own host', async () => {+ const forged = Buffer.from(+ JSON.stringify({ mode: 'reconstruct', taskId: 'x', baseUrl: WORKER }),+ ).toString('base64url');+ const { status, body } = await poll(forged);+ expect(status).toBe(400);+ expect(body.error).toBe('invalid_job');+ expect(workerCalls).toHaveLength(0);+ });++ it('refuses a token that is not decodable at all', async () => {+ const { status, body } = await poll('%%%not-a-token%%%');+ expect(status).toBe(400);+ expect(body.error).toBe('invalid_job');+ expect(workerCalls).toHaveLength(0);+ });+});++describe('the texture worker is unavailable', () => {+ it('answers 501 on both verbs when the worker URL is unset, never a bogus "malformed token"', async () => {+ // A token issued while the lane was up must not be reported as forged just+ // because the deployment lost GCP_TEXTURE_URL: the honest answer is 501.+ const { body: submitted } = await post({ mesh_url: MESH, prompt: 'brushed steel', mask_b64: MASK });+ delete process.env.GCP_TEXTURE_URL;++ const submit = await post({ mesh_url: MESH, prompt: 'brushed steel', mask_b64: MASK });+ expect(submit.status).toBe(501);+ expect(submit.body.error).toBe('region_retex_unconfigured');++ const status = await poll(submitted.job);+ expect(status.status).toBe(501);+ expect(status.body.error).toBe('region_retex_unconfigured');+ expect(workerCalls).toHaveLength(1); // only the first, pre-outage submit+ });++ it('answers 501 when the shared worker key is unset', async () => {+ delete process.env.GCP_RECONSTRUCTION_KEY;+ const { status, body } = await post({ mesh_url: MESH, prompt: 'brushed steel', mask_b64: MASK });+ expect(status).toBe(501);+ expect(body.error).toBe('region_retex_unconfigured');+ });++ it('surfaces a worker rejection as a 502 rather than a stack trace', async () => {+ global.fetch = vi.fn(async () => ({+ ok: false,+ status: 503,+ json: async () => ({ detail: 'model server warming up' }),+ }));+ const { status, body } = await post({ mesh_url: MESH, prompt: 'brushed steel', mask_b64: MASK });+ expect(status).toBe(502);+ expect(body.error).toBe('provider_error');+ expect(body.error_description).toBe('model server warming up');+ });++ it('reports a failed task through the poll body instead of throwing', async () => {+ const { body: submitted } = await post({ mesh_url: MESH, prompt: 'brushed steel', mask_b64: MASK });+ global.fetch = vi.fn(async () => ({+ ok: true,+ status: 200,+ json: async () => ({ status: 'failed', error: 'mask covered no UV island' }),+ }));+ const { status, body } = await poll(submitted.job);+ expect(status).toBe(200);+ expect(body).toMatchObject({ status: 'failed', result_url: null, error: 'mask covered no UV island' });+ });+});++describe('transport', () => {+ it('answers a CORS preflight and refuses an unsupported method', async () => {+ const pre = await call({ method: 'OPTIONS', headers: { origin: 'https://three.ws' } });+ expect(pre.status).toBe(204);+ expect(pre.res.headers['access-control-allow-methods']).toContain('POST');++ const put = await call({ method: 'PUT' });+ expect(put.status).toBe(405);+ });+});diff --git a/tests/api-wallet-balances-handler.test.js b/tests/api-wallet-balances-handler.test.jsindex fe860744d..631f8271b 100644--- a/tests/api-wallet-balances-handler.test.js+++ b/tests/api-wallet-balances-handler.test.js@@ -15,6 +15,12 @@// 3. The two upstream failure shapes getBalances() raises stay mapped to// their intended statuses (503 not_configured with the missing key named,// 502 for a bad upstream) rather than collapsing into a 500.+// 4. A body that could not be READ keeps readJson()'s own status (415 for a+// non-JSON content-type, 413 for an oversize payload) instead of being+// reported as a field-validation fault, and a body that was read and+// rejected comes back as the platform's validation_error shape: one+// readable line plus a field-level `issues` array, not zod's raw+// multi-line JSON dump of every issue.import { Readable } from 'node:stream';import { describe, it, expect, beforeEach, vi } from 'vitest';@@ -41,13 +47,13 @@ vi.mock('../api/_lib/rate-limit.js', () => ({const handler = (await import('../api/wallet/balances.js')).default;-function makeReq({ method = 'POST', rawBody = null } = {}) {+function makeReq({ method = 'POST', rawBody = null, contentType = 'application/json' } = {}) {const req = Readable.from(rawBody == null ? [] : [Buffer.from(rawBody)]);req.method = method;req.url = '/api/wallet/balances';req.headers = {host: 'localhost',- ...(rawBody == null ? {} : { 'content-type': 'application/json' }),+ ...(rawBody == null ? {} : { 'content-type': contentType }),};return req;}@@ -68,10 +74,17 @@ function makeRes() {};}-async function call(body, { method = 'POST' } = {}) {+async function call(body, { method = 'POST', contentType } = {}) {const rawBody = body === undefined ? null : JSON.stringify(body);const res = makeRes();- await handler(makeReq({ method, rawBody }), res);+ await handler(makeReq({ method, rawBody, contentType }), res);+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };+}++// Bypasses JSON.stringify so a case can put arbitrary bytes on the wire.+async function callRaw(rawBody, { contentType = 'application/json' } = {}) {+ const res = makeRes();+ await handler(makeReq({ rawBody, contentType }), res);return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };}diff --git a/tests/api/robinhood-play-endpoints.test.js b/tests/api/robinhood-play-endpoints.test.jsnew file mode 100644index 000000000..f69080c25--- /dev/null+++ b/tests/api/robinhood-play-endpoints.test.js@@ -0,0 +1,244 @@+/**+ * GET /api/robinhood/coin-trades and GET /api/robinhood/play-worlds: the two+ * bridges between the Robinhood Chain firehose worker and the /play surfaces+ * (the in-world trading terminal's 5s trade poll, and the /worlds lobby tab).+ *+ * Pins the boundary behaviour that a degraded firehose must not break:+ * 1. Success path: real event shapes map to the card/chart contract.+ * 2. An event missing its `data` payload is dropped, not 500'd. Both handlers+ * used to throw a TypeError out of their filter/map, which the terminal+ * reads as a dead feed every 5s and the lobby swallows into an empty tab.+ * 3. A non-numeric timestamp nulls out instead of throwing a RangeError from+ * `toISOString()`; the client already treats a falsy timestamp as "now".+ * 4. A launch with no usable contract address is dropped, because its card+ * would seed a world from `undefined`.+ * 5. Malformed input gets a 400 JSON error, and an unreachable worker gets an+ * honest empty `configured: false` payload rather than fabricated data.+ *+ * fetch + the rate limiter are stubbed; the handlers themselves run unmodified.+ */++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ limits: {+ ...actual.limits,+ marketFeedIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ },+ clientIp: () => '203.0.113.11',+ };+});++// Synthetic addresses with hex letters in them, so the case-insensitivity test+// below is actually exercising something.+const COIN = '0xabcdef0123456789abcdef0123456789abcdef01';+const OTHER_COIN = '0xfedcba9876543210fedcba9876543210fedcba98';++function makeReq(url) {+ return { method: 'GET', url, headers: {}, on() {} };+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(n, v) {+ this.headers[String(n).toLowerCase()] = v;+ },+ getHeader(n) {+ return this.headers[String(n).toLowerCase()];+ },+ end(b) {+ this.body = b ? JSON.parse(b) : null;+ },+ };+}++/** Serve `events` from the worker's /recent snapshot, filtered by ?kind= like the real one. */+function feedReturning(events) {+ global.fetch = vi.fn(async (url) => {+ const kind = new URL(String(url), 'http://x').searchParams.get('kind') || 'all';+ const matching = kind === 'all' ? events : events.filter((ev) => ev?.kind === kind);+ return new Response(JSON.stringify({ events: matching }), { status: 200 });+ });+}++async function loadHandler(path) {+ vi.resetModules();+ return (await import(path)).default;+}++let savedFetch;+beforeEach(() => {+ savedFetch = global.fetch;+});+afterEach(() => {+ global.fetch = savedFetch;+});++describe('GET /api/robinhood/coin-trades', () => {+ it('maps the firehose trade events for one coin onto the chart contract', async () => {+ feedReturning([+ {+ kind: 'trade',+ data: {+ mint: COIN, tx: '0xaaa', timestamp: 1786860580, is_buy: true,+ price_usd: 1.5, sol_amount: 2, usd_amount: 3, user: '0xcafe',+ },+ },+ { kind: 'trade', data: { mint: OTHER_COIN, tx: '0xbbb', timestamp: 1786860581, is_buy: false } },+ { kind: 'launch', data: { mint: COIN } },+ ]);+ const handler = await loadHandler('../../api/robinhood/coin-trades.js');+ const res = makeRes();+ await handler(makeReq(`/api/robinhood/coin-trades?mint=${COIN}`), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.configured).toBe(true);+ expect(res.body.trades).toEqual([{+ tx: '0xaaa',+ timestamp: '2026-08-16T06:09:40.000Z',+ price_usd: 1.5,+ is_buy: true,+ sol_amount: 2,+ usd_amount: 3,+ user: '0xcafe',+ }]);+ });++ it('matches the coin case-insensitively, so a checksummed address still finds its tape', async () => {+ const checksummed = `0x${COIN.slice(2).toUpperCase()}`;+ feedReturning([{ kind: 'trade', data: { mint: checksummed, tx: '0xaaa', timestamp: 1786860580, is_buy: true } }]);+ const handler = await loadHandler('../../api/robinhood/coin-trades.js');+ const res = makeRes();+ await handler(makeReq(`/api/robinhood/coin-trades?mint=${COIN}`), res);++ expect(res.body.trades).toHaveLength(1);+ });++ it('drops an event with no data payload instead of 500ing the whole poll', async () => {+ feedReturning([+ { kind: 'trade' },+ { kind: 'trade', data: null },+ { kind: 'trade', data: { mint: COIN, tx: '0xok', timestamp: 1786860580, is_buy: true } },+ ]);+ const handler = await loadHandler('../../api/robinhood/coin-trades.js');+ const res = makeRes();+ await handler(makeReq(`/api/robinhood/coin-trades?mint=${COIN}`), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.trades.map((t) => t.tx)).toEqual(['0xok']);+ });++ it('nulls an unparseable timestamp rather than throwing out of toISOString()', async () => {+ feedReturning([{ kind: 'trade', data: { mint: COIN, tx: '0xaaa', timestamp: 'not-a-number', is_buy: true } }]);+ const handler = await loadHandler('../../api/robinhood/coin-trades.js');+ const res = makeRes();+ await handler(makeReq(`/api/robinhood/coin-trades?mint=${COIN}`), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.trades[0].timestamp).toBeNull();+ });++ it('keeps a missing price null instead of printing a real $0 trade', async () => {+ feedReturning([{ kind: 'trade', data: { mint: COIN, tx: '0xaaa', timestamp: 1786860580, is_buy: true, price_usd: null, usd_amount: null } }]);+ const handler = await loadHandler('../../api/robinhood/coin-trades.js');+ const res = makeRes();+ await handler(makeReq(`/api/robinhood/coin-trades?mint=${COIN}`), res);++ expect(res.body.trades[0].price_usd).toBeNull();+ expect(res.body.trades[0].usd_amount).toBeNull();+ expect(res.body.trades[0].sol_amount).toBe(0);+ });++ it('rejects a mint that is not an EVM address with a 400', async () => {+ feedReturning([]);+ const handler = await loadHandler('../../api/robinhood/coin-trades.js');+ for (const url of ['/api/robinhood/coin-trades', '/api/robinhood/coin-trades?mint=notanaddress']) {+ const res = makeRes();+ await handler(makeReq(url), res);+ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('invalid_mint');+ }+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('reports an unreachable worker as configured:false, never as fabricated trades', async () => {+ global.fetch = vi.fn(async () => {+ throw new Error('ECONNREFUSED');+ });+ const handler = await loadHandler('../../api/robinhood/coin-trades.js');+ const res = makeRes();+ await handler(makeReq(`/api/robinhood/coin-trades?mint=${COIN}`), res);++ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({ trades: [], configured: false });+ });+});++describe('GET /api/robinhood/play-worlds', () => {+ it('maps launch events onto the lobby card contract', async () => {+ feedReturning([{+ kind: 'launch',+ data: { mint: COIN, symbol: 'AAA', launchpad: 'test-pad', explorer_url: 'https://example.com/tx/1' },+ }]);+ const handler = await loadHandler('../../api/robinhood/play-worlds.js');+ const res = makeRes();+ await handler(makeReq('/api/robinhood/play-worlds'), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.data.worlds).toEqual([{+ token: COIN,+ symbol: 'AAA',+ image: null,+ members: 0,+ posts: 0,+ chain: 'robinhood-chain',+ launchpad: 'test-pad',+ explorer_url: 'https://example.com/tx/1',+ }]);+ });++ it('drops a payload-less event and an addressless launch instead of 500ing the lobby tab', async () => {+ feedReturning([+ { kind: 'launch' },+ { kind: 'launch', data: null },+ { kind: 'launch', data: {} },+ { kind: 'launch', data: { mint: 'not-an-address', symbol: 'BAD' } },+ { kind: 'launch', data: { mint: COIN, symbol: 'GOOD' } },+ ]);+ const handler = await loadHandler('../../api/robinhood/play-worlds.js');+ const res = makeRes();+ await handler(makeReq('/api/robinhood/play-worlds'), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.data.worlds.map((w) => w.symbol)).toEqual(['GOOD']);+ });++ it('honours the limit even when upstream ignores it', async () => {+ feedReturning(Array.from({ length: 12 }, (_, i) => ({+ kind: 'launch',+ data: { mint: `0x${String(i).padStart(40, '0')}`, symbol: `S${i}` },+ })));+ const handler = await loadHandler('../../api/robinhood/play-worlds.js');+ const res = makeRes();+ await handler(makeReq('/api/robinhood/play-worlds?limit=3'), res);++ expect(res.body.data.worlds).toHaveLength(3);+ });++ it('reports an unreachable worker as configured:false with an empty list', async () => {+ global.fetch = vi.fn(async () => new Response('nope', { status: 502 }));+ const handler = await loadHandler('../../api/robinhood/play-worlds.js');+ const res = makeRes();+ await handler(makeReq('/api/robinhood/play-worlds'), res);++ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({ data: { worlds: [] }, configured: false });+ expect(res.getHeader('cache-control')).toBe('no-store');+ });+});diff --git a/tests/api/three-query-guards.test.js b/tests/api/three-query-guards.test.jsnew file mode 100644index 000000000..d0f5b1a89--- /dev/null+++ b/tests/api/three-query-guards.test.js@@ -0,0 +1,177 @@+// Query-parameter boundary tests for api/three/[action].js.+//+// GET /api/three/stats?since_days=... (the aggregate window)+// GET /api/three/earnings?before=... (the earnings page cursor)+//+// Both params are interpolated into SQL as a Postgres cast (`::interval` and+// `::timestamptz`). Before these guards, a caller could send `since_days=abc` or+// `before=garbage` and get a 5xx back: the cast failed deep in the query instead+// of the value being rejected at the boundary. These tests pin the contract that+// a bad value is a typed 400 and a good one still reaches the ledger.+//+// The ledger reads and the session are mocked so the endpoint runs without a DB;+// the aggregate SQL itself is exercised by the token-payments tests.++import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++const getSessionUser = vi.fn();+const economyStats = vi.fn();+const creatorEarnings = vi.fn();+const listRewardsDistributions = vi.fn();+const getBalances = vi.fn();++vi.mock('../../api/_lib/auth.js', async (orig) => ({+ ...(await orig()),+ getSessionUser: (...a) => getSessionUser(...a),+}));+vi.mock('../../api/_lib/token/index.js', async (orig) => ({+ ...(await orig()),+ economyStats: (...a) => economyStats(...a),+ creatorEarnings: (...a) => creatorEarnings(...a),+ listRewardsDistributions: (...a) => listRewardsDistributions(...a),+}));+vi.mock('../../api/_lib/balances.js', async (orig) => ({+ ...(await orig()),+ getBalances: (...a) => getBalances(...a),+}));++let handler;++const WALLET = 'So11111111111111111111111111111111111111112';++function mockRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: '',+ _ended: false,+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; this._ended = true; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++function mockReq({ method = 'GET', url = '/' } = {}) {+ const r = Readable.from([]);+ r.method = method;+ r.url = url;+ r.headers = { origin: 'http://localhost:3000' };+ return r;+}++const get = async (url) => {+ const res = mockRes();+ await handler(mockReq({ url }), res);+ return res;+};++beforeAll(async () => {+ process.env.NODE_ENV = 'development';+ handler = (await import('../../api/three/[action].js')).default;+});++beforeEach(() => {+ vi.clearAllMocks();+ getSessionUser.mockResolvedValue(null);+ getBalances.mockResolvedValue({ tokens: [] });+ economyStats.mockResolvedValue({+ since: null,+ payment_count: 0,+ gross_atomics: '0',+ by_role: {},+ by_purpose: [],+ mint: null,+ decimals: null,+ });+ listRewardsDistributions.mockResolvedValue({+ total_reflected_atomics: '0',+ run_count: 0,+ items: [],+ });+ creatorEarnings.mockResolvedValue({+ total_atomics: '0',+ sale_count: 0,+ mint: null,+ decimals: null,+ items: [],+ next_cursor: null,+ });+});++describe('GET /api/three/stats?since_days=', () => {+ it('rejects a value that is not a finite number with a typed 400', async () => {+ for (const bad of ['notanumber', 'Infinity', '1e400', 'NaN']) {+ const res = await get(`/api/three/stats?since_days=${encodeURIComponent(bad)}`);+ expect(res.statusCode, bad).toBe(400);+ expect(res.json.error, bad).toBe('invalid_since_days');+ }+ // A rejected window must never reach the ledger query.+ expect(economyStats).not.toHaveBeenCalled();+ });++ it('passes a real window through to the ledger', async () => {+ const res = await get('/api/three/stats?since_days=7');+ expect(res.statusCode).toBe(200);+ expect(economyStats).toHaveBeenCalledWith({ sinceDays: 7 });+ });++ it('treats an omitted or empty value as no window', async () => {+ await get('/api/three/stats');+ expect(economyStats).toHaveBeenLastCalledWith({ sinceDays: null });+ await get('/api/three/stats?since_days=');+ expect(economyStats).toHaveBeenLastCalledWith({ sinceDays: null });+ });++ it('clamps an out-of-range window instead of overflowing the interval', async () => {+ await get('/api/three/stats?since_days=999999999999');+ expect(economyStats).toHaveBeenLastCalledWith({ sinceDays: 3650 });+ await get('/api/three/stats?since_days=-5');+ expect(economyStats).toHaveBeenLastCalledWith({ sinceDays: 1 });+ // Fractional days floor to whole days rather than failing the cast.+ await get('/api/three/stats?since_days=3.7');+ expect(economyStats).toHaveBeenLastCalledWith({ sinceDays: 3 });+ });+});++describe('GET /api/three/earnings?before=', () => {+ beforeEach(() => {+ getSessionUser.mockResolvedValue({ id: 'user-1', wallet_address: WALLET });+ });++ it('rejects a cursor that is not a timestamp with a typed 400', async () => {+ const res = await get('/api/three/earnings?before=garbage');+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('invalid_cursor');+ expect(creatorEarnings).not.toHaveBeenCalled();+ });++ it('passes a real cursor through to the ledger', async () => {+ const cursor = '2026-01-01T00:00:00.000Z';+ const res = await get(`/api/three/earnings?before=${encodeURIComponent(cursor)}`);+ expect(res.statusCode).toBe(200);+ expect(creatorEarnings).toHaveBeenCalledWith({+ sellerWallet: WALLET,+ limit: 50,+ before: cursor,+ });+ });++ it('treats an empty cursor as the first page and clamps the limit', async () => {+ await get('/api/three/earnings?before=&limit=99999');+ expect(creatorEarnings).toHaveBeenLastCalledWith({+ sellerWallet: WALLET,+ limit: 200,+ before: null,+ });+ });++ it('returns an empty ledger without a query when the account has no wallet', async () => {+ getSessionUser.mockResolvedValue({ id: 'user-2', wallet_address: null });+ const res = await get('/api/three/earnings');+ expect(res.statusCode).toBe(200);+ expect(res.json.items).toEqual([]);+ expect(creatorEarnings).not.toHaveBeenCalled();+ });+});diff --git a/tests/rider-pass.test.js b/tests/rider-pass.test.jsnew file mode 100644index 000000000..307f81460--- /dev/null+++ b/tests/rider-pass.test.js@@ -0,0 +1,347 @@+// The /api/rider/* pass surface: shared payment policy plus all four handlers.+//+// This surface shipped with three defects that only a test at the handler+// boundary catches:+// 1. /api/rider/check answered from the on-chain balance alone, so a wallet+// that BOUGHT a pass (and therefore sent its $THREE away) read as having+// none. rider_passes had a writer and no reader at all.+// 2. /api/rider/firebase read RIDER_FIREBASE_* env vars that api/_lib/env.js+// never declared, so it always returned 200 with an all-null config that+// crashes initializeApp() on the client.+// 3. /api/rider/webhook wrote one row per qualifying transfer, so a single+// batch transaction paying from two wallets tripped the UNIQUE index on+// tx_signature, 500'd, and sent Helius into a redelivery loop.++import { beforeEach, describe, expect, it, vi } from 'vitest';+import { qualifyingPayments, REQUIRED_AMOUNT } from '../api/_lib/rider.js';++const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const VAULT = 'ThreeVau1t1111111111111111111111111111111111';+const WALLET_A = 'So11111111111111111111111111111111111111112';+const WALLET_B = 'Sysvar1nstructions1111111111111111111111111';++// ── module doubles ──────────────────────────────────────────────────────────++const dbState = { rows: [], writes: [], fail: null };+vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ if (dbState.fail) throw dbState.fail;+ const q = (typeof strings === 'string' ? strings : strings.join('?')).toLowerCase();+ if (/insert into rider_passes/.test(q)) {+ dbState.writes.push({ wallet: values[0], amount: values[1], signature: values[2] });+ return [];+ }+ if (/from rider_passes/.test(q)) {+ return dbState.rows.filter((r) => r.wallet_address === values[0]);+ }+ return [];+ }),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authedReadIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '127.0.0.1',+}));++const rpcState = { accounts: [], fail: null };+vi.mock('../api/_lib/solana/connection.js', () => ({+ solanaConnection: () => ({+ getParsedTokenAccountsByOwner: async () => {+ if (rpcState.fail) throw rpcState.fail;+ return { value: rpcState.accounts };+ },+ }),+}));++const { default: checkHandler } = await import('../api/rider/check.js');+const { default: firebaseHandler } = await import('../api/rider/firebase.js');+const { default: infoHandler } = await import('../api/rider/info.js');+const { default: webhookHandler } = await import('../api/rider/webhook.js');++// ── http doubles ────────────────────────────────────────────────────────────++function makeRes() {+ return {+ statusCode: 0,+ payload: null,+ headers: {},+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ removeHeader(k) { delete this.headers[String(k).toLowerCase()]; },+ writeHead(code) { this.statusCode = code; return this; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ end(chunk) {+ if (chunk) {+ try { this.payload = JSON.parse(String(chunk)); } catch { this.payload = String(chunk); }+ }+ return this;+ },+ };+}++async function callGet(handler, path, query = {}) {+ const res = makeRes();+ await handler({ method: 'GET', url: path, headers: {}, query }, res);+ return res;+}++async function postWebhook(body, { authorization } = {}) {+ const res = makeRes();+ const headers = { 'content-type': 'application/json' };+ if (authorization) headers.authorization = authorization;+ await webhookHandler({ method: 'POST', url: '/api/rider/webhook', headers, body }, res);+ return res;+}++function tokenAccount(uiAmount) {+ return { account: { data: { parsed: { info: { tokenAmount: { uiAmount } } } } } };+}++beforeEach(() => {+ dbState.rows = [];+ dbState.writes = [];+ dbState.fail = null;+ rpcState.accounts = [];+ rpcState.fail = null;+ delete process.env.RIDER_VAULT_ADDRESS;+ delete process.env.RIDER_HELIUS_WEBHOOK_SECRET;+ delete process.env.RIDER_FIREBASE_API_KEY;+ delete process.env.RIDER_FIREBASE_PROJECT_ID;+ delete process.env.RIDER_FIREBASE_AUTH_DOMAIN;+});++// ── qualifyingPayments ──────────────────────────────────────────────────────++describe('qualifyingPayments', () => {+ const opts = { vaultAddress: VAULT, mint: MINT };++ it('accepts a transfer at the threshold and reports the sender', () => {+ const out = qualifyingPayments(+ [{ signature: 'sig1', tokenTransfers: [{ mint: MINT, toUserAccount: VAULT, fromUserAccount: WALLET_A, tokenAmount: REQUIRED_AMOUNT }] }],+ opts,+ );+ expect(out).toEqual([{ wallet: WALLET_A, amount: REQUIRED_AMOUNT, signature: 'sig1' }]);+ });++ it('credits every sender in one batch transaction', () => {+ const out = qualifyingPayments(+ [{+ signature: 'batch',+ tokenTransfers: [+ { mint: MINT, toUserAccount: VAULT, fromUserAccount: WALLET_A, tokenAmount: 9000 },+ { mint: MINT, toUserAccount: VAULT, fromUserAccount: WALLET_B, tokenAmount: 8000 },+ ],+ }],+ opts,+ );+ expect(out.map((p) => p.wallet).sort()).toEqual([WALLET_A, WALLET_B].sort());+ expect(out.every((p) => p.signature === 'batch')).toBe(true);+ });++ it('sums a wallet split across several legs of one transaction', () => {+ const out = qualifyingPayments(+ [{+ signature: 'split',+ tokenTransfers: [+ { mint: MINT, toUserAccount: VAULT, fromUserAccount: WALLET_A, tokenAmount: 5000 },+ { mint: MINT, toUserAccount: VAULT, fromUserAccount: WALLET_A, tokenAmount: 3000 },+ ],+ }],+ opts,+ );+ expect(out).toEqual([{ wallet: WALLET_A, amount: 8000, signature: 'split' }]);+ });++ it('drops short payments, other mints, other destinations and failed transactions', () => {+ const out = qualifyingPayments(+ [+ { signature: 'short', tokenTransfers: [{ mint: MINT, toUserAccount: VAULT, fromUserAccount: WALLET_A, tokenAmount: 7999 }] },+ { signature: 'other-mint', tokenTransfers: [{ mint: 'NotTheThreeMint1111111111111111111111111111', toUserAccount: VAULT, fromUserAccount: WALLET_A, tokenAmount: 50000 }] },+ { signature: 'other-dest', tokenTransfers: [{ mint: MINT, toUserAccount: WALLET_B, fromUserAccount: WALLET_A, tokenAmount: 50000 }] },+ { signature: 'failed', transactionError: { InstructionError: [0, 'Custom'] }, tokenTransfers: [{ mint: MINT, toUserAccount: VAULT, fromUserAccount: WALLET_A, tokenAmount: 50000 }] },+ { signature: 'no-sender', tokenTransfers: [{ mint: MINT, toUserAccount: VAULT, tokenAmount: 50000 }] },+ ],+ opts,+ );+ expect(out).toEqual([]);+ });++ it('returns nothing for a non-array body or an unset vault', () => {+ expect(qualifyingPayments(null, opts)).toEqual([]);+ expect(qualifyingPayments({ signature: 'x' }, opts)).toEqual([]);+ expect(qualifyingPayments([{ signature: 's', tokenTransfers: [{ mint: MINT, toUserAccount: VAULT, fromUserAccount: WALLET_A, tokenAmount: 50000 }] }], { vaultAddress: '', mint: MINT })).toEqual([]);+ });+});++// ── GET /api/rider/check ────────────────────────────────────────────────────++describe('GET /api/rider/check', () => {+ it('rejects a missing address', async () => {+ const res = await callGet(checkHandler, '/api/rider/check', {});+ expect(res.statusCode).toBe(400);+ expect(res.payload.error).toBe('validation_error');+ });++ it('rejects a repeated address param instead of throwing on it', async () => {+ // `?address=a&address=b` arrives as an array; calling .trim() on it used to+ // throw a TypeError and answer 500.+ const res = await callGet(checkHandler, '/api/rider/check', { address: ['nope', 'also-nope'] });+ expect(res.statusCode).toBe(400);+ expect(res.payload.error).toBe('validation_error');+ });++ it('rejects a non-base58 address', async () => {+ const res = await callGet(checkHandler, '/api/rider/check', { address: 'not-a-solana-address' });+ expect(res.statusCode).toBe(400);+ expect(res.payload.error_description).toMatch(/invalid Solana address/);+ });++ it('grants a holder pass from the on-chain balance', async () => {+ rpcState.accounts = [tokenAccount(1234.5)];+ const res = await callGet(checkHandler, '/api/rider/check', { address: WALLET_A });+ expect(res.statusCode).toBe(200);+ expect(res.payload).toMatchObject({ has_pass: true, holder_pass: true, paid_pass: false, balance: 1234.5, required_amount: REQUIRED_AMOUNT });+ });++ it('grants a paid pass to a wallet that spent its $THREE on the vault', async () => {+ rpcState.accounts = [];+ dbState.rows = [{ wallet_address: WALLET_A, amount_paid: '8000', tx_signature: 'sig1', created_at: new Date() }];+ const res = await callGet(checkHandler, '/api/rider/check', { address: WALLET_A });+ expect(res.statusCode).toBe(200);+ expect(res.payload).toMatchObject({ has_pass: true, holder_pass: false, paid_pass: true, balance: 0, amount_paid: 8000, tx_signature: 'sig1' });+ });++ it('reports no pass when neither source grants one', async () => {+ const res = await callGet(checkHandler, '/api/rider/check', { address: WALLET_A });+ expect(res.statusCode).toBe(200);+ expect(res.payload).toMatchObject({ has_pass: false, holder_pass: false, paid_pass: false });+ });++ it('answers 502 rather than a false negative when the RPC read fails', async () => {+ rpcState.fail = new Error('failed to fetch https://mainnet.helius-rpc.com/?api-key=secret');+ const res = await callGet(checkHandler, '/api/rider/check', { address: WALLET_A });+ expect(res.statusCode).toBe(502);+ expect(res.payload.error).toBe('rpc_unavailable');+ // The RPC URL carries the Helius key; it must never reach the caller.+ expect(JSON.stringify(res.payload)).not.toMatch(/api-key/);+ });++ it('still answers 200 on an RPC failure when a recorded payment already proves the pass', async () => {+ rpcState.fail = new Error('rpc down');+ dbState.rows = [{ wallet_address: WALLET_A, amount_paid: '8000', tx_signature: 'sig1', created_at: new Date() }];+ const res = await callGet(checkHandler, '/api/rider/check', { address: WALLET_A });+ expect(res.statusCode).toBe(200);+ expect(res.payload).toMatchObject({ has_pass: true, paid_pass: true, balance: null });+ });++ it('still answers 200 on a database failure when the balance already proves the pass', async () => {+ dbState.fail = new Error('db down');+ rpcState.accounts = [tokenAccount(10)];+ const res = await callGet(checkHandler, '/api/rider/check', { address: WALLET_A });+ expect(res.statusCode).toBe(200);+ expect(res.payload).toMatchObject({ has_pass: true, holder_pass: true, paid_pass: false });+ });+});++// ── GET /api/rider/info ─────────────────────────────────────────────────────++describe('GET /api/rider/info', () => {+ it('advertises the same amount the webhook accepts, and closes payments with no vault', async () => {+ const res = await callGet(infoHandler, '/api/rider/info');+ expect(res.statusCode).toBe(200);+ expect(res.payload).toMatchObject({ token_mint: MINT, token_symbol: '$THREE', required_amount: REQUIRED_AMOUNT, vault_address: null, accepting_payments: false });+ });++ it('opens payments once the vault is configured', async () => {+ process.env.RIDER_VAULT_ADDRESS = VAULT;+ const res = await callGet(infoHandler, '/api/rider/info');+ expect(res.payload).toMatchObject({ vault_address: VAULT, accepting_payments: true });+ });+});++// ── GET /api/rider/firebase ─────────────────────────────────────────────────++describe('GET /api/rider/firebase', () => {+ it('fails closed with 503 instead of serving an all-null config', async () => {+ const res = await callGet(firebaseHandler, '/api/rider/firebase');+ expect(res.statusCode).toBe(503);+ expect(res.payload.error).toBe('not_configured');+ });++ it('serves the configured client config', async () => {+ process.env.RIDER_FIREBASE_API_KEY = 'test-api-key';+ process.env.RIDER_FIREBASE_PROJECT_ID = 'rider-test';+ process.env.RIDER_FIREBASE_AUTH_DOMAIN = 'rider-test.firebaseapp.com';+ const res = await callGet(firebaseHandler, '/api/rider/firebase');+ expect(res.statusCode).toBe(200);+ expect(res.payload).toMatchObject({ apiKey: 'test-api-key', projectId: 'rider-test', authDomain: 'rider-test.firebaseapp.com', storageBucket: null });+ });+});++// ── POST /api/rider/webhook ─────────────────────────────────────────────────++describe('POST /api/rider/webhook', () => {+ const payment = (wallet, amount, signature) => ({+ signature,+ tokenTransfers: [{ mint: MINT, toUserAccount: VAULT, fromUserAccount: wallet, tokenAmount: amount }],+ });++ it('fails closed with 503 when the shared secret is unset', async () => {+ const res = await postWebhook([payment(WALLET_A, 8000, 'sig1')], { authorization: 'Bearer anything' });+ expect(res.statusCode).toBe(503);+ expect(dbState.writes).toEqual([]);+ });++ it('rejects a wrong or missing secret', async () => {+ process.env.RIDER_HELIUS_WEBHOOK_SECRET = 'right';+ process.env.RIDER_VAULT_ADDRESS = VAULT;+ expect((await postWebhook([], { authorization: 'Bearer wrong' })).statusCode).toBe(401);+ expect((await postWebhook([])).statusCode).toBe(401);+ expect(dbState.writes).toEqual([]);+ });++ it('reports 503 rather than a phantom success when the vault is unset', async () => {+ process.env.RIDER_HELIUS_WEBHOOK_SECRET = 'right';+ const res = await postWebhook([payment(WALLET_A, 8000, 'sig1')], { authorization: 'Bearer right' });+ expect(res.statusCode).toBe(503);+ expect(res.payload.error).toBe('not_configured');+ });++ it('rejects a body that is not an array', async () => {+ process.env.RIDER_HELIUS_WEBHOOK_SECRET = 'right';+ process.env.RIDER_VAULT_ADDRESS = VAULT;+ const res = await postWebhook({ not: 'an array' }, { authorization: 'Bearer right' });+ expect(res.statusCode).toBe(400);+ expect(res.payload.error).toBe('validation_error');+ });++ it('grants a pass per paying wallet, including two payers in one transaction', async () => {+ process.env.RIDER_HELIUS_WEBHOOK_SECRET = 'right';+ process.env.RIDER_VAULT_ADDRESS = VAULT;+ const res = await postWebhook(+ [{+ signature: 'batch',+ tokenTransfers: [+ { mint: MINT, toUserAccount: VAULT, fromUserAccount: WALLET_A, tokenAmount: 8000 },+ { mint: MINT, toUserAccount: VAULT, fromUserAccount: WALLET_B, tokenAmount: 12000 },+ ],+ }],+ { authorization: 'Bearer right' },+ );+ expect(res.statusCode).toBe(200);+ expect(res.payload).toEqual({ ok: true, granted: 2 });+ expect(dbState.writes.map((w) => w.wallet).sort()).toEqual([WALLET_A, WALLET_B].sort());+ });++ it('writes nothing for a payload with no qualifying transfer', async () => {+ process.env.RIDER_HELIUS_WEBHOOK_SECRET = 'right';+ process.env.RIDER_VAULT_ADDRESS = VAULT;+ const res = await postWebhook([payment(WALLET_A, 10, 'sig1')], { authorization: 'Bearer right' });+ expect(res.statusCode).toBe(200);+ expect(res.payload).toEqual({ ok: true, granted: 0 });+ expect(dbState.writes).toEqual([]);+ });+});diff --git a/tests/rss-announcements.test.js b/tests/rss-announcements.test.jsnew file mode 100644index 000000000..6f96bc951--- /dev/null+++ b/tests/rss-announcements.test.js@@ -0,0 +1,256 @@+// Coverage for the public RSS feed at /rss/announcements.xml (and its /rss.xml+// alias): api/rss/announcements.js plus the builder in api/_lib/rss-feed.js.+//+// HackerNoon auto-imports this feed, so a single malformed byte anywhere in it+// takes the whole syndication pipeline down rather than dropping one item. The+// regressions pinned here are exactly the inputs that used to do that:+// - a curated body_html containing a CDATA terminator, which closed the+// section early and corrupted every item after it;+// - a scraped post whose prose happened to spell the internal URL+// placeholder, which threw and returned a 500 for the entire feed;+// - a control character XML 1.0 forbids, which no escaping can rescue.+// Plus the handler contract: source selection, an unknown source, and the+// 500 boundary.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { XMLValidator } from 'fast-xml-parser';++const loaders = vi.hoisted(() => ({+ curated: null,+ archive: null,+}));++vi.mock('../api/_lib/rss-feed.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ loadCuratedItems: (...args) => (loaders.curated ? loaders.curated(...args) : actual.loadCuratedItems(...args)),+ loadAnnouncementItems: (...args) => (loaders.archive ? loaders.archive(...args) : actual.loadAnnouncementItems(...args)),+ };+});++const { buildRssXml, deriveSlug } = await import('../api/_lib/rss-feed.js');+const { default: handler } = await import('../api/rss/announcements.js');++function makeRes() {+ return {+ statusCode: 0,+ headers: {},+ body: '',+ ended: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(chunk) { this.body = chunk == null ? this.body : String(chunk); this.ended = true; return this; },+ write(chunk) { this.body += String(chunk); return this; },+ };+}++async function call(url, { method = 'GET', headers = {} } = {}) {+ const res = makeRes();+ await handler({ url, method, headers }, res);+ return res;+}++const CDATA_CLOSE = ']' + ']' + '>';+const BELL = String.fromCharCode(7);+const AT = new Date('2026-01-01T12:00:00Z');++const curatedItem = (over = {}) => ({+ id: 'launch-1',+ slug: 'launch-1',+ permalink: 'https://three.ws/news/launch-1',+ externalLink: '',+ externalSource: 'X',+ title: 'three.ws ships the forge',+ author: 'three.ws',+ summary: 'A summary of the launch.',+ bodyHtml: '<p>We shipped it.</p>',+ image: '',+ imageAlt: '',+ imageWidth: 0,+ imageHeight: 0,+ tags: ['launch'],+ timestamp: AT,+ published: true,+ ...over,+});++const archiveItem = (over = {}) => ({+ id: '1900000000000000001',+ account: 'trythreews',+ url: 'https://x.com/trythreews/status/1900000000000000001',+ text: 'A post long enough to clear the archive minimum length filter for the feed.',+ timestamp: AT,+ hasImage: false,+ hasVideo: false,+ ...over,+});++function expectWellFormed(xml) {+ const verdict = XMLValidator.validate(xml);+ expect(verdict, typeof verdict === 'object' ? JSON.stringify(verdict.err) : '').toBe(true);+}++beforeEach(() => {+ loaders.curated = null;+ loaders.archive = null;+});++describe('buildRssXml: malformed-output regressions', () => {+ it('keeps the feed parseable when a curated body carries a CDATA terminator', () => {+ const xml = buildRssXml({+ items: [curatedItem({ bodyHtml: `<p>use <code>if (a[b[c${CDATA_CLOSE}0)</code> here</p>` })],+ selfUrl: 'https://three.ws/rss/announcements.xml',+ source: 'curated',+ });+ expectWellFormed(xml);+ // The terminator survives as content, split across two CDATA sections.+ expect(xml).toContain(']]]]><![CDATA[>');+ });++ it('keeps the feed parseable when a scraped post spells the URL placeholder', () => {+ // Both spellings: ` URL5 ` is what the placeholder used to look like (prose+ // containing it threw and 500'd the whole feed), `<5>` is what it looks like+ // now. Neither may ever be mistaken for a real link, whichever form is in use.+ const xml = buildRssXml({+ items: [+ archiveItem({ id: '1', text: 'we shipped it, see URL5 for details and read the release notes' }),+ archiveItem({ id: '2', text: 'the build emits <5> as a marker, which the reader should show verbatim' }),+ ],+ selfUrl: 'https://three.ws/rss/announcements.xml?source=trythreews',+ source: 'trythreews',+ });+ expectWellFormed(xml);+ expect(xml).toContain('URL5');+ expect(xml).toContain('<5>');+ expect(xml).not.toContain('<a href="undefined"');+ });++ it('still linkifies real URLs and handles in scraped prose', () => {+ const xml = buildRssXml({+ items: [archiveItem({ text: 'built with @nichxbt, see https://three.ws/create for the full walkthrough' })],+ selfUrl: 'https://three.ws/rss/announcements.xml?source=trythreews',+ source: 'trythreews',+ });+ expectWellFormed(xml);+ expect(xml).toContain('<a href="https://three.ws/create" rel="noopener">https://three.ws/create</a>');+ expect(xml).toContain('<a href="https://x.com/nichxbt" rel="noopener">@nichxbt</a>');+ });++ it('drops control characters XML 1.0 forbids instead of emitting them', () => {+ const xml = buildRssXml({+ items: [curatedItem({ title: `Ti${BELL}tle`, bodyHtml: `<p>bo${BELL}dy</p>` })],+ selfUrl: 'https://three.ws/rss/announcements.xml',+ source: 'curated',+ });+ expectWellFormed(xml);+ expect(xml).not.toContain(BELL);+ expect(xml).toContain('<title>Title</title>');+ expect(xml).toContain('<p>body</p>');+ });++ it('escapes markup in titles and preserves astral characters', () => {+ const xml = buildRssXml({+ items: [curatedItem({ title: 'a <script> & an emoji 🚀' })],+ selfUrl: 'https://three.ws/rss/announcements.xml',+ source: 'curated',+ });+ expectWellFormed(xml);+ expect(xml).toContain('a <script> & an emoji 🚀');+ });++ it('builds a valid feed with no items at all', () => {+ const xml = buildRssXml({ items: [], selfUrl: 'https://three.ws/rss/announcements.xml', source: 'curated' });+ expectWellFormed(xml);+ expect(xml).not.toContain('<item>');+ });++ it('derives a URL-safe slug from a curated id', () => {+ expect(deriveSlug({ id: 't-1900000000000000001' })).toBe('1900000000000000001');+ expect(deriveSlug({ slug: 'Forge Ships!' })).toBe('forge-ships');+ expect(deriveSlug({})).toBe('item');+ });+});++describe('GET /rss/announcements.xml', () => {+ it('serves the curated feed as RSS with a cacheable, self-referential channel', async () => {+ loaders.curated = async () => [curatedItem()];+ const res = await call('/api/rss/announcements');++ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-type')).toBe('application/rss+xml; charset=utf-8');+ expect(res.getHeader('cache-control')).toContain('max-age=600');+ expectWellFormed(res.body);+ expect(res.body).toContain('<atom:link href="https://three.ws/rss/announcements.xml" rel="self"');+ expect(res.body).toContain('<title>three.ws ships the forge</title>');+ expect(res.body).toContain('<link>https://three.ws/news/launch-1</link>');+ });++ it('serves an account mirror and points the self link at that source', async () => {+ loaders.archive = async ({ source }) => {+ expect(source).toBe('trythreews');+ return [archiveItem()];+ };+ const res = await call('/api/rss/announcements?source=trythreews');++ expect(res.statusCode).toBe(200);+ expectWellFormed(res.body);+ expect(res.body).toContain('rss/announcements.xml?source=trythreews" rel="self"');+ expect(res.body).toContain('three.ws: three.ws updates');+ });++ it('maps ?source=archive onto every archived account', async () => {+ const seen = [];+ loaders.archive = async ({ source }) => { seen.push(source); return [archiveItem()]; };+ const res = await call('/api/rss/announcements?source=archive');++ expect(res.statusCode).toBe(200);+ expect(seen).toEqual(['all']);+ });++ it('accepts a source in any case', async () => {+ loaders.archive = async () => [archiveItem()];+ const res = await call('/api/rss/announcements?source=NichXBT');++ expect(res.statusCode).toBe(200);+ expect(res.body).toContain('rss/announcements.xml?source=nichxbt" rel="self"');+ });++ it('rejects an unknown source instead of silently serving the curated feed', async () => {+ loaders.curated = async () => { throw new Error('curated loader must not run'); };+ const res = await call('/api/rss/announcements?source=trythreewz');++ expect(res.statusCode).toBe(400);+ const body = JSON.parse(res.body);+ expect(body.error).toBe('unknown_source');+ expect(body.error_description).toContain('trythreewz');+ expect(res.getHeader('cache-control')).toBe('no-store');+ });++ it('rejects a non-GET method', async () => {+ const res = await call('/api/rss/announcements', { method: 'POST' });+ expect(res.statusCode).toBe(405);+ expect(JSON.parse(res.body).error).toBe('method_not_allowed');+ });++ it('answers a CORS preflight without building a feed', async () => {+ loaders.curated = async () => { throw new Error('preflight must not build a feed'); };+ const res = await call('/api/rss/announcements', { method: 'OPTIONS', headers: { origin: 'https://hackernoon.com' } });++ expect(res.statusCode).toBe(204);+ expect(res.getHeader('access-control-allow-origin')).toBe('*');+ });++ it('returns an uncached 500 with a support ref when the source data is unreadable', async () => {+ loaders.curated = async () => { throw new Error('ENOENT: items.json'); };+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const res = await call('/api/rss/announcements');+ errSpy.mockRestore();++ expect(res.statusCode).toBe(500);+ expect(res.getHeader('content-type')).toBe('text/plain; charset=utf-8');+ expect(res.getHeader('cache-control')).toBe('no-store');+ expect(res.body).toMatch(/^feed unavailable\. Quote ref \S+ to support\.$/);+ expect(res.body).not.toContain('items.json');+ });+});diff --git a/tests/signals-common.test.js b/tests/signals-common.test.jsnew file mode 100644index 000000000..645fa211d--- /dev/null+++ b/tests/signals-common.test.js@@ -0,0 +1,103 @@+/**+ * Shared helpers behind the signal-marketplace endpoints (api/signals/_common.js).+ *+ * These are small, but three of them sit directly on a money path: parseRowId+ * decides whether a caller typo becomes an honest 400 or a Postgres bigint cast+ * error surfaced as a 500, feedSlug is the public identity a paid feed is sold+ * and linked under, and loadOwnedAgent is the ownership gate every publisher and+ * subscriber write runs through.+ */++import { describe, it, expect } from 'vitest';+import { parseRowId, normNetwork, NETWORKS, slugify, feedSlug, loadOwnedAgent } from '../api/signals/_common.js';++function captureRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: '',+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ get json() {+ try { return JSON.parse(this._body); } catch { return null; }+ },+ };+}++describe('parseRowId', () => {+ it('accepts a positive integer id as a string or a number', () => {+ expect(parseRowId('1')).toBe(1);+ expect(parseRowId(' 42 ')).toBe(42);+ expect(parseRowId(9007199254740991)).toBe(9007199254740991);+ });++ it('rejects everything Postgres would reject as a bigint', () => {+ for (const bad of ['abc', '', ' ', '1.5', '-3', '0', '1e3', '12abc', '0x10', '9007199254740993']) {+ expect(parseRowId(bad), `expected ${JSON.stringify(bad)} to be rejected`).toBeNull();+ }+ });++ it('rejects non-scalar and empty inputs rather than stringifying them', () => {+ expect(parseRowId(null)).toBeNull();+ expect(parseRowId(undefined)).toBeNull();+ expect(parseRowId(true)).toBeNull();+ expect(parseRowId(['1'])).toBeNull();+ expect(parseRowId({ id: 1 })).toBeNull();+ });+});++describe('normNetwork', () => {+ it('passes through the two supported networks', () => {+ expect(normNetwork('mainnet')).toBe('mainnet');+ expect(normNetwork('devnet')).toBe('devnet');+ expect([...NETWORKS].sort()).toEqual(['devnet', 'mainnet']);+ });++ it('falls back to mainnet for anything else', () => {+ expect(normNetwork(null)).toBe('mainnet');+ expect(normNetwork('testnet')).toBe('mainnet');+ expect(normNetwork('DEVNET')).toBe('mainnet');+ });+});++describe('slugify', () => {+ it('kebabs arbitrary text and trims the edges', () => {+ expect(slugify('Alpha Trader 9000')).toBe('alpha-trader-9000');+ expect(slugify(' !!Ape Signals!! ')).toBe('ape-signals');+ });++ it('bounds the length and never returns an empty slug', () => {+ expect(slugify('x'.repeat(200)).length).toBe(40);+ expect(slugify('a'.repeat(200), 10)).toBe('a'.repeat(10));+ expect(slugify('!!!')).toBe('feed');+ expect(slugify(null)).toBe('feed');+ });+});++describe('feedSlug', () => {+ const agentId = 'b3e99b4f-13e8-4c00-9d59-b90e22bac9b4';++ it('binds the publisher name to the agent id so two feeds cannot collide', () => {+ expect(feedSlug('Alpha Trader', agentId, 'mainnet')).toBe('alpha-trader-b3e99b4f');+ expect(feedSlug('Alpha Trader', '11111111-2222-3333-4444-555555555555', 'mainnet'))+ .toBe('alpha-trader-11111111');+ });++ it('keeps the devnet feed on its own slug', () => {+ expect(feedSlug('Alpha Trader', agentId, 'devnet')).toBe('alpha-trader-b3e99b4f-dev');+ });+});++describe('loadOwnedAgent', () => {+ it('rejects a missing agent id with a 400 before it ever reaches the database', async () => {+ const res = captureRes();+ const result = await loadOwnedAgent({}, res, 'user-1', undefined);+ expect(result).toEqual({ error: true });+ expect(res.statusCode).toBe(400);+ expect(res.json).toMatchObject({ error: 'invalid_agent' });+ expect(res.getHeader('cache-control')).toBe('no-store');+ });+});diff --git a/tests/studio-assets-proxy.test.js b/tests/studio-assets-proxy.test.jsnew file mode 100644index 000000000..543c588ff--- /dev/null+++ b/tests/studio-assets-proxy.test.js@@ -0,0 +1,235 @@+// GET /api/studio-assets/<path>: the same-origin mirror of the loot-assets+// trait library the avatar studio loads from.+//+// Two properties earn a test here. First, the responses are `public,+// s-maxage=86400`, so the body must be a pure function of the path: if any+// request header could steer it, one poisoned request feeds every studio user+// for a day. Second, the handler serves attacker-reachable paths under our own+// origin, so the whitelist, the redirect pin, and the content-type gate are all+// load-bearing and every rejection must be a designed status rather than a+// throw.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const handler = (await import('../api/studio-assets/[...path].js')).default;++function mockReq(pathParts, { method = 'GET', headers = {} } = {}) {+ return {+ method,+ url: `/api/studio-assets/${Array.isArray(pathParts) ? pathParts.join('/') : pathParts}`,+ headers,+ query: { path: pathParts },+ };+}++function mockRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ ended: false,+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ removeHeader(k) { delete this.headers[k.toLowerCase()]; },+ end(b) { this.body = b; this.ended = true; this.writableEnded = true; },+ };+}++function upstreamResponse({ status = 200, body = '', type = 'application/json', headers = {}, url = 'https://m3-org.github.io/loot-assets/anata/female/manifest.json' } = {}) {+ const bag = new Map(+ Object.entries({ 'content-type': type, ...headers }).map(([k, v]) => [k.toLowerCase(), v]),+ );+ return {+ ok: status >= 200 && status < 300,+ status,+ url,+ headers: { get: (k) => (bag.has(k.toLowerCase()) ? bag.get(k.toLowerCase()) : null) },+ text: async () => body,+ arrayBuffer: async () => new Uint8Array(Buffer.from(body)).buffer,+ };+}++const MANIFEST = JSON.stringify({+ assetsLocation: 'https://m3-org.github.io/loot-assets/',+ traitsDirectory: '/anata/female/',+ animationPath: ['https://m3-org.github.io/loot-assets/animations/2_Idle.fbx'],+});++let fetchMock;++beforeEach(() => {+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('studio-assets mirror: success path', () => {+ it('serves a rewritten manifest that points every upstream URL back through the proxy', async () => {+ fetchMock.mockResolvedValue(upstreamResponse({ body: MANIFEST }));+ const res = mockRes();+ await handler(mockReq(['anata', 'female', 'manifest.json']), res);++ expect(fetchMock).toHaveBeenCalledWith(+ 'https://m3-org.github.io/loot-assets/anata/female/manifest.json',+ expect.objectContaining({ method: 'GET', redirect: 'follow' }),+ );+ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toBe('application/json');+ expect(res.headers['access-control-allow-origin']).toBe('*');+ expect(res.headers['cache-control']).toContain('s-maxage=86400');++ const out = JSON.parse(res.body);+ expect(out.assetsLocation).toBe('/api/studio-assets/');+ expect(out.animationPath[0]).toBe('/api/studio-assets/animations/2_Idle.fbx');+ expect(res.body).not.toContain('m3-org.github.io');+ });++ it('streams a binary trait through untouched', async () => {+ fetchMock.mockResolvedValue(+ upstreamResponse({ body: 'GLB-BYTES', type: 'model/gltf-binary', url: 'https://m3-org.github.io/loot-assets/anata/female/hair.vrm' }),+ );+ const res = mockRes();+ await handler(mockReq(['anata', 'female', 'hair.vrm']), res);++ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toBe('model/gltf-binary');+ expect(Buffer.isBuffer(res.body)).toBe(true);+ expect(res.body.toString()).toBe('GLB-BYTES');+ });++ it('produces a byte-identical body no matter what host headers the caller sends', async () => {+ fetchMock.mockResolvedValue(upstreamResponse({ body: MANIFEST }));+ const honest = mockRes();+ await handler(mockReq(['anata', 'female', 'manifest.json']), honest);++ fetchMock.mockResolvedValue(upstreamResponse({ body: MANIFEST }));+ const spoofed = mockRes();+ await handler(+ mockReq(['anata', 'female', 'manifest.json'], {+ headers: { host: 'evil.example', 'x-forwarded-host': 'evil.example', 'x-forwarded-proto': 'http' },+ }),+ spoofed,+ );++ expect(spoofed.body).toBe(honest.body);+ expect(spoofed.body).not.toContain('evil.example');+ });+});++describe('studio-assets mirror: rejected requests', () => {+ it('404s a path outside the mirrored trait library instead of proxying it', async () => {+ const res = mockRes();+ await handler(mockReq(['etc', 'passwd']), res);++ expect(res.statusCode).toBe(404);+ expect(JSON.parse(res.body).error).toBe('not_found');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('404s a double-encoded traversal that survives one decode pass', async () => {+ const res = mockRes();+ await handler(mockReq(['anata', '%2e%2e%2f%2e%2e%2fetc', 'passwd']), res);++ expect(res.statusCode).toBe(404);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('404s a path carrying a query or fragment that would truncate the upstream URL', async () => {+ for (const hostile of ['anata/female?x=1', 'anata/female#frag', 'anata\\..\\etc']) {+ const res = mockRes();+ await handler(mockReq(hostile), res);+ expect(res.statusCode).toBe(404);+ }+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('405s a write method', async () => {+ const res = mockRes();+ await handler(mockReq(['anata', 'female', 'manifest.json'], { method: 'POST' }), res);++ expect(res.statusCode).toBe(405);+ expect(JSON.parse(res.body).error).toBe('method_not_allowed');+ expect(fetchMock).not.toHaveBeenCalled();+ });+});++describe('studio-assets mirror: upstream failures', () => {+ it('answers 404 when the mirror does not have the asset', async () => {+ fetchMock.mockResolvedValue(upstreamResponse({ status: 404, body: 'nope' }));+ const res = mockRes();+ await handler(mockReq(['anata', 'female', 'missing.json']), res);++ expect(res.statusCode).toBe(404);+ expect(JSON.parse(res.body).error).toBe('not_found');+ });++ it('answers 502 rather than blaming three.ws for a mirror 500', async () => {+ fetchMock.mockResolvedValue(upstreamResponse({ status: 500, body: 'boom' }));+ const res = mockRes();+ await handler(mockReq(['anata', 'female', 'manifest.json']), res);++ expect(res.statusCode).toBe(502);+ expect(JSON.parse(res.body).error).toBe('upstream_error');+ });++ it('answers 502 when the mirror is unreachable', async () => {+ fetchMock.mockRejectedValue(new Error('ETIMEDOUT'));+ const res = mockRes();+ await handler(mockReq(['anata', 'female', 'manifest.json']), res);++ expect(res.statusCode).toBe(502);+ expect(JSON.parse(res.body).error).toBe('upstream_unreachable');+ });++ it('refuses to serve bytes a redirect fetched from off the asset library', async () => {+ fetchMock.mockResolvedValue(+ upstreamResponse({ body: 'pwned', url: 'https://evil.example/payload' }),+ );+ const res = mockRes();+ await handler(mockReq(['anata', 'female', 'manifest.json']), res);++ expect(res.statusCode).toBe(502);+ expect(res.body).not.toContain('pwned');+ });++ it('refuses to serve an HTML document under the three.ws origin', async () => {+ fetchMock.mockResolvedValue(+ upstreamResponse({ body: '<script>alert(1)</script>', type: 'text/html; charset=utf-8' }),+ );+ const res = mockRes();+ await handler(mockReq(['anata', 'female', 'manifest.json']), res);++ expect(res.statusCode).toBe(502);+ expect(res.body).not.toContain('<script>');+ });+});++describe('studio-assets mirror: HEAD', () => {+ it('omits the compressed upstream length instead of understating the body', async () => {+ fetchMock.mockResolvedValue(+ upstreamResponse({ body: MANIFEST, headers: { 'content-length': '2445', 'content-encoding': 'gzip' } }),+ );+ const res = mockRes();+ await handler(mockReq(['anata', 'female', 'manifest.json'], { method: 'HEAD' }), res);++ expect(res.statusCode).toBe(200);+ expect(res.headers['content-length']).toBeUndefined();+ expect(res.body).toBeUndefined();+ });++ it('forwards the length of an uncompressed binary asset', async () => {+ fetchMock.mockResolvedValue(+ upstreamResponse({ body: '', type: 'model/gltf-binary', headers: { 'content-length': '81920' } }),+ );+ const res = mockRes();+ await handler(mockReq(['anata', 'female', 'hair.vrm'], { method: 'HEAD' }), res);++ expect(res.statusCode).toBe(200);+ expect(res.headers['content-length']).toBe('81920');+ });+});