Finalise v1 and push
This commit is contained in:
parent
b12df1e2d7
commit
d7c3e11d7e
2 changed files with 238 additions and 0 deletions
587
How/Plan.md
Normal file
587
How/Plan.md
Normal file
|
|
@ -0,0 +1,587 @@
|
|||
# GCoordinator by [tyuXX]
|
||||
|
||||
> **Architecture & Implementation Blueprint** — A self-hosted, security-first central sysadmin hub for multiplexed SSH access, key lifecycle management, live agentless monitoring, endpoint probes, scheduled jobs, cross-server pipelines, event-driven alerting, and file transfers.
|
||||
|
||||
---
|
||||
|
||||
## 1. Overview & Design Goals
|
||||
|
||||
GCoordinator is a single-admin control plane for managing heterogeneous servers over SSH with centralized, encrypted credentials—without handing keys or server access to any third-party service.
|
||||
|
||||
| Goal | Approach |
|
||||
| :--- | :--- |
|
||||
| **Centralized SSH Hub** | Persistent multiplexed SSH connections with `ProxyJump` bastion chaining, server-side persistent PTY sessions, SFTP file manager, authenticated HTTP/WS tunnel proxy, and managed port forwarding. |
|
||||
| **Zero Third-Party Trust** | Self-hosted encrypted vault (`AES-256-GCM`) unlocked at runtime, master-key rotation, per-server SSH key management with atomic zero-lockout key rotation, and an emergency **Panic Lock**. |
|
||||
| **Editable & Synced Configs** | Per-entity modular JSON files (`servers/*.json`, `workflows/*.json`, `systems/*.json`, `snippets.json`, `alerts.json`, `settings.json`) editable via Web UI or disk with live hot-reload and automatic revision history + 1-click diff/rollback. |
|
||||
| **Agentless Monitoring & Probes** | Pure SSH polling with `uname -s` auto-detection for Linux, BSD, and macOS, multi-mount disk tracking, on-demand Server Inspector (processes/ports/temps), HTTP/TCP endpoint health probes, and SQLite time-series retention. |
|
||||
| **Custom Systems Engine** | Dedicated top-level **Systems** section (a page per system) defined declaratively in `/data/config/systems/*.json`. Ships editable presets (`docker-compose`, `systemd`, `os-packages`), supports per-server paths, multi-file overlays (`activeFiles[]`), container/item debugging shells, smart TTL caching + alert integration, live log streaming, and per-service cron tasks. |
|
||||
| **Interconnected Automation** | Unified workflow engine supporting cron/manual/event triggers, single/tag/fleet-wide (`all`) targets, safe env-var/quoted parameter passing, timeouts, overlap policies, dry-run preview, saved Command Snippets, Ad-Hoc Fleet Broadcast, cross-server transfers, and event-driven webhooks with maintenance windows/snoozing. |
|
||||
| **Optional BYO-API AI Assistant** | Strictly opt-in OpenAI-compatible (`/v1/chat/completions`) assistant (cloud or self-hosted Ollama/vLLM/llama.cpp) with context-specific built-in guides for generating workflows/snippets/systems, debugging logs, and setup help—with secret redaction and zero auto-execution. |
|
||||
| **Legacy Mobile Performance** | Sharp, flat terminal aesthetic (`0px` radius, `1px` borders, no bevels/shadows/`backdrop-filter`), zero-framework `esbuild`-bundled frontend (`<50KB` gzipped core, ES2019/ES2020), minimal PWA manifest, Safe/Read-Only mobile toggle, built to run smoothly on low-RAM devices like a **Samsung Galaxy J7**. |
|
||||
| **Zero Exposed Ports (+ Break-Glass)** | Dockerized deployment paired with a `cloudflared` tunnel sidecar on an internal Docker network, plus an optional `docker-compose.lan.yml` override for LAN/Tailscale break-glass access and raw TCP port forwards. |
|
||||
|
||||
---
|
||||
|
||||
## 2. Tech Stack
|
||||
|
||||
| Layer | Technology | Purpose |
|
||||
| :--- | :--- | :--- |
|
||||
| **Runtime & Language** | Node.js 22+ (LTS), TypeScript | Type-safe backend services, CLI utilities, and shared config schemas. |
|
||||
| **HTTP & Real-Time** | Express.js, `ws` | REST API, authenticated HTTP/WS tunnel proxy, static asset serving, and a single multiplexed WebSocket channel per client. |
|
||||
| **SSH Engine** | `ssh2` | Multiplexed SSH connections, `ProxyJump` via `forwardOut`, interactive PTY, SFTP streaming, and local/remote port forwarding. |
|
||||
| **Database** | `better-sqlite3` (WAL mode) | Time-series metrics, multi-mount disks, rollups, probe results, workflow runs/logs, config revisions, alert silences, sessions, known hosts, and audit logs. |
|
||||
| **Validation & Config** | `zod`, `chokidar` | Runtime JSON schema validation and debounced file-watch hot-reload. |
|
||||
| **Security & Auth** | Node `crypto` (`aes-256-gcm`, `ed25519`), `argon2`, `otpauth`, `@simplewebauthn/server` | Vault encryption, Ed25519 keypair generation, password hashing, universal TOTP 2FA, and optional Passkeys. |
|
||||
| **Scheduling** | `croner` | In-process cron scheduling with timezone, overlap policy, and concurrency support. |
|
||||
| **Frontend Core & Build** | Server-served HTML + Vanilla TS bundled via `esbuild` (ES2019/ES2020) + Pure CSS + PWA `manifest.json` | Zero SPA framework overhead, minimal HTTP requests on mobile, themeable via CSS custom properties, full-screen mobile launch. |
|
||||
| **Terminal & Charts** | `xterm.js` + `@xterm/addon-fit` (code-split lazy-loaded), custom SVG/Canvas | Terminal loaded only when opening a shell tab; lightweight sparklines/charts for dashboard metrics. |
|
||||
| **Deployment** | Multi-stage `Dockerfile`, `docker-compose.yml`, `docker-compose.lan.yml`, `cloudflared` | Non-root read-only container image with zero host-exposed ports by default and optional LAN/Tailscale override. |
|
||||
|
||||
---
|
||||
|
||||
## 3. System Architecture & Repository Layout
|
||||
|
||||
### System Architecture
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Client["Client Browser (Desktop / Galaxy J7 PWA)"] -->|"HTTPS + Single Multiplexed WSS"| Tunnel["Cloudflare Tunnel (cloudflared sidecar)"]
|
||||
Client -.->|"Optional Break-Glass / Raw TCP"| LAN["LAN / Tailscale Override (docker-compose.lan.yml)"]
|
||||
Tunnel -->|"Internal Docker Network"| Server["Express + Multiplexed WS + Tunnel Proxy"]
|
||||
LAN -.-> Server
|
||||
Server --> Auth["Auth, Safe-Mode & Panic Lock (Argon2id + TOTP / Passkeys)"]
|
||||
|
||||
Auth --> ConfigMgr["Config Manager (Zod + Chokidar + Revisions)"]
|
||||
Auth --> Vault["Encrypted Vault (AES-256-GCM + Key Rotation)"]
|
||||
Auth --> SSHPool["SSH Pool, ProxyJump, KeyMgr & Persistent PTY"]
|
||||
Auth --> Collector["OS-Aware Metrics, Disks, Inspector & Probes"]
|
||||
Auth --> Systems["Custom Systems Engine (Compose, systemd, Packages)"]
|
||||
Auth --> Workflow["Workflow, Snippets & Fleet Broadcast Engine"]
|
||||
Auth --> Alerts["Alert, Maintenance Windows & Webhook Engine"]
|
||||
Auth --> Transfer["Cross-Server Transfer Engine"]
|
||||
Auth -.-> AI["Optional BYO-API AI Assistant (Context Guides + Redactor)"]
|
||||
|
||||
ConfigMgr <-->|"Atomic Read/Write"| ConfigFiles["/data/config/ (servers/, workflows/, systems/, *.json)"]
|
||||
Vault <-->|"Master Key Unlock"| VaultFile["/data/vault.enc"]
|
||||
ConfigMgr -->|"Revisions"| DB["/data/gcoord.db (SQLite WAL)"]
|
||||
Collector -->|"Metrics, Disks & Probes"| DB
|
||||
Workflow -->|"Runs & Logs"| DB
|
||||
Alerts -->|"Events & Silences"| DB
|
||||
Auth -->|"Sessions, KnownHosts & Audit"| DB
|
||||
|
||||
SSHPool -->|"Multiplexed SSH / ProxyJump / SFTP / Tunnels"| Targets["Target Servers (Linux / BSD / macOS)"]
|
||||
Collector -->|"Agentless SSH Polling & On-Demand Inspect"| Targets
|
||||
Collector -->|"HTTP/TCP Health Probes"| Targets
|
||||
Systems -->|"Cached Discovery, Status & Actions"| Targets
|
||||
Workflow -->|"Exec / Read / System Action"| Targets
|
||||
Transfer -->|"Hub-Relayed SFTP or Direct rsync"| Targets
|
||||
Alerts -->|"Notifications"| Webhooks["Discord / Telegram / ntfy / Webhook"]
|
||||
AI -.->|"Opt-In /v1/chat/completions"| LLM["BYO OpenAI-Compatible Endpoint (Cloud / Local Ollama)"]
|
||||
```
|
||||
|
||||
### Repository Layout
|
||||
|
||||
```text
|
||||
GCoordinator/
|
||||
├── Plan.md # Architecture & implementation blueprint
|
||||
├── docker/
|
||||
│ ├── Dockerfile # Multi-stage build, non-root runtime user
|
||||
│ ├── docker-compose.yml # gcoordinator + cloudflared internal network (zero host ports)
|
||||
│ └── docker-compose.lan.yml # Optional LAN/Tailscale break-glass UI + raw TCP tunnel port range
|
||||
├── src/
|
||||
│ ├── shared/ # Shared TS types, WS protocol frames & Zod schemas
|
||||
│ ├── cli/ # CLI tools (backup, verify-backup, restore, rotate-key)
|
||||
│ ├── server/
|
||||
│ │ ├── index.ts # App bootstrap, graceful shutdown
|
||||
│ │ ├── config/ # ConfigManager, atomic writer, recursive chokidar watcher, revision store
|
||||
│ │ ├── security/ # Vault, master-key rotation, Panic Lock, Argon2id, TOTP, WebAuthn, sessions, rate limiter, audit
|
||||
│ │ ├── db/ # SQLite connection, migrations, retention/rollup jobs
|
||||
│ │ ├── ssh/ # ConnectionPool, ProxyJump, KnownHosts (TOFU), KeyManager (rotation), sudo helper, PTYManager, SFTP, Tunnels & HTTP Proxy
|
||||
│ │ ├── monitoring/ # OS detector, Linux/BSD/macOS collectors, multi-mount disks, on-demand Server Inspector, HTTP/TCP probes
|
||||
│ │ ├── systems/ # Custom Systems loader, TTL cache, discovery, multi-file overlays, status, actions, presets (docker-compose, systemd, os-packages)
|
||||
│ │ ├── automation/ # Cron scheduler, pipeline runner, safe env-var quoting, dry-run preview, snippets, fleet broadcast, transfer engine
|
||||
│ │ ├── alerts/ # Threshold/offline/probe/system evaluator, maintenance windows, snoozing, cooldowns, webhook dispatchers
|
||||
│ │ ├── ai/ # Optional OpenAI v1 client, secret redactor, and per-surface context guides (workflows, systems, snippets, logs, setup)
|
||||
│ │ └── api/ # Express routes, /proxy/:tunnelId reverse proxy, multiplexed WS hub
|
||||
│ └── client/
|
||||
│ ├── index.html # Shell layout + PWA manifest link
|
||||
│ ├── manifest.json # Minimal PWA manifest & sharp terminal icons
|
||||
│ ├── css/ # Flat sharp base styles + theme variable sheets
|
||||
│ ├── ts/ # Modular vanilla TS views (dashboard, inspector, systems/, terminal, keys, sftp, workflows, snippets, alerts, config)
|
||||
│ └── build.ts # esbuild bundler (ES2019/ES2020 target + code-split xterm.js)
|
||||
├── data/ # Runtime persistent volume (gitignored)
|
||||
│ ├── config/
|
||||
│ │ ├── servers/ # One JSON file per server (<server-id>.json)
|
||||
│ │ ├── workflows/ # One JSON file per workflow (<workflow-id>.json)
|
||||
│ │ ├── systems/ # One JSON file per custom system (docker-compose.json, systemd.json, os-packages.json, custom)
|
||||
│ │ ├── snippets.json # Reusable one-tap Command Snippets
|
||||
│ │ ├── alerts.json # Threshold, offline, probe, system & maintenance window rules
|
||||
│ │ └── settings.json # Global UI, retention, SSH defaults, tunnel proxy settings
|
||||
│ ├── vault.enc # Encrypted SSH keys, passphrases, passwords, sudo secrets, webhook tokens
|
||||
│ └── gcoord.db # SQLite database (WAL)
|
||||
├── package.json
|
||||
└── tsconfig.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Security & Credential Architecture
|
||||
|
||||
### Split Config & Encrypted Vault
|
||||
|
||||
- **Plain Configs, Secret References**: Human-editable JSON files under `/data/config/` store server definitions, workflows, snippets, systems, and alert rules. Secrets are never stored in plain JSON—entries reference a `credentialId` (SSH auth), `sudoCredentialId` (optional sudo password), or `secretRef` (webhook URLs/tokens).
|
||||
- **AES-256-GCM Vault (`/data/vault.enc`)**: Stores SSH private keys, key passphrases, SSH passwords, sudo passwords, and webhook tokens as a single authenticated JSON payload encrypted with `AES-256-GCM`. Every write generates a fresh 96-bit random IV and writes atomically (`vault.enc.tmp` -> `fsync` -> `rename`). Reads verify the GCM authentication tag before decrypting.
|
||||
- **Unattended Startup Unlock**: Unlocked at boot using a 32-byte server-side master key supplied via Docker secret (`/run/secrets/gcoord_master_key`) or `GCOORD_MASTER_KEY` environment variable, allowing unattended monitoring, probes, cron tasks, and alerts to survive container restarts.
|
||||
- **Master Key Rotation**: Dedicated CLI command (`gcoord rotate-key`) and step-up TOTP UI flow to re-encrypt `vault.enc` atomically under a newly generated 32-byte master key, verifying decryption before replacing the file.
|
||||
- **Emergency Panic Lock**: Accessible from Settings and header quick-menu (with confirmation). Immediately wipes the in-memory master key and decrypted vault, closes every active SSH connection, PTY session, and port-forward tunnel, pauses background pollers/workflows, and revokes all active auth sessions until unlocked again.
|
||||
|
||||
### Single-Admin Authentication, MFA & Mobile Safety
|
||||
|
||||
- **First-Run Bootstrap**: When no admin record exists in SQLite, a one-time setup flow sets the admin password (hashed with **Argon2id**) and enforces **TOTP 2FA** enrollment (QR code + single-use hashed recovery codes).
|
||||
- **Universal Compatibility + Optional Passkeys**: TOTP works reliably on every browser including legacy mobile devices (Galaxy J7). **WebAuthn/Passkeys** (`@simplewebauthn/server`) can be optionally enrolled for one-tap login on modern devices without locking out older ones.
|
||||
- **Session Hardening**:
|
||||
- Random 256-bit session tokens stored hashed in SQLite (`sessions` table).
|
||||
- Cookies set with `HttpOnly`, `Secure` (when behind HTTPS/`cloudflared`), `SameSite=Strict`.
|
||||
- Active sessions view in Settings with per-session and one-click "Revoke All Sessions" controls.
|
||||
- **Mobile Safe / Read-Only Mode Toggle**: A persistent toggle in the top bar (enabled per-client or per-session, optional default-on for mobile viewports) that blocks all mutating/destructive API calls and UI controls (`down`, `prune`, reboot, SFTP writes/deletes, key revocation, workflow runs) so you can safely monitor dashboards and read logs on a small touchscreen without accidental taps.
|
||||
- **Defense in Depth**:
|
||||
- Exponential-backoff rate limiting on auth/MFA endpoints, reading `CF-Connecting-IP` only when `TRUST_CLOUDFLARE=true`.
|
||||
- CSRF token validation on state-mutating API requests.
|
||||
- **Step-up TOTP verification** required before viewing/exporting/modifying vault credentials, rotating/revoking SSH keys, rotating the master key, or approving a host key mismatch.
|
||||
- Append-only `audit_log` in SQLite recording logins, failed MFA attempts, vault edits, key rotations, SSH session opens, SFTP writes, tunnel starts, and workflow executions.
|
||||
|
||||
### Strict SSH Host Key Verification (TOFU)
|
||||
|
||||
- First connection to a server records its host key fingerprint (`SHA-256`) in `known_hosts` only after explicit admin confirmation via an interactive TOFU prompt in the UI (or pre-seeded fingerprint in the server's JSON file).
|
||||
- Any subsequent fingerprint mismatch **immediately blocks the connection** (including background monitoring, probes, and workflows) and surfaces a prominent MITM security alert until the admin manually inspects and resets the host key with step-up verification.
|
||||
|
||||
---
|
||||
|
||||
## 5. Configuration & Persistence Model
|
||||
|
||||
### Modular JSON Configs (`/data/config/`)
|
||||
|
||||
| Path | Responsibility |
|
||||
| :--- | :--- |
|
||||
| `servers/<server-id>.json` | **One file per server**: `id`, `name`, `host`, `port`, `username`, `credentialId`, optional `jumpHostId` (bastion chaining), optional `sudoCredentialId`, `tags`, `osHint` (`auto`/`linux`/`bsd`/`macos`), `pollIntervalSec`, `diskMountFilter`, `probes[]` (optional HTTP/TCP endpoint checks), `systems[]` (attached custom systems with server-specific `params` and `itemOverrides` including ordered `activeFiles[]`), `enabled`. |
|
||||
| `workflows/<workflow-id>.json` | **One file per workflow**: `id`, `name`, `description`, `trigger` (`manual`, `cron`, or `event`), optional `scope` (`{ serverId, systemId, item }`), `inputs[]`, `concurrency`, `overlapPolicy` (`skip` \| `queue` \| `cancel-previous`), `display` (`log`, `file-view`, `json`, `table`, `summary`), `pinToDashboard`, `steps[]` (each with optional `timeoutSec` and `sudo: boolean`). |
|
||||
| `systems/<system-id>.json` | **One file per custom system**: `id`, `name`, `params[]`, `discovery` (`folder-scan` with optional `selectableFiles` patterns or `command`), `cacheTtlSec`, optional `backgroundCheckSec`, `status` (yielding item + optional `subItems`), `actions[]` (`scope`: `system` \| `item` \| `subitem`, `mode`: `oneshot` \| `stream` \| `interactive`, optional `sudo: true`, `confirm: true`), and `editableFiles[]`. Seeds editable presets: `docker-compose.json`, `systemd.json`, and `os-packages.json`. |
|
||||
| `snippets.json` | Reusable one-tap **Command Snippets** (`id`, `name`, `command`, `tags`, optional `inputs[]`, `sudo`, `confirm`) callable from the Terminal tab or Ad-Hoc Fleet Broadcast. |
|
||||
| `alerts.json` | Threshold (CPU/RAM/load/per-mount disk), offline, endpoint-probe, and system-item health rules; cooldown/hysteresis durations; scheduled `maintenanceWindows[]`; webhook channels (`discord`, `telegram`, `ntfy`, `generic`); and optional `remediationWorkflowId`. |
|
||||
| `settings.json` | Default UI theme, metric retention (`rawRetentionHours`, `rollupRetentionDays`), config revision retention count, terminal scrollback limit, global SSH timeouts/keepalives, default Safe-Mode preference on mobile, and optional `ai` config (`enabled`, `baseUrl`, `model`, `secretRef`, `maxContextChars`). |
|
||||
|
||||
#### Sync, Hot-Reload & Revision History Guarantees
|
||||
1. **Zod Validation**: Every config file is validated against strict Zod schemas on startup, on UI save, and on disk change (cross-checking filename `<id>.json` against internal `id`).
|
||||
2. **Atomic Writes**: UI edits serialize formatted JSON (`2`-space indent) to `<file>.tmp`, `fsync`, and atomically `rename` over the target.
|
||||
3. **Recursive Debounced Watch (`chokidar`)**: Direct edits, additions, or deletions under `/data/config/` trigger a 300ms debounced reload (ignoring self-writes via hash/mtime tracking).
|
||||
4. **Isolated Safe Fallback**: Because servers, workflows, and custom systems each live in their own file, a syntax or schema typo in one file **only preserves that single entity's last valid config** in memory and flags it in the UI—every other server, workflow, and system keeps running unaffected.
|
||||
5. **Automatic Config Revision History & Rollback**: Every validated UI save or disk change snapshots the previous version into SQLite (`config_revisions`, capped per file by `settings.json`). The Config UI provides a lightweight side-by-side/unified text diff and **1-click rollback** to any prior revision.
|
||||
|
||||
#### Illustrative `/data/config/servers/prod-web-01.json`
|
||||
```json
|
||||
{
|
||||
"id": "prod-web-01",
|
||||
"name": "Prod Web 01",
|
||||
"host": "10.10.0.12",
|
||||
"port": 22,
|
||||
"username": "ops",
|
||||
"credentialId": "cred-ed25519-main",
|
||||
"jumpHostId": "bastion-01",
|
||||
"sudoCredentialId": "sudo-prod-ops",
|
||||
"tags": ["prod", "web"],
|
||||
"osHint": "auto",
|
||||
"pollIntervalSec": 10,
|
||||
"probes": [
|
||||
{ "id": "nginx-https", "type": "http", "url": "http://127.0.0.1:8080/healthz", "from": "target", "intervalSec": 30, "expectedStatus": 200 }
|
||||
],
|
||||
"systems": [
|
||||
{
|
||||
"systemId": "docker-compose",
|
||||
"params": { "rootDirs": ["~/Services"] },
|
||||
"itemOverrides": {
|
||||
"myapp": { "activeFiles": ["compose.yml", "compose.prod.yml"] }
|
||||
}
|
||||
},
|
||||
{
|
||||
"systemId": "systemd",
|
||||
"params": { "unitFilter": "nginx|postgresql|caddy" }
|
||||
}
|
||||
],
|
||||
"enabled": true
|
||||
}
|
||||
```
|
||||
*(Another server JSON can attach `"systemId": "docker-compose"` with `"params": { "rootDirs": ["~/Documents"] }`—both use the same system definition, while `itemOverrides.<item>.activeFiles` supports either a single file or ordered overlay files.)*
|
||||
|
||||
#### Illustrative `/data/config/systems/docker-compose.json` (Built-in Editable Preset)
|
||||
```json
|
||||
{
|
||||
"id": "docker-compose",
|
||||
"name": "Docker Compose Stacks",
|
||||
"cacheTtlSec": 45,
|
||||
"params": [
|
||||
{ "name": "rootDirs", "type": "string[]", "default": ["~/Services"], "required": true }
|
||||
],
|
||||
"discovery": {
|
||||
"type": "folder-scan",
|
||||
"rootsParam": "rootDirs",
|
||||
"matchFiles": ["compose.yml", "compose.yaml", "docker-compose.yml", "docker-compose.yaml"],
|
||||
"selectableFiles": ["*compose*.yml", "*compose*.yaml"]
|
||||
},
|
||||
"status": {
|
||||
"command": "docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES ps --all --format json",
|
||||
"parser": "json-lines",
|
||||
"subItemField": "Service"
|
||||
},
|
||||
"actions": [
|
||||
{ "id": "up", "label": "Run", "scope": "item", "mode": "oneshot", "command": "docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES up -d" },
|
||||
{ "id": "down", "label": "Shut Down", "scope": "item", "mode": "oneshot", "confirm": true, "command": "docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES down" },
|
||||
{ "id": "restart", "label": "Restart", "scope": "item", "mode": "oneshot", "command": "docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES restart" },
|
||||
{ "id": "rebuild", "label": "Rebuild", "scope": "item", "mode": "stream", "command": "docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES up -d --build --force-recreate" },
|
||||
{ "id": "update", "label": "Pull & Update", "scope": "item", "mode": "stream", "command": "docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES pull && docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES up -d" },
|
||||
{ "id": "logs", "label": "Logs", "scope": "item", "mode": "stream", "command": "docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES logs -f --tail 100" },
|
||||
{ "id": "debug-shell", "label": "Debug Shell", "scope": "subitem", "mode": "interactive", "command": "docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES exec \"$GCOORD_SUBITEM\" sh -c 'command -v bash >/dev/null && exec bash || exec sh'" },
|
||||
{ "id": "inspect", "label": "Inspect", "scope": "subitem", "mode": "oneshot", "command": "docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES ps \"$GCOORD_SUBITEM\" --format json && docker inspect \"$(docker compose --project-directory \"$GCOORD_ITEM_DIR\" $GCOORD_COMPOSE_FILES ps -q \"$GCOORD_SUBITEM\")\"" },
|
||||
{ "id": "prune", "label": "Prune Host", "scope": "system", "mode": "stream", "confirm": true, "command": "docker system prune -f" }
|
||||
],
|
||||
"editableFiles": ["*compose*.yml", "*compose*.yaml", ".env"]
|
||||
}
|
||||
```
|
||||
*(For multi-file overlays, GCoordinator builds safely shell-quoted `-f` arguments into `$GCOORD_COMPOSE_FILES` or passes individual file paths via `GCOORD_ITEM_FILE` / `GCOORD_ITEM_FILES`.)*
|
||||
|
||||
#### Illustrative `/data/config/workflows/nightly-db-backup.json`
|
||||
```json
|
||||
{
|
||||
"id": "nightly-db-backup",
|
||||
"name": "Nightly DB Dump & Sync",
|
||||
"trigger": { "type": "cron", "expression": "0 3 * * *", "timezone": "UTC" },
|
||||
"overlapPolicy": "skip",
|
||||
"display": { "mode": "summary" },
|
||||
"steps": [
|
||||
{
|
||||
"id": "dump",
|
||||
"type": "exec",
|
||||
"target": { "serverId": "db-01" },
|
||||
"command": "/usr/local/bin/make-backup.sh",
|
||||
"timeoutSec": 600,
|
||||
"captureAs": "dumpPath",
|
||||
"onFailure": "notify-backup-failed"
|
||||
},
|
||||
{
|
||||
"id": "copy-offsite",
|
||||
"type": "transfer",
|
||||
"mode": "hub-relayed",
|
||||
"source": { "serverId": "db-01", "path": "{{steps.dump.stdout}}" },
|
||||
"destination": { "serverId": "storage-01", "path": "/backups/db/" }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Illustrative `/data/config/workflows/inspect-nginx-errors.json` & Fleet Update
|
||||
```json
|
||||
{
|
||||
"id": "inspect-nginx-errors",
|
||||
"name": "Read Nginx Error Log",
|
||||
"trigger": { "type": "manual" },
|
||||
"inputs": [
|
||||
{ "name": "serverId", "type": "server", "label": "Target Server", "required": true },
|
||||
{ "name": "lines", "type": "number", "label": "Tail Lines", "default": 100 }
|
||||
],
|
||||
"display": { "mode": "file-view", "syntax": "log", "pinToDashboard": true },
|
||||
"steps": [
|
||||
{
|
||||
"id": "read",
|
||||
"type": "read-file",
|
||||
"target": { "serverId": "{{inputs.serverId}}" },
|
||||
"path": "/var/log/nginx/error.log",
|
||||
"tailLines": "{{inputs.lines}}",
|
||||
"sudo": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
```json
|
||||
{
|
||||
"id": "update-all-compose-stacks",
|
||||
"name": "Update All Compose Services (Fleet)",
|
||||
"trigger": { "type": "manual" },
|
||||
"overlapPolicy": "skip",
|
||||
"display": { "mode": "table" },
|
||||
"steps": [
|
||||
{
|
||||
"id": "pull-and-up",
|
||||
"type": "system-action",
|
||||
"target": { "all": true },
|
||||
"concurrency": 2,
|
||||
"timeoutSec": 300,
|
||||
"systemId": "docker-compose",
|
||||
"action": "update",
|
||||
"item": "*"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### SQLite Database (`/data/gcoord.db`, WAL Mode)
|
||||
|
||||
| Table | Purpose |
|
||||
| :--- | :--- |
|
||||
| `metrics_raw` | Recent per-server samples (`ts`, `server_id`, `cpu_pct`, `mem_used_mb`, `mem_total_mb`, `net_rx_bps`, `net_tx_bps`, `load_1m`, `uptime_sec`). |
|
||||
| `metrics_disks` | Multi-mount disk snapshots (`ts`, `server_id`, `mount_point`, `fs_type`, `used_mb`, `total_mb`, `used_pct`) for all non-virtual filesystems. |
|
||||
| `metrics_rollup` | Hourly/daily aggregated (`min`, `avg`, `max`) metrics retained for 7–30+ days (configurable). |
|
||||
| `probe_results` | HTTP/TCP endpoint health probe samples (`ts`, `server_id`, `probe_id`, `ok`, `status_code`, `latency_ms`, `error`). |
|
||||
| `workflow_runs` | Execution records (`run_id`, `workflow_id`, `trigger_source`, `status`, `started_at`, `finished_at`, `cancelled_by`). |
|
||||
| `workflow_step_logs` | Per-step exit codes, target server, duration, and bounded stdout/stderr logs. |
|
||||
| `alert_events` | Triggered/resolved alert history, cooldown state, and webhook delivery status. |
|
||||
| `alert_silences` | Active one-tap snoozes/mutes (`scope_type`, `target_id`, `expires_at`, `reason`). |
|
||||
| `config_revisions` | Timestamped snapshots of prior JSON config files (`file_path`, `sha256`, `source`, `content`, `created_at`) for diff & 1-click rollback. |
|
||||
| `sessions` | Active admin session hashes, user-agent, IP, `created_at`, `last_seen_at`, `expires_at`. |
|
||||
| `webauthn_credentials` | Optional registered Passkey public keys and counters. |
|
||||
| `known_hosts` | Trusted SSH host key algorithms and SHA-256 fingerprints per `host:port`. |
|
||||
| `audit_log` | Immutable security/action audit trail. |
|
||||
|
||||
---
|
||||
|
||||
## 6. Core Subsystems
|
||||
|
||||
### 1. SSH Connection Pool, ProxyJump, Key Manager & Interactive Client
|
||||
- **Connection Pool & `ProxyJump` Bastion Chaining**:
|
||||
- Maintains one persistent multiplexed `ssh2` client per enabled server with TCP/SSH keepalives and exponential-backoff reconnection.
|
||||
- Servers specifying `jumpHostId` open a forwarded TCP stream through the bastion's pooled connection (`bastionClient.forwardOut(...)`) and negotiate SSH over that stream—supporting multi-hop chains with cycle detection and independent TOFU host key verification at every hop.
|
||||
- **Controlled `sudo` Execution**:
|
||||
- When a system action, workflow step, or file read sets `sudo: true`, GCoordinator runs with `sudo -n` if no `sudoCredentialId` is configured, or invokes `sudo -S -p ''` and writes the vaulted sudo password directly to stdin (never on the command line or in logs/history).
|
||||
- **Built-in SSH Key Manager & Per-Server Atomic Key Rotation**:
|
||||
- **Vault Key Generation**: Generate fresh `Ed25519` keypairs directly inside `vault.enc` (with optional passphrase) and export public keys.
|
||||
- **Per-Server Key Management Utility**: Dedicated **Keys** tab on each server page that parses `~/.ssh/authorized_keys`, displays key type/fingerprint/comment, highlights which key GCoordinator currently uses, lets you deploy a vaulted public key (`ssh-copy-id` equivalent with safe `0700`/`0600` permissions), or revoke/remove individual keys (requiring step-up TOTP).
|
||||
- **Atomic Zero-Lockout Key Rotation** (single server or tag/fleet):
|
||||
1. Generates a new `Ed25519` keypair in `vault.enc` (keeping the old key intact until rotation completes).
|
||||
2. Appends the new public key to target server(s)' `~/.ssh/authorized_keys` atomically.
|
||||
3. Opens a fresh verification SSH connection authenticating strictly with the **new** key.
|
||||
4. On verified success, updates the server JSON's `credentialId` and removes/invalidates the old public key entry from `~/.ssh/authorized_keys`.
|
||||
5. On any failure before verification, automatically rolls back (removes the unverified key and keeps the old credential active) so admin lockout cannot occur.
|
||||
- **Server-Side Persistent PTY Sessions & Scrollback Export**:
|
||||
- Opening a terminal allocates a remote PTY managed by `PTYManager` on the GCoordinator server, backed by a bounded circular scrollback buffer (e.g., `500KB` per session).
|
||||
- If the browser tab closes or a mobile cellular connection drops, the remote shell stays alive. Reattaching replays the scrollback buffer and resumes live I/O seamlessly.
|
||||
- One-click **Export Scrollback** downloads the session buffer as plain text (ANSI-stripped) or raw ANSI log for incident notes.
|
||||
- Sessions can be explicitly closed or auto-reaped after an idle TTL configured in `settings.json`.
|
||||
- **Interactive Web Terminal**:
|
||||
- Multi-tab terminal view using code-split lazy-loaded `xterm.js` + `@xterm/addon-fit`.
|
||||
- Dedicated **mobile touch-key bar** (`Esc`, `Tab`, `Ctrl` sticky toggle, `Alt`, arrow keys, `|`, `/`, `~`, `-`), quick font-size `-`/`+` buttons, and a **Snippets Drawer** to insert or run saved one-tap commands directly in the active PTY.
|
||||
- **SFTP File Manager**:
|
||||
- Directory listing with permissions/sizes/timestamps, streaming upload & download, `mkdir`, rename, `chmod`, delete.
|
||||
- **"Open Terminal Here"**: Launches a PTY tab directly `cd`'d into the current SFTP directory.
|
||||
- **Streamed Directory Archive Download**: Downloads any remote folder as a streamed `.tar.zst` archive (using `tar --zstd` / `zstd` when available on the remote host) or `.tar.gz` (selectable or automatic fallback) without creating temporary archives on disk.
|
||||
- **Inline Plain-Text Editor with Pre-Save Diff**: Edit small config files in place with a pre-save unified diff confirmation modal before writing back atomically.
|
||||
- **Port Forwarding & Authenticated HTTP/WS Tunnel Proxy**:
|
||||
- **Authenticated Web Proxy Mode (Zero Exposed Ports)**: For remote web UIs (Grafana, Proxmox, Portainer, internal admin panels), GCoordinator opens an SSH local forward bound strictly to `127.0.0.1:<ephemeral>` inside the container and serves it at `/proxy/<tunnelId>/*` behind GCoordinator's own auth/MFA session over `cloudflared` (supporting both HTTP and WebSocket upgrades).
|
||||
- **Raw TCP Local (`L`) Tunnels (LAN/Tailscale Override)**: When running with `docker-compose.lan.yml`, bind local forwards to a configurable host port range for raw TCP protocols (Postgres, Redis, VNC, etc.).
|
||||
- **Remote (`R`) & Server-to-Server Tunnels**: Create, start, stop, and monitor active tunnels with live connection counters in the UI.
|
||||
|
||||
### 2. Agentless Monitoring, Server Inspector & Endpoint Probes
|
||||
- **OS Auto-Detection & Multi-Mount Disk Tracking**: On initial handshake, runs `uname -s` (cached per connection unless overridden by `osHint`) and dispatches to a collector implementing a unified `MetricSample` contract:
|
||||
- **`LinuxCollector`**: Single compound POSIX `sh` invocation reading `/proc/stat`, `/proc/meminfo`, `/proc/loadavg`, `/proc/uptime`, `/proc/net/dev`, and `df -PT` (filtering out virtual filesystems like `tmpfs`, `devtmpfs`, `overlay`, `squashfs` to track all real mounts in `metrics_disks`). Zero external dependencies; works on Debian, Ubuntu, RHEL, Arch, Alpine, Raspberry Pi, OpenWrt.
|
||||
- **`BSDCollector`**: Uses `sysctl`, `vmstat`, `netstat -ib`, and `df -kT` for FreeBSD/OpenBSD.
|
||||
- **`MacOSCollector`**: Uses `sysctl`, `vm_stat`, `top -l 1` / `iostat`, `netstat -ib`, and `df -k`.
|
||||
- **On-Demand Server Inspector (Zero Background Polling Overhead)**:
|
||||
- Only invoked when the admin opens a server's detail view (with manual refresh or short active-view polling):
|
||||
- Top-N processes sorted by CPU or RAM (`ps`).
|
||||
- Listening TCP/UDP ports and owning processes (`ss -tulnp` / `netstat` / `sockstat`).
|
||||
- Hardware/thermal sensors where available (`/sys/class/thermal`, `sensors`, `sysctl dev.cpu.*.temperature`).
|
||||
- **HTTP/TCP Endpoint Health Probes**:
|
||||
- Optional per-server `probes[]` execute periodic HTTP(S) (status code, optional body substring, latency) or TCP connect checks either directly from GCoordinator or from inside the target server over SSH (ideal for `127.0.0.1` or internal-network services).
|
||||
- Results are stored in `probe_results`, displayed as live badges on server cards, and evaluable by `AlertEngine`.
|
||||
- **Live Streaming & Retention**: Pushes live updates over the multiplexed WebSocket and batches inserts into `metrics_raw` / `metrics_disks`. A periodic maintenance job downsamples old data into `metrics_rollup` and prunes expired rows.
|
||||
|
||||
### 3. Custom Systems Engine (Extensible Service Managers)
|
||||
- **Dedicated Multi-Page Systems UI**: A top-level **Systems** section hosts a Systems Hub and a dedicated page for every defined system (e.g., `/systems/docker-compose`, `/systems/systemd`, `/systems/os-packages`, `/systems/game-servers`). Each system page lists all bound servers and discovered services, and clicking a service opens its full Service Detail view.
|
||||
- **Declarative System Definitions (`/data/config/systems/*.json`)**: Define any service or stack architecture once via JSON without writing backend code.
|
||||
- **Per-Server Parameter Binding**: Each server attaches whichever systems it runs with its own paths and options. Leading `~/` expands safely via `$HOME/` on the remote host, and all interpolated params, active files, and item paths are passed via safely quoted arguments or `GCOORD_*` environment variables (`$GCOORD_ITEM_DIR`, `$GCOORD_ITEM_FILE`, `$GCOORD_COMPOSE_FILES`, `$GCOORD_ITEM_NAME`, `$GCOORD_SUBITEM`) to prevent shell injection or word-splitting on paths with spaces.
|
||||
- **Multi-File Overlays per Service (`activeFiles[]`)**: When a service directory holds multiple matching config files (e.g., `compose.yml`, `compose.prod.yml`, `compose.gpu.yml` matched via `selectableFiles`), you can select one or an ordered list of overlay files directly from the service page. Selections persist in `itemOverrides.<service>.activeFiles` and inject safely into every status check and action.
|
||||
- **Smart Discovery & Status Caching + Alert Integration**:
|
||||
- Supports `folder-scan` or `command` discovery and pluggable status parsers (`json-lines`, `json`, `lines`, `regex`, `exit-code`) yielding item + `subItems`.
|
||||
- Caches discovery/status per `(serverId, systemId)` for `cacheTtlSec` (e.g., 30–60s) to keep mobile navigation snappy, instantly invalidates cache after any action executes, and provides a manual Refresh button.
|
||||
- Optional `backgroundCheckSec` allows periodic background status polling so `AlertEngine` can fire alerts when a tracked Compose container or `systemd` unit enters a failed/stopped state.
|
||||
- **Three Action Scopes & Three Execution Modes**:
|
||||
- **Scopes**: `system` (host-wide ops like `docker system prune -f` or `apt upgrade`), `item` (service-level ops), and `subitem` (individual container/unit actions like `debug-shell`, `inspect`, `logs`, `restart`).
|
||||
- **Modes**: `oneshot`, `stream` (live WebSocket output tailing), and `interactive` (launches a persistent PTY session in the Terminal tab).
|
||||
- Supports `sudo: true`, `confirm: true`, and `editableFiles[]` shortcuts opening directly in the SFTP inline editor.
|
||||
- **Per-Service Tasks & Cron Jobs**: Each service's detail page includes a **Tasks & Cron** tab displaying workflows scoped to `(serverId, systemId, item)` and letting you create, edit, schedule, or trigger service-specific jobs in place.
|
||||
- **Built-In Editable Starter Presets**: First-run seeds three editable files under `/data/config/systems/`:
|
||||
1. `docker-compose.json` — run, shut down, restart, rebuild, pull & update, prune host, live logs, container inspect & interactive debug shell, multi-file overlays, and `.env`/compose quick-edit.
|
||||
2. `systemd.json` — discover filtered/active units, start/stop/restart/reload/enable/disable (`sudo: true`), live `journalctl -f` streaming, and drop-in override editing.
|
||||
3. `os-packages.json` — auto-detects `apt`, `dnf`, `apk`, or `pacman` to list upgradable packages, check reboot-required status, and run streamed upgrades with confirmation.
|
||||
|
||||
### 4. Automation, Pipelines, Snippets & Cross-Server File Transfers
|
||||
- **Flexible Targeting & Dry-Run Preview**:
|
||||
- Every step or workflow can target a single server (`serverId`), a tag group (`tags: ["prod"]`), or the entire fleet (`all: true`) with configurable rolling `concurrency` and `stopOnError`.
|
||||
- **Fleet Dry-Run Preview**: Before running a multi-server workflow, the UI can preview the resolved target servers, discovered system items, and rendered commands before confirming execution.
|
||||
- **Safe Execution Semantics**:
|
||||
- **No Raw Shell Injection**: `{{inputs.*}}` and `{{steps.*.stdout}}` values are injected via `GCOORD_INPUT_<NAME>` / `GCOORD_STEP_<ID>_STDOUT` environment variables or strict POSIX single-quote escaping when interpolated into arguments.
|
||||
- **Timeouts, Overlap Policy & Cancellation**: Per-step `timeoutSec`, workflow-level `overlapPolicy` (`skip` | `queue` | `cancel-previous`), and live **Cancel Run** support that cleanly terminates in-flight SSH channels.
|
||||
- **Rich Step Types**:
|
||||
- `exec`: Run shell commands/scripts (with optional `sudo: true`) and capture `stdout`, `stderr`, and `exitCode`.
|
||||
- `read-file`: Fetch a full file or trailing `N` lines via SFTP/SSH without custom shell boilerplate.
|
||||
- `system-action`: Invoke any action defined on any custom system (`systemId`, `action`, and `item` name or `*`), respecting each server's bound paths and overlays.
|
||||
- `transfer`: **`hub-relayed` mode** (streams Server A SFTP -> GCoordinator -> Server B SFTP with zero server-to-server keys/routing needed) or **`direct` mode** (`rsync` when servers have direct connectivity).
|
||||
- **Saved Command Snippets & Ad-Hoc Fleet Broadcast**:
|
||||
- `/data/config/snippets.json` stores reusable one-tap commands (with optional `{{var}}` inputs).
|
||||
- Trigger any snippet inside an active Terminal PTY tab, or open **Ad-Hoc Fleet Broadcast** to run a snippet or one-off command across selected servers/tags with live per-server output cards and exit-code badges.
|
||||
- **Output Presentation & Dashboard Widgets**:
|
||||
- Workflows declare a `display.mode` (`log`, `file-view`, `json`, `table`, `summary`).
|
||||
- Workflows with `pinToDashboard: true` pin directly to the main dashboard or server cards for one-tap refresh and display.
|
||||
|
||||
### 5. Event-Driven Triggers & Alerting
|
||||
- Evaluates incoming `MetricSample` updates (including per-mount `metrics_disks`), server online/offline state, `probe_results`, and optional background Custom System health checks against rules in `alerts.json`.
|
||||
- Supports **for-duration / hysteresis** (e.g., CPU > 90% for 3 consecutive polls) and **cooldowns** to prevent alert storms.
|
||||
- **Maintenance Windows & One-Tap Snoozing**:
|
||||
- Define recurring scheduled quiet windows in `alerts.json` (e.g., Sunday 03:00–04:00 UTC for automated updates/reboots).
|
||||
- One-tap **Mute / Snooze** (`30m`, `2h`, `12h`, or custom) per server, tag, or alert rule stored in `alert_silences`.
|
||||
- Dispatches formatted alerts (and recovery notices) to **Discord**, **Telegram**, **ntfy**, or generic JSON webhooks (secrets in `vault.enc`), with a **"Send Test Alert"** button per configured channel.
|
||||
- Can automatically trigger a configured remediation workflow (`remediationWorkflowId`) on firing.
|
||||
|
||||
### 6. Optional BYO-API AI Assistant (Context-Aware)
|
||||
- **Strictly Opt-In & Endpoint-Agnostic**:
|
||||
- Disabled by default (zero AI UI clutter or outbound requests when off).
|
||||
- Connects to any **OpenAI-compatible `v1` endpoint** (`POST <baseUrl>/v1/chat/completions` with streaming SSE) configured in `settings.json`, supporting cloud providers (OpenAI, OpenRouter, etc.) as well as 100% self-hosted local LLMs (Ollama, `llama.cpp`, vLLM, LM Studio) to preserve zero third-party trust.
|
||||
- API key is stored exclusively in `vault.enc` via `secretRef` (optional/empty for local endpoints).
|
||||
- **Context-Specific Built-In Guides**:
|
||||
- Rather than a generic chatbox, the assistant loads a tailored **system guide + schema reference + sanitized local context** based on where it is invoked:
|
||||
- **Workflows Editor**: Receives the `workflows/*.json` schema, step types (`exec`, `read-file`, `system-action`, `transfer`), safe `{{inputs.*}}`/`{{steps.*}}` rules, and available server IDs/tags/systems to draft valid workflow JSON (validated via Zod before offering a 1-click diff/Apply).
|
||||
- **Custom Systems Editor**: Receives the `systems/*.json` schema, `$GCOORD_*` env-var conventions, `activeFiles[]`, discovery types, and status parsers to help author new custom systems (e.g., Podman, PM2, game servers).
|
||||
- **Snippets & Terminal**: Receives `snippets.json` schema, target server OS (`uname -s`), and optional selected terminal scrollback to generate one-tap commands/snippets or explain CLI errors.
|
||||
- **Log & Alert Debugger** (Workflow run logs, streamed system logs, alert events): Receives a bounded tail of the failing log, exit code, server OS, and service context to diagnose root causes and suggest remediation steps.
|
||||
- **Setup & Config Helper** (Servers, Probes, `alerts.json`, `ProxyJump`): Receives the relevant config schema and sanitized server inventory to help configure jump hosts, health probes, or alert thresholds.
|
||||
- **Security, Privacy & Mobile Guardrails**:
|
||||
- **Zero Auto-Execution**: All generated configs, snippets, and commands are strictly drafts requiring explicit review and confirmation (and respect **Safe / Read-Only Mode**).
|
||||
- **Automatic Secret Redaction + Context Preview**: Before sending any payload, a built-in scrubber strips private key blocks, `Authorization`/`Bearer` headers, `.env`-style secret assignments, and known vault values, and displays a compact toggleable preview of the attached context.
|
||||
- **Lightweight Streaming**: Streams tokens over the existing multiplexed `/ws` channel (`ai:<chatId>`) into a minimal monospace drawer with zero heavy markdown/highlighter bundles.
|
||||
|
||||
---
|
||||
|
||||
## 7. Real-Time Protocol, UI / UX & Galaxy J7 Performance Strategy
|
||||
|
||||
### Multiplexed Single-WebSocket Protocol (`/ws`)
|
||||
- Every client maintains **one** authenticated WebSocket connection multiplexed by JSON/binary frames across channels:
|
||||
- `metrics` (live dashboard/server telemetry ticks)
|
||||
- `pty:<sessionId>` (low-latency terminal I/O and resize events)
|
||||
- `stream:<jobId>` (live workflow, system action, or fleet broadcast logs)
|
||||
- `ai:<chatId>` (optional streaming BYO-API assistant responses)
|
||||
- `alerts` & `config` (live alert badges, host-key MITM warnings, config hot-reload notifications)
|
||||
- **Flaky Mobile Resilience**: Periodic ping/pong heartbeat, exponential-backoff auto-reconnect, automatic channel re-subscription + PTY scrollback replay on reconnect, and a crisp top connection-status banner (`[ONLINE]` / `[RECONNECTING...]`) so mobile cellular handoffs never leave stale UI state.
|
||||
|
||||
### Visual Design & Galaxy J7 Optimizations
|
||||
- **Visual Design**: Sharp terminal aesthetic—`border-radius: 0`, crisp `1px` solid borders, monospace typography for data/logs, clear status badges (`[OK]`, `[WARN]`, `[DOWN]`, `[SAFE]`), zero gradients, zero bevels, zero `box-shadow` blur, zero `backdrop-filter`.
|
||||
- **Navigation Structure**: Clean top-level sections (`Dashboard`, `Systems`, `Terminal`, `SFTP`, `Workflows`, `Alerts`, `Config / Vault`) with single-tap routing, header **Safe Mode** toggle, and zero nested drawer clutter.
|
||||
- **Theme System**: Eye-friendly themes via CSS custom properties (`data-theme="..."`): `phosphor-green`, `amber-term`, `nord-dark`, `gruvbox-dark`, and `paper-light`.
|
||||
- **Galaxy J7 / Legacy Mobile Optimizations**:
|
||||
- Zero frontend framework (`React`/`Vue` avoided completely); bundled via `esbuild` targeting `es2019`/`es2020` to minimize HTTP requests and keep initial core payload `<50KB` gzipped.
|
||||
- Minimal **PWA `manifest.json`** (no heavy offline cache bloat) for Add-to-Home-Screen full-screen launch, reclaiming vertical browser chrome on small screens.
|
||||
- Minimal DOM mutations: update text/attribute nodes in place on WebSocket ticks instead of re-rendering whole tables.
|
||||
- Code-split lazy-load `xterm.js` and its addons only when a terminal tab is opened.
|
||||
- Lightweight Canvas/SVG sparklines with capped data points (`<=60` visible points on mobile).
|
||||
- Responsive single-column card layout at `<768px` with large tap targets (`>=44px` height) and a sticky bottom/top mobile navigation bar.
|
||||
|
||||
---
|
||||
|
||||
## 8. Docker, Break-Glass LAN & Portable Backup Strategy
|
||||
|
||||
### Default Deployment (`docker/docker-compose.yml` — Zero Exposed Ports)
|
||||
|
||||
```yaml
|
||||
services:
|
||||
gcoordinator:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
container_name: gcoordinator
|
||||
restart: unless-stopped
|
||||
user: "1000:1000"
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- PORT=3000
|
||||
- TRUST_CLOUDFLARE=true
|
||||
secrets:
|
||||
- gcoord_master_key
|
||||
volumes:
|
||||
- ../data:/data
|
||||
networks:
|
||||
- gcoord-internal
|
||||
# No ports exposed to host
|
||||
|
||||
cloudflared:
|
||||
image: cloudflare/cloudflared:latest
|
||||
container_name: gcoordinator-tunnel
|
||||
restart: unless-stopped
|
||||
command: tunnel --no-autoupdate run
|
||||
environment:
|
||||
- TUNNEL_TOKEN=${CLOUDFLARED_TUNNEL_TOKEN}
|
||||
depends_on:
|
||||
- gcoordinator
|
||||
networks:
|
||||
- gcoord-internal
|
||||
|
||||
networks:
|
||||
gcoord-internal:
|
||||
driver: bridge
|
||||
|
||||
secrets:
|
||||
gcoord_master_key:
|
||||
file: ./secrets/gcoord_master_key.txt
|
||||
```
|
||||
|
||||
### Optional Break-Glass LAN / Tailscale Override (`docker/docker-compose.lan.yml`)
|
||||
- Run via `docker compose -f docker-compose.yml -f docker-compose.lan.yml up -d` when you need:
|
||||
- Direct LAN or Tailscale break-glass access to the Web UI if Cloudflare Tunnel or WAN is down (binds `${GCOORD_LAN_BIND:-127.0.0.1}:3000:3000` with `TRUST_CLOUDFLARE=false` on the LAN listener).
|
||||
- An optional host port range (e.g., `${GCOORD_LAN_BIND:-127.0.0.1}:20000-20020:20000-20020`) for raw TCP Local (`L`) SSH port forwards.
|
||||
|
||||
### Portable Encrypted Backup & CLI Recovery (`gcoord` CLI)
|
||||
- **Portable Bundle (`.gcoord.enc`)**: Packages `/data/config/`, `vault.enc`, `known_hosts`, and optional DB metadata into a single `AES-256-GCM` authenticated archive encrypted with the master key (or a separate backup passphrase).
|
||||
- **CLI Utilities**:
|
||||
- `gcoord backup --out <path.gcoord.enc>` — creates a verified portable snapshot (also triggerable from the UI or as a scheduled self-backup workflow synced offsite via `transfer`).
|
||||
- `gcoord verify-backup <path.gcoord.enc>` — validates GCM authentication tag, JSON schemas, and vault integrity without modifying `/data`.
|
||||
- `gcoord restore <path.gcoord.enc>` — atomically restores `/data/config/`, `vault.enc`, and `known_hosts`.
|
||||
- `gcoord rotate-key` — safely rotates the 32-byte master key and re-encrypts `vault.enc`.
|
||||
- Store `gcoord_master_key` separately in a password manager so encrypted backups remain recoverable without exposing secrets alongside data.
|
||||
|
||||
---
|
||||
|
||||
## 9. Phased Implementation Roadmap
|
||||
|
||||
### Phase 1 — Foundation, Security & Config Core
|
||||
- [ ] Initialize TypeScript + Express + `ws` + `better-sqlite3` + `esbuild` project structure and build scripts.
|
||||
- [ ] Build `Dockerfile` (multi-stage, non-root, read-only rootfs), `docker-compose.yml` (`cloudflared` sidecar), and optional `docker-compose.lan.yml` break-glass/raw-TCP override.
|
||||
- [ ] Implement AES-256-GCM `VaultService` (`vault.enc`), master-key rotation, and Emergency **Panic Lock**.
|
||||
- [ ] Implement single-admin bootstrap, Argon2id password auth, TOTP 2FA + recovery codes, SQLite sessions, rate limiter, CSRF guard, Mobile **Safe / Read-Only Mode** guard, and `audit_log`.
|
||||
- [ ] Implement `ConfigManager` with Zod schemas, atomic writes, recursive `chokidar` hot-reload, per-file isolated fallback, and `config_revisions` diff + 1-click rollback.
|
||||
- [ ] Build the sharp, flat, multi-theme vanilla UI shell (with PWA `manifest.json`, multiplexed `/ws` client with auto-reconnect banner, login/bootstrap, settings/vault manager, JSON config editor + revision diff).
|
||||
|
||||
### Phase 2 — SSH Pool, ProxyJump, Key Lifecycle & Live Monitoring
|
||||
- [ ] Implement `SSHPool` (`ssh2` multiplexing, `ProxyJump` bastion chaining via `forwardOut`, keepalives, reconnect backoff), controlled `sudo` stdin helper, and strict TOFU `KnownHostsService` with UI verification prompt & MITM block banner.
|
||||
- [ ] Implement **SSH Key Manager**: Ed25519 keypair generation in vault, per-server `authorized_keys` inspector/deploy/revoke UI, and **atomic zero-lockout key rotation** (single server or fleet).
|
||||
- [ ] Implement OS auto-detection (`uname -s`), `LinuxCollector`, `BSDCollector`, `MacOSCollector` with multi-mount `metrics_disks` tracking, on-demand **Server Inspector** (top processes, listening ports, temps), and **HTTP/TCP Endpoint Health Probes**.
|
||||
- [ ] Stream live metrics over multiplexed WebSocket; store samples in `metrics_raw`/`metrics_disks`/`probe_results` with scheduled `metrics_rollup` and pruning.
|
||||
- [ ] Build server registration UI, live dashboard cards/table, Server Inspector view, and lightweight SVG/Canvas history charts.
|
||||
|
||||
### Phase 3 — Daily-Driver SSH Client, Tunnel Proxy & Custom Systems Engine
|
||||
- [ ] Implement server-side `PTYManager` with circular scrollback buffers, disconnect/reattach lifecycle, and plain-text/ANSI scrollback export.
|
||||
- [ ] Build multi-tab code-split lazy-loaded `xterm.js` terminal view with mobile touch-key bar, font/resize controls, and Snippets drawer.
|
||||
- [ ] Build SFTP file manager (browse, upload/download, "Open Terminal Here", streamed `.tar.zst`/`.tar.gz` folder download, inline editor with pre-save diff confirmation, `chmod`/rename/delete).
|
||||
- [ ] Build Port Forwarding UI supporting **Authenticated HTTP/WS Reverse Proxy** (`/proxy/<tunnelId>/*` over `cloudflared`), optional LAN/Tailscale raw TCP local binds, and Remote (`R`) tunnels.
|
||||
- [ ] Implement `CustomSystemsEngine`: declarative `systems/*.json` loader, per-server param binding, `activeFiles[]` multi-file overlays, TTL discovery/status cache with instant post-action invalidation and optional background health checks, `subItems` parsing, `system`/`item`/`subitem` scopes, `oneshot`/`stream`/`interactive` modes, and `sudo: true` support.
|
||||
- [ ] Build the dedicated multi-page **Systems** UI and seed editable built-in presets: `docker-compose.json`, `systemd.json`, and `os-packages.json`.
|
||||
|
||||
### Phase 4 — Automation, Snippets, Pipelines & Alerting
|
||||
- [ ] Implement `WorkflowEngine` with `croner` + manual triggers, `serverId`/`tags`/`all: true` fleet targeting, rolling concurrency, `overlapPolicy`, per-step `timeoutSec`, live run cancellation, safe env-var/quoted template injection, **Fleet Dry-Run Preview**, `read-file` & `system-action` steps, branching, and service-page `scope` integration.
|
||||
- [ ] Implement `TransferEngine` (`hub-relayed` SFTP streaming and `direct` `rsync` mode).
|
||||
- [ ] Implement Saved **Command Snippets** (`snippets.json`), **Ad-Hoc Fleet Broadcast**, structured workflow display views (`log`, `file-view`, `json`, `table`, `summary`), dashboard-pinned widgets, and run history viewer.
|
||||
- [ ] Implement `AlertEngine` (CPU/RAM/load/per-mount disk/offline/probe/system health rules, hysteresis/cooldowns, scheduled maintenance windows, one-tap snoozing, "Send Test Alert", Discord/Telegram/ntfy/generic webhooks, remediation workflow triggers).
|
||||
|
||||
### Phase 5 — Hardening, Optional AI Assistant, Backup CLI & Mobile Verification
|
||||
- [ ] Add optional WebAuthn/Passkeys enrollment alongside TOTP 2FA.
|
||||
- [ ] Implement the optional **BYO-API AI Assistant** (OpenAI-compatible `/v1/chat/completions` client with vaulted `secretRef`, secret redactor + context preview, per-surface built-in guides for workflows/systems/snippets/logs/setup, Zod-validated 1-click JSON draft apply, and `/ws` streaming drawer).
|
||||
- [ ] Expand theme presets (`phosphor-green`, `amber-term`, `nord-dark`, `gruvbox-dark`, `paper-light`).
|
||||
- [ ] Build portable encrypted backup/restore (`.gcoord.enc`) and `gcoord` CLI utilities (`backup`, `verify-backup`, `restore`, `rotate-key`).
|
||||
- [ ] Profile and optimize bundle size, memory usage, and rendering on throttled mobile profiles / Galaxy J7-class devices.
|
||||
Loading…
Add table
Add a link
Reference in a new issue