Weave Code
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

Laravel Surveillance Laravel Package

neelkanthk/laravel-surveillance

Monitor and control suspicious users in Laravel: track IPs and browser fingerprints, write surveillance logs, and block/allow access. Includes route middleware, CLI commands, and a fluent API; storage is extensible (MySQL by default).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require neelkanthk/laravel-surveillance
    php artisan vendor:publish --provider="Neelkanth\Laravel\Surveillance\Providers\SurveillanceServiceProvider" --tag="migrations"
    php artisan vendor:publish --provider="Neelkanth\Laravel\Surveillance\Providers\SurveillanceServiceProvider" --tag="config"
    php artisan migrate
    
  2. First Use Case:

    • Enable Surveillance for an IP via CLI:
      php artisan surveillance:enable ip 192.168.1.1
      
    • Apply Middleware to Routes:
      Route::middleware(['surveillance'])->group(function () {
          // Protected routes
      });
      
  3. Where to Look First:

    • Config File: config/surveillance.php (customize fingerprint-header-key or override repositories).
    • CLI Commands: List available commands with php artisan surveillance:.

Implementation Patterns

Usage Patterns

  1. Middleware Integration:

    • Apply surveillance middleware to route groups or individual routes to log requests for monitored entities (IPs, user IDs, or fingerprints).
    • Example:
      Route::middleware(['auth', 'surveillance'])->get('/admin', 'AdminController@index');
      
  2. Programmatic Control:

    • Use the Surveillance facade for runtime adjustments:
      // Enable surveillance for a user ID
      Surveillance::manager()->type('userid')->value(123)->enableSurveillance();
      
      // Block a fingerprint
      Surveillance::manager()->type('fingerprint')->value('abc123')->blockAccess();
      
      // Log a request (auto-populates with request data)
      Surveillance::logger()->writeLog();
      
  3. CLI Workflows:

    • Batch Management: Disable surveillance for all IPs in a range:
      # Disable surveillance for a range of IPs (requires custom script)
      php artisan surveillance:disable ip 192.168.1.0/24
      
    • Automate Blocking: Use Artisan commands in deployment scripts to block known malicious entities post-migration.
  4. Event-Driven Logging:

    • Extend SurveillanceLogRepository to log custom events (e.g., failed payments, brute-force attempts):
      // In an event listener
      Surveillance::logger()->setLogToWrite([
          'event' => 'payment_failed',
          'details' => $payment->toArray()
      ])->writeLog();
      

Integration Tips

  1. Browser Fingerprinting:

    • Pair with FingerprintJS to capture fingerprints client-side and send via the configured header (fingerprint-header-key).
    • Example JavaScript:
      FingerprintJS.load().then(fp => fp.get()).then(result => {
          fetch('/set-fingerprint', {
              method: 'POST',
              headers: { 'fingerprint': result.visitorId }
          });
      });
      
  2. Custom Storage:

    • Override SurveillanceManagerRepository or SurveillanceLogRepository to use Redis, Elasticsearch, or a custom database:
      // config/surveillance.php
      'manager-repository' => App\Repositories\RedisSurveillanceManager::class,
      'log-repository' => App\Repositories\ElasticSurveillanceLogger::class,
      
  3. Laravel Events:

    • Trigger surveillance logs from Laravel events (e.g., illuminate\auth\events\Failed):
      use Neelkanth\Laravel\Surveillance\Facades\Surveillance;
      
      event(new Failed($request, $credentials));
      Surveillance::logger()->writeLog(['event' => 'auth.failed', 'attempt' => $request->input('email')]);
      
  4. API Rate Limiting:

    • Combine with Laravel’s rate limiting to block IPs programmatically:
      if (request()->ip() === '192.168.1.100') {
          Surveillance::manager()->type('ip')->value(request()->ip())->blockAccess();
          abort(429, 'Access blocked');
      }
      

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Issue: Surveillance logs can bloat the database if enabled for high-traffic routes.
    • Fix: Use a queue (Surveillance::logger()->queueLog()) or limit log retention via database indexes:
      // Add to SurveillanceLogs migration
      $table->index(['created_at']);
      
  2. False Positives:

    • Issue: Blocking IPs/fingerprints may inadvertently block legitimate users (e.g., shared networks, VPNs).
    • Fix: Implement a whitelist or manual review process for blocked entities.
  3. Fingerprint Collisions:

    • Issue: Browser fingerprints may collide (different users getting the same fingerprint).
    • Fix: Combine with IP/user ID for higher accuracy or use a more robust library like FingerprintJS Pro.
  4. Middleware Order:

    • Issue: Surveillance middleware must run after authentication middleware to capture user IDs.
    • Fix: Order middleware in app/Http/Kernel.php:
      protected $middlewareGroups = [
          'web' => [
              \App\Http\Middleware\Authenticate::class,
              \Neelkanth\Laravel\Surveillance\Http\Middleware\Surveillance::class,
              // ...
          ],
      ];
      
  5. Database Locking:

    • Issue: Concurrent CLI commands (e.g., surveillance:block) may cause race conditions.
    • Fix: Use database transactions or locks:
      DB::transaction(function () {
          Surveillance::manager()->type('ip')->value('192.168.1.1')->blockAccess();
      });
      

Debugging

  1. Log Inspection:

    • Query the surveillance_logs table to verify logs:
      SELECT * FROM surveillance_logs WHERE type = 'ip' AND value = '192.168.1.1' ORDER BY created_at DESC;
      
  2. Middleware Debugging:

    • Temporarily log middleware execution:
      // In SurveillanceMiddleware.php
      public function handle($request, Closure $next) {
          \Log::info('Surveillance middleware triggered for IP: ' . $request->ip());
          return $next($request);
      }
      
  3. CLI Command Errors:

    • Check for typos in command arguments (e.g., userid vs. user_id):
      php artisan surveillance:enable userid 123  # Correct
      php artisan surveillance:enable user_id 123 # Fails
      

Tips

  1. Combine with Laravel Policies:

    • Use surveillance to enforce custom policies:
      public function authorize(Role $role) {
          if (Surveillance::manager()->type('userid')->value(auth()->id())->isBlocked()) {
              abort(403);
          }
          return $role->isAdmin();
      }
      
  2. Automate Surveillance:

    • Schedule CLI commands via Laravel Scheduler:
      // app/Console/Kernel.php
      protected function schedule(Schedule $schedule) {
          $schedule->command('surveillance:disable ip 192.168.1.100')->dailyAt('03:00');
      }
      
  3. Custom Log Fields:

    • Extend SurveillanceLogRepository to include additional metadata:
      public function writeLog($data = []) {
          $data['custom_field'] = 'value';
          parent::writeLog($data);
      }
      
  4. UI Integration:

  5. Testing:

    • Mock the Surveillance facade in tests:
      Surveillance::shouldReceive('logger()->writeLog')->once();
      
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony