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

Html Sanitizer Laravel Package

symfony/html-sanitizer

Symfony HtmlSanitizer provides an OO API to clean untrusted HTML for safe DOM insertion. Configure allowed/blocked elements and attributes, drop or keep children, force attributes, enforce HTTPS, and restrict link schemes/hosts to prevent XSS and unsafe behavior.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Highly Complementary to Laravel’s Security Needs: Laravel applications frequently handle user-generated HTML input (e.g., rich-text editors, comments, CMS content) where XSS (Cross-Site Scripting) is a critical risk. This package aligns perfectly with Laravel’s security-first philosophy by providing a granular, configurable sanitizer that replaces ad-hoc solutions (e.g., strip_tags, regex-based filters).
  • Context-Aware Sanitization: Supports context-specific rules (e.g., sanitizeFor('head'), sanitizeFor('textarea')), which is essential for Laravel’s dynamic rendering (e.g., Blade templates, API responses).
  • Modern PHP Integration: Leverages PHP 8.4+’s native HTML5 parser for performance, reducing dependency bloat compared to legacy libraries like HTMLPurifier.

Integration Feasibility

  • Laravel Service Provider Pattern: Can be seamlessly integrated via a Service Provider or Package (e.g., HtmlSanitizerServiceProvider), exposing a facade (HtmlSanitizer::sanitize()) for consistency with Laravel’s ecosystem.
  • Middleware Integration: Ideal for global sanitization via middleware (e.g., SanitizeInputMiddleware) to protect against XSS in API payloads or form submissions.
  • Blade Directives: Custom Blade directives (e.g., @sanitize) could simplify usage in templates:
    Blade::directive('sanitize', fn($expr) => "<?php echo app('sanitizer')->sanitize($expr); ?>");
    
    Usage: @sanitize($userInput).

Technical Risk

  • Performance Overhead: The native HTML5 parser (PHP 8.4+) is optimized, but large inputs (e.g., multi-MB HTML) may introduce latency. Benchmark against HTMLPurifier or DOMDocument for critical paths.
  • Configuration Complexity: Overly restrictive/permissive rules could break expected output. Requires thorough testing with edge cases (e.g., nested tags, malformed HTML).
  • PHP Version Dependency: PHP 8.4+ for native parser benefits; backward compatibility with older PHP versions may require MastermindsParser (deprecated in Symfony 8.0+).
  • False Positives/Negatives: Misconfigured rules (e.g., allowing javascript: in URLs) could introduce vulnerabilities. Automated testing (e.g., OWASP ZAP) is critical.

Key Questions

  1. Use Case Scope:
    • Will this replace all sanitization logic (e.g., form requests, API inputs, CMS content) or supplement existing solutions?
    • Are there legacy systems using custom sanitizers that would conflict?
  2. Performance Requirements:
    • What is the expected input size (e.g., comments vs. full HTML emails)?
    • Will caching (e.g., memoizing sanitized outputs) be needed for repeated inputs?
  3. Configuration Management:
    • Should configurations be hardcoded, database-driven, or environment-specific (e.g., dev vs. prod)?
    • How will context-specific rules (e.g., head, textarea) be managed across the app?
  4. Testing Strategy:
    • How will sanitization correctness be verified (e.g., unit tests, fuzz testing)?
    • Are there third-party libraries (e.g., laravel-html) that could interfere?
  5. Deprecation Risk:
    • Symfony’s roadmap may shift focus; is this package actively maintained for Laravel’s long-term needs?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • PHP 8.4+: Full native parser support; PHP 8.1–8.3: Fallback to MastermindsParser (minor performance hit).
    • Composer Dependency: Lightweight (~1MB) with no external binaries.
    • Symfony Integration: Works alongside Laravel’s existing Symfony components (e.g., HttpFoundation for request sanitization).
  • Alternatives Compared:
    Package Pros Cons Fit for Laravel?
    HTMLPurifier Feature-rich, battle-tested Heavy, complex config Medium
    DOMDocument Native PHP, simple Manual parsing, error-prone Low
    symfony/html-sanitizer Lightweight, modern, flexible Newer, fewer docs High

Migration Path

  1. Phase 1: Pilot Integration
    • Start with high-risk areas (e.g., user comments, rich-text inputs).
    • Replace strip_tags or regex-based sanitizers with HtmlSanitizer.
    • Example:
      // Before
      $clean = strip_tags($userInput, '<p><b><i>');
      
      // After
      $config = (new HtmlSanitizerConfig())->allowSafeElements();
      $clean = app(HtmlSanitizer::class)->sanitize($userInput, $config);
      
  2. Phase 2: Middleware Rollout
    • Create a global middleware to sanitize request payloads (e.g., SanitizePayloadMiddleware).
    • Example:
      public function handle(Request $request, Closure $next) {
          $request->merge([
              'sanitized_content' => $this->sanitizer->sanitize($request->input('content'))
          ]);
          return $next($request);
      }
      
  3. Phase 3: Blade/Template Integration
    • Add custom Blade directives or view composers to auto-sanitize dynamic content.
    • Example directive:
      Blade::directive('safeHtml', function ($expr) {
          return "<?php echo e(app('sanitizer')->sanitize({$expr})); ?>";
      });
      
  4. Phase 4: API/Validation Layer
    • Integrate with Laravel’s Form Request validation to sanitize inputs before validation.
    • Example:
      public function rules() {
          return ['content' => 'required|sanitized']; // Custom rule
      }
      
      protected function sanitized($attribute, $value, $fail) {
          $sanitized = app(HtmlSanitizer::class)->sanitize($value);
          $fail($sanitized !== $value ? 'Invalid HTML detected.' : '');
      }
      

Compatibility

  • Laravel Versions: Compatible with Laravel 10+ (PHP 8.1+) and Laravel 11+ (PHP 8.4+ native parser).
  • Existing Libraries:
    • No conflicts with laravel-html, Purifier, or DOMDocument if used selectively.
    • Caching libraries (e.g., symfony/cache) can optimize repeated sanitization.
  • Database/ORM: No direct impact, but ensure sanitized outputs are stored (e.g., in text columns).

Sequencing

  1. Dependency Injection Setup:
    • Register the service in AppServiceProvider:
      public function register() {
          $this->app->singleton(HtmlSanitizer::class, fn() => new HtmlSanitizer(
              (new HtmlSanitizerConfig())->allowSafeElements()
          ));
      }
      
  2. Configuration Centralization:
    • Define app-wide defaults (e.g., config/sanitizer.php) and allow per-context overrides.
  3. Testing Framework:
    • Write feature tests for critical paths (e.g., XSS payloads, malformed HTML).
    • Example test:
      public function test_xss_sanitization() {
          $sanitizer = app(HtmlSanitizer::class);
          $malicious = '<script>alert(1)</script>';
          $clean = $sanitizer->sanitize($malicious);
          $this->assertEmpty(trim($clean));
      }
      
  4. Monitoring:
    • Log sanitization events (e.g., dropped elements, blocked attributes) for debugging.
    • Example:
      $sanitizer->sanitize($input, $config, ['log' => true]);
      

Operational Impact

Maintenance

  • Configuration Drift Risk:
    • Mitigation: Use environment-specific configs (e.g., config/sanitizer.php with env() overrides) and version-controlled defaults.
    • Tooling: Implement a config validator (e.g., PHPStan rules) to catch misconfigurations early.
  • Dependency Updates:
    • Symfony’s LTS cycle (e.g., 6.x, 7.x) aligns with Laravel’s support window. Monitor for breaking changes (e.g., parser shifts in PHP 8.4+).
    • Automated updates: Use symfony/flex or `
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.
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
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata