GCoordinator/How/AGENTS.md

280 lines
29 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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 **v1.1.0** security hardening, lightweight low-resource runtime throttling, and operational enhancements are implemented and verified (`21/21` Vitest suites, `41/41` tests passing). Key v1.1 additions include configurable `runtime.throttleMode` (`low-resource` | `balanced` | `unthrottled`) tuned for 1 vCPU / 1 GB RAM + 2 GB Swap servers, Zero-Trust Egress Guard, Vault `seal()` + passwordless emergency recovery, encrypted TOTP + SQLite rate limiting + CIDR-gated proxy IP trust + real-time WS revocation, dual-mode isolated proxy origins + SOCKS5/TTL tunnels + OpenSSH config import, Prometheus `/metrics`, Security Event Alerting, scheduled `.gcoord.enc` backups, offline CLI admin tools (`status`, `panic-lock`, `reset-2fa`, `reset-password`), and full dynamic client code-splitting.
**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 across v1.0 and v1.1—including write-only Vault locking + explicit `seal()` vs. always-on runtime secrets, multi-password/multi-TOTP & configurable strictness, WebAuthn Passkeys, passwordless `data/recovery/` emergency secret backups, Zero-Trust egress & dual-mode isolated proxy origins, configurable `runtime.throttleMode`, 8 UI/terminal themes, a strict `< 20 KB` lazy-chunk budget across all code-split views, 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 Helper Scripts**: `docker` CLI is not installed in this dev container; `docker/Dockerfile`, `docker/docker-compose.yml`, and `docker/docker-compose.lan.yml` are deployment definitions configured via `.env` (see `.env.example`) and helper scripts under `scripts/` (`setup.sh`, `build.sh`, `up.sh`, `down.sh`, `logs.sh`, `cli.sh`).
### 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 recursively across `main.js` static imports and lazy chunks).
- `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 21 unit/E2E suites, 41 tests using in-process HTTP servers and `MockSshServer`).
- `npx vitest run tests/<file>.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 status [--data-dir <dir>] [--json]
node dist/cli/gcoord.js panic-lock [--data-dir <dir>]
node dist/cli/gcoord.js reset-2fa [--data-dir <dir>] [--disable] [--json]
node dist/cli/gcoord.js reset-password [--data-dir <dir>] [--password-file <path>]
node dist/cli/gcoord.js rotate-key [--data-dir <dir>] [--current-key-file <path>] [--new-key-out <path>]
node dist/cli/gcoord.js backup --out <path.gcoord.enc> [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>]
node dist/cli/gcoord.js verify-backup <path.gcoord.enc> [--bundle <path>] [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>] [--json]
node dist/cli/gcoord.js restore <path.gcoord.enc> [--bundle <path>] [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>]
```
### 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_DB_KEY` — 32-byte key encrypting TOTP secrets at rest in SQLite (otherwise auto-created `0600` at `data/db.key`).
- `GCOORD_AUTO_KEYFILE` — set `'true'` to mirror an env/secret Vault key into local `data/vault.key` (`0600`).
- `GCOORD_BACKUP_PASSPHRASE` — optional passphrase for `.gcoord.enc` CLI operations.
- `TRUST_CLOUDFLARE` — set `'true'` to trust proxy headers from `TRUSTED_PROXY_CIDRS` / loopback and honor `CF-Connecting-IP` in rate limiting.
- `TRUSTED_PROXY_CIDRS` — comma-separated CIDR allowlist of trusted reverse proxies (`trust proxy` & client IP resolution).
- `GCOORD_ALLOW_LAN_TUNNELS` — set `'true'` to permit LAN-bound tunnel listeners where applicable.
- `GCOORD_PROXY_PORT` — optional dedicated local port for origin-isolated reverse-proxy tunnel traffic.
- `GCOORD_PROXY_BASE_DOMAIN` — optional wildcard subdomain base host (e.g. `proxy.example.com`) for origin-isolated tunnel proxying.
- `GCOORD_WEBAUTHN_RP_ID` — optional explicit WebAuthn Relying Party ID override.
- `GCOORD_WEBAUTHN_ORIGINS` — optional comma-separated allowed WebAuthn origins.
- `GCOORD_METRICS_TOKEN` — optional Bearer token override for Prometheus `GET /metrics`.
- `GCOORD_THROTTLE_MODE` — runtime throttle profile override: `'low-resource'` | `'balanced'` | `'unthrottled'` (overrides `settings.runtime.throttleMode`).
---
## 3. Repository Map
```text
GCoordinator/
├── .env.example # Environment template for Docker Compose & runtime options
├── 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
├── scripts/ # Docker Compose setup, build, run, logs & container CLI helpers
│ ├── _compose.sh
│ ├── setup.sh
│ ├── build.sh
│ ├── up.sh
│ ├── down.sh
│ ├── logs.sh
│ └── cli.sh
├── src/
│ ├── cli/
│ │ └── gcoord.ts # status, panic-lock, reset-2fa, reset-password, rotate-key, backup, verify-backup, restore
│ ├── 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, /metrics
│ │ ├── db/
│ │ │ ├── database.ts # SQLite WAL connection, throttle PRAGMAs & ordered migration runner
│ │ │ └── migrations/ # 001_initial.ts .. 005_metrics_disks_indexes.ts
│ │ ├── security/
│ │ │ ├── vault.ts # VaultService (AES-256-GCM, runtime-ready vs write-locked, seal(), Ed25519)
│ │ │ ├── auth.ts # AuthService (Argon2id queue, multi-password, encrypted TOTP, idle TTL, WebAuthn)
│ │ │ ├── guards.ts # SQLite RateLimiter, attachClientIp (CIDR trust), CSRF, Safe Mode, Step-Up
│ │ │ ├── egress-guard.ts # Zero-Trust SSRF/DNS/CIDR guard & redirect: 'error' fetch wrapper
│ │ │ ├── audit.ts # Append-only AuditService (filtered query, CSV formula guard, NDJSON)
│ │ │ ├── recovery-store.ts # EmergencyRecoveryService (passwordless data/recovery/emergency-secrets.json)
│ │ │ ├── backup.ts # Async portable AES-256-GCM .gcoord.enc (GCOORD_BACKUP_V1) export/verify/restore
│ │ │ └── backup-scheduler.ts # Scheduled .gcoord.enc backups (local & SFTP) with retention pruning
│ │ ├── config/
│ │ │ ├── config-manager.ts # ConfigManager (atomic writes, chokidar hot-reload, revisions, symlink guard)
│ │ │ ├── runtime-limits.ts # Throttle profile presets (low-resource | balanced | unthrottled)
│ │ │ ├── presets.ts # Default docker-compose, systemd, os-packages seeds
│ │ │ └── diff.ts
│ │ ├── ssh/
│ │ │ ├── ssh-pool.ts # SSHPool (coalesced connections, ProxyJump, execStream, openShell, openSftp)
│ │ │ ├── ssh-config-import.ts # Safe OpenSSH config parser for /api/servers/import-ssh-config
│ │ │ ├── known-hosts.ts # KnownHostsService (strict multi-algo TOFU, MITM guard, replaceAllKnownHosts)
│ │ │ ├── key-manager.ts # KeyManager (authorized_keys deploy/revoke, zero-lockout rotation)
│ │ │ ├── sudo.ts # POSIX-quoted sudo wrapper, askpass-free pipe & Buffer zeroization
│ │ │ ├── pty-manager.ts # PTYManager (UTF-8 framing, scrollback ring, .cast v2 export, reaper)
│ │ │ ├── sftp-service.ts # SftpService (stream upload/download, touch/chown/search, symlink-safe ops)
│ │ │ └── tunnel-manager.ts # TunnelManager (dual-mode isolated HTTP/WS proxy, SOCKS5, local/remote TCP, TTL)
│ │ ├── monitoring/
│ │ │ ├── collectors.ts # OS-aware LinuxCollector, BSDCollector, MacOSCollector (+ net/disk I/O)
│ │ │ ├── inspector.ts # On-demand ServerInspector (processes, ports, sensors)
│ │ │ ├── probes.ts # ProbeRunner (hub egress-guarded HTTP + TLS expiry, target forwardOutStream)
│ │ │ ├── monitoring-service.ts # MonitoringService (staggered/capped polling, SQLite rollups, retention)
│ │ │ └── prometheus.ts # Opt-in Bearer-authenticated Prometheus GET /metrics exporter
│ │ ├── systems/
│ │ │ ├── parsers.ts # Output parsers for declarative system discovery/status
│ │ │ └── systems-engine.ts # CustomSystemsEngine (bounded TTL cache, overlays, editableFiles, action inputs)
│ │ ├── automation/
│ │ │ ├── template.ts # Safe env-var & POSIX single-quoted interpolation + target filtering
│ │ │ ├── stream-buffer.ts # BufferedStreamEmitter (capped circular WS replay ring)
│ │ │ ├── transfer-engine.ts # TransferEngine (hub-relayed SFTP or direct rsync)
│ │ │ ├── workflow-engine.ts # WorkflowEngine (Kahn DAG, retries, http/notify steps, croner, secret inputs)
│ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet execution + SQLite history & CSV)
│ │ ├── alerts/
│ │ │ └── alert-engine.ts # AlertEngine (metric/disk/offline/probe/system/security-event, egress-guarded webhooks)
│ │ ├── ai/
│ │ │ ├── redactor.ts # Linear O(n) collectVaultSecretStrings & redactSecrets
│ │ │ ├── guides.ts # AiSurfaceSchema & buildSurfaceGuideAndInventory
│ │ │ └── ai-service.ts # AiService (opt-in egress-guarded /v1/chat/completions, WS streaming, Zod draft check)
│ │ └── api/
│ │ ├── ws-hub.ts # Multiplexed WebSocket hub (/ws, origin & ticket/session checks, real-time close 4001)
│ │ └── routes/ # auth, vault, config, audit, servers, terminal, sftp, tunnels, systems, workflows, snippets, alerts, backup, ai
│ └── client/
│ ├── build.ts # esbuild client/CSS bundler + recursive sync-core & lazy-chunk gzip 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/toast/palette styles, mobile <768px rules
│ └── ts/
│ ├── main.ts # Router, nav, view cleanup lifecycle, topbar indicators, Panic Lock, global state sync
│ ├── state.ts # Client store, CLIENT_THEME_IDS, applyTheme, appendBoundedStreamText, registerViewCleanup
│ ├── api.ts # Fetch wrapper (CSRF header + auto Vault unlock prompt on 423 VAULT_LOCKED)
│ ├── ws-client.ts # Reconnecting /ws client with ref-counted subscribe()/unsubscribe
│ ├── dialogs.ts # Native <dialog> modals (multi-factor step-up, confirm, collapsible hunk diffs)
│ ├── charts.ts # Flat SVG sparklines & metric charts (viewport-capped points, multi-series overlay)
│ ├── toast.ts # Live toast notification bus (lazy/core feedback helpers)
│ ├── webauthn.ts # navigator.credentials base64url helper
│ ├── command-palette.ts # Code-split Ctrl/Cmd+K quick switcher & action palette
│ └── views/ # All views dynamically code-split via import(...)
│ ├── auth-view.ts
│ ├── dashboard-view.ts
│ ├── server-detail-view.ts
│ ├── vault-view.ts
│ ├── config-view.ts
│ ├── settings-view.ts
│ ├── settings-ops-panel.ts
│ ├── terminal-view.ts
│ ├── 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 # 21 Vitest integration & unit suites
```
---
## 4. Critical Architectural Invariants (Must Preserve)
### 1. Runtime-Ready Secrets, `seal()` & Panic 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). `data/vault.key` is only written for locally generated keys (never mirroring `GCOORD_MASTER_KEY` or Docker secrets unless `GCOORD_AUTO_KEYFILE=true`).
- Background and established-secret consumers (`SSHPool`, `MonitoringService`, `TunnelManager`, `CustomSystemsEngine`, `WorkflowEngine`, `AlertEngine`, `AiService`, `BackupScheduler`, `/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, Ed25519 key generation, raw secret reveals, master-key rotation, and fleet key rotation require `state === 'unlocked'`; write-locked mutations must fail with `HTTP 423 VAULT_LOCKED` (intercepted by `src/client/ts/api.ts`).
- **Explicit Seal (`POST /api/vault/seal` -> `vaultService.seal()`)**: clears runtime secret buffers and pauses active background SSH/monitoring/workflow/tunnel operations **without** revoking admin HTTP/WS sessions.
- **Emergency Panic Lock** (`panicLock()`, persisted via `${vaultFilePath}.panic-locked`): zeroes runtime secret buffers (`isRuntimeReady = false`), tears down active SSH/PTY/tunnel/AI/scheduler sessions, revokes sessions immediately (`WS 4001`), emits a `vault.panic_lock` security event, and refuses silent disk/env auto-unlock across restarts until manually unlocked with the master key.
### 2. Auth, Multi-Factor Strictness, Safe Mode & Passkeys (`auth.ts`, `guards.ts`)
- Supports multiple admin passwords (`admin_passwords`), multiple TOTPs (`admin_totps` encrypted at rest with `data/db.key` / `GCOORD_DB_KEY` using `AES-256-GCM`, plus single-use TOTP replay tracking) evaluated in `any` or `all` mode, single-use recovery codes, rate-limited bootstrap (`15m` token TTL), and `@simplewebauthn/server` Passkeys (`webauthn_credentials`; raw IP literals return `WEBAUTHN_RPID_INVALID`).
- Sessions enforce both absolute `sessionTtlHours` and sliding `sessionIdleTimeoutMin`; revoking sessions via logout, password reset, key/2FA reset, or Panic Lock broadcasts real-time `WS 4001` disconnects through `WsHub`.
- `RateLimiter` is SQLite-backed (`rate_limits` table) to persist lockouts across restarts, and `attachClientIp` / Express `trust proxy` only honor forwarding headers when the socket peer matches `TRUSTED_PROXY_CIDRS` (plus loopback when `TRUST_CLOUDFLARE=true`).
- `SecuritySettingsSchema` (`src/shared/schemas/settings.schema.ts`) configures `requireTotpOnLogin`, `stepUpPolicy` (`off | every-action | 5m | 15m | 1h | 24h | session`, default `15m`), `stepUpMethod` (`totp | password | both | passkey`), `elevateOnLogin`, and `keepElevationOnSafeMode`. Always gate elevated endpoints with `createStepUpGuard`.
- Mutating HTTP routes require an authenticated session cookie, matching `X-CSRF-Token`, and Safe Mode enforcement (`HTTP 423 SAFE_MODE_ACTIVE`; mobile `< 768px` defaults to Safe Mode ON). Safe-Mode exemptions are limited to `/api/auth/logout`, `/api/auth/safe-mode`, Panic Lock (`/api/security/panic-lock`), `/api/backup/verify`, read-only AI draft/chat endpoints (all except `/api/ai/save-draft`), `/api/workflows/:id/dry-run`, and live cancellation endpoints (`/api/systems/streams/:jobId/cancel`, `/api/workflows/runs/:runId/cancel`, `/api/workflows/broadcast/:jobId/cancel`).
### 3. Dual Backup Subsystems (`recovery-store.ts`, `backup.ts`, `backup-scheduler.ts`)
- **Local Emergency Secrets Store (`recovery-store.ts`)**: When `settings.security.enableEmergencySecretsBackup` is enabled, `EmergencyRecoveryService` maintains a **passwordless** `data/recovery/emergency-secrets.json` (`chmod 0600`, Vault/key/TOTP recovery data only—never stores plaintext admin login passwords) plus up to 10 snapshots under `data/recovery/snapshots/`. Keep `syncRecovery()` wired after auth/vault mutations.
- **Portable Encrypted Bundles (`backup.ts` & `backup-scheduler.ts`)**: Creates, verifies, and restores `GCOORD_BACKUP_V1` `.gcoord.enc` bundles encrypted with `AES-256-GCM` (`raw-master-key` or `scrypt` passphrase KDF) via non-blocking async workers (`createBackupBundleAsync`) bounded by `runtimeLimits`, plus scheduled local/SFTP backups with retention pruning.
- **Linux `inotify` Rule on Config Restore**: Whenever replacing `data/config/` while running (`/api/backup/restore`), **always** call `configManager.pauseWatcher()` before replacing the directory and `reloadAllFromDisk()` + `await configManager.resumeWatcher()` afterward so `chokidar` re-attaches cleanly to new directory inodes.
### 4. Runtime Throttle Profile & Lightweight Footprint (`runtime-limits.ts`, `settings.schema.ts`)
- `settings.runtime.throttleMode` defaults to `'low-resource'` (sized for single-core 1 vCPU / 1 GB RAM + 2 GB Swap deployments) and supports `'balanced'` and `'unthrottled'` (overrideable via `GCOORD_THROTTLE_MODE`).
- `resolveRuntimeLimits()` governs Argon2id memory/concurrency/queueing (`piscina`/mutex semaphore), `scrypt` concurrency, backup unzip/body limits, SQLite PRAGMAs (`cache_size`, `mmap_size`, `temp_store`), max active/retained PTYs & default scrollback bytes, staggered & concurrency-capped metric polling, parallel systems inspection & cache size, workflow concurrency/targets/queue/log bytes, WS replay buffer sizes, AI stream concurrency, and tunnel socket caps. Always consume limits via `getRuntimeLimits()` rather than hardcoding unbounded concurrency.
### 5. Config Hot-Reload, Symlink Safety & SQLite Migrations (`config-manager.ts`, `database.ts`)
- Every config write uses atomic staging (`tmp -> fsync -> rename`), rejects symlinks across config/backup/CLI file operations, validates against Zod schemas, and records `config_revisions`. Invalid hand-edited config files stay isolated without crashing the hub.
- Never mutate existing migration files (`001_initial.ts`, `002_multi_auth.ts`, `003_phase4_meta.ts`, `004_v1_1.ts`, `005_metrics_disks_indexes.ts`) destructively; add new schema changes as `006_*.ts` and register them in `src/server/db/database.ts`.
### 6. SSH, Shell Quoting, Egress Guard & Dual-Mode Isolated Proxy (`egress-guard.ts`, `tunnel-manager.ts`)
- **Zero-Trust Egress Guard (`egress-guard.ts`)**: All outbound hub HTTP calls (HTTP probes, webhook deliveries, BYO AI requests, workflow `http` steps) must go through `fetchWithEgressGuard()` / `assertSafeEgressUrl()`, which default-denies loopback, private, link-local, carrier-grade NAT, and cloud-metadata IPs/DNS resolutions, disables automatic redirects (`redirect: 'error'`), and honors explicit `settings.security.egressAllowedCidrs` opt-ins.
- **No Shell Injection**: Never interpolate user inputs, workflow variables, or PTY `cwd` directly into shell strings. Pass inputs via `GCOORD_*` environment variables (`buildWorkflowEnv`, `GCOORD_PARAM_*`) or sanitize explicitly with `interpolateShellCommandSafe()` (`template.ts`), `formatRemoteCd()` (`pty-manager.ts`), and POSIX single-quoting (`sudo.ts`, zeroizing password `Buffer`s immediately after writing).
- **Direct `rsync` & `ssh2` Invariants**: Generate Ed25519 keys via `generateValidEd25519KeyPair()` (`vault.ts`), validate all host-key algorithms in `known-hosts.ts`, drain SSH channel `stdout`/`stderr` streams in `TransferEngine`, and enforce symlink-safe `lstat` checks in `sftp-service.ts`.
- **Dual-Mode Isolated Reverse Proxy (`tunnel-manager.ts`, `app.ts`)**:
- Prefer origin-isolated proxying via `GCOORD_PROXY_PORT` (dedicated local port) or `GCOORD_PROXY_BASE_DOMAIN` (wildcard subdomain), bridged via single-use `/proxy-ticket` redemption into a proxy-scoped `gcoord_proxy_sid` session so proxied target apps cannot share hub origin cookies or storage.
- Same-origin `/proxy` requests are rejected with `HTTP 403 PROXY_ISOLATION_NOT_CONFIGURED` unless `settings.security.allowSameOriginProxy: true` is explicitly enabled.
- Keep `/proxy` mounted before `express.json()`, exempt `/proxy/*` from the hub CSP, strip `gcoord_sid` / `gcoord_csrf` / `gcoord_proxy_sid` cookies upstream, rewrite relative `Location` redirects, and support HTTPS upstream, SOCKS5 (`mode: 'socks5'`), and TTL auto-expiry.
### 7. Alerts, Prometheus `/metrics` & BYO-API AI (`alerts/`, `prometheus.ts`, `ai/`)
- Alert channels strictly allow only `webhook-secret` Vault credential IDs (preventing arbitrary Vault credential exfiltration in webhook headers/bodies) and dispatch `security-event` alerts emitted by Auth, KnownHosts, and Vault Panic Lock.
- Prometheus `GET /metrics` (`prometheus.ts`) is opt-in (`settings.metrics.prometheusEnabled`) and Bearer-authenticated against `GCOORD_METRICS_TOKEN`, the rotated SHA-256 token hash from `POST /api/config/prometheus-token`, or a Vault `api-token`/`webhook-secret` ref (`404` when disabled, `401` when unauthenticated).
- AI Assistant (`src/server/ai/`): opt-in (`403 AI_DISABLED` when disabled), linear-time `O(n)` secret redaction (`redactor.ts`), and mandatory server Zod `validateDraft` + diff review before saving/running anything.
---
## 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` + all recursive static ESM imports of `main.js`): strictly **`< 50.00 KB` gzipped** (currently `15.80 KB`).
- **Every non-terminal lazy chunk** (`dist/public/chunks/*.js` except `terminal-view-*`): strictly **`< 20.00 KB` gzipped**.
### CRITICAL: Zero Runtime `zod` & View Lifecycle in Client Code
- **NEVER** import runtime schemas or runtime values from `src/shared/schemas/*` or `zod` anywhere inside `src/client/ts/**`. Use `import type` exclusively and mirror minimal constants cleanly in `src/client/ts/state.ts`.
- Keep **all** views (`auth-view`, `dashboard-view`, `server-detail-view`, `vault-view`, `config-view`, `settings-view`, `settings-ops-panel`, `terminal-view`, `sftp-view`, `tunnels-panel`, `systems-view`, `workflows-view`, `alerts-view`, `ai-drawer`) plus `command-palette.ts` dynamically imported (`import(...)`) so initial core JS stays minimal.
- Every view/panel with timers, DOM window listeners, xterm instances, or dynamic WS channels **must** register teardown via `registerViewCleanup()` (`state.ts`, flushed on navigation by `main.ts`) and use ref-counted `wsClient.subscribe()` cleanup callbacks (which send `{ type: 'unsub' }` when refcount hits 0).
### 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 `<meta name="theme-color">`). 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 `<pre>` 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.