Filter JavaScript from HTML
Overview
This skill provides guidance for tasks that require removing JavaScript and XSS attack vectors from HTML content while preserving the original formatting exactly. The key challenge is balancing comprehensive security filtering with format preservation.
Critical Requirements Analysis
Before implementation, identify and prioritize these requirements:
- Security completeness: All XSS vectors must be removed
- Format preservation: Output must be functionally identical to input except for harmful content removal
- Clean content handling: Files without XSS content should remain completely unchanged
These requirements often conflict - comprehensive parsing may alter formatting, while simple string replacement may miss attack vectors.
Approach Selection
Option 1: Regex-Based Surgical Removal (Recommended for Format Preservation)
When the task explicitly requires preserving original formatting, prefer regex-based approaches that surgically remove only the dangerous content.
Advantages:
- Preserves whitespace, attribute ordering, quote styles exactly
- Does not reconstruct or reformat HTML
- Output matches input character-for-character except for removed content
Considerations:
- Requires careful pattern construction to avoid partial matches
- Must handle various encodings and obfuscation techniques
- Test patterns against comprehensive XSS vector lists
Option 2: HTML Parser-Based Filtering
When format preservation is less critical or when dealing with malformed HTML.
Considerations:
- HTML parsers inherently reconstruct output, changing formatting
- May normalize attribute quotes, whitespace, tag casing
- Better for malformed HTML that regex cannot reliably parse
- If using this approach, verify that clean HTML files remain unchanged
Comprehensive XSS Vector Checklist
Before implementing, research and account for ALL of these attack categories:
1. Script Execution Tags
<script> tags (including variations with attributes)
<noscript> abuse cases
2. Event Handlers (Comprehensive List Required)
Common handlers:
onclick, onload, onerror, onmouseover, onfocus, onblur
Frequently missed handlers:
onlayoutcomplete, ontimeerror, onselectionchange
onrowsinserted, onrowsdelete, onrowexit, onrowenter
oncellchange, ondataavailable, ondatasetchanged, ondatasetcomplete
onbeforeupdate, onafterupdate, onerrorupdate
onfilterchange, onpropertychange, onreadystatechange
onbeforeprint, onafterprint, onbeforeunload
oncontextmenu, ondrag, ondragend, ondragenter, ondragleave
ondragover, ondragstart, ondrop
onhashchange, oninput, oninvalid, onpageshow, onpagehide
onpopstate, onresize, onstorage, onwheel
Action: Search for comprehensive event handler lists (e.g., MDN, OWASP) rather than relying on memory.
3. JavaScript URL Protocol
javascript: in href, src, action, formaction, data, poster attributes
- Case variations:
JavaScript:, JAVASCRIPT:, JaVaScRiPt:
- Encoded variations:
javascript:, javascript:
4. Other Dangerous Protocols
vbscript: (IE legacy)
data: URIs with script content: data:text/html,<script>...</script>
data:text/html;base64,... encoded payloads
5. CSS-Based Attacks
<style> tags with dangerous properties
-moz-binding (Firefox legacy)
expression() (IE legacy)
behavior: property
@import with javascript or data URIs
6. Meta Tag Attacks
<meta http-equiv="refresh" content="0;url=data:text/html,...">
<meta http-equiv="refresh" content="0;url=javascript:...">
7. External Resource Loading
<link> tags with dangerous href values
<object> tags with data attributes
<embed> tags with src attributes
<applet> tags (legacy)
<iframe> with src or srcdoc containing scripts
8. SVG-Based Attacks
<svg> and other SVG event handlers
<svg><script>...</script></svg>
- SVG
<use> with external references
9. Encoding and Obfuscation
- HTML entity encoding:
<script>
- URL encoding:
%3Cscript%3E
- UTF-7 encoding attacks
- Null byte injection:
<scr\0ipt>
- Unicode variations
10. HTML Comment Exploits
- Conditional comments:
<!--[if IE]><script>...<![endif]-->
- Nested comment breaking
Verification Strategy
Test Categories (All Required)
XSS Attack Vectors
- Use established XSS test suites (OWASP XSS Filter Evasion Cheat Sheet)
- Test XSS polyglots that combine multiple techniques
- Include lesser-known event handlers in tests
Format Preservation
- Provide clean HTML files with varied formatting
- Verify byte-for-byte identical output for clean files
- Test various whitespace patterns, quote styles, attribute ordering
Edge Cases
- Malformed HTML
- Mixed case tags and attributes
- Attributes without quotes
- Multiple encodings in same document
Testing Process
Research first: Before writing tests, search for:
- OWASP XSS Prevention Cheat Sheet
- XSS Filter Evasion Cheat Sheet
- Known XSS polyglots
- Browser-specific attack vectors
Create adversarial tests: Do not rely solely on self-created test cases
- Use external comprehensive test suites
- Include vectors that have bypassed filters historically
Test clean content preservation: Equal priority to security testing
- Create diverse clean HTML samples
- Verify no modifications occur
- Check whitespace, comments, attribute order
Common Pitfalls
1. Incomplete Event Handler Lists
Mistake: Hardcoding only common event handlers like onclick, onload, onerror.
Solution: Research and include ALL valid HTML event handlers, including deprecated and browser-specific ones.
2. Ignoring CSS Attack Vectors
Mistake: Focusing only on JavaScript while ignoring CSS-based XSS.
Solution: Filter <style> tags, dangerous CSS properties, and style attributes with expressions.
3. Missing Protocol Handlers
Mistake: Only filtering javascript: protocol.
Solution: Also filter vbscript:, data: URIs with dangerous content, and handle encoded protocol names.
4. Format Alteration with Parsers
Mistake: Using HTML parsers when format preservation is required.
Solution: If format preservation is critical, use regex-based surgical removal or verify parser output matches input formatting.
5. Self-Validating Tests
Mistake: Creating test cases that match implementation capabilities rather than real attack vectors.
Solution: Use external, adversarial test suites created by security researchers.
6. Quote and Encoding Handling
Mistake: Not handling HTML entities in attributes (", ').
Solution: Consider how encoded characters in attributes might bypass filters.
7. Forgetting Meta Refresh
Mistake: Not filtering <meta http-equiv="refresh"> with dangerous URLs.
Solution: Include meta tags in the filtering scope, especially those with data: or javascript: URLs.
8. Ignoring External Resources
Mistake: Not filtering <link>, <object>, <embed> tags.
Solution: Evaluate whether these tags can load or execute dangerous content.
Implementation Checklist
Before considering the implementation complete:
1---2name: filter-js-from-html3description: Guidance for filtering JavaScript and XSS attack vectors from HTML while preserving original formatting. This skill should be used when tasks involve removing script content, sanitizing HTML, filtering XSS payloads, or creating security filters that must preserve the original document structure unchanged.4---56# Filter JavaScript from HTML78## Overview910This skill provides guidance for tasks that require removing JavaScript and XSS attack vectors from HTML content while preserving the original formatting exactly. The key challenge is balancing comprehensive security filtering with format preservation.1112## Critical Requirements Analysis1314Before implementation, identify and prioritize these requirements:15161. **Security completeness**: All XSS vectors must be removed172. **Format preservation**: Output must be functionally identical to input except for harmful content removal183. **Clean content handling**: Files without XSS content should remain completely unchanged1920These requirements often conflict - comprehensive parsing may alter formatting, while simple string replacement may miss attack vectors.2122## Approach Selection2324### Option 1: Regex-Based Surgical Removal (Recommended for Format Preservation)2526When the task explicitly requires preserving original formatting, prefer regex-based approaches that surgically remove only the dangerous content.2728**Advantages:**29- Preserves whitespace, attribute ordering, quote styles exactly30- Does not reconstruct or reformat HTML31- Output matches input character-for-character except for removed content3233**Considerations:**34- Requires careful pattern construction to avoid partial matches35- Must handle various encodings and obfuscation techniques36- Test patterns against comprehensive XSS vector lists3738### Option 2: HTML Parser-Based Filtering3940When format preservation is less critical or when dealing with malformed HTML.4142**Considerations:**43- HTML parsers inherently reconstruct output, changing formatting44- May normalize attribute quotes, whitespace, tag casing45- Better for malformed HTML that regex cannot reliably parse46- If using this approach, verify that clean HTML files remain unchanged4748## Comprehensive XSS Vector Checklist4950Before implementing, research and account for ALL of these attack categories:5152### 1. Script Execution Tags53- `<script>` tags (including variations with attributes)54- `<noscript>` abuse cases5556### 2. Event Handlers (Comprehensive List Required)57Common handlers:58- `onclick`, `onload`, `onerror`, `onmouseover`, `onfocus`, `onblur`5960Frequently missed handlers:61- `onlayoutcomplete`, `ontimeerror`, `onselectionchange`62- `onrowsinserted`, `onrowsdelete`, `onrowexit`, `onrowenter`63- `oncellchange`, `ondataavailable`, `ondatasetchanged`, `ondatasetcomplete`64- `onbeforeupdate`, `onafterupdate`, `onerrorupdate`65- `onfilterchange`, `onpropertychange`, `onreadystatechange`66- `onbeforeprint`, `onafterprint`, `onbeforeunload`67- `oncontextmenu`, `ondrag`, `ondragend`, `ondragenter`, `ondragleave`68- `ondragover`, `ondragstart`, `ondrop`69- `onhashchange`, `oninput`, `oninvalid`, `onpageshow`, `onpagehide`70- `onpopstate`, `onresize`, `onstorage`, `onwheel`7172**Action**: Search for comprehensive event handler lists (e.g., MDN, OWASP) rather than relying on memory.7374### 3. JavaScript URL Protocol75- `javascript:` in href, src, action, formaction, data, poster attributes76- Case variations: `JavaScript:`, `JAVASCRIPT:`, `JaVaScRiPt:`77- Encoded variations: `javascript:`, `javascript:`7879### 4. Other Dangerous Protocols80- `vbscript:` (IE legacy)81- `data:` URIs with script content: `data:text/html,<script>...</script>`82- `data:text/html;base64,...` encoded payloads8384### 5. CSS-Based Attacks85- `<style>` tags with dangerous properties86- `-moz-binding` (Firefox legacy)87- `expression()` (IE legacy)88- `behavior:` property89- `@import` with javascript or data URIs9091### 6. Meta Tag Attacks92- `<meta http-equiv="refresh" content="0;url=data:text/html,...">`93- `<meta http-equiv="refresh" content="0;url=javascript:...">`9495### 7. External Resource Loading96- `<link>` tags with dangerous href values97- `<object>` tags with data attributes98- `<embed>` tags with src attributes99- `<applet>` tags (legacy)100- `<iframe>` with src or srcdoc containing scripts101102### 8. SVG-Based Attacks103- `<svg onload="...">` and other SVG event handlers104- `<svg><script>...</script></svg>`105- SVG `<use>` with external references106107### 9. Encoding and Obfuscation108- HTML entity encoding: `<script>`109- URL encoding: `%3Cscript%3E`110- UTF-7 encoding attacks111- Null byte injection: `<scr\0ipt>`112- Unicode variations113114### 10. HTML Comment Exploits115- Conditional comments: `<!--[if IE]><script>...<![endif]-->`116- Nested comment breaking117118## Verification Strategy119120### Test Categories (All Required)1211221. **XSS Attack Vectors**123 - Use established XSS test suites (OWASP XSS Filter Evasion Cheat Sheet)124 - Test XSS polyglots that combine multiple techniques125 - Include lesser-known event handlers in tests1261272. **Format Preservation**128 - Provide clean HTML files with varied formatting129 - Verify byte-for-byte identical output for clean files130 - Test various whitespace patterns, quote styles, attribute ordering1311323. **Edge Cases**133 - Malformed HTML134 - Mixed case tags and attributes135 - Attributes without quotes136 - Multiple encodings in same document137138### Testing Process1391401. **Research first**: Before writing tests, search for:141 - OWASP XSS Prevention Cheat Sheet142 - XSS Filter Evasion Cheat Sheet143 - Known XSS polyglots144 - Browser-specific attack vectors1451462. **Create adversarial tests**: Do not rely solely on self-created test cases147 - Use external comprehensive test suites148 - Include vectors that have bypassed filters historically1491503. **Test clean content preservation**: Equal priority to security testing151 - Create diverse clean HTML samples152 - Verify no modifications occur153 - Check whitespace, comments, attribute order154155## Common Pitfalls156157### 1. Incomplete Event Handler Lists158**Mistake**: Hardcoding only common event handlers like `onclick`, `onload`, `onerror`.159**Solution**: Research and include ALL valid HTML event handlers, including deprecated and browser-specific ones.160161### 2. Ignoring CSS Attack Vectors162**Mistake**: Focusing only on JavaScript while ignoring CSS-based XSS.163**Solution**: Filter `<style>` tags, dangerous CSS properties, and style attributes with expressions.164165### 3. Missing Protocol Handlers166**Mistake**: Only filtering `javascript:` protocol.167**Solution**: Also filter `vbscript:`, `data:` URIs with dangerous content, and handle encoded protocol names.168169### 4. Format Alteration with Parsers170**Mistake**: Using HTML parsers when format preservation is required.171**Solution**: If format preservation is critical, use regex-based surgical removal or verify parser output matches input formatting.172173### 5. Self-Validating Tests174**Mistake**: Creating test cases that match implementation capabilities rather than real attack vectors.175**Solution**: Use external, adversarial test suites created by security researchers.176177### 6. Quote and Encoding Handling178**Mistake**: Not handling HTML entities in attributes (`"`, `'`).179**Solution**: Consider how encoded characters in attributes might bypass filters.180181### 7. Forgetting Meta Refresh182**Mistake**: Not filtering `<meta http-equiv="refresh">` with dangerous URLs.183**Solution**: Include meta tags in the filtering scope, especially those with data: or javascript: URLs.184185### 8. Ignoring External Resources186**Mistake**: Not filtering `<link>`, `<object>`, `<embed>` tags.187**Solution**: Evaluate whether these tags can load or execute dangerous content.188189## Implementation Checklist190191Before considering the implementation complete:192193- [ ] Researched comprehensive XSS attack vector lists194- [ ] Implemented filtering for ALL event handlers (not just common ones)195- [ ] Handled script tags and noscript abuse196- [ ] Filtered javascript:, vbscript:, and dangerous data: URIs197- [ ] Addressed CSS-based attacks (style tags, expressions, bindings)198- [ ] Handled meta refresh attacks199- [ ] Considered link, object, embed, applet tags200- [ ] Handled SVG-based attacks201- [ ] Accounted for encoding variations202- [ ] Tested with external XSS test suites203- [ ] Verified clean HTML files remain unchanged204- [ ] Tested format preservation (whitespace, quotes, ordering)