Skip to content

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

security(csp): move the other 113 inline handlers, the ones living in JS strings, off the blocked path

nirholase303158339b4
diff --git a/data/guards.json b/data/guards.json
index 95a3774c8..af0af1a5a 100644
--- a/data/guards.json
+++ b/data/guards.json
@@ -290,6 +290,22 @@
"expect": "guard-proof-inline-handler"
}
},
+ {
+ "id": "audit-csp",
+ "script": "scripts/audit-csp.mjs",
+ "npm": "audit:csp",
+ "title": "Live CSP sweep",
+ "protects": "No page violates the Content-Security-Policy the server sends with it.",
+ "why": "server/csp-hashes.mjs derives script-src from the bytes of each response, which is a strong guarantee on paper and a total outage when it is wrong: one missed inline script ships that page blank. Only a browser applies a policy the way a browser applies a policy, so this loads the real pages against a running server and fails on any securitypolicyviolation event. Add --all to sweep every route in data/pages.json.",
+ "stages": [
+ "manual"
+ ],
+ "needs": "browser",
+ "proof": {
+ "kind": "live",
+ "reason": "Needs Playwright plus a server serving dist/, because the thing under test is the browser's own policy evaluation against a real response. A static fixture cannot produce a securitypolicyviolation event."
+ }
+ },
{
"id": "audit-docs",
"script": "scripts/audit-docs.mjs",
diff --git a/docs/security/SECURITY_AUDIT.md b/docs/security/SECURITY_AUDIT.md
index 628f425e4..a86903ae3 100644
--- a/docs/security/SECURITY_AUDIT.md
+++ b/docs/security/SECURITY_AUDIT.md
@@ -226,6 +226,34 @@ disagree. Hashes cannot cover an inline event handler or a `javascript:` URL, so
those were removed site-wide and `scripts/audit-inline-handlers.mjs` (registered
in `data/guards.json`, wired into `npm run gate`) fails the build if one returns.
+Two checks prove it rather than assert it. `tests/csp-hashes.test.js` pins the
+parser edge cases a naive regex gets wrong, because a single missed inline
+script ships that page blank. `npm run audit:csp` (`scripts/audit-csp.mjs`) then
+loads real pages in a real browser against a running server and fails on any
+`securitypolicyviolation` event, which is the only way to confirm a policy the
+way a browser applies it. Add `--all` to sweep every route in `data/pages.json`.
+
+Both of those earned their keep immediately, and the two things they caught are
+the reason neither is optional:
+
+- The first pass at removing inline handlers scanned only `.html` files and
+ found 55. Almost all of this site's markup is built from template literals, so
+ another 113 lived inside `.js` strings where no HTML scan could see them:
+ 72 `onerror` image fallbacks, 15 `onclick="event.stopPropagation()"`, six
+ reload buttons, eight hover effects and a tail of named-function calls, across
+ 70 modules. The browser sweep found the first of them on `/communities`.
+ `public/inline-behaviors.js` now carries all of it declaratively
+ (`data-fallback*`, `data-action`, `data-stop-propagation`) and is injected on
+ every built page by `scripts/inject-inline-behaviors.mjs`, matching the
+ belt-and-suspenders pattern `inject-atlas.mjs` uses. The hover cases became
+ CSS. `audit-inline-handlers.mjs` now scans `src/` too.
+- The hash scanner treated a `<script>` written inside a `<style>` block as a
+ real element. A CSS comment on `/oracle` that mentioned one started a phantom
+ script that ran to the next real `</script>`, swallowing the analytics
+ snippet's opening tag so its hash never reached the header, and the browser
+ blocked it. The scanner now skips comments and raw-text elements (`style`,
+ `textarea`, `title`), with a test per case.
+
`'unsafe-eval'` remains, and is the weakest link now that inline injection is
closed. It cannot simply be dropped: the shipped bundles carry three distinct
`new Function` users. Two degrade gracefully when eval is blocked (the msgpack
@@ -234,8 +262,8 @@ a failed feature test; pdf.js gates on `isEvalSupported`), but the `cwise`
codegen inside the main `index` bundle and the `new Function` in
`public/scene-studio/{app/app.js,libs/acorn/acorn.js}` do not. Scoping it needs
`'wasm-unsafe-eval'` globally, `'unsafe-eval'` kept on `/scene-studio`, and a
-`cwise`-free path for the main bundle, verified by a real browser sweep
-(`npm run audit:web`) rather than by reading headers. **Status: `'unsafe-inline'`
+`cwise`-free path for the main bundle, verified with `npm run audit:csp`
+rather than by reading headers. **Status: `'unsafe-inline'`
fixed (per-response hashes); CDN trim + dedupe done; `'unsafe-eval'` scoping
tracked with the plan above.**
diff --git a/pages/activity.html b/pages/activity.html
index a023c688f..5d5f4463a 100644
--- a/pages/activity.html
+++ b/pages/activity.html
@@ -424,7 +424,6 @@
</main>
<script src="/brand.js" defer></script>
- <script src="/img-fallback.js" defer></script>
<script type="module">
import { proxiedImageURL } from '/src/ipfs.js';
diff --git a/pages/agent-exchange.html b/pages/agent-exchange.html
index 776670500..becb18893 100644
--- a/pages/agent-exchange.html
+++ b/pages/agent-exchange.html
@@ -23,6 +23,10 @@
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="manifest" href="/manifest.webmanifest" />
<style>
+ /* Hover lives here, not in an onmouseover attribute: the site CSP allows
+ inline script blocks by hash and never inline handlers. */
+ .ax-x402-link { color: var(--usdc-lt); text-decoration: none; }
+ .ax-x402-link:hover { text-decoration: underline; }
:root {
color-scheme: dark;
--bg: #080808;
diff --git a/pages/coin-intel.html b/pages/coin-intel.html
index eefa1aa4f..8ab5d84d3 100644
--- a/pages/coin-intel.html
+++ b/pages/coin-intel.html
@@ -1035,7 +1035,6 @@
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.html
index ef87c36ba..6530221e4 100644
--- a/pages/daily-match.html
+++ b/pages/daily-match.html
@@ -122,7 +122,6 @@
<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&amp;t=Daily+Match&amp;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&amp;p=%2Fdaily-match"}]}</script>
-<script src="/img-fallback.js" defer></script>
</head>
<body>
<header><div id="nav-container"></div></header>
diff --git a/pages/handle.html b/pages/handle.html
index 63e118257..1500e5359 100644
--- a/pages/handle.html
+++ b/pages/handle.html
@@ -27,6 +27,10 @@
<meta name="twitter:image" content="https://three.ws/og-image.png" id="tw-image" />
<style>
+ /* Hover lives here, not in an onmouseover attribute: the site CSP allows
+ inline script blocks by hash and never inline handlers. */
+ .hd-cta-link { transition: opacity 0.15s; }
+ .hd-cta-link:hover { opacity: 0.88; }
body {
margin: 0;
background: #0c0c0c;
diff --git a/pages/oracle.html b/pages/oracle.html
index 9fd790c01..0f345d6a2 100644
--- a/pages/oracle.html
+++ b/pages/oracle.html
@@ -20,6 +20,10 @@
<link rel="stylesheet" href="/nav.css" />
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"Oracle","applicationCategory":"FinanceApplication","description":"Fused pump.fun conviction scoring — who's buying, how, what, and how it's moving, in one live score, with an agent action loop.","url":"https://three.ws/oracle","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
<style>
+ /* Hover lives here, not in an onmouseover attribute: the site CSP allows
+ inline script blocks by hash and never inline handlers. */
+ .dr-related { background: var(--panel); transition: background 0.12s; }
+ .dr-related:hover { background: rgba(255, 255, 255, 0.05); }
:root {
--bg: #05060c; --panel: rgba(13,15,23,0.72); --panel-solid: #0c0e16; --line: rgba(255,255,255,0.09);
--ink: #eaeefa; --muted: #8a92a8; --faint: rgba(255,255,255,0.45);
diff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.html
index b10819e45..663ffb2fe 100644
--- a/pages/pump-dashboard.html
+++ b/pages/pump-dashboard.html
@@ -2342,7 +2342,7 @@
<td>${(() => {
const fallback = tokenLogoFallback(t.mint || t.symbol, t.symbol);
const src = t.logo || fallback;
- // /img-fallback.js swaps a broken remote logo to the
+ // /inline-behaviors.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" />`;
@@ -5294,7 +5294,6 @@
<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/smart-money.html b/pages/smart-money.html
index b5f5daf47..e80ba4afd 100644
--- a/pages/smart-money.html
+++ b/pages/smart-money.html
@@ -296,7 +296,6 @@
<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>
diff --git a/public/agents/index.html b/public/agents/index.html
index c93ec1d5a..9ac357f28 100644
--- a/public/agents/index.html
+++ b/public/agents/index.html
@@ -352,7 +352,6 @@
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/boot.js b/public/cz/boot.js
index c850b85cf..af9cec528 100644
--- a/public/cz/boot.js
+++ b/public/cz/boot.js
@@ -92,6 +92,13 @@ async function handleClaimClick(state) {
<p>Initializing claim flow…</p>
`;
+ // Result panels are rendered from strings; their OK/Dismiss buttons declare
+ // data-close-claim-modal and this delegated listener closes the modal. Inline
+ // onclick attributes cannot run under the site CSP.
+ document.addEventListener('click', (event) => {
+ if (event.target.closest('[data-close-claim-modal]')) modal.style.display = 'none';
+ });
+
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
});
@@ -113,26 +120,26 @@ async function handleClaimClick(state) {
content.innerHTML = `
<h3 style="margin:0 0 1rem">Coming Soon</h3>
<p>CZ is not yet registered on-chain. Claiming opens once the registration is complete.</p>
- <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>
+ <button class="modal-close-btn" data-close-claim-modal>OK</button>
`;
} else if (result.message === 'already_owned') {
content.innerHTML = `
<h3 style="margin:0 0 1rem">Already Claimed</h3>
<p>This agent is already owned by <code>${truncate(state.ownerAddress, 20)}</code>.</p>
- <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>
+ <button class="modal-close-btn" data-close-claim-modal>OK</button>
`;
} else {
content.innerHTML = `
<h3 style="margin:0 0 1rem">Claim Successful</h3>
<p>Transaction: <code>${result.txHash}</code></p>
- <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>
+ <button class="modal-close-btn" data-close-claim-modal>OK</button>
`;
}
} else {
content.innerHTML = `
<h3 style="margin:0 0 1rem">Error</h3>
<p>${result.error}</p>
- <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">Dismiss</button>
+ <button class="modal-close-btn" data-close-claim-modal>Dismiss</button>
`;
}
}
diff --git a/public/dashboard-next/shell.css b/public/dashboard-next/shell.css
index 979708474..feee41415 100644
--- a/public/dashboard-next/shell.css
+++ b/public/dashboard-next/shell.css
@@ -750,3 +750,21 @@ body.dn-body [contenteditable]:focus-visible {
outline: 2px solid var(--nxt-ink);
outline-offset: 2px;
}
+
+/* Icon-only affordance (dialog close, inline dismiss). The hover colour lives
+ here rather than in an onmouseenter attribute: the site CSP allows inline
+ <script> by hash and never inline handlers. */
+.nxt-icon-btn {
+ flex-shrink: 0;
+ background: none;
+ border: none;
+ cursor: pointer;
+ color: var(--nxt-ink-fade);
+ padding: 4px;
+ border-radius: 6px;
+ transition: color 120ms ease;
+}
+.nxt-icon-btn:hover,
+.nxt-icon-btn:focus-visible {
+ color: var(--nxt-ink);
+}
diff --git a/public/dashboard/portfolio-asset.html b/public/dashboard/portfolio-asset.html
index e8906d25a..e37e680ee 100644
--- a/public/dashboard/portfolio-asset.html
+++ b/public/dashboard/portfolio-asset.html
@@ -788,7 +788,6 @@
})();
</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.html
index 18df07f15..10c8bae8c 100644
--- a/public/dashboard/portfolio.html
+++ b/public/dashboard/portfolio.html
@@ -1394,7 +1394,6 @@
})();
</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/discover/discover.js b/public/discover/discover.js
index a45e79067..d121cd236 100644
--- a/public/discover/discover.js
+++ b/public/discover/discover.js
@@ -441,7 +441,7 @@ function renderCard(item) {
*/
function renderThumb({ image, glbUrl, has3d, alt }) {
if (image) {
- return `<img src="${escapeAttr(image)}" alt="${escapeAttr(alt || '')}" loading="lazy" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'explore-card-ph',textContent:'${has3d ? '🎭' : '🤖'}'}))" />`;
+ return `<img src="${escapeAttr(image)}" alt="${escapeAttr(alt || '')}" loading="lazy" data-fallback="element" data-fallback-class="explore-card-ph" data-fallback-text="${has3d ? '🎭' : '🤖'}" />`;
}
if (glbUrl) {
return `<model-viewer
diff --git a/public/guards.json b/public/guards.json
index 95a3774c8..af0af1a5a 100644
--- a/public/guards.json
+++ b/public/guards.json
@@ -290,6 +290,22 @@
"expect": "guard-proof-inline-handler"
}
},
+ {
+ "id": "audit-csp",
+ "script": "scripts/audit-csp.mjs",
+ "npm": "audit:csp",
+ "title": "Live CSP sweep",
+ "protects": "No page violates the Content-Security-Policy the server sends with it.",
+ "why": "server/csp-hashes.mjs derives script-src from the bytes of each response, which is a strong guarantee on paper and a total outage when it is wrong: one missed inline script ships that page blank. Only a browser applies a policy the way a browser applies a policy, so this loads the real pages against a running server and fails on any securitypolicyviolation event. Add --all to sweep every route in data/pages.json.",
+ "stages": [
+ "manual"
+ ],
+ "needs": "browser",
+ "proof": {
+ "kind": "live",
+ "reason": "Needs Playwright plus a server serving dist/, because the thing under test is the browser's own policy evaluation against a real response. A static fixture cannot produce a securitypolicyviolation event."
+ }
+ },
{
"id": "audit-docs",
"script": "scripts/audit-docs.mjs",
diff --git a/public/inline-behaviors.js b/public/inline-behaviors.js
index 045d85588..96cca12a6 100644
--- a/public/inline-behaviors.js
+++ b/public/inline-behaviors.js
@@ -1,37 +1,54 @@
/**
- * Declarative <img> failure handling, without inline onerror attributes.
+ * Declarative replacements for the inline handler attributes the CSP blocks.
*
- * 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.
+ * The site's Content-Security-Policy allows inline <script> by hash and nothing
+ * else, so `onerror="..."`, `onclick="..."` and friends no longer run. Almost
+ * all of ours were written inside template literals with interpolated values,
+ * which no hash could ever cover. This file is where those behaviours live now:
+ * markup declares its intent with a data-* attribute, and one delegated
+ * listener per behaviour does the work.
*
- * Load it once per page:
- * <script src="/img-fallback.js" defer></script>
+ * scripts/inject-inline-behaviors.mjs puts this on every built page, so any markup
+ * anywhere on the site can use these attributes with nothing else to wire up.
*
- * Then describe the failure behaviour on the image itself:
+ * ── Broken images ────────────────────────────────────────────────────────────
+ * data-fallback-src="URL" swap to URL on the first failure; if that fails
+ * too, run data-fallback (default: remove).
+ * data-fallback="hide" display:none
+ * data-fallback="invisible" visibility:hidden (keeps the layout box)
+ * data-fallback="remove" drop the element
+ * data-fallback="sibling" hide it and reveal its next element sibling
+ * (display from data-fallback-display, "flex")
+ * data-fallback="text" replace it with data-fallback-text
+ * data-fallback="parent-text" hide it, set the parent's text instead
+ * data-fallback="element" replace it with data-fallback-tag (default
+ * "div") carrying data-fallback-class and
+ * data-fallback-text
+ * data-fallback="closest" remove the nearest data-fallback-closest match
+ * data-fallback="keep" leave the broken image in place. Only useful
+ * with data-fallback-parent-class, where CSS on
+ * the container does the work.
*
- * 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
+ * data-fallback-parent-class added to the parent element on failure, in
+ * addition to whatever mode above runs. Lets CSS
+ * restyle the container that lost its image.
*
- * `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.
+ * ── Clicks ───────────────────────────────────────────────────────────────────
+ * data-action="reload" reload the page (retry buttons in error states)
+ * data-stop-propagation a click inside this element does not reach any
+ * ancestor listener. For a link inside a card
+ * that is itself clickable: the link navigates,
+ * the card does not also open.
+ *
+ * `error` does not bubble, so the image listener is registered in the capture
+ * phase; that also means images added to the DOM later are covered with no
+ * re-init. The stop-propagation listener is in the capture phase for a
+ * different reason: it has to run before the ancestor listener it is cancelling.
*/
(function () {
'use strict';
- if (window.__imgFallbackInstalled) return;
- window.__imgFallbackInstalled = true;
+ if (window.__inlineBehaviorsInstalled) return;
+ window.__inlineBehaviorsInstalled = true;
const HANDLED = '__imgFallbackDone';
@@ -39,18 +56,40 @@
if (el instanceof HTMLElement) el.style.display = display || 'flex';
}
+ function replacement(img) {
+ const el = document.createElement(img.dataset.fallbackTag || 'div');
+ if (img.dataset.fallbackClass) el.className = img.dataset.fallbackClass;
+ el.textContent = img.dataset.fallbackText || '';
+ return el;
+ }
+
+ // Only these values are ours. src/shared/news-render.js has its own
+ // capture-phase handler that reads `data-fallback` as the initials to show,
+ // so an unrecognised value means the image belongs to somebody else and this
+ // listener must not touch it.
+ const MODES = new Set([
+ 'hide',
+ 'invisible',
+ 'remove',
+ 'sibling',
+ 'text',
+ 'parent-text',
+ 'element',
+ 'closest',
+ 'keep',
+ ]);
+
function apply(img) {
- const mode = img.dataset.fallback || '';
- switch (mode) {
+ if (img.dataset.fallbackParentClass && img.parentElement) {
+ img.parentElement.classList.add(img.dataset.fallbackParentClass);
+ }
+ switch (img.dataset.fallback || '') {
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);
@@ -62,9 +101,19 @@
img.style.display = 'none';
if (img.parentElement) img.parentElement.textContent = img.dataset.fallbackText || '';
return;
+ case 'element':
+ img.replaceWith(replacement(img));
+ return;
+ case 'closest': {
+ const target = img.dataset.fallbackClosest && img.closest(img.dataset.fallbackClosest);
+ (target || img).remove();
+ return;
+ }
+ case 'keep':
+ return;
default:
- // A data-fallback-src that has already been tried and failed leaves
- // nothing sensible on screen, so drop the broken image.
+ // "remove", plus an image whose data-fallback-src was tried and
+ // failed: there is nothing sensible left to show, so drop it.
img.remove();
}
}
@@ -77,6 +126,10 @@
if (img[HANDLED]) return;
const swap = img.dataset.fallbackSrc;
+ // An image that declares nothing is not this module's business. Left
+ // alone it shows the browser's own broken-image glyph, which is what it
+ // did before; removing it would silently reshape layouts everywhere.
+ if (!swap && !img.dataset.fallbackParentClass && !MODES.has(img.dataset.fallback)) return;
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.
@@ -88,4 +141,20 @@
},
true,
);
+
+ document.addEventListener(
+ 'click',
+ function (event) {
+ if (event.target.closest('[data-stop-propagation]')) event.stopPropagation();
+ },
+ true,
+ );
+
+ document.addEventListener('click', function (event) {
+ const el = event.target.closest('[data-action]');
+ if (el && el.dataset.action === 'reload') {
+ event.preventDefault();
+ location.reload();
+ }
+ });
})();
diff --git a/public/launch-studio/launch-studio.js b/public/launch-studio/launch-studio.js
index c4684c686..4a9d82beb 100644
--- a/public/launch-studio/launch-studio.js
+++ b/public/launch-studio/launch-studio.js
@@ -404,7 +404,7 @@ export function mountLaunchStudio(root) {
const maxScore = Math.max(1, ...(s.preview.items.map((x) => Number(x.score) || 0)));
const pct = Math.max(6, Math.round(((Number(it.score) || 0) / maxScore) * 100));
const img = it.identity.image
- ? `<img class="ls-coin-img" src="${esc(it.identity.image)}" alt="" loading="lazy" onerror="this.outerHTML='<div class=\\'ls-coin-ph\\'>${esc((it.identity.symbol || '?')[0])}</div>'" />`
+ ? `<img class="ls-coin-img" src="${esc(it.identity.image)}" alt="" loading="lazy" data-fallback="element" data-fallback-class="ls-coin-ph" data-fallback-text="${esc((it.identity.symbol || '?')[0])}" />`
: `<div class="ls-coin-ph">${esc((it.identity.symbol || '?')[0])}</div>`;
const signal = it.signal && it.signal.detail ? `<span class="ls-tag">${esc(it.signal.detail)}</span>` : '';
return `<div class="ls-coin" style="animation-delay:${i * 40}ms">
diff --git a/public/my-agents/index.html b/public/my-agents/index.html
index cc6e35836..f31e5ab89 100644
--- a/public/my-agents/index.html
+++ b/public/my-agents/index.html
@@ -229,7 +229,6 @@
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.html
index e495f5828..96775849b 100644
--- a/public/pay/c/index.html
+++ b/public/pay/c/index.html
@@ -394,7 +394,6 @@
</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.html
index 0c31b0055..ff4a322c1 100644
--- a/public/pay/index.html
+++ b/public/pay/index.html
@@ -2278,7 +2278,6 @@ 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/studio/fees-panel.js b/public/studio/fees-panel.js
index dfeb6965a..1860538cd 100644
--- a/public/studio/fees-panel.js
+++ b/public/studio/fees-panel.js
@@ -745,7 +745,7 @@ export function mountFeesPanel(container, opts = {}) {
<div class="fp-share-row" data-i="${i}">
<div class="fp-sh-meta">
<input class="fp-share-addr" data-i="${i}" placeholder="Recipient Solana wallet" value="${esc(r.address)}" spellcheck="false" />
- ${r.gh ? `<span class="fp-share-gh"><img src="${esc(r.gh.avatar)}" alt="" onerror="this.style.display='none'" />${r.gh.platform === 'x' ? '𝕏 ' : ''}@${esc(r.gh.login)}${
+ ${r.gh ? `<span class="fp-share-gh"><img src="${esc(r.gh.avatar)}" alt="" data-fallback="hide" />${r.gh.platform === 'x' ? '𝕏 ' : ''}@${esc(r.gh.login)}${
r.gh.resolving ? ` · <span style="color:rgba(255,255,255,.4)">resolving…</span>`
: r.gh.linked ? ` · <span style="color:#a4f0bc">linked ✓</span>`
: r.gh.unlinked ? ` · <span style="color:rgba(246,200,114,.9)" title="No three.ws-linked Solana wallet — paste theirs, or ask them to link a wallet on three.ws">add wallet</span>`
diff --git a/scripts/audit-csp.mjs b/scripts/audit-csp.mjs
new file mode 100644
index 000000000..82b22b0a4
--- /dev/null
+++ b/scripts/audit-csp.mjs
@@ -0,0 +1,162 @@
+#!/usr/bin/env node
+// Loads real pages in a real browser and fails on any Content-Security-Policy
+// violation.
+//
+// server/csp-hashes.mjs computes `script-src` hashes from the exact bytes of
+// each HTML response. That is a strong guarantee on paper, and a page that
+// still breaks breaks completely: one missed inline script and the page ships
+// blank. This is the check that proves it, because only a browser applies a
+// policy the way a browser applies a policy.
+//
+// Every `securitypolicyviolation` event and every page error is collected per
+// URL. A violation is a hard failure; a page error is reported so a broken
+// refactor cannot hide behind a green CSP.
+//
+// Usage:
+// node server/index.mjs & # or any origin serving dist/
+// node scripts/audit-csp.mjs # sweeps the default page set
+// node scripts/audit-csp.mjs --base http://127.0.0.1:8099
+// node scripts/audit-csp.mjs --all # every page in data/pages.json
+// node scripts/audit-csp.mjs /pay /studio # only these paths
+
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { chromium } from 'playwright';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+// The pages whose inline handlers were converted to delegated listeners, plus
+// the shells that carry the most inline script. A regression shows up here
+// first.
+const DEFAULT_PATHS = [
+ '/',
+ '/activity',
+ '/coin-intel',
+ '/daily-match',
+ '/pump-dashboard',
+ '/pump-live',
+ '/smart-money',
+ '/payments',
+ '/unstoppable',
+ '/walk-analytics',
+ '/tour-builder',
+ '/avatar-artifact',
+ '/agents',
+ '/my-agents',
+ '/pay',
+ '/studio',
+ '/validation',
+ '/dashboard',
+ '/dashboard/wallets',
+ '/dashboard/x402',
+ '/dashboard/portfolio',
+ '/vanity/gallery',
+ '/vanity/premium',
+ '/demos-embed/forge.html',
+ '/docs',
+];
+
+const args = process.argv.slice(2);
+const baseIdx = args.indexOf('--base');
+const BASE = baseIdx === -1 ? 'http://127.0.0.1:8099' : args[baseIdx + 1];
+const wantAll = args.includes('--all');
+const explicit = args.filter((a) => a.startsWith('/'));
+
+function allCataloguedPaths() {
+ const catalogue = JSON.parse(readFileSync(path.join(ROOT, 'data', 'pages.json'), 'utf8'));
+ const paths = [];
+ for (const section of catalogue.sections || []) {
+ for (const page of section.pages || []) {
+ if (typeof page.path === 'string' && page.path.startsWith('/')) paths.push(page.path);
+ }
+ }
+ return [...new Set(paths)];
+}
+
+const paths = explicit.length ? explicit : wantAll ? allCataloguedPaths() : DEFAULT_PATHS;
+
+// How long to let a loaded page keep running before judging it. Long enough for
+// deferred scripts, dynamic imports and the first render pass of a live feed.
+const SETTLE_MS = Number(process.env.CSP_AUDIT_SETTLE_MS) || 3500;
+
+const browser = await chromium.launch({
+ args: ['--no-sandbox', '--disable-dev-shm-usage'],
+});
+
+const results = [];
+for (const p of paths) {
+ const context = await browser.newContext();
+ const page = await context.newPage();
+ const violations = [];
+ const errors = [];
+
+ // Collected inside the page so the browser's own policy evaluation is what
+ // reports, not a re-implementation of it here.
+ await page.addInitScript(() => {
+ window.__cspViolations = [];
+ document.addEventListener('securitypolicyviolation', (e) => {
+ window.__cspViolations.push({
+ directive: e.effectiveDirective || e.violatedDirective,
+ blocked: e.blockedURI,
+ sample: (e.sample || '').slice(0, 120),
+ line: e.lineNumber,
+ source: (e.sourceFile || '').slice(0, 200),
+ });
+ });
+ });
+ page.on('pageerror', (err) => errors.push(String(err.message).slice(0, 200)));
+
+ let status = 0;
+ try {
+ // Many pages here poll a live feed forever, so `networkidle` never
+ // fires. Wait for the document instead, then give deferred scripts and
+ // lazy chunks a fixed window to run and violate.
+ const res = await page.goto(BASE + p, { waitUntil: 'domcontentloaded', timeout: 45000 });
+ status = res ? res.status() : 0;
+ await page.waitForTimeout(SETTLE_MS);
+ violations.push(...(await page.evaluate(() => window.__cspViolations || [])));
+ } catch (err) {
+ errors.push(`navigation: ${err.message}`);
+ }
+ await context.close();
+ // A page that never loaded proves nothing. Counting it as clean is how a
+ // sweep reports success after the server under test died halfway through.
+ const unreachable = status === 0 || status >= 500;
+ results.push({ path: p, status, violations, errors, unreachable });
+ const mark = violations.length ? 'CSP' : unreachable ? 'DEAD' : errors.length ? 'err' : ' ok';
+ console.log(`[${mark}] ${String(status).padEnd(3)} ${p}${violations.length ? ` (${violations.length} violation(s))` : ''}`);
+}
+
+await browser.close();
+
+const failed = results.filter((r) => r.violations.length > 0);
+const unreachable = results.filter((r) => r.unreachable);
+const errored = results.filter((r) => r.errors.length > 0 && r.violations.length === 0 && !r.unreachable);
+
+if (errored.length) {
+ console.log('\nPage errors (not CSP, but worth reading):');
+ for (const r of errored) for (const e of r.errors) console.log(` ${r.path}: ${e}`);
+}
+
+if (unreachable.length) {
+ console.error(`\nCSP audit: ${unreachable.length} of ${results.length} page(s) never loaded, so this run proves nothing.`);
+ console.error(`Check that ${BASE} is still serving. First few:`);
+ for (const r of unreachable.slice(0, 8)) console.error(` ${r.path} (status ${r.status})`);
+ process.exit(2);
+}
+
+if (failed.length === 0) {
+ console.log(`\nCSP audit: clean across ${results.length} page(s) on ${BASE}`);
+ process.exit(0);
+}
+
+console.error(`\nCSP audit: ${failed.length} page(s) violated the policy\n`);
+for (const r of failed) {
+ console.error(` ${r.path}`);
+ for (const v of r.violations) {
+ console.error(` ${v.directive} blocked ${v.blocked || '(inline)'} at ${v.source}:${v.line}`);
+ if (v.sample) console.error(` sample: ${v.sample}`);
+ }
+}
+process.exit(1);
diff --git a/scripts/audit-inline-handlers.mjs b/scripts/audit-inline-handlers.mjs
index fd1ae908a..559f29aac 100644
--- a/scripts/audit-inline-handlers.mjs
+++ b/scripts/audit-inline-handlers.mjs
@@ -11,7 +11,16 @@
//
// 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:`.
+// attribute, and use a <button> or a real href instead of `javascript:`. For
+// broken images specifically, public/inline-behaviors.js reads declarative
+// `data-fallback*` attributes and is on every page, along with `data-action`
+// and `data-stop-propagation` for the click cases.
+//
+// JavaScript is scanned too, and that half matters more: most of this site's
+// markup is built from template literals, so an `onerror=` written inside a JS
+// string never appears in any .html file. Those were invisible to an HTML-only
+// scan and are exactly the ones that break silently in production, because a
+// dev server without the header runs them fine.
//
// Usage:
// node scripts/audit-inline-handlers.mjs # repo sources
@@ -27,11 +36,27 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
// `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 SOURCE_ROOTS = ['pages', 'public', 'src'];
const DIST_ROOTS = ['dist'];
const SKIP_DIRS = new Set(['node_modules', '.git', 'assets', 'locales']);
+// Third-party code we vendor rather than author. Rewriting an upstream editor's
+// own markup would be re-forking it; those surfaces carry their own policy.
+// Written without a leading root so each entry matches both the source tree and
+// its copy under dist/.
+const VENDOR_PATHS = [
+ 'scene-studio/vendor/',
+ 'scene-studio/libs/',
+ 'chat/assets/',
+ 'ibm/vendor/',
+ 'vendor/',
+];
+
+const isVendor = (rel) => VENDOR_PATHS.some((p) => rel.includes(`/${p}`) || rel.startsWith(p));
+
+const SCANNED_EXTENSIONS = ['.html', '.js', '.jsx', '.mjs'];
+
// 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.
@@ -68,10 +93,13 @@ function* walk(dir) {
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
+ const rel = path.relative(ROOT, full).split(path.sep).join('/');
if (entry.isDirectory()) {
if (SKIP_DIRS.has(entry.name)) continue;
+ if (isVendor(`${rel}/`)) continue;
yield* walk(full);
- } else if (entry.name.endsWith('.html')) {
+ } else if (SCANNED_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
+ if (isVendor(rel)) continue;
yield full;
}
}
@@ -115,11 +143,11 @@ for (const root of roots) {
}
if (findings.length === 0) {
- console.log(`inline-handler audit: clean (${scanned} HTML files, roots: ${roots.join(', ')})`);
+ console.log(`inline-handler audit: clean (${scanned} files, roots: ${roots.join(', ')})`);
process.exit(0);
}
-console.error(`inline-handler audit: ${findings.length} CSP-blocked construct(s) in ${scanned} HTML files\n`);
+console.error(`inline-handler audit: ${findings.length} CSP-blocked construct(s) in ${scanned} files\n`);
for (const f of findings) {
console.error(` ${f.file}:${f.line} ${f.kind}`);
console.error(` ${f.snippet}`);
diff --git a/scripts/inject-inline-behaviors.mjs b/scripts/inject-inline-behaviors.mjs
new file mode 100644
index 000000000..2a407764d
--- /dev/null
+++ b/scripts/inject-inline-behaviors.mjs
@@ -0,0 +1,98 @@
+#!/usr/bin/env node
+// Guarantee the declarative inline-behaviour handlers on EVERY built HTML page.
+// ===========================================================================
+// public/inline-behaviors.js turns `data-fallback*`, `data-action` and
+// `data-stop-propagation` attributes into behaviour. It exists because the site
+// CSP allows inline <script> by hash and nothing else, which means the
+// `onerror="..."` and `onclick="..."` attributes that used to do these jobs no
+// longer run.
+//
+// Coverage has to be total, and for a reason the Atlas injector does not
+// share: a page that renders an avatar grid from a template literal carries no
+// hint that it needs this file, and the failure is invisible until a remote
+// image 404s in front of a real visitor. So every page gets it, including the
+// embed surfaces Atlas deliberately skips: an embedded avatar with a broken
+// image is exactly the case this handles, and unlike stealing Cmd+K from a
+// third-party page, a delegated error listener scoped to our own <img> tags
+// takes nothing from the host.
+//
+// Only nav.html / footer.html are excluded. Those are fragments fetched and
+// assigned through innerHTML, where a <script> tag does not execute and can
+// render as visible text inside the nav.
+//
+// vite.config.js carries the matching `three-ws-inline-behaviors` transformIndexHtml
+// plugin so dev servers behave the same. This post-build pass over dist/ is the
+// belt to that suspenders, for the reason documented in inject-atlas.mjs: that
+// hook has historically missed pages depending on plugin ordering. Idempotent;
+// a second run is a no-op.
+
+import { readdirSync, statSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
+import { join, basename } from 'node:path';
+
+const EXCLUDED = new Set(['nav.html', 'footer.html']);
+
+export const INLINE_BEHAVIORS_TAG = '<script src="/inline-behaviors.js" defer></script>';
+// Presence of the src is the marker: it survives attribute reordering by a
+// later minifier, which matching the whole tag would not.
+const MARKER = 'src="/inline-behaviors.js"';
+
+export function shouldInject(filename) {
+ return !EXCLUDED.has(basename(filename));
+}
+
+export function injectInto(html) {
+ if (html.includes(MARKER)) return html;
+ if (html.includes('</head>')) return html.replace('</head>', `${INLINE_BEHAVIORS_TAG}</head>`);
+ if (html.includes('</body>')) return html.replace('</body>', `${INLINE_BEHAVIORS_TAG}</body>`);
+ return html + INLINE_BEHAVIORS_TAG;
+}
+
+function walk(dir, out = []) {
+ for (const name of readdirSync(dir)) {
+ const p = join(dir, name);
+ const st = statSync(p);
+ if (st.isDirectory()) walk(p, out);
+ else if (name.endsWith('.html')) out.push(p);
+ }
+ return out;
+}
+
+function main() {
+ const distDir = process.argv[2] || 'dist';
+ if (!existsSync(distDir)) {
+ console.error(`[inline-behaviors-inject] dist directory not found: ${distDir}`);
+ process.exit(2);
+ }
+
+ let injected = 0;
+ let already = 0;
+ let skipped = 0;
+
+ for (const file of walk(distDir)) {
+ if (!shouldInject(file)) {
+ skipped++;
+ continue;
+ }
+ const html = readFileSync(file, 'utf8');
+ if (html.includes(MARKER)) {
+ already++;
+ continue;
+ }
+ writeFileSync(file, injectInto(html));
+ injected++;
+ }
+
+ const covered = injected + already;
+ console.log(
+ `[inline-behaviors-inject] handler on ${covered}/${covered + skipped} pages ` +
+ `(${injected} injected, ${already} already had it, ${skipped} fragment surfaces skipped)`,
+ );
+
+ if (covered === 0) {
+ console.error('[inline-behaviors-inject] no pages were covered, which cannot be right');
+ process.exit(1);
+ }
+}
+
+// Importable for tests; only walks dist when run directly.
+if (process.argv[1] && process.argv[1].endsWith('inject-inline-behaviors.mjs')) main();
diff --git a/server/csp-hashes.mjs b/server/csp-hashes.mjs
index 3c1f81eb8..776299345 100644
--- a/server/csp-hashes.mjs
+++ b/server/csp-hashes.mjs
@@ -11,10 +11,11 @@
// 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.
+// elements, because a missed script means a blocked script means a broken page:
+// quoted attribute values may contain `>`, the element ends at the first
+// `</script` regardless of what the source text looks like, and a `<script`
+// inside a comment or a raw-text element is characters rather than markup.
+// 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
@@ -28,12 +29,17 @@
import { createHash } from 'node:crypto';
-const SCRIPT_OPEN = /<script/gi;
+// Elements whose content the HTML parser treats as raw text: a `<script>`
+// written inside one is characters on the page, not a tag. Missing this is not
+// a theoretical edge case. A CSS comment on /oracle that mentioned `<script>`
+// made the scanner start a phantom script element there and run it to the next
+// real `</script>`, which swallowed the PostHog snippet's opening tag. Its hash
+// never reached the header and the browser blocked it.
+const RAW_TEXT_ELEMENTS = ['style', 'textarea', 'title'];
// 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).
+// quoted values, and return the index just past the tag's closing `>` plus the
+// attribute text. Returns null for a tag that never closes (truncated document).
function readOpenTag(html, from) {
let i = from;
let quote = null;
@@ -56,54 +62,81 @@ function readOpenTag(html, from) {
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) {
+// Index of the first `</name` that actually terminates an element, i.e. one
+// followed by a tag terminator. `lower` is a lowercased copy of the whole
+// document so a page with many elements does not re-lowercase it each time.
+function findClose(lower, name, from) {
+ const needle = `</${name}`;
let i = from;
for (;;) {
- const idx = lower.indexOf('</script', i);
+ const idx = lower.indexOf(needle, i);
if (idx === -1) return null;
- const after = lower[idx + 8];
+ const after = lower[idx + needle.length];
if (after === undefined || after === '>' || after === '/' || /\s/.test(after)) return idx;
- i = idx + 8;
+ i = idx + needle.length;
}
}
+// True when `<` at `index` opens element `name` rather than one whose name
+// merely starts with it (`<scripty`, `<styles`).
+function opensElement(lower, index, name) {
+ if (!lower.startsWith(`<${name}`, index)) return false;
+ const next = lower[index + name.length + 1];
+ return next === undefined || next === '>' || next === '/' || /\s/.test(next);
+}
+
/**
* Every inline script body in `html`, in document order, exactly as the CSP
* hash algorithm sees it (the raw text between the tags).
+ *
+ * The scan walks the document once and steps over the three constructs where a
+ * `<script` is text rather than markup: HTML comments, and the raw-text
+ * elements above. Over-matching a script is harmless (an extra hash allows
+ * something that does not exist); under-matching ships the page blank.
+ *
* @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;
+ let i = 0;
+ while (i < html.length) {
+ const lt = html.indexOf('<', i);
+ if (lt === -1) break;
+
+ if (lower.startsWith('<!--', lt)) {
+ const end = html.indexOf('-->', lt + 4);
+ i = end === -1 ? html.length : end + 3;
continue;
}
- const tag = readOpenTag(html, nameEnd);
+
+ const raw = RAW_TEXT_ELEMENTS.find((name) => opensElement(lower, lt, name));
+ if (raw) {
+ const tag = readOpenTag(html, lt + raw.length + 1);
+ if (!tag) break;
+ const close = findClose(lower, raw, tag.end);
+ i = close === null ? html.length : close + raw.length + 2;
+ continue;
+ }
+
+ if (!opensElement(lower, lt, 'script')) {
+ i = lt + 1;
+ continue;
+ }
+
+ const tag = readOpenTag(html, lt + 7);
if (!tag) break;
- const close = findScriptCloseIn(lower, tag.end);
+ const isExternal = /\ssrc\s*=/i.test(tag.attrs);
+ const close = findClose(lower, 'script', 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));
+ if (!isExternal) bodies.push(html.slice(tag.end));
break;
}
- if (!/\ssrc\s*=/i.test(tag.attrs)) bodies.push(html.slice(tag.end, close));
- cursor = close + 8;
+ if (!isExternal) bodies.push(html.slice(tag.end, close));
+ i = close + 8;
}
return bodies;
}
diff --git a/src/agent-edit.js b/src/agent-edit.js
index b899736a3..5bb79330c 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -1324,8 +1324,8 @@ function renderPlansList(plans) {
const isActive = p.active !== false;
const planJson = JSON.stringify(p).replace(/"/g, '&quot;');
const action = isActive
- ? `<button class="btn-ghost danger" style="font-size:0.7rem; padding:0.25rem 0.6rem;" onclick="deletePlan('${p.id}')">Deactivate</button>`
- : `<button class="btn-ghost" style="font-size:0.7rem; padding:0.25rem 0.6rem; color:#86efac; border-color:rgba(134,239,172,0.4);" onclick="reactivatePlan('${p.id}')">Reactivate</button>`;
+ ? `<button class="btn-ghost danger" style="font-size:0.7rem; padding:0.25rem 0.6rem;" data-plan-action="deactivate" data-plan-id="${p.id}">Deactivate</button>`
+ : `<button class="btn-ghost" style="font-size:0.7rem; padding:0.25rem 0.6rem; color:#86efac; border-color:rgba(134,239,172,0.4);" data-plan-action="reactivate" data-plan-id="${p.id}">Reactivate</button>`;
return `
<div class="plan-row" style="display:flex; align-items:center; justify-content:space-between; padding:0.5rem 0.75rem; border:1px solid rgba(255,255,255,${isActive ? '0.08' : '0.05'}); border-radius:6px; background:rgba(255,255,255,0.02); opacity:${isActive ? '1' : '0.6'};">
<div>
@@ -1336,11 +1336,22 @@ function renderPlansList(plans) {
${p.included_skills?.length ? `<div style="font-size:0.7rem; color:rgba(164,240,188,0.65); margin-top:0.15rem;">Includes ${p.included_skills.length} skill${p.included_skills.length === 1 ? '' : 's'}: ${escHtml(p.included_skills.join(' · '))}</div>` : ''}
</div>
<div style="display:flex; gap:0.4rem;">
- <button class="btn-ghost" style="font-size:0.7rem; padding:0.25rem 0.6rem;" onclick="openPlanEditor(${planJson})">Edit</button>
+ <button class="btn-ghost" style="font-size:0.7rem; padding:0.25rem 0.6rem;" data-plan-action="edit" data-plan="${planJson}">Edit</button>
${action}
</div>
</div>`;
}).join('');
+
+ // Rows are rendered from strings, so each action declares itself and one
+ // delegated listener runs it. Inline onclick attributes do not survive the
+ // site CSP, which allows inline <script> by hash and nothing else.
+ list.onclick = (event) => {
+ const btn = event.target.closest('[data-plan-action]');
+ if (!btn) return;
+ if (btn.dataset.planAction === 'edit') return openPlanEditor(JSON.parse(btn.dataset.plan));
+ if (btn.dataset.planAction === 'deactivate') return deletePlan(btn.dataset.planId);
+ if (btn.dataset.planAction === 'reactivate') reactivatePlan(btn.dataset.planId);
+ };
}
// Skill names available on this agent (skills may be strings or {name} objects).
@@ -1368,7 +1379,7 @@ function renderPlanSkillsChecklist(selected = []) {
</label>`).join('');
}
-window.openPlanEditor = function openPlanEditor(plan) {
+function openPlanEditor(plan) {
const editor = $('plan-editor');
if (!editor) return;
$('plan-editor-id').value = plan?.id ?? '';
@@ -1384,7 +1395,7 @@ window.openPlanEditor = function openPlanEditor(plan) {
$('plan-name-input').focus();
};
-window.deletePlan = async function deletePlan(planId) {
+async function deletePlan(planId) {
if (!confirm('Deactivate this plan? It will be hidden from new subscribers; existing subscribers keep access until their period ends. You can reactivate it later.')) return;
try {
const r = await apiFetch(`${API_BASE}/subscriptions/plans/${planId}`, { method: 'DELETE', credentials: 'include' });
@@ -1395,7 +1406,7 @@ window.deletePlan = async function deletePlan(planId) {
}
};
-window.reactivatePlan = async function reactivatePlan(planId) {
+async function reactivatePlan(planId) {
try {
const r = await apiFetch(`${API_BASE}/subscriptions/plans/${planId}`, {
method: 'PATCH',
diff --git a/src/agent-exchange.js b/src/agent-exchange.js
index d64ab9fde..2e435ca11 100644
--- a/src/agent-exchange.js
+++ b/src/agent-exchange.js
@@ -464,7 +464,7 @@ async function doPurchase() {
`${escHtml(headline)}` +
`</div>` +
`<div style="font-size:12.5px;color:var(--muted);">${body} ` +
- `<a href="/pay" style="color:var(--usdc-lt);text-decoration:none;" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'">Learn about x402 →</a>` +
+ `<a href="/pay" class="ax-x402-link">Learn about x402 →</a>` +
`</div>` +
`</div>`;
els.receipt.classList.add('show');
diff --git a/src/agent-screen-hire.js b/src/agent-screen-hire.js
index c61cdb8e9..f0f81b315 100644
--- a/src/agent-screen-hire.js
+++ b/src/agent-screen-hire.js
@@ -203,7 +203,7 @@ export function createHireVisualizer(bodyEl, opts = {}) {
const ok = meta.phase === 'recorded';
const cls = meta.phase === 'over_cap' ? 'amber' : meta.phase === 'failed' ? 'red' : 'ok';
const link = meta.paymentExplorer
- ? `<a href="${esc(meta.paymentExplorer)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">tx ↗</a>`
+ ? `<a href="${esc(meta.paymentExplorer)}" target="_blank" rel="noopener" data-stop-propagation>tx ↗</a>`
: '';
const row = document.createElement('div');
row.className = `asc-hire-hrow ${cls}`;
diff --git a/src/agent-screen-pnl-hud.js b/src/agent-screen-pnl-hud.js
index 08445e841..334a21b1e 100644
--- a/src/agent-screen-pnl-hud.js
+++ b/src/agent-screen-pnl-hud.js
@@ -229,7 +229,7 @@ export function createPnlHud({ bodyEl, agentId, network = 'mainnet', onNetWorth
);
}
const logo = h.logo
- ? `<img class="asc-hud-row-logo" src="${esc(h.logo)}" alt="" loading="lazy" onerror="this.style.display='none'">`
+ ? `<img class="asc-hud-row-logo" src="${esc(h.logo)}" alt="" loading="lazy" data-fallback="hide">`
: `<span class="asc-hud-row-logo asc-hud-row-logo--ph"></span>`;
return (
`<div class="asc-hud-row" title="${esc(sym)}${pct ? ` · ${pct} of net worth` : ''}">` +
diff --git a/src/agent-team.js b/src/agent-team.js
index a89b99d54..a134c0608 100644
--- a/src/agent-team.js
+++ b/src/agent-team.js
@@ -240,7 +240,7 @@ function nodeFoot(node) {
const url = node.url || node.explorerUrl;
const sig = node.sig || node.signature;
if (url && sig) {
- bits.push(`<a class="tt-receipt" href="${esc(url)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">⛓ ${esc(truncate(sig, 6))}</a>`);
+ bits.push(`<a class="tt-receipt" href="${esc(url)}" target="_blank" rel="noopener" data-stop-propagation>⛓ ${esc(truncate(sig, 6))}</a>`);
}
if (!bits.length && node.status === 'running') return `<span class="tt-err" style="color:#7f8aa0">working…</span>`;
return bits.join('');
diff --git a/src/agent-wallet-hub/index.js b/src/agent-wallet-hub/index.js
index ccc6deab3..edcada8b6 100644
--- a/src/agent-wallet-hub/index.js
+++ b/src/agent-wallet-hub/index.js
@@ -197,7 +197,7 @@ export function mountAgentWalletHub({ mount, agent, initialTab, onNetworkChange
<div class="awh-header">
${
agent.avatar_thumbnail_url || agent.avatar_model_url
- ? `<img class="awh-avatar" src="${escapeHtml(agent.avatar_thumbnail_url || '')}" alt="" loading="lazy" onerror="this.remove()" />`
+ ? `<img class="awh-avatar" src="${escapeHtml(agent.avatar_thumbnail_url || '')}" alt="" loading="lazy" data-fallback="remove" />`
: '<div class="awh-avatar" aria-hidden="true"></div>'
}
<div class="awh-id">
diff --git a/src/agent-wallet-hub/tabs/deposit.js b/src/agent-wallet-hub/tabs/deposit.js
index 41bd83494..0fe5263df 100644
--- a/src/agent-wallet-hub/tabs/deposit.js
+++ b/src/agent-wallet-hub/tabs/deposit.js
@@ -255,7 +255,7 @@ registerWalletTab({
panel.innerHTML = `
<div class="awh-card">
<div class="awh-dep-who">
- ${avatar ? `<img class="awh-dep-who-av" src="${escapeHtml(avatar)}" alt="" loading="lazy" onerror="this.remove()" />` : ''}
+ ${avatar ? `<img class="awh-dep-who-av" src="${escapeHtml(avatar)}" alt="" loading="lazy" data-fallback="remove" />` : ''}
<div class="awh-dep-who-txt">You're funding <strong>${escapeHtml(agentName)}</strong></div>
</div>
<div class="awh-empty">This agent's Solana wallet is still being prepared. It's created automatically — refresh in a moment and the deposit address will appear here.</div>
@@ -275,7 +275,7 @@ registerWalletTab({
panel.innerHTML = `
<div class="awh-card">
<div class="awh-dep-who">
- ${avatar ? `<img class="awh-dep-who-av" src="${escapeHtml(avatar)}" alt="" loading="lazy" onerror="this.remove()" />` : ''}
+ ${avatar ? `<img class="awh-dep-who-av" src="${escapeHtml(avatar)}" alt="" loading="lazy" data-fallback="remove" />` : ''}
<div class="awh-dep-who-txt">You're funding <strong>${escapeHtml(agentName)}</strong> — send SOL to the wallet below.</div>
</div>
diff --git a/src/agent-wallet-hub/tabs/portfolio.js b/src/agent-wallet-hub/tabs/portfolio.js
index c3f02c331..51bed5b30 100644
--- a/src/agent-wallet-hub/tabs/portfolio.js
+++ b/src/agent-wallet-hub/tabs/portfolio.js
@@ -348,7 +348,7 @@ registerWalletTab({
const sym = escapeHtml(h.symbol || '?');
const sub = h.isNative ? 'Native' : (h.is_three ? '$THREE' : (h.stable ? 'Stable' : escapeHtml(h.name || '')));
const img = h.logo
- ? `<img src="${escapeHtml(h.logo)}" alt="" loading="lazy" onerror="this.replaceWith(Object.assign(document.createElement('span'),{className:'ph',textContent:'${sym.slice(0, 2)}'}))">`
+ ? `<img src="${escapeHtml(h.logo)}" alt="" loading="lazy" data-fallback="element" data-fallback-tag="span" data-fallback-class="ph" data-fallback-text="${sym.slice(0, 2)}">`
: `<span class="ph">${sym.slice(0, 2)}</span>`;
const value = h.usd_value != null ? (formatUsd(h.usd_value) || '—') : '<span class="awh-muted">unpriced</span>';
const amt = h.amount != null ? formatNum(h.amount) : '—';
diff --git a/src/agent-wallet-hub/tabs/recovery.js b/src/agent-wallet-hub/tabs/recovery.js
index f96bb05ec..10641b4da 100644
--- a/src/agent-wallet-hub/tabs/recovery.js
+++ b/src/agent-wallet-hub/tabs/recovery.js
@@ -216,7 +216,7 @@ registerWalletTab({
}
function avatarHTML(g) {
- if (g.avatar_url) return `<img src="${escapeHtml(g.avatar_url)}" alt="" loading="lazy" onerror="this.outerHTML='<span class=\\'awh-rec-ava\\'>${escapeHtml((g.label || '?').slice(0, 1).toUpperCase())}</span>'" />`;
+ if (g.avatar_url) return `<img src="${escapeHtml(g.avatar_url)}" alt="" loading="lazy" data-fallback="element" data-fallback-tag="span" data-fallback-class="awh-rec-ava" data-fallback-text="${escapeHtml((g.label || '?').slice(0, 1).toUpperCase())}" />`;
return `<span class="awh-rec-ava" aria-hidden="true">${escapeHtml((g.label || '?').slice(0, 1).toUpperCase())}</span>`;
}
diff --git a/src/agent-wallet-hub/tabs/trade.js b/src/agent-wallet-hub/tabs/trade.js
index 966b35848..78b8f6ff7 100644
--- a/src/agent-wallet-hub/tabs/trade.js
+++ b/src/agent-wallet-hub/tabs/trade.js
@@ -504,7 +504,7 @@ registerWalletTab({
const name = c.name ? esc(c.name) : 'Unknown coin';
const badge = c.graduated === true ? 'Graduated · AMM' : c.graduated === false ? 'Bonding curve' : '';
return `<div class="awh-tr-coin">
- ${c.image ? `<img src="${esc(c.image)}" alt="" loading="lazy" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'awh-tr-coin-ph'}))" />` : '<div class="awh-tr-coin-ph" aria-hidden="true"></div>'}
+ ${c.image ? `<img src="${esc(c.image)}" alt="" loading="lazy" data-fallback="element" data-fallback-class="awh-tr-coin-ph" />` : '<div class="awh-tr-coin-ph" aria-hidden="true"></div>'}
<div>
<div class="awh-tr-coin-name">${name}</div>
<div class="awh-tr-coin-sym">${sym} · <span class="awh-mono">${short(c.mint, 4, 4)}</span></div>
diff --git a/src/agents-live.js b/src/agents-live.js
index a32e280f7..a567cc90e 100644
--- a/src/agents-live.js
+++ b/src/agents-live.js
@@ -223,7 +223,7 @@ function buildCard(agent) {
</div>
<div class="al-card-info">
${avatar
- ? `<img loading="lazy" decoding="async" class="al-card-avatar" src="${esc(avatar)}" alt="${esc(name)}" onerror="this.style.display='none'">`
+ ? `<img loading="lazy" decoding="async" class="al-card-avatar" src="${esc(avatar)}" alt="${esc(name)}" data-fallback="hide">`
: `<div class="al-card-avatar" style="background:rgba(255,255,255,0.06)"></div>`}
<div class="al-card-meta">
<div class="al-card-name">${esc(name)}</div>
@@ -233,7 +233,7 @@ function buildCard(agent) {
<span class="al-card-pnl" data-pnl hidden></span>
</div>
</div>
- <a class="al-card-watch-btn" href="${esc(watchHref)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">Watch</a>
+ <a class="al-card-watch-btn" href="${esc(watchHref)}" target="_blank" rel="noopener" data-stop-propagation>Watch</a>
</div>`;
return el;
}
diff --git a/src/agora/agora-world.js b/src/agora/agora-world.js
index b2a0739c5..92b75b2bb 100644
--- a/src/agora/agora-world.js
+++ b/src/agora/agora-world.js
@@ -537,7 +537,7 @@ main().catch((err) => {
<h2>The Commons failed to load</h2>
<p>Something went wrong building the world. Reload to try again.</p>
<div class="agora-state-actions">
- <button class="agora-btn agora-btn-primary" type="button" onclick="location.reload()">Reload</button>
+ <button class="agora-btn agora-btn-primary" type="button" data-action="reload">Reload</button>
</div>
</div>`;
}
diff --git a/src/arm.js b/src/arm.js
index 55919753c..4f0c25c19 100644
--- a/src/arm.js
+++ b/src/arm.js
@@ -343,7 +343,7 @@ function renderQualifying() {
function qualRow(it, r) {
const sym = esc(it.symbol || (it.mint || '').slice(0, 6));
const img = it.image_uri
- ? `<img class="coinimg" src="${esc(it.image_uri)}" alt="" loading="lazy" onerror="this.remove()">`
+ ? `<img class="coinimg" src="${esc(it.image_uri)}" alt="" loading="lazy" data-fallback="remove">`
: '';
const smart = (it.smart_wallet_count || 0) >= 1
? `<span class="q-smart">${it.smart_wallet_count} smart in</span>`
diff --git a/src/autopilot.js b/src/autopilot.js
index b0070df71..e1d661e95 100644
--- a/src/autopilot.js
+++ b/src/autopilot.js
@@ -129,7 +129,7 @@ function coinCard(c) {
const on = p.enabled;
const initials = (c.symbol || c.name || 'A').slice(0, 2).toUpperCase();
const img = c.image
- ? `<img loading="lazy" decoding="async" src="${esc(c.image)}" alt="" onerror="this.remove()">`
+ ? `<img loading="lazy" decoding="async" src="${esc(c.image)}" alt="" data-fallback="remove">`
: '';
const gradPill = c.stats.graduated
? `<span class="pill grad"><span class="dot"></span>Graduated</span>`
diff --git a/src/avatar-edit.js b/src/avatar-edit.js
index fb3cf908b..e443bf5ec 100644
--- a/src/avatar-edit.js
+++ b/src/avatar-edit.js
@@ -669,7 +669,7 @@ function tilePreviewMarkup(preset) {
<span style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;">${emoji}</span>
<img src="${esc(preset.thumbnail)}" alt="" loading="lazy"
style="position:absolute;inset:0;"
- onerror="this.remove()" />
+ data-fallback="remove" />
`;
}
diff --git a/src/avatar-studio.js b/src/avatar-studio.js
index cbfadaa3d..1058ce0ae 100644
--- a/src/avatar-studio.js
+++ b/src/avatar-studio.js
@@ -791,7 +791,7 @@ function tilePreviewMarkup(preset) {
<span style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;">${emoji}</span>
<img src="${esc(preset.thumbnail)}" alt="" loading="lazy"
style="position:absolute;inset:0;"
- onerror="this.remove()" />
+ data-fallback="remove" />
`;
}
diff --git a/src/bounties.js b/src/bounties.js
index 4b750ce37..1ebdf7387 100644
--- a/src/bounties.js
+++ b/src/bounties.js
@@ -337,7 +337,7 @@ function scanningState() {
return `<div class="empty"><div class="ico">🔍</div><h3>Searching the board…</h3><p>Scanning every open bounty for “${esc(query)}”.</p></div>`;
}
function errorState(msg) {
- return `<div class="errbox"><div class="ico">⚠️</div><h3>Couldn't load bounties</h3><p>${esc(msg)}</p><button class="btn btn-ghost btn-sm" onclick="location.reload()">Try again</button></div>`;
+ return `<div class="errbox"><div class="ico">⚠️</div><h3>Couldn't load bounties</h3><p>${esc(msg)}</p><button class="btn btn-ghost btn-sm" data-action="reload">Try again</button></div>`;
}
function setLoadMore(text, disabled) {
const b = document.getElementById('load-more');
diff --git a/src/ca2x402.js b/src/ca2x402.js
index 47ac041f1..214bf8b4e 100644
--- a/src/ca2x402.js
+++ b/src/ca2x402.js
@@ -236,7 +236,7 @@ function riskPanel(r) {
function tokenCard(t) {
const chain = t.chain ? `<span class="cx-chain">${esc(t.chain)}</span>` : '';
const avatar = t.image
- ? `<img class="cx-av" src="${esc(t.image)}" alt="" loading="lazy" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'cx-av cx-av-ph',textContent:'${esc((t.symbol || '?').slice(0, 2))}'}))" />`
+ ? `<img class="cx-av" src="${esc(t.image)}" alt="" loading="lazy" data-fallback="element" data-fallback-class="cx-av cx-av-ph" data-fallback-text="${esc((t.symbol || '?').slice(0, 2))}" />`
: `<div class="cx-av cx-av-ph">${esc((t.symbol || '?').slice(0, 2))}</div>`;
const stats = [
['Price', fmtUsd(t.price_usd)],
diff --git a/src/category-page.js b/src/category-page.js
index 779c81095..0283569c8 100644
--- a/src/category-page.js
+++ b/src/category-page.js
@@ -321,7 +321,7 @@ function renderError() {
<h1 class="cv-h1">Category data unavailable</h1>
<div class="cv-empty" style="text-align:left">
<p style="margin:0">The market data source is temporarily unreachable. This usually clears in
- under a minute — <a href="javascript:location.reload()">reload the page</a> or head back to the
+ under a minute — <a href="#" data-action="reload">reload the page</a> or head back to the
<a href="/categories">categories index</a>.</p>
</div>`;
clearBelowHero();
diff --git a/src/character.js b/src/character.js
index bf1b7c0db..f387e9948 100644
--- a/src/character.js
+++ b/src/character.js
@@ -348,7 +348,7 @@ function renderMemes(agent) {
<a class="ch-meme-create" href="/agent/${agent.id}?meme=1" title="Create meme">
<div class="ch-meme-create-icon">
<img loading="lazy" decoding="async" src="${agent.meta?.profile_image_url || agent.avatar_thumbnail_url || ''}"
- onerror="this.style.display='none'"
+ data-fallback="hide"
alt="${agent.name}" />
</div>
<span class="ch-meme-create-label">Create Meme</span>
diff --git a/src/characters.js b/src/characters.js
index 2e3fd3739..f530f931d 100644
--- a/src/characters.js
+++ b/src/characters.js
@@ -53,7 +53,7 @@ function cardHtml(ch) {
const imgSrc = safeUrl(ch.image_url);
const avatarEl = imgSrc
? `<img loading="lazy" decoding="async" class="chs-card-avatar" src="${imgSrc}" alt="${name}"
- onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" />
+ data-fallback="sibling" />
<div class="chs-card-avatar-ph" style="display:none;background:${color}">${letter}</div>`
: `<div class="chs-card-avatar-ph" style="background:${color}">${letter}</div>`;
diff --git a/src/claim-wallet.js b/src/claim-wallet.js
index 35c727e30..5bafb2220 100644
--- a/src/claim-wallet.js
+++ b/src/claim-wallet.js
@@ -563,7 +563,7 @@ function ledgerRows(coins, sol) {
return rows.map((c) => {
const sym = esc((c.symbol || c.mint?.slice(0, 6) || '?').toUpperCase());
const img = c.image_uri
- ? `<img loading="lazy" decoding="async" class="cw-tok-img" src="${esc(c.image_uri)}" alt="" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'cw-tok-img',textContent:'${sym.slice(0, 2)}'}))" />`
+ ? `<img loading="lazy" decoding="async" class="cw-tok-img" src="${esc(c.image_uri)}" alt="" data-fallback="element" data-fallback-class="cw-tok-img" data-fallback-text="${esc(sym.slice(0, 2))}" />`
: `<div class="cw-tok-img">${esc(sym.slice(0, 2))}</div>`;
const badges = [
c.is_creator ? '<span class="cw-badge creator">DEV</span>' : '',
diff --git a/src/club.js b/src/club.js
index 845dfddb3..2b53c7cae 100644
--- a/src/club.js
+++ b/src/club.js
@@ -1905,7 +1905,7 @@ async function loadGalleryAvatars() {
function avatarThumbHTML(entry, name, { cls = 'club-pick-mono' } = {}) {
const initials = escapeText((name || '?').slice(0, 2).toUpperCase());
if (entry?.thumb) {
- return `<img src="${escapeText(entry.thumb)}" alt="" loading="lazy" onerror="this.remove()"/>`;
+ return `<img src="${escapeText(entry.thumb)}" alt="" loading="lazy" data-fallback="remove"/>`;
}
return `<span class="${cls}">${initials}</span>`;
}
diff --git a/src/coin-page.js b/src/coin-page.js
index 1af116299..3d735605b 100644
--- a/src/coin-page.js
+++ b/src/coin-page.js
@@ -1017,7 +1017,7 @@ function renderError() {
<h1 class="cv-h1">Market data unavailable</h1>
<div class="cv-empty" style="text-align:left">
<p style="margin:0">The market data source is temporarily unreachable. This usually clears in
- under a minute — <a href="javascript:location.reload()">reload the page</a> or head back to the
+ under a minute — <a href="#" data-action="reload">reload the page</a> or head back to the
<a href="/coins">markets index</a>.</p>
</div>`;
$('cv-chart').innerHTML = '';
diff --git a/src/coin3d/main.js b/src/coin3d/main.js
index d531d2f89..a2e452ad9 100644
--- a/src/coin3d/main.js
+++ b/src/coin3d/main.js
@@ -1073,7 +1073,7 @@ function launchCard(l) {
const initials = escapeHtml(sym.slice(0, 2));
const avatar = l.agent?.avatar_thumbnail_url || null;
const imgHtml = avatar
- ? `<img class="c3d-recent-img" src="${escapeHtml(avatar)}" alt="" loading="lazy" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'c3d-recent-img ph',textContent:'${initials}'}))" />`
+ ? `<img class="c3d-recent-img" src="${escapeHtml(avatar)}" alt="" loading="lazy" data-fallback="element" data-fallback-class="c3d-recent-img ph" data-fallback-text="${escapeHtml(initials)}" />`
: `<div class="c3d-recent-img ph">${initials}</div>`;
const label = escapeHtml(l.symbol ? `$${l.symbol.toUpperCase()}` : sym);
return `<a class="c3d-recent-card" href="?mint=${encodeURIComponent(l.mint)}" aria-label="View ${label} in 3D">
diff --git a/src/communities.js b/src/communities.js
index 560f394be..c0fa55227 100644
--- a/src/communities.js
+++ b/src/communities.js
@@ -50,7 +50,7 @@ function avatarChip({ kind, value, label, thumb, id }) {
chip.title = label;
chip.innerHTML = `
<span class="avatar-thumb">${thumb
- ? `<img loading="lazy" decoding="async" src="${escAttr(thumb)}" alt="" referrerpolicy="no-referrer" onerror="this.style.display='none'" />`
+ ? `<img loading="lazy" decoding="async" src="${escAttr(thumb)}" alt="" referrerpolicy="no-referrer" data-fallback="hide" />`
: `<span class="avatar-glyph">🧍</span>`}</span>
<span class="avatar-name">${esc(label)}</span>`;
chip.addEventListener('click', () => {
@@ -169,7 +169,7 @@ function coinCard(coin) {
card.className = 'coin-card';
card.innerHTML = `
<span class="coin-thumb">${image
- ? `<img src="${escAttr(image)}" alt="" loading="lazy" referrerpolicy="no-referrer" onerror="this.parentElement.classList.add('no-img')" />`
+ ? `<img src="${escAttr(image)}" alt="" loading="lazy" referrerpolicy="no-referrer" data-fallback="keep" data-fallback-parent-class="no-img" />`
: ''}<span class="coin-thumb-fallback">${esc((symbol || name).slice(0, 3).toUpperCase())}</span></span>
<span class="coin-info">
<span class="coin-symbol">$${esc(symbol || '—')}</span>
diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.js
index 240fc9057..085122a67 100644
--- a/src/dashboard-next/pages/agents.js
+++ b/src/dashboard-next/pages/agents.js
@@ -399,7 +399,9 @@ async function openDeployOnchainModal(host, agent, avatars, allAgents) {
skills: Array.isArray(agent.skills) && agent.skills.length ? agent.skills : undefined,
onchain: agent.onchain || null,
};
- const deployBtn = new OnchainDeployButton({ agent: deployAgentObj, container: deployHost });
+ // reveal:false keeps the user in the management flow (the modal + toast +
+ // re-render below is the feedback here, not the /mint-success page).
+ const deployBtn = new OnchainDeployButton({ agent: deployAgentObj, container: deployHost, reveal: false });
deployBtn.mount();
let deployed = false;
@@ -1220,11 +1222,7 @@ async function openCasterModal(agent) {
Generate credentials once, deploy anywhere Docker runs.
</p>
</div>
- <button data-action="close" aria-label="Close" style="
- flex-shrink:0;background:none;border:none;cursor:pointer;
- color:var(--nxt-ink-fade);padding:4px;border-radius:6px;
- transition:color 120ms ease;
- " onmouseenter="this.style.color='var(--nxt-ink)'" onmouseleave="this.style.color='var(--nxt-ink-fade)'">
+ <button data-action="close" aria-label="Close" class="nxt-icon-btn">
<svg viewBox="0 0 16 16" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M4 4l8 8M12 4l-8 8"/></svg>
</button>
</div>
diff --git a/src/dashboard-next/pages/analytics.js b/src/dashboard-next/pages/analytics.js
index fbd6ea1f0..9698511e0 100644
--- a/src/dashboard-next/pages/analytics.js
+++ b/src/dashboard-next/pages/analytics.js
@@ -37,7 +37,7 @@ let me = null;
return;
}
const main = document.querySelector('.dn-main-inner') || document.body;
- main.innerHTML = `<h1 class="dn-h1">Analytics</h1><div class="dn-panel"><div class="dn-panel-title" style="color:var(--nxt-danger)">Failed to load</div><div class="dn-panel-sub">${esc(err?.message || 'unknown')}</div><button class="dn-btn" onclick="location.reload()">Reload</button></div>`;
+ main.innerHTML = `<h1 class="dn-h1">Analytics</h1><div class="dn-panel"><div class="dn-panel-title" style="color:var(--nxt-danger)">Failed to load</div><div class="dn-panel-sub">${esc(err?.message || 'unknown')}</div><button class="dn-btn" data-action="reload">Reload</button></div>`;
});
function renderSkeletons(root) {
diff --git a/src/dashboard-next/pages/capabilities.js b/src/dashboard-next/pages/capabilities.js
index ac2dd2709..ef47e7e48 100644
--- a/src/dashboard-next/pages/capabilities.js
+++ b/src/dashboard-next/pages/capabilities.js
@@ -366,7 +366,7 @@ function renderAlphaHunt(strategies, agentMap) {
return `<tr>
<td>
<div class="cp-agent-chip">
- <img class="cp-av" src="${esc(ag?.image || '/favicon.ico')}" alt="" onerror="this.style.visibility='hidden'" loading="lazy" />
+ <img class="cp-av" src="${esc(ag?.image || '/favicon.ico')}" alt="" data-fallback="invisible" loading="lazy" />
<span>${esc(ag?.name || s.agent_id.slice(0, 8))}</span>
</div>
</td>
diff --git a/src/dashboard-next/pages/copy.js b/src/dashboard-next/pages/copy.js
index cf38fbc7e..73e8645ed 100644
--- a/src/dashboard-next/pages/copy.js
+++ b/src/dashboard-next/pages/copy.js
@@ -155,7 +155,7 @@ function intentRow(e) {
const mintAttr = e.mint ? ` data-oracle-mint="${esc(e.mint)}"` : '';
return `
<div class="cp-item" data-id="${esc(e.id)}"${mintAttr}>
- <img loading="lazy" decoding="async" class="cp-av" src="${esc(img(e))}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(img(e))}" alt="" data-fallback="invisible" />
<div class="cp-mid">
<div class="cp-title">
<span class="cp-tag ${isBuy ? 'buy' : 'sell'}">${isBuy ? 'BUY' : 'SELL'}</span>
@@ -178,7 +178,7 @@ function subRow(s) {
const paused = s.status === 'paused';
return `
<div class="cp-item" data-sub="${esc(s.id)}">
- <img loading="lazy" decoding="async" class="cp-av" src="${esc(img(s))}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(img(s))}" alt="" data-fallback="invisible" />
<div class="cp-mid">
<div class="cp-title">
<a href="${traderHref(s.leader_agent_id)}" style="color:inherit;text-decoration:none">${esc(s.leader_name || 'trader')}</a>
@@ -201,7 +201,7 @@ function earningsSection(earnings) {
const total = Number(earnings.total_fee_owed_sol) || 0;
const rows = owing.map((i) => `
<div class="cp-item" data-earn-sub="${esc(i.subscription_id)}">
- <img loading="lazy" decoding="async" class="cp-av" src="${esc(i.leader_image || '/favicon.ico')}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(i.leader_image || '/favicon.ico')}" alt="" data-fallback="invisible" />
<div class="cp-mid">
<div class="cp-title">${esc(i.leader_name || 'trader')}</div>
<div class="cp-sub">${fmtSol(i.cumulative_profit_sol)} profit copied · ${(i.perf_fee_bps / 100).toFixed(0)}% fee</div>
@@ -263,7 +263,7 @@ function historyRow(e) {
const label = status === 'skipped' ? (SKIP_LABEL[e.skip_reason] || 'Skipped') : status[0].toUpperCase() + status.slice(1);
return `
<div class="cp-item">
- <img loading="lazy" decoding="async" class="cp-av" src="${esc(img(e))}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(img(e))}" alt="" data-fallback="invisible" />
<div class="cp-mid">
<div class="cp-title">${esc(e.symbol || e.name || 'coin')} <span class="cp-sub" style="margin:0">via ${esc(e.leader_name || 'trader')}</span></div>
<div class="cp-sub">${relTime(e.created_at)} · ${e.direction === 'buy' && e.planned_sol ? fmtSol(e.planned_sol) : e.direction}</div>
@@ -311,7 +311,7 @@ function discoverRow(t) {
].filter(Boolean).join(' · ');
return `
<div class="cp-item">
- <img loading="lazy" decoding="async" class="cp-av" src="${esc(imgSrc)}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(imgSrc)}" alt="" data-fallback="invisible" />
<div class="cp-mid">
<div class="cp-title"><a href="/trader/${esc(t.agent_id)}" style="color:inherit;text-decoration:none">${esc(t.agent_name || 'agent')}</a></div>
<div class="cp-sub">${esc(meta)}</div>
@@ -556,7 +556,7 @@ function smartRow(w) {
: `<span class="sm-tw sm-mono">${esc(shortAddr(w.address))}</span>`;
const fallback = esc(initial(w));
const avatar = w.avatar
- ? `<img src="${esc(w.avatar)}" alt="" loading="lazy" onerror="this.replaceWith(document.createTextNode('${fallback}'))" />`
+ ? `<img src="${esc(w.avatar)}" alt="" loading="lazy" data-fallback="text" data-fallback-text="${fallback}" />`
: fallback;
const tags = [
...w.categories.map((c) => `<span class="sm-tag ${esc(c)}">${esc(c.replace('_', ' '))}</span>`),
diff --git a/src/dashboard-next/pages/fleet.js b/src/dashboard-next/pages/fleet.js
index e54dd28b5..0ef6d0f1e 100644
--- a/src/dashboard-next/pages/fleet.js
+++ b/src/dashboard-next/pages/fleet.js
@@ -373,7 +373,7 @@ function rosterRow(s) {
return `<tr class="fc-row ${_sel.has(s.agent_id) ? 'sel' : ''}" data-agent="${esc(s.agent_id)}">
<td class="c"><input type="checkbox" class="fc-check" data-check="${esc(s.agent_id)}" ${_sel.has(s.agent_id) ? 'checked' : ''} aria-label="Select ${esc(s.agent_name || s.agent_id)}" /></td>
<td><div class="fc-ag">
- <img class="fc-av" loading="lazy" decoding="async" src="${esc(s.image || '/favicon.ico')}" alt="" onerror="this.style.visibility='hidden'" />
+ <img class="fc-av" loading="lazy" decoding="async" src="${esc(s.image || '/favicon.ico')}" alt="" data-fallback="invisible" />
<div style="min-width:0"><div class="fc-agname">${esc(s.agent_name || s.agent_id)}</div><div class="fc-agsub fc-mono">${esc(String(s.agent_id).slice(0, 8))}</div></div>
</div></td>
<td>${pill}</td>
diff --git a/src/dashboard-next/pages/irl-outfit-editor.js b/src/dashboard-next/pages/irl-outfit-editor.js
index cfc665504..98208adcc 100644
--- a/src/dashboard-next/pages/irl-outfit-editor.js
+++ b/src/dashboard-next/pages/irl-outfit-editor.js
@@ -204,7 +204,7 @@ export async function openOutfitEditor({ pin, onSaved }) {
grid.innerHTML = items.map((p) => {
const on = active.has(p.id);
return `<button class="oe-acc-item${on ? ' on' : ''}" type="button" data-acc-id="${esc(p.id)}" aria-pressed="${on}" title="${esc(p.name)}">
- ${p.thumbnail ? `<img src="${esc(p.thumbnail)}" alt="" loading="lazy" onerror="this.style.visibility='hidden'" />` : '<span class="oe-acc-ph" aria-hidden="true">✦</span>'}
+ ${p.thumbnail ? `<img src="${esc(p.thumbnail)}" alt="" loading="lazy" data-fallback="invisible" />` : '<span class="oe-acc-ph" aria-hidden="true">✦</span>'}
<span class="oe-acc-name">${esc(p.name)}</span>
</button>`;
}).join('');
diff --git a/src/dashboard-next/pages/irl-placements.js b/src/dashboard-next/pages/irl-placements.js
index 09faf71dc..b167c4eba 100644
--- a/src/dashboard-next/pages/irl-placements.js
+++ b/src/dashboard-next/pages/irl-placements.js
@@ -483,7 +483,7 @@ function unreadForPin(pinId, list = inbox.interactions) {
function cardHtml(pin, ixList) {
const caption = pin.caption || '';
const img = pin.avatar_url
- ? `<img class="irl-av" src="${esc(pin.avatar_url)}" alt="" loading="lazy" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" /><div class="irl-av-fallback" style="display:none">📍</div>`
+ ? `<img class="irl-av" src="${esc(pin.avatar_url)}" alt="" loading="lazy" data-fallback="sibling" /><div class="irl-av-fallback" style="display:none">📍</div>`
: `<div class="irl-av-fallback">📍</div>`;
const visitors = Number(pin.view_count) || 0;
@@ -1193,7 +1193,7 @@ function openLocationMap({ pins, focusId, onSaved, onRemoved }) {
// ── Markers ────────────────────────────────────────────────────────────
function makeIcon(p, focused) {
const av = p.avatar_url
- ? `<img loading="lazy" decoding="async" src="${esc(p.avatar_url)}" alt="" onerror="this.remove()" />`
+ ? `<img loading="lazy" decoding="async" src="${esc(p.avatar_url)}" alt="" data-fallback="remove" />`
: '📍';
return L.divIcon({
className: 'irlmap-pin',
diff --git a/src/dashboard-next/pages/landscape.js b/src/dashboard-next/pages/landscape.js
index 57c8f620a..3ac97134b 100644
--- a/src/dashboard-next/pages/landscape.js
+++ b/src/dashboard-next/pages/landscape.js
@@ -288,7 +288,7 @@ function bindResize() {
})().catch(err => {
if (err?.message === 'redirecting') return;
const main = document.querySelector('.dn-main-inner') || document.body;
- main.innerHTML = `<h1 class="dn-h1">Competitive Landscape</h1><div class="dn-panel" style="padding:32px;text-align:center"><p style="color:var(--nxt-danger);margin-bottom:12px">Failed to load</p><p style="color:var(--nxt-ink-dim);font-size:13px">${esc(err?.message || 'Unknown error')}</p><button class="dn-btn" onclick="location.reload()" style="margin-top:16px">Reload</button></div>`;
+ main.innerHTML = `<h1 class="dn-h1">Competitive Landscape</h1><div class="dn-panel" style="padding:32px;text-align:center"><p style="color:var(--nxt-danger);margin-bottom:12px">Failed to load</p><p style="color:var(--nxt-ink-dim);font-size:13px">${esc(err?.message || 'Unknown error')}</p><button class="dn-btn" data-action="reload" style="margin-top:16px">Reload</button></div>`;
});
function renderAll(root) {
diff --git a/src/dashboard-next/pages/portfolio.js b/src/dashboard-next/pages/portfolio.js
index fa13c60fa..ca8ecc3a2 100644
--- a/src/dashboard-next/pages/portfolio.js
+++ b/src/dashboard-next/pages/portfolio.js
@@ -653,7 +653,7 @@ async function enrichHoldingsOracle(tbody) {
const badge = row.querySelector('.pf-oracle-badge');
if (!badge || badge.hasChildNodes()) continue;
const color = PF_TIER_COLOR[d.tier] || '#94a3b8';
- badge.innerHTML = `<a class="pf-ob" href="/oracle/coin/${encodeURIComponent(mint)}" title="Oracle conviction: ${d.score} · ${d.tier}" onclick="event.stopPropagation()" style="color:${color}">◎ ${d.score}</a>`;
+ badge.innerHTML = `<a class="pf-ob" href="/oracle/coin/${encodeURIComponent(mint)}" title="Oracle conviction: ${d.score} · ${d.tier}" data-stop-propagation style="color:${color}">◎ ${d.score}</a>`;
}
}
@@ -915,10 +915,12 @@ async function openAssetDrawer(token) {
<div class="pf-drawer-error">
<p>Failed to load asset data</p>
<p style="font-size:12px;color:var(--nxt-ink-fade)">${esc(err.message)}</p>
- <button class="dn-btn" onclick="this.closest('.pf-drawer-backdrop')?.classList.remove('is-open')">Close</button>
+ <button class="dn-btn" data-action="close">Close</button>
</div>
`;
- content.querySelector('[data-action="close"]').addEventListener('click', closeDrawer);
+ // The error state renders two close affordances (the header × and the
+ // button), so bind both rather than only the first match.
+ content.querySelectorAll('[data-action="close"]').forEach((el) => el.addEventListener('click', closeDrawer));
}
}
diff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.js
index bd07101d5..169cc600d 100644
--- a/src/dashboard-next/pages/sniper.js
+++ b/src/dashboard-next/pages/sniper.js
@@ -359,7 +359,7 @@ function stratCard(s) {
const label = s.agent_name || s.agent_id;
return `<div class="sn-card ${armed ? 'armed' : ''}" data-agent="${esc(s.agent_id)}">
<div class="sn-card-head" data-toggle="card" role="button" tabindex="0" aria-expanded="false" aria-label="Expand ${esc(label)} strategy details">
- <img loading="lazy" decoding="async" class="sn-av" src="${esc(img)}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="sn-av" src="${esc(img)}" alt="" data-fallback="invisible" />
<div class="sn-info">
<div class="sn-name">${esc(s.agent_name || s.agent_id)}</div>
<div class="sn-meta">
diff --git a/src/dashboard-next/pages/walk.js b/src/dashboard-next/pages/walk.js
index d3fa679b9..c2e362c50 100644
--- a/src/dashboard-next/pages/walk.js
+++ b/src/dashboard-next/pages/walk.js
@@ -231,7 +231,7 @@ function avatarCard(a) {
style="position:relative;display:flex;flex-direction:column;align-items:center;gap:8px;padding:14px 10px 12px;border-radius:12px;cursor:pointer;text-align:center;
background:rgba(255,255,255,0.02);border:1px solid ${selected ? 'var(--nxt-accent)' : 'var(--nxt-stroke)'};transition:border-color .15s,transform .15s,background .15s">
<div style="width:54px;height:54px;border-radius:12px;display:grid;place-items:center;overflow:hidden;font-size:30px;background:${a.accent ? hexSoft(a.accent) : 'rgba(255,255,255,0.04)'}">
- ${thumb ? `<img src="${esc(thumb)}" alt="" loading="lazy" style="width:100%;height:100%;object-fit:cover" onerror="this.replaceWith(document.createTextNode('${esc(a.emoji || '🚶')}'))" />` : esc(a.emoji || '🚶')}
+ ${thumb ? `<img src="${esc(thumb)}" alt="" loading="lazy" style="width:100%;height:100%;object-fit:cover" data-fallback="text" data-fallback-text="${esc(a.emoji || '🚶')}" />` : esc(a.emoji || '🚶')}
</div>
<div style="font-size:13px;font-weight:600;color:var(--nxt-ink);line-height:1.1">${esc(a.name)}</div>
<div style="font-size:11px;color:var(--nxt-ink-fade)">${esc(a.category || '')}</div>
diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.js
index e9bc5057e..b709aa4ca 100644
--- a/src/dashboard/dashboard.js
+++ b/src/dashboard/dashboard.js
@@ -3003,7 +3003,7 @@ function renderAgentRows(list, onchainAgents, dbAgents) {
'gap:12px; padding:10px; border:1px solid #2a2a34; border-radius:10px; align-items:flex-start';
el.innerHTML = `
<div style="flex:0 0 64px; width:64px; height:64px; border-radius:8px; background:#0f0f17; overflow:hidden; display:flex; align-items:center; justify-content:center">
- ${img ? `<img loading="lazy" decoding="async" src="${attr(img)}" alt="" style="max-width:100%;max-height:100%;object-fit:cover" onerror="this.remove()">` : '<span class="muted" style="font-size:10px">no image</span>'}
+ ${img ? `<img loading="lazy" decoding="async" src="${attr(img)}" alt="" style="max-width:100%;max-height:100%;object-fit:cover" data-fallback="remove">` : '<span class="muted" style="font-size:10px">no image</span>'}
</div>
<div style="flex:1 1 auto; min-width:0">
<div class="row" style="justify-content:space-between; gap:8px; flex-wrap:wrap">
diff --git a/src/deployments.js b/src/deployments.js
index 5d9f13b41..a9a0ebcdf 100644
--- a/src/deployments.js
+++ b/src/deployments.js
@@ -10,7 +10,7 @@
*/
import { createLogger } from './shared/log.js';
-import { updateValue, enterRow, liveDot, setLiveDot } from './ui-juice.js';
+import { updateValue, enterRow, enterStagger, liveDot, setLiveDot } from './ui-juice.js';
import { proxiedImageURL } from './ipfs.js';
const log = createLogger('deployments');
@@ -135,20 +135,74 @@ function renderTopChains(chains) {
return;
}
const peak = Math.max(1, ...chains.map((c) => c.count || 0));
+ const total = chains.reduce((sum, c) => sum + (c.count || 0), 0) || 1;
host.innerHTML = chains
.map((c) => {
const pct = Math.max(3, Math.round(((c.count || 0) / peak) * 100));
+ const share = Math.round(((c.count || 0) / total) * 100);
+ const name = c.explorer
+ ? `<a class="dp-chain-name" href="${esc(c.explorer)}" target="_blank" rel="noopener" title="Open ${esc(c.chain)} explorer">${esc(c.chain)}</a>`
+ : `<span class="dp-chain-name">${esc(c.chain)}</span>`;
return (
- `<div class="dp-chain-row">` +
- `<span class="dp-chain-name">${esc(c.chain)}</span>` +
+ `<div class="dp-chain-row" title="${esc(c.chain)}: ${fmtNum(c.count)} agents · ${share}% of this network">` +
+ name +
`<span class="dp-chain-bar"><span style="width:${pct}%"></span></span>` +
- `<span class="dp-chain-n">${fmtNum(c.count)}</span>` +
+ `<span class="dp-chain-n">${fmtNum(c.count)}<small class="dp-chain-share">${share}%</small></span>` +
`</div>`
);
})
.join('');
}
+// ── spotlight ─────────────────────────────────────────────────────────────────
+// The newest deployment of the current view gets a hero card above the
+// counters: the emotional beat of the page. Re-rendered (with an entrance)
+// only when a different agent takes the top slot.
+let spotlightId = null;
+
+function renderSpotlight(r) {
+ const host = $('dp-spotlight');
+ if (!host) return;
+ if (!r) {
+ host.hidden = true;
+ spotlightId = null;
+ return;
+ }
+ const dpId = `${r.chain_id}:${r.agent_id}`;
+ if (dpId === spotlightId) return;
+ spotlightId = dpId;
+
+ const remote = r.image && /^(https?|ipfs|ar):\/\//i.test(String(r.image));
+ const av = remote
+ ? `<img class="dp-spot-av" src="${esc(proxiedImageURL(String(r.image), dpId))}" alt="" loading="lazy" onerror="this.onerror=null;this.style.visibility='hidden'" />`
+ : `<span class="dp-spot-av dp-spot-av--mono" aria-hidden="true">${esc((r.name || '#').charAt(0).toUpperCase())}</span>`;
+ const title = r.name || `Agent #${esc(r.agent_id)}`;
+ const nameEl = r.agent_explorer
+ ? `<a class="dp-spot-name" href="${esc(r.agent_explorer)}" target="_blank" rel="noopener">${esc(title)}</a>`
+ : `<span class="dp-spot-name">${esc(title)}</span>`;
+ const tags =
+ (r.has_3d ? `<span class="dp-tag dp-tag--3d" title="Ships a 3D avatar">3D</span>` : '') +
+ (r.x402_support ? `<span class="dp-tag dp-tag--x402" title="Accepts x402 payments">x402</span>` : '');
+ const desc = r.description ? `<p class="dp-spot-desc">${esc(truncate(r.description, 160))}</p>` : '';
+ const owner = r.owner
+ ? `<a class="dp-owner" href="${esc(r.owner_explorer)}" target="_blank" rel="noopener" title="Owner address">${esc(shortAddr(r.owner))}</a>`
+ : '';
+ const tx = r.tx_explorer
+ ? `<a class="dp-tx" href="${esc(r.tx_explorer)}" target="_blank" rel="noopener">registration tx ↗</a>`
+ : '';
+ host.innerHTML =
+ `<span class="dp-spot-avwrap"><span class="dp-spot-ring" aria-hidden="true"></span>${av}</span>` +
+ `<span class="dp-spot-body">` +
+ `<span class="dp-spot-kicker">Latest to land</span>` +
+ `<span class="dp-spot-title">${nameEl}${tags}</span>` +
+ desc +
+ `<span class="dp-spot-meta"><span class="dp-chip">${esc(r.chain)}</span>${owner}` +
+ `<span class="dp-time" data-ts="${esc(r.registered_at)}" title="${esc(absDate(r.registered_at))}">${esc(timeAgo(r.registered_at))}</span>${tx}</span>` +
+ `</span>`;
+ host.hidden = false;
+ enterRow(host);
+}
+
// ── feed ───────────────────────────────────────────────────────────────────────
async function loadFeed(reset) {
if (state.loading) return;
@@ -202,7 +256,7 @@ function rowHTML(r) {
const mono = `<span class="dp-av dp-av--mono" aria-hidden="true">${esc((r.name || '#').charAt(0).toUpperCase())}</span>`;
const remote = r.image && /^(https?|ipfs|ar):\/\//i.test(String(r.image));
const av = remote
- ? `<img class="dp-av" src="${esc(proxiedImageURL(String(r.image), dpId))}" alt="" loading="lazy" onerror="this.onerror=null;this.style.visibility='hidden'" />`
+ ? `<img class="dp-av" src="${esc(proxiedImageURL(String(r.image), dpId))}" alt="" loading="lazy" data-fallback="invisible" />`
: mono;
const title = r.name || `Agent #${esc(r.agent_id)}`;
const nameEl = r.agent_explorer
@@ -226,7 +280,7 @@ function rowHTML(r) {
desc +
`<span class="dp-row-meta"><span class="dp-chip">${esc(r.chain)}</span>${owner}</span>` +
`</span>` +
- `<span class="dp-row-side"><span class="dp-time" title="${esc(timeTitle)}">${esc(timeLabel)}</span>${tx}</span>` +
+ `<span class="dp-row-side"><span class="dp-time" data-ts="${esc(r.registered_at)}" title="${esc(timeTitle)}">${esc(timeLabel)}</span>${tx}</span>` +
`</div>`
);
}
@@ -235,6 +289,7 @@ function renderFeed() {
const host = $('dp-feed');
if (!host) return;
if (!state.items.length) {
+ renderSpotlight(null);
const what = state.kind === '3d' ? 'agents with a 3D avatar' : state.kind === 'x402' ? 'x402-enabled agents' : 'on-chain agents';
host.innerHTML =
`<div class="dp-empty"><div class="dp-empty-title">No ${esc(what)} yet</div>` +
@@ -260,9 +315,12 @@ function renderFeed() {
enterRow(row); // shared slide-in so the live refresh reads as a stream
});
} else if (!renderedIds.size) {
- // Initial render or after full reset
+ // Initial render or after full reset: staggered entrance so the feed
+ // reads as a stream arriving, not a wall appearing.
host.innerHTML = state.items.map(rowHTML).join('');
+ enterStagger([...host.children], { step: 40 });
}
+ renderSpotlight(state.items[0] || null);
}
// ── controls ────────────────────────────────────────────────────────────────────
@@ -325,6 +383,13 @@ function setFeedLive(stateName) {
setLiveDot(document.querySelector('.dp-feed-head'), stateName);
}
+function tickTimes() {
+ for (const el of document.querySelectorAll('[data-ts]')) {
+ const label = timeAgo(el.dataset.ts);
+ if (label && el.textContent !== label) el.textContent = label;
+ }
+}
+
function init() {
const feedHead = document.querySelector('.dp-feed-head .dp-section-h');
if (feedHead) feedHead.insertAdjacentHTML('afterend', liveDot('connecting'));
@@ -340,6 +405,9 @@ function init() {
loadStats();
if (!state.paged) loadFeed(true);
}, 45_000);
+ setInterval(() => {
+ if (!document.hidden) tickTimes();
+ }, 30_000);
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index 715b98b1d..097993fc4 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -6,7 +6,7 @@
* viewer links specific to 3D-Agent.
*
* Tabs:
- * - Create Agent (4-step wizard: Identity → Services → Configuration → Deploy)
+ * - Create Agent (4-step wizard: Identity → Services → Avatar → Deploy)
* - My Agents (owned-by-wallet, current chain)
* - Search (by Agent ID)
* - Templates (pre-fills Create Agent)
@@ -363,6 +363,11 @@ export class RegisterUI {
constructor(containerEl, onRegistered, opts = {}) {
this.container = containerEl;
this.onRegistered = onRegistered || (() => {});
+ // Close-lifecycle callback, distinct from onRegistered: fired exactly once
+ // when the UI is torn down, with { registered } so callers refresh state
+ // only when a deploy actually happened (and never mid-success-screen).
+ this.onClose = opts.onClose || null;
+ this._didRegister = false;
this.mode = opts.mode === 'page' ? 'page' : 'modal';
this._viewer = opts.viewer || null;
this._avatarId = opts.avatarId || null;
@@ -504,7 +509,7 @@ export class RegisterUI {
<div class="erc8004-controls">
<select class="erc8004-chain-select" title="Target chain"></select>
<button class="erc8004-btn erc8004-btn--wallet btn btn--secondary" type="button">
- Connect MetaMask
+ Connect wallet
</button>
<button class="erc8004-btn erc8004-btn--close btn btn--ghost btn--icon" type="button" title="Close">✕</button>
</div>
@@ -568,6 +573,20 @@ export class RegisterUI {
.addEventListener('click', () => this._connectWallet());
const closeBtn = this.el.querySelector('.erc8004-btn--close');
if (closeBtn) closeBtn.addEventListener('click', () => this.destroy());
+ if (this.mode === 'modal') {
+ const card = this.el.querySelector('.erc8004-card');
+ if (card) {
+ card.setAttribute('role', 'dialog');
+ card.setAttribute('aria-modal', 'true');
+ card.setAttribute('aria-label', 'Deploy agent on-chain');
+ card.tabIndex = -1;
+ card.focus();
+ }
+ this._onKeydown = (e) => {
+ if (e.key === 'Escape') this.destroy();
+ };
+ document.addEventListener('keydown', this._onKeydown);
+ }
this.el.querySelector('.erc8004-chain-select').addEventListener('change', async (e) => {
const raw = e.target.value;
@@ -601,7 +620,11 @@ export class RegisterUI {
destroy() {
if (this._unsubscribeWallet) this._unsubscribeWallet();
+ if (this._onKeydown) document.removeEventListener('keydown', this._onKeydown);
this.el.remove();
+ const cb = this.onClose;
+ this.onClose = null;
+ cb?.({ registered: this._didRegister });
}
// -----------------------------------------------------------------------
@@ -1025,7 +1048,7 @@ export class RegisterUI {
_previewThumbHtml(thumb) {
if (thumb.kind === 'img') {
- return `<img loading="lazy" decoding="async" src="${esc(thumb.src)}" alt="" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" />
+ return `<img loading="lazy" decoding="async" src="${esc(thumb.src)}" alt="" data-fallback="sibling" />
<div class="deploy-preview-ph" style="display:none">Image failed to load</div>`;
}
if (thumb.kind === 'glb') {
@@ -1239,6 +1262,12 @@ export class RegisterUI {
*/
async _applyQuickStart(mode) {
if (mode === 'update') {
+ // Page mode renders only the Create wizard (no tab strip), so route to
+ // the real management surface instead of a tab that cannot appear here.
+ if (this._isPageMode()) {
+ window.location.href = '/dashboard-next/agents';
+ return;
+ }
this._setTab('my');
this._toast('Pick an agent and click "Edit on-chain ✏️".');
return;
@@ -1553,7 +1582,7 @@ export class RegisterUI {
body.innerHTML = `
<h3 class="erc8004-h3">3D Avatar</h3>
- <p class="erc8004-p">Attach a GLB so any 3D-aware client can render your agent's body, or deploy as metadata-only. ERC-8004 doesn't require a 3D avatar — a 2D <code>image</code> works too.</p>
+ <p class="erc8004-p">Attach a GLB so any 3D-aware client can render your agent's body, or deploy as metadata-only. ${_isSolana(this.selectedChainId) ? 'A Metaplex Core mint' : 'ERC-8004'} doesn't require a 3D avatar; a 2D <code>image</code> works too.</p>
<div class="erc8004-avatar-sources" data-role="sources">
${hasCurrent ? radio('current', 'Use current avatar', `From your active session — <code>${esc(this.form.glbUrl)}</code>`) : ''}
@@ -1561,15 +1590,16 @@ export class RegisterUI {
${DEFAULT_AVATARS.length ? radio('default', 'Use a default avatar', 'Pick a pre-pinned starter avatar — no upload needed.') : ''}
${radio('upload', 'Upload a new GLB', 'Drop or browse a .glb / .gltf file from your machine.')}
${radio('url', 'Paste a GLB URL', 'Use a GLB already hosted on IPFS, Arweave, or HTTPS.')}
- ${radio('skip', 'Skip — no 3D body', 'Deploy as a metadata-only agent. You can attach an avatar later via setAgentURI.')}
+ ${radio('skip', 'Skip: no 3D body', _isSolana(this.selectedChainId) ? 'Deploy as a metadata-only agent. You can attach an avatar later from your agent page.' : 'Deploy as a metadata-only agent. You can attach an avatar later via setAgentURI.')}
</div>
<div class="erc8004-avatar-panel" data-role="panel"></div>
+ ${_isSolana(this.selectedChainId) ? '' : `
<label class="erc8004-label">IPFS Pinning Token (optional)
<input class="erc8004-input" type="password" name="apiToken" autocomplete="off" placeholder="Pinata JWT (leave blank to use built-in R2 storage)" value="${esc(this.form.apiToken)}" />
</label>
- <p class="erc8004-hint">Without a token, uploads go through our backend (R2). Paste a Pinata JWT to pin directly to IPFS.</p>
+ <p class="erc8004-hint">Without a token, uploads go through our backend (R2). Paste a Pinata JWT to pin directly to IPFS.</p>`}
<div class="erc8004-wizard-nav">
<button class="erc8004-btn btn btn--secondary" data-role="back">← Back</button>
@@ -1688,7 +1718,7 @@ export class RegisterUI {
<span class="erc8004-avatar-summary-badge erc8004-avatar-summary-badge--muted">∅</span>
<div>
<div>Deploying as a metadata-only agent.</div>
- <div class="erc8004-hint">Your registration JSON will include <code>image</code> (from Step 1) and services but no GLB. You can attach an avatar later from My Agents → Edit.</div>
+ <div class="erc8004-hint">Your registration JSON will include <code>image</code> (from Step 1) and services but no GLB. ${_isSolana(this.selectedChainId) ? 'You can attach an avatar later from your agent page.' : 'You can attach an avatar later from My Agents → Edit.'}</div>
</div>
</div>
`;
@@ -1704,7 +1734,7 @@ export class RegisterUI {
});
});
- body.querySelector('[name="apiToken"]').addEventListener(
+ body.querySelector('[name="apiToken"]')?.addEventListener(
'input',
(e) => (this.form.apiToken = e.target.value),
);
@@ -2009,6 +2039,14 @@ export class RegisterUI {
<dt>Standard</dt> <dd>Metaplex Core (mpl-core)</dd>
</dl>
+ <div class="deploy-vanity-row">
+ <button type="button" class="erc8004-link deploy-vanity-link" data-role="vanity">
+ ${this._vanityPrefix
+ ? `✨ Vanity address: <code>${esc(this._vanityPrefix)}</code> · change`
+ : '✨ Customize mint address (optional)'}
+ </button>
+ </div>
+
${
!hasSolanaWallet
? `<div class="erc8004-alert">No Solana wallet detected. Install <a class="erc8004-link" href="https://phantom.app" target="_blank" rel="noopener">Phantom</a> (or Backpack / Solflare), then reload this page and click Mint.</div>`
@@ -2016,7 +2054,7 @@ export class RegisterUI {
}
<div class="erc8004-alert erc8004-alert--note">
<b>Note:</b> your Solana wallet must already be linked to this account
- (via Sign-In-with-Solana). If you haven't, <a class="erc8004-link" href="/login.html">link it first</a>.
+ (via Sign-In-with-Solana). If you haven't, <a class="erc8004-link" href="/login">link it first</a>.
</div>
<div class="deploy-phase-track" data-role="phase-track" hidden aria-live="polite">
@@ -2043,6 +2081,11 @@ export class RegisterUI {
</div>
</div>
+ <div class="erc8004-row deploy-grind" data-role="grind" hidden>
+ <span class="erc8004-muted erc8004-small" data-role="grind-status" aria-live="polite"></span>
+ <button type="button" class="erc8004-btn btn btn--ghost" data-role="grind-stop">Stop grinding</button>
+ </div>
+
<div class="erc8004-log" data-role="log" role="log" aria-live="polite" aria-label="Deploy log"></div>
<div class="deploy-error-panel" data-role="deploy-error" role="alert" hidden>
@@ -2081,6 +2124,24 @@ export class RegisterUI {
body.querySelector('[data-role="deploy"]').addEventListener('click', () =>
this._doSolanaDeploy(body),
);
+ body.querySelector('[data-role="vanity"]')?.addEventListener('click', async () => {
+ const { openVanityModal } = await import('./vanity-modal.js');
+ const chosen = await openVanityModal({
+ agentName: this.form.name || '',
+ initial: this._vanityPrefix || '',
+ });
+ if (chosen === null) return;
+ // The modal returns a string (prefix to grind in-browser) or
+ // { prefix, secretKey } for a CLI-ground keypair pasted by the user.
+ if (chosen && typeof chosen === 'object') {
+ this._vanityPrefix = chosen.prefix || '';
+ this._preGroundSecretKey = chosen.secretKey || null;
+ } else {
+ this._vanityPrefix = chosen;
+ this._preGroundSecretKey = null;
+ }
+ this._renderStepDeploySolana(body);
+ });
}
// -----------------------------------------------------------------------
@@ -2283,6 +2344,17 @@ export class RegisterUI {
return;
}
+ // First-time deployers get the plain-language wallet/fees explainer before
+ // any wallet prompt; returning users pass straight through.
+ try {
+ const { ensureOnchainPrimer } = await import('../shared/onchain-primer.js');
+ if (!(await ensureOnchainPrimer({ action: 'deploy' }))) {
+ deployBtn.disabled = false;
+ deployBtn.textContent = idleLabel;
+ return;
+ }
+ } catch { /* primer unavailable: proceed */ }
+
const setPhase = this._makePhaseTracker(body);
setPhase('prepare');
@@ -2300,7 +2372,7 @@ export class RegisterUI {
if (this.form.avatarSource !== 'skip') {
avatar = await this._ensurePersistedAvatar(say);
if (!avatar?.avatarId) {
- throw new Error('Could not prepare your avatar — fix the Avatar step and retry, or choose “Skip — no 3D body”.');
+ throw new Error('Could not prepare your avatar: fix the Avatar step and retry, or choose "Skip: no 3D body".');
}
if (avatar.imageUrl) {
this.form.imageUrl = avatar.imageUrl;
@@ -2315,13 +2387,46 @@ export class RegisterUI {
avatarId: avatar?.avatarId || undefined,
};
- say(avatar ? 'Avatar saved — connecting Solana wallet…' : 'Connecting Solana wallet…');
+ const vanityPrefix = (this._vanityPrefix || '').trim();
+ const preGround = this._preGroundSecretKey || null;
+ const willGrind = !!vanityPrefix && !preGround;
+ const grindRow = body.querySelector('[data-role="grind"]');
+ const grindStatus = body.querySelector('[data-role="grind-status"]');
+ const grindAbort = new AbortController();
+ const stopBtn = body.querySelector('[data-role="grind-stop"]');
+ if (stopBtn) stopBtn.onclick = () => grindAbort.abort();
+ if (willGrind && grindRow) {
+ grindRow.hidden = false;
+ if (grindStatus) grindStatus.textContent = `Searching for an address starting with "${vanityPrefix}"…`;
+ }
+
+ say(avatar ? 'Avatar saved. Connecting Solana wallet…' : 'Connecting Solana wallet…');
setPhase('sign');
- const result = await runSolanaDeploy({ agent: synthAgent, network });
+ const result = await runSolanaDeploy({
+ agent: synthAgent,
+ network,
+ vanity: (vanityPrefix || preGround)
+ ? {
+ prefix: vanityPrefix || undefined,
+ preGroundSecretKey: preGround || undefined,
+ signal: grindAbort.signal,
+ onProgress: willGrind
+ ? ({ attempts, rate, eta }) => {
+ if (grindStatus) {
+ grindStatus.textContent = `"${vanityPrefix}…" ${attempts.toLocaleString()} tries · ${Math.round(rate).toLocaleString()}/s · eta ${eta}`;
+ }
+ }
+ : undefined,
+ }
+ : undefined,
+ });
+ if (grindRow) grindRow.hidden = true;
setPhase('confirm');
say(`Minted asset ${result.assetPubkey}`);
say(`Tx ${result.txSignature}`);
setPhase('done');
+ this._vanityPrefix = '';
+ this._preGroundSecretKey = null;
deployBtn.textContent = 'Minted ✓';
body.querySelector('[data-role="res-id"]').textContent = result.assetPubkey;
@@ -2360,12 +2465,20 @@ export class RegisterUI {
);
}
+ this._didRegister = true;
this.onRegistered({
agentId: result.agent?.id || result.assetPubkey,
txHash: result.txSignature,
chainId: this.selectedChainId,
});
} catch (err) {
+ if (err?.name === 'AbortError') {
+ const grindRow = body.querySelector('[data-role="grind"]');
+ if (grindRow) grindRow.hidden = true;
+ deployBtn.disabled = false;
+ deployBtn.textContent = idleLabel;
+ return;
+ }
let friendly;
if (err?.code === 'forbidden') {
friendly =
@@ -2425,7 +2538,7 @@ export class RegisterUI {
const url = (this.form.imageUrl || '').trim();
if (!url) return '';
const thumb = `<img loading="lazy" decoding="async" src="${esc(url)}" alt="Agent image" class="erc8004-img-thumb"
- onerror="this.style.display='none'" />`;
+ data-fallback="hide" />`;
if (url.startsWith('data:')) {
const kb = Math.round((url.length * 0.75) / 1024);
return `<span class="erc8004-img-summary">${thumb}<span class="erc8004-muted">Captured from 3D view · inline image (~${kb} KB)</span></span>`;
@@ -2641,6 +2754,17 @@ export class RegisterUI {
return;
}
+ // First-time deployers get the plain-language wallet/fees explainer before
+ // any wallet prompt; returning users pass straight through.
+ try {
+ const { ensureOnchainPrimer } = await import('../shared/onchain-primer.js');
+ if (!(await ensureOnchainPrimer({ action: 'deploy' }))) {
+ deployBtn.disabled = false;
+ deployBtn.textContent = idleLabel;
+ return;
+ }
+ } catch { /* primer unavailable: proceed */ }
+
const setPhase = this._makePhaseTracker(body);
const phaseSay = this._phaseAwareSay(say, setPhase);
setPhase('prepare');
@@ -2691,6 +2815,7 @@ export class RegisterUI {
);
}
+ this._didRegister = true;
this.onRegistered({ ...result, chainId: this.selectedChainId });
await this._linkAgentToAccount({
agentId: result.agentId,
@@ -2823,18 +2948,73 @@ export class RegisterUI {
// Tab: My Agents
// -----------------------------------------------------------------------
+ // Solana explorer address URL (solana-deploy.js only exports the tx variant).
+ _solAddrUrl(network, addr) {
+ return network === 'devnet'
+ ? `https://explorer.solana.com/address/${addr}?cluster=devnet`
+ : `https://solscan.io/account/${addr}`;
+ }
+
+ // The user's on-chain Solana agents, read from the platform record
+ // (agent_identities.meta.onchain). Solana mints all flow through our
+ // pipeline, so the DB is the authoritative per-account index; no wallet
+ // scan is needed and signed-out users get a real sign-in path.
+ _renderMySolanaAgents(body) {
+ const network = _solanaNetwork(this.selectedChainId);
+ body.innerHTML = `
+ <h3 class="erc8004-h3">Your Registered Agents</h3>
+ <p class="erc8004-p">On-chain agents on <b>${esc(SOLANA_LABELS[this.selectedChainId])}</b> owned by this account.</p>
+ <div data-role="list"><div class="erc8004-muted">Loading…</div></div>
+ `;
+ const list = body.querySelector('[data-role="list"]');
+ fetch('/api/agents?onchain=true', { credentials: 'include', headers: { accept: 'application/json' } })
+ .then(async (res) => {
+ if (res.status === 401) {
+ list.innerHTML = `<div class="erc8004-muted">Sign in to see your on-chain agents. <a class="erc8004-link" href="/login">Sign in →</a></div>`;
+ return;
+ }
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ const wantDevnet = network === 'devnet';
+ const agents = (data.agents || []).filter((a) => {
+ const oc = a.onchain || a.meta?.onchain;
+ return oc?.family === 'solana' && (oc?.cluster === 'devnet') === wantDevnet;
+ });
+ if (!agents.length) {
+ list.innerHTML = `<div class="erc8004-muted">No agents minted on ${esc(network)} yet. <a class="erc8004-link" data-role="goto-create" href="#">Create one →</a> or <a class="erc8004-link" href="/discover" target="_blank" rel="noopener">browse the on-chain directory ↗</a>.</div>`;
+ list.querySelector('[data-role="goto-create"]').addEventListener('click', (e) => {
+ e.preventDefault();
+ this._setTab('create');
+ });
+ return;
+ }
+ list.innerHTML = '';
+ for (const a of agents) {
+ const oc = a.onchain || a.meta?.onchain || {};
+ const mint = oc.contract_or_mint || a.meta?.sol_mint_address || '';
+ const tx = oc.tx_hash || '';
+ const card = document.createElement('div');
+ card.className = 'erc8004-agent-card';
+ card.innerHTML = `
+ <div><b>${esc(a.name || 'Agent')}</b> <span class="erc8004-muted erc8004-small">${esc(network)}</span></div>
+ ${a.description ? `<p class="erc8004-p erc8004-small">${esc(a.description)}</p>` : ''}
+ <div class="erc8004-row">
+ <a class="erc8004-link" href="/agent/${encodeURIComponent(a.id)}">Agent page →</a>
+ ${mint ? `<a class="erc8004-link" href="${esc(this._solAddrUrl(network, mint))}" target="_blank" rel="noopener">Asset ↗</a>` : ''}
+ ${tx ? `<a class="erc8004-link" href="${esc(solanaTxExplorerUrl(network, tx))}" target="_blank" rel="noopener">Mint tx ↗</a>` : ''}
+ </div>
+ `;
+ list.appendChild(card);
+ }
+ })
+ .catch((err) => {
+ list.innerHTML = `<div class="erc8004-log-error">Could not load your agents: ${esc(err.message)}</div>`;
+ });
+ }
+
_renderMyAgents(body) {
if (_isSolana(this.selectedChainId)) {
- body.innerHTML = `
- <h3 class="erc8004-h3">Your Registered Agents</h3>
- <p class="erc8004-p">Listing on-chain Solana agents from this tab isn't wired up yet —
- use <a class="erc8004-link" data-role="goto-create" href="#">Create Agent →</a> to mint
- a new agent on <b>${esc(SOLANA_LABELS[this.selectedChainId])}</b>.</p>
- `;
- body.querySelector('[data-role="goto-create"]').addEventListener('click', (e) => {
- e.preventDefault();
- this._setTab('create');
- });
+ this._renderMySolanaAgents(body);
return;
}
body.innerHTML = `
@@ -3557,7 +3737,9 @@ export class RegisterUI {
if (_isSolana(this.selectedChainId)) {
body.innerHTML = `
<h3 class="erc8004-h3">Agent Search</h3>
- <p class="erc8004-p erc8004-muted">On-chain search isn't supported for Solana from this tab yet.</p>
+ <p class="erc8004-p">Cross-chain agent search (Solana included) lives in the on-chain
+ directory: <a class="erc8004-link" href="/discover" target="_blank" rel="noopener">open /discover ↗</a>.
+ For EVM-native lookups by ID, wallet, ENS, or tx hash, pick an EVM chain above.</p>
`;
return;
}
@@ -3750,12 +3932,43 @@ export class RegisterUI {
_renderHistory(body) {
if (_isSolana(this.selectedChainId)) {
+ const network = _solanaNetwork(this.selectedChainId);
body.innerHTML = `
<h3 class="erc8004-h3">Transaction History</h3>
- <p class="erc8004-p erc8004-muted">Solana history isn't surfaced here yet — check
- <a class="erc8004-link" href="https://solscan.io" target="_blank" rel="noopener">solscan.io</a>
- for your wallet's mints.</p>
+ <p class="erc8004-p">Your agent mints on <b>${esc(SOLANA_LABELS[this.selectedChainId])}</b>.</p>
+ <div data-role="list"><div class="erc8004-muted">Loading…</div></div>
`;
+ const list = body.querySelector('[data-role="list"]');
+ fetch('/api/agents?onchain=true', { credentials: 'include', headers: { accept: 'application/json' } })
+ .then(async (res) => {
+ if (res.status === 401) {
+ list.innerHTML = `<div class="erc8004-muted">Sign in to see your mint history. <a class="erc8004-link" href="/login">Sign in →</a></div>`;
+ return;
+ }
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ const wantDevnet = network === 'devnet';
+ const mints = (data.agents || [])
+ .map((a) => ({ a, oc: a.onchain || a.meta?.onchain }))
+ .filter(({ oc }) => oc?.family === 'solana' && (oc?.cluster === 'devnet') === wantDevnet && oc?.tx_hash);
+ if (!mints.length) {
+ list.innerHTML = `<div class="erc8004-muted">No mints on ${esc(network)} yet.</div>`;
+ return;
+ }
+ list.innerHTML = mints
+ .map(({ a, oc }) => {
+ const when = oc.confirmed_at ? new Date(oc.confirmed_at).toLocaleString() : '';
+ return `<div class="erc8004-agent-card">
+ <b>${esc(a.name || 'Agent')}</b>
+ ${when ? `<span class="erc8004-muted erc8004-small"> · ${esc(when)}</span>` : ''}
+ <a class="erc8004-link" style="margin-left:8px" href="${esc(solanaTxExplorerUrl(network, oc.tx_hash))}" target="_blank" rel="noopener">Tx ↗</a>
+ </div>`;
+ })
+ .join('');
+ })
+ .catch((err) => {
+ list.innerHTML = `<div class="erc8004-log-error">Could not load history: ${esc(err.message)}</div>`;
+ });
return;
}
body.innerHTML = `
diff --git a/src/fact-checker-app.js b/src/fact-checker-app.js
index a3fe89648..55a8adc36 100644
--- a/src/fact-checker-app.js
+++ b/src/fact-checker-app.js
@@ -96,7 +96,7 @@ function renderSources(sources) {
return `
<div class="source-card">
<div class="source-header">
- ${favicon ? `<img class="source-favicon" src="${favicon}" alt="" loading="lazy" onerror="this.style.display='none'" />` : ''}
+ ${favicon ? `<img class="source-favicon" src="${favicon}" alt="" loading="lazy" data-fallback="hide" />` : ''}
<div class="source-title">
<a href="${escHtml(sanitizeUrl(s.url))}" target="_blank" rel="noopener noreferrer">${escHtml(s.title || shortUrl)}</a>
</div>
diff --git a/src/guardian.js b/src/guardian.js
index ada947a8a..fd93cce81 100644
--- a/src/guardian.js
+++ b/src/guardian.js
@@ -109,7 +109,7 @@ async function call(url, { method = 'GET', body = null } = {}) {
let busy = false;
function avatarHTML(item) {
- if (item.avatar_url) return `<img class="gd-ava" src="${esc(item.avatar_url)}" alt="" loading="lazy" onerror="this.outerHTML='<span class=\\'gd-ava\\'>${esc((item.agent_name || '?').slice(0, 1).toUpperCase())}</span>'" />`;
+ if (item.avatar_url) return `<img class="gd-ava" src="${esc(item.avatar_url)}" alt="" loading="lazy" data-fallback="element" data-fallback-tag="span" data-fallback-class="gd-ava" data-fallback-text="${esc((item.agent_name || '?').slice(0, 1).toUpperCase())}" />`;
return `<span class="gd-ava" aria-hidden="true">${esc((item.agent_name || '?').slice(0, 1).toUpperCase())}</span>`;
}
diff --git a/src/handle.js b/src/handle.js
index 607a45579..62829b688 100644
--- a/src/handle.js
+++ b/src/handle.js
@@ -197,7 +197,7 @@ function renderClaimLanding() {
background: #fff; color: #0a0c10; font-weight: 600; font-size: 15px;
padding: 12px 28px; border-radius: 8px; text-decoration: none;
transition: opacity 0.15s;
- " onmouseover="this.style.opacity='0.88'" onmouseout="this.style.opacity='1'">
+ " class="hd-cta-link">
Get started →
</a>
<p style="margin: 24px 0 0; font-size: 13px; color: rgba(232,236,242,0.4);">
diff --git a/src/ibm-galaxy.js b/src/ibm-galaxy.js
index b8a885872..b796a2e82 100644
--- a/src/ibm-galaxy.js
+++ b/src/ibm-galaxy.js
@@ -701,7 +701,7 @@ function clearSearch() {
// ── Markup helpers ────────────────────────────────────────────────────────────
function avatarMarkup(a, cls) {
- if (a.image) return `<img class="${cls}" src="${escapeAttr(a.image)}" alt="" loading="lazy" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'${cls} placeholder',textContent:'${escapeAttr((a.name[0] || '?').toUpperCase())}'}))" />`;
+ if (a.image) return `<img class="${cls}" src="${escapeAttr(a.image)}" alt="" loading="lazy" data-fallback="element" data-fallback-class="${cls} placeholder" data-fallback-text="${escapeAttr((a.name[0] || '?').toUpperCase())}" />`;
return `<div class="${cls} placeholder">${escapeHtml((a.name[0] || '?').toUpperCase())}</div>`;
}
function escapeHtml(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])); }
diff --git a/src/labor-market.js b/src/labor-market.js
index 2cc6c10d2..6bb212efc 100644
--- a/src/labor-market.js
+++ b/src/labor-market.js
@@ -225,7 +225,7 @@ function bountyCard(b) {
<p class="lm-card-spec">${esc((b.spec || '').slice(0, 150))}${(b.spec || '').length > 150 ? '…' : ''}</p>
<div class="lm-card-foot">
${chip(b.required_skill)}
- <span class="lm-card-meta">by <a href="/agent/${esc(b.poster_agent_id)}" onclick="event.stopPropagation()">${esc(b.poster_name)}</a></span>
+ <span class="lm-card-meta">by <a href="/agent/${esc(b.poster_agent_id)}" data-stop-propagation>${esc(b.poster_name)}</a></span>
${mine ? '<span class="lm-tag-mine">yours</span>' : ''}
<span class="lm-card-bids ${hot ? 'is-hot' : ''}">${b.bid_count} bid${b.bid_count === 1 ? '' : 's'}</span>
${b.escrow_explorer ? `<span class="lm-card-escrow" title="Reward escrowed on-chain">◆ escrowed</span>` : ''}
@@ -244,7 +244,7 @@ function jobCard(j) {
<h3 class="lm-card-title">${esc(j.title || 'Job')}</h3>
<div class="lm-card-foot">
${chip(j.required_skill)}
- <span class="lm-card-meta"><a href="/agent/${esc(j.poster_agent_id)}" onclick="event.stopPropagation()">${esc(j.poster_name)}</a> → <a href="/agent/${esc(j.worker_agent_id)}" onclick="event.stopPropagation()">${esc(j.worker_name)}</a></span>
+ <span class="lm-card-meta"><a href="/agent/${esc(j.poster_agent_id)}" data-stop-propagation>${esc(j.poster_name)}</a> → <a href="/agent/${esc(j.worker_agent_id)}" data-stop-propagation>${esc(j.worker_name)}</a></span>
${mine ? '<span class="lm-tag-mine">yours</span>' : ''}
<span class="lm-card-bids">${ago(j.created_at)}</span>
</div>
@@ -262,7 +262,7 @@ function settledCard(s) {
<h3 class="lm-card-title">${esc(s.title || 'Bounty')}</h3>
<div class="lm-card-foot">
${chip(s.required_skill)}
- <span class="lm-card-meta"><a href="/agent/${esc(s.poster_agent_id)}" onclick="event.stopPropagation()">${esc(s.poster_name)}</a> → <a href="/agent/${esc(s.worker_agent_id)}" onclick="event.stopPropagation()">${esc(s.worker_name)}</a></span>
+ <span class="lm-card-meta"><a href="/agent/${esc(s.poster_agent_id)}" data-stop-propagation>${esc(s.poster_name)}</a> → <a href="/agent/${esc(s.worker_agent_id)}" data-stop-propagation>${esc(s.worker_name)}</a></span>
${mine ? '<span class="lm-tag-mine">yours</span>' : ''}
${Number(s.royalty_three) > 0 ? `<span class="lm-card-bids">+${fmtThree(s.royalty_three)} royalty</span>` : ''}
</div>
diff --git a/src/leaderboard.js b/src/leaderboard.js
index 6ed9bbfe0..b9e244522 100644
--- a/src/leaderboard.js
+++ b/src/leaderboard.js
@@ -109,7 +109,7 @@ function rowMarkup(r) {
<a class="lb-row" href="${href}" data-key="${escapeHtml(String(r.agent_id))}" data-top="${r.rank <= 3 ? r.rank : ''}" aria-label="${escapeHtml(rowLabel)}">
<span class="lb-rank">${r.rank}</span>
<span class="lb-trader">
- <img class="lb-avatar" src="${escapeHtml(img)}" alt="" loading="lazy" onerror="this.src='${identicon(r.agent_id || r.wallet || '?')}'" />
+ <img class="lb-avatar" src="${escapeHtml(img)}" alt="" loading="lazy" data-fallback-src="${identicon(r.agent_id || r.wallet || '?')}" />
<span class="lb-trader-meta">
<span class="lb-trader-name"><span class="lb-trader-nm">${escapeHtml(r.agent_name || 'Unnamed agent')}</span>${verifiedBadge(r.verified)}</span>
<span class="lb-trader-sub">${r.wallet ? walletChipHTML(r, { isOwner: false, showPending: false, link: false }) : escapeHtml(shortAddr(r.wallet))} · ${r.unique_coins} coins${r.top_coin ? ` · ${signatureCoin(r.top_coin, { compact: true })}` : ''}${r.copiers ? ` · <span class="lb-copiers">${r.copiers} copying</span>` : ''}</span>
@@ -295,7 +295,7 @@ function renderSpotlight(data) {
<a class="lb-spot-card" href="${href}" aria-label="${escapeHtml(label)}">
<div class="lb-spot-tag"><span class="lb-spot-crown" aria-hidden="true">♛</span> Most profitable trader · ${escapeHtml(WINDOW_LABEL[state.window] || state.window)}</div>
<div class="lb-spot-body">
- <img class="lb-spot-av" src="${escapeHtml(img)}" alt="" loading="lazy" onerror="this.src='${identicon(top.agent_id || '?')}'" />
+ <img class="lb-spot-av" src="${escapeHtml(img)}" alt="" loading="lazy" data-fallback-src="${identicon(top.agent_id || '?')}" />
<div class="lb-spot-main">
<div class="lb-spot-name">${name}${verifiedBadge(top.verified)}</div>
${coin}
@@ -553,7 +553,7 @@ async function loadOracleLeaderboard() {
for (const a of agents) {
// identicon() returns a data-URI for an <img loading="lazy" decoding="async" src> — it must never be dropped
// into element text (that renders the raw "data:image/svg+xml…" string).
- const img = `<img class="lb-avatar" src="${escapeHtml(a.image_url || identicon(a.agent_id))}" alt="" loading="lazy" onerror="this.src='${identicon(a.agent_id)}'" />`;
+ const img = `<img class="lb-avatar" src="${escapeHtml(a.image_url || identicon(a.agent_id))}" alt="" loading="lazy" data-fallback-src="${identicon(a.agent_id)}" />`;
const name = escapeHtml(a.name || a.agent_id.slice(0, 8) + '…');
const wr = a.win_rate != null
? `<span class="${a.win_rate >= 60 ? 'lb-pos' : a.win_rate >= 40 ? '' : 'lb-neg'}">${a.win_rate}%</span>`
diff --git a/src/marketplace.js b/src/marketplace.js
index 6e66350cb..667af47b8 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -4561,7 +4561,7 @@ function renderAvatarCard(a, spotlight = false) {
// reveal="auto" (default) means model-viewer un-veils the model on load;
// no explicit dismissPoster() call needed.
const preview = a.image
- ? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'card-img-fallback'}))" />`
+ ? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" data-fallback="element" data-fallback-class="card-img-fallback" />`
: a.glbUrl
? `${placeholderHtml(a.name)}<model-viewer
data-src="${escapeHtml(a.glbUrl)}"
@@ -4595,7 +4595,7 @@ function renderAvatarCard(a, spotlight = false) {
${tagPills}
<div class="footer">
${modelCategoryBadge(a.modelCategory)}
- ${a.glbUrl ? `<a class="compose-cta" href="/compose?glb=${encodeURIComponent(a.glbUrl)}" title="Open in Scene Composer" tabindex="-1" onclick="event.stopPropagation()">⚡ Compose</a>` : ''}
+ ${a.glbUrl ? `<a class="compose-cta" href="/compose?glb=${encodeURIComponent(a.glbUrl)}" title="Open in Scene Composer" tabindex="-1" data-stop-propagation>⚡ Compose</a>` : ''}
<span class="open-cta">Open →</span>
</div>
</div>
@@ -4631,7 +4631,7 @@ function pedigreeBadgeHTML(a) {
if (tier === 'common') return '';
const glyph = g.emergent > 0 ? '⚡' : '◈';
const title = `Generation ${g.generation} · ${tier} pedigree${g.emergent > 0 ? ` · ${g.emergent} emergent skill${g.emergent > 1 ? 's' : ''}` : ''}`;
- return `<a class="stat-pill pedigree-badge" data-tier="${escapeHtml(tier)}" href="/genome?a=${escapeHtml(a.id)}" title="${escapeHtml(title)}" onclick="event.stopPropagation()">${glyph} gen ${g.generation}</a>`;
+ return `<a class="stat-pill pedigree-badge" data-tier="${escapeHtml(tier)}" href="/genome?a=${escapeHtml(a.id)}" title="${escapeHtml(title)}" data-stop-propagation>${glyph} gen ${g.generation}</a>`;
}
function renderCard(a) {
@@ -4729,7 +4729,7 @@ function renderOnchainCard(a) {
const href = a.viewerUrl || a.tokenExplorerUrl || '#';
const priceBadge = priceBadgeHtml(a.price);
const preview = a.image
- ? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'card-img-fallback'}))" />`
+ ? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" data-fallback="element" data-fallback-class="card-img-fallback" />`
: a.glbUrl
? `${placeholderHtml(a.name)}<model-viewer
data-src="${escapeHtml(a.glbUrl)}"
@@ -8840,7 +8840,7 @@ async function loadTopPerformers() {
? (a.realized_pnl_sol >= 0 ? 'pos' : 'neg')
: '';
const avatarHtml = a.image_url
- ? `<img src="${escapeHtml(a.image_url)}" alt="" class="mkt-top-avatar" loading="lazy" onerror="this.style.display='none'">`
+ ? `<img src="${escapeHtml(a.image_url)}" alt="" class="mkt-top-avatar" loading="lazy" data-fallback="hide">`
: `<span class="mkt-top-avatar-fallback">${escapeHtml((a.name || '?')[0].toUpperCase())}</span>`;
return `<a class="mkt-top-card" href="/agents/${encodeURIComponent(a.agent_id)}"
diff --git a/src/markets-trending.js b/src/markets-trending.js
index 0bceb0de3..13e216f67 100644
--- a/src/markets-trending.js
+++ b/src/markets-trending.js
@@ -52,10 +52,10 @@ function coinRow(c, i) {
const flame = i === 0 ? '<span class="trd-flame" aria-hidden="true">🔥</span>' : '';
const href = `/coin/${encodeURIComponent(c.id)}`;
const spark = c.sparkline_url
- ? `<img class="trd-spark" src="${esc(c.sparkline_url)}" loading="lazy" alt="" width="120" height="40" onerror="this.remove()" />`
+ ? `<img class="trd-spark" src="${esc(c.sparkline_url)}" loading="lazy" alt="" width="120" height="40" data-fallback="remove" />`
: '<span class="trd-spark trd-spark-empty" aria-hidden="true"></span>';
const img = c.image
- ? `<img class="trd-coin-img" src="${esc(c.image)}" loading="lazy" alt="" width="28" height="28" onerror="this.style.visibility='hidden'" />`
+ ? `<img class="trd-coin-img" src="${esc(c.image)}" loading="lazy" alt="" width="28" height="28" data-fallback="invisible" />`
: '<span class="trd-coin-img" aria-hidden="true"></span>';
return `
<a class="trd-coin" href="${esc(href)}">
@@ -117,7 +117,7 @@ function renderCategories(cats) {
function nftCard(n) {
const thumb = n.thumb
- ? `<img class="trd-nft-img" src="${esc(n.thumb)}" loading="lazy" alt="" width="40" height="40" onerror="this.style.visibility='hidden'" />`
+ ? `<img class="trd-nft-img" src="${esc(n.thumb)}" loading="lazy" alt="" width="40" height="40" data-fallback="invisible" />`
: '<span class="trd-nft-img" aria-hidden="true"></span>';
return `
<div class="trd-card trd-nft">
diff --git a/src/mission-control/focus.js b/src/mission-control/focus.js
index fa6e0dcbf..ea2ceecfb 100644
--- a/src/mission-control/focus.js
+++ b/src/mission-control/focus.js
@@ -197,7 +197,7 @@ export function createFocusPane({ store, bus, enrich, mount }) {
].filter(Boolean);
head.innerHTML = `
- ${img ? `<img class="mc-focus-img" src="${escapeHtml(img)}" alt="" loading="lazy" onerror="this.style.visibility='hidden'" />` : '<div class="mc-focus-img" aria-hidden="true"></div>'}
+ ${img ? `<img class="mc-focus-img" src="${escapeHtml(img)}" alt="" loading="lazy" data-fallback="invisible" />` : '<div class="mc-focus-img" aria-hidden="true"></div>'}
<div class="mc-focus-id">
<h2>${sym} <span class="mc-focus-name">${name}</span></h2>
<div class="mc-focus-addr">
diff --git a/src/model-page.js b/src/model-page.js
index 1f6f479f3..155efae27 100644
--- a/src/model-page.js
+++ b/src/model-page.js
@@ -592,7 +592,7 @@ function renderError() {
<div class="mp-error">
<h1>Something broke</h1>
<p>The model could not be loaded right now.</p>
- <p><button type="button" onclick="location.reload()">Retry</button> · <a href="/creations">Back to creations</a></p>
+ <p><button type="button" data-action="reload">Retry</button> · <a href="/creations">Back to creations</a></p>
</div>`;
}
diff --git a/src/oracle.js b/src/oracle.js
index 74a19f093..8d3dec390 100644
--- a/src/oracle.js
+++ b/src/oracle.js
@@ -55,15 +55,15 @@ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '
//
// Returns the `src` + fallback attributes for an <img>. `seed` should be a stable
// per-token identifier (mint, symbol) so a given coin's placeholder art is unique
-// and identical across loads. On error we drop to the seed-only placeholder (no
-// upstream URL), clearing onerror first so a placeholder that itself fails cannot
-// spin an error loop.
+// and identical across loads. On error the shared handler in
+// public/inline-behaviors.js swaps to the seed-only placeholder (no upstream
+// URL) exactly once, so a placeholder that itself fails cannot spin an error
+// loop, and `data-fallback="keep"` leaves the element in place after that
+// rather than pulling it out of the grid.
//
-// The placeholder URL is carried in `data-ph` and read back via `this.dataset.ph`
-// rather than interpolated into the onerror script. Seeds are attacker-controlled
-// (a pump.fun launcher picks the token symbol), so splicing one into a quoted JS
-// string literal would be an injection vector. Here the onerror body is a constant
-// and both URLs only ever land in esc()'d attribute values.
+// Seeds are attacker-controlled (a pump.fun launcher picks the token symbol), so
+// both URLs only ever land in esc()'d attribute values and never inside a script
+// body, which is what an inline onerror would have made them.
function proxyImgAttrs(rawUrl, seed) {
const s = String(seed || 'coin');
const placeholder = `/api/img?${new URLSearchParams({ seed: s })}`;
@@ -72,7 +72,7 @@ function proxyImgAttrs(rawUrl, seed) {
const src = rawUrl && /^(https?|ipfs|ar):\/\//i.test(String(rawUrl))
? proxiedImageURL(String(rawUrl), s)
: placeholder;
- return `src="${esc(src)}" data-ph="${esc(placeholder)}" onerror="this.onerror=null;this.src=this.dataset.ph"`;
+ return `src="${esc(src)}" data-fallback-src="${esc(placeholder)}" data-fallback="keep"`;
}
const shortAddr = (a) => (a && a.length > 10 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || '');
const fmtSol = (n) => (n == null ? '—' : `${Number(n) < 0.01 && Number(n) > 0 ? Number(n).toFixed(4) : Number(n).toFixed(2)}◎`);
@@ -1608,9 +1608,9 @@ function winCardHtml(w, idx) {
<span class="win-when">${esc(when)}</span>
</div>
<div class="win-links">
- <a class="win-link" href="${esc(w.pump_url)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">pump.fun ↗</a>
- <a class="win-link" href="${esc(w.oracle_url)}" onclick="event.stopPropagation()">Oracle ↗</a>
- <a class="win-link" style="margin-left:auto;color:var(--muted)" href="${esc(winTweet(w))}" target="_blank" rel="noopener" onclick="event.stopPropagation()" title="Share on X">Share ↗</a>
+ <a class="win-link" href="${esc(w.pump_url)}" target="_blank" rel="noopener" data-stop-propagation>pump.fun ↗</a>
+ <a class="win-link" href="${esc(w.oracle_url)}" data-stop-propagation>Oracle ↗</a>
+ <a class="win-link" style="margin-left:auto;color:var(--muted)" href="${esc(winTweet(w))}" target="_blank" rel="noopener" data-stop-propagation title="Share on X">Share ↗</a>
</div>
</div>
</a>`;
@@ -1903,8 +1903,7 @@ async function loadRelatedCoins(mint, category) {
? `<img ${proxyImgAttrs(r.image_uri, r.mint)} alt="" style="width:28px;height:28px;border-radius:7px;object-fit:cover;flex:none;border:1px solid var(--line)" loading="lazy">`
: `<div style="width:28px;height:28px;border-radius:7px;background:var(--line);display:grid;place-items:center;font:700 11px/1 var(--mono);color:var(--faint);flex:none">${esc((r.symbol||'?')[0])}</div>`;
return `<button type="button" class="dr-related" data-related-mint="${esc(r.mint)}"
- style="display:flex;align-items:center;gap:10px;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:8px 10px;cursor:pointer;text-align:left;width:100%;transition:background .12s"
- onmouseover="this.style.background='rgba(255,255,255,0.05)'" onmouseout="this.style.background='var(--panel)'">
+ style="display:flex;align-items:center;gap:10px;border:1px solid var(--line);border-radius:8px;padding:8px 10px;cursor:pointer;text-align:left;width:100%">
${imgEl}
<span style="flex:1;min-width:0">
<span style="font-weight:700;font-size:13px;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(r.symbol || r.mint.slice(0,8))}</span>
diff --git a/src/play/arena.js b/src/play/arena.js
index c4bfadb26..5573c9c5a 100644
--- a/src/play/arena.js
+++ b/src/play/arena.js
@@ -368,7 +368,7 @@ function createLabel(agent) {
el.type = 'button';
el.innerHTML = `
<span class="lbl-rank">#${agent.label.rank ?? '?'}</span>
- ${agent.label.thumbnail ? `<img loading="lazy" decoding="async" class="lbl-av" src="${esc(agent.label.thumbnail)}" alt="" onerror="this.remove()"/>` : ''}
+ ${agent.label.thumbnail ? `<img loading="lazy" decoding="async" class="lbl-av" src="${esc(agent.label.thumbnail)}" alt="" data-fallback="remove"/>` : ''}
<span class="lbl-meta">
<span class="lbl-name">${esc(agent.label.name)}</span>
<span class="lbl-pnl ${agent.label.pnlUp ? 'up' : 'down'}">${esc(agent.label.pnlText)}</span>
@@ -687,7 +687,7 @@ function renderAgentDrawer(data, id) {
$('drawerBody').innerHTML = `
<div class="dw-head">
- ${a.image ? `<img loading="lazy" decoding="async" src="${esc(a.image)}" alt="" onerror="this.remove()"/>` : '<span class="dw-av-fallback"></span>'}
+ ${a.image ? `<img loading="lazy" decoding="async" src="${esc(a.image)}" alt="" data-fallback="remove"/>` : '<span class="dw-av-fallback"></span>'}
<div>
<div class="dw-name">${esc(a.name || 'Agent')}</div>
<div class="dw-sub">${verified}</div>
@@ -753,14 +753,14 @@ function renderBoard(rows) {
const initial = esc((name.trim()[0] || '?').toUpperCase());
// On a broken avatar, swap the <img> for a mono-initial tile that fills the
// same 26px column — no orphaned gap in the grid.
- const onerr = `this.outerHTML='<span class=&quot;r-av r-av-fb&quot;>${initial}</span>'`;
+ const avatarFallback = `data-fallback="element" data-fallback-tag="span" data-fallback-class="r-av r-av-fb" data-fallback-text="${initial}"`;
const sub = r.kind === 'live'
? `${r.trades != null ? Number(r.trades).toLocaleString('en-US') + ' trades' : 'live'}${r.win_pct != null ? ' · ' + Math.round(r.win_pct) + '% win' : ''}`
: `${r.open} open · ${r.closed ? Math.round(r.win_pct) + '% win' : 'new'}`;
// Live wallets have no avatar — use the mono-initial tile directly.
const av = r.kind === 'live'
? `<span class="r-av r-av-fb">${initial}</span>`
- : `<img loading="lazy" decoding="async" class="r-av" src="${esc(r.image || '/avatars/thumbs/default.png')}" alt="" onerror="${onerr}"/>`;
+ : `<img loading="lazy" decoding="async" class="r-av" src="${esc(r.image || '/avatars/thumbs/default.png')}" alt="" ${avatarFallback}/>`;
return `<button class="row no-orbit" data-id="${esc(r.id)}">
<span class="r-rank">${r.rank}</span>
${av}
@@ -993,7 +993,7 @@ async function renderPicker() {
function tile(saved) {
return (a) => `
<button class="pick-tile no-orbit ${a.url === saved ? 'selected' : ''}" data-url="${esc(a.url)}" title="${esc(a.name)}">
- <span class="pick-thumb">${a.thumb ? `<img src="${esc(a.thumb)}" alt="" loading="lazy" onerror="this.remove()"/>` : `<span class="pick-mono">${esc((a.name || '?').slice(0, 2).toUpperCase())}</span>`}</span>
+ <span class="pick-thumb">${a.thumb ? `<img src="${esc(a.thumb)}" alt="" loading="lazy" data-fallback="remove"/>` : `<span class="pick-mono">${esc((a.name || '?').slice(0, 2).toUpperCase())}</span>`}</span>
<span class="pick-name">${esc(a.name)}</span>
${a.starter ? '<span class="pick-badge">starter</span>' : ''}
</button>`;
diff --git a/src/pulse.js b/src/pulse.js
index bd8f2187c..ab7ec1534 100644
--- a/src/pulse.js
+++ b/src/pulse.js
@@ -194,7 +194,7 @@ function renderLaunches(list) {
.map((c) => {
const a = c.agent || {};
const av = a.avatar_thumbnail_url
- ? `<img class="px-lb-av" src="${esc(a.avatar_thumbnail_url)}" alt="" loading="lazy" onerror="this.style.visibility='hidden'" />`
+ ? `<img class="px-lb-av" src="${esc(a.avatar_thumbnail_url)}" alt="" loading="lazy" data-fallback="invisible" />`
: `<span class="px-lb-av px-lb-av--mono" aria-hidden="true">${esc((c.symbol || c.coin_name || '?').charAt(0).toUpperCase())}</span>`;
const title = c.symbol ? `$${esc(c.symbol)}` : esc(c.coin_name || 'Coin');
return (
diff --git a/src/pump/launch-token-modal.js b/src/pump/launch-token-modal.js
index 0babeec4d..9a6bfe6e1 100644
--- a/src/pump/launch-token-modal.js
+++ b/src/pump/launch-token-modal.js
@@ -412,7 +412,7 @@ export class LaunchTokenModal {
const d = this._d;
const initials = (d.symbol || d.name || 'A').slice(0, 3).toUpperCase();
const img = d.image
- ? `<img loading="lazy" decoding="async" class="ltm-pc-img" src="${_esc(d.image)}" alt="" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
+ ? `<img loading="lazy" decoding="async" class="ltm-pc-img" src="${_esc(d.image)}" alt="" data-fallback="sibling">
<div class="ltm-pc-fallback" style="display:none">${_esc(initials)}</div>`
: `<div class="ltm-pc-fallback">${_esc(initials)}</div>`;
return `
@@ -442,7 +442,7 @@ export class LaunchTokenModal {
if (media) {
const initials = (symbol || name || 'A').slice(0, 3).toUpperCase();
media.innerHTML = image
- ? `<img loading="lazy" decoding="async" class="ltm-pc-img" src="${_esc(image)}" alt="" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
+ ? `<img loading="lazy" decoding="async" class="ltm-pc-img" src="${_esc(image)}" alt="" data-fallback="sibling">
<div class="ltm-pc-fallback" style="display:none">${_esc(initials)}</div>`
: `<div class="ltm-pc-fallback">${_esc(initials)}</div>`;
}
diff --git a/src/reputation-ui.js b/src/reputation-ui.js
index 273b3e9c5..cfc6b37c4 100644
--- a/src/reputation-ui.js
+++ b/src/reputation-ui.js
@@ -263,7 +263,7 @@ export class ReputationDashboard {
<div class="rep-error">
<h3>Unable to load reputation</h3>
<p>${this._escapeHtml(errorMsg)}</p>
- <button onclick="location.reload()">Retry</button>
+ <button data-action="reload">Retry</button>
</div>
`;
}
diff --git a/src/shared/agent-money-stream.js b/src/shared/agent-money-stream.js
index a6296ca72..4e8fc0aaf 100644
--- a/src/shared/agent-money-stream.js
+++ b/src/shared/agent-money-stream.js
@@ -1133,7 +1133,7 @@ export function openStreamPanel(agent, opts = {}) {
shell.className = 'tms';
shell.innerHTML = `
<div class="tms-hd">
- ${avatar ? `<img loading="lazy" decoding="async" class="tms-av" src="${esc(avatar)}" alt="" onerror="this.remove()"/>` : '<div class="tms-av"></div>'}
+ ${avatar ? `<img loading="lazy" decoding="async" class="tms-av" src="${esc(avatar)}" alt="" data-fallback="remove"/>` : '<div class="tms-av"></div>'}
<div class="tms-hd-txt">
<div class="tms-hd-k">${mode === 'earnings' ? '◎ Stream earnings' : '◎ Money Stream'}</div>
<div class="tms-hd-n" title="${esc(name)}">${esc(name)}</div>
diff --git a/src/shared/agent-tip-modal.js b/src/shared/agent-tip-modal.js
index 3f0bb68a1..1881c58a6 100644
--- a/src/shared/agent-tip-modal.js
+++ b/src/shared/agent-tip-modal.js
@@ -186,7 +186,7 @@ export function openTipModal(agent, opts = {}) {
backdrop.innerHTML = `
<div class="ttm">
<div class="ttm-hd">
- ${avatar ? `<img loading="lazy" decoding="async" class="ttm-av" src="${esc(avatar)}" alt="" onerror="this.remove()"/>` : '<div class="ttm-av"></div>'}
+ ${avatar ? `<img loading="lazy" decoding="async" class="ttm-av" src="${esc(avatar)}" alt="" data-fallback="remove"/>` : '<div class="ttm-av"></div>'}
<div class="ttm-hd-txt">
<div class="ttm-hd-k">${esc(accepted.length ? 'Pay' : 'Tip')}</div>
<div class="ttm-hd-n" title="${esc(name)}">${esc(name)}</div>
@@ -221,7 +221,7 @@ export function openTipModal(agent, opts = {}) {
backdrop.innerHTML = `
<div class="ttm">
<div class="ttm-hd">
- ${avatar ? `<img loading="lazy" decoding="async" class="ttm-av" src="${esc(avatar)}" alt="" onerror="this.remove()"/>` : '<div class="ttm-av"></div>'}
+ ${avatar ? `<img loading="lazy" decoding="async" class="ttm-av" src="${esc(avatar)}" alt="" data-fallback="remove"/>` : '<div class="ttm-av"></div>'}
<div class="ttm-hd-txt">
<div class="ttm-hd-k">Sent</div>
<div class="ttm-hd-n" title="${esc(name)}">${esc(name)}</div>
diff --git a/src/shared/collab-graph.js b/src/shared/collab-graph.js
index 5459dcb1e..aa9117b2d 100644
--- a/src/shared/collab-graph.js
+++ b/src/shared/collab-graph.js
@@ -238,7 +238,7 @@ export function createCollabGraph(host, opts = {}) {
: '';
const receipt =
url && sig
- ? `<a class="cg-receipt" href="${esc(url)}" target="_blank" rel="noopener" title="On-chain invocation receipt" onclick="event.stopPropagation()">⛓ ${esc(String(sig).slice(0, 6))}…</a>`
+ ? `<a class="cg-receipt" href="${esc(url)}" target="_blank" rel="noopener" title="On-chain invocation receipt" data-stop-propagation>⛓ ${esc(String(sig).slice(0, 6))}…</a>`
: '';
const errBadge =
node.status === 'failed' && node.error
diff --git a/src/shared/pulse-format.js b/src/shared/pulse-format.js
index d2c67d624..d83c7f0e5 100644
--- a/src/shared/pulse-format.js
+++ b/src/shared/pulse-format.js
@@ -70,7 +70,7 @@ export function timeAgo(iso) {
// optional wallet chip, and a caller-supplied metric on the right.
export function agentCardHTML(a, metricHTML) {
const av = a.avatar_thumbnail_url
- ? `<img class="px-lb-av" src="${esc(a.avatar_thumbnail_url)}" alt="" loading="lazy" onerror="this.style.visibility='hidden'" />`
+ ? `<img class="px-lb-av" src="${esc(a.avatar_thumbnail_url)}" alt="" loading="lazy" data-fallback="invisible" />`
: `<span class="px-lb-av px-lb-av--mono" aria-hidden="true">${esc((a.name || '?').charAt(0).toUpperCase())}</span>`;
const chip = a.solana_address
? walletChipHTML({ name: a.name, meta: { solana_address: a.solana_address } }, { link: false, tip: false, showPending: false, balance: false, popover: false })
diff --git a/src/shared/share.js b/src/shared/share.js
index 56a563f34..0da4a4546 100644
--- a/src/shared/share.js
+++ b/src/shared/share.js
@@ -49,7 +49,7 @@ export function showSharePanel(entity, triggerEl = null) {
const previewHtml = previewImage
? `<div class="tws-sp-preview">
<img src="${esc(previewImage)}" alt="${esc(title)} card preview" loading="lazy" decoding="async"
- onerror="this.closest('.tws-sp-preview')?.remove()" />
+ data-fallback="closest" data-fallback-closest=".tws-sp-preview" />
</div>`
: '';
diff --git a/src/trader.js b/src/trader.js
index 2f54c2d61..4157f12ab 100644
--- a/src/trader.js
+++ b/src/trader.js
@@ -190,7 +190,7 @@ function oracleBlock(oracle) {
<span class="tp-oracle-label">Oracle conviction</span>
<div class="tp-oracle-actions">
<a class="tp-oracle-link" href="/oracle" target="_blank" rel="noopener">View live ↗</a>
- <a class="lb-btn lb-btn-primary tp-oracle-cta" href="#tp-copy-panel" onclick="document.getElementById('tp-copy-panel')?.scrollIntoView({behavior:'smooth',block:'start'});return false">Copy trades →</a>
+ <a class="lb-btn lb-btn-primary tp-oracle-cta" href="#tp-copy-panel">Copy trades →</a>
</div>
</div>
<div class="tp-oracle-kpis">
@@ -325,7 +325,7 @@ function render(data) {
content.innerHTML = `
<section class="tp-hero">
<div class="tp-avatar-wrap">
- <img loading="lazy" decoding="async" class="tp-avatar" src="${escapeHtml(img)}" alt="" onerror="this.src='${identicon(a.id || '?')}'" />
+ <img loading="lazy" decoding="async" class="tp-avatar" src="${escapeHtml(img)}" alt="" data-fallback-src="${identicon(a.id || '?')}" />
</div>
<div class="tp-id">
<div class="tp-name">${escapeHtml(a.name || 'Unnamed agent')}${verifiedBadge(m.verified)}</div>
diff --git a/src/trades-detail.js b/src/trades-detail.js
index a02095433..6b5aa05f3 100644
--- a/src/trades-detail.js
+++ b/src/trades-detail.js
@@ -456,7 +456,7 @@ export function mountDetail(host, opts = {}) {
</div>` : '';
body.innerHTML = `
${agent ? `<div class="dd-agent-row">
- <img src="${escapeHtml(av)}" alt="" class="dd-agent-av" loading="lazy" decoding="async" onerror="this.style.visibility='hidden'" />
+ <img src="${escapeHtml(av)}" alt="" class="dd-agent-av" loading="lazy" decoding="async" data-fallback="invisible" />
<div class="dd-agent-id">
<a href="${escapeHtml(agent.url || `/agents/${agent.id}`)}" class="dd-agent-name">${escapeHtml(agent.name || 'three.ws agent')}</a>
${agent.description ? `<p class="dd-agent-desc">${escapeHtml(agent.description)}</p>` : ''}
@@ -503,7 +503,7 @@ function shell({ mint, network, sym, name, img, isThree }) {
<div class="dd-scroll">
<header class="dd-hero">
<div class="dd-hero-img">
- ${img ? `<img src="${escapeHtml(img)}" alt="" loading="lazy" decoding="async" onerror="this.parentNode.classList.add('dd-noimg');this.remove()" />` : ''}
+ ${img ? `<img src="${escapeHtml(img)}" alt="" loading="lazy" decoding="async" data-fallback="remove" data-fallback-parent-class="dd-noimg" />` : ''}
<span class="dd-hero-ini">${escapeHtml(initials)}</span>
</div>
<div class="dd-hero-main">
diff --git a/src/trades.js b/src/trades.js
index 0ac229c8a..84b75487e 100644
--- a/src/trades.js
+++ b/src/trades.js
@@ -239,7 +239,7 @@ function rowHtml(r, { pinned = false } = {}) {
const seed = escapeHtml(JSON.stringify({ symbol: r.symbol, name: r.name, image_uri: r.image_uri }));
const initials = escapeHtml(r.symbol.slice(0, 2));
const imgHtml = r.image_uri
- ? `<img src="${escapeHtml(r.image_uri)}" alt="" class="tt-row-img" loading="lazy" onerror="this.outerHTML='<span class=tt-row-ini>${initials}</span>'" />`
+ ? `<img src="${escapeHtml(r.image_uri)}" alt="" class="tt-row-img" loading="lazy" data-fallback="element" data-fallback-tag="span" data-fallback-class="tt-row-ini" data-fallback-text="${initials}" />`
: `<span class="tt-row-ini">${initials}</span>`;
const tier = r.oracle_tier && r.oracle_tier !== 'avoid'
? `<span class="tt-tier ${TIER_CLASS[r.oracle_tier] || ''}">${escapeHtml(r.oracle_tier)}</span>` : '';
diff --git a/src/walk.js b/src/walk.js
index 0cc20ca25..c0837ae18 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -5108,7 +5108,7 @@ if (import.meta.env?.DEV) {
].join(';');
const imgHtml = COIN_PARAMS.image
- ? `<img loading="lazy" decoding="async" src="${escAttr(COIN_PARAMS.image)}" alt="" referrerpolicy="no-referrer" onerror="this.replaceWith(Object.assign(document.createElement('span'),{textContent:'${escAttr(initials(COIN_PARAMS.symbol, COIN_PARAMS.name))}',className:'coin-fallback'}))" style="width:34px;height:34px;border-radius:50%;object-fit:cover;border:1px solid ${accent.css};flex:0 0 34px;background:#0e0e16" />`
+ ? `<img loading="lazy" decoding="async" src="${escAttr(COIN_PARAMS.image)}" alt="" referrerpolicy="no-referrer" data-fallback="element" data-fallback-tag="span" data-fallback-class="coin-fallback" data-fallback-text="${escAttr(initials(COIN_PARAMS.symbol, COIN_PARAMS.name))}" style="width:34px;height:34px;border-radius:50%;object-fit:cover;border:1px solid ${accent.css};flex:0 0 34px;background:#0e0e16" />`
: `<span class="coin-fallback">${esc(initials(COIN_PARAMS.symbol, COIN_PARAMS.name))}</span>`;
const title = COIN_PARAMS.symbol ? `$${esc(COIN_PARAMS.symbol)}` : 'Coin';
diff --git a/src/widgets/pumpfun-feed.js b/src/widgets/pumpfun-feed.js
index 08b21e5f5..567cb3b4f 100644
--- a/src/widgets/pumpfun-feed.js
+++ b/src/widgets/pumpfun-feed.js
@@ -481,7 +481,7 @@ function renderGraduation(ev) {
? `<span style="position:absolute;top:8px;right:10px;font-size:9px;letter-spacing:.08em;text-transform:uppercase;color:#6a6a82;padding:1px 6px;border:1px solid #2a2a3c;border-radius:999px;background:#0e0e16">replay</span>`
: '';
const thumb = ev.image_uri
- ? `<img src="${attrEsc(ev.image_uri)}" alt="" loading="lazy" referrerpolicy="no-referrer" onerror="this.style.display='none'" style="width:40px;height:40px;border-radius:6px;object-fit:cover;border:1px solid #2a2a3c;background:#0e0e16;flex:0 0 40px" />`
+ ? `<img src="${attrEsc(ev.image_uri)}" alt="" loading="lazy" referrerpolicy="no-referrer" data-fallback="hide" style="width:40px;height:40px;border-radius:6px;object-fit:cover;border:1px solid #2a2a3c;background:#0e0e16;flex:0 0 40px" />`
: '';
el.innerHTML = `
diff --git a/tests/csp-hashes.test.js b/tests/csp-hashes.test.js
new file mode 100644
index 000000000..2c1984634
--- /dev/null
+++ b/tests/csp-hashes.test.js
@@ -0,0 +1,226 @@
+// The CSP inline-script hasher is the only thing standing between a strict
+// `script-src` and 1,000+ blank pages: if it misses one inline script, that
+// page's JavaScript stops running in production. These tests pin the parser
+// edge cases that a naive regex gets wrong, and the shape of the rewritten
+// policy.
+
+import { describe, it, expect } from 'vitest';
+import { createHash } from 'node:crypto';
+import {
+ inlineScriptBodies,
+ inlineScriptHashes,
+ hardenInlineScripts,
+ hardenHeaderBag,
+} from '../server/csp-hashes.mjs';
+
+const sha = (s) => `'sha256-${createHash('sha256').update(s, 'utf8').digest('base64')}'`;
+
+const POLICY =
+ "base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://esm.sh; worker-src 'self' blob:; frame-ancestors 'self'";
+
+describe('inlineScriptBodies', () => {
+ it('captures the body of a plain inline script', () => {
+ expect(inlineScriptBodies('<script>alert(1)</script>')).toEqual(['alert(1)']);
+ });
+
+ it('skips scripts loaded from a src (covered by the host allowlist)', () => {
+ const html = '<script src="/nav.js" defer></script><script>go()</script>';
+ expect(inlineScriptBodies(html)).toEqual(['go()']);
+ });
+
+ it('does not confuse a data-src attribute with src', () => {
+ expect(inlineScriptBodies('<script data-src="x">run()</script>')).toEqual(['run()']);
+ });
+
+ it('handles a `>` inside a quoted attribute value', () => {
+ const html = `<script type="module" data-note="a > b">body()</script>`;
+ expect(inlineScriptBodies(html)).toEqual(['body()']);
+ });
+
+ it('handles a `</script` written inside a string, the way the parser does', () => {
+ // The HTML parser ends the element at the first `</script`, so the hash
+ // must cover only the text up to that point.
+ const html = '<script>var s = "</script>";</script>';
+ expect(inlineScriptBodies(html)).toEqual(['var s = "']);
+ });
+
+ it('is case-insensitive on the tag name', () => {
+ expect(inlineScriptBodies('<SCRIPT>a()</SCRIPT>')).toEqual(['a()']);
+ });
+
+ it('tolerates whitespace before the closing bracket', () => {
+ expect(inlineScriptBodies('<script>a()</script >')).toEqual(['a()']);
+ });
+
+ it('ignores an element whose name merely starts with "script"', () => {
+ expect(inlineScriptBodies('<scripty>a()</scripty>')).toEqual([]);
+ });
+
+ it('covers JSON-LD blocks, which script-src also gates', () => {
+ const html = '<script type="application/ld+json">{"@type":"WebPage"}</script>';
+ expect(inlineScriptBodies(html)).toEqual(['{"@type":"WebPage"}']);
+ });
+
+ it('returns every script on a page, in document order', () => {
+ const html = '<script>one</script><p>x</p><script type="module">two</script>';
+ expect(inlineScriptBodies(html)).toEqual(['one', 'two']);
+ });
+
+ it('treats an unterminated script as running to the end of the document', () => {
+ expect(inlineScriptBodies('<p>x</p><script>tail')).toEqual(['tail']);
+ });
+
+ it('returns nothing for HTML with no inline scripts', () => {
+ expect(inlineScriptBodies('<p>hello</p><script src="/a.js"></script>')).toEqual([]);
+ });
+
+ // The bug this class of test exists for: a CSS comment on /oracle mentioning
+ // `<script>` started a phantom element that ran to the next real `</script>`,
+ // which swallowed the analytics snippet's opening tag. Its hash never reached
+ // the header and the browser blocked it.
+ it('ignores a <script> written inside a <style> block', () => {
+ const html = '<style>/* see <script> docs */ .a { color: red }</style><script>real()</script>';
+ expect(inlineScriptBodies(html)).toEqual(['real()']);
+ });
+
+ it('ignores a <script> written inside a <textarea>', () => {
+ const html = '<textarea><script>fake()</script></textarea><script>real()</script>';
+ expect(inlineScriptBodies(html)).toEqual(['real()']);
+ });
+
+ it('ignores a <script> written inside a <title>', () => {
+ const html = '<title>How <script> tags work</title><script>real()</script>';
+ expect(inlineScriptBodies(html)).toEqual(['real()']);
+ });
+
+ it('ignores a <script> inside an HTML comment', () => {
+ const html = '<!-- <script>fake()</script> --><script>real()</script>';
+ expect(inlineScriptBodies(html)).toEqual(['real()']);
+ });
+
+ it('does not treat <styles> or <titlebar> as raw-text elements', () => {
+ const html = '<styles><script>real()</script></styles>';
+ expect(inlineScriptBodies(html)).toEqual(['real()']);
+ });
+
+ it('keeps scanning after an unterminated raw-text element', () => {
+ // A stray <style> with no close swallows the rest of the document for a
+ // real parser too, so finding nothing after it is the correct answer.
+ expect(inlineScriptBodies('<style>.a{}<script>x()</script>')).toEqual([]);
+ });
+
+ it('finds every script on a page that mixes all of these', () => {
+ const html = [
+ '<title>A <script> primer</title>',
+ '<style>/* <script> */ .a{}</style>',
+ '<!-- <script>no()</script> -->',
+ '<script>one()</script>',
+ '<textarea><script>no()</script></textarea>',
+ '<script type="application/ld+json">{"a":1}</script>',
+ ].join('\n');
+ expect(inlineScriptBodies(html)).toEqual(['one()', '{"a":1}']);
+ });
+});
+
+describe('inlineScriptHashes', () => {
+ it('produces the sha256 of the exact body text', () => {
+ expect(inlineScriptHashes('<script>alert(1)</script>')).toEqual([sha('alert(1)')]);
+ });
+
+ it('preserves surrounding whitespace, which the browser hashes too', () => {
+ const body = '\n\t\tconst a = 1;\n\t';
+ expect(inlineScriptHashes(`<script>${body}</script>`)).toEqual([sha(body)]);
+ });
+
+ it('hashes multi-byte content as UTF-8', () => {
+ const body = 'const label = "价格 · €";';
+ expect(inlineScriptHashes(`<script>${body}</script>`)).toEqual([sha(body)]);
+ });
+
+ it('deduplicates identical scripts', () => {
+ const html = '<script>same()</script><script>same()</script>';
+ expect(inlineScriptHashes(html)).toEqual([sha('same()')]);
+ });
+});
+
+describe('hardenInlineScripts', () => {
+ it("replaces 'unsafe-inline' in script-src with the page's hashes", () => {
+ const out = hardenInlineScripts(POLICY, '<script>alert(1)</script>');
+ const scriptSrc = out.split(';').find((d) => d.trim().startsWith('script-src'));
+ expect(scriptSrc).not.toContain("'unsafe-inline'");
+ expect(scriptSrc).toContain(sha('alert(1)'));
+ });
+
+ it('keeps every other source in the directive', () => {
+ const out = hardenInlineScripts(POLICY, '<script>a()</script>');
+ const scriptSrc = out.split(';').find((d) => d.trim().startsWith('script-src'));
+ expect(scriptSrc).toContain("'self'");
+ expect(scriptSrc).toContain("'unsafe-eval'");
+ expect(scriptSrc).toContain('blob:');
+ expect(scriptSrc).toContain('https://esm.sh');
+ });
+
+ it('leaves the other directives untouched', () => {
+ const out = hardenInlineScripts(POLICY, '<script>a()</script>');
+ expect(out).toContain("object-src 'none'");
+ expect(out).toContain("frame-ancestors 'self'");
+ expect(out).toContain("worker-src 'self' blob:");
+ });
+
+ it("drops 'unsafe-inline' entirely on a page with no inline scripts", () => {
+ const out = hardenInlineScripts(POLICY, '<p>static</p>');
+ const scriptSrc = out.split(';').find((d) => d.trim().startsWith('script-src'));
+ expect(scriptSrc).not.toContain("'unsafe-inline'");
+ expect(scriptSrc).not.toContain('sha256-');
+ expect(scriptSrc).toContain("'self'");
+ });
+
+ it('is a no-op on a policy that never allowed inline script', () => {
+ const strict = "default-src 'self'; script-src 'self'";
+ expect(hardenInlineScripts(strict, '<script>a()</script>')).toBe(strict);
+ });
+
+ it('is a no-op on a policy with no script directive at all', () => {
+ const frameOnly = "frame-ancestors *; base-uri 'self'; object-src 'none'";
+ expect(hardenInlineScripts(frameOnly, '<script>a()</script>')).toBe(frameOnly);
+ });
+
+ it('does not accumulate hashes when applied twice', () => {
+ const once = hardenInlineScripts(POLICY, '<script>a()</script>');
+ expect(hardenInlineScripts(once, '<script>b()</script>')).toBe(once);
+ });
+
+ it('also hardens script-src-elem when a policy uses it', () => {
+ const policy = "script-src 'self' 'unsafe-inline'; script-src-elem 'self' 'unsafe-inline'";
+ const out = hardenInlineScripts(policy, '<script>a()</script>');
+ expect(out).not.toContain("'unsafe-inline'");
+ expect(out.match(/sha256-/g)).toHaveLength(2);
+ });
+
+ it('tolerates a non-string policy', () => {
+ expect(hardenInlineScripts(undefined, '<script>a()</script>')).toBe(undefined);
+ });
+});
+
+describe('hardenHeaderBag', () => {
+ it('rewrites the lowercase header key the route table uses', () => {
+ const bag = { 'content-security-policy': POLICY, 'x-frame-options': 'SAMEORIGIN' };
+ hardenHeaderBag(bag, '<script>a()</script>');
+ expect(bag['content-security-policy']).toContain(sha('a()'));
+ expect(bag['content-security-policy']).not.toContain("'unsafe-inline'");
+ expect(bag['x-frame-options']).toBe('SAMEORIGIN');
+ });
+
+ it('rewrites the canonical casing too', () => {
+ const bag = { 'Content-Security-Policy': POLICY };
+ hardenHeaderBag(bag, '<script>a()</script>');
+ expect(bag['Content-Security-Policy']).toContain(sha('a()'));
+ });
+
+ it('is a no-op on a bag with no policy', () => {
+ const bag = { 'cache-control': 'public, max-age=60' };
+ expect(hardenHeaderBag(bag, '<script>a()</script>')).toEqual({
+ 'cache-control': 'public, max-age=60',
+ });
+ });
+});
diff --git a/vite.config.js b/vite.config.js
index d9482dcfc..b133d0250 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -2100,6 +2100,28 @@ support: resolve(__dirname, 'pages/support.html'),
},
},
},
+ {
+ // public/inline-behaviors.js turns data-fallback*, data-action and
+ // data-stop-propagation attributes into behaviour, replacing the inline
+ // handler attributes the CSP blocks. It has to be everywhere: a page
+ // that renders a card grid from a template literal carries no hint that
+ // it needs it, and the failure only shows in front of a visitor.
+ // scripts/inject-inline-behaviors.mjs re-walks dist/ after the build and
+ // asserts coverage, for the same plugin-ordering reason documented above.
+ name: 'three-ws-inline-behaviors',
+ transformIndexHtml: {
+ order: 'pre',
+ handler(_html, ctx) {
+ const FRAGMENTS = new Set(['nav.html', 'footer.html']);
+ const filename = (ctx.filename || ctx.path || '')
+ .replace(/\\/g, '/')
+ .split('/')
+ .pop();
+ if (FRAGMENTS.has(filename)) return [];
+ return [{ tag: 'script', attrs: { src: '/inline-behaviors.js', defer: true }, injectTo: 'head' }];
+ },
+ },
+ },
{
// Mobile ergonomics: /mobile.css on every page, and viewport-fit=cover.
//