Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 77 additions & 1 deletion .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -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 '
Expand All @@ -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
Expand All @@ -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"
68 changes: 68 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
- `<style>` / `<textarea>` skipping uses an anchored case-insensitive scan, so offsets
stay correct on files containing Unicode case-folding characters.
- Analyzer subset matching memoises occurrence token sets and uses `Set` membership
instead of `Array#includes`.

## [1.0.0] — 2026-11-08

Initial open-source release of **TailClass**.
Expand Down
27 changes: 24 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.0 — https://github.com/Infinitode/TailClass */
/* Generated by TailClass v1.0.1 — https://github.com/Infinitode/TailClass */
/* Centralized Tailwind component classes. Edit rules here to update styles site-wide. */

@layer components {
Expand Down Expand Up @@ -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.0",
"version": "1.0.1",
"summary": {
"filesScanned": 12,
"filesWithClasses": 11,
Expand Down Expand Up @@ -305,6 +305,24 @@ npx tailclass init
}
```

### Configuration Safety

`tailclass.config.json` travels with the repository, so TailClass treats it as
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.
- 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
`@apply` — they simply stay inline on the element.
- `.git/`, `node_modules/` and `.tailclass-backup/` are always excluded, even with
`replaceDefaultExcludes`.

See [SECURITY.md](SECURITY.md) for the hardening guarantees and disclosure process.

### Opting Out Individual Elements Inline

Add `tc-ignore` (or any token listed in `excludePatterns`) to keep an element untouched:
Expand Down Expand Up @@ -342,6 +360,7 @@ tailclass <command> [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. |
| `-a, --all` | Include non-repeated / 1-off patterns in `list` mode. |
| `--report <file>` | Export Markdown (`.md`) or CSV (`.csv`) audit report in `list` mode. |
| `--format <mode>` | CSS format: `tailwind-v3` (default), `tailwind-v4`, or `plain`. |
Expand Down Expand Up @@ -443,7 +462,9 @@ Contributions, bug reports, and new UI naming heuristics are very welcome! Pleas

## Security

Please review [SECURITY.md](SECURITY.md) for responsible disclosure instructions. Never report security vulnerabilities in public issues.
Please review [SECURITY.md](SECURITY.md) for responsible disclosure instructions and the
hardening guarantees TailClass upholds. Never report security vulnerabilities in public
issues.

## License

Expand Down
23 changes: 22 additions & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,32 @@ TailClass scans and rewrites source code files on disk when `tailclass apply` or
`tailclass revert` is invoked. Correctness, path confinement, and deterministic
rewriting are treated seriously.

## Hardening guarantees

TailClass treats the scanned project, including `tailclass.config.json` and
`tailclass.map.json`, as **untrusted input**, because those files arrive with the
repository you clone.

- **Path confinement.** `outputCss`, `dictionaryFile` and `manifestFile` taken from a
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.
- **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.
- **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.
- **Bounded matching.** Globs are matched with a backtracking-free algorithm, so
repository-supplied patterns cannot hang the process. Symlinks are never followed out
of the project.

## Supported versions

| Version | Supported |
|---------|-----------|
| 1.0.x | ✅ |
| 1.0.1+ | ✅ |
| 1.0.0 | ❌ superseded — upgrade for the v1.0.1 security fixes |
| < 1.0 | ❌ |

## Reporting a vulnerability
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "tailclass",
"version": "1.0.0",
"version": "1.0.1",
"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",
Expand Down Expand Up @@ -53,7 +53,8 @@
"schema/",
"LICENSE",
"README.md",
"CHANGELOG.md"
"CHANGELOG.md",
"SECURITY.md"
],
"engines": {
"node": ">=18.0.0"
Expand Down
10 changes: 5 additions & 5 deletions schema/tailclass.config.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,22 @@
"replaceDefaultExcludes": {
"type": "boolean",
"default": false,
"description": "When true, replaces built-in excludes (node_modules, dist, .git) instead of appending."
"description": "When true, replaces built-in excludes (dist, build, vendor, ...) instead of appending. `.git/`, `node_modules/` and `.tailclass-backup/` are always excluded."
},
"outputCss": {
"type": "string",
"default": "tailclass.css",
"description": "Output path for the generated centralized Tailwind CSS file."
"description": "Output path for the generated centralized Tailwind CSS file. Must stay inside the scanned project root when set from a configuration file."
},
"dictionaryFile": {
"type": "string",
"default": "tailclass.map.json",
"description": "Path for Class List Mode dictionary output and lookup."
"description": "Path for Class List Mode dictionary output and lookup. Must stay inside the scanned project root when set from a configuration file."
},
"manifestFile": {
"type": "string",
"default": ".tailclass-manifest.json",
"description": "Path for the revert manifest generated during apply."
"description": "Path for the revert manifest generated during apply. Must stay inside the scanned project root when set from a configuration file."
},
"cssFormat": {
"type": "string",
Expand Down Expand Up @@ -81,7 +81,7 @@
"classPrefix": {
"type": "string",
"default": "",
"description": "Prefix prepended to every generated semantic class name (e.g. 'tc-')."
"description": "Prefix prepended to every generated semantic class name (e.g. 'tc-'). Only letters, digits, '-' and '_' are allowed; the resulting class name may not start with a digit."
},
"namingStyle": {
"type": "string",
Expand Down
25 changes: 23 additions & 2 deletions src/analyzer.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,26 @@ function computePatternId(canonicalKey) {
return `tc_${digest.slice(0, 8)}`;
}

/**
* Memoised token sets for occurrences. Subset checks run in nested loops, so
* rebuilding a Set per comparison turns large sites quadratic for no reason.
* @type {WeakMap<object, Set<string>>}
*/
const occurrenceTokenSets = new WeakMap();

/**
* @param {object} occurrence
* @returns {Set<string>}
*/
function getOccurrenceTokenSet(occurrence) {
let set = occurrenceTokenSets.get(occurrence);
if (!set) {
set = new Set(occurrence.canonicalTokens);
occurrenceTokenSets.set(occurrence, set);
}
return set;
}

/**
* Build expanded atomic CSS property axes set from a set of propertyGroups.
* @param {Set<string> | Iterable<string>} patternPropGroups
Expand Down Expand Up @@ -47,7 +67,7 @@ function checkSubsetCompatibility(patternTokens, patternPropGroups, occurrence)
return { matches: false, isExact: false, residualTokens: [] };
}

const occSet = new Set(occTokens);
const occSet = getOccurrenceTokenSet(occurrence);
for (const t of patternTokens) {
if (!occSet.has(t)) {
return { matches: false, isExact: false, residualTokens: [] };
Expand Down Expand Up @@ -210,8 +230,9 @@ function analyzeScanResult(scanResult, config = {}) {
if (maxClasses > 0 && pat.classCount > maxClasses) continue;

const matchedOccs = [...pat.occurrences];
const alreadyMatched = new Set(pat.occurrences);
for (const occ of unclaimed) {
if (pat.occurrences.includes(occ)) continue;
if (alreadyMatched.has(occ)) continue;
const compat = checkSubsetCompatibility(pat.canonicalTokens, pat.propGroups, occ);
if (compat.matches) {
matchedOccs.push(occ);
Expand Down
Loading
Loading