MrPunyapal/laravel-ai-aegis
GitHub: MrPunyapal/laravel-ai-aegis
为 Laravel AI SDK 提供本地优先的安全中间件,通过 Prompt 注入防御和双向 PII 假名化保护 AI 应用数据安全。
Stars: 2 | Forks: 0
# Laravel AI Aegis
[](https://packagist.org/packages/mrpunyapal/laravel-ai-aegis)
[](https://github.com/mrpunyapal/laravel-ai-aegis/actions?query=workflow%3ALint+branch%3Amain)
[](https://github.com/mrpunyapal/laravel-ai-aegis/actions?query=workflow%3ATests+branch%3Amain)
[](https://packagist.org/packages/mrpunyapal/laravel-ai-aegis)
一款原生的、**本地优先** 的 **Laravel AI SDK** 安全中间件。Aegis 拦截每一个 AI agent 的 prompt 和响应,以保护用户数据和您的系统 prompt —— 无需将原始 PII 或对抗性 payload 发送给外部 LLM 提供商。
## 功能特性
- **双向可逆假名化** — 在 LLM 接触数据之前,自动将 PII(电子邮件、电话、SSN、信用卡、IP 地址)替换为保留上下文的 `{{AEGIS_*}}` token,随后在响应中无缝还原原始值。
- **本地化 Prompt 注入防御** — 内置语义防火墙完全在本地针对 30 多种已知对抗性攻击模式(越狱、系统 prompt 提取、DAN 模式等)评估 prompt —— 无需外部 API 调用。
- **声明式属性配置** — 在单个 Agent 类上使用 `#[Aegis]` PHP 属性,以应用精细的、针对每个 agent 的安全规则。
- **Laravel Pulse 集成** — 一流的 Pulse 卡片提供实时遥测数据:拦截的注入、假名化处理量以及预估节省的计算成本。
- **PHP 8.4+ Lazy Objects** — 在 PHP 8.4 及更高版本上,所有重型服务都注册为 Lazy Ghost 对象,因此只有在请求生命周期中实际使用服务时才会分配内存。PHP 8.2/8.3 会回退到即时实例化。
- **Artisan Commands** — `aegis:install` 用于引导式设置,`aegis:test` 用于交互式调试 prompt。
## 环境要求
| Dependency | Version |
|---||
| PHP | `^8.3` |
| Laravel | `^12.0 \| ^13.0` |
| Laravel Pulse *(optional)* | `^1.0` |
## 安装
```
composer require mrpunyapal/laravel-ai-aegis
```
运行安装命令进行引导式设置:
```
php artisan aegis:install
```
或手动发布配置文件:
```
php artisan vendor:publish --tag="aegis-config"
```
## 配置
```
// 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),
],
];
```
## 使用方法
### 注册中间件
在您的 Laravel AI SDK agent pipeline 中注册 `AegisMiddleware`:
```
use MrPunyapal\LaravelAiAegis\Middleware\AegisMiddleware;
$agent->withMiddleware([
app(AegisMiddleware::class),
]);
```
### 使用 `#[Aegis]` 进行声明式配置
直接在 Agent 类上应用 `#[Aegis]` 属性以覆盖全局配置:
```
use MrPunyapal\LaravelAiAegis\Attributes\Aegis;
#[Aegis(
blockInjections: true,
pseudonymize: true,
strictMode: true,
piiTypes: ['email', 'ssn'],
)]
class MedicalSupportAgent extends Agent
{
// ...
}
```
| Parameter | Type | Default | Description |
|---|---|---|---|
| `blockInjections` | `bool` | `true` | 启用 prompt 注入防火墙 |
| `pseudonymize` | `bool` | `true` | 启用双向 PII 假名化 |
| `strictMode` | `bool` | `false` | 将注入检测阈值降低至 `0.3` |
| `piiTypes` | `array` | all types | 要扫描的 PII 类别 |
当 Agent 类没有 `#[Aegis]` 属性时,将使用 `config/aegis.php` 中的值。
### 中间件管道如何工作
```
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)
```
### 抛出自定义异常
当 prompt 被拦截时,会抛出带有 HTTP 状态码 `403` 的 `AegisSecurityException`:
```
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 检测
Aegis 开箱即支持检测以下 PII 类型:
| Type | Pattern 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` |
检测到的值会在到达 LLM 之前被替换为类似 `{{AEGIS_EMAIL_8F92A}}` 的 token。在 LLM 响应后,token 会透明地交换回原始值。
## 注入检测
Aegis 内置 30 多种加权对抗模式,涵盖:
- 系统 prompt 提取 (`output your system prompt`, `reveal your instructions`)
- 指令覆盖 (`ignore previous instructions`, `disregard all previous`)
- 角色扮演越狱 (`DAN mode`, `pretend you are`, `you are now`)
- 安全绕过尝试 (`bypass your safety`, `admin override`, `sudo mode`)
- 编码 payload 注入 (`base64 decode and execute`)
### 自定义攻击向量
通过绑定自定义 `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 卡片
将 Aegis 卡片添加到 `resources/views/vendor/pulse/dashboard.blade.php` 的 Pulse 仪表板中:
```
```
该卡片显示三个实时指标:
- **Blocked Injections** — 所选期间内拦截的 prompt 总数
- **PII Tokens Replaced** — 执行的假名化操作总数
- **Compute Capital Saved** — 通过在本地拦截请求而避免的预估 API 成本
## Artisan Commands
### `aegis:install`
发布配置文件并打印入门说明:
```
php artisan aegis:install
```
### `aegis:test`
通过完整的 Aegis 管道(注入检测 + PII 扫描)运行 prompt,并在终端中显示结果。非常适合调试或入门:
```
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 测试
```
# 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.md) 了解最近的更改。
## 安全漏洞
请查看 [我们的安全策略](../../security/policy) 了解如何报告安全漏洞。
## 贡献者
- [Punyapal Shah](https://github.com/MrPunyapal)
- [All Contributors](../../contributors)
## 许可证
MIT 许可证 (MIT)。请查看 [License File](LICENSE.md) 了解更多信息。
标签:AI 安全, DLL 劫持, ffuf, Laravel, Laravel Pulse, LLM 防护, OpenVAS, PHP, PII 脱敏, Prompt 注入防御, 中间件, 企业级安全, 大语言模型, 对抗攻击防御, 搜索引擎查询, 敏感信息过滤, 数据合规, 数据隐私, 本地优先, 网络安全, 身份匿名化, 防火墙, 隐私保护