From 8287c601b1392d65bc0a44db3f39f21a68fd6916 Mon Sep 17 00:00:00 2001 From: Cristian Horta Date: Fri, 2 Oct 2026 11:49:17 -0700 Subject: [PATCH 1/2] Make tier 4 work for a canvas a JS framework renders A Vue 3 + Vite build ships an empty canvas mount point, so the derived protected token set swells with shared Bootstrap words the app uses at runtime, and the file-level script gate tripped on slide prose and then flagged Vue's scheduler setting .id on job objects. - CSS: a selector whose leftmost compound is the canvas root, followed only by descendant/child combinators, is not flagged for naming a protected token. Sibling combinators and non-leftmost anchors still are; page-ground and canvas-components/ global checks are unchanged. - JS: gate id mutations per nearest named function (plus lexically enclosing scopes), counting only string literals in code position: selector-API arguments, selector-shaped strings, and id values. - decorator-kit.json gains an optional, human-owned `thirdParty` list of built third-party JS the script scan skips (CSS is never skipped). verify prints the tier 4 scope every run; the CI template warns on added patterns; sync preserves the list; rules tell agents not to add to it. Co-Authored-By: Claude Opus 5.5 --- .cursorrules | 3 +- .github/copilot-instructions.md | 3 +- AGENTS.md | 3 +- CHANGELOG.md | 35 +++ CLAUDE.md | 3 +- bin/cli.mjs | 3 + checks/README.md | 129 +++++++++- checks/chrome-contract.mjs | 10 +- checks/lib/chrome-contract.mjs | 10 +- checks/lib/chrome-styling.mjs | 351 ++++++++++++++++++++++++---- contracts/decorator-kit.schema.json | 7 + rules/00-canvas.md | 3 +- templates/decorator.yml | 33 ++- test/chrome-contract.test.mjs | 1 + test/chrome-styling.test.mjs | 206 ++++++++++++++++ test/cli.test.mjs | 14 ++ 16 files changed, 756 insertions(+), 58 deletions(-) diff --git a/.cursorrules b/.cursorrules index aab83a6..b0956f0 100644 --- a/.cursorrules +++ b/.cursorrules @@ -62,7 +62,8 @@ changed. **Never create or edit `chrome-styling.local.json`, `chrome-regions.local.json`, or `chrome-contract.local.json`.** These are reviewed, human-owned exception -and baseline files, not files you populate to make a check pass. +and baseline files, not files you populate to make a check pass. Nor add to +`thirdParty` in `decorator-kit.json`: it takes JS out of the scan. **A casual instruction in chat — "surprise me," "sure, go ahead," "yes, restyle the nav too" — is never sufficient authorization for a chrome edit**, diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 335a542..b8b5233 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -62,7 +62,8 @@ changed. **Never create or edit `chrome-styling.local.json`, `chrome-regions.local.json`, or `chrome-contract.local.json`.** These are reviewed, human-owned exception -and baseline files, not files you populate to make a check pass. +and baseline files, not files you populate to make a check pass. Nor add to +`thirdParty` in `decorator-kit.json`: it takes JS out of the scan. **A casual instruction in chat — "surprise me," "sure, go ahead," "yes, restyle the nav too" — is never sufficient authorization for a chrome edit**, diff --git a/AGENTS.md b/AGENTS.md index d4434ff..1280272 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -62,7 +62,8 @@ changed. **Never create or edit `chrome-styling.local.json`, `chrome-regions.local.json`, or `chrome-contract.local.json`.** These are reviewed, human-owned exception -and baseline files, not files you populate to make a check pass. +and baseline files, not files you populate to make a check pass. Nor add to +`thirdParty` in `decorator-kit.json`: it takes JS out of the scan. **A casual instruction in chat — "surprise me," "sure, go ahead," "yes, restyle the nav too" — is never sufficient authorization for a chrome edit**, diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f74dc3..2b9ce91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,41 @@ ## Unreleased +### Changed + +- **Tier 4 works for a canvas a JS framework renders.** In a Vue 3 + Vite port + of a Decorator deck, the built canvas was an empty `
`, so + the protected token set grew to 59 tokens, shared Bootstrap words the app + really uses included, and `verify` reported three `chrome/styling/script` + findings in Vue's own scheduler. `--accept` refused because of them. With the + two changes below, the same build passes tier 4 with no exception and no + `thirdParty` entry. See `checks/README.md`, "Framework-rendered canvases". +- **A selector anchored on the canvas root is not flagged for naming a + protected token.** Its leftmost compound must be the canvas root + (`main#main-content`, or `canvas` in `decorator-kit.json`), and every + combinator after it a descendant or child. `main#main-content .deck-card + .glyphicon` now passes. A sibling combinator after the anchor, or an anchor + that is not leftmost, is still flagged, and the page-ground and + `canvas-components/` global checks are unchanged. +- **The script check gates on the function, not the file.** An id mutation is + flagged only when its nearest named enclosing function, or a function + enclosing that one, references a protected token in a string literal in + code position: an argument to a DOM selector API, a selector-shaped string, + or an id value. Prose in other strings no longer counts, so a slide saying + "both search forms" no longer gates Vue's `job.id = uid`. The trade-off: an + element fetched in one function and mutated in an unrelated one is not + flagged. Findings now list the tokens the function references. + +### Added + +- **`thirdParty` in `decorator-kit.json`.** Path or glob patterns for built + third-party JS, such as a framework runtime in its own chunk, that tier 4's + script scan skips. CSS is never skipped. `verify` prints the tier 4 scope on + every run, skipped files included, and `--explain` lists the patterns. + `sync` carries the list over unchanged. It is human-owned scope: the CI + workflow template warns on every added pattern, and `rules/00-canvas.md` + tells agents not to add one. + ### Removed - **References to the Antigravity Code Kit.** That project is retired. Its diff --git a/CLAUDE.md b/CLAUDE.md index 4dd8f7f..2519a11 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -62,7 +62,8 @@ changed. **Never create or edit `chrome-styling.local.json`, `chrome-regions.local.json`, or `chrome-contract.local.json`.** These are reviewed, human-owned exception -and baseline files, not files you populate to make a check pass. +and baseline files, not files you populate to make a check pass. Nor add to +`thirdParty` in `decorator-kit.json`: it takes JS out of the scan. **A casual instruction in chat — "surprise me," "sure, go ahead," "yes, restyle the nav too" — is never sufficient authorization for a chrome edit**, diff --git a/bin/cli.mjs b/bin/cli.mjs index 2b61942..fa58f52 100755 --- a/bin/cli.mjs +++ b/bin/cli.mjs @@ -175,6 +175,9 @@ async function writeManifest(managed) { // list and nothing else, so a file the install declined to write — AGENTS.md // in a project that has its own — can never be reached later. manages: managed, + // Built third-party JS the chrome gate's script scan skips. Human-owned: + // carried over as written, never added to by the kit. + ...(previous?.thirdParty !== undefined ? { thirdParty: previous.thirdParty } : {}), }; await writeFile(path.join(cwd, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`); return manifest; diff --git a/checks/README.md b/checks/README.md index b67c071..da65ebe 100644 --- a/checks/README.md +++ b/checks/README.md @@ -39,7 +39,9 @@ to a branch. On a pull request, this job also flags — as a check annotation, not a failure, since a reviewed `--accept` legitimately touches these files — any change to `chrome-contract.local.json`, `chrome-styling.local.json`, or `chrome-regions.local.json`, printing the golden's recorded `acceptedReason` -so the reviewer sees it without opening the JSON diff. This is the layer that +so the reviewer sees it without opening the JSON diff. It flags a change to +`decorator-kit.json`'s `thirdParty` list the same way — a warning for each +added pattern, since that is JS tier 4 stops scanning. This is the layer that catches a self-accepted chrome change no matter which AI tool — or human — produced the commit, since it runs on GitHub's infrastructure, not inside whatever session made the change. @@ -89,12 +91,13 @@ Four things ship inside this kit, and hold for any Decorator site unmodified: | `contracts/ucsd-decorator-5.json` | Tier 3's structural require/forbid rules | | `contracts/chrome-styling.json` | Tier 4's campus-widget ids and the (empty by default) exception list | -Two things are specific to the project running this, and neither lives in +Three things are specific to the project running this, and none lives in this kit: | File | Role | |---|---| | `decorator-kit.json`'s `canvas` field | The one writable region — `main#main-content` for a plain template, or the selector a project with its own shell names. Falls back to `main#main-content` if the file is absent. | +| `decorator-kit.json`'s `thirdParty` field | Optional. Built third-party JS that tier 4's script scan skips — see "Framework-rendered canvases" below. Absent by default. | | `chrome-contract.local.json` | Tier 2's recorded golden — written by `--accept`, committed to the project, diffed against on every `--check`. | A project whose chrome genuinely differs from the six default regions or the @@ -165,6 +168,24 @@ The gate cannot close that one — a lint rule requiring every site selector to scoped under the canvas selector can, and the skill tells agents to write them that way. +**A selector anchored on the canvas root is not flagged, whatever it names.** +If a selector's leftmost compound is the canvas root — `main#main-content`, or +whatever `canvas` in `decorator-kit.json` names, matched by its id (or by its +tag and classes when it has no id) — and every combinator after it is a +descendant (space) or child (`>`), it can only match the canvas or something +inside it, and the chrome lies outside the canvas. So +`main#main-content .deck-card .glyphicon` passes even when `.glyphicon` is +protected; it is exactly the scoping the rules ask for. It still fails: + +- with a sibling combinator after the anchor: `main#main-content ~ footer .row` + leaves the canvas; +- when the anchor is not the leftmost compound: `.navbar main#main-content .row`, + `body main#main-content .row`, `:is(main#main-content, .navbar) .row`; +- with a leading combinator (a relative selector nested inside another rule). + +The page-ground and global checks below ignore anchoring: a full-bleed band +painted from inside the canvas is still flagged. + **CSS: any site selector that hits a protected token is flagged.** `[id="…"]` and `[class~="…"]` are handled as tokens too, and quoted strings are stripped *first*, so `a[href="#search"]` is not read as targeting `#search`. Selector @@ -195,14 +216,54 @@ folder isn't held to this: the gate never checked it, and turning the check on there would fail existing projects on day one. **JS: `removeAttribute("id")`, `setAttribute("id", …)`, and `.id =` are -flagged — but only in files that also reference a protected token.** Canvas +flagged — but only in a function that references a protected token.** Canvas scripts assign ids to their own components constantly (a drawer component -giving each panel an id so its trigger can point `aria-controls` at it), and -that is not this rule's business. This half is a heuristic, not a parser: it -does not fully disambiguate a regex literal from division, so a regex -containing an unescaped brace placed right around an id mutation could in -principle confuse which function it blames. Real canvas interaction scripts -are short and rarely hit this. +giving each panel an id so its trigger can point `aria-controls` at it), and a +framework runtime sets `.id` on objects that are not elements at all (Vue's +scheduler: `job.id = instance.uid`). Neither is this rule's business. + +The gate is the nearest named enclosing function, the same one a finding +blames, together with every function lexically enclosing it, module scope +included. A reference counts only when it is a string literal in code +position: + +- the first argument to a DOM selector API — `querySelector`, + `querySelectorAll`, `closest`, `matches`, `getElementById`, + `getElementsByClassName`, jQuery's `$`/`jQuery`, and `.find` — + read as a selector (`getElementById`'s as an id, `getElementsByClassName`'s as + class names); +- a selector-shaped string on its own — starts with `.`, `#`, or `[` and holds + only selector characters — so `const DRAWER = ".navmenu"` counts; +- an id value: compared with or assigned to `.id`, or the value in + `setAttribute("id", …)` — so `el.id = "search"` is always flagged. + +Outside a selector API, a token counts only with its sigil (`#search`, +`.search`), and `[...]` contents never count, so `a[href^='#']` names nothing. +Identifiers (`location.search`), comments, and prose (`"Navbar, drawer & both +search forms"`) never count. Earlier releases gated the whole file and +matched token names as bare words anywhere, strings included; a framework +bundle carrying both the runtime and the app's copy tripped it on a slide's +text, and then every `.id =` in the runtime was flagged. + +**Know what the per-function gate gives up.** It is lexical. An element fetched +by selector in one function and mutated in another that does not enclose it is +not flagged: + +```js +function getDrawer() { return document.getElementById("search"); } +function dedupe() { getDrawer().removeAttribute("id"); } // not flagged +``` + +Nor is a reference in a function nested *inside* the one doing the mutation. +A reference at module scope, or in an enclosing function, does reach every +function nested in it, which covers the common closure shape — +`const panel = $("#search")` at the top, mutated in a handler below. The real +incident above is that shape, and it is still caught. + +This half is a heuristic, not a parser: it does not fully disambiguate a regex +literal from division, so a regex containing an unescaped brace placed right +around an id mutation could in principle confuse which function it blames. +Real canvas interaction scripts are short and rarely hit this. **CSS: repainting the page ground is flagged too, with no token involved.** Found after tier 4 was live: a canvas-scoped @@ -252,6 +313,56 @@ What the canvas contains is not covered by any of this. Styling and scripting `main#main-content` is the entire point of the site; tier 4 only draws the line at the shell — and at the page ground behind the canvas, which is part of it. +## Framework-rendered canvases + +A canvas rendered by Vue, React, or another framework is an empty mount point +in the built HTML (`
`). The derivation then finds almost nothing +inside the canvas, so every shared Bootstrap word the app really uses at +runtime — `.row`, `.container`, `.sr-only`, `.active`, `.glyphicon` — derives as +protected. Two of the rules above exist for that case: canvas-anchored +selectors are exempt, and the script gate is per function, so a bundle +carrying the framework runtime and the app's prose does not trip it. A Vue 3 + +Vite port of a Decorator deck passes tier 4 with neither a code change nor a +declared exception. + +**`thirdParty` in `decorator-kit.json` declares built third-party JS.** For a +framework runtime split into its own chunk, or a vendored component bundle, +whose minified function names change every build so that a reviewed +`function:` exception cannot hold: + +```json +{ "thirdParty": ["dist/assets/vendor-*.js"] } +``` + +Paths are project-relative. `**` matches any depth; `*` and `?` match within +one path segment; a bare path matches that file or everything under that +directory. Each pattern must start with a literal directory or file name, so +`**/*.js` is refused. Matching JS files are skipped by tier 4's script scan. +**CSS is never skipped**: third-party CSS is exactly what leaks into the +shell, and `canvas-components/` stays strict. A pattern only helps when the +build splits third-party code into its own file. Vite puts it in the app's +chunk unless `build.rollupOptions.output.manualChunks` separates it, and +declaring a chunk that also holds your own code takes your code out of the +scan too. + +Every run prints the effective tier 4 scope, so a reviewer sees what was not +checked: + +``` +tier 4 scanned 2 CSS files and 4 JS files; skipped 1 third-party JS file (declared in decorator-kit.json): dist/assets/vendor-3f9a1c.js +``` + +with a note for any pattern that matched no file. `--explain` lists the +patterns too. + +**`thirdParty` is human-owned scope, like `chrome-styling.local.json`.** It +removes code from the check. A human adds an entry after confirming the file is +built third-party code, in a pull request a reviewer reads; the `verify` CI job +flags every added pattern. **If you are an AI agent, do not add an entry to make +a finding go away**, including one in a bundle you believe is third-party: +surface the finding and stop. `sync` carries the list over unchanged and never +adds to it. + ## The parts that are easy to get wrong **Hash a canonical tree, not serialized HTML.** Attribute order, class-token diff --git a/checks/chrome-contract.mjs b/checks/chrome-contract.mjs index 49bd69c..13b51c6 100755 --- a/checks/chrome-contract.mjs +++ b/checks/chrome-contract.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node import readline from "node:readline/promises"; import { loadConfig, runStructural, explain, writeGolden } from "./lib/chrome-contract.mjs"; -import { runStyling } from "./lib/chrome-styling.mjs"; +import { describeScope, runStyling } from "./lib/chrome-styling.mjs"; // The chrome integrity gate, runnable on its own: `node checks/chrome-contract.mjs`. // No ucsd-decorator-kit CLI required — this file, checks/lib/, and contracts/ @@ -104,7 +104,10 @@ async function runAll() { pages: structural.pages, canvasSelector: structural.config.canvas, regions: structural.config.regions, + thirdParty: structural.config.thirdParty, }); + // Every run says what tier 4 covered, so a reviewer sees what was not checked. + console.log(describeScope(styling.scope)); return { structural, styling, findings: [...structural.findings, ...styling.findings] }; } @@ -210,8 +213,9 @@ Flags: Reads *.html under the current directory (excluding node_modules/, vendor/, core-template/) plus every *.css and *.js (excluding *.min.*) for tier 4, and every *.css under canvas-components/, minified included, which tier 4 also -checks for global selectors. No server, no browser, no ucsd-decorator-kit CLI -required.`); +checks for global selectors. JS matching decorator-kit.json's "thirdParty" +patterns is skipped, and every run prints what was. No server, no browser, no +ucsd-decorator-kit CLI required.`); } try { diff --git a/checks/lib/chrome-contract.mjs b/checks/lib/chrome-contract.mjs index a298b36..4c73109 100644 --- a/checks/lib/chrome-contract.mjs +++ b/checks/lib/chrome-contract.mjs @@ -56,7 +56,11 @@ export async function loadConfig(cwd) { const ruleOverlay = await loadOptionalJSON(path.join(cwd, RULES_OVERLAY_FILE)); const rules = mergeById(ruleDefaults.rules, ruleOverlay?.rules ?? []); - return { cwd, canvas, regions, rules, manifestFound: manifest !== null }; + // Built third-party JS tier 4's script scan skips. Human-owned scope; + // validated in chrome-styling.mjs, where it is applied. + const thirdParty = manifest?.thirdParty ?? []; + + return { cwd, canvas, regions, rules, thirdParty, manifestFound: manifest !== null }; } /** Every `*.html` file under `cwd`, excluding node_modules/vendor/core-template and dotfiles. */ @@ -460,6 +464,10 @@ export function explain(config) { for (const rule of config.rules) { lines.push(` ${rule.id} — region "${rule.region}"${rule.within ? `, within "${rule.within}"` : ""}`); } + if (config.thirdParty?.length) { + lines.push("", "third-party JS tier 4 does not scan (decorator-kit.json thirdParty):"); + for (const pattern of config.thirdParty) lines.push(` ${pattern}`); + } if (!config.manifestFound) { lines.push("", "note: no decorator-kit.json here — using the default canvas main#main-content."); } diff --git a/checks/lib/chrome-styling.mjs b/checks/lib/chrome-styling.mjs index 5dbaf9f..2a7c740 100644 --- a/checks/lib/chrome-styling.mjs +++ b/checks/lib/chrome-styling.mjs @@ -212,10 +212,99 @@ function selectorsIn(preludeText, startLine) { return selectors; } -function scanSelectorList(preludeText, startLine, file, protectedTokens, exceptions, findings) { +// ── canvas-anchored selectors ─────────────────────────────────────────── +// +// A selector whose leftmost compound is the canvas root, followed only by +// descendant (space) and child (`>`) combinators, can only ever match the +// canvas or something inside it — and the chrome lies outside the canvas. So a +// protected token in it is the canvas's own use of a shared Bootstrap word, +// not a reach into the shell: `main#main-content .deck-card .glyphicon` styles +// a canvas icon, whatever the derivation decided about `.glyphicon`. This is +// what rules/10-brand-integrity.md tells authors to write; the check agrees. +// It holds for any project's regions: a token is only protected if it appears +// nowhere inside the canvas, so a region a project declares inside the canvas +// contributes nothing an anchored selector could reach. +// +// Still flagged: a sibling combinator anywhere after the anchor +// (`main#main-content ~ footer .row` leaves the canvas), an anchor that is not +// the leftmost compound (`.navbar main#main-content .row` — or +// `body main#main-content .row`, which the scanner does not try to reason +// about), and a leading combinator from CSS nesting. The page-ground and +// global checks do not consult this at all. + +/** Top-level compounds of one complex selector and the combinators between them; `leading` is a combinator before the first compound. */ +function splitComplexSelector(selector) { + const compounds = []; + const combinators = []; + let leading = null; + let current = ""; + let pending = null; + let depth = 0; + for (let i = 0; i < selector.length; i++) { + const c = selector[i]; + if (c === "\\") { + current += c + (selector[i + 1] ?? ""); + i++; + continue; + } + if (c === "[" || c === "(") depth++; + else if (c === "]" || c === ")") depth--; + if (depth === 0 && /[\s>+~]/.test(c)) { + if (current) { + compounds.push(current); + current = ""; + } + if (pending === null || pending === " ") pending = /\s/.test(c) ? " " : c; + continue; + } + if (pending !== null) { + if (compounds.length) combinators.push(pending); + else leading = pending; + pending = null; + } + current += c; + } + if (current) compounds.push(current); + return { compounds, combinators, leading }; +} + +/** Tag, ids, and classes of one compound, ignoring what is inside `[...]` and `(...)`. */ +function compoundParts(compound) { + let bare = ""; + let depth = 0; + for (const c of compound) { + if (c === "[" || c === "(") depth++; + else if (c === "]" || c === ")") depth--; + else if (depth === 0) bare += c; + } + return { + tag: /^(?:[a-z][\w-]*|\*)/i.exec(bare)?.[0].toLowerCase() ?? null, + ids: [...bare.matchAll(/#([\w-]+)/g)].map((m) => m[1]), + classes: [...bare.matchAll(/\.([\w-]+)/g)].map((m) => m[1]), + }; +} + +function compoundIsCanvasRoot(compound, root) { + const { tag, ids, classes } = compoundParts(compound); + if (root.tag && tag && tag !== "*" && tag !== root.tag) return false; + if (root.id) return ids.includes(root.id); + if (!root.classes.length) return Boolean(root.tag) && tag === root.tag; + return (!root.tag || tag === root.tag) && root.classes.every((cls) => classes.includes(cls)); +} + +/** Can this selector only match the canvas root or something inside it? */ +export function isCanvasAnchored(selector, root) { + const { compounds, combinators, leading } = splitComplexSelector(selector); + if (leading !== null || !compounds.length) return false; + if (!combinators.every((combinator) => combinator === " " || combinator === ">")) return false; + return compoundIsCanvasRoot(compounds[0], root); +} + +function scanSelectorList(preludeText, startLine, file, protectedTokens, exceptions, findings, root) { for (const { selector, line } of selectorsIn(preludeText, startLine)) { const hits = findProtectedTokenHits(selector, protectedTokens); if (!hits.length) continue; + if (isCanvasAnchored(selector, root)) continue; pushUnlessExcepted(findings, exceptions, { kind: "chrome/styling/stylesheet", file, @@ -297,12 +386,13 @@ function subjectCompound(selector) { return selector.slice(start).trim(); } -/** Tag and id of the canvas selector's own element, e.g. `main#main-content` → `{ tag: "main", id: "main-content" }`. */ +/** Tag, id, and classes of the canvas selector's own element, e.g. `main#main-content` → `{ tag: "main", id: "main-content", classes: [] }`. */ function canvasRoot(canvasSelector) { const compound = subjectCompound(canvasSelector ?? ""); return { tag: /^[a-z][\w-]*/i.exec(compound)?.[0].toLowerCase() ?? null, id: /#([\w-]+)/.exec(compound)?.[1] ?? null, + classes: [...compound.replace(/\[[^\]]*\]|\([^)]*\)/g, "").matchAll(/\.([\w-]+)/g)].map((m) => m[1]), }; } @@ -397,8 +487,9 @@ function anchorsNestedSelectors(block) { } /** - * Flag any site-authored selector that hits a protected token, and any rule - * that repaints the page ground (see "page ground" above). Handles + * Flag any site-authored selector that hits a protected token — unless it is + * anchored on the canvas root (see "canvas-anchored selectors" above) — and + * any rule that repaints the page ground (see "page ground" above). Handles * `@media`/`@supports` nesting (their prelude is never itself a selector, but * what is inside still gets scanned) and strings (so `content: "{"` cannot be * mistaken for a brace). Not a full CSS parse — selector and declaration @@ -455,7 +546,7 @@ export function scanCssFile( ? { atRule: null, prelude, line: bufferStartLine, start: i + 1, globals: [] } : { atRule: atRule ?? "", globals: [] }; if (isStyleRule) { - scanSelectorList(prelude, bufferStartLine, file, protectedTokens, exceptions, findings); + scanSelectorList(prelude, bufferStartLine, file, protectedTokens, exceptions, findings, root); if (strict && !stack.some(anchorsNestedSelectors)) { block.globals = selectorsIn(prelude, bufferStartLine).filter(({ selector }) => isGlobalSelector(selector)); } @@ -513,8 +604,11 @@ function isRegexContext(lastSignificant, outTail) { * * Regex-vs-division is genuinely ambiguous without a real parser; this uses * the common heuristic (what character precedes the `/`) rather than one. + * + * Pass a `literals` array to collect the `{ start, end }` span of every + * string and template literal, quotes included. */ -function stripJsNoise(source, { blankStrings = true } = {}) { +function stripJsNoise(source, { blankStrings = true, literals = null } = {}) { let out = ""; let i = 0; const n = source.length; @@ -544,6 +638,7 @@ function stripJsNoise(source, { blankStrings = true } = {}) { j++; } const stop = Math.min(j + 1, n); + literals?.push({ start: i, end: stop }); out += blankStrings ? source.slice(i, stop).replace(/[^\n]/g, " ") : source.slice(i, stop); i = stop; lastSignificant = "x"; @@ -599,21 +694,68 @@ function escapeRegExp(text) { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -/** Gates the whole file scan: canvas scripts assign ids to their own components constantly, and that is not this rule's business. */ -function referencesProtectedTokens(withStringsIntact, protectedTokens) { - for (const token of protectedTokens) { - const bare = token.slice(1); - if (!bare) continue; - if (new RegExp(`[#.]?\\b${escapeRegExp(bare)}\\b`).test(withStringsIntact)) return true; +// What counts as a script "referencing" a protected token. Only string +// literals in code position, never identifiers (`location.search` is not the +// `.search` class) and never prose: a framework bundle carries the app's copy +// as string literals, and a slide that says "Navbar, drawer & both search +// forms" names no selector. A literal counts when it is +// +// - the first argument to a DOM selector API — querySelector(All), closest, +// matches, getElementById, getElementsByClassName, jQuery's `$`/`jQuery`, +// and `.find` — read as a selector (getElementById: as an id; +// getElementsByClassName: as class names); +// - selector-shaped on its own: it starts with `.`, `#`, or `[` and holds only +// selector characters, so `const DRAWER = ".navmenu"` counts wherever the +// constant is later used; +// - an id value: assigned to or compared with `.id`, or the value in +// `setAttribute("id", …)`. +// +// In the first two cases a token only counts with its sigil (`#search`, +// `.search`), and `[...]` contents are ignored, so `a[href^='#']` names nothing. + +const SELECTOR_CALL = + /(?:\.\s*(querySelector|querySelectorAll|closest|matches|getElementById|getElementsByClassName|find)|(?+,()\\]*$/; + +/** + * Protected tokens one string literal names, given the code just before it — + * `before` from the blanked view, so an earlier string cannot pose as a call, + * and `beforeIntact` for `setAttribute("id", …)`, whose `"id"` is a string. + */ +function literalTokens(text, before, beforeIntact, protectedTokens) { + const call = SELECTOR_CALL.exec(before); + if (call) { + const api = call[1] ?? call[2]; + if (api === "getElementById") return protectedTokens.has(`#${text.trim()}`) ? [`#${text.trim()}`] : []; + if (api === "getElementsByClassName") { + return text.split(/\s+/).filter(Boolean).map((cls) => `.${cls}`).filter((token) => protectedTokens.has(token)); + } + return findProtectedTokenHits(text, protectedTokens); } - return false; + if (ID_VALUE.test(beforeIntact)) return protectedTokens.has(`#${text.trim()}`) ? [`#${text.trim()}`] : []; + if (SELECTOR_SHAPED.test(text)) return findProtectedTokenHits(text, protectedTokens); + return []; } /** * Flag `removeAttribute("id")`, `setAttribute("id", …)`, and `.id =` — but - * only in files that reference a protected token somewhere, and keyed to the - * enclosing function by name (not line), so reformatting a body does not - * silently drop a reviewed exception. + * only where the nearest named enclosing function, or a function lexically + * enclosing that one (module scope included), references a protected token + * (see `literalTokens` above). Canvas scripts assign ids to their own + * components constantly, and a framework runtime sets `.id` on objects that + * are not elements at all (Vue's scheduler: `job.id = instance.uid`); neither + * is this rule's business. Findings are keyed to the enclosing function by + * name (not line), so reformatting a body does not silently drop a reviewed + * exception. + * + * The gate is lexical, which is its trade-off: an element fetched by + * selector in one function and mutated in another that does not enclose it — + * `getDrawer().removeAttribute("id")`, with `#search` named only inside + * `getDrawer` — is not flagged. A reference in an enclosing function or at + * module scope does reach every function nested inside it, which covers the + * common closure shape (`const panel = $("#search")` at the top, mutated in a + * handler below). * * Two noise-stripped views of the same source are used, and matches on one * are safe to look up in the other: both blank comments the same way and @@ -622,17 +764,21 @@ function referencesProtectedTokens(withStringsIntact, protectedTokens) { * * - `clean` blanks string/template/regex contents too — safe for brace-depth * and function-name detection, which must not see a stray `{`, `}`, or - * quote hiding inside one. + * quote hiding inside one — and for reading the code before a literal. * - `withStringsIntact` keeps them — required to see the id-mutation calls * themselves, since `removeAttribute("id")` *is* a string literal: a view * that blanks it can never match the pattern it exists to detect. */ export function scanJsFile(file, source, protectedTokens, { exceptions = [] } = {}) { - const withStringsIntact = stripJsNoise(source, { blankStrings: false }); - if (!referencesProtectedTokens(withStringsIntact, protectedTokens)) return []; - + const literals = []; + const withStringsIntact = stripJsNoise(source, { blankStrings: false, literals }); const clean = stripJsNoise(source); - const boundaries = [{ index: 0, name: "" }]; + + // Scope 0 is the module. Every named function opens a scope whose parent is + // the named scope around it; blocks and anonymous callbacks open none. + const MODULE = { name: "", scope: 0 }; + const parents = [null]; + const boundaries = [{ index: 0, ...MODULE }]; const stack = []; let bufferStart = 0; @@ -642,40 +788,68 @@ export function scanJsFile(file, source, protectedTokens, { exceptions = [] } = // when a file has more than one of them. Blame the named function around // it instead — that is what a human can find and what stays stable if the // callback body is reformatted. - function currentName() { + function current() { for (let k = stack.length - 1; k >= 0; k--) { - if (stack[k] && stack[k] !== "") return stack[k]; + if (stack[k].scope !== null) return stack[k]; } - return ""; + return MODULE; } for (let i = 0; i < clean.length; i++) { const ch = clean[i]; if (ch === "{") { - stack.push(detectFunctionName(clean.slice(bufferStart, i))); + const name = detectFunctionName(clean.slice(bufferStart, i)); + let scope = null; + if (name && name !== "") { + scope = parents.length; + parents.push(current().scope); + } + stack.push({ name, scope }); bufferStart = i + 1; - boundaries.push({ index: i + 1, name: currentName() }); + boundaries.push({ index: i + 1, ...current() }); } else if (ch === "}") { stack.pop(); bufferStart = i + 1; - boundaries.push({ index: i + 1, name: currentName() }); + boundaries.push({ index: i + 1, ...current() }); } } - function nameAt(index) { - let name = boundaries[0].name; + function scopeAt(index) { + let found = boundaries[0]; for (const boundary of boundaries) { if (boundary.index > index) break; - name = boundary.name; + found = boundary; } - return name; + return found; + } + + const referenced = new Map(); // scope → Set of protected tokens named in it + for (const { start, end } of literals) { + const text = withStringsIntact.slice(start + 1, end - 1).replace(/\$\{[^}]*\}/g, " "); + const from = Math.max(0, start - 64); + const tokens = literalTokens(text, clean.slice(from, start), withStringsIntact.slice(from, start), protectedTokens); + if (!tokens.length) continue; + const { scope } = scopeAt(start); + if (!referenced.has(scope)) referenced.set(scope, new Set()); + for (const token of tokens) referenced.get(scope).add(token); + } + + /** Protected tokens named in this scope or any scope lexically enclosing it. */ + function tokensInReach(scope) { + const tokens = new Set(); + for (let s = scope; s !== null; s = parents[s]) { + for (const token of referenced.get(s) ?? []) tokens.add(token); + } + return [...tokens]; } const findings = []; const idMutation = /\bremoveAttribute\(\s*(['"])id\1\s*\)|\bsetAttribute\(\s*(['"])id\2\s*,|\.id\s*=(?!=)/g; for (const match of withStringsIntact.matchAll(idMutation)) { + const { name, scope } = scopeAt(match.index); + const tokens = tokensInReach(scope); + if (!tokens.length) continue; const line = 1 + countNewlines(withStringsIntact.slice(0, match.index)); - const name = nameAt(match.index); const exception = findException(exceptions, file, `function:${name}`); if (exception) { if (isExpired(exception)) { @@ -694,7 +868,8 @@ export function scanJsFile(file, source, protectedTokens, { exceptions = [] } = file, line, function: name, - detail: `${match[0].trim()} in function "${name}" — this file references a protected chrome token, and the Decorator may own that id at runtime (see the drawer search breakpoint contract)`, + tokens, + detail: `${match[0].trim()} in function "${name}", which (or a function enclosing it) references ${tokens.join(", ")} — the Decorator may own that id at runtime (see the drawer search breakpoint contract)`, }); } return findings; @@ -722,6 +897,82 @@ export async function discoverScriptFiles(cwd) { return walkFiles(cwd, { exclude: DEFAULT_EXCLUDE_DIRS, matches: (name) => /\.js$/i.test(name) && !/\.min\.js$/i.test(name) }); } +// ── declared third-party scripts ───────────────────────────────────────── +// +// decorator-kit.json's optional `thirdParty` lists built third-party code — a +// framework runtime split into its own chunk, a vendored component bundle — +// that tier 4's script scan skips. JS only: third-party CSS is exactly what +// leaks into the shell, so it is always scanned, and canvas-components/ stays +// strict. Every run prints what was skipped (see `describeScope`), and the CI +// workflow flags a pull request that changes the list. It is human-owned +// scope, like chrome-styling.local.json: never an entry added to make a +// finding go away. + +/** Glob → RegExp over a project-relative POSIX path: `**` any depth, `*` and `?` within one segment. A pattern without a glob matches that file, or everything under that directory. */ +function globToRegExp(pattern) { + if (!/[*?]/.test(pattern)) { + const bare = escapeRegExp(pattern.replace(/\/+$/, "")); + return new RegExp(`^${bare}(?:/.*)?$`); + } + let source = ""; + for (let i = 0; i < pattern.length; i++) { + const c = pattern[i]; + if (c === "*" && pattern[i + 1] === "*") { + if (pattern[i + 2] === "/") { + source += "(?:.*/)?"; + i += 2; + } else { + source += ".*"; + i += 1; + } + } else if (c === "*") source += "[^/]*"; + else if (c === "?") source += "[^/]"; + else source += escapeRegExp(c); + } + return new RegExp(`^${source}$`); +} + +/** + * Validate decorator-kit.json's `thirdParty` and compile it. Throws on a + * malformed list — it is a human-authored scope declaration with a mistake in + * it, not something to work around. A pattern must be project-relative and + * start with a literal directory or file name, so `**\/*.js` cannot quietly + * take every script out of the scan. + */ +export function thirdPartyPatterns(thirdParty = []) { + if (!Array.isArray(thirdParty)) { + throw new Error('decorator-kit.json: "thirdParty" must be an array of path or glob patterns.'); + } + return thirdParty.map((pattern, index) => { + if (typeof pattern !== "string" || pattern.trim() === "") { + throw new Error(`decorator-kit.json: thirdParty[${index}] must be a non-empty string.`); + } + const normalized = pattern.trim().replace(/^\.\//, ""); + const first = normalized.split("/")[0]; + if (normalized.startsWith("/") || normalized.split("/").includes("..") || /[*?]/.test(first) || first === "") { + throw new Error( + `decorator-kit.json: thirdParty[${index}] ("${pattern}") must be a project-relative path that starts with ` + + `a literal directory or file name, such as "dist/assets/vendor-*.js". This is human-owned scope — ` + + `see checks/README.md.`, + ); + } + return { pattern, regex: globToRegExp(normalized) }; + }); +} + +/** One line for every run: what tier 4 scanned, and what it skipped as declared third-party. */ +export function describeScope(scope) { + const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`; + let line = `tier 4 scanned ${plural(scope.css, "CSS file")} and ${plural(scope.js, "JS file")}`; + if (scope.skipped.length) { + line += `; skipped ${plural(scope.skipped.length, "third-party JS file")} (declared in decorator-kit.json): ${scope.skipped.join(", ")}`; + } else { + line += "; skipped no third-party JS"; + } + if (scope.unmatched.length) line += `\n note: thirdParty pattern${scope.unmatched.length === 1 ? "" : "s"} matched no file: ${scope.unmatched.join(", ")}`; + return line; +} + /** * Run tier 4 against a project: derive the protected token set from already * loaded `pages` (see chrome-contract.mjs's `loadRoutePages`), then scan its @@ -729,19 +980,35 @@ export async function discoverScriptFiles(cwd) { * `*.css`/`*.js` under `cwd` (excluding `*.min.*`, node_modules, vendor, * core-template), plus every `*.css` under canvas-components/ — pass explicit * lists to scan a narrower or different set. CSS under canvas-components/ is - * scanned strictly however it got into the list. + * scanned strictly however it got into the list. JS matching a `thirdParty` + * pattern (decorator-kit.json) is skipped and reported in `scope`. */ -export async function runStyling(cwd, { pages, canvasSelector, regions, styleFiles, scriptFiles }) { +export async function runStyling(cwd, { pages, canvasSelector, regions, styleFiles, scriptFiles, thirdParty = [] }) { const config = await loadStylingConfig(cwd); + const patterns = thirdPartyPatterns(thirdParty); const protectedTokens = deriveProtectedTokens(pages, canvasSelector, regions, config.widgetTokens); + const relativeTo = (absolute) => path.relative(cwd, absolute).split(path.sep).join("/"); const css = styleFiles ?? [...new Set([...(await discoverStyleFiles(cwd)), ...(await discoverComponentStyleFiles(cwd))])]; - const js = scriptFiles ?? (await discoverScriptFiles(cwd)); + const allJs = scriptFiles ?? (await discoverScriptFiles(cwd)); + const js = []; + const skipped = []; + const used = new Set(); + for (const absolute of allJs) { + const relative = relativeTo(absolute); + const match = patterns.find(({ regex }) => regex.test(relative)); + if (match) { + used.add(match.pattern); + skipped.push(relative); + } else { + js.push(absolute); + } + } const findings = []; for (const absolute of css) { - const relative = path.relative(cwd, absolute).split(path.sep).join("/"); + const relative = relativeTo(absolute); const source = await readFile(absolute, "utf8"); const strict = relative.startsWith(`${CANVAS_COMPONENTS_DIR}/`); findings.push( @@ -749,9 +1016,15 @@ export async function runStyling(cwd, { pages, canvasSelector, regions, styleFil ); } for (const absolute of js) { - const relative = path.relative(cwd, absolute).split(path.sep).join("/"); + const relative = relativeTo(absolute); const source = await readFile(absolute, "utf8"); findings.push(...scanJsFile(relative, source, protectedTokens, { exceptions: config.allow })); } - return { protectedTokens, findings }; + const scope = { + css: css.length, + js: js.length, + skipped, + unmatched: patterns.map(({ pattern }) => pattern).filter((pattern) => !used.has(pattern)), + }; + return { protectedTokens, findings, scope }; } diff --git a/contracts/decorator-kit.schema.json b/contracts/decorator-kit.schema.json index e9060f4..e32f942 100644 --- a/contracts/decorator-kit.schema.json +++ b/contracts/decorator-kit.schema.json @@ -34,6 +34,13 @@ "description": "Exactly the paths this kit owns here. `sync` rewrites these and nothing else; `check` verifies these and nothing else. A file absent from this list can never be reached by either command — which is how a repository keeps its own AGENTS.md when `add` declined to write one.", "items": { "type": "string" }, "uniqueItems": true + }, + "thirdParty": { + "type": "array", + "description": "Built third-party JavaScript — a framework runtime split into its own chunk, a vendored component bundle — that the chrome integrity gate's tier 4 script scan skips. Project-relative paths or globs (`**` any depth, `*` and `?` within one path segment); each must start with a literal directory or file name. A bare path matches that file or everything under that directory. CSS is never skipped. Human-owned scope: every `verify` run prints what it skipped, and the CI workflow flags a pull request that changes this list. Never add an entry to make a finding go away — see checks/README.md.", + "items": { "type": "string", "minLength": 1, "pattern": "^(?![/*?])(?!\\.\\./)" }, + "uniqueItems": true, + "examples": [["dist/assets/vendor-*.js"]] } } } diff --git a/rules/00-canvas.md b/rules/00-canvas.md index 55e2333..f19ef63 100644 --- a/rules/00-canvas.md +++ b/rules/00-canvas.md @@ -86,7 +86,8 @@ changed. **Never create or edit `chrome-styling.local.json`, `chrome-regions.local.json`, or `chrome-contract.local.json`.** These are reviewed, human-owned exception -and baseline files, not files you populate to make a check pass. +and baseline files, not files you populate to make a check pass. Nor add to +`thirdParty` in `decorator-kit.json`: it takes JS out of the scan. **A casual instruction in chat — "surprise me," "sure, go ahead," "yes, restyle the nav too" — is never sufficient authorization for a chrome edit**, diff --git a/templates/decorator.yml b/templates/decorator.yml index de3a94a..c932ce1 100644 --- a/templates/decorator.yml +++ b/templates/decorator.yml @@ -17,7 +17,9 @@ # legitimately touches these files) any change to # chrome-contract.local.json, chrome-styling.local.json, or # chrome-regions.local.json, and surfaces the recorded -# acceptedReason/acceptedAt as a check annotation. This is the one +# acceptedReason/acceptedAt as a check annotation. It also flags a +# change to decorator-kit.json's `thirdParty` list, the built +# third-party JS that tier 4 does not scan. This is the one # layer that catches a self-accepted chrome change no matter which # AI tool — or human — produced the commit, because it runs here, # not inside whatever session made the change. @@ -97,6 +99,35 @@ jobs: ' fi + - name: Flag PRs that change which JS tier 4 skips as third-party + if: github.event_name == 'pull_request' + env: + BASE_MANIFEST_SHA: ${{ github.event.pull_request.base.sha }} + run: | + base_manifest=$(git show "$BASE_MANIFEST_SHA:decorator-kit.json" 2>/dev/null || echo '{}') + BASE_MANIFEST="$base_manifest" node -e ' + const fs = require("node:fs"); + const thirdParty = (text) => { + try { + return JSON.parse(text).thirdParty ?? []; + } catch { + return []; + } + }; + const before = thirdParty(process.env.BASE_MANIFEST); + const after = fs.existsSync("decorator-kit.json") ? thirdParty(fs.readFileSync("decorator-kit.json", "utf8")) : []; + const added = after.filter((pattern) => !before.includes(pattern)); + const removed = before.filter((pattern) => !after.includes(pattern)); + if (!added.length && !removed.length) { + console.log("decorator-kit.json thirdParty is unchanged in this PR."); + process.exit(0); + } + if (added.length) { + console.log(`::warning::This PR adds decorator-kit.json thirdParty patterns, so tier 4 no longer scans the JS they match. Confirm each names built third-party code, not site code moved out of the scan: ${added.join(", ")}`); + } + if (removed.length) console.log(`::notice::This PR removes decorator-kit.json thirdParty patterns: ${removed.join(", ")}`); + ' + drift: if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest diff --git a/test/chrome-contract.test.mjs b/test/chrome-contract.test.mjs index 9a6d24c..9391c3b 100644 --- a/test/chrome-contract.test.mjs +++ b/test/chrome-contract.test.mjs @@ -327,6 +327,7 @@ describe("chrome-contract.mjs CLI: the --accept interlock", () => { const after = await runCli(["--check"], dir); assert.equal(after.code, 0); assert.match(after.stdout, /all four tiers pass/); + assert.match(after.stdout, /^tier 4 scanned 0 CSS files and 0 JS files; skipped no third-party JS$/m); }); it("--accept refuses while tier 3 fails, and does not touch the already-recorded golden", async () => { diff --git a/test/chrome-styling.test.mjs b/test/chrome-styling.test.mjs index 3ee460f..c2a07b4 100644 --- a/test/chrome-styling.test.mjs +++ b/test/chrome-styling.test.mjs @@ -7,12 +7,14 @@ import { decoratorPage } from "./fixtures/decorator-page.mjs"; import { discoverRoutes, loadConfig, loadRoutePages } from "../checks/lib/chrome-contract.mjs"; import { deriveProtectedTokens, + describeScope, discoverComponentStyleFiles, discoverStyleFiles, loadStylingConfig, runStyling, scanCssFile, scanJsFile, + thirdPartyPatterns, } from "../checks/lib/chrome-styling.mjs"; let workdir; @@ -138,6 +140,68 @@ describe("scanCssFile — shipped regression 1: site CSS rebuilding the drawer s }); }); +// A framework renders the canvas at runtime, so in the built HTML the canvas +// is an empty mount point and every shared Bootstrap word (.row, .glyphicon, +// .sr-only) derives as protected. A selector anchored on the canvas root with +// only descendant/child combinators cannot reach the shell, whatever it names. +describe("scanCssFile — selectors anchored on the canvas root", () => { + const tokens = new Set([".glyphicon", ".row", ".sr-only", "#search", ".navbar"]); + const selectorsFlagged = (css, options = {}) => + scanCssFile("css/site.css", css, tokens, { exceptions: [], ...options }) + .filter((f) => f.kind === "chrome/styling/stylesheet") + .map((f) => f.selector); + + it("passes descendant and child selectors under main#main-content that name a protected token", () => { + const css = [ + "main#main-content .deck-card .glyphicon { color: #00629b; }", + "main#main-content > .row { margin: 0; }", + "#main-content .row>.col-sm-4 .sr-only:focus { outline: 2px solid; }", + "main#main-content.is-ready .glyphicon::before { content: ''; }", + "main#main-content .deck:has(+ .row) .glyphicon { color: #00629b; }", + "@media (max-width: 767px) { main#main-content .row { margin: 0; } }", + "", + ].join("\n"); + assert.deepEqual(selectorsFlagged(css), []); + }); + + it("still flags a sibling combinator after the anchor — that leaves the canvas", () => { + const css = "main#main-content ~ footer .row { margin: 0; }\nmain#main-content + .navbar { color: red; }\n"; + assert.deepEqual(selectorsFlagged(css), ["main#main-content ~ footer .row", "main#main-content + .navbar"]); + }); + + it("still flags a selector with no canvas anchor, or one whose anchor is not leftmost", () => { + const css = [ + ".deck-card .glyphicon { color: red; }", + ".navbar main#main-content .row { color: red; }", + "body main#main-content .row { color: red; }", + ":is(main#main-content, .navbar) .row { color: red; }", + "div#main-content .row { color: red; }", + "", + ].join("\n"); + assert.deepEqual(selectorsFlagged(css), [ + ".deck-card .glyphicon", + ".navbar main#main-content .row", + "body main#main-content .row", + ":is(main#main-content, .navbar) .row", + "div#main-content .row", + ]); + }); + + it("splits a selector list: the anchored half passes, the bare half is still flagged", () => { + assert.deepEqual(selectorsFlagged("main#main-content .row, .row { margin: 0; }"), [".row"]); + }); + + it("anchors on the project's own canvas selector", () => { + const css = "div#app-canvas .row { margin: 0; }\nmain#main-content .row { margin: 0; }\n"; + assert.deepEqual(selectorsFlagged(css, { canvasSelector: "div#app-canvas" }), ["main#main-content .row"]); + }); + + it("leaves the page-ground check alone: an anchored full-bleed band is still flagged", () => { + const findings = scanCssFile("css/site.css", "main#main-content .row { box-shadow: 0 0 0 100vmax #eee; }", tokens); + assert.deepEqual(findings.map((f) => f.kind), ["chrome/styling/page-ground"]); + }); +}); + describe("scanCssFile — shipped regression 2: a widget id restyled even though it is in no page's markup", () => { it("catches #chat-bubble via the hand-maintained widget token list alone", async () => { const dir = await project(); @@ -283,6 +347,71 @@ function dedupeIds() { }); }); +// A Vue/Vite bundle carries the framework runtime and the app's copy in one +// file. Vue's scheduler sets `.id` on job objects, not elements, and the app's +// prose mentions chrome words; neither is a reach into the shell. +describe("scanJsFile — the gate is per function, and prose does not count", () => { + const tokens = new Set(["#search", ".search", ".navbar", ".navmenu"]); + + it("does not flag Vue's scheduler setting ids on job objects in a file whose prose mentions search", () => { + const js = [ + 'const slides=[{title:"Navbar, drawer & both search forms",body:"The .search toggle stays."}];', + "function Bi(e,t,l){l.augmentJob=T=>{t&&(T.flags|=4),u&&(T.id=u.uid,T.i=u)};const E=()=>{R()};E.id=-1;return T}", + "function le(c,x){const O=c.job=x.runIfDirty.bind(x);O.i=c,O.id=c.uid,x.scheduler=()=>rn(O)}", + "", + ].join("\n"); + assert.deepEqual(scanJsFile("dist/assets/index-abc123.js", js, tokens), []); + }); + + it("does not let a selector in one function gate an id mutation in an unrelated one", () => { + const js = [ + 'function onKey(v){if(v.target.closest(".navbar, .navmenu"))return}', + "function augment(T,u){T.id=u.uid}", + "", + ].join("\n"); + assert.deepEqual(scanJsFile("js/app.js", js, tokens), []); + }); + + it("flags an id mutation in a function that queries #search or .navmenu", () => { + const js = [ + "function fixDrawer(){ const d = document.querySelector('.navmenu'); d.removeAttribute('id'); }", + "function fixPanel(){ $('#search').each(function(){ this.id = 'search-panel'; }); }", + "", + ].join("\n"); + const findings = scanJsFile("js/site.js", js, tokens); + assert.deepEqual(findings.map((f) => [f.function, f.tokens]), [ + ["fixDrawer", [".navmenu"]], + ["fixPanel", ["#search"]], + ]); + }); + + it("a reference at module scope or in an enclosing function reaches the functions nested in it", () => { + const js = [ + "const panel = document.getElementById('search');", + "function onReady(){ panel.removeAttribute('id'); }", + "function outer(){ const DRAWER = '.navmenu'; function inner(){ el.setAttribute('id', 'x'); } }", + "", + ].join("\n"); + assert.deepEqual(scanJsFile("js/site.js", js, tokens).map((f) => f.function), ["onReady", "inner"]); + }); + + it("counts an id value naming a protected id: el.id = 'search' and setAttribute('id', 'search')", () => { + const js = "function a(){ el.id = 'search'; }\nfunction b(){ el.setAttribute('id', 'search'); }\n"; + assert.deepEqual(scanJsFile("js/site.js", js, tokens).map((f) => f.function), ["a", "b"]); + }); + + it("does not count identifiers, comments, attribute values, or prose as references", () => { + const js = [ + "function a(){ const q = location.search; el.id = q; }", + "function b(){ /* fixes #search */ el.id = 'x'; }", + "function c(){ document.querySelector(\"a[href='#search']\"); el.id = 'x'; }", + "function d(){ const msg = 'Open the .navmenu drawer to search'; el.id = 'x'; }", + "", + ].join("\n"); + assert.deepEqual(scanJsFile("js/site.js", js, tokens), []); + }); +}); + describe("loadStylingConfig: exception validation", () => { it("rejects an allow entry missing approvedBy — the human who reviewed it", async () => { const dir = await project(); @@ -507,3 +636,80 @@ describe("runStyling end-to-end: a component library dropped into canvas-compone assert.match(global[0].remedy, /main#main-content/); }); }); + +// decorator-kit.json's `thirdParty` takes built third-party JS out of the +// script scan. JS only — third-party CSS is what leaks into the shell. +describe("runStyling — declared third-party scripts", () => { + const replay = `function dedupeIds() {\n document.getElementById('search');\n el.removeAttribute('id');\n}\n`; + + async function bundleProject() { + const dir = await project(); + await writeFile(path.join(dir, "index.html"), decoratorPage("Home")); + await mkdir(path.join(dir, "dist/assets"), { recursive: true }); + await writeFile(path.join(dir, "dist/assets/vendor-abc123.js"), replay); + await writeFile(path.join(dir, "dist/assets/vendor-abc123.css"), ".search-toggle { display: none; }\n"); + return dir; + } + + it("skips a declared JS file, reports it in the scope, and still scans CSS that matches the same pattern", async () => { + const dir = await bundleProject(); + const { config, pages } = await loadPages(dir); + const { findings, scope } = await runStyling(dir, { + pages, + canvasSelector: config.canvas, + regions: config.regions, + thirdParty: ["dist/assets/vendor-*"], + }); + assert.deepEqual(findings.filter((f) => f.kind === "chrome/styling/script"), []); + assert.deepEqual(scope.skipped, ["dist/assets/vendor-abc123.js"]); + assert.ok(findings.some((f) => f.kind === "chrome/styling/stylesheet" && f.file === "dist/assets/vendor-abc123.css")); + assert.match( + describeScope(scope), + /^tier 4 scanned 1 CSS file and 0 JS files; skipped 1 third-party JS file \(declared in decorator-kit\.json\): dist\/assets\/vendor-abc123\.js$/, + ); + }); + + it("flags the same file when it is not declared", async () => { + const dir = await bundleProject(); + const { config, pages } = await loadPages(dir); + const { findings, scope } = await runStyling(dir, { pages, canvasSelector: config.canvas, regions: config.regions }); + assert.ok(findings.some((f) => f.kind === "chrome/styling/script" && f.file === "dist/assets/vendor-abc123.js")); + assert.deepEqual(scope.skipped, []); + assert.match(describeScope(scope), /skipped no third-party JS/); + }); + + it("reads thirdParty from decorator-kit.json, and notes a pattern that matched nothing", async () => { + const dir = await bundleProject(); + await writeFile( + path.join(dir, "decorator-kit.json"), + JSON.stringify({ canvas: "main#main-content", thirdParty: ["dist/assets/vendor-abc123.js", "dist/runtime/"] }), + ); + const { config, pages } = await loadPages(dir); + const { scope } = await runStyling(dir, { + pages, + canvasSelector: config.canvas, + regions: config.regions, + thirdParty: config.thirdParty, + }); + assert.deepEqual(scope.skipped, ["dist/assets/vendor-abc123.js"]); + assert.deepEqual(scope.unmatched, ["dist/runtime/"]); + assert.match(describeScope(scope), /matched no file: dist\/runtime\//); + }); + + it("matches globs by path segment and bare paths as a file or directory", () => { + const [glob, deep, dir] = thirdPartyPatterns(["dist/assets/vendor-*.js", "dist/**/runtime.js", "public/lib"]); + assert.ok(glob.regex.test("dist/assets/vendor-abc.js")); + assert.ok(!glob.regex.test("dist/assets/sub/vendor-abc.js")); + assert.ok(deep.regex.test("dist/runtime.js") && deep.regex.test("dist/a/b/runtime.js")); + assert.ok(dir.regex.test("public/lib/x.js") && dir.regex.test("public/lib")); + assert.ok(!dir.regex.test("public/library.js")); + }); + + it("refuses a malformed list, or a pattern that does not start at a literal path", () => { + assert.throws(() => thirdPartyPatterns("dist/vendor.js"), /must be an array/); + assert.throws(() => thirdPartyPatterns([""]), /non-empty string/); + for (const pattern of ["**/*.js", "*.js", "/dist/vendor.js", "../vendor.js", "dist/../js/site.js"]) { + assert.throws(() => thirdPartyPatterns([pattern]), /project-relative path/, pattern); + } + }); +}); diff --git a/test/cli.test.mjs b/test/cli.test.mjs index 20c014e..80bedcb 100644 --- a/test/cli.test.mjs +++ b/test/cli.test.mjs @@ -354,6 +354,20 @@ describe("sync", () => { assert.ok(JSON.parse(await readFile(manifestPath, "utf8")).manages.includes("DECORATOR.md")); assert.equal((await run(["check"], { cwd: project })).code, 0); }); + + it("carries decorator-kit.json's human-owned thirdParty list through a sync unchanged", async () => { + const project = path.join(workdir, "keeps-third-party"); + await mkdir(project, { recursive: true }); + await run(["add"], { cwd: project }); + + const manifestPath = path.join(project, "decorator-kit.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + manifest.thirdParty = ["dist/assets/vendor-*.js"]; + await writeFile(manifestPath, JSON.stringify(manifest, null, 2)); + + assert.equal((await run(["sync"], { cwd: project })).code, 0); + assert.deepEqual(JSON.parse(await readFile(manifestPath, "utf8")).thirdParty, ["dist/assets/vendor-*.js"]); + }); }); describe("init", () => { From e5d40b040c63a4456a7b1537356907ae9c2ee3a7 Mon Sep 17 00:00:00 2001 From: Cristian Horta Date: Fri, 2 Oct 2026 11:58:17 -0700 Subject: [PATCH 2/2] Guard decorator-kit.json like the chrome *.local.json files Its canvas selector decides what tier 4 protects and what counts as canvas-anchored, so "canvas": "body" would empty most of the check in one line, and nothing flagged it. - templates/claude-settings.json denies Edit/Write on decorator-kit.json. init/add/sync still write it through Node. - The CI workflow template now warns when canvas changes, alongside the existing thirdParty warning. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++++ bin/cli.mjs | 12 ++++++++---- checks/README.md | 32 ++++++++++++++++++++++---------- templates/claude-settings.json | 4 +++- templates/decorator.yml | 29 +++++++++++++++++++---------- test/cli.test.mjs | 2 ++ 6 files changed, 60 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b9ce91..0847f27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,12 @@ `sync` carries the list over unchanged. It is human-owned scope: the CI workflow template warns on every added pattern, and `rules/00-canvas.md` tells agents not to add one. +- **`decorator-kit.json` is guarded like the chrome `*.local.json` files.** Its + `canvas` decides what tier 4 protects and what counts as canvas-anchored, so + `"canvas": "body"` would empty most of the check in one line. The Claude + Code template (`add --with-hook`) now denies Edit and Write on the file, and + the CI workflow template warns when `canvas` changes, as it does for + `thirdParty`. The kit's own `init`, `add`, and `sync` still write it. ### Removed diff --git a/bin/cli.mjs b/bin/cli.mjs index fa58f52..a229f2a 100755 --- a/bin/cli.mjs +++ b/bin/cli.mjs @@ -285,7 +285,9 @@ async function addScripts() { * Hooks an earlier release installed (LEGACY_HOOK_COMMANDS) are replaced. * - `permissions.deny` on Edit/Write of the three chrome `*.local.json` * files — a hard block, matching rules/00-canvas.md's unconditional "never - * create or edit" language for the same files. + * create or edit" language for the same files — and of decorator-kit.json, + * whose `canvas` and `thirdParty` set what the gate checks. The kit's own + * commands still write it: they run through Node, not Edit/Write. * - `permissions.ask` on any Bash command matching `--accept` — forces * explicit human approval in Claude Code's own UI before it runs, on top * of (not instead of) the CLI-level gate in checks/chrome-contract.mjs, @@ -546,8 +548,9 @@ async function add() { console.log("No Claude Code hook installed. `add --with-hook` adds a Stop hook that runs"); console.log("`verify` in the background after each turn and wakes the agent back up — not"); console.log("the user, and not blocking anything meanwhile — if it finds a regression. It"); - console.log("also adds permission rules: denying edits to the chrome *.local.json files,"); - console.log("and requiring your approval before any Bash command matching --accept. Like"); + console.log("also adds permission rules: denying edits to the chrome *.local.json files and"); + console.log("decorator-kit.json, and requiring your approval before any Bash command"); + console.log("matching --accept. Like"); console.log(`--with-ci, it adds ${kitPackage.name} as a devDependency for the hook to run.`); } } @@ -708,7 +711,8 @@ Flags for \`add\`: --with-decorator also add ${DECORATOR_PACKAGE} to package.json --with-ci also write .github/dependabot.yml and a workflow --with-hook also add a Claude Code Stop hook that runs \`verify\`, plus - permission rules guarding the chrome *.local.json files and --accept + permission rules guarding the chrome *.local.json files, + decorator-kit.json, and --accept Each of the three also adds ${kitPackage.name} as a devDependency, and the decorator:* npm scripts, because what it writes runs the kit from node_modules. diff --git a/checks/README.md b/checks/README.md index da65ebe..d5d526c 100644 --- a/checks/README.md +++ b/checks/README.md @@ -39,9 +39,10 @@ to a branch. On a pull request, this job also flags — as a check annotation, not a failure, since a reviewed `--accept` legitimately touches these files — any change to `chrome-contract.local.json`, `chrome-styling.local.json`, or `chrome-regions.local.json`, printing the golden's recorded `acceptedReason` -so the reviewer sees it without opening the JSON diff. It flags a change to -`decorator-kit.json`'s `thirdParty` list the same way — a warning for each -added pattern, since that is JS tier 4 stops scanning. This is the layer that +so the reviewer sees it without opening the JSON diff. It warns the same way +on two fields of `decorator-kit.json`: a changed `canvas` selector, which moves +the line between canvas and chrome for every tier 4 check, and each pattern +added to `thirdParty`, since that is JS tier 4 stops scanning. This is the layer that catches a self-accepted chrome change no matter which AI tool — or human — produced the commit, since it runs on GitHub's infrastructure, not inside whatever session made the change. @@ -67,7 +68,8 @@ hook earlier releases wrote. The same template also adds a `permissions` block: `deny` on editing the three chrome -`*.local.json` files, and `ask` on any Bash command matching `--accept` — +`*.local.json` files and `decorator-kit.json`, and `ask` on any Bash command +matching `--accept` — this only protects a project when the person working on it is using Claude Code with this template installed; the CLI-level gate above is what has to hold for everyone else. @@ -358,10 +360,20 @@ patterns too. **`thirdParty` is human-owned scope, like `chrome-styling.local.json`.** It removes code from the check. A human adds an entry after confirming the file is built third-party code, in a pull request a reviewer reads; the `verify` CI job -flags every added pattern. **If you are an AI agent, do not add an entry to make -a finding go away**, including one in a bundle you believe is third-party: -surface the finding and stop. `sync` carries the list over unchanged and never -adds to it. +flags every added pattern, and the Claude Code template (`add --with-hook`) +denies agent edits to `decorator-kit.json`. **If you are an AI agent, do not +add an entry to make a finding go away**, including one in a bundle you +believe is third-party: surface the finding and stop. `sync` carries the list +over unchanged and never adds to it. + +**`canvas` is the same kind of lever.** It decides which tokens derive as +protected and what counts as canvas-anchored: `"canvas": "body"` would put +every class on the page inside the "canvas" and exempt every `body …` +selector, emptying most of tier 4 in one line. The CI job warns when it +changes, and the template denies agent edits to the file for this reason too. +The deny covers Claude Code's Edit and Write tools only; `init`, `add`, and +`sync` still write the file, and the CI warning is the backstop for any +other route. ## The parts that are easy to get wrong @@ -414,8 +426,8 @@ run non-interactively unless `--yes` is passed — which is documented, in both `--help` and `rules/00-canvas.md`, as being for a human-triggered non-interactive context only, never for an agent to pass itself. A project that installs the Claude Code template (`add --with-hook`) also gets a -`permissions` block denying edits to the three chrome `*.local.json` files -outright, and requiring explicit approval before any Bash command matching +`permissions` block denying edits to the three chrome `*.local.json` files and +`decorator-kit.json` outright, and requiring explicit approval before any Bash command matching `--accept` — on top of, not instead of, the CLI-level gate above, which holds for any caller regardless of which AI tool (or none) is involved. A PR that still changes one of those files gets flagged (not blocked) by the `verify` diff --git a/templates/claude-settings.json b/templates/claude-settings.json index 5eae09b..e8c8058 100644 --- a/templates/claude-settings.json +++ b/templates/claude-settings.json @@ -6,7 +6,9 @@ "Edit(chrome-regions.local.json)", "Write(chrome-regions.local.json)", "Edit(chrome-contract.local.json)", - "Write(chrome-contract.local.json)" + "Write(chrome-contract.local.json)", + "Edit(decorator-kit.json)", + "Write(decorator-kit.json)" ], "ask": [ "Bash(*--accept*)" diff --git a/templates/decorator.yml b/templates/decorator.yml index c932ce1..5adce8c 100644 --- a/templates/decorator.yml +++ b/templates/decorator.yml @@ -18,8 +18,9 @@ # chrome-contract.local.json, chrome-styling.local.json, or # chrome-regions.local.json, and surfaces the recorded # acceptedReason/acceptedAt as a check annotation. It also flags a -# change to decorator-kit.json's `thirdParty` list, the built -# third-party JS that tier 4 does not scan. This is the one +# change to decorator-kit.json's `canvas` selector, which moves the +# line between canvas and chrome, and to its `thirdParty` list, the +# built third-party JS that tier 4 does not scan. This is the one # layer that catches a self-accepted chrome change no matter which # AI tool — or human — produced the commit, because it runs here, # not inside whatever session made the change. @@ -99,7 +100,7 @@ jobs: ' fi - - name: Flag PRs that change which JS tier 4 skips as third-party + - name: Flag PRs that change the canvas selector or the JS tier 4 skips as third-party if: github.event_name == 'pull_request' env: BASE_MANIFEST_SHA: ${{ github.event.pull_request.base.sha }} @@ -107,19 +108,27 @@ jobs: base_manifest=$(git show "$BASE_MANIFEST_SHA:decorator-kit.json" 2>/dev/null || echo '{}') BASE_MANIFEST="$base_manifest" node -e ' const fs = require("node:fs"); - const thirdParty = (text) => { + const read = (text) => { try { - return JSON.parse(text).thirdParty ?? []; + return JSON.parse(text); } catch { - return []; + return {}; } }; - const before = thirdParty(process.env.BASE_MANIFEST); - const after = fs.existsSync("decorator-kit.json") ? thirdParty(fs.readFileSync("decorator-kit.json", "utf8")) : []; + const base = read(process.env.BASE_MANIFEST); + const head = fs.existsSync("decorator-kit.json") ? read(fs.readFileSync("decorator-kit.json", "utf8")) : {}; + // Both fall back the way the gate does: no canvas means main#main-content. + const canvasBefore = base.canvas ?? "main#main-content"; + const canvasAfter = head.canvas ?? "main#main-content"; + if (canvasBefore !== canvasAfter) { + console.log(`::warning::This PR changes decorator-kit.json canvas from "${canvasBefore}" to "${canvasAfter}". That moves the line between canvas and chrome for every tier 4 check — confirm it matches the shell, not a finding someone wanted gone.`); + } + const before = base.thirdParty ?? []; + const after = head.thirdParty ?? []; const added = after.filter((pattern) => !before.includes(pattern)); const removed = before.filter((pattern) => !after.includes(pattern)); - if (!added.length && !removed.length) { - console.log("decorator-kit.json thirdParty is unchanged in this PR."); + if (canvasBefore === canvasAfter && !added.length && !removed.length) { + console.log("decorator-kit.json canvas and thirdParty are unchanged in this PR."); process.exit(0); } if (added.length) { diff --git a/test/cli.test.mjs b/test/cli.test.mjs index 80bedcb..99404de 100644 --- a/test/cli.test.mjs +++ b/test/cli.test.mjs @@ -269,6 +269,8 @@ describe("add --with-hook", () => { const settings = JSON.parse(await readFile(path.join(project, ".claude/settings.json"), "utf8")); assert.ok(settings.permissions.deny.includes("Edit(chrome-styling.local.json)")); assert.ok(settings.permissions.deny.includes("Write(chrome-contract.local.json)")); + assert.ok(settings.permissions.deny.includes("Edit(decorator-kit.json)"), "canvas and thirdParty set what the gate checks"); + assert.ok(settings.permissions.deny.includes("Write(decorator-kit.json)")); assert.ok(settings.permissions.ask.includes("Bash(*--accept*)")); });