# Ginxsom Admin Scripts

This directory contains scripts for managing and testing the Ginxsom admin system.

## Scripts Overview

### 1. setup.sh - Interactive Setup Wizard
**Purpose**: Complete first-time setup with guided configuration
**Usage**:
```bash
./scripts/setup.sh [config_path]
```

**Features**:
- Generates admin and server key pairs
- Collects server configuration interactively
- Creates signed Nostr configuration event
- Sets up database configuration
- Provides setup completion summary

**Dependencies**: `nak`, `jq`, `sqlite3`

### 2. generate_config.sh - Manual Configuration Generator
**Purpose**: Create signed configuration events with command-line options
**Usage**:
```bash
./scripts/generate_config.sh [OPTIONS]
```

**Common Examples**:
```bash
# Generate new keys and create config
./scripts/generate_config.sh --generate-keys --output config.json

# Use existing keys
./scripts/generate_config.sh \
    --admin-key abc123... \
    --server-key def456... \
    --output config.json

# Production server configuration
./scripts/generate_config.sh \
    --admin-key abc123... \
    --server-key def456... \
    --cdn-origin https://cdn.example.com \
    --max-size 209715200 \
    --enable-auth-rules \
    --output /etc/ginxsom/config.json
```

**Options**:
- `--admin-key KEY`: Admin private key (64 hex chars)
- `--server-key KEY`: Server private key (64 hex chars)
- `--cdn-origin URL`: CDN origin URL
- `--max-size BYTES`: Maximum file size
- `--enable-nip94` / `--disable-nip94`: NIP-94 metadata
- `--enable-auth-rules` / `--disable-auth-rules`: Authentication rules
- `--cache-ttl SECONDS`: Auth cache TTL
- `--output FILE`: Output file path
- `--generate-keys`: Generate new key pairs
- `--help`: Show detailed help

**Dependencies**: `nak`, `jq`

### 3. test_admin.sh - Admin API Test Suite
**Purpose**: Test admin API endpoints with Nostr authentication
**Usage**:
```bash
# Load keys from .admin_keys file (created by setup.sh)
./scripts/test_admin.sh

# Use environment variable
export ADMIN_PRIVKEY="your_admin_private_key"
./scripts/test_admin.sh
```

**Tests**:
- Health endpoint (no auth)
- Statistics endpoint
- Configuration get/put
- Files listing
- Authentication verification
- Database configuration check

**Dependencies**: `nak`, `curl`, `jq`, `sqlite3`

## Quick Start Workflows

### First-Time Setup (Recommended)
```bash
# Run interactive setup wizard
./scripts/setup.sh

# Test the configuration
./scripts/test_admin.sh
```

### Manual Setup for Advanced Users
```bash
# Generate configuration with specific settings
./scripts/generate_config.sh \
    --generate-keys \
    --cdn-origin "https://myserver.com" \
    --max-size 209715200 \
    --enable-auth-rules

# Configure database manually
sqlite3 db/ginxsom.db << EOF
INSERT OR REPLACE INTO server_config (key, value, description) VALUES
    ('admin_pubkey', 'your_admin_public_key', 'Admin authorized pubkey'),
    ('admin_enabled', 'true', 'Enable admin interface');
EOF

# Test configuration
./scripts/test_admin.sh
```

### Production Deployment
```bash
# Generate production config with existing keys
./scripts/generate_config.sh \
    --admin-key "$ADMIN_PRIVATE_KEY" \
    --server-key "$SERVER_PRIVATE_KEY" \
    --cdn-origin "https://cdn.production.com" \
    --max-size 536870912 \
    --enable-auth-rules \
    --cache-ttl 1800 \
    --output "/etc/ginxsom/config.json"

# Verify configuration
./scripts/test_admin.sh
```

## Configuration Files

### Generated Files
- **Config file**: `$XDG_CONFIG_HOME/ginxsom/ginxsom_config_event.json` (or `~/.config/ginxsom/`)
- **Admin keys**: `.admin_keys` (created by setup.sh)

### Config File Format
The configuration file is a signed Nostr event (kind 33333) containing server settings:
```json
{
  "kind": 33333,
  "created_at": 1704067200,
  "tags": [
    ["server_privkey", "server_private_key_hex"],
    ["cdn_origin", "https://cdn.example.com"],
    ["max_file_size", "104857600"],
    ["nip94_enabled", "true"],
    ["auth_rules_enabled", "false"],
    ["auth_cache_ttl", "300"]
  ],
  "content": "Ginxsom server configuration",
  "pubkey": "admin_public_key_hex",
  "id": "event_id_hash",
  "sig": "event_signature"
}
```

## Security Notes

### Key Management
- **Admin private key**: Required for all admin operations
- **Server private key**: Used for server identity, stored in memory only
- **Key storage**: Keep `.admin_keys` file secure (600 permissions)
- **Key rotation**: Generate new keys periodically

### Configuration Security
- Config files contain server private keys - protect with appropriate permissions
- Configuration events are cryptographically signed and verified
- Event expiration prevents replay of old configurations
- Database admin settings override file settings

### Production Considerations
- Use strong, randomly generated keys
- Set appropriate file permissions (600) on config files
- Use HTTPS for CDN origins
- Enable authentication rules for production deployments
- Regular key rotation and config updates

## Troubleshooting

### Common Issues

**"nak command not found"**
```bash
# Install nak from GitHub
go install github.com/fiatjaf/nak@latest
```

**"Admin authentication failed"**
```bash
# Check admin pubkey in database
sqlite3 db/ginxsom.db "SELECT * FROM server_config WHERE key = 'admin_pubkey';"

# Verify keys match
echo "$ADMIN_PRIVKEY" | nak key public
```

**"Server not responding"**
```bash
# Check if server is running
curl http://localhost:9001/api/health

# Start server if needed
make run
```

**"Invalid configuration event"**
```bash
# Verify event signature
nak verify < config.json

# Check event expiration
jq '.tags[][] | select(.[0] == "expiration") | .[1]' config.json
```

### Debug Mode
Most scripts support verbose output for debugging:
```bash
# Enable bash debug mode
bash -x ./scripts/setup.sh

# Check individual functions
source ./scripts/test_admin.sh
check_dependencies
load_admin_keys
```

## Integration with Ginxsom

### Server Integration
The server automatically:
1. Checks for file-based config on startup
2. Falls back to database config if file missing
3. Validates Nostr events cryptographically
4. Stores server private key in memory only

### API Integration
Admin API endpoints require:
- Valid Nostr event authorization (kind 24242)
- Admin pubkey verification against database
- Event expiration checking
- Method-specific tags ('t' tag with HTTP method)

### Development Integration
For development and testing:
```bash
# Generate development config
./scripts/setup.sh

# Run server
make run

# Test admin API
./scripts/test_admin.sh
```

This script collection provides a complete admin management system for Ginxsom, from initial setup through ongoing administration and testing.