Download the PHP package jayanta/laravel-ai-guard without Composer
On this page you can find all versions of the php package jayanta/laravel-ai-guard. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download jayanta/laravel-ai-guard
More information about jayanta/laravel-ai-guard
Files in jayanta/laravel-ai-guard
Package laravel-ai-guard
Short Description Protect your Laravel app from AI scrapers, LLM crawlers, and prompt injection attacks
License MIT
Homepage https://github.com/jay123anta/laravel-ai-guard
Informations about the package laravel-ai-guard
Laravel AI Guard
Protect your Laravel app from AI scrapers, LLM crawlers, and prompt injection attacks.
What It Does
Laravel AI Guard is a middleware-based security package with a multi-layer detection pipeline:
- 364 bot signatures across 7 categories (AI training, AI assistants, SEO tools, scrapers, bad bots, data harvesters, search engines) with per-category confidence scoring
- 30 prompt injection patterns across 7 attack categories, with recursive nested input scanning
- Honeypot trap routes — hidden paths that real users never visit, instant 100 confidence on hit
- PII leak detection — scans outgoing responses for emails, credit cards, SSNs, API keys, JWTs, AWS keys, private keys, and database URLs
- robots.txt enforcement — boosts confidence when bots violate your Disallow rules
- Request fingerprinting — detects bots faking browser user-agents by analyzing header patterns
- Optional ML detection — pluggable ML providers (Lakera, HuggingFace, Pangea, LLM Guard, Ollama, or custom) for borderline cases, zero dependencies
All detections are logged to your database with a built-in dashboard, 10 REST API endpoints, an Artisan command, and Slack alerts.
Requirements
- PHP 8.1 or higher
- Laravel 10.x, 11.x, or 12.x
- A database supported by Laravel (MySQL, PostgreSQL, SQLite)
No additional PHP extensions or external services required.
Installation
Publish and run migrations:
Publish the config file:
Quick Start
Register the middleware globally so every request is scanned.
Laravel 11 / 12 — bootstrap/app.php:
Laravel 10 — app/Http/Kernel.php:
That's it. AI Guard is now monitoring all incoming requests in log_only mode.
Protecting specific routes only
The package registers an ai-guard middleware alias, so you can guard individual routes or groups instead of every request:
Recommended First Steps
- Start in
log_onlymode (default) — detects and logs everything, blocks nothing -
Remove auth from dashboard temporarily to view it without login:
- Visit the dashboard at
http://your-app.com/ai-guardto see detections -
Whitelist your tools — add Postman, your monitoring service, and internal IPs:
- Review detections for a few days before switching to
blockorrate_limitmode - Re-enable auth on dashboard and API before going to production
Detection Pipeline
Every request passes through this pipeline:
Configuration
After publishing, the config file is at config/ai-guard.php.
Mode
- log_only — Detect and log threats, never block. Start here.
- block — Return 403 for threats above the confidence threshold.
- rate_limit — Apply rate limiting to detected threats via cache.
Confidence Threshold
Bot Signatures (364 bots, 7 categories)
| Category | Count | Default Confidence | Enabled |
|---|---|---|---|
ai_training |
63 | 95 | Yes |
ai_assistants |
44 | 90 | Yes |
seo_tools |
58 | 60 | Yes |
scrapers |
58 | 85 | Yes |
bad_bots |
58 | 95 | Yes |
data_harvesters |
46 | 80 | Yes |
search_engines |
37 | 30 | No (disabled) |
You can also define custom AI crawler user-agents in the ai_crawlers config section:
Prompt Injection
Honeypot Traps
Default trap paths include /admin-backup, /wp-admin, /.env, /.git/config, /api/v1/users.json, /backup.sql, /phpinfo.php, and more. Any request to a trap path scores 100 confidence instantly.
Note: Honeypot paths are checked against the request path exactly. If your app has a real route at any of these paths, override
trap_pathswith your own array to avoid conflicts.
Response Scanning (PII Leak Detection)
Scans outgoing HTML, JSON, and text responses for leaked PII before they leave your server.
robots.txt Enforcement
Parses your public/robots.txt and boosts confidence by 30 when a detected bot is crawling a disallowed path.
Request Fingerprinting
Analyzes 5 signals: missing browser headers, alphabetical header order, anomalous Accept header, no keep-alive, no navigation context. Catches bots that fake browser user-agent strings.
ML Detection (Optional)
ML runs only when regex flags something borderline (score between 40-85). 99% of requests never touch ML.
| Driver | Provider | Cost | Latency | Data Privacy |
|---|---|---|---|---|
lakera |
Lakera Guard | 10K free/mo | 50-150ms | SaaS |
huggingface |
Meta Prompt Guard | ~1K free/day | 200-500ms | SaaS |
pangea |
Pangea AI Guard | Free community | 100-300ms | SaaS |
llm_guard |
LLM Guard | Free (self-hosted) | 100-500ms | Self-hosted |
ollama |
Ollama | Free | 50-200ms | Self-hosted |
custom |
Your own endpoint | Varies | Varies | You control |
To enable, add your API key to .env and set enabled to true:
Rate Limiting
Alerts
Dashboard & API Authentication
For local development without authentication:
Security note: Always re-enable authentication before deploying to production. The dashboard and API expose IP addresses, request URLs, and threat data.
False Positives
Important: If you test your API with tools like Postman, Insomnia, or curl, add them to the whitelist. Otherwise your own test requests will be logged as threats.
Events
Every detection dispatches a JayAnta\AiGuard\Events\ThreatDetected event, so you can plug in your own notifications, IP banning, or metrics:
Listener exceptions are caught and logged — a broken listener never breaks request handling.
Dashboard
After installation, visit your dashboard at:
The dashboard shows:
- Total threats detected in the last 24 hours
- Breakdown by threat type (AI crawlers, prompt injections, data harvesters, honeypot traps, bad bots, PII leaks)
- Count of blocked and rate-limited requests
- Top threat sources and IP addresses
- Recent threat log with confidence scores and actions taken
- Auto-refreshes every 30 seconds
REST API
All endpoints are prefixed with your configured prefix (default: /ai-guard).
| Method | Endpoint | Description |
|---|---|---|
| GET | /ai-guard/api/threats |
List threats (paginated, filterable) |
| GET | /ai-guard/api/threats/{id} |
Get single threat details |
| GET | /ai-guard/api/stats |
Threat summary counts |
| GET | /ai-guard/api/top-sources |
Top threat sources ranked |
| GET | /ai-guard/api/top-ips |
Top threat IPs ranked |
| GET | /ai-guard/api/timeline |
Hourly threat timeline |
| GET | /ai-guard/api/confidence-breakdown |
High/medium/low breakdown |
| GET | /ai-guard/api/detector-info |
Detector config and pattern counts |
| POST | /ai-guard/api/threats/{id}/false-positive |
Mark threat as false positive |
| DELETE | /ai-guard/api/flush |
Delete threat logs (requires ?confirm=yes) |
Query Parameters
GET /ai-guard/api/threats
| Parameter | Default | Description |
|---|---|---|
| hours | 24 | Lookback window (max 8760) |
| limit | 50 | Results per page (max 200) |
| threat_type | — | Filter: ai_crawler, prompt_injection, data_harvester, honeypot_trap, pii_leak, bad_bot, scraper, seo_bot |
| action_taken | — | Filter: logged, blocked, rate_limited |
Artisan Commands
Threat Statistics
Generate robots.txt
Generate a robots.txt that blocks AI crawlers and scrapers using the 364 bot signature database:
Default: blocks AI training bots + AI assistants (107 bots). Explicitly allows Googlebot and Bingbot.
Tip: Even without installing the full middleware, this command gives you a production-ready robots.txt that stays current with the latest AI bots.
Detection Details
Bot Signatures (364 bots in 7 categories)
AI Training Bots (63 bots, confidence: 95) — GPTBot, ChatGPT-User, ClaudeBot, CCBot, Bytespider, Diffbot, DeepSeekBot, TikTokSpider, Google-CloudVertexBot, cohere-training-data-crawler, and more.
AI Assistants (44 bots, confidence: 90) — PerplexityBot, YouBot, PhindBot, KagiBot, Claude-SearchBot, Gemini-Deep-Research, DuckAssistBot, MistralAI-User, and more.
SEO Tools (58 bots, confidence: 60) — AhrefsBot, SemrushBot, MJ12bot, DotBot, DataForSeoBot, Seobility, XoviBot, BrightEdge Crawler, and more.
Malicious Bots (59 bots, confidence: 95) — Nikto, sqlmap, Nessus, Nmap, Masscan, Acunetix, nuclei, Shodan, CensysInspect, and more.
Scrapers (58 bots, confidence: 85) — HeadlessChrome, PhantomJS, Puppeteer, Playwright, Selenium, ZenRows, ScrapingBee, ScraperAPI, Oxylabs, Zyte, Apify, and more.
Data Harvesters (46 bots, confidence: 80) — curl, python-requests, Go-http-client, Wget, okhttp, PostmanRuntime, fasthttp, RestSharp, and more.
Search Engines (37 bots, confidence: 30, disabled by default) — Googlebot, Bingbot, YandexBot, Baiduspider, DuckDuckBot, and more.
Prompt Injection Patterns
30 patterns across 7 categories:
- Instruction Override — "ignore previous instructions", "disregard your rules", "forget everything"
- Role Manipulation — "you are now", "act as if", "pretend to be", "from now on you are"
- System Prompt Attacks — "reveal your system prompt", "show your instructions", "repeat everything above"
- DAN / Jailbreak — "DAN", "do anything now", "jailbreak", "bypass safety"
- Privilege Escalation — "developer mode", "admin mode", "sudo override", "debug mode"
- Data Extraction — "dump all data", "output all records", "bypass validation"
- Token Manipulation —
<|im_start|>,<|im_end|>,[INST],<<SYS>>
PII Leak Detection (10 patterns)
| Pattern | Severity | Default |
|---|---|---|
| Email addresses | 70 | Enabled |
| Phone numbers | 75 | Enabled |
| Credit card numbers | 95 | Enabled |
| Social Security numbers | 95 | Enabled |
| API keys / tokens | 90 | Enabled |
| AWS access keys | 95 | Enabled |
| Private keys (RSA/EC/DSA) | 95 | Enabled |
| JWT tokens | 85 | Enabled |
| Internal IP addresses | 50 | Disabled |
| Database connection strings | 95 | Enabled |
Honeypot Trap Routes
Hidden paths that real users never visit. Any hit scores 100 confidence instantly:
/admin-backup, /wp-admin, /wp-login.php, /.env, /.git/config, /.aws/credentials, /phpinfo.php, /api/v1/users.json, /backup.sql, /database.sql, /users.csv, and more.
Three Modes Explained
| Mode | Behavior | Use Case |
|---|---|---|
log_only |
Detect and log. Never block any request. | Starting out. Understanding your traffic before enforcing. |
block |
Return 403 JSON for threats above the confidence threshold. | Production enforcement. Actively blocking AI scrapers. |
rate_limit |
Apply rate limiting via cache. Return 429 when exceeded. | Softer enforcement. Allow some access but limit volume. |
Switch modes at any time by changing mode in your config. No code changes needed.
Facade Usage
Integration with laravel-natural-query
If you also use jayanta/laravel-natural-query, ai-guard provides extra protection automatically. No configuration needed — just install both packages:
laravel-natural-query auto-detects ai-guard and calls AiGuard::detectText() to scan user queries for prompt injection before they reach the LLM. This adds ai-guard's 30 injection patterns on top of natural-query's built-in InputGuard.
You can also call detectText() directly in your own code:
Note: Neither package requires the other. They work independently. The integration is optional and automatic when both are installed.
Troubleshooting
Dashboard returns 403 or redirects to /login
The dashboard requires authentication by default. For local development:
My own curl/Postman requests are being logged as threats
Add your testing tools to the whitelist:
Honeypot conflicts with my real routes
If your app has routes like /admin or /api/v1/users.json, override the trap paths:
Everything is being blocked (403)
Check that mode is set to log_only (not block) and that confidence_threshold is appropriate:
The table ai_threat_logs doesn't exist
Run the migration:
Config changes aren't taking effect
Clear the config cache:
SEO bots (AhrefsBot, SemrushBot) are being logged
SEO tools score 60 confidence by default. If you use these tools and don't want them logged, either:
- Add them to your whitelist:
'whitelist_user_agents' => ['AhrefsBot', 'SemrushBot'] - Or disable the
seo_toolscategory:'disabled_categories' => ['search_engines', 'seo_tools']
The package is slowing down my app
AI Guard adds ~1ms per request in regex-only mode. If you notice slowness:
- Disable response scanning (it scans every outgoing response body)
- Disable fingerprinting (it analyzes headers on every request)
- Ensure ML detection is disabled unless you need it
- Check that your
ai_threat_logstable has indexes (they're created by the migration)
How It Compares
| Laravel AI Guard | crawler-detect | spatie/laravel-honeypot | Cloudflare Bot Management | |
|---|---|---|---|---|
| AI/LLM crawler signatures | ✅ 364 bots, 7 categories | ⚠️ Generic crawler list | ❌ | ✅ |
| Prompt injection detection | ✅ 30 patterns + optional ML | ❌ | ❌ | ❌ |
| PII leak detection (outbound) | ✅ 10 patterns | ❌ | ❌ | ❌ |
| Honeypot traps | ✅ Trap URLs | ❌ | ✅ Form fields | ❌ |
| Threat dashboard + API | ✅ Built-in | ❌ | ❌ | ✅ SaaS |
| Block / rate-limit modes | ✅ | ❌ Detection only | ✅ | ✅ |
| Runs inside your app | ✅ | ✅ | ✅ | ❌ Proxy/DNS |
| Cost | Free | Free | Free | Paid |
crawler-detect answers "is this a bot?"; spatie/laravel-honeypot stops form spam; Cloudflare needs DNS-level adoption. AI Guard is the only one purpose-built for the AI-scraper and LLM-security threat model, entirely inside Laravel.
Testing
The test suite includes 60 full-cycle tests with 508 assertions:
- Feature tests (23) — Complete request -> middleware -> detection -> database logging -> events -> model queries -> stats pipeline
- Unit tests (37) — AiDetector and PromptInjectionDetector covering all 7 attack categories, confidence stacking, whitelist bypass, config toggles, recursive scanning, and edge cases
Changelog
See CHANGELOG.md for a full history of changes.
Contributing
Contributions are welcome — new bot signatures and injection patterns especially. See CONTRIBUTING.md for guidelines.
Security
If you discover a security vulnerability, please follow the security policy — do not open a public issue.
Credits
Created by Jay Anta.
License
The MIT License (MIT). See LICENSE for more information.
All versions of laravel-ai-guard with dependencies
illuminate/support Version ^10.0|^11.0|^12.0
illuminate/database Version ^10.0|^11.0|^12.0
illuminate/http Version ^10.0|^11.0|^12.0
illuminate/cache Version ^10.0|^11.0|^12.0