PHPackages                             kd/xss-shield - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. kd/xss-shield

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

kd/xss-shield
=============

Comprehensive XSS prevention package for Laravel with context-aware sanitization, monitoring, and testing tools

v1.0.0(3mo ago)01MITPHPPHP ^8.1|^8.2|^8.3

Since Feb 7Pushed 3mo agoCompare

[ Source](https://github.com/keyurbhimani/xss-shield)[ Packagist](https://packagist.org/packages/kd/xss-shield)[ RSS](/packages/kd-xss-shield/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (8)Versions (2)Used By (0)

XSS Shield 🛡️
=============

[](#xss-shield-️)

[![Latest Version on Packagist](https://camo.githubusercontent.com/4126dc382b0ee5c35bf16504850abeb237ce539c53432081161d6dde74d112d6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b642f7873732d736869656c642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/kd/xss-shield)[![Total Downloads](https://camo.githubusercontent.com/0ee0292e6c8f0a5675ed87ab29a51689f31ab884efdb5947684afa02c0a36ee0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6b642f7873732d736869656c642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/kd/xss-shield)[![License](https://camo.githubusercontent.com/70736c68d8873137203d8366a6006b842c7ee94eb382cd4bf051854ac4a03409/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6b642f7873732d736869656c642e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/kd/xss-shield)

**XSS Shield** is a premium, high-performance security package designed to protect your Laravel applications from Cross-Site Scripting (XSS) attacks. Unlike other packages, XSS Shield uses a **Zero-Dependency**, custom-built engine optimized for speed and context-aware sanitization.

---

🚀 Why XSS Shield?
-----------------

[](#-why-xss-shield)

### 1. 🛡️ Zero External Dependencies (Custom Engine)

[](#1-️-zero-external-dependencies-custom-engine)

We do **NOT** rely on heavy third-party libraries or legacy sanitizers.

- **Lighter**: No bloat added to your `vendor` folder.
- **Faster**: Our custom regex engine is significantly optimized for speed.
- **Secure**: Audited specifically for modern XSS vectors (polyglots, obscure protocols).

### 2. ⚡ Intelligent &amp; Context-Aware

[](#2--intelligent--context-aware)

Most filters are "all or nothing". XSS Shield understands context:

- **Strict**: For usernames/fields (No HTML allowed).
- **Moderate**: For comments/bios (Safe HTML like ``, ``, `` allowed).
- **Relaxed**: For CMS/Admin areas (Almost all HTML allowed, scripts blocked).

### 3. 📊 Real-Time Threat Intelligence

[](#3--real-time-threat-intelligence)

Includes a built-in **dashboard** to visualize attacks effectively.

- **Monitor**: See live attack attempts.
- **Analyze**: Identify which IPs and users are targeting you.
- **Block**: Logs the exact malicious payload for forensic analysis.

---

🛠️ Installation
---------------

[](#️-installation)

```
composer require kd/xss-shield
```

Publish the configuration and assets:

```
php artisan xss-shield:install
```

---

� Comprehensive Usage Guide
---------------------------

[](#-comprehensive-usage-guide)

### 1. Middleware Protection (The "Set &amp; Forget" Method)

[](#1-middleware-protection-the-set--forget-method)

Protect your routes automatically. The middleware scans `POST`, `PUT`, `PATCH` requests.

#### Single Route

[](#single-route)

```
Route::post('/comment', [CommentController::class, 'store'])
    ->middleware('xss.shield:moderate');
```

#### Route Groups (Recommended)

[](#route-groups-recommended)

Apply to entire feature areas with different policies.

```
// Public Area - Strict Protection (No HTML)
Route::middleware(['xss.shield:strict'])->group(function () {
    Route::post('/register', [AuthController::class, 'register']);
    Route::post('/contact', [ContactController::class, 'send']);
});

// User Area - Moderate Protection (Basic Formatting Allowed)
Route::middleware(['auth', 'xss.shield:moderate'])->group(function () {
    Route::post('/profile/update', [ProfileController::class, 'update']);
    Route::post('/posts', [PostController::class, 'store']);
});
```

---

### 2. Blade Directives (Safe Output)

[](#2-blade-directives-safe-output)

Sanitize data right before displaying it.

#### A. `@xss($var)` - Strict Output

[](#a-xssvar---strict-output)

Removes **ALL** HTML tags. Use for names, titles, inputs.

```

Hello, @xss($user->name)

```

#### B. `@xssHtml($var)` - Safe HTML (Moderate)

[](#b-xsshtmlvar---safe-html-moderate)

Allows safe formatting tags (``, ``, ``) but strips scripts/iframes.

```

    @xssHtml($user->bio)

```

#### C. `@safeHtml($var)` - Trusted HTML (Relaxed)

[](#c-safehtmlvar---trusted-html-relaxed)

Allows images, tables, and links. Perfect for detailed content.

```

    @safeHtml($article->content)

```

---

### 3. Validation Rules

[](#3-validation-rules)

Validate input *before* it hits your controller logic.

```
use Illuminate\Http\Request;

public function store(Request $request)
{
    $request->validate([
        // Reject if contains XSS (Strict)
        'username' => 'required|string|xss:strict',

        // Clean and allow if safe (Moderate)
        'bio' => 'required|string|xss:moderate',

        // Custom policy validation
        'content' => 'required|xss:custom,policy:blog_post',
    ]);
}
```

---

### 4. Manual Usage (Facades &amp; Helpers)

[](#4-manual-usage-facades--helpers)

For granular control in your code.

```
use KD\XssShield\Facades\XssShield;

// Clean a string
$clean = XssShield::clean($input, 'moderate');

// Check if input contains XSS
if (XssShield::detect($input)) {
    abort(403, 'Malicious content detected');
}

// Helper Function
$clean_bio = xss_clean($dirty_bio, 'moderate');
```

---

🔒 Content Security Policy (CSP)
-------------------------------

[](#-content-security-policy-csp)

XSS Shield automates CSP header management, a critical security layer.

1. **Enable in Config**: Set `'enabled' => true` in `config/xss-shield.php`.
2. **Automatic Nonces**: The package generates a unique `nonce` for every request.

**Using Nonces in Blade:**Allow inline scripts securely by adding the nonce:

```

    var appData = { ... }; // This allowed

    alert('blocked'); // This BLOCKED by browser

```

---

📊 Dashboard &amp; Monitoring
----------------------------

[](#-dashboard--monitoring)

Access the dashboard at: `http://your-app.test/xss-shield/dashboard`

### Inspecting Logs

[](#inspecting-logs)

Below the charts is the **Recent Blocked Attacks** table. Click "View All Logs" to see detailed records:

ViewVisible Columns**Dashboard Overview**Time, IP Address, Attack Type, **Target URL**, Method**Full Logs View**Date, IP Address, Attack Type, Method, **Payload Snippet**, User Agent> **Note**: Hover over the "Payload Snippet" in the detailed logs to see the full malicious string.

---

📘 Cookbook &amp; Advanced Examples
----------------------------------

[](#-cookbook--advanced-examples)

### 1. Protect Logic in Controllers

[](#1-protect-logic-in-controllers)

Sometimes you need to clean data *inside* a controller without middleware.

```
public function updateProfile(Request $request)
{
    // 1. Clean a specific field
    $cleanBio = xss_clean($request->input('bio'), 'moderate');

    // 2. Check if input is malicious before processing
    if (XssShield::detect($request->input('website'))) {
        return back()->withErrors(['website' => 'Security alert: Malicious content detected.']);
    }

    $user->update(['bio' => $cleanBio]);
}
```

### 2. Handling JSON API Requests

[](#2-handling-json-api-requests)

XSS Shield automatically works with JSON bodies. No extra config needed.

**Request:**

```
POST /api/comments
Content-Type: application/json

{
    "comment": "Nice post! stealCookies()",
    "author_id": 5
}
```

**Result (Moderate Policy):**The middleware automatically cleans the JSON input before it reaches your controller:

```
{
    "comment": "Nice post! stealCookies()",
    "author_id": 5
}
```

### 3. Custom Policy for Specific Feature

[](#3-custom-policy-for-specific-feature)

Add this to your `AppServiceProvider::boot()` method to create a reusable policy for a Forum feature.

```
// App\Providers\AppServiceProvider.php

public function boot()
{
    app('xss-shield')->registerPolicy('forum_post', [
        'strip_tags' => false,
        'allowed_tags' => ['b', 'i', 'u', 'img', 'blockquote', 'code', 'pre'],
        'allowed_attributes' => [
            'img' => ['src', 'alt', 'width', 'height'],
            'code' => ['class'], // Allow syntax highlighting classes
            'global' => ['style'], // NOT recommended usually, but possible
        ],
        'blocked_tags' => ['script', 'iframe', 'applet'],
    ]);
}
```

**Usage:**

```
Route::post('/forum/topic', [TopicController::class, 'store'])
    ->middleware('xss.shield:custom,policy:forum_post');
```

---

⚙️ Configuration Reference
--------------------------

[](#️-configuration-reference)

You can publish the config file with `php artisan vendor:publish --tag=xss-shield-config`.

### 1. Protection Layers &amp; Advanced Vectors

[](#1-protection-layers--advanced-vectors)

By default, all protection layers are enabled. You can toggle them in `config/xss-shield.php`.

```
'protection_layers' => [
    'input_sanitization' => true, // Global middleware cleaning
    'pattern_detection' => [
        'enabled' => true,
        'patterns' => 'comprehensive', // 'basic' | 'moderate' | 'comprehensive'
    ],
],

'advanced_vectors' => [
    'svg_xss' => true,       // Block malicious SVG uploads
    'css_injection' => true, // Block malicious CSS (e.g., expression())
    'polyglot_detection' => true, // Detect complex polyglots
],
```

> **Tip**: If you strictly sanitize inputs, you might disable `output_encoding` to rely on Blade's `{{ }}` escaping.

### 2. Exclusions (Webhooks &amp; Passwords)

[](#2-exclusions-webhooks--passwords)

Prevent the middleware from modifying specific requests.

```
'excluded_routes' => [
    'api/webhook/*',      // Webhooks need raw payloads
    'admin/settings',     // Trusted admin routes
],

'excluded_keys' => [
    'password',           // Common exclusion
    'password_confirmation',
    'api_key',            // Don't modify API keys
],
```

### 3. Content Security Policy (CSP)

[](#3-content-security-policy-csp)

Configure CSP headers to prevent script execution from unauthorized sources.

```
'csp' => [
    'enabled' => true,
    'directives' => [
        'default-src' => ["'self'"],
        'script-src' => ["'self'", "'nonce'"], // 'nonce' handles inline scripts
        'style-src' => ["'self'", "'nonce'", 'https://fonts.googleapis.com'],
        'img-src' => ["'self'", 'data:', 'https://cdn.example.com'],
    ],
    'auto_nonce' => true, // Automatically generate/inject nonce
],
```

### 4. Logging &amp; Monitoring

[](#4-logging--monitoring)

Choose how to store attack logs.

```
'logging' => [
    'enabled' => true,
    'driver' => 'database', // 'database' for Dashboard, 'file' for logs/laravel.log
    'level' => 'all',       // 'critical' (blocked only) or 'all' (all attempts)
    'retention_days' => 90, // Auto-delete old logs
],
```

### 5. Performance Tweaks

[](#5-performance-tweaks)

Optimize for high-load environments.

```
'performance' => [
    'cache' => [
        'enabled' => true,  // Caches compiled regex patterns
        'driver' => 'file',
    ],
    'lazy_evaluation' => true, // Only load detectors when attack potential is found
],
```

### 6. Dashboard Customization

[](#6-dashboard-customization)

Secure and customize the dashboard URL.

```
'dashboard' => [
    'enabled' => true,
    'route_prefix' => 'security/xss', // Changes: /xss-shield/dashboard -> /security/xss/dashboard
    'middleware' => ['web', 'auth', 'can:manage_security'], // Add custom permissions
],
```

### 7. Custom Policies

[](#7-custom-policies)

Register reusable policies in `AppServiceProvider`.

```
// config/xss-shield.php (or dynamic)
'policies' => [
    'blog' => [
        'allowed_tags' => ['h1', 'p', 'b', 'i', 'img'],
        'allowed_attributes' => ['img' => ['src', 'alt']],
    ],
],
```

---

🧪 Security Benchmarking
-----------------------

[](#-security-benchmarking)

We include tools to test your own application.

```
# 1. Scan your routes for coverage
php artisan xss-shield:scan-routes

# 2. Benchmark sanitization speed
php artisan xss-shield:benchmark

# 3. Simulate an attack on a specific policy
php artisan xss-shield:test --policy=moderate --payload=""
```

---

🛠️ Artisan Commands
-------------------

[](#️-artisan-commands)

XSS Shield includes several commands to help you manage security.

### 1. Test Protection

[](#1-test-protection)

Simulate attacks to verify your policy settings.

```
# Basic test (moderate policy)
php artisan xss-shield:test

# Detailed output showing every payload
php artisan xss-shield:test --detailed

# Test a specific policy
php artisan xss-shield:test --policy=strict
```

### 2. Update Threat Intelligence

[](#2-update-threat-intelligence)

Update local threat definitions (clears pattern cache).

```
# Update patterns
php artisan xss-shield:update-threats

# Force update even if disabled in config
php artisan xss-shield:update-threats --force
```

### 3. Scan Routes

[](#3-scan-routes)

Find which of your routes are protected and which are vulnerable.

```
php artisan xss-shield:scan-routes
```

### 4. Benchmark Performance

[](#4-benchmark-performance)

Check the speed overhead of the sanitization engine.

```
php artisan xss-shield:benchmark
```

---

📄 License
---------

[](#-license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

Developed with ❤️ by **KD**.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance81

Actively maintained with recent releases

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

100d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0e612945da02e105ff54dcb289f8cb76ff73d644d722f23045774a6932082d46?d=identicon)[keyurbhimani](/maintainers/keyurbhimani)

---

Top Contributors

[![keyurbhimani](https://avatars.githubusercontent.com/u/36122223?v=4)](https://github.com/keyurbhimani "keyurbhimani (1 commits)")

---

Tags

laravelsecurityxssprotectionsanitizationzero-dependenciesKDcustom-security-engine

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/kd-xss-shield/health.svg)

```
[![Health](https://phpackages.com/badges/kd-xss-shield/health.svg)](https://phpackages.com/packages/kd-xss-shield)
```

###  Alternatives

[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

71510.9M66](/packages/laravel-mcp)[wendelladriel/laravel-validated-dto

Data Transfer Objects with validation for Laravel applications

759569.4k13](/packages/wendelladriel-laravel-validated-dto)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[galahad/laravel-addressing

Laravel package providing addressing functionality

70316.6k](/packages/galahad-laravel-addressing)[axlon/laravel-postal-code-validation

Worldwide postal code validation for Laravel and Lumen

3853.3M1](/packages/axlon-laravel-postal-code-validation)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
