PHP code example of jayanta / laravel-threat-detection

1. Go to this page and download the library: Download jayanta/laravel-threat-detection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jayanta / laravel-threat-detection example snippets


->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        \JayAnta\ThreatDetection\Http\Middleware\ThreatDetectionMiddleware::class,
    ]);
})

protected $middlewareGroups = [
    'web' => [
        // ... existing middleware
        \JayAnta\ThreatDetection\Http\Middleware\ThreatDetectionMiddleware::class,
    ],
];

DB::table('threat_logs')->latest()->take(5)->get(['ip_address', 'type', 'threat_level', 'confidence_score']);

'enabled_environments' => ['production', 'staging', 'local'],

// config/threat-detection.php
'only_paths' => [
    'admin/*',
    'api/*',
    'login',
    'register',
],

// app/Providers/EventServiceProvider.php
use JayAnta\ThreatDetection\Events\ThreatDetected;

protected $listen = [
    ThreatDetected::class => [
        YourCustomListener::class,
    ],
];

use JayAnta\ThreatDetection\Events\DdosThresholdExceeded;

protected $listen = [
    DdosThresholdExceeded::class => [
        YourFloodListener::class,
    ],
];

// config/threat-detection.php
'api' => [
    'enabled' => true,
    'prefix' => 'api/threat-detection',
    'middleware' => ['api', 'auth'],  // or 'auth:your-guard'
],

'middleware' => ['api'],  // remove 'auth:sanctum'

// app/Http/Middleware/EnforceThreatDecisions.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use JayAnta\ThreatDetection\Facades\ThreatDetection;

class EnforceThreatDecisions
{
    public function handle(Request $request, Closure $next)
    {
        $ip = (string) $request->ip();

        // Static operator denylist (config: blocklisted_ips).
        // CIDR supported; whitelisted_ips wins on overlap.
        if (ThreatDetection::isBlocklisted($ip)) {
            abort(403);
        }

        // Volumetric flood: refuse over-threshold clients until the window resets.
        if (ThreatDetection::isDdosThresholdExceeded($ip)) {
            return response('Too Many Requests', 429, [
                'Retry-After' => (string) config('threat-detection.ddos.window', 60),
            ]);
        }

        return $next($request);
    }
}

// bootstrap/app.php (Laravel 11+)
->withMiddleware(function ($middleware) {
    $middleware->prepend(\App\Http\Middleware\EnforceThreatDecisions::class);
})

'probe_tracking' => [
    'enabled' => true,
    'default_level' => 'medium',
    'paths' => [
        '/wp-admin' => 'WordPress Admin',
        '/wp-admin/*' => 'WordPress Admin',
        '/.env' => 'Environment File',
        '/phpmyadmin' => 'phpMyAdmin',
        '/actuator/*' => 'Spring Actuator',
        // Add your own probe paths...
    ],
],

'/api/pull' => ['label' => 'Ollama Model Pull', 'level' => 'high'],

// config/threat-detection.php
'safe_fields' => ['content', 'body', 'html', 'description', 'code'],

// config/threat-detection.php
'safe_paths' => ['search.query', 'filters.*.value'],

// config/threat-detection.php
'pattern_validators' => [
    'Aadhaar Number Detected' => 'verhoeff',   // shipped default
],

'custom_patterns'    => ['/\b(?:\d[ -]?){13,19}\b/' => 'Card Number Detected'],
'pattern_validators' => ['Card Number Detected' => 'luhn'],

// config/threat-detection.php
'redact' => [
    'enabled' => env('THREAT_DETECTION_REDACT', true),
    'mask'    => '[REDACTED]',
    'labels'  => ['Aadhaar Number Detected', 'PAN Number Detected', /* ... */],
    'fields'  => ['password', 'api_key', 'token', 'cvv', /* ... */],
],

'custom_patterns' => [
    '/your-regex-here/i' => 'Your Threat Label',
],

'/\/my-admin-panel/i' => 'Custom Admin Panel Probe',

'custom_patterns' => [
    '/\b(?:\d[ -]?){13,19}\b/' => [
        'label'     => 'Card Number Detected',   // contexts'  => ['query', 'body'],        // query|body|headers — default: all segments
        'validator' => 'luhn',                   // post-match checksum, wins over pattern_validators
    ],
],

'threat_levels' => [
    'high' => ['XSS', 'SQL Injection', 'SQL DDL', 'SQL DML', 'SQL File', 'SQL Hex', 'RCE', ..., 'Shellshock', 'Spring4Shell', 'PowerShell', 'CRLF', 'Null Byte', 'SSTI', 'Java', 'LDAP', 'XPath', 'PHP assert', ...],
    'medium' => ['Directory Traversal', 'LFI', 'SSRF', 'Sensitive', 'Config', ..., 'Open Redirect', 'LF Injection', 'GraphQL', 'Spring Boot Actuator', ...],
    'low' => ['User-Agent', 'JS Redirect', 'SEO Bot', 'Empty', 'Rate', 'Command-line Downloader', 'DNS Rebinding'],
],

use JayAnta\ThreatDetection\Facades\ThreatDetection;

// Get attack statistics for a specific IP
$stats = ThreatDetection::getIpStatistics('192.168.1.1');

// Detect coordinated attacks (multiple IPs targeting same URL within 15 minutes)
$attacks = ThreatDetection::detectCoordinatedAttacks(15, 3);

// Detect attack campaigns (same threat type from 5+ IPs in last 24 hours)
$campaigns = ThreatDetection::detectAttackCampaigns(24);

// Get a summary of all correlation data
$summary = ThreatDetection::getCorrelationSummary();

// Operator-side decision helpers (see "Acting on the Data")
$blocked = ThreatDetection::isBlocklisted('203.0.113.7');       // static denylist, CIDR, whitelist wins
$trusted = ThreatDetection::isWhitelisted('10.0.0.5');
$count   = ThreatDetection::ddosRequestCount('203.0.113.7');    // requests in the current DDoS window
$flooded = ThreatDetection::isDdosThresholdExceeded('203.0.113.7');

// config/threat-detection.php
'content_paths' => [
    'admin/posts/*',
    'admin/pages/*',
    'blog/*/edit',
    'comments',
],
bash
composer vendor:publish --tag=threat-detection-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=threat-detection-migrations
php artisan migrate
bash
php artisan migrate:status
bash
php artisan vendor:publish --tag=threat-detection-config
bash
php artisan serve

http://localhost:8000/?cmd=system('ls -la')
bash
php artisan threat-detection:stats
bash
php artisan tinker
bash
php artisan threat-detection:doctor
bash
php artisan route:clear
xml
<env name="THREAT_DETECTION_ENABLED" value="false"/>
bash
php artisan vendor:publish --tag=threat-detection-config
bash
php artisan vendor:publish --tag=threat-detection-migrations
php artisan migrate

GET /api/threat-detection/correlation?type=mutations

GET /api/threat-detection/correlation?type=clusters

GET /api/threat-detection/correlation?type=retries

GET /api/threat-detection/correlation?type=actors