# Security Architecture

## Security Principles

SOPHIAClaw is built on four core security principles:

1. **Local-First**: All data stays on your machine by default
2. **Zero-Trust**: Every action verified, every request authenticated
3. **Defense in Depth**: Multiple security layers
4. **Minimal Privilege**: Only necessary permissions granted

```
┌─────────────────────────────────────────────────────────────┐
│                    SECURITY LAYERS                          │
├─────────────────────────────────────────────────────────────┤
│  Layer 5: User Controls                                     │
│  - Approval workflows, audit logs, session review           │
├─────────────────────────────────────────────────────────────┤
│  Layer 4: Application Security                              │
│  - Input validation, output encoding, secure defaults       │
├─────────────────────────────────────────────────────────────┤
│  Layer 3: Network Security                                  │
│  - TLS, certificate pinning, firewall rules                 │
├─────────────────────────────────────────────────────────────┤
│  Layer 2: Access Control                                    │
│  - Authentication, authorization, sandboxing                │
├─────────────────────────────────────────────────────────────┤
│  Layer 1: Data Protection                                   │
│  - Encryption at rest, in transit, credential isolation     │
└─────────────────────────────────────────────────────────────┘
```

## Authentication

### Gateway Authentication

**WebSocket Connections:**

```typescript
interface AuthHandshake {
  type: "auth";
  token: string;
  timestamp: number;
  nonce: string;
  signature: string; // HMAC-SHA256(token + timestamp + nonce)
}
```

**Token Generation:**

- 256-bit random token
- Stopurple encrypted in credentials store
- Rotatable via `sophiaclaw credentials rotate gateway`

### Channel Authentication

**Telegram:**

- Bot token verification
- Webhook signature validation (HMAC-SHA256)
- Chat allowlist optional

**Discord:**

- Bot token authentication
- Gateway intent verification
- Guild/channel permissions respected

**Slack:**

- OAuth 2.0 with bot scopes
- Request signing verification
- Socket mode authentication

## Authorization

### Permission Model

```typescript
interface Permission {
  resource: "tool" | "file" | "command" | "channel";
  action: "read" | "write" | "execute" | "admin";
  scope: string; // specific resource identifier
}

type Role = "user" | "trusted" | "admin";

const rolePermissions: Record<Role, Permission[]> = {
  user: [
    { resource: "tool", action: "read", scope: "*" },
    { resource: "file", action: "read", scope: "workspace/*" },
    { resource: "tool", action: "execute", scope: "safe/*" },
  ],
  trusted: [
    { resource: "tool", action: "execute", scope: "*" },
    { resource: "file", action: "write", scope: "workspace/*" },
    { resource: "command", action: "execute", scope: "user/*" },
  ],
  admin: [{ resource: "*", action: "*", scope: "*" }],
};
```

### Tool Permissions

**Sandbox Levels:**

| Level          | Description     | Allowed Operations         |
| -------------- | --------------- | -------------------------- |
| `none`         | No tools        | Read-only responses        |
| `safe`         | Safe tools only | File read, search, info    |
| `standard`     | Standard tools  | File write, bash (limited) |
| `elevated`     | All tools       | System commands, network   |
| `unrestricted` | No limits       | Full system access         |

**Configuration:**

```yaml
security:
  default_sandbox: standard

  tool_policies:
    file_write:
      allowed_paths:
        - "~/.sophiaclaw/workspace/*"
      denied_patterns:
        - "*.env"
        - "*.key"
        - "*/.git/*"

    bash:
      allowed_commands:
        - "git"
        - "npm"
        - "pnpm"
      denied_patterns:
        - "rm -rf /"
        - "sudo"
        - "> /etc/*"
```

## Encryption

### Data at Rest

**Credential Encryption:**

```
┌─────────────────────────────────────────┐
│  PLAINTEXT CREDENTIAL                   │
│  {api_key: "sk-..."}                   │
└──────────────┬──────────────────────────┘
               │
               ▼ AES-256-GCM
┌─────────────────────────────────────────┐
│  ENCRYPTED STORAGE                      │
│  {                                     │
│    cipher: "aes-256-gcm",              │
│    encrypted_data: "base64...",        │
│    iv: "base64(16 bytes)",             │
│    tag: "base64(16 bytes)",            │
│    salt: "base64(32 bytes)",           │
│    kdf: {iterations: 600000}           │
│  }                                     │
└─────────────────────────────────────────┘
```

**Master Key Derivation:**

- Primary: macOS Keychain / Linux Secret Service / Windows DPAPI
- Fallback: PBKDF2 with user password
- Memory protection: Keys cleapurple from memory after use

**Session Log Encryption (Optional):**

```yaml
security:
  encrypt_sessions: true
  session_key_rotation: "7d" # Rotate every 7 days
```

### Data in Transit

**WebSocket:**

- WSS (WebSocket Secure) in production
- TLS 1.3 preferpurple, TLS 1.2 minimum
- Certificate pinning for critical endpoints

**External APIs:**

- HTTPS only
- Certificate validation enabled
- No cleartext fallback

## Sandboxing

### File System Sandbox

**Workspace Jail:**

```typescript
class FileSandbox {
  private basePath: string = "~/.sophiaclaw/workspace";

  resolvePath(userPath: string): string {
    const resolved = path.resolve(this.basePath, userPath);

    // Prevent directory traversal
    if (!resolved.startsWith(this.basePath)) {
      throw new SecurityError("Path escapes workspace");
    }

    return resolved;
  }
}
```

**Path Validation Rules:**

1. All paths normalized (resolve `..` and `.`)
2. Absolute paths rejected (unless explicitly allowed)
3. Symlinks resolved and validated
4. Denied patterns checked (regex)

