### MFA Setup and Verify Flow Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/authentication.md Example bash commands demonstrating the setup and verification flow for Multi-Factor Authentication. ```bash # 1. Setup MFA curl -X POST https://cosmos.example.com/cosmos/api/mfa \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"action":"setup"}' # Returns secret and QR code # User scans QR or enters secret into authenticator app # 2. Verify MFA code from app curl -X POST https://cosmos.example.com/cosmos/api/mfa \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"action":"verify","code":"123456"}' ``` -------------------------------- ### Install Cosmos Server Go SDK Source: https://github.com/azukaar/cosmos-server/blob/master/go-sdk/README.md Install the Cosmos Server Go SDK using the go get command. ```bash go get github.com/azukaar/cosmos-server/go-sdk ``` -------------------------------- ### Terraform VPN Setup Example Source: https://github.com/azukaar/cosmos-server/blob/master/terraform-provider-cosmos/examples/index.md This example demonstrates setting up a VPN on an existing Cosmos server using `cosmos_constellation`, `cosmos_constellation_device`, and `cosmos_constellation_dns` resources. ```terraform resource "cosmos_constellation" "vpn" { name = "my-vpn" } resource "cosmos_constellation_device" "client" { constellation = cosmos_constellation.vpn.name name = "client-device" ip = "10.0.0.2" } resource "cosmos_constellation_dns" "internal" { constellation = cosmos_constellation.vpn.name name = "internal.vpn" ip = "10.0.0.1" } ``` -------------------------------- ### Start Frontend Development Server Source: https://github.com/azukaar/cosmos-server/blob/master/CONTRIBUTE.md Starts the Vite-based React frontend development server. This command requires Node.js and npm to be installed. ```bash npm run client ``` -------------------------------- ### Setup New Cluster Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/constellation.md Guides through the process of initializing a new Constellation cluster. This involves setting up the master node and connecting secondary nodes. ```bash # 1. Initialize master node curl -X POST https://master.cosmos.local/cosmos/api/constellation/create \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "deviceName": "master", "nickname": "Master Node", "ipRange": "172.16.0.0/12" }' # 2. Get master key (from API or configuration) # 3. Connect secondary nodes curl -X POST https://node2.cosmos.local/cosmos/api/constellation/connect \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "masterURL": "https://master.cosmos.local", "masterKey": "key_from_master", "deviceName": "node2", "nickname": "Secondary Node" }' # 4. Verify cluster health curl https://node2.cosmos.local/cosmos/api/constellation/devices \ -H "Authorization: Bearer $TOKEN" ``` -------------------------------- ### Install Cosmos Cloud SDK Source: https://github.com/azukaar/cosmos-server/blob/master/sdk/README.md Install the SDK using npm. This command fetches and installs the necessary package for your project. ```bash npm install cosmos-cloud-sdk ``` -------------------------------- ### Setup or Verify Multi-Factor Authentication Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Manage multi-factor authentication settings. Use 'setup' to get a secret and QR code, 'verify' to confirm a TOTP code, or 'disable' to turn off MFA. ```bash curl -X POST https://cosmos.example.com/cosmos/api/mfa \ -H "Content-Type: application/json" \ -d '{"action":"setup"}' ``` ```bash curl -X POST https://cosmos.example.com/cosmos/api/mfa \ -H "Content-Type: application/json" \ -d '{"action":"verify","code":"123456"}' ``` ```bash curl -X POST https://cosmos.example.com/cosmos/api/mfa \ -H "Content-Type: application/json" \ -d '{"action":"disable"}' ``` -------------------------------- ### MFA Setup Request Body Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/authentication.md Initiate the Multi-Factor Authentication setup process by sending an action of 'setup'. ```json { "action": "setup" } ``` -------------------------------- ### Run Dashboard Example Source: https://github.com/azukaar/cosmos-server/blob/master/sdk/examples/index.md Execute the dashboard example script to view server overview, running containers, system metrics, recent events, and container logs. ```bash node sdk/examples/dashboard.mjs ``` -------------------------------- ### Install Docker Source: https://github.com/azukaar/cosmos-server/blob/master/CONTRIBUTE.md Installs Docker using a curl script. Ensure you have the necessary permissions. ```bash curl -fsSL https://get.docker.com | sudo sh ``` -------------------------------- ### Start Development Server Source: https://github.com/azukaar/cosmos-server/blob/master/CONTRIBUTE.md Starts the Cosmos development server with specific configuration overrides for easier testing. It uses a local config folder and a development config file. ```bash npm run start ``` -------------------------------- ### Setup Backup Workflow Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/README.md Steps to create a backup configuration, monitor backups, and restore data. ```bash # 1. Create backup configuration curl -X POST /cosmos/api/backups \ -d '{ "name": "daily-backup", "repository": "s3://bucket/backups", "password": "encryption-password", "source": "/var/lib/cosmos", "crontab": "0 2 * * *" }' # 2. Monitor backup curl /cosmos/api/backups-config # 3. Restore if needed curl -X POST /cosmos/api/backups/daily-backup/restore \ -d '{ "snapshotID": "snapshot-id", "targetPath": "/restore" }' ``` -------------------------------- ### Build and Install Terraform Provider Locally Source: https://github.com/azukaar/cosmos-server/blob/master/terraform-provider-cosmos/README.md Compile the Terraform provider and install it into the local Terraform plugin directory for development. ```bash cd terraform-provider-cosmos make build # compile make install # copy to ~/.terraform.d/plugins/ ``` -------------------------------- ### Terraform Provider Configuration Example Source: https://github.com/azukaar/cosmos-server/blob/master/terraform-provider-cosmos/examples/index.md This snippet shows a basic Terraform provider configuration for the Cosmos provider, including base URL and token. It serves as a starting point for managing resources on an existing Cosmos server. ```terraform provider "cosmos" { base_url = "https://your-cosmos-server.com" token = "your-admin-token" } ``` -------------------------------- ### Terraform Web App Stack Example Source: https://github.com/azukaar/cosmos-server/blob/master/terraform-provider-cosmos/examples/index.md This example shows how to deploy a typical web application stack on a configured Cosmos server. It includes resources for API tokens, Docker volumes, services, routing, backups, and alerts. ```terraform resource "cosmos_api_token" "app_token" { name = "webapp-api-token" } resource "cosmos_docker_volume" "app_data" { name = "webapp-data" } resource "cosmos_docker_service" "app" { name = "webapp" image = "nginx:latest" ports = ["8080:80"] volume = cosmos_docker_volume.app_data.name } resource "cosmos_route" "app_route" { path = "/app" service = cosmos_docker_service.app.name port = 80 } resource "cosmos_backup" "app_backup" { name = "webapp-backup" service = cosmos_docker_service.app.name } resource "cosmos_alert" "app_alert" { name = "webapp-down" service = cosmos_docker_service.app.name on_down = true } ``` -------------------------------- ### Run Demo System Source: https://github.com/azukaar/cosmos-server/blob/master/CONTRIBUTE.md Starts the integrated demo system, allowing you to test the frontend with mocked API calls. ```bash npm run devdemo ``` -------------------------------- ### CRONConfig Struct and Examples Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/types.md Configuration for scheduled jobs. Includes scheduling, command execution, and optional container targeting. Provides examples of crontab formats. ```go type CRONConfig struct { Enabled bool // Job enabled Name string // Job name Crontab string // Cron schedule (5-field format) Command string // Shell command to execute Container string // Container name (optional, for container jobs) } ``` ```text - `0 * * * *` - Every hour - `0 2 * * *` - Daily at 2 AM - `*/15 * * * *` - Every 15 minutes - `0 0 * * 0` - Weekly on Sunday ``` -------------------------------- ### POST /api/mfa Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Setup or verify multi-factor authentication. Supports 'setup', 'verify', or 'disable' actions. Returns MFA secret and QR code data for setup. ```APIDOC ## POST /api/mfa ### Description Setup or verify multi-factor authentication. ### Method POST ### Endpoint /api/mfa ### Parameters #### Request Body - **action** (string) - Yes - "setup", "verify", or "disable" - **code** (string) - Yes - 6-digit TOTP code (for verify) ### Response #### Success Response (200) - **status** (string) - "OK" on success - **secret** (string) - Base32-encoded MFA secret (setup only) - **qr** (string) - QR code data URL (setup only) ``` -------------------------------- ### Terraform Standalone Backup Example Source: https://github.com/azukaar/cosmos-server/blob/master/terraform-provider-cosmos/examples/index.md This example demonstrates the standalone usage of the `cosmos_backup` resource. Note that destroying this resource will permanently delete its associated backups. ```terraform resource "cosmos_backup" "standalone" { name = "my-service-backup" service = "my-service" } ``` -------------------------------- ### Install Cosmos Server with Docker Source: https://github.com/azukaar/cosmos-server/blob/master/readme.md Run this command to install Cosmos Server using Docker. Ensure you are using the correct network mode and volume mounts for your operating system. ```bash sudo docker run -d --network host --privileged --name cosmos-server -h cosmos-server --restart=always -v /var/run/docker.sock:/var/run/docker.sock -v /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket -v /:/mnt/host -v /var/lib/cosmos:/config azukaar/cosmos-server:latest ``` -------------------------------- ### Login and Get JWT Token using JavaScript Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/README.md This JavaScript example shows how to log in to the Cosmos API using the fetch API to obtain a JWT token. The token is then used in the Authorization header for subsequent requests. ```javascript // Login const loginResp = await fetch('https://cosmos.example.com/cosmos/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ nickname: 'admin', password: 'password' }) }); const { token } = await loginResp.json(); // Use token const userResp = await fetch('https://cosmos.example.com/cosmos/api/me', { headers: { 'Authorization': `Bearer ${token}` } }); const user = await userResp.json(); ``` -------------------------------- ### Pagination Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/README.md Most list endpoints support pagination using 'limit' and 'offset' parameters. ```http GET /api/resource?limit=50&offset=0 ``` -------------------------------- ### Terraform Initialization After Local Install Source: https://github.com/azukaar/cosmos-server/blob/master/terraform-provider-cosmos/README.md Re-initialize Terraform after installing a local provider build to ensure it's recognized. ```bash rm .terraform.lock.hcl && terraform init ``` -------------------------------- ### Example Error Response Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/errors.md An example of an error response, specifically indicating invalid credentials. ```json { "status": "error", "error": "Invalid credentials", "code": "AUTH001" } ``` -------------------------------- ### Get and Set Server Configuration Source: https://github.com/azukaar/cosmos-server/blob/master/sdk/README.md Retrieve the current server configuration and then apply updated settings. ```javascript // Config const config = await cosmos.config.get(); await cosmos.config.set(config.data); await cosmos.config.updateDNS({ dnsPort: '53' }); ``` -------------------------------- ### Setup Automated Backup (S3) Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/storage-backup.md Configures remote S3 storage and creates a backup configuration with a specified schedule and retention policy. ```bash # 1. Configure remote storage (S3) curl -X POST https://cosmos.example.com/cosmos/rclone/config/create \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "s3-backup", "type": "s3", "provider": "AWS", "env_auth": true, "region": "us-east-1", "bucket": "my-backups" }' # 2. Create backup configuration curl -X POST https://cosmos.example.com/cosmos/api/backups \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "cosmos-data", "repository": "s3://s3-backup/cosmos", "password": "strong-password", "source": "/var/lib/cosmos", "crontab": "0 2 * * *", "crontabForget": "0 3 * * 0", "retentionPolicy": "keep-daily 7 --keep-weekly 4 --keep-monthly 12" }' # 3. Monitor backups curl https://cosmos.example.com/cosmos/api/backups-config \ -H "Authorization: Bearer $TOKEN" ``` -------------------------------- ### Create and Get User Source: https://github.com/azukaar/cosmos-server/blob/master/sdk/README.md Create a new user with a nickname and password, then retrieve the user's details. ```javascript // Users await cosmos.users.create({ nickname: 'bob', password: '...' }); const user = await cosmos.users.get('bob'); ``` -------------------------------- ### GET /api/backups-config Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md List all configured backups. ```APIDOC ## GET /api/backups-config ### Description List backup configurations. ### Method GET ### Endpoint /api/backups-config ### Headers - Authorization: Bearer {token} - Permission: PERM_RESOURCES_READ ### Response #### Success Response (200) - **status** (string) - "OK" - **data** (SingleBackupConfig[]) - Backup configurations ``` -------------------------------- ### MFA Setup Response Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/authentication.md The response includes a secret key and a QR code for configuring an authenticator app. ```json { "status": "OK", "secret": "JBSWY3DPEBLW64TMMQ======", "qr": "data:image/png;base64,iVBORw0KGgoAAAANS..." } ``` -------------------------------- ### WebSocket Connection Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/README.md Connect to streaming endpoints like logs or metrics using WebSockets. ```websocket wss://cosmos.example.com/cosmos/api/endpoint?token=TOKEN&follow=true ``` -------------------------------- ### Set Cosmos Environment Variables Source: https://github.com/azukaar/cosmos-server/blob/master/sdk/examples/index.md Set the COSMOS_URL and COSMOS_TOKEN environment variables before running any examples. ```bash export COSMOS_URL=https://my-cosmos.example.com export COSMOS_TOKEN=cosmos_xxx ``` -------------------------------- ### Manage Container Lifecycle (Start, Stop, Restart) Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/docker-containers.md Performs lifecycle actions on a specified Docker container. Ensure the correct action is specified for the desired outcome. ```bash # Start container curl -X POST https://cosmos.example.com/cosmos/api/servapps/home-assistant/manage/start \ -H "Authorization: Bearer $TOKEN" ``` ```bash # Stop container curl -X POST https://cosmos.example.com/cosmos/api/servapps/home-assistant/manage/stop \ -H "Authorization: Bearer $TOKEN" ``` ```bash # Restart container curl -X POST https://cosmos.example.com/cosmos/api/servapps/home-assistant/manage/restart \ -H "Authorization: Bearer $TOKEN" ``` -------------------------------- ### Example Success API Response Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/types.md Illustrates the JSON format for a successful API response, containing status and data. ```json { "status": "OK", "data": { "id": "user123", "nickname": "admin" } } ``` -------------------------------- ### Create Cosmos Client and List Containers Source: https://github.com/azukaar/cosmos-server/blob/master/sdk/README.md Initialize the Cosmos client with your server URL and API token. Then, list available Docker containers. ```javascript const { createClient } = require('cosmos-cloud-sdk'); // or: import { createClient } from 'cosmos-cloud-sdk'; const cosmos = createClient({ baseUrl: 'https://my-cosmos.example.com', token: 'cosmos_abc123...', }); // List containers const containers = await cosmos.docker.list(); console.log(containers.data); ``` -------------------------------- ### Initiate Password Reset Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Start the password reset process by providing the user's email address. An email with reset instructions will be sent. ```bash curl -X POST https://cosmos.example.com/cosmos/api/password-reset \ -H "Content-Type: application/json" \ -d '{"email":"user@example.com"}' ``` -------------------------------- ### Login and Get JWT Token using curl Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/README.md This example shows how to log in to the Cosmos API using curl to obtain a JWT token. The token is stored in a temporary cookie file for subsequent requests. ```bash # Login and get token TOKEN=$(curl -X POST https://cosmos.example.com/cosmos/api/login \ -H "Content-Type: application/json" \ -d '{"nickname":"admin","password":"password"}' \ -c /tmp/cookies.txt | jq -r '.token') # Use token in header curl https://cosmos.example.com/cosmos/api/me \ -H "Authorization: Bearer $TOKEN" # Or use cookies curl https://cosmos.example.com/cosmos/api/me \ -b /tmp/cookies.txt ``` -------------------------------- ### Get Deployment Details by Name Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/constellation.md Fetches detailed information for a specific multi-node deployment, identified by its name. Includes node status and container IDs. ```json { "status": "OK", "data": { "name": "web-cluster", "image": "nginx:latest", "replicas": 3, "nodes": ["master", "node2", "node3"], "nodeStatus": { "master": "running", "node2": "running", "node3": "running" }, "containerIDs": { "master": "abc123def456", "node2": "xyz789abc123", "node3": "123456xyz789" } } } ``` -------------------------------- ### Run Initial Storage Sync Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/storage-backup.md Initiates a daily sync for storage backups. Requires an authorization token. ```bash curl -X POST https://cosmos.example.com/cosmos/api/snapraid/daily/sync \ -H "Authorization: Bearer $TOKEN" ``` -------------------------------- ### Build Demo System Source: https://github.com/azukaar/cosmos-server/blob/master/CONTRIBUTE.md Builds the integrated demo system, which includes a frontend with mocked API calls. ```bash npm run demo ``` -------------------------------- ### Run initial sync Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/storage-backup.md Initiates a daily synchronization process for storage backups. ```APIDOC ## POST /cosmos/api/snapraid/daily/sync ### Description Initiates a daily synchronization process for storage backups. ### Method POST ### Endpoint /cosmos/api/snapraid/daily/sync ### Request Example ```json { "example": "curl -X POST https://cosmos.example.com/cosmos/api/snapraid/daily/sync -H \"Authorization: Bearer $TOKEN\"" } ``` ### Response #### Success Response (200) (Response details not provided in source) #### Response Example (Response details not provided in source) ``` -------------------------------- ### Build Frontend for Production Source: https://github.com/azukaar/cosmos-server/blob/master/CONTRIBUTE.md Compiles the frontend application for production deployment. ```bash npm run client-build ``` -------------------------------- ### Terraform Bash Execution Example Source: https://github.com/azukaar/cosmos-server/blob/master/terraform-provider-cosmos/examples/index.md This bash script demonstrates the steps to initialize, plan, and apply a Terraform configuration for the Cosmos provider. It includes instructions for setting up local development overrides. ```bash # 1. Make sure the provider is locally available — either install it from the # registry, or use a dev_overrides block in ~/.terraformrc pointing to a # locally-built binary: # # provider_installation { # dev_overrides { # "cosmos-cloud.io/azukaar/cosmos" = "/path/to/built/binary/dir" # } # direct {} # } cd examples/ terraform init # skip if using dev_overrides terraform plan -var '…' -var '…' terraform apply -var '…' ``` -------------------------------- ### Token Claims Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/authentication.md Example structure of claims within a JWT token, including user ID, role, permissions, and MFA state. ```json { "sub": "user_id", "nickname": "username", "role": 1, "permissions": [100, 101], "mfa_state": 0, "iat": 1717258800, "exp": 1717863600 } ``` -------------------------------- ### GET /api/users/{nickname} Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Get specific user details by their nickname. Requires Authorization and Permission headers. Returns the user object if found. ```APIDOC ## GET /api/users/{nickname} ### Description Get specific user details. ### Method GET ### Endpoint /api/users/{nickname} ### Parameters #### Headers required - Authorization: Bearer {token} - Permission: PERM_USERS_READ #### Path Parameters - **nickname** (string) - Required - Target user's nickname ### Response #### Success Response (200) - **status** (string) - "OK" - **data** (User) - User object #### Error Response - **404**: User not found ``` -------------------------------- ### Example Cosmos Server Configuration Source: https://github.com/azukaar/cosmos-server/wiki/Configuration This JSON object shows a sample configuration for the Cosmos server, including logging, database connection, HTTP/HTTPS settings, and proxy route definitions. ```json { "LoggingLevel": "INFO", "MongoDB": "mongodb+srv://admin:123@localhost:2707", "HTTPConfig": { "TLSCert": "-----BEGIN CERTIFICATE-----\nMIIDVDCCAjy....suLvi4vwSPVvDgitwA==\n-----END CERTIFICATE-----\n", "TLSKey": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEArXof.....ueIAaco9gK0zjl\n-----END RSA PRIVATE KEY-----\n", "AuthPrivateKey": "-----BEGIN PRIVATE KEY-----.....\n-----END PRIVATE KEY-----\n", "AuthPublicKey": "-----BEGIN PUBLIC KEY-----../V8dCG1vn0S4YD4=\n-----END PUBLIC KEY-----\n", "GenerateMissingAuthCert": true, "HTTPSCertificateMode": "PROVIDED", "HTTPPort": "8080", "HTTPSPort": "8443", "ProxyConfig": { "Routes": [ { "Name": "Jellyfin", "Description": "Expose Jellyfin to the internet", "UseHost": false, "Host": "", "UsePathPrefix": true, "PathPrefix": "/jf", "Timeout": 30000, "ThrottlePerMinute": 100, "CORSOrigin": "", "StripPathPrefix": false, "AuthEnabled": false, "Target": "http://jellyfin:8096", "Mode": "SERVAPP" } ] }, "Hostname": "localhost", "SSLEmail": "" }, "DisableUserManagement": false, "NewInstall": false } ``` -------------------------------- ### Register New User Account Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Create a new user account by providing nickname, email, password, and a registration key. The nickname must be alphanumeric and 3-32 characters long. ```bash curl -X POST https://cosmos.example.com/cosmos/api/register \ -H "Content-Type: application/json" \ -d '{"nickname":"newuser","email":"user@example.com","password":"strong_pass","registerKey":"invitation_key"}' ``` -------------------------------- ### GET /api/me Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Get current user profile information. Requires an Authorization header with a Bearer token. Returns the current user object, excluding the password. ```APIDOC ## GET /api/me ### Description Get current user profile information. ### Method GET ### Endpoint /api/me ### Parameters #### Headers required - Authorization: Bearer {token} ### Response #### Success Response (200) - **status** (string) - "OK" - **data** (User) - Current user object (without password) #### Error Response - **401**: Unauthorized ``` -------------------------------- ### Initialize Cosmos Server Go Client Source: https://github.com/azukaar/cosmos-server/blob/master/go-sdk/README.md Initialize the Cosmos Server Go client with custom HTTP client and request interceptors. This example shows how to set up a client with TLS configuration and add an Authorization header. ```go package main import ( "context" "crypto/tls" "fmt" "net/http" cosmossdk "github.com/azukaar/cosmos-server/go-sdk" ) func main() { httpClient := &http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, } addToken := func(ctx context.Context, req *http.Request) error { req.Header.Set("Authorization", "Bearer "+token) return nil } client, err := cosmossdk.NewClient( "https://cosmos.example.com/cosmos", cosmossdk.WithHTTPClient(httpClient), cosmossdk.WithRequestEditorFn(addToken), ) if err != nil { panic(err) } // List routes resp, err := client.GetApiRoutes(context.Background()) if err != nil { panic(err) } defer resp.Body.Close() fmt.Println(resp.StatusCode) } ``` -------------------------------- ### Deploy Container Workflow Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/README.md Steps to deploy a container, create a reverse proxy route, and view logs. ```bash # 1. Pull image curl -X POST /cosmos/api/images/pull \ -d '{"image":"myimage:latest"}' # 2. Create container (via docker-compose or API) # 3. Create reverse proxy route curl -X POST /cosmos/api/routes \ -d '{ "name": "myapp", "target": "http://container-ip:8080", "host": "myapp.example.com", "useHost": true, "authEnabled": true }' # 4. View logs curl /cosmos/api/servapps/mycontainer/logs?tail=100 ``` -------------------------------- ### GET /api/events Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md List system events. ```APIDOC ## GET /api/events ### Description List system events. ### Method GET ### Endpoint /api/events ### Headers - Authorization: Bearer {token} - Permission: PERM_ADMIN_READ ### Parameters #### Query Parameters - **limit** (number) - Optional - Results limit - **offset** (number) - Optional - Pagination offset - **type** (string) - Optional - Filter by event type ### Response #### Success Response (200) - **status** (string) - "OK" - **data** (object[]) - Array of events ``` -------------------------------- ### GET /api/metrics Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieve system metrics. ```APIDOC ## GET /api/metrics ### Description Get system metrics. ### Method GET ### Endpoint /api/metrics ### Headers - Authorization: Bearer {token} - Permission: PERM_RESOURCES_READ ### Parameters #### Query Parameters - **metric** (string) - Optional - Specific metric name - **start** (number) - Optional - Start timestamp - **end** (number) - Optional - End timestamp ### Response #### Success Response (200) - **status** (string) - "OK" - **data** (object) - Metrics data ``` -------------------------------- ### Full Cosmos Server Configuration Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/configuration.md This JSON object represents a complete configuration for the Cosmos Server, illustrating all available settings and their typical values. It covers logging, security, network ports, domain names, SSL certificates, proxy routes, email server details, Docker settings, database credentials, constellation networking, storage, backup schedules, cron jobs, market sources, homepage widgets, theme colors, OpenID clients, API tokens, and user roles. ```json { "loggingLevel": "INFO", "newInstall": false, "disableUserManagement": false, "requireMfa": false, "autoUpdate": true, "betaUpdates": false, "monitoringDisabled": false, "disableHostModeWarning": false, "adminConstellationOnly": false, "disableOpenIDDirect": false, "mongodb": "mongodb://user:pass@localhost:27017/cosmos", "serverCountry": "US", "blockedCountries": [], "countryBlacklistIsWhitelist": false, "licence": "", "serverToken": "", "agentMode": false, "httpConfig": { "httpPort": "80", "httpsPort": "443", "hostname": "cosmos.example.com", "httpsCertificateMode": "LETSENCRYPT", "sslEmail": "admin@example.com", "useWildcardCertificate": false, "dnsChallengeProvider": "cloudflare", "dnsChallengeConfig": { "CLOUDFLARE_API_TOKEN": "your-token" }, "acceptAllInsecureHostname": false, "allowHTTPLocalIPAccess": true, "useForwardedFor": false, "allowSearchEngine": false, "publishMDNS": false, "trustedProxies": [], "tlsCert": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----", "tlsKey": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----", "authPrivateKey": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----", "authPublicKey": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----", "generateMissingAuthCert": true, "proxyConfig": { "routes": [ { "name": "home-assistant", "target": "http://192.168.1.10:8123", "host": "ha.example.com", "useHost": true, "authEnabled": true, "adminOnly": false, "mode": "PROXY", "timeout": 30000000000, "smartShield": { "enabled": true, "policy_strictness": 2 } } ] } }, "emailConfig": { "enabled": true, "host": "smtp.gmail.com", "port": "587", "username": "your-email@gmail.com", "password": "your-app-password", "from": "noreply@example.com", "useTLS": true, "allowInsecureTLS": false, "notifyLogin": true }, "dockerConfig": { "skipPruneNetwork": false, "skipPruneImages": false, "defaultDataPath": "/var/lib/docker/volumes" }, "database": { "puppetMode": true, "hostname": "cosmos-mongodb", "dbVolume": "/cosmos/data/db", "configVolume": "/cosmos/data/config", "version": "6.0", "username": "root", "password": "secure-password" }, "constellationConfig": { "enabled": false, "thisDeviceName": "node1", "constellationHostname": "vpn.example.com", "ipRange": "172.16.0.0/12", "dnsDisabled": false, "dnsPort": "53", "dnsFallback": "8.8.8.8", "dnsBlockBlacklist": true, "dnsAdditionalBlocklists": [], "doNotSyncNodes": false, "customDNSEntries": [] }, "storage": { "snapRAIDs": [] }, "backup": { "disable": false, "backups": { "daily": { "name": "daily", "repository": "s3://bucket-name/backups", "password": "restic-password", "source": "/var/lib/cosmos/backups", "crontab": "0 2 * * *", "crontabForget": "0 3 * * 0", "retentionPolicy": "keep-daily 7 --keep-weekly 4 --keep-monthly 12", "autoStopContainers": true } } }, "cron": { "cleanup": { "enabled": true, "name": "cleanup", "crontab": "0 3 * * *", "command": "rm -rf /var/lib/cosmos/temp/*", "container": "" } }, "marketConfig": { "sources": [ { "name": "Official", "url": "https://market.cosmos-cloud.io" } ] }, "homepageConfig": { "background": "https://example.com/background.jpg", "widgets": ["weather", "time", "status"], "expanded": false }, "themeConfig": { "primaryColor": "#1976d2", "secondaryColor": "#dc004e" }, "openIDClients": [ { "id": "client-id", "secret": "client-secret", "redirect": "https://example.com/callback" } ], "apiTokens": { "automation": { "name": "automation", "owner": "admin", "tokenHash": "sha256hash...", "tokenSuffix": "k3x7", "permissions": [20, 21], "ipWhitelist": ["192.168.1.0/24"], "restrictToConstellation": false, "createdAt": "2024-01-01T00:00:00Z", "expiresAt": "2025-01-01T00:00:00Z" } }, "roles": { "1": { "name": "User", "permissions": [100, 101] }, "2": { "name": "Admin", "permissions": [1, 2, 10, 11, 20, 21, 30, 31, 40, 100, 101] } } } ``` -------------------------------- ### GET /api/jobs Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md List currently running jobs. ```APIDOC ## GET /api/jobs ### Description List running jobs. ### Method GET ### Endpoint /api/jobs ### Headers - Authorization: Bearer {token} - Permission: PERM_RESOURCES_READ ### Response #### Success Response (200) - **status** (string) - "OK" - **data** (object[]) - Running jobs ``` -------------------------------- ### Get Backup Configurations Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/types.md Retrieves all backup job configurations. ```APIDOC ## GET /api/backups-config ### Description Retrieves all backup job configurations. ### Method GET ### Endpoint /api/backups-config ### Response #### Success Response (200) - **configs** (array of SingleBackupConfig) - List of backup configurations ``` -------------------------------- ### Get Devices Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/types.md Retrieves a list of all devices in the constellation cluster. ```APIDOC ## GET /api/constellation/devices ### Description Retrieves a list of all devices in the constellation cluster. ### Method GET ### Endpoint /api/constellation/devices ### Response #### Success Response (200) - **devices** (array of ConstellationDevice) - List of devices ``` -------------------------------- ### Initialize and Apply Terraform Configuration Source: https://github.com/azukaar/cosmos-server/blob/master/terraform-provider-cosmos/examples/install/index.md Initializes the Terraform working directory and applies the configuration to set up a Cosmos node. Ensure you have a reachable VM, SSH access, and optionally a DNS name for HTTPS. ```bash cd examples/install terraform init terraform apply \ -var 'vm_host=203.0.113.10' \ -var 'ssh_private_key_path=~/.ssh/id_ed25519' \ -var 'hostname=cosmos.example.com' \ -var 'admin_password=…' \ -var 'cosmos_licence=…' ``` -------------------------------- ### GET /api/backups/{name}/snapshots Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md List snapshots for a specific backup. ```APIDOC ## GET /api/backups/{name}/snapshots ### Description List backup snapshots. ### Method GET ### Endpoint /api/backups/{name}/snapshots ### Headers - Authorization: Bearer {token} - Permission: PERM_RESOURCES_READ ### Parameters #### Path Parameters - **name** (string) - Required - Backup name ### Response #### Success Response (200) - **status** (string) - "OK" - **data** (object[]) - Array of snapshots ``` -------------------------------- ### Build Server Source: https://github.com/azukaar/cosmos-server/blob/master/CONTRIBUTE.md Builds the Go-based server application. This command also copies the client build output into the server's build directory. ```bash npm run build ``` -------------------------------- ### Build and Run Docker Image for Development Source: https://github.com/azukaar/cosmos-server/blob/master/CONTRIBUTE.md Builds and immediately runs a Docker container using the non-production Dockerfile. ```bash npm run dockerdev ``` -------------------------------- ### Get Cron Jobs Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/types.md Retrieves all scheduled cron job configurations. ```APIDOC ## GET /api/cron ### Description Retrieves all scheduled cron job configurations. ### Method GET ### Endpoint /api/cron ### Response #### Success Response (200) - **configs** (array of CRONConfig) - List of cron job configurations ``` -------------------------------- ### Get DNS Entries Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/types.md Retrieves all DNS records in the constellation cluster. ```APIDOC ## GET /api/constellation/dns ### Description Retrieves all DNS records in the constellation cluster. ### Method GET ### Endpoint /api/constellation/dns ### Response #### Success Response (200) - **entries** (array of ConstellationDNSEntry) - List of DNS entries ``` -------------------------------- ### GET /api/config Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/configuration.md Retrieves the current configuration of the system. Requires authentication. ```APIDOC ## GET /api/config ### Description Retrieve current configuration. ### Method GET ### Endpoint /api/config ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **openIDClients** (object array) - OAuth2 client configurations - **apiTokens** (object) - Named API token configurations #### Response Example { "openIDClients": [ { "id": "string", "secret": "string", "redirect": "string" } ], "apiTokens": { "[name]": { "name": "string", "owner": "string", "tokenHash": "string", "tokenSuffix": "string", "permissions": ["number array"], "ipWhitelist": ["string array"], "restrictToConstellation": "boolean", "expiresAt": "string" } } } ``` -------------------------------- ### Filtering Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/README.md Search endpoints support filtering using a 'filter' parameter. ```http GET /api/resource?filter=searchterm ``` -------------------------------- ### ListMountsRoute Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/storage-backup.md Lists all mount points and their usage details, including mount point path, device, filesystem type, options, total size, used size, available size, and percentage used. ```APIDOC ## GET /cosmos/api/mounts ### Description List all mount points and their usage. ### Method GET ### Endpoint /cosmos/api/mounts ### Headers Required - Authorization: Bearer {token} - Permission: PERM_RESOURCES_READ ### Response #### Success Response (200) - **data** (array) - Array of mount point objects, each containing mountPoint, device, fsType, options, totalSize, usedSize, availableSize, and usePercent. #### Response Example ```json { "status": "OK", "data": [ { "mountPoint": "/", "device": "/dev/sda1", "fsType": "ext4", "options": "rw,relatime,errors=remount-ro", "totalSize": 1099511627776, "usedSize": 549755813888, "availableSize": 549755813888, "usePercent": 50.0 } ] } ``` ``` -------------------------------- ### GET /api/api-tokens Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Lists all API tokens for the system. This operation is restricted to administrators. ```APIDOC ## GET /api/api-tokens ### Description List API tokens (admin). ### Method GET ### Endpoint /api/api-tokens ### Parameters #### Headers required - Authorization: Bearer {token} - Permission: PERM_CONFIGURATION_READ ### Response #### Success Response (200) - **status** (string) - "OK" - **data** (APITokenConfig[]) - API token configurations ``` -------------------------------- ### Get Cosmos Server Status Source: https://github.com/azukaar/cosmos-server/blob/master/sdk/README.md Fetch the current status of the Cosmos server. ```javascript // Get server status const status = await cosmos.getStatus(); ``` -------------------------------- ### Deploy New Container Workflow Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/docker-containers.md A multi-step workflow for deploying a new container, including pulling the image, creating the service, and checking its status and logs. ```bash # 1. Pull image curl -X POST https://cosmos.example.com/cosmos/api/images/pull \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"image":"ghcr.io/home-assistant/home-assistant:latest"}' # 2. Create service (via docker-compose or API) # # 3. Check container status curl https://cosmos.example.com/cosmos/api/servapps/home-assistant \ -H "Authorization: Bearer $TOKEN" # 4. View logs curl "https://cosmos.example.com/cosmos/api/servapps/home-assistant/logs?tail=50" \ -H "Authorization: Bearer $TOKEN" ``` -------------------------------- ### Get Container Details Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves detailed information about a specific container using its ID. ```APIDOC ## GET /api/servapps/{containerId} ### Description Get container details. ### Method GET ### Endpoint /api/servapps/{containerId} ### Parameters #### Path Parameters - **containerId** (string) - Required - Container ID or name ### Headers Required - Authorization: Bearer {token} - Permission: PERM_RESOURCES_READ ### Response #### Success Response (200) - **status** (string) - "OK" - **data** (Container) - Container object with full details ``` -------------------------------- ### Manage Backups and Jobs Source: https://github.com/azukaar/cosmos-server/blob/master/sdk/examples/index.md List backup repositories and snapshots, trigger backups, and manage scheduled jobs using the provided script. ```bash node sdk/examples/backup-and-jobs.mjs ``` -------------------------------- ### Get Server Status Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/README.md Retrieves the current status of the Cosmos Server, including its version. ```APIDOC ## GET /cosmos/api/status ### Description Retrieves the current status and version information of the Cosmos Server. ### Method GET ### Endpoint /cosmos/api/status ``` -------------------------------- ### User Registration Request Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/authentication.md Create a new user account using a nickname, email, password, and an invitation key. Ensure the password meets the specified requirements. ```json { "nickname": "newuser", "email": "newuser@example.com", "password": "SecurePassword123!@", "registerKey": "inv_xyz789abc" } ``` -------------------------------- ### Initialize and Apply Terraform Configuration Source: https://github.com/azukaar/cosmos-server/blob/master/terraform-provider-cosmos/examples/digitalocean-3node/index.md This snippet shows the commands to initialize Terraform and apply the configuration for the 3-node DigitalOcean cluster. It includes placeholders for sensitive variables like API tokens and passwords. ```bash cd examples/digitalocean-3node terraform init terraform apply \ -var 'do_token=…' \ -var 'ssh_key_fingerprint=aa:bb:cc:…' \ -var 'ssh_private_key_path=~/.ssh/id_ed25519' \ -var 'node_hostnames=["cosmos-0.example.com","cosmos-1.example.com","cosmos-2.example.com"]' \ -var 'admin_password=…' \ -var 'cosmos_licence=…' ``` -------------------------------- ### POST /api/backups Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Create a new backup configuration. ```APIDOC ## POST /api/backups ### Description Create backup configuration. ### Method POST ### Endpoint /api/backups ### Headers - Authorization: Bearer {token} - Permission: PERM_RESOURCES ### Request Body #### Path Parameters - **name** (string) - Required - Backup name - **repository** (string) - Required - Restic repository URL - **source** (string) - Required - Source path to backup - **crontab** (string) - Required - Cron schedule - **password** (string) - Required - Repository password ### Response #### Success Response (200) - **status** (string) - "OK" - **data** (SingleBackupConfig) - Created backup config ``` -------------------------------- ### Get Current User Information Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/README.md Retrieves information about the currently authenticated user using their token. ```APIDOC ## GET /cosmos/api/me ### Description Retrieves information about the currently authenticated user. ### Method GET ### Endpoint /cosmos/api/me ### Parameters #### Request Headers - **Authorization** (string) - Required - Bearer token for authentication (e.g., `Bearer YOUR_TOKEN`). ``` -------------------------------- ### List and Create API Tokens Source: https://github.com/azukaar/cosmos-server/blob/master/sdk/README.md Retrieve a list of existing API tokens and create a new token, optionally with read-only permissions. ```javascript // API tokens const tokens = await cosmos.apiTokens.list(); const newToken = await cosmos.apiTokens.create({ name: 'my-automation', readOnly: true, }); ``` -------------------------------- ### Create New Directory Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/storage-backup.md Creates a new directory at the specified path. Ensure the path is valid and does not already exist. ```json { "path": "/home/user/new_folder" } ```