# 🛡️ RANGERBLOCK SECURITY INTEGRATION PLAN
## Project Codename: "SHEPHERD PROTOCOL"
### Unified Identity & Registration System

---

## 1. EXECUTIVE SUMMARY

Implement a unified security and registration system across ALL RangerBlock components:

| Component | Current State | Target State |
|-----------|---------------|--------------|
| **ranger-chat-lite** | Hardware fingerprint + RSA keys (unused) | Full encryption + Commander verification |
| **blockchain-chat.cjs** | Simple nickname only | Hardware ID + persistent identity |
| **voice-chat.cjs** | Simple nickname only | Hardware ID + encrypted voice |
| **server-only** | Does not exist | Centralized auth hub with kill switch |

---

## 2. CURRENT STATE ANALYSIS

### A. ranger-chat-lite (Electron App) ✅ BEST
**Location**: `/Users/ranger/rangerplex-ai/apps/ranger-chat-lite/`

**What It Has**:
```
✅ Hardware fingerprinting (SHA-256 of Hardware UUID + hostname + username)
✅ Persistent identity (user_identity.json)
✅ RSA-2048 keypair generation
✅ Cross-platform support (macOS/Windows/Linux)
✅ IPC API for identity operations
✅ Message statistics tracking
✅ User moderation note (admins can track real identity)
```

**Key Files**:
- `electron/identityService.ts` - Core identity logic (379 lines)
- `electron/main.ts` - IPC handlers
- `electron/preload.ts` - API bridge

**Hardware Fingerprint Code** (identityService.ts:109-173):
```typescript
// macOS: system_profiler SPHardwareDataType → Hardware UUID
// Windows: wmic csproduct get uuid
// Linux: /etc/machine-id
const fingerprint = crypto
    .createHash('sha256')
    .update(hardwareId + os.hostname() + os.userInfo().username)
    .digest('hex')
    .substring(0, 32)
```

**What It's Missing**:
```
❌ Password/PIN protection
❌ Message encryption (plain text over ws://)
❌ TLS/WSS (unencrypted WebSocket)
❌ Token-based auth (no JWT/session tokens)
❌ Server-side identity verification
❌ Kill switch integration
```

---

### B. blockchain-chat.cjs (Terminal Chat) ⚠️ BASIC
**Location**: `/Users/ranger/rangerplex-ai/rangerblock/just-chat/blockchain-chat.cjs`

**What It Has**:
```
✅ Basic nickname registration
✅ Machine name detection (getMachineName())
✅ Local IP detection
✅ Channel-based chat (#rangers)
```

**Current Registration** (line 204-216):
```javascript
// Very simple - just sends nickname to server
ws.send(JSON.stringify({
    type: 'register',
    address: `${nickname}-${Date.now()}`,
    nickname: nickname,
    channel: DEFAULT_CHANNEL,
    ip: getLocalIP(),
    port: 0
}));
```

**What It's Missing**:
```
❌ Hardware fingerprinting
❌ Persistent identity file
❌ RSA keypairs
❌ Any form of authentication
❌ TODO at line 412: "Implement challenge-response authentication"
```

---

### C. voice-chat.cjs (Terminal Voice) ⚠️ BASIC
**Location**: `/Users/ranger/rangerplex-ai/rangerblock/just-chat/voice-chat.cjs`

**What It Has**:
```
✅ Same basic registration as blockchain-chat
✅ Voice call states (IDLE, CALLING, RINGING, IN_CALL, IN_GROUP)
✅ Audio compression with zlib
✅ Private calls + group voice
```

**What It's Missing**:
```
❌ Hardware fingerprinting
❌ Persistent identity
❌ Voice encryption (just zlib compression, not crypto)
❌ Call authentication (anyone can call anyone)
```

---

### D. server-only (Planned) 🆕 NOT BUILT
**Location**: `/Users/ranger/rangerplex-ai/rangerblock/server-only/` (to be created)

