### 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 ``` -------------------------------- ### POST /cosmos/api/setup Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Perform initial server setup. ```APIDOC ## POST /cosmos/api/setup ### Description Initial setup. ### Method POST ### Endpoint /cosmos/api/setup ``` -------------------------------- ### Install Cosmos Cloud SDK Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/index.md Use npm to install the required SDK package. ```bash npm install cosmos-cloud-sdk ``` -------------------------------- ### 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 ``` -------------------------------- ### Initialize Cosmos Setup Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/configuration.md JSON payload required for the initial setup endpoint to configure database, SSL, and admin credentials. ```json { "mongodbMode": "single|replica|docker", "mongodb": "mongodb://connection-string", "hostname": "cosmos.example.com", "httpsCertificateMode": "letsencrypt|manual|self-signed", "sslEmail": "admin@example.com", "useWildcardCertificate": false, "dnsChallengeProvider": "cloudflare", "DNSChallengeConfig": { "CLOUDFLARE_DNS_API_TOKEN": "token" }, "tlsCert": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----", "tlsKey": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----", "allowHTTPLocalIPAccess": true, "nickname": "admin", "password": "admin_password", "email": "admin@example.com", "clearConfig": false, "constellationConfig": "", "createAdminToken": true } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 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 } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 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" } ``` -------------------------------- ### Configure server setup Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/additional-apis.md Performs initial server configuration; intended for first-run scenarios. ```typescript cosmos.setup(request: SetupRequest): Promise ``` ```typescript interface SetupRequest { mongodbMode: string; mongodb?: string; hostname: string; httpsCertificateMode: string; sslEmail?: string; useWildcardCertificate?: boolean; dnsChallengeProvider?: string; DNSChallengeConfig?: Record; tlsCert?: string; tlsKey?: string; allowHTTPLocalIPAccess?: boolean; nickname: string; password: string; email?: string; clearConfig?: boolean; constellationConfig?: string; createAdminToken?: boolean; } ``` ```typescript await cosmos.setup({ mongodbMode: 'single', hostname: 'cosmos.example.com', httpsCertificateMode: 'letsencrypt', sslEmail: 'admin@example.com', dnsChallengeProvider: 'cloudflare', DNSChallengeConfig: { 'CLOUDFLARE_DNS_API_TOKEN': 'token...' }, nickname: 'admin', password: 'admin_password', email: 'admin@example.com', createAdminToken: true }); console.log('Server initialized'); ``` -------------------------------- ### GET /cosmos/api/mfa Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Generates credentials for 2FA setup. ```APIDOC ## GET /cosmos/api/mfa ### Description Generate 2FA setup credentials. ### Method GET ### Endpoint /cosmos/api/mfa ``` -------------------------------- ### Sudo Implementation Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/authentication.md Demonstrates escalating to admin privileges by re-authenticating with a password. ```typescript try { await cosmos.auth.sudo({ password: 'mypassword' }); console.log('Admin mode activated'); // Now perform admin operations } catch (error) { console.error('Sudo failed:', error.message); } ``` -------------------------------- ### 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 ``` -------------------------------- ### Login Implementation Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/authentication.md Demonstrates authenticating a user and handling potential errors. ```typescript const cosmos = createClient({ baseUrl, token }); try { const response = await cosmos.auth.login({ username: 'alice', password: 'secret123' }); console.log('Login successful:', response.status); } catch (error) { console.error('Login failed:', error.message); } ``` -------------------------------- ### SetupRequest Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/types.md The SetupRequest interface defines the parameters required for the initial server setup, invoked via the createClient().setup() method. ```APIDOC ## SetupRequest ### Description Parameters for initial server setup. Used by: `createClient().setup()` ### Parameters - **mongodbMode** (string) - MongoDB deployment mode - **mongodb** (string) - MongoDB connection string - **hostname** (string) - Server hostname - **httpsCertificateMode** (string) - Certificate mode (letsencrypt, manual, self-signed) - **sslEmail** (string) - Email for Let's Encrypt notifications - **useWildcardCertificate** (boolean) - Use wildcard certificate - **dnsChallengeProvider** (string) - DNS provider for ACME challenge - **DNSChallengeConfig** (object) - DNS provider credentials - **tlsCert** (string) - Manual TLS certificate (PEM) - **tlsKey** (string) - Manual TLS key (PEM) - **allowHTTPLocalIPAccess** (boolean) - Allow HTTP on local IPs - **nickname** (string) - Admin user nickname - **password** (string) - Admin user password - **email** (string) - Admin user email - **clearConfig** (boolean) - Reset existing configuration - **constellationConfig** (string) - Initial Constellation config - **createAdminToken** (boolean) - Generate admin API token ``` -------------------------------- ### 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 ``` -------------------------------- ### Typical storage usage patterns Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/storage.md Demonstrates common administrative workflows including disk listing, mounting, RAID setup, and SnapRAID configuration. ```typescript // List all disks const disks = await cosmos.storage.disks.list(); console.log(`${disks.data.length} disks available`); // Mount a new disk await cosmos.storage.mounts.mount({ path: '/dev/sdb1', mountPoint: '/mnt/storage', permanent: true }); // Create RAID for redundancy await cosmos.storage.raid.create({ name: 'data-raid', level: '5', devices: ['/dev/sdc', '/dev/sdd', '/dev/sde'] }); // Setup parity protection with SnapRAID await cosmos.storage.snapRAID.create({ Name: 'data-protect', Enabled: true, Data: { d1: '/mnt/disk1', d2: '/mnt/disk2' }, Parity: ['/mnt/parity'], SyncCrontab: '0 3 * * *' // Daily 3am sync }); // Sync parity await cosmos.storage.snapRAID.sync('data-protect'); // Create directory await cosmos.storage.newFolder('disk1', '/mnt/storage', 'apps'); // List contents const files = await cosmos.storage.listDir('disk1', '/mnt/storage'); ``` -------------------------------- ### Self-Registration Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Registers a user during the initial setup phase. ```json { "nickname": "string", "password": "string", "registerKey": "string" } ``` -------------------------------- ### List Repository Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/backups.md Retrieves and iterates through the list of backup repositories. ```typescript const response = await cosmos.backups.listRepo(); const repos = response.data; repos.forEach(repo => { console.log(`${repo.name}: ${repo.location}`); }); ``` -------------------------------- ### Create User Usage Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/users.md Creates a new user with a nickname, email, password, and role. ```typescript const response = await cosmos.users.create({ Nickname: 'bob', Email: 'bob@example.com', password: 'secure_password_123', Role: 1 // Regular user }); console.log(`User created: ${response.data}`); ``` -------------------------------- ### Define SetupRequest interface Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/types.md Interface defining the parameters required for initial server setup via the createClient().setup() method. ```typescript interface SetupRequest { mongodbMode: string; mongodb?: string; hostname: string; httpsCertificateMode: string; sslEmail?: string; useWildcardCertificate?: boolean; dnsChallengeProvider?: string; DNSChallengeConfig?: Record; tlsCert?: string; tlsKey?: string; allowHTTPLocalIPAccess?: boolean; nickname: string; password: string; email?: string; clearConfig?: boolean; constellationConfig?: string; createAdminToken?: boolean; } ``` -------------------------------- ### POST /cosmos/api/register Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Performs self-registration during initial setup. ```APIDOC ## POST /cosmos/api/register ### Description Self-registration during setup. ### Method POST ### Endpoint /cosmos/api/register ### Request Body - **nickname** (string) - Required - **password** (string) - Required - **registerKey** (string) - Required ``` -------------------------------- ### Restore Backup Examples Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/backups.md Demonstrates full and selective restoration of data from a snapshot. ```typescript // Full restore await cosmos.backups.restoreBackup('app-data', { snapshotId: 'abc123def', target: '/data/app-restored' }); // Selective restore await cosmos.backups.restoreBackup('app-data', { snapshotId: 'abc123def', target: '/data/app-restored', include: ['/config', '/database'] }); console.log('Restore completed'); ``` -------------------------------- ### GET /cosmos/api/restart Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Restart the server. ```APIDOC ## GET /cosmos/api/restart ### Description Restart server. ### Method GET ### Endpoint /cosmos/api/restart ``` -------------------------------- ### 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 '…' ``` -------------------------------- ### 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 } ``` -------------------------------- ### get() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/config.md Retrieves the complete server configuration object, including routes, DNS settings, and SSL configuration. ```APIDOC ## get() ### Description Retrieves the full configuration object for the Cosmos server. ### Signature `get(): Promise` ### Returns - **Promise** - The full configuration object. ### Example ```typescript const response = await cosmos.config.get(); const config = response.data; ``` ``` -------------------------------- ### Me Implementation Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/authentication.md Demonstrates retrieving the current user's profile and checking MFA status. ```typescript const user = await cosmos.auth.me(); console.log(`Logged in as ${user.Nickname} (${user.Email})`); if (user.MFAState === 1) { console.log('2FA is enabled'); } ``` -------------------------------- ### Logout Implementation Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/authentication.md Demonstrates ending the current authentication session. ```typescript await cosmos.auth.logout(); console.log('Logged out'); ``` -------------------------------- ### Typical Cosmos Server API Usage Patterns Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/additional-apis.md Demonstrates common administrative tasks including status retrieval, API token creation, marketplace listing, OpenID configuration, and RClone storage setup. ```typescript // Check server status const status = await cosmos.getStatus(); console.log(`Server v${status.data.Version}`); // Setup API token for automation const token = await cosmos.apiTokens.create({ name: 'backup-bot', description: 'Automated backup triggers', readOnly: true, expiryDays: 90 }); console.log(`Token: ${token.data.token}`); // Browse marketplace const market = await cosmos.market.list(); market.data.Showcase.forEach(app => { console.log(`Featured: ${app.Name}`); }); // Configure OpenID for SSO await cosmos.openid.create({ id: 'internal-app', secret: 'secret123', redirect: 'https://app.internal/auth/callback' }); // Setup cloud storage await cosmos.rclone.create({ name: 'backup-s3', type: 's3', access_key_id: 'AKIA...', secret_access_key: 'wJalr...' }); // Test connectivity const storage = await cosmos.rclone.pingStorage('backup-s3'); console.log(`S3 available: ${storage.Available} bytes`); ``` -------------------------------- ### Unlock Repository Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/backups.md Unlocks a specified backup repository. ```typescript await cosmos.backups.unlockRepository('app-data'); console.log('Repository unlocked'); ``` -------------------------------- ### 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) } ``` -------------------------------- ### new2FA(nickname: string) Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/users.md Generates 2FA setup credentials including a QR code and secret. ```APIDOC ## new2FA(nickname: string) ### Description Generate 2FA setup credentials (QR code). ### Parameters - **nickname** (string) - Required - User to enable 2FA for ### Return Type Promise ### Example ```typescript const response = await cosmos.users.new2FA('alice'); // response.data contains QR code URI ``` ``` -------------------------------- ### cosmos.setup() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/additional-apis.md Performs initial server configuration (first-run only). ```APIDOC ## cosmos.setup() ### Description Initial server configuration (first-run only). ### Signature `cosmos.setup(request: SetupRequest): Promise` ### Parameters - **request** (SetupRequest) - Required - Configuration object containing mongodbMode, hostname, nickname, password, etc. ### Example ```typescript await cosmos.setup({ mongodbMode: 'single', hostname: 'cosmos.example.com', nickname: 'admin', password: 'admin_password' }); ``` ``` -------------------------------- ### 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 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' }); ``` -------------------------------- ### Repository Stats Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/backups.md Retrieves and displays storage usage and snapshot count for a repository. ```typescript const response = await cosmos.backups.repoStats('app-data'); const stats = response.data; console.log(`Total size: ${stats.TotalSize} bytes`); console.log(`Snapshots: ${stats.SnapshotCount}`); console.log(`Files: ${stats.FileCount}`); ``` -------------------------------- ### Create SnapRAID Configuration Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/storage.md Defines the method signature and configuration interface for initializing a new SnapRAID setup. ```typescript snapRAID.create(args: Partial): Promise ``` ```typescript interface SnapRAIDConfig { Name: string; Enabled: boolean; Data: Record; // disk1 -> /path mapping Parity: string[]; // Parity disk paths SyncCrontab: string; // Sync schedule ScrubCrontab: string; // Scrub schedule CheckOnFix: boolean; } ``` ```typescript await cosmos.storage.snapRAID.create({ Name: 'home-backup', Enabled: true, Data: { d1: '/mnt/disk1', d2: '/mnt/disk2', d3: '/mnt/disk3' }, Parity: ['/mnt/parity'], SyncCrontab: '0 0 * * *', // Daily at midnight ScrubCrontab: '0 2 * * 0', // Weekly Sunday 2am CheckOnFix: true }); ``` -------------------------------- ### Manage container lifecycle with TypeScript Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/docker.md Defines the signature for container lifecycle operations and provides examples for common actions like start, stop, and remove. ```typescript manageContainer(containerId: string, action: string): Promise ``` ```typescript // Stop a container await cosmos.docker.manageContainer('my-app', 'stop'); // Start it again await cosmos.docker.manageContainer('my-app', 'start'); // Restart await cosmos.docker.manageContainer('my-app', 'restart'); // Pause execution (but keep in memory) await cosmos.docker.manageContainer('my-app', 'pause'); await cosmos.docker.manageContainer('my-app', 'unpause'); // Delete container await cosmos.docker.manageContainer('my-app', 'remove'); ``` -------------------------------- ### Initialize Cosmos Client and List Containers Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/README.md Create a client instance with a base URL and token, then use the docker service to list containers. ```typescript import { createClient } from 'cosmos-cloud-sdk'; const cosmos = createClient({ baseUrl: 'https://my-cosmos.example.com', token: 'cosmos_abc123...', }); // Example: List containers const containers = await cosmos.docker.list(); containers.data.forEach(c => console.log(c.Name)); ``` -------------------------------- ### 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 ``` -------------------------------- ### Create a Docker Service Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/docker.md Defines the signature for creating a service and provides an example of deploying an Nginx container. ```typescript createService( serviceData: any, onProgress: (line: string) => void ): Promise ``` ```typescript await cosmos.docker.createService({ Image: 'nginx:latest', Name: 'web-server', Ports: [{ PublishedPort: 80, TargetPort: 80 }] }, (line) => { console.log('Create:', line); }); ``` -------------------------------- ### 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); ``` -------------------------------- ### Get server status and version Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/additional-apis.md Retrieves current server status and version information. ```typescript cosmos.getStatus(): Promise ``` ```typescript const status = await cosmos.getStatus(); console.log(`Version: ${status.data.Version}`); console.log(`Uptime: ${status.data.Uptime}`); console.log(`Status: ${status.data.Status}`); ``` -------------------------------- ### 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 ``` -------------------------------- ### List Users Usage Example Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/users.md Retrieves all users and iterates through the returned list to log user details. ```typescript const response = await cosmos.users.list(); const users = response.data; users.forEach(user => { console.log(`${user.Nickname} (${user.Email}) - Role: ${user.Role}`); }); ``` -------------------------------- ### GET /cosmos/api/dns Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Perform a DNS lookup. ```APIDOC ## GET /cosmos/api/dns ### Description DNS lookup. ### Method GET ### Endpoint /cosmos/api/dns ``` -------------------------------- ### Retrieve system metrics with get() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/metrics-alerts.md Fetches specific system metrics by providing an array of metric names. ```typescript get(metarr: string[]): Promise ``` ```typescript const response = await cosmos.metrics.get([ 'cpu.usage', 'memory.usage', 'disk.io', 'network.bytes_sent' ]); console.log('CPU:', response.data.cpu_usage); console.log('Memory:', response.data.memory_usage); ``` -------------------------------- ### GET /cosmos/api/servapps Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves a list of all containers. ```APIDOC ## GET /cosmos/api/servapps ### Description List all containers. ### Method GET ### Endpoint /cosmos/api/servapps ### Response #### Success Response (200) - **status** (string) - Status message - **data** (array) - List of container objects ``` -------------------------------- ### GET /cosmos/api/users Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Lists all users in the system. ```APIDOC ## GET /cosmos/api/users ### Description List all users. ### Method GET ### Endpoint /cosmos/api/users ``` -------------------------------- ### 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 ``` -------------------------------- ### create() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/constellation.md Initializes the constellation service. ```APIDOC ## create(nickname, isLighthouse, hostname, network, peers) ### Description Initializes the constellation service on first setup. ### Parameters - **nickname** (string) - The name of the constellation node. - **isLighthouse** (boolean) - Whether this node acts as a main lighthouse. - **hostname** (string) - The public hostname for the node. - **network** (string) - The network CIDR range. - **peers** (number) - The number of peers. ``` -------------------------------- ### GET /cosmos/api/dns-check Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Check host DNS configuration. ```APIDOC ## GET /cosmos/api/dns-check ### Description Check host DNS. ### Method GET ### Endpoint /cosmos/api/dns-check ``` -------------------------------- ### GET /cosmos/api/status Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieve the current status of the server. ```APIDOC ## GET /cosmos/api/status ### Description Get server status. ### Method GET ### Endpoint /cosmos/api/status ``` -------------------------------- ### Initialize and Use Cosmos Client Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/index.md Initialize the client with a base URL and token, then access namespaced modules like docker, users, and system status. ```typescript 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(); // List users const users = await cosmos.users.list(); // Get server status const status = await cosmos.getStatus(); ``` -------------------------------- ### GET /cosmos/api/notifications/read Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Marks specific notifications as read. ```APIDOC ## GET /cosmos/api/notifications/read ### Description Mark notifications as read. ### Method GET ### Endpoint /cosmos/api/notifications/read ### Parameters #### Query Parameters - **ids** (string) - Required - Comma-separated notification IDs ``` -------------------------------- ### Typical Backup Workflow Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/backups.md Demonstrates the full lifecycle of a backup job including creation, execution, inspection, restoration, and maintenance. ```typescript // Create backup job await cosmos.backups.addBackup({ name: 'production-db', source: '/var/lib/postgresql', repository: '/mnt/backup/postgres', password: 'secure-key-123', crontab: '0 1 * * *', // Daily 1am autoStopContainers: true }); // Trigger backup now await cosmos.backups.backupNow('production-db'); // List snapshots const snapshots = await cosmos.backups.listSnapshots('production-db'); console.log(`${snapshots.data.length} snapshots`); // Browse a snapshot const files = await cosmos.backups.listFolders( 'production-db', snapshots.data[0].ID, '/databases' ); // Restore if needed await cosmos.backups.restoreBackup('production-db', { snapshotId: snapshots.data[0].ID, target: '/restore/production-db', include: ['/databases/important'] }); // Check repository stats const stats = await cosmos.backups.repoStats('production-db'); console.log(`Using ${stats.data.TotalSize} bytes`); // Update backup config await cosmos.backups.editBackup({ name: 'production-db', source: '/var/lib/postgresql', repository: '/mnt/backup/postgres', password: 'secure-key-123', crontab: '0 2 * * *' // Change to 2am }); // Cleanup old snapshot await cosmos.backups.forgetSnapshot( 'production-db', 'very-old-snapshot-id', true // Reclaim space ); ``` -------------------------------- ### GET /cosmos/api/notifications Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves notifications for the current user. ```APIDOC ## GET /cosmos/api/notifications ### Description Get user notifications. ### Method GET ### Endpoint /cosmos/api/notifications ``` -------------------------------- ### GET /cosmos/api/logout Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Ends the current user session. ```APIDOC ## GET /cosmos/api/logout ### Description End user session. ### Method GET ### Endpoint /cosmos/api/logout ``` -------------------------------- ### GET /cosmos/api/disks Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves a list of available disks on the system. ```APIDOC ## GET /cosmos/api/disks ### Description List all disks connected to the system. ### Method GET ### Endpoint /cosmos/api/disks ``` -------------------------------- ### GET /cosmos/api/servapps/:containerId/logs Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves logs for a specific container. ```APIDOC ## GET /cosmos/api/servapps/:containerId/logs ### Description Get container logs. ### Method GET ### Endpoint /cosmos/api/servapps/:containerId/logs ### Parameters #### Query Parameters - **search** (string) - Optional - Text filter - **limit** (integer) - Optional - Number of lines - **lastReceivedLogs** (string) - Optional - Pagination - **errorOnly** (boolean) - Optional - Filter errors only ``` -------------------------------- ### Manage Cosmos Server Configuration Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/config.md Demonstrates common configuration tasks including retrieving settings, managing routes, updating DNS, and restarting the server. ```typescript // Get current config const config = await cosmos.config.get(); // List routes const routes = await cosmos.config.listRoutes(); console.log(`${routes.data.length} routes configured`); // Get specific route const route = await cosmos.config.getRoute('my-service'); console.log(`Route target: ${route.data.Target}`); // Create new route await cosmos.config.createNewRoute({ Name: 'new-service', // ... route configuration }); // Update DNS await cosmos.config.updateDNS({ dnsPort: '53', dnsBlockBlacklist: true, customDNSEntries: [ { Type: 'A', Key: 'local', Value: '192.168.1.1' } ] }); // Delete route await cosmos.config.deleteRouteByName('old-service'); // Restart server await cosmos.config.restart(); ``` -------------------------------- ### GET /cosmos/api/me Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves information about the currently authenticated user. ```APIDOC ## GET /cosmos/api/me ### Description Get current authenticated user info. ### Method GET ### Endpoint /cosmos/api/me ``` -------------------------------- ### snapRAID.list() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/storage.md Lists all existing SnapRAID configurations. ```APIDOC ## snapRAID.list(): Promise> ### Description Retrieves a list of all configured SnapRAID instances. ``` -------------------------------- ### get() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/users.md Retrieves complete information for a specific user by their nickname. ```APIDOC ## get(nickname: string) ### Description Get a specific user by nickname. ### Parameters - **nickname** (string) - Required - User's unique identifier ### Return Type Promise> ### Throws - CosmosError (status: 404) if user not found ### Example const response = await cosmos.users.get('alice'); const user = response.data; ``` -------------------------------- ### create() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/users.md Creates a new user account on the server. ```APIDOC ## create() ### Description Create a new user account. ### Signature `create(values: Partial & { password?: string }): Promise` ### Parameters - **values.Nickname** (string) - Required - Unique username - **values.Email** (string) - Optional - User's email - **values.password** (string) - Required - Initial password - **values.Role** (number) - Optional - Role (0=admin, 1=user, default 1) ### Return Type `Promise` - Returns confirmation of user creation. ### Throws - `CosmosError` with `status: 409` if username already exists - `CosmosError` with `status: 400` if validation fails - `CosmosError` with `status: 403` if not authorized ### Example ```typescript const response = await cosmos.users.create({ Nickname: 'bob', Email: 'bob@example.com', password: 'secure_password_123', Role: 1 // Regular user }); console.log(`User created: ${response.data}`); ``` ``` -------------------------------- ### GET /cosmos/api/metrics Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves system metrics based on provided filters. ```APIDOC ## GET /cosmos/api/metrics ### Description Get metrics. ### Method GET ### Endpoint /cosmos/api/metrics ### Parameters #### Query Parameters - **metrics** (string) - Optional - Comma-separated metric names ``` -------------------------------- ### GET /cosmos/api/storage/raid Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Lists all RAID arrays currently configured on the system. ```APIDOC ## GET /cosmos/api/storage/raid ### Description List RAID arrays. ### Method GET ### Endpoint /cosmos/api/storage/raid ``` -------------------------------- ### snapRAID.create() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/storage.md Creates a new SnapRAID configuration. ```APIDOC ## snapRAID.create(args: Partial): Promise ### Description Creates a new SnapRAID configuration with the provided settings. ### Parameters - **args** (Partial) - Required - Configuration object containing Name, Enabled status, Data mappings, Parity paths, and schedule crontabs. ``` -------------------------------- ### GET /cosmos/api/servapps/:containerId/manage/:action Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Performs management actions on a container. ```APIDOC ## GET /cosmos/api/servapps/:containerId/manage/:action ### Description Manage container (start, stop, restart, etc.). ### Method GET ### Endpoint /cosmos/api/servapps/:containerId/manage/:action ### Parameters #### Path Parameters - **containerId** (string) - Required - Container name or ID - **action** (string) - Required - Operation: start, stop, restart, pause, unpause, remove ``` -------------------------------- ### 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 /cosmos/api/servapps/:containerName Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves detailed information for a specific container. ```APIDOC ## GET /cosmos/api/servapps/:containerName ### Description Get container details. ### Method GET ### Endpoint /cosmos/api/servapps/:containerName ### Parameters #### Path Parameters - **containerName** (string) - Required - The name of the container ``` -------------------------------- ### GET /cosmos/api/users/:nickname Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves details for a specific user by their nickname. ```APIDOC ## GET /cosmos/api/users/:nickname ### Description Get specific user. ### Method GET ### Endpoint /cosmos/api/users/:nickname ### Parameters #### Path Parameters - **nickname** (string) - Required - User's unique identifier ``` -------------------------------- ### Get Specific User Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves details for a specific user by nickname. ```json { "status": "OK", "data": { /* User object */ } } ``` -------------------------------- ### Perform typical Constellation operations Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/constellation.md Demonstrates the full lifecycle of initializing a mesh, managing devices, configuring DNS, and monitoring connectivity. ```typescript // Initialize constellation on first setup await cosmos.constellation.create( 'headquarters', true, // Main lighthouse 'vpn.example.com', '10.100.0.0/8', 3 ); // Get current state const devices = await cosmos.constellation.list(); console.log(`${devices.data.length} devices in mesh`); // Add another device await cosmos.constellation.addDevice({ Nickname: 'remote-site', PublicHostname: 'remote.example.com' }); // Setup custom DNS await cosmos.constellation.createDNSEntry({ Type: 'A', Key: 'hq.vpn', Value: '10.100.0.1' }); await cosmos.constellation.createDNSEntry({ Type: 'A', Key: 'remote.vpn', Value: '10.100.0.2' }); // Test connectivity const ping = await cosmos.constellation.pingDevice('remote-site'); console.log(`Latency: ${ping.data.latency}ms`); // View tunnels const tunnels = await cosmos.constellation.tunnels(); tunnels.data.forEach(t => { console.log(`Tunnel: ${t.From} -> ${t.To}`); }); // Monitor logs const logs = await cosmos.constellation.getLogs(); console.log('Recent activity:', logs.data.slice(0, 5)); ``` -------------------------------- ### Get Current User Info Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Retrieves details for the authenticated user. ```json { "Nickname": "string", "Email": "string", "Role": 0, "MFAState": 0 } ``` -------------------------------- ### Create User Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Registers a new user in the system. ```json { "Nickname": "string", "Email": "string", "password": "string", "Role": 1 } ``` ```json { "status": "OK", "message": "User created" } ``` -------------------------------- ### get() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/docker.md Retrieves detailed information for a specific container identified by its name. ```APIDOC ## get() ### Description Get details for a specific container. ### Method SDK Method ### Signature get(containerName: string): Promise> ### Parameters - **containerName** (string) - Required - Container name (without leading /) ### Return Type Promise> ### Throws - CosmosError with status: 404 if container not found ### Example ```typescript const response = await cosmos.docker.get('my-app'); const container = response.data; console.log(`Image: ${container.Image}`); console.log(`Running: ${container.State.Running}`); console.log(`Started: ${container.State.StartedAt}`); ``` ``` -------------------------------- ### 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 ``` -------------------------------- ### Trigger Immediate Pruning Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/backups.md Starts the immediate pruning process for a backup job. ```typescript forgetNow(name: string): Promise ``` ```typescript await cosmos.backups.forgetNow('app-data'); console.log('Forget/prune started'); ``` -------------------------------- ### create() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/constellation.md Initializes a new constellation mesh with the specified configuration parameters. ```APIDOC ## create() ### Description Initialize a new constellation mesh. ### Signature `create(deviceName: string, isLighthouse: boolean, hostname: string, ipRange: string, natsReplicas: number): Promise` ### Parameters - **deviceName** (string) - Required - Name for this device - **isLighthouse** (boolean) - Required - Act as lighthouse (relay) - **hostname** (string) - Required - Public hostname or IP - **ipRange** (string) - Required - VPN subnet (e.g., 10.0.0.0/8) - **natsReplicas** (number) - Required - NAT traversal replicas ### Example ```typescript await cosmos.constellation.create( 'main-server', true, 'vpn.example.com', '10.0.0.0/8', 3 ); console.log('Constellation mesh created'); ``` ``` -------------------------------- ### GET /cosmos/api/events Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Queries system events and logs with filtering and pagination support. ```APIDOC ## GET /cosmos/api/events ### Description Query events/logs. ### Method GET ### Endpoint /cosmos/api/events ### Parameters #### Query Parameters - **from** (string) - Optional - ISO 8601 timestamp - **to** (string) - Optional - ISO 8601 timestamp - **search** (string) - Optional - Text filter - **query** (string) - Optional - Advanced query - **page** (integer) - Optional - Pagination - **logLevel** (string) - Optional - Filter by level ``` -------------------------------- ### GET /cosmos/api/backups/:name/snapshots Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/endpoints.md Lists all snapshots associated with a specific backup job. ```APIDOC ## GET /cosmos/api/backups/:name/snapshots ### Description List snapshots for a backup job. ### Method GET ### Endpoint /cosmos/api/backups/:name/snapshots ### Parameters #### Path Parameters - **name** (string) - Required - The name of the backup job. ``` -------------------------------- ### Typical user management operations Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/users.md Demonstrates common workflows including user creation, listing, updating, 2FA configuration, and password resets. ```typescript // Create a new user await cosmos.users.create({ Nickname: 'newuser', Email: 'user@example.com', password: 'initial_password', Role: 1 // Regular user }); // List all users const response = await cosmos.users.list(); console.log(`Total users: ${response.data.length}`); // Get specific user const user = await cosmos.users.get('newuser'); console.log(`User created: ${user.data.CreatedAt}`); // Update user await cosmos.users.edit('newuser', { Email: 'updated@example.com' }); // Setup 2FA const twofa = await cosmos.users.new2FA('newuser'); console.log('Setup code:', twofa.data.secret); // Enable 2FA await cosmos.users.check2FA('123456'); // Reset password await cosmos.users.resetPassword({ nickname: 'newuser', password: 'new_password_xyz' }); ``` -------------------------------- ### cosmos.market.list() Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/additional-apis.md Lists available applications in the marketplace. ```APIDOC ## cosmos.market.list() ### Description Retrieves a list of applications currently featured in the marketplace. ### Returns - **data.Showcase** (array) - List of featured applications. ``` -------------------------------- ### Get OpenID client Source: https://github.com/azukaar/cosmos-server/blob/master/_autodocs/api-reference/additional-apis.md Retrieves details for a specific OpenID client by its ID. ```typescript cosmos.openid.get(id: string): Promise> ``` ```typescript const response = await cosmos.openid.get('my-app'); const client = response.data; console.log(`ID: ${client.id}`); console.log(`Secret: ${client.secret}`); console.log(`Redirect URI: ${client.redirect}`); ```