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.

8.7 KB
Raw Blame
#!/usr/bin/env node
/**
 * Guard the <model-viewer> pin.
 *
 * Google's <model-viewer> registers itself as a custom element, so the second
 * `customElements.define('model-viewer', ...)` in one document throws and the
 * later surface renders nothing. A three.ws embed pasted onto a page that also
 * carries another three.ws surface is exactly that document, which is why every
 * reference in this repo must name ONE build. What legitimately differs per
 * surface is delivery, not version: a top-level document carries an SRI hash, a
 * server-interpolated embed does not, and the Vite pages walk a CDN failover
 * chain that cannot pin one hash. api/_lib/model-viewer-cdn.js explains each rung.
 *
 * Nothing enforced that, and it drifted: eight of eighty-one references sat a
 * major version behind the rest. This checks three things offline:
 *
 *   1. every model-viewer URL in tracked source names the same version,
 *   2. no version is served with two different integrity hashes (the shape a
 *      half-finished bump leaves behind: URL updated, SRI forgotten),
 *   3. the vendored copy under pages/ibm/vendor/ still hashes to the build the
 *      rest of the tree points at.
 *
 *   node scripts/check-model-viewer-version.mjs
 */

import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';

// The offline copy of the library that pages/ibm serves itself.
const VENDORED = 'pages/ibm/vendor/model-viewer.min.js';

