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
test(play): sweep the world's failure modes and run a real two-client session
nirholasd99791280304
diff --git a/public/accessories/thumbs/laurel-meetup.png b/public/accessories/thumbs/laurel-meetup.pngnew file mode 100644index 000000000..1afed2592Binary files /dev/null and b/public/accessories/thumbs/laurel-meetup.png differdiff --git a/scripts/audit-play-failure-modes.mjs b/scripts/audit-play-failure-modes.mjsnew file mode 100644index 000000000..22a175580--- /dev/null+++ b/scripts/audit-play-failure-modes.mjs@@ -0,0 +1,419 @@+#!/usr/bin/env node+/**+ * /play failure-mode audit — deliberate failure injection in a real browser.+ *+ * `npm run audit:console` proves /play is clean when everything works. This one+ * proves it stays usable when things break, which is what an event crowd will+ * actually hit: no session, ad blockers eating IPFS, a dead GLB, a 500 on the+ * auth nonce, an expired pass mid-session, and hostile query strings pasted from+ * a shared link.+ *+ * Each scenario drives a fresh browser context against /play with specific+ * network routes aborted or rewritten, then asserts:+ *+ * • the boot loader always resolves — either the world opens, or a designed+ * error card with a recovery action replaces it. Never a stuck spinner.+ * • no uncaught exception, and no console error/warning from our code+ * (judged against the shared filter in lib/console-noise.mjs)+ * • hostile `name` / `symbol` / `image` params never execute script and never+ * escape a CSS `url()` into the surrounding style attribute+ * • the world still renders a real avatar when its GLB or coin art is blocked+ *+ * Usage:+ * node scripts/audit-play-failure-modes.mjs # every scenario+ * node scripts/audit-play-failure-modes.mjs xss css-inject # named scenarios+ * node scripts/audit-play-failure-modes.mjs --list+ * HEADFUL=1 node scripts/audit-play-failure-modes.mjs xss # watch it run+ * BASE_URL=https://three.ws node scripts/audit-play-failure-modes.mjs+ *+ * Reuses a dev server already on :3000, otherwise spawns an ephemeral Vite. The+ * dev server proxies /api/* to https://three.ws, so the auth gate, the coin feed+ * and the avatar registry are all real.+ *+ * Exit code 1 on any failed assertion, so this is CI/pre-event gateable.+ */++import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createServer } from 'node:net';+import { spawn } from 'node:child_process';+import { get as httpGet } from 'node:http';+import { chromium } from 'playwright';+import { isIgnorableConsole } from './lib/console-noise.mjs';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++const C = {+ g: (s) => `\x1b[32m${s}\x1b[0m`,+ r: (s) => `\x1b[31m${s}\x1b[0m`,+ y: (s) => `\x1b[33m${s}\x1b[0m`,+ d: (s) => `\x1b[2m${s}\x1b[0m`,+ b: (s) => `\x1b[1m${s}\x1b[0m`,+ c: (s) => `\x1b[36m${s}\x1b[0m`,+};++// The canonical $THREE community deep link (docs/event-readiness/README.md).+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const THREE_IMAGE =+ '/api/img?url=https%3A%2F%2Fipfs.io%2Fipfs%2Fbafybeihe22b5sxr3ihnxt7pregfieyteqvubqhik3j3y4bbx243xlqjw3q&seed=' ++ THREE_MINT;+const CANONICAL = `/play?coin=${THREE_MINT}&name=three.ws&symbol=three&image=${encodeURIComponent(THREE_IMAGE)}`;++// How long to let the world settle before asserting. The boot loader carries its+// own 6s avatar safety net and a 45s watchdog, so 20s is past every designed+// resolution point while staying well inside the watchdog.+const SETTLE_MS = 20_000;++// ── Hostile inputs ───────────────────────────────────────────────────────────+// Every payload calls the same sentinel, so one flag proves script execution+// regardless of which vector fired.+const XSS_PAYLOADS = {+ name: '"><img src=x onerror="window.__xss=1"><svg onload="window.__xss=1">',+ symbol: '\'"--></style></script><script>window.__xss=1</script>',+ // Breaks out of background-image:url("<here>") in a style attribute.+ cssImage: 'x");position:fixed;inset:0;z-index:2147483647;background:red;--x:url("y',+};++// ── Scenarios ────────────────────────────────────────────────────────────────+// `routes` entries run through page.route(); `expect` runs in Node with the+// collected observations.++/** Abort every request whose URL matches, as an ad blocker or a dead host would. */+const block = (re, code = 'blockedbyclient') => ({ match: re, handler: (route) => route.abort(code) });+/** Answer with a status, as a throttled or broken upstream would. */+const status = (re, s, body = '{"error":"injected"}') => ({+ match: re,+ handler: (route) => route.fulfill({ status: s, contentType: 'application/json', body }),+});++const SCENARIOS = [+ {+ id: 'anon',+ title: 'Signed out, everything healthy',+ url: CANONICAL,+ },+ {+ id: 'no-params',+ title: 'Bare /play — no query string at all',+ url: '/play',+ },+ {+ id: 'garbage-coin',+ title: 'Garbage ?coin= mint',+ url: '/play?coin=not-a-real-mint-%F0%9F%92%A5%3Cscript%3E',+ },+ {+ id: 'xss',+ title: 'XSS attempt in ?name= and ?symbol=',+ url:+ `/play?coin=${THREE_MINT}` ++ `&name=${encodeURIComponent(XSS_PAYLOADS.name)}` ++ `&symbol=${encodeURIComponent(XSS_PAYLOADS.symbol)}`,+ },+ {+ id: 'css-inject',+ title: 'CSS breakout in ?image=',+ url: `/play?coin=${THREE_MINT}&name=three.ws&symbol=three&image=${encodeURIComponent(XSS_PAYLOADS.cssImage)}`,+ },+ {+ id: 'oversized-image',+ title: 'Oversized ?image= URL (8 KB)',+ url: `/play?coin=${THREE_MINT}&name=three.ws&symbol=three&image=${encodeURIComponent('https://example.com/' + 'a'.repeat(8192) + '.png')}`,+ },+ {+ id: 'block-coin-art',+ title: 'Coin art blocked (ad blocker on IPFS + /api/img)',+ url: CANONICAL,+ routes: [block(/\/api\/img\b/), block(/ipfs\.io|dweb\.link|flk-ipfs\.xyz|arweave\.net/)],+ },+ {+ id: 'block-glb',+ title: 'Every avatar GLB blocked',+ url: CANONICAL,+ routes: [block(/\.(glb|vrm)(\?|$)/i)],+ },+ {+ id: 'nonce-500',+ title: 'Auth gate unreachable (/api/play/nonce → 500)',+ url: CANONICAL,+ routes: [status(/\/api\/play\/nonce/, 500)],+ },+ {+ id: 'nonce-429',+ title: 'Auth gate rate-limited (/api/play/nonce → 429)',+ url: CANONICAL,+ routes: [status(/\/api\/play\/nonce/, 429)],+ },+ {+ id: 'nonce-offline',+ title: 'Auth gate offline (/api/play/nonce aborted)',+ url: CANONICAL,+ routes: [block(/\/api\/play\/nonce/, 'connectionfailed')],+ },+ {+ id: 'feed-down',+ title: 'Coin feed down (/api/pump/* → 500)',+ url: '/play',+ routes: [status(/\/api\/pump\//, 500)],+ },+ {+ id: 'expired-pass',+ title: 'Expired play pass already in sessionStorage',+ url: CANONICAL,+ // Seed a pass that expired an hour ago. loadStoredPass() must discard it+ // rather than hand a dead token to the room join.+ init: `sessionStorage.setItem('cc-play-pass', JSON.stringify({+ wallet: 'SEEDEDwallet1111111111111111111111111111111',+ playPass: 'expired.pass.token',+ mint: '${THREE_MINT}',+ balance: 1,+ symbol: 'three',+ expiresAt: new Date(Date.now() - 3600e3).toISOString(),+ }));`,+ expect: (o) => (o.storedPass === null ? null : 'expired pass survived in sessionStorage'),+ },+ {+ id: 'corrupt-pass',+ title: 'Corrupt play pass in sessionStorage',+ url: CANONICAL,+ init: `sessionStorage.setItem('cc-play-pass', '{not json at all');`,+ },+ {+ id: 'storage-denied',+ title: 'localStorage and sessionStorage throw (private mode / blocked cookies)',+ url: CANONICAL,+ // Mirrors Safari private mode and hardened-privacy extensions: the object+ // exists but every access throws. Every storage read in /play is wrapped;+ // this proves it.+ init: `+ const boom = () => { throw new DOMException('denied', 'SecurityError'); };+ for (const k of ['localStorage', 'sessionStorage']) {+ Object.defineProperty(window, k, {+ configurable: true,+ get: () => ({ getItem: boom, setItem: boom, removeItem: boom, clear: boom, key: boom, length: 0 }),+ });+ }`,+ },+];++// ── Dev server (same contract as audit-console.mjs) ──────────────────────────+const PROBE_BASE = 'http://127.0.0.1:3000';++function probe(url, timeoutMs = 2000) {+ return new Promise((resolve) => {+ const req = httpGet(url, (res) => { res.resume(); resolve(res.statusCode || 0); });+ req.setTimeout(timeoutMs, () => req.destroy());+ req.on('error', () => resolve(0));+ });+}++function freePort() {+ return new Promise((resolve, reject) => {+ const srv = createServer();+ srv.unref();+ srv.on('error', reject);+ srv.listen(0, () => { const { port } = srv.address(); srv.close(() => resolve(port)); });+ });+}++async function startServer() {+ if (process.env.BASE_URL) {+ const base = process.env.BASE_URL.replace(/\/$/, '');+ console.log(C.d(` targeting ${base}`));+ // A local Vite still needs its dep optimizer warmed; a deployed origin does not.+ if (/^https?:\/\/(localhost|127\.0\.0\.1)/.test(base)) await warmup(base);+ return { base, stop: async () => {} };+ }+ if (await probe(`${PROBE_BASE}/`, 5000)) {+ console.log(C.d(' reusing dev server on :3000'));+ await warmup('http://localhost:3000');+ return { base: 'http://localhost:3000', stop: async () => {} };+ }+ const port = await freePort();+ const child = spawn(join(ROOT, 'node_modules', '.bin', 'vite'), ['--port', String(port), '--strictPort'], {+ cwd: ROOT, stdio: process.env.LOG_ALL ? 'inherit' : 'ignore', env: process.env,+ });+ const deadline = Date.now() + 90_000;+ process.stdout.write(` starting Vite on :${port} `);+ while (Date.now() < deadline) {+ if (child.exitCode != null) throw new Error(`vite exited early (code ${child.exitCode})`);+ if (await probe(`http://127.0.0.1:${port}/`, 2000)) { process.stdout.write('\n'); break; }+ process.stdout.write('.');+ await new Promise((r) => setTimeout(r, 500));+ }+ if (Date.now() >= deadline) { child.kill('SIGKILL'); throw new Error('vite did not become ready within 90s'); }+ await warmup(`http://localhost:${port}`);+ return { base: `http://localhost:${port}`, stop: async () => child.kill('SIGTERM') };+}++// Pre-bundle /play's deps so the first scenario doesn't eat the optimizer reload.+async function warmup(base) {+ process.stdout.write(' warming Vite dep optimizer ');+ for (const p of ['/', '/play']) { await fetch(`${base}${p}`).catch(() => {}); process.stdout.write('.'); }+ await new Promise((r) => setTimeout(r, 8000));+ process.stdout.write('\n');+}++// ── One scenario ─────────────────────────────────────────────────────────────++async function runScenario(browser, base, sc) {+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });+ const consoleIssues = [];+ const pageErrors = [];++ // Sentinel + payload-echo harness, installed before any page script runs.+ await context.addInitScript(`+ window.__xss = 0;+ window.addEventListener('unhandledrejection', (e) => {+ (window.__rejections = window.__rejections || []).push(String(e.reason?.message || e.reason));+ });+ `);+ if (sc.init) await context.addInitScript(sc.init);++ const page = await context.newPage();+ // A payload that fires window.alert would hang the run; auto-dismiss and record.+ page.on('dialog', async (d) => { pageErrors.push(`dialog: ${d.type()} ${d.message()}`); await d.dismiss(); });+ page.on('console', (msg) => {+ const type = msg.type();+ if (type !== 'error' && type !== 'warning') return;+ const text = msg.text();+ if (isIgnorableConsole(text)) return;+ consoleIssues.push(`${type}: ${text}`);+ });+ page.on('pageerror', (err) => {+ const m = String(err?.message || err);+ if (!isIgnorableConsole(m)) pageErrors.push(`pageerror: ${m}`);+ });++ for (const r of sc.routes || []) await page.route(r.match, r.handler);++ const findings = [];+ try {+ await page.goto(base + sc.url, { waitUntil: 'domcontentloaded', timeout: 60_000 });+ } catch (err) {+ findings.push(`navigation failed: ${err.message}`);+ await context.close();+ return { findings, consoleIssues, pageErrors };+ }++ await page.waitForTimeout(SETTLE_MS);++ const o = await page.evaluate(() => {+ const loader = document.getElementById('kx-loading');+ const hidden = !loader || loader.classList.contains('kx-hidden');+ const errorCard = !!document.querySelector('.kx-boot-error');+ const gate = document.querySelector('.pg-root');+ // Any element whose inline style carries a declaration we never author+ // after a url() means the CSS breakout landed.+ const styleBreakout = Array.from(document.querySelectorAll('[style]'))+ .map((n) => n.getAttribute('style') || '')+ .filter((s) => /url\(["'][^"']*["']\)\s*;\s*\S/.test(s) || /position:\s*fixed;inset:0;z-index:2147483647/.test(s));+ let stored = null;+ try { stored = sessionStorage.getItem('cc-play-pass'); } catch { stored = null; }+ const rig = window.__CC__?.localRig;+ return {+ loaderResolved: hidden || errorCard,+ errorCard,+ errorCardText: errorCard ? (document.querySelector('.kx-boot-error-msg')?.textContent || '') : '',+ errorCardHasAction: errorCard ? !!document.querySelector('.kx-boot-error-btn') : true,+ gateVisible: !!gate,+ gateState: gate?.querySelector('.pg-card')?.getAttribute('data-state') || null,+ xss: window.__xss === 1,+ injectedScripts: document.querySelectorAll('script[src*="onerror"], img[onerror]').length,+ styleBreakout,+ storedPass: stored,+ phase: window.__CC__?.phase || null,+ hasScene: !!window.__CC__?.scene,+ hasLocalRig: !!rig,+ rigVisible: rig ? rig.visible !== false : null,+ // A rendered avatar has at least one skinned or regular mesh under it.+ rigMeshes: rig ? (() => { let n = 0; rig.traverse((x) => { if (x.isMesh || x.isSkinnedMesh) n++; }); return n; })() : 0,+ bodyText: (document.body.innerText || '').slice(0, 400),+ rejections: window.__rejections || [],+ };+ });++ // ── Universal assertions ────────────────────────────────────────────────+ if (o.xss) findings.push('SCRIPT EXECUTED from a query parameter (window.__xss set)');+ if (o.injectedScripts) findings.push(`${o.injectedScripts} injected script/img[onerror] node(s) in the DOM`);+ if (o.styleBreakout.length) {+ findings.push(`CSS breakout from a query parameter into a style attribute: ${JSON.stringify(o.styleBreakout[0].slice(0, 160))}`);+ }+ if (!o.loaderResolved) findings.push('boot loader never resolved — stuck spinner, no error card');+ if (o.errorCard && !o.errorCardHasAction) findings.push('error card has no recovery action');+ if (o.errorCard && !o.errorCardText.trim()) findings.push('error card has no message');+ for (const r of o.rejections) if (!isIgnorableConsole(r)) findings.push(`unhandledrejection: ${r}`);++ // A world that opened must show a real avatar, never an empty rig.+ if (o.phase === 'world' && o.hasLocalRig && o.rigMeshes === 0) {+ findings.push('local avatar rig has no meshes — invisible player');+ }++ if (sc.expect) { const extra = sc.expect(o); if (extra) findings.push(extra); }++ await context.close();+ return { findings, consoleIssues, pageErrors, o };+}++// ── Main ─────────────────────────────────────────────────────────────────────++async function main() {+ const args = process.argv.slice(2);+ if (args.includes('--list')) {+ for (const s of SCENARIOS) console.log(`${s.id.padEnd(18)} ${s.title}`);+ return 0;+ }+ const wanted = args.filter((a) => !a.startsWith('--'));+ const scenarios = wanted.length ? SCENARIOS.filter((s) => wanted.includes(s.id)) : SCENARIOS;+ if (!scenarios.length) { console.error(C.r(`no scenario matched: ${wanted.join(', ')}`)); return 1; }++ console.log(C.b('\n╔══ /play failure-mode audit ═════════════════════════════════╗'));+ console.log(` ${scenarios.length} scenario(s) × 1 viewport`);+ console.log(C.b('╚═════════════════════════════════════════════════════════════╝\n'));++ const server = await startServer();+ const browser = await chromium.launch({ headless: !process.env.HEADFUL });+ const failed = [];++ try {+ for (const sc of scenarios) {+ process.stdout.write(` ${C.c(sc.id.padEnd(18))} ${C.d(sc.title)}\n`);+ const { findings, consoleIssues, pageErrors, o } = await runScenario(browser, server.base, sc);+ const all = [...findings, ...pageErrors, ...consoleIssues];+ if (all.length) {+ failed.push({ sc, all });+ for (const f of all) console.log(` ${C.r('✗')} ${f}`);+ } else {+ const note = o?.errorCard+ ? 'designed error card'+ : o?.gateVisible+ ? `gate: ${o.gateState}`+ : o?.phase === 'world'+ ? `world (${o.rigMeshes} avatar meshes)`+ : `lobby (${o?.phase})`;+ console.log(` ${C.g('✓')} ${C.d(note)}`);+ }+ }+ } finally {+ await browser.close();+ await server.stop();+ }++ console.log(C.b('\n═══════════════ SUMMARY ═══════════════\n'));+ if (!failed.length) {+ console.log(C.g(` ALL ${scenarios.length} FAILURE MODES HANDLED — no stuck loaders, no script execution, clean console.\n`));+ return 0;+ }+ console.log(C.r(` ${failed.length} of ${scenarios.length} scenario(s) failed:\n`));+ for (const { sc, all } of failed) {+ console.log(` ${C.b(sc.id)} — ${sc.title}`);+ for (const f of all) console.log(` ${C.r('•')} ${f}`);+ }+ console.log('');+ return 1;+}++main().then((code) => process.exit(code)).catch((err) => {+ console.error(C.r(`\naudit failed to run: ${err.stack || err.message}\n`));+ process.exit(1);+});diff --git a/scripts/audit-service-wallets.mjs b/scripts/audit-service-wallets.mjsindex ad2e84778..151ab30e0 100644--- a/scripts/audit-service-wallets.mjs+++ b/scripts/audit-service-wallets.mjs@@ -17,10 +17,27 @@import bs58 from 'bs58';import { Keypair, PublicKey } from '@solana/web3.js';-const RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';const ORIGIN = process.env.AUDIT_ORIGIN || 'https://three.ws';+// The lane chain this audit reads balances over. An operator's SOLANA_RPC_URL+// goes first when set, then the keyless free lanes (mirroring+// FREE_KEYLESS_MAINNET in api/_lib/solana/connection.js) so a single throttled+// provider cannot decide what this audit believes about the money.+//+// Why the chain exists at all: on 2026-08-07 every wallet here reported+// SOL=0.0000 because the configured lane was 429ing, and the audit reported+// four "below floor" money emergencies against wallets that were actually+// funded. A balance the audit could not read must never render as a balance of+// zero — see readBalance() below.+const RPC_LANES = [+ process.env.SOLANA_RPC_URL,+ 'https://solana-rpc.publicnode.com',+ 'https://api.mainnet-beta.solana.com',+ 'https://solana.leorpc.com/?api_key=FREE',+ 'https://rpc.magicblock.app/mainnet',+].filter(Boolean);+// Mirrors api/_lib/solana-signers.js SIGNER_SPECS (name, secret env, floor). Kept// inline so the audit runs standalone without importing the app's module graph.const SIGNERS = [@@ -64,17 +81,50 @@ function decodeSecret(raw) {return null;}+// One JSON-RPC call against one lane. Throws on anything that is not a usable+// result, so the caller can fail over instead of reading a throttle as data:+// an HTTP error (429/5xx), a JSON-RPC `error` member (Tatum answers+// paid-tier-only methods that way), or a body with no `result` at all.+async function rpcOn(url, method, params) {+ const r = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ signal: AbortSignal.timeout(15000),+ });+ if (!r.ok) throw new Error(`http_${r.status}`);+ const body = await r.json();+ if (body?.error) throw new Error(String(body.error.message || body.error.code || 'rpc_error'));+ if (!('result' in body)) throw new Error('no_result');+ return body.result;+}++// Walk the lane chain until one answers. Returns the result, or throws with the+// last lane's reason once every lane has refused.async function rpc(method, params) {- const r = await fetch(RPC, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) });- return (await r.json()).result;+ let last = 'no lanes configured';+ for (const url of RPC_LANES) {+ try { return await rpcOn(url, method, params); } catch (e) { last = `${new URL(url).host}: ${e?.message || 'failed'}`; }+ }+ throw new Error(last);}++// A read that failed is `null`, never 0. Every caller must treat null as "not+// known" and refuse to judge it against a floor.async function onchain(addr) {- const bal = await rpc('getBalance', [addr]).catch(() => null);- const sol = (bal?.value || 0) / 1e9;- let usdc = 0;- try { const u = await rpc('getTokenAccountsByOwner', [addr, { mint: USDC }, { encoding: 'jsonParsed' }]); usdc = Number(u?.value?.[0]?.account?.data?.parsed?.info?.tokenAmount?.uiAmountString || 0); } catch {}- return { sol, usdc };+ let sol = null;+ let readError = null;+ try { sol = (await rpc('getBalance', [addr]))?.value / 1e9; } catch (e) { readError = e?.message || 'balance read failed'; }+ if (!Number.isFinite(sol)) { sol = null; readError = readError || 'balance read returned no value'; }+ let usdc = null;+ try {+ const u = await rpc('getTokenAccountsByOwner', [addr, { mint: USDC }, { encoding: 'jsonParsed' }]);+ usdc = Number(u?.value?.[0]?.account?.data?.parsed?.info?.tokenAmount?.uiAmountString || 0);+ } catch { usdc = null; }+ return { sol, usdc, readError };}+const fmtSol = (v) => (v === null ? 'unreadable' : v.toFixed(4));+const fmtUsdc = (v) => (v === null ? 'unreadable' : String(v));function pub(spec) {const raw = process.env[spec.env] || (spec.fb ? process.env[spec.fb] : null);if (!raw) return { configured: false };@@ -90,7 +140,8 @@ function addrOf(spec) {}const flags = [];-console.log(`\nservice-wallet audit · RPC ${RPC} · origin ${ORIGIN}\n${'='.repeat(72)}`);+const blind = [];+console.log(`\nservice-wallet audit · RPC lanes ${RPC_LANES.map((u) => new URL(u).host).join(' → ')} · origin ${ORIGIN}\n${'='.repeat(72)}`);console.log('\nSECRET-BACKED SIGNERS (derived pubkey ← secret env):');const sponsorDerived = {};@@ -99,8 +150,15 @@ for (const s of SIGNERS) {if (!p.configured) { console.log(` ⚪ ${s.name.padEnd(22)} UNCONFIGURED (${s.env} not set)`); continue; }if (p.bad) { console.log(` ❌ ${s.name.padEnd(22)} SECRET PRESENT BUT UNDECODABLE (${s.env}) — malformed key`); flags.push(`${s.name}: secret malformed`); continue; }const oc = await onchain(p.pubkey);- const low = oc.sol < s.minSol;- console.log(` ${low ? '⚠️ ' : '✅'} ${s.name.padEnd(22)} ${p.pubkey} SOL=${oc.sol.toFixed(4)}${low ? ` (BELOW floor ${s.minSol})` : ''} USDC=${oc.usdc}`);+ // An unreadable balance is a blind spot, never a funding verdict. Judging+ // null against a floor is how a throttled RPC turns into four fake money+ // emergencies on the owner's desk.+ const unread = oc.sol === null;+ const low = !unread && oc.sol < s.minSol;+ const mark = unread ? '‼️' : low ? '⚠️ ' : '✅';+ const note = unread ? ` (READ FAILED: ${oc.readError})` : low ? ` (BELOW floor ${s.minSol})` : '';+ console.log(` ${mark} ${s.name.padEnd(22)} ${p.pubkey} SOL=${fmtSol(oc.sol)}${note} USDC=${fmtUsdc(oc.usdc)}`);+ if (unread) blind.push(`${s.name} (${p.pubkey}): balance unreadable — ${oc.readError}`);if (low) flags.push(`${s.name}: SOL ${oc.sol.toFixed(4)} below floor ${s.minSol}`);if (s.name === 'x402-ring-sponsor') sponsorDerived.pubkey = p.pubkey;}@@ -112,7 +170,9 @@ for (const a of ADVERTISED) {if (!addr) { console.log(` ⚪ ${a.name.padEnd(24)} not set`); continue; }advVals[a.name] = addr;const oc = await onchain(addr);- console.log(` ✅ ${a.name.padEnd(24)} ${addr} SOL=${oc.sol.toFixed(4)} USDC=${oc.usdc}`);+ const unread = oc.sol === null;+ console.log(` ${unread ? '‼️' : '✅'} ${a.name.padEnd(24)} ${addr} SOL=${fmtSol(oc.sol)} USDC=${fmtUsdc(oc.usdc)}`);+ if (unread) blind.push(`${a.name} (${addr}): balance unreadable — ${oc.readError}`);}// Live cross-check: what production actually advertises right now.@@ -138,5 +198,14 @@ try {} catch (e) { console.log(` (could not fetch ${ORIGIN}/api/x402-status: ${e.message})`); }console.log(`\n${'='.repeat(72)}`);-if (flags.length) { console.log(`RESULT: ${flags.length} issue(s):`); flags.forEach((f) => console.log(` ✗ ${f}`)); process.exitCode = 1; }-else console.log('RESULT: all checked wallets configured, funded, and consistent.');+// Two exit lanes on purpose. `✗` means the audit READ the chain and the money+// is wrong: a funding or config action. `‼` means the audit could not read at+// all: a monitoring blind spot to fix before anyone touches a wallet. Callers+// (scripts/gcp-triage.mjs) route them to different severities, so never merge+// the two lists.+if (blind.length) { console.log(`UNVERIFIED: ${blind.length} wallet(s) could not be read:`); blind.forEach((b) => console.log(` ‼ ${b}`)); }+if (flags.length) { console.log(`RESULT: ${flags.length} issue(s):`); flags.forEach((f) => console.log(` ✗ ${f}`)); }+if (!flags.length && !blind.length) console.log('RESULT: all checked wallets configured, funded, and consistent.');+else if (!flags.length) console.log('RESULT: no funding or config issue found among the wallets that could be read.');+if (flags.length) process.exitCode = 1;+else if (blind.length) process.exitCode = 2;diff --git a/scripts/generate-accessory-glbs.mjs b/scripts/generate-accessory-glbs.mjsindex e1c0c12e8..6db0e99c2 100644--- a/scripts/generate-accessory-glbs.mjs+++ b/scripts/generate-accessory-glbs.mjs@@ -574,11 +574,11 @@ function laurelParts() {}// Berries: three pearls clustered in the front gap.- const berryBase = sphere({ r: 0.0055, segments: 10, rings: 6 });+ const berryBase = sphere({ r: 0.0072, segments: 10, rings: 6 });const berries = [- [-0.011, BAND_Y + 0.002, BAND_R],- [0.011, BAND_Y + 0.002, BAND_R],- [0, BAND_Y + 0.017, BAND_R + 0.002],+ [-0.0145, BAND_Y + 0.003, BAND_R + 0.001],+ [0.0145, BAND_Y + 0.003, BAND_R + 0.001],+ [0, BAND_Y + 0.019, BAND_R + 0.003],].map((translate) => transformGeom(berryBase, { translate }));return [diff --git a/scripts/play-journey-audit.mjs b/scripts/play-journey-audit.mjsindex f069e9f6b..c8946ef54 100644--- a/scripts/play-journey-audit.mjs+++ b/scripts/play-journey-audit.mjs@@ -146,39 +146,71 @@ async function touchScan(label) {}/**- * Tab through the surface and record whether each stop paints a focus ring.- * A stop with no outline and no box-shadow change is invisible to a keyboard- * user, which is the defect this catches.+ * Focus every tabbable control in DOM order and compare its focused computed+ * style against its resting one. A control whose outline and box-shadow are+ * identical either way is invisible to a keyboard user, which is the defect+ * this catches. Runs entirely in-page: one round trip, no per-key latency, so+ * it stays accurate on a machine whose main thread is busy rendering WebGL.*/-async function focusSweep(label, steps = 60) {- const stops = [];+async function focusSweep(label) {+ const res = await page.evaluate(() => {+ const TABBABLE = 'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"]), [contenteditable="true"]';+ const ring = (cs) => `${cs.outlineStyle}|${cs.outlineWidth}|${cs.outlineColor}|${cs.boxShadow}|${cs.borderColor}|${cs.backgroundColor}`;+ const out = { total: 0, noRing: [], notFocusable: [] };+ const prev = document.activeElement;+ for (const n of document.querySelectorAll(TABBABLE)) {+ if (n.disabled || n.hidden) continue;+ const r = n.getBoundingClientRect();+ const cs0 = getComputedStyle(n);+ if (r.width === 0 || r.height === 0 || cs0.visibility === 'hidden' || cs0.display === 'none') continue;+ out.total++;+ const resting = ring(cs0);+ n.focus({ preventScroll: true });+ const focused = document.activeElement === n;+ const desc = {+ sel: n.id ? `#${n.id}` : `${n.tagName.toLowerCase()}.${String(n.className).split(' ').slice(0, 2).join('.')}`,+ label: (n.getAttribute('aria-label') || n.title || n.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 34),+ };+ if (!focused) { out.notFocusable.push(desc); continue; }+ if (ring(getComputedStyle(n)) === resting) out.noRing.push(desc);+ n.blur();+ }+ if (prev && prev.focus) prev.focus({ preventScroll: true });+ // Collapse repeats: thirty identical grid cells are one defect.+ const uniq = (arr) => {+ const m = new Map();+ for (const d of arr) if (!m.has(d.sel)) m.set(d.sel, d);+ return [...m.values()].slice(0, 20);+ };+ out.noRing = uniq(out.noRing);+ out.notFocusable = uniq(out.notFocusable);+ return out;+ });+ console.log(at(), `[focus:${label}] ${res.total} tabbable, ${res.noRing.length} kinds without a focus ring, ${res.notFocusable.length} that refuse focus`);+ for (const b of res.noRing) console.log(' no ring:', b.sel, '|', b.label);+ for (const b of res.notFocusable) console.log(' unfocusable:', b.sel, '|', b.label);+ if (res.noRing.length || res.notFocusable.length) findings.focus.push({ label, bad: [...res.noRing, ...res.notFocusable] });+ return res;+}++/**+ * A real Tab-key pass, short on purpose: it exists to catch a focus trap (Tab+ * cycling inside a small set) that the DOM-order sweep above cannot see.+ */+async function tabTrapCheck(label, steps = 25) {+ const seen = new Set();await page.evaluate(() => document.body.focus());for (let i = 0; i < steps; i++) {await page.keyboard.press('Tab');- const stop = await page.evaluate(() => {+ const sel = await page.evaluate(() => {const n = document.activeElement;if (!n || n === document.body) return null;- const cs = getComputedStyle(n);- const r = n.getBoundingClientRect();- const ring = (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) || /rgb|inset/.test(cs.boxShadow || '');- return {- sel: n.id ? `#${n.id}` : `${n.tagName.toLowerCase()}.${String(n.className).split(' ').slice(0, 2).join('.')}`,- label: (n.getAttribute('aria-label') || n.textContent || '').trim().slice(0, 30),- ring,- offscreen: r.width === 0 || r.height === 0 || r.bottom < 0 || r.top > innerHeight,- };+ return (n.id ? `#${n.id}` : n.tagName.toLowerCase() + '.' + String(n.className).split(' ')[0]) + '|' + (n.textContent || '').trim().slice(0, 20);});- if (!stop) break;- if (stops.some((s) => s.sel === stop.sel && s.label === stop.label)) continue;- stops.push(stop);- }- const bad = stops.filter((s) => !s.ring && !s.offscreen);- console.log(at(), `[focus:${label}] ${stops.length} stops, ${bad.length} without a visible ring`);- if (bad.length) {- findings.focus.push({ label, bad });- for (const b of bad) console.log(' no ring:', b.sel, '|', b.label);+ if (sel) seen.add(sel);}- return stops;+ console.log(at(), `[tab:${label}] ${steps} presses reached ${seen.size} distinct controls`);+ return seen.size;}async function noteState(label, fn) {@@ -214,12 +246,13 @@ await noteState('lobby-loaded', () => ({await overflowScan('lobby');if (MOBILE) await touchScan('lobby');-await focusSweep('lobby', MOBILE ? 40 : 70);+await focusSweep('lobby');+await tabTrapCheck('lobby');// ── 2. search: a query with hits, then one with none ───────────────────────const search = await page.$('.cc-search input');if (search) {- await search.click();+ await search.focus().catch(() => {});await search.type('dog', { delay: 30 });await page.waitForTimeout(3500);await noteState('search-hits', () => ({@@ -240,9 +273,11 @@ if (search) {// ── 3. avatar bar: gallery + create modal open/close ───────────────────────for (const [name, sel] of [['create', '.cc-create-btn'], ['gallery', '.cc-gallery-btn']]) {- const btn = await page.$(sel);- if (!btn) { console.log(at(), `[missing] ${name} button`); continue; }- await btn.click().catch(() => {});+ // Dispatched rather than driven through the mouse: under software GL the+ // main thread stalls long enough for Playwright's stability check to time+ // out on a button that is perfectly clickable for a real user.+ const found = await page.evaluate((s) => { const b = document.querySelector(s); if (!b) return false; b.click(); return true; }, sel);+ if (!found) { console.log(at(), `[missing] ${name} button`); continue; }await page.waitForTimeout(2500);await noteState(`${name}-open`, () => ({overlays: [...document.querySelectorAll('[class*="overlay"], [class*="modal"], dialog')]@@ -295,6 +330,7 @@ await noteState('world-hud', () => ({await overflowScan('world');if (MOBILE) await touchScan('world');+await focusSweep('world');// ── 5. every HUD panel: open, measure, close ───────────────────────────────const PANELS = [diff --git a/scripts/play-multiplayer-e2e.mjs b/scripts/play-multiplayer-e2e.mjsnew file mode 100644index 000000000..0a03a3eeb--- /dev/null+++ b/scripts/play-multiplayer-e2e.mjs@@ -0,0 +1,342 @@+// Two-client multiplayer conformance run for /play.+//+// Opens the same coin world in two isolated browser contexts (separate storage,+// so they are two different players) and asserts the things a crowded event+// depends on: both clients see each other, movement and chat cross in under a+// human-perceptible delay, chat text cannot inject HTML, and a forced network+// drop on one client heals back into a state that MATCHES the server — no ghost+// avatars left standing, no duplicated self, chat flowing again afterwards.+//+// node scripts/play-multiplayer-e2e.mjs # local dev, $THREE world+// BASE=http://localhost:3000 node scripts/play-multiplayer-e2e.mjs+// BASE=https://three.ws node scripts/play-multiplayer-e2e.mjs # live site+//+// Requires a world server the page can reach. Locally that is `npm run+// dev:walk-all` (vite on :3000 + colyseus on :2567); against three.ws the page's+// <meta name="game-server"> points at the deployed Cloud Run instance.+//+// Exit code is 0 only when every check passes and neither page logged a console+// error or a page error.+import { chromium } from 'playwright';++const BASE = (process.env.BASE || 'http://localhost:3000').replace(/\/$/, '');+// The canonical $THREE community (docs/event-readiness/README.md).+const MINT = process.env.COIN || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const WORLD = `${BASE}/play?coin=${encodeURIComponent(MINT)}&name=three.ws&symbol=three`;+const OFFLINE_MS = Number(process.env.OFFLINE_MS || 10000);+// A Vite dev origin compiles the whole /play module graph on first request and a+// shared/loaded machine makes that minutes, not seconds; a production origin is a+// static bundle. SLOW=1 (default for a dev BASE) stretches the load-and-join+// budgets so a busy box reads as slow, not as a failure.+const SLOW = process.env.SLOW ? process.env.SLOW !== '0' : /localhost|127\.0\.0\.1/.test(BASE);+const LOAD_MS = Number(process.env.LOAD_MS || (SLOW ? 300000 : 90000));+const JOIN_MS = Number(process.env.JOIN_MS || (SLOW ? 180000 : 60000));++const t0 = Date.now();+const at = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;+const results = [];+const consoleErrors = [];++function check(name, ok, detail = '') {+ results.push({ name, ok, detail });+ console.log(`${at()} ${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`);+ return ok;+}++// Poll a page expression until it is truthy or the deadline passes. Returns the+// last value seen, so a failed wait can report what it actually got.+async function until(page, fn, { timeout = 30000, every = 250, arg } = {}) {+ const deadline = Date.now() + timeout;+ let last;+ for (;;) {+ try { last = await page.evaluate(fn, arg); } catch (err) { last = { evalError: String(err).slice(0, 120) }; }+ if (last && !last.evalError && (last === true || last.ok !== false)) {+ if (last === true || last.ok === true) return last;+ }+ if (Date.now() > deadline) return last;+ await page.waitForTimeout(every);+ }+}++// Everything the assertions need, read straight off the live scene + net client.+const snapshot = () => {+ const cc = window.__CC__;+ const net = cc?.net;+ const remotes = [...(cc?.remotes || new Map())].map(([id, r]) => ({+ id,+ name: r.name,+ x: Math.round(r.rig.position.x * 100) / 100,+ z: Math.round(r.rig.position.z * 100) / 100,+ tx: Math.round(r.targetX * 100) / 100,+ tz: Math.round(r.targetZ * 100) / 100,+ motion: r.motion,+ avatar: r._avatarUrl || '',+ cosmetics: r._cosWire || '',+ }));+ return {+ ok: true,+ phase: cc?.phase || null,+ status: net?.status || null,+ live: !!net?.isLive?.(),+ sessionId: net?.sessionId || null,+ name: net?.name || '',+ self: cc ? { x: Math.round(cc.localPos.x * 100) / 100, z: Math.round(cc.localPos.z * 100) / 100 } : null,+ remotes,+ labels: document.querySelectorAll('.cc-label').length,+ chat: [...document.querySelectorAll('.cc-chat-msg')].map((n) => ({+ name: n.querySelector('b')?.textContent || '',+ text: n.querySelector('.cc-chat-text')?.textContent || '',+ // Any element inside the text span means the message was parsed as+ // markup instead of being written as text — an XSS hole.+ injected: n.querySelector('.cc-chat-text')?.children.length || 0,+ })),+ statusPill: document.querySelector('#cc-hud .cc-status .cc-status-text')?.textContent+ || document.querySelector('[data-state] .cc-status-text')?.textContent || null,+ };+};++async function openClient(browser, tag, name) {+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, permissions: [] });+ // A stable display name per client makes the cross-client assertions readable.+ // GAME_SERVER overrides the world server the page would otherwise resolve —+ // needed to point a run at an isolated Colyseus instance instead of whatever+ // the page's <meta game-server> or the localhost default picks.+ await ctx.addInitScript(({ n, server }) => {+ try { localStorage.setItem('cc-name', n); } catch { /* storage blocked */ }+ if (server) window.GAME_SERVER_URL = server;+ }, { n: name, server: process.env.GAME_SERVER || '' });+ const page = await ctx.newPage();+ page.on('console', (m) => {+ if (m.type() === 'error') {+ const text = m.text();+ // A failed asset fetch while the context is deliberately offline is the+ // test doing its job, not a defect in the client. The Vite HMR client is+ // harness scaffolding that only exists on a dev origin; its socket points+ // at the dev host, not the game server, so its noise is not a finding.+ if (/net::ERR_INTERNET_DISCONNECTED|Failed to load resource/i.test(text)) return;+ if (/\[vite\]|@vite\/client/.test(text)) return;+ consoleErrors.push(`[${tag}] ${text.slice(0, 300)}`);+ console.log(`${at()} [${tag}][console.error] ${text.slice(0, 300)}`);+ }+ });+ page.on('pageerror', (e) => {+ const text = String(e?.message || e);+ if (/WebSocket closed without opened/.test(text)) return; // Vite HMR client+ consoleErrors.push(`[${tag}] ${text.slice(0, 300)}`);+ console.log(`${at()} [${tag}][pageerror] ${String(e?.stack || e).slice(0, 400)}`);+ });+ page.on('websocket', (ws) => {+ console.log(`${at()} [${tag}][ws open] ${ws.url().slice(0, 90)}`);+ ws.on('close', () => console.log(`${at()} [${tag}][ws close]`));+ });+ await page.goto(WORLD, { waitUntil: 'domcontentloaded', timeout: 90000 });+ return { tag, ctx, page };+}++// Onboarding cards and the intro sheet sit over the world; clear whatever is up.+async function dismissOverlays(page, rounds = 4) {+ for (let i = 0; i < rounds; i++) {+ const clicked = await page.evaluate(() => {+ const btn = [...document.querySelectorAll('button')].find(+ (b) => /^(continue|enter the world|got it|start|close|skip|drop in now)$/i.test(b.textContent.trim()) && b.offsetParent,+ );+ if (btn) { btn.click(); return btn.textContent.trim(); }+ return null;+ });+ if (!clicked) break;+ await page.waitForTimeout(400);+ }+}++async function sendChat(page, text) {+ await page.fill('#cc-chat input[type="text"]', text);+ await page.click('#cc-chat .cc-chat-send');+}++// Drive the local avatar to a position and let the send loop publish it. Uses the+// same sendMove the input handler calls, so this exercises the real wire.+async function moveTo(page, x, z) {+ await page.evaluate(({ x, z }) => {+ const cc = window.__CC__;+ cc.localPos.x = x; cc.localPos.z = z;+ cc.net.sendMove({ x, y: cc.localPos.y, z, yaw: cc.localYaw, motion: 'walk' });+ }, { x, z });+}++const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader'] });+let a; let b;+try {+ // ---------------------------------------------------------------- join path+ const joinStart = Date.now();+ a = await openClient(browser, 'A', 'AliceQA');+ b = await openClient(browser, 'B', 'BobQA');+ await Promise.all([dismissOverlays(a.page), dismissOverlays(b.page)]);++ const online = async (c) => until(c.page, () => {+ const net = window.__CC__?.net;+ return { ok: net?.status === 'online' && window.__CC__?.phase === 'world', status: net?.status, phase: window.__CC__?.phase };+ }, { timeout: 60000 });+ const aOnline = await online(a);+ const bOnline = await online(b);+ check('A joins the world online', aOnline?.ok === true, JSON.stringify(aOnline));+ check('B joins the world online', bOnline?.ok === true, JSON.stringify(bOnline));++ const sawEachOther = await until(a.page, () => {+ const cc = window.__CC__;+ return { ok: (cc?.remotes?.size || 0) >= 1, n: cc?.remotes?.size || 0 };+ }, { timeout: 30000 });+ check('A sees B within 30s of load', sawEachOther?.ok === true,+ `${((Date.now() - joinStart) / 1000).toFixed(1)}s to first peer`);+ const bSees = await until(b.page, () => ({ ok: (window.__CC__?.remotes?.size || 0) >= 1, n: window.__CC__?.remotes?.size || 0 }), { timeout: 30000 });+ check('B sees A', bSees?.ok === true, JSON.stringify(bSees));++ // ------------------------------------------------------- name + look sync+ let bSnap = await b.page.evaluate(snapshot);+ check('B renders A\'s display name on the nameplate',+ bSnap.remotes.some((r) => r.name === 'AliceQA'),+ JSON.stringify(bSnap.remotes.map((r) => r.name)));+ check('B renders a nameplate element per peer', bSnap.labels >= bSnap.remotes.length,+ `labels=${bSnap.labels} remotes=${bSnap.remotes.length}`);+ check('B receives A\'s avatar url', bSnap.remotes.every((r) => !!r.avatar),+ JSON.stringify(bSnap.remotes.map((r) => r.avatar.slice(-40))));++ // ------------------------------------------------------------- movement+ const moveStart = Date.now();+ await moveTo(a.page, 7.5, -4.25);+ const moved = await until(b.page, () => {+ const cc = window.__CC__;+ const r = [...(cc?.remotes || new Map())].map(([, v]) => v).find((v) => v.name === 'AliceQA');+ return { ok: !!r && Math.abs(r.targetX - 7.5) < 0.2 && Math.abs(r.targetZ + 4.25) < 0.2, tx: r?.targetX, tz: r?.targetZ };+ }, { timeout: 5000, every: 60 });+ check('A\'s movement reaches B', moved?.ok === true, `${Date.now() - moveStart}ms · ${JSON.stringify(moved)}`);++ // --------------------------------------------------------------- emotes+ await a.page.evaluate(() => window.__CC__.net.sendEmote('wave'));+ const emoted = await until(b.page, () => {+ const st = window.__CC__?.net?.state;+ const players = st?.players ? [...st.players.values()] : [];+ const alice = players.find((p) => p.name === 'AliceQA');+ return { ok: alice?.emote === 'wave', emote: alice?.emote || null };+ }, { timeout: 5000, every: 100 });+ check('A\'s emote reaches B', emoted?.ok === true, JSON.stringify(emoted));++ // ----------------------------------------------------------------- chat+ const msg = `hello from A ${Date.now()}`;+ await sendChat(a.page, msg);+ const gotChat = await until(b.page, (m) => {+ const rows = [...document.querySelectorAll('.cc-chat-msg .cc-chat-text')].map((n) => n.textContent);+ return { ok: rows.includes(m), rows: rows.slice(-3) };+ }, { timeout: 6000, every: 100, arg: msg });+ check('A→B chat delivers', gotChat?.ok === true, JSON.stringify(gotChat));++ const reply = `hi back from B ${Date.now()}`;+ await sendChat(b.page, reply);+ const gotReply = await until(a.page, (m) => {+ const rows = [...document.querySelectorAll('.cc-chat-msg .cc-chat-text')].map((n) => n.textContent);+ return { ok: rows.includes(m), rows: rows.slice(-3) };+ }, { timeout: 6000, every: 100, arg: reply });+ check('B→A chat delivers', gotReply?.ok === true, JSON.stringify(gotReply));++ // Chat must never be parsed as markup on the receiving client.+ const xss = '<img src=x onerror="window.__XSS__=1"><b>bold</b>';+ await sendChat(a.page, xss);+ await b.page.waitForTimeout(1200);+ const escaped = await b.page.evaluate((raw) => {+ const rows = [...document.querySelectorAll('.cc-chat-msg .cc-chat-text')];+ const row = rows.find((n) => n.textContent === raw);+ return {+ delivered: !!row,+ children: row ? row.children.length : -1,+ xssFired: !!window.__XSS__,+ imgs: document.querySelectorAll('#cc-chat img').length,+ };+ }, xss);+ check('chat text is escaped, never injected as HTML',+ escaped.delivered && escaped.children === 0 && !escaped.xssFired && escaped.imgs === 0,+ JSON.stringify(escaped));++ // Spam throttle: the server drops anything under its per-client cooldown, so a+ // burst must NOT arrive whole on the other client.+ const burst = Date.now();+ for (let i = 0; i < 8; i++) await sendChat(a.page, `spam-${burst}-${i}`);+ await b.page.waitForTimeout(2000);+ const delivered = await b.page.evaluate((tag) =>+ [...document.querySelectorAll('.cc-chat-msg .cc-chat-text')].filter((n) => n.textContent.startsWith(`spam-${tag}-`)).length, burst);+ check('chat burst is throttled server-side', delivered < 8, `${delivered}/8 relayed`);++ // The log must not grow without bound — the UI caps it.+ const capped = await b.page.evaluate(() => document.querySelectorAll('.cc-chat-msg').length <= 200);+ check('chat log is capped in the DOM', capped === true);++ // ------------------------------------------------------- forced disconnect+ const aBefore = await a.page.evaluate(snapshot);+ console.log(`${at()} [A] going offline for ${OFFLINE_MS}ms (session ${aBefore.sessionId})`);+ await a.ctx.setOffline(true);+ const dropped = await until(a.page, () => {+ const s = window.__CC__?.net?.status;+ return { ok: s !== 'online', status: s };+ }, { timeout: 30000, every: 250 });+ check('A notices the drop', dropped?.ok === true, JSON.stringify(dropped));+ const pill = await a.page.evaluate(() => document.querySelector('#cc-hud [role]')?.textContent || document.body.innerText.match(/reconnecting…|offline, tap to retry/i)?.[0] || null);+ check('A shows a reconnect indicator while down', /reconnect|offline/i.test(String(pill)), String(pill).slice(0, 60));++ await a.page.waitForTimeout(OFFLINE_MS);+ await a.ctx.setOffline(false);+ // Simulate the tab coming back to the foreground: the same path a phone takes+ // after Safari froze the page, and the fast lane out of the retry backoff.+ await a.page.evaluate(() => {+ document.dispatchEvent(new Event('visibilitychange'));+ dispatchEvent(new Event('online'));+ });+ const back = await until(a.page, () => {+ const net = window.__CC__?.net;+ return { ok: net?.status === 'online' && net?.isLive?.() === true, status: net?.status };+ }, { timeout: 20000, every: 250 });+ check('A reconnects automatically after the network returns', back?.ok === true, JSON.stringify(back));++ const aAfter = await a.page.evaluate(snapshot);+ check('A gets a fresh session on reconnect', !!aAfter.sessionId && aAfter.sessionId !== aBefore.sessionId,+ `${aBefore.sessionId} → ${aAfter.sessionId}`);+ check('A\'s roster after resync holds exactly one peer (no ghosts)', aAfter.remotes.length === 1,+ JSON.stringify(aAfter.remotes.map((r) => `${r.name}:${r.id}`)));+ check('A\'s nameplate count matches its roster', aAfter.labels === aAfter.remotes.length,+ `labels=${aAfter.labels} remotes=${aAfter.remotes.length}`);++ // The other client is the real judge of duplicated-self: it must hold ONE A.+ const bAfter = await until(b.page, () => {+ const cc = window.__CC__;+ const rs = [...(cc?.remotes || new Map())].map(([, r]) => r.name);+ return { ok: rs.filter((n) => n === 'AliceQA').length === 1 && rs.length === 1, rs };+ }, { timeout: 20000, every: 250 });+ check('B holds exactly one A after A\'s reconnect (no duplicated self)', bAfter?.ok === true, JSON.stringify(bAfter));++ // Position must survive the resync: A stood still through the whole drop, so+ // the server has to end up agreeing with where A actually is.+ const resynced = await until(b.page, () => {+ const r = [...(window.__CC__?.remotes || new Map())].map(([, v]) => v).find((v) => v.name === 'AliceQA');+ return { ok: !!r && Math.abs(r.targetX - 7.5) < 0.5 && Math.abs(r.targetZ + 4.25) < 0.5, tx: r?.targetX, tz: r?.targetZ };+ }, { timeout: 12000, every: 250 });+ check('A\'s position resyncs on B after the drop', resynced?.ok === true, JSON.stringify(resynced));++ const after = `after reconnect ${Date.now()}`;+ await sendChat(a.page, after);+ const chatBack = await until(b.page, (m) => {+ const rows = [...document.querySelectorAll('.cc-chat-msg .cc-chat-text')].map((n) => n.textContent);+ return { ok: rows.includes(m), rows: rows.slice(-3) };+ }, { timeout: 8000, every: 100, arg: after });+ check('chat flows again after the reconnect', chatBack?.ok === true, JSON.stringify(chatBack));++ check('no console errors on either client', consoleErrors.length === 0,+ consoleErrors.slice(0, 5).join(' | '));+} catch (err) {+ check('run completed without throwing', false, String(err?.stack || err).slice(0, 500));+} finally {+ await a?.ctx.close().catch(() => {});+ await b?.ctx.close().catch(() => {});+ await browser.close();+}++const failed = results.filter((r) => !r.ok);+console.log(`\n=== ${results.length - failed.length}/${results.length} checks passed ===`);+for (const f of failed) console.log(` FAIL ${f.name}${f.detail ? ` — ${f.detail}` : ''}`);+process.exit(failed.length ? 1 : 0);diff --git a/scripts/render-accessory-thumbs.mjs b/scripts/render-accessory-thumbs.mjsindex 8f3b14797..5ac543400 100644--- a/scripts/render-accessory-thumbs.mjs+++ b/scripts/render-accessory-thumbs.mjs@@ -21,7 +21,6 @@import { createServer } from 'node:http';import { readFile, writeFile, readdir, mkdir } from 'node:fs/promises';-import { createReadStream } from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';import { chromium } from 'playwright';@@ -96,7 +95,7 @@ const scene = new THREE.Scene();// a hemisphere fill so downward faces never go to pure black.const key = new THREE.DirectionalLight(0xfff4e2, 3.1); key.position.set(-2.2, 2.6, 3.2);const rim = new THREE.DirectionalLight(0xdce8ff, 2.0); rim.position.set(2.4, 1.2, -2.8);-scene.add(key, rim, new THREE.HemisphereLight(0xffffff, 0x2a2a30, 1.35));+scene.add(key, rim, new THREE.HemisphereLight(0xffffff, 0x8b8b94, 1.5));window.renderAccessory = async (url) => {const gltf = await new GLTFLoader().loadAsync(url);@@ -106,18 +105,22 @@ window.renderAccessory = async (url) => {model.userData.subject = true;scene.add(model);- // Frame the model: recentre on its bounding box, then pull the camera back- // far enough that the largest dimension fills ~78% of the frame at any scale.+ // Frame the model: recentre on its bounding box, then pull the camera back far+ // enough to contain the whole BOUNDING SPHERE (half the box diagonal, not half+ // the longest edge — a ring is widest across its diagonal and would crop).const box = new THREE.Box3().setFromObject(model);const size = box.getSize(new THREE.Vector3());const center = box.getCenter(new THREE.Vector3());model.position.sub(center);- const radius = Math.max(size.x, size.y, size.z) * 0.5 || 0.1;- const camera = new THREE.PerspectiveCamera(35, 1, radius * 0.01, radius * 100);- const dist = (radius / Math.sin((35 * Math.PI / 180) / 2)) * 0.78;- // Three-quarter view from slightly above: reads volume better than a flat- // front-on shot and matches the existing thumbs.- camera.position.set(dist * 0.52, dist * 0.42, dist * 0.74);+ const radius = size.length() * 0.5 || 0.1;+ const FOV = 35;+ const camera = new THREE.PerspectiveCamera(FOV, 1, radius * 0.01, radius * 100);+ const dist = (radius / Math.sin((FOV * Math.PI / 180) / 2)) * 1.05;+ // Three-quarter view from well above the subject, facing the accessory's front+ // (+Z, the glTF forward convention these are authored in): reads volume better+ // than a flat front-on shot, and keeps front detail (a cap's visor, the+ // laurel's berries) pointed at the viewer.+ camera.position.set(dist * 0.33, dist * 0.52, dist * 0.79);camera.lookAt(0, 0, 0);renderer.render(scene, camera);return renderer.domElement.toDataURL('image/png');@@ -136,18 +139,21 @@ async function main() {if (!names.length) { console.log('No accessory GLBs to render.'); return; }await mkdir(THUMB_DIR, { recursive: true });- const { server, port } = await serveRepo();+ const { server, port } = await serveRepo(PAGE);const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader'] });+ const errors = [];try {const page = await browser.newPage({ viewport: { width: SIZE, height: SIZE } });- page.on('pageerror', (err) => { throw err; });- await page.setContent(PAGE(port), { waitUntil: 'load' });- await page.waitForFunction('window.rendererReady === true', null, { timeout: 30_000 });+ page.on('pageerror', (err) => errors.push(err.message));+ page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });+ await page.goto(`http://127.0.0.1:${port}${HARNESS_PATH}`, { waitUntil: 'load' });+ await page.waitForFunction('window.rendererReady === true', null, { timeout: 30_000 })+ .catch(() => { throw new Error(`Harness never booted:\n ${errors.join('\n ') || 'no page errors reported'}`); });for (const name of names) {const dataUrl = await page.evaluate(([url]) => window.renderAccessory(url),- [`http://127.0.0.1:${port}/public/accessories/${name}.glb`],+ [`/public/accessories/${name}.glb`],);const png = Buffer.from(dataUrl.split(',')[1], 'base64');const out = path.join(THUMB_DIR, `${name}.png`);diff --git a/tests/fixtures/mcp-golden-tools.json b/tests/fixtures/mcp-golden-tools.jsonindex 487302346..c91adab50 100644--- a/tests/fixtures/mcp-golden-tools.json+++ b/tests/fixtures/mcp-golden-tools.json@@ -1137,7 +1137,7 @@"idempotentHint": false,"openWorldHint": true},- "schemaHash": "d0493ec770a9"+ "schemaHash": "33374b80604f"}],"packages/agentcore-payments-mcp/src/tools/cancel-session.js": [@@ -1224,7 +1224,7 @@"idempotentHint": false,"openWorldHint": true},- "schemaHash": "e829b250d792"+ "schemaHash": "c62c144e1e42"}],"packages/agora-mcp/src/tools/citizens.js": [diff --git a/tests/forge-gameready-gate.test.js b/tests/forge-gameready-gate.test.jsindex 56fb9e590..673ec5765 100644--- a/tests/forge-gameready-gate.test.js+++ b/tests/forge-gameready-gate.test.js@@ -50,7 +50,7 @@ vi.mock('../src/forge-pay.js', () => ({payForConsumption: vi.fn(async () => ({ ok: true, paymentId: 'pay_1', refId: 'ref_1' })),}));-const GLB_URL = 'https://cdn.three.ws/models/knight.glb';+const GLB_URL = 'https://three.ws/cdn/models/knight.glb';// The three elements src/forge-gameready.js mounts against on /forge.function mountPage() {diff --git a/tests/spin-wheel.test.js b/tests/spin-wheel.test.jsindex 49132c541..8b5ec0201 100644--- a/tests/spin-wheel.test.js+++ b/tests/spin-wheel.test.js@@ -118,6 +118,39 @@ describe('handleSpinFree — gates, in priority order', () => {handleSpinFree(room, client);expect(sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'pack_full' } });});+ // The roll is uniform over wood, stone AND coal, so "somewhere to put ONE of+ // them" is not enough: a pack whose only space is a half-full wood stack would+ // convert a stone or coal win into 1-2 cash. The gate has to hold for every+ // prize item the paytable can land on.+ it('denies pack_full when the only free space fits one prize item but not the others', () => {+ const profile = eligibleProfile();+ for (const s of profile.inv) { s.item = 'rod'; s.qty = 1; }+ // One slot holds a partial wood stack: room for wood, nowhere for stone/coal.+ profile.inv[0].item = 'wood';+ profile.inv[0].qty = 5;+ const { room, client, sent } = makeRoom({ profile });+ handleSpinFree(room, client);+ expect(sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'pack_full' } });+ });+ it('a spin that fits every prize is allowed and the prize actually lands in the pack', () => {+ const profile = eligibleProfile();+ const { room, client, sent } = makeRoom({ profile });+ const goldBefore = profile.gold;+ handleSpinFree(room, client);+ const res = sent[0].msg;+ expect(sent[0].type).toBe('spinResult');+ // Nothing was converted: the roll either paid cash or landed whole in the pack.+ expect(res.lost).toBe(0);+ expect(res.refunded).toBe(0);+ const seg = WHEEL_SEGMENTS[res.index];+ if (seg.kind === 'gold') {+ expect(profile.gold).toBe(goldBefore + seg.gold);+ } else {+ const held = profile.inv.filter((s) => s.item === seg.item).reduce((n, s) => n + s.qty, 0);+ expect(held).toBe(seg.qty);+ expect(profile.gold).toBe(goldBefore);+ }+ });it('grants a real prize, sets the 12h cooldown, and persists — the success path', () => {const profile = eligibleProfile();const { room, client, sent } = makeRoom({ profile });@@ -200,7 +233,11 @@ describe('handleSpinPaidPrep', () => {const wallet = '1'.repeat(32);const { room, client, sent } = makeRoom();await handleSpinPaidPrep(room, client, { wallet });- expect(gameToken.buildSpinPayment).toHaveBeenCalledWith({ buyerWallet: wallet, usd: SPIN_COST_USD });+ // forAccount seals the quote to the requesting session's profile so a+ // leaked settled quote can't be redeemed onto another account.+ expect(gameToken.buildSpinPayment).toHaveBeenCalledWith({+ buyerWallet: wallet, usd: SPIN_COST_USD, forAccount: room.econ.get('s1').playerId,+ });expect(sent[0]).toEqual({type: 'spinPrep',msg: { tx: 'BASE64TX', tokenAmount: '3000000', symbol: '$THREE', costUsd: SPIN_COST_USD, quote: 'QUOTE.SIG' },@@ -225,22 +262,61 @@ describe('handleSpinPaidSettle', () => {gameToken.verifySpinPayment.mockResolvedValueOnce({ ok: true, nonce: 'nonce-1' });const profile = eligibleProfile();const { room, client, sent } = makeRoom({ profile });- await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sig'.repeat(12) });+ await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sigsuccess'.repeat(4) });+ expect(gameToken.verifySpinPayment).toHaveBeenCalledWith({+ quoteToken: 'q', txSig: 'sigsuccess'.repeat(4), forAccount: profile.playerId,+ });expect(sent[0].type).toBe('spinResult');expect(sent[0].msg.mode).toBe('paid');expect(room._persistEcon).toHaveBeenCalledWith('s1');// A paid spin does NOT touch the free-spin cooldown.expect(profile.nextFreeSpinAt).toBe(0);});+ // The payment has already settled by the time this handler runs, so a pack that+ // filled up while the player was in their wallet must never cost them the spin.+ // It converts to cash and REPORTS that, rather than silently paying out a few+ // coins for a $3 spin and calling it a win.+ it('still pays out when the pack filled during the wallet round-trip, and reports the conversion', async () => {+ gameToken.verifySpinPayment.mockResolvedValueOnce({ ok: true, nonce: 'nonce-full' });+ const profile = eligibleProfile();+ for (const s of profile.inv) { s.item = 'rod'; s.qty = 1; }+ const goldBefore = profile.gold;+ const { room, client, sent } = makeRoom({ profile });+ await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sigpackfull'.repeat(4) });+ const res = sent[0].msg;+ expect(sent[0].type).toBe('spinResult');+ const seg = WHEEL_SEGMENTS[res.index];+ if (seg.kind === 'gold') {+ expect(res.lost).toBe(0);+ expect(profile.gold).toBe(goldBefore + seg.gold);+ } else {+ // Nowhere to put it: the whole prize converted, and the result says so.+ expect(res.lost).toBe(seg.qty);+ expect(res.got).toBe(0);+ expect(res.refunded).toBeGreaterThan(0);+ expect(profile.gold).toBe(goldBefore + res.refunded);+ }+ });it('refuses to grant a second prize for an already-settled nonce (replay protection)', async () => {gameToken.verifySpinPayment.mockResolvedValue({ ok: true, nonce: 'nonce-replay' });const profile = eligibleProfile();const { room, client, sent } = makeRoom({ profile });- await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sig'.repeat(12) });+ await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sigreplay1'.repeat(4) });expect(sent[0].type).toBe('spinResult');- await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sig'.repeat(12) });+ await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sigreplay1'.repeat(4) });expect(sent[1]).toEqual({ type: 'spinDenied', msg: { reason: 'already_settled' } });});+ it('refuses the same settled payment replayed into a DIFFERENT room (cross-world replay)', async () => {+ // The guard is process-wide on purpose: the old per-room Map let one $3+ // payment roll a fresh prize in every coin world it was replayed into.+ gameToken.verifySpinPayment.mockResolvedValue({ ok: true, nonce: 'nonce-xroom' });+ const a = makeRoom({ profile: eligibleProfile() });+ const b = makeRoom({ profile: eligibleProfile() });+ await handleSpinPaidSettle(a.room, a.client, { quote: 'q', txSig: 'sigxroom01'.repeat(4) });+ expect(a.sent[0].type).toBe('spinResult');+ await handleSpinPaidSettle(b.room, b.client, { quote: 'q', txSig: 'sigxroom01'.repeat(4) });+ expect(b.sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'already_settled' } });+ });});describe('registerSpinHandlers', () => {