PHPackages                             mrpunyapal/laravel-ai-aegis - 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. mrpunyapal/laravel-ai-aegis

ActiveLibrary[Security](/categories/security)

mrpunyapal/laravel-ai-aegis
===========================

A native, local-first security middleware for the Laravel AI SDK with bidirectional pseudonymization, prompt injection defense, and real-time Pulse telemetry.

0.0.4(2mo ago)30MITPHPPHP ^8.3CI failing

Since Mar 29Pushed 2mo agoCompare

[ Source](https://github.com/MrPunyapal/laravel-ai-aegis)[ Packagist](https://packagist.org/packages/mrpunyapal/laravel-ai-aegis)[ Docs](https://github.com/mrpunyapal/laravel-ai-aegis)[ RSS](/packages/mrpunyapal-laravel-ai-aegis/feed)WikiDiscussions main Synced 3w ago

READMEChangelog (4)Dependencies (36)Versions (6)Used By (0)

Laravel AI Aegis
================

[](#laravel-ai-aegis)

[![Latest Version on Packagist](https://camo.githubusercontent.com/880cc1c521fe80a0816725b85cf8b8d68a32f78d2408d69e44f7221e36a27ba4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d7270756e796170616c2f6c61726176656c2d61692d61656769732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mrpunyapal/laravel-ai-aegis)[![Lint & Static Analysis](https://camo.githubusercontent.com/3aee38e5e68b2c788ec82edf648d7f31c431c5a4c788ad548a57347d8a8dd0cf/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d7270756e796170616c2f6c61726176656c2d61692d61656769732f6c696e742d7374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d6c696e742b2532362b7374616e267374796c653d666c61742d737175617265)](https://github.com/mrpunyapal/laravel-ai-aegis/actions?query=workflow%3ALint+branch%3Amain)[![Tests](https://camo.githubusercontent.com/560a1c5c1938b5bd1047cc0100d4bdbf530b94c448c5b9d89057d883bb81e927/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d7270756e796170616c2f6c61726176656c2d61692d61656769732f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/mrpunyapal/laravel-ai-aegis/actions?query=workflow%3ATests+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/1fc40a609d3480a5f3f593029c34b7b8ad03c2da1bef7e22fccf698450bb2971/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d7270756e796170616c2f6c61726176656c2d61692d61656769732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mrpunyapal/laravel-ai-aegis)

A native, **local-first** security middleware for the **Laravel AI SDK**. Aegis intercepts every AI agent prompt and response to protect your users' data and your system prompts — without ever sending raw PII or adversarial payloads to an external LLM provider.

Features
--------

[](#features)

- **Pluggable PII Rules with DSL** — Configure per-type actions (`tokenize`, `replace`, `mask`) directly in config or per-agent via the `#[Aegis]` attribute. Fine-tune masking depth with `email:mask,3,5`.
- **12 Built-in PII Types** — email, phone, SSN, credit card, IP address, full name, street address, date of birth, bank account, API key, JWT, URL — plus user-defined custom types.
- **Staged Guard Rail Pipeline** — Six pluggable security stages run in order: input (injection, length, blocked phrases), approval, PII transform, LLM call, output (PII leakage, blocked phrases), PII restore.
- **Localized Prompt Injection Defense** — A built-in semantic firewall evaluates prompts against 30+ known adversarial attack patterns entirely locally — no external API call required.
- **Per-Agent Declarative Configuration** — The `#[Aegis]` attribute on any Agent class overrides global defaults with fine-grained, per-route security rules.
- **Laravel Pulse Integration** — Real-time telemetry: blocked injections, guard rail violations, PII token volume, tool denials, and approval events.
- **Artisan Commands** — `aegis:install` for guided setup, `aegis:test` for interactive per-rule prompt diagnostics.

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

[](#requirements)

DependencyVersionPHP`^8.3`Laravel`^12.0 | ^13.0`Laravel Pulse *(optional)*`^1.0`Installation
------------

[](#installation)

```
composer require mrpunyapal/laravel-ai-aegis
```

Run the install command for guided setup:

```
php artisan aegis:install
```

Or publish the config file manually:

```
php artisan vendor:publish --tag="aegis-config"
```

Configuration
-------------

[](#configuration)

```
// config/aegis.php

return [
    'pii' => [
        'enabled' => env('AEGIS_PII_ENABLED', true),

        // Rule formats — see "PII Rules DSL" section below
        'rules' => ['email:tokenize', 'phone:replace', 'ssn:mask,0,4'],

        // Custom PiiTypeInterface implementations
        'custom_detectors' => [],
    ],

    'guard_rails' => [
        'input' => [
            'injection' => [
                'enabled'          => env('AEGIS_BLOCK_INJECTIONS', true),
                'threshold'        => env('AEGIS_INJECTION_THRESHOLD', 0.7),
                'strict_threshold' => 0.3,
            ],
            'max_length'      => env('AEGIS_MAX_INPUT_LENGTH', null),
            'blocked_phrases' => [],
        ],
        'output' => [
            'pii_leakage'     => ['enabled' => env('AEGIS_BLOCK_OUTPUT_PII', true)],
            'blocked_phrases' => [],
        ],
        'tool'     => ['allowed' => [], 'blocked' => []],
        'approval' => ['enabled' => false, 'handler' => null],
    ],

    'strict_mode' => env('AEGIS_STRICT_MODE', false),

    'cache' => [
        'store'  => env('AEGIS_CACHE_STORE', 'redis'),
        'prefix' => 'aegis_pii',
        'ttl'    => env('AEGIS_CACHE_TTL', 3600),
    ],

    'pulse' => [
        'enabled' => env('AEGIS_PULSE_ENABLED', true),
    ],
];
```

> **Redis is recommended** for `cache.store` in production. Tokenized PII mappings must survive the full request/response cycle.

Usage
-----

[](#usage)

### Registering the Middleware

[](#registering-the-middleware)

```
use MrPunyapal\LaravelAiAegis\Middleware\AegisMiddleware;

$agent->withMiddleware([
    app(AegisMiddleware::class),
]);
```

### How the Pipeline Works

[](#how-the-pipeline-works)

```
User Prompt
     │
     ▼
 ┌────────────────────────────────────────────────┐
 │                AegisMiddleware                 │
 │                                                │
 │  1. runInput()  — injection, max-length,       │──► AegisSecurityException
 │                   blocked phrases              │    on any violation
 │                                                │
 │  2. runApproval() — custom approval handler    │──► AegisSecurityException
 │                     (if requireApproval=true)  │    if denied
 │                                                │
 │  3. PII transform (outbound)                   │
 │     john@example.com → {{AEGIS_EMAIL_8F92A}}   │
 │                                                │
 │  4. $next($prompt) ─────────────────────────────────► LLM Provider
 │                                                │           │
 │  5. ->then() ◄──────────────────────────────────────── LLM Response
 │     runOutput() — PII leakage, blocked phrases │
 │                                                │
 │  6. PII restore (inbound, tokenize only)       │
 │     {{AEGIS_EMAIL_8F92A}} → john@example.com   │
 └────────────────────────────────────────────────┘
     │
     ▼
Final Response (safe, PII restored)

```

PII Rules DSL
-------------

[](#pii-rules-dsl)

Every rule is either a **string** (DSL) or a **structured array**. Rules are set globally in `config/aegis.php` under `pii.rules`, or per-agent via the `#[Aegis]` attribute.

### String DSL

[](#string-dsl)

RuleActionBehaviour`email`tokenizeReversible token — default when no action given`email:tokenize`tokenizeExplicit tokenize`email:replace`replaceStatic `[REDACTED:EMAIL]` placeholder`email:replace,***`replaceCustom static text`email:mask`maskFull mask with `*``email:mask,3`maskKeep 3 chars at start, mask rest`email:mask,3,5`maskKeep 3 at start and 5 at end, mask middle> **Safety fallback**: when `maskStart + maskEnd ≥ value length`, the entire value is masked to prevent accidental leakage.

### Structured Array

[](#structured-array)

```
'rules' => [
    ['type' => 'email',  'action' => 'mask',    'mask_start' => 3, 'mask_end' => 5],
    ['type' => 'phone',  'action' => 'replace',  'replacement' => '[PHONE]'],
    ['type' => 'ssn',    'action' => 'tokenize'],
],
```

### Built-in PII Types

[](#built-in-pii-types)

TypeDetects`email``john.doe@example.com``phone``555-123-4567`, `+1 (555) 123-4567``ssn``123-45-6789``credit_card``4111-1111-1111-1111``ip_address``192.168.1.100``name``John Smith`, `Mary Jane Watson``address``123 Main St`, `456 Oak Avenue``date_of_birth``01/15/1990`, `1990/01/15``bank_account`8–17 digit account numbers`api_key``sk-abc123…`, `pk_live_…``jwt``eyJ…` (three-part JWT tokens)`url``https://internal.company.com/…`### Custom PII Types

[](#custom-pii-types)

Implement `PiiTypeInterface` and register the class in config:

```
use MrPunyapal\LaravelAiAegis\Contracts\PiiTypeInterface;

final readonly class NhsNumberType implements PiiTypeInterface
{
    public function type(): string    { return 'nhs_number'; }
    public function pattern(): string { return '/\b\d{3}\s\d{3}\s\d{4}\b/'; }
}
```

```
// config/aegis.php
'pii' => [
    'custom_detectors' => [
        \App\Pii\NhsNumberType::class,
    ],
    'rules' => ['email:mask,3', 'nhs_number:replace'],
],
```

Per-Agent Configuration — `#[Aegis]`
------------------------------------

[](#per-agent-configuration--aegis)

The `#[Aegis]` attribute on an Agent class overrides all global defaults for that agent. Every parameter is optional and falls back to config when omitted.

```
use MrPunyapal\LaravelAiAegis\Attributes\Aegis;

#[Aegis(
    piiEnabled:           true,
    piiRules:             ['email:mask,3,5', 'ssn:replace', 'credit_card:tokenize'],
    blockInjections:      true,
    strictMode:           true,
    injectionThreshold:   0.4,
    inputBlockedPhrases:  ['competitor name', 'internal codename'],
    maxInputLength:       2000,
    blockOutputPii:       true,
    outputBlockedPhrases: ['confidential', 'internal only'],
    allowedTools:         ['weather_tool', 'calendar_tool'],
    blockedTools:         ['file_write_tool'],
    requireApproval:      true,
    approvalHandler:      \App\Handlers\HumanApprovalHandler::class,
)]
class MedicalSupportAgent extends Agent {}
```

ParameterTypeDefaultDescription`piiEnabled``bool``true`Enable PII transformation`piiRules``array``[]` → config fallbackDSL strings or structured arrays`blockInjections``bool``true`Enable injection detection`strictMode``bool``false`Lower injection threshold to `0.3``injectionThreshold``?float``null` → config fallbackOverride threshold for this agent`inputBlockedPhrases``array``[]` → config fallbackPhrases that block the request`maxInputLength``?int``null` → config fallbackMax prompt character count`blockOutputPii``bool``true`Scan LLM response for PII leakage`outputBlockedPhrases``array``[]` → config fallbackPhrases blocked in responses`allowedTools``array``[]` = all allowedAllowlist of tool names`blockedTools``array``[]`Blocklist of tool names`requireApproval``bool``false`Require human approval before LLM call`approvalHandler``?string``null`FQCN of `ApprovalHandlerInterface`Guard Rails
-----------

[](#guard-rails)

All guard rails are registered automatically by the service provider. Each implements `GuardRailInterface` and is scoped to a `GuardRailStage`.

### Built-in Guard Rails

[](#built-in-guard-rails)

Guard RailStageWhat it does`InjectionGuardRail``Input`Blocks prompts above the injection threshold`MaxLengthGuardRail``Input`Blocks prompts exceeding `maxInputLength``BlockedPhrasesGuardRail``Input` / `Output`Case-insensitive phrase blocklist`OutputPiiGuardRail``Output`Re-scans LLM response for PII leakage`ToolGuardRail``Tool`Enforces `allowedTools` / `blockedTools``ApprovalGuardRail``Approval`Delegates to an `ApprovalHandlerInterface`### Custom Guard Rails

[](#custom-guard-rails)

```
use MrPunyapal\LaravelAiAegis\Contracts\GuardRailInterface;
use MrPunyapal\LaravelAiAegis\Data\GuardRailResult;
use MrPunyapal\LaravelAiAegis\Enums\GuardRailStage;

final readonly class ToxicityGuardRail implements GuardRailInterface
{
    public function stage(): GuardRailStage { return GuardRailStage::Input; }

    public function check(string $content, mixed $context): GuardRailResult
    {
        if ($this->isToxic($content)) {
            return GuardRailResult::fail(reason: 'Toxic content detected.', stage: 'input');
        }
        return GuardRailResult::pass();
    }
}
```

Register it in a service provider:

```
$this->app->extend(GuardRailOrchestratorInterface::class, function ($orchestrator) {
    $orchestrator->register(new ToxicityGuardRail);
    return $orchestrator;
});
```

### Human Approval Handler

[](#human-approval-handler)

```
use MrPunyapal\LaravelAiAegis\Contracts\ApprovalHandlerInterface;

final class SlackApprovalHandler implements ApprovalHandlerInterface
{
    public function approve(string $content, mixed $context): bool
    {
        // Send Slack notification and wait for response...
        return $this->waitForSlackApproval($content);
    }
}
```

Exception Handling
------------------

[](#exception-handling)

All security violations throw `AegisSecurityException` (extends `RuntimeException`):

```
use MrPunyapal\LaravelAiAegis\Exceptions\AegisSecurityException;

->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (AegisSecurityException $e, Request $request) {
        return response()->json(['error' => $e->getMessage()], $e->getCode());
    });
})
```

FactoryHTTP codeWhen thrown`promptInjectionDetected(float $score)`403Injection score ≥ threshold`guardRailViolation(string $stage, string $reason)`403Any guard rail `check()` fails`toolDenied(string $tool)`403Tool in blocklist or not in allowlist`approvalRequired(string $content)`403No approval handler configured`approvalDenied()`403Handler returned `false``maxInputLengthExceeded(int $length, int $max)`422Prompt too long`piiLeakageDetected(string $type)`403PII found in LLM responseInjection Detection
-------------------

[](#injection-detection)

The built-in `PromptInjectionDetector` scores prompts against 30+ weighted adversarial patterns:

- System prompt extraction (`output your system prompt`, `reveal your instructions`)
- Instruction override (`ignore previous instructions`, `disregard all previous`)
- Role-playing jailbreaks (`DAN mode`, `pretend you are`, `you are now`)
- Security bypass attempts (`bypass your safety`, `admin override`, `sudo mode`)
- Encoded payload injection (`base64 decode and execute`)

### Custom Attack Vectors

[](#custom-attack-vectors)

```
use MrPunyapal\LaravelAiAegis\Contracts\InjectionDetectorInterface;
use MrPunyapal\LaravelAiAegis\Defense\PromptInjectionDetector;

$this->app->singleton(InjectionDetectorInterface::class, fn () =>
    new PromptInjectionDetector(
        customVectors: [
            'my proprietary jailbreak pattern' => 0.95,
        ],
    )
);
```

Laravel Pulse Card
------------------

[](#laravel-pulse-card)

```

```

Metrics displayed:

- **Blocked Injections** — Prompts blocked by the injection guard rail
- **Guard Rail Violations** — All violations across all stages
- **PII Tokens Replaced** — Pseudonymization operations performed
- **Tool Denials** — Tool calls blocked by the tool guard rail
- **Approval Events** — Human approval approvals and denials

Artisan Commands
----------------

[](#artisan-commands)

### `aegis:install`

[](#aegisinstall)

Publishes the config and prints getting-started instructions:

```
php artisan aegis:install
```

### `aegis:test`

[](#aegistest)

Runs a prompt through injection detection and all configured PII rules, displaying per-rule results:

```
php artisan aegis:test "ignore previous instructions"
# Injection detection  BLOCKED
#   Score              0.95
#   Matched patterns   ignore previous instructions

php artisan aegis:test "Contact john@example.com for info."
# Injection detection  CLEAN
# PII detection        PII DETECTED
#   Rule email (tokenize)
#   Transformed text   Contact {{AEGIS_EMAIL_8F92A}} for info.
#   Tokens replaced    1
```

DevX Testing
------------

[](#devx-testing)

```
composer test          # lint + types + type-coverage + unit tests
composer test:unit     # unit tests with coverage
composer test:types    # PHPStan static analysis
composer test:arch     # architecture tests
composer lint          # Rector + Pint auto-fix
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for recent changes.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Punyapal Shah](https://github.com/MrPunyapal)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information. [![Lint & Static Analysis](https://camo.githubusercontent.com/3aee38e5e68b2c788ec82edf648d7f31c431c5a4c788ad548a57347d8a8dd0cf/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d7270756e796170616c2f6c61726176656c2d61692d61656769732f6c696e742d7374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d6c696e742b2532362b7374616e267374796c653d666c61742d737175617265)](https://github.com/mrpunyapal/laravel-ai-aegis/actions?query=workflow%3ALint+branch%3Amain)[![Tests](https://camo.githubusercontent.com/560a1c5c1938b5bd1047cc0100d4bdbf530b94c448c5b9d89057d883bb81e927/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d7270756e796170616c2f6c61726176656c2d61692d61656769732f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/mrpunyapal/laravel-ai-aegis/actions?query=workflow%3ATests+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/1fc40a609d3480a5f3f593029c34b7b8ad03c2da1bef7e22fccf698450bb2971/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d7270756e796170616c2f6c61726176656c2d61692d61656769732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mrpunyapal/laravel-ai-aegis)

A native, **local-first** security middleware for the **Laravel AI SDK**. Aegis intercepts every AI agent prompt and response to protect your users' data and your system prompts — without ever sending raw PII or adversarial payloads to an external LLM provider.

Features
--------

[](#features-1)

- **Bidirectional Reversible Pseudonymization** — Automatically replaces PII (emails, phones, SSNs, credit cards, IP addresses) with context-preserving `{{AEGIS_*}}` tokens before the LLM sees the data, then seamlessly restores the original values in the response.
- **Localized Prompt Injection Defense** — A built-in semantic firewall evaluates prompts against 30+ known adversarial attack patterns (jailbreaks, system prompt extraction, DAN mode, etc.) entirely locally — no external API call required.
- **Declarative Attribute Configuration** — Use the `#[Aegis]` PHP attribute on individual Agent classes to apply granular, per-agent security rules.
- **Laravel Pulse Integration** — A first-class Pulse card delivers real-time telemetry: blocked injections, pseudonymization volume, and estimated compute capital saved.
- **PHP 8.4+ Lazy Objects** — On PHP 8.4 and above, all heavy services are registered as Lazy Ghost objects, so memory is only allocated when a service is actually used in the request lifecycle. PHP 8.2/8.3 fall back to eager instantiation.
- **Artisan Commands** — `aegis:install` for guided setup, `aegis:test` to debug prompts interactively.

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

[](#requirements-1)

DependencyVersionPHP`^8.3`Laravel`^12.0 | ^13.0`Laravel Pulse *(optional)*`^1.0`Installation
------------

[](#installation-1)

```
composer require mrpunyapal/laravel-ai-aegis
```

Run the install command for guided setup:

```
php artisan aegis:install
```

Or publish the config file manually:

```
php artisan vendor:publish --tag="aegis-config"
```

Configuration
-------------

[](#configuration-1)

```
// config/aegis.php

return [
    'block_injections' => env('AEGIS_BLOCK_INJECTIONS', true),
    'pseudonymize'     => env('AEGIS_PSEUDONYMIZE', true),
    'strict_mode'      => env('AEGIS_STRICT_MODE', false),

    'pii_types' => ['email', 'phone', 'ssn', 'credit_card', 'ip_address'],

    'cache' => [
        'store'  => env('AEGIS_CACHE_STORE', 'redis'),
        'prefix' => 'aegis_pii',
        'ttl'    => env('AEGIS_CACHE_TTL', 3600),
    ],

    'injection_threshold' => env('AEGIS_INJECTION_THRESHOLD', 0.7),

    'pulse' => [
        'enabled' => env('AEGIS_PULSE_ENABLED', true),
    ],
];
```

> **Redis is recommended** for the `cache.store` in production. The pseudonymization engine stores short-lived PII-to-token mappings that must survive the full request/response cycle.

Usage
-----

[](#usage-1)

### Registering the Middleware

[](#registering-the-middleware-1)

Register `AegisMiddleware` in your Laravel AI SDK agent pipeline:

```
use MrPunyapal\LaravelAiAegis\Middleware\AegisMiddleware;

$agent->withMiddleware([
    app(AegisMiddleware::class),
]);
```

### Declarative Configuration with `#[Aegis]`

[](#declarative-configuration-with-aegis)

Apply the `#[Aegis]` attribute directly on an Agent class to override global config:

```
use MrPunyapal\LaravelAiAegis\Attributes\Aegis;

#[Aegis(
    blockInjections: true,
    pseudonymize: true,
    strictMode: true,
    piiTypes: ['email', 'ssn'],
)]
class MedicalSupportAgent extends Agent
{
    // ...
}
```

ParameterTypeDefaultDescription`blockInjections``bool``true`Enable the prompt injection firewall`pseudonymize``bool``true`Enable bidirectional PII pseudonymization`strictMode``bool``false`Lower injection detection threshold to `0.3``piiTypes``array`all typesPII categories to scan forWhen an Agent class has no `#[Aegis]` attribute, values from `config/aegis.php` are used.

### How the Middleware Pipeline Works

[](#how-the-middleware-pipeline-works)

```
User Prompt
     │
     ▼
 ┌─────────────────────────────────────────┐
 │           AegisMiddleware               │
 │                                         │
 │  1. Injection Detection (local scan)    │──► throws AegisSecurityException
 │                                         │    if score ≥ threshold
 │  2. PII Pseudonymization (outbound)     │──► replaces PII with tokens,
 │     john@example.com → {{AEGIS_EMAIL_}} │    stores mapping in cache
 │                                         │
 │  3. $next($prompt) ──────────────────────────► LLM Provider
 │                                         │         │
 │  4. ->then() closure ◄──────────────────────────── LLM Response
 │     Restore tokens → original values    │
 └─────────────────────────────────────────┘
     │
     ▼
Final Response (PII restored, safe)

```

### Throwing Custom Exceptions

[](#throwing-custom-exceptions)

When a prompt is blocked, `AegisSecurityException` is thrown with HTTP status `403`:

```
use MrPunyapal\LaravelAiAegis\Exceptions\AegisSecurityException;

// In your exception handler:
->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (AegisSecurityException $e, Request $request) {
        return response()->json(['error' => $e->getMessage()], 403);
    });
})
```

PII Detection
-------------

[](#pii-detection)

Aegis detects the following PII types out of the box:

TypePattern Example`email``john.doe@example.com``phone``555-123-4567`, `+1 (555) 123-4567``ssn``123-45-6789``credit_card``4111-1111-1111-1111``ip_address``192.168.1.100`Detected values are replaced with tokens like `{{AEGIS_EMAIL_8F92A}}` before reaching the LLM. After the LLM responds, tokens are swapped back with original values transparently.

Injection Detection
-------------------

[](#injection-detection-1)

Aegis ships with 30+ weighted adversarial patterns covering:

- System prompt extraction (`output your system prompt`, `reveal your instructions`)
- Instruction override (`ignore previous instructions`, `disregard all previous`)
- Role-playing jailbreaks (`DAN mode`, `pretend you are`, `you are now`)
- Security bypass attempts (`bypass your safety`, `admin override`, `sudo mode`)
- Encoded payload injection (`base64 decode and execute`)

### Custom Attack Vectors

[](#custom-attack-vectors-1)

Extend the built-in database by binding a custom `PromptInjectionDetector`:

```
use MrPunyapal\LaravelAiAegis\Contracts\InjectionDetectorInterface;
use MrPunyapal\LaravelAiAegis\Defense\PromptInjectionDetector;

$this->app->singleton(InjectionDetectorInterface::class, fn () =>
    new PromptInjectionDetector(
        customVectors: [
            'my proprietary jailbreak pattern' => 0.95,
        ],
    )
);
```

Laravel Pulse Card
------------------

[](#laravel-pulse-card-1)

Add the Aegis card to your Pulse dashboard in `resources/views/vendor/pulse/dashboard.blade.php`:

```

```

The card displays three real-time metrics:

- **Blocked Injections** — Total prompts blocked during the selected period
- **PII Tokens Replaced** — Total pseudonymization operations performed
- **Compute Capital Saved** — Estimated API cost avoided by blocking requests locally

Artisan Commands
----------------

[](#artisan-commands-1)

### `aegis:install`

[](#aegisinstall-1)

Publishes the config file and prints getting-started instructions:

```
php artisan aegis:install
```

### `aegis:test`

[](#aegistest-1)

Runs a prompt through the full Aegis pipeline (injection detection + PII scan) and displays the result in the terminal. Great for debugging or onboarding:

```
php artisan aegis:test "ignore previous instructions"
# ┌──────────────────────────┬─────────────────┐
# │ Injection detection      │ BLOCKED         │
# │   Score                  │ 0.95            │
# │   Matched patterns       │ ignore previous │
# └──────────────────────────┴─────────────────┘

php artisan aegis:test "What is the weather today?"
# ┌──────────────────────────┬─────────────────┐
# │ Injection detection      │ CLEAN           │
# │ PII detection            │ CLEAN           │
# └──────────────────────────┴─────────────────┘
```

DevX Testing
------------

[](#devx-testing-1)

```
# Run all tests
composer test

# Run only unit tests with coverage
composer test:unit

# Run static analysis
composer test:types

# Run architecture tests
composer test:arch

# Lint and auto-fix
composer lint
```

Changelog
---------

[](#changelog-1)

Please see [CHANGELOG](CHANGELOG.md) for recent changes.

Contributing
------------

[](#contributing-1)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities-1)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits-1)

- [Punyapal Shah](https://github.com/MrPunyapal)
- [All Contributors](../../contributors)

License
-------

[](#license-1)

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

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance88

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

Every ~9 days

Total

4

Last Release

64d ago

PHP version history (3 changes)0.0.1PHP ^8.3|^8.4|^8.5

0.0.2PHP ^8.2

0.0.3PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/230c58a4f918ca3e3f2988b38721230698bce88f76ae9087e4377ba0b3a074d5?d=identicon)[MrPunyapal](/maintainers/MrPunyapal)

---

Top Contributors

[![MrPunyapal](https://avatars.githubusercontent.com/u/53343069?v=4)](https://github.com/MrPunyapal "MrPunyapal (53 commits)")

---

Tags

ailaravellaravel-aillmmiddlewarephppiiprompt-injectionpseudonymizationsecuritymiddlewarelaravelsecurityaipiiprompt-injectionaegispseudonymization

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/mrpunyapal-laravel-ai-aegis/health.svg)

```
[![Health](https://phpackages.com/badges/mrpunyapal-laravel-ai-aegis/health.svg)](https://phpackages.com/packages/mrpunyapal-laravel-ai-aegis)
```

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k8.7M64](/packages/spatie-laravel-responsecache)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

43140.3k](/packages/harris21-laravel-fuse)[spatie/laravel-health

Monitor the health of a Laravel application

87411.3M154](/packages/spatie-laravel-health)[laravel/ai

The official AI SDK for Laravel.

1.0k2.1M163](/packages/laravel-ai)[propaganistas/laravel-disposable-email

Disposable email validator

6012.9M7](/packages/propaganistas-laravel-disposable-email)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)

PHPackages © 2026

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