Compare commits
19 commits
d7c3e11d7e
...
5701e77780
| Author | SHA1 | Date | |
|---|---|---|---|
| 5701e77780 | |||
| a5a937850e | |||
| f45d128c4f | |||
| f7d2abe3de | |||
| 5b09c8ada1 | |||
| c003afa9df | |||
| 3a28a2332f | |||
| 67137056f8 | |||
| 2b878c1d99 | |||
| d5822c9eca | |||
| dbf7144c5d | |||
| ca67c85fbf | |||
| 838e69ba4e | |||
| 716627afdd | |||
| 9a27525def | |||
| 1b2e425a00 | |||
| e3f716d24f | |||
| 005c82e6bf | |||
| afc2d6358a |
112 changed files with 14939 additions and 2513 deletions
12
.dockerignore
Normal file
12
.dockerignore
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
node_modules/
|
||||
dist/
|
||||
data/
|
||||
docker/secrets/
|
||||
.git/
|
||||
.env
|
||||
.env.*
|
||||
*.gcoord.enc
|
||||
*.tsbuildinfo
|
||||
coverage/
|
||||
tests/
|
||||
.DS_Store
|
||||
177
How/AGENTS.md
177
How/AGENTS.md
|
|
@ -12,9 +12,9 @@
|
|||
- Centralized `AES-256-GCM` credential storage (`vault.enc`), Ed25519 key lifecycle + zero-lockout atomic key rotation, Argon2id + multi-factor TOTP + optional WebAuthn Passkeys, configurable re-auth strictness, Safe Mode, and Emergency Panic Lock.
|
||||
- Agentless Linux/BSD/macOS metric polling, multi-mount disk tracking, on-demand Server Inspector, HTTP/TCP probes, declarative `systems/*.json` discovery/status/actions, Full-DAG `workflows/*.json`, fleet broadcast, cross-server transfers, webhook alerting, portable `.gcoord.enc` backups, and an opt-in BYO-API OpenAI-compatible AI assistant.
|
||||
|
||||
All 5 phases of [Plan.md](file:///home/devuser/workspace/GCoordinator/How/Plan.md) plus post-Phase-2 and post-Phase-3 enhancements are implemented and verified (`18/18` Vitest suites, `35/35` tests passing).
|
||||
All 5 phases of [Plan.md](file:///home/devuser/workspace/GCoordinator/How/Plan.md) plus **v1.1.0** security hardening, lightweight low-resource runtime throttling, and operational enhancements are implemented and verified (`21/21` Vitest suites, `41/41` tests passing). Key v1.1 additions include configurable `runtime.throttleMode` (`low-resource` | `balanced` | `unthrottled`) tuned for 1 vCPU / 1 GB RAM + 2 GB Swap servers, Zero-Trust Egress Guard, Vault `seal()` + passwordless emergency recovery, encrypted TOTP + SQLite rate limiting + CIDR-gated proxy IP trust + real-time WS revocation, dual-mode isolated proxy origins + SOCKS5/TTL tunnels + OpenSSH config import, Prometheus `/metrics`, Security Event Alerting, scheduled `.gcoord.enc` backups, offline CLI admin tools (`status`, `panic-lock`, `reset-2fa`, `reset-password`), and full dynamic client code-splitting.
|
||||
|
||||
**Precedence rule:** [How/Plan.md](./Plan.md) is the original Phase 1–5 design blueprint (its directory-tree diagram still references root `Plan.md`, which now lives at `How/Plan.md`). Several core behaviors evolved during implementation—including write-only Vault locking vs. always-on runtime secrets, multi-password/multi-TOTP & configurable strictness, WebAuthn Passkeys, the `data/recovery/` emergency backup store, 8 UI/terminal themes, a strict `< 20 KB` lazy-chunk budget, and `xterm.js` mobile IME composition fixes. **Wherever `How/AGENTS.md` differs from `How/Plan.md`, `How/AGENTS.md` reflects the live codebase and takes precedence.**
|
||||
**Precedence rule:** [How/Plan.md](./Plan.md) is the original Phase 1–5 design blueprint (its directory-tree diagram still references root `Plan.md`, which now lives at `How/Plan.md`). Several core behaviors evolved across v1.0 and v1.1—including write-only Vault locking + explicit `seal()` vs. always-on runtime secrets, multi-password/multi-TOTP & configurable strictness, WebAuthn Passkeys, passwordless `data/recovery/` emergency secret backups, Zero-Trust egress & dual-mode isolated proxy origins, configurable `runtime.throttleMode`, 8 UI/terminal themes, a strict `< 20 KB` lazy-chunk budget across all code-split views, and `xterm.js` mobile IME composition fixes. **Wherever `How/AGENTS.md` differs from `How/Plan.md`, `How/AGENTS.md` reflects the live codebase and takes precedence.**
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -29,19 +29,23 @@ All 5 phases of [Plan.md](file:///home/devuser/workspace/GCoordinator/How/Plan.m
|
|||
|
||||
### NPM Scripts (`package.json`)
|
||||
- `npm run typecheck` — `tsc --noEmit` (strict TypeScript with `noUncheckedIndexedAccess: true` and `noImplicitOverride: true`).
|
||||
- `npm run build:client` — `tsx src/client/build.ts` (bundles ES2020 client modules + CSS into `dist/public/` and enforces gzip budgets).
|
||||
- `npm run build:client` — `tsx src/client/build.ts` (bundles ES2020 client modules + CSS into `dist/public/` and enforces gzip budgets recursively across `main.js` static imports and lazy chunks).
|
||||
- `npm run build:server` — `esbuild` bundles `dist/server/index.js` and `dist/cli/gcoord.js` (`--platform=node --target=node22 --format=esm --packages=external`).
|
||||
- `npm run build` — runs `typecheck && build:client && build:server`.
|
||||
- `npm test` — `vitest run` (runs all 18 unit/E2E suites in ~5s using in-process HTTP servers and `MockSshServer`).
|
||||
- `npm test` — `vitest run` (runs all 21 unit/E2E suites, 41 tests using in-process HTTP servers and `MockSshServer`).
|
||||
- `npx vitest run tests/<file>.test.ts` — run a targeted Vitest file.
|
||||
- `npm run dev` — `tsx watch src/server/index.ts`.
|
||||
- `npm start` — `node dist/server/index.js` (requires `npm run build` first so `dist/public/` and `dist/server/` exist).
|
||||
|
||||
### CLI (`src/cli/gcoord.ts` -> `dist/cli/gcoord.js`)
|
||||
```bash
|
||||
node dist/cli/gcoord.js status [--data-dir <dir>] [--json]
|
||||
node dist/cli/gcoord.js panic-lock [--data-dir <dir>]
|
||||
node dist/cli/gcoord.js reset-2fa [--data-dir <dir>] [--disable] [--json]
|
||||
node dist/cli/gcoord.js reset-password [--data-dir <dir>] [--password-file <path>]
|
||||
node dist/cli/gcoord.js rotate-key [--data-dir <dir>] [--current-key-file <path>] [--new-key-out <path>]
|
||||
node dist/cli/gcoord.js backup --out <path.gcoord.enc> [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>]
|
||||
node dist/cli/gcoord.js verify-backup <path.gcoord.enc> [--bundle <path>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>] [--json]
|
||||
node dist/cli/gcoord.js verify-backup <path.gcoord.enc> [--bundle <path>] [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>] [--json]
|
||||
node dist/cli/gcoord.js restore <path.gcoord.enc> [--bundle <path>] [--data-dir <dir>] [--key-file <path>] [--passphrase-file <path>] [--vault-key-file <path>]
|
||||
```
|
||||
|
||||
|
|
@ -51,8 +55,18 @@ node dist/cli/gcoord.js restore <path.gcoord.enc> [--bundle <path>] [--data-dir
|
|||
- `HOST` — bind address (default: `0.0.0.0`).
|
||||
- `GCOORD_MASTER_KEY` — 32-byte Vault master key (hex or base64).
|
||||
- `GCOORD_MASTER_KEY_FILE` — master key file path (default: `/run/secrets/gcoord_master_key`).
|
||||
- `GCOORD_DB_KEY` — 32-byte key encrypting TOTP secrets at rest in SQLite (otherwise auto-created `0600` at `data/db.key`).
|
||||
- `GCOORD_AUTO_KEYFILE` — set `'true'` to mirror an env/secret Vault key into local `data/vault.key` (`0600`).
|
||||
- `GCOORD_BACKUP_PASSPHRASE` — optional passphrase for `.gcoord.enc` CLI operations.
|
||||
- `TRUST_CLOUDFLARE` — set `'true'` to enable `app.set('trust proxy', 1)` and honor `CF-Connecting-IP` in rate limiting.
|
||||
- `TRUST_CLOUDFLARE` — set `'true'` to trust proxy headers from `TRUSTED_PROXY_CIDRS` / loopback and honor `CF-Connecting-IP` in rate limiting.
|
||||
- `TRUSTED_PROXY_CIDRS` — comma-separated CIDR allowlist of trusted reverse proxies (`trust proxy` & client IP resolution).
|
||||
- `GCOORD_ALLOW_LAN_TUNNELS` — set `'true'` to permit LAN-bound tunnel listeners where applicable.
|
||||
- `GCOORD_PROXY_PORT` — optional dedicated local port for origin-isolated reverse-proxy tunnel traffic.
|
||||
- `GCOORD_PROXY_BASE_DOMAIN` — optional wildcard subdomain base host (e.g. `proxy.example.com`) for origin-isolated tunnel proxying.
|
||||
- `GCOORD_WEBAUTHN_RP_ID` — optional explicit WebAuthn Relying Party ID override.
|
||||
- `GCOORD_WEBAUTHN_ORIGINS` — optional comma-separated allowed WebAuthn origins.
|
||||
- `GCOORD_METRICS_TOKEN` — optional Bearer token override for Prometheus `GET /metrics`.
|
||||
- `GCOORD_THROTTLE_MODE` — runtime throttle profile override: `'low-resource'` | `'balanced'` | `'unthrottled'` (overrides `settings.runtime.throttleMode`).
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -69,7 +83,7 @@ GCoordinator/
|
|||
│ └── docker-compose.lan.yml
|
||||
├── src/
|
||||
│ ├── cli/
|
||||
│ │ └── gcoord.ts # rotate-key, backup, verify-backup, restore CLI
|
||||
│ │ └── gcoord.ts # status, panic-lock, reset-2fa, reset-password, rotate-key, backup, verify-backup, restore
|
||||
│ ├── shared/
|
||||
│ │ ├── diff.ts # Pure TS unified LCS line diff utility
|
||||
│ │ ├── ws-protocol.ts # Multiplexed /ws frame schemas & WS_CHANNELS helpers
|
||||
|
|
@ -85,76 +99,84 @@ GCoordinator/
|
|||
│ │ └── vault.schema.ts
|
||||
│ ├── server/
|
||||
│ │ ├── index.ts # Process bootstrap & SIGINT/SIGTERM graceful shutdown
|
||||
│ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock
|
||||
│ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock, /metrics
|
||||
│ │ ├── db/
|
||||
│ │ │ ├── database.ts # SQLite WAL connection & ordered migration runner
|
||||
│ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts
|
||||
│ │ │ ├── database.ts # SQLite WAL connection, throttle PRAGMAs & ordered migration runner
|
||||
│ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts, 004_v1_1.ts
|
||||
│ │ ├── security/
|
||||
│ │ │ ├── vault.ts # VaultService (AES-256-GCM, runtime-ready vs write-locked, Ed25519)
|
||||
│ │ │ ├── auth.ts # AuthService (Argon2id, multi-password, multi-TOTP, recovery codes, WebAuthn)
|
||||
│ │ │ ├── guards.ts # RateLimiter, attachClientIp, CSRF, Safe Mode, createStepUpGuard
|
||||
│ │ │ ├── audit.ts # Append-only AuditService
|
||||
│ │ │ ├── recovery-store.ts # EmergencyRecoveryService (data/recovery/emergency-secrets.json)
|
||||
│ │ │ └── backup.ts # Portable AES-256-GCM .gcoord.enc (GCOORD_BACKUP_V1) export/verify/restore
|
||||
│ │ │ ├── vault.ts # VaultService (AES-256-GCM, runtime-ready vs write-locked, seal(), Ed25519)
|
||||
│ │ │ ├── auth.ts # AuthService (Argon2id queue, multi-password, encrypted TOTP, idle TTL, WebAuthn)
|
||||
│ │ │ ├── guards.ts # SQLite RateLimiter, attachClientIp (CIDR trust), CSRF, Safe Mode, Step-Up
|
||||
│ │ │ ├── egress-guard.ts # Zero-Trust SSRF/DNS/CIDR guard & redirect: 'error' fetch wrapper
|
||||
│ │ │ ├── audit.ts # Append-only AuditService (filtered query, CSV formula guard, NDJSON)
|
||||
│ │ │ ├── recovery-store.ts # EmergencyRecoveryService (passwordless data/recovery/emergency-secrets.json)
|
||||
│ │ │ ├── backup.ts # Async portable AES-256-GCM .gcoord.enc (GCOORD_BACKUP_V1) export/verify/restore
|
||||
│ │ │ └── backup-scheduler.ts # Scheduled .gcoord.enc backups (local & SFTP) with retention pruning
|
||||
│ │ ├── config/
|
||||
│ │ │ ├── config-manager.ts # ConfigManager (atomic writes, chokidar hot-reload, revisions)
|
||||
│ │ │ ├── config-manager.ts # ConfigManager (atomic writes, chokidar hot-reload, revisions, symlink guard)
|
||||
│ │ │ ├── runtime-limits.ts # Throttle profile presets (low-resource | balanced | unthrottled)
|
||||
│ │ │ ├── presets.ts # Default docker-compose, systemd, os-packages seeds
|
||||
│ │ │ └── diff.ts
|
||||
│ │ ├── ssh/
|
||||
│ │ │ ├── ssh-pool.ts # SSHPool (coalesced connections, ProxyJump, execStream, openShell, openSftp)
|
||||
│ │ │ ├── known-hosts.ts # KnownHostsService (strict TOFU, MITM guard, replaceAllKnownHosts)
|
||||
│ │ │ ├── ssh-config-import.ts # Safe OpenSSH config parser for /api/servers/import-ssh-config
|
||||
│ │ │ ├── known-hosts.ts # KnownHostsService (strict multi-algo TOFU, MITM guard, replaceAllKnownHosts)
|
||||
│ │ │ ├── key-manager.ts # KeyManager (authorized_keys deploy/revoke, zero-lockout rotation)
|
||||
│ │ │ ├── sudo.ts # POSIX-quoted sudo wrapper & Buffer zeroization
|
||||
│ │ │ ├── pty-manager.ts # PTYManager (UTF-8 framing, scrollback ring, export, reaper)
|
||||
│ │ │ ├── sftp-service.ts # SftpService (stream upload/download, atomic inline edit, tar archives)
|
||||
│ │ │ └── tunnel-manager.ts # TunnelManager (http-proxy, local-tcp, remote-tcp)
|
||||
│ │ │ ├── sudo.ts # POSIX-quoted sudo wrapper, askpass-free pipe & Buffer zeroization
|
||||
│ │ │ ├── pty-manager.ts # PTYManager (UTF-8 framing, scrollback ring, .cast v2 export, reaper)
|
||||
│ │ │ ├── sftp-service.ts # SftpService (stream upload/download, touch/chown/search, symlink-safe ops)
|
||||
│ │ │ └── tunnel-manager.ts # TunnelManager (dual-mode isolated HTTP/WS proxy, SOCKS5, local/remote TCP, TTL)
|
||||
│ │ ├── monitoring/
|
||||
│ │ │ ├── collectors.ts # OS-aware LinuxCollector, BSDCollector, MacOSCollector
|
||||
│ │ │ ├── collectors.ts # OS-aware LinuxCollector, BSDCollector, MacOSCollector (+ net/disk I/O)
|
||||
│ │ │ ├── inspector.ts # On-demand ServerInspector (processes, ports, sensors)
|
||||
│ │ │ ├── probes.ts # ProbeRunner (hub or target forwardOutStream HTTP/TCP probes)
|
||||
│ │ │ └── monitoring-service.ts # MonitoringService (always-on polling, SQLite rollups, retention)
|
||||
│ │ │ ├── probes.ts # ProbeRunner (hub egress-guarded HTTP + TLS expiry, target forwardOutStream)
|
||||
│ │ │ ├── monitoring-service.ts # MonitoringService (staggered/capped polling, SQLite rollups, retention)
|
||||
│ │ │ └── prometheus.ts # Opt-in Bearer-authenticated Prometheus GET /metrics exporter
|
||||
│ │ ├── systems/
|
||||
│ │ │ ├── parsers.ts # Output parsers for declarative system discovery/status
|
||||
│ │ │ └── systems-engine.ts # CustomSystemsEngine (TTL cache, overlays, 3x3 scoped/moded actions)
|
||||
│ │ │ └── systems-engine.ts # CustomSystemsEngine (bounded TTL cache, overlays, editableFiles, action inputs)
|
||||
│ │ ├── automation/
|
||||
│ │ │ ├── template.ts # Safe env-var & POSIX single-quoted interpolation + target filtering
|
||||
│ │ │ ├── stream-buffer.ts # BufferedStreamEmitter (128 KB circular WS replay ring)
|
||||
│ │ │ ├── stream-buffer.ts # BufferedStreamEmitter (capped circular WS replay ring)
|
||||
│ │ │ ├── transfer-engine.ts # TransferEngine (hub-relayed SFTP or direct rsync)
|
||||
│ │ │ ├── workflow-engine.ts # WorkflowEngine (Kahn DAG scheduler, croner, event triggers, dry-run)
|
||||
│ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet command execution)
|
||||
│ │ │ ├── workflow-engine.ts # WorkflowEngine (Kahn DAG, retries, http/notify steps, croner, secret inputs)
|
||||
│ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet execution + SQLite history & CSV)
|
||||
│ │ ├── alerts/
|
||||
│ │ │ └── alert-engine.ts # AlertEngine (metric/disk/offline/probe/system rules, silences, webhooks)
|
||||
│ │ │ └── alert-engine.ts # AlertEngine (metric/disk/offline/probe/system/security-event, egress-guarded webhooks)
|
||||
│ │ ├── ai/
|
||||
│ │ │ ├── redactor.ts # collectVaultSecretStrings & redactSecrets
|
||||
│ │ │ ├── redactor.ts # Linear O(n) collectVaultSecretStrings & redactSecrets
|
||||
│ │ │ ├── guides.ts # AiSurfaceSchema & buildSurfaceGuideAndInventory
|
||||
│ │ │ └── ai-service.ts # AiService (opt-in /v1/chat/completions, WS streaming, Zod draft check)
|
||||
│ │ │ └── ai-service.ts # AiService (opt-in egress-guarded /v1/chat/completions, WS streaming, Zod draft check)
|
||||
│ │ └── api/
|
||||
│ │ ├── ws-hub.ts # Multiplexed WebSocket hub (/ws, origin & ticket/session checks, replay)
|
||||
│ │ ├── ws-hub.ts # Multiplexed WebSocket hub (/ws, origin & ticket/session checks, real-time close 4001)
|
||||
│ │ └── routes/ # auth, vault, config, audit, servers, terminal, sftp, tunnels, systems, workflows, snippets, alerts, backup, ai
|
||||
│ └── client/
|
||||
│ ├── build.ts # esbuild client/CSS bundler + gzip budget assertions
|
||||
│ ├── build.ts # esbuild client/CSS bundler + recursive sync-core & lazy-chunk gzip assertions
|
||||
│ ├── index.html # SPA shell + PWA manifest + dynamic theme-color meta
|
||||
│ ├── manifest.json
|
||||
│ ├── icon.svg
|
||||
│ ├── css/
|
||||
│ │ ├── themes.css # 8 CSS custom-property terminal themes
|
||||
│ │ └── base.css # Flat sharp styles, dialog/drawer styles, mobile <768px rules
|
||||
│ │ └── base.css # Flat sharp styles, dialog/drawer/toast/palette styles, mobile <768px rules
|
||||
│ └── ts/
|
||||
│ ├── main.ts # Router, nav, topbar indicators, Panic Lock, global state sync
|
||||
│ ├── state.ts # Client store, CLIENT_THEME_IDS, applyTheme, appendBoundedStreamText
|
||||
│ ├── main.ts # Router, nav, view cleanup lifecycle, topbar indicators, Panic Lock, global state sync
|
||||
│ ├── state.ts # Client store, CLIENT_THEME_IDS, applyTheme, appendBoundedStreamText, registerViewCleanup
|
||||
│ ├── api.ts # Fetch wrapper (CSRF header + auto Vault unlock prompt on 423 VAULT_LOCKED)
|
||||
│ ├── ws-client.ts # Reconnecting /ws client
|
||||
│ ├── dialogs.ts # Native <dialog> modals (multi-factor step-up, confirm, prompts)
|
||||
│ ├── charts.ts # Flat SVG sparklines & metric charts (viewport-capped points)
|
||||
│ ├── ws-client.ts # Reconnecting /ws client with ref-counted subscribe()/unsubscribe
|
||||
│ ├── dialogs.ts # Native <dialog> modals (multi-factor step-up, confirm, collapsible hunk diffs)
|
||||
│ ├── charts.ts # Flat SVG sparklines & metric charts (viewport-capped points, multi-series overlay)
|
||||
│ ├── toast.ts # Live toast notification bus (lazy/core feedback helpers)
|
||||
│ ├── webauthn.ts # navigator.credentials base64url helper
|
||||
│ └── views/
|
||||
│ ├── auth-view.ts # Core static views
|
||||
│ ├── command-palette.ts # Code-split Ctrl/Cmd+K quick switcher & action palette
|
||||
│ └── views/ # All views dynamically code-split via import(...)
|
||||
│ ├── auth-view.ts
|
||||
│ ├── dashboard-view.ts
|
||||
│ ├── server-detail-view.ts
|
||||
│ ├── vault-view.ts
|
||||
│ ├── config-view.ts
|
||||
│ ├── settings-view.ts
|
||||
│ ├── terminal-view.ts # Code-split lazy views (keep dynamically imported!)
|
||||
│ ├── settings-ops-panel.ts
|
||||
│ ├── terminal-view.ts
|
||||
│ ├── xterm-runtime.ts
|
||||
│ ├── sftp-view.ts
|
||||
│ ├── tunnels-panel.ts
|
||||
|
|
@ -164,56 +186,67 @@ GCoordinator/
|
|||
│ └── ai-drawer.ts
|
||||
└── tests/
|
||||
├── helpers/mock-ssh-server.ts # In-process ssh2.Server fixture (PTY, SFTP, forwardOut, forwardIn, sudo)
|
||||
└── *.test.ts # 18 Vitest integration & unit suites
|
||||
└── *.test.ts # 21 Vitest integration & unit suites
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Critical Architectural Invariants (Must Preserve)
|
||||
|
||||
### 1. Runtime-Ready Secrets vs. Write-Only Vault Lock (`vault.ts`)
|
||||
### 1. Runtime-Ready Secrets, `seal()` & Panic Lock (`vault.ts`)
|
||||
- `vaultService.isRuntimeReady` is decoupled from `vaultService.state === 'unlocked'`.
|
||||
- At server startup (`initRuntime` in `src/server/app.ts`), established secrets are decrypted into memory using `secretFilePath`, `GCOORD_MASTER_KEY`, `data/vault.key` (`0600`), or `data/recovery/emergency-secrets.json`, while `state` begins `'locked'` (write-locked).
|
||||
- Background and established-secret consumers (`SSHPool`, `MonitoringService`, `TunnelManager`, `CustomSystemsEngine`, `WorkflowEngine`, `AlertEngine`, `AiService`, `/api/backup/export`) **must** check `isRuntimeReady` and read credentials via `getRuntimeSecret(id)` so polling, crons, SFTP, and webhooks work unattended before login and while write-locked.
|
||||
- Only Vault mutations (adding/editing/deleting credentials), Ed25519 key generation, raw secret reveals, master-key rotation, and fleet key rotation require `state === 'unlocked'`. When write-locked, these endpoints must fail with `HTTP 423 VAULT_LOCKED` (which `src/client/ts/api.ts` intercepts to prompt Vault unlock and retry automatically).
|
||||
- **Emergency Panic Lock** (`panicLock()`, persisted via `${vaultFilePath}.panic-locked`) is the **only** state that zeroes runtime secret buffers (`isRuntimeReady = false`), tears down active SSH/PTY/tunnel/AI sessions, revokes sessions (`WS 4001`), and refuses silent disk/env auto-unlock across restarts until a user manually unlocks with the master key.
|
||||
- At server startup (`initRuntime` in `src/server/app.ts`), established secrets are decrypted into memory using `secretFilePath`, `GCOORD_MASTER_KEY`, `data/vault.key` (`0600`), or `data/recovery/emergency-secrets.json`, while `state` begins `'locked'` (write-locked). `data/vault.key` is only written for locally generated keys (never mirroring `GCOORD_MASTER_KEY` or Docker secrets unless `GCOORD_AUTO_KEYFILE=true`).
|
||||
- Background and established-secret consumers (`SSHPool`, `MonitoringService`, `TunnelManager`, `CustomSystemsEngine`, `WorkflowEngine`, `AlertEngine`, `AiService`, `BackupScheduler`, `/api/backup/export`) **must** check `isRuntimeReady` and read credentials via `getRuntimeSecret(id)` so polling, crons, SFTP, and webhooks work unattended before login and while write-locked.
|
||||
- Only Vault mutations, Ed25519 key generation, raw secret reveals, master-key rotation, and fleet key rotation require `state === 'unlocked'`; write-locked mutations must fail with `HTTP 423 VAULT_LOCKED` (intercepted by `src/client/ts/api.ts`).
|
||||
- **Explicit Seal (`POST /api/vault/seal` -> `vaultService.seal()`)**: clears runtime secret buffers and pauses active background SSH/monitoring/workflow/tunnel operations **without** revoking admin HTTP/WS sessions.
|
||||
- **Emergency Panic Lock** (`panicLock()`, persisted via `${vaultFilePath}.panic-locked`): zeroes runtime secret buffers (`isRuntimeReady = false`), tears down active SSH/PTY/tunnel/AI/scheduler sessions, revokes sessions immediately (`WS 4001`), emits a `vault.panic_lock` security event, and refuses silent disk/env auto-unlock across restarts until manually unlocked with the master key.
|
||||
|
||||
### 2. Auth, Multi-Factor Strictness, Safe Mode & Passkeys (`auth.ts`, `guards.ts`)
|
||||
- Supports multiple admin passwords (`admin_passwords`) and multiple TOTPs (`admin_totps`) evaluated in `any` or `all` mode, single-use recovery codes, and `@simplewebauthn/server` Passkeys (`webauthn_credentials`; accessing WebAuthn endpoints over raw IP literals returns `WEBAUTHN_RPID_INVALID`).
|
||||
- `SecuritySettingsSchema` (`src/shared/schemas/settings.schema.ts`) configures `requireTotpOnLogin`, `stepUpPolicy` (`off | every-action | 5m | 1h | 24h | session`), `stepUpMethod` (`totp | password | both | passkey`), `elevateOnLogin`, and `keepElevationOnSafeMode`. Always gate elevated endpoints with `createStepUpGuard` rather than hardcoding 5-minute TOTP assumptions.
|
||||
- All mutating HTTP routes require an authenticated session cookie, matching `X-CSRF-Token` header, and Safe Mode enforcement (`HTTP 423 SAFE_MODE_ACTIVE` when `session.safeMode` is true; mobile viewports `< 768px` default to Safe Mode ON). Only **Panic Lock** and **`/api/backup/verify`** are Safe-Mode exempt.
|
||||
- Supports multiple admin passwords (`admin_passwords`), multiple TOTPs (`admin_totps` encrypted at rest with `data/db.key` / `GCOORD_DB_KEY` using `AES-256-GCM`, plus single-use TOTP replay tracking) evaluated in `any` or `all` mode, single-use recovery codes, rate-limited bootstrap (`15m` token TTL), and `@simplewebauthn/server` Passkeys (`webauthn_credentials`; raw IP literals return `WEBAUTHN_RPID_INVALID`).
|
||||
- Sessions enforce both absolute `sessionTtlHours` and sliding `sessionIdleTimeoutMin`; revoking sessions via logout, password reset, key/2FA reset, or Panic Lock broadcasts real-time `WS 4001` disconnects through `WsHub`.
|
||||
- `RateLimiter` is SQLite-backed (`rate_limits` table) to persist lockouts across restarts, and `attachClientIp` / Express `trust proxy` only honor forwarding headers when the socket peer matches `TRUSTED_PROXY_CIDRS` (plus loopback when `TRUST_CLOUDFLARE=true`).
|
||||
- `SecuritySettingsSchema` (`src/shared/schemas/settings.schema.ts`) configures `requireTotpOnLogin`, `stepUpPolicy` (`off | every-action | 5m | 15m | 1h | 24h | session`, default `15m`), `stepUpMethod` (`totp | password | both | passkey`), `elevateOnLogin`, and `keepElevationOnSafeMode`. Always gate elevated endpoints with `createStepUpGuard`.
|
||||
- Mutating HTTP routes require an authenticated session cookie, matching `X-CSRF-Token`, and Safe Mode enforcement (`HTTP 423 SAFE_MODE_ACTIVE`; mobile `< 768px` defaults to Safe Mode ON). Safe-Mode exemptions are limited to `/api/auth/logout`, `/api/auth/safe-mode`, Panic Lock (`/api/security/panic-lock`), `/api/backup/verify`, read-only AI draft/chat endpoints (all except `/api/ai/save-draft`), `/api/workflows/:id/dry-run`, and live cancellation endpoints (`/api/systems/streams/:jobId/cancel`, `/api/workflows/runs/:runId/cancel`, `/api/workflows/broadcast/:jobId/cancel`).
|
||||
|
||||
### 3. Dual Backup Subsystems (`recovery-store.ts` vs. `backup.ts`)
|
||||
- **Local Emergency Secrets Store (`recovery-store.ts`)**: When `settings.security.enableEmergencySecretsBackup` is enabled, `EmergencyRecoveryService` maintains `data/recovery/emergency-secrets.json` (`chmod 0600`) plus up to 10 snapshots under `data/recovery/snapshots/`. Keep `syncRecovery()` wired after auth/vault mutations.
|
||||
- **Portable Encrypted Bundles (`backup.ts`)**: Creates, verifies, and restores `GCOORD_BACKUP_V1` `.gcoord.enc` bundles encrypted with `AES-256-GCM` (`raw-master-key` or `scrypt` passphrase KDF) containing gzipped `config/**` JSONs (including `servers/*.json` `systems[].itemOverrides` / `activeFiles[]`), `vault.enc`, and SQLite `known_hosts` + `alert_silences`.
|
||||
- **Linux `inotify` Rule on Config Restore**: Whenever swapping or replacing `data/config/` while the server is running (e.g., `/api/backup/restore`), **always** call `configManager.pauseWatcher()` before replacing the directory and `reloadAllFromDisk()` + `await configManager.resumeWatcher()` afterward; otherwise `chokidar` retains stale directory inodes and stops firing hot-reload events.
|
||||
### 3. Dual Backup Subsystems (`recovery-store.ts`, `backup.ts`, `backup-scheduler.ts`)
|
||||
- **Local Emergency Secrets Store (`recovery-store.ts`)**: When `settings.security.enableEmergencySecretsBackup` is enabled, `EmergencyRecoveryService` maintains a **passwordless** `data/recovery/emergency-secrets.json` (`chmod 0600`, Vault/key/TOTP recovery data only—never stores plaintext admin login passwords) plus up to 10 snapshots under `data/recovery/snapshots/`. Keep `syncRecovery()` wired after auth/vault mutations.
|
||||
- **Portable Encrypted Bundles (`backup.ts` & `backup-scheduler.ts`)**: Creates, verifies, and restores `GCOORD_BACKUP_V1` `.gcoord.enc` bundles encrypted with `AES-256-GCM` (`raw-master-key` or `scrypt` passphrase KDF) via non-blocking async workers (`createBackupBundleAsync`) bounded by `runtimeLimits`, plus scheduled local/SFTP backups with retention pruning.
|
||||
- **Linux `inotify` Rule on Config Restore**: Whenever replacing `data/config/` while running (`/api/backup/restore`), **always** call `configManager.pauseWatcher()` before replacing the directory and `reloadAllFromDisk()` + `await configManager.resumeWatcher()` afterward so `chokidar` re-attaches cleanly to new directory inodes.
|
||||
|
||||
### 4. Config Hot-Reload & SQLite Migrations (`config-manager.ts`, `database.ts`)
|
||||
- Every config write must be atomic (`tmp -> fsync -> rename`), validated against Zod schemas, and recorded in SQLite `config_revisions` for diff/rollback. Hand-edited invalid config files must remain isolated without crashing the hub or clobbering valid files.
|
||||
- Never mutate existing migration files (`001_initial.ts`, `002_multi_auth.ts`, `003_phase4_meta.ts`) destructively; add new schema changes as `004_*.ts` and register them in `src/server/db/database.ts`.
|
||||
### 4. Runtime Throttle Profile & Lightweight Footprint (`runtime-limits.ts`, `settings.schema.ts`)
|
||||
- `settings.runtime.throttleMode` defaults to `'low-resource'` (sized for single-core 1 vCPU / 1 GB RAM + 2 GB Swap deployments) and supports `'balanced'` and `'unthrottled'` (overrideable via `GCOORD_THROTTLE_MODE`).
|
||||
- `resolveRuntimeLimits()` governs Argon2id memory/concurrency/queueing (`piscina`/mutex semaphore), `scrypt` concurrency, backup unzip/body limits, SQLite PRAGMAs (`cache_size`, `mmap_size`, `temp_store`), max active/retained PTYs & default scrollback bytes, staggered & concurrency-capped metric polling, parallel systems inspection & cache size, workflow concurrency/targets/queue/log bytes, WS replay buffer sizes, AI stream concurrency, and tunnel socket caps. Always consume limits via `getRuntimeLimits()` rather than hardcoding unbounded concurrency.
|
||||
|
||||
### 5. SSH, Shell Quoting, Crypto & Tunnel Proxy Rules
|
||||
- **No Shell Injection**: Never interpolate user inputs, workflow variables, or parameters directly into shell strings. Pass inputs via `GCOORD_*` environment variables (`buildWorkflowEnv`, `GCOORD_PARAM_*`) or sanitize explicitly with `interpolateShellCommandSafe()` (`src/server/automation/template.ts`) / POSIX single-quoting in `src/server/ssh/sudo.ts` (and zeroize `sudo` password `Buffer`s right after writing to stdin).
|
||||
- **`ssh2` Ed25519 Keygen Bug**: Always generate Ed25519 keys through `generateValidEd25519KeyPair()` in `src/server/security/vault.ts` (retries around `ssh2`'s ASN.1 leading-`0x00` BitString parser issue).
|
||||
- **Direct `rsync` Channel Drain**: In `TransferEngine` (`src/server/automation/transfer-engine.ts`), always drain/consume SSH channel `stdout` and `stderr` streams so `close` never deadlocks on full flow-control windows.
|
||||
- **Reverse Proxy Isolation**: In `src/server/app.ts`, keep `/proxy` mounted **before** `express.json()` and exempt `/proxy/*` from the hub SPA Content-Security-Policy. `TunnelManager` (`src/server/ssh/tunnel-manager.ts`) must keep stripping `gcoord_sid` and `gcoord_csrf` cookies from forwarded headers and rewriting relative `Location` redirects.
|
||||
### 5. Config Hot-Reload, Symlink Safety & SQLite Migrations (`config-manager.ts`, `database.ts`)
|
||||
- Every config write uses atomic staging (`tmp -> fsync -> rename`), rejects symlinks across config/backup/CLI file operations, validates against Zod schemas, and records `config_revisions`. Invalid hand-edited config files stay isolated without crashing the hub.
|
||||
- Never mutate existing migration files (`001_initial.ts`, `002_multi_auth.ts`, `003_phase4_meta.ts`, `004_v1_1.ts`) destructively; add new schema changes as `005_*.ts` and register them in `src/server/db/database.ts`.
|
||||
|
||||
### 6. Optional BYO-API AI Assistant (`src/server/ai/`)
|
||||
- Strictly opt-in: return `403 AI_DISABLED` whenever `settings.ai.enabled === false` and hide `[AI ...]` triggers in the UI unless `isAiEnabled(state)` is true.
|
||||
- Sanitize all outbound AI prompts and context previews through `redactSecrets()` (`redactor.ts`) seeded with `collectVaultSecretStrings()`.
|
||||
- Never auto-execute AI-suggested shell commands or auto-save AI-generated JSON/system/workflow drafts—require server Zod `validateDraft`, line diff preview, and explicit user confirmation in `ai-drawer.ts`.
|
||||
### 6. SSH, Shell Quoting, Egress Guard & Dual-Mode Isolated Proxy (`egress-guard.ts`, `tunnel-manager.ts`)
|
||||
- **Zero-Trust Egress Guard (`egress-guard.ts`)**: All outbound hub HTTP calls (HTTP probes, webhook deliveries, BYO AI requests, workflow `http` steps) must go through `fetchWithEgressGuard()` / `assertSafeEgressUrl()`, which default-denies loopback, private, link-local, carrier-grade NAT, and cloud-metadata IPs/DNS resolutions, disables automatic redirects (`redirect: 'error'`), and honors explicit `settings.security.egressAllowedCidrs` opt-ins.
|
||||
- **No Shell Injection**: Never interpolate user inputs, workflow variables, or PTY `cwd` directly into shell strings. Pass inputs via `GCOORD_*` environment variables (`buildWorkflowEnv`, `GCOORD_PARAM_*`) or sanitize explicitly with `interpolateShellCommandSafe()` (`template.ts`), `formatRemoteCd()` (`pty-manager.ts`), and POSIX single-quoting (`sudo.ts`, zeroizing password `Buffer`s immediately after writing).
|
||||
- **Direct `rsync` & `ssh2` Invariants**: Generate Ed25519 keys via `generateValidEd25519KeyPair()` (`vault.ts`), validate all host-key algorithms in `known-hosts.ts`, drain SSH channel `stdout`/`stderr` streams in `TransferEngine`, and enforce symlink-safe `lstat` checks in `sftp-service.ts`.
|
||||
- **Dual-Mode Isolated Reverse Proxy (`tunnel-manager.ts`, `app.ts`)**:
|
||||
- Prefer origin-isolated proxying via `GCOORD_PROXY_PORT` (dedicated local port) or `GCOORD_PROXY_BASE_DOMAIN` (wildcard subdomain), bridged via single-use `/proxy-ticket` redemption into a proxy-scoped `gcoord_proxy_sid` session so proxied target apps cannot share hub origin cookies or storage.
|
||||
- Same-origin `/proxy` requests are rejected with `HTTP 403 PROXY_ISOLATION_NOT_CONFIGURED` unless `settings.security.allowSameOriginProxy: true` is explicitly enabled.
|
||||
- Keep `/proxy` mounted before `express.json()`, exempt `/proxy/*` from the hub CSP, strip `gcoord_sid` / `gcoord_csrf` / `gcoord_proxy_sid` cookies upstream, rewrite relative `Location` redirects, and support HTTPS upstream, SOCKS5 (`mode: 'socks5'`), and TTL auto-expiry.
|
||||
|
||||
### 7. Alerts, Prometheus `/metrics` & BYO-API AI (`alerts/`, `prometheus.ts`, `ai/`)
|
||||
- Alert channels strictly allow only `webhook-secret` Vault credential IDs (preventing arbitrary Vault credential exfiltration in webhook headers/bodies) and dispatch `security-event` alerts emitted by Auth, KnownHosts, and Vault Panic Lock.
|
||||
- Prometheus `GET /metrics` (`prometheus.ts`) is opt-in (`settings.metrics.prometheusEnabled`) and Bearer-authenticated against `GCOORD_METRICS_TOKEN`, the rotated SHA-256 token hash from `POST /api/config/prometheus-token`, or a Vault `api-token`/`webhook-secret` ref (`404` when disabled, `401` when unauthenticated).
|
||||
- AI Assistant (`src/server/ai/`): opt-in (`403 AI_DISABLED` when disabled), linear-time `O(n)` secret redaction (`redactor.ts`), and mandatory server Zod `validateDraft` + diff review before saving/running anything.
|
||||
|
||||
---
|
||||
|
||||
## 5. Frontend, Bundle Budget & Mobile Rules
|
||||
|
||||
### Hard Gzip Budgets (`src/client/build.ts` — throws and fails build if exceeded)
|
||||
- **Core bundle** (`index.html` + `themes.css` + `base.css` + `main.js`): strictly **`< 50.00 KB` gzipped** (currently `25.46 KB`).
|
||||
- **Core bundle** (`index.html` + `themes.css` + `base.css` + `main.js` + all recursive static ESM imports of `main.js`): strictly **`< 50.00 KB` gzipped** (currently `15.80 KB`).
|
||||
- **Every non-terminal lazy chunk** (`dist/public/chunks/*.js` except `terminal-view-*`): strictly **`< 20.00 KB` gzipped**.
|
||||
|
||||
### CRITICAL: Zero Runtime `zod` in Client Code
|
||||
- **NEVER** import runtime schemas or runtime values from `src/shared/schemas/*` or `zod` anywhere inside `src/client/ts/**`. Importing Zod into client TypeScript drags Zod into `main.js` or lazy chunks and breaks the gzip budgets.
|
||||
- Use `import type { ... } from '../../shared/...'` exclusively, mirror minimal constants cleanly in `src/client/ts/state.ts` (such as `CLIENT_THEME_IDS`), and keep heavy secondary views (`terminal-view`, `sftp-view`, `systems-view`, `workflows-view`, `alerts-view`, `ai-drawer`, `tunnels-panel`) code-split via dynamic `import(...)`.
|
||||
### CRITICAL: Zero Runtime `zod` & View Lifecycle in Client Code
|
||||
- **NEVER** import runtime schemas or runtime values from `src/shared/schemas/*` or `zod` anywhere inside `src/client/ts/**`. Use `import type` exclusively and mirror minimal constants cleanly in `src/client/ts/state.ts`.
|
||||
- Keep **all** views (`auth-view`, `dashboard-view`, `server-detail-view`, `vault-view`, `config-view`, `settings-view`, `settings-ops-panel`, `terminal-view`, `sftp-view`, `tunnels-panel`, `systems-view`, `workflows-view`, `alerts-view`, `ai-drawer`) plus `command-palette.ts` dynamically imported (`import(...)`) so initial core JS stays minimal.
|
||||
- Every view/panel with timers, DOM window listeners, xterm instances, or dynamic WS channels **must** register teardown via `registerViewCleanup()` (`state.ts`, flushed on navigation by `main.ts`) and use ref-counted `wsClient.subscribe()` cleanup callbacks (which send `{ type: 'unsub' }` when refcount hits 0).
|
||||
|
||||
### Flat Sharp Aesthetic & 8 Themes
|
||||
- Maintain the zero-overhead aesthetic: `border-radius: 0`, `1px` crisp borders, zero `box-shadow`, zero gradients, zero `backdrop-filter`.
|
||||
|
|
|
|||
|
|
@ -18,19 +18,21 @@ FROM node:22-bookworm-slim AS runtime
|
|||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ca-certificates openssh-client rsync zstd tar \
|
||||
ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& mkdir -p /data && chown -R 1000:1000 /app /data
|
||||
&& mkdir -p /data && chown 1000:1000 /data && chmod 0700 /data
|
||||
|
||||
COPY --from=builder --chown=1000:1000 /app/package.json ./
|
||||
COPY --from=builder --chown=1000:1000 /app/node_modules ./node_modules
|
||||
COPY --from=builder --chown=1000:1000 /app/dist ./dist
|
||||
COPY --from=builder /app/package.json ./
|
||||
COPY --from=builder /app/node_modules ./node_modules
|
||||
COPY --from=builder /app/dist ./dist
|
||||
|
||||
USER 1000:1000
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
PORT=3000 \
|
||||
GCOORD_DATA_DIR=/data
|
||||
HOST=0.0.0.0 \
|
||||
GCOORD_DATA_DIR=/data \
|
||||
NODE_OPTIONS="--max-old-space-size=384"
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ services:
|
|||
gcoordinator:
|
||||
environment:
|
||||
- TRUST_CLOUDFLARE=false
|
||||
- GCOORD_ALLOW_LAN_TUNNELS=${GCOORD_ALLOW_LAN_TUNNELS:-false}
|
||||
ports:
|
||||
- "${GCOORD_LAN_BIND:-127.0.0.1}:3000:3000"
|
||||
- "${GCOORD_LAN_BIND:-127.0.0.1}:20000-20020:20000-20020"
|
||||
|
|
|
|||
|
|
@ -7,13 +7,22 @@ services:
|
|||
restart: unless-stopped
|
||||
user: "1000:1000"
|
||||
read_only: true
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: ${GCOORD_MEM_LIMIT:-512m}
|
||||
pids_limit: 128
|
||||
tmpfs:
|
||||
- /tmp
|
||||
- /tmp:rw,noexec,nosuid,nodev,size=64m
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- PORT=3000
|
||||
- HOST=0.0.0.0
|
||||
- GCOORD_DATA_DIR=/data
|
||||
- TRUST_CLOUDFLARE=true
|
||||
- GCOORD_THROTTLE_MODE=${GCOORD_THROTTLE_MODE:-low-resource}
|
||||
- NODE_OPTIONS=--max-old-space-size=${GCOORD_NODE_MAX_OLD_SPACE:-384}
|
||||
secrets:
|
||||
- gcoord_master_key
|
||||
volumes:
|
||||
|
|
@ -26,6 +35,13 @@ services:
|
|||
image: cloudflare/cloudflared:latest
|
||||
container_name: gcoordinator-tunnel
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 128m
|
||||
pids_limit: 64
|
||||
command: tunnel --no-autoupdate run
|
||||
environment:
|
||||
- TUNNEL_TOKEN=${CLOUDFLARED_TUNNEL_TOKEN}
|
||||
|
|
|
|||
4
package-lock.json
generated
4
package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "gcoordinator",
|
||||
"version": "0.1.0",
|
||||
"version": "1.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gcoordinator",
|
||||
"version": "0.1.0",
|
||||
"version": "1.1.0",
|
||||
"dependencies": {
|
||||
"@simplewebauthn/server": "^13.1.1",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "gcoordinator",
|
||||
"version": "0.1.0",
|
||||
"version": "1.1.0",
|
||||
"description": "Self-hosted, security-first central sysadmin hub for multiplexed SSH access, monitoring, custom systems, workflows, and alerting.",
|
||||
"type": "module",
|
||||
"engines": {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,16 @@
|
|||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import readline from 'node:readline/promises';
|
||||
import { parseArgs } from 'node:util';
|
||||
import argon2 from 'argon2';
|
||||
import Database from 'better-sqlite3';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { openDatabase } from '../server/db/database.js';
|
||||
import {
|
||||
encryptTotpSecret,
|
||||
loadOrCreateDbKey,
|
||||
} from '../server/security/auth.js';
|
||||
import {
|
||||
createBackupBundle,
|
||||
restoreBackupBundle,
|
||||
|
|
@ -9,24 +18,42 @@ import {
|
|||
} from '../server/security/backup.js';
|
||||
import { EmergencyRecoveryService } from '../server/security/recovery-store.js';
|
||||
import { VaultService } from '../server/security/vault.js';
|
||||
import { SettingsSchema } from '../shared/schemas/settings.schema.js';
|
||||
|
||||
function printUsage(): void {
|
||||
console.log(`GCoordinator CLI (gcoord)
|
||||
|
||||
Commands:
|
||||
status Inspect GCoordinator data directory state (read-only)
|
||||
--data-dir <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
|
||||
--data-dir <path> Data directory (default: GCOORD_DATA_DIR or ./data)
|
||||
--current-key-file <path> Path to file containing current 32-byte key
|
||||
--new-key-out <path> Optional output file (0600) for generated key
|
||||
--new-key-out <path> Exclusive output file (0600, O_EXCL) for generated key
|
||||
|
||||
backup Create an AES-256-GCM .gcoord.enc portable backup bundle
|
||||
--out <path.gcoord.enc> Output bundle path (required)
|
||||
--data-dir <path> Data directory (default: GCOORD_DATA_DIR or ./data)
|
||||
--key-file <path> Path to 32-byte Vault master key (default mode)
|
||||
--passphrase-file <path> Path to passphrase file (overrides key-file using scrypt)
|
||||
--passphrase-file <path> Path to passphrase file (>= 12 chars, uses scrypt)
|
||||
|
||||
verify-backup Verify GCM tag, JSON schemas, and Vault envelope without modifying data
|
||||
<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
|
||||
--passphrase-file <path> Path to backup passphrase file
|
||||
--vault-key-file <path> Optional Vault master key to also decrypt/verify vault.enc
|
||||
|
|
@ -41,7 +68,153 @@ 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> {
|
||||
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({
|
||||
input: process.stdin,
|
||||
output: process.stderr,
|
||||
|
|
@ -56,18 +229,19 @@ async function promptHiddenOrLine(promptText: string): Promise<string> {
|
|||
|
||||
async function readCurrentKey(keyFile?: string, dataDir?: string): Promise<string> {
|
||||
if (keyFile) {
|
||||
return fs.readFileSync(keyFile, 'utf8').trim();
|
||||
return readRegularFileStrict(keyFile);
|
||||
}
|
||||
if (process.env.GCOORD_MASTER_KEY?.trim()) {
|
||||
return process.env.GCOORD_MASTER_KEY.trim();
|
||||
}
|
||||
if (fs.existsSync('/run/secrets/gcoord_master_key')) {
|
||||
return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim();
|
||||
const secretPath = process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key';
|
||||
if (fs.existsSync(secretPath)) {
|
||||
return readRegularFileStrict(secretPath);
|
||||
}
|
||||
if (dataDir) {
|
||||
const localKeyFile = path.join(path.resolve(dataDir), 'vault.key');
|
||||
if (fs.existsSync(localKeyFile)) {
|
||||
return fs.readFileSync(localKeyFile, 'utf8').trim();
|
||||
return readRegularFileStrict(localKeyFile);
|
||||
}
|
||||
}
|
||||
return promptHiddenOrLine('Enter current 32-byte vault master key (hex or base64): ');
|
||||
|
|
@ -75,18 +249,19 @@ async function readCurrentKey(keyFile?: string, dataDir?: string): Promise<strin
|
|||
|
||||
function readOptionalKeyNonInteractive(keyFile?: string, dataDir?: string): string | undefined {
|
||||
if (keyFile) {
|
||||
return fs.readFileSync(keyFile, 'utf8').trim();
|
||||
return readRegularFileStrict(keyFile);
|
||||
}
|
||||
if (process.env.GCOORD_MASTER_KEY?.trim()) {
|
||||
return process.env.GCOORD_MASTER_KEY.trim();
|
||||
}
|
||||
if (fs.existsSync('/run/secrets/gcoord_master_key')) {
|
||||
return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim();
|
||||
const secretPath = process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key';
|
||||
if (fs.existsSync(secretPath)) {
|
||||
return readRegularFileStrict(secretPath);
|
||||
}
|
||||
if (dataDir) {
|
||||
const localKeyFile = path.join(path.resolve(dataDir), 'vault.key');
|
||||
if (fs.existsSync(localKeyFile)) {
|
||||
return fs.readFileSync(localKeyFile, 'utf8').trim();
|
||||
return readRegularFileStrict(localKeyFile);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
|
|
@ -94,7 +269,7 @@ function readOptionalKeyNonInteractive(keyFile?: string, dataDir?: string): stri
|
|||
|
||||
function readOptionalPassphrase(passphraseFile?: string): string | undefined {
|
||||
if (passphraseFile) {
|
||||
return fs.readFileSync(passphraseFile, 'utf8').trim();
|
||||
return readRegularFileStrict(passphraseFile);
|
||||
}
|
||||
if (process.env.GCOORD_BACKUP_PASSPHRASE?.trim()) {
|
||||
return process.env.GCOORD_BACKUP_PASSPHRASE.trim();
|
||||
|
|
@ -102,6 +277,310 @@ function readOptionalPassphrase(passphraseFile?: string): string | 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> {
|
||||
const parsed = parseArgs({
|
||||
args,
|
||||
|
|
@ -122,32 +601,40 @@ async function runRotateKey(args: string[]): Promise<number> {
|
|||
return 1;
|
||||
}
|
||||
|
||||
const currentKey = await readCurrentKey(parsed.values['current-key-file']);
|
||||
const vault = new VaultService(vaultPath);
|
||||
vault.unlock(currentKey);
|
||||
const { generatedKeyHex } = vault.rotateMasterKey();
|
||||
return withDataDirLock(dataDir, async () => {
|
||||
const currentKey = await readCurrentKey(parsed.values['current-key-file'], dataDir);
|
||||
const vault = new VaultService(vaultPath, {
|
||||
keyFilePath: path.join(dataDir, 'vault.key'),
|
||||
});
|
||||
vault.unlock(currentKey);
|
||||
const { generatedKeyHex } = vault.rotateMasterKey();
|
||||
|
||||
if (!generatedKeyHex) {
|
||||
console.error('Error: Unexpected empty rotated key');
|
||||
return 1;
|
||||
}
|
||||
if (!generatedKeyHex) {
|
||||
console.error('Error: Unexpected empty rotated key');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const recovery = new EmergencyRecoveryService(dataDir);
|
||||
if (recovery.readBundle() !== null) {
|
||||
recovery.syncState({ enabled: true, vault, snapshotReason: 'cli-rotate-key' });
|
||||
}
|
||||
const recovery = new EmergencyRecoveryService(dataDir);
|
||||
const settings = loadSettingsObject(dataDir) as {
|
||||
security?: { enableEmergencySecretsBackup?: boolean };
|
||||
};
|
||||
if (
|
||||
settings.security?.enableEmergencySecretsBackup &&
|
||||
recovery.readBundle() !== null
|
||||
) {
|
||||
recovery.syncState({ enabled: true, vault, snapshotReason: 'cli-rotate-key' });
|
||||
}
|
||||
|
||||
if (parsed.values['new-key-out']) {
|
||||
const outPath = path.resolve(parsed.values['new-key-out']);
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
fs.writeFileSync(outPath, `${generatedKeyHex}\n`, { mode: 0o600 });
|
||||
fs.chmodSync(outPath, 0o600);
|
||||
console.log(`Vault master key rotated cleanly. New key written to ${outPath} (mode 0600).`);
|
||||
} else {
|
||||
console.log('Vault master key rotated cleanly. Store this new key securely:');
|
||||
console.log(generatedKeyHex);
|
||||
}
|
||||
return 0;
|
||||
if (parsed.values['new-key-out']) {
|
||||
const outPath = path.resolve(parsed.values['new-key-out']);
|
||||
writeExclusiveSecureFile(outPath, `${generatedKeyHex}\n`);
|
||||
console.log(`Vault master key rotated cleanly. New key written to ${outPath} (mode 0600).`);
|
||||
} else {
|
||||
console.log('Vault master key rotated cleanly. Store this new key securely:');
|
||||
console.log(generatedKeyHex);
|
||||
}
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
async function runBackup(args: string[]): Promise<number> {
|
||||
|
|
@ -183,17 +670,7 @@ async function runBackup(args: string[]): Promise<number> {
|
|||
});
|
||||
|
||||
const outPath = path.resolve(outRaw);
|
||||
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);
|
||||
writeAtomicSecureFile(outPath, result.serialized);
|
||||
|
||||
console.log(
|
||||
`Backup created at ${outPath} (kdf=${result.summary.kdf}, configs=${result.summary.configFileCount}, knownHosts=${result.summary.knownHostsCount}, vaultVerified=${result.summary.vaultVerified})`,
|
||||
|
|
@ -206,6 +683,7 @@ async function runVerifyBackup(args: string[]): Promise<number> {
|
|||
args,
|
||||
options: {
|
||||
bundle: { type: 'string' },
|
||||
'data-dir': { type: 'string' },
|
||||
'key-file': { type: 'string' },
|
||||
'passphrase-file': { type: 'string' },
|
||||
'vault-key-file': { type: 'string' },
|
||||
|
|
@ -220,17 +698,26 @@ async function runVerifyBackup(args: string[]): Promise<number> {
|
|||
return 1;
|
||||
}
|
||||
|
||||
const rawBuf = fs.readFileSync(path.resolve(bundleArg));
|
||||
const dataDir = parsed.values['data-dir']
|
||||
? path.resolve(parsed.values['data-dir'])
|
||||
: process.env.GCOORD_DATA_DIR
|
||||
? path.resolve(process.env.GCOORD_DATA_DIR)
|
||||
: undefined;
|
||||
|
||||
const bundlePath = path.resolve(bundleArg);
|
||||
const rawBuf = Buffer.from(readRegularFileStrict(bundlePath), 'utf8');
|
||||
const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']);
|
||||
let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file']);
|
||||
let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir);
|
||||
if (!passphrase && !masterKey) {
|
||||
const rawMeta = JSON.parse(rawBuf.toString('utf8')) as { kdf?: string };
|
||||
if (rawMeta.kdf === 'scrypt') {
|
||||
throw new Error('Passphrase required for scrypt-encrypted backup (--passphrase-file or GCOORD_BACKUP_PASSPHRASE)');
|
||||
throw new Error(
|
||||
'Passphrase required for scrypt-encrypted backup (--passphrase-file or GCOORD_BACKUP_PASSPHRASE)',
|
||||
);
|
||||
}
|
||||
masterKey = await readCurrentKey(undefined);
|
||||
masterKey = await readCurrentKey(undefined, dataDir);
|
||||
}
|
||||
const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file']);
|
||||
const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir);
|
||||
|
||||
const summary = verifyBackupSummaryOnly(rawBuf, {
|
||||
masterKey,
|
||||
|
|
@ -270,25 +757,28 @@ async function runRestore(args: string[]): Promise<number> {
|
|||
const dataDir = path.resolve(
|
||||
parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data',
|
||||
);
|
||||
const rawBuf = fs.readFileSync(path.resolve(bundleArg));
|
||||
const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']);
|
||||
let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir);
|
||||
if (!passphrase && !masterKey) {
|
||||
masterKey = await readCurrentKey(undefined, dataDir);
|
||||
}
|
||||
const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir);
|
||||
|
||||
const { summary } = restoreBackupBundle(rawBuf, {
|
||||
dataDir,
|
||||
masterKey,
|
||||
passphrase,
|
||||
vaultMasterKey,
|
||||
return withDataDirLock(dataDir, async () => {
|
||||
const rawBuf = Buffer.from(readRegularFileStrict(bundleArg), 'utf8');
|
||||
const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']);
|
||||
let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir);
|
||||
if (!passphrase && !masterKey) {
|
||||
masterKey = await readCurrentKey(undefined, dataDir);
|
||||
}
|
||||
const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir);
|
||||
|
||||
const { summary } = restoreBackupBundle(rawBuf, {
|
||||
dataDir,
|
||||
masterKey,
|
||||
passphrase,
|
||||
vaultMasterKey,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`Restored GCoordinator state to ${dataDir} (configs=${summary.configFileCount}, knownHosts=${summary.knownHostsCount}, silences=${summary.alertSilenceCount})`,
|
||||
);
|
||||
return 0;
|
||||
});
|
||||
|
||||
console.log(
|
||||
`Restored GCoordinator state to ${dataDir} (configs=${summary.configFileCount}, knownHosts=${summary.knownHostsCount}, silences=${summary.alertSilenceCount})`,
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
|
|
@ -298,22 +788,25 @@ async function main(): Promise<void> {
|
|||
process.exit(0);
|
||||
}
|
||||
|
||||
if (command === 'rotate-key') {
|
||||
process.exit(await runRotateKey(rest));
|
||||
}
|
||||
if (command === 'backup') {
|
||||
process.exit(await runBackup(rest));
|
||||
}
|
||||
if (command === 'verify-backup') {
|
||||
process.exit(await runVerifyBackup(rest));
|
||||
}
|
||||
if (command === 'restore') {
|
||||
process.exit(await runRestore(rest));
|
||||
const handlers: Record<string, (args: string[]) => Promise<number>> = {
|
||||
status: runStatus,
|
||||
'panic-lock': runPanicLock,
|
||||
'reset-2fa': runReset2fa,
|
||||
'reset-password': runResetPassword,
|
||||
'rotate-key': runRotateKey,
|
||||
backup: runBackup,
|
||||
'verify-backup': runVerifyBackup,
|
||||
restore: runRestore,
|
||||
};
|
||||
|
||||
const handler = handlers[command];
|
||||
if (!handler) {
|
||||
console.error(`Unknown command: ${command}`);
|
||||
printUsage();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.error(`Unknown command: ${command}`);
|
||||
printUsage();
|
||||
process.exit(1);
|
||||
process.exit(await handler(rest));
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
|
|
|
|||
|
|
@ -8,17 +8,52 @@ const LAZY_CHUNK_BUDGET_BYTES = 20 * 1024;
|
|||
const clientDir = path.resolve('src/client');
|
||||
const outDir = path.resolve('dist/public');
|
||||
|
||||
function normalizeOutKey(rawPath: string): string {
|
||||
const rel = path.relative(outDir, path.resolve(rawPath));
|
||||
return rel.replace(/\\/g, '/');
|
||||
}
|
||||
|
||||
function collectSyncImports(
|
||||
metaOutputs: Record<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> {
|
||||
fs.rmSync(outDir, { recursive: true, force: true });
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
|
||||
await esbuild.build({
|
||||
const jsResult = await esbuild.build({
|
||||
entryPoints: [path.join(clientDir, 'ts', 'main.ts')],
|
||||
bundle: true,
|
||||
format: 'esm',
|
||||
splitting: true,
|
||||
minify: true,
|
||||
sourcemap: false,
|
||||
metafile: true,
|
||||
target: 'es2020',
|
||||
outdir: outDir,
|
||||
entryNames: '[name]',
|
||||
|
|
@ -46,18 +81,22 @@ async function buildClient(): Promise<void> {
|
|||
fs.copyFileSync(path.join(clientDir, asset), path.join(outDir, asset));
|
||||
}
|
||||
|
||||
const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js'];
|
||||
const syncJsChunks = jsResult.metafile
|
||||
? collectSyncImports(jsResult.metafile.outputs, 'main.js').filter((k) => k !== 'main.js')
|
||||
: [];
|
||||
|
||||
const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js', ...syncJsChunks];
|
||||
let totalRaw = 0;
|
||||
let totalGzip = 0;
|
||||
|
||||
for (const file of coreAssets) {
|
||||
const buf = fs.readFileSync(path.join(outDir, file));
|
||||
const fullPath = path.join(outDir, file);
|
||||
if (!fs.existsSync(fullPath)) continue;
|
||||
const buf = fs.readFileSync(fullPath);
|
||||
const gz = zlib.gzipSync(buf, { level: 9 });
|
||||
totalRaw += buf.length;
|
||||
totalGzip += gz.length;
|
||||
console.log(
|
||||
` ${file.padEnd(14)} raw=${buf.length}B gzip=${gz.length}B`,
|
||||
);
|
||||
console.log(` ${file.padEnd(24)} raw=${buf.length}B gzip=${gz.length}B`);
|
||||
}
|
||||
|
||||
const chunksDir = path.join(outDir, 'chunks');
|
||||
|
|
@ -65,7 +104,8 @@ async function buildClient(): Promise<void> {
|
|||
for (const chunk of fs.readdirSync(chunksDir).sort()) {
|
||||
const cBuf = fs.readFileSync(path.join(chunksDir, chunk));
|
||||
const cGz = zlib.gzipSync(cBuf, { level: 9 });
|
||||
console.log(` chunks/${chunk.padEnd(28)} raw=${cBuf.length}B gzip=${cGz.length}B`);
|
||||
const syncTag = syncJsChunks.includes(`chunks/${chunk}`) ? ' [sync-core]' : '';
|
||||
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) {
|
||||
throw new Error(
|
||||
`Lazy chunk ${chunk} (${cGz.length}B gzipped) exceeded 20KB budget (${LAZY_CHUNK_BUDGET_BYTES}B)`,
|
||||
|
|
|
|||
|
|
@ -699,3 +699,87 @@ dialog.ai-drawer[open] {
|
|||
padding: 6px 10px;
|
||||
}
|
||||
}
|
||||
|
||||
.sr-only-focusable:focus {
|
||||
position: static;
|
||||
width: auto;
|
||||
height: auto;
|
||||
overflow: visible;
|
||||
clip: auto;
|
||||
white-space: normal;
|
||||
display: inline-block;
|
||||
margin-bottom: 6px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--accent);
|
||||
background: var(--bg-panel);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.toast-region {
|
||||
position: fixed;
|
||||
right: 12px;
|
||||
bottom: 12px;
|
||||
z-index: 40;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
max-width: min(380px, calc(100vw - 24px));
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.toast-item {
|
||||
pointer-events: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-panel);
|
||||
color: var(--fg);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.toast-ok {
|
||||
border-color: var(--ok);
|
||||
}
|
||||
|
||||
.toast-warn {
|
||||
border-color: var(--warn);
|
||||
}
|
||||
|
||||
.toast-err {
|
||||
border-color: var(--err);
|
||||
}
|
||||
|
||||
.cmd-palette-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
max-height: 55vh;
|
||||
overflow-y: auto;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.cmd-palette-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.cmd-palette-item.active {
|
||||
border-color: var(--accent);
|
||||
background: var(--bg-elevated);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.diff-hunk-sep {
|
||||
padding: 2px 6px;
|
||||
margin: 4px 0;
|
||||
border-top: 1px dashed var(--border);
|
||||
border-bottom: 1px dashed var(--border);
|
||||
color: var(--fg-muted);
|
||||
font-size: 0.78rem;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@
|
|||
</head>
|
||||
<body>
|
||||
<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>
|
||||
<div class="topbar-brand">
|
||||
<span class="brand-mark">>_ GCOORD</span>
|
||||
|
|
@ -33,6 +34,7 @@
|
|||
<option value="tokyo-night">tokyo-night</option>
|
||||
<option value="high-contrast">high-contrast</option>
|
||||
</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="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>
|
||||
|
|
@ -161,14 +163,29 @@
|
|||
<input id="srv-tags" name="tags" placeholder="prod, web">
|
||||
</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>
|
||||
<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 type="submit" class="btn btn-primary mutating-action">Register Server</button>
|
||||
</div>
|
||||
</form>
|
||||
</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>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -97,3 +97,44 @@ export function createRangeChartSvg(
|
|||
svg.appendChild(poly);
|
||||
return svg;
|
||||
}
|
||||
|
||||
export function createDualRangeChartSvg(
|
||||
seriesA: number[],
|
||||
seriesB: number[],
|
||||
options: { colorA?: string; colorB?: string; maxVal?: number } = {},
|
||||
): SVGSVGElement {
|
||||
const computedMax =
|
||||
options.maxVal ??
|
||||
Math.max(
|
||||
1,
|
||||
...seriesA.map((v) => (Number.isFinite(v) ? v : 0)),
|
||||
...seriesB.map((v) => (Number.isFinite(v) ? v : 0)),
|
||||
);
|
||||
|
||||
const svg = document.createElementNS(SVG_NS, 'svg');
|
||||
svg.setAttribute('viewBox', '0 0 600 120');
|
||||
svg.setAttribute('preserveAspectRatio', 'none');
|
||||
svg.setAttribute('class', 'chart-svg');
|
||||
|
||||
const midLine = document.createElementNS(SVG_NS, 'line');
|
||||
midLine.setAttribute('x1', '0');
|
||||
midLine.setAttribute('y1', '60');
|
||||
midLine.setAttribute('x2', '600');
|
||||
midLine.setAttribute('y2', '60');
|
||||
midLine.setAttribute('stroke', 'var(--border)');
|
||||
midLine.setAttribute('stroke-dasharray', '4 4');
|
||||
svg.appendChild(midLine);
|
||||
|
||||
const addLine = (vals: number[], stroke: string) => {
|
||||
const poly = document.createElementNS(SVG_NS, 'polyline');
|
||||
poly.setAttribute('fill', 'none');
|
||||
poly.setAttribute('stroke', stroke);
|
||||
poly.setAttribute('stroke-width', '2');
|
||||
poly.setAttribute('points', buildPolylinePoints(vals, 600, 120, 0, computedMax));
|
||||
svg.appendChild(poly);
|
||||
};
|
||||
|
||||
addLine(seriesA, options.colorA ?? 'var(--accent)');
|
||||
addLine(seriesB, options.colorB ?? 'var(--warn)');
|
||||
return svg;
|
||||
}
|
||||
|
|
|
|||
161
src/client/ts/command-palette.ts
Normal file
161
src/client/ts/command-palette.ts
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
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();
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
import { collapseDiffHunks, type CollapsedDiffEntry } from '../../shared/diff.js';
|
||||
import { apiFetch } from './api.js';
|
||||
import {
|
||||
el,
|
||||
|
|
@ -12,6 +13,7 @@ export interface DiffModalData {
|
|||
source: string;
|
||||
createdAt: number;
|
||||
lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>;
|
||||
collapsedLines?: CollapsedDiffEntry[];
|
||||
onRollback: () => Promise<void>;
|
||||
}
|
||||
|
||||
|
|
@ -232,16 +234,56 @@ export function openDiffModal(data: DiffModalData): void {
|
|||
const closeBtn = document.getElementById('dialog-diff-close') as HTMLButtonElement;
|
||||
const rollbackBtn = document.getElementById('dialog-diff-rollback') as HTMLButtonElement;
|
||||
|
||||
metaEl.textContent = `${data.filePath} — Revision #${data.revisionId} (${data.source})`;
|
||||
bodyEl.replaceChildren();
|
||||
for (const line of data.lines) {
|
||||
const prefix = line.type === 'add' ? '+ ' : line.type === 'del' ? '- ' : ' ';
|
||||
const cls =
|
||||
line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : '';
|
||||
bodyEl.append(el('div', { class: cls }, `${prefix}${line.text}`));
|
||||
const hunks = data.collapsedLines ?? collapseDiffHunks(data.lines);
|
||||
const hasHunk = hunks.some((entry) => entry.type === 'hunk');
|
||||
let expanded = hunks.length === 0 || !hasHunk;
|
||||
|
||||
const toggleBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm', style: 'margin-left:8px' },
|
||||
expanded ? 'Full Diff' : 'Expand Full Diff',
|
||||
);
|
||||
if (!hasHunk) {
|
||||
toggleBtn.hidden = true;
|
||||
}
|
||||
|
||||
const renderLines = () => {
|
||||
bodyEl.replaceChildren();
|
||||
if (expanded) {
|
||||
for (const line of data.lines) {
|
||||
const prefix = line.type === 'add' ? '+ ' : line.type === 'del' ? '- ' : ' ';
|
||||
const cls = line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : '';
|
||||
bodyEl.append(el('div', { class: cls }, `${prefix}${line.text}`));
|
||||
}
|
||||
toggleBtn.textContent = 'Collapse Context';
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of hunks) {
|
||||
if (entry.type === 'hunk') {
|
||||
bodyEl.append(el('div', { class: 'diff-hunk-sep' }, entry.text));
|
||||
} else {
|
||||
const prefix = entry.type === 'add' ? '+ ' : entry.type === 'del' ? '- ' : ' ';
|
||||
const cls = entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : '';
|
||||
bodyEl.append(el('div', { class: cls }, `${prefix}${entry.text}`));
|
||||
}
|
||||
}
|
||||
toggleBtn.textContent = 'Expand Full Diff';
|
||||
};
|
||||
|
||||
metaEl.replaceChildren(
|
||||
document.createTextNode(`${data.filePath} — Revision #${data.revisionId} (${data.source})`),
|
||||
toggleBtn,
|
||||
);
|
||||
renderLines();
|
||||
|
||||
const onToggle = () => {
|
||||
expanded = !expanded;
|
||||
renderLines();
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
toggleBtn.removeEventListener('click', onToggle);
|
||||
closeBtn.removeEventListener('click', onClose);
|
||||
rollbackBtn.removeEventListener('click', onRollbackClick);
|
||||
dialog.removeEventListener('close', cleanup);
|
||||
|
|
@ -262,6 +304,7 @@ export function openDiffModal(data: DiffModalData): void {
|
|||
}
|
||||
};
|
||||
|
||||
toggleBtn.addEventListener('click', onToggle);
|
||||
closeBtn.addEventListener('click', onClose);
|
||||
rollbackBtn.addEventListener('click', onRollbackClick);
|
||||
dialog.addEventListener('close', cleanup);
|
||||
|
|
|
|||
|
|
@ -12,6 +12,10 @@ import {
|
|||
SAFE_MODE_STORAGE_KEY,
|
||||
THEME_STORAGE_KEY,
|
||||
applyTheme,
|
||||
el,
|
||||
extractErrorMessage,
|
||||
flushViewCleanups,
|
||||
getDashboardLivePatchers,
|
||||
initialDeviceSafeMode,
|
||||
type ClientAuthRequirements,
|
||||
type ClientSecuritySettings,
|
||||
|
|
@ -19,16 +23,7 @@ import {
|
|||
type ConfigOverview,
|
||||
type RouteId,
|
||||
} from './state.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 { showToast } from './toast.js';
|
||||
import { MultiplexWsClient } from './ws-client.js';
|
||||
|
||||
const VALID_ROUTES = new Set<RouteId>([
|
||||
|
|
@ -167,93 +162,175 @@ async function refreshOverview(): Promise<void> {
|
|||
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> {
|
||||
const mySeq = ++renderSeq;
|
||||
runActiveCleanup();
|
||||
|
||||
const root = document.getElementById('view-root')!;
|
||||
updateTopBarUi();
|
||||
|
||||
if (!state.authenticated) {
|
||||
await renderAuthView(
|
||||
root,
|
||||
state.bootstrapped,
|
||||
state.safeMode,
|
||||
state.authRequirements,
|
||||
async () => {
|
||||
await bootstrapApp();
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (!state.authenticated) {
|
||||
const { renderAuthView } = await import('./views/auth-view.js');
|
||||
if (mySeq !== renderSeq) return;
|
||||
const cleanup = await renderAuthView(
|
||||
root,
|
||||
state.bootstrapped,
|
||||
state.safeMode,
|
||||
state.authRequirements,
|
||||
async () => {
|
||||
await bootstrapApp();
|
||||
},
|
||||
);
|
||||
captureCleanup(mySeq, cleanup);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!state.overview) {
|
||||
await refreshOverview();
|
||||
}
|
||||
|
||||
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 () => {
|
||||
if (!state.overview) {
|
||||
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 (mySeq !== renderSeq) 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);
|
||||
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,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -261,10 +338,41 @@ async function triggerPanicLock(): Promise<void> {
|
|||
const confirmed = await confirmDialog('dialog-panic');
|
||||
if (!confirmed) return;
|
||||
await apiFetch('/api/security/panic-lock', { method: 'POST' });
|
||||
showToast('Panic lock engaged: Vault zeroized and sessions revoked.', 'warn');
|
||||
handleLocalSessionReset(true);
|
||||
}
|
||||
|
||||
async function lockVaultAction(): Promise<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 {
|
||||
runActiveCleanup();
|
||||
wsClient.disconnect();
|
||||
setCsrfToken(null);
|
||||
state.authenticated = false;
|
||||
|
|
@ -284,7 +392,7 @@ async function syncStatusAndRender(): Promise<void> {
|
|||
authenticated: boolean;
|
||||
safeMode?: boolean;
|
||||
elevatedUntil?: number | null;
|
||||
vaultState: ClientState['vaultState'];
|
||||
vaultState?: ClientState['vaultState'];
|
||||
vaultRuntimeReady?: boolean;
|
||||
isPanicLocked?: boolean;
|
||||
defaultMobileSafeMode: boolean;
|
||||
|
|
@ -295,8 +403,8 @@ async function syncStatusAndRender(): Promise<void> {
|
|||
|
||||
state.bootstrapped = status.bootstrapped;
|
||||
state.authenticated = status.authenticated;
|
||||
state.vaultState = status.vaultState;
|
||||
state.vaultRuntimeReady = status.vaultRuntimeReady ?? status.vaultState === 'unlocked';
|
||||
state.vaultState = status.vaultState ?? 'locked';
|
||||
state.vaultRuntimeReady = status.vaultRuntimeReady ?? false;
|
||||
state.isPanicLocked = Boolean(status.isPanicLocked);
|
||||
state.defaultMobileSafeMode = status.defaultMobileSafeMode;
|
||||
state.elevatedUntil = status.elevatedUntil ?? null;
|
||||
|
|
@ -410,6 +518,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||
void renderCurrentView();
|
||||
}
|
||||
} else if (frame.type === 'security:panic-lock') {
|
||||
showToast('Panic lock engaged remotely — session terminated.', 'err');
|
||||
handleLocalSessionReset(true);
|
||||
} else if (frame.type === 'config:updated' && state.authenticated) {
|
||||
void refreshOverview().then(() => {
|
||||
|
|
@ -418,35 +527,80 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||
}
|
||||
});
|
||||
} else if (frame.type === 'metrics:tick' && state.authenticated && state.route === 'dashboard') {
|
||||
patchDashboardServerTick(frame);
|
||||
getDashboardLivePatchers()?.onTick(frame);
|
||||
} else if (frame.type === 'servers:state' && state.authenticated && state.route === 'dashboard') {
|
||||
const needsRefresh = patchDashboardServerStates(frame.states);
|
||||
const needsRefresh = getDashboardLivePatchers()?.onStates(frame.states) ?? false;
|
||||
if (needsRefresh) {
|
||||
void renderCurrentView();
|
||||
}
|
||||
} else if (frame.type === 'alerts:update') {
|
||||
const prevAlerts = state.activeAlertCount;
|
||||
state.activeAlertCount = frame.activeCount;
|
||||
updateTopBarUi();
|
||||
if (state.authenticated && frame.activeCount > prevAlerts) {
|
||||
showToast(`Active alerts increased to ${frame.activeCount}.`, 'warn');
|
||||
}
|
||||
if (state.authenticated && state.route === 'alerts') {
|
||||
void renderCurrentView();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('safe-toggle-btn')!.addEventListener('click', async () => {
|
||||
const next = !state.safeMode;
|
||||
localStorage.setItem(SAFE_MODE_STORAGE_KEY, next ? '1' : '0');
|
||||
state.safeMode = next;
|
||||
setApiSafeMode(next);
|
||||
if (next) state.elevatedUntil = null;
|
||||
wsClient.send({ type: 'safe-mode', enabled: next });
|
||||
if (state.authenticated) {
|
||||
await apiFetch('/api/auth/safe-mode', {
|
||||
method: 'POST',
|
||||
body: { enabled: next },
|
||||
});
|
||||
const openPalette = async () => {
|
||||
if (!state.authenticated) return;
|
||||
const { openCommandPalette } = await import('./command-palette.js');
|
||||
openCommandPalette({
|
||||
state,
|
||||
navigate: (hash) => {
|
||||
window.location.hash = hash;
|
||||
},
|
||||
toggleSafeMode,
|
||||
lockVault: lockVaultAction,
|
||||
triggerPanic: triggerPanicLock,
|
||||
});
|
||||
};
|
||||
|
||||
document.getElementById('cmd-palette-btn')!.addEventListener('click', () => {
|
||||
void openPalette();
|
||||
});
|
||||
|
||||
document.getElementById('safe-toggle-btn')!.addEventListener('click', () => {
|
||||
void toggleSafeMode();
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', (ev) => {
|
||||
const active = document.activeElement;
|
||||
if (active && active.closest('.xterm')) return;
|
||||
|
||||
if ((ev.ctrlKey || ev.metaKey || ev.altKey) && ev.key.toLowerCase() === 'k') {
|
||||
if (!state.authenticated) return;
|
||||
ev.preventDefault();
|
||||
void openPalette();
|
||||
return;
|
||||
}
|
||||
|
||||
if ((ev.ctrlKey || ev.metaKey) && ev.key.toLowerCase() === 's') {
|
||||
if (!state.authenticated || document.querySelector('dialog[open]')) return;
|
||||
ev.preventDefault();
|
||||
window.dispatchEvent(new CustomEvent('gcoord:save'));
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('storage', (ev) => {
|
||||
if (ev.key === THEME_STORAGE_KEY && ev.newValue) {
|
||||
state.theme = ev.newValue;
|
||||
document.documentElement.setAttribute('data-theme', ev.newValue);
|
||||
updateTopBarUi();
|
||||
} else if (ev.key === SAFE_MODE_STORAGE_KEY && ev.newValue !== null) {
|
||||
const next = ev.newValue === '1';
|
||||
if (next !== state.safeMode) {
|
||||
state.safeMode = next;
|
||||
setApiSafeMode(next);
|
||||
if (next) state.elevatedUntil = null;
|
||||
wsClient.send({ type: 'safe-mode', enabled: next });
|
||||
updateTopBarUi();
|
||||
}
|
||||
}
|
||||
updateTopBarUi();
|
||||
});
|
||||
|
||||
document.getElementById('theme-select')!.addEventListener('change', (ev) => {
|
||||
|
|
|
|||
|
|
@ -74,24 +74,28 @@ export interface ClientSecuritySettings {
|
|||
requireTotpOnLogin: boolean;
|
||||
passwordMode: 'any' | 'all';
|
||||
totpMode: 'any' | 'all';
|
||||
stepUpPolicy: 'off' | 'every-action' | '5m' | '1h' | '24h' | 'session';
|
||||
stepUpPolicy: 'off' | 'every-action' | '5m' | '15m' | '1h' | '24h' | 'session';
|
||||
stepUpMethod: 'totp' | 'password' | 'both' | 'passkey';
|
||||
elevateOnLogin: boolean;
|
||||
keepElevationOnSafeMode: boolean;
|
||||
enableEmergencySecretsBackup: boolean;
|
||||
allowSameOriginProxy?: boolean;
|
||||
egressAllowedCidrs?: string[];
|
||||
sessionTtlHours?: number;
|
||||
sessionIdleTimeoutMin?: number;
|
||||
}
|
||||
|
||||
export interface ClientAuthRequirements {
|
||||
requireTotpOnLogin: boolean;
|
||||
passwordMode: 'any' | 'all';
|
||||
passwordCount: number;
|
||||
passwordLabels: Array<{ id: string; label: string }>;
|
||||
passwordLabels?: Array<{ id: string; label: string }>;
|
||||
totpMode: 'any' | 'all';
|
||||
totpCount: number;
|
||||
totpLabels: Array<{ id: string; label: string }>;
|
||||
totpLabels?: Array<{ id: string; label: string }>;
|
||||
passkeyCount: number;
|
||||
stepUpPolicy: ClientSecuritySettings['stepUpPolicy'];
|
||||
stepUpMethod: ClientSecuritySettings['stepUpMethod'];
|
||||
stepUpPolicy?: ClientSecuritySettings['stepUpPolicy'];
|
||||
stepUpMethod?: ClientSecuritySettings['stepUpMethod'];
|
||||
}
|
||||
|
||||
export interface ClientState {
|
||||
|
|
@ -221,3 +225,40 @@ export function fmtUptime(sec: number): string {
|
|||
export function extractErrorMessage(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
export interface DashboardLivePatchers {
|
||||
onTick: (tick: {
|
||||
serverId: string;
|
||||
sample: MetricSample;
|
||||
disks: DiskSample[];
|
||||
probes?: ProbeSample[];
|
||||
}) => void;
|
||||
onStates: (states: ServerRuntimeState[]) => boolean;
|
||||
}
|
||||
|
||||
let dashboardPatchers: DashboardLivePatchers | null = null;
|
||||
const activeCleanups: Array<() => void> = [];
|
||||
|
||||
export function registerDashboardLivePatchers(patchers: DashboardLivePatchers | null): void {
|
||||
dashboardPatchers = patchers;
|
||||
}
|
||||
|
||||
export function getDashboardLivePatchers(): DashboardLivePatchers | null {
|
||||
return dashboardPatchers;
|
||||
}
|
||||
|
||||
export function registerViewCleanup(fn: () => void): void {
|
||||
activeCleanups.push(fn);
|
||||
}
|
||||
|
||||
export function flushViewCleanups(): void {
|
||||
while (activeCleanups.length > 0) {
|
||||
const fn = activeCleanups.pop();
|
||||
if (!fn) continue;
|
||||
try {
|
||||
fn();
|
||||
} catch {
|
||||
// Ignore view teardown errors
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
42
src/client/ts/toast.ts
Normal file
42
src/client/ts/toast.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import {
|
|||
extractErrorMessage,
|
||||
type ClientState,
|
||||
} from '../state.js';
|
||||
import { showToast } from '../toast.js';
|
||||
import type { MultiplexWsClient } from '../ws-client.js';
|
||||
|
||||
export type ClientAiSurface = 'workflows' | 'systems' | 'snippets' | 'logs' | 'setup';
|
||||
|
|
@ -27,6 +28,7 @@ export interface OpenAiDrawerOptions {
|
|||
contextText?: string;
|
||||
serverId?: string;
|
||||
targetPath?: string;
|
||||
targetId?: string;
|
||||
defaultDraftKind?: ClientAiDraftKind;
|
||||
onInsertTerminalText?: (cmd: string) => void;
|
||||
onApplied?: () => Promise<void> | void;
|
||||
|
|
@ -103,18 +105,29 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
|
|||
|
||||
const statusLine = el('p', { class: 'form-msg muted' }, '');
|
||||
const sendBtn = el('button', { type: 'submit', class: 'btn btn-primary btn-sm' }, 'Send');
|
||||
const stopBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm', disabled: true }, 'Stop');
|
||||
const stopBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm', disabled: true }, 'Cancel Stream');
|
||||
|
||||
const history: Array<{ role: 'user' | 'assistant'; content: string }> = [];
|
||||
let activeChatId: string | null = null;
|
||||
let currentReply = '';
|
||||
let unsubWs: (() => void) | null = null;
|
||||
let unsubChannel: (() => void) | null = null;
|
||||
|
||||
const releaseChannel = () => {
|
||||
if (unsubChannel) {
|
||||
unsubChannel();
|
||||
unsubChannel = null;
|
||||
}
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
if (activeChatId) {
|
||||
opts.wsClient.send({ type: 'ai:cancel', chatId: activeChatId });
|
||||
const cid = activeChatId;
|
||||
opts.wsClient.send({ type: 'ai:cancel', chatId: cid });
|
||||
void apiFetch(`/api/ai/chat/${encodeURIComponent(cid)}/cancel`, { method: 'POST' }).catch(() => undefined);
|
||||
activeChatId = null;
|
||||
}
|
||||
releaseChannel();
|
||||
if (unsubWs) {
|
||||
unsubWs();
|
||||
unsubWs = null;
|
||||
|
|
@ -170,7 +183,11 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
|
|||
| { valid: false; issues: Array<{ path: string; message: string }> }
|
||||
>('/api/ai/validate-draft', {
|
||||
method: 'POST',
|
||||
body: { kind: draftKindSel.value, jsonText: jsonBlock },
|
||||
body: {
|
||||
kind: draftKindSel.value,
|
||||
jsonText: jsonBlock,
|
||||
...(opts.targetId ? { targetId: opts.targetId } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
draftOutputBox.replaceChildren();
|
||||
|
|
@ -238,11 +255,14 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
|
|||
if (currentReply) history.push({ role: 'assistant', content: currentReply });
|
||||
appendBoundedStreamText(streamPre, '\n');
|
||||
activeChatId = null;
|
||||
releaseChannel();
|
||||
sendBtn.disabled = false;
|
||||
stopBtn.disabled = true;
|
||||
if (!frame.error) {
|
||||
statusLine.className = 'form-msg ok-text';
|
||||
statusLine.textContent = 'Response complete. Review any extracted draft below.';
|
||||
} else {
|
||||
showToast(frame.error, 'err');
|
||||
}
|
||||
refreshDraftActions();
|
||||
}
|
||||
|
|
@ -301,13 +321,17 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<
|
|||
},
|
||||
});
|
||||
activeChatId = started.chatId;
|
||||
opts.wsClient.subscribe([`ai:${started.chatId}`]);
|
||||
releaseChannel();
|
||||
unsubChannel = opts.wsClient.subscribe([`ai:${started.chatId}`]);
|
||||
} catch (err) {
|
||||
history.pop();
|
||||
releaseChannel();
|
||||
sendBtn.disabled = false;
|
||||
stopBtn.disabled = true;
|
||||
const errMsg = extractErrorMessage(err);
|
||||
statusLine.className = 'form-msg err-text';
|
||||
statusLine.textContent = extractErrorMessage(err);
|
||||
statusLine.textContent = errMsg;
|
||||
showToast(errMsg, 'err');
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ interface AlertChannelItem {
|
|||
interface AlertRuleItem {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system';
|
||||
kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system' | 'security-event';
|
||||
severity: 'warn' | 'critical';
|
||||
target: { serverId?: string; tags?: string[]; all?: boolean };
|
||||
forConsecutivePolls: number;
|
||||
|
|
@ -40,6 +40,7 @@ interface AlertRuleItem {
|
|||
probeId?: string;
|
||||
systemId?: string;
|
||||
item?: string;
|
||||
events?: string[];
|
||||
}
|
||||
|
||||
interface MaintenanceWindowItem {
|
||||
|
|
@ -330,11 +331,12 @@ export async function renderAlertsView(
|
|||
const chUrl = el('input', { placeholder: 'Webhook / base URL (optional for ntfy.sh or Telegram)' });
|
||||
const chExtra = el('input', { placeholder: 'Telegram chatId OR ntfy topic (optional)' });
|
||||
const chRef = el('select', {});
|
||||
for (const cr of credsRes.credentials) {
|
||||
const webhookCreds = credsRes.credentials.filter((cr) => cr.type === 'webhook-secret');
|
||||
for (const cr of webhookCreds) {
|
||||
chRef.append(el('option', { value: cr.id }, `${cr.id} (${cr.type})`));
|
||||
}
|
||||
if (credsRes.credentials.length === 0) {
|
||||
chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add in Vault)'));
|
||||
if (webhookCreds.length === 0) {
|
||||
chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add webhook-secret in Vault)'));
|
||||
}
|
||||
const chForm = el(
|
||||
'form',
|
||||
|
|
@ -385,7 +387,9 @@ export async function renderAlertsView(
|
|||
? `offline >= ${r.offlineSec}s`
|
||||
: r.kind === 'probe'
|
||||
? `probe ${r.probeId ?? '*'}`
|
||||
: `system ${r.systemId}/${r.item ?? '*'}`;
|
||||
: r.kind === 'security-event'
|
||||
? `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');
|
||||
toggleBtn.addEventListener('click', () => {
|
||||
void saveConfig({
|
||||
|
|
@ -404,9 +408,9 @@ export async function renderAlertsView(
|
|||
|
||||
const ruleId = el('input', { placeholder: 'high-cpu', required: true });
|
||||
const ruleName = el('input', { placeholder: 'High CPU Usage', required: true });
|
||||
const ruleKind = el('select', {}, el('option', { value: 'metric' }, 'metric'), el('option', { value: 'disk' }, 'disk'), el('option', { value: 'offline' }, 'offline'), el('option', { value: 'probe' }, 'probe'), el('option', { value: 'system' }, 'system'));
|
||||
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 ruleSev = el('select', {}, el('option', { value: 'warn' }, 'warn'), el('option', { value: 'critical' }, 'critical'));
|
||||
const ruleParam1 = el('input', { placeholder: 'metric/mount/probe/system (e.g. cpuPct)' });
|
||||
const ruleParam1 = el('input', { placeholder: 'metric/mount/probe/system or events csv (auth.lockout,ssh.host_key_mismatch,vault.panic_lock)' });
|
||||
const ruleThresh = el('input', { type: 'number', value: '85', placeholder: 'Threshold / Offline sec' });
|
||||
const rulePolls = el('input', { type: 'number', min: 1, value: '3', placeholder: 'forConsecutivePolls' });
|
||||
const ruleChans = el('input', { placeholder: 'channelIds comma-sep (optional)' });
|
||||
|
|
@ -443,6 +447,17 @@ export async function renderAlertsView(
|
|||
nextRule = { ...base, kind: 'probe', probeId: ruleParam1.value.trim() || undefined };
|
||||
} else if (ruleKind.value === 'system') {
|
||||
nextRule = { ...base, kind: 'system', systemId: ruleParam1.value.trim() || 'docker-compose' };
|
||||
} else if (ruleKind.value === 'security-event') {
|
||||
const events = ruleParam1.value
|
||||
.split(',')
|
||||
.map((e) => e.trim())
|
||||
.filter(Boolean);
|
||||
nextRule = {
|
||||
...base,
|
||||
kind: 'security-event',
|
||||
forConsecutivePolls: 1,
|
||||
events: events.length > 0 ? events : ['auth.lockout', 'ssh.host_key_mismatch', 'vault.panic_lock'],
|
||||
};
|
||||
} else {
|
||||
nextRule = { ...base, kind: 'metric', metric: (ruleParam1.value.trim() || 'cpuPct') as 'cpuPct', operator: 'gt', threshold: Number(ruleThresh.value || 85) };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,9 +7,11 @@ import {
|
|||
import { getPasskeyAssertion, isWebAuthnSupported } from '../webauthn.js';
|
||||
|
||||
interface BootstrapData {
|
||||
bootstrapToken?: string;
|
||||
secretBase32: string;
|
||||
otpauthUri: string;
|
||||
qrSvg: string;
|
||||
qrDataUri?: string;
|
||||
}
|
||||
|
||||
export async function renderAuthView(
|
||||
|
|
@ -85,14 +87,36 @@ export async function renderAuthView(
|
|||
placeholder: '6-digit code from authenticator',
|
||||
required: true,
|
||||
});
|
||||
const bootTokInput = el('input', {
|
||||
id: 'boot-token',
|
||||
name: 'bootstrapToken',
|
||||
type: 'password',
|
||||
autocomplete: 'off',
|
||||
placeholder: 'GCOORD_BOOTSTRAP_TOKEN (auto-filled unless operator-only)',
|
||||
}) as HTMLInputElement;
|
||||
|
||||
let secretBase32 = '';
|
||||
try {
|
||||
const data = await apiFetch<BootstrapData>('/api/auth/bootstrap');
|
||||
secretBase32 = data.secretBase32;
|
||||
const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml');
|
||||
if (doc.documentElement.nodeName === 'svg') {
|
||||
qrContainer.append(document.importNode(doc.documentElement, true));
|
||||
bootTokInput.value = data.bootstrapToken ?? '';
|
||||
if (
|
||||
typeof data.qrDataUri === 'string' &&
|
||||
/^data:image\/(?:png|svg\+xml);base64,[A-Za-z0-9+/=]+$/.test(data.qrDataUri)
|
||||
) {
|
||||
const img = el('img', {
|
||||
src: data.qrDataUri,
|
||||
alt: 'TOTP Enrollment QR Code',
|
||||
width: 200,
|
||||
height: 200,
|
||||
style: 'background:#fff;padding:6px;display:block',
|
||||
});
|
||||
qrContainer.append(img);
|
||||
} else {
|
||||
const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml');
|
||||
if (doc.documentElement.nodeName === 'svg') {
|
||||
qrContainer.append(document.importNode(doc.documentElement, true));
|
||||
}
|
||||
}
|
||||
secretLine.textContent = `Secret: ${data.secretBase32}`;
|
||||
} catch (err) {
|
||||
|
|
@ -115,6 +139,8 @@ export async function renderAuthView(
|
|||
el('div', { class: 'stack' }, el('label', {}, 'Scan TOTP QR Code'), qrContainer, secretLine),
|
||||
el('label', { for: 'boot-totp' }, 'Verify 6-Digit TOTP Code'),
|
||||
codeInput,
|
||||
el('label', { for: 'boot-token' }, 'Bootstrap Token (if GCOORD_BOOTSTRAP_TOKEN is enforced)'),
|
||||
bootTokInput,
|
||||
statusMsg,
|
||||
submitBtn,
|
||||
);
|
||||
|
|
@ -124,6 +150,7 @@ export async function renderAuthView(
|
|||
statusMsg.textContent = '';
|
||||
submitBtn.disabled = true;
|
||||
try {
|
||||
const tok = bootTokInput.value.trim();
|
||||
const res = await apiFetch<{
|
||||
csrfToken: string;
|
||||
recoveryCodes: string[];
|
||||
|
|
@ -134,6 +161,7 @@ export async function renderAuthView(
|
|||
password: passInput.value,
|
||||
totpCode: codeInput.value.trim(),
|
||||
secretBase32,
|
||||
...(tok ? { bootstrapToken: tok } : {}),
|
||||
initialSafeMode,
|
||||
securityPreset: presetSelect.value,
|
||||
},
|
||||
|
|
@ -283,7 +311,7 @@ export async function renderAuthView(
|
|||
form.append(el('label', { for: 'login-username' }, 'Username'), userInput);
|
||||
|
||||
const passwordInputs: HTMLInputElement[] = [];
|
||||
const pwCount = pwMode === 'all' ? Math.max(1, pwLabels.length) : 1;
|
||||
const pwCount = Math.max(1, reqs?.passwordCount ?? pwLabels.length);
|
||||
for (let i = 0; i < pwCount; i++) {
|
||||
const labelText =
|
||||
pwMode === 'all' ? `Password — ${pwLabels[i]?.label ?? `#${i + 1}`}` : 'Password';
|
||||
|
|
@ -310,7 +338,7 @@ export async function renderAuthView(
|
|||
|
||||
const codeInputs: HTMLInputElement[] = [];
|
||||
if (requireTotp) {
|
||||
const totpCount = totpMode === 'all' ? Math.max(1, totpLabels.length) : 1;
|
||||
const totpCount = Math.max(1, reqs?.totpCount ?? totpLabels.length);
|
||||
for (let i = 0; i < totpCount; i++) {
|
||||
const labelText =
|
||||
totpMode === 'all'
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { collapseDiffHunks, computeLineDiff, type CollapsedDiffEntry } from '../../../shared/diff.js';
|
||||
import { apiFetch, type ApiError } from '../api.js';
|
||||
import { confirmDialog, openDiffModal } from '../dialogs.js';
|
||||
import {
|
||||
|
|
@ -5,9 +6,11 @@ import {
|
|||
extractErrorMessage,
|
||||
fmtTime,
|
||||
isAiEnabled,
|
||||
registerViewCleanup,
|
||||
type ClientState,
|
||||
type ConfigOverview,
|
||||
} from '../state.js';
|
||||
import { showToast } from '../toast.js';
|
||||
import type { MultiplexWsClient } from '../ws-client.js';
|
||||
|
||||
interface FileDetails {
|
||||
|
|
@ -236,18 +239,14 @@ export async function renderConfigView(
|
|||
}
|
||||
});
|
||||
|
||||
const saveBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-primary mutating-action' },
|
||||
'Save Config',
|
||||
);
|
||||
saveBtn.addEventListener('click', async () => {
|
||||
const saveFile = async () => {
|
||||
msgEl.replaceChildren();
|
||||
try {
|
||||
await apiFetch('/api/config/file', {
|
||||
method: 'PUT',
|
||||
body: { path: details.filePath, content: editor.value },
|
||||
});
|
||||
showToast(`Saved ${details.filePath}.`, 'ok');
|
||||
await onReloadOverview();
|
||||
} catch (err) {
|
||||
const apiErr = err as ApiError;
|
||||
|
|
@ -256,9 +255,44 @@ export async function renderConfigView(
|
|||
msgEl.append(el('div', { class: 'mono err-text' }, ` ${issue.path}: ${issue.message}`));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const previewBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Preview Changes');
|
||||
previewBtn.addEventListener('click', () => {
|
||||
const diff = computeLineDiff(details.rawContent, editor.value, 'saved', 'draft');
|
||||
const hunks = diff.collapsedLines ?? collapseDiffHunks(diff.lines);
|
||||
msgEl.replaceChildren(
|
||||
el('div', { class: 'mono muted' }, `+${diff.additions} / -${diff.deletions}`),
|
||||
el(
|
||||
'pre',
|
||||
{ class: 'diff-body mono', style: 'max-height:220px' },
|
||||
...hunks.map((entry) =>
|
||||
entry.type === 'hunk'
|
||||
? el('div', { class: 'diff-hunk-sep' }, entry.text)
|
||||
: el(
|
||||
'div',
|
||||
{ class: entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : '' },
|
||||
`${entry.type === 'add' ? '+' : entry.type === 'del' ? '-' : ' '} ${entry.text}`,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const actionRow = el('div', { class: 'row' }, fmtBtn, saveBtn);
|
||||
const saveBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-primary mutating-action' },
|
||||
'Save Config',
|
||||
);
|
||||
saveBtn.addEventListener('click', () => void saveFile());
|
||||
|
||||
const onCtrlS = () => {
|
||||
if (editor.isConnected && !state.safeMode) void saveFile();
|
||||
};
|
||||
window.addEventListener('gcoord:save', onCtrlS);
|
||||
registerViewCleanup(() => window.removeEventListener('gcoord:save', onCtrlS));
|
||||
|
||||
const actionRow = el('div', { class: 'row' }, fmtBtn, previewBtn, saveBtn);
|
||||
if (isAiEnabled(state)) {
|
||||
const aiBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Assist]');
|
||||
aiBtn.addEventListener('click', async () => {
|
||||
|
|
@ -336,7 +370,10 @@ export async function renderConfigView(
|
|||
diffBtn.addEventListener('click', async () => {
|
||||
const res = await apiFetch<{
|
||||
revision: { id: number; filePath: string; source: string; createdAt: number };
|
||||
diff: { lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }> };
|
||||
diff: {
|
||||
lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>;
|
||||
collapsedLines?: CollapsedDiffEntry[];
|
||||
};
|
||||
}>(`/api/config/revisions/${rev.id}/diff`);
|
||||
openDiffModal({
|
||||
revisionId: res.revision.id,
|
||||
|
|
@ -344,6 +381,7 @@ export async function renderConfigView(
|
|||
source: res.revision.source,
|
||||
createdAt: res.revision.createdAt,
|
||||
lines: res.diff.lines,
|
||||
collapsedLines: res.diff.collapsedLines,
|
||||
onRollback: async () => {
|
||||
await apiFetch(`/api/config/revisions/${rev.id}/rollback`, { method: 'POST' });
|
||||
await onReloadOverview();
|
||||
|
|
|
|||
|
|
@ -16,11 +16,16 @@ import {
|
|||
extractErrorMessage,
|
||||
fmtBytesPerSec,
|
||||
fmtUptime,
|
||||
registerDashboardLivePatchers,
|
||||
registerViewCleanup,
|
||||
type ClientState,
|
||||
type ServerEntry,
|
||||
} from '../state.js';
|
||||
import { showToast } from '../toast.js';
|
||||
|
||||
const sparkHistory = new Map<string, number[]>();
|
||||
let fleetFilter: 'all' | 'connected' | 'issues' = 'all';
|
||||
let fleetSearch = '';
|
||||
|
||||
function statusBadgeClass(status: string): string {
|
||||
if (status === 'connected') return 'badge badge-ok';
|
||||
|
|
@ -63,11 +68,18 @@ function renderProbesInto(container: Element, probes: ProbeSample[]): void {
|
|||
container.replaceChildren();
|
||||
if (probes.length === 0) return;
|
||||
for (const p of probes) {
|
||||
const tlsNote =
|
||||
p.certExpiryDays !== undefined ? ` TLS:${p.certExpiryDays}d` : '';
|
||||
const cls = !p.ok || (p.certExpiryDays !== undefined && p.certExpiryDays <= 0)
|
||||
? 'badge-err'
|
||||
: p.certExpiryDays !== undefined && p.certExpiryDays <= 14
|
||||
? 'badge-warn'
|
||||
: 'badge-ok';
|
||||
container.append(
|
||||
el(
|
||||
'span',
|
||||
{ class: `badge ${p.ok ? 'badge-ok' : 'badge-err'}` },
|
||||
`${p.probeId}: ${p.ok ? `OK ${Math.round(p.latencyMs)}ms` : 'FAIL'}`,
|
||||
{ class: `badge ${cls}` },
|
||||
`${p.probeId}: ${p.ok ? `OK ${Math.round(p.latencyMs)}ms` : 'FAIL'}${tlsNote}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
|
@ -121,6 +133,7 @@ export function patchDashboardServerStates(states: ServerRuntimeState[]): boolea
|
|||
badge.textContent = `[${st.status.toUpperCase()}]`;
|
||||
badge.className = statusBadgeClass(st.status);
|
||||
}
|
||||
card.setAttribute('data-status', st.status);
|
||||
const osBadge = card.querySelector('[data-field="os"]');
|
||||
if (osBadge && st.osDetected) {
|
||||
osBadge.textContent = st.osDetected;
|
||||
|
|
@ -140,12 +153,16 @@ async function openRegisterServerDialog(
|
|||
const form = document.getElementById('dialog-srv-form') as HTMLFormElement;
|
||||
const credSelect = document.getElementById('srv-cred') as HTMLSelectElement;
|
||||
const jumpSelect = document.getElementById('srv-jump') as HTMLSelectElement;
|
||||
const testMsgEl = document.getElementById('srv-test-msg') as HTMLElement;
|
||||
const errEl = document.getElementById('srv-reg-err') as HTMLElement;
|
||||
const testBtn = document.getElementById('srv-test-conn-btn') as HTMLButtonElement;
|
||||
const closeBtn = document.getElementById('srv-reg-close') as HTMLButtonElement;
|
||||
const cancelBtn = document.getElementById('srv-reg-cancel') as HTMLButtonElement;
|
||||
|
||||
form.reset();
|
||||
errEl.textContent = '';
|
||||
testMsgEl.textContent = '';
|
||||
testMsgEl.className = 'form-msg';
|
||||
|
||||
credSelect.replaceChildren();
|
||||
try {
|
||||
|
|
@ -172,8 +189,69 @@ async function openRegisterServerDialog(
|
|||
jumpSelect.append(el('option', { value: s.config.id }, `${s.config.id} (${s.config.host})`));
|
||||
}
|
||||
|
||||
const buildPayload = () => {
|
||||
const fd = new FormData(form);
|
||||
const id = String(fd.get('id') ?? '').trim();
|
||||
const tagsRaw = String(fd.get('tags') ?? '');
|
||||
const tags = tagsRaw
|
||||
.split(',')
|
||||
.map((t) => t.trim())
|
||||
.filter(Boolean);
|
||||
return {
|
||||
id,
|
||||
name: String(fd.get('name') ?? id).trim(),
|
||||
host: String(fd.get('host') ?? '').trim(),
|
||||
port: Number(fd.get('port') ?? 22),
|
||||
username: String(fd.get('username') ?? '').trim(),
|
||||
credentialId: String(fd.get('credentialId') ?? '').trim(),
|
||||
jumpHostId: String(fd.get('jumpHostId') ?? '').trim() || undefined,
|
||||
osHint: String(fd.get('osHint') ?? 'auto'),
|
||||
pollIntervalSec: Number(fd.get('pollIntervalSec') ?? 10),
|
||||
tags,
|
||||
};
|
||||
};
|
||||
|
||||
const onTestConn = async () => {
|
||||
errEl.textContent = '';
|
||||
testBtn.disabled = true;
|
||||
testMsgEl.className = 'form-msg muted';
|
||||
testMsgEl.textContent = 'Testing SSH handshake...';
|
||||
try {
|
||||
const payload = buildPayload();
|
||||
const res = await apiFetch<{
|
||||
ok: boolean;
|
||||
latencyMs: number;
|
||||
osDetected?: string;
|
||||
hostFingerprint?: string;
|
||||
tofuRequired?: boolean;
|
||||
hostKeyMismatch?: { expectedFingerprint: string; actualFingerprint: string };
|
||||
error?: string;
|
||||
}>('/api/servers/test-connection', {
|
||||
method: 'POST',
|
||||
body: payload,
|
||||
});
|
||||
if (res.ok) {
|
||||
testMsgEl.className = 'form-msg ok-text';
|
||||
testMsgEl.textContent = `Connected in ${Math.round(res.latencyMs)}ms (${res.osDetected ?? 'unknown OS'})${res.hostFingerprint ? ` · fp ${res.hostFingerprint}` : ''}`;
|
||||
} else {
|
||||
testMsgEl.className = res.hostKeyMismatch ? 'form-msg err-text' : 'form-msg warn-text';
|
||||
testMsgEl.textContent = res.hostKeyMismatch
|
||||
? `HOST KEY MISMATCH: ${res.hostKeyMismatch.actualFingerprint}`
|
||||
: res.tofuRequired
|
||||
? `TOFU required (${res.hostFingerprint ?? 'unknown fingerprint'}): ${res.error ?? 'save then approve TOFU'}`
|
||||
: res.error ?? 'Connection test failed';
|
||||
}
|
||||
} catch (err) {
|
||||
testMsgEl.className = 'form-msg err-text';
|
||||
testMsgEl.textContent = extractErrorMessage(err);
|
||||
} finally {
|
||||
testBtn.disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
form.removeEventListener('submit', onSubmit);
|
||||
testBtn.removeEventListener('click', onTestConn);
|
||||
closeBtn.removeEventListener('click', onClose);
|
||||
cancelBtn.removeEventListener('click', onClose);
|
||||
dialog.removeEventListener('close', onDialogClose);
|
||||
|
|
@ -188,34 +266,18 @@ async function openRegisterServerDialog(
|
|||
const onSubmit = async (ev: Event) => {
|
||||
ev.preventDefault();
|
||||
errEl.textContent = '';
|
||||
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);
|
||||
const payload = buildPayload();
|
||||
|
||||
try {
|
||||
await apiFetch('/api/servers', {
|
||||
method: 'POST',
|
||||
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,
|
||||
},
|
||||
body: payload,
|
||||
});
|
||||
await apiFetch(`/api/servers/${encodeURIComponent(id)}/reconnect`, {
|
||||
await apiFetch(`/api/servers/${encodeURIComponent(payload.id)}/reconnect`, {
|
||||
method: 'POST',
|
||||
}).catch(() => undefined);
|
||||
if (dialog.open) dialog.close();
|
||||
showToast(`Server "${payload.id}" registered.`, 'ok');
|
||||
await onRegistered();
|
||||
} catch (err) {
|
||||
errEl.textContent = extractErrorMessage(err);
|
||||
|
|
@ -223,17 +285,118 @@ async function openRegisterServerDialog(
|
|||
};
|
||||
|
||||
form.addEventListener('submit', onSubmit);
|
||||
testBtn.addEventListener('click', onTestConn);
|
||||
closeBtn.addEventListener('click', onClose);
|
||||
cancelBtn.addEventListener('click', onClose);
|
||||
dialog.addEventListener('close', onDialogClose);
|
||||
dialog.showModal();
|
||||
}
|
||||
|
||||
async function openImportSshConfigDialog(onImported: () => Promise<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(
|
||||
root: HTMLElement,
|
||||
state: ClientState,
|
||||
): Promise<void> {
|
||||
root.replaceChildren();
|
||||
registerDashboardLivePatchers({
|
||||
onTick: patchDashboardServerTick,
|
||||
onStates: patchDashboardServerStates,
|
||||
});
|
||||
registerViewCleanup(() => {
|
||||
registerDashboardLivePatchers(null);
|
||||
});
|
||||
const [res, pinnedRes] = await Promise.all([
|
||||
apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
|
||||
apiFetch<{
|
||||
|
|
@ -294,18 +457,90 @@ export async function renderDashboardView(
|
|||
void renderDashboardView(root, state);
|
||||
});
|
||||
|
||||
const importSshBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm mutating-action' },
|
||||
'Import SSH Config',
|
||||
);
|
||||
importSshBtn.addEventListener('click', () => {
|
||||
void openImportSshConfigDialog(() => renderDashboardView(root, state));
|
||||
});
|
||||
|
||||
const connCount = servers.filter((s) => s.runtime.status === 'connected').length;
|
||||
const issueCount = servers.length - connCount;
|
||||
|
||||
const vaultSummary = !state.vaultRuntimeReady
|
||||
? 'Vault: sealed (master key required)'
|
||||
: state.vaultState === 'unlocked'
|
||||
? 'Vault: unlocked (editable)'
|
||||
: 'Vault: locked (collectors & secrets active)';
|
||||
|
||||
const filterSearchInput = el('input', {
|
||||
type: 'search',
|
||||
class: 'input-sm',
|
||||
placeholder: 'Filter host / tag / name...',
|
||||
value: fleetSearch,
|
||||
'aria-label': 'Filter servers',
|
||||
}) as HTMLInputElement;
|
||||
|
||||
const filterButtons = (['all', 'connected', 'issues'] as const).map((mode) => {
|
||||
const label =
|
||||
mode === 'all'
|
||||
? `All (${servers.length})`
|
||||
: mode === 'connected'
|
||||
? `Connected (${connCount})`
|
||||
: `Issues (${issueCount})`;
|
||||
const b = el(
|
||||
'button',
|
||||
{ type: 'button', class: `btn btn-sm${fleetFilter === mode ? ' btn-primary' : ''}` },
|
||||
label,
|
||||
);
|
||||
b.addEventListener('click', () => {
|
||||
fleetFilter = mode;
|
||||
applyFleetFilter();
|
||||
for (const btn of filterButtons) btn.classList.remove('btn-primary');
|
||||
b.classList.add('btn-primary');
|
||||
});
|
||||
return b;
|
||||
});
|
||||
|
||||
const applyFleetFilter = () => {
|
||||
const q = fleetSearch.trim().toLowerCase();
|
||||
for (const card of root.querySelectorAll('[data-server-card]')) {
|
||||
const st = card.getAttribute('data-status') ?? '';
|
||||
const hay = card.getAttribute('data-search') ?? '';
|
||||
const matchMode =
|
||||
fleetFilter === 'all'
|
||||
? true
|
||||
: fleetFilter === 'connected'
|
||||
? st === 'connected'
|
||||
: st !== 'connected';
|
||||
const matchQ = !q || hay.includes(q);
|
||||
(card as HTMLElement).hidden = !(matchMode && matchQ);
|
||||
}
|
||||
};
|
||||
|
||||
filterSearchInput.addEventListener('input', () => {
|
||||
fleetSearch = filterSearchInput.value;
|
||||
applyFleetFilter();
|
||||
});
|
||||
|
||||
root.append(
|
||||
el(
|
||||
'div',
|
||||
{ class: 'panel row-between' },
|
||||
el('div', {}, el('h1', {}, `Fleet Monitor (${servers.length} servers)`), el('span', { class: 'muted' }, vaultSummary)),
|
||||
el('div', { class: 'row' }, registerBtn, rotateFleetBtn, refreshBtn),
|
||||
{ class: 'panel stack' },
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
el('div', {}, el('h1', {}, `Fleet Monitor (${connCount}/${servers.length} connected)`), el('span', { class: 'muted' }, vaultSummary)),
|
||||
el('div', { class: 'row' }, registerBtn, importSshBtn, rotateFleetBtn, refreshBtn),
|
||||
),
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
el('div', { class: 'row' }, ...filterButtons),
|
||||
filterSearchInput,
|
||||
),
|
||||
),
|
||||
actionStatus,
|
||||
);
|
||||
|
|
@ -514,7 +749,12 @@ export async function renderDashboardView(
|
|||
|
||||
const card = el(
|
||||
'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(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
|
|
@ -559,4 +799,5 @@ export async function renderDashboardView(
|
|||
grid.append(card);
|
||||
}
|
||||
root.append(grid);
|
||||
applyFleetFilter();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,19 +1,23 @@
|
|||
import type { DiskSample, ProbeSample } from '../../../shared/ws-protocol.js';
|
||||
import { apiFetch } from '../api.js';
|
||||
import { createRangeChartSvg } from '../charts.js';
|
||||
import { createDualRangeChartSvg, createRangeChartSvg } from '../charts.js';
|
||||
import { confirmDialog } from '../dialogs.js';
|
||||
import {
|
||||
el,
|
||||
extractErrorMessage,
|
||||
fmtBytesPerSec,
|
||||
fmtTime,
|
||||
type ServerEntry,
|
||||
} from '../state.js';
|
||||
import { showToast } from '../toast.js';
|
||||
|
||||
type DetailTab = 'metrics' | 'inspector' | 'keys' | 'tunnels';
|
||||
|
||||
let activeTab: DetailTab = 'metrics';
|
||||
let activeRange: '1h' | '6h' | '24h' | '7d' | '30d' = '1h';
|
||||
let procSortBy: 'cpu' | 'mem' = 'cpu';
|
||||
let inspectSudo = false;
|
||||
let showAllKnownHosts = false;
|
||||
|
||||
export async function renderServerDetailView(
|
||||
root: HTMLElement,
|
||||
|
|
@ -37,6 +41,36 @@ export async function renderServerDetailView(
|
|||
}
|
||||
|
||||
const header = el('section', { class: 'panel' });
|
||||
const testConnBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm mutating-action' },
|
||||
'Test SSH',
|
||||
);
|
||||
testConnBtn.addEventListener('click', async () => {
|
||||
testConnBtn.disabled = true;
|
||||
try {
|
||||
const res = await apiFetch<{
|
||||
ok: boolean;
|
||||
latencyMs: number;
|
||||
osDetected?: string;
|
||||
hostFingerprint?: string;
|
||||
error?: string;
|
||||
}>('/api/servers/test-connection', {
|
||||
method: 'POST',
|
||||
body: entry.config,
|
||||
});
|
||||
if (res.ok) {
|
||||
showToast(`SSH OK in ${Math.round(res.latencyMs)}ms (${res.osDetected ?? 'unknown'})`, 'ok');
|
||||
} else {
|
||||
showToast(`SSH test failed: ${res.error ?? 'unknown error'}`, 'err');
|
||||
}
|
||||
} catch (err) {
|
||||
showToast(extractErrorMessage(err), 'err');
|
||||
} finally {
|
||||
testConnBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
const reconnBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm mutating-action' },
|
||||
|
|
@ -110,6 +144,7 @@ export async function renderServerDetailView(
|
|||
'div',
|
||||
{ class: 'row' },
|
||||
el('span', { class: 'badge' }, `[${entry.runtime.status.toUpperCase()}]`),
|
||||
testConnBtn,
|
||||
reconnBtn,
|
||||
delBtn,
|
||||
el('a', { href: '#dashboard', class: 'btn btn-sm' }, '← Dashboard'),
|
||||
|
|
@ -127,7 +162,7 @@ export async function renderServerDetailView(
|
|||
} else if (activeTab === 'inspector') {
|
||||
await renderInspectorTab(body, serverId);
|
||||
} else if (activeTab === 'keys') {
|
||||
await renderKeysTab(body, serverId);
|
||||
await renderKeysTab(body, serverId, `${entry.config.host}:${entry.config.port}`);
|
||||
} else {
|
||||
const { renderTunnelsPanel } = await import('./tunnels-panel.js');
|
||||
await renderTunnelsPanel(body, serverId);
|
||||
|
|
@ -135,13 +170,20 @@ export async function renderServerDetailView(
|
|||
}
|
||||
|
||||
async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<void> {
|
||||
const data = await apiFetch<{
|
||||
range: string;
|
||||
granularity: 'raw' | '1h' | '1d';
|
||||
points: Array<Record<string, number>>;
|
||||
latestDisks: DiskSample[];
|
||||
latestProbes: Array<ProbeSample & { ts: number }>;
|
||||
}>(`/api/servers/${encodeURIComponent(serverId)}/metrics?range=${activeRange}`);
|
||||
const [data, probeHistRes] = await Promise.all([
|
||||
apiFetch<{
|
||||
range: string;
|
||||
granularity: 'raw' | '1h' | '1d';
|
||||
points: Array<Record<string, number>>;
|
||||
latestDisks: DiskSample[];
|
||||
latestProbes: Array<ProbeSample & { ts: number }>;
|
||||
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(
|
||||
'div',
|
||||
|
|
@ -173,6 +215,22 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
|
|||
return p.memTotalMb ? ((p.memUsedMb ?? 0) / p.memTotalMb) * 100 : 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(
|
||||
'div',
|
||||
|
|
@ -180,6 +238,25 @@ 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', {}, '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', {}, '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);
|
||||
|
||||
|
|
@ -202,16 +279,82 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
|
|||
diskPanel.append(el('div', { class: 'table-wrap' }, dTable));
|
||||
body.append(diskPanel);
|
||||
|
||||
// Probes table
|
||||
// Probes table + Run Now + Probe History summary
|
||||
const probePanel = el('section', { class: 'panel' });
|
||||
probePanel.append(el('h2', {}, 'Endpoint Health Probes'));
|
||||
const okProbes = probeHistory.filter((p) => p.ok).length;
|
||||
const failProbes = probeHistory.length - okProbes;
|
||||
probePanel.append(
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
el('h2', {}, 'Endpoint Health Probes'),
|
||||
el(
|
||||
'span',
|
||||
{ class: 'muted mono' },
|
||||
probeHistory.length > 0 ? `${probeHistory.length} checks (${okProbes} ok / ${failProbes} fail in ${activeRange})` : 'No probe history in range',
|
||||
),
|
||||
),
|
||||
);
|
||||
const pTable = el('table');
|
||||
pTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'Probe ID'), el('th', {}, 'Status'), el('th', {}, 'HTTP Code'), el('th', {}, 'Latency'), el('th', {}, 'Checked At'), el('th', {}, 'Detail'))));
|
||||
pTable.append(
|
||||
el(
|
||||
'thead',
|
||||
{},
|
||||
el(
|
||||
'tr',
|
||||
{},
|
||||
el('th', {}, 'Probe ID'),
|
||||
el('th', {}, 'Status'),
|
||||
el('th', {}, 'HTTP Code'),
|
||||
el('th', {}, 'Latency'),
|
||||
el('th', {}, 'TLS Expiry'),
|
||||
el('th', {}, 'Checked At'),
|
||||
el('th', {}, 'Detail'),
|
||||
el('th', {}, 'Action'),
|
||||
),
|
||||
),
|
||||
);
|
||||
const pBody = el('tbody');
|
||||
if (data.latestProbes.length === 0) {
|
||||
pBody.append(el('tr', {}, el('td', { colspan: 6, class: 'muted' }, 'No probe results recorded yet.')));
|
||||
pBody.append(el('tr', {}, el('td', { colspan: 8, class: 'muted' }, 'No probe results recorded yet.')));
|
||||
} else {
|
||||
for (const p of data.latestProbes) {
|
||||
const tlsBadge =
|
||||
p.certExpiryDays !== undefined
|
||||
? el(
|
||||
'span',
|
||||
{
|
||||
class: `badge ${
|
||||
p.certExpiryDays <= 0
|
||||
? 'badge-err'
|
||||
: p.certExpiryDays <= 14
|
||||
? 'badge-warn'
|
||||
: 'badge-ok'
|
||||
}`,
|
||||
},
|
||||
`${p.certExpiryDays}d`,
|
||||
)
|
||||
: el('span', { class: 'muted' }, '—');
|
||||
const runBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Run Now');
|
||||
runBtn.addEventListener('click', async () => {
|
||||
runBtn.disabled = true;
|
||||
try {
|
||||
const runRes = await apiFetch<{ sample: ProbeSample }>(
|
||||
`/api/servers/${encodeURIComponent(serverId)}/probes/${encodeURIComponent(p.probeId)}/run`,
|
||||
{ method: 'POST', body: {} },
|
||||
);
|
||||
showToast(
|
||||
`Probe "${p.probeId}": ${runRes.sample.ok ? `OK (${Math.round(runRes.sample.latencyMs)}ms)` : runRes.sample.error ?? 'FAIL'}`,
|
||||
runRes.sample.ok ? 'ok' : 'err',
|
||||
);
|
||||
body.replaceChildren();
|
||||
await renderMetricsTab(body, serverId);
|
||||
} catch (err) {
|
||||
showToast(extractErrorMessage(err), 'err');
|
||||
} finally {
|
||||
runBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
pBody.append(
|
||||
el(
|
||||
'tr',
|
||||
|
|
@ -220,8 +363,10 @@ 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', { class: 'mono' }, p.statusCode ? String(p.statusCode) : '—'),
|
||||
el('td', { class: 'mono' }, `${Math.round(p.latencyMs)} ms`),
|
||||
el('td', {}, tlsBadge),
|
||||
el('td', { class: 'mono' }, fmtTime(p.ts)),
|
||||
el('td', { class: 'mono err-text' }, p.error ?? '—'),
|
||||
el('td', {}, runBtn),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
|
@ -234,6 +379,11 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise<vo
|
|||
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 sortMemBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'mem' ? ' btn-primary' : ''}` }, 'Sort RAM');
|
||||
const sudoBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: `btn btn-sm mutating-action${inspectSudo ? ' btn-primary' : ''}` },
|
||||
inspectSudo ? 'Sudo: ON' : '+Sudo',
|
||||
);
|
||||
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh Snapshot');
|
||||
|
||||
sortCpuBtn.addEventListener('click', () => {
|
||||
|
|
@ -246,13 +396,18 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<
|
|||
body.replaceChildren();
|
||||
void renderInspectorTab(body, serverId);
|
||||
});
|
||||
sudoBtn.addEventListener('click', () => {
|
||||
inspectSudo = !inspectSudo;
|
||||
body.replaceChildren();
|
||||
void renderInspectorTab(body, serverId);
|
||||
});
|
||||
refreshBtn.addEventListener('click', () => {
|
||||
body.replaceChildren();
|
||||
void renderInspectorTab(body, serverId);
|
||||
});
|
||||
|
||||
body.append(
|
||||
el('div', { class: 'panel row-between' }, el('strong', {}, 'On-Demand Server Inspector'), el('div', { class: 'row' }, sortCpuBtn, sortMemBtn, refreshBtn)),
|
||||
el('div', { class: 'panel row-between' }, el('strong', {}, 'On-Demand Server Inspector'), el('div', { class: 'row' }, sortCpuBtn, sortMemBtn, sudoBtn, refreshBtn)),
|
||||
);
|
||||
|
||||
try {
|
||||
|
|
@ -262,18 +417,53 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<
|
|||
processes: Array<{ pid: number; user: string; cpuPct: number; memPct: number; rssMb: number; command: string }>;
|
||||
ports: Array<{ proto: string; localAddress: string; process: string }>;
|
||||
thermals: Array<{ zone: string; tempC: number }>;
|
||||
}>(`/api/servers/${encodeURIComponent(serverId)}/inspect`);
|
||||
}>(`/api/servers/${encodeURIComponent(serverId)}/inspect?sort=${procSortBy}&sudo=${inspectSudo ? 'true' : 'false'}`);
|
||||
|
||||
const sortedProcs = [...res.processes].sort((a, b) =>
|
||||
procSortBy === 'cpu' ? b.cpuPct - a.cpuPct : b.memPct - a.memPct,
|
||||
);
|
||||
|
||||
const procTable = el('table');
|
||||
procTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'PID'), el('th', {}, 'User'), el('th', {}, 'CPU%'), el('th', {}, 'MEM%'), el('th', {}, 'RSS'), el('th', {}, 'Command'))));
|
||||
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'))));
|
||||
const pBody = el('tbody');
|
||||
for (const p of sortedProcs) {
|
||||
const makeSigBtn = (sig: 'SIGTERM' | 'SIGKILL', cls: string) => {
|
||||
const b = el('button', { type: 'button', class: `btn btn-sm ${cls} mutating-action` }, sig === 'SIGTERM' ? 'TERM' : 'KILL');
|
||||
b.addEventListener('click', async () => {
|
||||
const ok = await confirmDialog(
|
||||
'dialog-confirm',
|
||||
`Send ${sig} to PID ${p.pid} (${p.command.slice(0, 48)}) on ${serverId}?`,
|
||||
);
|
||||
if (!ok) return;
|
||||
try {
|
||||
const sigRes = await apiFetch<{ ok: boolean; error?: string }>(
|
||||
`/api/servers/${encodeURIComponent(serverId)}/processes/${p.pid}/signal`,
|
||||
{ method: 'POST', body: { signal: sig, sudo: inspectSudo } },
|
||||
);
|
||||
showToast(
|
||||
sigRes.ok ? `Sent ${sig} to PID ${p.pid}.` : `Signal ${sig} failed: ${sigRes.error ?? 'error'}`,
|
||||
sigRes.ok ? 'ok' : 'err',
|
||||
);
|
||||
body.replaceChildren();
|
||||
await renderInspectorTab(body, serverId);
|
||||
} catch (err) {
|
||||
showToast(extractErrorMessage(err), 'err');
|
||||
}
|
||||
});
|
||||
return b;
|
||||
};
|
||||
pBody.append(
|
||||
el('tr', {}, el('td', { class: 'mono' }, String(p.pid)), el('td', { class: 'mono' }, p.user), el('td', { class: 'mono' }, `${p.cpuPct}`), el('td', { class: 'mono' }, `${p.memPct}`), el('td', { class: 'mono' }, `${p.rssMb}M`), el('td', { class: 'mono' }, p.command.slice(0, 90))),
|
||||
el(
|
||||
'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);
|
||||
|
|
@ -306,7 +496,7 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise<
|
|||
}
|
||||
}
|
||||
|
||||
async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void> {
|
||||
async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: string): Promise<void> {
|
||||
const msg = el('p', { class: 'form-msg' });
|
||||
const rotateBtn = el(
|
||||
'button',
|
||||
|
|
@ -330,7 +520,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void>
|
|||
const r = res.results[0];
|
||||
if (r?.ok) {
|
||||
body.replaceChildren();
|
||||
await renderKeysTab(body, serverId);
|
||||
await renderKeysTab(body, serverId, hostPortKey);
|
||||
} else {
|
||||
msg.className = 'form-msg err-text';
|
||||
msg.textContent = `Rotation failed (rolledBack=${String(r?.rolledBack)}): ${r?.error ?? 'unknown'}`;
|
||||
|
|
@ -359,7 +549,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void>
|
|||
body: { credentialId: deploySelect.value },
|
||||
});
|
||||
body.replaceChildren();
|
||||
await renderKeysTab(body, serverId);
|
||||
await renderKeysTab(body, serverId, hostPortKey);
|
||||
} catch (err) {
|
||||
msg.className = 'form-msg err-text';
|
||||
msg.textContent = extractErrorMessage(err);
|
||||
|
|
@ -376,6 +566,72 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void>
|
|||
msg,
|
||||
);
|
||||
|
||||
// Known Hosts (Multi-Algo)
|
||||
try {
|
||||
const khRes = await apiFetch<{
|
||||
knownHosts: Array<{ hostPort: string; algorithm: string; fingerprint: string; updatedAt: number }>;
|
||||
}>('/api/servers/known-hosts');
|
||||
const filteredKh = showAllKnownHosts
|
||||
? khRes.knownHosts
|
||||
: khRes.knownHosts.filter((kh) => kh.hostPort === hostPortKey);
|
||||
const scopeBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm' },
|
||||
showAllKnownHosts ? `Filter ${hostPortKey}` : `Show All (${khRes.knownHosts.length})`,
|
||||
);
|
||||
scopeBtn.addEventListener('click', () => {
|
||||
showAllKnownHosts = !showAllKnownHosts;
|
||||
body.replaceChildren();
|
||||
void renderKeysTab(body, serverId, hostPortKey);
|
||||
});
|
||||
const khTable = el('table');
|
||||
khTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'Host:Port'), el('th', {}, 'Algorithm'), el('th', {}, 'Fingerprint'), el('th', {}, 'Updated'), el('th', {}, 'Action'))));
|
||||
const khBody = el('tbody');
|
||||
if (filteredKh.length === 0) {
|
||||
khBody.append(el('tr', {}, el('td', { colspan: 5, class: 'muted' }, 'No trusted host keys in scope.')));
|
||||
} else {
|
||||
for (const kh of filteredKh) {
|
||||
const delKhBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
|
||||
delKhBtn.addEventListener('click', async () => {
|
||||
const ok = await confirmDialog(
|
||||
'dialog-confirm',
|
||||
`Remove trusted ${kh.algorithm} key for ${kh.hostPort}? Next connection will require TOFU approval.`,
|
||||
);
|
||||
if (!ok) return;
|
||||
await apiFetch(
|
||||
`/api/servers/known-hosts?hostPort=${encodeURIComponent(kh.hostPort)}&algorithm=${encodeURIComponent(kh.algorithm)}`,
|
||||
{ method: 'DELETE' },
|
||||
);
|
||||
showToast(`Deleted ${kh.algorithm} key for ${kh.hostPort}.`, 'ok');
|
||||
body.replaceChildren();
|
||||
await renderKeysTab(body, serverId, hostPortKey);
|
||||
});
|
||||
khBody.append(
|
||||
el(
|
||||
'tr',
|
||||
{},
|
||||
el('td', { class: 'mono' }, kh.hostPort),
|
||||
el('td', { class: 'mono' }, kh.algorithm),
|
||||
el('td', { class: 'mono' }, kh.fingerprint),
|
||||
el('td', { class: 'mono' }, fmtTime(kh.updatedAt)),
|
||||
el('td', {}, delKhBtn),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
khTable.append(khBody);
|
||||
body.append(
|
||||
el(
|
||||
'section',
|
||||
{ class: 'panel' },
|
||||
el('div', { class: 'row-between' }, el('h2', {}, 'Trusted Host Keys (known_hosts)'), scopeBtn),
|
||||
el('div', { class: 'table-wrap' }, khTable),
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
body.append(el('div', { class: 'panel err-text' }, extractErrorMessage(err)));
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await apiFetch<{
|
||||
entries: Array<{
|
||||
|
|
@ -410,7 +666,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise<void>
|
|||
body: { fingerprint: k.fingerprint },
|
||||
});
|
||||
body.replaceChildren();
|
||||
await renderKeysTab(body, serverId);
|
||||
await renderKeysTab(body, serverId, hostPortKey);
|
||||
});
|
||||
}
|
||||
kBody.append(
|
||||
|
|
|
|||
360
src/client/ts/views/settings-ops-panel.ts
Normal file
360
src/client/ts/views/settings-ops-panel.ts
Normal file
|
|
@ -0,0 +1,360 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -20,16 +20,6 @@ interface SessionRow {
|
|||
current: boolean;
|
||||
}
|
||||
|
||||
interface AuditRow {
|
||||
id: number;
|
||||
ts: number;
|
||||
action: string;
|
||||
actor_ip: string;
|
||||
target: string | null;
|
||||
status: string;
|
||||
details: string | null;
|
||||
}
|
||||
|
||||
interface FactorsData {
|
||||
passwords: Array<{ id: string; label: string; createdAt: number }>;
|
||||
totps: Array<{ id: string; label: string; createdAt: number }>;
|
||||
|
|
@ -55,9 +45,8 @@ export async function renderSettingsView(
|
|||
): Promise<void> {
|
||||
root.replaceChildren();
|
||||
|
||||
const [sessRes, auditRes, factorsRes, credsRes] = await Promise.all([
|
||||
const [sessRes, factorsRes, credsRes] = await Promise.all([
|
||||
apiFetch<{ sessions: SessionRow[] }>('/api/auth/sessions'),
|
||||
apiFetch<{ total: number; items: AuditRow[] }>('/api/audit?limit=40'),
|
||||
apiFetch<FactorsData>('/api/auth/factors'),
|
||||
apiFetch<{ credentials: Array<{ id: string; name: string; type: string }> }>(
|
||||
'/api/vault/credentials',
|
||||
|
|
@ -198,12 +187,33 @@ export async function renderSettingsView(
|
|||
'select',
|
||||
{},
|
||||
el('option', { value: 'off', selected: sec.stepUpPolicy === 'off' ? true : undefined }, 'Off (never re-prompt)'),
|
||||
el('option', { value: 'session', selected: sec.stepUpPolicy === 'session' ? true : undefined }, 'Once per login session (7d)'),
|
||||
el('option', { value: 'session', selected: sec.stepUpPolicy === 'session' ? true : undefined }, 'Once per login session'),
|
||||
el('option', { value: '24h', selected: sec.stepUpPolicy === '24h' ? true : undefined }, '24 hours'),
|
||||
el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour (default)'),
|
||||
el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour'),
|
||||
el('option', { value: '15m', selected: sec.stepUpPolicy === '15m' ? true : undefined }, '15 minutes (v1.1 default)'),
|
||||
el('option', { value: '5m', selected: sec.stepUpPolicy === '5m' ? true : undefined }, '5 minutes'),
|
||||
el('option', { value: 'every-action', selected: sec.stepUpPolicy === 'every-action' ? true : undefined }, 'Every sensitive action'),
|
||||
);
|
||||
const allowSameOriginProxyChk = el('input', {
|
||||
type: 'checkbox',
|
||||
checked: sec.allowSameOriginProxy ? true : undefined,
|
||||
}) as HTMLInputElement;
|
||||
const egressCidrsInput = el('input', {
|
||||
value: (sec.egressAllowedCidrs ?? []).join(', '),
|
||||
placeholder: 'e.g. 10.20.0.0/24 (blank = block all private IPs)',
|
||||
}) as HTMLInputElement;
|
||||
const sessTtlInput = el('input', {
|
||||
type: 'number',
|
||||
min: 1,
|
||||
max: 720,
|
||||
value: String(sec.sessionTtlHours ?? 168),
|
||||
}) as HTMLInputElement;
|
||||
const sessIdleInput = el('input', {
|
||||
type: 'number',
|
||||
min: 0,
|
||||
max: 10080,
|
||||
value: String(sec.sessionIdleTimeoutMin ?? 60),
|
||||
}) as HTMLInputElement;
|
||||
const methodSel = el(
|
||||
'select',
|
||||
{},
|
||||
|
|
@ -270,6 +280,7 @@ export async function renderSettingsView(
|
|||
policyMsg.textContent = '';
|
||||
try {
|
||||
const nextSecurity: ClientSecuritySettings = {
|
||||
...sec,
|
||||
requireTotpOnLogin: reqTotpChk.checked,
|
||||
passwordMode: pwModeSel.value as 'any' | 'all',
|
||||
totpMode: totpModeSel.value as 'any' | 'all',
|
||||
|
|
@ -278,6 +289,13 @@ export async function renderSettingsView(
|
|||
elevateOnLogin: elevateLoginChk.checked,
|
||||
keepElevationOnSafeMode: keepSafeChk.checked,
|
||||
enableEmergencySecretsBackup: backupChk.checked,
|
||||
allowSameOriginProxy: allowSameOriginProxyChk.checked,
|
||||
egressAllowedCidrs: egressCidrsInput.value
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
sessionTtlHours: Number(sessTtlInput.value || 168),
|
||||
sessionIdleTimeoutMin: Number(sessIdleInput.value || 0),
|
||||
};
|
||||
const nextSettings = {
|
||||
...(state.overview?.settings ?? {}),
|
||||
|
|
@ -307,14 +325,18 @@ export async function renderSettingsView(
|
|||
el('div', {}, el('label', {}, 'TOTP Matching Mode'), totpModeSel),
|
||||
el('div', {}, el('label', {}, 'Step-Up Re-Auth Window'), policySel),
|
||||
el('div', {}, el('label', {}, 'Step-Up Method'), methodSel),
|
||||
el('div', {}, el('label', {}, 'Session Max Lifetime (hours)'), sessTtlInput),
|
||||
el('div', {}, el('label', {}, 'Session Idle Timeout (min, 0=off)'), sessIdleInput),
|
||||
),
|
||||
el('div', { style: 'margin-top:8px' }, el('label', {}, 'Egress Allowed CIDRs / IPs (CSV)'), egressCidrsInput),
|
||||
el(
|
||||
'div',
|
||||
{ class: 'stack', style: 'margin-top:8px' },
|
||||
el('label', { class: 'chk-row' }, reqTotpChk, 'Require TOTP code during Login'),
|
||||
el('label', { class: 'chk-row' }, elevateLoginChk, 'Auto-elevate session on Login (skips immediate Step-Up)'),
|
||||
el('label', { class: 'chk-row' }, keepSafeChk, 'Keep Step-Up elevation when toggling Safe Mode ON'),
|
||||
el('label', { class: 'chk-row' }, backupChk, 'Maintain automatic chmod 0600 secrets backup in data/recovery/'),
|
||||
el('label', { class: 'chk-row' }, allowSameOriginProxyChk, 'Allow same-origin HTTP proxy fallback (less strict cookie isolation than isolated origin)'),
|
||||
el('label', { class: 'chk-row' }, backupChk, 'Maintain passwordless emergency secrets backup in data/recovery/ (master key + vault creds only; login passwords never stored)'),
|
||||
),
|
||||
el('div', { class: 'row', style: 'margin-top:8px' }, savePolicyBtn),
|
||||
policyMsg,
|
||||
|
|
@ -730,7 +752,7 @@ export async function renderSettingsView(
|
|||
'p',
|
||||
{ class: 'muted' },
|
||||
isWebAuthnSupported()
|
||||
? 'Enroll device biometrics or hardware security keys for one-tap passwordless sign-in and Step-Up verification.'
|
||||
? '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.'
|
||||
: 'Passkeys require HTTPS (e.g. Cloudflare Tunnel) or http://localhost — plain HTTP or raw IP URLs block navigator.credentials.',
|
||||
),
|
||||
);
|
||||
|
|
@ -817,7 +839,7 @@ export async function renderSettingsView(
|
|||
el(
|
||||
'p',
|
||||
{ class: 'muted mono' },
|
||||
`Path: ${rb.filePath} (chmod 0600) | Exists: ${rb.exists ? 'YES' : 'NO'} | MasterKeySaved: ${rb.hasMasterKey ? 'YES' : 'NO'} | VaultCreds: ${rb.credentialCount} | Snapshots: ${rb.snapshotCount}`,
|
||||
`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}`,
|
||||
),
|
||||
);
|
||||
const bMsg = el('p', { class: 'form-msg' });
|
||||
|
|
@ -837,7 +859,10 @@ export async function renderSettingsView(
|
|||
dlBackupBtn.addEventListener('click', async () => {
|
||||
bMsg.textContent = '';
|
||||
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`], {
|
||||
type: 'application/json',
|
||||
});
|
||||
|
|
@ -944,41 +969,9 @@ export async function renderSettingsView(
|
|||
sessPanel.append(el('div', { class: 'table-wrap' }, sTable));
|
||||
root.append(sessPanel);
|
||||
|
||||
// 6. Audit Log
|
||||
const auditPanel = el('section', { class: 'panel panel-region' });
|
||||
auditPanel.append(el('h2', {}, `Security & Action Audit Log (${auditRes.total} entries)`));
|
||||
const aTable = el('table');
|
||||
aTable.append(
|
||||
el(
|
||||
'thead',
|
||||
{},
|
||||
el('tr', {}, el('th', {}, 'Timestamp'), el('th', {}, 'Action'), el('th', {}, 'Status'), el('th', {}, 'Target'), el('th', {}, 'IP'), el('th', {}, 'Details')),
|
||||
),
|
||||
);
|
||||
const aBody = el('tbody');
|
||||
for (const row of auditRes.items) {
|
||||
aBody.append(
|
||||
el(
|
||||
'tr',
|
||||
{},
|
||||
el('td', { class: 'mono' }, fmtTime(row.ts)),
|
||||
el('td', { class: 'mono' }, row.action),
|
||||
el(
|
||||
'td',
|
||||
{},
|
||||
el(
|
||||
'span',
|
||||
{ class: `badge ${row.status === 'ok' ? 'badge-ok' : 'badge-err'}` },
|
||||
row.status,
|
||||
),
|
||||
),
|
||||
el('td', { class: 'mono' }, row.target ?? '—'),
|
||||
el('td', { class: 'mono' }, row.actor_ip),
|
||||
el('td', { class: 'mono muted' }, row.details ?? '—'),
|
||||
),
|
||||
);
|
||||
}
|
||||
aTable.append(aBody);
|
||||
auditPanel.append(el('div', { class: 'table-wrap' }, aTable));
|
||||
root.append(auditPanel);
|
||||
// 6. Runtime Profile, Prometheus /metrics, Scheduled Backups & Filterable Audit Log (lazy chunk)
|
||||
const opsHost = el('div', { class: 'stack' });
|
||||
root.append(opsHost);
|
||||
const { renderSettingsOpsPanels } = await import('./settings-ops-panel.js');
|
||||
await renderSettingsOpsPanels(opsHost, state, credsRes.credentials, onReloadState);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,15 @@
|
|||
import { computeLineDiff } from '../../../shared/diff.js';
|
||||
import { collapseDiffHunks, computeLineDiff } from '../../../shared/diff.js';
|
||||
import { apiFetch, apiUploadBinary } from '../api.js';
|
||||
import { confirmDialog } from '../dialogs.js';
|
||||
import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js';
|
||||
import {
|
||||
el,
|
||||
extractErrorMessage,
|
||||
fmtTime,
|
||||
registerViewCleanup,
|
||||
type ClientState,
|
||||
type ServerEntry,
|
||||
} from '../state.js';
|
||||
import { showToast } from '../toast.js';
|
||||
import { renderTunnelsPanel } from './tunnels-panel.js';
|
||||
|
||||
interface SftpEntry {
|
||||
|
|
@ -12,6 +20,9 @@ interface SftpEntry {
|
|||
mode: number;
|
||||
permissionsOctal: string;
|
||||
mtimeMs: number;
|
||||
uid?: number;
|
||||
gid?: number;
|
||||
symlinkTarget?: string;
|
||||
}
|
||||
|
||||
interface SftpTextPayload {
|
||||
|
|
@ -27,6 +38,8 @@ let currentServerId = '';
|
|||
let currentPath = '';
|
||||
let activeEdit: SftpTextPayload | null = null;
|
||||
let activeEditSudo = false;
|
||||
let searchMatches: string[] | null = null;
|
||||
let lastSearchQuery = '';
|
||||
|
||||
function fmtFileSize(bytes: number): string {
|
||||
if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes} B`;
|
||||
|
|
@ -42,16 +55,35 @@ function showSftpDiffDialog(
|
|||
onConfirm: (force: boolean) => Promise<void>,
|
||||
): void {
|
||||
const diff = computeLineDiff(originalText, nextText, 'remote', 'edited');
|
||||
const collapsed = diff.collapsedLines ?? collapseDiffHunks(diff.lines);
|
||||
const hasHunk = collapsed.some((e) => e.type === 'hunk');
|
||||
let expanded = !hasHunk;
|
||||
|
||||
const dialog = document.createElement('dialog');
|
||||
dialog.className = 'dialog-wide';
|
||||
dialog.setAttribute('aria-labelledby', 'sftp-diff-title');
|
||||
|
||||
const pre = el('pre', { class: 'diff-body mono' });
|
||||
for (const line of diff.lines) {
|
||||
const cls = line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : '';
|
||||
const prefix = line.type === 'add' ? '+' : line.type === 'del' ? '-' : ' ';
|
||||
pre.append(el('div', { class: cls }, `${prefix}${line.text}`));
|
||||
}
|
||||
const toggleDiffBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: !hasHunk }, 'Expand Full Diff');
|
||||
const renderDiffBody = () => {
|
||||
pre.replaceChildren();
|
||||
const src = expanded ? diff.lines : collapsed;
|
||||
for (const entry of src) {
|
||||
if (entry.type === 'hunk') {
|
||||
pre.append(el('div', { class: 'diff-hunk-sep' }, entry.text));
|
||||
} else {
|
||||
const cls = entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : '';
|
||||
const prefix = entry.type === 'add' ? '+' : entry.type === 'del' ? '-' : ' ';
|
||||
pre.append(el('div', { class: cls }, `${prefix}${entry.text}`));
|
||||
}
|
||||
}
|
||||
toggleDiffBtn.textContent = expanded ? 'Collapse Context' : 'Expand Full Diff';
|
||||
};
|
||||
toggleDiffBtn.addEventListener('click', () => {
|
||||
expanded = !expanded;
|
||||
renderDiffBody();
|
||||
});
|
||||
renderDiffBody();
|
||||
|
||||
const errEl = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' });
|
||||
const forceWrap = el('div', { hidden: true });
|
||||
|
|
@ -83,7 +115,7 @@ function showSftpDiffDialog(
|
|||
|
||||
dialog.append(
|
||||
el('div', { class: 'row-between' }, el('h1', { id: 'sftp-diff-title' }, `Pre-Save Diff: ${filePath}${sudo ? ' [SUDO]' : ''}`), cancelBtn),
|
||||
el('p', { class: 'mono muted' }, `+${diff.additions} additions, -${diff.deletions} deletions`),
|
||||
el('div', { class: 'row-between' }, el('p', { class: 'mono muted' }, `+${diff.additions} additions, -${diff.deletions} deletions`), toggleDiffBtn),
|
||||
pre,
|
||||
errEl,
|
||||
el('div', { class: 'dialog-actions' }, forceWrap, writeBtn),
|
||||
|
|
@ -138,9 +170,13 @@ export async function renderSftpView(
|
|||
return;
|
||||
}
|
||||
|
||||
if (q.server && servers.some((s) => s.config.id === q.server)) {
|
||||
if (currentServerId !== q.server) currentPath = '';
|
||||
currentServerId = q.server;
|
||||
const targetServer = q.server ?? q.serverId;
|
||||
if (targetServer && servers.some((s) => s.config.id === targetServer)) {
|
||||
if (currentServerId !== targetServer) {
|
||||
currentPath = '';
|
||||
searchMatches = null;
|
||||
}
|
||||
currentServerId = targetServer;
|
||||
} else if (!currentServerId || !servers.some((s) => s.config.id === currentServerId)) {
|
||||
currentServerId = servers[0]!.config.id;
|
||||
}
|
||||
|
|
@ -185,6 +221,7 @@ export async function renderSftpView(
|
|||
const goPath = (nextPath: string) => {
|
||||
currentPath = nextPath;
|
||||
activeEdit = null;
|
||||
searchMatches = null;
|
||||
void renderSftpView(root, state);
|
||||
};
|
||||
goBtn.addEventListener('click', () => goPath(pathInput.value.trim() || '~'));
|
||||
|
|
@ -199,6 +236,7 @@ export async function renderSftpView(
|
|||
refreshBtn.addEventListener('click', () => void renderSftpView(root, state));
|
||||
|
||||
const mkdirBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ Folder');
|
||||
const touchBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ File');
|
||||
const uploadInput = el('input', { type: 'file', multiple: true, style: 'display:none' });
|
||||
const uploadBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Upload Files');
|
||||
uploadBtn.addEventListener('click', () => uploadInput.click());
|
||||
|
|
@ -257,6 +295,63 @@ export async function renderSftpView(
|
|||
}
|
||||
});
|
||||
|
||||
touchBtn.addEventListener('click', async () => {
|
||||
const name = window.prompt('New empty file name:');
|
||||
if (!name || !name.trim()) return;
|
||||
const target = currentPath === '/' ? `/${name.trim()}` : `${currentPath}/${name.trim()}`;
|
||||
try {
|
||||
await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/touch`, {
|
||||
method: 'POST',
|
||||
body: { path: target },
|
||||
});
|
||||
showToast(`Created ${target}`, 'ok');
|
||||
await renderSftpView(root, state);
|
||||
} catch (err) {
|
||||
statusMsg.className = 'form-msg err-text';
|
||||
statusMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
|
||||
const searchInput = el('input', {
|
||||
type: 'search',
|
||||
class: 'input-sm',
|
||||
value: lastSearchQuery,
|
||||
placeholder: 'Search files recursively (e.g. *.conf)...',
|
||||
'aria-label': 'Search remote files',
|
||||
}) as HTMLInputElement;
|
||||
const searchBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Search');
|
||||
const clearSearchBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: searchMatches === null }, 'Clear Search');
|
||||
|
||||
const runSearch = async () => {
|
||||
const qStr = searchInput.value.trim();
|
||||
if (!qStr) return;
|
||||
lastSearchQuery = qStr;
|
||||
statusMsg.className = 'form-msg muted';
|
||||
statusMsg.textContent = `Searching ${currentPath || '/'} for "${qStr}"...`;
|
||||
try {
|
||||
const sRes = await apiFetch<{ basePath: string; matches: string[] }>(
|
||||
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/search?path=${encodeURIComponent(currentPath || '/')}&q=${encodeURIComponent(qStr)}&max=100`,
|
||||
);
|
||||
searchMatches = sRes.matches;
|
||||
await renderSftpView(root, state);
|
||||
} catch (err) {
|
||||
statusMsg.className = 'form-msg err-text';
|
||||
statusMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
};
|
||||
searchBtn.addEventListener('click', () => void runSearch());
|
||||
searchInput.addEventListener('keydown', (ev) => {
|
||||
if (ev.key === 'Enter') {
|
||||
ev.preventDefault();
|
||||
void runSearch();
|
||||
}
|
||||
});
|
||||
clearSearchBtn.addEventListener('click', () => {
|
||||
searchMatches = null;
|
||||
lastSearchQuery = '';
|
||||
void renderSftpView(root, state);
|
||||
});
|
||||
|
||||
const termHref = `#terminal?server=${encodeURIComponent(currentServerId)}&cwd=${encodeURIComponent(currentPath || '~')}`;
|
||||
const archiveAutoHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=auto`;
|
||||
const archiveGzHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=tar.gz`;
|
||||
|
|
@ -292,13 +387,46 @@ export async function renderSftpView(
|
|||
el('a', { href: archiveAutoHref, class: 'btn btn-sm', download: '' }, 'Archive Folder (.tar.zst/.gz)'),
|
||||
el('a', { href: archiveGzHref, class: 'btn btn-sm', download: '' }, '.tar.gz'),
|
||||
mkdirBtn,
|
||||
touchBtn,
|
||||
uploadBtn,
|
||||
uploadInput,
|
||||
),
|
||||
el('div', { class: 'row', style: 'margin-top:8px' }, searchInput, searchBtn, clearSearchBtn),
|
||||
statusMsg,
|
||||
);
|
||||
root.append(topPanel);
|
||||
|
||||
if (searchMatches !== null) {
|
||||
const sBox = el('section', { class: 'panel stack' });
|
||||
sBox.append(el('strong', {}, `Search Results for "${lastSearchQuery}" (${searchMatches.length})`));
|
||||
if (searchMatches.length === 0) {
|
||||
sBox.append(el('p', { class: 'muted' }, 'No matching files or directories found (max depth 5).'));
|
||||
} else {
|
||||
for (const m of searchMatches) {
|
||||
const openEd = el('button', { type: 'button', class: 'btn btn-sm' }, 'Edit');
|
||||
openEd.addEventListener('click', async () => {
|
||||
try {
|
||||
const loaded = await apiFetch<{ file: SftpTextPayload }>(
|
||||
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/text?path=${encodeURIComponent(m)}&sudo=0`,
|
||||
);
|
||||
activeEditSudo = false;
|
||||
activeEdit = loaded.file;
|
||||
await renderSftpView(root, state);
|
||||
} catch (err) {
|
||||
showToast(extractErrorMessage(err), 'err');
|
||||
}
|
||||
});
|
||||
const jumpDir = el('button', { type: 'button', class: 'btn btn-sm' }, 'Open Dir');
|
||||
jumpDir.addEventListener('click', () => {
|
||||
const idx = m.lastIndexOf('/');
|
||||
goPath(idx > 0 ? m.slice(0, idx) : '/');
|
||||
});
|
||||
sBox.append(el('div', { class: 'row-between' }, el('span', { class: 'mono' }, m), el('div', { class: 'row' }, openEd, jumpDir)));
|
||||
}
|
||||
}
|
||||
root.append(sBox);
|
||||
}
|
||||
|
||||
// Inline Editor with Pre-Save Diff
|
||||
if (activeEdit) {
|
||||
const editBox = el('section', { class: 'panel' });
|
||||
|
|
@ -320,8 +448,7 @@ export async function renderSftpView(
|
|||
}
|
||||
});
|
||||
|
||||
const saveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Review Diff & Save');
|
||||
saveBtn.addEventListener('click', () => {
|
||||
const triggerSaveDiff = () => {
|
||||
if (!activeEdit) return;
|
||||
showSftpDiffDialog(activeEdit.path, activeEdit.content, textarea.value, activeEditSudo, async (force) => {
|
||||
const res = await apiFetch<{ path: string; sha256: string; size: number }>(
|
||||
|
|
@ -340,8 +467,18 @@ export async function renderSftpView(
|
|||
activeEdit = { ...activeEdit!, content: textarea.value, sha256: res.sha256, size: res.size };
|
||||
statusMsg.className = 'form-msg ok-text';
|
||||
statusMsg.textContent = `Saved ${res.path} (${res.size} B)`;
|
||||
showToast(`Saved ${res.path}`, 'ok');
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const saveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Review Diff & Save');
|
||||
saveBtn.addEventListener('click', triggerSaveDiff);
|
||||
|
||||
const onCtrlS = () => {
|
||||
if (textarea.isConnected && !state.safeMode) triggerSaveDiff();
|
||||
};
|
||||
window.addEventListener('gcoord:save', onCtrlS);
|
||||
registerViewCleanup(() => window.removeEventListener('gcoord:save', onCtrlS));
|
||||
|
||||
const closeEdBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close Editor');
|
||||
closeEdBtn.addEventListener('click', () => {
|
||||
|
|
@ -379,6 +516,42 @@ 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');
|
||||
tbl.append(
|
||||
el(
|
||||
|
|
@ -387,10 +560,11 @@ export async function renderSftpView(
|
|||
el(
|
||||
'tr',
|
||||
{},
|
||||
el('th', {}, 'Sel'),
|
||||
el('th', {}, 'Name'),
|
||||
el('th', {}, 'Type'),
|
||||
el('th', {}, 'Size'),
|
||||
el('th', {}, 'Mode'),
|
||||
el('th', {}, 'Mode / Owner'),
|
||||
el('th', {}, 'Modified'),
|
||||
el('th', {}, 'Actions'),
|
||||
),
|
||||
|
|
@ -401,15 +575,30 @@ export async function renderSftpView(
|
|||
if (listing.parentPath) {
|
||||
const upBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '.. (Parent Dir)');
|
||||
upBtn.addEventListener('click', () => goPath(listing!.parentPath!));
|
||||
tbody.append(el('tr', {}, el('td', { colspan: 6 }, upBtn)));
|
||||
tbody.append(el('tr', {}, el('td', { colspan: 7 }, upBtn)));
|
||||
}
|
||||
|
||||
for (const entry of listing.entries) {
|
||||
const selChk = el('input', { type: 'checkbox', 'aria-label': `Select ${entry.name}` }) as HTMLInputElement;
|
||||
selChk.addEventListener('change', () => {
|
||||
if (selChk.checked) selectedPaths.add(entry.path);
|
||||
else selectedPaths.delete(entry.path);
|
||||
updateBulkBtn();
|
||||
});
|
||||
|
||||
const nameCell = el('td', {});
|
||||
if (entry.type === 'dir') {
|
||||
const openBtn = el('button', { type: 'button', class: 'btn btn-sm' }, `[DIR] ${entry.name}/`);
|
||||
openBtn.addEventListener('click', () => goPath(entry.path));
|
||||
nameCell.append(openBtn);
|
||||
} else if (entry.type === 'symlink') {
|
||||
nameCell.append(
|
||||
el('span', { class: 'badge' }, 'LNK'),
|
||||
el('span', { class: 'mono', style: 'margin-left:6px' }, entry.name),
|
||||
entry.symlinkTarget
|
||||
? el('div', { class: 'mono muted' }, `-> ${entry.symlinkTarget}`)
|
||||
: '',
|
||||
);
|
||||
} else {
|
||||
nameCell.append(el('span', { class: 'mono' }, entry.name));
|
||||
}
|
||||
|
|
@ -466,6 +655,32 @@ export async function renderSftpView(
|
|||
await renderSftpView(root, state);
|
||||
});
|
||||
|
||||
const chownBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Chown');
|
||||
chownBtn.addEventListener('click', async () => {
|
||||
const curOwner = `${entry.uid ?? 0}:${entry.gid ?? 0}`;
|
||||
const rawOwner = window.prompt('Owner UID:GID (numeric, e.g. 1000:1000):', curOwner);
|
||||
if (!rawOwner) return;
|
||||
const parts = rawOwner.trim().split(':');
|
||||
const uid = Number(parts[0]);
|
||||
const gid = Number(parts[1] ?? parts[0]);
|
||||
if (!Number.isInteger(uid) || uid < 0 || !Number.isInteger(gid) || gid < 0) {
|
||||
showToast('Invalid UID:GID numbers.', 'err');
|
||||
return;
|
||||
}
|
||||
const useSudo = window.confirm('Use sudo chown (requires step-up)? Cancel = normal chown.');
|
||||
try {
|
||||
await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/chown`, {
|
||||
method: 'POST',
|
||||
body: { path: entry.path, uid, gid, sudo: useSudo },
|
||||
});
|
||||
showToast(`Changed owner of ${entry.name} to ${uid}:${gid}`, 'ok');
|
||||
await renderSftpView(root, state);
|
||||
} catch (err) {
|
||||
statusMsg.className = 'form-msg err-text';
|
||||
statusMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
|
||||
const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
|
||||
delBtn.addEventListener('click', async () => {
|
||||
const ok = await confirmDialog(
|
||||
|
|
@ -482,16 +697,20 @@ export async function renderSftpView(
|
|||
await renderSftpView(root, state);
|
||||
});
|
||||
|
||||
actionsRow.append(renBtn, chmodBtn, delBtn);
|
||||
actionsRow.append(renBtn, chmodBtn, chownBtn, delBtn);
|
||||
|
||||
const ownerText =
|
||||
entry.uid !== undefined && entry.gid !== undefined ? ` (${entry.uid}:${entry.gid})` : '';
|
||||
|
||||
tbody.append(
|
||||
el(
|
||||
'tr',
|
||||
{},
|
||||
el('td', {}, selChk),
|
||||
nameCell,
|
||||
el('td', { class: 'mono' }, entry.type),
|
||||
el('td', { class: 'mono' }, entry.type === 'dir' ? '—' : fmtFileSize(entry.size)),
|
||||
el('td', { class: 'mono' }, entry.permissionsOctal),
|
||||
el('td', { class: 'mono' }, `${entry.permissionsOctal}${ownerText}`),
|
||||
el('td', { class: 'mono' }, fmtTime(entry.mtimeMs)),
|
||||
el('td', {}, actionsRow),
|
||||
),
|
||||
|
|
@ -500,7 +719,7 @@ export async function renderSftpView(
|
|||
|
||||
tbl.append(tbody);
|
||||
dropPanel.append(
|
||||
el('div', { class: 'muted', style: 'margin-bottom:6px' }, 'Tip: Drag files anywhere onto this table to stream upload via SFTP.'),
|
||||
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: 'table-wrap' }, tbl),
|
||||
);
|
||||
root.append(dropPanel);
|
||||
|
|
|
|||
|
|
@ -7,11 +7,23 @@ import {
|
|||
extractErrorMessage,
|
||||
fmtTime,
|
||||
isAiEnabled,
|
||||
registerViewCleanup,
|
||||
type ClientState,
|
||||
type ServerEntry,
|
||||
} from '../state.js';
|
||||
import { showToast } from '../toast.js';
|
||||
import type { MultiplexWsClient } from '../ws-client.js';
|
||||
|
||||
interface SystemActionInputDef {
|
||||
name: string;
|
||||
type: 'string' | 'number' | 'boolean' | 'server' | 'select' | 'secret';
|
||||
label?: string;
|
||||
description?: string;
|
||||
required?: boolean;
|
||||
default?: unknown;
|
||||
options?: string[];
|
||||
}
|
||||
|
||||
interface SystemActionDef {
|
||||
id: string;
|
||||
label: string;
|
||||
|
|
@ -19,6 +31,7 @@ interface SystemActionDef {
|
|||
mode: 'oneshot' | 'stream' | 'interactive';
|
||||
sudo: boolean;
|
||||
confirm: boolean;
|
||||
inputs?: SystemActionInputDef[];
|
||||
}
|
||||
|
||||
interface SystemParamDef {
|
||||
|
|
@ -65,6 +78,88 @@ interface ServerSnapshotView {
|
|||
}
|
||||
|
||||
let unsubStreamListener: (() => void) | null = null;
|
||||
let unsubStreamChannel: (() => void) | null = null;
|
||||
|
||||
function releaseSystemStream(): void {
|
||||
if (unsubStreamChannel) {
|
||||
unsubStreamChannel();
|
||||
unsubStreamChannel = null;
|
||||
}
|
||||
if (unsubStreamListener) {
|
||||
unsubStreamListener();
|
||||
unsubStreamListener = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function promptActionInputs(
|
||||
actionLabel: string,
|
||||
defs: SystemActionInputDef[],
|
||||
): Promise<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 {
|
||||
if (h === 'ok') return 'badge badge-ok';
|
||||
|
|
@ -175,6 +270,12 @@ async function runSystemAction(opts: {
|
|||
onFinished: () => Promise<void>;
|
||||
}): Promise<void> {
|
||||
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) {
|
||||
const target = opts.subItemName ?? opts.itemName ?? opts.serverId;
|
||||
const ok = await confirmDialog(
|
||||
|
|
@ -186,20 +287,28 @@ async function runSystemAction(opts: {
|
|||
|
||||
opts.outputHost.replaceChildren(el('p', { class: 'muted mono' }, `Running ${action.label}...`));
|
||||
|
||||
const res = await apiFetch<
|
||||
let res:
|
||||
| { mode: 'oneshot'; exitCode: number | null; stdout: string; stderr: string; durationMs: number }
|
||||
| { mode: 'stream'; jobId: string }
|
||||
| { mode: 'interactive'; session: { sessionId: string } }
|
||||
>(
|
||||
`/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: {
|
||||
itemName: opts.itemName,
|
||||
subItemName: opts.subItemName,
|
||||
| { mode: 'interactive'; session: { sessionId: string } };
|
||||
try {
|
||||
res = await apiFetch(
|
||||
`/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: {
|
||||
itemName: opts.itemName,
|
||||
subItemName: opts.subItemName,
|
||||
...(actionInputs ? { inputs: actionInputs } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
);
|
||||
} catch (err) {
|
||||
const msg = extractErrorMessage(err);
|
||||
opts.outputHost.replaceChildren(el('p', { class: 'err-text mono' }, msg));
|
||||
showToast(msg, 'err');
|
||||
return;
|
||||
}
|
||||
|
||||
if (res.mode === 'interactive') {
|
||||
window.location.hash = `#terminal?session=${encodeURIComponent(res.session.sessionId)}`;
|
||||
|
|
@ -242,16 +351,14 @@ async function runSystemAction(opts: {
|
|||
}
|
||||
|
||||
// Stream mode
|
||||
if (unsubStreamListener) {
|
||||
unsubStreamListener();
|
||||
unsubStreamListener = null;
|
||||
}
|
||||
releaseSystemStream();
|
||||
|
||||
const logPre = el('pre', { class: 'stream-log mono' });
|
||||
const stopBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Stop Stream');
|
||||
const stopBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel Stream');
|
||||
stopBtn.addEventListener('click', async () => {
|
||||
await apiFetch(`/api/systems/streams/${encodeURIComponent(res.jobId)}/cancel`, { method: 'POST' });
|
||||
stopBtn.disabled = true;
|
||||
showToast(`Stream ${res.jobId} cancelled.`, 'warn');
|
||||
});
|
||||
const streamAiBtn = isAiEnabled(opts.state)
|
||||
? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Debug Output]')
|
||||
|
|
@ -303,7 +410,7 @@ async function runSystemAction(opts: {
|
|||
logPre.scrollTop = logPre.scrollHeight;
|
||||
});
|
||||
|
||||
opts.wsClient.subscribe([`stream:${res.jobId}`]);
|
||||
unsubStreamChannel = opts.wsClient.subscribe([`stream:${res.jobId}`]);
|
||||
}
|
||||
|
||||
export async function renderSystemsView(
|
||||
|
|
@ -311,10 +418,8 @@ export async function renderSystemsView(
|
|||
state: ClientState,
|
||||
wsClient: MultiplexWsClient,
|
||||
): Promise<void> {
|
||||
if (unsubStreamListener) {
|
||||
unsubStreamListener();
|
||||
unsubStreamListener = null;
|
||||
}
|
||||
releaseSystemStream();
|
||||
registerViewCleanup(releaseSystemStream);
|
||||
root.replaceChildren();
|
||||
const segs = state.routeSegments ?? [];
|
||||
const forceRefresh = state.routeQuery?.refresh === '1';
|
||||
|
|
@ -567,14 +672,16 @@ export async function renderSystemsView(
|
|||
|
||||
// Quick Editable Files via SFTP inline diff editor
|
||||
if (item.editableFiles.length > 0) {
|
||||
const needsSudo = system.actions.some((a) => a.sudo);
|
||||
const editRow = el('div', { class: 'chip-list' });
|
||||
for (const fPath of item.editableFiles) {
|
||||
editRow.append(
|
||||
el(
|
||||
'a',
|
||||
{
|
||||
href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}`,
|
||||
href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}${needsSudo ? '&sudo=1' : ''}`,
|
||||
class: 'btn btn-sm',
|
||||
title: fPath,
|
||||
},
|
||||
`Edit ${fPath.split('/').pop()}`,
|
||||
),
|
||||
|
|
|
|||
|
|
@ -3,7 +3,16 @@ import type { FitAddon } from '@xterm/addon-fit';
|
|||
import type { ServerWsFrame } from '../../../shared/ws-protocol.js';
|
||||
import { apiFetch } from '../api.js';
|
||||
import { confirmDialog } from '../dialogs.js';
|
||||
import { el, extractErrorMessage, fmtTime, isAiEnabled, type ClientState, type ServerEntry } from '../state.js';
|
||||
import {
|
||||
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 {
|
||||
clearTerminalComposition,
|
||||
|
|
@ -175,6 +184,7 @@ export async function renderTerminalView(
|
|||
root.replaceChildren();
|
||||
|
||||
const q = state.routeQuery ?? {};
|
||||
const targetServer = q.server ?? q.serverId;
|
||||
const [sessionsRes, serversRes] = await Promise.all([
|
||||
apiFetch<{ sessions: PtySessionInfo[] }>('/api/terminal/sessions'),
|
||||
apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
|
||||
|
|
@ -185,13 +195,13 @@ export async function renderTerminalView(
|
|||
|
||||
if (q.session && sessions.some((s) => s.sessionId === q.session)) {
|
||||
activeSessionId = q.session;
|
||||
} else if (q.server && q.cwd !== undefined && servers.some((s) => s.config.id === q.server)) {
|
||||
} else if (targetServer && q.cwd !== undefined && servers.some((s) => s.config.id === targetServer)) {
|
||||
// Open-Terminal-Here shortcut if not disabled by Safe Mode
|
||||
if (!state.safeMode) {
|
||||
try {
|
||||
const created = await apiFetch<{ session: PtySessionInfo }>('/api/terminal/sessions', {
|
||||
method: 'POST',
|
||||
body: { serverId: q.server, cwd: q.cwd, cols: 90, rows: 26 },
|
||||
body: { serverId: targetServer, cwd: q.cwd, cols: 90, rows: 26 },
|
||||
});
|
||||
sessions = [created.session, ...sessions];
|
||||
activeSessionId = created.session.sessionId;
|
||||
|
|
@ -213,7 +223,7 @@ export async function renderTerminalView(
|
|||
serverSel.append(
|
||||
el(
|
||||
'option',
|
||||
{ value: s.config.id, selected: q.server === s.config.id },
|
||||
{ value: s.config.id, selected: targetServer === s.config.id },
|
||||
`${s.config.name} (${s.config.id})`,
|
||||
),
|
||||
);
|
||||
|
|
@ -282,6 +292,15 @@ export async function renderTerminalView(
|
|||
el('div', { class: 'row' }, serverSel, cwdInput, openShellBtn),
|
||||
),
|
||||
tabsRow,
|
||||
...(state.safeMode
|
||||
? [
|
||||
el(
|
||||
'p',
|
||||
{ class: 'warn-text mono' },
|
||||
'[SAFE MODE] Read-only terminal view: keyboard input, reconnect, and session creation are locked.',
|
||||
),
|
||||
]
|
||||
: []),
|
||||
msgEl,
|
||||
),
|
||||
);
|
||||
|
|
@ -318,6 +337,40 @@ export async function renderTerminalView(
|
|||
},
|
||||
'Export ANSI',
|
||||
);
|
||||
const exportCastBtn = el(
|
||||
'a',
|
||||
{
|
||||
href: `/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/export?format=cast`,
|
||||
class: 'btn btn-sm',
|
||||
download: '',
|
||||
},
|
||||
'Export .cast',
|
||||
);
|
||||
const reconnectPtyBtn = el(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
class: 'btn btn-sm btn-primary mutating-action',
|
||||
hidden: !current.exited,
|
||||
},
|
||||
'Reconnect Session',
|
||||
);
|
||||
reconnectPtyBtn.addEventListener('click', async () => {
|
||||
reconnectPtyBtn.disabled = true;
|
||||
try {
|
||||
await apiFetch(`/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/reconnect`, {
|
||||
method: 'POST',
|
||||
body: {},
|
||||
});
|
||||
showToast('PTY session reconnected.', 'ok');
|
||||
await renderTerminalView(root, state, wsClient);
|
||||
} catch (err) {
|
||||
msgEl.className = 'form-msg err-text';
|
||||
msgEl.textContent = extractErrorMessage(err);
|
||||
showToast(extractErrorMessage(err), 'err');
|
||||
reconnectPtyBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
let term: Terminal | null = null;
|
||||
let fitAddon: FitAddon | null = null;
|
||||
|
|
@ -490,7 +543,7 @@ export async function renderTerminalView(
|
|||
{ class: 'mono muted' },
|
||||
`${current.title} | ${current.cols}x${current.rows} | opened ${fmtTime(current.createdAt)}`,
|
||||
),
|
||||
el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, ...(aiTermBtn ? [aiTermBtn] : []), exportPlainBtn, exportAnsiBtn, closeTabBtn),
|
||||
el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, ...(aiTermBtn ? [aiTermBtn] : []), reconnectPtyBtn, exportPlainBtn, exportAnsiBtn, exportCastBtn, closeTabBtn),
|
||||
),
|
||||
el('div', { class: 'term-shell' }, termContainer, touchBar),
|
||||
),
|
||||
|
|
@ -630,6 +683,14 @@ export async function renderTerminalView(
|
|||
typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => scheduleFit()) : null;
|
||||
ro?.observe(termContainer);
|
||||
|
||||
const themeObs =
|
||||
typeof MutationObserver !== 'undefined'
|
||||
? new MutationObserver(() => {
|
||||
if (term) term.options.theme = readXtermTheme();
|
||||
})
|
||||
: null;
|
||||
themeObs?.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
||||
|
||||
const unsubFrame = wsClient.onFrame((frame: ServerWsFrame) => {
|
||||
if (!term || !termContainer.isConnected) return;
|
||||
if (frame.type === 'pty:output' && frame.sessionId === current.sessionId) {
|
||||
|
|
@ -638,6 +699,8 @@ export async function renderTerminalView(
|
|||
}
|
||||
term.write(frame.data);
|
||||
} else if (frame.type === 'pty:exit' && frame.sessionId === current.sessionId) {
|
||||
current.exited = true;
|
||||
reconnectPtyBtn.hidden = false;
|
||||
term.writeln(`\r\n[Session exited with code ${String(frame.exitCode)}]`);
|
||||
} else if (frame.type === 'error' && frame.code === 'SAFE_MODE_ACTIVE') {
|
||||
msgEl.className = 'form-msg warn-text';
|
||||
|
|
@ -645,9 +708,17 @@ export async function renderTerminalView(
|
|||
}
|
||||
});
|
||||
|
||||
currentCleanup = () => {
|
||||
const unsubChannel = wsClient.subscribe([`pty:${current.sessionId}`]);
|
||||
|
||||
let cleaned = false;
|
||||
const disposeTerminalView = () => {
|
||||
if (cleaned) return;
|
||||
cleaned = true;
|
||||
currentCleanup = null;
|
||||
if (fitRaf !== null) window.cancelAnimationFrame(fitRaf);
|
||||
unsubChannel();
|
||||
unsubFrame();
|
||||
themeObs?.disconnect();
|
||||
ro?.disconnect();
|
||||
window.removeEventListener('resize', scheduleFit);
|
||||
window.visualViewport?.removeEventListener('resize', scheduleFit);
|
||||
|
|
@ -657,7 +728,9 @@ export async function renderTerminalView(
|
|||
term?.dispose();
|
||||
};
|
||||
|
||||
wsClient.subscribe([`pty:${current.sessionId}`]);
|
||||
currentCleanup = disposeTerminalView;
|
||||
registerViewCleanup(disposeTerminalView);
|
||||
|
||||
wsClient.send({
|
||||
type: 'pty:resize',
|
||||
sessionId: current.sessionId,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,13 @@
|
|||
import { apiFetch } from '../api.js';
|
||||
import { confirmDialog } from '../dialogs.js';
|
||||
import { el, extractErrorMessage, fmtTime, type ServerEntry } from '../state.js';
|
||||
import {
|
||||
el,
|
||||
extractErrorMessage,
|
||||
fmtTime,
|
||||
registerViewCleanup,
|
||||
type ServerEntry,
|
||||
} from '../state.js';
|
||||
import { showToast } from '../toast.js';
|
||||
|
||||
export interface TunnelViewEntry {
|
||||
key: string;
|
||||
|
|
@ -8,11 +15,15 @@ export interface TunnelViewEntry {
|
|||
tunnel: {
|
||||
id: string;
|
||||
name: string;
|
||||
mode: 'http-proxy' | 'local-tcp' | 'remote-tcp';
|
||||
mode: 'http-proxy' | 'local-tcp' | 'remote-tcp' | 'socks5';
|
||||
bindHost?: string;
|
||||
bindPort?: number;
|
||||
targetHost: string;
|
||||
targetPort: number;
|
||||
targetProtocol?: 'http' | 'https';
|
||||
tlsRejectUnauthorized?: boolean;
|
||||
tlsServerName?: string;
|
||||
ttlSec?: number;
|
||||
autoStart: boolean;
|
||||
};
|
||||
active: boolean;
|
||||
|
|
@ -20,6 +31,7 @@ export interface TunnelViewEntry {
|
|||
localBoundPort?: number;
|
||||
remoteBoundPort?: number;
|
||||
proxyPath?: string;
|
||||
expiresAt?: number;
|
||||
activeConnections: number;
|
||||
totalConnections: number;
|
||||
bytesIn: number;
|
||||
|
|
@ -28,6 +40,13 @@ export interface TunnelViewEntry {
|
|||
lastError?: string;
|
||||
}
|
||||
|
||||
function fmtRemainingSec(sec: number): string {
|
||||
const s = Math.max(0, Math.floor(sec));
|
||||
const m = Math.floor(s / 60);
|
||||
const rem = s % 60;
|
||||
return m > 0 ? `${m}m ${rem}s` : `${rem}s`;
|
||||
}
|
||||
|
||||
function fmtBytes(bytes: number): string {
|
||||
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
|
|
@ -90,24 +109,71 @@ export async function renderTunnelsPanel(
|
|||
),
|
||||
);
|
||||
const tbody = el('tbody');
|
||||
const countdownEls: Array<{ el: HTMLElement; expiresAt: number }> = [];
|
||||
for (const item of tunnels) {
|
||||
const bindInfo = item.proxyPath
|
||||
? el('a', { href: item.proxyPath, target: '_blank', rel: 'noopener', class: 'mono' }, item.proxyPath)
|
||||
: item.tunnel.mode === 'remote-tcp'
|
||||
? el(
|
||||
'span',
|
||||
{ class: 'mono' },
|
||||
item.active && item.remoteBoundPort
|
||||
? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}`
|
||||
: `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`,
|
||||
)
|
||||
: el(
|
||||
'span',
|
||||
{ class: 'mono' },
|
||||
item.active && item.localBoundPort
|
||||
? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}`
|
||||
: `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`,
|
||||
let bindInfo: HTMLElement;
|
||||
if (item.tunnel.mode === 'http-proxy' && item.active) {
|
||||
const launchBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm btn-primary' },
|
||||
'Open Isolated Proxy',
|
||||
);
|
||||
launchBtn.addEventListener('click', async () => {
|
||||
launchBtn.disabled = true;
|
||||
try {
|
||||
const ticketRes = await apiFetch<{
|
||||
launchUrl: string;
|
||||
mode: 'subdomain' | 'port' | 'same-origin';
|
||||
expiresInSec: number;
|
||||
}>(
|
||||
`/api/tunnels/${encodeURIComponent(item.serverId)}/${encodeURIComponent(item.tunnel.id)}/proxy-ticket`,
|
||||
{ method: 'POST', body: {} },
|
||||
);
|
||||
if (ticketRes.mode === 'same-origin') {
|
||||
showToast(
|
||||
'Launched via same-origin fallback proxy (isolated subdomain/port offers stronger cookie isolation).',
|
||||
'warn',
|
||||
);
|
||||
}
|
||||
window.open(ticketRes.launchUrl, '_blank', 'noopener,noreferrer');
|
||||
} catch (err) {
|
||||
const msg = extractErrorMessage(err);
|
||||
statusMsg.className = 'form-msg err-text';
|
||||
statusMsg.textContent = msg;
|
||||
showToast(msg, 'err');
|
||||
} finally {
|
||||
launchBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
bindInfo = el(
|
||||
'div',
|
||||
{ class: 'stack' },
|
||||
launchBtn,
|
||||
el(
|
||||
'span',
|
||||
{ class: 'mono muted' },
|
||||
`${item.tunnel.targetProtocol ?? 'http'}:// via ticket`,
|
||||
),
|
||||
);
|
||||
} else if (item.tunnel.mode === 'http-proxy') {
|
||||
bindInfo = el('span', { class: 'muted mono' }, 'proxy (inactive)');
|
||||
} else if (item.tunnel.mode === 'remote-tcp') {
|
||||
bindInfo = el(
|
||||
'span',
|
||||
{ class: 'mono' },
|
||||
item.active && item.remoteBoundPort
|
||||
? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}`
|
||||
: `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`,
|
||||
);
|
||||
} else {
|
||||
bindInfo = el(
|
||||
'span',
|
||||
{ class: 'mono' },
|
||||
item.active && item.localBoundPort
|
||||
? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}`
|
||||
: `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`,
|
||||
);
|
||||
}
|
||||
|
||||
const toggleBtn = el(
|
||||
'button',
|
||||
|
|
@ -154,6 +220,15 @@ export async function renderTunnelsPanel(
|
|||
}
|
||||
});
|
||||
|
||||
let ttlBadge: HTMLElement | string = '';
|
||||
if (item.active && item.expiresAt) {
|
||||
const b = el('div', { class: 'badge badge-warn' }, `TTL: ${fmtRemainingSec((item.expiresAt - Date.now()) / 1000)}`);
|
||||
countdownEls.push({ el: b, expiresAt: item.expiresAt });
|
||||
ttlBadge = b;
|
||||
} else if (item.tunnel.ttlSec) {
|
||||
ttlBadge = el('div', { class: 'muted' }, `TTL: ${item.tunnel.ttlSec}s`);
|
||||
}
|
||||
|
||||
tbody.append(
|
||||
el(
|
||||
'tr',
|
||||
|
|
@ -169,9 +244,16 @@ export async function renderTunnelsPanel(
|
|||
{},
|
||||
el('span', { class: `badge ${item.active ? 'badge-ok' : ''}` }, item.tunnel.mode.toUpperCase()),
|
||||
item.tunnel.autoStart ? el('div', { class: 'muted' }, 'auto-start') : '',
|
||||
ttlBadge,
|
||||
),
|
||||
el('td', {}, bindInfo),
|
||||
el('td', { class: 'mono' }, `${item.tunnel.targetHost}:${item.tunnel.targetPort}`),
|
||||
el(
|
||||
'td',
|
||||
{ class: 'mono' },
|
||||
item.tunnel.mode === 'socks5'
|
||||
? 'Dynamic SOCKS5'
|
||||
: `${item.tunnel.targetProtocol ? `${item.tunnel.targetProtocol}://` : ''}${item.tunnel.targetHost}:${item.tunnel.targetPort}`,
|
||||
),
|
||||
el(
|
||||
'td',
|
||||
{ class: 'mono' },
|
||||
|
|
@ -185,6 +267,17 @@ export async function renderTunnelsPanel(
|
|||
}
|
||||
tbl.append(tbody);
|
||||
listPanel.append(el('div', { class: 'table-wrap' }, tbl));
|
||||
|
||||
if (countdownEls.length > 0) {
|
||||
const ttlTimer = window.setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const row of countdownEls) {
|
||||
const remSec = Math.max(0, Math.floor((row.expiresAt - now) / 1000));
|
||||
row.el.textContent = `TTL: ${fmtRemainingSec(remSec)}`;
|
||||
}
|
||||
}, 1000);
|
||||
registerViewCleanup(() => window.clearInterval(ttlTimer));
|
||||
}
|
||||
}
|
||||
|
||||
// Add Tunnel Form
|
||||
|
|
@ -194,7 +287,7 @@ export async function renderTunnelsPanel(
|
|||
el(
|
||||
'p',
|
||||
{ class: 'muted' },
|
||||
'http-proxy binds strictly inside 127.0.0.1 and serves behind GCoordinator auth/CSRF/Safe-Mode at /proxy/<id>/.',
|
||||
'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.',
|
||||
),
|
||||
);
|
||||
|
||||
|
|
@ -213,31 +306,67 @@ export async function renderTunnelsPanel(
|
|||
const modeSel = el(
|
||||
'select',
|
||||
{ name: 'mode' },
|
||||
el('option', { value: 'http-proxy' }, 'http-proxy (Zero-Port Web Proxy /proxy/<id>/)'),
|
||||
el('option', { value: 'http-proxy' }, 'http-proxy (Authenticated Web Proxy)'),
|
||||
el('option', { value: 'local-tcp' }, 'local-tcp (Local Bind -> Target)'),
|
||||
el('option', { value: 'remote-tcp' }, 'remote-tcp (Remote Bind -R -> Hub/LAN)'),
|
||||
);
|
||||
const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true });
|
||||
el('option', { value: 'socks5' }, 'socks5 (Dynamic Local SOCKS5 Proxy)'),
|
||||
) as HTMLSelectElement;
|
||||
const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true }) as HTMLInputElement;
|
||||
const targetPortInput = el('input', {
|
||||
name: 'targetPort',
|
||||
type: 'number',
|
||||
min: 1,
|
||||
min: 0,
|
||||
max: 65535,
|
||||
value: '3000',
|
||||
required: true,
|
||||
});
|
||||
const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp modes)' });
|
||||
}) as HTMLInputElement;
|
||||
const protoSel = el(
|
||||
'select',
|
||||
{ name: 'targetProtocol' },
|
||||
el('option', { value: 'http' }, 'http'),
|
||||
el('option', { value: 'https' }, 'https'),
|
||||
) as HTMLSelectElement;
|
||||
const tlsVerifyChk = el('input', { type: 'checkbox', name: 'tlsRejectUnauthorized', checked: true }) as HTMLInputElement;
|
||||
const tlsSniInput = el('input', { name: 'tlsServerName', placeholder: 'optional TLS SNI host' }) as HTMLInputElement;
|
||||
const ttlSecInput = el('input', {
|
||||
name: 'ttlSec',
|
||||
type: 'number',
|
||||
min: 60,
|
||||
max: 86400,
|
||||
placeholder: 'optional auto-expire (60-86400s)',
|
||||
}) as HTMLInputElement;
|
||||
const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp/socks5)' }) as HTMLInputElement;
|
||||
const bindPortInput = el('input', {
|
||||
name: 'bindPort',
|
||||
type: 'number',
|
||||
min: 1,
|
||||
max: 65535,
|
||||
placeholder: 'auto (tcp modes)',
|
||||
});
|
||||
const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' });
|
||||
const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true });
|
||||
placeholder: 'auto (tcp/socks5)',
|
||||
}) as HTMLInputElement;
|
||||
const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' }) as HTMLInputElement;
|
||||
const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true }) as HTMLInputElement;
|
||||
const formMsg = el('p', { class: 'form-msg' });
|
||||
|
||||
const targetPortWrap = el('div', {}, el('label', {}, 'Target Port'), targetPortInput);
|
||||
const httpTlsWrap = el(
|
||||
'div',
|
||||
{ class: 'grid-3' },
|
||||
el('div', {}, el('label', {}, 'Upstream Protocol'), protoSel),
|
||||
el('div', {}, el('label', {}, 'TLS SNI ServerName (HTTPS)'), tlsSniInput),
|
||||
el('div', { style: 'padding-top:22px' }, el('label', { class: 'chk-row' }, tlsVerifyChk, 'Verify upstream TLS cert')),
|
||||
);
|
||||
|
||||
const syncModeFields = () => {
|
||||
const m = modeSel.value;
|
||||
targetPortWrap.hidden = m === 'socks5';
|
||||
targetPortInput.required = m !== 'socks5';
|
||||
if (m === 'socks5') targetPortInput.value = '0';
|
||||
else if (targetPortInput.value === '0') targetPortInput.value = '3000';
|
||||
httpTlsWrap.hidden = m !== 'http-proxy';
|
||||
};
|
||||
modeSel.addEventListener('change', syncModeFields);
|
||||
syncModeFields();
|
||||
|
||||
form.append(
|
||||
el(
|
||||
'div',
|
||||
|
|
@ -247,10 +376,12 @@ export async function renderTunnelsPanel(
|
|||
el('div', {}, el('label', {}, 'Display Name'), nameInput),
|
||||
el('div', {}, el('label', {}, 'Mode'), modeSel),
|
||||
el('div', {}, el('label', {}, 'Target Host'), targetHostInput),
|
||||
el('div', {}, el('label', {}, 'Target Port'), targetPortInput),
|
||||
el('div', {}, el('label', {}, 'Bind Host (TCP only)'), bindHostInput),
|
||||
el('div', {}, el('label', {}, 'Bind Port (TCP only)'), bindPortInput),
|
||||
targetPortWrap,
|
||||
el('div', {}, el('label', {}, 'Bind Host (TCP/SOCKS5)'), bindHostInput),
|
||||
el('div', {}, el('label', {}, 'Bind Port (TCP/SOCKS5)'), bindPortInput),
|
||||
el('div', {}, el('label', {}, 'TTL Seconds (Optional)'), ttlSecInput),
|
||||
),
|
||||
httpTlsWrap,
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row' },
|
||||
|
|
@ -271,10 +402,12 @@ export async function renderTunnelsPanel(
|
|||
return;
|
||||
}
|
||||
|
||||
const mode = modeSel.value as 'http-proxy' | 'local-tcp' | 'remote-tcp';
|
||||
const mode = modeSel.value as 'http-proxy' | 'local-tcp' | 'remote-tcp' | 'socks5';
|
||||
const bindHost = bindHostInput.value.trim() || undefined;
|
||||
const bindPortVal = bindPortInput.value.trim();
|
||||
const bindPort = bindPortVal ? Number(bindPortVal) : undefined;
|
||||
const ttlVal = ttlSecInput.value.trim();
|
||||
const ttlSec = ttlVal ? Number(ttlVal) : undefined;
|
||||
|
||||
try {
|
||||
const res = await apiFetch<{ startError?: string }>('/api/tunnels', {
|
||||
|
|
@ -286,7 +419,13 @@ export async function renderTunnelsPanel(
|
|||
name: nameInput.value.trim(),
|
||||
mode,
|
||||
targetHost: targetHostInput.value.trim() || '127.0.0.1',
|
||||
targetPort: Number(targetPortInput.value),
|
||||
targetPort: mode === 'socks5' ? 0 : Number(targetPortInput.value),
|
||||
targetProtocol: mode === 'http-proxy' ? protoSel.value : 'http',
|
||||
tlsRejectUnauthorized: mode === 'http-proxy' ? tlsVerifyChk.checked : true,
|
||||
...(mode === 'http-proxy' && tlsSniInput.value.trim()
|
||||
? { tlsServerName: tlsSniInput.value.trim() }
|
||||
: {}),
|
||||
...(ttlSec !== undefined ? { ttlSec } : {}),
|
||||
bindHost: mode === 'http-proxy' ? undefined : bindHost,
|
||||
bindPort: mode === 'http-proxy' ? undefined : bindPort,
|
||||
autoStart: autoStartChk.checked,
|
||||
|
|
@ -297,6 +436,8 @@ export async function renderTunnelsPanel(
|
|||
if (res.startError) {
|
||||
statusMsg.className = 'form-msg warn-text';
|
||||
statusMsg.textContent = `Saved, but start failed: ${res.startError}`;
|
||||
} else {
|
||||
showToast('Tunnel saved.', 'ok');
|
||||
}
|
||||
await renderTunnelsPanel(root, fixedServerId);
|
||||
} catch (err) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { apiFetch } from '../api.js';
|
||||
import { confirmDialog } from '../dialogs.js';
|
||||
import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js';
|
||||
import { showToast } from '../toast.js';
|
||||
|
||||
interface VaultCredMeta {
|
||||
id: string;
|
||||
|
|
@ -123,19 +124,44 @@ export async function renderVaultView(
|
|||
onPanicLock: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
root.replaceChildren();
|
||||
const vaultData = await apiFetch<{
|
||||
state: 'uninitialized' | 'locked' | 'unlocked';
|
||||
runtimeReady?: boolean;
|
||||
isPanicLocked?: boolean;
|
||||
credentials: VaultCredMeta[];
|
||||
}>('/api/vault/credentials');
|
||||
const runtimeReady = Boolean(vaultData.runtimeReady ?? vaultData.state === 'unlocked');
|
||||
state.vaultState = vaultData.state;
|
||||
const [vaultData, statusRes] = await Promise.all([
|
||||
apiFetch<{
|
||||
state: 'uninitialized' | 'locked' | 'unlocked';
|
||||
runtimeReady?: boolean;
|
||||
sealState?: string;
|
||||
isPanicLocked?: boolean;
|
||||
credentials: VaultCredMeta[];
|
||||
}>('/api/vault/credentials'),
|
||||
apiFetch<{
|
||||
state: 'uninitialized' | 'locked' | 'unlocked';
|
||||
runtimeReady: boolean;
|
||||
sealState: string;
|
||||
isPanicLocked: boolean;
|
||||
}>('/api/vault/status').catch(() => null),
|
||||
]);
|
||||
const runtimeReady = Boolean(statusRes?.runtimeReady ?? vaultData.runtimeReady ?? vaultData.state === 'unlocked');
|
||||
const sealState = statusRes?.sealState ?? vaultData.sealState ?? (runtimeReady ? 'unsealed' : 'sealed');
|
||||
state.vaultState = statusRes?.state ?? vaultData.state;
|
||||
state.vaultRuntimeReady = runtimeReady;
|
||||
if (vaultData.isPanicLocked !== undefined) {
|
||||
state.isPanicLocked = vaultData.isPanicLocked;
|
||||
if (statusRes?.isPanicLocked !== undefined || vaultData.isPanicLocked !== undefined) {
|
||||
state.isPanicLocked = Boolean(statusRes?.isPanicLocked ?? vaultData.isPanicLocked);
|
||||
}
|
||||
|
||||
const doSealVault = async () => {
|
||||
const ok = await confirmDialog(
|
||||
'dialog-confirm',
|
||||
'Seal the Vault now? This wipes the in-memory master key (collectors/SSH will pause until unsealed with the 32-byte key), without revoking your admin login session.',
|
||||
);
|
||||
if (!ok) return;
|
||||
try {
|
||||
await apiFetch('/api/vault/seal', { method: 'POST', body: {} });
|
||||
showToast('Vault sealed and runtime master key cleared from memory.', 'warn');
|
||||
await onStateChanged();
|
||||
} catch (err) {
|
||||
showToast(extractErrorMessage(err), 'err');
|
||||
}
|
||||
};
|
||||
|
||||
const statusPanel = el('section', { class: 'panel' });
|
||||
|
||||
if (vaultData.state === 'uninitialized') {
|
||||
|
|
@ -283,13 +309,23 @@ export async function renderVaultView(
|
|||
});
|
||||
|
||||
statusPanel.append(
|
||||
el('h1', {}, 'Encrypted Vault — [LOCKED]'),
|
||||
el('h1', {}, `Encrypted Vault — [${vaultData.state.toUpperCase()} / ${sealState.toUpperCase()}]`),
|
||||
el(
|
||||
'p',
|
||||
{ class: 'muted' },
|
||||
'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.',
|
||||
'Established secrets remain active in memory while unsealed (chmod 0600 data/vault.key or GCOORD_MASTER_KEY env). Unlock to edit, or Seal to zeroize keys from RAM without dropping sessions.',
|
||||
),
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row' },
|
||||
unlockBtn,
|
||||
(() => {
|
||||
const sealBtn = el('button', { type: 'button', class: 'btn mutating-action' }, 'Seal Vault');
|
||||
sealBtn.addEventListener('click', () => void doSealVault());
|
||||
return sealBtn;
|
||||
})(),
|
||||
panicBtn,
|
||||
),
|
||||
el('div', { class: 'row' }, unlockBtn, panicBtn),
|
||||
lockMsg,
|
||||
credTableWrap,
|
||||
revealBox,
|
||||
|
|
@ -308,9 +344,15 @@ export async function renderVaultView(
|
|||
await apiFetch('/api/vault/lock', { method: 'POST' });
|
||||
await onStateChanged();
|
||||
});
|
||||
const sealUnlockedBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm btn-danger mutating-action' },
|
||||
'Seal Vault',
|
||||
);
|
||||
sealUnlockedBtn.addEventListener('click', () => void doSealVault());
|
||||
|
||||
statusPanel.append(
|
||||
el('div', { class: 'row-between' }, el('h1', {}, 'Encrypted Vault — [UNLOCKED]'), lockBtn),
|
||||
el('div', { class: 'row-between' }, el('h1', {}, `Encrypted Vault — [UNLOCKED / ${sealState.toUpperCase()}]`), el('div', { class: 'row' }, lockBtn, sealUnlockedBtn)),
|
||||
credTableWrap,
|
||||
revealBox,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -7,16 +7,18 @@ import {
|
|||
extractErrorMessage,
|
||||
fmtTime,
|
||||
isAiEnabled,
|
||||
registerViewCleanup,
|
||||
type ClientState,
|
||||
type ServerEntry,
|
||||
} from '../state.js';
|
||||
import { showToast } from '../toast.js';
|
||||
import type { MultiplexWsClient } from '../ws-client.js';
|
||||
|
||||
type WfSubTab = 'workflows' | 'broadcast' | 'snippets';
|
||||
|
||||
interface WorkflowInputDef {
|
||||
name: string;
|
||||
type: 'string' | 'number' | 'boolean' | 'server' | 'select';
|
||||
type: 'string' | 'number' | 'boolean' | 'server' | 'select' | 'secret';
|
||||
label?: string;
|
||||
description?: string;
|
||||
required?: boolean;
|
||||
|
|
@ -26,7 +28,7 @@ interface WorkflowInputDef {
|
|||
|
||||
interface WorkflowStepDef {
|
||||
id: string;
|
||||
type: 'exec' | 'read-file' | 'system-action' | 'transfer';
|
||||
type: 'exec' | 'read-file' | 'system-action' | 'transfer' | 'http' | 'notify';
|
||||
dependsOn?: Array<string | { stepId: string; on: 'success' | 'failure' | 'always' }>;
|
||||
target?: { serverId?: string; tags?: string[]; all?: boolean };
|
||||
command?: string;
|
||||
|
|
@ -39,7 +41,19 @@ interface WorkflowStepDef {
|
|||
mode?: 'hub-relayed' | 'direct';
|
||||
source?: { serverId: string; path: string };
|
||||
destination?: { serverId: string; path: string };
|
||||
url?: string;
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
||||
body?: string;
|
||||
secretRef?: string;
|
||||
expectedStatus?: number;
|
||||
channelIds?: string[];
|
||||
title?: string;
|
||||
message?: string;
|
||||
severity?: 'warn' | 'critical';
|
||||
timeoutSec?: number;
|
||||
retries?: number;
|
||||
retryBackoffSec?: number;
|
||||
when?: string;
|
||||
sudo?: boolean;
|
||||
captureAs?: string;
|
||||
onFailure?: string | { action: string; channelId?: string; workflowId?: string };
|
||||
|
|
@ -108,6 +122,18 @@ let activeSubTab: WfSubTab = 'workflows';
|
|||
let selectedRunDetailId: string | null = null;
|
||||
let broadcastPresetSnippetId: string | null = null;
|
||||
let unsubWfWs: (() => void) | null = null;
|
||||
let unsubWfChannel: (() => void) | null = null;
|
||||
|
||||
function releaseWfWs(): void {
|
||||
if (unsubWfChannel) {
|
||||
unsubWfChannel();
|
||||
unsubWfChannel = null;
|
||||
}
|
||||
if (unsubWfWs) {
|
||||
unsubWfWs();
|
||||
unsubWfWs = null;
|
||||
}
|
||||
}
|
||||
|
||||
function statusBadgeClass(status: string): string {
|
||||
if (status === 'succeeded' || status === 'ok') return 'badge badge-ok';
|
||||
|
|
@ -251,10 +277,10 @@ async function promptWorkflowInputs(
|
|||
ctrl = el('input', { type: 'checkbox', checked: Boolean(def.default) });
|
||||
} else {
|
||||
ctrl = el('input', {
|
||||
type: def.type === 'number' ? 'number' : 'text',
|
||||
value: def.default !== undefined ? String(def.default) : '',
|
||||
type: def.type === 'secret' ? 'password' : def.type === 'number' ? 'number' : 'text',
|
||||
value: def.type === 'secret' ? '' : def.default !== undefined ? String(def.default) : '',
|
||||
required: def.required,
|
||||
placeholder: def.description ?? def.name,
|
||||
placeholder: def.type === 'secret' ? '(secret input — masked in logs)' : (def.description ?? def.name),
|
||||
});
|
||||
}
|
||||
fields.set(def.name, ctrl);
|
||||
|
|
@ -419,7 +445,7 @@ function openWorkflowEditorDialog(
|
|||
const sType = el(
|
||||
'select',
|
||||
{ class: 'input-sm' },
|
||||
...(['exec', 'read-file', 'system-action', 'transfer'] as const).map((t) =>
|
||||
...(['exec', 'read-file', 'system-action', 'transfer', 'http', 'notify'] as const).map((t) =>
|
||||
el('option', { value: t, selected: step.type === t }, t),
|
||||
),
|
||||
);
|
||||
|
|
@ -429,6 +455,14 @@ function openWorkflowEditorDialog(
|
|||
step.mode = 'hub-relayed';
|
||||
step.source = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file' };
|
||||
step.destination = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file.bak' };
|
||||
} else if (step.type === 'http' && !step.url) {
|
||||
step.method = 'POST';
|
||||
step.url = 'https://example.invalid/webhook';
|
||||
} else if (step.type === 'notify' && !step.channelIds) {
|
||||
step.channelIds = ['ops-webhook'];
|
||||
step.title = 'Workflow Notification';
|
||||
step.message = 'Step reached';
|
||||
step.severity = 'warn';
|
||||
}
|
||||
redrawSteps();
|
||||
});
|
||||
|
|
@ -462,6 +496,26 @@ function openWorkflowEditorDialog(
|
|||
redrawSteps();
|
||||
});
|
||||
|
||||
const sRetries = el('input', {
|
||||
class: 'input-sm',
|
||||
type: 'number',
|
||||
min: 0,
|
||||
max: 5,
|
||||
value: String(step.retries ?? 0),
|
||||
placeholder: 'retries (0-5)',
|
||||
}) as HTMLInputElement;
|
||||
sRetries.addEventListener('input', () => {
|
||||
step.retries = Number(sRetries.value || 0);
|
||||
});
|
||||
const sWhen = el('input', {
|
||||
class: 'input-sm',
|
||||
value: step.when ?? '',
|
||||
placeholder: 'when expr (e.g. inputs.env == "prod")',
|
||||
}) as HTMLInputElement;
|
||||
sWhen.addEventListener('input', () => {
|
||||
step.when = sWhen.value.trim() || undefined;
|
||||
});
|
||||
|
||||
card.append(
|
||||
el(
|
||||
'div',
|
||||
|
|
@ -469,10 +523,57 @@ function openWorkflowEditorDialog(
|
|||
el('strong', {}, `Step #${idx + 1}`),
|
||||
el('div', { class: 'row' }, sId, sType, rmBtn),
|
||||
),
|
||||
sDeps,
|
||||
el('div', { class: 'grid-3', style: 'margin-top:6px' }, sDeps, sRetries, sWhen),
|
||||
);
|
||||
|
||||
if (step.type === 'transfer') {
|
||||
if (step.type === 'http') {
|
||||
const mSel = el(
|
||||
'select',
|
||||
{ class: 'input-sm' },
|
||||
...(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const).map((m) =>
|
||||
el('option', { value: m, selected: (step.method ?? 'POST') === m }, m),
|
||||
),
|
||||
) as HTMLSelectElement;
|
||||
const uIn = el('input', { class: 'input-sm', value: step.url ?? '', placeholder: 'https://...' }) as HTMLInputElement;
|
||||
const secIn = el('input', { class: 'input-sm', value: step.secretRef ?? '', placeholder: 'secretRef (api-token/webhook-secret)' }) as HTMLInputElement;
|
||||
const expIn = el('input', { class: 'input-sm', type: 'number', value: step.expectedStatus ? String(step.expectedStatus) : '', placeholder: 'expectedStatus' }) as HTMLInputElement;
|
||||
const bArea = el('textarea', { rows: 2, placeholder: 'Optional HTTP JSON body' }, step.body ?? '') as HTMLTextAreaElement;
|
||||
bArea.value = step.body ?? '';
|
||||
const syncHttp = () => {
|
||||
step.method = mSel.value as WorkflowStepDef['method'];
|
||||
step.url = uIn.value.trim();
|
||||
step.secretRef = secIn.value.trim() || undefined;
|
||||
step.expectedStatus = expIn.value.trim() ? Number(expIn.value) : undefined;
|
||||
step.body = bArea.value || undefined;
|
||||
};
|
||||
[mSel, uIn, secIn, expIn, bArea].forEach((n) => n.addEventListener('input', syncHttp));
|
||||
card.append(
|
||||
el('div', { class: 'grid-2', style: 'margin-top:6px' }, mSel, uIn, secIn, expIn),
|
||||
bArea,
|
||||
);
|
||||
} else if (step.type === 'notify') {
|
||||
const chIn = el('input', { class: 'input-sm', value: (step.channelIds ?? []).join(', '), placeholder: 'channelIds (comma-sep)' }) as HTMLInputElement;
|
||||
const tIn = el('input', { class: 'input-sm', value: step.title ?? '', placeholder: 'Notification title' }) as HTMLInputElement;
|
||||
const sevSel = el(
|
||||
'select',
|
||||
{ class: 'input-sm' },
|
||||
el('option', { value: 'warn', selected: (step.severity ?? 'warn') === 'warn' }, 'warn'),
|
||||
el('option', { value: 'critical', selected: step.severity === 'critical' }, 'critical'),
|
||||
) as HTMLSelectElement;
|
||||
const mArea = el('textarea', { rows: 2, placeholder: 'Notification message' }, step.message ?? '') as HTMLTextAreaElement;
|
||||
mArea.value = step.message ?? '';
|
||||
const syncNotify = () => {
|
||||
step.channelIds = chIn.value.split(',').map((s) => s.trim()).filter(Boolean);
|
||||
step.title = tIn.value;
|
||||
step.severity = sevSel.value as 'warn' | 'critical';
|
||||
step.message = mArea.value;
|
||||
};
|
||||
[chIn, tIn, sevSel, mArea].forEach((n) => n.addEventListener('input', syncNotify));
|
||||
card.append(
|
||||
el('div', { class: 'grid-3', style: 'margin-top:6px' }, chIn, tIn, sevSel),
|
||||
mArea,
|
||||
);
|
||||
} else if (step.type === 'transfer') {
|
||||
const modeSel = el(
|
||||
'select',
|
||||
{ class: 'input-sm' },
|
||||
|
|
@ -675,11 +776,12 @@ export async function renderWorkflowsView(
|
|||
state: ClientState,
|
||||
wsClient: MultiplexWsClient,
|
||||
): Promise<void> {
|
||||
if (unsubWfWs) {
|
||||
unsubWfWs();
|
||||
unsubWfWs = null;
|
||||
}
|
||||
wsClient.subscribe(['workflows']);
|
||||
releaseWfWs();
|
||||
const unsubBase = wsClient.subscribe(['workflows']);
|
||||
registerViewCleanup(() => {
|
||||
releaseWfWs();
|
||||
unsubBase();
|
||||
});
|
||||
root.replaceChildren();
|
||||
|
||||
const tabBar = el(
|
||||
|
|
@ -761,17 +863,18 @@ export async function renderWorkflowsView(
|
|||
const watchRunStream = (runId: string, wfId: string) => {
|
||||
streamPanel.hidden = false;
|
||||
const logPre = el('pre', { class: 'stream-log mono' }, `Subscribed to live run ${runId} (${wfId})...\n`);
|
||||
const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Cancel Run');
|
||||
const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel Run');
|
||||
cancelBtn.addEventListener('click', async () => {
|
||||
cancelBtn.disabled = true;
|
||||
await apiFetch(`/api/workflows/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' });
|
||||
showToast(`Cancellation requested for run ${runId}.`, 'warn');
|
||||
});
|
||||
streamPanel.replaceChildren(
|
||||
el('div', { class: 'row-between' }, el('strong', {}, `Live Run Stream: ${wfId} (${runId})`), cancelBtn),
|
||||
logPre,
|
||||
);
|
||||
|
||||
if (unsubWfWs) unsubWfWs();
|
||||
releaseWfWs();
|
||||
unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => {
|
||||
if (frame.type === 'stream:chunk' && frame.jobId === `wf:${runId}`) {
|
||||
if (frame.stream !== 'meta') {
|
||||
|
|
@ -791,7 +894,7 @@ export async function renderWorkflowsView(
|
|||
}
|
||||
}
|
||||
});
|
||||
wsClient.subscribe([`stream:wf:${runId}`]);
|
||||
unsubWfChannel = wsClient.subscribe([`stream:wf:${runId}`]);
|
||||
};
|
||||
|
||||
const loadRunDetail = async (runId: string) => {
|
||||
|
|
@ -802,6 +905,29 @@ export async function renderWorkflowsView(
|
|||
}>(`/api/workflows/runs/${encodeURIComponent(runId)}`);
|
||||
detailPanel.hidden = false;
|
||||
renderStructuredOutput(detailPanel, res.workflow, res.run, res.stepLogs);
|
||||
const uniqueSteps = [...new Set(res.stepLogs.map((l) => l.stepId))];
|
||||
if (uniqueSteps.length > 0) {
|
||||
const lazyPre = el('pre', { class: 'stream-log mono', hidden: true });
|
||||
const stepRow = el('div', { class: 'row', style: 'margin-top:8px' }, el('span', { class: 'muted' }, 'Inspect step:'));
|
||||
for (const sid of uniqueSteps) {
|
||||
const b = el('button', { type: 'button', class: 'btn btn-sm' }, sid);
|
||||
b.addEventListener('click', async () => {
|
||||
try {
|
||||
const sLogs = await apiFetch<{ logs: WorkflowStepLogItem[] }>(
|
||||
`/api/workflows/runs/${encodeURIComponent(runId)}/steps/${encodeURIComponent(sid)}/logs`,
|
||||
);
|
||||
lazyPre.hidden = false;
|
||||
lazyPre.textContent = sLogs.logs
|
||||
.map((l) => `[${l.serverId}] exit=${String(l.exitCode)}\n${l.stdout}${l.stderr ? `\nSTDERR:\n${l.stderr}` : ''}`)
|
||||
.join('\n---\n') || '(empty)';
|
||||
} catch (err) {
|
||||
showToast(extractErrorMessage(err), 'err');
|
||||
}
|
||||
});
|
||||
stepRow.append(b);
|
||||
}
|
||||
detailPanel.append(stepRow, lazyPre);
|
||||
}
|
||||
if (isAiEnabled(state)) {
|
||||
const diagBtn = el(
|
||||
'button',
|
||||
|
|
@ -944,9 +1070,10 @@ export async function renderWorkflowsView(
|
|||
});
|
||||
const actRow = el('div', { class: 'row' }, inspectBtn);
|
||||
if (r.status === 'running' || r.status === 'queued') {
|
||||
const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Cancel');
|
||||
const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel');
|
||||
cancelBtn.addEventListener('click', async () => {
|
||||
await apiFetch(`/api/workflows/runs/${encodeURIComponent(r.runId)}/cancel`, { method: 'POST' });
|
||||
showToast(`Cancelled run ${r.runId}.`, 'warn');
|
||||
await renderWorkflowsView(root, state, wsClient);
|
||||
});
|
||||
actRow.append(cancelBtn);
|
||||
|
|
@ -1034,7 +1161,7 @@ export async function renderWorkflowsView(
|
|||
|
||||
const msgEl = el('p', { class: 'form-msg' });
|
||||
const cardsGrid = el('div', { class: 'grid-2' });
|
||||
const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action', hidden: true }, 'Cancel Broadcast');
|
||||
const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger', hidden: true }, 'Cancel Broadcast');
|
||||
let activeJobId: string | null = null;
|
||||
cancelBtn.addEventListener('click', async () => {
|
||||
if (!activeJobId) return;
|
||||
|
|
@ -1099,7 +1226,7 @@ export async function renderWorkflowsView(
|
|||
);
|
||||
}
|
||||
|
||||
if (unsubWfWs) unsubWfWs();
|
||||
releaseWfWs();
|
||||
unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => {
|
||||
if (frame.type !== 'stream:chunk' || frame.jobId !== activeJobId || frame.stream !== 'meta') return;
|
||||
try {
|
||||
|
|
@ -1134,20 +1261,77 @@ export async function renderWorkflowsView(
|
|||
cancelBtn.hidden = true;
|
||||
msgEl.className = 'form-msg ok-text';
|
||||
msgEl.textContent = `Broadcast finished: ${String(m.okCount)}/${String(m.total)} succeeded.`;
|
||||
void loadBroadcastHistory();
|
||||
}
|
||||
} catch {
|
||||
// Ignore meta parse error
|
||||
}
|
||||
});
|
||||
wsClient.subscribe([`stream:${activeJobId}`]);
|
||||
unsubWfChannel = wsClient.subscribe([`stream:${activeJobId}`]);
|
||||
} catch (err) {
|
||||
msgEl.className = 'form-msg err-text';
|
||||
msgEl.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
|
||||
const histPanel = el('section', { class: 'panel panel-region' });
|
||||
const loadBroadcastHistory = async () => {
|
||||
histPanel.replaceChildren(el('h2', {}, 'Broadcast History'));
|
||||
try {
|
||||
const hRes = await apiFetch<{
|
||||
jobs: Array<{
|
||||
jobId: string;
|
||||
snippetId?: string;
|
||||
command: string;
|
||||
createdAt: number;
|
||||
finishedAt: number | null;
|
||||
done: boolean;
|
||||
cancelled: boolean;
|
||||
targets: Array<{ status: string }>;
|
||||
}>;
|
||||
}>('/api/workflows/broadcast/history?limit=25');
|
||||
if (hRes.jobs.length === 0) {
|
||||
histPanel.append(el('p', { class: 'muted' }, 'No past fleet broadcasts recorded yet.'));
|
||||
return;
|
||||
}
|
||||
const tbl = el('table');
|
||||
tbl.append(
|
||||
el('thead', {}, el('tr', {}, el('th', {}, 'Job ID'), el('th', {}, 'Command / Snippet'), el('th', {}, 'Result'), el('th', {}, 'Started'), el('th', {}, 'Export'))),
|
||||
);
|
||||
const tbody = el('tbody');
|
||||
for (const j of hRes.jobs) {
|
||||
const okCount = j.targets.filter((t) => t.status === 'ok').length;
|
||||
tbody.append(
|
||||
el(
|
||||
'tr',
|
||||
{},
|
||||
el('td', { class: 'mono' }, j.jobId),
|
||||
el('td', { class: 'mono' }, j.snippetId ? `[${j.snippetId}] ${j.command.slice(0, 50)}` : j.command.slice(0, 60)),
|
||||
el('td', { class: 'mono' }, `${okCount}/${j.targets.length} ok${j.cancelled ? ' (cancelled)' : ''}`),
|
||||
el('td', { class: 'mono' }, fmtTime(j.createdAt)),
|
||||
el(
|
||||
'td',
|
||||
{},
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row' },
|
||||
el('a', { href: `/api/workflows/broadcast/${encodeURIComponent(j.jobId)}/export?format=json`, class: 'btn btn-sm', download: '' }, 'JSON'),
|
||||
el('a', { href: `/api/workflows/broadcast/${encodeURIComponent(j.jobId)}/export?format=csv`, class: 'btn btn-sm', download: '' }, 'CSV'),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
tbl.append(tbody);
|
||||
histPanel.append(el('div', { class: 'table-wrap' }, tbl));
|
||||
} catch (err) {
|
||||
histPanel.append(el('p', { class: 'err-text' }, extractErrorMessage(err)));
|
||||
}
|
||||
};
|
||||
|
||||
panel.append(el('h2', {}, 'Ad-Hoc Fleet Broadcast'), form);
|
||||
root.append(panel, cardsGrid);
|
||||
root.append(panel, cardsGrid, histPanel);
|
||||
void loadBroadcastHistory();
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,16 +2,24 @@ import type { ClientWsFrame, ServerWsFrame } from '../../shared/ws-protocol.js';
|
|||
|
||||
export type WsConnectionStatus = 'online' | 'reconnecting' | 'offline';
|
||||
|
||||
const CORE_CHANNELS = ['config', 'alerts', 'metrics', 'workflows'] as const;
|
||||
|
||||
export class MultiplexWsClient {
|
||||
private ws: WebSocket | null = null;
|
||||
private reconnectAttempt = 0;
|
||||
private reconnectTimer: number | null = null;
|
||||
private pingTimer: number | null = null;
|
||||
private shouldRun = false;
|
||||
private channels = new Set<string>(['config', 'alerts', 'metrics', 'workflows']);
|
||||
private readonly channelRefs = new Map<string, number>();
|
||||
private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>();
|
||||
private readonly statusListeners = new Set<(status: WsConnectionStatus) => void>();
|
||||
|
||||
constructor() {
|
||||
for (const ch of CORE_CHANNELS) {
|
||||
this.channelRefs.set(ch, 1);
|
||||
}
|
||||
}
|
||||
|
||||
onFrame(listener: (frame: ServerWsFrame) => void): () => void {
|
||||
this.frameListeners.add(listener);
|
||||
return () => this.frameListeners.delete(listener);
|
||||
|
|
@ -37,6 +45,11 @@ export class MultiplexWsClient {
|
|||
window.clearInterval(this.pingTimer);
|
||||
this.pingTimer = null;
|
||||
}
|
||||
for (const ch of [...this.channelRefs.keys()]) {
|
||||
if (!(CORE_CHANNELS as readonly string[]).includes(ch)) {
|
||||
this.channelRefs.delete(ch);
|
||||
}
|
||||
}
|
||||
if (this.ws) {
|
||||
this.ws.close(1000, 'Client disconnect');
|
||||
this.ws = null;
|
||||
|
|
@ -50,14 +63,54 @@ export class MultiplexWsClient {
|
|||
}
|
||||
}
|
||||
|
||||
subscribe(channels: string[]): void {
|
||||
for (const ch of channels) this.channels.add(ch);
|
||||
this.send({ type: 'sub', channels });
|
||||
/**
|
||||
* Reference-counted channel subscription. Returns a cleanup callback that
|
||||
* releases this caller's references and sends `{ type: 'unsub' }` once refcount hits 0.
|
||||
*/
|
||||
subscribe(channels: string[]): () => void {
|
||||
const addedNow: string[] = [];
|
||||
const tracked: string[] = [];
|
||||
for (const ch of channels) {
|
||||
if (!ch) continue;
|
||||
tracked.push(ch);
|
||||
const prev = this.channelRefs.get(ch) ?? 0;
|
||||
this.channelRefs.set(ch, prev + 1);
|
||||
if (prev === 0) addedNow.push(ch);
|
||||
}
|
||||
if (addedNow.length > 0) {
|
||||
this.send({ type: 'sub', channels: addedNow });
|
||||
}
|
||||
let disposed = false;
|
||||
return () => {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
this.unsubscribe(tracked);
|
||||
};
|
||||
}
|
||||
|
||||
unsubscribe(channels: string[]): void {
|
||||
const dropped: string[] = [];
|
||||
for (const ch of channels) {
|
||||
if ((CORE_CHANNELS as readonly string[]).includes(ch)) continue;
|
||||
const cur = this.channelRefs.get(ch) ?? 0;
|
||||
if (cur <= 1) {
|
||||
this.channelRefs.delete(ch);
|
||||
if (cur === 1) dropped.push(ch);
|
||||
} else {
|
||||
this.channelRefs.set(ch, cur - 1);
|
||||
}
|
||||
}
|
||||
if (dropped.length > 0) {
|
||||
this.send({ type: 'unsub', channels: dropped });
|
||||
}
|
||||
}
|
||||
|
||||
private openSocket(): void {
|
||||
if (!this.shouldRun) return;
|
||||
if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
|
||||
if (
|
||||
this.ws &&
|
||||
(this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -68,8 +121,9 @@ export class MultiplexWsClient {
|
|||
socket.addEventListener('open', () => {
|
||||
this.reconnectAttempt = 0;
|
||||
this.emitStatus('online');
|
||||
if (this.channels.size > 0) {
|
||||
this.send({ type: 'sub', channels: [...this.channels] });
|
||||
const allActive = [...this.channelRefs.keys()];
|
||||
if (allActive.length > 0) {
|
||||
this.send({ type: 'sub', channels: allActive });
|
||||
}
|
||||
if (this.pingTimer !== null) window.clearInterval(this.pingTimer);
|
||||
this.pingTimer = window.setInterval(() => {
|
||||
|
|
|
|||
|
|
@ -13,7 +13,9 @@ import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js';
|
|||
import type { WsHub } from '../api/ws-hub.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import { computeLineDiff, type DiffLine } from '../config/diff.js';
|
||||
import type { RuntimeLimits } from '../config/runtime-limits.js';
|
||||
import type { AuditService } from '../security/audit.js';
|
||||
import { fetchWithEgressGuard } from '../security/egress-guard.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
import {
|
||||
|
|
@ -31,6 +33,14 @@ export class AiDisabledError extends Error {
|
|||
}
|
||||
}
|
||||
|
||||
export class AiOverloadError extends Error {
|
||||
readonly code = 'AI_CONCURRENCY_LIMIT';
|
||||
readonly status = 503;
|
||||
constructor(limit: number) {
|
||||
super(`Too many concurrent AI streams (limit: ${limit}). Retry shortly.`);
|
||||
}
|
||||
}
|
||||
|
||||
export interface ChatMessageInput {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
|
|
@ -64,6 +74,7 @@ export class AiService {
|
|||
private readonly sshPool: SSHPool,
|
||||
private readonly wsHub: WsHub,
|
||||
private readonly auditService: AuditService,
|
||||
private readonly getRuntimeLimits?: () => RuntimeLimits,
|
||||
) {}
|
||||
|
||||
getReplayFrames(chatId: string): ServerWsFrame[] {
|
||||
|
|
@ -93,11 +104,8 @@ export class AiService {
|
|||
private resolveBearerToken(secretRef?: string): string | undefined {
|
||||
if (!secretRef || !this.vaultService.isRuntimeReady) return undefined;
|
||||
const cred = this.vaultService.getRuntimeSecret(secretRef);
|
||||
if (!cred) return undefined;
|
||||
if (cred.type === 'api-token') return cred.token;
|
||||
if (cred.type === 'webhook-secret') return cred.secret;
|
||||
if (cred.type === 'ssh-password' || cred.type === 'sudo-password') return cred.password;
|
||||
return undefined;
|
||||
if (!cred || cred.type !== 'api-token') return undefined;
|
||||
return cred.token;
|
||||
}
|
||||
|
||||
previewContext(opts: {
|
||||
|
|
@ -168,6 +176,12 @@ export class AiService {
|
|||
throw new AiDisabledError();
|
||||
}
|
||||
|
||||
const activeStreams = [...this.chats.values()].filter((c) => !c.done).length;
|
||||
const maxStreams = Math.max(1, this.getRuntimeLimits?.().maxConcurrentAiStreams ?? 2);
|
||||
if (activeStreams >= maxStreams) {
|
||||
throw new AiOverloadError(maxStreams);
|
||||
}
|
||||
|
||||
const knownSecrets = collectVaultSecretStrings(this.vaultService);
|
||||
const guide = buildSurfaceGuideAndInventory(
|
||||
opts.surface,
|
||||
|
|
@ -289,19 +303,26 @@ export class AiService {
|
|||
headers.Authorization = `Bearer ${bearerToken}`;
|
||||
}
|
||||
|
||||
const res = await fetch(endpointUrl, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ model, stream: true, messages }),
|
||||
signal: chat.abortController.signal,
|
||||
});
|
||||
const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs;
|
||||
const aiCfg = this.configManager.getSettings().ai;
|
||||
const res = await fetchWithEgressGuard(
|
||||
endpointUrl,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ model, stream: true, messages, max_tokens: aiCfg.maxTokens }),
|
||||
signal: chat.abortController.signal,
|
||||
},
|
||||
{ allowedCidrs, timeoutMs: (aiCfg.timeoutSec ?? 90) * 1000 },
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const errBody = await res.text().catch(() => '');
|
||||
const cleanErr = bearerToken ? errBody.split(bearerToken).join('[REDACTED]') : errBody;
|
||||
this.emitDelta(chat, {
|
||||
chunk: '',
|
||||
done: true,
|
||||
error: `LLM endpoint HTTP ${res.status}${errBody ? `: ${errBody.slice(0, 240)}` : ''}`,
|
||||
error: `LLM endpoint HTTP ${res.status}${cleanErr ? `: ${cleanErr.slice(0, 240)}` : ''}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
|
@ -323,12 +344,22 @@ export class AiService {
|
|||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buf = '';
|
||||
const MAX_SSE_LINE_BUF = 256 * 1024;
|
||||
let doneSent = false;
|
||||
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
if (buf.length > MAX_SSE_LINE_BUF) {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
this.emitDelta(chat, {
|
||||
chunk: '',
|
||||
done: true,
|
||||
error: 'AI SSE line buffer exceeded 256 KiB limit',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let nlIdx: number;
|
||||
while ((nlIdx = buf.indexOf('\n')) >= 0) {
|
||||
|
|
@ -371,11 +402,11 @@ export class AiService {
|
|||
this.emitDelta(chat, { chunk: '', done: true });
|
||||
}
|
||||
} catch (err) {
|
||||
const rawErr = err instanceof Error ? err.message : String(err);
|
||||
const safeErr = bearerToken ? rawErr.split(bearerToken).join('[REDACTED]') : rawErr;
|
||||
const msg = chat.abortController.signal.aborted
|
||||
? 'Generation cancelled'
|
||||
: err instanceof Error
|
||||
? err.message
|
||||
: String(err);
|
||||
: safeErr;
|
||||
this.emitDelta(chat, {
|
||||
chunk: '',
|
||||
done: true,
|
||||
|
|
@ -413,24 +444,29 @@ export class AiService {
|
|||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (bearer) headers.Authorization = `Bearer ${bearer}`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
stream: false,
|
||||
max_tokens: 16,
|
||||
messages: [{ role: 'user', content: 'Reply with OK' }],
|
||||
}),
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs;
|
||||
const res = await fetchWithEgressGuard(
|
||||
url,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
stream: false,
|
||||
max_tokens: 16,
|
||||
messages: [{ role: 'user', content: 'Reply with OK' }],
|
||||
}),
|
||||
},
|
||||
{ allowedCidrs, timeoutMs: 10_000 },
|
||||
);
|
||||
const latencyMs = Date.now() - started;
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
const cleanText = bearer ? text.split(bearer).join('[REDACTED]') : text;
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs,
|
||||
error: `HTTP ${res.status}${text ? `: ${text.slice(0, 180)}` : ''}`,
|
||||
error: `HTTP ${res.status}${cleanText ? `: ${cleanText.slice(0, 180)}` : ''}`,
|
||||
};
|
||||
}
|
||||
const data = (await res.json().catch(() => ({}))) as {
|
||||
|
|
@ -440,10 +476,11 @@ export class AiService {
|
|||
data.choices?.[0]?.message?.content ?? data.choices?.[0]?.text ?? 'Connected';
|
||||
return { ok: true, latencyMs, replyPreview: String(preview).trim().slice(0, 120) };
|
||||
} catch (err) {
|
||||
const rawErr = err instanceof Error ? err.message : String(err);
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: Date.now() - started,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
error: bearer ? rawErr.split(bearer).join('[REDACTED]') : rawErr,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -486,9 +523,29 @@ 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) =>
|
||||
opts.targetId && obj && typeof obj === 'object' && !Array.isArray(obj)
|
||||
? { ...(obj as Record<string, unknown>), id: (obj as Record<string, unknown>).id ?? opts.targetId }
|
||||
? { ...(obj as Record<string, unknown>), id: opts.targetId }
|
||||
: obj;
|
||||
|
||||
let targetPath: string;
|
||||
|
|
|
|||
|
|
@ -26,7 +26,8 @@ export function buildSurfaceGuideAndInventory(
|
|||
targetPath?: string;
|
||||
} = {},
|
||||
): SurfaceGuideResult {
|
||||
const { configManager, vaultService, sshPool } = deps;
|
||||
const { configManager, sshPool } = deps;
|
||||
void deps.vaultService;
|
||||
const servers = configManager.listServers();
|
||||
const systems = configManager.listSystems();
|
||||
const snippets = configManager.getSnippets().snippets;
|
||||
|
|
@ -51,10 +52,6 @@ export function buildSurfaceGuideAndInventory(
|
|||
actions: sys.actions.map((a) => ({ id: a.id, scope: a.scope, mode: a.mode })),
|
||||
}));
|
||||
|
||||
const credMeta = vaultService.isRuntimeReady
|
||||
? vaultService.listMetadata().map((c) => ({ id: c.id, name: c.name, type: c.type }))
|
||||
: [];
|
||||
|
||||
const targetSrv = opts.serverId ? configManager.getServer(opts.serverId) : undefined;
|
||||
const targetSrvOs = opts.serverId
|
||||
? sshPool.getState(opts.serverId)?.osDetected ?? targetSrv?.osHint ?? 'unknown'
|
||||
|
|
@ -67,7 +64,6 @@ export function buildSurfaceGuideAndInventory(
|
|||
existingWorkflowIds: workflows.map((w) => w.id),
|
||||
existingSnippetIds: snippets.map((s) => s.id),
|
||||
alertChannelIds: alerts.channels.map((c) => c.id),
|
||||
vaultCredentialRefs: credMeta,
|
||||
...(opts.serverId ? { focusedServer: { id: opts.serverId, os: targetSrvOs } } : {}),
|
||||
...(opts.targetPath ? { focusedConfigPath: opts.targetPath } : {}),
|
||||
},
|
||||
|
|
|
|||
|
|
@ -6,9 +6,7 @@ export interface RedactionResult {
|
|||
truncated: boolean;
|
||||
}
|
||||
|
||||
function escapeRegExp(literal: string): string {
|
||||
return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
const MIN_VAULT_SECRET_LEN = 4;
|
||||
|
||||
export function collectVaultSecretStrings(vaultService: VaultService): string[] {
|
||||
if (!vaultService.isRuntimeReady) return [];
|
||||
|
|
@ -18,21 +16,21 @@ export function collectVaultSecretStrings(vaultService: VaultService): string[]
|
|||
const creds = vaultService.exportAllCredentials();
|
||||
for (const cred of Object.values(creds)) {
|
||||
if (cred.type === 'ssh-password' || cred.type === 'sudo-password') {
|
||||
if (cred.password.length >= 6) collected.add(cred.password);
|
||||
if (cred.password.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.password);
|
||||
} else if (cred.type === 'webhook-secret') {
|
||||
if (cred.secret.length >= 6) collected.add(cred.secret);
|
||||
if (cred.secret.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.secret);
|
||||
} else if (cred.type === 'api-token') {
|
||||
if (cred.token.length >= 6) collected.add(cred.token);
|
||||
if (cred.token.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.token);
|
||||
} else if (cred.type === 'ssh-key') {
|
||||
const trimmed = cred.privateKey.trim();
|
||||
if (trimmed.length >= 6) collected.add(trimmed);
|
||||
if (trimmed.length >= MIN_VAULT_SECRET_LEN) collected.add(trimmed);
|
||||
for (const line of trimmed.split(/\r?\n/)) {
|
||||
const l = line.trim();
|
||||
if (l.length >= 12 && !l.startsWith('-----')) {
|
||||
collected.add(l);
|
||||
}
|
||||
}
|
||||
if (cred.passphrase && cred.passphrase.length >= 6) {
|
||||
if (cred.passphrase && cred.passphrase.length >= MIN_VAULT_SECRET_LEN) {
|
||||
collected.add(cred.passphrase);
|
||||
}
|
||||
}
|
||||
|
|
@ -44,6 +42,119 @@ export function collectVaultSecretStrings(vaultService: VaultService): string[]
|
|||
return [...collected].sort((a, b) => b.length - a.length);
|
||||
}
|
||||
|
||||
function replaceLiteralLinear(
|
||||
text: string,
|
||||
needle: string,
|
||||
replacement: string,
|
||||
): { text: string; hits: number } {
|
||||
if (!needle) return { text, hits: 0 };
|
||||
let idx = text.indexOf(needle);
|
||||
if (idx < 0) return { text, hits: 0 };
|
||||
let out = '';
|
||||
let last = 0;
|
||||
let hits = 0;
|
||||
while (idx >= 0) {
|
||||
out += text.slice(last, idx) + replacement;
|
||||
last = idx + needle.length;
|
||||
hits += 1;
|
||||
idx = text.indexOf(needle, last);
|
||||
}
|
||||
out += text.slice(last);
|
||||
return { text: out, hits };
|
||||
}
|
||||
|
||||
/**
|
||||
* Linear-time PEM private key block scanner (catches both complete blocks and
|
||||
* truncated logs containing only `-----BEGIN ... PRIVATE KEY-----` headers).
|
||||
*/
|
||||
function stripPemPrivateKeys(input: string): { text: string; hits: number } {
|
||||
const beginMarker = '-----BEGIN ';
|
||||
let idx = input.indexOf(beginMarker);
|
||||
if (idx < 0) return { text: input, hits: 0 };
|
||||
|
||||
let out = '';
|
||||
let last = 0;
|
||||
let hits = 0;
|
||||
|
||||
while (idx >= 0) {
|
||||
const headerEnd = input.indexOf('-----', idx + beginMarker.length);
|
||||
if (headerEnd < 0 || headerEnd - idx > 80) break;
|
||||
const headerSlice = input.slice(idx + beginMarker.length, headerEnd);
|
||||
if (!/PRIVATE KEY$/i.test(headerSlice)) {
|
||||
idx = input.indexOf(beginMarker, headerEnd + 5);
|
||||
continue;
|
||||
}
|
||||
|
||||
const endHeader = `-----END ${headerSlice}-----`;
|
||||
const footerPos = input.indexOf(endHeader, headerEnd + 5);
|
||||
let blockEnd: number;
|
||||
if (footerPos >= 0) {
|
||||
blockEnd = footerPos + endHeader.length;
|
||||
} else {
|
||||
// Truncated PEM: strip from BEGIN header up to a blank line or 8 KiB
|
||||
const blank = input.indexOf('\n\n', headerEnd + 5);
|
||||
blockEnd =
|
||||
blank >= 0
|
||||
? blank
|
||||
: Math.min(input.length, headerEnd + 5 + 8192);
|
||||
}
|
||||
|
||||
out += input.slice(last, idx) + '[REDACTED_PRIVATE_KEY]';
|
||||
hits += 1;
|
||||
last = blockEnd;
|
||||
idx = input.indexOf(beginMarker, last);
|
||||
}
|
||||
|
||||
out += input.slice(last);
|
||||
return { text: out, hits };
|
||||
}
|
||||
|
||||
/**
|
||||
* Linear-time O(n) JSON `"secretKey": "secretVal"` scrubber without ReDoS-prone
|
||||
* nested escape quantifiers.
|
||||
*/
|
||||
function stripJsonSecretValues(input: string): { text: string; hits: number } {
|
||||
const keyRe =
|
||||
/"[A-Za-z0-9_-]{0,40}(?:password|passwd|secret|token|apiKey|api_key|privateKey|private_key|passphrase|accessKey|secretKey|client_secret|refresh_token)[A-Za-z0-9_-]{0,40}"\s*:\s*"/gi;
|
||||
let out = '';
|
||||
let last = 0;
|
||||
let hits = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
|
||||
while ((m = keyRe.exec(input)) !== null) {
|
||||
const valStart = m.index + m[0].length;
|
||||
if (valStart < last) continue;
|
||||
|
||||
// Scan forward strictly once in O(k) checking backslash escapes
|
||||
let pos = valStart;
|
||||
let closed = false;
|
||||
while (pos < input.length) {
|
||||
const ch = input.charCodeAt(pos);
|
||||
if (ch === 92 /* '\\' */) {
|
||||
pos += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === 34 /* '"' */) {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
if (ch === 10 || ch === 13) break;
|
||||
pos += 1;
|
||||
}
|
||||
|
||||
const valSlice = input.slice(valStart, pos);
|
||||
if (valSlice.includes('[REDACTED')) continue;
|
||||
|
||||
out += input.slice(last, valStart) + '[REDACTED_SECRET]' + (closed ? '"' : '');
|
||||
hits += 1;
|
||||
last = closed ? pos + 1 : pos;
|
||||
keyRe.lastIndex = last;
|
||||
}
|
||||
|
||||
out += input.slice(last);
|
||||
return { text: out, hits };
|
||||
}
|
||||
|
||||
export function redactSecrets(
|
||||
input: string,
|
||||
knownSecrets: string[] = [],
|
||||
|
|
@ -52,27 +163,22 @@ export function redactSecrets(
|
|||
let redactedCount = 0;
|
||||
let text = input ?? '';
|
||||
|
||||
// 1. Strip PEM / OpenSSH private key blocks
|
||||
const keyBlockRe =
|
||||
/-----BEGIN [A-Z0-9 -]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 -]*PRIVATE KEY-----/g;
|
||||
text = text.replace(keyBlockRe, () => {
|
||||
redactedCount += 1;
|
||||
return '[REDACTED_PRIVATE_KEY]';
|
||||
});
|
||||
// 1. Complete & truncated PEM / OpenSSH private keys in O(n)
|
||||
const pem = stripPemPrivateKeys(text);
|
||||
text = pem.text;
|
||||
redactedCount += pem.hits;
|
||||
|
||||
// 2. Strip known secrets currently held in Vault
|
||||
// 2. Vault secrets >= 4 chars in O(n * m)
|
||||
for (const secret of knownSecrets) {
|
||||
if (secret.length < 6) continue;
|
||||
const re = new RegExp(escapeRegExp(secret), 'g');
|
||||
text = text.replace(re, () => {
|
||||
redactedCount += 1;
|
||||
return '[REDACTED_VAULT_SECRET]';
|
||||
});
|
||||
if (secret.length < MIN_VAULT_SECRET_LEN) continue;
|
||||
const res = replaceLiteralLinear(text, secret, '[REDACTED_VAULT_SECRET]');
|
||||
text = res.text;
|
||||
redactedCount += res.hits;
|
||||
}
|
||||
|
||||
// 3. Strip HTTP Authorization / Bearer / custom secret headers
|
||||
// 3. HTTP Authorization / Cookie / Proxy / custom secret headers
|
||||
text = text.replace(
|
||||
/\b(Authorization\s*:\s*(?:Bearer|Basic)\s+)([^\r\n]+)/gi,
|
||||
/\b((?:Proxy-)?Authorization\s*:\s*(?:Bearer|Basic|Token)\s+)([^\r\n]{1,1024})/gi,
|
||||
(_m, prefix: string, val: string) => {
|
||||
if (val.includes('[REDACTED')) return _m;
|
||||
redactedCount += 1;
|
||||
|
|
@ -80,25 +186,45 @@ export function redactSecrets(
|
|||
},
|
||||
);
|
||||
text = text.replace(
|
||||
/\bBearer\s+([A-Za-z0-9._~+/=-]{12,})/g,
|
||||
(_m, val: string) => {
|
||||
/\b(Cookie|Set-Cookie|X-API-Key|X-Auth-Token|X-Telegram-Bot-Token|X-Access-Token)\s*:\s*([^\r\n]{1,1024})/gi,
|
||||
(_m, key: string, val: string) => {
|
||||
if (val.includes('[REDACTED')) return _m;
|
||||
redactedCount += 1;
|
||||
return 'Bearer [REDACTED_TOKEN]';
|
||||
return `${key}: [REDACTED_TOKEN]`;
|
||||
},
|
||||
);
|
||||
text = text.replace(
|
||||
/\b(X-(?:API-Key|Telegram-Bot-Token|Auth-Token)\s*:\s*)([^\s\r\n]+)/gi,
|
||||
(_m, prefix: string, val: string) => {
|
||||
if (val.includes('[REDACTED')) return _m;
|
||||
/\b(?:Bearer|Basic)\s+([A-Za-z0-9._~+/=-]{8,1024})/g,
|
||||
(full, val: string) => {
|
||||
if (val.includes('[REDACTED')) return full;
|
||||
redactedCount += 1;
|
||||
return `${prefix}[REDACTED_TOKEN]`;
|
||||
return full.startsWith('Basic') ? 'Basic [REDACTED_TOKEN]' : 'Bearer [REDACTED_TOKEN]';
|
||||
},
|
||||
);
|
||||
|
||||
// 4. Strip .env / shell KEY=value secret assignments
|
||||
// 4. URL embedded credentials (user:pass@host)
|
||||
text = text.replace(
|
||||
/(^|[\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,
|
||||
/([a-zA-Z][a-zA-Z0-9+.-]{1,15}:\/\/[^:/\s@]{1,64}:)([^/\s@]{1,256})@/g,
|
||||
(_m, prefix: string, pw: string) => {
|
||||
if (pw.includes('[REDACTED')) return _m;
|
||||
redactedCount += 1;
|
||||
return `${prefix}[REDACTED_SECRET]@`;
|
||||
},
|
||||
);
|
||||
|
||||
// 5. Known API/cloud token formats
|
||||
text = text.replace(
|
||||
/\b(?:sk-[A-Za-z0-9_-]{12,256}|gh[pou]_[A-Za-z0-9]{12,256}|github_pat_[A-Za-z0-9_]{16,256}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,256}|AIza[0-9A-Za-z_-]{20,64}|glpat-[A-Za-z0-9_-]{12,256})/g,
|
||||
(tok) => {
|
||||
if (tok.includes('[REDACTED')) return tok;
|
||||
redactedCount += 1;
|
||||
return '[REDACTED_TOKEN]';
|
||||
},
|
||||
);
|
||||
|
||||
// 6. .env / shell KEY=value secret assignments (linear bounded match)
|
||||
text = text.replace(
|
||||
/(^|[\s;|&])([A-Za-z0-9_]{0,48}(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY|APIKEY|PRIVATE_KEY|PASSPHRASE|ACCESS_KEY|CREDENTIAL)[A-Za-z0-9_]{0,48})=([^\s\r\n]{1,512}|"[^"\r\n]{0,512}"|'[^'\r\n]{0,512}')/gim,
|
||||
(_m, lead: string, key: string, rawVal: string) => {
|
||||
if (rawVal.includes('[REDACTED')) return _m;
|
||||
redactedCount += 1;
|
||||
|
|
@ -106,15 +232,10 @@ export function redactSecrets(
|
|||
},
|
||||
);
|
||||
|
||||
// 5. Strip JSON "key": "secret" string properties
|
||||
text = text.replace(
|
||||
/("(?:[A-Za-z0-9_-]*(?:password|passwd|secret|token|apiKey|api_key|privateKey|private_key|passphrase)[A-Za-z0-9_-]*)"\s*:\s*)"([^"\\]*(?:\\.[^"\\]*)*)"/gi,
|
||||
(_m, keyPrefix: string, val: string) => {
|
||||
if (val.includes('[REDACTED')) return _m;
|
||||
redactedCount += 1;
|
||||
return `${keyPrefix}"[REDACTED_SECRET]"`;
|
||||
},
|
||||
);
|
||||
// 7. JSON "key": "secret" string properties in O(n)
|
||||
const jsonRes = stripJsonSecretValues(text);
|
||||
text = jsonRes.text;
|
||||
redactedCount += jsonRes.hits;
|
||||
|
||||
const cap = Math.max(256, maxChars);
|
||||
let truncated = false;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import type {
|
|||
AlertChannel,
|
||||
AlertRule,
|
||||
AlertRuleTargetSchema,
|
||||
SecurityEventKind,
|
||||
} from '../../shared/schemas/alerts.schema.js';
|
||||
import type { ServerConfig } from '../../shared/schemas/server.schema.js';
|
||||
import type { z } from 'zod';
|
||||
|
|
@ -17,6 +18,7 @@ import type {
|
|||
MonitoringTickEvent,
|
||||
} from '../monitoring/monitoring-service.js';
|
||||
import type { AuditService } from '../security/audit.js';
|
||||
import { fetchWithEgressGuard } from '../security/egress-guard.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
import type {
|
||||
|
|
@ -63,6 +65,7 @@ export class AlertEngine {
|
|||
private readonly emittedOffline = new Set<string>();
|
||||
private readonly prevProbeOk = new Map<string, boolean>();
|
||||
private readonly prevSystemDown = new Set<string>();
|
||||
private readonly channelCircuit = new Map<string, { failures: number; openUntil: number }>();
|
||||
private readonly unsubs: Array<() => void> = [];
|
||||
private sweepTimer: NodeJS.Timeout | null = null;
|
||||
private stopped = false;
|
||||
|
|
@ -83,10 +86,10 @@ export class AlertEngine {
|
|||
this.stopped = false;
|
||||
this.hydrateOpenIncidents();
|
||||
|
||||
this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId) => {
|
||||
this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId, meta) => {
|
||||
await this.sendDirectChannelMessage(channelId, {
|
||||
severity: 'critical',
|
||||
title: 'Workflow Execution Failure',
|
||||
severity: meta?.severity ?? 'critical',
|
||||
title: meta?.title ?? 'Workflow Execution Failure',
|
||||
message,
|
||||
state: 'firing',
|
||||
});
|
||||
|
|
@ -298,16 +301,20 @@ export class AlertEngine {
|
|||
throw new Error(`Unknown alert channel "${channelId}"`);
|
||||
}
|
||||
|
||||
const res = await this.dispatchToChannel(ch, {
|
||||
id: `test-${crypto.randomBytes(4).toString('hex')}`,
|
||||
ruleId: 'test-alert',
|
||||
serverId: 'hub',
|
||||
severity: 'warn',
|
||||
title: '[TEST] GCoordinator Alert Channel Verification',
|
||||
message: `Test notification dispatched to "${ch.name}" (${ch.type}) at ${new Date().toISOString()}.`,
|
||||
state: 'firing',
|
||||
ts: Date.now(),
|
||||
});
|
||||
const res = await this.dispatchToChannel(
|
||||
ch,
|
||||
{
|
||||
id: `test-${crypto.randomBytes(4).toString('hex')}`,
|
||||
ruleId: 'test-alert',
|
||||
serverId: 'hub',
|
||||
severity: 'warn',
|
||||
title: '[TEST] GCoordinator Alert Channel Verification',
|
||||
message: `Test notification dispatched to "${ch.name}" (${ch.type}) at ${new Date().toISOString()}.`,
|
||||
state: 'firing',
|
||||
ts: Date.now(),
|
||||
},
|
||||
{ bypassCircuitBreaker: true },
|
||||
);
|
||||
|
||||
this.auditService.log({
|
||||
action: 'alert.test_channel',
|
||||
|
|
@ -355,10 +362,6 @@ export class AlertEngine {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const probe of event.probes) {
|
||||
await this.evaluateProbe(server.id, probe, nowMs);
|
||||
}
|
||||
}
|
||||
|
||||
async evaluateProbe(
|
||||
|
|
@ -688,7 +691,151 @@ 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 {
|
||||
if (target.all) return true;
|
||||
if (!target.serverId && (!target.tags || target.tags.length === 0)) return false;
|
||||
if (target.serverId && target.serverId !== server.id) return false;
|
||||
if (target.tags && target.tags.length > 0) {
|
||||
if (!server.tags.some((t) => target.tags!.includes(t))) return false;
|
||||
|
|
@ -751,11 +898,8 @@ export class AlertEngine {
|
|||
private readChannelSecret(secretRef: string): string | null {
|
||||
if (!this.vaultService.isRuntimeReady) return null;
|
||||
const cred = this.vaultService.getRuntimeSecret(secretRef);
|
||||
if (!cred) return null;
|
||||
if (cred.type === 'webhook-secret') return cred.secret;
|
||||
if (cred.type === 'api-token') return cred.token;
|
||||
if (cred.type === 'ssh-password' || cred.type === 'sudo-password') return cred.password;
|
||||
return null;
|
||||
if (!cred || cred.type !== 'webhook-secret') return null;
|
||||
return cred.secret;
|
||||
}
|
||||
|
||||
private async dispatchToChannel(
|
||||
|
|
@ -770,15 +914,30 @@ export class AlertEngine {
|
|||
state: 'firing' | 'resolved';
|
||||
ts: number;
|
||||
},
|
||||
opts: { bypassCircuitBreaker?: boolean } = {},
|
||||
): Promise<{ ok: boolean; statusCode?: number; error?: string }> {
|
||||
const secret = this.readChannelSecret(channel.secretRef);
|
||||
if (!secret && !channel.url) {
|
||||
return { ok: false, error: `Missing vault secret "${channel.secretRef}"` };
|
||||
const cb = this.channelCircuit.get(channel.id);
|
||||
if (!opts.bypassCircuitBreaker && cb && cb.openUntil > Date.now()) {
|
||||
return { ok: false, error: 'Channel circuit breaker temporarily open after repeated failures' };
|
||||
}
|
||||
|
||||
const secret = channel.secretRef ? this.readChannelSecret(channel.secretRef) : null;
|
||||
if (channel.secretRef && !secret) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Missing or incompatible webhook-secret "${channel.secretRef}" in Vault`,
|
||||
};
|
||||
}
|
||||
if (!secret && !channel.url) {
|
||||
return { ok: false, error: 'Missing alert channel URL and webhook-secret' };
|
||||
}
|
||||
|
||||
const redactErr = (raw: string): string =>
|
||||
secret && secret.length > 0 ? raw.split(secret).join('[REDACTED]') : raw;
|
||||
|
||||
try {
|
||||
let targetUrl = channel.url ?? '';
|
||||
let method = 'POST';
|
||||
const method = 'POST';
|
||||
const headers: Record<string, string> = {};
|
||||
let body: string;
|
||||
|
||||
|
|
@ -831,24 +990,42 @@ export class AlertEngine {
|
|||
body = JSON.stringify(payload);
|
||||
}
|
||||
|
||||
const res = await fetch(targetUrl, {
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs;
|
||||
const res = await fetchWithEgressGuard(
|
||||
targetUrl,
|
||||
{ method, headers, body },
|
||||
{ allowedCidrs, timeoutMs: 10_000 },
|
||||
);
|
||||
|
||||
if (res.ok) {
|
||||
this.channelCircuit.delete(channel.id);
|
||||
} else {
|
||||
this.recordChannelFailure(channel.id);
|
||||
}
|
||||
|
||||
return {
|
||||
ok: res.ok,
|
||||
statusCode: res.status,
|
||||
error: res.ok ? undefined : `HTTP ${res.status}`,
|
||||
};
|
||||
} catch (err) {
|
||||
this.recordChannelFailure(channel.id);
|
||||
return {
|
||||
ok: false,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
error: redactErr(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(
|
||||
|
|
|
|||
|
|
@ -1,23 +1,30 @@
|
|||
import { Router } from 'express';
|
||||
import { Router, type RequestHandler } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { EntityIdSchema } from '../../../shared/schemas/common.js';
|
||||
import { AiDisabledError, AiDraftKindSchema, type AiService } from '../../ai/ai-service.js';
|
||||
import {
|
||||
AiDisabledError,
|
||||
AiDraftKindSchema,
|
||||
AiOverloadError,
|
||||
type AiService,
|
||||
} from '../../ai/ai-service.js';
|
||||
import { AiSurfaceSchema } from '../../ai/guides.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
requireStepUp,
|
||||
} from '../../security/guards.js';
|
||||
|
||||
export interface AiRouterDeps {
|
||||
authService: AuthService;
|
||||
aiService: AiService;
|
||||
stepUpGuard?: RequestHandler;
|
||||
}
|
||||
|
||||
export function createAiRouter(deps: AiRouterDeps): Router {
|
||||
const router = Router();
|
||||
const { authService, aiService } = deps;
|
||||
const { authService, aiService, stepUpGuard = requireStepUp } = deps;
|
||||
|
||||
// Read-only context redaction & preview (Safe-Mode exempt)
|
||||
router.post('/context-preview', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
|
|
@ -56,8 +63,8 @@ export function createAiRouter(deps: AiRouterDeps): Router {
|
|||
res.json(aiService.validateDraft(parsed.data));
|
||||
});
|
||||
|
||||
// Strictly read-only draft streaming: never auto-executes commands (Safe-Mode exempt)
|
||||
router.post('/chat', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
// Read-only draft streaming: Safe-Mode exempt, stepUpGuard protects Vault API token egress
|
||||
router.post('/chat', requireAuth(authService), requireCsrf, stepUpGuard, (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
chatId: z.string().min(1).max(64).optional(),
|
||||
|
|
@ -90,8 +97,8 @@ export function createAiRouter(deps: AiRouterDeps): Router {
|
|||
});
|
||||
res.status(202).json(started);
|
||||
} catch (err) {
|
||||
if (err instanceof AiDisabledError) {
|
||||
res.status(403).json({ error: err.code, message: err.message });
|
||||
if (err instanceof AiDisabledError || err instanceof AiOverloadError) {
|
||||
res.status(err.status).json({ error: err.code, message: err.message });
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
|
|
@ -106,22 +113,29 @@ export function createAiRouter(deps: AiRouterDeps): Router {
|
|||
res.json({ cancelled: aiService.cancelChat(chatId) });
|
||||
});
|
||||
|
||||
router.post('/test', requireAuth(authService), requireCsrf, enforceSafeMode, async (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
baseUrl: z.string().url().optional(),
|
||||
model: z.string().min(1).optional(),
|
||||
secretRef: z.string().max(64).optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
router.post(
|
||||
'/test',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
baseUrl: z.string().url().optional(),
|
||||
model: z.string().min(1).optional(),
|
||||
secretRef: z.string().max(64).optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json(await aiService.testEndpoint(parsed.data));
|
||||
});
|
||||
res.json(await aiService.testEndpoint(parsed.data));
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Router } from 'express';
|
||||
import { Router, type RequestHandler } from 'express';
|
||||
import { ZodError, z } from 'zod';
|
||||
import { AlertsFileSchema } from '../../../shared/schemas/alerts.schema.js';
|
||||
import type { AlertEngine } from '../../alerts/alert-engine.js';
|
||||
|
|
@ -9,6 +9,7 @@ import {
|
|||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
requireStepUp,
|
||||
} from '../../security/guards.js';
|
||||
|
||||
export interface AlertsRouterDeps {
|
||||
|
|
@ -16,11 +17,13 @@ export interface AlertsRouterDeps {
|
|||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
alertEngine: AlertEngine;
|
||||
stepUpGuard?: RequestHandler;
|
||||
}
|
||||
|
||||
export function createAlertsRouter(deps: AlertsRouterDeps): Router {
|
||||
const router = Router();
|
||||
const { authService, configManager, auditService, alertEngine } = deps;
|
||||
const { authService, configManager, auditService, alertEngine, stepUpGuard = requireStepUp } =
|
||||
deps;
|
||||
|
||||
router.get('/', requireAuth(authService), (req, res) => {
|
||||
const limit = typeof req.query.limit === 'string' ? Number(req.query.limit) : 50;
|
||||
|
|
@ -30,41 +33,48 @@ export function createAlertsRouter(deps: AlertsRouterDeps): Router {
|
|||
});
|
||||
});
|
||||
|
||||
router.put('/config', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
try {
|
||||
const parsed = AlertsFileSchema.parse({ version: 1, ...(req.body ?? {}) });
|
||||
const saved = configManager.saveConfigText(
|
||||
'alerts.json',
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Updated alerts configuration via UI',
|
||||
);
|
||||
auditService.log({
|
||||
action: 'alerts.config_update',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: 'alerts.json',
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ alertsConfig: saved.config, warnings: saved.warnings });
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid alerts configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
router.put(
|
||||
'/config',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
try {
|
||||
const parsed = AlertsFileSchema.parse({ version: 1, ...(req.body ?? {}) });
|
||||
const saved = configManager.saveConfigText(
|
||||
'alerts.json',
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Updated alerts configuration via UI',
|
||||
);
|
||||
auditService.log({
|
||||
action: 'alerts.config_update',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: 'alerts.json',
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ alertsConfig: saved.config, warnings: saved.warnings });
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid alerts configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'ALERTS_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save alerts configuration',
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'ALERTS_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save alerts configuration',
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/silences',
|
||||
|
|
@ -122,6 +132,7 @@ export function createAlertsRouter(deps: AlertsRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,33 @@
|
|||
import { Router } from 'express';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import { z } from 'zod';
|
||||
import type { AuditListOptions, AuditService } from '../../security/audit.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import { requireAuth } from '../../security/guards.js';
|
||||
|
||||
const AuditQuerySchema = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(200).optional(),
|
||||
offset: z.coerce.number().int().min(0).optional(),
|
||||
action: z.string().trim().min(1).max(128).optional(),
|
||||
actionPrefix: z.string().trim().min(1).max(64).optional(),
|
||||
status: z.enum(['ok', 'denied', 'error']).optional(),
|
||||
ip: z.string().trim().min(1).max(64).optional(),
|
||||
target: z.string().trim().min(1).max(128).optional(),
|
||||
q: z.string().trim().min(1).max(128).optional(),
|
||||
from: z.coerce.number().int().min(0).optional(),
|
||||
to: z.coerce.number().int().min(0).optional(),
|
||||
format: z.enum(['csv', 'ndjson']).optional(),
|
||||
});
|
||||
|
||||
function pickFilterOptions(raw: Record<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(
|
||||
authService: AuthService,
|
||||
auditService: AuditService,
|
||||
|
|
@ -10,20 +35,37 @@ export function createAuditRouter(
|
|||
const router = Router();
|
||||
|
||||
router.get('/', requireAuth(authService), (req, res) => {
|
||||
const limit = req.query.limit ? Number(req.query.limit) : 50;
|
||||
const offset = req.query.offset ? Number(req.query.offset) : 0;
|
||||
const action =
|
||||
typeof req.query.action === 'string' && req.query.action.trim()
|
||||
? req.query.action.trim()
|
||||
: undefined;
|
||||
const opts = pickFilterOptions(req.query as Record<string, unknown>);
|
||||
const result = auditService.list(opts);
|
||||
res.json({
|
||||
...result,
|
||||
actions: auditService.listActions(),
|
||||
});
|
||||
});
|
||||
|
||||
res.json(
|
||||
auditService.list({
|
||||
limit: Number.isFinite(limit) ? limit : 50,
|
||||
offset: Number.isFinite(offset) ? offset : 0,
|
||||
action,
|
||||
}),
|
||||
router.get('/export', requireAuth(authService), (req, res) => {
|
||||
const opts = pickFilterOptions(req.query as Record<string, unknown>);
|
||||
const format = opts.format ?? 'ndjson';
|
||||
const content = auditService.exportRecords(opts, format);
|
||||
|
||||
auditService.log({
|
||||
action: 'audit.export',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: format,
|
||||
status: 'ok',
|
||||
});
|
||||
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.setHeader(
|
||||
'Content-Type',
|
||||
format === 'csv' ? 'text/csv; charset=utf-8' : 'application/x-ndjson; charset=utf-8',
|
||||
);
|
||||
res.setHeader(
|
||||
'Content-Disposition',
|
||||
`attachment; filename="gcoordinator-audit-export.${format === 'csv' ? 'csv' : 'ndjson'}"`,
|
||||
);
|
||||
res.send(content);
|
||||
});
|
||||
|
||||
return router;
|
||||
|
|
|
|||
|
|
@ -1,13 +1,19 @@
|
|||
import { Router, type Request, type Response } from 'express';
|
||||
import { Router, type NextFunction, type Request, type Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type {
|
||||
AuthenticationResponseJSON,
|
||||
RegistrationResponseJSON,
|
||||
} from '@simplewebauthn/server';
|
||||
import { SecuritySettingsSchema } from '../../../shared/schemas/settings.schema.js';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import { SESSION_COOKIE_NAME, type AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
AuthOverloadError,
|
||||
SESSION_COOKIE_NAME,
|
||||
type AuthService,
|
||||
} from '../../security/auth.js';
|
||||
import {
|
||||
asyncHandler,
|
||||
createStepUpGuard,
|
||||
enforceSafeMode,
|
||||
extractCookies,
|
||||
|
|
@ -28,6 +34,8 @@ export interface AuthRouterDeps {
|
|||
recoveryStore: EmergencyRecoveryService;
|
||||
rateLimiter: RateLimiter;
|
||||
trustCloudflare: boolean;
|
||||
webauthnRpId?: string;
|
||||
webauthnOrigins?: string[];
|
||||
}
|
||||
|
||||
function isSecureCookie(req: Request, trustCloudflare: boolean): boolean {
|
||||
|
|
@ -44,9 +52,10 @@ function setAuthCookies(
|
|||
sessionToken: string,
|
||||
csrfToken: string,
|
||||
trustCloudflare: boolean,
|
||||
sessionTtlHours = 168,
|
||||
): void {
|
||||
const secure = isSecureCookie(req, trustCloudflare);
|
||||
const maxAge = 7 * 24 * 60 * 60 * 1000;
|
||||
const maxAge = Math.max(1, sessionTtlHours) * 60 * 60 * 1000;
|
||||
res.cookie(SESSION_COOKIE_NAME, sessionToken, {
|
||||
httpOnly: true,
|
||||
sameSite: 'strict',
|
||||
|
|
@ -76,6 +85,8 @@ class WebAuthnRpError extends Error {
|
|||
function resolveWebAuthnRp(
|
||||
req: Request,
|
||||
trustCloudflare: boolean,
|
||||
configuredRpId?: string,
|
||||
configuredOrigins?: string[],
|
||||
): { rpID: string; expectedOrigin: string } {
|
||||
const originHeader =
|
||||
typeof req.headers.origin === 'string' && req.headers.origin.trim()
|
||||
|
|
@ -92,10 +103,35 @@ function resolveWebAuthnRp(
|
|||
throw new WebAuthnRpError('Invalid Origin header for WebAuthn request');
|
||||
}
|
||||
|
||||
const rpID = parsed.hostname;
|
||||
if (/^\d+\.\d+\.\d+\.\d+$/.test(rpID) || rpID.includes(':')) {
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
||||
throw new WebAuthnRpError('WebAuthn Origin must use http or https');
|
||||
}
|
||||
|
||||
if (configuredOrigins && configuredOrigins.length > 0) {
|
||||
if (!configuredOrigins.includes(parsed.origin)) {
|
||||
throw new WebAuthnRpError(
|
||||
`Origin "${parsed.origin}" is not listed in GCOORD_WEBAUTHN_ORIGINS`,
|
||||
);
|
||||
}
|
||||
} else if (originHeader && parsed.host !== hostHeader) {
|
||||
throw new WebAuthnRpError('WebAuthn Origin host does not match Request Host');
|
||||
}
|
||||
|
||||
const hostname = parsed.hostname;
|
||||
if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname) || hostname.includes(':')) {
|
||||
throw new WebAuthnRpError(
|
||||
`WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${rpID}" is rejected by browsers).`,
|
||||
`WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${hostname}" is rejected by browsers).`,
|
||||
);
|
||||
}
|
||||
|
||||
const rpID = configuredRpId || hostname;
|
||||
if (
|
||||
configuredRpId &&
|
||||
hostname !== configuredRpId &&
|
||||
!hostname.endsWith(`.${configuredRpId}`)
|
||||
) {
|
||||
throw new WebAuthnRpError(
|
||||
`Hostname "${hostname}" does not match GCOORD_WEBAUTHN_RP_ID "${configuredRpId}"`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -115,6 +151,8 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
recoveryStore,
|
||||
rateLimiter,
|
||||
trustCloudflare,
|
||||
webauthnRpId,
|
||||
webauthnOrigins,
|
||||
} = deps;
|
||||
|
||||
const stepUpGuard = createStepUpGuard(
|
||||
|
|
@ -133,11 +171,16 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
res.json({
|
||||
bootstrapped,
|
||||
authenticated: false,
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
defaultMobileSafeMode: settings.defaultMobileSafeMode,
|
||||
theme: settings.theme,
|
||||
authRequirements,
|
||||
authRequirements: {
|
||||
requireTotpOnLogin: authRequirements.requireTotpOnLogin,
|
||||
passwordMode: authRequirements.passwordMode,
|
||||
passwordCount: authRequirements.passwordCount,
|
||||
totpMode: authRequirements.totpMode,
|
||||
totpCount: authRequirements.totpCount,
|
||||
passkeyCount: authRequirements.passkeyCount,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
|
@ -148,196 +191,231 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
safeMode: session.safeMode,
|
||||
elevatedUntil: session.elevatedUntil,
|
||||
vaultState: vaultService.state,
|
||||
sealState: vaultService.sealState,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
isPanicLocked: vaultService.isPanicLocked,
|
||||
defaultMobileSafeMode: settings.defaultMobileSafeMode,
|
||||
theme: settings.theme,
|
||||
security: settings.security,
|
||||
runtime: settings.runtime,
|
||||
authRequirements,
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/bootstrap', async (req, res) => {
|
||||
if (authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const username =
|
||||
typeof req.query.username === 'string' && req.query.username.trim()
|
||||
? req.query.username.trim()
|
||||
: 'admin';
|
||||
const data = await authService.beginBootstrap(username);
|
||||
res.json(data);
|
||||
});
|
||||
router.get(
|
||||
'/bootstrap',
|
||||
asyncHandler(async (req, res) => {
|
||||
if (authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const rawUser =
|
||||
typeof req.query.username === 'string' && req.query.username.trim()
|
||||
? req.query.username.trim().slice(0, 64)
|
||||
: 'admin';
|
||||
const data = await authService.beginBootstrap(rawUser);
|
||||
res.json(data);
|
||||
}),
|
||||
);
|
||||
|
||||
router.post('/bootstrap', async (req, res) => {
|
||||
if (authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('bootstrap', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
|
||||
const bodySchema = z.object({
|
||||
username: z.string().min(2).max(64).default('admin'),
|
||||
password: z.string().min(10).max(256),
|
||||
totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'),
|
||||
secretBase32: z.string().optional(),
|
||||
initialSafeMode: z.boolean().optional(),
|
||||
securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(),
|
||||
});
|
||||
const parsed = bodySchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
rateLimiter.recordFailure('bootstrap', ip);
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (parsed.data.securityPreset) {
|
||||
const cur = configManager.getSettings();
|
||||
const presetSecurity =
|
||||
parsed.data.securityPreset === 'relaxed'
|
||||
? {
|
||||
...cur.security,
|
||||
requireTotpOnLogin: false,
|
||||
stepUpPolicy: 'off' as const,
|
||||
stepUpMethod: 'password' as const,
|
||||
elevateOnLogin: true,
|
||||
keepElevationOnSafeMode: true,
|
||||
}
|
||||
: parsed.data.securityPreset === 'strict'
|
||||
? {
|
||||
...cur.security,
|
||||
requireTotpOnLogin: true,
|
||||
stepUpPolicy: '5m' as const,
|
||||
stepUpMethod: 'totp' as const,
|
||||
elevateOnLogin: false,
|
||||
keepElevationOnSafeMode: false,
|
||||
}
|
||||
: cur.security;
|
||||
|
||||
configManager.saveConfigText(
|
||||
'settings.json',
|
||||
JSON.stringify({ ...cur, security: presetSecurity }, null, 2),
|
||||
'ui',
|
||||
`Bootstrap preset: ${parsed.data.securityPreset}`,
|
||||
);
|
||||
router.post(
|
||||
'/bootstrap',
|
||||
asyncHandler(async (req, res) => {
|
||||
if (authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('bootstrap', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await authService.completeBootstrap({
|
||||
...parsed.data,
|
||||
ip,
|
||||
userAgent: String(req.headers['user-agent'] ?? 'unknown'),
|
||||
});
|
||||
rateLimiter.recordSuccess('bootstrap', ip);
|
||||
setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare);
|
||||
auditService.log({
|
||||
action: 'auth.bootstrap',
|
||||
actorIp: ip,
|
||||
sessionIdHash: result.session.idHash,
|
||||
target: parsed.data.username,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({
|
||||
authenticated: true,
|
||||
csrfToken: result.csrfToken,
|
||||
recoveryCodes: result.recoveryCodes,
|
||||
safeMode: result.session.safeMode,
|
||||
elevatedUntil: result.session.elevatedUntil,
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
});
|
||||
} catch (err) {
|
||||
rateLimiter.recordFailure('bootstrap', ip);
|
||||
auditService.log({
|
||||
action: 'auth.bootstrap',
|
||||
actorIp: ip,
|
||||
status: 'error',
|
||||
details: err instanceof Error ? err.message : 'Bootstrap failed',
|
||||
});
|
||||
res.status(400).json({
|
||||
error: 'BOOTSTRAP_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Bootstrap failed',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/login', async (req, res) => {
|
||||
if (!authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('login', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
|
||||
const bodySchema = z
|
||||
.object({
|
||||
username: z.string().min(1).optional(),
|
||||
password: z.string().min(1).optional(),
|
||||
passwords: z.array(z.string().min(1)).optional(),
|
||||
code: z.string().max(32).optional(),
|
||||
codes: z.array(z.string().max(32)).optional(),
|
||||
const bodySchema = z.object({
|
||||
username: z.string().trim().min(2).max(64).default('admin'),
|
||||
password: z.string().min(10).max(256),
|
||||
totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'),
|
||||
secretBase32: z.string().max(128).optional(),
|
||||
bootstrapToken: z.string().min(16).max(128).optional(),
|
||||
initialSafeMode: z.boolean().optional(),
|
||||
})
|
||||
.refine(
|
||||
(b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)),
|
||||
'Password is required',
|
||||
);
|
||||
const parsed = bodySchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
rateLimiter.recordFailure('login', ip);
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await authService.login({
|
||||
...parsed.data,
|
||||
ip,
|
||||
userAgent: String(req.headers['user-agent'] ?? 'unknown'),
|
||||
});
|
||||
|
||||
if (!result) {
|
||||
rateLimiter.recordFailure('login', ip);
|
||||
auditService.log({
|
||||
action: 'auth.login',
|
||||
actorIp: ip,
|
||||
target: parsed.data.username ?? 'admin',
|
||||
status: 'denied',
|
||||
securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(),
|
||||
});
|
||||
res.status(401).json({ error: 'INVALID_CREDENTIALS' });
|
||||
return;
|
||||
}
|
||||
const parsed = bodySchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
rateLimiter.recordFailure('bootstrap', ip);
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
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',
|
||||
});
|
||||
try {
|
||||
const result = await authService.completeBootstrap({
|
||||
...parsed.data,
|
||||
ip,
|
||||
userAgent: String(req.headers['user-agent'] ?? 'unknown'),
|
||||
});
|
||||
|
||||
res.json({
|
||||
authenticated: true,
|
||||
csrfToken: result.csrfToken,
|
||||
safeMode: result.session.safeMode,
|
||||
elevatedUntil: result.session.elevatedUntil,
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
});
|
||||
});
|
||||
if (parsed.data.securityPreset) {
|
||||
const cur = configManager.getSettings();
|
||||
const presetSecurity =
|
||||
parsed.data.securityPreset === 'relaxed'
|
||||
? {
|
||||
...cur.security,
|
||||
requireTotpOnLogin: false,
|
||||
stepUpPolicy: 'off' as const,
|
||||
stepUpMethod: 'password' as const,
|
||||
elevateOnLogin: true,
|
||||
keepElevationOnSafeMode: true,
|
||||
}
|
||||
: parsed.data.securityPreset === 'strict'
|
||||
? {
|
||||
...cur.security,
|
||||
requireTotpOnLogin: true,
|
||||
stepUpPolicy: '5m' as const,
|
||||
stepUpMethod: 'totp' as const,
|
||||
elevateOnLogin: false,
|
||||
keepElevationOnSafeMode: false,
|
||||
}
|
||||
: cur.security;
|
||||
|
||||
configManager.saveConfigText(
|
||||
'settings.json',
|
||||
JSON.stringify({ ...cur, security: presetSecurity }, null, 2),
|
||||
'ui',
|
||||
`Bootstrap preset: ${parsed.data.securityPreset}`,
|
||||
);
|
||||
authService.syncRecovery({
|
||||
newRecoveryCodes: result.recoveryCodes,
|
||||
snapshotReason: 'bootstrap-preset',
|
||||
});
|
||||
}
|
||||
|
||||
const ttlHours = configManager.getSettings().security.sessionTtlHours;
|
||||
rateLimiter.recordSuccess('bootstrap', ip);
|
||||
setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours);
|
||||
auditService.log({
|
||||
action: 'auth.bootstrap',
|
||||
actorIp: ip,
|
||||
sessionIdHash: result.session.idHash,
|
||||
target: parsed.data.username,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({
|
||||
authenticated: true,
|
||||
csrfToken: result.csrfToken,
|
||||
recoveryCodes: result.recoveryCodes,
|
||||
safeMode: result.session.safeMode,
|
||||
elevatedUntil: result.session.elevatedUntil,
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof AuthOverloadError) throw err;
|
||||
rateLimiter.recordFailure('bootstrap', ip);
|
||||
auditService.log({
|
||||
action: 'auth.bootstrap',
|
||||
actorIp: ip,
|
||||
status: 'error',
|
||||
details: err instanceof Error ? err.message : 'Bootstrap failed',
|
||||
});
|
||||
res.status(400).json({
|
||||
error: 'BOOTSTRAP_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Bootstrap failed',
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/login',
|
||||
asyncHandler(async (req, res) => {
|
||||
if (!authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('login', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
if (!rateLimiter.acquireInFlight('login', ip, 2)) {
|
||||
res.setHeader('Retry-After', '2');
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: 2 });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const bodySchema = z
|
||||
.object({
|
||||
username: z.string().trim().min(1).max(64),
|
||||
password: z.string().min(1).max(256).optional(),
|
||||
passwords: z.array(z.string().min(1).max(256)).max(16).optional(),
|
||||
code: z.string().max(64).optional(),
|
||||
codes: z.array(z.string().max(64)).max(16).optional(),
|
||||
initialSafeMode: z.boolean().optional(),
|
||||
})
|
||||
.refine(
|
||||
(b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)),
|
||||
'Password is required',
|
||||
);
|
||||
const parsed = bodySchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
rateLimiter.recordFailure('login', ip);
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await authService.login({
|
||||
...parsed.data,
|
||||
ip,
|
||||
userAgent: String(req.headers['user-agent'] ?? 'unknown'),
|
||||
});
|
||||
|
||||
if (!result) {
|
||||
const failState = rateLimiter.recordFailure('login', ip);
|
||||
if (failState.lockedUntil > 0 || failState.globalTriggered) {
|
||||
authService.emitSecurityEvent('auth.lockout', ip, {
|
||||
failures: failState.failures,
|
||||
globalTriggered: failState.globalTriggered,
|
||||
});
|
||||
}
|
||||
auditService.log({
|
||||
action: 'auth.login',
|
||||
actorIp: ip,
|
||||
target: parsed.data.username,
|
||||
status: 'denied',
|
||||
});
|
||||
res.status(401).json({ error: 'INVALID_CREDENTIALS' });
|
||||
return;
|
||||
}
|
||||
|
||||
const ttlHours = configManager.getSettings().security.sessionTtlHours;
|
||||
rateLimiter.recordSuccess('login', ip);
|
||||
setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours);
|
||||
auditService.log({
|
||||
action: 'auth.login',
|
||||
actorIp: ip,
|
||||
sessionIdHash: result.session.idHash,
|
||||
target: parsed.data.username,
|
||||
status: 'ok',
|
||||
});
|
||||
|
||||
res.json({
|
||||
authenticated: true,
|
||||
csrfToken: result.csrfToken,
|
||||
safeMode: result.session.safeMode,
|
||||
elevatedUntil: result.session.elevatedUntil,
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
});
|
||||
} finally {
|
||||
rateLimiter.releaseInFlight('login', ip);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Exempt from enforceSafeMode
|
||||
router.post('/logout', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
|
|
@ -383,7 +461,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
asyncHandler(async (req, res) => {
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('step-up', ip);
|
||||
if (!rate.allowed) {
|
||||
|
|
@ -394,10 +472,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
|
||||
const parsed = z
|
||||
.object({
|
||||
code: z.string().optional(),
|
||||
codes: z.array(z.string()).optional(),
|
||||
password: z.string().optional(),
|
||||
passwords: z.array(z.string()).optional(),
|
||||
code: z.string().max(64).optional(),
|
||||
codes: z.array(z.string().max(64)).max(16).optional(),
|
||||
password: z.string().max(256).optional(),
|
||||
passwords: z.array(z.string().max(256)).max(16).optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
|
|
@ -407,7 +485,12 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
|
||||
const outcome = await authService.stepUp(req.authSession!.idHash, parsed.data);
|
||||
if (!outcome.ok) {
|
||||
rateLimiter.recordFailure('step-up', ip);
|
||||
const failState = rateLimiter.recordFailure('step-up', ip);
|
||||
if (failState.lockedUntil > 0) {
|
||||
authService.emitSecurityEvent('auth.step_up_lockout', ip, {
|
||||
failures: failState.failures,
|
||||
});
|
||||
}
|
||||
auditService.log({
|
||||
action: 'auth.step_up',
|
||||
actorIp: ip,
|
||||
|
|
@ -430,7 +513,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
status: 'ok',
|
||||
});
|
||||
res.json({ elevatedUntil: outcome.elevatedUntil });
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
router.post('/drop-elevation', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
|
|
@ -627,7 +710,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
asyncHandler(async (req, res) => {
|
||||
const parsed = z
|
||||
.object({ label: z.string().min(1).max(64).default('Passkey') })
|
||||
.safeParse(req.body ?? {});
|
||||
|
|
@ -636,7 +719,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
return;
|
||||
}
|
||||
try {
|
||||
const rp = resolveWebAuthnRp(req, trustCloudflare);
|
||||
const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins);
|
||||
const data = await authService.beginPasskeyRegistration({
|
||||
label: parsed.data.label,
|
||||
...rp,
|
||||
|
|
@ -648,7 +731,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
message: err instanceof Error ? err.message : 'Unable to start passkey registration',
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
router.post(
|
||||
|
|
@ -657,10 +740,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
asyncHandler(async (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
challengeId: z.string().min(1),
|
||||
challengeId: z.string().min(1).max(128),
|
||||
response: z.record(z.unknown()),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
|
|
@ -687,7 +770,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
message: err instanceof Error ? err.message : 'Unable to verify passkey registration',
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
router.delete(
|
||||
|
|
@ -721,102 +804,115 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
router.post('/passkeys/login/options', async (req, res) => {
|
||||
if (!authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('login', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const rp = resolveWebAuthnRp(req, trustCloudflare);
|
||||
const data = await authService.beginPasskeyAuthentication({
|
||||
purpose: 'login',
|
||||
...rp,
|
||||
router.post(
|
||||
'/passkeys/login/options',
|
||||
asyncHandler(async (req, res) => {
|
||||
if (!authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('login', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins);
|
||||
const data = await authService.beginPasskeyAuthentication({
|
||||
purpose: 'login',
|
||||
...rp,
|
||||
});
|
||||
res.json(data);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_LOGIN_OPTIONS_FAILED',
|
||||
message: err instanceof Error ? err.message : 'No passkeys available',
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/passkeys/login/verify',
|
||||
asyncHandler(async (req, res) => {
|
||||
if (!authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('login', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = z
|
||||
.object({
|
||||
challengeId: z.string().min(1).max(128),
|
||||
response: z.record(z.unknown()),
|
||||
initialSafeMode: z.boolean().optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
rateLimiter.recordFailure('login', ip);
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await authService.loginWithPasskey({
|
||||
challengeId: parsed.data.challengeId,
|
||||
response: parsed.data.response as unknown as AuthenticationResponseJSON,
|
||||
ip,
|
||||
userAgent: String(req.headers['user-agent'] ?? 'unknown'),
|
||||
initialSafeMode: parsed.data.initialSafeMode,
|
||||
});
|
||||
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',
|
||||
});
|
||||
}
|
||||
});
|
||||
if (!result) {
|
||||
const failState = rateLimiter.recordFailure('login', ip);
|
||||
if (failState.lockedUntil > 0 || failState.globalTriggered) {
|
||||
authService.emitSecurityEvent('auth.lockout', ip, {
|
||||
failures: failState.failures,
|
||||
globalTriggered: failState.globalTriggered,
|
||||
});
|
||||
}
|
||||
auditService.log({
|
||||
action: 'auth.passkey_login',
|
||||
actorIp: ip,
|
||||
status: 'denied',
|
||||
});
|
||||
res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' });
|
||||
return;
|
||||
}
|
||||
|
||||
router.post('/passkeys/login/verify', async (req, res) => {
|
||||
if (!authService.isBootstrapped()) {
|
||||
res.status(409).json({ error: 'NOT_BOOTSTRAPPED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('login', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = z
|
||||
.object({
|
||||
challengeId: z.string().min(1),
|
||||
response: z.record(z.unknown()),
|
||||
initialSafeMode: z.boolean().optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
rateLimiter.recordFailure('login', ip);
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await authService.loginWithPasskey({
|
||||
challengeId: parsed.data.challengeId,
|
||||
response: parsed.data.response as unknown as AuthenticationResponseJSON,
|
||||
ip,
|
||||
userAgent: String(req.headers['user-agent'] ?? 'unknown'),
|
||||
initialSafeMode: parsed.data.initialSafeMode,
|
||||
});
|
||||
if (!result) {
|
||||
rateLimiter.recordFailure('login', ip);
|
||||
const ttlHours = configManager.getSettings().security.sessionTtlHours;
|
||||
rateLimiter.recordSuccess('login', ip);
|
||||
setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours);
|
||||
auditService.log({
|
||||
action: 'auth.passkey_login',
|
||||
actorIp: ip,
|
||||
status: 'denied',
|
||||
sessionIdHash: result.session.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' });
|
||||
return;
|
||||
}
|
||||
|
||||
rateLimiter.recordSuccess('login', ip);
|
||||
setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare);
|
||||
auditService.log({
|
||||
action: 'auth.passkey_login',
|
||||
actorIp: ip,
|
||||
sessionIdHash: result.session.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
|
||||
res.json({
|
||||
authenticated: true,
|
||||
csrfToken: result.csrfToken,
|
||||
safeMode: result.session.safeMode,
|
||||
elevatedUntil: result.session.elevatedUntil,
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
});
|
||||
});
|
||||
res.json({
|
||||
authenticated: true,
|
||||
csrfToken: result.csrfToken,
|
||||
safeMode: result.session.safeMode,
|
||||
elevatedUntil: result.session.elevatedUntil,
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/passkeys/step-up/options',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
asyncHandler(async (req, res) => {
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('step-up', ip);
|
||||
if (!rate.allowed) {
|
||||
|
|
@ -825,7 +921,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
return;
|
||||
}
|
||||
try {
|
||||
const rp = resolveWebAuthnRp(req, trustCloudflare);
|
||||
const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins);
|
||||
const data = await authService.beginPasskeyAuthentication({
|
||||
purpose: 'stepup',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
|
|
@ -838,7 +934,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
message: err instanceof Error ? err.message : 'Unable to start passkey verification',
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
router.post(
|
||||
|
|
@ -846,7 +942,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
asyncHandler(async (req, res) => {
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('step-up', ip);
|
||||
if (!rate.allowed) {
|
||||
|
|
@ -856,7 +952,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
}
|
||||
const parsed = z
|
||||
.object({
|
||||
challengeId: z.string().min(1),
|
||||
challengeId: z.string().min(1).max(128),
|
||||
response: z.record(z.unknown()),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
|
|
@ -894,6 +990,46 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
status: 'ok',
|
||||
});
|
||||
res.json({ elevatedUntil: outcome.elevatedUntil });
|
||||
}),
|
||||
);
|
||||
|
||||
router.put(
|
||||
'/security-policy',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const cur = configManager.getSettings();
|
||||
const bodyObj =
|
||||
typeof req.body === 'object' && req.body !== null && !Array.isArray(req.body)
|
||||
? (req.body as Record<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 });
|
||||
},
|
||||
);
|
||||
|
||||
|
|
@ -922,9 +1058,11 @@ export function createAuthRouter(deps: AuthRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
router.get(
|
||||
router.post(
|
||||
'/recovery-backup/export',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const settings = configManager.getSettings();
|
||||
|
|
@ -1032,5 +1170,14 @@ 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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,17 +1,21 @@
|
|||
import type Database from 'better-sqlite3';
|
||||
import { Router, type RequestHandler } from 'express';
|
||||
import { Router, type NextFunction, type Request, type RequestHandler, type Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { RuntimeLimits } from '../../config/runtime-limits.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
createBackupBundle,
|
||||
restoreBackupBundle,
|
||||
verifyBackupSummaryOnly,
|
||||
BackupBusyError,
|
||||
createBackupBundleAsync,
|
||||
restoreBackupBundleAsync,
|
||||
verifyBackupSummaryOnlyAsync,
|
||||
type BackupInnerPayload,
|
||||
type BackupVerificationSummary,
|
||||
} from '../../security/backup.js';
|
||||
import type { BackupScheduler } from '../../security/backup-scheduler.js';
|
||||
import {
|
||||
asyncHandler,
|
||||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
|
|
@ -26,6 +30,8 @@ export interface BackupRouterDeps {
|
|||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
stepUpGuard: RequestHandler;
|
||||
getRuntimeLimits?: () => RuntimeLimits;
|
||||
backupScheduler?: BackupScheduler;
|
||||
onRestored: (info: {
|
||||
summary: BackupVerificationSummary;
|
||||
inner: BackupInnerPayload;
|
||||
|
|
@ -54,6 +60,8 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
|
|||
configManager,
|
||||
auditService,
|
||||
stepUpGuard,
|
||||
getRuntimeLimits,
|
||||
backupScheduler,
|
||||
onRestored,
|
||||
} = deps;
|
||||
|
||||
|
|
@ -63,7 +71,7 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
|
|||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
asyncHandler(async (req, res) => {
|
||||
const parsed = ExportBackupBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
|
|
@ -81,11 +89,13 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
|
|||
}
|
||||
|
||||
try {
|
||||
const result = createBackupBundle({
|
||||
const limits = getRuntimeLimits?.();
|
||||
const result = await createBackupBundleAsync({
|
||||
dataDir,
|
||||
db,
|
||||
masterKey,
|
||||
passphrase,
|
||||
scryptConcurrency: limits?.scryptConcurrency,
|
||||
});
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
||||
const filename = `gcoordinator-backup-${stamp}.gcoord.enc`;
|
||||
|
|
@ -109,38 +119,73 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
|
|||
summary: result.summary,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof BackupBusyError) throw err;
|
||||
res.status(400).json({
|
||||
error: 'BACKUP_EXPORT_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to create backup bundle',
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// Read-only verification: exempt from enforceSafeMode
|
||||
router.post('/verify', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
// Read-only verification: exempt from enforceSafeMode, still requires step-up and writes audit entry
|
||||
router.post(
|
||||
'/verify',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
stepUpGuard,
|
||||
asyncHandler(async (req, res) => {
|
||||
const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const limits = getRuntimeLimits?.();
|
||||
const maxBodyBytes = limits?.backupMaxBodyBytes ?? 16 * 1024 * 1024;
|
||||
const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64');
|
||||
const summary = verifyBackupSummaryOnly(rawBuf, {
|
||||
masterKey:
|
||||
parsed.data.masterKey?.trim() || vaultService.exportMasterKeyHex() || undefined,
|
||||
passphrase: parsed.data.passphrase?.trim() || undefined,
|
||||
vaultMasterKey: parsed.data.vaultMasterKey?.trim() || undefined,
|
||||
});
|
||||
res.json({ summary });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'BACKUP_INVALID',
|
||||
message: err instanceof Error ? err.message : 'Backup verification failed',
|
||||
});
|
||||
}
|
||||
});
|
||||
if (rawBuf.length > maxBodyBytes) {
|
||||
res.status(413).json({
|
||||
error: 'PAYLOAD_TOO_LARGE',
|
||||
message: `Backup bundle exceeds limit (${maxBodyBytes} bytes)`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const summary = await verifyBackupSummaryOnlyAsync(rawBuf, {
|
||||
masterKey:
|
||||
parsed.data.masterKey?.trim() || vaultService.exportMasterKeyHex() || undefined,
|
||||
passphrase: parsed.data.passphrase?.trim() || undefined,
|
||||
vaultMasterKey: parsed.data.vaultMasterKey?.trim() || undefined,
|
||||
scryptConcurrency: limits?.scryptConcurrency,
|
||||
maxGunzipBytes: limits?.backupMaxGunzipBytes,
|
||||
});
|
||||
auditService.log({
|
||||
action: 'backup.verify',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: summary.kdf,
|
||||
status: 'ok',
|
||||
details: { configFileCount: summary.configFileCount, vaultVerified: summary.vaultVerified },
|
||||
});
|
||||
res.json({ summary });
|
||||
} catch (err) {
|
||||
if (err instanceof BackupBusyError) throw err;
|
||||
auditService.log({
|
||||
action: 'backup.verify',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'error',
|
||||
details: { message: err instanceof Error ? err.message : 'Verification failed' },
|
||||
});
|
||||
res.status(400).json({
|
||||
error: 'BACKUP_INVALID',
|
||||
message: err instanceof Error ? err.message : 'Backup verification failed',
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/restore',
|
||||
|
|
@ -148,14 +193,24 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
|
|||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
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?.();
|
||||
const maxBodyBytes = limits?.backupMaxBodyBytes ?? 16 * 1024 * 1024;
|
||||
const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64');
|
||||
if (rawBuf.length > maxBodyBytes) {
|
||||
res.status(413).json({
|
||||
error: 'PAYLOAD_TOO_LARGE',
|
||||
message: `Backup bundle exceeds limit (${maxBodyBytes} bytes)`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const passphrase = parsed.data.passphrase?.trim() || undefined;
|
||||
const runtimeKey = vaultService.exportMasterKeyHex() ?? undefined;
|
||||
const masterKey = parsed.data.masterKey?.trim() || runtimeKey;
|
||||
|
|
@ -163,12 +218,14 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
|
|||
|
||||
const wasWatching = await configManager.pauseWatcher();
|
||||
try {
|
||||
const restored = restoreBackupBundle(rawBuf, {
|
||||
const restored = await restoreBackupBundleAsync(rawBuf, {
|
||||
dataDir,
|
||||
db,
|
||||
masterKey,
|
||||
passphrase,
|
||||
vaultMasterKey,
|
||||
scryptConcurrency: limits?.scryptConcurrency,
|
||||
maxGunzipBytes: limits?.backupMaxGunzipBytes,
|
||||
});
|
||||
|
||||
await onRestored({
|
||||
|
|
@ -192,6 +249,7 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
|
|||
|
||||
res.json({ restored: true, summary: restored.summary });
|
||||
} catch (err) {
|
||||
if (err instanceof BackupBusyError) throw err;
|
||||
auditService.log({
|
||||
action: 'backup.restore',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
|
|
@ -209,8 +267,44 @@ export function createBackupRouter(deps: BackupRouterDeps): Router {
|
|||
await configManager.resumeWatcher();
|
||||
}
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
router.get('/schedule', requireAuth(authService), (_req, res) => {
|
||||
if (!backupScheduler) {
|
||||
res.status(404).json({ error: 'SCHEDULER_UNAVAILABLE' });
|
||||
return;
|
||||
}
|
||||
res.json({ schedule: backupScheduler.getStatus() });
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/schedule/run',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
asyncHandler(async (_req, res) => {
|
||||
if (!backupScheduler) {
|
||||
res.status(404).json({ error: 'SCHEDULER_UNAVAILABLE' });
|
||||
return;
|
||||
}
|
||||
const outcome = await backupScheduler.runNow('manual');
|
||||
res.status(outcome.ok ? 200 : 400).json({
|
||||
...outcome,
|
||||
schedule: backupScheduler.getStatus(),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
router.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {
|
||||
if (err instanceof BackupBusyError) {
|
||||
res.setHeader('Retry-After', '2');
|
||||
res.status(503).json({ error: err.code, message: err.message });
|
||||
return;
|
||||
}
|
||||
next(err);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,23 +1,36 @@
|
|||
import { Router } from 'express';
|
||||
import crypto from 'node:crypto';
|
||||
import { Router, type RequestHandler } from 'express';
|
||||
import { ZodError, z } from 'zod';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import { sha256Hex, type AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
requireStepUp,
|
||||
} from '../../security/guards.js';
|
||||
|
||||
export interface ConfigRouterDeps {
|
||||
authService: AuthService;
|
||||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
stepUpGuard?: RequestHandler;
|
||||
}
|
||||
|
||||
function isStepUpSensitiveConfigPath(rawPath: string): boolean {
|
||||
const norm = rawPath.replace(/\\/g, '/').replace(/^\/+/, '');
|
||||
return norm === 'settings.json' || norm === 'alerts.json' || norm.startsWith('servers/');
|
||||
}
|
||||
|
||||
export function createConfigRouter(deps: ConfigRouterDeps): Router {
|
||||
const router = Router();
|
||||
const { authService, configManager, auditService } = deps;
|
||||
const {
|
||||
authService,
|
||||
configManager,
|
||||
auditService,
|
||||
stepUpGuard = requireStepUp,
|
||||
} = deps;
|
||||
|
||||
router.get('/overview', requireAuth(authService), (_req, res) => {
|
||||
res.json({
|
||||
|
|
@ -63,38 +76,46 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router {
|
|||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const saved = configManager.saveConfigText(
|
||||
parsed.data.path,
|
||||
parsed.data.content,
|
||||
'ui',
|
||||
parsed.data.summary,
|
||||
);
|
||||
auditService.log({
|
||||
action: 'config.save',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: saved.filePath,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json(saved);
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'CONFIG_SCHEMA_ERROR',
|
||||
message: 'Schema validation failed',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
const executeSave = () => {
|
||||
try {
|
||||
const saved = configManager.saveConfigText(
|
||||
parsed.data.path,
|
||||
parsed.data.content,
|
||||
'ui',
|
||||
parsed.data.summary,
|
||||
);
|
||||
auditService.log({
|
||||
action: 'config.save',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: saved.filePath,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json(saved);
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'CONFIG_SCHEMA_ERROR',
|
||||
message: 'Schema validation failed',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'CONFIG_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save config file',
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'CONFIG_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save config file',
|
||||
});
|
||||
};
|
||||
|
||||
if (isStepUpSensitiveConfigPath(parsed.data.path)) {
|
||||
stepUpGuard(req, res, executeSave);
|
||||
return;
|
||||
}
|
||||
executeSave();
|
||||
});
|
||||
|
||||
router.delete(
|
||||
|
|
@ -108,26 +129,34 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router {
|
|||
res.status(400).json({ error: 'MISSING_PATH' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const deleted = configManager.deleteEntityFile(filePath);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'CONFIG_NOT_FOUND' });
|
||||
return;
|
||||
const executeDelete = () => {
|
||||
try {
|
||||
const deleted = configManager.deleteEntityFile(filePath);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'CONFIG_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
auditService.log({
|
||||
action: 'config.delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: filePath,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'CONFIG_DELETE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to delete config file',
|
||||
});
|
||||
}
|
||||
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',
|
||||
});
|
||||
};
|
||||
|
||||
if (isStepUpSensitiveConfigPath(filePath)) {
|
||||
stepUpGuard(req, res, executeDelete);
|
||||
return;
|
||||
}
|
||||
executeDelete();
|
||||
},
|
||||
);
|
||||
|
||||
|
|
@ -174,23 +203,83 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router {
|
|||
res.status(400).json({ error: 'INVALID_REVISION_ID' });
|
||||
return;
|
||||
}
|
||||
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) {
|
||||
const rev = configManager.getRevision(id);
|
||||
if (!rev) {
|
||||
res.status(400).json({
|
||||
error: 'ROLLBACK_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Rollback failed',
|
||||
message: `Revision #${id} not found`,
|
||||
});
|
||||
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,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ import {
|
|||
import type { VaultService } from '../../security/vault.js';
|
||||
import type { KeyManager } from '../../ssh/key-manager.js';
|
||||
import type { KnownHostsService } from '../../ssh/known-hosts.js';
|
||||
import { parseOpenSshConfig } from '../../ssh/ssh-config-import.js';
|
||||
import type { SSHPool } from '../../ssh/ssh-pool.js';
|
||||
|
||||
export interface ServersRouterDeps {
|
||||
|
|
@ -78,22 +79,173 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const hostPort = typeof req.query.hostPort === 'string' ? req.query.hostPort : '';
|
||||
const algorithm =
|
||||
typeof req.query.algorithm === 'string' && req.query.algorithm.trim()
|
||||
? req.query.algorithm.trim()
|
||||
: undefined;
|
||||
if (!hostPort) {
|
||||
res.status(400).json({ error: 'MISSING_HOST_PORT' });
|
||||
return;
|
||||
}
|
||||
const deleted = knownHosts.deleteKnownHost(hostPort);
|
||||
const deleted = knownHosts.deleteKnownHost(hostPort, algorithm);
|
||||
auditService.log({
|
||||
action: 'ssh.known_host_delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: hostPort,
|
||||
target: algorithm ? `${hostPort} (${algorithm})` : hostPort,
|
||||
status: deleted ? 'ok' : 'error',
|
||||
});
|
||||
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(
|
||||
'/rotate-keys',
|
||||
requireAuth(authService),
|
||||
|
|
@ -148,113 +300,142 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
router.post('/', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
try {
|
||||
const parsed = ServerConfigSchema.parse(req.body);
|
||||
const saved = configManager.saveConfigText(
|
||||
`servers/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Registered server via UI',
|
||||
);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.create',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({
|
||||
server: saved.config,
|
||||
warnings: saved.warnings,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid server configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
router.post(
|
||||
'/',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
try {
|
||||
const parsed = ServerConfigSchema.parse(req.body);
|
||||
if (hasJumpCycle(parsed.id, parsed.jumpHostId)) {
|
||||
res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' });
|
||||
return;
|
||||
}
|
||||
const saved = configManager.saveConfigText(
|
||||
`servers/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Registered server via UI',
|
||||
);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.create',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'SERVER_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save server',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
try {
|
||||
const parsed = ServerConfigSchema.parse({
|
||||
...(req.body ?? {}),
|
||||
id: req.params.id,
|
||||
});
|
||||
const saved = configManager.saveConfigText(
|
||||
`servers/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Updated server via UI',
|
||||
);
|
||||
sshPool.closeServer(parsed.id);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.update',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ server: saved.config, warnings: saved.warnings });
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid server configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
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({
|
||||
error: 'SERVER_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save server',
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'SERVER_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to update server',
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
router.delete('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
const deleted = configManager.deleteEntityFile(`servers/${id}.json`);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||
return;
|
||||
router.put(
|
||||
'/:id',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
try {
|
||||
const parsed = ServerConfigSchema.parse({
|
||||
...(req.body ?? {}),
|
||||
id: req.params.id,
|
||||
});
|
||||
if (hasJumpCycle(parsed.id, parsed.jumpHostId)) {
|
||||
res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' });
|
||||
return;
|
||||
}
|
||||
const saved = configManager.saveConfigText(
|
||||
`servers/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Updated server via UI',
|
||||
);
|
||||
sshPool.closeServer(parsed.id);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.update',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ server: saved.config, warnings: saved.warnings });
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid server configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'SERVER_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to update 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.delete(
|
||||
'/:id',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
const deleted = configManager.deleteEntityFile(`servers/${id}.json`);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
sshPool.closeServer(id);
|
||||
knownHosts.clearServerPending(id);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'SERVER_DELETE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to delete server',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/:id/reconnect',
|
||||
|
|
@ -286,6 +467,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z.object({ fingerprint: z.string().min(1) }).safeParse(req.body);
|
||||
|
|
@ -366,23 +548,140 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
});
|
||||
});
|
||||
|
||||
router.get('/:id/inspect', requireAuth(authService), async (req, res) => {
|
||||
router.get('/:id/inspect', requireAuth(authService), (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
if (!configManager.getServer(id)) {
|
||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await serverInspector.inspect(id);
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
res.status(502).json({
|
||||
error: 'INSPECT_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Server inspection failed',
|
||||
const sort = String(req.query.sort ?? 'cpu') === 'mem' ? 'mem' : 'cpu';
|
||||
const useSudo = req.query.sudo === 'true' || req.query.sudo === '1';
|
||||
|
||||
const executeInspect = async () => {
|
||||
try {
|
||||
const result = await serverInspector.inspect(id, { sort, useSudo });
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
res.status(502).json({
|
||||
error: 'INSPECT_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Server inspection failed',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (useSudo) {
|
||||
stepUpGuard(req, res, () => {
|
||||
void executeInspect();
|
||||
});
|
||||
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) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
if (!configManager.getServer(id)) {
|
||||
|
|
@ -405,6 +704,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z.object({ credentialId: EntityIdSchema }).safeParse(req.body);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Router, type Response } from 'express';
|
||||
import { Router, type NextFunction, type Request, type RequestHandler, type Response } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
|
|
@ -7,6 +7,7 @@ import {
|
|||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
requireStepUp,
|
||||
} from '../../security/guards.js';
|
||||
import { SftpServiceError, type SftpService } from '../../ssh/sftp-service.js';
|
||||
|
||||
|
|
@ -15,6 +16,16 @@ export interface SftpRouterDeps {
|
|||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
sftpService: SftpService;
|
||||
stepUpGuard?: RequestHandler;
|
||||
}
|
||||
|
||||
function buildContentDisposition(fileName: string): string {
|
||||
const asciiFallback = fileName.replace(/[^\x20-\x7e]|["\\;]/g, '_');
|
||||
const rfc5987 = encodeURIComponent(fileName).replace(
|
||||
/['()*!]/g,
|
||||
(c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||
);
|
||||
return `attachment; filename="${asciiFallback}"; filename*=UTF-8''${rfc5987}`;
|
||||
}
|
||||
|
||||
function sendSftpError(res: Response, err: unknown): void {
|
||||
|
|
@ -22,7 +33,7 @@ function sendSftpError(res: Response, err: unknown): void {
|
|||
const status =
|
||||
err.code === 'NOT_FOUND'
|
||||
? 404
|
||||
: err.code === 'CONFLICT'
|
||||
: err.code === 'CONFLICT' || err.code === 'ALREADY_EXISTS'
|
||||
? 409
|
||||
: err.code === 'FILE_TOO_LARGE'
|
||||
? 413
|
||||
|
|
@ -37,7 +48,13 @@ function sendSftpError(res: Response, err: unknown): void {
|
|||
|
||||
export function createSftpRouter(deps: SftpRouterDeps): Router {
|
||||
const router = Router({ mergeParams: true });
|
||||
const { authService, configManager, auditService, sftpService } = deps;
|
||||
const {
|
||||
authService,
|
||||
configManager,
|
||||
auditService,
|
||||
sftpService,
|
||||
stepUpGuard = requireStepUp,
|
||||
} = deps;
|
||||
|
||||
const ensureServer = (serverId: string, res: Response): boolean => {
|
||||
if (!configManager.getServer(serverId)) {
|
||||
|
|
@ -47,6 +64,18 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
return true;
|
||||
};
|
||||
|
||||
const conditionalSudoStepUp = (req: Request, res: Response, next: NextFunction) => {
|
||||
const wantsSudo =
|
||||
req.query.sudo === '1' ||
|
||||
req.query.sudo === 'true' ||
|
||||
Boolean((req.body as { sudo?: unknown } | undefined)?.sudo);
|
||||
if (!wantsSudo) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
stepUpGuard(req, res, next);
|
||||
};
|
||||
|
||||
router.get('/list', requireAuth(authService), async (req, res) => {
|
||||
const serverId = String(req.params.id ?? '');
|
||||
if (!ensureServer(serverId, res)) return;
|
||||
|
|
@ -75,6 +104,24 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
}
|
||||
});
|
||||
|
||||
router.get('/search', requireAuth(authService), async (req, res) => {
|
||||
const serverId = String(req.params.id ?? '');
|
||||
if (!ensureServer(serverId, res)) return;
|
||||
const basePath = typeof req.query.path === 'string' ? req.query.path : '/';
|
||||
const q = typeof req.query.q === 'string' ? req.query.q : '';
|
||||
const max = req.query.max ? Number(req.query.max) : 100;
|
||||
if (!q.trim()) {
|
||||
res.status(400).json({ error: 'MISSING_QUERY' });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await sftpService.searchFiles(serverId, basePath, q, Number.isFinite(max) ? max : 100);
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
sendSftpError(res, err);
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/download', requireAuth(authService), async (req, res) => {
|
||||
const serverId = String(req.params.id ?? '');
|
||||
if (!ensureServer(serverId, res)) return;
|
||||
|
|
@ -86,9 +133,9 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
|
||||
try {
|
||||
const dl = await sftpService.openDownloadStream(serverId, targetPath);
|
||||
const safeName = dl.fileName.replace(/["\r\n\\]/g, '_');
|
||||
res.setHeader('Content-Type', 'application/octet-stream');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${safeName}"`);
|
||||
res.setHeader('Content-Disposition', buildContentDisposition(dl.fileName));
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
if (Number.isFinite(dl.size)) {
|
||||
res.setHeader('Content-Length', String(dl.size));
|
||||
}
|
||||
|
|
@ -127,11 +174,9 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
try {
|
||||
const arch = await sftpService.streamDirectoryArchive(serverId, targetPath, format);
|
||||
res.setHeader('Content-Type', 'application/octet-stream');
|
||||
res.setHeader(
|
||||
'Content-Disposition',
|
||||
`attachment; filename="${arch.archiveFileName}"`,
|
||||
);
|
||||
res.setHeader('Content-Disposition', buildContentDisposition(arch.archiveFileName));
|
||||
res.setHeader('X-Archive-Format', arch.resolvedFormat);
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
|
||||
res.once('close', () => {
|
||||
if (!res.writableEnded) {
|
||||
|
|
@ -183,6 +228,35 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/touch',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const serverId = String(req.params.id ?? '');
|
||||
if (!ensureServer(serverId, res)) return;
|
||||
const parsed = z.object({ path: z.string().min(1) }).safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const created = await sftpService.touchFile(serverId, parsed.data.path);
|
||||
auditService.log({
|
||||
action: 'sftp.touch',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: `${serverId}:${created}`,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({ ok: true, path: created });
|
||||
} catch (err) {
|
||||
sendSftpError(res, err);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/mkdir',
|
||||
requireAuth(authService),
|
||||
|
|
@ -221,7 +295,11 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
const serverId = String(req.params.id ?? '');
|
||||
if (!ensureServer(serverId, res)) return;
|
||||
const parsed = z
|
||||
.object({ fromPath: z.string().min(1), toPath: z.string().min(1) })
|
||||
.object({
|
||||
fromPath: z.string().min(1),
|
||||
toPath: z.string().min(1),
|
||||
overwrite: z.boolean().optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
|
|
@ -232,6 +310,7 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
serverId,
|
||||
parsed.data.fromPath,
|
||||
parsed.data.toPath,
|
||||
Boolean(parsed.data.overwrite),
|
||||
);
|
||||
auditService.log({
|
||||
action: 'sftp.rename',
|
||||
|
|
@ -283,6 +362,50 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/chown',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const serverId = String(req.params.id ?? '');
|
||||
if (!ensureServer(serverId, res)) return;
|
||||
const parsed = z
|
||||
.object({
|
||||
path: z.string().min(1),
|
||||
uid: z.number().int().min(0),
|
||||
gid: z.number().int().min(0),
|
||||
sudo: z.boolean().optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await sftpService.chown(
|
||||
serverId,
|
||||
parsed.data.path,
|
||||
parsed.data.uid,
|
||||
parsed.data.gid,
|
||||
Boolean(parsed.data.sudo),
|
||||
);
|
||||
auditService.log({
|
||||
action: 'sftp.chown',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: `${serverId}:${result.path}`,
|
||||
status: 'ok',
|
||||
details: { uid: result.uid, gid: result.gid, sudo: Boolean(parsed.data.sudo) },
|
||||
});
|
||||
res.json({ ok: true, ...result });
|
||||
} catch (err) {
|
||||
sendSftpError(res, err);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/entry',
|
||||
requireAuth(authService),
|
||||
|
|
@ -314,7 +437,42 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
router.get('/text', requireAuth(authService), async (req, res) => {
|
||||
router.post(
|
||||
'/bulk-delete',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const serverId = String(req.params.id ?? '');
|
||||
if (!ensureServer(serverId, res)) return;
|
||||
const parsed = z
|
||||
.object({
|
||||
paths: z.array(z.string().min(1)).min(1).max(100),
|
||||
recursive: z.boolean().optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
const result = await sftpService.bulkDelete(
|
||||
serverId,
|
||||
parsed.data.paths,
|
||||
Boolean(parsed.data.recursive),
|
||||
);
|
||||
auditService.log({
|
||||
action: 'sftp.bulk_delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: serverId,
|
||||
status: result.failed.length === 0 ? 'ok' : 'error',
|
||||
details: { count: result.deleted.length, failedCount: result.failed.length },
|
||||
});
|
||||
res.json(result);
|
||||
},
|
||||
);
|
||||
|
||||
router.get('/text', requireAuth(authService), conditionalSudoStepUp, async (req, res) => {
|
||||
const serverId = String(req.params.id ?? '');
|
||||
if (!ensureServer(serverId, res)) return;
|
||||
const targetPath = typeof req.query.path === 'string' ? req.query.path : '';
|
||||
|
|
@ -325,6 +483,15 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
}
|
||||
try {
|
||||
const file = await sftpService.readTextFile(serverId, targetPath, { sudo });
|
||||
if (sudo) {
|
||||
auditService.log({
|
||||
action: 'sftp.sudo_read',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: `${serverId}:${file.path}`,
|
||||
status: 'ok',
|
||||
});
|
||||
}
|
||||
res.json({ file });
|
||||
} catch (err) {
|
||||
sendSftpError(res, err);
|
||||
|
|
@ -336,6 +503,7 @@ export function createSftpRouter(deps: SftpRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
conditionalSudoStepUp,
|
||||
async (req, res) => {
|
||||
const serverId = String(req.params.id ?? '');
|
||||
if (!ensureServer(serverId, res)) return;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Router } from 'express';
|
||||
import { Router, type RequestHandler } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
|
|
@ -6,6 +6,7 @@ import {
|
|||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
requireStepUp,
|
||||
} from '../../security/guards.js';
|
||||
import type { CustomSystemsEngine } from '../../systems/systems-engine.js';
|
||||
|
||||
|
|
@ -13,11 +14,12 @@ export interface SystemsRouterDeps {
|
|||
authService: AuthService;
|
||||
auditService: AuditService;
|
||||
systemsEngine: CustomSystemsEngine;
|
||||
stepUpGuard?: RequestHandler;
|
||||
}
|
||||
|
||||
export function createSystemsRouter(deps: SystemsRouterDeps): Router {
|
||||
const router = Router();
|
||||
const { authService, auditService, systemsEngine } = deps;
|
||||
const { authService, auditService, systemsEngine, stepUpGuard = requireStepUp } = deps;
|
||||
|
||||
router.get('/', requireAuth(authService), (_req, res) => {
|
||||
res.json({ systems: systemsEngine.listSystemsOverview() });
|
||||
|
|
@ -153,7 +155,7 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
(req, res) => {
|
||||
const systemId = String(req.params.systemId ?? '');
|
||||
const serverId = String(req.params.serverId ?? '');
|
||||
const actionId = String(req.params.actionId ?? '');
|
||||
|
|
@ -161,6 +163,7 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router {
|
|||
.object({
|
||||
itemName: z.string().min(1).optional(),
|
||||
subItemName: z.string().min(1).optional(),
|
||||
inputs: z.record(z.unknown()).optional(),
|
||||
cols: z.number().int().min(10).max(500).optional(),
|
||||
rows: z.number().int().min(4).max(200).optional(),
|
||||
})
|
||||
|
|
@ -170,43 +173,75 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router {
|
|||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await systemsEngine.executeAction({
|
||||
serverId,
|
||||
systemId,
|
||||
actionId,
|
||||
...parsed.data,
|
||||
});
|
||||
auditService.log({
|
||||
action: 'system.action',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: `${serverId}:${systemId}:${actionId}`,
|
||||
status: 'ok',
|
||||
details: {
|
||||
itemName: parsed.data.itemName,
|
||||
subItemName: parsed.data.subItemName,
|
||||
mode: result.mode,
|
||||
},
|
||||
});
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'SYSTEM_ACTION_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to execute system action',
|
||||
const actionMeta = systemsEngine.getActionMeta(systemId, actionId);
|
||||
const execute = async () => {
|
||||
try {
|
||||
const result = await systemsEngine.executeAction({
|
||||
serverId,
|
||||
systemId,
|
||||
actionId,
|
||||
...parsed.data,
|
||||
});
|
||||
const secretInputKeys = new Set(
|
||||
(actionMeta?.inputs ?? []).filter((i) => i.type === 'secret').map((i) => i.name),
|
||||
);
|
||||
const sanitizedInputs = parsed.data.inputs
|
||||
? Object.fromEntries(
|
||||
Object.entries(parsed.data.inputs).map(([k, v]) => [
|
||||
k,
|
||||
secretInputKeys.has(k) ? '[REDACTED]' : v,
|
||||
]),
|
||||
)
|
||||
: undefined;
|
||||
auditService.log({
|
||||
action: 'system.action',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: `${serverId}:${systemId}:${actionId}`,
|
||||
status: 'ok',
|
||||
details: {
|
||||
itemName: parsed.data.itemName,
|
||||
subItemName: parsed.data.subItemName,
|
||||
inputs: sanitizedInputs,
|
||||
mode: result.mode,
|
||||
},
|
||||
});
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'SYSTEM_ACTION_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to execute system action',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (actionMeta?.confirm || actionMeta?.sudo) {
|
||||
stepUpGuard(req, res, () => {
|
||||
void execute();
|
||||
});
|
||||
return;
|
||||
}
|
||||
void execute();
|
||||
},
|
||||
);
|
||||
|
||||
// Cancelling a running stream must work even if Safe Mode was just toggled on
|
||||
router.post(
|
||||
'/streams/:jobId/cancel',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
(req, res) => {
|
||||
const jobId = String(req.params.jobId ?? '');
|
||||
res.json({ cancelled: systemsEngine.cancelStream(jobId) });
|
||||
const cancelled = systemsEngine.cancelStream(jobId);
|
||||
auditService.log({
|
||||
action: 'system.stream_cancel',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: jobId,
|
||||
status: 'ok',
|
||||
details: { cancelled },
|
||||
});
|
||||
res.json({ cancelled });
|
||||
},
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -37,7 +37,11 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router {
|
|||
serverId: EntityIdSchema,
|
||||
cols: z.number().int().min(10).max(500).optional(),
|
||||
rows: z.number().int().min(4).max(200).optional(),
|
||||
cwd: z.string().max(1024).optional(),
|
||||
cwd: z
|
||||
.string()
|
||||
.max(1024)
|
||||
.refine((v) => !/[\x00-\x1f\x7f]/.test(v), 'Control characters not permitted in cwd')
|
||||
.optional(),
|
||||
title: z.string().max(120).optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
|
|
@ -70,6 +74,36 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/sessions/:sessionId/reconnect',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const sessionId = String(req.params.sessionId ?? '');
|
||||
try {
|
||||
const session = await ptyManager.reconnectSession(sessionId);
|
||||
if (!session) {
|
||||
res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
auditService.log({
|
||||
action: 'pty.reconnect',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: `${session.serverId}:${sessionId}`,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ ok: true, session });
|
||||
} catch (err) {
|
||||
res.status(502).json({
|
||||
error: 'PTY_RECONNECT_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to reconnect PTY session',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/sessions/:sessionId/resize',
|
||||
requireAuth(authService),
|
||||
|
|
@ -98,7 +132,12 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router {
|
|||
|
||||
router.get('/sessions/:sessionId/export', requireAuth(authService), (req, res) => {
|
||||
const sessionId = String(req.params.sessionId ?? '');
|
||||
const format = req.query.format === 'ansi' ? 'ansi' : 'plain';
|
||||
const format =
|
||||
req.query.format === 'ansi'
|
||||
? 'ansi'
|
||||
: req.query.format === 'cast'
|
||||
? 'cast'
|
||||
: 'plain';
|
||||
const exported = ptyManager.exportScrollback(sessionId, format);
|
||||
if (!exported) {
|
||||
res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' });
|
||||
|
|
@ -106,8 +145,9 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router {
|
|||
}
|
||||
|
||||
const safeFile = exported.filename.replace(/[^A-Za-z0-9._-]/g, '_');
|
||||
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
|
||||
res.setHeader('Content-Type', exported.contentType);
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${safeFile}"`);
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.send(exported.content);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import {
|
|||
requireAuth,
|
||||
requireCsrf,
|
||||
} from '../../security/guards.js';
|
||||
import type { TunnelManager } from '../../ssh/tunnel-manager.js';
|
||||
import { ProxyIsolationError, type TunnelManager } from '../../ssh/tunnel-manager.js';
|
||||
|
||||
export interface TunnelsRouterDeps {
|
||||
authService: AuthService;
|
||||
|
|
@ -180,6 +180,46 @@ 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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import {
|
|||
import {
|
||||
computeOpenSshFingerprint,
|
||||
generateMasterKeyBuffer,
|
||||
validatePrivateKey,
|
||||
type VaultCredentialInput,
|
||||
type VaultService,
|
||||
} from '../../security/vault.js';
|
||||
|
|
@ -114,6 +115,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
type: 'vault:state',
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
vaultSealState: vaultService.sealState,
|
||||
isPanicLocked: vaultService.isPanicLocked,
|
||||
});
|
||||
};
|
||||
|
|
@ -122,43 +124,52 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
res.json({
|
||||
state: vaultService.state,
|
||||
runtimeReady: vaultService.isRuntimeReady,
|
||||
sealState: vaultService.sealState,
|
||||
isPanicLocked: vaultService.isPanicLocked,
|
||||
});
|
||||
});
|
||||
|
||||
vaultRouter.post('/init', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = vaultService.initializeNewVault(parsed.data.masterKey);
|
||||
notifyConfigReeval();
|
||||
onVaultUnlocked?.();
|
||||
onVaultChanged?.('vault-init');
|
||||
broadcastVaultState();
|
||||
auditService.log({
|
||||
action: 'vault.init',
|
||||
actorIp: ip,
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({
|
||||
state: vaultService.state,
|
||||
runtimeReady: vaultService.isRuntimeReady,
|
||||
generatedKeyHex: result.generatedKeyHex,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'VAULT_INIT_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Vault initialization failed',
|
||||
});
|
||||
}
|
||||
});
|
||||
vaultRouter.post(
|
||||
'/init',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = vaultService.initializeNewVault(parsed.data.masterKey);
|
||||
notifyConfigReeval();
|
||||
onVaultUnlocked?.();
|
||||
onVaultChanged?.('vault-init');
|
||||
broadcastVaultState();
|
||||
auditService.log({
|
||||
action: 'vault.init',
|
||||
actorIp: ip,
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({
|
||||
state: vaultService.state,
|
||||
runtimeReady: vaultService.isRuntimeReady,
|
||||
sealState: vaultService.sealState,
|
||||
generatedKeyHex: result.generatedKeyHex,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'VAULT_INIT_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Vault initialization failed',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
|
|
@ -191,6 +202,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
res.json({
|
||||
state: vaultService.state,
|
||||
runtimeReady: vaultService.isRuntimeReady,
|
||||
sealState: vaultService.sealState,
|
||||
isPanicLocked: vaultService.isPanicLocked,
|
||||
});
|
||||
} catch (err) {
|
||||
|
|
@ -231,6 +243,7 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
res.json({
|
||||
state: vaultService.state,
|
||||
runtimeReady: vaultService.isRuntimeReady,
|
||||
sealState: vaultService.sealState,
|
||||
isPanicLocked: vaultService.isPanicLocked,
|
||||
});
|
||||
} catch (err) {
|
||||
|
|
@ -254,10 +267,35 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
res.json({
|
||||
state: vaultService.state,
|
||||
runtimeReady: vaultService.isRuntimeReady,
|
||||
sealState: vaultService.sealState,
|
||||
isPanicLocked: vaultService.isPanicLocked,
|
||||
});
|
||||
});
|
||||
|
||||
vaultRouter.post(
|
||||
'/seal',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
vaultService.seal();
|
||||
broadcastVaultState();
|
||||
auditService.log({
|
||||
action: 'vault.seal',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({
|
||||
state: vaultService.state,
|
||||
runtimeReady: vaultService.isRuntimeReady,
|
||||
sealState: vaultService.sealState,
|
||||
isPanicLocked: vaultService.isPanicLocked,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Panic Lock is ALWAYS reachable when authenticated + CSRF verified (even under Safe Mode!)
|
||||
panicLockHandler.post('/panic-lock', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
const session = req.authSession!;
|
||||
|
|
@ -299,6 +337,13 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
requireAuth(authService),
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
if (req.authSession?.safeMode || req.headers['x-gcoord-safe-mode'] === '1') {
|
||||
res.status(423).json({
|
||||
error: 'SAFE_MODE_ACTIVE',
|
||||
message: 'Disable Safe / Read-Only Mode before revealing secrets.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (vaultService.state !== 'unlocked') {
|
||||
res.status(423).json({ error: 'VAULT_LOCKED' });
|
||||
return;
|
||||
|
|
@ -337,15 +382,27 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
return;
|
||||
}
|
||||
const credInput: VaultCredentialInput = { ...parsed.data };
|
||||
if (
|
||||
credInput.type === 'ssh-key' &&
|
||||
credInput.publicKey &&
|
||||
!credInput.fingerprint
|
||||
) {
|
||||
if (credInput.type === 'ssh-key') {
|
||||
try {
|
||||
credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey);
|
||||
} catch {
|
||||
// Leave fingerprint omitted if user imported an unusual public key format
|
||||
validatePrivateKey(credInput.privateKey, credInput.passphrase);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'INVALID_SSH_KEY',
|
||||
message: err instanceof Error ? err.message : 'Invalid SSH private key',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (credInput.publicKey) {
|
||||
try {
|
||||
credInput.publicKey = credInput.publicKey.trim();
|
||||
credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'INVALID_SSH_PUBLIC_KEY',
|
||||
message: err instanceof Error ? err.message : 'Invalid SSH public key',
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
const meta = vaultService.upsertCredential(credInput);
|
||||
|
|
@ -381,15 +438,27 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
return;
|
||||
}
|
||||
const credInput: VaultCredentialInput = { ...parsed.data };
|
||||
if (
|
||||
credInput.type === 'ssh-key' &&
|
||||
credInput.publicKey &&
|
||||
!credInput.fingerprint
|
||||
) {
|
||||
if (credInput.type === 'ssh-key') {
|
||||
try {
|
||||
credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey);
|
||||
} catch {
|
||||
// Ignore non-standard public key strings
|
||||
validatePrivateKey(credInput.privateKey, credInput.passphrase);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'INVALID_SSH_KEY',
|
||||
message: err instanceof Error ? err.message : 'Invalid SSH private key',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (credInput.publicKey) {
|
||||
try {
|
||||
credInput.publicKey = credInput.publicKey.trim();
|
||||
credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'INVALID_SSH_PUBLIC_KEY',
|
||||
message: err instanceof Error ? err.message : 'Invalid SSH public key',
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
const meta = vaultService.upsertCredential(credInput);
|
||||
|
|
@ -495,6 +564,12 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
sessionIdHash: req.authSession!.idHash,
|
||||
expiresAt,
|
||||
};
|
||||
auditService.log({
|
||||
action: 'vault.rotate_key.prepare',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ candidateKeyHex, confirmToken, expiresAt });
|
||||
},
|
||||
);
|
||||
|
|
@ -510,10 +585,17 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
res.status(423).json({ error: 'VAULT_LOCKED' });
|
||||
return;
|
||||
}
|
||||
const ip = req.clientIp ?? 'unknown';
|
||||
const rate = rateLimiter.check('vault-rotate-commit', ip);
|
||||
if (!rate.allowed) {
|
||||
res.setHeader('Retry-After', String(rate.retryAfterSec));
|
||||
res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec });
|
||||
return;
|
||||
}
|
||||
const parsed = z
|
||||
.object({
|
||||
confirmToken: z.string().min(1),
|
||||
confirmedKeyHex: z.string().min(1).optional(),
|
||||
confirmedKeyHex: z.string().min(64).max(64),
|
||||
})
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
|
|
@ -521,32 +603,57 @@ export function createVaultRouter(deps: VaultRouterDeps): {
|
|||
return;
|
||||
}
|
||||
|
||||
const timingEq = (a: string, b: string) => {
|
||||
const ba = Buffer.from(a, 'utf8');
|
||||
const bb = Buffer.from(b, 'utf8');
|
||||
return ba.length === bb.length && crypto.timingSafeEqual(ba, bb);
|
||||
};
|
||||
|
||||
if (
|
||||
!pendingRotation ||
|
||||
pendingRotation.expiresAt <= Date.now() ||
|
||||
pendingRotation.sessionIdHash !== req.authSession!.idHash ||
|
||||
pendingRotation.confirmToken !== parsed.data.confirmToken
|
||||
!timingEq(pendingRotation.confirmToken, parsed.data.confirmToken)
|
||||
) {
|
||||
pendingRotation = null;
|
||||
rateLimiter.recordFailure('vault-rotate-commit', ip);
|
||||
auditService.log({
|
||||
action: 'vault.rotate_key.commit',
|
||||
actorIp: ip,
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'denied',
|
||||
});
|
||||
res.status(400).json({ error: 'ROTATION_TOKEN_INVALID_OR_EXPIRED' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
parsed.data.confirmedKeyHex &&
|
||||
parsed.data.confirmedKeyHex.trim().toLowerCase() !==
|
||||
pendingRotation.candidateKeyHex.toLowerCase()
|
||||
!timingEq(
|
||||
parsed.data.confirmedKeyHex.trim().toLowerCase(),
|
||||
pendingRotation.candidateKeyHex.toLowerCase(),
|
||||
)
|
||||
) {
|
||||
pendingRotation = null;
|
||||
rateLimiter.recordFailure('vault-rotate-commit', ip);
|
||||
auditService.log({
|
||||
action: 'vault.rotate_key.commit',
|
||||
actorIp: ip,
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'denied',
|
||||
details: { reason: 'key_confirmation_mismatch' },
|
||||
});
|
||||
res.status(400).json({ error: 'KEY_CONFIRMATION_MISMATCH' });
|
||||
return;
|
||||
}
|
||||
|
||||
rateLimiter.recordSuccess('vault-rotate-commit', ip);
|
||||
const nextHex = pendingRotation.candidateKeyHex;
|
||||
pendingRotation = null;
|
||||
vaultService.rotateMasterKey(nextHex);
|
||||
onVaultChanged?.('master-key-rotation');
|
||||
auditService.log({
|
||||
action: 'vault.rotate_key',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
actorIp: ip,
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
status: 'ok',
|
||||
});
|
||||
|
|
|
|||
|
|
@ -147,7 +147,8 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
|
|||
});
|
||||
|
||||
router.get('/runs/:runId', requireAuth(authService), (req, res) => {
|
||||
const detail = workflowEngine.getRunDetail(String(req.params.runId ?? ''));
|
||||
const includeLogs = req.query.includeLogs !== 'false' && req.query.includeLogs !== '0';
|
||||
const detail = workflowEngine.getRunDetail(String(req.params.runId ?? ''), { includeLogs });
|
||||
if (!detail) {
|
||||
res.status(404).json({ error: 'RUN_NOT_FOUND' });
|
||||
return;
|
||||
|
|
@ -155,11 +156,20 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
|
|||
res.json(detail);
|
||||
});
|
||||
|
||||
router.get('/runs/:runId/steps/:stepId/logs', requireAuth(authService), (req, res) => {
|
||||
const runId = String(req.params.runId ?? '');
|
||||
const stepId = String(req.params.stepId ?? '');
|
||||
const offset = Number(req.query.offset) || 0;
|
||||
const limit = Number(req.query.limit) || 50;
|
||||
const result = workflowEngine.getStepLogs(runId, { stepId, offset, limit });
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
// Cancelling a running workflow must remain available under Safe Mode
|
||||
router.post(
|
||||
'/runs/:runId/cancel',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
(req, res) => {
|
||||
const runId = String(req.params.runId ?? '');
|
||||
const cancelled = workflowEngine.cancelRun(runId, 'admin');
|
||||
|
|
@ -248,6 +258,7 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
|
|||
}),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
|
|
@ -269,6 +280,24 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
router.get('/broadcast/history', requireAuth(authService), (req, res) => {
|
||||
const limit = Number(req.query.limit) || 50;
|
||||
res.json({ jobs: broadcastService.listHistory(limit) });
|
||||
});
|
||||
|
||||
router.get('/broadcast/:jobId/export', requireAuth(authService), (req, res) => {
|
||||
const jobId = String(req.params.jobId ?? '');
|
||||
const format = String(req.query.format ?? 'json') === 'csv' ? 'csv' : 'json';
|
||||
const exported = broadcastService.exportBroadcast(jobId, format);
|
||||
if (!exported) {
|
||||
res.status(404).json({ error: 'BROADCAST_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
res.setHeader('Content-Type', exported.contentType);
|
||||
res.setHeader('Content-Disposition', `attachment; filename="${exported.filename}"`);
|
||||
res.send(exported.body);
|
||||
});
|
||||
|
||||
router.get('/broadcast/:jobId', requireAuth(authService), (req, res) => {
|
||||
const job = broadcastService.getBroadcastResult(String(req.params.jobId ?? ''));
|
||||
if (!job) {
|
||||
|
|
@ -278,14 +307,22 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
|
|||
res.json({ job });
|
||||
});
|
||||
|
||||
// Cancelling a running broadcast must remain available under Safe Mode
|
||||
router.post(
|
||||
'/broadcast/:jobId/cancel',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
(req, res) => {
|
||||
const jobId = String(req.params.jobId ?? '');
|
||||
res.json({ cancelled: broadcastService.cancelBroadcast(jobId) });
|
||||
const cancelled = broadcastService.cancelBroadcast(jobId);
|
||||
auditService.log({
|
||||
action: 'broadcast.cancel',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: jobId,
|
||||
status: cancelled ? 'ok' : 'error',
|
||||
});
|
||||
res.json({ cancelled });
|
||||
},
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -5,10 +5,18 @@ import {
|
|||
ClientWsFrameSchema,
|
||||
type ServerWsFrame,
|
||||
} from '../../shared/ws-protocol.js';
|
||||
import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js';
|
||||
import {
|
||||
SESSION_COOKIE_NAME,
|
||||
type AuthService,
|
||||
type AuthSession,
|
||||
} from '../security/auth.js';
|
||||
import { extractCookies } from '../security/guards.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
|
||||
const WS_MAX_PAYLOAD_BYTES = 128 * 1024;
|
||||
const WS_SOFT_BACKPRESSURE_BYTES = 1024 * 1024;
|
||||
const WS_HARD_BACKPRESSURE_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
interface WsClientMeta {
|
||||
ws: WebSocket;
|
||||
sessionToken: string;
|
||||
|
|
@ -42,25 +50,42 @@ export interface WsAiHandlers {
|
|||
}
|
||||
|
||||
export class WsHub {
|
||||
private readonly wss = new WebSocketServer({ noServer: true });
|
||||
private readonly wss = new WebSocketServer({
|
||||
noServer: true,
|
||||
maxPayload: WS_MAX_PAYLOAD_BYTES,
|
||||
});
|
||||
private readonly clients = new Set<WsClientMeta>();
|
||||
private readonly pingTimer: NodeJS.Timeout;
|
||||
private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = [];
|
||||
private readonly hostUpgradeHandlers: Array<(req: IncomingMessage, socket: Duplex, head: Buffer) => boolean> = [];
|
||||
private readonly subscribeListeners = new Set<WsSubscribeListener>();
|
||||
private ptyHandlers: WsPtyHandlers | null = null;
|
||||
private aiHandlers: WsAiHandlers | null = null;
|
||||
private readonly trustCloudflare: boolean;
|
||||
|
||||
constructor(
|
||||
httpServer: HttpServer,
|
||||
private readonly authService: AuthService,
|
||||
private readonly vaultService: VaultService,
|
||||
options: { trustCloudflare?: boolean } = {},
|
||||
) {
|
||||
this.trustCloudflare = Boolean(options.trustCloudflare);
|
||||
httpServer.on('upgrade', (req, socket, head) => {
|
||||
this.handleUpgrade(req, socket, head);
|
||||
});
|
||||
|
||||
this.pingTimer = setInterval(() => {
|
||||
for (const client of this.clients) {
|
||||
const session = this.authService.getSessionByToken(client.sessionToken);
|
||||
if (!session) {
|
||||
try {
|
||||
client.ws.close(4001, 'Session expired');
|
||||
} catch {
|
||||
client.ws.terminate();
|
||||
}
|
||||
this.clients.delete(client);
|
||||
continue;
|
||||
}
|
||||
if (!client.alive) {
|
||||
client.ws.terminate();
|
||||
this.clients.delete(client);
|
||||
|
|
@ -73,10 +98,34 @@ export class WsHub {
|
|||
this.pingTimer.unref();
|
||||
}
|
||||
|
||||
disconnectSessions(idHashes: string[]): void {
|
||||
if (idHashes.length === 0) return;
|
||||
const targetSet = new Set(idHashes);
|
||||
for (const client of this.clients) {
|
||||
if (!targetSet.has(client.sessionIdHash)) continue;
|
||||
try {
|
||||
if (client.ws.readyState === WebSocket.OPEN) {
|
||||
client.ws.close(4001, 'Session revoked');
|
||||
} else {
|
||||
client.ws.terminate();
|
||||
}
|
||||
} catch {
|
||||
// Ignore close errors
|
||||
}
|
||||
this.clients.delete(client);
|
||||
}
|
||||
}
|
||||
|
||||
registerUpgradeHandler(prefix: string, handler: WsUpgradeHandler): void {
|
||||
this.upgradeHandlers.push({ prefix, handler });
|
||||
}
|
||||
|
||||
registerHostUpgradeHandler(
|
||||
matcherHandler: (req: IncomingMessage, socket: Duplex, head: Buffer) => boolean,
|
||||
): void {
|
||||
this.hostUpgradeHandlers.push(matcherHandler);
|
||||
}
|
||||
|
||||
onChannelSubscribe(listener: WsSubscribeListener): () => void {
|
||||
this.subscribeListeners.add(listener);
|
||||
return () => {
|
||||
|
|
@ -118,21 +167,18 @@ export class WsHub {
|
|||
|
||||
broadcastAll(frame: ServerWsFrame): void {
|
||||
const text = JSON.stringify(frame);
|
||||
const critical = frame.type === 'security:panic-lock' || frame.type === 'vault:state';
|
||||
for (const client of this.clients) {
|
||||
if (client.ws.readyState === WebSocket.OPEN) {
|
||||
client.ws.send(text);
|
||||
}
|
||||
this.safeSendRaw(client, text, critical);
|
||||
}
|
||||
}
|
||||
|
||||
broadcastChannel(channel: string, frame: ServerWsFrame): void {
|
||||
const text = JSON.stringify(frame);
|
||||
const critical = frame.type === 'pty:exit' || frame.type === 'error';
|
||||
for (const client of this.clients) {
|
||||
if (
|
||||
client.ws.readyState === WebSocket.OPEN &&
|
||||
(client.channels.has(channel) || client.channels.has('*'))
|
||||
) {
|
||||
client.ws.send(text);
|
||||
if (client.channels.has(channel)) {
|
||||
this.safeSendRaw(client, text, critical);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -142,6 +188,11 @@ export class WsHub {
|
|||
socket: Duplex,
|
||||
head: Buffer,
|
||||
): void {
|
||||
for (const matcher of this.hostUpgradeHandlers) {
|
||||
if (matcher(req, socket, head)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const urlPath = (req.url ?? '').split('?')[0] ?? '';
|
||||
for (const entry of this.upgradeHandlers) {
|
||||
if (urlPath.startsWith(entry.prefix)) {
|
||||
|
|
@ -155,13 +206,29 @@ export class WsHub {
|
|||
return;
|
||||
}
|
||||
|
||||
// Validate Origin when provided by browsers to block cross-site WS hijacking
|
||||
const cookies = extractCookies(req.headers.cookie);
|
||||
const token = cookies[SESSION_COOKIE_NAME];
|
||||
const session = this.authService.getSessionByToken(token);
|
||||
if (!session || !token) {
|
||||
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate Origin strictly when present (browsers always send Origin) to block CSWSH
|
||||
const origin = req.headers.origin;
|
||||
const host = req.headers.host;
|
||||
if (origin && host) {
|
||||
if (origin) {
|
||||
try {
|
||||
const originUrl = new URL(origin);
|
||||
if (originUrl.host !== host) {
|
||||
const validScheme =
|
||||
originUrl.protocol === 'http:' || originUrl.protocol === 'https:';
|
||||
const isHttpsReq = Boolean(
|
||||
(req.socket as { encrypted?: boolean }).encrypted ||
|
||||
(this.trustCloudflare && req.headers['x-forwarded-proto'] === 'https'),
|
||||
);
|
||||
const expectedScheme = isHttpsReq ? 'https:' : 'http:';
|
||||
if (!validScheme || !host || originUrl.host !== host || originUrl.protocol !== expectedScheme) {
|
||||
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
|
||||
socket.destroy();
|
||||
return;
|
||||
|
|
@ -173,15 +240,6 @@ export class WsHub {
|
|||
}
|
||||
}
|
||||
|
||||
const cookies = extractCookies(req.headers.cookie);
|
||||
const token = cookies[SESSION_COOKIE_NAME];
|
||||
const session = this.authService.getSessionByToken(token);
|
||||
if (!session || !token) {
|
||||
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
this.wss.handleUpgrade(req, socket, head, (ws) => {
|
||||
const meta: WsClientMeta = {
|
||||
ws,
|
||||
|
|
@ -193,13 +251,17 @@ export class WsHub {
|
|||
};
|
||||
this.clients.add(meta);
|
||||
|
||||
this.sendFrame(ws, {
|
||||
type: 'hello',
|
||||
vaultState: this.vaultService.state,
|
||||
vaultRuntimeReady: this.vaultService.isRuntimeReady,
|
||||
safeMode: session.safeMode,
|
||||
elevatedUntil: session.elevatedUntil,
|
||||
});
|
||||
this.sendFrame(
|
||||
ws,
|
||||
{
|
||||
type: 'hello',
|
||||
vaultState: this.vaultService.state,
|
||||
vaultRuntimeReady: this.vaultService.isRuntimeReady,
|
||||
safeMode: session.safeMode,
|
||||
elevatedUntil: session.elevatedUntil,
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
ws.on('pong', () => {
|
||||
meta.alive = true;
|
||||
|
|
@ -219,40 +281,69 @@ export class WsHub {
|
|||
});
|
||||
}
|
||||
|
||||
private ensureActiveSession(meta: WsClientMeta): AuthSession | null {
|
||||
const latestSession = this.authService.getSessionByToken(meta.sessionToken);
|
||||
if (!latestSession) {
|
||||
try {
|
||||
meta.ws.close(4001, 'Session expired');
|
||||
} catch {
|
||||
meta.ws.terminate();
|
||||
}
|
||||
this.clients.delete(meta);
|
||||
return null;
|
||||
}
|
||||
return latestSession;
|
||||
}
|
||||
|
||||
private onMessage(meta: WsClientMeta, raw: unknown): void {
|
||||
let parsedJson: unknown;
|
||||
try {
|
||||
const text = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf8');
|
||||
parsedJson = JSON.parse(text);
|
||||
} catch {
|
||||
this.sendFrame(meta.ws, {
|
||||
type: 'error',
|
||||
code: 'BAD_JSON',
|
||||
message: 'Invalid WebSocket JSON frame',
|
||||
});
|
||||
this.sendFrame(
|
||||
meta.ws,
|
||||
{
|
||||
type: 'error',
|
||||
code: 'BAD_JSON',
|
||||
message: 'Invalid WebSocket JSON frame',
|
||||
},
|
||||
true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = ClientWsFrameSchema.safeParse(parsedJson);
|
||||
if (!result.success) {
|
||||
this.sendFrame(meta.ws, {
|
||||
type: 'error',
|
||||
code: 'INVALID_FRAME',
|
||||
message: 'Unrecognized or malformed WebSocket frame',
|
||||
});
|
||||
this.sendFrame(
|
||||
meta.ws,
|
||||
{
|
||||
type: 'error',
|
||||
code: 'INVALID_FRAME',
|
||||
message: 'Unrecognized or malformed WebSocket frame',
|
||||
},
|
||||
true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const frame = result.data;
|
||||
switch (frame.type) {
|
||||
case 'ping':
|
||||
this.sendFrame(meta.ws, {
|
||||
type: 'pong',
|
||||
ts: frame.ts,
|
||||
serverTs: Date.now(),
|
||||
});
|
||||
case 'ping': {
|
||||
if (!this.ensureActiveSession(meta)) return;
|
||||
this.sendFrame(
|
||||
meta.ws,
|
||||
{
|
||||
type: 'pong',
|
||||
ts: frame.ts,
|
||||
serverTs: Date.now(),
|
||||
},
|
||||
true,
|
||||
);
|
||||
break;
|
||||
}
|
||||
case 'sub': {
|
||||
if (!this.ensureActiveSession(meta)) return;
|
||||
const ctx = {
|
||||
send: (outFrame: ServerWsFrame) => this.sendFrame(meta.ws, outFrame),
|
||||
sessionIdHash: meta.sessionIdHash,
|
||||
|
|
@ -274,44 +365,78 @@ export class WsHub {
|
|||
meta.channels.delete(ch);
|
||||
}
|
||||
break;
|
||||
case 'safe-mode':
|
||||
meta.clientSafeMode = frame.enabled;
|
||||
case 'safe-mode': {
|
||||
const latestSession = this.ensureActiveSession(meta);
|
||||
if (!latestSession) return;
|
||||
meta.clientSafeMode = latestSession.safeMode || frame.enabled;
|
||||
break;
|
||||
}
|
||||
case 'pty:input': {
|
||||
const latestSession = this.authService.getSessionByToken(meta.sessionToken);
|
||||
if (!latestSession) {
|
||||
meta.ws.close(4001, 'Session expired');
|
||||
return;
|
||||
}
|
||||
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 terminal input.',
|
||||
});
|
||||
this.sendFrame(
|
||||
meta.ws,
|
||||
{
|
||||
type: 'error',
|
||||
code: 'SAFE_MODE_ACTIVE',
|
||||
message: 'Safe / Read-Only Mode blocks terminal input.',
|
||||
},
|
||||
true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
this.ptyHandlers?.onInput(frame.sessionId, frame.data);
|
||||
break;
|
||||
}
|
||||
case 'pty:resize': {
|
||||
const latestSession = this.authService.getSessionByToken(meta.sessionToken);
|
||||
if (!latestSession) {
|
||||
meta.ws.close(4001, 'Session expired');
|
||||
return;
|
||||
}
|
||||
if (!this.ensureActiveSession(meta)) return;
|
||||
this.ptyHandlers?.onResize(frame.sessionId, frame.cols, frame.rows);
|
||||
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);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sendFrame(ws: WebSocket, frame: ServerWsFrame): void {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify(frame));
|
||||
private safeSendRaw(client: WsClientMeta, payload: string, critical = false): void {
|
||||
if (client.ws.readyState !== WebSocket.OPEN) return;
|
||||
if (client.ws.bufferedAmount > WS_HARD_BACKPRESSURE_BYTES) {
|
||||
client.ws.terminate();
|
||||
this.clients.delete(client);
|
||||
return;
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,23 +2,29 @@ import fs from 'node:fs';
|
|||
import http from 'node:http';
|
||||
import path from 'node:path';
|
||||
import type Database from 'better-sqlite3';
|
||||
import express, { type Express } from 'express';
|
||||
import express, { type Express, type NextFunction, type Request, type Response } from 'express';
|
||||
import type { ThrottleMode } from '../shared/schemas/settings.schema.js';
|
||||
import { AiService } from './ai/ai-service.js';
|
||||
import { AlertEngine } from './alerts/alert-engine.js';
|
||||
import { BroadcastService } from './automation/broadcast-service.js';
|
||||
import { TransferEngine } from './automation/transfer-engine.js';
|
||||
import { WorkflowEngine } from './automation/workflow-engine.js';
|
||||
import { ConfigManager } from './config/config-manager.js';
|
||||
import { openDatabase } from './db/database.js';
|
||||
import { resolveRuntimeLimits } from './config/runtime-limits.js';
|
||||
import { applyDatabaseThrottlePragmas, openDatabase } from './db/database.js';
|
||||
import { ServerInspector } from './monitoring/inspector.js';
|
||||
import { MonitoringService } from './monitoring/monitoring-service.js';
|
||||
import { ProbeRunner } from './monitoring/probes.js';
|
||||
import { createPrometheusHandler } from './monitoring/prometheus.js';
|
||||
import { AuditService } from './security/audit.js';
|
||||
import { AuthService } from './security/auth.js';
|
||||
import { BackupScheduler } from './security/backup-scheduler.js';
|
||||
import {
|
||||
DEFAULT_TRUSTED_PROXY_CIDRS,
|
||||
RateLimiter,
|
||||
attachClientIp,
|
||||
createStepUpGuard,
|
||||
isTrustedProxyPeer,
|
||||
} from './security/guards.js';
|
||||
import { EmergencyRecoveryService } from './security/recovery-store.js';
|
||||
import { VaultService } from './security/vault.js';
|
||||
|
|
@ -27,7 +33,7 @@ import { KnownHostsService } from './ssh/known-hosts.js';
|
|||
import { PTYManager } from './ssh/pty-manager.js';
|
||||
import { SftpService } from './ssh/sftp-service.js';
|
||||
import { SSHPool } from './ssh/ssh-pool.js';
|
||||
import { TunnelManager } from './ssh/tunnel-manager.js';
|
||||
import { TunnelManager, extractSubdomainTunnel } from './ssh/tunnel-manager.js';
|
||||
import { CustomSystemsEngine } from './systems/systems-engine.js';
|
||||
import { createAiRouter } from './api/routes/ai.routes.js';
|
||||
import { createAlertsRouter } from './api/routes/alerts.routes.js';
|
||||
|
|
@ -52,7 +58,17 @@ export interface ServerOptions {
|
|||
publicDir?: string;
|
||||
secretFilePath?: string;
|
||||
envMasterKey?: string;
|
||||
envDbKey?: string;
|
||||
trustCloudflare?: boolean;
|
||||
trustedProxyCidrs?: string[];
|
||||
allowLanTunnels?: boolean;
|
||||
proxyBaseDomain?: string;
|
||||
proxyPort?: number;
|
||||
webauthnRpId?: string;
|
||||
webauthnOrigins?: string[];
|
||||
metricsToken?: string;
|
||||
throttleModeOverride?: ThrottleMode;
|
||||
autoKeyFile?: boolean;
|
||||
watchConfig?: boolean;
|
||||
}
|
||||
|
||||
|
|
@ -74,6 +90,7 @@ export interface GCoordinatorInstance {
|
|||
customSystemsEngine: CustomSystemsEngine;
|
||||
serverInspector: ServerInspector;
|
||||
monitoringService: MonitoringService;
|
||||
backupScheduler: BackupScheduler;
|
||||
transferEngine: TransferEngine;
|
||||
workflowEngine: WorkflowEngine;
|
||||
broadcastService: BroadcastService;
|
||||
|
|
@ -81,6 +98,7 @@ export interface GCoordinatorInstance {
|
|||
aiService: AiService;
|
||||
wsHub: WsHub;
|
||||
port: number;
|
||||
proxyPort?: number;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
|
|
@ -92,24 +110,41 @@ export async function createGCoordinatorServer(
|
|||
const dbPath = path.join(dataDir, 'gcoord.db');
|
||||
const vaultPath = path.join(dataDir, 'vault.enc');
|
||||
const trustCloudflare = Boolean(options.trustCloudflare);
|
||||
const trustedProxyCidrs = options.trustedProxyCidrs ?? DEFAULT_TRUSTED_PROXY_CIDRS;
|
||||
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
||||
try {
|
||||
fs.chmodSync(dataDir, 0o700);
|
||||
} catch {
|
||||
// Best-effort on filesystems without POSIX permissions
|
||||
}
|
||||
|
||||
const db = openDatabase(dbPath);
|
||||
const auditService = new AuditService(db);
|
||||
const vaultService = new VaultService(vaultPath, {
|
||||
keyFilePath: path.join(dataDir, 'vault.key'),
|
||||
allowLocalKeyFile: options.autoKeyFile ?? true,
|
||||
});
|
||||
const recoveryStore = new EmergencyRecoveryService(dataDir);
|
||||
const rateLimiter = new RateLimiter();
|
||||
const rateLimiter = new RateLimiter({ db });
|
||||
const configManager = new ConfigManager(configDir, db, vaultService);
|
||||
|
||||
await configManager.init({ watch: options.watchConfig ?? true });
|
||||
|
||||
const getRuntimeLimits = () =>
|
||||
resolveRuntimeLimits(
|
||||
configManager.getSettings().runtime?.throttleMode ?? 'low-resource',
|
||||
options.throttleModeOverride,
|
||||
);
|
||||
applyDatabaseThrottlePragmas(db, getRuntimeLimits());
|
||||
|
||||
const authService = new AuthService(db, {
|
||||
getSecuritySettings: () => configManager.getSettings().security,
|
||||
getRuntimeLimits,
|
||||
recoveryStore,
|
||||
vaultService,
|
||||
dataDir,
|
||||
envDbKey: options.envDbKey,
|
||||
});
|
||||
|
||||
const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup
|
||||
|
|
@ -129,37 +164,49 @@ export async function createGCoordinatorServer(
|
|||
}
|
||||
|
||||
const app = express();
|
||||
app.locals.auditService = auditService;
|
||||
app.disable('x-powered-by');
|
||||
if (trustCloudflare) {
|
||||
app.set('trust proxy', 1);
|
||||
app.set('trust proxy', (ip: string) => isTrustedProxyPeer(ip, trustedProxyCidrs));
|
||||
}
|
||||
|
||||
const httpServer = http.createServer(app);
|
||||
const wsHub = new WsHub(httpServer, authService, vaultService);
|
||||
const wsHub = new WsHub(httpServer, authService, vaultService, { trustCloudflare });
|
||||
authService.onSessionsRevoked((idHashes) => {
|
||||
wsHub.disconnectSessions(idHashes);
|
||||
});
|
||||
|
||||
const knownHosts = new KnownHostsService(db, auditService);
|
||||
const sshPool = new SSHPool(configManager, vaultService, knownHosts);
|
||||
const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService);
|
||||
const ptyManager = new PTYManager(sshPool, configManager, wsHub);
|
||||
const ptyManager = new PTYManager(sshPool, configManager, wsHub, getRuntimeLimits);
|
||||
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(
|
||||
sshPool,
|
||||
configManager,
|
||||
vaultService,
|
||||
ptyManager,
|
||||
wsHub,
|
||||
getRuntimeLimits,
|
||||
);
|
||||
const serverInspector = new ServerInspector(sshPool, configManager);
|
||||
const probeRunner = new ProbeRunner(sshPool);
|
||||
const probeRunner = new ProbeRunner(sshPool, configManager);
|
||||
const monitoringService = new MonitoringService(
|
||||
db,
|
||||
configManager,
|
||||
vaultService,
|
||||
sshPool,
|
||||
probeRunner,
|
||||
getRuntimeLimits,
|
||||
);
|
||||
const transferEngine = new TransferEngine(sshPool, sftpService, configManager);
|
||||
const transferEngine = new TransferEngine(sshPool, sftpService, configManager, knownHosts);
|
||||
const workflowEngine = new WorkflowEngine(
|
||||
db,
|
||||
configManager,
|
||||
|
|
@ -170,6 +217,7 @@ export async function createGCoordinatorServer(
|
|||
transferEngine,
|
||||
wsHub,
|
||||
auditService,
|
||||
getRuntimeLimits,
|
||||
);
|
||||
const broadcastService = new BroadcastService(
|
||||
configManager,
|
||||
|
|
@ -177,6 +225,8 @@ export async function createGCoordinatorServer(
|
|||
sshPool,
|
||||
wsHub,
|
||||
auditService,
|
||||
db,
|
||||
getRuntimeLimits,
|
||||
);
|
||||
const alertEngine = new AlertEngine(
|
||||
db,
|
||||
|
|
@ -195,8 +245,24 @@ export async function createGCoordinatorServer(
|
|||
sshPool,
|
||||
wsHub,
|
||||
auditService,
|
||||
getRuntimeLimits,
|
||||
);
|
||||
const backupScheduler = new BackupScheduler(
|
||||
dataDir,
|
||||
db,
|
||||
configManager,
|
||||
vaultService,
|
||||
sftpService,
|
||||
auditService,
|
||||
getRuntimeLimits,
|
||||
);
|
||||
|
||||
wsHub.registerHostUpgradeHandler((req, socket, head) => {
|
||||
const tunnelSub = extractSubdomainTunnel(req.headers.host, options.proxyBaseDomain);
|
||||
if (!tunnelSub) return false;
|
||||
tunnelManager.handleSubdomainProxyWs(req, socket, head, tunnelSub);
|
||||
return true;
|
||||
});
|
||||
wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => {
|
||||
tunnelManager.handleWsProxyUpgrade(req, socket, head);
|
||||
});
|
||||
|
|
@ -253,29 +319,57 @@ export async function createGCoordinatorServer(
|
|||
}
|
||||
});
|
||||
|
||||
app.use((req, res, next) => {
|
||||
const tunnelSub = extractSubdomainTunnel(req.headers.host, options.proxyBaseDomain);
|
||||
if (tunnelSub) {
|
||||
tunnelManager.handleSubdomainProxyHttp(req, res, tunnelSub);
|
||||
return;
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
app.use((req, res, next) => {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'no-referrer');
|
||||
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
|
||||
if (req.secure || trustCloudflare) {
|
||||
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
|
||||
}
|
||||
if (req.path.startsWith('/api/')) {
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.setHeader('Pragma', 'no-cache');
|
||||
}
|
||||
if (!req.path.startsWith('/proxy/')) {
|
||||
const rawHost = typeof req.headers.host === 'string' ? req.headers.host.trim() : '';
|
||||
const safeHost = /^[A-Za-z0-9.\-:\[\]]+$/.test(rawHost) ? rawHost : '';
|
||||
const connectSrc = safeHost
|
||||
? `'self' ws://${safeHost} wss://${safeHost}`
|
||||
: `'self'`;
|
||||
res.setHeader('X-Frame-Options', 'DENY');
|
||||
res.setHeader(
|
||||
'Content-Security-Policy',
|
||||
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ws: wss:; frame-ancestors 'none'; base-uri 'self'",
|
||||
`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'`,
|
||||
);
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
app.use(attachClientIp(trustCloudflare));
|
||||
app.use(attachClientIp(trustCloudflare, trustedProxyCidrs));
|
||||
// Mount /proxy before express.json so proxied POST/PUT payloads stream untouched upstream
|
||||
app.use('/proxy', createProxyRouter({ authService, tunnelManager }));
|
||||
|
||||
const jsonParser = express.json({ limit: '2mb' });
|
||||
const backupJsonParser = express.json({ limit: '16mb' });
|
||||
|
||||
app.use((req, res, next) => {
|
||||
if (req.path.endsWith('/sftp/upload')) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
if (req.path.startsWith('/api/backup/')) {
|
||||
backupJsonParser(req, res, next);
|
||||
return;
|
||||
}
|
||||
jsonParser(req, res, next);
|
||||
});
|
||||
|
||||
|
|
@ -303,14 +397,49 @@ export async function createGCoordinatorServer(
|
|||
});
|
||||
});
|
||||
|
||||
authService.setSecurityEventListener((ev) => {
|
||||
void alertEngine.emitSecurityEvent(ev.type, {
|
||||
ip: ev.ip,
|
||||
details: ev.details,
|
||||
message: `${ev.type}${ev.ip ? ` from ${ev.ip}` : ''}`,
|
||||
});
|
||||
});
|
||||
|
||||
knownHosts.onHostKeyMismatch((alert) => {
|
||||
void alertEngine.emitSecurityEvent('ssh.host_key_mismatch', {
|
||||
serverId: alert.serverId,
|
||||
message: `Host key mismatch on ${alert.hostPortKey} (${alert.algorithm})`,
|
||||
});
|
||||
});
|
||||
|
||||
monitoringService.start();
|
||||
void tunnelManager.syncAutoStart();
|
||||
customSystemsEngine.syncBackgroundChecks();
|
||||
workflowEngine.start();
|
||||
alertEngine.start();
|
||||
backupScheduler.start();
|
||||
auditService.pruneOlderThan(configManager.getSettings().auditRetentionDays);
|
||||
|
||||
vaultService.onSeal(() => {
|
||||
aiService.cancelAll();
|
||||
backupScheduler.stop();
|
||||
alertEngine.handlePanicLock();
|
||||
workflowEngine.handlePanicLock();
|
||||
broadcastService.cancelAll();
|
||||
monitoringService.stopAll();
|
||||
customSystemsEngine.stopBackgroundChecks();
|
||||
customSystemsEngine.cancelAllStreams();
|
||||
tunnelManager.stopAll();
|
||||
ptyManager.closeAll(true);
|
||||
sshPool.closeAll('vault_sealed');
|
||||
});
|
||||
|
||||
vaultService.onPanicLock(() => {
|
||||
void alertEngine.emitSecurityEvent('vault.panic_lock', {
|
||||
message: 'Emergency Panic Lock activated',
|
||||
});
|
||||
aiService.cancelAll();
|
||||
backupScheduler.stop();
|
||||
alertEngine.handlePanicLock();
|
||||
workflowEngine.handlePanicLock();
|
||||
broadcastService.cancelAll();
|
||||
|
|
@ -320,8 +449,8 @@ export async function createGCoordinatorServer(
|
|||
tunnelManager.stopAll();
|
||||
ptyManager.closeAll(true);
|
||||
sshPool.closeAll('panic_lock');
|
||||
authService.revokeAllSessions();
|
||||
wsHub.handlePanicLock();
|
||||
authService.revokeAllSessions();
|
||||
});
|
||||
|
||||
configManager.onChange((event) => {
|
||||
|
|
@ -332,6 +461,9 @@ export async function createGCoordinatorServer(
|
|||
warnings: event.warnings,
|
||||
errors: event.errors,
|
||||
});
|
||||
if (event.entityType === 'alerts' || event.entityType === 'server' || event.entityType === 'all') {
|
||||
alertEngine.syncWithConfig();
|
||||
}
|
||||
if (
|
||||
event.entityType === 'server' ||
|
||||
event.entityType === 'system' ||
|
||||
|
|
@ -346,16 +478,32 @@ export async function createGCoordinatorServer(
|
|||
customSystemsEngine.invalidateCache(event.id);
|
||||
} else if (event.entityType === 'system' && event.id) {
|
||||
customSystemsEngine.invalidateCache(undefined, event.id);
|
||||
} else {
|
||||
} else if (event.entityType === 'all') {
|
||||
customSystemsEngine.invalidateCache();
|
||||
}
|
||||
if (event.entityType === 'settings') {
|
||||
authService.syncRecovery();
|
||||
if (event.entityType === 'settings' || event.entityType === 'all') {
|
||||
applyDatabaseThrottlePragmas(db, getRuntimeLimits());
|
||||
if (!configManager.getSettings().security.enableEmergencySecretsBackup) {
|
||||
recoveryStore.wipeAll();
|
||||
} else {
|
||||
authService.syncRecovery();
|
||||
}
|
||||
backupScheduler.sync();
|
||||
}
|
||||
if (event.entityType === 'server' || event.entityType === 'all') {
|
||||
monitoringService.syncServers();
|
||||
void tunnelManager.syncAutoStart();
|
||||
}
|
||||
if (
|
||||
event.entityType === 'server' ||
|
||||
event.entityType === 'system' ||
|
||||
event.entityType === 'all'
|
||||
) {
|
||||
customSystemsEngine.syncBackgroundChecks();
|
||||
}
|
||||
if (event.entityType === 'workflow' || event.entityType === 'all') {
|
||||
workflowEngine.syncCronJobs();
|
||||
}
|
||||
monitoringService.syncServers();
|
||||
customSystemsEngine.syncBackgroundChecks();
|
||||
workflowEngine.syncCronJobs();
|
||||
void tunnelManager.syncAutoStart();
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -365,11 +513,7 @@ export async function createGCoordinatorServer(
|
|||
);
|
||||
|
||||
app.get('/api/healthz', (_req, res) => {
|
||||
res.json({
|
||||
ok: true,
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
});
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.use(
|
||||
|
|
@ -382,6 +526,8 @@ export async function createGCoordinatorServer(
|
|||
recoveryStore,
|
||||
rateLimiter,
|
||||
trustCloudflare,
|
||||
webauthnRpId: options.webauthnRpId,
|
||||
webauthnOrigins: options.webauthnOrigins,
|
||||
}),
|
||||
);
|
||||
|
||||
|
|
@ -397,6 +543,7 @@ export async function createGCoordinatorServer(
|
|||
monitoringService.syncServers();
|
||||
customSystemsEngine.syncBackgroundChecks();
|
||||
workflowEngine.syncCronJobs();
|
||||
backupScheduler.sync();
|
||||
void tunnelManager.syncAutoStart();
|
||||
},
|
||||
onVaultChanged: (snapshotReason) => {
|
||||
|
|
@ -416,18 +563,27 @@ export async function createGCoordinatorServer(
|
|||
configManager,
|
||||
auditService,
|
||||
stepUpGuard,
|
||||
getRuntimeLimits,
|
||||
backupScheduler,
|
||||
onRestored: async ({ inner, vaultKeyCandidate }) => {
|
||||
if (inner.vaultEnvelopeRaw !== null) {
|
||||
try {
|
||||
vaultService.reloadFromDisk(vaultKeyCandidate);
|
||||
} catch {
|
||||
// Keep existing runtime state untouched if backup vault used a different key
|
||||
// Avoid keeping an old runtime master key unlocked against a newly restored foreign vault
|
||||
vaultService.seal();
|
||||
vaultService.dropLocalKeyFile();
|
||||
}
|
||||
}
|
||||
knownHosts.replaceAllKnownHosts(inner.knownHosts);
|
||||
configManager.reloadAllFromDisk();
|
||||
sshPool.syncWithConfig();
|
||||
if (authService.isBootstrapped() && vaultService.isRuntimeReady) {
|
||||
backupScheduler.sync();
|
||||
if (
|
||||
authService.isBootstrapped() &&
|
||||
vaultService.isRuntimeReady &&
|
||||
configManager.getSettings().security.enableEmergencySecretsBackup
|
||||
) {
|
||||
authService.syncRecovery({ snapshotReason: 'backup-restore' });
|
||||
}
|
||||
wsHub.broadcastAll({
|
||||
|
|
@ -446,7 +602,12 @@ export async function createGCoordinatorServer(
|
|||
);
|
||||
app.use(
|
||||
'/api/systems',
|
||||
createSystemsRouter({ authService, auditService, systemsEngine: customSystemsEngine }),
|
||||
createSystemsRouter({
|
||||
authService,
|
||||
auditService,
|
||||
systemsEngine: customSystemsEngine,
|
||||
stepUpGuard,
|
||||
}),
|
||||
);
|
||||
app.use(
|
||||
'/api/workflows',
|
||||
|
|
@ -464,12 +625,12 @@ export async function createGCoordinatorServer(
|
|||
);
|
||||
app.use(
|
||||
'/api/alerts',
|
||||
createAlertsRouter({ authService, configManager, auditService, alertEngine }),
|
||||
createAlertsRouter({ authService, configManager, auditService, alertEngine, stepUpGuard }),
|
||||
);
|
||||
app.use('/api/ai', createAiRouter({ authService, aiService }));
|
||||
app.use('/api/ai', createAiRouter({ authService, aiService, stepUpGuard }));
|
||||
app.use(
|
||||
'/api/servers/:id/sftp',
|
||||
createSftpRouter({ authService, configManager, auditService, sftpService }),
|
||||
createSftpRouter({ authService, configManager, auditService, sftpService, stepUpGuard }),
|
||||
);
|
||||
app.use(
|
||||
'/api/servers',
|
||||
|
|
@ -491,9 +652,20 @@ export async function createGCoordinatorServer(
|
|||
);
|
||||
app.use(
|
||||
'/api/config',
|
||||
createConfigRouter({ authService, configManager, auditService }),
|
||||
createConfigRouter({ authService, configManager, auditService, stepUpGuard }),
|
||||
);
|
||||
app.use('/api/audit', createAuditRouter(authService, auditService));
|
||||
app.get(
|
||||
'/metrics',
|
||||
createPrometheusHandler({
|
||||
configManager,
|
||||
vaultService,
|
||||
sshPool,
|
||||
monitoringService,
|
||||
tunnelManager,
|
||||
alertEngine,
|
||||
}),
|
||||
);
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
res.status(404).json({ error: 'API_ROUTE_NOT_FOUND' });
|
||||
|
|
@ -508,6 +680,26 @@ 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) => {
|
||||
httpServer.once('error', reject);
|
||||
httpServer.listen(options.port, options.host ?? '0.0.0.0', () => {
|
||||
|
|
@ -538,6 +730,7 @@ export async function createGCoordinatorServer(
|
|||
customSystemsEngine,
|
||||
serverInspector,
|
||||
monitoringService,
|
||||
backupScheduler,
|
||||
transferEngine,
|
||||
workflowEngine,
|
||||
broadcastService,
|
||||
|
|
@ -545,16 +738,20 @@ export async function createGCoordinatorServer(
|
|||
aiService,
|
||||
wsHub,
|
||||
port: actualPort,
|
||||
proxyPort: tunnelManager.actualProxyPort,
|
||||
async close() {
|
||||
aiService.close();
|
||||
backupScheduler.close();
|
||||
alertEngine.close();
|
||||
workflowEngine.close();
|
||||
broadcastService.cancelAll();
|
||||
monitoringService.close();
|
||||
customSystemsEngine.close();
|
||||
tunnelManager.stopAll();
|
||||
await tunnelManager.stopProxyServer();
|
||||
ptyManager.close();
|
||||
sshPool.closeAll('shutdown');
|
||||
authService.close();
|
||||
wsHub.close();
|
||||
await configManager.close();
|
||||
await new Promise<void>((resolve) => {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import crypto from 'node:crypto';
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { ServerWsFrame } from '../../shared/ws-protocol.js';
|
||||
import type { WsHub } from '../api/ws-hub.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import type { RuntimeLimits } from '../config/runtime-limits.js';
|
||||
import type { AuditService } from '../security/audit.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
|
|
@ -9,6 +11,8 @@ import { BufferedStreamEmitter } from './stream-buffer.js';
|
|||
import {
|
||||
buildWorkflowEnv,
|
||||
interpolateShellCommandSafe,
|
||||
maskSecretInputsForStorage,
|
||||
redactWorkflowSecrets,
|
||||
resolveTargetServers,
|
||||
validateAndResolveInputs,
|
||||
} from './template.js';
|
||||
|
|
@ -38,10 +42,14 @@ export interface BroadcastJobSummary {
|
|||
interface ActiveBroadcastJob extends BroadcastJobSummary {
|
||||
emitter: BufferedStreamEmitter;
|
||||
abortController: AbortController;
|
||||
secretValues: string[];
|
||||
}
|
||||
|
||||
const MAX_RETAINED_BROADCASTS = 25;
|
||||
const MAX_OUTPUT_PER_SERVER = 256 * 1024;
|
||||
function csvSafeCell(val: unknown): string {
|
||||
const s = val === null || val === undefined ? '' : String(val);
|
||||
const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s;
|
||||
return `"${safe.replace(/"/g, '""')}"`;
|
||||
}
|
||||
|
||||
async function runPool<T>(
|
||||
items: T[],
|
||||
|
|
@ -68,6 +76,8 @@ export class BroadcastService {
|
|||
private readonly sshPool: SSHPool,
|
||||
private readonly wsHub: WsHub,
|
||||
private readonly auditService: AuditService,
|
||||
private readonly db?: Database.Database,
|
||||
private readonly getRuntimeLimits?: () => RuntimeLimits,
|
||||
) {}
|
||||
|
||||
getStreamReplayFrames(jobId: string): ServerWsFrame[] {
|
||||
|
|
@ -76,17 +86,178 @@ export class BroadcastService {
|
|||
|
||||
getBroadcastResult(jobId: string): BroadcastJobSummary | undefined {
|
||||
const job = this.jobs.get(jobId);
|
||||
if (!job) return undefined;
|
||||
if (job) {
|
||||
return {
|
||||
jobId: job.jobId,
|
||||
snippetId: job.snippetId,
|
||||
command: job.command,
|
||||
sudo: job.sudo,
|
||||
createdAt: job.createdAt,
|
||||
finishedAt: job.finishedAt,
|
||||
cancelled: job.cancelled,
|
||||
done: job.done,
|
||||
targets: job.targets.map((t) => ({ ...t })),
|
||||
};
|
||||
}
|
||||
|
||||
if (!this.db) return undefined;
|
||||
const row = this.db
|
||||
.prepare(
|
||||
`SELECT job_id AS jobId, command, snippet_id AS snippetId, status,
|
||||
started_at AS startedAt, finished_at AS finishedAt, results_json AS resultsJson
|
||||
FROM broadcast_jobs
|
||||
WHERE job_id = ?`,
|
||||
)
|
||||
.get(jobId) as
|
||||
| {
|
||||
jobId: string;
|
||||
command: string;
|
||||
snippetId: string | null;
|
||||
status: string;
|
||||
startedAt: number;
|
||||
finishedAt: number | null;
|
||||
resultsJson: string;
|
||||
}
|
||||
| undefined;
|
||||
if (!row) return undefined;
|
||||
|
||||
let targets: BroadcastTargetResult[] = [];
|
||||
try {
|
||||
targets = JSON.parse(row.resultsJson) as BroadcastTargetResult[];
|
||||
} catch {
|
||||
targets = [];
|
||||
}
|
||||
|
||||
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 })),
|
||||
jobId: row.jobId,
|
||||
snippetId: row.snippetId ?? undefined,
|
||||
command: row.command,
|
||||
sudo: false,
|
||||
createdAt: row.startedAt,
|
||||
finishedAt: row.finishedAt,
|
||||
cancelled: row.status === 'cancelled',
|
||||
done: row.finishedAt !== null || row.status !== 'running',
|
||||
targets,
|
||||
};
|
||||
}
|
||||
|
||||
listHistory(limit = 50): Array<{
|
||||
jobId: string;
|
||||
snippetId?: string;
|
||||
command: string;
|
||||
status: string;
|
||||
startedAt: number;
|
||||
finishedAt: number | null;
|
||||
targetCount: number;
|
||||
okCount: number;
|
||||
}> {
|
||||
if (!this.db) {
|
||||
return [...this.jobs.values()]
|
||||
.sort((a, b) => b.createdAt - a.createdAt)
|
||||
.slice(0, limit)
|
||||
.map((j) => ({
|
||||
jobId: j.jobId,
|
||||
snippetId: j.snippetId,
|
||||
command: j.command,
|
||||
status: j.cancelled
|
||||
? 'cancelled'
|
||||
: !j.done
|
||||
? 'running'
|
||||
: j.targets.every((t) => t.status === 'ok')
|
||||
? 'ok'
|
||||
: 'error',
|
||||
startedAt: j.createdAt,
|
||||
finishedAt: j.finishedAt,
|
||||
targetCount: j.targets.length,
|
||||
okCount: j.targets.filter((t) => t.status === 'ok').length,
|
||||
}));
|
||||
}
|
||||
|
||||
const safeLimit = Math.max(1, Math.min(200, Math.floor(limit)));
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT job_id AS jobId, command, snippet_id AS snippetId, status,
|
||||
started_at AS startedAt, finished_at AS finishedAt, results_json AS resultsJson
|
||||
FROM broadcast_jobs
|
||||
ORDER BY started_at DESC
|
||||
LIMIT ?`,
|
||||
)
|
||||
.all(safeLimit) as Array<{
|
||||
jobId: string;
|
||||
command: string;
|
||||
snippetId: string | null;
|
||||
status: string;
|
||||
startedAt: number;
|
||||
finishedAt: number | null;
|
||||
resultsJson: string;
|
||||
}>;
|
||||
|
||||
return rows.map((r) => {
|
||||
const live = this.jobs.get(r.jobId);
|
||||
const targets = live
|
||||
? live.targets
|
||||
: (() => {
|
||||
try {
|
||||
return JSON.parse(r.resultsJson) as BroadcastTargetResult[];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
})();
|
||||
return {
|
||||
jobId: r.jobId,
|
||||
snippetId: r.snippetId ?? undefined,
|
||||
command: r.command,
|
||||
status: live
|
||||
? live.cancelled
|
||||
? 'cancelled'
|
||||
: !live.done
|
||||
? 'running'
|
||||
: live.targets.every((t) => t.status === 'ok')
|
||||
? 'ok'
|
||||
: 'error'
|
||||
: r.status,
|
||||
startedAt: r.startedAt,
|
||||
finishedAt: live ? live.finishedAt : r.finishedAt,
|
||||
targetCount: targets.length,
|
||||
okCount: targets.filter((t) => t.status === 'ok').length,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
exportBroadcast(
|
||||
jobId: string,
|
||||
format: 'json' | 'csv' = 'json',
|
||||
): { contentType: string; filename: string; body: string } | null {
|
||||
const job = this.getBroadcastResult(jobId);
|
||||
if (!job) return null;
|
||||
|
||||
if (format === 'csv') {
|
||||
const header = 'jobId,serverId,serverName,status,exitCode,durationMs,stdout,stderr';
|
||||
const rows = job.targets.map((t) =>
|
||||
[
|
||||
job.jobId,
|
||||
t.serverId,
|
||||
t.serverName,
|
||||
t.status,
|
||||
t.exitCode ?? '',
|
||||
t.durationMs,
|
||||
t.stdout,
|
||||
t.stderr,
|
||||
]
|
||||
.map(csvSafeCell)
|
||||
.join(','),
|
||||
);
|
||||
return {
|
||||
contentType: 'text/csv; charset=utf-8',
|
||||
filename: `${job.jobId}.csv`,
|
||||
body: `${[header, ...rows].join('\n')}\n`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
contentType: 'application/json; charset=utf-8',
|
||||
filename: `${job.jobId}.json`,
|
||||
body: JSON.stringify(job, null, 2),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -125,6 +296,7 @@ export class BroadcastService {
|
|||
let rawCommand = opts.command?.trim() ?? '';
|
||||
let sudo = Boolean(opts.sudo);
|
||||
let resolvedInputs: Record<string, string> = {};
|
||||
let secretValues: string[] = [];
|
||||
|
||||
if (opts.snippetId) {
|
||||
const snip = this.configManager
|
||||
|
|
@ -134,6 +306,7 @@ export class BroadcastService {
|
|||
throw new Error(`Unknown command snippet "${opts.snippetId}"`);
|
||||
}
|
||||
resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {});
|
||||
secretValues = maskSecretInputsForStorage(snip.inputs, resolvedInputs).secretValues;
|
||||
rawCommand = snip.command;
|
||||
sudo = opts.sudo ?? snip.sudo;
|
||||
} else {
|
||||
|
|
@ -141,14 +314,14 @@ export class BroadcastService {
|
|||
throw new Error('Command or snippetId is required for Fleet Broadcast');
|
||||
}
|
||||
if (opts.inputs) {
|
||||
for (const [k, v] of Object.entries(opts.inputs)) {
|
||||
if (v !== undefined && v !== null) resolvedInputs[k] = String(v);
|
||||
}
|
||||
resolvedInputs = validateAndResolveInputs([], opts.inputs);
|
||||
}
|
||||
}
|
||||
|
||||
const limits = this.getRuntimeLimits?.();
|
||||
const baseCtx = { inputs: resolvedInputs };
|
||||
const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx);
|
||||
const displayCommand = redactWorkflowSecrets(renderedCommand, secretValues);
|
||||
const allServers = this.configManager.listServers();
|
||||
|
||||
let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx);
|
||||
|
|
@ -168,7 +341,11 @@ export class BroadcastService {
|
|||
}
|
||||
|
||||
const jobId = `bcast-${crypto.randomBytes(6).toString('hex')}`;
|
||||
const emitter = new BufferedStreamEmitter(this.wsHub, jobId);
|
||||
const emitter = new BufferedStreamEmitter(
|
||||
this.wsHub,
|
||||
jobId,
|
||||
limits?.streamReplayBytes,
|
||||
);
|
||||
const abortController = new AbortController();
|
||||
|
||||
const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({
|
||||
|
|
@ -184,7 +361,7 @@ export class BroadcastService {
|
|||
const job: ActiveBroadcastJob = {
|
||||
jobId,
|
||||
snippetId: opts.snippetId,
|
||||
command: renderedCommand,
|
||||
command: displayCommand,
|
||||
sudo,
|
||||
createdAt: Date.now(),
|
||||
finishedAt: null,
|
||||
|
|
@ -193,9 +370,12 @@ export class BroadcastService {
|
|||
targets,
|
||||
emitter,
|
||||
abortController,
|
||||
secretValues,
|
||||
};
|
||||
this.jobs.set(jobId, job);
|
||||
|
||||
this.persistBroadcastRow(job, 'running');
|
||||
|
||||
this.auditService.log({
|
||||
action: 'broadcast.start',
|
||||
actorIp: opts.actorIp,
|
||||
|
|
@ -211,12 +391,14 @@ export class BroadcastService {
|
|||
emitter.pushMeta({
|
||||
event: 'start',
|
||||
jobId,
|
||||
command: renderedCommand,
|
||||
command: displayCommand,
|
||||
targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })),
|
||||
});
|
||||
|
||||
const maxStepLogBytes = limits?.maxStepLogBytes ?? 256 * 1024;
|
||||
const timeoutMs = (opts.timeoutSec ?? 120) * 1000;
|
||||
const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, 32));
|
||||
const concurrencyCap = limits?.maxWorkflowStepTargets ?? 32;
|
||||
const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, concurrencyCap));
|
||||
|
||||
void runPool(matchedServers, concurrency, async (srv) => {
|
||||
const targetEntry = job.targets.find((t) => t.serverId === srv.id)!;
|
||||
|
|
@ -239,6 +421,7 @@ export class BroadcastService {
|
|||
const env = buildWorkflowEnv({
|
||||
inputs: resolvedInputs,
|
||||
serverId: srv.id,
|
||||
serverMeta: { id: srv.id, name: srv.name, host: srv.host, port: srv.port },
|
||||
});
|
||||
|
||||
try {
|
||||
|
|
@ -253,9 +436,9 @@ export class BroadcastService {
|
|||
let errBytes = 0;
|
||||
|
||||
handle.channel.on('data', (chunk: Buffer) => {
|
||||
const text = chunk.toString('utf8');
|
||||
if (outBytes < MAX_OUTPUT_PER_SERVER) {
|
||||
const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - outBytes);
|
||||
const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues);
|
||||
if (outBytes < maxStepLogBytes) {
|
||||
const slice = chunk.subarray(0, maxStepLogBytes - outBytes);
|
||||
outChunks.push(slice);
|
||||
outBytes += slice.length;
|
||||
}
|
||||
|
|
@ -269,9 +452,9 @@ export class BroadcastService {
|
|||
});
|
||||
|
||||
handle.channel.stderr?.on('data', (chunk: Buffer) => {
|
||||
const text = chunk.toString('utf8');
|
||||
if (errBytes < MAX_OUTPUT_PER_SERVER) {
|
||||
const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - errBytes);
|
||||
const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues);
|
||||
if (errBytes < maxStepLogBytes) {
|
||||
const slice = chunk.subarray(0, maxStepLogBytes - errBytes);
|
||||
errChunks.push(slice);
|
||||
errBytes += slice.length;
|
||||
}
|
||||
|
|
@ -296,8 +479,14 @@ export class BroadcastService {
|
|||
|
||||
try {
|
||||
const { exitCode } = await handle.done;
|
||||
targetEntry.stdout = Buffer.concat(outChunks).toString('utf8');
|
||||
targetEntry.stderr = Buffer.concat(errChunks).toString('utf8');
|
||||
targetEntry.stdout = redactWorkflowSecrets(
|
||||
Buffer.concat(outChunks).toString('utf8'),
|
||||
secretValues,
|
||||
);
|
||||
targetEntry.stderr = redactWorkflowSecrets(
|
||||
Buffer.concat(errChunks).toString('utf8'),
|
||||
secretValues,
|
||||
);
|
||||
targetEntry.durationMs = Date.now() - started;
|
||||
targetEntry.exitCode = exitCode;
|
||||
|
||||
|
|
@ -316,7 +505,10 @@ export class BroadcastService {
|
|||
} catch (err) {
|
||||
targetEntry.durationMs = Date.now() - started;
|
||||
targetEntry.status = abortController.signal.aborted ? 'cancelled' : 'error';
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const msg = redactWorkflowSecrets(
|
||||
err instanceof Error ? err.message : String(err),
|
||||
secretValues,
|
||||
);
|
||||
targetEntry.stderr = targetEntry.stderr ? `${targetEntry.stderr}\n${msg}` : msg;
|
||||
emitter.push('stderr', `[${srv.id}] ${msg}\n`);
|
||||
}
|
||||
|
|
@ -332,6 +524,12 @@ export class BroadcastService {
|
|||
job.done = true;
|
||||
job.finishedAt = Date.now();
|
||||
const okCount = job.targets.filter((t) => t.status === 'ok').length;
|
||||
const finalStatus = job.cancelled
|
||||
? 'cancelled'
|
||||
: okCount === job.targets.length
|
||||
? 'ok'
|
||||
: 'error';
|
||||
this.persistBroadcastRow(job, finalStatus);
|
||||
emitter.pushMeta({
|
||||
event: 'done',
|
||||
cancelled: job.cancelled,
|
||||
|
|
@ -344,9 +542,33 @@ export class BroadcastService {
|
|||
return this.getBroadcastResult(jobId)!;
|
||||
}
|
||||
|
||||
private persistBroadcastRow(job: ActiveBroadcastJob, status: string): void {
|
||||
if (!this.db) return;
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO broadcast_jobs (job_id, command, snippet_id, targets_json, status, started_at, finished_at, results_json)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(job_id) DO UPDATE SET
|
||||
status = excluded.status,
|
||||
finished_at = excluded.finished_at,
|
||||
results_json = excluded.results_json`,
|
||||
)
|
||||
.run(
|
||||
job.jobId,
|
||||
job.command,
|
||||
job.snippetId ?? null,
|
||||
JSON.stringify(job.targets.map((t) => t.serverId)),
|
||||
status,
|
||||
job.createdAt,
|
||||
job.finishedAt,
|
||||
JSON.stringify(job.targets),
|
||||
);
|
||||
}
|
||||
|
||||
private pruneJobs(): void {
|
||||
const maxRam = Math.max(1, this.getRuntimeLimits?.().maxRamBroadcastJobs ?? 5);
|
||||
const done = [...this.jobs.values()].filter((j) => j.done);
|
||||
while (done.length > MAX_RETAINED_BROADCASTS) {
|
||||
while (done.length > maxRam) {
|
||||
const oldest = done.shift()!;
|
||||
this.jobs.delete(oldest.jobId);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,13 +10,17 @@ export interface StepOutputSummary {
|
|||
export interface TemplateContext {
|
||||
workflowId?: string;
|
||||
runId?: string;
|
||||
triggerSource?: string;
|
||||
serverId?: string;
|
||||
serverMeta?: { id: string; name: string; host: string; port: number };
|
||||
inputs: Record<string, string>;
|
||||
stepOutputs?: Map<string, StepOutputSummary>;
|
||||
captures?: Map<string, string>;
|
||||
eventMeta?: Record<string, string>;
|
||||
}
|
||||
|
||||
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
||||
|
||||
export function toEnvIdent(raw: string): string {
|
||||
return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase();
|
||||
}
|
||||
|
|
@ -27,8 +31,15 @@ export function validateAndResolveInputs(
|
|||
): 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) {
|
||||
const raw = supplied[def.name];
|
||||
if (FORBIDDEN_KEYS.has(def.name)) continue;
|
||||
const raw = Object.hasOwn(supplied, def.name) ? supplied[def.name] : undefined;
|
||||
const hasSupplied = raw !== undefined && raw !== null && raw !== '';
|
||||
const candidate = hasSupplied ? raw : def.default;
|
||||
|
||||
|
|
@ -61,6 +72,9 @@ export function validateAndResolveInputs(
|
|||
}
|
||||
|
||||
const strVal = String(candidate);
|
||||
if (/[\x00]/.test(strVal)) {
|
||||
throw new Error(`Input "${def.name}" contains NUL bytes`);
|
||||
}
|
||||
if (def.type === 'select' && def.options && def.options.length > 0) {
|
||||
if (!def.options.includes(strVal)) {
|
||||
throw new Error(
|
||||
|
|
@ -72,14 +86,48 @@ export function validateAndResolveInputs(
|
|||
}
|
||||
|
||||
for (const [k, v] of Object.entries(supplied)) {
|
||||
if (!(k in out) && v !== undefined && v !== null) {
|
||||
out[k] = String(v);
|
||||
if (FORBIDDEN_KEYS.has(k)) continue;
|
||||
if (!Object.hasOwn(out, k) && v !== undefined && v !== null) {
|
||||
const s = String(v);
|
||||
if (/[\x00]/.test(s)) {
|
||||
throw new Error(`Input "${k}" contains NUL bytes`);
|
||||
}
|
||||
out[k] = s;
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
const env: Record<string, string> = {};
|
||||
if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId;
|
||||
|
|
@ -87,6 +135,7 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
|
|||
if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId;
|
||||
|
||||
for (const [k, v] of Object.entries(ctx.inputs)) {
|
||||
if (FORBIDDEN_KEYS.has(k)) continue;
|
||||
env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v;
|
||||
}
|
||||
|
||||
|
|
@ -106,6 +155,7 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
|
|||
|
||||
if (ctx.eventMeta) {
|
||||
for (const [k, v] of Object.entries(ctx.eventMeta)) {
|
||||
if (FORBIDDEN_KEYS.has(k)) continue;
|
||||
env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v;
|
||||
}
|
||||
}
|
||||
|
|
@ -113,45 +163,188 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
|
|||
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();
|
||||
if (expr.startsWith('inputs.')) {
|
||||
const key = expr.slice('inputs.'.length);
|
||||
return ctx.inputs[key] ?? '';
|
||||
if (!expr || expr.startsWith('.')) return { matched: false, value: '' };
|
||||
const parts = expr.split('.');
|
||||
if (parts.some((p) => FORBIDDEN_KEYS.has(p))) {
|
||||
return { matched: false, value: '' };
|
||||
}
|
||||
if (expr.startsWith('steps.')) {
|
||||
const rest = expr.slice('steps.'.length);
|
||||
|
||||
if (expr.startsWith('inputs.') || expr.startsWith('input.')) {
|
||||
const key = expr.slice(expr.indexOf('.') + 1);
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key)) return { matched: false, value: '' };
|
||||
return {
|
||||
matched: true,
|
||||
value: Object.hasOwn(ctx.inputs, key) ? ctx.inputs[key]! : '',
|
||||
};
|
||||
}
|
||||
|
||||
if (expr.startsWith('steps.') || expr.startsWith('step.')) {
|
||||
const rest = expr.slice(expr.indexOf('.') + 1);
|
||||
const dot = rest.lastIndexOf('.');
|
||||
if (dot > 0) {
|
||||
const stepId = rest.slice(0, dot);
|
||||
const field = rest.slice(dot + 1);
|
||||
const out = ctx.stepOutputs?.get(stepId);
|
||||
if (!out) return '';
|
||||
if (field === 'stdout') return out.stdout.trim();
|
||||
if (field === 'exitCode') return out.exitCode === null ? '' : String(out.exitCode);
|
||||
if (field === 'stdout') return { matched: true, value: out ? out.stdout.trim() : '' };
|
||||
if (field === 'exitCode') {
|
||||
return {
|
||||
matched: true,
|
||||
value: out && out.exitCode !== null ? String(out.exitCode) : '',
|
||||
};
|
||||
}
|
||||
}
|
||||
return { matched: false, value: '' };
|
||||
}
|
||||
if (expr.startsWith('captures.')) {
|
||||
const key = expr.slice('captures.'.length);
|
||||
return (ctx.captures?.get(key) ?? '').trim();
|
||||
|
||||
if (expr.startsWith('captures.') || expr.startsWith('capture.')) {
|
||||
const key = expr.slice(expr.indexOf('.') + 1);
|
||||
return { matched: true, value: (ctx.captures?.get(key) ?? '').trim() };
|
||||
}
|
||||
|
||||
if (expr.startsWith('event.')) {
|
||||
const key = expr.slice('event.'.length);
|
||||
return ctx.eventMeta?.[key] ?? '';
|
||||
return {
|
||||
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 {
|
||||
return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) =>
|
||||
resolveTemplateToken(expr, ctx),
|
||||
);
|
||||
return template.replace(/\{\{([^{}]+)\}\}/g, (full, expr: string) => {
|
||||
const res = 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 {
|
||||
return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) =>
|
||||
posixSingleQuote(resolveTemplateToken(expr, ctx)),
|
||||
);
|
||||
let out = '';
|
||||
let quote: 'none' | 'single' | 'double' = 'none';
|
||||
let i = 0;
|
||||
|
||||
while (i < template.length) {
|
||||
const ch = template[i]!;
|
||||
if (quote === 'none') {
|
||||
if (ch === '\\' && i + 1 < template.length) {
|
||||
out += template.slice(i, i + 2);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === "'") {
|
||||
quote = 'single';
|
||||
out += ch;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
quote = 'double';
|
||||
out += ch;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
} else if (quote === 'single') {
|
||||
if (ch === "'") {
|
||||
quote = 'none';
|
||||
out += ch;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
} else if (quote === 'double') {
|
||||
if (ch === '\\' && i + 1 < template.length) {
|
||||
out += template.slice(i, i + 2);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
quote = 'none';
|
||||
out += ch;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (ch === '{' && template[i + 1] === '{') {
|
||||
const closeIdx = template.indexOf('}}', i + 2);
|
||||
if (closeIdx > i + 1) {
|
||||
const expr = template.slice(i + 2, closeIdx);
|
||||
const resolved = resolveTemplateToken(expr, ctx);
|
||||
if (!resolved.matched) {
|
||||
out += template.slice(i, closeIdx + 2);
|
||||
} else if (quote === 'single') {
|
||||
out += escapeInsideSingleQuotedShell(resolved.value);
|
||||
} else if (quote === 'double') {
|
||||
out += escapeDoubleQuotedShell(resolved.value);
|
||||
} else {
|
||||
out += posixSingleQuote(resolved.value);
|
||||
}
|
||||
i = closeIdx + 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
out += ch;
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function resolveTargetServers(
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import crypto from 'node:crypto';
|
|||
import path from 'node:path';
|
||||
import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import type { KnownHostsService } from '../ssh/known-hosts.js';
|
||||
import type { SftpService } from '../ssh/sftp-service.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
import { posixSingleQuote } from '../ssh/sudo.js';
|
||||
|
|
@ -15,8 +16,42 @@ export interface TransferResult {
|
|||
durationMs: number;
|
||||
}
|
||||
|
||||
const FILE_TYPE_MASK = 0o170000;
|
||||
const MODE_DIR = 0o040000;
|
||||
const MODE_REG = 0o100000;
|
||||
|
||||
function isDirMode(mode: number): boolean {
|
||||
return (mode & 0o170000) === 0o040000;
|
||||
return (mode & FILE_TYPE_MASK) === MODE_DIR;
|
||||
}
|
||||
|
||||
function isRegularMode(mode: number): boolean {
|
||||
return (mode & FILE_TYPE_MASK) === MODE_REG;
|
||||
}
|
||||
|
||||
function assertSafeRemotePath(rawPath: string, label: string): string {
|
||||
const trimmed = rawPath.trim();
|
||||
if (!trimmed || /[\x00-\x1f\x7f]/.test(trimmed)) {
|
||||
throw new Error(`Invalid ${label} path`);
|
||||
}
|
||||
const parts = trimmed.split('/');
|
||||
if (parts.some((seg) => seg === '..')) {
|
||||
throw new Error(`${label} path cannot contain ".." traversal segments`);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function sanitizeRsyncExcludes(excludes?: string[]): string[] {
|
||||
if (!excludes || excludes.length === 0) return [];
|
||||
const out: string[] = [];
|
||||
for (const raw of excludes) {
|
||||
const clean = raw.trim();
|
||||
if (!clean) continue;
|
||||
if (/[\x00-\x1f\x7f]/.test(clean) || clean.startsWith('-')) {
|
||||
throw new Error(`Invalid rsync exclude pattern: "${clean}"`);
|
||||
}
|
||||
out.push(clean);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function promisifySftp<T>(
|
||||
|
|
@ -46,6 +81,7 @@ export class TransferEngine {
|
|||
private readonly sshPool: SSHPool,
|
||||
private readonly _sftpService: SftpService,
|
||||
private readonly configManager: ConfigManager,
|
||||
private readonly knownHosts?: KnownHostsService,
|
||||
) {
|
||||
void this._sftpService;
|
||||
}
|
||||
|
|
@ -54,6 +90,8 @@ export class TransferEngine {
|
|||
mode: 'hub-relayed' | 'direct';
|
||||
source: { serverId: string; path: string };
|
||||
destination: { serverId: string; path: string };
|
||||
delete?: boolean;
|
||||
exclude?: string[];
|
||||
sudo?: boolean;
|
||||
timeoutMs?: number;
|
||||
signal?: AbortSignal;
|
||||
|
|
@ -72,12 +110,29 @@ export class TransferEngine {
|
|||
throw new Error(`Destination server "${opts.destination.serverId}" not found or disabled`);
|
||||
}
|
||||
|
||||
const safeSrcPath = assertSafeRemotePath(opts.source.path, 'source');
|
||||
const safeDstPath = assertSafeRemotePath(opts.destination.path, 'destination');
|
||||
const started = Date.now();
|
||||
const timeoutMs = opts.timeoutMs ?? 600_000;
|
||||
|
||||
if (opts.mode === 'direct') {
|
||||
const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`;
|
||||
const cmd = `rsync -az -e ${posixSingleQuote(sshOpt)} -- ${posixSingleQuote(opts.source.path)} ${posixSingleQuote(`${dstServer.username}@${dstServer.host}:${opts.destination.path}`)}`;
|
||||
const safeExcludes = sanitizeRsyncExcludes(opts.exclude);
|
||||
const excludeFlags = safeExcludes
|
||||
.map((ex) => `--exclude=${posixSingleQuote(ex)} `)
|
||||
.join('');
|
||||
const deleteFlag = opts.delete ? '--delete ' : '';
|
||||
const dstTarget = `${dstServer.username}@${dstServer.host}:${safeDstPath}`;
|
||||
const khLine = this.knownHosts?.getOpenSshKnownHostLine(dstServer);
|
||||
|
||||
let cmd: string;
|
||||
if (khLine) {
|
||||
const sshCmd = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$_kh`;
|
||||
cmd = `_kh=$(mktemp /tmp/.gcoord_kh.XXXXXX) && chmod 600 "$_kh" && trap 'rm -f -- "$_kh"' EXIT && printf '%s\\n' ${posixSingleQuote(khLine)} > "$_kh" && rsync -az -s --stats -e "${sshCmd}" ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`;
|
||||
} else {
|
||||
const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`;
|
||||
cmd = `rsync -az -s --stats -e ${posixSingleQuote(sshOpt)} ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`;
|
||||
}
|
||||
|
||||
opts.onProgress?.(`Running direct rsync on ${srcServer.id}...`);
|
||||
|
||||
const handle = await this.sshPool.execStream(srcServer.id, cmd, {
|
||||
|
|
@ -157,8 +212,8 @@ export class TransferEngine {
|
|||
|
||||
return {
|
||||
mode: 'direct',
|
||||
sourcePath: opts.source.path,
|
||||
destinationPath: opts.destination.path,
|
||||
sourcePath: safeSrcPath,
|
||||
destinationPath: safeDstPath,
|
||||
filesTransferred: 1,
|
||||
bytesTransferred: 0,
|
||||
durationMs: Date.now() - started,
|
||||
|
|
@ -201,16 +256,21 @@ export class TransferEngine {
|
|||
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
try {
|
||||
const trimmedDest = opts.destination.path.trim();
|
||||
const trimmedDest = safeDstPath;
|
||||
const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/');
|
||||
const resolvedSrc = await this.resolveRemotePath(srcSftp, opts.source.path);
|
||||
const resolvedDest = await this.resolveRemotePath(dstSftp, opts.destination.path);
|
||||
const resolvedSrc = await this.resolveRemotePath(srcSftp, safeSrcPath);
|
||||
const resolvedDest = await this.resolveRemotePath(dstSftp, safeDstPath);
|
||||
|
||||
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 bytesTransferred = 0;
|
||||
|
||||
if (isDirMode(srcStat.mode ?? 0)) {
|
||||
if (isDirMode(srcMode)) {
|
||||
const dstStat = await promisifySftp<Stats>((cb) => dstSftp!.stat(resolvedDest, cb)).catch(
|
||||
() => null,
|
||||
);
|
||||
|
|
@ -254,7 +314,7 @@ export class TransferEngine {
|
|||
dstSftp,
|
||||
resolvedSrc,
|
||||
targetFile,
|
||||
srcStat.mode ?? 0o644,
|
||||
srcMode || 0o644,
|
||||
activeStreams,
|
||||
() => timedOutOrAborted,
|
||||
opts.onProgress,
|
||||
|
|
@ -341,10 +401,21 @@ export class TransferEngine {
|
|||
let files = 0;
|
||||
let bytes = 0;
|
||||
for (const entry of entries) {
|
||||
if (entry.filename === '.' || entry.filename === '..') continue;
|
||||
if (
|
||||
entry.filename === '.' ||
|
||||
entry.filename === '..' ||
|
||||
entry.filename.includes('/') ||
|
||||
entry.filename.includes('\0')
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const srcChild = path.posix.join(srcDir, entry.filename);
|
||||
const dstChild = path.posix.join(dstDir, entry.filename);
|
||||
const mode = entry.attrs.mode ?? 0;
|
||||
let 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)) {
|
||||
const sub = await this.copyDirectoryRecursive(
|
||||
|
|
@ -358,7 +429,7 @@ export class TransferEngine {
|
|||
);
|
||||
files += sub.files;
|
||||
bytes += sub.bytes;
|
||||
} else {
|
||||
} else if (isRegularMode(mode)) {
|
||||
const copied = await this.copySingleFile(
|
||||
srcSftp,
|
||||
dstSftp,
|
||||
|
|
@ -371,6 +442,8 @@ export class TransferEngine {
|
|||
);
|
||||
files += 1;
|
||||
bytes += copied;
|
||||
} else {
|
||||
onProgress?.(`Skipping non-regular entry ${srcChild}`);
|
||||
}
|
||||
}
|
||||
return { files, bytes };
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -351,7 +351,7 @@ export class ConfigManager {
|
|||
const channelIds = new Set(this.alerts.channels.map((c) => c.id));
|
||||
if (this.vault && this.vault.isRuntimeReady) {
|
||||
for (const ch of this.alerts.channels) {
|
||||
if (!this.vault.hasCredential(ch.secretRef)) {
|
||||
if (ch.secretRef && !this.vault.hasCredential(ch.secretRef)) {
|
||||
next.push({
|
||||
filePath: 'alerts.json',
|
||||
code: 'MISSING_CHANNEL_SECRET',
|
||||
|
|
@ -368,6 +368,21 @@ export class ConfigManager {
|
|||
}
|
||||
}
|
||||
|
||||
for (const ch of this.alerts.channels) {
|
||||
if (
|
||||
ch.url &&
|
||||
/(discord\.com\/api\/webhooks\/|api\.telegram\.org\/bot|[?&](token|key|secret|password)=)/i.test(
|
||||
ch.url,
|
||||
)
|
||||
) {
|
||||
next.push({
|
||||
filePath: 'alerts.json',
|
||||
code: 'ALERT_INLINE_SECRET',
|
||||
message: `Alert channel "${ch.id}" URL appears to contain an inline token/secret; store secrets in Vault via secretRef instead.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const rule of this.alerts.rules) {
|
||||
for (const cid of rule.channelIds) {
|
||||
if (!channelIds.has(cid)) {
|
||||
|
|
@ -604,6 +619,7 @@ export class ConfigManager {
|
|||
ignoreInitial: true,
|
||||
persistent: true,
|
||||
depth: 2,
|
||||
followSymlinks: false,
|
||||
});
|
||||
|
||||
const scheduleReload = (absPath: string, kind: 'upsert' | 'unlink') => {
|
||||
|
|
@ -813,11 +829,39 @@ export class ConfigManager {
|
|||
}
|
||||
|
||||
private resolveSafeAbsPath(relPath: string): string {
|
||||
const resolved = path.resolve(this.configDir, relPath);
|
||||
const root = path.resolve(this.configDir);
|
||||
const resolved = path.resolve(root, relPath);
|
||||
if (!resolved.startsWith(`${root}${path.sep}`)) {
|
||||
throw new Error(`Path escapes config directory: ${relPath}`);
|
||||
}
|
||||
|
||||
// Verify no symlinked directory/file components inside configDir
|
||||
let cur = root;
|
||||
const parts = path.relative(root, resolved).split(path.sep).filter(Boolean);
|
||||
for (const part of parts) {
|
||||
cur = path.join(cur, part);
|
||||
if (fs.existsSync(cur)) {
|
||||
const lstat = fs.lstatSync(cur);
|
||||
if (lstat.isSymbolicLink()) {
|
||||
throw new Error(`Symlinks are not allowed inside config directory: ${relPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (fs.existsSync(root)) {
|
||||
const realRoot = fs.realpathSync(root);
|
||||
let checkPath = resolved;
|
||||
while (!fs.existsSync(checkPath) && checkPath !== root) {
|
||||
checkPath = path.dirname(checkPath);
|
||||
}
|
||||
if (fs.existsSync(checkPath)) {
|
||||
const realTarget = fs.realpathSync(checkPath);
|
||||
if (realTarget !== realRoot && !realTarget.startsWith(`${realRoot}${path.sep}`)) {
|
||||
throw new Error(`Realpath escapes config directory: ${relPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return resolved;
|
||||
}
|
||||
|
||||
|
|
@ -898,8 +942,8 @@ export class ConfigManager {
|
|||
}
|
||||
|
||||
private writeAtomicFile(absPath: string, content: string): void {
|
||||
fs.mkdirSync(path.dirname(absPath), { recursive: true });
|
||||
const tmpPath = `${absPath}.tmp.${process.pid}.${Date.now()}`;
|
||||
fs.mkdirSync(path.dirname(absPath), { recursive: true, mode: 0o700 });
|
||||
const tmpPath = `${absPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
|
||||
const fd = fs.openSync(tmpPath, 'w', 0o600);
|
||||
try {
|
||||
fs.writeFileSync(fd, content, 'utf8');
|
||||
|
|
|
|||
|
|
@ -138,12 +138,12 @@ export const PRESET_SYSTEMS: SystemConfig[] = [
|
|||
discovery: {
|
||||
type: 'command',
|
||||
command:
|
||||
'systemctl list-units --type=service --all --no-pager --no-legend --plain | awk \'{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 \'NF && $1 !~ /^UNIT$/ {print $1}\' | { if [ -n "$GCOORD_PARAM_UNITFILTER" ]; then grep -E -- "$GCOORD_PARAM_UNITFILTER" || true; else cat; fi; }',
|
||||
parser: 'lines',
|
||||
},
|
||||
status: {
|
||||
command:
|
||||
'systemctl show "$GCOORD_ITEM_NAME" --property=Id,LoadState,ActiveState,SubState,MainPID --no-pager | awk -F= \'BEGIN{printf "{"} NR>1{printf ","} {gsub(/"/,"\\\\\"",$2); printf "\\"%s\\":\\"%s\\"",$1,$2} END{printf "}\\n"}\'',
|
||||
'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"}\'',
|
||||
parser: 'json',
|
||||
health: {
|
||||
field: 'ActiveState',
|
||||
|
|
@ -322,7 +322,10 @@ export function seedDefaultConfigs(configDir: string): string[] {
|
|||
for (const [relPath, obj] of defaults) {
|
||||
const absPath = path.join(configDir, relPath);
|
||||
if (!fs.existsSync(absPath)) {
|
||||
fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, 'utf8');
|
||||
fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, {
|
||||
encoding: 'utf8',
|
||||
mode: 0o600,
|
||||
});
|
||||
created.push(relPath);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
132
src/server/config/runtime-limits.ts
Normal file
132
src/server/config/runtime-limits.ts
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
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'];
|
||||
}
|
||||
|
|
@ -1,26 +1,62 @@
|
|||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import Database from 'better-sqlite3';
|
||||
import type { RuntimeLimits } from '../config/runtime-limits.js';
|
||||
import { migration001Initial, type Migration } from './migrations/001_initial.js';
|
||||
import { migration002MultiAuth } from './migrations/002_multi_auth.js';
|
||||
import { migration003Phase4Meta } from './migrations/003_phase4_meta.js';
|
||||
import { migration004V11 } from './migrations/004_v1_1.js';
|
||||
|
||||
const MIGRATIONS: Migration[] = [
|
||||
migration001Initial,
|
||||
migration002MultiAuth,
|
||||
migration003Phase4Meta,
|
||||
migration004V11,
|
||||
];
|
||||
|
||||
function chmodBestEffort(targetPath: string, mode: number): void {
|
||||
try {
|
||||
if (fs.existsSync(targetPath)) {
|
||||
fs.chmodSync(targetPath, mode);
|
||||
}
|
||||
} catch {
|
||||
// Best effort on filesystems without POSIX permissions
|
||||
}
|
||||
}
|
||||
|
||||
export function applyDatabaseThrottlePragmas(
|
||||
db: Database.Database,
|
||||
limits: Pick<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 {
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
const parentDir = path.dirname(dbPath);
|
||||
fs.mkdirSync(parentDir, { recursive: true, mode: 0o700 });
|
||||
chmodBestEffort(parentDir, 0o700);
|
||||
const db = new Database(dbPath);
|
||||
|
||||
db.pragma('journal_mode = WAL');
|
||||
db.pragma('synchronous = NORMAL');
|
||||
db.pragma('foreign_keys = ON');
|
||||
db.pragma('busy_timeout = 5000');
|
||||
db.pragma('secure_delete = ON');
|
||||
db.pragma('cache_size = -8000');
|
||||
db.pragma('mmap_size = 0');
|
||||
db.pragma('temp_store = FILE');
|
||||
db.pragma('wal_autocheckpoint = 1000');
|
||||
db.pragma('journal_size_limit = 16777216');
|
||||
|
||||
runMigrations(db);
|
||||
chmodBestEffort(dbPath, 0o600);
|
||||
chmodBestEffort(`${dbPath}-wal`, 0o600);
|
||||
chmodBestEffort(`${dbPath}-shm`, 0o600);
|
||||
return db;
|
||||
}
|
||||
|
||||
|
|
|
|||
65
src/server/db/migrations/004_v1_1.ts
Normal file
65
src/server/db/migrations/004_v1_1.ts
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
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);
|
||||
`);
|
||||
},
|
||||
};
|
||||
|
|
@ -1,14 +1,27 @@
|
|||
import path from 'node:path';
|
||||
import { createGCoordinatorServer } from './app.js';
|
||||
import { normalizeThrottleMode } from './config/runtime-limits.js';
|
||||
|
||||
function parseCsvList(raw: string | undefined): string[] | undefined {
|
||||
if (!raw || !raw.trim()) return undefined;
|
||||
const list = raw
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
return list.length > 0 ? list : undefined;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const dataDir = path.resolve(process.env.GCOORD_DATA_DIR ?? './data');
|
||||
const port = Number(process.env.PORT ?? 3000);
|
||||
const host = process.env.HOST ?? '0.0.0.0';
|
||||
const trustCloudflare = process.env.TRUST_CLOUDFLARE === 'true';
|
||||
const trustedProxyCidrs = parseCsvList(process.env.TRUSTED_PROXY_CIDRS);
|
||||
const secretFilePath =
|
||||
process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key';
|
||||
const envMasterKey = process.env.GCOORD_MASTER_KEY;
|
||||
const envDbKey = process.env.GCOORD_DB_KEY;
|
||||
const proxyPortRaw = process.env.GCOORD_PROXY_PORT ? Number(process.env.GCOORD_PROXY_PORT) : undefined;
|
||||
|
||||
const instance = await createGCoordinatorServer({
|
||||
dataDir,
|
||||
|
|
@ -16,7 +29,17 @@ async function main(): Promise<void> {
|
|||
host,
|
||||
secretFilePath,
|
||||
envMasterKey,
|
||||
envDbKey,
|
||||
trustCloudflare,
|
||||
trustedProxyCidrs,
|
||||
allowLanTunnels: process.env.GCOORD_ALLOW_LAN_TUNNELS === 'true',
|
||||
proxyBaseDomain: process.env.GCOORD_PROXY_BASE_DOMAIN?.trim() || undefined,
|
||||
proxyPort: proxyPortRaw && Number.isFinite(proxyPortRaw) ? proxyPortRaw : undefined,
|
||||
webauthnRpId: process.env.GCOORD_WEBAUTHN_RP_ID?.trim() || undefined,
|
||||
webauthnOrigins: parseCsvList(process.env.GCOORD_WEBAUTHN_ORIGINS),
|
||||
metricsToken: process.env.GCOORD_METRICS_TOKEN?.trim() || undefined,
|
||||
throttleModeOverride: normalizeThrottleMode(process.env.GCOORD_THROTTLE_MODE),
|
||||
autoKeyFile: process.env.GCOORD_AUTO_KEYFILE === 'true',
|
||||
});
|
||||
|
||||
console.log(
|
||||
|
|
|
|||
|
|
@ -56,20 +56,67 @@ export const LINUX_METRIC_CMD = [
|
|||
].join('; ');
|
||||
|
||||
export const BSD_METRIC_CMD = [
|
||||
'printf "===SYSCTL===\\n"; sysctl -n hw.physmem hw.pagesize vm.loadavg kern.boottime kern.cp_time 2>/dev/null',
|
||||
'printf "===SYSCTL===\\n"; sysctl hw.physmem hw.pagesize vm.loadavg kern.boottime kern.cp_time 2>/dev/null || true',
|
||||
'printf "===VMSTAT===\\n"; vmstat -H 2>/dev/null || vmstat',
|
||||
'printf "===NET===\\n"; netstat -ibn 2>/dev/null',
|
||||
'printf "===DF===\\n"; df -kT 2>/dev/null || df -kP',
|
||||
].join('; ');
|
||||
|
||||
export const MACOS_METRIC_CMD = [
|
||||
'printf "===SYSCTL===\\n"; sysctl -n hw.memsize hw.pagesize vm.loadavg kern.boottime',
|
||||
'printf "===SYSCTL===\\n"; sysctl hw.memsize hw.pagesize vm.loadavg kern.boottime 2>/dev/null || true',
|
||||
'printf "===VMSTAT===\\n"; vm_stat',
|
||||
'printf "===TOP===\\n"; top -l 1 -n 0 2>/dev/null | grep -i "CPU usage" || true',
|
||||
'printf "===NET===\\n"; netstat -ibn 2>/dev/null || netstat -ib',
|
||||
'printf "===DF===\\n"; df -kP',
|
||||
].join('; ');
|
||||
|
||||
const VIRTUAL_NIC_PREFIXES = [
|
||||
'lo',
|
||||
'veth',
|
||||
'docker',
|
||||
'br-',
|
||||
'tun',
|
||||
'tap',
|
||||
'wg',
|
||||
'virbr',
|
||||
'dummy',
|
||||
'cilium',
|
||||
'flannel',
|
||||
'cni',
|
||||
'vxlan',
|
||||
'ifb',
|
||||
];
|
||||
|
||||
function isVirtualNic(iface: string): boolean {
|
||||
const clean = iface.trim().replace(/:$/, '').toLowerCase();
|
||||
return VIRTUAL_NIC_PREFIXES.some(
|
||||
(p) => clean === p || (p.endsWith('-') ? clean.startsWith(p) : clean.startsWith(p)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse `sysctl` sections supporting both `key: val` / `key=val` (resilient to
|
||||
* missing keys across BSD/macOS versions) and legacy unlabeled positional lines.
|
||||
*/
|
||||
function parseSysctlMap(rawText: string, positionalKeys: string[]): Map<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> {
|
||||
const sections: Record<string, string> = {};
|
||||
let current = '';
|
||||
|
|
@ -137,6 +184,7 @@ function parseDfLines(
|
|||
if (
|
||||
fsName === 'devfs' ||
|
||||
fsName === 'map' ||
|
||||
fsName.startsWith('/dev/loop') ||
|
||||
!Number.isFinite(totalKb) ||
|
||||
totalKb <= 0
|
||||
) {
|
||||
|
|
@ -205,9 +253,12 @@ export function parseLinuxOutput(
|
|||
Math.floor(Number((sec.UPTIME ?? '0').trim().split(/\s+/)[0]) || 0),
|
||||
);
|
||||
|
||||
// Network RX/TX across non-loopback interfaces
|
||||
let netRxBytes = 0;
|
||||
let netTxBytes = 0;
|
||||
// Network RX/TX prioritizing physical NICs and excluding loopback/virtual bridges
|
||||
let physRxBytes = 0;
|
||||
let physTxBytes = 0;
|
||||
let hasPhys = false;
|
||||
let fallbackRxBytes = 0;
|
||||
let fallbackTxBytes = 0;
|
||||
for (const line of (sec.NET ?? '').split(/\r?\n/)) {
|
||||
const colon = line.indexOf(':');
|
||||
if (colon <= 0) continue;
|
||||
|
|
@ -215,10 +266,19 @@ export function parseLinuxOutput(
|
|||
if (iface === 'lo' || iface.startsWith('lo:')) continue;
|
||||
const cols = line.slice(colon + 1).trim().split(/\s+/);
|
||||
if (cols.length >= 9) {
|
||||
netRxBytes += Number(cols[0]) || 0;
|
||||
netTxBytes += Number(cols[8]) || 0;
|
||||
const rx = Number(cols[0]) || 0;
|
||||
const tx = Number(cols[8]) || 0;
|
||||
fallbackRxBytes += rx;
|
||||
fallbackTxBytes += tx;
|
||||
if (!isVirtualNic(iface)) {
|
||||
hasPhys = true;
|
||||
physRxBytes += rx;
|
||||
physTxBytes += tx;
|
||||
}
|
||||
}
|
||||
}
|
||||
const netRxBytes = hasPhys ? physRxBytes : fallbackRxBytes;
|
||||
const netTxBytes = hasPhys ? physTxBytes : fallbackTxBytes;
|
||||
|
||||
let netRxBps = 0;
|
||||
let netTxBps = 0;
|
||||
|
|
@ -267,25 +327,28 @@ export function parseBsdOutput(
|
|||
nowMs = Date.now(),
|
||||
): CollectOutput {
|
||||
const sec = splitSections(stdout);
|
||||
const sysctlLines = (sec.SYSCTL ?? '')
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter(Boolean);
|
||||
const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [
|
||||
'hw.physmem',
|
||||
'hw.pagesize',
|
||||
'vm.loadavg',
|
||||
'kern.boottime',
|
||||
'kern.cp_time',
|
||||
]);
|
||||
|
||||
const physMemBytes = Number(sysctlLines[0]) || 0;
|
||||
const pageSize = Number(sysctlLines[1]) || 4096;
|
||||
const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0');
|
||||
const physMemBytes = Number(sysctl.get('hw.physmem')) || 0;
|
||||
const pageSize = Number(sysctl.get('hw.pagesize')) || 4096;
|
||||
const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0');
|
||||
const load1m = round2(Number(loadMatch?.[1] ?? 0));
|
||||
|
||||
let uptimeSec = 0;
|
||||
const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? '');
|
||||
const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctl.get('kern.boottime') ?? '');
|
||||
if (bootSecMatch) {
|
||||
uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!));
|
||||
}
|
||||
|
||||
let cpuTotal = 0;
|
||||
let cpuIdle = 0;
|
||||
const cpNums = (sysctlLines[4] ?? '')
|
||||
const cpNums = (sysctl.get('kern.cp_time') ?? '')
|
||||
.split(/\s+/)
|
||||
.map((n) => Number(n) || 0);
|
||||
if (cpNums.length >= 5) {
|
||||
|
|
@ -369,18 +432,20 @@ export function parseMacOsOutput(
|
|||
nowMs = Date.now(),
|
||||
): CollectOutput {
|
||||
const sec = splitSections(stdout);
|
||||
const sysctlLines = (sec.SYSCTL ?? '')
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter(Boolean);
|
||||
const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [
|
||||
'hw.memsize',
|
||||
'hw.pagesize',
|
||||
'vm.loadavg',
|
||||
'kern.boottime',
|
||||
]);
|
||||
|
||||
const memBytes = Number(sysctlLines[0]) || 0;
|
||||
const pageSize = Number(sysctlLines[1]) || 4096;
|
||||
const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0');
|
||||
const memBytes = Number(sysctl.get('hw.memsize')) || 0;
|
||||
const pageSize = Number(sysctl.get('hw.pagesize')) || 4096;
|
||||
const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0');
|
||||
const load1m = round2(Number(loadMatch?.[1] ?? 0));
|
||||
|
||||
let uptimeSec = 0;
|
||||
const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? '');
|
||||
const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctl.get('kern.boottime') ?? '');
|
||||
if (bootSecMatch) {
|
||||
uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,25 +26,30 @@ export interface ServerInspectionResult {
|
|||
serverId: string;
|
||||
os: OsType;
|
||||
collectedAt: number;
|
||||
sort: 'cpu' | 'mem';
|
||||
processes: ProcessEntry[];
|
||||
ports: PortEntry[];
|
||||
thermals: ThermalEntry[];
|
||||
}
|
||||
|
||||
const LINUX_INSPECT_CMD = [
|
||||
'printf "===PROCS===\\n"; ps -eo pid,user:24,%cpu,%mem,rss,args --sort=-%cpu 2>/dev/null | head -n 26 || ps -Ao pid,user,pcpu,pmem,rss,args | head -n 26',
|
||||
'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true',
|
||||
'printf "===THERMAL===\\n"; for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && printf "%s:%s\\n" "$(cat "$z/type" 2>/dev/null || basename "$z")" "$(cat "$z/temp")"; done 2>/dev/null || true',
|
||||
].join('; ');
|
||||
function buildLinuxInspectCmd(sort: 'cpu' | 'mem'): string {
|
||||
const linuxSort = sort === 'mem' ? '-rss' : '-%cpu';
|
||||
const bsdFlag = sort === 'mem' ? '-m' : '-r';
|
||||
return [
|
||||
`printf "===PROCS===\\n"; ps -eo pid,user:24,%cpu,%mem,rss,args --sort=${linuxSort} 2>/dev/null | head -n 41 || ps -Ao pid,user,pcpu,pmem,rss,args ${bsdFlag} 2>/dev/null | head -n 41 || ps -Ao pid,user,pcpu,pmem,rss,args | head -n 41`,
|
||||
'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true',
|
||||
'printf "===THERMAL===\\n"; for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && printf "%s:%s\\n" "$(cat "$z/type" 2>/dev/null || basename "$z")" "$(cat "$z/temp")"; done 2>/dev/null || true',
|
||||
].join('; ');
|
||||
}
|
||||
|
||||
const BSD_INSPECT_CMD = [
|
||||
'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 26',
|
||||
'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 41',
|
||||
'printf "===PORTS===\\n"; sockstat -l 2>/dev/null || netstat -an 2>/dev/null || true',
|
||||
'printf "===THERMAL===\\n"; sysctl dev.cpu 2>/dev/null | grep temperature || true',
|
||||
].join('; ');
|
||||
|
||||
const MACOS_INSPECT_CMD = [
|
||||
'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 26',
|
||||
'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 41',
|
||||
'printf "===PORTS===\\n"; lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null || netstat -an 2>/dev/null || true',
|
||||
'printf "===THERMAL===\\n"; true',
|
||||
].join('; ');
|
||||
|
|
@ -54,6 +59,7 @@ export function parseInspectorOutput(
|
|||
os: OsType,
|
||||
stdout: string,
|
||||
collectedAt = Date.now(),
|
||||
sort: 'cpu' | 'mem' = 'cpu',
|
||||
): ServerInspectionResult {
|
||||
const sections: Record<string, string[]> = {};
|
||||
let current = '';
|
||||
|
|
@ -85,6 +91,12 @@ export function parseInspectorOutput(
|
|||
});
|
||||
}
|
||||
|
||||
processes.sort((a, b) =>
|
||||
sort === 'mem'
|
||||
? b.memPct - a.memPct || b.rssMb - a.rssMb || b.cpuPct - a.cpuPct
|
||||
: b.cpuPct - a.cpuPct || b.memPct - a.memPct,
|
||||
);
|
||||
|
||||
// Ports
|
||||
const ports: PortEntry[] = [];
|
||||
const portLines = sections.PORTS ?? [];
|
||||
|
|
@ -98,7 +110,6 @@ export function parseInspectorOutput(
|
|||
}
|
||||
const cols = trimmed.split(/\s+/);
|
||||
if (/^(tcp|udp|tcp4|tcp6|udp4|udp6)/i.test(cols[0] ?? '')) {
|
||||
// ss -tulnp format: Netid State Recv-Q Send-Q Local Peer Process
|
||||
if (cols.length >= 6 && (cols[1] === 'LISTEN' || cols[1] === 'UNCONN')) {
|
||||
ports.push({
|
||||
proto: cols[0]!,
|
||||
|
|
@ -113,14 +124,12 @@ export function parseInspectorOutput(
|
|||
});
|
||||
}
|
||||
} else if (cols.length >= 9 && cols[cols.length - 1] === '(LISTEN)') {
|
||||
// lsof format
|
||||
ports.push({
|
||||
proto: cols[7] ?? 'TCP',
|
||||
localAddress: cols[8] ?? '',
|
||||
process: `${cols[0]}(${cols[1]})`,
|
||||
});
|
||||
} else if (cols.length >= 6 && /^\d+$/.test(cols[2] ?? '')) {
|
||||
// sockstat -l: USER COMMAND PID FD PROTO LOCAL FOREIGN
|
||||
ports.push({
|
||||
proto: cols[4] ?? 'tcp',
|
||||
localAddress: cols[5] ?? '',
|
||||
|
|
@ -144,7 +153,7 @@ export function parseInspectorOutput(
|
|||
thermals.push({ zone, tempC });
|
||||
}
|
||||
|
||||
return { serverId, os, collectedAt, processes, ports, thermals };
|
||||
return { serverId, os, collectedAt, sort, processes, ports, thermals };
|
||||
}
|
||||
|
||||
export class ServerInspector {
|
||||
|
|
@ -153,11 +162,15 @@ export class ServerInspector {
|
|||
private readonly configManager: ConfigManager,
|
||||
) {}
|
||||
|
||||
async inspect(serverId: string): Promise<ServerInspectionResult> {
|
||||
async inspect(
|
||||
serverId: string,
|
||||
opts: { sort?: 'cpu' | 'mem'; useSudo?: boolean } = {},
|
||||
): Promise<ServerInspectionResult> {
|
||||
const server = this.configManager.getServer(serverId);
|
||||
if (!server) {
|
||||
throw new Error(`Unknown server "${serverId}"`);
|
||||
}
|
||||
const sort = opts.sort === 'mem' ? 'mem' : 'cpu';
|
||||
const runtime = this.sshPool.getState(serverId);
|
||||
const os = await detectServerOs(this.sshPool, server, runtime?.osDetected);
|
||||
const cmd =
|
||||
|
|
@ -165,9 +178,39 @@ export class ServerInspector {
|
|||
? MACOS_INSPECT_CMD
|
||||
: os === 'bsd'
|
||||
? BSD_INSPECT_CMD
|
||||
: LINUX_INSPECT_CMD;
|
||||
: buildLinuxInspectCmd(sort);
|
||||
|
||||
const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000 });
|
||||
return parseInspectorOutput(serverId, os, res.stdout);
|
||||
const res = await this.sshPool.exec(serverId, cmd, {
|
||||
timeoutMs: 15_000,
|
||||
sudo: opts.useSudo,
|
||||
});
|
||||
return parseInspectorOutput(serverId, os, res.stdout, Date.now(), sort);
|
||||
}
|
||||
|
||||
async signalProcess(
|
||||
serverId: string,
|
||||
pid: number,
|
||||
signal: 'SIGTERM' | 'SIGKILL',
|
||||
opts: { useSudo?: boolean } = {},
|
||||
): Promise<{ ok: boolean; pid: number; signal: string; stderr: string }> {
|
||||
const server = this.configManager.getServer(serverId);
|
||||
if (!server) {
|
||||
throw new Error(`Unknown server "${serverId}"`);
|
||||
}
|
||||
if (!Number.isInteger(pid) || pid < 1 || pid > 99_999_999) {
|
||||
throw new Error('Invalid PID');
|
||||
}
|
||||
const sigName = signal === 'SIGKILL' ? 'KILL' : 'TERM';
|
||||
const res = await this.sshPool.exec(
|
||||
serverId,
|
||||
`kill -s ${sigName} ${pid}`,
|
||||
{ timeoutMs: 10_000, sudo: opts.useSudo },
|
||||
);
|
||||
return {
|
||||
ok: res.exitCode === 0,
|
||||
pid,
|
||||
signal,
|
||||
stderr: res.stderr.trim(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import type {
|
|||
ProbeSample,
|
||||
} from '../../shared/ws-protocol.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import type { RuntimeLimits } from '../config/runtime-limits.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
import {
|
||||
|
|
@ -37,6 +38,7 @@ export interface MonitoringTickEvent {
|
|||
interface ServerTimers {
|
||||
metricTimer: NodeJS.Timeout | null;
|
||||
warmupTimer: NodeJS.Timeout | null;
|
||||
staggerTimer: NodeJS.Timeout | null;
|
||||
probeTimers: Map<string, NodeJS.Timeout>;
|
||||
pollingMetrics: boolean;
|
||||
}
|
||||
|
|
@ -54,6 +56,8 @@ export class MonitoringService {
|
|||
>();
|
||||
private maintenanceTimer: NodeJS.Timeout | null = null;
|
||||
private stopped = false;
|
||||
private inFlightPolls = 0;
|
||||
private readonly pollQueue: Array<() => void> = [];
|
||||
|
||||
constructor(
|
||||
private readonly db: Database.Database,
|
||||
|
|
@ -61,6 +65,7 @@ export class MonitoringService {
|
|||
private readonly vaultService: VaultService,
|
||||
private readonly sshPool: SSHPool,
|
||||
private readonly probeRunner: ProbeRunner,
|
||||
private readonly getRuntimeLimits?: () => RuntimeLimits,
|
||||
) {}
|
||||
|
||||
onTick(listener: (event: MonitoringTickEvent) => void): () => void {
|
||||
|
|
@ -96,6 +101,7 @@ export class MonitoringService {
|
|||
for (const timers of this.serverTimers.values()) {
|
||||
if (timers.metricTimer) clearInterval(timers.metricTimer);
|
||||
if (timers.warmupTimer) clearTimeout(timers.warmupTimer);
|
||||
if (timers.staggerTimer) clearTimeout(timers.staggerTimer);
|
||||
for (const pt of timers.probeTimers.values()) clearInterval(pt);
|
||||
}
|
||||
this.serverTimers.clear();
|
||||
|
|
@ -104,6 +110,9 @@ export class MonitoringService {
|
|||
close(): void {
|
||||
this.stopped = true;
|
||||
this.stopAll();
|
||||
while (this.pollQueue.length > 0) {
|
||||
this.pollQueue.shift()?.();
|
||||
}
|
||||
if (this.maintenanceTimer) {
|
||||
clearInterval(this.maintenanceTimer);
|
||||
this.maintenanceTimer = null;
|
||||
|
|
@ -119,10 +128,10 @@ export class MonitoringService {
|
|||
return;
|
||||
}
|
||||
|
||||
for (const server of this.configManager.listServers()) {
|
||||
if (!server.enabled) continue;
|
||||
this.scheduleServer(server);
|
||||
}
|
||||
const enabledServers = this.configManager.listServers().filter((s) => s.enabled);
|
||||
enabledServers.forEach((server, idx) => {
|
||||
this.scheduleServer(server, idx);
|
||||
});
|
||||
}
|
||||
|
||||
getLatest(serverId: string): LatestServerTelemetry | undefined {
|
||||
|
|
@ -138,45 +147,105 @@ export class MonitoringService {
|
|||
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 {
|
||||
const settings = this.configManager.getSettings();
|
||||
const rawCutoff = nowMs - settings.rawRetentionHours * 3600_000;
|
||||
const rollupCutoff = nowMs - settings.rollupRetentionDays * 86_400_000;
|
||||
const auditCutoff = nowMs - settings.auditRetentionDays * 86_400_000;
|
||||
const workflowCutoff = nowMs - settings.workflowRunRetentionDays * 86_400_000;
|
||||
const alertCutoff = nowMs - settings.alertEventRetentionDays * 86_400_000;
|
||||
|
||||
const tx = this.db.transaction(() => {
|
||||
// Aggregate hourly rollups from raw metrics
|
||||
// Stage 1: Aggregate 1h rollups preserving any partial bucket spanning rawCutoff
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max)
|
||||
`INSERT INTO metrics_rollup (
|
||||
bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max,
|
||||
mem_avg_pct, load_max, net_rx_avg_bps, net_tx_avg_bps, disk_max_pct
|
||||
)
|
||||
SELECT
|
||||
(ts / 3600000) * 3600000 AS bucket_ts,
|
||||
(r.ts / 3600000) * 3600000 AS bucket_ts,
|
||||
'1h' AS granularity,
|
||||
server_id,
|
||||
MIN(cpu_pct),
|
||||
AVG(cpu_pct),
|
||||
MAX(cpu_pct),
|
||||
COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0),
|
||||
MAX(load_1m)
|
||||
FROM metrics_raw
|
||||
GROUP BY server_id, (ts / 3600000) * 3600000`,
|
||||
r.server_id,
|
||||
MIN(r.cpu_pct),
|
||||
AVG(r.cpu_pct),
|
||||
MAX(r.cpu_pct),
|
||||
COALESCE(AVG(CASE WHEN r.mem_total_mb > 0 THEN (r.mem_used_mb * 100.0 / r.mem_total_mb) ELSE 0 END), 0),
|
||||
MAX(r.load_1m),
|
||||
AVG(r.net_rx_bps),
|
||||
AVG(r.net_tx_bps),
|
||||
COALESCE(MAX(d.max_disk_pct), 0)
|
||||
FROM metrics_raw r
|
||||
LEFT JOIN (
|
||||
SELECT server_id, ts, MAX(used_pct) AS max_disk_pct
|
||||
FROM metrics_disks
|
||||
GROUP BY server_id, ts
|
||||
) d ON d.server_id = r.server_id AND d.ts = r.ts
|
||||
GROUP BY r.server_id, (r.ts / 3600000) * 3600000
|
||||
ON CONFLICT(server_id, granularity, bucket_ts) DO UPDATE SET
|
||||
cpu_min = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_min ELSE MIN(metrics_rollup.cpu_min, excluded.cpu_min) END,
|
||||
cpu_max = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_max ELSE MAX(metrics_rollup.cpu_max, excluded.cpu_max) END,
|
||||
load_max = CASE WHEN excluded.bucket_ts >= ? THEN excluded.load_max ELSE MAX(metrics_rollup.load_max, excluded.load_max) END,
|
||||
disk_max_pct = CASE WHEN excluded.bucket_ts >= ? THEN excluded.disk_max_pct ELSE MAX(metrics_rollup.disk_max_pct, excluded.disk_max_pct) END,
|
||||
cpu_avg = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_avg ELSE metrics_rollup.cpu_avg END,
|
||||
mem_avg_pct = CASE WHEN excluded.bucket_ts >= ? THEN excluded.mem_avg_pct ELSE metrics_rollup.mem_avg_pct END,
|
||||
net_rx_avg_bps = CASE WHEN excluded.bucket_ts >= ? THEN excluded.net_rx_avg_bps ELSE metrics_rollup.net_rx_avg_bps END,
|
||||
net_tx_avg_bps = CASE WHEN excluded.bucket_ts >= ? THEN excluded.net_tx_avg_bps ELSE metrics_rollup.net_tx_avg_bps END`,
|
||||
)
|
||||
.run();
|
||||
.run(
|
||||
rawCutoff,
|
||||
rawCutoff,
|
||||
rawCutoff,
|
||||
rawCutoff,
|
||||
rawCutoff,
|
||||
rawCutoff,
|
||||
rawCutoff,
|
||||
rawCutoff,
|
||||
);
|
||||
|
||||
// Aggregate daily rollups
|
||||
// Stage 2: Aggregate 1d rollups from complete 1h buckets so raw pruning never truncates a day
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max)
|
||||
`INSERT INTO metrics_rollup (
|
||||
bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max,
|
||||
mem_avg_pct, load_max, net_rx_avg_bps, net_tx_avg_bps, disk_max_pct
|
||||
)
|
||||
SELECT
|
||||
(ts / 86400000) * 86400000 AS bucket_ts,
|
||||
(bucket_ts / 86400000) * 86400000 AS day_ts,
|
||||
'1d' AS granularity,
|
||||
server_id,
|
||||
MIN(cpu_pct),
|
||||
AVG(cpu_pct),
|
||||
MAX(cpu_pct),
|
||||
COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0),
|
||||
MAX(load_1m)
|
||||
FROM metrics_raw
|
||||
GROUP BY server_id, (ts / 86400000) * 86400000`,
|
||||
MIN(cpu_min),
|
||||
AVG(cpu_avg),
|
||||
MAX(cpu_max),
|
||||
AVG(mem_avg_pct),
|
||||
MAX(load_max),
|
||||
AVG(net_rx_avg_bps),
|
||||
AVG(net_tx_avg_bps),
|
||||
MAX(disk_max_pct)
|
||||
FROM metrics_rollup
|
||||
WHERE granularity = '1h'
|
||||
GROUP BY server_id, (bucket_ts / 86400000) * 86400000
|
||||
ON CONFLICT(server_id, granularity, bucket_ts) DO UPDATE SET
|
||||
cpu_min = MIN(metrics_rollup.cpu_min, excluded.cpu_min),
|
||||
cpu_max = MAX(metrics_rollup.cpu_max, excluded.cpu_max),
|
||||
load_max = MAX(metrics_rollup.load_max, excluded.load_max),
|
||||
disk_max_pct = MAX(metrics_rollup.disk_max_pct, excluded.disk_max_pct),
|
||||
cpu_avg = excluded.cpu_avg,
|
||||
mem_avg_pct = excluded.mem_avg_pct,
|
||||
net_rx_avg_bps = excluded.net_rx_avg_bps,
|
||||
net_tx_avg_bps = excluded.net_tx_avg_bps`,
|
||||
)
|
||||
.run();
|
||||
|
||||
|
|
@ -184,16 +253,65 @@ export class MonitoringService {
|
|||
this.db.prepare('DELETE FROM metrics_disks WHERE ts < ?').run(rawCutoff);
|
||||
this.db.prepare('DELETE FROM probe_results WHERE ts < ?').run(rawCutoff);
|
||||
this.db.prepare('DELETE FROM metrics_rollup WHERE bucket_ts < ?').run(rollupCutoff);
|
||||
this.db.prepare('DELETE FROM audit_log WHERE ts < ?').run(auditCutoff);
|
||||
this.db
|
||||
.prepare('DELETE FROM workflow_runs WHERE finished_at IS NOT NULL AND started_at < ?')
|
||||
.run(workflowCutoff);
|
||||
this.db
|
||||
.prepare(
|
||||
"DELETE FROM alert_events WHERE state = 'resolved' AND COALESCE(resolved_at, triggered_at) < ?",
|
||||
)
|
||||
.run(alertCutoff);
|
||||
this.db.prepare('DELETE FROM alert_silences WHERE expires_at < ?').run(nowMs);
|
||||
this.db
|
||||
.prepare('DELETE FROM broadcast_jobs WHERE finished_at IS NOT NULL AND started_at < ?')
|
||||
.run(workflowCutoff);
|
||||
});
|
||||
tx();
|
||||
}
|
||||
|
||||
queryProbeHistory(
|
||||
serverId: string,
|
||||
sinceMs = Date.now() - 24 * 3600_000,
|
||||
limit = 200,
|
||||
): Array<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'): {
|
||||
range: MetricRange;
|
||||
granularity: 'raw' | '1h' | '1d';
|
||||
points: Array<Record<string, unknown>>;
|
||||
latestDisks: DiskSample[];
|
||||
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 rangeMs: Record<MetricRange, number> = {
|
||||
|
|
@ -223,7 +341,9 @@ export class MonitoringService {
|
|||
points = this.db
|
||||
.prepare(
|
||||
`SELECT bucket_ts AS ts, cpu_min AS cpuMin, cpu_avg AS cpuAvg, cpu_max AS cpuMax,
|
||||
mem_avg_pct AS memAvgPct, load_max AS loadMax
|
||||
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
|
||||
WHERE server_id = ? AND granularity = ? AND bucket_ts >= ?
|
||||
ORDER BY bucket_ts ASC`,
|
||||
|
|
@ -240,6 +360,22 @@ export class MonitoringService {
|
|||
)
|
||||
.all(serverId, serverId) as DiskSample[];
|
||||
|
||||
const diskHistory = this.db
|
||||
.prepare(
|
||||
`SELECT ts, mount_point AS mountPoint, used_pct AS usedPct, used_mb AS usedMb, total_mb AS totalMb
|
||||
FROM metrics_disks
|
||||
WHERE server_id = ? AND ts >= ?
|
||||
ORDER BY ts ASC
|
||||
LIMIT 500`,
|
||||
)
|
||||
.all(serverId, since) as Array<{
|
||||
ts: number;
|
||||
mountPoint: string;
|
||||
usedPct: number;
|
||||
usedMb: number;
|
||||
totalMb: number;
|
||||
}>;
|
||||
|
||||
const latestProbes = this.db
|
||||
.prepare(
|
||||
`SELECT p.probe_id AS probeId, p.ok AS okInt, p.status_code AS statusCode,
|
||||
|
|
@ -262,6 +398,8 @@ export class MonitoringService {
|
|||
ts: number;
|
||||
}>;
|
||||
|
||||
const probeHistory = this.queryProbeHistory(serverId, since, 200);
|
||||
|
||||
return {
|
||||
range,
|
||||
granularity,
|
||||
|
|
@ -275,50 +413,88 @@ export class MonitoringService {
|
|||
error: r.error ?? undefined,
|
||||
ts: r.ts,
|
||||
})),
|
||||
probeHistory,
|
||||
diskHistory,
|
||||
};
|
||||
}
|
||||
|
||||
private scheduleServer(server: ServerConfig): void {
|
||||
private async withPollSlot<T>(fn: () => Promise<T>): Promise<T> {
|
||||
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 = {
|
||||
metricTimer: null,
|
||||
warmupTimer: null,
|
||||
staggerTimer: null,
|
||||
probeTimers: new Map(),
|
||||
pollingMetrics: false,
|
||||
};
|
||||
this.serverTimers.set(server.id, timers);
|
||||
|
||||
// Kick initial poll asynchronously without delaying syncServers()
|
||||
const hadDelta = this.deltaStates.has(server.id);
|
||||
void this.executeMetricPoll(server).then((ev) => {
|
||||
if (
|
||||
ev &&
|
||||
!hadDelta &&
|
||||
!this.stopped &&
|
||||
this.serverTimers.get(server.id) === timers &&
|
||||
server.pollIntervalSec >= 3
|
||||
) {
|
||||
const wt = setTimeout(() => {
|
||||
timers.warmupTimer = null;
|
||||
void this.executeMetricPoll(server);
|
||||
}, 1000);
|
||||
wt.unref();
|
||||
timers.warmupTimer = wt;
|
||||
}
|
||||
});
|
||||
const limits = this.getRuntimeLimits?.();
|
||||
const staggerMs =
|
||||
limits?.staggerPolls && index > 0 ? Math.min(index * 120, 2_500) : 0;
|
||||
|
||||
timers.metricTimer = setInterval(() => {
|
||||
void this.executeMetricPoll(server);
|
||||
}, server.pollIntervalSec * 1000);
|
||||
timers.metricTimer.unref();
|
||||
const kickInitialAndStartTimer = () => {
|
||||
if (this.stopped || this.serverTimers.get(server.id) !== timers) return;
|
||||
|
||||
for (const probe of server.probes) {
|
||||
if (!probe.enabled) continue;
|
||||
void this.executeProbe(server, probe.id);
|
||||
const pt = setInterval(() => {
|
||||
const hadDelta = this.deltaStates.has(server.id);
|
||||
void this.executeMetricPoll(server).then((ev) => {
|
||||
if (
|
||||
ev &&
|
||||
!hadDelta &&
|
||||
!this.stopped &&
|
||||
this.serverTimers.get(server.id) === timers &&
|
||||
server.pollIntervalSec >= 3
|
||||
) {
|
||||
const wt = setTimeout(() => {
|
||||
timers.warmupTimer = null;
|
||||
void this.executeMetricPoll(server);
|
||||
}, 1000);
|
||||
wt.unref();
|
||||
timers.warmupTimer = wt;
|
||||
}
|
||||
});
|
||||
|
||||
timers.metricTimer = setInterval(() => {
|
||||
void this.executeMetricPoll(server);
|
||||
}, server.pollIntervalSec * 1000);
|
||||
timers.metricTimer.unref();
|
||||
|
||||
for (const probe of server.probes) {
|
||||
if (!probe.enabled) continue;
|
||||
void this.executeProbe(server, probe.id);
|
||||
}, probe.intervalSec * 1000);
|
||||
pt.unref();
|
||||
timers.probeTimers.set(probe.id, pt);
|
||||
const pt = setInterval(() => {
|
||||
void this.executeProbe(server, probe.id);
|
||||
}, probe.intervalSec * 1000);
|
||||
pt.unref();
|
||||
timers.probeTimers.set(probe.id, pt);
|
||||
}
|
||||
};
|
||||
|
||||
if (staggerMs > 0) {
|
||||
const st = setTimeout(() => {
|
||||
timers.staggerTimer = null;
|
||||
kickInitialAndStartTimer();
|
||||
}, staggerMs);
|
||||
st.unref();
|
||||
timers.staggerTimer = st;
|
||||
} else {
|
||||
kickInitialAndStartTimer();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -332,51 +508,55 @@ export class MonitoringService {
|
|||
if (timerState) timerState.pollingMetrics = true;
|
||||
|
||||
try {
|
||||
const os = await detectServerOs(
|
||||
this.sshPool,
|
||||
server,
|
||||
this.osCache.get(server.id),
|
||||
);
|
||||
this.osCache.set(server.id, os);
|
||||
return await this.withPollSlot(async () => {
|
||||
if (this.stopped || !this.vaultService.isRuntimeReady) return null;
|
||||
|
||||
const collected = await collectServerMetrics(
|
||||
this.sshPool,
|
||||
server,
|
||||
os,
|
||||
this.deltaStates.get(server.id),
|
||||
);
|
||||
this.deltaStates.set(server.id, collected.nextState);
|
||||
const os = await detectServerOs(
|
||||
this.sshPool,
|
||||
server,
|
||||
this.osCache.get(server.id),
|
||||
);
|
||||
this.osCache.set(server.id, os);
|
||||
|
||||
this.persistMetricSample(server.id, collected.sample, collected.disks);
|
||||
const collected = await collectServerMetrics(
|
||||
this.sshPool,
|
||||
server,
|
||||
os,
|
||||
this.deltaStates.get(server.id),
|
||||
);
|
||||
this.deltaStates.set(server.id, collected.nextState);
|
||||
|
||||
const prevLatest = this.latest.get(server.id) ?? {
|
||||
serverId: server.id,
|
||||
disks: [],
|
||||
probes: {},
|
||||
};
|
||||
this.latest.set(server.id, {
|
||||
...prevLatest,
|
||||
os,
|
||||
sample: collected.sample,
|
||||
disks: collected.disks,
|
||||
lastError: undefined,
|
||||
});
|
||||
this.persistMetricSample(server.id, collected.sample, collected.disks);
|
||||
|
||||
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
|
||||
const prevLatest = this.latest.get(server.id) ?? {
|
||||
serverId: server.id,
|
||||
disks: [],
|
||||
probes: {},
|
||||
};
|
||||
this.latest.set(server.id, {
|
||||
...prevLatest,
|
||||
os,
|
||||
sample: collected.sample,
|
||||
disks: collected.disks,
|
||||
lastError: undefined,
|
||||
});
|
||||
|
||||
const probes = Object.values(this.latest.get(server.id)!.probes);
|
||||
const event: MonitoringTickEvent = {
|
||||
serverId: server.id,
|
||||
sample: collected.sample,
|
||||
disks: collected.disks,
|
||||
probes,
|
||||
};
|
||||
for (const listener of this.tickListeners) {
|
||||
try {
|
||||
listener(event);
|
||||
} catch {
|
||||
// Isolate listener errors
|
||||
}
|
||||
}
|
||||
}
|
||||
return event;
|
||||
return event;
|
||||
});
|
||||
} catch (err) {
|
||||
const prevLatest = this.latest.get(server.id) ?? {
|
||||
serverId: server.id,
|
||||
|
|
@ -397,8 +577,16 @@ export class MonitoringService {
|
|||
if (this.stopped || !this.vaultService.isRuntimeReady) return;
|
||||
const probe = server.probes.find((p) => p.id === probeId);
|
||||
if (!probe || !probe.enabled) return;
|
||||
await this.runAndPersistProbe(server, probe);
|
||||
}
|
||||
|
||||
const sample = await this.probeRunner.runProbe(server.id, probe);
|
||||
private async runAndPersistProbe(
|
||||
server: ServerConfig,
|
||||
probe: ServerConfig['probes'][number],
|
||||
): Promise<ProbeSample> {
|
||||
const sample = await this.withPollSlot(() =>
|
||||
this.probeRunner.runProbe(server.id, probe),
|
||||
);
|
||||
const ts = Date.now();
|
||||
this.db
|
||||
.prepare(
|
||||
|
|
@ -430,6 +618,7 @@ export class MonitoringService {
|
|||
// Isolate probe listener errors
|
||||
}
|
||||
}
|
||||
return sample;
|
||||
}
|
||||
|
||||
private hydrateLatestFromDb(): void {
|
||||
|
|
|
|||
|
|
@ -3,36 +3,93 @@ import tls from 'node:tls';
|
|||
import type { Duplex } from 'node:stream';
|
||||
import type { ServerProbe } from '../../shared/schemas/server.schema.js';
|
||||
import type { ProbeSample } from '../../shared/ws-protocol.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import {
|
||||
fetchWithEgressGuard,
|
||||
resolveAllowedEgressIps,
|
||||
} from '../security/egress-guard.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
|
||||
const MAX_PROBE_BODY_BYTES = 128 * 1024;
|
||||
|
||||
function decodeChunkedIfNeeded(head: string, body: string): string {
|
||||
if (!/^transfer-encoding:\s*chunked\b/im.test(head)) return body;
|
||||
let idx = 0;
|
||||
let out = '';
|
||||
while (idx < body.length) {
|
||||
const lineEnd = body.indexOf('\r\n', idx);
|
||||
if (lineEnd < 0) break;
|
||||
const sizeHex = body.slice(idx, lineEnd).split(';')[0]!.trim();
|
||||
const size = Number.parseInt(sizeHex, 16);
|
||||
if (!Number.isFinite(size) || size <= 0) break;
|
||||
idx = lineEnd + 2;
|
||||
out += body.slice(idx, idx + size);
|
||||
idx += size + 2;
|
||||
}
|
||||
return out || body;
|
||||
}
|
||||
|
||||
async function readResponseTextCapped(
|
||||
res: Response,
|
||||
maxBytes = MAX_PROBE_BODY_BYTES,
|
||||
): Promise<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(
|
||||
stream: Duplex,
|
||||
url: URL,
|
||||
timeoutMs: number,
|
||||
): Promise<{ statusCode: number; body: string }> {
|
||||
tlsOpts: { rejectUnauthorized?: boolean } = {},
|
||||
): Promise<{ statusCode: number; body: string; certExpiryDays?: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
let certExpiryDays: number | undefined;
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
stream.destroy();
|
||||
reject(new Error(`Target HTTP probe timed out after ${timeoutMs}ms`));
|
||||
reject(new Error(`HTTP probe timed out after ${timeoutMs}ms`));
|
||||
}, timeoutMs);
|
||||
|
||||
const servername = net.isIP(url.hostname) ? undefined : url.hostname;
|
||||
const transport: Duplex =
|
||||
url.protocol === 'https:'
|
||||
? tls.connect({ socket: stream, servername: url.hostname })
|
||||
? tls.connect({
|
||||
socket: stream,
|
||||
servername,
|
||||
rejectUnauthorized: tlsOpts.rejectUnauthorized ?? true,
|
||||
})
|
||||
: stream;
|
||||
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
const maxBytes = 256 * 1024;
|
||||
|
||||
const done = (err?: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
transport.destroy();
|
||||
stream.destroy();
|
||||
if (err) {
|
||||
reject(err);
|
||||
return;
|
||||
|
|
@ -40,36 +97,53 @@ function readHttpFromStream(
|
|||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
const headerEnd = raw.indexOf('\r\n\r\n');
|
||||
const head = headerEnd >= 0 ? raw.slice(0, headerEnd) : raw;
|
||||
const body = headerEnd >= 0 ? raw.slice(headerEnd + 4) : '';
|
||||
const rawBody = headerEnd >= 0 ? raw.slice(headerEnd + 4) : '';
|
||||
const statusLine = head.split('\r\n')[0] ?? '';
|
||||
const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(statusLine);
|
||||
if (!m) {
|
||||
reject(new Error(`Invalid HTTP response line: ${statusLine}`));
|
||||
return;
|
||||
}
|
||||
resolve({ statusCode: Number(m[1]), body });
|
||||
resolve({
|
||||
statusCode: Number(m[1]),
|
||||
body: decodeChunkedIfNeeded(head, rawBody),
|
||||
certExpiryDays,
|
||||
});
|
||||
};
|
||||
|
||||
transport.on('data', (chunk: Buffer) => {
|
||||
if (total < maxBytes) {
|
||||
chunks.push(chunk.subarray(0, maxBytes - total));
|
||||
if (total < MAX_PROBE_BODY_BYTES) {
|
||||
chunks.push(chunk.subarray(0, MAX_PROBE_BODY_BYTES - total));
|
||||
total += chunk.length;
|
||||
} else {
|
||||
transport.destroy();
|
||||
}
|
||||
});
|
||||
transport.once('end', () => done());
|
||||
transport.once('close', () => done());
|
||||
transport.once('error', (err) => done(err));
|
||||
if (transport !== stream) {
|
||||
stream.once('error', (err) => done(err));
|
||||
}
|
||||
|
||||
const pathAndQuery = `${url.pathname || '/'}${url.search || ''}`;
|
||||
const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname;
|
||||
const reqText =
|
||||
`GET ${pathAndQuery} HTTP/1.1\r\n` +
|
||||
`Host: ${hostHeader}\r\n` +
|
||||
`User-Agent: GCoordinator-Probe/1.0\r\n` +
|
||||
`User-Agent: GCoordinator-Probe/1.1\r\n` +
|
||||
`Accept-Encoding: identity\r\n` +
|
||||
`Connection: close\r\n\r\n`;
|
||||
|
||||
if (url.protocol === 'https:') {
|
||||
(transport as tls.TLSSocket).once('secureConnect', () => {
|
||||
const cert = (transport as tls.TLSSocket).getPeerCertificate(false);
|
||||
if (cert && typeof cert.valid_to === 'string') {
|
||||
const expMs = Date.parse(cert.valid_to);
|
||||
if (Number.isFinite(expMs)) {
|
||||
certExpiryDays = Math.floor((expMs - Date.now()) / 86_400_000);
|
||||
}
|
||||
}
|
||||
transport.write(reqText);
|
||||
});
|
||||
} else {
|
||||
|
|
@ -79,16 +153,26 @@ function readHttpFromStream(
|
|||
}
|
||||
|
||||
export class ProbeRunner {
|
||||
constructor(private readonly sshPool: SSHPool) {}
|
||||
constructor(
|
||||
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> {
|
||||
const started = Date.now();
|
||||
const allowedCidrs = this.configManager?.getSettings().security.egressAllowedCidrs ?? [];
|
||||
|
||||
try {
|
||||
if (probe.type === 'tcp') {
|
||||
if (probe.from === 'hub') {
|
||||
const ips = await resolveAllowedEgressIps(probe.host, allowedCidrs);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const sock = net.createConnection({
|
||||
host: probe.host,
|
||||
host: ips[0]!,
|
||||
port: probe.port,
|
||||
});
|
||||
const timer = setTimeout(() => {
|
||||
|
|
@ -125,19 +209,35 @@ export class ProbeRunner {
|
|||
}
|
||||
|
||||
// HTTP(S) probe
|
||||
const parsedUrl = new URL(probe.url);
|
||||
let statusCode: number;
|
||||
let body: string;
|
||||
let certExpiryDays: number | undefined;
|
||||
|
||||
if (probe.from === 'hub') {
|
||||
const res = await fetch(probe.url, {
|
||||
method: 'GET',
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(probe.timeoutMs),
|
||||
});
|
||||
statusCode = res.status;
|
||||
body = await res.text();
|
||||
if (
|
||||
parsedUrl.protocol === 'https:' &&
|
||||
(probe.tlsRejectUnauthorized === false || probe.tlsCheckExpiryDays !== undefined)
|
||||
) {
|
||||
const ips = await resolveAllowedEgressIps(parsedUrl.hostname, allowedCidrs);
|
||||
const port = parsedUrl.port ? Number(parsedUrl.port) : 443;
|
||||
const sock = net.createConnection({ host: ips[0]!, port });
|
||||
const resp = await readHttpFromStream(sock, parsedUrl, probe.timeoutMs, {
|
||||
rejectUnauthorized: probe.tlsRejectUnauthorized,
|
||||
});
|
||||
statusCode = resp.statusCode;
|
||||
body = resp.body;
|
||||
certExpiryDays = resp.certExpiryDays;
|
||||
} else {
|
||||
const res = await fetchWithEgressGuard(
|
||||
probe.url,
|
||||
{ method: 'GET', redirect: 'manual' },
|
||||
{ allowedCidrs, timeoutMs: probe.timeoutMs },
|
||||
);
|
||||
statusCode = res.status;
|
||||
body = await readResponseTextCapped(res, MAX_PROBE_BODY_BYTES);
|
||||
}
|
||||
} else {
|
||||
const parsedUrl = new URL(probe.url);
|
||||
const port = parsedUrl.port
|
||||
? Number(parsedUrl.port)
|
||||
: parsedUrl.protocol === 'https:'
|
||||
|
|
@ -149,24 +249,40 @@ export class ProbeRunner {
|
|||
port,
|
||||
probe.timeoutMs,
|
||||
);
|
||||
const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs);
|
||||
const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs, {
|
||||
rejectUnauthorized: probe.tlsRejectUnauthorized,
|
||||
});
|
||||
statusCode = resp.statusCode;
|
||||
body = resp.body;
|
||||
certExpiryDays = resp.certExpiryDays;
|
||||
}
|
||||
|
||||
const statusOk = statusCode === probe.expectedStatus;
|
||||
const bodyOk = probe.bodyIncludes ? body.includes(probe.bodyIncludes) : true;
|
||||
const ok = statusOk && bodyOk;
|
||||
const certOk =
|
||||
probe.tlsCheckExpiryDays !== undefined && certExpiryDays !== undefined
|
||||
? certExpiryDays >= probe.tlsCheckExpiryDays
|
||||
: true;
|
||||
const ok = statusOk && bodyOk && certOk;
|
||||
|
||||
let error: string | undefined;
|
||||
if (!ok) {
|
||||
if (!statusOk) {
|
||||
error = `Expected HTTP ${probe.expectedStatus}, got ${statusCode}`;
|
||||
} else if (!bodyOk) {
|
||||
error = `Response body missing substring "${probe.bodyIncludes}"`;
|
||||
} else {
|
||||
error = `TLS certificate expires in ${certExpiryDays}d (threshold ${probe.tlsCheckExpiryDays}d)`;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
probeId: probe.id,
|
||||
ok,
|
||||
statusCode,
|
||||
latencyMs: Date.now() - started,
|
||||
error: ok
|
||||
? undefined
|
||||
: !statusOk
|
||||
? `Expected HTTP ${probe.expectedStatus}, got ${statusCode}`
|
||||
: `Response body missing substring "${probe.bodyIncludes}"`,
|
||||
certExpiryDays,
|
||||
error,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
|
|
|
|||
180
src/server/monitoring/prometheus.ts
Normal file
180
src/server/monitoring/prometheus.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
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`);
|
||||
};
|
||||
}
|
||||
|
|
@ -20,6 +20,28 @@ export interface AuditLogRecord {
|
|||
details: string | null;
|
||||
}
|
||||
|
||||
export interface AuditListOptions {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
action?: string;
|
||||
actionPrefix?: string;
|
||||
status?: 'ok' | 'denied' | 'error';
|
||||
ip?: string;
|
||||
target?: string;
|
||||
q?: string;
|
||||
from?: number;
|
||||
to?: number;
|
||||
}
|
||||
|
||||
function escapeLike(input: string): string {
|
||||
return input.replace(/[\\%_]/g, '\\$&');
|
||||
}
|
||||
|
||||
function sanitizeCsvCell(value: string): string {
|
||||
const safe = /^[ \t]*[=+\-@\t\r]/.test(value) ? `'${value}` : value;
|
||||
return `"${safe.replace(/"/g, '""')}"`;
|
||||
}
|
||||
|
||||
export class AuditService {
|
||||
private readonly insertStmt;
|
||||
|
||||
|
|
@ -49,33 +71,143 @@ export class AuditService {
|
|||
);
|
||||
}
|
||||
|
||||
list(options: { limit?: number; offset?: number; action?: string } = {}): {
|
||||
private buildWhereClause(options: AuditListOptions): { sql: string; params: Array<string | number> } {
|
||||
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;
|
||||
items: AuditLogRecord[];
|
||||
} {
|
||||
const limit = Math.max(1, Math.min(200, options.limit ?? 50));
|
||||
const offset = Math.max(0, options.offset ?? 0);
|
||||
|
||||
if (options.action) {
|
||||
const countRow = this.db
|
||||
.prepare('SELECT COUNT(*) AS cnt FROM audit_log WHERE action = ?')
|
||||
.get(options.action) as { cnt: number };
|
||||
const items = this.db
|
||||
.prepare(
|
||||
'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log WHERE action = ? ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?',
|
||||
)
|
||||
.all(options.action, limit, offset) as AuditLogRecord[];
|
||||
return { total: countRow.cnt, items };
|
||||
}
|
||||
const where = this.buildWhereClause(options);
|
||||
|
||||
const countRow = this.db
|
||||
.prepare('SELECT COUNT(*) AS cnt FROM audit_log')
|
||||
.get() as { cnt: number };
|
||||
.prepare(`SELECT COUNT(*) AS cnt FROM audit_log ${where.sql}`)
|
||||
.get(...where.params) as { cnt: number };
|
||||
|
||||
const items = this.db
|
||||
.prepare(
|
||||
'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?',
|
||||
`SELECT id, ts, action, actor_ip, session_id_hash, target, status, details
|
||||
FROM audit_log ${where.sql}
|
||||
ORDER BY ts DESC, id DESC
|
||||
LIMIT ? OFFSET ?`,
|
||||
)
|
||||
.all(limit, offset) as AuditLogRecord[];
|
||||
.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`;
|
||||
}
|
||||
|
||||
const lines = [
|
||||
'id,ts,isoTime,action,status,actorIp,target,sessionIdHash,details',
|
||||
...rows.map((r) =>
|
||||
[
|
||||
String(r.id),
|
||||
String(r.ts),
|
||||
sanitizeCsvCell(new Date(r.ts).toISOString()),
|
||||
sanitizeCsvCell(r.action),
|
||||
sanitizeCsvCell(r.status),
|
||||
sanitizeCsvCell(r.actor_ip),
|
||||
sanitizeCsvCell(r.target ?? ''),
|
||||
sanitizeCsvCell(r.session_id_hash ?? ''),
|
||||
sanitizeCsvCell(r.details ?? ''),
|
||||
].join(','),
|
||||
),
|
||||
];
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
pruneOlderThan(retentionDays: number): number {
|
||||
const days = Math.max(1, retentionDays);
|
||||
const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
|
||||
return this.db.prepare('DELETE FROM audit_log WHERE ts < ?').run(cutoff).changes;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
generateAuthenticationOptions,
|
||||
generateRegistrationOptions,
|
||||
|
|
@ -17,18 +19,120 @@ import {
|
|||
type SecuritySettings,
|
||||
type StepUpPolicy,
|
||||
} from '../../shared/schemas/settings.schema.js';
|
||||
import type { RuntimeLimits } from '../config/runtime-limits.js';
|
||||
import type { EmergencyRecoveryService, SavedTotpEntry } from './recovery-store.js';
|
||||
import type { VaultService } from './vault.js';
|
||||
|
||||
const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
const BOOTSTRAP_TTL_MS = 15 * 60 * 1000;
|
||||
const WEBAUTHN_TTL_MS = 5 * 60 * 1000;
|
||||
const SESSION_REAPER_MS = 5 * 60 * 1000;
|
||||
const TOTP_PERIOD_SEC = 30;
|
||||
const DEFAULT_SECURITY = SecuritySettingsSchema.parse({});
|
||||
|
||||
export const SESSION_COOKIE_NAME = 'gcoord_sid';
|
||||
|
||||
export class AuthOverloadError extends Error {
|
||||
readonly code = 'AUTH_OVERLOADED';
|
||||
constructor(message = 'Authentication queue is busy; try again shortly') {
|
||||
super(message);
|
||||
this.name = 'AuthOverloadError';
|
||||
}
|
||||
}
|
||||
|
||||
export function loadOrCreateDbKey(options: { dataDir?: string; envDbKey?: string }): Buffer {
|
||||
if (options.envDbKey && options.envDbKey.trim().length > 0) {
|
||||
const clean = options.envDbKey.trim().toLowerCase();
|
||||
if (!/^[0-9a-f]{64}$/.test(clean)) {
|
||||
throw new Error('GCOORD_DB_KEY must be exactly 64 hex characters (32 bytes)');
|
||||
}
|
||||
return Buffer.from(clean, 'hex');
|
||||
}
|
||||
|
||||
if (!options.dataDir) {
|
||||
return crypto.randomBytes(32);
|
||||
}
|
||||
|
||||
const keyPath = path.join(options.dataDir, 'db.key');
|
||||
try {
|
||||
const stat = fs.lstatSync(keyPath);
|
||||
if (stat.isSymbolicLink() || !stat.isFile()) {
|
||||
throw new Error(`Refusing symlink or non-file db key at ${keyPath}`);
|
||||
}
|
||||
const clean = fs.readFileSync(keyPath, 'utf8').trim().toLowerCase();
|
||||
if (!/^[0-9a-f]{64}$/.test(clean)) {
|
||||
throw new Error(`Invalid db.key format at ${keyPath}`);
|
||||
}
|
||||
try {
|
||||
fs.chmodSync(keyPath, 0o600);
|
||||
} catch {
|
||||
// Best-effort POSIX permission tightening
|
||||
}
|
||||
return Buffer.from(clean, 'hex');
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const key = crypto.randomBytes(32);
|
||||
const hex = `${key.toString('hex')}\n`;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(keyPath), { recursive: true, mode: 0o700 });
|
||||
const fd = fs.openSync(
|
||||
keyPath,
|
||||
fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL,
|
||||
0o600,
|
||||
);
|
||||
try {
|
||||
fs.writeSync(fd, hex, 0, 'utf8');
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
return key;
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException)?.code === 'EEXIST') {
|
||||
const clean = fs.readFileSync(keyPath, 'utf8').trim().toLowerCase();
|
||||
if (!/^[0-9a-f]{64}$/.test(clean)) {
|
||||
throw new Error(`Invalid db.key format at ${keyPath}`);
|
||||
}
|
||||
return Buffer.from(clean, 'hex');
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function encryptTotpSecret(dbKey: Buffer, totpId: string, secretBase32: string): string {
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', dbKey, iv);
|
||||
cipher.setAAD(Buffer.from(`gcoord-totp-v1:${totpId}`, 'utf8'));
|
||||
const ct = Buffer.concat([cipher.update(secretBase32, 'utf8'), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return `v1:${iv.toString('hex')}:${tag.toString('hex')}:${ct.toString('hex')}`;
|
||||
}
|
||||
|
||||
export function decryptTotpSecret(dbKey: Buffer, totpId: string, encoded: string): string {
|
||||
const parts = encoded.split(':');
|
||||
if (parts.length !== 4 || parts[0] !== 'v1') {
|
||||
throw new Error(`Invalid encrypted TOTP envelope for ${totpId}`);
|
||||
}
|
||||
const iv = Buffer.from(parts[1]!, 'hex');
|
||||
const tag = Buffer.from(parts[2]!, 'hex');
|
||||
const ct = Buffer.from(parts[3]!, 'hex');
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', dbKey, iv);
|
||||
decipher.setAAD(Buffer.from(`gcoord-totp-v1:${totpId}`, 'utf8'));
|
||||
decipher.setAuthTag(tag);
|
||||
return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8');
|
||||
}
|
||||
|
||||
function timingSafeStringEqual(a: string, b: string): boolean {
|
||||
const bufA = Buffer.from(a, 'utf8');
|
||||
const bufB = Buffer.from(b, 'utf8');
|
||||
if (bufA.length !== bufB.length) return false;
|
||||
return crypto.timingSafeEqual(bufA, bufB);
|
||||
}
|
||||
|
||||
export interface AuthSession {
|
||||
idHash: string;
|
||||
csrfTokenHash: string;
|
||||
|
|
@ -96,8 +200,16 @@ export type StepUpInput =
|
|||
|
||||
export interface AuthServiceOptions {
|
||||
getSecuritySettings?: () => SecuritySettings;
|
||||
getRuntimeLimits?: () => RuntimeLimits;
|
||||
recoveryStore?: EmergencyRecoveryService;
|
||||
vaultService?: VaultService;
|
||||
dataDir?: string;
|
||||
envDbKey?: string;
|
||||
onSecurityEvent?: (event: {
|
||||
type: string;
|
||||
ip?: string;
|
||||
details?: Record<string, unknown>;
|
||||
}) => void;
|
||||
}
|
||||
|
||||
interface AdminRow {
|
||||
|
|
@ -120,8 +232,10 @@ interface TotpRow {
|
|||
id: string;
|
||||
label: string;
|
||||
secret_base32: string;
|
||||
secret_enc: string | null;
|
||||
last_login_step: number | null;
|
||||
last_stepup_step: number | null;
|
||||
last_used_step: number | null;
|
||||
created_at: number;
|
||||
}
|
||||
|
||||
|
|
@ -179,6 +293,8 @@ function computeElevatedUntil(
|
|||
return fromLogin ? null : nowMs + 60_000;
|
||||
case '5m':
|
||||
return nowMs + 5 * 60 * 1000;
|
||||
case '15m':
|
||||
return nowMs + 15 * 60 * 1000;
|
||||
case '1h':
|
||||
return nowMs + 60 * 60 * 1000;
|
||||
case '24h':
|
||||
|
|
@ -189,13 +305,21 @@ function computeElevatedUntil(
|
|||
}
|
||||
|
||||
export class AuthService {
|
||||
private pendingBootstrap: { secretBase32: string; createdAt: number } | null = null;
|
||||
private pendingBootstrap: { secretBase32: string; token: string; createdAt: number } | null = null;
|
||||
private readonly pendingEnrollments = new Map<
|
||||
string,
|
||||
{ label: string; secretBase32: string; createdAt: number }
|
||||
>();
|
||||
private readonly pendingWebAuthn = new Map<string, PendingWebAuthnChallenge>();
|
||||
private readonly sessionRevokedListeners = new Set<(idHashes: string[]) => void>();
|
||||
private readonly getSecurity: () => SecuritySettings;
|
||||
private readonly getRuntimeLimits?: () => RuntimeLimits;
|
||||
private onSecurityEvent?: AuthServiceOptions['onSecurityEvent'];
|
||||
private readonly dbKey: Buffer;
|
||||
private readonly sessionReaperTimer: NodeJS.Timeout;
|
||||
private argon2Active = 0;
|
||||
private readonly argon2Queue: Array<{ resolve: () => void; reject: (err: Error) => void }> = [];
|
||||
private dummyArgon2Hash: string | null = null;
|
||||
private recoveryStore?: EmergencyRecoveryService;
|
||||
private vaultService?: VaultService;
|
||||
|
||||
|
|
@ -204,8 +328,169 @@ export class AuthService {
|
|||
options: AuthServiceOptions = {},
|
||||
) {
|
||||
this.getSecurity = options.getSecuritySettings ?? (() => DEFAULT_SECURITY);
|
||||
this.getRuntimeLimits = options.getRuntimeLimits;
|
||||
this.onSecurityEvent = options.onSecurityEvent;
|
||||
this.recoveryStore = options.recoveryStore;
|
||||
this.vaultService = options.vaultService;
|
||||
|
||||
const inferredDir =
|
||||
options.dataDir ??
|
||||
(db.name && db.name !== ':memory:' ? path.dirname(db.name) : undefined);
|
||||
this.dbKey = loadOrCreateDbKey({ dataDir: inferredDir, envDbKey: options.envDbKey });
|
||||
this.migratePlaintextTotpsIfNeeded();
|
||||
|
||||
this.sessionReaperTimer = setInterval(() => {
|
||||
this.reapExpiredSessions();
|
||||
}, SESSION_REAPER_MS);
|
||||
this.sessionReaperTimer.unref();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
clearInterval(this.sessionReaperTimer);
|
||||
while (this.argon2Queue.length > 0) {
|
||||
const waiter = this.argon2Queue.shift()!;
|
||||
waiter.reject(new Error('AuthService shutting down'));
|
||||
}
|
||||
}
|
||||
|
||||
setSecurityEventListener(listener: AuthServiceOptions['onSecurityEvent']): void {
|
||||
this.onSecurityEvent = listener;
|
||||
}
|
||||
|
||||
emitSecurityEvent(type: string, ip?: string, details?: Record<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(
|
||||
|
|
@ -257,9 +542,11 @@ export class AuthService {
|
|||
}
|
||||
|
||||
async beginBootstrap(username = 'admin'): Promise<{
|
||||
bootstrapToken: string;
|
||||
secretBase32: string;
|
||||
otpauthUri: string;
|
||||
qrSvg: string;
|
||||
qrDataUri: string;
|
||||
}> {
|
||||
if (this.isBootstrapped()) {
|
||||
throw new Error('Admin account is already configured');
|
||||
|
|
@ -272,17 +559,24 @@ export class AuthService {
|
|||
const secret = new OTPAuth.Secret({ size: 20 });
|
||||
this.pendingBootstrap = {
|
||||
secretBase32: secret.base32,
|
||||
token: crypto.randomBytes(24).toString('base64url'),
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
const totp = buildTotp(this.pendingBootstrap.secretBase32, username);
|
||||
const cleanUser = username.trim().slice(0, 64) || 'admin';
|
||||
const totp = buildTotp(this.pendingBootstrap.secretBase32, cleanUser);
|
||||
const otpauthUri = totp.toString();
|
||||
const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 });
|
||||
const [qrSvg, qrDataUri] = await Promise.all([
|
||||
QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }),
|
||||
QRCode.toDataURL(otpauthUri, { margin: 1, width: 220 }),
|
||||
]);
|
||||
return {
|
||||
bootstrapToken: this.pendingBootstrap.token,
|
||||
secretBase32: this.pendingBootstrap.secretBase32,
|
||||
otpauthUri,
|
||||
qrSvg,
|
||||
qrDataUri,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -291,6 +585,7 @@ export class AuthService {
|
|||
password: string;
|
||||
totpCode: string;
|
||||
secretBase32?: string;
|
||||
bootstrapToken?: string;
|
||||
ip: string;
|
||||
userAgent: string;
|
||||
initialSafeMode?: boolean;
|
||||
|
|
@ -311,11 +606,30 @@ export class AuthService {
|
|||
throw new Error('Password must be at least 10 characters');
|
||||
}
|
||||
|
||||
const secretBase32 = params.secretBase32 ?? this.pendingBootstrap?.secretBase32;
|
||||
if (!secretBase32) {
|
||||
if (
|
||||
!this.pendingBootstrap ||
|
||||
Date.now() - this.pendingBootstrap.createdAt > BOOTSTRAP_TTL_MS
|
||||
) {
|
||||
this.pendingBootstrap = null;
|
||||
throw new Error('Bootstrap enrollment session expired; reload setup');
|
||||
}
|
||||
|
||||
if (
|
||||
params.bootstrapToken !== undefined &&
|
||||
!timingSafeStringEqual(params.bootstrapToken, this.pendingBootstrap.token)
|
||||
) {
|
||||
throw new Error('Invalid bootstrap session token; reload setup');
|
||||
}
|
||||
|
||||
if (
|
||||
params.secretBase32 !== undefined &&
|
||||
!timingSafeStringEqual(params.secretBase32.trim(), this.pendingBootstrap.secretBase32)
|
||||
) {
|
||||
throw new Error('Bootstrap secret mismatch; reload setup');
|
||||
}
|
||||
|
||||
const secretBase32 = this.pendingBootstrap.secretBase32;
|
||||
|
||||
const nowMs = Date.now();
|
||||
const totp = buildTotp(secretBase32, username);
|
||||
const delta = totp.validate({
|
||||
|
|
@ -328,12 +642,8 @@ export class AuthService {
|
|||
}
|
||||
|
||||
const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta;
|
||||
const passwordHash = await argon2.hash(params.password, {
|
||||
type: argon2.argon2id,
|
||||
memoryCost: 65536,
|
||||
timeCost: 3,
|
||||
parallelism: 1,
|
||||
});
|
||||
const passwordHash = await this.hashPassword(params.password);
|
||||
const secretEnc = encryptTotpSecret(this.dbKey, 'totp-primary', secretBase32);
|
||||
|
||||
const recoveryCodes: string[] = [];
|
||||
for (let i = 0; i < 8; i++) {
|
||||
|
|
@ -344,9 +654,9 @@ export class AuthService {
|
|||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO admin_users (id, username, password_hash, totp_secret, last_login_totp_step, last_stepup_totp_step, created_at, updated_at)
|
||||
VALUES (1, ?, ?, ?, ?, NULL, ?, ?)`,
|
||||
VALUES (1, ?, '', '', ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(username, passwordHash, secretBase32, matchedStep, nowMs, nowMs);
|
||||
.run(username, matchedStep, matchedStep, nowMs, nowMs);
|
||||
|
||||
this.db
|
||||
.prepare(
|
||||
|
|
@ -356,10 +666,10 @@ export class AuthService {
|
|||
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at)
|
||||
VALUES (?, ?, ?, ?, NULL, ?)`,
|
||||
`INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at)
|
||||
VALUES (?, ?, '', ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run('totp-primary', 'Primary Authenticator', secretBase32, matchedStep, nowMs);
|
||||
.run('totp-primary', 'Primary Authenticator', secretEnc, matchedStep, matchedStep, matchedStep, nowMs);
|
||||
|
||||
const insertRec = this.db.prepare(
|
||||
'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)',
|
||||
|
|
@ -372,12 +682,6 @@ export class AuthService {
|
|||
this.pendingBootstrap = null;
|
||||
|
||||
this.syncRecovery({
|
||||
passwordPlaintextUpdate: {
|
||||
id: 'pw-primary',
|
||||
label: 'Primary Password',
|
||||
password: params.password,
|
||||
createdAt: nowMs,
|
||||
},
|
||||
newRecoveryCodes: recoveryCodes,
|
||||
snapshotReason: 'bootstrap',
|
||||
});
|
||||
|
|
@ -403,28 +707,35 @@ export class AuthService {
|
|||
const admin = this.db
|
||||
.prepare('SELECT * FROM admin_users WHERE id = 1')
|
||||
.get() as AdminRow | undefined;
|
||||
if (!admin) return null;
|
||||
const suppliedPasswords = (
|
||||
params.passwords ?? (params.password !== undefined ? [params.password] : [])
|
||||
)
|
||||
.filter((p) => p.length > 0)
|
||||
.slice(0, 16);
|
||||
const cleanUser = params.username?.trim() ?? '';
|
||||
|
||||
if (params.username && params.username.trim() !== admin.username) {
|
||||
if (
|
||||
!admin ||
|
||||
!cleanUser ||
|
||||
cleanUser.length > 64 ||
|
||||
suppliedPasswords.length === 0 ||
|
||||
!timingSafeStringEqual(cleanUser, admin.username)
|
||||
) {
|
||||
await this.verifyDummyPassword(suppliedPasswords[0] ?? 'dummy');
|
||||
return null;
|
||||
}
|
||||
|
||||
const sec = this.getSecurity();
|
||||
const suppliedPasswords = (
|
||||
params.passwords ?? (params.password !== undefined ? [params.password] : [])
|
||||
).filter((p) => p.length > 0);
|
||||
if (suppliedPasswords.length === 0) return null;
|
||||
|
||||
const pwOk = await this.verifyPasswords(suppliedPasswords, sec.passwordMode);
|
||||
if (!pwOk) return null;
|
||||
|
||||
const totpRows = this.listTotpRows();
|
||||
if (sec.requireTotpOnLogin && totpRows.length > 0) {
|
||||
if (sec.requireTotpOnLogin) {
|
||||
const suppliedCodes = (
|
||||
params.codes ?? (params.code !== undefined ? [params.code] : [])
|
||||
)
|
||||
.map((c) => c.trim())
|
||||
.filter((c) => c.length > 0);
|
||||
.filter((c) => c.length > 0)
|
||||
.slice(0, 16);
|
||||
|
||||
if (suppliedCodes.length === 0) return null;
|
||||
|
||||
|
|
@ -433,6 +744,7 @@ export class AuthService {
|
|||
sec.totpMode,
|
||||
'login',
|
||||
admin.username,
|
||||
params.ip,
|
||||
);
|
||||
if (!mfaOk) return null;
|
||||
}
|
||||
|
|
@ -446,7 +758,11 @@ export class AuthService {
|
|||
|
||||
getSessionByToken(sessionToken: string | undefined): AuthSession | null {
|
||||
if (!sessionToken || sessionToken.length < 16) return null;
|
||||
const idHash = sha256Hex(sessionToken);
|
||||
return this.getSessionByHash(sha256Hex(sessionToken));
|
||||
}
|
||||
|
||||
getSessionByHash(idHash: string | undefined): AuthSession | null {
|
||||
if (!idHash || idHash.length < 16) return null;
|
||||
const row = this.db
|
||||
.prepare('SELECT * FROM sessions WHERE id_hash = ?')
|
||||
.get(idHash) as SessionRow | undefined;
|
||||
|
|
@ -455,10 +771,24 @@ export class AuthService {
|
|||
const now = Date.now();
|
||||
if (row.expires_at <= now) {
|
||||
this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash);
|
||||
this.notifySessionsRevoked([idHash]);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (now - row.last_seen_at > 60_000) {
|
||||
const sec = this.getSecurity();
|
||||
const idleMs = (sec.sessionIdleTimeoutMin ?? 60) * 60 * 1000;
|
||||
if (idleMs > 0 && now - row.last_seen_at > idleMs) {
|
||||
this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash);
|
||||
this.notifySessionsRevoked([idHash]);
|
||||
this.emitSecurityEvent('auth.session_idle_expired', row.ip, {
|
||||
idPrefix: idHash.slice(0, 12),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const touchIntervalMs =
|
||||
idleMs > 0 ? Math.min(60_000, Math.max(1000, Math.floor(idleMs / 4))) : 60_000;
|
||||
if (now - row.last_seen_at > touchIntervalMs) {
|
||||
this.db
|
||||
.prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?')
|
||||
.run(now, idHash);
|
||||
|
|
@ -526,20 +856,17 @@ export class AuthService {
|
|||
}
|
||||
|
||||
if (sec.stepUpMethod === 'totp' || sec.stepUpMethod === 'both') {
|
||||
const totpRows = this.listTotpRows();
|
||||
if (totpRows.length > 0) {
|
||||
if (suppliedCodes.length === 0) {
|
||||
return { ok: false, reason: 'invalid_totp' };
|
||||
}
|
||||
const totpResult = this.verifyTotpRows(
|
||||
suppliedCodes,
|
||||
sec.totpMode,
|
||||
'stepup',
|
||||
admin.username,
|
||||
);
|
||||
if (!totpResult.ok) {
|
||||
return { ok: false, reason: totpResult.reason };
|
||||
}
|
||||
if (suppliedCodes.length === 0) {
|
||||
return { ok: false, reason: 'invalid_totp' };
|
||||
}
|
||||
const totpResult = this.verifyTotpRows(
|
||||
suppliedCodes,
|
||||
sec.totpMode,
|
||||
'stepup',
|
||||
admin.username,
|
||||
);
|
||||
if (!totpResult.ok) {
|
||||
return { ok: false, reason: totpResult.reason };
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -684,7 +1011,7 @@ export class AuthService {
|
|||
})),
|
||||
authenticatorSelection: {
|
||||
residentKey: 'preferred',
|
||||
userVerification: 'preferred',
|
||||
userVerification: 'required',
|
||||
},
|
||||
});
|
||||
|
||||
|
|
@ -715,7 +1042,7 @@ export class AuthService {
|
|||
expectedChallenge: pending.challenge,
|
||||
expectedOrigin: pending.expectedOrigin,
|
||||
expectedRPID: pending.rpID,
|
||||
requireUserVerification: false,
|
||||
requireUserVerification: true,
|
||||
});
|
||||
|
||||
if (!verification.verified || !verification.registrationInfo) {
|
||||
|
|
@ -780,7 +1107,7 @@ export class AuthService {
|
|||
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
|
||||
: undefined,
|
||||
})),
|
||||
userVerification: 'preferred',
|
||||
userVerification: 'required',
|
||||
});
|
||||
|
||||
const challengeId = crypto.randomBytes(16).toString('hex');
|
||||
|
|
@ -806,6 +1133,14 @@ export class AuthService {
|
|||
if (!this.isBootstrapped()) return null;
|
||||
const pending = this.consumeWebAuthnChallenge(params.challengeId, 'login');
|
||||
if (!pending) return null;
|
||||
if (
|
||||
!params.response ||
|
||||
typeof params.response.id !== 'string' ||
|
||||
params.response.id.length === 0 ||
|
||||
params.response.id.length > 512
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = this.db
|
||||
.prepare('SELECT * FROM webauthn_credentials WHERE id = ?')
|
||||
|
|
@ -826,7 +1161,7 @@ export class AuthService {
|
|||
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
|
||||
: undefined,
|
||||
},
|
||||
requireUserVerification: false,
|
||||
requireUserVerification: true,
|
||||
});
|
||||
if (!verification.verified) return null;
|
||||
|
||||
|
|
@ -861,11 +1196,22 @@ export class AuthService {
|
|||
if (session.safe_mode === 1) {
|
||||
return { ok: false, reason: 'safe_mode_active' };
|
||||
}
|
||||
if (sec.stepUpMethod !== 'passkey') {
|
||||
return { ok: false, reason: 'passkey_stepup_not_enabled' };
|
||||
}
|
||||
|
||||
const pending = this.consumeWebAuthnChallenge(params.challengeId, 'stepup');
|
||||
if (!pending || pending.sessionIdHash !== params.idHash) {
|
||||
return { ok: false, reason: 'invalid_challenge' };
|
||||
}
|
||||
if (
|
||||
!params.response ||
|
||||
typeof params.response.id !== 'string' ||
|
||||
params.response.id.length === 0 ||
|
||||
params.response.id.length > 512
|
||||
) {
|
||||
return { ok: false, reason: 'invalid_assertion' };
|
||||
}
|
||||
|
||||
const row = this.db
|
||||
.prepare('SELECT * FROM webauthn_credentials WHERE id = ?')
|
||||
|
|
@ -886,7 +1232,7 @@ export class AuthService {
|
|||
? (JSON.parse(row.transports) as AuthenticatorTransportFuture[])
|
||||
: undefined,
|
||||
},
|
||||
requireUserVerification: false,
|
||||
requireUserVerification: true,
|
||||
});
|
||||
if (!verification.verified) {
|
||||
return { ok: false, reason: 'invalid_assertion' };
|
||||
|
|
@ -926,12 +1272,7 @@ export class AuthService {
|
|||
|
||||
const id = `pw-${crypto.randomBytes(4).toString('hex')}`;
|
||||
const createdAt = Date.now();
|
||||
const hash = await argon2.hash(password, {
|
||||
type: argon2.argon2id,
|
||||
memoryCost: 65536,
|
||||
timeCost: 3,
|
||||
parallelism: 1,
|
||||
});
|
||||
const hash = await this.hashPassword(password);
|
||||
|
||||
this.db
|
||||
.prepare(
|
||||
|
|
@ -940,12 +1281,6 @@ export class AuthService {
|
|||
.run(id, cleanLabel, hash, createdAt);
|
||||
|
||||
this.syncRecovery({
|
||||
passwordPlaintextUpdate: {
|
||||
id,
|
||||
label: cleanLabel,
|
||||
password,
|
||||
createdAt,
|
||||
},
|
||||
snapshotReason: 'password-added',
|
||||
});
|
||||
|
||||
|
|
@ -972,6 +1307,7 @@ export class AuthService {
|
|||
secretBase32: string;
|
||||
otpauthUri: string;
|
||||
qrSvg: string;
|
||||
qrDataUri: string;
|
||||
}> {
|
||||
const cleanLabel = label.trim();
|
||||
if (cleanLabel.length < 1 || cleanLabel.length > 64) {
|
||||
|
|
@ -995,13 +1331,17 @@ export class AuthService {
|
|||
const username = this.getAdminUsername() ?? 'admin';
|
||||
const totp = buildTotp(secret.base32, `${username} (${cleanLabel})`);
|
||||
const otpauthUri = totp.toString();
|
||||
const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 });
|
||||
const [qrSvg, qrDataUri] = await Promise.all([
|
||||
QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }),
|
||||
QRCode.toDataURL(otpauthUri, { margin: 1, width: 220 }),
|
||||
]);
|
||||
return {
|
||||
enrollmentId,
|
||||
label: cleanLabel,
|
||||
secretBase32: secret.base32,
|
||||
otpauthUri,
|
||||
qrSvg,
|
||||
qrDataUri,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -1029,12 +1369,13 @@ export class AuthService {
|
|||
|
||||
const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta;
|
||||
const id = `totp-${crypto.randomBytes(4).toString('hex')}`;
|
||||
const secretEnc = encryptTotpSecret(this.dbKey, id, pending.secretBase32);
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
`INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at)
|
||||
VALUES (?, ?, '', ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(id, pending.label, pending.secretBase32, matchedStep, matchedStep, nowMs);
|
||||
.run(id, pending.label, secretEnc, matchedStep, matchedStep, matchedStep, nowMs);
|
||||
|
||||
this.pendingEnrollments.delete(enrollmentId);
|
||||
this.syncRecovery({ snapshotReason: 'totp-added' });
|
||||
|
|
@ -1088,12 +1429,6 @@ export class AuthService {
|
|||
|
||||
syncRecovery(
|
||||
overrides: {
|
||||
passwordPlaintextUpdate?: {
|
||||
id: string;
|
||||
label: string;
|
||||
password: string;
|
||||
createdAt?: number;
|
||||
};
|
||||
removedPasswordId?: string;
|
||||
newRecoveryCodes?: string[];
|
||||
snapshotReason?: string;
|
||||
|
|
@ -1108,16 +1443,19 @@ export class AuthService {
|
|||
.prepare('SELECT id, label, created_at AS createdAt FROM admin_passwords ORDER BY created_at ASC')
|
||||
.all() as Array<{ id: string; label: string; createdAt: number }>;
|
||||
const totpRows = this.listTotpRows();
|
||||
const totps: SavedTotpEntry[] = totpRows.map((t) => ({
|
||||
id: t.id,
|
||||
label: t.label,
|
||||
secretBase32: t.secret_base32,
|
||||
otpauthUri: buildTotp(
|
||||
t.secret_base32,
|
||||
username ? `${username} (${t.label})` : t.label,
|
||||
).toString(),
|
||||
createdAt: new Date(t.created_at).toISOString(),
|
||||
}));
|
||||
const totps: SavedTotpEntry[] = totpRows.map((t) => {
|
||||
const secretBase32 = this.getTotpSecret(t);
|
||||
return {
|
||||
id: t.id,
|
||||
label: t.label,
|
||||
secretBase32,
|
||||
otpauthUri: buildTotp(
|
||||
secretBase32,
|
||||
username ? `${username} (${t.label})` : t.label,
|
||||
).toString(),
|
||||
createdAt: new Date(t.created_at).toISOString(),
|
||||
};
|
||||
});
|
||||
|
||||
this.recoveryStore.syncState({
|
||||
enabled: sec.enableEmergencySecretsBackup,
|
||||
|
|
@ -1150,24 +1488,43 @@ export class AuthService {
|
|||
}
|
||||
|
||||
revokeSessionByHash(idHash: string): void {
|
||||
this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash);
|
||||
const res = this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash);
|
||||
if (res.changes > 0) {
|
||||
this.notifySessionsRevoked([idHash]);
|
||||
}
|
||||
}
|
||||
|
||||
revokeSessionByPrefix(prefix: string): number {
|
||||
if (!/^[0-9a-f]{8,64}$/i.test(prefix)) return 0;
|
||||
const rows = this.db
|
||||
.prepare('SELECT id_hash FROM sessions WHERE id_hash LIKE ?')
|
||||
.all(`${prefix}%`) as Array<{ id_hash: string }>;
|
||||
if (rows.length === 0) return 0;
|
||||
const result = this.db
|
||||
.prepare('DELETE FROM sessions WHERE id_hash LIKE ?')
|
||||
.run(`${prefix}%`);
|
||||
if (result.changes > 0) {
|
||||
this.notifySessionsRevoked(rows.map((r) => r.id_hash));
|
||||
}
|
||||
return result.changes;
|
||||
}
|
||||
|
||||
revokeAllSessions(exceptIdHash?: string): number {
|
||||
if (exceptIdHash) {
|
||||
return this.db
|
||||
.prepare('DELETE FROM sessions WHERE id_hash != ?')
|
||||
.run(exceptIdHash).changes;
|
||||
const rows = (
|
||||
exceptIdHash
|
||||
? this.db
|
||||
.prepare('SELECT id_hash FROM sessions WHERE id_hash != ?')
|
||||
.all(exceptIdHash)
|
||||
: this.db.prepare('SELECT id_hash FROM sessions').all()
|
||||
) as Array<{ id_hash: string }>;
|
||||
if (rows.length === 0) return 0;
|
||||
const changes = exceptIdHash
|
||||
? this.db.prepare('DELETE FROM sessions WHERE id_hash != ?').run(exceptIdHash).changes
|
||||
: this.db.prepare('DELETE FROM sessions').run().changes;
|
||||
if (changes > 0) {
|
||||
this.notifySessionsRevoked(rows.map((r) => r.id_hash));
|
||||
}
|
||||
return this.db.prepare('DELETE FROM sessions').run().changes;
|
||||
return changes;
|
||||
}
|
||||
|
||||
private listTotpRows(): TotpRow[] {
|
||||
|
|
@ -1188,7 +1545,7 @@ export class AuthService {
|
|||
if (mode === 'any') {
|
||||
for (const row of rows) {
|
||||
for (const candidate of suppliedPasswords) {
|
||||
if (await argon2.verify(row.password_hash, candidate)) {
|
||||
if (await this.verifyPasswordHash(row.password_hash, candidate)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -1200,7 +1557,7 @@ export class AuthService {
|
|||
for (const row of rows) {
|
||||
let rowMatched = false;
|
||||
for (const candidate of suppliedPasswords) {
|
||||
if (await argon2.verify(row.password_hash, candidate)) {
|
||||
if (await this.verifyPasswordHash(row.password_hash, candidate)) {
|
||||
rowMatched = true;
|
||||
break;
|
||||
}
|
||||
|
|
@ -1215,8 +1572,9 @@ export class AuthService {
|
|||
mode: 'any' | 'all',
|
||||
purpose: 'login' | 'stepup',
|
||||
username: string,
|
||||
ip?: string,
|
||||
): boolean {
|
||||
const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username);
|
||||
const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username, ip);
|
||||
if (totpRes.ok) return true;
|
||||
|
||||
// In 'any' mode, a single-use recovery code may replace TOTP
|
||||
|
|
@ -1230,33 +1588,48 @@ export class AuthService {
|
|||
'UPDATE recovery_codes SET used_at = ? WHERE code_hash = ? AND used_at IS NULL',
|
||||
)
|
||||
.run(Date.now(), sha256Hex(normalized));
|
||||
if (updated.changes === 1) return true;
|
||||
if (updated.changes === 1) {
|
||||
this.emitSecurityEvent('auth.recovery_code_used', ip, { username });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private getRowLastUsedStep(row: TotpRow): number | null {
|
||||
if (row.last_used_step !== null && row.last_used_step !== undefined) {
|
||||
return row.last_used_step;
|
||||
}
|
||||
const candidates = [row.last_login_step, row.last_stepup_step].filter(
|
||||
(n): n is number => typeof n === 'number',
|
||||
);
|
||||
return candidates.length > 0 ? Math.max(...candidates) : null;
|
||||
}
|
||||
|
||||
private verifyTotpRows(
|
||||
suppliedCodes: string[],
|
||||
mode: 'any' | 'all',
|
||||
purpose: 'login' | 'stepup',
|
||||
username: string,
|
||||
ip?: string,
|
||||
): { ok: true } | { ok: false; reason: string } {
|
||||
const rows = this.listTotpRows();
|
||||
if (rows.length === 0) return { ok: true };
|
||||
if (rows.length === 0) {
|
||||
return { ok: false, reason: 'totp_not_configured' };
|
||||
}
|
||||
|
||||
const numericCodes = suppliedCodes.filter((c) => /^\d{6}$/.test(c));
|
||||
if (numericCodes.length === 0) return { ok: false, reason: 'invalid_totp' };
|
||||
|
||||
const nowMs = Date.now();
|
||||
const stepCol = purpose === 'login' ? 'last_login_step' : 'last_stepup_step';
|
||||
|
||||
if (mode === 'any') {
|
||||
let sawReplay = false;
|
||||
for (const row of rows) {
|
||||
const totp = buildTotp(row.secret_base32, username);
|
||||
const lastStep =
|
||||
purpose === 'login' ? row.last_login_step : row.last_stepup_step;
|
||||
const secret = this.getTotpSecret(row);
|
||||
const totp = buildTotp(secret, username);
|
||||
const lastStep = this.getRowLastUsedStep(row);
|
||||
for (const code of numericCodes) {
|
||||
const delta = totp.validate({ token: code, window: 1, timestamp: nowMs });
|
||||
if (delta === null) continue;
|
||||
|
|
@ -1266,20 +1639,25 @@ export class AuthService {
|
|||
continue;
|
||||
}
|
||||
this.db
|
||||
.prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`)
|
||||
.run(matchedStep, row.id);
|
||||
.prepare(
|
||||
'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?',
|
||||
)
|
||||
.run(matchedStep, matchedStep, matchedStep, row.id);
|
||||
return { ok: true };
|
||||
}
|
||||
}
|
||||
if (sawReplay) {
|
||||
this.emitSecurityEvent('auth.totp_replay', ip, { purpose });
|
||||
}
|
||||
return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' };
|
||||
}
|
||||
|
||||
// 'all': every configured TOTP authenticator must match a supplied valid non-replayed code
|
||||
const matchedUpdates: Array<{ id: string; step: number }> = [];
|
||||
for (const row of rows) {
|
||||
const totp = buildTotp(row.secret_base32, username);
|
||||
const lastStep =
|
||||
purpose === 'login' ? row.last_login_step : row.last_stepup_step;
|
||||
const secret = this.getTotpSecret(row);
|
||||
const totp = buildTotp(secret, username);
|
||||
const lastStep = this.getRowLastUsedStep(row);
|
||||
let rowStep: number | null = null;
|
||||
let sawReplay = false;
|
||||
|
||||
|
|
@ -1296,15 +1674,20 @@ export class AuthService {
|
|||
}
|
||||
|
||||
if (rowStep === null) {
|
||||
if (sawReplay) {
|
||||
this.emitSecurityEvent('auth.totp_replay', ip, { purpose });
|
||||
}
|
||||
return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' };
|
||||
}
|
||||
matchedUpdates.push({ id: row.id, step: rowStep });
|
||||
}
|
||||
|
||||
const tx = this.db.transaction(() => {
|
||||
const stmt = this.db.prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`);
|
||||
const stmt = this.db.prepare(
|
||||
'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?',
|
||||
);
|
||||
for (const upd of matchedUpdates) {
|
||||
stmt.run(upd.step, upd.id);
|
||||
stmt.run(upd.step, upd.step, upd.step, upd.id);
|
||||
}
|
||||
});
|
||||
tx();
|
||||
|
|
@ -1321,8 +1704,9 @@ export class AuthService {
|
|||
const idHash = sha256Hex(sessionToken);
|
||||
const csrfTokenHash = sha256Hex(csrfToken);
|
||||
const now = Date.now();
|
||||
const expiresAt = now + SESSION_TTL_MS;
|
||||
const sec = this.getSecurity();
|
||||
const ttlMs = (sec.sessionTtlHours ?? 168) * 60 * 60 * 1000;
|
||||
const expiresAt = now + ttlMs;
|
||||
|
||||
const shouldElevate =
|
||||
sec.elevateOnLogin && (!safeMode || sec.keepElevationOnSafeMode);
|
||||
|
|
|
|||
275
src/server/security/backup-scheduler.ts
Normal file
275
src/server/security/backup-scheduler.ts
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -21,6 +21,13 @@ export const BackupEnvelopeSchema = z.object({
|
|||
alg: z.literal('aes-256-gcm'),
|
||||
kdf: z.enum(['raw-master-key', 'scrypt']),
|
||||
salt: z.string().optional(),
|
||||
kdfParams: z
|
||||
.object({
|
||||
N: z.number().int().min(16384).max(65536),
|
||||
r: z.number().int().min(4).max(16),
|
||||
p: z.number().int().min(1).max(4),
|
||||
})
|
||||
.optional(),
|
||||
iv: z.string().min(1),
|
||||
tag: z.string().min(1),
|
||||
ciphertext: z.string().min(1),
|
||||
|
|
@ -76,9 +83,62 @@ export interface BackupVerificationSummary {
|
|||
overlayCount: number;
|
||||
}
|
||||
|
||||
export class BackupBusyError extends Error {
|
||||
readonly code = 'BACKUP_KDF_BUSY';
|
||||
constructor(message = 'Backup encryption worker queue is busy; try again shortly') {
|
||||
super(message);
|
||||
this.name = 'BackupBusyError';
|
||||
}
|
||||
}
|
||||
|
||||
const SLUG_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
|
||||
const MAX_GUNZIP_BYTES = 32 * 1024 * 1024;
|
||||
const DEFAULT_MAX_GUNZIP_BYTES = 32 * 1024 * 1024;
|
||||
const SCRYPT_PARAMS = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 } as const;
|
||||
const BACKUP_AAD = Buffer.from('gcoord-backup-v1', 'utf8');
|
||||
const MIN_BACKUP_PASSPHRASE_LEN = 12;
|
||||
const MAX_SCRYPT_QUEUE = 8;
|
||||
|
||||
let scryptActive = 0;
|
||||
const scryptWaiters: Array<() => void> = [];
|
||||
|
||||
async function runScryptAsync(
|
||||
password: string,
|
||||
salt: Buffer,
|
||||
params: { N: number; r: number; p: number; maxmem: number },
|
||||
concurrency = 1,
|
||||
): Promise<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(
|
||||
relPath: string,
|
||||
|
|
@ -147,18 +207,23 @@ function collectConfigFilesFromDisk(configDir: string): Record<string, string> {
|
|||
|
||||
for (const name of ['settings.json', 'alerts.json', 'snippets.json']) {
|
||||
const abs = path.join(configDir, name);
|
||||
if (fs.existsSync(abs)) {
|
||||
if (isRegularNonSymlink(abs)) {
|
||||
out[name] = fs.readFileSync(abs, 'utf8');
|
||||
}
|
||||
}
|
||||
for (const folder of ['servers', 'systems', 'workflows']) {
|
||||
const dir = path.join(configDir, folder);
|
||||
if (!fs.existsSync(dir)) continue;
|
||||
try {
|
||||
const dirStat = fs.lstatSync(dir);
|
||||
if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) continue;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const entry of fs.readdirSync(dir).sort()) {
|
||||
if (!entry.endsWith('.json') || entry.includes('.tmp')) continue;
|
||||
const rel = `${folder}/${entry}`;
|
||||
const abs = path.join(dir, entry);
|
||||
if (fs.statSync(abs).isFile()) {
|
||||
if (isRegularNonSymlink(abs)) {
|
||||
out[rel] = fs.readFileSync(abs, 'utf8');
|
||||
}
|
||||
}
|
||||
|
|
@ -166,6 +231,17 @@ function collectConfigFilesFromDisk(configDir: string): Record<string, string> {
|
|||
return out;
|
||||
}
|
||||
|
||||
function validateEncryptPassphrase(passphrase?: string): string | undefined {
|
||||
const pass = passphrase?.trim();
|
||||
if (!pass || pass.length === 0) return undefined;
|
||||
if (pass.length < MIN_BACKUP_PASSPHRASE_LEN) {
|
||||
throw new Error(
|
||||
`Backup passphrase must be at least ${MIN_BACKUP_PASSPHRASE_LEN} characters`,
|
||||
);
|
||||
}
|
||||
return pass;
|
||||
}
|
||||
|
||||
function deriveEnvelopeKeyForEncrypt(opts: {
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
|
|
@ -173,12 +249,18 @@ function deriveEnvelopeKeyForEncrypt(opts: {
|
|||
key: Buffer;
|
||||
kdf: 'raw-master-key' | 'scrypt';
|
||||
saltB64?: string;
|
||||
kdfParams?: { N: number; r: number; p: number };
|
||||
} {
|
||||
const pass = opts.passphrase?.trim();
|
||||
if (pass && pass.length > 0) {
|
||||
const pass = validateEncryptPassphrase(opts.passphrase);
|
||||
if (pass) {
|
||||
const salt = crypto.randomBytes(16);
|
||||
const key = crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS);
|
||||
return { key, kdf: 'scrypt', saltB64: salt.toString('base64') };
|
||||
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');
|
||||
|
|
@ -186,40 +268,92 @@ function deriveEnvelopeKeyForEncrypt(opts: {
|
|||
return { key: parseMasterKey(opts.masterKey), kdf: 'raw-master-key' };
|
||||
}
|
||||
|
||||
async function deriveEnvelopeKeyForEncryptAsync(opts: {
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
scryptConcurrency?: number;
|
||||
}): Promise<{
|
||||
key: Buffer;
|
||||
kdf: 'raw-master-key' | 'scrypt';
|
||||
saltB64?: string;
|
||||
kdfParams?: { N: number; r: number; p: number };
|
||||
}> {
|
||||
const pass = validateEncryptPassphrase(opts.passphrase);
|
||||
if (pass) {
|
||||
const salt = crypto.randomBytes(16);
|
||||
const key = await runScryptAsync(pass, salt, SCRYPT_PARAMS, opts.scryptConcurrency);
|
||||
return {
|
||||
key,
|
||||
kdf: 'scrypt',
|
||||
saltB64: salt.toString('base64'),
|
||||
kdfParams: { N: SCRYPT_PARAMS.N, r: SCRYPT_PARAMS.r, p: SCRYPT_PARAMS.p },
|
||||
};
|
||||
}
|
||||
if (!opts.masterKey || !opts.masterKey.trim()) {
|
||||
throw new Error('Either Vault master key or backup passphrase is required');
|
||||
}
|
||||
return { key: parseMasterKey(opts.masterKey), kdf: 'raw-master-key' };
|
||||
}
|
||||
|
||||
function getDecryptScryptInputs(
|
||||
envelope: BackupEnvelope,
|
||||
opts: { masterKey?: string; passphrase?: string },
|
||||
): { pass: string; salt: Buffer; params: { N: number; r: number; p: number; maxmem: number } } {
|
||||
const pass = opts.passphrase?.trim();
|
||||
if (!pass) {
|
||||
throw new Error('This backup is encrypted with a passphrase; provide backup passphrase');
|
||||
}
|
||||
if (!envelope.salt) {
|
||||
throw new Error('Backup envelope is missing scrypt salt');
|
||||
}
|
||||
const salt = Buffer.from(envelope.salt, 'base64');
|
||||
if (salt.length < 8) {
|
||||
throw new Error('Backup envelope contains an invalid scrypt salt');
|
||||
}
|
||||
const p = envelope.kdfParams;
|
||||
const params = p
|
||||
? { N: p.N, r: p.r, p: p.p, maxmem: 128 * 1024 * 1024 }
|
||||
: SCRYPT_PARAMS;
|
||||
return { pass, salt, params };
|
||||
}
|
||||
|
||||
function deriveEnvelopeKeyForDecrypt(
|
||||
envelope: BackupEnvelope,
|
||||
opts: { masterKey?: string; passphrase?: string },
|
||||
): Buffer {
|
||||
if (envelope.kdf === 'scrypt') {
|
||||
const pass = opts.passphrase?.trim();
|
||||
if (!pass) {
|
||||
throw new Error('This backup is encrypted with a passphrase; provide backup passphrase');
|
||||
}
|
||||
if (!envelope.salt) {
|
||||
throw new Error('Backup envelope is missing scrypt salt');
|
||||
}
|
||||
const salt = Buffer.from(envelope.salt, 'base64');
|
||||
if (salt.length < 8) {
|
||||
throw new Error('Backup envelope contains an invalid scrypt salt');
|
||||
}
|
||||
return crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS);
|
||||
const { pass, salt, params } = getDecryptScryptInputs(envelope, opts);
|
||||
return crypto.scryptSync(pass, salt, 32, params);
|
||||
}
|
||||
|
||||
if (!opts.masterKey || !opts.masterKey.trim()) {
|
||||
throw new Error('This backup requires the 32-byte Vault master key to decrypt');
|
||||
}
|
||||
return parseMasterKey(opts.masterKey);
|
||||
}
|
||||
|
||||
export function createBackupBundle(opts: {
|
||||
async function deriveEnvelopeKeyForDecryptAsync(
|
||||
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;
|
||||
db?: Database.Database;
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
}): {
|
||||
serialized: string;
|
||||
envelope: BackupEnvelope;
|
||||
summary: BackupVerificationSummary;
|
||||
inner: BackupInnerPayload;
|
||||
vaultVerified: boolean;
|
||||
vaultCredentialCount?: number;
|
||||
overlayCount: number;
|
||||
} {
|
||||
const dataDir = path.resolve(opts.dataDir);
|
||||
const configDir = path.join(dataDir, 'config');
|
||||
|
|
@ -232,7 +366,7 @@ export function createBackupBundle(opts: {
|
|||
overlayCount += validateAndParseConfigEntry(relPath, rawJson).overlayCount;
|
||||
}
|
||||
|
||||
const vaultEnvelopeRaw = fs.existsSync(vaultPath)
|
||||
const vaultEnvelopeRaw = isRegularNonSymlink(vaultPath)
|
||||
? fs.readFileSync(vaultPath, 'utf8')
|
||||
: null;
|
||||
let vaultVerified = false;
|
||||
|
|
@ -249,7 +383,7 @@ export function createBackupBundle(opts: {
|
|||
let localDb: Database.Database | null = null;
|
||||
const db =
|
||||
opts.db ??
|
||||
(fs.existsSync(dbPath) ? (localDb = openDatabase(dbPath)) : null);
|
||||
(isRegularNonSymlink(dbPath) ? (localDb = openDatabase(dbPath)) : null);
|
||||
|
||||
let knownHosts: Array<z.infer<typeof KnownHostRowSchema>> = [];
|
||||
let alertSilences: Array<z.infer<typeof AlertSilenceRowSchema>> = [];
|
||||
|
|
@ -257,7 +391,7 @@ export function createBackupBundle(opts: {
|
|||
if (db) {
|
||||
knownHosts = db
|
||||
.prepare(
|
||||
'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC',
|
||||
'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',
|
||||
)
|
||||
.all() as Array<z.infer<typeof KnownHostRowSchema>>;
|
||||
|
||||
|
|
@ -286,17 +420,29 @@ export function createBackupBundle(opts: {
|
|||
knownHosts,
|
||||
dbMeta: { alertSilences },
|
||||
};
|
||||
return { inner, vaultVerified, vaultCredentialCount, overlayCount };
|
||||
}
|
||||
|
||||
const { key, kdf, saltB64 } = deriveEnvelopeKeyForEncrypt({
|
||||
masterKey: opts.masterKey,
|
||||
passphrase: opts.passphrase,
|
||||
});
|
||||
|
||||
function finalizeBackupEnvelope(
|
||||
prepared: ReturnType<typeof prepareBackupInner>,
|
||||
keyInfo: {
|
||||
key: Buffer;
|
||||
kdf: 'raw-master-key' | 'scrypt';
|
||||
saltB64?: string;
|
||||
kdfParams?: { N: number; r: number; p: number };
|
||||
},
|
||||
): {
|
||||
serialized: string;
|
||||
envelope: BackupEnvelope;
|
||||
summary: BackupVerificationSummary;
|
||||
} {
|
||||
const { inner, vaultVerified, vaultCredentialCount, overlayCount } = prepared;
|
||||
const plaintextJson = Buffer.from(JSON.stringify(inner), 'utf8');
|
||||
const compressed = zlib.gzipSync(plaintextJson, { level: 9 });
|
||||
try {
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', keyInfo.key, iv);
|
||||
cipher.setAAD(BACKUP_AAD);
|
||||
const ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
|
||||
|
|
@ -304,63 +450,115 @@ export function createBackupBundle(opts: {
|
|||
magic: 'GCOORD_BACKUP_V1',
|
||||
version: 1,
|
||||
alg: 'aes-256-gcm',
|
||||
kdf,
|
||||
...(saltB64 ? { salt: saltB64 } : {}),
|
||||
kdf: keyInfo.kdf,
|
||||
...(keyInfo.saltB64 ? { salt: keyInfo.saltB64 } : {}),
|
||||
...(keyInfo.kdfParams ? { kdfParams: keyInfo.kdfParams } : {}),
|
||||
iv: iv.toString('base64'),
|
||||
tag: tag.toString('base64'),
|
||||
ciphertext: ciphertext.toString('base64'),
|
||||
createdAt,
|
||||
createdAt: inner.createdAt,
|
||||
};
|
||||
|
||||
const fileList = Object.keys(configFiles).sort();
|
||||
const fileList = Object.keys(inner.configFiles).sort();
|
||||
return {
|
||||
serialized: `${JSON.stringify(envelope, null, 2)}\n`,
|
||||
envelope,
|
||||
summary: {
|
||||
valid: true,
|
||||
createdAt,
|
||||
kdf,
|
||||
createdAt: inner.createdAt,
|
||||
kdf: keyInfo.kdf,
|
||||
configFileCount: fileList.length,
|
||||
configFiles: fileList,
|
||||
hasVault: vaultEnvelopeRaw !== null,
|
||||
hasVault: inner.vaultEnvelopeRaw !== null,
|
||||
vaultVerified,
|
||||
vaultCredentialCount,
|
||||
knownHostsCount: knownHosts.length,
|
||||
alertSilenceCount: alertSilences.length,
|
||||
knownHostsCount: inner.knownHosts.length,
|
||||
alertSilenceCount: inner.dbMeta.alertSilences.length,
|
||||
overlayCount,
|
||||
},
|
||||
};
|
||||
} finally {
|
||||
key.fill(0);
|
||||
keyInfo.key.fill(0);
|
||||
plaintextJson.fill(0);
|
||||
compressed.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
export function verifyBackupBundle(
|
||||
rawTextOrBuf: string | Buffer,
|
||||
keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string },
|
||||
): { summary: BackupVerificationSummary; inner: BackupInnerPayload } {
|
||||
const rawStr = typeof rawTextOrBuf === 'string' ? rawTextOrBuf : rawTextOrBuf.toString('utf8');
|
||||
const envelope = BackupEnvelopeSchema.parse(JSON.parse(rawStr));
|
||||
export function createBackupBundle(opts: {
|
||||
dataDir: string;
|
||||
db?: Database.Database;
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
}): {
|
||||
serialized: string;
|
||||
envelope: BackupEnvelope;
|
||||
summary: BackupVerificationSummary;
|
||||
} {
|
||||
const keyInfo = deriveEnvelopeKeyForEncrypt({
|
||||
masterKey: opts.masterKey,
|
||||
passphrase: opts.passphrase,
|
||||
});
|
||||
try {
|
||||
const prepared = prepareBackupInner(opts);
|
||||
return finalizeBackupEnvelope(prepared, keyInfo);
|
||||
} catch (err) {
|
||||
keyInfo.key.fill(0);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function createBackupBundleAsync(opts: {
|
||||
dataDir: string;
|
||||
db?: Database.Database;
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
scryptConcurrency?: number;
|
||||
}): Promise<{
|
||||
serialized: string;
|
||||
envelope: BackupEnvelope;
|
||||
summary: BackupVerificationSummary;
|
||||
}> {
|
||||
const keyInfo = await deriveEnvelopeKeyForEncryptAsync(opts);
|
||||
try {
|
||||
const prepared = prepareBackupInner(opts);
|
||||
return finalizeBackupEnvelope(prepared, keyInfo);
|
||||
} catch (err) {
|
||||
keyInfo.key.fill(0);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function decryptVerifiedInner(
|
||||
envelope: BackupEnvelope,
|
||||
key: Buffer,
|
||||
keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string },
|
||||
maxGunzipBytes = DEFAULT_MAX_GUNZIP_BYTES,
|
||||
): { summary: BackupVerificationSummary; inner: BackupInnerPayload } {
|
||||
const iv = Buffer.from(envelope.iv, 'base64');
|
||||
const tag = Buffer.from(envelope.tag, 'base64');
|
||||
const ciphertext = Buffer.from(envelope.ciphertext, 'base64');
|
||||
if (iv.length !== 12 || tag.length !== 16) {
|
||||
throw new Error('Invalid AES-256-GCM parameters inside backup envelope');
|
||||
}
|
||||
|
||||
const key = deriveEnvelopeKeyForDecrypt(envelope, keyOpts);
|
||||
let compressed: Buffer | null = null;
|
||||
let plaintext: Buffer | null = null;
|
||||
let inner: BackupInnerPayload;
|
||||
|
||||
try {
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
||||
decipher.setAuthTag(tag);
|
||||
compressed = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
plaintext = zlib.gunzipSync(compressed, { maxOutputLength: MAX_GUNZIP_BYTES });
|
||||
const decryptOnce = (useAad: boolean): Buffer => {
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
||||
if (useAad) decipher.setAAD(BACKUP_AAD);
|
||||
decipher.setAuthTag(tag);
|
||||
return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
};
|
||||
|
||||
try {
|
||||
compressed = decryptOnce(true);
|
||||
} catch (aadErr) {
|
||||
if (envelope.kdfParams) {
|
||||
throw aadErr;
|
||||
}
|
||||
compressed = decryptOnce(false);
|
||||
}
|
||||
|
||||
plaintext = zlib.gunzipSync(compressed, { maxOutputLength: maxGunzipBytes });
|
||||
inner = BackupInnerPayloadSchema.parse(JSON.parse(plaintext.toString('utf8')));
|
||||
} finally {
|
||||
key.fill(0);
|
||||
|
|
@ -404,16 +602,75 @@ export function verifyBackupBundle(
|
|||
};
|
||||
}
|
||||
|
||||
function parseBackupEnvelopeForVerify(rawTextOrBuf: string | Buffer): BackupEnvelope {
|
||||
const rawStr = typeof rawTextOrBuf === 'string' ? rawTextOrBuf : rawTextOrBuf.toString('utf8');
|
||||
const envelope = BackupEnvelopeSchema.parse(JSON.parse(rawStr));
|
||||
const iv = Buffer.from(envelope.iv, 'base64');
|
||||
const tag = Buffer.from(envelope.tag, 'base64');
|
||||
if (iv.length !== 12 || tag.length !== 16) {
|
||||
throw new Error('Invalid AES-256-GCM parameters inside backup envelope');
|
||||
}
|
||||
return envelope;
|
||||
}
|
||||
|
||||
export function verifyBackupBundle(
|
||||
rawTextOrBuf: string | Buffer,
|
||||
keyOpts: {
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
vaultMasterKey?: string;
|
||||
maxGunzipBytes?: number;
|
||||
},
|
||||
): { summary: BackupVerificationSummary; inner: BackupInnerPayload } {
|
||||
const envelope = parseBackupEnvelopeForVerify(rawTextOrBuf);
|
||||
const key = deriveEnvelopeKeyForDecrypt(envelope, keyOpts);
|
||||
return decryptVerifiedInner(envelope, key, keyOpts, keyOpts.maxGunzipBytes);
|
||||
}
|
||||
|
||||
export async function verifyBackupBundleAsync(
|
||||
rawTextOrBuf: string | Buffer,
|
||||
keyOpts: {
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
vaultMasterKey?: string;
|
||||
scryptConcurrency?: number;
|
||||
maxGunzipBytes?: number;
|
||||
},
|
||||
): Promise<{ summary: BackupVerificationSummary; inner: BackupInnerPayload }> {
|
||||
const envelope = parseBackupEnvelopeForVerify(rawTextOrBuf);
|
||||
const key = await deriveEnvelopeKeyForDecryptAsync(envelope, keyOpts);
|
||||
return decryptVerifiedInner(envelope, key, keyOpts, keyOpts.maxGunzipBytes);
|
||||
}
|
||||
|
||||
export function verifyBackupSummaryOnly(
|
||||
rawTextOrBuf: string | Buffer,
|
||||
keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string },
|
||||
keyOpts: {
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
vaultMasterKey?: string;
|
||||
maxGunzipBytes?: number;
|
||||
},
|
||||
): BackupVerificationSummary {
|
||||
return verifyBackupBundle(rawTextOrBuf, keyOpts).summary;
|
||||
}
|
||||
|
||||
export async function verifyBackupSummaryOnlyAsync(
|
||||
rawTextOrBuf: string | Buffer,
|
||||
keyOpts: {
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
vaultMasterKey?: string;
|
||||
scryptConcurrency?: number;
|
||||
maxGunzipBytes?: number;
|
||||
},
|
||||
): Promise<BackupVerificationSummary> {
|
||||
const res = await verifyBackupBundleAsync(rawTextOrBuf, keyOpts);
|
||||
return res.summary;
|
||||
}
|
||||
|
||||
function writeAtomicPrivateFile(targetPath: string, content: string): void {
|
||||
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
|
||||
const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
|
||||
const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
|
||||
const fd = fs.openSync(tmpPath, 'w', 0o600);
|
||||
try {
|
||||
fs.writeFileSync(fd, content, 'utf8');
|
||||
|
|
@ -436,7 +693,7 @@ function writeAtomicPrivateFile(targetPath: string, content: string): void {
|
|||
|
||||
function swapConfigDirectoryAtomic(configDir: string, configFiles: Record<string, string>): void {
|
||||
const parent = path.dirname(configDir);
|
||||
const rand = crypto.randomBytes(5).toString('hex');
|
||||
const rand = crypto.randomBytes(6).toString('hex');
|
||||
const stageDir = path.join(parent, `config.restore-${rand}`);
|
||||
const bakDir = path.join(parent, `config.bak-${rand}`);
|
||||
|
||||
|
|
@ -474,22 +731,10 @@ function swapConfigDirectoryAtomic(configDir: string, configFiles: Record<string
|
|||
}
|
||||
}
|
||||
|
||||
export function restoreBackupBundle(
|
||||
rawTextOrBuf: string | Buffer,
|
||||
opts: {
|
||||
dataDir: string;
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
vaultMasterKey?: string;
|
||||
db?: Database.Database;
|
||||
},
|
||||
function applyVerifiedRestoreToDisk(
|
||||
verified: { summary: BackupVerificationSummary; inner: BackupInnerPayload },
|
||||
opts: { dataDir: string; db?: Database.Database },
|
||||
): { summary: BackupVerificationSummary; inner: BackupInnerPayload } {
|
||||
const verified = verifyBackupBundle(rawTextOrBuf, {
|
||||
masterKey: opts.masterKey,
|
||||
passphrase: opts.passphrase,
|
||||
vaultMasterKey: opts.vaultMasterKey,
|
||||
});
|
||||
|
||||
const dataDir = path.resolve(opts.dataDir);
|
||||
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
||||
|
||||
|
|
@ -532,3 +777,45 @@ export function restoreBackupBundle(
|
|||
|
||||
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);
|
||||
}
|
||||
|
|
|
|||
258
src/server/security/egress-guard.ts
Normal file
258
src/server/security/egress-guard.ts
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
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,
|
||||
});
|
||||
}
|
||||
|
|
@ -1,12 +1,16 @@
|
|||
import crypto from 'node:crypto';
|
||||
import type { NextFunction, Request, Response } from 'express';
|
||||
import net from 'node:net';
|
||||
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 { AuditService } from './audit.js';
|
||||
import {
|
||||
SESSION_COOKIE_NAME,
|
||||
sha256Hex,
|
||||
type AuthService,
|
||||
type AuthSession,
|
||||
} from './auth.js';
|
||||
import { isIpInCidrs } from './egress-guard.js';
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
|
|
@ -17,54 +21,207 @@ declare global {
|
|||
}
|
||||
}
|
||||
|
||||
export const DEFAULT_TRUSTED_PROXY_CIDRS = [
|
||||
'127.0.0.0/8',
|
||||
'::1/128',
|
||||
'10.0.0.0/8',
|
||||
'172.16.0.0/12',
|
||||
'192.168.0.0/16',
|
||||
'fc00::/7',
|
||||
];
|
||||
|
||||
interface RateBucketState {
|
||||
failures: number;
|
||||
lockedUntil: number;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
const DECAY_WINDOW_MS = 60 * 60 * 1000;
|
||||
const MAX_INMEM_BUCKETS = 2000;
|
||||
const GLOBAL_LOGIN_THRESHOLD = 20;
|
||||
|
||||
export class RateLimiter {
|
||||
private readonly buckets = new Map<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 } {
|
||||
const key = `${scope}:${ip}`;
|
||||
const state = this.buckets.get(key);
|
||||
if (!state) return { allowed: true, retryAfterSec: 0 };
|
||||
|
||||
const state = this.readBucket(key);
|
||||
const now = Date.now();
|
||||
if (state.lockedUntil > now) {
|
||||
if (state && state.lockedUntil > now) {
|
||||
return {
|
||||
allowed: false,
|
||||
retryAfterSec: Math.max(1, Math.ceil((state.lockedUntil - now) / 1000)),
|
||||
};
|
||||
}
|
||||
|
||||
if (scope === 'login') {
|
||||
const globalState = this.readBucket('login:__global__');
|
||||
if (globalState && globalState.lockedUntil > now) {
|
||||
return {
|
||||
allowed: false,
|
||||
retryAfterSec: Math.max(1, Math.ceil((globalState.lockedUntil - now) / 1000)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { allowed: true, retryAfterSec: 0 };
|
||||
}
|
||||
|
||||
recordFailure(scope: string, ip: string): number {
|
||||
acquireInFlight(scope: string, ip: string, maxConcurrent = 2): boolean {
|
||||
const key = `${scope}:${ip}`;
|
||||
const prev = this.buckets.get(key) ?? { failures: 0, lockedUntil: 0 };
|
||||
const failures = prev.failures + 1;
|
||||
const cur = this.inFlightCounts.get(key) ?? 0;
|
||||
if (cur >= maxConcurrent) return false;
|
||||
this.inFlightCounts.set(key, cur + 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
releaseInFlight(scope: string, ip: string): void {
|
||||
const key = `${scope}:${ip}`;
|
||||
const cur = this.inFlightCounts.get(key) ?? 0;
|
||||
if (cur <= 1) {
|
||||
this.inFlightCounts.delete(key);
|
||||
} else {
|
||||
this.inFlightCounts.set(key, cur - 1);
|
||||
}
|
||||
}
|
||||
|
||||
recordFailure(scope: string, ip: string): { lockedUntil: number; failures: number; globalTriggered: boolean } {
|
||||
const now = Date.now();
|
||||
const key = `${scope}:${ip}`;
|
||||
const prev = this.readBucket(key);
|
||||
const baseFailures =
|
||||
prev && (now - prev.updatedAt <= DECAY_WINDOW_MS || prev.lockedUntil > now)
|
||||
? prev.failures
|
||||
: 0;
|
||||
const failures = baseFailures + 1;
|
||||
let lockedUntil = 0;
|
||||
if (failures >= 5) {
|
||||
const delayMs = Math.min(300_000, 2000 * 2 ** (failures - 5));
|
||||
lockedUntil = Date.now() + delayMs;
|
||||
lockedUntil = now + delayMs;
|
||||
}
|
||||
this.buckets.set(key, { failures, lockedUntil });
|
||||
return lockedUntil;
|
||||
this.writeBucket(key, { failures, lockedUntil, updatedAt: now });
|
||||
|
||||
let globalTriggered = false;
|
||||
if (scope === 'login') {
|
||||
const gPrev = this.readBucket('login:__global__');
|
||||
const gBase =
|
||||
gPrev && (now - gPrev.updatedAt <= 15 * 60 * 1000 || gPrev.lockedUntil > now)
|
||||
? gPrev.failures
|
||||
: 0;
|
||||
const gFailures = gBase + 1;
|
||||
let gLockedUntil = gPrev?.lockedUntil ?? 0;
|
||||
if (gFailures >= GLOBAL_LOGIN_THRESHOLD) {
|
||||
const gDelay = Math.min(300_000, 60_000 * 2 ** Math.min(3, Math.floor((gFailures - GLOBAL_LOGIN_THRESHOLD) / 5)));
|
||||
gLockedUntil = now + gDelay;
|
||||
globalTriggered = true;
|
||||
}
|
||||
this.writeBucket('login:__global__', {
|
||||
failures: gFailures,
|
||||
lockedUntil: gLockedUntil,
|
||||
updatedAt: now,
|
||||
});
|
||||
}
|
||||
|
||||
return { lockedUntil, failures, globalTriggered };
|
||||
}
|
||||
|
||||
recordSuccess(scope: string, ip: string): void {
|
||||
this.buckets.delete(`${scope}:${ip}`);
|
||||
this.deleteBucket(`${scope}:${ip}`);
|
||||
if (scope === 'login') {
|
||||
this.deleteBucket('login:__global__');
|
||||
}
|
||||
}
|
||||
|
||||
private readBucket(key: string): RateBucketState | undefined {
|
||||
if (this.db) {
|
||||
try {
|
||||
const row = this.db
|
||||
.prepare(
|
||||
'SELECT failures, locked_until AS lockedUntil, updated_at AS updatedAt FROM rate_limits WHERE scope_key = ?',
|
||||
)
|
||||
.get(key) as RateBucketState | undefined;
|
||||
if (!row) return undefined;
|
||||
const now = Date.now();
|
||||
if (row.lockedUntil <= now && now - row.updatedAt > DECAY_WINDOW_MS) {
|
||||
this.deleteBucket(key);
|
||||
return undefined;
|
||||
}
|
||||
return row;
|
||||
} catch {
|
||||
// Fallback to in-memory map if DB unavailable
|
||||
}
|
||||
}
|
||||
|
||||
const mem = this.buckets.get(key);
|
||||
if (!mem) return undefined;
|
||||
const now = Date.now();
|
||||
if (mem.lockedUntil <= now && now - mem.updatedAt > DECAY_WINDOW_MS) {
|
||||
this.buckets.delete(key);
|
||||
return undefined;
|
||||
}
|
||||
return mem;
|
||||
}
|
||||
|
||||
private writeBucket(key: string, state: RateBucketState): void {
|
||||
if (this.db) {
|
||||
try {
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO rate_limits (scope_key, failures, locked_until, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(scope_key) DO UPDATE SET
|
||||
failures = excluded.failures,
|
||||
locked_until = excluded.locked_until,
|
||||
updated_at = excluded.updated_at`,
|
||||
)
|
||||
.run(key, state.failures, state.lockedUntil, state.updatedAt);
|
||||
|
||||
if (state.updatedAt - this.lastPruneAt > 10 * 60 * 1000) {
|
||||
this.lastPruneAt = state.updatedAt;
|
||||
this.db
|
||||
.prepare('DELETE FROM rate_limits WHERE locked_until <= ? AND updated_at < ?')
|
||||
.run(state.updatedAt, state.updatedAt - DECAY_WINDOW_MS);
|
||||
}
|
||||
return;
|
||||
} catch {
|
||||
// Fallback below
|
||||
}
|
||||
}
|
||||
|
||||
if (this.buckets.size >= MAX_INMEM_BUCKETS && !this.buckets.has(key)) {
|
||||
const oldestKey = this.buckets.keys().next().value;
|
||||
if (oldestKey) this.buckets.delete(oldestKey);
|
||||
}
|
||||
this.buckets.set(key, state);
|
||||
}
|
||||
|
||||
private deleteBucket(key: string): void {
|
||||
if (this.db) {
|
||||
try {
|
||||
this.db.prepare('DELETE FROM rate_limits WHERE scope_key = ?').run(key);
|
||||
} catch {
|
||||
// Ignore DB error
|
||||
}
|
||||
}
|
||||
this.buckets.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
export function extractCookies(cookieHeader: string | undefined): Record<string, string> {
|
||||
const result: Record<string, string> = {};
|
||||
const result = Object.create(null) as Record<string, string>;
|
||||
if (!cookieHeader) return result;
|
||||
for (const part of cookieHeader.split(';')) {
|
||||
const eq = part.indexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
const key = part.slice(0, eq).trim();
|
||||
if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
|
||||
const rawVal = part.slice(eq + 1).trim();
|
||||
try {
|
||||
result[key] = decodeURIComponent(rawVal);
|
||||
|
|
@ -75,23 +232,54 @@ export function extractCookies(cookieHeader: string | undefined): Record<string,
|
|||
return result;
|
||||
}
|
||||
|
||||
export function resolveClientIp(req: Request, trustCloudflare: boolean): string {
|
||||
if (trustCloudflare) {
|
||||
const cf = req.headers['cf-connecting-ip'];
|
||||
if (typeof cf === 'string' && cf.trim().length > 0) {
|
||||
return cf.split(',')[0]!.trim();
|
||||
}
|
||||
}
|
||||
return req.ip || req.socket.remoteAddress || 'unknown';
|
||||
export function isTrustedProxyPeer(
|
||||
remoteAddr: string | undefined,
|
||||
trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS,
|
||||
): boolean {
|
||||
if (!remoteAddr) return false;
|
||||
return isIpInCidrs(remoteAddr, trustedProxyCidrs);
|
||||
}
|
||||
|
||||
export function attachClientIp(trustCloudflare: boolean) {
|
||||
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'];
|
||||
if (typeof cf === 'string' && cf.trim().length > 0) {
|
||||
const candidate = cf.split(',')[0]!.trim();
|
||||
if (net.isIP(candidate) !== 0) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
return req.ip || peerIp || 'unknown';
|
||||
}
|
||||
|
||||
export function attachClientIp(
|
||||
trustCloudflare: boolean,
|
||||
trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS,
|
||||
) {
|
||||
return (req: Request, _res: Response, next: NextFunction): void => {
|
||||
req.clientIp = resolveClientIp(req, trustCloudflare);
|
||||
req.clientIp = resolveClientIp(req, trustCloudflare, trustedProxyCidrs);
|
||||
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) {
|
||||
return (req: Request, res: Response, next: NextFunction): void => {
|
||||
const cookies = extractCookies(req.headers.cookie);
|
||||
|
|
@ -118,6 +306,13 @@ export function requireCsrf(req: Request, res: Response, next: NextFunction): vo
|
|||
}
|
||||
const headerToken = req.headers['x-csrf-token'];
|
||||
if (typeof headerToken !== 'string' || headerToken.length < 16) {
|
||||
getAudit(req)?.log({
|
||||
action: 'security.csrf_denied',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: session.idHash,
|
||||
target: `${req.method} ${req.path}`,
|
||||
status: 'denied',
|
||||
});
|
||||
res.status(403).json({ error: 'CSRF_INVALID' });
|
||||
return;
|
||||
}
|
||||
|
|
@ -127,6 +322,13 @@ export function requireCsrf(req: Request, res: Response, next: NextFunction): vo
|
|||
providedHash.length !== expectedHash.length ||
|
||||
!crypto.timingSafeEqual(providedHash, expectedHash)
|
||||
) {
|
||||
getAudit(req)?.log({
|
||||
action: 'security.csrf_denied',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: session.idHash,
|
||||
target: `${req.method} ${req.path}`,
|
||||
status: 'denied',
|
||||
});
|
||||
res.status(403).json({ error: 'CSRF_INVALID' });
|
||||
return;
|
||||
}
|
||||
|
|
@ -140,6 +342,13 @@ export function enforceSafeMode(req: Request, res: Response, next: NextFunction)
|
|||
}
|
||||
const clientSafeHeader = req.headers['x-gcoord-safe-mode'] === '1';
|
||||
if (req.authSession?.safeMode || clientSafeHeader) {
|
||||
getAudit(req)?.log({
|
||||
action: 'security.safe_mode_denied',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession?.idHash ?? null,
|
||||
target: `${req.method} ${req.path}`,
|
||||
status: 'denied',
|
||||
});
|
||||
res.status(423).json({
|
||||
error: 'SAFE_MODE_ACTIVE',
|
||||
message: 'Disable Safe / Read-Only Mode before performing mutating actions.',
|
||||
|
|
@ -167,6 +376,13 @@ export function createStepUpGuard(
|
|||
}
|
||||
|
||||
if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) {
|
||||
getAudit(req)?.log({
|
||||
action: 'security.stepup_denied',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: session.idHash,
|
||||
target: `${req.method} ${req.path}`,
|
||||
status: 'denied',
|
||||
});
|
||||
res.status(403).json({
|
||||
error: 'STEP_UP_REQUIRED',
|
||||
message: 'Re-authentication verification is required for this sensitive operation.',
|
||||
|
|
@ -189,6 +405,13 @@ export function requireStepUp(req: Request, res: Response, next: NextFunction):
|
|||
return;
|
||||
}
|
||||
if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) {
|
||||
getAudit(req)?.log({
|
||||
action: 'security.stepup_denied',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: session.idHash,
|
||||
target: `${req.method} ${req.path}`,
|
||||
status: 'denied',
|
||||
});
|
||||
res.status(403).json({
|
||||
error: 'STEP_UP_REQUIRED',
|
||||
message: 'Re-authentication verification is required for this sensitive operation.',
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { VaultCredential } from '../../shared/schemas/vault.schema.js';
|
||||
|
|
@ -6,7 +7,6 @@ import type { VaultService } from './vault.js';
|
|||
export interface SavedPasswordEntry {
|
||||
id: string;
|
||||
label: string;
|
||||
plaintextPassword?: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
|
|
@ -48,7 +48,6 @@ export interface SyncRecoveryOptions {
|
|||
username?: string | null;
|
||||
totps?: SavedTotpEntry[];
|
||||
passwordMetaList?: Array<{ id: string; label: string; createdAt: number }>;
|
||||
passwordPlaintextUpdate?: { id: string; label: string; password: string; createdAt?: number };
|
||||
removedPasswordId?: string;
|
||||
newRecoveryCodes?: string[];
|
||||
snapshotReason?: string;
|
||||
|
|
@ -74,6 +73,8 @@ export class EmergencyRecoveryService {
|
|||
readBundle(): EmergencySecretsBundle | null {
|
||||
if (!fs.existsSync(this.bundlePath)) return null;
|
||||
try {
|
||||
const stat = fs.lstatSync(this.bundlePath);
|
||||
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
||||
const raw = JSON.parse(fs.readFileSync(this.bundlePath, 'utf8'));
|
||||
if (!raw || typeof raw !== 'object' || raw.version !== 1) return null;
|
||||
return raw as EmergencySecretsBundle;
|
||||
|
|
@ -105,43 +106,30 @@ export class EmergencyRecoveryService {
|
|||
? opts.vault.exportAllCredentials()
|
||||
: existing?.vaultCredentials ?? {};
|
||||
|
||||
// Merge saved plaintext passwords safely across updates
|
||||
const prevPwById = new Map<string, SavedPasswordEntry>();
|
||||
for (const p of existing?.admin.passwords ?? []) {
|
||||
prevPwById.set(p.id, p);
|
||||
prevPwById.set(p.id, {
|
||||
id: p.id,
|
||||
label: p.label,
|
||||
createdAt: p.createdAt,
|
||||
});
|
||||
}
|
||||
if (opts.removedPasswordId) {
|
||||
prevPwById.delete(opts.removedPasswordId);
|
||||
}
|
||||
if (opts.passwordPlaintextUpdate) {
|
||||
const u = opts.passwordPlaintextUpdate;
|
||||
prevPwById.set(u.id, {
|
||||
id: u.id,
|
||||
label: u.label,
|
||||
plaintextPassword: u.password,
|
||||
createdAt: new Date(u.createdAt ?? Date.now()).toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
let finalPasswords: SavedPasswordEntry[];
|
||||
if (opts.passwordMetaList) {
|
||||
finalPasswords = opts.passwordMetaList.map((meta) => {
|
||||
const prev = prevPwById.get(meta.id);
|
||||
return {
|
||||
const finalPasswords: SavedPasswordEntry[] = opts.passwordMetaList
|
||||
? opts.passwordMetaList.map((meta) => ({
|
||||
id: meta.id,
|
||||
label: meta.label,
|
||||
plaintextPassword: prev?.plaintextPassword,
|
||||
createdAt: new Date(meta.createdAt).toISOString(),
|
||||
};
|
||||
});
|
||||
} else {
|
||||
finalPasswords = [...prevPwById.values()];
|
||||
}
|
||||
}))
|
||||
: [...prevPwById.values()];
|
||||
|
||||
const bundle: EmergencySecretsBundle = {
|
||||
version: 1,
|
||||
updatedAt: nowIso,
|
||||
note: 'Local emergency plaintext backup managed by GCoordinator. Keep this file private (chmod 0600).',
|
||||
note: 'Local emergency recovery bundle managed by GCoordinator (passwords excluded). Keep this file private (chmod 0600).',
|
||||
vaultMasterKeyHex: masterKeyHex,
|
||||
admin: {
|
||||
username: opts.username !== undefined ? opts.username : existing?.admin.username ?? null,
|
||||
|
|
@ -185,10 +173,22 @@ export class EmergencyRecoveryService {
|
|||
|
||||
wipeAll(): void {
|
||||
const shred = (filePath: string) => {
|
||||
if (!fs.existsSync(filePath)) return;
|
||||
let stat: fs.Stats;
|
||||
try {
|
||||
const stat = fs.statSync(filePath);
|
||||
if (stat.isFile() && stat.size > 0) {
|
||||
stat = fs.lstatSync(filePath);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (stat.isSymbolicLink()) {
|
||||
fs.unlinkSync(filePath);
|
||||
return;
|
||||
}
|
||||
if (stat.isDirectory()) {
|
||||
fs.rmSync(filePath, { recursive: true, force: true });
|
||||
return;
|
||||
}
|
||||
if (stat.isFile() && stat.size > 0) {
|
||||
try {
|
||||
const fd = fs.openSync(filePath, 'r+');
|
||||
try {
|
||||
fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0);
|
||||
|
|
@ -196,9 +196,9 @@ export class EmergencyRecoveryService {
|
|||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
} catch {
|
||||
// Best-effort overwrite before unlink
|
||||
}
|
||||
} catch {
|
||||
// Best-effort overwrite before unlink
|
||||
}
|
||||
fs.unlinkSync(filePath);
|
||||
};
|
||||
|
|
@ -208,7 +208,11 @@ export class EmergencyRecoveryService {
|
|||
for (const f of fs.readdirSync(this.snapshotsDir)) {
|
||||
shred(path.join(this.snapshotsDir, f));
|
||||
}
|
||||
fs.rmdirSync(this.snapshotsDir);
|
||||
try {
|
||||
fs.rmdirSync(this.snapshotsDir);
|
||||
} catch {
|
||||
// Ignore unexpected remaining files
|
||||
}
|
||||
}
|
||||
if (fs.existsSync(this.recoveryDir)) {
|
||||
try {
|
||||
|
|
@ -227,7 +231,7 @@ export class EmergencyRecoveryService {
|
|||
}
|
||||
|
||||
private writeAtomicSecure(targetPath: string, content: string): void {
|
||||
const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
|
||||
const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
|
||||
const fd = fs.openSync(tmpPath, 'w', 0o600);
|
||||
try {
|
||||
fs.writeFileSync(fd, content, 'utf8');
|
||||
|
|
@ -247,8 +251,19 @@ export class EmergencyRecoveryService {
|
|||
.sort();
|
||||
while (files.length > MAX_SNAPSHOTS) {
|
||||
const oldest = files.shift()!;
|
||||
const p = path.join(this.snapshotsDir, oldest);
|
||||
try {
|
||||
fs.unlinkSync(path.join(this.snapshotsDir, oldest));
|
||||
const stat = fs.lstatSync(p);
|
||||
if (stat.isFile() && !stat.isSymbolicLink() && stat.size > 0) {
|
||||
const fd = fs.openSync(p, 'r+');
|
||||
try {
|
||||
fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0);
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
fs.unlinkSync(p);
|
||||
} catch {
|
||||
// Ignore cleanup failure
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,11 +10,14 @@ import {
|
|||
type VaultCredentialMeta,
|
||||
type VaultPayload,
|
||||
} from '../../shared/schemas/vault.schema.js';
|
||||
import type { VaultState } from '../../shared/ws-protocol.js';
|
||||
import type { VaultSealState, VaultState } from '../../shared/ws-protocol.js';
|
||||
|
||||
const VAULT_AAD = Buffer.from('gcoord-vault-v1', 'utf8');
|
||||
|
||||
export const VaultEnvelopeSchema = z.object({
|
||||
version: z.literal(1),
|
||||
alg: z.literal('aes-256-gcm'),
|
||||
aad: z.boolean().optional(),
|
||||
iv: z.string().min(1),
|
||||
tag: z.string().min(1),
|
||||
ciphertext: z.string().min(1),
|
||||
|
|
@ -42,6 +45,7 @@ export function generateMasterKeyBuffer(): Buffer {
|
|||
function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope {
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
||||
cipher.setAAD(VAULT_AAD);
|
||||
const plaintext = Buffer.from(JSON.stringify(payload), 'utf8');
|
||||
const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
|
|
@ -50,6 +54,7 @@ function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope {
|
|||
return {
|
||||
version: 1,
|
||||
alg: 'aes-256-gcm',
|
||||
aad: true,
|
||||
iv: iv.toString('base64'),
|
||||
tag: tag.toString('base64'),
|
||||
ciphertext: ciphertext.toString('base64'),
|
||||
|
|
@ -67,6 +72,9 @@ function decryptEnvelope(envelope: VaultEnvelope, key: Buffer): VaultPayload {
|
|||
}
|
||||
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
||||
if (envelope.aad) {
|
||||
decipher.setAAD(VAULT_AAD);
|
||||
}
|
||||
decipher.setAuthTag(tag);
|
||||
const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
try {
|
||||
|
|
@ -109,7 +117,11 @@ export function verifyVaultEnvelopeText(
|
|||
}
|
||||
|
||||
export function computeOpenSshFingerprint(publicKeyLine: string): string {
|
||||
const parsed = ssh2.utils.parseKey(publicKeyLine.trim());
|
||||
const trimmed = publicKeyLine.trim();
|
||||
if (/[\r\n\0]/.test(trimmed)) {
|
||||
throw new Error('Public key must be a single line');
|
||||
}
|
||||
const parsed = ssh2.utils.parseKey(trimmed);
|
||||
if (parsed instanceof Error) {
|
||||
throw parsed;
|
||||
}
|
||||
|
|
@ -122,6 +134,13 @@ export function computeOpenSshFingerprint(publicKeyLine: string): string {
|
|||
return `SHA256:${hash}`;
|
||||
}
|
||||
|
||||
export function validatePrivateKey(privateKey: string, passphrase?: string): void {
|
||||
const parsed = ssh2.utils.parseKey(privateKey, passphrase);
|
||||
if (parsed instanceof Error) {
|
||||
throw new Error(`Invalid SSH private key or passphrase: ${parsed.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates an OpenSSH Ed25519 keypair, retrying around ssh2's BitString
|
||||
* leading-zero stripping bug when a generated public key starts with 0x00.
|
||||
|
|
@ -165,22 +184,29 @@ export type VaultCredentialInput = DistributiveOmit<
|
|||
|
||||
export interface VaultServiceOptions {
|
||||
keyFilePath?: string;
|
||||
allowLocalKeyFile?: boolean;
|
||||
}
|
||||
|
||||
type KeySource = 'secret-file' | 'env' | 'key-file' | 'backup' | 'generated' | 'manual';
|
||||
|
||||
export class VaultService {
|
||||
private masterKey: Buffer | null = null;
|
||||
private credentials = new Map<string, VaultCredential>();
|
||||
private writeUnlocked = false;
|
||||
private autoInitializedEmpty = false;
|
||||
private wasPanicLocked = false;
|
||||
private keySource: KeySource | null = null;
|
||||
private readonly keyFilePath: string | null;
|
||||
private readonly allowLocalKeyFile: boolean;
|
||||
private readonly panicListeners = new Set<() => void>();
|
||||
private readonly sealListeners = new Set<() => void>();
|
||||
|
||||
constructor(
|
||||
private readonly vaultFilePath: string,
|
||||
options: VaultServiceOptions = {},
|
||||
) {
|
||||
this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null;
|
||||
this.allowLocalKeyFile = options.allowLocalKeyFile ?? true;
|
||||
this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath());
|
||||
}
|
||||
|
||||
|
|
@ -212,6 +238,12 @@ export class VaultService {
|
|||
return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized';
|
||||
}
|
||||
|
||||
get sealState(): VaultSealState {
|
||||
if (!fs.existsSync(this.vaultFilePath)) return 'uninitialized';
|
||||
if (this.masterKey === null) return 'sealed';
|
||||
return this.writeUnlocked ? 'unlocked' : 'write-locked';
|
||||
}
|
||||
|
||||
get isPanicLocked(): boolean {
|
||||
return this.wasPanicLocked || fs.existsSync(this.panicLockMarkerPath());
|
||||
}
|
||||
|
|
@ -223,6 +255,13 @@ export class VaultService {
|
|||
};
|
||||
}
|
||||
|
||||
onSeal(listener: () => void): () => void {
|
||||
this.sealListeners.add(listener);
|
||||
return () => {
|
||||
this.sealListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
initRuntime(options: {
|
||||
secretFilePath?: string;
|
||||
envKey?: string;
|
||||
|
|
@ -234,20 +273,20 @@ export class VaultService {
|
|||
return { runtimeReady: false, reason: 'panic_locked' };
|
||||
}
|
||||
|
||||
const candidates: string[] = [];
|
||||
const candidates: Array<{ value: string; source: KeySource }> = [];
|
||||
if (options.secretFilePath && fs.existsSync(options.secretFilePath)) {
|
||||
const val = fs.readFileSync(options.secretFilePath, 'utf8').trim();
|
||||
if (val) candidates.push(val);
|
||||
if (val) candidates.push({ value: val, source: 'secret-file' });
|
||||
}
|
||||
if (options.envKey && options.envKey.trim().length > 0) {
|
||||
candidates.push(options.envKey.trim());
|
||||
candidates.push({ value: options.envKey.trim(), source: 'env' });
|
||||
}
|
||||
if (this.keyFilePath && fs.existsSync(this.keyFilePath)) {
|
||||
const val = fs.readFileSync(this.keyFilePath, 'utf8').trim();
|
||||
if (val) candidates.push(val);
|
||||
if (val) candidates.push({ value: val, source: 'key-file' });
|
||||
}
|
||||
if (options.backupKey && options.backupKey.trim().length > 0) {
|
||||
candidates.push(options.backupKey.trim());
|
||||
candidates.push({ value: options.backupKey.trim(), source: 'backup' });
|
||||
}
|
||||
|
||||
if (fs.existsSync(this.vaultFilePath)) {
|
||||
|
|
@ -268,15 +307,19 @@ export class VaultService {
|
|||
for (const candidate of candidates) {
|
||||
let keyBuf: Buffer | null = null;
|
||||
try {
|
||||
keyBuf = parseMasterKey(candidate);
|
||||
keyBuf = parseMasterKey(candidate.value);
|
||||
const payload = decryptEnvelope(envelope, keyBuf);
|
||||
this.zeroizeMasterKey();
|
||||
this.masterKey = keyBuf;
|
||||
this.keySource = candidate.source;
|
||||
this.credentials = new Map(Object.entries(payload.credentials));
|
||||
this.writeUnlocked = false;
|
||||
this.autoInitializedEmpty = false;
|
||||
this.setPanicLockMarker(false);
|
||||
this.persistKeyFileIfConfigured(keyBuf);
|
||||
// Security invariant: NEVER mirror Docker Secret or env master keys to disk vault.key
|
||||
if (candidate.source === 'key-file') {
|
||||
this.persistKeyFileIfConfigured(keyBuf);
|
||||
}
|
||||
return { runtimeReady: true };
|
||||
} catch {
|
||||
keyBuf?.fill(0);
|
||||
|
|
@ -291,17 +334,28 @@ export class VaultService {
|
|||
|
||||
let keyBuf: Buffer | null = null;
|
||||
try {
|
||||
keyBuf = candidates[0] ? parseMasterKey(candidates[0]) : generateMasterKeyBuffer();
|
||||
const chosen = candidates[0];
|
||||
const source: KeySource = chosen ? chosen.source : 'generated';
|
||||
keyBuf = chosen ? parseMasterKey(chosen.value) : generateMasterKeyBuffer();
|
||||
const emptyPayload: VaultPayload = { version: 1, credentials: {} };
|
||||
this.writeVerifiedVaultAtomic(emptyPayload, keyBuf);
|
||||
|
||||
this.zeroizeMasterKey();
|
||||
this.masterKey = keyBuf;
|
||||
this.keySource = source;
|
||||
this.credentials.clear();
|
||||
this.writeUnlocked = false;
|
||||
this.autoInitializedEmpty = true;
|
||||
this.setPanicLockMarker(false);
|
||||
this.persistKeyFileIfConfigured(keyBuf);
|
||||
// Only write local keyfile when generated locally (or already using key-file) and allowed
|
||||
if (
|
||||
this.allowLocalKeyFile &&
|
||||
source !== 'secret-file' &&
|
||||
source !== 'env' &&
|
||||
source !== 'backup'
|
||||
) {
|
||||
this.persistKeyFileIfConfigured(keyBuf);
|
||||
}
|
||||
return { runtimeReady: true, initialized: true };
|
||||
} catch (err) {
|
||||
keyBuf?.fill(0);
|
||||
|
|
@ -362,11 +416,14 @@ export class VaultService {
|
|||
|
||||
this.zeroizeMasterKey();
|
||||
this.masterKey = keyBuf;
|
||||
this.keySource = 'manual';
|
||||
this.credentials.clear();
|
||||
this.writeUnlocked = true;
|
||||
this.autoInitializedEmpty = false;
|
||||
this.setPanicLockMarker(false);
|
||||
this.persistKeyFileIfConfigured(keyBuf);
|
||||
if (this.allowLocalKeyFile && this.keyFilePath && fs.existsSync(this.keyFilePath)) {
|
||||
this.persistKeyFileIfConfigured(keyBuf);
|
||||
}
|
||||
|
||||
return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') };
|
||||
}
|
||||
|
|
@ -384,17 +441,48 @@ export class VaultService {
|
|||
|
||||
this.zeroizeMasterKey();
|
||||
this.masterKey = keyBuf;
|
||||
this.keySource = 'manual';
|
||||
this.credentials = new Map(Object.entries(payload.credentials));
|
||||
this.writeUnlocked = true;
|
||||
this.autoInitializedEmpty = false;
|
||||
this.setPanicLockMarker(false);
|
||||
this.persistKeyFileIfConfigured(keyBuf);
|
||||
if (this.allowLocalKeyFile && this.keyFilePath && fs.existsSync(this.keyFilePath)) {
|
||||
this.persistKeyFileIfConfigured(keyBuf);
|
||||
}
|
||||
} catch (err) {
|
||||
keyBuf.fill(0);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
seal(): void {
|
||||
this.zeroizeMasterKey();
|
||||
this.keySource = null;
|
||||
this.credentials.clear();
|
||||
this.writeUnlocked = false;
|
||||
this.autoInitializedEmpty = false;
|
||||
|
||||
for (const listener of this.sealListeners) {
|
||||
try {
|
||||
listener();
|
||||
} catch {
|
||||
// Seal cleanup must continue across all listeners
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dropLocalKeyFile(): void {
|
||||
if (!this.keyFilePath) return;
|
||||
try {
|
||||
const stat = fs.lstatSync(this.keyFilePath);
|
||||
if (stat.isFile() || stat.isSymbolicLink()) {
|
||||
fs.unlinkSync(this.keyFilePath);
|
||||
}
|
||||
} catch {
|
||||
// Ignore missing or unreadable key file
|
||||
}
|
||||
}
|
||||
|
||||
unlockForModifications(): void {
|
||||
if (this.masterKey === null || this.isPanicLocked) {
|
||||
throw new Error('Master key is required to unseal vault');
|
||||
|
|
@ -472,7 +560,15 @@ export class VaultService {
|
|||
this.zeroizeMasterKey();
|
||||
this.masterKey = nextKey;
|
||||
this.writeUnlocked = true;
|
||||
this.persistKeyFileIfConfigured(nextKey);
|
||||
if (
|
||||
this.allowLocalKeyFile &&
|
||||
this.keySource !== 'secret-file' &&
|
||||
this.keySource !== 'env' &&
|
||||
this.keyFilePath &&
|
||||
fs.existsSync(this.keyFilePath)
|
||||
) {
|
||||
this.persistKeyFileIfConfigured(nextKey);
|
||||
}
|
||||
return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') };
|
||||
} catch (err) {
|
||||
nextKey.fill(0);
|
||||
|
|
@ -613,8 +709,8 @@ export class VaultService {
|
|||
this.keyFilePath ?? (fs.existsSync(siblingKeyFile) ? siblingKeyFile : null);
|
||||
if (!targetPath) return;
|
||||
|
||||
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
|
||||
const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`;
|
||||
fs.mkdirSync(path.dirname(targetPath), { recursive: true, mode: 0o700 });
|
||||
const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
|
||||
const fd = fs.openSync(tmpPath, 'w', 0o600);
|
||||
try {
|
||||
fs.writeFileSync(fd, `${key.toString('hex')}\n`, 'utf8');
|
||||
|
|
@ -635,11 +731,11 @@ export class VaultService {
|
|||
|
||||
private writeVerifiedVaultAtomic(payload: VaultPayload, key: Buffer): void {
|
||||
const dir = path.dirname(this.vaultFilePath);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
|
||||
const envelope = encryptPayload(payload, key);
|
||||
const serialized = JSON.stringify(envelope, null, 2);
|
||||
const tmpPath = `${this.vaultFilePath}.tmp.${process.pid}.${Date.now()}`;
|
||||
const tmpPath = `${this.vaultFilePath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`;
|
||||
|
||||
const fd = fs.openSync(tmpPath, 'w', 0o600);
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -7,13 +7,22 @@ import type { SSHPool } from './ssh-pool.js';
|
|||
|
||||
const OPENSSH_KEY_TYPES = new Set([
|
||||
'ssh-ed25519',
|
||||
'ssh-ed25519-cert-v01@openssh.com',
|
||||
'ssh-rsa',
|
||||
'ssh-rsa-cert-v01@openssh.com',
|
||||
'rsa-sha2-256',
|
||||
'rsa-sha2-512',
|
||||
'ssh-dss',
|
||||
'ecdsa-sha2-nistp256',
|
||||
'ecdsa-sha2-nistp256-cert-v01@openssh.com',
|
||||
'ecdsa-sha2-nistp384',
|
||||
'ecdsa-sha2-nistp384-cert-v01@openssh.com',
|
||||
'ecdsa-sha2-nistp521',
|
||||
'ecdsa-sha2-nistp521-cert-v01@openssh.com',
|
||||
'sk-ssh-ed25519@openssh.com',
|
||||
'sk-ssh-ed25519-cert-v01@openssh.com',
|
||||
'sk-ecdsa-sha2-nistp256@openssh.com',
|
||||
'sk-ecdsa-sha2-nistp256-cert-v01@openssh.com',
|
||||
]);
|
||||
|
||||
export interface AuthorizedKeyEntry {
|
||||
|
|
@ -135,6 +144,8 @@ function makeRotatedCredentialId(serverId: string): string {
|
|||
}
|
||||
|
||||
export class KeyManager {
|
||||
private readonly activeRotations = new Set<string>();
|
||||
|
||||
constructor(
|
||||
private readonly sshPool: SSHPool,
|
||||
private readonly vaultService: VaultService,
|
||||
|
|
@ -277,6 +288,32 @@ export class KeyManager {
|
|||
passphrase: string | undefined,
|
||||
actorIp: string,
|
||||
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> {
|
||||
const server = this.configManager.getServer(serverId);
|
||||
if (!server) {
|
||||
|
|
@ -324,7 +361,7 @@ export class KeyManager {
|
|||
newSecret.passphrase,
|
||||
);
|
||||
|
||||
// Step 4: Verified! Persist updated credentialId in server JSON
|
||||
// Step 4: Verified! Persist updated credentialId without tearing down live PTY/tunnel sessions
|
||||
const updatedServer = { ...server, credentialId: newCredId };
|
||||
this.configManager.saveConfigText(
|
||||
`servers/${server.id}.json`,
|
||||
|
|
@ -333,9 +370,6 @@ export class KeyManager {
|
|||
`Atomic SSH key rotation -> ${newCredId}`,
|
||||
);
|
||||
|
||||
// Reconnect pool onto the new key
|
||||
await this.sshPool.reconnect(server.id);
|
||||
|
||||
// Cleanly remove old public key from authorized_keys if it differs
|
||||
if (oldFingerprint && oldFingerprint !== newMeta.fingerprint) {
|
||||
const afterInspect = await this.inspectAuthorizedKeys(server.id);
|
||||
|
|
|
|||
|
|
@ -12,11 +12,16 @@ export interface KnownHostRecord {
|
|||
updatedAt: number;
|
||||
}
|
||||
|
||||
export function normalizeHostForKey(rawHost: string): string {
|
||||
const clean = rawHost.trim().toLowerCase().replace(/^\[|\]$/g, '');
|
||||
return clean.includes(':') ? `[${clean}]` : clean;
|
||||
}
|
||||
|
||||
export function buildHostPortKey(server: Pick<ServerConfig, 'host' | 'port' | 'jumpHostId'>): string {
|
||||
const hostLower = server.host.trim().toLowerCase();
|
||||
const hostNormalized = normalizeHostForKey(server.host);
|
||||
return server.jumpHostId
|
||||
? `${server.jumpHostId}->${hostLower}:${server.port}`
|
||||
: `${hostLower}:${server.port}`;
|
||||
? `${server.jumpHostId}->${hostNormalized}:${server.port}`
|
||||
: `${hostNormalized}:${server.port}`;
|
||||
}
|
||||
|
||||
export function parseHostKeyBuffer(keyBuf: Buffer): {
|
||||
|
|
@ -44,13 +49,32 @@ export function parseHostKeyBuffer(keyBuf: Buffer): {
|
|||
export class KnownHostsService {
|
||||
private readonly pendingTofu = new Map<string, PendingTofuInfo>();
|
||||
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 mismatchListeners = new Set<(alert: HostKeyAlert) => void>();
|
||||
|
||||
constructor(
|
||||
private readonly db: Database.Database,
|
||||
private readonly auditService?: AuditService,
|
||||
) {}
|
||||
|
||||
onHostKeyMismatch(listener: (alert: HostKeyAlert) => void): () => void {
|
||||
this.mismatchListeners.add(listener);
|
||||
return () => {
|
||||
this.mismatchListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
private emitMismatch(alert: HostKeyAlert): void {
|
||||
for (const cb of this.mismatchListeners) {
|
||||
try {
|
||||
cb(alert);
|
||||
} catch {
|
||||
// Isolate subscriber failures
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onChange(listener: () => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
|
|
@ -63,19 +87,20 @@ export class KnownHostsService {
|
|||
const { algorithm, fingerprint } = parseHostKeyBuffer(keyBuf);
|
||||
const now = Date.now();
|
||||
|
||||
const row = this.db
|
||||
const exactRow = this.db
|
||||
.prepare(
|
||||
'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts WHERE host_port = ?',
|
||||
'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts WHERE host_port = ? AND algorithm = ?',
|
||||
)
|
||||
.get(hostPortKey) as KnownHostRecord | undefined;
|
||||
.get(hostPortKey, algorithm) as KnownHostRecord | undefined;
|
||||
|
||||
if (row) {
|
||||
if (row.fingerprint === fingerprint) {
|
||||
if (exactRow) {
|
||||
if (exactRow.fingerprint === fingerprint) {
|
||||
const hadPending =
|
||||
this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id);
|
||||
this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf);
|
||||
this.db
|
||||
.prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ?')
|
||||
.run(now, hostPortKey);
|
||||
.prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ? AND algorithm = ?')
|
||||
.run(now, hostPortKey, algorithm);
|
||||
if (hadPending) this.emitChange();
|
||||
return true;
|
||||
}
|
||||
|
|
@ -86,7 +111,7 @@ export class KnownHostsService {
|
|||
host: server.host,
|
||||
port: server.port,
|
||||
algorithm,
|
||||
expectedFingerprint: row.fingerprint,
|
||||
expectedFingerprint: exactRow.fingerprint,
|
||||
actualFingerprint: fingerprint,
|
||||
detectedAt: now,
|
||||
};
|
||||
|
|
@ -99,10 +124,12 @@ export class KnownHostsService {
|
|||
status: 'denied',
|
||||
details: {
|
||||
hostPortKey,
|
||||
expected: row.fingerprint,
|
||||
algorithm,
|
||||
expected: exactRow.fingerprint,
|
||||
actual: fingerprint,
|
||||
},
|
||||
});
|
||||
this.emitMismatch(alert);
|
||||
this.emitChange();
|
||||
return false;
|
||||
}
|
||||
|
|
@ -112,6 +139,7 @@ export class KnownHostsService {
|
|||
const expected = server.hostKeyFingerprint.trim();
|
||||
if (expected === fingerprint) {
|
||||
this.upsertKnownHost(hostPortKey, algorithm, fingerprint, now);
|
||||
this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf);
|
||||
this.pendingTofu.delete(server.id);
|
||||
this.pendingMismatches.delete(server.id);
|
||||
this.auditService?.log({
|
||||
|
|
@ -141,8 +169,9 @@ export class KnownHostsService {
|
|||
actorIp: 'hub',
|
||||
target: server.id,
|
||||
status: 'denied',
|
||||
details: { hostPortKey, expected, actual: fingerprint },
|
||||
details: { hostPortKey, algorithm, expected, actual: fingerprint },
|
||||
});
|
||||
this.emitMismatch(alert);
|
||||
this.emitChange();
|
||||
return false;
|
||||
}
|
||||
|
|
@ -238,7 +267,7 @@ export class KnownHostsService {
|
|||
listKnownHosts(): KnownHostRecord[] {
|
||||
return this.db
|
||||
.prepare(
|
||||
'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC',
|
||||
'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',
|
||||
)
|
||||
.all() as KnownHostRecord[];
|
||||
}
|
||||
|
|
@ -272,15 +301,21 @@ export class KnownHostsService {
|
|||
this.emitChange();
|
||||
}
|
||||
|
||||
deleteKnownHost(hostPort: string): boolean {
|
||||
const res = this.db
|
||||
.prepare('DELETE FROM known_hosts WHERE host_port = ?')
|
||||
.run(hostPort);
|
||||
deleteKnownHost(hostPort: string, algorithm?: string): boolean {
|
||||
const res = algorithm
|
||||
? this.db
|
||||
.prepare('DELETE FROM known_hosts WHERE host_port = ? AND algorithm = ?')
|
||||
.run(hostPort, algorithm)
|
||||
: this.db.prepare('DELETE FROM known_hosts WHERE host_port = ?').run(hostPort);
|
||||
for (const [sid, p] of this.pendingTofu.entries()) {
|
||||
if (p.hostPortKey === hostPort) this.pendingTofu.delete(sid);
|
||||
if (p.hostPortKey === hostPort && (!algorithm || p.algorithm === algorithm)) {
|
||||
this.pendingTofu.delete(sid);
|
||||
}
|
||||
}
|
||||
for (const [sid, m] of this.pendingMismatches.entries()) {
|
||||
if (m.hostPortKey === hostPort) this.pendingMismatches.delete(sid);
|
||||
if (m.hostPortKey === hostPort && (!algorithm || m.algorithm === algorithm)) {
|
||||
this.pendingMismatches.delete(sid);
|
||||
}
|
||||
}
|
||||
if (res.changes > 0) this.emitChange();
|
||||
return res.changes > 0;
|
||||
|
|
@ -296,14 +331,29 @@ export class KnownHostsService {
|
|||
.prepare(
|
||||
`INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT(host_port) DO UPDATE SET
|
||||
algorithm = excluded.algorithm,
|
||||
ON CONFLICT(host_port, algorithm) DO UPDATE SET
|
||||
fingerprint = excluded.fingerprint,
|
||||
updated_at = excluded.updated_at`,
|
||||
)
|
||||
.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 {
|
||||
for (const listener of this.listeners) {
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import type { ClientChannel } from 'ssh2';
|
|||
import { WS_CHANNELS } from '../../shared/ws-protocol.js';
|
||||
import type { WsHub } from '../api/ws-hub.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import type { RuntimeLimits } from '../config/runtime-limits.js';
|
||||
import type { SSHPool } from './ssh-pool.js';
|
||||
import { posixSingleQuote } from './sudo.js';
|
||||
|
||||
|
|
@ -34,22 +35,34 @@ export interface OpenPtyParams {
|
|||
}
|
||||
|
||||
interface ScrollChunk {
|
||||
offsetMs: number;
|
||||
text: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
interface InternalPtySession {
|
||||
info: PtySessionInfo;
|
||||
env?: Record<string, string>;
|
||||
sudo?: boolean;
|
||||
channel: ClientChannel;
|
||||
chunks: ScrollChunk[];
|
||||
stdoutDecoder: StringDecoder;
|
||||
stderrDecoder: StringDecoder;
|
||||
}
|
||||
|
||||
const MAX_RETAINED_EXITED_SESSIONS = 20;
|
||||
export function assertSafeCwd(cwd: string): string {
|
||||
if (/[\x00-\x1f\x7f]/.test(cwd)) {
|
||||
throw new Error('Invalid cwd: control characters are not permitted');
|
||||
}
|
||||
const trimmed = cwd.trim();
|
||||
if (trimmed.length > 1024) {
|
||||
throw new Error('Invalid cwd: exceeds 1024 character limit');
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
export function formatRemoteCd(cwd: string): string {
|
||||
const trimmed = cwd.trim();
|
||||
const trimmed = assertSafeCwd(cwd);
|
||||
if (trimmed === '~' || trimmed === '~/') {
|
||||
return 'cd -- "$HOME"';
|
||||
}
|
||||
|
|
@ -71,7 +84,6 @@ function sliceTrailingUtf8(text: string, maxBytes: number): { text: string; byte
|
|||
return { text, bytes: buf.length };
|
||||
}
|
||||
let start = buf.length - maxBytes;
|
||||
// Skip UTF-8 continuation bytes (10xxxxxx) so we never cut inside a codepoint
|
||||
while (start < buf.length && (buf[start]! & 0b1100_0000) === 0b1000_0000) {
|
||||
start++;
|
||||
}
|
||||
|
|
@ -87,6 +99,7 @@ export class PTYManager {
|
|||
private readonly sshPool: SSHPool,
|
||||
private readonly configManager: ConfigManager,
|
||||
private readonly wsHub: WsHub,
|
||||
private readonly getRuntimeLimits?: () => RuntimeLimits,
|
||||
) {
|
||||
this.reaperTimer = setInterval(() => {
|
||||
this.reapIdleSessions();
|
||||
|
|
@ -94,14 +107,12 @@ export class PTYManager {
|
|||
this.reaperTimer.unref();
|
||||
}
|
||||
|
||||
async openSession(params: OpenPtyParams): Promise<PtySessionInfo> {
|
||||
const cols = Math.max(10, Math.min(500, Math.floor(params.cols ?? 80)));
|
||||
const rows = Math.max(4, Math.min(200, Math.floor(params.rows ?? 24)));
|
||||
const now = Date.now();
|
||||
const sessionId = `pty-${crypto.randomBytes(6).toString('hex')}`;
|
||||
const trimmedCwd = params.cwd?.trim();
|
||||
|
||||
let channel: ClientChannel;
|
||||
private async createChannel(
|
||||
params: OpenPtyParams,
|
||||
cols: number,
|
||||
rows: number,
|
||||
trimmedCwd?: string,
|
||||
): Promise<ClientChannel> {
|
||||
if (params.command) {
|
||||
const cmd = trimmedCwd
|
||||
? `${formatRemoteCd(trimmedCwd)} && (${params.command})`
|
||||
|
|
@ -111,45 +122,30 @@ export class PTYManager {
|
|||
sudo: params.sudo,
|
||||
pty: { cols, rows, term: 'xterm-256color' },
|
||||
});
|
||||
channel = stream.channel;
|
||||
} else {
|
||||
channel = await this.sshPool.openShell(params.serverId, {
|
||||
stream.done.catch(() => undefined);
|
||||
return stream.channel;
|
||||
}
|
||||
|
||||
if (trimmedCwd && trimmedCwd !== '~') {
|
||||
const channel = await this.sshPool.openShell(params.serverId, {
|
||||
cols,
|
||||
rows,
|
||||
term: 'xterm-256color',
|
||||
});
|
||||
if (trimmedCwd && trimmedCwd !== '~') {
|
||||
channel.write(`${formatRemoteCd(trimmedCwd)}\n`);
|
||||
}
|
||||
channel.write(`${formatRemoteCd(trimmedCwd)}\n`);
|
||||
return channel;
|
||||
}
|
||||
|
||||
const title =
|
||||
params.title?.trim() ||
|
||||
(params.command
|
||||
? `${params.serverId}: ${params.command.slice(0, 32)}`
|
||||
: `${params.serverId} shell`);
|
||||
return this.sshPool.openShell(params.serverId, {
|
||||
cols,
|
||||
rows,
|
||||
term: 'xterm-256color',
|
||||
});
|
||||
}
|
||||
|
||||
const internal: InternalPtySession = {
|
||||
info: {
|
||||
sessionId,
|
||||
serverId: params.serverId,
|
||||
title,
|
||||
cwd: trimmedCwd || undefined,
|
||||
command: params.command,
|
||||
cols,
|
||||
rows,
|
||||
createdAt: now,
|
||||
lastActivityAt: now,
|
||||
exited: false,
|
||||
exitCode: null,
|
||||
scrollbackBytes: 0,
|
||||
},
|
||||
channel,
|
||||
chunks: [],
|
||||
stdoutDecoder: new StringDecoder('utf8'),
|
||||
stderrDecoder: new StringDecoder('utf8'),
|
||||
};
|
||||
this.sessions.set(sessionId, internal);
|
||||
private bindChannelHandlers(internal: InternalPtySession): void {
|
||||
const { channel } = internal;
|
||||
const { sessionId } = internal.info;
|
||||
|
||||
channel.on('data', (chunk: Buffer) => {
|
||||
const text = internal.stdoutDecoder.write(chunk);
|
||||
|
|
@ -162,7 +158,7 @@ export class PTYManager {
|
|||
});
|
||||
|
||||
const finalizeExit = (code: number | null) => {
|
||||
if (internal.info.exited) return;
|
||||
if (internal.channel !== channel || internal.info.exited) return;
|
||||
const tailOut = internal.stdoutDecoder.end();
|
||||
if (tailOut) this.appendOutput(internal, tailOut);
|
||||
const tailErr = internal.stderrDecoder.end();
|
||||
|
|
@ -185,7 +181,99 @@ export class PTYManager {
|
|||
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 =
|
||||
params.title?.trim() ||
|
||||
(params.command
|
||||
? `${params.serverId}: ${params.command.slice(0, 32)}`
|
||||
: `${params.serverId} shell`);
|
||||
|
||||
const internal: InternalPtySession = {
|
||||
info: {
|
||||
sessionId,
|
||||
serverId: params.serverId,
|
||||
title,
|
||||
cwd: trimmedCwd || undefined,
|
||||
command: params.command,
|
||||
cols,
|
||||
rows,
|
||||
createdAt: now,
|
||||
lastActivityAt: now,
|
||||
exited: false,
|
||||
exitCode: null,
|
||||
scrollbackBytes: 0,
|
||||
},
|
||||
env: params.env,
|
||||
sudo: params.sudo,
|
||||
channel,
|
||||
chunks: [],
|
||||
stdoutDecoder: new StringDecoder('utf8'),
|
||||
stderrDecoder: new StringDecoder('utf8'),
|
||||
};
|
||||
this.sessions.set(sessionId, internal);
|
||||
this.bindChannelHandlers(internal);
|
||||
|
||||
return { ...internal.info };
|
||||
}
|
||||
|
||||
async reconnectSession(sessionId: string): Promise<PtySessionInfo | null> {
|
||||
const internal = this.sessions.get(sessionId);
|
||||
if (!internal) return null;
|
||||
|
||||
const oldChannel = internal.channel;
|
||||
const channel = await this.createChannel(
|
||||
{
|
||||
serverId: internal.info.serverId,
|
||||
command: internal.info.command,
|
||||
env: internal.env,
|
||||
sudo: internal.sudo,
|
||||
},
|
||||
internal.info.cols,
|
||||
internal.info.rows,
|
||||
internal.info.cwd,
|
||||
);
|
||||
|
||||
internal.channel = channel;
|
||||
internal.stdoutDecoder = new StringDecoder('utf8');
|
||||
internal.stderrDecoder = new StringDecoder('utf8');
|
||||
internal.info.exited = false;
|
||||
internal.info.exitCode = null;
|
||||
internal.info.lastActivityAt = Date.now();
|
||||
this.bindChannelHandlers(internal);
|
||||
|
||||
try {
|
||||
oldChannel.close();
|
||||
oldChannel.destroy();
|
||||
} catch {
|
||||
// Ignore cleanup errors on prior channel
|
||||
}
|
||||
|
||||
this.appendOutput(internal, '\r\n[gcoord: reconnected PTY session]\r\n');
|
||||
return { ...internal.info };
|
||||
}
|
||||
|
||||
|
|
@ -215,7 +303,6 @@ export class PTYManager {
|
|||
entry.info.cols = clampedCols;
|
||||
entry.info.rows = clampedRows;
|
||||
entry.info.lastActivityAt = Date.now();
|
||||
// @types/ssh2: Channel.setWindow(rows, cols, height, width)
|
||||
entry.channel.setWindow(clampedRows, clampedCols, 0, 0);
|
||||
return true;
|
||||
}
|
||||
|
|
@ -228,16 +315,34 @@ export class PTYManager {
|
|||
|
||||
exportScrollback(
|
||||
sessionId: string,
|
||||
format: 'plain' | 'ansi' = 'plain',
|
||||
): { filename: string; content: string } | null {
|
||||
format: 'plain' | 'ansi' | 'cast' = 'plain',
|
||||
): { filename: string; content: string; contentType: string } | null {
|
||||
const entry = this.sessions.get(sessionId);
|
||||
if (!entry) return null;
|
||||
if (format === 'cast') {
|
||||
const header = JSON.stringify({
|
||||
version: 2,
|
||||
width: entry.info.cols,
|
||||
height: entry.info.rows,
|
||||
timestamp: Math.floor(entry.info.createdAt / 1000),
|
||||
title: entry.info.title,
|
||||
});
|
||||
const events = entry.chunks.map((c) =>
|
||||
JSON.stringify([Number((c.offsetMs / 1000).toFixed(3)), 'o', c.text]),
|
||||
);
|
||||
return {
|
||||
filename: `${entry.info.serverId}-${sessionId}.cast`,
|
||||
content: `${[header, ...events].join('\n')}\n`,
|
||||
contentType: 'application/x-asciicast; charset=utf-8',
|
||||
};
|
||||
}
|
||||
const raw = entry.chunks.map((c) => c.text).join('');
|
||||
const content = format === 'ansi' ? raw : stripAnsiSequences(raw);
|
||||
const ext = format === 'ansi' ? 'ansi.log' : 'txt';
|
||||
return {
|
||||
filename: `${entry.info.serverId}-${sessionId}.${ext}`,
|
||||
content,
|
||||
contentType: 'text/plain; charset=utf-8',
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -275,15 +380,22 @@ export class PTYManager {
|
|||
}
|
||||
|
||||
private appendOutput(entry: InternalPtySession, text: string): void {
|
||||
const maxBytes = Math.max(16_384, this.configManager.getSettings().ptyScrollbackBytes);
|
||||
const configuredMax = 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 now = Date.now();
|
||||
const offsetMs = Math.max(0, now - entry.info.createdAt);
|
||||
|
||||
if (rawBytes >= maxBytes) {
|
||||
const trimmed = sliceTrailingUtf8(text, maxBytes);
|
||||
entry.chunks = [{ text: trimmed.text, bytes: trimmed.bytes }];
|
||||
entry.chunks = [{ offsetMs, text: trimmed.text, bytes: trimmed.bytes }];
|
||||
entry.info.scrollbackBytes = trimmed.bytes;
|
||||
} else {
|
||||
entry.chunks.push({ text, bytes: rawBytes });
|
||||
entry.chunks.push({ offsetMs, text, bytes: rawBytes });
|
||||
entry.info.scrollbackBytes += rawBytes;
|
||||
while (entry.info.scrollbackBytes > maxBytes && entry.chunks.length > 0) {
|
||||
const dropped = entry.chunks.shift()!;
|
||||
|
|
@ -291,7 +403,7 @@ export class PTYManager {
|
|||
}
|
||||
}
|
||||
|
||||
entry.info.lastActivityAt = Date.now();
|
||||
entry.info.lastActivityAt = now;
|
||||
this.wsHub.broadcastChannel(WS_CHANNELS.pty(entry.info.sessionId), {
|
||||
type: 'pty:output',
|
||||
sessionId: entry.info.sessionId,
|
||||
|
|
@ -320,10 +432,11 @@ export class PTYManager {
|
|||
}
|
||||
|
||||
private pruneExcessExited(): void {
|
||||
const maxRetained = this.getRuntimeLimits?.()?.maxRetainedExitedPtys ?? 12;
|
||||
const exited = [...this.sessions.values()]
|
||||
.filter((s) => s.info.exited)
|
||||
.sort((a, b) => a.info.lastActivityAt - b.info.lastActivityAt);
|
||||
while (exited.length > MAX_RETAINED_EXITED_SESSIONS) {
|
||||
while (exited.length > maxRetained) {
|
||||
const oldest = exited.shift()!;
|
||||
this.sessions.delete(oldest.info.sessionId);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ export interface SftpListEntry {
|
|||
mtimeMs: number;
|
||||
uid: number;
|
||||
gid: number;
|
||||
symlinkTarget?: string;
|
||||
}
|
||||
|
||||
export interface SftpTextFile {
|
||||
|
|
@ -33,6 +34,8 @@ export class SftpServiceError extends Error {
|
|||
| 'NOT_FOUND'
|
||||
| 'NOT_A_DIRECTORY'
|
||||
| 'IS_A_DIRECTORY'
|
||||
| 'UNSUPPORTED_FILE_TYPE'
|
||||
| 'ALREADY_EXISTS'
|
||||
| 'FILE_TOO_LARGE'
|
||||
| 'BINARY_FILE_NOT_EDITABLE'
|
||||
| 'CONFLICT'
|
||||
|
|
@ -104,9 +107,18 @@ export class SftpService {
|
|||
if (item.filename === '.' || item.filename === '..') continue;
|
||||
const mode = item.attrs.mode ?? 0;
|
||||
const type = modeToType(mode);
|
||||
const itemPath = path.posix.join(resolved, item.filename);
|
||||
let symlinkTarget: string | undefined;
|
||||
if (type === 'symlink') {
|
||||
try {
|
||||
symlinkTarget = await promisifySftp<string>((cb) => sftp.readlink(itemPath, cb));
|
||||
} catch {
|
||||
symlinkTarget = undefined;
|
||||
}
|
||||
}
|
||||
entries.push({
|
||||
name: item.filename,
|
||||
path: path.posix.join(resolved, item.filename),
|
||||
path: itemPath,
|
||||
type,
|
||||
size: item.attrs.size ?? 0,
|
||||
mode,
|
||||
|
|
@ -114,6 +126,7 @@ export class SftpService {
|
|||
mtimeMs: (item.attrs.mtime ?? 0) * 1000,
|
||||
uid: item.attrs.uid ?? 0,
|
||||
gid: item.attrs.gid ?? 0,
|
||||
...(symlinkTarget !== undefined ? { symlinkTarget } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -131,18 +144,28 @@ export class SftpService {
|
|||
async statPath(serverId: string, remotePath: string): Promise<SftpListEntry> {
|
||||
return this.withSftp(serverId, async (sftp) => {
|
||||
const resolved = await this.resolveRemotePath(sftp, remotePath);
|
||||
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
|
||||
const mode = stats.mode ?? 0;
|
||||
const lstats = await promisifySftp<Stats>((cb) => sftp.lstat(resolved, cb));
|
||||
const mode = lstats.mode ?? 0;
|
||||
const type = modeToType(mode);
|
||||
let symlinkTarget: string | undefined;
|
||||
if (type === 'symlink') {
|
||||
try {
|
||||
symlinkTarget = await promisifySftp<string>((cb) => sftp.readlink(resolved, cb));
|
||||
} catch {
|
||||
symlinkTarget = undefined;
|
||||
}
|
||||
}
|
||||
return {
|
||||
name: path.posix.basename(resolved) || '/',
|
||||
path: resolved,
|
||||
type: modeToType(mode),
|
||||
size: stats.size ?? 0,
|
||||
type,
|
||||
size: lstats.size ?? 0,
|
||||
mode,
|
||||
permissionsOctal: (mode & 0o7777).toString(8).padStart(4, '0'),
|
||||
mtimeMs: (stats.mtime ?? 0) * 1000,
|
||||
uid: stats.uid ?? 0,
|
||||
gid: stats.gid ?? 0,
|
||||
mtimeMs: (lstats.mtime ?? 0) * 1000,
|
||||
uid: lstats.uid ?? 0,
|
||||
gid: lstats.gid ?? 0,
|
||||
...(symlinkTarget !== undefined ? { symlinkTarget } : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
|
@ -169,12 +192,19 @@ export class SftpService {
|
|||
try {
|
||||
const resolved = await this.resolveRemotePath(sftp, remotePath);
|
||||
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
|
||||
if (modeToType(stats.mode) === 'dir') {
|
||||
const kind = modeToType(stats.mode);
|
||||
if (kind === 'dir') {
|
||||
throw new SftpServiceError(
|
||||
'IS_A_DIRECTORY',
|
||||
'Cannot download a directory as a single file; use /archive instead.',
|
||||
);
|
||||
}
|
||||
if (kind !== 'file') {
|
||||
throw new SftpServiceError(
|
||||
'UNSUPPORTED_FILE_TYPE',
|
||||
`Refusing to download special/non-regular file: ${resolved}`,
|
||||
);
|
||||
}
|
||||
const stream = sftp.createReadStream(resolved);
|
||||
stream.once('close', cleanup);
|
||||
stream.once('error', cleanup);
|
||||
|
|
@ -199,10 +229,14 @@ export class SftpService {
|
|||
): Promise<{ path: string; bytesWritten: number }> {
|
||||
return this.withSftp(serverId, async (sftp) => {
|
||||
const resolved = await this.resolveRemotePath(sftp, remotePath);
|
||||
const dest = sftp.createWriteStream(resolved);
|
||||
const tmpPath = path.posix.join(
|
||||
path.posix.dirname(resolved),
|
||||
`.gcoord-up-${crypto.randomBytes(6).toString('hex')}`,
|
||||
);
|
||||
const dest = sftp.createWriteStream(tmpPath);
|
||||
|
||||
let bytesWritten = 0;
|
||||
return new Promise<{ path: string; bytesWritten: number }>((resolve, reject) => {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const fail = (err: Error) => {
|
||||
if (settled) return;
|
||||
|
|
@ -237,11 +271,41 @@ export class SftpService {
|
|||
dest.on('close', () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve({ path: resolved, bytesWritten });
|
||||
resolve();
|
||||
});
|
||||
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -253,16 +317,43 @@ export class SftpService {
|
|||
});
|
||||
}
|
||||
|
||||
async rename(serverId: string, fromPath: string, toPath: string): Promise<{ from: string; to: string }> {
|
||||
async rename(
|
||||
serverId: string,
|
||||
fromPath: string,
|
||||
toPath: string,
|
||||
overwrite = false,
|
||||
): Promise<{ from: string; to: string }> {
|
||||
return this.withSftp(serverId, async (sftp) => {
|
||||
const resolvedFrom = await this.resolveRemotePath(sftp, fromPath);
|
||||
const resolvedTo = await this.resolveRemotePath(sftp, toPath);
|
||||
await this.renameSftpPath(sftp, resolvedFrom, resolvedTo);
|
||||
if (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 };
|
||||
});
|
||||
}
|
||||
|
||||
async chmod(serverId: string, remotePath: string, modeInput: string | number): Promise<{ path: string; permissionsOctal: string }> {
|
||||
async chmod(
|
||||
serverId: string,
|
||||
remotePath: string,
|
||||
modeInput: string | number,
|
||||
): Promise<{ path: string; permissionsOctal: string }> {
|
||||
const parsedMode =
|
||||
typeof modeInput === 'number'
|
||||
? modeInput
|
||||
|
|
@ -283,6 +374,37 @@ export class SftpService {
|
|||
});
|
||||
}
|
||||
|
||||
async chown(
|
||||
serverId: string,
|
||||
remotePath: string,
|
||||
uid: number,
|
||||
gid: number,
|
||||
sudo = false,
|
||||
): Promise<{ path: string; uid: number; gid: number }> {
|
||||
if (!Number.isInteger(uid) || uid < 0 || !Number.isInteger(gid) || gid < 0) {
|
||||
throw new SftpServiceError('INVALID_MODE', 'uid and gid must be non-negative integers');
|
||||
}
|
||||
|
||||
if (sudo) {
|
||||
const resolved = await this.resolvePathNoStat(serverId, remotePath);
|
||||
const res = await this.sshPool.exec(
|
||||
serverId,
|
||||
`chown ${uid}:${gid} -- ${posixSingleQuote(resolved)}`,
|
||||
{ sudo: true },
|
||||
);
|
||||
if (res.exitCode !== 0) {
|
||||
throw new Error(res.stderr.trim() || `chown failed for ${resolved}`);
|
||||
}
|
||||
return { path: resolved, uid, gid };
|
||||
}
|
||||
|
||||
return this.withSftp(serverId, async (sftp) => {
|
||||
const resolved = await this.resolveRemotePath(sftp, remotePath);
|
||||
await promisifySftpVoid((cb) => sftp.chown(resolved, uid, gid, cb));
|
||||
return { path: resolved, uid, gid };
|
||||
});
|
||||
}
|
||||
|
||||
async deletePath(
|
||||
serverId: string,
|
||||
remotePath: string,
|
||||
|
|
@ -298,6 +420,51 @@ export class SftpService {
|
|||
});
|
||||
}
|
||||
|
||||
async bulkDelete(
|
||||
serverId: string,
|
||||
paths: string[],
|
||||
recursive = false,
|
||||
): Promise<{ deleted: string[]; failed: Array<{ path: string; error: string }> }> {
|
||||
const deleted: string[] = [];
|
||||
const failed: Array<{ path: string; error: string }> = [];
|
||||
for (const p of paths) {
|
||||
try {
|
||||
const res = await this.deletePath(serverId, p, recursive);
|
||||
deleted.push(res);
|
||||
} catch (err) {
|
||||
failed.push({
|
||||
path: p,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
}
|
||||
}
|
||||
return { deleted, failed };
|
||||
}
|
||||
|
||||
async searchFiles(
|
||||
serverId: string,
|
||||
basePath: string,
|
||||
query: string,
|
||||
maxResults = 100,
|
||||
): Promise<{ basePath: string; matches: string[] }> {
|
||||
const cleanQuery = query.trim();
|
||||
if (!cleanQuery || /[\x00\r\n]/.test(cleanQuery)) {
|
||||
throw new SftpServiceError('INVALID_PATH', 'Invalid search query');
|
||||
}
|
||||
const resolvedBase = await this.resolvePathNoStat(serverId, basePath || '/');
|
||||
const escapedPattern = cleanQuery.includes('*') || cleanQuery.includes('?')
|
||||
? cleanQuery
|
||||
: `*${cleanQuery}*`;
|
||||
const cap = Math.max(1, Math.min(200, maxResults));
|
||||
const cmd = `find ${posixSingleQuote(resolvedBase)} -maxdepth 5 -iname ${posixSingleQuote(escapedPattern)} 2>/dev/null | head -n ${cap}`;
|
||||
const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000, maxBytes: 256 * 1024 });
|
||||
const matches = res.stdout
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l.length > 0 && l !== resolvedBase);
|
||||
return { basePath: resolvedBase, matches };
|
||||
}
|
||||
|
||||
async readTextFile(
|
||||
serverId: string,
|
||||
remotePath: string,
|
||||
|
|
@ -341,7 +508,10 @@ export class SftpService {
|
|||
}
|
||||
const buf = Buffer.from(catRes.stdout, 'utf8');
|
||||
if (buf.includes(0)) {
|
||||
throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor');
|
||||
throw new SftpServiceError(
|
||||
'BINARY_FILE_NOT_EDITABLE',
|
||||
'Binary file cannot be opened in inline editor',
|
||||
);
|
||||
}
|
||||
return {
|
||||
path: resolved,
|
||||
|
|
@ -355,9 +525,16 @@ export class SftpService {
|
|||
return this.withSftp(serverId, async (sftp) => {
|
||||
const resolved = await this.resolveRemotePath(sftp, remotePath);
|
||||
const stats = await promisifySftp<Stats>((cb) => sftp.stat(resolved, cb));
|
||||
if (modeToType(stats.mode) === 'dir') {
|
||||
const kind = modeToType(stats.mode);
|
||||
if (kind === 'dir') {
|
||||
throw new SftpServiceError('IS_A_DIRECTORY', `${resolved} is a directory`);
|
||||
}
|
||||
if (kind !== 'file') {
|
||||
throw new SftpServiceError(
|
||||
'UNSUPPORTED_FILE_TYPE',
|
||||
`Refusing to open special/non-regular file: ${resolved}`,
|
||||
);
|
||||
}
|
||||
if ((stats.size ?? 0) > maxBytes) {
|
||||
throw new SftpServiceError(
|
||||
'FILE_TOO_LARGE',
|
||||
|
|
@ -369,7 +546,10 @@ export class SftpService {
|
|||
throw new SftpServiceError('FILE_TOO_LARGE', 'File exceeds inline editor limit');
|
||||
}
|
||||
if (buf.includes(0)) {
|
||||
throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor');
|
||||
throw new SftpServiceError(
|
||||
'BINARY_FILE_NOT_EDITABLE',
|
||||
'Binary file cannot be opened in inline editor',
|
||||
);
|
||||
}
|
||||
return {
|
||||
path: resolved,
|
||||
|
|
@ -412,7 +592,7 @@ export class SftpService {
|
|||
const qTmp = posixSingleQuote(tmp);
|
||||
const res = await this.sshPool.exec(
|
||||
serverId,
|
||||
`umask 077 && cat > ${qTmp} && { [ ! -e ${qDst} ] || chmod --reference=${qDst} ${qTmp} 2>/dev/null || true; } && mv -f ${qTmp} ${qDst}`,
|
||||
`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}`,
|
||||
{ sudo: true, stdin: newBuf },
|
||||
);
|
||||
if (res.exitCode !== 0) {
|
||||
|
|
@ -438,7 +618,6 @@ export class SftpService {
|
|||
}
|
||||
} catch (err) {
|
||||
if (err instanceof SftpServiceError && err.code === 'CONFLICT') throw err;
|
||||
// File does not yet exist or could not be pre-read
|
||||
}
|
||||
|
||||
const dir = path.posix.dirname(resolved);
|
||||
|
|
@ -450,7 +629,7 @@ export class SftpService {
|
|||
() => undefined,
|
||||
);
|
||||
}
|
||||
await this.renameSftpPath(sftp, tmp, resolved);
|
||||
await this.renameSftpPath(sftp, tmp, resolved, true);
|
||||
} catch (err) {
|
||||
await promisifySftpVoid((cb) => sftp.unlink(tmp, cb)).catch(() => undefined);
|
||||
throw err;
|
||||
|
|
@ -498,8 +677,10 @@ export class SftpService {
|
|||
const safeName = (resolved === '/' ? 'root' : baseName).replace(/[^A-Za-z0-9._-]/g, '_');
|
||||
const archiveFileName = `${safeName}.${resolvedFormat}`;
|
||||
|
||||
const compressCmd = resolvedFormat === 'tar.zst' ? 'zstd -T0 -c' : 'gzip -c';
|
||||
const cmd = `set -o pipefail 2>/dev/null || true; tar -C ${posixSingleQuote(parentDir)} -cf - ${posixSingleQuote(baseName)} | ${compressCmd}`;
|
||||
const osDetected = this.sshPool.getState(serverId)?.osDetected;
|
||||
const oneFsFlag = osDetected !== 'bsd' && osDetected !== 'macos' ? '--one-file-system ' : '';
|
||||
const compressCmd = resolvedFormat === 'tar.zst' ? 'zstd -T2 -c' : 'gzip -c';
|
||||
const cmd = `set -o pipefail 2>/dev/null || true; tar ${oneFsFlag}-C ${posixSingleQuote(parentDir)} -cf - -- ${posixSingleQuote(baseName)} | ${compressCmd}`;
|
||||
const handle = await this.sshPool.execStream(serverId, cmd);
|
||||
|
||||
return {
|
||||
|
|
@ -538,6 +719,9 @@ export class SftpService {
|
|||
|
||||
private async resolveRemotePath(sftp: SFTPWrapper, requestedPath?: string): Promise<string> {
|
||||
const trimmed = requestedPath?.trim() ?? '';
|
||||
if (/[\x00\r\n]/.test(trimmed)) {
|
||||
throw new SftpServiceError('INVALID_PATH', 'Control characters not permitted in path');
|
||||
}
|
||||
if (!trimmed || trimmed === '.' || trimmed === '~') {
|
||||
const home = await promisifySftp<string>((cb) => sftp.realpath('.', cb));
|
||||
return path.posix.normalize(home || '/');
|
||||
|
|
@ -557,7 +741,12 @@ export class SftpService {
|
|||
sftp: SFTPWrapper,
|
||||
fromPath: string,
|
||||
toPath: string,
|
||||
overwrite = false,
|
||||
): Promise<void> {
|
||||
if (!overwrite) {
|
||||
await promisifySftpVoid((cb) => sftp.rename(fromPath, toPath, cb));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await promisifySftpVoid((cb) => sftp.ext_openssh_rename(fromPath, toPath, cb));
|
||||
} catch {
|
||||
|
|
|
|||
149
src/server/ssh/ssh-config-import.ts
Normal file
149
src/server/ssh/ssh-config-import.ts
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
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 };
|
||||
}
|
||||
|
|
@ -7,13 +7,29 @@ import ssh2, {
|
|||
} from 'ssh2';
|
||||
import type { ServerConfig } from '../../shared/schemas/server.schema.js';
|
||||
import type {
|
||||
HostKeyAlert,
|
||||
ServerConnectionStatus,
|
||||
ServerRuntimeState,
|
||||
} from '../../shared/ws-protocol.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import type { KnownHostsService } from './known-hosts.js';
|
||||
import { buildEnvPrefix, prepareSudoExecution } from './sudo.js';
|
||||
import {
|
||||
buildEnvPrefix,
|
||||
posixSingleQuote,
|
||||
prepareSudoExecution,
|
||||
SUDO_PTY_PROMPT,
|
||||
} from './sudo.js';
|
||||
|
||||
export interface ServerTestResult {
|
||||
ok: boolean;
|
||||
latencyMs: number;
|
||||
osDetected?: 'linux' | 'bsd' | 'macos';
|
||||
hostFingerprint?: string;
|
||||
tofuRequired?: boolean;
|
||||
hostKeyMismatch?: HostKeyAlert;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ExecResult {
|
||||
stdout: string;
|
||||
|
|
@ -58,6 +74,9 @@ const DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
|
|||
export class SSHPool {
|
||||
private readonly connections = new Map<string, PooledConnection>();
|
||||
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 reconnectTimers = new Map<string, NodeJS.Timeout>();
|
||||
private readonly reconnectAttempts = new Map<string, number>();
|
||||
|
|
@ -74,6 +93,24 @@ 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 {
|
||||
this.stateListeners.add(listener);
|
||||
return () => {
|
||||
|
|
@ -132,6 +169,7 @@ export class SSHPool {
|
|||
if (visited.has(serverId)) {
|
||||
throw new Error(`ProxyJump cycle detected involving "${serverId}"`);
|
||||
}
|
||||
this.validateJumpChain(serverId);
|
||||
|
||||
const existing = this.connections.get(serverId);
|
||||
if (existing) {
|
||||
|
|
@ -145,19 +183,42 @@ export class SSHPool {
|
|||
|
||||
const nextVisited = new Set(visited);
|
||||
nextVisited.add(serverId);
|
||||
const startPoolEpoch = this.poolEpoch;
|
||||
const startSrvEpoch = this.getServerEpoch(serverId);
|
||||
|
||||
const connectPromise = this.connectServer(server, nextVisited).finally(() => {
|
||||
this.inFlight.delete(serverId);
|
||||
const connectPromise = this.connectServer(
|
||||
server,
|
||||
nextVisited,
|
||||
startPoolEpoch,
|
||||
startSrvEpoch,
|
||||
).finally(() => {
|
||||
if (this.inFlight.get(serverId) === connectPromise) {
|
||||
this.inFlight.delete(serverId);
|
||||
}
|
||||
});
|
||||
this.inFlight.set(serverId, connectPromise);
|
||||
return connectPromise;
|
||||
}
|
||||
|
||||
private getSudoPassword(server: ServerConfig): string | undefined {
|
||||
if (!server.sudoCredentialId) return undefined;
|
||||
const sudoCred = this.vaultService.getRuntimeSecret(server.sudoCredentialId);
|
||||
if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) {
|
||||
return sudoCred.password;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private prepareCommand(
|
||||
server: ServerConfig,
|
||||
command: string,
|
||||
opts: { sudo?: boolean; env?: Record<string, string>; stdin?: Buffer | string },
|
||||
): { finalCommand: string; stdinBuf?: Buffer } {
|
||||
opts: {
|
||||
sudo?: boolean;
|
||||
env?: Record<string, string>;
|
||||
stdin?: Buffer | string;
|
||||
ptyPrompt?: boolean;
|
||||
},
|
||||
): { finalCommand: string; stdinBuf?: Buffer; ptyPassword?: string } {
|
||||
const envPrefix = buildEnvPrefix(opts.env);
|
||||
let finalCommand = `${envPrefix}${command}`;
|
||||
let stdinBuf: Buffer | undefined =
|
||||
|
|
@ -168,20 +229,16 @@ export class SSHPool {
|
|||
: Buffer.from(opts.stdin);
|
||||
|
||||
if (opts.sudo) {
|
||||
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 sudoPassword = this.getSudoPassword(server);
|
||||
const prepared = prepareSudoExecution(finalCommand, {
|
||||
sudoPassword,
|
||||
stdin: stdinBuf,
|
||||
ptyPrompt: opts.ptyPrompt,
|
||||
});
|
||||
if (stdinBuf) stdinBuf.fill(0);
|
||||
finalCommand = prepared.command;
|
||||
stdinBuf = prepared.stdin;
|
||||
return { finalCommand, stdinBuf, ptyPassword: prepared.ptyPassword };
|
||||
}
|
||||
|
||||
return { finalCommand, stdinBuf };
|
||||
|
|
@ -228,7 +285,10 @@ export class SSHPool {
|
|||
throw new Error(`Unknown server "${serverId}"`);
|
||||
}
|
||||
|
||||
const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts);
|
||||
const { finalCommand, stdinBuf, ptyPassword } = this.prepareCommand(server, command, {
|
||||
...opts,
|
||||
ptyPrompt: Boolean(opts.pty),
|
||||
});
|
||||
|
||||
return new Promise<ExecStreamHandle>((resolve, reject) => {
|
||||
const execOpts = opts.pty
|
||||
|
|
@ -248,6 +308,21 @@ export class SSHPool {
|
|||
return;
|
||||
}
|
||||
|
||||
let sudoSent = false;
|
||||
let promptProbeBuf = '';
|
||||
const maybeSendPtyPassword = (chunk: Buffer) => {
|
||||
if (!ptyPassword || sudoSent) return;
|
||||
promptProbeBuf = (promptProbeBuf + chunk.toString('utf8')).slice(-256);
|
||||
if (promptProbeBuf.includes(SUDO_PTY_PROMPT)) {
|
||||
sudoSent = true;
|
||||
channel.stdin.write(`${ptyPassword}\n`);
|
||||
}
|
||||
};
|
||||
if (ptyPassword) {
|
||||
channel.on('data', maybeSendPtyPassword);
|
||||
channel.stderr?.on('data', maybeSendPtyPassword);
|
||||
}
|
||||
|
||||
let exitCode: number | null = null;
|
||||
let signal: string | undefined;
|
||||
const done = new Promise<{ exitCode: number | null; signal?: string }>(
|
||||
|
|
@ -303,10 +378,94 @@ export class SSHPool {
|
|||
throw new Error(`Unknown server "${serverId}"`);
|
||||
}
|
||||
|
||||
const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts);
|
||||
const rawStdinBuf =
|
||||
opts.stdin === undefined
|
||||
? undefined
|
||||
: typeof opts.stdin === 'string'
|
||||
? Buffer.from(opts.stdin, 'utf8')
|
||||
: Buffer.from(opts.stdin);
|
||||
|
||||
const timeoutMs = opts.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS;
|
||||
const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||
// When both sudo password and non-empty stdin exist, avoid concatenating them into sudo's stdin:
|
||||
// probe `sudo -n true` first; otherwise stage the payload in a private 0600 temp file.
|
||||
if (opts.sudo && rawStdinBuf && rawStdinBuf.length > 0) {
|
||||
const sudoPassword = this.getSudoPassword(server);
|
||||
const envPrefix = buildEnvPrefix(opts.env);
|
||||
const fullCmd = `${envPrefix}${command}`;
|
||||
const quotedCmd = posixSingleQuote(fullCmd);
|
||||
|
||||
if (sudoPassword) {
|
||||
const noPassProbe = await this.execRaw(client, serverId, 'sudo -n true', undefined, 5_000, 4096);
|
||||
if (noPassProbe.exitCode === 0) {
|
||||
try {
|
||||
return await this.execRaw(
|
||||
client,
|
||||
serverId,
|
||||
`sudo -n sh -c ${quotedCmd}`,
|
||||
rawStdinBuf,
|
||||
opts.timeoutMs,
|
||||
opts.maxBytes,
|
||||
);
|
||||
} finally {
|
||||
rawStdinBuf.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
const mk = await this.execRaw(
|
||||
client,
|
||||
serverId,
|
||||
'f=$(mktemp /tmp/.gcoord_in.XXXXXX) && chmod 600 "$f" && printf "%s" "$f"',
|
||||
undefined,
|
||||
10_000,
|
||||
1024,
|
||||
);
|
||||
const tmpFile = mk.stdout.trim();
|
||||
if (mk.exitCode === 0 && tmpFile.startsWith('/tmp/.gcoord_in.')) {
|
||||
try {
|
||||
const stage = await this.execRaw(
|
||||
client,
|
||||
serverId,
|
||||
`cat > ${posixSingleQuote(tmpFile)}`,
|
||||
rawStdinBuf,
|
||||
opts.timeoutMs,
|
||||
4096,
|
||||
);
|
||||
if (stage.exitCode === 0) {
|
||||
const pwBuf = Buffer.from(`${sudoPassword}\n`, 'utf8');
|
||||
try {
|
||||
const execCmd = `sudo -S -k -p '' sh -c ${quotedCmd} < ${posixSingleQuote(tmpFile)}`;
|
||||
return await this.execRaw(
|
||||
client,
|
||||
serverId,
|
||||
execCmd,
|
||||
pwBuf,
|
||||
opts.timeoutMs,
|
||||
opts.maxBytes,
|
||||
);
|
||||
} finally {
|
||||
pwBuf.fill(0);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
rawStdinBuf.fill(0);
|
||||
await this.execRaw(client, serverId, `rm -f -- ${posixSingleQuote(tmpFile)}`, undefined, 5_000, 1024).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rawStdinBuf?.fill(0);
|
||||
|
||||
const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts);
|
||||
return this.execRaw(client, serverId, finalCommand, stdinBuf, opts.timeoutMs, opts.maxBytes);
|
||||
}
|
||||
|
||||
private execRaw(
|
||||
client: Client,
|
||||
serverId: string,
|
||||
finalCommand: string,
|
||||
stdinBuf: Buffer | undefined,
|
||||
timeoutMs = DEFAULT_EXEC_TIMEOUT_MS,
|
||||
maxBytes = DEFAULT_MAX_BYTES,
|
||||
): Promise<ExecResult> {
|
||||
const started = Date.now();
|
||||
|
||||
return new Promise<ExecResult>((resolve, reject) => {
|
||||
|
|
@ -341,6 +500,7 @@ export class SSHPool {
|
|||
reject(new Error(`SSH exec timed out after ${timeoutMs}ms on "${serverId}"`)),
|
||||
);
|
||||
}, timeoutMs);
|
||||
timer.unref();
|
||||
|
||||
if (stdinBuf && stdinBuf.length > 0) {
|
||||
stream.stdin.write(stdinBuf);
|
||||
|
|
@ -501,6 +661,112 @@ 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> {
|
||||
this.closeServer(serverId);
|
||||
this.reconnectAttempts.delete(serverId);
|
||||
|
|
@ -542,12 +808,27 @@ export class SSHPool {
|
|||
}
|
||||
|
||||
closeServer(serverId: string): void {
|
||||
this.serverEpoch.set(serverId, this.getServerEpoch(serverId) + 1);
|
||||
this.inFlight.delete(serverId);
|
||||
const timer = this.reconnectTimers.get(serverId);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.reconnectTimers.delete(serverId);
|
||||
}
|
||||
|
||||
const pendingSet = this.pendingClients.get(serverId);
|
||||
if (pendingSet) {
|
||||
for (const c of [...pendingSet]) {
|
||||
try {
|
||||
c.end();
|
||||
c.destroy();
|
||||
} catch {
|
||||
// Ignore pending client destroy error
|
||||
}
|
||||
}
|
||||
this.pendingClients.delete(serverId);
|
||||
}
|
||||
|
||||
const conn = this.connections.get(serverId);
|
||||
if (!conn) return;
|
||||
|
||||
|
|
@ -574,7 +855,9 @@ export class SSHPool {
|
|||
}
|
||||
}
|
||||
|
||||
closeAll(reason: 'panic_lock' | 'shutdown'): void {
|
||||
closeAll(reason: 'panic_lock' | 'shutdown' | 'vault_sealed'): void {
|
||||
this.poolEpoch += 1;
|
||||
this.inFlight.clear();
|
||||
if (reason === 'shutdown') {
|
||||
this.closed = true;
|
||||
}
|
||||
|
|
@ -584,16 +867,29 @@ export class SSHPool {
|
|||
}
|
||||
this.reconnectTimers.clear();
|
||||
|
||||
for (const [id, pendingSet] of [...this.pendingClients.entries()]) {
|
||||
for (const c of [...pendingSet]) {
|
||||
try {
|
||||
c.end();
|
||||
c.destroy();
|
||||
} catch {
|
||||
// Ignore destroy error
|
||||
}
|
||||
}
|
||||
this.pendingClients.delete(id);
|
||||
}
|
||||
|
||||
for (const id of [...this.connections.keys()]) {
|
||||
this.closeServer(id);
|
||||
}
|
||||
|
||||
if (reason === 'panic_lock') {
|
||||
if (reason === 'panic_lock' || reason === 'vault_sealed') {
|
||||
const msg = reason === 'panic_lock' ? 'Panic Lock engaged' : 'Vault sealed';
|
||||
for (const server of this.configManager.listServers()) {
|
||||
this.states.set(server.id, {
|
||||
serverId: server.id,
|
||||
status: server.enabled ? 'vault_locked' : 'disabled',
|
||||
lastError: server.enabled ? 'Panic Lock engaged' : undefined,
|
||||
lastError: server.enabled ? msg : undefined,
|
||||
});
|
||||
}
|
||||
this.emitStates();
|
||||
|
|
@ -603,6 +899,8 @@ export class SSHPool {
|
|||
private async connectServer(
|
||||
server: ServerConfig,
|
||||
visited: Set<string>,
|
||||
startPoolEpoch: number,
|
||||
startSrvEpoch: number,
|
||||
): Promise<Client> {
|
||||
const cred = this.vaultService.getRuntimeSecret(server.credentialId);
|
||||
if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) {
|
||||
|
|
@ -616,6 +914,14 @@ export class SSHPool {
|
|||
let hopStream: Duplex | undefined;
|
||||
if (server.jumpHostId) {
|
||||
const bastion = await this.acquireClient(server.jumpHostId, visited);
|
||||
if (
|
||||
this.closed ||
|
||||
!this.vaultService.isRuntimeReady ||
|
||||
this.poolEpoch !== startPoolEpoch ||
|
||||
this.getServerEpoch(server.id) !== startSrvEpoch
|
||||
) {
|
||||
throw new Error('SSH connection aborted due to pool reset or Vault lock');
|
||||
}
|
||||
hopStream = await forwardOutOnClient(
|
||||
bastion,
|
||||
'127.0.0.1',
|
||||
|
|
@ -627,6 +933,20 @@ export class SSHPool {
|
|||
|
||||
const settings = this.configManager.getSettings();
|
||||
const client = new ssh2.Client();
|
||||
let setForServer = this.pendingClients.get(server.id);
|
||||
if (!setForServer) {
|
||||
setForServer = new Set();
|
||||
this.pendingClients.set(server.id, setForServer);
|
||||
}
|
||||
setForServer.add(client);
|
||||
|
||||
const untrackPending = () => {
|
||||
const s = this.pendingClients.get(server.id);
|
||||
if (s) {
|
||||
s.delete(client);
|
||||
if (s.size === 0) this.pendingClients.delete(server.id);
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<Client>((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
|
@ -634,6 +954,7 @@ export class SSHPool {
|
|||
const failConnect = (err: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
untrackPending();
|
||||
hopStream?.destroy();
|
||||
try {
|
||||
client.destroy();
|
||||
|
|
@ -641,6 +962,16 @@ export class SSHPool {
|
|||
// Ignore destroy failure
|
||||
}
|
||||
|
||||
if (
|
||||
this.closed ||
|
||||
!this.vaultService.isRuntimeReady ||
|
||||
this.poolEpoch !== startPoolEpoch ||
|
||||
this.getServerEpoch(server.id) !== startSrvEpoch
|
||||
) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
const mismatch = this.knownHosts.getPendingMismatch(server.id);
|
||||
const tofu = this.knownHosts.getPendingTofu(server.id);
|
||||
let status: ServerConnectionStatus = 'disconnected';
|
||||
|
|
@ -663,8 +994,23 @@ export class SSHPool {
|
|||
};
|
||||
|
||||
client.once('ready', () => {
|
||||
if (settled) {
|
||||
client.end();
|
||||
untrackPending();
|
||||
const invalidated =
|
||||
settled ||
|
||||
this.closed ||
|
||||
!this.vaultService.isRuntimeReady ||
|
||||
this.poolEpoch !== startPoolEpoch ||
|
||||
this.getServerEpoch(server.id) !== startSrvEpoch;
|
||||
if (invalidated) {
|
||||
settled = true;
|
||||
hopStream?.destroy();
|
||||
try {
|
||||
client.end();
|
||||
client.destroy();
|
||||
} catch {
|
||||
// Ignore close failure
|
||||
}
|
||||
reject(new Error('SSH connection aborted due to Panic Lock, seal, or reset'));
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
|
|
@ -709,6 +1055,16 @@ export class SSHPool {
|
|||
}
|
||||
});
|
||||
|
||||
if (
|
||||
this.closed ||
|
||||
!this.vaultService.isRuntimeReady ||
|
||||
this.poolEpoch !== startPoolEpoch ||
|
||||
this.getServerEpoch(server.id) !== startSrvEpoch
|
||||
) {
|
||||
failConnect(new Error('SSH connection aborted due to pool reset or Vault lock'));
|
||||
return;
|
||||
}
|
||||
|
||||
const cfg: ConnectConfig = {
|
||||
username: server.username,
|
||||
keepaliveInterval: settings.sshKeepaliveMs,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
export const SUDO_PTY_PROMPT = '[gcoord-sudo-prompt] ';
|
||||
|
||||
export function posixSingleQuote(value: string): string {
|
||||
return `'${value.replace(/'/g, "'\\''")}'`;
|
||||
}
|
||||
|
|
@ -16,13 +18,31 @@ export function buildEnvPrefix(env?: Record<string, string>): string {
|
|||
|
||||
export function prepareSudoExecution(
|
||||
command: string,
|
||||
options: { sudoPassword?: string; stdin?: Buffer | string } = {},
|
||||
): { command: string; stdin?: Buffer } {
|
||||
options: {
|
||||
sudoPassword?: string;
|
||||
stdin?: Buffer | string;
|
||||
ptyPrompt?: boolean;
|
||||
} = {},
|
||||
): { command: string; stdin?: Buffer; ptyPassword?: string } {
|
||||
const quoted = posixSingleQuote(command);
|
||||
if (options.sudoPassword !== undefined && options.sudoPassword.length > 0) {
|
||||
if (options.ptyPrompt) {
|
||||
const extraStdin =
|
||||
options.stdin === undefined
|
||||
? undefined
|
||||
: typeof options.stdin === 'string'
|
||||
? Buffer.from(options.stdin, 'utf8')
|
||||
: Buffer.from(options.stdin);
|
||||
return {
|
||||
command: `sudo -S -k -p ${posixSingleQuote(SUDO_PTY_PROMPT)} sh -c ${quoted}`,
|
||||
stdin: extraStdin,
|
||||
ptyPassword: options.sudoPassword,
|
||||
};
|
||||
}
|
||||
|
||||
const pwPrefix = Buffer.from(`${options.sudoPassword}\n`, 'utf8');
|
||||
let combined = pwPrefix;
|
||||
if (options.stdin !== undefined) {
|
||||
if (options.stdin !== undefined && options.stdin.length > 0) {
|
||||
const extra =
|
||||
typeof options.stdin === 'string'
|
||||
? Buffer.from(options.stdin, 'utf8')
|
||||
|
|
@ -31,7 +51,7 @@ export function prepareSudoExecution(
|
|||
pwPrefix.fill(0);
|
||||
}
|
||||
return {
|
||||
command: `sudo -S -p '' sh -c ${quoted}`,
|
||||
command: `sudo -S -k -p '' sh -c ${quoted}`,
|
||||
stdin: combined,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -17,6 +17,7 @@ export interface ParsedStatusResult {
|
|||
subItems: ParsedSubItem[];
|
||||
rawSummary: string;
|
||||
exitCode: number | null;
|
||||
raw?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ScannedFolderMatch {
|
||||
|
|
@ -25,10 +26,11 @@ export interface ScannedFolderMatch {
|
|||
}
|
||||
|
||||
export function globToRegExp(pattern: string): RegExp {
|
||||
const escaped = pattern
|
||||
const collapsed = pattern.slice(0, 128).replace(/\*+/g, '*');
|
||||
const escaped = collapsed
|
||||
.replace(/[.+^${}()|[\]\\]/g, '\\$&')
|
||||
.replace(/\*/g, '.*')
|
||||
.replace(/\?/g, '.');
|
||||
.replace(/\*/g, '[^/]*')
|
||||
.replace(/\?/g, '[^/]');
|
||||
return new RegExp(`^${escaped}$`);
|
||||
}
|
||||
|
||||
|
|
@ -314,6 +316,7 @@ export function parseStatusOutput(
|
|||
subItems: [],
|
||||
rawSummary: summarizeRecord(rec),
|
||||
exitCode,
|
||||
raw: rec,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
|
|
@ -327,15 +330,16 @@ export function parseStatusOutput(
|
|||
}
|
||||
|
||||
if (statusCfg.parser === 'regex') {
|
||||
const bounded = trimmed.length > 262_144 ? trimmed.slice(0, 262_144) : trimmed;
|
||||
const re = statusCfg.regexPattern ? new RegExp(statusCfg.regexPattern, 'm') : null;
|
||||
const matched = re ? re.test(trimmed) : trimmed.length > 0;
|
||||
const matched = re ? re.test(bounded) : bounded.length > 0;
|
||||
const exitOk = statusCfg.health?.healthyExitCodes
|
||||
? exitCode !== null && statusCfg.health.healthyExitCodes.includes(exitCode)
|
||||
: exitCode === null || exitCode === 0;
|
||||
return {
|
||||
health: exitOk && matched ? 'ok' : 'down',
|
||||
subItems: [],
|
||||
rawSummary: trimmed.split(/\r?\n/).slice(0, 4).join(' | '),
|
||||
rawSummary: bounded.split(/\r?\n/).slice(0, 4).join(' | '),
|
||||
exitCode,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import type { SystemAction, SystemConfig } from '../../shared/schemas/system.sch
|
|||
import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js';
|
||||
import type { WsHub } from '../api/ws-hub.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import type { RuntimeLimits } from '../config/runtime-limits.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import type { PTYManager, PtySessionInfo } from '../ssh/pty-manager.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
|
|
@ -64,19 +65,65 @@ interface ActiveStreamJob {
|
|||
bufferBytes: number;
|
||||
done: boolean;
|
||||
abort: () => void;
|
||||
timeoutTimer?: NodeJS.Timeout;
|
||||
idleTimer?: NodeJS.Timeout;
|
||||
}
|
||||
|
||||
const MAX_STREAM_REPLAY_BYTES = 128 * 1024;
|
||||
const MAX_RETAINED_DONE_STREAMS = 25;
|
||||
const MAX_DISCOVERED_ITEMS = 500;
|
||||
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
||||
const SUBITEM_SAFE_RE = /^[A-Za-z0-9._][A-Za-z0-9._:@/-]{0,127}$/;
|
||||
|
||||
export function isValidRelativeOverlayFile(fileName: string): boolean {
|
||||
const clean = fileName.trim();
|
||||
if (!clean) return false;
|
||||
if (clean.includes('/') || clean.includes('\\') || clean.includes('..')) return false;
|
||||
if (/[\s'"$;|&<>()`]/.test(clean)) return false;
|
||||
if (!clean || clean.length > 255) return false;
|
||||
if (FORBIDDEN_KEYS.has(clean)) return false;
|
||||
if (clean.startsWith('-') || clean.includes('/') || clean.includes('\\') || clean.includes('..')) {
|
||||
return false;
|
||||
}
|
||||
if (/[\x00-\x1f\x7f\s'"$;|&<>()`{}!*?[\]]/.test(clean)) return false;
|
||||
return /^[A-Za-z0-9._][A-Za-z0-9._+-]*$/.test(clean);
|
||||
}
|
||||
|
||||
function isValidSubItemName(subItem: string): boolean {
|
||||
const clean = subItem.trim();
|
||||
if (!clean || clean.startsWith('-') || clean.includes('..')) return false;
|
||||
if (/[\x00-\x1f\x7f]/.test(clean)) return false;
|
||||
return SUBITEM_SAFE_RE.test(clean);
|
||||
}
|
||||
|
||||
function isValidAbsolutePath(p: string): boolean {
|
||||
if (!p.startsWith('/') || p.includes('..')) return false;
|
||||
if (/[\x00-\x1f\x7f]/.test(p)) return false;
|
||||
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 {
|
||||
const trimmed = root.trim();
|
||||
if (trimmed === '~' || trimmed === '~/') return '"$HOME"';
|
||||
|
|
@ -85,20 +132,27 @@ function expandShellRoot(root: string): string {
|
|||
}
|
||||
|
||||
function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: string[]): string {
|
||||
const safeDepth = Math.max(1, Math.min(5, Math.floor(maxDepth)));
|
||||
const rootArgs = roots.map(expandShellRoot).join(' ');
|
||||
const casePatterns = matchFiles
|
||||
.map((p) => p.replace(/[^A-Za-z0-9._*?[\]-]/g, ''))
|
||||
.filter(Boolean)
|
||||
.join('|') || '*';
|
||||
const casePatterns =
|
||||
matchFiles
|
||||
.map((p) => p.replace(/[^A-Za-z0-9._*?-]/g, ''))
|
||||
.filter((p) => p && !p.startsWith('-'))
|
||||
.slice(0, 32)
|
||||
.join('|') || '*';
|
||||
|
||||
return [
|
||||
`TAB=$(printf '\\t'); CR=$(printf '\\r')`,
|
||||
`for r in ${rootArgs}; do`,
|
||||
` case "$r" in -*) r="./$r" ;; esac`,
|
||||
` [ -d "$r" ] || continue`,
|
||||
` find "$r" -maxdepth ${maxDepth} -type d 2>/dev/null | while IFS= read -r d; do`,
|
||||
` find "$r" -maxdepth ${safeDepth} -type d 2>/dev/null | while IFS= read -r d; do`,
|
||||
` case "$d" in *"$TAB"*|*"$CR"*) continue ;; esac`,
|
||||
` matched=0`,
|
||||
` for f in "$d"/* "$d"/.*; do`,
|
||||
` [ -f "$f" ] || continue`,
|
||||
` b=\${f##*/}`,
|
||||
` [ "$b" = "." ] || [ "$b" = ".." ] && continue`,
|
||||
` case "$b" in`,
|
||||
` ${casePatterns}) matched=1; break ;;`,
|
||||
` esac`,
|
||||
|
|
@ -116,6 +170,16 @@ function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: st
|
|||
].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 {
|
||||
private readonly cache = new Map<string, ServerSystemSnapshot>();
|
||||
private readonly streamJobs = new Map<string, ActiveStreamJob>();
|
||||
|
|
@ -128,6 +192,7 @@ export class CustomSystemsEngine {
|
|||
private readonly vaultService: VaultService,
|
||||
private readonly ptyManager: PTYManager,
|
||||
private readonly wsHub: WsHub,
|
||||
private readonly getRuntimeLimits?: () => RuntimeLimits,
|
||||
) {}
|
||||
|
||||
onHealthSnapshot(listener: (snapshot: ServerSystemSnapshot) => void): () => void {
|
||||
|
|
@ -137,6 +202,11 @@ export class CustomSystemsEngine {
|
|||
};
|
||||
}
|
||||
|
||||
getActionMeta(systemId: string, actionId: string): SystemAction | undefined {
|
||||
const sys = this.configManager.getSystem(systemId);
|
||||
return sys?.actions.find((a) => a.id === actionId);
|
||||
}
|
||||
|
||||
getStreamReplayFrames(jobId: string): ServerWsFrame[] {
|
||||
const job = this.streamJobs.get(jobId);
|
||||
return job ? [...job.frames] : [];
|
||||
|
|
@ -199,10 +269,12 @@ export class CustomSystemsEngine {
|
|||
.filter((s) => s.enabled && s.systems.some((a) => a.systemId === systemId))
|
||||
.filter((s) => !opts.serverId || s.id === opts.serverId);
|
||||
|
||||
const snapshots = await Promise.all(
|
||||
targets.map((srv) =>
|
||||
this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }),
|
||||
),
|
||||
const concurrency = Math.max(
|
||||
1,
|
||||
this.getRuntimeLimits?.().maxParallelSystemInspect ?? 2,
|
||||
);
|
||||
const snapshots = await runPool(targets, concurrency, (srv) =>
|
||||
this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }),
|
||||
);
|
||||
|
||||
return { system, snapshots };
|
||||
|
|
@ -247,7 +319,7 @@ export class CustomSystemsEngine {
|
|||
'ok',
|
||||
),
|
||||
};
|
||||
this.cache.set(cacheKey, snapshot);
|
||||
this.setCacheBounded(cacheKey, snapshot);
|
||||
this.emitHealth(snapshot);
|
||||
return snapshot;
|
||||
} catch (err) {
|
||||
|
|
@ -261,16 +333,68 @@ export class CustomSystemsEngine {
|
|||
items: [],
|
||||
systemHealth: 'down',
|
||||
};
|
||||
this.emitHealth(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: {
|
||||
serverId: string;
|
||||
systemId: string;
|
||||
actionId: string;
|
||||
itemName?: string;
|
||||
subItemName?: string;
|
||||
inputs?: Record<string, unknown>;
|
||||
}) {
|
||||
return (async () => {
|
||||
const system = this.configManager.getSystem(params.systemId);
|
||||
|
|
@ -287,7 +411,13 @@ export class CustomSystemsEngine {
|
|||
throw new Error(`Action "${params.actionId}" not found in system "${system.id}"`);
|
||||
}
|
||||
|
||||
if (params.itemName) assertSafeKey(params.itemName, 'itemName');
|
||||
if (params.subItemName && !isValidSubItemName(params.subItemName)) {
|
||||
throw new Error(`Invalid subItemName "${params.subItemName}"`);
|
||||
}
|
||||
|
||||
const resolvedParams = this.resolveParams(system, attachment.params);
|
||||
const { resolved: actionInputs } = this.resolveActionInputs(action, params.inputs);
|
||||
let item: DiscoveredSystemItem | undefined;
|
||||
|
||||
if (action.scope === 'item' || action.scope === 'subitem') {
|
||||
|
|
@ -299,8 +429,18 @@ export class CustomSystemsEngine {
|
|||
if (!item) {
|
||||
throw new Error(`Item "${params.itemName}" not found under ${server.id}/${system.id}`);
|
||||
}
|
||||
if (action.scope === 'subitem' && !params.subItemName) {
|
||||
throw new Error(`Action "${action.id}" requires subItemName`);
|
||||
if (action.scope === 'subitem') {
|
||||
if (!params.subItemName) {
|
||||
throw new Error(`Action "${action.id}" requires subItemName`);
|
||||
}
|
||||
if (
|
||||
item.status.subItems.length > 0 &&
|
||||
!item.status.subItems.some((s) => s.name === params.subItemName)
|
||||
) {
|
||||
throw new Error(
|
||||
`Sub-item "${params.subItemName}" was not discovered under "${item.name}"`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -310,13 +450,15 @@ export class CustomSystemsEngine {
|
|||
resolvedParams,
|
||||
item,
|
||||
params.subItemName,
|
||||
actionInputs,
|
||||
);
|
||||
|
||||
const substitutedCmd = substituteActionInputs(action.command, actionInputs);
|
||||
const execCmd = item?.dir
|
||||
? `cd -- ${posixSingleQuote(item.dir)} && ${action.command}`
|
||||
: action.command;
|
||||
? `cd -- ${posixSingleQuote(item.dir)} && ${substitutedCmd}`
|
||||
: substitutedCmd;
|
||||
|
||||
return { system, server, action, item, env, execCmd };
|
||||
return { system, server, action, item, env, execCmd, substitutedCmd };
|
||||
})();
|
||||
}
|
||||
|
||||
|
|
@ -326,6 +468,7 @@ export class CustomSystemsEngine {
|
|||
actionId: string;
|
||||
itemName?: string;
|
||||
subItemName?: string;
|
||||
inputs?: Record<string, unknown>;
|
||||
timeoutMs?: number;
|
||||
signal?: AbortSignal;
|
||||
onChunk?: (stream: 'stdout' | 'stderr', text: string) => void;
|
||||
|
|
@ -344,7 +487,7 @@ export class CustomSystemsEngine {
|
|||
throw new Error('Interactive PTY actions cannot run unattended in workflows');
|
||||
}
|
||||
|
||||
const timeoutMs = params.timeoutMs ?? 300_000;
|
||||
const timeoutMs = params.timeoutMs ?? (action.timeoutSec ?? 300) * 1000;
|
||||
const started = Date.now();
|
||||
const handle = await this.sshPool.execStream(server.id, execCmd, {
|
||||
env,
|
||||
|
|
@ -434,17 +577,18 @@ export class CustomSystemsEngine {
|
|||
actionId: string;
|
||||
itemName?: string;
|
||||
subItemName?: string;
|
||||
inputs?: Record<string, unknown>;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
}): Promise<ActionExecutionResult> {
|
||||
const { system, server, action, item, env, execCmd } =
|
||||
const { system, server, action, item, env, execCmd, substitutedCmd } =
|
||||
await this.resolveActionContext(params);
|
||||
|
||||
if (action.mode === 'oneshot') {
|
||||
const res = await this.sshPool.exec(server.id, execCmd, {
|
||||
env,
|
||||
sudo: action.sudo,
|
||||
timeoutMs: 120_000,
|
||||
timeoutMs: (action.timeoutSec ?? 120) * 1000,
|
||||
});
|
||||
this.invalidateCache(server.id, system.id);
|
||||
return {
|
||||
|
|
@ -460,7 +604,7 @@ export class CustomSystemsEngine {
|
|||
const session = await this.ptyManager.openSession({
|
||||
serverId: server.id,
|
||||
cwd: item?.dir,
|
||||
command: action.command,
|
||||
command: substitutedCmd,
|
||||
env,
|
||||
sudo: action.sudo,
|
||||
cols: params.cols,
|
||||
|
|
@ -471,13 +615,14 @@ export class CustomSystemsEngine {
|
|||
return { mode: 'interactive', session };
|
||||
}
|
||||
|
||||
// Stream mode
|
||||
// Stream mode with timeout & idle reaper
|
||||
const jobId = `stream-${crypto.randomBytes(6).toString('hex')}`;
|
||||
const handle = await this.sshPool.execStream(server.id, execCmd, {
|
||||
env,
|
||||
sudo: action.sudo,
|
||||
});
|
||||
|
||||
const maxReplayBytes = this.getRuntimeLimits?.().streamReplayBytes ?? 128 * 1024;
|
||||
const job: ActiveStreamJob = {
|
||||
jobId,
|
||||
serverId: server.id,
|
||||
|
|
@ -489,12 +634,23 @@ export class CustomSystemsEngine {
|
|||
};
|
||||
this.streamJobs.set(jobId, job);
|
||||
|
||||
const clearJobTimers = () => {
|
||||
if (job.timeoutTimer) {
|
||||
clearTimeout(job.timeoutTimer);
|
||||
job.timeoutTimer = undefined;
|
||||
}
|
||||
if (job.idleTimer) {
|
||||
clearTimeout(job.idleTimer);
|
||||
job.idleTimer = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const pushFrame = (stream: 'stdout' | 'stderr' | 'meta', data: string) => {
|
||||
const frame: ServerWsFrame = { type: 'stream:chunk', jobId, stream, data };
|
||||
const bytes = Buffer.byteLength(data, 'utf8');
|
||||
job.frames.push(frame);
|
||||
job.bufferBytes += bytes;
|
||||
while (job.bufferBytes > MAX_STREAM_REPLAY_BYTES && job.frames.length > 0) {
|
||||
while (job.bufferBytes > maxReplayBytes && job.frames.length > 0) {
|
||||
const dropped = job.frames.shift()!;
|
||||
if (dropped.type === 'stream:chunk') {
|
||||
job.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8');
|
||||
|
|
@ -503,6 +659,28 @@ export class CustomSystemsEngine {
|
|||
this.wsHub.broadcastChannel(WS_CHANNELS.stream(jobId), frame);
|
||||
};
|
||||
|
||||
const maxStreamMs = (action.timeoutSec ?? 600) * 1000;
|
||||
job.timeoutTimer = setTimeout(() => {
|
||||
if (job.done) return;
|
||||
pushFrame(
|
||||
'meta',
|
||||
JSON.stringify({ event: 'timeout', message: `Stream exceeded ${maxStreamMs}ms limit` }),
|
||||
);
|
||||
handle.abort();
|
||||
}, maxStreamMs);
|
||||
job.timeoutTimer.unref();
|
||||
|
||||
const bumpIdleTimer = () => {
|
||||
if (job.idleTimer) clearTimeout(job.idleTimer);
|
||||
job.idleTimer = setTimeout(() => {
|
||||
if (job.done) return;
|
||||
pushFrame('meta', JSON.stringify({ event: 'timeout', message: 'Stream idle timeout' }));
|
||||
handle.abort();
|
||||
}, Math.min(maxStreamMs, 300_000));
|
||||
job.idleTimer.unref();
|
||||
};
|
||||
bumpIdleTimer();
|
||||
|
||||
pushFrame(
|
||||
'meta',
|
||||
JSON.stringify({
|
||||
|
|
@ -516,21 +694,25 @@ export class CustomSystemsEngine {
|
|||
);
|
||||
|
||||
handle.channel.on('data', (chunk: Buffer) => {
|
||||
bumpIdleTimer();
|
||||
pushFrame('stdout', chunk.toString('utf8'));
|
||||
});
|
||||
handle.channel.stderr?.on('data', (chunk: Buffer) => {
|
||||
bumpIdleTimer();
|
||||
pushFrame('stderr', chunk.toString('utf8'));
|
||||
});
|
||||
|
||||
void handle.done
|
||||
.then(({ exitCode, signal }) => {
|
||||
job.done = true;
|
||||
clearJobTimers();
|
||||
this.invalidateCache(server.id, system.id);
|
||||
pushFrame('meta', JSON.stringify({ event: 'exit', exitCode, signal }));
|
||||
this.pruneStreamJobs();
|
||||
})
|
||||
.catch((err) => {
|
||||
job.done = true;
|
||||
clearJobTimers();
|
||||
this.invalidateCache(server.id, system.id);
|
||||
pushFrame(
|
||||
'meta',
|
||||
|
|
@ -556,10 +738,11 @@ export class CustomSystemsEngine {
|
|||
throw new Error(`Unknown server "${serverId}" or system "${systemId}"`);
|
||||
}
|
||||
|
||||
const validatedParams = this.validateAndResolveParamsStrict(system, params);
|
||||
const existing = server.systems.find((a) => a.systemId === systemId);
|
||||
const nextSystems = existing
|
||||
? server.systems.map((a) => (a.systemId === systemId ? { ...a, params } : a))
|
||||
: [...server.systems, { systemId, params, itemOverrides: {} }];
|
||||
? server.systems.map((a) => (a.systemId === systemId ? { ...a, params: validatedParams } : a))
|
||||
: [...server.systems, { systemId, params: validatedParams, itemOverrides: {} }];
|
||||
|
||||
const updated: ServerConfig = { ...server, systems: nextSystems };
|
||||
this.configManager.saveConfigText(
|
||||
|
|
@ -599,18 +782,38 @@ export class CustomSystemsEngine {
|
|||
itemName: string,
|
||||
activeFiles: string[],
|
||||
): ServerConfig {
|
||||
assertSafeKey(itemName, 'itemName');
|
||||
const system = this.configManager.getSystem(systemId);
|
||||
const server = this.configManager.getServer(serverId);
|
||||
if (!server) {
|
||||
throw new Error(`Unknown server "${serverId}"`);
|
||||
if (!system || !server) {
|
||||
throw new Error(`Unknown server "${serverId}" or system "${systemId}"`);
|
||||
}
|
||||
const cleanFiles = activeFiles.map((f) => f.trim()).filter(Boolean);
|
||||
const cleanFiles = [...new Set(activeFiles.map((f) => f.trim()).filter(Boolean))];
|
||||
if (cleanFiles.length === 0) {
|
||||
throw new Error('At least one active file must be selected');
|
||||
}
|
||||
|
||||
const cachedItem = this.cache
|
||||
.get(`${serverId}:${systemId}`)
|
||||
?.items.find((i) => i.name === itemName);
|
||||
const selectableRegexes =
|
||||
system.discovery.type === 'folder-scan'
|
||||
? (system.discovery.selectableFiles ?? system.discovery.matchFiles).map(globToRegExp)
|
||||
: [];
|
||||
|
||||
for (const file of cleanFiles) {
|
||||
if (!isValidRelativeOverlayFile(file)) {
|
||||
throw new Error(`Invalid overlay filename: "${file}"`);
|
||||
}
|
||||
if (cachedItem && cachedItem.selectableFiles.length > 0) {
|
||||
if (!cachedItem.selectableFiles.includes(file)) {
|
||||
throw new Error(`Overlay file "${file}" was not discovered for item "${itemName}"`);
|
||||
}
|
||||
} else if (selectableRegexes.length > 0) {
|
||||
if (!selectableRegexes.some((re) => re.test(file))) {
|
||||
throw new Error(`Overlay file "${file}" does not match selectableFiles patterns`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const hasAtt = server.systems.some((a) => a.systemId === systemId);
|
||||
|
|
@ -620,20 +823,20 @@ export class CustomSystemsEngine {
|
|||
|
||||
const updated: ServerConfig = {
|
||||
...server,
|
||||
systems: server.systems.map((att) =>
|
||||
att.systemId === systemId
|
||||
? {
|
||||
...att,
|
||||
itemOverrides: {
|
||||
...att.itemOverrides,
|
||||
[itemName]: {
|
||||
...(att.itemOverrides[itemName] ?? {}),
|
||||
activeFiles: cleanFiles,
|
||||
},
|
||||
},
|
||||
}
|
||||
: att,
|
||||
),
|
||||
systems: server.systems.map((att) => {
|
||||
if (att.systemId !== systemId) return att;
|
||||
const safeOverrides: Record<string, { activeFiles?: string[]; [k: string]: unknown }> =
|
||||
Object.create(null);
|
||||
for (const [k, v] of Object.entries(att.itemOverrides ?? {})) {
|
||||
if (FORBIDDEN_KEYS.has(k)) continue;
|
||||
safeOverrides[k] = v;
|
||||
}
|
||||
safeOverrides[itemName] = {
|
||||
...(Object.hasOwn(att.itemOverrides, itemName) ? att.itemOverrides[itemName] : {}),
|
||||
activeFiles: cleanFiles,
|
||||
};
|
||||
return { ...att, itemOverrides: safeOverrides };
|
||||
}),
|
||||
};
|
||||
|
||||
this.configManager.saveConfigText(
|
||||
|
|
@ -679,6 +882,8 @@ export class CustomSystemsEngine {
|
|||
for (const job of this.streamJobs.values()) {
|
||||
if (!job.done) {
|
||||
job.done = true;
|
||||
if (job.timeoutTimer) clearTimeout(job.timeoutTimer);
|
||||
if (job.idleTimer) clearTimeout(job.idleTimer);
|
||||
job.abort();
|
||||
}
|
||||
}
|
||||
|
|
@ -690,6 +895,17 @@ export class CustomSystemsEngine {
|
|||
this.cache.clear();
|
||||
}
|
||||
|
||||
private setCacheBounded(key: string, snapshot: ServerSystemSnapshot): void {
|
||||
const maxEntries = Math.max(8, this.getRuntimeLimits?.().maxSystemCacheEntries ?? 64);
|
||||
if (this.cache.has(key)) this.cache.delete(key);
|
||||
this.cache.set(key, snapshot);
|
||||
while (this.cache.size > maxEntries) {
|
||||
const oldestKey = this.cache.keys().next().value;
|
||||
if (!oldestKey) break;
|
||||
this.cache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
|
||||
private async discoverAndInspectItems(
|
||||
server: ServerConfig,
|
||||
system: SystemConfig,
|
||||
|
|
@ -697,6 +913,10 @@ export class CustomSystemsEngine {
|
|||
params: Record<string, unknown>,
|
||||
): Promise<DiscoveredSystemItem[]> {
|
||||
const baseEnv = this.buildExecutionEnv(server.id, system.id, params);
|
||||
const concurrency = Math.max(
|
||||
1,
|
||||
this.getRuntimeLimits?.().maxParallelSystemInspect ?? 2,
|
||||
);
|
||||
|
||||
if (system.discovery.type === 'folder-scan') {
|
||||
const rawRoots = params[system.discovery.rootsParam];
|
||||
|
|
@ -713,7 +933,7 @@ export class CustomSystemsEngine {
|
|||
system.discovery.matchFiles,
|
||||
);
|
||||
const scanRes = await this.sshPool.exec(server.id, script, { env: baseEnv });
|
||||
const rawMatches = parseFolderScanOutput(scanRes.stdout);
|
||||
const rawMatches = parseFolderScanOutput(scanRes.stdout).slice(0, MAX_DISCOVERED_ITEMS);
|
||||
|
||||
const matchRegexes = system.discovery.matchFiles.map(globToRegExp);
|
||||
const selectableRegexes = (
|
||||
|
|
@ -724,33 +944,45 @@ export class CustomSystemsEngine {
|
|||
.map(globToRegExp);
|
||||
|
||||
const usedNames = new Map<string, number>();
|
||||
const items: DiscoveredSystemItem[] = [];
|
||||
const draftItems: DiscoveredSystemItem[] = [];
|
||||
|
||||
for (const m of rawMatches) {
|
||||
const matchedFiles = m.files.filter((f) => matchRegexes.some((re) => re.test(f)));
|
||||
if (/[\x00-\x1f\x7f]/.test(m.dir)) continue;
|
||||
const safeFiles = m.files.filter(
|
||||
(f) => !/[\x00-\x1f\x7f]/.test(f) && !f.startsWith('-'),
|
||||
);
|
||||
const matchedFiles = safeFiles.filter((f) => matchRegexes.some((re) => re.test(f)));
|
||||
if (matchedFiles.length === 0) continue;
|
||||
|
||||
let baseName = path.posix.basename(m.dir) || 'root';
|
||||
if (FORBIDDEN_KEYS.has(baseName)) baseName = `item-${baseName}`;
|
||||
const seenCount = (usedNames.get(baseName) ?? 0) + 1;
|
||||
usedNames.set(baseName, seenCount);
|
||||
if (seenCount > 1) {
|
||||
baseName = `${baseName}-${seenCount}`;
|
||||
}
|
||||
|
||||
const selectableFiles = m.files.filter((f) => selectableRegexes.some((re) => re.test(f)));
|
||||
const editableFiles = m.files
|
||||
const selectableFiles = safeFiles.filter(
|
||||
(f) => isValidRelativeOverlayFile(f) && selectableRegexes.some((re) => re.test(f)),
|
||||
);
|
||||
const editableFiles = safeFiles
|
||||
.filter((f) => editableRegexes.some((re) => re.test(f)))
|
||||
.map((f) => path.posix.join(m.dir, f));
|
||||
|
||||
const overrideFiles = attachment.itemOverrides[baseName]?.activeFiles?.filter((f) =>
|
||||
isValidRelativeOverlayFile(f),
|
||||
const overrideRaw = Object.hasOwn(attachment.itemOverrides, baseName)
|
||||
? attachment.itemOverrides[baseName]?.activeFiles
|
||||
: undefined;
|
||||
const overrideFiles = overrideRaw?.filter(
|
||||
(f) =>
|
||||
isValidRelativeOverlayFile(f) &&
|
||||
(selectableFiles.length === 0 || selectableFiles.includes(f)),
|
||||
);
|
||||
const activeFiles =
|
||||
overrideFiles && overrideFiles.length > 0
|
||||
? overrideFiles
|
||||
: [matchedFiles[0]!];
|
||||
|
||||
const draftItem: DiscoveredSystemItem = {
|
||||
draftItems.push({
|
||||
name: baseName,
|
||||
dir: m.dir,
|
||||
activeFiles,
|
||||
|
|
@ -762,12 +994,14 @@ export class CustomSystemsEngine {
|
|||
rawSummary: '',
|
||||
exitCode: null,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
await runPool(draftItems, concurrency, async (draftItem) => {
|
||||
const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem);
|
||||
const statusRes = await this.sshPool.exec(
|
||||
server.id,
|
||||
`cd -- ${posixSingleQuote(m.dir)} && ${system.status.command}`,
|
||||
`cd -- ${posixSingleQuote(draftItem.dir!)} && ${system.status.command}`,
|
||||
{ env: itemEnv },
|
||||
);
|
||||
draftItem.status = parseStatusOutput(
|
||||
|
|
@ -776,32 +1010,33 @@ export class CustomSystemsEngine {
|
|||
statusRes.exitCode,
|
||||
system.status,
|
||||
);
|
||||
items.push(draftItem);
|
||||
}
|
||||
});
|
||||
|
||||
return items;
|
||||
return draftItems;
|
||||
}
|
||||
|
||||
// command discovery
|
||||
const discRes = await this.sshPool.exec(server.id, system.discovery.command, {
|
||||
env: baseEnv,
|
||||
});
|
||||
const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser);
|
||||
const items: DiscoveredSystemItem[] = [];
|
||||
const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser)
|
||||
.filter((n) => !FORBIDDEN_KEYS.has(n) && !/[\x00-\x1f\x7f]/.test(n))
|
||||
.slice(0, MAX_DISCOVERED_ITEMS);
|
||||
|
||||
for (const itemName of names) {
|
||||
const draftItem: DiscoveredSystemItem = {
|
||||
name: itemName,
|
||||
activeFiles: [],
|
||||
selectableFiles: [],
|
||||
editableFiles: [],
|
||||
status: {
|
||||
health: 'unknown',
|
||||
subItems: [],
|
||||
rawSummary: '',
|
||||
exitCode: null,
|
||||
},
|
||||
};
|
||||
const draftItems: DiscoveredSystemItem[] = names.map((itemName) => ({
|
||||
name: itemName,
|
||||
activeFiles: [],
|
||||
selectableFiles: [],
|
||||
editableFiles: [],
|
||||
status: {
|
||||
health: 'unknown',
|
||||
subItems: [],
|
||||
rawSummary: '',
|
||||
exitCode: null,
|
||||
},
|
||||
}));
|
||||
|
||||
await runPool(draftItems, concurrency, async (draftItem) => {
|
||||
const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem);
|
||||
const statusRes = await this.sshPool.exec(server.id, system.status.command, {
|
||||
env: itemEnv,
|
||||
|
|
@ -812,25 +1047,88 @@ export class CustomSystemsEngine {
|
|||
statusRes.exitCode,
|
||||
system.status,
|
||||
);
|
||||
items.push(draftItem);
|
||||
}
|
||||
|
||||
return items;
|
||||
// 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) {
|
||||
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(
|
||||
system: SystemConfig,
|
||||
supplied: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = {};
|
||||
const out: Record<string, unknown> = Object.create(null);
|
||||
for (const def of system.params) {
|
||||
if (supplied[def.name] !== undefined) {
|
||||
if (FORBIDDEN_KEYS.has(def.name)) continue;
|
||||
if (Object.hasOwn(supplied, def.name) && supplied[def.name] !== undefined) {
|
||||
out[def.name] = supplied[def.name];
|
||||
} else if (def.default !== undefined) {
|
||||
out[def.name] = structuredClone(def.default);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
return { ...out };
|
||||
}
|
||||
|
||||
private buildExecutionEnv(
|
||||
|
|
@ -839,6 +1137,7 @@ export class CustomSystemsEngine {
|
|||
params: Record<string, unknown>,
|
||||
item?: DiscoveredSystemItem,
|
||||
subItem?: string,
|
||||
actionInputs?: Record<string, string>,
|
||||
): Record<string, string> {
|
||||
const env: Record<string, string> = {
|
||||
GCOORD_SERVER_ID: serverId,
|
||||
|
|
@ -846,10 +1145,19 @@ export class CustomSystemsEngine {
|
|||
};
|
||||
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
if (FORBIDDEN_KEYS.has(k)) continue;
|
||||
const envKey = `GCOORD_PARAM_${k.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`;
|
||||
env[envKey] = Array.isArray(v) ? v.map((x) => String(x)).join('\n') : String(v ?? '');
|
||||
}
|
||||
|
||||
if (actionInputs) {
|
||||
for (const [k, v] of Object.entries(actionInputs)) {
|
||||
if (FORBIDDEN_KEYS.has(k)) continue;
|
||||
const envKey = `GCOORD_INPUT_${k.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`;
|
||||
env[envKey] = v;
|
||||
}
|
||||
}
|
||||
|
||||
if (item) {
|
||||
env.GCOORD_ITEM_NAME = item.name;
|
||||
if (item.dir) {
|
||||
|
|
|
|||
|
|
@ -5,18 +5,74 @@ export interface DiffLine {
|
|||
text: string;
|
||||
}
|
||||
|
||||
export type CollapsedDiffEntry =
|
||||
| DiffLine
|
||||
| { type: 'hunk'; omittedCount: number; text: string };
|
||||
|
||||
export interface DiffResult {
|
||||
lines: DiffLine[];
|
||||
collapsedLines: CollapsedDiffEntry[];
|
||||
unified: string;
|
||||
additions: number;
|
||||
deletions: number;
|
||||
}
|
||||
|
||||
export function collapseDiffHunks(lines: DiffLine[], contextLines = 3): CollapsedDiffEntry[] {
|
||||
const ctx = Math.max(0, Math.floor(contextLines));
|
||||
const keep = new Uint8Array(lines.length);
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (lines[i]!.type !== 'equal') {
|
||||
const start = Math.max(0, i - ctx);
|
||||
const end = Math.min(lines.length - 1, i + ctx);
|
||||
for (let k = start; k <= end; k++) keep[k] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (!keep.some((v) => v === 1)) {
|
||||
return lines.length <= ctx * 2 + 2
|
||||
? [...lines]
|
||||
: [
|
||||
...lines.slice(0, ctx),
|
||||
{
|
||||
type: 'hunk',
|
||||
omittedCount: lines.length - ctx,
|
||||
text: `... ${lines.length - ctx} unchanged lines omitted ...`,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const out: CollapsedDiffEntry[] = [];
|
||||
let i = 0;
|
||||
while (i < lines.length) {
|
||||
if (keep[i]) {
|
||||
out.push(lines[i]!);
|
||||
i++;
|
||||
} else {
|
||||
let j = i;
|
||||
while (j < lines.length && !keep[j]) j++;
|
||||
const count = j - i;
|
||||
if (count === 1) {
|
||||
out.push(lines[i]!);
|
||||
} else {
|
||||
out.push({
|
||||
type: 'hunk',
|
||||
omittedCount: count,
|
||||
text: `... ${count} unchanged lines omitted ...`,
|
||||
});
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function computeLineDiff(
|
||||
oldText: string,
|
||||
newText: string,
|
||||
oldLabel = 'revision',
|
||||
newLabel = 'current',
|
||||
opts: { contextLines?: number } = {},
|
||||
): DiffResult {
|
||||
const a = oldText.replace(/\r\n/g, '\n').split('\n');
|
||||
const b = newText.replace(/\r\n/g, '\n').split('\n');
|
||||
|
|
@ -75,21 +131,25 @@ export function computeLineDiff(
|
|||
|
||||
let additions = 0;
|
||||
let deletions = 0;
|
||||
const collapsedLines = collapseDiffHunks(lines, opts.contextLines ?? 3);
|
||||
const body: string[] = [`--- ${oldLabel}`, `+++ ${newLabel}`];
|
||||
for (const line of lines) {
|
||||
if (line.type === 'add') {
|
||||
for (const entry of collapsedLines) {
|
||||
if (entry.type === 'hunk') {
|
||||
body.push(`@@ ${entry.text} @@`);
|
||||
} else if (entry.type === 'add') {
|
||||
additions++;
|
||||
body.push(`+${line.text}`);
|
||||
} else if (line.type === 'del') {
|
||||
body.push(`+${entry.text}`);
|
||||
} else if (entry.type === 'del') {
|
||||
deletions++;
|
||||
body.push(`-${line.text}`);
|
||||
body.push(`-${entry.text}`);
|
||||
} else {
|
||||
body.push(` ${line.text}`);
|
||||
body.push(` ${entry.text}`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
lines,
|
||||
collapsedLines,
|
||||
unified: body.join('\n'),
|
||||
additions,
|
||||
deletions,
|
||||
|
|
|
|||
|
|
@ -1,16 +1,38 @@
|
|||
import { z } from 'zod';
|
||||
import { CronExpressionSchema, EntityIdSchema } from './common.js';
|
||||
import {
|
||||
CronExpressionSchema,
|
||||
EntityIdSchema,
|
||||
HttpUrlSchema,
|
||||
IanaTimezoneSchema,
|
||||
} from './common.js';
|
||||
|
||||
export const AlertChannelSchema = z.object({
|
||||
id: EntityIdSchema,
|
||||
name: z.string().min(1).max(120),
|
||||
type: z.enum(['discord', 'telegram', 'ntfy', 'generic']),
|
||||
url: z.string().url().optional(),
|
||||
secretRef: EntityIdSchema,
|
||||
chatId: z.string().optional(),
|
||||
topic: z.string().optional(),
|
||||
enabled: z.boolean().default(true),
|
||||
});
|
||||
export const AlertChannelSchema = z
|
||||
.object({
|
||||
id: EntityIdSchema,
|
||||
name: z.string().min(1).max(120),
|
||||
type: z.enum(['discord', 'telegram', 'ntfy', 'generic']),
|
||||
url: HttpUrlSchema.optional(),
|
||||
secretRef: EntityIdSchema.optional(),
|
||||
chatId: z.string().optional(),
|
||||
topic: z.string().optional(),
|
||||
enabled: z.boolean().default(true),
|
||||
})
|
||||
.superRefine((ch, ctx) => {
|
||||
if (!ch.url && !ch.secretRef) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['secretRef'],
|
||||
message: 'Alert channel must specify either url or secretRef',
|
||||
});
|
||||
}
|
||||
if ((ch.type === 'discord' || ch.type === 'telegram') && !ch.secretRef && !ch.url) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['secretRef'],
|
||||
message: `${ch.type} channel requires secretRef or url`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const AlertRuleTargetSchema = z.object({
|
||||
serverId: EntityIdSchema.optional(),
|
||||
|
|
@ -30,6 +52,20 @@ const AlertRuleBase = {
|
|||
enabled: z.boolean().default(true),
|
||||
};
|
||||
|
||||
export const SecurityEventKindSchema = z.enum([
|
||||
'login_burst',
|
||||
'new_ip_login',
|
||||
'panic_lock',
|
||||
'key_rotation',
|
||||
'backup_restore',
|
||||
'auth.lockout',
|
||||
'auth.totp_replay',
|
||||
'auth.recovery_code_used',
|
||||
'auth.session_idle_expired',
|
||||
'ssh.host_key_mismatch',
|
||||
'vault.panic_lock',
|
||||
]);
|
||||
|
||||
export const AlertRuleSchema = z.discriminatedUnion('kind', [
|
||||
z.object({
|
||||
...AlertRuleBase,
|
||||
|
|
@ -60,26 +96,51 @@ export const AlertRuleSchema = z.discriminatedUnion('kind', [
|
|||
systemId: EntityIdSchema,
|
||||
item: z.string().optional(),
|
||||
}),
|
||||
z.object({
|
||||
...AlertRuleBase,
|
||||
kind: z.literal('security-event'),
|
||||
events: z.array(SecurityEventKindSchema).min(1),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const MaintenanceWindowSchema = z.object({
|
||||
id: EntityIdSchema,
|
||||
name: z.string().min(1).max(120),
|
||||
cron: CronExpressionSchema,
|
||||
timezone: z.string().min(1).default('UTC'),
|
||||
timezone: IanaTimezoneSchema.default('UTC'),
|
||||
durationMinutes: z.number().int().min(1).max(1440),
|
||||
target: AlertRuleTargetSchema.default({ all: true }),
|
||||
enabled: z.boolean().default(true),
|
||||
});
|
||||
|
||||
export const AlertsFileSchema = z.object({
|
||||
version: z.literal(1).default(1),
|
||||
channels: z.array(AlertChannelSchema).default([]),
|
||||
rules: z.array(AlertRuleSchema).default([]),
|
||||
maintenanceWindows: z.array(MaintenanceWindowSchema).default([]),
|
||||
});
|
||||
export const AlertsFileSchema = z
|
||||
.object({
|
||||
version: z.literal(1).default(1),
|
||||
channels: z.array(AlertChannelSchema).default([]),
|
||||
rules: z.array(AlertRuleSchema).default([]),
|
||||
maintenanceWindows: z.array(MaintenanceWindowSchema).default([]),
|
||||
})
|
||||
.superRefine((doc, ctx) => {
|
||||
const checkDupes = (items: Array<{ id: string }>, arrPath: string) => {
|
||||
const seen = new Set<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 AlertRule = z.infer<typeof AlertRuleSchema>;
|
||||
export type SecurityEventKind = z.infer<typeof SecurityEventKindSchema>;
|
||||
export type MaintenanceWindow = z.infer<typeof MaintenanceWindowSchema>;
|
||||
export type AlertsFile = z.infer<typeof AlertsFileSchema>;
|
||||
|
|
|
|||
|
|
@ -5,16 +5,44 @@ export const EntityIdSchema = z
|
|||
.string()
|
||||
.min(1, 'ID must not be empty')
|
||||
.max(64, 'ID must be at most 64 characters')
|
||||
.regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/, 'ID must start with alphanumeric and contain only [a-zA-Z0-9._-]');
|
||||
.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 HttpUrlSchema = z
|
||||
.string()
|
||||
.url()
|
||||
.refine((u) => /^https?:\/\//i.test(u), 'URL must use http:// or https://');
|
||||
|
||||
export const IanaTimezoneSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(64)
|
||||
.refine((tz) => {
|
||||
try {
|
||||
Intl.DateTimeFormat(undefined, { timeZone: tz });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, 'Invalid IANA timezone');
|
||||
|
||||
export const CronExpressionSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.superRefine((expr, ctx) => {
|
||||
const trimmed = expr.trim();
|
||||
const fields = trimmed.split(/\s+/);
|
||||
if (fields.length !== 5) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Cron expression must have exactly 5 fields (minute hour day month weekday)',
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
new CronPattern(expr);
|
||||
new CronPattern(trimmed);
|
||||
} catch (err) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
|
|
@ -25,7 +53,7 @@ export const CronExpressionSchema = z
|
|||
|
||||
export const InputDefSchema = z.object({
|
||||
name: EntityIdSchema,
|
||||
type: z.enum(['string', 'number', 'boolean', 'server', 'select']).default('string'),
|
||||
type: z.enum(['string', 'number', 'boolean', 'server', 'select', 'secret']).default('string'),
|
||||
label: z.string().min(1).optional(),
|
||||
description: z.string().optional(),
|
||||
required: z.boolean().default(false),
|
||||
|
|
|
|||
|
|
@ -1,22 +1,42 @@
|
|||
import { z } from 'zod';
|
||||
import { EntityIdSchema, PortSchema } from './common.js';
|
||||
import { EntityIdSchema, HttpUrlSchema, PortSchema } from './common.js';
|
||||
|
||||
export const SafeHostSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(255)
|
||||
.regex(
|
||||
/^[A-Za-z0-9\[][A-Za-z0-9._:\[\]-]*$/,
|
||||
'Host cannot start with "-" or contain whitespace, "@", or control characters',
|
||||
);
|
||||
|
||||
export const SafeUsernameSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(64)
|
||||
.regex(
|
||||
/^[A-Za-z0-9_][A-Za-z0-9._-]*$/,
|
||||
'Username cannot start with "-" or contain whitespace, "@", or ":"',
|
||||
);
|
||||
|
||||
export const HttpProbeSchema = z.object({
|
||||
id: EntityIdSchema,
|
||||
type: z.literal('http'),
|
||||
url: z.string().url(),
|
||||
url: HttpUrlSchema,
|
||||
from: z.enum(['hub', 'target']).default('target'),
|
||||
intervalSec: z.number().int().min(5).max(86400).default(30),
|
||||
timeoutMs: z.number().int().min(200).max(60000).default(5000),
|
||||
expectedStatus: z.number().int().min(100).max(599).default(200),
|
||||
bodyIncludes: z.string().optional(),
|
||||
tlsRejectUnauthorized: z.boolean().default(true),
|
||||
tlsCheckExpiryDays: z.number().int().min(1).max(365).optional(),
|
||||
enabled: z.boolean().default(true),
|
||||
});
|
||||
|
||||
export const TcpProbeSchema = z.object({
|
||||
id: EntityIdSchema,
|
||||
type: z.literal('tcp'),
|
||||
host: z.string().min(1).default('127.0.0.1'),
|
||||
host: SafeHostSchema.default('127.0.0.1'),
|
||||
port: PortSchema,
|
||||
from: z.enum(['hub', 'target']).default('target'),
|
||||
intervalSec: z.number().int().min(5).max(86400).default(30),
|
||||
|
|
@ -40,36 +60,71 @@ export const ServerSystemAttachmentSchema = z.object({
|
|||
.default({}),
|
||||
});
|
||||
|
||||
export const ServerTunnelSchema = z.object({
|
||||
id: EntityIdSchema,
|
||||
name: z.string().min(1).max(120),
|
||||
mode: z.enum(['http-proxy', 'local-tcp', 'remote-tcp']),
|
||||
bindHost: z.string().min(1).optional(),
|
||||
bindPort: PortSchema.optional(),
|
||||
targetHost: z.string().min(1).default('127.0.0.1'),
|
||||
targetPort: PortSchema,
|
||||
autoStart: z.boolean().default(false),
|
||||
});
|
||||
export const ServerTunnelSchema = z
|
||||
.object({
|
||||
id: EntityIdSchema,
|
||||
name: z.string().min(1).max(120),
|
||||
mode: z.enum(['http-proxy', 'local-tcp', 'remote-tcp', 'socks5']),
|
||||
bindHost: SafeHostSchema.optional(),
|
||||
bindPort: PortSchema.optional(),
|
||||
targetHost: SafeHostSchema.default('127.0.0.1'),
|
||||
targetPort: z.number().int().min(0).max(65535).default(0),
|
||||
targetProtocol: z.enum(['http', 'https']).default('http'),
|
||||
tlsRejectUnauthorized: z.boolean().default(true),
|
||||
tlsServerName: z.string().max(255).optional(),
|
||||
ttlSec: z.number().int().min(60).max(86400).optional(),
|
||||
autoStart: z.boolean().default(false),
|
||||
})
|
||||
.superRefine((tunnel, ctx) => {
|
||||
if (tunnel.mode !== 'socks5' && tunnel.targetPort < 1) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['targetPort'],
|
||||
message: 'targetPort must be between 1 and 65535',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const ServerConfigSchema = z.object({
|
||||
id: EntityIdSchema,
|
||||
name: z.string().min(1).max(120),
|
||||
host: z.string().min(1),
|
||||
port: PortSchema.default(22),
|
||||
username: z.string().min(1).max(64),
|
||||
credentialId: EntityIdSchema,
|
||||
jumpHostId: EntityIdSchema.optional(),
|
||||
sudoCredentialId: EntityIdSchema.optional(),
|
||||
hostKeyFingerprint: z.string().min(1).optional(),
|
||||
tags: z.array(z.string().min(1)).default([]),
|
||||
osHint: z.enum(['auto', 'linux', 'bsd', 'macos']).default('auto'),
|
||||
pollIntervalSec: z.number().int().min(2).max(3600).default(10),
|
||||
diskMountFilter: z.array(z.string().min(1)).optional(),
|
||||
probes: z.array(ServerProbeSchema).default([]),
|
||||
systems: z.array(ServerSystemAttachmentSchema).default([]),
|
||||
tunnels: z.array(ServerTunnelSchema).default([]),
|
||||
enabled: z.boolean().default(true),
|
||||
});
|
||||
export const ServerConfigSchema = z
|
||||
.object({
|
||||
id: EntityIdSchema,
|
||||
name: z.string().min(1).max(120),
|
||||
host: SafeHostSchema,
|
||||
port: PortSchema.default(22),
|
||||
username: SafeUsernameSchema,
|
||||
credentialId: EntityIdSchema,
|
||||
jumpHostId: EntityIdSchema.optional(),
|
||||
sudoCredentialId: EntityIdSchema.optional(),
|
||||
hostKeyFingerprint: z.string().min(1).optional(),
|
||||
tags: z.array(z.string().min(1)).default([]),
|
||||
osHint: z.enum(['auto', 'linux', 'bsd', 'macos']).default('auto'),
|
||||
pollIntervalSec: z.number().int().min(2).max(3600).default(10),
|
||||
diskMountFilter: z.array(z.string().min(1)).optional(),
|
||||
probes: z.array(ServerProbeSchema).default([]),
|
||||
systems: z.array(ServerSystemAttachmentSchema).default([]),
|
||||
tunnels: z.array(ServerTunnelSchema).default([]),
|
||||
enabled: z.boolean().default(true),
|
||||
})
|
||||
.superRefine((srv, ctx) => {
|
||||
const checkDupes = (items: Array<{ id?: string; systemId?: string }>, key: 'id' | 'systemId', arrPath: string) => {
|
||||
const seen = new Set<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 ServerSystemAttachment = z.infer<typeof ServerSystemAttachmentSchema>;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { EntityIdSchema } from './common.js';
|
||||
import { EntityIdSchema, HttpUrlSchema, IanaTimezoneSchema } from './common.js';
|
||||
|
||||
export const ThemeIdSchema = z.enum([
|
||||
'phosphor-green',
|
||||
|
|
@ -14,10 +14,13 @@ export const ThemeIdSchema = z.enum([
|
|||
|
||||
export const THEME_IDS = ThemeIdSchema.options;
|
||||
|
||||
export const ThrottleModeSchema = z.enum(['low-resource', 'balanced', 'unthrottled']);
|
||||
|
||||
export const StepUpPolicySchema = z.enum([
|
||||
'off',
|
||||
'every-action',
|
||||
'5m',
|
||||
'15m',
|
||||
'1h',
|
||||
'24h',
|
||||
'session',
|
||||
|
|
@ -29,11 +32,15 @@ export const SecuritySettingsSchema = z.object({
|
|||
requireTotpOnLogin: z.boolean().default(true),
|
||||
passwordMode: z.enum(['any', 'all']).default('any'),
|
||||
totpMode: z.enum(['any', 'all']).default('any'),
|
||||
stepUpPolicy: StepUpPolicySchema.default('1h'),
|
||||
stepUpPolicy: StepUpPolicySchema.default('15m'),
|
||||
stepUpMethod: StepUpMethodSchema.default('totp'),
|
||||
elevateOnLogin: z.boolean().default(true),
|
||||
elevateOnLogin: z.boolean().default(false),
|
||||
keepElevationOnSafeMode: z.boolean().default(true),
|
||||
enableEmergencySecretsBackup: z.boolean().default(true),
|
||||
enableEmergencySecretsBackup: z.boolean().default(false),
|
||||
allowSameOriginProxy: z.boolean().default(false),
|
||||
egressAllowedCidrs: z.array(z.string().min(1).max(64)).max(64).default([]),
|
||||
sessionTtlHours: z.number().int().min(1).max(720).default(168),
|
||||
sessionIdleTimeoutMin: z.number().int().min(0).max(10080).default(60),
|
||||
});
|
||||
|
||||
export const SettingsSchema = z.object({
|
||||
|
|
@ -42,29 +49,69 @@ export const SettingsSchema = z.object({
|
|||
defaultMobileSafeMode: z.boolean().default(true),
|
||||
rawRetentionHours: z.number().int().min(1).max(720).default(48),
|
||||
rollupRetentionDays: z.number().int().min(1).max(3650).default(30),
|
||||
auditRetentionDays: z.number().int().min(1).max(3650).default(90),
|
||||
workflowRunRetentionDays: z.number().int().min(1).max(3650).default(30),
|
||||
alertEventRetentionDays: z.number().int().min(1).max(3650).default(30),
|
||||
configRevisionLimit: z.number().int().min(5).max(500).default(50),
|
||||
ptyScrollbackBytes: z.number().int().min(16384).max(4194304).default(524288),
|
||||
ptyScrollbackBytes: z.number().int().min(16384).max(2097152).default(262144),
|
||||
ptyIdleTtlSec: z.number().int().min(60).max(604800).default(43200),
|
||||
sshKeepaliveMs: z.number().int().min(5000).max(120000).default(15000),
|
||||
sshReadyTimeoutMs: z.number().int().min(3000).max(120000).default(15000),
|
||||
runtime: z
|
||||
.object({
|
||||
throttleMode: ThrottleModeSchema.default('low-resource'),
|
||||
})
|
||||
.default({ throttleMode: 'low-resource' }),
|
||||
scheduledBackup: z
|
||||
.object({
|
||||
enabled: z.boolean().default(false),
|
||||
cron: z.string().min(1).default('0 3 * * *'),
|
||||
timezone: IanaTimezoneSchema.default('UTC'),
|
||||
destination: z.enum(['local', 'sftp']).default('local'),
|
||||
localDir: z.string().min(1).max(128).default('backups'),
|
||||
remoteServerId: EntityIdSchema.optional(),
|
||||
remotePath: z.string().min(1).max(256).optional(),
|
||||
retentionCount: z.number().int().min(1).max(100).default(7),
|
||||
passphraseSecretRef: EntityIdSchema.optional(),
|
||||
})
|
||||
.default({
|
||||
enabled: false,
|
||||
cron: '0 3 * * *',
|
||||
timezone: 'UTC',
|
||||
destination: 'local',
|
||||
localDir: 'backups',
|
||||
retentionCount: 7,
|
||||
}),
|
||||
metrics: z
|
||||
.object({
|
||||
prometheusEnabled: z.boolean().default(false),
|
||||
prometheusSecretRef: EntityIdSchema.optional(),
|
||||
prometheusTokenHash: z.string().regex(/^[a-f0-9]{64}$/).optional(),
|
||||
})
|
||||
.default({ prometheusEnabled: false }),
|
||||
security: SecuritySettingsSchema.default({}),
|
||||
ai: z
|
||||
.object({
|
||||
enabled: z.boolean().default(false),
|
||||
baseUrl: z.string().url().default('http://127.0.0.1:11434'),
|
||||
baseUrl: HttpUrlSchema.default('http://127.0.0.1:11434'),
|
||||
model: z.string().min(1).default('qwen2.5-coder:7b'),
|
||||
secretRef: EntityIdSchema.optional(),
|
||||
maxContextChars: z.number().int().min(1000).max(128000).default(16000),
|
||||
timeoutSec: z.number().int().min(5).max(300).default(90),
|
||||
maxTokens: z.number().int().min(64).max(32768).default(2048),
|
||||
})
|
||||
.default({
|
||||
enabled: false,
|
||||
baseUrl: 'http://127.0.0.1:11434',
|
||||
model: 'qwen2.5-coder:7b',
|
||||
maxContextChars: 16000,
|
||||
timeoutSec: 90,
|
||||
maxTokens: 2048,
|
||||
}),
|
||||
});
|
||||
|
||||
export type ThemeId = z.infer<typeof ThemeIdSchema>;
|
||||
export type ThrottleMode = z.infer<typeof ThrottleModeSchema>;
|
||||
export type StepUpPolicy = z.infer<typeof StepUpPolicySchema>;
|
||||
export type StepUpMethod = z.infer<typeof StepUpMethodSchema>;
|
||||
export type SecuritySettings = z.infer<typeof SecuritySettingsSchema>;
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ export const SnippetSchema = z.object({
|
|||
description: z.string().optional(),
|
||||
command: z.string().min(1),
|
||||
tags: z.array(z.string().min(1)).default([]),
|
||||
osFilter: z.array(z.enum(['linux', 'bsd', 'macos'])).optional(),
|
||||
inputs: z.array(InputDefSchema).default([]),
|
||||
sudo: z.boolean().default(false),
|
||||
confirm: z.boolean().default(false),
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { EntityIdSchema } from './common.js';
|
||||
import { EntityIdSchema, InputDefSchema } from './common.js';
|
||||
|
||||
export const SystemParamDefSchema = z.object({
|
||||
name: EntityIdSchema,
|
||||
|
|
@ -39,7 +39,19 @@ export const SystemStatusSchema = z.object({
|
|||
command: z.string().min(1),
|
||||
parser: z.enum(['json-lines', 'json', 'lines', 'regex', 'exit-code']),
|
||||
subItemField: z.string().min(1).optional(),
|
||||
regexPattern: z.string().min(1).optional(),
|
||||
regexPattern: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(512)
|
||||
.refine((pat) => {
|
||||
try {
|
||||
new RegExp(pat);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, 'Invalid regular expression pattern')
|
||||
.optional(),
|
||||
health: SystemHealthRuleSchema.optional(),
|
||||
});
|
||||
|
||||
|
|
@ -49,22 +61,61 @@ export const SystemActionSchema = z.object({
|
|||
scope: z.enum(['system', 'item', 'subitem']),
|
||||
mode: z.enum(['oneshot', 'stream', 'interactive']),
|
||||
command: z.string().min(1),
|
||||
inputs: z.array(InputDefSchema).default([]),
|
||||
timeoutSec: z.number().int().min(5).max(3600).optional(),
|
||||
sudo: z.boolean().default(false),
|
||||
confirm: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export const SystemConfigSchema = z.object({
|
||||
id: EntityIdSchema,
|
||||
name: z.string().min(1).max(120),
|
||||
description: z.string().optional(),
|
||||
cacheTtlSec: z.number().int().min(0).max(86400).default(45),
|
||||
backgroundCheckSec: z.number().int().min(10).max(86400).optional(),
|
||||
params: z.array(SystemParamDefSchema).default([]),
|
||||
discovery: SystemDiscoverySchema,
|
||||
status: SystemStatusSchema,
|
||||
actions: z.array(SystemActionSchema).default([]),
|
||||
editableFiles: z.array(z.string().min(1)).default([]),
|
||||
});
|
||||
export const SystemConfigSchema = z
|
||||
.object({
|
||||
id: EntityIdSchema,
|
||||
name: z.string().min(1).max(120),
|
||||
description: z.string().optional(),
|
||||
cacheTtlSec: z.number().int().min(0).max(86400).default(45),
|
||||
backgroundCheckSec: z.number().int().min(10).max(86400).optional(),
|
||||
params: z.array(SystemParamDefSchema).default([]),
|
||||
discovery: SystemDiscoverySchema,
|
||||
status: SystemStatusSchema,
|
||||
actions: z.array(SystemActionSchema).default([]),
|
||||
editableFiles: z.array(z.string().min(1)).default([]),
|
||||
})
|
||||
.superRefine((sys, ctx) => {
|
||||
const paramNames = new Set<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 SystemHealthRule = z.infer<typeof SystemHealthRuleSchema>;
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
import { z } from 'zod';
|
||||
import { CronExpressionSchema, EntityIdSchema, InputDefSchema } from './common.js';
|
||||
import {
|
||||
CronExpressionSchema,
|
||||
EntityIdSchema,
|
||||
HttpUrlSchema,
|
||||
IanaTimezoneSchema,
|
||||
InputDefSchema,
|
||||
} from './common.js';
|
||||
|
||||
export const WorkflowTargetSchema = z
|
||||
.object({
|
||||
|
|
@ -23,12 +29,13 @@ export const StepDependencySchema = z.union([
|
|||
export const StepFailureActionSchema = z.union([
|
||||
z.literal('abort'),
|
||||
z.literal('continue'),
|
||||
z.string().min(1),
|
||||
z.object({
|
||||
action: z.enum(['abort', 'continue', 'notify', 'run-workflow']),
|
||||
channelId: z.string().min(1).optional(),
|
||||
workflowId: EntityIdSchema.optional(),
|
||||
}),
|
||||
EntityIdSchema,
|
||||
z.discriminatedUnion('action', [
|
||||
z.object({ action: z.literal('abort') }),
|
||||
z.object({ action: z.literal('continue') }),
|
||||
z.object({ action: z.literal('notify'), channelId: EntityIdSchema }),
|
||||
z.object({ action: z.literal('run-workflow'), workflowId: EntityIdSchema }),
|
||||
]),
|
||||
]);
|
||||
|
||||
const StepBaseFields = {
|
||||
|
|
@ -36,6 +43,9 @@ const StepBaseFields = {
|
|||
name: z.string().min(1).max(120).optional(),
|
||||
dependsOn: z.array(StepDependencySchema).default([]),
|
||||
timeoutSec: z.number().int().min(1).max(86400).optional(),
|
||||
retries: z.number().int().min(0).max(5).default(0),
|
||||
retryBackoffSec: z.number().int().min(1).max(300).default(5),
|
||||
when: z.string().min(1).max(256).optional(),
|
||||
sudo: z.boolean().default(false),
|
||||
captureAs: z.string().min(1).max(64).optional(),
|
||||
onFailure: StepFailureActionSchema.optional(),
|
||||
|
|
@ -80,6 +90,28 @@ export const TransferStepSchema = z.object({
|
|||
serverId: z.string().min(1),
|
||||
path: z.string().min(1),
|
||||
}),
|
||||
delete: z.boolean().optional(),
|
||||
exclude: z.array(z.string().min(1)).max(32).optional(),
|
||||
});
|
||||
|
||||
export const HttpStepSchema = z.object({
|
||||
...StepBaseFields,
|
||||
type: z.literal('http'),
|
||||
url: HttpUrlSchema,
|
||||
method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).default('POST'),
|
||||
headers: z.record(z.string()).optional(),
|
||||
body: z.string().optional(),
|
||||
secretRef: EntityIdSchema.optional(),
|
||||
expectedStatus: z.number().int().min(100).max(599).optional(),
|
||||
});
|
||||
|
||||
export const NotifyStepSchema = z.object({
|
||||
...StepBaseFields,
|
||||
type: z.literal('notify'),
|
||||
channelIds: z.array(EntityIdSchema).min(1),
|
||||
title: z.string().min(1).max(160),
|
||||
message: z.string().min(1).max(4000),
|
||||
severity: z.enum(['warn', 'critical']).default('warn'),
|
||||
});
|
||||
|
||||
export const WorkflowStepSchema = z.discriminatedUnion('type', [
|
||||
|
|
@ -87,6 +119,8 @@ export const WorkflowStepSchema = z.discriminatedUnion('type', [
|
|||
ReadFileStepSchema,
|
||||
SystemActionStepSchema,
|
||||
TransferStepSchema,
|
||||
HttpStepSchema,
|
||||
NotifyStepSchema,
|
||||
]);
|
||||
|
||||
export const WorkflowTriggerSchema = z.discriminatedUnion('type', [
|
||||
|
|
@ -94,7 +128,7 @@ export const WorkflowTriggerSchema = z.discriminatedUnion('type', [
|
|||
z.object({
|
||||
type: z.literal('cron'),
|
||||
expression: CronExpressionSchema,
|
||||
timezone: z.string().min(1).default('UTC'),
|
||||
timezone: IanaTimezoneSchema.default('UTC'),
|
||||
}),
|
||||
z.object({
|
||||
type: z.literal('event'),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
export type VaultState = 'uninitialized' | 'locked' | 'unlocked';
|
||||
export type VaultSealState = 'uninitialized' | 'sealed' | 'write-locked' | 'unlocked';
|
||||
|
||||
export type ServerConnectionStatus =
|
||||
| 'disconnected'
|
||||
|
|
@ -48,6 +49,7 @@ export interface ProbeSample {
|
|||
ok: boolean;
|
||||
statusCode?: number;
|
||||
latencyMs: number;
|
||||
certExpiryDays?: number;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
|
|
@ -133,6 +135,7 @@ export type ServerWsFrame =
|
|||
type: 'hello';
|
||||
vaultState: VaultState;
|
||||
vaultRuntimeReady?: boolean;
|
||||
vaultSealState?: VaultSealState;
|
||||
safeMode: boolean;
|
||||
elevatedUntil: number | null;
|
||||
}
|
||||
|
|
@ -140,6 +143,7 @@ export type ServerWsFrame =
|
|||
type: 'vault:state';
|
||||
vaultState: VaultState;
|
||||
vaultRuntimeReady: boolean;
|
||||
vaultSealState?: VaultSealState;
|
||||
isPanicLocked: boolean;
|
||||
}
|
||||
| {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import http from 'node:http';
|
|||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
|
||||
|
|
@ -205,6 +205,8 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide
|
|||
return { status: res.status, data };
|
||||
};
|
||||
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(Date.now() - 35_000);
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
const secretBase32 = String(bootInfo.data.secretBase32);
|
||||
const totp = new OTPAuth.TOTP({
|
||||
|
|
@ -225,7 +227,11 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide
|
|||
initialSafeMode: false,
|
||||
},
|
||||
});
|
||||
vi.useRealTimers();
|
||||
csrfToken = String(boot.data.csrfToken);
|
||||
expect(
|
||||
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
|
||||
).toBe(200);
|
||||
|
||||
await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
await api('/api/vault/credentials', {
|
||||
|
|
@ -281,6 +287,19 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide
|
|||
// Write-lock Vault -> AI runtime secret still works via VaultService.getRuntimeSecret
|
||||
expect((await api('/api/vault/lock', { method: 'POST' })).data.state).toBe('locked');
|
||||
|
||||
// Default Zero-Trust egress policy blocks outbound calls to loopback until allowlisted
|
||||
const blockedEp = await api('/api/ai/test', { method: 'POST', body: {} });
|
||||
expect(blockedEp.data.ok).toBe(false);
|
||||
|
||||
expect(
|
||||
(
|
||||
await api('/api/auth/security-policy', {
|
||||
method: 'PUT',
|
||||
body: { egressAllowedCidrs: ['127.0.0.1/32'] },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
|
||||
const testEp = await api('/api/ai/test', { method: 'POST', body: {} });
|
||||
expect(testEp.status).toBe(200);
|
||||
expect(testEp.data.ok).toBe(true);
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import http from 'node:http';
|
|||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
import { MockSshServer } from './helpers/mock-ssh-server.js';
|
||||
|
|
@ -132,6 +132,8 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () =>
|
|||
return { status: res.status, data };
|
||||
};
|
||||
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(Date.now() - 35_000);
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
const secretBase32 = String(bootInfo.data.secretBase32);
|
||||
const totp = new OTPAuth.TOTP({
|
||||
|
|
@ -152,7 +154,11 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () =>
|
|||
initialSafeMode: false,
|
||||
},
|
||||
});
|
||||
vi.useRealTimers();
|
||||
csrfToken = String(boot.data.csrfToken);
|
||||
expect(
|
||||
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
|
||||
).toBe(200);
|
||||
|
||||
await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
const keyRes = await api('/api/vault/generate-ed25519', {
|
||||
|
|
@ -409,6 +415,19 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () =>
|
|||
expect(lockRes.data.state).toBe('locked');
|
||||
expect(lockRes.data.runtimeReady).toBe(true);
|
||||
|
||||
// Default Zero-Trust egress policy blocks webhook dispatch to 127.0.0.1 until allowlisted
|
||||
const deniedWebhook = await api('/api/alerts/channels/ch-discord/test', { method: 'POST' });
|
||||
expect(deniedWebhook.data.ok).toBe(false);
|
||||
|
||||
expect(
|
||||
(
|
||||
await api('/api/auth/security-policy', {
|
||||
method: 'PUT',
|
||||
body: { egressAllowedCidrs: ['127.0.0.1/32'] },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
|
||||
// --- 1. Send Test Alert for all 4 channel types while Vault is write-locked ---
|
||||
for (const chId of ['ch-discord', 'ch-tg', 'ch-ntfy', 'ch-generic']) {
|
||||
const tRes = await api(`/api/alerts/channels/${chId}/test`, { method: 'POST' });
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import os from 'node:os';
|
|||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
|
||||
|
|
@ -115,7 +115,9 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
|
|||
expect(health.status).toBe(200);
|
||||
await expect(openWs(wsUrl, {})).rejects.toThrow('WS_HTTP_401');
|
||||
|
||||
// 2. Bootstrap Admin + TOTP
|
||||
// 2. Bootstrap Admin + TOTP (offset 65s back so step-up tests below have fresh TOTP steps)
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(Date.now() - 65_000);
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
expect(bootInfo.status).toBe(200);
|
||||
const secretBase32 = String(bootInfo.data.secretBase32);
|
||||
|
|
@ -138,6 +140,7 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
|
|||
initialSafeMode: false,
|
||||
},
|
||||
});
|
||||
vi.setSystemTime(Date.now() + 31_000);
|
||||
expect(bootDone.status).toBe(201);
|
||||
csrfToken = String(bootDone.data.csrfToken);
|
||||
const recoveryCodes = bootDone.data.recoveryCodes as string[];
|
||||
|
|
@ -198,24 +201,14 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
|
|||
(await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } })).status,
|
||||
).toBe(200);
|
||||
|
||||
// 6. Vault Init + Drop Elevation -> Step-Up guard + Generate Ed25519 key
|
||||
const vInit = await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
expect(vInit.status).toBe(201);
|
||||
const generatedMasterKey = String(vInit.data.generatedKeyHex);
|
||||
// 6. Vault Init + Step-Up guard + Drop Elevation + Generate Ed25519 key
|
||||
// v1.1 defaults elevateOnLogin=false; verify non-elevated session cannot init vault
|
||||
const statusInitial = await api('/api/auth/status');
|
||||
expect(statusInitial.data.elevatedUntil).toBeNull();
|
||||
|
||||
// Default balanced mode elevates on bootstrap/login; drop elevation to verify guard enforcement
|
||||
const statusBeforeDrop = await api('/api/auth/status');
|
||||
expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number');
|
||||
const dropped = await api('/api/auth/drop-elevation', { method: 'POST' });
|
||||
expect(dropped.status).toBe(200);
|
||||
expect(dropped.data.elevatedUntil).toBeNull();
|
||||
|
||||
const noStepUp = await api('/api/vault/generate-ed25519', {
|
||||
method: 'POST',
|
||||
body: { id: 'prod-key', name: 'Prod Key' },
|
||||
});
|
||||
expect(noStepUp.status).toBe(403);
|
||||
expect(noStepUp.data.error).toBe('STEP_UP_REQUIRED');
|
||||
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',
|
||||
|
|
@ -223,6 +216,27 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
|
|||
});
|
||||
expect(stepUpRes.status).toBe(200);
|
||||
|
||||
const vInit = await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
expect(vInit.status).toBe(201);
|
||||
const generatedMasterKey = String(vInit.data.generatedKeyHex);
|
||||
|
||||
const statusBeforeDrop = await api('/api/auth/status');
|
||||
expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number');
|
||||
const dropped = await api('/api/auth/drop-elevation', { method: 'POST' });
|
||||
expect(dropped.status).toBe(200);
|
||||
expect(dropped.data.elevatedUntil).toBeNull();
|
||||
|
||||
const afterDropDenied = await api('/api/vault/generate-ed25519', {
|
||||
method: 'POST',
|
||||
body: { id: 'prod-key', name: 'Prod Key' },
|
||||
});
|
||||
expect(afterDropDenied.status).toBe(403);
|
||||
|
||||
vi.useRealTimers();
|
||||
expect(
|
||||
(await api('/api/auth/step-up', { method: 'POST', body: { code: totpGen.generate() } })).status,
|
||||
).toBe(200);
|
||||
|
||||
const genRes = await api('/api/vault/generate-ed25519', {
|
||||
method: 'POST',
|
||||
body: { id: 'prod-key', name: 'Prod Key' },
|
||||
|
|
|
|||
|
|
@ -129,15 +129,21 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
|
|||
});
|
||||
expect(boot.session.elevatedUntil).toBeNull();
|
||||
|
||||
// Step-up tracks replay independently from login step
|
||||
const stepUp1 = await auth.stepUp(boot.session.idHash, code0);
|
||||
// Unified monotonic TOTP step blocks replaying bootstrap code for step-up
|
||||
const replayBootCode = await auth.stepUp(boot.session.idHash, code0);
|
||||
expect(replayBootCode).toEqual({ ok: false, reason: 'totp_replayed' });
|
||||
|
||||
const t1 = t0 + 31_000;
|
||||
vi.setSystemTime(t1);
|
||||
const code1 = generateTotp(enroll.secretBase32, t1);
|
||||
const stepUp1 = await auth.stepUp(boot.session.idHash, code1);
|
||||
expect(stepUp1).toEqual({
|
||||
ok: true,
|
||||
elevatedUntil: t0 + 5 * 60 * 1000,
|
||||
elevatedUntil: t1 + 5 * 60 * 1000,
|
||||
});
|
||||
|
||||
// Replaying exact same step-up code is denied
|
||||
const stepUpReplay = await auth.stepUp(boot.session.idHash, code0);
|
||||
const stepUpReplay = await auth.stepUp(boot.session.idHash, code1);
|
||||
expect(stepUpReplay).toEqual({ ok: false, reason: 'totp_replayed' });
|
||||
|
||||
// Enabling Safe Mode clears elevatedUntil immediately
|
||||
|
|
@ -146,25 +152,26 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
|
|||
expect(safeSession?.elevatedUntil).toBeNull();
|
||||
|
||||
// Step-up is blocked while Safe Mode is ON
|
||||
vi.setSystemTime(t0 + 31_000);
|
||||
const code1 = generateTotp(enroll.secretBase32, t0 + 31_000);
|
||||
const whileSafe = await auth.stepUp(boot.session.idHash, code1);
|
||||
const t2 = t1 + 31_000;
|
||||
vi.setSystemTime(t2);
|
||||
const code2 = generateTotp(enroll.secretBase32, t2);
|
||||
const whileSafe = await auth.stepUp(boot.session.idHash, code2);
|
||||
expect(whileSafe).toEqual({ ok: false, reason: 'safe_mode_active' });
|
||||
|
||||
// Turning Safe Mode OFF allows step-up again
|
||||
auth.setSafeMode(boot.session.idHash, false);
|
||||
const stepUp2 = await auth.stepUp(boot.session.idHash, code1);
|
||||
const stepUp2 = await auth.stepUp(boot.session.idHash, code2);
|
||||
expect(stepUp2.ok).toBe(true);
|
||||
|
||||
// Elevation expires automatically after 5 minutes
|
||||
vi.setSystemTime(t0 + 31_000 + 5 * 60 * 1000 + 1000);
|
||||
vi.setSystemTime(t2 + 5 * 60 * 1000 + 1000);
|
||||
const expiredSession = auth.getSessionByToken(boot.sessionToken);
|
||||
expect(expiredSession?.elevatedUntil).toBeNull();
|
||||
|
||||
db.close();
|
||||
});
|
||||
|
||||
it('grants default 1h elevation on bootstrap/login and preserves elevation across Safe Mode toggle', async () => {
|
||||
it('keeps elevateOnLogin disabled by default (15m step-up policy) and preserves elevation across Safe Mode toggle', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
const t0 = 1_700_000_010_000;
|
||||
vi.setSystemTime(t0);
|
||||
|
|
@ -180,11 +187,18 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
|
|||
userAgent: 'vitest',
|
||||
});
|
||||
|
||||
expect(boot.session.elevatedUntil).toBe(t0 + 60 * 60 * 1000);
|
||||
expect(boot.session.elevatedUntil).toBeNull();
|
||||
|
||||
vi.setSystemTime(t0 + 31_000);
|
||||
const step = await auth.stepUp(boot.session.idHash, generateTotp(enroll.secretBase32, t0 + 31_000));
|
||||
expect(step).toEqual({
|
||||
ok: true,
|
||||
elevatedUntil: t0 + 31_000 + 15 * 60 * 1000,
|
||||
});
|
||||
|
||||
const safeSession = auth.setSafeMode(boot.session.idHash, true);
|
||||
expect(safeSession?.safeMode).toBe(true);
|
||||
expect(safeSession?.elevatedUntil).toBe(t0 + 60 * 60 * 1000);
|
||||
expect(safeSession?.elevatedUntil).toBe(t0 + 31_000 + 15 * 60 * 1000);
|
||||
|
||||
db.close();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import os from 'node:os';
|
|||
import path from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
import { openDatabase } from '../src/server/db/database.js';
|
||||
import { VaultService } from '../src/server/security/vault.js';
|
||||
|
|
@ -84,6 +84,8 @@ describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord C
|
|||
return { status: res.status, data };
|
||||
};
|
||||
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(Date.now() - 35_000);
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
const secretBase32 = String(bootInfo.data.secretBase32);
|
||||
const totp = new OTPAuth.TOTP({
|
||||
|
|
@ -104,7 +106,11 @@ describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord C
|
|||
initialSafeMode: false,
|
||||
},
|
||||
});
|
||||
vi.useRealTimers();
|
||||
csrfToken = String(boot.data.csrfToken);
|
||||
expect(
|
||||
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
|
||||
).toBe(200);
|
||||
|
||||
await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
const keyRes = await api('/api/vault/generate-ed25519', {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import fs from 'node:fs';
|
|||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
import { MockSshServer } from './helpers/mock-ssh-server.js';
|
||||
|
|
@ -103,6 +103,8 @@ describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions &
|
|||
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 secretBase32 = String(bootInfo.data.secretBase32);
|
||||
const totp = new OTPAuth.TOTP({
|
||||
|
|
@ -123,7 +125,11 @@ describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions &
|
|||
initialSafeMode: false,
|
||||
},
|
||||
});
|
||||
vi.useRealTimers();
|
||||
csrfToken = String(boot.data.csrfToken);
|
||||
expect(
|
||||
(await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status,
|
||||
).toBe(200);
|
||||
|
||||
await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
const keyRes = await api('/api/vault/generate-ed25519', {
|
||||
|
|
|
|||
|
|
@ -401,7 +401,27 @@ export class MockSshServer {
|
|||
let stdin = rawStdin;
|
||||
|
||||
// Handle sudo wrappers produced by prepareSudoExecution
|
||||
if (command.startsWith("sudo -S -p '' sh -c ")) {
|
||||
if (command.startsWith("sudo -S -k -p '' sh -c ")) {
|
||||
const nl = stdin.indexOf('\n');
|
||||
const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin;
|
||||
this.lastSudoStdin = suppliedPw;
|
||||
stdin = nl >= 0 ? stdin.slice(nl + 1) : '';
|
||||
if (this.options.sudoPassword && suppliedPw !== this.options.sudoPassword) {
|
||||
return { stdout: '', stderr: 'sudo: incorrect password', exitCode: 1 };
|
||||
}
|
||||
command = unquoteSinglePosix(command.slice("sudo -S -k -p '' sh -c ".length));
|
||||
} else if (command.startsWith("sudo -S -k -p '[gcoord-sudo-prompt] ' sh -c ")) {
|
||||
const nl = stdin.indexOf('\n');
|
||||
const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin;
|
||||
this.lastSudoStdin = suppliedPw;
|
||||
stdin = nl >= 0 ? stdin.slice(nl + 1) : '';
|
||||
if (this.options.sudoPassword && suppliedPw !== this.options.sudoPassword) {
|
||||
return { stdout: '', stderr: 'sudo: incorrect password', exitCode: 1 };
|
||||
}
|
||||
command = unquoteSinglePosix(
|
||||
command.slice("sudo -S -k -p '[gcoord-sudo-prompt] ' sh -c ".length),
|
||||
);
|
||||
} else if (command.startsWith("sudo -S -p '' sh -c ")) {
|
||||
const nl = stdin.indexOf('\n');
|
||||
const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin;
|
||||
this.lastSudoStdin = suppliedPw;
|
||||
|
|
@ -547,9 +567,10 @@ export class MockSshServer {
|
|||
rawCommand: string,
|
||||
): { stdout: Buffer; stderr?: string; exitCode: number } | null {
|
||||
// Support streamed SFTP folder archive command in integration tests
|
||||
const tarMatch = /tar -C ('(?:[^']|'\\'')*'|\S+) -cf - ('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec(
|
||||
rawCommand,
|
||||
);
|
||||
const tarMatch =
|
||||
/tar (?:--one-file-system )?-C ('(?:[^']|'\\'')*'|\S+) -cf - (?:-- )?('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec(
|
||||
rawCommand,
|
||||
);
|
||||
if (tarMatch) {
|
||||
try {
|
||||
const virtualParent = unquoteSinglePosix(tarMatch[1]!);
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue