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.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-ai-guard

Laravel AI Guard

Latest Version on Packagist Total Downloads PHP Version Laravel Version License Tests PHPStan Code Style

Protect your Laravel app from AI scrapers, spoofed crawlers, and prompt injection — and guard the LLM features you build yourself: budgets, moderation, PII redaction, a tool-call firewall, MCP pinning, safe rendering, red-teaming, and an audit trail.

Upgrading from v2? Read UPGRADE.md — AI bots are now split by purpose, and prompt-injection scores are weighted.

What It Does

Inbound traffic — a middleware with a multi-layer detection pipeline:

Your own LLM features — helpers and middleware for chatbots, agents, RAG, and MCP:

All detections are logged to your database with a built-in dashboard, 10 REST API endpoints, Artisan commands, a ThreatDetected event, and Slack alerts. Bot identity is also published as dependency-free events that other code can listen to.

Requirements

No PHP extensions or external services are required. ext-intl (full Unicode folding), ext-sodium (native Ed25519), and ext-dom (HTML sanitizing) are used when present; fallbacks cover them otherwise. The laravel/ai integration needs laravel/ai (PHP 8.3+, Laravel 12+).

Installation

Publish and run migrations:

Publish the config file:

Quick Start

Register the middleware globally so every request is scanned.

Laravel 11 / 12 / 13 — 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:

Other aliases: ai-guard.llm (routes that call a model), ai-guard.agents (AI agent policy), ai-guard.mcp (MCP servers), ai-guard.csp (Content-Security-Policy), and ai-guard.preferences (AI usage preferences).

Recommended First Steps

  1. Start in log_only mode (default) — detects and logs everything, blocks nothing
  2. Open the dashboard at http://your-app.com/ai-guard — it requires login by default (Dashboard & API Authentication)
  3. Whitelist your own tools — Postman, monitoring, office IPs (False Positives)
  4. Decide your AI policy — which of training crawlers, AI search crawlers, and AI agents you want to block (see Bot Signatures)
  5. Review detections for a few days before switching to block or rate_limit mode

Detection Pipeline

Every request passes through this pipeline:

Configuration

After publishing, the config file is at config/ai-guard.php.

Mode

Mode Behavior Use case
log_only Detect and log. Never block. Starting out — understand your traffic before enforcing
block 403 JSON for threats above the confidence threshold Production enforcement
rate_limit Rate-limit detected threats; 429 when exceeded Softer enforcement — allow some access, limit volume

Switching modes is a config change, no code. Budgets on ai-guard.llm routes and the ai-guard.agents rules are access controls, so they apply in every mode.

Confidence Threshold

Bot Signatures (353 signatures, 8 categories)

Category Count Default Confidence Blocked at threshold 70
ai_training — collects content to train models (GPTBot, ClaudeBot, CCBot) 51 95 Yes
ai_search — builds AI answer indexes (OAI-SearchBot, Claude-SearchBot, PerplexityBot) 21 65 No — logged
ai_agents — live fetches for a user (ChatGPT-User, Claude-User, Perplexity-User, Google-Agent) 31 60 No — logged
scrapers — headless browsers and scraping APIs (Puppeteer, Playwright, ScrapingBee, Zyte) 58 85 Yes
bad_bots — vulnerability scanners (Nikto, sqlmap, nuclei, Masscan) 55 95 Yes
data_harvesters — HTTP libraries (curl, python-requests, Go-http-client, PostmanRuntime) 45 80 Yes
seo_tools (AhrefsBot, SemrushBot, MJ12bot) 56 60 No — logged
search_engines (Googlebot, Bingbot, YandexBot) 36 30 Disabled

Blocking training crawlers costs you nothing in AI answers; blocking AI search crawlers and user-triggered agents removes your pages from them. Choose per purpose:

Signatures match on word boundaries, and the strongest match wins — appending "Googlebot" to an attack tool's user-agent does not hide it. The v2 category name ai_assistants is still accepted and means ai_search + ai_agents.

New AI crawlers appear every month. php artisan ai-guard:update-signatures adds the tokens from the community ai.robots.txt list (MIT) that the built-in database lacks, sorted by purpose. Nothing is fetched unless you run it — schedule it weekly if you like:

To flag extra AI crawler tokens of your own, list them in ai_crawlers.user_agents (they score 95):

Prompt Injection

Every pattern carries a weight. Strong signals ("ignore previous instructions", <|im_start|>, "reveal your system prompt") score 85–95 on their own; weak ones ("act as a", "you are now", "debug mode", the bare word "jailbreak") stay below min_score unless they appear together. Additional signals add up to 15 points, and a payload that only matched after de-obfuscation gets +10.

Bot Verification

A request that claims a verifiable crawler but fails every check that could run is logged as spoofed_bot. If a range list is unreachable, the verdict is unverified, never spoofed. Verdicts are stored in the bot_verification column (verified, spoofed, unverified).

Honeypot Traps

28 paths real users never visit — /admin-backup, /wp-admin, /wp-login.php, /.env, /.git/config, /.aws/credentials, /phpinfo.php, /api/v1/users.json, /backup.sql, and more. Any request to one 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_paths with your own array to avoid conflicts.

Response Scanning

Scans outgoing HTML, JSON, and text responses for leaked secrets and PII before they leave your server.

With scan_hidden_injection, pages are also checked for indirect prompt injection: instructions hidden from human readers but read by AI agents and AI browsers — HTML comments, hidden / aria-hidden / display:none / zero-size / off-screen elements, and invisible Unicode tag text (including JSON-escaped). Useful when you render user-generated content such as reviews, profiles, or comments. Matches are logged as indirect_prompt_injection.

robots.txt Enforcement

Parses your robots.txt per RFC 9309 — grouped User-agent lines, Allow rules with longest-match precedence, bot-specific groups overriding *, and * / $ wildcards — and boosts confidence when a detected bot requests a disallowed path.

Request Fingerprinting

Header signals: missing browser headers (only ones every current engine sends — Chromium-only Sec-CH-UA* and HTTP/2-forbidden Connection are not counted, so Firefox and Safari are not scored as suspicious for lacking them), alphabetical header order, anomalous Accept header, an explicit Connection: close, and no navigation context.

Edge fingerprints. A client's JA4 TLS fingerprint is hard to fake with a user-agent string. CloudFront sends it as CloudFront-Viewer-JA4-Fingerprint; on Cloudflare, add a request header transform rule (cf-ja4 = cf.bot_management.ja4, and cf-bot-score = cf.bot_management.score). A request claiming a browser whose JA4 shows no SNI, no TLS 1.3, or HTTP/1.1-first ALPN is flagged, as is any fingerprint you list in client_ja4. Because anyone can send these headers, they are only read from requests that came through a trusted proxy.

Datacenter IPs. A browser user-agent from AWS, Google Cloud, or Oracle Cloud adds to the score. It is weak evidence alone (VPNs, corporate proxies), so it only tips requests that other signals already make suspicious. Lists are compiled once and cached; warm them with php artisan ai-guard:refresh-ranges (and set fetch_on_request to false to never fetch during a request).

ML Detection (Optional)

By default ML only refines borderline scores: strong regex detections are never sent to a provider, so ML cannot talk them down. On always_run_on paths (your chat endpoints) every input is classified, so ML catches paraphrased attacks that no pattern matches.

Driver Provider Data Privacy
lakera Lakera Guard (v2 /guard API) SaaS
huggingface Llama Prompt Guard 2 via Inference Providers SaaS
pangea Pangea AI Guard SaaS
llm_guard LLM Guard — deprecated: the project was archived in July 2026; the driver is removed in v4 Self-hosted
ollama Ollama — input is fenced and the model must answer in a JSON schema Self-hosted
custom Your own endpoint You control

To enable, add your API key to .env and set enabled to true:

Rate Limiting

Applies in rate_limit mode. Counters use Laravel's rate limiter, on your default cache store.

Alerts

AI Usage Preferences

Tell AI crawlers how your content may be used. ai-guard:robots-txt writes both into robots.txt, and the ai-guard.preferences middleware sends a Content-Usage response header:

Both standards are drafts and advisory — crawlers may ignore them — so they complement blocking rather than replace it.

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

If you test your API with Postman, Insomnia, or curl, whitelist them — otherwise your own requests are logged as threats:

AI Agents on Your Site

User-triggered AI agents (ChatGPT-User, Perplexity-User, Operator, Google-Agent, signed Web Bot Auth agents) fetch pages for a person, and many do not read robots.txt. Decide per route who may use a page — checkout, account, and booking pages are the usual candidates:

"Verified" means a valid Web Bot Auth signature or the operator's published IP ranges, so turn on bot_verification. This is an access rule: it is enforced in every mode, refused agents get a 403, and each refusal is logged as ai_agent_denied. People and crawlers that are not agents pass through to the main middleware.

Guarding Your Own LLM Features

The middleware protects inbound traffic. The following protect the LLM features you build — chatbots, agents, RAG, MCP servers.

A note on what to rely on: detecting prompt injection (patterns, ML, spotlighting) catches known and careless attacks, but a determined attacker who adapts can get past any detector. The controls that hold are the ones that do not need to recognise the attack — the tool-call firewall, the egress allow-list, taint tracking, and safe rendering limit what an injected model can actually do. Use detection as a signal; use those for protection.

Routes that call a model

Put ai-guard.llm on the routes that send user input to a model:

It checks, before your controller runs:

Record what a call actually used, so budgets and cost tracking stay accurate:

Behind the ai-guard.llm middleware, the input was already reserved when the request came in. The first recordUsage() call in that request for the same user and tier settles that reservation, so the input is not counted twice. If you reserved it some other way (for example with consumeBudget()), say how much:

The same checks are available directly: AiGuard::checkBudget() (or consumeBudget(), which reserves the estimate as it checks — what the middleware uses, so simultaneous calls cannot each pass the same check), moderate(), checkTopic(), and observeConversation().

Redact personal data, restore it in the reply

Which types are masked, and which are put back, is set in llm_guard.redaction.

Spotlight untrusted content

Text your app did not write — a web page, an email, a document, a tool result — should reach the model as data, not instructions:

Modes: delimit (random boundary markers), datamark (a marker between every word), and base64.

Scan model output before returning it

scanOutput() flags:

Render model output safely

@aiSafe (or AiGuard::safeHtml($reply)) renders Markdown with raw HTML escaped, then removes scripts, event handlers, javascript: and data: links, and images that would load from — and leak chat data to — hosts other than yours and llm_guard.allowed_domains. Links get rel="nofollow noopener noreferrer". Options in llm_guard.rendering.

Add a Content-Security-Policy to the pages that show model output, so an injection that slips through still cannot run script or load remote images:

The nonce is shared with Vite, and the policy is set in llm_guard.csp.

Canary tokens

Canaries are HMAC-signed with your APP_KEY (or llm_guard.canary_secret), so AiGuard::isCanary($token) rejects forged ones.

Tool-call firewall

An agent that reads untrusted content and can also act — send email, write files, call APIs — is the combination attackers look for. The firewall checks each tool call before it runs:

Refusals are logged as tool_call_blocked and held calls as tool_call_held.

MCP

Servers you serve. Put ai-guard.mcp on your MCP route (laravel/mcp or any JSON-RPC endpoint):

Every tools/call is scanned and checked against the tool policies above — decided from the decoded JSON-RPC body, not the Content-Type. A refused call gets a JSON-RPC error; a call that needs approval gets error -32002, and the client retries with the token from AiGuard::approveToolCall() in an X-AI-Guard-Approval header.

Results are scanned (including event-stream responses) and a poisoned result taints the MCP session. A tool whose policy sets untrusted_output taints the session as soon as it is called, so a result that comes back over a stream this middleware cannot read still guards the calls that follow it. The session is keyed to the authenticated client, not to the MCP-Session-Id it sends.

Servers you use. Before handing an MCP server's tools to an agent:

Scan any tool definition, argument set, or result directly with AiGuard::scanToolCall($payload, 'definition' | 'arguments' | 'result').

laravel/ai agents

With laravel/ai installed, add the prompt guard to an agent and wrap its tools:

GuardPrompt runs the budget, injection, topic, moderation, and escalation checks before the provider is called, can redact the prompt and restore the reply, scans the reply for exfiltration and leaks of the agent's instructions, and records token usage. A blocked prompt throws JayAnta\AiGuard\Exceptions\AiGuardBlockedException, which renders as a JSON 403, 429, or 413 if you do not catch it. Streamed replies are scanned and logged when the stream ends. It works with laravel/ai 0.x and 1.x; under 1.x, where middleware runs once per step of the agent loop, the input is checked on the first step, redaction holds for every step, and token usage is recorded for each one.

