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

typo3/html-sanitizer

Standalone PHP HTML sanitizer from TYPO3. Define sanitization rules via Behavior, apply with Visitors, and get a ready-to-use Sanitizer via Builders/presets. Control allowed tags, attributes, and values; encode or remove invalid nodes and comments.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strengths:

    • Granular Control: The package provides fine-grained control over allowed HTML tags, attributes, and values via the Behavior class, making it highly customizable for different use cases (e.g., CMS content, user-generated input, or third-party integrations).
    • Visitor Pattern: The use of VisitorInterface enables modular sanitization logic, allowing TPMs to extend or replace sanitization rules without modifying core logic.
    • Security-First Design: Actively maintained with a focus on XSS mitigation (e.g., handling CDATA, processing instructions, and raw text securely). Recent security patches (e.g., ALLOW_INSECURE_RAW_TEXT mitigation) demonstrate proactive risk management.
    • Immutable Configuration: The Behavior class enforces immutability (e.g., withFlags() returns new instances), reducing side-effect risks in shared environments.
    • PHP 8.x Compatibility: Supports modern PHP versions (8.2–8.5), aligning with Laravel’s LTS roadmap.
  • Gaps:

    • Lack of Laravel-Specific Integrations: No built-in Laravel service provider, facade, or caching layer (e.g., for Redis). TPMs must manually integrate with Laravel’s request/response pipeline.
    • No Opinionated Presets: While CommonBuilder exists, it’s not Laravel-optimized (e.g., lacks Blade template compatibility or CSRF token handling).
    • Performance Overhead: DOM manipulation (via DOMNode) may introduce latency for high-throughput APIs. Benchmarking against alternatives like HTMLPurifier or DOMDocument-based solutions is recommended.

Integration Feasibility

  • Laravel Stack Fit:
    • Request Sanitization: Ideal for sanitizing user input (e.g., form submissions, API payloads) before storage/processing. Can integrate with Laravel’s Illuminate\Validation or Illuminate\Http\Request middleware.
    • Response Sanitization: Useful for escaping dynamic content in Blade templates or API responses (e.g., sanitizing user-generated comments in real-time).
    • Caching: Compatible with Laravel’s cache layer (e.g., cache sanitized HTML fragments to reduce reprocessing).
  • Middleware Integration:
    • Can be wrapped in a Laravel middleware to sanitize incoming/outgoing HTML (e.g., SanitizeHtmlMiddleware).
    • Example:
      public function handle(Request $request, Closure $next) {
          $request->merge(['sanitized_body' => $this->sanitizer->sanitize($request->input('body'))]);
          return $next($request);
      }
      
  • Service Container:
    • Bind the Sanitizer to Laravel’s IoC container for dependency injection:
      $this->app->singleton(Sanitizer::class, function ($app) {
          $behavior = (new Behavior())->withTags(...);
          return new Sanitizer($behavior, new CommonVisitor($behavior));
      });
      

Technical Risk

  • Critical Risks:
    • Misconfiguration: Incorrect Behavior settings (e.g., allowing unsafe tags like <script>) could reintroduce XSS vulnerabilities. Requires rigorous testing (e.g., OWASP ZAP scans).
    • Performance: DOM parsing/serialization may bottleneck high-traffic endpoints. Profile with tools like Blackfire or Xdebug.
    • Backward Compatibility: Breaking changes in minor versions (e.g., v2.3.0 deprecated CommonBuilder->srcsetAttr). Monitor Laravel’s PHP version alignment.
  • Mitigation Strategies:
    • Testing: Use the demo project to test edge cases (e.g., malformed HTML, Unicode attacks).
    • Fallbacks: Implement a secondary sanitizer (e.g., htmlspecialchars) for critical paths.
    • Monitoring: Log sanitization failures (e.g., invalid tags) via Laravel’s logging system.

Key Questions for TPM

  1. Use Case Specificity:
    • Will this replace existing sanitization (e.g., htmlspecialchars, DOMDocument) or augment it?
    • Are there Laravel-specific requirements (e.g., Blade directives, API response formatting)?
  2. Performance Requirements:
    • What’s the expected throughput for sanitized content? (e.g., 1000 requests/sec)
    • Can caching (e.g., Redis) be applied to sanitized outputs?
  3. Maintenance:
    • Who will own updates (e.g., security patches)?
    • How will configuration drift (e.g., custom Behavior instances) be managed across environments?
  4. Alternatives:
    • Compare with HTMLPurifier (more features but heavier) or Symfony’s StringUtil (simpler but less flexible).
  5. Compliance:
    • Does this meet regulatory requirements (e.g., GDPR, PCI-DSS) for input sanitization?

Integration Approach

Stack Fit

  • Laravel Ecosystem:

    • Request Pipeline: Integrate with Illuminate\Http\Middleware to sanitize input (e.g., form data, API payloads).
    • Response Pipeline: Use in Illuminate\View\ViewComposer or Illuminate\Routing\Controller to sanitize dynamic content before rendering.
    • Validation: Extend Illuminate\Validation\Rules to include sanitization:
      use TYPO3\HtmlSanitizer\Sanitizer;
      class Sanitize extends Rule {
          public function passes($attribute, $value) {
              return $this->sanitizer->sanitize($value) === $value;
          }
      }
      
    • APIs: Sanitize JSON responses (e.g., user-generated fields) via Illuminate\Http\JsonResponse.
    • Queue Jobs: Sanitize delayed content (e.g., email templates) in Illuminate\Bus\Queueable.
  • Third-Party Integrations:

    • CKEditor/TinyMCE: Sanitize rich-text editor outputs before storage.
    • Markdown Parsers: Sanitize Markdown-to-HTML conversions (e.g., Parsedown).
    • GraphQL: Sanitize dynamic field resolvers (e.g., user-provided GraphQL queries).

Migration Path

  1. Pilot Phase:
    • Start with a single high-risk endpoint (e.g., user comments) to validate performance/security.
    • Use a feature flag (e.g., Laravel’s config('features.html_sanitizer')) to toggle integration.
  2. Incremental Rollout:
    • Phase 1: Sanitize input (e.g., form submissions) via middleware.
    • Phase 2: Sanitize responses (e.g., Blade templates) via view composers.
    • Phase 3: Replace legacy sanitization (e.g., strip_tags) with custom Behavior presets.
  3. Deprecation:
    • Phase out unsafe alternatives (e.g., htmlspecialchars for full HTML) over 2–3 releases.

Compatibility

  • Laravel Versions:
    • Compatible with Laravel 10+ (PHP 8.1+) and 11 (PHP 8.2+). Test with Laravel’s latest LTS.
    • For older versions, use v1.5.x (PHP 7.0+ support).
  • PHP Extensions:
    • Requires dom and libxml extensions (enabled by default in Laravel).
  • Database:
    • No direct DB dependencies, but sanitized content may need schema updates (e.g., increasing text field sizes for escaped HTML).

Sequencing

  1. Setup:
    • Install via Composer: composer require typo3/html-sanitizer.
    • Configure a base Behavior in config/sanitizer.php:
      'default' => [
          'tags' => [
              'a' => ['attrs' => ['href' => ['values' => ['#^https?://#']]]],
              'p' => [],
          ],
          'flags' => Behavior::ENCODE_INVALID_TAG,
      ],
      
  2. Middleware:
    • Register a middleware to sanitize requests:
      // app/Http/Middleware/SanitizeInput.php
      public function handle(Request $request, Closure $next) {
          $request->sanitize = function ($field) use ($request) {
              return app(Sanitizer::class)->sanitize($request->input($field));
          };
          return $next($request);
      }
      
  3. Blade Integration:
    • Create a Blade directive for sanitized output:
      // app/Providers/BladeServiceProvider.php
      Blade::directive('sanitize', function ($expression) {
          return "<?php echo app(\TYPO3\HtmlSanitizer\Sanitizer::class)->sanitize({$expression}); ?>";
      });
      
      Usage: @sanitize($userComment)
  4. Testing:
    • Write PHPUnit tests for custom Behavior rules:
      public function testSanitizerRemovesScriptTags() {
          $sanitizer =
      
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
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi