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.

chore(audits): print the warning text and prove guards against real sources

nirholas972d18d4a6b9
diff --git a/scripts/audit-cron-liveness.mjs b/scripts/audit-cron-liveness.mjs
index e606c9e6b..7f47c13d7 100644
--- a/scripts/audit-cron-liveness.mjs
+++ b/scripts/audit-cron-liveness.mjs
@@ -547,11 +547,19 @@ if (AS_JSON) {
for (const d of drift.duplicates || []) console.log(` duplicate job id ${d.id}`);
}
if (WITH_DRIFT && drift?.checkedLive) {
- console.log('\nCloud Scheduler drift:');
- for (const m of drift.missing || []) console.log(` MISSING ${m.path}`);
- for (const m of drift.mismatched || []) console.log(` MISMATCH ${m.path} declared "${m.declared}" live "${m.live}"`);
- for (const p of drift.paused || []) console.log(` NOT ENABLED ${p.path} ${p.state}`);
- for (const o of drift.orphaned || []) console.log(` ORPHANED ${o.id}`);
+ // A bare "Cloud Scheduler drift:" header over nothing reads as truncated
+ // output, which is the one thing a clean comparison must never look like.
+ const driftRows = [
+ ...(drift.missing || []).map((m) => ` MISSING ${m.path}`),
+ ...(drift.mismatched || []).map((m) => ` MISMATCH ${m.path} declared "${m.declared}" live "${m.live}"`),
+ ...(drift.paused || []).map((p) => ` NOT ENABLED ${p.path} ${p.state}`),
+ ...(drift.orphaned || []).map((o) => ` ORPHANED ${o.id}`),
+ ];
+ console.log(
+ driftRows.length
+ ? `\nCloud Scheduler drift:\n${driftRows.join('\n')}`
+ : '\nCloud Scheduler drift: none (every declared cron exists, is enabled, and matches its live schedule).',
+ );
} else if (WITH_DRIFT && drift?.liveError) {
console.log(`\nCloud Scheduler not readable: ${drift.liveError}`);
}
diff --git a/scripts/audit-csp.mjs b/scripts/audit-csp.mjs
index 82b22b0a4..a27af70b8 100644
--- a/scripts/audit-csp.mjs
+++ b/scripts/audit-csp.mjs
@@ -12,10 +12,30 @@
// URL. A violation is a hard failure; a page error is reported so a broken
// refactor cannot hide behind a green CSP.
//
+// A violation-free run only means something if the page actually loaded AND the
+// response actually carried the policy. Both halves are checked here, because
+// each has produced a green run over nothing:
+//
+// - A 404 has no inline scripts, so it can never fire a violation. A sweep
+// that counts 4xx as clean reports success loudest exactly when `dist/` is
+// missing, which is the moment it should be screaming.
+// - A response with no CSP header cannot be violated either. On 2026-08-11
+// the default origin (port 8099) was held by an unrelated uvicorn server;
+// the sweep walked 25 URLs on it and printed "clean across 25 page(s)".
+// Nothing about three.ws was tested.
+//
+// So every page's own response headers are compared against what vercel.json
+// declares for that path, using the server's own resolver (`resolvePhase1`)
+// rather than a second copy of the rules. `server/csp-hashes.mjs` rewrites
+// script-src per response, so that one directive is compared modulo the
+// documented transform (drop 'unsafe-inline', add 'sha256-…'); every other
+// directive and every other security header must match the route table exactly.
+//
// 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 --base https://three.ws # audit production
// node scripts/audit-csp.mjs --all # every page in data/pages.json
// node scripts/audit-csp.mjs /pay /studio # only these paths
@@ -23,6 +43,7 @@ import { readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
+import { loadRouteTable, resolvePhase1 } from '../server/route-resolve.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -80,6 +101,111 @@ const paths = explicit.length ? explicit : wantAll ? allCataloguedPaths() : DEFA
// 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 { phase1Routes } = loadRouteTable(path.join(ROOT, 'vercel.json'));
+
+// The security headers vercel.json is expected to put on a document. Anything
+// the route table declares for a path is checked; this list is what makes a
+// MISSING declaration visible too, so deleting the global header rule fails
+// here instead of shipping a bare-headed site.
+const REQUIRED_ON_HTML = [
+ 'content-security-policy',
+ 'strict-transport-security',
+ 'x-content-type-options',
+ 'referrer-policy',
+];
+
+/** The header bag vercel.json declares for `pathname`, per the server's resolver. */
+function declaredHeaders(pathname, base) {
+ const url = new URL(pathname, base);
+ const req = { headers: { host: url.host } };
+ const bag = {};
+ for (const [k, v] of Object.entries(resolvePhase1(phase1Routes, req, url).headers)) {
+ bag[k.toLowerCase()] = v;
+ }
+ return bag;
+}
+
+/** "a 'b' c; d 'e'" -> Map{ a => Set{'b','c'}, d => Set{'e'} } */
+function parsePolicy(value) {
+ const directives = new Map();
+ for (const chunk of String(value).split(';')) {
+ const parts = chunk.trim().split(/\s+/).filter(Boolean);
+ if (!parts.length) continue;
+ directives.set(parts[0].toLowerCase(), new Set(parts.slice(1)));
+ }
+ return directives;
+}
+
+const setsEqual = (a, b) => a.size === b.size && [...a].every((v) => b.has(v));
+
+/**
+ * Differences between the policy the route table declares and the one the
+ * response carried, allowing only the rewrite server/csp-hashes.mjs performs:
+ * within script-src / script-src-elem, `'unsafe-inline'` is replaced by any
+ * number of `'sha256-…'` sources. Everything else must survive byte-for-byte.
+ */
+function policyDiff(declared, served) {
+ const want = parsePolicy(declared);
+ const got = parsePolicy(served);
+ const problems = [];
+ for (const [name, wantSources] of want) {
+ const gotSources = got.get(name);
+ if (!gotSources) {
+ problems.push(`directive "${name}" is missing from the served policy`);
+ continue;
+ }
+ const hashable = name === 'script-src' || name === 'script-src-elem';
+ const expected = new Set(wantSources);
+ const actual = new Set(gotSources);
+ if (hashable) {
+ expected.delete("'unsafe-inline'");
+ for (const src of [...actual]) if (src.startsWith("'sha256-")) actual.delete(src);
+ }
+ if (setsEqual(expected, actual)) continue;
+ const missing = [...expected].filter((s) => !actual.has(s));
+ const extra = [...actual].filter((s) => !expected.has(s));
+ problems.push(
+ `directive "${name}" differs${missing.length ? ` (missing ${missing.join(' ')})` : ''}` +
+ `${extra.length ? ` (unexpected ${extra.join(' ')})` : ''}`,
+ );
+ }
+ return problems;
+}
+
+/**
+ * Every way the response's security headers fail to be what the repo says it
+ * serves for this path.
+ */
+function headerProblems(pathname, base, servedHeaders) {
+ const want = declaredHeaders(pathname, base);
+ const problems = [];
+
+ for (const name of REQUIRED_ON_HTML) {
+ if (!want[name]) problems.push(`vercel.json declares no ${name} for this path`);
+ }
+
+ for (const [name, expected] of Object.entries(want)) {
+ // Only security headers are the subject here. Cache and CORS values are
+ // legitimately rewritten by the CDN and by conditional-request handling.
+ if (!name.startsWith('x-') && !REQUIRED_ON_HTML.includes(name) && name !== 'permissions-policy') {
+ continue;
+ }
+ const served = servedHeaders[name];
+ if (served === undefined) {
+ problems.push(`${name} was declared but the response did not carry it`);
+ continue;
+ }
+ if (name === 'content-security-policy') {
+ problems.push(...policyDiff(expected, served));
+ continue;
+ }
+ if (served.trim() !== expected.trim()) {
+ problems.push(`${name} is "${served}" but vercel.json declares "${expected}"`);
+ }
+ }
+ return problems;
+}
+
const browser = await chromium.launch({
args: ['--no-sandbox', '--disable-dev-shm-usage'],
});
@@ -108,30 +234,52 @@ for (const p of paths) {
page.on('pageerror', (err) => errors.push(String(err.message).slice(0, 200)));
let status = 0;
+ const headers = [];
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;
+ if (res && status < 400) {
+ // Judge the headers of the document that actually rendered: a route
+ // that redirects is governed by its destination's rules, not the
+ // requested path's.
+ headers.push(...headerProblems(new URL(res.url()).pathname, BASE, res.headers()));
+ }
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))` : ''}`);
+ // A page that never loaded, or answered with an error status, proves
+ // nothing: it has no inline scripts to block. Counting it as clean is how a
+ // sweep reports success over a wiped dist/ or a server that died halfway.
+ const unreachable = status === 0 || status >= 400;
+ results.push({ path: p, status, violations, errors, headers, unreachable });
+ const mark = violations.length
+ ? 'CSP'
+ : unreachable
+ ? 'DEAD'
+ : headers.length
+ ? 'HDR'
+ : errors.length
+ ? 'err'
+ : ' ok';
+ const note = violations.length
+ ? ` (${violations.length} violation(s))`
+ : headers.length
+ ? ` (${headers.length} header problem(s))`
+ : '';
+ console.log(`[${mark}] ${String(status).padEnd(3)} ${p}${note}`);
}
await browser.close();
const failed = results.filter((r) => r.violations.length > 0);
const unreachable = results.filter((r) => r.unreachable);
+const misheaded = results.filter((r) => !r.unreachable && r.headers.length > 0);
const errored = results.filter((r) => r.errors.length > 0 && r.violations.length === 0 && !r.unreachable);
if (errored.length) {
@@ -140,14 +288,24 @@ if (errored.length) {
}
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:`);
+ console.error(`\nCSP audit: ${unreachable.length} of ${results.length} page(s) never loaded or answered with an error, so this run proves nothing.`);
+ console.error(`A page that does not render has no inline script to block. Check that ${BASE} is serving a built dist/. First few:`);
for (const r of unreachable.slice(0, 8)) console.error(` ${r.path} (status ${r.status})`);
process.exit(2);
}
+if (misheaded.length) {
+ console.error(`\nCSP audit: ${misheaded.length} page(s) did not carry the headers vercel.json declares\n`);
+ for (const r of misheaded) {
+ console.error(` ${r.path}`);
+ for (const h of r.headers) console.error(` ${h}`);
+ }
+ process.exit(3);
+}
+
if (failed.length === 0) {
console.log(`\nCSP audit: clean across ${results.length} page(s) on ${BASE}`);
+ console.log('Each page loaded, carried the policy vercel.json declares, and fired no violation.');
process.exit(0);
}
diff --git a/scripts/audit-guards.mjs b/scripts/audit-guards.mjs
index 5ddaf8bd1..5246e9ebb 100644
--- a/scripts/audit-guards.mjs
+++ b/scripts/audit-guards.mjs
@@ -164,6 +164,34 @@ for (const rel of onDisk) {
);
}
+// docs/guards.md is the prose companion to the registry, and its tables are
+// hand-maintained: nothing generates them. That is fine as long as something
+// notices when a guard lands in the registry and never reaches the page. On
+// 2026-08-11 five had: sync-studio-openapi, audit-inline-handlers, audit-csp,
+// check-event-window, and audit-play-failure-modes ran on real stages while the
+// doc that claims to list every guard did not mention them at all. A reader
+// auditing coverage from the doc would have concluded those areas were
+// unguarded. Matching on the npm command (which the tables print in a code
+// span) rather than on the title keeps this immune to prose edits.
+{
+ const docPath = 'docs/guards.md';
+ if (!existsSync(path.join(root, docPath))) {
+ note(`${docPath} is missing, but it is the page /docs/guards renders and this registry documents`);
+ } else {
+ const doc = read(docPath);
+ const documented = new Set([...doc.matchAll(/`npm run ([a-z0-9:-]+)`/g)].map((m) => m[1]));
+ for (const g of registry.guards || []) {
+ const npmNames = [g.npm, ...(g.npmAliases || [])].filter(Boolean);
+ if (!npmNames.length) continue;
+ if (npmNames.some((n) => documented.has(n))) continue;
+ note(
+ `guard \`${g.id}\` is in the registry but no table in ${docPath} names \`npm run ${npmNames[0]}\`. ` +
+ `Add a row for it, so the page that claims to list every guard actually does.`,
+ );
+ }
+ }
+}
+
// The published copy the /guards page fetches. data/ is never served, so the
// page reads public/guards.json; if the two drift, the page and docs/guards.md
// show different answers and neither looks wrong on its own.
diff --git a/scripts/audit-mcp-manifests.mjs b/scripts/audit-mcp-manifests.mjs
index 757f8f83f..5031a2fec 100644
--- a/scripts/audit-mcp-manifests.mjs
+++ b/scripts/audit-mcp-manifests.mjs
@@ -13,6 +13,13 @@
// packages[0].identifier/version match, mcpName matches server.json name
// - remote manifests: every remotes[].url is https
//
+// Plus the public directory at public/.well-known/mcp.json, which agents fetch
+// to enumerate the hosted fleet in one request: it must list exactly the remote
+// manifests on disk (no orphan entry, no unlisted endpoint), agree with each
+// manifest on transport, and point every documentation link at a doc that
+// exists. /docs/<slug> is served by an SPA shell that answers 200 for any slug,
+// so a live probe cannot catch a dead docs link; only docs/<slug>.md can.
+//
// Run: node scripts/audit-mcp-manifests.mjs (exit 1 on any violation)
import { readFileSync, existsSync, readdirSync } from 'node:fs';
@@ -136,6 +143,52 @@ for (const path of remoteManifests) {
}
}
+// The hosted-fleet directory must describe the same servers the repo ships.
+{
+ const dirPath = 'public/.well-known/mcp.json';
+ const dir = load(dirPath);
+ const entries = Array.isArray(dir?.servers) ? dir.servers : null;
+ if (dir && !entries) fail(dirPath, 'missing servers[]');
+
+ if (entries) {
+ const byEndpoint = new Map();
+ for (const s of entries) {
+ for (const field of ['name', 'endpoint', 'transport', 'auth', 'description', 'documentation']) {
+ if (!s[field]) fail(dirPath, `entry "${s.name || s.endpoint || '?'}" missing ${field}`);
+ }
+ if (s.endpoint) {
+ if (byEndpoint.has(s.endpoint)) fail(dirPath, `endpoint listed twice: ${s.endpoint}`);
+ byEndpoint.set(s.endpoint, s);
+ }
+ const doc = s.documentation || '';
+ const slug = doc.startsWith('https://three.ws/docs/') ? doc.slice('https://three.ws/docs/'.length) : null;
+ if (!slug) {
+ fail(dirPath, `documentation must be an https://three.ws/docs/<slug> link (${doc})`);
+ } else if (!existsSync(resolve(root, 'docs', `${slug}.md`))) {
+ fail(dirPath, `documentation ${doc} has no docs/${slug}.md behind it`);
+ }
+ }
+
+ for (const path of remoteManifests) {
+ const m = load(path);
+ for (const r of m?.remotes ?? []) {
+ const entry = byEndpoint.get(r.url);
+ if (!entry) {
+ fail(dirPath, `${path} serves ${r.url} but the directory does not list it`);
+ continue;
+ }
+ if (entry.transport !== r.type) {
+ fail(dirPath, `${r.url}: directory says transport "${entry.transport}", ${path} says "${r.type}"`);
+ }
+ byEndpoint.delete(r.url);
+ }
+ }
+ for (const url of byEndpoint.keys()) {
+ fail(dirPath, `lists ${url}, which no server*.json at the repo root declares`);
+ }
+ }
+}
+
const total = PACKAGE_MANIFESTS.length + remoteManifests.length;
if (violations) {
console.error(`[audit:mcp] ${violations} violation(s) across ${total} manifests`);
diff --git a/scripts/audit-route-shadowing.mjs b/scripts/audit-route-shadowing.mjs
index 9e4a3b278..23c3d935d 100644
--- a/scripts/audit-route-shadowing.mjs
+++ b/scripts/audit-route-shadowing.mjs
@@ -10,9 +10,9 @@
// (scripts/lib/vercel-routes.mjs), which mirrors server/index.mjs, so there is
// no second copy of the routing rules to drift.
//
-// A handler is REACHABLE if at least one concrete request path resolves to it.
-// Two families of path can do that, and both are modeled here, because checking
-// only the first produces mostly false positives:
+// A handler is REACHABLE if at least one concrete request can run its code.
+// Three families do that, and all three are modeled here, because checking only
+// the first produces mostly false positives:
//
// 1. Its own filesystem path: /api/pump/balances for api/pump/balances.js,
// with [param] segments filled in by several probe values (a rule regex may
@@ -21,12 +21,26 @@
// lands on api/agents/[id]/memory-seed-x.js, whose own filesystem path is
// swallowed by the /api/agents catch-all. The handler is alive; only its
// literal path is not.
+// 3. IN-HANDLER DISPATCH: the handler that claims the swallowed path imports
+// the module and hands the request to it. api/agents/[id].js does exactly
+// that for its ~18 sub-resource modules (`await import('./sns.js')`), and
+// api/auth/[action].js for api/auth/captcha.js. The request arrives, just
+// not at the sibling's own URL.
//
-// For (2) a concrete sample path is synthesised from each rule's `src` regex and
-// then re-tested against the same regex AND pushed through the real matcher, so
-// a rule only counts as delivering traffic when a request provably reaches its
-// own dest. A rule that cannot deliver to its own dest is itself reported as a
-// shadowed rule, which is how the /api/agents catch-all incident presents.
+// The line family 3 draws is the load-bearing one. A dispatcher that IMPORTS the
+// sibling runs the sibling's code; a dispatcher that reimplements the action
+// inline (`case 'channel-feed':`) does NOT, and the sibling is then a stale
+// duplicate of live logic — a real defect, still reported. So reachability
+// follows the import graph under api/ (transitively, since a dispatched module
+// may itself dispatch further), seeded from the handlers families 1 and 2 reach.
+//
+// For (2) a concrete sample path is synthesised from each rule's `src` regex,
+// plus a request that satisfies the rule's `has` conditions (a bot user-agent, a
+// query param), and is then re-tested against the same regex AND pushed through
+// the real matcher, so a rule only counts as delivering traffic when a request
+// provably reaches its own dest. A rule that cannot deliver to its own dest is
+// itself reported as a shadowed rule, which is how the /api/agents catch-all
+// incident presents.
//
// Usage:
// node scripts/audit-route-shadowing.mjs # human-readable report
@@ -36,7 +50,7 @@
// Exit code 1 when a handler has no reachable path, or a rule cannot reach its
// own destination.
-import { readFileSync, readdirSync } from 'node:fs';
+import { existsSync, readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { isRoutable, loadRouteTable, resolveApiPath, resolveRequest } from './lib/vercel-routes.mjs';
@@ -98,6 +112,41 @@ function sampleCharClass(pattern) {
return null;
}
+// `{8}` / `{8,12}` / `{2,}`: no probe is the right length, so repeat one
+// accepted character the minimum number of times.
+function repeatCount(quant) {
+ const m = /^\{(\d+)(?:,(\d*))?\}$/.exec(quant);
+ return m ? Number(m[1]) : null;
+}
+
+function sampleRepeated(pattern, count) {
+ for (const ch of ALPHABET) if (accepts(pattern, ch)) return ch.repeat(count);
+ return null;
+}
+
+// Read the quantifier that follows a group or class: `?`, `*`, `+`, or `{n,m}`.
+function readQuantifier(src, from) {
+ let i = from;
+ let quant = '';
+ while (i < src.length) {
+ if ('?*+'.includes(src[i])) {
+ quant += src[i++];
+ continue;
+ }
+ if (src[i] === '{') {
+ const close = src.indexOf('}', i);
+ if (close === -1) break;
+ const candidate = src.slice(i, close + 1);
+ if (!/^\{\d+(?:,\d*)?\}$/.test(candidate)) break;
+ quant += candidate;
+ i = close + 1;
+ continue;
+ }
+ break;
+ }
+ return { quant, next: i };
+}
+
// A group is satisfied by the first probe its own pattern accepts; failing that
// (nested groups, alternations) its first alternative is sampled recursively.
function sampleGroup(inner, depth) {
@@ -135,15 +184,14 @@ function sampleFromSrc(src, depth = 0) {
const end = closingParen(src, i);
if (end === -1) return null;
const inner = src.slice(i + 1, end);
- let j = end + 1;
- let quant = '';
- while (j < src.length && '?*+'.includes(src[j])) quant += src[j++];
- i = j;
+ const grouped = readQuantifier(src, end + 1);
+ i = grouped.next;
// An optional or starred group contributes nothing to the shortest path.
- if (quant.startsWith('?') || quant.startsWith('*')) continue;
- const piece = sampleGroup(inner, depth);
- if (piece === null) return null;
- out += piece;
+ if (grouped.quant.startsWith('?') || grouped.quant.startsWith('*')) continue;
+ const sampled = sampleGroup(inner, depth);
+ if (sampled === null) return null;
+ const groupReps = repeatCount(grouped.quant);
+ out += groupReps === null ? sampled : sampled.repeat(groupReps);
continue;
}
if (ch === '[') {
@@ -151,12 +199,13 @@ function sampleFromSrc(src, depth = 0) {
while (j < src.length && src[j] !== ']') j += src[j] === '\\' ? 2 : 1;
if (j >= src.length) return null;
const cls = src.slice(i, j + 1);
- let k = j + 1;
- let quant = '';
- while (k < src.length && '?*+'.includes(src[k])) quant += src[k++];
- i = k;
+ const classed = readQuantifier(src, j + 1);
+ const quant = classed.quant;
+ i = classed.next;
if (quant.startsWith('?') || quant.startsWith('*')) continue;
- const piece = sampleCharClass(`${cls}${quant || ''}`);
+ const reps = repeatCount(quant);
+ const piece =
+ reps === null ? sampleCharClass(`${cls}${quant || ''}`) : sampleRepeated(cls, reps);
if (piece === null) return null;
out += piece;
continue;
@@ -197,6 +246,48 @@ function sampleForRoute(route) {
return route.re.test(sample) ? sample : null;
}
+// ---------------------------------------------------------------------------
+// `has` conditions: probe the request the rule was written for.
+//
+// A rule can be gated on a header, query param, cookie or host (the OG rules are
+// gated on a crawler user-agent). A plain GET satisfies none of them, so probing
+// one with a default request proves nothing except that the gate works. Build a
+// request that DOES satisfy the gate, and only then ask where it lands.
+// ---------------------------------------------------------------------------
+
+// `has[].value` is matched unanchored and may carry a Perl-style `(?i)` prefix.
+function sampleHasValue(value) {
+ if (value === undefined) return 'probe';
+ const caseInsensitive = value.startsWith('(?i)');
+ const pattern = caseInsensitive ? value.slice(4) : value;
+ const sample = sampleFromSrc(pattern);
+ if (sample === null) return null;
+ try {
+ return new RegExp(pattern, caseInsensitive ? 'i' : undefined).test(sample) ? sample : null;
+ } catch {
+ return null;
+ }
+}
+
+/** @returns {{headers:object, search:string}|null} null when a gate cannot be met. */
+function probeForHas(route) {
+ const headers = { host: 'three.ws' };
+ const params = new URLSearchParams();
+ const cookies = [];
+ for (const cond of route.has || []) {
+ const value = sampleHasValue(cond.value);
+ if (value === null) return null;
+ if (cond.type === 'header') headers[cond.key.toLowerCase()] = value;
+ else if (cond.type === 'query') params.set(cond.key, value);
+ else if (cond.type === 'cookie') cookies.push(`${cond.key}=${encodeURIComponent(value)}`);
+ else if (cond.type === 'host') headers.host = value;
+ else return null;
+ }
+ if (cookies.length) headers.cookie = cookies.join('; ');
+ const search = params.toString();
+ return { headers, search: search ? `?${search}` : '' };
+}
+
// ---------------------------------------------------------------------------
// Handler inventory
// ---------------------------------------------------------------------------
@@ -270,11 +361,16 @@ for (const route of table.phase1Routes) {
const touchesApi = route.src.startsWith('/api/') || (route.dest || '').startsWith('/api/');
if (!touchesApi) continue;
const sample = sampleForRoute(route);
- if (!sample) {
+ const probe = probeForHas(route);
+ if (!sample || !probe) {
unsampledRules.push({ index: route.index, src: route.src, dest: route.dest ?? null });
continue;
}
- const result = resolveRequest(table, sample, { apiRoot: API_ROOT });
+ const result = resolveRequest(table, sample, {
+ apiRoot: API_ROOT,
+ headers: probe.headers,
+ search: probe.search,
+ });
const wanted = (route.dest || '').startsWith('/api/')
? resolveApiPath(API_ROOT, route.dest.split('?')[0])
: null;
@@ -301,8 +397,7 @@ for (const route of table.phase1Routes) {
// ---------------------------------------------------------------------------
const handlers = collectHandlers(API_ROOT, [], []);
-const unreachable = [];
-const ruleOnly = [];
+const paths = new Map(); // handler file -> { direct[], diverted[] }
for (const h of handlers) {
const direct = [];
@@ -312,10 +407,75 @@ for (const h of handlers) {
if (result.outcome === 'handler' && result.file === h.file) direct.push(p);
else diverted.push({ path: p, to: describe(result), rule: result.rule ?? null });
}
+ paths.set(h.file, { handler: h, direct, diverted });
+}
+
+// ---------------------------------------------------------------------------
+// Pass 3: the in-handler dispatch graph (reachability family 3).
+//
+// Seeded with every file a request already reaches, then walked over the import
+// edges between files under api/ — including through api/_lib, since a live
+// handler routinely reaches a sibling endpoint's module by way of a shared
+// library. Following the edges transitively is what makes the walk correct for
+// api/agents/patronage.js, which api/agents/[id].js reaches only through
+// api/agents/solana-wallet.js.
+//
+// Import edges, not name mentions: a dispatcher that reimplements the action
+// inline never imports the sibling, so a stale duplicate of live logic keeps
+// failing this audit instead of hiding behind the dispatcher that replaced it.
+// ---------------------------------------------------------------------------
+
+const IMPORT_RE = /\bfrom\s*['"]([^'"]+)['"]|\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
+
+function apiImportsOf(file) {
+ let src;
+ try {
+ src = readFileSync(file, 'utf8');
+ } catch {
+ return [];
+ }
+ const out = [];
+ for (const m of src.matchAll(IMPORT_RE)) {
+ const spec = m[1] ?? m[2];
+ if (!spec.startsWith('.')) continue;
+ const resolved = path.resolve(path.dirname(file), spec);
+ if (!resolved.startsWith(API_ROOT + path.sep)) continue;
+ const target = resolved.endsWith('.js') ? resolved : `${resolved}.js`;
+ if (existsSync(target)) out.push(target);
+ }
+ return out;
+}
+
+const dispatchedFrom = new Map(); // handler file -> the importing file that reaches it
+const queue = [];
+const walked = new Set();
+for (const [file, info] of paths) {
+ if (info.direct.length || (reachableVia.get(file) || []).length) {
+ walked.add(file);
+ queue.push(file);
+ }
+}
+while (queue.length) {
+ const file = queue.shift();
+ for (const target of apiImportsOf(file)) {
+ if (walked.has(target)) continue;
+ walked.add(target);
+ if (paths.has(target)) dispatchedFrom.set(target, file);
+ queue.push(target);
+ }
+}
+
+const unreachable = [];
+const ruleOnly = [];
+const dispatched = [];
+
+for (const [file, info] of paths) {
+ const { handler: h, direct, diverted } = info;
if (direct.length === canonicalPaths(h.segments).length) continue;
- const viaRules = reachableVia.get(h.file) || [];
+ const viaRules = reachableVia.get(file) || [];
+ const dispatcher = dispatchedFrom.get(file);
const record = {
- handler: rel(h.file),
+ handler: rel(file),
canonical: canonicalPaths(h.segments)[0],
directPaths: direct,
divertedTo: diverted.map((d) => ({ path: d.path, to: d.to })),
@@ -323,9 +483,12 @@ for (const h of handlers) {
? { index: diverted[0].rule.index, src: diverted[0].rule.src, dest: diverted[0].rule.dest ?? null }
: null,
reachableVia: viaRules.map((v) => v.path),
+ dispatchedFrom: dispatcher ? rel(dispatcher) : null,
};
- if (direct.length === 0 && viaRules.length === 0) unreachable.push(record);
- else if (direct.length === 0) ruleOnly.push(record);
+ if (direct.length) continue;
+ if (viaRules.length) ruleOnly.push(record);
+ else if (dispatcher) dispatched.push(record);
+ else unreachable.push(record);
}
// ---------------------------------------------------------------------------
@@ -338,7 +501,7 @@ const showAll = process.argv.includes('--all');
if (asJson) {
console.log(
JSON.stringify(
- { scanned: handlers.length, unreachable, ruleOnly, deadRules, unsampledRules },
+ { scanned: handlers.length, unreachable, ruleOnly, dispatched, deadRules, unsampledRules },
null,
2,
),
@@ -373,6 +536,15 @@ if (asJson) {
console.log(' (re-run with --all to list them)');
}
+ console.log(
+ `\nReachable only through in-handler dispatch (a live handler imports it): ${dispatched.length}`,
+ );
+ if (showAll) {
+ for (const r of dispatched) console.log(` ${r.handler} <- ${r.dispatchedFrom}`);
+ } else if (dispatched.length) {
+ console.log(' (re-run with --all to list them)');
+ }
+
if (unsampledRules.length) {
console.log(`\nRules whose src could not be sampled (not verified): ${unsampledRules.length}`);
for (const r of unsampledRules) console.log(` #${r.index}: ${r.src} -> ${r.dest}`);
diff --git a/scripts/build-page-index.mjs b/scripts/build-page-index.mjs
index 23154e24c..466995de6 100644
--- a/scripts/build-page-index.mjs
+++ b/scripts/build-page-index.mjs
@@ -276,36 +276,60 @@ ${items}
.map((s) => `\t\t\t<a href="#${escapeHtml(s.id)}">${escapeHtml(s.title)}</a>`)
.join('\n');
- const sitemapDescription = `Complete index of every public page on ${site.name}.`;
+ // Copy comes from the catalog entry for /sitemap, not a second hardcoded
+ // string: this file is regenerated on every run, so any drift from the
+ // catalog would be re-applied by scripts/inject-seo-meta.mjs and undone here
+ // on the next build, leaving the pair permanently out of sync.
+ const sitemapEntry = allPages.find((p) => p.path === '/sitemap');
+ const sitemapTitle = sitemapEntry?.title || 'Sitemap';
+ const sitemapDescription =
+ sitemapEntry?.description || `Complete index of every public page on ${site.name}.`;
const sitemapOgImage = `${baseUrl}/api/page-og?${new URLSearchParams({
- s: 'main',
- t: 'Sitemap',
+ s: sitemapEntry?.section?.id || 'main',
+ t: sitemapTitle,
d: sitemapDescription,
p: '/sitemap',
})}`;
+ const sitemapJsonLd = JSON.stringify({
+ '@context': 'https://schema.org',
+ '@graph': [
+ {
+ '@type': 'WebPage',
+ name: sitemapTitle,
+ description: sitemapDescription,
+ url: `${baseUrl}/sitemap`,
+ isPartOf: { '@type': 'WebSite', name: site.name, url: baseUrl },
+ primaryImageOfPage: sitemapOgImage,
+ },
+ ],
+ }).replace(/</g, '\\u003c');
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
-<title>Sitemap · ${escapeHtml(site.name)}</title>
+<title>${escapeHtml(sitemapTitle)} · ${escapeHtml(site.name)}</title>
<meta name="description" content="${escapeHtml(sitemapDescription)}" />
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
<link rel="canonical" href="${escapeHtml(baseUrl)}/sitemap" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="${escapeHtml(site.name)}" />
+<meta property="og:locale" content="en_US" />
<meta property="og:url" content="${escapeHtml(baseUrl)}/sitemap" />
-<meta property="og:title" content="Sitemap · ${escapeHtml(site.name)}" />
+<meta property="og:title" content="${escapeHtml(sitemapTitle)} · ${escapeHtml(site.name)}" />
<meta property="og:description" content="${escapeHtml(sitemapDescription)}" />
<meta property="og:image" content="${escapeHtml(sitemapOgImage)}" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
+<meta property="og:image:type" content="image/png" />
+<meta property="og:image:alt" content="${escapeHtml(sitemapTitle)} - ${escapeHtml(site.name)}" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@trythreews" />
-<meta name="twitter:title" content="Sitemap · ${escapeHtml(site.name)}" />
+<meta name="twitter:title" content="${escapeHtml(sitemapTitle)} · ${escapeHtml(site.name)}" />
<meta name="twitter:description" content="${escapeHtml(sitemapDescription)}" />
<meta name="twitter:image" content="${escapeHtml(sitemapOgImage)}" />
+<script type="application/ld+json">${sitemapJsonLd}</script>
<link rel="alternate" type="application/xml" title="XML sitemap" href="/sitemap.xml" />
<link rel="alternate" type="text/plain" title="llms.txt" href="/llms.txt" />
<link rel="stylesheet" href="/nav.css" />
diff --git a/scripts/changelog-gaps.mjs b/scripts/changelog-gaps.mjs
index 46aa0ea3d..6d8394ed8 100644
--- a/scripts/changelog-gaps.mjs
+++ b/scripts/changelog-gaps.mjs
@@ -60,8 +60,14 @@ const CHORE_KEYWORD = /\b(lockfile|package-lock|pnpm-lock|node_modules|gitignore
// Paths that, if a commit touches ONLY these, make it internal regardless of
// its subject. A commit that also touches product code is kept.
+//
+// The generated block is every file scripts/build-page-index.mjs writes. They
+// are mirrors of data/pages.json + data/changelog.json, which this audit
+// already reads directly, so a commit that only regenerates them ships nothing
+// new by construction. Left out, a bare `npm run build:pages` commit reads as
+// unlogged user-visible work and pads the GAPS count with pure churn.
const INTERNAL_ONLY_PATH =
- /^(tests?\/|\.github\/|scripts\/|\.husky\/|\.claude\/|\.agents\/|prompts\/|data\/_generated\/|CHANGELOG\.md$|CLAUDE\.md$|ISSUES\.md$|data\/changelog\.json$|public\/changelog\.(json|xml)$|.*\.lock$|.*\.test\.[jt]s$|.*\.spec\.[jt]s$)/;
+ /^(tests?\/|\.github\/|scripts\/|\.husky\/|\.claude\/|\.agents\/|prompts\/|data\/_generated\/|CHANGELOG\.md$|CLAUDE\.md$|ISSUES\.md$|data\/changelog\.json$|public\/changelog\.(json|xml)$|public\/features\.json$|public\/llms(-full)?\.txt$|public\/sitemap\/|public\/locales\/localized-pages\.json$|.*\.lock$|.*\.test\.[jt]s$|.*\.spec\.[jt]s$)/;
// Plumbing: real shipped work that a $THREE holder still never perceives —
// container builds, GPU-worker image pins, generated translation bundles,
@@ -70,11 +76,17 @@ const INTERNAL_ONLY_PATH =
// what trained everyone to ignore this audit. A commit whose files are ALL
// plumbing gets reported under its own heading instead, outside the count.
const PLUMBING_PATH =
- /^(workers\/|crates\/|server\/|deploy\/|marketing\/|specs\/|docs\/|blog\/|public\/locales\/|locales\/|\.env\.example$|STRUCTURE\.md$|ARCHITECTURE\.md$|README\.md$|.*\/README\.md$|.*\/Dockerfile$|.*cloudbuild.*\.ya?ml$|.*\.md$)/;
+ /^(workers\/|services\/|crates\/|server\/|deploy\/|marketing\/|specs\/|docs\/|blog\/|public\/locales\/|locales\/|\.env\.example$|STRUCTURE\.md$|ARCHITECTURE\.md$|README\.md$|.*\/README\.md$|.*\/Dockerfile$|.*cloudbuild.*\.ya?ml$|.*\.md$)/;
// …unless the subject says the plumbing IS the product: a brand-new worker
// lane or backend is a capability holders can use, however deep it sits.
+//
+// Tested against the subject with its conventional-commit SCOPE removed, type
+// kept: `feat(screen-worker): resolve local Chrome launch options` is a config
+// change inside one worker, not a new lane, and matching "worker" out of the
+// scope escaped every such commit into the GAPS count.
const PLUMBING_ESCAPE = /\b(lane|backend|worker)\b.*\b(new|add|introduc)|^(feat|feature)\b.*\b(lane|worker)\b/i;
+const escapeSubject = (subject) => subject.replace(/^([a-z]+)\([^)]*\):/i, '$1:');
// --- keyword extraction -----------------------------------------------------
@@ -175,7 +187,7 @@ for (const c of commits) {
const allPlumbing =
files.length > 0 &&
files.every((f) => PLUMBING_PATH.test(f) || INTERNAL_ONLY_PATH.test(f)) &&
- !PLUMBING_ESCAPE.test(c.subject);
+ !PLUMBING_ESCAPE.test(escapeSubject(c.subject));
(allPlumbing ? plumbing : gaps).push(row);
}
diff --git a/scripts/check-secrets.mjs b/scripts/check-secrets.mjs
new file mode 100644
index 000000000..6af440be2
--- /dev/null
+++ b/scripts/check-secrets.mjs
@@ -0,0 +1,299 @@
+#!/usr/bin/env node
+// Stop credential material from becoming a tracked file.
+//
+// A leaked key in git is not a bug you fix by deleting the line: every clone,
+// every fork, and every mirror keeps a copy, so the only real remedy is
+// rotating the credential at the provider. That asymmetry is why this runs
+// before the push rather than after, and why it is deliberately loud.
+//
+// Two checks, with two different scopes, for two different reasons:
+//
+// 1. FILENAMES, repo-wide and absolute. A real `.env`, a `.pem`, an
+// `id_ed25519`, a downloaded service-account JSON: these are credential
+// files by construction, and the tree currently contains exactly zero of
+// them. A rule with no legacy to grandfather can be absolute, so this one
+// is: any tracked path matching it fails, no diff scoping, no exceptions
+// beyond the `.env.example` style templates that exist to be committed.
+//
+// 2. CONTENTS, diff scoped. Added lines only, same reasoning as
+// scripts/check-rules.mjs: the tree holds thousands of hex addresses,
+// transaction signatures, hardhat test keys, and `YOUR_TOKEN` docs
+// placeholders, so a repo-wide content scan drowns in noise and gets
+// switched off. Judging only what you are adding keeps the signal high
+// enough to be worth blocking a push over.
+//
+// The content rules are narrow on purpose. Each one matches a credential
+// format that a provider issues and nothing else looks like (a `sk-ant-` key,
+// a PEM private-key block, a database URL carrying a password, a Solana
+// keypair byte array). Entropy heuristics were left out: they flag build
+// hashes, base64 fixtures, and minified code, and a guard that cries wolf is a
+// guard someone disables.
+//
+// Modes (matching scripts/check-rules.mjs so the pre-push hook can drive both):
+// node scripts/check-secrets.mjs working tree + staged, vs HEAD
+// node scripts/check-secrets.mjs --staged staged only
+// node scripts/check-secrets.mjs --base <ref> everything since <ref>
+// node scripts/check-secrets.mjs --base <ref> --head <ref> a pushed ref (hook)
+// node scripts/check-secrets.mjs --paths a.js only these files
+// node scripts/check-secrets.mjs --all every tracked file (full sweep)
+//
+// Exit 1 on any finding, with file:line and the credential class.
+
+import { execFileSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const argv = process.argv.slice(2);
+const staged = argv.includes('--staged');
+const all = argv.includes('--all');
+const baseIdx = argv.indexOf('--base');
+const base = baseIdx === -1 ? null : argv[baseIdx + 1];
+const headIdx = argv.indexOf('--head');
+const head = headIdx === -1 ? 'HEAD' : argv[headIdx + 1];
+const pathsIdx = argv.indexOf('--paths');
+const paths = pathsIdx === -1 ? [] : argv.slice(pathsIdx + 1).filter((a) => !a.startsWith('--'));
+
+const git = (args) =>
+ execFileSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+
+// Filename patterns that ARE credential files, whatever they contain. Kept
+// separate from the content rules because the answer here does not depend on
+// reading the file: nobody commits a private key deliberately.
+const SECRET_FILENAMES = [
+ {
+ id: 'dotenv-file',
+ // `.env`, `.env.local`, `.env.production`, `.env.xspace`. NOT the
+ // templates whose whole job is to be committed with placeholder values.
+ test: (file) => {
+ const name = path.basename(file);
+ if (!/^\.env(\.|$)/.test(name)) return false;
+ return !/\.(example|sample|template|defaults|schema|d\.ts)$/.test(name);
+ },
+ why: 'a real dotenv file belongs in .gitignore, never in the tree (commit a .env.example instead)',
+ },
+ {
+ id: 'key-file',
+ test: (file) => /\.(pem|key|p12|pfx|jks|keystore|ppk)$/i.test(file) && !/\.(public|pub)\.(pem|key)$/i.test(file),
+ why: 'private-key and keystore files are credential material by construction',
+ },
+ {
+ id: 'ssh-key',
+ test: (file) => /(^|\/)id_(rsa|dsa|ecdsa|ed25519)$/.test(file),
+ why: 'an SSH private key must never be tracked',
+ },
+ {
+ id: 'cloud-credentials',
+ test: (file) =>
+ /(^|\/)(service[-_]account|gcp[-_]key|application_default_credentials|credentials)\.json$/i.test(file) ||
+ /(^|\/)\.aws\/credentials$/.test(file),
+ why: 'downloaded cloud credential files carry a live private key',
+ },
+];
+
+// Generated, vendored, and binary paths. Same list-shaped reasoning as
+// check-rules.mjs: machine-written content produces noise, not signal.
+const SKIP_CONTENT = [
+ /^dist\//,
+ /^dist-lib\//,
+ /(^|\/)node_modules\//,
+ /^public\/chat\/assets\//,
+ /^contracts\/lib\//,
+ /package-lock\.json$/,
+ /\.min\.(js|css)$/,
+ /\.(png|jpg|jpeg|gif|webp|glb|gltf|bin|woff2?|ttf|mp4|wasm|ico|svg|pdf|zip|gz)$/i,
+ // This file and its proof fixture must contain the patterns verbatim in
+ // order to detect them, so scanning either reports the detector as the
+ // offense. A scanner cannot scan its own pattern table.
+ /^scripts\/check-secrets\.mjs$/,
+ /^data\/guards\.json$/,
+ /^public\/guards\.json$/,
+ // The runtime scrubber and its tests exist to redact these strings, so they
+ // must hold synthetic examples of every shape they redact.
+ /^api\/_lib\/scrub-secrets\.js$/,
+ /^tests\/scrub-secrets\.test\.js$/,
+];
+const skippedContent = (file) => SKIP_CONTENT.some((re) => re.test(file));
+
+// A value that announces itself as fake. Providers never issue these, and docs
+// are full of them, so every content rule consults this before reporting.
+const PLACEHOLDER =
+ /(x{4,}|\.\.\.|your[_-]?|my[_-]?|replace|placeholder|redacted|example|sample|dummy|fake|test[_-]|demo|changeme|insert[_-]|here|abc123|0123456789|1234567890|hunter2|s3cr3t|secret)/i;
+
+const CONTENT_RULES = [
+ {
+ id: 'provider-api-key',
+ what: 'a live API key in a provider-issued format',
+ // Each alternative is a format one vendor issues and nothing else
+ // produces. Lengths are the vendor minimums, so a truncated docs sample
+ // ("sk-ant-...") does not match.
+ test: (line) =>
+ /(sk-ant-api[0-9]{2}-[A-Za-z0-9_-]{40,}|sk-proj-[A-Za-z0-9_-]{40,}|sk-[A-Za-z0-9]{48,}|gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,}|glpat-[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35}|xox[baprs]-[0-9A-Za-z-]{20,}|hf_[A-Za-z0-9]{34,}|nvapi-[A-Za-z0-9_-]{40,}|r8_[A-Za-z0-9]{37,}|gsk_[A-Za-z0-9]{50,}|sk-or-v1-[a-f0-9]{60,}|SG\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{30,}|npm_[A-Za-z0-9]{36}|dckr_pat_[A-Za-z0-9_-]{20,}|ya29\.[0-9A-Za-z_-]{60,})/.test(
+ line,
+ ),
+ except: (line) => PLACEHOLDER.test(line),
+ },
+ {
+ id: 'private-key-block',
+ what: 'a PEM private-key block',
+ test: (line) => /-----BEGIN (RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----/.test(line),
+ // Code that strips the header, and docs that show the shape with an
+ // ellipsis instead of key bytes, both name the header legitimately.
+ except: (line) => /replace\(|RegExp|match\(|split\(|includes\(|…|\.\.\.|MIGH|YOUR|\$\{/.test(line) || PLACEHOLDER.test(line),
+ },
+ {
+ id: 'connection-string',
+ what: 'a database or broker URL carrying a real password',
+ test: (line) => /(postgres(ql)?|mysql|mongodb(\+srv)?|redis[s]?|amqp[s]?):\/\/[A-Za-z0-9_.-]+:[^@\s"'`/]{6,}@/.test(line),
+ except: (line) => {
+ const pw = line.match(/(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis[s]?|amqp[s]?):\/\/[A-Za-z0-9_.-]+:([^@\s"'`/]{6,})@/)?.[1] ?? '';
+ return PLACEHOLDER.test(pw) || /^pass(word)?$/i.test(pw) || /^\$\{?[A-Z_]/.test(pw);
+ },
+ },
+ {
+ id: 'solana-keypair',
+ what: 'a Solana keypair serialized as a 64-byte array',
+ test: (line) => /\[\s*(\d{1,3}\s*,\s*){63}\d{1,3}\s*\]/.test(line),
+ },
+ {
+ id: 'ethereum-private-key',
+ what: 'a 32-byte hex private key assigned to a key-shaped name',
+ // The bare hex is indistinguishable from a transaction hash or a storage
+ // slot, so the name on the left of the assignment is what makes this a
+ // finding.
+ test: (line) => /(private[_-]?key|privkey|secret[_-]?key|mnemonic|seed[_-]?phrase)\W{0,4}["'`]?(0x)?[a-fA-F0-9]{64}\b/i.test(line),
+ except: (line) => {
+ if (PLACEHOLDER.test(line)) return true;
+ // The two published test keys every EVM tutorial uses (hardhat and
+ // ethers account #0). Public by design, funded on nothing.
+ if (/0x(59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d|ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80)/i.test(line)) return true;
+ // A template's fill-me-in value: all zeroes, all f's, `deadbeef`
+ // repeated. A key drawn at random uses nearly every hex digit, so a
+ // 64-nibble string spanning fewer than eight distinct ones is a
+ // placeholder with a probability no real key ever reaches.
+ const hex = line.match(/(?:private[_-]?key|privkey|secret[_-]?key|mnemonic|seed[_-]?phrase)\W{0,4}["'`]?(?:0x)?([a-fA-F0-9]{64})\b/i)?.[1] ?? '';
+ return new Set(hex.toLowerCase()).size < 8;
+ },
+ },
+];
+
+const findings = [];
+const report = (file, line, rule, content) =>
+ findings.push({ file, line, id: rule.id, what: rule.what, content: content.trim().slice(0, 80) });
+
+// 1. Filenames, repo-wide. Cheap enough to run in every mode: it reads one
+// `git ls-files`, and a credential file that is already tracked is a finding no
+// matter which commit added it.
+let trackedFiles = [];
+try {
+ trackedFiles = git(['ls-files']).split('\n').filter(Boolean);
+} catch (err) {
+ console.error(`[check-secrets] could not list tracked files: ${err.message}`);
+ process.exit(1);
+}
+for (const file of trackedFiles) {
+ for (const rule of SECRET_FILENAMES) {
+ if (rule.test(file)) findings.push({ file, line: 1, id: rule.id, what: rule.why, content: path.basename(file) });
+ }
+}
+
+// 2. Contents.
+let filesScanned = 0;
+if (all) {
+ for (const file of trackedFiles) {
+ if (skippedContent(file)) continue;
+ let body;
+ try {
+ body = readFileSync(path.join(root, file), 'utf8');
+ } catch {
+ continue;
+ }
+ if (body.includes('\u0000')) continue;
+ filesScanned += 1;
+ const lines = body.split('\n');
+ for (let i = 0; i < lines.length; i += 1) {
+ for (const rule of CONTENT_RULES) {
+ if (rule.test(lines[i]) && !(rule.except && rule.except(lines[i]))) report(file, i + 1, rule, lines[i]);
+ }
+ }
+ }
+} else {
+ let diffArgs;
+ if (base) diffArgs = ['diff', '--unified=0', `${base}...${head}`];
+ else if (staged) diffArgs = ['diff', '--unified=0', '--staged'];
+ else diffArgs = ['diff', '--unified=0', 'HEAD'];
+ if (paths.length) diffArgs = [...diffArgs, '--', ...paths];
+
+ let diff;
+ try {
+ diff = git(diffArgs);
+ } catch (err) {
+ console.error(`[check-secrets] could not read the diff (${diffArgs.join(' ')}): ${err.message}`);
+ process.exit(1);
+ }
+
+ // A brand-new file is invisible to `git diff HEAD`, and a pasted key file is
+ // exactly the shape that arrives untracked. Treat its every line as added.
+ if (!base) {
+ const untrackedArgs = ['ls-files', '--others', '--exclude-standard'];
+ if (paths.length) untrackedArgs.push('--', ...paths);
+ let untracked = [];
+ try {
+ untracked = git(untrackedArgs).split('\n').filter(Boolean);
+ } catch {
+ untracked = [];
+ }
+ for (const f of untracked) {
+ if (skippedContent(f)) continue;
+ let body;
+ try {
+ body = readFileSync(path.join(root, f), 'utf8');
+ } catch {
+ continue;
+ }
+ if (body.includes('\u0000')) continue;
+ diff += `\n+++ b/${f}\n@@ -0,0 +1 @@\n${body.split('\n').map((l) => `+${l}`).join('\n')}\n`;
+ }
+ }
+
+ let file = null;
+ let lineNo = 0;
+ for (const raw of diff.split('\n')) {
+ if (raw.startsWith('+++ ')) {
+ const p = raw.slice(4).replace(/^b\//, '');
+ file = p === '/dev/null' ? null : p;
+ if (file && !skippedContent(file)) filesScanned += 1;
+ continue;
+ }
+ if (raw.startsWith('@@')) {
+ const m = raw.match(/\+(\d+)/);
+ lineNo = m ? Number(m[1]) : 0;
+ continue;
+ }
+ if (!raw.startsWith('+') || raw.startsWith('+++')) continue;
+ const content = raw.slice(1);
+ if (file && !skippedContent(file)) {
+ for (const rule of CONTENT_RULES) {
+ if (rule.test(content) && !(rule.except && rule.except(content))) report(file, lineNo, rule, content);
+ }
+ }
+ lineNo += 1;
+ }
+}
+
+if (findings.length) {
+ console.error(`[check-secrets] ${findings.length} possible credential(s) in tracked or added content:\n`);
+ for (const f of findings) {
+ console.error(`[check-secrets] ${f.file}:${f.line} [${f.id}]`);
+ console.error(`[check-secrets] ${f.what}`);
+ console.error(`[check-secrets] > ${f.content}`);
+ }
+ console.error('\n[check-secrets] Remove it from the tree AND rotate the credential at the provider:');
+ console.error('[check-secrets] once a key reaches git, every clone and fork keeps a copy forever.');
+ console.error('[check-secrets] Real values belong in .env (gitignored), Secret Manager, or the Cloud Run service env.');
+ process.exit(1);
+}
+
+const scope = all ? `${filesScanned} tracked file(s)` : `${filesScanned} changed file(s)`;
+console.log(`[check-secrets] OK: no credential material in ${trackedFiles.length} tracked path(s) or ${scope}`);
diff --git a/scripts/lib/guard-proofs.mjs b/scripts/lib/guard-proofs.mjs
index 544387b0a..19f2daa08 100644
--- a/scripts/lib/guard-proofs.mjs
+++ b/scripts/lib/guard-proofs.mjs
@@ -1,7 +1,8 @@
// Shared vocabulary for guard proofs: the sandbox, the fixture applier, and the
// verdict model. scripts/prove-guards.mjs drives it, scripts/audit-guards.mjs
-// validates the declarations against it, and tests/prove-guards.test.js
-// exercises it without touching the real repository.
+// validates the declarations against it, and tests/audit-guards.test.js
+// exercises it against a synthetic registry without touching the real
+// repository.
//
// A "proof" answers a question the guard registry could not: does this guard
// still catch the thing it claims to catch? A registry entry is a claim. A
diff --git a/scripts/prove-guards.mjs b/scripts/prove-guards.mjs
index c44501f43..435a3af2a 100644
--- a/scripts/prove-guards.mjs
+++ b/scripts/prove-guards.mjs
@@ -36,17 +36,11 @@
// are reported as such rather than quietly counted as passing: an honest gap
// beats a fake green.
//
-// Usage:
-// node scripts/prove-guards.mjs prove everything, write results
-// node scripts/prove-guards.mjs --only <id,id> prove a subset
-// node scripts/prove-guards.mjs --stage gate prove one stage
-// node scripts/prove-guards.mjs --no-write do not touch public/guard-proofs.json
-// node scripts/prove-guards.mjs --keep leave the sandbox for inspection
-//
-// Exit 1 if any proof fails. Wired as `npm run prove:guards`.
+// See USAGE below for the flags. Exit 1 if any proof fails. Wired as
+// `npm run prove:guards`.
import { execFileSync, spawnSync } from 'node:child_process';
-import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -55,17 +49,47 @@ import { FAILING_VERDICTS, VERDICTS, normalizeProof, proveGuard } from './lib/gu
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const argv = process.argv.slice(2);
+const USAGE = `prove-guards: run every guard in data/guards.json against a declared violation.
+
+Usage:
+ node scripts/prove-guards.mjs prove everything, write results
+ node scripts/prove-guards.mjs --only <id,id> prove a subset
+ node scripts/prove-guards.mjs --stage gate prove one stage
+ node scripts/prove-guards.mjs --no-write do not touch public/guard-proofs.json
+ node scripts/prove-guards.mjs --keep leave the sandbox for inspection
+ node scripts/prove-guards.mjs --sandbox <dir> use an explicit sandbox path
+ node scripts/prove-guards.mjs --help print this and exit
+
+Each run builds a throwaway git worktree, runs every guard twice (clean, then
+mutated), and tears the worktree down. It never writes to the repository except
+public/guard-proofs.json.`;
+
const flag = (name) => argv.includes(`--${name}`);
function value(name) {
const i = argv.indexOf(`--${name}`);
return i === -1 ? null : argv[i + 1];
}
+// Before anything else: an unrecognized flag must not silently become a full
+// destructive run. `--help` did exactly that, and because the sandbox path was
+// shared it wrecked a real proof run in progress in another shell.
+if (flag('help') || argv.includes('-h')) {
+ console.log(USAGE);
+ process.exit(0);
+}
+
const only = (value('only') ?? '').split(',').map((s) => s.trim()).filter(Boolean);
const stageFilter = value('stage');
const write = !flag('no-write');
const keep = flag('keep');
-const sandboxDir = value('sandbox') ?? path.resolve(root, '..', '.guard-proof-wt');
+
+// The sandbox path is per-process by default. Concurrent agents share this
+// worktree (see CLAUDE.md), so a fixed path meant two simultaneous runs used
+// the SAME throwaway worktree: the second run's `git worktree remove` deleted
+// the first run's checkout mid-proof, and every remaining guard reported
+// "wrong reason" with `Cannot find module` as its evidence. That reads as 40
+// broken guards when nothing was broken but the harness.
+const sandboxDir = value('sandbox') ?? path.resolve(root, '..', `.guard-proof-wt-${process.pid}`);
const registry = JSON.parse(readFileSync(path.join(root, 'data/guards.json'), 'utf8'));
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
@@ -101,7 +125,46 @@ if (!selected.length) {
* would prove the last commit, which is precisely the version you are not
* asking about.
*/
+/**
+ * Remove sandboxes left behind by runs that died before their teardown.
+ *
+ * The teardown lives in a `finally`, which a SIGKILL or an OOM never reaches,
+ * so a crashed run leaves both a directory and a registered git worktree. They
+ * accumulate on disk exactly like the deploy worktrees `npm run clean:worktrees`
+ * exists to reclaim. A sandbox is only reclaimed when its owning process is
+ * gone, so a concurrent run in another shell is never touched.
+ */
+function reapAbandonedSandboxes() {
+ const parent = path.dirname(sandboxDir);
+ let entries;
+ try {
+ entries = readdirSync(parent);
+ } catch {
+ return;
+ }
+ for (const name of entries) {
+ const match = /^\.guard-proof-wt-(\d+)$/.exec(name);
+ if (!match) continue;
+ const pid = Number(match[1]);
+ if (pid === process.pid) continue;
+ try {
+ process.kill(pid, 0);
+ continue;
+ } catch (err) {
+ // EPERM means the pid exists but belongs to another user, so it is
+ // still live. Only ESRCH proves the owner is gone.
+ if (err.code !== 'ESRCH') continue;
+ }
+ const stale = path.join(parent, name);
+ spawnSync('git', ['worktree', 'remove', '--force', stale], { cwd: root });
+ rmSync(stale, { recursive: true, force: true });
+ console.log(`[prove-guards] reclaimed abandoned sandbox ${stale} (owner pid ${pid} is gone)`);
+ }
+ spawnSync('git', ['worktree', 'prune'], { cwd: root });
+}
+
function buildSandbox() {
+ reapAbandonedSandboxes();
if (existsSync(sandboxDir)) {
spawnSync('git', ['worktree', 'remove', '--force', sandboxDir], { cwd: root });
rmSync(sandboxDir, { recursive: true, force: true });
diff --git a/scripts/schedule-event.mjs b/scripts/schedule-event.mjs
index 1281edd27..af6b786d3 100644
--- a/scripts/schedule-event.mjs
+++ b/scripts/schedule-event.mjs
@@ -67,7 +67,10 @@ try {
doc = JSON.parse(readFileSync(CONFIG_PATH, 'utf8'));
} catch (err) {
console.error(`[event-schedule] cannot read public/event.json: ${err?.message || err}`);
- console.error('[event-schedule] Create it from a previous event (git show HEAD:public/event.json) before scheduling.');
+ console.error('[event-schedule] Between events the file is deleted on purpose, so HEAD may not carry one.');
+ console.error('[event-schedule] Restore the last shipped config, then schedule on top of it:');
+ console.error('[event-schedule] git show "$(git rev-list -1 HEAD -- public/event.json)^:public/event.json" > public/event.json');
+ console.error('[event-schedule] Or write a fresh one from the template in docs/play-live-events.md.');
process.exit(1);
}
diff --git a/scripts/setup-git-hooks.mjs b/scripts/setup-git-hooks.mjs
index c671dffcc..4860ede07 100644
--- a/scripts/setup-git-hooks.mjs
+++ b/scripts/setup-git-hooks.mjs
@@ -8,9 +8,14 @@
// commit-content rules is pre-push: it sees exactly the commits leaving the
// machine, after all local churn has settled.
//
+// scripts/check-secrets.mjs rides the same path for the same reason, and with a
+// sharper deadline: a credential that reaches a remote is copied by every clone
+// and fork, so deleting the line later does not undo the leak. Pre-push is the
+// last moment a block is still cheaper than a rotation.
+//
// Design constraints, in order:
-// 1. Scoped to the push. The hook runs check-rules with --base <remote sha>
-// --head <local sha> per pushed ref, so it judges only the commits being
+// 1. Scoped to the push. The hook runs both guards with --base <remote sha>
+// --head <local sha> per pushed ref, so they judge only the commits being
// pushed. Concurrent agents' in-flight worktree edits are invisible to it.
// This is why the hook does NOT run `npm run gate` or working-tree checks:
// on a worktree shared by several agents those block your push on someone
@@ -32,15 +37,18 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
-const MARKER = 'three.ws pre-push hook v1';
+const MARKER = 'three.ws pre-push hook v2';
const HOOK = `#!/bin/sh
# ${MARKER} (installed by scripts/setup-git-hooks.mjs; edits here are overwritten
# on the next npm install, change the installer instead).
#
-# Enforces the CLAUDE.md hard rules on the commits being pushed, scoped to
-# exactly those commits (never the shared working tree), then hands the refs to
-# git-lfs. Emergency bypass: SKIP_PUSH_CHECKS=1 git push
+# Enforces the CLAUDE.md hard rules, and the no-credentials-in-git rule, on the
+# commits being pushed, scoped to exactly those commits (never the shared
+# working tree), then hands the refs to git-lfs. Both checks are diff scoped for
+# the same reason: a worktree-state audit would block a requested push on
+# another agent's in-flight work.
+# Emergency bypass: SKIP_PUSH_CHECKS=1 git push
input="$(cat)"
zero=0000000000000000000000000000000000000000
@@ -56,11 +64,12 @@ if [ -z "$SKIP_PUSH_CHECKS" ] && command -v node >/dev/null 2>&1; then
[ "$remote_sha" = "$zero" ] && continue
git cat-file -e "$remote_sha" 2>/dev/null || continue
node scripts/check-rules.mjs --base "$remote_sha" --head "$local_sha" || { status=1; break; }
+ node scripts/check-secrets.mjs --base "$remote_sha" --head "$local_sha" || { status=1; break; }
done
exit "$status"
} || {
echo >&2 ""
- echo >&2 "pre-push: CLAUDE.md hard-rule violations in the commits being pushed."
+ echo >&2 "pre-push: CLAUDE.md hard-rule or credential violations in the commits being pushed."
echo >&2 "pre-push: fix them, or bypass once with: SKIP_PUSH_CHECKS=1 git push"
exit 1
}
diff --git a/scripts/sync-tour-global.mjs b/scripts/sync-tour-global.mjs
new file mode 100644
index 000000000..11e47202a
--- /dev/null
+++ b/scripts/sync-tour-global.mjs
@@ -0,0 +1,54 @@
+#!/usr/bin/env node
+// Rebuild @three-ws/tour's CDN bundle and sync it into public/tour-builder/.
+// =========================================================================
+// The Tour Builder page (/tour-builder) previews a REAL tour, not a mockup, by
+// loading /tour-builder/tour.global.js — the same IIFE the package publishes to
+// unpkg. That file used to be a hand-copied build output with nothing producing
+// it, so it drifted: the copy served to visitors was built against an older
+// walk-sdk than the one in this repo. This script is the missing wiring.
+//
+// node scripts/sync-tour-global.mjs # rebuild + copy
+// node scripts/sync-tour-global.mjs --check # fail if the copy is stale
+//
+// The bundle's //# sourceMappingURL comment is stripped on the way in: the map
+// is 3.6 MB of build output nobody ships to the edge, and leaving the comment
+// makes every visitor's devtools request a 404.
+
+import { execFileSync } from 'node:child_process';
+import { readFileSync, writeFileSync, existsSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const sdkDir = resolve(root, 'tour-sdk');
+const built = resolve(sdkDir, 'dist/tour.global.js');
+const target = resolve(root, 'public/tour-builder/tour.global.js');
+const check = process.argv.includes('--check');
+
+execFileSync('node', ['build.mjs'], { cwd: sdkDir, stdio: 'inherit' });
+
+if (!existsSync(built)) {
+ console.error('[sync-tour-global] tour-sdk build produced no dist/tour.global.js');
+ process.exit(1);
+}
+
+const next = readFileSync(built, 'utf8').replace(/\n?\/\/# sourceMappingURL=.*\n?$/, '\n');
+const current = existsSync(target) ? readFileSync(target, 'utf8') : null;
+const kb = (s) => Math.round(s.length / 1024);
+
+if (current === next) {
+ console.log(`[sync-tour-global] public/tour-builder/tour.global.js up to date (${kb(next)} kB)`);
+ process.exit(0);
+}
+
+if (check) {
+ console.error(
+ '[sync-tour-global] public/tour-builder/tour.global.js is stale — run `npm run build:tour-global`',
+ );
+ process.exit(1);
+}
+
+writeFileSync(target, next);
+console.log(
+ `[sync-tour-global] wrote public/tour-builder/tour.global.js (${kb(next)} kB, was ${current ? `${kb(current)} kB` : 'absent'})`,
+);
diff --git a/scripts/x402-modal-e2e.mjs b/scripts/x402-modal-e2e.mjs
new file mode 100644
index 000000000..e271f1d79
--- /dev/null
+++ b/scripts/x402-modal-e2e.mjs
@@ -0,0 +1,138 @@
+#!/usr/bin/env node
+// Real-browser conformance for x402-modal-sdk (@three-ws/x402-modal).
+//
+// The package's `npm test` is a zero-dependency `node --test` run, so it covers
+// the protocol and helper layers but cannot open the modal. This script covers
+// what only a browser can: the global build binding `[data-x402-endpoint]`, the
+// modal mounting and completing real discovery against a live three.ws x402
+// route, cancellation staying silent, and the `data-x402-*` script-tag config
+// applying under BOTH documented CDN URL shapes (the extensionless
+// `unpkg.com/@three-ws/x402-modal/global` subpath and a self-hosted
+// `x402.global.js`).
+//
+// Run from the repo root, after `npm --prefix x402-modal-sdk run build`:
+//
+// node scripts/x402-modal-e2e.mjs
+//
+// Exits non-zero on the first failed assertion. Needs network: the demo route
+// (https://three.ws/api/x402/dance-tip) is a live paid endpoint, probed only as
+// far as its 402 challenge. Nothing is signed and nothing is spent.
+
+import { createServer } from 'node:http';
+import { readFile } from 'node:fs/promises';
+import { extname, join, normalize, resolve } from 'node:path';
+import assert from 'node:assert/strict';
+import { chromium } from 'playwright';
+
+const ROOT = resolve(import.meta.dirname, '..', 'x402-modal-sdk');
+const DEMO = 'https://three.ws/api/x402/dance-tip?dancer=1&dance=rumba';
+const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.map': 'application/json' };
+
+// One static server for the package dir, plus two synthetic pages that load the
+// same global build under different URL shapes.
+const GLOBAL_BUILD = await readFile(join(ROOT, 'dist/x402.global.js')).catch(() => {
+ console.error('dist/ is missing. Run: npm --prefix x402-modal-sdk run build');
+ process.exit(1);
+});
+
+const configPage = (src) => `<!doctype html><meta charset="utf-8"><body>
+<script type="module" src="${src}" data-x402-brand-label="Powered by Acme" data-x402-brand-href="https://acme.com"></script>
+<button id="pay" data-x402-endpoint="${DEMO}">Pay</button>
+</body>`;
+
+const server = createServer(async (req, res) => {
+ const path = new URL(req.url, 'http://x').pathname;
+ // The CDN's extensionless subpath, serving the same bytes as the file.
+ if (path === '/global') {
+ res.writeHead(200, { 'content-type': 'text/javascript' });
+ return res.end(GLOBAL_BUILD);
+ }
+ if (path === '/cdn-form.html') return html(res, configPage('/global'));
+ if (path === '/file-form.html') return html(res, configPage('/dist/x402.global.js'));
+ try {
+ const file = join(ROOT, normalize(decodeURIComponent(path)));
+ res.writeHead(200, { 'content-type': MIME[extname(file)] || 'application/octet-stream' });
+ res.end(await readFile(file));
+ } catch {
+ res.writeHead(404).end('not found');
+ }
+});
+const html = (res, body) => { res.writeHead(200, { 'content-type': 'text/html' }); res.end(body); };
+
+await new Promise((r) => server.listen(0, '127.0.0.1', r));
+const origin = `http://127.0.0.1:${server.address().port}`;
+
+const browser = await chromium.launch();
+const checks = [];
+const check = (name, fn) => { fn(); checks.push(name); console.log(` ok ${name}`); };
+
+// A 402 is the protocol working, not a page error; everything else is a real failure.
+const watch = (page, errors) => {
+ page.on('pageerror', (e) => errors.push(`pageerror: ${e.message}`));
+ page.on('console', (m) => {
+ if (m.type() === 'error' && !/status of 402/.test(m.text())) errors.push(m.text());
+ });
+};
+
+const priceResolved = () => !/resolving/.test(document.querySelector('[data-network]')?.textContent || '');
+
+try {
+ console.log('examples/index.html');
+ const errors = [];
+ const page = await browser.newPage();
+ watch(page, errors);
+ await page.goto(`${origin}/examples/index.html`, { waitUntil: 'networkidle' });
+
+ const api = await page.evaluate(() => Object.keys(window.X402 || {}));
+ check('the global build exposes window.X402', () => assert.deepEqual(api.sort(), ['configure', 'discover', 'init', 'pay', 'version']));
+ check('it auto-binds [data-x402-endpoint]', async () => assert.equal(await page.getAttribute('#declarative', 'data-x402-bound'), '1'));
+
+ // Declarative button: modal mounts and runs real discovery against the live route.
+ await page.click('#declarative');
+ await page.waitForSelector('.x402-overlay .x402-modal', { timeout: 15_000 });
+ await page.waitForFunction(priceResolved, { timeout: 30_000 });
+ const price = (await page.textContent('[data-price]'))?.trim();
+ const network = (await page.textContent('[data-network]'))?.trim();
+ check('discovery resolves a real price from the live 402', () => assert.match(price, /^[\d.]+\s*USDC$/));
+ check('discovery resolves the network', () => assert.ok(network && network !== 'resolving'));
+
+ // Escape cancels; cancellation must not surface as an error to the merchant.
+ await page.keyboard.press('Escape');
+ await page.waitForFunction(() => !document.querySelector('.x402-overlay'), { timeout: 10_000 });
+ const out = (await page.textContent('#declarative-out'))?.trim();
+ check('cancelling closes the modal without firing x402:error', () => assert.doesNotMatch(out, /^Error:/));
+
+ // Programmatic pay() rejects with code 'cancelled' when the user closes it.
+ await page.click('#programmatic');
+ await page.waitForSelector('.x402-overlay .x402-modal', { timeout: 15_000 });
+ await page.waitForFunction(priceResolved, { timeout: 30_000 });
+ await page.click('.x402-close');
+ await page.waitForFunction(() => document.querySelector('#programmatic-out')?.textContent === 'cancelled.', { timeout: 10_000 });
+ check("pay() rejects with code 'cancelled' on close", () => assert.ok(true));
+
+ // discover() runs headless in the page, off the ESM build.
+ const accepts = await page.evaluate(async ([o, demo]) => {
+ const { discover } = await import(`${o}/dist/x402-modal.mjs`);
+ return (await discover({ endpoint: demo })).accepts.map((a) => a.network);
+ }, [origin, DEMO]);
+ check('discover() returns accepts[] without opening any UI', () => assert.ok(accepts.length > 0));
+ check('the page logged no unexpected errors', () => assert.deepEqual(errors, []));
+ await page.close();
+
+ // The data-x402-* script-tag config must apply under both documented URL shapes.
+ console.log('data-x402-* script-tag config');
+ for (const [label, path] of [['CDN subpath (/global)', '/cdn-form.html'], ['self-hosted file (x402.global.js)', '/file-form.html']]) {
+ const p = await browser.newPage();
+ await p.goto(`${origin}${path}`, { waitUntil: 'networkidle' });
+ await p.click('#pay');
+ await p.waitForSelector('.x402-foot', { timeout: 15_000 });
+ const foot = (await p.textContent('.x402-foot'))?.replace(/\s+/g, ' ').trim();
+ check(`brand override applies via ${label}`, () => assert.match(foot, /Powered by Acme/));
+ await p.close();
+ }
+
+ console.log(`\n${checks.length} checks passed.`);
+} finally {
+ await browser.close();
+ server.close();
+}