PHPackages                             litesoc/litesoc-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. litesoc/litesoc-php

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

litesoc/litesoc-php
===================

Official PHP SDK for LiteSOC - Security event tracking and threat detection

v2.5.0(4mo ago)00MITPHPPHP ^8.2CI passing

Since Feb 22Pushed 4mo agoCompare

[ Source](https://github.com/LiteSOC/litesoc-php)[ Packagist](https://packagist.org/packages/litesoc/litesoc-php)[ Docs](https://www.litesoc.io)[ RSS](/packages/litesoc-litesoc-php/feed)WikiDiscussions main Synced today

READMEChangelog (4)Dependencies (8)Versions (10)Used By (0)

LiteSOC PHP SDK
===============

[](#litesoc-php-sdk)

Official PHP SDK for [LiteSOC](https://www.litesoc.io) - Security event tracking and threat detection for your applications.

[![Latest Stable Version](https://camo.githubusercontent.com/548d05b42e753914ca9a979806bcfcce64960567253d35c1e3941bd1552efbe5/68747470733a2f2f706f7365722e707567782e6f72672f6c697465736f632f6c697465736f632d7068702f76)](https://packagist.org/packages/litesoc/litesoc-php)[![PHP Version](https://camo.githubusercontent.com/2560d3a485198d966f33551daed52f34eac0ac2c228b94ee89022f9a10a1944b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6c697465736f632f6c697465736f632d706870)](https://packagist.org/packages/litesoc/litesoc-php)[![Tests](https://github.com/LiteSOC/litesoc-php/actions/workflows/ci.yml/badge.svg)](https://github.com/LiteSOC/litesoc-php/actions/workflows/ci.yml)[![PHPStan](https://camo.githubusercontent.com/b6d441ad4fe8332cb16c72aa27f22cc685181dfd74ae34964afc92c6c1146b3c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c2532306d61782d627269676874677265656e2e737667)](https://phpstan.org/)[![License](https://camo.githubusercontent.com/0f468d89383d074abf811cbcf0f947aec52e381d214628c4c96790fa5bccfc4b/68747470733a2f2f706f7365722e707567782e6f72672f6c697465736f632f6c697465736f632d7068702f6c6963656e7365)](https://packagist.org/packages/litesoc/litesoc-php)

Installation
------------

[](#installation)

```
composer require litesoc/litesoc-php
```

Quick Start
-----------

[](#quick-start)

```
use LiteSOC\LiteSOC;

// Initialize the SDK
$litesoc = new LiteSOC('your-api-key');

// Track a login failure - LiteSOC auto-enriches with GeoIP & Network Intelligence
$litesoc->track('auth.login_failed', [
    'actor_id' => 'user_123',
    'actor_email' => 'user@example.com',
    'user_ip' => '192.168.1.1',  // Required for Security Intelligence
    'metadata' => ['reason' => 'invalid_password']
]);

// Flush remaining events before shutdown
$litesoc->flush();
```

Features
--------

[](#features)

- ✅ **26 standard security event types** - Authentication, authorization, admin, data, and security events
- ✅ **Management API** - Query alerts and events programmatically (Business/Enterprise plans)
- ✅ **Custom exceptions** - Specific exceptions for auth, rate limits, and plan restrictions
- ✅ **Automatic batching** - Events are batched for efficient delivery
- ✅ **Batch ingestion helper** - `trackBatch()` sends up to 100 events in a single request
- ✅ **Retry logic** - Failed events are automatically retried
- ✅ **Laravel integration** - Service provider, facade, and config publishing
- ✅ **PHP 8.2+** - Modern PHP with full type declarations
- 🗺️ **GeoIP Enrichment** - Automatic location data from IP addresses
- 🛡️ **Network Intelligence** - VPN, Tor, Proxy &amp; Datacenter detection
- 📊 **Threat Scoring** - Auto-assigned severity (Low → Critical)

Security Intelligence (Automatic Enrichment)
--------------------------------------------

[](#security-intelligence-automatic-enrichment)

When you provide `user_ip`, LiteSOC automatically enriches your events with:

### 🗺️ Geolocation

[](#️-geolocation)

- Country &amp; City resolution
- Latitude/Longitude coordinates
- Interactive map visualization in dashboard

### 🛡️ Network Intelligence

[](#️-network-intelligence)

- **VPN Detection** - NordVPN, ExpressVPN, Surfshark, etc.
- **Tor Exit Nodes** - Anonymizing network detection
- **Proxy Detection** - HTTP/SOCKS proxy identification
- **Datacenter IPs** - AWS, GCP, Azure, DigitalOcean, etc.

### 📊 Threat Scoring

[](#-threat-scoring)

Events are auto-classified by severity:

- **Low** - Normal activity
- **Medium** - Unusual patterns
- **High** - Suspicious behavior
- **Critical** - Active threats (triggers instant alerts)

> **Important**: Always include `user_ip` for full Security Intelligence features.

Configuration Options
---------------------

[](#configuration-options)

```
use LiteSOC\LiteSOC;

$litesoc = new LiteSOC('your-api-key', [
    'endpoint' => 'https://...',      // Custom API endpoint
    'batching' => true,                // Enable event batching (default: true)
    'batch_size' => 10,                // Events before auto-flush (default: 10)
    'flush_interval' => 5.0,           // Seconds between auto-flushes (default: 5.0)
    'debug' => false,                  // Enable debug logging (default: false)
    'silent' => true,                  // Fail silently on errors (default: true)
    'timeout' => 5.0,                  // Request timeout in seconds (default: 5.0)
]);
```

Tracking Events
---------------

[](#tracking-events)

### Basic Usage

[](#basic-usage)

```
// Track any event type
$litesoc->track('auth.login_failed', [
    'actor_id' => 'user_123',
    'actor_email' => 'user@example.com',
    'user_ip' => '192.168.1.1'
]);
```

### Batch Ingestion with `trackBatch` (v2.5.0+)

[](#batch-ingestion-with-trackbatch-v250)

To reduce HTTP overhead and align with the backend batch ingestion contract, you can send up to **100 events** in a single call:

```
use LiteSOC\LiteSOC;

$litesoc = new LiteSOC('your-api-key');

$accepted = $litesoc->trackBatch([
    [
        'event_name'  => 'auth.login_success',
        'actor_id'    => 'user_123',
        'actor_email' => 'user@example.com',
        'user_ip'     => '203.0.113.50',
        'metadata'    => ['method' => 'password'],
    ],
    [
        'event_name' => 'data.export',
        'actor_id'   => 'user_123',
        'user_ip'    => '203.0.113.50',
        'metadata'   => ['table' => 'orders', 'rows' => 500],
    ],
]);

echo "{$accepted} events accepted";
```

### Using Event Type Constants

[](#using-event-type-constants)

```
use LiteSOC\EventType;

$litesoc->track(EventType::AUTH_LOGIN_FAILED, [
    'actor_id' => 'user_123',
    'user_ip' => '192.168.1.1'
]);
```

### Using SecurityEvents Class

[](#using-securityevents-class)

```
use LiteSOC\SecurityEvents;

// Use predefined security event types
$litesoc->track(SecurityEvents::AUTH_LOGIN_FAILED, [
    'actor_id' => 'user_123',
    'user_ip' => '192.168.1.1'
]);

// Get all 26 standard events
$allEvents = SecurityEvents::all();

// Validate an event type
if (SecurityEvents::isValid('auth.login_failed')) {
    // Valid standard event
}
```

### With Severity Level

[](#with-severity-level)

```
use LiteSOC\EventSeverity;

$litesoc->track('security.suspicious_activity', [
    'actor_id' => 'user_123',
    'user_ip' => '192.168.1.1',
    'severity' => EventSeverity::CRITICAL,
    'metadata' => ['reason' => 'impossible travel detected']
]);
```

### With Metadata

[](#with-metadata)

```
$litesoc->track('data.export', [
    'actor_id' => 'user_123',
    'user_ip' => '192.168.1.1',
    'metadata' => [
        'file_type' => 'csv',
        'record_count' => 1000,
        'export_reason' => 'monthly_report'
    ]
]);
```

Convenience Methods
-------------------

[](#convenience-methods)

The SDK provides convenience methods for common security events:

```
// Track login failures
$litesoc->trackLoginFailed('user_123', ['user_ip' => '192.168.1.1']);

// Track login successes
$litesoc->trackLoginSuccess('user_123', ['user_ip' => '192.168.1.1']);

// Track privilege escalation (critical severity)
$litesoc->trackPrivilegeEscalation('admin_user', ['user_ip' => '192.168.1.1']);

// Track sensitive data access (high severity)
$litesoc->trackSensitiveAccess('user_123', 'customer_pii_table', ['user_ip' => '192.168.1.1']);

// Track bulk deletions (high severity)
$litesoc->trackBulkDelete('admin_user', 500, ['user_ip' => '192.168.1.1']);

// Track role changes
$litesoc->trackRoleChanged('user_123', 'viewer', 'admin', ['user_ip' => '192.168.1.1']);

// Track access denied
$litesoc->trackAccessDenied('user_123', '/admin/settings', ['user_ip' => '192.168.1.1']);
```

Laravel Integration
-------------------

[](#laravel-integration)

### Installation

[](#installation-1)

```
composer require litesoc/litesoc-php
```

The package auto-discovers the service provider and facade.

### Configuration

[](#configuration)

Publish the config file:

```
php artisan vendor:publish --tag=litesoc-config
```

Add your API key to `.env`:

```
LITESOC_API_KEY=your-api-key
```

### Usage with Facade

[](#usage-with-facade)

```
use LiteSOC\Laravel\Facades\LiteSOC;

// Track events using the facade
LiteSOC::track('auth.login_failed', [
    'actor_id' => auth()->id(),
    'user_ip' => request()->ip()
]);

// Use convenience methods
LiteSOC::trackLoginSuccess(auth()->id(), [
    'actor_email' => auth()->user()->email,
    'user_ip' => request()->ip()
]);
```

### Usage with Dependency Injection

[](#usage-with-dependency-injection)

```
use LiteSOC\LiteSOC;

class LoginController extends Controller
{
    public function __construct(
        private LiteSOC $litesoc
    ) {}

    public function login(Request $request)
    {
        // Attempt authentication
        if (Auth::attempt($request->only('email', 'password'))) {
            $this->litesoc->trackLoginSuccess(auth()->id(), [
                'actor_email' => auth()->user()->email,
                'user_ip' => $request->ip()
            ]);
            return redirect('/dashboard');
        }

        $this->litesoc->trackLoginFailed($request->email, [
            'user_ip' => $request->ip()
        ]);
        return back()->withErrors(['email' => 'Invalid credentials']);
    }
}
```

### Event Listener Integration

[](#event-listener-integration)

```
// app/Providers/EventServiceProvider.php
protected $listen = [
    \Illuminate\Auth\Events\Login::class => [
        \App\Listeners\TrackLoginSuccess::class,
    ],
    \Illuminate\Auth\Events\Failed::class => [
        \App\Listeners\TrackLoginFailed::class,
    ],
];

// app/Listeners/TrackLoginSuccess.php
use LiteSOC\Laravel\Facades\LiteSOC;
use Illuminate\Auth\Events\Login;

class TrackLoginSuccess
{
    public function handle(Login $event): void
    {
        LiteSOC::trackLoginSuccess($event->user->id, [
            'actor_email' => $event->user->email,
            'user_ip' => request()->ip()
        ]);
    }
}

// app/Listeners/TrackLoginFailed.php
use LiteSOC\Laravel\Facades\LiteSOC;
use Illuminate\Auth\Events\Failed;

class TrackLoginFailed
{
    public function handle(Failed $event): void
    {
        LiteSOC::trackLoginFailed($event->credentials['email'] ?? 'unknown', [
            'user_ip' => request()->ip()
        ]);
    }
}
```

### Middleware for Auth Events

[](#middleware-for-auth-events)

```
// app/Http/Middleware/TrackSecurityEvents.php
namespace App\Http\Middleware;

use Closure;
use LiteSOC\Laravel\Facades\LiteSOC;

class TrackSecurityEvents
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        // Track access denied (403 responses)
        if ($response->status() === 403) {
            LiteSOC::trackAccessDenied(
                auth()->id() ?? 'anonymous',
                $request->path(),
                ['user_ip' => $request->ip()]
            );
        }
    }
}
```

Event Types
-----------

[](#event-types)

### 26 Standard Events (Primary)

[](#26-standard-events-primary)

These are the primary events for comprehensive security coverage:

CategoryEvent TypeDescription**Auth**`auth.login_success`Successful user login**Auth**`auth.login_failed`Failed login attempt**Auth**`auth.logout`User logout**Auth**`auth.password_reset`Password reset completed**Auth**`auth.mfa_enabled`MFA enabled on account**Auth**`auth.mfa_disabled`MFA disabled on account**Auth**`auth.session_expired`Session timeout/expiry**Auth**`auth.token_refreshed`Token refresh**Authz**`authz.role_changed`User role modified**Authz**`authz.permission_granted`Permission assigned**Authz**`authz.permission_revoked`Permission removed**Authz**`authz.access_denied`Access denied event**Admin**`admin.privilege_escalation`Admin privilege escalation**Admin**`admin.user_impersonation`Admin impersonating user**Admin**`admin.settings_changed`System settings modified**Admin**`admin.api_key_created`New API key generated**Admin**`admin.api_key_revoked`API key revoked**Admin**`admin.user_suspended`User account suspended**Admin**`admin.user_deleted`User account deleted**Data**`data.bulk_delete`Bulk data deletion**Data**`data.sensitive_access`PII/sensitive data accessed**Data**`data.export`Data export operation**Security**`security.suspicious_activity`Suspicious behavior detected**Security**`security.rate_limit_exceeded`Rate limit triggered**Security**`security.ip_blocked`IP address blocked**Security**`security.brute_force_detected`Brute force attack detected### Extended Events (Backward Compatible)

[](#extended-events-backward-compatible)

Additional events for granular tracking:

- `auth.password_changed`, `auth.password_reset_requested`, `auth.mfa_challenge_success`, `auth.mfa_challenge_failed`, `auth.session_created`
- `user.created`, `user.updated`, `user.deleted`, `user.email_changed`, `user.profile_updated`
- `authz.role_assigned`, `authz.role_removed`, `authz.access_granted`
- `admin.invite_sent`, `admin.invite_accepted`, `admin.member_removed`
- `data.import`, `data.bulk_update`, `data.download`, `data.upload`, `data.shared`
- `security.ip_unblocked`, `security.account_locked`, `security.impossible_travel`, `security.geo_anomaly`
- `api.key_used`, `api.rate_limited`, `api.error`, `api.webhook_sent`, `api.webhook_failed`
- `billing.subscription_created`, `billing.subscription_cancelled`, `billing.payment_succeeded`, `billing.payment_failed`

Queue Management
----------------

[](#queue-management)

```
// Get current queue size
$queueSize = $litesoc->getQueueSize();

// Manually flush all events
$litesoc->flush();

// Clear queue without sending
$litesoc->clearQueue();

// Graceful shutdown
$litesoc->shutdown();
```

Management API (Business/Enterprise)
------------------------------------

[](#management-api-businessenterprise)

The Management API allows you to query alerts and events programmatically. Requires a Business or Enterprise plan.

> **API Endpoints**: These methods interact with `/api/v1/alerts` and `/api/v1/events`

### Get Alerts

[](#get-alerts)

```
use LiteSOC\LiteSOC;

$litesoc = new LiteSOC('your-api-key');

// Get all alerts
$result = $litesoc->getAlerts();
// Returns:
// [
//     'success' => true,
//     'data' => [
//         ['id' => 'alert_123', 'alert_type' => 'impossible_travel', 'severity' => 'critical', ...],
//         ['id' => 'alert_456', 'alert_type' => 'brute_force', 'severity' => 'warning', ...],
//     ],
//     'pagination' => ['total' => 42, 'limit' => 20, 'offset' => 0, 'has_more' => true],
//     'meta' => ['plan' => 'business', 'retention_days' => 90]
// ]

// Get alerts with filters
$result = $litesoc->getAlerts([
    'severity' => 'critical',         // 'critical', 'warning', 'info'
    'status' => 'active',             // 'active', 'resolved', 'safe'
    'alert_type' => 'impossible_travel',
    'limit' => 10,
    'offset' => 0,
]);

// Access alerts from the response
foreach ($result['data'] as $alert) {
    echo $alert['id'] . ': ' . $alert['title'];
}
```

### Get Single Alert

[](#get-single-alert)

```
$result = $litesoc->getAlert('alert_abc123');
// Returns:
// [
//     'success' => true,
//     'data' => [
//         'id' => 'alert_abc123',
//         'alert_type' => 'impossible_travel',
//         'severity' => 'critical',
//         'status' => 'active',
//         'title' => 'Impossible Travel Detected',
//         'description' => 'Login from New York, then Tokyo within 30 minutes',
//         'actor_id' => 'user_123',
//         'trigger_event_id' => 'evt_xyz789',
//         'created_at' => '2026-03-02T10:30:00Z',
//         'forensics' => [...],  // Network intelligence & geolocation (Pro/Enterprise)
//     ],
//     'meta' => ['plan' => 'business', 'retention_days' => 90]
// ]

$alert = $result['data'];
echo $alert['title'] . ' - ' . $alert['severity'];
```

### Resolve Alert

[](#resolve-alert)

```
// Mark an alert as resolved with resolution type and notes
$result = $litesoc->resolveAlert(
    'alert_abc123',
    'blocked_ip',                    // Resolution type: 'blocked_ip', 'false_positive', 'investigated', etc.
    'Blocked IP in firewall'         // Internal notes (optional)
);
// Returns:
// [
//     'success' => true,
//     'data' => ['id' => 'alert_abc123', 'status' => 'resolved', 'resolved_at' => '...'],
// ]

// Mark an alert as safe (false positive)
$result = $litesoc->markAlertSafe(
    'alert_abc123',
    'Expected behavior from automated testing'  // Internal notes (optional)
);
// Returns:
// [
//     'success' => true,
//     'data' => ['id' => 'alert_abc123', 'status' => 'safe'],
// ]
```

### Get Events

[](#get-events)

```
// Get recent events (default limit: 20)
$result = $litesoc->getEvents();
// Returns:
// [
//     'success' => true,
//     'data' => [...events],
//     'pagination' => ['total' => 100, 'limit' => 20, 'offset' => 0, 'has_more' => true],
//     'meta' => ['plan' => 'business', 'retention_days' => 90, 'redacted' => false]
// ]

// Get events with filters
$result = $litesoc->getEvents(50, [
    'event_name' => 'auth.login_failed',  // Filter by event type
    'actor_id' => 'user_123',             // Filter by actor
    'severity' => 'critical',             // 'critical', 'warning', or 'info'
    'offset' => 10,                       // Pagination offset
]);

// Access events from the response
foreach ($result['data'] as $event) {
    echo $event['event_name'] . ': ' . $event['actor']['id'];
}
```

### Get Single Event

[](#get-single-event)

```
$result = $litesoc->getEvent('event_xyz789');
// Returns:
// [
//     'success' => true,
//     'data' => [...event data],
//     'meta' => ['plan' => 'business', 'retention_days' => 90, 'redacted' => false]
// ]

$event = $result['data'];
echo $event['event_name'];
```

Plan Awareness &amp; Quota Headers
----------------------------------

[](#plan-awareness--quota-headers)

The SDK automatically captures plan and quota information from API response headers:

### Response Metadata

[](#response-metadata)

After any Management API call, you can access plan information:

```
use LiteSOC\LiteSOC;

$litesoc = new LiteSOC('your-api-key');

// Make an API call first
$alerts = $litesoc->getAlerts();

// Get plan metadata from response headers
$planInfo = $litesoc->getPlanInfo();

if ($planInfo) {
    echo "Plan: " . $planInfo->plan;              // e.g., "business", "enterprise"
    echo "Retention: " . $planInfo->retentionDays . " days";
    echo "Cutoff: " . $planInfo->cutoffDate;       // ISO 8601 timestamp
}

// Check if plan info is available
if ($litesoc->hasPlanInfo()) {
    // Plan data has been populated
}
```

### Headers Parsed

[](#headers-parsed)

HeaderPropertyDescription`X-LiteSOC-Plan``plan`Current plan name (starter, business, enterprise)`X-LiteSOC-Retention``retentionDays`Data retention period in days`X-LiteSOC-Cutoff``cutoffDate`Earliest accessible data timestamp### ResponseMetadata Class

[](#responsemetadata-class)

```
use LiteSOC\ResponseMetadata;

// Access properties directly (readonly)
$planInfo = $litesoc->getPlanInfo();
$plan = $planInfo->plan;                 // string|null
$days = $planInfo->retentionDays;        // int|null
$cutoff = $planInfo->cutoffDate;         // string|null

// Helper methods
$planInfo->hasPlanInfo();                // bool
$planInfo->hasRetentionInfo();           // bool
$planInfo->toArray();                    // array
```

### Plan-Restricted Features (403 Handling)

[](#plan-restricted-features-403-handling)

When accessing features that require a higher plan, the SDK throws `PlanRestrictedException`:

```
use LiteSOC\Exceptions\PlanRestrictedException;

try {
    $alerts = $litesoc->getAlerts();
} catch (PlanRestrictedException $e) {
    echo "Upgrade required: " . $e->getMessage();
    echo "Upgrade at: " . $e->getUpgradeUrl();  // https://www.litesoc.io/pricing
    echo "Required plan: " . $e->getRequiredPlan();
}
```

Exception Handling
------------------

[](#exception-handling)

The SDK provides specific exceptions for different error scenarios:

```
use LiteSOC\LiteSOC;
use LiteSOC\Exceptions\LiteSOCException;
use LiteSOC\Exceptions\AuthenticationException;
use LiteSOC\Exceptions\RateLimitException;
use LiteSOC\Exceptions\PlanRestrictedException;

$litesoc = new LiteSOC('your-api-key', ['silent' => false]);

try {
    $alerts = $litesoc->getAlerts();
} catch (AuthenticationException $e) {
    // Invalid or missing API key (401)
    error_log('Auth failed: ' . $e->getMessage());
} catch (PlanRestrictedException $e) {
    // Feature requires higher plan (403)
    error_log('Upgrade required: ' . $e->getRequiredPlan());
} catch (RateLimitException $e) {
    // Rate limit exceeded (429)
    error_log('Rate limited. Retry after: ' . $e->getRetryAfter() . ' seconds');
} catch (LiteSOCException $e) {
    // Other API errors
    error_log('API error: ' . $e->getMessage() . ' (Status: ' . $e->getStatusCode() . ')');
}
```

### Exception Hierarchy

[](#exception-hierarchy)

```
LiteSOCException (base)
├── AuthenticationException (401)
├── PlanRestrictedException (403)
└── RateLimitException (429)

```

Error Handling (Silent Mode)
----------------------------

[](#error-handling-silent-mode)

By default, the SDK fails silently (`silent => true`). To catch errors:

```
$litesoc = new LiteSOC('your-api-key', ['silent' => false]);

try {
    $litesoc->track('auth.login_failed', ['actor_id' => 'user_123']);
    $litesoc->flush();
} catch (\Exception $e) {
    // Handle error
    error_log("Failed to track event: " . $e->getMessage());
}
```

Debug Mode
----------

[](#debug-mode)

Enable debug logging to troubleshoot issues:

```
$litesoc = new LiteSOC('your-api-key', ['debug' => true]);
// Logs will be printed to stdout
```

For Laravel, set in your `.env`:

```
LITESOC_DEBUG=true
```

Non-Blocking / Async Usage
--------------------------

[](#non-blocking--async-usage)

By default, the SDK is synchronous - HTTP requests block until complete. However, the SDK has safeguards:

- **Silent mode** (`silent => true` default): Errors are logged, not thrown
- **Timeout** (`timeout => 30.0` default): Prevents indefinite blocking
- **Batching**: Reduces number of HTTP calls

### True Non-Blocking with `fastcgi_finish_request()`

[](#true-non-blocking-with-fastcgi_finish_request)

For PHP-FPM environments (Laravel, Symfony, etc.), you can achieve true non-blocking behavior by sending the response to the client before flushing events:

```
// In a controller or middleware
public function login(Request $request)
{
    // ... authentication logic ...

    // Queue the security event (fast, no HTTP call yet)
    $litesoc->track('auth.login_success', [
        'actor_id' => auth()->id(),
        'user_ip' => $request->ip()
    ]);

    // Return response to client immediately
    $response = redirect('/dashboard');

    // Finish the request - client receives response NOW
    if (function_exists('fastcgi_finish_request')) {
        // Send response headers and body to client
        $response->send();

        // Close the connection - client is done waiting
        fastcgi_finish_request();

        // This runs AFTER the client has received their response
        $litesoc->flush();
    }

    return $response;
}
```

### Laravel Middleware for Non-Blocking Flush

[](#laravel-middleware-for-non-blocking-flush)

Create a middleware that flushes events after the response is sent:

```
// app/Http/Middleware/FlushLiteSOCEvents.php
namespace App\Http\Middleware;

use Closure;
use LiteSOC\LiteSOC;

class FlushLiteSOCEvents
{
    public function __construct(private LiteSOC $litesoc) {}

    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    /**
     * Flush events after response is sent to client
     */
    public function terminate($request, $response)
    {
        // In PHP-FPM, this runs after fastcgi_finish_request()
        // The client has already received their response
        $this->litesoc->flush();
    }
}

// Register in app/Http/Kernel.php
protected $middleware = [
    // ... other middleware
    \App\Http\Middleware\FlushLiteSOCEvents::class,
];
```

### Laravel Queued Jobs (Recommended for High-Traffic)

[](#laravel-queued-jobs-recommended-for-high-traffic)

For high-traffic applications, dispatch events to a queue:

```
// app/Jobs/TrackSecurityEvent.php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use LiteSOC\LiteSOC;

class TrackSecurityEvent implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    public function __construct(
        public string $eventType,
        public array $options
    ) {}

    public function handle(LiteSOC $litesoc): void
    {
        $litesoc->track($this->eventType, $this->options);
        $litesoc->flush();
    }
}

// Usage - non-blocking, runs in background queue worker
TrackSecurityEvent::dispatch('auth.login_failed', [
    'actor_id' => 'user_123',
    'user_ip' => request()->ip()
]);
```

API Reference
-------------

[](#api-reference)

### Event Collection API (`/api/v1/collect`)

[](#event-collection-api-apiv1collect)

MethodDescription`track($eventName, $options)`Queue a security event for sending`trackLoginFailed($actorId, $options)`Track failed login attempt`trackLoginSuccess($actorId, $options)`Track successful login`trackPrivilegeEscalation($actorId, $options)`Track privilege escalation (critical)`trackSensitiveAccess($actorId, $resource, $options)`Track sensitive data access`trackBulkDelete($actorId, $recordCount, $options)`Track bulk deletion operation`trackRoleChanged($actorId, $oldRole, $newRole, $options)`Track role/permission changes`trackAccessDenied($actorId, $resource, $options)`Track access denied events`flush()`Send all queued events immediately`shutdown()`Graceful shutdown with flush### Events API (`/api/v1/events`)

[](#events-api-apiv1events)

MethodDescription`getEvents($limit, $filters)`List events with pagination`getEvent($eventId)`Get single event by ID**Filters for `getEvents()`:**

- `event_name` - Filter by event type (e.g., `auth.login_failed`)
- `actor_id` - Filter by actor ID
- `severity` - Filter by severity: `critical`, `warning`, `info`
- `offset` - Pagination offset (default: 0)

### Alerts API (`/api/v1/alerts`)

[](#alerts-api-apiv1alerts)

MethodDescription`getAlerts($filters)`List alerts with pagination`getAlert($alertId)`Get single alert by ID`resolveAlert($alertId, $resolutionType, $notes)`Mark alert as resolved`markAlertSafe($alertId, $notes)`Mark alert as safe/false positive**Filters for `getAlerts()`:**

- `severity` - Filter by severity: `critical`, `warning`, `info`
- `status` - Filter by status: `active`, `resolved`, `safe`
- `alert_type` - Filter by type: `impossible_travel`, `brute_force`, etc.
- `limit` - Results per page (default: 20, max: 100)
- `offset` - Pagination offset (default: 0)

**Resolution Types for `resolveAlert()`:**

- `blocked_ip` - IP address was blocked
- `blocked_user` - User account was blocked
- `false_positive` - Alert was a false positive
- `investigated` - Investigated, no action needed
- `other` - Other resolution

License
-------

[](#license)

MIT License - see [LICENSE](LICENSE) for details.

Links
-----

[](#links)

- [LiteSOC Website](https://www.litesoc.io)
- [Documentation](https://www.litesoc.io/docs)
- [API Reference](https://www.litesoc.io/docs/api)
- [GitHub Repository](https://github.com/litesoc/litesoc-php)

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance78

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

8

Last Release

122d ago

Major Versions

v1.2.0 → v2.1.02026-02-28

PHP version history (2 changes)1.1.0PHP ^8.1

v1.2.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/c1abf64c1ea20e53540b0caf4bf89b7dfaa096ead601a5bcb6a4ce5c7d678479?d=identicon)[litesoc](/maintainers/litesoc)

---

Top Contributors

[![AmirolAhmad](https://avatars.githubusercontent.com/u/1130863?v=4)](https://github.com/AmirolAhmad "AmirolAhmad (23 commits)")

---

Tags

composerphplaravelloggingsecurityAuditSIEMthreat-detectionlitesoc

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/litesoc-litesoc-php/health.svg)

```
[![Health](https://phpackages.com/badges/litesoc-litesoc-php/health.svg)](https://phpackages.com/packages/litesoc-litesoc-php)
```

###  Alternatives

[spatie/laravel-health

Monitor the health of a Laravel application

87512.0M165](/packages/spatie-laravel-health)[muhammadsadeeq/laravel-activitylog-ui

A beautiful, modern UI for Spatie's Activity Log with advanced filtering, analytics, and real-time features.

17717.0k](/packages/muhammadsadeeq-laravel-activitylog-ui)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

273.0k](/packages/eslazarev-wildberries-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
