Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Spiderman Security Bundle Laravel Package

coderaf/spiderman-security-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require coderaf/spiderman-security-bundle
    

    Register the bundle in config/app.php under providers:

    Coderaf\SpiderManSecurityBundle\SpiderManSecurityServiceProvider::class,
    

    Publish the config file:

    php artisan vendor:publish --provider="Coderaf\SpiderManSecurityBundle\SpiderManSecurityServiceProvider" --tag=config
    
  2. Basic Configuration Edit config/spiderman-security.php to define:

    • Security rules (e.g., IP whitelisting, rate limiting).
    • Middleware priorities (e.g., where to place SpiderManSecurityMiddleware in the stack).
    • Logging settings (e.g., failed attempts, blocked IPs).
  3. First Use Case: IP Whitelisting Define allowed IPs in the config:

    'ip_whitelist' => [
        '192.168.1.1',
        '127.0.0.1',
    ],
    

    Place the middleware in app/Http/Kernel.php:

    protected $middleware = [
        \Coderaf\SpiderManSecurityBundle\Http\Middleware\SpiderManSecurityMiddleware::class,
        // ... other middleware
    ];
    

    Test by accessing a route from a non-whitelisted IP—it should be blocked.


Implementation Patterns

1. Rule-Based Security

  • Dynamic Rules: Extend the bundle by creating custom rules (e.g., user-agent blocking, geolocation restrictions).

    // app/Rules/CustomRule.php
    namespace App\Rules;
    use Coderaf\SpiderManSecurityBundle\Contracts\SecurityRuleInterface;
    
    class CustomRule implements SecurityRuleInterface {
        public function check($request) {
            return $request->userAgent() !== 'BadBot/1.0';
        }
    }
    

    Register in spiderman-security.php:

    'custom_rules' => [
        \App\Rules\CustomRule::class,
    ],
    
  • Priority Handling: Rules are evaluated in order. Place stricter rules (e.g., IP whitelist) before looser ones (e.g., rate limiting).

2. Rate Limiting

Configure in spiderman-security.php:

'rate_limits' => [
    'login_attempts' => [
        'max_attempts' => 5,
        'time_window' => '10 minutes',
        'key' => 'login_attempts',
    ],
],

Use the RateLimit trait in controllers:

use Coderaf\SpiderManSecurityBundle\Traits\RateLimit;

class LoginController extends Controller {
    use RateLimit;

    public function attemptLogin() {
        $this->checkRateLimit('login_attempts');
        // ... login logic
    }
}

3. Middleware Integration

  • Conditional Application: Use the middleware only for specific routes:
    Route::middleware(['web', 'spiderman.security'])->group(function () {
        // Admin routes
    });
    
  • Custom Logic: Extend the middleware to add pre/post-processing:
    namespace App\Http\Middleware;
    use Coderaf\SpiderManSecurityBundle\Http\Middleware\SpiderManSecurityMiddleware;
    
    class CustomSecurityMiddleware extends SpiderManSecurityMiddleware {
        protected function handleBlockedRequest($request, $response) {
            // Custom response (e.g., redirect to CAPTCHA)
            return redirect()->route('captcha');
        }
    }
    

4. Logging and Monitoring

  • Log Failed Attempts: Enable logging in config:
    'logging' => [
        'enabled' => true,
        'path' => storage_path('logs/spiderman-security.log'),
    ],
    
  • Monitor Blocked IPs: Query the spiderman_security_logs table for patterns:
    $blockedIps = \DB::table('spiderman_security_logs')
        ->where('action', 'blocked')
        ->groupBy('ip')
        ->orderBy('count', 'desc')
        ->take(10)
        ->get();
    

Gotchas and Tips

Pitfalls

  1. Middleware Order Matters

    • Place SpiderManSecurityMiddleware before authentication middleware (e.g., auth). Otherwise, blocked requests may bypass checks.
    • Example (in app/Http/Kernel.php):
      protected $middlewareGroups = [
          'web' => [
              \Coderaf\SpiderManSecurityBundle\Http\Middleware\SpiderManSecurityMiddleware::class,
              \App\Http\Middleware\TrustProxies::class,
              // ... other middleware
          ],
      ];
      
  2. Rate Limit Key Collisions

    • Ensure key in rate_limits is unique per route/action to avoid shared counters.
    • Example: Use user_id or ip as part of the key:
      'key' => 'login_attempts_{$request->ip()}_{$request->user()->id}',
      
  3. Config Overrides

    • Bundle config is not cached by default. Clear config after changes:
      php artisan config:clear
      
  4. Performance Impact

    • Rules are evaluated synchronously on every request. For high-traffic apps:
      • Cache whitelists (e.g., ip_whitelist) in a static array.
      • Use Redis for rate limiting instead of database.

Debugging Tips

  1. Enable Verbose Logging Temporarily set 'debug' => true in config to log rule evaluations:

    'logging' => [
        'debug' => true,
    ],
    
  2. Check Middleware Execution Add a debug endpoint to test rules:

    Route::get('/debug-security', function () {
        $rules = app('spiderman.security.rules');
        foreach ($rules as $rule) {
            dd($rule->check(request()));
        }
    });
    
  3. Database Locks If using database-backed rate limiting, ensure transactions are short to avoid locks:

    \DB::transaction(function () use ($request) {
        $this->checkRateLimit('login_attempts');
    });
    

Extension Points

  1. Custom Rule Storage Override the default rule storage (e.g., switch from database to Redis):

    // app/Providers/SpiderManSecurityServiceProvider.php
    public function register() {
        $this->app->bind(
            \Coderaf\SpiderManSecurityBundle\Contracts\RuleStorageInterface::class,
            \App\Services\RedisRuleStorage::class
        );
    }
    
  2. Event Listeners Listen for security events (e.g., SpiderManSecurity.Blocked):

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        \Coderaf\SpiderManSecurityBundle\Events\SecurityBlocked::class => [
           \App\Listeners\LogBlockedAttempt::class,
       ],
    ];
    
  3. API-Specific Rules For APIs, combine with Laravel's throttle middleware:

    Route::middleware(['throttle:60,1', 'spiderman.security'])->group(function () {
        // API routes
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums