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

Purify Laravel Package

stevebauman/purify

Laravel wrapper for HTMLPurifier to sanitize user-submitted HTML and prevent XSS. Clean strings or arrays via the Purify facade, with support for per-call (dynamic) configuration and published config for app-wide rules.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Leverages Laravel’s Service Provider Pattern: The package integrates seamlessly with Laravel’s dependency injection and service container, making it a natural fit for Laravel-based applications. The facade (Purify) and service provider (PurifyServiceProvider) align with Laravel’s architectural patterns.
  • Modular Configuration: Supports multiple configuration sets (e.g., default, comments), enabling granular control over HTML sanitization rules across different parts of the application (e.g., user-generated content vs. admin panels).
  • Extensibility: Allows custom Definition and CssDefinition classes, enabling teams to tailor HTML/CSS rules to domain-specific needs (e.g., Trix editor support, custom elements/attributes).
  • Cache Integration: Leverages Laravel’s cache system (CacheDefinitionCache) or filesystem caching, reducing performance overhead in production by avoiding repeated serialization of HTMLPurifier definitions.

Integration Feasibility

  • Low Friction: Installation is straightforward (composer require, vendor:publish), and the package requires minimal setup (PHP 7.4+, Laravel 7.0+).
  • Backward Compatibility: Supports Laravel 7–11, with clear upgrade paths (e.g., v4→v5 migration guide). The PurifyHtmlOnGet cast integrates natively with Eloquent models, reducing boilerplate.
  • Dependency Alignment: Relies on ezyang/htmlpurifier (a battle-tested library), ensuring reliability. No conflicting dependencies with Laravel’s core or popular packages (e.g., Blade, Livewire).
  • Testing Support: Includes GitHub Actions for CI/CD, and the package’s design encourages unit testing (e.g., mocking Purify facade for isolated tests).

Technical Risk

  • Performance Overhead:
    • Cache Dependency: If caching is misconfigured (e.g., shared cache driver with other critical data), clearing definitions (purify:clear) could disrupt unrelated cached data. Mitigation: Use a dedicated cache store/disk for Purify.
    • Serialization: Disabling caching (serializer: null) in production could degrade performance due to repeated definition serialization. Monitor CPU/memory usage post-deployment.
  • Complexity of Custom Definitions:
    • Custom Definition/CssDefinition classes require familiarity with HTMLPurifier’s API. Risk of misconfiguration (e.g., allowing unsafe elements) if not validated thoroughly.
    • Mitigation: Start with pre-defined configs (default, comments) and gradually extend. Use the HTMLPurifier ConfigDoc as a reference.
  • Upgrade Risks:
    • Breaking changes between major versions (e.g., v4→v5). The migration guide is detailed but requires manual intervention (e.g., copying settings to configs.default).
    • Mitigation: Test upgrades in a staging environment with a subset of configurations first.
  • Security Risks:
    • Incorrect configurations (e.g., allowing <script> tags) could expose XSS vulnerabilities. Validate all custom definitions against OWASP guidelines.
    • Mitigation: Use the HTML.ForbiddenElements and CSS.AllowedProperties arrays to restrict allowed content strictly.

Key Questions

  1. Configuration Strategy:

    • How many distinct sanitization profiles (e.g., comments, rich_text_editor) will the application need? Will dynamic configurations (e.g., Purify::config($name)) be used frequently?
    • Impact: Overly granular configs increase maintenance complexity; too few may limit flexibility.
  2. Caching Strategy:

    • Will Purify share a cache driver/disk with other critical systems? If so, how will cache invalidation be managed during deployments?
    • Impact: Shared caches risk unintended data loss during purify:clear.
  3. Custom Definitions:

    • Are there domain-specific HTML/CSS requirements (e.g., custom elements, Trix editor attributes)? If so, how will these be tested for security?
    • Impact: Custom definitions add attack surface; require rigorous validation.
  4. Performance Baseline:

    • What is the expected volume of HTML sanitization (e.g., per request, per batch)? Will caching be enabled in production?
    • Impact: High-volume applications may need to benchmark serialization vs. caching tradeoffs.
  5. Integration with Frontend:

    • How will sanitized HTML interact with frontend frameworks (e.g., React, Vue, Alpine.js)? Will the package be used for both server-side sanitization and client-side validation?
    • Impact: Mismatched rules between server/client could lead to inconsistent rendering.
  6. Upgrade Cadence:

    • What is the team’s policy for dependency updates? Will Purify be pinned to a specific version or allowed to auto-update?
    • Impact: Auto-updates risk introducing breaking changes; pinned versions require manual upgrades.

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Facade Integration: The Purify facade aligns with Laravel’s Hash, Cache, and Str facades, reducing learning curves for developers.
    • Eloquent Casts: PurifyHtmlOnGet/PurifyHtmlOnSet casts integrate natively with Eloquent, enabling seamless sanitization for model attributes (e.g., content, description).
    • Service Provider: The package registers as a Laravel service provider, enabling configuration via config/purify.php and dependency injection.
  • PHP Extensions:
    • Requires no additional PHP extensions beyond Laravel’s defaults (e.g., dom, mbstring are typically enabled for HTML processing).
  • Frontend Compatibility:
    • Works agnostically with frontend frameworks (e.g., Livewire, Inertia.js, vanilla Blade). Sanitized HTML can be rendered directly in Blade templates or passed to JavaScript.

Migration Path

  1. Assessment Phase:

    • Audit existing HTML storage/rendering logic to identify:
      • Where user-generated HTML is stored (e.g., database fields, cache).
      • Where HTML is rendered (e.g., Blade templates, API responses).
    • Document current sanitization rules (if any) to compare against Purify’s defaults.
  2. Pilot Integration:

    • Step 1: Install and publish the package:
      composer require stevebauman/purify
      php artisan vendor:publish --provider="Stevebauman\Purify\PurifyServiceProvider"
      
    • Step 2: Start with the default config and test sanitization on a non-critical endpoint (e.g., a blog comment system).
    • Step 3: Gradually replace ad-hoc sanitization (e.g., strip_tags, regex) with Purify::clean().
  3. Configuration Rollout:

    • Define additional configs (e.g., comments, rich_text) in config/purify.php based on use cases.
    • Example:
      'configs' => [
          'comments' => [
              'HTML.Allowed' => 'p,b,i,a[href],ul,ol,li,br',
              'AutoFormat.RemoveEmpty' => true,
          ],
          'rich_text' => [
              'HTML.Allowed' => 'div,p,h1,h2,h3,b,i,u,a[href|target],img[src|alt],table,tr,td',
              'CSS.AllowedProperties' => 'font-size,color,text-align',
          ],
      ],
      
    • Use Purify::config('comments')->clean($input) for context-specific sanitization.
  4. Eloquent Integration:

    • Apply PurifyHtmlOnGet casts to models where HTML is rendered:
      class Post extends Model {
          protected $casts = [
              'body' => PurifyHtmlOnGet::class, // Uses 'default' config
              'description' => PurifyHtmlOnGet::class.':rich_text', // Uses 'rich_text' config
          ];
      }
      
    • For Laravel 11+, use the casts() method.
  5. Custom Definitions (Optional):

    • If supporting custom elements (e.g., Trix editor), create a Definition class:
      namespace App\Purify;
      
      use Stevebauman\Purify\Definitions\Definition;
      use HTMLPurifier_HTMLDefinition;
      
      class TrixDefinition implements Definition {
          public static function apply(HTMLPurifier_HTMLDefinition $definition) {
              // Add Trix-specific elements/attributes
          }
      }
      
    • Reference it in config/purify.php:
      'definitions' => \App\Purify\TrixDefinition::class,
      
  6. Caching Setup:

    • Configure caching in config/purify.php:
      'serializer' => storage_path('app/purify-cache'),
      
    • Clear cache after definition changes:
      php artisan purify:clear
      
    • For shared environments, use a dedicated cache driver/disk.
  7. Testing:

    • Write unit tests for sanitization logic using the facade:
      use Stevebauman\Purify\Facades\Purify;
      use Tests\TestCase;
      
      class PurifyTest extends TestCase {
          public
      
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