Download the PHP package mrpunyapal/laravel-ai-aegis without Composer
On this page you can find all versions of the php package mrpunyapal/laravel-ai-aegis. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download mrpunyapal/laravel-ai-aegis
More information about mrpunyapal/laravel-ai-aegis
Files in mrpunyapal/laravel-ai-aegis
Package laravel-ai-aegis
Short Description A native, local-first security middleware for the Laravel AI SDK with bidirectional pseudonymization, prompt injection defense, and real-time Pulse telemetry.
License MIT
Homepage https://github.com/mrpunyapal/laravel-ai-aegis
Informations about the package laravel-ai-aegis
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
- 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 withemail: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:installfor guided setup,aegis:testfor interactive per-rule prompt diagnostics.
Requirements
| Dependency | Version |
|---|---|
| PHP | ^8.3 |
| Laravel | ^12.0 \| ^13.0 |
| Laravel Pulse (optional) | ^1.0 |
Installation
Run the install command for guided setup:
Or publish the config file manually:
Configuration
Redis is recommended for
cache.storein production. Tokenized PII mappings must survive the full request/response cycle.
Usage
Registering the Middleware
How the Pipeline Works
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
| Rule | Action | Behaviour |
|---|---|---|
email |
tokenize | Reversible token — default when no action given |
email:tokenize |
tokenize | Explicit tokenize |
email:replace |
replace | Static [REDACTED:EMAIL] placeholder |
email:replace,*** |
replace | Custom static text |
email:mask |
mask | Full mask with * |
email:mask,3 |
mask | Keep 3 chars at start, mask rest |
email:mask,3,5 |
mask | Keep 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
Built-in PII Types
| Type | Detects |
|---|---|
email |
[email protected] |
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
Implement PiiTypeInterface and register the class in config:
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.
| Parameter | Type | Default | Description |
|---|---|---|---|
piiEnabled |
bool |
true |
Enable PII transformation |
piiRules |
array |
[] → config fallback |
DSL strings or structured arrays |
blockInjections |
bool |
true |
Enable injection detection |
strictMode |
bool |
false |
Lower injection threshold to 0.3 |
injectionThreshold |
?float |
null → config fallback |
Override threshold for this agent |
inputBlockedPhrases |
array |
[] → config fallback |
Phrases that block the request |
maxInputLength |
?int |
null → config fallback |
Max prompt character count |
blockOutputPii |
bool |
true |
Scan LLM response for PII leakage |
outputBlockedPhrases |
array |
[] → config fallback |
Phrases blocked in responses |
allowedTools |
array |
[] = all allowed |
Allowlist 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
All guard rails are registered automatically by the service provider. Each implements GuardRailInterface and is scoped to a GuardRailStage.
Built-in Guard Rails
| Guard Rail | Stage | What 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
Register it in a service provider:
Human Approval Handler
Exception Handling
All security violations throw AegisSecurityException (extends RuntimeException):
| Factory | HTTP code | When thrown |
|---|---|---|
promptInjectionDetected(float $score) |
403 | Injection score ≥ threshold |
guardRailViolation(string $stage, string $reason) |
403 | Any guard rail check() fails |
toolDenied(string $tool) |
403 | Tool in blocklist or not in allowlist |
approvalRequired(string $content) |
403 | No approval handler configured |
approvalDenied() |
403 | Handler returned false |
maxInputLengthExceeded(int $length, int $max) |
422 | Prompt too long |
piiLeakageDetected(string $type) |
403 | PII found in LLM response |
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
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
aegis:install
Publishes the config and prints getting-started instructions:
aegis:test
Runs a prompt through injection detection and all configured PII rules, displaying per-rule results:
DevX Testing
Changelog
Please see CHANGELOG for recent changes.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
- Punyapal Shah
- All Contributors
License
The MIT License (MIT). Please see License File for more information.
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
- 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:installfor guided setup,aegis:testto debug prompts interactively.
Requirements
| Dependency | Version |
|---|---|
| PHP | ^8.3 |
| Laravel | ^12.0 \| ^13.0 |
| Laravel Pulse (optional) | ^1.0 |
Installation
Run the install command for guided setup:
Or publish the config file manually:
Configuration
Redis is recommended for the
cache.storein production. The pseudonymization engine stores short-lived PII-to-token mappings that must survive the full request/response cycle.
Usage
Registering the Middleware
Register AegisMiddleware in your Laravel AI SDK agent pipeline:
Declarative Configuration with #[Aegis]
Apply the #[Aegis] attribute directly on an Agent class to override global config:
| Parameter | Type | Default | Description |
|---|---|---|---|
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 types | PII categories to scan for |
When an Agent class has no #[Aegis] attribute, values from config/aegis.php are used.
How the Middleware Pipeline Works
Throwing Custom Exceptions
When a prompt is blocked, AegisSecurityException is thrown with HTTP status 403:
PII Detection
Aegis detects the following PII types out of the box:
| Type | Pattern Example |
|---|---|
email |
[email protected] |
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
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
Extend the built-in database by binding a custom PromptInjectionDetector:
Laravel Pulse Card
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
aegis:install
Publishes the config file and prints getting-started instructions:
aegis:test
Runs a prompt through the full Aegis pipeline (injection detection + PII scan) and displays the result in the terminal. Great for debugging or onboarding:
DevX Testing
Changelog
Please see CHANGELOG for recent changes.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
- Punyapal Shah
- All Contributors
License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-ai-aegis with dependencies
illuminate/cache Version ^12.0|^13.0
illuminate/contracts Version ^12.0|^13.0
illuminate/support Version ^12.0|^13.0
spatie/laravel-package-tools Version ^1.16