**Purpose**: Centralized authentication hub + kill switch controller

---

## 3. TARGET ARCHITECTURE

```
┌─────────────────────────────────────────────────────────────────────┐
│                     RANGERBLOCK SECURITY LAYER                       │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐               │
│  │ ranger-chat- │  │ blockchain-  │  │ voice-chat   │               │
│  │    lite      │  │   chat.cjs   │  │    .cjs      │               │
│  │  (Electron)  │  │  (Terminal)  │  │  (Terminal)  │               │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘               │
│         │                 │                 │                        │
│         ▼                 ▼                 ▼                        │
│  ┌─────────────────────────────────────────────────────────┐        │
│  │              SHARED IDENTITY SERVICE                     │        │
│  │    ~/.rangerblock/identity/                              │        │
│  │    - hardware_fingerprint.json                           │        │
│  │    - user_identity.json                                  │        │
│  │    - keys/ (RSA-2048)                                    │        │
│  └──────────────────────────┬──────────────────────────────┘        │
│                             │                                        │
│                             ▼                                        │
│  ┌─────────────────────────────────────────────────────────┐        │
│  │              RANGERBLOCK AUTH SERVER                     │        │
│  │    (server-only/auth-server.cjs)                         │        │
│  │    - Challenge-response auth                             │        │
│  │    - Hardware ID verification                            │        │
│  │    - Session token issuance                              │        │
│  │    - Ban list management                                 │        │
│  │    - KILL SWITCH LISTENER                                │        │
│  └──────────────────────────┬──────────────────────────────┘        │
│                             │                                        │
│                             ▼                                        │
│  ┌─────────────────────────────────────────────────────────┐        │
│  │              COMMANDER CONTROL PANEL                     │        │
│  │    (~/.claude/ranger/classified/rain/)                   │        │
│  │    - Rain Protocol triggers                              │        │
│  │    - User management                                     │        │
│  │    - Network monitoring                                  │        │
│  └─────────────────────────────────────────────────────────┘        │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘
```

---

## 4. SHARED IDENTITY SERVICE

### A. Common Identity Module
**New File**: `/Users/ranger/rangerplex-ai/rangerblock/lib/identity-service.cjs`

**Purpose**: Shared code for ALL RangerBlock apps (Electron + Node.js terminal)

**Features**:
```javascript
class RangerBlockIdentity {
    // Core identity
    getOrCreateIdentity(username)     // Returns persistent identity
    getHardwareFingerprint()          // Cross-platform hardware ID

    // Cryptography
    generateKeyPair()                 // RSA-2048 keys
    signMessage(message)              // Sign with private key
    verifySignature(message, sig, pubKey)  // Verify with public key

    // Storage
    saveIdentity()                    // Persist to ~/.rangerblock/
    loadIdentity()                    // Load from disk
    exportIdentity()                  // Backup identity

    // Auth helpers
    generateChallenge()               // Create auth challenge
    respondToChallenge(challenge)     // Sign challenge

    // Commander integration
    checkKillSwitch()                 // Check if network is live
    validateCommanderMessage(msg)     // Verify Commander signature
}
```

### B. Storage Structure
**Location**: `~/.rangerblock/` (shared across all apps)

```
~/.rangerblock/
├── identity/
│   ├── hardware_fingerprint.json    # Device-specific ID
│   ├── user_identity.json           # User profile + stats
│   └── registration_token.json      # Server-issued auth token
├── keys/
│   ├── private_key.pem              # RSA-2048 private (NEVER share)
│   └── public_key.pem               # RSA-2048 public (sent to server)
├── sessions/
│   └── current_session.json         # Active session token
└── config/
    └── preferences.json             # User preferences
```

---

## 5. AUTHENTICATION FLOW

### Phase 1: First-Time Registration

