Files
pic/api/API_DOCUMENTATION.md
T
Constantin 2277b11563 init
2025-09-12 23:04:52 +03:00

21 KiB

Personal Internet Cell API Documentation

Overview

The Personal Internet Cell API provides a comprehensive REST interface for managing all aspects of a personal internet cell, including network services, VPN management, email/calendar/file services, routing, and security features.

Base URL: http://localhost:3000/api
Content-Type: application/json
Authentication: Currently supports local access only (127.0.0.1, ::1, localhost)

Table of Contents

  1. Authentication
  2. Error Handling
  3. Health & Status
  4. Configuration Management
  5. Network Services
  6. WireGuard VPN
  7. Peer Management
  8. Email Services
  9. Calendar Services
  10. File Services
  11. Routing Services
  12. Vault & Security
  13. Container Management
  14. Logging & Monitoring

Authentication

Currently, the API only accepts requests from localhost for security reasons. All endpoints require the client to be running on the same machine as the API server.

# Valid client IPs
127.0.0.1
::1
localhost

Error Handling

All API endpoints return consistent error responses:

{
  "error": "Error description",
  "timestamp": "2024-01-01T12:00:00Z",
  "service": "service_name"
}

Common HTTP status codes:

  • 200 - Success
  • 400 - Bad Request (invalid parameters)
  • 403 - Forbidden (access denied)
  • 404 - Not Found
  • 500 - Internal Server Error

Health & Status

Get Cell Status

GET /status

Returns overall cell status including all services.

Response:

{
  "cell_name": "personal-internet-cell",
  "domain": "cell.local",
  "uptime": 3600,
  "peers_count": 5,
  "services": {
    "network": {
      "running": true,
      "status": "online"
    },
    "wireguard": {
      "running": true,
      "status": "online"
    },
    "email": {
      "running": true,
      "status": "online"
    },
    "calendar": {
      "running": true,
      "status": "online"
    },
    "files": {
      "running": true,
      "status": "online"
    }
  },
  "timestamp": "2024-01-01T12:00:00Z"
}

Health Check

GET /health

Simple health check endpoint.

Response:

{
  "status": "healthy",
  "timestamp": "2024-01-01T12:00:00Z",
  "version": "1.0.0"
}

Get All Services Status

GET /services/status

Returns detailed status of all services.

Response:

{
  "network": {
    "running": true,
    "status": "online",
    "dns_running": true,
    "dhcp_running": true,
    "ntp_running": true
  },
  "wireguard": {
    "running": true,
    "status": "online",
    "peers_count": 5
  },
  "email": {
    "running": true,
    "status": "online",
    "users_count": 3
  },
  "calendar": {
    "running": true,
    "status": "online",
    "calendars_count": 2
  },
  "files": {
    "running": true,
    "status": "online",
    "storage_used": "1.2GB"
  },
  "routing": {
    "running": true,
    "status": "online",
    "nat_rules_count": 3
  },
  "vault": {
    "running": true,
    "status": "online",
    "ca_configured": true,
    "certificates_count": 5
  },
  "timestamp": "2024-01-01T12:00:00Z"
}

Configuration Management

Get Configuration

GET /config

Returns current cell configuration.

Response:

{
  "cell_name": "personal-internet-cell",
  "domain": "cell.local",
  "ip_range": "10.0.0.0/24",
  "wireguard_port": 51820,
  "dns_port": 53,
  "dhcp_range": "10.0.0.100-10.0.0.200"
}

Update Configuration

PUT /config

Update cell configuration.

Request:

{
  "cell_name": "my-cell",
  "domain": "mycell.local",
  "ip_range": "192.168.1.0/24"
}

Response:

{
  "message": "Configuration updated successfully"
}

Network Services

Get DNS Records

GET /dns/records

Returns all DNS records.

Response:

[
  {
    "name": "www",
    "type": "A",
    "value": "10.0.0.10",
    "ttl": 3600
  },
  {
    "name": "mail",
    "type": "CNAME",
    "value": "www",
    "ttl": 3600
  }
]

