diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 98b322b..0000000 --- a/.dockerignore +++ /dev/null @@ -1,12 +0,0 @@ -node_modules/ -dist/ -data/ -docker/secrets/ -.git/ -.env -.env.* -*.gcoord.enc -*.tsbuildinfo -coverage/ -tests/ -.DS_Store diff --git a/How/AGENTS.md b/How/AGENTS.md index d6e7f91..21137d6 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 **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. +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 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.** +**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.** --- @@ -29,23 +29,19 @@ 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 recursively across `main.js` static imports and lazy chunks). +- `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 21 unit/E2E suites, 41 tests using in-process HTTP servers and `MockSshServer`). +- `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 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 ] [--data-dir ] [--key-file ] [--passphrase-file ] [--vault-key-file ] [--json] +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 ] ``` @@ -55,18 +51,8 @@ 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 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`). +- `TRUST_CLOUDFLARE` — set `'true'` to enable `app.set('trust proxy', 1)` and honor `CF-Connecting-IP` in rate limiting. --- @@ -83,7 +69,7 @@ GCoordinator/ │ └── docker-compose.lan.yml ├── src/ │ ├── cli/ -│ │ └── gcoord.ts # status, panic-lock, reset-2fa, reset-password, rotate-key, backup, verify-backup, restore +│ │ └── 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 @@ -99,84 +85,76 @@ GCoordinator/ │ │ └── vault.schema.ts │ ├── server/ │ │ ├── index.ts # Process bootstrap & SIGINT/SIGTERM graceful shutdown -│ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock, /metrics +│ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock │ │ ├── db/ -│ │ │ ├── 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 +│ │ │ ├── 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, 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 +│ │ │ ├── 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, symlink guard) -│ │ │ ├── runtime-limits.ts # Throttle profile presets (low-resource | balanced | unthrottled) +│ │ │ ├── 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) -│ │ │ ├── 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) +│ │ │ ├── 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, 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) +│ │ │ ├── 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 (+ net/disk I/O) +│ │ │ ├── collectors.ts # OS-aware LinuxCollector, BSDCollector, MacOSCollector │ │ │ ├── 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 +│ │ │ ├── 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 (bounded TTL cache, overlays, editableFiles, action inputs) +│ │ │ └── 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 (capped circular WS replay ring) +│ │ │ ├── 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, retries, http/notify steps, croner, secret inputs) -│ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet execution + SQLite history & CSV) +│ │ │ ├── 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/security-event, egress-guarded webhooks) +│ │ │ └── alert-engine.ts # AlertEngine (metric/disk/offline/probe/system rules, silences, webhooks) │ │ ├── ai/ -│ │ │ ├── redactor.ts # Linear O(n) collectVaultSecretStrings & redactSecrets +│ │ │ ├── redactor.ts # collectVaultSecretStrings & redactSecrets │ │ │ ├── guides.ts # AiSurfaceSchema & buildSurfaceGuideAndInventory -│ │ │ └── ai-service.ts # AiService (opt-in egress-guarded /v1/chat/completions, WS streaming, Zod draft check) +│ │ │ └── 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, real-time close 4001) +│ │ ├── 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 + recursive sync-core & lazy-chunk gzip assertions +│ ├── 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/toast/palette styles, mobile <768px rules +│ │ └── base.css # Flat sharp styles, dialog/drawer 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 +│ ├── 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 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) +│ ├── 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 -│ ├── command-palette.ts # Code-split Ctrl/Cmd+K quick switcher & action palette -│ └── views/ # All views dynamically code-split via import(...) -│ ├── auth-view.ts +│ └── views/ +│ ├── auth-view.ts # Core static views │ ├── dashboard-view.ts │ ├── server-detail-view.ts │ ├── vault-view.ts │ ├── config-view.ts │ ├── settings-view.ts -│ ├── settings-ops-panel.ts -│ ├── terminal-view.ts +│ ├── terminal-view.ts # Code-split lazy views (keep dynamically imported!) │ ├── xterm-runtime.ts │ ├── sftp-view.ts │ ├── tunnels-panel.ts @@ -186,67 +164,56 @@ GCoordinator/ │ └── 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 + └── *.test.ts # 18 Vitest integration & unit suites ``` --- ## 4. Critical Architectural Invariants (Must Preserve) -### 1. Runtime-Ready Secrets, `seal()` & Panic Lock (`vault.ts`) +### 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). `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. +- 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`), 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`). +- 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`, `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. +### 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. 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. +### 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. 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`. +### 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. 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. +### 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` + all recursive static ESM imports of `main.js`): strictly **`< 50.00 KB` gzipped** (currently `15.80 KB`). +- **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` & 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). +### 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`. diff --git a/docker/Dockerfile b/docker/Dockerfile index f2993fc..c473dcc 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -18,21 +18,19 @@ FROM node:22-bookworm-slim AS runtime WORKDIR /app RUN apt-get update && apt-get install -y --no-install-recommends \ - ca-certificates \ + ca-certificates openssh-client rsync zstd tar \ && rm -rf /var/lib/apt/lists/* \ - && mkdir -p /data && chown 1000:1000 /data && chmod 0700 /data + && mkdir -p /data && chown -R 1000:1000 /app /data -COPY --from=builder /app/package.json ./ -COPY --from=builder /app/node_modules ./node_modules -COPY --from=builder /app/dist ./dist +COPY --from=builder --chown=1000:1000 /app/package.json ./ +COPY --from=builder --chown=1000:1000 /app/node_modules ./node_modules +COPY --from=builder --chown=1000:1000 /app/dist ./dist USER 1000:1000 ENV NODE_ENV=production \ PORT=3000 \ - HOST=0.0.0.0 \ - GCOORD_DATA_DIR=/data \ - NODE_OPTIONS="--max-old-space-size=384" + GCOORD_DATA_DIR=/data EXPOSE 3000 diff --git a/docker/docker-compose.lan.yml b/docker/docker-compose.lan.yml index 2ccd7dc..1b38964 100644 --- a/docker/docker-compose.lan.yml +++ b/docker/docker-compose.lan.yml @@ -2,7 +2,6 @@ services: gcoordinator: environment: - TRUST_CLOUDFLARE=false - - GCOORD_ALLOW_LAN_TUNNELS=${GCOORD_ALLOW_LAN_TUNNELS:-false} ports: - "${GCOORD_LAN_BIND:-127.0.0.1}:3000:3000" - "${GCOORD_LAN_BIND:-127.0.0.1}:20000-20020:20000-20020" diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 15a1e1f..5451cf0 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -7,22 +7,13 @@ services: restart: unless-stopped user: "1000:1000" read_only: true - cap_drop: - - ALL - security_opt: - - no-new-privileges:true - mem_limit: ${GCOORD_MEM_LIMIT:-512m} - pids_limit: 128 tmpfs: - - /tmp:rw,noexec,nosuid,nodev,size=64m + - /tmp environment: - NODE_ENV=production - PORT=3000 - - HOST=0.0.0.0 - GCOORD_DATA_DIR=/data - TRUST_CLOUDFLARE=true - - GCOORD_THROTTLE_MODE=${GCOORD_THROTTLE_MODE:-low-resource} - - NODE_OPTIONS=--max-old-space-size=${GCOORD_NODE_MAX_OLD_SPACE:-384} secrets: - gcoord_master_key volumes: @@ -35,13 +26,6 @@ services: image: cloudflare/cloudflared:latest container_name: gcoordinator-tunnel restart: unless-stopped - read_only: true - cap_drop: - - ALL - security_opt: - - no-new-privileges:true - mem_limit: 128m - pids_limit: 64 command: tunnel --no-autoupdate run environment: - TUNNEL_TOKEN=${CLOUDFLARED_TUNNEL_TOKEN} diff --git a/package-lock.json b/package-lock.json index d020f50..010f476 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gcoordinator", - "version": "1.1.0", + "version": "0.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gcoordinator", - "version": "1.1.0", + "version": "0.1.0", "dependencies": { "@simplewebauthn/server": "^13.1.1", "@xterm/addon-fit": "^0.11.0", diff --git a/package.json b/package.json index ac93c5f..24db5a4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gcoordinator", - "version": "1.1.0", + "version": "0.1.0", "description": "Self-hosted, security-first central sysadmin hub for multiplexed SSH access, monitoring, custom systems, workflows, and alerting.", "type": "module", "engines": { diff --git a/src/cli/gcoord.ts b/src/cli/gcoord.ts index c38df01..ef67f22 100644 --- a/src/cli/gcoord.ts +++ b/src/cli/gcoord.ts @@ -1,16 +1,7 @@ -import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import readline from 'node:readline/promises'; import { parseArgs } from 'node:util'; -import argon2 from 'argon2'; -import Database from 'better-sqlite3'; -import * as OTPAuth from 'otpauth'; -import { openDatabase } from '../server/db/database.js'; -import { - encryptTotpSecret, - loadOrCreateDbKey, -} from '../server/security/auth.js'; import { createBackupBundle, restoreBackupBundle, @@ -18,42 +9,24 @@ import { } from '../server/security/backup.js'; import { EmergencyRecoveryService } from '../server/security/recovery-store.js'; import { VaultService } from '../server/security/vault.js'; -import { SettingsSchema } from '../shared/schemas/settings.schema.js'; function printUsage(): void { console.log(`GCoordinator CLI (gcoord) Commands: - status Inspect GCoordinator data directory state (read-only) - --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) - --json Print status summary as JSON - - panic-lock Engage Panic Lock offline: mark vault locked and revoke all sessions - --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) - - reset-2fa Reset TOTP authenticators offline (re-enroll new TOTP or disable 2FA) - --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) - --disable Disable requireTotpOnLogin and switch stepUpMethod to password - --json Print new secret & otpauth URI as JSON - - reset-password Reset the admin password offline (revokes all sessions & clears lockouts) - --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) - --password-file Read new password (>= 10 chars) from file instead of prompt - rotate-key Re-encrypt vault.enc atomically with a new 32-byte master key --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) --current-key-file Path to file containing current 32-byte key - --new-key-out Exclusive output file (0600, O_EXCL) for generated key + --new-key-out Optional output file (0600) for generated key backup Create an AES-256-GCM .gcoord.enc portable backup bundle --out Output bundle path (required) --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) --key-file Path to 32-byte Vault master key (default mode) - --passphrase-file Path to passphrase file (>= 12 chars, uses scrypt) + --passphrase-file Path to passphrase file (overrides key-file using scrypt) verify-backup Verify GCM tag, JSON schemas, and Vault envelope without modifying data Backup bundle path (or --bundle ) - --data-dir Data directory fallback for vault.key lookup --key-file Path to 32-byte master key --passphrase-file Path to backup passphrase file --vault-key-file Optional Vault master key to also decrypt/verify vault.enc @@ -68,153 +41,7 @@ Commands: `); } -function readRegularFileStrict(filePath: string): string { - const abs = path.resolve(filePath); - const stat = fs.lstatSync(abs); - if (stat.isSymbolicLink() || !stat.isFile()) { - throw new Error(`Refusing symlink or non-file path: ${abs}`); - } - return fs.readFileSync(abs, 'utf8').trim(); -} - -function writeAtomicSecureFile(targetPath: string, content: string): void { - const abs = path.resolve(targetPath); - try { - const stat = fs.lstatSync(abs); - if (stat.isSymbolicLink()) { - throw new Error(`Refusing to overwrite symlink at ${abs}`); - } - } catch (err) { - if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') throw err; - } - - fs.mkdirSync(path.dirname(abs), { recursive: true, mode: 0o700 }); - const tmpPath = `${abs}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; - const fd = fs.openSync(tmpPath, 'w', 0o600); - try { - fs.writeFileSync(fd, content, 'utf8'); - fs.fsyncSync(fd); - } finally { - fs.closeSync(fd); - } - try { - fs.renameSync(tmpPath, abs); - fs.chmodSync(abs, 0o600); - } catch (err) { - try { - fs.unlinkSync(tmpPath); - } catch { - // Ignore cleanup error - } - throw err; - } -} - -function writeExclusiveSecureFile(targetPath: string, content: string): void { - const abs = path.resolve(targetPath); - fs.mkdirSync(path.dirname(abs), { recursive: true, mode: 0o700 }); - const fd = fs.openSync( - abs, - fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, - 0o600, - ); - try { - fs.writeFileSync(fd, content, 'utf8'); - fs.fsyncSync(fd); - } finally { - fs.closeSync(fd); - } -} - -function isPidAlive(pid: number): boolean { - if (!Number.isInteger(pid) || pid <= 0) return false; - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - -async function withDataDirLock(dataDir: string, fn: () => Promise): Promise { - const absDir = path.resolve(dataDir); - fs.mkdirSync(absDir, { recursive: true, mode: 0o700 }); - const lockPath = path.join(absDir, 'gcoord.lock'); - - const tryAcquire = (): number => - fs.openSync( - lockPath, - fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, - 0o600, - ); - - let fd: number; - try { - fd = tryAcquire(); - } catch (err) { - if ((err as NodeJS.ErrnoException)?.code !== 'EEXIST') throw err; - const raw = fs.readFileSync(lockPath, 'utf8'); - const existingPid = Number.parseInt(raw.split(/\r?\n/)[0] ?? '', 10); - if (isPidAlive(existingPid)) { - throw new Error(`Another gcoord CLI command (PID ${existingPid}) holds ${lockPath}`); - } - fs.rmSync(lockPath, { force: true }); - fd = tryAcquire(); - } - - try { - fs.writeFileSync(fd, `${process.pid}\n${Date.now()}\n`, 'utf8'); - fs.closeSync(fd); - return await fn(); - } finally { - fs.rmSync(lockPath, { force: true }); - } -} - async function promptHiddenOrLine(promptText: string): Promise { - if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') { - process.stderr.write(promptText); - const wasRaw = Boolean(process.stdin.isRaw); - process.stdin.setRawMode(true); - process.stdin.resume(); - - return new Promise((resolve, reject) => { - let buf = ''; - const cleanup = () => { - process.stdin.off('data', onData); - try { - process.stdin.setRawMode(wasRaw); - } catch { - // Ignore restore error - } - process.stdin.pause(); - }; - const onData = (chunk: Buffer) => { - const text = chunk.toString('utf8'); - for (const ch of text) { - if (ch === '\u0003') { - cleanup(); - process.stderr.write('\n'); - reject(new Error('Aborted by user')); - return; - } - if (ch === '\r' || ch === '\n') { - cleanup(); - process.stderr.write('\n'); - resolve(buf.trim()); - return; - } - if (ch === '\u007f' || ch === '\b') { - if (buf.length > 0) buf = buf.slice(0, -1); - continue; - } - buf += ch; - } - }; - process.stdin.on('data', onData); - }); - } - const rl = readline.createInterface({ input: process.stdin, output: process.stderr, @@ -229,19 +56,18 @@ async function promptHiddenOrLine(promptText: string): Promise { async function readCurrentKey(keyFile?: string, dataDir?: string): Promise { if (keyFile) { - return readRegularFileStrict(keyFile); + return fs.readFileSync(keyFile, 'utf8').trim(); } if (process.env.GCOORD_MASTER_KEY?.trim()) { return process.env.GCOORD_MASTER_KEY.trim(); } - const secretPath = process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; - if (fs.existsSync(secretPath)) { - return readRegularFileStrict(secretPath); + if (fs.existsSync('/run/secrets/gcoord_master_key')) { + return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim(); } if (dataDir) { const localKeyFile = path.join(path.resolve(dataDir), 'vault.key'); if (fs.existsSync(localKeyFile)) { - return readRegularFileStrict(localKeyFile); + return fs.readFileSync(localKeyFile, 'utf8').trim(); } } return promptHiddenOrLine('Enter current 32-byte vault master key (hex or base64): '); @@ -249,19 +75,18 @@ async function readCurrentKey(keyFile?: string, dataDir?: string): Promise { - const settingsPath = path.join(dataDir, 'config', 'settings.json'); - if (!fs.existsSync(settingsPath)) return SettingsSchema.parse({}); - return SettingsSchema.parse(JSON.parse(readRegularFileStrict(settingsPath))); -} - -async function runStatus(args: string[]): Promise { - const parsed = parseArgs({ - args, - options: { - 'data-dir': { type: 'string' }, - json: { type: 'boolean', default: false }, - }, - allowPositionals: false, - }); - - const dataDir = path.resolve( - parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', - ); - const dbPath = path.join(dataDir, 'gcoord.db'); - const vaultPath = path.join(dataDir, 'vault.enc'); - const vaultKeyPath = path.join(dataDir, 'vault.key'); - const dbKeyPath = path.join(dataDir, 'db.key'); - const panicMarkerPath = `${vaultPath}.panic-locked`; - - const status: Record = { - dataDir, - dataDirExists: fs.existsSync(dataDir), - vaultInitialized: fs.existsSync(vaultPath), - panicLocked: fs.existsSync(panicMarkerPath), - localVaultKeyFile: fs.existsSync(vaultKeyPath), - localDbKeyFile: fs.existsSync(dbKeyPath), - dbInitialized: fs.existsSync(dbPath), - }; - - if (fs.existsSync(dbPath)) { - const roDb = new Database(dbPath, { readonly: true }); - try { - const admin = roDb - .prepare('SELECT username FROM admin_users WHERE id = 1') - .get() as { username: string } | undefined; - const now = Date.now(); - const pwCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM admin_passwords').get() as { cnt: number }).cnt; - const totpCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM admin_totps').get() as { cnt: number }).cnt; - const passkeyCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM webauthn_credentials').get() as { cnt: number }).cnt; - const activeSessions = ( - roDb.prepare('SELECT COUNT(*) AS cnt FROM sessions WHERE expires_at > ?').get(now) as { cnt: number } - ).cnt; - const auditCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM audit_log').get() as { cnt: number }).cnt; - let activeLockouts = 0; - try { - activeLockouts = ( - roDb.prepare('SELECT COUNT(*) AS cnt FROM rate_limits WHERE locked_until > ?').get(now) as { cnt: number } - ).cnt; - } catch { - activeLockouts = 0; - } - - Object.assign(status, { - bootstrapped: Boolean(admin), - username: admin?.username ?? null, - passwordCount: pwCount, - totpCount, - passkeyCount, - activeSessions, - activeLockouts, - auditLogRows: auditCount, - }); - } finally { - roDb.close(); - } - } - - if (parsed.values.json) { - console.log(JSON.stringify(status, null, 2)); - } else { - console.log( - `GCoordinator status (${dataDir}): vault=${status.vaultInitialized ? (status.panicLocked ? 'panic-locked' : 'present') : 'uninitialized'}, db=${status.dbInitialized ? 'present' : 'missing'}, bootstrapped=${Boolean(status.bootstrapped)}, sessions=${String(status.activeSessions ?? 0)}, auditRows=${String(status.auditLogRows ?? 0)}`, - ); - } - return 0; -} - -async function runPanicLock(args: string[]): Promise { - const parsed = parseArgs({ - args, - options: { - 'data-dir': { type: 'string' }, - }, - allowPositionals: false, - }); - - const dataDir = path.resolve( - parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', - ); - if (!fs.existsSync(dataDir)) { - console.error(`Error: Data directory not found at ${dataDir}`); - return 1; - } - - return withDataDirLock(dataDir, async () => { - const markerPath = path.join(dataDir, 'vault.enc.panic-locked'); - writeAtomicSecureFile(markerPath, `${Date.now()}\n`); - - const dbPath = path.join(dataDir, 'gcoord.db'); - let revoked = 0; - if (fs.existsSync(dbPath)) { - const db = openDatabase(dbPath); - try { - revoked = db.prepare('DELETE FROM sessions').run().changes; - db.prepare( - 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, ?)', - ).run(Date.now(), 'security.cli_panic_lock', 'cli', 'vault', 'ok', JSON.stringify({ revoked })); - } finally { - db.close(); - } - } - - console.log(`Panic Lock engaged cleanly (marker=${markerPath}, revokedSessions=${revoked}).`); - return 0; - }); -} - -async function runReset2fa(args: string[]): Promise { - const parsed = parseArgs({ - args, - options: { - 'data-dir': { type: 'string' }, - disable: { type: 'boolean', default: false }, - json: { type: 'boolean', default: false }, - }, - allowPositionals: false, - }); - - const dataDir = path.resolve( - parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', - ); - const dbPath = path.join(dataDir, 'gcoord.db'); - if (!fs.existsSync(dbPath)) { - console.error(`Error: Database not found at ${dbPath}`); - return 1; - } - - return withDataDirLock(dataDir, async () => { - const db = openDatabase(dbPath); - try { - const admin = db - .prepare('SELECT username FROM admin_users WHERE id = 1') - .get() as { username: string } | undefined; - if (!admin) { - console.error('Error: Admin account is not bootstrapped yet'); - return 1; - } - - if (parsed.values.disable) { - const settingsPath = path.join(dataDir, 'config', 'settings.json'); - const settings = loadSettingsObject(dataDir) as { - security?: Record; - [k: string]: unknown; - }; - const updated = SettingsSchema.parse({ - ...settings, - security: { - ...(settings.security ?? {}), - requireTotpOnLogin: false, - stepUpMethod: 'password', - }, - }); - writeAtomicSecureFile(settingsPath, `${JSON.stringify(updated, null, 2)}\n`); - - db.transaction(() => { - db.prepare('DELETE FROM admin_totps').run(); - db.prepare('DELETE FROM sessions').run(); - db.prepare('DELETE FROM rate_limits').run(); - db.prepare( - 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, NULL)', - ).run(Date.now(), 'auth.cli_reset_2fa_disable', 'cli', admin.username, 'ok'); - })(); - - console.log('TOTP 2FA disabled offline. Sessions revoked and rate limits cleared.'); - return 0; - } - - const dbKey = loadOrCreateDbKey({ dataDir, envDbKey: process.env.GCOORD_DB_KEY }); - const secret = new OTPAuth.Secret({ size: 20 }); - const id = `totp-${crypto.randomBytes(4).toString('hex')}`; - const enc = encryptTotpSecret(dbKey, id, secret.base32); - const now = Date.now(); - const otpauthUri = new OTPAuth.TOTP({ - issuer: 'GCoordinator', - label: `${admin.username} (CLI Reset)`, - algorithm: 'SHA1', - digits: 6, - period: 30, - secret, - }).toString(); - - db.transaction(() => { - db.prepare('DELETE FROM admin_totps').run(); - db.prepare( - `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) - VALUES (?, 'CLI Reset Authenticator', '', ?, NULL, NULL, NULL, ?)`, - ).run(id, enc, now); - db.prepare('DELETE FROM sessions').run(); - db.prepare('DELETE FROM rate_limits').run(); - db.prepare( - 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, ?)', - ).run(now, 'auth.cli_reset_2fa', 'cli', admin.username, 'ok', JSON.stringify({ totpId: id })); - })(); - - if (parsed.values.json) { - console.log( - JSON.stringify({ - reset: true, - username: admin.username, - totpId: id, - secretBase32: secret.base32, - otpauthUri, - }), - ); - } else { - console.log(`TOTP reset cleanly for "${admin.username}". Enroll this new authenticator secret:`); - console.log(`Secret (Base32): ${secret.base32}`); - console.log(`otpauth URI: ${otpauthUri}`); - } - return 0; - } finally { - db.close(); - } - }); -} - -async function runResetPassword(args: string[]): Promise { - const parsed = parseArgs({ - args, - options: { - 'data-dir': { type: 'string' }, - 'password-file': { type: 'string' }, - }, - allowPositionals: false, - }); - - const dataDir = path.resolve( - parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', - ); - const dbPath = path.join(dataDir, 'gcoord.db'); - if (!fs.existsSync(dbPath)) { - console.error(`Error: Database not found at ${dbPath}`); - return 1; - } - - return withDataDirLock(dataDir, async () => { - const newPassword = parsed.values['password-file'] - ? readRegularFileStrict(parsed.values['password-file']) - : await promptHiddenOrLine('Enter new admin password (>= 10 characters): '); - - if (newPassword.length < 10 || newPassword.length > 256) { - console.error('Error: Password must be between 10 and 256 characters'); - return 1; - } - - const db = openDatabase(dbPath); - try { - const admin = db - .prepare('SELECT username FROM admin_users WHERE id = 1') - .get() as { username: string } | undefined; - if (!admin) { - console.error('Error: Admin account is not bootstrapped yet'); - return 1; - } - - const hash = await argon2.hash(newPassword, { - type: argon2.argon2id, - memoryCost: 32768, - timeCost: 3, - parallelism: 1, - }); - const now = Date.now(); - - db.transaction(() => { - db.prepare('DELETE FROM admin_passwords').run(); - db.prepare( - 'INSERT INTO admin_passwords (id, label, password_hash, created_at) VALUES (?, ?, ?, ?)', - ).run('pw-primary', 'Primary Password', hash, now); - db.prepare("UPDATE admin_users SET password_hash = '', updated_at = ? WHERE id = 1").run( - now, - ); - db.prepare('DELETE FROM sessions').run(); - db.prepare('DELETE FROM rate_limits').run(); - db.prepare( - 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, NULL)', - ).run(now, 'auth.cli_reset_password', 'cli', admin.username, 'ok'); - })(); - - console.log( - `Admin password reset cleanly for "${admin.username}". All active sessions revoked.`, - ); - return 0; - } finally { - db.close(); - } - }); -} - async function runRotateKey(args: string[]): Promise { const parsed = parseArgs({ args, @@ -601,40 +122,32 @@ async function runRotateKey(args: string[]): Promise { return 1; } - return withDataDirLock(dataDir, async () => { - const currentKey = await readCurrentKey(parsed.values['current-key-file'], dataDir); - const vault = new VaultService(vaultPath, { - keyFilePath: path.join(dataDir, 'vault.key'), - }); - vault.unlock(currentKey); - const { generatedKeyHex } = vault.rotateMasterKey(); + const currentKey = await readCurrentKey(parsed.values['current-key-file']); + const vault = new VaultService(vaultPath); + vault.unlock(currentKey); + const { generatedKeyHex } = vault.rotateMasterKey(); - if (!generatedKeyHex) { - console.error('Error: Unexpected empty rotated key'); - return 1; - } + if (!generatedKeyHex) { + console.error('Error: Unexpected empty rotated key'); + return 1; + } - const recovery = new EmergencyRecoveryService(dataDir); - const settings = loadSettingsObject(dataDir) as { - security?: { enableEmergencySecretsBackup?: boolean }; - }; - if ( - settings.security?.enableEmergencySecretsBackup && - recovery.readBundle() !== null - ) { - recovery.syncState({ enabled: true, vault, snapshotReason: 'cli-rotate-key' }); - } + const recovery = new EmergencyRecoveryService(dataDir); + if (recovery.readBundle() !== null) { + recovery.syncState({ enabled: true, vault, snapshotReason: 'cli-rotate-key' }); + } - if (parsed.values['new-key-out']) { - const outPath = path.resolve(parsed.values['new-key-out']); - writeExclusiveSecureFile(outPath, `${generatedKeyHex}\n`); - console.log(`Vault master key rotated cleanly. New key written to ${outPath} (mode 0600).`); - } else { - console.log('Vault master key rotated cleanly. Store this new key securely:'); - console.log(generatedKeyHex); - } - return 0; - }); + if (parsed.values['new-key-out']) { + const outPath = path.resolve(parsed.values['new-key-out']); + fs.mkdirSync(path.dirname(outPath), { recursive: true }); + fs.writeFileSync(outPath, `${generatedKeyHex}\n`, { mode: 0o600 }); + fs.chmodSync(outPath, 0o600); + console.log(`Vault master key rotated cleanly. New key written to ${outPath} (mode 0600).`); + } else { + console.log('Vault master key rotated cleanly. Store this new key securely:'); + console.log(generatedKeyHex); + } + return 0; } async function runBackup(args: string[]): Promise { @@ -670,7 +183,17 @@ async function runBackup(args: string[]): Promise { }); const outPath = path.resolve(outRaw); - writeAtomicSecureFile(outPath, result.serialized); + fs.mkdirSync(path.dirname(outPath), { recursive: true }); + const tmpPath = `${outPath}.tmp.${process.pid}.${Date.now()}`; + const fd = fs.openSync(tmpPath, 'w', 0o600); + try { + fs.writeFileSync(fd, result.serialized, 'utf8'); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + fs.renameSync(tmpPath, outPath); + fs.chmodSync(outPath, 0o600); console.log( `Backup created at ${outPath} (kdf=${result.summary.kdf}, configs=${result.summary.configFileCount}, knownHosts=${result.summary.knownHostsCount}, vaultVerified=${result.summary.vaultVerified})`, @@ -683,7 +206,6 @@ async function runVerifyBackup(args: string[]): Promise { args, options: { bundle: { type: 'string' }, - 'data-dir': { type: 'string' }, 'key-file': { type: 'string' }, 'passphrase-file': { type: 'string' }, 'vault-key-file': { type: 'string' }, @@ -698,26 +220,17 @@ async function runVerifyBackup(args: string[]): Promise { return 1; } - const dataDir = parsed.values['data-dir'] - ? path.resolve(parsed.values['data-dir']) - : process.env.GCOORD_DATA_DIR - ? path.resolve(process.env.GCOORD_DATA_DIR) - : undefined; - - const bundlePath = path.resolve(bundleArg); - const rawBuf = Buffer.from(readRegularFileStrict(bundlePath), 'utf8'); + const rawBuf = fs.readFileSync(path.resolve(bundleArg)); const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']); - let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir); + let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file']); if (!passphrase && !masterKey) { const rawMeta = JSON.parse(rawBuf.toString('utf8')) as { kdf?: string }; if (rawMeta.kdf === 'scrypt') { - throw new Error( - 'Passphrase required for scrypt-encrypted backup (--passphrase-file or GCOORD_BACKUP_PASSPHRASE)', - ); + throw new Error('Passphrase required for scrypt-encrypted backup (--passphrase-file or GCOORD_BACKUP_PASSPHRASE)'); } - masterKey = await readCurrentKey(undefined, dataDir); + masterKey = await readCurrentKey(undefined); } - const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir); + const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file']); const summary = verifyBackupSummaryOnly(rawBuf, { masterKey, @@ -757,28 +270,25 @@ async function runRestore(args: string[]): Promise { const dataDir = path.resolve( parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', ); + const rawBuf = fs.readFileSync(path.resolve(bundleArg)); + const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']); + let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir); + if (!passphrase && !masterKey) { + masterKey = await readCurrentKey(undefined, dataDir); + } + const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir); - return withDataDirLock(dataDir, async () => { - const rawBuf = Buffer.from(readRegularFileStrict(bundleArg), 'utf8'); - const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']); - let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir); - if (!passphrase && !masterKey) { - masterKey = await readCurrentKey(undefined, dataDir); - } - const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir); - - const { summary } = restoreBackupBundle(rawBuf, { - dataDir, - masterKey, - passphrase, - vaultMasterKey, - }); - - console.log( - `Restored GCoordinator state to ${dataDir} (configs=${summary.configFileCount}, knownHosts=${summary.knownHostsCount}, silences=${summary.alertSilenceCount})`, - ); - return 0; + const { summary } = restoreBackupBundle(rawBuf, { + dataDir, + masterKey, + passphrase, + vaultMasterKey, }); + + console.log( + `Restored GCoordinator state to ${dataDir} (configs=${summary.configFileCount}, knownHosts=${summary.knownHostsCount}, silences=${summary.alertSilenceCount})`, + ); + return 0; } async function main(): Promise { @@ -788,25 +298,22 @@ async function main(): Promise { process.exit(0); } - const handlers: Record Promise> = { - status: runStatus, - 'panic-lock': runPanicLock, - 'reset-2fa': runReset2fa, - 'reset-password': runResetPassword, - 'rotate-key': runRotateKey, - backup: runBackup, - 'verify-backup': runVerifyBackup, - restore: runRestore, - }; - - const handler = handlers[command]; - if (!handler) { - console.error(`Unknown command: ${command}`); - printUsage(); - process.exit(1); + if (command === 'rotate-key') { + process.exit(await runRotateKey(rest)); + } + if (command === 'backup') { + process.exit(await runBackup(rest)); + } + if (command === 'verify-backup') { + process.exit(await runVerifyBackup(rest)); + } + if (command === 'restore') { + process.exit(await runRestore(rest)); } - process.exit(await handler(rest)); + console.error(`Unknown command: ${command}`); + printUsage(); + process.exit(1); } main().catch((err) => { diff --git a/src/client/build.ts b/src/client/build.ts index 6745406..e17addc 100644 --- a/src/client/build.ts +++ b/src/client/build.ts @@ -8,52 +8,17 @@ const LAZY_CHUNK_BUDGET_BYTES = 20 * 1024; const clientDir = path.resolve('src/client'); const outDir = path.resolve('dist/public'); -function normalizeOutKey(rawPath: string): string { - const rel = path.relative(outDir, path.resolve(rawPath)); - return rel.replace(/\\/g, '/'); -} - -function collectSyncImports( - metaOutputs: Record, - entryKey: string, -): string[] { - const visited = new Set(); - const queue: string[] = [entryKey]; - - while (queue.length > 0) { - const cur = queue.shift()!; - if (visited.has(cur)) continue; - visited.add(cur); - - const matchEntry = Object.entries(metaOutputs).find( - ([outPath]) => normalizeOutKey(outPath) === cur, - ); - if (!matchEntry) continue; - - for (const imp of matchEntry[1].imports) { - if (imp.kind !== 'import-statement') continue; - const targetKey = normalizeOutKey(imp.path); - if (!visited.has(targetKey)) { - queue.push(targetKey); - } - } - } - - return [...visited]; -} - async function buildClient(): Promise { fs.rmSync(outDir, { recursive: true, force: true }); fs.mkdirSync(outDir, { recursive: true }); - const jsResult = await esbuild.build({ + await esbuild.build({ entryPoints: [path.join(clientDir, 'ts', 'main.ts')], bundle: true, format: 'esm', splitting: true, minify: true, sourcemap: false, - metafile: true, target: 'es2020', outdir: outDir, entryNames: '[name]', @@ -81,22 +46,18 @@ async function buildClient(): Promise { fs.copyFileSync(path.join(clientDir, asset), path.join(outDir, asset)); } - const syncJsChunks = jsResult.metafile - ? collectSyncImports(jsResult.metafile.outputs, 'main.js').filter((k) => k !== 'main.js') - : []; - - const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js', ...syncJsChunks]; + const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js']; let totalRaw = 0; let totalGzip = 0; for (const file of coreAssets) { - const fullPath = path.join(outDir, file); - if (!fs.existsSync(fullPath)) continue; - const buf = fs.readFileSync(fullPath); + const buf = fs.readFileSync(path.join(outDir, file)); const gz = zlib.gzipSync(buf, { level: 9 }); totalRaw += buf.length; totalGzip += gz.length; - console.log(` ${file.padEnd(24)} raw=${buf.length}B gzip=${gz.length}B`); + console.log( + ` ${file.padEnd(14)} raw=${buf.length}B gzip=${gz.length}B`, + ); } const chunksDir = path.join(outDir, 'chunks'); @@ -104,8 +65,7 @@ async function buildClient(): Promise { for (const chunk of fs.readdirSync(chunksDir).sort()) { const cBuf = fs.readFileSync(path.join(chunksDir, chunk)); const cGz = zlib.gzipSync(cBuf, { level: 9 }); - const syncTag = syncJsChunks.includes(`chunks/${chunk}`) ? ' [sync-core]' : ''; - console.log(` chunks/${chunk.padEnd(28)} raw=${cBuf.length}B gzip=${cGz.length}B${syncTag}`); + console.log(` chunks/${chunk.padEnd(28)} raw=${cBuf.length}B gzip=${cGz.length}B`); if (!chunk.startsWith('terminal-view-') && cGz.length >= LAZY_CHUNK_BUDGET_BYTES) { throw new Error( `Lazy chunk ${chunk} (${cGz.length}B gzipped) exceeded 20KB budget (${LAZY_CHUNK_BUDGET_BYTES}B)`, diff --git a/src/client/css/base.css b/src/client/css/base.css index 41699fb..1077214 100644 --- a/src/client/css/base.css +++ b/src/client/css/base.css @@ -699,87 +699,3 @@ dialog.ai-drawer[open] { padding: 6px 10px; } } - -.sr-only-focusable:focus { - position: static; - width: auto; - height: auto; - overflow: visible; - clip: auto; - white-space: normal; - display: inline-block; - margin-bottom: 6px; - padding: 6px 10px; - border: 1px solid var(--accent); - background: var(--bg-panel); - color: var(--accent); -} - -.toast-region { - position: fixed; - right: 12px; - bottom: 12px; - z-index: 40; - display: flex; - flex-direction: column; - gap: 6px; - max-width: min(380px, calc(100vw - 24px)); - pointer-events: none; -} - -.toast-item { - pointer-events: auto; - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; - padding: 8px 10px; - border: 1px solid var(--border); - background: var(--bg-panel); - color: var(--fg); - font-size: 0.85rem; -} - -.toast-ok { - border-color: var(--ok); -} - -.toast-warn { - border-color: var(--warn); -} - -.toast-err { - border-color: var(--err); -} - -.cmd-palette-list { - display: flex; - flex-direction: column; - gap: 4px; - max-height: 55vh; - overflow-y: auto; - margin-top: 8px; -} - -.cmd-palette-item { - display: flex; - align-items: center; - justify-content: space-between; - width: 100%; - text-align: left; -} - -.cmd-palette-item.active { - border-color: var(--accent); - background: var(--bg-elevated); - color: var(--accent); -} - -.diff-hunk-sep { - padding: 2px 6px; - margin: 4px 0; - border-top: 1px dashed var(--border); - border-bottom: 1px dashed var(--border); - color: var(--fg-muted); - font-size: 0.78rem; -} diff --git a/src/client/index.html b/src/client/index.html index 5f92b1c..2484694 100644 --- a/src/client/index.html +++ b/src/client/index.html @@ -13,7 +13,6 @@
- Skip to main content
-

-
- -
- - - -
-

Command Palette

- -
- -
-
- diff --git a/src/client/ts/charts.ts b/src/client/ts/charts.ts index 36ed648..b4b79a1 100644 --- a/src/client/ts/charts.ts +++ b/src/client/ts/charts.ts @@ -97,44 +97,3 @@ export function createRangeChartSvg( svg.appendChild(poly); return svg; } - -export function createDualRangeChartSvg( - seriesA: number[], - seriesB: number[], - options: { colorA?: string; colorB?: string; maxVal?: number } = {}, -): SVGSVGElement { - const computedMax = - options.maxVal ?? - Math.max( - 1, - ...seriesA.map((v) => (Number.isFinite(v) ? v : 0)), - ...seriesB.map((v) => (Number.isFinite(v) ? v : 0)), - ); - - const svg = document.createElementNS(SVG_NS, 'svg'); - svg.setAttribute('viewBox', '0 0 600 120'); - svg.setAttribute('preserveAspectRatio', 'none'); - svg.setAttribute('class', 'chart-svg'); - - const midLine = document.createElementNS(SVG_NS, 'line'); - midLine.setAttribute('x1', '0'); - midLine.setAttribute('y1', '60'); - midLine.setAttribute('x2', '600'); - midLine.setAttribute('y2', '60'); - midLine.setAttribute('stroke', 'var(--border)'); - midLine.setAttribute('stroke-dasharray', '4 4'); - svg.appendChild(midLine); - - const addLine = (vals: number[], stroke: string) => { - const poly = document.createElementNS(SVG_NS, 'polyline'); - poly.setAttribute('fill', 'none'); - poly.setAttribute('stroke', stroke); - poly.setAttribute('stroke-width', '2'); - poly.setAttribute('points', buildPolylinePoints(vals, 600, 120, 0, computedMax)); - svg.appendChild(poly); - }; - - addLine(seriesA, options.colorA ?? 'var(--accent)'); - addLine(seriesB, options.colorB ?? 'var(--warn)'); - return svg; -} diff --git a/src/client/ts/command-palette.ts b/src/client/ts/command-palette.ts deleted file mode 100644 index 3e08788..0000000 --- a/src/client/ts/command-palette.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { el, type ClientState } from './state.js'; - -interface PaletteAction { - id: string; - label: string; - hint: string; - run: () => void | Promise; -} - -export interface CommandPaletteContext { - state: ClientState; - navigate: (hash: string) => void; - toggleSafeMode: () => Promise; - lockVault: () => Promise; - triggerPanic: () => Promise; -} - -export function openCommandPalette(ctx: CommandPaletteContext): void { - const dialog = document.getElementById('dialog-cmd') as HTMLDialogElement | null; - const input = document.getElementById('cmd-palette-input') as HTMLInputElement | null; - const listEl = document.getElementById('cmd-palette-list') as HTMLElement | null; - const closeBtn = document.getElementById('cmd-palette-close') as HTMLButtonElement | null; - if (!dialog || !input || !listEl || !closeBtn) return; - - const actions: PaletteAction[] = [ - { id: 'nav-dashboard', label: 'Go to Dashboard', hint: '#dashboard', run: () => ctx.navigate('#dashboard') }, - { id: 'nav-systems', label: 'Go to Systems', hint: '#systems', run: () => ctx.navigate('#systems') }, - { id: 'nav-terminal', label: 'Go to Terminal', hint: '#terminal', run: () => ctx.navigate('#terminal') }, - { id: 'nav-sftp', label: 'Go to SFTP Files', hint: '#sftp', run: () => ctx.navigate('#sftp') }, - { id: 'nav-workflows', label: 'Go to Workflows & Broadcast', hint: '#workflows', run: () => ctx.navigate('#workflows') }, - { id: 'nav-alerts', label: 'Go to Alerts & Incidents', hint: '#alerts', run: () => ctx.navigate('#alerts') }, - { id: 'nav-config', label: 'Go to Config & Diffs', hint: '#config', run: () => ctx.navigate('#config') }, - { id: 'nav-vault', label: 'Go to Vault & Keys', hint: '#vault', run: () => ctx.navigate('#vault') }, - { id: 'nav-settings', label: 'Go to Settings & Audit', hint: '#settings', run: () => ctx.navigate('#settings') }, - { - id: 'act-safemode', - label: ctx.state.safeMode ? 'Disable Safe Mode' : 'Enable Safe Mode', - hint: 'security', - run: () => ctx.toggleSafeMode(), - }, - { id: 'act-lockvault', label: 'Lock Vault (Write-Only)', hint: 'vault', run: () => ctx.lockVault() }, - { id: 'act-panic', label: 'Engage Panic Lock', hint: 'danger', run: () => ctx.triggerPanic() }, - ]; - - for (const srv of ctx.state.overview?.servers ?? []) { - const srvId = typeof srv.id === 'string' ? srv.id : String(srv.id ?? ''); - if (!srvId) continue; - const srvName = typeof srv.name === 'string' ? srv.name : srvId; - const srvHost = typeof srv.host === 'string' ? srv.host : ''; - actions.push( - { - id: `srv-${srvId}`, - label: `Server: ${srvName}${srvHost ? ` (${srvHost})` : ''}`, - hint: `#server/${srvId}`, - run: () => ctx.navigate(`#server/${encodeURIComponent(srvId)}`), - }, - { - id: `term-${srvId}`, - label: `Open Terminal on ${srvName}`, - hint: 'ssh pty', - run: () => ctx.navigate(`#terminal?server=${encodeURIComponent(srvId)}`), - }, - { - id: `sftp-${srvId}`, - label: `Browse SFTP on ${srvName}`, - hint: 'files', - run: () => ctx.navigate(`#sftp?server=${encodeURIComponent(srvId)}`), - }, - ); - } - - let selectedIdx = 0; - let filtered: PaletteAction[] = actions; - - const close = () => { - cleanup(); - if (dialog.open) dialog.close(); - }; - - const runAction = (act: PaletteAction | undefined) => { - if (!act) return; - close(); - void act.run(); - }; - - const renderList = () => { - const q = input.value.trim().toLowerCase(); - filtered = q - ? actions.filter( - (a) => - a.label.toLowerCase().includes(q) || - a.hint.toLowerCase().includes(q), - ) - : actions; - if (selectedIdx >= filtered.length) selectedIdx = Math.max(0, filtered.length - 1); - - listEl.replaceChildren(); - if (filtered.length === 0) { - listEl.append(el('div', { class: 'muted' }, 'No matching commands.')); - return; - } - - filtered.slice(0, 14).forEach((act, idx) => { - const btn = el( - 'button', - { - type: 'button', - class: `btn cmd-palette-item ${idx === selectedIdx ? 'active' : ''}`, - role: 'option', - 'aria-selected': idx === selectedIdx ? 'true' : 'false', - }, - el('span', {}, act.label), - el('span', { class: 'muted mono' }, act.hint), - ); - btn.addEventListener('click', () => runAction(act)); - listEl.append(btn); - }); - }; - - const onInput = () => { - selectedIdx = 0; - renderList(); - }; - - const onKeyDown = (ev: KeyboardEvent) => { - if (ev.key === 'ArrowDown') { - ev.preventDefault(); - if (filtered.length > 0) { - selectedIdx = (selectedIdx + 1) % Math.min(filtered.length, 14); - renderList(); - } - } else if (ev.key === 'ArrowUp') { - ev.preventDefault(); - const len = Math.min(filtered.length, 14); - if (len > 0) { - selectedIdx = (selectedIdx - 1 + len) % len; - renderList(); - } - } else if (ev.key === 'Enter') { - ev.preventDefault(); - runAction(filtered[selectedIdx]); - } - }; - - const cleanup = () => { - input.removeEventListener('input', onInput); - input.removeEventListener('keydown', onKeyDown); - closeBtn.removeEventListener('click', close); - dialog.removeEventListener('close', cleanup); - }; - - input.value = ''; - renderList(); - input.addEventListener('input', onInput); - input.addEventListener('keydown', onKeyDown); - closeBtn.addEventListener('click', close); - dialog.addEventListener('close', cleanup); - - if (!dialog.open) dialog.showModal(); - input.focus(); -} diff --git a/src/client/ts/dialogs.ts b/src/client/ts/dialogs.ts index 5ebd2c8..9d5bd91 100644 --- a/src/client/ts/dialogs.ts +++ b/src/client/ts/dialogs.ts @@ -1,4 +1,3 @@ -import { collapseDiffHunks, type CollapsedDiffEntry } from '../../shared/diff.js'; import { apiFetch } from './api.js'; import { el, @@ -13,7 +12,6 @@ export interface DiffModalData { source: string; createdAt: number; lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>; - collapsedLines?: CollapsedDiffEntry[]; onRollback: () => Promise; } @@ -234,56 +232,16 @@ export function openDiffModal(data: DiffModalData): void { const closeBtn = document.getElementById('dialog-diff-close') as HTMLButtonElement; const rollbackBtn = document.getElementById('dialog-diff-rollback') as HTMLButtonElement; - const hunks = data.collapsedLines ?? collapseDiffHunks(data.lines); - const hasHunk = hunks.some((entry) => entry.type === 'hunk'); - let expanded = hunks.length === 0 || !hasHunk; - - const toggleBtn = el( - 'button', - { type: 'button', class: 'btn btn-sm', style: 'margin-left:8px' }, - expanded ? 'Full Diff' : 'Expand Full Diff', - ); - if (!hasHunk) { - toggleBtn.hidden = true; + metaEl.textContent = `${data.filePath} — Revision #${data.revisionId} (${data.source})`; + bodyEl.replaceChildren(); + for (const line of data.lines) { + const prefix = line.type === 'add' ? '+ ' : line.type === 'del' ? '- ' : ' '; + const cls = + line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : ''; + bodyEl.append(el('div', { class: cls }, `${prefix}${line.text}`)); } - const renderLines = () => { - bodyEl.replaceChildren(); - if (expanded) { - for (const line of data.lines) { - const prefix = line.type === 'add' ? '+ ' : line.type === 'del' ? '- ' : ' '; - const cls = line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : ''; - bodyEl.append(el('div', { class: cls }, `${prefix}${line.text}`)); - } - toggleBtn.textContent = 'Collapse Context'; - return; - } - - for (const entry of hunks) { - if (entry.type === 'hunk') { - bodyEl.append(el('div', { class: 'diff-hunk-sep' }, entry.text)); - } else { - const prefix = entry.type === 'add' ? '+ ' : entry.type === 'del' ? '- ' : ' '; - const cls = entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : ''; - bodyEl.append(el('div', { class: cls }, `${prefix}${entry.text}`)); - } - } - toggleBtn.textContent = 'Expand Full Diff'; - }; - - metaEl.replaceChildren( - document.createTextNode(`${data.filePath} — Revision #${data.revisionId} (${data.source})`), - toggleBtn, - ); - renderLines(); - - const onToggle = () => { - expanded = !expanded; - renderLines(); - }; - const cleanup = () => { - toggleBtn.removeEventListener('click', onToggle); closeBtn.removeEventListener('click', onClose); rollbackBtn.removeEventListener('click', onRollbackClick); dialog.removeEventListener('close', cleanup); @@ -304,7 +262,6 @@ export function openDiffModal(data: DiffModalData): void { } }; - toggleBtn.addEventListener('click', onToggle); closeBtn.addEventListener('click', onClose); rollbackBtn.addEventListener('click', onRollbackClick); dialog.addEventListener('close', cleanup); diff --git a/src/client/ts/main.ts b/src/client/ts/main.ts index bb326c8..d41b44c 100644 --- a/src/client/ts/main.ts +++ b/src/client/ts/main.ts @@ -12,10 +12,6 @@ import { SAFE_MODE_STORAGE_KEY, THEME_STORAGE_KEY, applyTheme, - el, - extractErrorMessage, - flushViewCleanups, - getDashboardLivePatchers, initialDeviceSafeMode, type ClientAuthRequirements, type ClientSecuritySettings, @@ -23,7 +19,16 @@ import { type ConfigOverview, type RouteId, } from './state.js'; -import { showToast } from './toast.js'; +import { renderAuthView } from './views/auth-view.js'; +import { renderConfigView } from './views/config-view.js'; +import { + patchDashboardServerStates, + patchDashboardServerTick, + renderDashboardView, +} from './views/dashboard-view.js'; +import { renderServerDetailView } from './views/server-detail-view.js'; +import { renderSettingsView } from './views/settings-view.js'; +import { renderVaultView } from './views/vault-view.js'; import { MultiplexWsClient } from './ws-client.js'; const VALID_ROUTES = new Set([ @@ -162,175 +167,93 @@ async function refreshOverview(): Promise { updateTopBarUi(); } -let activeViewCleanup: (() => void) | null = null; -let renderSeq = 0; - -function runActiveCleanup(): void { - if (activeViewCleanup) { - try { - activeViewCleanup(); - } catch { - // Ignore view unmount errors - } - activeViewCleanup = null; - } - flushViewCleanups(); -} - -function captureCleanup(seq: number, result: unknown): void { - if (typeof result !== 'function') return; - const fn = result as () => void; - if (seq !== renderSeq) { - try { - fn(); - } catch { - // Ignore stale cleanup error - } - return; - } - activeViewCleanup = fn; -} - async function renderCurrentView(): Promise { - const mySeq = ++renderSeq; - runActiveCleanup(); - const root = document.getElementById('view-root')!; updateTopBarUi(); - try { - if (!state.authenticated) { - const { renderAuthView } = await import('./views/auth-view.js'); - if (mySeq !== renderSeq) return; - const cleanup = await renderAuthView( - root, - state.bootstrapped, - state.safeMode, - state.authRequirements, - async () => { - await bootstrapApp(); - }, - ); - captureCleanup(mySeq, cleanup); - return; - } - - if (!state.overview) { - await refreshOverview(); - if (mySeq !== renderSeq) return; - } - - const route = state.route; - if (route === 'dashboard') { - const { renderDashboardView } = await import('./views/dashboard-view.js'); - if (mySeq !== renderSeq) return; - captureCleanup(mySeq, await renderDashboardView(root, state)); - return; - } - if (route === 'server-detail' && state.selectedServerId) { - const { renderServerDetailView } = await import('./views/server-detail-view.js'); - if (mySeq !== renderSeq) return; - captureCleanup( - mySeq, - await renderServerDetailView(root, state.selectedServerId, () => { - window.location.hash = '#dashboard'; - }), - ); - return; - } - if (route === 'config') { - const { renderConfigView } = await import('./views/config-view.js'); - if (mySeq !== renderSeq) return; - captureCleanup( - mySeq, - await renderConfigView(root, state.overview!, state, wsClient, async () => { - await refreshOverview(); - await renderCurrentView(); - }), - ); - return; - } - if (route === 'vault') { - const { renderVaultView } = await import('./views/vault-view.js'); - if (mySeq !== renderSeq) return; - captureCleanup( - mySeq, - await renderVaultView( - root, - state, - async () => { - await syncStatusAndRender(); - }, - triggerPanicLock, - ), - ); - return; - } - if (route === 'settings') { - const { renderSettingsView } = await import('./views/settings-view.js'); - if (mySeq !== renderSeq) return; - captureCleanup( - mySeq, - await renderSettingsView( - root, - state, - (theme) => { - state.theme = theme; - applyTheme(theme); - updateTopBarUi(); - }, - syncStatusAndRender, - ), - ); - return; - } - - if (route === 'terminal') { - const { renderTerminalView } = await import('./views/terminal-view.js'); - if (mySeq !== renderSeq) return; - captureCleanup(mySeq, await renderTerminalView(root, state, wsClient)); - return; - } - if (route === 'sftp') { - const { renderSftpView } = await import('./views/sftp-view.js'); - if (mySeq !== renderSeq) return; - captureCleanup(mySeq, await renderSftpView(root, state)); - return; - } - if (route === 'systems') { - const { renderSystemsView } = await import('./views/systems-view.js'); - if (mySeq !== renderSeq) return; - captureCleanup(mySeq, await renderSystemsView(root, state, wsClient)); - return; - } - if (route === 'workflows') { - const { renderWorkflowsView } = await import('./views/workflows-view.js'); - if (mySeq !== renderSeq) return; - captureCleanup(mySeq, await renderWorkflowsView(root, state, wsClient)); - return; - } - if (route === 'alerts') { - const { renderAlertsView } = await import('./views/alerts-view.js'); - if (mySeq !== renderSeq) return; - captureCleanup(mySeq, await renderAlertsView(root, state, wsClient)); - } - } catch (err) { - if (mySeq !== renderSeq) return; - const msg = extractErrorMessage(err); - showToast(`View error: ${msg}`, 'err'); - const retryBtn = el('button', { type: 'button', class: 'btn btn-primary' }, 'Retry View'); - retryBtn.addEventListener('click', () => { - void renderCurrentView(); - }); - root.replaceChildren( - el( - 'section', - { class: 'panel panel-region' }, - el('h2', { class: 'err-text' }, 'View Render Error'), - el('p', { class: 'mono muted' }, msg), - retryBtn, - ), + if (!state.authenticated) { + await renderAuthView( + root, + state.bootstrapped, + state.safeMode, + state.authRequirements, + async () => { + await bootstrapApp(); + }, ); + return; + } + + if (!state.overview) { + await refreshOverview(); + } + + const route = state.route; + if (route === 'dashboard') { + await renderDashboardView(root, state); + return; + } + if (route === 'server-detail' && state.selectedServerId) { + await renderServerDetailView(root, state.selectedServerId, () => { + window.location.hash = '#dashboard'; + }); + return; + } + if (route === 'config') { + await renderConfigView(root, state.overview!, state, wsClient, async () => { + await refreshOverview(); + await renderCurrentView(); + }); + return; + } + if (route === 'vault') { + await renderVaultView( + root, + state, + async () => { + await syncStatusAndRender(); + }, + triggerPanicLock, + ); + return; + } + if (route === 'settings') { + await renderSettingsView( + root, + state, + (theme) => { + state.theme = theme; + applyTheme(theme); + updateTopBarUi(); + }, + syncStatusAndRender, + ); + return; + } + + if (route === 'terminal') { + const { renderTerminalView } = await import('./views/terminal-view.js'); + await renderTerminalView(root, state, wsClient); + return; + } + if (route === 'sftp') { + const { renderSftpView } = await import('./views/sftp-view.js'); + await renderSftpView(root, state); + return; + } + if (route === 'systems') { + const { renderSystemsView } = await import('./views/systems-view.js'); + await renderSystemsView(root, state, wsClient); + return; + } + if (route === 'workflows') { + const { renderWorkflowsView } = await import('./views/workflows-view.js'); + await renderWorkflowsView(root, state, wsClient); + return; + } + if (route === 'alerts') { + const { renderAlertsView } = await import('./views/alerts-view.js'); + await renderAlertsView(root, state, wsClient); } } @@ -338,41 +261,10 @@ async function triggerPanicLock(): Promise { const confirmed = await confirmDialog('dialog-panic'); if (!confirmed) return; await apiFetch('/api/security/panic-lock', { method: 'POST' }); - showToast('Panic lock engaged: Vault zeroized and sessions revoked.', 'warn'); handleLocalSessionReset(true); } -async function lockVaultAction(): Promise { - try { - await apiFetch('/api/vault/lock', { method: 'POST', body: {} }); - state.vaultState = 'locked'; - updateTopBarUi(); - showToast('Vault locked (write-only mode).', 'ok'); - if (state.route === 'vault') void renderCurrentView(); - } catch (err) { - showToast(extractErrorMessage(err), 'err'); - } -} - -async function toggleSafeMode(): Promise { - const next = !state.safeMode; - localStorage.setItem(SAFE_MODE_STORAGE_KEY, next ? '1' : '0'); - state.safeMode = next; - setApiSafeMode(next); - if (next) state.elevatedUntil = null; - wsClient.send({ type: 'safe-mode', enabled: next }); - if (state.authenticated) { - await apiFetch('/api/auth/safe-mode', { - method: 'POST', - body: { enabled: next }, - }); - } - updateTopBarUi(); - showToast(`Safe Mode ${next ? 'enabled (read-only)' : 'disabled'}.`, next ? 'warn' : 'ok'); -} - function handleLocalSessionReset(panic = false): void { - runActiveCleanup(); wsClient.disconnect(); setCsrfToken(null); state.authenticated = false; @@ -392,7 +284,7 @@ async function syncStatusAndRender(): Promise { authenticated: boolean; safeMode?: boolean; elevatedUntil?: number | null; - vaultState?: ClientState['vaultState']; + vaultState: ClientState['vaultState']; vaultRuntimeReady?: boolean; isPanicLocked?: boolean; defaultMobileSafeMode: boolean; @@ -403,8 +295,8 @@ async function syncStatusAndRender(): Promise { state.bootstrapped = status.bootstrapped; state.authenticated = status.authenticated; - state.vaultState = status.vaultState ?? 'locked'; - state.vaultRuntimeReady = status.vaultRuntimeReady ?? false; + state.vaultState = status.vaultState; + state.vaultRuntimeReady = status.vaultRuntimeReady ?? status.vaultState === 'unlocked'; state.isPanicLocked = Boolean(status.isPanicLocked); state.defaultMobileSafeMode = status.defaultMobileSafeMode; state.elevatedUntil = status.elevatedUntil ?? null; @@ -518,7 +410,6 @@ document.addEventListener('DOMContentLoaded', () => { void renderCurrentView(); } } else if (frame.type === 'security:panic-lock') { - showToast('Panic lock engaged remotely — session terminated.', 'err'); handleLocalSessionReset(true); } else if (frame.type === 'config:updated' && state.authenticated) { void refreshOverview().then(() => { @@ -527,80 +418,35 @@ document.addEventListener('DOMContentLoaded', () => { } }); } else if (frame.type === 'metrics:tick' && state.authenticated && state.route === 'dashboard') { - getDashboardLivePatchers()?.onTick(frame); + patchDashboardServerTick(frame); } else if (frame.type === 'servers:state' && state.authenticated && state.route === 'dashboard') { - const needsRefresh = getDashboardLivePatchers()?.onStates(frame.states) ?? false; + const needsRefresh = patchDashboardServerStates(frame.states); if (needsRefresh) { void renderCurrentView(); } } else if (frame.type === 'alerts:update') { - const prevAlerts = state.activeAlertCount; state.activeAlertCount = frame.activeCount; updateTopBarUi(); - if (state.authenticated && frame.activeCount > prevAlerts) { - showToast(`Active alerts increased to ${frame.activeCount}.`, 'warn'); - } if (state.authenticated && state.route === 'alerts') { void renderCurrentView(); } } }); - const openPalette = async () => { - if (!state.authenticated) return; - const { openCommandPalette } = await import('./command-palette.js'); - openCommandPalette({ - state, - navigate: (hash) => { - window.location.hash = hash; - }, - toggleSafeMode, - lockVault: lockVaultAction, - triggerPanic: triggerPanicLock, - }); - }; - - document.getElementById('cmd-palette-btn')!.addEventListener('click', () => { - void openPalette(); - }); - - document.getElementById('safe-toggle-btn')!.addEventListener('click', () => { - void toggleSafeMode(); - }); - - document.addEventListener('keydown', (ev) => { - const active = document.activeElement; - if (active && active.closest('.xterm')) return; - - if ((ev.ctrlKey || ev.metaKey || ev.altKey) && ev.key.toLowerCase() === 'k') { - if (!state.authenticated) return; - ev.preventDefault(); - void openPalette(); - return; - } - - if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === 's') { - if (!state.authenticated || document.querySelector('dialog[open]')) return; - ev.preventDefault(); - window.dispatchEvent(new CustomEvent('gcoord:save')); - } - }); - - window.addEventListener('storage', (ev) => { - if (ev.key === THEME_STORAGE_KEY && ev.newValue) { - state.theme = ev.newValue; - document.documentElement.setAttribute('data-theme', ev.newValue); - updateTopBarUi(); - } else if (ev.key === SAFE_MODE_STORAGE_KEY && ev.newValue !== null) { - const next = ev.newValue === '1'; - if (next !== state.safeMode) { - state.safeMode = next; - setApiSafeMode(next); - if (next) state.elevatedUntil = null; - wsClient.send({ type: 'safe-mode', enabled: next }); - updateTopBarUi(); - } + document.getElementById('safe-toggle-btn')!.addEventListener('click', async () => { + const next = !state.safeMode; + localStorage.setItem(SAFE_MODE_STORAGE_KEY, next ? '1' : '0'); + state.safeMode = next; + setApiSafeMode(next); + if (next) state.elevatedUntil = null; + wsClient.send({ type: 'safe-mode', enabled: next }); + if (state.authenticated) { + await apiFetch('/api/auth/safe-mode', { + method: 'POST', + body: { enabled: next }, + }); } + updateTopBarUi(); }); document.getElementById('theme-select')!.addEventListener('change', (ev) => { diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts index b8455d4..c0f690c 100644 --- a/src/client/ts/state.ts +++ b/src/client/ts/state.ts @@ -74,28 +74,24 @@ export interface ClientSecuritySettings { requireTotpOnLogin: boolean; passwordMode: 'any' | 'all'; totpMode: 'any' | 'all'; - stepUpPolicy: 'off' | 'every-action' | '5m' | '15m' | '1h' | '24h' | 'session'; + stepUpPolicy: 'off' | 'every-action' | '5m' | '1h' | '24h' | 'session'; stepUpMethod: 'totp' | 'password' | 'both' | 'passkey'; elevateOnLogin: boolean; keepElevationOnSafeMode: boolean; enableEmergencySecretsBackup: boolean; - allowSameOriginProxy?: boolean; - egressAllowedCidrs?: string[]; - sessionTtlHours?: number; - sessionIdleTimeoutMin?: number; } export interface ClientAuthRequirements { requireTotpOnLogin: boolean; passwordMode: 'any' | 'all'; passwordCount: number; - passwordLabels?: Array<{ id: string; label: string }>; + passwordLabels: Array<{ id: string; label: string }>; totpMode: 'any' | 'all'; totpCount: number; - totpLabels?: Array<{ id: string; label: string }>; + totpLabels: Array<{ id: string; label: string }>; passkeyCount: number; - stepUpPolicy?: ClientSecuritySettings['stepUpPolicy']; - stepUpMethod?: ClientSecuritySettings['stepUpMethod']; + stepUpPolicy: ClientSecuritySettings['stepUpPolicy']; + stepUpMethod: ClientSecuritySettings['stepUpMethod']; } export interface ClientState { @@ -225,40 +221,3 @@ export function fmtUptime(sec: number): string { export function extractErrorMessage(err: unknown): string { return err instanceof Error ? err.message : String(err); } - -export interface DashboardLivePatchers { - onTick: (tick: { - serverId: string; - sample: MetricSample; - disks: DiskSample[]; - probes?: ProbeSample[]; - }) => void; - onStates: (states: ServerRuntimeState[]) => boolean; -} - -let dashboardPatchers: DashboardLivePatchers | null = null; -const activeCleanups: Array<() => void> = []; - -export function registerDashboardLivePatchers(patchers: DashboardLivePatchers | null): void { - dashboardPatchers = patchers; -} - -export function getDashboardLivePatchers(): DashboardLivePatchers | null { - return dashboardPatchers; -} - -export function registerViewCleanup(fn: () => void): void { - activeCleanups.push(fn); -} - -export function flushViewCleanups(): void { - while (activeCleanups.length > 0) { - const fn = activeCleanups.pop(); - if (!fn) continue; - try { - fn(); - } catch { - // Ignore view teardown errors - } - } -} diff --git a/src/client/ts/toast.ts b/src/client/ts/toast.ts deleted file mode 100644 index bc9de02..0000000 --- a/src/client/ts/toast.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { el } from './state.js'; - -export type ToastKind = 'info' | 'ok' | 'warn' | 'err'; - -const MAX_TOASTS = 4; - -export function showToast( - message: string, - kind: ToastKind = 'info', - durationMs = 4500, -): void { - const region = document.getElementById('toast-region'); - if (!region) return; - - while (region.children.length >= MAX_TOASTS) { - region.firstElementChild?.remove(); - } - - const closeBtn = el( - 'button', - { type: 'button', class: 'btn btn-sm toast-close', 'aria-label': 'Dismiss notification' }, - 'X', - ); - const item = el( - 'div', - { class: `toast-item toast-${kind}`, role: 'status' }, - el('span', { class: 'toast-msg' }, message), - closeBtn, - ); - - let timer: number | undefined; - const dismiss = () => { - if (timer !== undefined) window.clearTimeout(timer); - item.remove(); - }; - closeBtn.addEventListener('click', dismiss); - - if (durationMs > 0) { - timer = window.setTimeout(dismiss, durationMs); - } - region.append(item); -} diff --git a/src/client/ts/views/ai-drawer.ts b/src/client/ts/views/ai-drawer.ts index fb0048e..d3620f7 100644 --- a/src/client/ts/views/ai-drawer.ts +++ b/src/client/ts/views/ai-drawer.ts @@ -7,7 +7,6 @@ import { extractErrorMessage, type ClientState, } from '../state.js'; -import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; export type ClientAiSurface = 'workflows' | 'systems' | 'snippets' | 'logs' | 'setup'; @@ -28,7 +27,6 @@ export interface OpenAiDrawerOptions { contextText?: string; serverId?: string; targetPath?: string; - targetId?: string; defaultDraftKind?: ClientAiDraftKind; onInsertTerminalText?: (cmd: string) => void; onApplied?: () => Promise | void; @@ -105,29 +103,18 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise< const statusLine = el('p', { class: 'form-msg muted' }, ''); const sendBtn = el('button', { type: 'submit', class: 'btn btn-primary btn-sm' }, 'Send'); - const stopBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm', disabled: true }, 'Cancel Stream'); + const stopBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm', disabled: true }, 'Stop'); const history: Array<{ role: 'user' | 'assistant'; content: string }> = []; let activeChatId: string | null = null; let currentReply = ''; let unsubWs: (() => void) | null = null; - let unsubChannel: (() => void) | null = null; - - const releaseChannel = () => { - if (unsubChannel) { - unsubChannel(); - unsubChannel = null; - } - }; const cleanup = () => { if (activeChatId) { - const cid = activeChatId; - opts.wsClient.send({ type: 'ai:cancel', chatId: cid }); - void apiFetch(`/api/ai/chat/${encodeURIComponent(cid)}/cancel`, { method: 'POST' }).catch(() => undefined); + opts.wsClient.send({ type: 'ai:cancel', chatId: activeChatId }); activeChatId = null; } - releaseChannel(); if (unsubWs) { unsubWs(); unsubWs = null; @@ -183,11 +170,7 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise< | { valid: false; issues: Array<{ path: string; message: string }> } >('/api/ai/validate-draft', { method: 'POST', - body: { - kind: draftKindSel.value, - jsonText: jsonBlock, - ...(opts.targetId ? { targetId: opts.targetId } : {}), - }, + body: { kind: draftKindSel.value, jsonText: jsonBlock }, }); draftOutputBox.replaceChildren(); @@ -255,14 +238,11 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise< if (currentReply) history.push({ role: 'assistant', content: currentReply }); appendBoundedStreamText(streamPre, '\n'); activeChatId = null; - releaseChannel(); sendBtn.disabled = false; stopBtn.disabled = true; if (!frame.error) { statusLine.className = 'form-msg ok-text'; statusLine.textContent = 'Response complete. Review any extracted draft below.'; - } else { - showToast(frame.error, 'err'); } refreshDraftActions(); } @@ -321,17 +301,13 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise< }, }); activeChatId = started.chatId; - releaseChannel(); - unsubChannel = opts.wsClient.subscribe([`ai:${started.chatId}`]); + opts.wsClient.subscribe([`ai:${started.chatId}`]); } catch (err) { history.pop(); - releaseChannel(); sendBtn.disabled = false; stopBtn.disabled = true; - const errMsg = extractErrorMessage(err); statusLine.className = 'form-msg err-text'; - statusLine.textContent = errMsg; - showToast(errMsg, 'err'); + statusLine.textContent = extractErrorMessage(err); } }); diff --git a/src/client/ts/views/alerts-view.ts b/src/client/ts/views/alerts-view.ts index 240bca9..9014748 100644 --- a/src/client/ts/views/alerts-view.ts +++ b/src/client/ts/views/alerts-view.ts @@ -23,7 +23,7 @@ interface AlertChannelItem { interface AlertRuleItem { id: string; name: string; - kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system' | 'security-event'; + kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system'; severity: 'warn' | 'critical'; target: { serverId?: string; tags?: string[]; all?: boolean }; forConsecutivePolls: number; @@ -40,7 +40,6 @@ interface AlertRuleItem { probeId?: string; systemId?: string; item?: string; - events?: string[]; } interface MaintenanceWindowItem { @@ -331,12 +330,11 @@ export async function renderAlertsView( const chUrl = el('input', { placeholder: 'Webhook / base URL (optional for ntfy.sh or Telegram)' }); const chExtra = el('input', { placeholder: 'Telegram chatId OR ntfy topic (optional)' }); const chRef = el('select', {}); - const webhookCreds = credsRes.credentials.filter((cr) => cr.type === 'webhook-secret'); - for (const cr of webhookCreds) { + for (const cr of credsRes.credentials) { chRef.append(el('option', { value: cr.id }, `${cr.id} (${cr.type})`)); } - if (webhookCreds.length === 0) { - chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add webhook-secret in Vault)')); + if (credsRes.credentials.length === 0) { + chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add in Vault)')); } const chForm = el( 'form', @@ -387,9 +385,7 @@ export async function renderAlertsView( ? `offline >= ${r.offlineSec}s` : r.kind === 'probe' ? `probe ${r.probeId ?? '*'}` - : r.kind === 'security-event' - ? `security-event [${r.events?.join(', ') ?? ''}]` - : `system ${r.systemId}/${r.item ?? '*'}`; + : `system ${r.systemId}/${r.item ?? '*'}`; const toggleBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, r.enabled ? 'Disable' : 'Enable'); toggleBtn.addEventListener('click', () => { void saveConfig({ @@ -408,9 +404,9 @@ export async function renderAlertsView( const ruleId = el('input', { placeholder: 'high-cpu', required: true }); const ruleName = el('input', { placeholder: 'High CPU Usage', required: true }); - const ruleKind = el('select', {}, el('option', { value: 'metric' }, 'metric'), el('option', { value: 'disk' }, 'disk'), el('option', { value: 'offline' }, 'offline'), el('option', { value: 'probe' }, 'probe'), el('option', { value: 'system' }, 'system'), el('option', { value: 'security-event' }, 'security-event')); + const ruleKind = el('select', {}, el('option', { value: 'metric' }, 'metric'), el('option', { value: 'disk' }, 'disk'), el('option', { value: 'offline' }, 'offline'), el('option', { value: 'probe' }, 'probe'), el('option', { value: 'system' }, 'system')); const ruleSev = el('select', {}, el('option', { value: 'warn' }, 'warn'), el('option', { value: 'critical' }, 'critical')); - const ruleParam1 = el('input', { placeholder: 'metric/mount/probe/system or events csv (auth.lockout,ssh.host_key_mismatch,vault.panic_lock)' }); + const ruleParam1 = el('input', { placeholder: 'metric/mount/probe/system (e.g. cpuPct)' }); const ruleThresh = el('input', { type: 'number', value: '85', placeholder: 'Threshold / Offline sec' }); const rulePolls = el('input', { type: 'number', min: 1, value: '3', placeholder: 'forConsecutivePolls' }); const ruleChans = el('input', { placeholder: 'channelIds comma-sep (optional)' }); @@ -447,17 +443,6 @@ export async function renderAlertsView( nextRule = { ...base, kind: 'probe', probeId: ruleParam1.value.trim() || undefined }; } else if (ruleKind.value === 'system') { nextRule = { ...base, kind: 'system', systemId: ruleParam1.value.trim() || 'docker-compose' }; - } else if (ruleKind.value === 'security-event') { - const events = ruleParam1.value - .split(',') - .map((e) => e.trim()) - .filter(Boolean); - nextRule = { - ...base, - kind: 'security-event', - forConsecutivePolls: 1, - events: events.length > 0 ? events : ['auth.lockout', 'ssh.host_key_mismatch', 'vault.panic_lock'], - }; } else { nextRule = { ...base, kind: 'metric', metric: (ruleParam1.value.trim() || 'cpuPct') as 'cpuPct', operator: 'gt', threshold: Number(ruleThresh.value || 85) }; } diff --git a/src/client/ts/views/auth-view.ts b/src/client/ts/views/auth-view.ts index fd1c305..d183e36 100644 --- a/src/client/ts/views/auth-view.ts +++ b/src/client/ts/views/auth-view.ts @@ -7,11 +7,9 @@ import { import { getPasskeyAssertion, isWebAuthnSupported } from '../webauthn.js'; interface BootstrapData { - bootstrapToken?: string; secretBase32: string; otpauthUri: string; qrSvg: string; - qrDataUri?: string; } export async function renderAuthView( @@ -87,36 +85,14 @@ export async function renderAuthView( placeholder: '6-digit code from authenticator', required: true, }); - const bootTokInput = el('input', { - id: 'boot-token', - name: 'bootstrapToken', - type: 'password', - autocomplete: 'off', - placeholder: 'GCOORD_BOOTSTRAP_TOKEN (auto-filled unless operator-only)', - }) as HTMLInputElement; let secretBase32 = ''; try { const data = await apiFetch('/api/auth/bootstrap'); secretBase32 = data.secretBase32; - bootTokInput.value = data.bootstrapToken ?? ''; - if ( - typeof data.qrDataUri === 'string' && - /^data:image\/(?:png|svg\+xml);base64,[A-Za-z0-9+/=]+$/.test(data.qrDataUri) - ) { - const img = el('img', { - src: data.qrDataUri, - alt: 'TOTP Enrollment QR Code', - width: 200, - height: 200, - style: 'background:#fff;padding:6px;display:block', - }); - qrContainer.append(img); - } else { - const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml'); - if (doc.documentElement.nodeName === 'svg') { - qrContainer.append(document.importNode(doc.documentElement, true)); - } + const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml'); + if (doc.documentElement.nodeName === 'svg') { + qrContainer.append(document.importNode(doc.documentElement, true)); } secretLine.textContent = `Secret: ${data.secretBase32}`; } catch (err) { @@ -139,8 +115,6 @@ export async function renderAuthView( el('div', { class: 'stack' }, el('label', {}, 'Scan TOTP QR Code'), qrContainer, secretLine), el('label', { for: 'boot-totp' }, 'Verify 6-Digit TOTP Code'), codeInput, - el('label', { for: 'boot-token' }, 'Bootstrap Token (if GCOORD_BOOTSTRAP_TOKEN is enforced)'), - bootTokInput, statusMsg, submitBtn, ); @@ -150,7 +124,6 @@ export async function renderAuthView( statusMsg.textContent = ''; submitBtn.disabled = true; try { - const tok = bootTokInput.value.trim(); const res = await apiFetch<{ csrfToken: string; recoveryCodes: string[]; @@ -161,7 +134,6 @@ export async function renderAuthView( password: passInput.value, totpCode: codeInput.value.trim(), secretBase32, - ...(tok ? { bootstrapToken: tok } : {}), initialSafeMode, securityPreset: presetSelect.value, }, @@ -311,7 +283,7 @@ export async function renderAuthView( form.append(el('label', { for: 'login-username' }, 'Username'), userInput); const passwordInputs: HTMLInputElement[] = []; - const pwCount = Math.max(1, reqs?.passwordCount ?? pwLabels.length); + const pwCount = pwMode === 'all' ? Math.max(1, pwLabels.length) : 1; for (let i = 0; i < pwCount; i++) { const labelText = pwMode === 'all' ? `Password — ${pwLabels[i]?.label ?? `#${i + 1}`}` : 'Password'; @@ -338,7 +310,7 @@ export async function renderAuthView( const codeInputs: HTMLInputElement[] = []; if (requireTotp) { - const totpCount = Math.max(1, reqs?.totpCount ?? totpLabels.length); + const totpCount = totpMode === 'all' ? Math.max(1, totpLabels.length) : 1; for (let i = 0; i < totpCount; i++) { const labelText = totpMode === 'all' diff --git a/src/client/ts/views/config-view.ts b/src/client/ts/views/config-view.ts index 2f440df..6bc070f 100644 --- a/src/client/ts/views/config-view.ts +++ b/src/client/ts/views/config-view.ts @@ -1,4 +1,3 @@ -import { collapseDiffHunks, computeLineDiff, type CollapsedDiffEntry } from '../../../shared/diff.js'; import { apiFetch, type ApiError } from '../api.js'; import { confirmDialog, openDiffModal } from '../dialogs.js'; import { @@ -6,11 +5,9 @@ import { extractErrorMessage, fmtTime, isAiEnabled, - registerViewCleanup, type ClientState, type ConfigOverview, } from '../state.js'; -import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; interface FileDetails { @@ -239,14 +236,18 @@ export async function renderConfigView( } }); - const saveFile = async () => { + const saveBtn = el( + 'button', + { type: 'button', class: 'btn btn-primary mutating-action' }, + 'Save Config', + ); + saveBtn.addEventListener('click', async () => { msgEl.replaceChildren(); try { await apiFetch('/api/config/file', { method: 'PUT', body: { path: details.filePath, content: editor.value }, }); - showToast(`Saved ${details.filePath}.`, 'ok'); await onReloadOverview(); } catch (err) { const apiErr = err as ApiError; @@ -255,44 +256,9 @@ export async function renderConfigView( msgEl.append(el('div', { class: 'mono err-text' }, ` ${issue.path}: ${issue.message}`)); } } - }; - - const previewBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Preview Changes'); - previewBtn.addEventListener('click', () => { - const diff = computeLineDiff(details.rawContent, editor.value, 'saved', 'draft'); - const hunks = diff.collapsedLines ?? collapseDiffHunks(diff.lines); - msgEl.replaceChildren( - el('div', { class: 'mono muted' }, `+${diff.additions} / -${diff.deletions}`), - el( - 'pre', - { class: 'diff-body mono', style: 'max-height:220px' }, - ...hunks.map((entry) => - entry.type === 'hunk' - ? el('div', { class: 'diff-hunk-sep' }, entry.text) - : el( - 'div', - { class: entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : '' }, - `${entry.type === 'add' ? '+' : entry.type === 'del' ? '-' : ' '} ${entry.text}`, - ), - ), - ), - ); }); - const saveBtn = el( - 'button', - { type: 'button', class: 'btn btn-primary mutating-action' }, - 'Save Config', - ); - saveBtn.addEventListener('click', () => void saveFile()); - - const onCtrlS = () => { - if (editor.isConnected && !state.safeMode) void saveFile(); - }; - window.addEventListener('gcoord:save', onCtrlS); - registerViewCleanup(() => window.removeEventListener('gcoord:save', onCtrlS)); - - const actionRow = el('div', { class: 'row' }, fmtBtn, previewBtn, saveBtn); + const actionRow = el('div', { class: 'row' }, fmtBtn, saveBtn); if (isAiEnabled(state)) { const aiBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Assist]'); aiBtn.addEventListener('click', async () => { @@ -370,10 +336,7 @@ export async function renderConfigView( diffBtn.addEventListener('click', async () => { const res = await apiFetch<{ revision: { id: number; filePath: string; source: string; createdAt: number }; - diff: { - lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>; - collapsedLines?: CollapsedDiffEntry[]; - }; + diff: { lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }> }; }>(`/api/config/revisions/${rev.id}/diff`); openDiffModal({ revisionId: res.revision.id, @@ -381,7 +344,6 @@ export async function renderConfigView( source: res.revision.source, createdAt: res.revision.createdAt, lines: res.diff.lines, - collapsedLines: res.diff.collapsedLines, onRollback: async () => { await apiFetch(`/api/config/revisions/${rev.id}/rollback`, { method: 'POST' }); await onReloadOverview(); diff --git a/src/client/ts/views/dashboard-view.ts b/src/client/ts/views/dashboard-view.ts index 3410724..c67870b 100644 --- a/src/client/ts/views/dashboard-view.ts +++ b/src/client/ts/views/dashboard-view.ts @@ -16,16 +16,11 @@ import { extractErrorMessage, fmtBytesPerSec, fmtUptime, - registerDashboardLivePatchers, - registerViewCleanup, type ClientState, type ServerEntry, } from '../state.js'; -import { showToast } from '../toast.js'; const sparkHistory = new Map(); -let fleetFilter: 'all' | 'connected' | 'issues' = 'all'; -let fleetSearch = ''; function statusBadgeClass(status: string): string { if (status === 'connected') return 'badge badge-ok'; @@ -68,18 +63,11 @@ function renderProbesInto(container: Element, probes: ProbeSample[]): void { container.replaceChildren(); if (probes.length === 0) return; for (const p of probes) { - const tlsNote = - p.certExpiryDays !== undefined ? ` TLS:${p.certExpiryDays}d` : ''; - const cls = !p.ok || (p.certExpiryDays !== undefined && p.certExpiryDays <= 0) - ? 'badge-err' - : p.certExpiryDays !== undefined && p.certExpiryDays <= 14 - ? 'badge-warn' - : 'badge-ok'; container.append( el( 'span', - { class: `badge ${cls}` }, - `${p.probeId}: ${p.ok ? `OK ${Math.round(p.latencyMs)}ms` : 'FAIL'}${tlsNote}`, + { class: `badge ${p.ok ? 'badge-ok' : 'badge-err'}` }, + `${p.probeId}: ${p.ok ? `OK ${Math.round(p.latencyMs)}ms` : 'FAIL'}`, ), ); } @@ -133,7 +121,6 @@ export function patchDashboardServerStates(states: ServerRuntimeState[]): boolea badge.textContent = `[${st.status.toUpperCase()}]`; badge.className = statusBadgeClass(st.status); } - card.setAttribute('data-status', st.status); const osBadge = card.querySelector('[data-field="os"]'); if (osBadge && st.osDetected) { osBadge.textContent = st.osDetected; @@ -153,16 +140,12 @@ async function openRegisterServerDialog( const form = document.getElementById('dialog-srv-form') as HTMLFormElement; const credSelect = document.getElementById('srv-cred') as HTMLSelectElement; const jumpSelect = document.getElementById('srv-jump') as HTMLSelectElement; - const testMsgEl = document.getElementById('srv-test-msg') as HTMLElement; const errEl = document.getElementById('srv-reg-err') as HTMLElement; - const testBtn = document.getElementById('srv-test-conn-btn') as HTMLButtonElement; const closeBtn = document.getElementById('srv-reg-close') as HTMLButtonElement; const cancelBtn = document.getElementById('srv-reg-cancel') as HTMLButtonElement; form.reset(); errEl.textContent = ''; - testMsgEl.textContent = ''; - testMsgEl.className = 'form-msg'; credSelect.replaceChildren(); try { @@ -189,69 +172,8 @@ async function openRegisterServerDialog( jumpSelect.append(el('option', { value: s.config.id }, `${s.config.id} (${s.config.host})`)); } - const buildPayload = () => { - const fd = new FormData(form); - const id = String(fd.get('id') ?? '').trim(); - const tagsRaw = String(fd.get('tags') ?? ''); - const tags = tagsRaw - .split(',') - .map((t) => t.trim()) - .filter(Boolean); - return { - id, - name: String(fd.get('name') ?? id).trim(), - host: String(fd.get('host') ?? '').trim(), - port: Number(fd.get('port') ?? 22), - username: String(fd.get('username') ?? '').trim(), - credentialId: String(fd.get('credentialId') ?? '').trim(), - jumpHostId: String(fd.get('jumpHostId') ?? '').trim() || undefined, - osHint: String(fd.get('osHint') ?? 'auto'), - pollIntervalSec: Number(fd.get('pollIntervalSec') ?? 10), - tags, - }; - }; - - const onTestConn = async () => { - errEl.textContent = ''; - testBtn.disabled = true; - testMsgEl.className = 'form-msg muted'; - testMsgEl.textContent = 'Testing SSH handshake...'; - try { - const payload = buildPayload(); - const res = await apiFetch<{ - ok: boolean; - latencyMs: number; - osDetected?: string; - hostFingerprint?: string; - tofuRequired?: boolean; - hostKeyMismatch?: { expectedFingerprint: string; actualFingerprint: string }; - error?: string; - }>('/api/servers/test-connection', { - method: 'POST', - body: payload, - }); - if (res.ok) { - testMsgEl.className = 'form-msg ok-text'; - testMsgEl.textContent = `Connected in ${Math.round(res.latencyMs)}ms (${res.osDetected ?? 'unknown OS'})${res.hostFingerprint ? ` · fp ${res.hostFingerprint}` : ''}`; - } else { - testMsgEl.className = res.hostKeyMismatch ? 'form-msg err-text' : 'form-msg warn-text'; - testMsgEl.textContent = res.hostKeyMismatch - ? `HOST KEY MISMATCH: ${res.hostKeyMismatch.actualFingerprint}` - : res.tofuRequired - ? `TOFU required (${res.hostFingerprint ?? 'unknown fingerprint'}): ${res.error ?? 'save then approve TOFU'}` - : res.error ?? 'Connection test failed'; - } - } catch (err) { - testMsgEl.className = 'form-msg err-text'; - testMsgEl.textContent = extractErrorMessage(err); - } finally { - testBtn.disabled = false; - } - }; - const cleanup = () => { form.removeEventListener('submit', onSubmit); - testBtn.removeEventListener('click', onTestConn); closeBtn.removeEventListener('click', onClose); cancelBtn.removeEventListener('click', onClose); dialog.removeEventListener('close', onDialogClose); @@ -266,18 +188,34 @@ async function openRegisterServerDialog( const onSubmit = async (ev: Event) => { ev.preventDefault(); errEl.textContent = ''; - const payload = buildPayload(); + const fd = new FormData(form); + const id = String(fd.get('id') ?? '').trim(); + const tagsRaw = String(fd.get('tags') ?? ''); + const tags = tagsRaw + .split(',') + .map((t) => t.trim()) + .filter(Boolean); try { await apiFetch('/api/servers', { method: 'POST', - body: payload, + body: { + id, + name: String(fd.get('name') ?? id).trim(), + host: String(fd.get('host') ?? '').trim(), + port: Number(fd.get('port') ?? 22), + username: String(fd.get('username') ?? '').trim(), + credentialId: String(fd.get('credentialId') ?? '').trim(), + jumpHostId: String(fd.get('jumpHostId') ?? '').trim() || undefined, + osHint: String(fd.get('osHint') ?? 'auto'), + pollIntervalSec: Number(fd.get('pollIntervalSec') ?? 10), + tags, + }, }); - await apiFetch(`/api/servers/${encodeURIComponent(payload.id)}/reconnect`, { + await apiFetch(`/api/servers/${encodeURIComponent(id)}/reconnect`, { method: 'POST', }).catch(() => undefined); if (dialog.open) dialog.close(); - showToast(`Server "${payload.id}" registered.`, 'ok'); await onRegistered(); } catch (err) { errEl.textContent = extractErrorMessage(err); @@ -285,118 +223,17 @@ async function openRegisterServerDialog( }; form.addEventListener('submit', onSubmit); - testBtn.addEventListener('click', onTestConn); closeBtn.addEventListener('click', onClose); cancelBtn.addEventListener('click', onClose); dialog.addEventListener('close', onDialogClose); dialog.showModal(); } -async function openImportSshConfigDialog(onImported: () => Promise): Promise { - const dlg = el('dialog', { class: 'dialog-wide', 'aria-labelledby': 'imp-ssh-title' }); - const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close'); - const credSelect = el('select', { class: 'input-sm' }); - const textarea = el('textarea', { - rows: 8, - class: 'code-editor', - placeholder: 'Host prod-web\n HostName 10.0.1.12\n User ops\n Port 22', - }) as HTMLTextAreaElement; - const msgEl = el('p', { class: 'form-msg' }); - const previewBox = el('div', { class: 'stack' }); - const previewBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Preview'); - const applyBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Import Hosts'); - - try { - const creds = await apiFetch<{ credentials: Array<{ id: string; type: string }> }>('/api/vault/credentials'); - for (const c of creds.credentials.filter((x) => x.type === 'ssh-key' || x.type === 'ssh-password')) { - credSelect.append(el('option', { value: c.id }, `${c.id} (${c.type})`)); - } - } catch { - // Vault may be locked or empty - } - if (credSelect.options.length === 0) { - credSelect.append(el('option', { value: '' }, 'No SSH credential (unlock Vault first)')); - } - - const close = () => { - if (dlg.open) dlg.close(); - dlg.remove(); - }; - closeBtn.addEventListener('click', close); - dlg.addEventListener('close', () => dlg.remove()); - - const runImport = async (apply: boolean) => { - msgEl.className = 'form-msg muted'; - msgEl.textContent = apply ? 'Importing hosts...' : 'Parsing SSH config...'; - previewBox.replaceChildren(); - try { - const res = await apiFetch<{ - entries: Array<{ alias: string; id: string; host: string; port: number; username: string; jumpHostAlias?: string }>; - warnings: string[]; - createdIds: string[]; - }>('/api/servers/import-ssh-config', { - method: 'POST', - body: { - configText: textarea.value, - defaultCredentialId: credSelect.value || undefined, - apply, - }, - }); - if (res.warnings.length > 0) { - previewBox.append(el('div', { class: 'warn-text mono' }, `Warnings: ${res.warnings.join(' | ')}`)); - } - if (res.entries.length === 0) { - previewBox.append(el('div', { class: 'muted' }, 'No concrete Host blocks found.')); - } else { - for (const e of res.entries) { - previewBox.append( - el('div', { class: 'mono' }, `${e.alias} -> ${e.username}@${e.host}:${e.port}${e.jumpHostAlias ? ` (via ${e.jumpHostAlias})` : ''}`), - ); - } - } - if (apply) { - msgEl.className = 'form-msg ok-text'; - msgEl.textContent = `Imported ${res.createdIds.length} server(s): ${res.createdIds.join(', ')}`; - showToast(`Imported ${res.createdIds.length} server(s) from SSH config.`, 'ok'); - close(); - await onImported(); - } else { - msgEl.className = 'form-msg ok-text'; - msgEl.textContent = `Previewed ${res.entries.length} host(s).`; - } - } catch (err) { - msgEl.className = 'form-msg err-text'; - msgEl.textContent = extractErrorMessage(err); - } - }; - - previewBtn.addEventListener('click', () => void runImport(false)); - applyBtn.addEventListener('click', () => void runImport(true)); - - dlg.append( - el('div', { class: 'row-between' }, el('h1', { id: 'imp-ssh-title' }, 'Import OpenSSH Config'), closeBtn), - el('div', { class: 'row' }, el('label', {}, 'Default SSH Credential:'), credSelect), - textarea, - msgEl, - previewBox, - el('div', { class: 'dialog-actions' }, previewBtn, applyBtn), - ); - document.body.append(dlg); - dlg.showModal(); -} - export async function renderDashboardView( root: HTMLElement, state: ClientState, ): Promise { root.replaceChildren(); - registerDashboardLivePatchers({ - onTick: patchDashboardServerTick, - onStates: patchDashboardServerStates, - }); - registerViewCleanup(() => { - registerDashboardLivePatchers(null); - }); const [res, pinnedRes] = await Promise.all([ apiFetch<{ servers: ServerEntry[] }>('/api/servers'), apiFetch<{ @@ -457,90 +294,18 @@ export async function renderDashboardView( void renderDashboardView(root, state); }); - const importSshBtn = el( - 'button', - { type: 'button', class: 'btn btn-sm mutating-action' }, - 'Import SSH Config', - ); - importSshBtn.addEventListener('click', () => { - void openImportSshConfigDialog(() => renderDashboardView(root, state)); - }); - - const connCount = servers.filter((s) => s.runtime.status === 'connected').length; - const issueCount = servers.length - connCount; - const vaultSummary = !state.vaultRuntimeReady ? 'Vault: sealed (master key required)' : state.vaultState === 'unlocked' ? 'Vault: unlocked (editable)' : 'Vault: locked (collectors & secrets active)'; - const filterSearchInput = el('input', { - type: 'search', - class: 'input-sm', - placeholder: 'Filter host / tag / name...', - value: fleetSearch, - 'aria-label': 'Filter servers', - }) as HTMLInputElement; - - const filterButtons = (['all', 'connected', 'issues'] as const).map((mode) => { - const label = - mode === 'all' - ? `All (${servers.length})` - : mode === 'connected' - ? `Connected (${connCount})` - : `Issues (${issueCount})`; - const b = el( - 'button', - { type: 'button', class: `btn btn-sm${fleetFilter === mode ? ' btn-primary' : ''}` }, - label, - ); - b.addEventListener('click', () => { - fleetFilter = mode; - applyFleetFilter(); - for (const btn of filterButtons) btn.classList.remove('btn-primary'); - b.classList.add('btn-primary'); - }); - return b; - }); - - const applyFleetFilter = () => { - const q = fleetSearch.trim().toLowerCase(); - for (const card of root.querySelectorAll('[data-server-card]')) { - const st = card.getAttribute('data-status') ?? ''; - const hay = card.getAttribute('data-search') ?? ''; - const matchMode = - fleetFilter === 'all' - ? true - : fleetFilter === 'connected' - ? st === 'connected' - : st !== 'connected'; - const matchQ = !q || hay.includes(q); - (card as HTMLElement).hidden = !(matchMode && matchQ); - } - }; - - filterSearchInput.addEventListener('input', () => { - fleetSearch = filterSearchInput.value; - applyFleetFilter(); - }); - root.append( el( 'div', - { class: 'panel stack' }, - el( - 'div', - { class: 'row-between' }, - el('div', {}, el('h1', {}, `Fleet Monitor (${connCount}/${servers.length} connected)`), el('span', { class: 'muted' }, vaultSummary)), - el('div', { class: 'row' }, registerBtn, importSshBtn, rotateFleetBtn, refreshBtn), - ), - el( - 'div', - { class: 'row-between' }, - el('div', { class: 'row' }, ...filterButtons), - filterSearchInput, - ), + { class: 'panel row-between' }, + el('div', {}, el('h1', {}, `Fleet Monitor (${servers.length} servers)`), el('span', { class: 'muted' }, vaultSummary)), + el('div', { class: 'row' }, registerBtn, rotateFleetBtn, refreshBtn), ), actionStatus, ); @@ -749,12 +514,7 @@ export async function renderDashboardView( const card = el( 'article', - { - class: 'panel panel-region', - 'data-server-card': config.id, - 'data-status': runtime.status, - 'data-search': `${config.id} ${config.name} ${config.host} ${config.tags.join(' ')}`.toLowerCase(), - }, + { class: 'panel panel-region', 'data-server-card': config.id }, el( 'div', { class: 'row-between' }, @@ -799,5 +559,4 @@ export async function renderDashboardView( grid.append(card); } root.append(grid); - applyFleetFilter(); } diff --git a/src/client/ts/views/server-detail-view.ts b/src/client/ts/views/server-detail-view.ts index b9b9b8c..cec3ce4 100644 --- a/src/client/ts/views/server-detail-view.ts +++ b/src/client/ts/views/server-detail-view.ts @@ -1,23 +1,19 @@ import type { DiskSample, ProbeSample } from '../../../shared/ws-protocol.js'; import { apiFetch } from '../api.js'; -import { createDualRangeChartSvg, createRangeChartSvg } from '../charts.js'; +import { createRangeChartSvg } from '../charts.js'; import { confirmDialog } from '../dialogs.js'; import { el, extractErrorMessage, - fmtBytesPerSec, fmtTime, type ServerEntry, } from '../state.js'; -import { showToast } from '../toast.js'; type DetailTab = 'metrics' | 'inspector' | 'keys' | 'tunnels'; let activeTab: DetailTab = 'metrics'; let activeRange: '1h' | '6h' | '24h' | '7d' | '30d' = '1h'; let procSortBy: 'cpu' | 'mem' = 'cpu'; -let inspectSudo = false; -let showAllKnownHosts = false; export async function renderServerDetailView( root: HTMLElement, @@ -41,36 +37,6 @@ export async function renderServerDetailView( } const header = el('section', { class: 'panel' }); - const testConnBtn = el( - 'button', - { type: 'button', class: 'btn btn-sm mutating-action' }, - 'Test SSH', - ); - testConnBtn.addEventListener('click', async () => { - testConnBtn.disabled = true; - try { - const res = await apiFetch<{ - ok: boolean; - latencyMs: number; - osDetected?: string; - hostFingerprint?: string; - error?: string; - }>('/api/servers/test-connection', { - method: 'POST', - body: entry.config, - }); - if (res.ok) { - showToast(`SSH OK in ${Math.round(res.latencyMs)}ms (${res.osDetected ?? 'unknown'})`, 'ok'); - } else { - showToast(`SSH test failed: ${res.error ?? 'unknown error'}`, 'err'); - } - } catch (err) { - showToast(extractErrorMessage(err), 'err'); - } finally { - testConnBtn.disabled = false; - } - }); - const reconnBtn = el( 'button', { type: 'button', class: 'btn btn-sm mutating-action' }, @@ -144,7 +110,6 @@ export async function renderServerDetailView( 'div', { class: 'row' }, el('span', { class: 'badge' }, `[${entry.runtime.status.toUpperCase()}]`), - testConnBtn, reconnBtn, delBtn, el('a', { href: '#dashboard', class: 'btn btn-sm' }, '← Dashboard'), @@ -162,7 +127,7 @@ export async function renderServerDetailView( } else if (activeTab === 'inspector') { await renderInspectorTab(body, serverId); } else if (activeTab === 'keys') { - await renderKeysTab(body, serverId, `${entry.config.host}:${entry.config.port}`); + await renderKeysTab(body, serverId); } else { const { renderTunnelsPanel } = await import('./tunnels-panel.js'); await renderTunnelsPanel(body, serverId); @@ -170,20 +135,13 @@ export async function renderServerDetailView( } async function renderMetricsTab(body: HTMLElement, serverId: string): Promise { - const [data, probeHistRes] = await Promise.all([ - apiFetch<{ - range: string; - granularity: 'raw' | '1h' | '1d'; - points: Array>; - latestDisks: DiskSample[]; - latestProbes: Array; - probeHistory?: Array; - diskHistory?: Array<{ ts: number; mountPoint: string; usedPct: number; usedMb: number; totalMb: number }>; - }>(`/api/servers/${encodeURIComponent(serverId)}/metrics?range=${activeRange}`), - apiFetch<{ samples: Array }>( - `/api/servers/${encodeURIComponent(serverId)}/probes/history?range=${activeRange}`, - ).catch(() => ({ samples: [] })), - ]); + const data = await apiFetch<{ + range: string; + granularity: 'raw' | '1h' | '1d'; + points: Array>; + latestDisks: DiskSample[]; + latestProbes: Array; + }>(`/api/servers/${encodeURIComponent(serverId)}/metrics?range=${activeRange}`); const rangeBar = el( 'div', @@ -215,22 +173,6 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise p.load1m ?? p.loadMax ?? 0); - const netRxSeries = data.points.map((p) => p.netRxBps ?? p.netRxAvgBps ?? 0); - const netTxSeries = data.points.map((p) => p.netTxBps ?? p.netTxAvgBps ?? 0); - - const diskMaxByTs = new Map(); - for (const d of data.diskHistory ?? []) { - const prev = diskMaxByTs.get(d.ts) ?? 0; - if (d.usedPct > prev) diskMaxByTs.set(d.ts, d.usedPct); - } - const diskSeries = data.points.some((p) => p.diskMaxPct !== undefined) - ? data.points.map((p) => p.diskMaxPct ?? 0) - : [...diskMaxByTs.entries()].sort((a, b) => a[0] - b[0]).map((x) => x[1]); - - const probeHistory = probeHistRes.samples.length > 0 ? probeHistRes.samples : (data.probeHistory ?? []); - const probeLatencySeries = probeHistory.map((p) => p.latencyMs ?? 0); - const lastRx = netRxSeries.at(-1) ?? 0; - const lastTx = netTxSeries.at(-1) ?? 0; const chartsGrid = el( 'div', @@ -238,25 +180,6 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise p.ok).length; - const failProbes = probeHistory.length - okProbes; - probePanel.append( - el( - 'div', - { class: 'row-between' }, - el('h2', {}, 'Endpoint Health Probes'), - el( - 'span', - { class: 'muted mono' }, - probeHistory.length > 0 ? `${probeHistory.length} checks (${okProbes} ok / ${failProbes} fail in ${activeRange})` : 'No probe history in range', - ), - ), - ); + probePanel.append(el('h2', {}, 'Endpoint Health Probes')); const pTable = el('table'); - pTable.append( - el( - 'thead', - {}, - el( - 'tr', - {}, - el('th', {}, 'Probe ID'), - el('th', {}, 'Status'), - el('th', {}, 'HTTP Code'), - el('th', {}, 'Latency'), - el('th', {}, 'TLS Expiry'), - el('th', {}, 'Checked At'), - el('th', {}, 'Detail'), - el('th', {}, 'Action'), - ), - ), - ); + pTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'Probe ID'), el('th', {}, 'Status'), el('th', {}, 'HTTP Code'), el('th', {}, 'Latency'), el('th', {}, 'Checked At'), el('th', {}, 'Detail')))); const pBody = el('tbody'); if (data.latestProbes.length === 0) { - pBody.append(el('tr', {}, el('td', { colspan: 8, class: 'muted' }, 'No probe results recorded yet.'))); + pBody.append(el('tr', {}, el('td', { colspan: 6, class: 'muted' }, 'No probe results recorded yet.'))); } else { for (const p of data.latestProbes) { - const tlsBadge = - p.certExpiryDays !== undefined - ? el( - 'span', - { - class: `badge ${ - p.certExpiryDays <= 0 - ? 'badge-err' - : p.certExpiryDays <= 14 - ? 'badge-warn' - : 'badge-ok' - }`, - }, - `${p.certExpiryDays}d`, - ) - : el('span', { class: 'muted' }, '—'); - const runBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Run Now'); - runBtn.addEventListener('click', async () => { - runBtn.disabled = true; - try { - const runRes = await apiFetch<{ sample: ProbeSample }>( - `/api/servers/${encodeURIComponent(serverId)}/probes/${encodeURIComponent(p.probeId)}/run`, - { method: 'POST', body: {} }, - ); - showToast( - `Probe "${p.probeId}": ${runRes.sample.ok ? `OK (${Math.round(runRes.sample.latencyMs)}ms)` : runRes.sample.error ?? 'FAIL'}`, - runRes.sample.ok ? 'ok' : 'err', - ); - body.replaceChildren(); - await renderMetricsTab(body, serverId); - } catch (err) { - showToast(extractErrorMessage(err), 'err'); - } finally { - runBtn.disabled = false; - } - }); pBody.append( el( 'tr', @@ -363,10 +220,8 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise { const sortCpuBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'cpu' ? ' btn-primary' : ''}` }, 'Sort CPU'); const sortMemBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'mem' ? ' btn-primary' : ''}` }, 'Sort RAM'); - const sudoBtn = el( - 'button', - { type: 'button', class: `btn btn-sm mutating-action${inspectSudo ? ' btn-primary' : ''}` }, - inspectSudo ? 'Sudo: ON' : '+Sudo', - ); const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh Snapshot'); sortCpuBtn.addEventListener('click', () => { @@ -396,18 +246,13 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise< body.replaceChildren(); void renderInspectorTab(body, serverId); }); - sudoBtn.addEventListener('click', () => { - inspectSudo = !inspectSudo; - body.replaceChildren(); - void renderInspectorTab(body, serverId); - }); refreshBtn.addEventListener('click', () => { body.replaceChildren(); void renderInspectorTab(body, serverId); }); body.append( - el('div', { class: 'panel row-between' }, el('strong', {}, 'On-Demand Server Inspector'), el('div', { class: 'row' }, sortCpuBtn, sortMemBtn, sudoBtn, refreshBtn)), + el('div', { class: 'panel row-between' }, el('strong', {}, 'On-Demand Server Inspector'), el('div', { class: 'row' }, sortCpuBtn, sortMemBtn, refreshBtn)), ); try { @@ -417,53 +262,18 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise< processes: Array<{ pid: number; user: string; cpuPct: number; memPct: number; rssMb: number; command: string }>; ports: Array<{ proto: string; localAddress: string; process: string }>; thermals: Array<{ zone: string; tempC: number }>; - }>(`/api/servers/${encodeURIComponent(serverId)}/inspect?sort=${procSortBy}&sudo=${inspectSudo ? 'true' : 'false'}`); + }>(`/api/servers/${encodeURIComponent(serverId)}/inspect`); const sortedProcs = [...res.processes].sort((a, b) => procSortBy === 'cpu' ? b.cpuPct - a.cpuPct : b.memPct - a.memPct, ); const procTable = el('table'); - procTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'PID'), el('th', {}, 'User'), el('th', {}, 'CPU%'), el('th', {}, 'MEM%'), el('th', {}, 'RSS'), el('th', {}, 'Command'), el('th', {}, 'Signal')))); + procTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'PID'), el('th', {}, 'User'), el('th', {}, 'CPU%'), el('th', {}, 'MEM%'), el('th', {}, 'RSS'), el('th', {}, 'Command')))); const pBody = el('tbody'); for (const p of sortedProcs) { - const makeSigBtn = (sig: 'SIGTERM' | 'SIGKILL', cls: string) => { - const b = el('button', { type: 'button', class: `btn btn-sm ${cls} mutating-action` }, sig === 'SIGTERM' ? 'TERM' : 'KILL'); - b.addEventListener('click', async () => { - const ok = await confirmDialog( - 'dialog-confirm', - `Send ${sig} to PID ${p.pid} (${p.command.slice(0, 48)}) on ${serverId}?`, - ); - if (!ok) return; - try { - const sigRes = await apiFetch<{ ok: boolean; error?: string }>( - `/api/servers/${encodeURIComponent(serverId)}/processes/${p.pid}/signal`, - { method: 'POST', body: { signal: sig, sudo: inspectSudo } }, - ); - showToast( - sigRes.ok ? `Sent ${sig} to PID ${p.pid}.` : `Signal ${sig} failed: ${sigRes.error ?? 'error'}`, - sigRes.ok ? 'ok' : 'err', - ); - body.replaceChildren(); - await renderInspectorTab(body, serverId); - } catch (err) { - showToast(extractErrorMessage(err), 'err'); - } - }); - return b; - }; pBody.append( - el( - 'tr', - {}, - el('td', { class: 'mono' }, String(p.pid)), - el('td', { class: 'mono' }, p.user), - el('td', { class: 'mono' }, `${p.cpuPct}`), - el('td', { class: 'mono' }, `${p.memPct}`), - el('td', { class: 'mono' }, `${p.rssMb}M`), - el('td', { class: 'mono' }, p.command.slice(0, 90)), - el('td', {}, el('div', { class: 'row' }, makeSigBtn('SIGTERM', ''), makeSigBtn('SIGKILL', 'btn-danger'))), - ), + el('tr', {}, el('td', { class: 'mono' }, String(p.pid)), el('td', { class: 'mono' }, p.user), el('td', { class: 'mono' }, `${p.cpuPct}`), el('td', { class: 'mono' }, `${p.memPct}`), el('td', { class: 'mono' }, `${p.rssMb}M`), el('td', { class: 'mono' }, p.command.slice(0, 90))), ); } procTable.append(pBody); @@ -496,7 +306,7 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise< } } -async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: string): Promise { +async function renderKeysTab(body: HTMLElement, serverId: string): Promise { const msg = el('p', { class: 'form-msg' }); const rotateBtn = el( 'button', @@ -520,7 +330,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: s const r = res.results[0]; if (r?.ok) { body.replaceChildren(); - await renderKeysTab(body, serverId, hostPortKey); + await renderKeysTab(body, serverId); } else { msg.className = 'form-msg err-text'; msg.textContent = `Rotation failed (rolledBack=${String(r?.rolledBack)}): ${r?.error ?? 'unknown'}`; @@ -549,7 +359,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: s body: { credentialId: deploySelect.value }, }); body.replaceChildren(); - await renderKeysTab(body, serverId, hostPortKey); + await renderKeysTab(body, serverId); } catch (err) { msg.className = 'form-msg err-text'; msg.textContent = extractErrorMessage(err); @@ -566,72 +376,6 @@ async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: s msg, ); - // Known Hosts (Multi-Algo) - try { - const khRes = await apiFetch<{ - knownHosts: Array<{ hostPort: string; algorithm: string; fingerprint: string; updatedAt: number }>; - }>('/api/servers/known-hosts'); - const filteredKh = showAllKnownHosts - ? khRes.knownHosts - : khRes.knownHosts.filter((kh) => kh.hostPort === hostPortKey); - const scopeBtn = el( - 'button', - { type: 'button', class: 'btn btn-sm' }, - showAllKnownHosts ? `Filter ${hostPortKey}` : `Show All (${khRes.knownHosts.length})`, - ); - scopeBtn.addEventListener('click', () => { - showAllKnownHosts = !showAllKnownHosts; - body.replaceChildren(); - void renderKeysTab(body, serverId, hostPortKey); - }); - const khTable = el('table'); - khTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'Host:Port'), el('th', {}, 'Algorithm'), el('th', {}, 'Fingerprint'), el('th', {}, 'Updated'), el('th', {}, 'Action')))); - const khBody = el('tbody'); - if (filteredKh.length === 0) { - khBody.append(el('tr', {}, el('td', { colspan: 5, class: 'muted' }, 'No trusted host keys in scope.'))); - } else { - for (const kh of filteredKh) { - const delKhBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete'); - delKhBtn.addEventListener('click', async () => { - const ok = await confirmDialog( - 'dialog-confirm', - `Remove trusted ${kh.algorithm} key for ${kh.hostPort}? Next connection will require TOFU approval.`, - ); - if (!ok) return; - await apiFetch( - `/api/servers/known-hosts?hostPort=${encodeURIComponent(kh.hostPort)}&algorithm=${encodeURIComponent(kh.algorithm)}`, - { method: 'DELETE' }, - ); - showToast(`Deleted ${kh.algorithm} key for ${kh.hostPort}.`, 'ok'); - body.replaceChildren(); - await renderKeysTab(body, serverId, hostPortKey); - }); - khBody.append( - el( - 'tr', - {}, - el('td', { class: 'mono' }, kh.hostPort), - el('td', { class: 'mono' }, kh.algorithm), - el('td', { class: 'mono' }, kh.fingerprint), - el('td', { class: 'mono' }, fmtTime(kh.updatedAt)), - el('td', {}, delKhBtn), - ), - ); - } - } - khTable.append(khBody); - body.append( - el( - 'section', - { class: 'panel' }, - el('div', { class: 'row-between' }, el('h2', {}, 'Trusted Host Keys (known_hosts)'), scopeBtn), - el('div', { class: 'table-wrap' }, khTable), - ), - ); - } catch (err) { - body.append(el('div', { class: 'panel err-text' }, extractErrorMessage(err))); - } - try { const res = await apiFetch<{ entries: Array<{ @@ -666,7 +410,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: s body: { fingerprint: k.fingerprint }, }); body.replaceChildren(); - await renderKeysTab(body, serverId, hostPortKey); + await renderKeysTab(body, serverId); }); } kBody.append( diff --git a/src/client/ts/views/settings-ops-panel.ts b/src/client/ts/views/settings-ops-panel.ts deleted file mode 100644 index 34af14b..0000000 --- a/src/client/ts/views/settings-ops-panel.ts +++ /dev/null @@ -1,360 +0,0 @@ -import { apiFetch } from '../api.js'; -import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; -import { showToast } from '../toast.js'; - -interface AuditRow { - id: number; - ts: number; - action: string; - actor_ip: string; - target: string | null; - status: string; - details: string | null; -} - -interface BackupScheduleStatus { - enabled: boolean; - cron: string; - timezone: string; - destination: 'local' | 'sftp'; - running: boolean; - lastRunAt: number | null; - lastStatus: 'never' | 'ok' | 'error' | 'skipped'; - lastFilename: string | null; - lastError: string | null; - nextRunAt: number | null; - localFiles: Array<{ name: string; sizeBytes: number; mtimeMs: number }>; -} - -export async function renderSettingsOpsPanels( - host: HTMLElement, - state: ClientState, - creds: Array<{ id: string; name: string; type: string }>, - onReloadState: () => Promise, -): Promise { - const settingsObj = (state.overview?.settings ?? {}) as Record; - const runtimeCfg = (settingsObj.runtime ?? {}) as { throttleMode?: string }; - const metricsCfg = (settingsObj.metrics ?? {}) as { - prometheusEnabled?: boolean; - prometheusSecretRef?: string; - prometheusTokenHash?: string; - }; - const schedCfg = (settingsObj.scheduledBackup ?? {}) as { - enabled?: boolean; - cron?: string; - timezone?: string; - destination?: 'local' | 'sftp'; - localDir?: string; - remoteServerId?: string; - remotePath?: string; - retentionCount?: number; - passphraseSecretRef?: string; - }; - - // 1. Runtime Resource Profile & Prometheus /metrics - const opsGrid = el('div', { class: 'grid-2' }); - - const rtPanel = el('section', { class: 'panel panel-region' }); - rtPanel.append( - el('h2', {}, 'Runtime Throttle Profile'), - el( - 'p', - { class: 'muted' }, - 'Tune polling, log caps, and worker concurrency for constrained 1 vCPU / 1 GB RAM VPS vs larger servers.', - ), - ); - const modeSel = el( - 'select', - {}, - el('option', { value: 'low-resource', selected: (runtimeCfg.throttleMode ?? 'low-resource') === 'low-resource' }, 'low-resource (1 vCPU / 1 GB RAM — bounded polls & caches)'), - el('option', { value: 'balanced', selected: runtimeCfg.throttleMode === 'balanced' }, 'balanced (moderate parallelism & buffer caps)'), - el('option', { value: 'unthrottled', selected: runtimeCfg.throttleMode === 'unthrottled' }, 'unthrottled (high parallelism for multi-core hosts)'), - ) as HTMLSelectElement; - const rtMsg = el('p', { class: 'form-msg' }); - const saveRtBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Save Runtime Mode'); - saveRtBtn.addEventListener('click', async () => { - rtMsg.textContent = ''; - try { - const nextSettings = { - ...settingsObj, - runtime: { throttleMode: modeSel.value }, - }; - await apiFetch('/api/config/file', { - method: 'PUT', - body: { - path: 'settings.json', - content: `${JSON.stringify(nextSettings, null, 2)}\n`, - summary: `runtime.throttleMode -> ${modeSel.value}`, - }, - }); - showToast(`Runtime profile set to ${modeSel.value}.`, 'ok'); - await onReloadState(); - } catch (err) { - rtMsg.className = 'form-msg err-text'; - rtMsg.textContent = extractErrorMessage(err); - } - }); - rtPanel.append(el('label', {}, 'Throttle Mode'), modeSel, el('div', { class: 'row', style: 'margin-top:8px' }, saveRtBtn), rtMsg); - - const promPanel = el('section', { class: 'panel panel-region' }); - promPanel.append( - el('h2', {}, 'Prometheus /metrics Endpoint'), - el( - 'p', - { class: 'muted' }, - 'Exposes fleet gauges on GET /metrics with Bearer token auth (either rotated token hash or Vault secret).', - ), - ); - const promChk = el('input', { type: 'checkbox', checked: metricsCfg.prometheusEnabled ? true : undefined }) as HTMLInputElement; - const promMsg = el('p', { class: 'form-msg' }); - const tokenBox = el('pre', { class: 'mono warn-text', hidden: true }); - const copyPromBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: true }, 'Copy Bearer Token'); - copyPromBtn.addEventListener('click', () => { - void navigator.clipboard?.writeText(tokenBox.textContent ?? ''); - copyPromBtn.textContent = 'Copied!'; - }); - - const savePromBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Save Metrics Setting'); - savePromBtn.addEventListener('click', async () => { - try { - const nextSettings = { - ...settingsObj, - metrics: { ...metricsCfg, prometheusEnabled: promChk.checked }, - }; - await apiFetch('/api/config/file', { - method: 'PUT', - body: { - path: 'settings.json', - content: `${JSON.stringify(nextSettings, null, 2)}\n`, - summary: `metrics.prometheusEnabled -> ${String(promChk.checked)}`, - }, - }); - showToast(`Prometheus /metrics ${promChk.checked ? 'enabled' : 'disabled'}.`, 'ok'); - await onReloadState(); - } catch (err) { - promMsg.className = 'form-msg err-text'; - promMsg.textContent = extractErrorMessage(err); - } - }); - - const rotPromBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Rotate Bearer Token'); - rotPromBtn.addEventListener('click', async () => { - try { - const r = await apiFetch<{ token: string; prometheusEnabled: boolean }>('/api/config/prometheus-token', { - method: 'POST', - body: { enable: true }, - }); - promChk.checked = r.prometheusEnabled; - tokenBox.hidden = false; - tokenBox.textContent = r.token; - copyPromBtn.hidden = false; - promMsg.className = 'form-msg ok-text'; - promMsg.textContent = 'New Bearer token generated (copy now — shown once):'; - showToast('Rotated Prometheus Bearer token.', 'ok'); - } catch (err) { - promMsg.className = 'form-msg err-text'; - promMsg.textContent = extractErrorMessage(err); - } - }); - - promPanel.append( - el('label', { class: 'chk-row' }, promChk, 'Enable GET /metrics endpoint'), - el( - 'div', - { class: 'mono muted', style: 'margin-top:4px' }, - metricsCfg.prometheusTokenHash - ? 'Auth status: Bearer token hash configured' - : metricsCfg.prometheusSecretRef - ? `Auth status: Vault ref ${metricsCfg.prometheusSecretRef}` - : 'Auth status: Rotate Bearer Token to enable authenticated scrapes', - ), - el('div', { class: 'row', style: 'margin-top:8px' }, savePromBtn, rotPromBtn), - promMsg, - tokenBox, - copyPromBtn, - ); - - opsGrid.append(rtPanel, promPanel); - host.append(opsGrid); - - // 2. Scheduled Encrypted Backups - const schedPanel = el('section', { class: 'panel panel-region' }); - const schedStatusRes = await apiFetch<{ schedule: BackupScheduleStatus }>('/api/backup/schedule').catch(() => null); - const st = schedStatusRes?.schedule; - schedPanel.append( - el('h2', {}, 'Scheduled .gcoord.enc Backups'), - el( - 'p', - { class: 'muted mono' }, - st - ? `Status: ${st.lastStatus.toUpperCase()} | Running: ${String(st.running)} | Local bundles: ${st.localFiles.length} | Next: ${fmtTime(st.nextRunAt)}${st.lastError ? ` | Err: ${st.lastError}` : ''}` - : 'Backup scheduler unavailable.', - ), - ); - - const sbEnChk = el('input', { type: 'checkbox', checked: schedCfg.enabled ? true : undefined }) as HTMLInputElement; - const sbCronInp = el('input', { value: schedCfg.cron ?? '0 3 * * *', placeholder: '0 3 * * *' }) as HTMLInputElement; - const sbTzInp = el('input', { value: schedCfg.timezone ?? 'UTC', placeholder: 'UTC' }) as HTMLInputElement; - const sbDestSel = el( - 'select', - {}, - el('option', { value: 'local', selected: (schedCfg.destination ?? 'local') === 'local' }, 'local'), - el('option', { value: 'sftp', selected: schedCfg.destination === 'sftp' }, 'sftp'), - ) as HTMLSelectElement; - const sbLocalDirInp = el('input', { value: schedCfg.localDir ?? 'backups', placeholder: 'backups' }) as HTMLInputElement; - const sbRetInp = el('input', { type: 'number', min: 1, max: 100, value: String(schedCfg.retentionCount ?? 7) }) as HTMLInputElement; - const sbSrvInp = el('input', { value: schedCfg.remoteServerId ?? '', placeholder: 'Remote Server ID (sftp)' }) as HTMLInputElement; - const sbPathInp = el('input', { value: schedCfg.remotePath ?? '', placeholder: '/var/backups/gcoord (sftp)' }) as HTMLInputElement; - const sbRefSel = el( - 'select', - {}, - el('option', { value: '' }, '(Use Vault Master Key)'), - ...creds.map((c) => el('option', { value: c.id, selected: schedCfg.passphraseSecretRef === c.id }, `${c.id} (${c.type})`)), - ) as HTMLSelectElement; - - const sbMsg = el('p', { class: 'form-msg' }); - const saveSbBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Save Schedule'); - saveSbBtn.addEventListener('click', async () => { - sbMsg.textContent = ''; - try { - const nextSettings = { - ...settingsObj, - scheduledBackup: { - enabled: sbEnChk.checked, - cron: sbCronInp.value.trim() || '0 3 * * *', - timezone: sbTzInp.value.trim() || 'UTC', - destination: sbDestSel.value as 'local' | 'sftp', - localDir: sbLocalDirInp.value.trim() || 'backups', - retentionCount: Number(sbRetInp.value || 7), - ...(sbSrvInp.value.trim() ? { remoteServerId: sbSrvInp.value.trim() } : {}), - ...(sbPathInp.value.trim() ? { remotePath: sbPathInp.value.trim() } : {}), - ...(sbRefSel.value ? { passphraseSecretRef: sbRefSel.value } : {}), - }, - }; - await apiFetch('/api/config/file', { - method: 'PUT', - body: { - path: 'settings.json', - content: `${JSON.stringify(nextSettings, null, 2)}\n`, - summary: 'Update scheduled backup configuration', - }, - }); - showToast('Scheduled backup config saved.', 'ok'); - await onReloadState(); - } catch (err) { - sbMsg.className = 'form-msg err-text'; - sbMsg.textContent = extractErrorMessage(err); - } - }); - - const runSbBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Run Backup Now'); - runSbBtn.addEventListener('click', async () => { - sbMsg.className = 'form-msg muted'; - sbMsg.textContent = 'Running scheduled backup...'; - try { - const r = await apiFetch<{ ok: boolean; filename?: string; error?: string }>('/api/backup/schedule/run', { - method: 'POST', - body: {}, - }); - sbMsg.className = r.ok ? 'form-msg ok-text' : 'form-msg err-text'; - sbMsg.textContent = r.ok ? `Backup created: ${r.filename ?? 'ok'}` : (r.error ?? 'Backup failed'); - showToast(sbMsg.textContent, r.ok ? 'ok' : 'err'); - } catch (err) { - sbMsg.className = 'form-msg err-text'; - sbMsg.textContent = extractErrorMessage(err); - } - }); - - schedPanel.append( - el('label', { class: 'chk-row' }, sbEnChk, 'Enable scheduled encrypted backups'), - el( - 'div', - { class: 'grid-3', style: 'margin-top:8px' }, - el('div', {}, el('label', {}, 'Cron'), sbCronInp), - el('div', {}, el('label', {}, 'Timezone'), sbTzInp), - el('div', {}, el('label', {}, 'Destination'), sbDestSel), - el('div', {}, el('label', {}, 'Local Dir (under data/)'), sbLocalDirInp), - el('div', {}, el('label', {}, 'Retention Count'), sbRetInp), - el('div', {}, el('label', {}, 'Passphrase Secret'), sbRefSel), - el('div', {}, el('label', {}, 'Remote Server (SFTP)'), sbSrvInp), - el('div', {}, el('label', {}, 'Remote Path (SFTP)'), sbPathInp), - ), - el('div', { class: 'row', style: 'margin-top:8px' }, saveSbBtn, runSbBtn), - sbMsg, - ); - host.append(schedPanel); - - // 3. Filterable & Exportable Audit Log - const auditPanel = el('section', { class: 'panel panel-region' }); - const initialAudit = await apiFetch<{ total: number; items: AuditRow[]; actions?: string[] }>('/api/audit?limit=40'); - - const actSel = el( - 'select', - { class: 'input-sm' }, - el('option', { value: '' }, 'All Actions'), - ...(initialAudit.actions ?? []).map((a) => el('option', { value: a }, a)), - ) as HTMLSelectElement; - const stSel = el( - 'select', - { class: 'input-sm' }, - el('option', { value: '' }, 'All Statuses'), - el('option', { value: 'ok' }, 'ok'), - el('option', { value: 'denied' }, 'denied'), - el('option', { value: 'error' }, 'error'), - ) as HTMLSelectElement; - const qInput = el('input', { type: 'search', class: 'input-sm', placeholder: 'Filter target/IP/details...' }) as HTMLInputElement; - const applyBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary' }, 'Filter'); - const exportCsvLink = el('a', { href: '/api/audit/export?format=csv', class: 'btn btn-sm', download: '' }, 'Export CSV'); - const exportNdLink = el('a', { href: '/api/audit/export?format=ndjson', class: 'btn btn-sm', download: '' }, 'Export NDJSON'); - const titleEl = el('h2', {}, `Security & Action Audit Log (${initialAudit.total} entries)`); - const aBody = el('tbody'); - - const buildAuditQuery = () => { - const p = new URLSearchParams(); - p.set('limit', '60'); - if (actSel.value) p.set('action', actSel.value); - if (stSel.value) p.set('status', stSel.value); - if (qInput.value.trim()) p.set('q', qInput.value.trim()); - return p.toString(); - }; - - const renderRows = (rows: AuditRow[], total: number) => { - titleEl.textContent = `Security & Action Audit Log (${total} matching)`; - const qStr = buildAuditQuery(); - exportCsvLink.setAttribute('href', `/api/audit/export?format=csv&${qStr}`); - exportNdLink.setAttribute('href', `/api/audit/export?format=ndjson&${qStr}`); - aBody.replaceChildren(); - for (const row of rows) { - aBody.append( - el( - 'tr', - {}, - el('td', { class: 'mono' }, fmtTime(row.ts)), - el('td', { class: 'mono' }, row.action), - el('td', {}, el('span', { class: `badge ${row.status === 'ok' ? 'badge-ok' : 'badge-err'}` }, row.status)), - el('td', { class: 'mono' }, row.target ?? '—'), - el('td', { class: 'mono' }, row.actor_ip), - el('td', { class: 'mono muted' }, row.details ?? '—'), - ), - ); - } - }; - renderRows(initialAudit.items, initialAudit.total); - - applyBtn.addEventListener('click', async () => { - const res = await apiFetch<{ total: number; items: AuditRow[] }>(`/api/audit?${buildAuditQuery()}`); - renderRows(res.items, res.total); - }); - - const aTable = el('table'); - aTable.append( - el('thead', {}, el('tr', {}, el('th', {}, 'Timestamp'), el('th', {}, 'Action'), el('th', {}, 'Status'), el('th', {}, 'Target'), el('th', {}, 'IP'), el('th', {}, 'Details'))), - aBody, - ); - auditPanel.append( - el('div', { class: 'row-between' }, titleEl, el('div', { class: 'row' }, exportCsvLink, exportNdLink)), - el('div', { class: 'row', style: 'margin:8px 0' }, actSel, stSel, qInput, applyBtn), - el('div', { class: 'table-wrap' }, aTable), - ); - host.append(auditPanel); -} diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts index 55c942e..4830224 100644 --- a/src/client/ts/views/settings-view.ts +++ b/src/client/ts/views/settings-view.ts @@ -20,6 +20,16 @@ interface SessionRow { current: boolean; } +interface AuditRow { + id: number; + ts: number; + action: string; + actor_ip: string; + target: string | null; + status: string; + details: string | null; +} + interface FactorsData { passwords: Array<{ id: string; label: string; createdAt: number }>; totps: Array<{ id: string; label: string; createdAt: number }>; @@ -45,8 +55,9 @@ export async function renderSettingsView( ): Promise { root.replaceChildren(); - const [sessRes, factorsRes, credsRes] = await Promise.all([ + const [sessRes, auditRes, factorsRes, credsRes] = await Promise.all([ apiFetch<{ sessions: SessionRow[] }>('/api/auth/sessions'), + apiFetch<{ total: number; items: AuditRow[] }>('/api/audit?limit=40'), apiFetch('/api/auth/factors'), apiFetch<{ credentials: Array<{ id: string; name: string; type: string }> }>( '/api/vault/credentials', @@ -187,33 +198,12 @@ export async function renderSettingsView( 'select', {}, el('option', { value: 'off', selected: sec.stepUpPolicy === 'off' ? true : undefined }, 'Off (never re-prompt)'), - el('option', { value: 'session', selected: sec.stepUpPolicy === 'session' ? true : undefined }, 'Once per login session'), + el('option', { value: 'session', selected: sec.stepUpPolicy === 'session' ? true : undefined }, 'Once per login session (7d)'), el('option', { value: '24h', selected: sec.stepUpPolicy === '24h' ? true : undefined }, '24 hours'), - el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour'), - el('option', { value: '15m', selected: sec.stepUpPolicy === '15m' ? true : undefined }, '15 minutes (v1.1 default)'), + el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour (default)'), el('option', { value: '5m', selected: sec.stepUpPolicy === '5m' ? true : undefined }, '5 minutes'), el('option', { value: 'every-action', selected: sec.stepUpPolicy === 'every-action' ? true : undefined }, 'Every sensitive action'), ); - const allowSameOriginProxyChk = el('input', { - type: 'checkbox', - checked: sec.allowSameOriginProxy ? true : undefined, - }) as HTMLInputElement; - const egressCidrsInput = el('input', { - value: (sec.egressAllowedCidrs ?? []).join(', '), - placeholder: 'e.g. 10.20.0.0/24 (blank = block all private IPs)', - }) as HTMLInputElement; - const sessTtlInput = el('input', { - type: 'number', - min: 1, - max: 720, - value: String(sec.sessionTtlHours ?? 168), - }) as HTMLInputElement; - const sessIdleInput = el('input', { - type: 'number', - min: 0, - max: 10080, - value: String(sec.sessionIdleTimeoutMin ?? 60), - }) as HTMLInputElement; const methodSel = el( 'select', {}, @@ -280,7 +270,6 @@ export async function renderSettingsView( policyMsg.textContent = ''; try { const nextSecurity: ClientSecuritySettings = { - ...sec, requireTotpOnLogin: reqTotpChk.checked, passwordMode: pwModeSel.value as 'any' | 'all', totpMode: totpModeSel.value as 'any' | 'all', @@ -289,13 +278,6 @@ export async function renderSettingsView( elevateOnLogin: elevateLoginChk.checked, keepElevationOnSafeMode: keepSafeChk.checked, enableEmergencySecretsBackup: backupChk.checked, - allowSameOriginProxy: allowSameOriginProxyChk.checked, - egressAllowedCidrs: egressCidrsInput.value - .split(',') - .map((s) => s.trim()) - .filter(Boolean), - sessionTtlHours: Number(sessTtlInput.value || 168), - sessionIdleTimeoutMin: Number(sessIdleInput.value || 0), }; const nextSettings = { ...(state.overview?.settings ?? {}), @@ -325,18 +307,14 @@ export async function renderSettingsView( el('div', {}, el('label', {}, 'TOTP Matching Mode'), totpModeSel), el('div', {}, el('label', {}, 'Step-Up Re-Auth Window'), policySel), el('div', {}, el('label', {}, 'Step-Up Method'), methodSel), - el('div', {}, el('label', {}, 'Session Max Lifetime (hours)'), sessTtlInput), - el('div', {}, el('label', {}, 'Session Idle Timeout (min, 0=off)'), sessIdleInput), ), - el('div', { style: 'margin-top:8px' }, el('label', {}, 'Egress Allowed CIDRs / IPs (CSV)'), egressCidrsInput), el( 'div', { class: 'stack', style: 'margin-top:8px' }, el('label', { class: 'chk-row' }, reqTotpChk, 'Require TOTP code during Login'), el('label', { class: 'chk-row' }, elevateLoginChk, 'Auto-elevate session on Login (skips immediate Step-Up)'), el('label', { class: 'chk-row' }, keepSafeChk, 'Keep Step-Up elevation when toggling Safe Mode ON'), - el('label', { class: 'chk-row' }, allowSameOriginProxyChk, 'Allow same-origin HTTP proxy fallback (less strict cookie isolation than isolated origin)'), - el('label', { class: 'chk-row' }, backupChk, 'Maintain passwordless emergency secrets backup in data/recovery/ (master key + vault creds only; login passwords never stored)'), + el('label', { class: 'chk-row' }, backupChk, 'Maintain automatic chmod 0600 secrets backup in data/recovery/'), ), el('div', { class: 'row', style: 'margin-top:8px' }, savePolicyBtn), policyMsg, @@ -752,7 +730,7 @@ export async function renderSettingsView( 'p', { class: 'muted' }, isWebAuthnSupported() - ? 'Enroll device biometrics or hardware security keys for one-tap passwordless sign-in and Step-Up verification. Reverse-proxy overrides: GCOORD_WEBAUTHN_RP_ID and GCOORD_WEBAUTHN_ORIGINS.' + ? 'Enroll device biometrics or hardware security keys for one-tap passwordless sign-in and Step-Up verification.' : 'Passkeys require HTTPS (e.g. Cloudflare Tunnel) or http://localhost — plain HTTP or raw IP URLs block navigator.credentials.', ), ); @@ -839,7 +817,7 @@ export async function renderSettingsView( el( 'p', { class: 'muted mono' }, - `Passwordless bundle (login passwords are never written) — Path: ${rb.filePath} (chmod 0600) | Exists: ${rb.exists ? 'YES' : 'NO'} | MasterKeySaved: ${rb.hasMasterKey ? 'YES' : 'NO'} | VaultCreds: ${rb.credentialCount} | Snapshots: ${rb.snapshotCount}`, + `Path: ${rb.filePath} (chmod 0600) | Exists: ${rb.exists ? 'YES' : 'NO'} | MasterKeySaved: ${rb.hasMasterKey ? 'YES' : 'NO'} | VaultCreds: ${rb.credentialCount} | Snapshots: ${rb.snapshotCount}`, ), ); const bMsg = el('p', { class: 'form-msg' }); @@ -859,10 +837,7 @@ export async function renderSettingsView( dlBackupBtn.addEventListener('click', async () => { bMsg.textContent = ''; try { - const res = await apiFetch<{ bundle: unknown }>('/api/auth/recovery-backup/export', { - method: 'POST', - body: {}, - }); + const res = await apiFetch<{ bundle: unknown }>('/api/auth/recovery-backup/export'); const blob = new Blob([`${JSON.stringify(res.bundle, null, 2)}\n`], { type: 'application/json', }); @@ -969,9 +944,41 @@ export async function renderSettingsView( sessPanel.append(el('div', { class: 'table-wrap' }, sTable)); root.append(sessPanel); - // 6. Runtime Profile, Prometheus /metrics, Scheduled Backups & Filterable Audit Log (lazy chunk) - const opsHost = el('div', { class: 'stack' }); - root.append(opsHost); - const { renderSettingsOpsPanels } = await import('./settings-ops-panel.js'); - await renderSettingsOpsPanels(opsHost, state, credsRes.credentials, onReloadState); + // 6. Audit Log + const auditPanel = el('section', { class: 'panel panel-region' }); + auditPanel.append(el('h2', {}, `Security & Action Audit Log (${auditRes.total} entries)`)); + const aTable = el('table'); + aTable.append( + el( + 'thead', + {}, + el('tr', {}, el('th', {}, 'Timestamp'), el('th', {}, 'Action'), el('th', {}, 'Status'), el('th', {}, 'Target'), el('th', {}, 'IP'), el('th', {}, 'Details')), + ), + ); + const aBody = el('tbody'); + for (const row of auditRes.items) { + aBody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, fmtTime(row.ts)), + el('td', { class: 'mono' }, row.action), + el( + 'td', + {}, + el( + 'span', + { class: `badge ${row.status === 'ok' ? 'badge-ok' : 'badge-err'}` }, + row.status, + ), + ), + el('td', { class: 'mono' }, row.target ?? '—'), + el('td', { class: 'mono' }, row.actor_ip), + el('td', { class: 'mono muted' }, row.details ?? '—'), + ), + ); + } + aTable.append(aBody); + auditPanel.append(el('div', { class: 'table-wrap' }, aTable)); + root.append(auditPanel); } diff --git a/src/client/ts/views/sftp-view.ts b/src/client/ts/views/sftp-view.ts index 585203d..3359bf3 100644 --- a/src/client/ts/views/sftp-view.ts +++ b/src/client/ts/views/sftp-view.ts @@ -1,15 +1,7 @@ -import { collapseDiffHunks, computeLineDiff } from '../../../shared/diff.js'; +import { computeLineDiff } from '../../../shared/diff.js'; import { apiFetch, apiUploadBinary } from '../api.js'; import { confirmDialog } from '../dialogs.js'; -import { - el, - extractErrorMessage, - fmtTime, - registerViewCleanup, - type ClientState, - type ServerEntry, -} from '../state.js'; -import { showToast } from '../toast.js'; +import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js'; import { renderTunnelsPanel } from './tunnels-panel.js'; interface SftpEntry { @@ -20,9 +12,6 @@ interface SftpEntry { mode: number; permissionsOctal: string; mtimeMs: number; - uid?: number; - gid?: number; - symlinkTarget?: string; } interface SftpTextPayload { @@ -38,8 +27,6 @@ let currentServerId = ''; let currentPath = ''; let activeEdit: SftpTextPayload | null = null; let activeEditSudo = false; -let searchMatches: string[] | null = null; -let lastSearchQuery = ''; function fmtFileSize(bytes: number): string { if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes} B`; @@ -55,35 +42,16 @@ function showSftpDiffDialog( onConfirm: (force: boolean) => Promise, ): void { const diff = computeLineDiff(originalText, nextText, 'remote', 'edited'); - const collapsed = diff.collapsedLines ?? collapseDiffHunks(diff.lines); - const hasHunk = collapsed.some((e) => e.type === 'hunk'); - let expanded = !hasHunk; - const dialog = document.createElement('dialog'); dialog.className = 'dialog-wide'; dialog.setAttribute('aria-labelledby', 'sftp-diff-title'); const pre = el('pre', { class: 'diff-body mono' }); - const toggleDiffBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: !hasHunk }, 'Expand Full Diff'); - const renderDiffBody = () => { - pre.replaceChildren(); - const src = expanded ? diff.lines : collapsed; - for (const entry of src) { - if (entry.type === 'hunk') { - pre.append(el('div', { class: 'diff-hunk-sep' }, entry.text)); - } else { - const cls = entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : ''; - const prefix = entry.type === 'add' ? '+' : entry.type === 'del' ? '-' : ' '; - pre.append(el('div', { class: cls }, `${prefix}${entry.text}`)); - } - } - toggleDiffBtn.textContent = expanded ? 'Collapse Context' : 'Expand Full Diff'; - }; - toggleDiffBtn.addEventListener('click', () => { - expanded = !expanded; - renderDiffBody(); - }); - renderDiffBody(); + for (const line of diff.lines) { + const cls = line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : ''; + const prefix = line.type === 'add' ? '+' : line.type === 'del' ? '-' : ' '; + pre.append(el('div', { class: cls }, `${prefix}${line.text}`)); + } const errEl = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' }); const forceWrap = el('div', { hidden: true }); @@ -115,7 +83,7 @@ function showSftpDiffDialog( dialog.append( el('div', { class: 'row-between' }, el('h1', { id: 'sftp-diff-title' }, `Pre-Save Diff: ${filePath}${sudo ? ' [SUDO]' : ''}`), cancelBtn), - el('div', { class: 'row-between' }, el('p', { class: 'mono muted' }, `+${diff.additions} additions, -${diff.deletions} deletions`), toggleDiffBtn), + el('p', { class: 'mono muted' }, `+${diff.additions} additions, -${diff.deletions} deletions`), pre, errEl, el('div', { class: 'dialog-actions' }, forceWrap, writeBtn), @@ -170,13 +138,9 @@ export async function renderSftpView( return; } - const targetServer = q.server ?? q.serverId; - if (targetServer && servers.some((s) => s.config.id === targetServer)) { - if (currentServerId !== targetServer) { - currentPath = ''; - searchMatches = null; - } - currentServerId = targetServer; + if (q.server && servers.some((s) => s.config.id === q.server)) { + if (currentServerId !== q.server) currentPath = ''; + currentServerId = q.server; } else if (!currentServerId || !servers.some((s) => s.config.id === currentServerId)) { currentServerId = servers[0]!.config.id; } @@ -221,7 +185,6 @@ export async function renderSftpView( const goPath = (nextPath: string) => { currentPath = nextPath; activeEdit = null; - searchMatches = null; void renderSftpView(root, state); }; goBtn.addEventListener('click', () => goPath(pathInput.value.trim() || '~')); @@ -236,7 +199,6 @@ export async function renderSftpView( refreshBtn.addEventListener('click', () => void renderSftpView(root, state)); const mkdirBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ Folder'); - const touchBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ File'); const uploadInput = el('input', { type: 'file', multiple: true, style: 'display:none' }); const uploadBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Upload Files'); uploadBtn.addEventListener('click', () => uploadInput.click()); @@ -295,63 +257,6 @@ export async function renderSftpView( } }); - touchBtn.addEventListener('click', async () => { - const name = window.prompt('New empty file name:'); - if (!name || !name.trim()) return; - const target = currentPath === '/' ? `/${name.trim()}` : `${currentPath}/${name.trim()}`; - try { - await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/touch`, { - method: 'POST', - body: { path: target }, - }); - showToast(`Created ${target}`, 'ok'); - await renderSftpView(root, state); - } catch (err) { - statusMsg.className = 'form-msg err-text'; - statusMsg.textContent = extractErrorMessage(err); - } - }); - - const searchInput = el('input', { - type: 'search', - class: 'input-sm', - value: lastSearchQuery, - placeholder: 'Search files recursively (e.g. *.conf)...', - 'aria-label': 'Search remote files', - }) as HTMLInputElement; - const searchBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Search'); - const clearSearchBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: searchMatches === null }, 'Clear Search'); - - const runSearch = async () => { - const qStr = searchInput.value.trim(); - if (!qStr) return; - lastSearchQuery = qStr; - statusMsg.className = 'form-msg muted'; - statusMsg.textContent = `Searching ${currentPath || '/'} for "${qStr}"...`; - try { - const sRes = await apiFetch<{ basePath: string; matches: string[] }>( - `/api/servers/${encodeURIComponent(currentServerId)}/sftp/search?path=${encodeURIComponent(currentPath || '/')}&q=${encodeURIComponent(qStr)}&max=100`, - ); - searchMatches = sRes.matches; - await renderSftpView(root, state); - } catch (err) { - statusMsg.className = 'form-msg err-text'; - statusMsg.textContent = extractErrorMessage(err); - } - }; - searchBtn.addEventListener('click', () => void runSearch()); - searchInput.addEventListener('keydown', (ev) => { - if (ev.key === 'Enter') { - ev.preventDefault(); - void runSearch(); - } - }); - clearSearchBtn.addEventListener('click', () => { - searchMatches = null; - lastSearchQuery = ''; - void renderSftpView(root, state); - }); - const termHref = `#terminal?server=${encodeURIComponent(currentServerId)}&cwd=${encodeURIComponent(currentPath || '~')}`; const archiveAutoHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=auto`; const archiveGzHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=tar.gz`; @@ -387,46 +292,13 @@ export async function renderSftpView( el('a', { href: archiveAutoHref, class: 'btn btn-sm', download: '' }, 'Archive Folder (.tar.zst/.gz)'), el('a', { href: archiveGzHref, class: 'btn btn-sm', download: '' }, '.tar.gz'), mkdirBtn, - touchBtn, uploadBtn, uploadInput, ), - el('div', { class: 'row', style: 'margin-top:8px' }, searchInput, searchBtn, clearSearchBtn), statusMsg, ); root.append(topPanel); - if (searchMatches !== null) { - const sBox = el('section', { class: 'panel stack' }); - sBox.append(el('strong', {}, `Search Results for "${lastSearchQuery}" (${searchMatches.length})`)); - if (searchMatches.length === 0) { - sBox.append(el('p', { class: 'muted' }, 'No matching files or directories found (max depth 5).')); - } else { - for (const m of searchMatches) { - const openEd = el('button', { type: 'button', class: 'btn btn-sm' }, 'Edit'); - openEd.addEventListener('click', async () => { - try { - const loaded = await apiFetch<{ file: SftpTextPayload }>( - `/api/servers/${encodeURIComponent(currentServerId)}/sftp/text?path=${encodeURIComponent(m)}&sudo=0`, - ); - activeEditSudo = false; - activeEdit = loaded.file; - await renderSftpView(root, state); - } catch (err) { - showToast(extractErrorMessage(err), 'err'); - } - }); - const jumpDir = el('button', { type: 'button', class: 'btn btn-sm' }, 'Open Dir'); - jumpDir.addEventListener('click', () => { - const idx = m.lastIndexOf('/'); - goPath(idx > 0 ? m.slice(0, idx) : '/'); - }); - sBox.append(el('div', { class: 'row-between' }, el('span', { class: 'mono' }, m), el('div', { class: 'row' }, openEd, jumpDir))); - } - } - root.append(sBox); - } - // Inline Editor with Pre-Save Diff if (activeEdit) { const editBox = el('section', { class: 'panel' }); @@ -448,7 +320,8 @@ export async function renderSftpView( } }); - const triggerSaveDiff = () => { + const saveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Review Diff & Save'); + saveBtn.addEventListener('click', () => { if (!activeEdit) return; showSftpDiffDialog(activeEdit.path, activeEdit.content, textarea.value, activeEditSudo, async (force) => { const res = await apiFetch<{ path: string; sha256: string; size: number }>( @@ -467,18 +340,8 @@ export async function renderSftpView( activeEdit = { ...activeEdit!, content: textarea.value, sha256: res.sha256, size: res.size }; statusMsg.className = 'form-msg ok-text'; statusMsg.textContent = `Saved ${res.path} (${res.size} B)`; - showToast(`Saved ${res.path}`, 'ok'); }); - }; - - const saveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Review Diff & Save'); - saveBtn.addEventListener('click', triggerSaveDiff); - - const onCtrlS = () => { - if (textarea.isConnected && !state.safeMode) triggerSaveDiff(); - }; - window.addEventListener('gcoord:save', onCtrlS); - registerViewCleanup(() => window.removeEventListener('gcoord:save', onCtrlS)); + }); const closeEdBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close Editor'); closeEdBtn.addEventListener('click', () => { @@ -516,42 +379,6 @@ export async function renderSftpView( } }); - const selectedPaths = new Set(); - const bulkDelBtn = el( - 'button', - { type: 'button', class: 'btn btn-sm btn-danger mutating-action', disabled: true }, - 'Delete Selected (0)', - ); - const updateBulkBtn = () => { - bulkDelBtn.textContent = `Delete Selected (${selectedPaths.size})`; - bulkDelBtn.disabled = selectedPaths.size === 0; - }; - bulkDelBtn.addEventListener('click', async () => { - if (selectedPaths.size === 0) return; - const ok = await confirmDialog( - 'dialog-confirm', - `Bulk delete ${selectedPaths.size} selected item(s)? Directories will be deleted recursively.`, - ); - if (!ok) return; - try { - const bRes = await apiFetch<{ deleted: string[]; failed: Array<{ path: string; error: string }> }>( - `/api/servers/${encodeURIComponent(currentServerId)}/sftp/bulk-delete`, - { - method: 'POST', - body: { paths: [...selectedPaths], recursive: true }, - }, - ); - showToast( - `Bulk delete: ${bRes.deleted.length} removed${bRes.failed.length ? `, ${bRes.failed.length} failed` : ''}.`, - bRes.failed.length ? 'warn' : 'ok', - ); - await renderSftpView(root, state); - } catch (err) { - statusMsg.className = 'form-msg err-text'; - statusMsg.textContent = extractErrorMessage(err); - } - }); - const tbl = el('table'); tbl.append( el( @@ -560,11 +387,10 @@ export async function renderSftpView( el( 'tr', {}, - el('th', {}, 'Sel'), el('th', {}, 'Name'), el('th', {}, 'Type'), el('th', {}, 'Size'), - el('th', {}, 'Mode / Owner'), + el('th', {}, 'Mode'), el('th', {}, 'Modified'), el('th', {}, 'Actions'), ), @@ -575,30 +401,15 @@ export async function renderSftpView( if (listing.parentPath) { const upBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '.. (Parent Dir)'); upBtn.addEventListener('click', () => goPath(listing!.parentPath!)); - tbody.append(el('tr', {}, el('td', { colspan: 7 }, upBtn))); + tbody.append(el('tr', {}, el('td', { colspan: 6 }, upBtn))); } for (const entry of listing.entries) { - const selChk = el('input', { type: 'checkbox', 'aria-label': `Select ${entry.name}` }) as HTMLInputElement; - selChk.addEventListener('change', () => { - if (selChk.checked) selectedPaths.add(entry.path); - else selectedPaths.delete(entry.path); - updateBulkBtn(); - }); - const nameCell = el('td', {}); if (entry.type === 'dir') { const openBtn = el('button', { type: 'button', class: 'btn btn-sm' }, `[DIR] ${entry.name}/`); openBtn.addEventListener('click', () => goPath(entry.path)); nameCell.append(openBtn); - } else if (entry.type === 'symlink') { - nameCell.append( - el('span', { class: 'badge' }, 'LNK'), - el('span', { class: 'mono', style: 'margin-left:6px' }, entry.name), - entry.symlinkTarget - ? el('div', { class: 'mono muted' }, `-> ${entry.symlinkTarget}`) - : '', - ); } else { nameCell.append(el('span', { class: 'mono' }, entry.name)); } @@ -655,32 +466,6 @@ export async function renderSftpView( await renderSftpView(root, state); }); - const chownBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Chown'); - chownBtn.addEventListener('click', async () => { - const curOwner = `${entry.uid ?? 0}:${entry.gid ?? 0}`; - const rawOwner = window.prompt('Owner UID:GID (numeric, e.g. 1000:1000):', curOwner); - if (!rawOwner) return; - const parts = rawOwner.trim().split(':'); - const uid = Number(parts[0]); - const gid = Number(parts[1] ?? parts[0]); - if (!Number.isInteger(uid) || uid < 0 || !Number.isInteger(gid) || gid < 0) { - showToast('Invalid UID:GID numbers.', 'err'); - return; - } - const useSudo = window.confirm('Use sudo chown (requires step-up)? Cancel = normal chown.'); - try { - await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/chown`, { - method: 'POST', - body: { path: entry.path, uid, gid, sudo: useSudo }, - }); - showToast(`Changed owner of ${entry.name} to ${uid}:${gid}`, 'ok'); - await renderSftpView(root, state); - } catch (err) { - statusMsg.className = 'form-msg err-text'; - statusMsg.textContent = extractErrorMessage(err); - } - }); - const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete'); delBtn.addEventListener('click', async () => { const ok = await confirmDialog( @@ -697,20 +482,16 @@ export async function renderSftpView( await renderSftpView(root, state); }); - actionsRow.append(renBtn, chmodBtn, chownBtn, delBtn); - - const ownerText = - entry.uid !== undefined && entry.gid !== undefined ? ` (${entry.uid}:${entry.gid})` : ''; + actionsRow.append(renBtn, chmodBtn, delBtn); tbody.append( el( 'tr', {}, - el('td', {}, selChk), nameCell, el('td', { class: 'mono' }, entry.type), el('td', { class: 'mono' }, entry.type === 'dir' ? '—' : fmtFileSize(entry.size)), - el('td', { class: 'mono' }, `${entry.permissionsOctal}${ownerText}`), + el('td', { class: 'mono' }, entry.permissionsOctal), el('td', { class: 'mono' }, fmtTime(entry.mtimeMs)), el('td', {}, actionsRow), ), @@ -719,7 +500,7 @@ export async function renderSftpView( tbl.append(tbody); dropPanel.append( - el('div', { class: 'row-between', style: 'margin-bottom:6px' }, el('span', { class: 'muted' }, 'Tip: Drag files anywhere onto this table to stream upload via SFTP.'), bulkDelBtn), + el('div', { class: 'muted', style: 'margin-bottom:6px' }, 'Tip: Drag files anywhere onto this table to stream upload via SFTP.'), el('div', { class: 'table-wrap' }, tbl), ); root.append(dropPanel); diff --git a/src/client/ts/views/systems-view.ts b/src/client/ts/views/systems-view.ts index 752682b..a24300b 100644 --- a/src/client/ts/views/systems-view.ts +++ b/src/client/ts/views/systems-view.ts @@ -7,23 +7,11 @@ import { extractErrorMessage, fmtTime, isAiEnabled, - registerViewCleanup, type ClientState, type ServerEntry, } from '../state.js'; -import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; -interface SystemActionInputDef { - name: string; - type: 'string' | 'number' | 'boolean' | 'server' | 'select' | 'secret'; - label?: string; - description?: string; - required?: boolean; - default?: unknown; - options?: string[]; -} - interface SystemActionDef { id: string; label: string; @@ -31,7 +19,6 @@ interface SystemActionDef { mode: 'oneshot' | 'stream' | 'interactive'; sudo: boolean; confirm: boolean; - inputs?: SystemActionInputDef[]; } interface SystemParamDef { @@ -78,88 +65,6 @@ interface ServerSnapshotView { } let unsubStreamListener: (() => void) | null = null; -let unsubStreamChannel: (() => void) | null = null; - -function releaseSystemStream(): void { - if (unsubStreamChannel) { - unsubStreamChannel(); - unsubStreamChannel = null; - } - if (unsubStreamListener) { - unsubStreamListener(); - unsubStreamListener = null; - } -} - -async function promptActionInputs( - actionLabel: string, - defs: SystemActionInputDef[], -): Promise | null> { - if (!defs || defs.length === 0) return {}; - return new Promise((resolve) => { - const dialog = document.createElement('dialog'); - dialog.className = 'dialog-wide'; - const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Cancel'); - const ctrls = new Map(); - const fieldsBox = el('div', { class: 'stack' }); - for (const def of defs) { - let node: HTMLInputElement | HTMLSelectElement; - if (def.type === 'select' && def.options) { - const sel = el('select', { required: def.required !== false }); - for (const opt of def.options) { - sel.append(el('option', { value: opt, selected: def.default === opt }, opt)); - } - node = sel; - } else if (def.type === 'boolean') { - node = el('input', { type: 'checkbox', checked: Boolean(def.default) }) as HTMLInputElement; - } else { - node = el('input', { - type: def.type === 'secret' ? 'password' : def.type === 'number' ? 'number' : 'text', - value: def.default !== undefined ? String(def.default) : '', - required: def.required !== false, - placeholder: def.description ?? def.name, - }) as HTMLInputElement; - } - ctrls.set(def.name, { def, node }); - fieldsBox.append(el('label', {}, `${def.label ?? def.name} (${def.type})`), node); - } - - const form = el( - 'form', - { class: 'stack' }, - fieldsBox, - el('div', { class: 'dialog-actions' }, closeBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Run')), - ); - - let settled = false; - const finish = (val: Record | null) => { - if (settled) return; - settled = true; - if (dialog.open) dialog.close(); - dialog.remove(); - resolve(val); - }; - closeBtn.addEventListener('click', () => finish(null)); - dialog.addEventListener('close', () => finish(null)); - form.addEventListener('submit', (ev) => { - ev.preventDefault(); - const out: Record = {}; - for (const [k, { def, node }] of ctrls.entries()) { - out[k] = - def.type === 'boolean' - ? (node as HTMLInputElement).checked - : def.type === 'number' - ? Number(node.value) - : node.value; - } - finish(out); - }); - - dialog.append(el('h1', {}, `Action Inputs: ${actionLabel}`), form); - document.body.append(dialog); - dialog.showModal(); - }); -} function healthBadgeClass(h: string): string { if (h === 'ok') return 'badge badge-ok'; @@ -270,12 +175,6 @@ async function runSystemAction(opts: { onFinished: () => Promise; }): Promise { const { action } = opts; - let actionInputs: Record | undefined; - if (action.inputs && action.inputs.length > 0) { - const prompted = await promptActionInputs(action.label, action.inputs); - if (!prompted) return; - actionInputs = prompted; - } if (action.confirm) { const target = opts.subItemName ?? opts.itemName ?? opts.serverId; const ok = await confirmDialog( @@ -287,28 +186,20 @@ async function runSystemAction(opts: { opts.outputHost.replaceChildren(el('p', { class: 'muted mono' }, `Running ${action.label}...`)); - let res: + const res = await apiFetch< | { mode: 'oneshot'; exitCode: number | null; stdout: string; stderr: string; durationMs: number } | { mode: 'stream'; jobId: string } - | { mode: 'interactive'; session: { sessionId: string } }; - try { - res = await apiFetch( - `/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`, - { - method: 'POST', - body: { - itemName: opts.itemName, - subItemName: opts.subItemName, - ...(actionInputs ? { inputs: actionInputs } : {}), - }, + | { mode: 'interactive'; session: { sessionId: string } } + >( + `/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`, + { + method: 'POST', + body: { + itemName: opts.itemName, + subItemName: opts.subItemName, }, - ); - } catch (err) { - const msg = extractErrorMessage(err); - opts.outputHost.replaceChildren(el('p', { class: 'err-text mono' }, msg)); - showToast(msg, 'err'); - return; - } + }, + ); if (res.mode === 'interactive') { window.location.hash = `#terminal?session=${encodeURIComponent(res.session.sessionId)}`; @@ -351,14 +242,16 @@ async function runSystemAction(opts: { } // Stream mode - releaseSystemStream(); + if (unsubStreamListener) { + unsubStreamListener(); + unsubStreamListener = null; + } const logPre = el('pre', { class: 'stream-log mono' }); - const stopBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel Stream'); + const stopBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Stop Stream'); stopBtn.addEventListener('click', async () => { await apiFetch(`/api/systems/streams/${encodeURIComponent(res.jobId)}/cancel`, { method: 'POST' }); stopBtn.disabled = true; - showToast(`Stream ${res.jobId} cancelled.`, 'warn'); }); const streamAiBtn = isAiEnabled(opts.state) ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Debug Output]') @@ -410,7 +303,7 @@ async function runSystemAction(opts: { logPre.scrollTop = logPre.scrollHeight; }); - unsubStreamChannel = opts.wsClient.subscribe([`stream:${res.jobId}`]); + opts.wsClient.subscribe([`stream:${res.jobId}`]); } export async function renderSystemsView( @@ -418,8 +311,10 @@ export async function renderSystemsView( state: ClientState, wsClient: MultiplexWsClient, ): Promise { - releaseSystemStream(); - registerViewCleanup(releaseSystemStream); + if (unsubStreamListener) { + unsubStreamListener(); + unsubStreamListener = null; + } root.replaceChildren(); const segs = state.routeSegments ?? []; const forceRefresh = state.routeQuery?.refresh === '1'; @@ -672,16 +567,14 @@ export async function renderSystemsView( // Quick Editable Files via SFTP inline diff editor if (item.editableFiles.length > 0) { - const needsSudo = system.actions.some((a) => a.sudo); const editRow = el('div', { class: 'chip-list' }); for (const fPath of item.editableFiles) { editRow.append( el( 'a', { - href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}${needsSudo ? '&sudo=1' : ''}`, + href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}`, class: 'btn btn-sm', - title: fPath, }, `Edit ${fPath.split('/').pop()}`, ), diff --git a/src/client/ts/views/terminal-view.ts b/src/client/ts/views/terminal-view.ts index d5486b0..3bf01db 100644 --- a/src/client/ts/views/terminal-view.ts +++ b/src/client/ts/views/terminal-view.ts @@ -3,16 +3,7 @@ import type { FitAddon } from '@xterm/addon-fit'; import type { ServerWsFrame } from '../../../shared/ws-protocol.js'; import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; -import { - el, - extractErrorMessage, - fmtTime, - isAiEnabled, - registerViewCleanup, - type ClientState, - type ServerEntry, -} from '../state.js'; -import { showToast } from '../toast.js'; +import { el, extractErrorMessage, fmtTime, isAiEnabled, type ClientState, type ServerEntry } from '../state.js'; import type { MultiplexWsClient } from '../ws-client.js'; import { clearTerminalComposition, @@ -184,7 +175,6 @@ export async function renderTerminalView( root.replaceChildren(); const q = state.routeQuery ?? {}; - const targetServer = q.server ?? q.serverId; const [sessionsRes, serversRes] = await Promise.all([ apiFetch<{ sessions: PtySessionInfo[] }>('/api/terminal/sessions'), apiFetch<{ servers: ServerEntry[] }>('/api/servers'), @@ -195,13 +185,13 @@ export async function renderTerminalView( if (q.session && sessions.some((s) => s.sessionId === q.session)) { activeSessionId = q.session; - } else if (targetServer && q.cwd !== undefined && servers.some((s) => s.config.id === targetServer)) { + } else if (q.server && q.cwd !== undefined && servers.some((s) => s.config.id === q.server)) { // Open-Terminal-Here shortcut if not disabled by Safe Mode if (!state.safeMode) { try { const created = await apiFetch<{ session: PtySessionInfo }>('/api/terminal/sessions', { method: 'POST', - body: { serverId: targetServer, cwd: q.cwd, cols: 90, rows: 26 }, + body: { serverId: q.server, cwd: q.cwd, cols: 90, rows: 26 }, }); sessions = [created.session, ...sessions]; activeSessionId = created.session.sessionId; @@ -223,7 +213,7 @@ export async function renderTerminalView( serverSel.append( el( 'option', - { value: s.config.id, selected: targetServer === s.config.id }, + { value: s.config.id, selected: q.server === s.config.id }, `${s.config.name} (${s.config.id})`, ), ); @@ -292,15 +282,6 @@ export async function renderTerminalView( el('div', { class: 'row' }, serverSel, cwdInput, openShellBtn), ), tabsRow, - ...(state.safeMode - ? [ - el( - 'p', - { class: 'warn-text mono' }, - '[SAFE MODE] Read-only terminal view: keyboard input, reconnect, and session creation are locked.', - ), - ] - : []), msgEl, ), ); @@ -337,40 +318,6 @@ export async function renderTerminalView( }, 'Export ANSI', ); - const exportCastBtn = el( - 'a', - { - href: `/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/export?format=cast`, - class: 'btn btn-sm', - download: '', - }, - 'Export .cast', - ); - const reconnectPtyBtn = el( - 'button', - { - type: 'button', - class: 'btn btn-sm btn-primary mutating-action', - hidden: !current.exited, - }, - 'Reconnect Session', - ); - reconnectPtyBtn.addEventListener('click', async () => { - reconnectPtyBtn.disabled = true; - try { - await apiFetch(`/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/reconnect`, { - method: 'POST', - body: {}, - }); - showToast('PTY session reconnected.', 'ok'); - await renderTerminalView(root, state, wsClient); - } catch (err) { - msgEl.className = 'form-msg err-text'; - msgEl.textContent = extractErrorMessage(err); - showToast(extractErrorMessage(err), 'err'); - reconnectPtyBtn.disabled = false; - } - }); let term: Terminal | null = null; let fitAddon: FitAddon | null = null; @@ -543,7 +490,7 @@ export async function renderTerminalView( { class: 'mono muted' }, `${current.title} | ${current.cols}x${current.rows} | opened ${fmtTime(current.createdAt)}`, ), - el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, ...(aiTermBtn ? [aiTermBtn] : []), reconnectPtyBtn, exportPlainBtn, exportAnsiBtn, exportCastBtn, closeTabBtn), + el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, ...(aiTermBtn ? [aiTermBtn] : []), exportPlainBtn, exportAnsiBtn, closeTabBtn), ), el('div', { class: 'term-shell' }, termContainer, touchBar), ), @@ -683,14 +630,6 @@ export async function renderTerminalView( typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => scheduleFit()) : null; ro?.observe(termContainer); - const themeObs = - typeof MutationObserver !== 'undefined' - ? new MutationObserver(() => { - if (term) term.options.theme = readXtermTheme(); - }) - : null; - themeObs?.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); - const unsubFrame = wsClient.onFrame((frame: ServerWsFrame) => { if (!term || !termContainer.isConnected) return; if (frame.type === 'pty:output' && frame.sessionId === current.sessionId) { @@ -699,8 +638,6 @@ export async function renderTerminalView( } term.write(frame.data); } else if (frame.type === 'pty:exit' && frame.sessionId === current.sessionId) { - current.exited = true; - reconnectPtyBtn.hidden = false; term.writeln(`\r\n[Session exited with code ${String(frame.exitCode)}]`); } else if (frame.type === 'error' && frame.code === 'SAFE_MODE_ACTIVE') { msgEl.className = 'form-msg warn-text'; @@ -708,17 +645,9 @@ export async function renderTerminalView( } }); - const unsubChannel = wsClient.subscribe([`pty:${current.sessionId}`]); - - let cleaned = false; - const disposeTerminalView = () => { - if (cleaned) return; - cleaned = true; - currentCleanup = null; + currentCleanup = () => { if (fitRaf !== null) window.cancelAnimationFrame(fitRaf); - unsubChannel(); unsubFrame(); - themeObs?.disconnect(); ro?.disconnect(); window.removeEventListener('resize', scheduleFit); window.visualViewport?.removeEventListener('resize', scheduleFit); @@ -728,9 +657,7 @@ export async function renderTerminalView( term?.dispose(); }; - currentCleanup = disposeTerminalView; - registerViewCleanup(disposeTerminalView); - + wsClient.subscribe([`pty:${current.sessionId}`]); wsClient.send({ type: 'pty:resize', sessionId: current.sessionId, diff --git a/src/client/ts/views/tunnels-panel.ts b/src/client/ts/views/tunnels-panel.ts index 4c4a40a..c748242 100644 --- a/src/client/ts/views/tunnels-panel.ts +++ b/src/client/ts/views/tunnels-panel.ts @@ -1,13 +1,6 @@ import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; -import { - el, - extractErrorMessage, - fmtTime, - registerViewCleanup, - type ServerEntry, -} from '../state.js'; -import { showToast } from '../toast.js'; +import { el, extractErrorMessage, fmtTime, type ServerEntry } from '../state.js'; export interface TunnelViewEntry { key: string; @@ -15,15 +8,11 @@ export interface TunnelViewEntry { tunnel: { id: string; name: string; - mode: 'http-proxy' | 'local-tcp' | 'remote-tcp' | 'socks5'; + mode: 'http-proxy' | 'local-tcp' | 'remote-tcp'; bindHost?: string; bindPort?: number; targetHost: string; targetPort: number; - targetProtocol?: 'http' | 'https'; - tlsRejectUnauthorized?: boolean; - tlsServerName?: string; - ttlSec?: number; autoStart: boolean; }; active: boolean; @@ -31,7 +20,6 @@ export interface TunnelViewEntry { localBoundPort?: number; remoteBoundPort?: number; proxyPath?: string; - expiresAt?: number; activeConnections: number; totalConnections: number; bytesIn: number; @@ -40,13 +28,6 @@ export interface TunnelViewEntry { lastError?: string; } -function fmtRemainingSec(sec: number): string { - const s = Math.max(0, Math.floor(sec)); - const m = Math.floor(s / 60); - const rem = s % 60; - return m > 0 ? `${m}m ${rem}s` : `${rem}s`; -} - function fmtBytes(bytes: number): string { if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'; if (bytes < 1024) return `${bytes} B`; @@ -109,71 +90,24 @@ export async function renderTunnelsPanel( ), ); const tbody = el('tbody'); - const countdownEls: Array<{ el: HTMLElement; expiresAt: number }> = []; for (const item of tunnels) { - let bindInfo: HTMLElement; - if (item.tunnel.mode === 'http-proxy' && item.active) { - const launchBtn = el( - 'button', - { type: 'button', class: 'btn btn-sm btn-primary' }, - 'Open Isolated Proxy', - ); - launchBtn.addEventListener('click', async () => { - launchBtn.disabled = true; - try { - const ticketRes = await apiFetch<{ - launchUrl: string; - mode: 'subdomain' | 'port' | 'same-origin'; - expiresInSec: number; - }>( - `/api/tunnels/${encodeURIComponent(item.serverId)}/${encodeURIComponent(item.tunnel.id)}/proxy-ticket`, - { method: 'POST', body: {} }, + const bindInfo = item.proxyPath + ? el('a', { href: item.proxyPath, target: '_blank', rel: 'noopener', class: 'mono' }, item.proxyPath) + : item.tunnel.mode === 'remote-tcp' + ? el( + 'span', + { class: 'mono' }, + item.active && item.remoteBoundPort + ? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}` + : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, + ) + : el( + 'span', + { class: 'mono' }, + item.active && item.localBoundPort + ? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}` + : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, ); - if (ticketRes.mode === 'same-origin') { - showToast( - 'Launched via same-origin fallback proxy (isolated subdomain/port offers stronger cookie isolation).', - 'warn', - ); - } - window.open(ticketRes.launchUrl, '_blank', 'noopener,noreferrer'); - } catch (err) { - const msg = extractErrorMessage(err); - statusMsg.className = 'form-msg err-text'; - statusMsg.textContent = msg; - showToast(msg, 'err'); - } finally { - launchBtn.disabled = false; - } - }); - bindInfo = el( - 'div', - { class: 'stack' }, - launchBtn, - el( - 'span', - { class: 'mono muted' }, - `${item.tunnel.targetProtocol ?? 'http'}:// via ticket`, - ), - ); - } else if (item.tunnel.mode === 'http-proxy') { - bindInfo = el('span', { class: 'muted mono' }, 'proxy (inactive)'); - } else if (item.tunnel.mode === 'remote-tcp') { - bindInfo = el( - 'span', - { class: 'mono' }, - item.active && item.remoteBoundPort - ? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}` - : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, - ); - } else { - bindInfo = el( - 'span', - { class: 'mono' }, - item.active && item.localBoundPort - ? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}` - : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, - ); - } const toggleBtn = el( 'button', @@ -220,15 +154,6 @@ export async function renderTunnelsPanel( } }); - let ttlBadge: HTMLElement | string = ''; - if (item.active && item.expiresAt) { - const b = el('div', { class: 'badge badge-warn' }, `TTL: ${fmtRemainingSec((item.expiresAt - Date.now()) / 1000)}`); - countdownEls.push({ el: b, expiresAt: item.expiresAt }); - ttlBadge = b; - } else if (item.tunnel.ttlSec) { - ttlBadge = el('div', { class: 'muted' }, `TTL: ${item.tunnel.ttlSec}s`); - } - tbody.append( el( 'tr', @@ -244,16 +169,9 @@ export async function renderTunnelsPanel( {}, el('span', { class: `badge ${item.active ? 'badge-ok' : ''}` }, item.tunnel.mode.toUpperCase()), item.tunnel.autoStart ? el('div', { class: 'muted' }, 'auto-start') : '', - ttlBadge, ), el('td', {}, bindInfo), - el( - 'td', - { class: 'mono' }, - item.tunnel.mode === 'socks5' - ? 'Dynamic SOCKS5' - : `${item.tunnel.targetProtocol ? `${item.tunnel.targetProtocol}://` : ''}${item.tunnel.targetHost}:${item.tunnel.targetPort}`, - ), + el('td', { class: 'mono' }, `${item.tunnel.targetHost}:${item.tunnel.targetPort}`), el( 'td', { class: 'mono' }, @@ -267,17 +185,6 @@ export async function renderTunnelsPanel( } tbl.append(tbody); listPanel.append(el('div', { class: 'table-wrap' }, tbl)); - - if (countdownEls.length > 0) { - const ttlTimer = window.setInterval(() => { - const now = Date.now(); - for (const row of countdownEls) { - const remSec = Math.max(0, Math.floor((row.expiresAt - now) / 1000)); - row.el.textContent = `TTL: ${fmtRemainingSec(remSec)}`; - } - }, 1000); - registerViewCleanup(() => window.clearInterval(ttlTimer)); - } } // Add Tunnel Form @@ -287,7 +194,7 @@ export async function renderTunnelsPanel( el( 'p', { class: 'muted' }, - 'http-proxy serves via short-lived proxy tickets in isolated origin mode (subdomain/port) or same-origin fallback when enabled. socks5 provides dynamic local forwarding without targetPort.', + 'http-proxy binds strictly inside 127.0.0.1 and serves behind GCoordinator auth/CSRF/Safe-Mode at /proxy//.', ), ); @@ -306,67 +213,31 @@ export async function renderTunnelsPanel( const modeSel = el( 'select', { name: 'mode' }, - el('option', { value: 'http-proxy' }, 'http-proxy (Authenticated Web Proxy)'), + el('option', { value: 'http-proxy' }, 'http-proxy (Zero-Port Web Proxy /proxy//)'), el('option', { value: 'local-tcp' }, 'local-tcp (Local Bind -> Target)'), el('option', { value: 'remote-tcp' }, 'remote-tcp (Remote Bind -R -> Hub/LAN)'), - el('option', { value: 'socks5' }, 'socks5 (Dynamic Local SOCKS5 Proxy)'), - ) as HTMLSelectElement; - const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true }) as HTMLInputElement; + ); + const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true }); const targetPortInput = el('input', { name: 'targetPort', type: 'number', - min: 0, + min: 1, max: 65535, value: '3000', required: true, - }) as HTMLInputElement; - const protoSel = el( - 'select', - { name: 'targetProtocol' }, - el('option', { value: 'http' }, 'http'), - el('option', { value: 'https' }, 'https'), - ) as HTMLSelectElement; - const tlsVerifyChk = el('input', { type: 'checkbox', name: 'tlsRejectUnauthorized', checked: true }) as HTMLInputElement; - const tlsSniInput = el('input', { name: 'tlsServerName', placeholder: 'optional TLS SNI host' }) as HTMLInputElement; - const ttlSecInput = el('input', { - name: 'ttlSec', - type: 'number', - min: 60, - max: 86400, - placeholder: 'optional auto-expire (60-86400s)', - }) as HTMLInputElement; - const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp/socks5)' }) as HTMLInputElement; + }); + const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp modes)' }); const bindPortInput = el('input', { name: 'bindPort', type: 'number', min: 1, max: 65535, - placeholder: 'auto (tcp/socks5)', - }) as HTMLInputElement; - const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' }) as HTMLInputElement; - const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true }) as HTMLInputElement; + placeholder: 'auto (tcp modes)', + }); + const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' }); + const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true }); const formMsg = el('p', { class: 'form-msg' }); - const targetPortWrap = el('div', {}, el('label', {}, 'Target Port'), targetPortInput); - const httpTlsWrap = el( - 'div', - { class: 'grid-3' }, - el('div', {}, el('label', {}, 'Upstream Protocol'), protoSel), - el('div', {}, el('label', {}, 'TLS SNI ServerName (HTTPS)'), tlsSniInput), - el('div', { style: 'padding-top:22px' }, el('label', { class: 'chk-row' }, tlsVerifyChk, 'Verify upstream TLS cert')), - ); - - const syncModeFields = () => { - const m = modeSel.value; - targetPortWrap.hidden = m === 'socks5'; - targetPortInput.required = m !== 'socks5'; - if (m === 'socks5') targetPortInput.value = '0'; - else if (targetPortInput.value === '0') targetPortInput.value = '3000'; - httpTlsWrap.hidden = m !== 'http-proxy'; - }; - modeSel.addEventListener('change', syncModeFields); - syncModeFields(); - form.append( el( 'div', @@ -376,12 +247,10 @@ export async function renderTunnelsPanel( el('div', {}, el('label', {}, 'Display Name'), nameInput), el('div', {}, el('label', {}, 'Mode'), modeSel), el('div', {}, el('label', {}, 'Target Host'), targetHostInput), - targetPortWrap, - el('div', {}, el('label', {}, 'Bind Host (TCP/SOCKS5)'), bindHostInput), - el('div', {}, el('label', {}, 'Bind Port (TCP/SOCKS5)'), bindPortInput), - el('div', {}, el('label', {}, 'TTL Seconds (Optional)'), ttlSecInput), + el('div', {}, el('label', {}, 'Target Port'), targetPortInput), + el('div', {}, el('label', {}, 'Bind Host (TCP only)'), bindHostInput), + el('div', {}, el('label', {}, 'Bind Port (TCP only)'), bindPortInput), ), - httpTlsWrap, el( 'div', { class: 'row' }, @@ -402,12 +271,10 @@ export async function renderTunnelsPanel( return; } - const mode = modeSel.value as 'http-proxy' | 'local-tcp' | 'remote-tcp' | 'socks5'; + const mode = modeSel.value as 'http-proxy' | 'local-tcp' | 'remote-tcp'; const bindHost = bindHostInput.value.trim() || undefined; const bindPortVal = bindPortInput.value.trim(); const bindPort = bindPortVal ? Number(bindPortVal) : undefined; - const ttlVal = ttlSecInput.value.trim(); - const ttlSec = ttlVal ? Number(ttlVal) : undefined; try { const res = await apiFetch<{ startError?: string }>('/api/tunnels', { @@ -419,13 +286,7 @@ export async function renderTunnelsPanel( name: nameInput.value.trim(), mode, targetHost: targetHostInput.value.trim() || '127.0.0.1', - targetPort: mode === 'socks5' ? 0 : Number(targetPortInput.value), - targetProtocol: mode === 'http-proxy' ? protoSel.value : 'http', - tlsRejectUnauthorized: mode === 'http-proxy' ? tlsVerifyChk.checked : true, - ...(mode === 'http-proxy' && tlsSniInput.value.trim() - ? { tlsServerName: tlsSniInput.value.trim() } - : {}), - ...(ttlSec !== undefined ? { ttlSec } : {}), + targetPort: Number(targetPortInput.value), bindHost: mode === 'http-proxy' ? undefined : bindHost, bindPort: mode === 'http-proxy' ? undefined : bindPort, autoStart: autoStartChk.checked, @@ -436,8 +297,6 @@ export async function renderTunnelsPanel( if (res.startError) { statusMsg.className = 'form-msg warn-text'; statusMsg.textContent = `Saved, but start failed: ${res.startError}`; - } else { - showToast('Tunnel saved.', 'ok'); } await renderTunnelsPanel(root, fixedServerId); } catch (err) { diff --git a/src/client/ts/views/vault-view.ts b/src/client/ts/views/vault-view.ts index 02359ed..1789733 100644 --- a/src/client/ts/views/vault-view.ts +++ b/src/client/ts/views/vault-view.ts @@ -1,7 +1,6 @@ import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; -import { showToast } from '../toast.js'; interface VaultCredMeta { id: string; @@ -124,44 +123,19 @@ export async function renderVaultView( onPanicLock: () => Promise, ): Promise { root.replaceChildren(); - const [vaultData, statusRes] = await Promise.all([ - apiFetch<{ - state: 'uninitialized' | 'locked' | 'unlocked'; - runtimeReady?: boolean; - sealState?: string; - isPanicLocked?: boolean; - credentials: VaultCredMeta[]; - }>('/api/vault/credentials'), - apiFetch<{ - state: 'uninitialized' | 'locked' | 'unlocked'; - runtimeReady: boolean; - sealState: string; - isPanicLocked: boolean; - }>('/api/vault/status').catch(() => null), - ]); - const runtimeReady = Boolean(statusRes?.runtimeReady ?? vaultData.runtimeReady ?? vaultData.state === 'unlocked'); - const sealState = statusRes?.sealState ?? vaultData.sealState ?? (runtimeReady ? 'unsealed' : 'sealed'); - state.vaultState = statusRes?.state ?? vaultData.state; + const vaultData = await apiFetch<{ + state: 'uninitialized' | 'locked' | 'unlocked'; + runtimeReady?: boolean; + isPanicLocked?: boolean; + credentials: VaultCredMeta[]; + }>('/api/vault/credentials'); + const runtimeReady = Boolean(vaultData.runtimeReady ?? vaultData.state === 'unlocked'); + state.vaultState = vaultData.state; state.vaultRuntimeReady = runtimeReady; - if (statusRes?.isPanicLocked !== undefined || vaultData.isPanicLocked !== undefined) { - state.isPanicLocked = Boolean(statusRes?.isPanicLocked ?? vaultData.isPanicLocked); + if (vaultData.isPanicLocked !== undefined) { + state.isPanicLocked = vaultData.isPanicLocked; } - const doSealVault = async () => { - const ok = await confirmDialog( - 'dialog-confirm', - 'Seal the Vault now? This wipes the in-memory master key (collectors/SSH will pause until unsealed with the 32-byte key), without revoking your admin login session.', - ); - if (!ok) return; - try { - await apiFetch('/api/vault/seal', { method: 'POST', body: {} }); - showToast('Vault sealed and runtime master key cleared from memory.', 'warn'); - await onStateChanged(); - } catch (err) { - showToast(extractErrorMessage(err), 'err'); - } - }; - const statusPanel = el('section', { class: 'panel' }); if (vaultData.state === 'uninitialized') { @@ -309,23 +283,13 @@ export async function renderVaultView( }); statusPanel.append( - el('h1', {}, `Encrypted Vault — [${vaultData.state.toUpperCase()} / ${sealState.toUpperCase()}]`), + el('h1', {}, 'Encrypted Vault — [LOCKED]'), el( 'p', { class: 'muted' }, - 'Established secrets remain active in memory while unsealed (chmod 0600 data/vault.key or GCOORD_MASTER_KEY env). Unlock to edit, or Seal to zeroize keys from RAM without dropping sessions.', - ), - el( - 'div', - { class: 'row' }, - unlockBtn, - (() => { - const sealBtn = el('button', { type: 'button', class: 'btn mutating-action' }, 'Seal Vault'); - sealBtn.addEventListener('click', () => void doSealVault()); - return sealBtn; - })(), - panicBtn, + 'Established secrets remain active in the background for stat collectors, SSH, SFTP, Terminal, Systems, and Tunnels. Unlock the Vault to add, update, delete, rotate, or reveal secrets.', ), + el('div', { class: 'row' }, unlockBtn, panicBtn), lockMsg, credTableWrap, revealBox, @@ -344,15 +308,9 @@ export async function renderVaultView( await apiFetch('/api/vault/lock', { method: 'POST' }); await onStateChanged(); }); - const sealUnlockedBtn = el( - 'button', - { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, - 'Seal Vault', - ); - sealUnlockedBtn.addEventListener('click', () => void doSealVault()); statusPanel.append( - el('div', { class: 'row-between' }, el('h1', {}, `Encrypted Vault — [UNLOCKED / ${sealState.toUpperCase()}]`), el('div', { class: 'row' }, lockBtn, sealUnlockedBtn)), + el('div', { class: 'row-between' }, el('h1', {}, 'Encrypted Vault — [UNLOCKED]'), lockBtn), credTableWrap, revealBox, ); diff --git a/src/client/ts/views/workflows-view.ts b/src/client/ts/views/workflows-view.ts index 4d0bb20..83a4b30 100644 --- a/src/client/ts/views/workflows-view.ts +++ b/src/client/ts/views/workflows-view.ts @@ -7,18 +7,16 @@ import { extractErrorMessage, fmtTime, isAiEnabled, - registerViewCleanup, type ClientState, type ServerEntry, } from '../state.js'; -import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; type WfSubTab = 'workflows' | 'broadcast' | 'snippets'; interface WorkflowInputDef { name: string; - type: 'string' | 'number' | 'boolean' | 'server' | 'select' | 'secret'; + type: 'string' | 'number' | 'boolean' | 'server' | 'select'; label?: string; description?: string; required?: boolean; @@ -28,7 +26,7 @@ interface WorkflowInputDef { interface WorkflowStepDef { id: string; - type: 'exec' | 'read-file' | 'system-action' | 'transfer' | 'http' | 'notify'; + type: 'exec' | 'read-file' | 'system-action' | 'transfer'; dependsOn?: Array; target?: { serverId?: string; tags?: string[]; all?: boolean }; command?: string; @@ -41,19 +39,7 @@ interface WorkflowStepDef { mode?: 'hub-relayed' | 'direct'; source?: { serverId: string; path: string }; destination?: { serverId: string; path: string }; - url?: string; - method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; - body?: string; - secretRef?: string; - expectedStatus?: number; - channelIds?: string[]; - title?: string; - message?: string; - severity?: 'warn' | 'critical'; timeoutSec?: number; - retries?: number; - retryBackoffSec?: number; - when?: string; sudo?: boolean; captureAs?: string; onFailure?: string | { action: string; channelId?: string; workflowId?: string }; @@ -122,18 +108,6 @@ let activeSubTab: WfSubTab = 'workflows'; let selectedRunDetailId: string | null = null; let broadcastPresetSnippetId: string | null = null; let unsubWfWs: (() => void) | null = null; -let unsubWfChannel: (() => void) | null = null; - -function releaseWfWs(): void { - if (unsubWfChannel) { - unsubWfChannel(); - unsubWfChannel = null; - } - if (unsubWfWs) { - unsubWfWs(); - unsubWfWs = null; - } -} function statusBadgeClass(status: string): string { if (status === 'succeeded' || status === 'ok') return 'badge badge-ok'; @@ -277,10 +251,10 @@ async function promptWorkflowInputs( ctrl = el('input', { type: 'checkbox', checked: Boolean(def.default) }); } else { ctrl = el('input', { - type: def.type === 'secret' ? 'password' : def.type === 'number' ? 'number' : 'text', - value: def.type === 'secret' ? '' : def.default !== undefined ? String(def.default) : '', + type: def.type === 'number' ? 'number' : 'text', + value: def.default !== undefined ? String(def.default) : '', required: def.required, - placeholder: def.type === 'secret' ? '(secret input — masked in logs)' : (def.description ?? def.name), + placeholder: def.description ?? def.name, }); } fields.set(def.name, ctrl); @@ -445,7 +419,7 @@ function openWorkflowEditorDialog( const sType = el( 'select', { class: 'input-sm' }, - ...(['exec', 'read-file', 'system-action', 'transfer', 'http', 'notify'] as const).map((t) => + ...(['exec', 'read-file', 'system-action', 'transfer'] as const).map((t) => el('option', { value: t, selected: step.type === t }, t), ), ); @@ -455,14 +429,6 @@ function openWorkflowEditorDialog( step.mode = 'hub-relayed'; step.source = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file' }; step.destination = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file.bak' }; - } else if (step.type === 'http' && !step.url) { - step.method = 'POST'; - step.url = 'https://example.invalid/webhook'; - } else if (step.type === 'notify' && !step.channelIds) { - step.channelIds = ['ops-webhook']; - step.title = 'Workflow Notification'; - step.message = 'Step reached'; - step.severity = 'warn'; } redrawSteps(); }); @@ -496,26 +462,6 @@ function openWorkflowEditorDialog( redrawSteps(); }); - const sRetries = el('input', { - class: 'input-sm', - type: 'number', - min: 0, - max: 5, - value: String(step.retries ?? 0), - placeholder: 'retries (0-5)', - }) as HTMLInputElement; - sRetries.addEventListener('input', () => { - step.retries = Number(sRetries.value || 0); - }); - const sWhen = el('input', { - class: 'input-sm', - value: step.when ?? '', - placeholder: 'when expr (e.g. inputs.env == "prod")', - }) as HTMLInputElement; - sWhen.addEventListener('input', () => { - step.when = sWhen.value.trim() || undefined; - }); - card.append( el( 'div', @@ -523,57 +469,10 @@ function openWorkflowEditorDialog( el('strong', {}, `Step #${idx + 1}`), el('div', { class: 'row' }, sId, sType, rmBtn), ), - el('div', { class: 'grid-3', style: 'margin-top:6px' }, sDeps, sRetries, sWhen), + sDeps, ); - if (step.type === 'http') { - const mSel = el( - 'select', - { class: 'input-sm' }, - ...(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const).map((m) => - el('option', { value: m, selected: (step.method ?? 'POST') === m }, m), - ), - ) as HTMLSelectElement; - const uIn = el('input', { class: 'input-sm', value: step.url ?? '', placeholder: 'https://...' }) as HTMLInputElement; - const secIn = el('input', { class: 'input-sm', value: step.secretRef ?? '', placeholder: 'secretRef (api-token/webhook-secret)' }) as HTMLInputElement; - const expIn = el('input', { class: 'input-sm', type: 'number', value: step.expectedStatus ? String(step.expectedStatus) : '', placeholder: 'expectedStatus' }) as HTMLInputElement; - const bArea = el('textarea', { rows: 2, placeholder: 'Optional HTTP JSON body' }, step.body ?? '') as HTMLTextAreaElement; - bArea.value = step.body ?? ''; - const syncHttp = () => { - step.method = mSel.value as WorkflowStepDef['method']; - step.url = uIn.value.trim(); - step.secretRef = secIn.value.trim() || undefined; - step.expectedStatus = expIn.value.trim() ? Number(expIn.value) : undefined; - step.body = bArea.value || undefined; - }; - [mSel, uIn, secIn, expIn, bArea].forEach((n) => n.addEventListener('input', syncHttp)); - card.append( - el('div', { class: 'grid-2', style: 'margin-top:6px' }, mSel, uIn, secIn, expIn), - bArea, - ); - } else if (step.type === 'notify') { - const chIn = el('input', { class: 'input-sm', value: (step.channelIds ?? []).join(', '), placeholder: 'channelIds (comma-sep)' }) as HTMLInputElement; - const tIn = el('input', { class: 'input-sm', value: step.title ?? '', placeholder: 'Notification title' }) as HTMLInputElement; - const sevSel = el( - 'select', - { class: 'input-sm' }, - el('option', { value: 'warn', selected: (step.severity ?? 'warn') === 'warn' }, 'warn'), - el('option', { value: 'critical', selected: step.severity === 'critical' }, 'critical'), - ) as HTMLSelectElement; - const mArea = el('textarea', { rows: 2, placeholder: 'Notification message' }, step.message ?? '') as HTMLTextAreaElement; - mArea.value = step.message ?? ''; - const syncNotify = () => { - step.channelIds = chIn.value.split(',').map((s) => s.trim()).filter(Boolean); - step.title = tIn.value; - step.severity = sevSel.value as 'warn' | 'critical'; - step.message = mArea.value; - }; - [chIn, tIn, sevSel, mArea].forEach((n) => n.addEventListener('input', syncNotify)); - card.append( - el('div', { class: 'grid-3', style: 'margin-top:6px' }, chIn, tIn, sevSel), - mArea, - ); - } else if (step.type === 'transfer') { + if (step.type === 'transfer') { const modeSel = el( 'select', { class: 'input-sm' }, @@ -776,12 +675,11 @@ export async function renderWorkflowsView( state: ClientState, wsClient: MultiplexWsClient, ): Promise { - releaseWfWs(); - const unsubBase = wsClient.subscribe(['workflows']); - registerViewCleanup(() => { - releaseWfWs(); - unsubBase(); - }); + if (unsubWfWs) { + unsubWfWs(); + unsubWfWs = null; + } + wsClient.subscribe(['workflows']); root.replaceChildren(); const tabBar = el( @@ -863,18 +761,17 @@ export async function renderWorkflowsView( const watchRunStream = (runId: string, wfId: string) => { streamPanel.hidden = false; const logPre = el('pre', { class: 'stream-log mono' }, `Subscribed to live run ${runId} (${wfId})...\n`); - const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel Run'); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Cancel Run'); cancelBtn.addEventListener('click', async () => { cancelBtn.disabled = true; await apiFetch(`/api/workflows/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' }); - showToast(`Cancellation requested for run ${runId}.`, 'warn'); }); streamPanel.replaceChildren( el('div', { class: 'row-between' }, el('strong', {}, `Live Run Stream: ${wfId} (${runId})`), cancelBtn), logPre, ); - releaseWfWs(); + if (unsubWfWs) unsubWfWs(); unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { if (frame.type === 'stream:chunk' && frame.jobId === `wf:${runId}`) { if (frame.stream !== 'meta') { @@ -894,7 +791,7 @@ export async function renderWorkflowsView( } } }); - unsubWfChannel = wsClient.subscribe([`stream:wf:${runId}`]); + wsClient.subscribe([`stream:wf:${runId}`]); }; const loadRunDetail = async (runId: string) => { @@ -905,29 +802,6 @@ export async function renderWorkflowsView( }>(`/api/workflows/runs/${encodeURIComponent(runId)}`); detailPanel.hidden = false; renderStructuredOutput(detailPanel, res.workflow, res.run, res.stepLogs); - const uniqueSteps = [...new Set(res.stepLogs.map((l) => l.stepId))]; - if (uniqueSteps.length > 0) { - const lazyPre = el('pre', { class: 'stream-log mono', hidden: true }); - const stepRow = el('div', { class: 'row', style: 'margin-top:8px' }, el('span', { class: 'muted' }, 'Inspect step:')); - for (const sid of uniqueSteps) { - const b = el('button', { type: 'button', class: 'btn btn-sm' }, sid); - b.addEventListener('click', async () => { - try { - const sLogs = await apiFetch<{ logs: WorkflowStepLogItem[] }>( - `/api/workflows/runs/${encodeURIComponent(runId)}/steps/${encodeURIComponent(sid)}/logs`, - ); - lazyPre.hidden = false; - lazyPre.textContent = sLogs.logs - .map((l) => `[${l.serverId}] exit=${String(l.exitCode)}\n${l.stdout}${l.stderr ? `\nSTDERR:\n${l.stderr}` : ''}`) - .join('\n---\n') || '(empty)'; - } catch (err) { - showToast(extractErrorMessage(err), 'err'); - } - }); - stepRow.append(b); - } - detailPanel.append(stepRow, lazyPre); - } if (isAiEnabled(state)) { const diagBtn = el( 'button', @@ -1070,10 +944,9 @@ export async function renderWorkflowsView( }); const actRow = el('div', { class: 'row' }, inspectBtn); if (r.status === 'running' || r.status === 'queued') { - const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel'); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Cancel'); cancelBtn.addEventListener('click', async () => { await apiFetch(`/api/workflows/runs/${encodeURIComponent(r.runId)}/cancel`, { method: 'POST' }); - showToast(`Cancelled run ${r.runId}.`, 'warn'); await renderWorkflowsView(root, state, wsClient); }); actRow.append(cancelBtn); @@ -1161,7 +1034,7 @@ export async function renderWorkflowsView( const msgEl = el('p', { class: 'form-msg' }); const cardsGrid = el('div', { class: 'grid-2' }); - const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger', hidden: true }, 'Cancel Broadcast'); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action', hidden: true }, 'Cancel Broadcast'); let activeJobId: string | null = null; cancelBtn.addEventListener('click', async () => { if (!activeJobId) return; @@ -1226,7 +1099,7 @@ export async function renderWorkflowsView( ); } - releaseWfWs(); + if (unsubWfWs) unsubWfWs(); unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { if (frame.type !== 'stream:chunk' || frame.jobId !== activeJobId || frame.stream !== 'meta') return; try { @@ -1261,77 +1134,20 @@ export async function renderWorkflowsView( cancelBtn.hidden = true; msgEl.className = 'form-msg ok-text'; msgEl.textContent = `Broadcast finished: ${String(m.okCount)}/${String(m.total)} succeeded.`; - void loadBroadcastHistory(); } } catch { // Ignore meta parse error } }); - unsubWfChannel = wsClient.subscribe([`stream:${activeJobId}`]); + wsClient.subscribe([`stream:${activeJobId}`]); } catch (err) { msgEl.className = 'form-msg err-text'; msgEl.textContent = extractErrorMessage(err); } }); - const histPanel = el('section', { class: 'panel panel-region' }); - const loadBroadcastHistory = async () => { - histPanel.replaceChildren(el('h2', {}, 'Broadcast History')); - try { - const hRes = await apiFetch<{ - jobs: Array<{ - jobId: string; - snippetId?: string; - command: string; - createdAt: number; - finishedAt: number | null; - done: boolean; - cancelled: boolean; - targets: Array<{ status: string }>; - }>; - }>('/api/workflows/broadcast/history?limit=25'); - if (hRes.jobs.length === 0) { - histPanel.append(el('p', { class: 'muted' }, 'No past fleet broadcasts recorded yet.')); - return; - } - const tbl = el('table'); - tbl.append( - el('thead', {}, el('tr', {}, el('th', {}, 'Job ID'), el('th', {}, 'Command / Snippet'), el('th', {}, 'Result'), el('th', {}, 'Started'), el('th', {}, 'Export'))), - ); - const tbody = el('tbody'); - for (const j of hRes.jobs) { - const okCount = j.targets.filter((t) => t.status === 'ok').length; - tbody.append( - el( - 'tr', - {}, - el('td', { class: 'mono' }, j.jobId), - el('td', { class: 'mono' }, j.snippetId ? `[${j.snippetId}] ${j.command.slice(0, 50)}` : j.command.slice(0, 60)), - el('td', { class: 'mono' }, `${okCount}/${j.targets.length} ok${j.cancelled ? ' (cancelled)' : ''}`), - el('td', { class: 'mono' }, fmtTime(j.createdAt)), - el( - 'td', - {}, - el( - 'div', - { class: 'row' }, - el('a', { href: `/api/workflows/broadcast/${encodeURIComponent(j.jobId)}/export?format=json`, class: 'btn btn-sm', download: '' }, 'JSON'), - el('a', { href: `/api/workflows/broadcast/${encodeURIComponent(j.jobId)}/export?format=csv`, class: 'btn btn-sm', download: '' }, 'CSV'), - ), - ), - ), - ); - } - tbl.append(tbody); - histPanel.append(el('div', { class: 'table-wrap' }, tbl)); - } catch (err) { - histPanel.append(el('p', { class: 'err-text' }, extractErrorMessage(err))); - } - }; - panel.append(el('h2', {}, 'Ad-Hoc Fleet Broadcast'), form); - root.append(panel, cardsGrid, histPanel); - void loadBroadcastHistory(); + root.append(panel, cardsGrid); return; } diff --git a/src/client/ts/ws-client.ts b/src/client/ts/ws-client.ts index 3529d96..507dcbb 100644 --- a/src/client/ts/ws-client.ts +++ b/src/client/ts/ws-client.ts @@ -2,24 +2,16 @@ import type { ClientWsFrame, ServerWsFrame } from '../../shared/ws-protocol.js'; export type WsConnectionStatus = 'online' | 'reconnecting' | 'offline'; -const CORE_CHANNELS = ['config', 'alerts', 'metrics', 'workflows'] as const; - export class MultiplexWsClient { private ws: WebSocket | null = null; private reconnectAttempt = 0; private reconnectTimer: number | null = null; private pingTimer: number | null = null; private shouldRun = false; - private readonly channelRefs = new Map(); + private channels = new Set(['config', 'alerts', 'metrics', 'workflows']); private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>(); private readonly statusListeners = new Set<(status: WsConnectionStatus) => void>(); - constructor() { - for (const ch of CORE_CHANNELS) { - this.channelRefs.set(ch, 1); - } - } - onFrame(listener: (frame: ServerWsFrame) => void): () => void { this.frameListeners.add(listener); return () => this.frameListeners.delete(listener); @@ -45,11 +37,6 @@ export class MultiplexWsClient { window.clearInterval(this.pingTimer); this.pingTimer = null; } - for (const ch of [...this.channelRefs.keys()]) { - if (!(CORE_CHANNELS as readonly string[]).includes(ch)) { - this.channelRefs.delete(ch); - } - } if (this.ws) { this.ws.close(1000, 'Client disconnect'); this.ws = null; @@ -63,54 +50,14 @@ export class MultiplexWsClient { } } - /** - * Reference-counted channel subscription. Returns a cleanup callback that - * releases this caller's references and sends `{ type: 'unsub' }` once refcount hits 0. - */ - subscribe(channels: string[]): () => void { - const addedNow: string[] = []; - const tracked: string[] = []; - for (const ch of channels) { - if (!ch) continue; - tracked.push(ch); - const prev = this.channelRefs.get(ch) ?? 0; - this.channelRefs.set(ch, prev + 1); - if (prev === 0) addedNow.push(ch); - } - if (addedNow.length > 0) { - this.send({ type: 'sub', channels: addedNow }); - } - let disposed = false; - return () => { - if (disposed) return; - disposed = true; - this.unsubscribe(tracked); - }; - } - - unsubscribe(channels: string[]): void { - const dropped: string[] = []; - for (const ch of channels) { - if ((CORE_CHANNELS as readonly string[]).includes(ch)) continue; - const cur = this.channelRefs.get(ch) ?? 0; - if (cur <= 1) { - this.channelRefs.delete(ch); - if (cur === 1) dropped.push(ch); - } else { - this.channelRefs.set(ch, cur - 1); - } - } - if (dropped.length > 0) { - this.send({ type: 'unsub', channels: dropped }); - } + subscribe(channels: string[]): void { + for (const ch of channels) this.channels.add(ch); + this.send({ type: 'sub', channels }); } private openSocket(): void { if (!this.shouldRun) return; - if ( - this.ws && - (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) - ) { + if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) { return; } @@ -121,9 +68,8 @@ export class MultiplexWsClient { socket.addEventListener('open', () => { this.reconnectAttempt = 0; this.emitStatus('online'); - const allActive = [...this.channelRefs.keys()]; - if (allActive.length > 0) { - this.send({ type: 'sub', channels: allActive }); + if (this.channels.size > 0) { + this.send({ type: 'sub', channels: [...this.channels] }); } if (this.pingTimer !== null) window.clearInterval(this.pingTimer); this.pingTimer = window.setInterval(() => { diff --git a/src/server/ai/ai-service.ts b/src/server/ai/ai-service.ts index 61af7b6..fd9c629 100644 --- a/src/server/ai/ai-service.ts +++ b/src/server/ai/ai-service.ts @@ -13,9 +13,7 @@ import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; import type { WsHub } from '../api/ws-hub.js'; import type { ConfigManager } from '../config/config-manager.js'; import { computeLineDiff, type DiffLine } from '../config/diff.js'; -import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { AuditService } from '../security/audit.js'; -import { fetchWithEgressGuard } from '../security/egress-guard.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { @@ -33,14 +31,6 @@ export class AiDisabledError extends Error { } } -export class AiOverloadError extends Error { - readonly code = 'AI_CONCURRENCY_LIMIT'; - readonly status = 503; - constructor(limit: number) { - super(`Too many concurrent AI streams (limit: ${limit}). Retry shortly.`); - } -} - export interface ChatMessageInput { role: 'user' | 'assistant'; content: string; @@ -74,7 +64,6 @@ export class AiService { private readonly sshPool: SSHPool, private readonly wsHub: WsHub, private readonly auditService: AuditService, - private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} getReplayFrames(chatId: string): ServerWsFrame[] { @@ -104,8 +93,11 @@ export class AiService { private resolveBearerToken(secretRef?: string): string | undefined { if (!secretRef || !this.vaultService.isRuntimeReady) return undefined; const cred = this.vaultService.getRuntimeSecret(secretRef); - if (!cred || cred.type !== 'api-token') return undefined; - return cred.token; + if (!cred) return undefined; + if (cred.type === 'api-token') return cred.token; + if (cred.type === 'webhook-secret') return cred.secret; + if (cred.type === 'ssh-password' || cred.type === 'sudo-password') return cred.password; + return undefined; } previewContext(opts: { @@ -176,12 +168,6 @@ export class AiService { throw new AiDisabledError(); } - const activeStreams = [...this.chats.values()].filter((c) => !c.done).length; - const maxStreams = Math.max(1, this.getRuntimeLimits?.().maxConcurrentAiStreams ?? 2); - if (activeStreams >= maxStreams) { - throw new AiOverloadError(maxStreams); - } - const knownSecrets = collectVaultSecretStrings(this.vaultService); const guide = buildSurfaceGuideAndInventory( opts.surface, @@ -303,26 +289,19 @@ export class AiService { headers.Authorization = `Bearer ${bearerToken}`; } - const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; - const aiCfg = this.configManager.getSettings().ai; - const res = await fetchWithEgressGuard( - endpointUrl, - { - method: 'POST', - headers, - body: JSON.stringify({ model, stream: true, messages, max_tokens: aiCfg.maxTokens }), - signal: chat.abortController.signal, - }, - { allowedCidrs, timeoutMs: (aiCfg.timeoutSec ?? 90) * 1000 }, - ); + const res = await fetch(endpointUrl, { + method: 'POST', + headers, + body: JSON.stringify({ model, stream: true, messages }), + signal: chat.abortController.signal, + }); if (!res.ok) { const errBody = await res.text().catch(() => ''); - const cleanErr = bearerToken ? errBody.split(bearerToken).join('[REDACTED]') : errBody; this.emitDelta(chat, { chunk: '', done: true, - error: `LLM endpoint HTTP ${res.status}${cleanErr ? `: ${cleanErr.slice(0, 240)}` : ''}`, + error: `LLM endpoint HTTP ${res.status}${errBody ? `: ${errBody.slice(0, 240)}` : ''}`, }); return; } @@ -344,22 +323,12 @@ export class AiService { const reader = res.body.getReader(); const decoder = new TextDecoder(); let buf = ''; - const MAX_SSE_LINE_BUF = 256 * 1024; let doneSent = false; while (true) { const { value, done } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); - if (buf.length > MAX_SSE_LINE_BUF) { - await reader.cancel().catch(() => undefined); - this.emitDelta(chat, { - chunk: '', - done: true, - error: 'AI SSE line buffer exceeded 256 KiB limit', - }); - return; - } let nlIdx: number; while ((nlIdx = buf.indexOf('\n')) >= 0) { @@ -402,11 +371,11 @@ export class AiService { this.emitDelta(chat, { chunk: '', done: true }); } } catch (err) { - const rawErr = err instanceof Error ? err.message : String(err); - const safeErr = bearerToken ? rawErr.split(bearerToken).join('[REDACTED]') : rawErr; const msg = chat.abortController.signal.aborted ? 'Generation cancelled' - : safeErr; + : err instanceof Error + ? err.message + : String(err); this.emitDelta(chat, { chunk: '', done: true, @@ -444,29 +413,24 @@ export class AiService { const headers: Record = { 'Content-Type': 'application/json' }; if (bearer) headers.Authorization = `Bearer ${bearer}`; - const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; - const res = await fetchWithEgressGuard( - url, - { - method: 'POST', - headers, - body: JSON.stringify({ - model, - stream: false, - max_tokens: 16, - messages: [{ role: 'user', content: 'Reply with OK' }], - }), - }, - { allowedCidrs, timeoutMs: 10_000 }, - ); + const res = await fetch(url, { + method: 'POST', + headers, + body: JSON.stringify({ + model, + stream: false, + max_tokens: 16, + messages: [{ role: 'user', content: 'Reply with OK' }], + }), + signal: AbortSignal.timeout(10_000), + }); const latencyMs = Date.now() - started; if (!res.ok) { const text = await res.text().catch(() => ''); - const cleanText = bearer ? text.split(bearer).join('[REDACTED]') : text; return { ok: false, latencyMs, - error: `HTTP ${res.status}${cleanText ? `: ${cleanText.slice(0, 180)}` : ''}`, + error: `HTTP ${res.status}${text ? `: ${text.slice(0, 180)}` : ''}`, }; } const data = (await res.json().catch(() => ({}))) as { @@ -476,11 +440,10 @@ export class AiService { data.choices?.[0]?.message?.content ?? data.choices?.[0]?.text ?? 'Connected'; return { ok: true, latencyMs, replyPreview: String(preview).trim().slice(0, 120) }; } catch (err) { - const rawErr = err instanceof Error ? err.message : String(err); return { ok: false, latencyMs: Date.now() - started, - error: bearer ? rawErr.split(bearer).join('[REDACTED]') : rawErr, + error: err instanceof Error ? err.message : String(err), }; } } @@ -523,29 +486,9 @@ export class AiService { }; } - if ( - opts.targetId && - rawObj && - typeof rawObj === 'object' && - !Array.isArray(rawObj) - ) { - const suppliedId = (rawObj as Record).id; - if (suppliedId !== undefined && suppliedId !== opts.targetId) { - return { - valid: false, - issues: [ - { - path: 'id', - message: `Draft id "${String(suppliedId)}" does not match locked targetId "${opts.targetId}"`, - }, - ], - }; - } - } - const withOptionalId = (obj: unknown) => opts.targetId && obj && typeof obj === 'object' && !Array.isArray(obj) - ? { ...(obj as Record), id: opts.targetId } + ? { ...(obj as Record), id: (obj as Record).id ?? opts.targetId } : obj; let targetPath: string; diff --git a/src/server/ai/guides.ts b/src/server/ai/guides.ts index 4906066..5d3b16f 100644 --- a/src/server/ai/guides.ts +++ b/src/server/ai/guides.ts @@ -26,8 +26,7 @@ export function buildSurfaceGuideAndInventory( targetPath?: string; } = {}, ): SurfaceGuideResult { - const { configManager, sshPool } = deps; - void deps.vaultService; + const { configManager, vaultService, sshPool } = deps; const servers = configManager.listServers(); const systems = configManager.listSystems(); const snippets = configManager.getSnippets().snippets; @@ -52,6 +51,10 @@ export function buildSurfaceGuideAndInventory( actions: sys.actions.map((a) => ({ id: a.id, scope: a.scope, mode: a.mode })), })); + const credMeta = vaultService.isRuntimeReady + ? vaultService.listMetadata().map((c) => ({ id: c.id, name: c.name, type: c.type })) + : []; + const targetSrv = opts.serverId ? configManager.getServer(opts.serverId) : undefined; const targetSrvOs = opts.serverId ? sshPool.getState(opts.serverId)?.osDetected ?? targetSrv?.osHint ?? 'unknown' @@ -64,6 +67,7 @@ export function buildSurfaceGuideAndInventory( existingWorkflowIds: workflows.map((w) => w.id), existingSnippetIds: snippets.map((s) => s.id), alertChannelIds: alerts.channels.map((c) => c.id), + vaultCredentialRefs: credMeta, ...(opts.serverId ? { focusedServer: { id: opts.serverId, os: targetSrvOs } } : {}), ...(opts.targetPath ? { focusedConfigPath: opts.targetPath } : {}), }, diff --git a/src/server/ai/redactor.ts b/src/server/ai/redactor.ts index dc4b5bb..43a4fe8 100644 --- a/src/server/ai/redactor.ts +++ b/src/server/ai/redactor.ts @@ -6,7 +6,9 @@ export interface RedactionResult { truncated: boolean; } -const MIN_VAULT_SECRET_LEN = 4; +function escapeRegExp(literal: string): string { + return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} export function collectVaultSecretStrings(vaultService: VaultService): string[] { if (!vaultService.isRuntimeReady) return []; @@ -16,21 +18,21 @@ export function collectVaultSecretStrings(vaultService: VaultService): string[] const creds = vaultService.exportAllCredentials(); for (const cred of Object.values(creds)) { if (cred.type === 'ssh-password' || cred.type === 'sudo-password') { - if (cred.password.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.password); + if (cred.password.length >= 6) collected.add(cred.password); } else if (cred.type === 'webhook-secret') { - if (cred.secret.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.secret); + if (cred.secret.length >= 6) collected.add(cred.secret); } else if (cred.type === 'api-token') { - if (cred.token.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.token); + if (cred.token.length >= 6) collected.add(cred.token); } else if (cred.type === 'ssh-key') { const trimmed = cred.privateKey.trim(); - if (trimmed.length >= MIN_VAULT_SECRET_LEN) collected.add(trimmed); + if (trimmed.length >= 6) collected.add(trimmed); for (const line of trimmed.split(/\r?\n/)) { const l = line.trim(); if (l.length >= 12 && !l.startsWith('-----')) { collected.add(l); } } - if (cred.passphrase && cred.passphrase.length >= MIN_VAULT_SECRET_LEN) { + if (cred.passphrase && cred.passphrase.length >= 6) { collected.add(cred.passphrase); } } @@ -42,119 +44,6 @@ export function collectVaultSecretStrings(vaultService: VaultService): string[] return [...collected].sort((a, b) => b.length - a.length); } -function replaceLiteralLinear( - text: string, - needle: string, - replacement: string, -): { text: string; hits: number } { - if (!needle) return { text, hits: 0 }; - let idx = text.indexOf(needle); - if (idx < 0) return { text, hits: 0 }; - let out = ''; - let last = 0; - let hits = 0; - while (idx >= 0) { - out += text.slice(last, idx) + replacement; - last = idx + needle.length; - hits += 1; - idx = text.indexOf(needle, last); - } - out += text.slice(last); - return { text: out, hits }; -} - -/** - * Linear-time PEM private key block scanner (catches both complete blocks and - * truncated logs containing only `-----BEGIN ... PRIVATE KEY-----` headers). - */ -function stripPemPrivateKeys(input: string): { text: string; hits: number } { - const beginMarker = '-----BEGIN '; - let idx = input.indexOf(beginMarker); - if (idx < 0) return { text: input, hits: 0 }; - - let out = ''; - let last = 0; - let hits = 0; - - while (idx >= 0) { - const headerEnd = input.indexOf('-----', idx + beginMarker.length); - if (headerEnd < 0 || headerEnd - idx > 80) break; - const headerSlice = input.slice(idx + beginMarker.length, headerEnd); - if (!/PRIVATE KEY$/i.test(headerSlice)) { - idx = input.indexOf(beginMarker, headerEnd + 5); - continue; - } - - const endHeader = `-----END ${headerSlice}-----`; - const footerPos = input.indexOf(endHeader, headerEnd + 5); - let blockEnd: number; - if (footerPos >= 0) { - blockEnd = footerPos + endHeader.length; - } else { - // Truncated PEM: strip from BEGIN header up to a blank line or 8 KiB - const blank = input.indexOf('\n\n', headerEnd + 5); - blockEnd = - blank >= 0 - ? blank - : Math.min(input.length, headerEnd + 5 + 8192); - } - - out += input.slice(last, idx) + '[REDACTED_PRIVATE_KEY]'; - hits += 1; - last = blockEnd; - idx = input.indexOf(beginMarker, last); - } - - out += input.slice(last); - return { text: out, hits }; -} - -/** - * Linear-time O(n) JSON `"secretKey": "secretVal"` scrubber without ReDoS-prone - * nested escape quantifiers. - */ -function stripJsonSecretValues(input: string): { text: string; hits: number } { - const keyRe = - /"[A-Za-z0-9_-]{0,40}(?:password|passwd|secret|token|apiKey|api_key|privateKey|private_key|passphrase|accessKey|secretKey|client_secret|refresh_token)[A-Za-z0-9_-]{0,40}"\s*:\s*"/gi; - let out = ''; - let last = 0; - let hits = 0; - let m: RegExpExecArray | null; - - while ((m = keyRe.exec(input)) !== null) { - const valStart = m.index + m[0].length; - if (valStart < last) continue; - - // Scan forward strictly once in O(k) checking backslash escapes - let pos = valStart; - let closed = false; - while (pos < input.length) { - const ch = input.charCodeAt(pos); - if (ch === 92 /* '\\' */) { - pos += 2; - continue; - } - if (ch === 34 /* '"' */) { - closed = true; - break; - } - if (ch === 10 || ch === 13) break; - pos += 1; - } - - const valSlice = input.slice(valStart, pos); - if (valSlice.includes('[REDACTED')) continue; - - out += input.slice(last, valStart) + '[REDACTED_SECRET]' + (closed ? '"' : ''); - hits += 1; - last = closed ? pos + 1 : pos; - keyRe.lastIndex = last; - } - - out += input.slice(last); - return { text: out, hits }; -} - export function redactSecrets( input: string, knownSecrets: string[] = [], @@ -163,22 +52,27 @@ export function redactSecrets( let redactedCount = 0; let text = input ?? ''; - // 1. Complete & truncated PEM / OpenSSH private keys in O(n) - const pem = stripPemPrivateKeys(text); - text = pem.text; - redactedCount += pem.hits; + // 1. Strip PEM / OpenSSH private key blocks + const keyBlockRe = + /-----BEGIN [A-Z0-9 -]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 -]*PRIVATE KEY-----/g; + text = text.replace(keyBlockRe, () => { + redactedCount += 1; + return '[REDACTED_PRIVATE_KEY]'; + }); - // 2. Vault secrets >= 4 chars in O(n * m) + // 2. Strip known secrets currently held in Vault for (const secret of knownSecrets) { - if (secret.length < MIN_VAULT_SECRET_LEN) continue; - const res = replaceLiteralLinear(text, secret, '[REDACTED_VAULT_SECRET]'); - text = res.text; - redactedCount += res.hits; + if (secret.length < 6) continue; + const re = new RegExp(escapeRegExp(secret), 'g'); + text = text.replace(re, () => { + redactedCount += 1; + return '[REDACTED_VAULT_SECRET]'; + }); } - // 3. HTTP Authorization / Cookie / Proxy / custom secret headers + // 3. Strip HTTP Authorization / Bearer / custom secret headers text = text.replace( - /\b((?:Proxy-)?Authorization\s*:\s*(?:Bearer|Basic|Token)\s+)([^\r\n]{1,1024})/gi, + /\b(Authorization\s*:\s*(?:Bearer|Basic)\s+)([^\r\n]+)/gi, (_m, prefix: string, val: string) => { if (val.includes('[REDACTED')) return _m; redactedCount += 1; @@ -186,45 +80,25 @@ export function redactSecrets( }, ); text = text.replace( - /\b(Cookie|Set-Cookie|X-API-Key|X-Auth-Token|X-Telegram-Bot-Token|X-Access-Token)\s*:\s*([^\r\n]{1,1024})/gi, - (_m, key: string, val: string) => { + /\bBearer\s+([A-Za-z0-9._~+/=-]{12,})/g, + (_m, val: string) => { if (val.includes('[REDACTED')) return _m; redactedCount += 1; - return `${key}: [REDACTED_TOKEN]`; + return 'Bearer [REDACTED_TOKEN]'; }, ); text = text.replace( - /\b(?:Bearer|Basic)\s+([A-Za-z0-9._~+/=-]{8,1024})/g, - (full, val: string) => { - if (val.includes('[REDACTED')) return full; + /\b(X-(?:API-Key|Telegram-Bot-Token|Auth-Token)\s*:\s*)([^\s\r\n]+)/gi, + (_m, prefix: string, val: string) => { + if (val.includes('[REDACTED')) return _m; redactedCount += 1; - return full.startsWith('Basic') ? 'Basic [REDACTED_TOKEN]' : 'Bearer [REDACTED_TOKEN]'; + return `${prefix}[REDACTED_TOKEN]`; }, ); - // 4. URL embedded credentials (user:pass@host) + // 4. Strip .env / shell KEY=value secret assignments text = text.replace( - /([a-zA-Z][a-zA-Z0-9+.-]{1,15}:\/\/[^:/\s@]{1,64}:)([^/\s@]{1,256})@/g, - (_m, prefix: string, pw: string) => { - if (pw.includes('[REDACTED')) return _m; - redactedCount += 1; - return `${prefix}[REDACTED_SECRET]@`; - }, - ); - - // 5. Known API/cloud token formats - text = text.replace( - /\b(?:sk-[A-Za-z0-9_-]{12,256}|gh[pou]_[A-Za-z0-9]{12,256}|github_pat_[A-Za-z0-9_]{16,256}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,256}|AIza[0-9A-Za-z_-]{20,64}|glpat-[A-Za-z0-9_-]{12,256})/g, - (tok) => { - if (tok.includes('[REDACTED')) return tok; - redactedCount += 1; - return '[REDACTED_TOKEN]'; - }, - ); - - // 6. .env / shell KEY=value secret assignments (linear bounded match) - text = text.replace( - /(^|[\s;|&])([A-Za-z0-9_]{0,48}(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY|APIKEY|PRIVATE_KEY|PASSPHRASE|ACCESS_KEY|CREDENTIAL)[A-Za-z0-9_]{0,48})=([^\s\r\n]{1,512}|"[^"\r\n]{0,512}"|'[^'\r\n]{0,512}')/gim, + /(^|[\s;|&])([A-Za-z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY|APIKEY|PRIVATE_KEY|PASSPHRASE)[A-Za-z0-9_]*)=("[^"\n]*"|'[^'\n]*'|[^\s\r\n]+)/gim, (_m, lead: string, key: string, rawVal: string) => { if (rawVal.includes('[REDACTED')) return _m; redactedCount += 1; @@ -232,10 +106,15 @@ export function redactSecrets( }, ); - // 7. JSON "key": "secret" string properties in O(n) - const jsonRes = stripJsonSecretValues(text); - text = jsonRes.text; - redactedCount += jsonRes.hits; + // 5. Strip JSON "key": "secret" string properties + text = text.replace( + /("(?:[A-Za-z0-9_-]*(?:password|passwd|secret|token|apiKey|api_key|privateKey|private_key|passphrase)[A-Za-z0-9_-]*)"\s*:\s*)"([^"\\]*(?:\\.[^"\\]*)*)"/gi, + (_m, keyPrefix: string, val: string) => { + if (val.includes('[REDACTED')) return _m; + redactedCount += 1; + return `${keyPrefix}"[REDACTED_SECRET]"`; + }, + ); const cap = Math.max(256, maxChars); let truncated = false; diff --git a/src/server/alerts/alert-engine.ts b/src/server/alerts/alert-engine.ts index 765e58f..7dfc025 100644 --- a/src/server/alerts/alert-engine.ts +++ b/src/server/alerts/alert-engine.ts @@ -5,7 +5,6 @@ import type { AlertChannel, AlertRule, AlertRuleTargetSchema, - SecurityEventKind, } from '../../shared/schemas/alerts.schema.js'; import type { ServerConfig } from '../../shared/schemas/server.schema.js'; import type { z } from 'zod'; @@ -18,7 +17,6 @@ import type { MonitoringTickEvent, } from '../monitoring/monitoring-service.js'; import type { AuditService } from '../security/audit.js'; -import { fetchWithEgressGuard } from '../security/egress-guard.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import type { @@ -65,7 +63,6 @@ export class AlertEngine { private readonly emittedOffline = new Set(); private readonly prevProbeOk = new Map(); private readonly prevSystemDown = new Set(); - private readonly channelCircuit = new Map(); private readonly unsubs: Array<() => void> = []; private sweepTimer: NodeJS.Timeout | null = null; private stopped = false; @@ -86,10 +83,10 @@ export class AlertEngine { this.stopped = false; this.hydrateOpenIncidents(); - this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId, meta) => { + this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId) => { await this.sendDirectChannelMessage(channelId, { - severity: meta?.severity ?? 'critical', - title: meta?.title ?? 'Workflow Execution Failure', + severity: 'critical', + title: 'Workflow Execution Failure', message, state: 'firing', }); @@ -301,20 +298,16 @@ export class AlertEngine { throw new Error(`Unknown alert channel "${channelId}"`); } - const res = await this.dispatchToChannel( - ch, - { - id: `test-${crypto.randomBytes(4).toString('hex')}`, - ruleId: 'test-alert', - serverId: 'hub', - severity: 'warn', - title: '[TEST] GCoordinator Alert Channel Verification', - message: `Test notification dispatched to "${ch.name}" (${ch.type}) at ${new Date().toISOString()}.`, - state: 'firing', - ts: Date.now(), - }, - { bypassCircuitBreaker: true }, - ); + const res = await this.dispatchToChannel(ch, { + id: `test-${crypto.randomBytes(4).toString('hex')}`, + ruleId: 'test-alert', + serverId: 'hub', + severity: 'warn', + title: '[TEST] GCoordinator Alert Channel Verification', + message: `Test notification dispatched to "${ch.name}" (${ch.type}) at ${new Date().toISOString()}.`, + state: 'firing', + ts: Date.now(), + }); this.auditService.log({ action: 'alert.test_channel', @@ -362,6 +355,10 @@ export class AlertEngine { } } } + + for (const probe of event.probes) { + await this.evaluateProbe(server.id, probe, nowMs); + } } async evaluateProbe( @@ -691,151 +688,7 @@ export class AlertEngine { } } - syncWithConfig(): void { - const alerts = this.configManager.getAlerts(); - const activeRuleIds = new Set(alerts.rules.filter((r) => r.enabled).map((r) => r.id)); - const activeServerIds = new Set( - this.configManager.listServers().filter((s) => s.enabled).map((s) => s.id), - ); - const now = Date.now(); - let changed = false; - - for (const [key, state] of this.incidents.entries()) { - const parts = key.split('::'); - const ruleId = parts[0] ?? ''; - const serverId = parts[1] ?? ''; - if (!activeRuleIds.has(ruleId) || (serverId !== 'hub' && !activeServerIds.has(serverId))) { - if (state.firingEventId) { - this.db - .prepare(`UPDATE alert_events SET state = 'resolved', resolved_at = ? WHERE id = ? AND state = 'firing'`) - .run(now, state.firingEventId); - changed = true; - } - this.incidents.delete(key); - } - } - - if (changed) { - this.wsHub.broadcastChannel(WS_CHANNELS.ALERTS, { - type: 'alerts:update', - activeCount: this.getActiveCount(), - }); - } - } - - async emitSecurityEvent( - eventType: SecurityEventKind | string, - payload: { - serverId?: string; - ip?: string; - message?: string; - details?: Record; - } = {}, - nowMs = Date.now(), - ): Promise { - if (this.stopped) return; - - const aliasMap: Record = { - 'auth.lockout': ['auth.lockout', 'login_burst'], - login_burst: ['login_burst', 'auth.lockout'], - 'auth.totp_replay': ['auth.totp_replay', 'login_burst'], - 'auth.recovery_code_used': ['auth.recovery_code_used', 'new_ip_login'], - 'auth.session_idle_expired': ['auth.session_idle_expired'], - 'ssh.host_key_mismatch': ['ssh.host_key_mismatch'], - 'vault.panic_lock': ['vault.panic_lock', 'panic_lock'], - panic_lock: ['panic_lock', 'vault.panic_lock'], - }; - const matchSet = new Set(aliasMap[eventType] ?? [eventType]); - - const rules = this.configManager - .getAlerts() - .rules.filter( - (r) => - r.enabled && - r.kind === 'security-event' && - r.events.some((ev) => matchSet.has(ev)), - ); - - if (rules.length === 0) return; - - const server = payload.serverId ? this.configManager.getServer(payload.serverId) : undefined; - const msgSuffix = - payload.message ?? - (payload.ip ? `source IP ${payload.ip}` : 'hub security boundary'); - const summaryMsg = `SECURITY [${eventType}]: ${msgSuffix}`; - - for (const rule of rules) { - if (rule.kind !== 'security-event') continue; - if (server && !this.matchesTarget(rule.target, server)) continue; - - const incKey = `${rule.id}::${server?.id ?? 'hub'}::sec::${eventType}`; - const state = this.incidents.get(incKey) ?? { consecutiveFailures: 0 }; - const inCooldown = - state.lastNotifiedAt !== undefined && - nowMs - state.lastNotifiedAt < rule.cooldownSec * 1000; - const silences = this.listSilences(nowMs); - const silenced = silences.some( - (s) => - s.scopeType === 'all' || - (s.scopeType === 'rule' && s.targetId === rule.id) || - (server && s.scopeType === 'server' && s.targetId === server.id), - ); - - const eventId = `evt-${crypto.randomBytes(6).toString('hex')}`; - const initialStatus = silenced ? 'suppressed' : inCooldown ? 'cooldown' : 'pending'; - - this.db - .prepare( - `INSERT INTO alert_events (id, rule_id, server_id, state, severity, message, webhook_status, triggered_at, resolved_at, incident_key) - VALUES (?, ?, ?, 'firing', ?, ?, ?, ?, NULL, ?)`, - ) - .run( - eventId, - rule.id, - server?.id ?? null, - rule.severity, - summaryMsg, - initialStatus, - nowMs, - incKey, - ); - - this.wsHub.broadcastChannel(WS_CHANNELS.ALERTS, { - type: 'alerts:update', - activeCount: this.getActiveCount(), - event: { - id: eventId, - ruleId: rule.id, - serverId: server?.id, - severity: rule.severity, - message: summaryMsg, - ts: nowMs, - }, - }); - - if (!silenced && !inCooldown && rule.channelIds.length > 0) { - state.lastNotifiedAt = nowMs; - this.incidents.set(incKey, state); - const statusText = await this.dispatchRuleChannels(rule.channelIds, { - id: eventId, - ruleId: rule.id, - serverId: server?.id ?? 'hub', - severity: rule.severity, - title: `[SECURITY ${rule.severity.toUpperCase()}] ${rule.name}`, - message: summaryMsg, - state: 'firing', - ts: nowMs, - }); - this.db - .prepare('UPDATE alert_events SET webhook_status = ? WHERE id = ?') - .run(statusText, eventId); - } - } - } - private matchesTarget(target: AlertRuleTarget, server: ServerConfig): boolean { - if (target.all) return true; - if (!target.serverId && (!target.tags || target.tags.length === 0)) return false; if (target.serverId && target.serverId !== server.id) return false; if (target.tags && target.tags.length > 0) { if (!server.tags.some((t) => target.tags!.includes(t))) return false; @@ -898,8 +751,11 @@ export class AlertEngine { private readChannelSecret(secretRef: string): string | null { if (!this.vaultService.isRuntimeReady) return null; const cred = this.vaultService.getRuntimeSecret(secretRef); - if (!cred || cred.type !== 'webhook-secret') return null; - return cred.secret; + if (!cred) return null; + if (cred.type === 'webhook-secret') return cred.secret; + if (cred.type === 'api-token') return cred.token; + if (cred.type === 'ssh-password' || cred.type === 'sudo-password') return cred.password; + return null; } private async dispatchToChannel( @@ -914,30 +770,15 @@ export class AlertEngine { state: 'firing' | 'resolved'; ts: number; }, - opts: { bypassCircuitBreaker?: boolean } = {}, ): Promise<{ ok: boolean; statusCode?: number; error?: string }> { - const cb = this.channelCircuit.get(channel.id); - if (!opts.bypassCircuitBreaker && cb && cb.openUntil > Date.now()) { - return { ok: false, error: 'Channel circuit breaker temporarily open after repeated failures' }; - } - - const secret = channel.secretRef ? this.readChannelSecret(channel.secretRef) : null; - if (channel.secretRef && !secret) { - return { - ok: false, - error: `Missing or incompatible webhook-secret "${channel.secretRef}" in Vault`, - }; - } + const secret = this.readChannelSecret(channel.secretRef); if (!secret && !channel.url) { - return { ok: false, error: 'Missing alert channel URL and webhook-secret' }; + return { ok: false, error: `Missing vault secret "${channel.secretRef}"` }; } - const redactErr = (raw: string): string => - secret && secret.length > 0 ? raw.split(secret).join('[REDACTED]') : raw; - try { let targetUrl = channel.url ?? ''; - const method = 'POST'; + let method = 'POST'; const headers: Record = {}; let body: string; @@ -990,42 +831,24 @@ export class AlertEngine { body = JSON.stringify(payload); } - const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; - const res = await fetchWithEgressGuard( - targetUrl, - { method, headers, body }, - { allowedCidrs, timeoutMs: 10_000 }, - ); - - if (res.ok) { - this.channelCircuit.delete(channel.id); - } else { - this.recordChannelFailure(channel.id); - } - + const res = await fetch(targetUrl, { + method, + headers, + body, + signal: AbortSignal.timeout(10_000), + }); return { ok: res.ok, statusCode: res.status, error: res.ok ? undefined : `HTTP ${res.status}`, }; } catch (err) { - this.recordChannelFailure(channel.id); return { ok: false, - error: redactErr(err instanceof Error ? err.message : String(err)), + error: err instanceof Error ? err.message : String(err), }; } } - - private recordChannelFailure(channelId: string): void { - const cur = this.channelCircuit.get(channelId) ?? { failures: 0, openUntil: 0 }; - cur.failures += 1; - if (cur.failures >= 5) { - cur.openUntil = Date.now() + 60_000; - cur.failures = 0; - } - this.channelCircuit.set(channelId, cur); - } } function compareOp( diff --git a/src/server/api/routes/ai.routes.ts b/src/server/api/routes/ai.routes.ts index 0fdb554..6f45cec 100644 --- a/src/server/api/routes/ai.routes.ts +++ b/src/server/api/routes/ai.routes.ts @@ -1,30 +1,23 @@ -import { Router, type RequestHandler } from 'express'; +import { Router } from 'express'; import { z } from 'zod'; import { EntityIdSchema } from '../../../shared/schemas/common.js'; -import { - AiDisabledError, - AiDraftKindSchema, - AiOverloadError, - type AiService, -} from '../../ai/ai-service.js'; +import { AiDisabledError, AiDraftKindSchema, type AiService } from '../../ai/ai-service.js'; import { AiSurfaceSchema } from '../../ai/guides.js'; import type { AuthService } from '../../security/auth.js'; import { enforceSafeMode, requireAuth, requireCsrf, - requireStepUp, } from '../../security/guards.js'; export interface AiRouterDeps { authService: AuthService; aiService: AiService; - stepUpGuard?: RequestHandler; } export function createAiRouter(deps: AiRouterDeps): Router { const router = Router(); - const { authService, aiService, stepUpGuard = requireStepUp } = deps; + const { authService, aiService } = deps; // Read-only context redaction & preview (Safe-Mode exempt) router.post('/context-preview', requireAuth(authService), requireCsrf, (req, res) => { @@ -63,8 +56,8 @@ export function createAiRouter(deps: AiRouterDeps): Router { res.json(aiService.validateDraft(parsed.data)); }); - // Read-only draft streaming: Safe-Mode exempt, stepUpGuard protects Vault API token egress - router.post('/chat', requireAuth(authService), requireCsrf, stepUpGuard, (req, res) => { + // Strictly read-only draft streaming: never auto-executes commands (Safe-Mode exempt) + router.post('/chat', requireAuth(authService), requireCsrf, (req, res) => { const parsed = z .object({ chatId: z.string().min(1).max(64).optional(), @@ -97,8 +90,8 @@ export function createAiRouter(deps: AiRouterDeps): Router { }); res.status(202).json(started); } catch (err) { - if (err instanceof AiDisabledError || err instanceof AiOverloadError) { - res.status(err.status).json({ error: err.code, message: err.message }); + if (err instanceof AiDisabledError) { + res.status(403).json({ error: err.code, message: err.message }); return; } res.status(400).json({ @@ -113,29 +106,22 @@ export function createAiRouter(deps: AiRouterDeps): Router { res.json({ cancelled: aiService.cancelChat(chatId) }); }); - router.post( - '/test', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - async (req, res) => { - const parsed = z - .object({ - baseUrl: z.string().url().optional(), - model: z.string().min(1).optional(), - secretRef: z.string().max(64).optional(), - }) - .safeParse(req.body ?? {}); + router.post('/test', requireAuth(authService), requireCsrf, enforceSafeMode, async (req, res) => { + const parsed = z + .object({ + baseUrl: z.string().url().optional(), + model: z.string().min(1).optional(), + secretRef: z.string().max(64).optional(), + }) + .safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } - res.json(await aiService.testEndpoint(parsed.data)); - }, - ); + res.json(await aiService.testEndpoint(parsed.data)); + }); return router; } diff --git a/src/server/api/routes/alerts.routes.ts b/src/server/api/routes/alerts.routes.ts index 0b2c345..bfb82f7 100644 --- a/src/server/api/routes/alerts.routes.ts +++ b/src/server/api/routes/alerts.routes.ts @@ -1,4 +1,4 @@ -import { Router, type RequestHandler } from 'express'; +import { Router } from 'express'; import { ZodError, z } from 'zod'; import { AlertsFileSchema } from '../../../shared/schemas/alerts.schema.js'; import type { AlertEngine } from '../../alerts/alert-engine.js'; @@ -9,7 +9,6 @@ import { enforceSafeMode, requireAuth, requireCsrf, - requireStepUp, } from '../../security/guards.js'; export interface AlertsRouterDeps { @@ -17,13 +16,11 @@ export interface AlertsRouterDeps { configManager: ConfigManager; auditService: AuditService; alertEngine: AlertEngine; - stepUpGuard?: RequestHandler; } export function createAlertsRouter(deps: AlertsRouterDeps): Router { const router = Router(); - const { authService, configManager, auditService, alertEngine, stepUpGuard = requireStepUp } = - deps; + const { authService, configManager, auditService, alertEngine } = deps; router.get('/', requireAuth(authService), (req, res) => { const limit = typeof req.query.limit === 'string' ? Number(req.query.limit) : 50; @@ -33,48 +30,41 @@ export function createAlertsRouter(deps: AlertsRouterDeps): Router { }); }); - router.put( - '/config', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - (req, res) => { - try { - const parsed = AlertsFileSchema.parse({ version: 1, ...(req.body ?? {}) }); - const saved = configManager.saveConfigText( - 'alerts.json', - JSON.stringify(parsed, null, 2), - 'ui', - 'Updated alerts configuration via UI', - ); - auditService.log({ - action: 'alerts.config_update', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: 'alerts.json', - status: 'ok', - }); - res.json({ alertsConfig: saved.config, warnings: saved.warnings }); - } catch (err) { - if (err instanceof ZodError) { - res.status(400).json({ - error: 'VALIDATION_ERROR', - message: 'Invalid alerts configuration', - issues: err.issues.map((i) => ({ - path: i.path.join('.') || '(root)', - message: i.message, - })), - }); - return; - } + router.put('/config', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { + try { + const parsed = AlertsFileSchema.parse({ version: 1, ...(req.body ?? {}) }); + const saved = configManager.saveConfigText( + 'alerts.json', + JSON.stringify(parsed, null, 2), + 'ui', + 'Updated alerts configuration via UI', + ); + auditService.log({ + action: 'alerts.config_update', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: 'alerts.json', + status: 'ok', + }); + res.json({ alertsConfig: saved.config, warnings: saved.warnings }); + } catch (err) { + if (err instanceof ZodError) { res.status(400).json({ - error: 'ALERTS_SAVE_ERROR', - message: err instanceof Error ? err.message : 'Unable to save alerts configuration', + error: 'VALIDATION_ERROR', + message: 'Invalid alerts configuration', + issues: err.issues.map((i) => ({ + path: i.path.join('.') || '(root)', + message: i.message, + })), }); + return; } - }, - ); + res.status(400).json({ + error: 'ALERTS_SAVE_ERROR', + message: err instanceof Error ? err.message : 'Unable to save alerts configuration', + }); + } + }); router.post( '/silences', @@ -132,7 +122,6 @@ export function createAlertsRouter(deps: AlertsRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - stepUpGuard, async (req, res) => { const id = String(req.params.id ?? ''); try { diff --git a/src/server/api/routes/audit.routes.ts b/src/server/api/routes/audit.routes.ts index 1194bcc..48b66a5 100644 --- a/src/server/api/routes/audit.routes.ts +++ b/src/server/api/routes/audit.routes.ts @@ -1,33 +1,8 @@ import { Router } from 'express'; -import { z } from 'zod'; -import type { AuditListOptions, AuditService } from '../../security/audit.js'; +import type { AuditService } from '../../security/audit.js'; import type { AuthService } from '../../security/auth.js'; import { requireAuth } from '../../security/guards.js'; -const AuditQuerySchema = z.object({ - limit: z.coerce.number().int().min(1).max(200).optional(), - offset: z.coerce.number().int().min(0).optional(), - action: z.string().trim().min(1).max(128).optional(), - actionPrefix: z.string().trim().min(1).max(64).optional(), - status: z.enum(['ok', 'denied', 'error']).optional(), - ip: z.string().trim().min(1).max(64).optional(), - target: z.string().trim().min(1).max(128).optional(), - q: z.string().trim().min(1).max(128).optional(), - from: z.coerce.number().int().min(0).optional(), - to: z.coerce.number().int().min(0).optional(), - format: z.enum(['csv', 'ndjson']).optional(), -}); - -function pickFilterOptions(raw: Record): AuditListOptions & { format?: 'csv' | 'ndjson' } { - const cleaned: Record = {}; - for (const [k, v] of Object.entries(raw)) { - if (typeof v === 'string' && v.trim() === '') continue; - cleaned[k] = v; - } - const parsed = AuditQuerySchema.safeParse(cleaned); - return parsed.success ? parsed.data : {}; -} - export function createAuditRouter( authService: AuthService, auditService: AuditService, @@ -35,37 +10,20 @@ export function createAuditRouter( const router = Router(); router.get('/', requireAuth(authService), (req, res) => { - const opts = pickFilterOptions(req.query as Record); - const result = auditService.list(opts); - res.json({ - ...result, - actions: auditService.listActions(), - }); - }); + const limit = req.query.limit ? Number(req.query.limit) : 50; + const offset = req.query.offset ? Number(req.query.offset) : 0; + const action = + typeof req.query.action === 'string' && req.query.action.trim() + ? req.query.action.trim() + : undefined; - router.get('/export', requireAuth(authService), (req, res) => { - const opts = pickFilterOptions(req.query as Record); - const format = opts.format ?? 'ndjson'; - const content = auditService.exportRecords(opts, format); - - auditService.log({ - action: 'audit.export', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: format, - status: 'ok', - }); - - res.setHeader('Cache-Control', 'no-store'); - res.setHeader( - 'Content-Type', - format === 'csv' ? 'text/csv; charset=utf-8' : 'application/x-ndjson; charset=utf-8', + res.json( + auditService.list({ + limit: Number.isFinite(limit) ? limit : 50, + offset: Number.isFinite(offset) ? offset : 0, + action, + }), ); - res.setHeader( - 'Content-Disposition', - `attachment; filename="gcoordinator-audit-export.${format === 'csv' ? 'csv' : 'ndjson'}"`, - ); - res.send(content); }); return router; diff --git a/src/server/api/routes/auth.routes.ts b/src/server/api/routes/auth.routes.ts index 44dc5bf..4f9fe52 100644 --- a/src/server/api/routes/auth.routes.ts +++ b/src/server/api/routes/auth.routes.ts @@ -1,19 +1,13 @@ -import { Router, type NextFunction, type Request, type Response } from 'express'; +import { Router, type Request, type Response } from 'express'; import { z } from 'zod'; import type { AuthenticationResponseJSON, RegistrationResponseJSON, } from '@simplewebauthn/server'; -import { SecuritySettingsSchema } from '../../../shared/schemas/settings.schema.js'; import type { ConfigManager } from '../../config/config-manager.js'; import type { AuditService } from '../../security/audit.js'; +import { SESSION_COOKIE_NAME, type AuthService } from '../../security/auth.js'; import { - AuthOverloadError, - SESSION_COOKIE_NAME, - type AuthService, -} from '../../security/auth.js'; -import { - asyncHandler, createStepUpGuard, enforceSafeMode, extractCookies, @@ -34,8 +28,6 @@ export interface AuthRouterDeps { recoveryStore: EmergencyRecoveryService; rateLimiter: RateLimiter; trustCloudflare: boolean; - webauthnRpId?: string; - webauthnOrigins?: string[]; } function isSecureCookie(req: Request, trustCloudflare: boolean): boolean { @@ -52,10 +44,9 @@ function setAuthCookies( sessionToken: string, csrfToken: string, trustCloudflare: boolean, - sessionTtlHours = 168, ): void { const secure = isSecureCookie(req, trustCloudflare); - const maxAge = Math.max(1, sessionTtlHours) * 60 * 60 * 1000; + const maxAge = 7 * 24 * 60 * 60 * 1000; res.cookie(SESSION_COOKIE_NAME, sessionToken, { httpOnly: true, sameSite: 'strict', @@ -85,8 +76,6 @@ class WebAuthnRpError extends Error { function resolveWebAuthnRp( req: Request, trustCloudflare: boolean, - configuredRpId?: string, - configuredOrigins?: string[], ): { rpID: string; expectedOrigin: string } { const originHeader = typeof req.headers.origin === 'string' && req.headers.origin.trim() @@ -103,35 +92,10 @@ function resolveWebAuthnRp( throw new WebAuthnRpError('Invalid Origin header for WebAuthn request'); } - if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { - throw new WebAuthnRpError('WebAuthn Origin must use http or https'); - } - - if (configuredOrigins && configuredOrigins.length > 0) { - if (!configuredOrigins.includes(parsed.origin)) { - throw new WebAuthnRpError( - `Origin "${parsed.origin}" is not listed in GCOORD_WEBAUTHN_ORIGINS`, - ); - } - } else if (originHeader && parsed.host !== hostHeader) { - throw new WebAuthnRpError('WebAuthn Origin host does not match Request Host'); - } - - const hostname = parsed.hostname; - if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname) || hostname.includes(':')) { + const rpID = parsed.hostname; + if (/^\d+\.\d+\.\d+\.\d+$/.test(rpID) || rpID.includes(':')) { throw new WebAuthnRpError( - `WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${hostname}" is rejected by browsers).`, - ); - } - - const rpID = configuredRpId || hostname; - if ( - configuredRpId && - hostname !== configuredRpId && - !hostname.endsWith(`.${configuredRpId}`) - ) { - throw new WebAuthnRpError( - `Hostname "${hostname}" does not match GCOORD_WEBAUTHN_RP_ID "${configuredRpId}"`, + `WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${rpID}" is rejected by browsers).`, ); } @@ -151,8 +115,6 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { recoveryStore, rateLimiter, trustCloudflare, - webauthnRpId, - webauthnOrigins, } = deps; const stepUpGuard = createStepUpGuard( @@ -171,16 +133,11 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { res.json({ bootstrapped, authenticated: false, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, defaultMobileSafeMode: settings.defaultMobileSafeMode, theme: settings.theme, - authRequirements: { - requireTotpOnLogin: authRequirements.requireTotpOnLogin, - passwordMode: authRequirements.passwordMode, - passwordCount: authRequirements.passwordCount, - totpMode: authRequirements.totpMode, - totpCount: authRequirements.totpCount, - passkeyCount: authRequirements.passkeyCount, - }, + authRequirements, }); return; } @@ -191,231 +148,196 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { safeMode: session.safeMode, elevatedUntil: session.elevatedUntil, vaultState: vaultService.state, - sealState: vaultService.sealState, vaultRuntimeReady: vaultService.isRuntimeReady, isPanicLocked: vaultService.isPanicLocked, defaultMobileSafeMode: settings.defaultMobileSafeMode, theme: settings.theme, security: settings.security, - runtime: settings.runtime, authRequirements, }); }); - router.get( - '/bootstrap', - asyncHandler(async (req, res) => { - if (authService.isBootstrapped()) { - res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); - return; - } - const rawUser = - typeof req.query.username === 'string' && req.query.username.trim() - ? req.query.username.trim().slice(0, 64) - : 'admin'; - const data = await authService.beginBootstrap(rawUser); - res.json(data); - }), - ); + router.get('/bootstrap', async (req, res) => { + if (authService.isBootstrapped()) { + res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); + return; + } + const username = + typeof req.query.username === 'string' && req.query.username.trim() + ? req.query.username.trim() + : 'admin'; + const data = await authService.beginBootstrap(username); + res.json(data); + }); - router.post( - '/bootstrap', - asyncHandler(async (req, res) => { - if (authService.isBootstrapped()) { - res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('bootstrap', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } + router.post('/bootstrap', async (req, res) => { + if (authService.isBootstrapped()) { + res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('bootstrap', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } - const bodySchema = z.object({ - username: z.string().trim().min(2).max(64).default('admin'), - password: z.string().min(10).max(256), - totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'), - secretBase32: z.string().max(128).optional(), - bootstrapToken: z.string().min(16).max(128).optional(), - initialSafeMode: z.boolean().optional(), - securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(), - }); - const parsed = bodySchema.safeParse(req.body); - if (!parsed.success) { - rateLimiter.recordFailure('bootstrap', ip); - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } + const bodySchema = z.object({ + username: z.string().min(2).max(64).default('admin'), + password: z.string().min(10).max(256), + totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'), + secretBase32: z.string().optional(), + initialSafeMode: z.boolean().optional(), + securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(), + }); + const parsed = bodySchema.safeParse(req.body); + if (!parsed.success) { + rateLimiter.recordFailure('bootstrap', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } - try { - const result = await authService.completeBootstrap({ - ...parsed.data, - ip, - userAgent: String(req.headers['user-agent'] ?? 'unknown'), - }); - - if (parsed.data.securityPreset) { - const cur = configManager.getSettings(); - const presetSecurity = - parsed.data.securityPreset === 'relaxed' + try { + if (parsed.data.securityPreset) { + const cur = configManager.getSettings(); + const presetSecurity = + parsed.data.securityPreset === 'relaxed' + ? { + ...cur.security, + requireTotpOnLogin: false, + stepUpPolicy: 'off' as const, + stepUpMethod: 'password' as const, + elevateOnLogin: true, + keepElevationOnSafeMode: true, + } + : parsed.data.securityPreset === 'strict' ? { ...cur.security, - requireTotpOnLogin: false, - stepUpPolicy: 'off' as const, - stepUpMethod: 'password' as const, - elevateOnLogin: true, - keepElevationOnSafeMode: true, + requireTotpOnLogin: true, + stepUpPolicy: '5m' as const, + stepUpMethod: 'totp' as const, + elevateOnLogin: false, + keepElevationOnSafeMode: false, } - : parsed.data.securityPreset === 'strict' - ? { - ...cur.security, - requireTotpOnLogin: true, - stepUpPolicy: '5m' as const, - stepUpMethod: 'totp' as const, - elevateOnLogin: false, - keepElevationOnSafeMode: false, - } - : cur.security; + : cur.security; - configManager.saveConfigText( - 'settings.json', - JSON.stringify({ ...cur, security: presetSecurity }, null, 2), - 'ui', - `Bootstrap preset: ${parsed.data.securityPreset}`, - ); - authService.syncRecovery({ - newRecoveryCodes: result.recoveryCodes, - snapshotReason: 'bootstrap-preset', - }); - } - - const ttlHours = configManager.getSettings().security.sessionTtlHours; - rateLimiter.recordSuccess('bootstrap', ip); - setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); - auditService.log({ - action: 'auth.bootstrap', - actorIp: ip, - sessionIdHash: result.session.idHash, - target: parsed.data.username, - status: 'ok', - }); - res.status(201).json({ - authenticated: true, - csrfToken: result.csrfToken, - recoveryCodes: result.recoveryCodes, - safeMode: result.session.safeMode, - elevatedUntil: result.session.elevatedUntil, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, - }); - } catch (err) { - if (err instanceof AuthOverloadError) throw err; - rateLimiter.recordFailure('bootstrap', ip); - auditService.log({ - action: 'auth.bootstrap', - actorIp: ip, - status: 'error', - details: err instanceof Error ? err.message : 'Bootstrap failed', - }); - res.status(400).json({ - error: 'BOOTSTRAP_FAILED', - message: err instanceof Error ? err.message : 'Bootstrap failed', - }); - } - }), - ); - - router.post( - '/login', - asyncHandler(async (req, res) => { - if (!authService.isBootstrapped()) { - res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('login', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - if (!rateLimiter.acquireInFlight('login', ip, 2)) { - res.setHeader('Retry-After', '2'); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: 2 }); - return; + configManager.saveConfigText( + 'settings.json', + JSON.stringify({ ...cur, security: presetSecurity }, null, 2), + 'ui', + `Bootstrap preset: ${parsed.data.securityPreset}`, + ); } - try { - const bodySchema = z - .object({ - username: z.string().trim().min(1).max(64), - password: z.string().min(1).max(256).optional(), - passwords: z.array(z.string().min(1).max(256)).max(16).optional(), - code: z.string().max(64).optional(), - codes: z.array(z.string().max(64)).max(16).optional(), - initialSafeMode: z.boolean().optional(), - }) - .refine( - (b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)), - 'Password is required', - ); - const parsed = bodySchema.safeParse(req.body); - if (!parsed.success) { - rateLimiter.recordFailure('login', ip); - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } + const result = await authService.completeBootstrap({ + ...parsed.data, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + }); + rateLimiter.recordSuccess('bootstrap', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); + auditService.log({ + action: 'auth.bootstrap', + actorIp: ip, + sessionIdHash: result.session.idHash, + target: parsed.data.username, + status: 'ok', + }); + res.status(201).json({ + authenticated: true, + csrfToken: result.csrfToken, + recoveryCodes: result.recoveryCodes, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + }); + } catch (err) { + rateLimiter.recordFailure('bootstrap', ip); + auditService.log({ + action: 'auth.bootstrap', + actorIp: ip, + status: 'error', + details: err instanceof Error ? err.message : 'Bootstrap failed', + }); + res.status(400).json({ + error: 'BOOTSTRAP_FAILED', + message: err instanceof Error ? err.message : 'Bootstrap failed', + }); + } + }); - const result = await authService.login({ - ...parsed.data, - ip, - userAgent: String(req.headers['user-agent'] ?? 'unknown'), - }); + router.post('/login', async (req, res) => { + if (!authService.isBootstrapped()) { + res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('login', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } - if (!result) { - const failState = rateLimiter.recordFailure('login', ip); - if (failState.lockedUntil > 0 || failState.globalTriggered) { - authService.emitSecurityEvent('auth.lockout', ip, { - failures: failState.failures, - globalTriggered: failState.globalTriggered, - }); - } - auditService.log({ - action: 'auth.login', - actorIp: ip, - target: parsed.data.username, - status: 'denied', - }); - res.status(401).json({ error: 'INVALID_CREDENTIALS' }); - return; - } + const bodySchema = z + .object({ + username: z.string().min(1).optional(), + password: z.string().min(1).optional(), + passwords: z.array(z.string().min(1)).optional(), + code: z.string().max(32).optional(), + codes: z.array(z.string().max(32)).optional(), + initialSafeMode: z.boolean().optional(), + }) + .refine( + (b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)), + 'Password is required', + ); + const parsed = bodySchema.safeParse(req.body); + if (!parsed.success) { + rateLimiter.recordFailure('login', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } - const ttlHours = configManager.getSettings().security.sessionTtlHours; - rateLimiter.recordSuccess('login', ip); - setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); - auditService.log({ - action: 'auth.login', - actorIp: ip, - sessionIdHash: result.session.idHash, - target: parsed.data.username, - status: 'ok', - }); + const result = await authService.login({ + ...parsed.data, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + }); - res.json({ - authenticated: true, - csrfToken: result.csrfToken, - safeMode: result.session.safeMode, - elevatedUntil: result.session.elevatedUntil, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, - }); - } finally { - rateLimiter.releaseInFlight('login', ip); - } - }), - ); + if (!result) { + rateLimiter.recordFailure('login', ip); + auditService.log({ + action: 'auth.login', + actorIp: ip, + target: parsed.data.username ?? 'admin', + status: 'denied', + }); + res.status(401).json({ error: 'INVALID_CREDENTIALS' }); + return; + } + + rateLimiter.recordSuccess('login', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); + auditService.log({ + action: 'auth.login', + actorIp: ip, + sessionIdHash: result.session.idHash, + target: parsed.data.username ?? 'admin', + status: 'ok', + }); + + res.json({ + authenticated: true, + csrfToken: result.csrfToken, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + }); + }); // Exempt from enforceSafeMode router.post('/logout', requireAuth(authService), requireCsrf, (req, res) => { @@ -461,7 +383,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - asyncHandler(async (req, res) => { + async (req, res) => { const ip = req.clientIp ?? 'unknown'; const rate = rateLimiter.check('step-up', ip); if (!rate.allowed) { @@ -472,10 +394,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { const parsed = z .object({ - code: z.string().max(64).optional(), - codes: z.array(z.string().max(64)).max(16).optional(), - password: z.string().max(256).optional(), - passwords: z.array(z.string().max(256)).max(16).optional(), + code: z.string().optional(), + codes: z.array(z.string()).optional(), + password: z.string().optional(), + passwords: z.array(z.string()).optional(), }) .safeParse(req.body ?? {}); if (!parsed.success) { @@ -485,12 +407,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { const outcome = await authService.stepUp(req.authSession!.idHash, parsed.data); if (!outcome.ok) { - const failState = rateLimiter.recordFailure('step-up', ip); - if (failState.lockedUntil > 0) { - authService.emitSecurityEvent('auth.step_up_lockout', ip, { - failures: failState.failures, - }); - } + rateLimiter.recordFailure('step-up', ip); auditService.log({ action: 'auth.step_up', actorIp: ip, @@ -513,7 +430,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { status: 'ok', }); res.json({ elevatedUntil: outcome.elevatedUntil }); - }), + }, ); router.post('/drop-elevation', requireAuth(authService), requireCsrf, (req, res) => { @@ -710,7 +627,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - asyncHandler(async (req, res) => { + async (req, res) => { const parsed = z .object({ label: z.string().min(1).max(64).default('Passkey') }) .safeParse(req.body ?? {}); @@ -719,7 +636,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { return; } try { - const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); + const rp = resolveWebAuthnRp(req, trustCloudflare); const data = await authService.beginPasskeyRegistration({ label: parsed.data.label, ...rp, @@ -731,7 +648,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { message: err instanceof Error ? err.message : 'Unable to start passkey registration', }); } - }), + }, ); router.post( @@ -740,10 +657,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - asyncHandler(async (req, res) => { + async (req, res) => { const parsed = z .object({ - challengeId: z.string().min(1).max(128), + challengeId: z.string().min(1), response: z.record(z.unknown()), }) .safeParse(req.body ?? {}); @@ -770,7 +687,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { message: err instanceof Error ? err.message : 'Unable to verify passkey registration', }); } - }), + }, ); router.delete( @@ -804,115 +721,102 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { }, ); - router.post( - '/passkeys/login/options', - asyncHandler(async (req, res) => { - if (!authService.isBootstrapped()) { - res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('login', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - try { - const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); - const data = await authService.beginPasskeyAuthentication({ - purpose: 'login', - ...rp, - }); - res.json(data); - } catch (err) { - res.status(400).json({ - error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_LOGIN_OPTIONS_FAILED', - message: err instanceof Error ? err.message : 'No passkeys available', - }); - } - }), - ); - - router.post( - '/passkeys/login/verify', - asyncHandler(async (req, res) => { - if (!authService.isBootstrapped()) { - res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('login', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - - const parsed = z - .object({ - challengeId: z.string().min(1).max(128), - response: z.record(z.unknown()), - initialSafeMode: z.boolean().optional(), - }) - .safeParse(req.body ?? {}); - if (!parsed.success) { - rateLimiter.recordFailure('login', ip); - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - - const result = await authService.loginWithPasskey({ - challengeId: parsed.data.challengeId, - response: parsed.data.response as unknown as AuthenticationResponseJSON, - ip, - userAgent: String(req.headers['user-agent'] ?? 'unknown'), - initialSafeMode: parsed.data.initialSafeMode, + router.post('/passkeys/login/options', async (req, res) => { + if (!authService.isBootstrapped()) { + res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('login', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + try { + const rp = resolveWebAuthnRp(req, trustCloudflare); + const data = await authService.beginPasskeyAuthentication({ + purpose: 'login', + ...rp, }); - if (!result) { - const failState = rateLimiter.recordFailure('login', ip); - if (failState.lockedUntil > 0 || failState.globalTriggered) { - authService.emitSecurityEvent('auth.lockout', ip, { - failures: failState.failures, - globalTriggered: failState.globalTriggered, - }); - } - auditService.log({ - action: 'auth.passkey_login', - actorIp: ip, - status: 'denied', - }); - res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' }); - return; - } + res.json(data); + } catch (err) { + res.status(400).json({ + error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_LOGIN_OPTIONS_FAILED', + message: err instanceof Error ? err.message : 'No passkeys available', + }); + } + }); - const ttlHours = configManager.getSettings().security.sessionTtlHours; - rateLimiter.recordSuccess('login', ip); - setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); + router.post('/passkeys/login/verify', async (req, res) => { + if (!authService.isBootstrapped()) { + res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('login', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + + const parsed = z + .object({ + challengeId: z.string().min(1), + response: z.record(z.unknown()), + initialSafeMode: z.boolean().optional(), + }) + .safeParse(req.body ?? {}); + if (!parsed.success) { + rateLimiter.recordFailure('login', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + const result = await authService.loginWithPasskey({ + challengeId: parsed.data.challengeId, + response: parsed.data.response as unknown as AuthenticationResponseJSON, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + initialSafeMode: parsed.data.initialSafeMode, + }); + if (!result) { + rateLimiter.recordFailure('login', ip); auditService.log({ action: 'auth.passkey_login', actorIp: ip, - sessionIdHash: result.session.idHash, - status: 'ok', + status: 'denied', }); + res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' }); + return; + } - res.json({ - authenticated: true, - csrfToken: result.csrfToken, - safeMode: result.session.safeMode, - elevatedUntil: result.session.elevatedUntil, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, - }); - }), - ); + rateLimiter.recordSuccess('login', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); + auditService.log({ + action: 'auth.passkey_login', + actorIp: ip, + sessionIdHash: result.session.idHash, + status: 'ok', + }); + + res.json({ + authenticated: true, + csrfToken: result.csrfToken, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + }); + }); router.post( '/passkeys/step-up/options', requireAuth(authService), requireCsrf, enforceSafeMode, - asyncHandler(async (req, res) => { + async (req, res) => { const ip = req.clientIp ?? 'unknown'; const rate = rateLimiter.check('step-up', ip); if (!rate.allowed) { @@ -921,7 +825,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { return; } try { - const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); + const rp = resolveWebAuthnRp(req, trustCloudflare); const data = await authService.beginPasskeyAuthentication({ purpose: 'stepup', sessionIdHash: req.authSession!.idHash, @@ -934,7 +838,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { message: err instanceof Error ? err.message : 'Unable to start passkey verification', }); } - }), + }, ); router.post( @@ -942,7 +846,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - asyncHandler(async (req, res) => { + async (req, res) => { const ip = req.clientIp ?? 'unknown'; const rate = rateLimiter.check('step-up', ip); if (!rate.allowed) { @@ -952,7 +856,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { } const parsed = z .object({ - challengeId: z.string().min(1).max(128), + challengeId: z.string().min(1), response: z.record(z.unknown()), }) .safeParse(req.body ?? {}); @@ -990,46 +894,6 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { status: 'ok', }); res.json({ elevatedUntil: outcome.elevatedUntil }); - }), - ); - - router.put( - '/security-policy', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - (req, res) => { - const cur = configManager.getSettings(); - const bodyObj = - typeof req.body === 'object' && req.body !== null && !Array.isArray(req.body) - ? (req.body as Record) - : null; - if (!bodyObj) { - res.status(400).json({ error: 'VALIDATION_ERROR', message: 'Expected JSON object' }); - return; - } - const parsed = SecuritySettingsSchema.safeParse({ - ...cur.security, - ...bodyObj, - }); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - configManager.saveConfigText( - 'settings.json', - JSON.stringify({ ...cur, security: parsed.data }, null, 2), - 'ui', - 'Updated security policy via /api/auth/security-policy', - ); - auditService.log({ - action: 'auth.security_policy_update', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - status: 'ok', - }); - res.json({ security: parsed.data }); }, ); @@ -1058,11 +922,9 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { }, ); - router.post( + router.get( '/recovery-backup/export', requireAuth(authService), - requireCsrf, - enforceSafeMode, stepUpGuard, (req, res) => { const settings = configManager.getSettings(); @@ -1170,14 +1032,5 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { }, ); - router.use((err: unknown, _req: Request, res: Response, next: NextFunction) => { - if (err instanceof AuthOverloadError) { - res.setHeader('Retry-After', '2'); - res.status(503).json({ error: err.code, message: err.message }); - return; - } - next(err); - }); - return router; } diff --git a/src/server/api/routes/backup.routes.ts b/src/server/api/routes/backup.routes.ts index a4ba2b1..70aff8a 100644 --- a/src/server/api/routes/backup.routes.ts +++ b/src/server/api/routes/backup.routes.ts @@ -1,21 +1,17 @@ import type Database from 'better-sqlite3'; -import { Router, type NextFunction, type Request, type RequestHandler, type Response } from 'express'; +import { Router, type RequestHandler } from 'express'; import { z } from 'zod'; import type { ConfigManager } from '../../config/config-manager.js'; -import type { RuntimeLimits } from '../../config/runtime-limits.js'; import type { AuditService } from '../../security/audit.js'; import type { AuthService } from '../../security/auth.js'; import { - BackupBusyError, - createBackupBundleAsync, - restoreBackupBundleAsync, - verifyBackupSummaryOnlyAsync, + createBackupBundle, + restoreBackupBundle, + verifyBackupSummaryOnly, type BackupInnerPayload, type BackupVerificationSummary, } from '../../security/backup.js'; -import type { BackupScheduler } from '../../security/backup-scheduler.js'; import { - asyncHandler, enforceSafeMode, requireAuth, requireCsrf, @@ -30,8 +26,6 @@ export interface BackupRouterDeps { configManager: ConfigManager; auditService: AuditService; stepUpGuard: RequestHandler; - getRuntimeLimits?: () => RuntimeLimits; - backupScheduler?: BackupScheduler; onRestored: (info: { summary: BackupVerificationSummary; inner: BackupInnerPayload; @@ -60,8 +54,6 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { configManager, auditService, stepUpGuard, - getRuntimeLimits, - backupScheduler, onRestored, } = deps; @@ -71,7 +63,7 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - asyncHandler(async (req, res) => { + (req, res) => { const parsed = ExportBackupBodySchema.safeParse(req.body ?? {}); if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); @@ -89,13 +81,11 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { } try { - const limits = getRuntimeLimits?.(); - const result = await createBackupBundleAsync({ + const result = createBackupBundle({ dataDir, db, masterKey, passphrase, - scryptConcurrency: limits?.scryptConcurrency, }); const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); const filename = `gcoordinator-backup-${stamp}.gcoord.enc`; @@ -119,73 +109,38 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { summary: result.summary, }); } catch (err) { - if (err instanceof BackupBusyError) throw err; res.status(400).json({ error: 'BACKUP_EXPORT_ERROR', message: err instanceof Error ? err.message : 'Unable to create backup bundle', }); } - }), + }, ); - // Read-only verification: exempt from enforceSafeMode, still requires step-up and writes audit entry - router.post( - '/verify', - requireAuth(authService), - requireCsrf, - stepUpGuard, - asyncHandler(async (req, res) => { - const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } + // Read-only verification: exempt from enforceSafeMode + router.post('/verify', requireAuth(authService), requireCsrf, (req, res) => { + const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } - const limits = getRuntimeLimits?.(); - const maxBodyBytes = limits?.backupMaxBodyBytes ?? 16 * 1024 * 1024; + try { const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64'); - if (rawBuf.length > maxBodyBytes) { - res.status(413).json({ - error: 'PAYLOAD_TOO_LARGE', - message: `Backup bundle exceeds limit (${maxBodyBytes} bytes)`, - }); - return; - } - - try { - const summary = await verifyBackupSummaryOnlyAsync(rawBuf, { - masterKey: - parsed.data.masterKey?.trim() || vaultService.exportMasterKeyHex() || undefined, - passphrase: parsed.data.passphrase?.trim() || undefined, - vaultMasterKey: parsed.data.vaultMasterKey?.trim() || undefined, - scryptConcurrency: limits?.scryptConcurrency, - maxGunzipBytes: limits?.backupMaxGunzipBytes, - }); - auditService.log({ - action: 'backup.verify', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: summary.kdf, - status: 'ok', - details: { configFileCount: summary.configFileCount, vaultVerified: summary.vaultVerified }, - }); - res.json({ summary }); - } catch (err) { - if (err instanceof BackupBusyError) throw err; - auditService.log({ - action: 'backup.verify', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - status: 'error', - details: { message: err instanceof Error ? err.message : 'Verification failed' }, - }); - res.status(400).json({ - error: 'BACKUP_INVALID', - message: err instanceof Error ? err.message : 'Backup verification failed', - }); - } - }), - ); + const summary = verifyBackupSummaryOnly(rawBuf, { + masterKey: + parsed.data.masterKey?.trim() || vaultService.exportMasterKeyHex() || undefined, + passphrase: parsed.data.passphrase?.trim() || undefined, + vaultMasterKey: parsed.data.vaultMasterKey?.trim() || undefined, + }); + res.json({ summary }); + } catch (err) { + res.status(400).json({ + error: 'BACKUP_INVALID', + message: err instanceof Error ? err.message : 'Backup verification failed', + }); + } + }); router.post( '/restore', @@ -193,24 +148,14 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - asyncHandler(async (req, res) => { + async (req, res) => { const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {}); if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); return; } - const limits = getRuntimeLimits?.(); - const maxBodyBytes = limits?.backupMaxBodyBytes ?? 16 * 1024 * 1024; const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64'); - if (rawBuf.length > maxBodyBytes) { - res.status(413).json({ - error: 'PAYLOAD_TOO_LARGE', - message: `Backup bundle exceeds limit (${maxBodyBytes} bytes)`, - }); - return; - } - const passphrase = parsed.data.passphrase?.trim() || undefined; const runtimeKey = vaultService.exportMasterKeyHex() ?? undefined; const masterKey = parsed.data.masterKey?.trim() || runtimeKey; @@ -218,14 +163,12 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { const wasWatching = await configManager.pauseWatcher(); try { - const restored = await restoreBackupBundleAsync(rawBuf, { + const restored = restoreBackupBundle(rawBuf, { dataDir, db, masterKey, passphrase, vaultMasterKey, - scryptConcurrency: limits?.scryptConcurrency, - maxGunzipBytes: limits?.backupMaxGunzipBytes, }); await onRestored({ @@ -249,7 +192,6 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { res.json({ restored: true, summary: restored.summary }); } catch (err) { - if (err instanceof BackupBusyError) throw err; auditService.log({ action: 'backup.restore', actorIp: req.clientIp ?? 'unknown', @@ -267,44 +209,8 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { await configManager.resumeWatcher(); } } - }), + }, ); - router.get('/schedule', requireAuth(authService), (_req, res) => { - if (!backupScheduler) { - res.status(404).json({ error: 'SCHEDULER_UNAVAILABLE' }); - return; - } - res.json({ schedule: backupScheduler.getStatus() }); - }); - - router.post( - '/schedule/run', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - asyncHandler(async (_req, res) => { - if (!backupScheduler) { - res.status(404).json({ error: 'SCHEDULER_UNAVAILABLE' }); - return; - } - const outcome = await backupScheduler.runNow('manual'); - res.status(outcome.ok ? 200 : 400).json({ - ...outcome, - schedule: backupScheduler.getStatus(), - }); - }), - ); - - router.use((err: unknown, _req: Request, res: Response, next: NextFunction) => { - if (err instanceof BackupBusyError) { - res.setHeader('Retry-After', '2'); - res.status(503).json({ error: err.code, message: err.message }); - return; - } - next(err); - }); - return router; } diff --git a/src/server/api/routes/config.routes.ts b/src/server/api/routes/config.routes.ts index b9c6eef..7bcde14 100644 --- a/src/server/api/routes/config.routes.ts +++ b/src/server/api/routes/config.routes.ts @@ -1,36 +1,23 @@ -import crypto from 'node:crypto'; -import { Router, type RequestHandler } from 'express'; +import { Router } from 'express'; import { ZodError, z } from 'zod'; import type { ConfigManager } from '../../config/config-manager.js'; import type { AuditService } from '../../security/audit.js'; -import { sha256Hex, type AuthService } from '../../security/auth.js'; +import type { AuthService } from '../../security/auth.js'; import { enforceSafeMode, requireAuth, requireCsrf, - requireStepUp, } from '../../security/guards.js'; export interface ConfigRouterDeps { authService: AuthService; configManager: ConfigManager; auditService: AuditService; - stepUpGuard?: RequestHandler; -} - -function isStepUpSensitiveConfigPath(rawPath: string): boolean { - const norm = rawPath.replace(/\\/g, '/').replace(/^\/+/, ''); - return norm === 'settings.json' || norm === 'alerts.json' || norm.startsWith('servers/'); } export function createConfigRouter(deps: ConfigRouterDeps): Router { const router = Router(); - const { - authService, - configManager, - auditService, - stepUpGuard = requireStepUp, - } = deps; + const { authService, configManager, auditService } = deps; router.get('/overview', requireAuth(authService), (_req, res) => { res.json({ @@ -76,46 +63,38 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { return; } - const executeSave = () => { - try { - const saved = configManager.saveConfigText( - parsed.data.path, - parsed.data.content, - 'ui', - parsed.data.summary, - ); - auditService.log({ - action: 'config.save', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: saved.filePath, - status: 'ok', - }); - res.json(saved); - } catch (err) { - if (err instanceof ZodError) { - res.status(400).json({ - error: 'CONFIG_SCHEMA_ERROR', - message: 'Schema validation failed', - issues: err.issues.map((i) => ({ - path: i.path.join('.') || '(root)', - message: i.message, - })), - }); - return; - } + try { + const saved = configManager.saveConfigText( + parsed.data.path, + parsed.data.content, + 'ui', + parsed.data.summary, + ); + auditService.log({ + action: 'config.save', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: saved.filePath, + status: 'ok', + }); + res.json(saved); + } catch (err) { + if (err instanceof ZodError) { res.status(400).json({ - error: 'CONFIG_SAVE_ERROR', - message: err instanceof Error ? err.message : 'Unable to save config file', + error: 'CONFIG_SCHEMA_ERROR', + message: 'Schema validation failed', + issues: err.issues.map((i) => ({ + path: i.path.join('.') || '(root)', + message: i.message, + })), }); + return; } - }; - - if (isStepUpSensitiveConfigPath(parsed.data.path)) { - stepUpGuard(req, res, executeSave); - return; + res.status(400).json({ + error: 'CONFIG_SAVE_ERROR', + message: err instanceof Error ? err.message : 'Unable to save config file', + }); } - executeSave(); }); router.delete( @@ -129,34 +108,26 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { res.status(400).json({ error: 'MISSING_PATH' }); return; } - const executeDelete = () => { - try { - const deleted = configManager.deleteEntityFile(filePath); - if (!deleted) { - res.status(404).json({ error: 'CONFIG_NOT_FOUND' }); - return; - } - auditService.log({ - action: 'config.delete', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: filePath, - status: 'ok', - }); - res.json({ deleted: true }); - } catch (err) { - res.status(400).json({ - error: 'CONFIG_DELETE_ERROR', - message: err instanceof Error ? err.message : 'Unable to delete config file', - }); + try { + const deleted = configManager.deleteEntityFile(filePath); + if (!deleted) { + res.status(404).json({ error: 'CONFIG_NOT_FOUND' }); + return; } - }; - - if (isStepUpSensitiveConfigPath(filePath)) { - stepUpGuard(req, res, executeDelete); - return; + auditService.log({ + action: 'config.delete', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: filePath, + status: 'ok', + }); + res.json({ deleted: true }); + } catch (err) { + res.status(400).json({ + error: 'CONFIG_DELETE_ERROR', + message: err instanceof Error ? err.message : 'Unable to delete config file', + }); } - executeDelete(); }, ); @@ -203,83 +174,23 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { res.status(400).json({ error: 'INVALID_REVISION_ID' }); return; } - const rev = configManager.getRevision(id); - if (!rev) { + try { + const result = configManager.rollbackRevision(id); + auditService.log({ + action: 'config.rollback', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: result.filePath, + status: 'ok', + details: { revisionId: id }, + }); + res.json(result); + } catch (err) { res.status(400).json({ error: 'ROLLBACK_FAILED', - message: `Revision #${id} not found`, + message: err instanceof Error ? err.message : 'Rollback failed', }); - return; } - const executeRollback = () => { - try { - const result = configManager.rollbackRevision(id); - auditService.log({ - action: 'config.rollback', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: result.filePath, - status: 'ok', - details: { revisionId: id }, - }); - res.json(result); - } catch (err) { - res.status(400).json({ - error: 'ROLLBACK_FAILED', - message: err instanceof Error ? err.message : 'Rollback failed', - }); - } - }; - if (isStepUpSensitiveConfigPath(rev.filePath)) { - stepUpGuard(req, res, executeRollback); - return; - } - executeRollback(); - }, - ); - - router.post( - '/prometheus-token', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - (req, res) => { - const parsed = z - .object({ enable: z.boolean().optional() }) - .safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - const token = crypto.randomBytes(32).toString('base64url'); - const tokenHash = sha256Hex(token); - const next = structuredClone(configManager.getSettings()); - next.metrics.prometheusTokenHash = tokenHash; - if (parsed.data.enable !== undefined) { - next.metrics.prometheusEnabled = parsed.data.enable; - } else { - next.metrics.prometheusEnabled = true; - } - configManager.saveConfigText( - 'settings.json', - JSON.stringify(next, null, 2), - 'ui', - 'Rotate Prometheus metrics Bearer token', - ); - auditService.log({ - action: 'metrics.prometheus_token_rotate', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: 'settings.json', - status: 'ok', - details: { prometheusEnabled: next.metrics.prometheusEnabled }, - }); - res.json({ - token, - tokenHash, - prometheusEnabled: next.metrics.prometheusEnabled, - }); }, ); diff --git a/src/server/api/routes/servers.routes.ts b/src/server/api/routes/servers.routes.ts index b177717..f6e3d1d 100644 --- a/src/server/api/routes/servers.routes.ts +++ b/src/server/api/routes/servers.routes.ts @@ -19,7 +19,6 @@ import { import type { VaultService } from '../../security/vault.js'; import type { KeyManager } from '../../ssh/key-manager.js'; import type { KnownHostsService } from '../../ssh/known-hosts.js'; -import { parseOpenSshConfig } from '../../ssh/ssh-config-import.js'; import type { SSHPool } from '../../ssh/ssh-pool.js'; export interface ServersRouterDeps { @@ -79,173 +78,22 @@ export function createServersRouter(deps: ServersRouterDeps): Router { stepUpGuard, (req, res) => { const hostPort = typeof req.query.hostPort === 'string' ? req.query.hostPort : ''; - const algorithm = - typeof req.query.algorithm === 'string' && req.query.algorithm.trim() - ? req.query.algorithm.trim() - : undefined; if (!hostPort) { res.status(400).json({ error: 'MISSING_HOST_PORT' }); return; } - const deleted = knownHosts.deleteKnownHost(hostPort, algorithm); + const deleted = knownHosts.deleteKnownHost(hostPort); auditService.log({ action: 'ssh.known_host_delete', actorIp: req.clientIp ?? 'unknown', sessionIdHash: req.authSession!.idHash, - target: algorithm ? `${hostPort} (${algorithm})` : hostPort, + target: hostPort, status: deleted ? 'ok' : 'error', }); res.json({ deleted }); }, ); - const hasJumpCycle = ( - serverId: string, - jumpHostId: string | undefined, - extraMap?: Map, - ): boolean => { - const visited = new Set([serverId]); - let cur = jumpHostId; - while (cur) { - if (visited.has(cur)) return true; - visited.add(cur); - if (extraMap && extraMap.has(cur)) { - cur = extraMap.get(cur); - } else { - cur = configManager.getServer(cur)?.jumpHostId; - } - } - return false; - }; - - router.post( - '/test-connection', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - async (req, res) => { - const parsed = ServerConfigSchema.safeParse({ - ...(typeof req.body === 'object' && req.body !== null ? req.body : {}), - id: - typeof (req.body as { id?: unknown } | undefined)?.id === 'string' && - (req.body as { id: string }).id.trim() - ? (req.body as { id: string }).id.trim() - : 'test-probe-tmp', - name: - typeof (req.body as { name?: unknown } | undefined)?.name === 'string' && - (req.body as { name: string }).name.trim() - ? (req.body as { name: string }).name.trim() - : 'Test Connection', - }); - if (!parsed.success) { - res.status(400).json({ - error: 'VALIDATION_ERROR', - issues: parsed.error.issues, - }); - return; - } - if (hasJumpCycle(parsed.data.id, parsed.data.jumpHostId)) { - res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' }); - return; - } - const result = await sshPool.testConnection(parsed.data); - res.json(result); - }, - ); - - router.post( - '/import-ssh-config', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - (req, res) => { - const parsed = z - .object({ - configText: z.string().min(1).max(256_000), - defaultCredentialId: EntityIdSchema.optional(), - apply: z.boolean().default(false), - }) - .safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - - const preview = parseOpenSshConfig(parsed.data.configText); - if (!parsed.data.apply) { - res.json({ ...preview, createdIds: [] }); - return; - } - - if (!parsed.data.defaultCredentialId) { - res.status(400).json({ - error: 'MISSING_CREDENTIAL_ID', - message: 'Select a default SSH credential before importing hosts', - }); - return; - } - - const aliasToId = new Map(); - const existingServers = configManager.listServers(); - const takenIds = new Set(existingServers.map((s) => s.id)); - for (const s of existingServers) { - aliasToId.set(s.name, s.id); - aliasToId.set(s.id, s.id); - } - - const resolvedIds = new Map(); - for (const entry of preview.entries) { - let finalId = entry.id; - if (takenIds.has(finalId)) { - let n = 2; - while (takenIds.has(`${finalId.slice(0, 58)}-${n}`)) n++; - finalId = `${finalId.slice(0, 58)}-${n}`; - } - takenIds.add(finalId); - resolvedIds.set(entry.alias, finalId); - aliasToId.set(entry.alias, finalId); - } - - const createdIds: string[] = []; - for (const entry of preview.entries) { - const finalId = resolvedIds.get(entry.alias)!; - const jumpId = entry.jumpHostAlias - ? aliasToId.get(entry.jumpHostAlias) - : undefined; - const serverCfg = ServerConfigSchema.parse({ - id: finalId, - name: entry.name, - host: entry.host, - port: entry.port, - username: entry.username, - credentialId: parsed.data.defaultCredentialId, - ...(jumpId && jumpId !== finalId ? { jumpHostId: jumpId } : {}), - }); - configManager.saveConfigText( - `servers/${serverCfg.id}.json`, - JSON.stringify(serverCfg, null, 2), - 'ui', - `Imported from OpenSSH config (${entry.alias})`, - ); - createdIds.push(serverCfg.id); - } - - if (createdIds.length > 0) { - monitoringService.syncServers(); - auditService.log({ - action: 'server.import_ssh_config', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: createdIds.join(','), - status: 'ok', - }); - } - - res.status(201).json({ ...preview, createdIds }); - }, - ); - router.post( '/rotate-keys', requireAuth(authService), @@ -300,142 +148,113 @@ export function createServersRouter(deps: ServersRouterDeps): Router { }, ); - router.post( - '/', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - (req, res) => { - try { - const parsed = ServerConfigSchema.parse(req.body); - if (hasJumpCycle(parsed.id, parsed.jumpHostId)) { - res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' }); - return; - } - const saved = configManager.saveConfigText( - `servers/${parsed.id}.json`, - JSON.stringify(parsed, null, 2), - 'ui', - 'Registered server via UI', - ); - monitoringService.syncServers(); - auditService.log({ - action: 'server.create', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: parsed.id, - status: 'ok', - }); - res.status(201).json({ - server: saved.config, - warnings: saved.warnings, - }); - } catch (err) { - if (err instanceof ZodError) { - res.status(400).json({ - error: 'VALIDATION_ERROR', - message: 'Invalid server configuration', - issues: err.issues.map((i) => ({ - path: i.path.join('.') || '(root)', - message: i.message, - })), - }); - return; - } + router.post('/', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { + try { + const parsed = ServerConfigSchema.parse(req.body); + const saved = configManager.saveConfigText( + `servers/${parsed.id}.json`, + JSON.stringify(parsed, null, 2), + 'ui', + 'Registered server via UI', + ); + monitoringService.syncServers(); + auditService.log({ + action: 'server.create', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: parsed.id, + status: 'ok', + }); + res.status(201).json({ + server: saved.config, + warnings: saved.warnings, + }); + } catch (err) { + if (err instanceof ZodError) { res.status(400).json({ - error: 'SERVER_SAVE_ERROR', - message: err instanceof Error ? err.message : 'Unable to save server', + error: 'VALIDATION_ERROR', + message: 'Invalid server configuration', + issues: err.issues.map((i) => ({ + path: i.path.join('.') || '(root)', + message: i.message, + })), }); + return; } - }, - ); + res.status(400).json({ + error: 'SERVER_SAVE_ERROR', + message: err instanceof Error ? err.message : 'Unable to save server', + }); + } + }); - router.put( - '/:id', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - (req, res) => { - try { - const parsed = ServerConfigSchema.parse({ - ...(req.body ?? {}), - id: req.params.id, - }); - if (hasJumpCycle(parsed.id, parsed.jumpHostId)) { - res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' }); - return; - } - const saved = configManager.saveConfigText( - `servers/${parsed.id}.json`, - JSON.stringify(parsed, null, 2), - 'ui', - 'Updated server via UI', - ); - sshPool.closeServer(parsed.id); - monitoringService.syncServers(); - auditService.log({ - action: 'server.update', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: parsed.id, - status: 'ok', - }); - res.json({ server: saved.config, warnings: saved.warnings }); - } catch (err) { - if (err instanceof ZodError) { - res.status(400).json({ - error: 'VALIDATION_ERROR', - message: 'Invalid server configuration', - issues: err.issues.map((i) => ({ - path: i.path.join('.') || '(root)', - message: i.message, - })), - }); - return; - } + router.put('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { + try { + const parsed = ServerConfigSchema.parse({ + ...(req.body ?? {}), + id: req.params.id, + }); + const saved = configManager.saveConfigText( + `servers/${parsed.id}.json`, + JSON.stringify(parsed, null, 2), + 'ui', + 'Updated server via UI', + ); + sshPool.closeServer(parsed.id); + monitoringService.syncServers(); + auditService.log({ + action: 'server.update', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: parsed.id, + status: 'ok', + }); + res.json({ server: saved.config, warnings: saved.warnings }); + } catch (err) { + if (err instanceof ZodError) { res.status(400).json({ - error: 'SERVER_SAVE_ERROR', - message: err instanceof Error ? err.message : 'Unable to update server', + error: 'VALIDATION_ERROR', + message: 'Invalid server configuration', + issues: err.issues.map((i) => ({ + path: i.path.join('.') || '(root)', + message: i.message, + })), }); + return; } - }, - ); + res.status(400).json({ + error: 'SERVER_SAVE_ERROR', + message: err instanceof Error ? err.message : 'Unable to update server', + }); + } + }); - router.delete( - '/:id', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - (req, res) => { - const id = String(req.params.id ?? ''); - try { - const deleted = configManager.deleteEntityFile(`servers/${id}.json`); - if (!deleted) { - res.status(404).json({ error: 'SERVER_NOT_FOUND' }); - return; - } - sshPool.closeServer(id); - knownHosts.clearServerPending(id); - monitoringService.syncServers(); - auditService.log({ - action: 'server.delete', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: id, - status: 'ok', - }); - res.json({ deleted: true }); - } catch (err) { - res.status(400).json({ - error: 'SERVER_DELETE_ERROR', - message: err instanceof Error ? err.message : 'Unable to delete server', - }); + router.delete('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { + const id = String(req.params.id ?? ''); + try { + const deleted = configManager.deleteEntityFile(`servers/${id}.json`); + if (!deleted) { + res.status(404).json({ error: 'SERVER_NOT_FOUND' }); + return; } - }, - ); + sshPool.closeServer(id); + knownHosts.clearServerPending(id); + monitoringService.syncServers(); + auditService.log({ + action: 'server.delete', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: id, + status: 'ok', + }); + res.json({ deleted: true }); + } catch (err) { + res.status(400).json({ + error: 'SERVER_DELETE_ERROR', + message: err instanceof Error ? err.message : 'Unable to delete server', + }); + } + }); router.post( '/:id/reconnect', @@ -467,7 +286,6 @@ export function createServersRouter(deps: ServersRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - stepUpGuard, async (req, res) => { const id = String(req.params.id ?? ''); const parsed = z.object({ fingerprint: z.string().min(1) }).safeParse(req.body); @@ -548,140 +366,23 @@ export function createServersRouter(deps: ServersRouterDeps): Router { }); }); - router.get('/:id/inspect', requireAuth(authService), (req, res) => { + router.get('/:id/inspect', requireAuth(authService), async (req, res) => { const id = String(req.params.id ?? ''); if (!configManager.getServer(id)) { res.status(404).json({ error: 'SERVER_NOT_FOUND' }); return; } - const sort = String(req.query.sort ?? 'cpu') === 'mem' ? 'mem' : 'cpu'; - const useSudo = req.query.sudo === 'true' || req.query.sudo === '1'; - - const executeInspect = async () => { - try { - const result = await serverInspector.inspect(id, { sort, useSudo }); - res.json(result); - } catch (err) { - res.status(502).json({ - error: 'INSPECT_FAILED', - message: err instanceof Error ? err.message : 'Server inspection failed', - }); - } - }; - - if (useSudo) { - stepUpGuard(req, res, () => { - void executeInspect(); + try { + const result = await serverInspector.inspect(id); + res.json(result); + } catch (err) { + res.status(502).json({ + error: 'INSPECT_FAILED', + message: err instanceof Error ? err.message : 'Server inspection failed', }); - return; } - void executeInspect(); }); - router.post( - '/:id/processes/:pid/signal', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - async (req, res) => { - const id = String(req.params.id ?? ''); - if (!configManager.getServer(id)) { - res.status(404).json({ error: 'SERVER_NOT_FOUND' }); - return; - } - const rawPid = String(req.params.pid ?? ''); - if (!/^[1-9][0-9]{0,7}$/.test(rawPid)) { - res.status(400).json({ error: 'INVALID_PID' }); - return; - } - const parsed = z - .object({ - signal: z.enum(['SIGTERM', 'SIGKILL']).default('SIGTERM'), - sudo: z.boolean().optional(), - }) - .safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - const pid = Number(rawPid); - try { - const result = await serverInspector.signalProcess(id, pid, parsed.data.signal, { - useSudo: parsed.data.sudo, - }); - auditService.log({ - action: 'server.process_signal', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: `${id}:${pid}`, - status: result.ok ? 'ok' : 'error', - details: { signal: parsed.data.signal, sudo: Boolean(parsed.data.sudo) }, - }); - res.json(result); - } catch (err) { - res.status(400).json({ - error: 'SIGNAL_FAILED', - message: err instanceof Error ? err.message : 'Unable to send process signal', - }); - } - }, - ); - - router.get('/:id/probes/history', requireAuth(authService), (req, res) => { - const id = String(req.params.id ?? ''); - if (!configManager.getServer(id)) { - res.status(404).json({ error: 'SERVER_NOT_FOUND' }); - return; - } - const rawRange = String(req.query.range ?? '24h') as MetricRange; - const hoursMap: Record = { - '1h': 1, - '6h': 6, - '24h': 24, - '7d': 168, - '30d': 720, - }; - const hours = hoursMap[rawRange] ?? 24; - const limit = Math.max(1, Math.min(1000, Number(req.query.limit) || 200)); - const samples = monitoringService.queryProbeHistory( - id, - Date.now() - hours * 3600_000, - limit, - ); - res.json({ serverId: id, samples }); - }); - - router.post( - '/:id/probes/:probeId/run', - requireAuth(authService), - requireCsrf, - async (req, res) => { - const id = String(req.params.id ?? ''); - const probeId = String(req.params.probeId ?? ''); - if (!configManager.getServer(id)) { - res.status(404).json({ error: 'SERVER_NOT_FOUND' }); - return; - } - try { - const sample = await monitoringService.runProbeNow(id, probeId); - auditService.log({ - action: 'server.probe_run', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: `${id}:${probeId}`, - status: sample.ok ? 'ok' : 'error', - }); - res.json({ serverId: id, sample }); - } catch (err) { - res.status(404).json({ - error: 'PROBE_RUN_FAILED', - message: err instanceof Error ? err.message : 'Unable to run probe', - }); - } - }, - ); - router.get('/:id/keys', requireAuth(authService), async (req, res) => { const id = String(req.params.id ?? ''); if (!configManager.getServer(id)) { @@ -704,7 +405,6 @@ export function createServersRouter(deps: ServersRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - stepUpGuard, async (req, res) => { const id = String(req.params.id ?? ''); const parsed = z.object({ credentialId: EntityIdSchema }).safeParse(req.body); diff --git a/src/server/api/routes/sftp.routes.ts b/src/server/api/routes/sftp.routes.ts index b24951a..fbf9f93 100644 --- a/src/server/api/routes/sftp.routes.ts +++ b/src/server/api/routes/sftp.routes.ts @@ -1,4 +1,4 @@ -import { Router, type NextFunction, type Request, type RequestHandler, type Response } from 'express'; +import { Router, type Response } from 'express'; import { z } from 'zod'; import type { ConfigManager } from '../../config/config-manager.js'; import type { AuditService } from '../../security/audit.js'; @@ -7,7 +7,6 @@ import { enforceSafeMode, requireAuth, requireCsrf, - requireStepUp, } from '../../security/guards.js'; import { SftpServiceError, type SftpService } from '../../ssh/sftp-service.js'; @@ -16,16 +15,6 @@ export interface SftpRouterDeps { configManager: ConfigManager; auditService: AuditService; sftpService: SftpService; - stepUpGuard?: RequestHandler; -} - -function buildContentDisposition(fileName: string): string { - const asciiFallback = fileName.replace(/[^\x20-\x7e]|["\\;]/g, '_'); - const rfc5987 = encodeURIComponent(fileName).replace( - /['()*!]/g, - (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, - ); - return `attachment; filename="${asciiFallback}"; filename*=UTF-8''${rfc5987}`; } function sendSftpError(res: Response, err: unknown): void { @@ -33,7 +22,7 @@ function sendSftpError(res: Response, err: unknown): void { const status = err.code === 'NOT_FOUND' ? 404 - : err.code === 'CONFLICT' || err.code === 'ALREADY_EXISTS' + : err.code === 'CONFLICT' ? 409 : err.code === 'FILE_TOO_LARGE' ? 413 @@ -48,13 +37,7 @@ function sendSftpError(res: Response, err: unknown): void { export function createSftpRouter(deps: SftpRouterDeps): Router { const router = Router({ mergeParams: true }); - const { - authService, - configManager, - auditService, - sftpService, - stepUpGuard = requireStepUp, - } = deps; + const { authService, configManager, auditService, sftpService } = deps; const ensureServer = (serverId: string, res: Response): boolean => { if (!configManager.getServer(serverId)) { @@ -64,18 +47,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { return true; }; - const conditionalSudoStepUp = (req: Request, res: Response, next: NextFunction) => { - const wantsSudo = - req.query.sudo === '1' || - req.query.sudo === 'true' || - Boolean((req.body as { sudo?: unknown } | undefined)?.sudo); - if (!wantsSudo) { - next(); - return; - } - stepUpGuard(req, res, next); - }; - router.get('/list', requireAuth(authService), async (req, res) => { const serverId = String(req.params.id ?? ''); if (!ensureServer(serverId, res)) return; @@ -104,24 +75,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { } }); - router.get('/search', requireAuth(authService), async (req, res) => { - const serverId = String(req.params.id ?? ''); - if (!ensureServer(serverId, res)) return; - const basePath = typeof req.query.path === 'string' ? req.query.path : '/'; - const q = typeof req.query.q === 'string' ? req.query.q : ''; - const max = req.query.max ? Number(req.query.max) : 100; - if (!q.trim()) { - res.status(400).json({ error: 'MISSING_QUERY' }); - return; - } - try { - const result = await sftpService.searchFiles(serverId, basePath, q, Number.isFinite(max) ? max : 100); - res.json(result); - } catch (err) { - sendSftpError(res, err); - } - }); - router.get('/download', requireAuth(authService), async (req, res) => { const serverId = String(req.params.id ?? ''); if (!ensureServer(serverId, res)) return; @@ -133,9 +86,9 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { try { const dl = await sftpService.openDownloadStream(serverId, targetPath); + const safeName = dl.fileName.replace(/["\r\n\\]/g, '_'); res.setHeader('Content-Type', 'application/octet-stream'); - res.setHeader('Content-Disposition', buildContentDisposition(dl.fileName)); - res.setHeader('Cache-Control', 'no-store'); + res.setHeader('Content-Disposition', `attachment; filename="${safeName}"`); if (Number.isFinite(dl.size)) { res.setHeader('Content-Length', String(dl.size)); } @@ -174,9 +127,11 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { try { const arch = await sftpService.streamDirectoryArchive(serverId, targetPath, format); res.setHeader('Content-Type', 'application/octet-stream'); - res.setHeader('Content-Disposition', buildContentDisposition(arch.archiveFileName)); + res.setHeader( + 'Content-Disposition', + `attachment; filename="${arch.archiveFileName}"`, + ); res.setHeader('X-Archive-Format', arch.resolvedFormat); - res.setHeader('Cache-Control', 'no-store'); res.once('close', () => { if (!res.writableEnded) { @@ -228,35 +183,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { }, ); - router.post( - '/touch', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - async (req, res) => { - const serverId = String(req.params.id ?? ''); - if (!ensureServer(serverId, res)) return; - const parsed = z.object({ path: z.string().min(1) }).safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - try { - const created = await sftpService.touchFile(serverId, parsed.data.path); - auditService.log({ - action: 'sftp.touch', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: `${serverId}:${created}`, - status: 'ok', - }); - res.status(201).json({ ok: true, path: created }); - } catch (err) { - sendSftpError(res, err); - } - }, - ); - router.post( '/mkdir', requireAuth(authService), @@ -295,11 +221,7 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { const serverId = String(req.params.id ?? ''); if (!ensureServer(serverId, res)) return; const parsed = z - .object({ - fromPath: z.string().min(1), - toPath: z.string().min(1), - overwrite: z.boolean().optional(), - }) + .object({ fromPath: z.string().min(1), toPath: z.string().min(1) }) .safeParse(req.body ?? {}); if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); @@ -310,7 +232,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { serverId, parsed.data.fromPath, parsed.data.toPath, - Boolean(parsed.data.overwrite), ); auditService.log({ action: 'sftp.rename', @@ -362,50 +283,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { }, ); - router.post( - '/chown', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - async (req, res) => { - const serverId = String(req.params.id ?? ''); - if (!ensureServer(serverId, res)) return; - const parsed = z - .object({ - path: z.string().min(1), - uid: z.number().int().min(0), - gid: z.number().int().min(0), - sudo: z.boolean().optional(), - }) - .safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - try { - const result = await sftpService.chown( - serverId, - parsed.data.path, - parsed.data.uid, - parsed.data.gid, - Boolean(parsed.data.sudo), - ); - auditService.log({ - action: 'sftp.chown', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: `${serverId}:${result.path}`, - status: 'ok', - details: { uid: result.uid, gid: result.gid, sudo: Boolean(parsed.data.sudo) }, - }); - res.json({ ok: true, ...result }); - } catch (err) { - sendSftpError(res, err); - } - }, - ); - router.delete( '/entry', requireAuth(authService), @@ -437,42 +314,7 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { }, ); - router.post( - '/bulk-delete', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - async (req, res) => { - const serverId = String(req.params.id ?? ''); - if (!ensureServer(serverId, res)) return; - const parsed = z - .object({ - paths: z.array(z.string().min(1)).min(1).max(100), - recursive: z.boolean().optional(), - }) - .safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - const result = await sftpService.bulkDelete( - serverId, - parsed.data.paths, - Boolean(parsed.data.recursive), - ); - auditService.log({ - action: 'sftp.bulk_delete', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: serverId, - status: result.failed.length === 0 ? 'ok' : 'error', - details: { count: result.deleted.length, failedCount: result.failed.length }, - }); - res.json(result); - }, - ); - - router.get('/text', requireAuth(authService), conditionalSudoStepUp, async (req, res) => { + router.get('/text', requireAuth(authService), async (req, res) => { const serverId = String(req.params.id ?? ''); if (!ensureServer(serverId, res)) return; const targetPath = typeof req.query.path === 'string' ? req.query.path : ''; @@ -483,15 +325,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { } try { const file = await sftpService.readTextFile(serverId, targetPath, { sudo }); - if (sudo) { - auditService.log({ - action: 'sftp.sudo_read', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: `${serverId}:${file.path}`, - status: 'ok', - }); - } res.json({ file }); } catch (err) { sendSftpError(res, err); @@ -503,7 +336,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - conditionalSudoStepUp, async (req, res) => { const serverId = String(req.params.id ?? ''); if (!ensureServer(serverId, res)) return; diff --git a/src/server/api/routes/systems.routes.ts b/src/server/api/routes/systems.routes.ts index d63c03e..7ddb676 100644 --- a/src/server/api/routes/systems.routes.ts +++ b/src/server/api/routes/systems.routes.ts @@ -1,4 +1,4 @@ -import { Router, type RequestHandler } from 'express'; +import { Router } from 'express'; import { z } from 'zod'; import type { AuditService } from '../../security/audit.js'; import type { AuthService } from '../../security/auth.js'; @@ -6,7 +6,6 @@ import { enforceSafeMode, requireAuth, requireCsrf, - requireStepUp, } from '../../security/guards.js'; import type { CustomSystemsEngine } from '../../systems/systems-engine.js'; @@ -14,12 +13,11 @@ export interface SystemsRouterDeps { authService: AuthService; auditService: AuditService; systemsEngine: CustomSystemsEngine; - stepUpGuard?: RequestHandler; } export function createSystemsRouter(deps: SystemsRouterDeps): Router { const router = Router(); - const { authService, auditService, systemsEngine, stepUpGuard = requireStepUp } = deps; + const { authService, auditService, systemsEngine } = deps; router.get('/', requireAuth(authService), (_req, res) => { res.json({ systems: systemsEngine.listSystemsOverview() }); @@ -155,7 +153,7 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - (req, res) => { + async (req, res) => { const systemId = String(req.params.systemId ?? ''); const serverId = String(req.params.serverId ?? ''); const actionId = String(req.params.actionId ?? ''); @@ -163,7 +161,6 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router { .object({ itemName: z.string().min(1).optional(), subItemName: z.string().min(1).optional(), - inputs: z.record(z.unknown()).optional(), cols: z.number().int().min(10).max(500).optional(), rows: z.number().int().min(4).max(200).optional(), }) @@ -173,75 +170,43 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router { return; } - const actionMeta = systemsEngine.getActionMeta(systemId, actionId); - const execute = async () => { - try { - const result = await systemsEngine.executeAction({ - serverId, - systemId, - actionId, - ...parsed.data, - }); - const secretInputKeys = new Set( - (actionMeta?.inputs ?? []).filter((i) => i.type === 'secret').map((i) => i.name), - ); - const sanitizedInputs = parsed.data.inputs - ? Object.fromEntries( - Object.entries(parsed.data.inputs).map(([k, v]) => [ - k, - secretInputKeys.has(k) ? '[REDACTED]' : v, - ]), - ) - : undefined; - auditService.log({ - action: 'system.action', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: `${serverId}:${systemId}:${actionId}`, - status: 'ok', - details: { - itemName: parsed.data.itemName, - subItemName: parsed.data.subItemName, - inputs: sanitizedInputs, - mode: result.mode, - }, - }); - res.json(result); - } catch (err) { - res.status(400).json({ - error: 'SYSTEM_ACTION_FAILED', - message: err instanceof Error ? err.message : 'Unable to execute system action', - }); - } - }; - - if (actionMeta?.confirm || actionMeta?.sudo) { - stepUpGuard(req, res, () => { - void execute(); + try { + const result = await systemsEngine.executeAction({ + serverId, + systemId, + actionId, + ...parsed.data, + }); + auditService.log({ + action: 'system.action', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${serverId}:${systemId}:${actionId}`, + status: 'ok', + details: { + itemName: parsed.data.itemName, + subItemName: parsed.data.subItemName, + mode: result.mode, + }, + }); + res.json(result); + } catch (err) { + res.status(400).json({ + error: 'SYSTEM_ACTION_FAILED', + message: err instanceof Error ? err.message : 'Unable to execute system action', }); - return; } - void execute(); }, ); - // Cancelling a running stream must work even if Safe Mode was just toggled on router.post( '/streams/:jobId/cancel', requireAuth(authService), requireCsrf, + enforceSafeMode, (req, res) => { const jobId = String(req.params.jobId ?? ''); - const cancelled = systemsEngine.cancelStream(jobId); - auditService.log({ - action: 'system.stream_cancel', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: jobId, - status: 'ok', - details: { cancelled }, - }); - res.json({ cancelled }); + res.json({ cancelled: systemsEngine.cancelStream(jobId) }); }, ); diff --git a/src/server/api/routes/terminal.routes.ts b/src/server/api/routes/terminal.routes.ts index 1e2321a..0d3d352 100644 --- a/src/server/api/routes/terminal.routes.ts +++ b/src/server/api/routes/terminal.routes.ts @@ -37,11 +37,7 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router { serverId: EntityIdSchema, cols: z.number().int().min(10).max(500).optional(), rows: z.number().int().min(4).max(200).optional(), - cwd: z - .string() - .max(1024) - .refine((v) => !/[\x00-\x1f\x7f]/.test(v), 'Control characters not permitted in cwd') - .optional(), + cwd: z.string().max(1024).optional(), title: z.string().max(120).optional(), }) .safeParse(req.body ?? {}); @@ -74,36 +70,6 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router { }, ); - router.post( - '/sessions/:sessionId/reconnect', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - async (req, res) => { - const sessionId = String(req.params.sessionId ?? ''); - try { - const session = await ptyManager.reconnectSession(sessionId); - if (!session) { - res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' }); - return; - } - auditService.log({ - action: 'pty.reconnect', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: `${session.serverId}:${sessionId}`, - status: 'ok', - }); - res.json({ ok: true, session }); - } catch (err) { - res.status(502).json({ - error: 'PTY_RECONNECT_FAILED', - message: err instanceof Error ? err.message : 'Unable to reconnect PTY session', - }); - } - }, - ); - router.post( '/sessions/:sessionId/resize', requireAuth(authService), @@ -132,12 +98,7 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router { router.get('/sessions/:sessionId/export', requireAuth(authService), (req, res) => { const sessionId = String(req.params.sessionId ?? ''); - const format = - req.query.format === 'ansi' - ? 'ansi' - : req.query.format === 'cast' - ? 'cast' - : 'plain'; + const format = req.query.format === 'ansi' ? 'ansi' : 'plain'; const exported = ptyManager.exportScrollback(sessionId, format); if (!exported) { res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' }); @@ -145,9 +106,8 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router { } const safeFile = exported.filename.replace(/[^A-Za-z0-9._-]/g, '_'); - res.setHeader('Content-Type', exported.contentType); + res.setHeader('Content-Type', 'text/plain; charset=utf-8'); res.setHeader('Content-Disposition', `attachment; filename="${safeFile}"`); - res.setHeader('Cache-Control', 'no-store'); res.send(exported.content); }); diff --git a/src/server/api/routes/tunnels.routes.ts b/src/server/api/routes/tunnels.routes.ts index 7d37b6d..ca4df39 100644 --- a/src/server/api/routes/tunnels.routes.ts +++ b/src/server/api/routes/tunnels.routes.ts @@ -10,7 +10,7 @@ import { requireAuth, requireCsrf, } from '../../security/guards.js'; -import { ProxyIsolationError, type TunnelManager } from '../../ssh/tunnel-manager.js'; +import type { TunnelManager } from '../../ssh/tunnel-manager.js'; export interface TunnelsRouterDeps { authService: AuthService; @@ -180,46 +180,6 @@ export function createTunnelsRouter(deps: TunnelsRouterDeps): Router { }, ); - // Issue single-use isolated-origin launch ticket (allowed in Safe Mode for read-only viewing) - router.post( - '/:serverId/:tunnelId/proxy-ticket', - requireAuth(authService), - requireCsrf, - (req, res) => { - const serverId = String(req.params.serverId ?? ''); - const tunnelId = String(req.params.tunnelId ?? ''); - try { - const result = tunnelManager.issueProxyTicket( - req.authSession!.idHash, - serverId, - tunnelId, - { - host: req.headers.host, - protocol: req.protocol, - }, - ); - auditService.log({ - action: 'tunnel.proxy_ticket', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: `${serverId}:${tunnelId}`, - status: 'ok', - details: { mode: result.mode }, - }); - res.json(result); - } catch (err) { - if (err instanceof ProxyIsolationError) { - res.status(403).json({ error: err.code, message: err.message }); - return; - } - res.status(400).json({ - error: 'PROXY_TICKET_FAILED', - message: err instanceof Error ? err.message : 'Unable to issue proxy ticket', - }); - } - }, - ); - return router; } diff --git a/src/server/api/routes/vault.routes.ts b/src/server/api/routes/vault.routes.ts index 8cf4836..504f861 100644 --- a/src/server/api/routes/vault.routes.ts +++ b/src/server/api/routes/vault.routes.ts @@ -15,7 +15,6 @@ import { import { computeOpenSshFingerprint, generateMasterKeyBuffer, - validatePrivateKey, type VaultCredentialInput, type VaultService, } from '../../security/vault.js'; @@ -115,7 +114,6 @@ export function createVaultRouter(deps: VaultRouterDeps): { type: 'vault:state', vaultState: vaultService.state, vaultRuntimeReady: vaultService.isRuntimeReady, - vaultSealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); }; @@ -124,52 +122,43 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, - sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); }); - vaultRouter.post( - '/init', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - (req, res) => { - const ip = req.clientIp ?? 'unknown'; - const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - try { - const result = vaultService.initializeNewVault(parsed.data.masterKey); - notifyConfigReeval(); - onVaultUnlocked?.(); - onVaultChanged?.('vault-init'); - broadcastVaultState(); - auditService.log({ - action: 'vault.init', - actorIp: ip, - sessionIdHash: req.authSession!.idHash, - status: 'ok', - }); - res.status(201).json({ - state: vaultService.state, - runtimeReady: vaultService.isRuntimeReady, - sealState: vaultService.sealState, - generatedKeyHex: result.generatedKeyHex, - }); - } catch (err) { - res.status(400).json({ - error: 'VAULT_INIT_FAILED', - message: err instanceof Error ? err.message : 'Vault initialization failed', - }); - } - }, - ); + vaultRouter.post('/init', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { + const ip = req.clientIp ?? 'unknown'; + const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + try { + const result = vaultService.initializeNewVault(parsed.data.masterKey); + notifyConfigReeval(); + onVaultUnlocked?.(); + onVaultChanged?.('vault-init'); + broadcastVaultState(); + auditService.log({ + action: 'vault.init', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.status(201).json({ + state: vaultService.state, + runtimeReady: vaultService.isRuntimeReady, + generatedKeyHex: result.generatedKeyHex, + }); + } catch (err) { + res.status(400).json({ + error: 'VAULT_INIT_FAILED', + message: err instanceof Error ? err.message : 'Vault initialization failed', + }); + } + }); - vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { + vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, (req, res) => { const ip = req.clientIp ?? 'unknown'; const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); if (!parsed.success) { @@ -202,7 +191,6 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, - sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); } catch (err) { @@ -243,7 +231,6 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, - sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); } catch (err) { @@ -267,35 +254,10 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, - sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); }); - vaultRouter.post( - '/seal', - requireAuth(authService), - requireCsrf, - enforceSafeMode, - stepUpGuard, - (req, res) => { - vaultService.seal(); - broadcastVaultState(); - auditService.log({ - action: 'vault.seal', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - status: 'ok', - }); - res.json({ - state: vaultService.state, - runtimeReady: vaultService.isRuntimeReady, - sealState: vaultService.sealState, - isPanicLocked: vaultService.isPanicLocked, - }); - }, - ); - // Panic Lock is ALWAYS reachable when authenticated + CSRF verified (even under Safe Mode!) panicLockHandler.post('/panic-lock', requireAuth(authService), requireCsrf, (req, res) => { const session = req.authSession!; @@ -337,13 +299,6 @@ export function createVaultRouter(deps: VaultRouterDeps): { requireAuth(authService), stepUpGuard, (req, res) => { - if (req.authSession?.safeMode || req.headers['x-gcoord-safe-mode'] === '1') { - res.status(423).json({ - error: 'SAFE_MODE_ACTIVE', - message: 'Disable Safe / Read-Only Mode before revealing secrets.', - }); - return; - } if (vaultService.state !== 'unlocked') { res.status(423).json({ error: 'VAULT_LOCKED' }); return; @@ -382,27 +337,15 @@ export function createVaultRouter(deps: VaultRouterDeps): { return; } const credInput: VaultCredentialInput = { ...parsed.data }; - if (credInput.type === 'ssh-key') { + if ( + credInput.type === 'ssh-key' && + credInput.publicKey && + !credInput.fingerprint + ) { try { - validatePrivateKey(credInput.privateKey, credInput.passphrase); - } catch (err) { - res.status(400).json({ - error: 'INVALID_SSH_KEY', - message: err instanceof Error ? err.message : 'Invalid SSH private key', - }); - return; - } - if (credInput.publicKey) { - try { - credInput.publicKey = credInput.publicKey.trim(); - credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); - } catch (err) { - res.status(400).json({ - error: 'INVALID_SSH_PUBLIC_KEY', - message: err instanceof Error ? err.message : 'Invalid SSH public key', - }); - return; - } + credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); + } catch { + // Leave fingerprint omitted if user imported an unusual public key format } } const meta = vaultService.upsertCredential(credInput); @@ -438,27 +381,15 @@ export function createVaultRouter(deps: VaultRouterDeps): { return; } const credInput: VaultCredentialInput = { ...parsed.data }; - if (credInput.type === 'ssh-key') { + if ( + credInput.type === 'ssh-key' && + credInput.publicKey && + !credInput.fingerprint + ) { try { - validatePrivateKey(credInput.privateKey, credInput.passphrase); - } catch (err) { - res.status(400).json({ - error: 'INVALID_SSH_KEY', - message: err instanceof Error ? err.message : 'Invalid SSH private key', - }); - return; - } - if (credInput.publicKey) { - try { - credInput.publicKey = credInput.publicKey.trim(); - credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); - } catch (err) { - res.status(400).json({ - error: 'INVALID_SSH_PUBLIC_KEY', - message: err instanceof Error ? err.message : 'Invalid SSH public key', - }); - return; - } + credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); + } catch { + // Ignore non-standard public key strings } } const meta = vaultService.upsertCredential(credInput); @@ -564,12 +495,6 @@ export function createVaultRouter(deps: VaultRouterDeps): { sessionIdHash: req.authSession!.idHash, expiresAt, }; - auditService.log({ - action: 'vault.rotate_key.prepare', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - status: 'ok', - }); res.json({ candidateKeyHex, confirmToken, expiresAt }); }, ); @@ -585,17 +510,10 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.status(423).json({ error: 'VAULT_LOCKED' }); return; } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('vault-rotate-commit', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } const parsed = z .object({ confirmToken: z.string().min(1), - confirmedKeyHex: z.string().min(64).max(64), + confirmedKeyHex: z.string().min(1).optional(), }) .safeParse(req.body); if (!parsed.success) { @@ -603,57 +521,32 @@ export function createVaultRouter(deps: VaultRouterDeps): { return; } - const timingEq = (a: string, b: string) => { - const ba = Buffer.from(a, 'utf8'); - const bb = Buffer.from(b, 'utf8'); - return ba.length === bb.length && crypto.timingSafeEqual(ba, bb); - }; - if ( !pendingRotation || pendingRotation.expiresAt <= Date.now() || pendingRotation.sessionIdHash !== req.authSession!.idHash || - !timingEq(pendingRotation.confirmToken, parsed.data.confirmToken) + pendingRotation.confirmToken !== parsed.data.confirmToken ) { - pendingRotation = null; - rateLimiter.recordFailure('vault-rotate-commit', ip); - auditService.log({ - action: 'vault.rotate_key.commit', - actorIp: ip, - sessionIdHash: req.authSession!.idHash, - status: 'denied', - }); res.status(400).json({ error: 'ROTATION_TOKEN_INVALID_OR_EXPIRED' }); return; } if ( - !timingEq( - parsed.data.confirmedKeyHex.trim().toLowerCase(), - pendingRotation.candidateKeyHex.toLowerCase(), - ) + parsed.data.confirmedKeyHex && + parsed.data.confirmedKeyHex.trim().toLowerCase() !== + pendingRotation.candidateKeyHex.toLowerCase() ) { - pendingRotation = null; - rateLimiter.recordFailure('vault-rotate-commit', ip); - auditService.log({ - action: 'vault.rotate_key.commit', - actorIp: ip, - sessionIdHash: req.authSession!.idHash, - status: 'denied', - details: { reason: 'key_confirmation_mismatch' }, - }); res.status(400).json({ error: 'KEY_CONFIRMATION_MISMATCH' }); return; } - rateLimiter.recordSuccess('vault-rotate-commit', ip); const nextHex = pendingRotation.candidateKeyHex; pendingRotation = null; vaultService.rotateMasterKey(nextHex); onVaultChanged?.('master-key-rotation'); auditService.log({ action: 'vault.rotate_key', - actorIp: ip, + actorIp: req.clientIp ?? 'unknown', sessionIdHash: req.authSession!.idHash, status: 'ok', }); diff --git a/src/server/api/routes/workflows.routes.ts b/src/server/api/routes/workflows.routes.ts index cea3718..34c7809 100644 --- a/src/server/api/routes/workflows.routes.ts +++ b/src/server/api/routes/workflows.routes.ts @@ -147,8 +147,7 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { }); router.get('/runs/:runId', requireAuth(authService), (req, res) => { - const includeLogs = req.query.includeLogs !== 'false' && req.query.includeLogs !== '0'; - const detail = workflowEngine.getRunDetail(String(req.params.runId ?? ''), { includeLogs }); + const detail = workflowEngine.getRunDetail(String(req.params.runId ?? '')); if (!detail) { res.status(404).json({ error: 'RUN_NOT_FOUND' }); return; @@ -156,20 +155,11 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { res.json(detail); }); - router.get('/runs/:runId/steps/:stepId/logs', requireAuth(authService), (req, res) => { - const runId = String(req.params.runId ?? ''); - const stepId = String(req.params.stepId ?? ''); - const offset = Number(req.query.offset) || 0; - const limit = Number(req.query.limit) || 50; - const result = workflowEngine.getStepLogs(runId, { stepId, offset, limit }); - res.json(result); - }); - - // Cancelling a running workflow must remain available under Safe Mode router.post( '/runs/:runId/cancel', requireAuth(authService), requireCsrf, + enforceSafeMode, (req, res) => { const runId = String(req.params.runId ?? ''); const cancelled = workflowEngine.cancelRun(runId, 'admin'); @@ -258,7 +248,6 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { }), }) .safeParse(req.body ?? {}); - if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); return; @@ -280,24 +269,6 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { }, ); - router.get('/broadcast/history', requireAuth(authService), (req, res) => { - const limit = Number(req.query.limit) || 50; - res.json({ jobs: broadcastService.listHistory(limit) }); - }); - - router.get('/broadcast/:jobId/export', requireAuth(authService), (req, res) => { - const jobId = String(req.params.jobId ?? ''); - const format = String(req.query.format ?? 'json') === 'csv' ? 'csv' : 'json'; - const exported = broadcastService.exportBroadcast(jobId, format); - if (!exported) { - res.status(404).json({ error: 'BROADCAST_NOT_FOUND' }); - return; - } - res.setHeader('Content-Type', exported.contentType); - res.setHeader('Content-Disposition', `attachment; filename="${exported.filename}"`); - res.send(exported.body); - }); - router.get('/broadcast/:jobId', requireAuth(authService), (req, res) => { const job = broadcastService.getBroadcastResult(String(req.params.jobId ?? '')); if (!job) { @@ -307,22 +278,14 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { res.json({ job }); }); - // Cancelling a running broadcast must remain available under Safe Mode router.post( '/broadcast/:jobId/cancel', requireAuth(authService), requireCsrf, + enforceSafeMode, (req, res) => { const jobId = String(req.params.jobId ?? ''); - const cancelled = broadcastService.cancelBroadcast(jobId); - auditService.log({ - action: 'broadcast.cancel', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: jobId, - status: cancelled ? 'ok' : 'error', - }); - res.json({ cancelled }); + res.json({ cancelled: broadcastService.cancelBroadcast(jobId) }); }, ); diff --git a/src/server/api/ws-hub.ts b/src/server/api/ws-hub.ts index 7a5ea04..abfa4ff 100644 --- a/src/server/api/ws-hub.ts +++ b/src/server/api/ws-hub.ts @@ -5,18 +5,10 @@ import { ClientWsFrameSchema, type ServerWsFrame, } from '../../shared/ws-protocol.js'; -import { - SESSION_COOKIE_NAME, - type AuthService, - type AuthSession, -} from '../security/auth.js'; +import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js'; import { extractCookies } from '../security/guards.js'; import type { VaultService } from '../security/vault.js'; -const WS_MAX_PAYLOAD_BYTES = 128 * 1024; -const WS_SOFT_BACKPRESSURE_BYTES = 1024 * 1024; -const WS_HARD_BACKPRESSURE_BYTES = 4 * 1024 * 1024; - interface WsClientMeta { ws: WebSocket; sessionToken: string; @@ -50,42 +42,25 @@ export interface WsAiHandlers { } export class WsHub { - private readonly wss = new WebSocketServer({ - noServer: true, - maxPayload: WS_MAX_PAYLOAD_BYTES, - }); + private readonly wss = new WebSocketServer({ noServer: true }); private readonly clients = new Set(); private readonly pingTimer: NodeJS.Timeout; private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = []; - private readonly hostUpgradeHandlers: Array<(req: IncomingMessage, socket: Duplex, head: Buffer) => boolean> = []; private readonly subscribeListeners = new Set(); private ptyHandlers: WsPtyHandlers | null = null; private aiHandlers: WsAiHandlers | null = null; - private readonly trustCloudflare: boolean; constructor( httpServer: HttpServer, private readonly authService: AuthService, private readonly vaultService: VaultService, - options: { trustCloudflare?: boolean } = {}, ) { - this.trustCloudflare = Boolean(options.trustCloudflare); httpServer.on('upgrade', (req, socket, head) => { this.handleUpgrade(req, socket, head); }); this.pingTimer = setInterval(() => { for (const client of this.clients) { - const session = this.authService.getSessionByToken(client.sessionToken); - if (!session) { - try { - client.ws.close(4001, 'Session expired'); - } catch { - client.ws.terminate(); - } - this.clients.delete(client); - continue; - } if (!client.alive) { client.ws.terminate(); this.clients.delete(client); @@ -98,34 +73,10 @@ export class WsHub { this.pingTimer.unref(); } - disconnectSessions(idHashes: string[]): void { - if (idHashes.length === 0) return; - const targetSet = new Set(idHashes); - for (const client of this.clients) { - if (!targetSet.has(client.sessionIdHash)) continue; - try { - if (client.ws.readyState === WebSocket.OPEN) { - client.ws.close(4001, 'Session revoked'); - } else { - client.ws.terminate(); - } - } catch { - // Ignore close errors - } - this.clients.delete(client); - } - } - registerUpgradeHandler(prefix: string, handler: WsUpgradeHandler): void { this.upgradeHandlers.push({ prefix, handler }); } - registerHostUpgradeHandler( - matcherHandler: (req: IncomingMessage, socket: Duplex, head: Buffer) => boolean, - ): void { - this.hostUpgradeHandlers.push(matcherHandler); - } - onChannelSubscribe(listener: WsSubscribeListener): () => void { this.subscribeListeners.add(listener); return () => { @@ -167,18 +118,21 @@ export class WsHub { broadcastAll(frame: ServerWsFrame): void { const text = JSON.stringify(frame); - const critical = frame.type === 'security:panic-lock' || frame.type === 'vault:state'; for (const client of this.clients) { - this.safeSendRaw(client, text, critical); + if (client.ws.readyState === WebSocket.OPEN) { + client.ws.send(text); + } } } broadcastChannel(channel: string, frame: ServerWsFrame): void { const text = JSON.stringify(frame); - const critical = frame.type === 'pty:exit' || frame.type === 'error'; for (const client of this.clients) { - if (client.channels.has(channel)) { - this.safeSendRaw(client, text, critical); + if ( + client.ws.readyState === WebSocket.OPEN && + (client.channels.has(channel) || client.channels.has('*')) + ) { + client.ws.send(text); } } } @@ -188,11 +142,6 @@ export class WsHub { socket: Duplex, head: Buffer, ): void { - for (const matcher of this.hostUpgradeHandlers) { - if (matcher(req, socket, head)) { - return; - } - } const urlPath = (req.url ?? '').split('?')[0] ?? ''; for (const entry of this.upgradeHandlers) { if (urlPath.startsWith(entry.prefix)) { @@ -206,29 +155,13 @@ export class WsHub { return; } - const cookies = extractCookies(req.headers.cookie); - const token = cookies[SESSION_COOKIE_NAME]; - const session = this.authService.getSessionByToken(token); - if (!session || !token) { - socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); - socket.destroy(); - return; - } - - // Validate Origin strictly when present (browsers always send Origin) to block CSWSH + // Validate Origin when provided by browsers to block cross-site WS hijacking const origin = req.headers.origin; const host = req.headers.host; - if (origin) { + if (origin && host) { try { const originUrl = new URL(origin); - const validScheme = - originUrl.protocol === 'http:' || originUrl.protocol === 'https:'; - const isHttpsReq = Boolean( - (req.socket as { encrypted?: boolean }).encrypted || - (this.trustCloudflare && req.headers['x-forwarded-proto'] === 'https'), - ); - const expectedScheme = isHttpsReq ? 'https:' : 'http:'; - if (!validScheme || !host || originUrl.host !== host || originUrl.protocol !== expectedScheme) { + if (originUrl.host !== host) { socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); socket.destroy(); return; @@ -240,6 +173,15 @@ export class WsHub { } } + const cookies = extractCookies(req.headers.cookie); + const token = cookies[SESSION_COOKIE_NAME]; + const session = this.authService.getSessionByToken(token); + if (!session || !token) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + this.wss.handleUpgrade(req, socket, head, (ws) => { const meta: WsClientMeta = { ws, @@ -251,17 +193,13 @@ export class WsHub { }; this.clients.add(meta); - this.sendFrame( - ws, - { - type: 'hello', - vaultState: this.vaultService.state, - vaultRuntimeReady: this.vaultService.isRuntimeReady, - safeMode: session.safeMode, - elevatedUntil: session.elevatedUntil, - }, - true, - ); + this.sendFrame(ws, { + type: 'hello', + vaultState: this.vaultService.state, + vaultRuntimeReady: this.vaultService.isRuntimeReady, + safeMode: session.safeMode, + elevatedUntil: session.elevatedUntil, + }); ws.on('pong', () => { meta.alive = true; @@ -281,69 +219,40 @@ export class WsHub { }); } - private ensureActiveSession(meta: WsClientMeta): AuthSession | null { - const latestSession = this.authService.getSessionByToken(meta.sessionToken); - if (!latestSession) { - try { - meta.ws.close(4001, 'Session expired'); - } catch { - meta.ws.terminate(); - } - this.clients.delete(meta); - return null; - } - return latestSession; - } - private onMessage(meta: WsClientMeta, raw: unknown): void { let parsedJson: unknown; try { const text = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf8'); parsedJson = JSON.parse(text); } catch { - this.sendFrame( - meta.ws, - { - type: 'error', - code: 'BAD_JSON', - message: 'Invalid WebSocket JSON frame', - }, - true, - ); + this.sendFrame(meta.ws, { + type: 'error', + code: 'BAD_JSON', + message: 'Invalid WebSocket JSON frame', + }); return; } const result = ClientWsFrameSchema.safeParse(parsedJson); if (!result.success) { - this.sendFrame( - meta.ws, - { - type: 'error', - code: 'INVALID_FRAME', - message: 'Unrecognized or malformed WebSocket frame', - }, - true, - ); + this.sendFrame(meta.ws, { + type: 'error', + code: 'INVALID_FRAME', + message: 'Unrecognized or malformed WebSocket frame', + }); return; } const frame = result.data; switch (frame.type) { - case 'ping': { - if (!this.ensureActiveSession(meta)) return; - this.sendFrame( - meta.ws, - { - type: 'pong', - ts: frame.ts, - serverTs: Date.now(), - }, - true, - ); + case 'ping': + this.sendFrame(meta.ws, { + type: 'pong', + ts: frame.ts, + serverTs: Date.now(), + }); break; - } case 'sub': { - if (!this.ensureActiveSession(meta)) return; const ctx = { send: (outFrame: ServerWsFrame) => this.sendFrame(meta.ws, outFrame), sessionIdHash: meta.sessionIdHash, @@ -365,78 +274,44 @@ export class WsHub { meta.channels.delete(ch); } break; - case 'safe-mode': { - const latestSession = this.ensureActiveSession(meta); - if (!latestSession) return; - meta.clientSafeMode = latestSession.safeMode || frame.enabled; + case 'safe-mode': + meta.clientSafeMode = frame.enabled; break; - } case 'pty:input': { - const latestSession = this.ensureActiveSession(meta); - if (!latestSession) return; + const latestSession = this.authService.getSessionByToken(meta.sessionToken); + if (!latestSession) { + meta.ws.close(4001, 'Session expired'); + return; + } if (latestSession.safeMode || meta.clientSafeMode) { - this.sendFrame( - meta.ws, - { - type: 'error', - code: 'SAFE_MODE_ACTIVE', - message: 'Safe / Read-Only Mode blocks terminal input.', - }, - true, - ); + this.sendFrame(meta.ws, { + type: 'error', + code: 'SAFE_MODE_ACTIVE', + message: 'Safe / Read-Only Mode blocks terminal input.', + }); return; } this.ptyHandlers?.onInput(frame.sessionId, frame.data); break; } case 'pty:resize': { - if (!this.ensureActiveSession(meta)) return; + const latestSession = this.authService.getSessionByToken(meta.sessionToken); + if (!latestSession) { + meta.ws.close(4001, 'Session expired'); + return; + } this.ptyHandlers?.onResize(frame.sessionId, frame.cols, frame.rows); break; } - case 'ai:cancel': { - const latestSession = this.ensureActiveSession(meta); - if (!latestSession) return; - if (latestSession.safeMode || meta.clientSafeMode) { - this.sendFrame( - meta.ws, - { - type: 'error', - code: 'SAFE_MODE_ACTIVE', - message: 'Safe / Read-Only Mode blocks mutating AI actions.', - }, - true, - ); - return; - } + case 'ai:cancel': this.aiHandlers?.onCancel(frame.chatId); break; - } } } - private safeSendRaw(client: WsClientMeta, payload: string, critical = false): void { - if (client.ws.readyState !== WebSocket.OPEN) return; - if (client.ws.bufferedAmount > WS_HARD_BACKPRESSURE_BYTES) { - client.ws.terminate(); - this.clients.delete(client); - return; + private sendFrame(ws: WebSocket, frame: ServerWsFrame): void { + if (ws.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify(frame)); } - if (!critical && client.ws.bufferedAmount > WS_SOFT_BACKPRESSURE_BYTES) { - return; - } - client.ws.send(payload); - } - - private sendFrame(ws: WebSocket, frame: ServerWsFrame, critical = false): void { - if (ws.readyState !== WebSocket.OPEN) return; - if (ws.bufferedAmount > WS_HARD_BACKPRESSURE_BYTES) { - ws.terminate(); - return; - } - if (!critical && ws.bufferedAmount > WS_SOFT_BACKPRESSURE_BYTES) { - return; - } - ws.send(JSON.stringify(frame)); } } diff --git a/src/server/app.ts b/src/server/app.ts index 5e525b2..3a0ba6e 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -2,29 +2,23 @@ import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; import type Database from 'better-sqlite3'; -import express, { type Express, type NextFunction, type Request, type Response } from 'express'; -import type { ThrottleMode } from '../shared/schemas/settings.schema.js'; +import express, { type Express } from 'express'; import { AiService } from './ai/ai-service.js'; import { AlertEngine } from './alerts/alert-engine.js'; import { BroadcastService } from './automation/broadcast-service.js'; import { TransferEngine } from './automation/transfer-engine.js'; import { WorkflowEngine } from './automation/workflow-engine.js'; import { ConfigManager } from './config/config-manager.js'; -import { resolveRuntimeLimits } from './config/runtime-limits.js'; -import { applyDatabaseThrottlePragmas, openDatabase } from './db/database.js'; +import { openDatabase } from './db/database.js'; import { ServerInspector } from './monitoring/inspector.js'; import { MonitoringService } from './monitoring/monitoring-service.js'; import { ProbeRunner } from './monitoring/probes.js'; -import { createPrometheusHandler } from './monitoring/prometheus.js'; import { AuditService } from './security/audit.js'; import { AuthService } from './security/auth.js'; -import { BackupScheduler } from './security/backup-scheduler.js'; import { - DEFAULT_TRUSTED_PROXY_CIDRS, RateLimiter, attachClientIp, createStepUpGuard, - isTrustedProxyPeer, } from './security/guards.js'; import { EmergencyRecoveryService } from './security/recovery-store.js'; import { VaultService } from './security/vault.js'; @@ -33,7 +27,7 @@ import { KnownHostsService } from './ssh/known-hosts.js'; import { PTYManager } from './ssh/pty-manager.js'; import { SftpService } from './ssh/sftp-service.js'; import { SSHPool } from './ssh/ssh-pool.js'; -import { TunnelManager, extractSubdomainTunnel } from './ssh/tunnel-manager.js'; +import { TunnelManager } from './ssh/tunnel-manager.js'; import { CustomSystemsEngine } from './systems/systems-engine.js'; import { createAiRouter } from './api/routes/ai.routes.js'; import { createAlertsRouter } from './api/routes/alerts.routes.js'; @@ -58,17 +52,7 @@ export interface ServerOptions { publicDir?: string; secretFilePath?: string; envMasterKey?: string; - envDbKey?: string; trustCloudflare?: boolean; - trustedProxyCidrs?: string[]; - allowLanTunnels?: boolean; - proxyBaseDomain?: string; - proxyPort?: number; - webauthnRpId?: string; - webauthnOrigins?: string[]; - metricsToken?: string; - throttleModeOverride?: ThrottleMode; - autoKeyFile?: boolean; watchConfig?: boolean; } @@ -90,7 +74,6 @@ export interface GCoordinatorInstance { customSystemsEngine: CustomSystemsEngine; serverInspector: ServerInspector; monitoringService: MonitoringService; - backupScheduler: BackupScheduler; transferEngine: TransferEngine; workflowEngine: WorkflowEngine; broadcastService: BroadcastService; @@ -98,7 +81,6 @@ export interface GCoordinatorInstance { aiService: AiService; wsHub: WsHub; port: number; - proxyPort?: number; close(): Promise; } @@ -110,41 +92,24 @@ export async function createGCoordinatorServer( const dbPath = path.join(dataDir, 'gcoord.db'); const vaultPath = path.join(dataDir, 'vault.enc'); const trustCloudflare = Boolean(options.trustCloudflare); - const trustedProxyCidrs = options.trustedProxyCidrs ?? DEFAULT_TRUSTED_PROXY_CIDRS; - fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 }); - try { - fs.chmodSync(dataDir, 0o700); - } catch { - // Best-effort on filesystems without POSIX permissions - } + fs.mkdirSync(dataDir, { recursive: true }); const db = openDatabase(dbPath); const auditService = new AuditService(db); const vaultService = new VaultService(vaultPath, { keyFilePath: path.join(dataDir, 'vault.key'), - allowLocalKeyFile: options.autoKeyFile ?? true, }); const recoveryStore = new EmergencyRecoveryService(dataDir); - const rateLimiter = new RateLimiter({ db }); + const rateLimiter = new RateLimiter(); const configManager = new ConfigManager(configDir, db, vaultService); await configManager.init({ watch: options.watchConfig ?? true }); - const getRuntimeLimits = () => - resolveRuntimeLimits( - configManager.getSettings().runtime?.throttleMode ?? 'low-resource', - options.throttleModeOverride, - ); - applyDatabaseThrottlePragmas(db, getRuntimeLimits()); - const authService = new AuthService(db, { getSecuritySettings: () => configManager.getSettings().security, - getRuntimeLimits, recoveryStore, vaultService, - dataDir, - envDbKey: options.envDbKey, }); const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup @@ -164,49 +129,37 @@ export async function createGCoordinatorServer( } const app = express(); - app.locals.auditService = auditService; app.disable('x-powered-by'); if (trustCloudflare) { - app.set('trust proxy', (ip: string) => isTrustedProxyPeer(ip, trustedProxyCidrs)); + app.set('trust proxy', 1); } const httpServer = http.createServer(app); - const wsHub = new WsHub(httpServer, authService, vaultService, { trustCloudflare }); - authService.onSessionsRevoked((idHashes) => { - wsHub.disconnectSessions(idHashes); - }); + const wsHub = new WsHub(httpServer, authService, vaultService); const knownHosts = new KnownHostsService(db, auditService); const sshPool = new SSHPool(configManager, vaultService, knownHosts); const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService); - const ptyManager = new PTYManager(sshPool, configManager, wsHub, getRuntimeLimits); + const ptyManager = new PTYManager(sshPool, configManager, wsHub); const sftpService = new SftpService(sshPool); - const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService, { - getRuntimeLimits, - allowLanTunnels: options.allowLanTunnels, - proxyBaseDomain: options.proxyBaseDomain, - proxyPort: options.proxyPort, - trustCloudflare, - }); + const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService); const customSystemsEngine = new CustomSystemsEngine( sshPool, configManager, vaultService, ptyManager, wsHub, - getRuntimeLimits, ); const serverInspector = new ServerInspector(sshPool, configManager); - const probeRunner = new ProbeRunner(sshPool, configManager); + const probeRunner = new ProbeRunner(sshPool); const monitoringService = new MonitoringService( db, configManager, vaultService, sshPool, probeRunner, - getRuntimeLimits, ); - const transferEngine = new TransferEngine(sshPool, sftpService, configManager, knownHosts); + const transferEngine = new TransferEngine(sshPool, sftpService, configManager); const workflowEngine = new WorkflowEngine( db, configManager, @@ -217,7 +170,6 @@ export async function createGCoordinatorServer( transferEngine, wsHub, auditService, - getRuntimeLimits, ); const broadcastService = new BroadcastService( configManager, @@ -225,8 +177,6 @@ export async function createGCoordinatorServer( sshPool, wsHub, auditService, - db, - getRuntimeLimits, ); const alertEngine = new AlertEngine( db, @@ -245,24 +195,8 @@ export async function createGCoordinatorServer( sshPool, wsHub, auditService, - getRuntimeLimits, - ); - const backupScheduler = new BackupScheduler( - dataDir, - db, - configManager, - vaultService, - sftpService, - auditService, - getRuntimeLimits, ); - wsHub.registerHostUpgradeHandler((req, socket, head) => { - const tunnelSub = extractSubdomainTunnel(req.headers.host, options.proxyBaseDomain); - if (!tunnelSub) return false; - tunnelManager.handleSubdomainProxyWs(req, socket, head, tunnelSub); - return true; - }); wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => { tunnelManager.handleWsProxyUpgrade(req, socket, head); }); @@ -319,57 +253,29 @@ export async function createGCoordinatorServer( } }); - app.use((req, res, next) => { - const tunnelSub = extractSubdomainTunnel(req.headers.host, options.proxyBaseDomain); - if (tunnelSub) { - tunnelManager.handleSubdomainProxyHttp(req, res, tunnelSub); - return; - } - next(); - }); - app.use((req, res, next) => { res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('Referrer-Policy', 'no-referrer'); - res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()'); - if (req.secure || trustCloudflare) { - res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains'); - } - if (req.path.startsWith('/api/')) { - res.setHeader('Cache-Control', 'no-store'); - res.setHeader('Pragma', 'no-cache'); - } if (!req.path.startsWith('/proxy/')) { - const rawHost = typeof req.headers.host === 'string' ? req.headers.host.trim() : ''; - const safeHost = /^[A-Za-z0-9.\-:\[\]]+$/.test(rawHost) ? rawHost : ''; - const connectSrc = safeHost - ? `'self' ws://${safeHost} wss://${safeHost}` - : `'self'`; res.setHeader('X-Frame-Options', 'DENY'); res.setHeader( 'Content-Security-Policy', - `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src ${connectSrc}; object-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'`, + "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ws: wss:; frame-ancestors 'none'; base-uri 'self'", ); } next(); }); - app.use(attachClientIp(trustCloudflare, trustedProxyCidrs)); + app.use(attachClientIp(trustCloudflare)); // Mount /proxy before express.json so proxied POST/PUT payloads stream untouched upstream app.use('/proxy', createProxyRouter({ authService, tunnelManager })); const jsonParser = express.json({ limit: '2mb' }); - const backupJsonParser = express.json({ limit: '16mb' }); - app.use((req, res, next) => { if (req.path.endsWith('/sftp/upload')) { next(); return; } - if (req.path.startsWith('/api/backup/')) { - backupJsonParser(req, res, next); - return; - } jsonParser(req, res, next); }); @@ -397,49 +303,14 @@ export async function createGCoordinatorServer( }); }); - authService.setSecurityEventListener((ev) => { - void alertEngine.emitSecurityEvent(ev.type, { - ip: ev.ip, - details: ev.details, - message: `${ev.type}${ev.ip ? ` from ${ev.ip}` : ''}`, - }); - }); - - knownHosts.onHostKeyMismatch((alert) => { - void alertEngine.emitSecurityEvent('ssh.host_key_mismatch', { - serverId: alert.serverId, - message: `Host key mismatch on ${alert.hostPortKey} (${alert.algorithm})`, - }); - }); - monitoringService.start(); void tunnelManager.syncAutoStart(); customSystemsEngine.syncBackgroundChecks(); workflowEngine.start(); alertEngine.start(); - backupScheduler.start(); - auditService.pruneOlderThan(configManager.getSettings().auditRetentionDays); - - vaultService.onSeal(() => { - aiService.cancelAll(); - backupScheduler.stop(); - alertEngine.handlePanicLock(); - workflowEngine.handlePanicLock(); - broadcastService.cancelAll(); - monitoringService.stopAll(); - customSystemsEngine.stopBackgroundChecks(); - customSystemsEngine.cancelAllStreams(); - tunnelManager.stopAll(); - ptyManager.closeAll(true); - sshPool.closeAll('vault_sealed'); - }); vaultService.onPanicLock(() => { - void alertEngine.emitSecurityEvent('vault.panic_lock', { - message: 'Emergency Panic Lock activated', - }); aiService.cancelAll(); - backupScheduler.stop(); alertEngine.handlePanicLock(); workflowEngine.handlePanicLock(); broadcastService.cancelAll(); @@ -449,8 +320,8 @@ export async function createGCoordinatorServer( tunnelManager.stopAll(); ptyManager.closeAll(true); sshPool.closeAll('panic_lock'); - wsHub.handlePanicLock(); authService.revokeAllSessions(); + wsHub.handlePanicLock(); }); configManager.onChange((event) => { @@ -461,9 +332,6 @@ export async function createGCoordinatorServer( warnings: event.warnings, errors: event.errors, }); - if (event.entityType === 'alerts' || event.entityType === 'server' || event.entityType === 'all') { - alertEngine.syncWithConfig(); - } if ( event.entityType === 'server' || event.entityType === 'system' || @@ -478,32 +346,16 @@ export async function createGCoordinatorServer( customSystemsEngine.invalidateCache(event.id); } else if (event.entityType === 'system' && event.id) { customSystemsEngine.invalidateCache(undefined, event.id); - } else if (event.entityType === 'all') { + } else { customSystemsEngine.invalidateCache(); } - if (event.entityType === 'settings' || event.entityType === 'all') { - applyDatabaseThrottlePragmas(db, getRuntimeLimits()); - if (!configManager.getSettings().security.enableEmergencySecretsBackup) { - recoveryStore.wipeAll(); - } else { - authService.syncRecovery(); - } - backupScheduler.sync(); - } - if (event.entityType === 'server' || event.entityType === 'all') { - monitoringService.syncServers(); - void tunnelManager.syncAutoStart(); - } - if ( - event.entityType === 'server' || - event.entityType === 'system' || - event.entityType === 'all' - ) { - customSystemsEngine.syncBackgroundChecks(); - } - if (event.entityType === 'workflow' || event.entityType === 'all') { - workflowEngine.syncCronJobs(); + if (event.entityType === 'settings') { + authService.syncRecovery(); } + monitoringService.syncServers(); + customSystemsEngine.syncBackgroundChecks(); + workflowEngine.syncCronJobs(); + void tunnelManager.syncAutoStart(); } }); @@ -513,7 +365,11 @@ export async function createGCoordinatorServer( ); app.get('/api/healthz', (_req, res) => { - res.json({ ok: true }); + res.json({ + ok: true, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + }); }); app.use( @@ -526,8 +382,6 @@ export async function createGCoordinatorServer( recoveryStore, rateLimiter, trustCloudflare, - webauthnRpId: options.webauthnRpId, - webauthnOrigins: options.webauthnOrigins, }), ); @@ -543,7 +397,6 @@ export async function createGCoordinatorServer( monitoringService.syncServers(); customSystemsEngine.syncBackgroundChecks(); workflowEngine.syncCronJobs(); - backupScheduler.sync(); void tunnelManager.syncAutoStart(); }, onVaultChanged: (snapshotReason) => { @@ -563,27 +416,18 @@ export async function createGCoordinatorServer( configManager, auditService, stepUpGuard, - getRuntimeLimits, - backupScheduler, onRestored: async ({ inner, vaultKeyCandidate }) => { if (inner.vaultEnvelopeRaw !== null) { try { vaultService.reloadFromDisk(vaultKeyCandidate); } catch { - // Avoid keeping an old runtime master key unlocked against a newly restored foreign vault - vaultService.seal(); - vaultService.dropLocalKeyFile(); + // Keep existing runtime state untouched if backup vault used a different key } } knownHosts.replaceAllKnownHosts(inner.knownHosts); configManager.reloadAllFromDisk(); sshPool.syncWithConfig(); - backupScheduler.sync(); - if ( - authService.isBootstrapped() && - vaultService.isRuntimeReady && - configManager.getSettings().security.enableEmergencySecretsBackup - ) { + if (authService.isBootstrapped() && vaultService.isRuntimeReady) { authService.syncRecovery({ snapshotReason: 'backup-restore' }); } wsHub.broadcastAll({ @@ -602,12 +446,7 @@ export async function createGCoordinatorServer( ); app.use( '/api/systems', - createSystemsRouter({ - authService, - auditService, - systemsEngine: customSystemsEngine, - stepUpGuard, - }), + createSystemsRouter({ authService, auditService, systemsEngine: customSystemsEngine }), ); app.use( '/api/workflows', @@ -625,12 +464,12 @@ export async function createGCoordinatorServer( ); app.use( '/api/alerts', - createAlertsRouter({ authService, configManager, auditService, alertEngine, stepUpGuard }), + createAlertsRouter({ authService, configManager, auditService, alertEngine }), ); - app.use('/api/ai', createAiRouter({ authService, aiService, stepUpGuard })); + app.use('/api/ai', createAiRouter({ authService, aiService })); app.use( '/api/servers/:id/sftp', - createSftpRouter({ authService, configManager, auditService, sftpService, stepUpGuard }), + createSftpRouter({ authService, configManager, auditService, sftpService }), ); app.use( '/api/servers', @@ -652,20 +491,9 @@ export async function createGCoordinatorServer( ); app.use( '/api/config', - createConfigRouter({ authService, configManager, auditService, stepUpGuard }), + createConfigRouter({ authService, configManager, auditService }), ); app.use('/api/audit', createAuditRouter(authService, auditService)); - app.get( - '/metrics', - createPrometheusHandler({ - configManager, - vaultService, - sshPool, - monitoringService, - tunnelManager, - alertEngine, - }), - ); app.use('/api', (_req, res) => { res.status(404).json({ error: 'API_ROUTE_NOT_FOUND' }); @@ -680,26 +508,6 @@ export async function createGCoordinatorServer( }); } - app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => { - const statusErr = err as { status?: number; type?: string; message?: string }; - const status = - typeof statusErr?.status === 'number' && statusErr.status >= 400 && statusErr.status < 600 - ? statusErr.status - : 500; - if (!res.headersSent) { - res.status(status).json({ - error: status === 413 || statusErr?.type === 'entity.too.large' - ? 'PAYLOAD_TOO_LARGE' - : status < 500 - ? 'BAD_REQUEST' - : 'INTERNAL_SERVER_ERROR', - message: status < 500 && statusErr?.message ? statusErr.message : 'Internal server error', - }); - } - }); - - await tunnelManager.startProxyServer(); - await new Promise((resolve, reject) => { httpServer.once('error', reject); httpServer.listen(options.port, options.host ?? '0.0.0.0', () => { @@ -730,7 +538,6 @@ export async function createGCoordinatorServer( customSystemsEngine, serverInspector, monitoringService, - backupScheduler, transferEngine, workflowEngine, broadcastService, @@ -738,20 +545,16 @@ export async function createGCoordinatorServer( aiService, wsHub, port: actualPort, - proxyPort: tunnelManager.actualProxyPort, async close() { aiService.close(); - backupScheduler.close(); alertEngine.close(); workflowEngine.close(); broadcastService.cancelAll(); monitoringService.close(); customSystemsEngine.close(); tunnelManager.stopAll(); - await tunnelManager.stopProxyServer(); ptyManager.close(); sshPool.closeAll('shutdown'); - authService.close(); wsHub.close(); await configManager.close(); await new Promise((resolve) => { diff --git a/src/server/automation/broadcast-service.ts b/src/server/automation/broadcast-service.ts index 69d9804..4909164 100644 --- a/src/server/automation/broadcast-service.ts +++ b/src/server/automation/broadcast-service.ts @@ -1,9 +1,7 @@ import crypto from 'node:crypto'; -import type Database from 'better-sqlite3'; import type { ServerWsFrame } from '../../shared/ws-protocol.js'; import type { WsHub } from '../api/ws-hub.js'; import type { ConfigManager } from '../config/config-manager.js'; -import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { AuditService } from '../security/audit.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; @@ -11,8 +9,6 @@ import { BufferedStreamEmitter } from './stream-buffer.js'; import { buildWorkflowEnv, interpolateShellCommandSafe, - maskSecretInputsForStorage, - redactWorkflowSecrets, resolveTargetServers, validateAndResolveInputs, } from './template.js'; @@ -42,14 +38,10 @@ export interface BroadcastJobSummary { interface ActiveBroadcastJob extends BroadcastJobSummary { emitter: BufferedStreamEmitter; abortController: AbortController; - secretValues: string[]; } -function csvSafeCell(val: unknown): string { - const s = val === null || val === undefined ? '' : String(val); - const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s; - return `"${safe.replace(/"/g, '""')}"`; -} +const MAX_RETAINED_BROADCASTS = 25; +const MAX_OUTPUT_PER_SERVER = 256 * 1024; async function runPool( items: T[], @@ -76,8 +68,6 @@ export class BroadcastService { private readonly sshPool: SSHPool, private readonly wsHub: WsHub, private readonly auditService: AuditService, - private readonly db?: Database.Database, - private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} getStreamReplayFrames(jobId: string): ServerWsFrame[] { @@ -86,178 +76,17 @@ export class BroadcastService { getBroadcastResult(jobId: string): BroadcastJobSummary | undefined { const job = this.jobs.get(jobId); - if (job) { - return { - jobId: job.jobId, - snippetId: job.snippetId, - command: job.command, - sudo: job.sudo, - createdAt: job.createdAt, - finishedAt: job.finishedAt, - cancelled: job.cancelled, - done: job.done, - targets: job.targets.map((t) => ({ ...t })), - }; - } - - if (!this.db) return undefined; - const row = this.db - .prepare( - `SELECT job_id AS jobId, command, snippet_id AS snippetId, status, - started_at AS startedAt, finished_at AS finishedAt, results_json AS resultsJson - FROM broadcast_jobs - WHERE job_id = ?`, - ) - .get(jobId) as - | { - jobId: string; - command: string; - snippetId: string | null; - status: string; - startedAt: number; - finishedAt: number | null; - resultsJson: string; - } - | undefined; - if (!row) return undefined; - - let targets: BroadcastTargetResult[] = []; - try { - targets = JSON.parse(row.resultsJson) as BroadcastTargetResult[]; - } catch { - targets = []; - } - + if (!job) return undefined; return { - jobId: row.jobId, - snippetId: row.snippetId ?? undefined, - command: row.command, - sudo: false, - createdAt: row.startedAt, - finishedAt: row.finishedAt, - cancelled: row.status === 'cancelled', - done: row.finishedAt !== null || row.status !== 'running', - targets, - }; - } - - listHistory(limit = 50): Array<{ - jobId: string; - snippetId?: string; - command: string; - status: string; - startedAt: number; - finishedAt: number | null; - targetCount: number; - okCount: number; - }> { - if (!this.db) { - return [...this.jobs.values()] - .sort((a, b) => b.createdAt - a.createdAt) - .slice(0, limit) - .map((j) => ({ - jobId: j.jobId, - snippetId: j.snippetId, - command: j.command, - status: j.cancelled - ? 'cancelled' - : !j.done - ? 'running' - : j.targets.every((t) => t.status === 'ok') - ? 'ok' - : 'error', - startedAt: j.createdAt, - finishedAt: j.finishedAt, - targetCount: j.targets.length, - okCount: j.targets.filter((t) => t.status === 'ok').length, - })); - } - - const safeLimit = Math.max(1, Math.min(200, Math.floor(limit))); - const rows = this.db - .prepare( - `SELECT job_id AS jobId, command, snippet_id AS snippetId, status, - started_at AS startedAt, finished_at AS finishedAt, results_json AS resultsJson - FROM broadcast_jobs - ORDER BY started_at DESC - LIMIT ?`, - ) - .all(safeLimit) as Array<{ - jobId: string; - command: string; - snippetId: string | null; - status: string; - startedAt: number; - finishedAt: number | null; - resultsJson: string; - }>; - - return rows.map((r) => { - const live = this.jobs.get(r.jobId); - const targets = live - ? live.targets - : (() => { - try { - return JSON.parse(r.resultsJson) as BroadcastTargetResult[]; - } catch { - return []; - } - })(); - return { - jobId: r.jobId, - snippetId: r.snippetId ?? undefined, - command: r.command, - status: live - ? live.cancelled - ? 'cancelled' - : !live.done - ? 'running' - : live.targets.every((t) => t.status === 'ok') - ? 'ok' - : 'error' - : r.status, - startedAt: r.startedAt, - finishedAt: live ? live.finishedAt : r.finishedAt, - targetCount: targets.length, - okCount: targets.filter((t) => t.status === 'ok').length, - }; - }); - } - - exportBroadcast( - jobId: string, - format: 'json' | 'csv' = 'json', - ): { contentType: string; filename: string; body: string } | null { - const job = this.getBroadcastResult(jobId); - if (!job) return null; - - if (format === 'csv') { - const header = 'jobId,serverId,serverName,status,exitCode,durationMs,stdout,stderr'; - const rows = job.targets.map((t) => - [ - job.jobId, - t.serverId, - t.serverName, - t.status, - t.exitCode ?? '', - t.durationMs, - t.stdout, - t.stderr, - ] - .map(csvSafeCell) - .join(','), - ); - return { - contentType: 'text/csv; charset=utf-8', - filename: `${job.jobId}.csv`, - body: `${[header, ...rows].join('\n')}\n`, - }; - } - - return { - contentType: 'application/json; charset=utf-8', - filename: `${job.jobId}.json`, - body: JSON.stringify(job, null, 2), + jobId: job.jobId, + snippetId: job.snippetId, + command: job.command, + sudo: job.sudo, + createdAt: job.createdAt, + finishedAt: job.finishedAt, + cancelled: job.cancelled, + done: job.done, + targets: job.targets.map((t) => ({ ...t })), }; } @@ -296,7 +125,6 @@ export class BroadcastService { let rawCommand = opts.command?.trim() ?? ''; let sudo = Boolean(opts.sudo); let resolvedInputs: Record = {}; - let secretValues: string[] = []; if (opts.snippetId) { const snip = this.configManager @@ -306,7 +134,6 @@ export class BroadcastService { throw new Error(`Unknown command snippet "${opts.snippetId}"`); } resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {}); - secretValues = maskSecretInputsForStorage(snip.inputs, resolvedInputs).secretValues; rawCommand = snip.command; sudo = opts.sudo ?? snip.sudo; } else { @@ -314,14 +141,14 @@ export class BroadcastService { throw new Error('Command or snippetId is required for Fleet Broadcast'); } if (opts.inputs) { - resolvedInputs = validateAndResolveInputs([], opts.inputs); + for (const [k, v] of Object.entries(opts.inputs)) { + if (v !== undefined && v !== null) resolvedInputs[k] = String(v); + } } } - const limits = this.getRuntimeLimits?.(); const baseCtx = { inputs: resolvedInputs }; const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx); - const displayCommand = redactWorkflowSecrets(renderedCommand, secretValues); const allServers = this.configManager.listServers(); let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx); @@ -341,11 +168,7 @@ export class BroadcastService { } const jobId = `bcast-${crypto.randomBytes(6).toString('hex')}`; - const emitter = new BufferedStreamEmitter( - this.wsHub, - jobId, - limits?.streamReplayBytes, - ); + const emitter = new BufferedStreamEmitter(this.wsHub, jobId); const abortController = new AbortController(); const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({ @@ -361,7 +184,7 @@ export class BroadcastService { const job: ActiveBroadcastJob = { jobId, snippetId: opts.snippetId, - command: displayCommand, + command: renderedCommand, sudo, createdAt: Date.now(), finishedAt: null, @@ -370,12 +193,9 @@ export class BroadcastService { targets, emitter, abortController, - secretValues, }; this.jobs.set(jobId, job); - this.persistBroadcastRow(job, 'running'); - this.auditService.log({ action: 'broadcast.start', actorIp: opts.actorIp, @@ -391,14 +211,12 @@ export class BroadcastService { emitter.pushMeta({ event: 'start', jobId, - command: displayCommand, + command: renderedCommand, targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })), }); - const maxStepLogBytes = limits?.maxStepLogBytes ?? 256 * 1024; const timeoutMs = (opts.timeoutSec ?? 120) * 1000; - const concurrencyCap = limits?.maxWorkflowStepTargets ?? 32; - const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, concurrencyCap)); + const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, 32)); void runPool(matchedServers, concurrency, async (srv) => { const targetEntry = job.targets.find((t) => t.serverId === srv.id)!; @@ -421,7 +239,6 @@ export class BroadcastService { const env = buildWorkflowEnv({ inputs: resolvedInputs, serverId: srv.id, - serverMeta: { id: srv.id, name: srv.name, host: srv.host, port: srv.port }, }); try { @@ -436,9 +253,9 @@ export class BroadcastService { let errBytes = 0; handle.channel.on('data', (chunk: Buffer) => { - const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues); - if (outBytes < maxStepLogBytes) { - const slice = chunk.subarray(0, maxStepLogBytes - outBytes); + const text = chunk.toString('utf8'); + if (outBytes < MAX_OUTPUT_PER_SERVER) { + const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - outBytes); outChunks.push(slice); outBytes += slice.length; } @@ -452,9 +269,9 @@ export class BroadcastService { }); handle.channel.stderr?.on('data', (chunk: Buffer) => { - const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues); - if (errBytes < maxStepLogBytes) { - const slice = chunk.subarray(0, maxStepLogBytes - errBytes); + const text = chunk.toString('utf8'); + if (errBytes < MAX_OUTPUT_PER_SERVER) { + const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - errBytes); errChunks.push(slice); errBytes += slice.length; } @@ -479,14 +296,8 @@ export class BroadcastService { try { const { exitCode } = await handle.done; - targetEntry.stdout = redactWorkflowSecrets( - Buffer.concat(outChunks).toString('utf8'), - secretValues, - ); - targetEntry.stderr = redactWorkflowSecrets( - Buffer.concat(errChunks).toString('utf8'), - secretValues, - ); + targetEntry.stdout = Buffer.concat(outChunks).toString('utf8'); + targetEntry.stderr = Buffer.concat(errChunks).toString('utf8'); targetEntry.durationMs = Date.now() - started; targetEntry.exitCode = exitCode; @@ -505,10 +316,7 @@ export class BroadcastService { } catch (err) { targetEntry.durationMs = Date.now() - started; targetEntry.status = abortController.signal.aborted ? 'cancelled' : 'error'; - const msg = redactWorkflowSecrets( - err instanceof Error ? err.message : String(err), - secretValues, - ); + const msg = err instanceof Error ? err.message : String(err); targetEntry.stderr = targetEntry.stderr ? `${targetEntry.stderr}\n${msg}` : msg; emitter.push('stderr', `[${srv.id}] ${msg}\n`); } @@ -524,12 +332,6 @@ export class BroadcastService { job.done = true; job.finishedAt = Date.now(); const okCount = job.targets.filter((t) => t.status === 'ok').length; - const finalStatus = job.cancelled - ? 'cancelled' - : okCount === job.targets.length - ? 'ok' - : 'error'; - this.persistBroadcastRow(job, finalStatus); emitter.pushMeta({ event: 'done', cancelled: job.cancelled, @@ -542,33 +344,9 @@ export class BroadcastService { return this.getBroadcastResult(jobId)!; } - private persistBroadcastRow(job: ActiveBroadcastJob, status: string): void { - if (!this.db) return; - this.db - .prepare( - `INSERT INTO broadcast_jobs (job_id, command, snippet_id, targets_json, status, started_at, finished_at, results_json) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) - ON CONFLICT(job_id) DO UPDATE SET - status = excluded.status, - finished_at = excluded.finished_at, - results_json = excluded.results_json`, - ) - .run( - job.jobId, - job.command, - job.snippetId ?? null, - JSON.stringify(job.targets.map((t) => t.serverId)), - status, - job.createdAt, - job.finishedAt, - JSON.stringify(job.targets), - ); - } - private pruneJobs(): void { - const maxRam = Math.max(1, this.getRuntimeLimits?.().maxRamBroadcastJobs ?? 5); const done = [...this.jobs.values()].filter((j) => j.done); - while (done.length > maxRam) { + while (done.length > MAX_RETAINED_BROADCASTS) { const oldest = done.shift()!; this.jobs.delete(oldest.jobId); } diff --git a/src/server/automation/template.ts b/src/server/automation/template.ts index 4dd7b86..a890e2f 100644 --- a/src/server/automation/template.ts +++ b/src/server/automation/template.ts @@ -10,17 +10,13 @@ export interface StepOutputSummary { export interface TemplateContext { workflowId?: string; runId?: string; - triggerSource?: string; serverId?: string; - serverMeta?: { id: string; name: string; host: string; port: number }; inputs: Record; stepOutputs?: Map; captures?: Map; eventMeta?: Record; } -const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']); - export function toEnvIdent(raw: string): string { return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase(); } @@ -31,15 +27,8 @@ export function validateAndResolveInputs( ): Record { const out: Record = {}; - for (const k of Object.keys(supplied)) { - if (FORBIDDEN_KEYS.has(k)) { - throw new Error(`Unsafe input parameter name "${k}"`); - } - } - for (const def of defs) { - if (FORBIDDEN_KEYS.has(def.name)) continue; - const raw = Object.hasOwn(supplied, def.name) ? supplied[def.name] : undefined; + const raw = supplied[def.name]; const hasSupplied = raw !== undefined && raw !== null && raw !== ''; const candidate = hasSupplied ? raw : def.default; @@ -72,9 +61,6 @@ export function validateAndResolveInputs( } const strVal = String(candidate); - if (/[\x00]/.test(strVal)) { - throw new Error(`Input "${def.name}" contains NUL bytes`); - } if (def.type === 'select' && def.options && def.options.length > 0) { if (!def.options.includes(strVal)) { throw new Error( @@ -86,48 +72,14 @@ export function validateAndResolveInputs( } for (const [k, v] of Object.entries(supplied)) { - if (FORBIDDEN_KEYS.has(k)) continue; - if (!Object.hasOwn(out, k) && v !== undefined && v !== null) { - const s = String(v); - if (/[\x00]/.test(s)) { - throw new Error(`Input "${k}" contains NUL bytes`); - } - out[k] = s; + if (!(k in out) && v !== undefined && v !== null) { + out[k] = String(v); } } return out; } -export function maskSecretInputsForStorage( - defs: InputDef[], - resolved: Record, -): { masked: Record; secretValues: string[] } { - const secretKeys = new Set(defs.filter((d) => d.type === 'secret').map((d) => d.name)); - const masked: Record = {}; - const secretValues: string[] = []; - for (const [k, v] of Object.entries(resolved)) { - if (secretKeys.has(k) && v.length > 0) { - masked[k] = '***REDACTED***'; - secretValues.push(v); - } else { - masked[k] = v; - } - } - return { masked, secretValues }; -} - -export function redactWorkflowSecrets(text: string, secretValues: string[]): string { - if (!text || secretValues.length === 0) return text; - let out = text; - for (const sec of secretValues) { - if (sec.length >= 2 && out.includes(sec)) { - out = out.split(sec).join('***REDACTED***'); - } - } - return out; -} - export function buildWorkflowEnv(ctx: TemplateContext): Record { const env: Record = {}; if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId; @@ -135,7 +87,6 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record { if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId; for (const [k, v] of Object.entries(ctx.inputs)) { - if (FORBIDDEN_KEYS.has(k)) continue; env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v; } @@ -155,7 +106,6 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record { if (ctx.eventMeta) { for (const [k, v] of Object.entries(ctx.eventMeta)) { - if (FORBIDDEN_KEYS.has(k)) continue; env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v; } } @@ -163,188 +113,45 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record { return env; } -/** - * Resolve ONLY recognized GCoordinator template namespaces so Go/Docker format - * templates like `{{.Names}}` or `{{json .}}` are left completely untouched. - */ -export function resolveTemplateToken( - rawExpr: string, - ctx: TemplateContext, -): { matched: boolean; value: string } { +function resolveTemplateToken(rawExpr: string, ctx: TemplateContext): string { const expr = rawExpr.trim(); - if (!expr || expr.startsWith('.')) return { matched: false, value: '' }; - const parts = expr.split('.'); - if (parts.some((p) => FORBIDDEN_KEYS.has(p))) { - return { matched: false, value: '' }; + if (expr.startsWith('inputs.')) { + const key = expr.slice('inputs.'.length); + return ctx.inputs[key] ?? ''; } - - if (expr.startsWith('inputs.') || expr.startsWith('input.')) { - const key = expr.slice(expr.indexOf('.') + 1); - if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key)) return { matched: false, value: '' }; - return { - matched: true, - value: Object.hasOwn(ctx.inputs, key) ? ctx.inputs[key]! : '', - }; - } - - if (expr.startsWith('steps.') || expr.startsWith('step.')) { - const rest = expr.slice(expr.indexOf('.') + 1); + if (expr.startsWith('steps.')) { + const rest = expr.slice('steps.'.length); const dot = rest.lastIndexOf('.'); if (dot > 0) { const stepId = rest.slice(0, dot); const field = rest.slice(dot + 1); const out = ctx.stepOutputs?.get(stepId); - if (field === 'stdout') return { matched: true, value: out ? out.stdout.trim() : '' }; - if (field === 'exitCode') { - return { - matched: true, - value: out && out.exitCode !== null ? String(out.exitCode) : '', - }; - } + if (!out) return ''; + if (field === 'stdout') return out.stdout.trim(); + if (field === 'exitCode') return out.exitCode === null ? '' : String(out.exitCode); } - return { matched: false, value: '' }; } - - if (expr.startsWith('captures.') || expr.startsWith('capture.')) { - const key = expr.slice(expr.indexOf('.') + 1); - return { matched: true, value: (ctx.captures?.get(key) ?? '').trim() }; + if (expr.startsWith('captures.')) { + const key = expr.slice('captures.'.length); + return (ctx.captures?.get(key) ?? '').trim(); } - if (expr.startsWith('event.')) { const key = expr.slice('event.'.length); - return { - matched: true, - value: ctx.eventMeta && Object.hasOwn(ctx.eventMeta, key) ? ctx.eventMeta[key]! : '', - }; + return ctx.eventMeta?.[key] ?? ''; } - - if (expr.startsWith('server.')) { - const field = expr.slice('server.'.length); - if (field === 'id') return { matched: true, value: ctx.serverMeta?.id ?? ctx.serverId ?? '' }; - if (field === 'name') return { matched: true, value: ctx.serverMeta?.name ?? '' }; - if (field === 'host') return { matched: true, value: ctx.serverMeta?.host ?? '' }; - if (field === 'port') { - return { - matched: true, - value: ctx.serverMeta ? String(ctx.serverMeta.port) : '', - }; - } - return { matched: false, value: '' }; - } - - if (expr === 'run.id') return { matched: true, value: ctx.runId ?? '' }; - if (expr === 'run.workflowId') return { matched: true, value: ctx.workflowId ?? '' }; - if (expr === 'trigger.source') return { matched: true, value: ctx.triggerSource ?? '' }; - if (expr.startsWith('env.')) { - const key = expr.slice('env.'.length); - const env = buildWorkflowEnv(ctx); - return { matched: true, value: Object.hasOwn(env, key) ? env[key]! : '' }; - } - - if (/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(expr)) { - if (ctx.captures?.has(expr)) { - return { matched: true, value: (ctx.captures.get(expr) ?? '').trim() }; - } - if (Object.hasOwn(ctx.inputs, expr)) { - return { matched: true, value: ctx.inputs[expr]! }; - } - } - - return { matched: false, value: '' }; + return (ctx.captures?.get(expr) ?? ctx.inputs[expr] ?? '').trim(); } export function interpolateValuePlain(template: string, ctx: TemplateContext): string { - return template.replace(/\{\{([^{}]+)\}\}/g, (full, expr: string) => { - const res = resolveTemplateToken(expr, ctx); - return res.matched ? res.value : full; - }); + return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) => + resolveTemplateToken(expr, ctx), + ); } -function escapeDoubleQuotedShell(val: string): string { - return val.replace(/([\\"$`])/g, '\\$1'); -} - -function escapeInsideSingleQuotedShell(val: string): string { - return val.replace(/'/g, "'\\''"); -} - -/** - * Quote-aware shell template substitution: - * - Unquoted `{{token}}`: wrapped in `posixSingleQuote(...)` - * - Inside `'...'`: safely single-quote escaped without outer quotes - * - Inside `"..."`: escaped for `$`, `"`, `\`, `` ` `` - * - Unrecognized `{{.Names}}` Go templates remain byte-for-byte untouched - */ export function interpolateShellCommandSafe(template: string, ctx: TemplateContext): string { - let out = ''; - let quote: 'none' | 'single' | 'double' = 'none'; - let i = 0; - - while (i < template.length) { - const ch = template[i]!; - if (quote === 'none') { - if (ch === '\\' && i + 1 < template.length) { - out += template.slice(i, i + 2); - i += 2; - continue; - } - if (ch === "'") { - quote = 'single'; - out += ch; - i += 1; - continue; - } - if (ch === '"') { - quote = 'double'; - out += ch; - i += 1; - continue; - } - } else if (quote === 'single') { - if (ch === "'") { - quote = 'none'; - out += ch; - i += 1; - continue; - } - } else if (quote === 'double') { - if (ch === '\\' && i + 1 < template.length) { - out += template.slice(i, i + 2); - i += 2; - continue; - } - if (ch === '"') { - quote = 'none'; - out += ch; - i += 1; - continue; - } - } - - if (ch === '{' && template[i + 1] === '{') { - const closeIdx = template.indexOf('}}', i + 2); - if (closeIdx > i + 1) { - const expr = template.slice(i + 2, closeIdx); - const resolved = resolveTemplateToken(expr, ctx); - if (!resolved.matched) { - out += template.slice(i, closeIdx + 2); - } else if (quote === 'single') { - out += escapeInsideSingleQuotedShell(resolved.value); - } else if (quote === 'double') { - out += escapeDoubleQuotedShell(resolved.value); - } else { - out += posixSingleQuote(resolved.value); - } - i = closeIdx + 2; - continue; - } - } - - out += ch; - i += 1; - } - - return out; + return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) => + posixSingleQuote(resolveTemplateToken(expr, ctx)), + ); } export function resolveTargetServers( diff --git a/src/server/automation/transfer-engine.ts b/src/server/automation/transfer-engine.ts index a52b1b8..88acdeb 100644 --- a/src/server/automation/transfer-engine.ts +++ b/src/server/automation/transfer-engine.ts @@ -2,7 +2,6 @@ import crypto from 'node:crypto'; import path from 'node:path'; import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2'; import type { ConfigManager } from '../config/config-manager.js'; -import type { KnownHostsService } from '../ssh/known-hosts.js'; import type { SftpService } from '../ssh/sftp-service.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { posixSingleQuote } from '../ssh/sudo.js'; @@ -16,42 +15,8 @@ export interface TransferResult { durationMs: number; } -const FILE_TYPE_MASK = 0o170000; -const MODE_DIR = 0o040000; -const MODE_REG = 0o100000; - function isDirMode(mode: number): boolean { - return (mode & FILE_TYPE_MASK) === MODE_DIR; -} - -function isRegularMode(mode: number): boolean { - return (mode & FILE_TYPE_MASK) === MODE_REG; -} - -function assertSafeRemotePath(rawPath: string, label: string): string { - const trimmed = rawPath.trim(); - if (!trimmed || /[\x00-\x1f\x7f]/.test(trimmed)) { - throw new Error(`Invalid ${label} path`); - } - const parts = trimmed.split('/'); - if (parts.some((seg) => seg === '..')) { - throw new Error(`${label} path cannot contain ".." traversal segments`); - } - return trimmed; -} - -function sanitizeRsyncExcludes(excludes?: string[]): string[] { - if (!excludes || excludes.length === 0) return []; - const out: string[] = []; - for (const raw of excludes) { - const clean = raw.trim(); - if (!clean) continue; - if (/[\x00-\x1f\x7f]/.test(clean) || clean.startsWith('-')) { - throw new Error(`Invalid rsync exclude pattern: "${clean}"`); - } - out.push(clean); - } - return out; + return (mode & 0o170000) === 0o040000; } function promisifySftp( @@ -81,7 +46,6 @@ export class TransferEngine { private readonly sshPool: SSHPool, private readonly _sftpService: SftpService, private readonly configManager: ConfigManager, - private readonly knownHosts?: KnownHostsService, ) { void this._sftpService; } @@ -90,8 +54,6 @@ export class TransferEngine { mode: 'hub-relayed' | 'direct'; source: { serverId: string; path: string }; destination: { serverId: string; path: string }; - delete?: boolean; - exclude?: string[]; sudo?: boolean; timeoutMs?: number; signal?: AbortSignal; @@ -110,29 +72,12 @@ export class TransferEngine { throw new Error(`Destination server "${opts.destination.serverId}" not found or disabled`); } - const safeSrcPath = assertSafeRemotePath(opts.source.path, 'source'); - const safeDstPath = assertSafeRemotePath(opts.destination.path, 'destination'); const started = Date.now(); const timeoutMs = opts.timeoutMs ?? 600_000; if (opts.mode === 'direct') { - const safeExcludes = sanitizeRsyncExcludes(opts.exclude); - const excludeFlags = safeExcludes - .map((ex) => `--exclude=${posixSingleQuote(ex)} `) - .join(''); - const deleteFlag = opts.delete ? '--delete ' : ''; - const dstTarget = `${dstServer.username}@${dstServer.host}:${safeDstPath}`; - const khLine = this.knownHosts?.getOpenSshKnownHostLine(dstServer); - - let cmd: string; - if (khLine) { - const sshCmd = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$_kh`; - cmd = `_kh=$(mktemp /tmp/.gcoord_kh.XXXXXX) && chmod 600 "$_kh" && trap 'rm -f -- "$_kh"' EXIT && printf '%s\\n' ${posixSingleQuote(khLine)} > "$_kh" && rsync -az -s --stats -e "${sshCmd}" ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`; - } else { - const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`; - cmd = `rsync -az -s --stats -e ${posixSingleQuote(sshOpt)} ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`; - } - + const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`; + const cmd = `rsync -az -e ${posixSingleQuote(sshOpt)} -- ${posixSingleQuote(opts.source.path)} ${posixSingleQuote(`${dstServer.username}@${dstServer.host}:${opts.destination.path}`)}`; opts.onProgress?.(`Running direct rsync on ${srcServer.id}...`); const handle = await this.sshPool.execStream(srcServer.id, cmd, { @@ -212,8 +157,8 @@ export class TransferEngine { return { mode: 'direct', - sourcePath: safeSrcPath, - destinationPath: safeDstPath, + sourcePath: opts.source.path, + destinationPath: opts.destination.path, filesTransferred: 1, bytesTransferred: 0, durationMs: Date.now() - started, @@ -256,21 +201,16 @@ export class TransferEngine { opts.signal?.addEventListener('abort', onAbort, { once: true }); try { - const trimmedDest = safeDstPath; + const trimmedDest = opts.destination.path.trim(); const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/'); - const resolvedSrc = await this.resolveRemotePath(srcSftp, safeSrcPath); - const resolvedDest = await this.resolveRemotePath(dstSftp, safeDstPath); - - const srcStat = await promisifySftp((cb) => srcSftp.lstat(resolvedSrc, cb)); - const srcMode = srcStat.mode ?? 0; - if (!isDirMode(srcMode) && !isRegularMode(srcMode)) { - throw new Error(`Refusing SFTP transfer of non-regular/symlink source "${resolvedSrc}"`); - } + const resolvedSrc = await this.resolveRemotePath(srcSftp, opts.source.path); + const resolvedDest = await this.resolveRemotePath(dstSftp, opts.destination.path); + const srcStat = await promisifySftp((cb) => srcSftp.stat(resolvedSrc, cb)); let filesTransferred = 0; let bytesTransferred = 0; - if (isDirMode(srcMode)) { + if (isDirMode(srcStat.mode ?? 0)) { const dstStat = await promisifySftp((cb) => dstSftp!.stat(resolvedDest, cb)).catch( () => null, ); @@ -314,7 +254,7 @@ export class TransferEngine { dstSftp, resolvedSrc, targetFile, - srcMode || 0o644, + srcStat.mode ?? 0o644, activeStreams, () => timedOutOrAborted, opts.onProgress, @@ -401,21 +341,10 @@ export class TransferEngine { let files = 0; let bytes = 0; for (const entry of entries) { - if ( - entry.filename === '.' || - entry.filename === '..' || - entry.filename.includes('/') || - entry.filename.includes('\0') - ) { - continue; - } + if (entry.filename === '.' || entry.filename === '..') continue; const srcChild = path.posix.join(srcDir, entry.filename); const dstChild = path.posix.join(dstDir, entry.filename); - let mode = entry.attrs.mode ?? 0; - if (mode === 0) { - const ls = await promisifySftp((cb) => srcSftp.lstat(srcChild, cb)).catch(() => null); - mode = ls?.mode ?? 0; - } + const mode = entry.attrs.mode ?? 0; if (isDirMode(mode)) { const sub = await this.copyDirectoryRecursive( @@ -429,7 +358,7 @@ export class TransferEngine { ); files += sub.files; bytes += sub.bytes; - } else if (isRegularMode(mode)) { + } else { const copied = await this.copySingleFile( srcSftp, dstSftp, @@ -442,8 +371,6 @@ export class TransferEngine { ); files += 1; bytes += copied; - } else { - onProgress?.(`Skipping non-regular entry ${srcChild}`); } } return { files, bytes }; diff --git a/src/server/automation/workflow-engine.ts b/src/server/automation/workflow-engine.ts index 7bd8312..8d3a181 100644 --- a/src/server/automation/workflow-engine.ts +++ b/src/server/automation/workflow-engine.ts @@ -1,19 +1,17 @@ import crypto from 'node:crypto'; import type Database from 'better-sqlite3'; import { Cron } from 'croner'; -import type { z } from 'zod'; import type { ServerConfig } from '../../shared/schemas/server.schema.js'; import type { StepDependencySchema, WorkflowConfig, WorkflowStep, } from '../../shared/schemas/workflow.schema.js'; +import type { z } from 'zod'; import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; import type { WsHub } from '../api/ws-hub.js'; import type { ConfigManager } from '../config/config-manager.js'; -import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { AuditService } from '../security/audit.js'; -import { fetchWithEgressGuard } from '../security/egress-guard.js'; import type { VaultService } from '../security/vault.js'; import type { SftpService } from '../ssh/sftp-service.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; @@ -24,10 +22,7 @@ import { buildWorkflowEnv, interpolateShellCommandSafe, interpolateValuePlain, - maskSecretInputsForStorage, - redactWorkflowSecrets, resolveTargetServers, - resolveTemplateToken, validateAndResolveInputs, type StepOutputSummary, type TemplateContext, @@ -118,8 +113,6 @@ interface QueuedRunRequest { workflow: WorkflowConfig; triggerSource: string; inputs: Record; - maskedInputsJson: string; - secretValues: string[]; eventMeta?: Record; actorIp: string; sessionIdHash: string | null; @@ -131,10 +124,9 @@ export type FailureNotifierFn = ( channelId: string, message: string, workflowId: string, - meta?: { title?: string; severity?: 'warn' | 'critical' }, ) => Promise; -const MAX_HTTP_STEP_BYTES = 128 * 1024; +const MAX_OUTPUT_CHARS = 256 * 1024; const MAX_RETAINED_STREAM_RUNS = 30; function normalizeDep(dep: StepDependency): { @@ -145,90 +137,6 @@ function normalizeDep(dep: StepDependency): { return { stepId: dep.stepId, on: dep.on }; } -function unquoteLiteral(raw: string): string { - const s = raw.trim(); - if ( - (s.startsWith("'") && s.endsWith("'") && s.length >= 2) || - (s.startsWith('"') && s.endsWith('"') && s.length >= 2) - ) { - return s.slice(1, -1); - } - return s; -} - -function resolveWhenOperand(raw: string, ctx: TemplateContext): string { - const trimmed = raw.trim(); - if ( - (trimmed.startsWith("'") && trimmed.endsWith("'")) || - (trimmed.startsWith('"') && trimmed.endsWith('"')) - ) { - return unquoteLiteral(trimmed); - } - if (trimmed.startsWith('{{') && trimmed.endsWith('}}')) { - const inner = trimmed.slice(2, -2); - const tok = resolveTemplateToken(inner, ctx); - return tok.matched ? tok.value : ''; - } - const direct = resolveTemplateToken(trimmed, ctx); - if (direct.matched) return direct.value; - return trimmed; -} - -function evaluateStepWhen( - whenExpr: string | undefined, - deps: Array<{ stepId: string; on: 'success' | 'failure' | 'always' }>, - terminalState: Map, - ctx: TemplateContext, -): boolean { - if (!whenExpr) return true; - const expr = whenExpr.trim(); - if (!expr || expr === 'always' || expr === 'true') return true; - if (expr === 'false') return false; - if (expr === 'success') { - return deps.every((d) => terminalState.get(d.stepId) === 'succeeded'); - } - if (expr === 'failure') { - return deps.some((d) => terminalState.get(d.stepId) === 'failed'); - } - - const eqMatch = /^(.+?)\s*(==|!=)\s*(.+)$/.exec(expr); - if (eqMatch) { - const left = resolveWhenOperand(eqMatch[1]!, ctx); - const op = eqMatch[2]!; - const right = resolveWhenOperand(eqMatch[3]!, ctx); - return op === '==' ? left === right : left !== right; - } - - const negated = expr.startsWith('!'); - const inner = negated ? expr.slice(1).trim() : expr; - const val = resolveWhenOperand(inner, ctx).trim().toLowerCase(); - const truthy = val !== '' && val !== 'false' && val !== '0'; - return negated ? !truthy : truthy; -} - -async function readResponseCapped(res: Response, maxBytes = MAX_HTTP_STEP_BYTES): Promise { - if (!res.body) return ''; - const reader = res.body.getReader(); - const chunks: Buffer[] = []; - let total = 0; - try { - while (total < maxBytes) { - const { value, done } = await reader.read(); - if (done || !value) break; - const take = Math.min(value.byteLength, maxBytes - total); - chunks.push(Buffer.from(value.subarray(0, take))); - total += take; - if (total >= maxBytes) { - await reader.cancel().catch(() => undefined); - break; - } - } - } finally { - reader.releaseLock(); - } - return Buffer.concat(chunks).toString('utf8'); -} - async function runWithConcurrency( items: T[], concurrency: number, @@ -245,33 +153,13 @@ async function runWithConcurrency( await Promise.all(workers); } -async function sleepAbortable(ms: number, signal: AbortSignal): Promise { - if (ms <= 0) return; - if (signal.aborted) throw new Error('Cancelled'); - await new Promise((resolve, reject) => { - const onAbort = () => { - clearTimeout(t); - reject(new Error('Cancelled')); - }; - const t = setTimeout(() => { - signal.removeEventListener('abort', onAbort); - resolve(); - }, ms); - t.unref(); - signal.addEventListener('abort', onAbort, { once: true }); - }); -} - export class WorkflowEngine { private readonly cronJobs = new Map(); private readonly activeByWorkflow = new Map(); private readonly queueByWorkflow = new Map(); private readonly runsById = new Map(); - private readonly secretValuesByRun = new Map(); private failureNotifier: FailureNotifierFn | null = null; private closed = false; - private runningSlots = 0; - private readonly slotWaiters: Array<() => void> = []; constructor( private readonly db: Database.Database, @@ -283,7 +171,6 @@ export class WorkflowEngine { private readonly transferEngine: TransferEngine, private readonly wsHub: WsHub, private readonly auditService: AuditService, - private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} setFailureNotifier(fn: FailureNotifierFn): void { @@ -293,14 +180,7 @@ export class WorkflowEngine { getStreamReplayFrames(jobId: string): ServerWsFrame[] { if (!jobId.startsWith('wf:')) return []; const runId = jobId.slice(3); - const control = this.runsById.get(runId); - if (!control) return []; - const secrets = this.secretValuesByRun.get(runId) ?? []; - return control.emitter.getReplayFrames().map((frame) => - frame.type === 'stream:chunk' - ? { ...frame, data: redactWorkflowSecrets(frame.data, secrets) } - : frame, - ); + return this.runsById.get(runId)?.emitter.getReplayFrames() ?? []; } start(): void { @@ -315,31 +195,21 @@ export class WorkflowEngine { for (const wf of this.configManager.listWorkflows()) { if (!wf.enabled || wf.trigger.type !== 'cron') continue; const wfId = wf.id; - try { - const cron = new Cron( - wf.trigger.expression, - { - timezone: wf.trigger.timezone, - protect: true, - unref: true, - }, - () => { - if (this.closed || !this.vaultService.isRuntimeReady) return; - void this.triggerWorkflow(wfId, { - triggerSource: 'cron', - }).catch(() => undefined); - }, - ); - this.cronJobs.set(wfId, cron); - } catch (err) { - this.auditService.log({ - action: 'workflow.cron_error', - actorIp: 'scheduler', - target: wfId, - status: 'error', - details: { message: err instanceof Error ? err.message : String(err) }, - }); - } + const cron = new Cron( + wf.trigger.expression, + { + timezone: wf.trigger.timezone, + protect: true, + unref: true, + }, + () => { + if (this.closed || !this.vaultService.isRuntimeReady) return; + void this.triggerWorkflow(wfId, { + triggerSource: 'cron', + }).catch(() => undefined); + }, + ); + this.cronJobs.set(wfId, cron); } } @@ -361,9 +231,6 @@ export class WorkflowEngine { for (const run of this.activeByWorkflow.values()) { this.cancelRun(run.runId, 'panic_lock'); } - while (this.slotWaiters.length > 0) { - this.slotWaiters.shift()?.(); - } } close(): void { @@ -378,13 +245,6 @@ export class WorkflowEngine { return next ? next.getTime() : null; } - async triggerScheduledCron(workflowId: string): Promise { - const job = this.cronJobs.get(workflowId); - if (!job) return false; - await job.trigger(); - return true; - } - listWorkflowsWithSummary(): Array<{ workflow: WorkflowConfig; nextRunAt: number | null; @@ -462,50 +322,7 @@ export class WorkflowEngine { .all(capped) as WorkflowRunRecord[]; } - getStepLogs( - runId: string, - opts: { stepId?: string; offset?: number; limit?: number } = {}, - ): { logs: WorkflowStepLogRecord[]; total: number } { - const safeOffset = Math.max(0, Math.floor(opts.offset ?? 0)); - const safeLimit = Math.max(1, Math.min(200, Math.floor(opts.limit ?? 50))); - if (opts.stepId) { - const totalRow = this.db - .prepare('SELECT COUNT(*) AS cnt FROM workflow_step_logs WHERE run_id = ? AND step_id = ?') - .get(runId, opts.stepId) as { cnt: number }; - const logs = this.db - .prepare( - `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, - exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, - created_at AS createdAt - FROM workflow_step_logs - WHERE run_id = ? AND step_id = ? - ORDER BY id ASC - LIMIT ? OFFSET ?`, - ) - .all(runId, opts.stepId, safeLimit, safeOffset) as WorkflowStepLogRecord[]; - return { logs, total: totalRow.cnt }; - } - const totalRow = this.db - .prepare('SELECT COUNT(*) AS cnt FROM workflow_step_logs WHERE run_id = ?') - .get(runId) as { cnt: number }; - const logs = this.db - .prepare( - `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, - exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, - created_at AS createdAt - FROM workflow_step_logs - WHERE run_id = ? - ORDER BY id ASC - LIMIT ? OFFSET ?`, - ) - .all(runId, safeLimit, safeOffset) as WorkflowStepLogRecord[]; - return { logs, total: totalRow.cnt }; - } - - getRunDetail( - runId: string, - opts: { includeLogs?: boolean } = {}, - ): { + getRunDetail(runId: string): { run: WorkflowRunRecord; stepLogs: WorkflowStepLogRecord[]; workflow: WorkflowConfig | null; @@ -521,19 +338,16 @@ export class WorkflowEngine { .get(runId) as WorkflowRunRecord | undefined; if (!run) return null; - const stepLogs = - opts.includeLogs === false - ? [] - : (this.db - .prepare( - `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, - exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, - created_at AS createdAt - FROM workflow_step_logs - WHERE run_id = ? - ORDER BY id ASC`, - ) - .all(runId) as WorkflowStepLogRecord[]); + const stepLogs = this.db + .prepare( + `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, + exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, + created_at AS createdAt + FROM workflow_step_logs + WHERE run_id = ? + ORDER BY id ASC`, + ) + .all(runId) as WorkflowStepLogRecord[]; return { run, @@ -614,8 +428,6 @@ export class WorkflowEngine { } const inputs = validateAndResolveInputs(wf.inputs, opts.inputs ?? {}); - const { masked, secretValues } = maskSecretInputsForStorage(wf.inputs, inputs); - const maskedInputsJson = JSON.stringify(masked); const runId = `run-${crypto.randomBytes(6).toString('hex')}`; const now = Date.now(); const depth = opts.onFailureDepth ?? 0; @@ -630,7 +442,7 @@ export class WorkflowEngine { `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) VALUES (?, ?, ?, 'skipped', ?, ?, 'overlap:skip', ?)`, ) - .run(runId, wf.id, opts.triggerSource, now, now, maskedInputsJson); + .run(runId, wf.id, opts.triggerSource, now, now, JSON.stringify(inputs)); this.broadcastRunFrame({ runId, @@ -644,26 +456,19 @@ export class WorkflowEngine { } if (wf.overlapPolicy === 'queue') { - const q = this.queueByWorkflow.get(wf.id) ?? []; - const maxQueue = Math.max(1, this.getRuntimeLimits?.().maxWorkflowQueue ?? 10); - if (q.length >= maxQueue) { - throw new Error(`Workflow "${wf.id}" queue is full (${maxQueue} pending runs)`); - } - this.db .prepare( `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) VALUES (?, ?, ?, 'queued', ?, NULL, NULL, ?)`, ) - .run(runId, wf.id, opts.triggerSource, now, maskedInputsJson); + .run(runId, wf.id, opts.triggerSource, now, JSON.stringify(inputs)); + const q = this.queueByWorkflow.get(wf.id) ?? []; q.push({ runId, workflow: wf, triggerSource: opts.triggerSource, inputs, - maskedInputsJson, - secretValues, eventMeta: opts.eventMeta, actorIp, sessionIdHash, @@ -706,15 +511,13 @@ export class WorkflowEngine { `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) VALUES (?, ?, ?, 'running', ?, NULL, NULL, ?)`, ) - .run(runId, wf.id, opts.triggerSource, now, maskedInputsJson); + .run(runId, wf.id, opts.triggerSource, now, JSON.stringify(inputs)); this.startExecution({ runId, workflow: wf, triggerSource: opts.triggerSource, inputs, - maskedInputsJson, - secretValues, eventMeta: opts.eventMeta, actorIp, sessionIdHash, @@ -767,12 +570,12 @@ export class WorkflowEngine { throw new Error(`Unknown workflow "${String(workflowInput)}"`); } - const rawInputs = validateAndResolveInputs(wf.inputs, suppliedInputs); - const { masked: inputs } = maskSecretInputsForStorage(wf.inputs, rawInputs); + const inputs = validateAndResolveInputs(wf.inputs, suppliedInputs); const allServers = this.configManager.listServers(); const baseCtx: TemplateContext = { workflowId: wf.id, inputs }; const envKeys = Object.keys(buildWorkflowEnv(baseCtx)); + // Compute topological waves matching WorkflowConfigSchema DAG const waveMap = new Map(); const stepById = new Map(wf.steps.map((s) => [s.id, s])); const computeWave = (stepId: string): number => { @@ -829,18 +632,6 @@ export class WorkflowEngine { continue; } - if (step.type === 'http' || step.type === 'notify') { - steps.push({ - stepId: step.id, - type: step.type, - wave, - dependsOn: deps, - targets: [], - envKeys, - }); - continue; - } - const matched = resolveTargetServers(step.target, allServers, baseCtx); const plan: DryRunStepPlan = { stepId: step.id, @@ -884,46 +675,8 @@ export class WorkflowEngine { }; } - private async withGlobalWorkflowSlot( - signal: AbortSignal, - fn: () => Promise, - ): Promise { - const maxConcurrent = Math.max(1, this.getRuntimeLimits?.().maxConcurrentWorkflows ?? 2); - if (this.runningSlots >= maxConcurrent) { - await new Promise((resolve, reject) => { - if (signal.aborted) { - reject(new Error('Cancelled before acquiring workflow execution slot')); - return; - } - const wake = () => { - signal.removeEventListener('abort', onAbort); - resolve(); - }; - const onAbort = () => { - const idx = this.slotWaiters.indexOf(wake); - if (idx >= 0) this.slotWaiters.splice(idx, 1); - reject(new Error('Cancelled while waiting for workflow execution slot')); - }; - this.slotWaiters.push(wake); - signal.addEventListener('abort', onAbort, { once: true }); - }); - } - this.runningSlots += 1; - try { - return await fn(); - } finally { - this.runningSlots = Math.max(0, this.runningSlots - 1); - const next = this.slotWaiters.shift(); - if (next) next(); - } - } - private startExecution(req: QueuedRunRequest): void { - const emitter = new BufferedStreamEmitter( - this.wsHub, - `wf:${req.runId}`, - this.getRuntimeLimits?.().streamReplayBytes, - ); + const emitter = new BufferedStreamEmitter(this.wsHub, `wf:${req.runId}`); const abortController = new AbortController(); const control: ActiveRunControl = { runId: req.runId, @@ -936,7 +689,6 @@ export class WorkflowEngine { this.activeByWorkflow.set(req.workflow.id, control); this.runsById.set(req.runId, control); - this.secretValuesByRun.set(req.runId, req.secretValues); this.auditService.log({ action: 'workflow.start', @@ -962,9 +714,7 @@ export class WorkflowEngine { triggerSource: req.triggerSource, }); - void this.withGlobalWorkflowSlot(abortController.signal, () => - this.executeDag(req, control), - ) + void this.executeDag(req, control) .then((finalStatus) => { control.done = true; control.status = finalStatus; @@ -980,10 +730,7 @@ export class WorkflowEngine { }) .catch((err) => { control.done = true; - const msg = redactWorkflowSecrets( - err instanceof Error ? err.message : String(err), - req.secretValues, - ); + const msg = err instanceof Error ? err.message : String(err); emitter.push('stderr', `${msg}\n`); control.status = abortController.signal.aborted ? 'cancelled' : 'failed'; this.markRunFinished( @@ -1081,21 +828,6 @@ export class WorkflowEngine { } } - if (eligible && step.when) { - const whenCtx: TemplateContext = { - workflowId: wf.id, - runId: req.runId, - triggerSource: req.triggerSource, - inputs: req.inputs, - stepOutputs, - captures, - eventMeta: req.eventMeta, - }; - if (!evaluateStepWhen(step.when, deps, terminalState, whenCtx)) { - eligible = false; - } - } - if (!eligible) { terminalState.set(step.id, 'skipped'); madeProgress = true; @@ -1104,7 +836,7 @@ export class WorkflowEngine { madeProgress = true; const p = (async () => { - const ok = await this.runStepWithRetries( + const ok = await this.runSingleStep( wf, step, allServers, @@ -1161,45 +893,6 @@ export class WorkflowEngine { return hasFatalFailure ? 'failed' : 'succeeded'; } - private async runStepWithRetries( - wf: WorkflowConfig, - step: WorkflowStep, - allServers: ServerConfig[], - req: QueuedRunRequest, - control: ActiveRunControl, - stepOutputs: Map, - captures: Map, - ): Promise { - const maxRetries = Math.max(0, Math.min(5, step.retries ?? 0)); - const backoffMs = Math.max(500, Math.min(300_000, (step.retryBackoffSec ?? 5) * 1000)); - - for (let attempt = 0; attempt <= maxRetries; attempt++) { - const attemptOutcome = await this.runSingleStep( - wf, - step, - allServers, - req, - control, - stepOutputs, - captures, - ); - if (attemptOutcome.ok) return true; - if (attempt >= maxRetries || attemptOutcome.timedOut || control.abortController.signal.aborted) { - return false; - } - control.emitter.push( - 'stderr', - `[${step.id}] Attempt ${attempt + 1}/${maxRetries + 1} failed; retrying in ${Math.round(backoffMs / 1000)}s...\n`, - ); - try { - await sleepAbortable(backoffMs, control.abortController.signal); - } catch { - return false; - } - } - return false; - } - private async handleStepFailure( wf: WorkflowConfig, step: WorkflowStep, @@ -1256,12 +949,12 @@ export class WorkflowEngine { control: ActiveRunControl, stepOutputs: Map, captures: Map, - ): Promise<{ ok: boolean; timedOut: boolean }> { + ): Promise { const timeoutMs = (step.timeoutSec ?? 300) * 1000; const stepAbort = new AbortController(); const onParentAbort = () => stepAbort.abort(); if (control.abortController.signal.aborted) { - return { ok: false, timedOut: false }; + return false; } control.abortController.signal.addEventListener('abort', onParentAbort, { once: true }); @@ -1272,27 +965,16 @@ export class WorkflowEngine { }, timeoutMs); stepTimer.unref(); - const secrets = req.secretValues; - const safeEmit = (stream: 'stdout' | 'stderr', text: string) => { - control.emitter.push(stream, redactWorkflowSecrets(text, secrets)); - }; - - const makeCtx = (srv?: ServerConfig): TemplateContext => ({ + const makeCtx = (serverId?: string): TemplateContext => ({ workflowId: wf.id, runId: req.runId, - triggerSource: req.triggerSource, - serverId: srv?.id, - serverMeta: srv - ? { id: srv.id, name: srv.name, host: srv.host, port: srv.port } - : undefined, + serverId, inputs: req.inputs, stepOutputs, captures, eventMeta: req.eventMeta, }); - const maxTargetCap = Math.max(1, this.getRuntimeLimits?.().maxWorkflowStepTargets ?? 16); - control.emitter.pushMeta({ event: 'step-start', stepId: step.id, type: step.type }); try { @@ -1309,12 +991,12 @@ export class WorkflowEngine { mode: step.mode, source: { serverId: srcServerId, path: srcPath }, destination: { serverId: dstServerId, path: dstPath }, - delete: step.delete, - exclude: step.exclude, sudo: step.sudo, timeoutMs, signal: stepAbort.signal, - onProgress: (msg) => safeEmit('stdout', `[${step.id}] ${msg}\n`), + onProgress: (msg) => { + control.emitter.push('stdout', `[${step.id}] ${msg}\n`); + }, }); const summaryJson = JSON.stringify(xfer); this.recordStepLog( @@ -1325,19 +1007,18 @@ export class WorkflowEngine { xfer.durationMs, summaryJson, '', - secrets, ); stepOutputs.set(step.id, { stdout: xfer.destinationPath, exitCode: 0 }); if (step.captureAs) captures.set(step.captureAs, xfer.destinationPath); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: true }); - return { ok: true, timedOut: false }; + return true; } catch (err) { const msg = timedOut ? `Step "${step.id}" timed out after ${timeoutMs}ms` : err instanceof Error ? err.message : String(err); - safeEmit('stderr', `[${step.id}] ${msg}\n`); + control.emitter.push('stderr', `[${step.id}] ${msg}\n`); this.recordStepLog( req.runId, step.id, @@ -1346,192 +1027,31 @@ export class WorkflowEngine { Date.now() - started, '', msg, - secrets, ); stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return { ok: false, timedOut }; - } - } - - if (step.type === 'http') { - const started = Date.now(); - const ctx = makeCtx(); - const localSecrets = [...secrets]; - try { - const targetUrl = interpolateValuePlain(step.url, ctx).trim(); - let stepSecret: string | undefined; - if (step.secretRef) { - const cred = this.vaultService.getRuntimeSecret(step.secretRef); - if (!cred || (cred.type !== 'api-token' && cred.type !== 'webhook-secret')) { - throw new Error( - `HTTP step secretRef "${step.secretRef}" must be an api-token or webhook-secret`, - ); - } - stepSecret = cred.type === 'api-token' ? cred.token : cred.secret; - if (stepSecret) localSecrets.push(stepSecret); - } - - const headers: Record = {}; - let usedSecretInHeaders = false; - if (step.headers) { - for (const [k, v] of Object.entries(step.headers)) { - let renderedVal = interpolateValuePlain(v, ctx); - if (stepSecret && renderedVal.includes('{{secret}}')) { - renderedVal = renderedVal.split('{{secret}}').join(stepSecret); - usedSecretInHeaders = true; - } - headers[k] = renderedVal; - } - } - if (stepSecret && !usedSecretInHeaders && !Object.keys(headers).some((k) => k.toLowerCase() === 'authorization')) { - headers.Authorization = `Bearer ${stepSecret}`; - } - - let reqBody: string | undefined; - if (step.body !== undefined && step.method !== 'GET') { - reqBody = interpolateValuePlain(step.body, ctx); - if (stepSecret && reqBody.includes('{{secret}}')) { - reqBody = reqBody.split('{{secret}}').join(stepSecret); - } - if (!Object.keys(headers).some((k) => k.toLowerCase() === 'content-type')) { - headers['Content-Type'] = 'application/json'; - } - } - - const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; - const res = await fetchWithEgressGuard( - targetUrl, - { - method: step.method, - headers, - body: reqBody, - signal: stepAbort.signal, - }, - { allowedCidrs, timeoutMs }, - ); - const bodyText = redactWorkflowSecrets( - await readResponseCapped(res, MAX_HTTP_STEP_BYTES), - localSecrets, - ); - const ok = - step.expectedStatus !== undefined ? res.status === step.expectedStatus : res.ok; - - safeEmit(ok ? 'stdout' : 'stderr', `[${step.id}] HTTP ${res.status}\n${bodyText}\n`); - this.recordStepLog( - req.runId, - step.id, - 'http', - ok ? 0 : 1, - Date.now() - started, - bodyText, - ok ? '' : `HTTP status ${res.status}`, - localSecrets, - ); - stepOutputs.set(step.id, { stdout: bodyText, exitCode: ok ? 0 : 1 }); - if (step.captureAs && ok) captures.set(step.captureAs, bodyText.trim()); - control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok }); - return { ok, timedOut: false }; - } catch (err) { - const msg = redactWorkflowSecrets( - timedOut - ? `HTTP step timed out after ${timeoutMs}ms` - : err instanceof Error - ? err.message - : String(err), - localSecrets, - ); - safeEmit('stderr', `[${step.id}] ${msg}\n`); - this.recordStepLog( - req.runId, - step.id, - 'http', - 1, - Date.now() - started, - '', - msg, - localSecrets, - ); - stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); - control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return { ok: false, timedOut }; - } - } - - if (step.type === 'notify') { - const started = Date.now(); - const ctx = makeCtx(); - const title = redactWorkflowSecrets(interpolateValuePlain(step.title, ctx), secrets); - const message = redactWorkflowSecrets(interpolateValuePlain(step.message, ctx), secrets); - if (!this.failureNotifier) { - const msg = 'Alert notification handler is not wired'; - safeEmit('stderr', `[${step.id}] ${msg}\n`); - this.recordStepLog(req.runId, step.id, 'notify', 1, 0, '', msg, secrets); - stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); - control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return { ok: false, timedOut: false }; - } - try { - for (const channelId of step.channelIds) { - await this.failureNotifier(channelId, message, wf.id, { - title, - severity: step.severity, - }); - } - const summary = `Notified channels: ${step.channelIds.join(', ')}`; - safeEmit('stdout', `[${step.id}] ${summary}\n`); - this.recordStepLog( - req.runId, - step.id, - 'notify', - 0, - Date.now() - started, - summary, - '', - secrets, - ); - stepOutputs.set(step.id, { stdout: summary, exitCode: 0 }); - control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: true }); - return { ok: true, timedOut: false }; - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - safeEmit('stderr', `[${step.id}] ${msg}\n`); - this.recordStepLog( - req.runId, - step.id, - 'notify', - 1, - Date.now() - started, - '', - msg, - secrets, - ); - stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); - control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return { ok: false, timedOut: false }; + return false; } } const targets = resolveTargetServers(step.target, allServers, makeCtx()); if (targets.length === 0) { const msg = `No enabled target servers matched step "${step.id}"`; - safeEmit('stderr', `[${step.id}] ${msg}\n`); - this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg, secrets); + control.emitter.push('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg); stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return { ok: false, timedOut: false }; + return false; } if (step.type === 'exec') { let allOk = true; const stdouts: string[] = []; let lastExit: number | null = 0; - let lastNonZero: number | null = null; - const concurrency = Math.min(step.concurrency ?? wf.concurrency, maxTargetCap); - await runWithConcurrency(targets, concurrency, async (srv) => { + await runWithConcurrency(targets, step.concurrency ?? wf.concurrency, async (srv) => { const started = Date.now(); - const ctx = makeCtx(srv); + const ctx = makeCtx(srv.id); const env = buildWorkflowEnv(ctx); const cmd = interpolateShellCommandSafe(step.command, ctx); try { @@ -1539,8 +1059,8 @@ export class WorkflowEngine { env, sudo: step.sudo, signal: stepAbort.signal, - onStdout: (txt) => safeEmit('stdout', `[${step.id}@${srv.id}] ${txt}`), - onStderr: (txt) => safeEmit('stderr', `[${step.id}@${srv.id}] ${txt}`), + onStdout: (txt) => control.emitter.push('stdout', `[${step.id}@${srv.id}] ${txt}`), + onStderr: (txt) => control.emitter.push('stderr', `[${step.id}@${srv.id}] ${txt}`), }); this.recordStepLog( req.runId, @@ -1550,52 +1070,37 @@ export class WorkflowEngine { res.durationMs, res.stdout, res.stderr, - secrets, ); - stdouts.push(redactWorkflowSecrets(res.stdout, secrets)); + stdouts.push(res.stdout); lastExit = res.exitCode; - if (res.exitCode !== 0) { - allOk = false; - lastNonZero = res.exitCode; - } + if (res.exitCode !== 0) allOk = false; } catch (err) { allOk = false; lastExit = 1; - lastNonZero = 1; const msg = timedOut ? `Timed out after ${timeoutMs}ms` : err instanceof Error ? err.message : String(err); - safeEmit('stderr', `[${step.id}@${srv.id}] ${msg}\n`); - this.recordStepLog( - req.runId, - step.id, - srv.id, - 1, - Date.now() - started, - '', - msg, - secrets, - ); + control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); } }); const joined = stdouts.join('\n'); - stepOutputs.set(step.id, { stdout: joined, exitCode: lastNonZero ?? lastExit }); + stepOutputs.set(step.id, { stdout: joined, exitCode: lastExit }); if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); - return { ok: allOk, timedOut }; + return allOk; } if (step.type === 'read-file') { let allOk = true; const contents: string[] = []; - const concurrency = Math.min(wf.concurrency, maxTargetCap); - await runWithConcurrency(targets, concurrency, async (srv) => { + await runWithConcurrency(targets, wf.concurrency, async (srv) => { const started = Date.now(); - const ctx = makeCtx(srv); + const ctx = makeCtx(srv.id); const remotePath = interpolateValuePlain(step.path, ctx); const tailRaw = typeof step.tailLines === 'number' @@ -1605,17 +1110,11 @@ export class WorkflowEngine { : undefined; try { - if (stepAbort.signal.aborted) { - throw new Error('Workflow step aborted'); - } let text = ''; try { const fileRes = await this.sftpService.readTextFile(srv.id, remotePath, { sudo: step.sudo, }); - if (stepAbort.signal.aborted) { - throw new Error('Workflow step aborted'); - } text = fileRes.content; if (tailRaw && Number.isFinite(tailRaw) && tailRaw > 0) { const lines = text.replace(/\n$/, '').split(/\r?\n/); @@ -1638,7 +1137,7 @@ export class WorkflowEngine { } } - safeEmit('stdout', `[${step.id}@${srv.id}] ${text}`); + control.emitter.push('stdout', `[${step.id}@${srv.id}] ${text}`); this.recordStepLog( req.runId, step.id, @@ -1647,23 +1146,13 @@ export class WorkflowEngine { Date.now() - started, text, '', - secrets, ); - contents.push(redactWorkflowSecrets(text, secrets)); + contents.push(text); } catch (err) { allOk = false; const msg = err instanceof Error ? err.message : String(err); - safeEmit('stderr', `[${step.id}@${srv.id}] ${msg}\n`); - this.recordStepLog( - req.runId, - step.id, - srv.id, - 1, - Date.now() - started, - '', - msg, - secrets, - ); + control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); } }); @@ -1671,7 +1160,7 @@ export class WorkflowEngine { stepOutputs.set(step.id, { stdout: joined, exitCode: allOk ? 0 : 1 }); if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); - return { ok: allOk, timedOut }; + return allOk; } // system-action step @@ -1680,22 +1169,21 @@ export class WorkflowEngine { ); if (attachedTargets.length === 0) { const msg = `No matched server has system "${step.systemId}" attached`; - safeEmit('stderr', `[${step.id}] ${msg}\n`); - this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg, secrets); + control.emitter.push('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg); stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return { ok: false, timedOut: false }; + return false; } const system = this.configManager.getSystem(step.systemId); const actionDef = system?.actions.find((a) => a.id === step.action); let allOk = true; const sysOutputs: string[] = []; - const concurrency = Math.min(step.concurrency ?? wf.concurrency, maxTargetCap); - await runWithConcurrency(attachedTargets, concurrency, async (srv) => { + await runWithConcurrency(attachedTargets, step.concurrency ?? wf.concurrency, async (srv) => { const started = Date.now(); - const ctx = makeCtx(srv); + const ctx = makeCtx(srv.id); const itemSpec = interpolateValuePlain(step.item, ctx); const subItemVal = step.subItem ? interpolateValuePlain(step.subItem, ctx) : undefined; @@ -1707,7 +1195,7 @@ export class WorkflowEngine { actionId: step.action, timeoutMs, signal: stepAbort.signal, - onChunk: (st, txt) => safeEmit(st, `[${step.id}@${srv.id}] ${txt}`), + onChunk: (st, txt) => control.emitter.push(st, `[${step.id}@${srv.id}] ${txt}`), }); this.recordStepLog( req.runId, @@ -1717,9 +1205,8 @@ export class WorkflowEngine { res.durationMs, res.stdout, res.stderr, - secrets, ); - sysOutputs.push(redactWorkflowSecrets(res.stdout, secrets)); + sysOutputs.push(res.stdout); if (res.exitCode !== 0) allOk = false; return; } @@ -1743,7 +1230,6 @@ export class WorkflowEngine { Date.now() - started, `No discovered items for ${step.systemId}`, '', - secrets, ); return; } @@ -1758,7 +1244,7 @@ export class WorkflowEngine { timeoutMs, signal: stepAbort.signal, onChunk: (st, txt) => - safeEmit(st, `[${step.id}@${srv.id}/${itemName}] ${txt}`), + control.emitter.push(st, `[${step.id}@${srv.id}/${itemName}] ${txt}`), }); this.recordStepLog( req.runId, @@ -1768,25 +1254,15 @@ export class WorkflowEngine { res.durationMs, res.stdout, res.stderr, - secrets, ); - sysOutputs.push(redactWorkflowSecrets(res.stdout, secrets)); + sysOutputs.push(res.stdout); if (res.exitCode !== 0) allOk = false; } } catch (err) { allOk = false; const msg = err instanceof Error ? err.message : String(err); - safeEmit('stderr', `[${step.id}@${srv.id}] ${msg}\n`); - this.recordStepLog( - req.runId, - step.id, - srv.id, - 1, - Date.now() - started, - '', - msg, - secrets, - ); + control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); } }); @@ -1794,7 +1270,7 @@ export class WorkflowEngine { stepOutputs.set(step.id, { stdout: joined, exitCode: allOk ? 0 : 1 }); if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); - return { ok: allOk, timedOut }; + return allOk; } finally { clearTimeout(stepTimer); control.abortController.signal.removeEventListener('abort', onParentAbort); @@ -1816,7 +1292,6 @@ export class WorkflowEngine { throw new Error('Workflow step aborted'); } - const maxBytes = this.getRuntimeLimits?.().maxStepLogBytes ?? 256 * 1024; const started = Date.now(); const handle = await this.sshPool.execStream(serverId, command, { env: opts.env, @@ -1849,15 +1324,15 @@ export class WorkflowEngine { opts.signal.addEventListener('abort', onAbort, { once: true }); handle.channel.on('data', (chunk: Buffer) => { - if (outLen < maxBytes) { - outChunks.push(chunk.subarray(0, maxBytes - outLen)); + if (outLen < MAX_OUTPUT_CHARS) { + outChunks.push(chunk.subarray(0, MAX_OUTPUT_CHARS - outLen)); outLen += chunk.length; } opts.onStdout?.(chunk.toString('utf8')); }); handle.channel.stderr?.on('data', (chunk: Buffer) => { - if (errLen < maxBytes) { - errChunks.push(chunk.subarray(0, maxBytes - errLen)); + if (errLen < MAX_OUTPUT_CHARS) { + errChunks.push(chunk.subarray(0, MAX_OUTPUT_CHARS - errLen)); errLen += chunk.length; } opts.onStderr?.(chunk.toString('utf8')); @@ -1894,11 +1369,7 @@ export class WorkflowEngine { durationMs: number, stdout: string, stderr: string, - secrets: string[] = [], ): void { - const maxLog = this.getRuntimeLimits?.().maxStepLogBytes ?? 256 * 1024; - const cleanOut = redactWorkflowSecrets(stdout, secrets).slice(0, maxLog); - const cleanErr = redactWorkflowSecrets(stderr, secrets).slice(0, maxLog); this.db .prepare( `INSERT INTO workflow_step_logs (run_id, step_id, server_id, exit_code, duration_ms, stdout, stderr, created_at) @@ -1910,8 +1381,8 @@ export class WorkflowEngine { serverId, exitCode, Math.max(0, Math.round(durationMs)), - cleanOut, - cleanErr, + stdout.slice(0, MAX_OUTPUT_CHARS), + stderr.slice(0, MAX_OUTPUT_CHARS), Date.now(), ); } @@ -1962,7 +1433,6 @@ export class WorkflowEngine { while (doneRuns.length > MAX_RETAINED_STREAM_RUNS) { const oldest = doneRuns.shift()!; this.runsById.delete(oldest.runId); - this.secretValuesByRun.delete(oldest.runId); } } } diff --git a/src/server/config/config-manager.ts b/src/server/config/config-manager.ts index c23a4ba..14bed4c 100644 --- a/src/server/config/config-manager.ts +++ b/src/server/config/config-manager.ts @@ -351,7 +351,7 @@ export class ConfigManager { const channelIds = new Set(this.alerts.channels.map((c) => c.id)); if (this.vault && this.vault.isRuntimeReady) { for (const ch of this.alerts.channels) { - if (ch.secretRef && !this.vault.hasCredential(ch.secretRef)) { + if (!this.vault.hasCredential(ch.secretRef)) { next.push({ filePath: 'alerts.json', code: 'MISSING_CHANNEL_SECRET', @@ -368,21 +368,6 @@ export class ConfigManager { } } - for (const ch of this.alerts.channels) { - if ( - ch.url && - /(discord\.com\/api\/webhooks\/|api\.telegram\.org\/bot|[?&](token|key|secret|password)=)/i.test( - ch.url, - ) - ) { - next.push({ - filePath: 'alerts.json', - code: 'ALERT_INLINE_SECRET', - message: `Alert channel "${ch.id}" URL appears to contain an inline token/secret; store secrets in Vault via secretRef instead.`, - }); - } - } - for (const rule of this.alerts.rules) { for (const cid of rule.channelIds) { if (!channelIds.has(cid)) { @@ -619,7 +604,6 @@ export class ConfigManager { ignoreInitial: true, persistent: true, depth: 2, - followSymlinks: false, }); const scheduleReload = (absPath: string, kind: 'upsert' | 'unlink') => { @@ -829,39 +813,11 @@ export class ConfigManager { } private resolveSafeAbsPath(relPath: string): string { + const resolved = path.resolve(this.configDir, relPath); const root = path.resolve(this.configDir); - const resolved = path.resolve(root, relPath); if (!resolved.startsWith(`${root}${path.sep}`)) { throw new Error(`Path escapes config directory: ${relPath}`); } - - // Verify no symlinked directory/file components inside configDir - let cur = root; - const parts = path.relative(root, resolved).split(path.sep).filter(Boolean); - for (const part of parts) { - cur = path.join(cur, part); - if (fs.existsSync(cur)) { - const lstat = fs.lstatSync(cur); - if (lstat.isSymbolicLink()) { - throw new Error(`Symlinks are not allowed inside config directory: ${relPath}`); - } - } - } - - if (fs.existsSync(root)) { - const realRoot = fs.realpathSync(root); - let checkPath = resolved; - while (!fs.existsSync(checkPath) && checkPath !== root) { - checkPath = path.dirname(checkPath); - } - if (fs.existsSync(checkPath)) { - const realTarget = fs.realpathSync(checkPath); - if (realTarget !== realRoot && !realTarget.startsWith(`${realRoot}${path.sep}`)) { - throw new Error(`Realpath escapes config directory: ${relPath}`); - } - } - } - return resolved; } @@ -942,8 +898,8 @@ export class ConfigManager { } private writeAtomicFile(absPath: string, content: string): void { - fs.mkdirSync(path.dirname(absPath), { recursive: true, mode: 0o700 }); - const tmpPath = `${absPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; + fs.mkdirSync(path.dirname(absPath), { recursive: true }); + const tmpPath = `${absPath}.tmp.${process.pid}.${Date.now()}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, content, 'utf8'); diff --git a/src/server/config/presets.ts b/src/server/config/presets.ts index 5579fa3..da391d8 100644 --- a/src/server/config/presets.ts +++ b/src/server/config/presets.ts @@ -138,12 +138,12 @@ export const PRESET_SYSTEMS: SystemConfig[] = [ discovery: { type: 'command', command: - 'systemctl list-units --type=service --all --no-pager --no-legend --plain | awk \'NF && $1 !~ /^UNIT$/ {print $1}\' | { if [ -n "$GCOORD_PARAM_UNITFILTER" ]; then grep -E -- "$GCOORD_PARAM_UNITFILTER" || true; else cat; fi; }', + 'systemctl list-units --type=service --all --no-pager --no-legend --plain | awk \'{print $1}\' | { if [ -n "$GCOORD_PARAM_UNITFILTER" ]; then grep -E "$GCOORD_PARAM_UNITFILTER" || true; else cat; fi; }', parser: 'lines', }, status: { command: - 'systemctl show "$GCOORD_ITEM_NAME" --property=Id,LoadState,ActiveState,SubState,MainPID,FragmentPath,DropInPaths --no-pager | awk -F= \'BEGIN{printf "{"} NR>1{printf ","} {key=$1; sub(/^[^=]*=/,""); gsub(/\\\\/,"\\\\\\\\"); gsub(/"/,"\\\\\""); gsub(/\\t/," "); printf "\\"%s\\":\\"%s\\"",key,$0} END{printf "}\\n"}\'', + 'systemctl show "$GCOORD_ITEM_NAME" --property=Id,LoadState,ActiveState,SubState,MainPID --no-pager | awk -F= \'BEGIN{printf "{"} NR>1{printf ","} {gsub(/"/,"\\\\\"",$2); printf "\\"%s\\":\\"%s\\"",$1,$2} END{printf "}\\n"}\'', parser: 'json', health: { field: 'ActiveState', @@ -322,10 +322,7 @@ export function seedDefaultConfigs(configDir: string): string[] { for (const [relPath, obj] of defaults) { const absPath = path.join(configDir, relPath); if (!fs.existsSync(absPath)) { - fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, { - encoding: 'utf8', - mode: 0o600, - }); + fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, 'utf8'); created.push(relPath); } } diff --git a/src/server/config/runtime-limits.ts b/src/server/config/runtime-limits.ts deleted file mode 100644 index 5c30c30..0000000 --- a/src/server/config/runtime-limits.ts +++ /dev/null @@ -1,132 +0,0 @@ -import type { ThrottleMode } from '../../shared/schemas/settings.schema.js'; - -export interface RuntimeLimits { - mode: ThrottleMode; - argon2MemoryCost: number; - argon2Concurrency: number; - argon2MaxQueue: number; - scryptConcurrency: number; - backupMaxGunzipBytes: number; - backupMaxBodyBytes: number; - sqliteCacheKb: number; - sqliteMmapBytes: number; - sqliteTempStore: 'FILE' | 'MEMORY'; - maxActivePtys: number; - maxRetainedExitedPtys: number; - defaultPtyScrollbackBytes: number; - maxConcurrentMetricPolls: number; - staggerPolls: boolean; - maxParallelSystemInspect: number; - maxSystemCacheEntries: number; - maxConcurrentWorkflows: number; - maxWorkflowStepTargets: number; - maxWorkflowQueue: number; - maxStepLogBytes: number; - streamReplayBytes: number; - maxRamBroadcastJobs: number; - maxConcurrentAiStreams: number; - maxTunnelSocketsPerTunnel: number; - maxGlobalTunnelSockets: number; -} - -const PRESETS: Record = { - 'low-resource': { - mode: 'low-resource', - argon2MemoryCost: 32768, - argon2Concurrency: 1, - argon2MaxQueue: 8, - scryptConcurrency: 1, - backupMaxGunzipBytes: 16 * 1024 * 1024, - backupMaxBodyBytes: 8 * 1024 * 1024, - sqliteCacheKb: 8000, - sqliteMmapBytes: 0, - sqliteTempStore: 'FILE', - maxActivePtys: 12, - maxRetainedExitedPtys: 5, - defaultPtyScrollbackBytes: 262144, - maxConcurrentMetricPolls: 4, - staggerPolls: true, - maxParallelSystemInspect: 2, - maxSystemCacheEntries: 64, - maxConcurrentWorkflows: 2, - maxWorkflowStepTargets: 4, - maxWorkflowQueue: 10, - maxStepLogBytes: 131072, - streamReplayBytes: 65536, - maxRamBroadcastJobs: 5, - maxConcurrentAiStreams: 2, - maxTunnelSocketsPerTunnel: 64, - maxGlobalTunnelSockets: 256, - }, - balanced: { - mode: 'balanced', - argon2MemoryCost: 65536, - argon2Concurrency: 2, - argon2MaxQueue: 16, - scryptConcurrency: 2, - backupMaxGunzipBytes: 32 * 1024 * 1024, - backupMaxBodyBytes: 16 * 1024 * 1024, - sqliteCacheKb: 32000, - sqliteMmapBytes: 0, - sqliteTempStore: 'FILE', - maxActivePtys: 32, - maxRetainedExitedPtys: 12, - defaultPtyScrollbackBytes: 524288, - maxConcurrentMetricPolls: 12, - staggerPolls: true, - maxParallelSystemInspect: 4, - maxSystemCacheEntries: 128, - maxConcurrentWorkflows: 6, - maxWorkflowStepTargets: 12, - maxWorkflowQueue: 25, - maxStepLogBytes: 262144, - streamReplayBytes: 131072, - maxRamBroadcastJobs: 15, - maxConcurrentAiStreams: 6, - maxTunnelSocketsPerTunnel: 128, - maxGlobalTunnelSockets: 512, - }, - unthrottled: { - mode: 'unthrottled', - argon2MemoryCost: 65536, - argon2Concurrency: 4, - argon2MaxQueue: 32, - scryptConcurrency: 4, - backupMaxGunzipBytes: 64 * 1024 * 1024, - backupMaxBodyBytes: 32 * 1024 * 1024, - sqliteCacheKb: 64000, - sqliteMmapBytes: 134217728, - sqliteTempStore: 'MEMORY', - maxActivePtys: 128, - maxRetainedExitedPtys: 30, - defaultPtyScrollbackBytes: 524288, - maxConcurrentMetricPolls: 0, - staggerPolls: false, - maxParallelSystemInspect: 16, - maxSystemCacheEntries: 512, - maxConcurrentWorkflows: 32, - maxWorkflowStepTargets: 0, - maxWorkflowQueue: 100, - maxStepLogBytes: 524288, - streamReplayBytes: 262144, - maxRamBroadcastJobs: 25, - maxConcurrentAiStreams: 16, - maxTunnelSocketsPerTunnel: 512, - maxGlobalTunnelSockets: 2048, - }, -}; - -export function normalizeThrottleMode(raw: string | undefined): ThrottleMode | undefined { - if (raw === 'low-resource' || raw === 'balanced' || raw === 'unthrottled') { - return raw; - } - return undefined; -} - -export function resolveRuntimeLimits( - mode: ThrottleMode = 'low-resource', - envOverride?: string, -): RuntimeLimits { - const effective = normalizeThrottleMode(envOverride) ?? mode; - return PRESETS[effective] ?? PRESETS['low-resource']; -} diff --git a/src/server/db/database.ts b/src/server/db/database.ts index b9f2fd5..0e1fedc 100644 --- a/src/server/db/database.ts +++ b/src/server/db/database.ts @@ -1,62 +1,26 @@ import fs from 'node:fs'; import path from 'node:path'; import Database from 'better-sqlite3'; -import type { RuntimeLimits } from '../config/runtime-limits.js'; import { migration001Initial, type Migration } from './migrations/001_initial.js'; import { migration002MultiAuth } from './migrations/002_multi_auth.js'; import { migration003Phase4Meta } from './migrations/003_phase4_meta.js'; -import { migration004V11 } from './migrations/004_v1_1.js'; const MIGRATIONS: Migration[] = [ migration001Initial, migration002MultiAuth, migration003Phase4Meta, - migration004V11, ]; -function chmodBestEffort(targetPath: string, mode: number): void { - try { - if (fs.existsSync(targetPath)) { - fs.chmodSync(targetPath, mode); - } - } catch { - // Best effort on filesystems without POSIX permissions - } -} - -export function applyDatabaseThrottlePragmas( - db: Database.Database, - limits: Pick, -): void { - const cacheKb = Math.max(2000, Math.floor(limits.sqliteCacheKb)); - const mmapBytes = Math.max(0, Math.floor(limits.sqliteMmapBytes)); - const tempStore = limits.sqliteTempStore === 'MEMORY' ? 'MEMORY' : 'FILE'; - db.pragma(`cache_size = -${cacheKb}`); - db.pragma(`mmap_size = ${mmapBytes}`); - db.pragma(`temp_store = ${tempStore}`); -} - export function openDatabase(dbPath: string): Database.Database { - const parentDir = path.dirname(dbPath); - fs.mkdirSync(parentDir, { recursive: true, mode: 0o700 }); - chmodBestEffort(parentDir, 0o700); + fs.mkdirSync(path.dirname(dbPath), { recursive: true }); const db = new Database(dbPath); db.pragma('journal_mode = WAL'); db.pragma('synchronous = NORMAL'); db.pragma('foreign_keys = ON'); db.pragma('busy_timeout = 5000'); - db.pragma('secure_delete = ON'); - db.pragma('cache_size = -8000'); - db.pragma('mmap_size = 0'); - db.pragma('temp_store = FILE'); - db.pragma('wal_autocheckpoint = 1000'); - db.pragma('journal_size_limit = 16777216'); runMigrations(db); - chmodBestEffort(dbPath, 0o600); - chmodBestEffort(`${dbPath}-wal`, 0o600); - chmodBestEffort(`${dbPath}-shm`, 0o600); return db; } diff --git a/src/server/db/migrations/004_v1_1.ts b/src/server/db/migrations/004_v1_1.ts deleted file mode 100644 index fde7645..0000000 --- a/src/server/db/migrations/004_v1_1.ts +++ /dev/null @@ -1,65 +0,0 @@ -import type Database from 'better-sqlite3'; -import type { Migration } from './001_initial.js'; - -export const migration004V11: Migration = { - id: '004_v1_1', - up(db: Database.Database) { - db.exec(` - ALTER TABLE admin_totps ADD COLUMN last_used_step INTEGER; - ALTER TABLE admin_totps ADD COLUMN secret_enc TEXT; - - UPDATE admin_totps - SET last_used_step = CASE - WHEN last_login_step IS NOT NULL AND last_stepup_step IS NOT NULL THEN MAX(last_login_step, last_stepup_step) - WHEN last_login_step IS NOT NULL THEN last_login_step - ELSE last_stepup_step - END; - - UPDATE admin_users - SET password_hash = '', totp_secret = '' - WHERE EXISTS (SELECT 1 FROM admin_passwords); - - CREATE TABLE IF NOT EXISTS rate_limits ( - scope_key TEXT PRIMARY KEY, - failures INTEGER NOT NULL, - locked_until INTEGER NOT NULL, - updated_at INTEGER NOT NULL - ); - - CREATE TABLE IF NOT EXISTS known_hosts_v2 ( - host_port TEXT NOT NULL, - algorithm TEXT NOT NULL, - fingerprint TEXT NOT NULL, - trusted_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL, - PRIMARY KEY (host_port, algorithm) - ); - - INSERT OR IGNORE INTO known_hosts_v2 (host_port, algorithm, fingerprint, trusted_at, updated_at) - SELECT host_port, algorithm, fingerprint, trusted_at, updated_at FROM known_hosts; - - DROP TABLE known_hosts; - ALTER TABLE known_hosts_v2 RENAME TO known_hosts; - - ALTER TABLE metrics_rollup ADD COLUMN net_rx_avg_bps REAL NOT NULL DEFAULT 0; - ALTER TABLE metrics_rollup ADD COLUMN net_tx_avg_bps REAL NOT NULL DEFAULT 0; - ALTER TABLE metrics_rollup ADD COLUMN disk_max_pct REAL NOT NULL DEFAULT 0; - - CREATE TABLE IF NOT EXISTS broadcast_jobs ( - job_id TEXT PRIMARY KEY, - command TEXT NOT NULL, - snippet_id TEXT, - targets_json TEXT NOT NULL, - status TEXT NOT NULL, - started_at INTEGER NOT NULL, - finished_at INTEGER, - results_json TEXT NOT NULL - ); - CREATE INDEX IF NOT EXISTS idx_broadcast_jobs_ts ON broadcast_jobs(started_at DESC); - - CREATE INDEX IF NOT EXISTS idx_audit_status ON audit_log(status); - CREATE INDEX IF NOT EXISTS idx_audit_ip ON audit_log(actor_ip); - CREATE INDEX IF NOT EXISTS idx_audit_target ON audit_log(target); - `); - }, -}; diff --git a/src/server/index.ts b/src/server/index.ts index 8e1a56b..fbe1059 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -1,27 +1,14 @@ import path from 'node:path'; import { createGCoordinatorServer } from './app.js'; -import { normalizeThrottleMode } from './config/runtime-limits.js'; - -function parseCsvList(raw: string | undefined): string[] | undefined { - if (!raw || !raw.trim()) return undefined; - const list = raw - .split(',') - .map((s) => s.trim()) - .filter(Boolean); - return list.length > 0 ? list : undefined; -} async function main(): Promise { const dataDir = path.resolve(process.env.GCOORD_DATA_DIR ?? './data'); const port = Number(process.env.PORT ?? 3000); const host = process.env.HOST ?? '0.0.0.0'; const trustCloudflare = process.env.TRUST_CLOUDFLARE === 'true'; - const trustedProxyCidrs = parseCsvList(process.env.TRUSTED_PROXY_CIDRS); const secretFilePath = process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; const envMasterKey = process.env.GCOORD_MASTER_KEY; - const envDbKey = process.env.GCOORD_DB_KEY; - const proxyPortRaw = process.env.GCOORD_PROXY_PORT ? Number(process.env.GCOORD_PROXY_PORT) : undefined; const instance = await createGCoordinatorServer({ dataDir, @@ -29,17 +16,7 @@ async function main(): Promise { host, secretFilePath, envMasterKey, - envDbKey, trustCloudflare, - trustedProxyCidrs, - allowLanTunnels: process.env.GCOORD_ALLOW_LAN_TUNNELS === 'true', - proxyBaseDomain: process.env.GCOORD_PROXY_BASE_DOMAIN?.trim() || undefined, - proxyPort: proxyPortRaw && Number.isFinite(proxyPortRaw) ? proxyPortRaw : undefined, - webauthnRpId: process.env.GCOORD_WEBAUTHN_RP_ID?.trim() || undefined, - webauthnOrigins: parseCsvList(process.env.GCOORD_WEBAUTHN_ORIGINS), - metricsToken: process.env.GCOORD_METRICS_TOKEN?.trim() || undefined, - throttleModeOverride: normalizeThrottleMode(process.env.GCOORD_THROTTLE_MODE), - autoKeyFile: process.env.GCOORD_AUTO_KEYFILE === 'true', }); console.log( diff --git a/src/server/monitoring/collectors.ts b/src/server/monitoring/collectors.ts index 5faee22..b1a7220 100644 --- a/src/server/monitoring/collectors.ts +++ b/src/server/monitoring/collectors.ts @@ -56,67 +56,20 @@ export const LINUX_METRIC_CMD = [ ].join('; '); export const BSD_METRIC_CMD = [ - 'printf "===SYSCTL===\\n"; sysctl hw.physmem hw.pagesize vm.loadavg kern.boottime kern.cp_time 2>/dev/null || true', + 'printf "===SYSCTL===\\n"; sysctl -n hw.physmem hw.pagesize vm.loadavg kern.boottime kern.cp_time 2>/dev/null', 'printf "===VMSTAT===\\n"; vmstat -H 2>/dev/null || vmstat', 'printf "===NET===\\n"; netstat -ibn 2>/dev/null', 'printf "===DF===\\n"; df -kT 2>/dev/null || df -kP', ].join('; '); export const MACOS_METRIC_CMD = [ - 'printf "===SYSCTL===\\n"; sysctl hw.memsize hw.pagesize vm.loadavg kern.boottime 2>/dev/null || true', + 'printf "===SYSCTL===\\n"; sysctl -n hw.memsize hw.pagesize vm.loadavg kern.boottime', 'printf "===VMSTAT===\\n"; vm_stat', 'printf "===TOP===\\n"; top -l 1 -n 0 2>/dev/null | grep -i "CPU usage" || true', 'printf "===NET===\\n"; netstat -ibn 2>/dev/null || netstat -ib', 'printf "===DF===\\n"; df -kP', ].join('; '); -const VIRTUAL_NIC_PREFIXES = [ - 'lo', - 'veth', - 'docker', - 'br-', - 'tun', - 'tap', - 'wg', - 'virbr', - 'dummy', - 'cilium', - 'flannel', - 'cni', - 'vxlan', - 'ifb', -]; - -function isVirtualNic(iface: string): boolean { - const clean = iface.trim().replace(/:$/, '').toLowerCase(); - return VIRTUAL_NIC_PREFIXES.some( - (p) => clean === p || (p.endsWith('-') ? clean.startsWith(p) : clean.startsWith(p)), - ); -} - -/** - * Parse `sysctl` sections supporting both `key: val` / `key=val` (resilient to - * missing keys across BSD/macOS versions) and legacy unlabeled positional lines. - */ -function parseSysctlMap(rawText: string, positionalKeys: string[]): Map { - const out = new Map(); - const lines = rawText - .split(/\r?\n/) - .map((l) => l.trim()) - .filter(Boolean); - let posIdx = 0; - for (const line of lines) { - const kv = /^([a-zA-Z][a-zA-Z0-9_.]*)\s*[:=]\s*(.+)$/.exec(line); - if (kv) { - out.set(kv[1]!, kv[2]!.trim()); - } else if (posIdx < positionalKeys.length) { - out.set(positionalKeys[posIdx]!, line); - posIdx += 1; - } - } - return out; -} - function splitSections(stdout: string): Record { const sections: Record = {}; let current = ''; @@ -184,7 +137,6 @@ function parseDfLines( if ( fsName === 'devfs' || fsName === 'map' || - fsName.startsWith('/dev/loop') || !Number.isFinite(totalKb) || totalKb <= 0 ) { @@ -253,12 +205,9 @@ export function parseLinuxOutput( Math.floor(Number((sec.UPTIME ?? '0').trim().split(/\s+/)[0]) || 0), ); - // Network RX/TX prioritizing physical NICs and excluding loopback/virtual bridges - let physRxBytes = 0; - let physTxBytes = 0; - let hasPhys = false; - let fallbackRxBytes = 0; - let fallbackTxBytes = 0; + // Network RX/TX across non-loopback interfaces + let netRxBytes = 0; + let netTxBytes = 0; for (const line of (sec.NET ?? '').split(/\r?\n/)) { const colon = line.indexOf(':'); if (colon <= 0) continue; @@ -266,19 +215,10 @@ export function parseLinuxOutput( if (iface === 'lo' || iface.startsWith('lo:')) continue; const cols = line.slice(colon + 1).trim().split(/\s+/); if (cols.length >= 9) { - const rx = Number(cols[0]) || 0; - const tx = Number(cols[8]) || 0; - fallbackRxBytes += rx; - fallbackTxBytes += tx; - if (!isVirtualNic(iface)) { - hasPhys = true; - physRxBytes += rx; - physTxBytes += tx; - } + netRxBytes += Number(cols[0]) || 0; + netTxBytes += Number(cols[8]) || 0; } } - const netRxBytes = hasPhys ? physRxBytes : fallbackRxBytes; - const netTxBytes = hasPhys ? physTxBytes : fallbackTxBytes; let netRxBps = 0; let netTxBps = 0; @@ -327,28 +267,25 @@ export function parseBsdOutput( nowMs = Date.now(), ): CollectOutput { const sec = splitSections(stdout); - const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [ - 'hw.physmem', - 'hw.pagesize', - 'vm.loadavg', - 'kern.boottime', - 'kern.cp_time', - ]); + const sysctlLines = (sec.SYSCTL ?? '') + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); - const physMemBytes = Number(sysctl.get('hw.physmem')) || 0; - const pageSize = Number(sysctl.get('hw.pagesize')) || 4096; - const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0'); + const physMemBytes = Number(sysctlLines[0]) || 0; + const pageSize = Number(sysctlLines[1]) || 4096; + const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0'); const load1m = round2(Number(loadMatch?.[1] ?? 0)); let uptimeSec = 0; - const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctl.get('kern.boottime') ?? ''); + const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? ''); if (bootSecMatch) { uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!)); } let cpuTotal = 0; let cpuIdle = 0; - const cpNums = (sysctl.get('kern.cp_time') ?? '') + const cpNums = (sysctlLines[4] ?? '') .split(/\s+/) .map((n) => Number(n) || 0); if (cpNums.length >= 5) { @@ -432,20 +369,18 @@ export function parseMacOsOutput( nowMs = Date.now(), ): CollectOutput { const sec = splitSections(stdout); - const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [ - 'hw.memsize', - 'hw.pagesize', - 'vm.loadavg', - 'kern.boottime', - ]); + const sysctlLines = (sec.SYSCTL ?? '') + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); - const memBytes = Number(sysctl.get('hw.memsize')) || 0; - const pageSize = Number(sysctl.get('hw.pagesize')) || 4096; - const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0'); + const memBytes = Number(sysctlLines[0]) || 0; + const pageSize = Number(sysctlLines[1]) || 4096; + const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0'); const load1m = round2(Number(loadMatch?.[1] ?? 0)); let uptimeSec = 0; - const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctl.get('kern.boottime') ?? ''); + const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? ''); if (bootSecMatch) { uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!)); } diff --git a/src/server/monitoring/inspector.ts b/src/server/monitoring/inspector.ts index 3246dcc..518de1a 100644 --- a/src/server/monitoring/inspector.ts +++ b/src/server/monitoring/inspector.ts @@ -26,30 +26,25 @@ export interface ServerInspectionResult { serverId: string; os: OsType; collectedAt: number; - sort: 'cpu' | 'mem'; processes: ProcessEntry[]; ports: PortEntry[]; thermals: ThermalEntry[]; } -function buildLinuxInspectCmd(sort: 'cpu' | 'mem'): string { - const linuxSort = sort === 'mem' ? '-rss' : '-%cpu'; - const bsdFlag = sort === 'mem' ? '-m' : '-r'; - return [ - `printf "===PROCS===\\n"; ps -eo pid,user:24,%cpu,%mem,rss,args --sort=${linuxSort} 2>/dev/null | head -n 41 || ps -Ao pid,user,pcpu,pmem,rss,args ${bsdFlag} 2>/dev/null | head -n 41 || ps -Ao pid,user,pcpu,pmem,rss,args | head -n 41`, - 'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true', - 'printf "===THERMAL===\\n"; for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && printf "%s:%s\\n" "$(cat "$z/type" 2>/dev/null || basename "$z")" "$(cat "$z/temp")"; done 2>/dev/null || true', - ].join('; '); -} +const LINUX_INSPECT_CMD = [ + 'printf "===PROCS===\\n"; ps -eo pid,user:24,%cpu,%mem,rss,args --sort=-%cpu 2>/dev/null | head -n 26 || ps -Ao pid,user,pcpu,pmem,rss,args | head -n 26', + 'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true', + 'printf "===THERMAL===\\n"; for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && printf "%s:%s\\n" "$(cat "$z/type" 2>/dev/null || basename "$z")" "$(cat "$z/temp")"; done 2>/dev/null || true', +].join('; '); const BSD_INSPECT_CMD = [ - 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 41', + 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 26', 'printf "===PORTS===\\n"; sockstat -l 2>/dev/null || netstat -an 2>/dev/null || true', 'printf "===THERMAL===\\n"; sysctl dev.cpu 2>/dev/null | grep temperature || true', ].join('; '); const MACOS_INSPECT_CMD = [ - 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 41', + 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 26', 'printf "===PORTS===\\n"; lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null || netstat -an 2>/dev/null || true', 'printf "===THERMAL===\\n"; true', ].join('; '); @@ -59,7 +54,6 @@ export function parseInspectorOutput( os: OsType, stdout: string, collectedAt = Date.now(), - sort: 'cpu' | 'mem' = 'cpu', ): ServerInspectionResult { const sections: Record = {}; let current = ''; @@ -91,12 +85,6 @@ export function parseInspectorOutput( }); } - processes.sort((a, b) => - sort === 'mem' - ? b.memPct - a.memPct || b.rssMb - a.rssMb || b.cpuPct - a.cpuPct - : b.cpuPct - a.cpuPct || b.memPct - a.memPct, - ); - // Ports const ports: PortEntry[] = []; const portLines = sections.PORTS ?? []; @@ -110,6 +98,7 @@ export function parseInspectorOutput( } const cols = trimmed.split(/\s+/); if (/^(tcp|udp|tcp4|tcp6|udp4|udp6)/i.test(cols[0] ?? '')) { + // ss -tulnp format: Netid State Recv-Q Send-Q Local Peer Process if (cols.length >= 6 && (cols[1] === 'LISTEN' || cols[1] === 'UNCONN')) { ports.push({ proto: cols[0]!, @@ -124,12 +113,14 @@ export function parseInspectorOutput( }); } } else if (cols.length >= 9 && cols[cols.length - 1] === '(LISTEN)') { + // lsof format ports.push({ proto: cols[7] ?? 'TCP', localAddress: cols[8] ?? '', process: `${cols[0]}(${cols[1]})`, }); } else if (cols.length >= 6 && /^\d+$/.test(cols[2] ?? '')) { + // sockstat -l: USER COMMAND PID FD PROTO LOCAL FOREIGN ports.push({ proto: cols[4] ?? 'tcp', localAddress: cols[5] ?? '', @@ -153,7 +144,7 @@ export function parseInspectorOutput( thermals.push({ zone, tempC }); } - return { serverId, os, collectedAt, sort, processes, ports, thermals }; + return { serverId, os, collectedAt, processes, ports, thermals }; } export class ServerInspector { @@ -162,15 +153,11 @@ export class ServerInspector { private readonly configManager: ConfigManager, ) {} - async inspect( - serverId: string, - opts: { sort?: 'cpu' | 'mem'; useSudo?: boolean } = {}, - ): Promise { + async inspect(serverId: string): Promise { const server = this.configManager.getServer(serverId); if (!server) { throw new Error(`Unknown server "${serverId}"`); } - const sort = opts.sort === 'mem' ? 'mem' : 'cpu'; const runtime = this.sshPool.getState(serverId); const os = await detectServerOs(this.sshPool, server, runtime?.osDetected); const cmd = @@ -178,39 +165,9 @@ export class ServerInspector { ? MACOS_INSPECT_CMD : os === 'bsd' ? BSD_INSPECT_CMD - : buildLinuxInspectCmd(sort); + : LINUX_INSPECT_CMD; - const res = await this.sshPool.exec(serverId, cmd, { - timeoutMs: 15_000, - sudo: opts.useSudo, - }); - return parseInspectorOutput(serverId, os, res.stdout, Date.now(), sort); - } - - async signalProcess( - serverId: string, - pid: number, - signal: 'SIGTERM' | 'SIGKILL', - opts: { useSudo?: boolean } = {}, - ): Promise<{ ok: boolean; pid: number; signal: string; stderr: string }> { - const server = this.configManager.getServer(serverId); - if (!server) { - throw new Error(`Unknown server "${serverId}"`); - } - if (!Number.isInteger(pid) || pid < 1 || pid > 99_999_999) { - throw new Error('Invalid PID'); - } - const sigName = signal === 'SIGKILL' ? 'KILL' : 'TERM'; - const res = await this.sshPool.exec( - serverId, - `kill -s ${sigName} ${pid}`, - { timeoutMs: 10_000, sudo: opts.useSudo }, - ); - return { - ok: res.exitCode === 0, - pid, - signal, - stderr: res.stderr.trim(), - }; + const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000 }); + return parseInspectorOutput(serverId, os, res.stdout); } } diff --git a/src/server/monitoring/monitoring-service.ts b/src/server/monitoring/monitoring-service.ts index 29a02b1..1a69daa 100644 --- a/src/server/monitoring/monitoring-service.ts +++ b/src/server/monitoring/monitoring-service.ts @@ -6,7 +6,6 @@ import type { ProbeSample, } from '../../shared/ws-protocol.js'; import type { ConfigManager } from '../config/config-manager.js'; -import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { @@ -38,7 +37,6 @@ export interface MonitoringTickEvent { interface ServerTimers { metricTimer: NodeJS.Timeout | null; warmupTimer: NodeJS.Timeout | null; - staggerTimer: NodeJS.Timeout | null; probeTimers: Map; pollingMetrics: boolean; } @@ -56,8 +54,6 @@ export class MonitoringService { >(); private maintenanceTimer: NodeJS.Timeout | null = null; private stopped = false; - private inFlightPolls = 0; - private readonly pollQueue: Array<() => void> = []; constructor( private readonly db: Database.Database, @@ -65,7 +61,6 @@ export class MonitoringService { private readonly vaultService: VaultService, private readonly sshPool: SSHPool, private readonly probeRunner: ProbeRunner, - private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} onTick(listener: (event: MonitoringTickEvent) => void): () => void { @@ -101,7 +96,6 @@ export class MonitoringService { for (const timers of this.serverTimers.values()) { if (timers.metricTimer) clearInterval(timers.metricTimer); if (timers.warmupTimer) clearTimeout(timers.warmupTimer); - if (timers.staggerTimer) clearTimeout(timers.staggerTimer); for (const pt of timers.probeTimers.values()) clearInterval(pt); } this.serverTimers.clear(); @@ -110,9 +104,6 @@ export class MonitoringService { close(): void { this.stopped = true; this.stopAll(); - while (this.pollQueue.length > 0) { - this.pollQueue.shift()?.(); - } if (this.maintenanceTimer) { clearInterval(this.maintenanceTimer); this.maintenanceTimer = null; @@ -128,10 +119,10 @@ export class MonitoringService { return; } - const enabledServers = this.configManager.listServers().filter((s) => s.enabled); - enabledServers.forEach((server, idx) => { - this.scheduleServer(server, idx); - }); + for (const server of this.configManager.listServers()) { + if (!server.enabled) continue; + this.scheduleServer(server); + } } getLatest(serverId: string): LatestServerTelemetry | undefined { @@ -147,105 +138,45 @@ export class MonitoringService { return this.executeMetricPoll(server); } - async runProbeNow(serverId: string, probeId: string): Promise { - const server = this.configManager.getServer(serverId); - if (!server) { - throw new Error(`Unknown server "${serverId}"`); - } - const probe = server.probes.find((p) => p.id === probeId); - if (!probe) { - throw new Error(`Unknown probe "${probeId}" on server "${serverId}"`); - } - return this.runAndPersistProbe(server, probe); - } - runMaintenance(nowMs = Date.now()): void { const settings = this.configManager.getSettings(); const rawCutoff = nowMs - settings.rawRetentionHours * 3600_000; const rollupCutoff = nowMs - settings.rollupRetentionDays * 86_400_000; - const auditCutoff = nowMs - settings.auditRetentionDays * 86_400_000; - const workflowCutoff = nowMs - settings.workflowRunRetentionDays * 86_400_000; - const alertCutoff = nowMs - settings.alertEventRetentionDays * 86_400_000; const tx = this.db.transaction(() => { - // Stage 1: Aggregate 1h rollups preserving any partial bucket spanning rawCutoff + // Aggregate hourly rollups from raw metrics this.db .prepare( - `INSERT INTO metrics_rollup ( - bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, - mem_avg_pct, load_max, net_rx_avg_bps, net_tx_avg_bps, disk_max_pct - ) + `INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max) SELECT - (r.ts / 3600000) * 3600000 AS bucket_ts, + (ts / 3600000) * 3600000 AS bucket_ts, '1h' AS granularity, - r.server_id, - MIN(r.cpu_pct), - AVG(r.cpu_pct), - MAX(r.cpu_pct), - COALESCE(AVG(CASE WHEN r.mem_total_mb > 0 THEN (r.mem_used_mb * 100.0 / r.mem_total_mb) ELSE 0 END), 0), - MAX(r.load_1m), - AVG(r.net_rx_bps), - AVG(r.net_tx_bps), - COALESCE(MAX(d.max_disk_pct), 0) - FROM metrics_raw r - LEFT JOIN ( - SELECT server_id, ts, MAX(used_pct) AS max_disk_pct - FROM metrics_disks - GROUP BY server_id, ts - ) d ON d.server_id = r.server_id AND d.ts = r.ts - GROUP BY r.server_id, (r.ts / 3600000) * 3600000 - ON CONFLICT(server_id, granularity, bucket_ts) DO UPDATE SET - cpu_min = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_min ELSE MIN(metrics_rollup.cpu_min, excluded.cpu_min) END, - cpu_max = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_max ELSE MAX(metrics_rollup.cpu_max, excluded.cpu_max) END, - load_max = CASE WHEN excluded.bucket_ts >= ? THEN excluded.load_max ELSE MAX(metrics_rollup.load_max, excluded.load_max) END, - disk_max_pct = CASE WHEN excluded.bucket_ts >= ? THEN excluded.disk_max_pct ELSE MAX(metrics_rollup.disk_max_pct, excluded.disk_max_pct) END, - cpu_avg = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_avg ELSE metrics_rollup.cpu_avg END, - mem_avg_pct = CASE WHEN excluded.bucket_ts >= ? THEN excluded.mem_avg_pct ELSE metrics_rollup.mem_avg_pct END, - net_rx_avg_bps = CASE WHEN excluded.bucket_ts >= ? THEN excluded.net_rx_avg_bps ELSE metrics_rollup.net_rx_avg_bps END, - net_tx_avg_bps = CASE WHEN excluded.bucket_ts >= ? THEN excluded.net_tx_avg_bps ELSE metrics_rollup.net_tx_avg_bps END`, + server_id, + MIN(cpu_pct), + AVG(cpu_pct), + MAX(cpu_pct), + COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0), + MAX(load_1m) + FROM metrics_raw + GROUP BY server_id, (ts / 3600000) * 3600000`, ) - .run( - rawCutoff, - rawCutoff, - rawCutoff, - rawCutoff, - rawCutoff, - rawCutoff, - rawCutoff, - rawCutoff, - ); + .run(); - // Stage 2: Aggregate 1d rollups from complete 1h buckets so raw pruning never truncates a day + // Aggregate daily rollups this.db .prepare( - `INSERT INTO metrics_rollup ( - bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, - mem_avg_pct, load_max, net_rx_avg_bps, net_tx_avg_bps, disk_max_pct - ) + `INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max) SELECT - (bucket_ts / 86400000) * 86400000 AS day_ts, + (ts / 86400000) * 86400000 AS bucket_ts, '1d' AS granularity, server_id, - MIN(cpu_min), - AVG(cpu_avg), - MAX(cpu_max), - AVG(mem_avg_pct), - MAX(load_max), - AVG(net_rx_avg_bps), - AVG(net_tx_avg_bps), - MAX(disk_max_pct) - FROM metrics_rollup - WHERE granularity = '1h' - GROUP BY server_id, (bucket_ts / 86400000) * 86400000 - ON CONFLICT(server_id, granularity, bucket_ts) DO UPDATE SET - cpu_min = MIN(metrics_rollup.cpu_min, excluded.cpu_min), - cpu_max = MAX(metrics_rollup.cpu_max, excluded.cpu_max), - load_max = MAX(metrics_rollup.load_max, excluded.load_max), - disk_max_pct = MAX(metrics_rollup.disk_max_pct, excluded.disk_max_pct), - cpu_avg = excluded.cpu_avg, - mem_avg_pct = excluded.mem_avg_pct, - net_rx_avg_bps = excluded.net_rx_avg_bps, - net_tx_avg_bps = excluded.net_tx_avg_bps`, + MIN(cpu_pct), + AVG(cpu_pct), + MAX(cpu_pct), + COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0), + MAX(load_1m) + FROM metrics_raw + GROUP BY server_id, (ts / 86400000) * 86400000`, ) .run(); @@ -253,65 +184,16 @@ export class MonitoringService { this.db.prepare('DELETE FROM metrics_disks WHERE ts < ?').run(rawCutoff); this.db.prepare('DELETE FROM probe_results WHERE ts < ?').run(rawCutoff); this.db.prepare('DELETE FROM metrics_rollup WHERE bucket_ts < ?').run(rollupCutoff); - this.db.prepare('DELETE FROM audit_log WHERE ts < ?').run(auditCutoff); - this.db - .prepare('DELETE FROM workflow_runs WHERE finished_at IS NOT NULL AND started_at < ?') - .run(workflowCutoff); - this.db - .prepare( - "DELETE FROM alert_events WHERE state = 'resolved' AND COALESCE(resolved_at, triggered_at) < ?", - ) - .run(alertCutoff); - this.db.prepare('DELETE FROM alert_silences WHERE expires_at < ?').run(nowMs); - this.db - .prepare('DELETE FROM broadcast_jobs WHERE finished_at IS NOT NULL AND started_at < ?') - .run(workflowCutoff); }); tx(); } - queryProbeHistory( - serverId: string, - sinceMs = Date.now() - 24 * 3600_000, - limit = 200, - ): Array { - const safeLimit = Math.max(1, Math.min(1000, Math.floor(limit))); - const rows = this.db - .prepare( - `SELECT ts, probe_id AS probeId, ok AS okInt, status_code AS statusCode, - latency_ms AS latencyMs, error - FROM probe_results - WHERE server_id = ? AND ts >= ? - ORDER BY ts DESC - LIMIT ?`, - ) - .all(serverId, sinceMs, safeLimit) as Array<{ - ts: number; - probeId: string; - okInt: number; - statusCode: number | null; - latencyMs: number; - error: string | null; - }>; - - return rows.reverse().map((r) => ({ - ts: r.ts, - probeId: r.probeId, - ok: r.okInt === 1, - statusCode: r.statusCode ?? undefined, - latencyMs: r.latencyMs, - error: r.error ?? undefined, - })); - } - queryHistory(serverId: string, range: MetricRange = '1h'): { range: MetricRange; granularity: 'raw' | '1h' | '1d'; points: Array>; latestDisks: DiskSample[]; latestProbes: Array; - probeHistory: Array; - diskHistory: Array<{ ts: number; mountPoint: string; usedPct: number; usedMb: number; totalMb: number }>; } { const now = Date.now(); const rangeMs: Record = { @@ -341,9 +223,7 @@ export class MonitoringService { points = this.db .prepare( `SELECT bucket_ts AS ts, cpu_min AS cpuMin, cpu_avg AS cpuAvg, cpu_max AS cpuMax, - mem_avg_pct AS memAvgPct, load_max AS loadMax, - net_rx_avg_bps AS netRxAvgBps, net_tx_avg_bps AS netTxAvgBps, - disk_max_pct AS diskMaxPct + mem_avg_pct AS memAvgPct, load_max AS loadMax FROM metrics_rollup WHERE server_id = ? AND granularity = ? AND bucket_ts >= ? ORDER BY bucket_ts ASC`, @@ -360,22 +240,6 @@ export class MonitoringService { ) .all(serverId, serverId) as DiskSample[]; - const diskHistory = this.db - .prepare( - `SELECT ts, mount_point AS mountPoint, used_pct AS usedPct, used_mb AS usedMb, total_mb AS totalMb - FROM metrics_disks - WHERE server_id = ? AND ts >= ? - ORDER BY ts ASC - LIMIT 500`, - ) - .all(serverId, since) as Array<{ - ts: number; - mountPoint: string; - usedPct: number; - usedMb: number; - totalMb: number; - }>; - const latestProbes = this.db .prepare( `SELECT p.probe_id AS probeId, p.ok AS okInt, p.status_code AS statusCode, @@ -398,8 +262,6 @@ export class MonitoringService { ts: number; }>; - const probeHistory = this.queryProbeHistory(serverId, since, 200); - return { range, granularity, @@ -413,88 +275,50 @@ export class MonitoringService { error: r.error ?? undefined, ts: r.ts, })), - probeHistory, - diskHistory, }; } - private async withPollSlot(fn: () => Promise): Promise { - const limit = Math.max(1, this.getRuntimeLimits?.().maxConcurrentMetricPolls ?? 4); - if (this.inFlightPolls >= limit) { - await new Promise((resolve) => { - this.pollQueue.push(resolve); - }); - } - this.inFlightPolls += 1; - try { - return await fn(); - } finally { - this.inFlightPolls = Math.max(0, this.inFlightPolls - 1); - const next = this.pollQueue.shift(); - if (next) next(); - } - } - - private scheduleServer(server: ServerConfig, index: number): void { + private scheduleServer(server: ServerConfig): void { const timers: ServerTimers = { metricTimer: null, warmupTimer: null, - staggerTimer: null, probeTimers: new Map(), pollingMetrics: false, }; this.serverTimers.set(server.id, timers); - const limits = this.getRuntimeLimits?.(); - const staggerMs = - limits?.staggerPolls && index > 0 ? Math.min(index * 120, 2_500) : 0; - - const kickInitialAndStartTimer = () => { - if (this.stopped || this.serverTimers.get(server.id) !== timers) return; - - const hadDelta = this.deltaStates.has(server.id); - void this.executeMetricPoll(server).then((ev) => { - if ( - ev && - !hadDelta && - !this.stopped && - this.serverTimers.get(server.id) === timers && - server.pollIntervalSec >= 3 - ) { - const wt = setTimeout(() => { - timers.warmupTimer = null; - void this.executeMetricPoll(server); - }, 1000); - wt.unref(); - timers.warmupTimer = wt; - } - }); - - timers.metricTimer = setInterval(() => { - void this.executeMetricPoll(server); - }, server.pollIntervalSec * 1000); - timers.metricTimer.unref(); - - for (const probe of server.probes) { - if (!probe.enabled) continue; - void this.executeProbe(server, probe.id); - const pt = setInterval(() => { - void this.executeProbe(server, probe.id); - }, probe.intervalSec * 1000); - pt.unref(); - timers.probeTimers.set(probe.id, pt); + // Kick initial poll asynchronously without delaying syncServers() + const hadDelta = this.deltaStates.has(server.id); + void this.executeMetricPoll(server).then((ev) => { + if ( + ev && + !hadDelta && + !this.stopped && + this.serverTimers.get(server.id) === timers && + server.pollIntervalSec >= 3 + ) { + const wt = setTimeout(() => { + timers.warmupTimer = null; + void this.executeMetricPoll(server); + }, 1000); + wt.unref(); + timers.warmupTimer = wt; } - }; + }); - if (staggerMs > 0) { - const st = setTimeout(() => { - timers.staggerTimer = null; - kickInitialAndStartTimer(); - }, staggerMs); - st.unref(); - timers.staggerTimer = st; - } else { - kickInitialAndStartTimer(); + timers.metricTimer = setInterval(() => { + void this.executeMetricPoll(server); + }, server.pollIntervalSec * 1000); + timers.metricTimer.unref(); + + for (const probe of server.probes) { + if (!probe.enabled) continue; + void this.executeProbe(server, probe.id); + const pt = setInterval(() => { + void this.executeProbe(server, probe.id); + }, probe.intervalSec * 1000); + pt.unref(); + timers.probeTimers.set(probe.id, pt); } } @@ -508,55 +332,51 @@ export class MonitoringService { if (timerState) timerState.pollingMetrics = true; try { - return await this.withPollSlot(async () => { - if (this.stopped || !this.vaultService.isRuntimeReady) return null; + const os = await detectServerOs( + this.sshPool, + server, + this.osCache.get(server.id), + ); + this.osCache.set(server.id, os); - const os = await detectServerOs( - this.sshPool, - server, - this.osCache.get(server.id), - ); - this.osCache.set(server.id, os); + const collected = await collectServerMetrics( + this.sshPool, + server, + os, + this.deltaStates.get(server.id), + ); + this.deltaStates.set(server.id, collected.nextState); - const collected = await collectServerMetrics( - this.sshPool, - server, - os, - this.deltaStates.get(server.id), - ); - this.deltaStates.set(server.id, collected.nextState); + this.persistMetricSample(server.id, collected.sample, collected.disks); - this.persistMetricSample(server.id, collected.sample, collected.disks); - - const prevLatest = this.latest.get(server.id) ?? { - serverId: server.id, - disks: [], - probes: {}, - }; - this.latest.set(server.id, { - ...prevLatest, - os, - sample: collected.sample, - disks: collected.disks, - lastError: undefined, - }); - - const probes = Object.values(this.latest.get(server.id)!.probes); - const event: MonitoringTickEvent = { - serverId: server.id, - sample: collected.sample, - disks: collected.disks, - probes, - }; - for (const listener of this.tickListeners) { - try { - listener(event); - } catch { - // Isolate listener errors - } - } - return event; + const prevLatest = this.latest.get(server.id) ?? { + serverId: server.id, + disks: [], + probes: {}, + }; + this.latest.set(server.id, { + ...prevLatest, + os, + sample: collected.sample, + disks: collected.disks, + lastError: undefined, }); + + const probes = Object.values(this.latest.get(server.id)!.probes); + const event: MonitoringTickEvent = { + serverId: server.id, + sample: collected.sample, + disks: collected.disks, + probes, + }; + for (const listener of this.tickListeners) { + try { + listener(event); + } catch { + // Isolate listener errors + } + } + return event; } catch (err) { const prevLatest = this.latest.get(server.id) ?? { serverId: server.id, @@ -577,16 +397,8 @@ export class MonitoringService { if (this.stopped || !this.vaultService.isRuntimeReady) return; const probe = server.probes.find((p) => p.id === probeId); if (!probe || !probe.enabled) return; - await this.runAndPersistProbe(server, probe); - } - private async runAndPersistProbe( - server: ServerConfig, - probe: ServerConfig['probes'][number], - ): Promise { - const sample = await this.withPollSlot(() => - this.probeRunner.runProbe(server.id, probe), - ); + const sample = await this.probeRunner.runProbe(server.id, probe); const ts = Date.now(); this.db .prepare( @@ -618,7 +430,6 @@ export class MonitoringService { // Isolate probe listener errors } } - return sample; } private hydrateLatestFromDb(): void { diff --git a/src/server/monitoring/probes.ts b/src/server/monitoring/probes.ts index b09f3aa..02d5bed 100644 --- a/src/server/monitoring/probes.ts +++ b/src/server/monitoring/probes.ts @@ -3,93 +3,36 @@ import tls from 'node:tls'; import type { Duplex } from 'node:stream'; import type { ServerProbe } from '../../shared/schemas/server.schema.js'; import type { ProbeSample } from '../../shared/ws-protocol.js'; -import type { ConfigManager } from '../config/config-manager.js'; -import { - fetchWithEgressGuard, - resolveAllowedEgressIps, -} from '../security/egress-guard.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; -const MAX_PROBE_BODY_BYTES = 128 * 1024; - -function decodeChunkedIfNeeded(head: string, body: string): string { - if (!/^transfer-encoding:\s*chunked\b/im.test(head)) return body; - let idx = 0; - let out = ''; - while (idx < body.length) { - const lineEnd = body.indexOf('\r\n', idx); - if (lineEnd < 0) break; - const sizeHex = body.slice(idx, lineEnd).split(';')[0]!.trim(); - const size = Number.parseInt(sizeHex, 16); - if (!Number.isFinite(size) || size <= 0) break; - idx = lineEnd + 2; - out += body.slice(idx, idx + size); - idx += size + 2; - } - return out || body; -} - -async function readResponseTextCapped( - res: Response, - maxBytes = MAX_PROBE_BODY_BYTES, -): Promise { - if (!res.body) return ''; - const reader = res.body.getReader(); - const chunks: Buffer[] = []; - let total = 0; - try { - while (total < maxBytes) { - const { value, done } = await reader.read(); - if (done || !value) break; - const take = Math.min(value.byteLength, maxBytes - total); - chunks.push(Buffer.from(value.subarray(0, take))); - total += take; - if (total >= maxBytes) { - await reader.cancel().catch(() => undefined); - break; - } - } - } finally { - reader.releaseLock(); - } - return Buffer.concat(chunks).toString('utf8'); -} - function readHttpFromStream( stream: Duplex, url: URL, timeoutMs: number, - tlsOpts: { rejectUnauthorized?: boolean } = {}, -): Promise<{ statusCode: number; body: string; certExpiryDays?: number }> { +): Promise<{ statusCode: number; body: string }> { return new Promise((resolve, reject) => { let settled = false; - let certExpiryDays: number | undefined; const timer = setTimeout(() => { if (settled) return; settled = true; stream.destroy(); - reject(new Error(`HTTP probe timed out after ${timeoutMs}ms`)); + reject(new Error(`Target HTTP probe timed out after ${timeoutMs}ms`)); }, timeoutMs); - const servername = net.isIP(url.hostname) ? undefined : url.hostname; const transport: Duplex = url.protocol === 'https:' - ? tls.connect({ - socket: stream, - servername, - rejectUnauthorized: tlsOpts.rejectUnauthorized ?? true, - }) + ? tls.connect({ socket: stream, servername: url.hostname }) : stream; const chunks: Buffer[] = []; let total = 0; + const maxBytes = 256 * 1024; const done = (err?: Error) => { if (settled) return; settled = true; clearTimeout(timer); transport.destroy(); - stream.destroy(); if (err) { reject(err); return; @@ -97,53 +40,36 @@ function readHttpFromStream( const raw = Buffer.concat(chunks).toString('utf8'); const headerEnd = raw.indexOf('\r\n\r\n'); const head = headerEnd >= 0 ? raw.slice(0, headerEnd) : raw; - const rawBody = headerEnd >= 0 ? raw.slice(headerEnd + 4) : ''; + const body = headerEnd >= 0 ? raw.slice(headerEnd + 4) : ''; const statusLine = head.split('\r\n')[0] ?? ''; const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(statusLine); if (!m) { reject(new Error(`Invalid HTTP response line: ${statusLine}`)); return; } - resolve({ - statusCode: Number(m[1]), - body: decodeChunkedIfNeeded(head, rawBody), - certExpiryDays, - }); + resolve({ statusCode: Number(m[1]), body }); }; transport.on('data', (chunk: Buffer) => { - if (total < MAX_PROBE_BODY_BYTES) { - chunks.push(chunk.subarray(0, MAX_PROBE_BODY_BYTES - total)); + if (total < maxBytes) { + chunks.push(chunk.subarray(0, maxBytes - total)); total += chunk.length; - } else { - transport.destroy(); } }); transport.once('end', () => done()); transport.once('close', () => done()); transport.once('error', (err) => done(err)); - if (transport !== stream) { - stream.once('error', (err) => done(err)); - } const pathAndQuery = `${url.pathname || '/'}${url.search || ''}`; const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname; const reqText = `GET ${pathAndQuery} HTTP/1.1\r\n` + `Host: ${hostHeader}\r\n` + - `User-Agent: GCoordinator-Probe/1.1\r\n` + - `Accept-Encoding: identity\r\n` + + `User-Agent: GCoordinator-Probe/1.0\r\n` + `Connection: close\r\n\r\n`; if (url.protocol === 'https:') { (transport as tls.TLSSocket).once('secureConnect', () => { - const cert = (transport as tls.TLSSocket).getPeerCertificate(false); - if (cert && typeof cert.valid_to === 'string') { - const expMs = Date.parse(cert.valid_to); - if (Number.isFinite(expMs)) { - certExpiryDays = Math.floor((expMs - Date.now()) / 86_400_000); - } - } transport.write(reqText); }); } else { @@ -153,26 +79,16 @@ function readHttpFromStream( } export class ProbeRunner { - constructor( - private readonly sshPool: SSHPool, - private readonly configManager?: ConfigManager, - ) {} - - runSingleProbe(serverId: string, probe: ServerProbe): Promise { - return this.runProbe(serverId, probe); - } + constructor(private readonly sshPool: SSHPool) {} async runProbe(serverId: string, probe: ServerProbe): Promise { const started = Date.now(); - const allowedCidrs = this.configManager?.getSettings().security.egressAllowedCidrs ?? []; - try { if (probe.type === 'tcp') { if (probe.from === 'hub') { - const ips = await resolveAllowedEgressIps(probe.host, allowedCidrs); await new Promise((resolve, reject) => { const sock = net.createConnection({ - host: ips[0]!, + host: probe.host, port: probe.port, }); const timer = setTimeout(() => { @@ -209,35 +125,19 @@ export class ProbeRunner { } // HTTP(S) probe - const parsedUrl = new URL(probe.url); let statusCode: number; let body: string; - let certExpiryDays: number | undefined; if (probe.from === 'hub') { - if ( - parsedUrl.protocol === 'https:' && - (probe.tlsRejectUnauthorized === false || probe.tlsCheckExpiryDays !== undefined) - ) { - const ips = await resolveAllowedEgressIps(parsedUrl.hostname, allowedCidrs); - const port = parsedUrl.port ? Number(parsedUrl.port) : 443; - const sock = net.createConnection({ host: ips[0]!, port }); - const resp = await readHttpFromStream(sock, parsedUrl, probe.timeoutMs, { - rejectUnauthorized: probe.tlsRejectUnauthorized, - }); - statusCode = resp.statusCode; - body = resp.body; - certExpiryDays = resp.certExpiryDays; - } else { - const res = await fetchWithEgressGuard( - probe.url, - { method: 'GET', redirect: 'manual' }, - { allowedCidrs, timeoutMs: probe.timeoutMs }, - ); - statusCode = res.status; - body = await readResponseTextCapped(res, MAX_PROBE_BODY_BYTES); - } + const res = await fetch(probe.url, { + method: 'GET', + redirect: 'manual', + signal: AbortSignal.timeout(probe.timeoutMs), + }); + statusCode = res.status; + body = await res.text(); } else { + const parsedUrl = new URL(probe.url); const port = parsedUrl.port ? Number(parsedUrl.port) : parsedUrl.protocol === 'https:' @@ -249,40 +149,24 @@ export class ProbeRunner { port, probe.timeoutMs, ); - const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs, { - rejectUnauthorized: probe.tlsRejectUnauthorized, - }); + const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs); statusCode = resp.statusCode; body = resp.body; - certExpiryDays = resp.certExpiryDays; } const statusOk = statusCode === probe.expectedStatus; const bodyOk = probe.bodyIncludes ? body.includes(probe.bodyIncludes) : true; - const certOk = - probe.tlsCheckExpiryDays !== undefined && certExpiryDays !== undefined - ? certExpiryDays >= probe.tlsCheckExpiryDays - : true; - const ok = statusOk && bodyOk && certOk; - - let error: string | undefined; - if (!ok) { - if (!statusOk) { - error = `Expected HTTP ${probe.expectedStatus}, got ${statusCode}`; - } else if (!bodyOk) { - error = `Response body missing substring "${probe.bodyIncludes}"`; - } else { - error = `TLS certificate expires in ${certExpiryDays}d (threshold ${probe.tlsCheckExpiryDays}d)`; - } - } - + const ok = statusOk && bodyOk; return { probeId: probe.id, ok, statusCode, latencyMs: Date.now() - started, - certExpiryDays, - error, + error: ok + ? undefined + : !statusOk + ? `Expected HTTP ${probe.expectedStatus}, got ${statusCode}` + : `Response body missing substring "${probe.bodyIncludes}"`, }; } catch (err) { return { diff --git a/src/server/monitoring/prometheus.ts b/src/server/monitoring/prometheus.ts deleted file mode 100644 index a69692c..0000000 --- a/src/server/monitoring/prometheus.ts +++ /dev/null @@ -1,180 +0,0 @@ -import crypto from 'node:crypto'; -import type { Request, Response } from 'express'; -import type { AlertEngine } from '../alerts/alert-engine.js'; -import type { ConfigManager } from '../config/config-manager.js'; -import { sha256Hex } from '../security/auth.js'; -import type { VaultService } from '../security/vault.js'; -import type { SSHPool } from '../ssh/ssh-pool.js'; -import type { TunnelManager } from '../ssh/tunnel-manager.js'; -import type { MonitoringService } from './monitoring-service.js'; - -export interface PrometheusHandlerDeps { - configManager: ConfigManager; - vaultService: VaultService; - sshPool: SSHPool; - monitoringService: MonitoringService; - tunnelManager: TunnelManager; - alertEngine: AlertEngine; -} - -function escapePromLabel(val: string): string { - return val.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n'); -} - -function labels(pairs: Record): string { - const parts = Object.entries(pairs).map( - ([k, v]) => `${k}="${escapePromLabel(v)}"`, - ); - return parts.length > 0 ? `{${parts.join(',')}}` : ''; -} - -function constantTimeTokenMatch(provided: string, expectedSha256Hex: string): boolean { - if (!/^[a-f0-9]{64}$/i.test(expectedSha256Hex)) return false; - const providedDigest = Buffer.from(sha256Hex(provided), 'hex'); - const expectedDigest = Buffer.from(expectedSha256Hex.toLowerCase(), 'hex'); - if (providedDigest.length !== expectedDigest.length) return false; - return crypto.timingSafeEqual(providedDigest, expectedDigest); -} - -export function createPrometheusHandler(deps: PrometheusHandlerDeps) { - const { - configManager, - vaultService, - sshPool, - monitoringService, - tunnelManager, - alertEngine, - } = deps; - - return (req: Request, res: Response): void => { - const settings = configManager.getSettings(); - if (!settings.metrics.prometheusEnabled) { - res.status(404).json({ error: 'METRICS_DISABLED' }); - return; - } - - const authHeader = typeof req.headers.authorization === 'string' ? req.headers.authorization : ''; - const bearerMatch = /^Bearer\s+(.+)$/i.exec(authHeader.trim()); - const providedToken = bearerMatch?.[1]?.trim() ?? ''; - - let authorized = false; - if (providedToken) { - if (settings.metrics.prometheusSecretRef && vaultService.isRuntimeReady) { - const cred = vaultService.getRuntimeSecret(settings.metrics.prometheusSecretRef); - const rawSecret = - cred?.type === 'api-token' - ? cred.token - : cred?.type === 'webhook-secret' - ? cred.secret - : undefined; - if (rawSecret) { - authorized = constantTimeTokenMatch(providedToken, sha256Hex(rawSecret)); - } - } - if (!authorized && settings.metrics.prometheusTokenHash) { - authorized = constantTimeTokenMatch(providedToken, settings.metrics.prometheusTokenHash); - } - } - - if (!authorized) { - res.setHeader('WWW-Authenticate', 'Bearer realm="GCoordinator"'); - res.status(401).json({ error: 'METRICS_UNAUTHORIZED' }); - return; - } - - const lines: string[] = []; - const metric = (name: string, help: string, type: 'gauge' | 'counter', rows: string[]) => { - lines.push(`# HELP ${name} ${help}`); - lines.push(`# TYPE ${name} ${type}`); - lines.push(...rows); - }; - - const states = new Map(sshPool.getStates().map((s) => [s.serverId, s])); - const servers = configManager.listServers(); - - const upRows: string[] = []; - const cpuRows: string[] = []; - const memUsedRows: string[] = []; - const memTotalRows: string[] = []; - const load1Rows: string[] = []; - const uptimeRows: string[] = []; - const netRxRows: string[] = []; - const netTxRows: string[] = []; - const diskRows: string[] = []; - const probeUpRows: string[] = []; - const probeLatencyRows: string[] = []; - const probeTlsExpiryRows: string[] = []; - - for (const srv of servers) { - const state = states.get(srv.id); - const isUp = state?.status === 'connected' ? 1 : 0; - const baseLabels = labels({ server_id: srv.id, name: srv.name }); - upRows.push(`gcoordinator_server_up${baseLabels} ${isUp}`); - - const latest = monitoringService.getLatest(srv.id); - if (latest?.sample) { - const s = latest.sample; - cpuRows.push(`gcoordinator_server_cpu_percent${baseLabels} ${s.cpuPct}`); - memUsedRows.push( - `gcoordinator_server_memory_used_bytes${baseLabels} ${Math.round(s.memUsedMb * 1024 * 1024)}`, - ); - memTotalRows.push( - `gcoordinator_server_memory_total_bytes${baseLabels} ${Math.round(s.memTotalMb * 1024 * 1024)}`, - ); - load1Rows.push(`gcoordinator_server_load1${baseLabels} ${s.load1m}`); - uptimeRows.push(`gcoordinator_server_uptime_seconds${baseLabels} ${s.uptimeSec}`); - netRxRows.push(`gcoordinator_server_net_rx_bytes_per_sec${baseLabels} ${s.netRxBps}`); - netTxRows.push(`gcoordinator_server_net_tx_bytes_per_sec${baseLabels} ${s.netTxBps}`); - } - if (latest?.disks) { - for (const d of latest.disks) { - const dl = labels({ server_id: srv.id, mount: d.mountPoint }); - diskRows.push(`gcoordinator_server_disk_used_percent${dl} ${d.usedPct}`); - } - } - if (latest?.probes) { - for (const p of Object.values(latest.probes)) { - const pl = labels({ server_id: srv.id, probe_id: p.probeId }); - probeUpRows.push(`gcoordinator_probe_up${pl} ${p.ok ? 1 : 0}`); - probeLatencyRows.push(`gcoordinator_probe_latency_ms${pl} ${p.latencyMs}`); - if (typeof p.certExpiryDays === 'number') { - probeTlsExpiryRows.push(`gcoordinator_probe_tls_expiry_days${pl} ${p.certExpiryDays}`); - } - } - } - } - - metric('gcoordinator_server_up', 'Server SSH reachability (1=connected, 0=disconnected)', 'gauge', upRows); - metric('gcoordinator_server_cpu_percent', 'Latest sampled CPU utilization percentage', 'gauge', cpuRows); - metric('gcoordinator_server_memory_used_bytes', 'Latest sampled memory used in bytes', 'gauge', memUsedRows); - metric('gcoordinator_server_memory_total_bytes', 'Total RAM in bytes', 'gauge', memTotalRows); - metric('gcoordinator_server_load1', 'Latest 1-minute load average', 'gauge', load1Rows); - metric('gcoordinator_server_uptime_seconds', 'Server uptime in seconds', 'gauge', uptimeRows); - metric('gcoordinator_server_net_rx_bytes_per_sec', 'Network receive throughput B/s', 'gauge', netRxRows); - metric('gcoordinator_server_net_tx_bytes_per_sec', 'Network transmit throughput B/s', 'gauge', netTxRows); - metric('gcoordinator_server_disk_used_percent', 'Disk filesystem usage percentage', 'gauge', diskRows); - metric('gcoordinator_probe_up', 'Latest health probe result (1=ok, 0=fail)', 'gauge', probeUpRows); - metric('gcoordinator_probe_latency_ms', 'Latest health probe latency in ms', 'gauge', probeLatencyRows); - if (probeTlsExpiryRows.length > 0) { - metric('gcoordinator_probe_tls_expiry_days', 'Days remaining until TLS certificate expiry', 'gauge', probeTlsExpiryRows); - } - - const activeTunnels = tunnelManager.listTunnels().filter((t) => t.active).length; - metric('gcoordinator_tunnels_active', 'Number of currently active SSH tunnels', 'gauge', [ - `gcoordinator_tunnels_active ${activeTunnels}`, - ]); - metric('gcoordinator_alerts_active', 'Number of active unresolved alert incidents', 'gauge', [ - `gcoordinator_alerts_active ${alertEngine.getActiveCount()}`, - ]); - metric('gcoordinator_process_resident_memory_bytes', 'Hub Node.js resident set size bytes', 'gauge', [ - `gcoordinator_process_resident_memory_bytes ${process.memoryUsage().rss}`, - ]); - metric('gcoordinator_process_uptime_seconds', 'Hub Node.js process uptime in seconds', 'gauge', [ - `gcoordinator_process_uptime_seconds ${Math.round(process.uptime())}`, - ]); - - res.setHeader('Content-Type', 'text/plain; version=0.0.4; charset=utf-8'); - res.setHeader('Cache-Control', 'no-store'); - res.send(`${lines.join('\n')}\n`); - }; -} diff --git a/src/server/security/audit.ts b/src/server/security/audit.ts index c7146e5..e63d78d 100644 --- a/src/server/security/audit.ts +++ b/src/server/security/audit.ts @@ -20,28 +20,6 @@ export interface AuditLogRecord { details: string | null; } -export interface AuditListOptions { - limit?: number; - offset?: number; - action?: string; - actionPrefix?: string; - status?: 'ok' | 'denied' | 'error'; - ip?: string; - target?: string; - q?: string; - from?: number; - to?: number; -} - -function escapeLike(input: string): string { - return input.replace(/[\\%_]/g, '\\$&'); -} - -function sanitizeCsvCell(value: string): string { - const safe = /^[ \t]*[=+\-@\t\r]/.test(value) ? `'${value}` : value; - return `"${safe.replace(/"/g, '""')}"`; -} - export class AuditService { private readonly insertStmt; @@ -71,143 +49,33 @@ export class AuditService { ); } - private buildWhereClause(options: AuditListOptions): { sql: string; params: Array } { - const clauses: string[] = []; - const params: Array = []; - - if (options.action) { - clauses.push('action = ?'); - params.push(options.action); - } else if (options.actionPrefix) { - clauses.push("action LIKE ? ESCAPE '\\'"); - params.push(`${escapeLike(options.actionPrefix)}%`); - } - - if (options.status) { - clauses.push('status = ?'); - params.push(options.status); - } - - if (options.ip) { - clauses.push('actor_ip = ?'); - params.push(options.ip); - } - - if (options.target) { - clauses.push("target LIKE ? ESCAPE '\\'"); - params.push(`%${escapeLike(options.target)}%`); - } - - if (typeof options.from === 'number' && Number.isFinite(options.from)) { - clauses.push('ts >= ?'); - params.push(options.from); - } - if (typeof options.to === 'number' && Number.isFinite(options.to)) { - clauses.push('ts <= ?'); - params.push(options.to); - } - - if (options.q) { - const needle = `%${escapeLike(options.q)}%`; - clauses.push( - "(action LIKE ? ESCAPE '\\' OR actor_ip LIKE ? ESCAPE '\\' OR COALESCE(target, '') LIKE ? ESCAPE '\\' OR COALESCE(details, '') LIKE ? ESCAPE '\\')", - ); - params.push(needle, needle, needle, needle); - } - - return { - sql: clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '', - params, - }; - } - - list(options: AuditListOptions = {}): { + list(options: { limit?: number; offset?: number; action?: string } = {}): { total: number; items: AuditLogRecord[]; } { const limit = Math.max(1, Math.min(200, options.limit ?? 50)); const offset = Math.max(0, options.offset ?? 0); - const where = this.buildWhereClause(options); - const countRow = this.db - .prepare(`SELECT COUNT(*) AS cnt FROM audit_log ${where.sql}`) - .get(...where.params) as { cnt: number }; - - const items = this.db - .prepare( - `SELECT id, ts, action, actor_ip, session_id_hash, target, status, details - FROM audit_log ${where.sql} - ORDER BY ts DESC, id DESC - LIMIT ? OFFSET ?`, - ) - .all(...where.params, limit, offset) as AuditLogRecord[]; - - return { total: countRow.cnt, items }; - } - - listActions(): string[] { - const rows = this.db - .prepare('SELECT DISTINCT action FROM audit_log ORDER BY action ASC LIMIT 200') - .all() as Array<{ action: string }>; - return rows.map((r) => r.action); - } - - exportRecords( - options: AuditListOptions, - format: 'csv' | 'ndjson', - maxRows = 10_000, - ): string { - const cap = Math.max(1, Math.min(50_000, maxRows)); - const where = this.buildWhereClause(options); - const rows = this.db - .prepare( - `SELECT id, ts, action, actor_ip, session_id_hash, target, status, details - FROM audit_log ${where.sql} - ORDER BY ts DESC, id DESC - LIMIT ?`, - ) - .all(...where.params, cap) as AuditLogRecord[]; - - if (format === 'ndjson') { - return `${rows - .map((r) => - JSON.stringify({ - id: r.id, - ts: r.ts, - isoTime: new Date(r.ts).toISOString(), - action: r.action, - status: r.status, - actorIp: r.actor_ip, - target: r.target, - sessionIdHash: r.session_id_hash, - details: r.details, - }), + if (options.action) { + const countRow = this.db + .prepare('SELECT COUNT(*) AS cnt FROM audit_log WHERE action = ?') + .get(options.action) as { cnt: number }; + const items = this.db + .prepare( + 'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log WHERE action = ? ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?', ) - .join('\n')}\n`; + .all(options.action, limit, offset) as AuditLogRecord[]; + return { total: countRow.cnt, items }; } - const lines = [ - 'id,ts,isoTime,action,status,actorIp,target,sessionIdHash,details', - ...rows.map((r) => - [ - String(r.id), - String(r.ts), - sanitizeCsvCell(new Date(r.ts).toISOString()), - sanitizeCsvCell(r.action), - sanitizeCsvCell(r.status), - sanitizeCsvCell(r.actor_ip), - sanitizeCsvCell(r.target ?? ''), - sanitizeCsvCell(r.session_id_hash ?? ''), - sanitizeCsvCell(r.details ?? ''), - ].join(','), - ), - ]; - return `${lines.join('\n')}\n`; - } - - pruneOlderThan(retentionDays: number): number { - const days = Math.max(1, retentionDays); - const cutoff = Date.now() - days * 24 * 60 * 60 * 1000; - return this.db.prepare('DELETE FROM audit_log WHERE ts < ?').run(cutoff).changes; + const countRow = this.db + .prepare('SELECT COUNT(*) AS cnt FROM audit_log') + .get() as { cnt: number }; + const items = this.db + .prepare( + 'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?', + ) + .all(limit, offset) as AuditLogRecord[]; + return { total: countRow.cnt, items }; } } diff --git a/src/server/security/auth.ts b/src/server/security/auth.ts index 76c6928..30bdb06 100644 --- a/src/server/security/auth.ts +++ b/src/server/security/auth.ts @@ -1,6 +1,4 @@ import crypto from 'node:crypto'; -import fs from 'node:fs'; -import path from 'node:path'; import { generateAuthenticationOptions, generateRegistrationOptions, @@ -19,120 +17,18 @@ import { type SecuritySettings, type StepUpPolicy, } from '../../shared/schemas/settings.schema.js'; -import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { EmergencyRecoveryService, SavedTotpEntry } from './recovery-store.js'; import type { VaultService } from './vault.js'; const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; +const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; const BOOTSTRAP_TTL_MS = 15 * 60 * 1000; const WEBAUTHN_TTL_MS = 5 * 60 * 1000; -const SESSION_REAPER_MS = 5 * 60 * 1000; const TOTP_PERIOD_SEC = 30; const DEFAULT_SECURITY = SecuritySettingsSchema.parse({}); export const SESSION_COOKIE_NAME = 'gcoord_sid'; -export class AuthOverloadError extends Error { - readonly code = 'AUTH_OVERLOADED'; - constructor(message = 'Authentication queue is busy; try again shortly') { - super(message); - this.name = 'AuthOverloadError'; - } -} - -export function loadOrCreateDbKey(options: { dataDir?: string; envDbKey?: string }): Buffer { - if (options.envDbKey && options.envDbKey.trim().length > 0) { - const clean = options.envDbKey.trim().toLowerCase(); - if (!/^[0-9a-f]{64}$/.test(clean)) { - throw new Error('GCOORD_DB_KEY must be exactly 64 hex characters (32 bytes)'); - } - return Buffer.from(clean, 'hex'); - } - - if (!options.dataDir) { - return crypto.randomBytes(32); - } - - const keyPath = path.join(options.dataDir, 'db.key'); - try { - const stat = fs.lstatSync(keyPath); - if (stat.isSymbolicLink() || !stat.isFile()) { - throw new Error(`Refusing symlink or non-file db key at ${keyPath}`); - } - const clean = fs.readFileSync(keyPath, 'utf8').trim().toLowerCase(); - if (!/^[0-9a-f]{64}$/.test(clean)) { - throw new Error(`Invalid db.key format at ${keyPath}`); - } - try { - fs.chmodSync(keyPath, 0o600); - } catch { - // Best-effort POSIX permission tightening - } - return Buffer.from(clean, 'hex'); - } catch (err) { - if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') { - throw err; - } - } - - const key = crypto.randomBytes(32); - const hex = `${key.toString('hex')}\n`; - try { - fs.mkdirSync(path.dirname(keyPath), { recursive: true, mode: 0o700 }); - const fd = fs.openSync( - keyPath, - fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, - 0o600, - ); - try { - fs.writeSync(fd, hex, 0, 'utf8'); - fs.fsyncSync(fd); - } finally { - fs.closeSync(fd); - } - return key; - } catch (err) { - if ((err as NodeJS.ErrnoException)?.code === 'EEXIST') { - const clean = fs.readFileSync(keyPath, 'utf8').trim().toLowerCase(); - if (!/^[0-9a-f]{64}$/.test(clean)) { - throw new Error(`Invalid db.key format at ${keyPath}`); - } - return Buffer.from(clean, 'hex'); - } - throw err; - } -} - -export function encryptTotpSecret(dbKey: Buffer, totpId: string, secretBase32: string): string { - const iv = crypto.randomBytes(12); - const cipher = crypto.createCipheriv('aes-256-gcm', dbKey, iv); - cipher.setAAD(Buffer.from(`gcoord-totp-v1:${totpId}`, 'utf8')); - const ct = Buffer.concat([cipher.update(secretBase32, 'utf8'), cipher.final()]); - const tag = cipher.getAuthTag(); - return `v1:${iv.toString('hex')}:${tag.toString('hex')}:${ct.toString('hex')}`; -} - -export function decryptTotpSecret(dbKey: Buffer, totpId: string, encoded: string): string { - const parts = encoded.split(':'); - if (parts.length !== 4 || parts[0] !== 'v1') { - throw new Error(`Invalid encrypted TOTP envelope for ${totpId}`); - } - const iv = Buffer.from(parts[1]!, 'hex'); - const tag = Buffer.from(parts[2]!, 'hex'); - const ct = Buffer.from(parts[3]!, 'hex'); - const decipher = crypto.createDecipheriv('aes-256-gcm', dbKey, iv); - decipher.setAAD(Buffer.from(`gcoord-totp-v1:${totpId}`, 'utf8')); - decipher.setAuthTag(tag); - return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8'); -} - -function timingSafeStringEqual(a: string, b: string): boolean { - const bufA = Buffer.from(a, 'utf8'); - const bufB = Buffer.from(b, 'utf8'); - if (bufA.length !== bufB.length) return false; - return crypto.timingSafeEqual(bufA, bufB); -} - export interface AuthSession { idHash: string; csrfTokenHash: string; @@ -200,16 +96,8 @@ export type StepUpInput = export interface AuthServiceOptions { getSecuritySettings?: () => SecuritySettings; - getRuntimeLimits?: () => RuntimeLimits; recoveryStore?: EmergencyRecoveryService; vaultService?: VaultService; - dataDir?: string; - envDbKey?: string; - onSecurityEvent?: (event: { - type: string; - ip?: string; - details?: Record; - }) => void; } interface AdminRow { @@ -232,10 +120,8 @@ interface TotpRow { id: string; label: string; secret_base32: string; - secret_enc: string | null; last_login_step: number | null; last_stepup_step: number | null; - last_used_step: number | null; created_at: number; } @@ -293,8 +179,6 @@ function computeElevatedUntil( return fromLogin ? null : nowMs + 60_000; case '5m': return nowMs + 5 * 60 * 1000; - case '15m': - return nowMs + 15 * 60 * 1000; case '1h': return nowMs + 60 * 60 * 1000; case '24h': @@ -305,21 +189,13 @@ function computeElevatedUntil( } export class AuthService { - private pendingBootstrap: { secretBase32: string; token: string; createdAt: number } | null = null; + private pendingBootstrap: { secretBase32: string; createdAt: number } | null = null; private readonly pendingEnrollments = new Map< string, { label: string; secretBase32: string; createdAt: number } >(); private readonly pendingWebAuthn = new Map(); - private readonly sessionRevokedListeners = new Set<(idHashes: string[]) => void>(); private readonly getSecurity: () => SecuritySettings; - private readonly getRuntimeLimits?: () => RuntimeLimits; - private onSecurityEvent?: AuthServiceOptions['onSecurityEvent']; - private readonly dbKey: Buffer; - private readonly sessionReaperTimer: NodeJS.Timeout; - private argon2Active = 0; - private readonly argon2Queue: Array<{ resolve: () => void; reject: (err: Error) => void }> = []; - private dummyArgon2Hash: string | null = null; private recoveryStore?: EmergencyRecoveryService; private vaultService?: VaultService; @@ -328,169 +204,8 @@ export class AuthService { options: AuthServiceOptions = {}, ) { this.getSecurity = options.getSecuritySettings ?? (() => DEFAULT_SECURITY); - this.getRuntimeLimits = options.getRuntimeLimits; - this.onSecurityEvent = options.onSecurityEvent; this.recoveryStore = options.recoveryStore; this.vaultService = options.vaultService; - - const inferredDir = - options.dataDir ?? - (db.name && db.name !== ':memory:' ? path.dirname(db.name) : undefined); - this.dbKey = loadOrCreateDbKey({ dataDir: inferredDir, envDbKey: options.envDbKey }); - this.migratePlaintextTotpsIfNeeded(); - - this.sessionReaperTimer = setInterval(() => { - this.reapExpiredSessions(); - }, SESSION_REAPER_MS); - this.sessionReaperTimer.unref(); - } - - close(): void { - clearInterval(this.sessionReaperTimer); - while (this.argon2Queue.length > 0) { - const waiter = this.argon2Queue.shift()!; - waiter.reject(new Error('AuthService shutting down')); - } - } - - setSecurityEventListener(listener: AuthServiceOptions['onSecurityEvent']): void { - this.onSecurityEvent = listener; - } - - emitSecurityEvent(type: string, ip?: string, details?: Record): void { - try { - this.onSecurityEvent?.({ type, ip, details }); - } catch { - // Never let security event hook break authentication flow - } - } - - onSessionsRevoked(listener: (idHashes: string[]) => void): () => void { - this.sessionRevokedListeners.add(listener); - return () => { - this.sessionRevokedListeners.delete(listener); - }; - } - - private notifySessionsRevoked(idHashes: string[]): void { - if (idHashes.length === 0) return; - for (const listener of this.sessionRevokedListeners) { - try { - listener(idHashes); - } catch { - // Ignore subscriber errors - } - } - } - - private async runArgon2(task: (memoryCost: number) => Promise): Promise { - const limits = this.getRuntimeLimits?.(); - const concurrency = Math.max(1, limits?.argon2Concurrency ?? 2); - const maxQueue = Math.max(1, limits?.argon2MaxQueue ?? 16); - const memoryCost = limits?.argon2MemoryCost ?? 32768; - - if (this.argon2Active >= concurrency) { - if (this.argon2Queue.length >= maxQueue) { - throw new AuthOverloadError(); - } - await new Promise((resolve, reject) => { - this.argon2Queue.push({ resolve, reject }); - }); - } - - this.argon2Active += 1; - try { - return await task(memoryCost); - } finally { - this.argon2Active -= 1; - const next = this.argon2Queue.shift(); - if (next) next.resolve(); - } - } - - private hashPassword(password: string): Promise { - return this.runArgon2((memoryCost) => - argon2.hash(password, { - type: argon2.argon2id, - memoryCost, - timeCost: 3, - parallelism: 1, - }), - ); - } - - private verifyPasswordHash(hash: string, candidate: string): Promise { - return this.runArgon2(() => argon2.verify(hash, candidate).catch(() => false)); - } - - private async verifyDummyPassword(candidate: string): Promise { - if (!this.dummyArgon2Hash) { - this.dummyArgon2Hash = await this.hashPassword('gcoord-dummy-timing-guard-v1'); - } - await this.verifyPasswordHash(this.dummyArgon2Hash, candidate); - } - - private getTotpSecret(row: TotpRow): string { - if (row.secret_enc && row.secret_enc.startsWith('v1:')) { - return decryptTotpSecret(this.dbKey, row.id, row.secret_enc); - } - if (row.secret_base32 && row.secret_base32.length > 0) { - const enc = encryptTotpSecret(this.dbKey, row.id, row.secret_base32); - try { - this.db - .prepare("UPDATE admin_totps SET secret_enc = ?, secret_base32 = '' WHERE id = ?") - .run(enc, row.id); - } catch { - // Ignore read-only DB edge case - } - return row.secret_base32; - } - throw new Error(`Missing TOTP secret for ${row.id}`); - } - - private migratePlaintextTotpsIfNeeded(): void { - try { - const rows = this.db - .prepare("SELECT id, secret_base32 FROM admin_totps WHERE (secret_enc IS NULL OR secret_enc = '') AND secret_base32 != ''") - .all() as Array<{ id: string; secret_base32: string }>; - if (rows.length === 0) return; - const tx = this.db.transaction(() => { - const stmt = this.db.prepare( - "UPDATE admin_totps SET secret_enc = ?, secret_base32 = '' WHERE id = ?", - ); - for (const r of rows) { - stmt.run(encryptTotpSecret(this.dbKey, r.id, r.secret_base32), r.id); - } - }); - tx(); - } catch { - // Safe before migrations finish if constructed manually - } - } - - reapExpiredSessions(): number { - const now = Date.now(); - const sec = this.getSecurity(); - const idleMs = (sec.sessionIdleTimeoutMin ?? 60) * 60 * 1000; - const rows = - idleMs > 0 - ? (this.db - .prepare('SELECT id_hash FROM sessions WHERE expires_at <= ? OR last_seen_at <= ?') - .all(now, now - idleMs) as Array<{ id_hash: string }>) - : (this.db - .prepare('SELECT id_hash FROM sessions WHERE expires_at <= ?') - .all(now) as Array<{ id_hash: string }>); - if (rows.length === 0) return 0; - const hashes = rows.map((r) => r.id_hash); - if (idleMs > 0) { - this.db - .prepare('DELETE FROM sessions WHERE expires_at <= ? OR last_seen_at <= ?') - .run(now, now - idleMs); - } else { - this.db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(now); - } - this.notifySessionsRevoked(hashes); - return hashes.length; } attachRecoveryDependencies( @@ -542,11 +257,9 @@ export class AuthService { } async beginBootstrap(username = 'admin'): Promise<{ - bootstrapToken: string; secretBase32: string; otpauthUri: string; qrSvg: string; - qrDataUri: string; }> { if (this.isBootstrapped()) { throw new Error('Admin account is already configured'); @@ -559,24 +272,17 @@ export class AuthService { const secret = new OTPAuth.Secret({ size: 20 }); this.pendingBootstrap = { secretBase32: secret.base32, - token: crypto.randomBytes(24).toString('base64url'), createdAt: Date.now(), }; } - const cleanUser = username.trim().slice(0, 64) || 'admin'; - const totp = buildTotp(this.pendingBootstrap.secretBase32, cleanUser); + const totp = buildTotp(this.pendingBootstrap.secretBase32, username); const otpauthUri = totp.toString(); - const [qrSvg, qrDataUri] = await Promise.all([ - QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }), - QRCode.toDataURL(otpauthUri, { margin: 1, width: 220 }), - ]); + const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }); return { - bootstrapToken: this.pendingBootstrap.token, secretBase32: this.pendingBootstrap.secretBase32, otpauthUri, qrSvg, - qrDataUri, }; } @@ -585,7 +291,6 @@ export class AuthService { password: string; totpCode: string; secretBase32?: string; - bootstrapToken?: string; ip: string; userAgent: string; initialSafeMode?: boolean; @@ -606,30 +311,11 @@ export class AuthService { throw new Error('Password must be at least 10 characters'); } - if ( - !this.pendingBootstrap || - Date.now() - this.pendingBootstrap.createdAt > BOOTSTRAP_TTL_MS - ) { - this.pendingBootstrap = null; + const secretBase32 = params.secretBase32 ?? this.pendingBootstrap?.secretBase32; + if (!secretBase32) { throw new Error('Bootstrap enrollment session expired; reload setup'); } - if ( - params.bootstrapToken !== undefined && - !timingSafeStringEqual(params.bootstrapToken, this.pendingBootstrap.token) - ) { - throw new Error('Invalid bootstrap session token; reload setup'); - } - - if ( - params.secretBase32 !== undefined && - !timingSafeStringEqual(params.secretBase32.trim(), this.pendingBootstrap.secretBase32) - ) { - throw new Error('Bootstrap secret mismatch; reload setup'); - } - - const secretBase32 = this.pendingBootstrap.secretBase32; - const nowMs = Date.now(); const totp = buildTotp(secretBase32, username); const delta = totp.validate({ @@ -642,8 +328,12 @@ export class AuthService { } const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; - const passwordHash = await this.hashPassword(params.password); - const secretEnc = encryptTotpSecret(this.dbKey, 'totp-primary', secretBase32); + const passwordHash = await argon2.hash(params.password, { + type: argon2.argon2id, + memoryCost: 65536, + timeCost: 3, + parallelism: 1, + }); const recoveryCodes: string[] = []; for (let i = 0; i < 8; i++) { @@ -654,9 +344,9 @@ export class AuthService { this.db .prepare( `INSERT INTO admin_users (id, username, password_hash, totp_secret, last_login_totp_step, last_stepup_totp_step, created_at, updated_at) - VALUES (1, ?, '', '', ?, ?, ?, ?)`, + VALUES (1, ?, ?, ?, ?, NULL, ?, ?)`, ) - .run(username, matchedStep, matchedStep, nowMs, nowMs); + .run(username, passwordHash, secretBase32, matchedStep, nowMs, nowMs); this.db .prepare( @@ -666,10 +356,10 @@ export class AuthService { this.db .prepare( - `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) - VALUES (?, ?, '', ?, ?, ?, ?, ?)`, + `INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at) + VALUES (?, ?, ?, ?, NULL, ?)`, ) - .run('totp-primary', 'Primary Authenticator', secretEnc, matchedStep, matchedStep, matchedStep, nowMs); + .run('totp-primary', 'Primary Authenticator', secretBase32, matchedStep, nowMs); const insertRec = this.db.prepare( 'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)', @@ -682,6 +372,12 @@ export class AuthService { this.pendingBootstrap = null; this.syncRecovery({ + passwordPlaintextUpdate: { + id: 'pw-primary', + label: 'Primary Password', + password: params.password, + createdAt: nowMs, + }, newRecoveryCodes: recoveryCodes, snapshotReason: 'bootstrap', }); @@ -707,35 +403,28 @@ export class AuthService { const admin = this.db .prepare('SELECT * FROM admin_users WHERE id = 1') .get() as AdminRow | undefined; - const suppliedPasswords = ( - params.passwords ?? (params.password !== undefined ? [params.password] : []) - ) - .filter((p) => p.length > 0) - .slice(0, 16); - const cleanUser = params.username?.trim() ?? ''; + if (!admin) return null; - if ( - !admin || - !cleanUser || - cleanUser.length > 64 || - suppliedPasswords.length === 0 || - !timingSafeStringEqual(cleanUser, admin.username) - ) { - await this.verifyDummyPassword(suppliedPasswords[0] ?? 'dummy'); + if (params.username && params.username.trim() !== admin.username) { return null; } const sec = this.getSecurity(); + const suppliedPasswords = ( + params.passwords ?? (params.password !== undefined ? [params.password] : []) + ).filter((p) => p.length > 0); + if (suppliedPasswords.length === 0) return null; + const pwOk = await this.verifyPasswords(suppliedPasswords, sec.passwordMode); if (!pwOk) return null; - if (sec.requireTotpOnLogin) { + const totpRows = this.listTotpRows(); + if (sec.requireTotpOnLogin && totpRows.length > 0) { const suppliedCodes = ( params.codes ?? (params.code !== undefined ? [params.code] : []) ) .map((c) => c.trim()) - .filter((c) => c.length > 0) - .slice(0, 16); + .filter((c) => c.length > 0); if (suppliedCodes.length === 0) return null; @@ -744,7 +433,6 @@ export class AuthService { sec.totpMode, 'login', admin.username, - params.ip, ); if (!mfaOk) return null; } @@ -758,11 +446,7 @@ export class AuthService { getSessionByToken(sessionToken: string | undefined): AuthSession | null { if (!sessionToken || sessionToken.length < 16) return null; - return this.getSessionByHash(sha256Hex(sessionToken)); - } - - getSessionByHash(idHash: string | undefined): AuthSession | null { - if (!idHash || idHash.length < 16) return null; + const idHash = sha256Hex(sessionToken); const row = this.db .prepare('SELECT * FROM sessions WHERE id_hash = ?') .get(idHash) as SessionRow | undefined; @@ -771,24 +455,10 @@ export class AuthService { const now = Date.now(); if (row.expires_at <= now) { this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); - this.notifySessionsRevoked([idHash]); return null; } - const sec = this.getSecurity(); - const idleMs = (sec.sessionIdleTimeoutMin ?? 60) * 60 * 1000; - if (idleMs > 0 && now - row.last_seen_at > idleMs) { - this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); - this.notifySessionsRevoked([idHash]); - this.emitSecurityEvent('auth.session_idle_expired', row.ip, { - idPrefix: idHash.slice(0, 12), - }); - return null; - } - - const touchIntervalMs = - idleMs > 0 ? Math.min(60_000, Math.max(1000, Math.floor(idleMs / 4))) : 60_000; - if (now - row.last_seen_at > touchIntervalMs) { + if (now - row.last_seen_at > 60_000) { this.db .prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?') .run(now, idHash); @@ -856,17 +526,20 @@ export class AuthService { } if (sec.stepUpMethod === 'totp' || sec.stepUpMethod === 'both') { - if (suppliedCodes.length === 0) { - return { ok: false, reason: 'invalid_totp' }; - } - const totpResult = this.verifyTotpRows( - suppliedCodes, - sec.totpMode, - 'stepup', - admin.username, - ); - if (!totpResult.ok) { - return { ok: false, reason: totpResult.reason }; + const totpRows = this.listTotpRows(); + if (totpRows.length > 0) { + if (suppliedCodes.length === 0) { + return { ok: false, reason: 'invalid_totp' }; + } + const totpResult = this.verifyTotpRows( + suppliedCodes, + sec.totpMode, + 'stepup', + admin.username, + ); + if (!totpResult.ok) { + return { ok: false, reason: totpResult.reason }; + } } } @@ -1011,7 +684,7 @@ export class AuthService { })), authenticatorSelection: { residentKey: 'preferred', - userVerification: 'required', + userVerification: 'preferred', }, }); @@ -1042,7 +715,7 @@ export class AuthService { expectedChallenge: pending.challenge, expectedOrigin: pending.expectedOrigin, expectedRPID: pending.rpID, - requireUserVerification: true, + requireUserVerification: false, }); if (!verification.verified || !verification.registrationInfo) { @@ -1107,7 +780,7 @@ export class AuthService { ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, })), - userVerification: 'required', + userVerification: 'preferred', }); const challengeId = crypto.randomBytes(16).toString('hex'); @@ -1133,14 +806,6 @@ export class AuthService { if (!this.isBootstrapped()) return null; const pending = this.consumeWebAuthnChallenge(params.challengeId, 'login'); if (!pending) return null; - if ( - !params.response || - typeof params.response.id !== 'string' || - params.response.id.length === 0 || - params.response.id.length > 512 - ) { - return null; - } const row = this.db .prepare('SELECT * FROM webauthn_credentials WHERE id = ?') @@ -1161,7 +826,7 @@ export class AuthService { ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, }, - requireUserVerification: true, + requireUserVerification: false, }); if (!verification.verified) return null; @@ -1196,22 +861,11 @@ export class AuthService { if (session.safe_mode === 1) { return { ok: false, reason: 'safe_mode_active' }; } - if (sec.stepUpMethod !== 'passkey') { - return { ok: false, reason: 'passkey_stepup_not_enabled' }; - } const pending = this.consumeWebAuthnChallenge(params.challengeId, 'stepup'); if (!pending || pending.sessionIdHash !== params.idHash) { return { ok: false, reason: 'invalid_challenge' }; } - if ( - !params.response || - typeof params.response.id !== 'string' || - params.response.id.length === 0 || - params.response.id.length > 512 - ) { - return { ok: false, reason: 'invalid_assertion' }; - } const row = this.db .prepare('SELECT * FROM webauthn_credentials WHERE id = ?') @@ -1232,7 +886,7 @@ export class AuthService { ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, }, - requireUserVerification: true, + requireUserVerification: false, }); if (!verification.verified) { return { ok: false, reason: 'invalid_assertion' }; @@ -1272,7 +926,12 @@ export class AuthService { const id = `pw-${crypto.randomBytes(4).toString('hex')}`; const createdAt = Date.now(); - const hash = await this.hashPassword(password); + const hash = await argon2.hash(password, { + type: argon2.argon2id, + memoryCost: 65536, + timeCost: 3, + parallelism: 1, + }); this.db .prepare( @@ -1281,6 +940,12 @@ export class AuthService { .run(id, cleanLabel, hash, createdAt); this.syncRecovery({ + passwordPlaintextUpdate: { + id, + label: cleanLabel, + password, + createdAt, + }, snapshotReason: 'password-added', }); @@ -1307,7 +972,6 @@ export class AuthService { secretBase32: string; otpauthUri: string; qrSvg: string; - qrDataUri: string; }> { const cleanLabel = label.trim(); if (cleanLabel.length < 1 || cleanLabel.length > 64) { @@ -1331,17 +995,13 @@ export class AuthService { const username = this.getAdminUsername() ?? 'admin'; const totp = buildTotp(secret.base32, `${username} (${cleanLabel})`); const otpauthUri = totp.toString(); - const [qrSvg, qrDataUri] = await Promise.all([ - QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }), - QRCode.toDataURL(otpauthUri, { margin: 1, width: 220 }), - ]); + const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }); return { enrollmentId, label: cleanLabel, secretBase32: secret.base32, otpauthUri, qrSvg, - qrDataUri, }; } @@ -1369,13 +1029,12 @@ export class AuthService { const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; const id = `totp-${crypto.randomBytes(4).toString('hex')}`; - const secretEnc = encryptTotpSecret(this.dbKey, id, pending.secretBase32); this.db .prepare( - `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) - VALUES (?, ?, '', ?, ?, ?, ?, ?)`, + `INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at) + VALUES (?, ?, ?, ?, ?, ?)`, ) - .run(id, pending.label, secretEnc, matchedStep, matchedStep, matchedStep, nowMs); + .run(id, pending.label, pending.secretBase32, matchedStep, matchedStep, nowMs); this.pendingEnrollments.delete(enrollmentId); this.syncRecovery({ snapshotReason: 'totp-added' }); @@ -1429,6 +1088,12 @@ export class AuthService { syncRecovery( overrides: { + passwordPlaintextUpdate?: { + id: string; + label: string; + password: string; + createdAt?: number; + }; removedPasswordId?: string; newRecoveryCodes?: string[]; snapshotReason?: string; @@ -1443,19 +1108,16 @@ export class AuthService { .prepare('SELECT id, label, created_at AS createdAt FROM admin_passwords ORDER BY created_at ASC') .all() as Array<{ id: string; label: string; createdAt: number }>; const totpRows = this.listTotpRows(); - const totps: SavedTotpEntry[] = totpRows.map((t) => { - const secretBase32 = this.getTotpSecret(t); - return { - id: t.id, - label: t.label, - secretBase32, - otpauthUri: buildTotp( - secretBase32, - username ? `${username} (${t.label})` : t.label, - ).toString(), - createdAt: new Date(t.created_at).toISOString(), - }; - }); + const totps: SavedTotpEntry[] = totpRows.map((t) => ({ + id: t.id, + label: t.label, + secretBase32: t.secret_base32, + otpauthUri: buildTotp( + t.secret_base32, + username ? `${username} (${t.label})` : t.label, + ).toString(), + createdAt: new Date(t.created_at).toISOString(), + })); this.recoveryStore.syncState({ enabled: sec.enableEmergencySecretsBackup, @@ -1488,43 +1150,24 @@ export class AuthService { } revokeSessionByHash(idHash: string): void { - const res = this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); - if (res.changes > 0) { - this.notifySessionsRevoked([idHash]); - } + this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); } revokeSessionByPrefix(prefix: string): number { if (!/^[0-9a-f]{8,64}$/i.test(prefix)) return 0; - const rows = this.db - .prepare('SELECT id_hash FROM sessions WHERE id_hash LIKE ?') - .all(`${prefix}%`) as Array<{ id_hash: string }>; - if (rows.length === 0) return 0; const result = this.db .prepare('DELETE FROM sessions WHERE id_hash LIKE ?') .run(`${prefix}%`); - if (result.changes > 0) { - this.notifySessionsRevoked(rows.map((r) => r.id_hash)); - } return result.changes; } revokeAllSessions(exceptIdHash?: string): number { - const rows = ( - exceptIdHash - ? this.db - .prepare('SELECT id_hash FROM sessions WHERE id_hash != ?') - .all(exceptIdHash) - : this.db.prepare('SELECT id_hash FROM sessions').all() - ) as Array<{ id_hash: string }>; - if (rows.length === 0) return 0; - const changes = exceptIdHash - ? this.db.prepare('DELETE FROM sessions WHERE id_hash != ?').run(exceptIdHash).changes - : this.db.prepare('DELETE FROM sessions').run().changes; - if (changes > 0) { - this.notifySessionsRevoked(rows.map((r) => r.id_hash)); + if (exceptIdHash) { + return this.db + .prepare('DELETE FROM sessions WHERE id_hash != ?') + .run(exceptIdHash).changes; } - return changes; + return this.db.prepare('DELETE FROM sessions').run().changes; } private listTotpRows(): TotpRow[] { @@ -1545,7 +1188,7 @@ export class AuthService { if (mode === 'any') { for (const row of rows) { for (const candidate of suppliedPasswords) { - if (await this.verifyPasswordHash(row.password_hash, candidate)) { + if (await argon2.verify(row.password_hash, candidate)) { return true; } } @@ -1557,7 +1200,7 @@ export class AuthService { for (const row of rows) { let rowMatched = false; for (const candidate of suppliedPasswords) { - if (await this.verifyPasswordHash(row.password_hash, candidate)) { + if (await argon2.verify(row.password_hash, candidate)) { rowMatched = true; break; } @@ -1572,9 +1215,8 @@ export class AuthService { mode: 'any' | 'all', purpose: 'login' | 'stepup', username: string, - ip?: string, ): boolean { - const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username, ip); + const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username); if (totpRes.ok) return true; // In 'any' mode, a single-use recovery code may replace TOTP @@ -1588,48 +1230,33 @@ export class AuthService { 'UPDATE recovery_codes SET used_at = ? WHERE code_hash = ? AND used_at IS NULL', ) .run(Date.now(), sha256Hex(normalized)); - if (updated.changes === 1) { - this.emitSecurityEvent('auth.recovery_code_used', ip, { username }); - return true; - } + if (updated.changes === 1) return true; } } return false; } - private getRowLastUsedStep(row: TotpRow): number | null { - if (row.last_used_step !== null && row.last_used_step !== undefined) { - return row.last_used_step; - } - const candidates = [row.last_login_step, row.last_stepup_step].filter( - (n): n is number => typeof n === 'number', - ); - return candidates.length > 0 ? Math.max(...candidates) : null; - } - private verifyTotpRows( suppliedCodes: string[], mode: 'any' | 'all', purpose: 'login' | 'stepup', username: string, - ip?: string, ): { ok: true } | { ok: false; reason: string } { const rows = this.listTotpRows(); - if (rows.length === 0) { - return { ok: false, reason: 'totp_not_configured' }; - } + if (rows.length === 0) return { ok: true }; const numericCodes = suppliedCodes.filter((c) => /^\d{6}$/.test(c)); if (numericCodes.length === 0) return { ok: false, reason: 'invalid_totp' }; const nowMs = Date.now(); + const stepCol = purpose === 'login' ? 'last_login_step' : 'last_stepup_step'; if (mode === 'any') { let sawReplay = false; for (const row of rows) { - const secret = this.getTotpSecret(row); - const totp = buildTotp(secret, username); - const lastStep = this.getRowLastUsedStep(row); + const totp = buildTotp(row.secret_base32, username); + const lastStep = + purpose === 'login' ? row.last_login_step : row.last_stepup_step; for (const code of numericCodes) { const delta = totp.validate({ token: code, window: 1, timestamp: nowMs }); if (delta === null) continue; @@ -1639,25 +1266,20 @@ export class AuthService { continue; } this.db - .prepare( - 'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?', - ) - .run(matchedStep, matchedStep, matchedStep, row.id); + .prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`) + .run(matchedStep, row.id); return { ok: true }; } } - if (sawReplay) { - this.emitSecurityEvent('auth.totp_replay', ip, { purpose }); - } return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; } // 'all': every configured TOTP authenticator must match a supplied valid non-replayed code const matchedUpdates: Array<{ id: string; step: number }> = []; for (const row of rows) { - const secret = this.getTotpSecret(row); - const totp = buildTotp(secret, username); - const lastStep = this.getRowLastUsedStep(row); + const totp = buildTotp(row.secret_base32, username); + const lastStep = + purpose === 'login' ? row.last_login_step : row.last_stepup_step; let rowStep: number | null = null; let sawReplay = false; @@ -1674,20 +1296,15 @@ export class AuthService { } if (rowStep === null) { - if (sawReplay) { - this.emitSecurityEvent('auth.totp_replay', ip, { purpose }); - } return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; } matchedUpdates.push({ id: row.id, step: rowStep }); } const tx = this.db.transaction(() => { - const stmt = this.db.prepare( - 'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?', - ); + const stmt = this.db.prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`); for (const upd of matchedUpdates) { - stmt.run(upd.step, upd.step, upd.step, upd.id); + stmt.run(upd.step, upd.id); } }); tx(); @@ -1704,9 +1321,8 @@ export class AuthService { const idHash = sha256Hex(sessionToken); const csrfTokenHash = sha256Hex(csrfToken); const now = Date.now(); + const expiresAt = now + SESSION_TTL_MS; const sec = this.getSecurity(); - const ttlMs = (sec.sessionTtlHours ?? 168) * 60 * 60 * 1000; - const expiresAt = now + ttlMs; const shouldElevate = sec.elevateOnLogin && (!safeMode || sec.keepElevationOnSafeMode); diff --git a/src/server/security/backup-scheduler.ts b/src/server/security/backup-scheduler.ts deleted file mode 100644 index abd4409..0000000 --- a/src/server/security/backup-scheduler.ts +++ /dev/null @@ -1,275 +0,0 @@ -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import path from 'node:path'; -import { Readable } from 'node:stream'; -import type Database from 'better-sqlite3'; -import { Cron } from 'croner'; -import type { ConfigManager } from '../config/config-manager.js'; -import type { RuntimeLimits } from '../config/runtime-limits.js'; -import type { SftpService } from '../ssh/sftp-service.js'; -import type { AuditService } from './audit.js'; -import { createBackupBundleAsync } from './backup.js'; -import type { VaultService } from './vault.js'; - -export interface ScheduledBackupStatus { - enabled: boolean; - cron: string; - timezone: string; - destination: 'local' | 'sftp'; - running: boolean; - lastRunAt: number | null; - lastStatus: 'never' | 'ok' | 'error' | 'skipped'; - lastFilename: string | null; - lastError: string | null; - nextRunAt: number | null; - localFiles: Array<{ name: string; sizeBytes: number; mtimeMs: number }>; -} - -function resolveSafeLocalBackupDir(dataDir: string, rawLocalDir: string): string { - const baseDir = path.resolve(dataDir); - const rel = rawLocalDir.trim() || 'backups'; - if (path.isAbsolute(rel) || rel.includes('..') || rel.includes('\\')) { - throw new Error(`Unsafe local backup directory: ${rawLocalDir}`); - } - const targetDir = path.resolve(baseDir, rel); - if (targetDir === baseDir || !targetDir.startsWith(`${baseDir}${path.sep}`)) { - throw new Error(`Local backup directory must stay inside dataDir: ${rawLocalDir}`); - } - return targetDir; -} - -export class BackupScheduler { - private job: Cron | null = null; - private running = false; - private closed = false; - private lastRunAt: number | null = null; - private lastStatus: ScheduledBackupStatus['lastStatus'] = 'never'; - private lastFilename: string | null = null; - private lastError: string | null = null; - - constructor( - private readonly dataDir: string, - private readonly db: Database.Database, - private readonly configManager: ConfigManager, - private readonly vaultService: VaultService, - private readonly sftpService: SftpService, - private readonly auditService: AuditService, - private readonly getRuntimeLimits: () => RuntimeLimits, - ) {} - - start(): void { - this.sync(); - } - - stop(): void { - if (this.job) { - this.job.stop(); - this.job = null; - } - } - - close(): void { - this.closed = true; - this.stop(); - } - - sync(): void { - this.stop(); - if (this.closed || !this.vaultService.isRuntimeReady || this.vaultService.isPanicLocked) { - return; - } - const cfg = this.configManager.getSettings().scheduledBackup; - if (!cfg?.enabled) { - return; - } - try { - this.job = new Cron( - cfg.cron, - { - timezone: cfg.timezone || 'UTC', - protect: true, - }, - () => { - void this.runNow('cron'); - }, - ); - } catch (err) { - this.lastStatus = 'error'; - this.lastError = err instanceof Error ? err.message : 'Invalid backup cron expression'; - } - } - - getStatus(): ScheduledBackupStatus { - const cfg = this.configManager.getSettings().scheduledBackup; - let localFiles: ScheduledBackupStatus['localFiles'] = []; - try { - const dir = resolveSafeLocalBackupDir(this.dataDir, cfg.localDir); - if (fs.existsSync(dir) && !fs.lstatSync(dir).isSymbolicLink()) { - localFiles = fs - .readdirSync(dir) - .filter((name) => name.endsWith('.gcoord.enc')) - .map((name) => { - const p = path.join(dir, name); - const st = fs.lstatSync(p); - return !st.isSymbolicLink() && st.isFile() - ? { name, sizeBytes: st.size, mtimeMs: st.mtimeMs } - : null; - }) - .filter((v): v is NonNullable => v !== null) - .sort((a, b) => b.mtimeMs - a.mtimeMs); - } - } catch { - localFiles = []; - } - - const nextDate = this.job?.nextRun() ?? null; - return { - enabled: Boolean(cfg.enabled), - cron: cfg.cron, - timezone: cfg.timezone, - destination: cfg.destination, - running: this.running, - lastRunAt: this.lastRunAt, - lastStatus: this.lastStatus, - lastFilename: this.lastFilename, - lastError: this.lastError, - nextRunAt: nextDate ? nextDate.getTime() : null, - localFiles, - }; - } - - async runNow(trigger: 'cron' | 'manual' = 'manual'): Promise<{ - ok: boolean; - filename?: string; - message?: string; - }> { - if (this.closed) { - return { ok: false, message: 'Scheduler stopped' }; - } - if (this.running) { - return { ok: false, message: 'Scheduled backup already in progress' }; - } - if (!this.vaultService.isRuntimeReady || this.vaultService.isPanicLocked) { - this.lastRunAt = Date.now(); - this.lastStatus = 'skipped'; - this.lastError = 'Vault is sealed'; - return { ok: false, message: 'Vault is sealed' }; - } - - const cfg = this.configManager.getSettings().scheduledBackup; - this.running = true; - try { - let passphrase: string | undefined; - if (cfg.passphraseSecretRef) { - const cred = this.vaultService.getSecret(cfg.passphraseSecretRef); - if (!cred) { - throw new Error(`Backup passphrase secret "${cfg.passphraseSecretRef}" not found in Vault`); - } - passphrase = - cred.type === 'api-token' - ? cred.token - : cred.type === 'webhook-secret' - ? cred.secret - : undefined; - if (!passphrase) { - throw new Error( - `Credential "${cfg.passphraseSecretRef}" must be an api-token or webhook-secret`, - ); - } - } - - const masterKey = this.vaultService.exportMasterKeyHex() ?? undefined; - const limits = this.getRuntimeLimits(); - const result = await createBackupBundleAsync({ - dataDir: this.dataDir, - db: this.db, - masterKey, - passphrase, - scryptConcurrency: limits.scryptConcurrency, - }); - - const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); - const filename = `gcoord-sched-${stamp}.gcoord.enc`; - - if (cfg.destination === 'sftp') { - if (!cfg.remoteServerId || !cfg.remotePath) { - throw new Error('SFTP scheduled backup requires remoteServerId and remotePath'); - } - const remoteDir = path.posix.normalize(cfg.remotePath).replace(/\/+$/, '') || '/'; - const remoteFile = path.posix.join(remoteDir, filename); - const buf = Buffer.from(result.serialized, 'utf8'); - await this.sftpService.uploadStream(cfg.remoteServerId, remoteFile, Readable.from([buf])); - try { - const listing = await this.sftpService.listDirectory(cfg.remoteServerId, remoteDir); - const oldFiles = listing.entries - .filter( - (e) => - e.type === 'file' && - e.name.startsWith('gcoord-sched-') && - e.name.endsWith('.gcoord.enc'), - ) - .sort((a, b) => b.mtimeMs - a.mtimeMs); - for (const stale of oldFiles.slice(cfg.retentionCount)) { - await this.sftpService.deletePath(cfg.remoteServerId, stale.path, false); - } - } catch { - // Best-effort remote retention pruning - } - } else { - const dir = resolveSafeLocalBackupDir(this.dataDir, cfg.localDir); - fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); - const outPath = path.join(dir, filename); - const tmpPath = `${outPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; - const fd = fs.openSync(tmpPath, 'w', 0o600); - try { - fs.writeFileSync(fd, result.serialized, 'utf8'); - fs.fsyncSync(fd); - } finally { - fs.closeSync(fd); - } - fs.renameSync(tmpPath, outPath); - fs.chmodSync(outPath, 0o600); - - const existing = fs - .readdirSync(dir) - .filter((n) => n.startsWith('gcoord-sched-') && n.endsWith('.gcoord.enc')) - .map((n) => ({ - path: path.join(dir, n), - mtime: fs.lstatSync(path.join(dir, n)).mtimeMs, - })) - .sort((a, b) => b.mtime - a.mtime); - for (const stale of existing.slice(cfg.retentionCount)) { - fs.rmSync(stale.path, { force: true }); - } - } - - this.lastRunAt = Date.now(); - this.lastStatus = 'ok'; - this.lastFilename = filename; - this.lastError = null; - this.auditService.log({ - action: trigger === 'cron' ? 'backup.scheduled' : 'backup.scheduled_run', - actorIp: 'system', - target: filename, - status: 'ok', - details: { destination: cfg.destination, kdf: result.summary.kdf }, - }); - return { ok: true, filename }; - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - this.lastRunAt = Date.now(); - this.lastStatus = 'error'; - this.lastError = message; - this.auditService.log({ - action: trigger === 'cron' ? 'backup.scheduled' : 'backup.scheduled_run', - actorIp: 'system', - target: cfg.destination, - status: 'error', - details: { message }, - }); - return { ok: false, message }; - } finally { - this.running = false; - } - } -} diff --git a/src/server/security/backup.ts b/src/server/security/backup.ts index 1967ff3..f6daf45 100644 --- a/src/server/security/backup.ts +++ b/src/server/security/backup.ts @@ -21,13 +21,6 @@ export const BackupEnvelopeSchema = z.object({ alg: z.literal('aes-256-gcm'), kdf: z.enum(['raw-master-key', 'scrypt']), salt: z.string().optional(), - kdfParams: z - .object({ - N: z.number().int().min(16384).max(65536), - r: z.number().int().min(4).max(16), - p: z.number().int().min(1).max(4), - }) - .optional(), iv: z.string().min(1), tag: z.string().min(1), ciphertext: z.string().min(1), @@ -83,62 +76,9 @@ export interface BackupVerificationSummary { overlayCount: number; } -export class BackupBusyError extends Error { - readonly code = 'BACKUP_KDF_BUSY'; - constructor(message = 'Backup encryption worker queue is busy; try again shortly') { - super(message); - this.name = 'BackupBusyError'; - } -} - const SLUG_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/; -const DEFAULT_MAX_GUNZIP_BYTES = 32 * 1024 * 1024; +const MAX_GUNZIP_BYTES = 32 * 1024 * 1024; const SCRYPT_PARAMS = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 } as const; -const BACKUP_AAD = Buffer.from('gcoord-backup-v1', 'utf8'); -const MIN_BACKUP_PASSPHRASE_LEN = 12; -const MAX_SCRYPT_QUEUE = 8; - -let scryptActive = 0; -const scryptWaiters: Array<() => void> = []; - -async function runScryptAsync( - password: string, - salt: Buffer, - params: { N: number; r: number; p: number; maxmem: number }, - concurrency = 1, -): Promise { - const limit = Math.max(1, concurrency); - if (scryptActive >= limit) { - if (scryptWaiters.length >= MAX_SCRYPT_QUEUE) { - throw new BackupBusyError(); - } - await new Promise((resolve) => { - scryptWaiters.push(resolve); - }); - } - scryptActive += 1; - try { - return await new Promise((resolve, reject) => { - crypto.scrypt(password, salt, 32, params, (err, derived) => { - if (err) reject(err); - else resolve(derived); - }); - }); - } finally { - scryptActive -= 1; - const next = scryptWaiters.shift(); - if (next) next(); - } -} - -function isRegularNonSymlink(filePath: string): boolean { - try { - const stat = fs.lstatSync(filePath); - return !stat.isSymbolicLink() && stat.isFile(); - } catch { - return false; - } -} function validateAndParseConfigEntry( relPath: string, @@ -207,23 +147,18 @@ function collectConfigFilesFromDisk(configDir: string): Record { for (const name of ['settings.json', 'alerts.json', 'snippets.json']) { const abs = path.join(configDir, name); - if (isRegularNonSymlink(abs)) { + if (fs.existsSync(abs)) { out[name] = fs.readFileSync(abs, 'utf8'); } } for (const folder of ['servers', 'systems', 'workflows']) { const dir = path.join(configDir, folder); - try { - const dirStat = fs.lstatSync(dir); - if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) continue; - } catch { - continue; - } + if (!fs.existsSync(dir)) continue; for (const entry of fs.readdirSync(dir).sort()) { if (!entry.endsWith('.json') || entry.includes('.tmp')) continue; const rel = `${folder}/${entry}`; const abs = path.join(dir, entry); - if (isRegularNonSymlink(abs)) { + if (fs.statSync(abs).isFile()) { out[rel] = fs.readFileSync(abs, 'utf8'); } } @@ -231,17 +166,6 @@ function collectConfigFilesFromDisk(configDir: string): Record { return out; } -function validateEncryptPassphrase(passphrase?: string): string | undefined { - const pass = passphrase?.trim(); - if (!pass || pass.length === 0) return undefined; - if (pass.length < MIN_BACKUP_PASSPHRASE_LEN) { - throw new Error( - `Backup passphrase must be at least ${MIN_BACKUP_PASSPHRASE_LEN} characters`, - ); - } - return pass; -} - function deriveEnvelopeKeyForEncrypt(opts: { masterKey?: string; passphrase?: string; @@ -249,18 +173,12 @@ function deriveEnvelopeKeyForEncrypt(opts: { key: Buffer; kdf: 'raw-master-key' | 'scrypt'; saltB64?: string; - kdfParams?: { N: number; r: number; p: number }; } { - const pass = validateEncryptPassphrase(opts.passphrase); - if (pass) { + const pass = opts.passphrase?.trim(); + if (pass && pass.length > 0) { const salt = crypto.randomBytes(16); const key = crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS); - return { - key, - kdf: 'scrypt', - saltB64: salt.toString('base64'), - kdfParams: { N: SCRYPT_PARAMS.N, r: SCRYPT_PARAMS.r, p: SCRYPT_PARAMS.p }, - }; + return { key, kdf: 'scrypt', saltB64: salt.toString('base64') }; } if (!opts.masterKey || !opts.masterKey.trim()) { throw new Error('Either Vault master key or backup passphrase is required'); @@ -268,92 +186,40 @@ function deriveEnvelopeKeyForEncrypt(opts: { return { key: parseMasterKey(opts.masterKey), kdf: 'raw-master-key' }; } -async function deriveEnvelopeKeyForEncryptAsync(opts: { - masterKey?: string; - passphrase?: string; - scryptConcurrency?: number; -}): Promise<{ - key: Buffer; - kdf: 'raw-master-key' | 'scrypt'; - saltB64?: string; - kdfParams?: { N: number; r: number; p: number }; -}> { - const pass = validateEncryptPassphrase(opts.passphrase); - if (pass) { - const salt = crypto.randomBytes(16); - const key = await runScryptAsync(pass, salt, SCRYPT_PARAMS, opts.scryptConcurrency); - return { - key, - kdf: 'scrypt', - saltB64: salt.toString('base64'), - kdfParams: { N: SCRYPT_PARAMS.N, r: SCRYPT_PARAMS.r, p: SCRYPT_PARAMS.p }, - }; - } - if (!opts.masterKey || !opts.masterKey.trim()) { - throw new Error('Either Vault master key or backup passphrase is required'); - } - return { key: parseMasterKey(opts.masterKey), kdf: 'raw-master-key' }; -} - -function getDecryptScryptInputs( - envelope: BackupEnvelope, - opts: { masterKey?: string; passphrase?: string }, -): { pass: string; salt: Buffer; params: { N: number; r: number; p: number; maxmem: number } } { - const pass = opts.passphrase?.trim(); - if (!pass) { - throw new Error('This backup is encrypted with a passphrase; provide backup passphrase'); - } - if (!envelope.salt) { - throw new Error('Backup envelope is missing scrypt salt'); - } - const salt = Buffer.from(envelope.salt, 'base64'); - if (salt.length < 8) { - throw new Error('Backup envelope contains an invalid scrypt salt'); - } - const p = envelope.kdfParams; - const params = p - ? { N: p.N, r: p.r, p: p.p, maxmem: 128 * 1024 * 1024 } - : SCRYPT_PARAMS; - return { pass, salt, params }; -} - function deriveEnvelopeKeyForDecrypt( envelope: BackupEnvelope, opts: { masterKey?: string; passphrase?: string }, ): Buffer { if (envelope.kdf === 'scrypt') { - const { pass, salt, params } = getDecryptScryptInputs(envelope, opts); - return crypto.scryptSync(pass, salt, 32, params); + const pass = opts.passphrase?.trim(); + if (!pass) { + throw new Error('This backup is encrypted with a passphrase; provide backup passphrase'); + } + if (!envelope.salt) { + throw new Error('Backup envelope is missing scrypt salt'); + } + const salt = Buffer.from(envelope.salt, 'base64'); + if (salt.length < 8) { + throw new Error('Backup envelope contains an invalid scrypt salt'); + } + return crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS); } + if (!opts.masterKey || !opts.masterKey.trim()) { throw new Error('This backup requires the 32-byte Vault master key to decrypt'); } return parseMasterKey(opts.masterKey); } -async function deriveEnvelopeKeyForDecryptAsync( - envelope: BackupEnvelope, - opts: { masterKey?: string; passphrase?: string; scryptConcurrency?: number }, -): Promise { - if (envelope.kdf === 'scrypt') { - const { pass, salt, params } = getDecryptScryptInputs(envelope, opts); - return runScryptAsync(pass, salt, params, opts.scryptConcurrency); - } - if (!opts.masterKey || !opts.masterKey.trim()) { - throw new Error('This backup requires the 32-byte Vault master key to decrypt'); - } - return parseMasterKey(opts.masterKey); -} - -function prepareBackupInner(opts: { +export function createBackupBundle(opts: { dataDir: string; db?: Database.Database; masterKey?: string; + passphrase?: string; }): { - inner: BackupInnerPayload; - vaultVerified: boolean; - vaultCredentialCount?: number; - overlayCount: number; + serialized: string; + envelope: BackupEnvelope; + summary: BackupVerificationSummary; } { const dataDir = path.resolve(opts.dataDir); const configDir = path.join(dataDir, 'config'); @@ -366,7 +232,7 @@ function prepareBackupInner(opts: { overlayCount += validateAndParseConfigEntry(relPath, rawJson).overlayCount; } - const vaultEnvelopeRaw = isRegularNonSymlink(vaultPath) + const vaultEnvelopeRaw = fs.existsSync(vaultPath) ? fs.readFileSync(vaultPath, 'utf8') : null; let vaultVerified = false; @@ -383,7 +249,7 @@ function prepareBackupInner(opts: { let localDb: Database.Database | null = null; const db = opts.db ?? - (isRegularNonSymlink(dbPath) ? (localDb = openDatabase(dbPath)) : null); + (fs.existsSync(dbPath) ? (localDb = openDatabase(dbPath)) : null); let knownHosts: Array> = []; let alertSilences: Array> = []; @@ -391,7 +257,7 @@ function prepareBackupInner(opts: { if (db) { knownHosts = db .prepare( - 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC, algorithm ASC', + 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC', ) .all() as Array>; @@ -420,29 +286,17 @@ function prepareBackupInner(opts: { knownHosts, dbMeta: { alertSilences }, }; - return { inner, vaultVerified, vaultCredentialCount, overlayCount }; -} -function finalizeBackupEnvelope( - prepared: ReturnType, - keyInfo: { - key: Buffer; - kdf: 'raw-master-key' | 'scrypt'; - saltB64?: string; - kdfParams?: { N: number; r: number; p: number }; - }, -): { - serialized: string; - envelope: BackupEnvelope; - summary: BackupVerificationSummary; -} { - const { inner, vaultVerified, vaultCredentialCount, overlayCount } = prepared; + const { key, kdf, saltB64 } = deriveEnvelopeKeyForEncrypt({ + masterKey: opts.masterKey, + passphrase: opts.passphrase, + }); + const plaintextJson = Buffer.from(JSON.stringify(inner), 'utf8'); const compressed = zlib.gzipSync(plaintextJson, { level: 9 }); try { const iv = crypto.randomBytes(12); - const cipher = crypto.createCipheriv('aes-256-gcm', keyInfo.key, iv); - cipher.setAAD(BACKUP_AAD); + const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); const ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]); const tag = cipher.getAuthTag(); @@ -450,115 +304,63 @@ function finalizeBackupEnvelope( magic: 'GCOORD_BACKUP_V1', version: 1, alg: 'aes-256-gcm', - kdf: keyInfo.kdf, - ...(keyInfo.saltB64 ? { salt: keyInfo.saltB64 } : {}), - ...(keyInfo.kdfParams ? { kdfParams: keyInfo.kdfParams } : {}), + kdf, + ...(saltB64 ? { salt: saltB64 } : {}), iv: iv.toString('base64'), tag: tag.toString('base64'), ciphertext: ciphertext.toString('base64'), - createdAt: inner.createdAt, + createdAt, }; - const fileList = Object.keys(inner.configFiles).sort(); + const fileList = Object.keys(configFiles).sort(); return { serialized: `${JSON.stringify(envelope, null, 2)}\n`, envelope, summary: { valid: true, - createdAt: inner.createdAt, - kdf: keyInfo.kdf, + createdAt, + kdf, configFileCount: fileList.length, configFiles: fileList, - hasVault: inner.vaultEnvelopeRaw !== null, + hasVault: vaultEnvelopeRaw !== null, vaultVerified, vaultCredentialCount, - knownHostsCount: inner.knownHosts.length, - alertSilenceCount: inner.dbMeta.alertSilences.length, + knownHostsCount: knownHosts.length, + alertSilenceCount: alertSilences.length, overlayCount, }, }; } finally { - keyInfo.key.fill(0); + key.fill(0); plaintextJson.fill(0); compressed.fill(0); } } -export function createBackupBundle(opts: { - dataDir: string; - db?: Database.Database; - masterKey?: string; - passphrase?: string; -}): { - serialized: string; - envelope: BackupEnvelope; - summary: BackupVerificationSummary; -} { - const keyInfo = deriveEnvelopeKeyForEncrypt({ - masterKey: opts.masterKey, - passphrase: opts.passphrase, - }); - try { - const prepared = prepareBackupInner(opts); - return finalizeBackupEnvelope(prepared, keyInfo); - } catch (err) { - keyInfo.key.fill(0); - throw err; - } -} - -export async function createBackupBundleAsync(opts: { - dataDir: string; - db?: Database.Database; - masterKey?: string; - passphrase?: string; - scryptConcurrency?: number; -}): Promise<{ - serialized: string; - envelope: BackupEnvelope; - summary: BackupVerificationSummary; -}> { - const keyInfo = await deriveEnvelopeKeyForEncryptAsync(opts); - try { - const prepared = prepareBackupInner(opts); - return finalizeBackupEnvelope(prepared, keyInfo); - } catch (err) { - keyInfo.key.fill(0); - throw err; - } -} - -function decryptVerifiedInner( - envelope: BackupEnvelope, - key: Buffer, +export function verifyBackupBundle( + rawTextOrBuf: string | Buffer, keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string }, - maxGunzipBytes = DEFAULT_MAX_GUNZIP_BYTES, ): { summary: BackupVerificationSummary; inner: BackupInnerPayload } { + const rawStr = typeof rawTextOrBuf === 'string' ? rawTextOrBuf : rawTextOrBuf.toString('utf8'); + const envelope = BackupEnvelopeSchema.parse(JSON.parse(rawStr)); + const iv = Buffer.from(envelope.iv, 'base64'); const tag = Buffer.from(envelope.tag, 'base64'); const ciphertext = Buffer.from(envelope.ciphertext, 'base64'); + if (iv.length !== 12 || tag.length !== 16) { + throw new Error('Invalid AES-256-GCM parameters inside backup envelope'); + } + + const key = deriveEnvelopeKeyForDecrypt(envelope, keyOpts); let compressed: Buffer | null = null; let plaintext: Buffer | null = null; let inner: BackupInnerPayload; try { - const decryptOnce = (useAad: boolean): Buffer => { - const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); - if (useAad) decipher.setAAD(BACKUP_AAD); - decipher.setAuthTag(tag); - return Buffer.concat([decipher.update(ciphertext), decipher.final()]); - }; - - try { - compressed = decryptOnce(true); - } catch (aadErr) { - if (envelope.kdfParams) { - throw aadErr; - } - compressed = decryptOnce(false); - } - - plaintext = zlib.gunzipSync(compressed, { maxOutputLength: maxGunzipBytes }); + const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); + decipher.setAuthTag(tag); + compressed = Buffer.concat([decipher.update(ciphertext), decipher.final()]); + plaintext = zlib.gunzipSync(compressed, { maxOutputLength: MAX_GUNZIP_BYTES }); inner = BackupInnerPayloadSchema.parse(JSON.parse(plaintext.toString('utf8'))); } finally { key.fill(0); @@ -602,75 +404,16 @@ function decryptVerifiedInner( }; } -function parseBackupEnvelopeForVerify(rawTextOrBuf: string | Buffer): BackupEnvelope { - const rawStr = typeof rawTextOrBuf === 'string' ? rawTextOrBuf : rawTextOrBuf.toString('utf8'); - const envelope = BackupEnvelopeSchema.parse(JSON.parse(rawStr)); - const iv = Buffer.from(envelope.iv, 'base64'); - const tag = Buffer.from(envelope.tag, 'base64'); - if (iv.length !== 12 || tag.length !== 16) { - throw new Error('Invalid AES-256-GCM parameters inside backup envelope'); - } - return envelope; -} - -export function verifyBackupBundle( - rawTextOrBuf: string | Buffer, - keyOpts: { - masterKey?: string; - passphrase?: string; - vaultMasterKey?: string; - maxGunzipBytes?: number; - }, -): { summary: BackupVerificationSummary; inner: BackupInnerPayload } { - const envelope = parseBackupEnvelopeForVerify(rawTextOrBuf); - const key = deriveEnvelopeKeyForDecrypt(envelope, keyOpts); - return decryptVerifiedInner(envelope, key, keyOpts, keyOpts.maxGunzipBytes); -} - -export async function verifyBackupBundleAsync( - rawTextOrBuf: string | Buffer, - keyOpts: { - masterKey?: string; - passphrase?: string; - vaultMasterKey?: string; - scryptConcurrency?: number; - maxGunzipBytes?: number; - }, -): Promise<{ summary: BackupVerificationSummary; inner: BackupInnerPayload }> { - const envelope = parseBackupEnvelopeForVerify(rawTextOrBuf); - const key = await deriveEnvelopeKeyForDecryptAsync(envelope, keyOpts); - return decryptVerifiedInner(envelope, key, keyOpts, keyOpts.maxGunzipBytes); -} - export function verifyBackupSummaryOnly( rawTextOrBuf: string | Buffer, - keyOpts: { - masterKey?: string; - passphrase?: string; - vaultMasterKey?: string; - maxGunzipBytes?: number; - }, + keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string }, ): BackupVerificationSummary { return verifyBackupBundle(rawTextOrBuf, keyOpts).summary; } -export async function verifyBackupSummaryOnlyAsync( - rawTextOrBuf: string | Buffer, - keyOpts: { - masterKey?: string; - passphrase?: string; - vaultMasterKey?: string; - scryptConcurrency?: number; - maxGunzipBytes?: number; - }, -): Promise { - const res = await verifyBackupBundleAsync(rawTextOrBuf, keyOpts); - return res.summary; -} - function writeAtomicPrivateFile(targetPath: string, content: string): void { fs.mkdirSync(path.dirname(targetPath), { recursive: true }); - const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; + const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, content, 'utf8'); @@ -693,7 +436,7 @@ function writeAtomicPrivateFile(targetPath: string, content: string): void { function swapConfigDirectoryAtomic(configDir: string, configFiles: Record): void { const parent = path.dirname(configDir); - const rand = crypto.randomBytes(6).toString('hex'); + const rand = crypto.randomBytes(5).toString('hex'); const stageDir = path.join(parent, `config.restore-${rand}`); const bakDir = path.join(parent, `config.bak-${rand}`); @@ -731,10 +474,22 @@ function swapConfigDirectoryAtomic(configDir: string, configFiles: Record { - const verified = await verifyBackupBundleAsync(rawTextOrBuf, { - masterKey: opts.masterKey, - passphrase: opts.passphrase, - vaultMasterKey: opts.vaultMasterKey, - scryptConcurrency: opts.scryptConcurrency, - maxGunzipBytes: opts.maxGunzipBytes, - }); - return applyVerifiedRestoreToDisk(verified, opts); -} diff --git a/src/server/security/egress-guard.ts b/src/server/security/egress-guard.ts deleted file mode 100644 index adfec66..0000000 --- a/src/server/security/egress-guard.ts +++ /dev/null @@ -1,258 +0,0 @@ -import dns from 'node:dns'; -import net from 'node:net'; - -export class EgressBlockedError extends Error { - readonly code = 'EGRESS_BLOCKED'; - - constructor(message: string) { - super(message); - this.name = 'EgressBlockedError'; - } -} - -interface ParsedCidr { - family: 4 | 6; - network: bigint; - mask: bigint; -} - -const DEFAULT_BLOCKED_CIDR_STRINGS = [ - '0.0.0.0/8', - '10.0.0.0/8', - '100.64.0.0/10', - '127.0.0.0/8', - '169.254.0.0/16', - '172.16.0.0/12', - '192.0.0.0/24', - '192.168.0.0/16', - '198.18.0.0/15', - '224.0.0.0/4', - '240.0.0.0/4', - '::/128', - '::1/128', - 'fc00::/7', - 'fe80::/10', - 'ff00::/8', - 'fd00:ec2::254/128', -]; - -function stripZoneAndBrackets(raw: string): { ip: string; hasZone: boolean } { - let s = raw.trim(); - if (s.startsWith('[') && s.endsWith(']')) { - s = s.slice(1, -1); - } - const pct = s.indexOf('%'); - if (pct >= 0) { - return { ip: s.slice(0, pct), hasZone: true }; - } - return { ip: s, hasZone: false }; -} - -function parseIpv4ToBigInt(ip: string): bigint | null { - const parts = ip.split('.'); - if (parts.length !== 4) return null; - let val = 0n; - for (const part of parts) { - if (!/^\d{1,3}$/.test(part)) return null; - const n = Number(part); - if (n < 0 || n > 255) return null; - val = (val << 8n) | BigInt(n); - } - return val; -} - -function parseIpv6ToBigInt(ip: string): bigint | null { - let s = ip.toLowerCase(); - const lastColon = s.lastIndexOf(':'); - if (lastColon >= 0 && s.includes('.')) { - const v4Part = s.slice(lastColon + 1); - const v4 = parseIpv4ToBigInt(v4Part); - if (v4 === null) return null; - const hi = Number((v4 >> 16n) & 0xffffn).toString(16); - const lo = Number(v4 & 0xffffn).toString(16); - s = `${s.slice(0, lastColon)}:${hi}:${lo}`; - } - - const dblIdx = s.indexOf('::'); - let groups: string[]; - if (dblIdx >= 0) { - if (s.indexOf('::', dblIdx + 2) >= 0) return null; - const left = dblIdx === 0 ? [] : s.slice(0, dblIdx).split(':'); - const right = dblIdx + 2 >= s.length ? [] : s.slice(dblIdx + 2).split(':'); - const missing = 8 - (left.length + right.length); - if (missing < 1) return null; - groups = [...left, ...Array(missing).fill('0'), ...right]; - } else { - groups = s.split(':'); - if (groups.length !== 8) return null; - } - - let out = 0n; - for (const g of groups) { - if (!/^[0-9a-f]{1,4}$/.test(g)) return null; - out = (out << 16n) | BigInt(parseInt(g, 16)); - } - return out; -} - -function parseIpNormalized(rawIp: string): { family: 4 | 6; value: bigint; hasZone: boolean } | null { - const { ip, hasZone } = stripZoneAndBrackets(rawIp); - const kind = net.isIP(ip); - if (kind === 4) { - const value = parseIpv4ToBigInt(ip); - return value === null ? null : { family: 4, value, hasZone }; - } - if (kind === 6) { - const v6 = parseIpv6ToBigInt(ip); - if (v6 === null) return null; - // Unwrap IPv4-mapped IPv6 addresses (::ffff:0:0/96) - if ((v6 >> 32n) === 0xffffn) { - return { family: 4, value: v6 & 0xffffffffn, hasZone }; - } - return { family: 6, value: v6, hasZone }; - } - return null; -} - -export function parseCidr(raw: string): ParsedCidr | null { - const trimmed = raw.trim(); - if (!trimmed) return null; - const slash = trimmed.indexOf('/'); - const ipStr = slash >= 0 ? trimmed.slice(0, slash) : trimmed; - const parsed = parseIpNormalized(ipStr); - if (!parsed) return null; - - const totalBits = parsed.family === 4 ? 32 : 128; - const prefixLen = - slash >= 0 ? Number(trimmed.slice(slash + 1)) : totalBits; - if (!Number.isInteger(prefixLen) || prefixLen < 0 || prefixLen > totalBits) { - return null; - } - - const shift = BigInt(totalBits - prefixLen); - const fullMask = parsed.family === 4 ? 0xffffffffn : (1n << 128n) - 1n; - const mask = prefixLen === 0 ? 0n : (fullMask << shift) & fullMask; - return { - family: parsed.family, - network: parsed.value & mask, - mask, - }; -} - -const DEFAULT_BLOCKED_CIDRS: ParsedCidr[] = DEFAULT_BLOCKED_CIDR_STRINGS - .map((c) => parseCidr(c)!) - .filter(Boolean); - -export function isIpInCidrs(rawIp: string, cidrs: string[]): boolean { - const parsed = parseIpNormalized(rawIp); - if (!parsed) return false; - for (const rawCidr of cidrs) { - const cidr = parseCidr(rawCidr); - if (!cidr || cidr.family !== parsed.family) continue; - if ((parsed.value & cidr.mask) === cidr.network) { - return true; - } - } - return false; -} - -export function isBlockedByDefaultIp(rawIp: string): boolean { - const parsed = parseIpNormalized(rawIp); - if (!parsed || parsed.hasZone) return true; - for (const cidr of DEFAULT_BLOCKED_CIDRS) { - if (cidr.family === parsed.family && (parsed.value & cidr.mask) === cidr.network) { - return true; - } - } - return false; -} - -/** - * Validate `rawHost` against Zero-Trust egress CIDR rules and return all - * permitted resolved IP addresses in lookup order. - */ -export async function resolveAllowedEgressIps( - rawHost: string, - allowedCidrs: string[] = [], -): Promise { - const { ip: cleanHost } = stripZoneAndBrackets(rawHost); - if (!cleanHost) { - throw new EgressBlockedError('Empty egress destination host'); - } - - if (net.isIP(cleanHost) !== 0) { - if (isBlockedByDefaultIp(rawHost) && !isIpInCidrs(rawHost, allowedCidrs)) { - throw new EgressBlockedError( - `Egress to non-public IP "${cleanHost}" is blocked by Zero-Trust egress policy`, - ); - } - return [cleanHost]; - } - - let records: dns.LookupAddress[]; - try { - records = await dns.promises.lookup(cleanHost, { all: true, verbatim: true }); - } catch (err) { - throw new EgressBlockedError( - `Failed to resolve egress host "${cleanHost}": ${err instanceof Error ? err.message : String(err)}`, - ); - } - - if (records.length === 0) { - throw new EgressBlockedError(`Egress host "${cleanHost}" resolved to no addresses`); - } - - const ips: string[] = []; - for (const rec of records) { - if (isBlockedByDefaultIp(rec.address) && !isIpInCidrs(rec.address, allowedCidrs)) { - throw new EgressBlockedError( - `Egress host "${cleanHost}" resolved to blocked address ${rec.address}`, - ); - } - ips.push(rec.address); - } - return ips; -} - -export async function assertEgressHostAllowed( - rawHost: string, - allowedCidrs: string[] = [], -): Promise { - await resolveAllowedEgressIps(rawHost, allowedCidrs); -} - -export async function assertEgressUrlAllowed( - rawUrl: string, - allowedCidrs: string[] = [], -): Promise { - let url: URL; - try { - url = new URL(rawUrl); - } catch { - throw new EgressBlockedError(`Invalid URL "${rawUrl}"`); - } - if (url.protocol !== 'http:' && url.protocol !== 'https:') { - throw new EgressBlockedError(`Unsupported egress URL scheme "${url.protocol}"`); - } - await assertEgressHostAllowed(url.hostname, allowedCidrs); - return url; -} - -export async function fetchWithEgressGuard( - rawUrl: string, - init: RequestInit = {}, - opts: { allowedCidrs?: string[]; timeoutMs?: number } = {}, -): Promise { - const url = await assertEgressUrlAllowed(rawUrl, opts.allowedCidrs ?? []); - const timeoutMs = Math.max(500, Math.min(300_000, opts.timeoutMs ?? 15_000)); - const timeoutSignal = AbortSignal.timeout(timeoutMs); - const signal = init.signal - ? AbortSignal.any([init.signal, timeoutSignal]) - : timeoutSignal; - - return fetch(url.toString(), { - ...init, - redirect: 'error', - signal, - }); -} diff --git a/src/server/security/guards.ts b/src/server/security/guards.ts index cf445b5..470383d 100644 --- a/src/server/security/guards.ts +++ b/src/server/security/guards.ts @@ -1,16 +1,12 @@ import crypto from 'node:crypto'; -import net from 'node:net'; -import type Database from 'better-sqlite3'; -import type { NextFunction, Request, RequestHandler, Response } from 'express'; +import type { NextFunction, Request, Response } from 'express'; import type { StepUpPolicy } from '../../shared/schemas/settings.schema.js'; -import type { AuditService } from './audit.js'; import { SESSION_COOKIE_NAME, sha256Hex, type AuthService, type AuthSession, } from './auth.js'; -import { isIpInCidrs } from './egress-guard.js'; declare global { namespace Express { @@ -21,207 +17,54 @@ declare global { } } -export const DEFAULT_TRUSTED_PROXY_CIDRS = [ - '127.0.0.0/8', - '::1/128', - '10.0.0.0/8', - '172.16.0.0/12', - '192.168.0.0/16', - 'fc00::/7', -]; - interface RateBucketState { failures: number; lockedUntil: number; - updatedAt: number; } -const DECAY_WINDOW_MS = 60 * 60 * 1000; -const MAX_INMEM_BUCKETS = 2000; -const GLOBAL_LOGIN_THRESHOLD = 20; - export class RateLimiter { private readonly buckets = new Map(); - private readonly inFlightCounts = new Map(); - private readonly db?: Database.Database; - private lastPruneAt = 0; - - constructor(options: { db?: Database.Database } = {}) { - this.db = options.db; - } check(scope: string, ip: string): { allowed: boolean; retryAfterSec: number } { const key = `${scope}:${ip}`; - const state = this.readBucket(key); + const state = this.buckets.get(key); + if (!state) return { allowed: true, retryAfterSec: 0 }; + const now = Date.now(); - if (state && state.lockedUntil > now) { + if (state.lockedUntil > now) { return { allowed: false, retryAfterSec: Math.max(1, Math.ceil((state.lockedUntil - now) / 1000)), }; } - - if (scope === 'login') { - const globalState = this.readBucket('login:__global__'); - if (globalState && globalState.lockedUntil > now) { - return { - allowed: false, - retryAfterSec: Math.max(1, Math.ceil((globalState.lockedUntil - now) / 1000)), - }; - } - } - return { allowed: true, retryAfterSec: 0 }; } - acquireInFlight(scope: string, ip: string, maxConcurrent = 2): boolean { + recordFailure(scope: string, ip: string): number { const key = `${scope}:${ip}`; - const cur = this.inFlightCounts.get(key) ?? 0; - if (cur >= maxConcurrent) return false; - this.inFlightCounts.set(key, cur + 1); - return true; - } - - releaseInFlight(scope: string, ip: string): void { - const key = `${scope}:${ip}`; - const cur = this.inFlightCounts.get(key) ?? 0; - if (cur <= 1) { - this.inFlightCounts.delete(key); - } else { - this.inFlightCounts.set(key, cur - 1); - } - } - - recordFailure(scope: string, ip: string): { lockedUntil: number; failures: number; globalTriggered: boolean } { - const now = Date.now(); - const key = `${scope}:${ip}`; - const prev = this.readBucket(key); - const baseFailures = - prev && (now - prev.updatedAt <= DECAY_WINDOW_MS || prev.lockedUntil > now) - ? prev.failures - : 0; - const failures = baseFailures + 1; + const prev = this.buckets.get(key) ?? { failures: 0, lockedUntil: 0 }; + const failures = prev.failures + 1; let lockedUntil = 0; if (failures >= 5) { const delayMs = Math.min(300_000, 2000 * 2 ** (failures - 5)); - lockedUntil = now + delayMs; + lockedUntil = Date.now() + delayMs; } - this.writeBucket(key, { failures, lockedUntil, updatedAt: now }); - - let globalTriggered = false; - if (scope === 'login') { - const gPrev = this.readBucket('login:__global__'); - const gBase = - gPrev && (now - gPrev.updatedAt <= 15 * 60 * 1000 || gPrev.lockedUntil > now) - ? gPrev.failures - : 0; - const gFailures = gBase + 1; - let gLockedUntil = gPrev?.lockedUntil ?? 0; - if (gFailures >= GLOBAL_LOGIN_THRESHOLD) { - const gDelay = Math.min(300_000, 60_000 * 2 ** Math.min(3, Math.floor((gFailures - GLOBAL_LOGIN_THRESHOLD) / 5))); - gLockedUntil = now + gDelay; - globalTriggered = true; - } - this.writeBucket('login:__global__', { - failures: gFailures, - lockedUntil: gLockedUntil, - updatedAt: now, - }); - } - - return { lockedUntil, failures, globalTriggered }; + this.buckets.set(key, { failures, lockedUntil }); + return lockedUntil; } recordSuccess(scope: string, ip: string): void { - this.deleteBucket(`${scope}:${ip}`); - if (scope === 'login') { - this.deleteBucket('login:__global__'); - } - } - - private readBucket(key: string): RateBucketState | undefined { - if (this.db) { - try { - const row = this.db - .prepare( - 'SELECT failures, locked_until AS lockedUntil, updated_at AS updatedAt FROM rate_limits WHERE scope_key = ?', - ) - .get(key) as RateBucketState | undefined; - if (!row) return undefined; - const now = Date.now(); - if (row.lockedUntil <= now && now - row.updatedAt > DECAY_WINDOW_MS) { - this.deleteBucket(key); - return undefined; - } - return row; - } catch { - // Fallback to in-memory map if DB unavailable - } - } - - const mem = this.buckets.get(key); - if (!mem) return undefined; - const now = Date.now(); - if (mem.lockedUntil <= now && now - mem.updatedAt > DECAY_WINDOW_MS) { - this.buckets.delete(key); - return undefined; - } - return mem; - } - - private writeBucket(key: string, state: RateBucketState): void { - if (this.db) { - try { - this.db - .prepare( - `INSERT INTO rate_limits (scope_key, failures, locked_until, updated_at) - VALUES (?, ?, ?, ?) - ON CONFLICT(scope_key) DO UPDATE SET - failures = excluded.failures, - locked_until = excluded.locked_until, - updated_at = excluded.updated_at`, - ) - .run(key, state.failures, state.lockedUntil, state.updatedAt); - - if (state.updatedAt - this.lastPruneAt > 10 * 60 * 1000) { - this.lastPruneAt = state.updatedAt; - this.db - .prepare('DELETE FROM rate_limits WHERE locked_until <= ? AND updated_at < ?') - .run(state.updatedAt, state.updatedAt - DECAY_WINDOW_MS); - } - return; - } catch { - // Fallback below - } - } - - if (this.buckets.size >= MAX_INMEM_BUCKETS && !this.buckets.has(key)) { - const oldestKey = this.buckets.keys().next().value; - if (oldestKey) this.buckets.delete(oldestKey); - } - this.buckets.set(key, state); - } - - private deleteBucket(key: string): void { - if (this.db) { - try { - this.db.prepare('DELETE FROM rate_limits WHERE scope_key = ?').run(key); - } catch { - // Ignore DB error - } - } - this.buckets.delete(key); + this.buckets.delete(`${scope}:${ip}`); } } export function extractCookies(cookieHeader: string | undefined): Record { - const result = Object.create(null) as Record; + const result: Record = {}; if (!cookieHeader) return result; for (const part of cookieHeader.split(';')) { const eq = part.indexOf('='); if (eq <= 0) continue; const key = part.slice(0, eq).trim(); - if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue; const rawVal = part.slice(eq + 1).trim(); try { result[key] = decodeURIComponent(rawVal); @@ -232,54 +75,23 @@ export function extractCookies(cookieHeader: string | undefined): Record 0) { - const candidate = cf.split(',')[0]!.trim(); - if (net.isIP(candidate) !== 0) { - return candidate; - } + return cf.split(',')[0]!.trim(); } } - return req.ip || peerIp || 'unknown'; + return req.ip || req.socket.remoteAddress || 'unknown'; } -export function attachClientIp( - trustCloudflare: boolean, - trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS, -) { +export function attachClientIp(trustCloudflare: boolean) { return (req: Request, _res: Response, next: NextFunction): void => { - req.clientIp = resolveClientIp(req, trustCloudflare, trustedProxyCidrs); + req.clientIp = resolveClientIp(req, trustCloudflare); next(); }; } -export function asyncHandler( - fn: (req: Request, res: Response, next: NextFunction) => Promise | void, -): RequestHandler { - return (req, res, next) => { - Promise.resolve(fn(req, res, next)).catch(next); - }; -} - -function getAudit(req: Request): AuditService | undefined { - return req.app?.locals?.auditService as AuditService | undefined; -} - export function requireAuth(authService: AuthService) { return (req: Request, res: Response, next: NextFunction): void => { const cookies = extractCookies(req.headers.cookie); @@ -306,13 +118,6 @@ export function requireCsrf(req: Request, res: Response, next: NextFunction): vo } const headerToken = req.headers['x-csrf-token']; if (typeof headerToken !== 'string' || headerToken.length < 16) { - getAudit(req)?.log({ - action: 'security.csrf_denied', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: session.idHash, - target: `${req.method} ${req.path}`, - status: 'denied', - }); res.status(403).json({ error: 'CSRF_INVALID' }); return; } @@ -322,13 +127,6 @@ export function requireCsrf(req: Request, res: Response, next: NextFunction): vo providedHash.length !== expectedHash.length || !crypto.timingSafeEqual(providedHash, expectedHash) ) { - getAudit(req)?.log({ - action: 'security.csrf_denied', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: session.idHash, - target: `${req.method} ${req.path}`, - status: 'denied', - }); res.status(403).json({ error: 'CSRF_INVALID' }); return; } @@ -342,13 +140,6 @@ export function enforceSafeMode(req: Request, res: Response, next: NextFunction) } const clientSafeHeader = req.headers['x-gcoord-safe-mode'] === '1'; if (req.authSession?.safeMode || clientSafeHeader) { - getAudit(req)?.log({ - action: 'security.safe_mode_denied', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession?.idHash ?? null, - target: `${req.method} ${req.path}`, - status: 'denied', - }); res.status(423).json({ error: 'SAFE_MODE_ACTIVE', message: 'Disable Safe / Read-Only Mode before performing mutating actions.', @@ -376,13 +167,6 @@ export function createStepUpGuard( } if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) { - getAudit(req)?.log({ - action: 'security.stepup_denied', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: session.idHash, - target: `${req.method} ${req.path}`, - status: 'denied', - }); res.status(403).json({ error: 'STEP_UP_REQUIRED', message: 'Re-authentication verification is required for this sensitive operation.', @@ -405,13 +189,6 @@ export function requireStepUp(req: Request, res: Response, next: NextFunction): return; } if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) { - getAudit(req)?.log({ - action: 'security.stepup_denied', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: session.idHash, - target: `${req.method} ${req.path}`, - status: 'denied', - }); res.status(403).json({ error: 'STEP_UP_REQUIRED', message: 'Re-authentication verification is required for this sensitive operation.', diff --git a/src/server/security/recovery-store.ts b/src/server/security/recovery-store.ts index e0c5312..d77c752 100644 --- a/src/server/security/recovery-store.ts +++ b/src/server/security/recovery-store.ts @@ -1,4 +1,3 @@ -import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import type { VaultCredential } from '../../shared/schemas/vault.schema.js'; @@ -7,6 +6,7 @@ import type { VaultService } from './vault.js'; export interface SavedPasswordEntry { id: string; label: string; + plaintextPassword?: string; createdAt: string; } @@ -48,6 +48,7 @@ export interface SyncRecoveryOptions { username?: string | null; totps?: SavedTotpEntry[]; passwordMetaList?: Array<{ id: string; label: string; createdAt: number }>; + passwordPlaintextUpdate?: { id: string; label: string; password: string; createdAt?: number }; removedPasswordId?: string; newRecoveryCodes?: string[]; snapshotReason?: string; @@ -73,8 +74,6 @@ export class EmergencyRecoveryService { readBundle(): EmergencySecretsBundle | null { if (!fs.existsSync(this.bundlePath)) return null; try { - const stat = fs.lstatSync(this.bundlePath); - if (!stat.isFile() || stat.isSymbolicLink()) return null; const raw = JSON.parse(fs.readFileSync(this.bundlePath, 'utf8')); if (!raw || typeof raw !== 'object' || raw.version !== 1) return null; return raw as EmergencySecretsBundle; @@ -106,30 +105,43 @@ export class EmergencyRecoveryService { ? opts.vault.exportAllCredentials() : existing?.vaultCredentials ?? {}; + // Merge saved plaintext passwords safely across updates const prevPwById = new Map(); for (const p of existing?.admin.passwords ?? []) { - prevPwById.set(p.id, { - id: p.id, - label: p.label, - createdAt: p.createdAt, - }); + prevPwById.set(p.id, p); } if (opts.removedPasswordId) { prevPwById.delete(opts.removedPasswordId); } + if (opts.passwordPlaintextUpdate) { + const u = opts.passwordPlaintextUpdate; + prevPwById.set(u.id, { + id: u.id, + label: u.label, + plaintextPassword: u.password, + createdAt: new Date(u.createdAt ?? Date.now()).toISOString(), + }); + } - const finalPasswords: SavedPasswordEntry[] = opts.passwordMetaList - ? opts.passwordMetaList.map((meta) => ({ + let finalPasswords: SavedPasswordEntry[]; + if (opts.passwordMetaList) { + finalPasswords = opts.passwordMetaList.map((meta) => { + const prev = prevPwById.get(meta.id); + return { id: meta.id, label: meta.label, + plaintextPassword: prev?.plaintextPassword, createdAt: new Date(meta.createdAt).toISOString(), - })) - : [...prevPwById.values()]; + }; + }); + } else { + finalPasswords = [...prevPwById.values()]; + } const bundle: EmergencySecretsBundle = { version: 1, updatedAt: nowIso, - note: 'Local emergency recovery bundle managed by GCoordinator (passwords excluded). Keep this file private (chmod 0600).', + note: 'Local emergency plaintext backup managed by GCoordinator. Keep this file private (chmod 0600).', vaultMasterKeyHex: masterKeyHex, admin: { username: opts.username !== undefined ? opts.username : existing?.admin.username ?? null, @@ -173,22 +185,10 @@ export class EmergencyRecoveryService { wipeAll(): void { const shred = (filePath: string) => { - let stat: fs.Stats; + if (!fs.existsSync(filePath)) return; try { - stat = fs.lstatSync(filePath); - } catch { - return; - } - if (stat.isSymbolicLink()) { - fs.unlinkSync(filePath); - return; - } - if (stat.isDirectory()) { - fs.rmSync(filePath, { recursive: true, force: true }); - return; - } - if (stat.isFile() && stat.size > 0) { - try { + const stat = fs.statSync(filePath); + if (stat.isFile() && stat.size > 0) { const fd = fs.openSync(filePath, 'r+'); try { fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0); @@ -196,9 +196,9 @@ export class EmergencyRecoveryService { } finally { fs.closeSync(fd); } - } catch { - // Best-effort overwrite before unlink } + } catch { + // Best-effort overwrite before unlink } fs.unlinkSync(filePath); }; @@ -208,11 +208,7 @@ export class EmergencyRecoveryService { for (const f of fs.readdirSync(this.snapshotsDir)) { shred(path.join(this.snapshotsDir, f)); } - try { - fs.rmdirSync(this.snapshotsDir); - } catch { - // Ignore unexpected remaining files - } + fs.rmdirSync(this.snapshotsDir); } if (fs.existsSync(this.recoveryDir)) { try { @@ -231,7 +227,7 @@ export class EmergencyRecoveryService { } private writeAtomicSecure(targetPath: string, content: string): void { - const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; + const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, content, 'utf8'); @@ -251,19 +247,8 @@ export class EmergencyRecoveryService { .sort(); while (files.length > MAX_SNAPSHOTS) { const oldest = files.shift()!; - const p = path.join(this.snapshotsDir, oldest); try { - const stat = fs.lstatSync(p); - if (stat.isFile() && !stat.isSymbolicLink() && stat.size > 0) { - const fd = fs.openSync(p, 'r+'); - try { - fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0); - fs.fsyncSync(fd); - } finally { - fs.closeSync(fd); - } - } - fs.unlinkSync(p); + fs.unlinkSync(path.join(this.snapshotsDir, oldest)); } catch { // Ignore cleanup failure } diff --git a/src/server/security/vault.ts b/src/server/security/vault.ts index 5bbc402..26811a3 100644 --- a/src/server/security/vault.ts +++ b/src/server/security/vault.ts @@ -10,14 +10,11 @@ import { type VaultCredentialMeta, type VaultPayload, } from '../../shared/schemas/vault.schema.js'; -import type { VaultSealState, VaultState } from '../../shared/ws-protocol.js'; - -const VAULT_AAD = Buffer.from('gcoord-vault-v1', 'utf8'); +import type { VaultState } from '../../shared/ws-protocol.js'; export const VaultEnvelopeSchema = z.object({ version: z.literal(1), alg: z.literal('aes-256-gcm'), - aad: z.boolean().optional(), iv: z.string().min(1), tag: z.string().min(1), ciphertext: z.string().min(1), @@ -45,7 +42,6 @@ export function generateMasterKeyBuffer(): Buffer { function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); - cipher.setAAD(VAULT_AAD); const plaintext = Buffer.from(JSON.stringify(payload), 'utf8'); const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]); const tag = cipher.getAuthTag(); @@ -54,7 +50,6 @@ function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope { return { version: 1, alg: 'aes-256-gcm', - aad: true, iv: iv.toString('base64'), tag: tag.toString('base64'), ciphertext: ciphertext.toString('base64'), @@ -72,9 +67,6 @@ function decryptEnvelope(envelope: VaultEnvelope, key: Buffer): VaultPayload { } const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); - if (envelope.aad) { - decipher.setAAD(VAULT_AAD); - } decipher.setAuthTag(tag); const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]); try { @@ -117,11 +109,7 @@ export function verifyVaultEnvelopeText( } export function computeOpenSshFingerprint(publicKeyLine: string): string { - const trimmed = publicKeyLine.trim(); - if (/[\r\n\0]/.test(trimmed)) { - throw new Error('Public key must be a single line'); - } - const parsed = ssh2.utils.parseKey(trimmed); + const parsed = ssh2.utils.parseKey(publicKeyLine.trim()); if (parsed instanceof Error) { throw parsed; } @@ -134,13 +122,6 @@ export function computeOpenSshFingerprint(publicKeyLine: string): string { return `SHA256:${hash}`; } -export function validatePrivateKey(privateKey: string, passphrase?: string): void { - const parsed = ssh2.utils.parseKey(privateKey, passphrase); - if (parsed instanceof Error) { - throw new Error(`Invalid SSH private key or passphrase: ${parsed.message}`); - } -} - /** * Generates an OpenSSH Ed25519 keypair, retrying around ssh2's BitString * leading-zero stripping bug when a generated public key starts with 0x00. @@ -184,29 +165,22 @@ export type VaultCredentialInput = DistributiveOmit< export interface VaultServiceOptions { keyFilePath?: string; - allowLocalKeyFile?: boolean; } -type KeySource = 'secret-file' | 'env' | 'key-file' | 'backup' | 'generated' | 'manual'; - export class VaultService { private masterKey: Buffer | null = null; private credentials = new Map(); private writeUnlocked = false; private autoInitializedEmpty = false; private wasPanicLocked = false; - private keySource: KeySource | null = null; private readonly keyFilePath: string | null; - private readonly allowLocalKeyFile: boolean; private readonly panicListeners = new Set<() => void>(); - private readonly sealListeners = new Set<() => void>(); constructor( private readonly vaultFilePath: string, options: VaultServiceOptions = {}, ) { this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null; - this.allowLocalKeyFile = options.allowLocalKeyFile ?? true; this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath()); } @@ -238,12 +212,6 @@ export class VaultService { return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized'; } - get sealState(): VaultSealState { - if (!fs.existsSync(this.vaultFilePath)) return 'uninitialized'; - if (this.masterKey === null) return 'sealed'; - return this.writeUnlocked ? 'unlocked' : 'write-locked'; - } - get isPanicLocked(): boolean { return this.wasPanicLocked || fs.existsSync(this.panicLockMarkerPath()); } @@ -255,13 +223,6 @@ export class VaultService { }; } - onSeal(listener: () => void): () => void { - this.sealListeners.add(listener); - return () => { - this.sealListeners.delete(listener); - }; - } - initRuntime(options: { secretFilePath?: string; envKey?: string; @@ -273,20 +234,20 @@ export class VaultService { return { runtimeReady: false, reason: 'panic_locked' }; } - const candidates: Array<{ value: string; source: KeySource }> = []; + const candidates: string[] = []; if (options.secretFilePath && fs.existsSync(options.secretFilePath)) { const val = fs.readFileSync(options.secretFilePath, 'utf8').trim(); - if (val) candidates.push({ value: val, source: 'secret-file' }); + if (val) candidates.push(val); } if (options.envKey && options.envKey.trim().length > 0) { - candidates.push({ value: options.envKey.trim(), source: 'env' }); + candidates.push(options.envKey.trim()); } if (this.keyFilePath && fs.existsSync(this.keyFilePath)) { const val = fs.readFileSync(this.keyFilePath, 'utf8').trim(); - if (val) candidates.push({ value: val, source: 'key-file' }); + if (val) candidates.push(val); } if (options.backupKey && options.backupKey.trim().length > 0) { - candidates.push({ value: options.backupKey.trim(), source: 'backup' }); + candidates.push(options.backupKey.trim()); } if (fs.existsSync(this.vaultFilePath)) { @@ -307,19 +268,15 @@ export class VaultService { for (const candidate of candidates) { let keyBuf: Buffer | null = null; try { - keyBuf = parseMasterKey(candidate.value); + keyBuf = parseMasterKey(candidate); const payload = decryptEnvelope(envelope, keyBuf); this.zeroizeMasterKey(); this.masterKey = keyBuf; - this.keySource = candidate.source; this.credentials = new Map(Object.entries(payload.credentials)); this.writeUnlocked = false; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); - // Security invariant: NEVER mirror Docker Secret or env master keys to disk vault.key - if (candidate.source === 'key-file') { - this.persistKeyFileIfConfigured(keyBuf); - } + this.persistKeyFileIfConfigured(keyBuf); return { runtimeReady: true }; } catch { keyBuf?.fill(0); @@ -334,28 +291,17 @@ export class VaultService { let keyBuf: Buffer | null = null; try { - const chosen = candidates[0]; - const source: KeySource = chosen ? chosen.source : 'generated'; - keyBuf = chosen ? parseMasterKey(chosen.value) : generateMasterKeyBuffer(); + keyBuf = candidates[0] ? parseMasterKey(candidates[0]) : generateMasterKeyBuffer(); const emptyPayload: VaultPayload = { version: 1, credentials: {} }; this.writeVerifiedVaultAtomic(emptyPayload, keyBuf); this.zeroizeMasterKey(); this.masterKey = keyBuf; - this.keySource = source; this.credentials.clear(); this.writeUnlocked = false; this.autoInitializedEmpty = true; this.setPanicLockMarker(false); - // Only write local keyfile when generated locally (or already using key-file) and allowed - if ( - this.allowLocalKeyFile && - source !== 'secret-file' && - source !== 'env' && - source !== 'backup' - ) { - this.persistKeyFileIfConfigured(keyBuf); - } + this.persistKeyFileIfConfigured(keyBuf); return { runtimeReady: true, initialized: true }; } catch (err) { keyBuf?.fill(0); @@ -416,14 +362,11 @@ export class VaultService { this.zeroizeMasterKey(); this.masterKey = keyBuf; - this.keySource = 'manual'; this.credentials.clear(); this.writeUnlocked = true; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); - if (this.allowLocalKeyFile && this.keyFilePath && fs.existsSync(this.keyFilePath)) { - this.persistKeyFileIfConfigured(keyBuf); - } + this.persistKeyFileIfConfigured(keyBuf); return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') }; } @@ -441,48 +384,17 @@ export class VaultService { this.zeroizeMasterKey(); this.masterKey = keyBuf; - this.keySource = 'manual'; this.credentials = new Map(Object.entries(payload.credentials)); this.writeUnlocked = true; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); - if (this.allowLocalKeyFile && this.keyFilePath && fs.existsSync(this.keyFilePath)) { - this.persistKeyFileIfConfigured(keyBuf); - } + this.persistKeyFileIfConfigured(keyBuf); } catch (err) { keyBuf.fill(0); throw err; } } - seal(): void { - this.zeroizeMasterKey(); - this.keySource = null; - this.credentials.clear(); - this.writeUnlocked = false; - this.autoInitializedEmpty = false; - - for (const listener of this.sealListeners) { - try { - listener(); - } catch { - // Seal cleanup must continue across all listeners - } - } - } - - dropLocalKeyFile(): void { - if (!this.keyFilePath) return; - try { - const stat = fs.lstatSync(this.keyFilePath); - if (stat.isFile() || stat.isSymbolicLink()) { - fs.unlinkSync(this.keyFilePath); - } - } catch { - // Ignore missing or unreadable key file - } - } - unlockForModifications(): void { if (this.masterKey === null || this.isPanicLocked) { throw new Error('Master key is required to unseal vault'); @@ -560,15 +472,7 @@ export class VaultService { this.zeroizeMasterKey(); this.masterKey = nextKey; this.writeUnlocked = true; - if ( - this.allowLocalKeyFile && - this.keySource !== 'secret-file' && - this.keySource !== 'env' && - this.keyFilePath && - fs.existsSync(this.keyFilePath) - ) { - this.persistKeyFileIfConfigured(nextKey); - } + this.persistKeyFileIfConfigured(nextKey); return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') }; } catch (err) { nextKey.fill(0); @@ -709,8 +613,8 @@ export class VaultService { this.keyFilePath ?? (fs.existsSync(siblingKeyFile) ? siblingKeyFile : null); if (!targetPath) return; - fs.mkdirSync(path.dirname(targetPath), { recursive: true, mode: 0o700 }); - const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; + fs.mkdirSync(path.dirname(targetPath), { recursive: true }); + const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, `${key.toString('hex')}\n`, 'utf8'); @@ -731,11 +635,11 @@ export class VaultService { private writeVerifiedVaultAtomic(payload: VaultPayload, key: Buffer): void { const dir = path.dirname(this.vaultFilePath); - fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + fs.mkdirSync(dir, { recursive: true }); const envelope = encryptPayload(payload, key); const serialized = JSON.stringify(envelope, null, 2); - const tmpPath = `${this.vaultFilePath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; + const tmpPath = `${this.vaultFilePath}.tmp.${process.pid}.${Date.now()}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { diff --git a/src/server/ssh/key-manager.ts b/src/server/ssh/key-manager.ts index 9380355..aad4eca 100644 --- a/src/server/ssh/key-manager.ts +++ b/src/server/ssh/key-manager.ts @@ -7,22 +7,13 @@ import type { SSHPool } from './ssh-pool.js'; const OPENSSH_KEY_TYPES = new Set([ 'ssh-ed25519', - 'ssh-ed25519-cert-v01@openssh.com', 'ssh-rsa', - 'ssh-rsa-cert-v01@openssh.com', - 'rsa-sha2-256', - 'rsa-sha2-512', 'ssh-dss', 'ecdsa-sha2-nistp256', - 'ecdsa-sha2-nistp256-cert-v01@openssh.com', 'ecdsa-sha2-nistp384', - 'ecdsa-sha2-nistp384-cert-v01@openssh.com', 'ecdsa-sha2-nistp521', - 'ecdsa-sha2-nistp521-cert-v01@openssh.com', 'sk-ssh-ed25519@openssh.com', - 'sk-ssh-ed25519-cert-v01@openssh.com', 'sk-ecdsa-sha2-nistp256@openssh.com', - 'sk-ecdsa-sha2-nistp256-cert-v01@openssh.com', ]); export interface AuthorizedKeyEntry { @@ -144,8 +135,6 @@ function makeRotatedCredentialId(serverId: string): string { } export class KeyManager { - private readonly activeRotations = new Set(); - constructor( private readonly sshPool: SSHPool, private readonly vaultService: VaultService, @@ -288,32 +277,6 @@ export class KeyManager { passphrase: string | undefined, actorIp: string, sessionIdHash: string | null, - ): Promise { - if (this.activeRotations.has(serverId)) { - return { - serverId, - ok: false, - error: `Key rotation already in progress for "${serverId}"`, - }; - } - this.activeRotations.add(serverId); - try { - return await this.rotateSingleServerLocked( - serverId, - passphrase, - actorIp, - sessionIdHash, - ); - } finally { - this.activeRotations.delete(serverId); - } - } - - private async rotateSingleServerLocked( - serverId: string, - passphrase: string | undefined, - actorIp: string, - sessionIdHash: string | null, ): Promise { const server = this.configManager.getServer(serverId); if (!server) { @@ -361,7 +324,7 @@ export class KeyManager { newSecret.passphrase, ); - // Step 4: Verified! Persist updated credentialId without tearing down live PTY/tunnel sessions + // Step 4: Verified! Persist updated credentialId in server JSON const updatedServer = { ...server, credentialId: newCredId }; this.configManager.saveConfigText( `servers/${server.id}.json`, @@ -370,6 +333,9 @@ export class KeyManager { `Atomic SSH key rotation -> ${newCredId}`, ); + // Reconnect pool onto the new key + await this.sshPool.reconnect(server.id); + // Cleanly remove old public key from authorized_keys if it differs if (oldFingerprint && oldFingerprint !== newMeta.fingerprint) { const afterInspect = await this.inspectAuthorizedKeys(server.id); diff --git a/src/server/ssh/known-hosts.ts b/src/server/ssh/known-hosts.ts index 6d2e6bf..0fc21ee 100644 --- a/src/server/ssh/known-hosts.ts +++ b/src/server/ssh/known-hosts.ts @@ -12,16 +12,11 @@ export interface KnownHostRecord { updatedAt: number; } -export function normalizeHostForKey(rawHost: string): string { - const clean = rawHost.trim().toLowerCase().replace(/^\[|\]$/g, ''); - return clean.includes(':') ? `[${clean}]` : clean; -} - export function buildHostPortKey(server: Pick): string { - const hostNormalized = normalizeHostForKey(server.host); + const hostLower = server.host.trim().toLowerCase(); return server.jumpHostId - ? `${server.jumpHostId}->${hostNormalized}:${server.port}` - : `${hostNormalized}:${server.port}`; + ? `${server.jumpHostId}->${hostLower}:${server.port}` + : `${hostLower}:${server.port}`; } export function parseHostKeyBuffer(keyBuf: Buffer): { @@ -49,32 +44,13 @@ export function parseHostKeyBuffer(keyBuf: Buffer): { export class KnownHostsService { private readonly pendingTofu = new Map(); private readonly pendingMismatches = new Map(); - private readonly verifiedOpenSshKeys = new Map(); private readonly listeners = new Set<() => void>(); - private readonly mismatchListeners = new Set<(alert: HostKeyAlert) => void>(); constructor( private readonly db: Database.Database, private readonly auditService?: AuditService, ) {} - onHostKeyMismatch(listener: (alert: HostKeyAlert) => void): () => void { - this.mismatchListeners.add(listener); - return () => { - this.mismatchListeners.delete(listener); - }; - } - - private emitMismatch(alert: HostKeyAlert): void { - for (const cb of this.mismatchListeners) { - try { - cb(alert); - } catch { - // Isolate subscriber failures - } - } - } - onChange(listener: () => void): () => void { this.listeners.add(listener); return () => { @@ -87,20 +63,19 @@ export class KnownHostsService { const { algorithm, fingerprint } = parseHostKeyBuffer(keyBuf); const now = Date.now(); - const exactRow = this.db + const row = this.db .prepare( - 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts WHERE host_port = ? AND algorithm = ?', + 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts WHERE host_port = ?', ) - .get(hostPortKey, algorithm) as KnownHostRecord | undefined; + .get(hostPortKey) as KnownHostRecord | undefined; - if (exactRow) { - if (exactRow.fingerprint === fingerprint) { + if (row) { + if (row.fingerprint === fingerprint) { const hadPending = this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id); - this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf); this.db - .prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ? AND algorithm = ?') - .run(now, hostPortKey, algorithm); + .prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ?') + .run(now, hostPortKey); if (hadPending) this.emitChange(); return true; } @@ -111,7 +86,7 @@ export class KnownHostsService { host: server.host, port: server.port, algorithm, - expectedFingerprint: exactRow.fingerprint, + expectedFingerprint: row.fingerprint, actualFingerprint: fingerprint, detectedAt: now, }; @@ -124,12 +99,10 @@ export class KnownHostsService { status: 'denied', details: { hostPortKey, - algorithm, - expected: exactRow.fingerprint, + expected: row.fingerprint, actual: fingerprint, }, }); - this.emitMismatch(alert); this.emitChange(); return false; } @@ -139,7 +112,6 @@ export class KnownHostsService { const expected = server.hostKeyFingerprint.trim(); if (expected === fingerprint) { this.upsertKnownHost(hostPortKey, algorithm, fingerprint, now); - this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf); this.pendingTofu.delete(server.id); this.pendingMismatches.delete(server.id); this.auditService?.log({ @@ -169,9 +141,8 @@ export class KnownHostsService { actorIp: 'hub', target: server.id, status: 'denied', - details: { hostPortKey, algorithm, expected, actual: fingerprint }, + details: { hostPortKey, expected, actual: fingerprint }, }); - this.emitMismatch(alert); this.emitChange(); return false; } @@ -267,7 +238,7 @@ export class KnownHostsService { listKnownHosts(): KnownHostRecord[] { return this.db .prepare( - 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC, algorithm ASC', + 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC', ) .all() as KnownHostRecord[]; } @@ -301,21 +272,15 @@ export class KnownHostsService { this.emitChange(); } - deleteKnownHost(hostPort: string, algorithm?: string): boolean { - const res = algorithm - ? this.db - .prepare('DELETE FROM known_hosts WHERE host_port = ? AND algorithm = ?') - .run(hostPort, algorithm) - : this.db.prepare('DELETE FROM known_hosts WHERE host_port = ?').run(hostPort); + deleteKnownHost(hostPort: string): boolean { + const res = this.db + .prepare('DELETE FROM known_hosts WHERE host_port = ?') + .run(hostPort); for (const [sid, p] of this.pendingTofu.entries()) { - if (p.hostPortKey === hostPort && (!algorithm || p.algorithm === algorithm)) { - this.pendingTofu.delete(sid); - } + if (p.hostPortKey === hostPort) this.pendingTofu.delete(sid); } for (const [sid, m] of this.pendingMismatches.entries()) { - if (m.hostPortKey === hostPort && (!algorithm || m.algorithm === algorithm)) { - this.pendingMismatches.delete(sid); - } + if (m.hostPortKey === hostPort) this.pendingMismatches.delete(sid); } if (res.changes > 0) this.emitChange(); return res.changes > 0; @@ -331,29 +296,14 @@ export class KnownHostsService { .prepare( `INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at) VALUES (?, ?, ?, ?, ?) - ON CONFLICT(host_port, algorithm) DO UPDATE SET + ON CONFLICT(host_port) DO UPDATE SET + algorithm = excluded.algorithm, fingerprint = excluded.fingerprint, updated_at = excluded.updated_at`, ) .run(hostPortKey, algorithm, fingerprint, now, now); } - private recordOpenSshKey( - server: Pick, - hostPortKey: string, - algorithm: string, - keyBuf: Buffer, - ): void { - const cleanHost = normalizeHostForKey(server.host); - const hostToken = server.port === 22 ? cleanHost : `${cleanHost.startsWith('[') ? cleanHost : `[${cleanHost}]`}:${server.port}`; - const line = `${hostToken} ${algorithm} ${keyBuf.toString('base64')}`; - this.verifiedOpenSshKeys.set(server.id, { hostPortKey, line }); - } - - getOpenSshKnownHostLine(server: Pick): string | undefined { - return this.verifiedOpenSshKeys.get(server.id)?.line; - } - private emitChange(): void { for (const listener of this.listeners) { try { diff --git a/src/server/ssh/pty-manager.ts b/src/server/ssh/pty-manager.ts index 6e79f2f..87bf2b9 100644 --- a/src/server/ssh/pty-manager.ts +++ b/src/server/ssh/pty-manager.ts @@ -4,7 +4,6 @@ import type { ClientChannel } from 'ssh2'; import { WS_CHANNELS } from '../../shared/ws-protocol.js'; import type { WsHub } from '../api/ws-hub.js'; import type { ConfigManager } from '../config/config-manager.js'; -import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { SSHPool } from './ssh-pool.js'; import { posixSingleQuote } from './sudo.js'; @@ -35,34 +34,22 @@ export interface OpenPtyParams { } interface ScrollChunk { - offsetMs: number; text: string; bytes: number; } interface InternalPtySession { info: PtySessionInfo; - env?: Record; - sudo?: boolean; channel: ClientChannel; chunks: ScrollChunk[]; stdoutDecoder: StringDecoder; stderrDecoder: StringDecoder; } -export function assertSafeCwd(cwd: string): string { - if (/[\x00-\x1f\x7f]/.test(cwd)) { - throw new Error('Invalid cwd: control characters are not permitted'); - } - const trimmed = cwd.trim(); - if (trimmed.length > 1024) { - throw new Error('Invalid cwd: exceeds 1024 character limit'); - } - return trimmed; -} +const MAX_RETAINED_EXITED_SESSIONS = 20; export function formatRemoteCd(cwd: string): string { - const trimmed = assertSafeCwd(cwd); + const trimmed = cwd.trim(); if (trimmed === '~' || trimmed === '~/') { return 'cd -- "$HOME"'; } @@ -84,6 +71,7 @@ function sliceTrailingUtf8(text: string, maxBytes: number): { text: string; byte return { text, bytes: buf.length }; } let start = buf.length - maxBytes; + // Skip UTF-8 continuation bytes (10xxxxxx) so we never cut inside a codepoint while (start < buf.length && (buf[start]! & 0b1100_0000) === 0b1000_0000) { start++; } @@ -99,7 +87,6 @@ export class PTYManager { private readonly sshPool: SSHPool, private readonly configManager: ConfigManager, private readonly wsHub: WsHub, - private readonly getRuntimeLimits?: () => RuntimeLimits, ) { this.reaperTimer = setInterval(() => { this.reapIdleSessions(); @@ -107,12 +94,14 @@ export class PTYManager { this.reaperTimer.unref(); } - private async createChannel( - params: OpenPtyParams, - cols: number, - rows: number, - trimmedCwd?: string, - ): Promise { + async openSession(params: OpenPtyParams): Promise { + const cols = Math.max(10, Math.min(500, Math.floor(params.cols ?? 80))); + const rows = Math.max(4, Math.min(200, Math.floor(params.rows ?? 24))); + const now = Date.now(); + const sessionId = `pty-${crypto.randomBytes(6).toString('hex')}`; + const trimmedCwd = params.cwd?.trim(); + + let channel: ClientChannel; if (params.command) { const cmd = trimmedCwd ? `${formatRemoteCd(trimmedCwd)} && (${params.command})` @@ -122,91 +111,18 @@ export class PTYManager { sudo: params.sudo, pty: { cols, rows, term: 'xterm-256color' }, }); - stream.done.catch(() => undefined); - return stream.channel; - } - - if (trimmedCwd && trimmedCwd !== '~') { - const channel = await this.sshPool.openShell(params.serverId, { + channel = stream.channel; + } else { + channel = await this.sshPool.openShell(params.serverId, { cols, rows, term: 'xterm-256color', }); - channel.write(`${formatRemoteCd(trimmedCwd)}\n`); - return channel; + if (trimmedCwd && trimmedCwd !== '~') { + channel.write(`${formatRemoteCd(trimmedCwd)}\n`); + } } - return this.sshPool.openShell(params.serverId, { - cols, - rows, - term: 'xterm-256color', - }); - } - - private bindChannelHandlers(internal: InternalPtySession): void { - const { channel } = internal; - const { sessionId } = internal.info; - - channel.on('data', (chunk: Buffer) => { - const text = internal.stdoutDecoder.write(chunk); - if (text) this.appendOutput(internal, text); - }); - - channel.stderr?.on('data', (chunk: Buffer) => { - const text = internal.stderrDecoder.write(chunk); - if (text) this.appendOutput(internal, text); - }); - - const finalizeExit = (code: number | null) => { - if (internal.channel !== channel || internal.info.exited) return; - const tailOut = internal.stdoutDecoder.end(); - if (tailOut) this.appendOutput(internal, tailOut); - const tailErr = internal.stderrDecoder.end(); - if (tailErr) this.appendOutput(internal, tailErr); - - internal.info.exited = true; - internal.info.exitCode = code; - internal.info.lastActivityAt = Date.now(); - this.wsHub.broadcastChannel(WS_CHANNELS.pty(sessionId), { - type: 'pty:exit', - sessionId, - exitCode: code, - }); - this.pruneExcessExited(); - }; - - channel.on('exit', (code: number | null) => { - finalizeExit(typeof code === 'number' ? code : null); - }); - channel.on('close', () => { - finalizeExit(internal.info.exitCode); - }); - channel.on('error', () => { - finalizeExit(internal.info.exitCode); - }); - } - - async openSession(params: OpenPtyParams): Promise { - const limits = this.getRuntimeLimits?.(); - const maxActive = limits?.maxActivePtys ?? 32; - const activeCount = [...this.sessions.values()].filter((s) => !s.info.exited).length; - if (activeCount >= maxActive) { - throw new Error(`Active PTY limit (${maxActive}) reached`); - } - - const cols = Math.max(10, Math.min(500, Math.floor(params.cols ?? 80))); - const rows = Math.max(4, Math.min(200, Math.floor(params.rows ?? 24))); - const now = Date.now(); - const sessionId = `pty-${crypto.randomBytes(6).toString('hex')}`; - const trimmedCwd = params.cwd !== undefined ? assertSafeCwd(params.cwd) : undefined; - - const channel = await this.createChannel( - params, - cols, - rows, - trimmedCwd || undefined, - ); - const title = params.title?.trim() || (params.command @@ -228,52 +144,48 @@ export class PTYManager { exitCode: null, scrollbackBytes: 0, }, - env: params.env, - sudo: params.sudo, channel, chunks: [], stdoutDecoder: new StringDecoder('utf8'), stderrDecoder: new StringDecoder('utf8'), }; this.sessions.set(sessionId, internal); - this.bindChannelHandlers(internal); - return { ...internal.info }; - } + channel.on('data', (chunk: Buffer) => { + const text = internal.stdoutDecoder.write(chunk); + if (text) this.appendOutput(internal, text); + }); - async reconnectSession(sessionId: string): Promise { - const internal = this.sessions.get(sessionId); - if (!internal) return null; + channel.stderr?.on('data', (chunk: Buffer) => { + const text = internal.stderrDecoder.write(chunk); + if (text) this.appendOutput(internal, text); + }); - const oldChannel = internal.channel; - const channel = await this.createChannel( - { - serverId: internal.info.serverId, - command: internal.info.command, - env: internal.env, - sudo: internal.sudo, - }, - internal.info.cols, - internal.info.rows, - internal.info.cwd, - ); + const finalizeExit = (code: number | null) => { + if (internal.info.exited) return; + const tailOut = internal.stdoutDecoder.end(); + if (tailOut) this.appendOutput(internal, tailOut); + const tailErr = internal.stderrDecoder.end(); + if (tailErr) this.appendOutput(internal, tailErr); - internal.channel = channel; - internal.stdoutDecoder = new StringDecoder('utf8'); - internal.stderrDecoder = new StringDecoder('utf8'); - internal.info.exited = false; - internal.info.exitCode = null; - internal.info.lastActivityAt = Date.now(); - this.bindChannelHandlers(internal); + internal.info.exited = true; + internal.info.exitCode = code; + internal.info.lastActivityAt = Date.now(); + this.wsHub.broadcastChannel(WS_CHANNELS.pty(sessionId), { + type: 'pty:exit', + sessionId, + exitCode: code, + }); + this.pruneExcessExited(); + }; - try { - oldChannel.close(); - oldChannel.destroy(); - } catch { - // Ignore cleanup errors on prior channel - } + channel.on('exit', (code: number | null) => { + finalizeExit(typeof code === 'number' ? code : null); + }); + channel.on('close', () => { + finalizeExit(internal.info.exitCode); + }); - this.appendOutput(internal, '\r\n[gcoord: reconnected PTY session]\r\n'); return { ...internal.info }; } @@ -303,6 +215,7 @@ export class PTYManager { entry.info.cols = clampedCols; entry.info.rows = clampedRows; entry.info.lastActivityAt = Date.now(); + // @types/ssh2: Channel.setWindow(rows, cols, height, width) entry.channel.setWindow(clampedRows, clampedCols, 0, 0); return true; } @@ -315,34 +228,16 @@ export class PTYManager { exportScrollback( sessionId: string, - format: 'plain' | 'ansi' | 'cast' = 'plain', - ): { filename: string; content: string; contentType: string } | null { + format: 'plain' | 'ansi' = 'plain', + ): { filename: string; content: string } | null { const entry = this.sessions.get(sessionId); if (!entry) return null; - if (format === 'cast') { - const header = JSON.stringify({ - version: 2, - width: entry.info.cols, - height: entry.info.rows, - timestamp: Math.floor(entry.info.createdAt / 1000), - title: entry.info.title, - }); - const events = entry.chunks.map((c) => - JSON.stringify([Number((c.offsetMs / 1000).toFixed(3)), 'o', c.text]), - ); - return { - filename: `${entry.info.serverId}-${sessionId}.cast`, - content: `${[header, ...events].join('\n')}\n`, - contentType: 'application/x-asciicast; charset=utf-8', - }; - } const raw = entry.chunks.map((c) => c.text).join(''); const content = format === 'ansi' ? raw : stripAnsiSequences(raw); const ext = format === 'ansi' ? 'ansi.log' : 'txt'; return { filename: `${entry.info.serverId}-${sessionId}.${ext}`, content, - contentType: 'text/plain; charset=utf-8', }; } @@ -380,22 +275,15 @@ export class PTYManager { } private appendOutput(entry: InternalPtySession, text: string): void { - const configuredMax = this.configManager.getSettings().ptyScrollbackBytes; - const runtimeCap = this.getRuntimeLimits?.()?.defaultPtyScrollbackBytes; - const maxBytes = Math.max( - 16_384, - runtimeCap ? Math.min(configuredMax, runtimeCap) : configuredMax, - ); + const maxBytes = Math.max(16_384, this.configManager.getSettings().ptyScrollbackBytes); const rawBytes = Buffer.byteLength(text, 'utf8'); - const now = Date.now(); - const offsetMs = Math.max(0, now - entry.info.createdAt); if (rawBytes >= maxBytes) { const trimmed = sliceTrailingUtf8(text, maxBytes); - entry.chunks = [{ offsetMs, text: trimmed.text, bytes: trimmed.bytes }]; + entry.chunks = [{ text: trimmed.text, bytes: trimmed.bytes }]; entry.info.scrollbackBytes = trimmed.bytes; } else { - entry.chunks.push({ offsetMs, text, bytes: rawBytes }); + entry.chunks.push({ text, bytes: rawBytes }); entry.info.scrollbackBytes += rawBytes; while (entry.info.scrollbackBytes > maxBytes && entry.chunks.length > 0) { const dropped = entry.chunks.shift()!; @@ -403,7 +291,7 @@ export class PTYManager { } } - entry.info.lastActivityAt = now; + entry.info.lastActivityAt = Date.now(); this.wsHub.broadcastChannel(WS_CHANNELS.pty(entry.info.sessionId), { type: 'pty:output', sessionId: entry.info.sessionId, @@ -432,11 +320,10 @@ export class PTYManager { } private pruneExcessExited(): void { - const maxRetained = this.getRuntimeLimits?.()?.maxRetainedExitedPtys ?? 12; const exited = [...this.sessions.values()] .filter((s) => s.info.exited) .sort((a, b) => a.info.lastActivityAt - b.info.lastActivityAt); - while (exited.length > maxRetained) { + while (exited.length > MAX_RETAINED_EXITED_SESSIONS) { const oldest = exited.shift()!; this.sessions.delete(oldest.info.sessionId); } diff --git a/src/server/ssh/sftp-service.ts b/src/server/ssh/sftp-service.ts index 9308d0a..ee9ba12 100644 --- a/src/server/ssh/sftp-service.ts +++ b/src/server/ssh/sftp-service.ts @@ -17,7 +17,6 @@ export interface SftpListEntry { mtimeMs: number; uid: number; gid: number; - symlinkTarget?: string; } export interface SftpTextFile { @@ -34,8 +33,6 @@ export class SftpServiceError extends Error { | 'NOT_FOUND' | 'NOT_A_DIRECTORY' | 'IS_A_DIRECTORY' - | 'UNSUPPORTED_FILE_TYPE' - | 'ALREADY_EXISTS' | 'FILE_TOO_LARGE' | 'BINARY_FILE_NOT_EDITABLE' | 'CONFLICT' @@ -107,18 +104,9 @@ export class SftpService { if (item.filename === '.' || item.filename === '..') continue; const mode = item.attrs.mode ?? 0; const type = modeToType(mode); - const itemPath = path.posix.join(resolved, item.filename); - let symlinkTarget: string | undefined; - if (type === 'symlink') { - try { - symlinkTarget = await promisifySftp((cb) => sftp.readlink(itemPath, cb)); - } catch { - symlinkTarget = undefined; - } - } entries.push({ name: item.filename, - path: itemPath, + path: path.posix.join(resolved, item.filename), type, size: item.attrs.size ?? 0, mode, @@ -126,7 +114,6 @@ export class SftpService { mtimeMs: (item.attrs.mtime ?? 0) * 1000, uid: item.attrs.uid ?? 0, gid: item.attrs.gid ?? 0, - ...(symlinkTarget !== undefined ? { symlinkTarget } : {}), }); } @@ -144,28 +131,18 @@ export class SftpService { async statPath(serverId: string, remotePath: string): Promise { return this.withSftp(serverId, async (sftp) => { const resolved = await this.resolveRemotePath(sftp, remotePath); - const lstats = await promisifySftp((cb) => sftp.lstat(resolved, cb)); - const mode = lstats.mode ?? 0; - const type = modeToType(mode); - let symlinkTarget: string | undefined; - if (type === 'symlink') { - try { - symlinkTarget = await promisifySftp((cb) => sftp.readlink(resolved, cb)); - } catch { - symlinkTarget = undefined; - } - } + const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); + const mode = stats.mode ?? 0; return { name: path.posix.basename(resolved) || '/', path: resolved, - type, - size: lstats.size ?? 0, + type: modeToType(mode), + size: stats.size ?? 0, mode, permissionsOctal: (mode & 0o7777).toString(8).padStart(4, '0'), - mtimeMs: (lstats.mtime ?? 0) * 1000, - uid: lstats.uid ?? 0, - gid: lstats.gid ?? 0, - ...(symlinkTarget !== undefined ? { symlinkTarget } : {}), + mtimeMs: (stats.mtime ?? 0) * 1000, + uid: stats.uid ?? 0, + gid: stats.gid ?? 0, }; }); } @@ -192,19 +169,12 @@ export class SftpService { try { const resolved = await this.resolveRemotePath(sftp, remotePath); const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); - const kind = modeToType(stats.mode); - if (kind === 'dir') { + if (modeToType(stats.mode) === 'dir') { throw new SftpServiceError( 'IS_A_DIRECTORY', 'Cannot download a directory as a single file; use /archive instead.', ); } - if (kind !== 'file') { - throw new SftpServiceError( - 'UNSUPPORTED_FILE_TYPE', - `Refusing to download special/non-regular file: ${resolved}`, - ); - } const stream = sftp.createReadStream(resolved); stream.once('close', cleanup); stream.once('error', cleanup); @@ -229,14 +199,10 @@ export class SftpService { ): Promise<{ path: string; bytesWritten: number }> { return this.withSftp(serverId, async (sftp) => { const resolved = await this.resolveRemotePath(sftp, remotePath); - const tmpPath = path.posix.join( - path.posix.dirname(resolved), - `.gcoord-up-${crypto.randomBytes(6).toString('hex')}`, - ); - const dest = sftp.createWriteStream(tmpPath); + const dest = sftp.createWriteStream(resolved); let bytesWritten = 0; - await new Promise((resolve, reject) => { + return new Promise<{ path: string; bytesWritten: number }>((resolve, reject) => { let settled = false; const fail = (err: Error) => { if (settled) return; @@ -271,41 +237,11 @@ export class SftpService { dest.on('close', () => { if (settled) return; settled = true; - resolve(); + resolve({ path: resolved, bytesWritten }); }); source.pipe(dest); - }).catch(async (err) => { - await promisifySftpVoid((cb) => sftp.unlink(tmpPath, cb)).catch(() => undefined); - throw err; }); - - try { - await this.renameSftpPath(sftp, tmpPath, resolved, true); - } catch (err) { - await promisifySftpVoid((cb) => sftp.unlink(tmpPath, cb)).catch(() => undefined); - throw err; - } - - return { path: resolved, bytesWritten }; - }); - } - - async touchFile(serverId: string, remotePath: string): Promise { - return this.withSftp(serverId, async (sftp) => { - const resolved = await this.resolveRemotePath(sftp, remotePath); - let exists = false; - try { - await promisifySftp((cb) => sftp.lstat(resolved, cb)); - exists = true; - } catch { - exists = false; - } - if (exists) { - throw new SftpServiceError('ALREADY_EXISTS', `Path already exists: ${resolved}`); - } - await promisifySftpVoid((cb) => sftp.writeFile(resolved, Buffer.alloc(0), cb)); - return resolved; }); } @@ -317,43 +253,16 @@ export class SftpService { }); } - async rename( - serverId: string, - fromPath: string, - toPath: string, - overwrite = false, - ): Promise<{ from: string; to: string }> { + async rename(serverId: string, fromPath: string, toPath: string): Promise<{ from: string; to: string }> { return this.withSftp(serverId, async (sftp) => { const resolvedFrom = await this.resolveRemotePath(sftp, fromPath); const resolvedTo = await this.resolveRemotePath(sftp, toPath); - if (resolvedFrom === resolvedTo) { - return { from: resolvedFrom, to: resolvedTo }; - } - if (!overwrite) { - let destExists = false; - try { - await promisifySftp((cb) => sftp.lstat(resolvedTo, cb)); - destExists = true; - } catch { - destExists = false; - } - if (destExists) { - throw new SftpServiceError( - 'ALREADY_EXISTS', - `Destination "${resolvedTo}" already exists`, - ); - } - } - await this.renameSftpPath(sftp, resolvedFrom, resolvedTo, overwrite); + await this.renameSftpPath(sftp, resolvedFrom, resolvedTo); return { from: resolvedFrom, to: resolvedTo }; }); } - async chmod( - serverId: string, - remotePath: string, - modeInput: string | number, - ): Promise<{ path: string; permissionsOctal: string }> { + async chmod(serverId: string, remotePath: string, modeInput: string | number): Promise<{ path: string; permissionsOctal: string }> { const parsedMode = typeof modeInput === 'number' ? modeInput @@ -374,37 +283,6 @@ export class SftpService { }); } - async chown( - serverId: string, - remotePath: string, - uid: number, - gid: number, - sudo = false, - ): Promise<{ path: string; uid: number; gid: number }> { - if (!Number.isInteger(uid) || uid < 0 || !Number.isInteger(gid) || gid < 0) { - throw new SftpServiceError('INVALID_MODE', 'uid and gid must be non-negative integers'); - } - - if (sudo) { - const resolved = await this.resolvePathNoStat(serverId, remotePath); - const res = await this.sshPool.exec( - serverId, - `chown ${uid}:${gid} -- ${posixSingleQuote(resolved)}`, - { sudo: true }, - ); - if (res.exitCode !== 0) { - throw new Error(res.stderr.trim() || `chown failed for ${resolved}`); - } - return { path: resolved, uid, gid }; - } - - return this.withSftp(serverId, async (sftp) => { - const resolved = await this.resolveRemotePath(sftp, remotePath); - await promisifySftpVoid((cb) => sftp.chown(resolved, uid, gid, cb)); - return { path: resolved, uid, gid }; - }); - } - async deletePath( serverId: string, remotePath: string, @@ -420,51 +298,6 @@ export class SftpService { }); } - async bulkDelete( - serverId: string, - paths: string[], - recursive = false, - ): Promise<{ deleted: string[]; failed: Array<{ path: string; error: string }> }> { - const deleted: string[] = []; - const failed: Array<{ path: string; error: string }> = []; - for (const p of paths) { - try { - const res = await this.deletePath(serverId, p, recursive); - deleted.push(res); - } catch (err) { - failed.push({ - path: p, - error: err instanceof Error ? err.message : String(err), - }); - } - } - return { deleted, failed }; - } - - async searchFiles( - serverId: string, - basePath: string, - query: string, - maxResults = 100, - ): Promise<{ basePath: string; matches: string[] }> { - const cleanQuery = query.trim(); - if (!cleanQuery || /[\x00\r\n]/.test(cleanQuery)) { - throw new SftpServiceError('INVALID_PATH', 'Invalid search query'); - } - const resolvedBase = await this.resolvePathNoStat(serverId, basePath || '/'); - const escapedPattern = cleanQuery.includes('*') || cleanQuery.includes('?') - ? cleanQuery - : `*${cleanQuery}*`; - const cap = Math.max(1, Math.min(200, maxResults)); - const cmd = `find ${posixSingleQuote(resolvedBase)} -maxdepth 5 -iname ${posixSingleQuote(escapedPattern)} 2>/dev/null | head -n ${cap}`; - const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000, maxBytes: 256 * 1024 }); - const matches = res.stdout - .split(/\r?\n/) - .map((l) => l.trim()) - .filter((l) => l.length > 0 && l !== resolvedBase); - return { basePath: resolvedBase, matches }; - } - async readTextFile( serverId: string, remotePath: string, @@ -508,10 +341,7 @@ export class SftpService { } const buf = Buffer.from(catRes.stdout, 'utf8'); if (buf.includes(0)) { - throw new SftpServiceError( - 'BINARY_FILE_NOT_EDITABLE', - 'Binary file cannot be opened in inline editor', - ); + throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor'); } return { path: resolved, @@ -525,16 +355,9 @@ export class SftpService { return this.withSftp(serverId, async (sftp) => { const resolved = await this.resolveRemotePath(sftp, remotePath); const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); - const kind = modeToType(stats.mode); - if (kind === 'dir') { + if (modeToType(stats.mode) === 'dir') { throw new SftpServiceError('IS_A_DIRECTORY', `${resolved} is a directory`); } - if (kind !== 'file') { - throw new SftpServiceError( - 'UNSUPPORTED_FILE_TYPE', - `Refusing to open special/non-regular file: ${resolved}`, - ); - } if ((stats.size ?? 0) > maxBytes) { throw new SftpServiceError( 'FILE_TOO_LARGE', @@ -546,10 +369,7 @@ export class SftpService { throw new SftpServiceError('FILE_TOO_LARGE', 'File exceeds inline editor limit'); } if (buf.includes(0)) { - throw new SftpServiceError( - 'BINARY_FILE_NOT_EDITABLE', - 'Binary file cannot be opened in inline editor', - ); + throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor'); } return { path: resolved, @@ -592,7 +412,7 @@ export class SftpService { const qTmp = posixSingleQuote(tmp); const res = await this.sshPool.exec( serverId, - `umask 077 && cat > ${qTmp} && { [ ! -e ${qDst} ] || { chmod --reference=${qDst} ${qTmp} 2>/dev/null; chown --reference=${qDst} ${qTmp} 2>/dev/null; true; }; } && mv -f -- ${qTmp} ${qDst}`, + `umask 077 && cat > ${qTmp} && { [ ! -e ${qDst} ] || chmod --reference=${qDst} ${qTmp} 2>/dev/null || true; } && mv -f ${qTmp} ${qDst}`, { sudo: true, stdin: newBuf }, ); if (res.exitCode !== 0) { @@ -618,6 +438,7 @@ export class SftpService { } } catch (err) { if (err instanceof SftpServiceError && err.code === 'CONFLICT') throw err; + // File does not yet exist or could not be pre-read } const dir = path.posix.dirname(resolved); @@ -629,7 +450,7 @@ export class SftpService { () => undefined, ); } - await this.renameSftpPath(sftp, tmp, resolved, true); + await this.renameSftpPath(sftp, tmp, resolved); } catch (err) { await promisifySftpVoid((cb) => sftp.unlink(tmp, cb)).catch(() => undefined); throw err; @@ -677,10 +498,8 @@ export class SftpService { const safeName = (resolved === '/' ? 'root' : baseName).replace(/[^A-Za-z0-9._-]/g, '_'); const archiveFileName = `${safeName}.${resolvedFormat}`; - const osDetected = this.sshPool.getState(serverId)?.osDetected; - const oneFsFlag = osDetected !== 'bsd' && osDetected !== 'macos' ? '--one-file-system ' : ''; - const compressCmd = resolvedFormat === 'tar.zst' ? 'zstd -T2 -c' : 'gzip -c'; - const cmd = `set -o pipefail 2>/dev/null || true; tar ${oneFsFlag}-C ${posixSingleQuote(parentDir)} -cf - -- ${posixSingleQuote(baseName)} | ${compressCmd}`; + const compressCmd = resolvedFormat === 'tar.zst' ? 'zstd -T0 -c' : 'gzip -c'; + const cmd = `set -o pipefail 2>/dev/null || true; tar -C ${posixSingleQuote(parentDir)} -cf - ${posixSingleQuote(baseName)} | ${compressCmd}`; const handle = await this.sshPool.execStream(serverId, cmd); return { @@ -719,9 +538,6 @@ export class SftpService { private async resolveRemotePath(sftp: SFTPWrapper, requestedPath?: string): Promise { const trimmed = requestedPath?.trim() ?? ''; - if (/[\x00\r\n]/.test(trimmed)) { - throw new SftpServiceError('INVALID_PATH', 'Control characters not permitted in path'); - } if (!trimmed || trimmed === '.' || trimmed === '~') { const home = await promisifySftp((cb) => sftp.realpath('.', cb)); return path.posix.normalize(home || '/'); @@ -741,12 +557,7 @@ export class SftpService { sftp: SFTPWrapper, fromPath: string, toPath: string, - overwrite = false, ): Promise { - if (!overwrite) { - await promisifySftpVoid((cb) => sftp.rename(fromPath, toPath, cb)); - return; - } try { await promisifySftpVoid((cb) => sftp.ext_openssh_rename(fromPath, toPath, cb)); } catch { diff --git a/src/server/ssh/ssh-config-import.ts b/src/server/ssh/ssh-config-import.ts deleted file mode 100644 index cb300ff..0000000 --- a/src/server/ssh/ssh-config-import.ts +++ /dev/null @@ -1,149 +0,0 @@ -export interface ParsedOpenSshHost { - alias: string; - id: string; - name: string; - host: string; - port: number; - username: string; - jumpHostAlias?: string; -} - -export interface OpenSshImportPreview { - entries: ParsedOpenSshHost[]; - warnings: string[]; -} - -function slugifyHostId(alias: string): string { - const clean = alias - .toLowerCase() - .replace(/[^a-z0-9._-]+/g, '-') - .replace(/^[^a-z0-9]+|[-_.]+$/g, '') - .slice(0, 64); - return clean || 'srv'; -} - -function stripComment(line: string): string { - let inQuotes = false; - for (let i = 0; i < line.length; i++) { - const ch = line[i]!; - if (ch === '"') inQuotes = !inQuotes; - else if (ch === '#' && !inQuotes) return line.slice(0, i); - } - return line; -} - -function unquoteVal(val: string): string { - const t = val.trim(); - if (t.length >= 2 && t.startsWith('"') && t.endsWith('"')) { - return t.slice(1, -1); - } - return t; -} - -export function parseOpenSshConfig(text: string): OpenSshImportPreview { - const warnings: string[] = []; - const rawLines = text.split(/\r?\n/); - - interface DraftBlock { - patterns: string[]; - hostName?: string; - port?: number; - user?: string; - proxyJump?: string; - } - - const blocks: DraftBlock[] = []; - let current: DraftBlock | null = null; - - for (let i = 0; i < rawLines.length; i++) { - const cleaned = stripComment(rawLines[i]!).trim(); - if (!cleaned) continue; - - const eqOrSpace = /^([A-Za-z][A-Za-z0-9]*)\s*(?:=|\s+)\s*(.+)$/.exec(cleaned); - if (!eqOrSpace) { - warnings.push(`Line ${i + 1}: ignored unparseable directive`); - continue; - } - - const key = eqOrSpace[1]!.toLowerCase(); - const rawVal = unquoteVal(eqOrSpace[2]!); - - if (key === 'match') { - current = null; - warnings.push(`Line ${i + 1}: skipped unsupported Match block`); - continue; - } - - if (key === 'host') { - const patterns = rawVal.split(/\s+/).filter(Boolean); - current = { patterns }; - blocks.push(current); - continue; - } - - if (!current) continue; - - if (key === 'hostname') { - current.hostName = rawVal; - } else if (key === 'port') { - const p = Number.parseInt(rawVal, 10); - if (Number.isInteger(p) && p >= 1 && p <= 65535) { - current.port = p; - } else { - warnings.push(`Line ${i + 1}: invalid Port "${rawVal}"`); - } - } else if (key === 'user') { - current.user = rawVal; - } else if (key === 'proxyjump') { - const firstHop = rawVal.split(',')[0]?.trim(); - if (firstHop && firstHop.toLowerCase() !== 'none') { - const atIdx = firstHop.lastIndexOf('@'); - const hopHost = atIdx >= 0 ? firstHop.slice(atIdx + 1) : firstHop; - const colonIdx = hopHost.lastIndexOf(':'); - current.proxyJump = colonIdx > 0 && !hopHost.includes(']') ? hopHost.slice(0, colonIdx) : hopHost; - } - } - } - - const entries: ParsedOpenSshHost[] = []; - const usedIds = new Set(); - - for (const blk of blocks) { - for (const alias of blk.patterns) { - if (alias.includes('*') || alias.includes('?') || alias.startsWith('!')) { - warnings.push(`Skipped wildcard/negated Host pattern "${alias}"`); - continue; - } - const host = (blk.hostName ?? alias).trim(); - if (!host || /\s/.test(host)) { - warnings.push(`Skipped Host "${alias}": invalid host name`); - continue; - } - const username = (blk.user ?? 'root').trim(); - if (!username || /\s/.test(username)) { - warnings.push(`Skipped Host "${alias}": invalid username`); - continue; - } - - let id = slugifyHostId(alias); - if (usedIds.has(id)) { - let n = 2; - while (usedIds.has(`${id.slice(0, 58)}-${n}`)) n++; - id = `${id.slice(0, 58)}-${n}`; - } - usedIds.add(id); - - entries.push({ - alias, - id, - name: alias, - host, - port: blk.port ?? 22, - username, - ...(blk.proxyJump ? { jumpHostAlias: blk.proxyJump } : {}), - }); - } - } - - return { entries, warnings }; -} diff --git a/src/server/ssh/ssh-pool.ts b/src/server/ssh/ssh-pool.ts index 3dab1e5..e27920f 100644 --- a/src/server/ssh/ssh-pool.ts +++ b/src/server/ssh/ssh-pool.ts @@ -7,29 +7,13 @@ import ssh2, { } from 'ssh2'; import type { ServerConfig } from '../../shared/schemas/server.schema.js'; import type { - HostKeyAlert, ServerConnectionStatus, ServerRuntimeState, } from '../../shared/ws-protocol.js'; import type { ConfigManager } from '../config/config-manager.js'; import type { VaultService } from '../security/vault.js'; import type { KnownHostsService } from './known-hosts.js'; -import { - buildEnvPrefix, - posixSingleQuote, - prepareSudoExecution, - SUDO_PTY_PROMPT, -} from './sudo.js'; - -export interface ServerTestResult { - ok: boolean; - latencyMs: number; - osDetected?: 'linux' | 'bsd' | 'macos'; - hostFingerprint?: string; - tofuRequired?: boolean; - hostKeyMismatch?: HostKeyAlert; - error?: string; -} +import { buildEnvPrefix, prepareSudoExecution } from './sudo.js'; export interface ExecResult { stdout: string; @@ -74,9 +58,6 @@ const DEFAULT_MAX_BYTES = 2 * 1024 * 1024; export class SSHPool { private readonly connections = new Map(); private readonly inFlight = new Map>(); - private readonly pendingClients = new Map>(); - private readonly serverEpoch = new Map(); - private poolEpoch = 0; private readonly states = new Map(); private readonly reconnectTimers = new Map(); private readonly reconnectAttempts = new Map(); @@ -93,24 +74,6 @@ export class SSHPool { }); } - private getServerEpoch(serverId: string): number { - return this.serverEpoch.get(serverId) ?? 0; - } - - private validateJumpChain(serverId: string): void { - const chain = new Set(); - let currentId: string | undefined = serverId; - while (currentId) { - if (chain.has(currentId)) { - throw new Error(`ProxyJump cycle detected involving "${currentId}"`); - } - chain.add(currentId); - const srv = this.configManager.getServer(currentId); - if (!srv) break; - currentId = srv.jumpHostId; - } - } - onStateChange(listener: (states: ServerRuntimeState[]) => void): () => void { this.stateListeners.add(listener); return () => { @@ -169,7 +132,6 @@ export class SSHPool { if (visited.has(serverId)) { throw new Error(`ProxyJump cycle detected involving "${serverId}"`); } - this.validateJumpChain(serverId); const existing = this.connections.get(serverId); if (existing) { @@ -183,42 +145,19 @@ export class SSHPool { const nextVisited = new Set(visited); nextVisited.add(serverId); - const startPoolEpoch = this.poolEpoch; - const startSrvEpoch = this.getServerEpoch(serverId); - const connectPromise = this.connectServer( - server, - nextVisited, - startPoolEpoch, - startSrvEpoch, - ).finally(() => { - if (this.inFlight.get(serverId) === connectPromise) { - this.inFlight.delete(serverId); - } + const connectPromise = this.connectServer(server, nextVisited).finally(() => { + this.inFlight.delete(serverId); }); this.inFlight.set(serverId, connectPromise); return connectPromise; } - private getSudoPassword(server: ServerConfig): string | undefined { - if (!server.sudoCredentialId) return undefined; - const sudoCred = this.vaultService.getRuntimeSecret(server.sudoCredentialId); - if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) { - return sudoCred.password; - } - return undefined; - } - private prepareCommand( server: ServerConfig, command: string, - opts: { - sudo?: boolean; - env?: Record; - stdin?: Buffer | string; - ptyPrompt?: boolean; - }, - ): { finalCommand: string; stdinBuf?: Buffer; ptyPassword?: string } { + opts: { sudo?: boolean; env?: Record; stdin?: Buffer | string }, + ): { finalCommand: string; stdinBuf?: Buffer } { const envPrefix = buildEnvPrefix(opts.env); let finalCommand = `${envPrefix}${command}`; let stdinBuf: Buffer | undefined = @@ -229,16 +168,20 @@ export class SSHPool { : Buffer.from(opts.stdin); if (opts.sudo) { - const sudoPassword = this.getSudoPassword(server); + let sudoPassword: string | undefined; + if (server.sudoCredentialId) { + const sudoCred = this.vaultService.getRuntimeSecret(server.sudoCredentialId); + if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) { + sudoPassword = sudoCred.password; + } + } const prepared = prepareSudoExecution(finalCommand, { sudoPassword, stdin: stdinBuf, - ptyPrompt: opts.ptyPrompt, }); if (stdinBuf) stdinBuf.fill(0); finalCommand = prepared.command; stdinBuf = prepared.stdin; - return { finalCommand, stdinBuf, ptyPassword: prepared.ptyPassword }; } return { finalCommand, stdinBuf }; @@ -285,10 +228,7 @@ export class SSHPool { throw new Error(`Unknown server "${serverId}"`); } - const { finalCommand, stdinBuf, ptyPassword } = this.prepareCommand(server, command, { - ...opts, - ptyPrompt: Boolean(opts.pty), - }); + const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts); return new Promise((resolve, reject) => { const execOpts = opts.pty @@ -308,21 +248,6 @@ export class SSHPool { return; } - let sudoSent = false; - let promptProbeBuf = ''; - const maybeSendPtyPassword = (chunk: Buffer) => { - if (!ptyPassword || sudoSent) return; - promptProbeBuf = (promptProbeBuf + chunk.toString('utf8')).slice(-256); - if (promptProbeBuf.includes(SUDO_PTY_PROMPT)) { - sudoSent = true; - channel.stdin.write(`${ptyPassword}\n`); - } - }; - if (ptyPassword) { - channel.on('data', maybeSendPtyPassword); - channel.stderr?.on('data', maybeSendPtyPassword); - } - let exitCode: number | null = null; let signal: string | undefined; const done = new Promise<{ exitCode: number | null; signal?: string }>( @@ -378,94 +303,10 @@ export class SSHPool { throw new Error(`Unknown server "${serverId}"`); } - const rawStdinBuf = - opts.stdin === undefined - ? undefined - : typeof opts.stdin === 'string' - ? Buffer.from(opts.stdin, 'utf8') - : Buffer.from(opts.stdin); - - // When both sudo password and non-empty stdin exist, avoid concatenating them into sudo's stdin: - // probe `sudo -n true` first; otherwise stage the payload in a private 0600 temp file. - if (opts.sudo && rawStdinBuf && rawStdinBuf.length > 0) { - const sudoPassword = this.getSudoPassword(server); - const envPrefix = buildEnvPrefix(opts.env); - const fullCmd = `${envPrefix}${command}`; - const quotedCmd = posixSingleQuote(fullCmd); - - if (sudoPassword) { - const noPassProbe = await this.execRaw(client, serverId, 'sudo -n true', undefined, 5_000, 4096); - if (noPassProbe.exitCode === 0) { - try { - return await this.execRaw( - client, - serverId, - `sudo -n sh -c ${quotedCmd}`, - rawStdinBuf, - opts.timeoutMs, - opts.maxBytes, - ); - } finally { - rawStdinBuf.fill(0); - } - } - - const mk = await this.execRaw( - client, - serverId, - 'f=$(mktemp /tmp/.gcoord_in.XXXXXX) && chmod 600 "$f" && printf "%s" "$f"', - undefined, - 10_000, - 1024, - ); - const tmpFile = mk.stdout.trim(); - if (mk.exitCode === 0 && tmpFile.startsWith('/tmp/.gcoord_in.')) { - try { - const stage = await this.execRaw( - client, - serverId, - `cat > ${posixSingleQuote(tmpFile)}`, - rawStdinBuf, - opts.timeoutMs, - 4096, - ); - if (stage.exitCode === 0) { - const pwBuf = Buffer.from(`${sudoPassword}\n`, 'utf8'); - try { - const execCmd = `sudo -S -k -p '' sh -c ${quotedCmd} < ${posixSingleQuote(tmpFile)}`; - return await this.execRaw( - client, - serverId, - execCmd, - pwBuf, - opts.timeoutMs, - opts.maxBytes, - ); - } finally { - pwBuf.fill(0); - } - } - } finally { - rawStdinBuf.fill(0); - await this.execRaw(client, serverId, `rm -f -- ${posixSingleQuote(tmpFile)}`, undefined, 5_000, 1024).catch(() => undefined); - } - } - } - } - rawStdinBuf?.fill(0); - const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts); - return this.execRaw(client, serverId, finalCommand, stdinBuf, opts.timeoutMs, opts.maxBytes); - } - private execRaw( - client: Client, - serverId: string, - finalCommand: string, - stdinBuf: Buffer | undefined, - timeoutMs = DEFAULT_EXEC_TIMEOUT_MS, - maxBytes = DEFAULT_MAX_BYTES, - ): Promise { + const timeoutMs = opts.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS; + const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES; const started = Date.now(); return new Promise((resolve, reject) => { @@ -500,7 +341,6 @@ export class SSHPool { reject(new Error(`SSH exec timed out after ${timeoutMs}ms on "${serverId}"`)), ); }, timeoutMs); - timer.unref(); if (stdinBuf && stdinBuf.length > 0) { stream.stdin.write(stdinBuf); @@ -661,112 +501,6 @@ export class SSHPool { } } - async testConnection(candidate: ServerConfig): Promise { - const started = Date.now(); - if (!this.vaultService.isRuntimeReady) { - return { ok: false, latencyMs: 0, error: 'Vault is locked' }; - } - const cred = this.vaultService.getRuntimeSecret(candidate.credentialId); - if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) { - return { - ok: false, - latencyMs: 0, - error: `Missing or incompatible SSH credential "${candidate.credentialId}" in Vault`, - }; - } - - let hopStream: Duplex | undefined; - const settings = this.configManager.getSettings(); - const client = new ssh2.Client(); - let observedFp: string | undefined; - - try { - if (candidate.jumpHostId) { - const bastion = await this.acquireClient( - candidate.jumpHostId, - new Set([candidate.id]), - ); - hopStream = await forwardOutOnClient( - bastion, - '127.0.0.1', - 0, - candidate.host, - candidate.port, - ); - } - - await new Promise((resolve, reject) => { - let settled = false; - const done = (err?: Error) => { - if (settled) return; - settled = true; - if (err) reject(err); - else resolve(); - }; - client.once('ready', () => done()); - client.once('error', (err) => done(err)); - client.once('close', () => done(new Error('SSH connection closed during test'))); - - const cfg: ConnectConfig = { - username: candidate.username, - readyTimeout: settings.sshReadyTimeoutMs, - hostVerifier: (keyBuf: Buffer) => { - const verified = this.knownHosts.verifyServerHostKey(candidate, keyBuf); - const tofu = this.knownHosts.getPendingTofu(candidate.id); - const mismatch = this.knownHosts.getPendingMismatch(candidate.id); - observedFp = mismatch?.actualFingerprint ?? tofu?.fingerprint; - return verified; - }, - }; - if (cred.type === 'ssh-key') { - cfg.privateKey = cred.privateKey; - if (cred.passphrase) cfg.passphrase = cred.passphrase; - } else { - cfg.password = cred.password; - } - if (hopStream) cfg.sock = hopStream; - else { - cfg.host = candidate.host; - cfg.port = candidate.port; - } - client.connect(cfg); - }); - - const uname = await this.execRaw(client, candidate.id, 'uname -s', undefined, 5_000, 512); - const rawOs = uname.stdout.trim().toLowerCase(); - const osDetected = rawOs.includes('freebsd') || rawOs.includes('openbsd') || rawOs.includes('netbsd') - ? 'bsd' - : rawOs.includes('darwin') - ? 'macos' - : 'linux'; - return { - ok: true, - latencyMs: Date.now() - started, - osDetected, - hostFingerprint: observedFp, - }; - } catch (err) { - const tofu = this.knownHosts.getPendingTofu(candidate.id); - const mismatch = this.knownHosts.getPendingMismatch(candidate.id); - return { - ok: false, - latencyMs: Date.now() - started, - hostFingerprint: mismatch?.actualFingerprint ?? tofu?.fingerprint ?? observedFp, - tofuRequired: Boolean(tofu), - hostKeyMismatch: mismatch, - error: err instanceof Error ? err.message : String(err), - }; - } finally { - try { - client.end(); - client.destroy(); - } catch { - // Ignore cleanup errors - } - hopStream?.destroy(); - } - } - async reconnect(serverId: string): Promise { this.closeServer(serverId); this.reconnectAttempts.delete(serverId); @@ -808,27 +542,12 @@ export class SSHPool { } closeServer(serverId: string): void { - this.serverEpoch.set(serverId, this.getServerEpoch(serverId) + 1); - this.inFlight.delete(serverId); const timer = this.reconnectTimers.get(serverId); if (timer) { clearTimeout(timer); this.reconnectTimers.delete(serverId); } - const pendingSet = this.pendingClients.get(serverId); - if (pendingSet) { - for (const c of [...pendingSet]) { - try { - c.end(); - c.destroy(); - } catch { - // Ignore pending client destroy error - } - } - this.pendingClients.delete(serverId); - } - const conn = this.connections.get(serverId); if (!conn) return; @@ -855,9 +574,7 @@ export class SSHPool { } } - closeAll(reason: 'panic_lock' | 'shutdown' | 'vault_sealed'): void { - this.poolEpoch += 1; - this.inFlight.clear(); + closeAll(reason: 'panic_lock' | 'shutdown'): void { if (reason === 'shutdown') { this.closed = true; } @@ -867,29 +584,16 @@ export class SSHPool { } this.reconnectTimers.clear(); - for (const [id, pendingSet] of [...this.pendingClients.entries()]) { - for (const c of [...pendingSet]) { - try { - c.end(); - c.destroy(); - } catch { - // Ignore destroy error - } - } - this.pendingClients.delete(id); - } - for (const id of [...this.connections.keys()]) { this.closeServer(id); } - if (reason === 'panic_lock' || reason === 'vault_sealed') { - const msg = reason === 'panic_lock' ? 'Panic Lock engaged' : 'Vault sealed'; + if (reason === 'panic_lock') { for (const server of this.configManager.listServers()) { this.states.set(server.id, { serverId: server.id, status: server.enabled ? 'vault_locked' : 'disabled', - lastError: server.enabled ? msg : undefined, + lastError: server.enabled ? 'Panic Lock engaged' : undefined, }); } this.emitStates(); @@ -899,8 +603,6 @@ export class SSHPool { private async connectServer( server: ServerConfig, visited: Set, - startPoolEpoch: number, - startSrvEpoch: number, ): Promise { const cred = this.vaultService.getRuntimeSecret(server.credentialId); if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) { @@ -914,14 +616,6 @@ export class SSHPool { let hopStream: Duplex | undefined; if (server.jumpHostId) { const bastion = await this.acquireClient(server.jumpHostId, visited); - if ( - this.closed || - !this.vaultService.isRuntimeReady || - this.poolEpoch !== startPoolEpoch || - this.getServerEpoch(server.id) !== startSrvEpoch - ) { - throw new Error('SSH connection aborted due to pool reset or Vault lock'); - } hopStream = await forwardOutOnClient( bastion, '127.0.0.1', @@ -933,20 +627,6 @@ export class SSHPool { const settings = this.configManager.getSettings(); const client = new ssh2.Client(); - let setForServer = this.pendingClients.get(server.id); - if (!setForServer) { - setForServer = new Set(); - this.pendingClients.set(server.id, setForServer); - } - setForServer.add(client); - - const untrackPending = () => { - const s = this.pendingClients.get(server.id); - if (s) { - s.delete(client); - if (s.size === 0) this.pendingClients.delete(server.id); - } - }; return new Promise((resolve, reject) => { let settled = false; @@ -954,7 +634,6 @@ export class SSHPool { const failConnect = (err: Error) => { if (settled) return; settled = true; - untrackPending(); hopStream?.destroy(); try { client.destroy(); @@ -962,16 +641,6 @@ export class SSHPool { // Ignore destroy failure } - if ( - this.closed || - !this.vaultService.isRuntimeReady || - this.poolEpoch !== startPoolEpoch || - this.getServerEpoch(server.id) !== startSrvEpoch - ) { - reject(err); - return; - } - const mismatch = this.knownHosts.getPendingMismatch(server.id); const tofu = this.knownHosts.getPendingTofu(server.id); let status: ServerConnectionStatus = 'disconnected'; @@ -994,23 +663,8 @@ export class SSHPool { }; client.once('ready', () => { - untrackPending(); - const invalidated = - settled || - this.closed || - !this.vaultService.isRuntimeReady || - this.poolEpoch !== startPoolEpoch || - this.getServerEpoch(server.id) !== startSrvEpoch; - if (invalidated) { - settled = true; - hopStream?.destroy(); - try { - client.end(); - client.destroy(); - } catch { - // Ignore close failure - } - reject(new Error('SSH connection aborted due to Panic Lock, seal, or reset')); + if (settled) { + client.end(); return; } settled = true; @@ -1055,16 +709,6 @@ export class SSHPool { } }); - if ( - this.closed || - !this.vaultService.isRuntimeReady || - this.poolEpoch !== startPoolEpoch || - this.getServerEpoch(server.id) !== startSrvEpoch - ) { - failConnect(new Error('SSH connection aborted due to pool reset or Vault lock')); - return; - } - const cfg: ConnectConfig = { username: server.username, keepaliveInterval: settings.sshKeepaliveMs, diff --git a/src/server/ssh/sudo.ts b/src/server/ssh/sudo.ts index 2867cf8..2f8ebee 100644 --- a/src/server/ssh/sudo.ts +++ b/src/server/ssh/sudo.ts @@ -1,5 +1,3 @@ -export const SUDO_PTY_PROMPT = '[gcoord-sudo-prompt] '; - export function posixSingleQuote(value: string): string { return `'${value.replace(/'/g, "'\\''")}'`; } @@ -18,31 +16,13 @@ export function buildEnvPrefix(env?: Record): string { export function prepareSudoExecution( command: string, - options: { - sudoPassword?: string; - stdin?: Buffer | string; - ptyPrompt?: boolean; - } = {}, -): { command: string; stdin?: Buffer; ptyPassword?: string } { + options: { sudoPassword?: string; stdin?: Buffer | string } = {}, +): { command: string; stdin?: Buffer } { const quoted = posixSingleQuote(command); if (options.sudoPassword !== undefined && options.sudoPassword.length > 0) { - if (options.ptyPrompt) { - const extraStdin = - options.stdin === undefined - ? undefined - : typeof options.stdin === 'string' - ? Buffer.from(options.stdin, 'utf8') - : Buffer.from(options.stdin); - return { - command: `sudo -S -k -p ${posixSingleQuote(SUDO_PTY_PROMPT)} sh -c ${quoted}`, - stdin: extraStdin, - ptyPassword: options.sudoPassword, - }; - } - const pwPrefix = Buffer.from(`${options.sudoPassword}\n`, 'utf8'); let combined = pwPrefix; - if (options.stdin !== undefined && options.stdin.length > 0) { + if (options.stdin !== undefined) { const extra = typeof options.stdin === 'string' ? Buffer.from(options.stdin, 'utf8') @@ -51,7 +31,7 @@ export function prepareSudoExecution( pwPrefix.fill(0); } return { - command: `sudo -S -k -p '' sh -c ${quoted}`, + command: `sudo -S -p '' sh -c ${quoted}`, stdin: combined, }; } diff --git a/src/server/ssh/tunnel-manager.ts b/src/server/ssh/tunnel-manager.ts index dea4a30..7da4a9c 100644 --- a/src/server/ssh/tunnel-manager.ts +++ b/src/server/ssh/tunnel-manager.ts @@ -1,36 +1,15 @@ -import crypto from 'node:crypto'; import http, { type IncomingMessage } from 'node:http'; import net, { type Socket } from 'node:net'; import type { Duplex } from 'node:stream'; -import tls from 'node:tls'; import type { Request, Response } from 'express'; import type { Client, TcpConnectionDetails } from 'ssh2'; import type { ServerTunnel } from '../../shared/schemas/server.schema.js'; import type { ConfigManager } from '../config/config-manager.js'; -import type { RuntimeLimits } from '../config/runtime-limits.js'; -import { SESSION_COOKIE_NAME, sha256Hex, type AuthService } from '../security/auth.js'; -import { - assertEgressHostAllowed, - resolveAllowedEgressIps, -} from '../security/egress-guard.js'; +import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js'; import { extractCookies } from '../security/guards.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from './ssh-pool.js'; -export const PROXY_SESSION_COOKIE_NAME = 'gcoord_proxy_sid'; - -export class ProxyIsolationError extends Error { - readonly code = 'PROXY_ISOLATION_NOT_CONFIGURED'; -} - -export interface TunnelManagerOptions { - getRuntimeLimits?: () => RuntimeLimits; - allowLanTunnels?: boolean; - proxyBaseDomain?: string; - proxyPort?: number; - trustCloudflare?: boolean; -} - export interface TunnelRuntimeInfo { key: string; serverId: string; @@ -40,7 +19,6 @@ export interface TunnelRuntimeInfo { localBoundPort?: number; remoteBoundPort?: number; proxyPath?: string; - expiresAt?: number; activeConnections: number; totalConnections: number; bytesIn: number; @@ -56,45 +34,21 @@ interface ActiveTunnelHandle { localBoundHost?: string; localBoundPort?: number; remoteBoundPort?: number; - httpProxyActive?: boolean; activeConnections: number; totalConnections: number; bytesIn: number; bytesOut: number; startedAt: number; - expiresAt?: number; lastError?: string; tcpServer?: net.Server; remoteClient?: Client; - remoteReconnectTimer?: NodeJS.Timeout; - ttlTimer?: NodeJS.Timeout; sockets: Set; - manuallyStopped?: boolean; -} - -interface PendingProxyTicket { - tunnelKey: string; - proxyId: string; - sessionIdHash: string; - expiresAt: number; -} - -interface IsolatedProxySession { - tunnelKey: string; - proxyId: string; - sessionIdHash: string; - expiresAt: number; } function makeTunnelKey(serverId: string, tunnelId: string): string { return `${serverId}--${tunnelId}`; } -function isLoopbackHost(host: string): boolean { - const clean = host.trim().toLowerCase().replace(/^\[|\]$/g, ''); - return clean === '127.0.0.1' || clean === '::1' || clean === 'localhost'; -} - function stripHubCookies(cookieHeader: string | string[] | undefined): string | undefined { if (!cookieHeader) return undefined; const raw = Array.isArray(cookieHeader) ? cookieHeader.join('; ') : cookieHeader; @@ -103,186 +57,24 @@ function stripHubCookies(cookieHeader: string | string[] | undefined): string | .map((part) => part.trim()) .filter((part) => { const name = part.split('=')[0]?.trim(); - return ( - name && - name !== SESSION_COOKIE_NAME && - name !== 'gcoord_csrf' && - name !== PROXY_SESSION_COOKIE_NAME - ); + return name && name !== SESSION_COOKIE_NAME && name !== 'gcoord_csrf'; }); return kept.length > 0 ? kept.join('; ') : undefined; } -function sanitizeOutgoingProxyHeaders( - rawHeaders: IncomingMessage['headers'], - targetHost: string, - targetPort: number, - extra: Record = {}, -): http.OutgoingHttpHeaders { - const headers: http.OutgoingHttpHeaders = {}; - for (const [hKey, hVal] of Object.entries(rawHeaders)) { - if (hVal === undefined) continue; - const lower = hKey.toLowerCase(); - if ( - lower === 'connection' || - lower === 'keep-alive' || - lower === 'transfer-encoding' || - lower === 'upgrade' || - lower === 'host' || - lower === 'proxy-connection' || - lower === 'proxy-authorization' || - lower === 'proxy-authenticate' || - lower === 'te' || - lower === 'trailers' - ) { - continue; - } - if (lower === 'cookie') { - const filtered = stripHubCookies(hVal); - if (filtered) headers.cookie = filtered; - continue; - } - headers[hKey] = hVal; - } - headers.host = `${targetHost}:${targetPort}`; - for (const [k, v] of Object.entries(extra)) { - headers[k] = v; - } - return headers; -} - -function rewriteSetCookieHeaders( - rawSetCookie: string | string[] | undefined, - baseMountPath: string, -): string[] | undefined { - if (!rawSetCookie) return undefined; - const list = Array.isArray(rawSetCookie) ? rawSetCookie : [rawSetCookie]; - const scopedPath = baseMountPath ? `${baseMountPath}/` : '/'; - return list.map((line) => { - const parts = line - .split(';') - .map((p) => p.trim()) - .filter((p) => !/^domain=/i.test(p) && !/^path=/i.test(p)); - parts.push(`Path=${scopedPath}`); - return parts.join('; '); - }); -} - -function rewriteRedirectLocation( - loc: string, - baseMountPath: string, - tunnel: ServerTunnel, -): string { - if (!baseMountPath) { - const originHttp = `http://${tunnel.targetHost}:${tunnel.targetPort}`; - const originHttps = `https://${tunnel.targetHost}:${tunnel.targetPort}`; - if (loc.startsWith(originHttp)) return loc.slice(originHttp.length) || '/'; - if (loc.startsWith(originHttps)) return loc.slice(originHttps.length) || '/'; - return loc; - } - if (loc.startsWith('/') && !loc.startsWith('//')) { - if (loc === baseMountPath || loc.startsWith(`${baseMountPath}/`)) { - return loc; - } - return `${baseMountPath}${loc}`; - } - const targetOrigin = `${tunnel.targetProtocol ?? 'http'}://${tunnel.targetHost}:${tunnel.targetPort}`; - if (loc.startsWith(targetOrigin)) { - const rest = loc.slice(targetOrigin.length) || '/'; - return `${baseMountPath}${rest.startsWith('/') ? rest : `/${rest}`}`; - } - return loc; -} - -export function extractSubdomainTunnel( - hostHeader: string | undefined, - proxyBaseDomain: string | undefined, -): string | null { - if (!hostHeader || !proxyBaseDomain) return null; - const base = proxyBaseDomain.trim().toLowerCase().replace(/^\./, ''); - if (!base) return null; - const hostOnly = hostHeader.trim().toLowerCase().split(':')[0] ?? ''; - const suffix = `.${base}`; - if (!hostOnly.endsWith(suffix)) return null; - const sub = hostOnly.slice(0, -suffix.length); - if (!sub || sub.includes('.') || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(sub)) { - return null; - } - return sub; -} - export class TunnelManager { private readonly active = new Map(); private readonly remoteDispatch = new WeakMap< Client, Map Duplex, reject: () => void) => void> >(); - private readonly pendingTickets = new Map(); - private readonly proxySessions = new Map(); - private proxyHttpServer: http.Server | null = null; - private boundProxyPort: number | undefined; - private readonly getRuntimeLimits?: () => RuntimeLimits; - private readonly allowLanTunnels: boolean; - private readonly proxyBaseDomain?: string; - private readonly configuredProxyPort?: number; - private readonly trustCloudflare: boolean; constructor( private readonly sshPool: SSHPool, private readonly configManager: ConfigManager, private readonly vaultService: VaultService, private readonly authService: AuthService, - options: TunnelManagerOptions = {}, - ) { - this.getRuntimeLimits = options.getRuntimeLimits; - this.allowLanTunnels = Boolean(options.allowLanTunnels); - this.proxyBaseDomain = options.proxyBaseDomain?.trim().toLowerCase() || undefined; - this.configuredProxyPort = options.proxyPort; - this.trustCloudflare = Boolean(options.trustCloudflare); - } - - get actualProxyPort(): number | undefined { - return this.boundProxyPort; - } - - get baseDomain(): string | undefined { - return this.proxyBaseDomain; - } - - async startProxyServer(): Promise { - if (this.configuredProxyPort === undefined) return undefined; - if (this.proxyHttpServer) return this.boundProxyPort; - - const srv = http.createServer((req, res) => { - this.handleDedicatedProxyPortHttp(req, res); - }); - srv.on('upgrade', (req, socket, head) => { - this.handleDedicatedProxyPortWs(req, socket, head); - }); - - const bindHost = this.allowLanTunnels ? '0.0.0.0' : '127.0.0.1'; - await new Promise((resolve, reject) => { - srv.once('error', reject); - srv.listen(this.configuredProxyPort!, bindHost, () => { - srv.off('error', reject); - resolve(); - }); - }); - - this.proxyHttpServer = srv; - const addr = srv.address(); - this.boundProxyPort = - typeof addr === 'object' && addr ? addr.port : this.configuredProxyPort; - return this.boundProxyPort; - } - - async stopProxyServer(): Promise { - if (!this.proxyHttpServer) return; - const srv = this.proxyHttpServer; - this.proxyHttpServer = null; - this.boundProxyPort = undefined; - await new Promise((resolve) => srv.close(() => resolve())); - } + ) {} listTunnels(): TunnelRuntimeInfo[] { const out: TunnelRuntimeInfo[] = []; @@ -342,14 +134,13 @@ export class TunnelManager { if (tunnel.mode === 'remote-tcp') { return this.startRemoteTunnel(serverId, tunnel); } - return this.startLocalOrHttpTunnel(serverId, tunnel); + return this.startLocalListenerTunnel(serverId, tunnel); } async stopTunnel(serverId: string, tunnelId: string): Promise { const key = makeTunnelKey(serverId, tunnelId); const handle = this.active.get(key); if (!handle) return false; - handle.manuallyStopped = true; this.active.delete(key); await this.teardownHandle(handle); return true; @@ -358,7 +149,6 @@ export class TunnelManager { stopServerTunnels(serverId: string): void { for (const [key, handle] of this.active.entries()) { if (handle.serverId === serverId) { - handle.manuallyStopped = true; this.active.delete(key); void this.teardownHandle(handle); } @@ -367,22 +157,19 @@ export class TunnelManager { stopAll(): void { for (const [key, handle] of this.active.entries()) { - handle.manuallyStopped = true; this.active.delete(key); void this.teardownHandle(handle); } - this.pendingTickets.clear(); - this.proxySessions.clear(); } resolveProxyTarget(idOrKey: string): TunnelRuntimeInfo | undefined { const direct = this.active.get(idOrKey); - if (direct && direct.tunnel.mode === 'http-proxy' && direct.httpProxyActive) { + if (direct && direct.tunnel.mode === 'http-proxy' && direct.localBoundPort) { return this.toRuntimeInfo(direct.serverId, direct.tunnel, direct); } const matches = [...this.active.values()].filter( - (h) => h.tunnel.mode === 'http-proxy' && h.httpProxyActive && h.tunnel.id === idOrKey, + (h) => h.tunnel.mode === 'http-proxy' && h.localBoundPort && h.tunnel.id === idOrKey, ); if (matches.length === 1) { const m = matches[0]!; @@ -391,311 +178,9 @@ export class TunnelManager { return undefined; } - issueProxyTicket( - sessionIdHash: string, - serverId: string, - tunnelId: string, - reqMeta: { host?: string; protocol?: string }, - ): { - ticket?: string; - launchUrl: string; - mode: 'subdomain' | 'port' | 'same-origin'; - expiresInSec: number; - } { - const key = makeTunnelKey(serverId, tunnelId); - const live = this.active.get(key); - if (!live || live.tunnel.mode !== 'http-proxy' || !live.httpProxyActive) { - throw new Error(`HTTP proxy tunnel "${tunnelId}" on "${serverId}" is not active`); - } - - this.sweepProxyAuthState(); - const proxyId = this.computeProxyId(serverId, live.tunnel); - const proto = reqMeta.protocol === 'https' || this.trustCloudflare ? 'https' : 'http'; - const rawHostOnly = (reqMeta.host ?? '127.0.0.1').split(':')[0]?.trim() || '127.0.0.1'; - - if (this.proxyBaseDomain) { - const ticket = crypto.randomBytes(24).toString('base64url'); - this.pendingTickets.set(sha256Hex(ticket), { - tunnelKey: key, - proxyId, - sessionIdHash, - expiresAt: Date.now() + 30_000, - }); - return { - ticket, - launchUrl: `${proto}://${proxyId}.${this.proxyBaseDomain}/__gcoord_ticket?ticket=${encodeURIComponent(ticket)}`, - mode: 'subdomain', - expiresInSec: 30, - }; - } - - if (this.boundProxyPort !== undefined) { - const ticket = crypto.randomBytes(24).toString('base64url'); - this.pendingTickets.set(sha256Hex(ticket), { - tunnelKey: key, - proxyId, - sessionIdHash, - expiresAt: Date.now() + 30_000, - }); - return { - ticket, - launchUrl: `http://${rawHostOnly}:${this.boundProxyPort}/__gcoord_ticket?ticket=${encodeURIComponent(ticket)}`, - mode: 'port', - expiresInSec: 30, - }; - } - - if (this.configManager.getSettings().security.allowSameOriginProxy) { - return { - launchUrl: `/proxy/${encodeURIComponent(proxyId)}/`, - mode: 'same-origin', - expiresInSec: 0, - }; - } - - throw new ProxyIsolationError( - 'Same-origin /proxy is disabled. Configure GCOORD_PROXY_BASE_DOMAIN or GCOORD_PROXY_PORT, or explicitly enable security.allowSameOriginProxy.', - ); - } - - private redeemTicket( - ticket: string, - expectedProxyId?: string, - ): { proxySid: string; redirectPath: string } | null { - this.sweepProxyAuthState(); - if (!ticket) return null; - const hash = sha256Hex(ticket); - const entry = this.pendingTickets.get(hash); - if (!entry) return null; - this.pendingTickets.delete(hash); - if (entry.expiresAt <= Date.now()) return null; - if (expectedProxyId && entry.proxyId !== expectedProxyId) return null; - if (!this.authService.getSessionByHash(entry.sessionIdHash)) return null; - - const proxySid = crypto.randomBytes(32).toString('base64url'); - this.proxySessions.set(sha256Hex(proxySid), { - tunnelKey: entry.tunnelKey, - proxyId: entry.proxyId, - sessionIdHash: entry.sessionIdHash, - expiresAt: Date.now() + 12 * 60 * 60 * 1000, - }); - return { - proxySid, - redirectPath: expectedProxyId ? '/' : `/proxy/${encodeURIComponent(entry.proxyId)}/`, - }; - } - - private resolveIsolatedSession( - req: IncomingMessage, - expectedProxyIdOrKey: string, - ): { safeMode: boolean; target: TunnelRuntimeInfo; live: ActiveTunnelHandle } | { errorStatus: number; code: string } { - this.sweepProxyAuthState(); - const cookies = extractCookies(req.headers.cookie); - const proxySid = cookies[PROXY_SESSION_COOKIE_NAME]; - if (!proxySid) { - return { errorStatus: 401, code: 'PROXY_AUTH_REQUIRED' }; - } - const sess = this.proxySessions.get(sha256Hex(proxySid)); - if (!sess || sess.expiresAt <= Date.now()) { - this.proxySessions.delete(sha256Hex(proxySid)); - return { errorStatus: 401, code: 'PROXY_SESSION_EXPIRED' }; - } - const authSess = this.authService.getSessionByHash(sess.sessionIdHash); - if (!authSess) { - this.proxySessions.delete(sha256Hex(proxySid)); - return { errorStatus: 401, code: 'HUB_SESSION_REVOKED' }; - } - const target = this.resolveProxyTarget(expectedProxyIdOrKey); - const live = target ? this.active.get(target.key) : undefined; - if (!target || !live || target.key !== sess.tunnelKey) { - return { errorStatus: 403, code: 'PROXY_TUNNEL_SCOPE_MISMATCH' }; - } - return { safeMode: authSess.safeMode, target, live }; - } - - private sweepProxyAuthState(): void { - const now = Date.now(); - for (const [k, v] of this.pendingTickets.entries()) { - if (v.expiresAt <= now) this.pendingTickets.delete(k); - } - if (this.pendingTickets.size > 500) { - for (const k of [...this.pendingTickets.keys()].slice(0, this.pendingTickets.size - 500)) { - this.pendingTickets.delete(k); - } - } - for (const [k, v] of this.proxySessions.entries()) { - if (v.expiresAt <= now) this.proxySessions.delete(k); - } - } - - private handleDedicatedProxyPortHttp(req: IncomingMessage, res: Response | http.ServerResponse): void { - res.setHeader('X-Content-Type-Options', 'nosniff'); - res.setHeader('Referrer-Policy', 'no-referrer'); - const urlObj = new URL(req.url ?? '/', 'http://127.0.0.1'); - - if (urlObj.pathname === '/__gcoord_ticket' && req.method === 'GET') { - const redeemed = this.redeemTicket(urlObj.searchParams.get('ticket') ?? ''); - if (!redeemed) { - res.writeHead(401, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); - res.end(JSON.stringify({ error: 'INVALID_OR_EXPIRED_TICKET' })); - return; - } - res.writeHead(302, { - Location: redeemed.redirectPath, - 'Cache-Control': 'no-store', - 'Set-Cookie': `${PROXY_SESSION_COOKIE_NAME}=${redeemed.proxySid}; HttpOnly; SameSite=Lax; Path=/`, - }); - res.end(); - return; - } - - const match = /^\/proxy\/([^/]+)(\/.*)?$/.exec(urlObj.pathname); - if (!match) { - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'NOT_FOUND' })); - return; - } - - const idOrKey = decodeURIComponent(match[1]!); - const authRes = this.resolveIsolatedSession(req, idOrKey); - if ('errorStatus' in authRes) { - res.writeHead(authRes.errorStatus, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); - res.end(JSON.stringify({ error: authRes.code })); - return; - } - - const method = (req.method ?? 'GET').toUpperCase(); - if (authRes.safeMode && method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') { - res.writeHead(423, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'SAFE_MODE_ACTIVE' })); - return; - } - - const subPath = `${match[2] || '/'}${urlObj.search}`; - void this.forwardHttpStream(req, res, authRes.target, authRes.live, subPath, `/proxy/${idOrKey}`); - } - - private handleDedicatedProxyPortWs(req: IncomingMessage, socket: Duplex, head: Buffer): void { - const urlObj = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`); - const origin = req.headers.origin; - const host = req.headers.host; - if (origin) { - try { - const u = new URL(origin); - if (!host || u.host !== host || (u.protocol !== 'http:' && u.protocol !== 'https:')) { - socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); - socket.destroy(); - return; - } - } catch { - socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); - socket.destroy(); - return; - } - } - - const match = /^\/proxy\/([^/]+)(\/.*)?$/.exec(urlObj.pathname); - if (!match) { - socket.write('HTTP/1.1 404 Not Found\r\n\r\n'); - socket.destroy(); - return; - } - const idOrKey = decodeURIComponent(match[1]!); - const authRes = this.resolveIsolatedSession(req, idOrKey); - if ('errorStatus' in authRes) { - socket.write(`HTTP/1.1 ${authRes.errorStatus} Unauthorized\r\n\r\n`); - socket.destroy(); - return; - } - if (authRes.safeMode) { - socket.write('HTTP/1.1 423 Locked\r\n\r\n'); - socket.destroy(); - return; - } - const subPath = `${match[2] || '/'}${urlObj.search}`; - void this.forwardWsStream(req, socket, head, authRes.target, authRes.live, subPath); - } - - handleSubdomainProxyHttp(req: Request, res: Response, tunnelSub: string): void { - res.setHeader('X-Content-Type-Options', 'nosniff'); - res.setHeader('Referrer-Policy', 'no-referrer'); - const urlObj = new URL(req.originalUrl, 'http://localhost'); - - if (urlObj.pathname === '/__gcoord_ticket' && req.method === 'GET') { - const redeemed = this.redeemTicket(urlObj.searchParams.get('ticket') ?? '', tunnelSub); - if (!redeemed) { - res.status(401).json({ error: 'INVALID_OR_EXPIRED_TICKET' }); - return; - } - const secure = Boolean(this.trustCloudflare || req.secure); - res.cookie(PROXY_SESSION_COOKIE_NAME, redeemed.proxySid, { - httpOnly: true, - sameSite: 'lax', - secure, - path: '/', - }); - res.redirect(302, '/'); - return; - } - - const authRes = this.resolveIsolatedSession(req, tunnelSub); - if ('errorStatus' in authRes) { - res.status(authRes.errorStatus).json({ error: authRes.code }); - return; - } - - const method = req.method.toUpperCase(); - if (authRes.safeMode && method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') { - res.status(423).json({ error: 'SAFE_MODE_ACTIVE' }); - return; - } - - void this.forwardHttpStream(req, res, authRes.target, authRes.live, req.originalUrl, ''); - } - - handleSubdomainProxyWs(req: IncomingMessage, socket: Duplex, head: Buffer, tunnelSub: string): void { - const origin = req.headers.origin; - const host = req.headers.host; - if (origin) { - try { - const u = new URL(origin); - if (!host || u.host !== host || (u.protocol !== 'http:' && u.protocol !== 'https:')) { - socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); - socket.destroy(); - return; - } - } catch { - socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); - socket.destroy(); - return; - } - } - const authRes = this.resolveIsolatedSession(req, tunnelSub); - if ('errorStatus' in authRes) { - socket.write(`HTTP/1.1 ${authRes.errorStatus} Unauthorized\r\n\r\n`); - socket.destroy(); - return; - } - if (authRes.safeMode) { - socket.write('HTTP/1.1 423 Locked\r\n\r\n'); - socket.destroy(); - return; - } - void this.forwardWsStream(req, socket, head, authRes.target, authRes.live, req.url ?? '/'); - } - handleHttpProxy(req: Request, res: Response, idOrKey: string, subPath: string): void { - if (!this.configManager.getSettings().security.allowSameOriginProxy) { - res.status(403).json({ - error: 'PROXY_ORIGIN_ISOLATION_REQUIRED', - message: 'Same-origin /proxy is disabled by default; launch via /proxy-ticket or enable security.allowSameOriginProxy.', - }); - return; - } - const target = this.resolveProxyTarget(idOrKey); - const live = target ? this.active.get(target.key) : undefined; - if (!target || !live || !live.httpProxyActive) { + if (!target || !target.localBoundPort) { res.status(502).json({ error: 'TUNNEL_NOT_ACTIVE', message: `HTTP proxy tunnel "${idOrKey}" is not active`, @@ -703,8 +188,64 @@ export class TunnelManager { return; } - const cleanSub = subPath.startsWith('/') ? subPath : `/${subPath}`; - void this.forwardHttpStream(req, res, target, live, cleanSub, `/proxy/${idOrKey}`); + const live = this.active.get(target.key); + const qsIndex = req.originalUrl.indexOf('?'); + const qs = qsIndex >= 0 ? req.originalUrl.slice(qsIndex) : ''; + const upstreamPath = `${subPath.startsWith('/') ? subPath : `/${subPath}`}${qs}`; + + const headers: http.OutgoingHttpHeaders = {}; + for (const [hKey, hVal] of Object.entries(req.headers)) { + if (hVal === undefined) continue; + const lower = hKey.toLowerCase(); + if ( + lower === 'connection' || + lower === 'keep-alive' || + lower === 'transfer-encoding' || + lower === 'upgrade' || + lower === 'host' + ) { + continue; + } + if (lower === 'cookie') { + const filtered = stripHubCookies(hVal); + if (filtered) headers.cookie = filtered; + continue; + } + headers[hKey] = hVal; + } + headers.host = `${target.tunnel.targetHost}:${target.tunnel.targetPort}`; + headers['x-forwarded-host'] = req.headers.host ?? ''; + headers['x-forwarded-proto'] = req.protocol; + headers['x-forwarded-prefix'] = `/proxy/${idOrKey}`; + + const proxyReq = http.request( + { + host: '127.0.0.1', + port: target.localBoundPort, + method: req.method, + path: upstreamPath, + headers, + }, + (proxyRes) => { + const resHeaders: http.OutgoingHttpHeaders = { ...proxyRes.headers }; + if (typeof resHeaders.location === 'string' && resHeaders.location.startsWith('/')) { + resHeaders.location = `/proxy/${idOrKey}${resHeaders.location}`; + } + res.writeHead(proxyRes.statusCode ?? 502, resHeaders); + proxyRes.pipe(res); + }, + ); + + proxyReq.on('error', (err) => { + if (live) live.lastError = err.message; + if (!res.headersSent) { + res.status(502).json({ error: 'UPSTREAM_PROXY_ERROR', message: err.message }); + } else { + res.end(); + } + }); + + req.pipe(proxyReq); } handleWsProxyUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void { @@ -719,14 +260,9 @@ export class TunnelManager { const origin = req.headers.origin; const host = req.headers.host; - if (origin) { + if (origin && host) { try { - const originUrl = new URL(origin); - if ( - !host || - originUrl.host !== host || - (originUrl.protocol !== 'http:' && originUrl.protocol !== 'https:') - ) { + if (new URL(origin).host !== host) { socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); socket.destroy(); return; @@ -746,337 +282,69 @@ export class TunnelManager { return; } - if (!this.configManager.getSettings().security.allowSameOriginProxy) { - socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); - socket.destroy(); - return; - } - - if (session.safeMode) { - socket.write('HTTP/1.1 423 Locked\r\n\r\n'); - socket.destroy(); - return; - } - const idOrKey = decodeURIComponent(match[1]!); - const subPath = `${match[2] || '/'}${parsedUrl.search}`; + const subPath = match[2] || '/'; const target = this.resolveProxyTarget(idOrKey); const live = target ? this.active.get(target.key) : undefined; - if (!target || !live || !live.httpProxyActive) { + if (!target || !live || !target.localBoundPort) { socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.destroy(); return; } - void this.forwardWsStream(req, socket, head, target, live, subPath); - } - - private getGlobalActiveConnections(): number { - let total = 0; - for (const h of this.active.values()) total += h.activeConnections; - return total; - } - - private canAcceptSocket(handle: ActiveTunnelHandle): boolean { - const limits = this.getRuntimeLimits?.(); - const perTunnel = limits?.maxTunnelSocketsPerTunnel ?? 64; - const globalMax = limits?.maxGlobalTunnelSockets ?? 256; - return ( - handle.activeConnections < perTunnel && - this.getGlobalActiveConnections() < globalMax - ); - } - - private async forwardHttpStream( - req: IncomingMessage, - res: Response | http.ServerResponse, - target: TunnelRuntimeInfo, - live: ActiveTunnelHandle, - upstreamPath: string, - baseMountPath: string, - ): Promise { - if (!this.canAcceptSocket(live)) { - res.writeHead(503, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'TUNNEL_SOCKET_LIMIT_REACHED' })); - return; - } - - let sshStream: Duplex; - try { - sshStream = await this.sshPool.forwardOutStream( - live.serverId, - target.tunnel.targetHost, - target.tunnel.targetPort, - ); - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - live.lastError = msg; - if (!res.headersSent) { - res.writeHead(502, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'UPSTREAM_PROXY_ERROR', message: msg })); + const upstreamPath = `${subPath}${parsedUrl.search}`; + const upstream = net.connect(target.localBoundPort, '127.0.0.1', () => { + const headerLines: string[] = [ + `${req.method ?? 'GET'} ${upstreamPath} HTTP/1.1`, + `Host: ${target.tunnel.targetHost}:${target.tunnel.targetPort}`, + ]; + for (const [k, v] of Object.entries(req.headers)) { + if (v === undefined) continue; + const lower = k.toLowerCase(); + if (lower === 'host') continue; + if (lower === 'cookie') { + const filtered = stripHubCookies(v); + if (filtered) headerLines.push(`Cookie: ${filtered}`); + continue; + } + const vals = Array.isArray(v) ? v : [v]; + for (const item of vals) { + headerLines.push(`${k}: ${item}`); + } } - return; - } + upstream.write(`${headerLines.join('\r\n')}\r\n\r\n`); + if (head.length > 0) upstream.write(head); - live.activeConnections += 1; - live.totalConnections += 1; - live.sockets.add(sshStream); - - let decremented = false; - const markClosed = () => { - live.sockets.delete(sshStream); - if (!decremented) { - decremented = true; - live.activeConnections = Math.max(0, live.activeConnections - 1); - } - }; - sshStream.once('close', markClosed); - // Prevent unhandled 'error' events if raw SSH channel errors during TLS wrap or teardown. - sshStream.on('error', () => undefined); - - const headers = sanitizeOutgoingProxyHeaders( - req.headers, - target.tunnel.targetHost, - target.tunnel.targetPort, - { - 'x-forwarded-host': String(req.headers.host ?? ''), - 'x-forwarded-proto': this.trustCloudflare ? 'https' : 'http', - ...(baseMountPath ? { 'x-forwarded-prefix': baseMountPath } : {}), - }, - ); - - const useHttps = target.tunnel.targetProtocol === 'https'; - const serverName = - target.tunnel.tlsServerName || - (!net.isIP(target.tunnel.targetHost) ? target.tunnel.targetHost : undefined); - - const createConnection = (): Duplex => { - if (!useHttps) return sshStream; - const tlsSock = tls.connect({ - socket: sshStream, - servername: serverName, - rejectUnauthorized: target.tunnel.tlsRejectUnauthorized ?? true, - }); - live.sockets.add(tlsSock); - tlsSock.once('close', () => live.sockets.delete(tlsSock)); - return tlsSock; - }; - - const agent = new http.Agent({ keepAlive: false }); - (agent as unknown as { createConnection: () => Duplex }).createConnection = createConnection; - - const reqOpts: http.RequestOptions = { - method: req.method, - path: upstreamPath.startsWith('/') ? upstreamPath : `/${upstreamPath}`, - headers, - agent, - }; - - const proxyReq = http.request(reqOpts, (proxyRes) => { - const resHeaders: http.OutgoingHttpHeaders = { ...proxyRes.headers }; - delete resHeaders['proxy-authenticate']; - delete resHeaders['proxy-connection']; - if (typeof resHeaders.location === 'string') { - resHeaders.location = rewriteRedirectLocation( - resHeaders.location, - baseMountPath, - target.tunnel, - ); - } - const rewrittenCookies = rewriteSetCookieHeaders(resHeaders['set-cookie'], baseMountPath); - if (rewrittenCookies) { - resHeaders['set-cookie'] = rewrittenCookies; - } - - res.writeHead(proxyRes.statusCode ?? 502, resHeaders); - proxyRes.on('data', (chunk: Buffer) => { - live.bytesIn += chunk.length; - }); - proxyRes.pipe(res); + live.sockets.add(socket); + live.sockets.add(upstream); + socket.pipe(upstream); + upstream.pipe(socket); }); - req.on('data', (chunk: Buffer) => { - live.bytesOut += chunk.length; - }); - - proxyReq.on('error', (err) => { - live.lastError = err.message; - markClosed(); - if (!res.headersSent) { - res.writeHead(502, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: 'UPSTREAM_PROXY_ERROR', message: err.message })); - } else { - res.end(); - } - }); - - res.once('close', () => { - if (!res.writableEnded) { - proxyReq.destroy(); - sshStream.destroy(); - } - }); - - req.pipe(proxyReq); - } - - private async forwardWsStream( - req: IncomingMessage, - socket: Duplex, - head: Buffer, - target: TunnelRuntimeInfo, - live: ActiveTunnelHandle, - upstreamPath: string, - ): Promise { - if (!this.canAcceptSocket(live)) { - socket.write('HTTP/1.1 503 Service Unavailable\r\n\r\n'); - socket.destroy(); - return; - } - - let sshStream: Duplex; - try { - sshStream = await this.sshPool.forwardOutStream( - live.serverId, - target.tunnel.targetHost, - target.tunnel.targetPort, - ); - } catch (err) { - live.lastError = err instanceof Error ? err.message : String(err); - socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); - socket.destroy(); - return; - } - - let upstream: Duplex = sshStream; - if (target.tunnel.targetProtocol === 'https') { - const serverName = - target.tunnel.tlsServerName || - (!net.isIP(target.tunnel.targetHost) ? target.tunnel.targetHost : undefined); - try { - upstream = await new Promise((resolve, reject) => { - const tSock = tls.connect( - { - socket: sshStream, - servername: serverName, - rejectUnauthorized: target.tunnel.tlsRejectUnauthorized ?? true, - }, - () => resolve(tSock), - ); - tSock.once('error', reject); - }); - } catch (err) { - live.lastError = err instanceof Error ? err.message : String(err); - sshStream.destroy(); - socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); - socket.destroy(); - return; - } - } - - const headerLines: string[] = [ - `${req.method ?? 'GET'} ${upstreamPath} HTTP/1.1`, - `Host: ${target.tunnel.targetHost}:${target.tunnel.targetPort}`, - ]; - for (const [k, v] of Object.entries(req.headers)) { - if (v === undefined) continue; - const lower = k.toLowerCase(); - if ( - lower === 'host' || - lower === 'proxy-authorization' || - lower === 'proxy-connection' - ) { - continue; - } - if (lower === 'cookie') { - const filtered = stripHubCookies(v); - if (filtered) headerLines.push(`Cookie: ${filtered}`); - continue; - } - const vals = Array.isArray(v) ? v : [v]; - for (const item of vals) { - headerLines.push(`${k}: ${item}`); - } - } - - live.activeConnections += 1; - live.totalConnections += 1; - live.sockets.add(socket); - live.sockets.add(upstream); - - let cleaned = false; const cleanup = () => { - if (cleaned) return; - cleaned = true; live.sockets.delete(socket); live.sockets.delete(upstream); socket.destroy(); upstream.destroy(); - if (upstream !== sshStream) sshStream.destroy(); - live.activeConnections = Math.max(0, live.activeConnections - 1); }; - - socket.on('data', (c: Buffer) => { - live.bytesOut += c.length; - }); - upstream.on('data', (c: Buffer) => { - live.bytesIn += c.length; - }); - - upstream.write(`${headerLines.join('\r\n')}\r\n\r\n`); - if (head.length > 0) upstream.write(head); - - socket.pipe(upstream); - upstream.pipe(socket); upstream.on('error', cleanup); upstream.on('close', cleanup); socket.on('error', cleanup); socket.on('close', cleanup); } - private scheduleTtl(handle: ActiveTunnelHandle): void { - if (!handle.tunnel.ttlSec) return; - const ttlMs = handle.tunnel.ttlSec * 1000; - handle.expiresAt = Date.now() + ttlMs; - handle.ttlTimer = setTimeout(() => { - void this.stopTunnel(handle.serverId, handle.tunnel.id); - }, ttlMs); - handle.ttlTimer.unref(); - } - - private async startLocalOrHttpTunnel( + private async startLocalListenerTunnel( serverId: string, tunnel: ServerTunnel, ): Promise { + // Verify SSH reachability upfront so callers get immediate handshake/TOFU/vault feedback await this.sshPool.acquireClient(serverId); + + const bindHost = + tunnel.mode === 'http-proxy' ? '127.0.0.1' : tunnel.bindHost ?? '127.0.0.1'; + const bindPort = tunnel.mode === 'http-proxy' ? 0 : tunnel.bindPort ?? 0; const key = makeTunnelKey(serverId, tunnel.id); - if (tunnel.mode === 'http-proxy') { - const handle: ActiveTunnelHandle = { - key, - serverId, - tunnel, - httpProxyActive: true, - activeConnections: 0, - totalConnections: 0, - bytesIn: 0, - bytesOut: 0, - startedAt: Date.now(), - sockets: new Set(), - }; - this.scheduleTtl(handle); - this.active.set(key, handle); - return this.toRuntimeInfo(serverId, tunnel, handle); - } - - const bindHost = tunnel.bindHost ?? '127.0.0.1'; - if (!this.allowLanTunnels && !isLoopbackHost(bindHost)) { - throw new Error( - `Non-loopback bindHost "${bindHost}" requires GCOORD_ALLOW_LAN_TUNELS=true`, - ); - } - const bindPort = tunnel.bindPort ?? 0; - const handle: ActiveTunnelHandle = { key, serverId, @@ -1091,11 +359,7 @@ export class TunnelManager { }; const tcpServer = net.createServer((clientSocket: Socket) => { - if (tunnel.mode === 'socks5') { - this.bridgeSocks5Socket(handle, clientSocket); - } else { - this.bridgeLocalSocket(handle, clientSocket); - } + this.bridgeLocalSocket(handle, clientSocket); }); handle.tcpServer = tcpServer; @@ -1115,163 +379,11 @@ export class TunnelManager { handle.lastError = err.message; }); - this.scheduleTtl(handle); this.active.set(key, handle); return this.toRuntimeInfo(serverId, tunnel, handle); } - private bridgeSocks5Socket(handle: ActiveTunnelHandle, clientSocket: Socket): void { - if (!this.canAcceptSocket(handle)) { - clientSocket.destroy(); - return; - } - - handle.activeConnections += 1; - handle.totalConnections += 1; - handle.sockets.add(clientSocket); - - let decremented = false; - const closeSocket = () => { - handle.sockets.delete(clientSocket); - clientSocket.destroy(); - if (!decremented) { - decremented = true; - handle.activeConnections = Math.max(0, handle.activeConnections - 1); - } - }; - - let stage: 'greeting' | 'request' | 'connected' = 'greeting'; - let buf = Buffer.alloc(0); - - const sendSocksError = (rep: number) => { - try { - clientSocket.write(Buffer.from([0x05, rep, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); - } catch { - // Ignore write error - } - closeSocket(); - }; - - const onData = (chunk: Buffer) => { - if (stage === 'connected') return; - buf = Buffer.concat([buf, chunk]); - if (buf.length > 1024) { - closeSocket(); - return; - } - - if (stage === 'greeting') { - if (buf.length < 2) return; - const ver = buf[0]!; - const nMethods = buf[1]!; - if (ver !== 0x05) { - closeSocket(); - return; - } - if (buf.length < 2 + nMethods) return; - const methods = buf.subarray(2, 2 + nMethods); - buf = buf.subarray(2 + nMethods); - if (!methods.includes(0x00)) { - clientSocket.write(Buffer.from([0x05, 0xff])); - closeSocket(); - return; - } - clientSocket.write(Buffer.from([0x05, 0x00])); - stage = 'request'; - } - - if (stage === 'request') { - if (buf.length < 4) return; - const ver = buf[0]!; - const cmd = buf[1]!; - const atyp = buf[3]!; - if (ver !== 0x05 || cmd !== 0x01) { - sendSocksError(0x07); - return; - } - - let dstHost = ''; - let offset = 4; - if (atyp === 0x01) { - if (buf.length < offset + 4 + 2) return; - dstHost = `${buf[offset]!}.${buf[offset + 1]!}.${buf[offset + 2]!}.${buf[offset + 3]!}`; - offset += 4; - } else if (atyp === 0x03) { - if (buf.length < offset + 1) return; - const len = buf[offset]!; - offset += 1; - if (buf.length < offset + len + 2) return; - dstHost = buf.subarray(offset, offset + len).toString('utf8'); - offset += len; - } else if (atyp === 0x04) { - if (buf.length < offset + 16 + 2) return; - const parts: string[] = []; - for (let i = 0; i < 16; i += 2) { - parts.push(buf.readUInt16BE(offset + i).toString(16)); - } - dstHost = parts.join(':'); - offset += 16; - } else { - sendSocksError(0x08); - return; - } - - const dstPort = buf.readUInt16BE(offset); - const remaining = buf.subarray(offset + 2); - stage = 'connected'; - clientSocket.off('data', onData); - - this.sshPool - .forwardOutStream(handle.serverId, dstHost, dstPort) - .then((sshStream) => { - if (clientSocket.destroyed || !this.active.has(handle.key)) { - sshStream.destroy(); - closeSocket(); - return; - } - handle.sockets.add(sshStream); - clientSocket.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); - if (remaining.length > 0) { - sshStream.write(remaining); - handle.bytesOut += remaining.length; - } - clientSocket.on('data', (c: Buffer) => { - handle.bytesOut += c.length; - }); - sshStream.on('data', (c: Buffer) => { - handle.bytesIn += c.length; - }); - clientSocket.pipe(sshStream); - sshStream.pipe(clientSocket); - - const cleanup = () => { - handle.sockets.delete(sshStream); - sshStream.destroy(); - closeSocket(); - }; - sshStream.once('close', cleanup); - sshStream.once('error', cleanup); - clientSocket.once('close', cleanup); - clientSocket.once('error', cleanup); - }) - .catch((err) => { - handle.lastError = err instanceof Error ? err.message : String(err); - sendSocksError(0x05); - }); - } - }; - - clientSocket.on('data', onData); - clientSocket.once('error', closeSocket); - clientSocket.once('close', closeSocket); - } - private bridgeLocalSocket(handle: ActiveTunnelHandle, clientSocket: Socket): void { - if (!this.canAcceptSocket(handle)) { - clientSocket.destroy(); - return; - } - handle.activeConnections += 1; handle.totalConnections += 1; handle.sockets.add(clientSocket); @@ -1328,9 +440,6 @@ export class TunnelManager { serverId: string, tunnel: ServerTunnel, ): Promise { - const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; - await assertEgressHostAllowed(tunnel.targetHost, allowedCidrs); - const client = await this.sshPool.acquireClient(serverId); const bindHost = tunnel.bindHost ?? '127.0.0.1'; const bindPort = tunnel.bindPort ?? 0; @@ -1375,92 +484,47 @@ export class TunnelManager { }); handle.remoteBoundPort = actualPort; - portMap.set(actualPort, (_details, accept, reject) => { - if (!this.canAcceptSocket(handle)) { - reject(); - return; - } - + portMap.set(actualPort, (_details, accept, _reject) => { const channel = accept(); handle.activeConnections += 1; handle.totalConnections += 1; handle.sockets.add(channel); + const targetSock = net.connect(tunnel.targetPort, tunnel.targetHost); + handle.sockets.add(targetSock); + let decremented = false; - const cleanupBase = () => { + const cleanup = () => { handle.sockets.delete(channel); + handle.sockets.delete(targetSock); channel.destroy(); + targetSock.destroy(); if (!decremented) { decremented = true; handle.activeConnections = Math.max(0, handle.activeConnections - 1); } }; - const curCidrs = this.configManager.getSettings().security.egressAllowedCidrs; - resolveAllowedEgressIps(tunnel.targetHost, curCidrs) - .then((resolvedIps: string[]) => { - if (!this.active.has(handle.key)) { - cleanupBase(); - return; - } - const targetSock = net.connect(tunnel.targetPort, resolvedIps[0]!); - handle.sockets.add(targetSock); + channel.on('data', (chunk: Buffer) => { + handle.bytesIn += chunk.length; + }); + targetSock.on('data', (chunk: Buffer) => { + handle.bytesOut += chunk.length; + }); - const cleanupAll = () => { - handle.sockets.delete(targetSock); - targetSock.destroy(); - cleanupBase(); - }; - - channel.on('data', (chunk: Buffer) => { - handle.bytesIn += chunk.length; - }); - targetSock.on('data', (chunk: Buffer) => { - handle.bytesOut += chunk.length; - }); - - channel.pipe(targetSock); - targetSock.pipe(channel); - channel.once('close', cleanupAll); - channel.once('error', cleanupAll); - targetSock.once('close', cleanupAll); - targetSock.once('error', cleanupAll); - }) - .catch((err: unknown) => { - handle.lastError = err instanceof Error ? err.message : String(err); - cleanupBase(); - }); + channel.pipe(targetSock); + targetSock.pipe(channel); + channel.once('close', cleanup); + channel.once('error', cleanup); + targetSock.once('close', cleanup); + targetSock.once('error', cleanup); }); - client.once('close', () => { - if (this.active.get(key) === handle && !handle.manuallyStopped) { - this.active.delete(key); - void this.teardownHandle(handle); - if (tunnel.autoStart && this.vaultService.isRuntimeReady) { - const timer = setTimeout(() => { - void this.startTunnel(serverId, tunnel.id).catch(() => undefined); - }, 5_000); - timer.unref(); - handle.remoteReconnectTimer = timer; - } - } - }); - - this.scheduleTtl(handle); this.active.set(key, handle); return this.toRuntimeInfo(serverId, tunnel, handle); } private async teardownHandle(handle: ActiveTunnelHandle): Promise { - if (handle.ttlTimer) { - clearTimeout(handle.ttlTimer); - handle.ttlTimer = undefined; - } - if (handle.remoteReconnectTimer) { - clearTimeout(handle.remoteReconnectTimer); - handle.remoteReconnectTimer = undefined; - } - for (const sock of handle.sockets) { try { sock.destroy(); @@ -1486,22 +550,17 @@ export class TunnelManager { } } - private computeProxyId(serverId: string, tunnel: ServerTunnel): string { - const key = makeTunnelKey(serverId, tunnel.id); - const sameIdCount = this.configManager - .listServers() - .flatMap((s) => s.tunnels) - .filter((t) => t.id === tunnel.id && t.mode === 'http-proxy').length; - return sameIdCount <= 1 ? tunnel.id : key; - } - private toRuntimeInfo( serverId: string, tunnel: ServerTunnel, live?: ActiveTunnelHandle, ): TunnelRuntimeInfo { const key = makeTunnelKey(serverId, tunnel.id); - const proxyId = this.computeProxyId(serverId, tunnel); + const sameIdCount = this.configManager + .listServers() + .flatMap((s) => s.tunnels) + .filter((t) => t.id === tunnel.id && t.mode === 'http-proxy').length; + const proxyId = sameIdCount <= 1 ? tunnel.id : key; return { key, serverId, @@ -1511,10 +570,9 @@ export class TunnelManager { localBoundPort: live?.localBoundPort, remoteBoundPort: live?.remoteBoundPort, proxyPath: - tunnel.mode === 'http-proxy' && live?.httpProxyActive + tunnel.mode === 'http-proxy' && live?.localBoundPort ? `/proxy/${proxyId}/` : undefined, - expiresAt: live?.expiresAt, activeConnections: live?.activeConnections ?? 0, totalConnections: live?.totalConnections ?? 0, bytesIn: live?.bytesIn ?? 0, diff --git a/src/server/systems/parsers.ts b/src/server/systems/parsers.ts index aa9d85e..1f7a4ce 100644 --- a/src/server/systems/parsers.ts +++ b/src/server/systems/parsers.ts @@ -17,7 +17,6 @@ export interface ParsedStatusResult { subItems: ParsedSubItem[]; rawSummary: string; exitCode: number | null; - raw?: Record; } export interface ScannedFolderMatch { @@ -26,11 +25,10 @@ export interface ScannedFolderMatch { } export function globToRegExp(pattern: string): RegExp { - const collapsed = pattern.slice(0, 128).replace(/\*+/g, '*'); - const escaped = collapsed + const escaped = pattern .replace(/[.+^${}()|[\]\\]/g, '\\$&') - .replace(/\*/g, '[^/]*') - .replace(/\?/g, '[^/]'); + .replace(/\*/g, '.*') + .replace(/\?/g, '.'); return new RegExp(`^${escaped}$`); } @@ -316,7 +314,6 @@ export function parseStatusOutput( subItems: [], rawSummary: summarizeRecord(rec), exitCode, - raw: rec, }; } } catch { @@ -330,16 +327,15 @@ export function parseStatusOutput( } if (statusCfg.parser === 'regex') { - const bounded = trimmed.length > 262_144 ? trimmed.slice(0, 262_144) : trimmed; const re = statusCfg.regexPattern ? new RegExp(statusCfg.regexPattern, 'm') : null; - const matched = re ? re.test(bounded) : bounded.length > 0; + const matched = re ? re.test(trimmed) : trimmed.length > 0; const exitOk = statusCfg.health?.healthyExitCodes ? exitCode !== null && statusCfg.health.healthyExitCodes.includes(exitCode) : exitCode === null || exitCode === 0; return { health: exitOk && matched ? 'ok' : 'down', subItems: [], - rawSummary: bounded.split(/\r?\n/).slice(0, 4).join(' | '), + rawSummary: trimmed.split(/\r?\n/).slice(0, 4).join(' | '), exitCode, }; } diff --git a/src/server/systems/systems-engine.ts b/src/server/systems/systems-engine.ts index 3ec5092..b6ff48a 100644 --- a/src/server/systems/systems-engine.ts +++ b/src/server/systems/systems-engine.ts @@ -5,7 +5,6 @@ import type { SystemAction, SystemConfig } from '../../shared/schemas/system.sch import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; import type { WsHub } from '../api/ws-hub.js'; import type { ConfigManager } from '../config/config-manager.js'; -import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { VaultService } from '../security/vault.js'; import type { PTYManager, PtySessionInfo } from '../ssh/pty-manager.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; @@ -65,65 +64,19 @@ interface ActiveStreamJob { bufferBytes: number; done: boolean; abort: () => void; - timeoutTimer?: NodeJS.Timeout; - idleTimer?: NodeJS.Timeout; } +const MAX_STREAM_REPLAY_BYTES = 128 * 1024; const MAX_RETAINED_DONE_STREAMS = 25; -const MAX_DISCOVERED_ITEMS = 500; -const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']); -const SUBITEM_SAFE_RE = /^[A-Za-z0-9._][A-Za-z0-9._:@/-]{0,127}$/; export function isValidRelativeOverlayFile(fileName: string): boolean { const clean = fileName.trim(); - if (!clean || clean.length > 255) return false; - if (FORBIDDEN_KEYS.has(clean)) return false; - if (clean.startsWith('-') || clean.includes('/') || clean.includes('\\') || clean.includes('..')) { - return false; - } - if (/[\x00-\x1f\x7f\s'"$;|&<>()`{}!*?[\]]/.test(clean)) return false; - return /^[A-Za-z0-9._][A-Za-z0-9._+-]*$/.test(clean); -} - -function isValidSubItemName(subItem: string): boolean { - const clean = subItem.trim(); - if (!clean || clean.startsWith('-') || clean.includes('..')) return false; - if (/[\x00-\x1f\x7f]/.test(clean)) return false; - return SUBITEM_SAFE_RE.test(clean); -} - -function isValidAbsolutePath(p: string): boolean { - if (!p.startsWith('/') || p.includes('..')) return false; - if (/[\x00-\x1f\x7f]/.test(p)) return false; + if (!clean) return false; + if (clean.includes('/') || clean.includes('\\') || clean.includes('..')) return false; + if (/[\s'"$;|&<>()`]/.test(clean)) return false; return true; } -function assertSafeKey(key: string, label = 'key'): void { - if (!key || FORBIDDEN_KEYS.has(key) || /[\x00-\x1f\x7f]/.test(key)) { - throw new Error(`Unsafe ${label}: "${key}"`); - } -} - -async function runPool( - items: T[], - concurrency: number, - worker: (item: T) => Promise, -): Promise { - if (items.length === 0) return []; - const cap = Math.max(1, Math.min(items.length, concurrency)); - const results = new Array(items.length); - let cursor = 0; - - const runners = Array.from({ length: cap }, async () => { - while (cursor < items.length) { - const idx = cursor++; - results[idx] = await worker(items[idx]!); - } - }); - await Promise.all(runners); - return results; -} - function expandShellRoot(root: string): string { const trimmed = root.trim(); if (trimmed === '~' || trimmed === '~/') return '"$HOME"'; @@ -132,27 +85,20 @@ function expandShellRoot(root: string): string { } function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: string[]): string { - const safeDepth = Math.max(1, Math.min(5, Math.floor(maxDepth))); const rootArgs = roots.map(expandShellRoot).join(' '); - const casePatterns = - matchFiles - .map((p) => p.replace(/[^A-Za-z0-9._*?-]/g, '')) - .filter((p) => p && !p.startsWith('-')) - .slice(0, 32) - .join('|') || '*'; + const casePatterns = matchFiles + .map((p) => p.replace(/[^A-Za-z0-9._*?[\]-]/g, '')) + .filter(Boolean) + .join('|') || '*'; return [ - `TAB=$(printf '\\t'); CR=$(printf '\\r')`, `for r in ${rootArgs}; do`, - ` case "$r" in -*) r="./$r" ;; esac`, ` [ -d "$r" ] || continue`, - ` find "$r" -maxdepth ${safeDepth} -type d 2>/dev/null | while IFS= read -r d; do`, - ` case "$d" in *"$TAB"*|*"$CR"*) continue ;; esac`, + ` find "$r" -maxdepth ${maxDepth} -type d 2>/dev/null | while IFS= read -r d; do`, ` matched=0`, ` for f in "$d"/* "$d"/.*; do`, ` [ -f "$f" ] || continue`, ` b=\${f##*/}`, - ` [ "$b" = "." ] || [ "$b" = ".." ] && continue`, ` case "$b" in`, ` ${casePatterns}) matched=1; break ;;`, ` esac`, @@ -170,16 +116,6 @@ function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: st ].join('\n'); } -function substituteActionInputs( - command: string, - inputs: Record, -): string { - return command.replace(/\{\{\s*input\.([a-zA-Z0-9._-]+)\s*\}\}/g, (_match, key: string) => { - assertSafeKey(key, 'input name'); - return posixSingleQuote(inputs[key] ?? ''); - }); -} - export class CustomSystemsEngine { private readonly cache = new Map(); private readonly streamJobs = new Map(); @@ -192,7 +128,6 @@ export class CustomSystemsEngine { private readonly vaultService: VaultService, private readonly ptyManager: PTYManager, private readonly wsHub: WsHub, - private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} onHealthSnapshot(listener: (snapshot: ServerSystemSnapshot) => void): () => void { @@ -202,11 +137,6 @@ export class CustomSystemsEngine { }; } - getActionMeta(systemId: string, actionId: string): SystemAction | undefined { - const sys = this.configManager.getSystem(systemId); - return sys?.actions.find((a) => a.id === actionId); - } - getStreamReplayFrames(jobId: string): ServerWsFrame[] { const job = this.streamJobs.get(jobId); return job ? [...job.frames] : []; @@ -269,12 +199,10 @@ export class CustomSystemsEngine { .filter((s) => s.enabled && s.systems.some((a) => a.systemId === systemId)) .filter((s) => !opts.serverId || s.id === opts.serverId); - const concurrency = Math.max( - 1, - this.getRuntimeLimits?.().maxParallelSystemInspect ?? 2, - ); - const snapshots = await runPool(targets, concurrency, (srv) => - this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }), + const snapshots = await Promise.all( + targets.map((srv) => + this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }), + ), ); return { system, snapshots }; @@ -319,7 +247,7 @@ export class CustomSystemsEngine { 'ok', ), }; - this.setCacheBounded(cacheKey, snapshot); + this.cache.set(cacheKey, snapshot); this.emitHealth(snapshot); return snapshot; } catch (err) { @@ -333,68 +261,16 @@ export class CustomSystemsEngine { items: [], systemHealth: 'down', }; - this.emitHealth(snapshot); return snapshot; } } - private resolveActionInputs( - action: SystemAction, - suppliedInputs?: Record, - ): { resolved: Record; secretNames: Set } { - const supplied = suppliedInputs ?? {}; - for (const k of Object.keys(supplied)) { - assertSafeKey(k, 'input parameter'); - } - - const resolved: Record = {}; - const secretNames = new Set(); - for (const def of action.inputs ?? []) { - assertSafeKey(def.name, 'input definition'); - if (def.type === 'secret') secretNames.add(def.name); - - let rawVal = Object.hasOwn(supplied, def.name) ? supplied[def.name] : def.default; - if (rawVal === undefined || rawVal === null || rawVal === '') { - if (def.required) { - throw new Error(`Missing required input "${def.name}" for action "${action.id}"`); - } - continue; - } - - if (def.type === 'number') { - const n = Number(rawVal); - if (!Number.isFinite(n)) { - throw new Error(`Input "${def.name}" must be a finite number`); - } - rawVal = String(n); - } else if (def.type === 'boolean') { - rawVal = rawVal === true || rawVal === 'true' ? 'true' : 'false'; - } else { - const str = String(rawVal); - if (/[\x00]/.test(str)) { - throw new Error(`Input "${def.name}" contains NUL bytes`); - } - if (def.type === 'select' && def.options && def.options.length > 0) { - if (!def.options.includes(str)) { - throw new Error(`Input "${def.name}" value is not in allowed options`); - } - } - rawVal = str; - } - - resolved[def.name] = String(rawVal); - } - - return { resolved, secretNames }; - } - private resolveActionContext(params: { serverId: string; systemId: string; actionId: string; itemName?: string; subItemName?: string; - inputs?: Record; }) { return (async () => { const system = this.configManager.getSystem(params.systemId); @@ -411,13 +287,7 @@ export class CustomSystemsEngine { throw new Error(`Action "${params.actionId}" not found in system "${system.id}"`); } - if (params.itemName) assertSafeKey(params.itemName, 'itemName'); - if (params.subItemName && !isValidSubItemName(params.subItemName)) { - throw new Error(`Invalid subItemName "${params.subItemName}"`); - } - const resolvedParams = this.resolveParams(system, attachment.params); - const { resolved: actionInputs } = this.resolveActionInputs(action, params.inputs); let item: DiscoveredSystemItem | undefined; if (action.scope === 'item' || action.scope === 'subitem') { @@ -429,18 +299,8 @@ export class CustomSystemsEngine { if (!item) { throw new Error(`Item "${params.itemName}" not found under ${server.id}/${system.id}`); } - if (action.scope === 'subitem') { - if (!params.subItemName) { - throw new Error(`Action "${action.id}" requires subItemName`); - } - if ( - item.status.subItems.length > 0 && - !item.status.subItems.some((s) => s.name === params.subItemName) - ) { - throw new Error( - `Sub-item "${params.subItemName}" was not discovered under "${item.name}"`, - ); - } + if (action.scope === 'subitem' && !params.subItemName) { + throw new Error(`Action "${action.id}" requires subItemName`); } } @@ -450,15 +310,13 @@ export class CustomSystemsEngine { resolvedParams, item, params.subItemName, - actionInputs, ); - const substitutedCmd = substituteActionInputs(action.command, actionInputs); const execCmd = item?.dir - ? `cd -- ${posixSingleQuote(item.dir)} && ${substitutedCmd}` - : substitutedCmd; + ? `cd -- ${posixSingleQuote(item.dir)} && ${action.command}` + : action.command; - return { system, server, action, item, env, execCmd, substitutedCmd }; + return { system, server, action, item, env, execCmd }; })(); } @@ -468,7 +326,6 @@ export class CustomSystemsEngine { actionId: string; itemName?: string; subItemName?: string; - inputs?: Record; timeoutMs?: number; signal?: AbortSignal; onChunk?: (stream: 'stdout' | 'stderr', text: string) => void; @@ -487,7 +344,7 @@ export class CustomSystemsEngine { throw new Error('Interactive PTY actions cannot run unattended in workflows'); } - const timeoutMs = params.timeoutMs ?? (action.timeoutSec ?? 300) * 1000; + const timeoutMs = params.timeoutMs ?? 300_000; const started = Date.now(); const handle = await this.sshPool.execStream(server.id, execCmd, { env, @@ -577,18 +434,17 @@ export class CustomSystemsEngine { actionId: string; itemName?: string; subItemName?: string; - inputs?: Record; cols?: number; rows?: number; }): Promise { - const { system, server, action, item, env, execCmd, substitutedCmd } = + const { system, server, action, item, env, execCmd } = await this.resolveActionContext(params); if (action.mode === 'oneshot') { const res = await this.sshPool.exec(server.id, execCmd, { env, sudo: action.sudo, - timeoutMs: (action.timeoutSec ?? 120) * 1000, + timeoutMs: 120_000, }); this.invalidateCache(server.id, system.id); return { @@ -604,7 +460,7 @@ export class CustomSystemsEngine { const session = await this.ptyManager.openSession({ serverId: server.id, cwd: item?.dir, - command: substitutedCmd, + command: action.command, env, sudo: action.sudo, cols: params.cols, @@ -615,14 +471,13 @@ export class CustomSystemsEngine { return { mode: 'interactive', session }; } - // Stream mode with timeout & idle reaper + // Stream mode const jobId = `stream-${crypto.randomBytes(6).toString('hex')}`; const handle = await this.sshPool.execStream(server.id, execCmd, { env, sudo: action.sudo, }); - const maxReplayBytes = this.getRuntimeLimits?.().streamReplayBytes ?? 128 * 1024; const job: ActiveStreamJob = { jobId, serverId: server.id, @@ -634,23 +489,12 @@ export class CustomSystemsEngine { }; this.streamJobs.set(jobId, job); - const clearJobTimers = () => { - if (job.timeoutTimer) { - clearTimeout(job.timeoutTimer); - job.timeoutTimer = undefined; - } - if (job.idleTimer) { - clearTimeout(job.idleTimer); - job.idleTimer = undefined; - } - }; - const pushFrame = (stream: 'stdout' | 'stderr' | 'meta', data: string) => { const frame: ServerWsFrame = { type: 'stream:chunk', jobId, stream, data }; const bytes = Buffer.byteLength(data, 'utf8'); job.frames.push(frame); job.bufferBytes += bytes; - while (job.bufferBytes > maxReplayBytes && job.frames.length > 0) { + while (job.bufferBytes > MAX_STREAM_REPLAY_BYTES && job.frames.length > 0) { const dropped = job.frames.shift()!; if (dropped.type === 'stream:chunk') { job.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8'); @@ -659,28 +503,6 @@ export class CustomSystemsEngine { this.wsHub.broadcastChannel(WS_CHANNELS.stream(jobId), frame); }; - const maxStreamMs = (action.timeoutSec ?? 600) * 1000; - job.timeoutTimer = setTimeout(() => { - if (job.done) return; - pushFrame( - 'meta', - JSON.stringify({ event: 'timeout', message: `Stream exceeded ${maxStreamMs}ms limit` }), - ); - handle.abort(); - }, maxStreamMs); - job.timeoutTimer.unref(); - - const bumpIdleTimer = () => { - if (job.idleTimer) clearTimeout(job.idleTimer); - job.idleTimer = setTimeout(() => { - if (job.done) return; - pushFrame('meta', JSON.stringify({ event: 'timeout', message: 'Stream idle timeout' })); - handle.abort(); - }, Math.min(maxStreamMs, 300_000)); - job.idleTimer.unref(); - }; - bumpIdleTimer(); - pushFrame( 'meta', JSON.stringify({ @@ -694,25 +516,21 @@ export class CustomSystemsEngine { ); handle.channel.on('data', (chunk: Buffer) => { - bumpIdleTimer(); pushFrame('stdout', chunk.toString('utf8')); }); handle.channel.stderr?.on('data', (chunk: Buffer) => { - bumpIdleTimer(); pushFrame('stderr', chunk.toString('utf8')); }); void handle.done .then(({ exitCode, signal }) => { job.done = true; - clearJobTimers(); this.invalidateCache(server.id, system.id); pushFrame('meta', JSON.stringify({ event: 'exit', exitCode, signal })); this.pruneStreamJobs(); }) .catch((err) => { job.done = true; - clearJobTimers(); this.invalidateCache(server.id, system.id); pushFrame( 'meta', @@ -738,11 +556,10 @@ export class CustomSystemsEngine { throw new Error(`Unknown server "${serverId}" or system "${systemId}"`); } - const validatedParams = this.validateAndResolveParamsStrict(system, params); const existing = server.systems.find((a) => a.systemId === systemId); const nextSystems = existing - ? server.systems.map((a) => (a.systemId === systemId ? { ...a, params: validatedParams } : a)) - : [...server.systems, { systemId, params: validatedParams, itemOverrides: {} }]; + ? server.systems.map((a) => (a.systemId === systemId ? { ...a, params } : a)) + : [...server.systems, { systemId, params, itemOverrides: {} }]; const updated: ServerConfig = { ...server, systems: nextSystems }; this.configManager.saveConfigText( @@ -782,38 +599,18 @@ export class CustomSystemsEngine { itemName: string, activeFiles: string[], ): ServerConfig { - assertSafeKey(itemName, 'itemName'); - const system = this.configManager.getSystem(systemId); const server = this.configManager.getServer(serverId); - if (!system || !server) { - throw new Error(`Unknown server "${serverId}" or system "${systemId}"`); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); } - const cleanFiles = [...new Set(activeFiles.map((f) => f.trim()).filter(Boolean))]; + const cleanFiles = activeFiles.map((f) => f.trim()).filter(Boolean); if (cleanFiles.length === 0) { throw new Error('At least one active file must be selected'); } - - const cachedItem = this.cache - .get(`${serverId}:${systemId}`) - ?.items.find((i) => i.name === itemName); - const selectableRegexes = - system.discovery.type === 'folder-scan' - ? (system.discovery.selectableFiles ?? system.discovery.matchFiles).map(globToRegExp) - : []; - for (const file of cleanFiles) { if (!isValidRelativeOverlayFile(file)) { throw new Error(`Invalid overlay filename: "${file}"`); } - if (cachedItem && cachedItem.selectableFiles.length > 0) { - if (!cachedItem.selectableFiles.includes(file)) { - throw new Error(`Overlay file "${file}" was not discovered for item "${itemName}"`); - } - } else if (selectableRegexes.length > 0) { - if (!selectableRegexes.some((re) => re.test(file))) { - throw new Error(`Overlay file "${file}" does not match selectableFiles patterns`); - } - } } const hasAtt = server.systems.some((a) => a.systemId === systemId); @@ -823,20 +620,20 @@ export class CustomSystemsEngine { const updated: ServerConfig = { ...server, - systems: server.systems.map((att) => { - if (att.systemId !== systemId) return att; - const safeOverrides: Record = - Object.create(null); - for (const [k, v] of Object.entries(att.itemOverrides ?? {})) { - if (FORBIDDEN_KEYS.has(k)) continue; - safeOverrides[k] = v; - } - safeOverrides[itemName] = { - ...(Object.hasOwn(att.itemOverrides, itemName) ? att.itemOverrides[itemName] : {}), - activeFiles: cleanFiles, - }; - return { ...att, itemOverrides: safeOverrides }; - }), + systems: server.systems.map((att) => + att.systemId === systemId + ? { + ...att, + itemOverrides: { + ...att.itemOverrides, + [itemName]: { + ...(att.itemOverrides[itemName] ?? {}), + activeFiles: cleanFiles, + }, + }, + } + : att, + ), }; this.configManager.saveConfigText( @@ -882,8 +679,6 @@ export class CustomSystemsEngine { for (const job of this.streamJobs.values()) { if (!job.done) { job.done = true; - if (job.timeoutTimer) clearTimeout(job.timeoutTimer); - if (job.idleTimer) clearTimeout(job.idleTimer); job.abort(); } } @@ -895,17 +690,6 @@ export class CustomSystemsEngine { this.cache.clear(); } - private setCacheBounded(key: string, snapshot: ServerSystemSnapshot): void { - const maxEntries = Math.max(8, this.getRuntimeLimits?.().maxSystemCacheEntries ?? 64); - if (this.cache.has(key)) this.cache.delete(key); - this.cache.set(key, snapshot); - while (this.cache.size > maxEntries) { - const oldestKey = this.cache.keys().next().value; - if (!oldestKey) break; - this.cache.delete(oldestKey); - } - } - private async discoverAndInspectItems( server: ServerConfig, system: SystemConfig, @@ -913,10 +697,6 @@ export class CustomSystemsEngine { params: Record, ): Promise { const baseEnv = this.buildExecutionEnv(server.id, system.id, params); - const concurrency = Math.max( - 1, - this.getRuntimeLimits?.().maxParallelSystemInspect ?? 2, - ); if (system.discovery.type === 'folder-scan') { const rawRoots = params[system.discovery.rootsParam]; @@ -933,7 +713,7 @@ export class CustomSystemsEngine { system.discovery.matchFiles, ); const scanRes = await this.sshPool.exec(server.id, script, { env: baseEnv }); - const rawMatches = parseFolderScanOutput(scanRes.stdout).slice(0, MAX_DISCOVERED_ITEMS); + const rawMatches = parseFolderScanOutput(scanRes.stdout); const matchRegexes = system.discovery.matchFiles.map(globToRegExp); const selectableRegexes = ( @@ -944,45 +724,33 @@ export class CustomSystemsEngine { .map(globToRegExp); const usedNames = new Map(); - const draftItems: DiscoveredSystemItem[] = []; + const items: DiscoveredSystemItem[] = []; for (const m of rawMatches) { - if (/[\x00-\x1f\x7f]/.test(m.dir)) continue; - const safeFiles = m.files.filter( - (f) => !/[\x00-\x1f\x7f]/.test(f) && !f.startsWith('-'), - ); - const matchedFiles = safeFiles.filter((f) => matchRegexes.some((re) => re.test(f))); + const matchedFiles = m.files.filter((f) => matchRegexes.some((re) => re.test(f))); if (matchedFiles.length === 0) continue; let baseName = path.posix.basename(m.dir) || 'root'; - if (FORBIDDEN_KEYS.has(baseName)) baseName = `item-${baseName}`; const seenCount = (usedNames.get(baseName) ?? 0) + 1; usedNames.set(baseName, seenCount); if (seenCount > 1) { baseName = `${baseName}-${seenCount}`; } - const selectableFiles = safeFiles.filter( - (f) => isValidRelativeOverlayFile(f) && selectableRegexes.some((re) => re.test(f)), - ); - const editableFiles = safeFiles + const selectableFiles = m.files.filter((f) => selectableRegexes.some((re) => re.test(f))); + const editableFiles = m.files .filter((f) => editableRegexes.some((re) => re.test(f))) .map((f) => path.posix.join(m.dir, f)); - const overrideRaw = Object.hasOwn(attachment.itemOverrides, baseName) - ? attachment.itemOverrides[baseName]?.activeFiles - : undefined; - const overrideFiles = overrideRaw?.filter( - (f) => - isValidRelativeOverlayFile(f) && - (selectableFiles.length === 0 || selectableFiles.includes(f)), + const overrideFiles = attachment.itemOverrides[baseName]?.activeFiles?.filter((f) => + isValidRelativeOverlayFile(f), ); const activeFiles = overrideFiles && overrideFiles.length > 0 ? overrideFiles : [matchedFiles[0]!]; - draftItems.push({ + const draftItem: DiscoveredSystemItem = { name: baseName, dir: m.dir, activeFiles, @@ -994,14 +762,12 @@ export class CustomSystemsEngine { rawSummary: '', exitCode: null, }, - }); - } + }; - await runPool(draftItems, concurrency, async (draftItem) => { const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem); const statusRes = await this.sshPool.exec( server.id, - `cd -- ${posixSingleQuote(draftItem.dir!)} && ${system.status.command}`, + `cd -- ${posixSingleQuote(m.dir)} && ${system.status.command}`, { env: itemEnv }, ); draftItem.status = parseStatusOutput( @@ -1010,33 +776,32 @@ export class CustomSystemsEngine { statusRes.exitCode, system.status, ); - }); + items.push(draftItem); + } - return draftItems; + return items; } // command discovery const discRes = await this.sshPool.exec(server.id, system.discovery.command, { env: baseEnv, }); - const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser) - .filter((n) => !FORBIDDEN_KEYS.has(n) && !/[\x00-\x1f\x7f]/.test(n)) - .slice(0, MAX_DISCOVERED_ITEMS); + const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser); + const items: DiscoveredSystemItem[] = []; - const draftItems: DiscoveredSystemItem[] = names.map((itemName) => ({ - name: itemName, - activeFiles: [], - selectableFiles: [], - editableFiles: [], - status: { - health: 'unknown', - subItems: [], - rawSummary: '', - exitCode: null, - }, - })); - - await runPool(draftItems, concurrency, async (draftItem) => { + for (const itemName of names) { + const draftItem: DiscoveredSystemItem = { + name: itemName, + activeFiles: [], + selectableFiles: [], + editableFiles: [], + status: { + health: 'unknown', + subItems: [], + rawSummary: '', + exitCode: null, + }, + }; const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem); const statusRes = await this.sshPool.exec(server.id, system.status.command, { env: itemEnv, @@ -1047,88 +812,25 @@ export class CustomSystemsEngine { statusRes.exitCode, system.status, ); - - // Populate editableFiles dynamically from systemd FragmentPath / DropInPaths when present - const raw = draftItem.status.raw; - if (raw) { - const dynamicPaths: string[] = []; - if (typeof raw.FragmentPath === 'string' && isValidAbsolutePath(raw.FragmentPath.trim())) { - dynamicPaths.push(raw.FragmentPath.trim()); - } - if (typeof raw.DropInPaths === 'string') { - for (const dp of raw.DropInPaths.trim().split(/\s+/)) { - if (dp && isValidAbsolutePath(dp)) dynamicPaths.push(dp); - } - } - if (dynamicPaths.length > 0) { - draftItem.editableFiles = [...new Set(dynamicPaths)]; - } - } - }); - - return draftItems; - } - - private validateAndResolveParamsStrict( - system: SystemConfig, - supplied: Record, - ): Record { - for (const k of Object.keys(supplied)) { - assertSafeKey(k, 'param name'); + items.push(draftItem); } - const out: Record = Object.create(null); - for (const def of system.params) { - assertSafeKey(def.name, 'param definition'); - const hasVal = Object.hasOwn(supplied, def.name) && supplied[def.name] !== undefined; - const val = hasVal ? supplied[def.name] : def.default; - if (val === undefined) { - if (def.required) { - throw new Error(`Missing required system param "${def.name}"`); - } - continue; - } - - if (def.type === 'string') { - if (typeof val !== 'string' || /[\x00]/.test(val)) { - throw new Error(`Param "${def.name}" must be a valid string`); - } - out[def.name] = val; - } else if (def.type === 'number') { - const num = typeof val === 'number' ? val : Number(val); - if (!Number.isFinite(num)) { - throw new Error(`Param "${def.name}" must be a finite number`); - } - out[def.name] = num; - } else if (def.type === 'boolean') { - if (typeof val !== 'boolean') { - throw new Error(`Param "${def.name}" must be a boolean`); - } - out[def.name] = val; - } else if (def.type === 'string[]') { - if (!Array.isArray(val) || !val.every((x) => typeof x === 'string' && !/[\x00]/.test(x))) { - throw new Error(`Param "${def.name}" must be an array of strings`); - } - out[def.name] = [...val]; - } - } - return { ...out }; + return items; } private resolveParams( system: SystemConfig, supplied: Record, ): Record { - const out: Record = Object.create(null); + const out: Record = {}; for (const def of system.params) { - if (FORBIDDEN_KEYS.has(def.name)) continue; - if (Object.hasOwn(supplied, def.name) && supplied[def.name] !== undefined) { + if (supplied[def.name] !== undefined) { out[def.name] = supplied[def.name]; } else if (def.default !== undefined) { out[def.name] = structuredClone(def.default); } } - return { ...out }; + return out; } private buildExecutionEnv( @@ -1137,7 +839,6 @@ export class CustomSystemsEngine { params: Record, item?: DiscoveredSystemItem, subItem?: string, - actionInputs?: Record, ): Record { const env: Record = { GCOORD_SERVER_ID: serverId, @@ -1145,19 +846,10 @@ export class CustomSystemsEngine { }; for (const [k, v] of Object.entries(params)) { - if (FORBIDDEN_KEYS.has(k)) continue; const envKey = `GCOORD_PARAM_${k.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`; env[envKey] = Array.isArray(v) ? v.map((x) => String(x)).join('\n') : String(v ?? ''); } - if (actionInputs) { - for (const [k, v] of Object.entries(actionInputs)) { - if (FORBIDDEN_KEYS.has(k)) continue; - const envKey = `GCOORD_INPUT_${k.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`; - env[envKey] = v; - } - } - if (item) { env.GCOORD_ITEM_NAME = item.name; if (item.dir) { diff --git a/src/shared/diff.ts b/src/shared/diff.ts index b7a77f5..d1b8e3e 100644 --- a/src/shared/diff.ts +++ b/src/shared/diff.ts @@ -5,74 +5,18 @@ export interface DiffLine { text: string; } -export type CollapsedDiffEntry = - | DiffLine - | { type: 'hunk'; omittedCount: number; text: string }; - export interface DiffResult { lines: DiffLine[]; - collapsedLines: CollapsedDiffEntry[]; unified: string; additions: number; deletions: number; } -export function collapseDiffHunks(lines: DiffLine[], contextLines = 3): CollapsedDiffEntry[] { - const ctx = Math.max(0, Math.floor(contextLines)); - const keep = new Uint8Array(lines.length); - - for (let i = 0; i < lines.length; i++) { - if (lines[i]!.type !== 'equal') { - const start = Math.max(0, i - ctx); - const end = Math.min(lines.length - 1, i + ctx); - for (let k = start; k <= end; k++) keep[k] = 1; - } - } - - if (!keep.some((v) => v === 1)) { - return lines.length <= ctx * 2 + 2 - ? [...lines] - : [ - ...lines.slice(0, ctx), - { - type: 'hunk', - omittedCount: lines.length - ctx, - text: `... ${lines.length - ctx} unchanged lines omitted ...`, - }, - ]; - } - - const out: CollapsedDiffEntry[] = []; - let i = 0; - while (i < lines.length) { - if (keep[i]) { - out.push(lines[i]!); - i++; - } else { - let j = i; - while (j < lines.length && !keep[j]) j++; - const count = j - i; - if (count === 1) { - out.push(lines[i]!); - } else { - out.push({ - type: 'hunk', - omittedCount: count, - text: `... ${count} unchanged lines omitted ...`, - }); - } - i = j; - } - } - return out; -} - export function computeLineDiff( oldText: string, newText: string, oldLabel = 'revision', newLabel = 'current', - opts: { contextLines?: number } = {}, ): DiffResult { const a = oldText.replace(/\r\n/g, '\n').split('\n'); const b = newText.replace(/\r\n/g, '\n').split('\n'); @@ -131,25 +75,21 @@ export function computeLineDiff( let additions = 0; let deletions = 0; - const collapsedLines = collapseDiffHunks(lines, opts.contextLines ?? 3); const body: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`]; - for (const entry of collapsedLines) { - if (entry.type === 'hunk') { - body.push(`@@ ${entry.text} @@`); - } else if (entry.type === 'add') { + for (const line of lines) { + if (line.type === 'add') { additions++; - body.push(`+${entry.text}`); - } else if (entry.type === 'del') { + body.push(`+${line.text}`); + } else if (line.type === 'del') { deletions++; - body.push(`-${entry.text}`); + body.push(`-${line.text}`); } else { - body.push(` ${entry.text}`); + body.push(` ${line.text}`); } } return { lines, - collapsedLines, unified: body.join('\n'), additions, deletions, diff --git a/src/shared/schemas/alerts.schema.ts b/src/shared/schemas/alerts.schema.ts index 26f751b..2f7ba6d 100644 --- a/src/shared/schemas/alerts.schema.ts +++ b/src/shared/schemas/alerts.schema.ts @@ -1,38 +1,16 @@ import { z } from 'zod'; -import { - CronExpressionSchema, - EntityIdSchema, - HttpUrlSchema, - IanaTimezoneSchema, -} from './common.js'; +import { CronExpressionSchema, EntityIdSchema } from './common.js'; -export const AlertChannelSchema = z - .object({ - id: EntityIdSchema, - name: z.string().min(1).max(120), - type: z.enum(['discord', 'telegram', 'ntfy', 'generic']), - url: HttpUrlSchema.optional(), - secretRef: EntityIdSchema.optional(), - chatId: z.string().optional(), - topic: z.string().optional(), - enabled: z.boolean().default(true), - }) - .superRefine((ch, ctx) => { - if (!ch.url && !ch.secretRef) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['secretRef'], - message: 'Alert channel must specify either url or secretRef', - }); - } - if ((ch.type === 'discord' || ch.type === 'telegram') && !ch.secretRef && !ch.url) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['secretRef'], - message: `${ch.type} channel requires secretRef or url`, - }); - } - }); +export const AlertChannelSchema = z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + type: z.enum(['discord', 'telegram', 'ntfy', 'generic']), + url: z.string().url().optional(), + secretRef: EntityIdSchema, + chatId: z.string().optional(), + topic: z.string().optional(), + enabled: z.boolean().default(true), +}); export const AlertRuleTargetSchema = z.object({ serverId: EntityIdSchema.optional(), @@ -52,20 +30,6 @@ const AlertRuleBase = { enabled: z.boolean().default(true), }; -export const SecurityEventKindSchema = z.enum([ - 'login_burst', - 'new_ip_login', - 'panic_lock', - 'key_rotation', - 'backup_restore', - 'auth.lockout', - 'auth.totp_replay', - 'auth.recovery_code_used', - 'auth.session_idle_expired', - 'ssh.host_key_mismatch', - 'vault.panic_lock', -]); - export const AlertRuleSchema = z.discriminatedUnion('kind', [ z.object({ ...AlertRuleBase, @@ -96,51 +60,26 @@ export const AlertRuleSchema = z.discriminatedUnion('kind', [ systemId: EntityIdSchema, item: z.string().optional(), }), - z.object({ - ...AlertRuleBase, - kind: z.literal('security-event'), - events: z.array(SecurityEventKindSchema).min(1), - }), ]); export const MaintenanceWindowSchema = z.object({ id: EntityIdSchema, name: z.string().min(1).max(120), cron: CronExpressionSchema, - timezone: IanaTimezoneSchema.default('UTC'), + timezone: z.string().min(1).default('UTC'), durationMinutes: z.number().int().min(1).max(1440), target: AlertRuleTargetSchema.default({ all: true }), enabled: z.boolean().default(true), }); -export const AlertsFileSchema = z - .object({ - version: z.literal(1).default(1), - channels: z.array(AlertChannelSchema).default([]), - rules: z.array(AlertRuleSchema).default([]), - maintenanceWindows: z.array(MaintenanceWindowSchema).default([]), - }) - .superRefine((doc, ctx) => { - const checkDupes = (items: Array<{ id: string }>, arrPath: string) => { - const seen = new Set(); - items.forEach((item, idx) => { - if (seen.has(item.id)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: [arrPath, idx, 'id'], - message: `Duplicate ${arrPath} id "${item.id}"`, - }); - } - seen.add(item.id); - }); - }; - checkDupes(doc.channels, 'channels'); - checkDupes(doc.rules, 'rules'); - checkDupes(doc.maintenanceWindows, 'maintenanceWindows'); - }); +export const AlertsFileSchema = z.object({ + version: z.literal(1).default(1), + channels: z.array(AlertChannelSchema).default([]), + rules: z.array(AlertRuleSchema).default([]), + maintenanceWindows: z.array(MaintenanceWindowSchema).default([]), +}); export type AlertChannel = z.infer; export type AlertRule = z.infer; -export type SecurityEventKind = z.infer; export type MaintenanceWindow = z.infer; export type AlertsFile = z.infer; diff --git a/src/shared/schemas/common.ts b/src/shared/schemas/common.ts index 3493d45..081c377 100644 --- a/src/shared/schemas/common.ts +++ b/src/shared/schemas/common.ts @@ -5,44 +5,16 @@ export const EntityIdSchema = z .string() .min(1, 'ID must not be empty') .max(64, 'ID must be at most 64 characters') - .regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/, 'ID must start with alphanumeric and contain only [a-zA-Z0-9._-]') - .refine((v) => !v.includes('..'), 'ID cannot contain ".."'); + .regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/, 'ID must start with alphanumeric and contain only [a-zA-Z0-9._-]'); export const PortSchema = z.number().int().min(1).max(65535); -export const HttpUrlSchema = z - .string() - .url() - .refine((u) => /^https?:\/\//i.test(u), 'URL must use http:// or https://'); - -export const IanaTimezoneSchema = z - .string() - .min(1) - .max(64) - .refine((tz) => { - try { - Intl.DateTimeFormat(undefined, { timeZone: tz }); - return true; - } catch { - return false; - } - }, 'Invalid IANA timezone'); - export const CronExpressionSchema = z .string() .min(1) .superRefine((expr, ctx) => { - const trimmed = expr.trim(); - const fields = trimmed.split(/\s+/); - if (fields.length !== 5) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Cron expression must have exactly 5 fields (minute hour day month weekday)', - }); - return; - } try { - new CronPattern(trimmed); + new CronPattern(expr); } catch (err) { ctx.addIssue({ code: z.ZodIssueCode.custom, @@ -53,7 +25,7 @@ export const CronExpressionSchema = z export const InputDefSchema = z.object({ name: EntityIdSchema, - type: z.enum(['string', 'number', 'boolean', 'server', 'select', 'secret']).default('string'), + type: z.enum(['string', 'number', 'boolean', 'server', 'select']).default('string'), label: z.string().min(1).optional(), description: z.string().optional(), required: z.boolean().default(false), diff --git a/src/shared/schemas/server.schema.ts b/src/shared/schemas/server.schema.ts index 95f7d4d..c3426e1 100644 --- a/src/shared/schemas/server.schema.ts +++ b/src/shared/schemas/server.schema.ts @@ -1,42 +1,22 @@ import { z } from 'zod'; -import { EntityIdSchema, HttpUrlSchema, PortSchema } from './common.js'; - -export const SafeHostSchema = z - .string() - .min(1) - .max(255) - .regex( - /^[A-Za-z0-9\[][A-Za-z0-9._:\[\]-]*$/, - 'Host cannot start with "-" or contain whitespace, "@", or control characters', - ); - -export const SafeUsernameSchema = z - .string() - .min(1) - .max(64) - .regex( - /^[A-Za-z0-9_][A-Za-z0-9._-]*$/, - 'Username cannot start with "-" or contain whitespace, "@", or ":"', - ); +import { EntityIdSchema, PortSchema } from './common.js'; export const HttpProbeSchema = z.object({ id: EntityIdSchema, type: z.literal('http'), - url: HttpUrlSchema, + url: z.string().url(), from: z.enum(['hub', 'target']).default('target'), intervalSec: z.number().int().min(5).max(86400).default(30), timeoutMs: z.number().int().min(200).max(60000).default(5000), expectedStatus: z.number().int().min(100).max(599).default(200), bodyIncludes: z.string().optional(), - tlsRejectUnauthorized: z.boolean().default(true), - tlsCheckExpiryDays: z.number().int().min(1).max(365).optional(), enabled: z.boolean().default(true), }); export const TcpProbeSchema = z.object({ id: EntityIdSchema, type: z.literal('tcp'), - host: SafeHostSchema.default('127.0.0.1'), + host: z.string().min(1).default('127.0.0.1'), port: PortSchema, from: z.enum(['hub', 'target']).default('target'), intervalSec: z.number().int().min(5).max(86400).default(30), @@ -60,71 +40,36 @@ export const ServerSystemAttachmentSchema = z.object({ .default({}), }); -export const ServerTunnelSchema = z - .object({ - id: EntityIdSchema, - name: z.string().min(1).max(120), - mode: z.enum(['http-proxy', 'local-tcp', 'remote-tcp', 'socks5']), - bindHost: SafeHostSchema.optional(), - bindPort: PortSchema.optional(), - targetHost: SafeHostSchema.default('127.0.0.1'), - targetPort: z.number().int().min(0).max(65535).default(0), - targetProtocol: z.enum(['http', 'https']).default('http'), - tlsRejectUnauthorized: z.boolean().default(true), - tlsServerName: z.string().max(255).optional(), - ttlSec: z.number().int().min(60).max(86400).optional(), - autoStart: z.boolean().default(false), - }) - .superRefine((tunnel, ctx) => { - if (tunnel.mode !== 'socks5' && tunnel.targetPort < 1) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['targetPort'], - message: 'targetPort must be between 1 and 65535', - }); - } - }); +export const ServerTunnelSchema = z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + mode: z.enum(['http-proxy', 'local-tcp', 'remote-tcp']), + bindHost: z.string().min(1).optional(), + bindPort: PortSchema.optional(), + targetHost: z.string().min(1).default('127.0.0.1'), + targetPort: PortSchema, + autoStart: z.boolean().default(false), +}); -export const ServerConfigSchema = z - .object({ - id: EntityIdSchema, - name: z.string().min(1).max(120), - host: SafeHostSchema, - port: PortSchema.default(22), - username: SafeUsernameSchema, - credentialId: EntityIdSchema, - jumpHostId: EntityIdSchema.optional(), - sudoCredentialId: EntityIdSchema.optional(), - hostKeyFingerprint: z.string().min(1).optional(), - tags: z.array(z.string().min(1)).default([]), - osHint: z.enum(['auto', 'linux', 'bsd', 'macos']).default('auto'), - pollIntervalSec: z.number().int().min(2).max(3600).default(10), - diskMountFilter: z.array(z.string().min(1)).optional(), - probes: z.array(ServerProbeSchema).default([]), - systems: z.array(ServerSystemAttachmentSchema).default([]), - tunnels: z.array(ServerTunnelSchema).default([]), - enabled: z.boolean().default(true), - }) - .superRefine((srv, ctx) => { - const checkDupes = (items: Array<{ id?: string; systemId?: string }>, key: 'id' | 'systemId', arrPath: string) => { - const seen = new Set(); - items.forEach((item, idx) => { - const val = item[key]; - if (!val) return; - if (seen.has(val)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: [arrPath, idx, key], - message: `Duplicate ${arrPath} identifier "${val}"`, - }); - } - seen.add(val); - }); - }; - checkDupes(srv.probes, 'id', 'probes'); - checkDupes(srv.systems, 'systemId', 'systems'); - checkDupes(srv.tunnels, 'id', 'tunnels'); - }); +export const ServerConfigSchema = z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + host: z.string().min(1), + port: PortSchema.default(22), + username: z.string().min(1).max(64), + credentialId: EntityIdSchema, + jumpHostId: EntityIdSchema.optional(), + sudoCredentialId: EntityIdSchema.optional(), + hostKeyFingerprint: z.string().min(1).optional(), + tags: z.array(z.string().min(1)).default([]), + osHint: z.enum(['auto', 'linux', 'bsd', 'macos']).default('auto'), + pollIntervalSec: z.number().int().min(2).max(3600).default(10), + diskMountFilter: z.array(z.string().min(1)).optional(), + probes: z.array(ServerProbeSchema).default([]), + systems: z.array(ServerSystemAttachmentSchema).default([]), + tunnels: z.array(ServerTunnelSchema).default([]), + enabled: z.boolean().default(true), +}); export type ServerProbe = z.infer; export type ServerSystemAttachment = z.infer; diff --git a/src/shared/schemas/settings.schema.ts b/src/shared/schemas/settings.schema.ts index 003e01c..efd2ca8 100644 --- a/src/shared/schemas/settings.schema.ts +++ b/src/shared/schemas/settings.schema.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { EntityIdSchema, HttpUrlSchema, IanaTimezoneSchema } from './common.js'; +import { EntityIdSchema } from './common.js'; export const ThemeIdSchema = z.enum([ 'phosphor-green', @@ -14,13 +14,10 @@ export const ThemeIdSchema = z.enum([ export const THEME_IDS = ThemeIdSchema.options; -export const ThrottleModeSchema = z.enum(['low-resource', 'balanced', 'unthrottled']); - export const StepUpPolicySchema = z.enum([ 'off', 'every-action', '5m', - '15m', '1h', '24h', 'session', @@ -32,15 +29,11 @@ export const SecuritySettingsSchema = z.object({ requireTotpOnLogin: z.boolean().default(true), passwordMode: z.enum(['any', 'all']).default('any'), totpMode: z.enum(['any', 'all']).default('any'), - stepUpPolicy: StepUpPolicySchema.default('15m'), + stepUpPolicy: StepUpPolicySchema.default('1h'), stepUpMethod: StepUpMethodSchema.default('totp'), - elevateOnLogin: z.boolean().default(false), + elevateOnLogin: z.boolean().default(true), keepElevationOnSafeMode: z.boolean().default(true), - enableEmergencySecretsBackup: z.boolean().default(false), - allowSameOriginProxy: z.boolean().default(false), - egressAllowedCidrs: z.array(z.string().min(1).max(64)).max(64).default([]), - sessionTtlHours: z.number().int().min(1).max(720).default(168), - sessionIdleTimeoutMin: z.number().int().min(0).max(10080).default(60), + enableEmergencySecretsBackup: z.boolean().default(true), }); export const SettingsSchema = z.object({ @@ -49,69 +42,29 @@ export const SettingsSchema = z.object({ defaultMobileSafeMode: z.boolean().default(true), rawRetentionHours: z.number().int().min(1).max(720).default(48), rollupRetentionDays: z.number().int().min(1).max(3650).default(30), - auditRetentionDays: z.number().int().min(1).max(3650).default(90), - workflowRunRetentionDays: z.number().int().min(1).max(3650).default(30), - alertEventRetentionDays: z.number().int().min(1).max(3650).default(30), configRevisionLimit: z.number().int().min(5).max(500).default(50), - ptyScrollbackBytes: z.number().int().min(16384).max(2097152).default(262144), + ptyScrollbackBytes: z.number().int().min(16384).max(4194304).default(524288), ptyIdleTtlSec: z.number().int().min(60).max(604800).default(43200), sshKeepaliveMs: z.number().int().min(5000).max(120000).default(15000), sshReadyTimeoutMs: z.number().int().min(3000).max(120000).default(15000), - runtime: z - .object({ - throttleMode: ThrottleModeSchema.default('low-resource'), - }) - .default({ throttleMode: 'low-resource' }), - scheduledBackup: z - .object({ - enabled: z.boolean().default(false), - cron: z.string().min(1).default('0 3 * * *'), - timezone: IanaTimezoneSchema.default('UTC'), - destination: z.enum(['local', 'sftp']).default('local'), - localDir: z.string().min(1).max(128).default('backups'), - remoteServerId: EntityIdSchema.optional(), - remotePath: z.string().min(1).max(256).optional(), - retentionCount: z.number().int().min(1).max(100).default(7), - passphraseSecretRef: EntityIdSchema.optional(), - }) - .default({ - enabled: false, - cron: '0 3 * * *', - timezone: 'UTC', - destination: 'local', - localDir: 'backups', - retentionCount: 7, - }), - metrics: z - .object({ - prometheusEnabled: z.boolean().default(false), - prometheusSecretRef: EntityIdSchema.optional(), - prometheusTokenHash: z.string().regex(/^[a-f0-9]{64}$/).optional(), - }) - .default({ prometheusEnabled: false }), security: SecuritySettingsSchema.default({}), ai: z .object({ enabled: z.boolean().default(false), - baseUrl: HttpUrlSchema.default('http://127.0.0.1:11434'), + baseUrl: z.string().url().default('http://127.0.0.1:11434'), model: z.string().min(1).default('qwen2.5-coder:7b'), secretRef: EntityIdSchema.optional(), maxContextChars: z.number().int().min(1000).max(128000).default(16000), - timeoutSec: z.number().int().min(5).max(300).default(90), - maxTokens: z.number().int().min(64).max(32768).default(2048), }) .default({ enabled: false, baseUrl: 'http://127.0.0.1:11434', model: 'qwen2.5-coder:7b', maxContextChars: 16000, - timeoutSec: 90, - maxTokens: 2048, }), }); export type ThemeId = z.infer; -export type ThrottleMode = z.infer; export type StepUpPolicy = z.infer; export type StepUpMethod = z.infer; export type SecuritySettings = z.infer; diff --git a/src/shared/schemas/snippets.schema.ts b/src/shared/schemas/snippets.schema.ts index c85a888..905a5f9 100644 --- a/src/shared/schemas/snippets.schema.ts +++ b/src/shared/schemas/snippets.schema.ts @@ -7,7 +7,6 @@ export const SnippetSchema = z.object({ description: z.string().optional(), command: z.string().min(1), tags: z.array(z.string().min(1)).default([]), - osFilter: z.array(z.enum(['linux', 'bsd', 'macos'])).optional(), inputs: z.array(InputDefSchema).default([]), sudo: z.boolean().default(false), confirm: z.boolean().default(false), diff --git a/src/shared/schemas/system.schema.ts b/src/shared/schemas/system.schema.ts index 1d2a59e..dc54458 100644 --- a/src/shared/schemas/system.schema.ts +++ b/src/shared/schemas/system.schema.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { EntityIdSchema, InputDefSchema } from './common.js'; +import { EntityIdSchema } from './common.js'; export const SystemParamDefSchema = z.object({ name: EntityIdSchema, @@ -39,19 +39,7 @@ export const SystemStatusSchema = z.object({ command: z.string().min(1), parser: z.enum(['json-lines', 'json', 'lines', 'regex', 'exit-code']), subItemField: z.string().min(1).optional(), - regexPattern: z - .string() - .min(1) - .max(512) - .refine((pat) => { - try { - new RegExp(pat); - return true; - } catch { - return false; - } - }, 'Invalid regular expression pattern') - .optional(), + regexPattern: z.string().min(1).optional(), health: SystemHealthRuleSchema.optional(), }); @@ -61,61 +49,22 @@ export const SystemActionSchema = z.object({ scope: z.enum(['system', 'item', 'subitem']), mode: z.enum(['oneshot', 'stream', 'interactive']), command: z.string().min(1), - inputs: z.array(InputDefSchema).default([]), - timeoutSec: z.number().int().min(5).max(3600).optional(), sudo: z.boolean().default(false), confirm: z.boolean().default(false), }); -export const SystemConfigSchema = z - .object({ - id: EntityIdSchema, - name: z.string().min(1).max(120), - description: z.string().optional(), - cacheTtlSec: z.number().int().min(0).max(86400).default(45), - backgroundCheckSec: z.number().int().min(10).max(86400).optional(), - params: z.array(SystemParamDefSchema).default([]), - discovery: SystemDiscoverySchema, - status: SystemStatusSchema, - actions: z.array(SystemActionSchema).default([]), - editableFiles: z.array(z.string().min(1)).default([]), - }) - .superRefine((sys, ctx) => { - const paramNames = new Set(); - sys.params.forEach((p, idx) => { - if (paramNames.has(p.name)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['params', idx, 'name'], - message: `Duplicate system param "${p.name}"`, - }); - } - paramNames.add(p.name); - }); - - if ( - sys.discovery.type === 'folder-scan' && - !paramNames.has(sys.discovery.rootsParam) - ) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['discovery', 'rootsParam'], - message: `rootsParam "${sys.discovery.rootsParam}" is not defined in params`, - }); - } - - const actionIds = new Set(); - sys.actions.forEach((a, idx) => { - if (actionIds.has(a.id)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['actions', idx, 'id'], - message: `Duplicate action id "${a.id}"`, - }); - } - actionIds.add(a.id); - }); - }); +export const SystemConfigSchema = z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + description: z.string().optional(), + cacheTtlSec: z.number().int().min(0).max(86400).default(45), + backgroundCheckSec: z.number().int().min(10).max(86400).optional(), + params: z.array(SystemParamDefSchema).default([]), + discovery: SystemDiscoverySchema, + status: SystemStatusSchema, + actions: z.array(SystemActionSchema).default([]), + editableFiles: z.array(z.string().min(1)).default([]), +}); export type SystemParamDef = z.infer; export type SystemHealthRule = z.infer; diff --git a/src/shared/schemas/workflow.schema.ts b/src/shared/schemas/workflow.schema.ts index 646a10f..7e1cf6c 100644 --- a/src/shared/schemas/workflow.schema.ts +++ b/src/shared/schemas/workflow.schema.ts @@ -1,11 +1,5 @@ import { z } from 'zod'; -import { - CronExpressionSchema, - EntityIdSchema, - HttpUrlSchema, - IanaTimezoneSchema, - InputDefSchema, -} from './common.js'; +import { CronExpressionSchema, EntityIdSchema, InputDefSchema } from './common.js'; export const WorkflowTargetSchema = z .object({ @@ -29,13 +23,12 @@ export const StepDependencySchema = z.union([ export const StepFailureActionSchema = z.union([ z.literal('abort'), z.literal('continue'), - EntityIdSchema, - z.discriminatedUnion('action', [ - z.object({ action: z.literal('abort') }), - z.object({ action: z.literal('continue') }), - z.object({ action: z.literal('notify'), channelId: EntityIdSchema }), - z.object({ action: z.literal('run-workflow'), workflowId: EntityIdSchema }), - ]), + z.string().min(1), + z.object({ + action: z.enum(['abort', 'continue', 'notify', 'run-workflow']), + channelId: z.string().min(1).optional(), + workflowId: EntityIdSchema.optional(), + }), ]); const StepBaseFields = { @@ -43,9 +36,6 @@ const StepBaseFields = { name: z.string().min(1).max(120).optional(), dependsOn: z.array(StepDependencySchema).default([]), timeoutSec: z.number().int().min(1).max(86400).optional(), - retries: z.number().int().min(0).max(5).default(0), - retryBackoffSec: z.number().int().min(1).max(300).default(5), - when: z.string().min(1).max(256).optional(), sudo: z.boolean().default(false), captureAs: z.string().min(1).max(64).optional(), onFailure: StepFailureActionSchema.optional(), @@ -90,28 +80,6 @@ export const TransferStepSchema = z.object({ serverId: z.string().min(1), path: z.string().min(1), }), - delete: z.boolean().optional(), - exclude: z.array(z.string().min(1)).max(32).optional(), -}); - -export const HttpStepSchema = z.object({ - ...StepBaseFields, - type: z.literal('http'), - url: HttpUrlSchema, - method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).default('POST'), - headers: z.record(z.string()).optional(), - body: z.string().optional(), - secretRef: EntityIdSchema.optional(), - expectedStatus: z.number().int().min(100).max(599).optional(), -}); - -export const NotifyStepSchema = z.object({ - ...StepBaseFields, - type: z.literal('notify'), - channelIds: z.array(EntityIdSchema).min(1), - title: z.string().min(1).max(160), - message: z.string().min(1).max(4000), - severity: z.enum(['warn', 'critical']).default('warn'), }); export const WorkflowStepSchema = z.discriminatedUnion('type', [ @@ -119,8 +87,6 @@ export const WorkflowStepSchema = z.discriminatedUnion('type', [ ReadFileStepSchema, SystemActionStepSchema, TransferStepSchema, - HttpStepSchema, - NotifyStepSchema, ]); export const WorkflowTriggerSchema = z.discriminatedUnion('type', [ @@ -128,7 +94,7 @@ export const WorkflowTriggerSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('cron'), expression: CronExpressionSchema, - timezone: IanaTimezoneSchema.default('UTC'), + timezone: z.string().min(1).default('UTC'), }), z.object({ type: z.literal('event'), diff --git a/src/shared/ws-protocol.ts b/src/shared/ws-protocol.ts index 6a8092a..66a596e 100644 --- a/src/shared/ws-protocol.ts +++ b/src/shared/ws-protocol.ts @@ -1,7 +1,6 @@ import { z } from 'zod'; export type VaultState = 'uninitialized' | 'locked' | 'unlocked'; -export type VaultSealState = 'uninitialized' | 'sealed' | 'write-locked' | 'unlocked'; export type ServerConnectionStatus = | 'disconnected' @@ -49,7 +48,6 @@ export interface ProbeSample { ok: boolean; statusCode?: number; latencyMs: number; - certExpiryDays?: number; error?: string; } @@ -135,7 +133,6 @@ export type ServerWsFrame = type: 'hello'; vaultState: VaultState; vaultRuntimeReady?: boolean; - vaultSealState?: VaultSealState; safeMode: boolean; elevatedUntil: number | null; } @@ -143,7 +140,6 @@ export type ServerWsFrame = type: 'vault:state'; vaultState: VaultState; vaultRuntimeReady: boolean; - vaultSealState?: VaultSealState; isPanicLocked: boolean; } | { diff --git a/tests/ai-assistant.test.ts b/tests/ai-assistant.test.ts index 66f40b7..8dedbae 100644 --- a/tests/ai-assistant.test.ts +++ b/tests/ai-assistant.test.ts @@ -3,7 +3,7 @@ import http from 'node:http'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; @@ -205,8 +205,6 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide return { status: res.status, data }; }; - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -227,11 +225,7 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide initialSafeMode: false, }, }); - vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); - expect( - (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); await api('/api/vault/credentials', { @@ -287,19 +281,6 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide // Write-lock Vault -> AI runtime secret still works via VaultService.getRuntimeSecret expect((await api('/api/vault/lock', { method: 'POST' })).data.state).toBe('locked'); - // Default Zero-Trust egress policy blocks outbound calls to loopback until allowlisted - const blockedEp = await api('/api/ai/test', { method: 'POST', body: {} }); - expect(blockedEp.data.ok).toBe(false); - - expect( - ( - await api('/api/auth/security-policy', { - method: 'PUT', - body: { egressAllowedCidrs: ['127.0.0.1/32'] }, - }) - ).status, - ).toBe(200); - const testEp = await api('/api/ai/test', { method: 'POST', body: {} }); expect(testEp.status).toBe(200); expect(testEp.data.ok).toBe(true); diff --git a/tests/alerts-engine.test.ts b/tests/alerts-engine.test.ts index c1caaca..59d0fd8 100644 --- a/tests/alerts-engine.test.ts +++ b/tests/alerts-engine.test.ts @@ -3,7 +3,7 @@ import http from 'node:http'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -132,8 +132,6 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () => return { status: res.status, data }; }; - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -154,11 +152,7 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () => initialSafeMode: false, }, }); - vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); - expect( - (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { @@ -415,19 +409,6 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () => expect(lockRes.data.state).toBe('locked'); expect(lockRes.data.runtimeReady).toBe(true); - // Default Zero-Trust egress policy blocks webhook dispatch to 127.0.0.1 until allowlisted - const deniedWebhook = await api('/api/alerts/channels/ch-discord/test', { method: 'POST' }); - expect(deniedWebhook.data.ok).toBe(false); - - expect( - ( - await api('/api/auth/security-policy', { - method: 'PUT', - body: { egressAllowedCidrs: ['127.0.0.1/32'] }, - }) - ).status, - ).toBe(200); - // --- 1. Send Test Alert for all 4 channel types while Vault is write-locked --- for (const chId of ['ch-discord', 'ch-tg', 'ch-ntfy', 'ch-generic']) { const tRes = await api(`/api/alerts/channels/${chId}/test`, { method: 'POST' }); diff --git a/tests/api-ws-smoke.test.ts b/tests/api-ws-smoke.test.ts index 1e603de..863fa15 100644 --- a/tests/api-ws-smoke.test.ts +++ b/tests/api-ws-smoke.test.ts @@ -3,7 +3,7 @@ import os from 'node:os'; import path from 'node:path'; import zlib from 'node:zlib'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; @@ -115,9 +115,7 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { expect(health.status).toBe(200); await expect(openWs(wsUrl, {})).rejects.toThrow('WS_HTTP_401'); - // 2. Bootstrap Admin + TOTP (offset 65s back so step-up tests below have fresh TOTP steps) - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 65_000); + // 2. Bootstrap Admin + TOTP const bootInfo = await api('/api/auth/bootstrap'); expect(bootInfo.status).toBe(200); const secretBase32 = String(bootInfo.data.secretBase32); @@ -140,7 +138,6 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { initialSafeMode: false, }, }); - vi.setSystemTime(Date.now() + 31_000); expect(bootDone.status).toBe(201); csrfToken = String(bootDone.data.csrfToken); const recoveryCodes = bootDone.data.recoveryCodes as string[]; @@ -201,41 +198,30 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { (await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } })).status, ).toBe(200); - // 6. Vault Init + Step-Up guard + Drop Elevation + Generate Ed25519 key - // v1.1 defaults elevateOnLogin=false; verify non-elevated session cannot init vault - const statusInitial = await api('/api/auth/status'); - expect(statusInitial.data.elevatedUntil).toBeNull(); - - const vInitDenied = await api('/api/vault/init', { method: 'POST', body: {} }); - expect(vInitDenied.status).toBe(403); - expect(vInitDenied.data.error).toBe('STEP_UP_REQUIRED'); - - const stepUpRes = await api('/api/auth/step-up', { - method: 'POST', - body: { code: totpGen.generate() }, - }); - expect(stepUpRes.status).toBe(200); - + // 6. Vault Init + Drop Elevation -> Step-Up guard + Generate Ed25519 key const vInit = await api('/api/vault/init', { method: 'POST', body: {} }); expect(vInit.status).toBe(201); const generatedMasterKey = String(vInit.data.generatedKeyHex); + // Default balanced mode elevates on bootstrap/login; drop elevation to verify guard enforcement const statusBeforeDrop = await api('/api/auth/status'); expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number'); const dropped = await api('/api/auth/drop-elevation', { method: 'POST' }); expect(dropped.status).toBe(200); expect(dropped.data.elevatedUntil).toBeNull(); - const afterDropDenied = await api('/api/vault/generate-ed25519', { + const noStepUp = await api('/api/vault/generate-ed25519', { method: 'POST', body: { id: 'prod-key', name: 'Prod Key' }, }); - expect(afterDropDenied.status).toBe(403); + expect(noStepUp.status).toBe(403); + expect(noStepUp.data.error).toBe('STEP_UP_REQUIRED'); - vi.useRealTimers(); - expect( - (await api('/api/auth/step-up', { method: 'POST', body: { code: totpGen.generate() } })).status, - ).toBe(200); + const stepUpRes = await api('/api/auth/step-up', { + method: 'POST', + body: { code: totpGen.generate() }, + }); + expect(stepUpRes.status).toBe(200); const genRes = await api('/api/vault/generate-ed25519', { method: 'POST', diff --git a/tests/auth-and-guards.test.ts b/tests/auth-and-guards.test.ts index 1683dbe..7d6b6bf 100644 --- a/tests/auth-and-guards.test.ts +++ b/tests/auth-and-guards.test.ts @@ -129,21 +129,15 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => { }); expect(boot.session.elevatedUntil).toBeNull(); - // Unified monotonic TOTP step blocks replaying bootstrap code for step-up - const replayBootCode = await auth.stepUp(boot.session.idHash, code0); - expect(replayBootCode).toEqual({ ok: false, reason: 'totp_replayed' }); - - const t1 = t0 + 31_000; - vi.setSystemTime(t1); - const code1 = generateTotp(enroll.secretBase32, t1); - const stepUp1 = await auth.stepUp(boot.session.idHash, code1); + // Step-up tracks replay independently from login step + const stepUp1 = await auth.stepUp(boot.session.idHash, code0); expect(stepUp1).toEqual({ ok: true, - elevatedUntil: t1 + 5 * 60 * 1000, + elevatedUntil: t0 + 5 * 60 * 1000, }); // Replaying exact same step-up code is denied - const stepUpReplay = await auth.stepUp(boot.session.idHash, code1); + const stepUpReplay = await auth.stepUp(boot.session.idHash, code0); expect(stepUpReplay).toEqual({ ok: false, reason: 'totp_replayed' }); // Enabling Safe Mode clears elevatedUntil immediately @@ -152,26 +146,25 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => { expect(safeSession?.elevatedUntil).toBeNull(); // Step-up is blocked while Safe Mode is ON - const t2 = t1 + 31_000; - vi.setSystemTime(t2); - const code2 = generateTotp(enroll.secretBase32, t2); - const whileSafe = await auth.stepUp(boot.session.idHash, code2); + vi.setSystemTime(t0 + 31_000); + const code1 = generateTotp(enroll.secretBase32, t0 + 31_000); + const whileSafe = await auth.stepUp(boot.session.idHash, code1); expect(whileSafe).toEqual({ ok: false, reason: 'safe_mode_active' }); // Turning Safe Mode OFF allows step-up again auth.setSafeMode(boot.session.idHash, false); - const stepUp2 = await auth.stepUp(boot.session.idHash, code2); + const stepUp2 = await auth.stepUp(boot.session.idHash, code1); expect(stepUp2.ok).toBe(true); // Elevation expires automatically after 5 minutes - vi.setSystemTime(t2 + 5 * 60 * 1000 + 1000); + vi.setSystemTime(t0 + 31_000 + 5 * 60 * 1000 + 1000); const expiredSession = auth.getSessionByToken(boot.sessionToken); expect(expiredSession?.elevatedUntil).toBeNull(); db.close(); }); - it('keeps elevateOnLogin disabled by default (15m step-up policy) and preserves elevation across Safe Mode toggle', async () => { + it('grants default 1h elevation on bootstrap/login and preserves elevation across Safe Mode toggle', async () => { vi.useFakeTimers({ toFake: ['Date'] }); const t0 = 1_700_000_010_000; vi.setSystemTime(t0); @@ -187,18 +180,11 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => { userAgent: 'vitest', }); - expect(boot.session.elevatedUntil).toBeNull(); - - vi.setSystemTime(t0 + 31_000); - const step = await auth.stepUp(boot.session.idHash, generateTotp(enroll.secretBase32, t0 + 31_000)); - expect(step).toEqual({ - ok: true, - elevatedUntil: t0 + 31_000 + 15 * 60 * 1000, - }); + expect(boot.session.elevatedUntil).toBe(t0 + 60 * 60 * 1000); const safeSession = auth.setSafeMode(boot.session.idHash, true); expect(safeSession?.safeMode).toBe(true); - expect(safeSession?.elevatedUntil).toBe(t0 + 31_000 + 15 * 60 * 1000); + expect(safeSession?.elevatedUntil).toBe(t0 + 60 * 60 * 1000); db.close(); }); diff --git a/tests/backup-and-cli.test.ts b/tests/backup-and-cli.test.ts index 63fdc36..e6e58e9 100644 --- a/tests/backup-and-cli.test.ts +++ b/tests/backup-and-cli.test.ts @@ -4,7 +4,7 @@ import os from 'node:os'; import path from 'node:path'; import { promisify } from 'node:util'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import { createGCoordinatorServer } from '../src/server/app.js'; import { openDatabase } from '../src/server/db/database.js'; import { VaultService } from '../src/server/security/vault.js'; @@ -84,8 +84,6 @@ describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord C return { status: res.status, data }; }; - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -106,11 +104,7 @@ describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord C initialSafeMode: false, }, }); - vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); - expect( - (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { diff --git a/tests/custom-systems.test.ts b/tests/custom-systems.test.ts index e5e12a4..f587d67 100644 --- a/tests/custom-systems.test.ts +++ b/tests/custom-systems.test.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -103,8 +103,6 @@ describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions & return { status: res.status, data: data as Record }; }; - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -125,11 +123,7 @@ describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions & initialSafeMode: false, }, }); - vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); - expect( - (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { diff --git a/tests/helpers/mock-ssh-server.ts b/tests/helpers/mock-ssh-server.ts index 8bdd653..67a03df 100644 --- a/tests/helpers/mock-ssh-server.ts +++ b/tests/helpers/mock-ssh-server.ts @@ -401,27 +401,7 @@ export class MockSshServer { let stdin = rawStdin; // Handle sudo wrappers produced by prepareSudoExecution - if (command.startsWith("sudo -S -k -p '' sh -c ")) { - const nl = stdin.indexOf('\n'); - const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin; - this.lastSudoStdin = suppliedPw; - stdin = nl >= 0 ? stdin.slice(nl + 1) : ''; - if (this.options.sudoPassword && suppliedPw !== this.options.sudoPassword) { - return { stdout: '', stderr: 'sudo: incorrect password', exitCode: 1 }; - } - command = unquoteSinglePosix(command.slice("sudo -S -k -p '' sh -c ".length)); - } else if (command.startsWith("sudo -S -k -p '[gcoord-sudo-prompt] ' sh -c ")) { - const nl = stdin.indexOf('\n'); - const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin; - this.lastSudoStdin = suppliedPw; - stdin = nl >= 0 ? stdin.slice(nl + 1) : ''; - if (this.options.sudoPassword && suppliedPw !== this.options.sudoPassword) { - return { stdout: '', stderr: 'sudo: incorrect password', exitCode: 1 }; - } - command = unquoteSinglePosix( - command.slice("sudo -S -k -p '[gcoord-sudo-prompt] ' sh -c ".length), - ); - } else if (command.startsWith("sudo -S -p '' sh -c ")) { + if (command.startsWith("sudo -S -p '' sh -c ")) { const nl = stdin.indexOf('\n'); const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin; this.lastSudoStdin = suppliedPw; @@ -567,10 +547,9 @@ export class MockSshServer { rawCommand: string, ): { stdout: Buffer; stderr?: string; exitCode: number } | null { // Support streamed SFTP folder archive command in integration tests - const tarMatch = - /tar (?:--one-file-system )?-C ('(?:[^']|'\\'')*'|\S+) -cf - (?:-- )?('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec( - rawCommand, - ); + const tarMatch = /tar -C ('(?:[^']|'\\'')*'|\S+) -cf - ('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec( + rawCommand, + ); if (tarMatch) { try { const virtualParent = unquoteSinglePosix(tarMatch[1]!); diff --git a/tests/mobile-and-themes.test.ts b/tests/mobile-and-themes.test.ts index 17f3e83..9195ab7 100644 --- a/tests/mobile-and-themes.test.ts +++ b/tests/mobile-and-themes.test.ts @@ -26,29 +26,9 @@ describe('Phase 5: 8 Theme Presets, Code-Splitting Budgets & Galaxy J7 Mobile Op } }); - it('meets <50KB core gzipped bundle (including static sync chunks), splits lazy chunks, preserves PWA & mobile CSS, and caps DOM streams', () => { + it('meets <50KB core gzipped bundle, splits lazy chunks, preserves PWA & mobile CSS, and caps DOM streams', () => { const publicDir = path.resolve('dist/public'); - - // Recursively follow static ESM imports from main.js to measure true eager core bundle - const visitedJs = new Set(['main.js']); - const queue = ['main.js']; - while (queue.length > 0) { - const rel = queue.shift()!; - const abs = path.join(publicDir, rel); - if (!fs.existsSync(abs)) continue; - const code = fs.readFileSync(abs, 'utf8'); - const importRe = /\bfrom\s*["']\.\/(chunks\/[^"']+\.js)["']|\bimport\s*["']\.\/(chunks\/[^"']+\.js)["']/g; - let m: RegExpExecArray | null; - while ((m = importRe.exec(code)) !== null) { - const target = m[1] ?? m[2]!; - if (!visitedJs.has(target)) { - visitedJs.add(target); - queue.push(target); - } - } - } - - const coreFiles = ['index.html', 'themes.css', 'base.css', ...visitedJs]; + const coreFiles = ['index.html', 'themes.css', 'base.css', 'main.js']; let totalCoreGzip = 0; for (const f of coreFiles) { @@ -57,18 +37,13 @@ describe('Phase 5: 8 Theme Presets, Code-Splitting Budgets & Galaxy J7 Mobile Op } expect(totalCoreGzip).toBeLessThan(50 * 1024); - // Heavy/optional views & overlays stay code-split out of main.js + // Heavy/optional UI stays code-split out of main.js const mainJs = fs.readFileSync(path.join(publicDir, 'main.js'), 'utf8'); expect(mainJs).not.toContain('ai-drawer-dialog'); expect(mainJs).not.toContain('xterm-helper-textarea'); - expect(mainJs).not.toContain('Fleet Monitor'); const chunks = fs.readdirSync(path.join(publicDir, 'chunks')); expect(chunks.some((c) => c.startsWith('ai-drawer-') && c.endsWith('.js'))).toBe(true); - expect(chunks.some((c) => c.startsWith('command-palette-') && c.endsWith('.js'))).toBe(true); - expect(chunks.some((c) => c.startsWith('dashboard-view-') && c.endsWith('.js'))).toBe(true); - expect(chunks.some((c) => c.startsWith('settings-view-') && c.endsWith('.js'))).toBe(true); - expect(chunks.some((c) => c.startsWith('settings-ops-panel-') && c.endsWith('.js'))).toBe(true); expect(chunks.some((c) => c.startsWith('terminal-view-') && c.endsWith('.js'))).toBe(true); expect(chunks.some((c) => c.startsWith('workflows-view-') && c.endsWith('.js'))).toBe(true); expect(chunks.some((c) => c.startsWith('alerts-view-') && c.endsWith('.js'))).toBe(true); diff --git a/tests/monitoring-and-probes.test.ts b/tests/monitoring-and-probes.test.ts index c15573e..46d8097 100644 --- a/tests/monitoring-and-probes.test.ts +++ b/tests/monitoring-and-probes.test.ts @@ -170,7 +170,7 @@ describe('OS Collectors, ServerInspector, Health Probes & MonitoringService', () await cfg.init({ watch: false }); const knownHosts = new KnownHostsService(db, audit); const sshPool = new SSHPool(cfg, vault, knownHosts); - const probeRunner = new ProbeRunner(sshPool, cfg); + const probeRunner = new ProbeRunner(sshPool); const inspector = new ServerInspector(sshPool, cfg); const monitoring = new MonitoringService(db, cfg, vault, sshPool, probeRunner); @@ -222,15 +222,6 @@ describe('OS Collectors, ServerInspector, Health Probes & MonitoringService', () ); const serverCfg = cfg.getServer('linux-01')!; - // Hub loopback HTTP probe is blocked by default Zero-Trust egress policy until explicitly allowlisted - const hubProbe = serverCfg.probes.find((p) => p.id === 'hub-http')!; - const deniedSample = await probeRunner.runProbe('linux-01', hubProbe); - expect(deniedSample.ok).toBe(false); - - const nextSettings = cfg.getSettings(); - nextSettings.security.egressAllowedCidrs = ['127.0.0.1/32']; - cfg.saveConfigText('settings.json', JSON.stringify(nextSettings, null, 2)); - for (const p of serverCfg.probes) { const sample = await probeRunner.runProbe('linux-01', p); expect(sample.ok).toBe(true); diff --git a/tests/multi-auth-and-recovery.test.ts b/tests/multi-auth-and-recovery.test.ts index 60b4710..f2431b2 100644 --- a/tests/multi-auth-and-recovery.test.ts +++ b/tests/multi-auth-and-recovery.test.ts @@ -192,13 +192,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret ).status, ).toBe(201); - // Explicitly step up before vault mutations (v1.1 default elevateOnLogin=false) - vi.setSystemTime(t0 + 31_000); - expect( - (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp1.generate() } })).status, - ).toBe(200); - - // Initialize vault & generate key while elevated + // Initialize vault & generate key while default 1h login elevation is active expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); expect( ( @@ -237,7 +231,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200); api.clearCsrf(); - vi.setSystemTime(t0 + 62_000); + vi.setSystemTime(t0 + 31_000); const anyLogin = await api.call('/api/auth/login', { method: 'POST', body: { @@ -250,9 +244,6 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret expect(anyLogin.status).toBe(200); // Switch settings.json to strict multi-factor 'all' + 'every-action' + password step-up - expect( - (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp1.generate() } })).status, - ).toBe(200); const rawSettings = await api.call('/api/config/file?path=settings.json'); expect(rawSettings.status).toBe(200); const parsedSettings = JSON.parse(String(rawSettings.data.rawContent)) as Record< @@ -284,7 +275,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret // Logout and test 'all' enforcement expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200); api.clearCsrf(); - vi.setSystemTime(t0 + 93_000); + vi.setSystemTime(t0 + 62_000); const partialPw = await api.call('/api/auth/login', { method: 'POST', @@ -297,7 +288,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret }); expect(partialPw.status).toBe(401); - vi.setSystemTime(t0 + 124_000); + vi.setSystemTime(t0 + 93_000); const partialTotp = await api.call('/api/auth/login', { method: 'POST', body: { @@ -309,7 +300,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret }); expect(partialTotp.status).toBe(401); - vi.setSystemTime(t0 + 155_000); + vi.setSystemTime(t0 + 124_000); const fullAllLogin = await api.call('/api/auth/login', { method: 'POST', body: { @@ -373,24 +364,6 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret } }); - const curSettings = server.configManager.getSettings(); - server.configManager.saveConfigText( - 'settings.json', - JSON.stringify( - { - ...curSettings, - security: { - ...curSettings.security, - enableEmergencySecretsBackup: true, - }, - }, - null, - 2, - ), - 'ui', - 'Enable emergency recovery for test', - ); - let api = createApiClient(server); const bootInfo = await api.call('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); @@ -409,11 +382,6 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret expect(boot.status).toBe(201); const recoveryCodes = boot.data.recoveryCodes as string[]; - vi.setSystemTime(t0 + 31_000); - expect( - (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); - const vInit = await api.call('/api/vault/init', { method: 'POST', body: {} }); expect(vInit.status).toBe(201); const masterKeyHex = String(vInit.data.generatedKeyHex); @@ -434,7 +402,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret const bundle = JSON.parse(fs.readFileSync(bundlePath, 'utf8')) as EmergencySecretsBundle; expect(bundle.vaultMasterKeyHex).toBe(masterKeyHex); expect(bundle.admin.username).toBe('admin'); - expect(bundle.admin.passwords.some((p) => p.label === 'Primary Password' && !('plaintextPassword' in p))).toBe(true); + expect(bundle.admin.passwords.some((p) => p.plaintextPassword === password)).toBe(true); expect(bundle.admin.totps.some((t) => t.secretBase32 === secretBase32)).toBe(true); expect(bundle.admin.recoveryCodes).toEqual(recoveryCodes); expect(bundle.vaultCredentials['backup-key']).toBeDefined(); @@ -453,7 +421,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret activeServer = server; api = createApiClient(server); - vi.setSystemTime(t0 + 62_000); + vi.setSystemTime(t0 + 31_000); const relogin = await api.call('/api/auth/login', { method: 'POST', body: { @@ -510,11 +478,6 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret ).status, ).toBe(200); - vi.setSystemTime(t0 + 93_000); - expect( - (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); - const wipeRes = await api.call('/api/auth/recovery-backup?disable=1', { method: 'DELETE', }); diff --git a/tests/passkeys.test.ts b/tests/passkeys.test.ts index 0a9137b..7489aee 100644 --- a/tests/passkeys.test.ts +++ b/tests/passkeys.test.ts @@ -1,10 +1,9 @@ import crypto from 'node:crypto'; import fs from 'node:fs'; -import http from 'node:http'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import { createGCoordinatorServer } from '../src/server/app.js'; const cleanups: Array<() => Promise | void> = []; @@ -153,7 +152,6 @@ function buildSyntheticAuthenticator(rpID: string, expectedOrigin: string) { } afterEach(async () => { - vi.useRealTimers(); while (cleanups.length > 0) { await cleanups.pop()!(); } @@ -174,6 +172,7 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { fs.rmSync(dataDir, { recursive: true, force: true }); }); + const baseUrl = `http://127.0.0.1:${server.port}`; const origin = `http://localhost:${server.port}`; const jar = new CookieJar(); let csrfToken = ''; @@ -187,65 +186,22 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { Host: `localhost:${server.port}`, }; if (jar.header()) headers.Cookie = jar.header(); - const payload = opts.body !== undefined ? JSON.stringify(opts.body) : undefined; - if (payload !== undefined) { - headers['Content-Type'] = 'application/json'; - headers['Content-Length'] = String(Buffer.byteLength(payload)); - } + if (opts.body !== undefined) headers['Content-Type'] = 'application/json'; if (csrfToken) headers['X-CSRF-Token'] = csrfToken; - const res = await new Promise<{ status: number; setCookies: string[]; text: string }>( - (resolve, reject) => { - const req = http.request( - { - host: '127.0.0.1', - port: server.port, - path: pathname, - method: opts.method ?? 'GET', - headers, - }, - (incoming) => { - const chunks: Buffer[] = []; - incoming.on('data', (c) => chunks.push(Buffer.from(c))); - incoming.on('end', () => { - const rawSetCookie = incoming.headers['set-cookie']; - resolve({ - status: incoming.statusCode ?? 0, - setCookies: Array.isArray(rawSetCookie) ? rawSetCookie : [], - text: Buffer.concat(chunks).toString('utf8'), - }); - }); - }, - ); - req.on('error', reject); - if (payload !== undefined) req.write(payload); - req.end(); - }, - ); - for (const line of res.setCookies) { - const first = line.split(';')[0] ?? ''; - const eq = first.indexOf('='); - if (eq > 0) { - const name = first.slice(0, eq).trim(); - const val = first.slice(eq + 1).trim(); - if (val === '') jar['cookies'].delete(name); - else jar['cookies'].set(name, val); - } - } - let data: Record = {}; - try { - data = JSON.parse(res.text) as Record; - } catch { - data = {}; - } + const res = await fetch(`${baseUrl}${pathname}`, { + method: opts.method ?? 'GET', + headers, + body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, + }); + jar.updateFrom(res); + const data = (await res.json().catch(() => ({}))) as Record; if (typeof data.csrfToken === 'string' && data.csrfToken) { csrfToken = data.csrfToken; } return { status: res.status, data }; }; - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -270,10 +226,6 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { }) ).status, ).toBe(201); - vi.useRealTimers(); - expect( - (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); await api('/api/vault/generate-ed25519', { @@ -358,38 +310,7 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { }); expect(loginVerify2.status).toBe(200); - // 3. Step-Up Verification via Passkey requires stepUpMethod === 'passkey' - await api('/api/auth/drop-elevation', { method: 'POST' }); - expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403); - - const deniedOpts = await api('/api/auth/passkeys/step-up/options', { method: 'POST', body: {} }); - expect(deniedOpts.status).toBe(200); - const deniedVerify = await api('/api/auth/passkeys/step-up/verify', { - method: 'POST', - body: { - challengeId: String(deniedOpts.data.challengeId), - response: authn.createAuthenticationResponse( - String((deniedOpts.data.options as { challenge: string }).challenge), - ), - }, - }); - expect(deniedVerify.status).toBe(403); - expect(deniedVerify.data.reason).toBe('passkey_stepup_not_enabled'); - - // Step up with TOTP in next step, enable stepUpMethod = 'passkey', then drop & verify passkey step-up - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() + 35_000); - expect( - (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); - expect( - ( - await api('/api/auth/security-policy', { - method: 'PUT', - body: { stepUpMethod: 'passkey' }, - }) - ).status, - ).toBe(200); + // 3. Step-Up Verification via Passkey await api('/api/auth/drop-elevation', { method: 'POST' }); expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403); @@ -408,22 +329,7 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { expect(typeof stepVerify.data.elevatedUntil).toBe('number'); expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(200); - // 4. Cannot delete the last passkey while stepUpMethod === 'passkey' - const blockedDel = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, { - method: 'DELETE', - }); - expect(blockedDel.status).toBe(400); - - // Switch stepUpMethod back to 'totp', then delete passkey cleanly - expect( - ( - await api('/api/auth/security-policy', { - method: 'PUT', - body: { stepUpMethod: 'totp' }, - }) - ).status, - ).toBe(200); - + // 4. Delete passkey factor const delRes = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, { method: 'DELETE', }); diff --git a/tests/pty-and-sftp.test.ts b/tests/pty-and-sftp.test.ts index 40cb5ba..a65c8c6 100644 --- a/tests/pty-and-sftp.test.ts +++ b/tests/pty-and-sftp.test.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -82,8 +82,6 @@ async function setupServerWithSsh() { return { status: res.status, data: data as Record }; }; - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -104,11 +102,7 @@ async function setupServerWithSsh() { initialSafeMode: false, }, }); - vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); - expect( - (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { diff --git a/tests/servers-api-e2e.test.ts b/tests/servers-api-e2e.test.ts index 26e9060..6b34ce5 100644 --- a/tests/servers-api-e2e.test.ts +++ b/tests/servers-api-e2e.test.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -88,8 +88,6 @@ describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic }; // Bootstrap + Auth + Vault + Ed25519 Key - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -110,7 +108,6 @@ describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic secretBase32, }, }); - vi.useRealTimers(); expect(bootRes.status).toBe(201); csrfToken = String(bootRes.data.csrfToken); @@ -121,10 +118,10 @@ describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic }); ws.send(JSON.stringify({ type: 'sub', channels: ['metrics', 'alerts', 'config'] })); + expect((await api('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); expect( (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, ).toBe(200); - expect((await api('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); const keyRes = await api('/api/vault/generate-ed25519', { method: 'POST', diff --git a/tests/tunnels-and-proxy.test.ts b/tests/tunnels-and-proxy.test.ts index cc4bc20..0d1e9e0 100644 --- a/tests/tunnels-and-proxy.test.ts +++ b/tests/tunnels-and-proxy.test.ts @@ -4,7 +4,7 @@ import net from 'node:net'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import WebSocket, { WebSocketServer } from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -97,7 +97,6 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC dataDir, port: 0, host: '127.0.0.1', - proxyPort: 0, publicDir: path.resolve('dist/public'), watchConfig: false, }); @@ -128,8 +127,6 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC return { status: res.status, data: data as Record }; }; - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -150,11 +147,7 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC initialSafeMode: false, }, }); - vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); - expect( - (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { @@ -211,46 +204,6 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC const unauthProxy = await fetch(`${baseUrl}/proxy/web-ui/hello`); expect(unauthProxy.status).toBe(401); - // Same-origin /proxy is blocked with 403 by default; test isolated proxyPort ticket flow first! - const blockedSameOrigin = await api('/proxy/web-ui/hello'); - expect(blockedSameOrigin.status).toBe(403); - expect(blockedSameOrigin.data.error).toBe('PROXY_ORIGIN_ISOLATION_REQUIRED'); - - const ticketRes = await api('/api/tunnels/app1/web-ui/proxy-ticket', { - method: 'POST', - body: {}, - }); - expect(ticketRes.status).toBe(200); - expect(ticketRes.data.mode).toBe('port'); - const launchUrl = String(ticketRes.data.launchUrl); - const proxyBaseUrl = `http://127.0.0.1:${server.proxyPort}`; - - // Redeem single-use ticket on isolated proxy origin to receive scoped gcoord_proxy_sid cookie - const proxyJar = new CookieJar(); - const ticketHit = await fetch(launchUrl, { redirect: 'manual' }); - expect(ticketHit.status).toBe(302); - proxyJar.updateFrom(ticketHit); - expect(proxyJar.header()).toContain('gcoord_proxy_sid='); - - const isoHello = await fetch(`${proxyBaseUrl}/proxy/web-ui/hello`, { - headers: { Cookie: proxyJar.header() }, - }); - expect(isoHello.status).toBe(200); - const isoHelloData = (await isoHello.json()) as { ok: boolean }; - expect(isoHelloData.ok).toBe(true); - expect(upstream.getLastCookie() ?? '').not.toContain('gcoord_sid'); - expect(upstream.getLastCookie() ?? '').not.toContain('gcoord_proxy_sid'); - - // Also enable allowSameOriginProxy explicitly to test same-origin backwards compatibility - expect( - ( - await api('/api/auth/security-policy', { - method: 'PUT', - body: { allowSameOriginProxy: true }, - }) - ).status, - ).toBe(200); - // Authenticated GET & POST JSON stream through proxy without exposing hub session cookies const authedHello = await api('/proxy/web-ui/hello'); expect(authedHello.status).toBe(200); @@ -345,35 +298,7 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC expect(localHttp.status).toBe(200); expect(((await localHttp.json()) as { ok: boolean }).ok).toBe(true); - // 3. Remote TCP (R) tunnel targets 127.0.0.1 -> blocked by Zero-Trust egress guard unless allowlisted - const blockedRemoteTcp = await api('/api/tunnels', { - method: 'POST', - body: { - serverId: 'app1', - tunnel: { - id: 'tcp-remote', - name: 'Remote TCP Reverse', - mode: 'remote-tcp', - bindHost: '127.0.0.1', - targetHost: '127.0.0.1', - targetPort: upstream.port, - autoStart: false, - }, - start: true, - }, - }); - expect(blockedRemoteTcp.data.startError).toBeTruthy(); - - // Allow 127.0.0.1/32 in egressAllowedCidrs -> Remote TCP (R) starts and forwards cleanly - expect( - ( - await api('/api/auth/security-policy', { - method: 'PUT', - body: { egressAllowedCidrs: ['127.0.0.1/32'] }, - }) - ).status, - ).toBe(200); - + // 3. Remote TCP (R) tunnel via forwardIn const remoteTcpRes = await api('/api/tunnels', { method: 'POST', body: { diff --git a/tests/v11-automation-monitoring-cli.test.ts b/tests/v11-automation-monitoring-cli.test.ts deleted file mode 100644 index 8566613..0000000 --- a/tests/v11-automation-monitoring-cli.test.ts +++ /dev/null @@ -1,451 +0,0 @@ -import { execFile } from 'node:child_process'; -import fs from 'node:fs'; -import http from 'node:http'; -import os from 'node:os'; -import path from 'node:path'; -import { promisify } from 'node:util'; -import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it } from 'vitest'; -import { createGCoordinatorServer } from '../src/server/app.js'; -import { interpolateShellCommandSafe } from '../src/server/automation/template.js'; -import { MockSshServer } from './helpers/mock-ssh-server.js'; - -const execFileAsync = promisify(execFile); -const CLI_PATH = path.resolve('dist/cli/gcoord.js'); -const cleanups: Array<() => Promise | void> = []; - -class CookieJar { - private cookies = new Map(); - updateFrom(res: Response): void { - const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie; - const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : []; - for (const line of rawList) { - const first = line.split(';')[0] ?? ''; - const eq = first.indexOf('='); - if (eq > 0) { - const name = first.slice(0, eq).trim(); - const val = first.slice(eq + 1).trim(); - if (val === '') this.cookies.delete(name); - else this.cookies.set(name, val); - } - } - } - header(): string { - return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; '); - } -} - -afterEach(async () => { - while (cleanups.length > 0) { - await cleanups.pop()!(); - } -}); - -describe('v1.1 Monitoring, Prometheus /metrics, Systems, Workflows, Broadcast History & CLI Tools', () => { - it('covers template Go preservation, Prometheus /metrics, rollup/probe history, systems inputs/cancel, http/notify workflows, broadcast export, and CLI tools', async () => { - // 1. Go template preservation vs safe shell quoting - const goCmd = interpolateShellCommandSafe( - "docker ps --format '{{.Names}}' --filter name={{inputs.filter}}", - { inputs: { filter: "web'; rm -rf /; #" } }, - ); - expect(goCmd).toContain('{{.Names}}'); - expect(goCmd).toContain("'web'\\''; rm -rf /; #'"); - - let httpStepHit: Record | null = null; - const targetHttp = http.createServer((req, res) => { - if (req.url === '/probe') { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.end('probe-healthy-ok'); - return; - } - if (req.url === '/wf-hook' && req.method === 'POST') { - const chunks: Buffer[] = []; - req.on('data', (c: Buffer) => chunks.push(c)); - req.on('end', () => { - httpStepHit = { - auth: req.headers.authorization, - body: Buffer.concat(chunks).toString('utf8'), - }; - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ accepted: true })); - }); - return; - } - res.writeHead(404).end(); - }); - await new Promise((r) => targetHttp.listen(0, '127.0.0.1', () => r())); - cleanups.push(() => new Promise((r) => targetHttp.close(() => r()))); - const httpPort = (targetHttp.address() as { port: number }).port; - - let lastActionCmd = ''; - const mock = new MockSshServer({ - username: 'ops', - os: 'Linux', - onExec: (cmd) => { - lastActionCmd = cmd; - if (cmd.includes('SYSTEMD_DISCOVER')) { - return { stdout: 'demo.service\n', exitCode: 0 }; - } - if (cmd.includes('SYSTEMD_SHOW')) { - return { - stdout: JSON.stringify({ - Id: 'demo.service', - ActiveState: 'active', - SubState: 'running', - FragmentPath: '/etc/systemd/system/demo.service', - DropInPaths: '/etc/systemd/system/demo.service.d/override.conf', - }), - exitCode: 0, - }; - } - if (cmd.includes('echo-secret-action')) { - return { stdout: 'action-ok\n', exitCode: 0 }; - } - return null; - }, - }); - await mock.start(); - cleanups.push(() => mock.close()); - - const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-auto-')); - const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-cli-work-')); - const server = await createGCoordinatorServer({ - dataDir, - port: 0, - host: '127.0.0.1', - publicDir: path.resolve('dist/public'), - watchConfig: false, - }); - let closedServer = false; - cleanups.push(async () => { - if (!closedServer) await server.close(); - fs.rmSync(dataDir, { recursive: true, force: true }); - fs.rmSync(workDir, { recursive: true, force: true }); - }); - - const baseUrl = `http://127.0.0.1:${server.port}`; - const jar = new CookieJar(); - let csrfToken = ''; - const api = async ( - pathname: string, - opts: { method?: string; body?: unknown; raw?: boolean; safeMode?: boolean } = {}, - ) => { - const headers: Record = {}; - if (jar.header()) headers.Cookie = jar.header(); - if (opts.body !== undefined) headers['Content-Type'] = 'application/json'; - if (csrfToken) headers['X-CSRF-Token'] = csrfToken; - if (opts.safeMode) headers['X-GCoord-Safe-Mode'] = '1'; - const res = await fetch(`${baseUrl}${pathname}`, { - method: opts.method ?? 'GET', - headers, - body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, - }); - jar.updateFrom(res); - if (opts.raw) { - return { status: res.status, text: await res.text(), data: {} as Record }; - } - const data = (await res.json().catch(() => ({}))) as Record; - return { status: res.status, data, text: '' }; - }; - - const bootInfo = await api('/api/auth/bootstrap'); - const totp = new OTPAuth.TOTP({ - issuer: 'GCoordinator', - label: 'admin', - algorithm: 'SHA1', - digits: 6, - period: 30, - secret: OTPAuth.Secret.fromBase32(String(bootInfo.data.secretBase32)), - }); - const bootRes = await api('/api/auth/bootstrap', { - method: 'POST', - body: { - username: 'admin', - password: 'automation-v11-password!', - totpCode: totp.generate(), - securityPreset: 'relaxed', - }, - }); - csrfToken = String(bootRes.data.csrfToken); - - await api('/api/vault/init', { method: 'POST', body: {} }); - const kp = await api('/api/vault/generate-ed25519', { - method: 'POST', - body: { id: 'main-key', name: 'Main Key' }, - }); - mock.authorizedKeys.push(String((kp.data.credential as { publicKey: string }).publicKey)); - await api('/api/vault/credentials', { - method: 'POST', - body: { id: 'wf-api-tok', name: 'WF API', type: 'api-token', token: 'Bearer wf-tok-secret' }, - }); - - await api('/api/auth/security-policy', { - method: 'PUT', - body: { egressAllowedCidrs: ['127.0.0.1/32'] }, - }); - - // Prometheus /metrics disabled initially -> 404; rotate-token enables & secures it - expect((await fetch(`${baseUrl}/metrics`)).status).toBe(404); - const promRot = await api('/api/config/prometheus-token', { - method: 'POST', - body: { enable: true }, - }); - expect(promRot.status).toBe(200); - const promToken = String(promRot.data.token); - expect(promToken.length).toBeGreaterThan(20); - expect((await fetch(`${baseUrl}/metrics`)).status).toBe(401); - const promOk = await fetch(`${baseUrl}/metrics`, { - headers: { Authorization: `Bearer ${promToken}` }, - }); - expect(promOk.status).toBe(200); - const promText = await promOk.text(); - expect(promText).toContain('gcoordinator_tunnels_active'); - expect(promText).toContain('gcoordinator_process_resident_memory_bytes'); - - // Register server with hub HTTP probe - await api('/api/servers', { - method: 'POST', - body: { - id: 'srv-1', - name: 'Server 1', - host: '127.0.0.1', - port: mock.port, - username: 'ops', - credentialId: 'main-key', - pollIntervalSec: 120, - probes: [ - { - id: 'web-hp', - type: 'http', - url: `http://127.0.0.1:${httpPort}/probe`, - from: 'hub', - expectedStatus: 200, - bodyIncludes: 'probe-healthy-ok', - enabled: true, - }, - ], - }, - }); - await api('/api/servers/srv-1/reconnect', { method: 'POST' }); - await api('/api/servers/srv-1/tofu/approve', { - method: 'POST', - body: { fingerprint: mock.hostFingerprint }, - }); - - // On-demand probe run + probe history query - const runProbe = await api('/api/servers/srv-1/probes/web-hp/run', { method: 'POST', body: {} }); - expect(runProbe.status).toBe(200); - expect((runProbe.data.sample as { ok: boolean }).ok).toBe(true); - const probeHist = await api('/api/servers/srv-1/probes/history?range=1h'); - expect(probeHist.status).toBe(200); - expect((probeHist.data.samples as unknown[]).length).toBeGreaterThanOrEqual(1); - - // Rollup partial-bucket upsert check: seed older bucket raw rows across two flushes - const oldBucketTs = Math.floor((Date.now() - 2 * 3600_000) / 3600_000) * 3600_000; - server.db - .prepare( - `INSERT INTO metrics_raw (ts, server_id, cpu_pct, mem_used_mb, mem_total_mb, net_rx_bps, net_tx_bps, load_1m, uptime_sec) - VALUES (?, 'srv-1', 20, 500, 1000, 1000, 2000, 0.5, 100)`, - ) - .run(oldBucketTs + 10_000); - server.db - .prepare( - `INSERT INTO metrics_disks (ts, server_id, mount_point, fs_type, used_mb, total_mb, used_pct) - VALUES (?, 'srv-1', '/', 'ext4', 4000, 10000, 40)`, - ) - .run(oldBucketTs + 10_000); - server.monitoringService.runMaintenance(); - - server.db - .prepare( - `INSERT INTO metrics_raw (ts, server_id, cpu_pct, mem_used_mb, mem_total_mb, net_rx_bps, net_tx_bps, load_1m, uptime_sec) - VALUES (?, 'srv-1', 80, 700, 1000, 3000, 4000, 1.5, 200)`, - ) - .run(oldBucketTs + 20_000); - server.monitoringService.runMaintenance(); - - const rollupRow = server.db - .prepare( - `SELECT cpu_min, cpu_max, net_rx_avg_bps, disk_max_pct FROM metrics_rollup - WHERE server_id = 'srv-1' AND granularity = '1h' AND bucket_ts = ?`, - ) - .get(oldBucketTs) as { - cpu_min: number; - cpu_max: number; - net_rx_avg_bps: number; - disk_max_pct: number; - }; - expect(rollupRow.cpu_min).toBe(20); - expect(rollupRow.cpu_max).toBe(80); - expect(rollupRow.disk_max_pct).toBe(40); - expect(rollupRow.net_rx_avg_bps).toBe(2000); - - // Custom System with systemd editableFiles + action inputs[] secret redaction + Safe-Mode stream cancel - await api('/api/config/file', { - method: 'PUT', - body: { - path: 'systems/sys-v11.json', - content: JSON.stringify({ - id: 'sys-v11', - name: 'System v1.1 Test', - cacheTtlSec: 30, - params: [], - discovery: { type: 'command', command: 'echo SYSTEMD_DISCOVER', parser: 'lines' }, - status: { command: 'echo SYSTEMD_SHOW', parser: 'json' }, - actions: [ - { - id: 'secret-act', - label: 'Secret Action', - scope: 'item', - mode: 'oneshot', - inputs: [{ name: 'apiSecret', type: 'secret', required: true }], - command: 'echo echo-secret-action "$GCOORD_INPUT_APISECRET"', - }, - ], - editableFiles: [], - }), - }, - }); - await api('/api/systems/sys-v11/servers/srv-1/attach', { method: 'PUT', body: { params: {} } }); - const sysSnap = await api('/api/systems/sys-v11?refresh=1&serverId=srv-1'); - const items = (sysSnap.data.snapshots as Array<{ items: Array<{ editableFiles: string[] }> }>)[0]!.items; - expect(items[0]!.editableFiles).toContain('/etc/systemd/system/demo.service'); - expect(items[0]!.editableFiles).toContain('/etc/systemd/system/demo.service.d/override.conf'); - - const actRun = await api('/api/systems/sys-v11/servers/srv-1/actions/secret-act', { - method: 'POST', - body: { itemName: 'demo.service', inputs: { apiSecret: 'super-secret-input-val' } }, - }); - expect(actRun.status).toBe(200); - expect(lastActionCmd).toContain('echo-secret-action'); - const sysAudit = await api('/api/audit?action=system.action&limit=5'); - expect(JSON.stringify(sysAudit.data.items)).not.toContain('super-secret-input-val'); - - // Safe Mode stream cancel exemption works even cleanly - const safeCancel = await api('/api/systems/streams/nonexistent-job/cancel', { - method: 'POST', - safeMode: true, - }); - expect(safeCancel.status).toBe(200); - - // Workflow with http step + secret input masking + lazy step logs - await api('/api/workflows', { - method: 'POST', - body: { - id: 'wf-v11-http', - name: 'Workflow v1.1', - enabled: true, - trigger: { type: 'manual' }, - overlapPolicy: 'skip', - display: { mode: 'log' }, - inputs: [{ name: 'secretTok', type: 'secret', required: true }], - steps: [ - { - id: 'exec-mask', - type: 'exec', - target: { serverId: 'srv-1' }, - command: 'echo got={{inputs.secretTok}}', - }, - { - id: 'call-http', - type: 'http', - dependsOn: ['exec-mask'], - url: `http://127.0.0.1:${httpPort}/wf-hook`, - method: 'POST', - secretRef: 'wf-api-tok', - body: '{"event":"done"}', - expectedStatus: 200, - }, - ], - }, - }); - const wfRun = await api('/api/workflows/wf-v11-http/run', { - method: 'POST', - body: { inputs: { secretTok: 'MY-TOP-SECRET-VALUE-77' } }, - }); - expect(wfRun.status).toBe(202); - const runId = String(wfRun.data.runId); - - for (let i = 0; i < 30; i++) { - const st = await api(`/api/workflows/runs/${runId}`); - if ((st.data.run as { status: string }).status !== 'running' && (st.data.run as { status: string }).status !== 'queued') { - expect((st.data.run as { status: string }).status).toBe('succeeded'); - break; - } - await new Promise((r) => setTimeout(r, 80)); - } - expect(httpStepHit).not.toBeNull(); - const stepLogRes = await api(`/api/workflows/runs/${runId}/steps/exec-mask/logs`); - expect(stepLogRes.status).toBe(200); - expect(JSON.stringify(stepLogRes.data)).not.toContain('MY-TOP-SECRET-VALUE-77'); - - // Broadcast history + JSON/CSV export - const bcastRes = await api('/api/workflows/broadcast', { - method: 'POST', - body: { command: 'echo broadcast-v11', target: { serverIds: ['srv-1'] } }, - }); - expect(bcastRes.status).toBe(202); - const jobId = String((bcastRes.data.job as { jobId: string }).jobId); - for (let i = 0; i < 20; i++) { - const pollB = await api(`/api/workflows/broadcast/${jobId}`); - if ((pollB.data.job as { done: boolean }).done) break; - await new Promise((r) => setTimeout(r, 60)); - } - const histRes = await api('/api/workflows/broadcast/history?limit=10'); - expect(histRes.status).toBe(200); - expect((histRes.data.jobs as Array<{ jobId: string }>).some((j) => j.jobId === jobId)).toBe(true); - const bCsv = await api(`/api/workflows/broadcast/${jobId}/export?format=csv`, { raw: true }); - expect(bCsv.status).toBe(200); - expect(bCsv.text).toContain('srv-1'); - - // Scheduled Backup runNow - const schedRun = await api('/api/backup/schedule/run', { method: 'POST', body: {} }); - expect(schedRun.status).toBe(200); - expect(schedRun.data.ok).toBe(true); - - // Close server before offline CLI tests - await server.close(); - closedServer = true; - - const statusOut = await execFileAsync(process.execPath, [ - CLI_PATH, - 'status', - '--data-dir', - dataDir, - '--json', - ]); - const stJson = JSON.parse(statusOut.stdout) as { bootstrapped: boolean; auditLogRows: number }; - expect(stJson.bootstrapped).toBe(true); - expect(stJson.auditLogRows).toBeGreaterThan(0); - - const newPwFile = path.join(workDir, 'newpw.txt'); - fs.writeFileSync(newPwFile, 'offline-reset-password-2026!', { mode: 0o600 }); - const resetPwOut = await execFileAsync(process.execPath, [ - CLI_PATH, - 'reset-password', - '--data-dir', - dataDir, - '--password-file', - newPwFile, - ]); - expect(resetPwOut.stdout).toContain('reset cleanly'); - - const reset2faOut = await execFileAsync(process.execPath, [ - CLI_PATH, - 'reset-2fa', - '--data-dir', - dataDir, - '--json', - ]); - expect((JSON.parse(reset2faOut.stdout) as { reset: boolean }).reset).toBe(true); - - const panicOut = await execFileAsync(process.execPath, [ - CLI_PATH, - 'panic-lock', - '--data-dir', - dataDir, - ]); - expect(panicOut.stdout).toContain('Panic Lock engaged cleanly'); - expect(fs.existsSync(path.join(dataDir, 'vault.enc.panic-locked'))).toBe(true); - }); -}); diff --git a/tests/v11-security-hardening.test.ts b/tests/v11-security-hardening.test.ts deleted file mode 100644 index ef0840a..0000000 --- a/tests/v11-security-hardening.test.ts +++ /dev/null @@ -1,388 +0,0 @@ -import fs from 'node:fs'; -import http from 'node:http'; -import os from 'node:os'; -import path from 'node:path'; -import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it } from 'vitest'; -import WebSocket from 'ws'; -import { redactSecrets } from '../src/server/ai/redactor.js'; -import { createGCoordinatorServer } from '../src/server/app.js'; -import { resolveRuntimeLimits } from '../src/server/config/runtime-limits.js'; -import { openDatabase } from '../src/server/db/database.js'; -import { AuditService } from '../src/server/security/audit.js'; -import { - EgressBlockedError, - assertEgressUrlAllowed, - fetchWithEgressGuard, -} from '../src/server/security/egress-guard.js'; -import { RateLimiter } from '../src/server/security/guards.js'; -import { EmergencyRecoveryService } from '../src/server/security/recovery-store.js'; -import { VaultService } from '../src/server/security/vault.js'; -import { AlertChannelSchema } from '../src/shared/schemas/alerts.schema.js'; - -const cleanups: Array<() => Promise | void> = []; - -class CookieJar { - private cookies = new Map(); - updateFrom(res: Response): void { - const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie; - const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : []; - for (const line of rawList) { - const first = line.split(';')[0] ?? ''; - const eq = first.indexOf('='); - if (eq > 0) { - const name = first.slice(0, eq).trim(); - const val = first.slice(eq + 1).trim(); - if (val === '') this.cookies.delete(name); - else this.cookies.set(name, val); - } - } - } - header(): string { - return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; '); - } -} - -afterEach(async () => { - while (cleanups.length > 0) { - await cleanups.pop()!(); - } -}); - -describe('v1.1 Security Hardening Suite', () => { - it('enforces Zero-Trust Egress Guard, CIDR allowlist, and redirect blocking', async () => { - await expect(assertEgressUrlAllowed('http://127.0.0.1:8080/api')).rejects.toBeInstanceOf( - EgressBlockedError, - ); - await expect( - assertEgressUrlAllowed('http://169.254.169.254/latest/meta-data/'), - ).rejects.toBeInstanceOf(EgressBlockedError); - await expect(assertEgressUrlAllowed('http://10.0.0.5/hook')).rejects.toBeInstanceOf( - EgressBlockedError, - ); - - let internalRedirectFollowed = false; - const srv = http.createServer((req, res) => { - if (req.url === '/ok') { - res.writeHead(200, { 'Content-Type': 'text/plain' }); - res.end('hello-egress'); - return; - } - if (req.url === '/redir') { - res.writeHead(302, { Location: `http://127.0.0.1:${port}/never-hit` }); - res.end(); - return; - } - if (req.url === '/never-hit') { - internalRedirectFollowed = true; - res.writeHead(200).end('leaked'); - return; - } - res.writeHead(404).end(); - }); - await new Promise((r) => srv.listen(0, '127.0.0.1', () => r())); - cleanups.push(() => new Promise((r) => srv.close(() => r()))); - const port = (srv.address() as { port: number }).port; - - const okRes = await fetchWithEgressGuard( - `http://127.0.0.1:${port}/ok`, - { method: 'GET' }, - { allowedCidrs: ['127.0.0.1/32'], timeoutMs: 3000 }, - ); - expect(okRes.status).toBe(200); - expect(await okRes.text()).toBe('hello-egress'); - - await expect( - fetchWithEgressGuard( - `http://127.0.0.1:${port}/redir`, - { method: 'GET' }, - { allowedCidrs: ['127.0.0.1/32'], timeoutMs: 3000 }, - ), - ).rejects.toThrow(); - expect(internalRedirectFollowed).toBe(false); - }); - - it('persists SQLite RateLimiter lockouts across instances and removes legacy recovery passwords', () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-rl-')); - cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true })); - const dbPath = path.join(dir, 'gcoord.db'); - const db1 = openDatabase(dbPath); - const rl1 = new RateLimiter({ db: db1 }); - for (let i = 0; i < 6; i++) { - rl1.recordFailure('login', '198.51.100.77'); - } - expect(rl1.check('login', '198.51.100.77').allowed).toBe(false); - db1.close(); - - const db2 = openDatabase(dbPath); - const rl2 = new RateLimiter({ db: db2 }); - expect(rl2.check('login', '198.51.100.77').allowed).toBe(false); - db2.close(); - - // Passwordless emergency recovery + chmod 0600 Vault keyfile + seal() - const vault = new VaultService(path.join(dir, 'vault.enc'), { - keyFilePath: path.join(dir, 'vault.key'), - allowLocalKeyFile: true, - }); - vault.initRuntime({ autoCreateIfMissing: true }); - const keyMode = fs.statSync(path.join(dir, 'vault.key')).mode & 0o777; - expect(keyMode).toBe(0o600); - vault.unlockForModifications(); - - vault.upsertCredential({ - id: 'wh-1', - name: 'Webhook Sec', - type: 'webhook-secret', - secret: 'super-secret-wh-value', - }); - - const recovery = new EmergencyRecoveryService(dir); - const bundle = recovery.syncState({ - enabled: true, - vault, - username: 'admin', - passwordMetaList: [{ id: 'pw-1', label: 'Primary', createdAt: Date.now() }], - }); - expect(bundle).not.toBeNull(); - const recMode = fs.statSync(recovery.filePath).mode & 0o777; - expect(recMode).toBe(0o600); - const serialized = fs.readFileSync(recovery.filePath, 'utf8'); - expect(serialized).not.toContain('passwordHash'); - expect(serialized).not.toContain('plaintext'); - - let panicTriggered = false; - vault.onPanicLock(() => { - panicTriggered = true; - }); - vault.seal(); - expect(vault.sealState).toBe('sealed'); - expect(vault.isRuntimeReady).toBe(false); - expect(panicTriggered).toBe(false); - - const keyHex = fs.readFileSync(path.join(dir, 'vault.key'), 'utf8').trim(); - vault.unlock(keyHex); - expect(vault.sealState).toBe('unlocked'); - expect(vault.isRuntimeReady).toBe(true); - }); - - it('scales AI redactor linearly O(n) on huge malformed inputs and strips truncated PEM & Vault secrets', () => { - const bigPem = `-----BEGIN RSA PRIVATE KEY-----\n${'MIIEowIBAAKCAQEA'.repeat(8000)}\n`; - const sampleJson = `{"password":"my-db-pass-123","api_key":"sk-live-secret-999","token":"tok-abc"}`; - const payload = `${bigPem}\n${sampleJson}\nAuthorization: Bearer topsecretbearer\n`; - - const started = Date.now(); - const res = redactSecrets(payload, ['topsecretbearer', 'xy99']); - const elapsed = Date.now() - started; - - expect(elapsed).toBeLessThan(1000); - expect(res.text).toContain('[REDACTED_PRIVATE_KEY]'); - expect(res.text).not.toContain('my-db-pass-123'); - expect(res.text).not.toContain('sk-live-secret-999'); - expect(res.text).not.toContain('topsecretbearer'); - expect(res.redactedCount).toBeGreaterThanOrEqual(3); - }); - - it('enforces idle timeout, real-time WS revocation, audit CSV formula neutralization, alert security events & throttle presets', async () => { - const low = resolveRuntimeLimits('low-resource'); - const bal = resolveRuntimeLimits('balanced'); - const unth = resolveRuntimeLimits('unthrottled'); - expect(low.maxConcurrentMetricPolls).toBeLessThan(bal.maxConcurrentMetricPolls); - expect(unth.maxConcurrentMetricPolls).toBe(0); // 0 = unthrottled unlimited polls - expect(low.maxConcurrentWorkflows).toBeLessThan(bal.maxConcurrentWorkflows); - expect(bal.maxConcurrentWorkflows).toBeLessThan(unth.maxConcurrentWorkflows); - expect(low.argon2Concurrency).toBe(1); - - // Non-webhook-secret creds are rejected by alerts test or config runtime check cleanly; schema parses valid channel - expect(() => - AlertChannelSchema.parse({ - id: 'ch1', - name: 'Ch', - type: 'generic', - url: 'https://hooks.example.com/1', - secretRef: 'wh-sec', - }), - ).not.toThrow(); - - let receivedWebhook: Record | null = null; - const whSrv = http.createServer((req, res) => { - const chunks: Buffer[] = []; - req.on('data', (c: Buffer) => chunks.push(c)); - req.on('end', () => { - try { - receivedWebhook = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record; - } catch { - receivedWebhook = { raw: Buffer.concat(chunks).toString('utf8') }; - } - res.writeHead(200).end('ok'); - }); - }); - await new Promise((r) => whSrv.listen(0, '127.0.0.1', () => r())); - cleanups.push(() => new Promise((r) => whSrv.close(() => r()))); - const whPort = (whSrv.address() as { port: number }).port; - - const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-sec-e2e-')); - const server = await createGCoordinatorServer({ - dataDir, - port: 0, - host: '127.0.0.1', - publicDir: path.resolve('dist/public'), - watchConfig: false, - }); - cleanups.push(async () => { - await server.close(); - fs.rmSync(dataDir, { recursive: true, force: true }); - }); - - const baseUrl = `http://127.0.0.1:${server.port}`; - const jar = new CookieJar(); - let csrfToken = ''; - const api = async ( - pathname: string, - opts: { method?: string; body?: unknown; raw?: boolean } = {}, - ) => { - const headers: Record = {}; - if (jar.header()) headers.Cookie = jar.header(); - if (opts.body !== undefined) headers['Content-Type'] = 'application/json'; - if (csrfToken) headers['X-CSRF-Token'] = csrfToken; - const res = await fetch(`${baseUrl}${pathname}`, { - method: opts.method ?? 'GET', - headers, - body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, - }); - jar.updateFrom(res); - if (opts.raw) { - return { status: res.status, text: await res.text(), data: {} as Record }; - } - const data = (await res.json().catch(() => ({}))) as Record; - return { status: res.status, data, text: '' }; - }; - - const bootInfo = await api('/api/auth/bootstrap'); - const totp = new OTPAuth.TOTP({ - issuer: 'GCoordinator', - label: 'admin', - algorithm: 'SHA1', - digits: 6, - period: 30, - secret: OTPAuth.Secret.fromBase32(String(bootInfo.data.secretBase32)), - }); - const bootRes = await api('/api/auth/bootstrap', { - method: 'POST', - body: { - username: 'admin', - password: 'v11-hardening-password!', - totpCode: totp.generate(), - securityPreset: 'relaxed', - }, - }); - expect(bootRes.status).toBe(201); - csrfToken = String(bootRes.data.csrfToken); - - // Initialize Vault + allow localhost egress for webhook test - await api('/api/vault/init', { method: 'POST', body: {} }); - await api('/api/vault/credentials', { - method: 'POST', - body: { id: 'tok-not-wh', name: 'API Token', type: 'api-token', token: 'bearer-xyz' }, - }); - await api('/api/vault/credentials', { - method: 'POST', - body: { id: 'wh-valid', name: 'Webhook', type: 'webhook-secret', secret: 'wh-tok-1' }, - }); - await api('/api/auth/security-policy', { - method: 'PUT', - body: { egressAllowedCidrs: ['127.0.0.1/32'], sessionIdleTimeoutMin: 60 }, - }); - - // Reject referencing non-webhook-secret credential in channel test - await api('/api/alerts/config', { - method: 'PUT', - body: { - channels: [ - { - id: 'bad-ch', - name: 'Bad Channel', - type: 'generic', - url: `http://127.0.0.1:${whPort}/hook`, - secretRef: 'tok-not-wh', - enabled: true, - }, - { - id: 'good-ch', - name: 'Good Channel', - type: 'generic', - url: `http://127.0.0.1:${whPort}/hook`, - secretRef: 'wh-valid', - enabled: true, - }, - ], - rules: [ - { - id: 'sec-lockout', - name: 'Auth Lockout Event', - kind: 'security-event', - events: ['auth.lockout'], - severity: 'critical', - forConsecutivePolls: 1, - cooldownSec: 0, - channelIds: ['good-ch'], - enabled: true, - }, - ], - }, - }); - const badTest = await api('/api/alerts/channels/bad-ch/test', { method: 'POST' }); - expect(badTest.status === 400 || badTest.data.ok === false).toBe(true); - - // Trigger security-event alert -> webhook receives notification - await server.alertEngine.emitSecurityEvent('auth.lockout', { - message: 'Repeated login failure from 203.0.113.9', - }); - expect(receivedWebhook).not.toBeNull(); - - // Audit formula-injection neutralization + filtering + CSV/NDJSON export - server.auditService.log({ - action: 'custom.formula', - actorIp: '127.0.0.1', - target: '=CMD|calc', - status: 'denied', - details: 'formula-needle', - }); - const filteredAudit = await api('/api/audit?action=custom.formula&status=denied&q=formula-needle'); - expect(filteredAudit.status).toBe(200); - expect(filteredAudit.data.total).toBe(1); - - const csvRes = await api('/api/audit/export?format=csv&action=custom.formula', { raw: true }); - expect(csvRes.status).toBe(200); - expect(csvRes.text).toContain('"\'=CMD|calc"'); - - const ndjsonRes = await api('/api/audit/export?format=ndjson&action=custom.formula', { raw: true }); - expect(ndjsonRes.status).toBe(200); - const firstRow = JSON.parse(ndjsonRes.text.trim().split('\n')[0]!) as { action: string }; - expect(firstRow.action).toBe('custom.formula'); - - // Real-time WS close with 4001 on logout/revocation - const wsCloseCode = await new Promise((resolve, reject) => { - const ws = new WebSocket(`ws://127.0.0.1:${server.port}/ws`, { - headers: { Cookie: jar.header() }, - }); - ws.once('open', () => { - void api('/api/auth/logout', { method: 'POST' }); - }); - ws.once('close', (code) => resolve(code)); - ws.once('error', reject); - }); - expect(wsCloseCode).toBe(4001); - - // Log back in and verify sliding sessionIdleTimeoutMin invalidates idle session - await new Promise((r) => setTimeout(r, 20)); - const reLogin = await api('/api/auth/login', { - method: 'POST', - body: { username: 'admin', passwords: ['v11-hardening-password!'], codes: [] }, - }); - expect(reLogin.status).toBe(200); - server.db.prepare('UPDATE sessions SET last_seen_at = ?').run(Date.now() - 120 * 60_000); - const afterIdle = await api('/api/auth/status'); - expect(afterIdle.status).toBe(200); - expect(afterIdle.data.authenticated).toBe(false); - }); -}); diff --git a/tests/v11-ssh-proxy-sftp.test.ts b/tests/v11-ssh-proxy-sftp.test.ts deleted file mode 100644 index 5768e1e..0000000 --- a/tests/v11-ssh-proxy-sftp.test.ts +++ /dev/null @@ -1,361 +0,0 @@ -import fs from 'node:fs'; -import net from 'node:net'; -import os from 'node:os'; -import path from 'node:path'; -import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it } from 'vitest'; -import { createGCoordinatorServer } from '../src/server/app.js'; -import { formatRemoteCd } from '../src/server/ssh/pty-manager.js'; -import { parseOpenSshConfig } from '../src/server/ssh/ssh-config-import.js'; -import { MockSshServer } from './helpers/mock-ssh-server.js'; - -const cleanups: Array<() => Promise | void> = []; - -class CookieJar { - private cookies = new Map(); - updateFrom(res: Response): void { - const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie; - const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : []; - for (const line of rawList) { - const first = line.split(';')[0] ?? ''; - const eq = first.indexOf('='); - if (eq > 0) { - const name = first.slice(0, eq).trim(); - const val = first.slice(eq + 1).trim(); - if (val === '') this.cookies.delete(name); - else this.cookies.set(name, val); - } - } - } - header(): string { - return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; '); - } -} - -afterEach(async () => { - while (cleanups.length > 0) { - await cleanups.pop()!(); - } -}); - -describe('v1.1 SSH Import, Multi-Algo known_hosts, PTY Security/.cast, SFTP v1.1 & Isolated Proxy / SOCKS5', () => { - it('parses & imports OpenSSH config, manages multi-algo known_hosts, enforces PTY/SFTP v1.1 ops, and validates proxy/SOCKS5/TTL', async () => { - const seenExecs: string[] = []; - const mock = new MockSshServer({ - username: 'ops', - os: 'Linux', - allowTcpForward: true, - onExec: (cmd) => { - seenExecs.push(cmd); - if (cmd.startsWith('chown ')) { - return { stdout: '', exitCode: 0 }; - } - if (cmd.startsWith('find ') && cmd.includes('needle')) { - return { stdout: '/sub/needle.conf\n', exitCode: 0 }; - } - return null; - }, - }); - await mock.start(); - cleanups.push(() => mock.close()); - - // Populate mock sftp root files - fs.writeFileSync(path.join(mock.sftpRootDir, 'alpha.log'), 'hello-alpha\n'); - fs.mkdirSync(path.join(mock.sftpRootDir, 'sub'), { recursive: true }); - fs.writeFileSync(path.join(mock.sftpRootDir, 'sub', 'needle.conf'), 'port=8080\n'); - const outsideSecret = path.join(os.tmpdir(), `outside-secret-${Date.now()}.txt`); - fs.writeFileSync(outsideSecret, 'TOP_SECRET'); - cleanups.push(() => fs.rmSync(outsideSecret, { force: true })); - fs.symlinkSync(outsideSecret, path.join(mock.sftpRootDir, 'escape-link')); - - const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-ssh-')); - // First start WITHOUT proxyPort to test strict PROXY_ORIGIN_ISOLATION_REQUIRED enforcement - const serverNoIso = await createGCoordinatorServer({ - dataDir, - port: 0, - host: '127.0.0.1', - publicDir: path.resolve('dist/public'), - watchConfig: false, - }); - - const baseUrl = `http://127.0.0.1:${serverNoIso.port}`; - const jar = new CookieJar(); - let csrfToken = ''; - const api = async ( - pathname: string, - opts: { method?: string; body?: unknown; raw?: boolean } = {}, - ) => { - const headers: Record = {}; - if (jar.header()) headers.Cookie = jar.header(); - if (opts.body !== undefined) headers['Content-Type'] = 'application/json'; - if (csrfToken) headers['X-CSRF-Token'] = csrfToken; - const res = await fetch(`${baseUrl}${pathname}`, { - method: opts.method ?? 'GET', - headers, - body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, - }); - jar.updateFrom(res); - if (opts.raw) { - return { status: res.status, text: await res.text(), data: {} as Record }; - } - const data = (await res.json().catch(() => ({}))) as Record; - return { status: res.status, data, text: '' }; - }; - - try { - const bootInfo = await api('/api/auth/bootstrap'); - const totp = new OTPAuth.TOTP({ - issuer: 'GCoordinator', - label: 'admin', - algorithm: 'SHA1', - digits: 6, - period: 30, - secret: OTPAuth.Secret.fromBase32(String(bootInfo.data.secretBase32)), - }); - const bootRes = await api('/api/auth/bootstrap', { - method: 'POST', - body: { - username: 'admin', - password: 'ssh-proxy-v11-password!', - totpCode: totp.generate(), - securityPreset: 'relaxed', - }, - }); - expect(bootRes.status).toBe(201); - csrfToken = String(bootRes.data.csrfToken); - - await api('/api/vault/init', { method: 'POST', body: {} }); - const genKey = await api('/api/vault/generate-ed25519', { - method: 'POST', - body: { id: 'ssh-main', name: 'Main Key' }, - }); - mock.authorizedKeys.push( - String((genKey.data.credential as { publicKey: string }).publicKey), - ); - - // OpenSSH parser + /api/servers/import-ssh-config preview & apply - const sshConfigText = [ - 'Host *', - ' User ignored', - 'Host bastion', - ' HostName 127.0.0.1', - ` Port ${mock.port}`, - ' User ops', - 'Host app-behind-bastion', - ' HostName 127.0.0.1', - ` Port ${mock.port}`, - ' User ops', - ' ProxyJump bastion', - ].join('\n'); - const parsed = parseOpenSshConfig(sshConfigText); - expect(parsed.entries.map((e) => e.alias)).toEqual(['bastion', 'app-behind-bastion']); - - const prevRes = await api('/api/servers/import-ssh-config', { - method: 'POST', - body: { configText: sshConfigText, apply: false }, - }); - expect(prevRes.status).toBe(200); - expect((prevRes.data.createdIds as string[]).length).toBe(0); - - const applyRes = await api('/api/servers/import-ssh-config', { - method: 'POST', - body: { configText: sshConfigText, defaultCredentialId: 'ssh-main', apply: true }, - }); - expect(applyRes.status).toBe(201); - expect(applyRes.data.createdIds).toEqual(['bastion', 'app-behind-bastion']); - - // Reconnect + approve TOFU on bastion - await api('/api/servers/bastion/reconnect', { method: 'POST' }); - const approve = await api('/api/servers/bastion/tofu/approve', { - method: 'POST', - body: { fingerprint: mock.hostFingerprint }, - }); - expect(approve.status).toBe(200); - - // Multi-algorithm known_hosts CRUD - const curKnown = serverNoIso.knownHosts.listKnownHosts(); - serverNoIso.knownHosts.replaceAllKnownHosts([ - ...curKnown, - { - hostPort: `127.0.0.1:${mock.port}`, - algorithm: 'ssh-rsa', - fingerprint: 'SHA256:fakeRsaFp', - }, - ]); - const khList = await api('/api/servers/known-hosts'); - expect(khList.status).toBe(200); - const matching = (khList.data.knownHosts as Array<{ hostPort: string; algorithm: string }>).filter( - (x) => x.hostPort === `127.0.0.1:${mock.port}`, - ); - expect(matching.length).toBeGreaterThanOrEqual(2); - - const delRsa = await api( - `/api/servers/known-hosts?hostPort=${encodeURIComponent(`127.0.0.1:${mock.port}`)}&algorithm=ssh-rsa`, - { method: 'DELETE' }, - ); - expect(delRsa.status).toBe(200); - - // PTY cwd injection defense (control chars blocked 400 + single-quoted shell cwd) + .cast export + reconnect - expect(formatRemoteCd("/tmp'; rm -rf /")).toBe("cd -- '/tmp'\\''; rm -rf /'"); - expect(formatRemoteCd('~/My Dir')).toBe('cd -- "$HOME/"\'My Dir\''); - - const badCtrlPty = await api('/api/terminal/sessions', { - method: 'POST', - body: { serverId: 'bastion', cwd: '/tmp\nbad', cols: 80, rows: 24 }, - }); - expect(badCtrlPty.status).toBe(400); - - const quotedCwdPty = await api('/api/terminal/sessions', { - method: 'POST', - body: { serverId: 'bastion', cwd: '/tmp; rm -rf /', cols: 80, rows: 24 }, - }); - expect(quotedCwdPty.status).toBe(201); - const qPtyId = String((quotedCwdPty.data.session as { sessionId: string }).sessionId); - await new Promise((r) => setTimeout(r, 80)); - const qExport = await api(`/api/terminal/sessions/${qPtyId}/export?format=plain`, { raw: true }); - expect(qExport.text).toContain("cd -- '/tmp; rm -rf /'"); - await api(`/api/terminal/sessions/${qPtyId}`, { method: 'DELETE' }); - - const ptyRes = await api('/api/terminal/sessions', { - method: 'POST', - body: { serverId: 'bastion', cwd: '/tmp', cols: 80, rows: 24 }, - }); - expect(ptyRes.status).toBe(201); - const ptyId = String((ptyRes.data.session as { sessionId: string }).sessionId); - await new Promise((r) => setTimeout(r, 150)); - - const castRes = await api(`/api/terminal/sessions/${ptyId}/export?format=cast`, { raw: true }); - expect(castRes.status).toBe(200); - const header = JSON.parse(castRes.text.trim().split('\n')[0]!) as { version: number; width: number }; - expect(header.version).toBe(2); - expect(header.width).toBe(80); - - const reconPty = await api(`/api/terminal/sessions/${ptyId}/reconnect`, { - method: 'POST', - body: {}, - }); - expect(reconPty.status).toBe(200); - expect((reconPty.data.session as { exited: boolean }).exited).toBe(false); - await api(`/api/terminal/sessions/${ptyId}`, { method: 'DELETE' }); - - // SFTP v1.1: touch, chown (sudo via MockSshServer), search, bulk-delete, symlink escape refusal - const touchRes = await api('/api/servers/bastion/sftp/touch', { - method: 'POST', - body: { path: '/touched.txt' }, - }); - expect(touchRes.status).toBe(201); - expect(fs.existsSync(path.join(mock.sftpRootDir, 'touched.txt'))).toBe(true); - - const chownRes = await api('/api/servers/bastion/sftp/chown', { - method: 'POST', - body: { path: '/touched.txt', uid: 1000, gid: 1000, sudo: true }, - }); - expect(chownRes.status).toBe(200); - expect(seenExecs.some((c) => c.includes('chown 1000:1000'))).toBe(true); - - const searchRes = await api('/api/servers/bastion/sftp/search?path=/&q=needle'); - expect(searchRes.status).toBe(200); - expect(searchRes.data.matches).toContain('/sub/needle.conf'); - expect(seenExecs.some((c) => c.startsWith("find '/' -maxdepth 5 -iname '*needle*'"))).toBe( - true, - ); - - const bulkDel = await api('/api/servers/bastion/sftp/bulk-delete', { - method: 'POST', - body: { paths: ['/touched.txt', '/alpha.log'], recursive: false }, - }); - expect(bulkDel.status).toBe(200); - expect((bulkDel.data.deleted as string[]).length).toBe(2); - - // Symlink inspection + safe symlink deletion (lstat unlinks symlink without touching target dir) - const targetDir = path.join(mock.sftpRootDir, 'keep-dir'); - fs.mkdirSync(targetDir, { recursive: true }); - fs.writeFileSync(path.join(targetDir, 'precious.txt'), 'do-not-delete'); - fs.symlinkSync(targetDir, path.join(mock.sftpRootDir, 'link-to-dir')); - - const symStat = await api('/api/servers/bastion/sftp/stat?path=/escape-link'); - expect(symStat.status).toBe(200); - expect((symStat.data.entry as { type: string }).type).toBe('symlink'); - - const delLink = await api( - '/api/servers/bastion/sftp/entry?path=/link-to-dir&recursive=1', - { method: 'DELETE' }, - ); - expect(delLink.status).toBe(200); - expect(fs.existsSync(path.join(targetDir, 'precious.txt'))).toBe(true); - expect(fs.existsSync(path.join(mock.sftpRootDir, 'link-to-dir'))).toBe(false); - - const nullPath = await api('/api/servers/bastion/sftp/text?path=/bad%00path'); - expect(nullPath.status).toBeGreaterThanOrEqual(400); - - // SOCKS5 tunnel without targetPort + TTL countdown metadata - const socksCreate = await api('/api/tunnels', { - method: 'POST', - body: { - serverId: 'bastion', - tunnel: { - id: 'socks-tun', - name: 'SOCKS5 Local', - mode: 'socks5', - targetHost: '127.0.0.1', - targetPort: 0, - ttlSec: 120, - autoStart: false, - }, - start: true, - }, - }); - expect(socksCreate.status).toBe(201); - const tList = await api('/api/tunnels'); - const socksItem = (tList.data.tunnels as Array<{ - tunnel: { id: string; mode: string; ttlSec?: number }; - active: boolean; - localBoundPort?: number; - expiresAt?: number; - }>).find((t) => t.tunnel.id === 'socks-tun'); - expect(socksItem?.active).toBe(true); - expect(socksItem?.expiresAt).toBeGreaterThan(Date.now()); - - // SOCKS5 method negotiation (0x05 0x01 0x00 -> 0x05 0x00) - const socksReply = await new Promise((resolve, reject) => { - const sock = net.connect(socksItem!.localBoundPort!, '127.0.0.1', () => { - sock.write(Buffer.from([0x05, 0x01, 0x00])); - }); - sock.once('data', (d) => { - sock.destroy(); - resolve(d); - }); - sock.once('error', reject); - }); - expect(socksReply[0]).toBe(0x05); - expect(socksReply[1]).toBe(0x00); - - // Without isolated proxyPort/subdomain & allowSameOriginProxy=false -> 403 PROXY_ORIGIN_ISOLATION_REQUIRED - const proxyCreate = await api('/api/tunnels', { - method: 'POST', - body: { - serverId: 'bastion', - tunnel: { - id: 'web-noiso', - name: 'NoIso Web', - mode: 'http-proxy', - targetHost: '127.0.0.1', - targetPort: 9999, - autoStart: false, - }, - start: true, - }, - }); - expect(proxyCreate.status).toBe(201); - const noIsoTicket = await api('/api/tunnels/bastion/web-noiso/proxy-ticket', { - method: 'POST', - body: {}, - }); - expect(noIsoTicket.status).toBe(403); - expect(noIsoTicket.data.error).toBe('PROXY_ISOLATION_NOT_CONFIGURED'); - } finally { - await serverNoIso.close(); - fs.rmSync(dataDir, { recursive: true, force: true }); - } - }); -}); diff --git a/tests/vault-runtime-and-collectors.test.ts b/tests/vault-runtime-and-collectors.test.ts index 77ee897..373a588 100644 --- a/tests/vault-runtime-and-collectors.test.ts +++ b/tests/vault-runtime-and-collectors.test.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -104,8 +104,6 @@ describe('Always-on background collectors & write-only Vault lock', () => { } }); - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 65_000); let api = createApiClient(activeServer); const bootInfo = await api.call('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); @@ -132,12 +130,6 @@ describe('Always-on background collectors & write-only Vault lock', () => { const recoveryCodes = bootRes.data.recoveryCodes as string[]; expect(recoveryCodes.length).toBeGreaterThan(0); - vi.setSystemTime(Date.now() + 31_000); - expect( - (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); - vi.useRealTimers(); - // Explicitly initialize & add SSH key, register server, then lock Vault expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); const keyRes = await api.call('/api/vault/generate-ed25519', { @@ -188,12 +180,12 @@ describe('Always-on background collectors & write-only Vault lock', () => { }); api = createApiClient(activeServer); - // Before ANY user logs in, status is unauthenticated and omits internal vault state, yet runtime collectors run immediately + // Before ANY user logs in, status is unauthenticated + write-locked, yet runtime collectors run immediately const preLoginStatus = await api.call('/api/auth/status'); expect(preLoginStatus.status).toBe(200); expect(preLoginStatus.data.authenticated).toBe(false); - expect(preLoginStatus.data.vaultState).toBeUndefined(); - expect(preLoginStatus.data.vaultRuntimeReady).toBeUndefined(); + expect(preLoginStatus.data.vaultState).toBe('locked'); + expect(preLoginStatus.data.vaultRuntimeReady).toBe(true); const latestBeforeLogin = await waitFor( () => activeServer!.monitoringService.getLatest('srv-1')?.sample, @@ -238,11 +230,6 @@ describe('Always-on background collectors & write-only Vault lock', () => { expect((await api.call('/api/servers/srv-1/inspect')).status).toBe(200); expect((await api.call('/api/servers/srv-1/sftp/list?path=/')).status).toBe(200); - // Step up so the Vault write-lock guard (423 VAULT_LOCKED) is reached - expect( - (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); - // Modifications and secret reveals must still be blocked with 423 VAULT_LOCKED while locked const addBlocked = await api.call('/api/vault/credentials', { method: 'POST', diff --git a/tests/workflows-and-transfer.test.ts b/tests/workflows-and-transfer.test.ts index 70b63be..41ee12e 100644 --- a/tests/workflows-and-transfer.test.ts +++ b/tests/workflows-and-transfer.test.ts @@ -141,8 +141,6 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers return { status: res.status, data }; }; - vi.useFakeTimers({ toFake: ['Date'] }); - vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -163,11 +161,7 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers initialSafeMode: false, }, }); - vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); - expect( - (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, - ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { @@ -607,7 +601,7 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers expect(dagStart.status).toBe(202); const dagRunId = String(dagStart.data.runId); const dagDetail = await waitForWorkflowRun(server, dagRunId, 10_000); - expect(dagDetail.run.status, JSON.stringify(dagDetail.stepLogs)).toBe('succeeded'); + expect(dagDetail.run.status).toBe('succeeded'); const logByStep = new Map(dagDetail.stepLogs.map((l) => [l.stepId, l])); expect(logByStep.get('gen-token')?.stdout).toBe('tok-v42'); @@ -757,36 +751,20 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers expect(dCancelled.run.status).toBe('cancelled'); expect(dCancelled.run.cancelledBy).toBe('admin'); - // --- 5. Cron Workflow Scheduling (5-field enforced; 6-field rejected) --- - const badCronRes = await api('/api/workflows', { - method: 'POST', - body: { - id: 'wf-cron-bad', - name: '6-Field Spam Cron', - enabled: true, - trigger: { type: 'cron', expression: '* * * * * *', timezone: 'UTC' }, - overlapPolicy: 'skip', - display: { mode: 'log' }, - inputs: [], - steps: [{ id: 'tick', type: 'exec', target: { serverId: 'srv-b' }, command: 'echo NOPE' }], - }, - }); - expect(badCronRes.status).toBe(400); - - const okCronRes = await api('/api/workflows', { + // --- 5. Cron Workflow Scheduling --- + await api('/api/workflows', { method: 'POST', body: { id: 'wf-cron-sec', - name: 'Every Minute Cron', + name: 'Every Second Cron', enabled: true, - trigger: { type: 'cron', expression: '* * * * *', timezone: 'UTC' }, + trigger: { type: 'cron', expression: '* * * * * *', timezone: 'UTC' }, overlapPolicy: 'skip', display: { mode: 'log' }, inputs: [], steps: [{ id: 'tick', type: 'exec', target: { serverId: 'srv-b' }, command: 'echo CRON_TICK' }], }, }); - expect(okCronRes.status).toBe(201); const listSummary = await api('/api/workflows'); const cronSummary = ( @@ -798,7 +776,6 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers expect(typeof cronSummary?.nextRunAt).toBe('number'); expect(cronSummary!.nextRunAt!).toBeGreaterThan(Date.now() - 2000); - expect(await server.workflowEngine.triggerScheduledCron('wf-cron-sec')).toBe(true); const cronRun = await waitFor( () => { const runs = server.workflowEngine.listRuns('wf-cron-sec');