// Both URL shapes in use: Google's hosted path form and the npm CDN form.
//
// The version is captured as "everything up to the next path separator or
// quote", NOT as \d+\.\d+\.\d+, so a semver RANGE is caught rather than
// skipped. An earlier digits-only pattern silently ignored
// `@google/model-viewer@^3.5.0` on the published cookbook page, which therefore
// served 3.5.0 to real visitors for as long as the guard reported the tree
// clean. A range is never a valid pin here anyway: the whole point is that every
// surface loads one identical build, and `^3.5.0` resolves to whatever the CDN
// last published. Anything that is not exactly the pinned version now fails.
const URL_RE =
	/(?:ajax\.googleapis\.com\/ajax\/libs\/model-viewer\/([^/"'`\s]+)|@google\/model-viewer@([^/"'`\s]+))/g;
// Integrity is read per <script> TAG, never from a character window around the
// URL: pages routinely load model-viewer next to another SRI-pinned CDN script
// (highlight.js on /tutorial), and a window wide enough to reach the attribute
// is also wide enough to steal the neighbour's hash.
const SCRIPT_TAG_RE = /<script\b[^>]*>/gi;
const INTEGRITY_RE = /integrity=["'](sha\d{3}-[A-Za-z0-9+/=]+)["']/i;

const SCANNED = /\.(js|mjs|cjs|jsx|ts|tsx|html|htm|md|json|svelte|vue|py|ipynb)$/;

// Not real references, so not this guard's business:
//   _generated/  point-in-time captures of past runs (audit baselines, recorded
//                MCP responses). Records of what shipped then, not pins to bump.
//   *.min.js     the vendored library itself, which names its own version.
//   guards.json  the guard registry carries THIS guard's proof fixture inline
//                (a deliberately wrong version the harness writes to a temp file
//                and expects us to reject). Reading it back as a real reference
//                would make the guard fail on its own proof, forever.
//   this file    the guard's own source spells the URL shapes it looks for, so
//                scanning itself would report its own regex as a reference.
const SKIPPED = [
	/\/_generated\//,
	/\.min\.js$/,
	/^node_modules\//,
	/(^|\/)guards\.json$/,
	/(^|\/)check-model-viewer-version\.mjs$/,
];

// A reference whose version is a template interpolation (`@google/model-viewer@
// ${VERSION}`) IS the single-sourcing this guard exists to encourage: the value
// comes from one constant. Read past it rather than reporting "${VERSION}" as a
// rogue sixth version.
const INTERPOLATED = /^\$\{/;

// Published builds that must never be the pin again, with the reason. 4.3.x is
// the first line that decodes KHR_meshopt_compression (api/_lib/bake.js emits
// it), but Google shipped it with debug console.log calls left in
// ("[$updateSource] called!", "BAILING OUT EARLY!", "IntersectionObserver
// fired!"), so every page with a viewer flooded the visitor's console. Fixed
// upstream in 4.4.0 (google/model-viewer#5182).
const BANNED = {
	'4.3.0': 'ships leftover debug console.log calls on every source update (fixed in 4.4.0)',
	'4.3.1': 'ships leftover debug console.log calls on every source update (fixed in 4.4.0)',
};

function trackedFiles() {
	const listed = (args) => execFileSync('git', args, { encoding: 'utf8', maxBuffer: 1 << 28 }).split('\n');
	return [...listed(['ls-files']), ...listed(['ls-files', '-o', '--exclude-standard'])]
		.filter(Boolean)
		.filter((p) => SCANNED.test(p))
		.filter((p) => !SKIPPED.some((re) => re.test(p)))
		.sort();
}

function digest(path, algo = 'sha384') {
	return `${algo}-${createHash(algo).update(readFileSync(path)).digest('base64')}`;
}

// version -> Set(file), and version -> Map(integrity -> Set(file))
const versions = new Map();
const integrities = new Map();
let refs = 0;

for (const file of trackedFiles()) {
	let text;
	try {
		text = readFileSync(file, 'utf8');
	} catch {
		continue;
	}
	if (!text.includes('model-viewer')) continue;

	for (const match of text.matchAll(URL_RE)) {
		const version = match[1] || match[2];
		if (INTERPOLATED.test(version)) continue;
		refs += 1;
		if (!versions.has(version)) versions.set(version, new Set());
		versions.get(version).add(file);
	}

	for (const tag of text.match(SCRIPT_TAG_RE) || []) {
		URL_RE.lastIndex = 0;
		const url = URL_RE.exec(tag);
		if (!url) continue;
		const version = url[1] || url[2];
		if (INTERPOLATED.test(version)) continue;
		const integrity = tag.match(INTEGRITY_RE)?.[1];
		if (!integrity) continue;
		if (!integrities.has(version)) integrities.set(version, new Map());
		const byHash = integrities.get(version);
		if (!byHash.has(integrity)) byHash.set(integrity, new Set());
		byHash.get(integrity).add(file);
	}
}

const failures = [];

if (versions.size === 0) {
	failures.push('found no <model-viewer> references at all: this guard is scanning the wrong thing');
} else if (versions.size > 1) {
	const ranked = [...versions.entries()].sort((a, b) => b[1].size - a[1].size);
	const [canonical] = ranked[0];
	const lines = ranked
		.slice(1)
		.map(([v, files]) => `    ${v} in ${files.size} file(s):\n${[...files].map((f) => `      ${f}`).join('\n')}`);
	failures.push(
		`${versions.size} model-viewer versions in the tree; the majority is ${canonical}.\n` +
			`${lines.join('\n')}\n` +
			`    Two builds can collide in one document. Move every reference to one version.`,
	);
}

for (const [version, files] of versions) {
	if (!BANNED[version]) continue;
	failures.push(`model-viewer ${version} ${BANNED[version]}; it is referenced in ${files.size} file(s), e.g. ${[...files][0]}`);
}

for (const [version, byHash] of integrities) {
	if (byHash.size < 2) continue;
	const lines = [...byHash.entries()].map(
		([hash, files]) => `    ${hash}\n${[...files].map((f) => `      ${f}`).join('\n')}`,
	);
	failures.push(
		`model-viewer ${version} is served with ${byHash.size} different integrity hashes:\n${lines.join('\n')}\n` +
			`    One of these is stale (a bumped URL with its SRI left behind). Recompute:\n` +
			`      curl -s https://cdn.jsdelivr.net/npm/@google/model-viewer@${version}/dist/model-viewer.min.js | openssl dgst -sha384 -binary | openssl base64 -A`,
	);
}

// The vendored copy must be the same build everything else points at.
const [pinned] = [...versions.keys()];
if (versions.size === 1 && integrities.has(pinned)) {
	const [expected] = [...integrities.get(pinned).keys()];
	let actual;
	try {
		actual = digest(VENDORED, expected.split('-')[0]);
	} catch {
		actual = null;
	}
	if (actual === null) {
		failures.push(`${VENDORED} is missing; the pages/ibm hosted page has no model-viewer to serve`);
	} else if (actual !== expected) {
		failures.push(
			`${VENDORED} is not the pinned ${pinned} build.\n` +
				`    expected ${expected}\n` +
				`    actual   ${actual}\n` +
				`    Restage it:\n` +
				`      curl -sSfo ${VENDORED} https://cdn.jsdelivr.net/npm/@google/model-viewer@${pinned}/dist/model-viewer.min.js`,
		);
	}
}

if (failures.length) {
	console.error('[check-model-viewer-version] the <model-viewer> pin has drifted:\n');
	for (const failure of failures) console.error(`  ${failure}\n`);
	console.error('Background: api/_lib/model-viewer-cdn.js explains why one version is load-bearing.');
	process.exit(1);
}

console.log(
	`[check-model-viewer-version] OK: ${refs} references across ${[...versions.values()][0].size} files all pin ${pinned}` +
		(integrities.has(pinned) ? `, one integrity hash, vendored copy matches` : ''),
);