### Setup User and Namespace Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CommunityApi.md Registers a new user and creates a namespace with the same name as the username. This is typically used for initial user setup. ```APIDOC ## POST /setup ### Description Register an user and create namespace with the same name as username. ### Method POST ### Endpoint /setup ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **setupRequest** (SetupRequest) - Required - Description of the request body. - **sign** (string) - Optional - Signature used to validate request origin generated by running `./bin/setup` script. ### Request Example ```json { "sign": "your-signature", "setupRequest": {} } ``` ### Response #### Success Response (200) - **None** (void) - Success to register user on setup. #### Response Example ```json {} ``` #### Error Responses - **400** - Bad request - **409** - Conflict - **500** - Internal error ``` -------------------------------- ### Get Sessions Example (TypeScript) Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CommunityApi.md Shows how to fetch a list of sessions from the ShellHub API using TypeScript. It includes setting up the API client and calling the getSessions method with optional pagination parameters. ```typescript import { CommunityApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new CommunityApi(configuration); let page: number; //Page number (optional) (default to 1) let perPage: number; //Items per page (optional) (default to 10) const { status, data } = await apiInstance.getSessions( page, perPage ); ``` -------------------------------- ### Get Customer API Example (TypeScript) Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/BillingApi.md Example of how to retrieve customer information using the BillingApi. This function takes no parameters and returns a GetCustomer200Response object. Authorization is required, either via API key or JWT. ```typescript import { BillingApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new BillingApi(configuration); const { status, data } = await apiInstance.getCustomer(); ``` -------------------------------- ### ShellHub Docker Compose Deployment (Development) Source: https://context7.com/shellhub-io/shellhub/llms.txt Guides through deploying a self-hosted ShellHub instance using Docker Compose in a development environment. This involves generating keys, setting an environment variable, starting all services, creating an initial user and namespace, and accessing the web UI. It also includes commands to stop services and view logs. ```bash # Generate required keys make keygen # Set environment to development echo "SHELLHUB_ENV=development" >> .env.override # Start all services make start # This starts: MongoDB, Redis, API, SSH, Gateway, UI, Agent # Create initial user ./bin/cli user create admin Secret123! admin@example.com # Create namespace (use the hardcoded tenant ID for development) ./bin/cli namespace create production admin 00000000-0000-4000-0000-000000000000 # Access the web UI # Open browser to http://localhost:80 # Stop all services make stop # View logs docker-compose logs -f api docker-compose logs -f ssh docker-compose logs -f agent ``` -------------------------------- ### Start ShellHub Development Environment Source: https://github.com/shellhub-io/shellhub/blob/master/README.md This command starts all the necessary services for the ShellHub development environment using a wrapper script. It is recommended over using docker-compose directly unless you have specific needs. ```shell make start ``` -------------------------------- ### Get Session Example (TypeScript) Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CommunityApi.md Demonstrates how to retrieve a specific session using the ShellHub API in TypeScript. It shows the import statements, configuration, and the asynchronous call to the getSession method. ```typescript import { CommunityApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new CommunityApi(configuration); let uid: string; // (default to undefined) const { status, data } = await apiInstance.getSession( uid ); ``` -------------------------------- ### Get Devices Admin Endpoint Example (TypeScript) Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/DevicesApi.md Demonstrates how to use the `getDevicesAdmin` function from the ShellHub API client in TypeScript. It shows how to instantiate the API client, set optional parameters like filter, page, perPage, status, sortBy, and orderBy, and then make the API call to retrieve a list of devices. ```typescript import { DevicesApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new DevicesApi(configuration); let filter: string; //Device\'s filter Filter field receives a base64 enconded JSON object for limit a search. The JSON object should have a property called `type`, it will filter by a `property` called `name` where the value should `contains` `linux`. If you want get only Devices name as `Linux`, the JSON object will looks like this ```json [ { "type":"property", "params": { "name":"name", "operator":"contains", "value":"linux" } } ] ``` So, the output encoded string will result on: `W3sidHlwZSI6InByb3BlcnR5IiwicGFyYW1zIjp7Im5hbWUiOiJuYW1lIiwib3BlcmF0b3IiOiJjb250YWlucyIsInZhbHVlIjoiZDAifX1d` (optional) (default to undefined) let page: number; //Page number (optional) (default to 1) let perPage: number; //Items per page (optional) (default to 10) let status: DeviceStatus; //Device\'s status (optional) (default to undefined) let sortBy: string; //Device\'s property to sort of (optional) (default to undefined) let orderBy: GetDevicesAdminOrderByParameter; // (optional) (default to undefined) const { status, data } = await apiInstance.getDevicesAdmin( filter, page, perPage, status, sortBy, orderBy ); ``` -------------------------------- ### Install ShellHub Agent via Docker Source: https://context7.com/shellhub-io/shellhub/llms.txt Provides commands for installing the ShellHub agent using Docker. This includes standard installation, custom configuration with environment variables, and manual Docker run commands for both agent and connector modes. The connector mode is used for accessing Docker containers. ```bash # Install agent in standard mode curl -sSf https://get.shellhub.io | \ SERVER_ADDRESS=https://cloud.shellhub.io \ TENANT_ID=00000000-0000-4000-0000-000000000000 \ sh # Install with custom configuration curl -sSf https://get.shellhub.io | \ SERVER_ADDRESS=https://cloud.shellhub.io \ TENANT_ID=00000000-0000-4000-0000-000000000000 \ KEEPALIVE_INTERVAL=60 \ PREFERRED_HOSTNAME=my-device \ CONTAINER_NAME=shellhub-agent \ sh # Manual Docker installation docker run -d \ --name=shellhub \ --restart=on-failure \ --privileged \ --pid=host \ --network host \ -v /:/host \ -v /dev:/dev \ -v /var/run/docker.sock:/var/run/docker.sock \ -e SHELLHUB_SERVER_ADDRESS=https://cloud.shellhub.io \ -e SHELLHUB_TENANT_ID=00000000-0000-4000-0000-000000000000 \ -e SHELLHUB_PRIVATE_KEY=/host/etc/shellhub.key \ -e SHELLHUB_KEEPALIVE_INTERVAL=30 \ shellhubio/agent:latest # Install connector mode (for Docker container access) curl -sSf https://get.shellhub.io | \ SERVER_ADDRESS=https://cloud.shellhub.io \ TENANT_ID=00000000-0000-4000-0000-000000000000 \ sh -s -- connector # Manual connector mode installation docker run -d \ --name=shellhub-connector \ --restart=on-failure \ --privileged \ --network host \ -v /var/run/docker.sock:/var/run/docker.sock \ -e SHELLHUB_SERVER_ADDRESS=https://cloud.shellhub.io \ -e SHELLHUB_TENANT_ID=00000000-0000-4000-0000-000000000000 \ -e SHELLHUB_PRIVATE_KEYS=/host/etc/shellhub/connector/keys \ -e SHELLHUB_CONNECTOR_LABEL=production \ shellhubio/agent:latest \ connector ``` -------------------------------- ### Example JSON for Device Filtering (JSON) Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/DevicesApi.md Provides JSON examples for filtering device lists based on specific criteria. The first example filters for devices where the 'confirmed' property is true. The second example demonstrates a more complex filter combining conditions using 'and' to filter by 'info.id' and 'online' status. ```json [ { "type": "property", "params": { "name": "confirmed", "operator": "bool", "value": "true" } } ] ``` ```json [ { "type": "property", "params": { "name": "info.id", "operator": "eq", "value": "manjaro" } }, { "type": "property", "params": { "name": "online", "operator": "bool", "value": "true" } }, { "type": "property", "params": { "name": "and" } } ] ``` -------------------------------- ### TypeScript ConnectorInfo200Response Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/ConnectorInfo200Response.md This snippet illustrates the instantiation and structure of the ConnectorInfo200Response object in TypeScript. It imports the necessary type definition and assigns a sample object with various properties related to connector information. ```typescript import { ConnectorInfo200Response } from './api'; const instance: ConnectorInfo200Response = { ID, Containers, ContainersRunning, ContainersPaused, ContainersStopped, Images, Driver, DriverStatus, Plugins, MemoryLimit, SwapLimit, CpuCfsPeriod, CpuCfsQuota, CPUShares, CPUSet, PidsLimit, IPv4Forwarding, BridgeNfIptables, BridgeNfIp6tables, Debug, NFd, OomKillDisable, NGoroutines, SystemTime, LoggingDriver, CgroupDriver, CgroupVersion, NEventsListener, KernelVersion, OperatingSystem, OSVersion, OSType, Architecture, IndexServerAddress, RegistryConfig, NCPU, MemTotal, GenericResources, DockerRootDir, HttpProxy, HttpsProxy, NoProxy, Name, Labels, ExperimentalBuild, ServerVersion, Runtimes, DefaultRuntime, Swarm, LiveRestoreEnabled, Isolation, InitBinary, ContainerdCommit, RuncCommit, InitCommit, SecurityOptions, CDISpecDirs, Warnings, }; ``` -------------------------------- ### Get Devices Admin - TypeScript Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/AdminApi.md Retrieves a list of devices with optional filtering, pagination, and sorting. It requires configuration for the AdminApi and handles various parameters for precise device retrieval. The response includes the status of the operation and the device data. ```typescript import { AdminApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new AdminApi(configuration); let filter: string; let page: number; let perPage: number; let status: DeviceStatus; let sortBy: string; let orderBy: GetDevicesAdminOrderByParameter; const { status, data } = await apiInstance.getDevicesAdmin( filter, page, perPage, status, sortBy, orderBy ); ``` -------------------------------- ### Create Connector - TypeScript Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CloudApi.md Example of creating a new connector using the connectorCreate function in TypeScript. This function requires the CloudApi, Configuration, and ConnectorData from the './api' module. It returns the status and data of the creation process. ```typescript import { CloudApi, Configuration, ConnectorData } from './api'; const configuration = new Configuration(); const apiInstance = new CloudApi(configuration); let connectorData: ConnectorData; // const { status, data } = await apiInstance.connectorCreate( connectorData ); ``` -------------------------------- ### Get Firewall Rules Admin - TypeScript Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/RulesApi.md This TypeScript code snippet demonstrates how to fetch a list of firewall rules using the ShellHub API. It utilizes the RulesApi from the generated client library and requires configuration for API access. The function accepts optional page and perPage parameters for pagination. ```typescript import { RulesApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new RulesApi(configuration); let page: number; //Page number (optional) (default to 1) let perPage: number; //Items per page (optional) (default to 10) const { status, data } = await apiInstance.getFirewallRulesAdmin( page, perPage ); ``` -------------------------------- ### Create Subscription API Example (TypeScript) Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/BillingApi.md Example of how to create a new subscription using the BillingApi. This function does not require any parameters and returns an empty response body upon success. It uses API key or JWT for authorization. ```typescript import { BillingApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new BillingApi(configuration); const { status, data } = await apiInstance.createSubscription(); ``` -------------------------------- ### Choice Devices - TypeScript Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CloudApi.md Example of how to use the choiceDevices function in TypeScript. This function is used to choose devices when a device's limit is reached. It requires the CloudApi, Configuration, and ChoiceDevicesRequest from the './api' module. The function returns the status and data of the API call. ```typescript import { CloudApi, Configuration, ChoiceDevicesRequest } from './api'; const configuration = new Configuration(); const apiInstance = new CloudApi(configuration); let choiceDevicesRequest: ChoiceDevicesRequest; // (optional) const { status, data } = await apiInstance.choiceDevices( choiceDevicesRequest ); ``` -------------------------------- ### Authentication and User Management Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CommunityApi.md Endpoints for user authentication, setup, and retrieving user information. ```APIDOC ## POST /api/auth/ssh ### Description Authenticates a user using an SSH public key. ### Method POST ### Endpoint /api/auth/ssh ### Parameters #### Request Body - **username** (string) - Required - The username. - **public_key** (string) - Required - The SSH public key. ### Request Example ```json { "example": "{\"username\": \"testuser\", \"public_key\": \"ssh-rsa AAAAB3NzaC1yc2EAAA...\"}" } ``` ### Response #### Success Response (200) - **token** (string) - Authentication token. #### Response Example ```json { "example": "{\"token\": \"your_jwt_token_here\"}" } ``` ## POST /api/auth/user ### Description Authenticates a user using username and password. ### Method POST ### Endpoint /api/auth/user ### Parameters #### Request Body - **username** (string) - Required - The username. - **password** (string) - Required - The user's password. ### Request Example ```json { "example": "{\"username\": \"testuser\", \"password\": \"password123\"}" } ``` ### Response #### Success Response (200) - **token** (string) - Authentication token. #### Response Example ```json { "example": "{\"token\": \"your_jwt_token_here\"}" } ``` ## GET /api/users/security ### Description Checks the session record status for the authenticated user. ### Method GET ### Endpoint /api/users/security ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) - **session_record** (boolean) - Indicates if session recording is enabled. #### Response Example ```json { "example": "{\"session_record\": true}" } ``` ## GET /api/auth/user ### Description Retrieves information about the currently authenticated user. ### Method GET ### Endpoint /api/auth/user ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) - **username** (string) - The username of the authenticated user. - **email** (string) - The email address of the authenticated user. #### Response Example ```json { "example": "{\"username\": \"testuser\", \"email\": \"testuser@example.com\"}" } ``` ## POST /api/setup ### Description Initializes the user setup process. ### Method POST ### Endpoint /api/setup ### Parameters #### Request Body - **username** (string) - Required - The desired username. - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```json { "example": "{\"username\": \"newuser\", \"email\": \"newuser@example.com\", \"password\": \"securepassword\"}" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating successful setup. #### Response Example ```json { "example": "{\"message\": \"User setup complete.\"}" } ``` ``` -------------------------------- ### TypeScript Example: UserAdminResponse Instance Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/UserAdminResponse.md This snippet shows how to create an instance of the UserAdminResponse model in TypeScript. It assumes that variables like 'id', 'namespaces', 'confirmed', 'created_at', 'last_login', 'name', 'email', 'username', and 'password' are already defined. This example is useful for understanding the structure and usage of the UserAdminResponse object. ```typescript import { UserAdminResponse } from './api'; const instance: UserAdminResponse = { id, namespaces, confirmed, created_at, last_login, name, email, username, password, }; ``` -------------------------------- ### GET /devices Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CommunityApi.md Retrieves a list of devices, with options for filtering, pagination, and sorting. ```APIDOC ## GET /devices ### Description Get a list of devices. ### Method GET ### Endpoint /devices ### Parameters #### Query Parameters - **filter** (string) - Optional - Filter field receives a JSON object encoded as base64 string for limiting a search. The JSON encoded must follow these interfaces: ```typescript interface ParamProperty { name: string; operator: "contains" | "eq" | "bool" | "gt" | "lt"; value: string; } interface ParamOperator { name: "and" | "or"; } interface Filter { type: "property" | "operator"; param: ParamOperator | ParamProperty; } interface FilterList { Filters: Array; } ``` ## Examples This is a example to filter and get only the resource what property "confirmed" is "true" ```json [ { "type": "property", "params": { "name": "confirmed", "operator": "bool", "value": "true" } } ] ``` This one, filter resource by the property "id" inside "info" structure when it is equal to "manjaro" and online property is set to "true" ```json [ { "type": "property", "params": { "name": "info.id", "operator": "eq", "value": "manjaro" } }, { "type": "property", "params": { "name": "online", "operator": "bool", "value": "true" } }, { "type": "operator", "params": { "name": "and" } } ] ``` - **page** (number) - Optional - Page number (default to 1) - **perPage** (number) - Optional - Items per page (default to 10) - **status** (DeviceStatus) - Optional - Device's status (default to undefined) - **sortBy** (string) - Optional - Device's property to sort of (default to 'last_seen') - **orderBy** (GetDevicesOrderByParameter) - Optional - (default to undefined) ### Request Example ```typescript import { CommunityApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new CommunityApi(configuration); let filter: string; let page: number; let perPage: number; let status: DeviceStatus; let sortBy: string; let orderBy: GetDevicesOrderByParameter; const { status, data } = await apiInstance.getDevices( filter, page, perPage, status, sortBy, orderBy ); ``` ### Response #### Success Response (200) - **Array** (array) - A list of devices. #### Response Example ```json { "example": "Array of Device objects" } ``` #### Error Response - **401**: Unauthorized - **500**: Internal error ``` -------------------------------- ### POST /api/setup Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/SystemApi.md Registers a new user and creates a namespace with the same name as the username. This is typically the first step in setting up a new ShellHub instance. ```APIDOC ## POST /api/setup ### Description Register an user and create namespace with the same name as username. ### Method POST ### Endpoint /api/setup ### Parameters #### Query Parameters - **sign** (string) - Optional - Signature used to validate request origin generated by running `./bin/setup` script. #### Request Body - **setupRequest** (object) - Required - User and namespace details for setup. ### Request Example ```typescript import { SystemApi, Configuration, SetupRequest } from './api'; const configuration = new Configuration(); const apiInstance = new SystemApi(configuration); let sign: string; let setupRequest: SetupRequest; const { status, data } = await apiInstance.setup(sign, setupRequest); ``` ### Response #### Success Response (200) - **void** (empty response body) - Indicates successful user registration and namespace creation. #### Response Example (No response body on success) ``` -------------------------------- ### Setup User and Namespace (TypeScript) Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/SystemApi.md Registers a new user and creates a namespace with the same name as the username. This operation requires a signature for validation, generated by running the './bin/setup' script. It uses the 'SystemApi', 'Configuration', and 'SetupRequest' classes from the './api' module. ```typescript import { SystemApi, Configuration, SetupRequest } from './api'; const configuration = new Configuration(); const apiInstance = new SystemApi(configuration); let sign: string; //Signature used to validate request origin generated by running `./bin/setup` script (default to undefined) let setupRequest: SetupRequest; // (optional) const { status, data } = await apiInstance.setup( sign, setupRequest ); ``` -------------------------------- ### Get Device - TypeScript Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/DevicesApi.md Retrieves device information using its UID. Requires API-key or JWT authorization. Returns a Device object on success. ```typescript import { DevicesApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new DevicesApi(configuration); let uid: string; //Device\'s UID (default to undefined) const { status, data } = await apiInstance.getDevice( uid ); ``` -------------------------------- ### Create and Use ShellHub Go API Client Source: https://context7.com/shellhub-io/shellhub/llms.txt Demonstrates how to create a Go client to interact with the ShellHub API. It covers client initialization, fetching server info and endpoints, device authentication, listing and retrieving devices, and setting up a reverse listener for SSH tunneling. Requires the shellhub-io/shellhub/pkg/api/client package. ```go package main import ( "context" "log" "github.com/shellhub-io/shellhub/pkg/api/client" "github.com/shellhub-io/shellhub/pkg/models" "net" ) func main() { // Create client cli, err := client.NewClient("https://cloud.shellhub.io:443") if err != nil { log.Fatalf("Failed to create client: %v", err) } // Get server information info, err := cli.GetInfo("v0.15.0") if err != nil { log.Fatalf("Failed to get info: %v", err) } log.Printf("ShellHub version: %s", info.Version) // Get API endpoints endpoints, err := cli.Endpoints() if err != nil { log.Fatalf("Failed to get endpoints: %v", err) } log.Printf("API endpoint: %s", endpoints.API) log.Printf("SSH endpoint: %s", endpoints.SSH) // Authenticate device authReq := &models.DeviceAuthRequest{ DeviceAuth: &models.DeviceAuth{ Hostname: "my-device", PublicKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ...", TenantID: "00000000-0000-4000-0000-000000000000", }, Info: &models.DeviceInfo{ ID: "alpine", Version: "3.18", Arch: "x86_64", Platform: "linux", }, } authRes, err := cli.AuthDevice(authReq) if err != nil { log.Fatalf("Device auth failed: %v", err) } log.Printf("Authenticated as device: %s", authRes.UID) // List devices devices, err := cli.ListDevices() if err != nil { log.Fatalf("Failed to list devices: %v", err) } for _, device := range devices { log.Printf("Device: %s (online: %v)", device.Name, device.Online) } // Get specific device device, err := cli.GetDevice("a1b2c3d4e5f6") if err != nil { log.Fatalf("Failed to get device: %v", err) } log.Printf("Device: %s at %s", device.Name, device.RemoteAddr) // Create reverse listener for SSH tunneling ctx := context.Background() listener, err := cli.NewReverseListener(ctx, authRes.Token, "/ssh/connection") if err != nil { log.Fatalf("Failed to create reverse listener: %v", err) } defer listener.Close() log.Println("Reverse listener established, waiting for connections...") for { conn, err := listener.Accept() if err != nil { log.Printf("Accept error: %v", err) continue } go handleConnection(conn) } } func handleConnection(conn net.Conn) { defer conn.Close() log.Printf("New connection from reverse tunnel") // Handle SSH connection } ``` -------------------------------- ### Get Device Admin - TypeScript Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/DevicesApi.md Retrieves device information using its UID. Requires API-key or JWT authorization. Returns a Device object on success. ```typescript import { DevicesApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new DevicesApi(configuration); let uid: string; //Device\'s UID (default to undefined) const { status, data } = await apiInstance.getDeviceAdmin( uid ); ``` -------------------------------- ### Get Sessions Admin - TypeScript Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/SessionsApi.md Retrieves a list of sessions with optional pagination. This function requires a Configuration object and an instance of SessionsApi. It returns the status and data of the API call, where data is an array of Session objects. ```typescript import { SessionsApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new SessionsApi(configuration); let page: number; //Page number (optional) (default to 1) let perPage: number; //Items per page (optional) (default to 10) const { status, data } = await apiInstance.getSessionsAdmin( page, perPage ); ``` -------------------------------- ### Initialize ShellHub API Service (Go) Source: https://context7.com/shellhub-io/shellhub/llms.txt Initializes the ShellHub API service by configuring dependencies such as Redis for caching, MongoDB for data storage, and RSA keys for JWT signing. It also sets up an internal HTTP client. The service is then used to list devices. ```go package main import ( "context" "crypto/rsa" "log" "github.com/shellhub-io/shellhub/api/services" "github.com/shellhub-io/shellhub/api/store/mongo" "github.com/shellhub-io/shellhub/pkg/cache" "github.com/shellhub-io/shellhub/pkg/api/internalclient" "github.com/shellhub-io/shellhub/pkg/api/requests" "github.com/shellhub-io/shellhub/pkg/query" ) func main() { ctx := context.Background() // Initialize Redis cache redisCache := cache.NewRedisCache("redis://localhost:6379") // Connect to MongoDB store, err := mongo.NewStore( ctx, "mongodb://localhost:27017/shellhub", redisCache, mongo.WithIndexes(), ) if err != nil { log.Fatalf("Failed to connect to database: %v", err) } // Load RSA keys for JWT signing privateKey := loadPrivateKey("/etc/shellhub/keys/private.pem") publicKey := &privateKey.PublicKey // Create HTTP client for internal requests client := internalclient.NewClient() // Initialize service with all components service := services.NewService( store, privateKey, publicKey, redisCache, client, ) // Use service methods devices, count, err := service.ListDevices(ctx, &requests.DeviceList{ Paginator: query.Paginator{Page: 1, PerPage: 10}, TenantID: "00000000-0000-4000-0000-000000000000", }) if err != nil { log.Fatalf("Failed to list devices: %v", err) } log.Printf("Found %d devices (total: %d)", len(devices), count) } func loadPrivateKey(path string) *rsa.PrivateKey { // Implementation to load RSA private key from file // ... return privateKey } ``` -------------------------------- ### Get Announcement - TypeScript Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CommunityApi.md Shows how to retrieve an announcement using the ShellHub Community API. This operation does not require authorization. It accepts an optional UUID parameter and returns an Announcement object. The API client handles potential 'Not found' or 'Internal error' responses. ```typescript import { CommunityApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new CommunityApi(configuration); let uuid: string; // (default to undefined) const { status, data } = await apiInstance.getAnnouncement( uuid ); ``` -------------------------------- ### TypeScript SetupRequest Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/SetupRequest.md This code snippet demonstrates how to create an instance of the SetupRequest model in TypeScript. It imports the necessary type and initializes an object with user details. Ensure that the 'name', 'email', 'username', and 'password' variables are defined before instantiation. ```typescript import { SetupRequest } from './api'; const instance: SetupRequest = { name, email, username, password, }; ``` -------------------------------- ### Get Most Used Devices - TypeScript Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/BillingApi.md Retrieves the most used devices from the billing API. Requires configuration setup and returns an array of Device objects upon success. Handles errors like forbidden access or internal server errors. ```typescript import { BillingApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new BillingApi(configuration); const { status, data } = await apiInstance.getDevicesMostUsed(); ``` -------------------------------- ### Bash: CLI User Management Commands Source: https://context7.com/shellhub-io/shellhub/llms.txt Provides command-line examples for managing users in ShellHub. It demonstrates how to create a new user with credentials and email, reset a user's password, and delete a user account using the `cli` tool. ```bash # Create a new user ./bin/cli user create admin Secret123! admin@example.com # Output: User 'admin' created successfully with ID: 1234567890 # Reset user password ./bin/cli user password admin NewSecret456! # Output: Password updated for user 'admin' # Delete user ./bin/cli user delete admin # Output: User 'admin' deleted successfully ``` -------------------------------- ### Manage Devices with ShellHub Service (Go) Source: https://context7.com/shellhub-io/shellhub/llms.txt Demonstrates various device management operations using the ShellHub service, including listing devices with pagination and sorting, retrieving a specific device, renaming, updating status (accept/reject), marking offline, and deleting. ```go package main import ( "context" "log" "github.com/shellhub-io/shellhub/api/services" "github.com/shellhub-io/shellhub/pkg/api/requests" "github.com/shellhub-io/shellhub/pkg/models" "github.com/shellhub-io/shellhub/pkg/query" ) func main() { ctx := context.Background() var service services.Service // Assume initialized // List devices with filtering deviceReq := &requests.DeviceList{ Paginator: query.Paginator{Page: 1, PerPage: 20}, Sorter: query.Sorter{By: "last_seen", Order: "desc"}, TenantID: "00000000-0000-4000-0000-000000000000", } devices, count, err := service.ListDevices(ctx, deviceReq) if err != nil { log.Fatalf("Failed to list devices: %v", err) } log.Printf("Found %d devices (total: %d)", len(devices), count) // Get specific device device, err := service.GetDevice(ctx, models.UID("a1b2c3d4e5f6")) if err != nil { log.Fatalf("Failed to get device: %v", err) } log.Printf("Device: %s (online: %v)", device.Name, device.Online) // Rename device err = service.RenameDevice( ctx, models.UID("a1b2c3d4e5f6"), "new-device-name", "00000000-0000-4000-0000-000000000000", ) if err != nil { log.Fatalf("Failed to rename device: %v", err) } // Update device status (accept/reject) err = service.UpdateDeviceStatus(ctx, &requests.DeviceUpdateStatus{ UID: "a1b2c3d4e5f6", TenantID: "00000000-0000-4000-0000-000000000000", Status: string(models.DeviceStatusAccepted), }) if err != nil { log.Fatalf("Failed to update status: %v", err) } // Mark device offline err = service.OfflineDevice(ctx, models.UID("a1b2c3d4e5f6")) if err != nil { log.Fatalf("Failed to mark offline: %v", err) } // Delete device err = service.DeleteDevice( ctx, models.UID("a1b2c3d4e5f6"), "00000000-0000-4000-0000-000000000000", ) if err != nil { log.Fatalf("Failed to delete device: %v", err) } } ``` -------------------------------- ### Get Announcement by UUID (TypeScript) Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/AnnouncementsApi.md Retrieves a specific announcement using its unique identifier (UUID). This function requires the 'uuid' as a string parameter and returns an 'Announcement' object upon success. It is part of the AnnouncementsApi and relies on the Configuration object for setup. No authorization is required. ```typescript import { AnnouncementsApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new AnnouncementsApi(configuration); let uuid: string; // (default to undefined) const { status, data } = await apiInstance.getAnnouncement( uuid ); ``` -------------------------------- ### Get Public Keys Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CommunityApi.md Demonstrates how to retrieve a list of public keys using the Shellhub Community API. It shows how to configure the API client and make a request with optional filter, page, and perPage parameters. The filter parameter accepts a base64 encoded JSON object for advanced searching. ```typescript import { CommunityApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new CommunityApi(configuration); let filter: string; //Filter field receives a JSON object enconded as base64 string for limit a search. The JSON enconded must follow these interafaces: ```typescript interface ParamProperty { name: string; operator: "contains" | "eq" | "bool" | "gt" | "lt"; value: string; } interface ParamOperator { name: "and" | "or"; } interface Filter { type: "property" | "operator"; param: ParamOperator | ParamProperty; } interface FilterList { Filters: Array; } ``` ## Examples This is a example to filter and get only the resource what property "confirmed" is "true" ```json [ { "type": "property", "params": { "name": "confirmed", "operator": "bool", "value": "true" } } ] ``` This one, filter resource by the property "id" inside "info" structure when it is equal to "manjaro" and online property is set to "true" ```json [ { "type": "property", "params": { "name": "info.id", "operator": "eq", "value": "manjaro" } }, { "type": "property", "params": { "name": "online", "operator": "bool", "value": "true" } }, { "type": "operator", "params": { "name": "and" } } ] ``` (optional) (default to undefined) let page: number; //Page number (optional) (default to 1) let perPage: number; //Items per page (optional) (default to 10) const { status, data } = await apiInstance.getPublicKeys( filter, page, perPage ); ``` ``` -------------------------------- ### Setup User and Namespace in TypeScript Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CommunityApi.md Registers a user and creates a namespace with the same name as the username. This function requires a signature for validation and an optional SetupRequest object. It returns void and does not require authorization. ```typescript import { CommunityApi, Configuration, SetupRequest } from './api'; const configuration = new Configuration(); const apiInstance = new CommunityApi(configuration); let sign: string; //Signature used to validate request origin generated by running `./bin/setup` script (default to undefined) let setupRequest: SetupRequest; // (optional) const { status, data } = await apiInstance.setup( sign, setupRequest ); ``` -------------------------------- ### Get Firewall Rule Admin - TypeScript Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/AdminApi.md Fetches a specific firewall rule by its ID. This function requires the AdminApi to be configured and takes an optional 'id' parameter to specify the rule to retrieve. The result includes the operation status and the firewall rule data. ```typescript import { AdminApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new AdminApi(configuration); let id: string; const { status, data } = await apiInstance.getFirewallRuleAdmin( id ); ``` -------------------------------- ### Go: Device, User, Public Key, and API Key Authentication Source: https://context7.com/shellhub-io/shellhub/llms.txt Demonstrates various authentication methods using the ShellHub Go API, including device authentication, local user login, SSH public key validation, and API key verification. It covers essential parameters and expected outcomes for each authentication type. ```go package main import ( "context" "log" "github.com/shellhub-io/shellhub/api/services" "github.com/shellhub-io/shellhub/pkg/api/requests" "github.com/shellhub-io/shellhub/pkg/models" ) func main() { ctx := context.Background() var service services.Service // Assume initialized // Authenticate device deviceAuthReq := &models.DeviceAuthRequest{ DeviceAuth: &models.DeviceAuth{ Hostname: "webserver-01", Identity: &models.DeviceIdentity{MAC: "00:11:22:33:44:55"}, PublicKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ...", TenantID: "00000000-0000-4000-0000-000000000000", }, Info: &models.DeviceInfo{ ID: "ubuntu", PrettyName: "Ubuntu 22.04 LTS", Version: "22.04", Arch: "x86_64", Platform: "linux", }, } deviceAuthRes, err := service.AuthDevice(ctx, deviceAuthReq) if err != nil { log.Fatalf("Device auth failed: %v", err) } log.Printf("Device authenticated: %s (token: %s)", deviceAuthRes.UID, deviceAuthRes.Token) // Authenticate user userAuthReq := &requests.AuthLocalUser{ Username: "admin", Password: "secret123", } userAuthRes, lockout, mfaToken, err := service.AuthLocalUser( ctx, userAuthReq, "192.168.1.100", // source IP ) if lockout > 0 { log.Fatalf("Account locked out for %d seconds", lockout) } if mfaToken != "" { log.Printf("MFA required. Token: %s", mfaToken) // User must provide MFA code return } if err != nil { log.Fatalf("User auth failed: %v", err) } log.Printf("User authenticated: %s (token: %s)", userAuthRes.Name, userAuthRes.Token) // Authenticate SSH public key pubKeyAuthReq := &models.PublicKeyAuthRequest{ Fingerprint: "SHA256:abcd1234efgh5678...", Data: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC5...", } pubKeyAuthRes, err := service.AuthPublicKey(ctx, pubKeyAuthReq) if err != nil { log.Fatalf("Public key auth failed: %v", err) } log.Printf("Public key authenticated for device: %s", pubKeyAuthRes.DeviceUID) // Authenticate API key apiKey, err := service.AuthAPIKey(ctx, "sk_test_1234567890abcdefghijklmnop") if err != nil { log.Fatalf("API key auth failed: %v", err) } log.Printf("API key authenticated: tenant=%s, role=%s", apiKey.TenantID, apiKey.Role) } ``` -------------------------------- ### Bash: CLI Namespace Management Commands Source: https://context7.com/shellhub-io/shellhub/llms.txt Illustrates how to manage namespaces for device organization using ShellHub's command-line interface. Includes commands for creating a new namespace with a specified name, owner, and tenant ID, along with a note about tenant ID behavior in development environments. ```bash # Create namespace ./bin/cli namespace create production admin 00000000-0000-4000-0000-000000000000 # Output: Namespace 'production' created with tenant ID: 00000000-0000-4000-0000-000000000000 # Note: The tenant ID in development mode is always 00000000-0000-4000-0000-000000000000 # This is hardcoded for agent initialization during development ``` -------------------------------- ### Get Container - TypeScript Example Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/CommunityApi.md Illustrates how to retrieve a specific container's details using the ShellHub Community API. Requires API key or JWT for authorization. It accepts a device UID and returns a Device object. The function handles potential 'Unauthorized', 'Not found', or 'Internal error' responses. ```typescript import { CommunityApi, Configuration } from './api'; const configuration = new Configuration(); const apiInstance = new CommunityApi(configuration); let uid: string; //Device's UID (default to undefined) const { status, data } = await apiInstance.getContainer( uid ); ``` -------------------------------- ### Create ShellHub Agent Programmatically in Go Source: https://context7.com/shellhub-io/shellhub/llms.txt Initializes and runs a ShellHub agent within a Go application. It requires configuration parameters such as server address, tenant ID, and private key path. The agent can be initialized and then start listening for SSH connections. ```go package main import ( "context" "log" "github.com/shellhub-io/shellhub/agent" ) func main() { // Configure the agent cfg := agent.Config{ ServerAddress: "http://localhost:80", TenantID: "00000000-0000-4000-0000-000000000000", PrivateKey: "/tmp/shellhub.key", KeepAliveInterval: 30, PreferredHostname: "my-custom-hostname", PreferredIdentity: "00:11:22:33:44:55", } // Create agent instance with host mode ag, err := agent.NewAgentWithConfig(&cfg, new(agent.HostMode)) if err != nil { log.Fatalf("Failed to create agent: %v", err) } // Initialize the agent (generates keys, sets up SSH server) if err := ag.Initialize(); err != nil { log.Fatalf("Failed to initialize agent: %v", err) } // Start listening for SSH connections ctx := context.Background() if err := ag.Listen(ctx); err != nil { log.Fatalf("Agent stopped: %v", err) } } ``` -------------------------------- ### TypeScript Example: Instantiate ConnectorInfo200ResponseRegistryConfig Source: https://github.com/shellhub-io/shellhub/blob/master/ui/src/api/client/docs/ConnectorInfo200ResponseRegistryConfig.md This TypeScript code snippet demonstrates how to create an instance of the ConnectorInfo200ResponseRegistryConfig model. It shows the import statement and the structure for initializing the object with its various properties. ```typescript import { ConnectorInfo200ResponseRegistryConfig } from './api'; const instance: ConnectorInfo200ResponseRegistryConfig = { AllowNondistributableArtifactsCIDRs, AllowNondistributableArtifactsHostnames, InsecureRegistryCIDRs, IndexConfigs, Mirrors, }; ```