From 8432e2cea0a79c798c91a9cc1346b2ef04341273 Mon Sep 17 00:00:00 2001 From: Arena Agent Date: Mon, 9 Nov 2026 10:33:11 +0000 Subject: [PATCH 1/4] Harden scanning, generation and file writes against hostile repos TailClass parses repository content and then writes files, so a cloned repository can influence output paths, CSS payloads and glob patterns. This commit fixes what an adversarial review turned up and adds regression tests plus a written review (docs/security-review.md). Security - Confine config-supplied outputCss/dictionaryFile/manifestFile to the project root (apply/list/revert, incl. the --clean unlink path). A malicious tailclass.config.json could previously write, and with `revert --clean` delete, arbitrary files outside the project. - Reject CSS-breaking class tokens (`;`, `{`, `}`, control chars, `*/`) from `@apply`; they are preserved inline on the element instead. This closes CSS injection via arbitrary values like `text-[red;}html{display:none}]`. - Replace the regex-based glob matcher with a backtracking-free DP matcher: `**`-heavy patterns used to hang the process (config-driven ReDoS); malformed `[` classes now degrade to literals instead of throwing. Compiled matchers are cached and length-capped. - Validate classPrefix/tailwindPrefix, sanitize dictionary labels, categories and element hints, and validate selectors/payloads in the generator (comment + CSS injection hardening). - Refuse to overwrite scanned source files, or stylesheets/manifests that do not look like TailClass output, without --force. - Sanitize manifest-driven reverts and report corrupt manifests. - Always exclude .git/, node_modules/ and .tailclass-backup/, even with replaceDefaultExcludes. - Validate configuration up front with actionable errors; unknown keys become stderr warnings; JSON errors name the offending file. Fixes - `pointer-fine:` variants are recognised again (stray space in the variant regex). - Numeric custom class names are prefixed (tc-) so selectors stay valid. - `, ``, ...) case-insensitively while + * returning offsets that are valid for the *original* source string. + * + * Lower-casing a whole file to search for a closing tag is unsafe (some Unicode + * characters change length when lower-cased, shifting every later offset) and + * wasteful, so this helper uses an anchored, case-insensitive scan instead. + * + * @param {string} source + * @param {string} tagName + * @param {number} fromIdx + * @returns {number} index of `<` in the closing tag, or -1 + */ +function findClosingTagIndex(source, tagName, fromIdx) { + const needle = `]/.test(source[end])) return idx; + } + i = idx + 1; + } + return -1; +} + /** * Advance past a JS/HTML quoted string starting at `quoteIdx`. * Returns the index of the closing quote, or `source.length` if unterminated. @@ -514,8 +544,8 @@ function scanSource(source, filePath, config = {}) { // Skip raw blocks completely if (lowerTag === "style" && !parsedTag.selfClosing) { - const closeStyle = source.toLowerCase().indexOf("", parsedTag.tagEndIdx + 1); - const nextIdx = closeStyle === -1 ? len : closeStyle + 8; + const closeStyle = findClosingTagIndex(source, "style", parsedTag.tagEndIdx + 1); + const nextIdx = closeStyle === -1 ? len : closeStyle + "".length; ignoredRanges.push([parsedTag.tagEndIdx + 1, nextIdx]); i = nextIdx; continue; @@ -542,8 +572,8 @@ function scanSource(source, filePath, config = {}) { // Skip raw RCDATA inside so literal sample text is never rewritten if (lowerTag === "textarea" && !parsedTag.selfClosing) { - const closeTa = source.toLowerCase().indexOf("", parsedTag.tagEndIdx + 1); - const nextIdx = closeTa === -1 ? len : closeTa + 11; + const closeTa = findClosingTagIndex(source, "textarea", parsedTag.tagEndIdx + 1); + const nextIdx = closeTa === -1 ? len : closeTa + "".length; ignoredRanges.push([parsedTag.tagEndIdx + 1, nextIdx]); i = nextIdx; continue; diff --git a/src/tailwind.js b/src/tailwind.js index 3ceb1ad..35c837f 100644 --- a/src/tailwind.js +++ b/src/tailwind.js @@ -1,5 +1,7 @@ "use strict"; +const { isCssSafeToken } = require("./css-safety"); + /** * Exact single-token Tailwind CSS v3 & v4 utilities. * Mapped to [bucket, propertyGroup]. @@ -286,7 +288,7 @@ const PREFIX_RULES = [ * container queries, aria/data/supports/has, arbitrary variants). */ const VALID_VARIANT_RE = - /^(?:sm|md|lg|xl|2xl|max-(?:sm|md|lg|xl|2xl|\[.+\])|min-\[.+\]|@[a-z0-9_-]+(?:\/[a-zA-Z0-9_-]+)?|hover|focus|focus-within|focus-visible|active|visited|target|first|last|only|odd|even|first-of-type|last-of-type|only-of-type|empty|disabled|enabled|checked|indeterminate|default|optional|required|valid|invalid|user-valid|user-invalid|in-range|out-of-range|placeholder-shown|autofill|read-only|open|closed|before|after|first-letter|first-line|marker|selection|file|backdrop|placeholder|details-content|dark|light|print|portrait|landscape|motion-safe|motion-reduce|contrast-more|contrast-less|forced-colors|inverted-colors|noscript| pointer-fine|pointer-coarse|any-pointer-fine|any-pointer-coarse|ltr|rtl|starting|inert|(?:group|peer|has|in|not)-(?:[a-z0-9-]+|\[.+\])(?:\/[a-zA-Z0-9_-]+)?|(?:aria|data|supports|nth|nth-last|nth-of-type|nth-last-of-type)-(?:[a-z0-9-]+|\[.+\])|\*|\*\*|\[.+\])$/; + /^(?:sm|md|lg|xl|2xl|max-(?:sm|md|lg|xl|2xl|\[.+\])|min-\[.+\]|@[a-z0-9_-]+(?:\/[a-zA-Z0-9_-]+)?|hover|focus|focus-within|focus-visible|active|visited|target|first|last|only|odd|even|first-of-type|last-of-type|only-of-type|empty|disabled|enabled|checked|indeterminate|default|optional|required|valid|invalid|user-valid|user-invalid|in-range|out-of-range|placeholder-shown|autofill|read-only|open|closed|before|after|first-letter|first-line|marker|selection|file|backdrop|placeholder|details-content|dark|light|print|portrait|landscape|motion-safe|motion-reduce|contrast-more|contrast-less|forced-colors|inverted-colors|noscript|pointer-fine|pointer-coarse|any-pointer-fine|any-pointer-coarse|ltr|rtl|starting|inert|(?:group|peer|has|in|not)-(?:[a-z0-9-]+|\[.+\])(?:\/[a-zA-Z0-9_-]+)?|(?:aria|data|supports|nth|nth-last|nth-of-type|nth-last-of-type)-(?:[a-z0-9-]+|\[.+\])|\*|\*\*|\[.+\])$/; /** * Canonical ordering priority for variants so `sm:` comes before `md:`, `lg:`, @@ -392,6 +394,27 @@ function classifyToken(rawToken, options = {}) { }; } + // Class tokens are ultimately written into `@apply` rules inside the generated + // stylesheet. Tokens carrying `;`, `{`, `}`, control characters or `*/` could + // terminate the declaration/rule (or the surrounding comment) and inject + // arbitrary CSS, so they are never treated as applyable Tailwind utilities. + // They are kept inline in the markup (and thus still work) instead. + if (!isCssSafeToken(token)) { + return { + raw: token, + variants: [], + base: token, + important: false, + negative: false, + isTailwind: false, + isApplyable: false, + isMarker: false, + bucket: 99, + propertyGroup: "custom", + sortKey: `99|${token}`, + }; + } + const parts = splitTopLevelColons(token); const rawUtility = parts[parts.length - 1]; const variants = parts.slice(0, -1); diff --git a/test/glob.test.js b/test/glob.test.js new file mode 100644 index 0000000..919d4d9 --- /dev/null +++ b/test/glob.test.js @@ -0,0 +1,115 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const test = require("node:test"); +const { + MAX_GLOB_PATTERN_LENGTH, + clearGlobCache, + compileGlob, + expandBraces, + matchesAnyGlob, +} = require("../src/glob"); + +test("glob matcher keeps its documented semantics", () => { + const cases = [ + ["**/*.html", "a/b/c.html", true], + ["**/*.html", "c.html", true], + ["**/*.html", "c.htm", false], + ["src/**", "src/a/b.js", true], + ["src/**", "lib/a/b.js", false], + ["*.js", "src/a.js", true], // no slash in pattern -> basename match + ["src/*.js", "src/a/b.js", false], + ["?.js", "a.js", true], + ["?.js", "ab.js", false], + ["[abc].js", "b.js", true], + ["[abc].js", "d.js", false], + ["[!abc].js", "d.js", true], + ["[a-c]x", "bx", true], + ["**", "a/b", true], + ["a/**/b", "a/b", true], + ["a/**/b", "a/x/y/b", true], + ["a/**/b", "a/x/y/c", false], + ["node_modules/**", "node_modules/pkg/index.js", true], + ["node_modules/**", "src/node_modules.js", false], + ["*.{js,ts}", "x.ts", true], + ["*.{js,ts}", "x.css", false], + ]; + + for (const [pattern, candidate, expected] of cases) { + assert.equal( + compileGlob(pattern)(candidate), + expected, + `${pattern} vs ${candidate} should be ${expected}` + ); + } +}); + +test("expandBraces handles multiple and nested alternatives", () => { + assert.deepEqual(expandBraces("a.{js,ts}"), ["a.js", "a.ts"]); + assert.deepEqual(expandBraces("{a,b}.{js,ts}"), ["a.js", "a.ts", "b.js", "b.ts"]); + assert.deepEqual(expandBraces("no-braces"), ["no-braces"]); + assert.deepEqual(expandBraces("unclosed{js"), ["unclosed{js"]); +}); + +test("matchesAnyGlob supports negated entries", () => { + const patterns = ["**/*.js", "!**/*.min.js"]; + assert.equal(matchesAnyGlob("src/app.js", patterns), true); + assert.equal(matchesAnyGlob("src/app.min.js", patterns), false); + assert.equal(matchesAnyGlob("src/app.html", patterns), false); + assert.equal(matchesAnyGlob("src/app.js", []), false); + assert.equal(matchesAnyGlob("src/app.js", null), false); +}); + +test("malformed character classes are treated as literals instead of crashing", () => { + assert.doesNotThrow(() => compileGlob("[")("anything")); + assert.equal(compileGlob("a[b")("a[b"), true); + assert.equal(compileGlob("[abc")("[abc"), true); + assert.equal(compileGlob("[]")("[]"), true); +}); + +test("pathological wildcard patterns match in linear time (no ReDoS)", () => { + clearGlobCache(); + const candidates = [ + ["**".repeat(40) + "z", "a".repeat(500)], + ["**/**/**/**/**/**/**/**/**/**/z", "/a".repeat(500)], + ["*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*b", "a".repeat(500)], + ["[".repeat(200) + "z", "[".repeat(200)], + ]; + + for (const [pattern, candidate] of candidates) { + const started = Date.now(); + const result = compileGlob(pattern)(candidate); + const elapsed = Date.now() - started; + assert.equal(result, false); + assert.ok( + elapsed < 2000, + `pattern ${pattern.slice(0, 24)}… took ${elapsed}ms (expected << 2s)` + ); + } +}); + +test("repeated compilation is cached and stays fast", () => { + clearGlobCache(); + const matcher = compileGlob("**/*.html"); + const started = Date.now(); + for (let i = 0; i < 20000; i++) { + matcher(`src/components/file-${i}.html`); + } + const firstRun = Date.now() - started; + + const startedAgain = Date.now(); + for (let i = 0; i < 20000; i++) { + compileGlob("**/*.html")(`src/components/file-${i}.html`); + } + const cachedRun = Date.now() - startedAgain; + + assert.ok(firstRun < 2000, `20k matches took ${firstRun}ms`); + assert.ok(cachedRun < 2000, `20k recompiled matches took ${cachedRun}ms`); +}); + +test("over-long glob patterns are rejected with a clear message", () => { + clearGlobCache(); + const pattern = "a".repeat(MAX_GLOB_PATTERN_LENGTH + 1); + assert.throws(() => compileGlob(pattern), /too long/i); + assert.throws(() => compileGlob("a\u0000b"), /NUL/); +}); diff --git a/test/security.test.js b/test/security.test.js new file mode 100644 index 0000000..a12c26b --- /dev/null +++ b/test/security.test.js @@ -0,0 +1,266 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const test = require("node:test"); +const { + applyAutoClasses, + classifyToken, + generateStylesheet, + resolveConfig, + revertProject, + sanitizeCustomClassName, +} = require("../src"); + +/** + * @param {string} prefix + * @returns {string} + */ +function tempDir(prefix) { + return fs.mkdtempSync(path.join(os.tmpdir(), `tailclass-${prefix}-`)); +} + +/** + * @param {string} dir + * @param {string} name + * @param {string} content + * @returns {string} + */ +function writeFile(dir, name, content) { + const target = path.join(dir, name); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, content, "utf8"); + return target; +} + +/** + * @param {string} file + * @returns {string} + */ +function read(file) { + return fs.readFileSync(file, "utf8"); +} + +const NAV = "sticky top-0 flex items-center justify-between bg-white px-6 py-4 border-b border-slate-200"; +const NAV_HTML = `\n\n`; + +test("config files cannot redirect generated output outside the project root", () => { + const dir = tempDir("traversal"); + const site = path.join(dir, "site"); + fs.mkdirSync(site); + writeFile(site, "index.html", NAV_HTML); + + for (const key of ["outputCss", "manifestFile", "dictionaryFile"]) { + writeFile(site, "tailclass.config.json", JSON.stringify({ [key]: "../escaped.css" })); + assert.throws( + () => resolveConfig(site), + /must stay inside the project root/, + `${key} should be confined to the project root` + ); + assert.throws(() => applyAutoClasses(site), /must stay inside the project root/); + } + + assert.equal(fs.existsSync(path.join(dir, "escaped.css")), false); + assert.match(read(path.join(site, "index.html")), /