Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Agent-wallet x402 bridge, marketplace + x API hardening, http-params tests, changelog regen

nirholas08c0b68f079f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e96476c25..363c640c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Agent lookup now matches the rest of the site and links straight to the agent’s page** — The agent lookup tool used to render as a stark white page that ignored your light/dark theme and had no site navigation or footer. It now uses the same chrome and theme tokens as every other page, so it looks on-brand in both modes. More importantly, when a lookup resolves an agent it now shows a prominent “Open agent page” button that takes you to that agent’s profile on three.ws — so resolving an agent no longer dead-ends on external explorer links. Copy buttons also tell you if a copy fails instead of staying silent. (`/lookup`) `[improvement]`
- **Avatar Studio no longer crashes on NFT-gated traits, wallet checks, exports, or VRM0 models** — An audit of Avatar Studio turned up twelve places where it would throw and stop instead of working: checking whether a trait is NFT-locked, looking up traits and model parts, verifying that your wallet owns a required collection, connecting an Ethereum or Polygon wallet, exporting a GLB, recovering from a failed Solana transaction, decoding KTX2 textures, and loading older VRM0 avatars all hit undefined-variable errors. All twelve are fixed, so trait selection, wallet-ownership gating, EVM wallet connect, model export, and VRM0 loading now run cleanly. (`/create/studio`) `[fix]`
+- **Avatar viewer, lipsync tools, sign-in and account polish from a labs & account audit** — A page-by-page audit of the labs, avatar tools and account pages turned up rough edges we’ve now smoothed. The standalone Avatar Artifact viewer works on phones — it has a back link to three.ws, links out to Playground, Labs and Agents, a loading state, a designed message if the 3D runtime can’t load, and you can steer the avatar with touch or the arrow keys, not just a mouse. The mic lipsync demo now shows a clear, recoverable message when the microphone is blocked, missing or busy instead of a bare pop-up, and the TTS lipsync demo shows a retry banner if speech generation fails. Sign-in and sign-up no longer leave you on the form after a connection blip, redirect cleanly so Back doesn’t return you to a login screen you already passed, and signup now bounces you onward if you’re already signed in. Forgot-password tells you if your request didn’t reach us instead of always saying it was sent. The Playground rejects oversized or wrong-type model uploads with friendly guidance, the account page’s delegation panel now opens a working console to have one of your agents answer a prompt, and the reputation explorer clearly flags when reviews are written to a test network. (`/labs`) `[improvement, fix]`
- **Bundle specific skills into your subscription plans** — When you create or edit a subscription plan in the agent editor's Monetization tab, you can now tick exactly which of your agent's skills the plan includes. Subscribers to that plan get unlimited access to those skills for the life of their subscription, and the plan list shows what each plan bundles at a glance — so you can offer a focused starter plan and a fuller pro plan side by side. `[feature, improvement]`
- **Coin community worlds no longer get stuck on “Connecting…”** — Opening a coin community world could occasionally hang on “Connecting…” forever — you'd see only yourself, with chat, voice, and shared building all stalled and no way to recover short of a reload. It happened when the game server accepted the connection but never finished the join handshake, for instance while a server instance was waking from idle. The connection now has a firm time limit: if the handshake doesn't complete in time it retries on its own, and if the server stays unreachable it drops you cleanly into single-player so you can still explore and build locally — with the status pill tappable to reconnect. The same safeguard covers the open /walk world and the IRL map. `[fix]`
- **Connect a wallet and your $THREE tier is recognized — no account needed** — You no longer need a three.ws account to be seen as a $THREE holder. Connect your Solana wallet and the site reads your tier straight from your on-chain holdings: the holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) and holder features like High-quality generation on Forge unlock from the connected wallet alone. When a feature needs proof the wallet is yours, you approve a single free signature that moves no funds. Switch or disconnect a wallet and your tier updates instantly, no reload. Signed-in accounts keep working exactly as before. (`/forge`) `[improvement]`
diff --git a/api/_lib/http-params.js b/api/_lib/http-params.js
index a9f3d4278..dc20930d3 100644
--- a/api/_lib/http-params.js
+++ b/api/_lib/http-params.js
@@ -17,7 +17,7 @@
export function clampInt(raw, { min = 1, max, fallback }) {
if (!Number.isFinite(max)) throw new TypeError('clampInt: `max` is required and must be finite');
if (!Number.isFinite(fallback)) throw new TypeError('clampInt: `fallback` is required and must be finite');
- const parsed = typeof raw === 'number' ? raw : parseInt(raw, 10);
+ const parsed = typeof raw === 'number' ? Math.trunc(raw) : parseInt(raw, 10);
const base = Number.isFinite(parsed) ? parsed : fallback;
return Math.min(Math.max(base, min), max);
}
diff --git a/api/_lib/pump-go.js b/api/_lib/pump-go.js
index 3ed26f2ce..509867dca 100644
--- a/api/_lib/pump-go.js
+++ b/api/_lib/pump-go.js
@@ -13,6 +13,8 @@
// into a lean, UI-friendly shape. The normalizers are pure so they unit-test
// without the network.
+import { clampInt } from './http-params.js';
+
const REST_BASE = 'https://livestream-api.pump.fun';
const PROGRAM_ID = 'goGzNYTYkSEe4hUqz6dPmY5uf3CTt36AQAoujXDrKiV';
const WSOL_MINT = 'So11111111111111111111111111111111111111112';
@@ -55,7 +57,7 @@ async function pumpGoGet(path) {
}
function clampLimit(limit, fallback = 30) {
- return Math.min(Math.max(parseInt(limit, 10) || fallback, 1), MAX_LIMIT);
+ return clampInt(limit, { max: MAX_LIMIT, fallback });
}
// USD for a reward leg from the parallel rewardLegsUsd array (only when priced).
diff --git a/api/_lib/x402/receipt-storage.js b/api/_lib/x402/receipt-storage.js
index a35c5f35d..692a8ac94 100644
--- a/api/_lib/x402/receipt-storage.js
+++ b/api/_lib/x402/receipt-storage.js
@@ -12,6 +12,7 @@
// must not surface as a 5xx on a paid response that already settled on-chain.
import { sql } from '../db.js';
+import { clampInt } from '../http-params.js';
import { extractReceiptPayload } from '@x402/extensions';
@@ -69,7 +70,7 @@ export function recordReceipt({ resourceUrl, signedReceipt, settled }) {
export async function listReceiptsForPayer({ payer, sinceUnix, limit }) {
const normPayer = normalisePayer(payer);
if (!normPayer) return [];
- const clampedLimit = Math.min(Math.max(parseInt(limit, 10) || 50, 1), 200);
+ const clampedLimit = clampInt(limit, { max: 200, fallback: 50 });
const sinceDate =
sinceUnix && Number.isFinite(Number(sinceUnix))
? new Date(Number(sinceUnix) * 1000)
diff --git a/api/agent-wallet-bridge.js b/api/agent-wallet-bridge.js
new file mode 100644
index 000000000..1abbc8323
--- /dev/null
+++ b/api/agent-wallet-bridge.js
@@ -0,0 +1,359 @@
+// Hosted agent-wallet x402 bridge — the production equivalent of
+// scripts/agent-wallet-x402-bridge.mjs, so the /play/agent-wallet page works
+// for real visitors instead of dead-ending on "bridge offline".
+//
+// GET /api/agent-wallet-bridge?status=1 → wallet + balances
+// GET /api/agent-wallet-bridge?quote=1&endpoint=<url>&... → parsed 402 challenge
+// POST /api/agent-wallet-bridge?pay=1 {endpoint,method,body} → SSE real payment
+//
+// The platform-held A2A payer keypair (A2A_PAYER_SOLANA_SECRET) signs a real SPL
+// USDC TransferChecked on Solana mainnet against three.ws's own x402 endpoints
+// (standard x402 v2 `exact` scheme via @x402/svm — the same flow the local
+// bridge runs). Settlement happens at the paid endpoint's facilitator; real
+// USDC moves.
+//
+// Because the payer wallet is shared, the spend path is protected:
+// • status / quote are read-only and public.
+// • pay requires a signed-in session (or bearer) — anonymous visitors get a
+// clear "sign in" error instead of draining the wallet.
+// • per-IP rate limit + per-payment cap + per-wallet daily USDC cap.
+// • target endpoints must be on an allowlisted origin (three.ws + local dev).
+
+import { cors, wrap, error, setRateLimitHeaders } from './_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { createSolanaSigner } from './_lib/x402/a2a-client.js';
+import { enforceCap, commit, rollbackReservation } from './_lib/x402-spending-cap.js';
+import { env } from './_lib/env.js';
+
+const SOLANA_RPC_URL = env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+const USDC_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const PAYER_SECRET = env.A2A_PAYER_SOLANA_SECRET || '';
+
+// Caps (micro-USDC == micro-USD for USDC). Per-payment default $0.10, matching
+// the local bridge; per-wallet daily default $2.00. Both env-overridable.
+const MAX_PER_CALL_MICROS = Number(process.env.AGENT_WALLET_MAX_USDC_MICROS || 100_000);
+const MAX_PER_DAY_MICROS = Number(process.env.AGENT_WALLET_DAILY_USDC_MICROS || 2_000_000);
+
+const ALLOWED_ENDPOINT_ORIGINS = (
+ process.env.AGENT_WALLET_ALLOWED_ORIGINS ||
+ 'https://three.ws,http://localhost:3000,http://127.0.0.1:3000'
+)
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+
+const BUILDER_CODE_PATTERN = /^[a-z0-9_]{1,32}$/;
+
+function fmtUsdc(micros) {
+ return '$' + (Number(micros) / 1e6).toFixed(2);
+}
+
+function endpointAllowed(endpoint) {
+ try {
+ return ALLOWED_ENDPOINT_ORIGINS.includes(new URL(endpoint).origin);
+ } catch {
+ return false;
+ }
+}
+
+// A co-signable Solana accept: exact scheme, Solana CAIP-2 network, and the
+// facilitator fee payer the @x402/svm scheme needs to build the transaction.
+function isSolanaExactAccept(a) {
+ return a && a.scheme === 'exact' && String(a.network || '').startsWith('solana:') && a.extra?.feePayer;
+}
+
+let signerPromise = null;
+function agentSigner() {
+ if (!PAYER_SECRET) {
+ return Promise.reject(new Error('agent wallet not configured on the server'));
+ }
+ if (!signerPromise) {
+ signerPromise = createSolanaSigner(PAYER_SECRET);
+ signerPromise.catch(() => { signerPromise = null; });
+ }
+ return signerPromise;
+}
+
+let statusCache = null; // { at, payload }
+async function walletStatus() {
+ if (statusCache && Date.now() - statusCache.at < 10_000) return statusCache.payload;
+ const signer = await agentSigner();
+ const [{ Connection, PublicKey }, { getAssociatedTokenAddressSync }] = await Promise.all([
+ import('@solana/web3.js'),
+ import('@solana/spl-token'),
+ ]);
+ const conn = new Connection(SOLANA_RPC_URL, 'confirmed');
+ const owner = new PublicKey(signer.address);
+ let sol = null;
+ let usdc = 0;
+ try {
+ sol = (await conn.getBalance(owner)) / 1e9;
+ const ata = getAssociatedTokenAddressSync(new PublicKey(USDC_MINT_SOLANA), owner);
+ const bal = await conn.getTokenAccountBalance(ata).catch(() => null);
+ usdc = bal?.value?.uiAmount ?? 0;
+ } catch {
+ // RPC hiccup — report the wallet without live balances rather than fail.
+ }
+ const payload = {
+ ok: true,
+ wallet: { address: signer.address, mode: 'solana', chainNamespace: 'solana' },
+ balance: {
+ currency: 'USD',
+ totalValue: usdc.toFixed(2),
+ chains: [{ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', sol, usdc }],
+ },
+ };
+ statusCache = { at: Date.now(), payload };
+ return payload;
+}
+
+async function fetch402(endpoint, method, body) {
+ const res = await fetch(endpoint, {
+ method,
+ headers: { accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}) },
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ if (res.status !== 402) {
+ const text = (await res.text()).slice(0, 300);
+ throw new Error(`expected a 402 challenge from ${endpoint}, got ${res.status}: ${text}`);
+ }
+ const challenge = await res.json();
+ if (!Array.isArray(challenge?.accepts) || !challenge.accepts.length) {
+ throw new Error('402 challenge has no accepts[] entries');
+ }
+ const accept = challenge.accepts.find(isSolanaExactAccept);
+ if (!accept) throw new Error('endpoint does not accept exact-scheme USDC on Solana');
+ return { challenge, accept };
+}
+
+// ERC-8021 builder-code echo — the server rejects payments that don't echo the
+// declared app code. Self-attribute as the wallet/service pair.
+function builderCodeEcho(challenge) {
+ const declaredA = challenge?.extensions?.['builder-code']?.info?.a;
+ if (!declaredA || !BUILDER_CODE_PATTERN.test(declaredA)) return null;
+ return {
+ a: declaredA,
+ w: env.X402_BUILDER_CODE_WALLET || 'threews_agent',
+ s: ['agent_wallet_x402_bridge'],
+ };
+}
+
+async function executePayment({ endpoint, method, body, payerAddress, emit }) {
+ // 1. Real 402 challenge from the paid endpoint.
+ const { challenge, accept } = await fetch402(endpoint, method, body);
+ const amount = BigInt(accept.amount);
+ if (amount > BigInt(MAX_PER_CALL_MICROS)) {
+ throw new Error(
+ `endpoint asks for ${fmtUsdc(accept.amount)} USDC, above the per-payment cap of ${fmtUsdc(MAX_PER_CALL_MICROS)}`,
+ );
+ }
+
+ // 2. Spending-cap admission (per-payment already checked; this enforces the
+ // per-wallet daily ceiling and records the spend).
+ const cap = await enforceCap({
+ requirement: accept,
+ opts: {
+ address: payerAddress,
+ maxPerCall: MAX_PER_CALL_MICROS,
+ maxPerDay: MAX_PER_DAY_MICROS,
+ strict: true,
+ },
+ });
+ if (cap.abort) throw new Error(cap.reason || 'spending cap exceeded');
+
+ let committed = false;
+ try {
+ emit({
+ stage: 'challenge',
+ amount: accept.amount,
+ payTo: accept.payTo,
+ asset: accept.asset,
+ network: accept.network,
+ resource: challenge.resource || null,
+ });
+
+ // 3. The agent wallet builds + partially signs the SPL TransferChecked.
+ const signer = await agentSigner();
+ emit({
+ stage: 'signing',
+ signer: signer.address,
+ network: accept.network,
+ mint: accept.asset,
+ to: accept.payTo,
+ value: accept.amount,
+ feePayer: accept.extra.feePayer,
+ });
+ const { ExactSvmScheme } = await import('@x402/svm');
+ const scheme = new ExactSvmScheme(signer, { rpcUrl: SOLANA_RPC_URL });
+ const built = await scheme.createPaymentPayload(2, accept);
+ emit({ stage: 'signed', signer: signer.address });
+
+ // 4. Retry with the X-PAYMENT header — the endpoint verifies, settles via
+ // its facilitator, then does the paid work.
+ const paymentPayload = {
+ x402Version: built.x402Version || 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: { url: endpoint, mimeType: 'application/json' },
+ accepted: accept,
+ payload: built.payload,
+ };
+ const echo = builderCodeEcho(challenge);
+ if (echo) paymentPayload.extensions = { 'builder-code': echo };
+ emit({ stage: 'submitting' });
+
+ const paidRes = await fetch(endpoint, {
+ method,
+ headers: {
+ accept: 'application/json',
+ 'x-payment': Buffer.from(JSON.stringify(paymentPayload), 'utf8').toString('base64'),
+ ...(body ? { 'content-type': 'application/json' } : {}),
+ },
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const resultText = await paidRes.text();
+ let result = null;
+ try { result = JSON.parse(resultText); } catch { result = { raw: resultText.slice(0, 1000) }; }
+ if (!paidRes.ok) {
+ throw new Error(
+ `payment rejected by endpoint (HTTP ${paidRes.status}): ${result?.error?.message || result?.error || resultText.slice(0, 300)}`,
+ );
+ }
+
+ let settlement = null;
+ const settleHeader = paidRes.headers.get('x-payment-response');
+ if (settleHeader) {
+ try { settlement = JSON.parse(Buffer.from(settleHeader, 'base64').toString('utf8')); } catch { settlement = null; }
+ }
+
+ await commit(cap.reservation, { endpoint, tx: settlement?.transaction || null });
+ committed = true;
+ statusCache = null; // balance just changed
+ emit({
+ stage: 'done',
+ amount: accept.amount,
+ payer: signer.address,
+ payTo: accept.payTo,
+ settlement,
+ result,
+ });
+ } finally {
+ if (!committed) await rollbackReservation(cap.reservation).catch(() => {});
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+
+ const url = new URL(req.url, 'http://x');
+
+ // ── STATUS (public, read-only) ────────────────────────────────────────
+ if (req.method === 'GET' && url.searchParams.get('status') === '1') {
+ try {
+ res.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' });
+ res.end(JSON.stringify(await walletStatus()));
+ } catch (err) {
+ error(res, 503, 'wallet_unavailable', err.message);
+ }
+ return;
+ }
+
+ // ── QUOTE (public, read-only) ─────────────────────────────────────────
+ if (req.method === 'GET' && url.searchParams.get('quote') === '1') {
+ const endpoint = url.searchParams.get('endpoint') || '';
+ const method = (url.searchParams.get('method') || 'POST').toUpperCase();
+ if (!endpointAllowed(endpoint)) {
+ return error(res, 400, 'endpoint_not_allowed', `endpoint origin not allowed (allowed: ${ALLOWED_ENDPOINT_ORIGINS.join(', ')})`);
+ }
+ try {
+ const bodyParam = url.searchParams.get('body');
+ const probeBody = bodyParam ? JSON.parse(bodyParam) : undefined;
+ const { challenge, accept } = await fetch402(endpoint, method, probeBody);
+ res.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' });
+ res.end(JSON.stringify({
+ ok: true,
+ amount: accept.amount,
+ payTo: accept.payTo,
+ asset: accept.asset,
+ network: accept.network,
+ feePayer: accept.extra?.feePayer || null,
+ maxTimeoutSeconds: accept.maxTimeoutSeconds,
+ resource: challenge.resource || null,
+ }));
+ } catch (err) {
+ error(res, 502, 'quote_failed', err.message);
+ }
+ return;
+ }
+
+ // ── PAY (real on-chain spend — auth + rate limit + caps) ──────────────
+ if (req.method !== 'POST') {
+ return error(res, 405, 'method_not_allowed', 'use ?status=1, ?quote=1, or POST ?pay=1');
+ }
+
+ // Real USDC leaves the shared platform wallet — require a signed-in caller.
+ const sessionUser = await getSessionUser(req).catch(() => null);
+ const bearerUser = sessionUser ? null : await authenticateBearer(extractBearer(req)).catch(() => null);
+ if (!sessionUser && !bearerUser) {
+ return error(res, 401, 'unauthorized', 'Sign in to let your agent wallet make a real payment.');
+ }
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) {
+ const retryAfter = Math.max(1, setRateLimitHeaders(res, rl));
+ res.setHeader('retry-after', String(retryAfter));
+ return error(res, 429, 'rate_limited', 'Too many payment attempts — try again shortly.');
+ }
+
+ let parsed;
+ try {
+ parsed = typeof req.body === 'object' && req.body ? req.body : JSON.parse(await readRawBody(req) || '{}');
+ } catch {
+ return error(res, 400, 'invalid_body', 'invalid JSON body');
+ }
+ const endpoint = String(parsed.endpoint || '');
+ const payMethod = String(parsed.method || 'POST').toUpperCase();
+ if (!['GET', 'POST'].includes(payMethod)) {
+ return error(res, 400, 'invalid_method', 'method must be GET or POST');
+ }
+ if (!endpointAllowed(endpoint)) {
+ return error(res, 400, 'endpoint_not_allowed', `endpoint origin not allowed (allowed: ${ALLOWED_ENDPOINT_ORIGINS.join(', ')})`);
+ }
+
+ res.writeHead(200, {
+ 'content-type': 'text/event-stream; charset=utf-8',
+ 'cache-control': 'no-cache, no-store',
+ connection: 'keep-alive',
+ 'x-accel-buffering': 'no',
+ 'access-control-allow-origin': '*',
+ });
+ res.flushHeaders?.();
+
+ let lastStage = 'challenge';
+ const emit = (evt) => {
+ lastStage = evt.stage || lastStage;
+ res.write(`data: ${JSON.stringify(evt)}\n\n`);
+ };
+ try {
+ const signer = await agentSigner();
+ await executePayment({ endpoint, method: payMethod, body: parsed.body, payerAddress: signer.address, emit });
+ } catch (err) {
+ emit({ stage: 'error', failedStage: lastStage, message: err.message });
+ }
+ res.end();
+});
+
+function readRawBody(req) {
+ return new Promise((resolve, reject) => {
+ let data = '';
+ req.on('data', (c) => {
+ data += c;
+ if (data.length > 64 * 1024) reject(new Error('request body too large'));
+ });
+ req.on('end', () => resolve(data));
+ req.on('error', reject);
+ });
+}
+
+export const maxDuration = 30;
diff --git a/api/agent/activity.js b/api/agent/activity.js
index a6b699504..d70ebee36 100644
--- a/api/agent/activity.js
+++ b/api/agent/activity.js
@@ -8,6 +8,7 @@
// Address + parsed transactions); no mocks, no sample feed.
import { cors, json, method, wrap } from '../_lib/http.js';
+import { clampInt } from '../_lib/http-params.js';
import {
avatarWalletConfig,
getConnection,
@@ -75,7 +76,7 @@ export default wrap(async (req, res) => {
// Graceful no-op for the poller when the wallet isn't set up yet.
if (!cfg.configured) return json(res, 200, { configured: false, transfers: [] });
- const limit = Math.min(Math.max(parseInt(req.query?.limit, 10) || 10, 1), 25);
+ const limit = clampInt(req.query?.limit, { max: 25, fallback: 10 });
const connection = getConnection(cfg.rpcUrl);
const owner = new PublicKey(cfg.address);
diff --git a/api/characters.js b/api/characters.js
index 14bcc7c1d..79f0330b1 100644
--- a/api/characters.js
+++ b/api/characters.js
@@ -10,6 +10,7 @@
import { sql } from './_lib/db.js';
import { cors, json, method, wrap, rateLimited } from './_lib/http.js';
+import { clampInt } from './_lib/http-params.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { publicUrl } from './_lib/r2.js';
@@ -21,7 +22,7 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
const url = new URL(req.url, 'http://x');
- const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '24', 10), 1), 60);
+ const limit = clampInt(url.searchParams.get('limit'), { max: 60, fallback: 24 });
const cursor = url.searchParams.get('cursor') || null;
const q = (url.searchParams.get('q') || '').trim().slice(0, 80);
const sort = url.searchParams.get('sort') === 'chats' ? 'chats' : 'new';
diff --git a/api/developer/mcp-test.js b/api/developer/mcp-test.js
index e231e39f5..0fe087821 100644
--- a/api/developer/mcp-test.js
+++ b/api/developer/mcp-test.js
@@ -16,6 +16,7 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { limits } from '../_lib/rate-limit.js';
import { dispatch } from '../_mcp/dispatch.js';
@@ -31,9 +32,11 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const user = await getSessionUser(req);
+ const user = await getSessionUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in to test MCP');
+ if (!(await requireCsrf(req, res, user.id))) return;
+
const rl = await limits.mcpUser(user.id);
if (!rl.success) return rateLimited(res, rl);
diff --git a/api/galaxy.js b/api/galaxy.js
index f66f2201c..698f29da9 100644
--- a/api/galaxy.js
+++ b/api/galaxy.js
@@ -20,6 +20,7 @@
import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';
+import { clampInt } from './_lib/http-params.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { publicUrl } from './_lib/r2.js';
import { watsonxConfig, watsonxEmbed, watsonxChatComplete } from './_lib/watsonx.js';
@@ -82,7 +83,7 @@ export default wrap(async (req, res) => {
async function handleGalaxy(req, res, cfg) {
const url = new URL(req.url, 'http://x');
const refresh = url.searchParams.get('refresh') === '1';
- const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '600', 10), 1), 1200);
+ const limit = clampInt(url.searchParams.get('limit'), { max: 1200, fallback: 600 });
await ensureSnapshotTable();
@@ -178,7 +179,7 @@ async function handleSearch(req, res, cfg) {
const query = String(body.query || '').trim().slice(0, 200);
if (!query) return error(res, 400, 'validation_error', 'query is required');
- const topK = Math.min(Math.max(parseInt(body.limit, 10) || 12, 1), 30);
+ const topK = clampInt(body.limit, { max: 30, fallback: 12 });
// Embed the query with the same Granite model the agents were embedded with, so
// query and agent vectors share a space.
diff --git a/api/marketplace/asset-price.js b/api/marketplace/asset-price.js
index c92c12543..cda0795a5 100644
--- a/api/marketplace/asset-price.js
+++ b/api/marketplace/asset-price.js
@@ -16,6 +16,7 @@
import { sql } from '../_lib/db.js';
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { z } from 'zod';
@@ -34,9 +35,9 @@ const postBody = z.object({
async function resolveAuth(req) {
const session = await getSessionUser(req);
- if (session) return { userId: session.id };
+ if (session) return { userId: session.id, fromSession: true };
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
+ if (bearer) return { userId: bearer.userId, fromSession: false };
return null;
}
@@ -111,6 +112,9 @@ async function handleSet(req, res) {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ // Session-cookie writes need CSRF; bearer-token callers are exempt.
+ if (auth.fromSession && !(await requireCsrf(req, res, auth.userId))) return;
+
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
diff --git a/api/marketplace/purchase-as-agent.js b/api/marketplace/purchase-as-agent.js
index 8c098a0b0..c9a98268a 100644
--- a/api/marketplace/purchase-as-agent.js
+++ b/api/marketplace/purchase-as-agent.js
@@ -28,7 +28,8 @@ import {
import { sql } from '../_lib/db.js';
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
-import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
+import { cors, error, json, method, readJson, wrap, rateLimited, respondError } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
import { confirmSkillPurchase, resolvePayoutAddress, logEvent } from '../_lib/purchase-confirm.js';
@@ -45,9 +46,9 @@ const bodySchema = z.object({
async function resolveAuth(req) {
const session = await getSessionUser(req);
- if (session) return { userId: session.id };
+ if (session) return { userId: session.id, fromSession: true };
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
+ if (bearer) return { userId: bearer.userId, fromSession: false };
return null;
}
@@ -62,6 +63,9 @@ export default wrap(async (req, res) => {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ // Session-cookie writes need CSRF; bearer-token callers are exempt.
+ if (auth.fromSession && !(await requireCsrf(req, res, auth.userId))) return;
+
// Per-IP rate limit (coarse gate)
const rlIp = await limits.authIp(clientIp(req));
if (!rlIp.success) return rateLimited(res, rlIp);
@@ -182,7 +186,7 @@ export default wrap(async (req, res) => {
meta: { seller_agent_id, skill, is_self_dealing: isSelfDealing },
});
} catch (e) {
- return error(res, 500, 'wallet_decrypt_failed', `could not load buyer keypair: ${e.message}`);
+ return respondError(res, 500, 'wallet_decrypt_failed', e);
}
// Resolve seller payout wallet
@@ -277,7 +281,7 @@ export default wrap(async (req, res) => {
`;
await logEvent(pur.id, 'tx_send_failed', { error: e.message }).catch(() => {});
log('purchase_as_agent.tx_failed', { purchase_id: pur.id, error: e.message, buyer_agent_id });
- return error(res, 502, 'tx_send_failed', `failed to submit transaction: ${e.message}`);
+ return respondError(res, 502, 'tx_send_failed', e);
}
// Validate on-chain + record revenue + emit notifications via canonical lib
diff --git a/api/marketplace/set-skill-price.js b/api/marketplace/set-skill-price.js
index 23228831e..ec6ea529e 100644
--- a/api/marketplace/set-skill-price.js
+++ b/api/marketplace/set-skill-price.js
@@ -7,6 +7,7 @@
import { sql } from '../_lib/db.js';
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { invalidateSkillPriceCache } from '../_lib/skill-price-cache.js';
import { z } from 'zod';
@@ -21,9 +22,9 @@ const bodySchema = z.object({
async function resolveAuth(req) {
const session = await getSessionUser(req);
- if (session) return { userId: session.id };
+ if (session) return { userId: session.id, fromSession: true };
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
+ if (bearer) return { userId: bearer.userId, fromSession: false };
return null;
}
@@ -34,6 +35,9 @@ export default wrap(async (req, res) => {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ // Session-cookie writes need CSRF; bearer-token callers are exempt.
+ if (auth.fromSession && !(await requireCsrf(req, res, auth.userId))) return;
+
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
diff --git a/api/notifications/read-all.js b/api/notifications/read-all.js
index 52e4147f3..423ad110e 100644
--- a/api/notifications/read-all.js
+++ b/api/notifications/read-all.js
@@ -3,6 +3,7 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -11,6 +12,8 @@ export default wrap(async (req, res) => {
const user = await getSessionUser(req);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, user.id))) return;
+
const rows = await sql`
update user_notifications
set read_at = now()
diff --git a/api/pump-bounties.js b/api/pump-bounties.js
index 0b4c3967a..25d4ebeed 100644
--- a/api/pump-bounties.js
+++ b/api/pump-bounties.js
@@ -8,13 +8,14 @@
import { cors, json, error, wrap, method } from './_lib/http.js';
import { cacheGet, cacheSet } from './_lib/cache.js';
import { listBounties, PumpGoError } from './_lib/pump-go.js';
+import { clampInt } from './_lib/http-params.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://localhost');
- const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '30', 10), 1), 50);
+ const limit = clampInt(url.searchParams.get('limit'), { max: 50, fallback: 30 });
const cursor = url.searchParams.get('cursor') || null;
const status = url.searchParams.get('status') || null;
diff --git a/api/x/reviews.js b/api/x/reviews.js
index 91aa00a1a..1ecde6757 100644
--- a/api/x/reviews.js
+++ b/api/x/reviews.js
@@ -6,6 +6,7 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { publishTweet, XPostError } from '../_lib/x-post.js';
export default wrap(async (req, res) => {
@@ -26,6 +27,10 @@ export default wrap(async (req, res) => {
return json(res, 200, { reviews: rows });
}
+ // PATCH (approve/edit/reject) and DELETE (reject) are state-changing — gate
+ // them behind CSRF before touching the review.
+ if (!(await requireCsrf(req, res, user.id))) return;
+
const url = new URL(req.url, 'http://x');
const id = url.searchParams.get('id');
if (!id) return error(res, 400, 'validation_error', 'id required');
diff --git a/api/x/schedule.js b/api/x/schedule.js
index 98e3602c8..cd064c153 100644
--- a/api/x/schedule.js
+++ b/api/x/schedule.js
@@ -5,6 +5,7 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { MAX_TWEET_LEN } from '../_lib/x-post.js';
export default wrap(async (req, res) => {
@@ -26,6 +27,7 @@ export default wrap(async (req, res) => {
}
if (req.method === 'DELETE') {
+ if (!(await requireCsrf(req, res, user.id))) return;
const url = new URL(req.url, 'http://x');
const id = url.searchParams.get('id');
if (!id) return error(res, 400, 'validation_error', 'id required');
@@ -39,6 +41,7 @@ export default wrap(async (req, res) => {
}
// POST
+ if (!(await requireCsrf(req, res, user.id))) return;
const body = await readJson(req);
const text = typeof body?.text === 'string' ? body.text.trim() : '';
const scheduledAt = typeof body?.scheduled_at === 'string' ? body.scheduled_at : '';
diff --git a/api/x/status.js b/api/x/status.js
index 655943ea3..72f53017d 100644
--- a/api/x/status.js
+++ b/api/x/status.js
@@ -4,6 +4,7 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { cors, method, wrap, error, json } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
import { getUserTier } from '../_lib/x-post.js';
export default wrap(async (req, res) => {
@@ -14,6 +15,7 @@ export default wrap(async (req, res) => {
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
if (req.method === 'DELETE') {
+ if (!(await requireCsrf(req, res, user.id))) return;
await sql`
update social_connections
set disconnected_at = now(), updated_at = now()
diff --git a/api/x/triggers.js b/api/x/triggers.js
index b987838c6..ce98d0242 100644
--- a/api/x/triggers.js
+++ b/api/x/triggers.js
@@ -6,6 +6,7 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
const VALID_KINDS = new Set(['daily_persona', 'weekly_digest', 'price_milestone', 'payment_received']);
@@ -53,6 +54,7 @@ export default wrap(async (req, res) => {
}
if (req.method === 'POST') {
+ if (!(await requireCsrf(req, res, user.id))) return;
const body = await readJson(req);
const kind = body?.kind;
if (!VALID_KINDS.has(kind)) return error(res, 400, 'validation_error', `kind must be one of: ${[...VALID_KINDS].join(', ')}`);
@@ -72,6 +74,7 @@ export default wrap(async (req, res) => {
if (!id) return error(res, 400, 'validation_error', 'id required');
if (req.method === 'PATCH') {
+ if (!(await requireCsrf(req, res, user.id))) return;
const body = await readJson(req);
const existing = (await sql`select kind, config from x_triggers where id = ${id} and user_id = ${user.id} limit 1`)[0];
if (!existing) return error(res, 404, 'not_found', 'trigger not found');
@@ -96,6 +99,7 @@ export default wrap(async (req, res) => {
}
// DELETE
+ if (!(await requireCsrf(req, res, user.id))) return;
const result = await sql`delete from x_triggers where id = ${id} and user_id = ${user.id} returning id`;
if (!result.length) return error(res, 404, 'not_found', 'trigger not found');
return json(res, 200, { deleted: id });
diff --git a/data/changelog.json b/data/changelog.json
index a4dff3a90..3d8fd33bf 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-18",
+ "title": "Avatar viewer, lipsync tools, sign-in and account polish from a labs & account audit",
+ "summary": "A page-by-page audit of the labs, avatar tools and account pages turned up rough edges we’ve now smoothed. The standalone Avatar Artifact viewer works on phones — it has a back link to three.ws, links out to Playground, Labs and Agents, a loading state, a designed message if the 3D runtime can’t load, and you can steer the avatar with touch or the arrow keys, not just a mouse. The mic lipsync demo now shows a clear, recoverable message when the microphone is blocked, missing or busy instead of a bare pop-up, and the TTS lipsync demo shows a retry banner if speech generation fails. Sign-in and sign-up no longer leave you on the form after a connection blip, redirect cleanly so Back doesn’t return you to a login screen you already passed, and signup now bounces you onward if you’re already signed in. Forgot-password tells you if your request didn’t reach us instead of always saying it was sent. The Playground rejects oversized or wrong-type model uploads with friendly guidance, the account page’s delegation panel now opens a working console to have one of your agents answer a prompt, and the reputation explorer clearly flags when reviews are written to a test network.",
+ "tags": [
+ "improvement",
+ "fix"
+ ],
+ "link": "/labs"
+ },
{
"date": "2026-06-18",
"title": "Agent lookup now matches the rest of the site and links straight to the agent’s page",
diff --git a/pages/claim-wallet.html b/pages/claim-wallet.html
index ee3dd81a3..437dea9bb 100644
--- a/pages/claim-wallet.html
+++ b/pages/claim-wallet.html
@@ -96,6 +96,17 @@
.cw-cta-btn.secondary { background: none; border: 1px solid var(--line); color: var(--muted); }
.cw-cta-btn.secondary:hover { border-color: var(--cyan); color: var(--cyan); }
.cw-cta-claimed { background: color-mix(in srgb, var(--up) 6%, var(--panel)); border-color: color-mix(in srgb, var(--up) 30%, var(--line)); }
+ .cw-cta-claimed h3 { display: inline-flex; align-items: center; gap: 8px; }
+ .cw-cta-claimed h3::before { content: "✓"; font: 700 13px/1 var(--mono); color: var(--up); width: 22px; height: 22px; display: grid; place-items: center; border-radius: 50%; background: color-mix(in srgb, var(--up) 16%, transparent); border: 1px solid color-mix(in srgb, var(--up) 40%, transparent); }
+
+ /* claim button (signed-in, not-yet-linked state) */
+ .cw-cta-btn[disabled] { opacity: .55; cursor: progress; }
+ .cw-cta-btn.danger { background: color-mix(in srgb, var(--dn) 14%, transparent); border: 1px solid color-mix(in srgb, var(--dn) 45%, transparent); color: var(--dn); }
+ .cw-cta-btn.danger:hover { background: color-mix(in srgb, var(--dn) 22%, transparent); }
+ .cw-claim-msg { font: 600 12px/1.5 var(--mono); margin-top: 12px; }
+ .cw-claim-msg.err { color: var(--dn); }
+ .cw-claim-msg.ok { color: var(--up); }
+ .cw-claim-hint { font: 400 11px/1.5 var(--sans); color: var(--faint); margin: 10px 0 0; }
/* not-found state */
.cw-notfound { margin-top: 40px; text-align: center; padding: 48px 20px; background: var(--panel); border: 1px solid var(--line); border-radius: var(--r); }
diff --git a/pages/club.html b/pages/club.html
index cf3ce78bb..b34757f55 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -1598,10 +1598,14 @@
height: 85vh;
height: 85dvh;
/* Slide the bulk of the panel below the fold; only the
- handle + the "Poles" section peek above. Bumped to
- include both the safe-area inset and the iOS bottom
- bar so the tip buttons stay reachable. */
- transform: translateY(calc(85dvh - 240px));
+ handle + the "Poles" section peek above. The panel grows
+ by env(safe-area-inset-bottom) (padding-bottom below), so
+ the collapsed offset must subtract that same inset —
+ otherwise on a notched phone the home-indicator gutter
+ shoves the peeking tip buttons under the rounded corner.
+ 240px keeps the Poles section visible above the fold. */
+ --club-sheet-peek: 240px;
+ transform: translateY(calc(85dvh - var(--club-sheet-peek) + env(safe-area-inset-bottom, 0px)));
transition: transform 0.28s cubic-bezier(0.2, 0.7, 0.2, 1);
box-shadow: 0 -12px 32px rgba(0, 0, 0, 0.55);
z-index: 12;
@@ -1658,12 +1662,14 @@
font-size: 13px;
}
.club-pole-select {
- min-height: 36px;
+ min-height: 44px;
font-size: 14px;
}
+ /* Leaderboard window pills are interactive — give them the full
+ 44px touch target even though their label text is small. */
.club-lb-tab {
- min-height: 36px;
- padding: 6px 12px;
+ min-height: 44px;
+ padding: 8px 14px;
}
/* The canvas owns all pointer gestures (orbit + pinch). */
#club-canvas { touch-action: none; }
@@ -1680,8 +1686,9 @@
color: var(--text-3);
letter-spacing: 0.1em;
text-transform: uppercase;
- min-height: 36px;
+ min-height: 44px;
}
+ .club-lb-retry { min-height: 44px; }
.club-lb-details > summary::after {
content: '▾';
font-size: 14px;
@@ -1720,6 +1727,11 @@
.club-avatar-btn:active { transform: translateY(1px); }
.club-avatar-btn:focus-visible { outline: 2px solid var(--accent-2); outline-offset: 2px; }
.club-avatar-btn:disabled { opacity: 0.55; cursor: not-allowed; }
+ .club-avatar-btn.needs-reselect {
+ border-color: rgba(245, 166, 35, 0.55);
+ background: rgba(245, 166, 35, 0.08);
+ }
+ .club-avatar-btn.needs-reselect .club-avatar-change { color: #f5a623; }
.club-avatar-chip {
flex: none;
width: 34px;
diff --git a/public/changelog.json b/public/changelog.json
index 44fdbf5a8..95e0039d6 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-18T23:14:18.214Z",
+ "generated_at": "2026-06-18T23:25:57.581Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -26,6 +26,17 @@
"fix"
]
},
+ {
+ "date": "2026-06-18",
+ "type": "update",
+ "title": "Avatar viewer, lipsync tools, sign-in and account polish from a labs & account audit",
+ "summary": "A page-by-page audit of the labs, avatar tools and account pages turned up rough edges we’ve now smoothed. The standalone Avatar Artifact viewer works on phones — it has a back link to three.ws, links out to Playground, Labs and Agents, a loading state, a designed message if the 3D runtime can’t load, and you can steer the avatar with touch or the arrow keys, not just a mouse. The mic lipsync demo now shows a clear, recoverable message when the microphone is blocked, missing or busy instead of a bare pop-up, and the TTS lipsync demo shows a retry banner if speech generation fails. Sign-in and sign-up no longer leave you on the form after a connection blip, redirect cleanly so Back doesn’t return you to a login screen you already passed, and signup now bounces you onward if you’re already signed in. Forgot-password tells you if your request didn’t reach us instead of always saying it was sent. The Playground rejects oversized or wrong-type model uploads with friendly guidance, the account page’s delegation panel now opens a working console to have one of your agents answer a prompt, and the reputation explorer clearly flags when reviews are written to a test network.",
+ "link": "/labs",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-06-18",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 604d85fe8..78c250033 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -22,6 +22,14 @@
<category>fix</category>
<description>An audit of Avatar Studio turned up twelve places where it would throw and stop instead of working: checking whether a trait is NFT-locked, looking up traits and model parts, verifying that your wallet owns a required collection, connecting an Ethereum or Polygon wallet, exporting a GLB, recovering from a failed Solana transaction, decoding KTX2 textures, and loading older VRM0 avatars all hit undefined-variable errors. All twelve are fixed, so trait selection, wallet-ownership gating, EVM wallet connect, model export, and VRM0 loading now run cleanly.</description>
</item>
+ <item>
+ <title>Avatar viewer, lipsync tools, sign-in and account polish from a labs &amp; account audit</title>
+ <link>https://three.ws/labs</link>
+ <guid isPermaLink="false">2026-06-18:Avatar viewer, lipsync tools, sign-in and account polish from a labs &amp; account audit</guid>
+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>A page-by-page audit of the labs, avatar tools and account pages turned up rough edges we’ve now smoothed. The standalone Avatar Artifact viewer works on phones — it has a back link to three.ws, links out to Playground, Labs and Agents, a loading state, a designed message if the 3D runtime can’t load, and you can steer the avatar with touch or the arrow keys, not just a mouse. The mic lipsync demo now shows a clear, recoverable message when the microphone is blocked, missing or busy instead of a bare pop-up, and the TTS lipsync demo shows a retry banner if speech generation fails. Sign-in and sign-up no longer leave you on the form after a connection blip, redirect cleanly so Back doesn’t return you to a login screen you already passed, and signup now bounces you onward if you’re already signed in. Forgot-password tells you if your request didn’t reach us instead of always saying it was sent. The Playground rejects oversized or wrong-type model uploads with friendly guidance, the account page’s delegation panel now opens a working console to have one of your agents answer a prompt, and the reputation explorer clearly flags when reviews are written to a test network.</description>
+ </item>
<item>
<title>Bundle specific skills into your subscription plans</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 96efbd93c..be2e81a66 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-18T23:14:18.161Z",
+ "generated_at": "2026-06-18T23:25:57.491Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/reputation/index.html b/public/reputation/index.html
index 39e3e7c23..aec545c3b 100644
--- a/public/reputation/index.html
+++ b/public/reputation/index.html
@@ -164,6 +164,31 @@
appearance: none;
}
.rep-chain-select:focus { outline: none; border-color: rgba(255,255,255,0.45); }
+ .rep-testnet-tag {
+ display: inline-block;
+ margin-left: 0.4rem;
+ padding: 0.05rem 0.4rem;
+ border-radius: 999px;
+ font-size: 0.625rem;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: #ffd479;
+ background: rgba(255, 196, 0, 0.12);
+ border: 1px solid rgba(255, 196, 0, 0.3);
+ vertical-align: middle;
+ }
+ .rep-testnet-notice {
+ margin: 0.75rem 0 0;
+ padding: 0.7rem 0.85rem;
+ border-radius: 8px;
+ font-size: 0.78rem;
+ line-height: 1.5;
+ color: #ffe1a8;
+ background: rgba(255, 196, 0, 0.07);
+ border: 1px solid rgba(255, 196, 0, 0.22);
+ }
+ .rep-testnet-notice strong { color: #fff; font-weight: 600; }
.rep-search-btn {
padding: 0.875rem;
background: #ffffff;
diff --git a/public/reputation/reputation.js b/public/reputation/reputation.js
index 19c442df7..28997456c 100644
--- a/public/reputation/reputation.js
+++ b/public/reputation/reputation.js
@@ -32,6 +32,7 @@ const EAS_CHAINS = {
},
84532: {
name: 'Base Sepolia',
+ testnet: true,
graphql: 'https://base-sepolia.easscan.org/graphql',
contract: '0x4200000000000000000000000000000000000021',
easscan: 'https://base-sepolia.easscan.org',
@@ -355,9 +356,10 @@ function mountSubmitForm(container, { recipientAddress, chainId }) {
<div class="rep-submit-header">
<div>
<h3 class="rep-submit-title">Write a review</h3>
- <p class="rep-submit-sub">Signed on-chain · permanently public · ${esc(writeChain.name)}</p>
+ <p class="rep-submit-sub">Signed on-chain · permanently public · ${esc(writeChain.name)}${writeChain.testnet ? ' <span class="rep-testnet-tag">testnet</span>' : ''}</p>
</div>
</div>
+ ${writeChain.testnet ? `<div class="rep-testnet-notice" role="note">Reviews are written to <strong>${esc(writeChain.name)}</strong> — a free test network. They're real, signed attestations for trying the flow, not mainnet reputation.</div>` : ''}
<div id="rep-wallet-area">
<button class="rep-connect-btn" id="rep-connect-btn">
@@ -395,7 +397,7 @@ function mountSubmitForm(container, { recipientAddress, chainId }) {
</button>
<p class="rep-submit-note">
Requires ~0.001 ${esc(writeChain.name)} ETH for gas.
- ${writeChain.name === 'Base Sepolia' ? `Get free testnet ETH at <a href="https://www.alchemy.com/faucets/base-sepolia" target="_blank" rel="noopener">Alchemy faucet</a>.` : ''}
+ ${writeChain.testnet ? `Get free testnet ETH at <a href="https://www.alchemy.com/faucets/base-sepolia" target="_blank" rel="noopener">Alchemy faucet</a>.` : ''}
</p>
</div>
</div>
diff --git a/src/claim-wallet.js b/src/claim-wallet.js
index 4a01c2ffe..c3c0e9935 100644
--- a/src/claim-wallet.js
+++ b/src/claim-wallet.js
@@ -20,6 +20,30 @@ async function getSession() {
return _session;
}
+// The signed-in user's linked Solana wallets — the source of truth for whether
+// a wallet is *actually* claimed. A claim is a SIWS-verified `user_wallets`
+// row (chain_type=solana); we read it back here rather than trusting an
+// optimistic "you're signed in, so it's claimed" assumption.
+let _linkedWallets = null;
+async function getLinkedSolanaWallets({ force = false } = {}) {
+ if (_linkedWallets !== null && !force) return _linkedWallets;
+ try {
+ const r = await fetch('/api/auth/wallets', { credentials: 'include' });
+ if (!r.ok) { _linkedWallets = []; return _linkedWallets; }
+ const { wallets } = await r.json();
+ _linkedWallets = (wallets || [])
+ .filter((w) => (w.chain_type || '').toLowerCase() === 'solana')
+ .map((w) => w.address);
+ } catch { _linkedWallets = []; }
+ return _linkedWallets;
+}
+
+// Solana base58 is case-sensitive; compare addresses exactly.
+async function isWalletClaimed(wallet) {
+ const linked = await getLinkedSolanaWallets();
+ return linked.includes(wallet);
+}
+
function esc(s) {
return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
@@ -106,9 +130,15 @@ async function preview(wallet) {
}
const session = await getSession();
- result.innerHTML = cardHtml(data, !!session);
+ const signedIn = !!session?.user;
+ const claimed = signedIn ? await isWalletClaimed(wallet) : false;
- // Wire share button (only present when signed in)
+ result.innerHTML = cardHtml(data, { signedIn, claimed });
+ wireCtaActions(result, data, wallet);
+}
+
+// Wire the share + claim buttons for whichever CTA was rendered.
+function wireCtaActions(result, data, wallet) {
const shareBtn = result.querySelector('#cwShare');
if (shareBtn) {
const traderUrl = `${location.origin}/trader/${encodeURIComponent(wallet)}`;
@@ -124,6 +154,136 @@ async function preview(wallet) {
}
});
}
+
+ const claimBtn = result.querySelector('#cwClaim');
+ if (claimBtn) {
+ claimBtn.addEventListener('click', () => claimWallet(wallet, result, data));
+ }
+}
+
+// ── Real claim: link the wallet to the signed-in account via SIWS ───────────────
+// Claiming a wallet means proving you control its keypair. We drive the same
+// signature-verified link flow the dashboard uses:
+// POST /api/auth/wallets/nonce-solana → sign the message → POST link-solana.
+// On success the wallet becomes a `user_wallets` row owned by the session user,
+// and /api/auth/wallets reflects it — i.e. the round-trip is real, not optimistic.
+
+function detectSolanaProvider() {
+ if (typeof window === 'undefined') return null;
+ return window.phantom?.solana || window.solana || window.backpack || window.solflare || null;
+}
+
+function setClaimMsg(result, text, tone = '') {
+ let el = result.querySelector('#cwClaimMsg');
+ if (!el) {
+ const cta = result.querySelector('.cw-cta');
+ if (!cta) return;
+ el = document.createElement('p');
+ el.id = 'cwClaimMsg';
+ cta.appendChild(el);
+ }
+ el.className = `cw-claim-msg ${tone}`;
+ el.textContent = text;
+}
+
+async function performLink({ message, signature, takeover }) {
+ const body = { message, signature };
+ if (takeover) body.takeover = true;
+ const res = await fetch('/api/auth/wallets/link-solana', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const data = await res.json().catch(() => ({}));
+ return { res, data };
+}
+
+async function claimWallet(wallet, result, previewData) {
+ const btn = result.querySelector('#cwClaim');
+ if (!btn) return;
+
+ const provider = detectSolanaProvider();
+ if (!provider) {
+ setClaimMsg(result, 'No Solana wallet detected. Install Phantom, Backpack, or Solflare to claim — they prove you control this keypair.', 'err');
+ return;
+ }
+
+ btn.disabled = true;
+ const restore = btn.textContent;
+ btn.textContent = 'Connect wallet…';
+ setClaimMsg(result, '', '');
+
+ try {
+ if (!provider.isConnected) await provider.connect();
+ const connected = provider.publicKey?.toBase58?.() || provider.publicKey?.toString?.();
+ if (!connected) throw new Error('Could not read your wallet public key.');
+
+ // You can only claim the wallet you actually control. If the connected
+ // keypair doesn't match the previewed address, say so plainly.
+ if (connected !== wallet) {
+ setClaimMsg(result, `Your connected wallet (${shortAddr(connected)}) isn't this one. Switch to ${shortAddr(wallet)} in your wallet, then claim again.`, 'err');
+ btn.disabled = false;
+ btn.textContent = restore;
+ return;
+ }
+
+ btn.textContent = 'Requesting message…';
+ const nonceRes = await fetch('/api/auth/wallets/nonce-solana', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ address: wallet, chainId: 'mainnet' }),
+ });
+ const nonceData = await nonceRes.json().catch(() => ({}));
+ if (!nonceRes.ok) throw new Error(nonceData.error_description || nonceData.message || 'Could not start the claim.');
+
+ btn.textContent = 'Sign to claim…';
+ let sigBase64;
+ try {
+ const msgBytes = new TextEncoder().encode(nonceData.message);
+ const { signature } = await provider.signMessage(msgBytes, 'utf8');
+ sigBase64 = btoa(String.fromCharCode(...signature));
+ } catch (err) {
+ if (err?.code === 4001 || /reject|cancel/i.test(err?.message || '')) {
+ setClaimMsg(result, 'Signature cancelled — claim again whenever you’re ready.', 'err');
+ } else {
+ setClaimMsg(result, err?.message || 'Could not sign the claim message.', 'err');
+ }
+ btn.disabled = false;
+ btn.textContent = restore;
+ return;
+ }
+
+ btn.textContent = 'Claiming…';
+ let { res, data } = await performLink({ message: nonceData.message, signature: sigBase64 });
+
+ // Already linked to another account. The signature already proved you
+ // control the keypair, so offer an explicit takeover.
+ if (res.status === 409 && (data.error === 'address_in_use' || data.code === 'address_in_use')) {
+ const confirmed = window.confirm('This wallet is currently claimed by another three.ws account. Your signature proves you control it — move it to this account?');
+ if (!confirmed) {
+ setClaimMsg(result, 'Claim cancelled — this wallet stays on its current account.', 'err');
+ btn.disabled = false;
+ btn.textContent = restore;
+ return;
+ }
+ btn.textContent = 'Transferring…';
+ ({ res, data } = await performLink({ message: nonceData.message, signature: sigBase64, takeover: true }));
+ }
+
+ if (!res.ok) throw new Error(data.error_description || data.message || `Claim failed (HTTP ${res.status}).`);
+
+ // Real success: re-read linked wallets and re-render in the claimed state.
+ await getLinkedSolanaWallets({ force: true });
+ result.innerHTML = cardHtml(previewData, { signedIn: true, claimed: true });
+ wireCtaActions(result, previewData, wallet);
+ setClaimMsg(result, data.transferred ? 'Moved to your account — your Trader Card is live.' : 'Claimed — your Trader Card is live.', 'ok');
+ } catch (err) {
+ setClaimMsg(result, err?.message || 'Could not claim this wallet. Try again.', 'err');
+ btn.disabled = false;
+ btn.textContent = restore;
+ }
}
// ── Card HTML ─────────────────────────────────────────────────────────────────
@@ -138,7 +298,8 @@ const LABEL_COPY = {
unproven: 'Unproven',
};
-function cardHtml({ wallet, profile, coins, summary }, isSignedIn = false) {
+function cardHtml({ wallet, profile, coins, summary }, state = {}) {
+ const { signedIn = false, claimed = false } = state;
const label = profile?.label || 'unproven';
const labelTxt = LABEL_COPY[label] || label;
const shortW = shortAddr(wallet);
@@ -183,17 +344,34 @@ function cardHtml({ wallet, profile, coins, summary }, isSignedIn = false) {
const loginUrl = `/login?next=${encodeURIComponent(`/claim-wallet?wallet=${encodeURIComponent(wallet)}`)}`;
const traderUrl = `/trader/${encodeURIComponent(wallet)}`;
- const ctaHtml = isSignedIn
- ? `<div class="cw-cta cw-cta-claimed">
+ let ctaHtml;
+ if (claimed) {
+ // Verified-claimed: the wallet is a SIWS-linked row on this account.
+ ctaHtml = `<div class="cw-cta cw-cta-claimed">
<h3>Your Trader Card is live</h3>
- <p>Share your track record publicly. Anyone can follow your trades and copy your entries
- from their own wallet — you earn a performance fee when they profit.</p>
+ <p>This wallet is verified and linked to your account. Share your track record publicly —
+ anyone can follow your trades and copy your entries from their own wallet, and you earn
+ a performance fee when they profit.</p>
<div class="cw-cta-btns">
<a href="${esc(traderUrl)}" class="cw-cta-btn primary">View your Trader Card →</a>
<button type="button" class="cw-cta-btn secondary" id="cwShare">Share ↗</button>
</div>
- </div>`
- : `<div class="cw-cta">
+ </div>`;
+ } else if (signedIn) {
+ // Signed in but not yet linked — offer the real, signature-verified claim.
+ ctaHtml = `<div class="cw-cta">
+ <h3>This is your track record — claim it</h3>
+ <p>Sign a message with this wallet to prove you control it and publish it as your official
+ three.ws Trader Card. Your history becomes provable, shareable, and open for followers
+ to copy — and you earn a performance fee on their profits.</p>
+ <div class="cw-cta-btns">
+ <button type="button" class="cw-cta-btn primary" id="cwClaim">Claim this wallet →</button>
+ <a href="${esc(traderUrl)}" class="cw-cta-btn secondary">Preview the public card</a>
+ </div>
+ <p class="cw-claim-hint">You’ll sign a free, gasless message in Phantom, Backpack, or Solflare — no transaction, no approval to spend.</p>
+ </div>`;
+ } else {
+ ctaHtml = `<div class="cw-cta">
<h3>This is your track record — own it</h3>
<p>Sign in to publish this as your official three.ws Trader Card. Your history becomes provable,
shareable, and open for followers to copy — and you earn a performance fee on their profits.</p>
@@ -202,6 +380,7 @@ function cardHtml({ wallet, profile, coins, summary }, isSignedIn = false) {
<a href="/leaderboard" class="cw-cta-btn secondary">See the leaderboard</a>
</div>
</div>`;
+ }
return `<div class="cw-card">
<div class="cw-card-head">
diff --git a/src/club.js b/src/club.js
index 35990066d..053415c3a 100644
--- a/src/club.js
+++ b/src/club.js
@@ -1908,6 +1908,16 @@ function markAvatarReselect(poleId, message) {
setStatus(message, { kind: 'warn' });
}
+// Clear the re-select prompt once a look loads successfully.
+function clearAvatarReselect(poleId) {
+ const btn = poleCardEls.get(poleId)?.querySelector('.club-avatar-btn');
+ if (!btn || !btn.classList.contains('needs-reselect')) return;
+ btn.classList.remove('needs-reselect');
+ btn.removeAttribute('title');
+ const change = btn.querySelector('.club-avatar-change');
+ if (change) change.textContent = 'Change avatar';
+}
+
function renderPoles() {
if (!polesPanel) return;
polesPanel.innerHTML = '';
diff --git a/src/dashboard-next/pages/account.js b/src/dashboard-next/pages/account.js
index 8279dadbb..b9c3c2615 100644
--- a/src/dashboard-next/pages/account.js
+++ b/src/dashboard-next/pages/account.js
@@ -781,11 +781,11 @@ function openDelegationConsole(host, preselectAgentId) {
<form data-deleg-form style="margin-top:14px;border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm);padding:16px;display:flex;flex-direction:column;gap:12px">
<div style="display:flex;flex-direction:column;gap:6px">
<label style="font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.04em">Delegate to</label>
- <select data-deleg-agent class="dn-input" style="width:100%">${options}</select>
+ <select data-deleg-agent style="width:100%;background:rgba(255,255,255,0.04);border:1px solid var(--nxt-stroke-strong);border-radius:6px;padding:8px 10px;color:var(--nxt-ink);font-size:13.5px;font-family:inherit">${options}</select>
</div>
<div style="display:flex;flex-direction:column;gap:6px">
<label style="font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:0.04em">Message</label>
- <textarea data-deleg-message class="dn-input" rows="3" maxlength="8000" placeholder="What should this agent answer on your behalf?" style="width:100%;resize:vertical;font-family:inherit"></textarea>
+ <textarea data-deleg-message rows="3" maxlength="8000" placeholder="What should this agent answer on your behalf?" style="width:100%;resize:vertical;background:rgba(255,255,255,0.04);border:1px solid var(--nxt-stroke-strong);border-radius:6px;padding:8px 10px;color:var(--nxt-ink);font-size:13.5px;font-family:inherit;line-height:1.55"></textarea>
</div>
<div style="display:flex;gap:10px;align-items:center">
<button class="dn-btn primary" type="submit" data-deleg-run>Run delegation</button>
diff --git a/src/play-agent-wallet.js b/src/play-agent-wallet.js
index c3fdad06c..58c9f77dc 100644
--- a/src/play-agent-wallet.js
+++ b/src/play-agent-wallet.js
@@ -27,12 +27,12 @@ import { CC_AVATAR_KEY } from './game/play-handoff.js';
// ── config ──────────────────────────────────────────────────────────────────
const params = new URLSearchParams(location.search);
-// The agent-wallet bridge (scripts/agent-wallet-x402-bridge.mjs) holds a signing
-// key in the developer's terminal session, so it only ever runs locally — there
-// is no hosted production equivalent. Default to the local bridge in dev (or when
-// the host is literal localhost); in production stay empty so we surface the
-// designed "bridge offline" banner instead of hammering a dead 127.0.0.1 socket.
-function defaultBridgeUrl() {
+// The local bridge (scripts/agent-wallet-x402-bridge.mjs) holds a signing key in
+// a developer's terminal, so it only runs on localhost. In production we use the
+// hosted bridge (api/agent-wallet-bridge) which signs with the platform-held
+// payer wallet — gated behind sign-in + spending caps — so real visitors can pay
+// too. Prefer an explicit ?bridge= override, then a local dev bridge, else hosted.
+function localBridgeUrl() {
const explicit = params.get('bridge');
if (explicit) return explicit.replace(/\/$/, '');
let isDev = false;
@@ -41,7 +41,13 @@ function defaultBridgeUrl() {
const isLocalHost = host === 'localhost' || host === '127.0.0.1';
return isDev || isLocalHost ? 'http://127.0.0.1:4402' : '';
}
-const BRIDGE_URL = defaultBridgeUrl();
+const LOCAL_BRIDGE = localBridgeUrl();
+const HOSTED = !LOCAL_BRIDGE;
+const BRIDGE_BASE = LOCAL_BRIDGE || '/api/agent-wallet-bridge';
+const BRIDGE_URL = BRIDGE_BASE; // always set — hosted in prod, local in dev
+const statusUrl = () => (HOSTED ? `${BRIDGE_BASE}?status=1` : `${BRIDGE_BASE}/status`);
+const quoteUrl = (qs) => (HOSTED ? `${BRIDGE_BASE}?quote=1&${qs}` : `${BRIDGE_BASE}/quote?${qs}`);
+const payUrl = () => (HOSTED ? `${BRIDGE_BASE}?pay=1` : `${BRIDGE_BASE}/pay`);
// The paid endpoint the avatar buys from. three.ws prod by default so the
// payment settles against the live facilitator even from local dev.
const ENDPOINT = params.get('endpoint') || 'https://three.ws/api/x402/crypto-intel';
@@ -496,7 +502,11 @@ renderStages();
function renderError() {
const el = $('flowError');
if (!live.error) { el.classList.remove('show'); return; }
- el.innerHTML = `<div class="b-head">Payment failed — no funds moved</div>${escapeHtml(live.error.message)}`;
+ if (live.error.needsAuth) {
+ el.innerHTML = `<div class="b-head">Sign in to pay</div>${escapeHtml(live.error.message)} <a href="/login" style="color:var(--acc);text-decoration:underline">Sign in →</a>`;
+ } else {
+ el.innerHTML = `<div class="b-head">Payment failed — no funds moved</div>${escapeHtml(live.error.message)}`;
+ }
el.classList.add('show');
}
function escapeHtml(s) {
@@ -543,19 +553,8 @@ function updatePayButton() {
// ── bridge client ───────────────────────────────────────────────────────────
async function refreshStatus() {
- if (!BRIDGE_URL) {
- // Production / no local bridge configured: skip the doomed socket and go
- // straight to the offline banner that explains how to run the bridge.
- live.bridge = 'offline';
- $('bridgeOffline').classList.add('show');
- $('lowBalance').classList.remove('show');
- $('wBal').innerHTML = '—<small>USD</small>';
- updatePayButton();
- renderStages();
- return;
- }
try {
- const r = await fetch(`${BRIDGE_URL}/status`, { signal: AbortSignal.timeout(4000) });
+ const r = await fetch(statusUrl(), { signal: AbortSignal.timeout(8000) });
if (!r.ok) throw new Error('HTTP ' + r.status);
const data = await r.json();
live.bridge = 'online';
@@ -580,9 +579,8 @@ async function refreshStatus() {
async function loadQuote() {
try {
- if (!BRIDGE_URL) throw new Error('no local bridge');
const qs = new URLSearchParams({ endpoint: ENDPOINT, method: 'POST', body: JSON.stringify({ topic: activeTopic }) });
- const r = await fetch(`${BRIDGE_URL}/quote?${qs}`, { signal: AbortSignal.timeout(8000) });
+ const r = await fetch(quoteUrl(qs.toString()), { signal: AbortSignal.timeout(8000) });
if (!r.ok) throw new Error('HTTP ' + r.status);
const q = await r.json();
if (!q.ok) throw new Error(q.error || 'quote failed');
@@ -622,11 +620,20 @@ async function pay() {
await walkTo(PAY_SPOT);
try {
- const res = await fetch(`${BRIDGE_URL}/pay`, {
+ const res = await fetch(payUrl(), {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'text/event-stream' },
body: JSON.stringify({ endpoint: ENDPOINT, method: 'POST', body: { topic: activeTopic } }),
});
+ if (res.status === 401) {
+ // Hosted bridge: real spend needs a signed-in session.
+ live.error = { stage: 'challenge', message: 'Sign in to let your agent wallet make a real payment.', needsAuth: true };
+ throw new Error('auth required');
+ }
+ if (res.status === 429) {
+ live.error = { stage: 'challenge', message: 'Too many payment attempts — try again in a moment.' };
+ throw new Error('rate limited');
+ }
if (!res.ok || !res.body) throw new Error(`bridge /pay failed: HTTP ${res.status}`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
@@ -648,7 +655,8 @@ async function pay() {
throw new Error('payment stream ended without a settlement');
}
} catch (err) {
- live.error = { stage: live.stage || 'challenge', message: err.message };
+ // Keep a more specific error (e.g. needs-auth / rate-limited) if one was set.
+ if (!live.error) live.error = { stage: live.stage || 'challenge', message: err.message };
} finally {
live.paying = false;
}
diff --git a/src/watchlist.js b/src/watchlist.js
index 4262a1a8b..683591cdc 100644
--- a/src/watchlist.js
+++ b/src/watchlist.js
@@ -189,7 +189,10 @@ function maybeFire(mint, symbol, newTier, oldTier) {
const body = `Oracle scored this coin ${newTier} on three.ws`;
try {
const n = new Notification(title, { body, icon: '/favicon-32x32.png', tag: mint });
- n.onclick = () => { window.focus(); window.open(`/oracle?mint=${mint}`, '_blank'); n.close(); };
+ // Navigate the watchlist tab itself rather than spawning an orphaned new
+ // tab — keeps the browser Back button as a reliable return path to the
+ // watchlist once the user is done reading the Oracle breakdown.
+ n.onclick = () => { window.focus(); location.href = `/oracle?mint=${encodeURIComponent(mint)}`; n.close(); };
} catch { /* Notification blocked mid-flight */ }
}
diff --git a/tests/api/http-params.test.js b/tests/api/http-params.test.js
new file mode 100644
index 000000000..28c4115fc
--- /dev/null
+++ b/tests/api/http-params.test.js
@@ -0,0 +1,71 @@
+// Unit tests for the shared pagination/query helpers in api/_lib/http-params.js.
+// These back the `limit`/`offset` clamps used across the public API surface, so
+// the coercion + clamping contract is asserted directly here rather than
+// per-endpoint.
+
+import { describe, it, expect } from 'vitest';
+import { clampInt, parseLimit, parseOffset } from '../../api/_lib/http-params.js';
+
+describe('clampInt', () => {
+ it('parses and clamps within [min, max]', () => {
+ expect(clampInt('30', { max: 50, fallback: 30 })).toBe(30);
+ expect(clampInt('999', { max: 50, fallback: 30 })).toBe(50);
+ expect(clampInt('0', { max: 50, fallback: 30 })).toBe(1); // default min = 1
+ expect(clampInt('-5', { max: 50, fallback: 30 })).toBe(1);
+ });
+
+ it('falls back to `fallback` on missing / non-numeric input (no NaN leak)', () => {
+ expect(clampInt(null, { max: 50, fallback: 30 })).toBe(30);
+ expect(clampInt(undefined, { max: 50, fallback: 30 })).toBe(30);
+ expect(clampInt('', { max: 50, fallback: 30 })).toBe(30);
+ expect(clampInt('abc', { max: 50, fallback: 30 })).toBe(30);
+ expect(clampInt('12px', { max: 50, fallback: 30 })).toBe(12); // parseInt is lenient by design
+ });
+
+ it('accepts numeric input directly', () => {
+ expect(clampInt(7, { max: 50, fallback: 30 })).toBe(7);
+ expect(clampInt(7.9, { max: 50, fallback: 30 })).toBe(7); // numeric input is truncated to an int
+ });
+
+ it('honours a custom min', () => {
+ expect(clampInt('0', { min: 0, max: 50, fallback: 10 })).toBe(0);
+ });
+
+ it('throws when max/fallback are not finite (programmer error)', () => {
+ expect(() => clampInt('1', { fallback: 5 })).toThrow(TypeError);
+ expect(() => clampInt('1', { max: 5 })).toThrow(TypeError);
+ });
+});
+
+describe('parseLimit', () => {
+ it('reads from a URLSearchParams source', () => {
+ const params = new URLSearchParams('limit=42');
+ expect(parseLimit(params, { max: 60, fallback: 24 })).toBe(42);
+ });
+
+ it('reads from a plain object source', () => {
+ expect(parseLimit({ limit: '500' }, { max: 60, fallback: 24 })).toBe(60);
+ });
+
+ it('falls back when the key is absent', () => {
+ expect(parseLimit(new URLSearchParams(''), { max: 60, fallback: 24 })).toBe(24);
+ expect(parseLimit(null, { max: 60, fallback: 24 })).toBe(24);
+ });
+
+ it('supports a custom key', () => {
+ expect(parseLimit({ count: '7' }, { max: 60, fallback: 24, key: 'count' })).toBe(7);
+ });
+});
+
+describe('parseOffset', () => {
+ it('floors at 0 and tolerates junk', () => {
+ expect(parseOffset(new URLSearchParams('offset=15'))).toBe(15);
+ expect(parseOffset(new URLSearchParams('offset=-3'))).toBe(0);
+ expect(parseOffset(new URLSearchParams(''))).toBe(0);
+ expect(parseOffset({ offset: 'abc' })).toBe(0);
+ });
+
+ it('respects a max bound when provided', () => {
+ expect(parseOffset({ offset: '9999' }, { max: 1000 })).toBe(1000);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 3cd2930bf..8707d0d02 100644
--- a/vercel.json
+++ b/vercel.json
@@ -3488,6 +3488,16 @@
"src": "/a/me/?",
"dest": "/a-me.html"
},
+ {
+ "src": "/a-embed",
+ "headers": {
+ "content-security-policy": "frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors",
+ "x-content-type-options": "nosniff",
+ "referrer-policy": "strict-origin-when-cross-origin",
+ "permissions-policy": "microphone=(self), camera=(self), xr-spatial-tracking=*"
+ },
+ "dest": "/a-embed.html"
+ },
{
"src": "/a/(\\d+)/(\\d+)/embed",
"headers": {