css-sanitizer
Policy-driven CSS sanitization on top of lightningcss.
This crate exposes lightningcss directly and lets you sanitize rules, selectors,
properties, and descriptors through a custom policy trait. It is an AST policy engine,
not a built-in preset sanitizer.
Install
[]
= "0.1.4"
Example
Core model
CssSanitizationPolicyis the main extension point.clean_declaration_list_with_policy()andclean_stylesheet_with_policy()parse, sanitize, and serialize strings.sanitize_declaration_block_ast()andsanitize_stylesheet_ast()mutate parsedlightningcssASTs in place.lightningcssis re-exported so callers can work against the same AST types.
Default trait methods are fail-open. If you want a strict sanitizer, your policy must
explicitly return NodeAction::Drop for anything you do not want to keep.
Quick start
use ;
use CssRule;
;
let safe = clean_stylesheet_with_policy;
assert!;
assert!;
assert!;
In-place AST sanitization
use ;
use CssRule;
use ;
;
let mut stylesheet =
parse
.expect;
sanitize_stylesheet_ast;
let output = stylesheet
.to_css
.expect
.code;
assert!;
assert!;
What the sanitizer walks
The built-in walker already handles:
- full stylesheet rule lists
- nested style rules
@media,@supports,@container,@scope,@starting-style@keyframes@font-face@font-palette-values@font-feature-valuesand its sub-rules@pageand page margin rules@counter-style@viewport- selector lists on style-like rules
- normal properties and
!importantdeclarations - descriptor-style nodes exposed by
lightningcss
Empty rules created by filtering are removed during traversal.
API surface
CssSanitizationPolicyNodeActionRuleContextSelectorContextPropertyContextDescriptorContextsanitize_declaration_block_ast()sanitize_stylesheet_ast()clean_declaration_list_with_policy()clean_stylesheet_with_policy()pub use lightningcss
Security notes
- This crate does not ship a safe default policy.
- Selector scoping,
@import, remote URLs,!important,var(), and unknown rules are all policy decisions. var(--x)still cannot be resolved statically across external cascade boundaries unless your own policy or environment model provides that information.
Publishing
Benchmarking
The Criterion benchmark suite measures:
- declaration-list parse + sanitize + serialize
- stylesheet parse + sanitize + serialize
- stylesheet AST API parse + sanitize
lightningcssparse/serialize round-trips as a baseline next to sanitizer runs
The built-in fixtures are synthetic but intentionally stress nested rules, descriptor rules,
URLs, var(), and pruning behavior. If you later want real-world corpora, prefer fetching
official distributed CSS from upstream projects during benchmarking rather than vendoring
large third-party CSS blobs into this repository.
License
Apache-2.0