Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(embed): freeze each agent-3d release so its immutable URL and SRI hash never change
nirholasbde1f4975133
diff --git a/.agents/skills/embed-three-ws-avatar/SKILL.md b/.agents/skills/embed-three-ws-avatar/SKILL.mdindex 088a96284..74cac29be 100644--- a/.agents/skills/embed-three-ws-avatar/SKILL.md+++ b/.agents/skills/embed-three-ws-avatar/SKILL.md@@ -22,7 +22,7 @@ the three.ws CDN with `access-control-allow-origin: *`, so it loads from any ori<scripttype="module"src="https://three.ws/agent-3d/1.5.2/agent-3d.js"- integrity="sha384-xkFDjVP866hYt7voUhfnQHj6IO4hYxA6n8Laupk+VtD6y+IKiO/AZdE3VbfLtg0C"+ integrity="sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q"crossorigin="anonymous"></script>diff --git a/README.md b/README.mdindex 852100d12..17d52cfea 100644--- a/README.md+++ b/README.md@@ -11030,7 +11030,8 @@ plan_quotas (plan, max_avatars, max_bytes_per_avatar, max_total_bytes)| `npm run build:lib` | Build `<agent-3d>` web component library to `dist-lib/` || `npm run build:artifact` | Build standalone Claude artifact viewer bundle || `npm run build:all` | Chat build, then `build` + `build:lib` + `build:rider` in parallel |-| `npm run publish:lib` | Publish versioned CDN bundles to `/agent-3d/` |+| `npm run publish:lib` | Lay out the `/agent-3d/` CDN: released versions from the archive, channels from the build |+| `npm run release:lib` | Cut a new `<agent-3d>` release: archive its bytes once, record their SRI hashes || `npm run test` | Vitest unit suite + Playwright end-to-end suite || `npm run test:e2e` | Playwright end-to-end suite only || `npm run verify` | Prettier check + Vite build (pre-deploy gate) |diff --git a/data/agent-3d-releases.json b/data/agent-3d-releases.jsonnew file mode 100644index 000000000..fe6c6e1a5--- /dev/null+++ b/data/agent-3d-releases.json@@ -0,0 +1,14 @@+{+ "$comment": "Released <agent-3d> CDN versions and the exact bytes each one is. Written only by `npm run release:lib`; scripts/publish-lib.mjs serves every version listed here from the archive (verified against these hashes) under its immutable /agent-3d/<version>/ path, and scripts/check-dist.mjs fails a build whose dist or documented SRI pins disagree with it. See docs/web-component.md#cdn-versioning.",+ "archive": "https://storage.googleapis.com/three-ws-lib-releases/agent-3d",+ "releases": {+ "1.5.2": {+ "publishedAt": "2026-10-01T19:22:44.064Z",+ "source": "https://three.ws/agent-3d/1.5.2/",+ "integrity": {+ "agent-3d.js": "sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q",+ "agent-3d.umd.cjs": "sha384-z74vjNbQ8KKXBZHL6JFhl4h45B+InYbzbV8ArjZSgzR+ATWOEthqu0S/eadTA0XC"+ }+ }+ }+}diff --git a/data/changelog.json b/data/changelog.jsonindex 1a697dcd3..d8fe0affa 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-01",+ "title": "Pinned agent-3d embeds keep working after every update",+ "summary": "If you embedded the 3D avatar component with a pinned version and an integrity hash, as our docs recommend for production, the embed could stop loading after one of our updates: the file behind a version that is promised never to change was being rebuilt each time we shipped, so its fingerprint changed and browsers refused to run it. A released version is now frozen for good, every update serves exactly the same file under it, and the build fails if any hash in our docs, skills or code snippets ever disagrees with the file it points to. Version 1.5.2 is frozen as it is served today; if your page pins an older hash for 1.5.2, update it once from /agent-3d/1.5.2/integrity.json.",+ "tags": ["fix", "sdk"],+ "link": "/docs/web-component"+ },{"date": "2026-10-01","title": "Search the 3D asset catalog from any AI client without an account",diff --git a/docs/ALL.md b/docs/ALL.mdindex 9a1777bc1..48944edd0 100644--- a/docs/ALL.md+++ b/docs/ALL.md@@ -121674,7 +121674,7 @@ One script tag, one element. Create `index.html`:<scripttype="module"src="https://three.ws/agent-3d/1.5.2/agent-3d.js"- integrity="sha384-qCG5gH4q2+k2Gsf98zs9RFXyN8iezoklCWt63pA2Xk2YF7Onae4rfUwu+oZSqRzN"+ integrity="sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q"crossorigin="anonymous"></script>diff --git a/docs/embedding.md b/docs/embedding.mdindex e4e2afbb6..21e94b31b 100644--- a/docs/embedding.md+++ b/docs/embedding.md@@ -268,7 +268,7 @@ The RAF loop pauses when the element is fully off-screen and resumes on re-entry| `/agent-3d/1/agent-3d.js` | 5 min | Follow minor + patch releases || `/agent-3d/latest/agent-3d.js` | 5 min | Demos and prototypes only |-The current SRI hash for each release is at `/agent-3d/<version>/integrity.json`. A UMD build (`agent-3d.umd.cjs`) is available at the same paths for non-ESM environments.+The current SRI hash for each release is at `/agent-3d/<version>/integrity.json`. A released version's bytes are frozen, so its hash never goes stale; the moving channels follow the current build and are not for SRI pinning ([details](./web-component.md#what-immutable-guarantees)). A UMD build (`agent-3d.umd.cjs`) is available at the same paths for non-ESM environments.---diff --git a/docs/sdk.md b/docs/sdk.mdindex 0ab2b4598..27fcb9696 100644--- a/docs/sdk.md+++ b/docs/sdk.md@@ -383,7 +383,9 @@ The `build:lib` step runs Vite with `TARGET=lib`. The output is a self-containednode scripts/publish-lib.mjs```-This copies `dist-lib/agent-3d.js` and `dist-lib/agent-3d.umd.cjs` into `dist/agent-3d/<version>/` and creates channel aliases (`<major>`, `<major>.<minor>`, `latest`). It also emits SRI hashes and a `versions.json` manifest so embedders can pin with `integrity` attributes.+This copies the current build (`dist-lib/agent-3d.js` and `dist-lib/agent-3d.umd.cjs`) into the moving channels (`<major>`, `<major>.<minor>`, `latest`), lays out every released version under `dist/agent-3d/<version>/` from the release archive (verified against the SRI hashes in `data/agent-3d-releases.json`, never from the current build), and writes the `versions.json` manifest embedders pin from. It fails when `package.json` names a version that has not been released.++To release new code under a pinned URL, bump `package.json` and run `npm run release:lib`: it builds the library, archives the bytes once, and records their hashes. See [CDN versioning](./web-component.md#cdn-versioning) for the guarantees.Requires the library bundle to have been built first. It's also wired as the `npm run publish:lib` script, and runs automatically inside the production build: `npm run build:gcp` chains `build:lib:full` (which emits both the ES and UMD formats) straight into `publish:lib`, then verifies the result with `check:dist`.diff --git a/docs/security.md b/docs/security.mdindex dc7611fc6..90c0a3150 100644--- a/docs/security.md+++ b/docs/security.md@@ -124,7 +124,7 @@ Pin the exact bundle version and validate with Subresource Integrity:></script>```-SRI hashes for each release are at `/agent-3d/<version>/integrity.json`. The `latest` channel (served with `max-age=3600, s-maxage=300, stale-while-revalidate=86400`) should never be used in production; use a pinned `MAJOR.MINOR.PATCH` URL, which is served with `max-age=31536000, immutable`.+SRI hashes for each release are at `/agent-3d/<version>/integrity.json`, and a released version's bytes never change, so the hash stays valid for as long as the release exists ([how releases are frozen](./web-component.md#what-immutable-guarantees)). The `latest` channel (served with `max-age=3600, s-maxage=300, stale-while-revalidate=86400`) should never be used in production; use a pinned `MAJOR.MINOR.PATCH` URL, which is served with `max-age=31536000, immutable`.### postMessage securitydiff --git a/docs/tutorials/character-library-to-embed.md b/docs/tutorials/character-library-to-embed.mdindex 80c4b6c9f..b7423c797 100644--- a/docs/tutorials/character-library-to-embed.md+++ b/docs/tutorials/character-library-to-embed.md@@ -209,7 +209,7 @@ One script tag, one element. Create `index.html`:<scripttype="module"src="https://three.ws/agent-3d/1.5.2/agent-3d.js"- integrity="sha384-qCG5gH4q2+k2Gsf98zs9RFXyN8iezoklCWt63pA2Xk2YF7Onae4rfUwu+oZSqRzN"+ integrity="sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q"crossorigin="anonymous"></script>diff --git a/docs/web-component.md b/docs/web-component.mdindex 6c8b5e593..cecbd41e6 100644--- a/docs/web-component.md+++ b/docs/web-component.md@@ -1036,15 +1036,45 @@ Three URL channels are available. Pick based on how strictly you need to control| Path | Cache | Use when ||------|-------|----------|| `/agent-3d/<MAJOR>.<MINOR>.<PATCH>/agent-3d.js` | `immutable` | **Production.** Pin exact bytes. Combine with SRI. |-| `/agent-3d/<MAJOR>.<MINOR>/agent-3d.js` | 5 min | Follow patch releases automatically. |-| `/agent-3d/<MAJOR>/agent-3d.js` | 5 min | Follow minor + patch releases. |+| `/agent-3d/<MAJOR>.<MINOR>/agent-3d.js` | 5 min | Follow the newest code on this minor line. |+| `/agent-3d/<MAJOR>/agent-3d.js` | 5 min | Follow the newest code on this major line. || `/agent-3d/latest/agent-3d.js` | 5 min | Demos and prototypes only. Never in production. |+### What "immutable" guarantees++A `MAJOR.MINOR.PATCH` URL serves the same bytes for as long as that release exists, so+an `integrity` hash taken from it never goes stale. Each version is cut exactly once:++- `npm run release:lib` builds the library, uploads `agent-3d.js` and `agent-3d.umd.cjs`+ to a write-once archive (`gs://three-ws-lib-releases/agent-3d/<version>/`, public at+ `https://storage.googleapis.com/three-ws-lib-releases/agent-3d/<version>/`), and records+ their SRI hashes in [`data/agent-3d-releases.json`](../data/agent-3d-releases.json). It+ refuses to re-cut a version that already exists with different bytes: bump+ `package.json` instead.+- Every deploy (`scripts/publish-lib.mjs`, inside `build:gcp`) serves each released+ version from that archive, after checking the bytes against the recorded hash. It never+ writes a version directory from the current build.+- The moving channels (`<MAJOR>.<MINOR>`, `<MAJOR>`, `latest`) serve the build that is+ currently deployed, which can be newer than the newest release. `versions.json` marks+ them `"build": "current"` and lists that build's hashes under `currentBuild`; do not+ pin those hashes, because the next deploy replaces them.+- `check:dist` fails a build when a released file in `dist/` does not hash to its+ recorded value, when `versions.json` advertises anything else, or when a documented+ `integrity` pin in the docs or skills disagrees with the release it names.+ `npm run check:sri-pins -- --fix` rewrites stale documented pins from the ledger, and+ the same check runs under `npm test`.++Before 2026-10-01 the version directory was rebuilt on every deploy while the version+string stayed at 1.5.2, so its bytes, and therefore its hash, changed under every pinned+embed. 1.5.2 is now frozen at the bytes production served on that date+(`sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q`); a pin taken+from an earlier deploy has to be updated to that value once.+Current SRI hashes are at `/agent-3d/<version>/integrity.json`. The full release manifest is at `/agent-3d/versions.json`, or from the origin API at `/api/agent-3d/versions`, which serves the identical JSON with an `ETag`:```bashcurl -s https://three.ws/api/agent-3d/versions-# {"latest":"1.5.2","channels":{…},"publishedAt":"2026-08-10T16:20:09.870Z"}+# {"latest":"1.5.2","channels":{"1.5.2":{"integrity":{…},"immutable":true,…},…},"currentBuild":{…},"publishedAt":"…"}# Poll cheaply: an unchanged manifest answers 304 with no body.curl -s -o /dev/null -w '%{http_code}\n' \@@ -1060,7 +1090,7 @@ Both are CORS-open (`access-control-allow-origin: *`) and cached for 60 seconds.<scripttype="module"src="https://three.ws/agent-3d/1.5.2/agent-3d.js"- integrity="sha384-…"+ integrity="sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q"crossorigin="anonymous"></script>```diff --git a/package.json b/package.jsonindex 5af59ea26..c72e72895 100644--- a/package.json+++ b/package.json@@ -336,6 +336,7 @@"build:avatar-sdk": "node avatar-sdk/build.mjs","build:artifact": "vite build --config vite.config.artifact.js","publish:lib": "node scripts/publish-lib.mjs",+ "check:sri-pins": "node scripts/check-sri-pins.mjs","publish:packages": "node scripts/publish-packages.mjs","publish:packages:dry": "node scripts/publish-packages.mjs --dry-run","publish:queue:dry": "node scripts/publish-npm-queue.mjs",@@ -352,7 +353,7 @@"build:vercel": "npm run build:production","apply:r2-cors": "node scripts/set-r2-cors.mjs || echo '[apply:r2-cors] skipped (missing creds or transient failure — see build log)'","build:all": "npm run build:chat && (npm run build & npm run build:lib & wait)",- "release:lib": "npm run build:lib && npm run publish:lib",+ "release:lib": "npm run build:lib:full && node scripts/release-lib.mjs","clean": "rm -rf dist/* dist-lib/* || true","generate-icons": "node scripts/generate-pwa-icons.mjs","build:extension": "node scripts/build-extension-icons.mjs && node scripts/build-extension.mjs",diff --git a/public/skills/3d-studio/embed-three-ws-avatar/SKILL.md b/public/skills/3d-studio/embed-three-ws-avatar/SKILL.mdindex 088a96284..74cac29be 100644--- a/public/skills/3d-studio/embed-three-ws-avatar/SKILL.md+++ b/public/skills/3d-studio/embed-three-ws-avatar/SKILL.md@@ -22,7 +22,7 @@ the three.ws CDN with `access-control-allow-origin: *`, so it loads from any ori<scripttype="module"src="https://three.ws/agent-3d/1.5.2/agent-3d.js"- integrity="sha384-xkFDjVP866hYt7voUhfnQHj6IO4hYxA6n8Laupk+VtD6y+IKiO/AZdE3VbfLtg0C"+ integrity="sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q"crossorigin="anonymous"></script>diff --git a/public/skills/3d-studio/three-ws-3d-skills.zip b/public/skills/3d-studio/three-ws-3d-skills.zipindex 8bc324b2a..4ff3d221e 100644Binary files a/public/skills/3d-studio/three-ws-3d-skills.zip and b/public/skills/3d-studio/three-ws-3d-skills.zip differdiff --git a/scripts/check-dist.mjs b/scripts/check-dist.mjsindex 4d1420b14..c087f1954 100644--- a/scripts/check-dist.mjs+++ b/scripts/check-dist.mjs@@ -2,6 +2,7 @@import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';import { resolve, dirname, sep } from 'node:path';import { fileURLToPath } from 'node:url';+import { LEDGER_REL, RELEASE_FILES, checkPins, readLedger, releasedVersions, sri } from './lib/agent-3d-releases.mjs';const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');@@ -40,6 +41,56 @@ if (ok) {}}+// ── Immutable <agent-3d> releases ──────────────────────────────────────────+// /agent-3d/<version>/ is served `immutable` and pinned with SRI, so its bytes+// must be the released bytes and nothing else. Until 2026-10-01 the publish+// step rebuilt that directory on every deploy, the hash changed under every+// pinned embed, and browsers refused to run the script. Every release in the+// ledger must be present and hash to its recorded value, versions.json must+// advertise exactly those hashes, and so must every SRI pin in the docs.+let ledger = null;+try {+ ledger = readLedger(root);+} catch (err) {+ console.error(`[check-dist] ${LEDGER_REL} is unreadable: ${err.message}`);+ ok = false;+}+if (ledger) {+ const releases = releasedVersions(ledger);+ const manifestPath = resolve(root, 'dist/agent-3d/versions.json');+ const manifest = existsSync(manifestPath) ? JSON.parse(readFileSync(manifestPath, 'utf8')) : null;+ let releaseProblems = 0;+ for (const v of releases) {+ for (const name of RELEASE_FILES) {+ const expected = ledger.releases[v].integrity?.[name];+ const p = resolve(root, 'dist/agent-3d', v, name);+ if (!existsSync(p)) {+ console.error(`[check-dist] MISSING released file: dist/agent-3d/${v}/${name}`);+ releaseProblems++;+ continue;+ }+ const actual = sri(readFileSync(p));+ if (actual !== expected) {+ console.error(`[check-dist] dist/agent-3d/${v}/${name} hashes to ${actual} but release ${v} is ${expected}; an immutable URL would change bytes`);+ releaseProblems++;+ }+ const advertised = manifest?.channels?.[v]?.integrity?.[name];+ if (manifest && advertised !== expected) {+ console.error(`[check-dist] versions.json advertises ${advertised ?? 'nothing'} for ${v} ${name}; the release is ${expected}`);+ releaseProblems++;+ }+ }+ }+ const pins = checkPins(root, ledger);+ for (const p of pins.problems) {+ console.error(`[check-dist] SRI pin ${p.file}:${p.line} ${p.message}`);+ releaseProblems++;+ }+ if (pins.problems.length) console.error('[check-dist] fix the pins with: npm run check:sri-pins -- --fix');+ if (releaseProblems) ok = false;+ else console.log(`[check-dist] ${releases.length} immutable agent-3d release(s) byte-exact; ${pins.checked} documented SRI pin(s) match`);+}+// dist-lib mirror checksconst distLibChecks = [{ rel: 'dist/dist-lib/agent-3d.js', min: 1_000_000 },diff --git a/scripts/check-sri-pins.mjs b/scripts/check-sri-pins.mjsnew file mode 100644index 000000000..dba55be16--- /dev/null+++ b/scripts/check-sri-pins.mjs@@ -0,0 +1,25 @@+#!/usr/bin/env node+// Hold every documented <agent-3d> SRI pin to the release ledger.+//+// npm run check:sri-pins fail on a pin whose hash is not the+// released hash of the version it pins+// npm run check:sri-pins -- --fix rewrite those hashes from the ledger+//+// A pin on a version that was never released cannot be fixed by rewriting a+// hash; point it at a released version instead. check-dist runs the same check+// on every build, and tests/agent-3d-releases.test.js runs it under npm test.++import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { LEDGER_REL, checkPins, readLedger } from './lib/agent-3d-releases.mjs';++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const fix = process.argv.includes('--fix');+const { checked, problems, fixed } = checkPins(root, readLedger(root), { fix });+for (const p of problems) console.error(`[sri-pins] ${p.file}:${p.line} ${p.message}`);+if (fixed) console.log(`[sri-pins] rewrote ${fixed} pin(s) from ${LEDGER_REL}`);+if (problems.length) {+ if (!fix) console.error('[sri-pins] run: npm run check:sri-pins -- --fix');+ process.exit(1);+}+console.log(`[sri-pins] ${checked} documented SRI pin(s) match ${LEDGER_REL}`);diff --git a/scripts/lib/agent-3d-releases.mjs b/scripts/lib/agent-3d-releases.mjsnew file mode 100644index 000000000..9003c93db--- /dev/null+++ b/scripts/lib/agent-3d-releases.mjs@@ -0,0 +1,192 @@+// The <agent-3d> release ledger: which versions exist, the exact bytes each one+// is (as SRI hashes), and where those bytes are archived.+//+// Why a ledger at all: `/agent-3d/<MAJOR>.<MINOR>.<PATCH>/` is served with+// `cache-control: immutable`, and embedders pin it with an `integrity` hash. The+// old publish step rewrote that directory from whatever dist-lib/ held on every+// deploy while package.json stayed at 1.5.2 for months, so the bytes behind an+// "immutable" URL changed on every deploy and every documented SRI pin broke+// (the browser refuses a script whose hash does not match). A version is now+// cut once, by `npm run release:lib`, which archives its bytes and records their+// hashes here; every build after that serves those archived bytes under that+// version, verified against this file, and only the moving channels (latest,+// <major>, <major>.<minor>) follow the current build.+//+// Node builtins only: check-dist runs this inside Cloud Build's verify-context+// step, which has no node_modules.++import { createHash } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';+import { dirname, join, relative, resolve } from 'node:path';++export const LEDGER_REL = 'data/agent-3d-releases.json';++// Every file a release carries. agent-3d.js is the ES module embedders load;+// agent-3d.umd.cjs is the same build for non-ESM environments.+export const RELEASE_FILES = ['agent-3d.js', 'agent-3d.umd.cjs'];++export function sri(bytes) {+ return `sha384-${createHash('sha384').update(bytes).digest('base64')}`;+}++export function readLedger(root) {+ const ledger = JSON.parse(readFileSync(resolve(root, LEDGER_REL), 'utf8'));+ if (!ledger || typeof ledger.archive !== 'string' || !ledger.releases || typeof ledger.releases !== 'object') {+ throw new Error(`${LEDGER_REL} must carry "archive" (a URL) and "releases" (an object)`);+ }+ return ledger;+}++export function writeLedger(root, ledger) {+ writeFileSync(resolve(root, LEDGER_REL), JSON.stringify(ledger, null, '\t') + '\n');+}++const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/;++export function parseVersion(v) {+ const m = SEMVER.exec(String(v));+ if (!m) return null;+ return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), pre: String(v).includes('-') };+}++/** Released versions, oldest first. Prereleases sort before their release. */+export function releasedVersions(ledger) {+ return Object.keys(ledger.releases).sort((a, b) => {+ const x = parseVersion(a);+ const y = parseVersion(b);+ return x.major - y.major || x.minor - y.minor || x.patch - y.patch || Number(y.pre) - Number(x.pre);+ });+}++export function archiveUrl(ledger, version, file) {+ return `${ledger.archive.replace(/\/+$/, '')}/${version}/${file}`;+}++/**+ * The archived bytes of one released file, verified against the ledger. A local+ * cache keeps rebuilds offline-friendly; a cached copy is re-verified on every+ * read, so a corrupt cache entry is refetched rather than served.+ */+export async function fetchReleaseFile(ledger, version, file, { cacheDir = null } = {}) {+ const expected = ledger.releases[version]?.integrity?.[file];+ if (!expected) throw new Error(`${LEDGER_REL} has no ${file} hash for ${version}`);+ const cached = cacheDir ? join(cacheDir, version, file) : null;+ if (cached && existsSync(cached)) {+ const bytes = readFileSync(cached);+ if (sri(bytes) === expected) return bytes;+ }+ const url = archiveUrl(ledger, version, file);+ const res = await fetch(url, { signal: AbortSignal.timeout(120_000) });+ if (!res.ok) throw new Error(`${url} answered ${res.status}; the archived release is unreachable`);+ const bytes = Buffer.from(await res.arrayBuffer());+ const actual = sri(bytes);+ if (actual !== expected) {+ throw new Error(`${url} hashes to ${actual} but ${LEDGER_REL} records ${expected}; refusing to publish altered bytes`);+ }+ if (cached) {+ mkdirSync(dirname(cached), { recursive: true });+ writeFileSync(cached, bytes);+ }+ return bytes;+}++// ── Documented pins ─────────────────────────────────────────────────────────+//+// Any <script> tag in the docs that loads a versioned agent-3d file with an+// integrity attribute is a promise to the reader that those exact bytes exist.+// These helpers find every such pin so check-dist can hold it to the ledger and+// `npm run check:sri-pins -- --fix` can rewrite it from the ledger.++// Where documentation lives. Tests are deliberately absent: their fixtures pin+// wrong hashes on purpose to exercise stale-pin detection.+export const PIN_ROOTS = ['docs', 'specs', 'blog', 'examples', '.agents/skills', 'public/skills', 'README.md', 'packages'];+const PIN_EXT = /\.(md|mdx|html?|txt)$/i;+const SKIP_DIRS = new Set(['node_modules', 'dist', 'test', 'tests', '.git']);++const SCRIPT_TAG = /<script\b[^>]*>/gi;+const PINNED_SRC = /\bsrc\s*=\s*["']?[^"'\s>]*\/agent-3d\/(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\/(agent-3d\.(?:js|umd\.cjs))\b/i;+const INTEGRITY = /\bintegrity\s*=\s*["'](sha384-[A-Za-z0-9+/]{64})["']/i;++/** Every pinned, integrity-carrying agent-3d script tag in one text. */+export function findPins(text) {+ const pins = [];+ for (const m of text.matchAll(SCRIPT_TAG)) {+ const tag = m[0];+ const src = PINNED_SRC.exec(tag);+ const integrity = INTEGRITY.exec(tag);+ if (!src || !integrity) continue;+ const offset = m.index + integrity.index + integrity[0].indexOf(integrity[1]);+ pins.push({+ version: src[1],+ file: src[2],+ integrity: integrity[1],+ start: offset,+ end: offset + integrity[1].length,+ line: text.slice(0, offset).split('\n').length,+ });+ }+ return pins;+}++function walkDocs(abs, out) {+ const st = statSync(abs);+ if (st.isFile()) {+ if (PIN_EXT.test(abs)) out.push(abs);+ return;+ }+ for (const name of readdirSync(abs)) {+ if (SKIP_DIRS.has(name)) continue;+ walkDocs(join(abs, name), out);+ }+}++export function docFiles(root, roots = PIN_ROOTS) {+ const out = [];+ for (const r of roots) {+ const abs = resolve(root, r);+ if (existsSync(abs)) walkDocs(abs, out);+ }+ return out.sort();+}++/**+ * Check (and optionally rewrite) every documented pin against the ledger.+ * Returns { checked, problems: [{ file, line, message }], fixed }.+ * A pin on a version the ledger does not know cannot be fixed by rewriting a+ * hash, so it stays a problem even with fix=true.+ */+export function checkPins(root, ledger, { fix = false, roots = PIN_ROOTS } = {}) {+ const problems = [];+ let checked = 0;+ let fixed = 0;+ for (const abs of docFiles(root, roots)) {+ const text = readFileSync(abs, 'utf8');+ if (!text.includes('/agent-3d/')) continue;+ const pins = findPins(text);+ if (!pins.length) continue;+ const rel = relative(root, abs);+ let next = text;+ // Right to left, so earlier offsets stay valid while later ones are rewritten.+ for (const pin of [...pins].reverse()) {+ checked++;+ const expected = ledger.releases[pin.version]?.integrity?.[pin.file];+ if (!expected) {+ problems.push({ file: rel, line: pin.line, message: `pins agent-3d ${pin.version}, which ${LEDGER_REL} has never released` });+ continue;+ }+ if (pin.integrity === expected) continue;+ if (fix) {+ next = next.slice(0, pin.start) + expected + next.slice(pin.end);+ fixed++;+ } else {+ problems.push({+ file: rel,+ line: pin.line,+ message: `${pin.file} ${pin.version} is pinned to ${pin.integrity} but the release is ${expected}; browsers will refuse it`,+ });+ }+ }+ if (next !== text) writeFileSync(abs, next);+ }+ return { checked, problems, fixed };+}diff --git a/scripts/publish-lib.mjs b/scripts/publish-lib.mjsindex f6792bec9..66fe59172 100644--- a/scripts/publish-lib.mjs+++ b/scripts/publish-lib.mjs@@ -1,101 +1,128 @@#!/usr/bin/env node-// Copies the CDN bundle from dist-lib/ into dist/agent-3d/<version>/-// and moving aliases (<major>, <major>.<minor>, latest). Emits SRI hashes-// and a versions.json manifest so embedders can pin with integrity.+// Lays out the <agent-3d> CDN under dist/agent-3d/ and writes versions.json.//-// Run after `vite build && TARGET=lib vite build` — see npm run build:all.+// dist/agent-3d/<version>/ every released version, byte for byte as+// archived (data/agent-3d-releases.json),+// served `immutable` and pinned with SRI+// dist/agent-3d/<major>.<minor>/ the current build (dist-lib/), moving+// dist/agent-3d/<major>/ the current build, moving+// dist/agent-3d/latest/ the current build, moving+//+// An immutable version directory is NEVER written from dist-lib/. It used to+// be, which rebuilt /agent-3d/1.5.2/agent-3d.js on every deploy while the+// version string stayed put, so the bytes behind an immutable URL changed and+// every SRI pin of it broke. Released bytes now come from the archive, each+// file verified against the ledger's hash before it is written. To publish new+// code under a pinned URL, bump package.json and run `npm run release:lib`.+//+// Run after the lib build (`npm run build:lib:full`) and after the frontend+// `vite build`, which empties dist/: see the build:gcp chain.-import { readFileSync, writeFileSync, mkdirSync, existsSync, copyFileSync } from 'node:fs';-import { createHash } from 'node:crypto';+import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';import { resolve, dirname } from 'node:path';import { fileURLToPath } from 'node:url';+import {+ LEDGER_REL,+ RELEASE_FILES,+ fetchReleaseFile,+ parseVersion,+ readLedger,+ releasedVersions,+ sri,+} from './lib/agent-3d-releases.mjs';const here = dirname(fileURLToPath(import.meta.url));const root = resolve(here, '..');const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));const version = pkg.version;-const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version);-if (!match) {+const parsed = parseVersion(version);+if (!parsed) {console.error(`[publish-lib] package.json version "${version}" is not semver`);process.exit(1);}-const [, major, minor] = match;+const { major, minor } = parsed;++const ledger = readLedger(root);+if (!ledger.releases[version]) {+ console.error(+ `[publish-lib] package.json is at ${version}, which has never been released, so there are no archived bytes to` ++ ` serve at /agent-3d/${version}/. Run \`npm run release:lib\` to release the current build as ${version},` ++ ` or set package.json back to a released version (${releasedVersions(ledger).join(', ') || 'none yet'}).`,+ );+ process.exit(1);+}const srcDir = resolve(root, 'dist-lib');const destRoot = resolve(root, 'dist', 'agent-3d');--const files = [- { name: 'agent-3d.js', required: true },- { name: 'agent-3d.umd.cjs', required: false },-];--for (const f of files) {- const p = resolve(srcDir, f.name);- if (!existsSync(p)) {- if (f.required) {- console.error(`[publish-lib] missing ${p} — did you run \`npm run build:lib\`?`);- process.exit(1);- }- f.skip = true;- }+// node_modules/.cache survives between builds and is hardlinked into deploy+// worktrees, so a rebuild verifies cached release bytes instead of refetching.+const cacheDir = resolve(root, 'node_modules', '.cache', 'agent-3d-releases');++// The ES module is required. The UMD build only exists after build:lib:full+// (LIB_FORMATS=es,umd), which is what build:gcp runs; an ES-only lib build+// still lays out the moving channels, and check-dist fails a deploy without it.+const build = {};+for (const name of RELEASE_FILES) {+ const p = resolve(srcDir, name);+ if (existsSync(p)) build[name] = readFileSync(p);+ else if (name === 'agent-3d.js') {+ console.error(`[publish-lib] missing ${p}; run \`npm run build:lib:full\` first`);+ process.exit(1);+ } else console.warn(`[publish-lib] no ${name} in dist-lib/ (ES-only lib build); moving channels ship without it`);}+const built = Object.keys(build);mkdirSync(destRoot, { recursive: true });-const channels = [version, `${major}.${minor}`, major, 'latest'];-const sri = {};--for (const f of files) {- if (f.skip) continue;- const bytes = readFileSync(resolve(srcDir, f.name));- const hash = createHash('sha384').update(bytes).digest('base64');- sri[f.name] = `sha384-${hash}`;+// Moving channels: the current build.+const moving = [`${major}.${minor}`, String(major), 'latest'];+for (const channel of moving) {+ const outDir = resolve(destRoot, channel);+ mkdirSync(outDir, { recursive: true });+ for (const name of built) writeFileSync(resolve(outDir, name), build[name]);+}- for (const channel of channels) {- const outDir = resolve(destRoot, channel);- mkdirSync(outDir, { recursive: true });- writeFileSync(resolve(outDir, f.name), bytes);+// Immutable versions: the archived release bytes, verified.+const releases = releasedVersions(ledger);+for (const v of releases) {+ const outDir = resolve(destRoot, v);+ mkdirSync(outDir, { recursive: true });+ for (const name of RELEASE_FILES) {+ writeFileSync(resolve(outDir, name), await fetchReleaseFile(ledger, v, name, { cacheDir }));}+ writeFileSync(+ resolve(outDir, 'integrity.json'),+ JSON.stringify({ version: v, integrity: ledger.releases[v].integrity }, null, '\t') + '\n',+ );}-// Per-version SRI sidecars under the immutable path only.-const immutableDir = resolve(destRoot, version);-writeFileSync(- resolve(immutableDir, 'integrity.json'),- JSON.stringify({ version, integrity: sri }, null, '\t') + '\n',-);+const channels = {};+for (const v of releases) {+ channels[v] = { integrity: ledger.releases[v].integrity, immutable: true, releasedAt: ledger.releases[v].publishedAt };+}+channels[`${major}.${minor}`] = { tracks: `>=${major}.${minor}.0 <${major}.${minor + 1}.0`, build: 'current' };+channels[String(major)] = { tracks: `>=${major}.0.0 <${major + 1}.0.0`, build: 'current' };+channels.latest = { tracks: '*', build: 'current' };const versions = {latest: version,- channels: {- [version]: { integrity: sri, immutable: true },- [`${major}.${minor}`]: { tracks: `>=${major}.${minor}.0 <${major}.${Number(minor) + 1}.0` },- [major]: { tracks: `>=${major}.0.0 <${Number(major) + 1}.0.0` },- latest: { tracks: '*' },- },+ channels,+ // The moving channels serve the build deployed at this time; the+ // immutable versions above never change.+ currentBuild: Object.fromEntries(built.map((name) => [name, sri(build[name])])),publishedAt: new Date().toISOString(),};writeFileSync(resolve(destRoot, 'versions.json'), JSON.stringify(versions, null, '\t') + '\n');const distLibMirror = resolve(root, 'dist', 'dist-lib');mkdirSync(distLibMirror, { recursive: true });--for (const f of files) {- if (f.skip) continue;- const bytes = readFileSync(resolve(srcDir, f.name));- writeFileSync(resolve(distLibMirror, f.name), bytes);+for (const name of built) writeFileSync(resolve(distLibMirror, name), build[name]);+console.log('[publish-lib] mirrored dist-lib → dist/dist-lib/');++const sizes = built.map((n) => `${n}: ${(build[n].byteLength / 1024).toFixed(1)} KiB`).join(', ');+console.log(`[publish-lib] current build → dist/agent-3d/{${moving.join(',')}}/ (${sizes})`);+console.log(`[publish-lib] released, from the archive in ${LEDGER_REL}: ${releases.join(', ')}`);+for (const [name, hash] of Object.entries(ledger.releases[version].integrity)) {+ console.log(`[publish-lib] ${version} ${name} ${hash}`);}--console.log(`[publish-lib] mirrored dist-lib → dist/dist-lib/`);--const sizes = files- .filter((f) => !f.skip)- .map((f) => {- const bytes = readFileSync(resolve(srcDir, f.name)).byteLength;- return `${f.name}: ${(bytes / 1024).toFixed(1)} KiB`;- })- .join(', ');--console.log(`[publish-lib] v${version} → dist/agent-3d/{${channels.join(',')}}/ (${sizes})`);-for (const [name, hash] of Object.entries(sri)) console.log(`[publish-lib] ${name} ${hash}`);diff --git a/scripts/release-lib.mjs b/scripts/release-lib.mjsnew file mode 100644index 000000000..04bd15137--- /dev/null+++ b/scripts/release-lib.mjs@@ -0,0 +1,158 @@+#!/usr/bin/env node+// Cut an <agent-3d> CDN release: archive the bytes of package.json's version+// once, record their SRI hashes in data/agent-3d-releases.json, and rewrite any+// documented pin of that version to match. From then on every build serves+// exactly these bytes at /agent-3d/<version>/ (scripts/publish-lib.mjs), so the+// immutable URL and its integrity hash hold for as long as the release exists.+//+// npm run release:lib+// Build the lib (build:lib:full), then release the bytes in dist-lib/ as+// package.json's version. Bump the version first: an already-released+// version is never re-cut.+//+// node scripts/release-lib.mjs --from https://three.ws+// Adopt the bytes a live origin already serves for package.json's version+// instead of dist-lib/. This is how 1.5.2 was frozen at the bytes+// production was serving, so pins taken from it keep working.+//+// --dry-run compute and print the hashes, upload nothing, write nothing.+//+// The archive is a public-read GCS bucket. Uploads use an if-generation-match=0+// precondition, so an existing archived file is never overwritten: re-running+// a release whose bytes are already archived is a no-op, and a re-run with+// different bytes fails instead of altering a published version.++import { execFileSync } from 'node:child_process';+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import './lib/gcloud-path.mjs';+import {+ LEDGER_REL,+ RELEASE_FILES,+ archiveUrl,+ checkPins,+ fetchReleaseFile,+ parseVersion,+ readLedger,+ sri,+ writeLedger,+} from './lib/agent-3d-releases.mjs';++const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const args = process.argv.slice(2);+const dryRun = args.includes('--dry-run');+const fromIdx = args.indexOf('--from');+const from = fromIdx >= 0 ? args[fromIdx + 1] : null;+if (fromIdx >= 0 && !from) {+ console.error('[release-lib] --from needs an origin, e.g. --from https://three.ws');+ process.exit(1);+}++const version = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')).version;+if (!parseVersion(version)) {+ console.error(`[release-lib] package.json version "${version}" is not semver`);+ process.exit(1);+}++const ledger = readLedger(root);+const archive = new URL(ledger.archive);+if (archive.hostname !== 'storage.googleapis.com') {+ console.error(`[release-lib] ${LEDGER_REL} archive must be a storage.googleapis.com URL, got ${ledger.archive}`);+ process.exit(1);+}+const [bucket, ...prefixParts] = archive.pathname.replace(/^\/+|\/+$/g, '').split('/');+const gsBase = `gs://${bucket}/${prefixParts.join('/')}`;++async function sourceBytes(file) {+ if (from) {+ const url = `${from.replace(/\/+$/, '')}/agent-3d/${version}/${file}`;+ const res = await fetch(url, { signal: AbortSignal.timeout(120_000) });+ if (!res.ok) throw new Error(`${url} answered ${res.status}`);+ return Buffer.from(await res.arrayBuffer());+ }+ const p = resolve(root, 'dist-lib', file);+ if (!existsSync(p)) throw new Error(`missing ${p}; run \`npm run build:lib:full\` first`);+ return readFileSync(p);+}++const files = {};+for (const file of RELEASE_FILES) {+ const bytes = await sourceBytes(file);+ files[file] = { bytes, integrity: sri(bytes) };+ console.log(`[release-lib] ${version} ${file} ${files[file].integrity} (${(bytes.length / 1024).toFixed(1)} KiB)`);+}++const existing = ledger.releases[version];+if (existing) {+ const same = RELEASE_FILES.every((f) => existing.integrity?.[f] === files[f].integrity);+ if (!same) {+ console.error(+ `[release-lib] ${version} is already released with different bytes. A released version never changes;` ++ ' bump package.json to a new version and release that.',+ );+ process.exit(1);+ }+ console.log(`[release-lib] ${version} is already released with exactly these bytes; nothing to do.`);+ process.exit(0);+}++if (dryRun) {+ console.log('[release-lib] --dry-run: nothing uploaded, ledger unchanged.');+ process.exit(0);+}++const CONTENT_TYPE = { 'agent-3d.js': 'text/javascript; charset=utf-8', 'agent-3d.umd.cjs': 'text/javascript; charset=utf-8' };++function gcloud(argv) {+ return execFileSync('gcloud', argv, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+}++const work = mkdtempSync(join(tmpdir(), 'agent-3d-release-'));+try {+ for (const file of RELEASE_FILES) {+ const local = join(work, file);+ writeFileSync(local, files[file].bytes);+ const dest = `${gsBase}/${version}/${file}`;+ try {+ gcloud([+ 'storage',+ 'cp',+ local,+ dest,+ '--if-generation-match=0',+ `--content-type=${CONTENT_TYPE[file]}`,+ '--cache-control=public, max-age=31536000, immutable',+ ]);+ console.log(`[release-lib] archived ${dest}`);+ } catch (err) {+ const stderr = String(err.stderr || err.message);+ if (!/precondition|412|already exists/i.test(stderr)) throw new Error(`upload of ${dest} failed: ${stderr.trim()}`);+ console.log(`[release-lib] ${dest} already archived; verifying it holds these bytes`);+ }+ }+} finally {+ rmSync(work, { recursive: true, force: true });+}++// Read every file back through the public URL the build fetches from, so a+// release is only recorded once the archive demonstrably serves its bytes.+const entry = {+ publishedAt: new Date().toISOString(),+ source: from ? `${from.replace(/\/+$/, '')}/agent-3d/${version}/` : 'dist-lib/',+ integrity: Object.fromEntries(RELEASE_FILES.map((f) => [f, files[f].integrity])),+};+const probe = { ...ledger, releases: { ...ledger.releases, [version]: entry } };+for (const file of RELEASE_FILES) {+ await fetchReleaseFile(probe, version, file);+ console.log(`[release-lib] verified ${archiveUrl(probe, version, file)}`);+}++writeLedger(root, probe);+console.log(`[release-lib] recorded ${version} in ${LEDGER_REL}`);++const pins = checkPins(root, probe, { fix: true });+console.log(`[release-lib] documented pins: ${pins.checked} checked, ${pins.fixed} rewritten to the released hash`);+for (const p of pins.problems) console.log(`[release-lib] ${p.file}:${p.line} ${p.message}`);+console.log(`[release-lib] commit ${LEDGER_REL} and any rewritten docs; the next deploy serves ${version} from the archive.`);diff --git a/tests/agent-3d-releases.test.js b/tests/agent-3d-releases.test.jsnew file mode 100644index 000000000..089cfbb8b--- /dev/null+++ b/tests/agent-3d-releases.test.js@@ -0,0 +1,164 @@+// The <agent-3d> release ledger and the SRI pins that depend on it.+//+// /agent-3d/<version>/ is served `immutable` and embedders pin it with an+// integrity hash. Until 2026-10-01 its bytes were rebuilt on every deploy while+// the version stayed 1.5.2, so the documented pin (sha384-qCG5gH4...) no longer+// matched the served file (sha384-KdAiFR...) and browsers refused to run it.+// These tests pin the three things that stop that recurring: the pin finder+// sees every pinned tag, the checker flags and rewrites a stale pin, and the+// archive fetch refuses bytes that do not match the ledger. The last block runs+// the real check over this repo's docs, so a stale pin fails `npm test` before+// it ever reaches a build.++import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { createServer } from 'node:http';+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import {+ RELEASE_FILES,+ checkPins,+ fetchReleaseFile,+ findPins,+ readLedger,+ releasedVersions,+ sri,+} from '../scripts/lib/agent-3d-releases.mjs';++const ROOT = resolve(import.meta.dirname, '..');+const GOOD = 'sha384-KdAiFRsdcCbQMu4O5rkoL8hOEYLkmrdpf9ELd7jro+9NTNipWis3oqqFLll7v20Q';+const STALE = 'sha384-qCG5gH4q2+k2Gsf98zs9RFXyN8iezoklCWt63pA2Xk2YF7Onae4rfUwu+oZSqRzN';++const ledgerWith = (integrity) => ({+ archive: 'https://storage.googleapis.com/example/agent-3d',+ releases: { '1.5.2': { integrity: { 'agent-3d.js': integrity, 'agent-3d.umd.cjs': integrity } } },+});++describe('findPins', () => {+ it('finds a multi-line pinned tag in any attribute order', () => {+ const text = [+ '<script',+ ' integrity="' + STALE + '"',+ ' type="module"',+ ' src="https://three.ws/agent-3d/1.5.2/agent-3d.js"',+ ' crossorigin="anonymous"',+ '></script>',+ ].join('\n');+ const [pin] = findPins(text);+ expect(pin).toMatchObject({ version: '1.5.2', file: 'agent-3d.js', integrity: STALE, line: 2 });+ expect(text.slice(pin.start, pin.end)).toBe(STALE);+ });++ it('ignores placeholders, moving channels and tags without integrity', () => {+ const text = [+ '<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js" integrity="sha384-…"></script>',+ '<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js" integrity="' + GOOD + '"></script>',+ '<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>',+ ].join('\n');+ expect(findPins(text)).toEqual([]);+ });+});++describe('checkPins', () => {+ let dir;+ beforeAll(() => {+ dir = mkdtempSync(join(tmpdir(), 'sri-pins-'));+ mkdirSync(join(dir, 'docs'));+ });+ afterAll(() => rmSync(dir, { recursive: true, force: true }));++ const doc = (integrity, version = '1.5.2') =>+ `# Embed\n\n<script type="module" src="https://three.ws/agent-3d/${version}/agent-3d.js" integrity="${integrity}" crossorigin="anonymous"></script>\n`;++ it('flags a pin whose hash is not the released hash', () => {+ writeFileSync(join(dir, 'docs', 'a.md'), doc(STALE));+ const r = checkPins(dir, ledgerWith(GOOD), { roots: ['docs'] });+ expect(r.checked).toBe(1);+ expect(r.problems).toHaveLength(1);+ expect(r.problems[0]).toMatchObject({ file: join('docs', 'a.md'), line: 3 });+ expect(r.problems[0].message).toMatch(/browsers will refuse it/);+ });++ it('rewrites the stale hash from the ledger with fix', () => {+ writeFileSync(join(dir, 'docs', 'a.md'), doc(STALE));+ const r = checkPins(dir, ledgerWith(GOOD), { fix: true, roots: ['docs'] });+ expect(r.fixed).toBe(1);+ expect(r.problems).toEqual([]);+ expect(readFileSync(join(dir, 'docs', 'a.md'), 'utf8')).toBe(doc(GOOD));+ });++ it('cannot fix a pin on a version that was never released', () => {+ writeFileSync(join(dir, 'docs', 'a.md'), doc(GOOD, '9.9.9'));+ const r = checkPins(dir, ledgerWith(GOOD), { fix: true, roots: ['docs'] });+ expect(r.fixed).toBe(0);+ expect(r.problems[0].message).toMatch(/9\.9\.9, which .* has never released/);+ });+});++describe('fetchReleaseFile', () => {+ let server;+ let origin;+ let served;+ let cacheDir;+ beforeAll(async () => {+ server = createServer((req, res) => {+ res.end(served);+ });+ await new Promise((r) => server.listen(0, '127.0.0.1', r));+ origin = `http://127.0.0.1:${server.address().port}`;+ cacheDir = mkdtempSync(join(tmpdir(), 'release-cache-'));+ });+ afterAll(() => {+ server.close();+ rmSync(cacheDir, { recursive: true, force: true });+ });++ const ledgerAt = (integrity) => ({ ...ledgerWith(integrity), archive: `${origin}/agent-3d` });++ it('returns archived bytes that match the ledger and caches them', async () => {+ served = Buffer.from('export const released = true;\n');+ const bytes = await fetchReleaseFile(ledgerAt(sri(served)), '1.5.2', 'agent-3d.js', { cacheDir });+ expect(bytes.equals(served)).toBe(true);+ expect(readFileSync(join(cacheDir, '1.5.2', 'agent-3d.js')).equals(served)).toBe(true);+ });++ it('refuses archived bytes that do not match the ledger', async () => {+ const released = Buffer.from('export const released = true;\n');+ served = Buffer.from('export const released = "altered";\n');+ await expect(fetchReleaseFile(ledgerAt(sri(released)), '1.5.2', 'agent-3d.umd.cjs')).rejects.toThrow(+ /refusing to publish altered bytes/,+ );+ });++ it('refetches instead of trusting a corrupt cache entry', async () => {+ served = Buffer.from('export const fresh = 1;\n');+ mkdirSync(join(cacheDir, '1.5.2'), { recursive: true });+ writeFileSync(join(cacheDir, '1.5.2', 'agent-3d.umd.cjs'), 'corrupt');+ const bytes = await fetchReleaseFile(ledgerAt(sri(served)), '1.5.2', 'agent-3d.umd.cjs', { cacheDir });+ expect(bytes.equals(served)).toBe(true);+ });+});++describe('this repo', () => {+ const ledger = readLedger(ROOT);++ it('records both files of every release as sha384 SRI', () => {+ const versions = releasedVersions(ledger);+ expect(versions.length).toBeGreaterThan(0);+ for (const v of versions) {+ for (const f of RELEASE_FILES) expect(ledger.releases[v].integrity[f]).toMatch(/^sha384-[A-Za-z0-9+/]{64}$/);+ }+ expect(ledger.archive).toMatch(/^https:\/\/storage\.googleapis\.com\//);+ });++ it('has released the version package.json declares', () => {+ const { version } = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));+ expect(Object.keys(ledger.releases)).toContain(version);+ });++ it('pins every documented agent-3d SRI hash to its released bytes', () => {+ const { problems, checked } = checkPins(ROOT, ledger);+ expect(problems).toEqual([]);+ expect(checked).toBeGreaterThan(0);+ });+});