diff --git a/How/AGENTS.md b/How/AGENTS.md index 21137d6..d6e7f91 100644 --- a/How/AGENTS.md +++ b/How/AGENTS.md @@ -12,9 +12,9 @@ - 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). +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 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.** +**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.** --- @@ -29,19 +29,23 @@ All 5 phases of [Plan.md](file:///home/devuser/workspace/GCoordinator/How/Plan.m ### 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: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 18 unit/E2E suites in ~5s using in-process HTTP servers and `MockSshServer`). +- `npm test` — `vitest run` (runs all 21 unit/E2E suites, 41 tests 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 status [--data-dir ] [--json] +node dist/cli/gcoord.js panic-lock [--data-dir ] +node dist/cli/gcoord.js reset-2fa [--data-dir ] [--disable] [--json] +node dist/cli/gcoord.js reset-password [--data-dir ] [--password-file ] 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 verify-backup [--bundle ] [--data-dir ] [--key-file ] [--passphrase-file ] [--vault-key-file ] [--json] node dist/cli/gcoord.js restore [--bundle ] [--data-dir ] [--key-file ] [--passphrase-file ] [--vault-key-file ] ``` @@ -51,8 +55,18 @@ node dist/cli/gcoord.js restore [--bundle ] [--data-dir - `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 enable `app.set('trust proxy', 1)` and honor `CF-Connecting-IP` in rate limiting. +- `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`). --- @@ -69,7 +83,7 @@ GCoordinator/ │ └── docker-compose.lan.yml ├── src/ │ ├── cli/ -│ │ └── gcoord.ts # rotate-key, backup, verify-backup, restore 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 @@ -85,76 +99,84 @@ GCoordinator/ │ │ └── vault.schema.ts │ ├── server/ │ │ ├── index.ts # Process bootstrap & SIGINT/SIGTERM graceful shutdown -│ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock +│ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock, /metrics │ │ ├── db/ -│ │ │ ├── database.ts # SQLite WAL connection & ordered migration runner -│ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts +│ │ │ ├── database.ts # SQLite WAL connection, throttle PRAGMAs & ordered migration runner +│ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts, 004_v1_1.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 +│ │ │ ├── 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) +│ │ │ ├── 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) -│ │ │ ├── known-hosts.ts # KnownHostsService (strict TOFU, MITM guard, replaceAllKnownHosts) +│ │ │ ├── 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 & 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) +│ │ │ ├── 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 +│ │ │ ├── collectors.ts # OS-aware LinuxCollector, BSDCollector, MacOSCollector (+ net/disk I/O) │ │ │ ├── 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) +│ │ │ ├── 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 (TTL cache, overlays, 3x3 scoped/moded actions) +│ │ │ └── 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 (128 KB circular WS replay ring) +│ │ │ ├── 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 scheduler, croner, event triggers, dry-run) -│ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet command execution) +│ │ │ ├── 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 rules, silences, webhooks) +│ │ │ └── alert-engine.ts # AlertEngine (metric/disk/offline/probe/system/security-event, egress-guarded webhooks) │ │ ├── ai/ -│ │ │ ├── redactor.ts # collectVaultSecretStrings & redactSecrets +│ │ │ ├── redactor.ts # Linear O(n) collectVaultSecretStrings & redactSecrets │ │ │ ├── guides.ts # AiSurfaceSchema & buildSurfaceGuideAndInventory -│ │ │ └── ai-service.ts # AiService (opt-in /v1/chat/completions, WS streaming, Zod draft check) +│ │ │ └── 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, replay) +│ │ ├── 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 + gzip budget assertions +│ ├── 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 styles, mobile <768px rules +│ │ └── base.css # Flat sharp styles, dialog/drawer/toast/palette 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 +│ ├── 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 -│ ├── dialogs.ts # Native modals (multi-factor step-up, confirm, prompts) -│ ├── charts.ts # Flat SVG sparklines & metric charts (viewport-capped points) +│ ├── ws-client.ts # Reconnecting /ws client with ref-counted subscribe()/unsubscribe +│ ├── dialogs.ts # Native 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 -│ └── views/ -│ ├── auth-view.ts # Core static views +│ ├── 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 -│ ├── terminal-view.ts # Code-split lazy views (keep dynamically imported!) +│ ├── settings-ops-panel.ts +│ ├── terminal-view.ts │ ├── xterm-runtime.ts │ ├── sftp-view.ts │ ├── tunnels-panel.ts @@ -164,56 +186,67 @@ GCoordinator/ │ └── 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 + └── *.test.ts # 21 Vitest integration & unit suites ``` --- ## 4. Critical Architectural Invariants (Must Preserve) -### 1. Runtime-Ready Secrets vs. Write-Only Vault Lock (`vault.ts`) +### 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). -- 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. +- 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`) 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. +- 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` 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. +### 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. 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`. +### 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. 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. +### 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`) destructively; add new schema changes as `005_*.ts` and register them in `src/server/db/database.ts`. -### 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`. +### 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`): strictly **`< 50.00 KB` gzipped** (currently `25.46 KB`). +- **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` 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(...)`. +### 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`. diff --git a/package-lock.json b/package-lock.json index 010f476..d020f50 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gcoordinator", - "version": "0.1.0", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gcoordinator", - "version": "0.1.0", + "version": "1.1.0", "dependencies": { "@simplewebauthn/server": "^13.1.1", "@xterm/addon-fit": "^0.11.0", diff --git a/package.json b/package.json index 24db5a4..ac93c5f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gcoordinator", - "version": "0.1.0", + "version": "1.1.0", "description": "Self-hosted, security-first central sysadmin hub for multiplexed SSH access, monitoring, custom systems, workflows, and alerting.", "type": "module", "engines": {