AiGuard::guardTools() puts each tool — including sub-agents, ToolSearch tool sets, and MCP client and server tools — behind the tool firewall. A refused call never runs (the model is told why), and a call that needs approval pauses the run through laravel/ai's own approval flow.

Model-written SQL

For "ask your data" features that let a model write SQL:

runReadOnlySql() re-runs the check itself, so pass it the same options — otherwise it checks against llm_guard.sql in your config alone, where no allowed_tables means every table is allowed.

The check accepts a single read-only statement over allowed tables and refuses writes (including data-modifying CTEs), INTO OUTFILE, row locks, sleep and file functions, and system catalogs. Where a statement could be read two ways — backslash escapes, MySQL /*! */ and # comments, an unterminated quote — it fails closed. runReadOnlySql() caps the rows as it reads them and runs the query in a transaction that is always rolled back (read-only on MySQL and PostgreSQL). Still use a database user with SELECT rights only.

Red Teaming

Measure how AI Guard, as configured in your app, handles known attacks:

It runs a bundled corpus — prompt injections, system-prompt extraction, jailbreaks, tool poisoning, output exfiltration, egress destinations hidden in tool arguments, model-written SQL, unsafe rendering, and benign prompts that look like attacks ("ignore the typos in my last message", "act as a reviewer") — through up to 11 encodings (base64, zero-width, homoglyphs, fullwidth, leetspeak, spacing, URL and HTML encoding, Unicode tags, emoji variation selectors, code fences), and reports detection and false-positive rates per category and per encoding.

The bundled corpus is a regression suite, not a benchmark. The v3 patterns were tuned against it: its first run caught 61% of attacks with a 3.3% false-positive rate, and after every miss was fixed — with general patterns and de-obfuscation, not by matching the corpus text — v3.0 catches all 406 attack variants (100 cases with --mutations=all) with no false positives on its 35 benign cases. It measures the detectors as this package configures them, on attacks that are already known; it says nothing about attacks nobody has written down yet. The test suite also checks phrasings that are not in the corpus. For an independent measurement, export the corpus and run garak or promptfoo against your endpoint.

Options: --suite=injection,jailbreak,..., --mutations=none|basic|all|<list>, --format=json, --show-misses.

Audit Trail and Export

Exports are buffered and sent when the request, command, or queued job ends, so they never slow a response; a failed export is logged and never breaks the app. Threats are exported even when database logging is off.

Events

Every detection dispatches a JayAnta\AiGuard\Events\ThreatDetected event, so you can plug in your own notifications, IP banning, or metrics:

This includes tool-firewall, MCP, budget, and agent-policy decisions. Listener exceptions are caught and logged — a broken listener never breaks request handling. AiGuard::log() dispatches the event too.

Interop Contract

ThreatDetected reports what AI Guard acted on. The interop contract, ai-guard.verdict/1, reports who the client is — for other packages and services that want AI Guard's bot identity without depending on AI Guard. It is a published convention, not an API: named events and a request attribute, read by class-name string and array key, with nothing to import. Code that listens keeps working when AI Guard is not installed; the events simply never fire.

Events — at most once per request, when an AI Guard middleware first evaluates it:

Event Fires when
JayAnta\AiGuard\Events\BotClassified The client is a known bot category, or its identity was verified or found spoofed
JayAnta\AiGuard\Events\AgentVerified Its identity was verified (Web Bot Auth, published IP ranges, or reverse DNS) — in addition to BotClassified
JayAnta\AiGuard\Events\SpoofedBotDetected It claimed a verifiable identity and failed every check that could run — in addition to BotClassified

Each carries scalar, read-only properties — schema, category, token, identity, status, method, ip, requestMethod, path (no query string), evaluatedAt — and toArray(). Ordinary visitors fire nothing.

Request attribute — after an AI Guard middleware has run, request()->attributes->get('ai_guard.verdict'):

Absent means the request was not evaluated: the package is disabled, the request is whitelisted, or no AI Guard middleware has evaluated it yet (ai-guard.agents:allow lets everyone through without evaluating). Present with nulls means evaluated: not a recognised bot.

