diff --git a/How/AGENTS.md b/How/AGENTS.md new file mode 100644 index 0000000..21137d6 --- /dev/null +++ b/How/AGENTS.md @@ -0,0 +1,238 @@ +# AGENTS.md — GCoordinator Engineering & Continuation Guide + +> Operational & architectural guide for AI coding agents (**Neon** and compatible coding agents) continuing maintenance and feature development in `/home/devuser/workspace/GCoordinator`. + +--- + +## 1. Purpose & Relationship to `How/Plan.md` + +**GCoordinator** is a self-hosted, single-admin, security-first central SSH control plane built around: + +- Multiplexed SSH access (`ssh2`) with multi-hop `ProxyJump` forwarding, persistent server-side PTY (`xterm.js` + `@xterm/addon-fit`), streaming SFTP file management with pre-save unified diffs, and authenticated `/proxy/:tunnelId/*` HTTP/WS + local/remote TCP port forwarding. +- Centralized `AES-256-GCM` credential storage (`vault.enc`), Ed25519 key lifecycle + zero-lockout atomic key rotation, Argon2id + multi-factor TOTP + optional WebAuthn Passkeys, configurable re-auth strictness, Safe Mode, and Emergency Panic Lock. +- Agentless Linux/BSD/macOS metric polling, multi-mount disk tracking, on-demand Server Inspector, HTTP/TCP probes, declarative `systems/*.json` discovery/status/actions, Full-DAG `workflows/*.json`, fleet broadcast, cross-server transfers, webhook alerting, portable `.gcoord.enc` backups, and an opt-in BYO-API OpenAI-compatible AI assistant. + +All 5 phases of [Plan.md](file:///home/devuser/workspace/GCoordinator/How/Plan.md) plus post-Phase-2 and post-Phase-3 enhancements are implemented and verified (`18/18` Vitest suites, `35/35` tests passing). + +**Precedence rule:** [How/Plan.md](./Plan.md) is the original Phase 1–5 design blueprint (its directory-tree diagram still references root `Plan.md`, which now lives at `How/Plan.md`). Several core behaviors evolved during implementation—including write-only Vault locking vs. always-on runtime secrets, multi-password/multi-TOTP & configurable strictness, WebAuthn Passkeys, the `data/recovery/` emergency backup store, 8 UI/terminal themes, a strict `< 20 KB` lazy-chunk budget, and `xterm.js` mobile IME composition fixes. **Wherever `How/AGENTS.md` differs from `How/Plan.md`, `How/AGENTS.md` reflects the live codebase and takes precedence.** + +--- + +## 2. Environment, Build, Run & Test Commands + +### Runtime Toolchain +- **Node.js 22+ LTS**: In this dev container, `node`, `npm`, and `npx` live in `~/.local/bin`. Always prepend PATH in non-login shells: + ```bash + export PATH="$HOME/.local/bin:$PATH" + ``` +- **Containers**: `docker` CLI is not installed in this dev container; `docker/Dockerfile`, `docker/docker-compose.yml`, and `docker/docker-compose.lan.yml` are deployment definitions. + +### NPM Scripts (`package.json`) +- `npm run typecheck` — `tsc --noEmit` (strict TypeScript with `noUncheckedIndexedAccess: true` and `noImplicitOverride: true`). +- `npm run build:client` — `tsx src/client/build.ts` (bundles ES2020 client modules + CSS into `dist/public/` and enforces gzip budgets). +- `npm run build:server` — `esbuild` bundles `dist/server/index.js` and `dist/cli/gcoord.js` (`--platform=node --target=node22 --format=esm --packages=external`). +- `npm run build` — runs `typecheck && build:client && build:server`. +- `npm test` — `vitest run` (runs all 18 unit/E2E suites in ~5s using in-process HTTP servers and `MockSshServer`). +- `npx vitest run tests/.test.ts` — run a targeted Vitest file. +- `npm run dev` — `tsx watch src/server/index.ts`. +- `npm start` — `node dist/server/index.js` (requires `npm run build` first so `dist/public/` and `dist/server/` exist). + +### CLI (`src/cli/gcoord.ts` -> `dist/cli/gcoord.js`) +```bash +node dist/cli/gcoord.js rotate-key [--data-dir ] [--current-key-file ] [--new-key-out ] +node dist/cli/gcoord.js backup --out [--data-dir ] [--key-file ] [--passphrase-file ] +node dist/cli/gcoord.js verify-backup [--bundle ] [--key-file ] [--passphrase-file ] [--vault-key-file ] [--json] +node dist/cli/gcoord.js restore [--bundle ] [--data-dir ] [--key-file ] [--passphrase-file ] [--vault-key-file ] +``` + +### Server Environment Variables (`src/server/index.ts`) +- `GCOORD_DATA_DIR` — persistent state directory (default: `./data`). +- `PORT` — HTTP/WS listen port (default: `3000`). +- `HOST` — bind address (default: `0.0.0.0`). +- `GCOORD_MASTER_KEY` — 32-byte Vault master key (hex or base64). +- `GCOORD_MASTER_KEY_FILE` — master key file path (default: `/run/secrets/gcoord_master_key`). +- `GCOORD_BACKUP_PASSPHRASE` — optional passphrase for `.gcoord.enc` CLI operations. +- `TRUST_CLOUDFLARE` — set `'true'` to enable `app.set('trust proxy', 1)` and honor `CF-Connecting-IP` in rate limiting. + +--- + +## 3. Repository Map + +```text +GCoordinator/ +├── How/ +│ ├── AGENTS.md # This guide (authoritative for live codebase conventions) +│ └── Plan.md # Original Phase 1–5 architecture blueprint +├── docker/ +│ ├── Dockerfile +│ ├── docker-compose.yml +│ └── docker-compose.lan.yml +├── src/ +│ ├── cli/ +│ │ └── gcoord.ts # rotate-key, backup, verify-backup, restore CLI +│ ├── shared/ +│ │ ├── diff.ts # Pure TS unified LCS line diff utility +│ │ ├── ws-protocol.ts # Multiplexed /ws frame schemas & WS_CHANNELS helpers +│ │ └── schemas/ # Shared Zod schemas & TypeScript types +│ │ ├── index.ts +│ │ ├── common.ts +│ │ ├── server.schema.ts +│ │ ├── system.schema.ts +│ │ ├── workflow.schema.ts +│ │ ├── snippets.schema.ts +│ │ ├── alerts.schema.ts +│ │ ├── settings.schema.ts +│ │ └── vault.schema.ts +│ ├── server/ +│ │ ├── index.ts # Process bootstrap & SIGINT/SIGTERM graceful shutdown +│ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock +│ │ ├── db/ +│ │ │ ├── database.ts # SQLite WAL connection & ordered migration runner +│ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts +│ │ ├── security/ +│ │ │ ├── vault.ts # VaultService (AES-256-GCM, runtime-ready vs write-locked, Ed25519) +│ │ │ ├── auth.ts # AuthService (Argon2id, multi-password, multi-TOTP, recovery codes, WebAuthn) +│ │ │ ├── guards.ts # RateLimiter, attachClientIp, CSRF, Safe Mode, createStepUpGuard +│ │ │ ├── audit.ts # Append-only AuditService +│ │ │ ├── recovery-store.ts # EmergencyRecoveryService (data/recovery/emergency-secrets.json) +│ │ │ └── backup.ts # Portable AES-256-GCM .gcoord.enc (GCOORD_BACKUP_V1) export/verify/restore +│ │ ├── config/ +│ │ │ ├── config-manager.ts # ConfigManager (atomic writes, chokidar hot-reload, revisions) +│ │ │ ├── presets.ts # Default docker-compose, systemd, os-packages seeds +│ │ │ └── diff.ts +│ │ ├── ssh/ +│ │ │ ├── ssh-pool.ts # SSHPool (coalesced connections, ProxyJump, execStream, openShell, openSftp) +│ │ │ ├── known-hosts.ts # KnownHostsService (strict TOFU, MITM guard, replaceAllKnownHosts) +│ │ │ ├── key-manager.ts # KeyManager (authorized_keys deploy/revoke, zero-lockout rotation) +│ │ │ ├── sudo.ts # POSIX-quoted sudo wrapper & Buffer zeroization +│ │ │ ├── pty-manager.ts # PTYManager (UTF-8 framing, scrollback ring, export, reaper) +│ │ │ ├── sftp-service.ts # SftpService (stream upload/download, atomic inline edit, tar archives) +│ │ │ └── tunnel-manager.ts # TunnelManager (http-proxy, local-tcp, remote-tcp) +│ │ ├── monitoring/ +│ │ │ ├── collectors.ts # OS-aware LinuxCollector, BSDCollector, MacOSCollector +│ │ │ ├── inspector.ts # On-demand ServerInspector (processes, ports, sensors) +│ │ │ ├── probes.ts # ProbeRunner (hub or target forwardOutStream HTTP/TCP probes) +│ │ │ └── monitoring-service.ts # MonitoringService (always-on polling, SQLite rollups, retention) +│ │ ├── systems/ +│ │ │ ├── parsers.ts # Output parsers for declarative system discovery/status +│ │ │ └── systems-engine.ts # CustomSystemsEngine (TTL cache, overlays, 3x3 scoped/moded actions) +│ │ ├── automation/ +│ │ │ ├── template.ts # Safe env-var & POSIX single-quoted interpolation + target filtering +│ │ │ ├── stream-buffer.ts # BufferedStreamEmitter (128 KB circular WS replay ring) +│ │ │ ├── transfer-engine.ts # TransferEngine (hub-relayed SFTP or direct rsync) +│ │ │ ├── workflow-engine.ts # WorkflowEngine (Kahn DAG scheduler, croner, event triggers, dry-run) +│ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet command execution) +│ │ ├── alerts/ +│ │ │ └── alert-engine.ts # AlertEngine (metric/disk/offline/probe/system rules, silences, webhooks) +│ │ ├── ai/ +│ │ │ ├── redactor.ts # collectVaultSecretStrings & redactSecrets +│ │ │ ├── guides.ts # AiSurfaceSchema & buildSurfaceGuideAndInventory +│ │ │ └── ai-service.ts # AiService (opt-in /v1/chat/completions, WS streaming, Zod draft check) +│ │ └── api/ +│ │ ├── ws-hub.ts # Multiplexed WebSocket hub (/ws, origin & ticket/session checks, replay) +│ │ └── routes/ # auth, vault, config, audit, servers, terminal, sftp, tunnels, systems, workflows, snippets, alerts, backup, ai +│ └── client/ +│ ├── build.ts # esbuild client/CSS bundler + gzip budget assertions +│ ├── index.html # SPA shell + PWA manifest + dynamic theme-color meta +│ ├── manifest.json +│ ├── icon.svg +│ ├── css/ +│ │ ├── themes.css # 8 CSS custom-property terminal themes +│ │ └── base.css # Flat sharp styles, dialog/drawer styles, mobile <768px rules +│ └── ts/ +│ ├── main.ts # Router, nav, topbar indicators, Panic Lock, global state sync +│ ├── state.ts # Client store, CLIENT_THEME_IDS, applyTheme, appendBoundedStreamText +│ ├── api.ts # Fetch wrapper (CSRF header + auto Vault unlock prompt on 423 VAULT_LOCKED) +│ ├── ws-client.ts # Reconnecting /ws client +│ ├── dialogs.ts # Native modals (multi-factor step-up, confirm, prompts) +│ ├── charts.ts # Flat SVG sparklines & metric charts (viewport-capped points) +│ ├── webauthn.ts # navigator.credentials base64url helper +│ └── views/ +│ ├── auth-view.ts # Core static views +│ ├── dashboard-view.ts +│ ├── server-detail-view.ts +│ ├── vault-view.ts +│ ├── config-view.ts +│ ├── settings-view.ts +│ ├── terminal-view.ts # Code-split lazy views (keep dynamically imported!) +│ ├── xterm-runtime.ts +│ ├── sftp-view.ts +│ ├── tunnels-panel.ts +│ ├── systems-view.ts +│ ├── workflows-view.ts +│ ├── alerts-view.ts +│ └── ai-drawer.ts +└── tests/ + ├── helpers/mock-ssh-server.ts # In-process ssh2.Server fixture (PTY, SFTP, forwardOut, forwardIn, sudo) + └── *.test.ts # 18 Vitest integration & unit suites +``` + +--- + +## 4. Critical Architectural Invariants (Must Preserve) + +### 1. Runtime-Ready Secrets vs. Write-Only Vault Lock (`vault.ts`) +- `vaultService.isRuntimeReady` is decoupled from `vaultService.state === 'unlocked'`. +- At server startup (`initRuntime` in `src/server/app.ts`), established secrets are decrypted into memory using `secretFilePath`, `GCOORD_MASTER_KEY`, `data/vault.key` (`0600`), or `data/recovery/emergency-secrets.json`, while `state` begins `'locked'` (write-locked). +- Background and established-secret consumers (`SSHPool`, `MonitoringService`, `TunnelManager`, `CustomSystemsEngine`, `WorkflowEngine`, `AlertEngine`, `AiService`, `/api/backup/export`) **must** check `isRuntimeReady` and read credentials via `getRuntimeSecret(id)` so polling, crons, SFTP, and webhooks work unattended before login and while write-locked. +- Only Vault mutations (adding/editing/deleting credentials), Ed25519 key generation, raw secret reveals, master-key rotation, and fleet key rotation require `state === 'unlocked'`. When write-locked, these endpoints must fail with `HTTP 423 VAULT_LOCKED` (which `src/client/ts/api.ts` intercepts to prompt Vault unlock and retry automatically). +- **Emergency Panic Lock** (`panicLock()`, persisted via `${vaultFilePath}.panic-locked`) is the **only** state that zeroes runtime secret buffers (`isRuntimeReady = false`), tears down active SSH/PTY/tunnel/AI sessions, revokes sessions (`WS 4001`), and refuses silent disk/env auto-unlock across restarts until a user manually unlocks with the master key. + +### 2. Auth, Multi-Factor Strictness, Safe Mode & Passkeys (`auth.ts`, `guards.ts`) +- Supports multiple admin passwords (`admin_passwords`) and multiple TOTPs (`admin_totps`) evaluated in `any` or `all` mode, single-use recovery codes, and `@simplewebauthn/server` Passkeys (`webauthn_credentials`; accessing WebAuthn endpoints over raw IP literals returns `WEBAUTHN_RPID_INVALID`). +- `SecuritySettingsSchema` (`src/shared/schemas/settings.schema.ts`) configures `requireTotpOnLogin`, `stepUpPolicy` (`off | every-action | 5m | 1h | 24h | session`), `stepUpMethod` (`totp | password | both | passkey`), `elevateOnLogin`, and `keepElevationOnSafeMode`. Always gate elevated endpoints with `createStepUpGuard` rather than hardcoding 5-minute TOTP assumptions. +- All mutating HTTP routes require an authenticated session cookie, matching `X-CSRF-Token` header, and Safe Mode enforcement (`HTTP 423 SAFE_MODE_ACTIVE` when `session.safeMode` is true; mobile viewports `< 768px` default to Safe Mode ON). Only **Panic Lock** and **`/api/backup/verify`** are Safe-Mode exempt. + +### 3. Dual Backup Subsystems (`recovery-store.ts` vs. `backup.ts`) +- **Local Emergency Secrets Store (`recovery-store.ts`)**: When `settings.security.enableEmergencySecretsBackup` is enabled, `EmergencyRecoveryService` maintains `data/recovery/emergency-secrets.json` (`chmod 0600`) plus up to 10 snapshots under `data/recovery/snapshots/`. Keep `syncRecovery()` wired after auth/vault mutations. +- **Portable Encrypted Bundles (`backup.ts`)**: Creates, verifies, and restores `GCOORD_BACKUP_V1` `.gcoord.enc` bundles encrypted with `AES-256-GCM` (`raw-master-key` or `scrypt` passphrase KDF) containing gzipped `config/**` JSONs (including `servers/*.json` `systems[].itemOverrides` / `activeFiles[]`), `vault.enc`, and SQLite `known_hosts` + `alert_silences`. +- **Linux `inotify` Rule on Config Restore**: Whenever swapping or replacing `data/config/` while the server is running (e.g., `/api/backup/restore`), **always** call `configManager.pauseWatcher()` before replacing the directory and `reloadAllFromDisk()` + `await configManager.resumeWatcher()` afterward; otherwise `chokidar` retains stale directory inodes and stops firing hot-reload events. + +### 4. Config Hot-Reload & SQLite Migrations (`config-manager.ts`, `database.ts`) +- Every config write must be atomic (`tmp -> fsync -> rename`), validated against Zod schemas, and recorded in SQLite `config_revisions` for diff/rollback. Hand-edited invalid config files must remain isolated without crashing the hub or clobbering valid files. +- Never mutate existing migration files (`001_initial.ts`, `002_multi_auth.ts`, `003_phase4_meta.ts`) destructively; add new schema changes as `004_*.ts` and register them in `src/server/db/database.ts`. + +### 5. SSH, Shell Quoting, Crypto & Tunnel Proxy Rules +- **No Shell Injection**: Never interpolate user inputs, workflow variables, or parameters directly into shell strings. Pass inputs via `GCOORD_*` environment variables (`buildWorkflowEnv`, `GCOORD_PARAM_*`) or sanitize explicitly with `interpolateShellCommandSafe()` (`src/server/automation/template.ts`) / POSIX single-quoting in `src/server/ssh/sudo.ts` (and zeroize `sudo` password `Buffer`s right after writing to stdin). +- **`ssh2` Ed25519 Keygen Bug**: Always generate Ed25519 keys through `generateValidEd25519KeyPair()` in `src/server/security/vault.ts` (retries around `ssh2`'s ASN.1 leading-`0x00` BitString parser issue). +- **Direct `rsync` Channel Drain**: In `TransferEngine` (`src/server/automation/transfer-engine.ts`), always drain/consume SSH channel `stdout` and `stderr` streams so `close` never deadlocks on full flow-control windows. +- **Reverse Proxy Isolation**: In `src/server/app.ts`, keep `/proxy` mounted **before** `express.json()` and exempt `/proxy/*` from the hub SPA Content-Security-Policy. `TunnelManager` (`src/server/ssh/tunnel-manager.ts`) must keep stripping `gcoord_sid` and `gcoord_csrf` cookies from forwarded headers and rewriting relative `Location` redirects. + +### 6. Optional BYO-API AI Assistant (`src/server/ai/`) +- Strictly opt-in: return `403 AI_DISABLED` whenever `settings.ai.enabled === false` and hide `[AI ...]` triggers in the UI unless `isAiEnabled(state)` is true. +- Sanitize all outbound AI prompts and context previews through `redactSecrets()` (`redactor.ts`) seeded with `collectVaultSecretStrings()`. +- Never auto-execute AI-suggested shell commands or auto-save AI-generated JSON/system/workflow drafts—require server Zod `validateDraft`, line diff preview, and explicit user confirmation in `ai-drawer.ts`. + +--- + +## 5. Frontend, Bundle Budget & Mobile Rules + +### Hard Gzip Budgets (`src/client/build.ts` — throws and fails build if exceeded) +- **Core bundle** (`index.html` + `themes.css` + `base.css` + `main.js`): strictly **`< 50.00 KB` gzipped** (currently `25.46 KB`). +- **Every non-terminal lazy chunk** (`dist/public/chunks/*.js` except `terminal-view-*`): strictly **`< 20.00 KB` gzipped**. + +### CRITICAL: Zero Runtime `zod` in Client Code +- **NEVER** import runtime schemas or runtime values from `src/shared/schemas/*` or `zod` anywhere inside `src/client/ts/**`. Importing Zod into client TypeScript drags Zod into `main.js` or lazy chunks and breaks the gzip budgets. +- Use `import type { ... } from '../../shared/...'` exclusively, mirror minimal constants cleanly in `src/client/ts/state.ts` (such as `CLIENT_THEME_IDS`), and keep heavy secondary views (`terminal-view`, `sftp-view`, `systems-view`, `workflows-view`, `alerts-view`, `ai-drawer`, `tunnels-panel`) code-split via dynamic `import(...)`. + +### Flat Sharp Aesthetic & 8 Themes +- Maintain the zero-overhead aesthetic: `border-radius: 0`, `1px` crisp borders, zero `box-shadow`, zero gradients, zero `backdrop-filter`. +- Keep all 8 themes (`phosphor-green`, `amber-term`, `nord-dark`, `gruvbox-dark`, `paper-light`, `solarized-dark`, `tokyo-night`, `high-contrast`) in sync across `THEME_IDS` (`src/shared/schemas/settings.schema.ts`), `src/client/css/themes.css`, `CLIENT_THEME_IDS` (`src/client/ts/state.ts`), and `applyTheme()` (which updates ``). Note that `esbuild` CSS minification removes quotes in attribute selectors (`[data-theme=phosphor-green]`). + +### `xterm.js`, QR & Low-RAM Mobile (`< 768px` / Galaxy J7) Safeguards +- Keep global textarea sizing in `src/client/css/base.css` scoped to `textarea:not(.xterm-helper-textarea)` so `.xterm-helper-textarea` stays `0x0` and does not overflow its container. +- Preserve capture-phase sticky `Ctrl`/`Alt` input handling and `clearTerminalComposition()` in `src/client/ts/views/xterm-runtime.ts` so mobile IMEs (e.g., Firefox Android + Gboard) cannot leave ghost characters (like `x` after `Ctrl+x`). +- Keep `.qr-box` square (`align-self: flex-start; width: fit-content; line-height: 0`). +- Preserve `< 768px` `44px` minimum touch target heights on `.btn-sm` and `.input-sm`, `overscroll-behavior: contain` on `dialog:modal` and `dialog::backdrop`, `env(safe-area-inset-bottom)` nav padding, viewport-capped chart history via `maxChartPointsForViewport()`, and `appendBoundedStreamText()` for live `
` stream logs.
+
+---
+
+## 6. Testing & Verification Workflow
+
+- Write tests in `tests/*.test.ts` using `createGCoordinatorServer({ dataDir: tmpDir, port: 0, ... })` paired with `MockSshServer` (`tests/helpers/mock-ssh-server.ts`) for isolated HTTP + `/ws` + SSH/SFTP/PTY/ProxyJump/Tunnel testing without external daemons. Always clean up temp directories and `await instance.close()` / `await mockSsh.stop()` in `finally` or `afterEach`.
+- Before concluding any code change:
+  ```bash
+  export PATH="$HOME/.local/bin:$PATH"
+  npm run build && npm test
+  ```
+- Inspect `git status` and `git diff` after edits to confirm clean diffs, untouched unrelated docs/comments, and passing typechecks, bundle budgets, and all Vitest tests.
diff --git a/Plan.md b/How/Plan.md
similarity index 100%
rename from Plan.md
rename to How/Plan.md