Compare commits

..

No commits in common. "5701e7778098db0ae00897934204b5f4478a08ad" and "d7c3e11d7e754ebbd3d80789278904542ab34b3d" have entirely different histories.

112 changed files with 2494 additions and 14920 deletions

View file

@ -1,12 +0,0 @@
node_modules/
dist/
data/
docker/secrets/
.git/
.env
.env.*
*.gcoord.enc
*.tsbuildinfo
coverage/
tests/
.DS_Store

View file

@ -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. - 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. - 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 Scripts (`package.json`)
- `npm run typecheck` — `tsc --noEmit` (strict TypeScript with `noUncheckedIndexedAccess: true` and `noImplicitOverride: true`). - `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: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 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/<file>.test.ts` — run a targeted Vitest file. - `npx vitest run tests/<file>.test.ts` — run a targeted Vitest file.
- `npm run dev` — `tsx watch src/server/index.ts`. - `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). - `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`) ### CLI (`src/cli/gcoord.ts` -> `dist/cli/gcoord.js`)
```bash ```bash
node dist/cli/gcoord.js status [--data-dir <dir>] [--json]
node dist/cli/gcoord.js panic-lock [--data-dir <dir>]
node dist/cli/gcoord.js reset-2fa [--data-dir <dir>] [--disable] [--json]
node dist/cli/gcoord.js reset-password [--data-dir <dir>] [--password-file <path>]
node dist/cli/gcoord.js rotate-key [--data-dir <dir>] [--current-key-file <path>] [--new-key-out <path>] node dist/cli/gcoord.js rotate-key [--data-dir <dir>] [--current-key-file <path>] [--new-key-out <path>]
node dist/cli/gcoord.js backup --out <path.gcoord.enc> [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>] node dist/cli/gcoord.js backup --out <path.gcoord.enc> [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>]
node dist/cli/gcoord.js verify-backup <path.gcoord.enc> [--bundle <path>] [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>] [--json] node dist/cli/gcoord.js verify-backup <path.gcoord.enc> [--bundle <path>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>] [--json]
node dist/cli/gcoord.js restore <path.gcoord.enc> [--bundle <path>] [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>] node dist/cli/gcoord.js restore <path.gcoord.enc> [--bundle <path>] [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>]
``` ```
@ -55,18 +51,8 @@ node dist/cli/gcoord.js restore <path.gcoord.enc> [--bundle <path>] [--data-dir
- `HOST` — bind address (default: `0.0.0.0`). - `HOST` — bind address (default: `0.0.0.0`).
- `GCOORD_MASTER_KEY` — 32-byte Vault master key (hex or base64). - `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_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. - `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. - `TRUST_CLOUDFLARE` — set `'true'` to enable `app.set('trust proxy', 1)` 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`).
--- ---
@ -83,7 +69,7 @@ GCoordinator/
│ └── docker-compose.lan.yml │ └── docker-compose.lan.yml
├── src/ ├── src/
│ ├── cli/ │ ├── 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/ │ ├── shared/
│ │ ├── diff.ts # Pure TS unified LCS line diff utility │ │ ├── diff.ts # Pure TS unified LCS line diff utility
│ │ ├── ws-protocol.ts # Multiplexed /ws frame schemas & WS_CHANNELS helpers │ │ ├── ws-protocol.ts # Multiplexed /ws frame schemas & WS_CHANNELS helpers
@ -99,84 +85,76 @@ GCoordinator/
│ │ └── vault.schema.ts │ │ └── vault.schema.ts
│ ├── server/ │ ├── server/
│ │ ├── index.ts # Process bootstrap & SIGINT/SIGTERM graceful shutdown │ │ ├── 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/ │ │ ├── db/
│ │ │ ├── database.ts # SQLite WAL connection, throttle PRAGMAs & ordered migration runner │ │ │ ├── database.ts # SQLite WAL connection & ordered migration runner
│ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts, 004_v1_1.ts │ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts
│ │ ├── security/ │ │ ├── security/
│ │ │ ├── vault.ts # VaultService (AES-256-GCM, runtime-ready vs write-locked, seal(), Ed25519) │ │ │ ├── vault.ts # VaultService (AES-256-GCM, runtime-ready vs write-locked, Ed25519)
│ │ │ ├── auth.ts # AuthService (Argon2id queue, multi-password, encrypted TOTP, idle TTL, WebAuthn) │ │ │ ├── auth.ts # AuthService (Argon2id, multi-password, multi-TOTP, recovery codes, WebAuthn)
│ │ │ ├── guards.ts # SQLite RateLimiter, attachClientIp (CIDR trust), CSRF, Safe Mode, Step-Up │ │ │ ├── guards.ts # RateLimiter, attachClientIp, CSRF, Safe Mode, createStepUpGuard
│ │ │ ├── egress-guard.ts # Zero-Trust SSRF/DNS/CIDR guard & redirect: 'error' fetch wrapper │ │ │ ├── audit.ts # Append-only AuditService
│ │ │ ├── audit.ts # Append-only AuditService (filtered query, CSV formula guard, NDJSON) │ │ │ ├── recovery-store.ts # EmergencyRecoveryService (data/recovery/emergency-secrets.json)
│ │ │ ├── recovery-store.ts # EmergencyRecoveryService (passwordless data/recovery/emergency-secrets.json) │ │ │ └── backup.ts # Portable AES-256-GCM .gcoord.enc (GCOORD_BACKUP_V1) export/verify/restore
│ │ │ ├── backup.ts # Async portable AES-256-GCM .gcoord.enc (GCOORD_BACKUP_V1) export/verify/restore
│ │ │ └── backup-scheduler.ts # Scheduled .gcoord.enc backups (local & SFTP) with retention pruning
│ │ ├── config/ │ │ ├── config/
│ │ │ ├── config-manager.ts # ConfigManager (atomic writes, chokidar hot-reload, revisions, symlink guard) │ │ │ ├── config-manager.ts # ConfigManager (atomic writes, chokidar hot-reload, revisions)
│ │ │ ├── runtime-limits.ts # Throttle profile presets (low-resource | balanced | unthrottled)
│ │ │ ├── presets.ts # Default docker-compose, systemd, os-packages seeds │ │ │ ├── presets.ts # Default docker-compose, systemd, os-packages seeds
│ │ │ └── diff.ts │ │ │ └── diff.ts
│ │ ├── ssh/ │ │ ├── ssh/
│ │ │ ├── ssh-pool.ts # SSHPool (coalesced connections, ProxyJump, execStream, openShell, openSftp) │ │ │ ├── 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 TOFU, MITM guard, replaceAllKnownHosts)
│ │ │ ├── known-hosts.ts # KnownHostsService (strict multi-algo TOFU, MITM guard, replaceAllKnownHosts)
│ │ │ ├── key-manager.ts # KeyManager (authorized_keys deploy/revoke, zero-lockout rotation) │ │ │ ├── key-manager.ts # KeyManager (authorized_keys deploy/revoke, zero-lockout rotation)
│ │ │ ├── sudo.ts # POSIX-quoted sudo wrapper, askpass-free pipe & Buffer zeroization │ │ │ ├── sudo.ts # POSIX-quoted sudo wrapper & Buffer zeroization
│ │ │ ├── pty-manager.ts # PTYManager (UTF-8 framing, scrollback ring, .cast v2 export, reaper) │ │ │ ├── pty-manager.ts # PTYManager (UTF-8 framing, scrollback ring, export, reaper)
│ │ │ ├── sftp-service.ts # SftpService (stream upload/download, touch/chown/search, symlink-safe ops) │ │ │ ├── sftp-service.ts # SftpService (stream upload/download, atomic inline edit, tar archives)
│ │ │ └── tunnel-manager.ts # TunnelManager (dual-mode isolated HTTP/WS proxy, SOCKS5, local/remote TCP, TTL) │ │ │ └── tunnel-manager.ts # TunnelManager (http-proxy, local-tcp, remote-tcp)
│ │ ├── monitoring/ │ │ ├── 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) │ │ │ ├── inspector.ts # On-demand ServerInspector (processes, ports, sensors)
│ │ │ ├── probes.ts # ProbeRunner (hub egress-guarded HTTP + TLS expiry, target forwardOutStream) │ │ │ ├── probes.ts # ProbeRunner (hub or target forwardOutStream HTTP/TCP probes)
│ │ │ ├── monitoring-service.ts # MonitoringService (staggered/capped polling, SQLite rollups, retention) │ │ │ └── monitoring-service.ts # MonitoringService (always-on polling, SQLite rollups, retention)
│ │ │ └── prometheus.ts # Opt-in Bearer-authenticated Prometheus GET /metrics exporter
│ │ ├── systems/ │ │ ├── systems/
│ │ │ ├── parsers.ts # Output parsers for declarative system discovery/status │ │ │ ├── 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/ │ │ ├── automation/
│ │ │ ├── template.ts # Safe env-var & POSIX single-quoted interpolation + target filtering │ │ │ ├── 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) │ │ │ ├── transfer-engine.ts # TransferEngine (hub-relayed SFTP or direct rsync)
│ │ │ ├── workflow-engine.ts # WorkflowEngine (Kahn DAG, retries, http/notify steps, croner, secret inputs) │ │ │ ├── workflow-engine.ts # WorkflowEngine (Kahn DAG scheduler, croner, event triggers, dry-run)
│ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet execution + SQLite history & CSV) │ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet command execution)
│ │ ├── alerts/ │ │ ├── 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/ │ │ ├── ai/
│ │ │ ├── redactor.ts # Linear O(n) collectVaultSecretStrings & redactSecrets │ │ │ ├── redactor.ts # collectVaultSecretStrings & redactSecrets
│ │ │ ├── guides.ts # AiSurfaceSchema & buildSurfaceGuideAndInventory │ │ │ ├── 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/ │ │ └── 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 │ │ └── routes/ # auth, vault, config, audit, servers, terminal, sftp, tunnels, systems, workflows, snippets, alerts, backup, ai
│ └── client/ │ └── 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 │ ├── index.html # SPA shell + PWA manifest + dynamic theme-color meta
│ ├── manifest.json │ ├── manifest.json
│ ├── icon.svg │ ├── icon.svg
│ ├── css/ │ ├── css/
│ │ ├── themes.css # 8 CSS custom-property terminal themes │ │ ├── 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/ │ └── ts/
│ ├── main.ts # Router, nav, view cleanup lifecycle, topbar indicators, Panic Lock, global state sync │ ├── main.ts # Router, nav, topbar indicators, Panic Lock, global state sync
│ ├── state.ts # Client store, CLIENT_THEME_IDS, applyTheme, appendBoundedStreamText, registerViewCleanup │ ├── state.ts # Client store, CLIENT_THEME_IDS, applyTheme, appendBoundedStreamText
│ ├── api.ts # Fetch wrapper (CSRF header + auto Vault unlock prompt on 423 VAULT_LOCKED) │ ├── 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 │ ├── ws-client.ts # Reconnecting /ws client
│ ├── dialogs.ts # Native <dialog> modals (multi-factor step-up, confirm, collapsible hunk diffs) │ ├── dialogs.ts # Native <dialog> modals (multi-factor step-up, confirm, prompts)
│ ├── charts.ts # Flat SVG sparklines & metric charts (viewport-capped points, multi-series overlay) │ ├── charts.ts # Flat SVG sparklines & metric charts (viewport-capped points)
│ ├── toast.ts # Live toast notification bus (lazy/core feedback helpers)
│ ├── webauthn.ts # navigator.credentials base64url helper │ ├── webauthn.ts # navigator.credentials base64url helper
│ ├── command-palette.ts # Code-split Ctrl/Cmd+K quick switcher & action palette │ └── views/
│ └── views/ # All views dynamically code-split via import(...) │ ├── auth-view.ts # Core static views
│ ├── auth-view.ts
│ ├── dashboard-view.ts │ ├── dashboard-view.ts
│ ├── server-detail-view.ts │ ├── server-detail-view.ts
│ ├── vault-view.ts │ ├── vault-view.ts
│ ├── config-view.ts │ ├── config-view.ts
│ ├── settings-view.ts │ ├── settings-view.ts
│ ├── settings-ops-panel.ts │ ├── terminal-view.ts # Code-split lazy views (keep dynamically imported!)
│ ├── terminal-view.ts
│ ├── xterm-runtime.ts │ ├── xterm-runtime.ts
│ ├── sftp-view.ts │ ├── sftp-view.ts
│ ├── tunnels-panel.ts │ ├── tunnels-panel.ts
@ -186,67 +164,56 @@ GCoordinator/
│ └── ai-drawer.ts │ └── ai-drawer.ts
└── tests/ └── tests/
├── helpers/mock-ssh-server.ts # In-process ssh2.Server fixture (PTY, SFTP, forwardOut, forwardIn, sudo) ├── 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) ## 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'`. - `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`). - 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`, `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. - 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, 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`). - 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).
- **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`) 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.
- **Emergency Panic Lock** (`panicLock()`, persisted via `${vaultFilePath}.panic-locked`): zeroes runtime secret buffers (`isRuntimeReady = false`), tears down active SSH/PTY/tunnel/AI/scheduler sessions, revokes sessions immediately (`WS 4001`), emits a `vault.panic_lock` security event, and refuses silent disk/env auto-unlock across restarts until manually unlocked with the master key.
### 2. Auth, Multi-Factor Strictness, Safe Mode & Passkeys (`auth.ts`, `guards.ts`) ### 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`). - 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`).
- 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`. - `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.
- `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`). - 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.
- `SecuritySettingsSchema` (`src/shared/schemas/settings.schema.ts`) configures `requireTotpOnLogin`, `stepUpPolicy` (`off | every-action | 5m | 15m | 1h | 24h | session`, default `15m`), `stepUpMethod` (`totp | password | both | passkey`), `elevateOnLogin`, and `keepElevationOnSafeMode`. Always gate elevated endpoints with `createStepUpGuard`.
- Mutating HTTP routes require an authenticated session cookie, matching `X-CSRF-Token`, and Safe Mode enforcement (`HTTP 423 SAFE_MODE_ACTIVE`; mobile `< 768px` defaults to Safe Mode ON). Safe-Mode exemptions are limited to `/api/auth/logout`, `/api/auth/safe-mode`, Panic Lock (`/api/security/panic-lock`), `/api/backup/verify`, read-only AI draft/chat endpoints (all except `/api/ai/save-draft`), `/api/workflows/:id/dry-run`, and live cancellation endpoints (`/api/systems/streams/:jobId/cancel`, `/api/workflows/runs/:runId/cancel`, `/api/workflows/broadcast/:jobId/cancel`).
### 3. Dual Backup Subsystems (`recovery-store.ts`, `backup.ts`, `backup-scheduler.ts`) ### 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 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. - **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` & `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. - **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 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. - **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`) ### 4. Config Hot-Reload & SQLite Migrations (`config-manager.ts`, `database.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`). - 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.
- `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. - 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`) ### 5. SSH, Shell Quoting, Crypto & Tunnel Proxy Rules
- 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. - **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).
- 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`. - **`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`) ### 6. Optional BYO-API AI Assistant (`src/server/ai/`)
- **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. - Strictly opt-in: return `403 AI_DISABLED` whenever `settings.ai.enabled === false` and hide `[AI ...]` triggers in the UI unless `isAiEnabled(state)` is true.
- **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). - Sanitize all outbound AI prompts and context previews through `redactSecrets()` (`redactor.ts`) seeded with `collectVaultSecretStrings()`.
- **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`. - 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`.
- **Dual-Mode Isolated Reverse Proxy (`tunnel-manager.ts`, `app.ts`)**:
- Prefer origin-isolated proxying via `GCOORD_PROXY_PORT` (dedicated local port) or `GCOORD_PROXY_BASE_DOMAIN` (wildcard subdomain), bridged via single-use `/proxy-ticket` redemption into a proxy-scoped `gcoord_proxy_sid` session so proxied target apps cannot share hub origin cookies or storage.
- Same-origin `/proxy` requests are rejected with `HTTP 403 PROXY_ISOLATION_NOT_CONFIGURED` unless `settings.security.allowSameOriginProxy: true` is explicitly enabled.
- Keep `/proxy` mounted before `express.json()`, exempt `/proxy/*` from the hub CSP, strip `gcoord_sid` / `gcoord_csrf` / `gcoord_proxy_sid` cookies upstream, rewrite relative `Location` redirects, and support HTTPS upstream, SOCKS5 (`mode: 'socks5'`), and TTL auto-expiry.
### 7. Alerts, Prometheus `/metrics` & BYO-API AI (`alerts/`, `prometheus.ts`, `ai/`)
- Alert channels strictly allow only `webhook-secret` Vault credential IDs (preventing arbitrary Vault credential exfiltration in webhook headers/bodies) and dispatch `security-event` alerts emitted by Auth, KnownHosts, and Vault Panic Lock.
- Prometheus `GET /metrics` (`prometheus.ts`) is opt-in (`settings.metrics.prometheusEnabled`) and Bearer-authenticated against `GCOORD_METRICS_TOKEN`, the rotated SHA-256 token hash from `POST /api/config/prometheus-token`, or a Vault `api-token`/`webhook-secret` ref (`404` when disabled, `401` when unauthenticated).
- AI Assistant (`src/server/ai/`): opt-in (`403 AI_DISABLED` when disabled), linear-time `O(n)` secret redaction (`redactor.ts`), and mandatory server Zod `validateDraft` + diff review before saving/running anything.
--- ---
## 5. Frontend, Bundle Budget & Mobile Rules ## 5. Frontend, Bundle Budget & Mobile Rules
### Hard Gzip Budgets (`src/client/build.ts` — throws and fails build if exceeded) ### 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**. - **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 ### 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/**`. Use `import type` exclusively and mirror minimal constants cleanly in `src/client/ts/state.ts`. - **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.
- 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. - 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(...)`.
- Every view/panel with timers, DOM window listeners, xterm instances, or dynamic WS channels **must** register teardown via `registerViewCleanup()` (`state.ts`, flushed on navigation by `main.ts`) and use ref-counted `wsClient.subscribe()` cleanup callbacks (which send `{ type: 'unsub' }` when refcount hits 0).
### Flat Sharp Aesthetic & 8 Themes ### Flat Sharp Aesthetic & 8 Themes
- Maintain the zero-overhead aesthetic: `border-radius: 0`, `1px` crisp borders, zero `box-shadow`, zero gradients, zero `backdrop-filter`. - Maintain the zero-overhead aesthetic: `border-radius: 0`, `1px` crisp borders, zero `box-shadow`, zero gradients, zero `backdrop-filter`.

View file

@ -18,21 +18,19 @@ FROM node:22-bookworm-slim AS runtime
WORKDIR /app WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \ 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/* \ && 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 --chown=1000:1000 /app/package.json ./
COPY --from=builder /app/node_modules ./node_modules COPY --from=builder --chown=1000:1000 /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist COPY --from=builder --chown=1000:1000 /app/dist ./dist
USER 1000:1000 USER 1000:1000
ENV NODE_ENV=production \ ENV NODE_ENV=production \
PORT=3000 \ PORT=3000 \
HOST=0.0.0.0 \ GCOORD_DATA_DIR=/data
GCOORD_DATA_DIR=/data \
NODE_OPTIONS="--max-old-space-size=384"
EXPOSE 3000 EXPOSE 3000

View file

@ -2,7 +2,6 @@ services:
gcoordinator: gcoordinator:
environment: environment:
- TRUST_CLOUDFLARE=false - TRUST_CLOUDFLARE=false
- GCOORD_ALLOW_LAN_TUNNELS=${GCOORD_ALLOW_LAN_TUNNELS:-false}
ports: ports:
- "${GCOORD_LAN_BIND:-127.0.0.1}:3000:3000" - "${GCOORD_LAN_BIND:-127.0.0.1}:3000:3000"
- "${GCOORD_LAN_BIND:-127.0.0.1}:20000-20020:20000-20020" - "${GCOORD_LAN_BIND:-127.0.0.1}:20000-20020:20000-20020"

View file

@ -7,22 +7,13 @@ services:
restart: unless-stopped restart: unless-stopped
user: "1000:1000" user: "1000:1000"
read_only: true read_only: true
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
mem_limit: ${GCOORD_MEM_LIMIT:-512m}
pids_limit: 128
tmpfs: tmpfs:
- /tmp:rw,noexec,nosuid,nodev,size=64m - /tmp
environment: environment:
- NODE_ENV=production - NODE_ENV=production
- PORT=3000 - PORT=3000
- HOST=0.0.0.0
- GCOORD_DATA_DIR=/data - GCOORD_DATA_DIR=/data
- TRUST_CLOUDFLARE=true - TRUST_CLOUDFLARE=true
- GCOORD_THROTTLE_MODE=${GCOORD_THROTTLE_MODE:-low-resource}
- NODE_OPTIONS=--max-old-space-size=${GCOORD_NODE_MAX_OLD_SPACE:-384}
secrets: secrets:
- gcoord_master_key - gcoord_master_key
volumes: volumes:
@ -35,13 +26,6 @@ services:
image: cloudflare/cloudflared:latest image: cloudflare/cloudflared:latest
container_name: gcoordinator-tunnel container_name: gcoordinator-tunnel
restart: unless-stopped 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 command: tunnel --no-autoupdate run
environment: environment:
- TUNNEL_TOKEN=${CLOUDFLARED_TUNNEL_TOKEN} - TUNNEL_TOKEN=${CLOUDFLARED_TUNNEL_TOKEN}

4
package-lock.json generated
View file

@ -1,12 +1,12 @@
{ {
"name": "gcoordinator", "name": "gcoordinator",
"version": "1.1.0", "version": "0.1.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "gcoordinator", "name": "gcoordinator",
"version": "1.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@simplewebauthn/server": "^13.1.1", "@simplewebauthn/server": "^13.1.1",
"@xterm/addon-fit": "^0.11.0", "@xterm/addon-fit": "^0.11.0",

View file

@ -1,6 +1,6 @@
{ {
"name": "gcoordinator", "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.", "description": "Self-hosted, security-first central sysadmin hub for multiplexed SSH access, monitoring, custom systems, workflows, and alerting.",
"type": "module", "type": "module",
"engines": { "engines": {

View file

@ -1,16 +1,7 @@
import crypto from 'node:crypto';
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import readline from 'node:readline/promises'; import readline from 'node:readline/promises';
import { parseArgs } from 'node:util'; 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 { import {
createBackupBundle, createBackupBundle,
restoreBackupBundle, restoreBackupBundle,
@ -18,42 +9,24 @@ import {
} from '../server/security/backup.js'; } from '../server/security/backup.js';
import { EmergencyRecoveryService } from '../server/security/recovery-store.js'; import { EmergencyRecoveryService } from '../server/security/recovery-store.js';
import { VaultService } from '../server/security/vault.js'; import { VaultService } from '../server/security/vault.js';
import { SettingsSchema } from '../shared/schemas/settings.schema.js';
function printUsage(): void { function printUsage(): void {
console.log(`GCoordinator CLI (gcoord) console.log(`GCoordinator CLI (gcoord)
Commands: Commands:
status Inspect GCoordinator data directory state (read-only)
--data-dir <path> 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 <path> Data directory (default: GCOORD_DATA_DIR or ./data)
reset-2fa Reset TOTP authenticators offline (re-enroll new TOTP or disable 2FA)
--data-dir <path> 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 <path> Data directory (default: GCOORD_DATA_DIR or ./data)
--password-file <path> Read new password (>= 10 chars) from file instead of prompt
rotate-key Re-encrypt vault.enc atomically with a new 32-byte master key rotate-key Re-encrypt vault.enc atomically with a new 32-byte master key
--data-dir <path> Data directory (default: GCOORD_DATA_DIR or ./data) --data-dir <path> Data directory (default: GCOORD_DATA_DIR or ./data)
--current-key-file <path> Path to file containing current 32-byte key --current-key-file <path> Path to file containing current 32-byte key
--new-key-out <path> Exclusive output file (0600, O_EXCL) for generated key --new-key-out <path> Optional output file (0600) for generated key
backup Create an AES-256-GCM .gcoord.enc portable backup bundle backup Create an AES-256-GCM .gcoord.enc portable backup bundle
--out <path.gcoord.enc> Output bundle path (required) --out <path.gcoord.enc> Output bundle path (required)
--data-dir <path> Data directory (default: GCOORD_DATA_DIR or ./data) --data-dir <path> Data directory (default: GCOORD_DATA_DIR or ./data)
--key-file <path> Path to 32-byte Vault master key (default mode) --key-file <path> Path to 32-byte Vault master key (default mode)
--passphrase-file <path> Path to passphrase file (>= 12 chars, uses scrypt) --passphrase-file <path> Path to passphrase file (overrides key-file using scrypt)
verify-backup Verify GCM tag, JSON schemas, and Vault envelope without modifying data verify-backup Verify GCM tag, JSON schemas, and Vault envelope without modifying data
<path.gcoord.enc> Backup bundle path (or --bundle <path>) <path.gcoord.enc> Backup bundle path (or --bundle <path>)
--data-dir <path> Data directory fallback for vault.key lookup
--key-file <path> Path to 32-byte master key --key-file <path> Path to 32-byte master key
--passphrase-file <path> Path to backup passphrase file --passphrase-file <path> Path to backup passphrase file
--vault-key-file <path> Optional Vault master key to also decrypt/verify vault.enc --vault-key-file <path> 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<T>(dataDir: string, fn: () => Promise<T>): Promise<T> {
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<string> { async function promptHiddenOrLine(promptText: string): Promise<string> {
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<string>((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({ const rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stderr, output: process.stderr,
@ -229,19 +56,18 @@ async function promptHiddenOrLine(promptText: string): Promise<string> {
async function readCurrentKey(keyFile?: string, dataDir?: string): Promise<string> { async function readCurrentKey(keyFile?: string, dataDir?: string): Promise<string> {
if (keyFile) { if (keyFile) {
return readRegularFileStrict(keyFile); return fs.readFileSync(keyFile, 'utf8').trim();
} }
if (process.env.GCOORD_MASTER_KEY?.trim()) { if (process.env.GCOORD_MASTER_KEY?.trim()) {
return 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('/run/secrets/gcoord_master_key')) {
if (fs.existsSync(secretPath)) { return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim();
return readRegularFileStrict(secretPath);
} }
if (dataDir) { if (dataDir) {
const localKeyFile = path.join(path.resolve(dataDir), 'vault.key'); const localKeyFile = path.join(path.resolve(dataDir), 'vault.key');
if (fs.existsSync(localKeyFile)) { 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): '); return promptHiddenOrLine('Enter current 32-byte vault master key (hex or base64): ');
@ -249,19 +75,18 @@ async function readCurrentKey(keyFile?: string, dataDir?: string): Promise<strin
function readOptionalKeyNonInteractive(keyFile?: string, dataDir?: string): string | undefined { function readOptionalKeyNonInteractive(keyFile?: string, dataDir?: string): string | undefined {
if (keyFile) { if (keyFile) {
return readRegularFileStrict(keyFile); return fs.readFileSync(keyFile, 'utf8').trim();
} }
if (process.env.GCOORD_MASTER_KEY?.trim()) { if (process.env.GCOORD_MASTER_KEY?.trim()) {
return 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('/run/secrets/gcoord_master_key')) {
if (fs.existsSync(secretPath)) { return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim();
return readRegularFileStrict(secretPath);
} }
if (dataDir) { if (dataDir) {
const localKeyFile = path.join(path.resolve(dataDir), 'vault.key'); const localKeyFile = path.join(path.resolve(dataDir), 'vault.key');
if (fs.existsSync(localKeyFile)) { if (fs.existsSync(localKeyFile)) {
return readRegularFileStrict(localKeyFile); return fs.readFileSync(localKeyFile, 'utf8').trim();
} }
} }
return undefined; return undefined;
@ -269,7 +94,7 @@ function readOptionalKeyNonInteractive(keyFile?: string, dataDir?: string): stri
function readOptionalPassphrase(passphraseFile?: string): string | undefined { function readOptionalPassphrase(passphraseFile?: string): string | undefined {
if (passphraseFile) { if (passphraseFile) {
return readRegularFileStrict(passphraseFile); return fs.readFileSync(passphraseFile, 'utf8').trim();
} }
if (process.env.GCOORD_BACKUP_PASSPHRASE?.trim()) { if (process.env.GCOORD_BACKUP_PASSPHRASE?.trim()) {
return process.env.GCOORD_BACKUP_PASSPHRASE.trim(); return process.env.GCOORD_BACKUP_PASSPHRASE.trim();
@ -277,310 +102,6 @@ function readOptionalPassphrase(passphraseFile?: string): string | undefined {
return undefined; return undefined;
} }
function loadSettingsObject(dataDir: string): Record<string, unknown> {
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<number> {
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<string, unknown> = {
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<number> {
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<number> {
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<string, unknown>;
[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<number> {
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<number> { async function runRotateKey(args: string[]): Promise<number> {
const parsed = parseArgs({ const parsed = parseArgs({
args, args,
@ -601,40 +122,32 @@ async function runRotateKey(args: string[]): Promise<number> {
return 1; return 1;
} }
return withDataDirLock(dataDir, async () => { const currentKey = await readCurrentKey(parsed.values['current-key-file']);
const currentKey = await readCurrentKey(parsed.values['current-key-file'], dataDir); const vault = new VaultService(vaultPath);
const vault = new VaultService(vaultPath, { vault.unlock(currentKey);
keyFilePath: path.join(dataDir, 'vault.key'), const { generatedKeyHex } = vault.rotateMasterKey();
});
vault.unlock(currentKey);
const { generatedKeyHex } = vault.rotateMasterKey();
if (!generatedKeyHex) { if (!generatedKeyHex) {
console.error('Error: Unexpected empty rotated key'); console.error('Error: Unexpected empty rotated key');
return 1; return 1;
} }
const recovery = new EmergencyRecoveryService(dataDir); const recovery = new EmergencyRecoveryService(dataDir);
const settings = loadSettingsObject(dataDir) as { if (recovery.readBundle() !== null) {
security?: { enableEmergencySecretsBackup?: boolean }; recovery.syncState({ enabled: true, vault, snapshotReason: 'cli-rotate-key' });
}; }
if (
settings.security?.enableEmergencySecretsBackup &&
recovery.readBundle() !== null
) {
recovery.syncState({ enabled: true, vault, snapshotReason: 'cli-rotate-key' });
}
if (parsed.values['new-key-out']) { if (parsed.values['new-key-out']) {
const outPath = path.resolve(parsed.values['new-key-out']); const outPath = path.resolve(parsed.values['new-key-out']);
writeExclusiveSecureFile(outPath, `${generatedKeyHex}\n`); fs.mkdirSync(path.dirname(outPath), { recursive: true });
console.log(`Vault master key rotated cleanly. New key written to ${outPath} (mode 0600).`); fs.writeFileSync(outPath, `${generatedKeyHex}\n`, { mode: 0o600 });
} else { fs.chmodSync(outPath, 0o600);
console.log('Vault master key rotated cleanly. Store this new key securely:'); console.log(`Vault master key rotated cleanly. New key written to ${outPath} (mode 0600).`);
console.log(generatedKeyHex); } else {
} console.log('Vault master key rotated cleanly. Store this new key securely:');
return 0; console.log(generatedKeyHex);
}); }
return 0;
} }
async function runBackup(args: string[]): Promise<number> { async function runBackup(args: string[]): Promise<number> {
@ -670,7 +183,17 @@ async function runBackup(args: string[]): Promise<number> {
}); });
const outPath = path.resolve(outRaw); 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( console.log(
`Backup created at ${outPath} (kdf=${result.summary.kdf}, configs=${result.summary.configFileCount}, knownHosts=${result.summary.knownHostsCount}, vaultVerified=${result.summary.vaultVerified})`, `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<number> {
args, args,
options: { options: {
bundle: { type: 'string' }, bundle: { type: 'string' },
'data-dir': { type: 'string' },
'key-file': { type: 'string' }, 'key-file': { type: 'string' },
'passphrase-file': { type: 'string' }, 'passphrase-file': { type: 'string' },
'vault-key-file': { type: 'string' }, 'vault-key-file': { type: 'string' },
@ -698,26 +220,17 @@ async function runVerifyBackup(args: string[]): Promise<number> {
return 1; return 1;
} }
const dataDir = parsed.values['data-dir'] const rawBuf = fs.readFileSync(path.resolve(bundleArg));
? 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 passphrase = readOptionalPassphrase(parsed.values['passphrase-file']); 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) { if (!passphrase && !masterKey) {
const rawMeta = JSON.parse(rawBuf.toString('utf8')) as { kdf?: string }; const rawMeta = JSON.parse(rawBuf.toString('utf8')) as { kdf?: string };
if (rawMeta.kdf === 'scrypt') { if (rawMeta.kdf === 'scrypt') {
throw new Error( throw new Error('Passphrase required for scrypt-encrypted backup (--passphrase-file or GCOORD_BACKUP_PASSPHRASE)');
'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, { const summary = verifyBackupSummaryOnly(rawBuf, {
masterKey, masterKey,
@ -757,28 +270,25 @@ async function runRestore(args: string[]): Promise<number> {
const dataDir = path.resolve( const dataDir = path.resolve(
parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', 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 { summary } = restoreBackupBundle(rawBuf, {
const rawBuf = Buffer.from(readRegularFileStrict(bundleArg), 'utf8'); dataDir,
const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']); masterKey,
let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir); passphrase,
if (!passphrase && !masterKey) { vaultMasterKey,
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;
}); });
console.log(
`Restored GCoordinator state to ${dataDir} (configs=${summary.configFileCount}, knownHosts=${summary.knownHostsCount}, silences=${summary.alertSilenceCount})`,
);
return 0;
} }
async function main(): Promise<void> { async function main(): Promise<void> {
@ -788,25 +298,22 @@ async function main(): Promise<void> {
process.exit(0); process.exit(0);
} }
const handlers: Record<string, (args: string[]) => Promise<number>> = { if (command === 'rotate-key') {
status: runStatus, process.exit(await runRotateKey(rest));
'panic-lock': runPanicLock, }
'reset-2fa': runReset2fa, if (command === 'backup') {
'reset-password': runResetPassword, process.exit(await runBackup(rest));
'rotate-key': runRotateKey, }
backup: runBackup, if (command === 'verify-backup') {
'verify-backup': runVerifyBackup, process.exit(await runVerifyBackup(rest));
restore: runRestore, }
}; if (command === 'restore') {
process.exit(await runRestore(rest));
const handler = handlers[command];
if (!handler) {
console.error(`Unknown command: ${command}`);
printUsage();
process.exit(1);
} }
process.exit(await handler(rest)); console.error(`Unknown command: ${command}`);
printUsage();
process.exit(1);
} }
main().catch((err) => { main().catch((err) => {

View file

@ -8,52 +8,17 @@ const LAZY_CHUNK_BUDGET_BYTES = 20 * 1024;
const clientDir = path.resolve('src/client'); const clientDir = path.resolve('src/client');
const outDir = path.resolve('dist/public'); 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<string, esbuild.Metafile['outputs'][string]>,
entryKey: string,
): string[] {
const visited = new Set<string>();
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<void> { async function buildClient(): Promise<void> {
fs.rmSync(outDir, { recursive: true, force: true }); fs.rmSync(outDir, { recursive: true, force: true });
fs.mkdirSync(outDir, { recursive: true }); fs.mkdirSync(outDir, { recursive: true });
const jsResult = await esbuild.build({ await esbuild.build({
entryPoints: [path.join(clientDir, 'ts', 'main.ts')], entryPoints: [path.join(clientDir, 'ts', 'main.ts')],
bundle: true, bundle: true,
format: 'esm', format: 'esm',
splitting: true, splitting: true,
minify: true, minify: true,
sourcemap: false, sourcemap: false,
metafile: true,
target: 'es2020', target: 'es2020',
outdir: outDir, outdir: outDir,
entryNames: '[name]', entryNames: '[name]',
@ -81,22 +46,18 @@ async function buildClient(): Promise<void> {
fs.copyFileSync(path.join(clientDir, asset), path.join(outDir, asset)); fs.copyFileSync(path.join(clientDir, asset), path.join(outDir, asset));
} }
const syncJsChunks = jsResult.metafile const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js'];
? collectSyncImports(jsResult.metafile.outputs, 'main.js').filter((k) => k !== 'main.js')
: [];
const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js', ...syncJsChunks];
let totalRaw = 0; let totalRaw = 0;
let totalGzip = 0; let totalGzip = 0;
for (const file of coreAssets) { for (const file of coreAssets) {
const fullPath = path.join(outDir, file); const buf = fs.readFileSync(path.join(outDir, file));
if (!fs.existsSync(fullPath)) continue;
const buf = fs.readFileSync(fullPath);
const gz = zlib.gzipSync(buf, { level: 9 }); const gz = zlib.gzipSync(buf, { level: 9 });
totalRaw += buf.length; totalRaw += buf.length;
totalGzip += gz.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'); const chunksDir = path.join(outDir, 'chunks');
@ -104,8 +65,7 @@ async function buildClient(): Promise<void> {
for (const chunk of fs.readdirSync(chunksDir).sort()) { for (const chunk of fs.readdirSync(chunksDir).sort()) {
const cBuf = fs.readFileSync(path.join(chunksDir, chunk)); const cBuf = fs.readFileSync(path.join(chunksDir, chunk));
const cGz = zlib.gzipSync(cBuf, { level: 9 }); 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`);
console.log(` chunks/${chunk.padEnd(28)} raw=${cBuf.length}B gzip=${cGz.length}B${syncTag}`);
if (!chunk.startsWith('terminal-view-') && cGz.length >= LAZY_CHUNK_BUDGET_BYTES) { if (!chunk.startsWith('terminal-view-') && cGz.length >= LAZY_CHUNK_BUDGET_BYTES) {
throw new Error( throw new Error(
`Lazy chunk ${chunk} (${cGz.length}B gzipped) exceeded 20KB budget (${LAZY_CHUNK_BUDGET_BYTES}B)`, `Lazy chunk ${chunk} (${cGz.length}B gzipped) exceeded 20KB budget (${LAZY_CHUNK_BUDGET_BYTES}B)`,

View file

@ -699,87 +699,3 @@ dialog.ai-drawer[open] {
padding: 6px 10px; 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;
}

View file

@ -13,7 +13,6 @@
</head> </head>
<body> <body>
<div id="app" class="app-shell"> <div id="app" class="app-shell">
<a href="#view-root" class="sr-only sr-only-focusable">Skip to main content</a>
<header id="topbar" class="topbar" hidden> <header id="topbar" class="topbar" hidden>
<div class="topbar-brand"> <div class="topbar-brand">
<span class="brand-mark">&gt;_ GCOORD</span> <span class="brand-mark">&gt;_ GCOORD</span>
@ -34,7 +33,6 @@
<option value="tokyo-night">tokyo-night</option> <option value="tokyo-night">tokyo-night</option>
<option value="high-contrast">high-contrast</option> <option value="high-contrast">high-contrast</option>
</select> </select>
<button id="cmd-palette-btn" type="button" class="btn btn-sm" title="Command Palette (Ctrl+K / Alt+K)">[CMD]</button>
<button id="safe-toggle-btn" type="button" class="btn btn-sm" aria-pressed="false">[SAFE: OFF]</button> <button id="safe-toggle-btn" type="button" class="btn btn-sm" aria-pressed="false">[SAFE: OFF]</button>
<button id="panic-btn" type="button" class="btn btn-sm btn-danger">[PANIC LOCK]</button> <button id="panic-btn" type="button" class="btn btn-sm btn-danger">[PANIC LOCK]</button>
<button id="logout-btn" type="button" class="btn btn-sm">[LOGOUT]</button> <button id="logout-btn" type="button" class="btn btn-sm">[LOGOUT]</button>
@ -163,29 +161,14 @@
<input id="srv-tags" name="tags" placeholder="prod, web"> <input id="srv-tags" name="tags" placeholder="prod, web">
</div> </div>
</div> </div>
<p id="srv-test-msg" class="form-msg" aria-live="polite"></p>
<p id="srv-reg-err" class="form-msg err-text" aria-live="polite"></p> <p id="srv-reg-err" class="form-msg err-text" aria-live="polite"></p>
<div class="dialog-actions"> <div class="dialog-actions">
<button id="srv-test-conn-btn" type="button" class="btn mutating-action">Test Connection</button>
<button id="srv-reg-cancel" type="button" class="btn">Cancel</button> <button id="srv-reg-cancel" type="button" class="btn">Cancel</button>
<button type="submit" class="btn btn-primary mutating-action">Register Server</button> <button type="submit" class="btn btn-primary mutating-action">Register Server</button>
</div> </div>
</form> </form>
</dialog> </dialog>
<!-- Toast Region -->
<div id="toast-region" class="toast-region" aria-live="polite" aria-atomic="false"></div>
<!-- Command Palette Dialog -->
<dialog id="dialog-cmd" class="dialog-wide" aria-labelledby="dialog-cmd-title">
<div class="row-between">
<h1 id="dialog-cmd-title">Command Palette</h1>
<button id="cmd-palette-close" type="button" class="btn btn-sm">Esc</button>
</div>
<input id="cmd-palette-input" type="search" class="input-full" placeholder="Jump to route, server, terminal, SFTP, or security action..." autocomplete="off">
<div id="cmd-palette-list" class="cmd-palette-list" role="listbox" aria-label="Commands"></div>
</dialog>
<script type="module" src="/main.js"></script> <script type="module" src="/main.js"></script>
</body> </body>
</html> </html>

View file

@ -97,44 +97,3 @@ export function createRangeChartSvg(
svg.appendChild(poly); svg.appendChild(poly);
return svg; 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;
}

View file

@ -1,161 +0,0 @@
import { el, type ClientState } from './state.js';
interface PaletteAction {
id: string;
label: string;
hint: string;
run: () => void | Promise<void>;
}
export interface CommandPaletteContext {
state: ClientState;
navigate: (hash: string) => void;
toggleSafeMode: () => Promise<void>;
lockVault: () => Promise<void>;
triggerPanic: () => Promise<void>;
}
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();
}

View file

@ -1,4 +1,3 @@
import { collapseDiffHunks, type CollapsedDiffEntry } from '../../shared/diff.js';
import { apiFetch } from './api.js'; import { apiFetch } from './api.js';
import { import {
el, el,
@ -13,7 +12,6 @@ export interface DiffModalData {
source: string; source: string;
createdAt: number; createdAt: number;
lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>; lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>;
collapsedLines?: CollapsedDiffEntry[];
onRollback: () => Promise<void>; onRollback: () => Promise<void>;
} }
@ -234,56 +232,16 @@ export function openDiffModal(data: DiffModalData): void {
const closeBtn = document.getElementById('dialog-diff-close') as HTMLButtonElement; const closeBtn = document.getElementById('dialog-diff-close') as HTMLButtonElement;
const rollbackBtn = document.getElementById('dialog-diff-rollback') as HTMLButtonElement; const rollbackBtn = document.getElementById('dialog-diff-rollback') as HTMLButtonElement;
const hunks = data.collapsedLines ?? collapseDiffHunks(data.lines); metaEl.textContent = `${data.filePath} — Revision #${data.revisionId} (${data.source})`;
const hasHunk = hunks.some((entry) => entry.type === 'hunk'); bodyEl.replaceChildren();
let expanded = hunks.length === 0 || !hasHunk; for (const line of data.lines) {
const prefix = line.type === 'add' ? '+ ' : line.type === 'del' ? '- ' : ' ';
const toggleBtn = el( const cls =
'button', line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : '';
{ type: 'button', class: 'btn btn-sm', style: 'margin-left:8px' }, bodyEl.append(el('div', { class: cls }, `${prefix}${line.text}`));
expanded ? 'Full Diff' : 'Expand Full Diff',
);
if (!hasHunk) {
toggleBtn.hidden = true;
} }
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 = () => { const cleanup = () => {
toggleBtn.removeEventListener('click', onToggle);
closeBtn.removeEventListener('click', onClose); closeBtn.removeEventListener('click', onClose);
rollbackBtn.removeEventListener('click', onRollbackClick); rollbackBtn.removeEventListener('click', onRollbackClick);
dialog.removeEventListener('close', cleanup); dialog.removeEventListener('close', cleanup);
@ -304,7 +262,6 @@ export function openDiffModal(data: DiffModalData): void {
} }
}; };
toggleBtn.addEventListener('click', onToggle);
closeBtn.addEventListener('click', onClose); closeBtn.addEventListener('click', onClose);
rollbackBtn.addEventListener('click', onRollbackClick); rollbackBtn.addEventListener('click', onRollbackClick);
dialog.addEventListener('close', cleanup); dialog.addEventListener('close', cleanup);

View file

@ -12,10 +12,6 @@ import {
SAFE_MODE_STORAGE_KEY, SAFE_MODE_STORAGE_KEY,
THEME_STORAGE_KEY, THEME_STORAGE_KEY,
applyTheme, applyTheme,
el,
extractErrorMessage,
flushViewCleanups,
getDashboardLivePatchers,
initialDeviceSafeMode, initialDeviceSafeMode,
type ClientAuthRequirements, type ClientAuthRequirements,
type ClientSecuritySettings, type ClientSecuritySettings,
@ -23,7 +19,16 @@ import {
type ConfigOverview, type ConfigOverview,
type RouteId, type RouteId,
} from './state.js'; } 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'; import { MultiplexWsClient } from './ws-client.js';
const VALID_ROUTES = new Set<RouteId>([ const VALID_ROUTES = new Set<RouteId>([
@ -162,175 +167,93 @@ async function refreshOverview(): Promise<void> {
updateTopBarUi(); 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<void> { async function renderCurrentView(): Promise<void> {
const mySeq = ++renderSeq;
runActiveCleanup();
const root = document.getElementById('view-root')!; const root = document.getElementById('view-root')!;
updateTopBarUi(); updateTopBarUi();
try { if (!state.authenticated) {
if (!state.authenticated) { await renderAuthView(
const { renderAuthView } = await import('./views/auth-view.js'); root,
if (mySeq !== renderSeq) return; state.bootstrapped,
const cleanup = await renderAuthView( state.safeMode,
root, state.authRequirements,
state.bootstrapped, async () => {
state.safeMode, await bootstrapApp();
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,
),
); );
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<void> {
const confirmed = await confirmDialog('dialog-panic'); const confirmed = await confirmDialog('dialog-panic');
if (!confirmed) return; if (!confirmed) return;
await apiFetch('/api/security/panic-lock', { method: 'POST' }); await apiFetch('/api/security/panic-lock', { method: 'POST' });
showToast('Panic lock engaged: Vault zeroized and sessions revoked.', 'warn');
handleLocalSessionReset(true); handleLocalSessionReset(true);
} }
async function lockVaultAction(): Promise<void> {
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<void> {
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 { function handleLocalSessionReset(panic = false): void {
runActiveCleanup();
wsClient.disconnect(); wsClient.disconnect();
setCsrfToken(null); setCsrfToken(null);
state.authenticated = false; state.authenticated = false;
@ -392,7 +284,7 @@ async function syncStatusAndRender(): Promise<void> {
authenticated: boolean; authenticated: boolean;
safeMode?: boolean; safeMode?: boolean;
elevatedUntil?: number | null; elevatedUntil?: number | null;
vaultState?: ClientState['vaultState']; vaultState: ClientState['vaultState'];
vaultRuntimeReady?: boolean; vaultRuntimeReady?: boolean;
isPanicLocked?: boolean; isPanicLocked?: boolean;
defaultMobileSafeMode: boolean; defaultMobileSafeMode: boolean;
@ -403,8 +295,8 @@ async function syncStatusAndRender(): Promise<void> {
state.bootstrapped = status.bootstrapped; state.bootstrapped = status.bootstrapped;
state.authenticated = status.authenticated; state.authenticated = status.authenticated;
state.vaultState = status.vaultState ?? 'locked'; state.vaultState = status.vaultState;
state.vaultRuntimeReady = status.vaultRuntimeReady ?? false; state.vaultRuntimeReady = status.vaultRuntimeReady ?? status.vaultState === 'unlocked';
state.isPanicLocked = Boolean(status.isPanicLocked); state.isPanicLocked = Boolean(status.isPanicLocked);
state.defaultMobileSafeMode = status.defaultMobileSafeMode; state.defaultMobileSafeMode = status.defaultMobileSafeMode;
state.elevatedUntil = status.elevatedUntil ?? null; state.elevatedUntil = status.elevatedUntil ?? null;
@ -518,7 +410,6 @@ document.addEventListener('DOMContentLoaded', () => {
void renderCurrentView(); void renderCurrentView();
} }
} else if (frame.type === 'security:panic-lock') { } else if (frame.type === 'security:panic-lock') {
showToast('Panic lock engaged remotely — session terminated.', 'err');
handleLocalSessionReset(true); handleLocalSessionReset(true);
} else if (frame.type === 'config:updated' && state.authenticated) { } else if (frame.type === 'config:updated' && state.authenticated) {
void refreshOverview().then(() => { void refreshOverview().then(() => {
@ -527,80 +418,35 @@ document.addEventListener('DOMContentLoaded', () => {
} }
}); });
} else if (frame.type === 'metrics:tick' && state.authenticated && state.route === 'dashboard') { } 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') { } 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) { if (needsRefresh) {
void renderCurrentView(); void renderCurrentView();
} }
} else if (frame.type === 'alerts:update') { } else if (frame.type === 'alerts:update') {
const prevAlerts = state.activeAlertCount;
state.activeAlertCount = frame.activeCount; state.activeAlertCount = frame.activeCount;
updateTopBarUi(); updateTopBarUi();
if (state.authenticated && frame.activeCount > prevAlerts) {
showToast(`Active alerts increased to ${frame.activeCount}.`, 'warn');
}
if (state.authenticated && state.route === 'alerts') { if (state.authenticated && state.route === 'alerts') {
void renderCurrentView(); void renderCurrentView();
} }
} }
}); });
const openPalette = async () => { document.getElementById('safe-toggle-btn')!.addEventListener('click', async () => {
if (!state.authenticated) return; const next = !state.safeMode;
const { openCommandPalette } = await import('./command-palette.js'); localStorage.setItem(SAFE_MODE_STORAGE_KEY, next ? '1' : '0');
openCommandPalette({ state.safeMode = next;
state, setApiSafeMode(next);
navigate: (hash) => { if (next) state.elevatedUntil = null;
window.location.hash = hash; wsClient.send({ type: 'safe-mode', enabled: next });
}, if (state.authenticated) {
toggleSafeMode, await apiFetch('/api/auth/safe-mode', {
lockVault: lockVaultAction, method: 'POST',
triggerPanic: triggerPanicLock, body: { enabled: next },
}); });
};
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();
}
} }
updateTopBarUi();
}); });
document.getElementById('theme-select')!.addEventListener('change', (ev) => { document.getElementById('theme-select')!.addEventListener('change', (ev) => {

View file

@ -74,28 +74,24 @@ export interface ClientSecuritySettings {
requireTotpOnLogin: boolean; requireTotpOnLogin: boolean;
passwordMode: 'any' | 'all'; passwordMode: 'any' | 'all';
totpMode: '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'; stepUpMethod: 'totp' | 'password' | 'both' | 'passkey';
elevateOnLogin: boolean; elevateOnLogin: boolean;
keepElevationOnSafeMode: boolean; keepElevationOnSafeMode: boolean;
enableEmergencySecretsBackup: boolean; enableEmergencySecretsBackup: boolean;
allowSameOriginProxy?: boolean;
egressAllowedCidrs?: string[];
sessionTtlHours?: number;
sessionIdleTimeoutMin?: number;
} }
export interface ClientAuthRequirements { export interface ClientAuthRequirements {
requireTotpOnLogin: boolean; requireTotpOnLogin: boolean;
passwordMode: 'any' | 'all'; passwordMode: 'any' | 'all';
passwordCount: number; passwordCount: number;
passwordLabels?: Array<{ id: string; label: string }>; passwordLabels: Array<{ id: string; label: string }>;
totpMode: 'any' | 'all'; totpMode: 'any' | 'all';
totpCount: number; totpCount: number;
totpLabels?: Array<{ id: string; label: string }>; totpLabels: Array<{ id: string; label: string }>;
passkeyCount: number; passkeyCount: number;
stepUpPolicy?: ClientSecuritySettings['stepUpPolicy']; stepUpPolicy: ClientSecuritySettings['stepUpPolicy'];
stepUpMethod?: ClientSecuritySettings['stepUpMethod']; stepUpMethod: ClientSecuritySettings['stepUpMethod'];
} }
export interface ClientState { export interface ClientState {
@ -225,40 +221,3 @@ export function fmtUptime(sec: number): string {
export function extractErrorMessage(err: unknown): string { export function extractErrorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err); 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
}
}
}

View file

@ -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);
}

View file

@ -7,7 +7,6 @@ import {
extractErrorMessage, extractErrorMessage,
type ClientState, type ClientState,
} from '../state.js'; } from '../state.js';
import { showToast } from '../toast.js';
import type { MultiplexWsClient } from '../ws-client.js'; import type { MultiplexWsClient } from '../ws-client.js';
export type ClientAiSurface = 'workflows' | 'systems' | 'snippets' | 'logs' | 'setup'; export type ClientAiSurface = 'workflows' | 'systems' | 'snippets' | 'logs' | 'setup';
@ -28,7 +27,6 @@ export interface OpenAiDrawerOptions {
contextText?: string; contextText?: string;
serverId?: string; serverId?: string;
targetPath?: string; targetPath?: string;
targetId?: string;
defaultDraftKind?: ClientAiDraftKind; defaultDraftKind?: ClientAiDraftKind;
onInsertTerminalText?: (cmd: string) => void; onInsertTerminalText?: (cmd: string) => void;
onApplied?: () => Promise<void> | void; onApplied?: () => Promise<void> | void;
@ -105,29 +103,18 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
const statusLine = el('p', { class: 'form-msg muted' }, ''); const statusLine = el('p', { class: 'form-msg muted' }, '');
const sendBtn = el('button', { type: 'submit', class: 'btn btn-primary btn-sm' }, 'Send'); 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 }> = []; const history: Array<{ role: 'user' | 'assistant'; content: string }> = [];
let activeChatId: string | null = null; let activeChatId: string | null = null;
let currentReply = ''; let currentReply = '';
let unsubWs: (() => void) | null = null; let unsubWs: (() => void) | null = null;
let unsubChannel: (() => void) | null = null;
const releaseChannel = () => {
if (unsubChannel) {
unsubChannel();
unsubChannel = null;
}
};
const cleanup = () => { const cleanup = () => {
if (activeChatId) { if (activeChatId) {
const cid = activeChatId; opts.wsClient.send({ type: 'ai:cancel', chatId: activeChatId });
opts.wsClient.send({ type: 'ai:cancel', chatId: cid });
void apiFetch(`/api/ai/chat/${encodeURIComponent(cid)}/cancel`, { method: 'POST' }).catch(() => undefined);
activeChatId = null; activeChatId = null;
} }
releaseChannel();
if (unsubWs) { if (unsubWs) {
unsubWs(); unsubWs();
unsubWs = null; unsubWs = null;
@ -183,11 +170,7 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
| { valid: false; issues: Array<{ path: string; message: string }> } | { valid: false; issues: Array<{ path: string; message: string }> }
>('/api/ai/validate-draft', { >('/api/ai/validate-draft', {
method: 'POST', method: 'POST',
body: { body: { kind: draftKindSel.value, jsonText: jsonBlock },
kind: draftKindSel.value,
jsonText: jsonBlock,
...(opts.targetId ? { targetId: opts.targetId } : {}),
},
}); });
draftOutputBox.replaceChildren(); draftOutputBox.replaceChildren();
@ -255,14 +238,11 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
if (currentReply) history.push({ role: 'assistant', content: currentReply }); if (currentReply) history.push({ role: 'assistant', content: currentReply });
appendBoundedStreamText(streamPre, '\n'); appendBoundedStreamText(streamPre, '\n');
activeChatId = null; activeChatId = null;
releaseChannel();
sendBtn.disabled = false; sendBtn.disabled = false;
stopBtn.disabled = true; stopBtn.disabled = true;
if (!frame.error) { if (!frame.error) {
statusLine.className = 'form-msg ok-text'; statusLine.className = 'form-msg ok-text';
statusLine.textContent = 'Response complete. Review any extracted draft below.'; statusLine.textContent = 'Response complete. Review any extracted draft below.';
} else {
showToast(frame.error, 'err');
} }
refreshDraftActions(); refreshDraftActions();
} }
@ -321,17 +301,13 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
}, },
}); });
activeChatId = started.chatId; activeChatId = started.chatId;
releaseChannel(); opts.wsClient.subscribe([`ai:${started.chatId}`]);
unsubChannel = opts.wsClient.subscribe([`ai:${started.chatId}`]);
} catch (err) { } catch (err) {
history.pop(); history.pop();
releaseChannel();
sendBtn.disabled = false; sendBtn.disabled = false;
stopBtn.disabled = true; stopBtn.disabled = true;
const errMsg = extractErrorMessage(err);
statusLine.className = 'form-msg err-text'; statusLine.className = 'form-msg err-text';
statusLine.textContent = errMsg; statusLine.textContent = extractErrorMessage(err);
showToast(errMsg, 'err');
} }
}); });

View file

@ -23,7 +23,7 @@ interface AlertChannelItem {
interface AlertRuleItem { interface AlertRuleItem {
id: string; id: string;
name: string; name: string;
kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system' | 'security-event'; kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system';
severity: 'warn' | 'critical'; severity: 'warn' | 'critical';
target: { serverId?: string; tags?: string[]; all?: boolean }; target: { serverId?: string; tags?: string[]; all?: boolean };
forConsecutivePolls: number; forConsecutivePolls: number;
@ -40,7 +40,6 @@ interface AlertRuleItem {
probeId?: string; probeId?: string;
systemId?: string; systemId?: string;
item?: string; item?: string;
events?: string[];
} }
interface MaintenanceWindowItem { 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 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 chExtra = el('input', { placeholder: 'Telegram chatId OR ntfy topic (optional)' });
const chRef = el('select', {}); const chRef = el('select', {});
const webhookCreds = credsRes.credentials.filter((cr) => cr.type === 'webhook-secret'); for (const cr of credsRes.credentials) {
for (const cr of webhookCreds) {
chRef.append(el('option', { value: cr.id }, `${cr.id} (${cr.type})`)); chRef.append(el('option', { value: cr.id }, `${cr.id} (${cr.type})`));
} }
if (webhookCreds.length === 0) { if (credsRes.credentials.length === 0) {
chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add webhook-secret in Vault)')); chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add in Vault)'));
} }
const chForm = el( const chForm = el(
'form', 'form',
@ -387,9 +385,7 @@ export async function renderAlertsView(
? `offline >= ${r.offlineSec}s` ? `offline >= ${r.offlineSec}s`
: r.kind === 'probe' : r.kind === 'probe'
? `probe ${r.probeId ?? '*'}` ? `probe ${r.probeId ?? '*'}`
: r.kind === 'security-event' : `system ${r.systemId}/${r.item ?? '*'}`;
? `security-event [${r.events?.join(', ') ?? ''}]`
: `system ${r.systemId}/${r.item ?? '*'}`;
const toggleBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, r.enabled ? 'Disable' : 'Enable'); const toggleBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, r.enabled ? 'Disable' : 'Enable');
toggleBtn.addEventListener('click', () => { toggleBtn.addEventListener('click', () => {
void saveConfig({ void saveConfig({
@ -408,9 +404,9 @@ export async function renderAlertsView(
const ruleId = el('input', { placeholder: 'high-cpu', required: true }); const ruleId = el('input', { placeholder: 'high-cpu', required: true });
const ruleName = el('input', { placeholder: 'High CPU Usage', 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 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 ruleThresh = el('input', { type: 'number', value: '85', placeholder: 'Threshold / Offline sec' });
const rulePolls = el('input', { type: 'number', min: 1, value: '3', placeholder: 'forConsecutivePolls' }); const rulePolls = el('input', { type: 'number', min: 1, value: '3', placeholder: 'forConsecutivePolls' });
const ruleChans = el('input', { placeholder: 'channelIds comma-sep (optional)' }); 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 }; nextRule = { ...base, kind: 'probe', probeId: ruleParam1.value.trim() || undefined };
} else if (ruleKind.value === 'system') { } else if (ruleKind.value === 'system') {
nextRule = { ...base, kind: 'system', systemId: ruleParam1.value.trim() || 'docker-compose' }; 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 { } else {
nextRule = { ...base, kind: 'metric', metric: (ruleParam1.value.trim() || 'cpuPct') as 'cpuPct', operator: 'gt', threshold: Number(ruleThresh.value || 85) }; nextRule = { ...base, kind: 'metric', metric: (ruleParam1.value.trim() || 'cpuPct') as 'cpuPct', operator: 'gt', threshold: Number(ruleThresh.value || 85) };
} }

View file

@ -7,11 +7,9 @@ import {
import { getPasskeyAssertion, isWebAuthnSupported } from '../webauthn.js'; import { getPasskeyAssertion, isWebAuthnSupported } from '../webauthn.js';
interface BootstrapData { interface BootstrapData {
bootstrapToken?: string;
secretBase32: string; secretBase32: string;
otpauthUri: string; otpauthUri: string;
qrSvg: string; qrSvg: string;
qrDataUri?: string;
} }
export async function renderAuthView( export async function renderAuthView(
@ -87,36 +85,14 @@ export async function renderAuthView(
placeholder: '6-digit code from authenticator', placeholder: '6-digit code from authenticator',
required: true, 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 = ''; let secretBase32 = '';
try { try {
const data = await apiFetch<BootstrapData>('/api/auth/bootstrap'); const data = await apiFetch<BootstrapData>('/api/auth/bootstrap');
secretBase32 = data.secretBase32; secretBase32 = data.secretBase32;
bootTokInput.value = data.bootstrapToken ?? ''; const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml');
if ( if (doc.documentElement.nodeName === 'svg') {
typeof data.qrDataUri === 'string' && qrContainer.append(document.importNode(doc.documentElement, true));
/^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));
}
} }
secretLine.textContent = `Secret: ${data.secretBase32}`; secretLine.textContent = `Secret: ${data.secretBase32}`;
} catch (err) { } catch (err) {
@ -139,8 +115,6 @@ export async function renderAuthView(
el('div', { class: 'stack' }, el('label', {}, 'Scan TOTP QR Code'), qrContainer, secretLine), el('div', { class: 'stack' }, el('label', {}, 'Scan TOTP QR Code'), qrContainer, secretLine),
el('label', { for: 'boot-totp' }, 'Verify 6-Digit TOTP Code'), el('label', { for: 'boot-totp' }, 'Verify 6-Digit TOTP Code'),
codeInput, codeInput,
el('label', { for: 'boot-token' }, 'Bootstrap Token (if GCOORD_BOOTSTRAP_TOKEN is enforced)'),
bootTokInput,
statusMsg, statusMsg,
submitBtn, submitBtn,
); );
@ -150,7 +124,6 @@ export async function renderAuthView(
statusMsg.textContent = ''; statusMsg.textContent = '';
submitBtn.disabled = true; submitBtn.disabled = true;
try { try {
const tok = bootTokInput.value.trim();
const res = await apiFetch<{ const res = await apiFetch<{
csrfToken: string; csrfToken: string;
recoveryCodes: string[]; recoveryCodes: string[];
@ -161,7 +134,6 @@ export async function renderAuthView(
password: passInput.value, password: passInput.value,
totpCode: codeInput.value.trim(), totpCode: codeInput.value.trim(),
secretBase32, secretBase32,
...(tok ? { bootstrapToken: tok } : {}),
initialSafeMode, initialSafeMode,
securityPreset: presetSelect.value, securityPreset: presetSelect.value,
}, },
@ -311,7 +283,7 @@ export async function renderAuthView(
form.append(el('label', { for: 'login-username' }, 'Username'), userInput); form.append(el('label', { for: 'login-username' }, 'Username'), userInput);
const passwordInputs: HTMLInputElement[] = []; 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++) { for (let i = 0; i < pwCount; i++) {
const labelText = const labelText =
pwMode === 'all' ? `Password — ${pwLabels[i]?.label ?? `#${i + 1}`}` : 'Password'; pwMode === 'all' ? `Password — ${pwLabels[i]?.label ?? `#${i + 1}`}` : 'Password';
@ -338,7 +310,7 @@ export async function renderAuthView(
const codeInputs: HTMLInputElement[] = []; const codeInputs: HTMLInputElement[] = [];
if (requireTotp) { 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++) { for (let i = 0; i < totpCount; i++) {
const labelText = const labelText =
totpMode === 'all' totpMode === 'all'

View file

@ -1,4 +1,3 @@
import { collapseDiffHunks, computeLineDiff, type CollapsedDiffEntry } from '../../../shared/diff.js';
import { apiFetch, type ApiError } from '../api.js'; import { apiFetch, type ApiError } from '../api.js';
import { confirmDialog, openDiffModal } from '../dialogs.js'; import { confirmDialog, openDiffModal } from '../dialogs.js';
import { import {
@ -6,11 +5,9 @@ import {
extractErrorMessage, extractErrorMessage,
fmtTime, fmtTime,
isAiEnabled, isAiEnabled,
registerViewCleanup,
type ClientState, type ClientState,
type ConfigOverview, type ConfigOverview,
} from '../state.js'; } from '../state.js';
import { showToast } from '../toast.js';
import type { MultiplexWsClient } from '../ws-client.js'; import type { MultiplexWsClient } from '../ws-client.js';
interface FileDetails { 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(); msgEl.replaceChildren();
try { try {
await apiFetch('/api/config/file', { await apiFetch('/api/config/file', {
method: 'PUT', method: 'PUT',
body: { path: details.filePath, content: editor.value }, body: { path: details.filePath, content: editor.value },
}); });
showToast(`Saved ${details.filePath}.`, 'ok');
await onReloadOverview(); await onReloadOverview();
} catch (err) { } catch (err) {
const apiErr = err as ApiError; 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}`)); 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( const actionRow = el('div', { class: 'row' }, fmtBtn, saveBtn);
'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);
if (isAiEnabled(state)) { if (isAiEnabled(state)) {
const aiBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Assist]'); const aiBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Assist]');
aiBtn.addEventListener('click', async () => { aiBtn.addEventListener('click', async () => {
@ -370,10 +336,7 @@ export async function renderConfigView(
diffBtn.addEventListener('click', async () => { diffBtn.addEventListener('click', async () => {
const res = await apiFetch<{ const res = await apiFetch<{
revision: { id: number; filePath: string; source: string; createdAt: number }; revision: { id: number; filePath: string; source: string; createdAt: number };
diff: { diff: { lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }> };
lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>;
collapsedLines?: CollapsedDiffEntry[];
};
}>(`/api/config/revisions/${rev.id}/diff`); }>(`/api/config/revisions/${rev.id}/diff`);
openDiffModal({ openDiffModal({
revisionId: res.revision.id, revisionId: res.revision.id,
@ -381,7 +344,6 @@ export async function renderConfigView(
source: res.revision.source, source: res.revision.source,
createdAt: res.revision.createdAt, createdAt: res.revision.createdAt,
lines: res.diff.lines, lines: res.diff.lines,
collapsedLines: res.diff.collapsedLines,
onRollback: async () => { onRollback: async () => {
await apiFetch(`/api/config/revisions/${rev.id}/rollback`, { method: 'POST' }); await apiFetch(`/api/config/revisions/${rev.id}/rollback`, { method: 'POST' });
await onReloadOverview(); await onReloadOverview();

View file

@ -16,16 +16,11 @@ import {
extractErrorMessage, extractErrorMessage,
fmtBytesPerSec, fmtBytesPerSec,
fmtUptime, fmtUptime,
registerDashboardLivePatchers,
registerViewCleanup,
type ClientState, type ClientState,
type ServerEntry, type ServerEntry,
} from '../state.js'; } from '../state.js';
import { showToast } from '../toast.js';
const sparkHistory = new Map<string, number[]>(); const sparkHistory = new Map<string, number[]>();
let fleetFilter: 'all' | 'connected' | 'issues' = 'all';
let fleetSearch = '';
function statusBadgeClass(status: string): string { function statusBadgeClass(status: string): string {
if (status === 'connected') return 'badge badge-ok'; if (status === 'connected') return 'badge badge-ok';
@ -68,18 +63,11 @@ function renderProbesInto(container: Element, probes: ProbeSample[]): void {
container.replaceChildren(); container.replaceChildren();
if (probes.length === 0) return; if (probes.length === 0) return;
for (const p of probes) { 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( container.append(
el( el(
'span', 'span',
{ class: `badge ${cls}` }, { class: `badge ${p.ok ? 'badge-ok' : 'badge-err'}` },
`${p.probeId}: ${p.ok ? `OK ${Math.round(p.latencyMs)}ms` : 'FAIL'}${tlsNote}`, `${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.textContent = `[${st.status.toUpperCase()}]`;
badge.className = statusBadgeClass(st.status); badge.className = statusBadgeClass(st.status);
} }
card.setAttribute('data-status', st.status);
const osBadge = card.querySelector('[data-field="os"]'); const osBadge = card.querySelector('[data-field="os"]');
if (osBadge && st.osDetected) { if (osBadge && st.osDetected) {
osBadge.textContent = st.osDetected; osBadge.textContent = st.osDetected;
@ -153,16 +140,12 @@ async function openRegisterServerDialog(
const form = document.getElementById('dialog-srv-form') as HTMLFormElement; const form = document.getElementById('dialog-srv-form') as HTMLFormElement;
const credSelect = document.getElementById('srv-cred') as HTMLSelectElement; const credSelect = document.getElementById('srv-cred') as HTMLSelectElement;
const jumpSelect = document.getElementById('srv-jump') 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 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 closeBtn = document.getElementById('srv-reg-close') as HTMLButtonElement;
const cancelBtn = document.getElementById('srv-reg-cancel') as HTMLButtonElement; const cancelBtn = document.getElementById('srv-reg-cancel') as HTMLButtonElement;
form.reset(); form.reset();
errEl.textContent = ''; errEl.textContent = '';
testMsgEl.textContent = '';
testMsgEl.className = 'form-msg';
credSelect.replaceChildren(); credSelect.replaceChildren();
try { try {
@ -189,69 +172,8 @@ async function openRegisterServerDialog(
jumpSelect.append(el('option', { value: s.config.id }, `${s.config.id} (${s.config.host})`)); 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 = () => { const cleanup = () => {
form.removeEventListener('submit', onSubmit); form.removeEventListener('submit', onSubmit);
testBtn.removeEventListener('click', onTestConn);
closeBtn.removeEventListener('click', onClose); closeBtn.removeEventListener('click', onClose);
cancelBtn.removeEventListener('click', onClose); cancelBtn.removeEventListener('click', onClose);
dialog.removeEventListener('close', onDialogClose); dialog.removeEventListener('close', onDialogClose);
@ -266,18 +188,34 @@ async function openRegisterServerDialog(
const onSubmit = async (ev: Event) => { const onSubmit = async (ev: Event) => {
ev.preventDefault(); ev.preventDefault();
errEl.textContent = ''; 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 { try {
await apiFetch('/api/servers', { await apiFetch('/api/servers', {
method: 'POST', 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', method: 'POST',
}).catch(() => undefined); }).catch(() => undefined);
if (dialog.open) dialog.close(); if (dialog.open) dialog.close();
showToast(`Server "${payload.id}" registered.`, 'ok');
await onRegistered(); await onRegistered();
} catch (err) { } catch (err) {
errEl.textContent = extractErrorMessage(err); errEl.textContent = extractErrorMessage(err);
@ -285,118 +223,17 @@ async function openRegisterServerDialog(
}; };
form.addEventListener('submit', onSubmit); form.addEventListener('submit', onSubmit);
testBtn.addEventListener('click', onTestConn);
closeBtn.addEventListener('click', onClose); closeBtn.addEventListener('click', onClose);
cancelBtn.addEventListener('click', onClose); cancelBtn.addEventListener('click', onClose);
dialog.addEventListener('close', onDialogClose); dialog.addEventListener('close', onDialogClose);
dialog.showModal(); dialog.showModal();
} }
async function openImportSshConfigDialog(onImported: () => Promise<void>): Promise<void> {
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( export async function renderDashboardView(
root: HTMLElement, root: HTMLElement,
state: ClientState, state: ClientState,
): Promise<void> { ): Promise<void> {
root.replaceChildren(); root.replaceChildren();
registerDashboardLivePatchers({
onTick: patchDashboardServerTick,
onStates: patchDashboardServerStates,
});
registerViewCleanup(() => {
registerDashboardLivePatchers(null);
});
const [res, pinnedRes] = await Promise.all([ const [res, pinnedRes] = await Promise.all([
apiFetch<{ servers: ServerEntry[] }>('/api/servers'), apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
apiFetch<{ apiFetch<{
@ -457,90 +294,18 @@ export async function renderDashboardView(
void renderDashboardView(root, state); 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 const vaultSummary = !state.vaultRuntimeReady
? 'Vault: sealed (master key required)' ? 'Vault: sealed (master key required)'
: state.vaultState === 'unlocked' : state.vaultState === 'unlocked'
? 'Vault: unlocked (editable)' ? 'Vault: unlocked (editable)'
: 'Vault: locked (collectors & secrets active)'; : '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( root.append(
el( el(
'div', 'div',
{ class: 'panel stack' }, { class: 'panel row-between' },
el( el('div', {}, el('h1', {}, `Fleet Monitor (${servers.length} servers)`), el('span', { class: 'muted' }, vaultSummary)),
'div', el('div', { class: 'row' }, registerBtn, rotateFleetBtn, refreshBtn),
{ 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,
),
), ),
actionStatus, actionStatus,
); );
@ -749,12 +514,7 @@ export async function renderDashboardView(
const card = el( const card = el(
'article', 'article',
{ { class: 'panel panel-region', 'data-server-card': config.id },
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(),
},
el( el(
'div', 'div',
{ class: 'row-between' }, { class: 'row-between' },
@ -799,5 +559,4 @@ export async function renderDashboardView(
grid.append(card); grid.append(card);
} }
root.append(grid); root.append(grid);
applyFleetFilter();
} }

View file

@ -1,23 +1,19 @@
import type { DiskSample, ProbeSample } from '../../../shared/ws-protocol.js'; import type { DiskSample, ProbeSample } from '../../../shared/ws-protocol.js';
import { apiFetch } from '../api.js'; import { apiFetch } from '../api.js';
import { createDualRangeChartSvg, createRangeChartSvg } from '../charts.js'; import { createRangeChartSvg } from '../charts.js';
import { confirmDialog } from '../dialogs.js'; import { confirmDialog } from '../dialogs.js';
import { import {
el, el,
extractErrorMessage, extractErrorMessage,
fmtBytesPerSec,
fmtTime, fmtTime,
type ServerEntry, type ServerEntry,
} from '../state.js'; } from '../state.js';
import { showToast } from '../toast.js';
type DetailTab = 'metrics' | 'inspector' | 'keys' | 'tunnels'; type DetailTab = 'metrics' | 'inspector' | 'keys' | 'tunnels';
let activeTab: DetailTab = 'metrics'; let activeTab: DetailTab = 'metrics';
let activeRange: '1h' | '6h' | '24h' | '7d' | '30d' = '1h'; let activeRange: '1h' | '6h' | '24h' | '7d' | '30d' = '1h';
let procSortBy: 'cpu' | 'mem' = 'cpu'; let procSortBy: 'cpu' | 'mem' = 'cpu';
let inspectSudo = false;
let showAllKnownHosts = false;
export async function renderServerDetailView( export async function renderServerDetailView(
root: HTMLElement, root: HTMLElement,
@ -41,36 +37,6 @@ export async function renderServerDetailView(
} }
const header = el('section', { class: 'panel' }); 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( const reconnBtn = el(
'button', 'button',
{ type: 'button', class: 'btn btn-sm mutating-action' }, { type: 'button', class: 'btn btn-sm mutating-action' },
@ -144,7 +110,6 @@ export async function renderServerDetailView(
'div', 'div',
{ class: 'row' }, { class: 'row' },
el('span', { class: 'badge' }, `[${entry.runtime.status.toUpperCase()}]`), el('span', { class: 'badge' }, `[${entry.runtime.status.toUpperCase()}]`),
testConnBtn,
reconnBtn, reconnBtn,
delBtn, delBtn,
el('a', { href: '#dashboard', class: 'btn btn-sm' }, '← Dashboard'), el('a', { href: '#dashboard', class: 'btn btn-sm' }, '← Dashboard'),
@ -162,7 +127,7 @@ export async function renderServerDetailView(
} else if (activeTab === 'inspector') { } else if (activeTab === 'inspector') {
await renderInspectorTab(body, serverId); await renderInspectorTab(body, serverId);
} else if (activeTab === 'keys') { } else if (activeTab === 'keys') {
await renderKeysTab(body, serverId, `${entry.config.host}:${entry.config.port}`); await renderKeysTab(body, serverId);
} else { } else {
const { renderTunnelsPanel } = await import('./tunnels-panel.js'); const { renderTunnelsPanel } = await import('./tunnels-panel.js');
await renderTunnelsPanel(body, serverId); await renderTunnelsPanel(body, serverId);
@ -170,20 +135,13 @@ export async function renderServerDetailView(
} }
async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<void> { async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<void> {
const [data, probeHistRes] = await Promise.all([ const data = await apiFetch<{
apiFetch<{ range: string;
range: string; granularity: 'raw' | '1h' | '1d';
granularity: 'raw' | '1h' | '1d'; points: Array<Record<string, number>>;
points: Array<Record<string, number>>; latestDisks: DiskSample[];
latestDisks: DiskSample[]; latestProbes: Array<ProbeSample & { ts: number }>;
latestProbes: Array<ProbeSample & { ts: number }>; }>(`/api/servers/${encodeURIComponent(serverId)}/metrics?range=${activeRange}`);
probeHistory?: Array<ProbeSample & { ts: number }>;
diskHistory?: Array<{ ts: number; mountPoint: string; usedPct: number; usedMb: number; totalMb: number }>;
}>(`/api/servers/${encodeURIComponent(serverId)}/metrics?range=${activeRange}`),
apiFetch<{ samples: Array<ProbeSample & { ts: number }> }>(
`/api/servers/${encodeURIComponent(serverId)}/probes/history?range=${activeRange}`,
).catch(() => ({ samples: [] })),
]);
const rangeBar = el( const rangeBar = el(
'div', 'div',
@ -215,22 +173,6 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
return p.memTotalMb ? ((p.memUsedMb ?? 0) / p.memTotalMb) * 100 : 0; return p.memTotalMb ? ((p.memUsedMb ?? 0) / p.memTotalMb) * 100 : 0;
}); });
const loadSeries = data.points.map((p) => p.load1m ?? p.loadMax ?? 0); const loadSeries = data.points.map((p) => 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<number, number>();
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( const chartsGrid = el(
'div', 'div',
@ -238,25 +180,6 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
el('div', { class: 'panel' }, el('h2', {}, 'CPU %'), createRangeChartSvg(cpuSeries, { maxVal: 100 })), el('div', { class: 'panel' }, el('h2', {}, 'CPU %'), createRangeChartSvg(cpuSeries, { maxVal: 100 })),
el('div', { class: 'panel' }, el('h2', {}, 'Memory %'), createRangeChartSvg(memSeries, { maxVal: 100, color: 'var(--ok)' })), el('div', { class: 'panel' }, el('h2', {}, 'Memory %'), createRangeChartSvg(memSeries, { maxVal: 100, color: 'var(--ok)' })),
el('div', { class: 'panel' }, el('h2', {}, 'Load Average (1m)'), createRangeChartSvg(loadSeries, { color: 'var(--warn)' })), el('div', { class: 'panel' }, el('h2', {}, 'Load Average (1m)'), createRangeChartSvg(loadSeries, { color: 'var(--warn)' })),
el(
'div',
{ class: 'panel' },
el('h2', {}, 'Net I/O (RX / TX)'),
el('div', { class: 'muted mono' }, `RX ${fmtBytesPerSec(lastRx)} | TX ${fmtBytesPerSec(lastTx)}`),
createDualRangeChartSvg(netRxSeries, netTxSeries, { colorA: 'var(--accent)', colorB: 'var(--warn)' }),
),
el(
'div',
{ class: 'panel' },
el('h2', {}, 'Max Disk %'),
createRangeChartSvg(diskSeries, { maxVal: 100, color: 'var(--err)' }),
),
el(
'div',
{ class: 'panel' },
el('h2', {}, 'Probe Latency (ms)'),
createRangeChartSvg(probeLatencySeries, { color: 'var(--ok)' }),
),
); );
body.append(chartsGrid); body.append(chartsGrid);
@ -279,82 +202,16 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
diskPanel.append(el('div', { class: 'table-wrap' }, dTable)); diskPanel.append(el('div', { class: 'table-wrap' }, dTable));
body.append(diskPanel); body.append(diskPanel);
// Probes table + Run Now + Probe History summary // Probes table
const probePanel = el('section', { class: 'panel' }); const probePanel = el('section', { class: 'panel' });
const okProbes = probeHistory.filter((p) => p.ok).length; probePanel.append(el('h2', {}, 'Endpoint Health Probes'));
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',
),
),
);
const pTable = el('table'); const pTable = el('table');
pTable.append( 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'))));
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'),
),
),
);
const pBody = el('tbody'); const pBody = el('tbody');
if (data.latestProbes.length === 0) { 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 { } else {
for (const p of data.latestProbes) { 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( pBody.append(
el( el(
'tr', 'tr',
@ -363,10 +220,8 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
el('td', {}, el('span', { class: `badge ${p.ok ? 'badge-ok' : 'badge-err'}` }, p.ok ? 'OK' : 'FAIL')), el('td', {}, el('span', { class: `badge ${p.ok ? 'badge-ok' : 'badge-err'}` }, p.ok ? 'OK' : 'FAIL')),
el('td', { class: 'mono' }, p.statusCode ? String(p.statusCode) : '—'), el('td', { class: 'mono' }, p.statusCode ? String(p.statusCode) : '—'),
el('td', { class: 'mono' }, `${Math.round(p.latencyMs)} ms`), el('td', { class: 'mono' }, `${Math.round(p.latencyMs)} ms`),
el('td', {}, tlsBadge),
el('td', { class: 'mono' }, fmtTime(p.ts)), el('td', { class: 'mono' }, fmtTime(p.ts)),
el('td', { class: 'mono err-text' }, p.error ?? '—'), el('td', { class: 'mono err-text' }, p.error ?? '—'),
el('td', {}, runBtn),
), ),
); );
} }
@ -379,11 +234,6 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<void> { async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<void> {
const sortCpuBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'cpu' ? ' btn-primary' : ''}` }, 'Sort CPU'); 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 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'); const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh Snapshot');
sortCpuBtn.addEventListener('click', () => { sortCpuBtn.addEventListener('click', () => {
@ -396,18 +246,13 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<
body.replaceChildren(); body.replaceChildren();
void renderInspectorTab(body, serverId); void renderInspectorTab(body, serverId);
}); });
sudoBtn.addEventListener('click', () => {
inspectSudo = !inspectSudo;
body.replaceChildren();
void renderInspectorTab(body, serverId);
});
refreshBtn.addEventListener('click', () => { refreshBtn.addEventListener('click', () => {
body.replaceChildren(); body.replaceChildren();
void renderInspectorTab(body, serverId); void renderInspectorTab(body, serverId);
}); });
body.append( 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 { 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 }>; processes: Array<{ pid: number; user: string; cpuPct: number; memPct: number; rssMb: number; command: string }>;
ports: Array<{ proto: string; localAddress: string; process: string }>; ports: Array<{ proto: string; localAddress: string; process: string }>;
thermals: Array<{ zone: string; tempC: number }>; 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) => const sortedProcs = [...res.processes].sort((a, b) =>
procSortBy === 'cpu' ? b.cpuPct - a.cpuPct : b.memPct - a.memPct, procSortBy === 'cpu' ? b.cpuPct - a.cpuPct : b.memPct - a.memPct,
); );
const procTable = el('table'); 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'); const pBody = el('tbody');
for (const p of sortedProcs) { 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( pBody.append(
el( 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))),
'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'))),
),
); );
} }
procTable.append(pBody); 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<void> { async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void> {
const msg = el('p', { class: 'form-msg' }); const msg = el('p', { class: 'form-msg' });
const rotateBtn = el( const rotateBtn = el(
'button', 'button',
@ -520,7 +330,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: s
const r = res.results[0]; const r = res.results[0];
if (r?.ok) { if (r?.ok) {
body.replaceChildren(); body.replaceChildren();
await renderKeysTab(body, serverId, hostPortKey); await renderKeysTab(body, serverId);
} else { } else {
msg.className = 'form-msg err-text'; msg.className = 'form-msg err-text';
msg.textContent = `Rotation failed (rolledBack=${String(r?.rolledBack)}): ${r?.error ?? 'unknown'}`; 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: { credentialId: deploySelect.value },
}); });
body.replaceChildren(); body.replaceChildren();
await renderKeysTab(body, serverId, hostPortKey); await renderKeysTab(body, serverId);
} catch (err) { } catch (err) {
msg.className = 'form-msg err-text'; msg.className = 'form-msg err-text';
msg.textContent = extractErrorMessage(err); msg.textContent = extractErrorMessage(err);
@ -566,72 +376,6 @@ async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: s
msg, 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 { try {
const res = await apiFetch<{ const res = await apiFetch<{
entries: Array<{ entries: Array<{
@ -666,7 +410,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: s
body: { fingerprint: k.fingerprint }, body: { fingerprint: k.fingerprint },
}); });
body.replaceChildren(); body.replaceChildren();
await renderKeysTab(body, serverId, hostPortKey); await renderKeysTab(body, serverId);
}); });
} }
kBody.append( kBody.append(

View file

@ -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<void>,
): Promise<void> {
const settingsObj = (state.overview?.settings ?? {}) as Record<string, unknown>;
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);
}

View file

@ -20,6 +20,16 @@ interface SessionRow {
current: boolean; current: boolean;
} }
interface AuditRow {
id: number;
ts: number;
action: string;
actor_ip: string;
target: string | null;
status: string;
details: string | null;
}
interface FactorsData { interface FactorsData {
passwords: Array<{ id: string; label: string; createdAt: number }>; passwords: Array<{ id: string; label: string; createdAt: number }>;
totps: Array<{ id: string; label: string; createdAt: number }>; totps: Array<{ id: string; label: string; createdAt: number }>;
@ -45,8 +55,9 @@ export async function renderSettingsView(
): Promise<void> { ): Promise<void> {
root.replaceChildren(); root.replaceChildren();
const [sessRes, factorsRes, credsRes] = await Promise.all([ const [sessRes, auditRes, factorsRes, credsRes] = await Promise.all([
apiFetch<{ sessions: SessionRow[] }>('/api/auth/sessions'), apiFetch<{ sessions: SessionRow[] }>('/api/auth/sessions'),
apiFetch<{ total: number; items: AuditRow[] }>('/api/audit?limit=40'),
apiFetch<FactorsData>('/api/auth/factors'), apiFetch<FactorsData>('/api/auth/factors'),
apiFetch<{ credentials: Array<{ id: string; name: string; type: string }> }>( apiFetch<{ credentials: Array<{ id: string; name: string; type: string }> }>(
'/api/vault/credentials', '/api/vault/credentials',
@ -187,33 +198,12 @@ export async function renderSettingsView(
'select', 'select',
{}, {},
el('option', { value: 'off', selected: sec.stepUpPolicy === 'off' ? true : undefined }, 'Off (never re-prompt)'), 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: '24h', selected: sec.stepUpPolicy === '24h' ? true : undefined }, '24 hours'),
el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour'), el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour (default)'),
el('option', { value: '15m', selected: sec.stepUpPolicy === '15m' ? true : undefined }, '15 minutes (v1.1 default)'),
el('option', { value: '5m', selected: sec.stepUpPolicy === '5m' ? true : undefined }, '5 minutes'), 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'), 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( const methodSel = el(
'select', 'select',
{}, {},
@ -280,7 +270,6 @@ export async function renderSettingsView(
policyMsg.textContent = ''; policyMsg.textContent = '';
try { try {
const nextSecurity: ClientSecuritySettings = { const nextSecurity: ClientSecuritySettings = {
...sec,
requireTotpOnLogin: reqTotpChk.checked, requireTotpOnLogin: reqTotpChk.checked,
passwordMode: pwModeSel.value as 'any' | 'all', passwordMode: pwModeSel.value as 'any' | 'all',
totpMode: totpModeSel.value as 'any' | 'all', totpMode: totpModeSel.value as 'any' | 'all',
@ -289,13 +278,6 @@ export async function renderSettingsView(
elevateOnLogin: elevateLoginChk.checked, elevateOnLogin: elevateLoginChk.checked,
keepElevationOnSafeMode: keepSafeChk.checked, keepElevationOnSafeMode: keepSafeChk.checked,
enableEmergencySecretsBackup: backupChk.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 = { const nextSettings = {
...(state.overview?.settings ?? {}), ...(state.overview?.settings ?? {}),
@ -325,18 +307,14 @@ export async function renderSettingsView(
el('div', {}, el('label', {}, 'TOTP Matching Mode'), totpModeSel), el('div', {}, el('label', {}, 'TOTP Matching Mode'), totpModeSel),
el('div', {}, el('label', {}, 'Step-Up Re-Auth Window'), policySel), el('div', {}, el('label', {}, 'Step-Up Re-Auth Window'), policySel),
el('div', {}, el('label', {}, 'Step-Up Method'), methodSel), 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( el(
'div', 'div',
{ class: 'stack', style: 'margin-top:8px' }, { class: 'stack', style: 'margin-top:8px' },
el('label', { class: 'chk-row' }, reqTotpChk, 'Require TOTP code during Login'), 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' }, 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' }, 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 automatic chmod 0600 secrets backup in data/recovery/'),
el('label', { class: 'chk-row' }, backupChk, 'Maintain passwordless emergency secrets backup in data/recovery/ (master key + vault creds only; login passwords never stored)'),
), ),
el('div', { class: 'row', style: 'margin-top:8px' }, savePolicyBtn), el('div', { class: 'row', style: 'margin-top:8px' }, savePolicyBtn),
policyMsg, policyMsg,
@ -752,7 +730,7 @@ export async function renderSettingsView(
'p', 'p',
{ class: 'muted' }, { class: 'muted' },
isWebAuthnSupported() 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.', : '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( el(
'p', 'p',
{ class: 'muted mono' }, { 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' }); const bMsg = el('p', { class: 'form-msg' });
@ -859,10 +837,7 @@ export async function renderSettingsView(
dlBackupBtn.addEventListener('click', async () => { dlBackupBtn.addEventListener('click', async () => {
bMsg.textContent = ''; bMsg.textContent = '';
try { try {
const res = await apiFetch<{ bundle: unknown }>('/api/auth/recovery-backup/export', { const res = await apiFetch<{ bundle: unknown }>('/api/auth/recovery-backup/export');
method: 'POST',
body: {},
});
const blob = new Blob([`${JSON.stringify(res.bundle, null, 2)}\n`], { const blob = new Blob([`${JSON.stringify(res.bundle, null, 2)}\n`], {
type: 'application/json', type: 'application/json',
}); });
@ -969,9 +944,41 @@ export async function renderSettingsView(
sessPanel.append(el('div', { class: 'table-wrap' }, sTable)); sessPanel.append(el('div', { class: 'table-wrap' }, sTable));
root.append(sessPanel); root.append(sessPanel);
// 6. Runtime Profile, Prometheus /metrics, Scheduled Backups & Filterable Audit Log (lazy chunk) // 6. Audit Log
const opsHost = el('div', { class: 'stack' }); const auditPanel = el('section', { class: 'panel panel-region' });
root.append(opsHost); auditPanel.append(el('h2', {}, `Security & Action Audit Log (${auditRes.total} entries)`));
const { renderSettingsOpsPanels } = await import('./settings-ops-panel.js'); const aTable = el('table');
await renderSettingsOpsPanels(opsHost, state, credsRes.credentials, onReloadState); 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);
} }

View file

@ -1,15 +1,7 @@
import { collapseDiffHunks, computeLineDiff } from '../../../shared/diff.js'; import { computeLineDiff } from '../../../shared/diff.js';
import { apiFetch, apiUploadBinary } from '../api.js'; import { apiFetch, apiUploadBinary } from '../api.js';
import { confirmDialog } from '../dialogs.js'; import { confirmDialog } from '../dialogs.js';
import { import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js';
el,
extractErrorMessage,
fmtTime,
registerViewCleanup,
type ClientState,
type ServerEntry,
} from '../state.js';
import { showToast } from '../toast.js';
import { renderTunnelsPanel } from './tunnels-panel.js'; import { renderTunnelsPanel } from './tunnels-panel.js';
interface SftpEntry { interface SftpEntry {
@ -20,9 +12,6 @@ interface SftpEntry {
mode: number; mode: number;
permissionsOctal: string; permissionsOctal: string;
mtimeMs: number; mtimeMs: number;
uid?: number;
gid?: number;
symlinkTarget?: string;
} }
interface SftpTextPayload { interface SftpTextPayload {
@ -38,8 +27,6 @@ let currentServerId = '';
let currentPath = ''; let currentPath = '';
let activeEdit: SftpTextPayload | null = null; let activeEdit: SftpTextPayload | null = null;
let activeEditSudo = false; let activeEditSudo = false;
let searchMatches: string[] | null = null;
let lastSearchQuery = '';
function fmtFileSize(bytes: number): string { function fmtFileSize(bytes: number): string {
if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes} B`; if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes} B`;
@ -55,35 +42,16 @@ function showSftpDiffDialog(
onConfirm: (force: boolean) => Promise<void>, onConfirm: (force: boolean) => Promise<void>,
): void { ): void {
const diff = computeLineDiff(originalText, nextText, 'remote', 'edited'); 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'); const dialog = document.createElement('dialog');
dialog.className = 'dialog-wide'; dialog.className = 'dialog-wide';
dialog.setAttribute('aria-labelledby', 'sftp-diff-title'); dialog.setAttribute('aria-labelledby', 'sftp-diff-title');
const pre = el('pre', { class: 'diff-body mono' }); const pre = el('pre', { class: 'diff-body mono' });
const toggleDiffBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: !hasHunk }, 'Expand Full Diff'); for (const line of diff.lines) {
const renderDiffBody = () => { const cls = line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : '';
pre.replaceChildren(); const prefix = line.type === 'add' ? '+' : line.type === 'del' ? '-' : ' ';
const src = expanded ? diff.lines : collapsed; pre.append(el('div', { class: cls }, `${prefix}${line.text}`));
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();
const errEl = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' }); const errEl = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' });
const forceWrap = el('div', { hidden: true }); const forceWrap = el('div', { hidden: true });
@ -115,7 +83,7 @@ function showSftpDiffDialog(
dialog.append( 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('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, pre,
errEl, errEl,
el('div', { class: 'dialog-actions' }, forceWrap, writeBtn), el('div', { class: 'dialog-actions' }, forceWrap, writeBtn),
@ -170,13 +138,9 @@ export async function renderSftpView(
return; return;
} }
const targetServer = q.server ?? q.serverId; if (q.server && servers.some((s) => s.config.id === q.server)) {
if (targetServer && servers.some((s) => s.config.id === targetServer)) { if (currentServerId !== q.server) currentPath = '';
if (currentServerId !== targetServer) { currentServerId = q.server;
currentPath = '';
searchMatches = null;
}
currentServerId = targetServer;
} else if (!currentServerId || !servers.some((s) => s.config.id === currentServerId)) { } else if (!currentServerId || !servers.some((s) => s.config.id === currentServerId)) {
currentServerId = servers[0]!.config.id; currentServerId = servers[0]!.config.id;
} }
@ -221,7 +185,6 @@ export async function renderSftpView(
const goPath = (nextPath: string) => { const goPath = (nextPath: string) => {
currentPath = nextPath; currentPath = nextPath;
activeEdit = null; activeEdit = null;
searchMatches = null;
void renderSftpView(root, state); void renderSftpView(root, state);
}; };
goBtn.addEventListener('click', () => goPath(pathInput.value.trim() || '~')); goBtn.addEventListener('click', () => goPath(pathInput.value.trim() || '~'));
@ -236,7 +199,6 @@ export async function renderSftpView(
refreshBtn.addEventListener('click', () => void renderSftpView(root, state)); refreshBtn.addEventListener('click', () => void renderSftpView(root, state));
const mkdirBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ Folder'); 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 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'); const uploadBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Upload Files');
uploadBtn.addEventListener('click', () => uploadInput.click()); 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 termHref = `#terminal?server=${encodeURIComponent(currentServerId)}&cwd=${encodeURIComponent(currentPath || '~')}`;
const archiveAutoHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=auto`; 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`; 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: archiveAutoHref, class: 'btn btn-sm', download: '' }, 'Archive Folder (.tar.zst/.gz)'),
el('a', { href: archiveGzHref, class: 'btn btn-sm', download: '' }, '.tar.gz'), el('a', { href: archiveGzHref, class: 'btn btn-sm', download: '' }, '.tar.gz'),
mkdirBtn, mkdirBtn,
touchBtn,
uploadBtn, uploadBtn,
uploadInput, uploadInput,
), ),
el('div', { class: 'row', style: 'margin-top:8px' }, searchInput, searchBtn, clearSearchBtn),
statusMsg, statusMsg,
); );
root.append(topPanel); 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 // Inline Editor with Pre-Save Diff
if (activeEdit) { if (activeEdit) {
const editBox = el('section', { class: 'panel' }); 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; if (!activeEdit) return;
showSftpDiffDialog(activeEdit.path, activeEdit.content, textarea.value, activeEditSudo, async (force) => { showSftpDiffDialog(activeEdit.path, activeEdit.content, textarea.value, activeEditSudo, async (force) => {
const res = await apiFetch<{ path: string; sha256: string; size: number }>( 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 }; activeEdit = { ...activeEdit!, content: textarea.value, sha256: res.sha256, size: res.size };
statusMsg.className = 'form-msg ok-text'; statusMsg.className = 'form-msg ok-text';
statusMsg.textContent = `Saved ${res.path} (${res.size} B)`; 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'); const closeEdBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close Editor');
closeEdBtn.addEventListener('click', () => { closeEdBtn.addEventListener('click', () => {
@ -516,42 +379,6 @@ export async function renderSftpView(
} }
}); });
const selectedPaths = new Set<string>();
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'); const tbl = el('table');
tbl.append( tbl.append(
el( el(
@ -560,11 +387,10 @@ export async function renderSftpView(
el( el(
'tr', 'tr',
{}, {},
el('th', {}, 'Sel'),
el('th', {}, 'Name'), el('th', {}, 'Name'),
el('th', {}, 'Type'), el('th', {}, 'Type'),
el('th', {}, 'Size'), el('th', {}, 'Size'),
el('th', {}, 'Mode / Owner'), el('th', {}, 'Mode'),
el('th', {}, 'Modified'), el('th', {}, 'Modified'),
el('th', {}, 'Actions'), el('th', {}, 'Actions'),
), ),
@ -575,30 +401,15 @@ export async function renderSftpView(
if (listing.parentPath) { if (listing.parentPath) {
const upBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '.. (Parent Dir)'); const upBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '.. (Parent Dir)');
upBtn.addEventListener('click', () => goPath(listing!.parentPath!)); 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) { 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', {}); const nameCell = el('td', {});
if (entry.type === 'dir') { if (entry.type === 'dir') {
const openBtn = el('button', { type: 'button', class: 'btn btn-sm' }, `[DIR] ${entry.name}/`); const openBtn = el('button', { type: 'button', class: 'btn btn-sm' }, `[DIR] ${entry.name}/`);
openBtn.addEventListener('click', () => goPath(entry.path)); openBtn.addEventListener('click', () => goPath(entry.path));
nameCell.append(openBtn); 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 { } else {
nameCell.append(el('span', { class: 'mono' }, entry.name)); nameCell.append(el('span', { class: 'mono' }, entry.name));
} }
@ -655,32 +466,6 @@ export async function renderSftpView(
await renderSftpView(root, state); 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'); const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
delBtn.addEventListener('click', async () => { delBtn.addEventListener('click', async () => {
const ok = await confirmDialog( const ok = await confirmDialog(
@ -697,20 +482,16 @@ export async function renderSftpView(
await renderSftpView(root, state); await renderSftpView(root, state);
}); });
actionsRow.append(renBtn, chmodBtn, chownBtn, delBtn); actionsRow.append(renBtn, chmodBtn, delBtn);
const ownerText =
entry.uid !== undefined && entry.gid !== undefined ? ` (${entry.uid}:${entry.gid})` : '';
tbody.append( tbody.append(
el( el(
'tr', 'tr',
{}, {},
el('td', {}, selChk),
nameCell, nameCell,
el('td', { class: 'mono' }, entry.type), el('td', { class: 'mono' }, entry.type),
el('td', { class: 'mono' }, entry.type === 'dir' ? '—' : fmtFileSize(entry.size)), 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', { class: 'mono' }, fmtTime(entry.mtimeMs)),
el('td', {}, actionsRow), el('td', {}, actionsRow),
), ),
@ -719,7 +500,7 @@ export async function renderSftpView(
tbl.append(tbody); tbl.append(tbody);
dropPanel.append( 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), el('div', { class: 'table-wrap' }, tbl),
); );
root.append(dropPanel); root.append(dropPanel);

View file

@ -7,23 +7,11 @@ import {
extractErrorMessage, extractErrorMessage,
fmtTime, fmtTime,
isAiEnabled, isAiEnabled,
registerViewCleanup,
type ClientState, type ClientState,
type ServerEntry, type ServerEntry,
} from '../state.js'; } from '../state.js';
import { showToast } from '../toast.js';
import type { MultiplexWsClient } from '../ws-client.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 { interface SystemActionDef {
id: string; id: string;
label: string; label: string;
@ -31,7 +19,6 @@ interface SystemActionDef {
mode: 'oneshot' | 'stream' | 'interactive'; mode: 'oneshot' | 'stream' | 'interactive';
sudo: boolean; sudo: boolean;
confirm: boolean; confirm: boolean;
inputs?: SystemActionInputDef[];
} }
interface SystemParamDef { interface SystemParamDef {
@ -78,88 +65,6 @@ interface ServerSnapshotView {
} }
let unsubStreamListener: (() => void) | null = null; 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<Record<string, unknown> | 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<string, { def: SystemActionInputDef; node: HTMLInputElement | HTMLSelectElement }>();
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<string, unknown> | 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<string, unknown> = {};
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 { function healthBadgeClass(h: string): string {
if (h === 'ok') return 'badge badge-ok'; if (h === 'ok') return 'badge badge-ok';
@ -270,12 +175,6 @@ async function runSystemAction(opts: {
onFinished: () => Promise<void>; onFinished: () => Promise<void>;
}): Promise<void> { }): Promise<void> {
const { action } = opts; const { action } = opts;
let actionInputs: Record<string, unknown> | undefined;
if (action.inputs && action.inputs.length > 0) {
const prompted = await promptActionInputs(action.label, action.inputs);
if (!prompted) return;
actionInputs = prompted;
}
if (action.confirm) { if (action.confirm) {
const target = opts.subItemName ?? opts.itemName ?? opts.serverId; const target = opts.subItemName ?? opts.itemName ?? opts.serverId;
const ok = await confirmDialog( const ok = await confirmDialog(
@ -287,28 +186,20 @@ async function runSystemAction(opts: {
opts.outputHost.replaceChildren(el('p', { class: 'muted mono' }, `Running ${action.label}...`)); 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: 'oneshot'; exitCode: number | null; stdout: string; stderr: string; durationMs: number }
| { mode: 'stream'; jobId: string } | { mode: 'stream'; jobId: string }
| { mode: 'interactive'; session: { sessionId: string } }; | { mode: 'interactive'; session: { sessionId: string } }
try { >(
res = await apiFetch( `/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`,
`/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`, {
{ method: 'POST',
method: 'POST', body: {
body: { itemName: opts.itemName,
itemName: opts.itemName, subItemName: opts.subItemName,
subItemName: opts.subItemName,
...(actionInputs ? { inputs: actionInputs } : {}),
},
}, },
); },
} catch (err) { );
const msg = extractErrorMessage(err);
opts.outputHost.replaceChildren(el('p', { class: 'err-text mono' }, msg));
showToast(msg, 'err');
return;
}
if (res.mode === 'interactive') { if (res.mode === 'interactive') {
window.location.hash = `#terminal?session=${encodeURIComponent(res.session.sessionId)}`; window.location.hash = `#terminal?session=${encodeURIComponent(res.session.sessionId)}`;
@ -351,14 +242,16 @@ async function runSystemAction(opts: {
} }
// Stream mode // Stream mode
releaseSystemStream(); if (unsubStreamListener) {
unsubStreamListener();
unsubStreamListener = null;
}
const logPre = el('pre', { class: 'stream-log mono' }); 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 () => { stopBtn.addEventListener('click', async () => {
await apiFetch(`/api/systems/streams/${encodeURIComponent(res.jobId)}/cancel`, { method: 'POST' }); await apiFetch(`/api/systems/streams/${encodeURIComponent(res.jobId)}/cancel`, { method: 'POST' });
stopBtn.disabled = true; stopBtn.disabled = true;
showToast(`Stream ${res.jobId} cancelled.`, 'warn');
}); });
const streamAiBtn = isAiEnabled(opts.state) const streamAiBtn = isAiEnabled(opts.state)
? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Debug Output]') ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Debug Output]')
@ -410,7 +303,7 @@ async function runSystemAction(opts: {
logPre.scrollTop = logPre.scrollHeight; logPre.scrollTop = logPre.scrollHeight;
}); });
unsubStreamChannel = opts.wsClient.subscribe([`stream:${res.jobId}`]); opts.wsClient.subscribe([`stream:${res.jobId}`]);
} }
export async function renderSystemsView( export async function renderSystemsView(
@ -418,8 +311,10 @@ export async function renderSystemsView(
state: ClientState, state: ClientState,
wsClient: MultiplexWsClient, wsClient: MultiplexWsClient,
): Promise<void> { ): Promise<void> {
releaseSystemStream(); if (unsubStreamListener) {
registerViewCleanup(releaseSystemStream); unsubStreamListener();
unsubStreamListener = null;
}
root.replaceChildren(); root.replaceChildren();
const segs = state.routeSegments ?? []; const segs = state.routeSegments ?? [];
const forceRefresh = state.routeQuery?.refresh === '1'; const forceRefresh = state.routeQuery?.refresh === '1';
@ -672,16 +567,14 @@ export async function renderSystemsView(
// Quick Editable Files via SFTP inline diff editor // Quick Editable Files via SFTP inline diff editor
if (item.editableFiles.length > 0) { if (item.editableFiles.length > 0) {
const needsSudo = system.actions.some((a) => a.sudo);
const editRow = el('div', { class: 'chip-list' }); const editRow = el('div', { class: 'chip-list' });
for (const fPath of item.editableFiles) { for (const fPath of item.editableFiles) {
editRow.append( editRow.append(
el( el(
'a', 'a',
{ {
href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}${needsSudo ? '&sudo=1' : ''}`, href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}`,
class: 'btn btn-sm', class: 'btn btn-sm',
title: fPath,
}, },
`Edit ${fPath.split('/').pop()}`, `Edit ${fPath.split('/').pop()}`,
), ),

View file

@ -3,16 +3,7 @@ import type { FitAddon } from '@xterm/addon-fit';
import type { ServerWsFrame } from '../../../shared/ws-protocol.js'; import type { ServerWsFrame } from '../../../shared/ws-protocol.js';
import { apiFetch } from '../api.js'; import { apiFetch } from '../api.js';
import { confirmDialog } from '../dialogs.js'; import { confirmDialog } from '../dialogs.js';
import { import { el, extractErrorMessage, fmtTime, isAiEnabled, type ClientState, type ServerEntry } from '../state.js';
el,
extractErrorMessage,
fmtTime,
isAiEnabled,
registerViewCleanup,
type ClientState,
type ServerEntry,
} from '../state.js';
import { showToast } from '../toast.js';
import type { MultiplexWsClient } from '../ws-client.js'; import type { MultiplexWsClient } from '../ws-client.js';
import { import {
clearTerminalComposition, clearTerminalComposition,
@ -184,7 +175,6 @@ export async function renderTerminalView(
root.replaceChildren(); root.replaceChildren();
const q = state.routeQuery ?? {}; const q = state.routeQuery ?? {};
const targetServer = q.server ?? q.serverId;
const [sessionsRes, serversRes] = await Promise.all([ const [sessionsRes, serversRes] = await Promise.all([
apiFetch<{ sessions: PtySessionInfo[] }>('/api/terminal/sessions'), apiFetch<{ sessions: PtySessionInfo[] }>('/api/terminal/sessions'),
apiFetch<{ servers: ServerEntry[] }>('/api/servers'), apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
@ -195,13 +185,13 @@ export async function renderTerminalView(
if (q.session && sessions.some((s) => s.sessionId === q.session)) { if (q.session && sessions.some((s) => s.sessionId === q.session)) {
activeSessionId = 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 // Open-Terminal-Here shortcut if not disabled by Safe Mode
if (!state.safeMode) { if (!state.safeMode) {
try { try {
const created = await apiFetch<{ session: PtySessionInfo }>('/api/terminal/sessions', { const created = await apiFetch<{ session: PtySessionInfo }>('/api/terminal/sessions', {
method: 'POST', 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]; sessions = [created.session, ...sessions];
activeSessionId = created.session.sessionId; activeSessionId = created.session.sessionId;
@ -223,7 +213,7 @@ export async function renderTerminalView(
serverSel.append( serverSel.append(
el( el(
'option', '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})`, `${s.config.name} (${s.config.id})`,
), ),
); );
@ -292,15 +282,6 @@ export async function renderTerminalView(
el('div', { class: 'row' }, serverSel, cwdInput, openShellBtn), el('div', { class: 'row' }, serverSel, cwdInput, openShellBtn),
), ),
tabsRow, tabsRow,
...(state.safeMode
? [
el(
'p',
{ class: 'warn-text mono' },
'[SAFE MODE] Read-only terminal view: keyboard input, reconnect, and session creation are locked.',
),
]
: []),
msgEl, msgEl,
), ),
); );
@ -337,40 +318,6 @@ export async function renderTerminalView(
}, },
'Export ANSI', '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 term: Terminal | null = null;
let fitAddon: FitAddon | null = null; let fitAddon: FitAddon | null = null;
@ -543,7 +490,7 @@ export async function renderTerminalView(
{ class: 'mono muted' }, { class: 'mono muted' },
`${current.title} | ${current.cols}x${current.rows} | opened ${fmtTime(current.createdAt)}`, `${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), el('div', { class: 'term-shell' }, termContainer, touchBar),
), ),
@ -683,14 +630,6 @@ export async function renderTerminalView(
typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => scheduleFit()) : null; typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => scheduleFit()) : null;
ro?.observe(termContainer); 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) => { const unsubFrame = wsClient.onFrame((frame: ServerWsFrame) => {
if (!term || !termContainer.isConnected) return; if (!term || !termContainer.isConnected) return;
if (frame.type === 'pty:output' && frame.sessionId === current.sessionId) { if (frame.type === 'pty:output' && frame.sessionId === current.sessionId) {
@ -699,8 +638,6 @@ export async function renderTerminalView(
} }
term.write(frame.data); term.write(frame.data);
} else if (frame.type === 'pty:exit' && frame.sessionId === current.sessionId) { } 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)}]`); term.writeln(`\r\n[Session exited with code ${String(frame.exitCode)}]`);
} else if (frame.type === 'error' && frame.code === 'SAFE_MODE_ACTIVE') { } else if (frame.type === 'error' && frame.code === 'SAFE_MODE_ACTIVE') {
msgEl.className = 'form-msg warn-text'; msgEl.className = 'form-msg warn-text';
@ -708,17 +645,9 @@ export async function renderTerminalView(
} }
}); });
const unsubChannel = wsClient.subscribe([`pty:${current.sessionId}`]); currentCleanup = () => {
let cleaned = false;
const disposeTerminalView = () => {
if (cleaned) return;
cleaned = true;
currentCleanup = null;
if (fitRaf !== null) window.cancelAnimationFrame(fitRaf); if (fitRaf !== null) window.cancelAnimationFrame(fitRaf);
unsubChannel();
unsubFrame(); unsubFrame();
themeObs?.disconnect();
ro?.disconnect(); ro?.disconnect();
window.removeEventListener('resize', scheduleFit); window.removeEventListener('resize', scheduleFit);
window.visualViewport?.removeEventListener('resize', scheduleFit); window.visualViewport?.removeEventListener('resize', scheduleFit);
@ -728,9 +657,7 @@ export async function renderTerminalView(
term?.dispose(); term?.dispose();
}; };
currentCleanup = disposeTerminalView; wsClient.subscribe([`pty:${current.sessionId}`]);
registerViewCleanup(disposeTerminalView);
wsClient.send({ wsClient.send({
type: 'pty:resize', type: 'pty:resize',
sessionId: current.sessionId, sessionId: current.sessionId,

View file

@ -1,13 +1,6 @@
import { apiFetch } from '../api.js'; import { apiFetch } from '../api.js';
import { confirmDialog } from '../dialogs.js'; import { confirmDialog } from '../dialogs.js';
import { import { el, extractErrorMessage, fmtTime, type ServerEntry } from '../state.js';
el,
extractErrorMessage,
fmtTime,
registerViewCleanup,
type ServerEntry,
} from '../state.js';
import { showToast } from '../toast.js';
export interface TunnelViewEntry { export interface TunnelViewEntry {
key: string; key: string;
@ -15,15 +8,11 @@ export interface TunnelViewEntry {
tunnel: { tunnel: {
id: string; id: string;
name: string; name: string;
mode: 'http-proxy' | 'local-tcp' | 'remote-tcp' | 'socks5'; mode: 'http-proxy' | 'local-tcp' | 'remote-tcp';
bindHost?: string; bindHost?: string;
bindPort?: number; bindPort?: number;
targetHost: string; targetHost: string;
targetPort: number; targetPort: number;
targetProtocol?: 'http' | 'https';
tlsRejectUnauthorized?: boolean;
tlsServerName?: string;
ttlSec?: number;
autoStart: boolean; autoStart: boolean;
}; };
active: boolean; active: boolean;
@ -31,7 +20,6 @@ export interface TunnelViewEntry {
localBoundPort?: number; localBoundPort?: number;
remoteBoundPort?: number; remoteBoundPort?: number;
proxyPath?: string; proxyPath?: string;
expiresAt?: number;
activeConnections: number; activeConnections: number;
totalConnections: number; totalConnections: number;
bytesIn: number; bytesIn: number;
@ -40,13 +28,6 @@ export interface TunnelViewEntry {
lastError?: string; 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 { function fmtBytes(bytes: number): string {
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'; if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
if (bytes < 1024) return `${bytes} B`; if (bytes < 1024) return `${bytes} B`;
@ -109,71 +90,24 @@ export async function renderTunnelsPanel(
), ),
); );
const tbody = el('tbody'); const tbody = el('tbody');
const countdownEls: Array<{ el: HTMLElement; expiresAt: number }> = [];
for (const item of tunnels) { for (const item of tunnels) {
let bindInfo: HTMLElement; const bindInfo = item.proxyPath
if (item.tunnel.mode === 'http-proxy' && item.active) { ? el('a', { href: item.proxyPath, target: '_blank', rel: 'noopener', class: 'mono' }, item.proxyPath)
const launchBtn = el( : item.tunnel.mode === 'remote-tcp'
'button', ? el(
{ type: 'button', class: 'btn btn-sm btn-primary' }, 'span',
'Open Isolated Proxy', { class: 'mono' },
); item.active && item.remoteBoundPort
launchBtn.addEventListener('click', async () => { ? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}`
launchBtn.disabled = true; : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`,
try { )
const ticketRes = await apiFetch<{ : el(
launchUrl: string; 'span',
mode: 'subdomain' | 'port' | 'same-origin'; { class: 'mono' },
expiresInSec: number; item.active && item.localBoundPort
}>( ? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}`
`/api/tunnels/${encodeURIComponent(item.serverId)}/${encodeURIComponent(item.tunnel.id)}/proxy-ticket`, : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`,
{ method: 'POST', body: {} },
); );
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( const toggleBtn = el(
'button', '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( tbody.append(
el( el(
'tr', 'tr',
@ -244,16 +169,9 @@ export async function renderTunnelsPanel(
{}, {},
el('span', { class: `badge ${item.active ? 'badge-ok' : ''}` }, item.tunnel.mode.toUpperCase()), el('span', { class: `badge ${item.active ? 'badge-ok' : ''}` }, item.tunnel.mode.toUpperCase()),
item.tunnel.autoStart ? el('div', { class: 'muted' }, 'auto-start') : '', item.tunnel.autoStart ? el('div', { class: 'muted' }, 'auto-start') : '',
ttlBadge,
), ),
el('td', {}, bindInfo), el('td', {}, bindInfo),
el( el('td', { class: 'mono' }, `${item.tunnel.targetHost}:${item.tunnel.targetPort}`),
'td',
{ class: 'mono' },
item.tunnel.mode === 'socks5'
? 'Dynamic SOCKS5'
: `${item.tunnel.targetProtocol ? `${item.tunnel.targetProtocol}://` : ''}${item.tunnel.targetHost}:${item.tunnel.targetPort}`,
),
el( el(
'td', 'td',
{ class: 'mono' }, { class: 'mono' },
@ -267,17 +185,6 @@ export async function renderTunnelsPanel(
} }
tbl.append(tbody); tbl.append(tbody);
listPanel.append(el('div', { class: 'table-wrap' }, tbl)); 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 // Add Tunnel Form
@ -287,7 +194,7 @@ export async function renderTunnelsPanel(
el( el(
'p', 'p',
{ class: 'muted' }, { 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/<id>/.',
), ),
); );
@ -306,67 +213,31 @@ export async function renderTunnelsPanel(
const modeSel = el( const modeSel = el(
'select', 'select',
{ name: 'mode' }, { name: 'mode' },
el('option', { value: 'http-proxy' }, 'http-proxy (Authenticated Web Proxy)'), el('option', { value: 'http-proxy' }, 'http-proxy (Zero-Port Web Proxy /proxy/<id>/)'),
el('option', { value: 'local-tcp' }, 'local-tcp (Local Bind -> Target)'), 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: '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 });
const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true }) as HTMLInputElement;
const targetPortInput = el('input', { const targetPortInput = el('input', {
name: 'targetPort', name: 'targetPort',
type: 'number', type: 'number',
min: 0, min: 1,
max: 65535, max: 65535,
value: '3000', value: '3000',
required: true, required: true,
}) as HTMLInputElement; });
const protoSel = el( const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp modes)' });
'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 bindPortInput = el('input', { const bindPortInput = el('input', {
name: 'bindPort', name: 'bindPort',
type: 'number', type: 'number',
min: 1, min: 1,
max: 65535, max: 65535,
placeholder: 'auto (tcp/socks5)', placeholder: 'auto (tcp modes)',
}) as HTMLInputElement; });
const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' }) as HTMLInputElement; const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' });
const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true }) as HTMLInputElement; const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true });
const formMsg = el('p', { class: 'form-msg' }); 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( form.append(
el( el(
'div', 'div',
@ -376,12 +247,10 @@ export async function renderTunnelsPanel(
el('div', {}, el('label', {}, 'Display Name'), nameInput), el('div', {}, el('label', {}, 'Display Name'), nameInput),
el('div', {}, el('label', {}, 'Mode'), modeSel), el('div', {}, el('label', {}, 'Mode'), modeSel),
el('div', {}, el('label', {}, 'Target Host'), targetHostInput), el('div', {}, el('label', {}, 'Target Host'), targetHostInput),
targetPortWrap, el('div', {}, el('label', {}, 'Target Port'), targetPortInput),
el('div', {}, el('label', {}, 'Bind Host (TCP/SOCKS5)'), bindHostInput), el('div', {}, el('label', {}, 'Bind Host (TCP only)'), bindHostInput),
el('div', {}, el('label', {}, 'Bind Port (TCP/SOCKS5)'), bindPortInput), el('div', {}, el('label', {}, 'Bind Port (TCP only)'), bindPortInput),
el('div', {}, el('label', {}, 'TTL Seconds (Optional)'), ttlSecInput),
), ),
httpTlsWrap,
el( el(
'div', 'div',
{ class: 'row' }, { class: 'row' },
@ -402,12 +271,10 @@ export async function renderTunnelsPanel(
return; 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 bindHost = bindHostInput.value.trim() || undefined;
const bindPortVal = bindPortInput.value.trim(); const bindPortVal = bindPortInput.value.trim();
const bindPort = bindPortVal ? Number(bindPortVal) : undefined; const bindPort = bindPortVal ? Number(bindPortVal) : undefined;
const ttlVal = ttlSecInput.value.trim();
const ttlSec = ttlVal ? Number(ttlVal) : undefined;
try { try {
const res = await apiFetch<{ startError?: string }>('/api/tunnels', { const res = await apiFetch<{ startError?: string }>('/api/tunnels', {
@ -419,13 +286,7 @@ export async function renderTunnelsPanel(
name: nameInput.value.trim(), name: nameInput.value.trim(),
mode, mode,
targetHost: targetHostInput.value.trim() || '127.0.0.1', targetHost: targetHostInput.value.trim() || '127.0.0.1',
targetPort: mode === 'socks5' ? 0 : Number(targetPortInput.value), targetPort: 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 } : {}),
bindHost: mode === 'http-proxy' ? undefined : bindHost, bindHost: mode === 'http-proxy' ? undefined : bindHost,
bindPort: mode === 'http-proxy' ? undefined : bindPort, bindPort: mode === 'http-proxy' ? undefined : bindPort,
autoStart: autoStartChk.checked, autoStart: autoStartChk.checked,
@ -436,8 +297,6 @@ export async function renderTunnelsPanel(
if (res.startError) { if (res.startError) {
statusMsg.className = 'form-msg warn-text'; statusMsg.className = 'form-msg warn-text';
statusMsg.textContent = `Saved, but start failed: ${res.startError}`; statusMsg.textContent = `Saved, but start failed: ${res.startError}`;
} else {
showToast('Tunnel saved.', 'ok');
} }
await renderTunnelsPanel(root, fixedServerId); await renderTunnelsPanel(root, fixedServerId);
} catch (err) { } catch (err) {

View file

@ -1,7 +1,6 @@
import { apiFetch } from '../api.js'; import { apiFetch } from '../api.js';
import { confirmDialog } from '../dialogs.js'; import { confirmDialog } from '../dialogs.js';
import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js';
import { showToast } from '../toast.js';
interface VaultCredMeta { interface VaultCredMeta {
id: string; id: string;
@ -124,44 +123,19 @@ export async function renderVaultView(
onPanicLock: () => Promise<void>, onPanicLock: () => Promise<void>,
): Promise<void> { ): Promise<void> {
root.replaceChildren(); root.replaceChildren();
const [vaultData, statusRes] = await Promise.all([ const vaultData = await apiFetch<{
apiFetch<{ state: 'uninitialized' | 'locked' | 'unlocked';
state: 'uninitialized' | 'locked' | 'unlocked'; runtimeReady?: boolean;
runtimeReady?: boolean; isPanicLocked?: boolean;
sealState?: string; credentials: VaultCredMeta[];
isPanicLocked?: boolean; }>('/api/vault/credentials');
credentials: VaultCredMeta[]; const runtimeReady = Boolean(vaultData.runtimeReady ?? vaultData.state === 'unlocked');
}>('/api/vault/credentials'), state.vaultState = vaultData.state;
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;
state.vaultRuntimeReady = runtimeReady; state.vaultRuntimeReady = runtimeReady;
if (statusRes?.isPanicLocked !== undefined || vaultData.isPanicLocked !== undefined) { if (vaultData.isPanicLocked !== undefined) {
state.isPanicLocked = Boolean(statusRes?.isPanicLocked ?? vaultData.isPanicLocked); 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' }); const statusPanel = el('section', { class: 'panel' });
if (vaultData.state === 'uninitialized') { if (vaultData.state === 'uninitialized') {
@ -309,23 +283,13 @@ export async function renderVaultView(
}); });
statusPanel.append( statusPanel.append(
el('h1', {}, `Encrypted Vault — [${vaultData.state.toUpperCase()} / ${sealState.toUpperCase()}]`), el('h1', {}, 'Encrypted Vault — [LOCKED]'),
el( el(
'p', 'p',
{ class: 'muted' }, { 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.', '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,
(() => {
const sealBtn = el('button', { type: 'button', class: 'btn mutating-action' }, 'Seal Vault');
sealBtn.addEventListener('click', () => void doSealVault());
return sealBtn;
})(),
panicBtn,
), ),
el('div', { class: 'row' }, unlockBtn, panicBtn),
lockMsg, lockMsg,
credTableWrap, credTableWrap,
revealBox, revealBox,
@ -344,15 +308,9 @@ export async function renderVaultView(
await apiFetch('/api/vault/lock', { method: 'POST' }); await apiFetch('/api/vault/lock', { method: 'POST' });
await onStateChanged(); 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( 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, credTableWrap,
revealBox, revealBox,
); );

View file

@ -7,18 +7,16 @@ import {
extractErrorMessage, extractErrorMessage,
fmtTime, fmtTime,
isAiEnabled, isAiEnabled,
registerViewCleanup,
type ClientState, type ClientState,
type ServerEntry, type ServerEntry,
} from '../state.js'; } from '../state.js';
import { showToast } from '../toast.js';
import type { MultiplexWsClient } from '../ws-client.js'; import type { MultiplexWsClient } from '../ws-client.js';
type WfSubTab = 'workflows' | 'broadcast' | 'snippets'; type WfSubTab = 'workflows' | 'broadcast' | 'snippets';
interface WorkflowInputDef { interface WorkflowInputDef {
name: string; name: string;
type: 'string' | 'number' | 'boolean' | 'server' | 'select' | 'secret'; type: 'string' | 'number' | 'boolean' | 'server' | 'select';
label?: string; label?: string;
description?: string; description?: string;
required?: boolean; required?: boolean;
@ -28,7 +26,7 @@ interface WorkflowInputDef {
interface WorkflowStepDef { interface WorkflowStepDef {
id: string; id: string;
type: 'exec' | 'read-file' | 'system-action' | 'transfer' | 'http' | 'notify'; type: 'exec' | 'read-file' | 'system-action' | 'transfer';
dependsOn?: Array<string | { stepId: string; on: 'success' | 'failure' | 'always' }>; dependsOn?: Array<string | { stepId: string; on: 'success' | 'failure' | 'always' }>;
target?: { serverId?: string; tags?: string[]; all?: boolean }; target?: { serverId?: string; tags?: string[]; all?: boolean };
command?: string; command?: string;
@ -41,19 +39,7 @@ interface WorkflowStepDef {
mode?: 'hub-relayed' | 'direct'; mode?: 'hub-relayed' | 'direct';
source?: { serverId: string; path: string }; source?: { serverId: string; path: string };
destination?: { 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; timeoutSec?: number;
retries?: number;
retryBackoffSec?: number;
when?: string;
sudo?: boolean; sudo?: boolean;
captureAs?: string; captureAs?: string;
onFailure?: string | { action: string; channelId?: string; workflowId?: string }; onFailure?: string | { action: string; channelId?: string; workflowId?: string };
@ -122,18 +108,6 @@ let activeSubTab: WfSubTab = 'workflows';
let selectedRunDetailId: string | null = null; let selectedRunDetailId: string | null = null;
let broadcastPresetSnippetId: string | null = null; let broadcastPresetSnippetId: string | null = null;
let unsubWfWs: (() => void) | 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 { function statusBadgeClass(status: string): string {
if (status === 'succeeded' || status === 'ok') return 'badge badge-ok'; 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) }); ctrl = el('input', { type: 'checkbox', checked: Boolean(def.default) });
} else { } else {
ctrl = el('input', { ctrl = el('input', {
type: def.type === 'secret' ? 'password' : def.type === 'number' ? 'number' : 'text', type: def.type === 'number' ? 'number' : 'text',
value: def.type === 'secret' ? '' : def.default !== undefined ? String(def.default) : '', value: def.default !== undefined ? String(def.default) : '',
required: def.required, 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); fields.set(def.name, ctrl);
@ -445,7 +419,7 @@ function openWorkflowEditorDialog(
const sType = el( const sType = el(
'select', 'select',
{ class: 'input-sm' }, { 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), el('option', { value: t, selected: step.type === t }, t),
), ),
); );
@ -455,14 +429,6 @@ function openWorkflowEditorDialog(
step.mode = 'hub-relayed'; step.mode = 'hub-relayed';
step.source = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file' }; 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' }; 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(); redrawSteps();
}); });
@ -496,26 +462,6 @@ function openWorkflowEditorDialog(
redrawSteps(); 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( card.append(
el( el(
'div', 'div',
@ -523,57 +469,10 @@ function openWorkflowEditorDialog(
el('strong', {}, `Step #${idx + 1}`), el('strong', {}, `Step #${idx + 1}`),
el('div', { class: 'row' }, sId, sType, rmBtn), el('div', { class: 'row' }, sId, sType, rmBtn),
), ),
el('div', { class: 'grid-3', style: 'margin-top:6px' }, sDeps, sRetries, sWhen), sDeps,
); );
if (step.type === 'http') { if (step.type === 'transfer') {
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') {
const modeSel = el( const modeSel = el(
'select', 'select',
{ class: 'input-sm' }, { class: 'input-sm' },
@ -776,12 +675,11 @@ export async function renderWorkflowsView(
state: ClientState, state: ClientState,
wsClient: MultiplexWsClient, wsClient: MultiplexWsClient,
): Promise<void> { ): Promise<void> {
releaseWfWs(); if (unsubWfWs) {
const unsubBase = wsClient.subscribe(['workflows']); unsubWfWs();
registerViewCleanup(() => { unsubWfWs = null;
releaseWfWs(); }
unsubBase(); wsClient.subscribe(['workflows']);
});
root.replaceChildren(); root.replaceChildren();
const tabBar = el( const tabBar = el(
@ -863,18 +761,17 @@ export async function renderWorkflowsView(
const watchRunStream = (runId: string, wfId: string) => { const watchRunStream = (runId: string, wfId: string) => {
streamPanel.hidden = false; streamPanel.hidden = false;
const logPre = el('pre', { class: 'stream-log mono' }, `Subscribed to live run ${runId} (${wfId})...\n`); 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.addEventListener('click', async () => {
cancelBtn.disabled = true; cancelBtn.disabled = true;
await apiFetch(`/api/workflows/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' }); await apiFetch(`/api/workflows/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' });
showToast(`Cancellation requested for run ${runId}.`, 'warn');
}); });
streamPanel.replaceChildren( streamPanel.replaceChildren(
el('div', { class: 'row-between' }, el('strong', {}, `Live Run Stream: ${wfId} (${runId})`), cancelBtn), el('div', { class: 'row-between' }, el('strong', {}, `Live Run Stream: ${wfId} (${runId})`), cancelBtn),
logPre, logPre,
); );
releaseWfWs(); if (unsubWfWs) unsubWfWs();
unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => {
if (frame.type === 'stream:chunk' && frame.jobId === `wf:${runId}`) { if (frame.type === 'stream:chunk' && frame.jobId === `wf:${runId}`) {
if (frame.stream !== 'meta') { 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) => { const loadRunDetail = async (runId: string) => {
@ -905,29 +802,6 @@ export async function renderWorkflowsView(
}>(`/api/workflows/runs/${encodeURIComponent(runId)}`); }>(`/api/workflows/runs/${encodeURIComponent(runId)}`);
detailPanel.hidden = false; detailPanel.hidden = false;
renderStructuredOutput(detailPanel, res.workflow, res.run, res.stepLogs); 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)) { if (isAiEnabled(state)) {
const diagBtn = el( const diagBtn = el(
'button', 'button',
@ -1070,10 +944,9 @@ export async function renderWorkflowsView(
}); });
const actRow = el('div', { class: 'row' }, inspectBtn); const actRow = el('div', { class: 'row' }, inspectBtn);
if (r.status === 'running' || r.status === 'queued') { 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 () => { cancelBtn.addEventListener('click', async () => {
await apiFetch(`/api/workflows/runs/${encodeURIComponent(r.runId)}/cancel`, { method: 'POST' }); await apiFetch(`/api/workflows/runs/${encodeURIComponent(r.runId)}/cancel`, { method: 'POST' });
showToast(`Cancelled run ${r.runId}.`, 'warn');
await renderWorkflowsView(root, state, wsClient); await renderWorkflowsView(root, state, wsClient);
}); });
actRow.append(cancelBtn); actRow.append(cancelBtn);
@ -1161,7 +1034,7 @@ export async function renderWorkflowsView(
const msgEl = el('p', { class: 'form-msg' }); const msgEl = el('p', { class: 'form-msg' });
const cardsGrid = el('div', { class: 'grid-2' }); 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; let activeJobId: string | null = null;
cancelBtn.addEventListener('click', async () => { cancelBtn.addEventListener('click', async () => {
if (!activeJobId) return; if (!activeJobId) return;
@ -1226,7 +1099,7 @@ export async function renderWorkflowsView(
); );
} }
releaseWfWs(); if (unsubWfWs) unsubWfWs();
unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => {
if (frame.type !== 'stream:chunk' || frame.jobId !== activeJobId || frame.stream !== 'meta') return; if (frame.type !== 'stream:chunk' || frame.jobId !== activeJobId || frame.stream !== 'meta') return;
try { try {
@ -1261,77 +1134,20 @@ export async function renderWorkflowsView(
cancelBtn.hidden = true; cancelBtn.hidden = true;
msgEl.className = 'form-msg ok-text'; msgEl.className = 'form-msg ok-text';
msgEl.textContent = `Broadcast finished: ${String(m.okCount)}/${String(m.total)} succeeded.`; msgEl.textContent = `Broadcast finished: ${String(m.okCount)}/${String(m.total)} succeeded.`;
void loadBroadcastHistory();
} }
} catch { } catch {
// Ignore meta parse error // Ignore meta parse error
} }
}); });
unsubWfChannel = wsClient.subscribe([`stream:${activeJobId}`]); wsClient.subscribe([`stream:${activeJobId}`]);
} catch (err) { } catch (err) {
msgEl.className = 'form-msg err-text'; msgEl.className = 'form-msg err-text';
msgEl.textContent = extractErrorMessage(err); 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); panel.append(el('h2', {}, 'Ad-Hoc Fleet Broadcast'), form);
root.append(panel, cardsGrid, histPanel); root.append(panel, cardsGrid);
void loadBroadcastHistory();
return; return;
} }

View file

@ -2,24 +2,16 @@ import type { ClientWsFrame, ServerWsFrame } from '../../shared/ws-protocol.js';
export type WsConnectionStatus = 'online' | 'reconnecting' | 'offline'; export type WsConnectionStatus = 'online' | 'reconnecting' | 'offline';
const CORE_CHANNELS = ['config', 'alerts', 'metrics', 'workflows'] as const;
export class MultiplexWsClient { export class MultiplexWsClient {
private ws: WebSocket | null = null; private ws: WebSocket | null = null;
private reconnectAttempt = 0; private reconnectAttempt = 0;
private reconnectTimer: number | null = null; private reconnectTimer: number | null = null;
private pingTimer: number | null = null; private pingTimer: number | null = null;
private shouldRun = false; private shouldRun = false;
private readonly channelRefs = new Map<string, number>(); private channels = new Set<string>(['config', 'alerts', 'metrics', 'workflows']);
private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>(); private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>();
private readonly statusListeners = new Set<(status: WsConnectionStatus) => 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 { onFrame(listener: (frame: ServerWsFrame) => void): () => void {
this.frameListeners.add(listener); this.frameListeners.add(listener);
return () => this.frameListeners.delete(listener); return () => this.frameListeners.delete(listener);
@ -45,11 +37,6 @@ export class MultiplexWsClient {
window.clearInterval(this.pingTimer); window.clearInterval(this.pingTimer);
this.pingTimer = null; 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) { if (this.ws) {
this.ws.close(1000, 'Client disconnect'); this.ws.close(1000, 'Client disconnect');
this.ws = null; this.ws = null;
@ -63,54 +50,14 @@ export class MultiplexWsClient {
} }
} }
/** subscribe(channels: string[]): void {
* Reference-counted channel subscription. Returns a cleanup callback that for (const ch of channels) this.channels.add(ch);
* releases this caller's references and sends `{ type: 'unsub' }` once refcount hits 0. this.send({ type: 'sub', channels });
*/
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 });
}
} }
private openSocket(): void { private openSocket(): void {
if (!this.shouldRun) return; if (!this.shouldRun) return;
if ( if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
this.ws &&
(this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)
) {
return; return;
} }
@ -121,9 +68,8 @@ export class MultiplexWsClient {
socket.addEventListener('open', () => { socket.addEventListener('open', () => {
this.reconnectAttempt = 0; this.reconnectAttempt = 0;
this.emitStatus('online'); this.emitStatus('online');
const allActive = [...this.channelRefs.keys()]; if (this.channels.size > 0) {
if (allActive.length > 0) { this.send({ type: 'sub', channels: [...this.channels] });
this.send({ type: 'sub', channels: allActive });
} }
if (this.pingTimer !== null) window.clearInterval(this.pingTimer); if (this.pingTimer !== null) window.clearInterval(this.pingTimer);
this.pingTimer = window.setInterval(() => { this.pingTimer = window.setInterval(() => {

View file

@ -13,9 +13,7 @@ import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js';
import type { WsHub } from '../api/ws-hub.js'; import type { WsHub } from '../api/ws-hub.js';
import type { ConfigManager } from '../config/config-manager.js'; import type { ConfigManager } from '../config/config-manager.js';
import { computeLineDiff, type DiffLine } from '../config/diff.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 type { AuditService } from '../security/audit.js';
import { fetchWithEgressGuard } from '../security/egress-guard.js';
import type { VaultService } from '../security/vault.js'; import type { VaultService } from '../security/vault.js';
import type { SSHPool } from '../ssh/ssh-pool.js'; import type { SSHPool } from '../ssh/ssh-pool.js';
import { 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 { export interface ChatMessageInput {
role: 'user' | 'assistant'; role: 'user' | 'assistant';
content: string; content: string;
@ -74,7 +64,6 @@ export class AiService {
private readonly sshPool: SSHPool, private readonly sshPool: SSHPool,
private readonly wsHub: WsHub, private readonly wsHub: WsHub,
private readonly auditService: AuditService, private readonly auditService: AuditService,
private readonly getRuntimeLimits?: () => RuntimeLimits,
) {} ) {}
getReplayFrames(chatId: string): ServerWsFrame[] { getReplayFrames(chatId: string): ServerWsFrame[] {
@ -104,8 +93,11 @@ export class AiService {
private resolveBearerToken(secretRef?: string): string | undefined { private resolveBearerToken(secretRef?: string): string | undefined {
if (!secretRef || !this.vaultService.isRuntimeReady) return undefined; if (!secretRef || !this.vaultService.isRuntimeReady) return undefined;
const cred = this.vaultService.getRuntimeSecret(secretRef); const cred = this.vaultService.getRuntimeSecret(secretRef);
if (!cred || cred.type !== 'api-token') return undefined; if (!cred) return undefined;
return cred.token; 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: { previewContext(opts: {
@ -176,12 +168,6 @@ export class AiService {
throw new AiDisabledError(); 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 knownSecrets = collectVaultSecretStrings(this.vaultService);
const guide = buildSurfaceGuideAndInventory( const guide = buildSurfaceGuideAndInventory(
opts.surface, opts.surface,
@ -303,26 +289,19 @@ export class AiService {
headers.Authorization = `Bearer ${bearerToken}`; headers.Authorization = `Bearer ${bearerToken}`;
} }
const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; const res = await fetch(endpointUrl, {
const aiCfg = this.configManager.getSettings().ai; method: 'POST',
const res = await fetchWithEgressGuard( headers,
endpointUrl, body: JSON.stringify({ model, stream: true, messages }),
{ signal: chat.abortController.signal,
method: 'POST', });
headers,
body: JSON.stringify({ model, stream: true, messages, max_tokens: aiCfg.maxTokens }),
signal: chat.abortController.signal,
},
{ allowedCidrs, timeoutMs: (aiCfg.timeoutSec ?? 90) * 1000 },
);
if (!res.ok) { if (!res.ok) {
const errBody = await res.text().catch(() => ''); const errBody = await res.text().catch(() => '');
const cleanErr = bearerToken ? errBody.split(bearerToken).join('[REDACTED]') : errBody;
this.emitDelta(chat, { this.emitDelta(chat, {
chunk: '', chunk: '',
done: true, 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; return;
} }
@ -344,22 +323,12 @@ export class AiService {
const reader = res.body.getReader(); const reader = res.body.getReader();
const decoder = new TextDecoder(); const decoder = new TextDecoder();
let buf = ''; let buf = '';
const MAX_SSE_LINE_BUF = 256 * 1024;
let doneSent = false; let doneSent = false;
while (true) { while (true) {
const { value, done } = await reader.read(); const { value, done } = await reader.read();
if (done) break; if (done) break;
buf += decoder.decode(value, { stream: true }); 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; let nlIdx: number;
while ((nlIdx = buf.indexOf('\n')) >= 0) { while ((nlIdx = buf.indexOf('\n')) >= 0) {
@ -402,11 +371,11 @@ export class AiService {
this.emitDelta(chat, { chunk: '', done: true }); this.emitDelta(chat, { chunk: '', done: true });
} }
} catch (err) { } 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 const msg = chat.abortController.signal.aborted
? 'Generation cancelled' ? 'Generation cancelled'
: safeErr; : err instanceof Error
? err.message
: String(err);
this.emitDelta(chat, { this.emitDelta(chat, {
chunk: '', chunk: '',
done: true, done: true,
@ -444,29 +413,24 @@ export class AiService {
const headers: Record<string, string> = { 'Content-Type': 'application/json' }; const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (bearer) headers.Authorization = `Bearer ${bearer}`; if (bearer) headers.Authorization = `Bearer ${bearer}`;
const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; const res = await fetch(url, {
const res = await fetchWithEgressGuard( method: 'POST',
url, headers,
{ body: JSON.stringify({
method: 'POST', model,
headers, stream: false,
body: JSON.stringify({ max_tokens: 16,
model, messages: [{ role: 'user', content: 'Reply with OK' }],
stream: false, }),
max_tokens: 16, signal: AbortSignal.timeout(10_000),
messages: [{ role: 'user', content: 'Reply with OK' }], });
}),
},
{ allowedCidrs, timeoutMs: 10_000 },
);
const latencyMs = Date.now() - started; const latencyMs = Date.now() - started;
if (!res.ok) { if (!res.ok) {
const text = await res.text().catch(() => ''); const text = await res.text().catch(() => '');
const cleanText = bearer ? text.split(bearer).join('[REDACTED]') : text;
return { return {
ok: false, ok: false,
latencyMs, 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 { const data = (await res.json().catch(() => ({}))) as {
@ -476,11 +440,10 @@ export class AiService {
data.choices?.[0]?.message?.content ?? data.choices?.[0]?.text ?? 'Connected'; data.choices?.[0]?.message?.content ?? data.choices?.[0]?.text ?? 'Connected';
return { ok: true, latencyMs, replyPreview: String(preview).trim().slice(0, 120) }; return { ok: true, latencyMs, replyPreview: String(preview).trim().slice(0, 120) };
} catch (err) { } catch (err) {
const rawErr = err instanceof Error ? err.message : String(err);
return { return {
ok: false, ok: false,
latencyMs: Date.now() - started, 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<string, unknown>).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) => const withOptionalId = (obj: unknown) =>
opts.targetId && obj && typeof obj === 'object' && !Array.isArray(obj) opts.targetId && obj && typeof obj === 'object' && !Array.isArray(obj)
? { ...(obj as Record<string, unknown>), id: opts.targetId } ? { ...(obj as Record<string, unknown>), id: (obj as Record<string, unknown>).id ?? opts.targetId }
: obj; : obj;
let targetPath: string; let targetPath: string;

View file

@ -26,8 +26,7 @@ export function buildSurfaceGuideAndInventory(
targetPath?: string; targetPath?: string;
} = {}, } = {},
): SurfaceGuideResult { ): SurfaceGuideResult {
const { configManager, sshPool } = deps; const { configManager, vaultService, sshPool } = deps;
void deps.vaultService;
const servers = configManager.listServers(); const servers = configManager.listServers();
const systems = configManager.listSystems(); const systems = configManager.listSystems();
const snippets = configManager.getSnippets().snippets; 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 })), 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 targetSrv = opts.serverId ? configManager.getServer(opts.serverId) : undefined;
const targetSrvOs = opts.serverId const targetSrvOs = opts.serverId
? sshPool.getState(opts.serverId)?.osDetected ?? targetSrv?.osHint ?? 'unknown' ? sshPool.getState(opts.serverId)?.osDetected ?? targetSrv?.osHint ?? 'unknown'
@ -64,6 +67,7 @@ export function buildSurfaceGuideAndInventory(
existingWorkflowIds: workflows.map((w) => w.id), existingWorkflowIds: workflows.map((w) => w.id),
existingSnippetIds: snippets.map((s) => s.id), existingSnippetIds: snippets.map((s) => s.id),
alertChannelIds: alerts.channels.map((c) => c.id), alertChannelIds: alerts.channels.map((c) => c.id),
vaultCredentialRefs: credMeta,
...(opts.serverId ? { focusedServer: { id: opts.serverId, os: targetSrvOs } } : {}), ...(opts.serverId ? { focusedServer: { id: opts.serverId, os: targetSrvOs } } : {}),
...(opts.targetPath ? { focusedConfigPath: opts.targetPath } : {}), ...(opts.targetPath ? { focusedConfigPath: opts.targetPath } : {}),
}, },

View file

@ -6,7 +6,9 @@ export interface RedactionResult {
truncated: boolean; truncated: boolean;
} }
const MIN_VAULT_SECRET_LEN = 4; function escapeRegExp(literal: string): string {
return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export function collectVaultSecretStrings(vaultService: VaultService): string[] { export function collectVaultSecretStrings(vaultService: VaultService): string[] {
if (!vaultService.isRuntimeReady) return []; if (!vaultService.isRuntimeReady) return [];
@ -16,21 +18,21 @@ export function collectVaultSecretStrings(vaultService: VaultService): string[]
const creds = vaultService.exportAllCredentials(); const creds = vaultService.exportAllCredentials();
for (const cred of Object.values(creds)) { for (const cred of Object.values(creds)) {
if (cred.type === 'ssh-password' || cred.type === 'sudo-password') { 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') { } 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') { } 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') { } else if (cred.type === 'ssh-key') {
const trimmed = cred.privateKey.trim(); 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/)) { for (const line of trimmed.split(/\r?\n/)) {
const l = line.trim(); const l = line.trim();
if (l.length >= 12 && !l.startsWith('-----')) { if (l.length >= 12 && !l.startsWith('-----')) {
collected.add(l); collected.add(l);
} }
} }
if (cred.passphrase && cred.passphrase.length >= MIN_VAULT_SECRET_LEN) { if (cred.passphrase && cred.passphrase.length >= 6) {
collected.add(cred.passphrase); collected.add(cred.passphrase);
} }
} }
@ -42,119 +44,6 @@ export function collectVaultSecretStrings(vaultService: VaultService): string[]
return [...collected].sort((a, b) => b.length - a.length); 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( export function redactSecrets(
input: string, input: string,
knownSecrets: string[] = [], knownSecrets: string[] = [],
@ -163,22 +52,27 @@ export function redactSecrets(
let redactedCount = 0; let redactedCount = 0;
let text = input ?? ''; let text = input ?? '';
// 1. Complete & truncated PEM / OpenSSH private keys in O(n) // 1. Strip PEM / OpenSSH private key blocks
const pem = stripPemPrivateKeys(text); const keyBlockRe =
text = pem.text; /-----BEGIN [A-Z0-9 -]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 -]*PRIVATE KEY-----/g;
redactedCount += pem.hits; 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) { for (const secret of knownSecrets) {
if (secret.length < MIN_VAULT_SECRET_LEN) continue; if (secret.length < 6) continue;
const res = replaceLiteralLinear(text, secret, '[REDACTED_VAULT_SECRET]'); const re = new RegExp(escapeRegExp(secret), 'g');
text = res.text; text = text.replace(re, () => {
redactedCount += res.hits; 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( 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) => { (_m, prefix: string, val: string) => {
if (val.includes('[REDACTED')) return _m; if (val.includes('[REDACTED')) return _m;
redactedCount += 1; redactedCount += 1;
@ -186,45 +80,25 @@ export function redactSecrets(
}, },
); );
text = text.replace( 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, /\bBearer\s+([A-Za-z0-9._~+/=-]{12,})/g,
(_m, key: string, val: string) => { (_m, val: string) => {
if (val.includes('[REDACTED')) return _m; if (val.includes('[REDACTED')) return _m;
redactedCount += 1; redactedCount += 1;
return `${key}: [REDACTED_TOKEN]`; return 'Bearer [REDACTED_TOKEN]';
}, },
); );
text = text.replace( text = text.replace(
/\b(?:Bearer|Basic)\s+([A-Za-z0-9._~+/=-]{8,1024})/g, /\b(X-(?:API-Key|Telegram-Bot-Token|Auth-Token)\s*:\s*)([^\s\r\n]+)/gi,
(full, val: string) => { (_m, prefix: string, val: string) => {
if (val.includes('[REDACTED')) return full; if (val.includes('[REDACTED')) return _m;
redactedCount += 1; 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( text = text.replace(
/([a-zA-Z][a-zA-Z0-9+.-]{1,15}:\/\/[^:/\s@]{1,64}:)([^/\s@]{1,256})@/g, /(^|[\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, 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,
(_m, lead: string, key: string, rawVal: string) => { (_m, lead: string, key: string, rawVal: string) => {
if (rawVal.includes('[REDACTED')) return _m; if (rawVal.includes('[REDACTED')) return _m;
redactedCount += 1; redactedCount += 1;
@ -232,10 +106,15 @@ export function redactSecrets(
}, },
); );
// 7. JSON "key": "secret" string properties in O(n) // 5. Strip JSON "key": "secret" string properties
const jsonRes = stripJsonSecretValues(text); text = text.replace(
text = jsonRes.text; /("(?:[A-Za-z0-9_-]*(?:password|passwd|secret|token|apiKey|api_key|privateKey|private_key|passphrase)[A-Za-z0-9_-]*)"\s*:\s*)"([^"\\]*(?:\\.[^"\\]*)*)"/gi,
redactedCount += jsonRes.hits; (_m, keyPrefix: string, val: string) => {
if (val.includes('[REDACTED')) return _m;
redactedCount += 1;
return `${keyPrefix}"[REDACTED_SECRET]"`;
},
);
const cap = Math.max(256, maxChars); const cap = Math.max(256, maxChars);
let truncated = false; let truncated = false;

View file

@ -5,7 +5,6 @@ import type {
AlertChannel, AlertChannel,
AlertRule, AlertRule,
AlertRuleTargetSchema, AlertRuleTargetSchema,
SecurityEventKind,
} from '../../shared/schemas/alerts.schema.js'; } from '../../shared/schemas/alerts.schema.js';
import type { ServerConfig } from '../../shared/schemas/server.schema.js'; import type { ServerConfig } from '../../shared/schemas/server.schema.js';
import type { z } from 'zod'; import type { z } from 'zod';
@ -18,7 +17,6 @@ import type {
MonitoringTickEvent, MonitoringTickEvent,
} from '../monitoring/monitoring-service.js'; } from '../monitoring/monitoring-service.js';
import type { AuditService } from '../security/audit.js'; import type { AuditService } from '../security/audit.js';
import { fetchWithEgressGuard } from '../security/egress-guard.js';
import type { VaultService } from '../security/vault.js'; import type { VaultService } from '../security/vault.js';
import type { SSHPool } from '../ssh/ssh-pool.js'; import type { SSHPool } from '../ssh/ssh-pool.js';
import type { import type {
@ -65,7 +63,6 @@ export class AlertEngine {
private readonly emittedOffline = new Set<string>(); private readonly emittedOffline = new Set<string>();
private readonly prevProbeOk = new Map<string, boolean>(); private readonly prevProbeOk = new Map<string, boolean>();
private readonly prevSystemDown = new Set<string>(); private readonly prevSystemDown = new Set<string>();
private readonly channelCircuit = new Map<string, { failures: number; openUntil: number }>();
private readonly unsubs: Array<() => void> = []; private readonly unsubs: Array<() => void> = [];
private sweepTimer: NodeJS.Timeout | null = null; private sweepTimer: NodeJS.Timeout | null = null;
private stopped = false; private stopped = false;
@ -86,10 +83,10 @@ export class AlertEngine {
this.stopped = false; this.stopped = false;
this.hydrateOpenIncidents(); this.hydrateOpenIncidents();
this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId, meta) => { this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId) => {
await this.sendDirectChannelMessage(channelId, { await this.sendDirectChannelMessage(channelId, {
severity: meta?.severity ?? 'critical', severity: 'critical',
title: meta?.title ?? 'Workflow Execution Failure', title: 'Workflow Execution Failure',
message, message,
state: 'firing', state: 'firing',
}); });
@ -301,20 +298,16 @@ export class AlertEngine {
throw new Error(`Unknown alert channel "${channelId}"`); throw new Error(`Unknown alert channel "${channelId}"`);
} }
const res = await this.dispatchToChannel( const res = await this.dispatchToChannel(ch, {
ch, id: `test-${crypto.randomBytes(4).toString('hex')}`,
{ ruleId: 'test-alert',
id: `test-${crypto.randomBytes(4).toString('hex')}`, serverId: 'hub',
ruleId: 'test-alert', severity: 'warn',
serverId: 'hub', title: '[TEST] GCoordinator Alert Channel Verification',
severity: 'warn', message: `Test notification dispatched to "${ch.name}" (${ch.type}) at ${new Date().toISOString()}.`,
title: '[TEST] GCoordinator Alert Channel Verification', state: 'firing',
message: `Test notification dispatched to "${ch.name}" (${ch.type}) at ${new Date().toISOString()}.`, ts: Date.now(),
state: 'firing', });
ts: Date.now(),
},
{ bypassCircuitBreaker: true },
);
this.auditService.log({ this.auditService.log({
action: 'alert.test_channel', 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( 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<string, unknown>;
} = {},
nowMs = Date.now(),
): Promise<void> {
if (this.stopped) return;
const aliasMap: Record<string, string[]> = {
'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 { 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.serverId && target.serverId !== server.id) return false;
if (target.tags && target.tags.length > 0) { if (target.tags && target.tags.length > 0) {
if (!server.tags.some((t) => target.tags!.includes(t))) return false; if (!server.tags.some((t) => target.tags!.includes(t))) return false;
@ -898,8 +751,11 @@ export class AlertEngine {
private readChannelSecret(secretRef: string): string | null { private readChannelSecret(secretRef: string): string | null {
if (!this.vaultService.isRuntimeReady) return null; if (!this.vaultService.isRuntimeReady) return null;
const cred = this.vaultService.getRuntimeSecret(secretRef); const cred = this.vaultService.getRuntimeSecret(secretRef);
if (!cred || cred.type !== 'webhook-secret') return null; if (!cred) return null;
return cred.secret; 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( private async dispatchToChannel(
@ -914,30 +770,15 @@ export class AlertEngine {
state: 'firing' | 'resolved'; state: 'firing' | 'resolved';
ts: number; ts: number;
}, },
opts: { bypassCircuitBreaker?: boolean } = {},
): Promise<{ ok: boolean; statusCode?: number; error?: string }> { ): Promise<{ ok: boolean; statusCode?: number; error?: string }> {
const cb = this.channelCircuit.get(channel.id); const secret = this.readChannelSecret(channel.secretRef);
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`,
};
}
if (!secret && !channel.url) { 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 { try {
let targetUrl = channel.url ?? ''; let targetUrl = channel.url ?? '';
const method = 'POST'; let method = 'POST';
const headers: Record<string, string> = {}; const headers: Record<string, string> = {};
let body: string; let body: string;
@ -990,42 +831,24 @@ export class AlertEngine {
body = JSON.stringify(payload); body = JSON.stringify(payload);
} }
const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; const res = await fetch(targetUrl, {
const res = await fetchWithEgressGuard( method,
targetUrl, headers,
{ method, headers, body }, body,
{ allowedCidrs, timeoutMs: 10_000 }, signal: AbortSignal.timeout(10_000),
); });
if (res.ok) {
this.channelCircuit.delete(channel.id);
} else {
this.recordChannelFailure(channel.id);
}
return { return {
ok: res.ok, ok: res.ok,
statusCode: res.status, statusCode: res.status,
error: res.ok ? undefined : `HTTP ${res.status}`, error: res.ok ? undefined : `HTTP ${res.status}`,
}; };
} catch (err) { } catch (err) {
this.recordChannelFailure(channel.id);
return { return {
ok: false, 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( function compareOp(

View file

@ -1,30 +1,23 @@
import { Router, type RequestHandler } from 'express'; import { Router } from 'express';
import { z } from 'zod'; import { z } from 'zod';
import { EntityIdSchema } from '../../../shared/schemas/common.js'; import { EntityIdSchema } from '../../../shared/schemas/common.js';
import { import { AiDisabledError, AiDraftKindSchema, type AiService } from '../../ai/ai-service.js';
AiDisabledError,
AiDraftKindSchema,
AiOverloadError,
type AiService,
} from '../../ai/ai-service.js';
import { AiSurfaceSchema } from '../../ai/guides.js'; import { AiSurfaceSchema } from '../../ai/guides.js';
import type { AuthService } from '../../security/auth.js'; import type { AuthService } from '../../security/auth.js';
import { import {
enforceSafeMode, enforceSafeMode,
requireAuth, requireAuth,
requireCsrf, requireCsrf,
requireStepUp,
} from '../../security/guards.js'; } from '../../security/guards.js';
export interface AiRouterDeps { export interface AiRouterDeps {
authService: AuthService; authService: AuthService;
aiService: AiService; aiService: AiService;
stepUpGuard?: RequestHandler;
} }
export function createAiRouter(deps: AiRouterDeps): Router { export function createAiRouter(deps: AiRouterDeps): Router {
const router = Router(); const router = Router();
const { authService, aiService, stepUpGuard = requireStepUp } = deps; const { authService, aiService } = deps;
// Read-only context redaction & preview (Safe-Mode exempt) // Read-only context redaction & preview (Safe-Mode exempt)
router.post('/context-preview', requireAuth(authService), requireCsrf, (req, res) => { 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)); res.json(aiService.validateDraft(parsed.data));
}); });
// Read-only draft streaming: Safe-Mode exempt, stepUpGuard protects Vault API token egress // Strictly read-only draft streaming: never auto-executes commands (Safe-Mode exempt)
router.post('/chat', requireAuth(authService), requireCsrf, stepUpGuard, (req, res) => { router.post('/chat', requireAuth(authService), requireCsrf, (req, res) => {
const parsed = z const parsed = z
.object({ .object({
chatId: z.string().min(1).max(64).optional(), chatId: z.string().min(1).max(64).optional(),
@ -97,8 +90,8 @@ export function createAiRouter(deps: AiRouterDeps): Router {
}); });
res.status(202).json(started); res.status(202).json(started);
} catch (err) { } catch (err) {
if (err instanceof AiDisabledError || err instanceof AiOverloadError) { if (err instanceof AiDisabledError) {
res.status(err.status).json({ error: err.code, message: err.message }); res.status(403).json({ error: err.code, message: err.message });
return; return;
} }
res.status(400).json({ res.status(400).json({
@ -113,29 +106,22 @@ export function createAiRouter(deps: AiRouterDeps): Router {
res.json({ cancelled: aiService.cancelChat(chatId) }); res.json({ cancelled: aiService.cancelChat(chatId) });
}); });
router.post( router.post('/test', requireAuth(authService), requireCsrf, enforceSafeMode, async (req, res) => {
'/test', const parsed = z
requireAuth(authService), .object({
requireCsrf, baseUrl: z.string().url().optional(),
enforceSafeMode, model: z.string().min(1).optional(),
stepUpGuard, secretRef: z.string().max(64).optional(),
async (req, res) => { })
const parsed = z .safeParse(req.body ?? {});
.object({
baseUrl: z.string().url().optional(),
model: z.string().min(1).optional(),
secretRef: z.string().max(64).optional(),
})
.safeParse(req.body ?? {});
if (!parsed.success) { if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return; return;
} }
res.json(await aiService.testEndpoint(parsed.data)); res.json(await aiService.testEndpoint(parsed.data));
}, });
);
return router; return router;
} }

View file

@ -1,4 +1,4 @@
import { Router, type RequestHandler } from 'express'; import { Router } from 'express';
import { ZodError, z } from 'zod'; import { ZodError, z } from 'zod';
import { AlertsFileSchema } from '../../../shared/schemas/alerts.schema.js'; import { AlertsFileSchema } from '../../../shared/schemas/alerts.schema.js';
import type { AlertEngine } from '../../alerts/alert-engine.js'; import type { AlertEngine } from '../../alerts/alert-engine.js';
@ -9,7 +9,6 @@ import {
enforceSafeMode, enforceSafeMode,
requireAuth, requireAuth,
requireCsrf, requireCsrf,
requireStepUp,
} from '../../security/guards.js'; } from '../../security/guards.js';
export interface AlertsRouterDeps { export interface AlertsRouterDeps {
@ -17,13 +16,11 @@ export interface AlertsRouterDeps {
configManager: ConfigManager; configManager: ConfigManager;
auditService: AuditService; auditService: AuditService;
alertEngine: AlertEngine; alertEngine: AlertEngine;
stepUpGuard?: RequestHandler;
} }
export function createAlertsRouter(deps: AlertsRouterDeps): Router { export function createAlertsRouter(deps: AlertsRouterDeps): Router {
const router = Router(); const router = Router();
const { authService, configManager, auditService, alertEngine, stepUpGuard = requireStepUp } = const { authService, configManager, auditService, alertEngine } = deps;
deps;
router.get('/', requireAuth(authService), (req, res) => { router.get('/', requireAuth(authService), (req, res) => {
const limit = typeof req.query.limit === 'string' ? Number(req.query.limit) : 50; const limit = typeof req.query.limit === 'string' ? Number(req.query.limit) : 50;
@ -33,48 +30,41 @@ export function createAlertsRouter(deps: AlertsRouterDeps): Router {
}); });
}); });
router.put( router.put('/config', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
'/config', try {
requireAuth(authService), const parsed = AlertsFileSchema.parse({ version: 1, ...(req.body ?? {}) });
requireCsrf, const saved = configManager.saveConfigText(
enforceSafeMode, 'alerts.json',
stepUpGuard, JSON.stringify(parsed, null, 2),
(req, res) => { 'ui',
try { 'Updated alerts configuration via UI',
const parsed = AlertsFileSchema.parse({ version: 1, ...(req.body ?? {}) }); );
const saved = configManager.saveConfigText( auditService.log({
'alerts.json', action: 'alerts.config_update',
JSON.stringify(parsed, null, 2), actorIp: req.clientIp ?? 'unknown',
'ui', sessionIdHash: req.authSession!.idHash,
'Updated alerts configuration via UI', target: 'alerts.json',
); status: 'ok',
auditService.log({ });
action: 'alerts.config_update', res.json({ alertsConfig: saved.config, warnings: saved.warnings });
actorIp: req.clientIp ?? 'unknown', } catch (err) {
sessionIdHash: req.authSession!.idHash, if (err instanceof ZodError) {
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;
}
res.status(400).json({ res.status(400).json({
error: 'ALERTS_SAVE_ERROR', error: 'VALIDATION_ERROR',
message: err instanceof Error ? err.message : 'Unable to save alerts configuration', 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( router.post(
'/silences', '/silences',
@ -132,7 +122,6 @@ export function createAlertsRouter(deps: AlertsRouterDeps): Router {
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
stepUpGuard,
async (req, res) => { async (req, res) => {
const id = String(req.params.id ?? ''); const id = String(req.params.id ?? '');
try { try {

View file

@ -1,33 +1,8 @@
import { Router } from 'express'; import { Router } from 'express';
import { z } from 'zod'; import type { AuditService } from '../../security/audit.js';
import type { AuditListOptions, AuditService } from '../../security/audit.js';
import type { AuthService } from '../../security/auth.js'; import type { AuthService } from '../../security/auth.js';
import { requireAuth } from '../../security/guards.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<string, unknown>): AuditListOptions & { format?: 'csv' | 'ndjson' } {
const cleaned: Record<string, unknown> = {};
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( export function createAuditRouter(
authService: AuthService, authService: AuthService,
auditService: AuditService, auditService: AuditService,
@ -35,37 +10,20 @@ export function createAuditRouter(
const router = Router(); const router = Router();
router.get('/', requireAuth(authService), (req, res) => { router.get('/', requireAuth(authService), (req, res) => {
const opts = pickFilterOptions(req.query as Record<string, unknown>); const limit = req.query.limit ? Number(req.query.limit) : 50;
const result = auditService.list(opts); const offset = req.query.offset ? Number(req.query.offset) : 0;
res.json({ const action =
...result, typeof req.query.action === 'string' && req.query.action.trim()
actions: auditService.listActions(), ? req.query.action.trim()
}); : undefined;
});
router.get('/export', requireAuth(authService), (req, res) => { res.json(
const opts = pickFilterOptions(req.query as Record<string, unknown>); auditService.list({
const format = opts.format ?? 'ndjson'; limit: Number.isFinite(limit) ? limit : 50,
const content = auditService.exportRecords(opts, format); offset: Number.isFinite(offset) ? offset : 0,
action,
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.setHeader(
'Content-Disposition',
`attachment; filename="gcoordinator-audit-export.${format === 'csv' ? 'csv' : 'ndjson'}"`,
);
res.send(content);
}); });
return router; return router;

View file

@ -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 { z } from 'zod';
import type { import type {
AuthenticationResponseJSON, AuthenticationResponseJSON,
RegistrationResponseJSON, RegistrationResponseJSON,
} from '@simplewebauthn/server'; } from '@simplewebauthn/server';
import { SecuritySettingsSchema } from '../../../shared/schemas/settings.schema.js';
import type { ConfigManager } from '../../config/config-manager.js'; import type { ConfigManager } from '../../config/config-manager.js';
import type { AuditService } from '../../security/audit.js'; import type { AuditService } from '../../security/audit.js';
import { SESSION_COOKIE_NAME, type AuthService } from '../../security/auth.js';
import { import {
AuthOverloadError,
SESSION_COOKIE_NAME,
type AuthService,
} from '../../security/auth.js';
import {
asyncHandler,
createStepUpGuard, createStepUpGuard,
enforceSafeMode, enforceSafeMode,
extractCookies, extractCookies,
@ -34,8 +28,6 @@ export interface AuthRouterDeps {
recoveryStore: EmergencyRecoveryService; recoveryStore: EmergencyRecoveryService;
rateLimiter: RateLimiter; rateLimiter: RateLimiter;
trustCloudflare: boolean; trustCloudflare: boolean;
webauthnRpId?: string;
webauthnOrigins?: string[];
} }
function isSecureCookie(req: Request, trustCloudflare: boolean): boolean { function isSecureCookie(req: Request, trustCloudflare: boolean): boolean {
@ -52,10 +44,9 @@ function setAuthCookies(
sessionToken: string, sessionToken: string,
csrfToken: string, csrfToken: string,
trustCloudflare: boolean, trustCloudflare: boolean,
sessionTtlHours = 168,
): void { ): void {
const secure = isSecureCookie(req, trustCloudflare); 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, { res.cookie(SESSION_COOKIE_NAME, sessionToken, {
httpOnly: true, httpOnly: true,
sameSite: 'strict', sameSite: 'strict',
@ -85,8 +76,6 @@ class WebAuthnRpError extends Error {
function resolveWebAuthnRp( function resolveWebAuthnRp(
req: Request, req: Request,
trustCloudflare: boolean, trustCloudflare: boolean,
configuredRpId?: string,
configuredOrigins?: string[],
): { rpID: string; expectedOrigin: string } { ): { rpID: string; expectedOrigin: string } {
const originHeader = const originHeader =
typeof req.headers.origin === 'string' && req.headers.origin.trim() typeof req.headers.origin === 'string' && req.headers.origin.trim()
@ -103,35 +92,10 @@ function resolveWebAuthnRp(
throw new WebAuthnRpError('Invalid Origin header for WebAuthn request'); throw new WebAuthnRpError('Invalid Origin header for WebAuthn request');
} }
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { const rpID = parsed.hostname;
throw new WebAuthnRpError('WebAuthn Origin must use http or https'); if (/^\d+\.\d+\.\d+\.\d+$/.test(rpID) || rpID.includes(':')) {
}
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(':')) {
throw new WebAuthnRpError( throw new WebAuthnRpError(
`WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${hostname}" is rejected by browsers).`, `WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${rpID}" 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}"`,
); );
} }
@ -151,8 +115,6 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
recoveryStore, recoveryStore,
rateLimiter, rateLimiter,
trustCloudflare, trustCloudflare,
webauthnRpId,
webauthnOrigins,
} = deps; } = deps;
const stepUpGuard = createStepUpGuard( const stepUpGuard = createStepUpGuard(
@ -171,16 +133,11 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
res.json({ res.json({
bootstrapped, bootstrapped,
authenticated: false, authenticated: false,
vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
defaultMobileSafeMode: settings.defaultMobileSafeMode, defaultMobileSafeMode: settings.defaultMobileSafeMode,
theme: settings.theme, theme: settings.theme,
authRequirements: { authRequirements,
requireTotpOnLogin: authRequirements.requireTotpOnLogin,
passwordMode: authRequirements.passwordMode,
passwordCount: authRequirements.passwordCount,
totpMode: authRequirements.totpMode,
totpCount: authRequirements.totpCount,
passkeyCount: authRequirements.passkeyCount,
},
}); });
return; return;
} }
@ -191,231 +148,196 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
safeMode: session.safeMode, safeMode: session.safeMode,
elevatedUntil: session.elevatedUntil, elevatedUntil: session.elevatedUntil,
vaultState: vaultService.state, vaultState: vaultService.state,
sealState: vaultService.sealState,
vaultRuntimeReady: vaultService.isRuntimeReady, vaultRuntimeReady: vaultService.isRuntimeReady,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
defaultMobileSafeMode: settings.defaultMobileSafeMode, defaultMobileSafeMode: settings.defaultMobileSafeMode,
theme: settings.theme, theme: settings.theme,
security: settings.security, security: settings.security,
runtime: settings.runtime,
authRequirements, authRequirements,
}); });
}); });
router.get( router.get('/bootstrap', async (req, res) => {
'/bootstrap', if (authService.isBootstrapped()) {
asyncHandler(async (req, res) => { res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' });
if (authService.isBootstrapped()) { return;
res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); }
return; const username =
} typeof req.query.username === 'string' && req.query.username.trim()
const rawUser = ? req.query.username.trim()
typeof req.query.username === 'string' && req.query.username.trim() : 'admin';
? req.query.username.trim().slice(0, 64) const data = await authService.beginBootstrap(username);
: 'admin'; res.json(data);
const data = await authService.beginBootstrap(rawUser); });
res.json(data);
}),
);
router.post( router.post('/bootstrap', async (req, res) => {
'/bootstrap', if (authService.isBootstrapped()) {
asyncHandler(async (req, res) => { res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' });
if (authService.isBootstrapped()) { return;
res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); }
return; const ip = req.clientIp ?? 'unknown';
} const rate = rateLimiter.check('bootstrap', ip);
const ip = req.clientIp ?? 'unknown'; if (!rate.allowed) {
const rate = rateLimiter.check('bootstrap', ip); res.setHeader('Retry-After', String(rate.retryAfterSec));
if (!rate.allowed) { res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
res.setHeader('Retry-After', String(rate.retryAfterSec)); return;
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); }
return;
}
const bodySchema = z.object({ const bodySchema = z.object({
username: z.string().trim().min(2).max(64).default('admin'), username: z.string().min(2).max(64).default('admin'),
password: z.string().min(10).max(256), password: z.string().min(10).max(256),
totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'), totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'),
secretBase32: z.string().max(128).optional(), secretBase32: z.string().optional(),
bootstrapToken: z.string().min(16).max(128).optional(), initialSafeMode: z.boolean().optional(),
initialSafeMode: z.boolean().optional(), securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(),
securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(), });
}); const parsed = bodySchema.safeParse(req.body);
const parsed = bodySchema.safeParse(req.body); if (!parsed.success) {
if (!parsed.success) { rateLimiter.recordFailure('bootstrap', ip);
rateLimiter.recordFailure('bootstrap', ip); res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); return;
return; }
}
try { try {
const result = await authService.completeBootstrap({ if (parsed.data.securityPreset) {
...parsed.data, const cur = configManager.getSettings();
ip, const presetSecurity =
userAgent: String(req.headers['user-agent'] ?? 'unknown'), parsed.data.securityPreset === 'relaxed'
}); ? {
...cur.security,
if (parsed.data.securityPreset) { requireTotpOnLogin: false,
const cur = configManager.getSettings(); stepUpPolicy: 'off' as const,
const presetSecurity = stepUpMethod: 'password' as const,
parsed.data.securityPreset === 'relaxed' elevateOnLogin: true,
keepElevationOnSafeMode: true,
}
: parsed.data.securityPreset === 'strict'
? { ? {
...cur.security, ...cur.security,
requireTotpOnLogin: false, requireTotpOnLogin: true,
stepUpPolicy: 'off' as const, stepUpPolicy: '5m' as const,
stepUpMethod: 'password' as const, stepUpMethod: 'totp' as const,
elevateOnLogin: true, elevateOnLogin: false,
keepElevationOnSafeMode: true, keepElevationOnSafeMode: false,
} }
: parsed.data.securityPreset === 'strict' : cur.security;
? {
...cur.security,
requireTotpOnLogin: true,
stepUpPolicy: '5m' as const,
stepUpMethod: 'totp' as const,
elevateOnLogin: false,
keepElevationOnSafeMode: false,
}
: cur.security;
configManager.saveConfigText( configManager.saveConfigText(
'settings.json', 'settings.json',
JSON.stringify({ ...cur, security: presetSecurity }, null, 2), JSON.stringify({ ...cur, security: presetSecurity }, null, 2),
'ui', 'ui',
`Bootstrap preset: ${parsed.data.securityPreset}`, `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;
} }
try { const result = await authService.completeBootstrap({
const bodySchema = z ...parsed.data,
.object({ ip,
username: z.string().trim().min(1).max(64), userAgent: String(req.headers['user-agent'] ?? 'unknown'),
password: z.string().min(1).max(256).optional(), });
passwords: z.array(z.string().min(1).max(256)).max(16).optional(), rateLimiter.recordSuccess('bootstrap', ip);
code: z.string().max(64).optional(), setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare);
codes: z.array(z.string().max(64)).max(16).optional(), auditService.log({
initialSafeMode: z.boolean().optional(), action: 'auth.bootstrap',
}) actorIp: ip,
.refine( sessionIdHash: result.session.idHash,
(b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)), target: parsed.data.username,
'Password is required', status: 'ok',
); });
const parsed = bodySchema.safeParse(req.body); res.status(201).json({
if (!parsed.success) { authenticated: true,
rateLimiter.recordFailure('login', ip); csrfToken: result.csrfToken,
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); recoveryCodes: result.recoveryCodes,
return; 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({ router.post('/login', async (req, res) => {
...parsed.data, if (!authService.isBootstrapped()) {
ip, res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
userAgent: String(req.headers['user-agent'] ?? 'unknown'), 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 bodySchema = z
const failState = rateLimiter.recordFailure('login', ip); .object({
if (failState.lockedUntil > 0 || failState.globalTriggered) { username: z.string().min(1).optional(),
authService.emitSecurityEvent('auth.lockout', ip, { password: z.string().min(1).optional(),
failures: failState.failures, passwords: z.array(z.string().min(1)).optional(),
globalTriggered: failState.globalTriggered, code: z.string().max(32).optional(),
}); codes: z.array(z.string().max(32)).optional(),
} initialSafeMode: z.boolean().optional(),
auditService.log({ })
action: 'auth.login', .refine(
actorIp: ip, (b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)),
target: parsed.data.username, 'Password is required',
status: 'denied', );
}); const parsed = bodySchema.safeParse(req.body);
res.status(401).json({ error: 'INVALID_CREDENTIALS' }); if (!parsed.success) {
return; rateLimiter.recordFailure('login', ip);
} res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return;
}
const ttlHours = configManager.getSettings().security.sessionTtlHours; const result = await authService.login({
rateLimiter.recordSuccess('login', ip); ...parsed.data,
setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); ip,
auditService.log({ userAgent: String(req.headers['user-agent'] ?? 'unknown'),
action: 'auth.login', });
actorIp: ip,
sessionIdHash: result.session.idHash,
target: parsed.data.username,
status: 'ok',
});
res.json({ if (!result) {
authenticated: true, rateLimiter.recordFailure('login', ip);
csrfToken: result.csrfToken, auditService.log({
safeMode: result.session.safeMode, action: 'auth.login',
elevatedUntil: result.session.elevatedUntil, actorIp: ip,
vaultState: vaultService.state, target: parsed.data.username ?? 'admin',
vaultRuntimeReady: vaultService.isRuntimeReady, status: 'denied',
}); });
} finally { res.status(401).json({ error: 'INVALID_CREDENTIALS' });
rateLimiter.releaseInFlight('login', ip); 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 // Exempt from enforceSafeMode
router.post('/logout', requireAuth(authService), requireCsrf, (req, res) => { router.post('/logout', requireAuth(authService), requireCsrf, (req, res) => {
@ -461,7 +383,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
asyncHandler(async (req, res) => { async (req, res) => {
const ip = req.clientIp ?? 'unknown'; const ip = req.clientIp ?? 'unknown';
const rate = rateLimiter.check('step-up', ip); const rate = rateLimiter.check('step-up', ip);
if (!rate.allowed) { if (!rate.allowed) {
@ -472,10 +394,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
const parsed = z const parsed = z
.object({ .object({
code: z.string().max(64).optional(), code: z.string().optional(),
codes: z.array(z.string().max(64)).max(16).optional(), codes: z.array(z.string()).optional(),
password: z.string().max(256).optional(), password: z.string().optional(),
passwords: z.array(z.string().max(256)).max(16).optional(), passwords: z.array(z.string()).optional(),
}) })
.safeParse(req.body ?? {}); .safeParse(req.body ?? {});
if (!parsed.success) { if (!parsed.success) {
@ -485,12 +407,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
const outcome = await authService.stepUp(req.authSession!.idHash, parsed.data); const outcome = await authService.stepUp(req.authSession!.idHash, parsed.data);
if (!outcome.ok) { if (!outcome.ok) {
const failState = rateLimiter.recordFailure('step-up', ip); rateLimiter.recordFailure('step-up', ip);
if (failState.lockedUntil > 0) {
authService.emitSecurityEvent('auth.step_up_lockout', ip, {
failures: failState.failures,
});
}
auditService.log({ auditService.log({
action: 'auth.step_up', action: 'auth.step_up',
actorIp: ip, actorIp: ip,
@ -513,7 +430,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
status: 'ok', status: 'ok',
}); });
res.json({ elevatedUntil: outcome.elevatedUntil }); res.json({ elevatedUntil: outcome.elevatedUntil });
}), },
); );
router.post('/drop-elevation', requireAuth(authService), requireCsrf, (req, res) => { router.post('/drop-elevation', requireAuth(authService), requireCsrf, (req, res) => {
@ -710,7 +627,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
stepUpGuard, stepUpGuard,
asyncHandler(async (req, res) => { async (req, res) => {
const parsed = z const parsed = z
.object({ label: z.string().min(1).max(64).default('Passkey') }) .object({ label: z.string().min(1).max(64).default('Passkey') })
.safeParse(req.body ?? {}); .safeParse(req.body ?? {});
@ -719,7 +636,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
return; return;
} }
try { try {
const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); const rp = resolveWebAuthnRp(req, trustCloudflare);
const data = await authService.beginPasskeyRegistration({ const data = await authService.beginPasskeyRegistration({
label: parsed.data.label, label: parsed.data.label,
...rp, ...rp,
@ -731,7 +648,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
message: err instanceof Error ? err.message : 'Unable to start passkey registration', message: err instanceof Error ? err.message : 'Unable to start passkey registration',
}); });
} }
}), },
); );
router.post( router.post(
@ -740,10 +657,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
stepUpGuard, stepUpGuard,
asyncHandler(async (req, res) => { async (req, res) => {
const parsed = z const parsed = z
.object({ .object({
challengeId: z.string().min(1).max(128), challengeId: z.string().min(1),
response: z.record(z.unknown()), response: z.record(z.unknown()),
}) })
.safeParse(req.body ?? {}); .safeParse(req.body ?? {});
@ -770,7 +687,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
message: err instanceof Error ? err.message : 'Unable to verify passkey registration', message: err instanceof Error ? err.message : 'Unable to verify passkey registration',
}); });
} }
}), },
); );
router.delete( router.delete(
@ -804,115 +721,102 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
}, },
); );
router.post( router.post('/passkeys/login/options', async (req, res) => {
'/passkeys/login/options', if (!authService.isBootstrapped()) {
asyncHandler(async (req, res) => { res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
if (!authService.isBootstrapped()) { return;
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); }
return; const ip = req.clientIp ?? 'unknown';
} const rate = rateLimiter.check('login', ip);
const ip = req.clientIp ?? 'unknown'; if (!rate.allowed) {
const rate = rateLimiter.check('login', ip); res.setHeader('Retry-After', String(rate.retryAfterSec));
if (!rate.allowed) { res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
res.setHeader('Retry-After', String(rate.retryAfterSec)); return;
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); }
return; try {
} const rp = resolveWebAuthnRp(req, trustCloudflare);
try { const data = await authService.beginPasskeyAuthentication({
const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); purpose: 'login',
const data = await authService.beginPasskeyAuthentication({ ...rp,
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,
}); });
if (!result) { res.json(data);
const failState = rateLimiter.recordFailure('login', ip); } catch (err) {
if (failState.lockedUntil > 0 || failState.globalTriggered) { res.status(400).json({
authService.emitSecurityEvent('auth.lockout', ip, { error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_LOGIN_OPTIONS_FAILED',
failures: failState.failures, message: err instanceof Error ? err.message : 'No passkeys available',
globalTriggered: failState.globalTriggered, });
}); }
} });
auditService.log({
action: 'auth.passkey_login',
actorIp: ip,
status: 'denied',
});
res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' });
return;
}
const ttlHours = configManager.getSettings().security.sessionTtlHours; router.post('/passkeys/login/verify', async (req, res) => {
rateLimiter.recordSuccess('login', ip); if (!authService.isBootstrapped()) {
setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); 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({ auditService.log({
action: 'auth.passkey_login', action: 'auth.passkey_login',
actorIp: ip, actorIp: ip,
sessionIdHash: result.session.idHash, status: 'denied',
status: 'ok',
}); });
res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' });
return;
}
res.json({ rateLimiter.recordSuccess('login', ip);
authenticated: true, setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare);
csrfToken: result.csrfToken, auditService.log({
safeMode: result.session.safeMode, action: 'auth.passkey_login',
elevatedUntil: result.session.elevatedUntil, actorIp: ip,
vaultState: vaultService.state, sessionIdHash: result.session.idHash,
vaultRuntimeReady: vaultService.isRuntimeReady, 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( router.post(
'/passkeys/step-up/options', '/passkeys/step-up/options',
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
asyncHandler(async (req, res) => { async (req, res) => {
const ip = req.clientIp ?? 'unknown'; const ip = req.clientIp ?? 'unknown';
const rate = rateLimiter.check('step-up', ip); const rate = rateLimiter.check('step-up', ip);
if (!rate.allowed) { if (!rate.allowed) {
@ -921,7 +825,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
return; return;
} }
try { try {
const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); const rp = resolveWebAuthnRp(req, trustCloudflare);
const data = await authService.beginPasskeyAuthentication({ const data = await authService.beginPasskeyAuthentication({
purpose: 'stepup', purpose: 'stepup',
sessionIdHash: req.authSession!.idHash, 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', message: err instanceof Error ? err.message : 'Unable to start passkey verification',
}); });
} }
}), },
); );
router.post( router.post(
@ -942,7 +846,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
asyncHandler(async (req, res) => { async (req, res) => {
const ip = req.clientIp ?? 'unknown'; const ip = req.clientIp ?? 'unknown';
const rate = rateLimiter.check('step-up', ip); const rate = rateLimiter.check('step-up', ip);
if (!rate.allowed) { if (!rate.allowed) {
@ -952,7 +856,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
} }
const parsed = z const parsed = z
.object({ .object({
challengeId: z.string().min(1).max(128), challengeId: z.string().min(1),
response: z.record(z.unknown()), response: z.record(z.unknown()),
}) })
.safeParse(req.body ?? {}); .safeParse(req.body ?? {});
@ -990,46 +894,6 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
status: 'ok', status: 'ok',
}); });
res.json({ elevatedUntil: outcome.elevatedUntil }); 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<string, unknown>)
: 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', '/recovery-backup/export',
requireAuth(authService), requireAuth(authService),
requireCsrf,
enforceSafeMode,
stepUpGuard, stepUpGuard,
(req, res) => { (req, res) => {
const settings = configManager.getSettings(); 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; return router;
} }

View file

@ -1,21 +1,17 @@
import type Database from 'better-sqlite3'; 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 { z } from 'zod';
import type { ConfigManager } from '../../config/config-manager.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 { AuditService } from '../../security/audit.js';
import type { AuthService } from '../../security/auth.js'; import type { AuthService } from '../../security/auth.js';
import { import {
BackupBusyError, createBackupBundle,
createBackupBundleAsync, restoreBackupBundle,
restoreBackupBundleAsync, verifyBackupSummaryOnly,
verifyBackupSummaryOnlyAsync,
type BackupInnerPayload, type BackupInnerPayload,
type BackupVerificationSummary, type BackupVerificationSummary,
} from '../../security/backup.js'; } from '../../security/backup.js';
import type { BackupScheduler } from '../../security/backup-scheduler.js';
import { import {
asyncHandler,
enforceSafeMode, enforceSafeMode,
requireAuth, requireAuth,
requireCsrf, requireCsrf,
@ -30,8 +26,6 @@ export interface BackupRouterDeps {
configManager: ConfigManager; configManager: ConfigManager;
auditService: AuditService; auditService: AuditService;
stepUpGuard: RequestHandler; stepUpGuard: RequestHandler;
getRuntimeLimits?: () => RuntimeLimits;
backupScheduler?: BackupScheduler;
onRestored: (info: { onRestored: (info: {
summary: BackupVerificationSummary; summary: BackupVerificationSummary;
inner: BackupInnerPayload; inner: BackupInnerPayload;
@ -60,8 +54,6 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
configManager, configManager,
auditService, auditService,
stepUpGuard, stepUpGuard,
getRuntimeLimits,
backupScheduler,
onRestored, onRestored,
} = deps; } = deps;
@ -71,7 +63,7 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
stepUpGuard, stepUpGuard,
asyncHandler(async (req, res) => { (req, res) => {
const parsed = ExportBackupBodySchema.safeParse(req.body ?? {}); const parsed = ExportBackupBodySchema.safeParse(req.body ?? {});
if (!parsed.success) { if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
@ -89,13 +81,11 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
} }
try { try {
const limits = getRuntimeLimits?.(); const result = createBackupBundle({
const result = await createBackupBundleAsync({
dataDir, dataDir,
db, db,
masterKey, masterKey,
passphrase, passphrase,
scryptConcurrency: limits?.scryptConcurrency,
}); });
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const filename = `gcoordinator-backup-${stamp}.gcoord.enc`; const filename = `gcoordinator-backup-${stamp}.gcoord.enc`;
@ -119,73 +109,38 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
summary: result.summary, summary: result.summary,
}); });
} catch (err) { } catch (err) {
if (err instanceof BackupBusyError) throw err;
res.status(400).json({ res.status(400).json({
error: 'BACKUP_EXPORT_ERROR', error: 'BACKUP_EXPORT_ERROR',
message: err instanceof Error ? err.message : 'Unable to create backup bundle', 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 // Read-only verification: exempt from enforceSafeMode
router.post( router.post('/verify', requireAuth(authService), requireCsrf, (req, res) => {
'/verify', const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {});
requireAuth(authService), if (!parsed.success) {
requireCsrf, res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
stepUpGuard, return;
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;
}
const limits = getRuntimeLimits?.(); try {
const maxBodyBytes = limits?.backupMaxBodyBytes ?? 16 * 1024 * 1024;
const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64'); const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64');
if (rawBuf.length > maxBodyBytes) { const summary = verifyBackupSummaryOnly(rawBuf, {
res.status(413).json({ masterKey:
error: 'PAYLOAD_TOO_LARGE', parsed.data.masterKey?.trim() || vaultService.exportMasterKeyHex() || undefined,
message: `Backup bundle exceeds limit (${maxBodyBytes} bytes)`, passphrase: parsed.data.passphrase?.trim() || undefined,
}); vaultMasterKey: parsed.data.vaultMasterKey?.trim() || undefined,
return; });
} res.json({ summary });
} catch (err) {
try { res.status(400).json({
const summary = await verifyBackupSummaryOnlyAsync(rawBuf, { error: 'BACKUP_INVALID',
masterKey: message: err instanceof Error ? err.message : 'Backup verification failed',
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',
});
}
}),
);
router.post( router.post(
'/restore', '/restore',
@ -193,24 +148,14 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
stepUpGuard, stepUpGuard,
asyncHandler(async (req, res) => { async (req, res) => {
const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {}); const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {});
if (!parsed.success) { if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return; return;
} }
const limits = getRuntimeLimits?.();
const maxBodyBytes = limits?.backupMaxBodyBytes ?? 16 * 1024 * 1024;
const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64'); 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 passphrase = parsed.data.passphrase?.trim() || undefined;
const runtimeKey = vaultService.exportMasterKeyHex() ?? undefined; const runtimeKey = vaultService.exportMasterKeyHex() ?? undefined;
const masterKey = parsed.data.masterKey?.trim() || runtimeKey; const masterKey = parsed.data.masterKey?.trim() || runtimeKey;
@ -218,14 +163,12 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
const wasWatching = await configManager.pauseWatcher(); const wasWatching = await configManager.pauseWatcher();
try { try {
const restored = await restoreBackupBundleAsync(rawBuf, { const restored = restoreBackupBundle(rawBuf, {
dataDir, dataDir,
db, db,
masterKey, masterKey,
passphrase, passphrase,
vaultMasterKey, vaultMasterKey,
scryptConcurrency: limits?.scryptConcurrency,
maxGunzipBytes: limits?.backupMaxGunzipBytes,
}); });
await onRestored({ await onRestored({
@ -249,7 +192,6 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
res.json({ restored: true, summary: restored.summary }); res.json({ restored: true, summary: restored.summary });
} catch (err) { } catch (err) {
if (err instanceof BackupBusyError) throw err;
auditService.log({ auditService.log({
action: 'backup.restore', action: 'backup.restore',
actorIp: req.clientIp ?? 'unknown', actorIp: req.clientIp ?? 'unknown',
@ -267,44 +209,8 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
await configManager.resumeWatcher(); 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; return router;
} }

View file

@ -1,36 +1,23 @@
import crypto from 'node:crypto'; import { Router } from 'express';
import { Router, type RequestHandler } from 'express';
import { ZodError, z } from 'zod'; import { ZodError, z } from 'zod';
import type { ConfigManager } from '../../config/config-manager.js'; import type { ConfigManager } from '../../config/config-manager.js';
import type { AuditService } from '../../security/audit.js'; import type { AuditService } from '../../security/audit.js';
import { sha256Hex, type AuthService } from '../../security/auth.js'; import type { AuthService } from '../../security/auth.js';
import { import {
enforceSafeMode, enforceSafeMode,
requireAuth, requireAuth,
requireCsrf, requireCsrf,
requireStepUp,
} from '../../security/guards.js'; } from '../../security/guards.js';
export interface ConfigRouterDeps { export interface ConfigRouterDeps {
authService: AuthService; authService: AuthService;
configManager: ConfigManager; configManager: ConfigManager;
auditService: AuditService; 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 { export function createConfigRouter(deps: ConfigRouterDeps): Router {
const router = Router(); const router = Router();
const { const { authService, configManager, auditService } = deps;
authService,
configManager,
auditService,
stepUpGuard = requireStepUp,
} = deps;
router.get('/overview', requireAuth(authService), (_req, res) => { router.get('/overview', requireAuth(authService), (_req, res) => {
res.json({ res.json({
@ -76,46 +63,38 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router {
return; return;
} }
const executeSave = () => { try {
try { const saved = configManager.saveConfigText(
const saved = configManager.saveConfigText( parsed.data.path,
parsed.data.path, parsed.data.content,
parsed.data.content, 'ui',
'ui', parsed.data.summary,
parsed.data.summary, );
); auditService.log({
auditService.log({ action: 'config.save',
action: 'config.save', actorIp: req.clientIp ?? 'unknown',
actorIp: req.clientIp ?? 'unknown', sessionIdHash: req.authSession!.idHash,
sessionIdHash: req.authSession!.idHash, target: saved.filePath,
target: saved.filePath, status: 'ok',
status: 'ok', });
}); res.json(saved);
res.json(saved); } catch (err) {
} catch (err) { if (err instanceof ZodError) {
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;
}
res.status(400).json({ res.status(400).json({
error: 'CONFIG_SAVE_ERROR', error: 'CONFIG_SCHEMA_ERROR',
message: err instanceof Error ? err.message : 'Unable to save config file', message: 'Schema validation failed',
issues: err.issues.map((i) => ({
path: i.path.join('.') || '(root)',
message: i.message,
})),
}); });
return;
} }
}; res.status(400).json({
error: 'CONFIG_SAVE_ERROR',
if (isStepUpSensitiveConfigPath(parsed.data.path)) { message: err instanceof Error ? err.message : 'Unable to save config file',
stepUpGuard(req, res, executeSave); });
return;
} }
executeSave();
}); });
router.delete( router.delete(
@ -129,34 +108,26 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router {
res.status(400).json({ error: 'MISSING_PATH' }); res.status(400).json({ error: 'MISSING_PATH' });
return; return;
} }
const executeDelete = () => { try {
try { const deleted = configManager.deleteEntityFile(filePath);
const deleted = configManager.deleteEntityFile(filePath); if (!deleted) {
if (!deleted) { res.status(404).json({ error: 'CONFIG_NOT_FOUND' });
res.status(404).json({ error: 'CONFIG_NOT_FOUND' }); return;
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',
});
} }
}; auditService.log({
action: 'config.delete',
if (isStepUpSensitiveConfigPath(filePath)) { actorIp: req.clientIp ?? 'unknown',
stepUpGuard(req, res, executeDelete); sessionIdHash: req.authSession!.idHash,
return; 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' }); res.status(400).json({ error: 'INVALID_REVISION_ID' });
return; return;
} }
const rev = configManager.getRevision(id); try {
if (!rev) { 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({ res.status(400).json({
error: 'ROLLBACK_FAILED', 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,
});
}, },
); );

View file

@ -19,7 +19,6 @@ import {
import type { VaultService } from '../../security/vault.js'; import type { VaultService } from '../../security/vault.js';
import type { KeyManager } from '../../ssh/key-manager.js'; import type { KeyManager } from '../../ssh/key-manager.js';
import type { KnownHostsService } from '../../ssh/known-hosts.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'; import type { SSHPool } from '../../ssh/ssh-pool.js';
export interface ServersRouterDeps { export interface ServersRouterDeps {
@ -79,173 +78,22 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
stepUpGuard, stepUpGuard,
(req, res) => { (req, res) => {
const hostPort = typeof req.query.hostPort === 'string' ? req.query.hostPort : ''; 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) { if (!hostPort) {
res.status(400).json({ error: 'MISSING_HOST_PORT' }); res.status(400).json({ error: 'MISSING_HOST_PORT' });
return; return;
} }
const deleted = knownHosts.deleteKnownHost(hostPort, algorithm); const deleted = knownHosts.deleteKnownHost(hostPort);
auditService.log({ auditService.log({
action: 'ssh.known_host_delete', action: 'ssh.known_host_delete',
actorIp: req.clientIp ?? 'unknown', actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash, sessionIdHash: req.authSession!.idHash,
target: algorithm ? `${hostPort} (${algorithm})` : hostPort, target: hostPort,
status: deleted ? 'ok' : 'error', status: deleted ? 'ok' : 'error',
}); });
res.json({ deleted }); res.json({ deleted });
}, },
); );
const hasJumpCycle = (
serverId: string,
jumpHostId: string | undefined,
extraMap?: Map<string, string | undefined>,
): boolean => {
const visited = new Set<string>([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<string, string>();
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<string, string>();
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( router.post(
'/rotate-keys', '/rotate-keys',
requireAuth(authService), requireAuth(authService),
@ -300,142 +148,113 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
}, },
); );
router.post( router.post('/', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
'/', try {
requireAuth(authService), const parsed = ServerConfigSchema.parse(req.body);
requireCsrf, const saved = configManager.saveConfigText(
enforceSafeMode, `servers/${parsed.id}.json`,
stepUpGuard, JSON.stringify(parsed, null, 2),
(req, res) => { 'ui',
try { 'Registered server via UI',
const parsed = ServerConfigSchema.parse(req.body); );
if (hasJumpCycle(parsed.id, parsed.jumpHostId)) { monitoringService.syncServers();
res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' }); auditService.log({
return; action: 'server.create',
} actorIp: req.clientIp ?? 'unknown',
const saved = configManager.saveConfigText( sessionIdHash: req.authSession!.idHash,
`servers/${parsed.id}.json`, target: parsed.id,
JSON.stringify(parsed, null, 2), status: 'ok',
'ui', });
'Registered server via UI', res.status(201).json({
); server: saved.config,
monitoringService.syncServers(); warnings: saved.warnings,
auditService.log({ });
action: 'server.create', } catch (err) {
actorIp: req.clientIp ?? 'unknown', if (err instanceof ZodError) {
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;
}
res.status(400).json({ res.status(400).json({
error: 'SERVER_SAVE_ERROR', error: 'VALIDATION_ERROR',
message: err instanceof Error ? err.message : 'Unable to save server', 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( router.put('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
'/:id', try {
requireAuth(authService), const parsed = ServerConfigSchema.parse({
requireCsrf, ...(req.body ?? {}),
enforceSafeMode, id: req.params.id,
stepUpGuard, });
(req, res) => { const saved = configManager.saveConfigText(
try { `servers/${parsed.id}.json`,
const parsed = ServerConfigSchema.parse({ JSON.stringify(parsed, null, 2),
...(req.body ?? {}), 'ui',
id: req.params.id, 'Updated server via UI',
}); );
if (hasJumpCycle(parsed.id, parsed.jumpHostId)) { sshPool.closeServer(parsed.id);
res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' }); monitoringService.syncServers();
return; auditService.log({
} action: 'server.update',
const saved = configManager.saveConfigText( actorIp: req.clientIp ?? 'unknown',
`servers/${parsed.id}.json`, sessionIdHash: req.authSession!.idHash,
JSON.stringify(parsed, null, 2), target: parsed.id,
'ui', status: 'ok',
'Updated server via UI', });
); res.json({ server: saved.config, warnings: saved.warnings });
sshPool.closeServer(parsed.id); } catch (err) {
monitoringService.syncServers(); if (err instanceof ZodError) {
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;
}
res.status(400).json({ res.status(400).json({
error: 'SERVER_SAVE_ERROR', error: 'VALIDATION_ERROR',
message: err instanceof Error ? err.message : 'Unable to update server', 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( router.delete('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
'/:id', const id = String(req.params.id ?? '');
requireAuth(authService), try {
requireCsrf, const deleted = configManager.deleteEntityFile(`servers/${id}.json`);
enforceSafeMode, if (!deleted) {
stepUpGuard, res.status(404).json({ error: 'SERVER_NOT_FOUND' });
(req, res) => { return;
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',
});
} }
}, 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( router.post(
'/:id/reconnect', '/:id/reconnect',
@ -467,7 +286,6 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
stepUpGuard,
async (req, res) => { async (req, res) => {
const id = String(req.params.id ?? ''); const id = String(req.params.id ?? '');
const parsed = z.object({ fingerprint: z.string().min(1) }).safeParse(req.body); 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 ?? ''); const id = String(req.params.id ?? '');
if (!configManager.getServer(id)) { if (!configManager.getServer(id)) {
res.status(404).json({ error: 'SERVER_NOT_FOUND' }); res.status(404).json({ error: 'SERVER_NOT_FOUND' });
return; return;
} }
const sort = String(req.query.sort ?? 'cpu') === 'mem' ? 'mem' : 'cpu'; try {
const useSudo = req.query.sudo === 'true' || req.query.sudo === '1'; const result = await serverInspector.inspect(id);
res.json(result);
const executeInspect = async () => { } catch (err) {
try { res.status(502).json({
const result = await serverInspector.inspect(id, { sort, useSudo }); error: 'INSPECT_FAILED',
res.json(result); message: err instanceof Error ? err.message : 'Server inspection failed',
} 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();
}); });
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<MetricRange, number> = {
'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) => { router.get('/:id/keys', requireAuth(authService), async (req, res) => {
const id = String(req.params.id ?? ''); const id = String(req.params.id ?? '');
if (!configManager.getServer(id)) { if (!configManager.getServer(id)) {
@ -704,7 +405,6 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
stepUpGuard,
async (req, res) => { async (req, res) => {
const id = String(req.params.id ?? ''); const id = String(req.params.id ?? '');
const parsed = z.object({ credentialId: EntityIdSchema }).safeParse(req.body); const parsed = z.object({ credentialId: EntityIdSchema }).safeParse(req.body);

View file

@ -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 { z } from 'zod';
import type { ConfigManager } from '../../config/config-manager.js'; import type { ConfigManager } from '../../config/config-manager.js';
import type { AuditService } from '../../security/audit.js'; import type { AuditService } from '../../security/audit.js';
@ -7,7 +7,6 @@ import {
enforceSafeMode, enforceSafeMode,
requireAuth, requireAuth,
requireCsrf, requireCsrf,
requireStepUp,
} from '../../security/guards.js'; } from '../../security/guards.js';
import { SftpServiceError, type SftpService } from '../../ssh/sftp-service.js'; import { SftpServiceError, type SftpService } from '../../ssh/sftp-service.js';
@ -16,16 +15,6 @@ export interface SftpRouterDeps {
configManager: ConfigManager; configManager: ConfigManager;
auditService: AuditService; auditService: AuditService;
sftpService: SftpService; 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 { function sendSftpError(res: Response, err: unknown): void {
@ -33,7 +22,7 @@ function sendSftpError(res: Response, err: unknown): void {
const status = const status =
err.code === 'NOT_FOUND' err.code === 'NOT_FOUND'
? 404 ? 404
: err.code === 'CONFLICT' || err.code === 'ALREADY_EXISTS' : err.code === 'CONFLICT'
? 409 ? 409
: err.code === 'FILE_TOO_LARGE' : err.code === 'FILE_TOO_LARGE'
? 413 ? 413
@ -48,13 +37,7 @@ function sendSftpError(res: Response, err: unknown): void {
export function createSftpRouter(deps: SftpRouterDeps): Router { export function createSftpRouter(deps: SftpRouterDeps): Router {
const router = Router({ mergeParams: true }); const router = Router({ mergeParams: true });
const { const { authService, configManager, auditService, sftpService } = deps;
authService,
configManager,
auditService,
sftpService,
stepUpGuard = requireStepUp,
} = deps;
const ensureServer = (serverId: string, res: Response): boolean => { const ensureServer = (serverId: string, res: Response): boolean => {
if (!configManager.getServer(serverId)) { if (!configManager.getServer(serverId)) {
@ -64,18 +47,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
return true; 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) => { router.get('/list', requireAuth(authService), async (req, res) => {
const serverId = String(req.params.id ?? ''); const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return; 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) => { router.get('/download', requireAuth(authService), async (req, res) => {
const serverId = String(req.params.id ?? ''); const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return; if (!ensureServer(serverId, res)) return;
@ -133,9 +86,9 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
try { try {
const dl = await sftpService.openDownloadStream(serverId, targetPath); 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-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', buildContentDisposition(dl.fileName)); res.setHeader('Content-Disposition', `attachment; filename="${safeName}"`);
res.setHeader('Cache-Control', 'no-store');
if (Number.isFinite(dl.size)) { if (Number.isFinite(dl.size)) {
res.setHeader('Content-Length', String(dl.size)); res.setHeader('Content-Length', String(dl.size));
} }
@ -174,9 +127,11 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
try { try {
const arch = await sftpService.streamDirectoryArchive(serverId, targetPath, format); const arch = await sftpService.streamDirectoryArchive(serverId, targetPath, format);
res.setHeader('Content-Type', 'application/octet-stream'); 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('X-Archive-Format', arch.resolvedFormat);
res.setHeader('Cache-Control', 'no-store');
res.once('close', () => { res.once('close', () => {
if (!res.writableEnded) { 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( router.post(
'/mkdir', '/mkdir',
requireAuth(authService), requireAuth(authService),
@ -295,11 +221,7 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
const serverId = String(req.params.id ?? ''); const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return; if (!ensureServer(serverId, res)) return;
const parsed = z const parsed = z
.object({ .object({ fromPath: z.string().min(1), toPath: z.string().min(1) })
fromPath: z.string().min(1),
toPath: z.string().min(1),
overwrite: z.boolean().optional(),
})
.safeParse(req.body ?? {}); .safeParse(req.body ?? {});
if (!parsed.success) { if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
@ -310,7 +232,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
serverId, serverId,
parsed.data.fromPath, parsed.data.fromPath,
parsed.data.toPath, parsed.data.toPath,
Boolean(parsed.data.overwrite),
); );
auditService.log({ auditService.log({
action: 'sftp.rename', 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( router.delete(
'/entry', '/entry',
requireAuth(authService), requireAuth(authService),
@ -437,42 +314,7 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
}, },
); );
router.post( router.get('/text', requireAuth(authService), async (req, res) => {
'/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) => {
const serverId = String(req.params.id ?? ''); const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return; if (!ensureServer(serverId, res)) return;
const targetPath = typeof req.query.path === 'string' ? req.query.path : ''; const targetPath = typeof req.query.path === 'string' ? req.query.path : '';
@ -483,15 +325,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
} }
try { try {
const file = await sftpService.readTextFile(serverId, targetPath, { sudo }); 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 }); res.json({ file });
} catch (err) { } catch (err) {
sendSftpError(res, err); sendSftpError(res, err);
@ -503,7 +336,6 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
conditionalSudoStepUp,
async (req, res) => { async (req, res) => {
const serverId = String(req.params.id ?? ''); const serverId = String(req.params.id ?? '');
if (!ensureServer(serverId, res)) return; if (!ensureServer(serverId, res)) return;

View file

@ -1,4 +1,4 @@
import { Router, type RequestHandler } from 'express'; import { Router } from 'express';
import { z } from 'zod'; import { z } from 'zod';
import type { AuditService } from '../../security/audit.js'; import type { AuditService } from '../../security/audit.js';
import type { AuthService } from '../../security/auth.js'; import type { AuthService } from '../../security/auth.js';
@ -6,7 +6,6 @@ import {
enforceSafeMode, enforceSafeMode,
requireAuth, requireAuth,
requireCsrf, requireCsrf,
requireStepUp,
} from '../../security/guards.js'; } from '../../security/guards.js';
import type { CustomSystemsEngine } from '../../systems/systems-engine.js'; import type { CustomSystemsEngine } from '../../systems/systems-engine.js';
@ -14,12 +13,11 @@ export interface SystemsRouterDeps {
authService: AuthService; authService: AuthService;
auditService: AuditService; auditService: AuditService;
systemsEngine: CustomSystemsEngine; systemsEngine: CustomSystemsEngine;
stepUpGuard?: RequestHandler;
} }
export function createSystemsRouter(deps: SystemsRouterDeps): Router { export function createSystemsRouter(deps: SystemsRouterDeps): Router {
const router = Router(); const router = Router();
const { authService, auditService, systemsEngine, stepUpGuard = requireStepUp } = deps; const { authService, auditService, systemsEngine } = deps;
router.get('/', requireAuth(authService), (_req, res) => { router.get('/', requireAuth(authService), (_req, res) => {
res.json({ systems: systemsEngine.listSystemsOverview() }); res.json({ systems: systemsEngine.listSystemsOverview() });
@ -155,7 +153,7 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router {
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
(req, res) => { async (req, res) => {
const systemId = String(req.params.systemId ?? ''); const systemId = String(req.params.systemId ?? '');
const serverId = String(req.params.serverId ?? ''); const serverId = String(req.params.serverId ?? '');
const actionId = String(req.params.actionId ?? ''); const actionId = String(req.params.actionId ?? '');
@ -163,7 +161,6 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router {
.object({ .object({
itemName: z.string().min(1).optional(), itemName: z.string().min(1).optional(),
subItemName: 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(), cols: z.number().int().min(10).max(500).optional(),
rows: z.number().int().min(4).max(200).optional(), rows: z.number().int().min(4).max(200).optional(),
}) })
@ -173,75 +170,43 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router {
return; return;
} }
const actionMeta = systemsEngine.getActionMeta(systemId, actionId); try {
const execute = async () => { const result = await systemsEngine.executeAction({
try { serverId,
const result = await systemsEngine.executeAction({ systemId,
serverId, actionId,
systemId, ...parsed.data,
actionId, });
...parsed.data, auditService.log({
}); action: 'system.action',
const secretInputKeys = new Set( actorIp: req.clientIp ?? 'unknown',
(actionMeta?.inputs ?? []).filter((i) => i.type === 'secret').map((i) => i.name), sessionIdHash: req.authSession!.idHash,
); target: `${serverId}:${systemId}:${actionId}`,
const sanitizedInputs = parsed.data.inputs status: 'ok',
? Object.fromEntries( details: {
Object.entries(parsed.data.inputs).map(([k, v]) => [ itemName: parsed.data.itemName,
k, subItemName: parsed.data.subItemName,
secretInputKeys.has(k) ? '[REDACTED]' : v, mode: result.mode,
]), },
) });
: undefined; res.json(result);
auditService.log({ } catch (err) {
action: 'system.action', res.status(400).json({
actorIp: req.clientIp ?? 'unknown', error: 'SYSTEM_ACTION_FAILED',
sessionIdHash: req.authSession!.idHash, message: err instanceof Error ? err.message : 'Unable to execute system action',
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();
}); });
return;
} }
void execute();
}, },
); );
// Cancelling a running stream must work even if Safe Mode was just toggled on
router.post( router.post(
'/streams/:jobId/cancel', '/streams/:jobId/cancel',
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode,
(req, res) => { (req, res) => {
const jobId = String(req.params.jobId ?? ''); const jobId = String(req.params.jobId ?? '');
const cancelled = systemsEngine.cancelStream(jobId); res.json({ 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 });
}, },
); );

View file

@ -37,11 +37,7 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router {
serverId: EntityIdSchema, serverId: EntityIdSchema,
cols: z.number().int().min(10).max(500).optional(), cols: z.number().int().min(10).max(500).optional(),
rows: z.number().int().min(4).max(200).optional(), rows: z.number().int().min(4).max(200).optional(),
cwd: z cwd: z.string().max(1024).optional(),
.string()
.max(1024)
.refine((v) => !/[\x00-\x1f\x7f]/.test(v), 'Control characters not permitted in cwd')
.optional(),
title: z.string().max(120).optional(), title: z.string().max(120).optional(),
}) })
.safeParse(req.body ?? {}); .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( router.post(
'/sessions/:sessionId/resize', '/sessions/:sessionId/resize',
requireAuth(authService), requireAuth(authService),
@ -132,12 +98,7 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router {
router.get('/sessions/:sessionId/export', requireAuth(authService), (req, res) => { router.get('/sessions/:sessionId/export', requireAuth(authService), (req, res) => {
const sessionId = String(req.params.sessionId ?? ''); const sessionId = String(req.params.sessionId ?? '');
const format = const format = req.query.format === 'ansi' ? 'ansi' : 'plain';
req.query.format === 'ansi'
? 'ansi'
: req.query.format === 'cast'
? 'cast'
: 'plain';
const exported = ptyManager.exportScrollback(sessionId, format); const exported = ptyManager.exportScrollback(sessionId, format);
if (!exported) { if (!exported) {
res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' }); 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, '_'); 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('Content-Disposition', `attachment; filename="${safeFile}"`);
res.setHeader('Cache-Control', 'no-store');
res.send(exported.content); res.send(exported.content);
}); });

View file

@ -10,7 +10,7 @@ import {
requireAuth, requireAuth,
requireCsrf, requireCsrf,
} from '../../security/guards.js'; } from '../../security/guards.js';
import { ProxyIsolationError, type TunnelManager } from '../../ssh/tunnel-manager.js'; import type { TunnelManager } from '../../ssh/tunnel-manager.js';
export interface TunnelsRouterDeps { export interface TunnelsRouterDeps {
authService: AuthService; 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; return router;
} }

View file

@ -15,7 +15,6 @@ import {
import { import {
computeOpenSshFingerprint, computeOpenSshFingerprint,
generateMasterKeyBuffer, generateMasterKeyBuffer,
validatePrivateKey,
type VaultCredentialInput, type VaultCredentialInput,
type VaultService, type VaultService,
} from '../../security/vault.js'; } from '../../security/vault.js';
@ -115,7 +114,6 @@ export function createVaultRouter(deps: VaultRouterDeps): {
type: 'vault:state', type: 'vault:state',
vaultState: vaultService.state, vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady, vaultRuntimeReady: vaultService.isRuntimeReady,
vaultSealState: vaultService.sealState,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
}); });
}; };
@ -124,52 +122,43 @@ export function createVaultRouter(deps: VaultRouterDeps): {
res.json({ res.json({
state: vaultService.state, state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady, runtimeReady: vaultService.isRuntimeReady,
sealState: vaultService.sealState,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
}); });
}); });
vaultRouter.post( vaultRouter.post('/init', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
'/init', const ip = req.clientIp ?? 'unknown';
requireAuth(authService), const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {});
requireCsrf, if (!parsed.success) {
enforceSafeMode, res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
stepUpGuard, return;
(req, res) => { }
const ip = req.clientIp ?? 'unknown'; try {
const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); const result = vaultService.initializeNewVault(parsed.data.masterKey);
if (!parsed.success) { notifyConfigReeval();
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); onVaultUnlocked?.();
return; onVaultChanged?.('vault-init');
} broadcastVaultState();
try { auditService.log({
const result = vaultService.initializeNewVault(parsed.data.masterKey); action: 'vault.init',
notifyConfigReeval(); actorIp: ip,
onVaultUnlocked?.(); sessionIdHash: req.authSession!.idHash,
onVaultChanged?.('vault-init'); status: 'ok',
broadcastVaultState(); });
auditService.log({ res.status(201).json({
action: 'vault.init', state: vaultService.state,
actorIp: ip, runtimeReady: vaultService.isRuntimeReady,
sessionIdHash: req.authSession!.idHash, generatedKeyHex: result.generatedKeyHex,
status: 'ok', });
}); } catch (err) {
res.status(201).json({ res.status(400).json({
state: vaultService.state, error: 'VAULT_INIT_FAILED',
runtimeReady: vaultService.isRuntimeReady, message: err instanceof Error ? err.message : 'Vault initialization failed',
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('/unlock', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, (req, res) => {
const ip = req.clientIp ?? 'unknown'; const ip = req.clientIp ?? 'unknown';
const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {});
if (!parsed.success) { if (!parsed.success) {
@ -202,7 +191,6 @@ export function createVaultRouter(deps: VaultRouterDeps): {
res.json({ res.json({
state: vaultService.state, state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady, runtimeReady: vaultService.isRuntimeReady,
sealState: vaultService.sealState,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
}); });
} catch (err) { } catch (err) {
@ -243,7 +231,6 @@ export function createVaultRouter(deps: VaultRouterDeps): {
res.json({ res.json({
state: vaultService.state, state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady, runtimeReady: vaultService.isRuntimeReady,
sealState: vaultService.sealState,
isPanicLocked: vaultService.isPanicLocked, isPanicLocked: vaultService.isPanicLocked,
}); });
} catch (err) { } catch (err) {
@ -267,35 +254,10 @@ export function createVaultRouter(deps: VaultRouterDeps): {
res.json({ res.json({
state: vaultService.state, state: vaultService.state,
runtimeReady: vaultService.isRuntimeReady, runtimeReady: vaultService.isRuntimeReady,
sealState: vaultService.sealState,
isPanicLocked: vaultService.isPanicLocked, 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!) // Panic Lock is ALWAYS reachable when authenticated + CSRF verified (even under Safe Mode!)
panicLockHandler.post('/panic-lock', requireAuth(authService), requireCsrf, (req, res) => { panicLockHandler.post('/panic-lock', requireAuth(authService), requireCsrf, (req, res) => {
const session = req.authSession!; const session = req.authSession!;
@ -337,13 +299,6 @@ export function createVaultRouter(deps: VaultRouterDeps): {
requireAuth(authService), requireAuth(authService),
stepUpGuard, stepUpGuard,
(req, res) => { (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') { if (vaultService.state !== 'unlocked') {
res.status(423).json({ error: 'VAULT_LOCKED' }); res.status(423).json({ error: 'VAULT_LOCKED' });
return; return;
@ -382,27 +337,15 @@ export function createVaultRouter(deps: VaultRouterDeps): {
return; return;
} }
const credInput: VaultCredentialInput = { ...parsed.data }; const credInput: VaultCredentialInput = { ...parsed.data };
if (credInput.type === 'ssh-key') { if (
credInput.type === 'ssh-key' &&
credInput.publicKey &&
!credInput.fingerprint
) {
try { try {
validatePrivateKey(credInput.privateKey, credInput.passphrase); credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey);
} catch (err) { } catch {
res.status(400).json({ // Leave fingerprint omitted if user imported an unusual public key format
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;
}
} }
} }
const meta = vaultService.upsertCredential(credInput); const meta = vaultService.upsertCredential(credInput);
@ -438,27 +381,15 @@ export function createVaultRouter(deps: VaultRouterDeps): {
return; return;
} }
const credInput: VaultCredentialInput = { ...parsed.data }; const credInput: VaultCredentialInput = { ...parsed.data };
if (credInput.type === 'ssh-key') { if (
credInput.type === 'ssh-key' &&
credInput.publicKey &&
!credInput.fingerprint
) {
try { try {
validatePrivateKey(credInput.privateKey, credInput.passphrase); credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey);
} catch (err) { } catch {
res.status(400).json({ // Ignore non-standard public key strings
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;
}
} }
} }
const meta = vaultService.upsertCredential(credInput); const meta = vaultService.upsertCredential(credInput);
@ -564,12 +495,6 @@ export function createVaultRouter(deps: VaultRouterDeps): {
sessionIdHash: req.authSession!.idHash, sessionIdHash: req.authSession!.idHash,
expiresAt, expiresAt,
}; };
auditService.log({
action: 'vault.rotate_key.prepare',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
status: 'ok',
});
res.json({ candidateKeyHex, confirmToken, expiresAt }); res.json({ candidateKeyHex, confirmToken, expiresAt });
}, },
); );
@ -585,17 +510,10 @@ export function createVaultRouter(deps: VaultRouterDeps): {
res.status(423).json({ error: 'VAULT_LOCKED' }); res.status(423).json({ error: 'VAULT_LOCKED' });
return; 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 const parsed = z
.object({ .object({
confirmToken: z.string().min(1), confirmToken: z.string().min(1),
confirmedKeyHex: z.string().min(64).max(64), confirmedKeyHex: z.string().min(1).optional(),
}) })
.safeParse(req.body); .safeParse(req.body);
if (!parsed.success) { if (!parsed.success) {
@ -603,57 +521,32 @@ export function createVaultRouter(deps: VaultRouterDeps): {
return; 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 ( if (
!pendingRotation || !pendingRotation ||
pendingRotation.expiresAt <= Date.now() || pendingRotation.expiresAt <= Date.now() ||
pendingRotation.sessionIdHash !== req.authSession!.idHash || 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' }); res.status(400).json({ error: 'ROTATION_TOKEN_INVALID_OR_EXPIRED' });
return; return;
} }
if ( if (
!timingEq( parsed.data.confirmedKeyHex &&
parsed.data.confirmedKeyHex.trim().toLowerCase(), parsed.data.confirmedKeyHex.trim().toLowerCase() !==
pendingRotation.candidateKeyHex.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' }); res.status(400).json({ error: 'KEY_CONFIRMATION_MISMATCH' });
return; return;
} }
rateLimiter.recordSuccess('vault-rotate-commit', ip);
const nextHex = pendingRotation.candidateKeyHex; const nextHex = pendingRotation.candidateKeyHex;
pendingRotation = null; pendingRotation = null;
vaultService.rotateMasterKey(nextHex); vaultService.rotateMasterKey(nextHex);
onVaultChanged?.('master-key-rotation'); onVaultChanged?.('master-key-rotation');
auditService.log({ auditService.log({
action: 'vault.rotate_key', action: 'vault.rotate_key',
actorIp: ip, actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash, sessionIdHash: req.authSession!.idHash,
status: 'ok', status: 'ok',
}); });

View file

@ -147,8 +147,7 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
}); });
router.get('/runs/:runId', requireAuth(authService), (req, res) => { 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 ?? ''));
const detail = workflowEngine.getRunDetail(String(req.params.runId ?? ''), { includeLogs });
if (!detail) { if (!detail) {
res.status(404).json({ error: 'RUN_NOT_FOUND' }); res.status(404).json({ error: 'RUN_NOT_FOUND' });
return; return;
@ -156,20 +155,11 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
res.json(detail); 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( router.post(
'/runs/:runId/cancel', '/runs/:runId/cancel',
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode,
(req, res) => { (req, res) => {
const runId = String(req.params.runId ?? ''); const runId = String(req.params.runId ?? '');
const cancelled = workflowEngine.cancelRun(runId, 'admin'); const cancelled = workflowEngine.cancelRun(runId, 'admin');
@ -258,7 +248,6 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
}), }),
}) })
.safeParse(req.body ?? {}); .safeParse(req.body ?? {});
if (!parsed.success) { if (!parsed.success) {
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
return; 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) => { router.get('/broadcast/:jobId', requireAuth(authService), (req, res) => {
const job = broadcastService.getBroadcastResult(String(req.params.jobId ?? '')); const job = broadcastService.getBroadcastResult(String(req.params.jobId ?? ''));
if (!job) { if (!job) {
@ -307,22 +278,14 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
res.json({ job }); res.json({ job });
}); });
// Cancelling a running broadcast must remain available under Safe Mode
router.post( router.post(
'/broadcast/:jobId/cancel', '/broadcast/:jobId/cancel',
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode,
(req, res) => { (req, res) => {
const jobId = String(req.params.jobId ?? ''); const jobId = String(req.params.jobId ?? '');
const cancelled = broadcastService.cancelBroadcast(jobId); res.json({ 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 });
}, },
); );

View file

@ -5,18 +5,10 @@ import {
ClientWsFrameSchema, ClientWsFrameSchema,
type ServerWsFrame, type ServerWsFrame,
} from '../../shared/ws-protocol.js'; } from '../../shared/ws-protocol.js';
import { import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js';
SESSION_COOKIE_NAME,
type AuthService,
type AuthSession,
} from '../security/auth.js';
import { extractCookies } from '../security/guards.js'; import { extractCookies } from '../security/guards.js';
import type { VaultService } from '../security/vault.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 { interface WsClientMeta {
ws: WebSocket; ws: WebSocket;
sessionToken: string; sessionToken: string;
@ -50,42 +42,25 @@ export interface WsAiHandlers {
} }
export class WsHub { export class WsHub {
private readonly wss = new WebSocketServer({ private readonly wss = new WebSocketServer({ noServer: true });
noServer: true,
maxPayload: WS_MAX_PAYLOAD_BYTES,
});
private readonly clients = new Set<WsClientMeta>(); private readonly clients = new Set<WsClientMeta>();
private readonly pingTimer: NodeJS.Timeout; private readonly pingTimer: NodeJS.Timeout;
private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = []; private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = [];
private readonly hostUpgradeHandlers: Array<(req: IncomingMessage, socket: Duplex, head: Buffer) => boolean> = [];
private readonly subscribeListeners = new Set<WsSubscribeListener>(); private readonly subscribeListeners = new Set<WsSubscribeListener>();
private ptyHandlers: WsPtyHandlers | null = null; private ptyHandlers: WsPtyHandlers | null = null;
private aiHandlers: WsAiHandlers | null = null; private aiHandlers: WsAiHandlers | null = null;
private readonly trustCloudflare: boolean;
constructor( constructor(
httpServer: HttpServer, httpServer: HttpServer,
private readonly authService: AuthService, private readonly authService: AuthService,
private readonly vaultService: VaultService, private readonly vaultService: VaultService,
options: { trustCloudflare?: boolean } = {},
) { ) {
this.trustCloudflare = Boolean(options.trustCloudflare);
httpServer.on('upgrade', (req, socket, head) => { httpServer.on('upgrade', (req, socket, head) => {
this.handleUpgrade(req, socket, head); this.handleUpgrade(req, socket, head);
}); });
this.pingTimer = setInterval(() => { this.pingTimer = setInterval(() => {
for (const client of this.clients) { 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) { if (!client.alive) {
client.ws.terminate(); client.ws.terminate();
this.clients.delete(client); this.clients.delete(client);
@ -98,34 +73,10 @@ export class WsHub {
this.pingTimer.unref(); 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 { registerUpgradeHandler(prefix: string, handler: WsUpgradeHandler): void {
this.upgradeHandlers.push({ prefix, handler }); this.upgradeHandlers.push({ prefix, handler });
} }
registerHostUpgradeHandler(
matcherHandler: (req: IncomingMessage, socket: Duplex, head: Buffer) => boolean,
): void {
this.hostUpgradeHandlers.push(matcherHandler);
}
onChannelSubscribe(listener: WsSubscribeListener): () => void { onChannelSubscribe(listener: WsSubscribeListener): () => void {
this.subscribeListeners.add(listener); this.subscribeListeners.add(listener);
return () => { return () => {
@ -167,18 +118,21 @@ export class WsHub {
broadcastAll(frame: ServerWsFrame): void { broadcastAll(frame: ServerWsFrame): void {
const text = JSON.stringify(frame); const text = JSON.stringify(frame);
const critical = frame.type === 'security:panic-lock' || frame.type === 'vault:state';
for (const client of this.clients) { 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 { broadcastChannel(channel: string, frame: ServerWsFrame): void {
const text = JSON.stringify(frame); const text = JSON.stringify(frame);
const critical = frame.type === 'pty:exit' || frame.type === 'error';
for (const client of this.clients) { for (const client of this.clients) {
if (client.channels.has(channel)) { if (
this.safeSendRaw(client, text, critical); 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, socket: Duplex,
head: Buffer, head: Buffer,
): void { ): void {
for (const matcher of this.hostUpgradeHandlers) {
if (matcher(req, socket, head)) {
return;
}
}
const urlPath = (req.url ?? '').split('?')[0] ?? ''; const urlPath = (req.url ?? '').split('?')[0] ?? '';
for (const entry of this.upgradeHandlers) { for (const entry of this.upgradeHandlers) {
if (urlPath.startsWith(entry.prefix)) { if (urlPath.startsWith(entry.prefix)) {
@ -206,29 +155,13 @@ export class WsHub {
return; return;
} }
const cookies = extractCookies(req.headers.cookie); // Validate Origin when provided by browsers to block cross-site WS hijacking
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
const origin = req.headers.origin; const origin = req.headers.origin;
const host = req.headers.host; const host = req.headers.host;
if (origin) { if (origin && host) {
try { try {
const originUrl = new URL(origin); const originUrl = new URL(origin);
const validScheme = if (originUrl.host !== host) {
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) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy(); socket.destroy();
return; 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) => { this.wss.handleUpgrade(req, socket, head, (ws) => {
const meta: WsClientMeta = { const meta: WsClientMeta = {
ws, ws,
@ -251,17 +193,13 @@ export class WsHub {
}; };
this.clients.add(meta); this.clients.add(meta);
this.sendFrame( this.sendFrame(ws, {
ws, type: 'hello',
{ vaultState: this.vaultService.state,
type: 'hello', vaultRuntimeReady: this.vaultService.isRuntimeReady,
vaultState: this.vaultService.state, safeMode: session.safeMode,
vaultRuntimeReady: this.vaultService.isRuntimeReady, elevatedUntil: session.elevatedUntil,
safeMode: session.safeMode, });
elevatedUntil: session.elevatedUntil,
},
true,
);
ws.on('pong', () => { ws.on('pong', () => {
meta.alive = true; 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 { private onMessage(meta: WsClientMeta, raw: unknown): void {
let parsedJson: unknown; let parsedJson: unknown;
try { try {
const text = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf8'); const text = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf8');
parsedJson = JSON.parse(text); parsedJson = JSON.parse(text);
} catch { } catch {
this.sendFrame( this.sendFrame(meta.ws, {
meta.ws, type: 'error',
{ code: 'BAD_JSON',
type: 'error', message: 'Invalid WebSocket JSON frame',
code: 'BAD_JSON', });
message: 'Invalid WebSocket JSON frame',
},
true,
);
return; return;
} }
const result = ClientWsFrameSchema.safeParse(parsedJson); const result = ClientWsFrameSchema.safeParse(parsedJson);
if (!result.success) { if (!result.success) {
this.sendFrame( this.sendFrame(meta.ws, {
meta.ws, type: 'error',
{ code: 'INVALID_FRAME',
type: 'error', message: 'Unrecognized or malformed WebSocket frame',
code: 'INVALID_FRAME', });
message: 'Unrecognized or malformed WebSocket frame',
},
true,
);
return; return;
} }
const frame = result.data; const frame = result.data;
switch (frame.type) { switch (frame.type) {
case 'ping': { case 'ping':
if (!this.ensureActiveSession(meta)) return; this.sendFrame(meta.ws, {
this.sendFrame( type: 'pong',
meta.ws, ts: frame.ts,
{ serverTs: Date.now(),
type: 'pong', });
ts: frame.ts,
serverTs: Date.now(),
},
true,
);
break; break;
}
case 'sub': { case 'sub': {
if (!this.ensureActiveSession(meta)) return;
const ctx = { const ctx = {
send: (outFrame: ServerWsFrame) => this.sendFrame(meta.ws, outFrame), send: (outFrame: ServerWsFrame) => this.sendFrame(meta.ws, outFrame),
sessionIdHash: meta.sessionIdHash, sessionIdHash: meta.sessionIdHash,
@ -365,78 +274,44 @@ export class WsHub {
meta.channels.delete(ch); meta.channels.delete(ch);
} }
break; break;
case 'safe-mode': { case 'safe-mode':
const latestSession = this.ensureActiveSession(meta); meta.clientSafeMode = frame.enabled;
if (!latestSession) return;
meta.clientSafeMode = latestSession.safeMode || frame.enabled;
break; break;
}
case 'pty:input': { case 'pty:input': {
const latestSession = this.ensureActiveSession(meta); const latestSession = this.authService.getSessionByToken(meta.sessionToken);
if (!latestSession) return; if (!latestSession) {
meta.ws.close(4001, 'Session expired');
return;
}
if (latestSession.safeMode || meta.clientSafeMode) { if (latestSession.safeMode || meta.clientSafeMode) {
this.sendFrame( this.sendFrame(meta.ws, {
meta.ws, type: 'error',
{ code: 'SAFE_MODE_ACTIVE',
type: 'error', message: 'Safe / Read-Only Mode blocks terminal input.',
code: 'SAFE_MODE_ACTIVE', });
message: 'Safe / Read-Only Mode blocks terminal input.',
},
true,
);
return; return;
} }
this.ptyHandlers?.onInput(frame.sessionId, frame.data); this.ptyHandlers?.onInput(frame.sessionId, frame.data);
break; break;
} }
case 'pty:resize': { 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); this.ptyHandlers?.onResize(frame.sessionId, frame.cols, frame.rows);
break; break;
} }
case 'ai:cancel': { 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;
}
this.aiHandlers?.onCancel(frame.chatId); this.aiHandlers?.onCancel(frame.chatId);
break; break;
}
} }
} }
private safeSendRaw(client: WsClientMeta, payload: string, critical = false): void { private sendFrame(ws: WebSocket, frame: ServerWsFrame): void {
if (client.ws.readyState !== WebSocket.OPEN) return; if (ws.readyState === WebSocket.OPEN) {
if (client.ws.bufferedAmount > WS_HARD_BACKPRESSURE_BYTES) { ws.send(JSON.stringify(frame));
client.ws.terminate();
this.clients.delete(client);
return;
} }
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));
} }
} }

View file

@ -2,29 +2,23 @@ import fs from 'node:fs';
import http from 'node:http'; import http from 'node:http';
import path from 'node:path'; import path from 'node:path';
import type Database from 'better-sqlite3'; import type Database from 'better-sqlite3';
import express, { type Express, type NextFunction, type Request, type Response } from 'express'; import express, { type Express } from 'express';
import type { ThrottleMode } from '../shared/schemas/settings.schema.js';
import { AiService } from './ai/ai-service.js'; import { AiService } from './ai/ai-service.js';
import { AlertEngine } from './alerts/alert-engine.js'; import { AlertEngine } from './alerts/alert-engine.js';
import { BroadcastService } from './automation/broadcast-service.js'; import { BroadcastService } from './automation/broadcast-service.js';
import { TransferEngine } from './automation/transfer-engine.js'; import { TransferEngine } from './automation/transfer-engine.js';
import { WorkflowEngine } from './automation/workflow-engine.js'; import { WorkflowEngine } from './automation/workflow-engine.js';
import { ConfigManager } from './config/config-manager.js'; import { ConfigManager } from './config/config-manager.js';
import { resolveRuntimeLimits } from './config/runtime-limits.js'; import { openDatabase } from './db/database.js';
import { applyDatabaseThrottlePragmas, openDatabase } from './db/database.js';
import { ServerInspector } from './monitoring/inspector.js'; import { ServerInspector } from './monitoring/inspector.js';
import { MonitoringService } from './monitoring/monitoring-service.js'; import { MonitoringService } from './monitoring/monitoring-service.js';
import { ProbeRunner } from './monitoring/probes.js'; import { ProbeRunner } from './monitoring/probes.js';
import { createPrometheusHandler } from './monitoring/prometheus.js';
import { AuditService } from './security/audit.js'; import { AuditService } from './security/audit.js';
import { AuthService } from './security/auth.js'; import { AuthService } from './security/auth.js';
import { BackupScheduler } from './security/backup-scheduler.js';
import { import {
DEFAULT_TRUSTED_PROXY_CIDRS,
RateLimiter, RateLimiter,
attachClientIp, attachClientIp,
createStepUpGuard, createStepUpGuard,
isTrustedProxyPeer,
} from './security/guards.js'; } from './security/guards.js';
import { EmergencyRecoveryService } from './security/recovery-store.js'; import { EmergencyRecoveryService } from './security/recovery-store.js';
import { VaultService } from './security/vault.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 { PTYManager } from './ssh/pty-manager.js';
import { SftpService } from './ssh/sftp-service.js'; import { SftpService } from './ssh/sftp-service.js';
import { SSHPool } from './ssh/ssh-pool.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 { CustomSystemsEngine } from './systems/systems-engine.js';
import { createAiRouter } from './api/routes/ai.routes.js'; import { createAiRouter } from './api/routes/ai.routes.js';
import { createAlertsRouter } from './api/routes/alerts.routes.js'; import { createAlertsRouter } from './api/routes/alerts.routes.js';
@ -58,17 +52,7 @@ export interface ServerOptions {
publicDir?: string; publicDir?: string;
secretFilePath?: string; secretFilePath?: string;
envMasterKey?: string; envMasterKey?: string;
envDbKey?: string;
trustCloudflare?: boolean; trustCloudflare?: boolean;
trustedProxyCidrs?: string[];
allowLanTunnels?: boolean;
proxyBaseDomain?: string;
proxyPort?: number;
webauthnRpId?: string;
webauthnOrigins?: string[];
metricsToken?: string;
throttleModeOverride?: ThrottleMode;
autoKeyFile?: boolean;
watchConfig?: boolean; watchConfig?: boolean;
} }
@ -90,7 +74,6 @@ export interface GCoordinatorInstance {
customSystemsEngine: CustomSystemsEngine; customSystemsEngine: CustomSystemsEngine;
serverInspector: ServerInspector; serverInspector: ServerInspector;
monitoringService: MonitoringService; monitoringService: MonitoringService;
backupScheduler: BackupScheduler;
transferEngine: TransferEngine; transferEngine: TransferEngine;
workflowEngine: WorkflowEngine; workflowEngine: WorkflowEngine;
broadcastService: BroadcastService; broadcastService: BroadcastService;
@ -98,7 +81,6 @@ export interface GCoordinatorInstance {
aiService: AiService; aiService: AiService;
wsHub: WsHub; wsHub: WsHub;
port: number; port: number;
proxyPort?: number;
close(): Promise<void>; close(): Promise<void>;
} }
@ -110,41 +92,24 @@ export async function createGCoordinatorServer(
const dbPath = path.join(dataDir, 'gcoord.db'); const dbPath = path.join(dataDir, 'gcoord.db');
const vaultPath = path.join(dataDir, 'vault.enc'); const vaultPath = path.join(dataDir, 'vault.enc');
const trustCloudflare = Boolean(options.trustCloudflare); const trustCloudflare = Boolean(options.trustCloudflare);
const trustedProxyCidrs = options.trustedProxyCidrs ?? DEFAULT_TRUSTED_PROXY_CIDRS;
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 }); fs.mkdirSync(dataDir, { recursive: true });
try {
fs.chmodSync(dataDir, 0o700);
} catch {
// Best-effort on filesystems without POSIX permissions
}
const db = openDatabase(dbPath); const db = openDatabase(dbPath);
const auditService = new AuditService(db); const auditService = new AuditService(db);
const vaultService = new VaultService(vaultPath, { const vaultService = new VaultService(vaultPath, {
keyFilePath: path.join(dataDir, 'vault.key'), keyFilePath: path.join(dataDir, 'vault.key'),
allowLocalKeyFile: options.autoKeyFile ?? true,
}); });
const recoveryStore = new EmergencyRecoveryService(dataDir); const recoveryStore = new EmergencyRecoveryService(dataDir);
const rateLimiter = new RateLimiter({ db }); const rateLimiter = new RateLimiter();
const configManager = new ConfigManager(configDir, db, vaultService); const configManager = new ConfigManager(configDir, db, vaultService);
await configManager.init({ watch: options.watchConfig ?? true }); 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, { const authService = new AuthService(db, {
getSecuritySettings: () => configManager.getSettings().security, getSecuritySettings: () => configManager.getSettings().security,
getRuntimeLimits,
recoveryStore, recoveryStore,
vaultService, vaultService,
dataDir,
envDbKey: options.envDbKey,
}); });
const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup
@ -164,49 +129,37 @@ export async function createGCoordinatorServer(
} }
const app = express(); const app = express();
app.locals.auditService = auditService;
app.disable('x-powered-by'); app.disable('x-powered-by');
if (trustCloudflare) { if (trustCloudflare) {
app.set('trust proxy', (ip: string) => isTrustedProxyPeer(ip, trustedProxyCidrs)); app.set('trust proxy', 1);
} }
const httpServer = http.createServer(app); const httpServer = http.createServer(app);
const wsHub = new WsHub(httpServer, authService, vaultService, { trustCloudflare }); const wsHub = new WsHub(httpServer, authService, vaultService);
authService.onSessionsRevoked((idHashes) => {
wsHub.disconnectSessions(idHashes);
});
const knownHosts = new KnownHostsService(db, auditService); const knownHosts = new KnownHostsService(db, auditService);
const sshPool = new SSHPool(configManager, vaultService, knownHosts); const sshPool = new SSHPool(configManager, vaultService, knownHosts);
const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService); 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 sftpService = new SftpService(sshPool);
const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService, { const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService);
getRuntimeLimits,
allowLanTunnels: options.allowLanTunnels,
proxyBaseDomain: options.proxyBaseDomain,
proxyPort: options.proxyPort,
trustCloudflare,
});
const customSystemsEngine = new CustomSystemsEngine( const customSystemsEngine = new CustomSystemsEngine(
sshPool, sshPool,
configManager, configManager,
vaultService, vaultService,
ptyManager, ptyManager,
wsHub, wsHub,
getRuntimeLimits,
); );
const serverInspector = new ServerInspector(sshPool, configManager); const serverInspector = new ServerInspector(sshPool, configManager);
const probeRunner = new ProbeRunner(sshPool, configManager); const probeRunner = new ProbeRunner(sshPool);
const monitoringService = new MonitoringService( const monitoringService = new MonitoringService(
db, db,
configManager, configManager,
vaultService, vaultService,
sshPool, sshPool,
probeRunner, probeRunner,
getRuntimeLimits,
); );
const transferEngine = new TransferEngine(sshPool, sftpService, configManager, knownHosts); const transferEngine = new TransferEngine(sshPool, sftpService, configManager);
const workflowEngine = new WorkflowEngine( const workflowEngine = new WorkflowEngine(
db, db,
configManager, configManager,
@ -217,7 +170,6 @@ export async function createGCoordinatorServer(
transferEngine, transferEngine,
wsHub, wsHub,
auditService, auditService,
getRuntimeLimits,
); );
const broadcastService = new BroadcastService( const broadcastService = new BroadcastService(
configManager, configManager,
@ -225,8 +177,6 @@ export async function createGCoordinatorServer(
sshPool, sshPool,
wsHub, wsHub,
auditService, auditService,
db,
getRuntimeLimits,
); );
const alertEngine = new AlertEngine( const alertEngine = new AlertEngine(
db, db,
@ -245,24 +195,8 @@ export async function createGCoordinatorServer(
sshPool, sshPool,
wsHub, wsHub,
auditService, 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) => { wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => {
tunnelManager.handleWsProxyUpgrade(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) => { app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'no-referrer'); 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/')) { 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('X-Frame-Options', 'DENY');
res.setHeader( res.setHeader(
'Content-Security-Policy', '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(); next();
}); });
app.use(attachClientIp(trustCloudflare, trustedProxyCidrs)); app.use(attachClientIp(trustCloudflare));
// Mount /proxy before express.json so proxied POST/PUT payloads stream untouched upstream // Mount /proxy before express.json so proxied POST/PUT payloads stream untouched upstream
app.use('/proxy', createProxyRouter({ authService, tunnelManager })); app.use('/proxy', createProxyRouter({ authService, tunnelManager }));
const jsonParser = express.json({ limit: '2mb' }); const jsonParser = express.json({ limit: '2mb' });
const backupJsonParser = express.json({ limit: '16mb' });
app.use((req, res, next) => { app.use((req, res, next) => {
if (req.path.endsWith('/sftp/upload')) { if (req.path.endsWith('/sftp/upload')) {
next(); next();
return; return;
} }
if (req.path.startsWith('/api/backup/')) {
backupJsonParser(req, res, next);
return;
}
jsonParser(req, res, next); 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(); monitoringService.start();
void tunnelManager.syncAutoStart(); void tunnelManager.syncAutoStart();
customSystemsEngine.syncBackgroundChecks(); customSystemsEngine.syncBackgroundChecks();
workflowEngine.start(); workflowEngine.start();
alertEngine.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(() => { vaultService.onPanicLock(() => {
void alertEngine.emitSecurityEvent('vault.panic_lock', {
message: 'Emergency Panic Lock activated',
});
aiService.cancelAll(); aiService.cancelAll();
backupScheduler.stop();
alertEngine.handlePanicLock(); alertEngine.handlePanicLock();
workflowEngine.handlePanicLock(); workflowEngine.handlePanicLock();
broadcastService.cancelAll(); broadcastService.cancelAll();
@ -449,8 +320,8 @@ export async function createGCoordinatorServer(
tunnelManager.stopAll(); tunnelManager.stopAll();
ptyManager.closeAll(true); ptyManager.closeAll(true);
sshPool.closeAll('panic_lock'); sshPool.closeAll('panic_lock');
wsHub.handlePanicLock();
authService.revokeAllSessions(); authService.revokeAllSessions();
wsHub.handlePanicLock();
}); });
configManager.onChange((event) => { configManager.onChange((event) => {
@ -461,9 +332,6 @@ export async function createGCoordinatorServer(
warnings: event.warnings, warnings: event.warnings,
errors: event.errors, errors: event.errors,
}); });
if (event.entityType === 'alerts' || event.entityType === 'server' || event.entityType === 'all') {
alertEngine.syncWithConfig();
}
if ( if (
event.entityType === 'server' || event.entityType === 'server' ||
event.entityType === 'system' || event.entityType === 'system' ||
@ -478,32 +346,16 @@ export async function createGCoordinatorServer(
customSystemsEngine.invalidateCache(event.id); customSystemsEngine.invalidateCache(event.id);
} else if (event.entityType === 'system' && event.id) { } else if (event.entityType === 'system' && event.id) {
customSystemsEngine.invalidateCache(undefined, event.id); customSystemsEngine.invalidateCache(undefined, event.id);
} else if (event.entityType === 'all') { } else {
customSystemsEngine.invalidateCache(); customSystemsEngine.invalidateCache();
} }
if (event.entityType === 'settings' || event.entityType === 'all') { if (event.entityType === 'settings') {
applyDatabaseThrottlePragmas(db, getRuntimeLimits()); authService.syncRecovery();
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();
} }
monitoringService.syncServers();
customSystemsEngine.syncBackgroundChecks();
workflowEngine.syncCronJobs();
void tunnelManager.syncAutoStart();
} }
}); });
@ -513,7 +365,11 @@ export async function createGCoordinatorServer(
); );
app.get('/api/healthz', (_req, res) => { app.get('/api/healthz', (_req, res) => {
res.json({ ok: true }); res.json({
ok: true,
vaultState: vaultService.state,
vaultRuntimeReady: vaultService.isRuntimeReady,
});
}); });
app.use( app.use(
@ -526,8 +382,6 @@ export async function createGCoordinatorServer(
recoveryStore, recoveryStore,
rateLimiter, rateLimiter,
trustCloudflare, trustCloudflare,
webauthnRpId: options.webauthnRpId,
webauthnOrigins: options.webauthnOrigins,
}), }),
); );
@ -543,7 +397,6 @@ export async function createGCoordinatorServer(
monitoringService.syncServers(); monitoringService.syncServers();
customSystemsEngine.syncBackgroundChecks(); customSystemsEngine.syncBackgroundChecks();
workflowEngine.syncCronJobs(); workflowEngine.syncCronJobs();
backupScheduler.sync();
void tunnelManager.syncAutoStart(); void tunnelManager.syncAutoStart();
}, },
onVaultChanged: (snapshotReason) => { onVaultChanged: (snapshotReason) => {
@ -563,27 +416,18 @@ export async function createGCoordinatorServer(
configManager, configManager,
auditService, auditService,
stepUpGuard, stepUpGuard,
getRuntimeLimits,
backupScheduler,
onRestored: async ({ inner, vaultKeyCandidate }) => { onRestored: async ({ inner, vaultKeyCandidate }) => {
if (inner.vaultEnvelopeRaw !== null) { if (inner.vaultEnvelopeRaw !== null) {
try { try {
vaultService.reloadFromDisk(vaultKeyCandidate); vaultService.reloadFromDisk(vaultKeyCandidate);
} catch { } catch {
// Avoid keeping an old runtime master key unlocked against a newly restored foreign vault // Keep existing runtime state untouched if backup vault used a different key
vaultService.seal();
vaultService.dropLocalKeyFile();
} }
} }
knownHosts.replaceAllKnownHosts(inner.knownHosts); knownHosts.replaceAllKnownHosts(inner.knownHosts);
configManager.reloadAllFromDisk(); configManager.reloadAllFromDisk();
sshPool.syncWithConfig(); sshPool.syncWithConfig();
backupScheduler.sync(); if (authService.isBootstrapped() && vaultService.isRuntimeReady) {
if (
authService.isBootstrapped() &&
vaultService.isRuntimeReady &&
configManager.getSettings().security.enableEmergencySecretsBackup
) {
authService.syncRecovery({ snapshotReason: 'backup-restore' }); authService.syncRecovery({ snapshotReason: 'backup-restore' });
} }
wsHub.broadcastAll({ wsHub.broadcastAll({
@ -602,12 +446,7 @@ export async function createGCoordinatorServer(
); );
app.use( app.use(
'/api/systems', '/api/systems',
createSystemsRouter({ createSystemsRouter({ authService, auditService, systemsEngine: customSystemsEngine }),
authService,
auditService,
systemsEngine: customSystemsEngine,
stepUpGuard,
}),
); );
app.use( app.use(
'/api/workflows', '/api/workflows',
@ -625,12 +464,12 @@ export async function createGCoordinatorServer(
); );
app.use( app.use(
'/api/alerts', '/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( app.use(
'/api/servers/:id/sftp', '/api/servers/:id/sftp',
createSftpRouter({ authService, configManager, auditService, sftpService, stepUpGuard }), createSftpRouter({ authService, configManager, auditService, sftpService }),
); );
app.use( app.use(
'/api/servers', '/api/servers',
@ -652,20 +491,9 @@ export async function createGCoordinatorServer(
); );
app.use( app.use(
'/api/config', '/api/config',
createConfigRouter({ authService, configManager, auditService, stepUpGuard }), createConfigRouter({ authService, configManager, auditService }),
); );
app.use('/api/audit', createAuditRouter(authService, auditService)); app.use('/api/audit', createAuditRouter(authService, auditService));
app.get(
'/metrics',
createPrometheusHandler({
configManager,
vaultService,
sshPool,
monitoringService,
tunnelManager,
alertEngine,
}),
);
app.use('/api', (_req, res) => { app.use('/api', (_req, res) => {
res.status(404).json({ error: 'API_ROUTE_NOT_FOUND' }); 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<void>((resolve, reject) => { await new Promise<void>((resolve, reject) => {
httpServer.once('error', reject); httpServer.once('error', reject);
httpServer.listen(options.port, options.host ?? '0.0.0.0', () => { httpServer.listen(options.port, options.host ?? '0.0.0.0', () => {
@ -730,7 +538,6 @@ export async function createGCoordinatorServer(
customSystemsEngine, customSystemsEngine,
serverInspector, serverInspector,
monitoringService, monitoringService,
backupScheduler,
transferEngine, transferEngine,
workflowEngine, workflowEngine,
broadcastService, broadcastService,
@ -738,20 +545,16 @@ export async function createGCoordinatorServer(
aiService, aiService,
wsHub, wsHub,
port: actualPort, port: actualPort,
proxyPort: tunnelManager.actualProxyPort,
async close() { async close() {
aiService.close(); aiService.close();
backupScheduler.close();
alertEngine.close(); alertEngine.close();
workflowEngine.close(); workflowEngine.close();
broadcastService.cancelAll(); broadcastService.cancelAll();
monitoringService.close(); monitoringService.close();
customSystemsEngine.close(); customSystemsEngine.close();
tunnelManager.stopAll(); tunnelManager.stopAll();
await tunnelManager.stopProxyServer();
ptyManager.close(); ptyManager.close();
sshPool.closeAll('shutdown'); sshPool.closeAll('shutdown');
authService.close();
wsHub.close(); wsHub.close();
await configManager.close(); await configManager.close();
await new Promise<void>((resolve) => { await new Promise<void>((resolve) => {

View file

@ -1,9 +1,7 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import type Database from 'better-sqlite3';
import type { ServerWsFrame } from '../../shared/ws-protocol.js'; import type { ServerWsFrame } from '../../shared/ws-protocol.js';
import type { WsHub } from '../api/ws-hub.js'; import type { WsHub } from '../api/ws-hub.js';
import type { ConfigManager } from '../config/config-manager.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 { AuditService } from '../security/audit.js';
import type { VaultService } from '../security/vault.js'; import type { VaultService } from '../security/vault.js';
import type { SSHPool } from '../ssh/ssh-pool.js'; import type { SSHPool } from '../ssh/ssh-pool.js';
@ -11,8 +9,6 @@ import { BufferedStreamEmitter } from './stream-buffer.js';
import { import {
buildWorkflowEnv, buildWorkflowEnv,
interpolateShellCommandSafe, interpolateShellCommandSafe,
maskSecretInputsForStorage,
redactWorkflowSecrets,
resolveTargetServers, resolveTargetServers,
validateAndResolveInputs, validateAndResolveInputs,
} from './template.js'; } from './template.js';
@ -42,14 +38,10 @@ export interface BroadcastJobSummary {
interface ActiveBroadcastJob extends BroadcastJobSummary { interface ActiveBroadcastJob extends BroadcastJobSummary {
emitter: BufferedStreamEmitter; emitter: BufferedStreamEmitter;
abortController: AbortController; abortController: AbortController;
secretValues: string[];
} }
function csvSafeCell(val: unknown): string { const MAX_RETAINED_BROADCASTS = 25;
const s = val === null || val === undefined ? '' : String(val); const MAX_OUTPUT_PER_SERVER = 256 * 1024;
const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s;
return `"${safe.replace(/"/g, '""')}"`;
}
async function runPool<T>( async function runPool<T>(
items: T[], items: T[],
@ -76,8 +68,6 @@ export class BroadcastService {
private readonly sshPool: SSHPool, private readonly sshPool: SSHPool,
private readonly wsHub: WsHub, private readonly wsHub: WsHub,
private readonly auditService: AuditService, private readonly auditService: AuditService,
private readonly db?: Database.Database,
private readonly getRuntimeLimits?: () => RuntimeLimits,
) {} ) {}
getStreamReplayFrames(jobId: string): ServerWsFrame[] { getStreamReplayFrames(jobId: string): ServerWsFrame[] {
@ -86,178 +76,17 @@ export class BroadcastService {
getBroadcastResult(jobId: string): BroadcastJobSummary | undefined { getBroadcastResult(jobId: string): BroadcastJobSummary | undefined {
const job = this.jobs.get(jobId); const job = this.jobs.get(jobId);
if (job) { if (!job) return undefined;
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 = [];
}
return { return {
jobId: row.jobId, jobId: job.jobId,
snippetId: row.snippetId ?? undefined, snippetId: job.snippetId,
command: row.command, command: job.command,
sudo: false, sudo: job.sudo,
createdAt: row.startedAt, createdAt: job.createdAt,
finishedAt: row.finishedAt, finishedAt: job.finishedAt,
cancelled: row.status === 'cancelled', cancelled: job.cancelled,
done: row.finishedAt !== null || row.status !== 'running', done: job.done,
targets, targets: job.targets.map((t) => ({ ...t })),
};
}
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),
}; };
} }
@ -296,7 +125,6 @@ export class BroadcastService {
let rawCommand = opts.command?.trim() ?? ''; let rawCommand = opts.command?.trim() ?? '';
let sudo = Boolean(opts.sudo); let sudo = Boolean(opts.sudo);
let resolvedInputs: Record<string, string> = {}; let resolvedInputs: Record<string, string> = {};
let secretValues: string[] = [];
if (opts.snippetId) { if (opts.snippetId) {
const snip = this.configManager const snip = this.configManager
@ -306,7 +134,6 @@ export class BroadcastService {
throw new Error(`Unknown command snippet "${opts.snippetId}"`); throw new Error(`Unknown command snippet "${opts.snippetId}"`);
} }
resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {}); resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {});
secretValues = maskSecretInputsForStorage(snip.inputs, resolvedInputs).secretValues;
rawCommand = snip.command; rawCommand = snip.command;
sudo = opts.sudo ?? snip.sudo; sudo = opts.sudo ?? snip.sudo;
} else { } else {
@ -314,14 +141,14 @@ export class BroadcastService {
throw new Error('Command or snippetId is required for Fleet Broadcast'); throw new Error('Command or snippetId is required for Fleet Broadcast');
} }
if (opts.inputs) { 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 baseCtx = { inputs: resolvedInputs };
const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx); const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx);
const displayCommand = redactWorkflowSecrets(renderedCommand, secretValues);
const allServers = this.configManager.listServers(); const allServers = this.configManager.listServers();
let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx); let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx);
@ -341,11 +168,7 @@ export class BroadcastService {
} }
const jobId = `bcast-${crypto.randomBytes(6).toString('hex')}`; const jobId = `bcast-${crypto.randomBytes(6).toString('hex')}`;
const emitter = new BufferedStreamEmitter( const emitter = new BufferedStreamEmitter(this.wsHub, jobId);
this.wsHub,
jobId,
limits?.streamReplayBytes,
);
const abortController = new AbortController(); const abortController = new AbortController();
const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({ const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({
@ -361,7 +184,7 @@ export class BroadcastService {
const job: ActiveBroadcastJob = { const job: ActiveBroadcastJob = {
jobId, jobId,
snippetId: opts.snippetId, snippetId: opts.snippetId,
command: displayCommand, command: renderedCommand,
sudo, sudo,
createdAt: Date.now(), createdAt: Date.now(),
finishedAt: null, finishedAt: null,
@ -370,12 +193,9 @@ export class BroadcastService {
targets, targets,
emitter, emitter,
abortController, abortController,
secretValues,
}; };
this.jobs.set(jobId, job); this.jobs.set(jobId, job);
this.persistBroadcastRow(job, 'running');
this.auditService.log({ this.auditService.log({
action: 'broadcast.start', action: 'broadcast.start',
actorIp: opts.actorIp, actorIp: opts.actorIp,
@ -391,14 +211,12 @@ export class BroadcastService {
emitter.pushMeta({ emitter.pushMeta({
event: 'start', event: 'start',
jobId, jobId,
command: displayCommand, command: renderedCommand,
targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })), targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })),
}); });
const maxStepLogBytes = limits?.maxStepLogBytes ?? 256 * 1024;
const timeoutMs = (opts.timeoutSec ?? 120) * 1000; const timeoutMs = (opts.timeoutSec ?? 120) * 1000;
const concurrencyCap = limits?.maxWorkflowStepTargets ?? 32; const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, 32));
const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, concurrencyCap));
void runPool(matchedServers, concurrency, async (srv) => { void runPool(matchedServers, concurrency, async (srv) => {
const targetEntry = job.targets.find((t) => t.serverId === srv.id)!; const targetEntry = job.targets.find((t) => t.serverId === srv.id)!;
@ -421,7 +239,6 @@ export class BroadcastService {
const env = buildWorkflowEnv({ const env = buildWorkflowEnv({
inputs: resolvedInputs, inputs: resolvedInputs,
serverId: srv.id, serverId: srv.id,
serverMeta: { id: srv.id, name: srv.name, host: srv.host, port: srv.port },
}); });
try { try {
@ -436,9 +253,9 @@ export class BroadcastService {
let errBytes = 0; let errBytes = 0;
handle.channel.on('data', (chunk: Buffer) => { handle.channel.on('data', (chunk: Buffer) => {
const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues); const text = chunk.toString('utf8');
if (outBytes < maxStepLogBytes) { if (outBytes < MAX_OUTPUT_PER_SERVER) {
const slice = chunk.subarray(0, maxStepLogBytes - outBytes); const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - outBytes);
outChunks.push(slice); outChunks.push(slice);
outBytes += slice.length; outBytes += slice.length;
} }
@ -452,9 +269,9 @@ export class BroadcastService {
}); });
handle.channel.stderr?.on('data', (chunk: Buffer) => { handle.channel.stderr?.on('data', (chunk: Buffer) => {
const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues); const text = chunk.toString('utf8');
if (errBytes < maxStepLogBytes) { if (errBytes < MAX_OUTPUT_PER_SERVER) {
const slice = chunk.subarray(0, maxStepLogBytes - errBytes); const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - errBytes);
errChunks.push(slice); errChunks.push(slice);
errBytes += slice.length; errBytes += slice.length;
} }
@ -479,14 +296,8 @@ export class BroadcastService {
try { try {
const { exitCode } = await handle.done; const { exitCode } = await handle.done;
targetEntry.stdout = redactWorkflowSecrets( targetEntry.stdout = Buffer.concat(outChunks).toString('utf8');
Buffer.concat(outChunks).toString('utf8'), targetEntry.stderr = Buffer.concat(errChunks).toString('utf8');
secretValues,
);
targetEntry.stderr = redactWorkflowSecrets(
Buffer.concat(errChunks).toString('utf8'),
secretValues,
);
targetEntry.durationMs = Date.now() - started; targetEntry.durationMs = Date.now() - started;
targetEntry.exitCode = exitCode; targetEntry.exitCode = exitCode;
@ -505,10 +316,7 @@ export class BroadcastService {
} catch (err) { } catch (err) {
targetEntry.durationMs = Date.now() - started; targetEntry.durationMs = Date.now() - started;
targetEntry.status = abortController.signal.aborted ? 'cancelled' : 'error'; targetEntry.status = abortController.signal.aborted ? 'cancelled' : 'error';
const msg = redactWorkflowSecrets( const msg = err instanceof Error ? err.message : String(err);
err instanceof Error ? err.message : String(err),
secretValues,
);
targetEntry.stderr = targetEntry.stderr ? `${targetEntry.stderr}\n${msg}` : msg; targetEntry.stderr = targetEntry.stderr ? `${targetEntry.stderr}\n${msg}` : msg;
emitter.push('stderr', `[${srv.id}] ${msg}\n`); emitter.push('stderr', `[${srv.id}] ${msg}\n`);
} }
@ -524,12 +332,6 @@ export class BroadcastService {
job.done = true; job.done = true;
job.finishedAt = Date.now(); job.finishedAt = Date.now();
const okCount = job.targets.filter((t) => t.status === 'ok').length; 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({ emitter.pushMeta({
event: 'done', event: 'done',
cancelled: job.cancelled, cancelled: job.cancelled,
@ -542,33 +344,9 @@ export class BroadcastService {
return this.getBroadcastResult(jobId)!; 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 { private pruneJobs(): void {
const maxRam = Math.max(1, this.getRuntimeLimits?.().maxRamBroadcastJobs ?? 5);
const done = [...this.jobs.values()].filter((j) => j.done); const done = [...this.jobs.values()].filter((j) => j.done);
while (done.length > maxRam) { while (done.length > MAX_RETAINED_BROADCASTS) {
const oldest = done.shift()!; const oldest = done.shift()!;
this.jobs.delete(oldest.jobId); this.jobs.delete(oldest.jobId);
} }

View file

@ -10,17 +10,13 @@ export interface StepOutputSummary {
export interface TemplateContext { export interface TemplateContext {
workflowId?: string; workflowId?: string;
runId?: string; runId?: string;
triggerSource?: string;
serverId?: string; serverId?: string;
serverMeta?: { id: string; name: string; host: string; port: number };
inputs: Record<string, string>; inputs: Record<string, string>;
stepOutputs?: Map<string, StepOutputSummary>; stepOutputs?: Map<string, StepOutputSummary>;
captures?: Map<string, string>; captures?: Map<string, string>;
eventMeta?: Record<string, string>; eventMeta?: Record<string, string>;
} }
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
export function toEnvIdent(raw: string): string { export function toEnvIdent(raw: string): string {
return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase(); return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase();
} }
@ -31,15 +27,8 @@ export function validateAndResolveInputs(
): Record<string, string> { ): Record<string, string> {
const out: Record<string, string> = {}; const out: Record<string, string> = {};
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) { for (const def of defs) {
if (FORBIDDEN_KEYS.has(def.name)) continue; const raw = supplied[def.name];
const raw = Object.hasOwn(supplied, def.name) ? supplied[def.name] : undefined;
const hasSupplied = raw !== undefined && raw !== null && raw !== ''; const hasSupplied = raw !== undefined && raw !== null && raw !== '';
const candidate = hasSupplied ? raw : def.default; const candidate = hasSupplied ? raw : def.default;
@ -72,9 +61,6 @@ export function validateAndResolveInputs(
} }
const strVal = String(candidate); 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.type === 'select' && def.options && def.options.length > 0) {
if (!def.options.includes(strVal)) { if (!def.options.includes(strVal)) {
throw new Error( throw new Error(
@ -86,48 +72,14 @@ export function validateAndResolveInputs(
} }
for (const [k, v] of Object.entries(supplied)) { for (const [k, v] of Object.entries(supplied)) {
if (FORBIDDEN_KEYS.has(k)) continue; if (!(k in out) && v !== undefined && v !== null) {
if (!Object.hasOwn(out, k) && v !== undefined && v !== null) { out[k] = String(v);
const s = String(v);
if (/[\x00]/.test(s)) {
throw new Error(`Input "${k}" contains NUL bytes`);
}
out[k] = s;
} }
} }
return out; return out;
} }
export function maskSecretInputsForStorage(
defs: InputDef[],
resolved: Record<string, string>,
): { masked: Record<string, string>; secretValues: string[] } {
const secretKeys = new Set(defs.filter((d) => d.type === 'secret').map((d) => d.name));
const masked: Record<string, string> = {};
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<string, string> { export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
const env: Record<string, string> = {}; const env: Record<string, string> = {};
if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId; if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId;
@ -135,7 +87,6 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId; if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId;
for (const [k, v] of Object.entries(ctx.inputs)) { for (const [k, v] of Object.entries(ctx.inputs)) {
if (FORBIDDEN_KEYS.has(k)) continue;
env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v; env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v;
} }
@ -155,7 +106,6 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
if (ctx.eventMeta) { if (ctx.eventMeta) {
for (const [k, v] of Object.entries(ctx.eventMeta)) { for (const [k, v] of Object.entries(ctx.eventMeta)) {
if (FORBIDDEN_KEYS.has(k)) continue;
env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v; env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v;
} }
} }
@ -163,188 +113,45 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
return env; return env;
} }
/** function resolveTemplateToken(rawExpr: string, ctx: TemplateContext): string {
* 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 } {
const expr = rawExpr.trim(); const expr = rawExpr.trim();
if (!expr || expr.startsWith('.')) return { matched: false, value: '' }; if (expr.startsWith('inputs.')) {
const parts = expr.split('.'); const key = expr.slice('inputs.'.length);
if (parts.some((p) => FORBIDDEN_KEYS.has(p))) { return ctx.inputs[key] ?? '';
return { matched: false, value: '' };
} }
if (expr.startsWith('steps.')) {
if (expr.startsWith('inputs.') || expr.startsWith('input.')) { const rest = expr.slice('steps.'.length);
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);
const dot = rest.lastIndexOf('.'); const dot = rest.lastIndexOf('.');
if (dot > 0) { if (dot > 0) {
const stepId = rest.slice(0, dot); const stepId = rest.slice(0, dot);
const field = rest.slice(dot + 1); const field = rest.slice(dot + 1);
const out = ctx.stepOutputs?.get(stepId); const out = ctx.stepOutputs?.get(stepId);
if (field === 'stdout') return { matched: true, value: out ? out.stdout.trim() : '' }; if (!out) return '';
if (field === 'exitCode') { if (field === 'stdout') return out.stdout.trim();
return { if (field === 'exitCode') return out.exitCode === null ? '' : String(out.exitCode);
matched: true,
value: out && out.exitCode !== null ? String(out.exitCode) : '',
};
}
} }
return { matched: false, value: '' };
} }
if (expr.startsWith('captures.')) {
if (expr.startsWith('captures.') || expr.startsWith('capture.')) { const key = expr.slice('captures.'.length);
const key = expr.slice(expr.indexOf('.') + 1); return (ctx.captures?.get(key) ?? '').trim();
return { matched: true, value: (ctx.captures?.get(key) ?? '').trim() };
} }
if (expr.startsWith('event.')) { if (expr.startsWith('event.')) {
const key = expr.slice('event.'.length); const key = expr.slice('event.'.length);
return { return ctx.eventMeta?.[key] ?? '';
matched: true,
value: ctx.eventMeta && Object.hasOwn(ctx.eventMeta, key) ? ctx.eventMeta[key]! : '',
};
} }
return (ctx.captures?.get(expr) ?? ctx.inputs[expr] ?? '').trim();
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: '' };
} }
export function interpolateValuePlain(template: string, ctx: TemplateContext): string { export function interpolateValuePlain(template: string, ctx: TemplateContext): string {
return template.replace(/\{\{([^{}]+)\}\}/g, (full, expr: string) => { return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) =>
const res = resolveTemplateToken(expr, ctx); resolveTemplateToken(expr, ctx),
return res.matched ? res.value : full; );
});
} }
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 { export function interpolateShellCommandSafe(template: string, ctx: TemplateContext): string {
let out = ''; return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) =>
let quote: 'none' | 'single' | 'double' = 'none'; posixSingleQuote(resolveTemplateToken(expr, ctx)),
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;
} }
export function resolveTargetServers( export function resolveTargetServers(

View file

@ -2,7 +2,6 @@ import crypto from 'node:crypto';
import path from 'node:path'; import path from 'node:path';
import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2'; import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2';
import type { ConfigManager } from '../config/config-manager.js'; 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 { SftpService } from '../ssh/sftp-service.js';
import type { SSHPool } from '../ssh/ssh-pool.js'; import type { SSHPool } from '../ssh/ssh-pool.js';
import { posixSingleQuote } from '../ssh/sudo.js'; import { posixSingleQuote } from '../ssh/sudo.js';
@ -16,42 +15,8 @@ export interface TransferResult {
durationMs: number; durationMs: number;
} }
const FILE_TYPE_MASK = 0o170000;
const MODE_DIR = 0o040000;
const MODE_REG = 0o100000;
function isDirMode(mode: number): boolean { function isDirMode(mode: number): boolean {
return (mode & FILE_TYPE_MASK) === MODE_DIR; return (mode & 0o170000) === 0o040000;
}
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;
} }
function promisifySftp<T>( function promisifySftp<T>(
@ -81,7 +46,6 @@ export class TransferEngine {
private readonly sshPool: SSHPool, private readonly sshPool: SSHPool,
private readonly _sftpService: SftpService, private readonly _sftpService: SftpService,
private readonly configManager: ConfigManager, private readonly configManager: ConfigManager,
private readonly knownHosts?: KnownHostsService,
) { ) {
void this._sftpService; void this._sftpService;
} }
@ -90,8 +54,6 @@ export class TransferEngine {
mode: 'hub-relayed' | 'direct'; mode: 'hub-relayed' | 'direct';
source: { serverId: string; path: string }; source: { serverId: string; path: string };
destination: { serverId: string; path: string }; destination: { serverId: string; path: string };
delete?: boolean;
exclude?: string[];
sudo?: boolean; sudo?: boolean;
timeoutMs?: number; timeoutMs?: number;
signal?: AbortSignal; signal?: AbortSignal;
@ -110,29 +72,12 @@ export class TransferEngine {
throw new Error(`Destination server "${opts.destination.serverId}" not found or disabled`); 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 started = Date.now();
const timeoutMs = opts.timeoutMs ?? 600_000; const timeoutMs = opts.timeoutMs ?? 600_000;
if (opts.mode === 'direct') { if (opts.mode === 'direct') {
const safeExcludes = sanitizeRsyncExcludes(opts.exclude); const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`;
const excludeFlags = safeExcludes const cmd = `rsync -az -e ${posixSingleQuote(sshOpt)} -- ${posixSingleQuote(opts.source.path)} ${posixSingleQuote(`${dstServer.username}@${dstServer.host}:${opts.destination.path}`)}`;
.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)}`;
}
opts.onProgress?.(`Running direct rsync on ${srcServer.id}...`); opts.onProgress?.(`Running direct rsync on ${srcServer.id}...`);
const handle = await this.sshPool.execStream(srcServer.id, cmd, { const handle = await this.sshPool.execStream(srcServer.id, cmd, {
@ -212,8 +157,8 @@ export class TransferEngine {
return { return {
mode: 'direct', mode: 'direct',
sourcePath: safeSrcPath, sourcePath: opts.source.path,
destinationPath: safeDstPath, destinationPath: opts.destination.path,
filesTransferred: 1, filesTransferred: 1,
bytesTransferred: 0, bytesTransferred: 0,
durationMs: Date.now() - started, durationMs: Date.now() - started,
@ -256,21 +201,16 @@ export class TransferEngine {
opts.signal?.addEventListener('abort', onAbort, { once: true }); opts.signal?.addEventListener('abort', onAbort, { once: true });
try { try {
const trimmedDest = safeDstPath; const trimmedDest = opts.destination.path.trim();
const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/'); const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/');
const resolvedSrc = await this.resolveRemotePath(srcSftp, safeSrcPath); const resolvedSrc = await this.resolveRemotePath(srcSftp, opts.source.path);
const resolvedDest = await this.resolveRemotePath(dstSftp, safeDstPath); const resolvedDest = await this.resolveRemotePath(dstSftp, opts.destination.path);
const srcStat = await promisifySftp<Stats>((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 srcStat = await promisifySftp<Stats>((cb) => srcSftp.stat(resolvedSrc, cb));
let filesTransferred = 0; let filesTransferred = 0;
let bytesTransferred = 0; let bytesTransferred = 0;
if (isDirMode(srcMode)) { if (isDirMode(srcStat.mode ?? 0)) {
const dstStat = await promisifySftp<Stats>((cb) => dstSftp!.stat(resolvedDest, cb)).catch( const dstStat = await promisifySftp<Stats>((cb) => dstSftp!.stat(resolvedDest, cb)).catch(
() => null, () => null,
); );
@ -314,7 +254,7 @@ export class TransferEngine {
dstSftp, dstSftp,
resolvedSrc, resolvedSrc,
targetFile, targetFile,
srcMode || 0o644, srcStat.mode ?? 0o644,
activeStreams, activeStreams,
() => timedOutOrAborted, () => timedOutOrAborted,
opts.onProgress, opts.onProgress,
@ -401,21 +341,10 @@ export class TransferEngine {
let files = 0; let files = 0;
let bytes = 0; let bytes = 0;
for (const entry of entries) { for (const entry of entries) {
if ( if (entry.filename === '.' || entry.filename === '..') continue;
entry.filename === '.' ||
entry.filename === '..' ||
entry.filename.includes('/') ||
entry.filename.includes('\0')
) {
continue;
}
const srcChild = path.posix.join(srcDir, entry.filename); const srcChild = path.posix.join(srcDir, entry.filename);
const dstChild = path.posix.join(dstDir, entry.filename); const dstChild = path.posix.join(dstDir, entry.filename);
let mode = entry.attrs.mode ?? 0; const mode = entry.attrs.mode ?? 0;
if (mode === 0) {
const ls = await promisifySftp<Stats>((cb) => srcSftp.lstat(srcChild, cb)).catch(() => null);
mode = ls?.mode ?? 0;
}
if (isDirMode(mode)) { if (isDirMode(mode)) {
const sub = await this.copyDirectoryRecursive( const sub = await this.copyDirectoryRecursive(
@ -429,7 +358,7 @@ export class TransferEngine {
); );
files += sub.files; files += sub.files;
bytes += sub.bytes; bytes += sub.bytes;
} else if (isRegularMode(mode)) { } else {
const copied = await this.copySingleFile( const copied = await this.copySingleFile(
srcSftp, srcSftp,
dstSftp, dstSftp,
@ -442,8 +371,6 @@ export class TransferEngine {
); );
files += 1; files += 1;
bytes += copied; bytes += copied;
} else {
onProgress?.(`Skipping non-regular entry ${srcChild}`);
} }
} }
return { files, bytes }; return { files, bytes };

File diff suppressed because it is too large Load diff

View file

@ -351,7 +351,7 @@ export class ConfigManager {
const channelIds = new Set(this.alerts.channels.map((c) => c.id)); const channelIds = new Set(this.alerts.channels.map((c) => c.id));
if (this.vault && this.vault.isRuntimeReady) { if (this.vault && this.vault.isRuntimeReady) {
for (const ch of this.alerts.channels) { for (const ch of this.alerts.channels) {
if (ch.secretRef && !this.vault.hasCredential(ch.secretRef)) { if (!this.vault.hasCredential(ch.secretRef)) {
next.push({ next.push({
filePath: 'alerts.json', filePath: 'alerts.json',
code: 'MISSING_CHANNEL_SECRET', 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 rule of this.alerts.rules) {
for (const cid of rule.channelIds) { for (const cid of rule.channelIds) {
if (!channelIds.has(cid)) { if (!channelIds.has(cid)) {
@ -619,7 +604,6 @@ export class ConfigManager {
ignoreInitial: true, ignoreInitial: true,
persistent: true, persistent: true,
depth: 2, depth: 2,
followSymlinks: false,
}); });
const scheduleReload = (absPath: string, kind: 'upsert' | 'unlink') => { const scheduleReload = (absPath: string, kind: 'upsert' | 'unlink') => {
@ -829,39 +813,11 @@ export class ConfigManager {
} }
private resolveSafeAbsPath(relPath: string): string { private resolveSafeAbsPath(relPath: string): string {
const resolved = path.resolve(this.configDir, relPath);
const root = path.resolve(this.configDir); const root = path.resolve(this.configDir);
const resolved = path.resolve(root, relPath);
if (!resolved.startsWith(`${root}${path.sep}`)) { if (!resolved.startsWith(`${root}${path.sep}`)) {
throw new Error(`Path escapes config directory: ${relPath}`); 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; return resolved;
} }
@ -942,8 +898,8 @@ export class ConfigManager {
} }
private writeAtomicFile(absPath: string, content: string): void { private writeAtomicFile(absPath: string, content: string): void {
fs.mkdirSync(path.dirname(absPath), { recursive: true, mode: 0o700 }); fs.mkdirSync(path.dirname(absPath), { recursive: true });
const tmpPath = `${absPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const tmpPath = `${absPath}.tmp.${process.pid}.${Date.now()}`;
const fd = fs.openSync(tmpPath, 'w', 0o600); const fd = fs.openSync(tmpPath, 'w', 0o600);
try { try {
fs.writeFileSync(fd, content, 'utf8'); fs.writeFileSync(fd, content, 'utf8');

View file

@ -138,12 +138,12 @@ export const PRESET_SYSTEMS: SystemConfig[] = [
discovery: { discovery: {
type: 'command', type: 'command',
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', parser: 'lines',
}, },
status: { status: {
command: 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', parser: 'json',
health: { health: {
field: 'ActiveState', field: 'ActiveState',
@ -322,10 +322,7 @@ export function seedDefaultConfigs(configDir: string): string[] {
for (const [relPath, obj] of defaults) { for (const [relPath, obj] of defaults) {
const absPath = path.join(configDir, relPath); const absPath = path.join(configDir, relPath);
if (!fs.existsSync(absPath)) { if (!fs.existsSync(absPath)) {
fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, { fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, 'utf8');
encoding: 'utf8',
mode: 0o600,
});
created.push(relPath); created.push(relPath);
} }
} }

View file

@ -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<ThrottleMode, RuntimeLimits> = {
'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'];
}

View file

@ -1,62 +1,26 @@
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import Database from 'better-sqlite3'; import Database from 'better-sqlite3';
import type { RuntimeLimits } from '../config/runtime-limits.js';
import { migration001Initial, type Migration } from './migrations/001_initial.js'; import { migration001Initial, type Migration } from './migrations/001_initial.js';
import { migration002MultiAuth } from './migrations/002_multi_auth.js'; import { migration002MultiAuth } from './migrations/002_multi_auth.js';
import { migration003Phase4Meta } from './migrations/003_phase4_meta.js'; import { migration003Phase4Meta } from './migrations/003_phase4_meta.js';
import { migration004V11 } from './migrations/004_v1_1.js';
const MIGRATIONS: Migration[] = [ const MIGRATIONS: Migration[] = [
migration001Initial, migration001Initial,
migration002MultiAuth, migration002MultiAuth,
migration003Phase4Meta, 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<RuntimeLimits, 'sqliteCacheKb' | 'sqliteMmapBytes' | 'sqliteTempStore'>,
): 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 { export function openDatabase(dbPath: string): Database.Database {
const parentDir = path.dirname(dbPath); fs.mkdirSync(path.dirname(dbPath), { recursive: true });
fs.mkdirSync(parentDir, { recursive: true, mode: 0o700 });
chmodBestEffort(parentDir, 0o700);
const db = new Database(dbPath); const db = new Database(dbPath);
db.pragma('journal_mode = WAL'); db.pragma('journal_mode = WAL');
db.pragma('synchronous = NORMAL'); db.pragma('synchronous = NORMAL');
db.pragma('foreign_keys = ON'); db.pragma('foreign_keys = ON');
db.pragma('busy_timeout = 5000'); 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); runMigrations(db);
chmodBestEffort(dbPath, 0o600);
chmodBestEffort(`${dbPath}-wal`, 0o600);
chmodBestEffort(`${dbPath}-shm`, 0o600);
return db; return db;
} }

View file

@ -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);
`);
},
};

View file

@ -1,27 +1,14 @@
import path from 'node:path'; import path from 'node:path';
import { createGCoordinatorServer } from './app.js'; 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<void> { async function main(): Promise<void> {
const dataDir = path.resolve(process.env.GCOORD_DATA_DIR ?? './data'); const dataDir = path.resolve(process.env.GCOORD_DATA_DIR ?? './data');
const port = Number(process.env.PORT ?? 3000); const port = Number(process.env.PORT ?? 3000);
const host = process.env.HOST ?? '0.0.0.0'; const host = process.env.HOST ?? '0.0.0.0';
const trustCloudflare = process.env.TRUST_CLOUDFLARE === 'true'; const trustCloudflare = process.env.TRUST_CLOUDFLARE === 'true';
const trustedProxyCidrs = parseCsvList(process.env.TRUSTED_PROXY_CIDRS);
const secretFilePath = const secretFilePath =
process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key';
const envMasterKey = process.env.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({ const instance = await createGCoordinatorServer({
dataDir, dataDir,
@ -29,17 +16,7 @@ async function main(): Promise<void> {
host, host,
secretFilePath, secretFilePath,
envMasterKey, envMasterKey,
envDbKey,
trustCloudflare, 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( console.log(

View file

@ -56,67 +56,20 @@ export const LINUX_METRIC_CMD = [
].join('; '); ].join('; ');
export const BSD_METRIC_CMD = [ 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 "===VMSTAT===\\n"; vmstat -H 2>/dev/null || vmstat',
'printf "===NET===\\n"; netstat -ibn 2>/dev/null', 'printf "===NET===\\n"; netstat -ibn 2>/dev/null',
'printf "===DF===\\n"; df -kT 2>/dev/null || df -kP', 'printf "===DF===\\n"; df -kT 2>/dev/null || df -kP',
].join('; '); ].join('; ');
export const MACOS_METRIC_CMD = [ 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 "===VMSTAT===\\n"; vm_stat',
'printf "===TOP===\\n"; top -l 1 -n 0 2>/dev/null | grep -i "CPU usage" || true', '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 "===NET===\\n"; netstat -ibn 2>/dev/null || netstat -ib',
'printf "===DF===\\n"; df -kP', 'printf "===DF===\\n"; df -kP',
].join('; '); ].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<string, string> {
const out = new Map<string, string>();
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<string, string> { function splitSections(stdout: string): Record<string, string> {
const sections: Record<string, string> = {}; const sections: Record<string, string> = {};
let current = ''; let current = '';
@ -184,7 +137,6 @@ function parseDfLines(
if ( if (
fsName === 'devfs' || fsName === 'devfs' ||
fsName === 'map' || fsName === 'map' ||
fsName.startsWith('/dev/loop') ||
!Number.isFinite(totalKb) || !Number.isFinite(totalKb) ||
totalKb <= 0 totalKb <= 0
) { ) {
@ -253,12 +205,9 @@ export function parseLinuxOutput(
Math.floor(Number((sec.UPTIME ?? '0').trim().split(/\s+/)[0]) || 0), Math.floor(Number((sec.UPTIME ?? '0').trim().split(/\s+/)[0]) || 0),
); );
// Network RX/TX prioritizing physical NICs and excluding loopback/virtual bridges // Network RX/TX across non-loopback interfaces
let physRxBytes = 0; let netRxBytes = 0;
let physTxBytes = 0; let netTxBytes = 0;
let hasPhys = false;
let fallbackRxBytes = 0;
let fallbackTxBytes = 0;
for (const line of (sec.NET ?? '').split(/\r?\n/)) { for (const line of (sec.NET ?? '').split(/\r?\n/)) {
const colon = line.indexOf(':'); const colon = line.indexOf(':');
if (colon <= 0) continue; if (colon <= 0) continue;
@ -266,19 +215,10 @@ export function parseLinuxOutput(
if (iface === 'lo' || iface.startsWith('lo:')) continue; if (iface === 'lo' || iface.startsWith('lo:')) continue;
const cols = line.slice(colon + 1).trim().split(/\s+/); const cols = line.slice(colon + 1).trim().split(/\s+/);
if (cols.length >= 9) { if (cols.length >= 9) {
const rx = Number(cols[0]) || 0; netRxBytes += Number(cols[0]) || 0;
const tx = Number(cols[8]) || 0; netTxBytes += Number(cols[8]) || 0;
fallbackRxBytes += rx;
fallbackTxBytes += tx;
if (!isVirtualNic(iface)) {
hasPhys = true;
physRxBytes += rx;
physTxBytes += tx;
}
} }
} }
const netRxBytes = hasPhys ? physRxBytes : fallbackRxBytes;
const netTxBytes = hasPhys ? physTxBytes : fallbackTxBytes;
let netRxBps = 0; let netRxBps = 0;
let netTxBps = 0; let netTxBps = 0;
@ -327,28 +267,25 @@ export function parseBsdOutput(
nowMs = Date.now(), nowMs = Date.now(),
): CollectOutput { ): CollectOutput {
const sec = splitSections(stdout); const sec = splitSections(stdout);
const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [ const sysctlLines = (sec.SYSCTL ?? '')
'hw.physmem', .split(/\r?\n/)
'hw.pagesize', .map((l) => l.trim())
'vm.loadavg', .filter(Boolean);
'kern.boottime',
'kern.cp_time',
]);
const physMemBytes = Number(sysctl.get('hw.physmem')) || 0; const physMemBytes = Number(sysctlLines[0]) || 0;
const pageSize = Number(sysctl.get('hw.pagesize')) || 4096; const pageSize = Number(sysctlLines[1]) || 4096;
const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0'); const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0');
const load1m = round2(Number(loadMatch?.[1] ?? 0)); const load1m = round2(Number(loadMatch?.[1] ?? 0));
let uptimeSec = 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) { if (bootSecMatch) {
uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!)); uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!));
} }
let cpuTotal = 0; let cpuTotal = 0;
let cpuIdle = 0; let cpuIdle = 0;
const cpNums = (sysctl.get('kern.cp_time') ?? '') const cpNums = (sysctlLines[4] ?? '')
.split(/\s+/) .split(/\s+/)
.map((n) => Number(n) || 0); .map((n) => Number(n) || 0);
if (cpNums.length >= 5) { if (cpNums.length >= 5) {
@ -432,20 +369,18 @@ export function parseMacOsOutput(
nowMs = Date.now(), nowMs = Date.now(),
): CollectOutput { ): CollectOutput {
const sec = splitSections(stdout); const sec = splitSections(stdout);
const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [ const sysctlLines = (sec.SYSCTL ?? '')
'hw.memsize', .split(/\r?\n/)
'hw.pagesize', .map((l) => l.trim())
'vm.loadavg', .filter(Boolean);
'kern.boottime',
]);
const memBytes = Number(sysctl.get('hw.memsize')) || 0; const memBytes = Number(sysctlLines[0]) || 0;
const pageSize = Number(sysctl.get('hw.pagesize')) || 4096; const pageSize = Number(sysctlLines[1]) || 4096;
const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0'); const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0');
const load1m = round2(Number(loadMatch?.[1] ?? 0)); const load1m = round2(Number(loadMatch?.[1] ?? 0));
let uptimeSec = 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) { if (bootSecMatch) {
uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!)); uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!));
} }

View file

@ -26,30 +26,25 @@ export interface ServerInspectionResult {
serverId: string; serverId: string;
os: OsType; os: OsType;
collectedAt: number; collectedAt: number;
sort: 'cpu' | 'mem';
processes: ProcessEntry[]; processes: ProcessEntry[];
ports: PortEntry[]; ports: PortEntry[];
thermals: ThermalEntry[]; thermals: ThermalEntry[];
} }
function buildLinuxInspectCmd(sort: 'cpu' | 'mem'): string { const LINUX_INSPECT_CMD = [
const linuxSort = sort === 'mem' ? '-rss' : '-%cpu'; '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',
const bsdFlag = sort === 'mem' ? '-m' : '-r'; 'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true',
return [ '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',
`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`, ].join('; ');
'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 = [ 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 "===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', 'printf "===THERMAL===\\n"; sysctl dev.cpu 2>/dev/null | grep temperature || true',
].join('; '); ].join('; ');
const MACOS_INSPECT_CMD = [ 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 "===PORTS===\\n"; lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null || netstat -an 2>/dev/null || true',
'printf "===THERMAL===\\n"; true', 'printf "===THERMAL===\\n"; true',
].join('; '); ].join('; ');
@ -59,7 +54,6 @@ export function parseInspectorOutput(
os: OsType, os: OsType,
stdout: string, stdout: string,
collectedAt = Date.now(), collectedAt = Date.now(),
sort: 'cpu' | 'mem' = 'cpu',
): ServerInspectionResult { ): ServerInspectionResult {
const sections: Record<string, string[]> = {}; const sections: Record<string, string[]> = {};
let current = ''; 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 // Ports
const ports: PortEntry[] = []; const ports: PortEntry[] = [];
const portLines = sections.PORTS ?? []; const portLines = sections.PORTS ?? [];
@ -110,6 +98,7 @@ export function parseInspectorOutput(
} }
const cols = trimmed.split(/\s+/); const cols = trimmed.split(/\s+/);
if (/^(tcp|udp|tcp4|tcp6|udp4|udp6)/i.test(cols[0] ?? '')) { 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')) { if (cols.length >= 6 && (cols[1] === 'LISTEN' || cols[1] === 'UNCONN')) {
ports.push({ ports.push({
proto: cols[0]!, proto: cols[0]!,
@ -124,12 +113,14 @@ export function parseInspectorOutput(
}); });
} }
} else if (cols.length >= 9 && cols[cols.length - 1] === '(LISTEN)') { } else if (cols.length >= 9 && cols[cols.length - 1] === '(LISTEN)') {
// lsof format
ports.push({ ports.push({
proto: cols[7] ?? 'TCP', proto: cols[7] ?? 'TCP',
localAddress: cols[8] ?? '', localAddress: cols[8] ?? '',
process: `${cols[0]}(${cols[1]})`, process: `${cols[0]}(${cols[1]})`,
}); });
} else if (cols.length >= 6 && /^\d+$/.test(cols[2] ?? '')) { } else if (cols.length >= 6 && /^\d+$/.test(cols[2] ?? '')) {
// sockstat -l: USER COMMAND PID FD PROTO LOCAL FOREIGN
ports.push({ ports.push({
proto: cols[4] ?? 'tcp', proto: cols[4] ?? 'tcp',
localAddress: cols[5] ?? '', localAddress: cols[5] ?? '',
@ -153,7 +144,7 @@ export function parseInspectorOutput(
thermals.push({ zone, tempC }); thermals.push({ zone, tempC });
} }
return { serverId, os, collectedAt, sort, processes, ports, thermals }; return { serverId, os, collectedAt, processes, ports, thermals };
} }
export class ServerInspector { export class ServerInspector {
@ -162,15 +153,11 @@ export class ServerInspector {
private readonly configManager: ConfigManager, private readonly configManager: ConfigManager,
) {} ) {}
async inspect( async inspect(serverId: string): Promise<ServerInspectionResult> {
serverId: string,
opts: { sort?: 'cpu' | 'mem'; useSudo?: boolean } = {},
): Promise<ServerInspectionResult> {
const server = this.configManager.getServer(serverId); const server = this.configManager.getServer(serverId);
if (!server) { if (!server) {
throw new Error(`Unknown server "${serverId}"`); throw new Error(`Unknown server "${serverId}"`);
} }
const sort = opts.sort === 'mem' ? 'mem' : 'cpu';
const runtime = this.sshPool.getState(serverId); const runtime = this.sshPool.getState(serverId);
const os = await detectServerOs(this.sshPool, server, runtime?.osDetected); const os = await detectServerOs(this.sshPool, server, runtime?.osDetected);
const cmd = const cmd =
@ -178,39 +165,9 @@ export class ServerInspector {
? MACOS_INSPECT_CMD ? MACOS_INSPECT_CMD
: os === 'bsd' : os === 'bsd'
? BSD_INSPECT_CMD ? BSD_INSPECT_CMD
: buildLinuxInspectCmd(sort); : LINUX_INSPECT_CMD;
const res = await this.sshPool.exec(serverId, cmd, { const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000 });
timeoutMs: 15_000, return parseInspectorOutput(serverId, os, res.stdout);
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(),
};
} }
} }

View file

@ -6,7 +6,6 @@ import type {
ProbeSample, ProbeSample,
} from '../../shared/ws-protocol.js'; } from '../../shared/ws-protocol.js';
import type { ConfigManager } from '../config/config-manager.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 { VaultService } from '../security/vault.js';
import type { SSHPool } from '../ssh/ssh-pool.js'; import type { SSHPool } from '../ssh/ssh-pool.js';
import { import {
@ -38,7 +37,6 @@ export interface MonitoringTickEvent {
interface ServerTimers { interface ServerTimers {
metricTimer: NodeJS.Timeout | null; metricTimer: NodeJS.Timeout | null;
warmupTimer: NodeJS.Timeout | null; warmupTimer: NodeJS.Timeout | null;
staggerTimer: NodeJS.Timeout | null;
probeTimers: Map<string, NodeJS.Timeout>; probeTimers: Map<string, NodeJS.Timeout>;
pollingMetrics: boolean; pollingMetrics: boolean;
} }
@ -56,8 +54,6 @@ export class MonitoringService {
>(); >();
private maintenanceTimer: NodeJS.Timeout | null = null; private maintenanceTimer: NodeJS.Timeout | null = null;
private stopped = false; private stopped = false;
private inFlightPolls = 0;
private readonly pollQueue: Array<() => void> = [];
constructor( constructor(
private readonly db: Database.Database, private readonly db: Database.Database,
@ -65,7 +61,6 @@ export class MonitoringService {
private readonly vaultService: VaultService, private readonly vaultService: VaultService,
private readonly sshPool: SSHPool, private readonly sshPool: SSHPool,
private readonly probeRunner: ProbeRunner, private readonly probeRunner: ProbeRunner,
private readonly getRuntimeLimits?: () => RuntimeLimits,
) {} ) {}
onTick(listener: (event: MonitoringTickEvent) => void): () => void { onTick(listener: (event: MonitoringTickEvent) => void): () => void {
@ -101,7 +96,6 @@ export class MonitoringService {
for (const timers of this.serverTimers.values()) { for (const timers of this.serverTimers.values()) {
if (timers.metricTimer) clearInterval(timers.metricTimer); if (timers.metricTimer) clearInterval(timers.metricTimer);
if (timers.warmupTimer) clearTimeout(timers.warmupTimer); if (timers.warmupTimer) clearTimeout(timers.warmupTimer);
if (timers.staggerTimer) clearTimeout(timers.staggerTimer);
for (const pt of timers.probeTimers.values()) clearInterval(pt); for (const pt of timers.probeTimers.values()) clearInterval(pt);
} }
this.serverTimers.clear(); this.serverTimers.clear();
@ -110,9 +104,6 @@ export class MonitoringService {
close(): void { close(): void {
this.stopped = true; this.stopped = true;
this.stopAll(); this.stopAll();
while (this.pollQueue.length > 0) {
this.pollQueue.shift()?.();
}
if (this.maintenanceTimer) { if (this.maintenanceTimer) {
clearInterval(this.maintenanceTimer); clearInterval(this.maintenanceTimer);
this.maintenanceTimer = null; this.maintenanceTimer = null;
@ -128,10 +119,10 @@ export class MonitoringService {
return; return;
} }
const enabledServers = this.configManager.listServers().filter((s) => s.enabled); for (const server of this.configManager.listServers()) {
enabledServers.forEach((server, idx) => { if (!server.enabled) continue;
this.scheduleServer(server, idx); this.scheduleServer(server);
}); }
} }
getLatest(serverId: string): LatestServerTelemetry | undefined { getLatest(serverId: string): LatestServerTelemetry | undefined {
@ -147,105 +138,45 @@ export class MonitoringService {
return this.executeMetricPoll(server); return this.executeMetricPoll(server);
} }
async runProbeNow(serverId: string, probeId: string): Promise<ProbeSample> {
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 { runMaintenance(nowMs = Date.now()): void {
const settings = this.configManager.getSettings(); const settings = this.configManager.getSettings();
const rawCutoff = nowMs - settings.rawRetentionHours * 3600_000; const rawCutoff = nowMs - settings.rawRetentionHours * 3600_000;
const rollupCutoff = nowMs - settings.rollupRetentionDays * 86_400_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(() => { const tx = this.db.transaction(() => {
// Stage 1: Aggregate 1h rollups preserving any partial bucket spanning rawCutoff // Aggregate hourly rollups from raw metrics
this.db this.db
.prepare( .prepare(
`INSERT INTO metrics_rollup ( `INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max)
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
)
SELECT SELECT
(r.ts / 3600000) * 3600000 AS bucket_ts, (ts / 3600000) * 3600000 AS bucket_ts,
'1h' AS granularity, '1h' AS granularity,
r.server_id, server_id,
MIN(r.cpu_pct), MIN(cpu_pct),
AVG(r.cpu_pct), AVG(cpu_pct),
MAX(r.cpu_pct), MAX(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), COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0),
MAX(r.load_1m), MAX(load_1m)
AVG(r.net_rx_bps), FROM metrics_raw
AVG(r.net_tx_bps), GROUP BY server_id, (ts / 3600000) * 3600000`,
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`,
) )
.run( .run();
rawCutoff,
rawCutoff,
rawCutoff,
rawCutoff,
rawCutoff,
rawCutoff,
rawCutoff,
rawCutoff,
);
// Stage 2: Aggregate 1d rollups from complete 1h buckets so raw pruning never truncates a day // Aggregate daily rollups
this.db this.db
.prepare( .prepare(
`INSERT INTO metrics_rollup ( `INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max)
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
)
SELECT SELECT
(bucket_ts / 86400000) * 86400000 AS day_ts, (ts / 86400000) * 86400000 AS bucket_ts,
'1d' AS granularity, '1d' AS granularity,
server_id, server_id,
MIN(cpu_min), MIN(cpu_pct),
AVG(cpu_avg), AVG(cpu_pct),
MAX(cpu_max), MAX(cpu_pct),
AVG(mem_avg_pct), COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0),
MAX(load_max), MAX(load_1m)
AVG(net_rx_avg_bps), FROM metrics_raw
AVG(net_tx_avg_bps), GROUP BY server_id, (ts / 86400000) * 86400000`,
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`,
) )
.run(); .run();
@ -253,65 +184,16 @@ export class MonitoringService {
this.db.prepare('DELETE FROM metrics_disks WHERE ts < ?').run(rawCutoff); 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 probe_results WHERE ts < ?').run(rawCutoff);
this.db.prepare('DELETE FROM metrics_rollup WHERE bucket_ts < ?').run(rollupCutoff); 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(); tx();
} }
queryProbeHistory(
serverId: string,
sinceMs = Date.now() - 24 * 3600_000,
limit = 200,
): Array<ProbeSample & { ts: number }> {
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'): { queryHistory(serverId: string, range: MetricRange = '1h'): {
range: MetricRange; range: MetricRange;
granularity: 'raw' | '1h' | '1d'; granularity: 'raw' | '1h' | '1d';
points: Array<Record<string, unknown>>; points: Array<Record<string, unknown>>;
latestDisks: DiskSample[]; latestDisks: DiskSample[];
latestProbes: Array<ProbeSample & { ts: number }>; latestProbes: Array<ProbeSample & { ts: number }>;
probeHistory: Array<ProbeSample & { ts: number }>;
diskHistory: Array<{ ts: number; mountPoint: string; usedPct: number; usedMb: number; totalMb: number }>;
} { } {
const now = Date.now(); const now = Date.now();
const rangeMs: Record<MetricRange, number> = { const rangeMs: Record<MetricRange, number> = {
@ -341,9 +223,7 @@ export class MonitoringService {
points = this.db points = this.db
.prepare( .prepare(
`SELECT bucket_ts AS ts, cpu_min AS cpuMin, cpu_avg AS cpuAvg, cpu_max AS cpuMax, `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, 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
FROM metrics_rollup FROM metrics_rollup
WHERE server_id = ? AND granularity = ? AND bucket_ts >= ? WHERE server_id = ? AND granularity = ? AND bucket_ts >= ?
ORDER BY bucket_ts ASC`, ORDER BY bucket_ts ASC`,
@ -360,22 +240,6 @@ export class MonitoringService {
) )
.all(serverId, serverId) as DiskSample[]; .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 const latestProbes = this.db
.prepare( .prepare(
`SELECT p.probe_id AS probeId, p.ok AS okInt, p.status_code AS statusCode, `SELECT p.probe_id AS probeId, p.ok AS okInt, p.status_code AS statusCode,
@ -398,8 +262,6 @@ export class MonitoringService {
ts: number; ts: number;
}>; }>;
const probeHistory = this.queryProbeHistory(serverId, since, 200);
return { return {
range, range,
granularity, granularity,
@ -413,88 +275,50 @@ export class MonitoringService {
error: r.error ?? undefined, error: r.error ?? undefined,
ts: r.ts, ts: r.ts,
})), })),
probeHistory,
diskHistory,
}; };
} }
private async withPollSlot<T>(fn: () => Promise<T>): Promise<T> { private scheduleServer(server: ServerConfig): void {
const limit = Math.max(1, this.getRuntimeLimits?.().maxConcurrentMetricPolls ?? 4);
if (this.inFlightPolls >= limit) {
await new Promise<void>((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 {
const timers: ServerTimers = { const timers: ServerTimers = {
metricTimer: null, metricTimer: null,
warmupTimer: null, warmupTimer: null,
staggerTimer: null,
probeTimers: new Map(), probeTimers: new Map(),
pollingMetrics: false, pollingMetrics: false,
}; };
this.serverTimers.set(server.id, timers); this.serverTimers.set(server.id, timers);
const limits = this.getRuntimeLimits?.(); // Kick initial poll asynchronously without delaying syncServers()
const staggerMs = const hadDelta = this.deltaStates.has(server.id);
limits?.staggerPolls && index > 0 ? Math.min(index * 120, 2_500) : 0; void this.executeMetricPoll(server).then((ev) => {
if (
const kickInitialAndStartTimer = () => { ev &&
if (this.stopped || this.serverTimers.get(server.id) !== timers) return; !hadDelta &&
!this.stopped &&
const hadDelta = this.deltaStates.has(server.id); this.serverTimers.get(server.id) === timers &&
void this.executeMetricPoll(server).then((ev) => { server.pollIntervalSec >= 3
if ( ) {
ev && const wt = setTimeout(() => {
!hadDelta && timers.warmupTimer = null;
!this.stopped && void this.executeMetricPoll(server);
this.serverTimers.get(server.id) === timers && }, 1000);
server.pollIntervalSec >= 3 wt.unref();
) { timers.warmupTimer = wt;
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);
} }
}; });
if (staggerMs > 0) { timers.metricTimer = setInterval(() => {
const st = setTimeout(() => { void this.executeMetricPoll(server);
timers.staggerTimer = null; }, server.pollIntervalSec * 1000);
kickInitialAndStartTimer(); timers.metricTimer.unref();
}, staggerMs);
st.unref(); for (const probe of server.probes) {
timers.staggerTimer = st; if (!probe.enabled) continue;
} else { void this.executeProbe(server, probe.id);
kickInitialAndStartTimer(); 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; if (timerState) timerState.pollingMetrics = true;
try { try {
return await this.withPollSlot(async () => { const os = await detectServerOs(
if (this.stopped || !this.vaultService.isRuntimeReady) return null; this.sshPool,
server,
this.osCache.get(server.id),
);
this.osCache.set(server.id, os);
const os = await detectServerOs( const collected = await collectServerMetrics(
this.sshPool, this.sshPool,
server, server,
this.osCache.get(server.id), os,
); this.deltaStates.get(server.id),
this.osCache.set(server.id, os); );
this.deltaStates.set(server.id, collected.nextState);
const collected = await collectServerMetrics( this.persistMetricSample(server.id, collected.sample, collected.disks);
this.sshPool,
server,
os,
this.deltaStates.get(server.id),
);
this.deltaStates.set(server.id, collected.nextState);
this.persistMetricSample(server.id, collected.sample, collected.disks); const prevLatest = this.latest.get(server.id) ?? {
serverId: server.id,
const prevLatest = this.latest.get(server.id) ?? { disks: [],
serverId: server.id, probes: {},
disks: [], };
probes: {}, this.latest.set(server.id, {
}; ...prevLatest,
this.latest.set(server.id, { os,
...prevLatest, sample: collected.sample,
os, disks: collected.disks,
sample: collected.sample, lastError: undefined,
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 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) { } catch (err) {
const prevLatest = this.latest.get(server.id) ?? { const prevLatest = this.latest.get(server.id) ?? {
serverId: server.id, serverId: server.id,
@ -577,16 +397,8 @@ export class MonitoringService {
if (this.stopped || !this.vaultService.isRuntimeReady) return; if (this.stopped || !this.vaultService.isRuntimeReady) return;
const probe = server.probes.find((p) => p.id === probeId); const probe = server.probes.find((p) => p.id === probeId);
if (!probe || !probe.enabled) return; if (!probe || !probe.enabled) return;
await this.runAndPersistProbe(server, probe);
}
private async runAndPersistProbe( const sample = await this.probeRunner.runProbe(server.id, probe);
server: ServerConfig,
probe: ServerConfig['probes'][number],
): Promise<ProbeSample> {
const sample = await this.withPollSlot(() =>
this.probeRunner.runProbe(server.id, probe),
);
const ts = Date.now(); const ts = Date.now();
this.db this.db
.prepare( .prepare(
@ -618,7 +430,6 @@ export class MonitoringService {
// Isolate probe listener errors // Isolate probe listener errors
} }
} }
return sample;
} }
private hydrateLatestFromDb(): void { private hydrateLatestFromDb(): void {

View file

@ -3,93 +3,36 @@ import tls from 'node:tls';
import type { Duplex } from 'node:stream'; import type { Duplex } from 'node:stream';
import type { ServerProbe } from '../../shared/schemas/server.schema.js'; import type { ServerProbe } from '../../shared/schemas/server.schema.js';
import type { ProbeSample } from '../../shared/ws-protocol.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'; 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<string> {
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( function readHttpFromStream(
stream: Duplex, stream: Duplex,
url: URL, url: URL,
timeoutMs: number, timeoutMs: number,
tlsOpts: { rejectUnauthorized?: boolean } = {}, ): Promise<{ statusCode: number; body: string }> {
): Promise<{ statusCode: number; body: string; certExpiryDays?: number }> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let settled = false; let settled = false;
let certExpiryDays: number | undefined;
const timer = setTimeout(() => { const timer = setTimeout(() => {
if (settled) return; if (settled) return;
settled = true; settled = true;
stream.destroy(); stream.destroy();
reject(new Error(`HTTP probe timed out after ${timeoutMs}ms`)); reject(new Error(`Target HTTP probe timed out after ${timeoutMs}ms`));
}, timeoutMs); }, timeoutMs);
const servername = net.isIP(url.hostname) ? undefined : url.hostname;
const transport: Duplex = const transport: Duplex =
url.protocol === 'https:' url.protocol === 'https:'
? tls.connect({ ? tls.connect({ socket: stream, servername: url.hostname })
socket: stream,
servername,
rejectUnauthorized: tlsOpts.rejectUnauthorized ?? true,
})
: stream; : stream;
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
let total = 0; let total = 0;
const maxBytes = 256 * 1024;
const done = (err?: Error) => { const done = (err?: Error) => {
if (settled) return; if (settled) return;
settled = true; settled = true;
clearTimeout(timer); clearTimeout(timer);
transport.destroy(); transport.destroy();
stream.destroy();
if (err) { if (err) {
reject(err); reject(err);
return; return;
@ -97,53 +40,36 @@ function readHttpFromStream(
const raw = Buffer.concat(chunks).toString('utf8'); const raw = Buffer.concat(chunks).toString('utf8');
const headerEnd = raw.indexOf('\r\n\r\n'); const headerEnd = raw.indexOf('\r\n\r\n');
const head = headerEnd >= 0 ? raw.slice(0, headerEnd) : raw; 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 statusLine = head.split('\r\n')[0] ?? '';
const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(statusLine); const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(statusLine);
if (!m) { if (!m) {
reject(new Error(`Invalid HTTP response line: ${statusLine}`)); reject(new Error(`Invalid HTTP response line: ${statusLine}`));
return; return;
} }
resolve({ resolve({ statusCode: Number(m[1]), body });
statusCode: Number(m[1]),
body: decodeChunkedIfNeeded(head, rawBody),
certExpiryDays,
});
}; };
transport.on('data', (chunk: Buffer) => { transport.on('data', (chunk: Buffer) => {
if (total < MAX_PROBE_BODY_BYTES) { if (total < maxBytes) {
chunks.push(chunk.subarray(0, MAX_PROBE_BODY_BYTES - total)); chunks.push(chunk.subarray(0, maxBytes - total));
total += chunk.length; total += chunk.length;
} else {
transport.destroy();
} }
}); });
transport.once('end', () => done()); transport.once('end', () => done());
transport.once('close', () => done()); transport.once('close', () => done());
transport.once('error', (err) => done(err)); transport.once('error', (err) => done(err));
if (transport !== stream) {
stream.once('error', (err) => done(err));
}
const pathAndQuery = `${url.pathname || '/'}${url.search || ''}`; const pathAndQuery = `${url.pathname || '/'}${url.search || ''}`;
const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname; const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname;
const reqText = const reqText =
`GET ${pathAndQuery} HTTP/1.1\r\n` + `GET ${pathAndQuery} HTTP/1.1\r\n` +
`Host: ${hostHeader}\r\n` + `Host: ${hostHeader}\r\n` +
`User-Agent: GCoordinator-Probe/1.1\r\n` + `User-Agent: GCoordinator-Probe/1.0\r\n` +
`Accept-Encoding: identity\r\n` +
`Connection: close\r\n\r\n`; `Connection: close\r\n\r\n`;
if (url.protocol === 'https:') { if (url.protocol === 'https:') {
(transport as tls.TLSSocket).once('secureConnect', () => { (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); transport.write(reqText);
}); });
} else { } else {
@ -153,26 +79,16 @@ function readHttpFromStream(
} }
export class ProbeRunner { export class ProbeRunner {
constructor( constructor(private readonly sshPool: SSHPool) {}
private readonly sshPool: SSHPool,
private readonly configManager?: ConfigManager,
) {}
runSingleProbe(serverId: string, probe: ServerProbe): Promise<ProbeSample> {
return this.runProbe(serverId, probe);
}
async runProbe(serverId: string, probe: ServerProbe): Promise<ProbeSample> { async runProbe(serverId: string, probe: ServerProbe): Promise<ProbeSample> {
const started = Date.now(); const started = Date.now();
const allowedCidrs = this.configManager?.getSettings().security.egressAllowedCidrs ?? [];
try { try {
if (probe.type === 'tcp') { if (probe.type === 'tcp') {
if (probe.from === 'hub') { if (probe.from === 'hub') {
const ips = await resolveAllowedEgressIps(probe.host, allowedCidrs);
await new Promise<void>((resolve, reject) => { await new Promise<void>((resolve, reject) => {
const sock = net.createConnection({ const sock = net.createConnection({
host: ips[0]!, host: probe.host,
port: probe.port, port: probe.port,
}); });
const timer = setTimeout(() => { const timer = setTimeout(() => {
@ -209,35 +125,19 @@ export class ProbeRunner {
} }
// HTTP(S) probe // HTTP(S) probe
const parsedUrl = new URL(probe.url);
let statusCode: number; let statusCode: number;
let body: string; let body: string;
let certExpiryDays: number | undefined;
if (probe.from === 'hub') { if (probe.from === 'hub') {
if ( const res = await fetch(probe.url, {
parsedUrl.protocol === 'https:' && method: 'GET',
(probe.tlsRejectUnauthorized === false || probe.tlsCheckExpiryDays !== undefined) redirect: 'manual',
) { signal: AbortSignal.timeout(probe.timeoutMs),
const ips = await resolveAllowedEgressIps(parsedUrl.hostname, allowedCidrs); });
const port = parsedUrl.port ? Number(parsedUrl.port) : 443; statusCode = res.status;
const sock = net.createConnection({ host: ips[0]!, port }); body = await res.text();
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);
}
} else { } else {
const parsedUrl = new URL(probe.url);
const port = parsedUrl.port const port = parsedUrl.port
? Number(parsedUrl.port) ? Number(parsedUrl.port)
: parsedUrl.protocol === 'https:' : parsedUrl.protocol === 'https:'
@ -249,40 +149,24 @@ export class ProbeRunner {
port, port,
probe.timeoutMs, probe.timeoutMs,
); );
const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs, { const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs);
rejectUnauthorized: probe.tlsRejectUnauthorized,
});
statusCode = resp.statusCode; statusCode = resp.statusCode;
body = resp.body; body = resp.body;
certExpiryDays = resp.certExpiryDays;
} }
const statusOk = statusCode === probe.expectedStatus; const statusOk = statusCode === probe.expectedStatus;
const bodyOk = probe.bodyIncludes ? body.includes(probe.bodyIncludes) : true; const bodyOk = probe.bodyIncludes ? body.includes(probe.bodyIncludes) : true;
const certOk = const ok = statusOk && bodyOk;
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)`;
}
}
return { return {
probeId: probe.id, probeId: probe.id,
ok, ok,
statusCode, statusCode,
latencyMs: Date.now() - started, latencyMs: Date.now() - started,
certExpiryDays, error: ok
error, ? undefined
: !statusOk
? `Expected HTTP ${probe.expectedStatus}, got ${statusCode}`
: `Response body missing substring "${probe.bodyIncludes}"`,
}; };
} catch (err) { } catch (err) {
return { return {

View file

@ -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, string>): 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`);
};
}

View file

@ -20,28 +20,6 @@ export interface AuditLogRecord {
details: string | null; 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 { export class AuditService {
private readonly insertStmt; private readonly insertStmt;
@ -71,143 +49,33 @@ export class AuditService {
); );
} }
private buildWhereClause(options: AuditListOptions): { sql: string; params: Array<string | number> } { list(options: { limit?: number; offset?: number; action?: string } = {}): {
const clauses: string[] = [];
const params: Array<string | number> = [];
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 = {}): {
total: number; total: number;
items: AuditLogRecord[]; items: AuditLogRecord[];
} { } {
const limit = Math.max(1, Math.min(200, options.limit ?? 50)); const limit = Math.max(1, Math.min(200, options.limit ?? 50));
const offset = Math.max(0, options.offset ?? 0); const offset = Math.max(0, options.offset ?? 0);
const where = this.buildWhereClause(options);
const countRow = this.db if (options.action) {
.prepare(`SELECT COUNT(*) AS cnt FROM audit_log ${where.sql}`) const countRow = this.db
.get(...where.params) as { cnt: number }; .prepare('SELECT COUNT(*) AS cnt FROM audit_log WHERE action = ?')
.get(options.action) as { cnt: number };
const items = this.db const items = this.db
.prepare( .prepare(
`SELECT id, ts, action, actor_ip, session_id_hash, target, status, details '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 ?',
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,
}),
) )
.join('\n')}\n`; .all(options.action, limit, offset) as AuditLogRecord[];
return { total: countRow.cnt, items };
} }
const lines = [ const countRow = this.db
'id,ts,isoTime,action,status,actorIp,target,sessionIdHash,details', .prepare('SELECT COUNT(*) AS cnt FROM audit_log')
...rows.map((r) => .get() as { cnt: number };
[ const items = this.db
String(r.id), .prepare(
String(r.ts), 'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?',
sanitizeCsvCell(new Date(r.ts).toISOString()), )
sanitizeCsvCell(r.action), .all(limit, offset) as AuditLogRecord[];
sanitizeCsvCell(r.status), return { total: countRow.cnt, items };
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;
} }
} }

View file

@ -1,6 +1,4 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { import {
generateAuthenticationOptions, generateAuthenticationOptions,
generateRegistrationOptions, generateRegistrationOptions,
@ -19,120 +17,18 @@ import {
type SecuritySettings, type SecuritySettings,
type StepUpPolicy, type StepUpPolicy,
} from '../../shared/schemas/settings.schema.js'; } from '../../shared/schemas/settings.schema.js';
import type { RuntimeLimits } from '../config/runtime-limits.js';
import type { EmergencyRecoveryService, SavedTotpEntry } from './recovery-store.js'; import type { EmergencyRecoveryService, SavedTotpEntry } from './recovery-store.js';
import type { VaultService } from './vault.js'; import type { VaultService } from './vault.js';
const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const BOOTSTRAP_TTL_MS = 15 * 60 * 1000; const BOOTSTRAP_TTL_MS = 15 * 60 * 1000;
const WEBAUTHN_TTL_MS = 5 * 60 * 1000; const WEBAUTHN_TTL_MS = 5 * 60 * 1000;
const SESSION_REAPER_MS = 5 * 60 * 1000;
const TOTP_PERIOD_SEC = 30; const TOTP_PERIOD_SEC = 30;
const DEFAULT_SECURITY = SecuritySettingsSchema.parse({}); const DEFAULT_SECURITY = SecuritySettingsSchema.parse({});
export const SESSION_COOKIE_NAME = 'gcoord_sid'; 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 { export interface AuthSession {
idHash: string; idHash: string;
csrfTokenHash: string; csrfTokenHash: string;
@ -200,16 +96,8 @@ export type StepUpInput =
export interface AuthServiceOptions { export interface AuthServiceOptions {
getSecuritySettings?: () => SecuritySettings; getSecuritySettings?: () => SecuritySettings;
getRuntimeLimits?: () => RuntimeLimits;
recoveryStore?: EmergencyRecoveryService; recoveryStore?: EmergencyRecoveryService;
vaultService?: VaultService; vaultService?: VaultService;
dataDir?: string;
envDbKey?: string;
onSecurityEvent?: (event: {
type: string;
ip?: string;
details?: Record<string, unknown>;
}) => void;
} }
interface AdminRow { interface AdminRow {
@ -232,10 +120,8 @@ interface TotpRow {
id: string; id: string;
label: string; label: string;
secret_base32: string; secret_base32: string;
secret_enc: string | null;
last_login_step: number | null; last_login_step: number | null;
last_stepup_step: number | null; last_stepup_step: number | null;
last_used_step: number | null;
created_at: number; created_at: number;
} }
@ -293,8 +179,6 @@ function computeElevatedUntil(
return fromLogin ? null : nowMs + 60_000; return fromLogin ? null : nowMs + 60_000;
case '5m': case '5m':
return nowMs + 5 * 60 * 1000; return nowMs + 5 * 60 * 1000;
case '15m':
return nowMs + 15 * 60 * 1000;
case '1h': case '1h':
return nowMs + 60 * 60 * 1000; return nowMs + 60 * 60 * 1000;
case '24h': case '24h':
@ -305,21 +189,13 @@ function computeElevatedUntil(
} }
export class AuthService { 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< private readonly pendingEnrollments = new Map<
string, string,
{ label: string; secretBase32: string; createdAt: number } { label: string; secretBase32: string; createdAt: number }
>(); >();
private readonly pendingWebAuthn = new Map<string, PendingWebAuthnChallenge>(); private readonly pendingWebAuthn = new Map<string, PendingWebAuthnChallenge>();
private readonly sessionRevokedListeners = new Set<(idHashes: string[]) => void>();
private readonly getSecurity: () => SecuritySettings; 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 recoveryStore?: EmergencyRecoveryService;
private vaultService?: VaultService; private vaultService?: VaultService;
@ -328,169 +204,8 @@ export class AuthService {
options: AuthServiceOptions = {}, options: AuthServiceOptions = {},
) { ) {
this.getSecurity = options.getSecuritySettings ?? (() => DEFAULT_SECURITY); this.getSecurity = options.getSecuritySettings ?? (() => DEFAULT_SECURITY);
this.getRuntimeLimits = options.getRuntimeLimits;
this.onSecurityEvent = options.onSecurityEvent;
this.recoveryStore = options.recoveryStore; this.recoveryStore = options.recoveryStore;
this.vaultService = options.vaultService; 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<string, unknown>): 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<T>(task: (memoryCost: number) => Promise<T>): Promise<T> {
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<void>((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<string> {
return this.runArgon2((memoryCost) =>
argon2.hash(password, {
type: argon2.argon2id,
memoryCost,
timeCost: 3,
parallelism: 1,
}),
);
}
private verifyPasswordHash(hash: string, candidate: string): Promise<boolean> {
return this.runArgon2(() => argon2.verify(hash, candidate).catch(() => false));
}
private async verifyDummyPassword(candidate: string): Promise<void> {
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( attachRecoveryDependencies(
@ -542,11 +257,9 @@ export class AuthService {
} }
async beginBootstrap(username = 'admin'): Promise<{ async beginBootstrap(username = 'admin'): Promise<{
bootstrapToken: string;
secretBase32: string; secretBase32: string;
otpauthUri: string; otpauthUri: string;
qrSvg: string; qrSvg: string;
qrDataUri: string;
}> { }> {
if (this.isBootstrapped()) { if (this.isBootstrapped()) {
throw new Error('Admin account is already configured'); throw new Error('Admin account is already configured');
@ -559,24 +272,17 @@ export class AuthService {
const secret = new OTPAuth.Secret({ size: 20 }); const secret = new OTPAuth.Secret({ size: 20 });
this.pendingBootstrap = { this.pendingBootstrap = {
secretBase32: secret.base32, secretBase32: secret.base32,
token: crypto.randomBytes(24).toString('base64url'),
createdAt: Date.now(), createdAt: Date.now(),
}; };
} }
const cleanUser = username.trim().slice(0, 64) || 'admin'; const totp = buildTotp(this.pendingBootstrap.secretBase32, username);
const totp = buildTotp(this.pendingBootstrap.secretBase32, cleanUser);
const otpauthUri = totp.toString(); const otpauthUri = totp.toString();
const [qrSvg, qrDataUri] = await Promise.all([ const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 });
QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }),
QRCode.toDataURL(otpauthUri, { margin: 1, width: 220 }),
]);
return { return {
bootstrapToken: this.pendingBootstrap.token,
secretBase32: this.pendingBootstrap.secretBase32, secretBase32: this.pendingBootstrap.secretBase32,
otpauthUri, otpauthUri,
qrSvg, qrSvg,
qrDataUri,
}; };
} }
@ -585,7 +291,6 @@ export class AuthService {
password: string; password: string;
totpCode: string; totpCode: string;
secretBase32?: string; secretBase32?: string;
bootstrapToken?: string;
ip: string; ip: string;
userAgent: string; userAgent: string;
initialSafeMode?: boolean; initialSafeMode?: boolean;
@ -606,30 +311,11 @@ export class AuthService {
throw new Error('Password must be at least 10 characters'); throw new Error('Password must be at least 10 characters');
} }
if ( const secretBase32 = params.secretBase32 ?? this.pendingBootstrap?.secretBase32;
!this.pendingBootstrap || if (!secretBase32) {
Date.now() - this.pendingBootstrap.createdAt > BOOTSTRAP_TTL_MS
) {
this.pendingBootstrap = null;
throw new Error('Bootstrap enrollment session expired; reload setup'); 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 nowMs = Date.now();
const totp = buildTotp(secretBase32, username); const totp = buildTotp(secretBase32, username);
const delta = totp.validate({ const delta = totp.validate({
@ -642,8 +328,12 @@ export class AuthService {
} }
const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta;
const passwordHash = await this.hashPassword(params.password); const passwordHash = await argon2.hash(params.password, {
const secretEnc = encryptTotpSecret(this.dbKey, 'totp-primary', secretBase32); type: argon2.argon2id,
memoryCost: 65536,
timeCost: 3,
parallelism: 1,
});
const recoveryCodes: string[] = []; const recoveryCodes: string[] = [];
for (let i = 0; i < 8; i++) { for (let i = 0; i < 8; i++) {
@ -654,9 +344,9 @@ export class AuthService {
this.db this.db
.prepare( .prepare(
`INSERT INTO admin_users (id, username, password_hash, totp_secret, last_login_totp_step, last_stepup_totp_step, created_at, updated_at) `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 this.db
.prepare( .prepare(
@ -666,10 +356,10 @@ export class AuthService {
this.db this.db
.prepare( .prepare(
`INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) `INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at)
VALUES (?, ?, '', ?, ?, ?, ?, ?)`, 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( const insertRec = this.db.prepare(
'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)', 'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)',
@ -682,6 +372,12 @@ export class AuthService {
this.pendingBootstrap = null; this.pendingBootstrap = null;
this.syncRecovery({ this.syncRecovery({
passwordPlaintextUpdate: {
id: 'pw-primary',
label: 'Primary Password',
password: params.password,
createdAt: nowMs,
},
newRecoveryCodes: recoveryCodes, newRecoveryCodes: recoveryCodes,
snapshotReason: 'bootstrap', snapshotReason: 'bootstrap',
}); });
@ -707,35 +403,28 @@ export class AuthService {
const admin = this.db const admin = this.db
.prepare('SELECT * FROM admin_users WHERE id = 1') .prepare('SELECT * FROM admin_users WHERE id = 1')
.get() as AdminRow | undefined; .get() as AdminRow | undefined;
const suppliedPasswords = ( if (!admin) return null;
params.passwords ?? (params.password !== undefined ? [params.password] : [])
)
.filter((p) => p.length > 0)
.slice(0, 16);
const cleanUser = params.username?.trim() ?? '';
if ( if (params.username && params.username.trim() !== admin.username) {
!admin ||
!cleanUser ||
cleanUser.length > 64 ||
suppliedPasswords.length === 0 ||
!timingSafeStringEqual(cleanUser, admin.username)
) {
await this.verifyDummyPassword(suppliedPasswords[0] ?? 'dummy');
return null; return null;
} }
const sec = this.getSecurity(); 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); const pwOk = await this.verifyPasswords(suppliedPasswords, sec.passwordMode);
if (!pwOk) return null; if (!pwOk) return null;
if (sec.requireTotpOnLogin) { const totpRows = this.listTotpRows();
if (sec.requireTotpOnLogin && totpRows.length > 0) {
const suppliedCodes = ( const suppliedCodes = (
params.codes ?? (params.code !== undefined ? [params.code] : []) params.codes ?? (params.code !== undefined ? [params.code] : [])
) )
.map((c) => c.trim()) .map((c) => c.trim())
.filter((c) => c.length > 0) .filter((c) => c.length > 0);
.slice(0, 16);
if (suppliedCodes.length === 0) return null; if (suppliedCodes.length === 0) return null;
@ -744,7 +433,6 @@ export class AuthService {
sec.totpMode, sec.totpMode,
'login', 'login',
admin.username, admin.username,
params.ip,
); );
if (!mfaOk) return null; if (!mfaOk) return null;
} }
@ -758,11 +446,7 @@ export class AuthService {
getSessionByToken(sessionToken: string | undefined): AuthSession | null { getSessionByToken(sessionToken: string | undefined): AuthSession | null {
if (!sessionToken || sessionToken.length < 16) return null; if (!sessionToken || sessionToken.length < 16) return null;
return this.getSessionByHash(sha256Hex(sessionToken)); const idHash = sha256Hex(sessionToken);
}
getSessionByHash(idHash: string | undefined): AuthSession | null {
if (!idHash || idHash.length < 16) return null;
const row = this.db const row = this.db
.prepare('SELECT * FROM sessions WHERE id_hash = ?') .prepare('SELECT * FROM sessions WHERE id_hash = ?')
.get(idHash) as SessionRow | undefined; .get(idHash) as SessionRow | undefined;
@ -771,24 +455,10 @@ export class AuthService {
const now = Date.now(); const now = Date.now();
if (row.expires_at <= now) { if (row.expires_at <= now) {
this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash);
this.notifySessionsRevoked([idHash]);
return null; return null;
} }
const sec = this.getSecurity(); if (now - row.last_seen_at > 60_000) {
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) {
this.db this.db
.prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?') .prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?')
.run(now, idHash); .run(now, idHash);
@ -856,17 +526,20 @@ export class AuthService {
} }
if (sec.stepUpMethod === 'totp' || sec.stepUpMethod === 'both') { if (sec.stepUpMethod === 'totp' || sec.stepUpMethod === 'both') {
if (suppliedCodes.length === 0) { const totpRows = this.listTotpRows();
return { ok: false, reason: 'invalid_totp' }; if (totpRows.length > 0) {
} if (suppliedCodes.length === 0) {
const totpResult = this.verifyTotpRows( return { ok: false, reason: 'invalid_totp' };
suppliedCodes, }
sec.totpMode, const totpResult = this.verifyTotpRows(
'stepup', suppliedCodes,
admin.username, sec.totpMode,
); 'stepup',
if (!totpResult.ok) { admin.username,
return { ok: false, reason: totpResult.reason }; );
if (!totpResult.ok) {
return { ok: false, reason: totpResult.reason };
}
} }
} }
@ -1011,7 +684,7 @@ export class AuthService {
})), })),
authenticatorSelection: { authenticatorSelection: {
residentKey: 'preferred', residentKey: 'preferred',
userVerification: 'required', userVerification: 'preferred',
}, },
}); });
@ -1042,7 +715,7 @@ export class AuthService {
expectedChallenge: pending.challenge, expectedChallenge: pending.challenge,
expectedOrigin: pending.expectedOrigin, expectedOrigin: pending.expectedOrigin,
expectedRPID: pending.rpID, expectedRPID: pending.rpID,
requireUserVerification: true, requireUserVerification: false,
}); });
if (!verification.verified || !verification.registrationInfo) { if (!verification.verified || !verification.registrationInfo) {
@ -1107,7 +780,7 @@ export class AuthService {
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
: undefined, : undefined,
})), })),
userVerification: 'required', userVerification: 'preferred',
}); });
const challengeId = crypto.randomBytes(16).toString('hex'); const challengeId = crypto.randomBytes(16).toString('hex');
@ -1133,14 +806,6 @@ export class AuthService {
if (!this.isBootstrapped()) return null; if (!this.isBootstrapped()) return null;
const pending = this.consumeWebAuthnChallenge(params.challengeId, 'login'); const pending = this.consumeWebAuthnChallenge(params.challengeId, 'login');
if (!pending) return null; 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 const row = this.db
.prepare('SELECT * FROM webauthn_credentials WHERE id = ?') .prepare('SELECT * FROM webauthn_credentials WHERE id = ?')
@ -1161,7 +826,7 @@ export class AuthService {
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
: undefined, : undefined,
}, },
requireUserVerification: true, requireUserVerification: false,
}); });
if (!verification.verified) return null; if (!verification.verified) return null;
@ -1196,22 +861,11 @@ export class AuthService {
if (session.safe_mode === 1) { if (session.safe_mode === 1) {
return { ok: false, reason: 'safe_mode_active' }; 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'); const pending = this.consumeWebAuthnChallenge(params.challengeId, 'stepup');
if (!pending || pending.sessionIdHash !== params.idHash) { if (!pending || pending.sessionIdHash !== params.idHash) {
return { ok: false, reason: 'invalid_challenge' }; 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 const row = this.db
.prepare('SELECT * FROM webauthn_credentials WHERE id = ?') .prepare('SELECT * FROM webauthn_credentials WHERE id = ?')
@ -1232,7 +886,7 @@ export class AuthService {
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
: undefined, : undefined,
}, },
requireUserVerification: true, requireUserVerification: false,
}); });
if (!verification.verified) { if (!verification.verified) {
return { ok: false, reason: 'invalid_assertion' }; return { ok: false, reason: 'invalid_assertion' };
@ -1272,7 +926,12 @@ export class AuthService {
const id = `pw-${crypto.randomBytes(4).toString('hex')}`; const id = `pw-${crypto.randomBytes(4).toString('hex')}`;
const createdAt = Date.now(); 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 this.db
.prepare( .prepare(
@ -1281,6 +940,12 @@ export class AuthService {
.run(id, cleanLabel, hash, createdAt); .run(id, cleanLabel, hash, createdAt);
this.syncRecovery({ this.syncRecovery({
passwordPlaintextUpdate: {
id,
label: cleanLabel,
password,
createdAt,
},
snapshotReason: 'password-added', snapshotReason: 'password-added',
}); });
@ -1307,7 +972,6 @@ export class AuthService {
secretBase32: string; secretBase32: string;
otpauthUri: string; otpauthUri: string;
qrSvg: string; qrSvg: string;
qrDataUri: string;
}> { }> {
const cleanLabel = label.trim(); const cleanLabel = label.trim();
if (cleanLabel.length < 1 || cleanLabel.length > 64) { if (cleanLabel.length < 1 || cleanLabel.length > 64) {
@ -1331,17 +995,13 @@ export class AuthService {
const username = this.getAdminUsername() ?? 'admin'; const username = this.getAdminUsername() ?? 'admin';
const totp = buildTotp(secret.base32, `${username} (${cleanLabel})`); const totp = buildTotp(secret.base32, `${username} (${cleanLabel})`);
const otpauthUri = totp.toString(); const otpauthUri = totp.toString();
const [qrSvg, qrDataUri] = await Promise.all([ const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 });
QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }),
QRCode.toDataURL(otpauthUri, { margin: 1, width: 220 }),
]);
return { return {
enrollmentId, enrollmentId,
label: cleanLabel, label: cleanLabel,
secretBase32: secret.base32, secretBase32: secret.base32,
otpauthUri, otpauthUri,
qrSvg, qrSvg,
qrDataUri,
}; };
} }
@ -1369,13 +1029,12 @@ export class AuthService {
const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta;
const id = `totp-${crypto.randomBytes(4).toString('hex')}`; const id = `totp-${crypto.randomBytes(4).toString('hex')}`;
const secretEnc = encryptTotpSecret(this.dbKey, id, pending.secretBase32);
this.db this.db
.prepare( .prepare(
`INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) `INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at)
VALUES (?, ?, '', ?, ?, ?, ?, ?)`, VALUES (?, ?, ?, ?, ?, ?)`,
) )
.run(id, pending.label, secretEnc, matchedStep, matchedStep, matchedStep, nowMs); .run(id, pending.label, pending.secretBase32, matchedStep, matchedStep, nowMs);
this.pendingEnrollments.delete(enrollmentId); this.pendingEnrollments.delete(enrollmentId);
this.syncRecovery({ snapshotReason: 'totp-added' }); this.syncRecovery({ snapshotReason: 'totp-added' });
@ -1429,6 +1088,12 @@ export class AuthService {
syncRecovery( syncRecovery(
overrides: { overrides: {
passwordPlaintextUpdate?: {
id: string;
label: string;
password: string;
createdAt?: number;
};
removedPasswordId?: string; removedPasswordId?: string;
newRecoveryCodes?: string[]; newRecoveryCodes?: string[];
snapshotReason?: 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') .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 }>; .all() as Array<{ id: string; label: string; createdAt: number }>;
const totpRows = this.listTotpRows(); const totpRows = this.listTotpRows();
const totps: SavedTotpEntry[] = totpRows.map((t) => { const totps: SavedTotpEntry[] = totpRows.map((t) => ({
const secretBase32 = this.getTotpSecret(t); id: t.id,
return { label: t.label,
id: t.id, secretBase32: t.secret_base32,
label: t.label, otpauthUri: buildTotp(
secretBase32, t.secret_base32,
otpauthUri: buildTotp( username ? `${username} (${t.label})` : t.label,
secretBase32, ).toString(),
username ? `${username} (${t.label})` : t.label, createdAt: new Date(t.created_at).toISOString(),
).toString(), }));
createdAt: new Date(t.created_at).toISOString(),
};
});
this.recoveryStore.syncState({ this.recoveryStore.syncState({
enabled: sec.enableEmergencySecretsBackup, enabled: sec.enableEmergencySecretsBackup,
@ -1488,43 +1150,24 @@ export class AuthService {
} }
revokeSessionByHash(idHash: string): void { revokeSessionByHash(idHash: string): void {
const res = this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash);
if (res.changes > 0) {
this.notifySessionsRevoked([idHash]);
}
} }
revokeSessionByPrefix(prefix: string): number { revokeSessionByPrefix(prefix: string): number {
if (!/^[0-9a-f]{8,64}$/i.test(prefix)) return 0; 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 const result = this.db
.prepare('DELETE FROM sessions WHERE id_hash LIKE ?') .prepare('DELETE FROM sessions WHERE id_hash LIKE ?')
.run(`${prefix}%`); .run(`${prefix}%`);
if (result.changes > 0) {
this.notifySessionsRevoked(rows.map((r) => r.id_hash));
}
return result.changes; return result.changes;
} }
revokeAllSessions(exceptIdHash?: string): number { revokeAllSessions(exceptIdHash?: string): number {
const rows = ( if (exceptIdHash) {
exceptIdHash return this.db
? this.db .prepare('DELETE FROM sessions WHERE id_hash != ?')
.prepare('SELECT id_hash FROM sessions WHERE id_hash != ?') .run(exceptIdHash).changes;
.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));
} }
return changes; return this.db.prepare('DELETE FROM sessions').run().changes;
} }
private listTotpRows(): TotpRow[] { private listTotpRows(): TotpRow[] {
@ -1545,7 +1188,7 @@ export class AuthService {
if (mode === 'any') { if (mode === 'any') {
for (const row of rows) { for (const row of rows) {
for (const candidate of suppliedPasswords) { for (const candidate of suppliedPasswords) {
if (await this.verifyPasswordHash(row.password_hash, candidate)) { if (await argon2.verify(row.password_hash, candidate)) {
return true; return true;
} }
} }
@ -1557,7 +1200,7 @@ export class AuthService {
for (const row of rows) { for (const row of rows) {
let rowMatched = false; let rowMatched = false;
for (const candidate of suppliedPasswords) { for (const candidate of suppliedPasswords) {
if (await this.verifyPasswordHash(row.password_hash, candidate)) { if (await argon2.verify(row.password_hash, candidate)) {
rowMatched = true; rowMatched = true;
break; break;
} }
@ -1572,9 +1215,8 @@ export class AuthService {
mode: 'any' | 'all', mode: 'any' | 'all',
purpose: 'login' | 'stepup', purpose: 'login' | 'stepup',
username: string, username: string,
ip?: string,
): boolean { ): boolean {
const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username, ip); const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username);
if (totpRes.ok) return true; if (totpRes.ok) return true;
// In 'any' mode, a single-use recovery code may replace TOTP // 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', 'UPDATE recovery_codes SET used_at = ? WHERE code_hash = ? AND used_at IS NULL',
) )
.run(Date.now(), sha256Hex(normalized)); .run(Date.now(), sha256Hex(normalized));
if (updated.changes === 1) { if (updated.changes === 1) return true;
this.emitSecurityEvent('auth.recovery_code_used', ip, { username });
return true;
}
} }
} }
return false; 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( private verifyTotpRows(
suppliedCodes: string[], suppliedCodes: string[],
mode: 'any' | 'all', mode: 'any' | 'all',
purpose: 'login' | 'stepup', purpose: 'login' | 'stepup',
username: string, username: string,
ip?: string,
): { ok: true } | { ok: false; reason: string } { ): { ok: true } | { ok: false; reason: string } {
const rows = this.listTotpRows(); const rows = this.listTotpRows();
if (rows.length === 0) { if (rows.length === 0) return { ok: true };
return { ok: false, reason: 'totp_not_configured' };
}
const numericCodes = suppliedCodes.filter((c) => /^\d{6}$/.test(c)); const numericCodes = suppliedCodes.filter((c) => /^\d{6}$/.test(c));
if (numericCodes.length === 0) return { ok: false, reason: 'invalid_totp' }; if (numericCodes.length === 0) return { ok: false, reason: 'invalid_totp' };
const nowMs = Date.now(); const nowMs = Date.now();
const stepCol = purpose === 'login' ? 'last_login_step' : 'last_stepup_step';
if (mode === 'any') { if (mode === 'any') {
let sawReplay = false; let sawReplay = false;
for (const row of rows) { for (const row of rows) {
const secret = this.getTotpSecret(row); const totp = buildTotp(row.secret_base32, username);
const totp = buildTotp(secret, username); const lastStep =
const lastStep = this.getRowLastUsedStep(row); purpose === 'login' ? row.last_login_step : row.last_stepup_step;
for (const code of numericCodes) { for (const code of numericCodes) {
const delta = totp.validate({ token: code, window: 1, timestamp: nowMs }); const delta = totp.validate({ token: code, window: 1, timestamp: nowMs });
if (delta === null) continue; if (delta === null) continue;
@ -1639,25 +1266,20 @@ export class AuthService {
continue; continue;
} }
this.db this.db
.prepare( .prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`)
'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?', .run(matchedStep, row.id);
)
.run(matchedStep, matchedStep, matchedStep, row.id);
return { ok: true }; return { ok: true };
} }
} }
if (sawReplay) {
this.emitSecurityEvent('auth.totp_replay', ip, { purpose });
}
return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' };
} }
// 'all': every configured TOTP authenticator must match a supplied valid non-replayed code // 'all': every configured TOTP authenticator must match a supplied valid non-replayed code
const matchedUpdates: Array<{ id: string; step: number }> = []; const matchedUpdates: Array<{ id: string; step: number }> = [];
for (const row of rows) { for (const row of rows) {
const secret = this.getTotpSecret(row); const totp = buildTotp(row.secret_base32, username);
const totp = buildTotp(secret, username); const lastStep =
const lastStep = this.getRowLastUsedStep(row); purpose === 'login' ? row.last_login_step : row.last_stepup_step;
let rowStep: number | null = null; let rowStep: number | null = null;
let sawReplay = false; let sawReplay = false;
@ -1674,20 +1296,15 @@ export class AuthService {
} }
if (rowStep === null) { if (rowStep === null) {
if (sawReplay) {
this.emitSecurityEvent('auth.totp_replay', ip, { purpose });
}
return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' };
} }
matchedUpdates.push({ id: row.id, step: rowStep }); matchedUpdates.push({ id: row.id, step: rowStep });
} }
const tx = this.db.transaction(() => { const tx = this.db.transaction(() => {
const stmt = this.db.prepare( const stmt = this.db.prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`);
'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?',
);
for (const upd of matchedUpdates) { for (const upd of matchedUpdates) {
stmt.run(upd.step, upd.step, upd.step, upd.id); stmt.run(upd.step, upd.id);
} }
}); });
tx(); tx();
@ -1704,9 +1321,8 @@ export class AuthService {
const idHash = sha256Hex(sessionToken); const idHash = sha256Hex(sessionToken);
const csrfTokenHash = sha256Hex(csrfToken); const csrfTokenHash = sha256Hex(csrfToken);
const now = Date.now(); const now = Date.now();
const expiresAt = now + SESSION_TTL_MS;
const sec = this.getSecurity(); const sec = this.getSecurity();
const ttlMs = (sec.sessionTtlHours ?? 168) * 60 * 60 * 1000;
const expiresAt = now + ttlMs;
const shouldElevate = const shouldElevate =
sec.elevateOnLogin && (!safeMode || sec.keepElevationOnSafeMode); sec.elevateOnLogin && (!safeMode || sec.keepElevationOnSafeMode);

View file

@ -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<typeof v> => 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;
}
}
}

View file

@ -21,13 +21,6 @@ export const BackupEnvelopeSchema = z.object({
alg: z.literal('aes-256-gcm'), alg: z.literal('aes-256-gcm'),
kdf: z.enum(['raw-master-key', 'scrypt']), kdf: z.enum(['raw-master-key', 'scrypt']),
salt: z.string().optional(), 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), iv: z.string().min(1),
tag: z.string().min(1), tag: z.string().min(1),
ciphertext: z.string().min(1), ciphertext: z.string().min(1),
@ -83,62 +76,9 @@ export interface BackupVerificationSummary {
overlayCount: number; 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 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 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<Buffer> {
const limit = Math.max(1, concurrency);
if (scryptActive >= limit) {
if (scryptWaiters.length >= MAX_SCRYPT_QUEUE) {
throw new BackupBusyError();
}
await new Promise<void>((resolve) => {
scryptWaiters.push(resolve);
});
}
scryptActive += 1;
try {
return await new Promise<Buffer>((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( function validateAndParseConfigEntry(
relPath: string, relPath: string,
@ -207,23 +147,18 @@ function collectConfigFilesFromDisk(configDir: string): Record<string, string> {
for (const name of ['settings.json', 'alerts.json', 'snippets.json']) { for (const name of ['settings.json', 'alerts.json', 'snippets.json']) {
const abs = path.join(configDir, name); const abs = path.join(configDir, name);
if (isRegularNonSymlink(abs)) { if (fs.existsSync(abs)) {
out[name] = fs.readFileSync(abs, 'utf8'); out[name] = fs.readFileSync(abs, 'utf8');
} }
} }
for (const folder of ['servers', 'systems', 'workflows']) { for (const folder of ['servers', 'systems', 'workflows']) {
const dir = path.join(configDir, folder); const dir = path.join(configDir, folder);
try { if (!fs.existsSync(dir)) continue;
const dirStat = fs.lstatSync(dir);
if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) continue;
} catch {
continue;
}
for (const entry of fs.readdirSync(dir).sort()) { for (const entry of fs.readdirSync(dir).sort()) {
if (!entry.endsWith('.json') || entry.includes('.tmp')) continue; if (!entry.endsWith('.json') || entry.includes('.tmp')) continue;
const rel = `${folder}/${entry}`; const rel = `${folder}/${entry}`;
const abs = path.join(dir, entry); const abs = path.join(dir, entry);
if (isRegularNonSymlink(abs)) { if (fs.statSync(abs).isFile()) {
out[rel] = fs.readFileSync(abs, 'utf8'); out[rel] = fs.readFileSync(abs, 'utf8');
} }
} }
@ -231,17 +166,6 @@ function collectConfigFilesFromDisk(configDir: string): Record<string, string> {
return out; 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: { function deriveEnvelopeKeyForEncrypt(opts: {
masterKey?: string; masterKey?: string;
passphrase?: string; passphrase?: string;
@ -249,18 +173,12 @@ function deriveEnvelopeKeyForEncrypt(opts: {
key: Buffer; key: Buffer;
kdf: 'raw-master-key' | 'scrypt'; kdf: 'raw-master-key' | 'scrypt';
saltB64?: string; saltB64?: string;
kdfParams?: { N: number; r: number; p: number };
} { } {
const pass = validateEncryptPassphrase(opts.passphrase); const pass = opts.passphrase?.trim();
if (pass) { if (pass && pass.length > 0) {
const salt = crypto.randomBytes(16); const salt = crypto.randomBytes(16);
const key = crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS); const key = crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS);
return { return { key, kdf: 'scrypt', saltB64: salt.toString('base64') };
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()) { if (!opts.masterKey || !opts.masterKey.trim()) {
throw new Error('Either Vault master key or backup passphrase is required'); 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' }; 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( function deriveEnvelopeKeyForDecrypt(
envelope: BackupEnvelope, envelope: BackupEnvelope,
opts: { masterKey?: string; passphrase?: string }, opts: { masterKey?: string; passphrase?: string },
): Buffer { ): Buffer {
if (envelope.kdf === 'scrypt') { if (envelope.kdf === 'scrypt') {
const { pass, salt, params } = getDecryptScryptInputs(envelope, opts); const pass = opts.passphrase?.trim();
return crypto.scryptSync(pass, salt, 32, params); 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()) { if (!opts.masterKey || !opts.masterKey.trim()) {
throw new Error('This backup requires the 32-byte Vault master key to decrypt'); throw new Error('This backup requires the 32-byte Vault master key to decrypt');
} }
return parseMasterKey(opts.masterKey); return parseMasterKey(opts.masterKey);
} }
async function deriveEnvelopeKeyForDecryptAsync( export function createBackupBundle(opts: {
envelope: BackupEnvelope,
opts: { masterKey?: string; passphrase?: string; scryptConcurrency?: number },
): Promise<Buffer> {
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: {
dataDir: string; dataDir: string;
db?: Database.Database; db?: Database.Database;
masterKey?: string; masterKey?: string;
passphrase?: string;
}): { }): {
inner: BackupInnerPayload; serialized: string;
vaultVerified: boolean; envelope: BackupEnvelope;
vaultCredentialCount?: number; summary: BackupVerificationSummary;
overlayCount: number;
} { } {
const dataDir = path.resolve(opts.dataDir); const dataDir = path.resolve(opts.dataDir);
const configDir = path.join(dataDir, 'config'); const configDir = path.join(dataDir, 'config');
@ -366,7 +232,7 @@ function prepareBackupInner(opts: {
overlayCount += validateAndParseConfigEntry(relPath, rawJson).overlayCount; overlayCount += validateAndParseConfigEntry(relPath, rawJson).overlayCount;
} }
const vaultEnvelopeRaw = isRegularNonSymlink(vaultPath) const vaultEnvelopeRaw = fs.existsSync(vaultPath)
? fs.readFileSync(vaultPath, 'utf8') ? fs.readFileSync(vaultPath, 'utf8')
: null; : null;
let vaultVerified = false; let vaultVerified = false;
@ -383,7 +249,7 @@ function prepareBackupInner(opts: {
let localDb: Database.Database | null = null; let localDb: Database.Database | null = null;
const db = const db =
opts.db ?? opts.db ??
(isRegularNonSymlink(dbPath) ? (localDb = openDatabase(dbPath)) : null); (fs.existsSync(dbPath) ? (localDb = openDatabase(dbPath)) : null);
let knownHosts: Array<z.infer<typeof KnownHostRowSchema>> = []; let knownHosts: Array<z.infer<typeof KnownHostRowSchema>> = [];
let alertSilences: Array<z.infer<typeof AlertSilenceRowSchema>> = []; let alertSilences: Array<z.infer<typeof AlertSilenceRowSchema>> = [];
@ -391,7 +257,7 @@ function prepareBackupInner(opts: {
if (db) { if (db) {
knownHosts = db knownHosts = db
.prepare( .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<z.infer<typeof KnownHostRowSchema>>; .all() as Array<z.infer<typeof KnownHostRowSchema>>;
@ -420,29 +286,17 @@ function prepareBackupInner(opts: {
knownHosts, knownHosts,
dbMeta: { alertSilences }, dbMeta: { alertSilences },
}; };
return { inner, vaultVerified, vaultCredentialCount, overlayCount };
}
function finalizeBackupEnvelope( const { key, kdf, saltB64 } = deriveEnvelopeKeyForEncrypt({
prepared: ReturnType<typeof prepareBackupInner>, masterKey: opts.masterKey,
keyInfo: { passphrase: opts.passphrase,
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 plaintextJson = Buffer.from(JSON.stringify(inner), 'utf8'); const plaintextJson = Buffer.from(JSON.stringify(inner), 'utf8');
const compressed = zlib.gzipSync(plaintextJson, { level: 9 }); const compressed = zlib.gzipSync(plaintextJson, { level: 9 });
try { try {
const iv = crypto.randomBytes(12); const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', keyInfo.key, iv); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
cipher.setAAD(BACKUP_AAD);
const ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]); const ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]);
const tag = cipher.getAuthTag(); const tag = cipher.getAuthTag();
@ -450,115 +304,63 @@ function finalizeBackupEnvelope(
magic: 'GCOORD_BACKUP_V1', magic: 'GCOORD_BACKUP_V1',
version: 1, version: 1,
alg: 'aes-256-gcm', alg: 'aes-256-gcm',
kdf: keyInfo.kdf, kdf,
...(keyInfo.saltB64 ? { salt: keyInfo.saltB64 } : {}), ...(saltB64 ? { salt: saltB64 } : {}),
...(keyInfo.kdfParams ? { kdfParams: keyInfo.kdfParams } : {}),
iv: iv.toString('base64'), iv: iv.toString('base64'),
tag: tag.toString('base64'), tag: tag.toString('base64'),
ciphertext: ciphertext.toString('base64'), ciphertext: ciphertext.toString('base64'),
createdAt: inner.createdAt, createdAt,
}; };
const fileList = Object.keys(inner.configFiles).sort(); const fileList = Object.keys(configFiles).sort();
return { return {
serialized: `${JSON.stringify(envelope, null, 2)}\n`, serialized: `${JSON.stringify(envelope, null, 2)}\n`,
envelope, envelope,
summary: { summary: {
valid: true, valid: true,
createdAt: inner.createdAt, createdAt,
kdf: keyInfo.kdf, kdf,
configFileCount: fileList.length, configFileCount: fileList.length,
configFiles: fileList, configFiles: fileList,
hasVault: inner.vaultEnvelopeRaw !== null, hasVault: vaultEnvelopeRaw !== null,
vaultVerified, vaultVerified,
vaultCredentialCount, vaultCredentialCount,
knownHostsCount: inner.knownHosts.length, knownHostsCount: knownHosts.length,
alertSilenceCount: inner.dbMeta.alertSilences.length, alertSilenceCount: alertSilences.length,
overlayCount, overlayCount,
}, },
}; };
} finally { } finally {
keyInfo.key.fill(0); key.fill(0);
plaintextJson.fill(0); plaintextJson.fill(0);
compressed.fill(0); compressed.fill(0);
} }
} }
export function createBackupBundle(opts: { export function verifyBackupBundle(
dataDir: string; rawTextOrBuf: string | Buffer,
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,
keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string }, keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string },
maxGunzipBytes = DEFAULT_MAX_GUNZIP_BYTES,
): { summary: BackupVerificationSummary; inner: BackupInnerPayload } { ): { 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 iv = Buffer.from(envelope.iv, 'base64');
const tag = Buffer.from(envelope.tag, 'base64'); const tag = Buffer.from(envelope.tag, 'base64');
const ciphertext = Buffer.from(envelope.ciphertext, '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 compressed: Buffer | null = null;
let plaintext: Buffer | null = null; let plaintext: Buffer | null = null;
let inner: BackupInnerPayload; let inner: BackupInnerPayload;
try { try {
const decryptOnce = (useAad: boolean): Buffer => { const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); decipher.setAuthTag(tag);
if (useAad) decipher.setAAD(BACKUP_AAD); compressed = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
decipher.setAuthTag(tag); plaintext = zlib.gunzipSync(compressed, { maxOutputLength: MAX_GUNZIP_BYTES });
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 });
inner = BackupInnerPayloadSchema.parse(JSON.parse(plaintext.toString('utf8'))); inner = BackupInnerPayloadSchema.parse(JSON.parse(plaintext.toString('utf8')));
} finally { } finally {
key.fill(0); 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( export function verifyBackupSummaryOnly(
rawTextOrBuf: string | Buffer, rawTextOrBuf: string | Buffer,
keyOpts: { keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string },
masterKey?: string;
passphrase?: string;
vaultMasterKey?: string;
maxGunzipBytes?: number;
},
): BackupVerificationSummary { ): BackupVerificationSummary {
return verifyBackupBundle(rawTextOrBuf, keyOpts).summary; return verifyBackupBundle(rawTextOrBuf, keyOpts).summary;
} }
export async function verifyBackupSummaryOnlyAsync(
rawTextOrBuf: string | Buffer,
keyOpts: {
masterKey?: string;
passphrase?: string;
vaultMasterKey?: string;
scryptConcurrency?: number;
maxGunzipBytes?: number;
},
): Promise<BackupVerificationSummary> {
const res = await verifyBackupBundleAsync(rawTextOrBuf, keyOpts);
return res.summary;
}
function writeAtomicPrivateFile(targetPath: string, content: string): void { function writeAtomicPrivateFile(targetPath: string, content: string): void {
fs.mkdirSync(path.dirname(targetPath), { recursive: true }); 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); const fd = fs.openSync(tmpPath, 'w', 0o600);
try { try {
fs.writeFileSync(fd, content, 'utf8'); fs.writeFileSync(fd, content, 'utf8');
@ -693,7 +436,7 @@ function writeAtomicPrivateFile(targetPath: string, content: string): void {
function swapConfigDirectoryAtomic(configDir: string, configFiles: Record<string, string>): void { function swapConfigDirectoryAtomic(configDir: string, configFiles: Record<string, string>): void {
const parent = path.dirname(configDir); 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 stageDir = path.join(parent, `config.restore-${rand}`);
const bakDir = path.join(parent, `config.bak-${rand}`); const bakDir = path.join(parent, `config.bak-${rand}`);
@ -731,10 +474,22 @@ function swapConfigDirectoryAtomic(configDir: string, configFiles: Record<string
} }
} }
function applyVerifiedRestoreToDisk( export function restoreBackupBundle(
verified: { summary: BackupVerificationSummary; inner: BackupInnerPayload }, rawTextOrBuf: string | Buffer,
opts: { dataDir: string; db?: Database.Database }, opts: {
dataDir: string;
masterKey?: string;
passphrase?: string;
vaultMasterKey?: string;
db?: Database.Database;
},
): { summary: BackupVerificationSummary; inner: BackupInnerPayload } { ): { summary: BackupVerificationSummary; inner: BackupInnerPayload } {
const verified = verifyBackupBundle(rawTextOrBuf, {
masterKey: opts.masterKey,
passphrase: opts.passphrase,
vaultMasterKey: opts.vaultMasterKey,
});
const dataDir = path.resolve(opts.dataDir); const dataDir = path.resolve(opts.dataDir);
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 }); fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
@ -777,45 +532,3 @@ function applyVerifiedRestoreToDisk(
return verified; return verified;
} }
export function restoreBackupBundle(
rawTextOrBuf: string | Buffer,
opts: {
dataDir: string;
masterKey?: string;
passphrase?: string;
vaultMasterKey?: string;
db?: Database.Database;
maxGunzipBytes?: number;
},
): { summary: BackupVerificationSummary; inner: BackupInnerPayload } {
const verified = verifyBackupBundle(rawTextOrBuf, {
masterKey: opts.masterKey,
passphrase: opts.passphrase,
vaultMasterKey: opts.vaultMasterKey,
maxGunzipBytes: opts.maxGunzipBytes,
});
return applyVerifiedRestoreToDisk(verified, opts);
}
export async function restoreBackupBundleAsync(
rawTextOrBuf: string | Buffer,
opts: {
dataDir: string;
masterKey?: string;
passphrase?: string;
vaultMasterKey?: string;
db?: Database.Database;
scryptConcurrency?: number;
maxGunzipBytes?: number;
},
): Promise<{ summary: BackupVerificationSummary; inner: BackupInnerPayload }> {
const verified = await verifyBackupBundleAsync(rawTextOrBuf, {
masterKey: opts.masterKey,
passphrase: opts.passphrase,
vaultMasterKey: opts.vaultMasterKey,
scryptConcurrency: opts.scryptConcurrency,
maxGunzipBytes: opts.maxGunzipBytes,
});
return applyVerifiedRestoreToDisk(verified, opts);
}

View file

@ -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<string>(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<string[]> {
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<void> {
await resolveAllowedEgressIps(rawHost, allowedCidrs);
}
export async function assertEgressUrlAllowed(
rawUrl: string,
allowedCidrs: string[] = [],
): Promise<URL> {
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<Response> {
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,
});
}

View file

@ -1,16 +1,12 @@
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import net from 'node:net'; import type { NextFunction, Request, Response } from 'express';
import type Database from 'better-sqlite3';
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import type { StepUpPolicy } from '../../shared/schemas/settings.schema.js'; import type { StepUpPolicy } from '../../shared/schemas/settings.schema.js';
import type { AuditService } from './audit.js';
import { import {
SESSION_COOKIE_NAME, SESSION_COOKIE_NAME,
sha256Hex, sha256Hex,
type AuthService, type AuthService,
type AuthSession, type AuthSession,
} from './auth.js'; } from './auth.js';
import { isIpInCidrs } from './egress-guard.js';
declare global { declare global {
namespace Express { 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 { interface RateBucketState {
failures: number; failures: number;
lockedUntil: 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 { export class RateLimiter {
private readonly buckets = new Map<string, RateBucketState>(); private readonly buckets = new Map<string, RateBucketState>();
private readonly inFlightCounts = new Map<string, number>();
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 } { check(scope: string, ip: string): { allowed: boolean; retryAfterSec: number } {
const key = `${scope}:${ip}`; 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(); const now = Date.now();
if (state && state.lockedUntil > now) { if (state.lockedUntil > now) {
return { return {
allowed: false, allowed: false,
retryAfterSec: Math.max(1, Math.ceil((state.lockedUntil - now) / 1000)), 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 }; return { allowed: true, retryAfterSec: 0 };
} }
acquireInFlight(scope: string, ip: string, maxConcurrent = 2): boolean { recordFailure(scope: string, ip: string): number {
const key = `${scope}:${ip}`; const key = `${scope}:${ip}`;
const cur = this.inFlightCounts.get(key) ?? 0; const prev = this.buckets.get(key) ?? { failures: 0, lockedUntil: 0 };
if (cur >= maxConcurrent) return false; const failures = prev.failures + 1;
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;
let lockedUntil = 0; let lockedUntil = 0;
if (failures >= 5) { if (failures >= 5) {
const delayMs = Math.min(300_000, 2000 * 2 ** (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 }); this.buckets.set(key, { failures, lockedUntil });
return lockedUntil;
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 };
} }
recordSuccess(scope: string, ip: string): void { recordSuccess(scope: string, ip: string): void {
this.deleteBucket(`${scope}:${ip}`); this.buckets.delete(`${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);
} }
} }
export function extractCookies(cookieHeader: string | undefined): Record<string, string> { export function extractCookies(cookieHeader: string | undefined): Record<string, string> {
const result = Object.create(null) as Record<string, string>; const result: Record<string, string> = {};
if (!cookieHeader) return result; if (!cookieHeader) return result;
for (const part of cookieHeader.split(';')) { for (const part of cookieHeader.split(';')) {
const eq = part.indexOf('='); const eq = part.indexOf('=');
if (eq <= 0) continue; if (eq <= 0) continue;
const key = part.slice(0, eq).trim(); const key = part.slice(0, eq).trim();
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
const rawVal = part.slice(eq + 1).trim(); const rawVal = part.slice(eq + 1).trim();
try { try {
result[key] = decodeURIComponent(rawVal); result[key] = decodeURIComponent(rawVal);
@ -232,54 +75,23 @@ export function extractCookies(cookieHeader: string | undefined): Record<string,
return result; return result;
} }
export function isTrustedProxyPeer( export function resolveClientIp(req: Request, trustCloudflare: boolean): string {
remoteAddr: string | undefined, if (trustCloudflare) {
trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS,
): boolean {
if (!remoteAddr) return false;
return isIpInCidrs(remoteAddr, trustedProxyCidrs);
}
export function resolveClientIp(
req: Request,
trustCloudflare: boolean,
trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS,
): string {
const peerIp = req.socket?.remoteAddress;
if (trustCloudflare && isTrustedProxyPeer(peerIp, trustedProxyCidrs)) {
const cf = req.headers['cf-connecting-ip']; const cf = req.headers['cf-connecting-ip'];
if (typeof cf === 'string' && cf.trim().length > 0) { if (typeof cf === 'string' && cf.trim().length > 0) {
const candidate = cf.split(',')[0]!.trim(); return cf.split(',')[0]!.trim();
if (net.isIP(candidate) !== 0) {
return candidate;
}
} }
} }
return req.ip || peerIp || 'unknown'; return req.ip || req.socket.remoteAddress || 'unknown';
} }
export function attachClientIp( export function attachClientIp(trustCloudflare: boolean) {
trustCloudflare: boolean,
trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS,
) {
return (req: Request, _res: Response, next: NextFunction): void => { return (req: Request, _res: Response, next: NextFunction): void => {
req.clientIp = resolveClientIp(req, trustCloudflare, trustedProxyCidrs); req.clientIp = resolveClientIp(req, trustCloudflare);
next(); next();
}; };
} }
export function asyncHandler(
fn: (req: Request, res: Response, next: NextFunction) => Promise<void> | 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) { export function requireAuth(authService: AuthService) {
return (req: Request, res: Response, next: NextFunction): void => { return (req: Request, res: Response, next: NextFunction): void => {
const cookies = extractCookies(req.headers.cookie); 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']; const headerToken = req.headers['x-csrf-token'];
if (typeof headerToken !== 'string' || headerToken.length < 16) { 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' }); res.status(403).json({ error: 'CSRF_INVALID' });
return; return;
} }
@ -322,13 +127,6 @@ export function requireCsrf(req: Request, res: Response, next: NextFunction): vo
providedHash.length !== expectedHash.length || providedHash.length !== expectedHash.length ||
!crypto.timingSafeEqual(providedHash, expectedHash) !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' }); res.status(403).json({ error: 'CSRF_INVALID' });
return; return;
} }
@ -342,13 +140,6 @@ export function enforceSafeMode(req: Request, res: Response, next: NextFunction)
} }
const clientSafeHeader = req.headers['x-gcoord-safe-mode'] === '1'; const clientSafeHeader = req.headers['x-gcoord-safe-mode'] === '1';
if (req.authSession?.safeMode || clientSafeHeader) { 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({ res.status(423).json({
error: 'SAFE_MODE_ACTIVE', error: 'SAFE_MODE_ACTIVE',
message: 'Disable Safe / Read-Only Mode before performing mutating actions.', message: 'Disable Safe / Read-Only Mode before performing mutating actions.',
@ -376,13 +167,6 @@ export function createStepUpGuard(
} }
if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) { 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({ res.status(403).json({
error: 'STEP_UP_REQUIRED', error: 'STEP_UP_REQUIRED',
message: 'Re-authentication verification is required for this sensitive operation.', message: 'Re-authentication verification is required for this sensitive operation.',
@ -405,13 +189,6 @@ export function requireStepUp(req: Request, res: Response, next: NextFunction):
return; return;
} }
if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) { 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({ res.status(403).json({
error: 'STEP_UP_REQUIRED', error: 'STEP_UP_REQUIRED',
message: 'Re-authentication verification is required for this sensitive operation.', message: 'Re-authentication verification is required for this sensitive operation.',

View file

@ -1,4 +1,3 @@
import crypto from 'node:crypto';
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import type { VaultCredential } from '../../shared/schemas/vault.schema.js'; import type { VaultCredential } from '../../shared/schemas/vault.schema.js';
@ -7,6 +6,7 @@ import type { VaultService } from './vault.js';
export interface SavedPasswordEntry { export interface SavedPasswordEntry {
id: string; id: string;
label: string; label: string;
plaintextPassword?: string;
createdAt: string; createdAt: string;
} }
@ -48,6 +48,7 @@ export interface SyncRecoveryOptions {
username?: string | null; username?: string | null;
totps?: SavedTotpEntry[]; totps?: SavedTotpEntry[];
passwordMetaList?: Array<{ id: string; label: string; createdAt: number }>; passwordMetaList?: Array<{ id: string; label: string; createdAt: number }>;
passwordPlaintextUpdate?: { id: string; label: string; password: string; createdAt?: number };
removedPasswordId?: string; removedPasswordId?: string;
newRecoveryCodes?: string[]; newRecoveryCodes?: string[];
snapshotReason?: string; snapshotReason?: string;
@ -73,8 +74,6 @@ export class EmergencyRecoveryService {
readBundle(): EmergencySecretsBundle | null { readBundle(): EmergencySecretsBundle | null {
if (!fs.existsSync(this.bundlePath)) return null; if (!fs.existsSync(this.bundlePath)) return null;
try { try {
const stat = fs.lstatSync(this.bundlePath);
if (!stat.isFile() || stat.isSymbolicLink()) return null;
const raw = JSON.parse(fs.readFileSync(this.bundlePath, 'utf8')); const raw = JSON.parse(fs.readFileSync(this.bundlePath, 'utf8'));
if (!raw || typeof raw !== 'object' || raw.version !== 1) return null; if (!raw || typeof raw !== 'object' || raw.version !== 1) return null;
return raw as EmergencySecretsBundle; return raw as EmergencySecretsBundle;
@ -106,30 +105,43 @@ export class EmergencyRecoveryService {
? opts.vault.exportAllCredentials() ? opts.vault.exportAllCredentials()
: existing?.vaultCredentials ?? {}; : existing?.vaultCredentials ?? {};
// Merge saved plaintext passwords safely across updates
const prevPwById = new Map<string, SavedPasswordEntry>(); const prevPwById = new Map<string, SavedPasswordEntry>();
for (const p of existing?.admin.passwords ?? []) { for (const p of existing?.admin.passwords ?? []) {
prevPwById.set(p.id, { prevPwById.set(p.id, p);
id: p.id,
label: p.label,
createdAt: p.createdAt,
});
} }
if (opts.removedPasswordId) { if (opts.removedPasswordId) {
prevPwById.delete(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 let finalPasswords: SavedPasswordEntry[];
? opts.passwordMetaList.map((meta) => ({ if (opts.passwordMetaList) {
finalPasswords = opts.passwordMetaList.map((meta) => {
const prev = prevPwById.get(meta.id);
return {
id: meta.id, id: meta.id,
label: meta.label, label: meta.label,
plaintextPassword: prev?.plaintextPassword,
createdAt: new Date(meta.createdAt).toISOString(), createdAt: new Date(meta.createdAt).toISOString(),
})) };
: [...prevPwById.values()]; });
} else {
finalPasswords = [...prevPwById.values()];
}
const bundle: EmergencySecretsBundle = { const bundle: EmergencySecretsBundle = {
version: 1, version: 1,
updatedAt: nowIso, 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, vaultMasterKeyHex: masterKeyHex,
admin: { admin: {
username: opts.username !== undefined ? opts.username : existing?.admin.username ?? null, username: opts.username !== undefined ? opts.username : existing?.admin.username ?? null,
@ -173,22 +185,10 @@ export class EmergencyRecoveryService {
wipeAll(): void { wipeAll(): void {
const shred = (filePath: string) => { const shred = (filePath: string) => {
let stat: fs.Stats; if (!fs.existsSync(filePath)) return;
try { try {
stat = fs.lstatSync(filePath); const stat = fs.statSync(filePath);
} catch { if (stat.isFile() && stat.size > 0) {
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 fd = fs.openSync(filePath, 'r+'); const fd = fs.openSync(filePath, 'r+');
try { try {
fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0); fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0);
@ -196,9 +196,9 @@ export class EmergencyRecoveryService {
} finally { } finally {
fs.closeSync(fd); fs.closeSync(fd);
} }
} catch {
// Best-effort overwrite before unlink
} }
} catch {
// Best-effort overwrite before unlink
} }
fs.unlinkSync(filePath); fs.unlinkSync(filePath);
}; };
@ -208,11 +208,7 @@ export class EmergencyRecoveryService {
for (const f of fs.readdirSync(this.snapshotsDir)) { for (const f of fs.readdirSync(this.snapshotsDir)) {
shred(path.join(this.snapshotsDir, f)); shred(path.join(this.snapshotsDir, f));
} }
try { fs.rmdirSync(this.snapshotsDir);
fs.rmdirSync(this.snapshotsDir);
} catch {
// Ignore unexpected remaining files
}
} }
if (fs.existsSync(this.recoveryDir)) { if (fs.existsSync(this.recoveryDir)) {
try { try {
@ -231,7 +227,7 @@ export class EmergencyRecoveryService {
} }
private writeAtomicSecure(targetPath: string, content: string): void { 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); const fd = fs.openSync(tmpPath, 'w', 0o600);
try { try {
fs.writeFileSync(fd, content, 'utf8'); fs.writeFileSync(fd, content, 'utf8');
@ -251,19 +247,8 @@ export class EmergencyRecoveryService {
.sort(); .sort();
while (files.length > MAX_SNAPSHOTS) { while (files.length > MAX_SNAPSHOTS) {
const oldest = files.shift()!; const oldest = files.shift()!;
const p = path.join(this.snapshotsDir, oldest);
try { try {
const stat = fs.lstatSync(p); fs.unlinkSync(path.join(this.snapshotsDir, oldest));
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);
} catch { } catch {
// Ignore cleanup failure // Ignore cleanup failure
} }

View file

@ -10,14 +10,11 @@ import {
type VaultCredentialMeta, type VaultCredentialMeta,
type VaultPayload, type VaultPayload,
} from '../../shared/schemas/vault.schema.js'; } from '../../shared/schemas/vault.schema.js';
import type { VaultSealState, VaultState } from '../../shared/ws-protocol.js'; import type { VaultState } from '../../shared/ws-protocol.js';
const VAULT_AAD = Buffer.from('gcoord-vault-v1', 'utf8');
export const VaultEnvelopeSchema = z.object({ export const VaultEnvelopeSchema = z.object({
version: z.literal(1), version: z.literal(1),
alg: z.literal('aes-256-gcm'), alg: z.literal('aes-256-gcm'),
aad: z.boolean().optional(),
iv: z.string().min(1), iv: z.string().min(1),
tag: z.string().min(1), tag: z.string().min(1),
ciphertext: z.string().min(1), ciphertext: z.string().min(1),
@ -45,7 +42,6 @@ export function generateMasterKeyBuffer(): Buffer {
function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope { function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope {
const iv = crypto.randomBytes(12); const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
cipher.setAAD(VAULT_AAD);
const plaintext = Buffer.from(JSON.stringify(payload), 'utf8'); const plaintext = Buffer.from(JSON.stringify(payload), 'utf8');
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]); const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
const tag = cipher.getAuthTag(); const tag = cipher.getAuthTag();
@ -54,7 +50,6 @@ function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope {
return { return {
version: 1, version: 1,
alg: 'aes-256-gcm', alg: 'aes-256-gcm',
aad: true,
iv: iv.toString('base64'), iv: iv.toString('base64'),
tag: tag.toString('base64'), tag: tag.toString('base64'),
ciphertext: ciphertext.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); const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
if (envelope.aad) {
decipher.setAAD(VAULT_AAD);
}
decipher.setAuthTag(tag); decipher.setAuthTag(tag);
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]); const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
try { try {
@ -117,11 +109,7 @@ export function verifyVaultEnvelopeText(
} }
export function computeOpenSshFingerprint(publicKeyLine: string): string { export function computeOpenSshFingerprint(publicKeyLine: string): string {
const trimmed = publicKeyLine.trim(); const parsed = ssh2.utils.parseKey(publicKeyLine.trim());
if (/[\r\n\0]/.test(trimmed)) {
throw new Error('Public key must be a single line');
}
const parsed = ssh2.utils.parseKey(trimmed);
if (parsed instanceof Error) { if (parsed instanceof Error) {
throw parsed; throw parsed;
} }
@ -134,13 +122,6 @@ export function computeOpenSshFingerprint(publicKeyLine: string): string {
return `SHA256:${hash}`; 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 * Generates an OpenSSH Ed25519 keypair, retrying around ssh2's BitString
* leading-zero stripping bug when a generated public key starts with 0x00. * leading-zero stripping bug when a generated public key starts with 0x00.
@ -184,29 +165,22 @@ export type VaultCredentialInput = DistributiveOmit<
export interface VaultServiceOptions { export interface VaultServiceOptions {
keyFilePath?: string; keyFilePath?: string;
allowLocalKeyFile?: boolean;
} }
type KeySource = 'secret-file' | 'env' | 'key-file' | 'backup' | 'generated' | 'manual';
export class VaultService { export class VaultService {
private masterKey: Buffer | null = null; private masterKey: Buffer | null = null;
private credentials = new Map<string, VaultCredential>(); private credentials = new Map<string, VaultCredential>();
private writeUnlocked = false; private writeUnlocked = false;
private autoInitializedEmpty = false; private autoInitializedEmpty = false;
private wasPanicLocked = false; private wasPanicLocked = false;
private keySource: KeySource | null = null;
private readonly keyFilePath: string | null; private readonly keyFilePath: string | null;
private readonly allowLocalKeyFile: boolean;
private readonly panicListeners = new Set<() => void>(); private readonly panicListeners = new Set<() => void>();
private readonly sealListeners = new Set<() => void>();
constructor( constructor(
private readonly vaultFilePath: string, private readonly vaultFilePath: string,
options: VaultServiceOptions = {}, options: VaultServiceOptions = {},
) { ) {
this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null; this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null;
this.allowLocalKeyFile = options.allowLocalKeyFile ?? true;
this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath()); this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath());
} }
@ -238,12 +212,6 @@ export class VaultService {
return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized'; 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 { get isPanicLocked(): boolean {
return this.wasPanicLocked || fs.existsSync(this.panicLockMarkerPath()); 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: { initRuntime(options: {
secretFilePath?: string; secretFilePath?: string;
envKey?: string; envKey?: string;
@ -273,20 +234,20 @@ export class VaultService {
return { runtimeReady: false, reason: 'panic_locked' }; return { runtimeReady: false, reason: 'panic_locked' };
} }
const candidates: Array<{ value: string; source: KeySource }> = []; const candidates: string[] = [];
if (options.secretFilePath && fs.existsSync(options.secretFilePath)) { if (options.secretFilePath && fs.existsSync(options.secretFilePath)) {
const val = fs.readFileSync(options.secretFilePath, 'utf8').trim(); 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) { 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)) { if (this.keyFilePath && fs.existsSync(this.keyFilePath)) {
const val = fs.readFileSync(this.keyFilePath, 'utf8').trim(); 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) { 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)) { if (fs.existsSync(this.vaultFilePath)) {
@ -307,19 +268,15 @@ export class VaultService {
for (const candidate of candidates) { for (const candidate of candidates) {
let keyBuf: Buffer | null = null; let keyBuf: Buffer | null = null;
try { try {
keyBuf = parseMasterKey(candidate.value); keyBuf = parseMasterKey(candidate);
const payload = decryptEnvelope(envelope, keyBuf); const payload = decryptEnvelope(envelope, keyBuf);
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = keyBuf; this.masterKey = keyBuf;
this.keySource = candidate.source;
this.credentials = new Map(Object.entries(payload.credentials)); this.credentials = new Map(Object.entries(payload.credentials));
this.writeUnlocked = false; this.writeUnlocked = false;
this.autoInitializedEmpty = false; this.autoInitializedEmpty = false;
this.setPanicLockMarker(false); this.setPanicLockMarker(false);
// Security invariant: NEVER mirror Docker Secret or env master keys to disk vault.key this.persistKeyFileIfConfigured(keyBuf);
if (candidate.source === 'key-file') {
this.persistKeyFileIfConfigured(keyBuf);
}
return { runtimeReady: true }; return { runtimeReady: true };
} catch { } catch {
keyBuf?.fill(0); keyBuf?.fill(0);
@ -334,28 +291,17 @@ export class VaultService {
let keyBuf: Buffer | null = null; let keyBuf: Buffer | null = null;
try { try {
const chosen = candidates[0]; keyBuf = candidates[0] ? parseMasterKey(candidates[0]) : generateMasterKeyBuffer();
const source: KeySource = chosen ? chosen.source : 'generated';
keyBuf = chosen ? parseMasterKey(chosen.value) : generateMasterKeyBuffer();
const emptyPayload: VaultPayload = { version: 1, credentials: {} }; const emptyPayload: VaultPayload = { version: 1, credentials: {} };
this.writeVerifiedVaultAtomic(emptyPayload, keyBuf); this.writeVerifiedVaultAtomic(emptyPayload, keyBuf);
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = keyBuf; this.masterKey = keyBuf;
this.keySource = source;
this.credentials.clear(); this.credentials.clear();
this.writeUnlocked = false; this.writeUnlocked = false;
this.autoInitializedEmpty = true; this.autoInitializedEmpty = true;
this.setPanicLockMarker(false); this.setPanicLockMarker(false);
// Only write local keyfile when generated locally (or already using key-file) and allowed this.persistKeyFileIfConfigured(keyBuf);
if (
this.allowLocalKeyFile &&
source !== 'secret-file' &&
source !== 'env' &&
source !== 'backup'
) {
this.persistKeyFileIfConfigured(keyBuf);
}
return { runtimeReady: true, initialized: true }; return { runtimeReady: true, initialized: true };
} catch (err) { } catch (err) {
keyBuf?.fill(0); keyBuf?.fill(0);
@ -416,14 +362,11 @@ export class VaultService {
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = keyBuf; this.masterKey = keyBuf;
this.keySource = 'manual';
this.credentials.clear(); this.credentials.clear();
this.writeUnlocked = true; this.writeUnlocked = true;
this.autoInitializedEmpty = false; this.autoInitializedEmpty = false;
this.setPanicLockMarker(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') }; return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') };
} }
@ -441,48 +384,17 @@ export class VaultService {
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = keyBuf; this.masterKey = keyBuf;
this.keySource = 'manual';
this.credentials = new Map(Object.entries(payload.credentials)); this.credentials = new Map(Object.entries(payload.credentials));
this.writeUnlocked = true; this.writeUnlocked = true;
this.autoInitializedEmpty = false; this.autoInitializedEmpty = false;
this.setPanicLockMarker(false); this.setPanicLockMarker(false);
if (this.allowLocalKeyFile && this.keyFilePath && fs.existsSync(this.keyFilePath)) { this.persistKeyFileIfConfigured(keyBuf);
this.persistKeyFileIfConfigured(keyBuf);
}
} catch (err) { } catch (err) {
keyBuf.fill(0); keyBuf.fill(0);
throw err; 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 { unlockForModifications(): void {
if (this.masterKey === null || this.isPanicLocked) { if (this.masterKey === null || this.isPanicLocked) {
throw new Error('Master key is required to unseal vault'); throw new Error('Master key is required to unseal vault');
@ -560,15 +472,7 @@ export class VaultService {
this.zeroizeMasterKey(); this.zeroizeMasterKey();
this.masterKey = nextKey; this.masterKey = nextKey;
this.writeUnlocked = true; this.writeUnlocked = true;
if ( this.persistKeyFileIfConfigured(nextKey);
this.allowLocalKeyFile &&
this.keySource !== 'secret-file' &&
this.keySource !== 'env' &&
this.keyFilePath &&
fs.existsSync(this.keyFilePath)
) {
this.persistKeyFileIfConfigured(nextKey);
}
return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') }; return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') };
} catch (err) { } catch (err) {
nextKey.fill(0); nextKey.fill(0);
@ -709,8 +613,8 @@ export class VaultService {
this.keyFilePath ?? (fs.existsSync(siblingKeyFile) ? siblingKeyFile : null); this.keyFilePath ?? (fs.existsSync(siblingKeyFile) ? siblingKeyFile : null);
if (!targetPath) return; if (!targetPath) return;
fs.mkdirSync(path.dirname(targetPath), { recursive: true, mode: 0o700 }); fs.mkdirSync(path.dirname(targetPath), { recursive: true });
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); const fd = fs.openSync(tmpPath, 'w', 0o600);
try { try {
fs.writeFileSync(fd, `${key.toString('hex')}\n`, 'utf8'); fs.writeFileSync(fd, `${key.toString('hex')}\n`, 'utf8');
@ -731,11 +635,11 @@ export class VaultService {
private writeVerifiedVaultAtomic(payload: VaultPayload, key: Buffer): void { private writeVerifiedVaultAtomic(payload: VaultPayload, key: Buffer): void {
const dir = path.dirname(this.vaultFilePath); const dir = path.dirname(this.vaultFilePath);
fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); fs.mkdirSync(dir, { recursive: true });
const envelope = encryptPayload(payload, key); const envelope = encryptPayload(payload, key);
const serialized = JSON.stringify(envelope, null, 2); 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); const fd = fs.openSync(tmpPath, 'w', 0o600);
try { try {

View file

@ -7,22 +7,13 @@ import type { SSHPool } from './ssh-pool.js';
const OPENSSH_KEY_TYPES = new Set([ const OPENSSH_KEY_TYPES = new Set([
'ssh-ed25519', 'ssh-ed25519',
'ssh-ed25519-cert-v01@openssh.com',
'ssh-rsa', 'ssh-rsa',
'ssh-rsa-cert-v01@openssh.com',
'rsa-sha2-256',
'rsa-sha2-512',
'ssh-dss', 'ssh-dss',
'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp256',
'ecdsa-sha2-nistp256-cert-v01@openssh.com',
'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp384',
'ecdsa-sha2-nistp384-cert-v01@openssh.com',
'ecdsa-sha2-nistp521', 'ecdsa-sha2-nistp521',
'ecdsa-sha2-nistp521-cert-v01@openssh.com',
'sk-ssh-ed25519@openssh.com', 'sk-ssh-ed25519@openssh.com',
'sk-ssh-ed25519-cert-v01@openssh.com',
'sk-ecdsa-sha2-nistp256@openssh.com', 'sk-ecdsa-sha2-nistp256@openssh.com',
'sk-ecdsa-sha2-nistp256-cert-v01@openssh.com',
]); ]);
export interface AuthorizedKeyEntry { export interface AuthorizedKeyEntry {
@ -144,8 +135,6 @@ function makeRotatedCredentialId(serverId: string): string {
} }
export class KeyManager { export class KeyManager {
private readonly activeRotations = new Set<string>();
constructor( constructor(
private readonly sshPool: SSHPool, private readonly sshPool: SSHPool,
private readonly vaultService: VaultService, private readonly vaultService: VaultService,
@ -288,32 +277,6 @@ export class KeyManager {
passphrase: string | undefined, passphrase: string | undefined,
actorIp: string, actorIp: string,
sessionIdHash: string | null, sessionIdHash: string | null,
): Promise<KeyRotationResult> {
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<KeyRotationResult> { ): Promise<KeyRotationResult> {
const server = this.configManager.getServer(serverId); const server = this.configManager.getServer(serverId);
if (!server) { if (!server) {
@ -361,7 +324,7 @@ export class KeyManager {
newSecret.passphrase, 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 }; const updatedServer = { ...server, credentialId: newCredId };
this.configManager.saveConfigText( this.configManager.saveConfigText(
`servers/${server.id}.json`, `servers/${server.id}.json`,
@ -370,6 +333,9 @@ export class KeyManager {
`Atomic SSH key rotation -> ${newCredId}`, `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 // Cleanly remove old public key from authorized_keys if it differs
if (oldFingerprint && oldFingerprint !== newMeta.fingerprint) { if (oldFingerprint && oldFingerprint !== newMeta.fingerprint) {
const afterInspect = await this.inspectAuthorizedKeys(server.id); const afterInspect = await this.inspectAuthorizedKeys(server.id);

View file

@ -12,16 +12,11 @@ export interface KnownHostRecord {
updatedAt: number; 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<ServerConfig, 'host' | 'port' | 'jumpHostId'>): string { export function buildHostPortKey(server: Pick<ServerConfig, 'host' | 'port' | 'jumpHostId'>): string {
const hostNormalized = normalizeHostForKey(server.host); const hostLower = server.host.trim().toLowerCase();
return server.jumpHostId return server.jumpHostId
? `${server.jumpHostId}->${hostNormalized}:${server.port}` ? `${server.jumpHostId}->${hostLower}:${server.port}`
: `${hostNormalized}:${server.port}`; : `${hostLower}:${server.port}`;
} }
export function parseHostKeyBuffer(keyBuf: Buffer): { export function parseHostKeyBuffer(keyBuf: Buffer): {
@ -49,32 +44,13 @@ export function parseHostKeyBuffer(keyBuf: Buffer): {
export class KnownHostsService { export class KnownHostsService {
private readonly pendingTofu = new Map<string, PendingTofuInfo>(); private readonly pendingTofu = new Map<string, PendingTofuInfo>();
private readonly pendingMismatches = new Map<string, HostKeyAlert>(); private readonly pendingMismatches = new Map<string, HostKeyAlert>();
private readonly verifiedOpenSshKeys = new Map<string, { hostPortKey: string; line: string }>();
private readonly listeners = new Set<() => void>(); private readonly listeners = new Set<() => void>();
private readonly mismatchListeners = new Set<(alert: HostKeyAlert) => void>();
constructor( constructor(
private readonly db: Database.Database, private readonly db: Database.Database,
private readonly auditService?: AuditService, 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 { onChange(listener: () => void): () => void {
this.listeners.add(listener); this.listeners.add(listener);
return () => { return () => {
@ -87,20 +63,19 @@ export class KnownHostsService {
const { algorithm, fingerprint } = parseHostKeyBuffer(keyBuf); const { algorithm, fingerprint } = parseHostKeyBuffer(keyBuf);
const now = Date.now(); const now = Date.now();
const exactRow = this.db const row = this.db
.prepare( .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 (row) {
if (exactRow.fingerprint === fingerprint) { if (row.fingerprint === fingerprint) {
const hadPending = const hadPending =
this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id); this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id);
this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf);
this.db this.db
.prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ? AND algorithm = ?') .prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ?')
.run(now, hostPortKey, algorithm); .run(now, hostPortKey);
if (hadPending) this.emitChange(); if (hadPending) this.emitChange();
return true; return true;
} }
@ -111,7 +86,7 @@ export class KnownHostsService {
host: server.host, host: server.host,
port: server.port, port: server.port,
algorithm, algorithm,
expectedFingerprint: exactRow.fingerprint, expectedFingerprint: row.fingerprint,
actualFingerprint: fingerprint, actualFingerprint: fingerprint,
detectedAt: now, detectedAt: now,
}; };
@ -124,12 +99,10 @@ export class KnownHostsService {
status: 'denied', status: 'denied',
details: { details: {
hostPortKey, hostPortKey,
algorithm, expected: row.fingerprint,
expected: exactRow.fingerprint,
actual: fingerprint, actual: fingerprint,
}, },
}); });
this.emitMismatch(alert);
this.emitChange(); this.emitChange();
return false; return false;
} }
@ -139,7 +112,6 @@ export class KnownHostsService {
const expected = server.hostKeyFingerprint.trim(); const expected = server.hostKeyFingerprint.trim();
if (expected === fingerprint) { if (expected === fingerprint) {
this.upsertKnownHost(hostPortKey, algorithm, fingerprint, now); this.upsertKnownHost(hostPortKey, algorithm, fingerprint, now);
this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf);
this.pendingTofu.delete(server.id); this.pendingTofu.delete(server.id);
this.pendingMismatches.delete(server.id); this.pendingMismatches.delete(server.id);
this.auditService?.log({ this.auditService?.log({
@ -169,9 +141,8 @@ export class KnownHostsService {
actorIp: 'hub', actorIp: 'hub',
target: server.id, target: server.id,
status: 'denied', status: 'denied',
details: { hostPortKey, algorithm, expected, actual: fingerprint }, details: { hostPortKey, expected, actual: fingerprint },
}); });
this.emitMismatch(alert);
this.emitChange(); this.emitChange();
return false; return false;
} }
@ -267,7 +238,7 @@ export class KnownHostsService {
listKnownHosts(): KnownHostRecord[] { listKnownHosts(): KnownHostRecord[] {
return this.db return this.db
.prepare( .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[]; .all() as KnownHostRecord[];
} }
@ -301,21 +272,15 @@ export class KnownHostsService {
this.emitChange(); this.emitChange();
} }
deleteKnownHost(hostPort: string, algorithm?: string): boolean { deleteKnownHost(hostPort: string): boolean {
const res = algorithm const res = this.db
? this.db .prepare('DELETE FROM known_hosts WHERE host_port = ?')
.prepare('DELETE FROM known_hosts WHERE host_port = ? AND algorithm = ?') .run(hostPort);
.run(hostPort, algorithm)
: this.db.prepare('DELETE FROM known_hosts WHERE host_port = ?').run(hostPort);
for (const [sid, p] of this.pendingTofu.entries()) { for (const [sid, p] of this.pendingTofu.entries()) {
if (p.hostPortKey === hostPort && (!algorithm || p.algorithm === algorithm)) { if (p.hostPortKey === hostPort) this.pendingTofu.delete(sid);
this.pendingTofu.delete(sid);
}
} }
for (const [sid, m] of this.pendingMismatches.entries()) { for (const [sid, m] of this.pendingMismatches.entries()) {
if (m.hostPortKey === hostPort && (!algorithm || m.algorithm === algorithm)) { if (m.hostPortKey === hostPort) this.pendingMismatches.delete(sid);
this.pendingMismatches.delete(sid);
}
} }
if (res.changes > 0) this.emitChange(); if (res.changes > 0) this.emitChange();
return res.changes > 0; return res.changes > 0;
@ -331,29 +296,14 @@ export class KnownHostsService {
.prepare( .prepare(
`INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at) `INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at)
VALUES (?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(host_port, algorithm) DO UPDATE SET ON CONFLICT(host_port) DO UPDATE SET
algorithm = excluded.algorithm,
fingerprint = excluded.fingerprint, fingerprint = excluded.fingerprint,
updated_at = excluded.updated_at`, updated_at = excluded.updated_at`,
) )
.run(hostPortKey, algorithm, fingerprint, now, now); .run(hostPortKey, algorithm, fingerprint, now, now);
} }
private recordOpenSshKey(
server: Pick<ServerConfig, 'id' | 'host' | 'port'>,
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<ServerConfig, 'id'>): string | undefined {
return this.verifiedOpenSshKeys.get(server.id)?.line;
}
private emitChange(): void { private emitChange(): void {
for (const listener of this.listeners) { for (const listener of this.listeners) {
try { try {

View file

@ -4,7 +4,6 @@ import type { ClientChannel } from 'ssh2';
import { WS_CHANNELS } from '../../shared/ws-protocol.js'; import { WS_CHANNELS } from '../../shared/ws-protocol.js';
import type { WsHub } from '../api/ws-hub.js'; import type { WsHub } from '../api/ws-hub.js';
import type { ConfigManager } from '../config/config-manager.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 type { SSHPool } from './ssh-pool.js';
import { posixSingleQuote } from './sudo.js'; import { posixSingleQuote } from './sudo.js';
@ -35,34 +34,22 @@ export interface OpenPtyParams {
} }
interface ScrollChunk { interface ScrollChunk {
offsetMs: number;
text: string; text: string;
bytes: number; bytes: number;
} }
interface InternalPtySession { interface InternalPtySession {
info: PtySessionInfo; info: PtySessionInfo;
env?: Record<string, string>;
sudo?: boolean;
channel: ClientChannel; channel: ClientChannel;
chunks: ScrollChunk[]; chunks: ScrollChunk[];
stdoutDecoder: StringDecoder; stdoutDecoder: StringDecoder;
stderrDecoder: StringDecoder; stderrDecoder: StringDecoder;
} }
export function assertSafeCwd(cwd: string): string { const MAX_RETAINED_EXITED_SESSIONS = 20;
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;
}
export function formatRemoteCd(cwd: string): string { export function formatRemoteCd(cwd: string): string {
const trimmed = assertSafeCwd(cwd); const trimmed = cwd.trim();
if (trimmed === '~' || trimmed === '~/') { if (trimmed === '~' || trimmed === '~/') {
return 'cd -- "$HOME"'; return 'cd -- "$HOME"';
} }
@ -84,6 +71,7 @@ function sliceTrailingUtf8(text: string, maxBytes: number): { text: string; byte
return { text, bytes: buf.length }; return { text, bytes: buf.length };
} }
let start = buf.length - maxBytes; 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) { while (start < buf.length && (buf[start]! & 0b1100_0000) === 0b1000_0000) {
start++; start++;
} }
@ -99,7 +87,6 @@ export class PTYManager {
private readonly sshPool: SSHPool, private readonly sshPool: SSHPool,
private readonly configManager: ConfigManager, private readonly configManager: ConfigManager,
private readonly wsHub: WsHub, private readonly wsHub: WsHub,
private readonly getRuntimeLimits?: () => RuntimeLimits,
) { ) {
this.reaperTimer = setInterval(() => { this.reaperTimer = setInterval(() => {
this.reapIdleSessions(); this.reapIdleSessions();
@ -107,12 +94,14 @@ export class PTYManager {
this.reaperTimer.unref(); this.reaperTimer.unref();
} }
private async createChannel( async openSession(params: OpenPtyParams): Promise<PtySessionInfo> {
params: OpenPtyParams, const cols = Math.max(10, Math.min(500, Math.floor(params.cols ?? 80)));
cols: number, const rows = Math.max(4, Math.min(200, Math.floor(params.rows ?? 24)));
rows: number, const now = Date.now();
trimmedCwd?: string, const sessionId = `pty-${crypto.randomBytes(6).toString('hex')}`;
): Promise<ClientChannel> { const trimmedCwd = params.cwd?.trim();
let channel: ClientChannel;
if (params.command) { if (params.command) {
const cmd = trimmedCwd const cmd = trimmedCwd
? `${formatRemoteCd(trimmedCwd)} && (${params.command})` ? `${formatRemoteCd(trimmedCwd)} && (${params.command})`
@ -122,91 +111,18 @@ export class PTYManager {
sudo: params.sudo, sudo: params.sudo,
pty: { cols, rows, term: 'xterm-256color' }, pty: { cols, rows, term: 'xterm-256color' },
}); });
stream.done.catch(() => undefined); channel = stream.channel;
return stream.channel; } else {
} channel = await this.sshPool.openShell(params.serverId, {
if (trimmedCwd && trimmedCwd !== '~') {
const channel = await this.sshPool.openShell(params.serverId, {
cols, cols,
rows, rows,
term: 'xterm-256color', term: 'xterm-256color',
}); });
channel.write(`${formatRemoteCd(trimmedCwd)}\n`); if (trimmedCwd && trimmedCwd !== '~') {
return channel; 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<PtySessionInfo> {
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 = const title =
params.title?.trim() || params.title?.trim() ||
(params.command (params.command
@ -228,52 +144,48 @@ export class PTYManager {
exitCode: null, exitCode: null,
scrollbackBytes: 0, scrollbackBytes: 0,
}, },
env: params.env,
sudo: params.sudo,
channel, channel,
chunks: [], chunks: [],
stdoutDecoder: new StringDecoder('utf8'), stdoutDecoder: new StringDecoder('utf8'),
stderrDecoder: new StringDecoder('utf8'), stderrDecoder: new StringDecoder('utf8'),
}; };
this.sessions.set(sessionId, internal); 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<PtySessionInfo | null> { channel.stderr?.on('data', (chunk: Buffer) => {
const internal = this.sessions.get(sessionId); const text = internal.stderrDecoder.write(chunk);
if (!internal) return null; if (text) this.appendOutput(internal, text);
});
const oldChannel = internal.channel; const finalizeExit = (code: number | null) => {
const channel = await this.createChannel( if (internal.info.exited) return;
{ const tailOut = internal.stdoutDecoder.end();
serverId: internal.info.serverId, if (tailOut) this.appendOutput(internal, tailOut);
command: internal.info.command, const tailErr = internal.stderrDecoder.end();
env: internal.env, if (tailErr) this.appendOutput(internal, tailErr);
sudo: internal.sudo,
},
internal.info.cols,
internal.info.rows,
internal.info.cwd,
);
internal.channel = channel; internal.info.exited = true;
internal.stdoutDecoder = new StringDecoder('utf8'); internal.info.exitCode = code;
internal.stderrDecoder = new StringDecoder('utf8'); internal.info.lastActivityAt = Date.now();
internal.info.exited = false; this.wsHub.broadcastChannel(WS_CHANNELS.pty(sessionId), {
internal.info.exitCode = null; type: 'pty:exit',
internal.info.lastActivityAt = Date.now(); sessionId,
this.bindChannelHandlers(internal); exitCode: code,
});
this.pruneExcessExited();
};
try { channel.on('exit', (code: number | null) => {
oldChannel.close(); finalizeExit(typeof code === 'number' ? code : null);
oldChannel.destroy(); });
} catch { channel.on('close', () => {
// Ignore cleanup errors on prior channel finalizeExit(internal.info.exitCode);
} });
this.appendOutput(internal, '\r\n[gcoord: reconnected PTY session]\r\n');
return { ...internal.info }; return { ...internal.info };
} }
@ -303,6 +215,7 @@ export class PTYManager {
entry.info.cols = clampedCols; entry.info.cols = clampedCols;
entry.info.rows = clampedRows; entry.info.rows = clampedRows;
entry.info.lastActivityAt = Date.now(); entry.info.lastActivityAt = Date.now();
// @types/ssh2: Channel.setWindow(rows, cols, height, width)
entry.channel.setWindow(clampedRows, clampedCols, 0, 0); entry.channel.setWindow(clampedRows, clampedCols, 0, 0);
return true; return true;
} }
@ -315,34 +228,16 @@ export class PTYManager {
exportScrollback( exportScrollback(
sessionId: string, sessionId: string,
format: 'plain' | 'ansi' | 'cast' = 'plain', format: 'plain' | 'ansi' = 'plain',
): { filename: string; content: string; contentType: string } | null { ): { filename: string; content: string } | null {
const entry = this.sessions.get(sessionId); const entry = this.sessions.get(sessionId);
if (!entry) return null; 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 raw = entry.chunks.map((c) => c.text).join('');
const content = format === 'ansi' ? raw : stripAnsiSequences(raw); const content = format === 'ansi' ? raw : stripAnsiSequences(raw);
const ext = format === 'ansi' ? 'ansi.log' : 'txt'; const ext = format === 'ansi' ? 'ansi.log' : 'txt';
return { return {
filename: `${entry.info.serverId}-${sessionId}.${ext}`, filename: `${entry.info.serverId}-${sessionId}.${ext}`,
content, content,
contentType: 'text/plain; charset=utf-8',
}; };
} }
@ -380,22 +275,15 @@ export class PTYManager {
} }
private appendOutput(entry: InternalPtySession, text: string): void { private appendOutput(entry: InternalPtySession, text: string): void {
const configuredMax = this.configManager.getSettings().ptyScrollbackBytes; const maxBytes = Math.max(16_384, this.configManager.getSettings().ptyScrollbackBytes);
const runtimeCap = this.getRuntimeLimits?.()?.defaultPtyScrollbackBytes;
const maxBytes = Math.max(
16_384,
runtimeCap ? Math.min(configuredMax, runtimeCap) : configuredMax,
);
const rawBytes = Buffer.byteLength(text, 'utf8'); const rawBytes = Buffer.byteLength(text, 'utf8');
const now = Date.now();
const offsetMs = Math.max(0, now - entry.info.createdAt);
if (rawBytes >= maxBytes) { if (rawBytes >= maxBytes) {
const trimmed = sliceTrailingUtf8(text, 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; entry.info.scrollbackBytes = trimmed.bytes;
} else { } else {
entry.chunks.push({ offsetMs, text, bytes: rawBytes }); entry.chunks.push({ text, bytes: rawBytes });
entry.info.scrollbackBytes += rawBytes; entry.info.scrollbackBytes += rawBytes;
while (entry.info.scrollbackBytes > maxBytes && entry.chunks.length > 0) { while (entry.info.scrollbackBytes > maxBytes && entry.chunks.length > 0) {
const dropped = entry.chunks.shift()!; 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), { this.wsHub.broadcastChannel(WS_CHANNELS.pty(entry.info.sessionId), {
type: 'pty:output', type: 'pty:output',
sessionId: entry.info.sessionId, sessionId: entry.info.sessionId,
@ -432,11 +320,10 @@ export class PTYManager {
} }
private pruneExcessExited(): void { private pruneExcessExited(): void {
const maxRetained = this.getRuntimeLimits?.()?.maxRetainedExitedPtys ?? 12;
const exited = [...this.sessions.values()] const exited = [...this.sessions.values()]
.filter((s) => s.info.exited) .filter((s) => s.info.exited)
.sort((a, b) => a.info.lastActivityAt - b.info.lastActivityAt); .sort((a, b) => a.info.lastActivityAt - b.info.lastActivityAt);
while (exited.length > maxRetained) { while (exited.length > MAX_RETAINED_EXITED_SESSIONS) {
const oldest = exited.shift()!; const oldest = exited.shift()!;
this.sessions.delete(oldest.info.sessionId); this.sessions.delete(oldest.info.sessionId);
} }

View file

@ -17,7 +17,6 @@ export interface SftpListEntry {
mtimeMs: number; mtimeMs: number;
uid: number; uid: number;
gid: number; gid: number;
symlinkTarget?: string;
} }
export interface SftpTextFile { export interface SftpTextFile {
@ -34,8 +33,6 @@ export class SftpServiceError extends Error {
| 'NOT_FOUND' | 'NOT_FOUND'
| 'NOT_A_DIRECTORY' | 'NOT_A_DIRECTORY'
| 'IS_A_DIRECTORY' | 'IS_A_DIRECTORY'
| 'UNSUPPORTED_FILE_TYPE'
| 'ALREADY_EXISTS'
| 'FILE_TOO_LARGE' | 'FILE_TOO_LARGE'
| 'BINARY_FILE_NOT_EDITABLE' | 'BINARY_FILE_NOT_EDITABLE'
| 'CONFLICT' | 'CONFLICT'
@ -107,18 +104,9 @@ export class SftpService {
if (item.filename === '.' || item.filename === '..') continue; if (item.filename === '.' || item.filename === '..') continue;
const mode = item.attrs.mode ?? 0; const mode = item.attrs.mode ?? 0;
const type = modeToType(mode); const type = modeToType(mode);
const itemPath = path.posix.join(resolved, item.filename);
let symlinkTarget: string | undefined;
if (type === 'symlink') {
try {
symlinkTarget = await promisifySftp<string>((cb) => sftp.readlink(itemPath, cb));
} catch {
symlinkTarget = undefined;
}
}
entries.push({ entries.push({
name: item.filename, name: item.filename,
path: itemPath, path: path.posix.join(resolved, item.filename),
type, type,
size: item.attrs.size ?? 0, size: item.attrs.size ?? 0,
mode, mode,
@ -126,7 +114,6 @@ export class SftpService {
mtimeMs: (item.attrs.mtime ?? 0) * 1000, mtimeMs: (item.attrs.mtime ?? 0) * 1000,
uid: item.attrs.uid ?? 0, uid: item.attrs.uid ?? 0,
gid: item.attrs.gid ?? 0, gid: item.attrs.gid ?? 0,
...(symlinkTarget !== undefined ? { symlinkTarget } : {}),
}); });
} }
@ -144,28 +131,18 @@ export class SftpService {
async statPath(serverId: string, remotePath: string): Promise<SftpListEntry> { async statPath(serverId: string, remotePath: string): Promise<SftpListEntry> {
return this.withSftp(serverId, async (sftp) => { return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath); const resolved = await this.resolveRemotePath(sftp, remotePath);
const lstats = await promisifySftp<Stats>((cb) => sftp.lstat(resolved, cb)); const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
const mode = lstats.mode ?? 0; const mode = stats.mode ?? 0;
const type = modeToType(mode);
let symlinkTarget: string | undefined;
if (type === 'symlink') {
try {
symlinkTarget = await promisifySftp<string>((cb) => sftp.readlink(resolved, cb));
} catch {
symlinkTarget = undefined;
}
}
return { return {
name: path.posix.basename(resolved) || '/', name: path.posix.basename(resolved) || '/',
path: resolved, path: resolved,
type, type: modeToType(mode),
size: lstats.size ?? 0, size: stats.size ?? 0,
mode, mode,
permissionsOctal: (mode & 0o7777).toString(8).padStart(4, '0'), permissionsOctal: (mode & 0o7777).toString(8).padStart(4, '0'),
mtimeMs: (lstats.mtime ?? 0) * 1000, mtimeMs: (stats.mtime ?? 0) * 1000,
uid: lstats.uid ?? 0, uid: stats.uid ?? 0,
gid: lstats.gid ?? 0, gid: stats.gid ?? 0,
...(symlinkTarget !== undefined ? { symlinkTarget } : {}),
}; };
}); });
} }
@ -192,19 +169,12 @@ export class SftpService {
try { try {
const resolved = await this.resolveRemotePath(sftp, remotePath); const resolved = await this.resolveRemotePath(sftp, remotePath);
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb)); const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
const kind = modeToType(stats.mode); if (modeToType(stats.mode) === 'dir') {
if (kind === 'dir') {
throw new SftpServiceError( throw new SftpServiceError(
'IS_A_DIRECTORY', 'IS_A_DIRECTORY',
'Cannot download a directory as a single file; use /archive instead.', '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); const stream = sftp.createReadStream(resolved);
stream.once('close', cleanup); stream.once('close', cleanup);
stream.once('error', cleanup); stream.once('error', cleanup);
@ -229,14 +199,10 @@ export class SftpService {
): Promise<{ path: string; bytesWritten: number }> { ): Promise<{ path: string; bytesWritten: number }> {
return this.withSftp(serverId, async (sftp) => { return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath); const resolved = await this.resolveRemotePath(sftp, remotePath);
const tmpPath = path.posix.join( const dest = sftp.createWriteStream(resolved);
path.posix.dirname(resolved),
`.gcoord-up-${crypto.randomBytes(6).toString('hex')}`,
);
const dest = sftp.createWriteStream(tmpPath);
let bytesWritten = 0; let bytesWritten = 0;
await new Promise<void>((resolve, reject) => { return new Promise<{ path: string; bytesWritten: number }>((resolve, reject) => {
let settled = false; let settled = false;
const fail = (err: Error) => { const fail = (err: Error) => {
if (settled) return; if (settled) return;
@ -271,41 +237,11 @@ export class SftpService {
dest.on('close', () => { dest.on('close', () => {
if (settled) return; if (settled) return;
settled = true; settled = true;
resolve(); resolve({ path: resolved, bytesWritten });
}); });
source.pipe(dest); 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<string> {
return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath);
let exists = false;
try {
await promisifySftp<Stats>((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( async rename(serverId: string, fromPath: string, toPath: string): Promise<{ from: string; to: string }> {
serverId: string,
fromPath: string,
toPath: string,
overwrite = false,
): Promise<{ from: string; to: string }> {
return this.withSftp(serverId, async (sftp) => { return this.withSftp(serverId, async (sftp) => {
const resolvedFrom = await this.resolveRemotePath(sftp, fromPath); const resolvedFrom = await this.resolveRemotePath(sftp, fromPath);
const resolvedTo = await this.resolveRemotePath(sftp, toPath); const resolvedTo = await this.resolveRemotePath(sftp, toPath);
if (resolvedFrom === resolvedTo) { await this.renameSftpPath(sftp, resolvedFrom, resolvedTo);
return { from: resolvedFrom, to: resolvedTo };
}
if (!overwrite) {
let destExists = false;
try {
await promisifySftp<Stats>((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);
return { from: resolvedFrom, to: resolvedTo }; return { from: resolvedFrom, to: resolvedTo };
}); });
} }
async chmod( async chmod(serverId: string, remotePath: string, modeInput: string | number): Promise<{ path: string; permissionsOctal: string }> {
serverId: string,
remotePath: string,
modeInput: string | number,
): Promise<{ path: string; permissionsOctal: string }> {
const parsedMode = const parsedMode =
typeof modeInput === 'number' typeof modeInput === 'number'
? modeInput ? 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( async deletePath(
serverId: string, serverId: string,
remotePath: 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( async readTextFile(
serverId: string, serverId: string,
remotePath: string, remotePath: string,
@ -508,10 +341,7 @@ export class SftpService {
} }
const buf = Buffer.from(catRes.stdout, 'utf8'); const buf = Buffer.from(catRes.stdout, 'utf8');
if (buf.includes(0)) { if (buf.includes(0)) {
throw new SftpServiceError( throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor');
'BINARY_FILE_NOT_EDITABLE',
'Binary file cannot be opened in inline editor',
);
} }
return { return {
path: resolved, path: resolved,
@ -525,16 +355,9 @@ export class SftpService {
return this.withSftp(serverId, async (sftp) => { return this.withSftp(serverId, async (sftp) => {
const resolved = await this.resolveRemotePath(sftp, remotePath); const resolved = await this.resolveRemotePath(sftp, remotePath);
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb)); const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
const kind = modeToType(stats.mode); if (modeToType(stats.mode) === 'dir') {
if (kind === 'dir') {
throw new SftpServiceError('IS_A_DIRECTORY', `${resolved} is a directory`); 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) { if ((stats.size ?? 0) > maxBytes) {
throw new SftpServiceError( throw new SftpServiceError(
'FILE_TOO_LARGE', 'FILE_TOO_LARGE',
@ -546,10 +369,7 @@ export class SftpService {
throw new SftpServiceError('FILE_TOO_LARGE', 'File exceeds inline editor limit'); throw new SftpServiceError('FILE_TOO_LARGE', 'File exceeds inline editor limit');
} }
if (buf.includes(0)) { if (buf.includes(0)) {
throw new SftpServiceError( throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor');
'BINARY_FILE_NOT_EDITABLE',
'Binary file cannot be opened in inline editor',
);
} }
return { return {
path: resolved, path: resolved,
@ -592,7 +412,7 @@ export class SftpService {
const qTmp = posixSingleQuote(tmp); const qTmp = posixSingleQuote(tmp);
const res = await this.sshPool.exec( const res = await this.sshPool.exec(
serverId, 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 }, { sudo: true, stdin: newBuf },
); );
if (res.exitCode !== 0) { if (res.exitCode !== 0) {
@ -618,6 +438,7 @@ export class SftpService {
} }
} catch (err) { } catch (err) {
if (err instanceof SftpServiceError && err.code === 'CONFLICT') throw 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); const dir = path.posix.dirname(resolved);
@ -629,7 +450,7 @@ export class SftpService {
() => undefined, () => undefined,
); );
} }
await this.renameSftpPath(sftp, tmp, resolved, true); await this.renameSftpPath(sftp, tmp, resolved);
} catch (err) { } catch (err) {
await promisifySftpVoid((cb) => sftp.unlink(tmp, cb)).catch(() => undefined); await promisifySftpVoid((cb) => sftp.unlink(tmp, cb)).catch(() => undefined);
throw err; throw err;
@ -677,10 +498,8 @@ export class SftpService {
const safeName = (resolved === '/' ? 'root' : baseName).replace(/[^A-Za-z0-9._-]/g, '_'); const safeName = (resolved === '/' ? 'root' : baseName).replace(/[^A-Za-z0-9._-]/g, '_');
const archiveFileName = `${safeName}.${resolvedFormat}`; const archiveFileName = `${safeName}.${resolvedFormat}`;
const osDetected = this.sshPool.getState(serverId)?.osDetected; const compressCmd = resolvedFormat === 'tar.zst' ? 'zstd -T0 -c' : 'gzip -c';
const oneFsFlag = osDetected !== 'bsd' && osDetected !== 'macos' ? '--one-file-system ' : ''; const cmd = `set -o pipefail 2>/dev/null || true; tar -C ${posixSingleQuote(parentDir)} -cf - ${posixSingleQuote(baseName)} | ${compressCmd}`;
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 handle = await this.sshPool.execStream(serverId, cmd); const handle = await this.sshPool.execStream(serverId, cmd);
return { return {
@ -719,9 +538,6 @@ export class SftpService {
private async resolveRemotePath(sftp: SFTPWrapper, requestedPath?: string): Promise<string> { private async resolveRemotePath(sftp: SFTPWrapper, requestedPath?: string): Promise<string> {
const trimmed = requestedPath?.trim() ?? ''; 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 === '~') { if (!trimmed || trimmed === '.' || trimmed === '~') {
const home = await promisifySftp<string>((cb) => sftp.realpath('.', cb)); const home = await promisifySftp<string>((cb) => sftp.realpath('.', cb));
return path.posix.normalize(home || '/'); return path.posix.normalize(home || '/');
@ -741,12 +557,7 @@ export class SftpService {
sftp: SFTPWrapper, sftp: SFTPWrapper,
fromPath: string, fromPath: string,
toPath: string, toPath: string,
overwrite = false,
): Promise<void> { ): Promise<void> {
if (!overwrite) {
await promisifySftpVoid((cb) => sftp.rename(fromPath, toPath, cb));
return;
}
try { try {
await promisifySftpVoid((cb) => sftp.ext_openssh_rename(fromPath, toPath, cb)); await promisifySftpVoid((cb) => sftp.ext_openssh_rename(fromPath, toPath, cb));
} catch { } catch {

View file

@ -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<string>();
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 };
}

View file

@ -7,29 +7,13 @@ import ssh2, {
} from 'ssh2'; } from 'ssh2';
import type { ServerConfig } from '../../shared/schemas/server.schema.js'; import type { ServerConfig } from '../../shared/schemas/server.schema.js';
import type { import type {
HostKeyAlert,
ServerConnectionStatus, ServerConnectionStatus,
ServerRuntimeState, ServerRuntimeState,
} from '../../shared/ws-protocol.js'; } from '../../shared/ws-protocol.js';
import type { ConfigManager } from '../config/config-manager.js'; import type { ConfigManager } from '../config/config-manager.js';
import type { VaultService } from '../security/vault.js'; import type { VaultService } from '../security/vault.js';
import type { KnownHostsService } from './known-hosts.js'; import type { KnownHostsService } from './known-hosts.js';
import { import { buildEnvPrefix, prepareSudoExecution } from './sudo.js';
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;
}
export interface ExecResult { export interface ExecResult {
stdout: string; stdout: string;
@ -74,9 +58,6 @@ const DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
export class SSHPool { export class SSHPool {
private readonly connections = new Map<string, PooledConnection>(); private readonly connections = new Map<string, PooledConnection>();
private readonly inFlight = new Map<string, Promise<Client>>(); private readonly inFlight = new Map<string, Promise<Client>>();
private readonly pendingClients = new Map<string, Set<Client>>();
private readonly serverEpoch = new Map<string, number>();
private poolEpoch = 0;
private readonly states = new Map<string, ServerRuntimeState>(); private readonly states = new Map<string, ServerRuntimeState>();
private readonly reconnectTimers = new Map<string, NodeJS.Timeout>(); private readonly reconnectTimers = new Map<string, NodeJS.Timeout>();
private readonly reconnectAttempts = new Map<string, number>(); private readonly reconnectAttempts = new Map<string, number>();
@ -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<string>();
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 { onStateChange(listener: (states: ServerRuntimeState[]) => void): () => void {
this.stateListeners.add(listener); this.stateListeners.add(listener);
return () => { return () => {
@ -169,7 +132,6 @@ export class SSHPool {
if (visited.has(serverId)) { if (visited.has(serverId)) {
throw new Error(`ProxyJump cycle detected involving "${serverId}"`); throw new Error(`ProxyJump cycle detected involving "${serverId}"`);
} }
this.validateJumpChain(serverId);
const existing = this.connections.get(serverId); const existing = this.connections.get(serverId);
if (existing) { if (existing) {
@ -183,42 +145,19 @@ export class SSHPool {
const nextVisited = new Set(visited); const nextVisited = new Set(visited);
nextVisited.add(serverId); nextVisited.add(serverId);
const startPoolEpoch = this.poolEpoch;
const startSrvEpoch = this.getServerEpoch(serverId);
const connectPromise = this.connectServer( const connectPromise = this.connectServer(server, nextVisited).finally(() => {
server, this.inFlight.delete(serverId);
nextVisited,
startPoolEpoch,
startSrvEpoch,
).finally(() => {
if (this.inFlight.get(serverId) === connectPromise) {
this.inFlight.delete(serverId);
}
}); });
this.inFlight.set(serverId, connectPromise); this.inFlight.set(serverId, connectPromise);
return 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( private prepareCommand(
server: ServerConfig, server: ServerConfig,
command: string, command: string,
opts: { opts: { sudo?: boolean; env?: Record<string, string>; stdin?: Buffer | string },
sudo?: boolean; ): { finalCommand: string; stdinBuf?: Buffer } {
env?: Record<string, string>;
stdin?: Buffer | string;
ptyPrompt?: boolean;
},
): { finalCommand: string; stdinBuf?: Buffer; ptyPassword?: string } {
const envPrefix = buildEnvPrefix(opts.env); const envPrefix = buildEnvPrefix(opts.env);
let finalCommand = `${envPrefix}${command}`; let finalCommand = `${envPrefix}${command}`;
let stdinBuf: Buffer | undefined = let stdinBuf: Buffer | undefined =
@ -229,16 +168,20 @@ export class SSHPool {
: Buffer.from(opts.stdin); : Buffer.from(opts.stdin);
if (opts.sudo) { 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, { const prepared = prepareSudoExecution(finalCommand, {
sudoPassword, sudoPassword,
stdin: stdinBuf, stdin: stdinBuf,
ptyPrompt: opts.ptyPrompt,
}); });
if (stdinBuf) stdinBuf.fill(0); if (stdinBuf) stdinBuf.fill(0);
finalCommand = prepared.command; finalCommand = prepared.command;
stdinBuf = prepared.stdin; stdinBuf = prepared.stdin;
return { finalCommand, stdinBuf, ptyPassword: prepared.ptyPassword };
} }
return { finalCommand, stdinBuf }; return { finalCommand, stdinBuf };
@ -285,10 +228,7 @@ export class SSHPool {
throw new Error(`Unknown server "${serverId}"`); throw new Error(`Unknown server "${serverId}"`);
} }
const { finalCommand, stdinBuf, ptyPassword } = this.prepareCommand(server, command, { const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts);
...opts,
ptyPrompt: Boolean(opts.pty),
});
return new Promise<ExecStreamHandle>((resolve, reject) => { return new Promise<ExecStreamHandle>((resolve, reject) => {
const execOpts = opts.pty const execOpts = opts.pty
@ -308,21 +248,6 @@ export class SSHPool {
return; 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 exitCode: number | null = null;
let signal: string | undefined; let signal: string | undefined;
const done = new Promise<{ exitCode: number | null; signal?: string }>( const done = new Promise<{ exitCode: number | null; signal?: string }>(
@ -378,94 +303,10 @@ export class SSHPool {
throw new Error(`Unknown server "${serverId}"`); 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); const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts);
return this.execRaw(client, serverId, finalCommand, stdinBuf, opts.timeoutMs, opts.maxBytes);
}
private execRaw( const timeoutMs = opts.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS;
client: Client, const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
serverId: string,
finalCommand: string,
stdinBuf: Buffer | undefined,
timeoutMs = DEFAULT_EXEC_TIMEOUT_MS,
maxBytes = DEFAULT_MAX_BYTES,
): Promise<ExecResult> {
const started = Date.now(); const started = Date.now();
return new Promise<ExecResult>((resolve, reject) => { return new Promise<ExecResult>((resolve, reject) => {
@ -500,7 +341,6 @@ export class SSHPool {
reject(new Error(`SSH exec timed out after ${timeoutMs}ms on "${serverId}"`)), reject(new Error(`SSH exec timed out after ${timeoutMs}ms on "${serverId}"`)),
); );
}, timeoutMs); }, timeoutMs);
timer.unref();
if (stdinBuf && stdinBuf.length > 0) { if (stdinBuf && stdinBuf.length > 0) {
stream.stdin.write(stdinBuf); stream.stdin.write(stdinBuf);
@ -661,112 +501,6 @@ export class SSHPool {
} }
} }
async testConnection(candidate: ServerConfig): Promise<ServerTestResult> {
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<void>((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<Client> { async reconnect(serverId: string): Promise<Client> {
this.closeServer(serverId); this.closeServer(serverId);
this.reconnectAttempts.delete(serverId); this.reconnectAttempts.delete(serverId);
@ -808,27 +542,12 @@ export class SSHPool {
} }
closeServer(serverId: string): void { closeServer(serverId: string): void {
this.serverEpoch.set(serverId, this.getServerEpoch(serverId) + 1);
this.inFlight.delete(serverId);
const timer = this.reconnectTimers.get(serverId); const timer = this.reconnectTimers.get(serverId);
if (timer) { if (timer) {
clearTimeout(timer); clearTimeout(timer);
this.reconnectTimers.delete(serverId); 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); const conn = this.connections.get(serverId);
if (!conn) return; if (!conn) return;
@ -855,9 +574,7 @@ export class SSHPool {
} }
} }
closeAll(reason: 'panic_lock' | 'shutdown' | 'vault_sealed'): void { closeAll(reason: 'panic_lock' | 'shutdown'): void {
this.poolEpoch += 1;
this.inFlight.clear();
if (reason === 'shutdown') { if (reason === 'shutdown') {
this.closed = true; this.closed = true;
} }
@ -867,29 +584,16 @@ export class SSHPool {
} }
this.reconnectTimers.clear(); 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()]) { for (const id of [...this.connections.keys()]) {
this.closeServer(id); this.closeServer(id);
} }
if (reason === 'panic_lock' || reason === 'vault_sealed') { if (reason === 'panic_lock') {
const msg = reason === 'panic_lock' ? 'Panic Lock engaged' : 'Vault sealed';
for (const server of this.configManager.listServers()) { for (const server of this.configManager.listServers()) {
this.states.set(server.id, { this.states.set(server.id, {
serverId: server.id, serverId: server.id,
status: server.enabled ? 'vault_locked' : 'disabled', status: server.enabled ? 'vault_locked' : 'disabled',
lastError: server.enabled ? msg : undefined, lastError: server.enabled ? 'Panic Lock engaged' : undefined,
}); });
} }
this.emitStates(); this.emitStates();
@ -899,8 +603,6 @@ export class SSHPool {
private async connectServer( private async connectServer(
server: ServerConfig, server: ServerConfig,
visited: Set<string>, visited: Set<string>,
startPoolEpoch: number,
startSrvEpoch: number,
): Promise<Client> { ): Promise<Client> {
const cred = this.vaultService.getRuntimeSecret(server.credentialId); const cred = this.vaultService.getRuntimeSecret(server.credentialId);
if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) { if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) {
@ -914,14 +616,6 @@ export class SSHPool {
let hopStream: Duplex | undefined; let hopStream: Duplex | undefined;
if (server.jumpHostId) { if (server.jumpHostId) {
const bastion = await this.acquireClient(server.jumpHostId, visited); 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( hopStream = await forwardOutOnClient(
bastion, bastion,
'127.0.0.1', '127.0.0.1',
@ -933,20 +627,6 @@ export class SSHPool {
const settings = this.configManager.getSettings(); const settings = this.configManager.getSettings();
const client = new ssh2.Client(); 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<Client>((resolve, reject) => { return new Promise<Client>((resolve, reject) => {
let settled = false; let settled = false;
@ -954,7 +634,6 @@ export class SSHPool {
const failConnect = (err: Error) => { const failConnect = (err: Error) => {
if (settled) return; if (settled) return;
settled = true; settled = true;
untrackPending();
hopStream?.destroy(); hopStream?.destroy();
try { try {
client.destroy(); client.destroy();
@ -962,16 +641,6 @@ export class SSHPool {
// Ignore destroy failure // 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 mismatch = this.knownHosts.getPendingMismatch(server.id);
const tofu = this.knownHosts.getPendingTofu(server.id); const tofu = this.knownHosts.getPendingTofu(server.id);
let status: ServerConnectionStatus = 'disconnected'; let status: ServerConnectionStatus = 'disconnected';
@ -994,23 +663,8 @@ export class SSHPool {
}; };
client.once('ready', () => { client.once('ready', () => {
untrackPending(); if (settled) {
const invalidated = client.end();
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'));
return; return;
} }
settled = true; 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 = { const cfg: ConnectConfig = {
username: server.username, username: server.username,
keepaliveInterval: settings.sshKeepaliveMs, keepaliveInterval: settings.sshKeepaliveMs,

View file

@ -1,5 +1,3 @@
export const SUDO_PTY_PROMPT = '[gcoord-sudo-prompt] ';
export function posixSingleQuote(value: string): string { export function posixSingleQuote(value: string): string {
return `'${value.replace(/'/g, "'\\''")}'`; return `'${value.replace(/'/g, "'\\''")}'`;
} }
@ -18,31 +16,13 @@ export function buildEnvPrefix(env?: Record<string, string>): string {
export function prepareSudoExecution( export function prepareSudoExecution(
command: string, command: string,
options: { options: { sudoPassword?: string; stdin?: Buffer | string } = {},
sudoPassword?: string; ): { command: string; stdin?: Buffer } {
stdin?: Buffer | string;
ptyPrompt?: boolean;
} = {},
): { command: string; stdin?: Buffer; ptyPassword?: string } {
const quoted = posixSingleQuote(command); const quoted = posixSingleQuote(command);
if (options.sudoPassword !== undefined && options.sudoPassword.length > 0) { 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'); const pwPrefix = Buffer.from(`${options.sudoPassword}\n`, 'utf8');
let combined = pwPrefix; let combined = pwPrefix;
if (options.stdin !== undefined && options.stdin.length > 0) { if (options.stdin !== undefined) {
const extra = const extra =
typeof options.stdin === 'string' typeof options.stdin === 'string'
? Buffer.from(options.stdin, 'utf8') ? Buffer.from(options.stdin, 'utf8')
@ -51,7 +31,7 @@ export function prepareSudoExecution(
pwPrefix.fill(0); pwPrefix.fill(0);
} }
return { return {
command: `sudo -S -k -p '' sh -c ${quoted}`, command: `sudo -S -p '' sh -c ${quoted}`,
stdin: combined, stdin: combined,
}; };
} }

File diff suppressed because it is too large Load diff

View file

@ -17,7 +17,6 @@ export interface ParsedStatusResult {
subItems: ParsedSubItem[]; subItems: ParsedSubItem[];
rawSummary: string; rawSummary: string;
exitCode: number | null; exitCode: number | null;
raw?: Record<string, unknown>;
} }
export interface ScannedFolderMatch { export interface ScannedFolderMatch {
@ -26,11 +25,10 @@ export interface ScannedFolderMatch {
} }
export function globToRegExp(pattern: string): RegExp { export function globToRegExp(pattern: string): RegExp {
const collapsed = pattern.slice(0, 128).replace(/\*+/g, '*'); const escaped = pattern
const escaped = collapsed
.replace(/[.+^${}()|[\]\\]/g, '\\$&') .replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '[^/]*') .replace(/\*/g, '.*')
.replace(/\?/g, '[^/]'); .replace(/\?/g, '.');
return new RegExp(`^${escaped}$`); return new RegExp(`^${escaped}$`);
} }
@ -316,7 +314,6 @@ export function parseStatusOutput(
subItems: [], subItems: [],
rawSummary: summarizeRecord(rec), rawSummary: summarizeRecord(rec),
exitCode, exitCode,
raw: rec,
}; };
} }
} catch { } catch {
@ -330,16 +327,15 @@ export function parseStatusOutput(
} }
if (statusCfg.parser === 'regex') { 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 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 const exitOk = statusCfg.health?.healthyExitCodes
? exitCode !== null && statusCfg.health.healthyExitCodes.includes(exitCode) ? exitCode !== null && statusCfg.health.healthyExitCodes.includes(exitCode)
: exitCode === null || exitCode === 0; : exitCode === null || exitCode === 0;
return { return {
health: exitOk && matched ? 'ok' : 'down', health: exitOk && matched ? 'ok' : 'down',
subItems: [], subItems: [],
rawSummary: bounded.split(/\r?\n/).slice(0, 4).join(' | '), rawSummary: trimmed.split(/\r?\n/).slice(0, 4).join(' | '),
exitCode, exitCode,
}; };
} }

View file

@ -5,7 +5,6 @@ import type { SystemAction, SystemConfig } from '../../shared/schemas/system.sch
import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js';
import type { WsHub } from '../api/ws-hub.js'; import type { WsHub } from '../api/ws-hub.js';
import type { ConfigManager } from '../config/config-manager.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 { VaultService } from '../security/vault.js';
import type { PTYManager, PtySessionInfo } from '../ssh/pty-manager.js'; import type { PTYManager, PtySessionInfo } from '../ssh/pty-manager.js';
import type { SSHPool } from '../ssh/ssh-pool.js'; import type { SSHPool } from '../ssh/ssh-pool.js';
@ -65,65 +64,19 @@ interface ActiveStreamJob {
bufferBytes: number; bufferBytes: number;
done: boolean; done: boolean;
abort: () => void; abort: () => void;
timeoutTimer?: NodeJS.Timeout;
idleTimer?: NodeJS.Timeout;
} }
const MAX_STREAM_REPLAY_BYTES = 128 * 1024;
const MAX_RETAINED_DONE_STREAMS = 25; 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 { export function isValidRelativeOverlayFile(fileName: string): boolean {
const clean = fileName.trim(); const clean = fileName.trim();
if (!clean || clean.length > 255) return false; if (!clean) return false;
if (FORBIDDEN_KEYS.has(clean)) return false; if (clean.includes('/') || clean.includes('\\') || clean.includes('..')) return false;
if (clean.startsWith('-') || clean.includes('/') || clean.includes('\\') || clean.includes('..')) { if (/[\s'"$;|&<>()`]/.test(clean)) return false;
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;
return true; 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<T, R>(
items: T[],
concurrency: number,
worker: (item: T) => Promise<R>,
): Promise<R[]> {
if (items.length === 0) return [];
const cap = Math.max(1, Math.min(items.length, concurrency));
const results = new Array<R>(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 { function expandShellRoot(root: string): string {
const trimmed = root.trim(); const trimmed = root.trim();
if (trimmed === '~' || trimmed === '~/') return '"$HOME"'; if (trimmed === '~' || trimmed === '~/') return '"$HOME"';
@ -132,27 +85,20 @@ function expandShellRoot(root: string): string {
} }
function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: 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 rootArgs = roots.map(expandShellRoot).join(' ');
const casePatterns = const casePatterns = matchFiles
matchFiles .map((p) => p.replace(/[^A-Za-z0-9._*?[\]-]/g, ''))
.map((p) => p.replace(/[^A-Za-z0-9._*?-]/g, '')) .filter(Boolean)
.filter((p) => p && !p.startsWith('-')) .join('|') || '*';
.slice(0, 32)
.join('|') || '*';
return [ return [
`TAB=$(printf '\\t'); CR=$(printf '\\r')`,
`for r in ${rootArgs}; do`, `for r in ${rootArgs}; do`,
` case "$r" in -*) r="./$r" ;; esac`,
` [ -d "$r" ] || continue`, ` [ -d "$r" ] || continue`,
` find "$r" -maxdepth ${safeDepth} -type d 2>/dev/null | while IFS= read -r d; do`, ` find "$r" -maxdepth ${maxDepth} -type d 2>/dev/null | while IFS= read -r d; do`,
` case "$d" in *"$TAB"*|*"$CR"*) continue ;; esac`,
` matched=0`, ` matched=0`,
` for f in "$d"/* "$d"/.*; do`, ` for f in "$d"/* "$d"/.*; do`,
` [ -f "$f" ] || continue`, ` [ -f "$f" ] || continue`,
` b=\${f##*/}`, ` b=\${f##*/}`,
` [ "$b" = "." ] || [ "$b" = ".." ] && continue`,
` case "$b" in`, ` case "$b" in`,
` ${casePatterns}) matched=1; break ;;`, ` ${casePatterns}) matched=1; break ;;`,
` esac`, ` esac`,
@ -170,16 +116,6 @@ function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: st
].join('\n'); ].join('\n');
} }
function substituteActionInputs(
command: string,
inputs: Record<string, string>,
): 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 { export class CustomSystemsEngine {
private readonly cache = new Map<string, ServerSystemSnapshot>(); private readonly cache = new Map<string, ServerSystemSnapshot>();
private readonly streamJobs = new Map<string, ActiveStreamJob>(); private readonly streamJobs = new Map<string, ActiveStreamJob>();
@ -192,7 +128,6 @@ export class CustomSystemsEngine {
private readonly vaultService: VaultService, private readonly vaultService: VaultService,
private readonly ptyManager: PTYManager, private readonly ptyManager: PTYManager,
private readonly wsHub: WsHub, private readonly wsHub: WsHub,
private readonly getRuntimeLimits?: () => RuntimeLimits,
) {} ) {}
onHealthSnapshot(listener: (snapshot: ServerSystemSnapshot) => void): () => void { 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[] { getStreamReplayFrames(jobId: string): ServerWsFrame[] {
const job = this.streamJobs.get(jobId); const job = this.streamJobs.get(jobId);
return job ? [...job.frames] : []; return job ? [...job.frames] : [];
@ -269,12 +199,10 @@ export class CustomSystemsEngine {
.filter((s) => s.enabled && s.systems.some((a) => a.systemId === systemId)) .filter((s) => s.enabled && s.systems.some((a) => a.systemId === systemId))
.filter((s) => !opts.serverId || s.id === opts.serverId); .filter((s) => !opts.serverId || s.id === opts.serverId);
const concurrency = Math.max( const snapshots = await Promise.all(
1, targets.map((srv) =>
this.getRuntimeLimits?.().maxParallelSystemInspect ?? 2, this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }),
); ),
const snapshots = await runPool(targets, concurrency, (srv) =>
this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }),
); );
return { system, snapshots }; return { system, snapshots };
@ -319,7 +247,7 @@ export class CustomSystemsEngine {
'ok', 'ok',
), ),
}; };
this.setCacheBounded(cacheKey, snapshot); this.cache.set(cacheKey, snapshot);
this.emitHealth(snapshot); this.emitHealth(snapshot);
return snapshot; return snapshot;
} catch (err) { } catch (err) {
@ -333,68 +261,16 @@ export class CustomSystemsEngine {
items: [], items: [],
systemHealth: 'down', systemHealth: 'down',
}; };
this.emitHealth(snapshot);
return snapshot; return snapshot;
} }
} }
private resolveActionInputs(
action: SystemAction,
suppliedInputs?: Record<string, unknown>,
): { resolved: Record<string, string>; secretNames: Set<string> } {
const supplied = suppliedInputs ?? {};
for (const k of Object.keys(supplied)) {
assertSafeKey(k, 'input parameter');
}
const resolved: Record<string, string> = {};
const secretNames = new Set<string>();
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: { private resolveActionContext(params: {
serverId: string; serverId: string;
systemId: string; systemId: string;
actionId: string; actionId: string;
itemName?: string; itemName?: string;
subItemName?: string; subItemName?: string;
inputs?: Record<string, unknown>;
}) { }) {
return (async () => { return (async () => {
const system = this.configManager.getSystem(params.systemId); 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}"`); 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 resolvedParams = this.resolveParams(system, attachment.params);
const { resolved: actionInputs } = this.resolveActionInputs(action, params.inputs);
let item: DiscoveredSystemItem | undefined; let item: DiscoveredSystemItem | undefined;
if (action.scope === 'item' || action.scope === 'subitem') { if (action.scope === 'item' || action.scope === 'subitem') {
@ -429,18 +299,8 @@ export class CustomSystemsEngine {
if (!item) { if (!item) {
throw new Error(`Item "${params.itemName}" not found under ${server.id}/${system.id}`); throw new Error(`Item "${params.itemName}" not found under ${server.id}/${system.id}`);
} }
if (action.scope === 'subitem') { if (action.scope === 'subitem' && !params.subItemName) {
if (!params.subItemName) { throw new Error(`Action "${action.id}" requires 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}"`,
);
}
} }
} }
@ -450,15 +310,13 @@ export class CustomSystemsEngine {
resolvedParams, resolvedParams,
item, item,
params.subItemName, params.subItemName,
actionInputs,
); );
const substitutedCmd = substituteActionInputs(action.command, actionInputs);
const execCmd = item?.dir const execCmd = item?.dir
? `cd -- ${posixSingleQuote(item.dir)} && ${substitutedCmd}` ? `cd -- ${posixSingleQuote(item.dir)} && ${action.command}`
: substitutedCmd; : 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; actionId: string;
itemName?: string; itemName?: string;
subItemName?: string; subItemName?: string;
inputs?: Record<string, unknown>;
timeoutMs?: number; timeoutMs?: number;
signal?: AbortSignal; signal?: AbortSignal;
onChunk?: (stream: 'stdout' | 'stderr', text: string) => void; 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'); 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 started = Date.now();
const handle = await this.sshPool.execStream(server.id, execCmd, { const handle = await this.sshPool.execStream(server.id, execCmd, {
env, env,
@ -577,18 +434,17 @@ export class CustomSystemsEngine {
actionId: string; actionId: string;
itemName?: string; itemName?: string;
subItemName?: string; subItemName?: string;
inputs?: Record<string, unknown>;
cols?: number; cols?: number;
rows?: number; rows?: number;
}): Promise<ActionExecutionResult> { }): Promise<ActionExecutionResult> {
const { system, server, action, item, env, execCmd, substitutedCmd } = const { system, server, action, item, env, execCmd } =
await this.resolveActionContext(params); await this.resolveActionContext(params);
if (action.mode === 'oneshot') { if (action.mode === 'oneshot') {
const res = await this.sshPool.exec(server.id, execCmd, { const res = await this.sshPool.exec(server.id, execCmd, {
env, env,
sudo: action.sudo, sudo: action.sudo,
timeoutMs: (action.timeoutSec ?? 120) * 1000, timeoutMs: 120_000,
}); });
this.invalidateCache(server.id, system.id); this.invalidateCache(server.id, system.id);
return { return {
@ -604,7 +460,7 @@ export class CustomSystemsEngine {
const session = await this.ptyManager.openSession({ const session = await this.ptyManager.openSession({
serverId: server.id, serverId: server.id,
cwd: item?.dir, cwd: item?.dir,
command: substitutedCmd, command: action.command,
env, env,
sudo: action.sudo, sudo: action.sudo,
cols: params.cols, cols: params.cols,
@ -615,14 +471,13 @@ export class CustomSystemsEngine {
return { mode: 'interactive', session }; return { mode: 'interactive', session };
} }
// Stream mode with timeout & idle reaper // Stream mode
const jobId = `stream-${crypto.randomBytes(6).toString('hex')}`; const jobId = `stream-${crypto.randomBytes(6).toString('hex')}`;
const handle = await this.sshPool.execStream(server.id, execCmd, { const handle = await this.sshPool.execStream(server.id, execCmd, {
env, env,
sudo: action.sudo, sudo: action.sudo,
}); });
const maxReplayBytes = this.getRuntimeLimits?.().streamReplayBytes ?? 128 * 1024;
const job: ActiveStreamJob = { const job: ActiveStreamJob = {
jobId, jobId,
serverId: server.id, serverId: server.id,
@ -634,23 +489,12 @@ export class CustomSystemsEngine {
}; };
this.streamJobs.set(jobId, job); 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 pushFrame = (stream: 'stdout' | 'stderr' | 'meta', data: string) => {
const frame: ServerWsFrame = { type: 'stream:chunk', jobId, stream, data }; const frame: ServerWsFrame = { type: 'stream:chunk', jobId, stream, data };
const bytes = Buffer.byteLength(data, 'utf8'); const bytes = Buffer.byteLength(data, 'utf8');
job.frames.push(frame); job.frames.push(frame);
job.bufferBytes += bytes; 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()!; const dropped = job.frames.shift()!;
if (dropped.type === 'stream:chunk') { if (dropped.type === 'stream:chunk') {
job.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8'); job.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8');
@ -659,28 +503,6 @@ export class CustomSystemsEngine {
this.wsHub.broadcastChannel(WS_CHANNELS.stream(jobId), frame); 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( pushFrame(
'meta', 'meta',
JSON.stringify({ JSON.stringify({
@ -694,25 +516,21 @@ export class CustomSystemsEngine {
); );
handle.channel.on('data', (chunk: Buffer) => { handle.channel.on('data', (chunk: Buffer) => {
bumpIdleTimer();
pushFrame('stdout', chunk.toString('utf8')); pushFrame('stdout', chunk.toString('utf8'));
}); });
handle.channel.stderr?.on('data', (chunk: Buffer) => { handle.channel.stderr?.on('data', (chunk: Buffer) => {
bumpIdleTimer();
pushFrame('stderr', chunk.toString('utf8')); pushFrame('stderr', chunk.toString('utf8'));
}); });
void handle.done void handle.done
.then(({ exitCode, signal }) => { .then(({ exitCode, signal }) => {
job.done = true; job.done = true;
clearJobTimers();
this.invalidateCache(server.id, system.id); this.invalidateCache(server.id, system.id);
pushFrame('meta', JSON.stringify({ event: 'exit', exitCode, signal })); pushFrame('meta', JSON.stringify({ event: 'exit', exitCode, signal }));
this.pruneStreamJobs(); this.pruneStreamJobs();
}) })
.catch((err) => { .catch((err) => {
job.done = true; job.done = true;
clearJobTimers();
this.invalidateCache(server.id, system.id); this.invalidateCache(server.id, system.id);
pushFrame( pushFrame(
'meta', 'meta',
@ -738,11 +556,10 @@ export class CustomSystemsEngine {
throw new Error(`Unknown server "${serverId}" or system "${systemId}"`); 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 existing = server.systems.find((a) => a.systemId === systemId);
const nextSystems = existing const nextSystems = existing
? server.systems.map((a) => (a.systemId === systemId ? { ...a, params: validatedParams } : a)) ? server.systems.map((a) => (a.systemId === systemId ? { ...a, params } : a))
: [...server.systems, { systemId, params: validatedParams, itemOverrides: {} }]; : [...server.systems, { systemId, params, itemOverrides: {} }];
const updated: ServerConfig = { ...server, systems: nextSystems }; const updated: ServerConfig = { ...server, systems: nextSystems };
this.configManager.saveConfigText( this.configManager.saveConfigText(
@ -782,38 +599,18 @@ export class CustomSystemsEngine {
itemName: string, itemName: string,
activeFiles: string[], activeFiles: string[],
): ServerConfig { ): ServerConfig {
assertSafeKey(itemName, 'itemName');
const system = this.configManager.getSystem(systemId);
const server = this.configManager.getServer(serverId); const server = this.configManager.getServer(serverId);
if (!system || !server) { if (!server) {
throw new Error(`Unknown server "${serverId}" or system "${systemId}"`); 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) { if (cleanFiles.length === 0) {
throw new Error('At least one active file must be selected'); 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) { for (const file of cleanFiles) {
if (!isValidRelativeOverlayFile(file)) { if (!isValidRelativeOverlayFile(file)) {
throw new Error(`Invalid overlay filename: "${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); const hasAtt = server.systems.some((a) => a.systemId === systemId);
@ -823,20 +620,20 @@ export class CustomSystemsEngine {
const updated: ServerConfig = { const updated: ServerConfig = {
...server, ...server,
systems: server.systems.map((att) => { systems: server.systems.map((att) =>
if (att.systemId !== systemId) return att; att.systemId === systemId
const safeOverrides: Record<string, { activeFiles?: string[]; [k: string]: unknown }> = ? {
Object.create(null); ...att,
for (const [k, v] of Object.entries(att.itemOverrides ?? {})) { itemOverrides: {
if (FORBIDDEN_KEYS.has(k)) continue; ...att.itemOverrides,
safeOverrides[k] = v; [itemName]: {
} ...(att.itemOverrides[itemName] ?? {}),
safeOverrides[itemName] = { activeFiles: cleanFiles,
...(Object.hasOwn(att.itemOverrides, itemName) ? att.itemOverrides[itemName] : {}), },
activeFiles: cleanFiles, },
}; }
return { ...att, itemOverrides: safeOverrides }; : att,
}), ),
}; };
this.configManager.saveConfigText( this.configManager.saveConfigText(
@ -882,8 +679,6 @@ export class CustomSystemsEngine {
for (const job of this.streamJobs.values()) { for (const job of this.streamJobs.values()) {
if (!job.done) { if (!job.done) {
job.done = true; job.done = true;
if (job.timeoutTimer) clearTimeout(job.timeoutTimer);
if (job.idleTimer) clearTimeout(job.idleTimer);
job.abort(); job.abort();
} }
} }
@ -895,17 +690,6 @@ export class CustomSystemsEngine {
this.cache.clear(); 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( private async discoverAndInspectItems(
server: ServerConfig, server: ServerConfig,
system: SystemConfig, system: SystemConfig,
@ -913,10 +697,6 @@ export class CustomSystemsEngine {
params: Record<string, unknown>, params: Record<string, unknown>,
): Promise<DiscoveredSystemItem[]> { ): Promise<DiscoveredSystemItem[]> {
const baseEnv = this.buildExecutionEnv(server.id, system.id, params); const baseEnv = this.buildExecutionEnv(server.id, system.id, params);
const concurrency = Math.max(
1,
this.getRuntimeLimits?.().maxParallelSystemInspect ?? 2,
);
if (system.discovery.type === 'folder-scan') { if (system.discovery.type === 'folder-scan') {
const rawRoots = params[system.discovery.rootsParam]; const rawRoots = params[system.discovery.rootsParam];
@ -933,7 +713,7 @@ export class CustomSystemsEngine {
system.discovery.matchFiles, system.discovery.matchFiles,
); );
const scanRes = await this.sshPool.exec(server.id, script, { env: baseEnv }); 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 matchRegexes = system.discovery.matchFiles.map(globToRegExp);
const selectableRegexes = ( const selectableRegexes = (
@ -944,45 +724,33 @@ export class CustomSystemsEngine {
.map(globToRegExp); .map(globToRegExp);
const usedNames = new Map<string, number>(); const usedNames = new Map<string, number>();
const draftItems: DiscoveredSystemItem[] = []; const items: DiscoveredSystemItem[] = [];
for (const m of rawMatches) { for (const m of rawMatches) {
if (/[\x00-\x1f\x7f]/.test(m.dir)) continue; const matchedFiles = m.files.filter((f) => matchRegexes.some((re) => re.test(f)));
const safeFiles = m.files.filter(
(f) => !/[\x00-\x1f\x7f]/.test(f) && !f.startsWith('-'),
);
const matchedFiles = safeFiles.filter((f) => matchRegexes.some((re) => re.test(f)));
if (matchedFiles.length === 0) continue; if (matchedFiles.length === 0) continue;
let baseName = path.posix.basename(m.dir) || 'root'; let baseName = path.posix.basename(m.dir) || 'root';
if (FORBIDDEN_KEYS.has(baseName)) baseName = `item-${baseName}`;
const seenCount = (usedNames.get(baseName) ?? 0) + 1; const seenCount = (usedNames.get(baseName) ?? 0) + 1;
usedNames.set(baseName, seenCount); usedNames.set(baseName, seenCount);
if (seenCount > 1) { if (seenCount > 1) {
baseName = `${baseName}-${seenCount}`; baseName = `${baseName}-${seenCount}`;
} }
const selectableFiles = safeFiles.filter( const selectableFiles = m.files.filter((f) => selectableRegexes.some((re) => re.test(f)));
(f) => isValidRelativeOverlayFile(f) && selectableRegexes.some((re) => re.test(f)), const editableFiles = m.files
);
const editableFiles = safeFiles
.filter((f) => editableRegexes.some((re) => re.test(f))) .filter((f) => editableRegexes.some((re) => re.test(f)))
.map((f) => path.posix.join(m.dir, f)); .map((f) => path.posix.join(m.dir, f));
const overrideRaw = Object.hasOwn(attachment.itemOverrides, baseName) const overrideFiles = attachment.itemOverrides[baseName]?.activeFiles?.filter((f) =>
? attachment.itemOverrides[baseName]?.activeFiles isValidRelativeOverlayFile(f),
: undefined;
const overrideFiles = overrideRaw?.filter(
(f) =>
isValidRelativeOverlayFile(f) &&
(selectableFiles.length === 0 || selectableFiles.includes(f)),
); );
const activeFiles = const activeFiles =
overrideFiles && overrideFiles.length > 0 overrideFiles && overrideFiles.length > 0
? overrideFiles ? overrideFiles
: [matchedFiles[0]!]; : [matchedFiles[0]!];
draftItems.push({ const draftItem: DiscoveredSystemItem = {
name: baseName, name: baseName,
dir: m.dir, dir: m.dir,
activeFiles, activeFiles,
@ -994,14 +762,12 @@ export class CustomSystemsEngine {
rawSummary: '', rawSummary: '',
exitCode: null, exitCode: null,
}, },
}); };
}
await runPool(draftItems, concurrency, async (draftItem) => {
const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem); const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem);
const statusRes = await this.sshPool.exec( const statusRes = await this.sshPool.exec(
server.id, server.id,
`cd -- ${posixSingleQuote(draftItem.dir!)} && ${system.status.command}`, `cd -- ${posixSingleQuote(m.dir)} && ${system.status.command}`,
{ env: itemEnv }, { env: itemEnv },
); );
draftItem.status = parseStatusOutput( draftItem.status = parseStatusOutput(
@ -1010,33 +776,32 @@ export class CustomSystemsEngine {
statusRes.exitCode, statusRes.exitCode,
system.status, system.status,
); );
}); items.push(draftItem);
}
return draftItems; return items;
} }
// command discovery // command discovery
const discRes = await this.sshPool.exec(server.id, system.discovery.command, { const discRes = await this.sshPool.exec(server.id, system.discovery.command, {
env: baseEnv, env: baseEnv,
}); });
const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser) const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser);
.filter((n) => !FORBIDDEN_KEYS.has(n) && !/[\x00-\x1f\x7f]/.test(n)) const items: DiscoveredSystemItem[] = [];
.slice(0, MAX_DISCOVERED_ITEMS);
const draftItems: DiscoveredSystemItem[] = names.map((itemName) => ({ for (const itemName of names) {
name: itemName, const draftItem: DiscoveredSystemItem = {
activeFiles: [], name: itemName,
selectableFiles: [], activeFiles: [],
editableFiles: [], selectableFiles: [],
status: { editableFiles: [],
health: 'unknown', status: {
subItems: [], health: 'unknown',
rawSummary: '', subItems: [],
exitCode: null, rawSummary: '',
}, exitCode: null,
})); },
};
await runPool(draftItems, concurrency, async (draftItem) => {
const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem); const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem);
const statusRes = await this.sshPool.exec(server.id, system.status.command, { const statusRes = await this.sshPool.exec(server.id, system.status.command, {
env: itemEnv, env: itemEnv,
@ -1047,88 +812,25 @@ export class CustomSystemsEngine {
statusRes.exitCode, statusRes.exitCode,
system.status, system.status,
); );
items.push(draftItem);
// 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<string, unknown>,
): Record<string, unknown> {
for (const k of Object.keys(supplied)) {
assertSafeKey(k, 'param name');
} }
const out: Record<string, unknown> = 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) { return items;
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 };
} }
private resolveParams( private resolveParams(
system: SystemConfig, system: SystemConfig,
supplied: Record<string, unknown>, supplied: Record<string, unknown>,
): Record<string, unknown> { ): Record<string, unknown> {
const out: Record<string, unknown> = Object.create(null); const out: Record<string, unknown> = {};
for (const def of system.params) { for (const def of system.params) {
if (FORBIDDEN_KEYS.has(def.name)) continue; if (supplied[def.name] !== undefined) {
if (Object.hasOwn(supplied, def.name) && supplied[def.name] !== undefined) {
out[def.name] = supplied[def.name]; out[def.name] = supplied[def.name];
} else if (def.default !== undefined) { } else if (def.default !== undefined) {
out[def.name] = structuredClone(def.default); out[def.name] = structuredClone(def.default);
} }
} }
return { ...out }; return out;
} }
private buildExecutionEnv( private buildExecutionEnv(
@ -1137,7 +839,6 @@ export class CustomSystemsEngine {
params: Record<string, unknown>, params: Record<string, unknown>,
item?: DiscoveredSystemItem, item?: DiscoveredSystemItem,
subItem?: string, subItem?: string,
actionInputs?: Record<string, string>,
): Record<string, string> { ): Record<string, string> {
const env: Record<string, string> = { const env: Record<string, string> = {
GCOORD_SERVER_ID: serverId, GCOORD_SERVER_ID: serverId,
@ -1145,19 +846,10 @@ export class CustomSystemsEngine {
}; };
for (const [k, v] of Object.entries(params)) { 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()}`; 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 ?? ''); 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) { if (item) {
env.GCOORD_ITEM_NAME = item.name; env.GCOORD_ITEM_NAME = item.name;
if (item.dir) { if (item.dir) {

View file

@ -5,74 +5,18 @@ export interface DiffLine {
text: string; text: string;
} }
export type CollapsedDiffEntry =
| DiffLine
| { type: 'hunk'; omittedCount: number; text: string };
export interface DiffResult { export interface DiffResult {
lines: DiffLine[]; lines: DiffLine[];
collapsedLines: CollapsedDiffEntry[];
unified: string; unified: string;
additions: number; additions: number;
deletions: 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( export function computeLineDiff(
oldText: string, oldText: string,
newText: string, newText: string,
oldLabel = 'revision', oldLabel = 'revision',
newLabel = 'current', newLabel = 'current',
opts: { contextLines?: number } = {},
): DiffResult { ): DiffResult {
const a = oldText.replace(/\r\n/g, '\n').split('\n'); const a = oldText.replace(/\r\n/g, '\n').split('\n');
const b = newText.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 additions = 0;
let deletions = 0; let deletions = 0;
const collapsedLines = collapseDiffHunks(lines, opts.contextLines ?? 3);
const body: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`]; const body: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`];
for (const entry of collapsedLines) { for (const line of lines) {
if (entry.type === 'hunk') { if (line.type === 'add') {
body.push(`@@ ${entry.text} @@`);
} else if (entry.type === 'add') {
additions++; additions++;
body.push(`+${entry.text}`); body.push(`+${line.text}`);
} else if (entry.type === 'del') { } else if (line.type === 'del') {
deletions++; deletions++;
body.push(`-${entry.text}`); body.push(`-${line.text}`);
} else { } else {
body.push(` ${entry.text}`); body.push(` ${line.text}`);
} }
} }
return { return {
lines, lines,
collapsedLines,
unified: body.join('\n'), unified: body.join('\n'),
additions, additions,
deletions, deletions,

View file

@ -1,38 +1,16 @@
import { z } from 'zod'; import { z } from 'zod';
import { import { CronExpressionSchema, EntityIdSchema } from './common.js';
CronExpressionSchema,
EntityIdSchema,
HttpUrlSchema,
IanaTimezoneSchema,
} from './common.js';
export const AlertChannelSchema = z export const AlertChannelSchema = z.object({
.object({ id: EntityIdSchema,
id: EntityIdSchema, name: z.string().min(1).max(120),
name: z.string().min(1).max(120), type: z.enum(['discord', 'telegram', 'ntfy', 'generic']),
type: z.enum(['discord', 'telegram', 'ntfy', 'generic']), url: z.string().url().optional(),
url: HttpUrlSchema.optional(), secretRef: EntityIdSchema,
secretRef: EntityIdSchema.optional(), chatId: z.string().optional(),
chatId: z.string().optional(), topic: z.string().optional(),
topic: z.string().optional(), enabled: z.boolean().default(true),
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 AlertRuleTargetSchema = z.object({ export const AlertRuleTargetSchema = z.object({
serverId: EntityIdSchema.optional(), serverId: EntityIdSchema.optional(),
@ -52,20 +30,6 @@ const AlertRuleBase = {
enabled: z.boolean().default(true), 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', [ export const AlertRuleSchema = z.discriminatedUnion('kind', [
z.object({ z.object({
...AlertRuleBase, ...AlertRuleBase,
@ -96,51 +60,26 @@ export const AlertRuleSchema = z.discriminatedUnion('kind', [
systemId: EntityIdSchema, systemId: EntityIdSchema,
item: z.string().optional(), item: z.string().optional(),
}), }),
z.object({
...AlertRuleBase,
kind: z.literal('security-event'),
events: z.array(SecurityEventKindSchema).min(1),
}),
]); ]);
export const MaintenanceWindowSchema = z.object({ export const MaintenanceWindowSchema = z.object({
id: EntityIdSchema, id: EntityIdSchema,
name: z.string().min(1).max(120), name: z.string().min(1).max(120),
cron: CronExpressionSchema, cron: CronExpressionSchema,
timezone: IanaTimezoneSchema.default('UTC'), timezone: z.string().min(1).default('UTC'),
durationMinutes: z.number().int().min(1).max(1440), durationMinutes: z.number().int().min(1).max(1440),
target: AlertRuleTargetSchema.default({ all: true }), target: AlertRuleTargetSchema.default({ all: true }),
enabled: z.boolean().default(true), enabled: z.boolean().default(true),
}); });
export const AlertsFileSchema = z export const AlertsFileSchema = z.object({
.object({ version: z.literal(1).default(1),
version: z.literal(1).default(1), channels: z.array(AlertChannelSchema).default([]),
channels: z.array(AlertChannelSchema).default([]), rules: z.array(AlertRuleSchema).default([]),
rules: z.array(AlertRuleSchema).default([]), maintenanceWindows: z.array(MaintenanceWindowSchema).default([]),
maintenanceWindows: z.array(MaintenanceWindowSchema).default([]), });
})
.superRefine((doc, ctx) => {
const checkDupes = (items: Array<{ id: string }>, arrPath: string) => {
const seen = new Set<string>();
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 type AlertChannel = z.infer<typeof AlertChannelSchema>; export type AlertChannel = z.infer<typeof AlertChannelSchema>;
export type AlertRule = z.infer<typeof AlertRuleSchema>; export type AlertRule = z.infer<typeof AlertRuleSchema>;
export type SecurityEventKind = z.infer<typeof SecurityEventKindSchema>;
export type MaintenanceWindow = z.infer<typeof MaintenanceWindowSchema>; export type MaintenanceWindow = z.infer<typeof MaintenanceWindowSchema>;
export type AlertsFile = z.infer<typeof AlertsFileSchema>; export type AlertsFile = z.infer<typeof AlertsFileSchema>;

View file

@ -5,44 +5,16 @@ export const EntityIdSchema = z
.string() .string()
.min(1, 'ID must not be empty') .min(1, 'ID must not be empty')
.max(64, 'ID must be at most 64 characters') .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._-]') .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 ".."');
export const PortSchema = z.number().int().min(1).max(65535); 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 export const CronExpressionSchema = z
.string() .string()
.min(1) .min(1)
.superRefine((expr, ctx) => { .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 { try {
new CronPattern(trimmed); new CronPattern(expr);
} catch (err) { } catch (err) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
@ -53,7 +25,7 @@ export const CronExpressionSchema = z
export const InputDefSchema = z.object({ export const InputDefSchema = z.object({
name: EntityIdSchema, 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(), label: z.string().min(1).optional(),
description: z.string().optional(), description: z.string().optional(),
required: z.boolean().default(false), required: z.boolean().default(false),

View file

@ -1,42 +1,22 @@
import { z } from 'zod'; import { z } from 'zod';
import { EntityIdSchema, HttpUrlSchema, PortSchema } from './common.js'; import { EntityIdSchema, 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 ":"',
);
export const HttpProbeSchema = z.object({ export const HttpProbeSchema = z.object({
id: EntityIdSchema, id: EntityIdSchema,
type: z.literal('http'), type: z.literal('http'),
url: HttpUrlSchema, url: z.string().url(),
from: z.enum(['hub', 'target']).default('target'), from: z.enum(['hub', 'target']).default('target'),
intervalSec: z.number().int().min(5).max(86400).default(30), intervalSec: z.number().int().min(5).max(86400).default(30),
timeoutMs: z.number().int().min(200).max(60000).default(5000), timeoutMs: z.number().int().min(200).max(60000).default(5000),
expectedStatus: z.number().int().min(100).max(599).default(200), expectedStatus: z.number().int().min(100).max(599).default(200),
bodyIncludes: z.string().optional(), bodyIncludes: z.string().optional(),
tlsRejectUnauthorized: z.boolean().default(true),
tlsCheckExpiryDays: z.number().int().min(1).max(365).optional(),
enabled: z.boolean().default(true), enabled: z.boolean().default(true),
}); });
export const TcpProbeSchema = z.object({ export const TcpProbeSchema = z.object({
id: EntityIdSchema, id: EntityIdSchema,
type: z.literal('tcp'), type: z.literal('tcp'),
host: SafeHostSchema.default('127.0.0.1'), host: z.string().min(1).default('127.0.0.1'),
port: PortSchema, port: PortSchema,
from: z.enum(['hub', 'target']).default('target'), from: z.enum(['hub', 'target']).default('target'),
intervalSec: z.number().int().min(5).max(86400).default(30), intervalSec: z.number().int().min(5).max(86400).default(30),
@ -60,71 +40,36 @@ export const ServerSystemAttachmentSchema = z.object({
.default({}), .default({}),
}); });
export const ServerTunnelSchema = z export const ServerTunnelSchema = z.object({
.object({ id: EntityIdSchema,
id: EntityIdSchema, name: z.string().min(1).max(120),
name: z.string().min(1).max(120), mode: z.enum(['http-proxy', 'local-tcp', 'remote-tcp']),
mode: z.enum(['http-proxy', 'local-tcp', 'remote-tcp', 'socks5']), bindHost: z.string().min(1).optional(),
bindHost: SafeHostSchema.optional(), bindPort: PortSchema.optional(),
bindPort: PortSchema.optional(), targetHost: z.string().min(1).default('127.0.0.1'),
targetHost: SafeHostSchema.default('127.0.0.1'), targetPort: PortSchema,
targetPort: z.number().int().min(0).max(65535).default(0), autoStart: z.boolean().default(false),
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 ServerConfigSchema = z export const ServerConfigSchema = z.object({
.object({ id: EntityIdSchema,
id: EntityIdSchema, name: z.string().min(1).max(120),
name: z.string().min(1).max(120), host: z.string().min(1),
host: SafeHostSchema, port: PortSchema.default(22),
port: PortSchema.default(22), username: z.string().min(1).max(64),
username: SafeUsernameSchema, credentialId: EntityIdSchema,
credentialId: EntityIdSchema, jumpHostId: EntityIdSchema.optional(),
jumpHostId: EntityIdSchema.optional(), sudoCredentialId: EntityIdSchema.optional(),
sudoCredentialId: EntityIdSchema.optional(), hostKeyFingerprint: z.string().min(1).optional(),
hostKeyFingerprint: z.string().min(1).optional(), tags: z.array(z.string().min(1)).default([]),
tags: z.array(z.string().min(1)).default([]), osHint: z.enum(['auto', 'linux', 'bsd', 'macos']).default('auto'),
osHint: z.enum(['auto', 'linux', 'bsd', 'macos']).default('auto'), pollIntervalSec: z.number().int().min(2).max(3600).default(10),
pollIntervalSec: z.number().int().min(2).max(3600).default(10), diskMountFilter: z.array(z.string().min(1)).optional(),
diskMountFilter: z.array(z.string().min(1)).optional(), probes: z.array(ServerProbeSchema).default([]),
probes: z.array(ServerProbeSchema).default([]), systems: z.array(ServerSystemAttachmentSchema).default([]),
systems: z.array(ServerSystemAttachmentSchema).default([]), tunnels: z.array(ServerTunnelSchema).default([]),
tunnels: z.array(ServerTunnelSchema).default([]), enabled: z.boolean().default(true),
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<string>();
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 type ServerProbe = z.infer<typeof ServerProbeSchema>; export type ServerProbe = z.infer<typeof ServerProbeSchema>;
export type ServerSystemAttachment = z.infer<typeof ServerSystemAttachmentSchema>; export type ServerSystemAttachment = z.infer<typeof ServerSystemAttachmentSchema>;

View file

@ -1,5 +1,5 @@
import { z } from 'zod'; import { z } from 'zod';
import { EntityIdSchema, HttpUrlSchema, IanaTimezoneSchema } from './common.js'; import { EntityIdSchema } from './common.js';
export const ThemeIdSchema = z.enum([ export const ThemeIdSchema = z.enum([
'phosphor-green', 'phosphor-green',
@ -14,13 +14,10 @@ export const ThemeIdSchema = z.enum([
export const THEME_IDS = ThemeIdSchema.options; export const THEME_IDS = ThemeIdSchema.options;
export const ThrottleModeSchema = z.enum(['low-resource', 'balanced', 'unthrottled']);
export const StepUpPolicySchema = z.enum([ export const StepUpPolicySchema = z.enum([
'off', 'off',
'every-action', 'every-action',
'5m', '5m',
'15m',
'1h', '1h',
'24h', '24h',
'session', 'session',
@ -32,15 +29,11 @@ export const SecuritySettingsSchema = z.object({
requireTotpOnLogin: z.boolean().default(true), requireTotpOnLogin: z.boolean().default(true),
passwordMode: z.enum(['any', 'all']).default('any'), passwordMode: z.enum(['any', 'all']).default('any'),
totpMode: 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'), stepUpMethod: StepUpMethodSchema.default('totp'),
elevateOnLogin: z.boolean().default(false), elevateOnLogin: z.boolean().default(true),
keepElevationOnSafeMode: z.boolean().default(true), keepElevationOnSafeMode: z.boolean().default(true),
enableEmergencySecretsBackup: z.boolean().default(false), enableEmergencySecretsBackup: z.boolean().default(true),
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),
}); });
export const SettingsSchema = z.object({ export const SettingsSchema = z.object({
@ -49,69 +42,29 @@ export const SettingsSchema = z.object({
defaultMobileSafeMode: z.boolean().default(true), defaultMobileSafeMode: z.boolean().default(true),
rawRetentionHours: z.number().int().min(1).max(720).default(48), rawRetentionHours: z.number().int().min(1).max(720).default(48),
rollupRetentionDays: z.number().int().min(1).max(3650).default(30), 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), 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), ptyIdleTtlSec: z.number().int().min(60).max(604800).default(43200),
sshKeepaliveMs: z.number().int().min(5000).max(120000).default(15000), sshKeepaliveMs: z.number().int().min(5000).max(120000).default(15000),
sshReadyTimeoutMs: z.number().int().min(3000).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({}), security: SecuritySettingsSchema.default({}),
ai: z ai: z
.object({ .object({
enabled: z.boolean().default(false), 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'), model: z.string().min(1).default('qwen2.5-coder:7b'),
secretRef: EntityIdSchema.optional(), secretRef: EntityIdSchema.optional(),
maxContextChars: z.number().int().min(1000).max(128000).default(16000), 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({ .default({
enabled: false, enabled: false,
baseUrl: 'http://127.0.0.1:11434', baseUrl: 'http://127.0.0.1:11434',
model: 'qwen2.5-coder:7b', model: 'qwen2.5-coder:7b',
maxContextChars: 16000, maxContextChars: 16000,
timeoutSec: 90,
maxTokens: 2048,
}), }),
}); });
export type ThemeId = z.infer<typeof ThemeIdSchema>; export type ThemeId = z.infer<typeof ThemeIdSchema>;
export type ThrottleMode = z.infer<typeof ThrottleModeSchema>;
export type StepUpPolicy = z.infer<typeof StepUpPolicySchema>; export type StepUpPolicy = z.infer<typeof StepUpPolicySchema>;
export type StepUpMethod = z.infer<typeof StepUpMethodSchema>; export type StepUpMethod = z.infer<typeof StepUpMethodSchema>;
export type SecuritySettings = z.infer<typeof SecuritySettingsSchema>; export type SecuritySettings = z.infer<typeof SecuritySettingsSchema>;

View file

@ -7,7 +7,6 @@ export const SnippetSchema = z.object({
description: z.string().optional(), description: z.string().optional(),
command: z.string().min(1), command: z.string().min(1),
tags: z.array(z.string().min(1)).default([]), tags: z.array(z.string().min(1)).default([]),
osFilter: z.array(z.enum(['linux', 'bsd', 'macos'])).optional(),
inputs: z.array(InputDefSchema).default([]), inputs: z.array(InputDefSchema).default([]),
sudo: z.boolean().default(false), sudo: z.boolean().default(false),
confirm: z.boolean().default(false), confirm: z.boolean().default(false),

View file

@ -1,5 +1,5 @@
import { z } from 'zod'; import { z } from 'zod';
import { EntityIdSchema, InputDefSchema } from './common.js'; import { EntityIdSchema } from './common.js';
export const SystemParamDefSchema = z.object({ export const SystemParamDefSchema = z.object({
name: EntityIdSchema, name: EntityIdSchema,
@ -39,19 +39,7 @@ export const SystemStatusSchema = z.object({
command: z.string().min(1), command: z.string().min(1),
parser: z.enum(['json-lines', 'json', 'lines', 'regex', 'exit-code']), parser: z.enum(['json-lines', 'json', 'lines', 'regex', 'exit-code']),
subItemField: z.string().min(1).optional(), subItemField: z.string().min(1).optional(),
regexPattern: z regexPattern: z.string().min(1).optional(),
.string()
.min(1)
.max(512)
.refine((pat) => {
try {
new RegExp(pat);
return true;
} catch {
return false;
}
}, 'Invalid regular expression pattern')
.optional(),
health: SystemHealthRuleSchema.optional(), health: SystemHealthRuleSchema.optional(),
}); });
@ -61,61 +49,22 @@ export const SystemActionSchema = z.object({
scope: z.enum(['system', 'item', 'subitem']), scope: z.enum(['system', 'item', 'subitem']),
mode: z.enum(['oneshot', 'stream', 'interactive']), mode: z.enum(['oneshot', 'stream', 'interactive']),
command: z.string().min(1), command: z.string().min(1),
inputs: z.array(InputDefSchema).default([]),
timeoutSec: z.number().int().min(5).max(3600).optional(),
sudo: z.boolean().default(false), sudo: z.boolean().default(false),
confirm: z.boolean().default(false), confirm: z.boolean().default(false),
}); });
export const SystemConfigSchema = z export const SystemConfigSchema = z.object({
.object({ id: EntityIdSchema,
id: EntityIdSchema, name: z.string().min(1).max(120),
name: z.string().min(1).max(120), description: z.string().optional(),
description: z.string().optional(), cacheTtlSec: z.number().int().min(0).max(86400).default(45),
cacheTtlSec: z.number().int().min(0).max(86400).default(45), backgroundCheckSec: z.number().int().min(10).max(86400).optional(),
backgroundCheckSec: z.number().int().min(10).max(86400).optional(), params: z.array(SystemParamDefSchema).default([]),
params: z.array(SystemParamDefSchema).default([]), discovery: SystemDiscoverySchema,
discovery: SystemDiscoverySchema, status: SystemStatusSchema,
status: SystemStatusSchema, actions: z.array(SystemActionSchema).default([]),
actions: z.array(SystemActionSchema).default([]), editableFiles: z.array(z.string().min(1)).default([]),
editableFiles: z.array(z.string().min(1)).default([]), });
})
.superRefine((sys, ctx) => {
const paramNames = new Set<string>();
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<string>();
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 type SystemParamDef = z.infer<typeof SystemParamDefSchema>; export type SystemParamDef = z.infer<typeof SystemParamDefSchema>;
export type SystemHealthRule = z.infer<typeof SystemHealthRuleSchema>; export type SystemHealthRule = z.infer<typeof SystemHealthRuleSchema>;

View file

@ -1,11 +1,5 @@
import { z } from 'zod'; import { z } from 'zod';
import { import { CronExpressionSchema, EntityIdSchema, InputDefSchema } from './common.js';
CronExpressionSchema,
EntityIdSchema,
HttpUrlSchema,
IanaTimezoneSchema,
InputDefSchema,
} from './common.js';
export const WorkflowTargetSchema = z export const WorkflowTargetSchema = z
.object({ .object({
@ -29,13 +23,12 @@ export const StepDependencySchema = z.union([
export const StepFailureActionSchema = z.union([ export const StepFailureActionSchema = z.union([
z.literal('abort'), z.literal('abort'),
z.literal('continue'), z.literal('continue'),
EntityIdSchema, z.string().min(1),
z.discriminatedUnion('action', [ z.object({
z.object({ action: z.literal('abort') }), action: z.enum(['abort', 'continue', 'notify', 'run-workflow']),
z.object({ action: z.literal('continue') }), channelId: z.string().min(1).optional(),
z.object({ action: z.literal('notify'), channelId: EntityIdSchema }), workflowId: EntityIdSchema.optional(),
z.object({ action: z.literal('run-workflow'), workflowId: EntityIdSchema }), }),
]),
]); ]);
const StepBaseFields = { const StepBaseFields = {
@ -43,9 +36,6 @@ const StepBaseFields = {
name: z.string().min(1).max(120).optional(), name: z.string().min(1).max(120).optional(),
dependsOn: z.array(StepDependencySchema).default([]), dependsOn: z.array(StepDependencySchema).default([]),
timeoutSec: z.number().int().min(1).max(86400).optional(), 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), sudo: z.boolean().default(false),
captureAs: z.string().min(1).max(64).optional(), captureAs: z.string().min(1).max(64).optional(),
onFailure: StepFailureActionSchema.optional(), onFailure: StepFailureActionSchema.optional(),
@ -90,28 +80,6 @@ export const TransferStepSchema = z.object({
serverId: z.string().min(1), serverId: z.string().min(1),
path: 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', [ export const WorkflowStepSchema = z.discriminatedUnion('type', [
@ -119,8 +87,6 @@ export const WorkflowStepSchema = z.discriminatedUnion('type', [
ReadFileStepSchema, ReadFileStepSchema,
SystemActionStepSchema, SystemActionStepSchema,
TransferStepSchema, TransferStepSchema,
HttpStepSchema,
NotifyStepSchema,
]); ]);
export const WorkflowTriggerSchema = z.discriminatedUnion('type', [ export const WorkflowTriggerSchema = z.discriminatedUnion('type', [
@ -128,7 +94,7 @@ export const WorkflowTriggerSchema = z.discriminatedUnion('type', [
z.object({ z.object({
type: z.literal('cron'), type: z.literal('cron'),
expression: CronExpressionSchema, expression: CronExpressionSchema,
timezone: IanaTimezoneSchema.default('UTC'), timezone: z.string().min(1).default('UTC'),
}), }),
z.object({ z.object({
type: z.literal('event'), type: z.literal('event'),

View file

@ -1,7 +1,6 @@
import { z } from 'zod'; import { z } from 'zod';
export type VaultState = 'uninitialized' | 'locked' | 'unlocked'; export type VaultState = 'uninitialized' | 'locked' | 'unlocked';
export type VaultSealState = 'uninitialized' | 'sealed' | 'write-locked' | 'unlocked';
export type ServerConnectionStatus = export type ServerConnectionStatus =
| 'disconnected' | 'disconnected'
@ -49,7 +48,6 @@ export interface ProbeSample {
ok: boolean; ok: boolean;
statusCode?: number; statusCode?: number;
latencyMs: number; latencyMs: number;
certExpiryDays?: number;
error?: string; error?: string;
} }
@ -135,7 +133,6 @@ export type ServerWsFrame =
type: 'hello'; type: 'hello';
vaultState: VaultState; vaultState: VaultState;
vaultRuntimeReady?: boolean; vaultRuntimeReady?: boolean;
vaultSealState?: VaultSealState;
safeMode: boolean; safeMode: boolean;
elevatedUntil: number | null; elevatedUntil: number | null;
} }
@ -143,7 +140,6 @@ export type ServerWsFrame =
type: 'vault:state'; type: 'vault:state';
vaultState: VaultState; vaultState: VaultState;
vaultRuntimeReady: boolean; vaultRuntimeReady: boolean;
vaultSealState?: VaultSealState;
isPanicLocked: boolean; isPanicLocked: boolean;
} }
| { | {

View file

@ -3,7 +3,7 @@ import http from 'node:http';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js'; 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 }; return { status: res.status, data };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -227,11 +225,7 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
await api('/api/vault/credentials', { 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 // Write-lock Vault -> AI runtime secret still works via VaultService.getRuntimeSecret
expect((await api('/api/vault/lock', { method: 'POST' })).data.state).toBe('locked'); 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: {} }); const testEp = await api('/api/ai/test', { method: 'POST', body: {} });
expect(testEp.status).toBe(200); expect(testEp.status).toBe(200);
expect(testEp.data.ok).toBe(true); expect(testEp.data.ok).toBe(true);

View file

@ -3,7 +3,7 @@ import http from 'node:http';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js'; import { createGCoordinatorServer } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.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 }; return { status: res.status, data };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -154,11 +152,7 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () =>
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', { 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.state).toBe('locked');
expect(lockRes.data.runtimeReady).toBe(true); 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 --- // --- 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']) { for (const chId of ['ch-discord', 'ch-tg', 'ch-ntfy', 'ch-generic']) {
const tRes = await api(`/api/alerts/channels/${chId}/test`, { method: 'POST' }); const tRes = await api(`/api/alerts/channels/${chId}/test`, { method: 'POST' });

View file

@ -3,7 +3,7 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import zlib from 'node:zlib'; import zlib from 'node:zlib';
import * as OTPAuth from 'otpauth'; 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 WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js'; 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); expect(health.status).toBe(200);
await expect(openWs(wsUrl, {})).rejects.toThrow('WS_HTTP_401'); 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) // 2. Bootstrap Admin + TOTP
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 65_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
expect(bootInfo.status).toBe(200); expect(bootInfo.status).toBe(200);
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
@ -140,7 +138,6 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.setSystemTime(Date.now() + 31_000);
expect(bootDone.status).toBe(201); expect(bootDone.status).toBe(201);
csrfToken = String(bootDone.data.csrfToken); csrfToken = String(bootDone.data.csrfToken);
const recoveryCodes = bootDone.data.recoveryCodes as string[]; 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, (await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } })).status,
).toBe(200); ).toBe(200);
// 6. Vault Init + Step-Up guard + Drop Elevation + Generate Ed25519 key // 6. Vault Init + Drop Elevation -> Step-Up guard + 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);
const vInit = await api('/api/vault/init', { method: 'POST', body: {} }); const vInit = await api('/api/vault/init', { method: 'POST', body: {} });
expect(vInit.status).toBe(201); expect(vInit.status).toBe(201);
const generatedMasterKey = String(vInit.data.generatedKeyHex); 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'); const statusBeforeDrop = await api('/api/auth/status');
expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number'); expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number');
const dropped = await api('/api/auth/drop-elevation', { method: 'POST' }); const dropped = await api('/api/auth/drop-elevation', { method: 'POST' });
expect(dropped.status).toBe(200); expect(dropped.status).toBe(200);
expect(dropped.data.elevatedUntil).toBeNull(); expect(dropped.data.elevatedUntil).toBeNull();
const afterDropDenied = await api('/api/vault/generate-ed25519', { const noStepUp = await api('/api/vault/generate-ed25519', {
method: 'POST', method: 'POST',
body: { id: 'prod-key', name: 'Prod Key' }, 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(); const stepUpRes = await api('/api/auth/step-up', {
expect( method: 'POST',
(await api('/api/auth/step-up', { method: 'POST', body: { code: totpGen.generate() } })).status, body: { code: totpGen.generate() },
).toBe(200); });
expect(stepUpRes.status).toBe(200);
const genRes = await api('/api/vault/generate-ed25519', { const genRes = await api('/api/vault/generate-ed25519', {
method: 'POST', method: 'POST',

View file

@ -129,21 +129,15 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
}); });
expect(boot.session.elevatedUntil).toBeNull(); expect(boot.session.elevatedUntil).toBeNull();
// Unified monotonic TOTP step blocks replaying bootstrap code for step-up // Step-up tracks replay independently from login step
const replayBootCode = await auth.stepUp(boot.session.idHash, code0); const stepUp1 = 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);
expect(stepUp1).toEqual({ expect(stepUp1).toEqual({
ok: true, ok: true,
elevatedUntil: t1 + 5 * 60 * 1000, elevatedUntil: t0 + 5 * 60 * 1000,
}); });
// Replaying exact same step-up code is denied // 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' }); expect(stepUpReplay).toEqual({ ok: false, reason: 'totp_replayed' });
// Enabling Safe Mode clears elevatedUntil immediately // Enabling Safe Mode clears elevatedUntil immediately
@ -152,26 +146,25 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
expect(safeSession?.elevatedUntil).toBeNull(); expect(safeSession?.elevatedUntil).toBeNull();
// Step-up is blocked while Safe Mode is ON // Step-up is blocked while Safe Mode is ON
const t2 = t1 + 31_000; vi.setSystemTime(t0 + 31_000);
vi.setSystemTime(t2); const code1 = generateTotp(enroll.secretBase32, t0 + 31_000);
const code2 = generateTotp(enroll.secretBase32, t2); const whileSafe = await auth.stepUp(boot.session.idHash, code1);
const whileSafe = await auth.stepUp(boot.session.idHash, code2);
expect(whileSafe).toEqual({ ok: false, reason: 'safe_mode_active' }); expect(whileSafe).toEqual({ ok: false, reason: 'safe_mode_active' });
// Turning Safe Mode OFF allows step-up again // Turning Safe Mode OFF allows step-up again
auth.setSafeMode(boot.session.idHash, false); 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); expect(stepUp2.ok).toBe(true);
// Elevation expires automatically after 5 minutes // 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); const expiredSession = auth.getSessionByToken(boot.sessionToken);
expect(expiredSession?.elevatedUntil).toBeNull(); expect(expiredSession?.elevatedUntil).toBeNull();
db.close(); 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'] }); vi.useFakeTimers({ toFake: ['Date'] });
const t0 = 1_700_000_010_000; const t0 = 1_700_000_010_000;
vi.setSystemTime(t0); vi.setSystemTime(t0);
@ -187,18 +180,11 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
userAgent: 'vitest', userAgent: 'vitest',
}); });
expect(boot.session.elevatedUntil).toBeNull(); expect(boot.session.elevatedUntil).toBe(t0 + 60 * 60 * 1000);
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,
});
const safeSession = auth.setSafeMode(boot.session.idHash, true); const safeSession = auth.setSafeMode(boot.session.idHash, true);
expect(safeSession?.safeMode).toBe(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(); db.close();
}); });

View file

@ -4,7 +4,7 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { promisify } from 'node:util'; import { promisify } from 'node:util';
import * as OTPAuth from 'otpauth'; 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 { createGCoordinatorServer } from '../src/server/app.js';
import { openDatabase } from '../src/server/db/database.js'; import { openDatabase } from '../src/server/db/database.js';
import { VaultService } from '../src/server/security/vault.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 }; return { status: res.status, data };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -106,11 +104,7 @@ describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord C
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', { const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -3,7 +3,7 @@ import fs from 'node:fs';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js'; import { createGCoordinatorServer } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.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<string, unknown> }; return { status: res.status, data: data as Record<string, unknown> };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -125,11 +123,7 @@ describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions &
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', { const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -401,27 +401,7 @@ export class MockSshServer {
let stdin = rawStdin; let stdin = rawStdin;
// Handle sudo wrappers produced by prepareSudoExecution // Handle sudo wrappers produced by prepareSudoExecution
if (command.startsWith("sudo -S -k -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;
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 ")) {
const nl = stdin.indexOf('\n'); const nl = stdin.indexOf('\n');
const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin; const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin;
this.lastSudoStdin = suppliedPw; this.lastSudoStdin = suppliedPw;
@ -567,10 +547,9 @@ export class MockSshServer {
rawCommand: string, rawCommand: string,
): { stdout: Buffer; stderr?: string; exitCode: number } | null { ): { stdout: Buffer; stderr?: string; exitCode: number } | null {
// Support streamed SFTP folder archive command in integration tests // Support streamed SFTP folder archive command in integration tests
const tarMatch = const tarMatch = /tar -C ('(?:[^']|'\\'')*'|\S+) -cf - ('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec(
/tar (?:--one-file-system )?-C ('(?:[^']|'\\'')*'|\S+) -cf - (?:-- )?('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec( rawCommand,
rawCommand, );
);
if (tarMatch) { if (tarMatch) {
try { try {
const virtualParent = unquoteSinglePosix(tarMatch[1]!); const virtualParent = unquoteSinglePosix(tarMatch[1]!);

Some files were not shown because too many files have changed in this diff Show more