PHPackages                             rafalmasiarek/threat-detector - 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. [Security](/categories/security)
4. /
5. rafalmasiarek/threat-detector

ActiveLibrary[Security](/categories/security)

rafalmasiarek/threat-detector
=============================

Heuristic, modular threat detection (signal-only) with weighted float scoring, predefined thresholds, and PSR-15 middleware for PSR-7 apps.

v1.0.0(10mo ago)04MITPHPPHP &gt;=8.1

Since Sep 7Pushed 10mo agoCompare

[ Source](https://github.com/rafalmasiarek/php-threat-detector)[ Packagist](https://packagist.org/packages/rafalmasiarek/threat-detector)[ RSS](/packages/rafalmasiarek-threat-detector/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (4)Versions (2)Used By (0)

rafalmasiarek/threat-detector
=============================

[](#rafalmasiarekthreat-detector)

[![Latest Version](https://camo.githubusercontent.com/40311ee613e12e60dbe3f4cace9fe62e0c1a765df39caa37bbfb27d670e20103/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f726166616c6d6173696172656b2f7468726561742d6465746563746f722e737667)](https://packagist.org/packages/rafalmasiarek/threat-detector)[![License](https://camo.githubusercontent.com/84bbf088a624d2963fa25af42cdef763891df37a7e4e5081fd0bde9e47c435c8/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f726166616c6d6173696172656b2f7468726561742d6465746563746f72)](LICENSE)[![PHP](https://camo.githubusercontent.com/d6aac44f81cb2e6f4e71f098a1cb4a71992f24f7bfb424f6670db8313c9a855c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253545382e312d626c7565)](https://camo.githubusercontent.com/d6aac44f81cb2e6f4e71f098a1cb4a71992f24f7bfb424f6670db8313c9a855c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253545382e312d626c7565)

Heuristic, **modular** threat detection (signal-only) with **weighted float scoring**, **predefined thresholds**, and **PSR-15 middleware** for PSR-7 applications.

> ⚠️ This library is a *signal generator*. It **does not replace** proper validation/sanitization/escaping, CSP, prepared statements, etc.

---

Features
--------

[](#features)

- 🧩 **Modular scanners** — each category (XSS, SQLi, SSRF, …) in a separate class.
- ⚖️ **Weighted float scoring** — per-category weights; combine multiple signals.
- 🎚️ **Predefined thresholds** — `LOW`, `MEDIUM`, `HIGH` (or custom floats).
- 🧵 **PSR-15 middleware** — scan query, body, headers, cookies; annotate request; optional header `X-Threat-Suspect`.
- 📝 **phpDocs &amp; comments** — production-friendly code with clear docs.
- ✅ **Unit tests** — a couple of quick checks to get you started.
- 📂 **Examples** — basic HTML form + PSR-15 middleware demo.

---

Requirements
------------

[](#requirements)

- PHP **8.1+**
- ext-mbstring

---

Installation
------------

[](#installation)

Using Composer:

```
composer require rafalmasiarek/threat-detector
```

If you are using this repository locally (path repo):

```
composer config repositories.threat-detector path ./threat-detector
composer require rafalmasiarek/threat-detector:dev-main
```

---

Quick Start (Core)
------------------

[](#quick-start-core)

```
use rafalmasiarek\Threat\Core\ThreatDetector;
use rafalmasiarek\Threat\Core\ScoringPolicy;
use rafalmasiarek\Threat\Core\Thresholds;

// Create a policy with default weights and MEDIUM threshold
$policy = ScoringPolicy::withDefaults()
    ->withThreshold(Thresholds::MEDIUM)  // or 'LOW' | 'HIGH' | 3.5 (float)
    ->withWeight('SQLI', 2.25);          // optional: override category weights

$detector = ThreatDetector::default($policy);

// Scan a string
$input = "alert(1)";
$result = $detector->scanString($input);

var_dump($result->suspect); // bool
var_dump($result->score);   // float
var_dump($result->hits);    // array{category => list}
var_dump($result->norm);    // normalized input
```

Example output:

```
bool(true)
float(3)
array(1) {
  ["XSS"]=>
  array(2) {
    [0]=> string(10) "TAG_SCRIPT"
    [1]=> string(9)  "HTML_TAGS"
  }
}
string(23) "alert(1)"
```

---

Quick Start (PSR-15 Middleware)
-------------------------------

[](#quick-start-psr-15-middleware)

```
use rafalmasiarek\Threat\Middleware\ThreatDetectMiddleware;

$middleware = new ThreatDetectMiddleware([
    'threshold'    => 'MEDIUM',          // 'LOW' | 'MEDIUM' | 'HIGH' | float
    'weights'      => ['SQLI' => 2.1],   // optional overrides
    'scan_query'   => true,
    'scan_body'    => true,
    'scan_headers' => false,             // true or array of headers to scan
    'scan_cookies' => false,
    'attribute'    => 'threat.result',   // request attribute name
    'set_header'   => true,              // add X-Threat-Suspect: 1 when suspect
]);

// Add to your PSR-15 stack (Slim/Mezzio/etc.)
$result = $request->getAttribute('threat.result');
```

Example result:

```
[
  'suspect' => true,
  'score'   => 3.5,
  'hits'    => ['XSS' => ['TAG_SCRIPT','HTML_TAGS']],
]
```

---

Scoring
-------

[](#scoring)

- **Weights**: per category (e.g., `SQLI=2.0`, `CMD_INJECTION=2.5`, `CRLF=1.0`).
- **Score formula**: ```
    score = Σ ( weight(category) × unique_hits(category) )

    ```
- **Threshold**: request is **suspect** when `score ≥ threshold`.

### Predefined thresholds

[](#predefined-thresholds)

NameValueSensitivityLOW1.0Very sensitiveMEDIUM2.5Balanced (default)HIGH5.0Strict### Examples

[](#examples)

- `alert(1)`
    Hits: `XSS=[TAG_SCRIPT, HTML_TAGS]`
    Score: `1.5 × 2 = 3.0` → suspect at `MEDIUM`
- `UNION SELECT password FROM users`
    Hits: `SQLI=[UNION_SELECT]`
    Score: `2.0 × 1 = 2.0` → not suspect at `MEDIUM`, suspect at `LOW`

---

Categories &amp; Scanners
-------------------------

[](#categories--scanners)

- **XSS** — inline event handlers, ``, `javascript:` URIs.
- **SQLI** — `UNION SELECT`, `SLEEP()`, `INFORMATION_SCHEMA`, etc.
- **CMD\_INJECTION** — subshells, `;`, `&&`, `wget/curl`, redirects.
- **PATH\_TRAVERSAL** — `../`, URL-encoded traversal, `file://`, wrappers.
- **CRLF** — header injection sequences.
- **SSRF** — URLs to `localhost`, `127.0.0.1`, `RFC1918` ranges.
- **XXE** — ``, ``, external SYSTEM.
- **NOSQL** — Mongo-like operators `$where`, `$regex`.
- **LDAP** — wildcards, null bytes.
- **SERIALIZATION** — PHP serialized payload patterns.

---

Integration Ideas
-----------------

[](#integration-ideas)

- Add to Slim/Mezzio pipeline as PSR-15 middleware.
- Run against form input before sending mail (contact forms).
- Log suspect inputs into a security audit trail.
- Flag suspicious requests in rate-limiting / WAF logic.

---

Tests &amp; Examples
--------------------

[](#tests--examples)

- PHPUnit tests included (`tests/`):
    - `TruePositiveDetectionsTest.php`
    - `FalsePositiveHeuristicsTest.php`
- Example apps in `examples/`:
    - `basic/` (HTML form demo)
    - `psr15/` (middleware demo)

Run tests:

```
./vendor/bin/phpunit --colors=always
```

---

Security Notice
---------------

[](#security-notice)

This library generates **signals only**.
Always combine with:

- Prepared statements for SQL queries
- Proper HTML escaping and CSP
- Strong input validation

---

Folder Structure
----------------

[](#folder-structure)

```
src/
  Contracts/ScannerInterface.php
  Core/{ThreatDetector.php, ThreatResult.php, ScoringPolicy.php, Thresholds.php}
  Scanner/{XssScanner.php, SqliScanner.php, CmdInjectionScanner.php, PathTraversalScanner.php, CrlfScanner.php, SsrfScanner.php, XxeScanner.php, NoSqlScanner.php, LdapScanner.php, SerializationScanner.php}
  Middleware/ThreatDetectMiddleware.php
tests/
  ModularThreatDetectorTest.php
examples/
  basic/
  psr15/

```

---

License
-------

[](#license)

MIT

###  Health Score

29

—

LowBetter than 57% of packages

Maintenance55

Moderate activity, may be stable

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

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

300d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/36776423?v=4)[Rafał Masiarek](/maintainers/rafalmasiarek)[@rafalmasiarek](https://github.com/rafalmasiarek)

---

Top Contributors

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

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/rafalmasiarek-threat-detector/health.svg)

```
[![Health](https://phpackages.com/badges/rafalmasiarek-threat-detector/health.svg)](https://phpackages.com/packages/rafalmasiarek-threat-detector)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.9k19.5M1.8k](/packages/cakephp-cakephp)[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)[cakephp/authentication

Authentication plugin for CakePHP

1214.1M106](/packages/cakephp-authentication)[typo3/cms-core

TYPO3 CMS Core

3713.2M5.1k](/packages/typo3-cms-core)[typo3/cms-adminpanel

TYPO3 CMS Admin Panel - The Admin Panel displays information about your site in the frontend and contains a range of metrics including debug and caching information.

115.7M66](/packages/typo3-cms-adminpanel)[flarum/core

Delightfully simple forum software.

201.4M2.3k](/packages/flarum-core)

PHPackages © 2026

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