Add DNS Record

POST /dns/records

Add a new DNS record.

Request:

{
  "zone": "cell.local",
  "name": "api",
  "type": "A",
  "value": "10.0.0.5",
  "ttl": 3600
}

Get DHCP Leases

GET /dhcp/leases

Returns current DHCP leases.

Response:

[
  {
    "mac": "00:11:22:33:44:55",
    "ip": "10.0.0.100",
    "hostname": "laptop",
    "timestamp": "2024-01-01T10:00:00Z"
  }
]

Add DHCP Reservation

POST /dhcp/reservations

Add a DHCP reservation.

Request:

{
  "mac": "00:11:22:33:44:55",
  "ip": "10.0.0.50",
  "hostname": "server"
}

Get Network Info

GET /network/info

Returns detailed network information.

Response:

{
  "interfaces": [
    {
      "name": "eth0",
      "ip": "192.168.1.100",
      "mac": "00:11:22:33:44:55",
      "status": "up"
    }
  ],
  "gateway": "192.168.1.1",
  "dns_servers": ["8.8.8.8", "1.1.1.1"],
  "routing_table": [
    {
      "destination": "0.0.0.0/0",
      "gateway": "192.168.1.1",
      "interface": "eth0"
    }
  ]
}

Get DNS Status

GET /dns/status

Returns DNS service status.

Response:

{
  "running": true,
  "status": "online",
  "zones_count": 2,
  "records_count": 15,
  "queries_per_second": 25.5,
  "cache_hit_rate": 0.85
}

Get NTP Status

GET /ntp/status

Returns NTP service status.

Response:

{
  "running": true,
  "status": "online",
  "synchronized": true,
  "stratum": 3,
  "reference_id": "192.168.1.1",
  "offset": 0.001234
}

WireGuard VPN

Get WireGuard Status

GET /wireguard/status

Returns WireGuard service status.

Response:

{
  "running": true,
  "status": "online",
  "interface": "wg0",
  "peers_count": 5,
  "total_traffic": {
    "bytes_sent": 1048576,
    "bytes_received": 2097152
  }
}

Get WireGuard Peers

GET /wireguard/peers

Returns all WireGuard peers.

Response:

[
  {
    "name": "alice",
    "public_key": "abc123...",
    "ip": "10.0.0.2",
    "allowed_ips": "10.0.0.2/32",
    "last_handshake": "2024-01-01T12:00:00Z",
    "transfer_rx": 1048576,
    "transfer_tx": 2097152
  }
]

Add WireGuard Peer

POST /wireguard/peers

Add a new WireGuard peer.

Request:

{
  "name": "bob",
  "public_key": "def456...",
  "ip": "10.0.0.3",
  "allowed_ips": "10.0.0.3/32"
}

Generate Peer Keys

POST /wireguard/keys/peer

Generate new WireGuard keys for a peer.

Request:

{
  "peer_name": "charlie"
}

Response:

{
  "private_key": "private_key_here",
  "public_key": "public_key_here",
  "peer_name": "charlie"
}

Peer Management

Get All Peers

GET /peers

Returns all registered peers.

Response:

[
  {
    "name": "alice",
    "ip": "10.0.0.2",
    "public_key": "abc123...",
    "added_at": "2024-01-01T10:00:00Z"
  }
]

Add Peer

POST /peers

Add a new peer to the registry.

Request:

{
  "name": "bob",
  "ip": "10.0.0.3",
  "public_key": "def456..."
}

Response:

{
  "message": "Peer bob added successfully"
}

Remove Peer

DELETE /peers/{peer_name}

Remove a peer from the registry.

Response:

{
  "message": "Peer bob removed successfully"
}

Update Peer IP

PUT /peers/{peer_name}/update-ip

Update a peer's IP address.

Request:

{
  "ip": "10.0.0.4"
}

Email Services

Get Email Status

GET /email/status

Returns email service status.

Response:

{
  "running": true,
  "status": "online",
  "smtp_running": true,
  "imap_running": true,
  "users_count": 3,
  "domain": "cell.local"
}

Get Email Users

GET /email/users

Returns all email users.

Response:

[
  {
    "username": "alice",
    "domain": "cell.local",
    "email": "alice@cell.local",
    "created_at": "2024-01-01T10:00:00Z"
  }
]

Create Email User

POST /email/users

Create a new email user.

Request:

{
  "username": "bob",
  "domain": "cell.local",
  "password": "secure_password"
}

Delete Email User

DELETE /email/users/{username}

Delete an email user.

Response:

{
  "message": "User bob deleted successfully"
}

Send Email

POST /email/send

Send an email.

Request:

{
  "from_email": "alice@cell.local",
  "to_email": "bob@cell.local",
  "subject": "Hello",
  "body": "This is a test email",
  "html_body": "<p>This is a test email</p>"
}

Calendar Services

Get Calendar Status

GET /calendar/status

Returns calendar service status.

Response:

{
  "running": true,
  "status": "online",
  "users_count": 2,
  "calendars_count": 4,
  "events_count": 25
}

Get Calendar Users

GET /calendar/users

Returns all calendar users.

Response:

[
  {
    "username": "alice",
    "calendars_count": 2,
    "events_count": 15
  }
]

Create Calendar User

POST /calendar/users

Create a new calendar user.

Request:

{
  "username": "bob",
  "password": "secure_password"
}

Create Calendar

POST /calendar/calendars

Create a new calendar.

Request:

{
  "username": "alice",
  "calendar_name": "Work",
  "description": "Work calendar"
}

Get Calendar Events

GET /calendar/events/{username}/{calendar_name}

Returns calendar events.

Query Parameters:

  • start_date: Start date (YYYY-MM-DD)
  • end_date: End date (YYYY-MM-DD)

Response:

[
  {
    "id": "event_1",
    "title": "Meeting",
    "start": "2024-01-01T10:00:00Z",
    "end": "2024-01-01T11:00:00Z",
    "description": "Team meeting"
  }
]

File Services

Get File Status

GET /files/status

Returns file service status.

Response:

{
  "running": true,
  "status": "online",
  "users_count": 3,
  "total_storage": "100GB",
  "used_storage": "25GB"
}

Get File Users

GET /files/users

Returns all file storage users.

Response:

[
  {
    "username": "alice",
    "storage_used": "5GB",
    "files_count": 150
  }
]

Create File User

POST /files/users

Create a new file storage user.

Request:

{
  "username": "bob",
  "password": "secure_password",
  "quota": "10GB"
}

List Files

GET /files/list/{username}

List files for a user.

Query Parameters:

  • folder: Folder path (optional)

Response:

[
  {
    "name": "document.pdf",
    "path": "/documents/document.pdf",
    "size": 1048576,
    "modified": "2024-01-01T10:00:00Z",
    "type": "file"
  },
  {
    "name": "documents",
    "path": "/documents",
    "type": "folder"
  }
]

Upload File

POST /files/upload/{username}

Upload a file.

Request: Multipart form data

  • file: File to upload
  • path: Destination path (optional)

Download File

GET /files/download/{username}/{file_path}

Download a file.

Response: File content

Routing Services

Get Routing Status

GET /routing/status

Returns routing service status.

Response:

{
  "running": true,
  "status": "online",
  "nat_enabled": true,
  "firewall_enabled": true,
  "nat_rules_count": 3,
  "firewall_rules_count": 10,
  "peer_routes_count": 5
}

Get NAT Rules

GET /routing/nat

Returns all NAT rules.

Response:

{
  "nat_rules": [
    {
      "id": "rule_1",
      "source_network": "10.0.0.0/24",
      "target_interface": "eth0",
      "masquerade": true,
      "nat_type": "MASQUERADE",
      "protocol": "ALL"
    }
  ]
}

Add NAT Rule

POST /routing/nat

Add a new NAT rule.

Request:

