markdown-sanitizers / markdown-to-markdown-sanitizer
CLAUDE.md131 starsChanged 16 months agoMITView on GitHub
This is a robust markdown sanitizer that filters URLs in markdown links and images against prefix allow-lists, with comprehensive HTML sanitization. The sanitizer uses a sophisticated markdown-to-HTML-to-markdown pipeline to ensure security while preserving markdown structure. The sanitizer follows this flow: Always use pnpm, not npm. The codebase includes extensive security testing with 111 bypass attempt files that test various attack vectors: Tests use Vitest and run against multiple markdown parsers (remark, marked, markdown-it, showdown, commonmark) to ensure comprehensive coverage. The…
In this repositoryOne other file it gives its agents.
- CLAUDE.mdCLAUDE.md
The file
We split this CLAUDE.md into the rules it gives an agent
6 rules. About 0 are common, 6 are distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 36
Always use pnpm, not npm.
- Distinctive: line 165
When working with this codebase:
- Distinctive: line 167
Always test security changes against the bypass attempt files
- Distinctive: line 168
Use HTTPS prefixes in allow-lists
- Distinctive: line 170
Test with the comprehensive test suite before making changes
- Distinctive: line 171
Consider the markdown-to-HTML-to-markdown pipeline when making modifications
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project Overview
This is a robust markdown sanitizer that filters URLs in markdown links and images against prefix allow-lists, with comprehensive HTML sanitization. The sanitizer uses a sophisticated markdown-to-HTML-to-markdown pipeline to ensure security while preserving markdown structure.
Core Architecture
Processing Pipeline
The sanitizer follows this flow:
- Autolink Normalization (
normalizeAutolinks): Converts<url>syntax to explicit link format[url](url)and rejects URLs containing HTML entities - Markdown → HTML: Uses unified/remark to parse markdown and convert to HTML
- HTML Sanitization: Uses DOMPurify with GitHub-compatible allow-lists to sanitize HTML
- HTML → Markdown: Uses Turndown with GFM plugin to convert back to markdown
- Aggressive Escaping: Custom escape function converts special characters to HTML entities
Key Components
MarkdownSanitizer(main class insrc/index.ts): Orchestrates the entire pipelineUrlNormalizer(src/url-normalizer.ts): Validates URLs against allow-lists and normalizes themHtmlSanitizer(src/html-sanitizer.ts): DOMPurify wrapper with GitHub-compatible configurationSanitizeOptions(src/types.ts): Configuration interface for URL prefixes and origins
Security Features
- URL Validation: Comprehensive prefix matching with support for protocol-only prefixes
- HTML Entity Escaping: Aggressive character-to-entity conversion for dangerous characters
- Length Limits: Configurable maximum markdown length for DoS protection
Development Commands
Always use pnpm, not npm.
Testing
# Run all tests
pnpm test
# Run specific test file
pnpm test -- tests/basic-sanitization.test.ts
# Run tests matching pattern
pnpm test -- --testNamePattern="should sanitize"Code Quality
# TypeScript compilation
pnpm run build
# Type checking (source)
pnpm run check-types
# Type checking (tests)
pnpm run check-types:tests
# Type checking (all)
pnpm run check-types:all
# Linting (source)
pnpm run lint
# Linting (tests)
pnpm run lint:testsTesting Architecture
Test Structure
tests/bypass-attempts/: 111 adversarial markdown files testing security bypassestests/bypass-attempts.test.ts: Runs all bypass attempts against 5 different markdown parserstests/basic-sanitization.test.ts: Core functionality teststests/html-sanitization.test.ts: HTML sanitization teststests/security-attacks.test.ts: XSS prevention teststests/max-length-config.test.ts: Maximum length configuration tests
Security Testing
The codebase includes extensive security testing with 111 bypass attempt files that test various attack vectors:
- Protocol smuggling and confusion
- Unicode normalization attacks
- Parser state confusion
- Encoding bypass attempts
- URL validation bypasses
- HTML entity attacks
Test Execution
Tests use Vitest and run against multiple markdown parsers (remark, marked, markdown-it, showdown, commonmark) to ensure comprehensive coverage. The bypass tests expect empty arrays (no dangerous content) and flag any successful bypasses.
Key Implementation Details
Autolink Handling
The sanitizer preprocesses autolinks (<url>) by:
- Matching with regex:
/<([a-z][a-z0-9+.-]*:\/\/[^\s<>]+)>/gi - Decoding HTML entities within the URL
- Rejecting the autolink if entities were found (returns empty string)
- Converting to explicit link format:
[sanitizedUrl](sanitizedUrl)
URL Normalization
- Uses browser URL constructor for parsing and normalization
- Supports relative URLs with
defaultOriginconfiguration - Validates against
allowedLinkPrefixesandallowedImagePrefixes - Replaces invalid hrefs with
#and removes invalid src attributes entirely - Encodes markdown-dangerous characters (
!()[]`) as percent-encoded
HTML Sanitization
- Uses DOMPurify with GitHub-compatible tag and attribute allow-lists
- Supports advanced HTML elements like
<details>,<kbd>,<samp>, tables - Prefixes user-generated IDs with
user-content- - Applies URL sanitization to all
hrefandsrcattributes in HTML
Character Escaping
Recent implementation uses aggressive HTML entity encoding for dangerous characters:
function encodeAllCharactersToEntities(str: string): string {
return str.replace(/./g, (char) => `&${char.charCodeAt(0).toString(16)};`);
}This is applied to strings containing: <>&"'[]:()/!()
Configuration
Required Options
defaultOrigin: Required for relative URL handling (e.g., "https://github.com")
URL Prefixes
allowedLinkPrefixes: Array of allowed prefixes for linksallowedImagePrefixes: Array of allowed prefixes for images- Supports protocol-only prefixes like
["https:", "http:"] - Supports domain prefixes like
["https://example.com"] - Supports path prefixes like
["https://example.com/api"]
URL Length Limits
urlMaxLength: Default 200 characters, set to 0 for no limitmaxMarkdownLength: Default 100000 characters, set to 0 for no limit
Performance Considerations
- Configurable length limits prevent memory issues with large documents
- Character-by-character parsing avoids regex catastrophic backtracking
- HTML sanitization only runs when needed
- Efficient markdown-to-HTML-to-markdown pipeline
Security Best Practices
When working with this codebase:
- Always test security changes against the bypass attempt files
- Use HTTPS prefixes in allow-lists
- Be specific with URL prefixes (avoid overly broad matches)
- Test with the comprehensive test suite before making changes
- Consider the markdown-to-HTML-to-markdown pipeline when making modifications
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

