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 RSS, signals, SDP and retexture handlers and record the CoinGecko listing state
nirholas33c3734aebfa
diff --git a/api/_lib/rider.js b/api/_lib/rider.jsnew file mode 100644index 000000000..046fbc8eb--- /dev/null+++ b/api/_lib/rider.js@@ -0,0 +1,65 @@+// Rider pass — shared policy for the /api/rider/* surface.+//+// A rider pass is granted two ways, and every reader has to honor both:+// 1. Holding $THREE in the wallet (a holder pass), read on-chain.+// 2. Paying REQUIRED_AMOUNT $THREE into the rider vault, which the Helius+// webhook records in `rider_passes`. A payer no longer holds those tokens,+// so a balance read on its own revokes the pass the vault just sold.+//+// REQUIRED_AMOUNT used to be a literal in both info.js (the advertised price)+// and webhook.js (the accepted price). Two copies of one price is a single edit+// away from advertising a pass the webhook refuses to grant.++export const REQUIRED_AMOUNT = 8000;++/**+ * Reduce a Helius enhanced-transaction batch to the vault payments that earn a+ * pass, one entry per paying wallet.+ *+ * Helius delivers an array of enhanced transactions, each with a `tokenTransfers`+ * array. A single transaction can carry $THREE from more than one wallet (a batch+ * or aggregator transfer), and a wallet can appear in several transfers of the+ * same transaction, so the qualifying legs are summed per wallet per transaction+ * before the threshold is applied. Anything else in the payload — other mints,+ * other destinations, failed transactions, transfers with no sender — is dropped.+ *+ * @param {unknown} txns Parsed webhook body.+ * @param {object} opts+ * @param {string} opts.vaultAddress Owner account that must receive the transfer.+ * @param {string} opts.mint Mint that must be transferred.+ * @param {number} [opts.requiredAmount] Minimum whole tokens per wallet per transaction.+ * @returns {Array<{ wallet: string, amount: number, signature: string }>}+ */+export function qualifyingPayments(txns, { vaultAddress, mint, requiredAmount = REQUIRED_AMOUNT }) {+ if (!Array.isArray(txns) || !vaultAddress || !mint) return [];++ // wallet -> winning payment. A wallet that pays in two transactions of one+ // batch keeps the larger payment, so the row records what actually bought the+ // pass rather than whichever leg happened to land last.+ const best = new Map();++ for (const txn of txns) {+ if (!txn || typeof txn !== 'object') continue;+ if (txn.transactionError) continue;+ const signature = typeof txn.signature === 'string' ? txn.signature : '';+ if (!signature) continue;++ const perWallet = new Map();+ for (const t of Array.isArray(txn.tokenTransfers) ? txn.tokenTransfers : []) {+ if (!t || t.mint !== mint || t.toUserAccount !== vaultAddress) continue;+ const wallet = typeof t.fromUserAccount === 'string' ? t.fromUserAccount : '';+ if (!wallet) continue;+ const amount = Number(t.tokenAmount);+ if (!Number.isFinite(amount) || amount <= 0) continue;+ perWallet.set(wallet, (perWallet.get(wallet) ?? 0) + amount);+ }++ for (const [wallet, amount] of perWallet) {+ if (amount < requiredAmount) continue;+ const prior = best.get(wallet);+ if (!prior || amount > prior.amount) best.set(wallet, { wallet, amount, signature });+ }+ }++ return [...best.values()];+}diff --git a/api/_lib/rss-feed.js b/api/_lib/rss-feed.jsindex 7fa9780b4..60cff706a 100644--- a/api/_lib/rss-feed.js+++ b/api/_lib/rss-feed.js@@ -160,8 +160,39 @@ function cleanText(s) {.trim();}+// Characters XML 1.0 forbids outright (§2.2): the C0 controls other than tab,+// LF and CR, the two non-characters at the top of the BMP, and any unpaired+// surrogate. Escaping cannot rescue them (`` is just as illegal as a raw+// bell), so they are dropped. One of these anywhere in a title or body makes+// the WHOLE feed unparseable for every reader downstream, which is how a+// single stray byte in one scraped post takes the syndication feed offline.+const TAB = 0x09;+const LINE_FEED = 0x0a;+const CARRIAGE_RETURN = 0x0d;+const FIRST_PRINTABLE = 0x20;+const SURROGATE_START = 0xd800;+const SURROGATE_END = 0xdfff;+const BMP_NONCHARS = new Set([0xfffe, 0xffff]);++function isValidXmlCodePoint(cp) {+ if (cp === TAB || cp === LINE_FEED || cp === CARRIAGE_RETURN) return true;+ if (cp < FIRST_PRINTABLE) return false;+ // Iterating by code point pairs real astral characters up already, so any+ // surrogate that reaches here is by definition unpaired.+ if (cp >= SURROGATE_START && cp <= SURROGATE_END) return false;+ return !BMP_NONCHARS.has(cp);+}++function stripInvalidXmlChars(s) {+ let out = '';+ for (const ch of String(s)) {+ if (isValidXmlCodePoint(ch.codePointAt(0))) out += ch;+ }+ return out;+}+function escapeXml(s) {- return String(s)+ return stripInvalidXmlChars(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')@@ -173,6 +204,15 @@ function escapeAttr(s) {return escapeXml(s);}+// CDATA carries markup verbatim, so the one sequence it cannot contain is its+// own terminator. Curated items ship hand-authored HTML, and a code sample+// that happens to close two brackets before a `>` would otherwise end the+// section early and corrupt every item after it. The canonical fix: close,+// emit the `]]>` as escaped text in a fresh section, and continue.+function cdata(s) {+ return stripInvalidXmlChars(s).split(']]>').join(']]]]><![CDATA[>');+}+function rfc822(date) {return date.toUTCString();}diff --git a/api/robinhood/coin-trades.js b/api/robinhood/coin-trades.jsindex 946f6a68d..71bc678a3 100644--- a/api/robinhood/coin-trades.js+++ b/api/robinhood/coin-trades.js@@ -15,22 +15,47 @@// clearly-flagged payload rather than fabricating trades — the in-world HUD// renders its designed empty state instead of a fake feed.-import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';const FEED_URL = process.env.ROBINHOOD_FEED_URL || 'http://localhost:8788';const EVM_ADDR_RE = /^0x[a-fA-F0-9]{40}$/;const UPSTREAM_TIMEOUT_MS = 3000;+// The firehose is a network boundary, so nothing it returns is trusted. One+// event that lost its `data` payload used to throw a TypeError out of the+// filter and 500 the whole poll, which the in-world terminal reads as a dead+// feed every 5 seconds; a timestamp the upstream wrote as a string threw a+// RangeError out of `toISOString()` the same way. Both are coerced now: a+// malformed event is dropped or nulled, the rest of the tape still renders.+function isTradeEvent(ev) {+ return !!ev && ev.kind === 'trade' && !!ev.data && typeof ev.data === 'object';+}++function isoTimestamp(seconds) {+ const n = Number(seconds);+ if (!Number.isFinite(n) || n <= 0) return null;+ const at = new Date(n * 1000);+ return Number.isNaN(at.getTime()) ? null : at.toISOString();+}++// `Number(null) === 0`, so a missing price would otherwise render as a real $0+// print on the chart. Only a genuinely finite value survives.+function finiteOr(value, fallback) {+ if (value === null || value === undefined || value === '') return fallback;+ const n = Number(value);+ return Number.isFinite(n) ? n : fallback;+}+function toChartTrade(ev) {const d = ev.data;return {- tx: d.tx || d.tx_signature || d.signature,- timestamp: new Date((d.timestamp || 0) * 1000).toISOString(),- price_usd: d.price_usd ?? null,+ tx: d.tx || d.tx_signature || d.signature || '',+ timestamp: isoTimestamp(d.timestamp),+ price_usd: finiteOr(d.price_usd, null),is_buy: d.is_buy === true,- sol_amount: d.sol_amount ?? d.amount ?? 0,- usd_amount: d.usd_amount ?? d.value_usd ?? null,+ sol_amount: finiteOr(d.sol_amount ?? d.amount, 0),+ usd_amount: finiteOr(d.usd_amount ?? d.value_usd, null),user: d.user || d.trader || '',};}@@ -51,8 +76,13 @@ export default wrap(async (req, res) => {const rawLimit = Number(params.get('limit') || '100');const limit = Math.min(200, Math.max(1, Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 100));+ // A caller-supplied address that is not an EVM address is a client bug, not+ // a quiet market: say so with a 4xx the way the pump.fun coin-trades path+ // does, rather than an empty 200 that reads as "this coin has no trades".+ // The in-world terminal only routes here for addresses that already match+ // this shape (src/game/chart-screen.js), so no live caller sees it.if (!EVM_ADDR_RE.test(mint)) {- return json(res, 200, { trades: [], configured: true, error: 'invalid_mint' }, { 'cache-control': 'no-store' });+ return error(res, 400, 'invalid_mint', 'mint must be a 0x-prefixed EVM contract address');}let upstream;@@ -73,7 +103,7 @@ export default wrap(async (req, res) => {const events = Array.isArray(body?.events) ? body.events : [];const mintLower = mint.toLowerCase();const trades = events- .filter((ev) => ev.kind === 'trade' && (ev.data.mint || '').toLowerCase() === mintLower)+ .filter((ev) => isTradeEvent(ev) && String(ev.data.mint || '').toLowerCase() === mintLower).slice(0, limit).map(toChartTrade);diff --git a/api/robinhood/play-worlds.js b/api/robinhood/play-worlds.jsindex a38f68226..8e67086d3 100644--- a/api/robinhood/play-worlds.js+++ b/api/robinhood/play-worlds.js@@ -18,6 +18,19 @@ import { limits, clientIp } from '../_lib/rate-limit.js';const FEED_URL = process.env.ROBINHOOD_FEED_URL || 'http://localhost:8788';const UPSTREAM_TIMEOUT_MS = 3000;+const EVM_ADDR_RE = /^0x[a-fA-F0-9]{40}$/;++// The firehose is a network boundary. An event that lost its `data` payload+// used to throw a TypeError out of this map and 500 the endpoint, and the+// lobby swallows a non-ok response (src/worlds-lobby.js), so the whole tab+// vanished with no error anywhere the user could see. A launch with no usable+// contract address is dropped for the same reason: its card would seed a world+// from `undefined` and land the visitor nowhere.+function launchAddress(ev) {+ if (!ev || ev.kind !== 'launch' || !ev.data || typeof ev.data !== 'object') return null;+ const mint = typeof ev.data.mint === 'string' ? ev.data.mint.trim() : '';+ return EVM_ADDR_RE.test(mint) ? mint : null;+}export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;@@ -45,16 +58,18 @@ export default wrap(async (req, res) => {const body = await upstream.json().catch(() => null);const events = Array.isArray(body?.events) ? body.events : [];const worlds = events- .filter((ev) => ev.kind === 'launch')- .map((ev) => ({- token: ev.data.mint,+ .map((ev) => ({ ev, token: launchAddress(ev) }))+ .filter((row) => row.token !== null)+ .slice(0, limit)+ .map(({ ev, token }) => ({+ token,symbol: ev.data.symbol || null,image: null, // no off-chain metadata service on Robinhood Chain yetmembers: 0,posts: 0,chain: 'robinhood-chain',- launchpad: ev.data.launchpad,- explorer_url: ev.data.explorer_url,+ launchpad: ev.data.launchpad ?? null,+ explorer_url: ev.data.explorer_url ?? null,}));return json(res, 200, { data: { worlds }, configured: true }, { 'cache-control': 'public, max-age=15, s-maxage=30' });diff --git a/api/sdp/[...path].js b/api/sdp/[...path].jsindex 45a5eb8d2..24b0a020f 100644--- a/api/sdp/[...path].js+++ b/api/sdp/[...path].js@@ -43,13 +43,41 @@ function joinPath(parts) {return String(parts || '');}+// True when the request actually carries a body. Content-Length alone is not+// enough: an HTTP/2 or streaming client sends its body chunked with no such+// header, and the Cloud Run server's body-parser may already have consumed it+// onto req.body. Reading only on Content-Length forwarded those calls upstream+// with no body at all, so SDP answered with a validation error for a payload+// the caller did send.+function hasRequestBody(req) {+ if (Number(req.headers['content-length'] || 0) > 0) return true;+ if (req.headers['transfer-encoding']) return true;+ const parsed = req.body;+ if (parsed == null) return false;+ if (typeof parsed === 'string' || Buffer.isBuffer(parsed)) return parsed.length > 0;+ if (typeof parsed === 'object') return Object.keys(parsed).length > 0;+ return false;+}++// 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+// 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;++function relayContentType(contentType) {+ const ct = contentType || 'text/plain; charset=utf-8';+ return MARKUP_CONTENT_TYPE.test(ct) ? 'text/plain; charset=utf-8' : ct;+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,PUT,PATCH,DELETE,OPTIONS', credentials: false })) return;if (!methodGuard(req, res, ALLOWED_METHODS)) return;const path = decodeURIComponent(joinPath(req.query?.path)).replace(/^\/+/, '');if (!isSdpAllowedPath(path)) {- return error(res, 404, 'not_found', `unknown Solana Developer Platform route: ${path}`);+ return error(res, 404, 'not_found', `unknown Solana Developer Platform route: ${path.slice(0, 120)}`);}const rl = await limits.sdpIp(clientIp(req));@@ -87,8 +115,7 @@ export default wrap(async (req, res) => {let body;if (req.method !== 'GET' && req.method !== 'HEAD') {// Empty body is valid for some POSTs (e.g. collect/refresh actions).- const cl = req.headers['content-length'];- if (cl && Number(cl) > 0) body = await readJson(req);+ if (hasRequestBody(req)) body = await readJson(req);}const upstream = await sdpRequest(path, { method: req.method, query, body, headers });@@ -99,7 +126,7 @@ export default wrap(async (req, res) => {const extra = upstream.traceId ? { 'x-sdp-trace-id': upstream.traceId } : {};if (typeof upstream.body === 'string') {res.statusCode = upstream.status;- res.setHeader('content-type', upstream.contentType || 'text/plain; charset=utf-8');+ res.setHeader('content-type', relayContentType(upstream.contentType));res.setHeader('cache-control', 'no-store');for (const [k, v] of Object.entries(extra)) res.setHeader(k, v);return res.end(upstream.body);diff --git a/api/signals/_common.js b/api/signals/_common.jsindex c7f8aafbe..317f58be1 100644--- a/api/signals/_common.js+++ b/api/signals/_common.js@@ -33,6 +33,23 @@ export async function loadOwnedAgent(req, res, userId, agentId) {return { row, meta: { ...(row.meta || {}) } };}+/**+ * Parse a `bigserial` row id (signal_feeds.id, signal_subscriptions.id).+ * Returns a positive safe integer, or null when the input is not one.+ *+ * Handing a non-numeric id straight to Postgres turns a caller typo into an+ * `invalid input syntax for type bigint` 500 with a Sentry alert behind it,+ * when the honest answer is a 400. Every endpoint that reads an id off the+ * query string or a JSON body runs it through here first.+ */+export function parseRowId(value) {+ if (value == null || typeof value === 'boolean' || Array.isArray(value)) return null;+ const raw = String(value).trim();+ if (!/^\d+$/.test(raw)) return null;+ const n = Number(raw);+ return Number.isSafeInteger(n) && n > 0 ? n : null;+}+/** Kebab slug from arbitrary text, bounded. */export function slugify(text, max = 40) {return String(text || '')diff --git a/api/signals/feeds.js b/api/signals/feeds.jsindex 1dcf332a0..c186e5f17 100644--- a/api/signals/feeds.js+++ b/api/signals/feeds.js@@ -1,16 +1,16 @@/**- * Signal feeds — the publisher's CRUD surface.+ * Signal feeds: the publisher's CRUD surface.** GET /api/signals/feeds list the caller's feeds* GET /api/signals/feeds?agent_id=&network= one agent's feed + publish eligibility* POST /api/signals/feeds create / update a feed (verified gate)* POST /api/signals/feeds { id, status } pause / resume- * DELETE /api/signals/feeds?id= pause (soft — keeps signal history)+ * DELETE /api/signals/feeds?id= pause (soft, keeps signal history)** Publishing is gated on a REAL, verified on-chain track record: the publisher* agent must clear api/_lib/trader-stats.js's `verified` badge (12+ closed trades,* 5+ coins, ≤40% churn, positive realized SOL). An unproven wallet gets a 403 with- * the exact thresholds it still has to meet — sellers can never self-declare edge.+ * the exact thresholds it still has to meet. Sellers can never self-declare edge.*/import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';@@ -18,7 +18,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';import { sql } from '../_lib/db.js';import { publisherMetrics } from '../_lib/signal-engine.js';-import { requireUser, loadOwnedAgent, normNetwork, NETWORKS, feedSlug } from './_common.js';+import { requireUser, loadOwnedAgent, normNetwork, NETWORKS, feedSlug, parseRowId } from './_common.js';const MAX_USDC = 1000; // sane per-signal / per-epoch ceilingconst MIN_EPOCH_SECONDS = 3600; // 1 hour@@ -106,8 +106,8 @@ export default wrap(async (req, res) => {// ── DELETE (soft pause) ─────────────────────────────────────────────────────if (req.method === 'DELETE') {- const id = new URL(req.url, 'http://x').searchParams.get('id');- if (!id) return error(res, 400, 'invalid_id', 'id required');+ const id = parseRowId(new URL(req.url, 'http://x').searchParams.get('id'));+ if (!id) return error(res, 400, 'invalid_id', 'numeric feed id required');const [row] = await sql`update signal_feeds set status = 'paused', updated_at = now()where id = ${id} and owner_user_id = ${userId} returning id@@ -122,10 +122,12 @@ export default wrap(async (req, res) => {// Pause / resume an existing feed.if (body.id && body.status && !body.agent_id) {+ const feedId = parseRowId(body.id);+ if (!feedId) return error(res, 400, 'invalid_id', 'numeric feed id required');const status = body.status === 'active' ? 'active' : 'paused';const [row] = await sql`update signal_feeds set status = ${status}, updated_at = now()- where id = ${body.id} and owner_user_id = ${userId} returning *+ where id = ${feedId} and owner_user_id = ${userId} returning *`;if (!row) return error(res, 404, 'not_found', 'feed not found');return json(res, 200, { feed: shapeFeedRow(row) });@@ -138,7 +140,7 @@ export default wrap(async (req, res) => {if (owned.error) return;const payoutAddress = owned.meta.solana_address;- if (!payoutAddress) return error(res, 409, 'wallet_preparing', 'agent wallet is still being provisioned — try again shortly');+ if (!payoutAddress) return error(res, 409, 'wallet_preparing', 'agent wallet is still being provisioned, try again shortly');// THE GATE: only a verified track record may publish.const metrics = await publisherMetrics(body.agent_id, network).catch(() => null);diff --git a/api/signals/subscribe.js b/api/signals/subscribe.jsindex 640ab98a1..304f0cb0d 100644--- a/api/signals/subscribe.js+++ b/api/signals/subscribe.js@@ -1,18 +1,18 @@/**- * Signal subscriptions — the follower's control surface.+ * Signal subscriptions: the follower's control surface.** GET /api/signals/subscribe list the caller's subscriptions* POST /api/signals/subscribe create / update a subscription* POST /api/signals/subscribe { id, status } pause / resume / stop* POST /api/signals/subscribe { id, killed:true } INSTANT kill (no further pay/trade)* POST /api/signals/subscribe { id, action:'sync' } deliver pending now (owner-triggered)- * DELETE /api/signals/subscribe?id= stop (soft — keeps delivery history)+ * DELETE /api/signals/subscribe?id= stop (soft, keeps delivery history)** A subscriber agent's own custodial wallet pays the x402 USDC and signs the* mirror, so a subscription is owner-authenticated and scoped to an agent the* caller owns. `mode:'simulate'` mirrors WITHOUT paying or trading (trust-building);* `live` does both within the agent's spend policy. `killed` halts everything the- * instant it is set — the kill is honoured before any payment or trade fires.+ * instant it is set: the kill is honoured before any payment or trade fires.*/import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';@@ -105,7 +105,7 @@ export default wrap(async (req, res) => {// ── Mutations on an existing subscription (status / kill / sync) ────────────if (body.id && !body.feed_id) {- // Instant kill — the halt path, takes precedence.+ // Instant kill: the halt path, takes precedence.if (body.killed != null) {const killed = body.killed === true || body.killed === 'true';const [row] = await sql`diff --git a/api/studio/retexture-region.js b/api/studio/retexture-region.jsindex 41a4a9e1e..e4f939d7b 100644--- a/api/studio/retexture-region.js+++ b/api/studio/retexture-region.js@@ -59,19 +59,28 @@ async function resolveUser(req, scope) {return null;}+const UNCONFIGURED_HINT =+ 'Region retexture requires the GCP texture worker. Set GCP_RECONSTRUCTION_KEY and GCP_TEXTURE_URL.';++// The lane needs BOTH the shared worker bearer secret and the texture worker's+// base URL. Check them together so submit and status give the same 501 with the+// same code, rather than one 501 from the missing key and a different failure+// deeper in the provider from the missing URL.function getProviderOr501(res) {+ let provider;try {- return createRegenProvider();+ provider = createRegenProvider();} catch (err) {- error(- res,- 501,- 'region_retex_unconfigured',- 'Region retexture requires the GCP texture worker. Set GCP_RECONSTRUCTION_KEY and GCP_TEXTURE_URL.',- { reason: err.message },- );+ error(res, 501, 'region_retex_unconfigured', UNCONFIGURED_HINT, { reason: err.message });return null;}+ if (!provider.supportsMode(MODE)) {+ error(res, 501, 'region_retex_unconfigured', UNCONFIGURED_HINT, {+ reason: 'GCP_TEXTURE_URL is not set',+ });+ return null;+ }+ return provider;}// Re-validate that an opaque job token points at THE worker we configured, not@@ -145,16 +154,26 @@ async function handleStatus(req, res) {const userId = await resolveUser(req, 'avatars:read');if (!userId) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');+ // Polling is cheap for the client and an outbound worker fetch for us, so it+ // gets the same ceiling the sibling forge status endpoints use.+ const rl = await limits.mcp3dStatus(userId);+ if (!rl.success) return rateLimited(res, rl, 'too many status polls — slow down');+const url = new URL(req.url, 'http://x');const token = url.searchParams.get('job');if (!token) return error(res, 400, 'invalid_request', 'job token required');- if (!tokenTargetsOurWorker(token)) {- return error(res, 400, 'invalid_job', 'job token is malformed or not recognized');- }+ // Configuration is checked BEFORE the token shape: tokenTargetsOurWorker+ // compares against GCP_TEXTURE_URL, so on a deployment without the texture+ // worker every token fails it and a legitimately-issued job would be reported+ // as "malformed" instead of the honest 501 the submit path already returns.const provider = getProviderOr501(res);if (!provider) return;+ if (!tokenTargetsOurWorker(token)) {+ return error(res, 400, 'invalid_job', 'job token is malformed or not recognized');+ }+let update;try {update = await provider.status(token);diff --git a/docs/coingecko-listing-update-2026-08.md b/docs/coingecko-listing-update-2026-08.mdnew file mode 100644index 000000000..82e731640--- /dev/null+++ b/docs/coingecko-listing-update-2026-08.md@@ -0,0 +1,261 @@+# CoinGecko listing update: $THREE market additions (August 2026)++Working notes and post drafts for the CoinGecko "New Listings on Exchanges/New Market Addition"+form for $THREE (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`, CoinGecko id `three-ws`).++## The headline++Of every venue $THREE is live on, **only MEXC can actually go on this form.** CoinGecko's exchange+registry holds 1,488 entries and not one of them is an Alpha venue: no Bybit Alpha, no KuCoin Alpha,+no Binance Alpha. Jupiter and Phantom are not in it either. The form says so itself: "If you can't+find your exchange in the list, it might not be on CoinGecko yet, and we're unable to proceed."++## What CoinGecko already tracks++Pulled live from `api.coingecko.com/api/v3/coins/three-ws/tickers` on 2026-08-16:++| Market | Pair | 24h volume (USD) |+| --- | --- | --- |+| LBank | THREE / USDT | 600,824 |+| PumpSwap | three / SOL | 48,861 |+| Meteora | three / SOL | 18,130 |+| Orca | three / SOL | 13,445 |+| KCEX | THREE / USDT | 4,621 |+| Meteora (second pool) | three / SOL | 39 |++## Venue matrix++| Venue | Real? | On CoinGecko's exchange list? | Submit on this form? |+| --- | --- | --- | --- |+| MEXC spot THREE/USDT | Yes, verified via MEXC API | Yes, `MEXC [mxc]` | **Yes** |+| LBank THREE/USDT | Yes | Yes | Already tracked |+| KCEX THREE/USDT | Yes | Yes | Already tracked |+| Bybit Alpha | Yes, official announcement | No Alpha venue exists | No |+| KuCoin Alpha | Yes, official announcement | No Alpha venue exists | No |+| Binance Web3 (web3.binance.com) | Yes | No, and it is a wallet aggregator | No |+| Jupiter (Verified) | Yes | Not on CoinGecko at all | No |+| Phantom (Verified) | Yes | Not on CoinGecko at all | No |+| derp.trade | Yes, Solana leverage venue | No (CoinGecko's "DerpDEX" is a different project on zkSync/Base/opBnb) | No, and perps go through the derivatives process |++### 1. MEXC, spot THREE/USDT (the one to submit)++Confirmed the same asset from MEXC's own `exchangeInfo`:+`contractAddress: FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`, `fullName: three.ws`,+`isSpotTradingAllowed: true`. Live since 2026-06-02T01:45Z, roughly 56.5k USD of 24h quote volume.++Form values:++- Exchange Name: `MEXC`+- Exchange Trade URL: `https://www.mexc.com/exchange/THREE_USDT`++### 2. The Alpha venues++Both are real and both carry our exact mint in their trade URLs:++- Bybit Alpha: <https://announcements.bybit.com/en/article/three-is-now-live-on-bybit-alpha-bltc04fc471efada919/>+- KuCoin Alpha: <https://www.kucoin.com/announcement/ph-kucoin-alpha-new-listed-token-three-percolator>++CoinGecko carries `Bybit [bybit_spot]`, `Bybit (Futures) [bybit]` and `KuCoin [kucoin]`, but Alpha is+a separate product with separate liquidity and CoinGecko does not carry it as a venue. Submitting+Alpha markets under the parent exchange would misstate where the liquidity sits and is likely to be+rejected.++The route that does work is CoinGecko's **New Exchange Listing** request, asking them to add Bybit+Alpha and KuCoin Alpha as venues. That is a separate form and a slower process, driven by the+exchange more than by us. Worth filing, but do not let it hold up the MEXC submission.++### 3. Jupiter and Phantom "Verified"++These are token-list trust badges, not markets. Jupiter routes through the same PumpSwap, Meteora and+Orca pools CoinGecko already tracks, so there is no separate market to add, and neither is in+CoinGecko's exchange registry. They are still strong credibility signals and belong in the X post+even though they do not belong on the form.++### Ruled out++Swept the full public market lists of Gate.io, Bitget, BitMart, KuCoin spot, CoinEx, BingX, XT.com,+Toobit, Poloniex, Bitrue, LATOKEN, Phemex, CoinW, Biconomy, DigiFinex, Hotcoin, Pionex, BTSE and+Ourbit. No THREE market on any of them.++WEEX claims trace only to `weex.com/wiki/article/...` SEO pages, not to WEEX's official channel at+`weex.com/help/articles/...`. The main article 404s and their API is unreachable. Not submitted.++## Link check++Every link below was resolved on 2026-08-16 before being put in a post:++| Link | HTTP |+| --- | --- |+| jup.ag token page | 200 |+| trade.phantom.com token page | 200 |+| web3.binance.com token page | 202 |+| lbank.com support article | 200 |+| kucoin.com announcement (`en-` locale) | 200 |+| derp.trade market page | 200 |+| bybit.com alpha (tracking params stripped) | 200 |+| kcex.com/exchange/THREE_USDT | 403 |++Two notes. Use the `en-` KuCoin announcement locale, not `ph-`; both resolve but `en-` is the right+one for this audience. The KCEX 403 is their CDN blocking automated requests, not a dead link:+CoinGecko shows trades on that pair minutes old, so the market is live and the URL is fine in a post.++The Bybit trade URL is given with its affiliate and campaign tracking parameters stripped. The bare+`?address=...&chain=SOL` form resolves 200 on its own.++## Post 1: main announcement (all links)++Goes up first, from [@trythreews](https://x.com/trythreews). Its URL fills "Link (1)" in section 2+of the form, so MEXC has to be named in it.++This runs 542 characters by X's counting rules, where every URL costs 23 characters regardless of+length. It needs a Premium long post. The thread version below is the fallback if the account is on+the 280-character limit.++```+$THREE is live everywhere.++CEX+MEXC https://www.mexc.com/exchange/THREE_USDT+LBank https://www.lbank.com/trade/three_usdt+KCEX https://www.kcex.com/exchange/THREE_USDT++Alpha+Bybit https://www.bybit.com/en/alpha/?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&chain=SOL+KuCoin https://www.kucoin.com/trade/alpha/solana/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump++Verified+Jupiter https://jup.ag/tokens/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump+Phantom https://trade.phantom.com/token/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump+Binance Web3 https://web3.binance.com/en/token/sol/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump++Perps+derp.trade https://derp.trade/market/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump++Announcements+https://announcements.bybit.com/en/article/three-is-now-live-on-bybit-alpha-bltc04fc471efada919/+https://www.kucoin.com/announcement/en-kucoin-alpha-new-listed-token-three-percolator+https://www.lbank.com/support/articles/2062382639494463488++Charts+https://www.coingecko.com/en/coins/three-ws+https://www.geckoterminal.com/solana/pools/5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z++CA FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump++three.ws+```++The KuCoin announcement covers two tokens and its URL slug carries the other one's name. If keeping+the feed purely $THREE matters more than the citation, drop that single line; the KuCoin Alpha trade+link in the Alpha block already proves the listing.++## Post 1b: thread version (fits the 280-character limit)++Six tweets, measured at 231 / 110 / 75 / 125 / 162 / 138 characters.++```+1/ $THREE is live everywhere.++Listed on MEXC, LBank, KCEX.+Live on Bybit Alpha and KuCoin Alpha.+Verified on Jupiter, Phantom and Binance Web3.+Perps on derp.trade.++Every link below.++CA: FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump+```++```+2/ Centralized exchanges++MEXC https://www.mexc.com/exchange/THREE_USDT+LBank https://www.lbank.com/trade/three_usdt+KCEX https://www.kcex.com/exchange/THREE_USDT+```++```+3/ Alpha venues++Bybit https://www.bybit.com/en/alpha/?address=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump&chain=SOL++KuCoin https://www.kucoin.com/trade/alpha/solana/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump+```++```+4/ Verified token status++Jupiter https://jup.ag/tokens/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump++Phantom https://trade.phantom.com/token/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump++Binance Web3 https://web3.binance.com/en/token/sol/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump+```++```+5/ Perps and official announcements++derp.trade https://derp.trade/market/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump++Bybit https://announcements.bybit.com/en/article/three-is-now-live-on-bybit-alpha-bltc04fc471efada919/++KuCoin https://www.kucoin.com/announcement/en-kucoin-alpha-new-listed-token-three-percolator++LBank https://www.lbank.com/support/articles/2062382639494463488+```++```+6/ Charts++CoinGecko https://www.coingecko.com/en/coins/three-ws+GeckoTerminal https://www.geckoterminal.com/solana/pools/5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z++CA FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump++three.ws+```++## Post 2: public verification++Goes up after submitting, once the request ID exists. Both the request ID and the GeckoTerminal URL+have to be in the post body, not in a reply or quote tweet.++Keep this one lean. CoinGecko's reviewer is looking for two things, the request ID and the+GeckoTerminal URL, and a wall of links buries them. Request ID `CU1608260002`, filed 2026-08-16.+275 characters, fits the free tier.++```+Verifying our CoinGecko market addition request for $THREE.++Request ID: CU1608260002+GeckoTerminal: https://www.geckoterminal.com/solana/tokens/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump+CA: FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump+Telegram: @three_ws++MEXC market: https://www.mexc.com/exchange/THREE_USDT++Posted from the official three.ws account.+```++Three deliberate choices in that text:++- **The GeckoTerminal token URL, not a pool URL.** CoinGecko states the purpose of this step is to+ safeguard against fraudulent contract addresses. The token URL carries the contract address in its+ own path, so it does that job directly; a pool URL does not.+- **Telegram `@three_ws` included.** CoinGecko offers this as optional extra verification and it+ costs nothing. Verified on 2026-08-16 that three.ws links out to `https://t.me/three_ws`.+- **Posted from @trythreews.** Verified the same day that the live three.ws homepage links to+ `https://x.com/trythreews`, which is what satisfies "an account linked to the project's official+ website". Both social links are present on the homepage.++Paste that post's URL into the form's Remarks field. Quote-tweet the main announcement from it so the+full link set is one click away without cluttering the verification post itself.++## Checks before submitting++- three.ws must link out to @trythreews, since that link is how CoinGecko ties the account to the+ project.+- The MEXC pair URL in the announcement post and in section 3 must match exactly.+- Regular Pass (5-day) is enough for a single market addition. Fast Pass is 200 USD.+- In Remarks, note that Bybit Alpha and KuCoin Alpha markets exist but their venues are absent from+ CoinGecko's exchange list. That tells the reviewer the coverage gap is on their side, not ours.diff --git a/public/changelog.json b/public/changelog.jsonindex 59b1b85c4..cbb302a24 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-16T00:58:19.283Z",+ "generated_at": "2026-08-16T06:11:43.017Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex 893594b0d..cdca90e17 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-16T00:58:19.274Z",+ "generated_at": "2026-08-16T06:11:42.813Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/api-sdp-proxy.test.js b/tests/api-sdp-proxy.test.jsnew file mode 100644index 000000000..072b869c0--- /dev/null+++ b/tests/api-sdp-proxy.test.js@@ -0,0 +1,257 @@+// /api/sdp/* : the same-origin proxy in front of the Solana Developer Platform.+//+// The SDP key grants org-level control over custodial wallets, SPL issuance and+// payments, so the properties pinned here are the ones that keep that key from+// becoming an open capability:+// 1. only the upstream's real route surface forwards; everything else 404s+// before a request leaves the box (no open proxy, no traversal).+// 2. every key-bearing route requires an authenticated admin, and a mutating+// one additionally requires a same-origin request.+// 3. the unauthenticated public surface (health/openapi/llms.txt) stays open.+// 4. the caller's own Authorization header is never relayed upstream.+// 5. the request body reaches upstream even when the client sends it chunked+// with no Content-Length, and an upstream markup body is never replayed as+// markup from our origin.+//+// sdpRequest is mocked, so no network and no SDP key are involved.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const sdpRequest = vi.fn();+const requireAdmin = vi.fn();++vi.mock('../api/_lib/sdp.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, sdpRequest: (...args) => sdpRequest(...args) };+});++vi.mock('../api/_lib/admin.js', () => ({+ requireAdmin: (...args) => requireAdmin(...args),+}));++vi.mock('../api/_lib/rate-limit.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ clientIp: () => '203.0.113.7',+ limits: { ...actual.limits, sdpIp: async () => ({ success: true }) },+ };+});++const handler = (await import('../api/sdp/[...path].js')).default;++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ removeHeader(k) {+ delete this.headers[k.toLowerCase()];+ },+ writeHead(code) {+ this.statusCode = code;+ return this;+ },+ end(payload) {+ if (payload !== undefined && this.body === null) this.body = payload;+ this.finished = true;+ return this;+ },+ };+}++async function call(path, { method = 'GET', headers = {}, query = {}, body } = {}) {+ const res = makeRes();+ const req = {+ method,+ url: `/api/sdp/${path}`,+ headers: { host: 'three.ws', ...headers },+ query: { path: path.split('/'), ...query },+ };+ if (body !== undefined) req.body = body;+ await handler(req, res);+ let parsed = res.body;+ if (typeof parsed === 'string') {+ try {+ parsed = JSON.parse(parsed);+ } catch {+ /* a text relay body stays a string */+ }+ }+ return { status: res.statusCode, body: parsed, raw: res.body, headers: res.headers };+}++beforeEach(() => {+ sdpRequest.mockReset();+ requireAdmin.mockReset();+ requireAdmin.mockResolvedValue({ id: 'u_admin' });+ sdpRequest.mockResolvedValue({+ status: 200,+ contentType: 'application/json; charset=utf-8',+ traceId: 'req_test',+ body: { ok: true },+ });+ process.env.APP_ORIGIN = 'https://three.ws';+});++describe('route allowlist', () => {+ it('404s an unknown route without calling upstream', async () => {+ const r = await call('not-a-real-route');+ expect(r.status).toBe(404);+ expect(r.body.error).toBe('not_found');+ expect(sdpRequest).not.toHaveBeenCalled();+ });++ it('404s a traversal attempt, including a double-encoded one', async () => {+ for (const p of ['v1/../../etc/passwd', 'v1/%2e%2e%2fetc']) {+ const r = await call(p);+ expect(r.status).toBe(404);+ }+ expect(sdpRequest).not.toHaveBeenCalled();+ });++ it('caps the echoed path so an oversized probe cannot be reflected wholesale', async () => {+ const r = await call(`bogus${'a'.repeat(500)}`);+ expect(r.status).toBe(404);+ expect(r.body.error_description.length).toBeLessThan(200);+ });+});++describe('authorization', () => {+ it('requires an admin on a key-bearing route', async () => {+ requireAdmin.mockImplementation(async (_req, res) => {+ res.statusCode = 401;+ res.end(JSON.stringify({ error: 'unauthorized' }));+ return null;+ });+ const r = await call('v1/wallets');+ expect(r.status).toBe(401);+ expect(sdpRequest).not.toHaveBeenCalled();+ });++ it('blocks a mutating call that did not originate from our own origin', async () => {+ const r = await call('v1/issuance/tokens', {+ method: 'POST',+ headers: { origin: 'https://evil.example', 'content-type': 'application/json' },+ body: { name: 'x' },+ });+ expect(r.status).toBe(403);+ expect(sdpRequest).not.toHaveBeenCalled();+ });++ it('allows a mutating call from our own origin', async () => {+ const r = await call('v1/issuance/tokens', {+ method: 'POST',+ headers: { origin: 'https://three.ws', 'content-type': 'application/json' },+ body: { name: 'x' },+ });+ expect(r.status).toBe(200);+ expect(sdpRequest).toHaveBeenCalledTimes(1);+ });++ it('leaves the public health and doc surfaces unauthenticated', async () => {+ for (const p of ['health', 'health/ready', 'openapi.json', 'llms.txt']) {+ sdpRequest.mockClear();+ const r = await call(p);+ expect(r.status).toBe(200);+ expect(sdpRequest).toHaveBeenCalledTimes(1);+ }+ expect(requireAdmin).not.toHaveBeenCalled();+ });+});++describe('forwarding', () => {+ it('never relays the caller Authorization header, and relays idempotency-key', async () => {+ await call('v1/wallets', {+ method: 'POST',+ headers: {+ origin: 'https://three.ws',+ authorization: 'Bearer attacker-supplied',+ 'idempotency-key': 'idem-1',+ 'content-type': 'application/json',+ },+ body: { label: 'w' },+ });+ const opts = sdpRequest.mock.calls[0][1];+ expect(opts.headers.authorization).toBeUndefined();+ expect(opts.headers['idempotency-key']).toBe('idem-1');+ });++ it('forwards the caller query string but never the catch-all path param', async () => {+ await call('v1/wallets', { query: { limit: '25', cursor: 'abc' } });+ const opts = sdpRequest.mock.calls[0][1];+ expect(opts.query).toEqual({ limit: '25', cursor: 'abc' });+ expect(opts.query.path).toBeUndefined();+ });++ it('forwards a chunked body that carries no content-length', async () => {+ await call('v1/wallets', {+ method: 'POST',+ headers: {+ origin: 'https://three.ws',+ 'content-type': 'application/json',+ 'transfer-encoding': 'chunked',+ },+ body: { label: 'streamed' },+ });+ expect(sdpRequest.mock.calls[0][1].body).toEqual({ label: 'streamed' });+ });++ it('sends no body when the request genuinely has none', async () => {+ await call('v1/payments/transfers', {+ method: 'POST',+ headers: { origin: 'https://three.ws' },+ });+ expect(sdpRequest.mock.calls[0][1].body).toBeUndefined();+ });+});++describe('response relay', () => {+ it('relays the upstream status, envelope and trace id verbatim', async () => {+ sdpRequest.mockResolvedValue({+ status: 422,+ contentType: 'application/json',+ traceId: 'req_abc',+ body: { error: { code: 'invalid_request', message: 'bad mint' } },+ });+ const r = await call('v1/issuance/tokens', {+ method: 'POST',+ headers: { origin: 'https://three.ws', 'content-type': 'application/json' },+ body: { name: 'x' },+ });+ expect(r.status).toBe(422);+ expect(r.body.error.code).toBe('invalid_request');+ expect(r.headers['x-sdp-trace-id']).toBe('req_abc');+ });++ it('relays a text body with its own content type and no caching', async () => {+ sdpRequest.mockResolvedValue({+ status: 200,+ contentType: 'text/plain; charset=utf-8',+ traceId: null,+ body: '# Solana Developer Platform API',+ });+ const r = await call('llms.txt');+ expect(r.raw).toBe('# Solana Developer Platform API');+ expect(r.headers['content-type']).toBe('text/plain; charset=utf-8');+ expect(r.headers['cache-control']).toBe('no-store');+ });++ it('downgrades a markup body so it cannot execute under our own CSP', async () => {+ sdpRequest.mockResolvedValue({+ status: 400,+ contentType: 'text/html; charset=utf-8',+ traceId: null,+ body: '<script>alert(1)</script>',+ });+ const r = await call('llms.txt');+ expect(r.status).toBe(400);+ expect(r.headers['content-type']).toBe('text/plain; charset=utf-8');+ });+});