# Ginxsom Admin API

A Nostr-compliant admin interface for the Ginxsom Blossom server that provides programmatic access to server statistics, configuration, and file management operations.

## Overview

The admin API allows server administrators to:
- View server statistics (file counts, storage usage, user metrics)
- Retrieve and update server configuration settings
- Browse recent uploaded files with pagination
- Monitor server health and disk usage

All operations require Nostr authentication using admin-authorized public keys.

## Quick Start

### 1. Configure Admin Access

Add your admin pubkey to the server configuration:

```bash
# Generate admin keys (keep private key secure!)
ADMIN_PRIVKEY=$(nak key generate)
ADMIN_PUBKEY=$(echo "$ADMIN_PRIVKEY" | nak key public)

# Configure server
sqlite3 db/ginxsom.db << EOF
INSERT OR REPLACE INTO server_config (key, value, description) VALUES
    ('admin_pubkey', '$ADMIN_PUBKEY', 'Nostr public key authorized for admin operations'),
    ('admin_enabled', 'true', 'Enable admin interface');
EOF
```

### 2. Build and Start Server

```bash
make clean && make
spawn-fcgi -s /tmp/ginxsom-fcgi.sock -n ./build/ginxsom-fcgi
nginx -c $(pwd)/config/local-nginx.conf
```

### 3. Test the API

```bash
# Run the complete test suite
./tests/admin_test.sh

# Or test individual endpoints
export ADMIN_PRIVKEY="your_private_key_here"
./tests/admin_test.sh
```

## API Endpoints

### GET /api/health
System health check (no authentication required).
```bash
curl http://localhost:9001/api/health
```

### GET /api/stats
Server statistics and metrics.
```json
{
  "status": "success",
  "data": {
    "total_files": 1234,
    "total_bytes": 104857600,
    "total_size_mb": 100.0,
    "unique_uploaders": 56,
    "avg_file_size": 85049,
    "file_types": {
      "image/png": 45,
      "image/jpeg": 32
    }
  }
}
```

### GET /api/config
Current server configuration.
```json
{
  "status": "success",
  "data": {
    "max_file_size": "104857600",
    "require_auth": "false",
    "server_name": "ginxsom",
    "nip94_enabled": "true"
  }
}
```

### PUT /api/config
Update server configuration.
```json
{
  "max_file_size": "209715200",
  "require_auth": "true",
  "nip94_enabled": "true"
}
```

### GET /api/files
Recent uploaded files with pagination.
```json
{
  "status": "success",
  "data": {
    "files": [
      {
        "sha256": "abc123...",
        "size": 184292,
        "type": "application/pdf",
        "uploaded_at": 1725105921,
        "uploader_pubkey": "def456...",
        "url": "http://localhost:9001/abc123.pdf"
      }
    ],
    "total": 1234,
    "limit": 50,
    "offset": 0
  }
}
```

## Manual API Usage with nak and curl

### Generate Admin Authentication Event

```bash
# Create an authenticated event
EVENT=$(nak event -k 24242 -c "admin_request" \
    --tag t="GET" \
    --tag expiration="$(date -d '+1 hour' +%s)" \
    --sec "$ADMIN_PRIVKEY")

# Send authenticated request
AUTH_HEADER="Nostr $(echo "$EVENT" | base64 -w 0)"
curl -H "Authorization: $AUTH_HEADER" http://localhost:9001/api/stats
```

### Update Configuration

```bash
# Create PUT event (method in tag)
EVENT=$(nak event -k 24242 -c "admin_request" \
    --tag t="PUT" \
    --tag expiration="$(date -d '+1 hour' +%s)" \
    --sec "$ADMIN_PRIVKEY")

AUTH_HEADER="Nostr $(echo "$EVENT" | base64 -w 0)"

curl -X PUT -H "Authorization: $AUTH_HEADER" \
     -H "Content-Type: application/json" \
     -d '{"max_file_size": "209715200", "require_auth": "true"}' \
     http://localhost:9001/api/config
```

## Security Features

- **Nostr Authentication**: All admin operations require valid Nostr kind 24242 events
- **Pubkey Verification**: Only events signed by configured admin pubkeys are accepted
- **Event Expiration**: Admin events must include expiration timestamps for security
- **Access Control**: Separate enable/disable flag for admin interface

## Development and Testing

### Prerequisites
- nak (https://github.com/fiatjaf/nak)
- curl, jq
- sqlite3

### Run Tests
```bash
# Make test script executable
chmod +x tests/admin_test.sh

# Run complete test suite
./tests/admin_test.sh

# Run with specific admin key
export ADMIN_PRIVKEY="your_private_key"
./tests/admin_test.sh
```

### Build System
```bash
# Clean build
make clean

# Build with debug info
make debug

# Run FastCGI process
make run
```

## Files Added/Modified

- `src/admin_api.h` - Admin API function declarations
- `src/admin_api.c` - Complete admin API implementation
- `src/main.c` - Updated with admin API routing
- `config/local-nginx.conf` - Updated with admin API routes
- `tests/admin_test.sh` - Complete test suite
- `Makefile` - Updated to compile admin_api.c
- `README_ADMIN_API.md` - This documentation

## Future Enhancements

- **Nostr Relay Integration**: Automatic relay subscription for remote admin control
- **Admin Pubkey Rotation**: Support for multiple admin keys and key rotation
- **Audit Logging**: Detailed logging of admin operations
- **Rate Limiting**: Prevent abuse of admin endpoints
- **Web Dashboard**: Optional HTML/CSS/JavaScript frontend

---

The admin API provides a secure, Nostr-compliant interface for server management through command-line tools while maintaining full compatibility with the existing Blossom protocol implementation.