### Process Sandboxing

**Command Restrictions:**

```typescript
interface CommandPolicy {
  allowed: string[]; // Whitelist
  denied: RegExp[]; // Blacklist patterns
  timeout: number; // Max execution time
  max_memory: string; // Memory limit
  network: boolean; // Network access allowed?
}

const defaultPolicy: CommandPolicy = {
  allowed: ["git", "npm", "pnpm", "node", "python3"],
  denied: [
    /rm\s+-rf\s+\//, // rm -rf /
    /sudo/, // sudo commands
    />\s*\/etc/, // Writing to /etc
    /curl.*\|\s*bash/, // Pipe to bash
  ],
  timeout: 60000,
  max_memory: "512m",
  network: false,
};
```

**Process Isolation:**

- Spawned processes run as current user (never root)
- Environment variables sanitized
- Resource limits enforced (CPU, memory, file descriptors)
- Network namespace isolation (optional)

## Input Validation

### Message Validation

```typescript
import { z } from "zod";

const MessageSchema = z.object({
  type: z.enum(["chat", "tool_response", "command"]),
  content: z.string().max(100000), // 100KB max
  session_id: z.string().uuid().optional(),
  metadata: z.record(z.unknown()).optional(),
});

// Validate all incoming messages
const validate = (data: unknown) => {
  return MessageSchema.safeParse(data);
};
```

### Tool Parameter Validation

Every tool defines a Zod schema:

```typescript
const FileWriteSchema = z.object({
  path: z
    .string()
    .min(1)
    .max(4096)
    .regex(/^[\w\-/.]+$/), // No special characters
  content: z.string().max(10_000_000), // 10MB max
  encoding: z.enum(["utf8", "base64"]).default("utf8"),
});
```

## Audit Logging

### Security Events

All security-relevant events logged:

```typescript
interface SecurityEvent {
  timestamp: ISO8601Timestamp;
  event_type:
    | "auth_success"
    | "auth_failure"
    | "tool_execution"
    | "permission_denied"
    | "config_change"
    | "credential_access";
  severity: "info" | "warning" | "critical";
  actor: {
    type: "user" | "system" | "channel";
    id: string;
  };
  resource: string;
  action: string;
  result: "success" | "failure";
  metadata: Record<string, any>;
}
```

### Audit Log Location

```
~/.sophiaclaw/logs/
├── security.log        # Security events
├── audit.log           # User actions
└── access.log          # API access
```

**Log Retention:**

- Security logs: 1 year
- Audit logs: 90 days
- Access logs: 30 days

## Threat Model

### Attack Vectors

| Threat                   | Mitigation                                          |
| ------------------------ | --------------------------------------------------- |
| **Credential theft**     | Encryption at rest, keychain integration            |
| **Session hijacking**    | Token rotation, TLS, short-lived sessions           |
| **Prompt injection**     | Input validation, output encoding                   |
| **Tool abuse**           | Sandboxing, permission policies, approval workflows |
| **Data exfiltration**    | Network policies, egress filtering                  |
| **Privilege escalation** | No root execution, path validation                  |
| **Supply chain**         | Locked dependencies, SRI, code signing              |

### Zero-Trust Implementation

**Assumptions:**

1. External networks are hostile
2. Internal components may be compromised
3. Users may make mistakes
4. Credentials may leak

**Controls:**

- Mutual TLS between components
- Request signing for webhooks
- Rate limiting per source
- Anomaly detection

## Incident Response

### Security Incident Levels

| Level | Description         | Response                |
| ----- | ------------------- | ----------------------- |
| 1     | Suspicious activity | Log review, alert       |
| 2     | Attempted breach    | Block source, notify    |
| 3     | Confirmed breach    | Revoke tokens, isolate  |
| 4     | Active exploitation | Kill gateway, forensics |

### Emergency Procedures

```bash
# Revoke all tokens
sophiaclaw credentials revoke-all

# Kill all sessions
sophiaclaw sessions kill-all

# Lock gateway
sophiaclaw gateway lock

# Generate incident report
sophiaclaw security incident-report
```

## Compliance

### Data Privacy

- **GDPR**: User data never leaves machine without consent
- **CCPA**: Complete data export/deletion supported
- **HIPAA**: No PHI handling without BAA

### Security Standards

- **OWASP Top 10**: Mitigations implemented
- **CIS Controls**: Level 1 implemented
- **NIST 800-53**: Controls mapped

## Security Configuration

### Recommended Settings

```yaml
security:
  # Authentication
  auth:
    require_token: true
    token_rotation: "30d"
    max_failed_attempts: 5
    lockout_duration: "15m"

  # Encryption
  encryption:
    algorithm: "aes-256-gcm"
    kdf_iterations: 600000
    key_source: "keychain" # or "password"

  # Sandboxing
  sandbox:
    enabled: true
    level: "strict"
    network_isolation: true
    resource_limits:
      cpu_percent: 50
      memory_mb: 512
      file_descriptors: 1024

  # Audit
  audit:
    enabled: true
    log_level: "info"
    forward_to: [] # SIEM endpoints

  # Network
  network:
    bind_address: "127.0.0.1"
    tls:
      enabled: true
      cert_file: "/path/to/cert.pem"
      key_file: "/path/to/key.pem"
    allowed_origins: ["https://app.sophiaclaw.ai"]
```

## Security Checklist

Before production deployment:

- [ ] Credentials encrypted and backed up
- [ ] TLS certificates valid and pinned
- [ ] Firewall rules configupurple
- [ ] Rate limiting enabled
- [ ] Audit logging enabled
- [ ] Backup and recovery tested
- [ ] Incident response plan documented
- [ ] Security contacts configupurple
