Metadata-Version: 2.4
Name: dc-securex
Version: 2.11.9
Summary: Backend-only Discord anti-nuke protection SDK
Home-page: https://github.com/yourusername/securex-antinuke-sdk
Author: SecureX Team
Author-email: SecureX Team <contact@securex.dev>
License: MIT
Project-URL: Homepage, https://github.com/yourusername/securex-antinuke-sdk
Project-URL: Repository, https://github.com/yourusername/securex-antinuke-sdk
Project-URL: Issues, https://github.com/yourusername/securex-antinuke-sdk/issues
Keywords: discord,bot,antinuke,security,protection,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: discord.py>=2.0.0
Requires-Dist: aiofiles>=23.0.0
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# SecureX SDK - Ultra-Fast Discord Anti-Nuke Protection

**Backend-only Discord anti-nuke protection with 5-10ms response time.** You provide the UI, we provide the security logic.

[![PyPI version](https://badge.fury.io/py/dc-securex.svg)](https://pypi.org/project/dc-securex/)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)

## 🚀 Features

### Dual-System Architecture (v2.x)
- ⚡ **Instant Audit Log Workers** - 5-10ms detection & punishment (100x faster than v1.x)
- 🔄 **Traditional Event Handlers** - Comprehensive restoration from backups
- 🎯 **15 Violation Types** - Complete coverage of Discord audit log actions
- 📊 **3 Independent Workers** - Event, Action, and Log processing in parallel

### Protection Features
✅ **Channel Protection** - Instant detection & restoration of unauthorized changes  
✅ **Role Protection** - Instant punishment + backup restoration  
✅ **Member Protection** - Bot banning, role restoration, ban/kick reverting  
✅ **Webhook Protection** - Spam webhook detection & removal  
✅ **Punishment System** - Configurable kick/ban/timeout actions  
✅ **Role Position Monitoring** - 5-second checks with bulk restore  
✅ **Auto-Backup** - Automatic server backups with 10min refresh  
✅ **Whitelist System** - Manage authorized users  
❌ **No UI** - You design your own interface!

---

## 📋 Prerequisites

Before using SecureX SDK, ensure you have the following:

### 1. Discord Bot Setup
- ✅ Discord Application created at [Discord Developer Portal](https://discord.com/developers/applications)
- ✅ Bot token obtained from your application
- ✅ Bot invited to your server with proper permissions

### 2. Python Environment
- ✅ Python 3.8 or higher installed
- ✅ `discord.py` version 2.0 or higher
- ✅ `aiofiles` version 23.0 or higher (auto-installed with SDK)

### 3. Bot Intents (CRITICAL)

Enable these intents in **both** Discord Developer Portal AND your code:

**Discord Developer Portal:**
1. Go to your application → Bot → Privileged Gateway Intents
2. Enable:
   - ✅ SERVER MEMBERS INTENT
   - ✅ MESSAGE CONTENT INTENT (optional, for commands)

**Your Code:**
```python
intents = discord.Intents.all()  # Recommended for full functionality

# Or enable specific intents:
intents = discord.Intents.default()
intents.guilds = True        # Required
intents.members = True       # Required
intents.bans = True          # Required
intents.webhooks = True      # Required
intents.message_content = True  # Optional (for commands)
```

### 4. Bot Permissions (CRITICAL)

Your bot **MUST** have these permissions in your Discord server:

| Permission | Purpose | Priority |
|------------|---------|----------|
| `VIEW_AUDIT_LOG` | **Critical** - Without this, instant detection won't work | 🔴 REQUIRED |
| `MANAGE_CHANNELS` | Restore deleted/modified channels | 🔴 REQUIRED |
| `MANAGE_ROLES` | Restore roles and remove dangerous permissions | 🔴 REQUIRED |
| `BAN_MEMBERS` | Execute ban punishments | 🟡 Required for bans |
| `KICK_MEMBERS` | Execute kick punishments | 🟡 Required for kicks |
| `MODERATE_MEMBERS` | Execute timeout punishments | 🟡 Required for timeouts |
| `MANAGE_WEBHOOKS` | Remove spam webhooks | 🟢 Optional |

**Invite Link Generator:**
```
https://discord.com/api/oauth2/authorize?client_id=YOUR_BOT_ID&permissions=8&scope=bot
```
Replace `YOUR_BOT_ID` with your bot's client ID. Permission value `8` = Administrator (recommended for testing).

### 5. Bot Role Position

⚠️ **IMPORTANT**: Your bot's role must be **higher** than the roles it needs to manage/restore!

```
Role Hierarchy Example:
1. Owner
2. SecureX Bot  ← Must be here
3. Admin
4. Moderator
5. Member
```

### 6. Server Settings

Enable audit log in your Discord server (should be on by default):
- Server Settings → Audit Log → Ensure it's accessible

---

## 📦 Installation

```bash
pip install dc-securex
```

---

## 🎯 Quick Start

```python
import discord
from discord.ext import commands
from securex import SecureX

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
sx = SecureX(bot)

@bot.event
async def on_ready():
    # Enable protection with instant punishments
    await sx.enable(
        punishments={
            "role_create": "kick",      # Instant kick for role spam
            "channel_delete": "ban",     # Instant ban for channel deletion
            "bot_add": "none"            # Bot is instantly banned regardless
        }
    )
    print("✅ SecureX active with 5-10ms response time!")

# Register callback for custom logging/UI
@sx.on_threat_detected
async def handle_threat(threat):
    print(f"🚨 {threat.type} by {threat.actor_id}")
    print(f"   Punishment: {threat.punishment_action}")
    print(f"   Prevented: {threat.prevented}, Restored: {threat.restored}")

bot.run("YOUR_TOKEN")
```

---

## 📚 Complete API Reference

### Initialization

```python
sx = SecureX(
    bot,                           # Your discord.py Bot instance
    backup_dir="./data/backups",   # Where to store backups
    punishments=None,              # Default punishments (optional)
    timeout_duration=600,          # Timeout duration in seconds
    notify_user=True               # DM punishment notifications
)
```

### `enable()` - Activate Protection

```python
await sx.enable(
    guild_id=None,                    # Specific guild (None = all guilds)
    whitelist=None,                   # List of authorized user IDs
    auto_backup=True,                 # Enable automatic backups
    role_position_monitoring=True,    # 5-second role position checks
    punishments=None,                 # Override default punishments
    timeout_duration=600,             # Timeout duration
    notify_user=True                  # DM users about punishment
)
```

#### Punishment Configuration

**Available Actions:**
- `"none"` - No punishment (restoration only)
- `"warn"` - Warning only
- `"timeout"` - Timeout member
- `"kick"` - Kick from server
- `"ban"` - Ban from server

**Violation Types (15 total):**

| Category | Violation Type | Description |
|----------|---------------|-------------|
| **Bot** | `bot_add` | Unauthorized bot addition (always instant ban) |
| **Channels** | `channel_create` | Mass channel creation |
| | `channel_delete` | Channel deletion |
| | `channel_update` | Permission/name changes |
| **Roles** | `role_create` | Mass role creation |
| | `role_delete` | Role deletion |
| | `role_update` | Permission changes |
| **Members** | `member_kick` | Unauthorized kicks |
| | `member_ban` | Unauthorized bans |
| | `member_unban` | Unauthorized unbans |
| | `member_update` | Role assignment changes |
| **Webhooks** | `webhook_create` | Webhook spam |
| | `webhook_delete` | Webhook deletion |
| | `webhook_update` | Webhook modifications |

**Examples:**

```python
# Strict mode - Ban for everything
await sx.enable(
    punishments={
        "channel_delete": "ban",
        "channel_create": "ban",
        "role_delete": "ban",
        "role_create": "ban",
        "member_update": "ban"
    }
)

# Balanced mode - Kick for spam, ban for destruction
await sx.enable(
    punishments={
        "channel_delete": "ban",
        "role_delete": "ban",
        "channel_create": "kick",
        "role_create": "kick"
    }
)

# Timeout mode - 10 minute timeouts
await sx.enable(
    punishments={
        "channel_delete": "timeout",
        "role_update": "timeout"
    },
    timeout_duration=600
)

# Restoration only - No punishments
await sx.enable()  # All violations default to "none"
```

### Whitelist Management

```python
# Add authorized user
await sx.whitelist.add(guild_id, user_id)

# Remove from whitelist
await sx.whitelist.remove(guild_id, user_id)

# Get all whitelisted users
users = await sx.whitelist.get_all(guild_id)  # Returns: List[int]

# Check if user is whitelisted
is_safe = await sx.whitelist.is_whitelisted(guild_id, user_id)  # Returns: bool
```

### Backup Management

```python
# Create manual backup
backup_info = await sx.create_backup(guild_id)
# Returns: BackupInfo(guild_id, timestamp, channel_count, role_count, ...)

# Backups auto-refresh every 10 minutes when protection is enabled
```

### Threat History

```python
# Get recent threats
threats = await sx.get_recent_threats(guild_id, limit=10)
# Returns: List[ThreatEvent]
```

---

## 📊 Data Models

### ThreatEvent

```python
@dataclass
class ThreatEvent:
    type: str                    # Violation type (e.g., "channel_delete")
    guild_id: int
    actor_id: int                # Who committed the violation
    target_id: int               # What was affected
    target_name: str
    prevented: bool              # Was it stopped?
    restored: bool               # Was it restored from backup?
    timestamp: datetime
    details: Dict                # Additional context
    punishment_action: str       # "none", "warn", "kick", "ban", "timeout"
```

**Methods:**
- `threat.to_dict()` - Convert to dictionary
- `threat.to_json()` - Convert to JSON string

### BackupInfo

```python
@dataclass
class BackupInfo:
    guild_id: int
    timestamp: datetime
    channel_count: int
    role_count: int
    backup_path: str
    success: bool
```

### RestoreResult

```python
@dataclass
class RestoreResult:
    success: bool
    items_restored: int
    items_failed: int
    errors: List[str]
    duration: float
    details: Dict
```

### WhitelistChange

```python
@dataclass
class WhitelistChange:
    guild_id: int
    user_id: int
    action: str              # "added" or "removed"
    timestamp: datetime
    moderator_id: int
```

---

## 🔔 Event Callbacks

Register custom handlers for events:

```python
@sx.on_threat_detected
async def handle_threat(threat: ThreatEvent):
    """
    Fired when any violation is detected
    Includes: punishment_action field
    """
    print(f"{threat.type} - Punishment: {threat.punishment_action}")

@sx.on_backup_completed
async def handle_backup(backup: BackupInfo):
    """Fired when automatic backup completes"""
    print(f"Backup: {backup.channel_count} channels, {backup.role_count} roles")

@sx.on_restore_completed
async def handle_restore(result: RestoreResult):
    """Fired when restoration completes"""
    print(f"Restored {result.items_restored} items in {result.duration}s")

@sx.on_whitelist_changed
async def handle_whitelist(change: WhitelistChange):
    """Fired when whitelist is modified"""
    print(f"User {change.user_id} {change.action}")
```

---

## 💡 Advanced Examples

### Discord Embed Alerts

```python
@sx.on_threat_detected
async def custom_alert(threat):
    embed = discord.Embed(
        title="🚨 Security Alert",
        description=f"**{threat.type.replace('_', ' ').title()}**",
        color=discord.Color.red(),
        timestamp=threat.timestamp
    )
    
    embed.add_field(name="Violator", value=f"<@{threat.actor_id}>", inline=True)
    embed.add_field(name="Target", value=threat.target_name, inline=True)
    embed.add_field(
        name="Status", 
        value=f"{'✅ Prevented' if threat.prevented else '❌ Not Prevented'}", 
        inline=True
    )
    
    if threat.punishment_action and threat.punishment_action != "none":
        embed.add_field(
            name="⚡ Punishment",
            value=f"**{threat.punishment_action.upper()}**",
            inline=False
        )
    
    if threat.restored:
        embed.add_field(
            name="🔄 Restoration",
            value="✅ Restored from backup",
            inline=False
        )
    
    await log_channel.send(embed=embed)
```

### Webhook Integration

```python
import aiohttp

@sx.on_threat_detected
async def send_to_webhook(threat):
    async with aiohttp.ClientSession() as session:
        await session.post(
            "https://your-webhook-url.com/alerts",
            json=threat.to_dict()
        )
```

### Database Logging

```python
@sx.on_threat_detected
async def log_to_database(threat):
    await db.threats.insert_one({
        "type": threat.type,
        "actor_id": threat.actor_id,
        "target_name": threat.target_name,
        "punishment": threat.punishment_action,
        "prevented": threat.prevented,
        "restored": threat.restored,
        "timestamp": threat.timestamp
    })
```

### Dynamic Punishment Modes

```python
@bot.command()
@commands.is_owner()
async def setmode(ctx, mode: str):
    """Switch between strict/normal/lenient protection modes"""
    
    modes = {
        "strict": {
            "channel_delete": "ban",
            "channel_create": "ban",
            "role_delete": "ban",
            "role_create": "ban",
            "member_update": "ban"
        },
        "normal": {
            "channel_delete": "kick",
            "channel_create": "kick",
            "role_delete": "kick",
            "role_create": "timeout"
        },
        "lenient": {
            "channel_delete": "warn",
            "channel_create": "warn",
            "role_delete": "warn"
        }
    }
    
    await sx.enable(punishments=modes.get(mode, {}))
    await ctx.send(f"✅ Protection mode set to **{mode}**")
```

---

## 🏗️ Architecture Overview

### v2.x Dual-System Architecture

**System 1: Instant Audit Log Workers (5-10ms)**
```
Discord Audit Log Event
  ↓ on_audit_log_entry_create (instant)
  ↓ Broadcast to 3 queues
  ├─ Event Queue → Event Worker (validation)
  ├─ Action Queue → Action Worker (punishment)
  └─ Log Queue → Log Worker (callbacks)
```

**System 2: Traditional Event Handlers (restoration)**
```
Discord Event (on_channel_delete, etc.)
  ↓ ~500ms delay for audit log
  ↓ Check if unauthorized
  ↓ Restore from backup
  ↓ Trigger callbacks
```

**Key Benefits:**
- ⚡ Instant punishment (5-10ms) via audit log workers
- 🔄 Comprehensive restoration via event handlers
- 🎯 Zero conflicts - completely independent systems
- 📊 Broadcast queue - 3 workers process in parallel

---

## ⚙️ Requirements

### Python & Dependencies
- Python 3.8+
- discord.py 2.0+
- aiofiles 23.0+

### Bot Configuration

**Intents Required:**
```python
intents = discord.Intents.all()  # Recommended

# Or specific intents:
intents = discord.Intents(
    guilds=True,
    members=True,
    bans=True,
    webhooks=True,
    guild_messages=True
)
```

**Permissions Required:**
- `MANAGE_CHANNELS` - For restoration
- `MANAGE_ROLES` - For restoration
- `BAN_MEMBERS` - For punishments
- `KICK_MEMBERS` - For punishments
- `MODERATE_MEMBERS` - For timeouts
- `VIEW_AUDIT_LOG` - For detection (critical!)

---

## 🎨 Why SDK Approach?

- 🎨 **Full UI Control** - Design your own embeds, dashboards, webhooks
- 📦 **Easy Integration** - Just `pip install` and import
- 🔒 **Battle-Tested Logic** - Proven anti-nuke protection
- 🚀 **No Boilerplate** - We handle the complex stuff
- ⚡ **Ultra-Fast** - 5-10ms response time (100x faster than v1.x)
- 💰 **Reusable** - Use across multiple projects
- ⚙️ **Configurable** - Every parameter is optional with sensible defaults

---

## 📄 License

MIT License - see [LICENSE](LICENSE) file

## 🔗 Links

- **PyPI**: [dc-securex](https://pypi.org/project/dc-securex/)
- **Issues**: Report bugs on GitHub
- **Documentation**: This README

---

**Version 2.3.1** - Ultra-fast anti-nuke protection with 5-10ms response time

Made with ❤️ for Discord bot developers
