diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 6fb6905..0882a92 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,25 +1,59 @@ name: Publish Package 📦 to npm (Trusted Publishing OIDC) +# Triggered by pushing a release tag (e.g. `git push origin v1.0.1`). +# The tag must be created on a commit that is already on `main`, otherwise the +# `build_and_test` job fails before anything is published. on: push: tags: - "v*" -# Least privilege at the workflow root; id-token: write is granted only to the publish job. +# Least privilege at the workflow root; `id-token: write` (npm OIDC) and +# `contents: write` (GitHub Release) are granted only to the jobs that need them. permissions: contents: read +# A re-pushed tag or a double-clicked re-run must not publish the same version twice. +concurrency: + group: publish-${{ github.ref }} + cancel-in-progress: false + jobs: build_and_test: name: Verify tag, lint, and run full layout test suite runs-on: ubuntu-latest + timeout-minutes: 20 steps: - uses: actions/checkout@v7 with: persist-credentials: false + fetch-depth: 0 # full history is needed for the branch ancestry check - uses: actions/setup-node@v7 with: node-version: "24" + - name: Verify the tag is a semantic version (`vX.Y.Z`) + run: | + if ! printf '%s' "$GITHUB_REF_NAME" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then + echo "::error::Tag '$GITHUB_REF_NAME' is not of the form vX.Y.Z. Aborting release." + exit 1 + fi + - name: Verify the tagged commit is on the default branch + run: | + # `fetch-depth: 0` normally already fetched origin/main; only fall back to + # an explicit fetch when it is missing. + if ! git rev-parse --verify -q refs/remotes/origin/main >/dev/null; then + git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main || true + fi + if ! git rev-parse --verify -q refs/remotes/origin/main >/dev/null; then + echo "::warning::Could not resolve origin/main; skipping ancestry check." + exit 0 + fi + if ! git merge-base --is-ancestor "$GITHUB_SHA" refs/remotes/origin/main; then + echo "::error::Tag $GITHUB_REF_NAME points at $GITHUB_SHA, which is not on main." + echo "::error::Merge the release commit into main first, then tag it. Nothing was published." + exit 1 + fi + echo "Tag $GITHUB_REF_NAME is on main ✔" - name: Verify git tag matches package.json and library version run: | node -e ' @@ -43,6 +77,7 @@ jobs: name: Publish to npm via OIDC Trusted Publisher needs: build_and_test runs-on: ubuntu-latest + timeout-minutes: 20 permissions: contents: read id-token: write # Required for npm OIDC Trusted Publishing & automatic provenance @@ -58,3 +93,44 @@ jobs: run: npm install -g npm@latest - name: Publish via OIDC (no NPM_TOKEN required; provenance is automatic) run: npm publish --access public + - name: Summarise the published package + run: | + { + echo "### Published 📦" + echo "" + echo "| Field | Value |" + echo "| --- | --- |" + echo "| Package | \`$(node -p 'require("./package.json").name')\` |" + echo "| Version | \`$(node -p 'require("./package.json").version')\` |" + echo "| Tag | \`$GITHUB_REF_NAME\` |" + echo "| npm | https://www.npmjs.com/package/tailclass/v/$(node -p 'require("./package.json").version') |" + } >> "$GITHUB_STEP_SUMMARY" + + release: + name: Create GitHub Release + needs: publish + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write # required to create the release/tag notes + steps: + - name: Create the release (idempotent) + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + echo "Release $GITHUB_REF_NAME already exists — leaving it untouched." + exit 0 + fi + gh release create "$GITHUB_REF_NAME" \ + --repo "$GITHUB_REPOSITORY" \ + --verify-tag \ + --title "TailClass $GITHUB_REF_NAME" \ + --generate-notes + - name: Summarise the release + run: | + { + echo "### Release 🏷️" + echo "" + echo "GitHub Release: https://github.com/$GITHUB_REPOSITORY/releases/tag/$GITHUB_REF_NAME" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/CHANGELOG.md b/CHANGELOG.md index b2d8f3a..5ec6af6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,74 @@ All notable changes to **TailClass** are documented here. The format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.0.1] — 2026-11-09 + +Security & robustness hardening. All items are covered by regression tests. Upgrading from +1.0.0 is recommended for anyone who runs TailClass on repositories they did not author +(including CI jobs on pull requests). + +### Security + +- **Path confinement (High).** `outputCss`, `dictionaryFile` and `manifestFile` coming + from a configuration file can no longer resolve outside the scanned project root, so a + cloned repository can no longer make `apply`/`list` write — or `revert --clean` delete — + arbitrary files. CLI-supplied paths remain unrestricted. Writes now go through a single + checked resolver (`resolveWritablePath`). +- **CSS injection (High).** Class tokens containing `;`, `{`, `}`, control characters or + comment terminators are no longer treated as applyable utilities; they are preserved + inline on the element instead of being emitted into `@apply`. The stylesheet generator + independently validates selectors and payloads. +- **ReDoS (High).** The glob matcher is now a backtracking-free dynamic-programming + matcher (`O(pattern × candidate)`) instead of a translated `RegExp`. Pathological + patterns such as `****…z` used to hang the process; they now finish in milliseconds. + Compiled matchers are cached and patterns are length-capped. +- **`classPrefix` injection (Medium).** Prefixes must match `^[A-Za-z0-9_-]*$` and may not + produce a selector starting with a digit; they are sanitized again in the namer. +- **Dictionary comment injection (Medium).** `label`, `category` and `elements` values are + sanitized before being embedded in generated CSS comments. +- **`revert` hardening (Low).** Manifest entries that are not valid class names, or whose + expansion could break out of a markup attribute, are ignored; corrupt manifests produce + a descriptive error. + +### Added + +- `src/css-safety.js` — shared validators/sanitizers (`isCssSafeToken`, + `isValidClassIdentifier`, `sanitizeCommentText`, `sanitizeElementName`, + `sanitizeClassPrefix`). +- `--force` for `apply`/`revert`: required before overwriting a stylesheet or manifest that + does not look like TailClass output. +- Configuration diagnostics: unknown keys and coerced values are reported as warnings on + **stderr** (keeping `--json` stdout machine-readable). +- Tests: `test/glob.test.js` (glob semantics, ReDoS timings, caching) and + `test/security.test.js` (traversal, clobbering, CSS injection, config validation). + +### Changed + +- `VERSION` now lives in `src/version.js` and is reused by the generated stylesheet + header, the revert manifest and the dictionary payload (previously three hard-coded + `"1.0.0"` fallbacks could drift from `package.json`). +- Configuration is validated up front: array entries, numeric thresholds, booleans, + enums and prefixes produce actionable errors (`Invalid exclude[1]: expected a string, + received null`) instead of `TypeError`s, and JSON parse errors name the offending file. +- `apply` refuses to overwrite a scanned source file, or a stylesheet/manifest that it + does not own (unless `--force`). +- `.git/`, `node_modules/` and `.tailclass-backup/` are always excluded, even when + `replaceDefaultExcludes` is `true`. +- `revertProject()` now returns the resolved `config` (like the other workflows); + `config.warnings` and `config.pathSources` are available to API consumers. +- Unknown `rules` entries are skipped with a warning rather than throwing. + +### Fixed + +- `pointer-fine:*` utilities are recognised again (a stray space made the variant + unreachable). +- Numeric custom class names (`"123btn"`) are prefixed (`tc-123btn`) so selectors stay + valid CSS. +- ``, ``, ...) 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/src/version.js b/src/version.js new file mode 100644 index 0000000..4df1f95 --- /dev/null +++ b/src/version.js @@ -0,0 +1,14 @@ +"use strict"; + +/** + * Single source of truth for the TailClass version. + * + * `package.json`, the generated stylesheet header, the revert manifest and the + * dictionary payload all read it from here, and `scripts/lint.js` fails the build + * when `package.json` and this constant disagree. + * + * @type {string} + */ +const VERSION = "1.0.1"; + +module.exports = { VERSION }; diff --git a/test/cli.test.js b/test/cli.test.js index f467468..bf023d5 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -8,6 +8,7 @@ const { Writable } = require("node:stream"); const test = require("node:test"); const { pathToFileURL } = require("node:url"); const { runCli } = require("../src/cli"); +const { VERSION } = require("../src/version"); function execCli(args) { let out = ""; @@ -29,10 +30,17 @@ function execCli(args) { return { code, out, err }; } +test("package.json, src/version.js and the CLI agree on the version", () => { + const pkg = require("../package.json"); + assert.equal(VERSION, pkg.version); + assert.equal(require("../src").VERSION, pkg.version); +}); + test("CLI --version, --help, and unknown flag handling", () => { const ver = execCli(["--version"]); assert.equal(ver.code, 0); - assert.match(ver.out, /TailClass v1\.0\.0/); + // Keep version assertions version-agnostic so a release bump never breaks the suite. + assert.equal(ver.out.trim(), `TailClass v${VERSION}`); const help = execCli(["--help"]); assert.equal(help.code, 0); 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..1093d30 --- /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")), /