Field Meaning v1 values
bot.category What kind of client this is — from a Web Bot Auth signature when there is one (bot_verification.web_bot_auth.category, default ai_agents), otherwise from the user-agent ai_training, ai_search, ai_agents, search_engines, seo_tools, scrapers, bad_bots, data_harvesters, null
bot.token The bot name matched in the user-agent (GPTBot); null when nothing matched, e.g. a signed agent browsing with a normal browser user-agent any signature token, null
bot.identity Who verification checked: the signing agent's host (chatgpt.com), or the crawler it checked by IP range or DNS (Googlebot) any, null
verification.status The result of that check verified, spoofed, unverified, null
verification.method How it was checked; with unverified, the check that was tried but could not complete web_bot_auth, ip_ranges, reverse_dns, null

What to rely on:

The canonical example payload is tests/Fixtures/interop/verdict-v1.json, and the test suite fails if the package drifts from it.

Dashboard

After installation, visit your dashboard at:

The dashboard shows:

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; optional ?hours=N keeps the last N hours)

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 — ai_crawler, prompt_injection, data_harvester, honeypot_trap, pii_leak, bad_bot, scraper, seo_bot, spoofed_bot, suspicious_fingerprint, indirect_prompt_injection, llm_output_threat, tool_injection, system_prompt_leak, llm_budget_exceeded, content_moderation, denied_topic, multi_turn_attack, tool_call_blocked, tool_call_held, mcp_tool_changed, mcp_server_blocked, unsafe_sql, ai_agent_denied, ...
action_taken — logged, blocked, rate_limited
bot_category — Any signature category, e.g. ai_training, ai_search, ai_agents
bot_verification — verified, spoofed, unverified

Artisan Commands

Command What it does
ai-guard:stats Threat statistics (--hours=48)
ai-guard:robots-txt Generate a robots.txt from the signature database
ai-guard:update-signatures Add new AI crawler tokens from the ai.robots.txt list (--dry-run)
ai-guard:refresh-ranges Fetch and cache crawler and datacenter IP range lists
ai-guard:mcp-pins List, approve, or forget pinned MCP tool definitions
ai-guard:redteam Run the red-team corpus and report detection and false-positive rates
ai-guard:audit-verify Check the tamper-evident hash chain
ai-guard:prune Delete old threat logs (--days=90, --dry-run)

Generate robots.txt

The AI training section also writes the robots.txt-only control tokens (Google-Extended, Applebot-Extended, ...), which never appear in traffic, and marks retired tokens as legacy. Googlebot and Bingbot are explicitly allowed. Tokens added by ai-guard:update-signatures are included.

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

Prompt Injection Patterns

76 weighted patterns across these categories, matched against the de-obfuscated text:

Secret and PII Detection (16 patterns)

Pattern Severity Default
Anthropic / OpenAI / GitHub keys and tokens 95 Enabled
Hugging Face / Google API / Slack tokens 90 Enabled
AWS access keys, private keys, database URLs 95 Enabled
Credit card numbers, Social Security numbers 95 Enabled
Generic API keys / tokens 90 Enabled
JWT tokens 85 Enabled
Phone numbers 75 Enabled
Email addresses 70 Enabled
Internal IP addresses 50 Disabled

The same patterns redact text before it is sent to an ML provider (ml_detection.redact_pii) and power AiGuard::redact().

Facade Usage

The LLM helpers are shown in Guarding Your Own LLM Features. The rest of the facade:

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 76 weighted patterns and de-obfuscation on top of natural-query's built-in InputGuard. For generated SQL, AiGuard::checkSql() adds a second, independent read-only check.

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

It requires login by default — see Dashboard & API Authentication.

My own curl/Postman requests are being logged as threats

Whitelist your tools — see False Positives.

Real Googlebot is logged as spoofed_bot

Bot verification checks the client IP. Behind a load balancer, CDN, or reverse proxy, configure Laravel's TrustProxies middleware so $request->ip() is the visitor's address — otherwise every crawler appears to come from your proxy.

JA4 and bot-score headers are ignored

Edge headers are only read from requests that arrived through a trusted proxy — configure TrustProxies with your CDN's addresses. Cloudflare needs a transform rule to send them (see Request Fingerprinting).

"ai_threat_logs doesn't exist", or "is missing the v3 columns"

Publish and run the migrations — the same command adds the v3 columns when upgrading:

Until the upgrade migration runs, threats are still logged, just without bot_category, bot_verification, and chain_hash.

ai-guard:audit-verify reports a broken chain

The row it names was edited, moved, or a row before it was deleted outside ai-guard:prune and the API's flush endpoint (for example with DELETE in SQL, TRUNCATE, or migrate:fresh). Rows written before hash_chain was turned on are not part of the chain.

The break stays reported, including after new rows are written: that is what makes a deletion evident. If you emptied the table on purpose and want to start a new chain, also delete the signed record of the chain's end, storage/app/ai-guard/audit-anchor.json (or your audit.anchor_path).

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:

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:

The package is slowing down my app

The in-process detection pipeline (honeypot, signatures, prompt injection, fingerprinting) measured 0.02–0.37 ms per request on PHP 8.1 without OPcache — from a plain browser GET to a 2 KB chat prompt. Database writes happen only for detections, and audit exports are sent after the response. If you notice slowness:

How It Compares

Laravel AI Guard crawler-detect spatie/laravel-honeypot Cloudflare Bot Management
AI/LLM crawler signatures ✅ 353, split by purpose ⚠ Generic crawler list ❌ ✅
Spoofed-crawler verification ✅ Web Bot Auth, IP ranges, rDNS ❌ ❌ ✅
Prompt injection detection ✅ 76 weighted patterns + de-obfuscation + optional ML ❌ ❌ ⚠ Firewall for AI (add-on)
LLM output / canary / safe rendering ✅ ❌ ❌ ❌
Token and cost budgets, moderation, topic policy ✅ ❌ ❌ ❌
Tool-call firewall and MCP pinning ✅ ❌ ❌ ❌
Red-team command for CI ✅ ❌ ❌ ❌
Tamper-evident audit, SIEM and OpenTelemetry export ✅ ❌ ❌ ✅ SaaS
Secret & PII leak detection (outbound) ✅ 16 patterns ❌ ❌ ⚠ Add-on
Honeypot traps ✅ Trap URLs ❌ ✅ Form fields ⚠ AI Labyrinth decoy pages
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 works at the edge and needs your DNS, with the AI features as paid add-ons. AI Guard covers the AI-scraper and LLM-security threat model inside your Laravel app — and works alongside Cloudflare (it reads Cloudflare's JA4 and bot-score headers).

Testing

The suite has 480 tests. Feature tests run full request → middleware → detection → database → events pipelines against the package's real migrations: bot purpose policies, Web Bot Auth with real Ed25519 signatures, IP-range and reverse-DNS verification, edge fingerprints, ML and moderation drivers against faked providers, budgets, the tool firewall and MCP pinning, laravel/ai agents (when laravel/ai is installed), safe rendering and CSP, the SQL gate, the audit chain and exports, and every Artisan command. Unit tests cover signature matching, RFC 9309 parsing, text normalization, weighted prompt-injection scoring (including held-out phrasings that are not in the red-team corpus and a false-positive corpus), IP range sets, and secret patterns.

Tests never make real network calls (Http::preventStrayRequests()).

Changelog

See UPGRADE.md for upgrade steps.

Contributing

Contributions are welcome — new bot signatures, verification sources, and injection patterns especially. Run php artisan ai-guard:redteam before and after changing a pattern. 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 ai.robots.txt project (MIT).

License

The MIT License (MIT). See LICENSE for more information.


All versions of laravel-ai-guard with dependencies

PHP Build Version
Package Version
Requires php Version ^8.1
guzzlehttp/guzzle Version ^7.5|^8.0
illuminate/cache Version ^10.0|^11.0|^12.0|^13.0
illuminate/console Version ^10.0|^11.0|^12.0|^13.0
illuminate/contracts Version ^10.0|^11.0|^12.0|^13.0
illuminate/database Version ^10.0|^11.0|^12.0|^13.0
illuminate/events Version ^10.0|^11.0|^12.0|^13.0
illuminate/http Version ^10.0|^11.0|^12.0|^13.0
illuminate/routing Version ^10.0|^11.0|^12.0|^13.0
illuminate/support Version ^10.0|^11.0|^12.0|^13.0
illuminate/view Version ^10.0|^11.0|^12.0|^13.0
paragonie/sodium_compat Version ^1.21 || ^2.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package jayanta/laravel-ai-guard contains the following files

Loading the files please wait ...