diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 8e58ebe..75ba718 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -30,7 +30,7 @@ If applicable, paste terminal output or screenshots to help explain your problem - OS: [e.g. Windows, macOS, Ubuntu] - OS version: [e.g. Windows 11 (x64)] - Node.js: [e.g. v22.11.0] - - TailClass version: [e.g. 1.0.0] + - TailClass version: [e.g. 1.0.2] - Tailwind CSS version: [e.g. v3.4 / v4.0] - Framework (if relevant): [e.g. Plain HTML, React/Next.js, Vue, Svelte, Astro] diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 0882a92..86c81ea 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,6 +1,6 @@ name: Publish Package 📦 to npm (Trusted Publishing OIDC) -# Triggered by pushing a release tag (e.g. `git push origin v1.0.1`). +# Triggered by pushing a release tag (e.g. `git push origin v1.0.2`). # 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: diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ec6af6..4e3a547 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,78 @@ 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.2] — 2026-11-09 + +Security release. Fixes two escape hatches found during follow-up testing of the +1.0.1 hardening. Upgrading is recommended for anyone running TailClass against +repositories they did not author (including CI jobs on pull requests). + +### Security + +- **Symlink path traversal (High).** `outputCss`, `dictionaryFile` and + `manifestFile` were confined by a lexical `path.resolve()` check only. A + repository containing a directory symlink (for example `assets -> ../../.ssh`) + could therefore make `apply`/`list` write — or `revert --clean` delete — files + outside the project root even though the configured string never left it. + Config-derived paths are now checked component by component with + `lstat`/`realpath` against the **real** project root; a TailClass output file + may not be a symlink, and symlinks that resolve outside the root are rejected + before any write or deletion. Writes use `O_NOFOLLOW`, re-validate after + creating parent directories, and never follow a symlink for the final + component. Backups under `.tailclass-backup/` and the auto-discovered + dictionary are covered as well. Symlinked **directories** whose real path + stays inside the root keep working. +- **`revert --clean` arbitrary deletion (High).** `--clean` used to delete + whatever `outputCss`/`manifestFile` pointed at, without verifying ownership — + a hand-written stylesheet, an unrelated JSON file, or a file outside the root + reachable through a symlink. It now removes only files positively identified + as TailClass output (the generated header, or `@apply` rules matching an owned + manifest), and never a scanned source file, symlink or directory. Unowned + files are left in place and reported through `cleanupSkipped` plus a stderr + warning. `--force` never relaxes this rule. + +### Added + +- `src/fs-safety.js` — realpath-based confinement plus `writeFileNoFollow()` and + `unlinkRegularFile()` helpers. +- `writeResolvedFile()` / `unlinkResolvedFile()` in `src/config.js`: every output + write and every `--clean` deletion goes through the checked resolver. +- Generated manifests now carry `generator: "TailClass"` and `manifestPath`, so + `--clean` can still locate the files TailClass owns after a config change. +- `revertProject()` returns `cleanedFiles` and `cleanupSkipped`. +- Tests: `test/path-safety.test.js` (symlink escapes, ownership checks, + markerless `--no-comments` CSS, scanned-source protection, explicit CLI paths). + +### Changed + +- **Behavior change (symlinked output files).** In 1.0.1 a symlink at an output + path (for example `tailclass.css -> src/styles/generated.css`) was followed: + `apply`/`list` wrote through it and `revert --clean` removed the link. The + final component of every output path must now be a **regular file**. A + symlinked output file is rejected **even when its target is inside the + project root**, even with `--force`, and even when the path was supplied on the + command line; `--clean` also never deletes a symlink, wherever it points. + TailClass fails with `Refusing to write ... the target is a symlink ...`. + To migrate, replace the link with a regular file, or point `outputCss` / + `dictionaryFile` / `manifestFile` at the real file. Symlinked *directories* + in the middle of a path are unaffected as long as they resolve inside the + root (for example `outputCss: "styles/generated.css"` with + `styles -> ./src/styles`). +- `revert --clean` reports the files it removed and warns on stderr about any + file it deliberately left untouched. +- The error for a symlinked output file now says explicitly that the target must + be a regular file and how to migrate; it no longer suggests `--output`, which + is also rejected for symlinked output files. `--help` carries the same note. +- Configuration schema, README and SECURITY.md document that config-supplied + paths may not traverse symlinks and that `--clean` only deletes owned files. + +### Fixed + +- `apply` no longer reads the auto-discovered dictionary through an unchecked + path, and `--backup` writes are confined to the project root. +- `init` and source rewrites also refuse to follow a symlink at the final path + component. + ## [1.0.1] — 2026-11-09 Security & robustness hardening. All items are covered by regression tests. Upgrading from diff --git a/README.md b/README.md index 036d5c9..64dd2be 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ Don't want automatic names on certain patterns? Run **Class List Mode** (`tailcl **Centralized `tailclass.css` (edit once to restyle everywhere):** ```css -/* Generated by TailClass v1.0.1 — https://github.com/Infinitode/TailClass */ +/* Generated by TailClass v1.0.2 — https://github.com/Infinitode/TailClass */ /* Centralized Tailwind component classes. Edit rules here to update styles site-wide. */ @layer components { @@ -188,7 +188,7 @@ This prints a full breakdown in your terminal and generates **`tailclass.map.jso ```json { "$schema": "https://raw.githubusercontent.com/Infinitode/TailClass/main/schema/tailclass.map.schema.json", - "version": "1.0.1", + "version": "1.0.2", "summary": { "filesScanned": 12, "filesWithClasses": 11, @@ -312,8 +312,22 @@ untrusted input: - `outputCss`, `dictionaryFile` and `manifestFile` **must stay inside the project root** when they come from the config file (use `-o`/`--dict` on the command line for - deliberate out-of-root targets). `apply` additionally refuses to overwrite a scanned - source file, or a stylesheet/manifest that it does not own, unless `--force` is used. + deliberate out-of-root targets). This is a **physical** check: every existing path + component is resolved with `lstat`/`realpath` against the real project root, so a + directory symlink cannot redirect a write outside the project. Symlinked + *directories* that resolve inside the root still work. `apply` additionally refuses + to overwrite a scanned source file, or a stylesheet/manifest that it does not own, + unless `--force` is used. +- **Behavior change in v1.0.2:** an output path's final component must be a regular + file, **not a symlink** — even when the link points to a file inside the project + root, even with `--force`, and even for an explicit CLI path. 1.0.1 wrote through + such links; 1.0.2 fails with `Refusing to write ... the target is a symlink ...`, + and `revert --clean` never deletes a symlink. Replace the link with a regular file + or point `outputCss`/`dictionaryFile`/`manifestFile` at the real file. Intermediate + directory symlinks are unaffected. +- `revert --clean` only deletes files TailClass can verify it generated; a foreign + stylesheet, an unrelated JSON file, a scanned source file or a symlink is left + untouched and reported as a warning. `--force` does not override this. - Invalid values fail loudly with the offending key (`Invalid exclude[1]: expected a string, received null`); unknown keys are reported as warnings on stderr. - Class tokens containing `;`, `{`, `}` or comment terminators are never emitted into @@ -360,7 +374,7 @@ tailclass [directory] [options] | `--strict-dict` | Only extract patterns explicitly present in `--dict`. | | `-d, --dry-run` | Preview edits and generated CSS without writing to disk. | | `--backup` | Back up original modified files into `.tailclass-backup/`. | -| `--force` | Overwrite a stylesheet/manifest that does not look like TailClass output. | +| `--force` | Overwrite a stylesheet/manifest that does not look like TailClass output on `apply`. Never permits `--clean` to delete foreign files. | | `-a, --all` | Include non-repeated / 1-off patterns in `list` mode. | | `--report ` | Export Markdown (`.md`) or CSV (`.csv`) audit report in `list` mode. | | `--format ` | CSS format: `tailwind-v3` (default), `tailwind-v4`, or `plain`. | @@ -377,7 +391,7 @@ tailclass [directory] [options] | `--include-classes ` | Restrict extraction to matching utility globs. | | `--ignore-tags ` | Comma-separated HTML/JSX tags to ignore. | | `--only-tags ` | Restrict auto-classing to specific HTML/JSX tags. | -| `--clean` | Remove `tailclass.css` and `.tailclass-manifest.json` after `revert`. | +| `--clean` | After `revert`, remove only the stylesheet/manifest TailClass generated (foreign files are kept with a warning). | | `--json` | Output structured JSON for CI pipelines and editor integrations. | --- diff --git a/SECURITY.md b/SECURITY.md index 97af451..bc942a7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -14,9 +14,27 @@ repository you clone. configuration file must resolve inside the scanned project root; paths that escape it are rejected before anything is written or deleted. Paths supplied explicitly on the command line (`--output`, `--dict`, `--report`) are honoured as-is. +- **Physical path confinement.** The root check is not merely lexical (`../`): + every existing component of an output path is `lstat`ed and resolved with + `realpath` against the real project root. A directory symlink planted in a cloned + repository can no longer redirect a write, read, backup or `revert --clean` + deletion outside the project. Writes use `O_NOFOLLOW` and re-validate after + creating parent directories. Symlinked *directories* whose real path stays inside + the root are still allowed. +- **Output files must be regular files (behavior change in 1.0.2).** The final + component of any output path may not be a symlink, even if the link points to a + file inside the root, even with `--force`, and even for an explicit CLI path; + `revert --clean` likewise never unlinks a symlink. 1.0.1 followed such links. + Point the output at the real file instead. This prevents a symlink from being + used to clobber, read or delete a file TailClass did not intend to touch. - **No clobbering.** `apply` refuses to overwrite a scanned source file, or a stylesheet/manifest that does not look like TailClass output, unless `--force` is given. +- **No arbitrary deletion.** `revert --clean` deletes only regular files TailClass + can positively identify as its own (generated CSS header, or `@apply` rules + matching an owned revert manifest). Foreign stylesheets, foreign JSON files, + scanned source files, symlinks and directories are left untouched and reported + via `cleanupSkipped`/stderr. `--force` does not override this. - **CSS payload validation.** Class tokens containing `;`, `{`, `}`, control characters or comment terminators are kept inline on the element and never emitted into `@apply`; selectors, comments and dictionary metadata are validated on output. @@ -28,7 +46,8 @@ repository you clone. | Version | Supported | |---------|-----------| -| 1.0.1+ | ✅ | +| 1.0.2+ | ✅ | +| 1.0.1 | ❌ superseded — upgrade for the v1.0.2 symlink / `--clean` fixes | | 1.0.0 | ❌ superseded — upgrade for the v1.0.1 security fixes | | < 1.0 | ❌ | @@ -54,7 +73,8 @@ window to ship a fix before any public disclosure. In scope: -- arbitrary file overwrite or path traversal outside the target project root caused by crafted configuration or dictionary files; +- arbitrary file overwrite, deletion or path traversal outside the target project root caused by crafted configuration, dictionary or manifest files — including symlink-based traversal; +- deletion of non-TailClass files by `revert --clean`; - catastrophic backtracking (ReDoS) or denial of service in the markup scanner, glob matcher, or Tailwind token parser; - CSS injection or source corruption triggered by unsanitized dictionary values; - supply-chain issues in the repository's build or release workflows. diff --git a/package.json b/package.json index c5a338e..6830228 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tailclass", - "version": "1.0.1", + "version": "1.0.2", "description": "An open-source Tailwind CSS auto-classer that scans sites for repeated utility layouts, assigns smart semantic component names, supports custom mapping dictionaries, and generates a centralized stylesheet.", "keywords": [ "tailwindcss", diff --git a/schema/tailclass.config.schema.json b/schema/tailclass.config.schema.json index ce7df76..0e5c3a4 100644 --- a/schema/tailclass.config.schema.json +++ b/schema/tailclass.config.schema.json @@ -25,17 +25,17 @@ "outputCss": { "type": "string", "default": "tailclass.css", - "description": "Output path for the generated centralized Tailwind CSS file. Must stay inside the scanned project root when set from a configuration file." + "description": "Output path for the generated centralized Tailwind CSS file. Must stay inside the scanned project root when set from a configuration file, including when path components are symlinks. The target must be a regular file, not a symlink (even a symlink pointing inside the root); symlinked directories that resolve inside the root are allowed." }, "dictionaryFile": { "type": "string", "default": "tailclass.map.json", - "description": "Path for Class List Mode dictionary output and lookup. Must stay inside the scanned project root when set from a configuration file." + "description": "Path for Class List Mode dictionary output and lookup. Must stay inside the scanned project root when set from a configuration file, including when path components are symlinks. The target must be a regular file, not a symlink (even a symlink pointing inside the root); symlinked directories that resolve inside the root are allowed." }, "manifestFile": { "type": "string", "default": ".tailclass-manifest.json", - "description": "Path for the revert manifest generated during apply. Must stay inside the scanned project root when set from a configuration file." + "description": "Path for the revert manifest generated during apply. Must stay inside the scanned project root when set from a configuration file, including when path components are symlinks. The target must be a regular file, not a symlink (even a symlink pointing inside the root); symlinked directories that resolve inside the root are allowed. revert --clean only deletes manifests TailClass can verify it generated and never deletes a symlink." }, "cssFormat": { "type": "string", diff --git a/src/cli.js b/src/cli.js index 78ea7f9..18cb1f9 100644 --- a/src/cli.js +++ b/src/cli.js @@ -287,7 +287,7 @@ function formatHelpText(c) { ` --strict-dict Only extract patterns explicitly listed in --dict`, ` -d, --dry-run Preview CSS & file changes without touching disk`, ` --backup Save original modified files under .tailclass-backup/`, - ` --force Overwrite a stylesheet/manifest TailClass does not own`, + ` --force Overwrite a non-TailClass stylesheet/manifest on "apply"`, ` -a, --all Include 1-off / non-repeated patterns in "list" mode`, ` --report Also export a .md or .csv report in "list" mode`, ` --format CSS output format: tailwind-v3 | tailwind-v4 | plain`, @@ -304,11 +304,15 @@ function formatHelpText(c) { ` --include-classes Only extract utilities matching these globs`, ` --ignore-tags HTML/JSX tags to skip (e.g. "svg,code")`, ` --only-tags Only auto-class specific tags (e.g. "nav,button,div")`, - ` --clean Delete tailclass.css and manifest after "revert"`, + ` --clean After "revert", delete only TailClass-owned output files`, ` --json Emit machine-readable JSON output`, ` -h, --help Display this help message`, ` -v, --version Display version number`, "", + `${c.bold("NOTE")}`, + ` Output paths must be regular files: a symlinked output file is rejected even`, + ` when the link points inside the project (v1.0.2). Directory symlinks are OK.`, + "", `${c.bold("EXAMPLES")}`, ` tailclass scan ./src`, ` tailclass list ./src --report class-report.md`, @@ -673,6 +677,13 @@ function runCli(argv, io = {}) { force: Boolean(flags.force), }); printConfigWarnings(writeErr, c, res.config); + // Surface skipped deletions on stderr in every mode, including `--json` + // (where stdout must stay machine-readable). + if (flags.clean && !res.dryRun) { + for (const note of res.cleanupSkipped || []) { + writeErr(c.yellow(`Warning: ${note}. --clean only removes files TailClass owns.`)); + } + } if (flags.json) { write(JSON.stringify(res, null, 2)); @@ -687,7 +698,17 @@ function runCli(argv, io = {}) { )} file(s).` ); if (flags.clean && !res.dryRun) { - write(`${c.green("✔")} Removed centralized stylesheet and manifest.`); + const removed = res.cleanedFiles || []; + const skipped = res.cleanupSkipped || []; + if (removed.length === 2 && skipped.length === 0) { + write(`${c.green("✔")} Removed centralized stylesheet and manifest.`); + } else if (removed.length > 0) { + write( + `${c.green("✔")} Removed ${removed.length} TailClass-generated file${ + removed.length === 1 ? "" : "s" + } (${removed.map((f) => path.basename(f)).join(", ")}).` + ); + } } return 0; } diff --git a/src/config.js b/src/config.js index 2dbafa7..f85db1c 100644 --- a/src/config.js +++ b/src/config.js @@ -4,6 +4,12 @@ const fs = require("node:fs"); const path = require("node:path"); const { toPosixPath, MAX_GLOB_PATTERN_LENGTH } = require("./glob"); const { sanitizeClassPrefix } = require("./css-safety"); +const { + assertNoSymlinkEscape, + ensureParentDirectory, + unlinkRegularFile, + writeFileNoFollow, +} = require("./fs-safety"); const DEFAULT_CONFIG = Object.freeze({ include: [ @@ -170,6 +176,10 @@ function loadConfigFile(rootDir, explicitConfigPath) { * files, e.g. `"outputCss": "../../.bashrc"`). Paths typed on the command line * are explicit user intent and are therefore allowed to leave the root. * + * The check is both lexical (`../`) and physical (directory/file symlinks): + * `"outputCss": "link/escaped.css"` with `link -> ../../outside` also escapes, + * even though the string itself never leaves the root. + * * @param {unknown} value * @param {string} key * @param {string} absRoot @@ -194,6 +204,22 @@ function validateOutputPath(value, key, absRoot) { if (/[\\/]$/.test(value)) { throw new Error(`Invalid ${key} "${value}": expected a file path, not a directory.`); } + + try { + assertNoSymlinkEscape(absRoot, resolved, { key, value, operation: "write" }); + } catch (err) { + if (!err.symlinkEscape) throw err; + // The CLI hint only applies when a link actually leaves the root. A symlink + // *at the output path* is rejected for CLI paths too, so suggesting `-o` + // there would send the user in the wrong direction. + const cliHint = err.pathEscapesRoot + ? " Pass the path on the command line instead if you really need it outside (e.g. --output)." + : ""; + throw new Error( + `Invalid ${key} "${value}": paths in the configuration file must stay inside the project root. ` + + `${err.message}${cliHint}` + ); + } return value; } @@ -210,34 +236,90 @@ function isInsideRoot(root, target) { } /** - * Resolve a path that TailClass is about to write to, enforcing that + * Resolve a path that TailClass is about to write to (or delete), enforcing that * repository-supplied configuration cannot escape the project root. * * `resolveConfig` performs this check already; writers repeat it so the low-level - * API is safe even when a caller builds a config object by hand. + * API is safe even when a caller builds a config object by hand. A caller that + * does not say where a path came from is treated as untrusted (`config`): only + * an explicit `pathSources[key] === "cli"` relaxes the root boundary. + * + * Beyond the lexical `../` check, every existing path component is resolved + * with `lstat`/`realpath`, so a symlinked directory or a symlinked output file + * cannot redirect a write (or a `revert --clean` deletion) outside the project. * * @param {string} absRoot * @param {unknown} value * @param {string} key * @param {Record} [config] + * @param {"write" | "delete"} [operation] * @returns {string} absolute path */ -function resolveWritablePath(absRoot, value, key, config = {}) { +function resolveWritablePath(absRoot, value, key, config = {}, operation = "write") { if (typeof value !== "string" || value.trim() === "" || value.includes("\u0000")) { throw new Error(`Invalid ${key}: expected a non-empty file path.`); } const resolved = path.resolve(absRoot, value); const source = - config && config.pathSources && config.pathSources[key] ? config.pathSources[key] : "cli"; - if (source !== "cli" && !isInsideRoot(absRoot, resolved)) { + config && config.pathSources && config.pathSources[key] !== undefined + ? config.pathSources[key] + : "config"; + const lexicallyInside = isInsideRoot(absRoot, resolved); + + if (source !== "cli" && !lexicallyInside) { throw new Error( - `Refusing to write ${key} "${value}" outside the project root (${absRoot}). ` + + `Refusing to ${operation} ${key} "${value}" outside the project root (${absRoot}). ` + `Paths from configuration files must stay inside the project.` ); } + // Even an explicit CLI path that lands inside the root must not be redirected + // through a symlink planted by the repository. + if (lexicallyInside) { + assertNoSymlinkEscape(absRoot, resolved, { key, value, operation }); + } return resolved; } +/** + * Write an output file through the checked resolver. + * + * The path is validated once more *after* the parent directories are created + * (so a component swapped in between cannot redirect the write), and the final + * `open()` refuses to follow a symlink. + * + * @param {string} absRoot + * @param {string} target absolute path previously returned by `resolveWritablePath` + * @param {string} key + * @param {Record} config + * @param {string} content + * @returns {string} the validated absolute path + */ +function writeResolvedFile(absRoot, target, key, config, content) { + const checked = resolveWritablePath(absRoot, target, key, config); + ensureParentDirectory(path.dirname(checked)); + resolveWritablePath(absRoot, checked, key, config); + writeFileNoFollow(checked, content); + return checked; +} + +/** + * Delete an output file through the checked resolver. Only regular files are + * removed; symlinks, directories and special files are reported back to the + * caller instead of being followed. + * + * @param {string} absRoot + * @param {string} target absolute path previously returned by `resolveWritablePath` + * @param {string} key + * @param {Record} config + * @param {string} [label] + * @returns {{ removed: boolean, reason: string | null }} + */ +function unlinkResolvedFile(absRoot, target, key, config, label = "file") { + const checked = resolveWritablePath(absRoot, target, key, config, "delete"); + resolveWritablePath(absRoot, checked, key, config, "delete"); + return unlinkRegularFile(checked, label); +} + /** * Validate that a config value is an array of non-empty strings. * @param {unknown} value @@ -517,5 +599,7 @@ module.exports = { validateOutputPath, isInsideRoot, resolveWritablePath, + writeResolvedFile, + unlinkResolvedFile, createStarterConfig, }; diff --git a/src/fs-safety.js b/src/fs-safety.js new file mode 100644 index 0000000..631f79c --- /dev/null +++ b/src/fs-safety.js @@ -0,0 +1,227 @@ +"use strict"; + +const fs = require("node:fs"); +const path = require("node:path"); + +/** + * Filesystem helpers for paths that are derived from repository content. + * + * A lexical `path.resolve()` check is not enough: if a cloned repository holds + * `assets -> /home/user/.ssh`, then `outputCss: "assets/authorized_keys"` looks + * like it is inside the project while `writeFileSync` follows the directory + * symlink and writes outside it. Every writable/deletable path is therefore + * checked component by component with `lstat`/`realpath` before use, and the + * final `open`/`unlink` refuses to follow a symlink. + */ + +/** `O_NOFOLLOW` is POSIX-only; on Windows the `lstat` guards below still apply. */ +const O_NOFOLLOW = fs.constants.O_NOFOLLOW || 0; + +/** + * @param {string} p + * @returns {string} + */ +function comparable(p) { + const resolved = path.resolve(p); + return process.platform === "win32" ? resolved.toLowerCase() : resolved; +} + +/** + * Like `isInsideRoot`, but `root === target` counts as inside. Used on *real* + * paths (the root directory itself is the boundary, not an output file). + * @param {string} root + * @param {string} target + * @returns {boolean} + */ +function isInsideOrEqual(root, target) { + const rel = path.relative(comparable(root), comparable(target)); + if (path.isAbsolute(rel)) return false; + return rel === "" || (rel !== ".." && !rel.startsWith(".." + path.sep)); +} + +/** + * @param {string} absRoot + * @returns {string} + */ +function realRootOf(absRoot) { + try { + return fs.realpathSync.native(absRoot); + } catch { + return path.resolve(absRoot); + } +} + +/** + * Verify that `resolved` does not pass through a symlink that leaves the + * project root, and that a TailClass-owned file is never itself a symlink. + * + * The check walks from the *real* project root. Existing components are + * `lstat`ed, and every symlink is resolved with `realpath`; a link that lands + * outside the real root (or cannot be resolved at all) is rejected. Missing + * components are harmless: they are created as real directories by the caller, + * which re-runs this check immediately before writing. + * + * Deliberate behavior change in 1.0.2: only *directory* symlinks that resolve + * inside the root are allowed. A symlink at the final component is rejected + * regardless of where it points, because writing (or deleting) through it could + * affect a file TailClass did not intend to touch. + * + * @param {string} absRoot + * @param {string} resolved absolute, lexically inside `absRoot` + * @param {{ key?: string, value?: string, operation?: string }} [options] + * @returns {string} `resolved` + */ +function assertNoSymlinkEscape(absRoot, resolved, options = {}) { + const key = options.key || "path"; + const value = options.value || resolved; + const operation = options.operation || "write"; + const rootReal = realRootOf(absRoot); + const rel = path.relative(path.resolve(absRoot), path.resolve(resolved)); + + if (rel === "" || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) { + const err = new Error( + `Refusing to ${operation} ${key} "${value}" outside the project root (${absRoot}).` + ); + err.symlinkEscape = true; + err.pathEscapesRoot = true; + throw err; + } + + const parts = rel.split(path.sep).filter(Boolean); + let cursor = rootReal; + + for (let i = 0; i < parts.length; i += 1) { + const candidate = path.join(cursor, parts[i]); + const isLast = i === parts.length - 1; + let st; + try { + st = fs.lstatSync(candidate); + } catch (err) { + if (err.code === "ENOENT" || err.code === "ENOTDIR") break; + throw err; + } + + if (st.isSymbolicLink()) { + let linkTarget = null; + try { + linkTarget = fs.realpathSync.native(candidate); + } catch { + // Broken symlinks are rejected too: their target can appear later. + } + if (!linkTarget || !isInsideOrEqual(rootReal, linkTarget)) { + const err = new Error( + `Refusing to ${operation} ${key} "${value}" outside the project root (${absRoot}): ` + + `the path passes through a symlink (symbolic link) at "${candidate}" ` + + `whose target resolves outside the project root.` + ); + err.symlinkEscape = true; + err.pathEscapesRoot = true; + throw err; + } + if (isLast) { + const err = new Error( + `Refusing to ${operation} ${key} "${value}": the target is a symlink (symbolic link). ` + + `TailClass output files must be regular files, even when the link points inside the project root. ` + + `Replace the symlink with a regular file or point ${key} at the real file.` + ); + err.symlinkEscape = true; + throw err; + } + // Continue walking from the resolved target so chained links are checked. + cursor = linkTarget; + } else { + if (!isLast && !st.isDirectory()) { + throw new Error( + `Refusing to ${operation} ${key} "${value}": "${candidate}" is not a directory.` + ); + } + cursor = candidate; + } + } + + return resolved; +} + +/** + * Create the parent directory for an output file. The caller re-validates the + * full path afterwards, so a component swapped for a symlink in the meantime is + * caught before the file is opened. + * @param {string} parentDir + */ +function ensureParentDirectory(parentDir) { + fs.mkdirSync(parentDir, { recursive: true }); +} + +/** + * Write `content` to `filePath` without ever following a symlink at the final + * component. `O_NOFOLLOW` closes the race between the `lstat` check and `open`. + * @param {string} filePath + * @param {string} content + */ +function writeFileNoFollow(filePath, content) { + let st = null; + try { + st = fs.lstatSync(filePath); + } catch (err) { + if (err.code !== "ENOENT" && err.code !== "ENOTDIR") throw err; + } + if (st && st.isSymbolicLink()) { + throw new Error( + `Refusing to write through a symlink (symbolic link): ${filePath}. ` + + `TailClass output files must be regular files even when the link points inside the project root; ` + + `replace the symlink or point the output at the real file.` + ); + } + if (st && st.isDirectory()) { + throw new Error(`Refusing to overwrite a directory: ${filePath}`); + } + + const flags = + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_TRUNC | O_NOFOLLOW; + const fd = fs.openSync(filePath, flags, 0o666); + try { + fs.writeFileSync(fd, content, "utf8"); + } finally { + fs.closeSync(fd); + } +} + +/** + * Delete a regular file, never a symlink, directory or special file. + * @param {string} filePath + * @param {string} [label] + * @returns {{ removed: boolean, reason: string | null }} + */ +function unlinkRegularFile(filePath, label = "file") { + let st; + try { + st = fs.lstatSync(filePath); + } catch (err) { + if (err.code === "ENOENT" || err.code === "ENOTDIR") { + return { removed: false, reason: null }; + } + throw err; + } + if (st.isSymbolicLink()) { + return { + removed: false, + reason: `left ${label} ${filePath} untouched: it is a symlink (symbolic link), even if its target is inside the project root`, + }; + } + if (!st.isFile()) { + return { + removed: false, + reason: `left ${label} ${filePath} untouched: it is not a regular file`, + }; + } + fs.unlinkSync(filePath); + return { removed: true, reason: null }; +} + +module.exports = { + isInsideOrEqual, + assertNoSymlinkEscape, + ensureParentDirectory, + writeFileNoFollow, + unlinkRegularFile, +}; diff --git a/src/index.js b/src/index.js index a71c2d4..f1e5e5b 100644 --- a/src/index.js +++ b/src/index.js @@ -13,7 +13,9 @@ const { loadConfigFile, resolveConfig, resolveWritablePath, + writeResolvedFile, } = require("./config"); +const { writeFileNoFollow } = require("./fs-safety"); const { buildDictionaryPayload, formatClassListCsv, @@ -76,16 +78,15 @@ function generateClassList(rootDir = ".", options = {}) { const absRoot = path.resolve(rootDir || "."); const { config, scan, analysis } = scanProject(absRoot, options); - const dictRelPath = options.dictionaryFile || config.dictionaryFile || "tailclass.map.json"; - const dictionaryPath = resolveWritablePath(absRoot, dictRelPath, "dictionaryFile", { - ...config, - pathSources: { - ...(config.pathSources || {}), - // `options.dictionaryFile` is an explicit caller/CLI choice; config-derived - // values stay confined by resolveConfig. - dictionaryFile: options.dictionaryFile ? "cli" : config.pathSources?.dictionaryFile, - }, - }); + // `resolveConfig` has already merged `options.dictionaryFile` into the config + // and recorded its provenance; use that single checked resolver rather than + // re-resolving the raw string (which would bypass the symlink checks). + const dictionaryPath = resolveWritablePath( + absRoot, + config.dictionaryFile || "tailclass.map.json", + "dictionaryFile", + config + ); let existingDictionary = null; if (options.merge !== false && fs.existsSync(dictionaryPath)) { @@ -103,8 +104,13 @@ function generateClassList(rootDir = ".", options = {}) { }); if (options.write !== false) { - fs.mkdirSync(path.dirname(dictionaryPath), { recursive: true }); - fs.writeFileSync(dictionaryPath, JSON.stringify(dictionary, null, 2) + "\n", "utf8"); + writeResolvedFile( + absRoot, + dictionaryPath, + "dictionaryFile", + config, + JSON.stringify(dictionary, null, 2) + "\n" + ); } let reportPath = null; @@ -119,8 +125,9 @@ function generateClassList(rootDir = ".", options = {}) { ? formatClassListCsv(dictionary) : formatClassListMarkdown(dictionary); if (options.write !== false) { - fs.mkdirSync(path.dirname(reportPath), { recursive: true }); - fs.writeFileSync(reportPath, reportBody, "utf8"); + writeResolvedFile(absRoot, reportPath, "reportFile", { + pathSources: { reportFile: "cli" }, + }, reportBody); } } @@ -150,9 +157,13 @@ function applyAutoClasses(rootDir = ".", options = {}) { if (options.dictionary) { dictionaryObj = loadDictionary(options.dictionary, absRoot); } else if (!options.ignoreDictionary) { - const defaultDictPath = path.resolve( + // The auto-discovered dictionary comes from the repository: use the same + // confined resolver as the writers so a symlink cannot redirect the read. + const defaultDictPath = resolveWritablePath( absRoot, - config.dictionaryFile || "tailclass.map.json" + config.dictionaryFile || "tailclass.map.json", + "dictionaryFile", + config ); if (fs.existsSync(defaultDictPath)) { dictionaryObj = loadDictionary(defaultDictPath, absRoot); @@ -191,6 +202,7 @@ function revertProject(rootDir = ".", options = {}) { ...revertProjectFiles(absRoot, config, { dryRun: Boolean(options.dryRun), clean: Boolean(options.clean), + force: Boolean(options.force), }), }; } @@ -214,7 +226,7 @@ function initConfig(rootDir = ".", options = {}) { const starter = createStarterConfig(); fs.mkdirSync(path.dirname(targetPath), { recursive: true }); - fs.writeFileSync(targetPath, JSON.stringify(starter, null, 2) + "\n", "utf8"); + writeFileNoFollow(targetPath, JSON.stringify(starter, null, 2) + "\n"); return { configPath: targetPath, config: starter }; } diff --git a/src/rewriter.js b/src/rewriter.js index f29ab37..b61cb51 100644 --- a/src/rewriter.js +++ b/src/rewriter.js @@ -4,7 +4,12 @@ const fs = require("node:fs"); const path = require("node:path"); const { checkSubsetCompatibility, computePatternId } = require("./analyzer"); const { isValidClassIdentifier } = require("./css-safety"); -const { resolveWritablePath } = require("./config"); +const { + resolveWritablePath, + unlinkResolvedFile, + writeResolvedFile, +} = require("./config"); +const { writeFileNoFollow } = require("./fs-safety"); const { generateStylesheet, parseExistingStylesheet } = require("./generator"); const { toPosixPath } = require("./glob"); const { scanSource } = require("./scanner"); @@ -71,6 +76,103 @@ function manifestLooksGenerated(content) { } } +/** Top-level keys ever written into a TailClass revert manifest. */ +const MANIFEST_KEYS = new Set([ + "generator", + "version", + "updatedAt", + "generatedAt", + "outputCss", + "manifestPath", + "filesModified", + "mappings", + "$schema", +]); + +/** + * Strict ownership check used before `--clean` deletes anything. + * + * `manifestLooksGenerated` is intentionally lenient (it decides whether a file + * may be *overwritten*). Deletion is irreversible, so a file only counts as a + * TailClass manifest when it carries our version/generator marker and a + * plausible `mappings` record. A random JSON file that happens to have a + * `mappings` key is not enough. + * + * @param {unknown} value + * @returns {boolean} + */ +function isTailClassManifestObject(value) { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + // A file belonging to another tool (package.json, a source map, ...) may also + // have `version`/`mappings`; its extra keys make it clearly not ours. + if (Object.keys(value).some((key) => !MANIFEST_KEYS.has(key))) return false; + const marked = + value.generator === "TailClass" || + (typeof value.version === "string" && /^\d+\.\d+\.\d+/.test(value.version)); + if (!marked) return false; + const mappings = value.mappings; + if (!mappings || typeof mappings !== "object" || Array.isArray(mappings)) return false; + const entries = Object.entries(mappings); + // A run with no extracted patterns still produces an (empty) owned manifest. + if (entries.length === 0) return true; + return entries.some( + ([name, utilities]) => isValidClassIdentifier(name) && isSafeExpansion(utilities) + ); +} + +/** + * @param {string} text + * @returns {string} + */ +function normalizeUtilities(text) { + if (typeof text !== "string") return ""; + return splitClassTokens(text).sort().join(" "); +} + +/** + * Decide whether a stylesheet may be deleted by `revert --clean`. + * + * A generated stylesheet is recognised by its header marker. When comments were + * disabled (`--no-comments`) there is no header, so every `@apply` rule must + * instead match the class → utilities record in an owned revert manifest. + * Foreign CSS (including CSS that merely contains a few `@apply` rules) is + * never deleted. + * + * @param {string} cssText + * @param {unknown} manifest parsed manifest object, or null + * @returns {boolean} + */ +function stylesheetIsOwned(cssText, manifest) { + if (typeof cssText !== "string" || cssText.trim() === "") return false; + let rules; + try { + rules = parseExistingStylesheet(cssText); + } catch { + return false; + } + if (!rules || rules.size === 0) return false; + + // Require the real generated header (with its version), not just a stray + // mention of the tool name inside someone else's stylesheet. + const hasMarker = /\/\*\s*Generated by TailClass v\d+\.\d+\.\d+/.test(cssText); + const mappings = isTailClassManifestObject(manifest) ? manifest.mappings : null; + if (!hasMarker && !mappings) return false; + + for (const [name, utilities] of rules) { + if (!isValidClassIdentifier(name) || !isSafeExpansion(utilities)) return false; + if (!hasMarker) { + const expected = mappings[name]; + if ( + typeof expected !== "string" || + normalizeUtilities(expected) !== normalizeUtilities(utilities) + ) { + return false; + } + } + } + return true; +} + /** * Read a file only when it is safe to treat as TailClass output. * @param {string} filePath @@ -512,10 +614,19 @@ function applyMappingsToProject(scanResult, resolvedMappings, config, runOptions if (!dryRun) { if (backup) { const backupDest = path.join(absRoot, ".tailclass-backup", relFile); - fs.mkdirSync(path.dirname(backupDest), { recursive: true }); - fs.writeFileSync(backupDest, source, "utf8"); + // `.tailclass-backup/` is repository content too: make sure a symlink + // there cannot redirect backups outside the project. + const checkedBackup = resolveWritablePath( + absRoot, + path.relative(absRoot, backupDest), + "backupFile", + config + ); + fs.mkdirSync(path.dirname(checkedBackup), { recursive: true }); + resolveWritablePath(absRoot, checkedBackup, "backupFile", config); + writeFileNoFollow(checkedBackup, source); } - fs.writeFileSync(fullPath, res.output, "utf8"); + writeFileNoFollow(fullPath, res.output); } } @@ -539,8 +650,7 @@ function applyMappingsToProject(scanResult, resolvedMappings, config, runOptions }); if (!dryRun) { - fs.mkdirSync(path.dirname(outputCssPath), { recursive: true }); - fs.writeFileSync(outputCssPath, cssContent, "utf8"); + writeResolvedFile(absRoot, outputCssPath, "outputCss", config, cssContent); const mappingRecord = {}; for (const m of finalMappings) { @@ -548,14 +658,22 @@ function applyMappingsToProject(scanResult, resolvedMappings, config, runOptions } const manifestPayload = { + generator: "TailClass", version: runOptions.version || VERSION, updatedAt: new Date().toISOString(), outputCss: toPosixPath(path.relative(absRoot, outputCssPath)), + manifestPath: toPosixPath(path.relative(absRoot, manifestPath)), filesModified: fileEdits.map((f) => f.file), mappings: mappingRecord, }; - fs.writeFileSync(manifestPath, JSON.stringify(manifestPayload, null, 2) + "\n", "utf8"); + writeResolvedFile( + absRoot, + manifestPath, + "manifestFile", + config, + JSON.stringify(manifestPayload, null, 2) + "\n" + ); } return { @@ -575,9 +693,13 @@ function applyMappingsToProject(scanResult, resolvedMappings, config, runOptions * Revert centralized TailClass classes across a project back to inline Tailwind * utilities using `.tailclass-manifest.json` and/or `tailclass.css`. * + * `clean` only ever deletes files that TailClass can positively identify as its + * own output. `--force` never relaxes that rule: deleting a foreign stylesheet, + * manifest or source file is irreversible and is not needed to complete a revert. + * * @param {string} rootDir * @param {Record} config - * @param {{ dryRun?: boolean, clean?: boolean, filesScanned?: string[] }} [options] + * @param {{ dryRun?: boolean, clean?: boolean, force?: boolean, filesScanned?: string[] }} [options] */ function revertProjectFiles(rootDir, config, options = {}) { const absRoot = path.resolve(rootDir || "."); @@ -598,25 +720,41 @@ function revertProjectFiles(rootDir, config, options = {}) { const classToUtilities = new Map(); + let manifest = null; + let manifestOwned = false; if (fs.existsSync(manifestPath)) { - let manifest; + let raw; + try { + raw = fs.readFileSync(manifestPath, "utf8"); + } catch (err) { + throw new Error(`Invalid manifest ${manifestPath}: ${err.message}`); + } try { - manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + manifest = JSON.parse(raw); } catch (err) { throw new Error(`Invalid manifest ${manifestPath}: ${err.message}`); } - const mappings = manifest && typeof manifest.mappings === "object" ? manifest.mappings : {}; + manifestOwned = isTailClassManifestObject(manifest); + const mappings = + manifest && typeof manifest.mappings === "object" && manifest.mappings !== null + ? manifest.mappings + : {}; for (const [k, v] of Object.entries(mappings)) { if (typeof v !== "string") continue; classToUtilities.set(k, v); } } + let cssOwned = false; if (fs.existsSync(outputCssPath)) { - const fromCss = parseExistingStylesheet(fs.readFileSync(outputCssPath, "utf8")); - for (const [k, v] of fromCss.entries()) { - if (!classToUtilities.has(k)) { - classToUtilities.set(k, v); + const cssText = safeReadText(outputCssPath); + if (cssText !== null) { + cssOwned = stylesheetIsOwned(cssText, manifest); + const fromCss = parseExistingStylesheet(cssText); + for (const [k, v] of fromCss.entries()) { + if (!classToUtilities.has(k)) { + classToUtilities.set(k, v); + } } } } @@ -643,6 +781,7 @@ function revertProjectFiles(rootDir, config, options = {}) { exclude: config.exclude, }); + const scannedPaths = new Set(candidateFiles.map((f) => toPosixPath(f))); const filesReverted = []; let totalReverted = 0; @@ -659,13 +798,98 @@ function revertProjectFiles(rootDir, config, options = {}) { totalReverted += rev.revertedCount; if (!dryRun) { - fs.writeFileSync(fullPath, rev.output, "utf8"); + writeFileNoFollow(fullPath, rev.output); } } + const cleanedFiles = []; + const cleanupSkipped = []; + if (!dryRun && clean) { - if (fs.existsSync(outputCssPath)) fs.unlinkSync(outputCssPath); - if (fs.existsSync(manifestPath)) fs.unlinkSync(manifestPath); + /** @type {Array<{ target: string, key: string, label: string, owned: boolean, config: object }>} */ + const targets = [ + { target: manifestPath, key: "manifestFile", label: "manifest", owned: manifestOwned, config }, + { target: outputCssPath, key: "outputCss", label: "stylesheet", owned: cssOwned, config }, + ]; + + // `apply` records the paths it wrote. If the config changed afterwards, the + // recorded paths still let `--clean` remove the real generated files instead + // of leaving them behind (or deleting whatever the new config points at). + const confinedConfig = (key) => ({ + ...config, + pathSources: { ...(config.pathSources || {}), [key]: "config" }, + }); + const resolveRecorded = (raw, key) => { + if (typeof raw !== "string" || raw.trim() === "" || raw.includes("\u0000")) return null; + try { + return resolveWritablePath(absRoot, raw, key, confinedConfig(key)); + } catch { + return null; // hostile/legacy recorded path is ignored, never followed + } + }; + + if (manifestOwned) { + const recordedCss = resolveRecorded(manifest.outputCss, "outputCss"); + if (recordedCss && recordedCss !== outputCssPath) { + targets.push({ + target: recordedCss, + key: "outputCss", + label: "stylesheet recorded in the manifest", + owned: stylesheetIsOwned(safeReadText(recordedCss), manifest), + config: confinedConfig("outputCss"), + }); + } + const recordedManifest = resolveRecorded(manifest.manifestPath, "manifestFile"); + if (recordedManifest && recordedManifest !== manifestPath) { + let recordedText = safeReadText(recordedManifest); + let recordedJson = null; + try { + recordedJson = recordedText === null ? null : JSON.parse(recordedText); + } catch { + recordedJson = null; + } + targets.push({ + target: recordedManifest, + key: "manifestFile", + label: "manifest recorded in the manifest", + owned: isTailClassManifestObject(recordedJson), + config: confinedConfig("manifestFile"), + }); + } + } + + const seen = new Set(); + for (const entry of targets) { + if (seen.has(entry.target)) continue; + seen.add(entry.target); + // `--clean` must never remove a file TailClass is scanning/rewriting, + // even if a hostile config points an output path at it. + if (scannedPaths.has(toPosixPath(path.relative(absRoot, entry.target)))) { + cleanupSkipped.push( + `Refusing to delete ${entry.label} ${entry.target}: it is a scanned source file; left untouched` + ); + continue; + } + if (!entry.owned) { + cleanupSkipped.push( + `Refusing to delete ${entry.label} ${entry.target}: it does not look like TailClass output; left untouched` + ); + continue; + } + try { + const { removed, reason } = unlinkResolvedFile( + absRoot, + entry.target, + entry.key, + entry.config, + entry.label + ); + if (removed) cleanedFiles.push(entry.target); + else if (reason) cleanupSkipped.push(reason); + } catch (err) { + cleanupSkipped.push(`left ${entry.label} ${entry.target} untouched: ${err.message}`); + } + } } return { @@ -674,6 +898,8 @@ function revertProjectFiles(rootDir, config, options = {}) { totalFilesReverted: filesReverted.length, totalReverted, classesExpanded: Array.from(classToUtilities.keys()), + cleanedFiles, + cleanupSkipped, }; } diff --git a/src/version.js b/src/version.js index 4df1f95..8b7d344 100644 --- a/src/version.js +++ b/src/version.js @@ -9,6 +9,6 @@ * * @type {string} */ -const VERSION = "1.0.1"; +const VERSION = "1.0.2"; module.exports = { VERSION }; diff --git a/test/path-safety.test.js b/test/path-safety.test.js new file mode 100644 index 0000000..539ae15 --- /dev/null +++ b/test/path-safety.test.js @@ -0,0 +1,408 @@ +"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 { Writable } = require("node:stream"); +const { runCli } = require("../src/cli"); +const { + VERSION, + applyAutoClasses, + generateClassList, + resolveConfig, + revertProject, +} = require("../src"); +const { resolveWritablePath, unlinkResolvedFile, writeResolvedFile } = require("../src/config"); + +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`; + +/** @param {string} prefix */ +function tempDir(prefix) { + return fs.mkdtempSync(path.join(os.tmpdir(), `tailclass-${prefix}-`)); +} + +/** @param {string} dir @param {string} name @param {string} content */ +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 */ +function read(file) { + return fs.readFileSync(file, "utf8"); +} + +/** Symlink creation can require elevated privileges on Windows. */ +function symlinksAvailable() { + const dir = tempDir("symlink-probe"); + try { + fs.mkdirSync(path.join(dir, "target")); + fs.symlinkSync(path.join(dir, "target"), path.join(dir, "link"), "dir"); + return true; + } catch { + return false; + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} +const SKIP_SYMLINKS = symlinksAvailable() ? false : "symbolic links unavailable"; + +function execCli(args) { + let out = ""; + let err = ""; + const stdout = new Writable({ write(chunk, _enc, cb) { out += chunk.toString(); cb(); } }); + const stderr = new Writable({ write(chunk, _enc, cb) { err += chunk.toString(); cb(); } }); + const code = runCli(args, { stdout, stderr, color: false }); + return { code, out, err }; +} + +test("release is version 1.0.2", () => { + assert.equal(require("../package.json").version, "1.0.2"); + assert.equal(VERSION, "1.0.2"); +}); + +test("configured output paths cannot escape through a symlinked directory", { skip: SKIP_SYMLINKS }, () => { + const cases = [ + ["outputCss", "escaped.css"], + ["manifestFile", "escaped-manifest.json"], + ["dictionaryFile", "escaped-map.json"], + ]; + + for (const [key, fileName] of cases) { + const dir = tempDir("symlink-escape"); + try { + const site = path.join(dir, "site"); + const outside = path.join(dir, "outside"); + fs.mkdirSync(site); + fs.mkdirSync(outside); + fs.symlinkSync(outside, path.join(site, "link"), "dir"); + writeFile(site, "index.html", NAV_HTML); + writeFile(site, "tailclass.config.json", JSON.stringify({ [key]: `link/${fileName}` })); + + // The config is rejected up front (and every workflow repeats the check). + assert.throws(() => resolveConfig(site), /symlink|project root/, key); + assert.throws(() => applyAutoClasses(site), /symlink|project root/, key); + assert.throws(() => generateClassList(site), /symlink|project root/, key); + assert.throws(() => revertProject(site, { clean: true }), /symlink|project root/, key); + + assert.deepEqual(fs.readdirSync(outside), [], `${key} must not write outside`); + assert.match(read(path.join(site, "index.html")), /sticky top-0/, "sources untouched"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + } +}); + +test("a symlinked output file is never written, even with --force", { skip: SKIP_SYMLINKS }, () => { + const dir = tempDir("symlink-file"); + try { + const site = path.join(dir, "site"); + const outside = path.join(dir, "outside"); + fs.mkdirSync(site); + fs.mkdirSync(outside); + writeFile(site, "index.html", NAV_HTML); + + const victimCss = writeFile(outside, "victim.css", "KEEP CSS\n"); + const victimManifest = writeFile(outside, "victim.json", "KEEP MANIFEST\n"); + fs.symlinkSync(victimCss, path.join(site, "tailclass.css"), "file"); + fs.symlinkSync(victimManifest, path.join(site, ".tailclass-manifest.json"), "file"); + + assert.throws(() => resolveConfig(site), /symlink/); + assert.throws(() => applyAutoClasses(site, { force: true }), /symlink/); + assert.throws(() => generateClassList(site), /symlink/); + assert.equal(read(victimCss), "KEEP CSS\n"); + assert.equal(read(victimManifest), "KEEP MANIFEST\n"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("revert --clean cannot delete an outside file through a symlinked directory", { skip: SKIP_SYMLINKS }, () => { + const dir = tempDir("symlink-clean"); + try { + const site = path.join(dir, "site"); + const outside = path.join(dir, "outside"); + fs.mkdirSync(site); + fs.mkdirSync(outside); + fs.symlinkSync(outside, path.join(site, "link"), "dir"); + const precious = writeFile(outside, "precious.txt", "DO NOT DELETE\n"); + writeFile(site, "index.html", '
a
\n'); + writeFile( + site, + ".tailclass-manifest.json", + JSON.stringify({ version: "1.0.2", mappings: { "tc-card": "flex p-4 m-2" } }) + ); + writeFile(site, "tailclass.config.json", JSON.stringify({ outputCss: "link/precious.txt" })); + + assert.throws(() => revertProject(site, { clean: true }), /symlink|project root/); + assert.equal(read(precious), "DO NOT DELETE\n"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("behavior change: a symlinked output file is rejected even when its target is inside the root", { skip: SKIP_SYMLINKS }, () => { + const dir = tempDir("symlink-inside-file"); + try { + writeFile(dir, "index.html", NAV_HTML); + const realCss = writeFile(dir, "real.css", "KEEP\n"); + fs.symlinkSync(realCss, path.join(dir, "tailclass.css"), "file"); + + // 1.0.1 followed this link; 1.0.2 refuses it in config validation and in + // every workflow, including with --force and an explicit CLI path. + assert.throws(() => resolveConfig(dir), /symlink/); + assert.throws(() => applyAutoClasses(dir, { force: true }), /symlink/); + assert.throws( + () => applyAutoClasses(dir, { outputCss: path.join(dir, "tailclass.css") }), + /symlink/ + ); + // The error must be explicit and must not suggest a workaround that is also + // rejected (CLI-supplied symlinked output files are refused too). + assert.throws( + () => resolveConfig(dir), + /even when the link points inside the project root/ + ); + try { + resolveConfig(dir); + assert.fail("expected a symlink error"); + } catch (err) { + assert.doesNotMatch(err.message, /Pass the path on the command line/); + } + assert.equal(read(realCss), "KEEP\n"); + assert.equal(fs.lstatSync(path.join(dir, "tailclass.css")).isSymbolicLink(), true); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("--clean never unlinks a symlink, wherever it points", { skip: SKIP_SYMLINKS }, () => { + const base = tempDir("symlink-clean-inside"); + try { + const site = path.join(base, "site"); + const outside = path.join(base, "outside"); + fs.mkdirSync(site); + fs.mkdirSync(outside); + const realCss = writeFile(outside, "real.css", "KEEP\n"); + const link = path.join(outside, "linked.css"); + fs.symlinkSync(realCss, link, "file"); + + // An explicit CLI path outside the root skips root confinement, but the + // deletion helper still refuses to unlink the symlink itself. + const outcome = unlinkResolvedFile( + site, + link, + "outputCss", + { pathSources: { outputCss: "cli" } }, + "stylesheet" + ); + assert.equal(outcome.removed, false); + assert.match(outcome.reason || "", /symlink/); + assert.equal(fs.lstatSync(link).isSymbolicLink(), true); + assert.equal(read(realCss), "KEEP\n"); + } finally { + fs.rmSync(base, { recursive: true, force: true }); + } +}); + +test("directory symlinks that stay inside the root remain usable", { skip: SKIP_SYMLINKS }, () => { + const dir = tempDir("symlink-inside"); + try { + fs.mkdirSync(path.join(dir, "assets")); + fs.symlinkSync(path.join(dir, "assets"), path.join(dir, "link"), "dir"); + writeFile(dir, "index.html", NAV_HTML); + writeFile(dir, "tailclass.config.json", JSON.stringify({ outputCss: "link/generated.css" })); + + applyAutoClasses(dir); + assert.equal(fs.existsSync(path.join(dir, "assets", "generated.css")), true); + + const rev = revertProject(dir, { clean: true }); + assert.equal(rev.totalReverted, 2); + assert.equal(rev.cleanedFiles.length, 2); + assert.deepEqual(rev.cleanupSkipped, []); + assert.equal(fs.existsSync(path.join(dir, "assets", "generated.css")), false); + assert.equal(fs.existsSync(path.join(dir, "link")), true, "the symlink itself is kept"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("the low-level resolver never follows a symlink for writes", { skip: SKIP_SYMLINKS }, () => { + const dir = tempDir("symlink-low-level"); + try { + const victim = writeFile(dir, "victim.css", "KEEP\n"); + fs.symlinkSync(victim, path.join(dir, "out.css"), "file"); + + assert.throws(() => resolveWritablePath(dir, "out.css", "outputCss"), /symlink/); + assert.throws( + () => writeResolvedFile(dir, path.join(dir, "out.css"), "outputCss", {}, "evil"), + /symlink/ + ); + assert.equal(read(victim), "KEEP\n"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("revert --clean deletes the stylesheet and manifest TailClass generated", () => { + const dir = tempDir("clean-owned"); + try { + writeFile(dir, "index.html", NAV_HTML); + applyAutoClasses(dir); + assert.equal(fs.existsSync(path.join(dir, "tailclass.css")), true); + assert.equal(fs.existsSync(path.join(dir, ".tailclass-manifest.json")), true); + + const rev = revertProject(dir, { clean: true }); + assert.equal(rev.totalReverted, 2); + assert.equal(rev.cleanedFiles.length, 2); + assert.deepEqual(rev.cleanupSkipped, []); + assert.equal(fs.existsSync(path.join(dir, "tailclass.css")), false); + assert.equal(fs.existsSync(path.join(dir, ".tailclass-manifest.json")), false); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("revert --clean leaves a foreign stylesheet untouched, even with --force", () => { + const dir = tempDir("clean-foreign-css"); + try { + writeFile(dir, "index.html", '
a
\n'); + writeFile( + dir, + ".tailclass-manifest.json", + JSON.stringify({ version: "1.0.2", mappings: { "tc-card": "flex p-4 m-2" } }) + ); + writeFile(dir, "tailclass.config.json", JSON.stringify({ outputCss: "important.css" })); + writeFile(dir, "important.css", "/* my own stylesheet */\nbody { color: red; }\n"); + + const rev = revertProject(dir, { clean: true, force: true }); + assert.equal(rev.totalReverted, 1); + assert.equal(read(path.join(dir, "important.css")), "/* my own stylesheet */\nbody { color: red; }\n"); + assert.ok(rev.cleanupSkipped.some((note) => note.includes("does not look like TailClass output"))); + assert.equal(rev.cleanedFiles.length, 1, "the owned manifest is still removed"); + assert.equal(fs.existsSync(path.join(dir, ".tailclass-manifest.json")), false); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("revert --clean leaves a foreign manifest untouched", () => { + const dir = tempDir("clean-foreign-manifest"); + try { + writeFile(dir, "index.html", NAV_HTML); + applyAutoClasses(dir); + // A JSON file from another tool that happens to have a `mappings` key. + const foreign = writeFile( + dir, + ".tailclass-manifest.json", + JSON.stringify({ name: "my-app", version: "1.0.0", mappings: { a: "b" } }) + ); + + const rev = revertProject(dir, { clean: true }); + assert.ok(rev.cleanupSkipped.some((note) => note.includes("does not look like TailClass output"))); + assert.equal(read(foreign), JSON.stringify({ name: "my-app", version: "1.0.0", mappings: { a: "b" } })); + assert.equal(fs.existsSync(path.join(dir, "tailclass.css")), false, "owned CSS is removed"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("revert --clean removes a markerless (--no-comments) stylesheet it can match to its manifest", () => { + const dir = tempDir("clean-no-comments"); + try { + writeFile(dir, "index.html", NAV_HTML); + writeFile(dir, "tailclass.config.json", JSON.stringify({ comments: false })); + applyAutoClasses(dir); + assert.equal(read(path.join(dir, "tailclass.css")).includes("Generated by TailClass"), false); + + const rev = revertProject(dir, { clean: true }); + assert.deepEqual(rev.cleanupSkipped, []); + assert.equal(rev.cleanedFiles.length, 2); + assert.equal(fs.existsSync(path.join(dir, "tailclass.css")), false); + assert.equal(fs.existsSync(path.join(dir, ".tailclass-manifest.json")), false); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("CSS that is not TailClass output is never deleted by --clean", () => { + const dir = tempDir("clean-apply-css"); + try { + writeFile(dir, "index.html", NAV_HTML); + applyAutoClasses(dir); + // Point the config at a hand-written @apply stylesheet from another tool. + writeFile(dir, "own.css", ".my-card {\n @apply p-4 rounded;\n}\n"); + writeFile(dir, "tailclass.config.json", JSON.stringify({ outputCss: "own.css" })); + + const rev = revertProject(dir, { clean: true }); + assert.equal(read(path.join(dir, "own.css")), ".my-card {\n @apply p-4 rounded;\n}\n"); + assert.ok(rev.cleanupSkipped.length > 0); + // The stylesheet recorded in the manifest is still cleaned up. + assert.equal(fs.existsSync(path.join(dir, "tailclass.css")), false); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("revert --clean never deletes a scanned source file", () => { + const dir = tempDir("clean-source"); + try { + writeFile(dir, "index.html", NAV_HTML); + applyAutoClasses(dir); + const sourceBefore = read(path.join(dir, "index.html")); + // A hostile config redirects the stylesheet path at a source file. + writeFile(dir, "tailclass.config.json", JSON.stringify({ outputCss: "index.html" })); + + const rev = revertProject(dir, { clean: true }); + assert.equal(read(path.join(dir, "index.html")), sourceBefore, "source file survives"); + assert.ok( + rev.cleanupSkipped.some((note) => note.includes("does not look like TailClass output")), + "the redirected stylesheet path is reported as skipped" + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("CLI revert --clean reports skipped files instead of deleting them", () => { + const dir = tempDir("clean-cli"); + try { + writeFile(dir, "index.html", NAV_HTML); + assert.equal(execCli(["apply", dir]).code, 0); + + writeFile(dir, "important.css", "body { color: red; }\n"); + writeFile(dir, "tailclass.config.json", JSON.stringify({ outputCss: "important.css" })); + + const res = execCli(["revert", dir, "--clean", "--json"]); + assert.equal(res.code, 0); + assert.equal(read(path.join(dir, "important.css")), "body { color: red; }\n"); + const json = JSON.parse(res.out); + assert.ok(json.cleanupSkipped.length > 0); + assert.match(res.err, /does not look like TailClass output/); + assert.equal(fs.existsSync(path.join(dir, ".tailclass-manifest.json")), false); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("explicit CLI output paths outside the root are still honoured", () => { + const dir = tempDir("cli-outside"); + try { + const site = path.join(dir, "site"); + fs.mkdirSync(site); + writeFile(site, "index.html", NAV_HTML); + const explicit = path.join(dir, "explicit.css"); + + const applied = applyAutoClasses(site, { outputCss: explicit }); + assert.equal(applied.outputCssPath, explicit); + assert.match(read(explicit), /Generated by TailClass/); + assert.match(read(path.join(site, "index.html")), /class="navbar/); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/test/security.test.js b/test/security.test.js index 1093d30..b3dfa68 100644 --- a/test/security.test.js +++ b/test/security.test.js @@ -241,7 +241,7 @@ test("revert ignores manifest entries whose expansion could corrupt markup", () dir, ".tailclass-manifest.json", JSON.stringify({ - version: "1.0.1", + version: "1.0.2", mappings: { "tc-good": "flex p-4 m-2", "tc-evil": 'p-4" onmouseover="alert(1)', diff --git a/types/index.d.ts b/types/index.d.ts index 3d92b71..f3d462f 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -22,8 +22,11 @@ export interface TailClassConfig { include?: string[]; exclude?: string[]; replaceDefaultExcludes?: boolean; + /** Output paths must be regular files inside the project root when config-supplied; symlinked output files are rejected even if the link points inside the root (since 1.0.2). Symlinked directories that resolve inside the root are fine. */ outputCss?: string; + /** @see outputCss */ dictionaryFile?: string; + /** @see outputCss */ manifestFile?: string; cssFormat?: CssFormat; minOccurrences?: number; @@ -121,7 +124,9 @@ export interface ClassListOptions extends TailClassConfig { export interface RevertOptions extends TailClassConfig { dryRun?: boolean; + /** Only remove files TailClass can verify it generated (unowned files are reported in `cleanupSkipped`). */ clean?: boolean; + /** Applies to `apply` overwrites only; never allows `--clean` to delete foreign files. */ force?: boolean; } @@ -169,6 +174,10 @@ export function revertProject(rootDir?: string, options?: RevertOptions): { totalFilesReverted: number; totalReverted: number; classesExpanded: string[]; + /** Absolute paths removed by `--clean`. */ + cleanedFiles: string[]; + /** Reasons why `--clean` deliberately left a file untouched. */ + cleanupSkipped: string[]; }; export function initConfig(rootDir?: string, options?: { force?: boolean; fileName?: string }): {