newgeode / webguard
Lightweight Laravel security middleware for IP restrictions, trusted proxies, HTTPS enforcement, bot traps, Panic Shield, and input sanitization.
Requires
- php: ^8.2
- illuminate/cache: ^10.0|^11.0|^12.0|^13.0
- illuminate/database: ^10.0|^11.0|^12.0|^13.0
- illuminate/http: ^10.0|^11.0|^12.0|^13.0
- illuminate/support: ^10.0|^11.0|^12.0|^13.0
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
NewGeode WebGuard is Laravel middleware for IP restrictions, request filtering, rate limiting, temporary IP bans, bot heuristics, honeypots, input cleanup, and traffic-spike handling.
WebGuard supplements Laravel's security features; it does not replace authentication, authorization, validation, CSRF protection, output escaping, or infrastructure-level controls.
Requirements
- PHP 8.2+
- Laravel 10, 11, 12, or 13
- Database support for the package's verification-token migration
- Google reCAPTCHA v2 keys if the Panic Shield challenge is enabled
The package declares illuminate/support, illuminate/http, illuminate/cache, and illuminate/database dependencies.
Installation
Install the package:
composer require newgeode/webguard
Laravel package auto-discovery registers the service provider. Publish the configuration:
php artisan vendor:publish --tag=webguard-publish-config
This publishes config/webguard.php. Run the application's migrations to create the verification-token table:
php artisan migrate
The migration adds an expires_at index for pruning and a composite (token, expires_at) index for verification-token lookups.
Registering the middleware
The package registers the webguard middleware alias. You can apply it to a route or route group:
use Illuminate\Support\Facades\Route; Route::middleware(['webguard'])->group(function () { Route::get('/dashboard', fn () => view('dashboard')); });
Alternatively, add WebGuard to the global middleware stack. For Laravel 11–13, import the middleware in bootstrap/app.php:
use NewGeode\WebGuard\Http\Middleware\WebGuard;
Then add it to the existing withMiddleware callback:
$middleware->append(WebGuard::class);
For Laravel 10, add the middleware to the global $middleware array in app/Http/Kernel.php.
Use either global registration or route-specific registration, not both for the same requests. If you rely on user-specific rate limits, ensure WebGuard runs after session and authentication middleware; global middleware can run before those have resolved the current user.
Configuration
Edit the published config/webguard.php. WebGuard is disabled by default, as are IP restrictions, trap routes, rate limiting, Panic Shield, bot protection, honeypot protection, and sanitization. Enable the master switch and each feature you intend to use.
Relevant configuration sections:
| Key | Purpose | Package default |
|---|---|---|
enabled |
Master middleware switch | false |
cache_config.default |
Cache store for counters and bans | webguard |
cache_config.webguard |
Built-in file-cache store settings | file, under storage/framework/cache/webguard |
log_config |
Security log channel settings | webguard, daily |
except |
Paths that skip WebGuard checks | up, api/*, webhooks/*, livewire/*, verification endpoint |
trusted_proxies.enabled |
Whether to configure trusted proxies | false |
force_https |
Redirect HTTP requests to HTTPS | false |
ip_restriction.enabled |
Enable IP allow/block lists | false |
trap_routes.enabled |
Enable trap-path detection | false |
rate_limit.enabled |
Enable request counters and limits | false |
panic_shield.enabled |
Enable global traffic spike checks | false |
bot_protection.enabled |
Enable user-agent/header heuristics | false |
honeypot.enabled |
Enable hidden-field detection | false |
sanitize.enabled |
Modify incoming string values | false |
The following environment settings are read by the default configuration:
WG_ENABLED=true WG_FORCE_HTTPS=false WG_LOG_CHANNEL=webguard
There is no WG_CACHE_STORE setting: select the cache store with WG_DEFAULT_CACHE or cache_config.default. WG_LOG_CHANNEL is supported and sets log_config.channel. Set log_config.retention_days to change log retention.
Security features
IP restrictions
Enable the feature and configure individual IP addresses or CIDR ranges:
'ip_restriction' => [ 'enabled' => true, 'ip_allowlist' => ['192.0.2.10', '198.51.100.0/24'], 'ip_blocklist' => ['203.0.113.25'], ],
The middleware checks the blocklist first. When the allowlist is non-empty, other IPs are denied. IP checks use the client IP reported by Laravel, so configure trusted proxies carefully.
Trusted proxies
Only enable trusted proxy handling when the application is behind a proxy, and list the actual proxy addresses or CIDRs:
'trusted_proxies' => [ 'enabled' => true, 'proxies' => ['10.0.0.10', '192.168.1.0/24'], ],
Do not use '*' on an internet-facing application. In the current middleware, '*' is expanded to all IPv4 and IPv6 addresses. That trusts forwarded headers from any client and can allow IP or host spoofing. If your hosting platform uses dynamic proxy addresses, follow its documented trusted-proxy configuration.
HTTPS enforcement
'force_https' => env('WG_FORCE_HTTPS', false),
When enabled, non-local HTTP requests receive a permanent HTTPS redirect. Configure TLS and proxy headers correctly before enabling this option.
Trap routes
Trap paths can catch common scans for sensitive files and administrative endpoints:
'trap_routes' => [ 'enabled' => true, 'ban_minutes' => 1440, 'paths' => [ '*.env*', 'wp-admin*', 'wp-login.php', 'xmlrpc.php', '*.git*', 'phpmyadmin*', 'vendor/phpunit/*', ], ],
A matching request is logged, its IP is temporarily banned, and the middleware returns HTTP 403. Review patterns for your application to avoid matching legitimate routes.
Rate limiting
Configure per-minute thresholds and whether to temporarily ban guests that exceed them:
'rate_limit' => [ 'enabled' => true, 'guest_per_minute' => 60, 'auth_per_minute' => 300, 'ban_guest_on_exceed' => true, 'ban_minutes' => 5, ],
Authenticated-user limits use the user's auth identifier; guest limits use the client IP. The current cache key expires a fixed time after its first hit; it is not a true rolling window or a calendar-aligned minute bucket. Ensure middleware ordering allows Laravel to resolve the authenticated user before relying on separate user limits.
Panic Shield and reCAPTCHA challenge
Panic Shield tracks global requests per minute and can apply a stricter guest limit and challenge during a traffic spike:
'panic_shield' => [ 'enabled' => true, 'spike_rpm_threshold' => 2000, 'duration_minutes' => 10, 'panic_guest_rpm' => 20, 'js_challenge' => [ 'enabled' => true, 'duration_seconds' => 10, 'token_expiration_minutes' => 30, 'gcaptcha' => [ 'public_key' => 'your-site-key', 'secret_key' => 'your-secret-key', 'hostname' => 'example.com', ], ], ],
Register keys for reCAPTCHA v2 and set the expected hostname for production. The hostname check is skipped when hostname is empty. The challenge page asks the visitor to complete reCAPTCHA, waits for the configured countdown, then reloads the page. A successful verification creates a database token tied to the visitor's IP and user agent; it does not create a browser cookie.
The spike_multiplier option shown in some older configuration examples is not used by the current middleware. Panic Shield activates when the RPM counter reaches or exceeds spike_rpm_threshold. Its stricter guest rate limit is enforced only when rate_limit.enabled is also true.
Bot heuristics
'bot_protection' => [ 'enabled' => true, 'block_empty_user_agent' => true, 'blocked_agents' => [ 'curl/', 'python-requests', 'Go-http-client', 'libwww-perl', 'wget', ], ],
When enabled, WebGuard can reject an empty user agent (controlled by block_empty_user_agent), configured user-agent substrings (case-insensitive), and requests without Accept or Accept-Language headers. These are heuristics, not proof that a client is a bot; test integrations and API clients before enabling the feature.
Honeypot
Enable a hidden form field to identify some automated submissions:
'honeypot' => [ 'enabled' => true, 'field' => 'webguard_field', 'ban_minutes' => 30, ],
Add the field to relevant forms:
<input type="text" name="webguard_field" value="" autocomplete="off" tabindex="-1" style="position:absolute;left:-9999px;" >
The middleware checks unauthenticated POST requests. A filled field triggers a temporary IP ban and an HTTP 403 response.
Input sanitization
'sanitize' => [ 'enabled' => false, 'trim_strings' => true, 'strip_null_bytes' => true, 'strip_tags' => true, 'except_fields' => [ 'password', 'confirm_password', 'password_confirmation', 'current_password', 'html_body', ], ],
When enabled, configured operations are applied recursively to string input values. This can change submitted data. Sanitization does not replace validation, output escaping, authorization, or context-aware HTML sanitization.
Excluded routes and responses
The default exclusions are up, api/*, webhooks/*, livewire/*, and ng-webguard-verify-site-connection. Excluded requests skip WebGuard's checks after trusted-proxy setup and HTTPS enforcement. In particular, the default api/* exclusion means API routes do not receive WebGuard's IP restrictions, bans, rate limits, bot checks, honeypot checks, or sanitization.
WebGuard returns package views for these conditions:
| View | Condition | Status |
|---|---|---|
access-denied |
Trap path | 403 |
user-banned |
Blocked or temporarily banned IP | 403 |
suspicious-traffic |
Bot heuristic rejects the request | 403 |
too-many-requests |
Rate limit exceeded | 429 |
spam-detected |
Honeypot field is filled | 403 |
verify-connection |
Panic Shield challenge | 202 |
The package loads views under the WGResourcesViews namespace. If a security view fails to render, the current middleware returns an empty HTML response with the intended status.
Logging
WebGuard registers a log channel if the configured channel name does not already exist. Its package defaults are:
'log_config' => [ 'channel' => env('WG_LOG_CHANNEL', 'webguard'), 'driver' => 'daily', 'path' => storage_path('logs/webguard/webguard.log'), 'level' => 'debug', 'retention_days' => 30, ],
The provider maps retention_days to Laravel's daily channel days option when it creates the channel. If your application already defines that channel in config/logging.php, configure its days value there; WebGuard leaves existing channels unchanged.
Security events include trap-route hits, guest rate-limit bans, honeypot detections, and Panic Shield activation. Check that the selected channel and log path are valid and writable.
Pruning expired verification tokens
The package registers the webguard:prune-tokens Artisan command to delete expired verification tokens. Run it manually:
php artisan webguard:prune-tokens
To run it automatically, schedule it daily using Laravel's scheduler:
use Illuminate\Support\Facades\Schedule; Schedule::command('webguard:prune-tokens')->daily();
Place this in routes/console.php on Laravel 11 and later, or add the command to the schedule method in app/Console/Kernel.php on Laravel 10. Configure Laravel's scheduler cron entry on the server for scheduled tasks to run.
Cache and operational notes
WebGuard stores counters, bans, and Panic Shield state in the configured Laravel cache store. The package default is a dedicated webguard file store under storage/framework/cache/webguard. For multiple application servers, use a shared Laravel cache backend such as Redis and set cache_config.default to the name of that store.
When using a named shared store, make sure it already exists in config/cache.php, or add it under cache_config using the same configuration structure. The service provider copies the selected package cache configuration into Laravel's cache configuration only when that store is not already defined.
Current implementation caveats to review before relying on these protections under production traffic:
- Rate-limit counters use a fixed TTL from the first request, not a rolling window.
- Rate-limit and RPM counter creation uses separate cache
hasandputoperations. Concurrent first requests can overwrite each other's initial count, undercounting traffic. - The middleware's
'*'trusted-proxy setting trusts all IP addresses; use explicit proxy ranges instead. - Expired verification tokens are not deleted during lookups; run or schedule
webguard:prune-tokens. The migration includes a standaloneexpires_atindex for pruning and a(token, expires_at)index for token lookups. - User-specific behavior depends on WebGuard running after session/authentication middleware.
- The package config's default
WG_LOG_PATHis already an absolutestorage_path(). The service provider passes it throughstorage_path()again when registering the channel, which can produce an invalid nested path. SettingWG_LOG_PATHto a relative path (for example,logs/webguard/webguard.log) avoids the double-prefix until the package code is corrected.
Testing
The package does not currently declare a PHPUnit test script or test dependencies in composer.json. Run package behavior checks through the host Laravel application's test suite, or add an appropriate Testbench and PHPUnit setup before publishing the package.
php artisan test
Troubleshooting
Configuration changes do not take effect
php artisan config:clear
If configuration is cached in production, rebuild it after making changes:
php artisan config:cache
Verification keeps failing
- Confirm the Google reCAPTCHA v2 site and secret keys are correct.
- Confirm the configured hostname matches the hostname Google returns.
- Confirm the token table migration has run.
- Check that the IP address and user agent are consistent between verification and the redirected request.
- Check the configured log channel for verification errors.
API, webhook, or Livewire requests bypass WebGuard
Review the except patterns. Excluded requests skip most WebGuard checks by design.
Legitimate clients are blocked
Review the bot-protection headers and blocked-agent list, and ensure the route is not unintentionally affected by IP allowlists or trap patterns.
License
This package is open-source software licensed under the MIT License.
Author
New Geode — newgeode/webguard