```
┌─────────┐                    ┌─────────┐                    ┌─────────┐
│  CLIENT │                    │ SERVER  │                    │COMMANDER│
└────┬────┘                    └────┬────┘                    └────┬────┘
     │                              │                              │
     │ 1. Generate hardware ID      │                              │
     │    Generate RSA keypair      │                              │
     │                              │                              │
     │ 2. Connect to server         │                              │
     ├─────────────────────────────>│                              │
     │                              │                              │
     │ 3. Server sends challenge    │                              │
     │<─────────────────────────────┤                              │
     │    (random nonce)            │                              │
     │                              │                              │
     │ 4. Client signs challenge    │                              │
     │    with private key          │                              │
     │                              │                              │
     │ 5. Send registration:        │                              │
     │    - hardware_id             │                              │
     │    - public_key              │                              │
     │    - signed_challenge        │                              │
     │    - nickname                │                              │
     ├─────────────────────────────>│                              │
     │                              │                              │
     │                              │ 6. Verify signature          │
     │                              │    Store hardware_id +       │
     │                              │    public_key mapping        │
     │                              │                              │
     │ 7. Registration approved     │                              │
     │    (session token issued)    │                              │
     │<─────────────────────────────┤                              │
     │                              │                              │
     │                              │ 8. Log new registration      │
     │                              ├─────────────────────────────>│
     │                              │    (for Commander review)    │
     │                              │                              │
```

### Phase 2: Returning User

```
┌─────────┐                    ┌─────────┐
│  CLIENT │                    │ SERVER  │
└────┬────┘                    └────┬────┘
     │                              │
     │ 1. Load existing identity    │
     │    (hardware_id + keys)      │
     │                              │
     │ 2. Connect + send auth       │
     │    - hardware_id             │
     │    - session_token (if have) │
     ├─────────────────────────────>│
     │                              │
     │ 3. Server sends challenge    │
     │<─────────────────────────────┤
     │                              │
     │ 4. Sign challenge            │
     ├─────────────────────────────>│
     │                              │
     │ 5. Server verifies against   │
     │    stored public key         │
     │                              │
     │ 6. Session restored          │
     │<─────────────────────────────┤
```

---

## 6. IMPLEMENTATION PLAN

### Phase 1: Shared Identity Library (Week 1)
**Priority**: HIGH

**Tasks**:
- [ ] Create `/rangerblock/lib/identity-service.cjs`
- [ ] Port hardware fingerprinting from identityService.ts to Node.js
- [ ] Implement RSA-2048 key generation
- [ ] Implement signature creation/verification
- [ ] Create `~/.rangerblock/` storage structure
- [ ] Write unit tests

**Files to Create**:
```
/rangerblock/lib/
├── identity-service.cjs      # Core identity logic
├── crypto-utils.cjs          # RSA/signing helpers
├── storage-utils.cjs         # File system operations
└── identity-service.test.js  # Tests
```

---

### Phase 2: Auth Server (Week 2)
**Priority**: HIGH

**Tasks**:
- [ ] Create `/rangerblock/server-only/auth-server.cjs`
- [ ] Implement challenge-response protocol
- [ ] Store hardware_id → public_key mappings
- [ ] Implement session token generation (JWT-like)
- [ ] Add ban list functionality
- [ ] Integrate kill switch listener
- [ ] Add Commander notification endpoint

**Files to Create**:
```
/rangerblock/server-only/
├── auth-server.cjs           # Main auth server
├── user-database.cjs         # User storage (SQLite)
├── session-manager.cjs       # Token management
├── ban-list.cjs              # Banned users/hardware IDs
└── kill-switch-listener.cjs  # Rain Protocol integration
```