{
  "source_network": "10.0.0.0/24",
  "target_interface": "eth0",
  "masquerade": true,
  "nat_type": "MASQUERADE",
  "protocol": "ALL"
}

Get Firewall Rules

GET /routing/firewall

Returns all firewall rules.

Response:

{
  "firewall_rules": [
    {
      "id": "rule_1",
      "rule_type": "INPUT",
      "source": "0.0.0.0/0",
      "destination": "10.0.0.0/24",
      "action": "ACCEPT",
      "protocol": "TCP",
      "port": "22"
    }
  ]
}

Add Firewall Rule

POST /routing/firewall

Add a new firewall rule.

Request:

{
  "rule_type": "INPUT",
  "source": "0.0.0.0/0",
  "destination": "10.0.0.0/24",
  "action": "ACCEPT",
  "protocol": "TCP",
  "port": "22"
}

Get Peer Routes

GET /routing/peers

Returns all peer routes.

Response:

{
  "peer_routes": [
    {
      "peer_name": "alice",
      "peer_ip": "10.0.0.2",
      "allowed_networks": ["192.168.1.0/24"],
      "route_type": "split"
    }
  ]
}

Add Peer Route

POST /routing/peers

Add a new peer route.

Request:

{
  "peer_name": "bob",
  "peer_ip": "10.0.0.3",
  "allowed_networks": ["192.168.2.0/24"],
  "route_type": "bridge"
}

Vault & Security

Get Vault Status

GET /vault/status

Returns vault service status.

Response:

{
  "ca_configured": true,
  "age_configured": true,
  "fernet_configured": true,
  "certificates_count": 5,
  "trusted_keys_count": 3,
  "trust_chains_count": 2
}

Get Certificates

GET /vault/certificates

Returns all certificates.

Response:

[
  {
    "common_name": "api.cell.local",
    "domains": ["api.cell.local", "www.cell.local"],
    "created": "2024-01-01T10:00:00Z",
    "expires": "2025-01-01T10:00:00Z",
    "status": "valid"
  }
]

Generate Certificate

POST /vault/certificates

Generate a new certificate.

Request:

{
  "common_name": "mail.cell.local",
  "domains": ["mail.cell.local", "smtp.cell.local"],
  "key_size": 2048,
  "days": 365
}

Get CA Certificate

GET /vault/ca/certificate

Returns the CA certificate.

Response:

{
  "certificate": "-----BEGIN CERTIFICATE-----\n..."
}

Get Trusted Keys

GET /vault/trust/keys

Returns all trusted keys.

Response:

[
  {
    "name": "alice",
    "public_key": "age1...",
    "trust_level": "direct",
    "added_at": "2024-01-01T10:00:00Z"
  }
]

Add Trusted Key

POST /vault/trust/keys

Add a new trusted key.

Request:

{
  "name": "bob",
  "public_key": "age1...",
  "trust_level": "direct"
}

Container Management

List Containers

GET /containers

Returns all containers.

Response:

[
  {
    "id": "abc123",
    "name": "cell-api",
    "status": "running",
    "image": "personalinternetcell-api:latest",
    "labels": {}
  }
]

Start Container

POST /containers/{name}/start

Start a container.

Response:

{
  "started": true
}

Stop Container

POST /containers/{name}/stop

Stop a container.

Response:

{
  "stopped": true
}

Restart Container

POST /containers/{name}/restart

Restart a container.

Response:

{
  "restarted": true
}

Get Container Logs

GET /containers/{name}/logs

Returns container logs.

Query Parameters:

  • tail: Number of lines to return (default: 100)

Response:

{
  "logs": "Container log output..."
}

Get Container Stats

GET /containers/{name}/stats

Returns container statistics.

Response:

{
  "cpu_usage": 2.5,
  "memory_usage": "512MB",
  "network_rx": 1048576,
  "network_tx": 2097152,
  "disk_usage": "1GB"
}

Logging & Monitoring

Get Backend Logs

GET /logs

Returns backend log file contents.

