29 KiB
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-hopProxyJumpforwarding, 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-GCMcredential 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/*.jsondiscovery/status/actions, Full-DAGworkflows/*.json, fleet broadcast, cross-server transfers, webhook alerting, portable.gcoord.encbackups, and an opt-in BYO-API OpenAI-compatible AI assistant.
All 5 phases of 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 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, andnpxlive in~/.local/bin. Always prepend PATH in non-login shells:export PATH="$HOME/.local/bin:$PATH" - Containers & Docker Helper Scripts:
dockerCLI is not installed in this dev container;docker/Dockerfile,docker/docker-compose.yml, anddocker/docker-compose.lan.ymlare deployment definitions configured via.env(see.env.example) and helper scripts underscripts/(setup.sh,build.sh,up.sh,down.sh,logs.sh,cli.sh).
NPM Scripts (package.json)
npm run typecheck—tsc --noEmit(strict TypeScript withnoUncheckedIndexedAccess: trueandnoImplicitOverride: true).npm run build:client—tsx src/client/build.ts(bundles ES2020 client modules + CSS intodist/public/and enforces gzip budgets recursively acrossmain.jsstatic imports and lazy chunks).npm run build:server—esbuildbundlesdist/server/index.jsanddist/cli/gcoord.js(--platform=node --target=node22 --format=esm --packages=external).npm run build— runstypecheck && build:client && build:server.npm test—vitest run(runs all 21 unit/E2E suites, 41 tests using in-process HTTP servers andMockSshServer).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(requiresnpm run buildfirst sodist/public/anddist/server/exist).
CLI (src/cli/gcoord.ts -> dist/cli/gcoord.js)
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-created0600atdata/db.key).GCOORD_AUTO_KEYFILE— set'true'to mirror an env/secret Vault key into localdata/vault.key(0600).GCOORD_BACKUP_PASSPHRASE— optional passphrase for.gcoord.encCLI operations.TRUST_CLOUDFLARE— set'true'to trust proxy headers fromTRUSTED_PROXY_CIDRS/ loopback and honorCF-Connecting-IPin 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 PrometheusGET /metrics.GCOORD_THROTTLE_MODE— runtime throttle profile override:'low-resource'|'balanced'|'unthrottled'(overridessettings.runtime.throttleMode).
3. Repository Map
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.isRuntimeReadyis decoupled fromvaultService.state === 'unlocked'.- At server startup (
initRuntimeinsrc/server/app.ts), established secrets are decrypted into memory usingsecretFilePath,GCOORD_MASTER_KEY,data/vault.key(0600), ordata/recovery/emergency-secrets.json, whilestatebegins'locked'(write-locked).data/vault.keyis only written for locally generated keys (never mirroringGCOORD_MASTER_KEYor Docker secrets unlessGCOORD_AUTO_KEYFILE=true). - Background and established-secret consumers (
SSHPool,MonitoringService,TunnelManager,CustomSystemsEngine,WorkflowEngine,AlertEngine,AiService,BackupScheduler,/api/backup/export) must checkisRuntimeReadyand read credentials viagetRuntimeSecret(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 withHTTP 423 VAULT_LOCKED(intercepted bysrc/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 avault.panic_locksecurity 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_totpsencrypted at rest withdata/db.key/GCOORD_DB_KEYusingAES-256-GCM, plus single-use TOTP replay tracking) evaluated inanyorallmode, single-use recovery codes, rate-limited bootstrap (15mtoken TTL), and@simplewebauthn/serverPasskeys (webauthn_credentials; raw IP literals returnWEBAUTHN_RPID_INVALID). - Sessions enforce both absolute
sessionTtlHoursand slidingsessionIdleTimeoutMin; revoking sessions via logout, password reset, key/2FA reset, or Panic Lock broadcasts real-timeWS 4001disconnects throughWsHub. RateLimiteris SQLite-backed (rate_limitstable) to persist lockouts across restarts, andattachClientIp/ Expresstrust proxyonly honor forwarding headers when the socket peer matchesTRUSTED_PROXY_CIDRS(plus loopback whenTRUST_CLOUDFLARE=true).SecuritySettingsSchema(src/shared/schemas/settings.schema.ts) configuresrequireTotpOnLogin,stepUpPolicy(off | every-action | 5m | 15m | 1h | 24h | session, default15m),stepUpMethod(totp | password | both | passkey),elevateOnLogin, andkeepElevationOnSafeMode. Always gate elevated endpoints withcreateStepUpGuard.- Mutating HTTP routes require an authenticated session cookie, matching
X-CSRF-Token, and Safe Mode enforcement (HTTP 423 SAFE_MODE_ACTIVE; mobile< 768pxdefaults 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): Whensettings.security.enableEmergencySecretsBackupis enabled,EmergencyRecoveryServicemaintains a passwordlessdata/recovery/emergency-secrets.json(chmod 0600, Vault/key/TOTP recovery data only—never stores plaintext admin login passwords) plus up to 10 snapshots underdata/recovery/snapshots/. KeepsyncRecovery()wired after auth/vault mutations. - Portable Encrypted Bundles (
backup.ts&backup-scheduler.ts): Creates, verifies, and restoresGCOORD_BACKUP_V1.gcoord.encbundles encrypted withAES-256-GCM(raw-master-keyorscryptpassphrase KDF) via non-blocking async workers (createBackupBundleAsync) bounded byruntimeLimits, plus scheduled local/SFTP backups with retention pruning. - Linux
inotifyRule on Config Restore: Whenever replacingdata/config/while running (/api/backup/restore), always callconfigManager.pauseWatcher()before replacing the directory andreloadAllFromDisk()+await configManager.resumeWatcher()afterward sochokidarre-attaches cleanly to new directory inodes.
4. Runtime Throttle Profile & Lightweight Footprint (runtime-limits.ts, settings.schema.ts)
settings.runtime.throttleModedefaults to'low-resource'(sized for single-core 1 vCPU / 1 GB RAM + 2 GB Swap deployments) and supports'balanced'and'unthrottled'(overrideable viaGCOORD_THROTTLE_MODE).resolveRuntimeLimits()governs Argon2id memory/concurrency/queueing (piscina/mutex semaphore),scryptconcurrency, 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 viagetRuntimeLimits()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 recordsconfig_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 as006_*.tsand register them insrc/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, workflowhttpsteps) must go throughfetchWithEgressGuard()/assertSafeEgressUrl(), which default-denies loopback, private, link-local, carrier-grade NAT, and cloud-metadata IPs/DNS resolutions, disables automatic redirects (redirect: 'error'), and honors explicitsettings.security.egressAllowedCidrsopt-ins. - No Shell Injection: Never interpolate user inputs, workflow variables, or PTY
cwddirectly into shell strings. Pass inputs viaGCOORD_*environment variables (buildWorkflowEnv,GCOORD_PARAM_*) or sanitize explicitly withinterpolateShellCommandSafe()(template.ts),formatRemoteCd()(pty-manager.ts), and POSIX single-quoting (sudo.ts, zeroizing passwordBuffers immediately after writing). - Direct
rsync&ssh2Invariants: Generate Ed25519 keys viagenerateValidEd25519KeyPair()(vault.ts), validate all host-key algorithms inknown-hosts.ts, drain SSH channelstdout/stderrstreams inTransferEngine, and enforce symlink-safelstatchecks insftp-service.ts. - Dual-Mode Isolated Reverse Proxy (
tunnel-manager.ts,app.ts):- Prefer origin-isolated proxying via
GCOORD_PROXY_PORT(dedicated local port) orGCOORD_PROXY_BASE_DOMAIN(wildcard subdomain), bridged via single-use/proxy-ticketredemption into a proxy-scopedgcoord_proxy_sidsession so proxied target apps cannot share hub origin cookies or storage. - Same-origin
/proxyrequests are rejected withHTTP 403 PROXY_ISOLATION_NOT_CONFIGUREDunlesssettings.security.allowSameOriginProxy: trueis explicitly enabled. - Keep
/proxymounted beforeexpress.json(), exempt/proxy/*from the hub CSP, stripgcoord_sid/gcoord_csrf/gcoord_proxy_sidcookies upstream, rewrite relativeLocationredirects, and support HTTPS upstream, SOCKS5 (mode: 'socks5'), and TTL auto-expiry.
- Prefer origin-isolated proxying via
7. Alerts, Prometheus /metrics & BYO-API AI (alerts/, prometheus.ts, ai/)
- Alert channels strictly allow only
webhook-secretVault credential IDs (preventing arbitrary Vault credential exfiltration in webhook headers/bodies) and dispatchsecurity-eventalerts emitted by Auth, KnownHosts, and Vault Panic Lock. - Prometheus
GET /metrics(prometheus.ts) is opt-in (settings.metrics.prometheusEnabled) and Bearer-authenticated againstGCOORD_METRICS_TOKEN, the rotated SHA-256 token hash fromPOST /api/config/prometheus-token, or a Vaultapi-token/webhook-secretref (404when disabled,401when unauthenticated). - AI Assistant (
src/server/ai/): opt-in (403 AI_DISABLEDwhen disabled), linear-timeO(n)secret redaction (redactor.ts), and mandatory server ZodvalidateDraft+ 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 ofmain.js): strictly< 50.00 KBgzipped (currently15.80 KB). - Every non-terminal lazy chunk (
dist/public/chunks/*.jsexceptterminal-view-*): strictly< 20.00 KBgzipped.
CRITICAL: Zero Runtime zod & View Lifecycle in Client Code
- NEVER import runtime schemas or runtime values from
src/shared/schemas/*orzodanywhere insidesrc/client/ts/**. Useimport typeexclusively and mirror minimal constants cleanly insrc/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) pluscommand-palette.tsdynamically 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 bymain.ts) and use ref-countedwsClient.subscribe()cleanup callbacks (which send{ type: 'unsub' }when refcount hits 0).
Flat Sharp Aesthetic & 8 Themes
- Maintain the zero-overhead aesthetic:
border-radius: 0,1pxcrisp borders, zerobox-shadow, zero gradients, zerobackdrop-filter. - Keep all 8 themes (
phosphor-green,amber-term,nord-dark,gruvbox-dark,paper-light,solarized-dark,tokyo-night,high-contrast) in sync acrossTHEME_IDS(src/shared/schemas/settings.schema.ts),src/client/css/themes.css,CLIENT_THEME_IDS(src/client/ts/state.ts), andapplyTheme()(which updates<meta name="theme-color">). Note thatesbuildCSS 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.cssscoped totextarea:not(.xterm-helper-textarea)so.xterm-helper-textareastays0x0and does not overflow its container. - Preserve capture-phase sticky
Ctrl/Altinput handling andclearTerminalComposition()insrc/client/ts/views/xterm-runtime.tsso mobile IMEs (e.g., Firefox Android + Gboard) cannot leave ghost characters (likexafterCtrl+x). - Keep
.qr-boxsquare (align-self: flex-start; width: fit-content; line-height: 0). - Preserve
< 768px44pxminimum touch target heights on.btn-smand.input-sm,overscroll-behavior: containondialog:modalanddialog::backdrop,env(safe-area-inset-bottom)nav padding, viewport-capped chart history viamaxChartPointsForViewport(), andappendBoundedStreamText()for live<pre>stream logs.
6. Testing & Verification Workflow
- Write tests in
tests/*.test.tsusingcreateGCoordinatorServer({ dataDir: tmpDir, port: 0, ... })paired withMockSshServer(tests/helpers/mock-ssh-server.ts) for isolated HTTP +/ws+ SSH/SFTP/PTY/ProxyJump/Tunnel testing without external daemons. Always clean up temp directories andawait instance.close()/await mockSsh.stop()infinallyorafterEach. - Before concluding any code change:
export PATH="$HOME/.local/bin:$PATH" npm run build && npm test - Inspect
git statusandgit diffafter edits to confirm clean diffs, untouched unrelated docs/comments, and passing typechecks, bundle budgets, and all Vitest tests.