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

Laravel Security Laravel Package

make-dev/laravel-security

Drop-in security headers for Laravel 11–13: HSTS, CSP with per-request nonces and strict-dynamic, X-Content-Type-Options, Permissions-Policy, and Subresource Integrity. Includes CSP/SRI violation report endpoints, logging/db storage, and Vapor-friendly SRI manifests.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require make-dev/laravel-security
    

    The package auto-discovers the service provider.

  2. Run the interactive setup wizard

    php artisan security:install
    

    Follow prompts to configure CSP, HSTS, Permissions-Policy, and SRI based on your stack (e.g., GTM, Stripe, HubSpot). This generates config/security.php.

  3. Build the SRI manifest (after asset compilation)

    php artisan sri:build-manifest
    
  4. Run migrations (if using DB persistence)

    php artisan migrate
    

First Use Case

Enable strict CSP for a new Laravel 13 app with Vite + Filament:

  • Run php artisan security:install and select:
    • Vite for asset handling
    • Filament for admin panel
    • Google Tag Manager (GTM) for analytics
  • Update AppServiceProvider::boot():
    Vite::useCspNonce(app(\MakeDev\Security\Services\CspNonce::class)->value());
    
  • In Blade templates, mark trusted scripts:
    <script @cspNonce src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXX"></script>
    

Implementation Patterns

Core Workflows

  1. CSP Integration

    • Blade Templates: Use @cspNonce for inline scripts:
      <script @cspNonce>console.log('Safe!');</script>
      
    • Vite/Filament: Inject nonce via AppServiceProvider or Filament’s ->cspNonce().
    • Exclusions: Skip CSP for admin paths:
      'exclude_paths' => ['admin', 'livewire'],
      
  2. SRI for Assets

    • Manifest Build: Run post-asset-build:
      php artisan sri:build-manifest --skip-css  # For Vapor CSS post-processing
      
    • Warm Cache: For dynamic assets (e.g., Livewire):
      php artisan sri:warm
      
    • Host Allowlist: Restrict SRI to trusted domains:
      'host_allowlist' => ['self', 'asset', 'https://cdn.example.com'],
      
  3. Violation Reporting

    • Log to DB: Enable persistence:
      'csp_report_db' => true,
      'sri_report_db' => true,
      
    • Custom Endpoint: Override routes:
      'csp_report_uri' => 'https://your-reporting-service.com/csp',
      
  4. Third-Party Integrations

    • GTM/HubSpot: Auto-configured via wizard. Add to CSP:
      'directives' => [
        'script-src' => ['self', 'nonce-{NONCE}', 'https://www.googletagmanager.com'],
      ],
      

Integration Tips

  • Livewire/Vapor: Use sri:warm for dynamic assets (e.g., Livewire JS).
  • Filament Panels: Pass nonce via ->cspNonce() in panel config.
  • Vite: Extend vite.config.js to generate SRI hashes:
    export default defineConfig({
      build: {
        manifest: true,
        outDir: 'public/build',
      },
    });
    
  • CMS Content: Disable CSP_NONCE_AUTO_INJECT if rendering user-generated HTML with {!! !!}.

Gotchas and Tips

Pitfalls

  1. SRI Manifest Mismatches

    • Issue: Hashes change across deploys (e.g., Livewire JS).
    • Fix: Use sri:warm for dynamic assets or exclude paths:
      'skip_url_patterns' => ['/livewire/'],
      
  2. CSP Nonce Leaks

    • Issue: Nonces in user-generated content (e.g., {!! $comment !!}) can bypass CSP.
    • Fix: Disable CSP_NONCE_AUTO_INJECT and manually nonce trusted scripts.
  3. Double CSP Headers

    • Issue: Multiple packages adding CSP headers (e.g., Laravel Fortify).
    • Fix: Disable conflicting packages or merge directives:
      'directives' => [
        'script-src' => ['self', 'nonce-{NONCE}', 'https://fortify.net'],
      ],
      
  4. SRI Observer Noise

    • Issue: Third-party SRI failures (e.g., reCAPTCHA) clutter reports.
    • Fix: Exclude mutable CDNs from host_allowlist; rely on CSP for them.

Debugging

  • CSP Violations: Check browser console for blocked resources. Test with:
    CSP_REPORT_ONLY=true php artisan serve
    
  • SRI Failures: Inspect sri_reports table or logs. Verify hashes with:
    openssl dgst -sha384 -binary public/js/app.js | openssl base64 -A
    
  • Middleware Order: Ensure SubresourceIntegrity middleware runs after web group (auto-handled by the package).

Config Quirks

  1. Environment Variables

    • Override defaults via .env:
      CSP_ASSET_DOMAIN=https://cdn.example.com
      SRI_CACHE_STORE=redis
      
    • Use arrays for multiple domains:
      CSP_ASSET_DOMAIN=https://cdn1.example.com,https://cdn2.example.com
      
  2. Path Exclusions

    • Regex-like matching (e.g., str_starts_with):
      'exclude_paths' => ['api/', 'admin.*'],  // Admin routes with regex
      
  3. Permissions-Policy

    • Deny all by default; explicitly allow features:
      'features' => [
        'geolocation' => ['self'],
        'camera' => ['none'],  // Block entirely
      ],
      

Extension Points

  1. Custom Directives

    • Extend CSP directives in config/security.php:
      'directives' => [
        'frame-ancestors' => ['self'],
        'form-action' => ['self'],
      ],
      
  2. Report Processing

    • Override report handlers in app/Providers/SecurityServiceProvider.php:
      $this->app->bind(\MakeDev\Security\Services\CspReportHandler::class, function () {
          return new CustomCspReportHandler();
      });
      
  3. Manifest Build

    • Customize hash generation:
      'hash_algorithm' => 'sha256',  // Default is sha384
      'scan_dirs' => ['public/js', 'public/css', 'vendor/alpinejs'],
      
  4. Vapor-Specific

    • Use sri:warm with DynamoDB:
      'cache_store' => env('AWS_DYNAMODB'),
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky