Standalone, cache-first, Octane-safe, multi-panel & multi-tenant firewall for Laravel 12/13 and Filament 5.
Rebuilt from the ground up in v5.0 with zero third-party firewall dependencies:
-
Cache-first & Octane-safe: Compiled IPv4/IPv6 CIDR rules and auto-ban counters live in Laravel Cache (0 SQL queries on hot/attack paths; immediate cache invalidation when rules change; zero
Set-Cookie/ session touches so CDN edge caching stays intact). -
Dual modes:
- Protect mode (
filament-firewall.protect): Default for public sites & apps — allows visitors while blocking deny rules, fail2ban auto-bans, scanner probes (wp-login.php,.env,.git, path traversal, etc.), and excessive origin traffic. - Allowlist mode (
filament-firewall.allowlist/WhitelistRangeMiddleware): Deny-by-default for locking down/adminpanels to office/VPN IPs.
- Protect mode (
-
IPv4 & IPv6 CIDR rules:
/0–/32(IPv4) and/0–/128(IPv6), temporary bans (expires_at), notes, and a self-lockout guard preventing admins from banning their own IP. -
Security headers (
filament-firewall.headers):X-Content-Type-Options,Referrer-Policy,Permissions-Policy,HSTS(HTTPS only), andX-Frame-Options(skipped whenContent-Security-Policyalready definesframe-ancestors). -
Multi-panel & multi-tenant native: Independent per-panel resource toggles, per-panel Gate/closure authorization (
authorizeViewUsing/authorizeManageUsing), custom auth guards, and optional tenant/site scoping (scopeUsing+FilamentFirewall::resolveScopeUsing). -
Pairs with
solution-forest/filament-loginguard: Optionally auto-bans IPs at the firewall layer whenLoginLockedOutfires. -
Experimental, optional AI review: AI-scored triage of blocked traffic with an admin review queue, optional temporary auto-bans, and visitor unblock appeals. Uses laravel/ai or a logged-in local CLI. Off by default and can be switched with a Laravel Pennant flag (details).
| Filament Firewall | Filament | Laravel |
|---|---|---|
| 5.x (current) | ^5.8 |
12.x, 13.x |
| 4.x | ^5.0 |
11.x, 12.x, 13.x |
| 3.x | ^4.0 |
11.x, 12.x, 13.x |
| 2.x | ^3.0 |
10.x, 11.x, 12.x |
| 1.x | ^2.0 |
9.x, 10.x |
The legacy rows show which Laravel majors Composer resolves with the latest Git tag in each line. Filament and other dependencies can require a later patch release within a listed Laravel major.
Versions 1.x–4.x use Akaunting Laravel Firewall. If you are moving to the standalone v5 release, follow the upgrade guide.
composer require solution-forest/filament-firewall:^5.0
php artisan filament-firewall:installRegister the plugin on any Filament v5 panel:
use SolutionForest\FilamentFirewall\Enums\FirewallMode;
use SolutionForest\FilamentFirewall\FilamentFirewallPlugin;
public function panel(Panel $panel): Panel
{
return $panel
->plugin(
FilamentFirewallPlugin::make()
->protectPanel(FirewallMode::Protect, securityHeaders: true)
->authorizeViewUsing(fn ($user): bool => (bool) $user->is_super_admin)
->authorizeManageUsing(fn ($user): bool => (bool) $user->is_super_admin),
);
}// Scope HTTP middleware evaluation (e.g. in AppServiceProvider::boot):
FilamentFirewall::resolveScopeUsing(fn (Request $request): ?string => $site ? 'site:'.$site->id : null);
// Scope the Filament Resources to the active tenant:
FilamentFirewallPlugin::make()
->scopeUsing(fn (): ?string => Filament::getTenant() ? 'site:'.Filament::getTenant()->getKey() : null);protectPanel() evaluates panel requests with the panel's scopeUsing() when set, otherwise with the global
FilamentFirewall::resolveScopeUsing() resolver. Panel middleware runs before Filament identifies the tenant, so a
scopeUsing() callback used for request evaluation should not rely solely on Filament::getTenant() (read the
tenant from the route, e.g. request()->route('tenant'), if needed).
| Capability | Nothing configured | Configured |
|---|---|---|
| View rules & blocked requests | Any authenticated panel user | authorizeViewUsing() callback or authorization.view Gate ability |
| Manage (create/edit/delete rules, Ban/Allow IP actions) | Denied (resources are read-only and show a notice) | authorizeManageUsing() callback, authorization.manage Gate ability, or (fallback) the configured view callback/ability |
// Per panel:
FilamentFirewallPlugin::make()
->authorizeManageUsing(fn ($user): bool => $user->hasRole('security-admin'));
// Or globally via Gate abilities in config/filament-firewall.php:
'authorization' => ['view' => 'view-firewall', 'manage' => 'manage-firewall'],Warning
bypass.ips defaults to 127.0.0.1 and ::1. If a reverse proxy runs on the same host (nginx, Caddy,
Cloudflare Tunnel, a Docker ingress) and neither filament-firewall.trusted_proxies nor Laravel's
TrustProxies is configured, every visitor appears as 127.0.0.1 and bypasses the firewall.
Configure trusted proxies (or remove the loopback entries). The firewall logs a warning (at most once per
hour, cache-throttled) when a bypass IP sends X-Forwarded-For from an untrusted peer.
X-Forwarded-For entries with ports (203.0.113.7:5555, [2001:db8::1]:443) are normalized exactly like
Laravel's $request->ip().
Important
Laravel Cloud, or TrustProxies::at('*'). When the app trusts every proxy (Laravel's '*', which
Laravel Cloud turns on automatically), $request->ip() is the left-most X-Forwarded-For entry, which
the client controls. The firewall then ignores $request->ip(). It starts from the TCP peer (REMOTE_ADDR)
and walks X-Forwarded-For right to left past filament-firewall.trusted_proxies only. Set that list to
your load balancer and CDN ranges, for example private ranges plus Cloudflare's published ranges:
'trusted_proxies' => ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7', /* Cloudflare ranges… */],If it is empty, every visitor resolves to your load balancer. The firewall logs a warning (at most once an hour) when this happens. A trusted proxy is never auto-banned.
- Auto-ban: 5 probe strikes in 10 minutes → 60-minute ban. IPv6 is banned per
/64(auto_ban.ipv6_prefix). Temporary bans are enforced from cache keys (not the per-request rule list), persisted as expiring rules (capped atauto_ban.max_persisted= 10,000 rows) and re-hydrated from the DB after a cache flush. - Rate limit: 120 requests / 60 s per IP on routes using
filament-firewall.protect. Livewire endpoints (livewire/*,livewire-*/*) and panel requests protected viaprotectPanel()are excluded by default (rate_limit.except_paths,rate_limit.apply_to_panels) so admins polling behind one NAT IP are not throttled. - Probe detection inspects only the decoded path (
?q=../docsis not a strike). - Blocked-request events are deduped per IP (per
/64for IPv6) and reason, capped atevents.max_per_minute, and pruned after 30 days by the scheduledfilament-firewall:cleanup(enabled by default; requires the Laravel scheduler).
filament-firewall.protect(ProtectWithFirewall) — Protect mode (public & app routes)filament-firewall.allowlist(AllowlistFirewall/WhitelistRangeMiddleware) — Allowlist mode (admin/VPN routes)filament-firewall.headers(SecurityHeaders) — HTTP security headers
php artisan filament-firewall:unban 203.0.113.10 [--scope=site:1]
php artisan filament-firewall:cleanup [--days=30]
php artisan filament-firewall:ai-review [--scope=site:1] [--limit=20] # optional AI review
php artisan filament-firewall:ai-testWarning
The AI review is an experimental feature. Its configuration, database table, prompts and behaviour may change in minor releases until it is marked stable. It is off by default, AI verdicts are judgment calls rather than proof, and it never runs on the request path. Try it on a staging site first.
The master switch is FILAMENT_FIREWALL_AI_ENABLED. To switch the feature at runtime without a deploy (for
example, per environment or during an incident), add a Laravel Pennant
feature flag:
composer require laravel/pennantFILAMENT_FIREWALL_AI_ENABLED=true
FILAMENT_FIREWALL_AI_FEATURE=filament-firewall-aiuse Laravel\Pennant\Feature;
// AppServiceProvider::boot(): off until you activate it.
Feature::define('filament-firewall-ai', fn (): bool => false);
// Turn it on or off (tinker, a command, or an admin action). The flag uses Pennant's global (null) scope, so
// it applies to web requests, the scheduler and queues alike.
Feature::for(null)->activate('filament-firewall-ai');
Feature::for(null)->deactivate('filament-firewall-ai');- AI is on only when
FILAMENT_FIREWALL_AI_ENABLED=trueand the Pennant feature is active.FILAMENT_FIREWALL_AI_ENABLED=falsealways wins. - When it is off, nothing is scheduled, the AI Review page and Ask AI are hidden, and blocked visitors see no appeal link. Existing reviews and AI bans stay in place until they expire or an admin lifts them.
- The result is cached for
ai.feature_cache_seconds(30s) so the firewall's request path never queries Pennant storage. Callapp(\SolutionForest\FilamentFirewall\Ai\AiManager::class)->forgetFeatureCache()after toggling to apply the change immediately. - If
FILAMENT_FIREWALL_AI_FEATUREis set but Pennant is not installed, AI stays off.
The firewall can ask an AI model to triage blocked traffic. It is off until you enable it and configure a connection. When it is on, a scheduled job (every 15 minutes by default) does the following:
- Groups recent blocked requests per IP (IPv6 per
/64) and skips bypassed, trusted-proxy and allowlisted IPs. - Sends the model a summary for each IP: block reasons, counts, the most requested paths (without query strings) and user agents.
- Stores the model's verdict (
malicious/benign/unsure), confidence (0–100), a one-sentence summary and its evidence infilament_firewall_ai_reviewsfor admins to review. - By default, temporarily bans an IP when the model rates it
maliciouswith at least 90% confidence. These bans have the rule sourceaiand are capped per day. The AI never allowlists or unbans anyone.
It never runs on the request path. If the model times out, returns an error or hits the budget, the run is skipped and traffic is not affected.
AI calls go through laravel/ai, so any provider it supports works. Configure
providers and keys in config/ai.php (php artisan vendor:publish --tag=ai-config), then enable the review:
OPENAI_API_KEY=sk-... # or ANTHROPIC_API_KEY, GEMINI_API_KEY, XAI_API_KEY, OPENROUTER_API_KEY, ...
FILAMENT_FIREWALL_AI_ENABLED=true
FILAMENT_FIREWALL_AI_PROVIDER=openai # provider name from config/ai.php (default: ai.default)
FILAMENT_FIREWALL_AI_MODEL= # optional; the provider's default text model when emptyTo use an OpenAI-compatible gateway (LiteLLM, Cloudflare AI Gateway, an in-house gateway, vLLM, LM Studio), use
laravel/ai's openai-compatible provider:
OPENAI_COMPATIBLE_URL=https://ai-gateway.example.com/v1
OPENAI_COMPATIBLE_API_KEY=...
FILAMENT_FIREWALL_AI_PROVIDER=openai-compatible
FILAMENT_FIREWALL_AI_MODEL=your-modelphp artisan filament-firewall:ai-test # check the connection (sends no traffic data)
php artisan filament-firewall:ai-review # run a review now [--scope=site:1] [--global] [--limit=20]So that one model's mistake can't ban anyone, you can have several models review every IP and only auto-ban when enough of them agree:
// config/filament-firewall.php
'ai' => [
'consensus' => [
'enabled' => true, // or FILAMENT_FIREWALL_AI_CONSENSUS=true
'models' => [
['provider' => 'openai'], // inline laravel/ai entries…
['provider' => 'anthropic', 'model' => null],
['provider' => 'gemini'],
// 'cli', // …or connection names from ai.connections
],
'min_agree' => 2,
],
],- Every model gets the same prompt. An auto-ban needs at least
min_agreemodels to votemaliciouswith confidence ≥ai.auto_ban.min_confidence(90). One very confident model is never enough. - Without that agreement, the review is still saved with the majority verdict (a tie gives
unsure) for an admin to decide. Nothing is banned. - The AI Review page shows the agreement next to the verdict (for example
Malicious 94% · 2/3 agree), and the Evidence modal lists each model's vote and reasoning. Appeals and Ask AI use the same panel. - If a model fails, it only loses its vote, and the error names the model. The run stops only when every model fails.
- Each model counts as one call against
ai.budget.max_calls_per_day, so a three-model panel costs three times as much per batch. Calls run one after another. - Set
min_agreeto the number of models to require a unanimous decision. Ifmin_agreeis higher than the number of models that answered, nothing is auto-banned.
Instead of an API key, reviews can run through a coding-agent CLI that is already installed and logged in with your subscription on the server:
FILAMENT_FIREWALL_AI_CONNECTION=cli
FILAMENT_FIREWALL_AI_CLI=claude # claude | codex | cursor | opencode | pi | grok
FILAMENT_FIREWALL_AI_CLI_MODEL= # optional, passed with the CLI's model flag| Preset | Log in once with | Runs |
|---|---|---|
claude |
claude login (Claude Code) |
claude --print --output-format json --tools "" --json-schema … (prompt on stdin) |
codex |
codex login (Codex CLI) |
codex exec --sandbox read-only --output-schema … --output-last-message … - |
cursor |
cursor-agent login |
cursor-agent --print --output-format json --mode ask --trust … |
opencode |
opencode auth login (any provider, incl. xAI Grok OAuth) |
opencode run --pure --agent plan … |
pi |
pi, then /login |
pi --print --no-tools --no-session --no-context-files … |
grok |
grok login (xAI Grok Build, beta) |
grok exec … (headless flags may change; override command if needed) |
-
Each call runs in a fresh, empty temporary directory, with tools disabled or read-only where the CLI supports it, and one call at a time. The driver only runs the binary and never reads the CLI's stored credentials.
-
The CLI must be logged in for the OS user that runs it: the scheduler user for
ai-review, and the PHP-FPM user for Ask AI and appeal scoring. It doesn't work on serverless hosts such as Laravel Cloud or Vapor. -
Calls are slower than an API (from a few seconds to about 90s for Cursor).
timeoutdefaults to 180 seconds. -
To use another CLI or different flags, set
filament-firewall.ai.connections.cli.commandto a list of arguments. It supports{prompt},{schema},{schema_file},{output_file}and{model}placeholders, and the prompt goes on stdin when there's no{prompt}. -
Subscriptions are meant for personal use. Check that your plan's terms allow automated server use, and prefer an API key or gateway for production.
-
Privacy. By default the model receives a keyed hash of each IP (HMAC with
APP_KEY), not the address itself (ai.privacy.hash_ip). Admins still see the real IP. Request paths and, unless you turn offai.privacy.send_user_agent, user agents are sent to the provider you configure. -
Cost. IPs are sent in batches (
ai.review.batch_size), an IP is not reviewed again withinai.review.reuse_verdict_hours, andai.budget.max_calls_per_daycaps model calls per day. -
Prompt injection. Paths and user agents are controlled by attackers. They are passed to the model as quoted data, and its answer is validated against a schema. The worst case is a temporary, capped ban, and allowlisted, bypassed and trusted-proxy IPs are never banned.
-
Custom backends. Register a driver with
app(AiManager::class)->extend('name', fn (array $config): AiDriver => ...)and reference it from a connection'sdriverkey infilament-firewall.ai.connections. -
Testing your app. Fake the model with laravel/ai:
FirewallReviewAgent::fake([...]).
ai.auto_ban.mode (FILAMENT_FIREWALL_AI_BAN_MODE) decides what happens when the AI is confident that an IP is
malicious (and, with consensus, enough models agree):
| Mode | What the AI does | What a human does |
|---|---|---|
auto (default) |
Bans temporarily right away (auto_ban.duration_minutes, capped per day). |
Confirm ban to agree, Change ban to make it longer or permanent, or Unblock / Allow to undo it. |
approve |
Blocks nothing. The review is marked Awaiting ban approval. | Approve ban (choose the duration) or Reject ban. |
Either way, the AI never allowlists or unbans anyone, and every decision records who made it and when. By default
the AI Review page lists everything still waiting for a person: pending reviews, recommendations awaiting
approval, and unconfirmed auto-bans. Set FILAMENT_FIREWALL_AI_AUTO_BAN=false to turn off both auto-bans and
recommendations, so the AI only reports.
While AI is enabled, each panel gets an AI Review page next to Blocked Requests. Its badge counts the
reviews that still need a human decision. Each row shows the AI verdict and confidence (for example
Malicious 92%), the one-line summary, and the evidence behind it. Admins with manage permission can:
- Ban / Approve ban / Change ban: ban the subject (the IPv4 address or the IPv6
/64) for the AI's duration, 7 days, 30 days, or permanently with a manual Deny rule. - Confirm ban: agree with an AI auto-ban and keep it as it is.
- Unblock: lift the ban without allowlisting. This removes AI and other temporary bans, and any permanent rule created from that review.
- Allow / Approve (for appeals): allowlist the IP permanently and lift any ban on it.
- Dismiss / Reject ban / Reject (for appeals): close the review without blocking anything.
Ban, approve, confirm and dismiss also work as bulk actions. The self-lockout guard applies to every ban. Blocked Requests gets an
Ask AI action that reviews one IP on demand: it looks back 24 hours and never auto-bans. To hide the page on a
panel, use FilamentFirewallPlugin::make()->aiReviewsResource(false).
When AI is enabled, a visitor blocked by a deny rule or a temporary ban (ai.appeals.reasons) sees a link in the
403 response. It opens a small form at /firewall/appeal (ai.appeals.path) where they can explain what they were
doing.
- The link is signed, expires after
ai.appeals.link_ttl_minutes, and only works from the IP (or IPv6/64) it was issued to. The form uses no session, cookies or CSRF token, and the path gets through the firewall on its own. - Each IP can send
ai.appeals.max_per_ip_per_dayappeals (default 1) and has at most one open appeal. A honeypot field drops simple bots. - The AI scores each appeal (is this a real person who was blocked by mistake?) after the response is sent, and the scheduled review catches anything missed. Appeals appear on the AI Review page with Approve and Reject. The AI never unblocks anyone. Only an admin's Approve does.
- Signed links need correct absolute URLs. Behind a proxy, configure
TrustProxies(orURL::forceScheme('https')) so the scheme and host match. Turn the feature off withFILAMENT_FIREWALL_AI_APPEALS=false.
v5.0 is a standalone rewrite: akaunting/laravel-firewall is no longer used. Follow these steps in order.
-
Update the Composer constraint
composer require solution-forest/filament-firewall:^5.0
If nothing else in your app uses
akaunting/laravel-firewall, you may remove it afterwards (composer remove akaunting/laravel-firewall), together with itsconfig/firewall.php. -
Publish and merge the new config
php artisan vendor:publish --tag=filament-firewall-config --force
The v4 config (
models,resources,skip_whitelist_range) is replaced. Move any IPs fromskip_whitelist_rangeintobypass.ips. Until you do, v5 still honoursfilament-firewall.skip_whitelist_rangeand akaunting'sfirewall.whitelistas bypass IPs, so nobody is locked out mid-upgrade. -
Run the migrations
php artisan migrate
This creates
filament_firewall_rulesandfilament_firewall_events, then theimport_v4_firewall_ips_into_filament_firewall_rulesmigration copies your v4firewall_ipsrows:blocked = false→ Allow rule,blocked = true→ Deny rule;ipandprefix_sizeare preserved; rows are imported as global rules (scope = null) with sourcev4_import; soft-deleted and invalid rows are skipped;- it is idempotent (safe to re-run) and never modifies or drops
firewall_ips; drop it yourself once you have verified the import. Rolling the migration back removes onlyv4_importrules.
If you publish migrations instead of letting the package run them, re-publish with
php artisan vendor:publish --tag=filament-firewall-migrationsso the import migration is included. -
Update code that used renamed APIs
v4.x v5.0 FilamentFirewall::withinWhitelist($ip)FilamentFirewall::withinAllowlist($ip, ?$scope)FilamentFirewall::withinBlackList($ip)FilamentFirewall::withinBlocklist($ip, ?$scope)getWhiteList()/getBlackList()/getFirewallIpModel()Query SolutionForest\FilamentFirewall\Models\FirewallRule(action=allow/deny)Models\Ip,FirewallIpResourceModels\FirewallRule,FirewallRuleResource(+FirewallEventResource)WhitelistRangeMiddlewareStill available (alias of AllowlistFirewall,filament-firewall.allowlist)config('firewall.enabled')config('filament-firewall.enabled')/FILAMENT_FIREWALL_ENABLED -
Configure authorization (behaviour change)
In v4 every panel user could manage the firewall. In v5, viewing requires an authenticated panel user and managing is denied until you configure
authorizeManageUsing()(orauthorizeViewUsing()) on the plugin or theauthorization.manage/authorization.viewGate abilities. See Authorization. -
Review the new defaults (behaviour changes)
- Localhost bypass:
127.0.0.1/::1are bypassed. Behind a same-host reverse proxy configuretrusted_proxies/ TrustProxies first, otherwise everyone bypasses the firewall (see the warning above). - Rate limiting is on (120 req/min per IP) for routes using
filament-firewall.protect; Livewire and panel requests are excluded by default. - Probe blocking & auto-ban are on: scanner paths (
wp-login.php,.env,.git, …) return 404 and 5 strikes in 10 minutes ban the IP (IPv6: its/64) for 60 minutes. - HSTS: the
filament-firewall.headersmiddleware (orprotectPanel(..., securityHeaders: true)) sendsStrict-Transport-Security: max-age=31536000; includeSubDomainson HTTPS responses. Setheaders.strict_transport_securitytonullif any subdomain is not served over HTTPS. - Cleanup of expired rules and events older than 30 days is scheduled daily by default.
- Unban (
filament-firewall:unban,FilamentFirewall::unban()) only lifts temporary bans (auto_ban,loginguard,bansources) in the given scope; manual Deny rules are removed in the UI.
- Localhost bypass:
-
Allowlist panels: if you register the plugin with
protectPanel(FirewallMode::Allowlist), make sure your office/VPN Allow rules were imported before deploying. The admin UI refuses to delete or edit the Allow rule that admits your own IP.
