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
security(csp): serve per-response script hashes instead of script-src unsafe-inline
nirholas72064369207d
diff --git a/pages/activity.html b/pages/activity.htmlindex 68fde0d58..a023c688f 100644--- a/pages/activity.html+++ b/pages/activity.html@@ -424,6 +424,7 @@</main><script src="/brand.js" defer></script>+ <script src="/img-fallback.js" defer></script><script type="module">import { proxiedImageURL } from '/src/ipfs.js';@@ -436,7 +437,7 @@const sol = (n) => n == null ? '—' : (Math.abs(Number(n)) >= 1 ? Number(n).toFixed(2) : Number(n).toFixed(3)) + ' ◎';const sign = (n) => n > 0 ? '+' : '';const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));- const imgErr = `this.onerror=null;this.style.visibility='hidden'`;+ const imgFallbackAttr = `data-fallback="invisible"`;// Agent and token art URLs come from third-party data (pump.fun IPFS// metadata, per-agent hosts) and routinely fail ORB/CORS when loaded// directly as <img> sources: some are metadata JSON documents, some are@@ -522,7 +523,7 @@return `<div class="ac-row oc-${outcome}" data-id="${esc(item.id)}" data-agent="${esc(item.agent_id)}" role="article" aria-label="${esc(rowLabel)}"><span class="outcome-edge" aria-hidden="true"></span>- <img class="ac-av" src="${esc(av)}" alt="" onerror="${imgErr}" loading="lazy" />+ <img class="ac-av" src="${esc(av)}" alt="" ${imgFallbackAttr} loading="lazy" /><div class="ac-body"><div class="ac-headline"><span class="ac-tier ${tier}">${TIER_EMOJI[tier] || ''} ${tier}</span>@@ -973,7 +974,7 @@const av = imgSrc(a.image_url, a.agent_id);return `<a class="ac-li" href="/trader/${encodeURIComponent(a.agent_id)}"><span class="ac-li-rank ${a.rank <= 3 ? 'top' : ''}">${a.rank}</span>- <img class="ac-li-av round" src="${esc(av)}" alt="" onerror="${imgErr}" loading="lazy" />+ <img class="ac-li-av round" src="${esc(av)}" alt="" ${imgFallbackAttr} loading="lazy" /><span class="ac-li-main"><span class="ac-li-name">${esc(a.name || 'Agent')}</span><span class="ac-li-sub">${a.wins}W · ${a.losses}L · ${a.total} calls</span></span><span class="ac-li-r"><span class="big up">${wr}</span><span class="small ${roiCls}">${roi}</span></span></a>`;@@ -1001,7 +1002,7 @@const av = imgSrc(m.image_uri, m.mint);const up = (m.delta || 0) >= 0;return `<a class="ac-li" href="/oracle/coin/${encodeURIComponent(m.mint)}">- <img class="ac-li-av" src="${esc(av)}" alt="" onerror="${imgErr}" loading="lazy" />+ <img class="ac-li-av" src="${esc(av)}" alt="" ${imgFallbackAttr} loading="lazy" /><span class="ac-li-main"><span class="ac-li-name">$${esc(sym)}${m.tier_changed ? ' <span style="color:var(--ac-up);font-size:9px">▲ tier</span>' : ''}</span><span class="ac-li-sub">${esc(m.tier || '')} · score ${m.score ?? '—'}</span></span><span class="ac-li-r"><span class="ac-delta ${up ? 'up' : 'dn'}">${up ? '+' : ''}${m.delta}</span><span class="small">${m.first_score}→${m.score}</span></span></a>`;@@ -1029,7 +1030,7 @@const av = imgSrc(w.image_uri, w.mint);const ath = w.ath_multiple != null ? w.ath_multiple.toFixed(1) + '×' : '—';return `<a class="ac-li" href="${esc(w.pump_url)}" target="_blank" rel="noopener">- <img class="ac-li-av" src="${esc(av)}" alt="" onerror="${imgErr}" loading="lazy" />+ <img class="ac-li-av" src="${esc(av)}" alt="" ${imgFallbackAttr} loading="lazy" /><span class="ac-li-main"><span class="ac-li-name">$${esc(sym)}${w.graduated ? ' 🎓' : ''}</span><span class="ac-li-sub">${esc(w.tier || '')}${w.last_mc_usd ? ' · ' + usdc(w.last_mc_usd) : ''}</span></span><span class="ac-li-r"><span class="big up">${ath}</span><span class="small">ATH</span></span></a>`;diff --git a/pages/avatar-artifact.html b/pages/avatar-artifact.htmlindex b5ce5ab44..91244a2d4 100644--- a/pages/avatar-artifact.html+++ b/pages/avatar-artifact.html@@ -249,7 +249,7 @@hiccup or a browser without WebGL.</p><div class="foot-links">- <a href="javascript:location.reload()" data-i18n="avatar_artifact.retry">Retry</a>+ <a href="#" id="artifact-retry" data-i18n="avatar_artifact.retry">Retry</a><a href="/" data-i18n="avatar_artifact.back_to_three_ws">Back to three.ws</a></div></div>@@ -261,12 +261,15 @@document.getElementById('loading')?.setAttribute('hidden', '');document.getElementById('error')?.removeAttribute('hidden');};+ document.getElementById('artifact-retry')?.addEventListener('click', (event) => {+ event.preventDefault();+ location.reload();+ });</script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"integrity="sha384-CI3ELBVUz9XQO+97x6nwMDPosPR5XvsxW2ua7N1Xeygeh1IxtgqtCkGfQY9WWdHu"crossorigin="anonymous"- onerror="window.__avatarArtifactFailed()"></script><script>// WebGL / runtime guard: if Three.js didn't load or WebGL isdiff --git a/pages/coin-intel.html b/pages/coin-intel.htmlindex 2a7520b77..eefa1aa4f 100644--- a/pages/coin-intel.html+++ b/pages/coin-intel.html@@ -566,7 +566,7 @@article.innerHTML = `<span class="verdict-edge bg-${v.tone}"></span><div class="head">- <img class="avatar" loading="lazy" referrerpolicy="no-referrer" src="${esc(imgProxy(coin.image_uri, coin.mint))}" onerror="this.onerror=null;this.src='${esc(fallbackImg(coin.mint))}'" alt="" />+ <img class="avatar" loading="lazy" referrerpolicy="no-referrer" src="${esc(imgProxy(coin.image_uri, coin.mint))}" data-fallback-src="${esc(fallbackImg(coin.mint))}" alt="" /><div class="id"><div class="name">${esc(coin.name || 'Unknown')}</div><div class="sub"><span class="sym">$${esc((coin.symbol||'').toUpperCase())}</span><span class="age">${ago(coin.first_seen_at_ms)}</span></div>@@ -890,7 +890,7 @@return `<div class="d-head">- <img class="avatar" referrerpolicy="no-referrer" src="${esc(imgProxy(c.image_uri, c.mint))}" onerror="this.onerror=null;this.src='${esc(fallbackImg(c.mint))}'" alt="" />+ <img class="avatar" referrerpolicy="no-referrer" src="${esc(imgProxy(c.image_uri, c.mint))}" data-fallback-src="${esc(fallbackImg(c.mint))}" alt="" /><div><div class="name">${esc(c.name||'Unknown')}</div><div class="sym">$${esc((c.symbol||'').toUpperCase())} · ${esc(short(c.mint))}</div><div style="margin-top:8px;display:flex;gap:8px;align-items:center;flex-wrap:wrap">${catBadge(c.category)}${verdictPill(v)}${c.is_news_meme?'<span class="flag soft" style="text-transform:none">news meme</span>':''}</div></div></div>@@ -1035,6 +1035,7 @@document.addEventListener('visibilitychange', () => { if (!document.hidden && state.tab === 'radar') loadRadar(); });</script><script src="/brand.js" defer></script>+ <script src="/img-fallback.js" defer></script><script>fetch('/api/oracle/stats').then(r=>r.ok?r.json():null).then(d=>{if(!d) return;diff --git a/pages/daily-match.html b/pages/daily-match.htmlindex c6d869bce..ef87c36ba 100644--- a/pages/daily-match.html+++ b/pages/daily-match.html@@ -122,6 +122,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Daily Match: three.ws"><script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Daily Match","description":"Which agent ships the most real output today? Live daily standings over real agent activity: actions, trades, skill sales, and coin launches. Resets at 00:00 UTC.","url":"https://three.ws/daily-match","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=labs&t=Daily+Match&d=Which+agent+ships+the+most+real+output+today%3F+Live+daily+standings+over+real+agent+activity%3A+actions%2C+trades%2C+skill+sales%2C+and+coin+launches.+Resets+at+00%3A00+UT&p=%2Fdaily-match"}]}</script>+<script src="/img-fallback.js" defer></script></head><body><header><div id="nav-container"></div></header>@@ -185,7 +186,7 @@const agentHref = (id) => `/agents/${encodeURIComponent(id)}`;const avatarImg = (row, cls) =>row.avatar_url- ? `<img class="${cls}" src="${esc(row.avatar_url)}" alt="" loading="lazy" onerror="this.style.visibility='hidden'" />`+ ? `<img class="${cls}" src="${esc(row.avatar_url)}" alt="" loading="lazy" data-fallback="invisible" />`: `<span class="${cls}" aria-hidden="true"></span>`;let resetsAt = null;diff --git a/pages/payments.html b/pages/payments.htmlindex b547ec10b..1ba5031f3 100644--- a/pages/payments.html+++ b/pages/payments.html@@ -283,7 +283,7 @@<p data-i18n="payments.fund_spend_envelopes_from_your_credits_agent">Fund spend envelopes from your credits. Agents call paid x402 endpoints using a session token — the platform wallet signs. Budget, URL allowlists, and per-tx limits are enforced atomically.</p></div><div class="pw-hero-actions">- <button class="btn-ghost" id="btnDocs" onclick="window.open('https://three.ws/docs/payments','_blank')">+ <button class="btn-ghost" id="btnDocs" type="button"><svg width="14" height="14" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><rect x="3" y="2" width="14" height="16" rx="2"/><path d="M7 6h6M7 10h6M7 14h4"/></svg>Docs</button>@@ -923,6 +923,7 @@}$('btnNew').addEventListener('click', openCreate);+ $('btnDocs').addEventListener('click', () => window.open('https://three.ws/docs/payments', '_blank', 'noopener'));$('mClose').addEventListener('click', closeCreate);$('createModal').addEventListener('click', e => { if (e.target === $('createModal')) closeCreate(); });diff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.htmlindex 80254df35..b10819e45 100644--- a/pages/pump-dashboard.html+++ b/pages/pump-dashboard.html@@ -2342,10 +2342,10 @@<td>${(() => {const fallback = tokenLogoFallback(t.mint || t.symbol, t.symbol);const src = t.logo || fallback;- // onerror swaps a broken remote logo to the local- // data-URI fallback exactly once (guarded so a failing- // fallback can't loop).- return `<img class="pd-token-logo" src="${escapeHtml(src)}" alt="" loading="lazy" data-fallback="${escapeHtml(fallback)}" onerror="if(this.dataset.fallback&&this.src!==this.dataset.fallback){this.src=this.dataset.fallback}else{this.remove()}" />`;+ // /img-fallback.js swaps a broken remote logo to the+ // local data-URI fallback exactly once, then drops the+ // image if that fails too.+ return `<img class="pd-token-logo" src="${escapeHtml(src)}" alt="" loading="lazy" data-fallback-src="${escapeHtml(fallback)}" data-fallback="remove" />`;})()}<span class="pd-mono">${escapeHtml(t.symbol || shortAddr(t.mint || ''))}</span></td><td style="text-align:right" class="pd-mono">${t.amount.toLocaleString(undefined, { maximumFractionDigits: 4 })}</td><td style="text-align:right" class="pd-mono">${t.usd > 0 ? '$' + t.usd.toLocaleString(undefined, { maximumFractionDigits: 2 }) : '—'}</td>@@ -5294,6 +5294,7 @@<script src="/footer.js" defer></script><script src="/brand.js" defer></script>+ <script src="/img-fallback.js" defer></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. --><script type="module" src="/i18n.js"></script></body>diff --git a/pages/pump-live.html b/pages/pump-live.htmlindex d76d031f6..c7f045a5e 100644--- a/pages/pump-live.html+++ b/pages/pump-live.html@@ -423,7 +423,7 @@<span class="stat-label" data-i18n="pump_live.last_launch">Last launch</span><span class="stat-value" id="stat-age" aria-live="polite">—</span></div>- <div class="stat" style="cursor:pointer" title="Filter to prime coins" onclick="document.querySelector('[data-ftier=prime]')?.click()">+ <div class="stat" id="stat-prime-filter" style="cursor:pointer" title="Filter to prime coins"><span class="stat-label" data-i18n="pump_live.prime_scored">🔮 Prime scored</span><span class="stat-value" id="stat-prime" aria-live="polite" style="color:#c084fc">0</span></div>@@ -602,6 +602,11 @@}});+ // The "Prime scored" stat doubles as a shortcut into the prime filter.+ document.getElementById('stat-prime-filter').addEventListener('click', () => {+ document.querySelector('#filter-bar [data-ftier="prime"]')?.click();+ });+// Wire conviction filter buttonsdocument.getElementById('filter-bar').addEventListener('click', (e) => {const btn = e.target.closest('[data-ftier]');diff --git a/pages/smart-money.html b/pages/smart-money.htmlindex 229afa1d7..b5f5daf47 100644--- a/pages/smart-money.html+++ b/pages/smart-money.html@@ -296,6 +296,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Smart Money Radar — follow the wallets that win on pump.fun — three.ws"><meta name="twitter:site" content="@trythreews">+<script src="/img-fallback.js" defer></script></head><body><div id="nav-container"></div>@@ -496,7 +497,7 @@const imgSeed = c.symbol || c.name || c.mint || 'coin';const imgFallback = `/api/img?seed=${encodeURIComponent(imgSeed)}`;const img = c.image_uri && /^https?:\/\//i.test(c.image_uri)- ? `<img class="coin-img" src="${esc(`/api/img?url=${encodeURIComponent(c.image_uri)}&seed=${encodeURIComponent(imgSeed)}`)}" alt="" loading="lazy" onerror="this.onerror=null;this.src='${esc(imgFallback)}'">`+ ? `<img class="coin-img" src="${esc(`/api/img?url=${encodeURIComponent(c.image_uri)}&seed=${encodeURIComponent(imgSeed)}`)}" alt="" loading="lazy" data-fallback-src="${esc(imgFallback)}">`: `<div class="coin-img">${esc((c.symbol || '?').slice(0, 2))}</div>`;const notable = (c.notable || []).slice(0, 4).map((n) =>`<span class="nlabel lb-${n.label || 'neutral'}">${short(n.wallet)}</span>`).join('');@@ -902,7 +903,7 @@const coins = (recent_coins || []).slice(0, 18).map((c) => `<div class="nwallet" data-mint="${esc(c.mint)}" role="button" tabindex="0"><div class="lw-top"><span class="lw-addr">${esc(c.symbol || c.mint.slice(0, 8))}</span>${c.graduated ? '<span class="nlabel lb-smart_money">graduated</span>' : ''}</div><div class="lstat">${fmtSol(c.buy_sol)}◎</div>- <a class="solscan" href="https://pump.fun/${esc(c.mint)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">pump ↗</a>+ <a class="solscan" href="https://pump.fun/${esc(c.mint)}" target="_blank" rel="noopener">pump ↗</a></div>`).join('') || '<p style="color:var(--muted)">No recent coins on record.</p>';const last = ago(w.last_active_at);$('drBody').innerHTML = `@@ -925,7 +926,9 @@wireCopy($('drBody'));$('drBody').querySelectorAll('.nwallet[data-mint]').forEach((el) => {const go = () => openCoin(el.dataset.mint);- el.addEventListener('click', go);+ // The card links out to pump.fun; a click on that anchor must not+ // also open the coin drawer behind it.+ el.addEventListener('click', (e) => { if (!e.target.closest('a')) go(); });el.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } });});} catch (e) {diff --git a/pages/tour-builder.html b/pages/tour-builder.htmlindex 56bceb0f6..6eda19323 100644--- a/pages/tour-builder.html+++ b/pages/tour-builder.html@@ -297,16 +297,16 @@<div class="store"><div class="announce">Free shipping on orders over $60 · Summer collection is live</div><header>- <a class="logo" href="javascript:void(0)" data-i18n="tour_builder.northwind_goods">NORTHWIND GOODS</a>- <nav><a href="javascript:void(0)" data-i18n="tour_builder.home">Home</a><a href="javascript:void(0)" data-i18n="tour_builder.catalog">Catalog</a><a href="javascript:void(0)" data-i18n="tour_builder.about">About</a><a href="javascript:void(0)" data-i18n="tour_builder.reviews">Reviews</a><a href="javascript:void(0)" data-i18n="tour_builder.shipping">Shipping</a></nav>- <a class="cart" href="javascript:void(0)" data-i18n="tour_builder.cart_0">Cart · 0</a>+ <a class="logo" href="#" data-demo-link data-i18n="tour_builder.northwind_goods">NORTHWIND GOODS</a>+ <nav><a href="#" data-demo-link data-i18n="tour_builder.home">Home</a><a href="#" data-demo-link data-i18n="tour_builder.catalog">Catalog</a><a href="#" data-demo-link data-i18n="tour_builder.about">About</a><a href="#" data-demo-link data-i18n="tour_builder.reviews">Reviews</a><a href="#" data-demo-link data-i18n="tour_builder.shipping">Shipping</a></nav>+ <a class="cart" href="#" data-demo-link data-i18n="tour_builder.cart_0">Cart · 0</a></header><section class="hero" id="hero"><div><h1 data-i18n="tour_builder.handcrafted_homeware_for_slow_mornings">Handcrafted homeware for slow mornings</h1><p data-i18n="tour_builder.small_batch_ceramics_linen_and_oak_made">Small-batch ceramics, linen, and oak — made by workshops we know by name. Every piece is finished by hand and built to outlast trends.</p>- <a class="cta" id="hero-cta" href="javascript:void(0)" data-i18n="tour_builder.shop_the_collection">Shop the collection</a>+ <a class="cta" id="hero-cta" href="#" data-demo-link data-i18n="tour_builder.shop_the_collection">Shop the collection</a></div><div class="hero-art" role="img" aria-label="Stoneware mugs on an oak shelf"></div></section>@@ -315,12 +315,12 @@<h2 data-i18n="tour_builder.featured_products">Featured products</h2><p class="sub" data-i18n="tour_builder.this_season_s_most_loved_pieces_restocked">This season's most-loved pieces, restocked weekly.</p><div class="grid">- <a class="product" href="javascript:void(0)"><div class="ph" style="background:linear-gradient(140deg,#dcd5c9,#b8ad99)"></div><div class="meta"><h3 data-i18n="tour_builder.stoneware_mug_fog">Stoneware Mug — Fog</h3><div class="price">$28.00</div></div></a>- <a class="product" href="javascript:void(0)"><div class="ph" style="background:linear-gradient(140deg,#d7e0d7,#9fb5a1)"></div><div class="meta"><h3 data-i18n="tour_builder.linen_table_runner">Linen Table Runner</h3><div class="price">$54.00</div></div></a>- <a class="product" href="javascript:void(0)"><div class="ph" style="background:linear-gradient(140deg,#e6dccd,#c2a678)"></div><div class="meta"><h3 data-i18n="tour_builder.oak_serving_board">Oak Serving Board</h3><div class="price">$72.00</div></div></a>- <a class="product" href="javascript:void(0)"><div class="ph" style="background:linear-gradient(140deg,#ded8d2,#a89f96)"></div><div class="meta"><h3 data-i18n="tour_builder.ceramic_pour_over_set">Ceramic Pour-Over Set</h3><div class="price">$96.00</div></div></a>- <a class="product" href="javascript:void(0)"><div class="ph" style="background:linear-gradient(140deg,#e0dbd3,#bfb2a0)"></div><div class="meta"><h3 data-i18n="tour_builder.wool_throw_oat">Wool Throw — Oat</h3><div class="price">$148.00</div></div></a>- <a class="product" href="javascript:void(0)"><div class="ph" style="background:linear-gradient(140deg,#d9dfd9,#8fa892)"></div><div class="meta"><h3 data-i18n="tour_builder.botanical_candle_no_4">Botanical Candle No. 4</h3><div class="price">$36.00</div></div></a>+ <a class="product" href="#" data-demo-link><div class="ph" style="background:linear-gradient(140deg,#dcd5c9,#b8ad99)"></div><div class="meta"><h3 data-i18n="tour_builder.stoneware_mug_fog">Stoneware Mug — Fog</h3><div class="price">$28.00</div></div></a>+ <a class="product" href="#" data-demo-link><div class="ph" style="background:linear-gradient(140deg,#d7e0d7,#9fb5a1)"></div><div class="meta"><h3 data-i18n="tour_builder.linen_table_runner">Linen Table Runner</h3><div class="price">$54.00</div></div></a>+ <a class="product" href="#" data-demo-link><div class="ph" style="background:linear-gradient(140deg,#e6dccd,#c2a678)"></div><div class="meta"><h3 data-i18n="tour_builder.oak_serving_board">Oak Serving Board</h3><div class="price">$72.00</div></div></a>+ <a class="product" href="#" data-demo-link><div class="ph" style="background:linear-gradient(140deg,#ded8d2,#a89f96)"></div><div class="meta"><h3 data-i18n="tour_builder.ceramic_pour_over_set">Ceramic Pour-Over Set</h3><div class="price">$96.00</div></div></a>+ <a class="product" href="#" data-demo-link><div class="ph" style="background:linear-gradient(140deg,#e0dbd3,#bfb2a0)"></div><div class="meta"><h3 data-i18n="tour_builder.wool_throw_oat">Wool Throw — Oat</h3><div class="price">$148.00</div></div></a>+ <a class="product" href="#" data-demo-link><div class="ph" style="background:linear-gradient(140deg,#d9dfd9,#8fa892)"></div><div class="meta"><h3 data-i18n="tour_builder.botanical_candle_no_4">Botanical Candle No. 4</h3><div class="price">$36.00</div></div></a></div></section>diff --git a/pages/unstoppable.html b/pages/unstoppable.htmlindex f3825ba9c..76367ad06 100644--- a/pages/unstoppable.html+++ b/pages/unstoppable.html@@ -546,7 +546,7 @@<div class="donate-block" style="margin-top: 28px;"><div class="donate-label" id="donateLabel">Keep it alive — donate $0.01 USDC to extend the agent's runway and unlock the live view.</div>- <button class="btn primary" id="donateBtn" type="button" aria-label="Donate $0.01 USDC to fund the agent" onclick="window.__unstoppable.donate()" data-i18n="unstoppable.donate_0_01" data-i18n-attr="aria-label:unstoppable.donate_0_01_usdc_to_fund_the_arialabel">+ <button class="btn primary" id="donateBtn" type="button" aria-label="Donate $0.01 USDC to fund the agent" data-i18n="unstoppable.donate_0_01" data-i18n-attr="aria-label:unstoppable.donate_0_01_usdc_to_fund_the_arialabel">Donate $0.01</button><div class="donate-retry" id="donateRetry" role="note">diff --git a/pages/walk-analytics.html b/pages/walk-analytics.htmlindex 7a9b64f7e..87f43765d 100644--- a/pages/walk-analytics.html+++ b/pages/walk-analytics.html@@ -154,6 +154,16 @@function showGate(html) { gate.innerHTML = html; gate.hidden = false; dash.hidden = true; }+ // Error states are rendered from strings, so their buttons declare what+ // they do with data-action and this one delegated listener runs it. The+ // site CSP allows inline <script> by hash only, so an onclick attribute+ // on generated markup would never fire.+ document.addEventListener('click', (event) => {+ const action = event.target.closest('[data-action]')?.dataset.action;+ if (action === 'reload') location.reload();+ else if (action === 'retry') loadAnalytics();+ });+function fmtDistance(m) { return m >= 1000 ? (m / 1000).toFixed(2) + ' km' : Math.round(m) + ' m'; }function fmtDuration(s) {s = Math.round(s);@@ -172,7 +182,7 @@if (!res.ok) throw new Error('HTTP ' + res.status);mine = await res.json();} catch (err) {- return showGate(`<div class="wa-state"><p class="wa-state-title">Couldn't load your avatars</p><p class="wa-state-msg">${esc(err.message || 'Something went wrong.')}</p><button class="wa-cta" type="button" onclick="location.reload()">Retry</button></div>`);+ return showGate(`<div class="wa-state"><p class="wa-state-title">Couldn't load your avatars</p><p class="wa-state-msg">${esc(err.message || 'Something went wrong.')}</p><button class="wa-cta" type="button" data-action="reload">Retry</button></div>`);}const avatars = (mine && mine.avatars) || [];@@ -223,8 +233,7 @@if (!res.ok) throw new Error('HTTP ' + res.status);data = await res.json();} catch (err) {- document.getElementById('wa-chart-wrap').innerHTML = `<div class="wa-empty">Couldn't load analytics — ${esc(err.message || 'error')}. <button class="wa-cta ghost" type="button" style="margin-left:8px" onclick="this.dispatchEvent(new CustomEvent('retry',{bubbles:true}))">Retry</button></div>`;- document.getElementById('wa-chart-wrap').addEventListener('retry', loadAnalytics, { once: true });+ document.getElementById('wa-chart-wrap').innerHTML = `<div class="wa-empty">Couldn't load analytics — ${esc(err.message || 'error')}. <button class="wa-cta ghost" type="button" style="margin-left:8px" data-action="retry">Retry</button></div>`;return;}diff --git a/public/agents/index.html b/public/agents/index.htmlindex 53033b53a..c93ec1d5a 100644--- a/public/agents/index.html+++ b/public/agents/index.html@@ -247,7 +247,7 @@// host degrades to the lettered fallback instead of a console error.const img = a.image ? `/api/img?url=${encodeURIComponent(a.image)}` : null;const avatar = img- ? `<img class="ag-avatar" src="${esc(img)}" alt="" loading="lazy" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" /><div class="ag-avatar-fallback" style="display:none">${esc(initial(a.name))}</div>`+ ? `<img class="ag-avatar" src="${esc(img)}" alt="" loading="lazy" data-fallback="sibling" /><div class="ag-avatar-fallback" style="display:none">${esc(initial(a.name))}</div>`: `<div class="ag-avatar-fallback">${esc(initial(a.name))}</div>`;const services = (a.services || []).map((s) => s && s.name).filter(Boolean).concat(a.skills || []).slice(0, 3);@@ -352,6 +352,7 @@load(true);</script><script src="/brand.js" defer></script>+ <script src="/img-fallback.js" defer></script><div id="footer-container"></div><script src="/footer.js"></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->diff --git a/public/cz/offline/index.html b/public/cz/offline/index.htmlindex 16bc48a2a..5a027b996 100644--- a/public/cz/offline/index.html+++ b/public/cz/offline/index.html@@ -282,7 +282,7 @@<h2>Claim Successful!</h2><p>Your agent is now registered on Base Sepolia.</p><p>Transaction: <span class="code">0xabc123…</span></p>- <button class="button" onclick="document.getElementById('modal').classList.remove('active')">Close</button>+ <button class="button" type="button" data-close-modal>Close</button>`);}, 3200);}@@ -417,7 +417,7 @@ui.style.transform = 'translateX(-50%)';ui.style.zIndex = '50';ui.innerHTML = `- <button class="button" style="font-size: 16px; padding: 16px 32px;" onclick="window.handleClaimClick()">+ <button class="button" type="button" style="font-size: 16px; padding: 16px 32px;" data-claim-agent>Claim Agent</button>`;@@ -425,7 +425,16 @@}// Export for global access- window.handleClaimClick = handleClaimClick;+ // The demo builds its overlays from strings, so their buttons declare+ // what they do and this delegated listener runs it. The site CSP allows+ // inline <script> by hash only, never inline handlers.+ document.addEventListener('click', (event) => {+ if (event.target.closest('[data-close-modal]')) {+ document.getElementById('modal').classList.remove('active');+ return;+ }+ if (event.target.closest('[data-claim-agent]')) handleClaimClick();+ });// Initialize when page loadsdocument.addEventListener('DOMContentLoaded', () => {diff --git a/public/dashboard/index.html b/public/dashboard/index.htmlindex eda76acda..6591b2f80 100644--- a/public/dashboard/index.html+++ b/public/dashboard/index.html@@ -1327,7 +1327,9 @@<a href="/forge" class="dash-announce-cta" data-i18n="dashboard_index.try_forge">Try Forge →</a><buttonclass="dash-announce-dismiss"- onclick="document.getElementById('forge-announce').remove();localStorage.setItem('forge-announce-dismissed','1')"+ type="button"+ data-dismiss-banner="forge-announce"+ data-dismiss-key="forge-announce-dismissed"aria-label="Dismiss announcement"data-i18n-attr="aria-label:dashboard_index.dismiss_announcement_arialabel">×@@ -1338,6 +1340,20 @@var __fab = document.getElementById('forge-announce');if (__fab) __fab.remove();}+ // Dismiss buttons declare the banner they close and the localStorage+ // key that remembers it. Bound here rather than with onclick+ // attributes, which the site CSP does not allow.+ document.addEventListener('click', function (event) {+ var button = event.target.closest('[data-dismiss-banner]');+ if (!button) return;+ var banner = document.getElementById(button.dataset.dismissBanner);+ if (banner) banner.remove();+ try {+ localStorage.setItem(button.dataset.dismissKey, '1');+ } catch (err) {+ /* private browsing: the banner still closes for this visit */+ }+ });</script><div id="dn-next-banner" style="display: flex;@@ -1356,7 +1372,7 @@switch to new version</button></span>- <button onclick="document.getElementById('dn-next-banner').remove();localStorage.setItem('dn-next-dismissed','1')"+ <button type="button" data-dismiss-banner="dn-next-banner" data-dismiss-key="dn-next-dismissed"style="background:none;border:none;color:#888;font-size:18px;cursor:pointer;line-height:1;padding:0 2px"aria-label="Dismiss" data-i18n-attr="aria-label:dashboard_index.dismiss_arialabel">×</button></div>diff --git a/public/dashboard/portfolio-asset.html b/public/dashboard/portfolio-asset.htmlindex 402e252a7..e8906d25a 100644--- a/public/dashboard/portfolio-asset.html+++ b/public/dashboard/portfolio-asset.html@@ -364,7 +364,7 @@const change = m.change_24h_pct;const changeCls = change == null ? 'flat' : change >= 0 ? 'up' : 'down';const logoInner = asset.logo- ? `<img src="${escapeHtml(asset.logo)}" alt="" onerror="this.style.display='none';this.parentElement.textContent='${escapeHtml((asset.symbol || '?').slice(0,3))}'" />`+ ? `<img src="${escapeHtml(asset.logo)}" alt="" data-fallback="parent-text" data-fallback-text="${escapeHtml((asset.symbol || '?').slice(0,3))}" />`: escapeHtml((asset.symbol || '?').slice(0, 3));const name = m.name || asset.symbol || asset.id;const isAddr = !asset.is_native;@@ -788,6 +788,7 @@})();</script><script src="/brand.js" defer></script>+ <script src="/img-fallback.js" defer></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. --><script type="module" src="/i18n.js"></script></body>diff --git a/public/dashboard/portfolio.html b/public/dashboard/portfolio.htmlindex 7cfce48ee..18df07f15 100644--- a/public/dashboard/portfolio.html+++ b/public/dashboard/portfolio.html@@ -994,7 +994,7 @@const alloc = totalUsd > 0 ? (r.usd / totalUsd) * 100 : 0;const changeColor = r.change24h == null ? 'var(--muted)' : (r.change24h >= 0 ? 'var(--ok)' : 'var(--err)');const logoInner = r.logo- ? `<img src="${escapeHtml(r.logo)}" alt="" loading="lazy" onerror="this.style.display='none';this.parentElement.textContent='${escapeHtml((r.symbol || '?').slice(0,3))}'" />`+ ? `<img src="${escapeHtml(r.logo)}" alt="" loading="lazy" data-fallback="parent-text" data-fallback-text="${escapeHtml((r.symbol || '?').slice(0,3))}" />`: escapeHtml((r.symbol || '?').slice(0, 3));const chainCls = r.chain === 'solana' ? 'sol' : 'evm';const chainText = r.chain === 'solana' ? 'SOL' : 'EVM';@@ -1394,6 +1394,7 @@})();</script><script src="/brand.js" defer></script>+ <script src="/img-fallback.js" defer></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. --><script type="module" src="/i18n.js"></script></body>diff --git a/public/dashboard/wallets.html b/public/dashboard/wallets.htmlindex f8f7f3dc8..3cba22553 100644--- a/public/dashboard/wallets.html+++ b/public/dashboard/wallets.html@@ -282,7 +282,7 @@<span>${w.address.slice(0, 6)}…${w.address.slice(-4)}</span><buttonclass="copy-btn"- onclick="copyToClipboard('${w.address}')"+ data-copy-address="${w.address}"title="Copy full address">📋@@ -297,7 +297,7 @@<td style="text-align: right"><buttonclass="btn sec btn-sm"- onclick="unlinkWallet('${w.address}')"+ data-unlink-address="${w.address}"style="padding: 6px 10px; font-size: 12px">Unlink@@ -537,8 +537,15 @@el.style.display = 'block';}- window.copyToClipboard = copyToClipboard;- window.unlinkWallet = unlinkWallet;+ // Wallet rows are rendered from strings; their buttons name the address+ // they act on and this delegated listener runs it. Inline onclick+ // attributes do not survive the site CSP.+ document.addEventListener('click', (event) => {+ const copy = event.target.closest('[data-copy-address]');+ if (copy) return copyToClipboard(copy.dataset.copyAddress);+ const unlink = event.target.closest('[data-unlink-address]');+ if (unlink) unlinkWallet(unlink.dataset.unlinkAddress);+ });// Initialize(async () => {diff --git a/public/dashboard/x402.html b/public/dashboard/x402.htmlindex 4a7d8cb79..33efdb35c 100644--- a/public/dashboard/x402.html+++ b/public/dashboard/x402.html@@ -448,7 +448,7 @@<div class="empty"><h3>No SKUs yet</h3><p>Create your first checkout link — point it at any 402-enabled endpoint.</p>- <p style="margin-top:18px"><button class="btn" onclick="document.getElementById('newBtn').click()">+ Create SKU</button></p>+ <p style="margin-top:18px"><button class="btn" type="button" data-open-new-sku>+ Create SKU</button></p></div>`;$('stats').style.display = 'none';return;@@ -513,6 +513,10 @@skuForm.target_method.addEventListener('change', toggleBody);$('newBtn').addEventListener('click', () => openModal(null));+ // The empty state renders its own CTA from a string, so it is delegated.+ document.addEventListener('click', (event) => {+ if (event.target.closest('[data-open-new-sku]')) openModal(null);+ });$('modalClose').addEventListener('click', closeModal);$('cancelBtn').addEventListener('click', closeModal);modal.addEventListener('click', (e) => { if (e.target === modal) closeModal(); });diff --git a/public/demos-embed/forge.html b/public/demos-embed/forge.htmlindex acd63a292..00046dd71 100644--- a/public/demos-embed/forge.html+++ b/public/demos-embed/forge.html@@ -169,7 +169,7 @@placeholder="e.g. e.g. a futuristic robot with glowing blue eyes…"value="">- <button class="prompt-btn" onclick="openForge()" data-i18n="demos_embed_forge.generate">Generate →</button>+ <button class="prompt-btn" id="forge-generate" type="button" data-i18n="demos_embed_forge.generate">Generate →</button></div><p class="prompt-note" data-i18n-html="demos_embed_forge.generation_happens_on_three_ws_forge_real">Generation happens on <a href="https://three.ws/forge" target="_blank" rel="noopener">three.ws/forge</a> — real Meshy API, real GLB output.@@ -188,6 +188,7 @@document.getElementById('prompt-input').addEventListener('keydown', function(e) {if (e.key === 'Enter') openForge();});+ document.getElementById('forge-generate').addEventListener('click', openForge);</script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. --><script type="module" src="/i18n.js"></script>diff --git a/public/img-fallback.js b/public/img-fallback.jsnew file mode 100644index 000000000..045d85588--- /dev/null+++ b/public/img-fallback.js@@ -0,0 +1,91 @@+/**+ * Declarative <img> failure handling, without inline onerror attributes.+ *+ * The site's Content-Security-Policy allows inline <script> blocks by hash and+ * nothing else, so `onerror="..."` attributes no longer run. Most of ours were+ * built inside template literals with interpolated URLs anyway, which no hash+ * could ever cover. This replaces all of them with one delegated listener.+ *+ * Load it once per page:+ * <script src="/img-fallback.js" defer></script>+ *+ * Then describe the failure behaviour on the image itself:+ *+ * data-fallback-src="URL" swap to URL on the first failure. If URL also+ * fails, the element is removed unless+ * data-fallback names something else to do.+ * data-fallback="hide" display:none+ * data-fallback="invisible" visibility:hidden (keeps the layout box)+ * data-fallback="remove" drop the element+ * data-fallback="sibling" hide the image and reveal its next element+ * sibling (display from data-fallback-display,+ * default "flex")+ * data-fallback="text" replace the image with data-fallback-text+ * data-fallback="parent-text" hide the image and set the parent's text to+ * data-fallback-text+ *+ * `error` does not bubble, so the listener is registered in the capture phase.+ * That also means images added to the DOM later are covered with no re-init:+ * a page can render markup whenever it likes and the behaviour still applies.+ */+(function () {+ 'use strict';+ if (window.__imgFallbackInstalled) return;+ window.__imgFallbackInstalled = true;++ const HANDLED = '__imgFallbackDone';++ function reveal(el, display) {+ if (el instanceof HTMLElement) el.style.display = display || 'flex';+ }++ function apply(img) {+ const mode = img.dataset.fallback || '';+ switch (mode) {+ case 'hide':+ img.style.display = 'none';+ return;+ case 'invisible':+ img.style.visibility = 'hidden';+ return;+ case 'remove':+ img.remove();+ return;+ case 'sibling':+ img.style.display = 'none';+ reveal(img.nextElementSibling, img.dataset.fallbackDisplay);+ return;+ case 'text':+ img.replaceWith(document.createTextNode(img.dataset.fallbackText || ''));+ return;+ case 'parent-text':+ img.style.display = 'none';+ if (img.parentElement) img.parentElement.textContent = img.dataset.fallbackText || '';+ return;+ default:+ // A data-fallback-src that has already been tried and failed leaves+ // nothing sensible on screen, so drop the broken image.+ img.remove();+ }+ }++ document.addEventListener(+ 'error',+ function (event) {+ const img = event.target;+ if (!(img instanceof HTMLImageElement)) return;+ if (img[HANDLED]) return;++ const swap = img.dataset.fallbackSrc;+ if (swap && img.getAttribute('src') !== swap) {+ // One retry only: if the fallback image is itself broken, the next+ // error runs the declared mode instead of looping.+ img.setAttribute('src', swap);+ return;+ }+ img[HANDLED] = true;+ apply(img);+ },+ true,+ );+})();diff --git a/public/my-agents/index.html b/public/my-agents/index.htmlindex 9268ddad9..cc6e35836 100644--- a/public/my-agents/index.html+++ b/public/my-agents/index.html@@ -195,8 +195,8 @@return !!(a.onchain || m.sol_mint_address || m.erc8004_agent_id);};const thumb = (a) => {- if (a.avatar_thumbnail_url) return `<img class="ag-avatar" src="${esc(a.avatar_thumbnail_url)}" alt="" loading="lazy" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" />`;- if (a.avatar_model_url) return `<img class="ag-avatar" src="${esc(a.avatar_model_url)}" alt="" loading="lazy" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" />`;+ if (a.avatar_thumbnail_url) return `<img class="ag-avatar" src="${esc(a.avatar_thumbnail_url)}" alt="" loading="lazy" data-fallback="sibling" />`;+ if (a.avatar_model_url) return `<img class="ag-avatar" src="${esc(a.avatar_model_url)}" alt="" loading="lazy" data-fallback="sibling" />`;return '';};@@ -229,6 +229,7 @@load();</script><script src="/brand.js" defer></script>+ <script src="/img-fallback.js" defer></script><div id="footer-container"></div><script src="/footer.js"></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->diff --git a/public/pay/c/index.html b/public/pay/c/index.htmlindex 854c9d006..e495f5828 100644--- a/public/pay/c/index.html+++ b/public/pay/c/index.html@@ -218,7 +218,7 @@document.title = `${sku.merchant_name} · ${sku.action_name} — x402 checkout`;$('merchantName').textContent = sku.merchant_name;$('actionName').textContent = sku.action_name;- if (sku.logo_url) $('logo').innerHTML = `<img src="${escapeHtml(sku.logo_url)}" alt="" onerror="this.replaceWith(document.createTextNode('${escapeHtml(sku.merchant_name[0] || '·')}'))">`;+ if (sku.logo_url) $('logo').innerHTML = `<img src="${escapeHtml(sku.logo_url)}" alt="" data-fallback="text" data-fallback-text="${escapeHtml(sku.merchant_name[0] || '·')}">`;else $('logo').textContent = sku.merchant_name[0] || '·';if (sku.accent_color) {document.documentElement.style.setProperty('--accent', sku.accent_color);@@ -394,6 +394,7 @@</script><script src="/brand.js" defer></script>+ <script src="/img-fallback.js" defer></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. --><script type="module" src="/i18n.js"></script></body>diff --git a/public/pay/index.html b/public/pay/index.htmlindex 4f321a7eb..0c31b0055 100644--- a/public/pay/index.html+++ b/public/pay/index.html@@ -957,7 +957,7 @@ function renderAgentCards(agents) {el.className = 'agent-card' + (selectedAgent?.id === agent.id ? ' selected' : '');el.dataset.agentId = agent.id;const avatarHtml = agent.avatar_id- ? `<img src="https://three.ws/avatars/${agent.avatar_id}/thumbnail.png" onerror="this.style.display='none';this.nextSibling.style.display='flex'" alt="" /><span style="display:none">${escape(agent.name[0]||'?')}</span>`+ ? `<img src="https://three.ws/avatars/${agent.avatar_id}/thumbnail.png" data-fallback="sibling" alt="" /><span style="display:none">${escape(agent.name[0]||'?')}</span>`: `<span>${escape(agent.name[0]||'?')}</span>`;const walletHtml = agent.solana_address? `<span class="bal">${agent.usdc != null ? agent.usdc.toFixed(3)+' USDC' : ''}</span>`@@ -2278,6 +2278,7 @@ if (bscParams.get('chain') === 'bsc') activateChain('bsc');</script><script src="/brand.js" defer></script>+ <script src="/img-fallback.js" defer></script><!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. --><script type="module" src="/i18n.js"></script></body>diff --git a/public/scene-studio/app/index.html b/public/scene-studio/app/index.htmlindex 3971c40a7..d783bacb8 100644--- a/public/scene-studio/app/index.html+++ b/public/scene-studio/app/index.html@@ -17,7 +17,7 @@}</style></head>- <body ontouchstart="">+ <body><script type="importmap"><!-- importmap --></script><script type="module">diff --git a/public/studio/index.html b/public/studio/index.htmlindex 7f9e3566c..ea79d6b80 100644--- a/public/studio/index.html+++ b/public/studio/index.html@@ -200,7 +200,6 @@id="config-form"class="config-form"autocomplete="off"- onsubmit="return false"><labelclass="field"diff --git a/public/studio/studio.js b/public/studio/studio.jsindex 5d03e7807..577c7b49e 100644--- a/public/studio/studio.js+++ b/public/studio/studio.js@@ -195,6 +195,10 @@ const $ = (sel, root = document) => root.querySelector(sel);const layoutEl = $('#studio-layout');const formEl = $('#config-form');+// The config form is a layout container, not a submission target: every control+// applies live. Enter in a text field would otherwise reload the page. Bound+// here rather than with an onsubmit attribute, which the site CSP blocks.+formEl.addEventListener('submit', (event) => event.preventDefault());const errEl = $('#form-error');const previewIfr = $('#preview-iframe');const previewSt = $('#preview-status');diff --git a/public/tour-builder/builder.js b/public/tour-builder/builder.jsindex f2adcbf74..0b33ce057 100644--- a/public/tour-builder/builder.js+++ b/public/tour-builder/builder.js@@ -303,6 +303,13 @@ function pickTarget(el) {return nice || el;}+// The demo storefront's links are scenery, not navigation: they exist so the+// stage looks like a real shop you can point at. `href="#"` keeps them+// focusable and hoverable like real links; this swallows the navigation.+stage.addEventListener('click', (e) => {+ if (e.target.closest('[data-demo-link]')) e.preventDefault();+});+stage.addEventListener('click', (e) => {if (!pickingId) return;e.preventDefault(); e.stopPropagation();diff --git a/public/validation/index.html b/public/validation/index.htmlindex b3b8af04f..4971237d1 100644--- a/public/validation/index.html+++ b/public/validation/index.html@@ -1031,7 +1031,7 @@</div><div class="modal-actions">- <button class="btn sec" onclick="closeSubmitModal()" data-i18n="validation_index.cancel">Cancel</button>+ <button class="btn sec" id="cancel-report-btn" type="button" data-i18n="validation_index.cancel">Cancel</button><button class="btn" id="submit-report-btn" disabled data-i18n="validation_index.submit_on_chain">Submit on-chain</button></div></div>@@ -1080,7 +1080,7 @@window.valDash = dashboard;window.valPage = page;- window.closeSubmitModal = () => dashboard.closeModal();+ document.getElementById('cancel-report-btn').addEventListener('click', () => dashboard.closeModal());document.getElementById('empty-submit-btn')diff --git a/public/vanity/gallery/index.html b/public/vanity/gallery/index.htmlindex 2b4605ae5..c668c41eb 100644--- a/public/vanity/gallery/index.html+++ b/public/vanity/gallery/index.html@@ -294,7 +294,15 @@const x = `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(pageUrl)}`;window.open(x, '_blank', 'noopener');}- window.__shareCard = shareCard;+ // Cards are rendered from strings, so their buttons declare the address+ // they share and one delegated listener does the work. Inline onclick+ // attributes cannot run under the site CSP.+ document.addEventListener('click', (event) => {+ const target = event.target.closest('[data-share-card], [data-action="reload"]');+ if (!target) return;+ if (target.dataset.action === 'reload') location.reload();+ else shareCard(target.dataset.shareCard);+ });// ── Stats strip ────────────────────────────────────────────────────────async function loadStats() {@@ -340,7 +348,7 @@<div class="acts"><a href="${esc(e.explorerUrl)}" target="_blank" rel="noopener">Explorer ↗</a><a href="/vanity/verify" >Verify</a>- <button type="button" onclick="window.__shareCard('${esc(e.address)}')">Share</button>+ <button type="button" data-share-card="${esc(e.address)}">Share</button></div></article>`;}@@ -399,7 +407,7 @@galleryState.hasMore = data.hasMore;$('loadmore-row').style.display = data.hasMore ? 'block' : 'none';} catch {- if (galleryState.offset === 0) grid.innerHTML = `<div class="empty"><div class="glyph">⚠</div><h3>Couldn't load the gallery</h3><p>Check your connection and try again.</p><a class="cta" href="javascript:void 0" onclick="location.reload()">Retry</a></div>`;+ if (galleryState.offset === 0) grid.innerHTML = `<div class="empty"><div class="glyph">⚠</div><h3>Couldn't load the gallery</h3><p>Check your connection and try again.</p><button class="cta" type="button" data-action="reload">Retry</button></div>`;} finally {galleryState.loading = false;$('loadmore-btn').disabled = false;@@ -468,7 +476,7 @@<div class="s"><div class="k">Grind cost (≈20M/s)</div><div class="v">${esc(a.grindHuman)}</div></div></div>${a.bonuses.length ? `<div class="bonuses" style="margin-top:1rem">${a.bonuses.map((b) => `<span class="bonus">${esc(b.label)} +${b.bits} bits</span>`).join('')}</div>` : ''}- <div class="acts" style="margin-top:1.1rem"><button type="button" class="ghost" onclick="window.__shareCard('${esc(addr)}')">Share this card</button>+ <div class="acts" style="margin-top:1.1rem"><button type="button" class="ghost" data-share-card="${esc(addr)}">Share this card</button><a class="ghost" style="text-decoration:none" href="/api/vanity/og?address=${encodeURIComponent(addr)}" target="_blank" rel="noopener">View OG card ↗</a></div>`;resEl.classList.add('show');}@@ -487,7 +495,7 @@const r = await fetch(API, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ receipt, label: $('publish-label').value.trim() }) });const data = await r.json();if (!r.ok) throw new Error(data.error_description || data.error || 'publish failed');- okEl.innerHTML = `Published! Your <strong>${esc(data.entry.tierLabel)}</strong> wallet is on the board. <a href="#${encodeURIComponent(data.entry.address)}" style="color:#4ade80;text-decoration:underline">View it</a> · <a href="javascript:void 0" id="post-share" style="color:#4ade80;text-decoration:underline">Share card</a>`;+ okEl.innerHTML = `Published! Your <strong>${esc(data.entry.tierLabel)}</strong> wallet is on the board. <a href="#${encodeURIComponent(data.entry.address)}" style="color:#4ade80;text-decoration:underline">View it</a> · <button type="button" id="post-share" style="background:none;border:0;padding:0;font:inherit;cursor:pointer;color:#4ade80;text-decoration:underline">Share card</button>`;okEl.classList.add('show');const ps = document.getElementById('post-share'); if (ps) ps.onclick = () => shareCard(data.entry.address);$('publish-receipt').value = ''; $('publish-label').value = '';diff --git a/public/vanity/premium/index.html b/public/vanity/premium/index.htmlindex 4a61c783a..bdc662b1a 100644--- a/public/vanity/premium/index.html+++ b/public/vanity/premium/index.html@@ -243,7 +243,7 @@if (!res.ok) throw new Error('HTTP ' + res.status);data = await res.json();} catch (err) {- listEl.innerHTML = `<div class="state"><h3>Couldn't load inventory</h3><p>${esc(err.message)}. The store may be warming up — try again.</p><a class="cta" href="#" onclick="location.reload();return false">Retry</a></div>`;+ listEl.innerHTML = `<div class="state"><h3>Couldn't load inventory</h3><p>${esc(err.message)}. The store may be warming up — try again.</p><button class="cta" type="button" data-action="reload">Retry</button></div>`;return;}if (data.custodyNotice) document.getElementById('custody-copy').innerHTML = '<b>Custody:</b> ' + esc(data.custodyNotice);@@ -266,6 +266,12 @@listEl.appendChild(grid);}+ // The error state renders its retry button from a string, so it is+ // delegated rather than bound with an inline onclick the CSP would block.+ document.addEventListener('click', (event) => {+ if (event.target.closest('[data-action="reload"]')) location.reload();+ });+qEl.addEventListener('input', () => { clearTimeout(debounce); debounce = setTimeout(load, 280); });tierEl.addEventListener('change', load);sortEl.addEventListener('change', load);diff --git a/scripts/audit-inline-handlers.mjs b/scripts/audit-inline-handlers.mjsnew file mode 100644index 000000000..fd1ae908a--- /dev/null+++ b/scripts/audit-inline-handlers.mjs@@ -0,0 +1,130 @@+#!/usr/bin/env node+// Fails when HTML in this repo carries something the site's CSP cannot allow.+//+// server/csp-hashes.mjs replaces `script-src 'unsafe-inline'` with the hashes+// of the inline scripts in each response. Hashes cover `<script>` blocks and+// nothing else: an inline event handler attribute (`onclick="..."`) or a+// `javascript:` URL still needs `'unsafe-inline'` (or `'unsafe-hashes'`, which+// is barely better), so any that survive would silently stop working in+// production. Most of ours are built inside template literals with interpolated+// values, which no hash can cover anyway.+//+// The fix is always the same shape: bind the behaviour with addEventListener+// (or a delegated listener keyed off a data-* attribute) instead of an+// attribute, and use a <button> or a real href instead of `javascript:`.+//+// Usage:+// node scripts/audit-inline-handlers.mjs # repo sources+// node scripts/audit-inline-handlers.mjs --dist # built output too++import { readFileSync, readdirSync, statSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');++// Roots that produce HTML the site actually serves. `character-studio` and+// `chat` build through their own toolchains into dist/ and are covered by+// --dist; scanning their sources would flag framework templates that never+// reach a served document in this form.+const SOURCE_ROOTS = ['pages', 'public'];+const DIST_ROOTS = ['dist'];++const SKIP_DIRS = new Set(['node_modules', '.git', 'assets', 'locales']);++// Attribute-position `on*` handlers. Anchored on a preceding `<`-tag context by+// requiring whitespace before the name and `=` after it, which keeps prose like+// "turn onload on" out of the results.+const HANDLER_RE = /\son([a-z]{3,20})\s*=\s*(["'])/gi;+const JS_URL_RE = /\b(href|src|action|formaction)\s*=\s*(["'])\s*javascript:/gi;++// `on` prefixes that are real DOM events. A data attribute like `only="x"`+// would otherwise match the shape.+const EVENT_NAMES = new Set([+ 'abort', 'animationend', 'animationiteration', 'animationstart', 'auxclick',+ 'beforeinput', 'beforeunload', 'blur', 'cancel', 'canplay', 'canplaythrough',+ 'change', 'click', 'close', 'contextmenu', 'copy', 'cuechange', 'cut',+ 'dblclick', 'drag', 'dragend', 'dragenter', 'dragleave', 'dragover',+ 'dragstart', 'drop', 'durationchange', 'emptied', 'ended', 'error', 'focus',+ 'focusin', 'focusout', 'formdata', 'fullscreenchange', 'gotpointercapture',+ 'hashchange', 'input', 'invalid', 'keydown', 'keypress', 'keyup', 'load',+ 'loadeddata', 'loadedmetadata', 'loadstart', 'lostpointercapture', 'message',+ 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout',+ 'mouseover', 'mouseup', 'offline', 'online', 'paste', 'pause', 'play',+ 'playing', 'pointercancel', 'pointerdown', 'pointerenter', 'pointerleave',+ 'pointermove', 'pointerout', 'pointerover', 'pointerup', 'popstate',+ 'progress', 'ratechange', 'reset', 'resize', 'scroll', 'scrollend', 'seeked',+ 'seeking', 'select', 'slotchange', 'stalled', 'submit', 'suspend',+ 'timeupdate', 'toggle', 'touchcancel', 'touchend', 'touchmove', 'touchstart',+ 'transitionend', 'volumechange', 'waiting', 'wheel',+]);++function* walk(dir) {+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ if (SKIP_DIRS.has(entry.name)) continue;+ yield* walk(full);+ } else if (entry.name.endsWith('.html')) {+ yield full;+ }+ }+}++function lineOf(text, index) {+ let line = 1;+ for (let i = 0; i < index; i++) if (text[i] === '\n') line++;+ return line;+}++function scan(file) {+ const text = readFileSync(file, 'utf8');+ const rel = path.relative(ROOT, file);+ const findings = [];+ for (const m of text.matchAll(HANDLER_RE)) {+ if (!EVENT_NAMES.has(m[1].toLowerCase())) continue;+ findings.push({ file: rel, line: lineOf(text, m.index), kind: 'inline event handler', snippet: text.slice(m.index, m.index + 90).replace(/\s+/g, ' ').trim() });+ }+ for (const m of text.matchAll(JS_URL_RE)) {+ findings.push({ file: rel, line: lineOf(text, m.index), kind: 'javascript: URL', snippet: text.slice(m.index, m.index + 90).replace(/\s+/g, ' ').trim() });+ }+ return findings;+}++const roots = process.argv.includes('--dist') ? [...SOURCE_ROOTS, ...DIST_ROOTS] : SOURCE_ROOTS;++const findings = [];+let scanned = 0;+for (const root of roots) {+ const abs = path.join(ROOT, root);+ try {+ if (!statSync(abs).isDirectory()) continue;+ } catch {+ continue;+ }+ for (const file of walk(abs)) {+ scanned++;+ findings.push(...scan(file));+ }+}++if (findings.length === 0) {+ console.log(`inline-handler audit: clean (${scanned} HTML files, roots: ${roots.join(', ')})`);+ process.exit(0);+}++console.error(`inline-handler audit: ${findings.length} CSP-blocked construct(s) in ${scanned} HTML files\n`);+for (const f of findings) {+ console.error(` ${f.file}:${f.line} ${f.kind}`);+ console.error(` ${f.snippet}`);+}+console.error('\nThe site CSP has no \'unsafe-inline\' in script-src, so these will not run.');+console.error('Bind with addEventListener (delegate off a data-* attribute for generated markup);');+console.error('replace `javascript:` links with a <button> or a real href.');+process.exit(1);diff --git a/server/csp-hashes.mjs b/server/csp-hashes.mjsnew file mode 100644index 000000000..3c1f81eb8--- /dev/null+++ b/server/csp-hashes.mjs@@ -0,0 +1,170 @@+// Per-response CSP hardening: replaces `script-src 'unsafe-inline'` with the+// SHA-256 hashes of the inline scripts actually present in the HTML we are+// about to send.+//+// Why hashes and not a nonce: HTML on this site is cached at the CDN edge+// (`s-maxage=300` on the SSR/SEO paths, longer on plain static files). A+// per-request nonce baked into a cached document is the classic way to break a+// whole site: the first visitor's nonce is stored by the CDN and served to+// everybody else, whose CSP header carries a different nonce, so every inline+// script on the page is blocked. Hashes are a pure function of the bytes, so a+// cached document and its cached header always agree.+//+// The scanner below mirrors the HTML parser's own rules for finding script+// elements (quoted attribute values may contain `>`, the element ends at the+// first `</script` regardless of what the source text looks like), because a+// missed script means a blocked script means a broken page. Over-matching is+// harmless: an extra hash allows a script that does not exist.+//+// Scripts with a `src` attribute are not hashed. Those are covered by the+// host allowlist in the directive; hashing an external script would require an+// `integrity` attribute to match.+//+// What this deliberately does NOT allow: inline event handler attributes+// (`onclick="..."`) and `javascript:` URLs. Those need `'unsafe-hashes'` or+// `'unsafe-inline'`, and allowing them back would hand the primary XSS+// mitigation straight back. scripts/audit-inline-handlers.mjs fails the build+// if any HTML in the repo reintroduces one.++import { createHash } from 'node:crypto';++const SCRIPT_OPEN = /<script/gi;++// Walk the attribute list of an already-located `<script` tag, honouring+// quoted values, and return the index just past the tag's closing `>` plus+// whether the tag carried a `src` attribute. Returns null for a tag that never+// closes (truncated document).+function readOpenTag(html, from) {+ let i = from;+ let quote = null;+ let attrs = '';+ while (i < html.length) {+ const ch = html[i];+ if (quote) {+ if (ch === quote) quote = null;+ attrs += ch;+ } else if (ch === '"' || ch === "'") {+ quote = ch;+ attrs += ch;+ } else if (ch === '>') {+ return { end: i + 1, attrs };+ } else {+ attrs += ch;+ }+ i++;+ }+ return null;+}++// The HTML parser ends a script element at the first `</script` followed by a+// tag terminator, whatever the script text contains. `lower` is a lowercased+// copy of the whole document so a page with many scripts does not re-lowercase+// it once per script.+function findScriptCloseIn(lower, from) {+ let i = from;+ for (;;) {+ const idx = lower.indexOf('</script', i);+ if (idx === -1) return null;+ const after = lower[idx + 8];+ if (after === undefined || after === '>' || after === '/' || /\s/.test(after)) return idx;+ i = idx + 8;+ }+}++/**+ * Every inline script body in `html`, in document order, exactly as the CSP+ * hash algorithm sees it (the raw text between the tags).+ * @param {string} html+ * @returns {string[]}+ */+export function inlineScriptBodies(html) {+ const bodies = [];+ // One lowercase copy for the close-tag scan instead of one per script.+ const lower = html.toLowerCase();+ let cursor = 0;+ for (;;) {+ SCRIPT_OPEN.lastIndex = cursor;+ const open = SCRIPT_OPEN.exec(html);+ if (!open) break;+ const nameEnd = open.index + 7; // past "<script"+ const next = html[nameEnd];+ // `<scriptfoo` is not a script element.+ if (next !== undefined && !/[\s/>]/.test(next)) {+ cursor = nameEnd;+ continue;+ }+ const tag = readOpenTag(html, nameEnd);+ if (!tag) break;+ const close = findScriptCloseIn(lower, tag.end);+ if (close === null) {+ // Unterminated script: the parser treats the rest of the document as+ // its body, and so do we.+ if (!/\ssrc\s*=/i.test(tag.attrs)) bodies.push(html.slice(tag.end));+ break;+ }+ if (!/\ssrc\s*=/i.test(tag.attrs)) bodies.push(html.slice(tag.end, close));+ cursor = close + 8;+ }+ return bodies;+}++/**+ * CSP source expressions for every inline script in `html`, deduplicated.+ * @param {string} html+ * @returns {string[]} e.g. ["'sha256-47DEQpj8HBSa...'"]+ */+export function inlineScriptHashes(html) {+ const seen = new Set();+ for (const body of inlineScriptBodies(html)) {+ seen.add(`'sha256-${createHash('sha256').update(body, 'utf8').digest('base64')}'`);+ }+ return [...seen];+}++/**+ * Rewrite a CSP header value so `script-src` (and `script-src-elem`, when+ * present) allows exactly the inline scripts in `html` instead of all of them.+ *+ * A policy without `'unsafe-inline'` in its script directive is returned+ * untouched, so this is safe to run over every response.+ *+ * @param {string} csp the policy from the route table+ * @param {string} html the exact body being sent+ * @returns {string}+ */+export function hardenInlineScripts(csp, html) {+ if (typeof csp !== 'string' || !csp.includes("'unsafe-inline'")) return csp;+ const hashes = inlineScriptHashes(html);+ return csp+ .split(';')+ .map((directive) => {+ const trimmed = directive.trim();+ if (!trimmed) return directive;+ const name = trimmed.split(/\s+/, 1)[0].toLowerCase();+ if (name !== 'script-src' && name !== 'script-src-elem') return directive;+ if (!trimmed.includes("'unsafe-inline'")) return directive;+ const sources = trimmed+ .split(/\s+/)+ .slice(1)+ .filter((s) => s !== "'unsafe-inline'" && !s.startsWith("'sha256-"));+ return ` ${name} ${[...sources, ...hashes].join(' ')}`;+ })+ .join(';');+}++const CSP_KEYS = ['content-security-policy', 'Content-Security-Policy'];++/**+ * Apply {@link hardenInlineScripts} to whichever casing of the CSP key a+ * collected header bag happens to use. Mutates and returns the bag.+ * @param {Record<string, string>} headers+ * @param {string} html+ * @returns {Record<string, string>}+ */+export function hardenHeaderBag(headers, html) {+ if (!headers) return headers;+ for (const key of CSP_KEYS) {+ if (typeof headers[key] === 'string') headers[key] = hardenInlineScripts(headers[key], html);+ }+ return headers;+}diff --git a/server/index.mjs b/server/index.mjsindex ec1ffba63..cca4c992c 100644--- a/server/index.mjs+++ b/server/index.mjs@@ -37,6 +37,7 @@ import path from 'node:path';import { pathToFileURL, fileURLToPath } from 'node:url';import { isSsrRoute, renderSsrPage } from './ssr-pages.mjs';import { hasSeoRoute, renderSeoHead } from './seo-head.mjs';+import { hardenHeaderBag } from './csp-hashes.mjs';// Route resolution lives in its own module so the audit scripts// (scripts/audit-cron-liveness.mjs) exercise the SAME resolver production runs,// instead of a copy that can silently drift from it.@@ -246,7 +247,29 @@ function resolveStatic(pathname) {}}+// Static HTML gets its CSP tightened to the inline scripts it actually+// contains (see server/csp-hashes.mjs). dist/ is immutable for the lifetime of+// a deploy, so each file is read and hashed at most once per process; the+// response itself still streams from res.sendFile.+const staticCspCache = new Map();++function cspForStaticHtml(file) {+ if (staticCspCache.has(file)) return staticCspCache.get(file);+ let html = null;+ try {+ html = readFileSync(file, 'utf8');+ } catch (err) {+ console.error(`[csp] could not read ${file} for hashing:`, err.message);+ }+ staticCspCache.set(file, html);+ return html;+}+function serveFile(req, res, file, headers, status) {+ if (file.endsWith('.html')) {+ const html = cspForStaticHtml(file);+ if (html !== null) hardenHeaderBag(headers, html);+ }res.set(headers);if (status) res.status(status);// RFC 8615 discovery files (agent-card.json, ai-plugin.json, security.txt)@@ -400,7 +423,9 @@ app.use(async (req, res) => {const shell = readFileSync(file, 'utf8');const html = await renderSsrPage(currentPath, shell, `http://127.0.0.1:${PORT}`);if (html) {- res.set(collected);+ // Hash the body we are actually sending, not the shell on disk:+ // the injected block carries its own JSON-LD.+ res.set(hardenHeaderBag(collected, html));if (fileStatus) res.status(fileStatus);res.set('content-type', 'text/html; charset=utf-8');// Same freshness the static shell gets from the CDN, but the@@ -421,7 +446,9 @@ app.use(async (req, res) => {if (req.method === 'GET' && file.endsWith('.html') && hasSeoRoute(url.pathname)) {const html = renderSeoHead(url.pathname, file);if (html) {- res.set(collected);+ // The rewritten head swaps in this route's own JSON-LD block, so+ // the policy has to describe the rewritten bytes.+ res.set(hardenHeaderBag(collected, html));if (fileStatus) res.status(fileStatus);res.set('content-type', 'text/html; charset=utf-8');res.set('cache-control', 'public, max-age=60, s-maxage=300');diff --git a/src/unstoppable-dashboard.js b/src/unstoppable-dashboard.jsindex 4eeb421c6..e23654ee1 100644--- a/src/unstoppable-dashboard.js+++ b/src/unstoppable-dashboard.js@@ -426,8 +426,10 @@ async function scheduledPoll() {}export function init() {- // Expose public methods for onclick handlers.- window.__unstoppable = { donate };+ // Bound here rather than with an onclick attribute: the site CSP allows+ // inline <script> by hash and never inline handlers, so an attribute would+ // silently stop firing.+ document.getElementById('donateBtn')?.addEventListener('click', donate);// Show cached data immediately while we fetch.const cached = loadFromCache();diff --git a/vercel.json b/vercel.jsonindex 17ac26b7b..31ed8c7de 100644--- a/vercel.json+++ b/vercel.json@@ -209,7 +209,7 @@{"src": "/(login|register|forgot-password|reset-password|account|settings|wallet|pay|paywall|vanity-wallet|eth-vanity|evm-wallet|dashboard|dashboard-next|dashboard-classic)(/.*)?$","headers": {- "content-security-policy": "frame-ancestors 'self'; base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://challenges.cloudflare.com https://3d-agent.vercel.app https://three.ws https://three.ws; worker-src 'self' blob:; report-uri /api/client-errors",+ "content-security-policy": "frame-ancestors 'self'; base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://challenges.cloudflare.com https://3d-agent.vercel.app https://three.ws; worker-src 'self' blob:; report-uri /api/client-errors","x-frame-options": "SAMEORIGIN"},"continue": true