Query Parameters:

  • lines: Number of lines to return (default: 100)

Response:

{
  "log": "Log file contents..."
}

Get Health History

GET /health/history

Returns recent health check results.

Response:

[
  {
    "timestamp": "2024-01-01T12:00:00Z",
    "network": {"status": "online"},
    "wireguard": {"status": "online"},
    "email": {"status": "online"},
    "calendar": {"status": "online"},
    "files": {"status": "online"},
    "routing": {"status": "online"},
    "vault": {"status": "online"},
    "alerts": []
  }
]

Usage Examples

Python Client Example

import requests

API_BASE = "http://localhost:3000/api"

def get_cell_status():
    response = requests.get(f"{API_BASE}/status")
    return response.json()

def add_peer(name, ip, public_key):
    data = {
        "name": name,
        "ip": ip,
        "public_key": public_key
    }
    response = requests.post(f"{API_BASE}/peers", json=data)
    return response.json()

def get_service_logs(service, lines=50):
    response = requests.get(f"{API_BASE}/logs?lines={lines}")
    return response.json()

# Usage
status = get_cell_status()
print(f"Cell status: {status['cell_name']}")

result = add_peer("alice", "10.0.0.2", "abc123...")
print(f"Add peer result: {result}")

cURL Examples

# Get cell status
curl -X GET http://localhost:3000/api/status

# Add a peer
curl -X POST http://localhost:3000/api/peers \
  -H "Content-Type: application/json" \
  -d '{"name": "alice", "ip": "10.0.0.2", "public_key": "abc123..."}'

# Get service logs
curl -X GET "http://localhost:3000/api/logs?lines=100"

# Update configuration
curl -X PUT http://localhost:3000/api/config \
  -H "Content-Type: application/json" \
  -d '{"cell_name": "my-cell"}'

JavaScript Client Example

const API_BASE = 'http://localhost:3000/api';

async function getCellStatus() {
    const response = await fetch(`${API_BASE}/status`);
    return await response.json();
}

async function addPeer(name, ip, publicKey) {
    const response = await fetch(`${API_BASE}/peers`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            name: name,
            ip: ip,
            public_key: publicKey
        })
    });
    return await response.json();
}

// Usage
getCellStatus().then(status => {
    console.log('Cell status:', status);
});

addPeer('alice', '10.0.0.2', 'abc123...').then(result => {
    console.log('Add peer result:', result);
});

Rate Limiting

Currently, no rate limiting is implemented. However, it's recommended to:

  • Limit requests to reasonable frequencies
  • Implement exponential backoff for retries
  • Cache responses when appropriate

Best Practices

  1. Error Handling: Always check for errors in responses
  2. Logging: Use appropriate log levels for debugging
  3. Configuration: Validate configuration before applying
  4. Security: Keep private keys and secrets secure
  5. Monitoring: Regularly check service health
  6. Backup: Create regular configuration backups

Troubleshooting

Common Issues

  1. Connection Refused: Ensure the API server is running
  2. 403 Forbidden: Check that you're accessing from localhost
  3. Service Not Found: Verify the service is properly configured
  4. Configuration Errors: Check configuration validation

Debug Commands

# Check API server status
curl -X GET http://localhost:3000/api/health

# Check all services status
curl -X GET http://localhost:3000/api/services/status

# Get recent logs
curl -X GET "http://localhost:3000/api/logs?lines=50"

# Check health history
curl -X GET http://localhost:3000/api/health/history

Version History

  • v1.0.0: Initial API release with basic functionality
  • v1.1.0: Added configuration management and backup features
  • v1.2.0: Enhanced logging and monitoring capabilities
  • v1.3.0: Added service bus and event-driven architecture
  • v1.4.0: Improved error handling and validation

Support

For issues and questions:

  1. Check the logs: GET /api/logs
  2. Verify service status: GET /api/services/status
  3. Review configuration: GET /api/config
  4. Check health history: GET /api/health/history

License

This API is part of the Personal Internet Cell project and is licensed under the MIT License.