**Database Schema**:
```sql
CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    hardware_id TEXT UNIQUE NOT NULL,
    public_key TEXT NOT NULL,
    nickname TEXT,
    created_at DATETIME,
    last_seen DATETIME,
    is_banned BOOLEAN DEFAULT 0,
    ban_reason TEXT,
    message_count INTEGER DEFAULT 0,
    trust_score INTEGER DEFAULT 50
);

CREATE TABLE sessions (
    id INTEGER PRIMARY KEY,
    user_id INTEGER,
    token TEXT UNIQUE,
    created_at DATETIME,
    expires_at DATETIME,
    ip_address TEXT,
    FOREIGN KEY (user_id) REFERENCES users(id)
);

CREATE TABLE audit_log (
    id INTEGER PRIMARY KEY,
    user_id INTEGER,
    action TEXT,
    details TEXT,
    timestamp DATETIME,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
```

---

### Phase 3: Update blockchain-chat.cjs (Week 3)
**Priority**: MEDIUM

**Tasks**:
- [ ] Import shared identity service
- [ ] Replace simple registration with challenge-response
- [ ] Add persistent identity support
- [ ] Add session token handling
- [ ] Display identity status in UI
- [ ] Handle kill switch signals

**Code Changes**:
```javascript
// OLD (current)
ws.send(JSON.stringify({
    type: 'register',
    nickname: nickname
}));

// NEW (with security)
const identity = new RangerBlockIdentity();
const myIdentity = await identity.getOrCreateIdentity(nickname);

// Wait for challenge from server
ws.on('message', (data) => {
    const msg = JSON.parse(data);
    if (msg.type === 'challenge') {
        const signature = identity.signMessage(msg.nonce);
        ws.send(JSON.stringify({
            type: 'register',
            hardware_id: myIdentity.hardwareId,
            public_key: myIdentity.publicKey,
            signature: signature,
            nickname: nickname
        }));
    }
});
```

---

### Phase 4: Update voice-chat.cjs (Week 4)
**Priority**: MEDIUM

**Tasks**:
- [ ] Import shared identity service
- [ ] Add challenge-response auth
- [ ] Add voice stream encryption (AES-256-GCM)
- [ ] Add call authentication (verify caller identity)
- [ ] Handle kill switch signals

**Voice Encryption**:
```javascript
// Generate per-call session key
const sessionKey = crypto.randomBytes(32);

// Encrypt voice data before sending
function encryptVoice(audioBuffer) {
    const iv = crypto.randomBytes(12);
    const cipher = crypto.createCipheriv('aes-256-gcm', sessionKey, iv);
    const encrypted = Buffer.concat([cipher.update(audioBuffer), cipher.final()]);
    const authTag = cipher.getAuthTag();
    return Buffer.concat([iv, authTag, encrypted]);
}

// Key exchange: Encrypt session key with recipient's public key
const encryptedKey = crypto.publicEncrypt(recipientPublicKey, sessionKey);
```

---

### Phase 5: Update ranger-chat-lite (Week 5)
**Priority**: MEDIUM

**Tasks**:
- [ ] Move identity storage to shared `~/.rangerblock/`
- [ ] Enable RSA signing for all messages
- [ ] Add TLS/WSS support
- [ ] Integrate with auth server
- [ ] Add kill switch handling in Electron

---

### Phase 6: Commander Integration (Week 6)
**Priority**: HIGH

**Tasks**:
- [ ] Create user management API
- [ ] Build network dashboard
- [ ] Integrate Rain Protocol triggers
- [ ] Add real-time alerts for suspicious activity
- [ ] Implement trust score system

---

## 7. KILL SWITCH INTEGRATION

### Server-Side Kill Switch Listener
**File**: `/rangerblock/server-only/kill-switch-listener.cjs`

```javascript
const KILL_COMMANDS = {
    'gentle-rain': softKill,      // Graceful shutdown
    'thunderstorm': hardKill,     // Immediate termination
    'flood': nuclearKill          // Complete purge
};

function startKillSwitchListener(commanderPublicKey) {
    // Listen on secret port for Commander signals
    const ws = new WebSocket('ws://localhost:XXXX/commander');

    ws.on('message', (data) => {
        const msg = JSON.parse(data);

        // Verify Commander signature
        if (!verifyCommanderSignature(msg, commanderPublicKey)) {
            console.log('⚠️ Invalid kill switch attempt!');
            return;
        }

        // Execute kill command
        if (KILL_COMMANDS[msg.command]) {
            KILL_COMMANDS[msg.command](msg.params);
        }
    });
}
```

### Client-Side Kill Switch Handling
```javascript
// All clients check for kill switch on connect
ws.on('message', (data) => {
    const msg = JSON.parse(data);

    if (msg.type === 'kill-switch') {
        console.log('⚠️ Network shutdown initiated');

        switch (msg.level) {
            case 'soft':
                // Save state, graceful exit
                saveState();
                process.exit(0);
                break;
            case 'hard':
                // Immediate exit
                process.exit(1);
                break;
            case 'nuclear':
                // Wipe local data
                wipeLocalData();
                process.exit(1);
                break;
        }
    }
});
```

---

## 8. TRUST SCORE SYSTEM

### How It Works
Each user starts with trust score **50** (neutral).

**Score Increases**:
- +1 per day active (max +7/week)
- +5 for verified Commander interaction
- +10 for reporting valid abuse

**Score Decreases**:
- -5 for spam detection
- -10 for suspicious patterns
- -20 for attempted impersonation
- -50 for confirmed abuse (triggers review)

**Trust Levels**:
```
0-19:   BANNED (cannot connect)
20-39:  RESTRICTED (rate limited, monitored)
40-59:  NORMAL (standard access)
60-79:  TRUSTED (higher limits)
80-100: VERIFIED (full access, can report)
```

---

## 9. FILE LOCATIONS SUMMARY

### Classified (Commander Only)
```
~/.claude/ranger/classified/
├── RANGERBLOCK_KILL_SWITCH_PLAN.md       # Rain Protocol
├── RANGERBLOCK_SECURITY_INTEGRATION_PLAN.md  # This document
└── rain/                                  # Kill switch code (future)
    ├── commander-keys/
    └── rain-protocol.cjs
```

### Shared Identity (All Apps)
```
~/.rangerblock/
├── identity/
├── keys/
├── sessions/
└── config/
```

### Source Code
```
/Users/ranger/rangerplex-ai/rangerblock/
├── lib/
│   ├── identity-service.cjs      # NEW
│   ├── crypto-utils.cjs          # NEW
│   └── storage-utils.cjs         # NEW
├── server-only/                   # NEW
│   ├── auth-server.cjs
│   ├── user-database.cjs
│   └── kill-switch-listener.cjs
└── just-chat/
    ├── blockchain-chat.cjs       # UPDATE
    └── voice-chat.cjs            # UPDATE
```

---

## 10. SECURITY CHECKLIST

### Before Going Live:

- [ ] All communications over WSS (TLS)
- [ ] Private keys never leave device
- [ ] Hardware IDs salted with secret
- [ ] Session tokens expire after 24 hours
- [ ] Rate limiting on all endpoints
- [ ] Audit logging enabled
- [ ] Kill switch tested on test network
- [ ] Commander keys generated offline
- [ ] Backup keys in secure location
- [ ] Ban list functionality tested

---

## 11. NEXT STEPS

**Immediate** (awaiting green light):
1. Create `/rangerblock/lib/identity-service.cjs`
2. Port hardware fingerprinting from TypeScript
3. Test on all platforms

**Short-term**:
4. Build auth server
5. Update blockchain-chat.cjs
6. Update voice-chat.cjs

**Medium-term**:
7. Update ranger-chat-lite
8. Build Commander dashboard
9. Full integration testing

---

**Document Classification**: COMMANDER EYES ONLY
**Created**: December 3, 2024
**Author**: Ranger (AIR9cd99c4515aeb3f6)
**For**: David Keane (IR240474)
**Related**: RANGERBLOCK_KILL_SWITCH_PLAN.md

🎖️ Rangers lead the way!

---

## AWAITING GREEN LIGHT FOR IMPLEMENTATION
