PHPackages                             ahmedmerza/logscope-guard - 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. [Security](/categories/security)
4. /
5. ahmedmerza/logscope-guard

ActiveLibrary[Security](/categories/security)

ahmedmerza/logscope-guard
=========================

IP blocking and cross-environment blacklist sync for LogScope

v0.1.0(yesterday)00MITPHPPHP ^8.2CI failing

Since Apr 6Pushed yesterdayCompare

[ Source](https://github.com/AhmedMerza/laravel-logscope-guard)[ Packagist](https://packagist.org/packages/ahmedmerza/logscope-guard)[ Docs](https://github.com/ahmedmerza/laravel-logscope-guard)[ GitHub Sponsors](https://github.com/AhmedMerza)[ RSS](/packages/ahmedmerza-logscope-guard/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (14)Versions (3)Used By (0)

LogScope Guard
==============

[](#logscope-guard)

[![License](https://camo.githubusercontent.com/558ed864e43680969fe6042db3b75161c0502331ec0fd79ff491d68cefe818d3/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f41686d65644d65727a612f6c61726176656c2d6c6f6773636f70652d67756172643f7374796c653d666c61742d737175617265)](LICENSE.md)[![PHP Version](https://camo.githubusercontent.com/72e717bf3589ed4c4cc0cfc19d2e0931732b47b19de67287feb458aaf12e109d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e322d626c75653f7374796c653d666c61742d737175617265)](https://php.net)

IP blocking and cross-environment blacklist sync for [LogScope](https://github.com/AhmedMerza/laravel-logscope).

A malicious IP hits staging. You block it from the LogScope UI. Every other environment syncs within minutes — automatically.

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

[](#quick-start)

```
composer require ahmedmerza/logscope-guard
php artisan guard:install
```

That's it. A **Block IP** button now appears in the LogScope detail panel whenever a log entry has an IP address.

---

How It Works
------------

[](#how-it-works)

```
Admin blocks IP in LogScope UI (staging)
    │
    ├─► DB row created + Redis hash rebuilt → staging protected immediately
    │
    └─► Queued job pushes block to master env
            │
            └─► Every other env pulls from master via guard:sync (every 5 min)
                    └─► Redis rebuilt → all environments protected

```

Every incoming request is checked against a **Redis Hash** before any middleware, session, auth, or route runs. No DB hit per request.

---

Table of Contents
-----------------

[](#table-of-contents)

- [Requirements](#-requirements)
- [Installation](#-installation)
- [Configuration](#%EF%B8%8F-configuration)
- [Cross-Environment Sync](#-cross-environment-sync)
- [Auto-Block Rules](#-auto-block-rules)
- [Artisan Commands](#-artisan-commands)
- [Security Notes](#-security-notes)
- [License](#-license)

---

📋 Requirements
--------------

[](#-requirements)

- PHP 8.2+
- Laravel 10+
- Redis
- [ahmedmerza/logscope](https://github.com/AhmedMerza/laravel-logscope) &gt;= 1.5.2

---

📦 Installation
--------------

[](#-installation)

```
composer require ahmedmerza/logscope-guard
php artisan guard:install
```

The install command publishes the config and runs the migration. Add these to your `.env`:

```
GUARD_ENABLED=true
GUARD_NEVER_BLOCK_IPS=127.0.0.1,::1,your.own.ip
```

> **Important:** Add your own IP to `GUARD_NEVER_BLOCK_IPS` before enabling. You cannot be blocked by an IP on this list — it is checked before any block operation and before Redis.

---

⚙️ Configuration
----------------

[](#️-configuration)

```
# Master switch
GUARD_ENABLED=true

# IPs that can never be blocked (comma-separated) — prevents self-lockout
GUARD_NEVER_BLOCK_IPS=127.0.0.1,::1

# Redis connection to use for the blacklist hash
GUARD_REDIS_CONNECTION=default

# Cross-environment sync
GUARD_MASTER_URL=https://your-master-app.com
GUARD_SYNC_SECRET=a-long-random-secret

# Auto-block engine (disabled by default)
GUARD_AUTO_BLOCK_ENABLED=false
GUARD_AUTO_BLOCK_DURATION=60

# Webhook notification on every block (optional — useful for n8n, Slack, WhatsApp)
GUARD_WEBHOOK_URL=
GUARD_NOTIFICATION_QUEUE=default

# Dedicated log channel for Guard events (sync failures, auto-block skips, etc.)
GUARD_LOG_CHANNEL=stack

# Automatic cleanup of expired temporary blocks (runs daily)
GUARD_CLEANUP_ENABLED=true
```

### Block Response

[](#block-response)

By default, blocked IPs receive a plain `403 Access denied.` response. To redirect instead:

```
// config/logscope-guard.php
'block_response' => [
    'status'   => 403,
    'message'  => 'Access denied.',
    'redirect' => null, // Set a URL to redirect instead
],
```

---

🌐 Cross-Environment Sync
------------------------

[](#-cross-environment-sync)

Guard supports a **master/satellite** topology. One environment (production) is the master. Others (staging, alpha) pull from it.

### Setup

[](#setup)

**On every environment** (master + satellites), add to `.env`:

```
GUARD_MASTER_URL=https://your-production-app.com
GUARD_SYNC_SECRET=same-secret-on-all-environments
```

**On the master app**, expose two routes that satellites call:

```
// routes/web.php (or api.php) — protect with HMAC middleware
Route::get('/guard/api/blacklist', fn () => response()->json([
    'data' => \LogScopeGuard\Models\BlacklistedIp::active()->get(),
]));

Route::post('/guard/api/block', function (Request $request) {
    app(\LogScopeGuard\Services\BlacklistService::class)->block(
        $request->input('ip'),
        $request->only(['reason', 'source_env', 'expires_at', 'blocked_by'])
    );
    return response()->json(['ok' => true]);
});
```

**On satellites**, schedule the sync command:

```
// Laravel 11+ (routes/console.php)
Schedule::command('guard:sync')->everyFiveMinutes();

// Laravel 10 (app/Console/Kernel.php)
$schedule->command('guard:sync')->everyFiveMinutes();
```

### How Push + Pull Work Together

[](#how-push--pull-work-together)

DirectionTriggerSpeed**Push** (satellite → master)Every `BlacklistService::block()` callImmediate (queued job)**Pull** (master → satellites)`guard:sync` scheduleEvery 5 min (configurable)Block on staging → staging protected instantly → master updated asynchronously → production/alpha pull it within 5 minutes.

---

🤖 Auto-Block Rules
------------------

[](#-auto-block-rules)

Automatically block IPs based on log patterns. Disabled by default.

```
GUARD_AUTO_BLOCK_ENABLED=true
GUARD_AUTO_BLOCK_DURATION=60  # minutes
```

Define rules in `config/logscope-guard.php`:

```
'auto_block' => [
    'enabled'                => env('GUARD_AUTO_BLOCK_ENABLED', false),
    'block_duration_minutes' => 60,
    'rules' => [
        // Block IPs that generate 50+ errors in 5 minutes
        [
            'level'            => 'error',
            'message_contains' => null,
            'count'            => 50,
            'window_minutes'   => 5,
        ],
        // Block IPs that hit 404 more than 100 times in 10 minutes
        [
            'level'            => 'warning',
            'message_contains' => '404',
            'count'            => 100,
            'window_minutes'   => 10,
        ],
    ],
],
```

Rules run every minute via the scheduler. Add the scheduler to your server if not already running:

```
* * * * * cd /your-app && php artisan schedule:run >> /dev/null 2>&1
```

> **Note:** IPs in `GUARD_NEVER_BLOCK_IPS` are never auto-blocked, even if they match a rule.

---

🔧 Artisan Commands
------------------

[](#-artisan-commands)

```
# First-time setup (publish config + run migration)
php artisan guard:install

# Pull blacklist from master and rebuild local Redis cache
php artisan guard:sync

# Delete expired temporary blocks and rebuild the Redis cache
# Runs automatically every day — set GUARD_CLEANUP_ENABLED=false to manage manually
# Permanent blocks (no expiry) are never touched
php artisan guard:cleanup
```

---

🔒 Security Notes
----------------

[](#-security-notes)

**Trusted proxies:** Guard uses `$request->ip()` — the same method LogScope uses. If your app is behind a load balancer or proxy, configure Laravel's trusted proxies correctly so the real client IP is resolved, not the proxy IP.

**HMAC signatures:** All sync requests are signed with `GUARD_SYNC_SECRET` using `hash_hmac('sha256', ...)`. Use a long, random secret and keep it identical across environments.

**Redis TTL:** The blacklist Redis hash has a 24-hour TTL as a safety net. If Redis is flushed, the cache rebuilds from DB automatically on the next request boot.

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome. Please open an issue or submit a pull request on [GitHub](https://github.com/AhmedMerza/laravel-logscope-guard).

---

📄 License
---------

[](#-license)

MIT License. See [LICENSE](LICENSE.md) for details.

###  Health Score

37

—

LowBetter than 82% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

1d ago

### Community

Maintainers

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

---

Top Contributors

[![AhmedMerza](https://avatars.githubusercontent.com/u/67040497?v=4)](https://github.com/AhmedMerza "AhmedMerza (1 commits)")

---

Tags

laravelsecurityfirewallip-blockinglogscope

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/ahmedmerza-logscope-guard/health.svg)

```
[![Health](https://phpackages.com/badges/ahmedmerza-logscope-guard/health.svg)](https://phpackages.com/packages/ahmedmerza-logscope-guard)
```

###  Alternatives

[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[spatie/laravel-csp

Add CSP headers to the responses of a Laravel app

8519.6M19](/packages/spatie-laravel-csp)[ercsctt/laravel-file-encryption

Secure file encryption and decryption for Laravel applications

642.6k](/packages/ercsctt-laravel-file-encryption)[ralphjsmit/laravel-glide

Auto-magically generate responsive images from static image files.

4719.6k5](/packages/ralphjsmit-laravel-glide)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

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