# System Settings & Mini WAF - Deployment Guide

**Version:** 1.0.0
**Date:** December 2025
**Features:** Global Redirect Override, Shim Page, Anti-Block Domain Rotation, Facebook Family Optimization, Mini WAF

---

## Table of Contents

1. [Overview](#overview)
2. [Features](#features)
3. [Database Setup](#database-setup)
4. [Configuration](#configuration)
5. [Global Redirect Override](#global-redirect-override)
6. [Shim Page](#shim-page)
7. [Mini WAF (Web Application Firewall)](#mini-waf-web-application-firewall)
8. [Facebook Family Optimization](#facebook-family-optimization)
9. [Anti-Block Domain Rotation](#anti-block-domain-rotation)
10. [Security Considerations](#security-considerations)
11. [Testing](#testing)
12. [Troubleshooting](#troubleshooting)
13. [API Reference](#api-reference)

---

## Overview

The System Settings feature provides centralized control over advanced shortlink behavior including:

- **Global Redirect Override**: Redirect all shortlinks to a single URL
- **Shim Page**: Intermediate page before final redirect with countdown
- **Mini WAF**: Web Application Firewall for attack prevention
- **Facebook Optimization**: Platform-specific optimizations for WhatsApp/Instagram/Messenger
- **Domain Rotation**: Anti-block mechanism with multiple domains

---

## Features

### 1. Global Redirect Override

Temporarily override ALL shortlinks to redirect to a single destination URL.

**Use Cases:**
- Emergency maintenance redirect
- Campaign landing page override
- A/B testing with traffic control
- Event-specific redirects

### 2. Shim Page

An intermediate page shown before redirecting to the final destination.

**Benefits:**
- Improved Facebook link preview optimization
- Analytics tracking (auto vs manual redirect)
- Time-on-page metrics
- Facebook family platform detection
- Countdown timer for user engagement

### 3. Mini WAF (Web Application Firewall)

Protects against common web attacks:

- **SQL Injection** (SQLi)
- **Cross-Site Scripting** (XSS)
- **Local File Inclusion** (LFI)
- **Remote File Inclusion** (RFI)
- **Remote Code Execution** (RCE)
- **Path Traversal**
- **Command Injection**

**Features:**
- IP blocking (1-hour temporary ban)
- Attack pattern detection
- Suspicious user agent detection
- IP whitelisting
- Real-time statistics

### 4. Facebook Family Optimization

Detects and optimizes for Facebook family platforms:

- WhatsApp
- Instagram
- Messenger
- Facebook
- Threads

**Optimizations:**
- Custom styling for platform
- Platform-specific analytics
- Facebook URL Linter sync

### 5. Anti-Block Domain Rotation

Automatically rotate between multiple domains to prevent blocking.

**Features:**
- Domain pool management
- Health checking
- Automatic failover
- Usage statistics

---

## Database Setup

### Step 1: Run Migration

```bash
mysql -u your_user -p your_database < database-migrations/005_add_global_redirect_and_shim.sql
```

### Step 2: Verify Tables Created

```sql
-- Check tables
SHOW TABLES LIKE '%global_redirect%';
SHOW TABLES LIKE '%shim%';
SHOW TABLES LIKE '%fb_linter%';
SHOW TABLES LIKE '%domain_rotation%';
SHOW TABLES LIKE '%fb_family%';

-- Verify default settings
SELECT * FROM global_redirect_settings;
```

### Tables Created:

1. **global_redirect_settings** (singleton - max 1 row)
   - `enabled`: Global redirect on/off
   - `redirect_url`: Override destination URL
   - `shim_enabled`: Shim page on/off
   - `shim_delay_seconds`: Auto-redirect delay (1-30 seconds)
   - `shim_title`: Page title
   - `shim_message`: Custom message
   - `shim_button_text`: Continue button text
   - `antiblock_enabled`: Domain rotation on/off
   - `fb_family_optimization`: Facebook detection on/off
   - `fb_linter_sync`: Auto-sync with Facebook

2. **shim_page_analytics**
   - Tracks user interactions with shim page
   - `auto_redirect`: Was it auto-redirected?
   - `manual_click`: Did user click Continue?
   - `time_on_shim_seconds`: Time spent

3. **fb_linter_sync_log**
   - Facebook URL Linter sync history
   - API responses and error messages

4. **domain_rotation_pool**
   - Alternative domains for anti-block
   - Health check status
   - Usage statistics

5. **fb_family_detections**
   - WhatsApp, Instagram, Messenger detections
   - Platform-specific analytics

---

## Configuration

### Access System Settings

1. Login to dashboard: `http://yourdomain.com/`
2. Click **"System Settings"** tab
3. Configure each section

### Global Redirect Settings

```
✓ Enable Global Redirect Override
  Global Redirect URL: https://example.com/landing-page
```

**Effect:** ALL shortlinks will redirect to `https://example.com/landing-page`

### Shim Page Settings

```
✓ Enable Shim Page
  Auto-Redirect Delay: 3 seconds
  Shim Page Title: Redirecting...
  Custom Message: Please wait while we redirect you to your destination.
  Continue Button Text: Continue
```

**Effect:** Users see intermediate page for 3 seconds before auto-redirect

### Facebook Optimization

```
✓ Enable Facebook Family Detection
✓ Auto-Sync Facebook URL Linter
```

---

## Global Redirect Override

### How It Works

```
User clicks shortlink → s.php checks global settings
                      ↓
            Is global redirect enabled?
                      ↓
            YES: Override destination URL
                      ↓
            Is shim enabled?
                      ↓
            YES: Redirect to shim.php
            NO:  Direct redirect
```

### Example Flow

**Scenario:** Emergency maintenance redirect

1. Enable Global Redirect Override
2. Set URL: `https://status.example.com/maintenance`
3. Save settings
4. **Result:** ALL shortlinks now redirect to maintenance page
5. After maintenance: Disable global redirect
6. **Result:** Shortlinks resume normal behavior

### Code Example

```php
// In s.php (automatically applied)
if ($globalRedirectService->isGlobalRedirectEnabled()) {
    $globalUrl = $globalRedirectService->getGlobalRedirectUrl();
    if (!empty($globalUrl)) {
        $destinationUrl = $globalUrl; // Override
    }
}
```

---

## Shim Page

### Features

- **Countdown Timer**: Auto-redirect after configurable delay (1-30 seconds)
- **Manual Continue Button**: User can skip countdown
- **Analytics Tracking**: Track auto vs manual redirects
- **Time-on-Page**: Measure engagement
- **Facebook Optimization**: Platform-specific styling
- **Keyboard Support**: Enter/Space to continue

### User Flow

```
User clicks shortlink → s.php detects shim enabled
                      ↓
                  Redirect to shim.php
                      ↓
              Show intermediate page with:
                - Countdown timer (3... 2... 1...)
                - Continue button
                - Destination URL preview
                      ↓
              Auto-redirect OR Manual click
                      ↓
              Track analytics to database
                      ↓
              Final destination
```

### Shim Page URL Format

```
/shim.php?slug=abc123&dest=aHR0cHM6Ly9leGFtcGxlLmNvbQ==

Parameters:
- slug: Shortlink slug
- dest: Base64-encoded destination URL
```

### Analytics Tracked

```sql
SELECT * FROM shim_page_analytics;

-- Columns:
-- auto_redirect: 1 = Auto, 0 = Manual
-- manual_click: 1 = User clicked Continue
-- time_on_shim_seconds: Time spent on page
```

### Facebook Family Detection

Shim page automatically detects and optimizes for:

```
WhatsApp    → Green gradient background
Instagram   → Green gradient background
Messenger   → Default styling
Facebook    → Default styling
Threads     → Default styling
```

**Detection Logic:**

```php
$userAgent = $_SERVER['HTTP_USER_AGENT'];

if (str_contains($userAgent, 'whatsapp')) {
    // Apply WhatsApp styling
}
```

---

## Mini WAF (Web Application Firewall)

### Attack Patterns Detected

#### 1. SQL Injection (SQLi)

```
UNION SELECT, OR 1=1, DROP TABLE, --, /* */
```

**Threat Level:** CRITICAL

#### 2. Cross-Site Scripting (XSS)

```
<script>, javascript:, onclick=, onerror=, <iframe>
```

**Threat Level:** HIGH

#### 3. Local File Inclusion (LFI)

```
../, /etc/passwd, /proc/self, php://
```

**Threat Level:** MEDIUM

#### 4. Remote File Inclusion (RFI)

```
http:// in parameters
```

**Threat Level:** HIGH

#### 5. Remote Code Execution (RCE)

```
eval(), exec(), system(), shell_exec(), `command`
```

**Threat Level:** CRITICAL

#### 6. Command Injection

```
; ls, | cat, & whoami
```

**Threat Level:** HIGH

### How It Works

```
Request → bootstrap/init.php
          ↓
      Mini WAF Check
          ↓
    Scan query params, POST data, headers
          ↓
    Match against attack patterns
          ↓
    Attack detected?
          ↓
    YES: Block IP (1 hour) + 403 response
    NO:  Allow request
```

### IP Blocking

**Automatic Block Duration:** 1 hour

**Block Storage:** APCu cache

```php
apcu_store('waf_blocked_ips', [
    '192.168.1.100' => [
        'reason' => 'sqli',
        'blocked_at' => 1234567890,
        'expires_at' => 1234571490, // +1 hour
    ]
]);
```

### Whitelisting

**Whitelist IPs bypass ALL WAF checks:**

1. Go to System Settings → Mini WAF
2. Enter IP address: `192.168.1.1`
3. Click "Add to Whitelist"
4. **Result:** IP whitelisted for 24 hours

### WAF Statistics

```
Blocked IPs: 5
Requests Processed: 1,245
Protection Status: Active
```

### View Blocked IPs

Navigate to: **System Settings → Mini WAF → Currently Blocked IPs**

Table shows:
- IP Address
- Reason (sqli, xss, lfi, etc.)
- Blocked At timestamp
- Expires timestamp
- Action (Unblock button)

### Suspicious User Agents

WAF detects attack tools:

```
sqlmap, nikto, nmap, masscan, nessus, acunetix,
havij, w3af, metasploit, burp, zap, commix
```

**Action:** Log suspicious activity (no block)

---

## Facebook Family Optimization

### Platform Detection

```php
$userAgent = $_SERVER['HTTP_USER_AGENT'];

$platform = $globalRedirectService->detectFacebookFamily($userAgent);

// Returns: 'whatsapp', 'instagram', 'messenger', 'facebook', 'threads', or null
```

### Tracking

```sql
SELECT * FROM fb_family_detections;

-- Shows:
-- platform: whatsapp, instagram, etc.
-- user_agent: Full UA string
-- shortlink_id: Which shortlink was accessed
-- detected_at: Timestamp
```

### Facebook URL Linter Sync

**Purpose:** Force Facebook to refresh link preview

**Manual Trigger:**

```bash
curl -X POST https://graph.facebook.com/v18.0/
  -d id=https://yourdomain.com/s/abc123
  -d scrape=true
  -d access_token=YOUR_ACCESS_TOKEN
```

**Auto-Sync (Future):**

When `fb_linter_sync` is enabled, system automatically calls Facebook API when shortlink OG tags are updated.

---

## Anti-Block Domain Rotation

### Domain Pool Management

#### Add Domain to Pool

```sql
INSERT INTO domain_rotation_pool (domain, status, priority)
VALUES ('alt-domain1.com', 'active', 10);

INSERT INTO domain_rotation_pool (domain, status, priority)
VALUES ('alt-domain2.com', 'active', 20);
```

**Priority:** Lower number = higher priority

#### Enable Domain Rotation

1. Go to System Settings → Anti-Block Domain Rotation
2. Check **"Enable Domain Rotation"**
3. Save settings

#### How It Works

```php
if ($globalRedirectService->isAntiBlockEnabled()) {
    $rotatedDomain = $globalRedirectService->getRotatedDomain();

    if ($rotatedDomain) {
        // Use alternative domain instead of primary
    }
}
```

**Selection Logic:**

```sql
SELECT domain FROM domain_rotation_pool
WHERE status = 'active' AND is_healthy = 1
ORDER BY priority ASC, RAND()
LIMIT 1;
```

### Health Checking

**Manual Health Check:**

```sql
UPDATE domain_rotation_pool
SET last_health_check = NOW(), is_healthy = 1
WHERE domain = 'alt-domain1.com';
```

**Future:** Automated health check cron job

---

## Security Considerations

### CSRF Protection

All POST requests require valid CSRF token:

```php
// CSRF validation
$csrfToken = $_POST['csrf_token'] ?? '';
if (!hash_equals($_SESSION['csrf_token'], $csrfToken)) {
    die('Invalid CSRF token');
}
```

**Token Rotation:** After each critical operation

### Input Validation

```php
// URL validation
if (!filter_var($url, FILTER_VALIDATE_URL)) {
    die('Invalid URL');
}

// IP validation
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
    die('Invalid IP');
}

// Integer validation
$delay = (int) $_POST['delay'];
if ($delay < 1 || $delay > 30) {
    die('Invalid delay');
}
```

### Output Escaping

```php
function escape(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');
}

// Usage in HTML
<title><?= escape($title) ?></title>
```

### SQL Injection Prevention

**All queries use prepared statements:**

```php
$stmt = $pdo->prepare('SELECT * FROM shortlinks WHERE slug = ?');
$stmt->execute([$slug]);
```

### Session Security

```php
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_secure', '1');
ini_set('session.cookie_samesite', 'Strict');
```

---

## Testing

### Test Global Redirect Override

1. Create shortlink: `/s/test1` → `https://example.com/page1`
2. Enable Global Redirect → `https://override.com`
3. Visit `/s/test1`
4. **Expected:** Redirects to `https://override.com`
5. Disable Global Redirect
6. Visit `/s/test1`
7. **Expected:** Redirects to `https://example.com/page1`

### Test Shim Page

1. Enable Shim Page (3 seconds delay)
2. Visit any shortlink
3. **Expected:** See intermediate page with countdown
4. Wait 3 seconds
5. **Expected:** Auto-redirect to destination
6. **OR** Click "Continue" button
7. **Expected:** Immediate redirect

### Test Mini WAF

#### SQLi Attack Test

```bash
curl "http://yourdomain.com/?id=1' OR '1'='1"
```

**Expected Response:**

```json
{
    "ok": false,
    "error": "Request blocked by security filter",
    "threat_level": "critical"
}
```

#### XSS Attack Test

```bash
curl -X POST http://yourdomain.com/ajax/submit-shortlink.php \
  -d "csrf_token=valid_token" \
  -d "destination_url=<script>alert(1)</script>"
```

**Expected:** Request blocked, IP banned for 1 hour

#### Check Blocked IPs

1. Go to System Settings → Mini WAF
2. View "Currently Blocked IPs" table
3. **Expected:** See your test IP listed

#### Whitelist IP

1. Enter your IP in "Whitelist IP Address"
2. Click "Add to Whitelist"
3. Retry attack test
4. **Expected:** Request allowed (bypass WAF)

### Test Facebook Family Detection

1. Visit shortlink with WhatsApp user agent:

```bash
curl -H "User-Agent: WhatsApp/2.0" \
  http://yourdomain.com/s/test1
```

2. Check database:

```sql
SELECT * FROM fb_family_detections ORDER BY detected_at DESC LIMIT 1;
```

**Expected:** `platform = 'whatsapp'`

---

## Troubleshooting

### Issue: Global Redirect Not Working

**Symptoms:** Shortlinks still redirect to original destination

**Solutions:**

1. Check settings:

```sql
SELECT * FROM global_redirect_settings;
-- Verify: enabled = 1, redirect_url is set
```

2. Clear APCu cache:

```php
apcu_delete('global_redirect_settings');
```

3. Check s.php integration:

```php
// Should be present in s.php
if ($globalRedirectService->isGlobalRedirectEnabled()) {
    $globalUrl = $globalRedirectService->getGlobalRedirectUrl();
    // ...
}
```

### Issue: Shim Page Not Showing

**Symptoms:** Direct redirect instead of shim page

**Solutions:**

1. Check if bot detection is blocking:

```php
$isBot = isBotRequest();
// Shim disabled for bots
```

2. Verify shim enabled:

```sql
SELECT shim_enabled FROM global_redirect_settings;
-- Should be: 1
```

3. Check redirect logic in s.php:

```php
if ($globalRedirectService->isShimEnabled() && !$isBot) {
    // Should redirect to shim.php
}
```

### Issue: WAF Blocking Legitimate Requests

**Symptoms:** Users receiving 403 errors

**Solutions:**

1. Check WAF statistics:

```
System Settings → Mini WAF → Refresh Stats
```

2. Review blocked IPs:

```
Check "Currently Blocked IPs" table
```

3. Whitelist legitimate IPs:

```
Add IP to whitelist
```

4. Temporarily disable WAF (emergency):

```php
// In bootstrap/init.php, comment out:
// if (!$miniWAF->isIPWhitelisted($clientIP)) {
//     $wafResult = $miniWAF->checkRequest();
//     ...
// }
```

### Issue: Shim Analytics Not Tracking

**Symptoms:** No data in `shim_page_analytics` table

**Solutions:**

1. Check sendBeacon endpoint:

```bash
curl -X POST http://yourdomain.com/ajax/track-shim-analytics.php \
  -d "shortlink_id=1" \
  -d "slug=test" \
  -d "auto_redirect=1" \
  -d "time_on_shim_seconds=3"
```

**Expected:** `{"success":true}`

2. Verify GlobalRedirectService method:

```php
$result = $globalRedirectService->trackShimAnalytics([
    'shortlink_id' => 1,
    'slug' => 'test',
    'auto_redirect' => 1,
]);
// Should return: true
```

3. Check browser console for errors

4. Verify CORS/network issues

---

## API Reference

### AJAX Endpoints

#### GET /ajax/get-system-settings.php

**Description:** Fetch all system settings

**Response:**

```json
{
    "success": true,
    "settings": {
        "enabled": 0,
        "redirect_url": null,
        "shim_enabled": 0,
        "shim_delay_seconds": 3,
        "shim_title": "Redirecting...",
        "shim_message": "Please wait...",
        "shim_button_text": "Continue",
        "antiblock_enabled": 0,
        "fb_family_optimization": 1,
        "fb_linter_sync": 1
    }
}
```

#### POST /ajax/update-system-settings.php

**Description:** Update system settings

**Request:**

```
POST /ajax/update-system-settings.php

csrf_token=abc123
enabled=1
redirect_url=https://example.com
shim_enabled=1
shim_delay_seconds=5
shim_title=Please Wait
shim_message=Redirecting you...
shim_button_text=Continue
antiblock_enabled=0
fb_family_optimization=1
fb_linter_sync=1
```

**Response:**

```json
{
    "success": true,
    "message": "Settings updated successfully",
    "csrf_token": "new_token_xyz"
}
```

**Validation Rules:**

- `redirect_url`: Must be valid URL if provided
- `shim_delay_seconds`: Must be 1-30
- All boolean fields: Checkbox presence = 1, absence = 0

#### GET /ajax/get-waf-stats.php

**Description:** Get WAF statistics

**Response:**

```json
{
    "success": true,
    "stats": {
        "total_blocked_ips": 3,
        "requests_processed": 1245,
        "blocked_ips": {
            "192.168.1.100": {
                "reason": "sqli",
                "blocked_at": 1234567890,
                "expires_at": 1234571490
            }
        }
    }
}
```

#### POST /ajax/whitelist-ip.php

**Description:** Add IP to whitelist

**Request:**

```
POST /ajax/whitelist-ip.php

csrf_token=abc123
ip=192.168.1.1
```

**Response:**

```json
{
    "success": true,
    "message": "IP whitelisted successfully",
    "csrf_token": "new_token_xyz"
}
```

**Validation:**

- `ip`: Must be valid IP address (IPv4 or IPv6)

#### POST /ajax/track-shim-analytics.php

**Description:** Track shim page interaction

**Request:**

```
POST /ajax/track-shim-analytics.php

shortlink_id=123
slug=abc123
auto_redirect=1
manual_click=0
time_on_shim_seconds=3
```

**Response:**

```json
{
    "success": true
}
```

### PHP Service Methods

#### GlobalRedirectService

```php
// Check if global redirect enabled
$globalRedirectService->isGlobalRedirectEnabled(): bool

// Get global redirect URL
$globalRedirectService->getGlobalRedirectUrl(): ?string

// Check if shim enabled
$globalRedirectService->isShimEnabled(): bool

// Get shim configuration
$globalRedirectService->getShimConfig(): array

// Check if anti-block enabled
$globalRedirectService->isAntiBlockEnabled(): bool

// Get rotated domain
$globalRedirectService->getRotatedDomain(): ?string

// Update settings
$globalRedirectService->updateSettings(array $data): bool

// Track shim analytics
$globalRedirectService->trackShimAnalytics(array $data): bool

// Detect Facebook family platform
$globalRedirectService->detectFacebookFamily(string $userAgent): ?string

// Track Facebook family detection
$globalRedirectService->trackFacebookFamily(string $platform, int $shortlinkId, string $slug): bool
```

#### MiniWAFService

```php
// Check request for attacks
$miniWAF->checkRequest(): array

// Get WAF statistics
$miniWAF->getStats(): array

// Whitelist IP
$miniWAF->whitelistIP(string $ip): void

// Check if IP whitelisted
$miniWAF->isIPWhitelisted(string $ip): bool

// Get client IP (proxy-aware)
$miniWAF->getClientIP(): string
```

---

## Performance Considerations

### APCu Caching

**Settings Cache:**

```php
// Cache duration: 5 minutes
apcu_store('global_redirect_settings', $settings, 300);
```

**Cache Invalidation:**

Automatic on settings update:

```php
apcu_delete('global_redirect_settings');
```

### Database Indexing

**Critical Indexes:**

```sql
-- Shortlink lookups
INDEX idx_slug ON shortlinks(slug);

-- WAF blocked IPs (in-memory APCu)
-- No database index needed

-- Shim analytics
INDEX idx_shortlink_id ON shim_page_analytics(shortlink_id);
INDEX idx_viewed_at ON shim_page_analytics(viewed_at DESC);

-- Facebook detections
INDEX idx_platform ON fb_family_detections(platform);
INDEX idx_detected_at ON fb_family_detections(detected_at DESC);
```

### Optimization Tips

1. **Use APCu for WAF**: Blocked IPs stored in memory (fast)
2. **Cache settings**: 5-minute cache reduces DB queries
3. **Async tracking**: Click tracking doesn't block redirects
4. **sendBeacon**: Reliable analytics without blocking navigation

---

## Production Deployment Checklist

- [ ] Run database migration 005
- [ ] Verify all 5 tables created
- [ ] Test System Settings UI loads
- [ ] Test Global Redirect override
- [ ] Test Shim page functionality
- [ ] Test Mini WAF blocks attacks
- [ ] Test WAF whitelisting
- [ ] Test Facebook family detection
- [ ] Verify CSRF tokens working
- [ ] Check error logs for issues
- [ ] Monitor WAF statistics
- [ ] Set up domain rotation pool (if needed)
- [ ] Configure Facebook URL Linter API (if needed)
- [ ] Test with real traffic
- [ ] Monitor shim analytics
- [ ] Verify performance (APCu cache)

---

## Future Enhancements

### Planned Features:

1. **Domain Rotation UI**
   - Add/remove domains from pool
   - Health check automation
   - Failover testing

2. **Facebook URL Linter Integration**
   - Auto-sync on OG tag updates
   - Manual rescrape button
   - Sync status dashboard

3. **Advanced WAF Rules**
   - Custom attack patterns
   - Rate limiting per endpoint
   - GeoIP blocking

4. **Shim Page Customization**
   - Custom CSS themes
   - Multiple shim templates
   - A/B testing

5. **Analytics Dashboard**
   - Shim page conversion rates
   - Platform distribution charts
   - WAF attack trends

---

## Support

**Documentation:** `/SYSTEM_SETTINGS_DEPLOYMENT.md`

**Database Schema:** `/database-migrations/005_add_global_redirect_and_shim.sql`

**Source Files:**
- `/src/Service/GlobalRedirectService.php`
- `/src/Service/MiniWAFService.php`
- `/public/shim.php`
- `/public/s.php`
- `/public/ajax/get-system-settings.php`
- `/public/ajax/update-system-settings.php`
- `/public/ajax/get-waf-stats.php`
- `/public/ajax/whitelist-ip.php`
- `/public/ajax/track-shim-analytics.php`

**Report Issues:** Check error logs and review troubleshooting section

---

**End of System Settings & Mini WAF Deployment Guide**
