Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Dom Sanitizer Laravel Package

rhukster/dom-sanitizer

MIT-licensed PHP 7.3+ DOM/SVG/MathML sanitizer using DOMDocument and DOMPurify-based allowlists. Remove dangerous tags/attributes, strip namespaces and PHP/HTML/XML tags, and optionally compress output. Supports HTML, SVG, and MathML modes.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require rhukster/dom-sanitizer
    
  2. Basic Usage (HTML):
    use Rhukster\DomSanitizer\DOMSanitizer;
    
    $sanitizer = new DOMSanitizer(DOMSanitizer::HTML);
    $cleanHtml = $sanitizer->sanitize($userInput);
    
  3. First Use Case: Sanitize user-uploaded HTML (e.g., rich text editor output) or SVG (e.g., diagram uploads) before rendering.

Where to Look First

  • Constructor Modes: DOMSanitizer::HTML, DOMSanitizer::SVG, or DOMSanitizer::MATHML for context-specific sanitization.
  • Default Options: Review $options in the README for remove-namespaces, remove-php-tags, etc.
  • Security Hardening: Check release/1.0.11.md for XXE protections.

Implementation Patterns

Core Workflows

  1. Sanitizing User Input:
    // Laravel Form Request Example
    public function store(Request $request) {
        $sanitizer = new DOMSanitizer(DOMSanitizer::HTML);
        $cleanContent = $sanitizer->sanitize($request->input('content'));
        // Save $cleanContent to DB
    }
    
  2. SVG-Specific Handling:
    // For SVG uploads (e.g., Laravel File Upload)
    $sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
    $cleanSvg = $sanitizer->sanitize($svgFileContent);
    
  3. Dynamic Allowlists:
    $sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
    $sanitizer->addAllowedAttributes(['xlink:href' => ['href']]); // Whitelist SVG-specific attributes
    

Integration Tips

  • Laravel Middleware:
    // app/Http/Middleware/SanitizeInput.php
    public function handle($request, Closure $next) {
        $request->merge([
            'sanitized_content' => (new DOMSanitizer(DOMSanitizer::HTML))
                ->sanitize($request->content)
        ]);
        return $next($request);
    }
    
  • Service Container Binding (Laravel):
    // config/app.php
    'bindings' => [
        Rhukster\DomSanitizer\DOMSanitizer::class => function ($app) {
            return new DOMSanitizer(DOMSanitizer::HTML);
        },
    ];
    
  • Validation Rules (Laravel):
    use Illuminate\Validation\Rule;
    
    $validator = Validator::make($data, [
        'content' => [
            'required',
            function ($attribute, $value, $fail) {
                $sanitizer = new DOMSanitizer(DOMSanitizer::HTML);
                if ($sanitizer->sanitize($value) !== $value) {
                    $fail('Invalid HTML detected.');
                }
            },
        ],
    ]);
    

Advanced Patterns

  1. Custom Sanitizer Class (Extending Functionality):
    class AppSanitizer extends DOMSanitizer {
        public function __construct() {
            parent::__construct(DOMSanitizer::HTML);
            $this->addAllowedTags(['custom-tag']);
            $this->addAllowedAttributes(['custom-tag' => ['data-custom']]);
        }
    }
    
  2. Batch Processing (Laravel Queues):
    // Process multiple user-generated SVGs asynchronously
    SanitizeSvgJob::dispatch($svgContents)->onQueue('sanitize');
    
    // Job class
    public function handle() {
        $sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
        $cleanSvg = $sanitizer->sanitize($this->svgContents);
        // Store or send $cleanSvg
    }
    

Gotchas and Tips

Pitfalls

  1. XXE Risks in Legacy Code:

    • Issue: If your app uses simplexml_load_string or DOMDocument::loadHTML directly, bypassing this sanitizer, XXE attacks may still occur.
    • Fix: Replace all raw XML/HTML parsing with DOMSanitizer::sanitize() before DOM manipulation.
    // ❌ Vulnerable
    $dom = new DOMDocument();
    $dom->loadHTML($userInput);
    
    // ✅ Secure
    $sanitizer = new DOMSanitizer(DOMSanitizer::HTML);
    $dom->loadHTML($sanitizer->sanitize($userInput));
    
  2. False Positives in SVG:

    • Issue: SVG filters (e.g., feGaussianBlur) may be stripped if not properly whitelisted (see release/1.0.9.md).
    • Fix: Explicitly allow SVG-specific tags/attributes:
    $sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
    $sanitizer->addAllowedTags([
        'feGaussianBlur', 'feBlend', 'feColorMatrix',
        // ... other SVG filter tags
    ]);
    
  3. CSS Injection in <style> Tags:

    • Issue: Even with sanitization, <style> tags may contain malicious CSS (e.g., url('javascript:...')).
    • Fix: Disable <style> tags entirely or use the package’s built-in CSS sanitization:
    $sanitizer = new DOMSanitizer(DOMSanitizer::HTML);
    $sanitizer->addDisallowedTags(['style']);
    
  4. Performance with Large XML:

    • Issue: Complex SVGs/XML may cause memory issues during sanitization.
    • Fix: Use compress-output: false to reduce memory usage:
    $sanitizer->sanitize($largeXml, ['compress-output' => false]);
    

Debugging Tips

  1. Inspect Allowed/Disallowed Lists:

    $sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
    dump($sanitizer->getAllowedTags()); // Debug allowed tags
    dump($sanitizer->getDisallowedAttributes()); // Debug blocked attributes
    
  2. Log Sanitization Failures:

    $original = $userInput;
    $clean = $sanitizer->sanitize($original);
    if ($original !== $clean) {
        \Log::warning('Sanitization modified input', [
            'original' => $original,
            'clean' => $clean,
        ]);
    }
    
  3. Test Edge Cases:

    • XXE: Test with <!DOCTYPE ... [ <!ENTITY ...> ]> and <!ENTITY % ...> declarations.
    • CSS Injection: Test with <style>@import 'https://evil.com';</style>.
    • SVG Bypasses: Test with encoded whitespace entities (e.g., &#x09;javascript:alert(1)).

Extension Points

  1. Custom Validation Logic:

    $sanitizer = new DOMSanitizer(DOMSanitizer::HTML);
    $sanitizer->addAllowedAttributes(['custom' => ['data-*']]); // Allow data-* attributes
    
  2. Pre/Post-Processing:

    // Pre-process: Strip known malicious patterns
    $preProcessed = preg_replace('/<script.*?>.*?<\/script>/is', '', $input);
    $clean = $sanitizer->sanitize($preProcessed);
    
    // Post-process: Re-add safe elements
    $final = str_replace('{{placeholder}}', $safeElement, $clean);
    
  3. Laravel Service Provider:

    // app/Providers/AppServiceProvider.php
    public function boot() {
        \Blade::directive('sanitize', function ($expression) {
            return "<?php echo (new \\Rhukster\\DomSanitizer\\DOMSanitizer(\\Rhukster\\DomSanitizer\\DOMSanitizer::HTML))->sanitize($expression); ?>";
        });
    }
    

    Usage in Blade:

    {!! sanitize($userInput) !!}
    

Configuration Quirks

  1. PHP Version Notes:
    • PHP < 8.0: Manually call `libxml
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai