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

Technical Evaluation

Architecture Fit

  • Laravel/PHP 7.3+ Compatibility: Seamlessly integrates with Laravel’s dependency injection and service container. The package’s DOM-based approach aligns with Laravel’s native DOMDocument usage (e.g., in Blade templates or API responses).
  • Security-Critical Layer: Designed as a dedicated sanitization layer, not a monolithic framework. Ideal for:
    • Input validation middleware (e.g., app/Http/Middleware/SanitizeSVG).
    • Service classes handling user uploads (e.g., UploadService::sanitizeSVG()).
    • API request/response sanitization (e.g., app/Concerns/SanitizesXML).
  • Extensibility: Customizable allow/deny lists enable fine-grained control over SVG/HTML/MathML features, critical for niche use cases (e.g., scientific diagrams with specific entities).

Integration Feasibility

  • Low Friction: Single Composer dependency with zero Laravel-specific hooks required. Works alongside existing sanitizers (e.g., Laravel’s Str::of() or htmlspecialchars).
  • DOM Integration: Leverages PHP’s built-in DOMDocument, reducing abstraction overhead. Example:
    use Rhukster\DomSanitizer\DOMSanitizer;
    
    class SVGUploader {
        public function sanitize(string $svgContent): string {
            $sanitizer = new DOMSanitizer(DOMSanitizer::SVG);
            return $sanitizer->sanitize($svgContent, [
                'remove-namespaces' => true, // Laravel-specific tweak
            ]);
        }
    }
    
  • Middleware Support: Can be wrapped in Laravel middleware for automatic sanitization of incoming/outgoing XML:
    namespace App\Http\Middleware;
    
    use Rhukster\DomSanitizer\DOMSanitizer;
    
    class SanitizeXML {
        public function handle($request, Closure $next) {
            if ($request->isXml()) {
                $sanitizer = new DOMSanitizer(DOMSanitizer::HTML);
                $request->merge(['content' => $sanitizer->sanitize($request->content)]);
            }
            return $next($request);
        }
    }
    

Technical Risk

  • XXE/DoS Hardening: Mitigated by the package’s 1.0.11 fixes (e.g., LIBXML_NONET, libxml_disable_entity_loader), but custom XML schemas/DTDs may still pose risks if not pre-processed.
  • Performance: DOM parsing adds ~5–10ms overhead per request. Benchmark for high-volume XML (e.g., CMS content). Laravel’s queue workers can offload heavy sanitization.
  • False Positives/Negatives:
    • Risk: Custom allowlists may inadvertently block valid SVG features (e.g., feGaussianBlur in 1.0.9).
    • Mitigation: Test with real-world SVGs (e.g., from Figma/Illustrator) and audit allowlists.
  • PHP Version: Requires PHP 7.3+. Laravel 8+ (PHP 7.4+) is fully compatible; older Laravel versions may need runtime checks.

Key Questions

  1. Use Case Specificity:
    • Are you sanitizing user-uploaded SVGs, third-party XML feeds, or dynamic templates? This dictates allowlist customization.
    • Example: For GeoJSON, whitelist path, polygon, and marker tags.
  2. Integration Points:
    • Where in the stack will sanitization occur? (e.g., controller, service layer, API gateway).
    • Example: Laravel’s app/Providers/AppServiceProvider for global sanitization.
  3. Custom Rules:
    • Do you need to override default allowlists (e.g., for internal SVG entities)?
    • Example: Add addAllowedAttributes(['xlink:href' => ['href']]) for SVG links.
  4. Fallbacks:
    • What’s the rejection strategy for unsanitizable content? (e.g., return null, log, or reject with HTTP 400).
  5. Testing:
    • Have you audited existing XML/SVG inputs for edge cases (e.g., malformed DOCTYPEs, nested entities)?
    • Recommend: Use the package’s test suite as a baseline.

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Service Container: Register the sanitizer as a bound service for dependency injection:
      $this->app->bind(DOMSanitizer::class, function ($app) {
          return new DOMSanitizer(DOMSanitizer::SVG);
      });
      
    • Facades: Create a Sanitizer facade for concise usage:
      use Facades\App\Sanitizer;
      
      $cleanSVG = Sanitizer::sanitize($userUpload);
      
    • Blade Directives: Extend Blade with @sanitize directives for templates:
      Blade::directive('sanitize', function ($expression) {
          return "<?php echo app(Rhukster\DomSanitizer\DOMSanitizer::class)->sanitize({$expression}); ?>";
      });
      
  • PHP Extensions:
    • libxml: Required for DOM parsing. Ensure extension=php_libxml is enabled in php.ini.
    • dom: Also required. Verify with php -m | grep dom.

Migration Path

  1. Assessment Phase:
    • Audit all XML/HTML/SVG inputs (e.g., user uploads, API payloads, templates).
    • Identify custom sanitization logic (e.g., regex, strip_tags) to replace.
  2. Pilot Phase:
    • Replace one high-risk component (e.g., SVG uploader) with the package.
    • Example: Update app/Services/SVGService.php to use DOMSanitizer.
  3. Gradual Rollout:
    • Phase 1: Sanitize user uploads (highest risk).
    • Phase 2: Sanitize API responses (e.g., XML feeds).
    • Phase 3: Sanitize dynamic templates (e.g., Blade with @sanitize).
  4. Fallback Testing:
    • Verify edge cases (e.g., malformed XML, empty inputs) don’t break workflows.

Compatibility

  • Laravel Versions:
    • Fully compatible: Laravel 8+ (PHP 7.4+).
    • Partial compatibility: Laravel 7 (PHP 7.3) may need runtime checks for PHP 8+ features (e.g., libxml_disable_entity_loader).
  • Existing Sanitizers:
    • Replace: Custom strip_tags/preg_replace for XML/HTML/SVG.
    • Complement: Use alongside Laravel’s htmlspecialchars for non-DOM content.
  • Third-Party Packages:
    • Conflict Risk: Low. The package has zero dependents, reducing version clashes.
    • Example: Safe to use with spatie/laravel-medialibrary for SVG uploads.

Sequencing

  1. Dependency Installation:
    composer require rhukster/dom-sanitizer:^1.0.11
    
  2. Configuration:
    • Set default options in config/sanitizer.php:
      return [
          'default_mode' => DOMSanitizer::SVG,
          'options' => [
              'remove-namespaces' => env('SANITIZER_REMOVE_NAMESPACES', true),
          ],
      ];
      
  3. Service Binding:
    • Bind the sanitizer in AppServiceProvider:
      public function register() {
          $this->app->singleton(DOMSanitizer::class, function ($app) {
              return new DOMSanitizer(config('sanitizer.default_mode'), config('sanitizer.options'));
          });
      }
      
  4. Middleware (Optional):
    • Add to app/Http/Kernel.php:
      protected $middleware = [
          \App\Http\Middleware\SanitizeXML::class,
      ];
      
  5. Testing:
    • Write unit tests for sanitization logic (e.g., using PHPUnit).
    • Example test case:
      public function testSVGSanitization() {
          $sanitizer = $this->app->make(DOMSanitizer::class);
          $maliciousSVG = '<svg><script>alert(1)</script></svg>';
          $cleanSVG = $sanitizer->sanitize($maliciousSVG);
          $this->assertNotContains('script', $cleanSVG);
      }
      

Operational

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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony