mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-28 06:05:24 +00:00
release-2.8.0 (#1456)
* Fix private AI custom endpoints (#1299) * Fix Proxmox credential guest imports (#1300) * Fix Fleet command results layout (#1301) * Fix synced client tunnel endpoints (#1302) * Fix Proxmox sync jump host persistence (#1303) * Fix command palette keyboard navigation (#1304) * Add accessible interface font choices (#1306) * Add selectable host temperature sensors (#1307) * Improve file manager navigation and compact layout (#1308) * Add configurable global hotkeys (#1305) * fix: restore split layout selection (#1310) * fix: support macOS VNC connections (#1311) * fix: use matching Undici fetch for private AI providers (#1309) Co-authored-by: Angad Singh <angad@singhangad.in> * feat: support additional TOTP authenticators (#1312) * feat: add VNC display zoom controls (#1314) * feat: add host context menu actions (#1315) * fix: force classic auth for macOS VNC (#1313) * fix: harden HTTP trust boundaries (#1316) * fix: harden application trust boundaries (#1317) * fix: verify OPKSSH binary integrity (#1318) * Fix remote desktop connection timeout (#1319) * chore(deps): bump node in /docker in the docker-major-updates group (#1321) Bumps the docker-major-updates group in /docker with 1 update: node. Updates `node` from 24-slim to 26-slim --- updated-dependencies: - dependency-name: node dependency-version: 26-slim dependency-type: direct:production dependency-group: docker-major-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-patch-updates group with 15 updates (#1322) Bumps the dev-patch-updates group with 15 updates: | Package | From | To | | --- | --- | --- | | [@codemirror/view](https://github.com/codemirror/view) | `6.43.7` | `6.43.9` | | [@commitlint/cli](https://github.com/conventional-changelog/commitlint/tree/HEAD/@commitlint/cli) | `21.2.1` | `21.2.2` | | [@commitlint/config-conventional](https://github.com/conventional-changelog/commitlint/tree/HEAD/@commitlint/config-conventional) | `21.2.0` | `21.2.2` | | [@testing-library/jest-dom](https://github.com/testing-library/jest-dom) | `7.0.0` | `7.0.1` | | [@testing-library/user-event](https://github.com/testing-library/user-event) | `14.6.1` | `14.6.5` | | [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.1.10` | `4.1.11` | | [@vitest/ui](https://github.com/vitest-dev/vitest/tree/HEAD/packages/ui) | `4.1.10` | `4.1.11` | | [concurrently](https://github.com/open-cli-tools/concurrently) | `10.0.4` | `10.0.5` | | [cytoscape](https://github.com/cytoscape/cytoscape.js) | `3.34.0` | `3.34.1` | | [eslint](https://github.com/eslint/eslint) | `10.8.0` | `10.8.1` | | [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.3` | `0.5.4` | | [react-i18next](https://github.com/i18next/react-i18next) | `17.0.11` | `17.0.12` | | [sonner](https://github.com/emilkowalski/sonner) | `2.0.7` | `2.0.8` | | [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.2.0` | `8.2.2` | | [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.1.10` | `4.1.11` | Updates `@codemirror/view` from 6.43.7 to 6.43.9 - [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/view/commits) Updates `@commitlint/cli` from 21.2.1 to 21.2.2 - [Release notes](https://github.com/conventional-changelog/commitlint/releases) - [Changelog](https://github.com/conventional-changelog/commitlint/blob/master/@commitlint/cli/CHANGELOG.md) - [Commits](https://github.com/conventional-changelog/commitlint/commits/v21.2.2/@commitlint/cli) Updates `@commitlint/config-conventional` from 21.2.0 to 21.2.2 - [Release notes](https://github.com/conventional-changelog/commitlint/releases) - [Changelog](https://github.com/conventional-changelog/commitlint/blob/master/@commitlint/config-conventional/CHANGELOG.md) - [Commits](https://github.com/conventional-changelog/commitlint/commits/v21.2.2/@commitlint/config-conventional) Updates `@testing-library/jest-dom` from 7.0.0 to 7.0.1 - [Release notes](https://github.com/testing-library/jest-dom/releases) - [Changelog](https://github.com/testing-library/jest-dom/blob/main/CHANGELOG.md) - [Commits](https://github.com/testing-library/jest-dom/compare/v7.0.0...v7.0.1) Updates `@testing-library/user-event` from 14.6.1 to 14.6.5 - [Release notes](https://github.com/testing-library/user-event/releases) - [Changelog](https://github.com/testing-library/user-event/blob/main/CHANGELOG.md) - [Commits](https://github.com/testing-library/user-event/compare/v14.6.1...v14.6.5) Updates `@vitest/coverage-v8` from 4.1.10 to 4.1.11 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/coverage-v8) Updates `@vitest/ui` from 4.1.10 to 4.1.11 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/ui) Updates `concurrently` from 10.0.4 to 10.0.5 - [Release notes](https://github.com/open-cli-tools/concurrently/releases) - [Commits](https://github.com/open-cli-tools/concurrently/compare/v10.0.4...v10.0.5) Updates `cytoscape` from 3.34.0 to 3.34.1 - [Release notes](https://github.com/cytoscape/cytoscape.js/releases) - [Commits](https://github.com/cytoscape/cytoscape.js/compare/v3.34.0...v3.34.1) Updates `eslint` from 10.8.0 to 10.8.1 - [Release notes](https://github.com/eslint/eslint/releases) - [Commits](https://github.com/eslint/eslint/compare/v10.8.0...v10.8.1) Updates `eslint-plugin-react-refresh` from 0.5.3 to 0.5.4 - [Release notes](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/releases) - [Changelog](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/blob/main/CHANGELOG.md) - [Commits](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/compare/v0.5.3...v0.5.4) Updates `react-i18next` from 17.0.11 to 17.0.12 - [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/react-i18next/compare/v17.0.11...v17.0.12) Updates `sonner` from 2.0.7 to 2.0.8 - [Release notes](https://github.com/emilkowalski/sonner/releases) - [Commits](https://github.com/emilkowalski/sonner/compare/v2.0.7...v2.0.8) Updates `vite` from 8.2.0 to 8.2.2 - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/v8.2.2/packages/vite) Updates `vitest` from 4.1.10 to 4.1.11 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.11/packages/vitest) --- updated-dependencies: - dependency-name: "@codemirror/view" dependency-version: 6.43.9 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@commitlint/cli" dependency-version: 21.2.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@commitlint/config-conventional" dependency-version: 21.2.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@testing-library/jest-dom" dependency-version: 7.0.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@testing-library/user-event" dependency-version: 14.6.5 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitest/coverage-v8" dependency-version: 4.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitest/ui" dependency-version: 4.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: concurrently dependency-version: 10.0.5 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: cytoscape dependency-version: 3.34.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: eslint dependency-version: 10.8.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: eslint-plugin-react-refresh dependency-version: 0.5.4 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: react-i18next dependency-version: 17.0.12 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: sonner dependency-version: 2.0.8 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: vite dependency-version: 8.2.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: vitest dependency-version: 4.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump the prod-patch-updates group with 5 updates (#1324) Bumps the prod-patch-updates group with 5 updates: | Package | From | To | | --- | --- | --- | | [@tanstack/react-virtual](https://github.com/TanStack/virtual/tree/HEAD/packages/react-virtual) | `3.14.9` | `3.14.10` | | [better-sqlite3](https://github.com/WiseLibs/better-sqlite3) | `13.0.2` | `13.0.3` | | [jose](https://github.com/panva/jose) | `6.2.8` | `6.2.9` | | [mysql2](https://github.com/sidorares/node-mysql2) | `3.23.2` | `3.23.4` | | [ws](https://github.com/websockets/ws) | `8.21.1` | `8.21.3` | Updates `@tanstack/react-virtual` from 3.14.9 to 3.14.10 - [Release notes](https://github.com/TanStack/virtual/releases) - [Changelog](https://github.com/TanStack/virtual/blob/main/packages/react-virtual/CHANGELOG.md) - [Commits](https://github.com/TanStack/virtual/commits/@tanstack/react-virtual@3.14.10/packages/react-virtual) Updates `better-sqlite3` from 13.0.2 to 13.0.3 - [Release notes](https://github.com/WiseLibs/better-sqlite3/releases) - [Commits](https://github.com/WiseLibs/better-sqlite3/compare/v13.0.2...v13.0.3) Updates `jose` from 6.2.8 to 6.2.9 - [Release notes](https://github.com/panva/jose/releases) - [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md) - [Commits](https://github.com/panva/jose/compare/v6.2.8...v6.2.9) Updates `mysql2` from 3.23.2 to 3.23.4 - [Release notes](https://github.com/sidorares/node-mysql2/releases) - [Changelog](https://github.com/sidorares/node-mysql2/blob/master/Changelog.md) - [Commits](https://github.com/sidorares/node-mysql2/compare/v3.23.2...v3.23.4) Updates `ws` from 8.21.1 to 8.21.3 - [Release notes](https://github.com/websockets/ws/releases) - [Commits](https://github.com/websockets/ws/compare/8.21.1...8.21.3) --- updated-dependencies: - dependency-name: "@tanstack/react-virtual" dependency-version: 3.14.10 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: better-sqlite3 dependency-version: 13.0.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: jose dependency-version: 6.2.9 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: mysql2 dependency-version: 3.23.4 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: ws dependency-version: 8.21.3 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump motion in the major-updates group (#1326) Bumps the major-updates group with 1 update: [motion](https://github.com/motiondivision/motion). Updates `motion` from 12.43.0 to 13.1.1 - [Changelog](https://github.com/motiondivision/motion/blob/main/CHANGELOG.md) - [Commits](https://github.com/motiondivision/motion/compare/v12.43.0...v13.1.1) --- updated-dependencies: - dependency-name: motion dependency-version: 13.1.1 dependency-type: direct:production update-type: version-update:semver-major dependency-group: major-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * feat: add semantic motion system (#1320) * feat: add semantic motion system * feat: animate session workspace transitions * feat: refine motion accessibility and transfer feedback * feat: enforce RBAC and harden collaboration features (#1327) * feat: enforce RBAC and harden collaboration features - Mount requirePermission on hosts/snippets/credentials/automations/AI routes - Seed and backfill system role permissions on every dialect at startup - Support personal credential overrides for RDP/VNC/Telnet shared hosts - Broadcast participant presence in shared terminal sessions - Make audit log forwarding configurable from the admin panel - Add role members endpoint and snippet folder sharing * fix: enforce RBAC across split routes * fix: reject malformed Guacamole tokens safely (#1329) * fix: allow approved private notification hosts (#1330) * feat: collaboration rooms with switchable presenter (#1328) * feat: add collaboration rooms with switchable presenter Rooms are a group of members watching one stage - the live SSH/RDP/VNC session the current presenter shares. Any member can take over the stage; the host can invite, force-stop and end the meeting. Stages reuse session_shares (new room share type), so gating, recording, expiry and the global sharing toggle all apply unchanged. * feat: add stage control handoff to collaboration rooms The presenter or host can grant any member write access to the live stage and take it back; members can raise a hand to ask. SSH flips the participant's permission on the live gate; RDP/VNC re-mint the viewer's join token. Control clears on every stage switch. * feat: guest links, role invites and invite awareness for collab rooms - Anonymous guest link per room (host toggles/rotates), followed by polling the public resolve endpoint; SSH guests join over the terminal WS with roomGuestToken, guac guests get read-only join tokens - Invite by role (expands to current members, snapshot semantics) - Toast when a room you were invited to appears - Stale stages are cleared lazily when the presenter is gone - Telnet presenting, expired-tab fallback, documented single-instance and guac-kick limits - Tests for the collab routes, room hub, share access and control flip * fix: keep remote desktop collaboration read-only * fix: restore RDP clipboard paste across browsers (#1331) * fix: show the full command line in the process inspector (#1334) The CMD column rendered ps's comm field, which the kernel caps at 15 characters, so anything longer looked truncated no matter how wide the column was. The full args were already collected; show them. * fix: harden collaboration room access (#1332) * fix: harden collaboration room access * fix: confirm guest link lifecycle changes * fix: make RDP drive redirection writable on the stock deployment (#1333) * fix: make RDP drive redirection writable on the stock deployment The default drive-path was /drive on the guacd side, which the official guacd image cannot create as its non-root user, so every upload was refused with guacd's raw "FAIL (CANNOT OPEN)" ack. Default to GUACD_DRIVE_PATH (set to the shared termix-data volume in compose) with one folder per user, and explain guacd's refusal in the file browser. * style: format RDP drive settings * feat: quick connect for RDP and VNC (#1335) The Quick Connect panel gets a protocol switch. RDP/VNC quick hosts are built like SSH ones (never saved) and opened as regular remote desktop tabs; GuacamoleApp mints their token from the typed fields through the existing /guacamole/token endpoint instead of a host-row lookup. * fix: authenticate unwatched hosts during the status probe (#1337) With metrics enabled, the status probe left SSH authentication to the metrics poll - which only runs while someone is viewing the host. An unwatched host therefore never left "reachable", while a host with metrics disabled (whose probe always authenticates) showed online. The probe now authenticates whenever no metrics poll will. * feat: compact snippet list option (#1339) A "Show Commands" toggle in the snippets settings menu hides the command text under each snippet name, for people who dock the panel on the narrow right rail and only need the names. Local preference, on by default. * fix: guide users to Auto-Tmux when a persisted session expires (#1336) * fix: guide users to Auto-Tmux when a persisted session expires A timed-out terminal session silently reconnected to a fresh shell, so people running long jobs lost them with no explanation and never learned about Auto-Tmux. Explain the expiry with a one-click Enable Auto-Tmux action, let admins default it for new hosts and tune the persistence timeout from the UI, and move the setting up with copy that says what it does. The global default stays off. * style: format terminal expiry notice * feat: improve collaboration rooms (#1338) * feat: Step CA SSH certificates as a host authentication type (#1340) * feat: Step CA SSH certificates as a host authentication type Issue short-lived SSH user certificates from a smallstep CA through its OIDC provisioner, over the CA's HTTP API rather than the step binary. Everything after issuance reuses the OPKSSH plumbing: the same encrypted per-user/host token store, WebSocket dialog and ssh2 certificate injection, with the connect paths branching on a shared usesIssuedCertificate() predicate. Instance-wide CA settings live in the admin panel, with a private-host allowlist for the SSRF guard. * fix: harden Step CA callback flow * style: format Step CA changes * feat: 1Password Connect secret sources for SSH credentials (#1341) * feat: 1Password Connect secret sources for SSH credentials Hosts and credentials can hold op://vault/item/field references instead of secrets; they are resolved at connect time from the user's secret source (1Password Connect) at the single point where every subsystem receives plaintext credentials, so terminal, SFTP, Docker, metrics and tunnels all work without per-subsystem changes. Sources are per user, optionally shared, with the access token encrypted under the owner's data key; resolved values are cached briefly in memory. * style: format secret source changes * feat: share credentials with users and roles, inherit data on account deletion (#1342) * feat: share credentials with users and roles, inherit data on account deletion Credentials can be shared at "use" or "manage" level. Recipients get a copy re-encrypted under their own data key (shared_credential_secrets), kept in step with the owner's row through the same lifecycle hooks as shared host secrets. One gate, findUsableCredential(), replaces the private-namespace lookups so a shared credential works wherever a private one does. Deleting a user now hands their hosts and credentials to a successor (the deleting admin by default) instead of revoking everything they shared. * fix: harden credential ownership transfer * feat: folder shares apply to hosts added later (#1343) * feat: folder shares apply to hosts added later Sharing a folder only fanned grants out to the hosts in it at the time. The share is now also kept as a standing rule on the folder, and a host created in or moved into it (or a subfolder) inherits the same access and secret snapshots. Rules follow folder renames and can be stopped from the share dialog. * fix: stabilize folder access migrations * fix: package sharp for both macOS architectures (#1344) * fix: prompt shared RDP users for credentials (#1345) * feat: add terminal copy-on-select option (#1346) * fix: retry protected file reads with sudo (#1349) * fix: stop SSH-authenticating hosts during routine status polling (#1347) * fix: preserve omitted host protocol settings (#1350) * fix: surface remote sync reauthentication failures (#1351) * fix: harden file reads and timer cleanup (#1352) * fix: harden file reads and timer cleanup * fix: preserve literal file path escapes * fix: enforce SSH pool connection limits (#1353) * fix: enforce SSH pool connection limits * fix: discard stale pooled connections * fix: harden connection, payload, and persisted state handling (#1354) * fix: clean up Cloudflare tunnel timeouts * fix: couple tunnel socket lifecycle * fix: validate Docker console messages * fix: bound homepage proxy responses * fix: bound reconnect and response failures * fix: harden persisted and socket state * fix: support local connections to shared hosts * fix: recover expired dashboard metrics sessions (#1355) * fix: upload files to redirected RDP drives (#1356) * fix: unify connection toolbar visibility (#1357) * fix: reset host virtualizer after editing (#1358) * test: update Guacamole toolbar display mock (#1360) * fix: reflect live SSH sessions in host status (#1359) * fix: support Vault auth in file manager (#1361) * fix: allow exec on shared hosts (#1362) * fix(file-manager): align chunked upload contract (#1371) * fix(file-manager): make bulk uploads resilient (#1373) * fix(terminal): disable local echo on alternate screen (#1372) * fix(homepage): validate clock widget timezones (#1374) An invalid timezone in a clock widget's config reached toLocaleTimeString unchecked, throwing RangeError during render and taking the homepage canvas down with it. The edit dialog accepted any string, so "America/New York" - a space where IANA wants an underscore - was easy to save, and the homepage stayed broken on every later load because the value is reloaded from the database. The edit dialog now flags an unusable zone the way FolderMetadataDialog flags a duplicate folder name: inline message, aria-invalid, and a disabled Save. Whitespace is normalized to underscores on save, so the space spelling is stored as America/New_York rather than rejected. ClockWidget falls back to local time for any config already holding an invalid zone. Related to Termix-SSH/Support#1238 * fix(hosts): preserve connection origin in editor (#1376) * fix(remote-sync): expose local login notification (#1375) * fix(auth): allow passkeys in desktop login (#1378) * fix(proxmox): elevate guest discovery commands (#1379) * Fix permanent file-transfer completion toasts (#1383) * fix(file-manager): expire completed progress toasts * test(file-manager): use valid transfer status * fix(hosts): allow clearing SSH key type (#1384) * fix(terminal): suppress local echo for contextual password prompts (#1387) * fix(desktop): surface a failed embedded backend start (#1382) * fix(desktop): surface a failed embedded backend start When the embedded backend's HTTP port was already taken, the desktop app sat on the "Loading..." spinner forever with nothing in the UI to say why. The backend logged the conflict and exited 1, and startBackendServer resolved false, but that verdict never reached the renderer: the get-embedded-server-status channel was not exposed in preload and nothing called it. The renderer, by design, treats every connection failure as "the embedded backend is still booting" and retries indefinitely -- in main.tsx's verifying phase, in Auth's desktop auto-session, and in FullScreenAppWrapper. That holds while the backend is merely slow to boot, but not once the process has exited, and nothing distinguished the two. Classify why the child died from its exit code and a bounded tail of its stderr, report it through get-embedded-server-status, and have each retry loop keep waiting only while no failure is reported. A port conflict names the port, since that is what the user has to act on -- most often a Termix container on the same ports, or a backend orphaned by a hard-kill that reapOrphanedBackendProcess could not claim. A deliberate shutdown is not reported as a crash, and a backend that is only slow to start still gets retried as before. Fixes Termix-SSH/Support#1254 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(desktop): treat every unrequested backend exit as a failure The classifier exempted a clean exit and SIGTERM/SIGINT, calling those a deliberate shutdown. It has no evidence for that: its only caller already sits behind backendStopRequested, so it is reached only for exits stopBackendServer() did not ask for. A backend that exited 0 on its own, or was terminated by the OS or an external signal, therefore reported no failure at all -- leaving all three renderer loops waiting forever for a process that is gone, which is the exact hang this change set exists to remove. Every exit reaching the classifier is now a failure, port-in-use when stderr carries EADDRINUSE and crashed otherwise, with backendStopRequested left as the sole deliberate-shutdown guard. That makes the exit code and signal irrelevant to the verdict, so the classifier now takes only the stderr tail rather than carrying two parameters it no longer reads. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> * Add white label branding settings (#1386) * feat(admin): add white label branding settings Admins can configure a custom app name, logo and tagline from the Admin Settings panel. The values apply to the login screen and the browser tab title/favicon at runtime. * fix(admin): restore default icons on logo reset, validate upload MIME type Resetting the logo now restores the bundled favicon/apple-touch-icon instead of leaving the previous custom one until a reload. The admin upload also validates file.type up front instead of only failing later on save. * fix(admin): restore default favicons and reject invalid logo types Capture bundled icon hrefs before the first custom logo is applied so a reset does not leave the previous upload in the tab, and reject non-image uploads before they are read into branding state. * test(admin): cover branding routes and logo validation Add backend tests for the public GET, admin-only PATCH, unknown-field rejection, and parseBrandingLogoDataUrl so invalid images cannot land in settings without a failing test. * fix(backend): report port conflicts on the service ports (#1388) Express's app.listen(port, host, callback) registers that callback as the server's error handler as well as its listening handler: if (typeof args[args.length - 1] === 'function') { var done = args[args.length - 1] = once(args[args.length - 1]) server.once('error', done) } so a bind failure invoked the service's "started" callback with an EADDRINUSE error as its only argument and emitted nothing. None of the services read that argument, which made a failed bind indistinguishable from a successful one: the service logged that it had started, ran its initialisation, and served nothing. With one of 30003-30012 occupied the backend still reported backend_init_complete, the app loaded, and the affected feature was dead for the session with no error anywhere in the logs -- searching the backend log, the Electron main log and stdout for EADDRINUSE returned nothing, as did uncaughtException and unhandledRejection probes. This is also why only the main port behaved sensibly: database.ts does not use app.listen(), it builds the server and attaches a real error handler, so 30001 was the one port whose conflict was ever detected. listenOnServicePort() builds the server so that listening and error stay separate, and treats a conflict the way database.ts already does -- name the port, then exit -- rather than running on with one feature missing. Exiting also hands the desktop app the classified failure it already surfaces, so the user is told which port to free. Services that must own their server, such as the tunnel service with its WebSocket upgrade handler, get the same handler via attachServicePortConflictHandler(). Note that adding .on("error") to the services would not have worked: express consumes the event through once('error', done) before any later handler runs. The callback has to stop being passed to listen() at all. Fixes Termix-SSH/Support#1260 Co-authored-by: Claude Opus 5 <noreply@anthropic.com> * feat(desktop): allow RDP/VNC/Telnet to originate from this device (#1389) The desktop pinned rdp/vnc/telnet to the remote server, so a host the user's own machine could reach but the Termix server could not was impossible to open: the app answered "Remote server required" even when no remote server was wanted. The embedded backend already runs the Guacamole websocket server and guacd's address is already configurable globally and per host, so what was missing was the choice. resolveConnectionOrigin now honours an explicit per-host origin for these protocols. Left on Default they still resolve to remote: they need a guacd, which the desktop does not ship, so originating locally only works once the user has pointed Termix at one of their own. Keeping that opt-in means an upgrade never moves a working connection onto a guacd that is not there. Serial and non-Electron behaviour are unchanged. Three call paths had the same assumption baked in and would have quietly ignored the setting: - The Guacamole call sites resolved the origin without passing the host's own override, so it could never take effect. - guacamole-api sent every token, connect-host and status call to the remote server whenever running under Electron, and remapped the host id onto the remote server's id -- which would address the wrong row, or fail outright with no server configured. - GuacamoleDisplay minted its token before resolving the origin, so the token could come from a different backend than the socket dialled. The origin is a required parameter on those API functions rather than a defaulted one. A default silently sent a missed call site to the remote server: the guacd status check in fetchToken was one, and it failed with a bare "Network Error" on a desktop with no server configured. Making it required means the compiler names every caller instead. That also covers CollabRoomTab, which now resolves from the host it already holds, so a locally-originated host stays local when presented into a room. Finally, the Connection Origin control was gated on SSH alone, so a host enabling only these protocols could never reach the setting. That gate is now a named predicate covering every protocol the control applies to. Verified end to end on Linux against a local guacd: with a host set to "This device", guacd accepted the connection and reached the target, which answered for itself. With guacd stopped, the guacd status check that has run before every connection since v2.3.0 -- now asking the backend the session will actually use -- reports it clearly before a socket is opened. Refs Termix-SSH/Support#1240 Co-authored-by: Claude Opus 5 <noreply@anthropic.com> * feat(local-terminal): add copy/paste support (#1391) * feat(local-terminal): add copy/paste support Local terminal had no clipboard wiring, so selected text couldn't be copied. Extracted the SSH terminal's copy/paste shortcut and right-click handling into a shared terminal-clipboard module and wired it into both terminals, removing duplicated logic in the process. * fix(local-terminal): stop language changes from restarting the shell session The session effect that starts the local PTY depended on `t`, whose identity changes on every language switch (react-i18next). That tore down the running shell and spawned a new one just from changing the UI language. Read translations through a ref instead so localization stays decoupled from the PTY lifecycle. Also adds regression coverage for the extracted terminal-clipboard.ts helpers: copy with/without selection, explicit vs native paste, right-click preference, and Ctrl+right-click passthrough. * fix(file-manager): keep name column visible on narrow viewports in list view (#1402) Rebased onto dev-2.8.0 (the density refactor kept the same 3 list-view grid patterns). Use minmax(140px, 1fr) for the name track so it cannot collapse to 0px on narrow viewports; the table scrolls horizontally instead of hiding names and icons. Co-authored-by: inontz <inontz@users.noreply.github.com> * feat(desktop): local filesystem and transfer bridge for the file manager (#1392) * feat(desktop): local filesystem and transfer bridge for the file manager Adds the Electron main-process side of the upcoming Local | Remote dual-pane file manager, with no UI yet: - electron/local-files.cjs: IPC handlers to browse the local disk (home, list, mkdir, createFile, rename, trash, ensureDir, walk, reveal, open) and to stream files between the local disk and the file-manager backend (uploadLocalFile / downloadToLocal with progress events and cancellation). Streams go through Electron's `net` so the session cookie / remembered JWT is attached the same way as the renderer's own requests. - electron/preload.js: exposes them as `window.electronAPI.localFs` and `window.electronAPI.localTransfer`; the existing `invoke` allowlist is untouched. - src/types/electron.d.ts: typings for the new surface. - electron/main.cjs: registers the handlers. Follow-up PRs add the renderer side (local pane, drag-and-drop transfers, context menu). * fix(desktop): harden the local transfer bridge (origin allowlist, collision policy) Addresses the review on the transfer boundary: - The renderer no longer supplies a URL or headers. It sends `{ origin: "local" | "remote", route, deviceId }` and the main process resolves the target itself: fixed route allowlist (`uploadFileStream`, `downloadFileStream`), local = the embedded backend base, remote = the remote-sync config's URL (http/https only) with the stored JWT. Anything else is rejected before a request is made. `deviceId` is validated. - Downloads never rename or replace silently. The destination is checked first and `EEXIST` is returned unless the caller passes `overwrite: true`. Each transfer writes to its own `<dest>.<transferId>.termix-part` opened with `wx`, and publishes with `fs.link` / `COPYFILE_EXCL` (rename only when overwriting), so concurrent transfers to the same path cannot share or clobber a partial (`EBUSY` for the second). Partials are removed on failure or cancel. - New `local-fs:exists` handler so the renderer can ask before starting. - `createLocalFileHandlers` / `createTargetResolver` take their dependencies (net, shell, remote-sync getters) as parameters so the boundary is unit-testable without Electron. - src/backend/tests/electron/local-files.test.ts: target resolution and off-origin refusal, EEXIST / EBUSY / overwrite paths, unique partials and cleanup, upload multipart integrity (parsed with Busboy). * fix(desktop): Windows-safe replace for overwrite downloads `publishDownload()` used `rename(partial, dest)` for the explicit overwrite path. POSIX replaces the destination, but on Windows rename() onto an existing name commonly fails (EEXIST / EPERM, always while the file is open), so "Replace" did not actually work there. The overwrite path no longer renames onto an occupied name: 1. the current file is moved aside to a transfer-unique sibling (`<dest>.<transferId>.termix-replaced`) - renaming to a fresh name is safe on every platform; 2. the partial is published exclusively under the now-free name (the same `link` / `COPYFILE_EXCL` primitive the non-overwrite path uses); 3. the aside copy is deleted (retried once; if another process still holds it open on Windows it is left in place and logged rather than failing the transfer). Failure handling preserves the original: if step 1 fails (file in use) nothing has changed and the caller gets `EBUSY`; if step 2 fails the aside copy is moved back under its name and the error propagates. Replacing a folder with a file is refused with `EISDIR`; a destination that vanished mid-transfer falls back to the exclusive publish. The publish primitives take their filesystem operations as an injectable `publishFs` (default: real fs), and the tests drive them with a Windows-like fs whose rename() refuses to overwrite - so the strategy is verified without relying on POSIX rename-over-existing semantics: successful swap with no rename ever targeting an occupied name, original restored byte-for-byte when publishing fails, EBUSY with nothing touched when the file cannot be moved aside, EISDIR for folders, vanished destination, and the end-to-end overwrite through the download handler. --------- Co-authored-by: Max <maxim@cogitate.ai> * chore: update package lock * feat(file-manager): Termius-style Local | Remote dual pane with drag-and-drop transfers (desktop) Renderer side of the dual-pane file manager, built on the local filesystem bridge added in the previous PR. Desktop app only; the web build is unchanged (the toggle is hidden when `window.electronAPI.localFs` is absent). - New Local pane (LocalFilePane) next to the remote grid, toggled from the toolbar (Laptop icon); path, visibility and width are remembered in localStorage (`termix:file-manager:local-pane:*`). Grid and list views, hidden files toggle, breadcrumb navigation, New Folder. - Drag files/folders from the Local pane onto the remote grid to upload, and from the remote grid onto the Local pane to download. Both directions stream through the main process (`useLocalTransfers`) with a single progress toast per batch (speed, ETA, cancel). Finder drops onto the remote grid keep working as before. - Collision policy for downloads: destinations are checked first; if any exist the user is asked Replace / Skip for the batch. Skip, dismiss and timeout all mean skip - nothing is ever replaced without an explicit click, and the main process enforces the same rule (`EEXIST` unless `overwrite` is set). - Drag MIME contract: `application/x-termix-local-files` for local drags, `application/x-termix-remote-files` marker on the remote grid's internal drags, so each pane can tell the two apart from Finder drops. - Transfer targets are described as `{ origin, route, deviceId }` (`getSessionOrigin` in main-axios) - the renderer never hands the main process a URL. - i18n: new `fileManager.local*` keys in en.json only (other locales via Crowdin). - Tests: LocalFilePane rendering/navigation, local-transfer-utils (relative-path planning, size formatting). - Modified column uses the same `Mon DD HH:MM` / `Mon DD YYYY` (ls -l style) format as the remote grid, so both panes read alike. * docs: point security note to the docs root (old /security page is gone) (#1400) * chore: sync Crowdin translations * chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325) Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg). Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0) Updates `js-yaml` from 5.2.3 to 5.3.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0) Updates `pg` from 8.22.0 to 8.23.0 - [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md) - [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg) --- updated-dependencies: - dependency-name: "@anthropic-ai/sdk" dependency-version: 0.120.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: js-yaml dependency-version: 5.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: pg dependency-version: 8.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323) Bumps the dev-minor-updates group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` | | [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` | | [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` | | [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` | | [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` | Updates `@codemirror/commands` from 6.10.4 to 6.11.0 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@types/node` from 26.1.2 to 26.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react) Updates `electron` from 43.2.0 to 43.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1) Updates `globals` from 17.9.0 to 17.11.0 - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0) Updates `i18next` from 26.3.6 to 26.4.0 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0) Updates `lucide-react` from 1.28.0 to 1.33.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react) Updates `react-hook-form` from 7.84.0 to 7.85.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0) Updates `react-pdf` from 10.4.1 to 10.5.0 - [Release notes](https://github.com/wojtekmaj/react-pdf/releases) - [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf) Updates `typescript-eslint` from 8.66.0 to 8.67.0 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@types/node" dependency-version: 26.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 43.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: globals dependency-version: 17.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: i18next dependency-version: 26.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.33.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.85.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-pdf dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.67.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore: sync Crowdin translations * Update redirect-issues workflow configuration Updated the workflow to change the runner and modify the issue response message. * chore: sync Crowdin translations * Add Hetzner logo and referral link to README Added Hetzner logo with a referral link to README. * Fix Hetzner logo URL in README.md * docs: point security note to the feature security page The old /security page is gone and the docs root redirects to /install/, which loses the encryption context the sentence promises. Point the per-user secret and database encryption note at the canonical docs.termix.site/features/authentication/security/ page instead. Applied across all README locales. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: ssmurfgg04-gif <232103099+ssmurfgg04-gif@users.noreply.github.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> * fix: use i18n for host status tooltip labels (#1403) * chore: sync Crowdin translations * chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325) Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg). Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0) Updates `js-yaml` from 5.2.3 to 5.3.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0) Updates `pg` from 8.22.0 to 8.23.0 - [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md) - [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg) --- updated-dependencies: - dependency-name: "@anthropic-ai/sdk" dependency-version: 0.120.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: js-yaml dependency-version: 5.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: pg dependency-version: 8.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323) Bumps the dev-minor-updates group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` | | [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` | | [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` | | [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` | | [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` | Updates `@codemirror/commands` from 6.10.4 to 6.11.0 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@types/node` from 26.1.2 to 26.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react) Updates `electron` from 43.2.0 to 43.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1) Updates `globals` from 17.9.0 to 17.11.0 - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0) Updates `i18next` from 26.3.6 to 26.4.0 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0) Updates `lucide-react` from 1.28.0 to 1.33.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react) Updates `react-hook-form` from 7.84.0 to 7.85.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0) Updates `react-pdf` from 10.4.1 to 10.5.0 - [Release notes](https://github.com/wojtekmaj/react-pdf/releases) - [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf) Updates `typescript-eslint` from 8.66.0 to 8.67.0 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@types/node" dependency-version: 26.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 43.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: globals dependency-version: 17.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: i18next dependency-version: 26.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.33.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.85.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-pdf dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.67.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore: sync Crowdin translations * Update redirect-issues workflow configuration Updated the workflow to change the runner and modify the issue response message. * chore: sync Crowdin translations * fix: use i18n for host status tooltip labels (#1265) * fix: add missing hosts.status.* locale keys (fixes #1265) * fix: add hosts.status.* translation keys for i18n tooltip The buildStatusTooltip function calls t("hosts.status.available"), t("hosts.status.reachable"), t("hosts.status.offline"), and t("hosts.status.monitoringDisabled"), but the locale file only had "status": "Status" as a flat string. Replaced with a status object containing all four keys plus a "label" key preserving the original "Status" string. * fix: restore final newline in en.json Requested by ZacharyZcR in review feedback. * test: assert translated labels in buildStatusTooltip Per review feedback from ZacharyZcR: add focused tests that exercise buildStatusTooltip with a translator and assert the rendered labels rather than key paths. Covers all three status values, monitoring disabled, protocol list, and the no-key-path regression guard. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> * fix(workspaces): fall back when randomUUID is unavailable (#1397) * fix(terminal): preserve macOS Alt digit characters (#1398) * fix(ssh): verify resolved server host identity (#1419) * fix: add principals to Termix ID certificates (#1421) * chore: sync Crowdin translations * chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325) Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg). Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0) Updates `js-yaml` from 5.2.3 to 5.3.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0) Updates `pg` from 8.22.0 to 8.23.0 - [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md) - [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg) --- updated-dependencies: - dependency-name: "@anthropic-ai/sdk" dependency-version: 0.120.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: js-yaml dependency-version: 5.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: pg dependency-version: 8.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323) Bumps the dev-minor-updates group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` | | [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` | | [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` | | [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` | | [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` | Updates `@codemirror/commands` from 6.10.4 to 6.11.0 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@types/node` from 26.1.2 to 26.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react) Updates `electron` from 43.2.0 to 43.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1) Updates `globals` from 17.9.0 to 17.11.0 - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0) Updates `i18next` from 26.3.6 to 26.4.0 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0) Updates `lucide-react` from 1.28.0 to 1.33.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react) Updates `react-hook-form` from 7.84.0 to 7.85.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0) Updates `react-pdf` from 10.4.1 to 10.5.0 - [Release notes](https://github.com/wojtekmaj/react-pdf/releases) - [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf) Updates `typescript-eslint` from 8.66.0 to 8.67.0 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@types/node" dependency-version: 26.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 43.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: globals dependency-version: 17.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: i18next dependency-version: 26.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.33.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.85.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-pdf dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.67.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore: sync Crowdin translations * Update redirect-issues workflow configuration Updated the workflow to change the runner and modify the issue response message. * chore: sync Crowdin translations * Add Hetzner logo and referral link to README Added Hetzner logo with a referral link to README. * Fix Hetzner logo URL in README.md * chore: pull sponsor logos from the docs site * fix: add principals to Termix ID certificates --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> * fix(deps): resolve transitive security advisories (#1412) * chore: sync Crowdin translations * chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325) Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg). Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0) Updates `js-yaml` from 5.2.3 to 5.3.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0) Updates `pg` from 8.22.0 to 8.23.0 - [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md) - [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg) --- updated-dependencies: - dependency-name: "@anthropic-ai/sdk" dependency-version: 0.120.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: js-yaml dependency-version: 5.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: pg dependency-version: 8.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323) Bumps the dev-minor-updates group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` | | [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` | | [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` | | [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` | | [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` | Updates `@codemirror/commands` from 6.10.4 to 6.11.0 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@types/node` from 26.1.2 to 26.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react) Updates `electron` from 43.2.0 to 43.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1) Updates `globals` from 17.9.0 to 17.11.0 - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0) Updates `i18next` from 26.3.6 to 26.4.0 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0) Updates `lucide-react` from 1.28.0 to 1.33.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react) Updates `react-hook-form` from 7.84.0 to 7.85.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0) Updates `react-pdf` from 10.4.1 to 10.5.0 - [Release notes](https://github.com/wojtekmaj/react-pdf/releases) - [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf) Updates `typescript-eslint` from 8.66.0 to 8.67.0 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@types/node" dependency-version: 26.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 43.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: globals dependency-version: 17.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: i18next dependency-version: 26.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.33.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.85.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-pdf dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.67.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore: sync Crowdin translations * Update redirect-issues workflow configuration Updated the workflow to change the runner and modify the issue response message. * chore: sync Crowdin translations * Add Hetzner logo and referral link to README Added Hetzner logo with a referral link to README. * Fix Hetzner logo URL in README.md * chore: pull sponsor logos from the docs site * fix(deps): resolve transitive security advisories --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> * fix(sync): map nested host parent references (#1418) * fix(metrics): surface SSH host key changes (#1404) * fix(guacamole): coalesce VNC wheel floods and label meta keys by device (#1385) High-latency proxies like Cloudflare queue guacamole-common-js scroll clicks so the desktop keeps crawling after the user stops. Cap in-flight wheel buttons, and show Super/Cmd in the VNC toolbar on non-Windows clients. Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> * fix(file-manager): keep downloaded files inside the selected local folder Remote file names were turned into local destinations by splitting the relative remote path on "/" and concatenating each name with the platform separator. A POSIX file name may contain "\", ":" or end in a dot, so on Windows a remote "..\outside.txt" downloaded into C:\Downloads\selected was normalised to C:\Downloads\outside.txt - outside the folder the user picked, even with overwrite disabled. The main process only normalised destPath and never checked it against the selected root. Two independent layers now enforce containment: Renderer (local-transfer-utils.ts) - `assertSafeLocalComponent(name, separator)` validates each remote path component for the destination platform: never empty, "." or "..", never "/" or NUL; on Windows (separator "\") additionally no "\ : * ? " < > |", no control characters, no trailing dot/space, no reserved device names (CON, NUL, COM1...). Backslashes stay legal on macOS/Linux, where they are ordinary file-name characters and the result remains inside the folder. - `buildLocalDestination(localDir, relativePath, separator)` joins the validated components and asserts the result is strictly under localDir (case-insensitive on Windows). - useLocalTransfers builds every file and directory destination through it. Items that fail are skipped before any filesystem call and reported ("Skipped N item(s) whose names cannot be used on this computer"). Main process (electron/local-files.cjs) - `assertWithinRoot(rootPath, candidate, pathImpl)` resolves + normalises both paths and refuses anything that is the root itself, escapes it (".." after normalisation), is absolute relative to it (another drive, UNC) or contains empty/".." segments. `pathImpl` is injectable so the Windows rules run in tests on any OS. - downloadToLocal requires `rootPath` (the selected folder) and checks the destination before the request is made or any file is created; the ensure-dir handler applies the same check when a root is passed (used for the directory skeleton of downloaded trees). - LocalDownloadRequest / downloadSessionFileToLocal / ensureLocalDirectory carry the root. Tests - Renderer: ordinary nested folders on Windows; backslash traversal in a POSIX name; absolute, drive-qualified and UNC names; reserved names, trailing dots/spaces, control chars; POSIX traversal rejected while a POSIX-legal backslash name is kept inside the folder. - Main process (path.win32): nested destinations accepted incl. case differences; "selected\..\outside.txt" refused; other drive / UNC / sibling folder refused; missing root refused; end-to-end handler test that a POSIX "../outside.txt" download and an escaping ensure-dir are refused before any network traffic or disk write. * feat(file-manager): right-click context menu for the local pane Mirrors the remote grid's menu for the user's own disk. On an entry (or the current multi-selection): Open / Open folder, Upload to server, Reveal in Finder/Explorer, Rename (inline, F2), Copy Path, Move to Trash (confirmation toast, Del). On the background: New Folder, New File, Reveal, Show/Hide hidden files, Refresh (F5). Enter opens, Cmd/Ctrl+A selects all, Escape clears the selection. Deletion goes through shell.trashItem so it lands in the OS Trash and is recoverable; rename and create refuse names containing path separators and never overwrite an existing entry. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * feat(file-manager): resizable list-view columns in both panes Drag the boundary at the left edge of a column header (Modified, Owner, Size, Permissions on the remote grid; Modified, Size, Kind in the local pane) to change its width; the Name column takes whatever is left. Double-click a handle to reset that column. Widths are remembered per pane in localStorage. Finishing a drag over a sortable header no longer toggles the sort. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * feat(file-manager): pinned ".." parent entry in both panes Both the remote grid (list, grid and empty-folder states) and the local pane show a Termius-style ".." row pinned above the entries whenever the current folder has a parent. Double-clicking it goes up one level. It is also a drop target: local files dropped on it upload into the parent folder, remote rows dragged onto it move there, and remote items dropped on the local pane's ".." download into the parent folder. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * feat(file-manager): show/hide list-view columns from the header Right-click a list-view header (remote grid or local pane) to open a Columns menu and tick/untick Modified, Owner, Size, Permissions (remote) or Modified, Size, Kind (local). Hidden columns leave the grid template entirely so the Name column gets the space back; at least one optional column always stays on. The choice is remembered per pane alongside the column widths. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * feat(file-manager): sidebar toggle works on desktop too The toolbar's sidebar button now shows/hides the directories panel on desktop (persisted), while below md it still opens the mobile overlay. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * feat(file-manager): resizable directories sidebar The Trash/Directories sidebar can now be resized by dragging its right edge (160px minimum, up to 40% of the row); double-click the handle to restore the default 224px. The width is remembered. The same handle and persisted-width hook now also drive the local pane divider, replacing the inline implementation. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013Bn6K6xNAihgWZ5fMVWt1W * fix(metrics): support macOS/WIN hosts in stats collection (#1430) * fix(metrics): support macOS hosts in stats collection Host metrics collectors only ever ran Linux commands (/proc/*, ip, GNU df flags), so any macOS host always reported 0%/null for cpu, memory, uptime, network and disk. Detect the host platform once per poll and use vm_stat, sysctl, top, ifconfig and netstat on Darwin hosts instead. * fix(metrics): support Windows hosts in stats collection RDP/VNC hosts running Windows hit the same problem as macOS did: no /proc, no BSD tools, not even uname. Route CPU, memory, uptime, network and disk through PowerShell (WMI/CIM) when the host is detected as Windows, using -EncodedCommand so there's no cmd.exe quoting to fight with. * fix(metrics): use real macOS df/mount for disk collection BSD df's -T flag filters by filesystem type instead of printing one like GNU df does, so the previous macOS disk path was still running a GNU-only command and coming back empty. Now uses df -Pk plus mount output to build the filesystem type/percent list, filtering out the noisy APFS system volumes and devfs/autofs mounts. Verified on an M4 MacBook running the latest macOS - disk usage now reports correctly. * feat(file-manager): Termius-style Local | Remote dual pane with drag-and-drop transfers (desktop) (#1413) Integrate the reviewed change and its maintainer fixes into dev-2.8.0. Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs. * fix(terminal): persist Ctrl+/- font zoom so it survives option refreshes (#1399) Integrate the reviewed change and its maintainer fixes into dev-2.8.0. Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs. * Fix macOS terminal packaging and keyboard shortcuts. (#1417) Integrate the reviewed change and its maintainer fixes into dev-2.8.0. Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs. * fix(auth): skip TOTP only after verified WebAuthn user verification (#1420) Integrate the reviewed change and its maintainer fixes into dev-2.8.0. Validated with focused regression tests, type-check, lint, formatting, build, and the PR Check database jobs. * feat(hosts): add per-host Web Endpoints (direct or SSH-tunnelled web UIs) (#1416) * test: provide an in-memory localStorage for the vitest environment jsdom in this project ships without a localStorage global, so every suite that touched storage threw "Cannot read properties of undefined" during setup and failed wholesale -- 119 tests across 15 files, none of them actual product defects. Node only supplies localStorage with --localstorage-file, which persists to disk and is shared across test files. A per-process in-memory Storage is what tests want, so define one (plus sessionStorage) when the global is absent, alongside the existing matchMedia shim. Full suite goes from 15 failed files / 119 failed tests to 400 files and 2888 tests passing. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Fdjjsdaz6aFMyJr4h3Y6qj * feat(web-endpoints): add endpoint types and URL resolution First step of per-host Web Endpoints: a host declares web UIs it serves and opens them either directly at the host's address or through an SSH forward Termix establishes on demand. This commit is pure logic with no I/O, so it needs no mocks to test. resolveWebEndpointUrl expects an already-normalized path -- normalization is the storage boundary's job (a later commit), and duplicating it here would invite the two copies to drift. separatedTunnelHost is the one part that is a security control rather than a convenience. Cookies are keyed by host and ignore the port, and SameSite computes "site" as scheme + registrable domain -- also ignoring the port. A forward reached at the host string serving Termix is therefore same-site with Termix, which leaks the session both ways: the framed service receives the jwt cookie, and a Set-Cookie it returns lands in the jar Termix's own API calls read from. So a tunnel URL resolves to a different loopback spelling than the page's, and refuses outright when no alias exists. Only loopback literals qualify -- a same-registrable-domain alias could still answer Set-Cookie with a Domain attribute that reaches Termix. The cookie-separation tests were verified to fail against a resolver that returns the page host (4 failures), so they cannot pass vacuously. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(web-endpoints): validate and normalize endpoint config normalizeWebEndpoints is the enforcement point for values that reach an href and an iframe src, so the editor's constraints are UX rather than security. It drops any row it refuses instead of rejecting the whole host -- one bad endpoint must not make a host unsaveable or unlistable. Paths are checked for C0 controls and DEL by codepoint rather than by regex character class: "\t//evil.example" defeats a startsWith("//") guard, because the browser strips the control character and then follows the authority. bindHost lands both in a TCP listener and in a URL authority, so it is restricted to a bare host literal -- nothing carrying a scheme, port, path or credentials survives. bindHost and localPort are ignored on a direct endpoint, which never creates a forward. parseWebUiConfig never throws. A malformed stored value yields an empty endpoint list, so a half-written config cannot take out the whole host listing -- which is what dockerConfig's bare JSON.parse does today. The editor validator is a second implementation in a layer that cannot import backend route modules. Its accompanying test runs BOTH implementations over the same path and port samples, because drift here is invisible in the worst way: the editor accepts a row, the normalizer silently drops it, and the endpoint disappears on reload with no error. That agreement test was verified to fail (4 cases) when the editor's control-character check is removed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore(db): migrate the shared_credential_secrets foreign key rename Running `npm run schema:migrations` on an UNCHANGED schema emits these, so they are pre-existing drift between schema.ts and drizzle/, not something this branch introduced. Landing them alone, before the web-endpoint columns, so the feature's own migration is reviewable without an unrelated table rebuild sitting in the middle of it. Both forms are a foreign-key constraint rename only. Postgres drops and re-adds the constraint under a shorter name. SQLite has no ALTER for that, so drizzle emits the standard table rebuild -- verified data-preserving: CREATE lists 14 columns, INSERT...SELECT copies the same 14 in the same order, and both indexes are recreated. The SQLite file is in practice dead code: runRemoteMigrations throws for sqlite, which builds its schema from db/index.ts instead. It is kept rather than hand-trimmed because drizzle derives the meta snapshot from schema.ts regardless, so trimming the .sql while the snapshot advances would make the drift permanently invisible -- no future `generate` would re-emit it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(db): add enable_web_ui and web_ui_config columns Two columns on ssh_data mirroring the Docker pair. No show_web_ui_in_sidebar: every existing showXInSidebar column is vestigial -- they appear only in defaults, the export payload and tests, and gate no rendering -- so a fourth dead column plus a migration buys nothing. web_ui_config stores an object rather than a bare array so host-level web settings can be added later without a second migration. The column has to be declared in FOUR places, not one. SQLite never runs the drizzle migrations at all (runRemoteMigrations throws for sqlite), so the live default-dialect schema comes from hand-written DDL: 1. db/schema.ts, then the two generated dialect schemas and the migrations 2. db/index.ts CREATE TABLE -- fresh databases 3. db/index.ts addColumnIfNotExists -- existing databases 4. database.ts CREATE TABLE and its positional INSERT -- encrypted export Missing 2 or 3 breaks every host write on the default dialect while the migration file sits there looking correct. Two guards, both watched failing first. bootstrap-matches-schema-columns boots a real database and compares PRAGMA table_info against the drizzle definition for every table -- it reported ssh_data.enable_web_ui and ssh_data.web_ui_config missing before item 2/3 landed. A grep-based guard could not: db/index.ts names columns as snake_case strings, never the camelCase the schema uses. export-ddl-matches-schema-columns covers database.ts, which no booted database reaches. It caught a real defect while being written: the two new columns went into the INSERT list but the VALUES list still held 53 placeholders for 55 columns. Being positional, that shifts every later value by one. The placeholder-count assertion is now permanent. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(hosts): thread web endpoint config through host read and write paths A host field has to be enumerated by hand in nine places here, and "added a column, missed one update path" is this codebase's most repeated bug -- during the first attempt at this feature a field was missed at one of these points six separate times, each surfacing as a different mystery: endpoints that saved but never appeared, config that vanished on reload. Backend: host-normalizers (input type, CONNECT_LEVEL_FIELDS, boolean normalization, parse block), host.ts (create, update, both read paths, quick-connect defaults), host-bulk-routes (bulk update, import, reset). Renderer: host-export-payload, HostManagerData's sshHostToHost, tabUtils' hostToSSHHost, HostEditorData's form seed and payload builder. The three renderer mappers copy field by field, so an unlisted field is silently dropped -- which is how endpoints saved correctly and never appeared. webUiConfig is parsed with parseWebUiConfig rather than a bare JSON.parse. dockerConfig on the adjacent line uses a bare one, so a single malformed value takes out the whole host listing; that is a bug to avoid copying, not a convention to follow. All three write paths now clear webUiConfig when the feature is disabled. They disagreed before, and the export payload ships the config unconditionally -- so a host disabled without clearing still exported its endpoint list (internal hostnames, ports, paths) while the UI read as off, and re-enabling resurrected stale endpoints. webUiConfig is shared with connect-level recipients, unlike dockerConfig. A connect-level recipient is already authorized to open these tunnels, so withholding the config only breaks discovery while the flag advertises the feature. Docker's precedent does not transfer: its tab works without its config, whereas a web endpoint IS its config. The enumeration guard asserts every one of the nine files mentions the web endpoint field beside its Docker counterpart, and checks the Docker anchor is present too so it cannot pass vacuously if a file is restructured. The clear-on-disable assertion was rewritten after the first version passed with the guard deleted -- a loose regex matched unrelated sites. Both halves are now anchored on exact text and were watched failing. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(tunnel): report the real bound port, support idle close, reserve web: Three changes the web endpoint open route depends on, plus the name reservation that makes the scheme safe. Real bound port. Under sourcePort 0 the kernel assigns the port, but the runtime recorded the requested value -- so it advertised 0 and any caller reusing it failed. It now records tcpServer.address().port. Idle close, behind the new tunnelConfig.idleTimeoutMs. Web endpoint tunnels are opened on demand and must not outlive their use. The timer lives inside establishDirectTunnel because the socket set is only visible from that closure, polls at min(30s, timeout) so "empty for N" means roughly that rather than "empty at the instant of one N-spaced tick", and unrefs so it cannot hold the process open. It calls cleanupTunnelResources rather than close(): close() stops the listener but leaves the entry in activeTunnelRuntimes, so the open route would keep handing out a port nothing is listening on. Reserved names skip retry. handleDisconnect returns early for a "web:" name after a forced cleanup. maxRetries: 0 would NOT achieve this -- the retry path reads `maxRetries || 3`, so 0 falls through to 3. The cleanup is forced because cleanupTunnelResources no-ops while tunnelConnecting holds the name, and a web tunnel has no retry pass to self-heal a leaked runtime. That early return carries an identity guard, which is the subtle one. sourceClient.end() only STARTS an async teardown, so the SSH "close" event lands after a reopen may already have registered a NEW runtime under the same name. Acting by name alone would tear down the successor rather than the stale tunnel -- surfacing as a 200 with a good port followed by a silent connection reset and no error anywhere. handleDisconnect now takes the closing Client and returns early when the registered runtime belongs to someone else. The idle timer carries the same guard for the same reason. /ssh/tunnel/connect now rejects a user-supplied "web:" name with 400. validateTunnelConfig is no defence here: it returns true unconditionally for any name that is not the legacy 6-part format, so an authenticated user could otherwise create a real retry-configured tunnel that collides with a live web endpoint forward and silently loses its own reconnect behaviour. The manager tests run against a real TCP listener and real timers -- mixing fake timers with real socket I/O is a known route to a hanging test. Both were watched failing: reverting the bound port fails the port test, and swapping cleanupTunnelResources for close() fails the idle test, which asserts the ENTRY is gone rather than merely that the listener stopped. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(tunnel): add the web endpoint open route POST /ssh/tunnel/web-endpoint/open { hostId, endpointId } -> { port }. The host is resolved through the user-scoped resolveHostById, so an authenticated user cannot obtain a forward to a host id they do not own. The endpoint is re-normalized out of storage rather than trusted: the stored value predates any later tightening of the rules, and this is what a forward gets built from. An enabled flag is required as well as a present endpoint -- a bulk update that sends only { webUiConfig } can leave a configured endpoint on a host whose UI reads as off everywhere. Not gated to the desktop. The forward binds wherever this backend runs, as the server tunnels feature does, and the endpoint's own bindHost decides whether that is reachable from a browser. endpointHost: "127.0.0.1" is load-bearing, not cosmetic. connectSSHTunnel picks its strategy via shouldEstablishDirectTunnel -> isSingleHostTunnel, which keys on endpointHost -- setting only targetHost selects a different path and the forward never binds locally. connectSSHTunnel never rejects, and its promise resolves right after conn.connect() -- long before the SSH "ready" event populates activeTunnelRuntimes. Awaited is not connected, so waitForTunnelSettled polls the maps the manager already exports. Polling rather than adding a promise-returning variant: every existing caller is fire-and-forget by design, and changing that contract for one new caller is the larger blast radius. A probe forwardOut runs before returning 200. Without it the route succeeds the moment listen() does, and forwardOut is only attempted per inbound socket where failure is swallowed -- so the likeliest real error, nothing listening on the endpoint's port, reached the user as a blank frame and no message. Staleness is validated at open, never on save: host save lives in the database service and the runtimes live in the tunnel service, with no push between them. On reuse the route compares a fingerprint covering the endpoint's target AND the host's SSH identity, and reopens when it differs. An absent fingerprint means reuse, not staleness -- a reserved-prefixed runtime can only have been created here. Deletion, disabling and host removal then need no handling: nothing reopens the tunnel, so it idles out. Also closes an authorization gap this feature would otherwise have created. /ssh/tunnel/disconnect and /ssh/tunnel/cancel checked ownership only inside `if (config && config.sourceHostId)`, and web tunnels are deliberately absent from tunnelConfigs -- so the check never ran for them. Host ids are small sequential integers and endpoint ids are client-supplied, so the name is guessable and any authenticated user could force-close another user's tunnel. authorizeTunnelAction recovers the host id from the name and fails closed when it cannot; the tests were watched failing against the old behaviour. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(hosts): add the web endpoint client and per-origin certificate allowance The client posts a path relative to tunnelApi's base, which already includes /ssh -- a leading "/ssh" here resolves to /ssh/ssh/... and 404s on every call. The test asserts that on the captured runtime argument rather than by scanning source, so quoting style and indirection cannot fool it. Backend error messages are preserved rather than collapsed. 502 is this route's likeliest real failure and carries the actionable cause -- SSH auth rejected, host unreachable, nothing listening on the target port -- and handleApiError would replace all three with "Server error occurred". It stays as the fallback for bodies that carry no string reason, so a body shaped { error: <object> } cannot reach the user as "[object Object]". openWebEndpointExternally applies the same refusal gate as the embedded tab. Opening in the real browser is not the safer path: the cookie jar is the browser's either way, so a tunnel URL on the page's own host string leaks the session exactly as a frame would. The refusal happens before the forward is opened -- binding the port and then declining to navigate would be no protection. Certificate allowance covers the one case Electron's existing handling misses: direct access to a HOSTNAME over https. isPrivateNetworkHost matches IP literals only and sshData.ip has no IP validation, so https://nas.local:8006 fails the check and renders blank inside an iframe with no click-through -- Chromium offers no proceed option for subframes. Three properties of that allowance are deliberate and now pinned by tests, because each would otherwise be undone by a reasonable-looking simplification: - it is NOT wired into isInvalidCertificateAllowedForUrl, which also governs this process's own outbound TLS via getTlsVerificationOptions; - it is https-only, in both the check and the IPC handler, since a non-TLS origin in a TLS-error allowlist is meaningless and file:/ftp: must never be storable; and - entries carry a five-minute TTL refreshed on each registration. Main has no host-database access and cannot verify the renderer's claim that an origin is a configured endpoint, so the residual risk has to be a momentary window rather than one lasting until the app restarts. The handler stores the parsed origin, never the caller's string, so a path or wildcard cannot widen the allowance. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(hosts): add the Web UI editor tab Mounted as a Web UI sub-tab inside the SSH group, beside Docker, Tunnels, Files and Host Metrics, and laid out as two SectionCards following the tunnels editor: settings first, then the list it governs. There is a deliberate asymmetry with the sidebar here. The sidebar entry will appear on enableWebUi alone, because a direct endpoint needs no SSH -- but Web UI is an SSH sub-tab, so a host with SSH disabled cannot configure endpoints at all. That is the accepted behaviour and both halves are pinned by tests, so neither gets "fixed" into agreement later. tunnelAvailable is enableSsh && originIsLocal, resolved inside HostWebUiTab rather than in HostEditor.tsx, which is already ~2600 lines. It is NOT gated on isElectron(): the forward binds wherever the backend runs, exactly as the server tunnels feature does. resolveConnectionOrigin is called with connectionType "ssh" deliberately -- a tunnel endpoint always rides SSH, and "ssh" avoids the guacamole special case that forces "remote" for RDP/VNC/Telnet. Three input details that each prevent a silent data loss: - the id generator falls back off crypto.randomUUID, which is undefined outside a secure context -- a plain-http web deployment is a first-class target for direct+external and would otherwise throw on "Add endpoint"; - a new row gets a de-duplicated label, since labels are what identify an endpoint in the sidebar picker; and - the port field commits only a value the normalizer would keep. Number("") is 0, which the normalizer rejects, so clearing the field would otherwise write an endpoint that vanishes on save with no error. The tunnel fields carry three warnings: a non-loopback bind exposes the target's web UI unauthenticated to anyone who can reach the port; a loopback bind on a remote backend cannot be reached from a browser at all; and a tunnel reached at Termix's own hostname would hand the tunnelled service this session. All three are shown while configuring rather than only when the tab fails to load. The unavailable-tunnel reason is shown whenever tunnelling is unavailable, not only once a row asks for it -- a disabled dropdown option with no stated reason reads as the control being broken. Copy is reused verbatim from the previous iteration's reviewed strings rather than reworded. One test was written and then removed rather than kept: its name promised that switching to tunnel access clears ignoreCert, but Radix Select needs pointer APIs jsdom lacks, so the body only asserted the control existed. The clearing is covered where it is enforced, in the normalizer. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(hosts): open web endpoints from the sidebar and in a tab One sidebar entry per host, never one per endpoint: a host may declare up to 16, and a row of 16 identical globes is unusable. With a single endpoint the entry wears its label and acts directly; with several it carries no endpointId and the click opens a picker -- a DropdownMenu in the tray, a DropdownMenuSub in the Connect submenu. The entry is gated on enableWebUi ALONE, unlike every neighbouring action, which requires enableSsh. A direct endpoint needs no SSH; SSH matters only per-endpoint, for tunnel access, which the open route enforces. openTab gains a fourth optional parameter rather than overloading `restore`, which means something else. What was actually broken for two endpoints on one host was the LABEL -- tab ids are already `${name}-${type}-${Date.now()}`, so they never collided. All existing call sites keep working. The tab is passed the endpoint ID, not the endpoint object, so one deleted while its tab is open renders a plain message instead of throwing. Reload re-resolves and REMOUNTS. A direct endpoint's URL never changes and a live tunnel returns the same port on every open, so setUrl(resolved) would be a same-value setState that React bails out of, leaving the frame untouched -- Reload would silently do nothing in the two most common cases. A generation counter folded into the iframe key fixes that and doubles as the staleness guard for two resolutions landing out of order. The test captures the DOM node before and after, and was watched failing against a url-only key. PERSISTENT_TAB_TYPES is hoisted to module scope and exported so it can be asserted on -- it was a local const inside the component and therefore untestable. web-endpoint is deliberately excluded: an idle tunnel re-binds a fresh kernel-assigned port, so a restored tab could never hold a valid URL. Two notes on verification. `tsc -p tsconfig.json` passes vacuously in this repo -- tsconfig.json is a solution file with project references and does nothing without -b -- so `npm run type-check` (tsc -b --force) is the real check; it caught two insertions that had landed in the wrong function. And the one full-suite failure seen along the way was vault-signer-core, which passes in isolation and on re-run, is untouched by this branch, and is a flake under parallel load. Lint: 0 errors, 102 warnings, identical to the baseline on a clean tree. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(tunnel): register the web endpoint route under its /ssh path Every route in routes.ts registers the full "/ssh/tunnel/..." path -- nginx proxies /ssh through with the path intact -- and the client resolves "/tunnel/web-endpoint/open" against a baseURL that already ends in /ssh. The unprefixed registration therefore 404'd every call. No handler unit test could catch this: they call handleWebEndpointOpen directly and never touch registration. It surfaced only on opening a real tunnel against a deployed build, which is why that step exists. Added a registration test that captures the paths passed to app.post, so the invariant is checked without needing a server. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(hosts): apply session-cookie isolation to direct web endpoints The cookie guard only covered tunnel access. `unreachableTunnelReason` returned null for every `access: direct` endpoint, so WebEndpointTab framed the host's own address unconditionally. With Termix served at https://termix.example/ and a direct endpoint at https://termix.example:8443/, the browser attaches Termix's `jwt` to the framed request -- cookies are keyed by host and ignore the port -- and a `Set-Cookie` from that service lands in the jar both auth middlewares read before the Authorization header. Renames the helper to `webEndpointRefusalReason` so its scope is no longer tunnel-only, and gives it the endpoint's target host. A direct endpoint is now refused in a browser when that host shares Termix's cookie site, checked BEFORE any navigation in both open paths (embedded tab and external window) -- refusing after framing would leak on the first request. `sharesCookieSiteWithPage` treats an equal host as same-site (the jwt is set host-only, so the port is irrelevant) and also a parent/sub domain, which a `Set-Cookie: Domain=` from the target crosses. The suffix test is anchored on a dot boundary so `eviltermix.example` does not pass as `termix.example`. A precise eTLD+1 test would also catch sibling subdomains, but needs a public suffix list this app does not bundle. The desktop stays exempt: its session is Bearer-only with no `jwt` in the jar. Also drops "or change this endpoint to Direct" from the tunnel refusal copy, which pointed at the path that had this same leak. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> * fix(tunnel): preserve local status when remote names collide (#1431) * fix(desktop): honor remote sync certificate setting (#1432) * fix(file-manager): interpolate preview download filename (#1433) * fix(automations): dispatch SSH login events to triggers (#1434) * fix(hosts): preserve imported settings and remap jump hosts (#1435) * fix(hosts): preserve terminal switches across JSON transfer * fix(hosts): remap imported jump-host dependencies * fix(ssh): preserve agent framing after unsupported extensions (#1436) * fix(guacamole): return tokens before awaiting the client handshake (#1437) * fix(sidebar): unmount the host tree while its panel is hidden (#1438) * fix(terminal): leave macOS Option characters enabled by default (#1439) * fix(dashboard): open the enabled remote desktop protocol (#1440) * fix(version): preserve local version when update checks fail (#1441) * fix(sftp): create uploaded directories without shell access (#1442) * fix(desktop): honor explicit GPU acceleration opt-out (#1443) * fix(desktop): exclude remote-only host IDs from local tab persistence (#1444) * Enhance SFTP and terminal flows, stabilize desktop sync (#1377) * feat: add electron sftp c2s and terminal ai flows * fix: stabilize desktop sync and c2s tunnels * Improve remote tunnels and SFTP transfer feedback * chore: sync Crowdin translations * chore(deps): bump the prod-minor-updates group across 1 directory with 3 updates (#1325) Bumps the prod-minor-updates group with 3 updates in the / directory: [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript), [js-yaml](https://github.com/nodeca/js-yaml) and [pg](https://github.com/brianc/node-postgres/tree/HEAD/packages/pg). Updates `@anthropic-ai/sdk` from 0.116.0 to 0.120.0 - [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases) - [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md) - [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.116.0...sdk-v0.120.0) Updates `js-yaml` from 5.2.3 to 5.3.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.2.3...5.3.0) Updates `pg` from 8.22.0 to 8.23.0 - [Changelog](https://github.com/brianc/node-postgres/blob/master/CHANGELOG.md) - [Commits](https://github.com/brianc/node-postgres/commits/pg@8.23.0/packages/pg) --- updated-dependencies: - dependency-name: "@anthropic-ai/sdk" dependency-version: 0.120.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: js-yaml dependency-version: 5.3.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: pg dependency-version: 8.23.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-minor-updates group across 1 directory with 10 updates (#1323) Bumps the dev-minor-updates group with 10 updates in the / directory: | Package | From | To | | --- | --- | --- | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.4` | `6.11.0` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.1.2` | `26.2.0` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.5` | `6.1.0` | | [electron](https://github.com/electron/electron) | `43.2.0` | `43.4.1` | | [globals](https://github.com/sindresorhus/globals) | `17.9.0` | `17.11.0` | | [i18next](https://github.com/i18next/i18next) | `26.3.6` | `26.4.0` | | [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.28.0` | `1.33.0` | | [react-hook-form](https://github.com/react-hook-form/react-hook-form) | `7.84.0` | `7.85.0` | | [react-pdf](https://github.com/wojtekmaj/react-pdf/tree/HEAD/packages/react-pdf) | `10.4.1` | `10.5.0` | | [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.66.0` | `8.67.0` | Updates `@codemirror/commands` from 6.10.4 to 6.11.0 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@types/node` from 26.1.2 to 26.2.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `@vitejs/plugin-react` from 6.0.5 to 6.1.0 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.0/packages/plugin-react) Updates `electron` from 43.2.0 to 43.4.1 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v43.2.0...v43.4.1) Updates `globals` from 17.9.0 to 17.11.0 - [Release notes](https://github.com/sindresorhus/globals/releases) - [Commits](https://github.com/sindresorhus/globals/compare/v17.9.0...v17.11.0) Updates `i18next` from 26.3.6 to 26.4.0 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.6...v26.4.0) Updates `lucide-react` from 1.28.0 to 1.33.0 - [Release notes](https://github.com/lucide-icons/lucide/releases) - [Commits](https://github.com/lucide-icons/lucide/commits/1.33.0/packages/lucide-react) Updates `react-hook-form` from 7.84.0 to 7.85.0 - [Release notes](https://github.com/react-hook-form/react-hook-form/releases) - [Changelog](https://github.com/react-hook-form/react-hook-form/blob/master/CHANGELOG.md) - [Commits](https://github.com/react-hook-form/react-hook-form/compare/v7.84.0...v7.85.0) Updates `react-pdf` from 10.4.1 to 10.5.0 - [Release notes](https://github.com/wojtekmaj/react-pdf/releases) - [Commits](https://github.com/wojtekmaj/react-pdf/commits/v10.5.0/packages/react-pdf) Updates `typescript-eslint` from 8.66.0 to 8.67.0 - [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases) - [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md) - [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.67.0/packages/typescript-eslint) --- updated-dependencies: - dependency-name: "@codemirror/commands" dependency-version: 6.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@types/node" dependency-version: 26.2.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.1.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: electron dependency-version: 43.4.1 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: globals dependency-version: 17.11.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: i18next dependency-version: 26.4.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: lucide-react dependency-version: 1.33.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-hook-form dependency-version: 7.85.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: react-pdf dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates - dependency-name: typescript-eslint dependency-version: 8.67.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: dev-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore: sync Crowdin translations * Update redirect-issues workflow configuration Updated the workflow to change the runner and modify the issue response message. * test(sftp): verify local collection limit boundaries --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> * chore: increment ver * fix: allow any origin by default when CORS_ALLOWED_ORIGINS is unset * feat(file-manager): parallel local transfers (#1446) Uploads from the Local pane (and downloads to it) ran strictly one file after another. Batches of many small files were bound by per-file latency rather than bandwidth. - `runWithConcurrency(items, limit, worker, shouldStop)`: a bounded worker pool that dispatches in order, keeps at most `limit` transfers in flight, and stops dispatching once cancelled while letting in-flight items finish. Worker errors are handled by the worker (one failure never aborts the batch). - useLocalTransfers: both directions go through the pool. Remote / local directory skeletons are still created up front, so file order does not matter. The batch runner now tracks a set of in-flight transfer ids (Cancel cancels all of them), sums bytes across in-flight transfers plus settled ones for the progress bar / speed, and shows how many files are moving at once. - New preference "Simultaneous File Transfers" (1-8, default 4) in the profile settings, stored in localStorage (`termix:file-manager:transfer-concurrency`) and part of the storage snapshot. 1 restores the previous sequential behaviour; the hint suggests lowering it for servers that limit SFTP channels. - Remote directories are created with the now-idempotent mkdir (#1442) without swallowing its errors, so a real failure stops the batch up front instead of surfacing as N per-file failures. When files do fail, the summary toast carries the first underlying reason (e.g. the backend's 401 message) instead of a bare "Upload failed". - Tests: pool never exceeds the limit and drains everything, stops on cancel, tolerates a failing item, handles empty input; preference clamping and persistence; bridge-level concurrent uploads/downloads with a mid-flight cancel leave every other file intact and no partials. Co-authored-by: Max <maxim@cogitate.ai> * fix(sftp): complete streamed uploads and stop pre-parsing chunk bodies * fix(desktop): stop setting Content-Length on local download requests * fix(file-manager): keep drop overlays in view when the list is scrolled * fix(file-manager): let remote rows be dropped on the local pane * fix(desktop): authenticate local transfers with the renderer's token * chore: update release notes * chore: remove unused gitlab ci and argocd deploy configs * chore: remove unused files * feat: improve loading animation * fix(shell): stop tab reorder from resetting terminals and tab indicator Keep the tab-content portal order stable so reordering tabs doesn't retrigger React's offscreen pass and dispose live terminals. Also stop the active tab indicator from teleporting during a drag, and fix the drag ghost's size/border mismatch. * fix(shell): hand-roll the tab indicator instead of a shared layoutId Framer's layoutId could measure the wrong tab's rect during a reorder and land on an inactive tab, or leave a stray line visible mid-drag. Now it reads the active tab's own DOM rect directly and hides while dragging. * fix(hosts): fix right-click menu position and unwanted tray expand * chore: update release notes * fix(terminal): stop autosuggestion ghost text overlapping typed input Position was computed from cursorX before server echo landed, causing a stale read that overlapped just-typed characters on fast local input. * chore: update release notes for v2.8.0 * fix(sftp): rebuild transfer tab for web, fix menu offset bug Drop the electron-only local mode and dead code, i18n all strings, fix double progress toasts and a wrong pane refresh on move. Fix context menus rendering offset due to a lingering CSS transform from the tab-switch animation. Move SFTP next to SSH Tools in the rail. * fix(file-manager): shrink oversized .. entry, navigate on single click * fix: make select2 component use rounded corners * fix: rebuild terminal AI assistant on the real backend Removes the Electron-only Agent Mode/AI Command Helper that bypassed admin/user gating and ran commands with no approval step. Replaces it with a terminal-docked panel on the same gated backend as the AI tab, adds a per-host toggle (off by default), moves it into the toolbar, and fixes proposal ordering and run-in-terminal execution. * fix(file-manager): remove duplicate borders in toolbar view toggle Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix: separate registration toggle from step ca settings * fix: collab room bugs and add room deletion Accent-colored new room button, fix fullscreen guest view layout and duplicate view-only badges, self-heal stale presenter state, add delete room for persistent rooms. * refactor: move host-identity helpers to hosts core Used by docker, file-manager, and terminal alike, so it belongs at the hosts root instead of under terminal/. * refactor: move host-session-status singleton to hosts core metrics subscribed to terminal's private online/offline pub-sub module. Moved to hosts core so both sides depend on a shared module instead of metrics reaching into terminal. Marked the subscribe call with PLUGIN-EVENT for the future event bus. * refactor: split generic automation event notify out of metrics notifyAutomationInternalEvent was in hosts/metrics/automation-bridge.ts but is used by tunnel, host routes, user routes, and automations engine itself, not just metrics. Moved it to hosts/automation-events.ts so those callers depend on a shared module instead of metrics internals. Left the metrics-specific notifiers in place. * feat: add plugin system schema and repositories Adds plugins, plugin_permission_grants, plugin_registries, and plugin_install_counts tables plus their repositories. No routes or UI yet. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat: add runtime rail item and tab component registries for plugins * feat: support runtime-registered permission groups Adds register/unregister for plugin permission groups so the RBAC catalog and validation can grow beyond the static list. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat: add plugin-api nginx route and dispatcher stub * feat: add plugin manifest schema and validator * chore: update release notes * chore: update i18n for local/remote file manager * feat: add toggle to show/hide app rail pin button * feat(host-metrics): add NVIDIA GPU metrics card (#1452) * feat(host-metrics): add NVIDIA GPU metrics card Collect per-GPU utilization, VRAM, temperature, power, fan speed and the processes using each GPU over SSH with nvidia-smi. The collector exits immediately when nvidia-smi is missing, so hosts without a GPU pay almost nothing per poll. The GPU card is opt-in: it is available from the Add card tray but is not part of new-host defaults or any UI preset. It shows live sparklines for utilization and VRAM per GPU. Adaptive polling now also watches GPU readings and the GPU process count, so it no longer backs off on hosts where only the GPU is busy. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F2ctuPwiesLzhF6XQiozm8 * fix(host-metrics): draw sparklines from the first metrics sample The first sample fetched when the tab connects was shown but never added to the sparkline history, so every sparkline (CPU, memory, disk, GPU) stayed empty until the second poll, a full metrics interval later (about 35 s with the default 30 s interval). Record the first sample like every later one, so the lines appear as soon as the tab loads. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F2ctuPwiesLzhF6XQiozm8 * Fix logical condition for memory percentage calculation Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * fix: annotate local transfer plan type to fix CI type-check * fix: move connection toolbar settings to bottom of host editor general tab * chore: add debug logging for macOS sharp packaging failure Temporary diagnostic to find which phase drops @img/sharp-darwin-x64 from the packaged app. Revert once root cause is found. * fix: correct macOS sharp verify script for universal build layout electron-builder uses mergeASARs: false, so universal builds ship app-x64.asar.unpacked and app-arm64.asar.unpacked side by side instead of a single app.asar.unpacked. The verify script only checked the single-asar path, so it always failed on universal/mas artifacts even when packaging was correct. * fix: update sharp verify test fixtures for universal build layout The test built fake apps using the single app.asar.unpacked layout, which doesn't match how universal builds are actually packaged now (app-x64.asar.unpacked / app-arm64.asar.unpacked side by side). * chore: update readme * fix: guard against missing rooms array in collab list response * fix: distinct guac connection log stages, RDP black screen before failure * fix: proxy /collab routes in nginx configs * fix: stop tab-switch flash and host metrics/proxmox reconnect Tab DOM visibility now syncs before paint instead of after, and switching tabs no longer tears down live metrics connections. * fix: tab bar flashing, growing, and merged separators Terminal tabs no longer flash when switching, the enter animation no longer nudges layout size, and a stray transform on resting tabs no longer causes the border between tabs to vanish at some zoom levels. * fix: match select trigger height to inputs in web UI editor * chore: lint, format, and bump version to 2.8.0 * chore: sync Crowdin translations for 2.8.0 --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> Co-authored-by: Angad Singh <7099405+singhangadin@users.noreply.github.com> Co-authored-by: Angad Singh <angad@singhangad.in> Co-authored-by: Neo <54811660+neooriginal@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Wali Lambert <98448225+YatoVoid@users.noreply.github.com> Co-authored-by: Nasif Rahman <44437976+nasif-naseef@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: vietanhtwdk <vietanhtruongwdk@gmail.com> Co-authored-by: inontz <inontz@icloud.com> Co-authored-by: inontz <inontz@users.noreply.github.com> Co-authored-by: Max Serov <133950708+maxser0v@users.noreply.github.com> Co-authored-by: Max <maxim@cogitate.ai> Co-authored-by: ssmurfgg04-gif <ssmurfgg04@gmail.com> Co-authored-by: ssmurfgg04-gif <232103099+ssmurfgg04-gif@users.noreply.github.com> Co-authored-by: ZacharyZcR <payasonorahc@protonmail.com> Co-authored-by: slsgzs-cloud <slsgzs@gmail.com> Co-authored-by: anshtsolanki-sketch <anshtsolanki@gmail.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: tcezarl <tomescu.cezar.laurentiu@gmail.com> Co-authored-by: Anton Priestley <anton@priestley.me> Co-authored-by: Hakim M <hakimmarsudi@outlook.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Adel Alzubeir <14052842+Adelzu@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
+16



![dependabot[bot]](/assets/img/avatar_default.png)





Luke Gustafson
ZacharyZcR
Angad Singh
Angad Singh
Neo
dependabot[bot]
Wali Lambert
Nasif Rahman
Claude Opus 5
vietanhtwdk
inontz
inontz
Max Serov
Max
ssmurfgg04-gif
ssmurfgg04-gif
ZacharyZcR
slsgzs-cloud
anshtsolanki-sketch
Cursor
tcezarl
Anton Priestley
Hakim M
copilot-swe-agent[bot]
Adel Alzubeir
Copilot Autofix powered by AI authored and
GitHub committed 2026-09-20 14:56:39 -05:00
1 parent
9c04860821
commit
fef8a5f28a
692 files changed
+334737
-5210
No files matched your search
@@ -51,8 +51,7 @@ function normalizeHost(hostname: string): string {
|
||||
/**
|
||||
* True when the URL names a destination the SSRF guard would refuse. A bare
|
||||
* hostname that is not an IP literal (e.g. "ollama.internal") is treated as
|
||||
* private only if it is "localhost" -- anything else resolves through DNS and
|
||||
* is caught at connect time by the guard instead.
|
||||
* private only if it is "localhost" -- anything else needs DNS resolution.
|
||||
*/
|
||||
export function isPrivateDestination(rawUrl: string): boolean {
|
||||
let url: URL;
|
||||
@@ -98,12 +97,18 @@ export function evaluateEgress(
|
||||
|
||||
const host = normalizeHost(url.hostname);
|
||||
const isPrivate = isPrivateDestination(rawUrl);
|
||||
const normalized = allowlist.map((entry) => entry.trim().toLowerCase());
|
||||
|
||||
// An explicitly allowlisted hostname may resolve to a private address. It
|
||||
// must use the private fetch path; sending it through safeOutboundFetch
|
||||
// would reject it after DNS resolution and make hostname allowlist entries
|
||||
// ineffective. Only administrators can write this list.
|
||||
if (normalized.includes(host)) {
|
||||
return { allowed: true, isPrivate: true };
|
||||
}
|
||||
|
||||
if (!isPrivate) return { allowed: true, isPrivate: false };
|
||||
|
||||
const normalized = allowlist.map((entry) => entry.trim().toLowerCase());
|
||||
if (normalized.includes(host)) return { allowed: true, isPrivate: true };
|
||||
|
||||
return {
|
||||
allowed: false,
|
||||
isPrivate: true,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { getErrorMessage } from "../utils/error-message.js";
|
||||
import express from "express";
|
||||
import type { AuthenticatedRequest } from "../../types/index.js";
|
||||
import { PermissionManager } from "../utils/permission-manager.js";
|
||||
import { AuthManager } from "../utils/auth-manager.js";
|
||||
import { databaseLogger } from "../utils/logger.js";
|
||||
import {
|
||||
@@ -36,6 +37,7 @@ import { applyProposal } from "./tools/executor.js";
|
||||
const router = express.Router();
|
||||
|
||||
const authManager = AuthManager.getInstance();
|
||||
const permissionManager = PermissionManager.getInstance();
|
||||
const authenticateJWT = authManager.createAuthMiddleware();
|
||||
const requireDataAccess = authManager.createDataAccessMiddleware();
|
||||
const aiGate = createAiGate();
|
||||
@@ -97,6 +99,7 @@ router.get("/status", authenticateJWT, async (req, res) => {
|
||||
router.get(
|
||||
"/providers",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.use"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -147,6 +150,7 @@ router.get(
|
||||
router.post(
|
||||
"/providers",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.manage_providers"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -224,6 +228,7 @@ router.post(
|
||||
router.patch(
|
||||
"/providers/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.manage_providers"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -286,6 +291,7 @@ router.patch(
|
||||
router.delete(
|
||||
"/providers/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.manage_providers"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -358,6 +364,7 @@ router.delete(
|
||||
router.post(
|
||||
"/probe-models",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.manage_providers"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -423,6 +430,7 @@ router.post(
|
||||
router.get(
|
||||
"/providers/:id/models",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.use"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -470,6 +478,7 @@ router.get(
|
||||
router.get(
|
||||
"/conversations",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.use"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -510,6 +519,7 @@ router.get(
|
||||
router.get(
|
||||
"/conversations/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.use"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -560,6 +570,7 @@ router.get(
|
||||
router.delete(
|
||||
"/conversations/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.use"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -622,6 +633,7 @@ router.delete(
|
||||
router.post(
|
||||
"/chat/stream",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.use"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -840,6 +852,7 @@ router.post(
|
||||
router.post(
|
||||
"/proposals/:id/apply",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.apply_proposals"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
@@ -909,6 +922,129 @@ router.post(
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /ai/proposals/{id}/mark-run-in-terminal:
|
||||
* post:
|
||||
* summary: Record that a run_command proposal was executed in an open terminal
|
||||
* description: >
|
||||
* For the terminal-docked assistant only. The command is typed into the
|
||||
* user's already-open SSH session client-side, not re-run over a pooled
|
||||
* connection here; this just marks the proposal applied with the output
|
||||
* the client captured, so the card and the pooled-connection /apply path
|
||||
* stay in sync without running the command twice.
|
||||
* tags:
|
||||
* - AI
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* hostId:
|
||||
* type: integer
|
||||
* summary:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Proposal marked applied.
|
||||
* 400:
|
||||
* description: The proposal is not a run_command proposal, or the hostId does not match.
|
||||
* 404:
|
||||
* description: Proposal not found.
|
||||
*/
|
||||
router.post(
|
||||
"/proposals/:id/mark-run-in-terminal",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.apply_proposals"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
const userId = (req as AuthenticatedRequest).userId as string;
|
||||
const id = parseId(req.params.id);
|
||||
if (!id) return res.status(400).json({ error: "Invalid proposal id" });
|
||||
|
||||
const { hostId, summary } = req.body ?? {};
|
||||
const resolvedHostId = parseId(hostId);
|
||||
if (!resolvedHostId) {
|
||||
return res.status(400).json({ error: "hostId is required" });
|
||||
}
|
||||
|
||||
const repository = createCurrentAiRepository();
|
||||
|
||||
try {
|
||||
const stored = await repository.findProposal(id, userId);
|
||||
if (!stored) return res.status(404).json({ error: "Proposal not found" });
|
||||
if (stored.kind !== "propose_run_command") {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "Only run_command proposals can be marked this way" });
|
||||
}
|
||||
if (stored.status !== "pending") {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: `This proposal was already ${stored.status}` });
|
||||
}
|
||||
|
||||
let payload: Record<string, unknown>;
|
||||
try {
|
||||
payload = JSON.parse(stored.payload) as Record<string, unknown>;
|
||||
} catch {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "The proposal payload is invalid" });
|
||||
}
|
||||
if (parseId(payload.hostId) !== resolvedHostId) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "This proposal is for a different host" });
|
||||
}
|
||||
|
||||
const resultSummary =
|
||||
typeof summary === "string" && summary.trim()
|
||||
? summary.trim().slice(0, 2000)
|
||||
: "Run in the open terminal session";
|
||||
await repository.setProposalStatus(id, userId, "applied", resultSummary);
|
||||
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
await logAudit({
|
||||
userId,
|
||||
username: await getAuditUsername(userId),
|
||||
action: "ai_proposal_applied",
|
||||
resourceType: "ai_proposal",
|
||||
resourceId: String(id),
|
||||
resourceName: stored.kind,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
success: true,
|
||||
});
|
||||
|
||||
res.json({ success: true, summary: resultSummary });
|
||||
} catch (err) {
|
||||
const message = getErrorMessage(
|
||||
err,
|
||||
"Failed to mark the proposal applied",
|
||||
);
|
||||
databaseLogger.error(
|
||||
"Failed to mark AI proposal applied in terminal",
|
||||
err,
|
||||
{
|
||||
operation: "ai_proposal_mark_run_in_terminal_failed",
|
||||
userId,
|
||||
},
|
||||
);
|
||||
res.status(400).json({ error: message });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /ai/proposals/{id}/reject:
|
||||
@@ -931,6 +1067,7 @@ router.post(
|
||||
router.post(
|
||||
"/proposals/:id/reject",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("ai.use"),
|
||||
requireDataAccess,
|
||||
aiGate,
|
||||
async (req, res) => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getFetchDispatcher } from "../../utils/proxy-agent.js";
|
||||
import { fetchWithProxy } from "../../utils/proxy-agent.js";
|
||||
import { safeOutboundFetch } from "../../utils/safe-outbound-fetch.js";
|
||||
import { evaluateEgress, readPrivateAllowlist } from "../egress.js";
|
||||
import { AiProviderError } from "./types.js";
|
||||
@@ -9,8 +9,8 @@ import { AiProviderError } from "./types.js";
|
||||
*
|
||||
* Public hosts use safeOutboundFetch, which re-checks the resolved address at
|
||||
* connect time. Allowlisted private hosts cannot use it (its whole job is to
|
||||
* refuse them), so they fall back to plain fetch with the proxy dispatcher --
|
||||
* still respecting corporate proxy configuration.
|
||||
* refuse them), so they use the installed Undici fetch implementation with
|
||||
* its matching proxy dispatcher -- still respecting proxy configuration.
|
||||
*/
|
||||
export async function providerFetch(
|
||||
url: string,
|
||||
@@ -24,10 +24,7 @@ export async function providerFetch(
|
||||
}
|
||||
|
||||
if (decision.isPrivate) {
|
||||
return fetch(url, {
|
||||
...init,
|
||||
dispatcher: getFetchDispatcher(url),
|
||||
} as RequestInit);
|
||||
return fetchWithProxy(url, init);
|
||||
}
|
||||
|
||||
return safeOutboundFetch(url, init) as unknown as Promise<Response>;
|
||||
|
||||
@@ -5,12 +5,10 @@ import type { AiTool, ToolDefinitionShape } from "./types.js";
|
||||
/**
|
||||
* The allowlist, and the security boundary for the whole feature.
|
||||
*
|
||||
* A model can only ever invoke what appears here. This matters more than usual
|
||||
* in this codebase: PermissionManager.requirePermission exists but is currently
|
||||
* mounted on zero routes, so RBAC strings are a vocabulary for the admin role
|
||||
* editor rather than route enforcement. "The assistant cannot reach credentials
|
||||
* or user administration" is therefore a property of this list, not of the
|
||||
* permission system.
|
||||
* A model can only ever invoke what appears here. Route-level RBAC gates the
|
||||
* HTTP API, but tools run in-process with the calling user's identity and never
|
||||
* pass through a router, so "the assistant cannot reach credentials or user
|
||||
* administration" is a property of this list, not of the permission system.
|
||||
*
|
||||
* Anything touching credentials, vaults, RBAC, users, identity, certificates,
|
||||
* SSO or instance settings is deliberately absent and must stay absent.
|
||||
@@ -51,6 +49,8 @@ export const FORBIDDEN_DOMAINS = [
|
||||
"identity",
|
||||
"certificate",
|
||||
"opkssh",
|
||||
"stepca",
|
||||
"step_ca",
|
||||
"acme",
|
||||
"ssl",
|
||||
"audit",
|
||||
|
||||
@@ -267,7 +267,7 @@ export class AutomationEngine {
|
||||
// its own failure, so the event is not emitted for runs that this event
|
||||
// already started.
|
||||
if (request.triggerType !== "internal_event") {
|
||||
import("../hosts/metrics/automation-bridge.js")
|
||||
import("../hosts/automation-events.js")
|
||||
.then(({ notifyAutomationInternalEvent }) =>
|
||||
notifyAutomationInternalEvent(
|
||||
"automation_failed",
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { safeOutboundFetch } from "../utils/safe-outbound-fetch.js";
|
||||
import { readNotificationPrivateAllowlist } from "../utils/notification-egress.js";
|
||||
|
||||
/**
|
||||
* Outbound HTTP for automation steps and notification channels.
|
||||
*
|
||||
* safeOutboundFetch refuses private and loopback addresses, which is the right
|
||||
* default against SSRF but also blocks the self-hosted ntfy or Gotify sitting
|
||||
* on a LAN that many installs actually use. Rather than weaken the guard
|
||||
* globally, a destination can opt in explicitly; everything else about the
|
||||
* guard (scheme, embedded credentials, no redirects) still applies.
|
||||
* on a LAN that many installs actually use. Private delivery therefore needs
|
||||
* both a channel opt-in and an exact host in the administrator allowlist;
|
||||
* scheme validation, DNS pinning and redirect refusal remain in force.
|
||||
*/
|
||||
export interface AutomationFetchOptions {
|
||||
method?: string;
|
||||
@@ -52,8 +53,8 @@ export async function automationFetch(
|
||||
}
|
||||
|
||||
/**
|
||||
* The opt-in path. Keeps the parts of the guard that are always right and
|
||||
* drops only the address blocklist.
|
||||
* The opt-in path still goes through the guarded resolver. Only an exact host
|
||||
* authorized by an administrator may resolve to a private address.
|
||||
*/
|
||||
async function privateNetworkFetch(
|
||||
rawUrl: string,
|
||||
@@ -73,5 +74,6 @@ async function privateNetworkFetch(
|
||||
throw new Error("URLs with embedded credentials are not allowed");
|
||||
}
|
||||
|
||||
return fetch(rawUrl, { ...init, redirect: "error" });
|
||||
const allowlist = await readNotificationPrivateAllowlist();
|
||||
return safeOutboundFetch(rawUrl, init, allowlist);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import terminalRoutes from "./routes/terminal.js";
|
||||
import sessionLogRoutes from "./routes/session-log-routes.js";
|
||||
import guacamoleRoutes from "../hosts/guacamole/routes.js";
|
||||
import sessionSharingRoutes from "../hosts/session-sharing/routes.js";
|
||||
import collabRoutes from "../hosts/collab/routes.js";
|
||||
import networkTopologyRoutes from "./routes/network-topology.js";
|
||||
import rbacRoutes from "./routes/rbac.js";
|
||||
import openTabsRoutes from "./routes/open-tabs.js";
|
||||
@@ -29,10 +30,12 @@ import termixIdRoutes from "./routes/termix-id.js";
|
||||
import { registerAuditLogRoutes } from "./routes/audit-log-routes.js";
|
||||
import { registerTailscaleRoutes } from "./routes/tailscale-routes.js";
|
||||
import vaultRoutes from "./routes/vault.js";
|
||||
import secretSourceRoutes from "./routes/secret-sources.js";
|
||||
import alertRulesRoutes from "./routes/alert-rules-routes.js";
|
||||
import aiRoutes from "../ai/index.js";
|
||||
import automationsRoutes from "./routes/automations.js";
|
||||
import syncRoutes from "./routes/sync.js";
|
||||
import pluginApiRoutes from "./routes/plugin-api-routes.js";
|
||||
import { createCorsMiddleware } from "../utils/cors-config.js";
|
||||
import { createCompressionMiddleware } from "../utils/compression-config.js";
|
||||
import fs from "fs";
|
||||
@@ -73,7 +76,7 @@ const __dirname = path.dirname(__filename);
|
||||
|
||||
const app = express();
|
||||
|
||||
app.set("trust proxy", true);
|
||||
app.set("trust proxy", "loopback");
|
||||
|
||||
const authManager = AuthManager.getInstance();
|
||||
const authenticateJWT = authManager.createAuthMiddleware();
|
||||
@@ -259,9 +262,8 @@ async function fetchGitHubAPI<T>(
|
||||
}
|
||||
}
|
||||
|
||||
app.use(bodyParser.json({ limit: "1gb" }));
|
||||
app.use(bodyParser.urlencoded({ limit: "1gb", extended: true }));
|
||||
app.use(bodyParser.raw({ limit: "5gb", type: "application/octet-stream" }));
|
||||
app.use(bodyParser.json({ limit: "2mb" }));
|
||||
app.use(bodyParser.urlencoded({ limit: "2mb", extended: true }));
|
||||
app.use(cookieParser());
|
||||
app.use((_req, res, next) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
@@ -382,7 +384,7 @@ app.get("/version", authenticateJWT, async (req, res) => {
|
||||
operation: "version_check",
|
||||
rawTag,
|
||||
});
|
||||
return res.status(401).send("Remote Version Not Found");
|
||||
return res.json({ localVersion, status: "unknown" });
|
||||
}
|
||||
|
||||
const versionComparison = compareSemver(localVersion, remoteVersion);
|
||||
@@ -413,7 +415,7 @@ app.get("/version", authenticateJWT, async (req, res) => {
|
||||
databaseLogger.error("Version check failed", err, {
|
||||
operation: "version_check",
|
||||
});
|
||||
res.status(500).send("Fetch Error");
|
||||
res.json({ localVersion, status: "unknown" });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -791,6 +793,7 @@ app.post("/database/export", authenticateJWT, async (req, res) => {
|
||||
jump_hosts TEXT,
|
||||
enable_file_manager INTEGER NOT NULL DEFAULT 1,
|
||||
enable_docker INTEGER NOT NULL DEFAULT 0,
|
||||
enable_web_ui INTEGER NOT NULL DEFAULT 0,
|
||||
show_terminal_in_sidebar INTEGER NOT NULL DEFAULT 1,
|
||||
show_file_manager_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_tunnel_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
@@ -799,6 +802,7 @@ app.post("/database/export", authenticateJWT, async (req, res) => {
|
||||
default_path TEXT,
|
||||
stats_config TEXT,
|
||||
docker_config TEXT,
|
||||
web_ui_config TEXT,
|
||||
terminal_config TEXT,
|
||||
quick_actions TEXT,
|
||||
notes TEXT,
|
||||
@@ -921,8 +925,8 @@ app.post("/database/export", authenticateJWT, async (req, res) => {
|
||||
const sshHosts =
|
||||
await createCurrentHostRepository().listDecryptedByUserId(userId);
|
||||
const insertHost = exportDb.prepare(`
|
||||
INSERT INTO ssh_data (id, user_id, connection_type, name, ip, port, username, folder, tags, pin, auth_type, force_keyboard_interactive, password, key, key_password, key_type, sudo_password, autostart_password, autostart_key, autostart_key_password, credential_id, override_credential_username, enable_terminal, enable_tunnel, tunnel_connections, jump_hosts, enable_file_manager, enable_docker, show_terminal_in_sidebar, show_file_manager_in_sidebar, show_tunnel_in_sidebar, show_docker_in_sidebar, show_server_stats_in_sidebar, default_path, stats_config, docker_config, terminal_config, quick_actions, notes, use_socks5, socks5_host, socks5_port, socks5_username, socks5_password, socks5_proxy_chain, domain, security, ignore_cert, guacamole_config, mac_address, port_knock_sequence, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO ssh_data (id, user_id, connection_type, name, ip, port, username, folder, tags, pin, auth_type, force_keyboard_interactive, password, key, key_password, key_type, sudo_password, autostart_password, autostart_key, autostart_key_password, credential_id, override_credential_username, enable_terminal, enable_tunnel, tunnel_connections, jump_hosts, enable_file_manager, enable_docker, enable_web_ui, show_terminal_in_sidebar, show_file_manager_in_sidebar, show_tunnel_in_sidebar, show_docker_in_sidebar, show_server_stats_in_sidebar, default_path, stats_config, docker_config, web_ui_config, terminal_config, quick_actions, notes, use_socks5, socks5_host, socks5_port, socks5_username, socks5_password, socks5_proxy_chain, domain, security, ignore_cert, guacamole_config, mac_address, port_knock_sequence, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
for (const decrypted of sshHosts) {
|
||||
@@ -955,6 +959,7 @@ app.post("/database/export", authenticateJWT, async (req, res) => {
|
||||
decrypted.jumpHosts || null,
|
||||
decrypted.enableFileManager ? 1 : 0,
|
||||
decrypted.enableDocker ? 1 : 0,
|
||||
decrypted.enableWebUi ? 1 : 0,
|
||||
decrypted.showTerminalInSidebar ? 1 : 0,
|
||||
decrypted.showFileManagerInSidebar ? 1 : 0,
|
||||
decrypted.showTunnelInSidebar ? 1 : 0,
|
||||
@@ -963,6 +968,7 @@ app.post("/database/export", authenticateJWT, async (req, res) => {
|
||||
decrypted.defaultPath || null,
|
||||
decrypted.statsConfig || null,
|
||||
decrypted.dockerConfig || null,
|
||||
decrypted.webUiConfig || null,
|
||||
decrypted.terminalConfig || null,
|
||||
decrypted.quickActions || null,
|
||||
decrypted.notes || null,
|
||||
@@ -1753,6 +1759,7 @@ app.use("/terminal", terminalRoutes);
|
||||
app.use("/session_logs", sessionLogRoutes);
|
||||
app.use("/guacamole", guacamoleRoutes);
|
||||
app.use("/session-sharing", sessionSharingRoutes);
|
||||
app.use("/collab", collabRoutes);
|
||||
app.use("/network-topology", networkTopologyRoutes);
|
||||
app.use("/rbac", rbacRoutes);
|
||||
app.use("/open-tabs", openTabsRoutes);
|
||||
@@ -1765,12 +1772,14 @@ app.use("/termix-id", termixIdRoutes);
|
||||
registerAuditLogRoutes(app, authenticateJWT);
|
||||
registerTailscaleRoutes(app, authenticateJWT);
|
||||
app.use("/vault", vaultRoutes);
|
||||
app.use("/secret-sources", secretSourceRoutes);
|
||||
// Before the alert routes, which are mounted at the root and would otherwise
|
||||
// have first claim on the path.
|
||||
app.use("/automations", automationsRoutes);
|
||||
app.use("/ai", aiRoutes);
|
||||
app.use("/", alertRulesRoutes);
|
||||
app.use("/sync", syncRoutes);
|
||||
app.use("/plugin-api", pluginApiRoutes);
|
||||
|
||||
const frontendDistPaths = [
|
||||
path.join(__dirname, "../../../dist"),
|
||||
@@ -2035,7 +2044,7 @@ httpServer.on("error", (err: NodeJS.ErrnoException) => {
|
||||
});
|
||||
|
||||
export const serverReady = new Promise<void>((resolve) => {
|
||||
httpServer.listen(HTTP_PORT, async () => {
|
||||
httpServer.listen(HTTP_PORT, "127.0.0.1", async () => {
|
||||
if (!fs.existsSync(uploadsDir)) {
|
||||
fs.mkdirSync(uploadsDir, { recursive: true });
|
||||
}
|
||||
@@ -2084,7 +2093,7 @@ if (
|
||||
});
|
||||
});
|
||||
|
||||
httpsServer.listen(sslConfig.port, () => {
|
||||
httpsServer.listen(sslConfig.port, "127.0.0.1", () => {
|
||||
databaseLogger.success(
|
||||
`Backend is now also listening for HTTPS directly`,
|
||||
{
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
} from "../../utils/data-dir-guard.js";
|
||||
import { getDefaultGuacdUrl } from "../../utils/guacd-config.js";
|
||||
import { resolveDatabaseDialect, type DatabaseDialect } from "./dialect.js";
|
||||
import { SYSTEM_ROLE_DEFAULTS } from "../../utils/permission-catalog.js";
|
||||
import { connectRemoteDatabase } from "./connect.js";
|
||||
import { runRemoteMigrations } from "./migrate.js";
|
||||
import type { PortableDatabase } from "../repositories/database-context.js";
|
||||
@@ -305,6 +306,7 @@ async function initializeCompleteDatabase(): Promise<void> {
|
||||
tunnel_connections TEXT,
|
||||
enable_file_manager INTEGER NOT NULL DEFAULT 1,
|
||||
enable_docker INTEGER NOT NULL DEFAULT 0,
|
||||
enable_web_ui INTEGER NOT NULL DEFAULT 0,
|
||||
default_path TEXT,
|
||||
autostart_password TEXT,
|
||||
autostart_key TEXT,
|
||||
@@ -312,6 +314,7 @@ async function initializeCompleteDatabase(): Promise<void> {
|
||||
force_keyboard_interactive TEXT,
|
||||
stats_config TEXT,
|
||||
docker_config TEXT,
|
||||
web_ui_config TEXT,
|
||||
terminal_config TEXT,
|
||||
notes TEXT,
|
||||
use_socks5 INTEGER,
|
||||
@@ -577,6 +580,154 @@ async function initializeCompleteDatabase(): Promise<void> {
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS collab_rooms (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
owner_user_id TEXT NOT NULL,
|
||||
persistent INTEGER NOT NULL DEFAULT 0,
|
||||
presenter_user_id TEXT,
|
||||
stage_protocol TEXT,
|
||||
stage_host_id INTEGER,
|
||||
stage_share_id TEXT,
|
||||
guest_link_token TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
ended_at TEXT,
|
||||
FOREIGN KEY (owner_user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (presenter_user_id) REFERENCES users (id) ON DELETE SET NULL,
|
||||
FOREIGN KEY (stage_host_id) REFERENCES ssh_data (id) ON DELETE SET NULL,
|
||||
FOREIGN KEY (stage_share_id) REFERENCES session_shares (id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS collab_room_members (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
room_id TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
room_role TEXT NOT NULL DEFAULT 'member',
|
||||
added_by TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (room_id, user_id),
|
||||
FOREIGN KEY (room_id) REFERENCES collab_rooms (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (added_by) REFERENCES users (id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS secret_sources (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
kind TEXT NOT NULL DEFAULT 'onepassword-connect',
|
||||
base_url TEXT NOT NULL,
|
||||
token TEXT NOT NULL,
|
||||
shared INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS credential_access (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
credential_id INTEGER NOT NULL,
|
||||
user_id TEXT,
|
||||
role_id INTEGER,
|
||||
granted_by TEXT NOT NULL,
|
||||
permission_level TEXT NOT NULL DEFAULT 'use',
|
||||
expires_at TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (credential_id) REFERENCES ssh_credentials (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (granted_by) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_credential_access_user_id ON credential_access (user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_credential_access_role_id ON credential_access (role_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_credential_access_credential_id ON credential_access (credential_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shared_credential_secrets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
credential_access_id INTEGER NOT NULL,
|
||||
target_user_id TEXT NOT NULL,
|
||||
credential_id INTEGER NOT NULL,
|
||||
encrypted_username TEXT,
|
||||
auth_type TEXT NOT NULL DEFAULT 'password',
|
||||
encrypted_password TEXT,
|
||||
encrypted_key TEXT,
|
||||
encrypted_key_password TEXT,
|
||||
key_type TEXT,
|
||||
public_key TEXT,
|
||||
cert_public_key TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (credential_access_id, target_user_id),
|
||||
FOREIGN KEY (credential_access_id) REFERENCES credential_access (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (target_user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (credential_id) REFERENCES ssh_credentials (id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_shared_credential_secrets_target ON shared_credential_secrets (target_user_id, credential_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS folder_access (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
owner_user_id TEXT NOT NULL,
|
||||
folder TEXT NOT NULL,
|
||||
user_id TEXT,
|
||||
role_id INTEGER,
|
||||
granted_by TEXT NOT NULL,
|
||||
permission_level TEXT NOT NULL DEFAULT 'connect',
|
||||
expires_at TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (owner_user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (granted_by) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_folder_access_owner_folder ON folder_access (owner_user_id, folder);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS plugins (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
tier TEXT NOT NULL DEFAULT 'available',
|
||||
source TEXT NOT NULL DEFAULT 'community',
|
||||
registry_id TEXT,
|
||||
state TEXT NOT NULL DEFAULT 'disabled',
|
||||
installed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
auto_update INTEGER NOT NULL DEFAULT 0,
|
||||
manifest_json TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_plugins_registry_id ON plugins (registry_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS plugin_permission_grants (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
plugin_id TEXT NOT NULL,
|
||||
capability TEXT NOT NULL,
|
||||
granted_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
granted_by TEXT NOT NULL,
|
||||
UNIQUE (plugin_id, capability),
|
||||
FOREIGN KEY (plugin_id) REFERENCES plugins (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (granted_by) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS plugin_registries (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
kind TEXT NOT NULL DEFAULT 'community',
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
signing_key TEXT,
|
||||
last_checked_at TEXT,
|
||||
last_index_hash TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS plugin_install_counts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
plugin_id TEXT NOT NULL,
|
||||
registry_id TEXT NOT NULL,
|
||||
count INTEGER NOT NULL DEFAULT 0,
|
||||
source TEXT NOT NULL DEFAULT 'aggregate-telemetry',
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (plugin_id, registry_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
@@ -853,6 +1004,11 @@ const migrateSchema = () => {
|
||||
"expand_app_rail_on_hover",
|
||||
"INTEGER",
|
||||
);
|
||||
addColumnIfNotExists(
|
||||
"user_preferences",
|
||||
"show_pin_app_rail_button",
|
||||
"INTEGER",
|
||||
);
|
||||
addColumnIfNotExists("user_preferences", "folders_collapsed", "INTEGER");
|
||||
addColumnIfNotExists("user_preferences", "confirm_snippet_execution", "INTEGER");
|
||||
addColumnIfNotExists("user_preferences", "disable_update_check", "INTEGER");
|
||||
@@ -1057,6 +1213,12 @@ const migrateSchema = () => {
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
);
|
||||
addColumnIfNotExists("ssh_data", "docker_config", "TEXT");
|
||||
addColumnIfNotExists(
|
||||
"ssh_data",
|
||||
"enable_web_ui",
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
);
|
||||
addColumnIfNotExists("ssh_data", "web_ui_config", "TEXT");
|
||||
addColumnIfNotExists(
|
||||
"ssh_data",
|
||||
"enable_proxmox",
|
||||
@@ -1079,6 +1241,11 @@ const migrateSchema = () => {
|
||||
"enable_terminal_toolbar",
|
||||
"INTEGER NOT NULL DEFAULT 1",
|
||||
);
|
||||
addColumnIfNotExists(
|
||||
"ssh_data",
|
||||
"enable_ai_assistant",
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
);
|
||||
|
||||
addColumnIfNotExists("ssh_data", "connection_type", 'TEXT NOT NULL DEFAULT "ssh"');
|
||||
addColumnIfNotExists("ssh_data", "domain", "TEXT");
|
||||
@@ -1953,20 +2120,24 @@ const migrateSchema = () => {
|
||||
});
|
||||
}
|
||||
|
||||
const systemRoles = [
|
||||
{
|
||||
name: "admin",
|
||||
displayName: "rbac.roles.admin",
|
||||
description: "Administrator with full access",
|
||||
permissions: null,
|
||||
},
|
||||
{
|
||||
name: "user",
|
||||
displayName: "rbac.roles.user",
|
||||
description: "Regular user",
|
||||
permissions: null,
|
||||
},
|
||||
];
|
||||
const systemRoles = Object.entries(SYSTEM_ROLE_DEFAULTS).map(
|
||||
([name, defaults]) => ({
|
||||
name,
|
||||
displayName: `rbac.roles.${name}`,
|
||||
description: defaults.description,
|
||||
permissions: JSON.stringify(defaults.permissions),
|
||||
}),
|
||||
);
|
||||
|
||||
// Route-level RBAC needs the permission lists to exist; roles seeded by
|
||||
// earlier versions carried NULL there. Backfill only NULL so an admin's
|
||||
// edits to these roles are never overwritten.
|
||||
const backfillPermissions = sqlite.prepare(
|
||||
"UPDATE roles SET permissions = ? WHERE name = ? AND is_system = 1 AND permissions IS NULL",
|
||||
);
|
||||
for (const role of systemRoles) {
|
||||
backfillPermissions.run(role.permissions, role.name);
|
||||
}
|
||||
|
||||
for (const role of systemRoles) {
|
||||
const existingRole = sqlite.prepare("SELECT id FROM roles WHERE name = ?").get(role.name);
|
||||
@@ -2035,6 +2206,10 @@ const migrateSchema = () => {
|
||||
}
|
||||
|
||||
addColumnIfNotExists("users", "sso_provider_id", "INTEGER");
|
||||
addColumnIfNotExists("collab_rooms", "guest_link_token", "TEXT");
|
||||
sqlite.exec(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS idx_collab_rooms_guest_token ON collab_rooms (guest_link_token)",
|
||||
);
|
||||
|
||||
try {
|
||||
const usersTableInfo = sqlite.prepare("PRAGMA table_info(users)").all() as Array<{
|
||||
@@ -2986,6 +3161,12 @@ async function initializeRemoteDatabase(
|
||||
await primeCurrentSettingsCache();
|
||||
startSettingsCacheRefresh();
|
||||
|
||||
// The SQLite bootstrap seeds system roles inline below; migrations for the
|
||||
// remote dialects never did, and route-level RBAC denies a user with no
|
||||
// usable role, so they are seeded (and backfilled) here.
|
||||
const { ensureSystemRoles } = await import("../../utils/system-roles.js");
|
||||
await ensureSystemRoles();
|
||||
|
||||
databaseLogger.info(`${dialect} database ready`, {
|
||||
operation: "db_init_complete",
|
||||
dialect,
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
double,
|
||||
index,
|
||||
uniqueIndex,
|
||||
foreignKey,
|
||||
type AnyMySqlColumn,
|
||||
} from "drizzle-orm/mysql-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
@@ -150,7 +151,7 @@ export const hosts = mysqlTable(
|
||||
ip: text("ip").notNull(),
|
||||
port: int("port").notNull(),
|
||||
username: text("username").notNull(),
|
||||
folder: text("folder"),
|
||||
folder: varchar("folder", { length: 255 }),
|
||||
// Sub-host nesting: a host acting as an organizational parent for other
|
||||
// hosts, mutually exclusive with folder (see host route validation).
|
||||
parentHostId: int("parent_host_id").references(
|
||||
@@ -212,12 +213,18 @@ export const hosts = mysqlTable(
|
||||
enableDocker: boolean("enable_docker")
|
||||
.notNull()
|
||||
.default(false),
|
||||
enableWebUi: boolean("enable_web_ui")
|
||||
.notNull()
|
||||
.default(false),
|
||||
enableTmuxMonitor: boolean("enable_tmux_monitor")
|
||||
.notNull()
|
||||
.default(false),
|
||||
enableTerminalToolbar: boolean("enable_terminal_toolbar")
|
||||
.notNull()
|
||||
.default(true),
|
||||
enableAiAssistant: boolean("enable_ai_assistant")
|
||||
.notNull()
|
||||
.default(false),
|
||||
showTerminalInSidebar: boolean("show_terminal_in_sidebar")
|
||||
.notNull()
|
||||
.default(true),
|
||||
@@ -236,6 +243,7 @@ export const hosts = mysqlTable(
|
||||
defaultPath: text("default_path"),
|
||||
statsConfig: text("stats_config"),
|
||||
dockerConfig: text("docker_config"),
|
||||
webUiConfig: text("web_ui_config"),
|
||||
enableProxmox: boolean("enable_proxmox")
|
||||
.notNull()
|
||||
.default(false),
|
||||
@@ -439,7 +447,7 @@ export const sshCredentials = mysqlTable(
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
description: text("description"),
|
||||
folder: text("folder"),
|
||||
folder: varchar("folder", { length: 255 }),
|
||||
tags: text("tags"),
|
||||
pin: boolean("pin").notNull().default(false),
|
||||
// Manual drag-to-reorder position within a folder. Null means the
|
||||
@@ -505,7 +513,7 @@ export const snippets = mysqlTable(
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
content: text("content").notNull(),
|
||||
description: text("description"),
|
||||
folder: text("folder"),
|
||||
folder: varchar("folder", { length: 255 }),
|
||||
order: int("order").notNull().default(0),
|
||||
syncId: varchar("sync_id", { length: 255 }).unique(),
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
@@ -1022,7 +1030,7 @@ export const vaultProfiles = mysqlTable("vault_profiles", {
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
description: text("description"),
|
||||
folder: text("folder"),
|
||||
folder: varchar("folder", { length: 255 }),
|
||||
tags: text("tags"),
|
||||
// Vault server connection (non-secret)
|
||||
vaultAddr: text("vault_addr").notNull(),
|
||||
@@ -1136,6 +1144,7 @@ export const userPreferences = mysqlTable("user_preferences", {
|
||||
hostTrayOnClick: boolean("host_tray_on_click"),
|
||||
pinAppRail: boolean("pin_app_rail"),
|
||||
expandAppRailOnHover: boolean("expand_app_rail_on_hover"),
|
||||
showPinAppRailButton: boolean("show_pin_app_rail_button"),
|
||||
foldersCollapsed: boolean("folders_collapsed"),
|
||||
confirmSnippetExecution: boolean("confirm_snippet_execution"),
|
||||
disableUpdateCheck: boolean("disable_update_check"),
|
||||
@@ -1939,3 +1948,335 @@ export const aiProposals = mysqlTable(
|
||||
],
|
||||
);
|
||||
// --- ai end ---
|
||||
|
||||
// --- collab rooms ---
|
||||
|
||||
/**
|
||||
* A collaboration room: a group of users watching one "stage" - the live
|
||||
* session the current presenter is showing. The stage points at a
|
||||
* shareType="room" row in session_shares, so transport, gating, recording and
|
||||
* expiry all reuse the session-sharing machinery.
|
||||
*/
|
||||
export const collabRooms = mysqlTable(
|
||||
"collab_rooms",
|
||||
{
|
||||
id: varchar("id", { length: 255 }).primaryKey(),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
ownerUserId: varchar("owner_user_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
// Persistent rooms survive being emptied and can be re-used; one-off
|
||||
// rooms are ended explicitly and never listed again.
|
||||
persistent: boolean("persistent")
|
||||
.notNull()
|
||||
.default(false),
|
||||
|
||||
presenterUserId: varchar("presenter_user_id", { length: 255 }).references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
stageProtocol: text("stage_protocol"),
|
||||
stageHostId: int("stage_host_id").references(() => hosts.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
stageShareId: varchar("stage_share_id", { length: 255 }).references(() => sessionShares.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
|
||||
// Set = anonymous guests may watch the stage through this token.
|
||||
guestLinkToken: varchar("guest_link_token", { length: 255 }),
|
||||
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
endedAt: text("ended_at"),
|
||||
},
|
||||
(table) => [
|
||||
index("idx_collab_rooms_owner").on(table.ownerUserId),
|
||||
uniqueIndex("idx_collab_rooms_guest_token").on(table.guestLinkToken),
|
||||
],
|
||||
);
|
||||
|
||||
export const collabRoomMembers = mysqlTable(
|
||||
"collab_room_members",
|
||||
{
|
||||
id: int("id").autoincrement().primaryKey(),
|
||||
roomId: varchar("room_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => collabRooms.id, { onDelete: "cascade" }),
|
||||
userId: varchar("user_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
// "host" runs the room: invites, force-switches the presenter, ends it.
|
||||
roomRole: text("room_role").notNull().default("member"),
|
||||
addedBy: varchar("added_by", { length: 255 }).references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("idx_collab_room_members_room_user").on(
|
||||
table.roomId,
|
||||
table.userId,
|
||||
),
|
||||
index("idx_collab_room_members_user").on(table.userId),
|
||||
],
|
||||
);
|
||||
|
||||
// --- secret sources ---
|
||||
|
||||
/**
|
||||
* An external password manager Termix pulls secrets from at connect time,
|
||||
* instead of storing them. Only the access token is secret; it is encrypted
|
||||
* with the owner's data key under the row id. Hosts and credentials refer to
|
||||
* entries by reference ("op://vault/item/field") in their secret fields.
|
||||
*/
|
||||
export const secretSources = mysqlTable(
|
||||
"secret_sources",
|
||||
{
|
||||
id: varchar("id", { length: 255 }).primaryKey(),
|
||||
userId: varchar("user_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
// "onepassword-connect" for now; the reference syntax is per kind.
|
||||
kind: text("kind").notNull().default("onepassword-connect"),
|
||||
baseUrl: text("base_url").notNull(),
|
||||
token: text("token").notNull(),
|
||||
// Visible to every user; secrets still decrypt with the owner's key.
|
||||
shared: boolean("shared").notNull().default(false),
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
updatedAt: varchar("updated_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
},
|
||||
(table) => [index("idx_secret_sources_user").on(table.userId)],
|
||||
);
|
||||
|
||||
// --- credential sharing ---
|
||||
|
||||
/**
|
||||
* Who may use or manage someone else's credential. Same shape as
|
||||
* snippet_access; "use" attaches it to hosts and connects, "manage" also
|
||||
* edits and re-shares it.
|
||||
*/
|
||||
export const credentialAccess = mysqlTable(
|
||||
"credential_access",
|
||||
{
|
||||
id: int("id").autoincrement().primaryKey(),
|
||||
credentialId: int("credential_id")
|
||||
.notNull()
|
||||
.references(() => sshCredentials.id, { onDelete: "cascade" }),
|
||||
|
||||
userId: varchar("user_id", { length: 255 }).references(() => users.id, { onDelete: "cascade" }),
|
||||
roleId: int("role_id").references(() => roles.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
|
||||
grantedBy: varchar("granted_by", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
permissionLevel: text("permission_level").notNull().default("use"),
|
||||
|
||||
expiresAt: varchar("expires_at", { length: 255 }),
|
||||
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
},
|
||||
(table) => [
|
||||
index("idx_credential_access_user_id").on(table.userId),
|
||||
index("idx_credential_access_role_id").on(table.roleId),
|
||||
index("idx_credential_access_credential_id").on(table.credentialId),
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* A recipient's copy of a shared credential's secrets, re-encrypted under
|
||||
* the recipient's data key (the owner's key cannot be used by anyone else).
|
||||
* Rebuilt whenever the owner edits the credential; one row per grant and
|
||||
* recipient, like shared_host_secrets.
|
||||
*/
|
||||
export const sharedCredentialSecrets = mysqlTable(
|
||||
"shared_credential_secrets",
|
||||
{
|
||||
id: int("id").autoincrement().primaryKey(),
|
||||
credentialAccessId: int("credential_access_id").notNull(),
|
||||
targetUserId: varchar("target_user_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
credentialId: int("credential_id")
|
||||
.notNull()
|
||||
.references(() => sshCredentials.id, { onDelete: "cascade" }),
|
||||
|
||||
encryptedUsername: text("encrypted_username"),
|
||||
authType: text("auth_type").notNull().default("password"),
|
||||
encryptedPassword: text("encrypted_password"),
|
||||
encryptedKey: text("encrypted_key"),
|
||||
encryptedKeyPassword: text("encrypted_key_password"),
|
||||
keyType: text("key_type"),
|
||||
publicKey: text("public_key"),
|
||||
certPublicKey: text("cert_public_key"),
|
||||
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
updatedAt: varchar("updated_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
},
|
||||
(table) => [
|
||||
foreignKey({
|
||||
columns: [table.credentialAccessId],
|
||||
foreignColumns: [credentialAccess.id],
|
||||
name: "shared_cred_secrets_access_id_fk",
|
||||
}).onDelete("cascade"),
|
||||
uniqueIndex("idx_shared_credential_secrets_scope").on(
|
||||
table.credentialAccessId,
|
||||
table.targetUserId,
|
||||
),
|
||||
index("idx_shared_credential_secrets_target").on(
|
||||
table.targetUserId,
|
||||
table.credentialId,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
// --- folder access rules ---
|
||||
|
||||
/**
|
||||
* A standing share on a host folder. Sharing a folder fans out host_access
|
||||
* grants to the hosts in it today; this row is what makes hosts created in
|
||||
* or moved into the folder later inherit the same access.
|
||||
*/
|
||||
export const folderAccess = mysqlTable(
|
||||
"folder_access",
|
||||
{
|
||||
id: int("id").autoincrement().primaryKey(),
|
||||
ownerUserId: varchar("owner_user_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
// The folder path as stored on hosts ("Parent / Child"); subfolders inherit.
|
||||
folder: varchar("folder", { length: 255 }).notNull(),
|
||||
|
||||
userId: varchar("user_id", { length: 255 }).references(() => users.id, { onDelete: "cascade" }),
|
||||
roleId: int("role_id").references(() => roles.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
|
||||
grantedBy: varchar("granted_by", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
permissionLevel: text("permission_level").notNull().default("connect"),
|
||||
expiresAt: varchar("expires_at", { length: 255 }),
|
||||
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
},
|
||||
(table) => [
|
||||
index("idx_folder_access_owner_folder").on(table.ownerUserId, table.folder),
|
||||
],
|
||||
);
|
||||
|
||||
// --- plugins begin ---
|
||||
|
||||
/**
|
||||
* An installed plugin. id matches the manifest's own id (not autoincrement),
|
||||
* so a plugin can be looked up the same way the manifest and registry refer
|
||||
* to it. manifest_json is the full manifest as it was at install time, kept
|
||||
* for audit/rollback even after a registry updates or removes the entry.
|
||||
*/
|
||||
export const plugins = mysqlTable(
|
||||
"plugins",
|
||||
{
|
||||
id: varchar("id", { length: 255 }).primaryKey(),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
version: text("version").notNull(),
|
||||
tier: text("tier").notNull().default("available"),
|
||||
source: text("source").notNull().default("community"),
|
||||
registryId: varchar("registry_id", { length: 255 }),
|
||||
state: text("state").notNull().default("disabled"),
|
||||
installedAt: text("installed_at")
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
updatedAt: varchar("updated_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
autoUpdate: boolean("auto_update")
|
||||
.notNull()
|
||||
.default(false),
|
||||
manifestJson: text("manifest_json").notNull(),
|
||||
},
|
||||
(table) => [index("idx_plugins_registry_id").on(table.registryId)],
|
||||
);
|
||||
|
||||
export const pluginPermissionGrants = mysqlTable(
|
||||
"plugin_permission_grants",
|
||||
{
|
||||
id: int("id").autoincrement().primaryKey(),
|
||||
pluginId: varchar("plugin_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => plugins.id, { onDelete: "cascade" }),
|
||||
capability: varchar("capability", { length: 255 }).notNull(),
|
||||
grantedAt: text("granted_at")
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
grantedBy: varchar("granted_by", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
},
|
||||
// A plugin's grants are always read together, and re-granting the same
|
||||
// capability should update the existing row rather than duplicate it.
|
||||
(table) => [
|
||||
uniqueIndex("idx_plugin_permission_grants_plugin_capability").on(
|
||||
table.pluginId,
|
||||
table.capability,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const pluginRegistries = mysqlTable("plugin_registries", {
|
||||
id: varchar("id", { length: 255 }).primaryKey(),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
url: text("url").notNull(),
|
||||
kind: text("kind").notNull().default("community"),
|
||||
enabled: boolean("enabled").notNull().default(true),
|
||||
signingKey: text("signing_key"),
|
||||
lastCheckedAt: text("last_checked_at"),
|
||||
lastIndexHash: text("last_index_hash"),
|
||||
});
|
||||
|
||||
/**
|
||||
* Install counts populated by a background job (GitHub release download
|
||||
* counts, aggregated telemetry, or a manual override) rather than by the
|
||||
* install/uninstall actions themselves — kept separate from `plugins` so
|
||||
* that job can overwrite counts without touching install state.
|
||||
*/
|
||||
export const pluginInstallCounts = mysqlTable(
|
||||
"plugin_install_counts",
|
||||
{
|
||||
id: int("id").autoincrement().primaryKey(),
|
||||
pluginId: varchar("plugin_id", { length: 255 }).notNull(),
|
||||
registryId: varchar("registry_id", { length: 255 }).notNull(),
|
||||
count: int("count").notNull().default(0),
|
||||
source: text("source").notNull().default("aggregate-telemetry"),
|
||||
updatedAt: varchar("updated_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`(CURRENT_TIMESTAMP)`),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("idx_plugin_install_counts_plugin_registry").on(
|
||||
table.pluginId,
|
||||
table.registryId,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
// --- plugins end ---
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
doublePrecision,
|
||||
index,
|
||||
uniqueIndex,
|
||||
foreignKey,
|
||||
type AnyPgColumn,
|
||||
} from "drizzle-orm/pg-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
@@ -151,7 +152,7 @@ export const hosts = pgTable(
|
||||
ip: text("ip").notNull(),
|
||||
port: integer("port").notNull(),
|
||||
username: text("username").notNull(),
|
||||
folder: text("folder"),
|
||||
folder: varchar("folder", { length: 255 }),
|
||||
// Sub-host nesting: a host acting as an organizational parent for other
|
||||
// hosts, mutually exclusive with folder (see host route validation).
|
||||
parentHostId: integer("parent_host_id").references(
|
||||
@@ -213,12 +214,18 @@ export const hosts = pgTable(
|
||||
enableDocker: boolean("enable_docker")
|
||||
.notNull()
|
||||
.default(false),
|
||||
enableWebUi: boolean("enable_web_ui")
|
||||
.notNull()
|
||||
.default(false),
|
||||
enableTmuxMonitor: boolean("enable_tmux_monitor")
|
||||
.notNull()
|
||||
.default(false),
|
||||
enableTerminalToolbar: boolean("enable_terminal_toolbar")
|
||||
.notNull()
|
||||
.default(true),
|
||||
enableAiAssistant: boolean("enable_ai_assistant")
|
||||
.notNull()
|
||||
.default(false),
|
||||
showTerminalInSidebar: boolean("show_terminal_in_sidebar")
|
||||
.notNull()
|
||||
.default(true),
|
||||
@@ -237,6 +244,7 @@ export const hosts = pgTable(
|
||||
defaultPath: text("default_path"),
|
||||
statsConfig: text("stats_config"),
|
||||
dockerConfig: text("docker_config"),
|
||||
webUiConfig: text("web_ui_config"),
|
||||
enableProxmox: boolean("enable_proxmox")
|
||||
.notNull()
|
||||
.default(false),
|
||||
@@ -440,7 +448,7 @@ export const sshCredentials = pgTable(
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
description: text("description"),
|
||||
folder: text("folder"),
|
||||
folder: varchar("folder", { length: 255 }),
|
||||
tags: text("tags"),
|
||||
pin: boolean("pin").notNull().default(false),
|
||||
// Manual drag-to-reorder position within a folder. Null means the
|
||||
@@ -506,7 +514,7 @@ export const snippets = pgTable(
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
content: text("content").notNull(),
|
||||
description: text("description"),
|
||||
folder: text("folder"),
|
||||
folder: varchar("folder", { length: 255 }),
|
||||
order: integer("order").notNull().default(0),
|
||||
syncId: varchar("sync_id", { length: 255 }).unique(),
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
@@ -1023,7 +1031,7 @@ export const vaultProfiles = pgTable("vault_profiles", {
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
description: text("description"),
|
||||
folder: text("folder"),
|
||||
folder: varchar("folder", { length: 255 }),
|
||||
tags: text("tags"),
|
||||
// Vault server connection (non-secret)
|
||||
vaultAddr: text("vault_addr").notNull(),
|
||||
@@ -1137,6 +1145,7 @@ export const userPreferences = pgTable("user_preferences", {
|
||||
hostTrayOnClick: boolean("host_tray_on_click"),
|
||||
pinAppRail: boolean("pin_app_rail"),
|
||||
expandAppRailOnHover: boolean("expand_app_rail_on_hover"),
|
||||
showPinAppRailButton: boolean("show_pin_app_rail_button"),
|
||||
foldersCollapsed: boolean("folders_collapsed"),
|
||||
confirmSnippetExecution: boolean("confirm_snippet_execution"),
|
||||
disableUpdateCheck: boolean("disable_update_check"),
|
||||
@@ -1940,3 +1949,335 @@ export const aiProposals = pgTable(
|
||||
],
|
||||
);
|
||||
// --- ai end ---
|
||||
|
||||
// --- collab rooms ---
|
||||
|
||||
/**
|
||||
* A collaboration room: a group of users watching one "stage" - the live
|
||||
* session the current presenter is showing. The stage points at a
|
||||
* shareType="room" row in session_shares, so transport, gating, recording and
|
||||
* expiry all reuse the session-sharing machinery.
|
||||
*/
|
||||
export const collabRooms = pgTable(
|
||||
"collab_rooms",
|
||||
{
|
||||
id: varchar("id", { length: 255 }).primaryKey(),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
ownerUserId: varchar("owner_user_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
// Persistent rooms survive being emptied and can be re-used; one-off
|
||||
// rooms are ended explicitly and never listed again.
|
||||
persistent: boolean("persistent")
|
||||
.notNull()
|
||||
.default(false),
|
||||
|
||||
presenterUserId: varchar("presenter_user_id", { length: 255 }).references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
stageProtocol: text("stage_protocol"),
|
||||
stageHostId: integer("stage_host_id").references(() => hosts.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
stageShareId: varchar("stage_share_id", { length: 255 }).references(() => sessionShares.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
|
||||
// Set = anonymous guests may watch the stage through this token.
|
||||
guestLinkToken: varchar("guest_link_token", { length: 255 }),
|
||||
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
endedAt: text("ended_at"),
|
||||
},
|
||||
(table) => [
|
||||
index("idx_collab_rooms_owner").on(table.ownerUserId),
|
||||
uniqueIndex("idx_collab_rooms_guest_token").on(table.guestLinkToken),
|
||||
],
|
||||
);
|
||||
|
||||
export const collabRoomMembers = pgTable(
|
||||
"collab_room_members",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
roomId: varchar("room_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => collabRooms.id, { onDelete: "cascade" }),
|
||||
userId: varchar("user_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
// "host" runs the room: invites, force-switches the presenter, ends it.
|
||||
roomRole: text("room_role").notNull().default("member"),
|
||||
addedBy: varchar("added_by", { length: 255 }).references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("idx_collab_room_members_room_user").on(
|
||||
table.roomId,
|
||||
table.userId,
|
||||
),
|
||||
index("idx_collab_room_members_user").on(table.userId),
|
||||
],
|
||||
);
|
||||
|
||||
// --- secret sources ---
|
||||
|
||||
/**
|
||||
* An external password manager Termix pulls secrets from at connect time,
|
||||
* instead of storing them. Only the access token is secret; it is encrypted
|
||||
* with the owner's data key under the row id. Hosts and credentials refer to
|
||||
* entries by reference ("op://vault/item/field") in their secret fields.
|
||||
*/
|
||||
export const secretSources = pgTable(
|
||||
"secret_sources",
|
||||
{
|
||||
id: varchar("id", { length: 255 }).primaryKey(),
|
||||
userId: varchar("user_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
// "onepassword-connect" for now; the reference syntax is per kind.
|
||||
kind: text("kind").notNull().default("onepassword-connect"),
|
||||
baseUrl: text("base_url").notNull(),
|
||||
token: text("token").notNull(),
|
||||
// Visible to every user; secrets still decrypt with the owner's key.
|
||||
shared: boolean("shared").notNull().default(false),
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: varchar("updated_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [index("idx_secret_sources_user").on(table.userId)],
|
||||
);
|
||||
|
||||
// --- credential sharing ---
|
||||
|
||||
/**
|
||||
* Who may use or manage someone else's credential. Same shape as
|
||||
* snippet_access; "use" attaches it to hosts and connects, "manage" also
|
||||
* edits and re-shares it.
|
||||
*/
|
||||
export const credentialAccess = pgTable(
|
||||
"credential_access",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
credentialId: integer("credential_id")
|
||||
.notNull()
|
||||
.references(() => sshCredentials.id, { onDelete: "cascade" }),
|
||||
|
||||
userId: varchar("user_id", { length: 255 }).references(() => users.id, { onDelete: "cascade" }),
|
||||
roleId: integer("role_id").references(() => roles.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
|
||||
grantedBy: varchar("granted_by", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
permissionLevel: text("permission_level").notNull().default("use"),
|
||||
|
||||
expiresAt: varchar("expires_at", { length: 255 }),
|
||||
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
index("idx_credential_access_user_id").on(table.userId),
|
||||
index("idx_credential_access_role_id").on(table.roleId),
|
||||
index("idx_credential_access_credential_id").on(table.credentialId),
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* A recipient's copy of a shared credential's secrets, re-encrypted under
|
||||
* the recipient's data key (the owner's key cannot be used by anyone else).
|
||||
* Rebuilt whenever the owner edits the credential; one row per grant and
|
||||
* recipient, like shared_host_secrets.
|
||||
*/
|
||||
export const sharedCredentialSecrets = pgTable(
|
||||
"shared_credential_secrets",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
credentialAccessId: integer("credential_access_id").notNull(),
|
||||
targetUserId: varchar("target_user_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
credentialId: integer("credential_id")
|
||||
.notNull()
|
||||
.references(() => sshCredentials.id, { onDelete: "cascade" }),
|
||||
|
||||
encryptedUsername: text("encrypted_username"),
|
||||
authType: text("auth_type").notNull().default("password"),
|
||||
encryptedPassword: text("encrypted_password"),
|
||||
encryptedKey: text("encrypted_key"),
|
||||
encryptedKeyPassword: text("encrypted_key_password"),
|
||||
keyType: text("key_type"),
|
||||
publicKey: text("public_key"),
|
||||
certPublicKey: text("cert_public_key"),
|
||||
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: varchar("updated_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
foreignKey({
|
||||
columns: [table.credentialAccessId],
|
||||
foreignColumns: [credentialAccess.id],
|
||||
name: "shared_cred_secrets_access_id_fk",
|
||||
}).onDelete("cascade"),
|
||||
uniqueIndex("idx_shared_credential_secrets_scope").on(
|
||||
table.credentialAccessId,
|
||||
table.targetUserId,
|
||||
),
|
||||
index("idx_shared_credential_secrets_target").on(
|
||||
table.targetUserId,
|
||||
table.credentialId,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
// --- folder access rules ---
|
||||
|
||||
/**
|
||||
* A standing share on a host folder. Sharing a folder fans out host_access
|
||||
* grants to the hosts in it today; this row is what makes hosts created in
|
||||
* or moved into the folder later inherit the same access.
|
||||
*/
|
||||
export const folderAccess = pgTable(
|
||||
"folder_access",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
ownerUserId: varchar("owner_user_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
// The folder path as stored on hosts ("Parent / Child"); subfolders inherit.
|
||||
folder: varchar("folder", { length: 255 }).notNull(),
|
||||
|
||||
userId: varchar("user_id", { length: 255 }).references(() => users.id, { onDelete: "cascade" }),
|
||||
roleId: integer("role_id").references(() => roles.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
|
||||
grantedBy: varchar("granted_by", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
permissionLevel: text("permission_level").notNull().default("connect"),
|
||||
expiresAt: varchar("expires_at", { length: 255 }),
|
||||
|
||||
createdAt: varchar("created_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
index("idx_folder_access_owner_folder").on(table.ownerUserId, table.folder),
|
||||
],
|
||||
);
|
||||
|
||||
// --- plugins begin ---
|
||||
|
||||
/**
|
||||
* An installed plugin. id matches the manifest's own id (not autoincrement),
|
||||
* so a plugin can be looked up the same way the manifest and registry refer
|
||||
* to it. manifest_json is the full manifest as it was at install time, kept
|
||||
* for audit/rollback even after a registry updates or removes the entry.
|
||||
*/
|
||||
export const plugins = pgTable(
|
||||
"plugins",
|
||||
{
|
||||
id: varchar("id", { length: 255 }).primaryKey(),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
version: text("version").notNull(),
|
||||
tier: text("tier").notNull().default("available"),
|
||||
source: text("source").notNull().default("community"),
|
||||
registryId: varchar("registry_id", { length: 255 }),
|
||||
state: text("state").notNull().default("disabled"),
|
||||
installedAt: text("installed_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: varchar("updated_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
autoUpdate: boolean("auto_update")
|
||||
.notNull()
|
||||
.default(false),
|
||||
manifestJson: text("manifest_json").notNull(),
|
||||
},
|
||||
(table) => [index("idx_plugins_registry_id").on(table.registryId)],
|
||||
);
|
||||
|
||||
export const pluginPermissionGrants = pgTable(
|
||||
"plugin_permission_grants",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
pluginId: varchar("plugin_id", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => plugins.id, { onDelete: "cascade" }),
|
||||
capability: varchar("capability", { length: 255 }).notNull(),
|
||||
grantedAt: text("granted_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
grantedBy: varchar("granted_by", { length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
},
|
||||
// A plugin's grants are always read together, and re-granting the same
|
||||
// capability should update the existing row rather than duplicate it.
|
||||
(table) => [
|
||||
uniqueIndex("idx_plugin_permission_grants_plugin_capability").on(
|
||||
table.pluginId,
|
||||
table.capability,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const pluginRegistries = pgTable("plugin_registries", {
|
||||
id: varchar("id", { length: 255 }).primaryKey(),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
url: text("url").notNull(),
|
||||
kind: text("kind").notNull().default("community"),
|
||||
enabled: boolean("enabled").notNull().default(true),
|
||||
signingKey: text("signing_key"),
|
||||
lastCheckedAt: text("last_checked_at"),
|
||||
lastIndexHash: text("last_index_hash"),
|
||||
});
|
||||
|
||||
/**
|
||||
* Install counts populated by a background job (GitHub release download
|
||||
* counts, aggregated telemetry, or a manual override) rather than by the
|
||||
* install/uninstall actions themselves — kept separate from `plugins` so
|
||||
* that job can overwrite counts without touching install state.
|
||||
*/
|
||||
export const pluginInstallCounts = pgTable(
|
||||
"plugin_install_counts",
|
||||
{
|
||||
id: serial("id").primaryKey(),
|
||||
pluginId: varchar("plugin_id", { length: 255 }).notNull(),
|
||||
registryId: varchar("registry_id", { length: 255 }).notNull(),
|
||||
count: integer("count").notNull().default(0),
|
||||
source: text("source").notNull().default("aggregate-telemetry"),
|
||||
updatedAt: varchar("updated_at", { length: 255 })
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("idx_plugin_install_counts_plugin_registry").on(
|
||||
table.pluginId,
|
||||
table.registryId,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
// --- plugins end ---
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
real,
|
||||
index,
|
||||
uniqueIndex,
|
||||
foreignKey,
|
||||
type AnySQLiteColumn,
|
||||
} from "drizzle-orm/sqlite-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
@@ -205,12 +206,18 @@ export const hosts = sqliteTable(
|
||||
enableDocker: integer("enable_docker", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
enableWebUi: integer("enable_web_ui", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
enableTmuxMonitor: integer("enable_tmux_monitor", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
enableTerminalToolbar: integer("enable_terminal_toolbar", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(true),
|
||||
enableAiAssistant: integer("enable_ai_assistant", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
showTerminalInSidebar: integer("show_terminal_in_sidebar", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(true),
|
||||
@@ -229,6 +236,7 @@ export const hosts = sqliteTable(
|
||||
defaultPath: text("default_path"),
|
||||
statsConfig: text("stats_config"),
|
||||
dockerConfig: text("docker_config"),
|
||||
webUiConfig: text("web_ui_config"),
|
||||
enableProxmox: integer("enable_proxmox", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
@@ -1133,6 +1141,9 @@ export const userPreferences = sqliteTable("user_preferences", {
|
||||
expandAppRailOnHover: integer("expand_app_rail_on_hover", {
|
||||
mode: "boolean",
|
||||
}),
|
||||
showPinAppRailButton: integer("show_pin_app_rail_button", {
|
||||
mode: "boolean",
|
||||
}),
|
||||
foldersCollapsed: integer("folders_collapsed", { mode: "boolean" }),
|
||||
confirmSnippetExecution: integer("confirm_snippet_execution", { mode: "boolean" }),
|
||||
disableUpdateCheck: integer("disable_update_check", { mode: "boolean" }),
|
||||
@@ -1936,3 +1947,335 @@ export const aiProposals = sqliteTable(
|
||||
],
|
||||
);
|
||||
// --- ai end ---
|
||||
|
||||
// --- collab rooms ---
|
||||
|
||||
/**
|
||||
* A collaboration room: a group of users watching one "stage" - the live
|
||||
* session the current presenter is showing. The stage points at a
|
||||
* shareType="room" row in session_shares, so transport, gating, recording and
|
||||
* expiry all reuse the session-sharing machinery.
|
||||
*/
|
||||
export const collabRooms = sqliteTable(
|
||||
"collab_rooms",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
ownerUserId: text("owner_user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
// Persistent rooms survive being emptied and can be re-used; one-off
|
||||
// rooms are ended explicitly and never listed again.
|
||||
persistent: integer("persistent", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
|
||||
presenterUserId: text("presenter_user_id").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
stageProtocol: text("stage_protocol"),
|
||||
stageHostId: integer("stage_host_id").references(() => hosts.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
stageShareId: text("stage_share_id").references(() => sessionShares.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
|
||||
// Set = anonymous guests may watch the stage through this token.
|
||||
guestLinkToken: text("guest_link_token"),
|
||||
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
endedAt: text("ended_at"),
|
||||
},
|
||||
(table) => [
|
||||
index("idx_collab_rooms_owner").on(table.ownerUserId),
|
||||
uniqueIndex("idx_collab_rooms_guest_token").on(table.guestLinkToken),
|
||||
],
|
||||
);
|
||||
|
||||
export const collabRoomMembers = sqliteTable(
|
||||
"collab_room_members",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
roomId: text("room_id")
|
||||
.notNull()
|
||||
.references(() => collabRooms.id, { onDelete: "cascade" }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
// "host" runs the room: invites, force-switches the presenter, ends it.
|
||||
roomRole: text("room_role").notNull().default("member"),
|
||||
addedBy: text("added_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("idx_collab_room_members_room_user").on(
|
||||
table.roomId,
|
||||
table.userId,
|
||||
),
|
||||
index("idx_collab_room_members_user").on(table.userId),
|
||||
],
|
||||
);
|
||||
|
||||
// --- secret sources ---
|
||||
|
||||
/**
|
||||
* An external password manager Termix pulls secrets from at connect time,
|
||||
* instead of storing them. Only the access token is secret; it is encrypted
|
||||
* with the owner's data key under the row id. Hosts and credentials refer to
|
||||
* entries by reference ("op://vault/item/field") in their secret fields.
|
||||
*/
|
||||
export const secretSources = sqliteTable(
|
||||
"secret_sources",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
// "onepassword-connect" for now; the reference syntax is per kind.
|
||||
kind: text("kind").notNull().default("onepassword-connect"),
|
||||
baseUrl: text("base_url").notNull(),
|
||||
token: text("token").notNull(),
|
||||
// Visible to every user; secrets still decrypt with the owner's key.
|
||||
shared: integer("shared", { mode: "boolean" }).notNull().default(false),
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [index("idx_secret_sources_user").on(table.userId)],
|
||||
);
|
||||
|
||||
// --- credential sharing ---
|
||||
|
||||
/**
|
||||
* Who may use or manage someone else's credential. Same shape as
|
||||
* snippet_access; "use" attaches it to hosts and connects, "manage" also
|
||||
* edits and re-shares it.
|
||||
*/
|
||||
export const credentialAccess = sqliteTable(
|
||||
"credential_access",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
credentialId: integer("credential_id")
|
||||
.notNull()
|
||||
.references(() => sshCredentials.id, { onDelete: "cascade" }),
|
||||
|
||||
userId: text("user_id").references(() => users.id, { onDelete: "cascade" }),
|
||||
roleId: integer("role_id").references(() => roles.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
|
||||
grantedBy: text("granted_by")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
|
||||
permissionLevel: text("permission_level").notNull().default("use"),
|
||||
|
||||
expiresAt: text("expires_at"),
|
||||
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
index("idx_credential_access_user_id").on(table.userId),
|
||||
index("idx_credential_access_role_id").on(table.roleId),
|
||||
index("idx_credential_access_credential_id").on(table.credentialId),
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* A recipient's copy of a shared credential's secrets, re-encrypted under
|
||||
* the recipient's data key (the owner's key cannot be used by anyone else).
|
||||
* Rebuilt whenever the owner edits the credential; one row per grant and
|
||||
* recipient, like shared_host_secrets.
|
||||
*/
|
||||
export const sharedCredentialSecrets = sqliteTable(
|
||||
"shared_credential_secrets",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
credentialAccessId: integer("credential_access_id").notNull(),
|
||||
targetUserId: text("target_user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
credentialId: integer("credential_id")
|
||||
.notNull()
|
||||
.references(() => sshCredentials.id, { onDelete: "cascade" }),
|
||||
|
||||
encryptedUsername: text("encrypted_username"),
|
||||
authType: text("auth_type").notNull().default("password"),
|
||||
encryptedPassword: text("encrypted_password"),
|
||||
encryptedKey: text("encrypted_key", { length: 16384 }),
|
||||
encryptedKeyPassword: text("encrypted_key_password"),
|
||||
keyType: text("key_type"),
|
||||
publicKey: text("public_key", { length: 4096 }),
|
||||
certPublicKey: text("cert_public_key", { length: 8192 }),
|
||||
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
foreignKey({
|
||||
columns: [table.credentialAccessId],
|
||||
foreignColumns: [credentialAccess.id],
|
||||
name: "shared_cred_secrets_access_id_fk",
|
||||
}).onDelete("cascade"),
|
||||
uniqueIndex("idx_shared_credential_secrets_scope").on(
|
||||
table.credentialAccessId,
|
||||
table.targetUserId,
|
||||
),
|
||||
index("idx_shared_credential_secrets_target").on(
|
||||
table.targetUserId,
|
||||
table.credentialId,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
// --- folder access rules ---
|
||||
|
||||
/**
|
||||
* A standing share on a host folder. Sharing a folder fans out host_access
|
||||
* grants to the hosts in it today; this row is what makes hosts created in
|
||||
* or moved into the folder later inherit the same access.
|
||||
*/
|
||||
export const folderAccess = sqliteTable(
|
||||
"folder_access",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
ownerUserId: text("owner_user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
// The folder path as stored on hosts ("Parent / Child"); subfolders inherit.
|
||||
folder: text("folder").notNull(),
|
||||
|
||||
userId: text("user_id").references(() => users.id, { onDelete: "cascade" }),
|
||||
roleId: integer("role_id").references(() => roles.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
|
||||
grantedBy: text("granted_by")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
permissionLevel: text("permission_level").notNull().default("connect"),
|
||||
expiresAt: text("expires_at"),
|
||||
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
index("idx_folder_access_owner_folder").on(table.ownerUserId, table.folder),
|
||||
],
|
||||
);
|
||||
|
||||
// --- plugins begin ---
|
||||
|
||||
/**
|
||||
* An installed plugin. id matches the manifest's own id (not autoincrement),
|
||||
* so a plugin can be looked up the same way the manifest and registry refer
|
||||
* to it. manifest_json is the full manifest as it was at install time, kept
|
||||
* for audit/rollback even after a registry updates or removes the entry.
|
||||
*/
|
||||
export const plugins = sqliteTable(
|
||||
"plugins",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
version: text("version").notNull(),
|
||||
tier: text("tier").notNull().default("available"),
|
||||
source: text("source").notNull().default("community"),
|
||||
registryId: text("registry_id"),
|
||||
state: text("state").notNull().default("disabled"),
|
||||
installedAt: text("installed_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
autoUpdate: integer("auto_update", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
manifestJson: text("manifest_json").notNull(),
|
||||
},
|
||||
(table) => [index("idx_plugins_registry_id").on(table.registryId)],
|
||||
);
|
||||
|
||||
export const pluginPermissionGrants = sqliteTable(
|
||||
"plugin_permission_grants",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
pluginId: text("plugin_id")
|
||||
.notNull()
|
||||
.references(() => plugins.id, { onDelete: "cascade" }),
|
||||
capability: text("capability").notNull(),
|
||||
grantedAt: text("granted_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
grantedBy: text("granted_by")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
},
|
||||
// A plugin's grants are always read together, and re-granting the same
|
||||
// capability should update the existing row rather than duplicate it.
|
||||
(table) => [
|
||||
uniqueIndex("idx_plugin_permission_grants_plugin_capability").on(
|
||||
table.pluginId,
|
||||
table.capability,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
export const pluginRegistries = sqliteTable("plugin_registries", {
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
url: text("url").notNull(),
|
||||
kind: text("kind").notNull().default("community"),
|
||||
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
|
||||
signingKey: text("signing_key"),
|
||||
lastCheckedAt: text("last_checked_at"),
|
||||
lastIndexHash: text("last_index_hash"),
|
||||
});
|
||||
|
||||
/**
|
||||
* Install counts populated by a background job (GitHub release download
|
||||
* counts, aggregated telemetry, or a manual override) rather than by the
|
||||
* install/uninstall actions themselves — kept separate from `plugins` so
|
||||
* that job can overwrite counts without touching install state.
|
||||
*/
|
||||
export const pluginInstallCounts = sqliteTable(
|
||||
"plugin_install_counts",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
pluginId: text("plugin_id").notNull(),
|
||||
registryId: text("registry_id").notNull(),
|
||||
count: integer("count").notNull().default(0),
|
||||
source: text("source").notNull().default("aggregate-telemetry"),
|
||||
updatedAt: text("updated_at")
|
||||
.notNull()
|
||||
.default(sql`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("idx_plugin_install_counts_plugin_registry").on(
|
||||
table.pluginId,
|
||||
table.registryId,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
// --- plugins end ---
|
||||
@@ -0,0 +1,222 @@
|
||||
import { and, desc, eq, isNull } from "drizzle-orm";
|
||||
import { collabRoomMembers, collabRooms, users } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
|
||||
export type CollabRoomRecord = typeof collabRooms.$inferSelect;
|
||||
export type CollabRoomMemberRecord = typeof collabRoomMembers.$inferSelect;
|
||||
|
||||
export type CollabRoomRole = "host" | "member";
|
||||
|
||||
export interface CollabRoomMemberWithUser {
|
||||
userId: string;
|
||||
username: string;
|
||||
roomRole: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface CollabRoomStage {
|
||||
presenterUserId: string | null;
|
||||
stageProtocol: string | null;
|
||||
stageHostId: number | null;
|
||||
stageShareId: string | null;
|
||||
}
|
||||
|
||||
export class CollabRoomRepository {
|
||||
constructor(
|
||||
private readonly context: DatabaseContext,
|
||||
private readonly onWrite?: () => void | Promise<void>,
|
||||
) {}
|
||||
|
||||
async createRoom(input: {
|
||||
id: string;
|
||||
name: string;
|
||||
ownerUserId: string;
|
||||
persistent: boolean;
|
||||
}): Promise<CollabRoomRecord> {
|
||||
const [created] = await insertReturning(this.context, collabRooms, {
|
||||
id: input.id,
|
||||
name: input.name,
|
||||
ownerUserId: input.ownerUserId,
|
||||
persistent: input.persistent,
|
||||
});
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<CollabRoomRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(collabRooms)
|
||||
.where(eq(collabRooms.id, id))
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
/** The live room whose stage points at this share, if any. */
|
||||
async findByStageShareId(shareId: string): Promise<CollabRoomRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(collabRooms)
|
||||
.where(
|
||||
and(eq(collabRooms.stageShareId, shareId), isNull(collabRooms.endedAt)),
|
||||
)
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async findByGuestToken(token: string): Promise<CollabRoomRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(collabRooms)
|
||||
.where(
|
||||
and(eq(collabRooms.guestLinkToken, token), isNull(collabRooms.endedAt)),
|
||||
)
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async setGuestToken(roomId: string, token: string | null): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.update(collabRooms)
|
||||
.set({ guestLinkToken: token })
|
||||
.where(eq(collabRooms.id, roomId));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async listForUser(userId: string): Promise<CollabRoomRecord[]> {
|
||||
const rows = await this.context.drizzle
|
||||
.select({ room: collabRooms })
|
||||
.from(collabRoomMembers)
|
||||
.innerJoin(collabRooms, eq(collabRoomMembers.roomId, collabRooms.id))
|
||||
.where(
|
||||
and(eq(collabRoomMembers.userId, userId), isNull(collabRooms.endedAt)),
|
||||
)
|
||||
.orderBy(desc(collabRooms.createdAt));
|
||||
return rows.map((row) => row.room);
|
||||
}
|
||||
|
||||
async findMember(
|
||||
roomId: string,
|
||||
userId: string,
|
||||
): Promise<CollabRoomMemberRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(collabRoomMembers)
|
||||
.where(
|
||||
and(
|
||||
eq(collabRoomMembers.roomId, roomId),
|
||||
eq(collabRoomMembers.userId, userId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async addMember(input: {
|
||||
roomId: string;
|
||||
userId: string;
|
||||
roomRole: CollabRoomRole;
|
||||
addedBy: string | null;
|
||||
}): Promise<boolean> {
|
||||
if (await this.findMember(input.roomId, input.userId)) return false;
|
||||
await this.context.drizzle.insert(collabRoomMembers).values({
|
||||
roomId: input.roomId,
|
||||
userId: input.userId,
|
||||
roomRole: input.roomRole,
|
||||
addedBy: input.addedBy,
|
||||
});
|
||||
await this.afterWrite();
|
||||
return true;
|
||||
}
|
||||
|
||||
async removeMember(roomId: string, userId: string): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.delete(collabRoomMembers)
|
||||
.where(
|
||||
and(
|
||||
eq(collabRoomMembers.roomId, roomId),
|
||||
eq(collabRoomMembers.userId, userId),
|
||||
),
|
||||
);
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async listMembers(roomId: string): Promise<CollabRoomMemberWithUser[]> {
|
||||
return this.context.drizzle
|
||||
.select({
|
||||
userId: collabRoomMembers.userId,
|
||||
username: users.username,
|
||||
roomRole: collabRoomMembers.roomRole,
|
||||
createdAt: collabRoomMembers.createdAt,
|
||||
})
|
||||
.from(collabRoomMembers)
|
||||
.innerJoin(users, eq(collabRoomMembers.userId, users.id))
|
||||
.where(eq(collabRoomMembers.roomId, roomId))
|
||||
.orderBy(users.username);
|
||||
}
|
||||
|
||||
async updateStage(roomId: string, stage: CollabRoomStage): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.update(collabRooms)
|
||||
.set(stage)
|
||||
.where(eq(collabRooms.id, roomId));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async replaceStage(
|
||||
roomId: string,
|
||||
expectedShareId: string | null,
|
||||
stage: CollabRoomStage,
|
||||
): Promise<boolean> {
|
||||
const result = await this.context.drizzle
|
||||
.update(collabRooms)
|
||||
.set(stage)
|
||||
.where(
|
||||
and(
|
||||
eq(collabRooms.id, roomId),
|
||||
expectedShareId
|
||||
? eq(collabRooms.stageShareId, expectedShareId)
|
||||
: isNull(collabRooms.stageShareId),
|
||||
),
|
||||
);
|
||||
const changed = rowsAffected(result) > 0;
|
||||
if (changed) await this.afterWrite();
|
||||
return changed;
|
||||
}
|
||||
|
||||
async clearStage(roomId: string): Promise<void> {
|
||||
return this.updateStage(roomId, {
|
||||
presenterUserId: null,
|
||||
stageProtocol: null,
|
||||
stageHostId: null,
|
||||
stageShareId: null,
|
||||
});
|
||||
}
|
||||
|
||||
async endRoom(roomId: string): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.update(collabRooms)
|
||||
.set({
|
||||
endedAt: new Date().toISOString(),
|
||||
presenterUserId: null,
|
||||
stageProtocol: null,
|
||||
stageHostId: null,
|
||||
stageShareId: null,
|
||||
})
|
||||
.where(eq(collabRooms.id, roomId));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async deleteRoom(roomId: string): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.delete(collabRooms)
|
||||
.where(eq(collabRooms.id, roomId));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
await this.onWrite?.();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
import { and, eq, gte, inArray, isNull, or, type SQL } from "drizzle-orm";
|
||||
import { alias } from "drizzle-orm/sqlite-core";
|
||||
import {
|
||||
credentialAccess,
|
||||
roles,
|
||||
sshCredentials,
|
||||
users,
|
||||
} from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
|
||||
export type CredentialAccessRecord = typeof credentialAccess.$inferSelect;
|
||||
export type CredentialPermissionLevel = "use" | "manage";
|
||||
|
||||
export interface CredentialAccessListItem extends CredentialAccessRecord {
|
||||
targetType: "user" | "role";
|
||||
username: string | null;
|
||||
roleName: string | null;
|
||||
roleDisplayName: string | null;
|
||||
grantedByUsername: string | null;
|
||||
}
|
||||
|
||||
export type CredentialAccessTarget =
|
||||
| { targetType: "user"; targetUserId: string }
|
||||
| { targetType: "role"; targetRoleId: number };
|
||||
|
||||
export interface UpsertCredentialAccessInput {
|
||||
credentialId: number;
|
||||
grantedBy: string;
|
||||
permissionLevel: CredentialPermissionLevel;
|
||||
expiresAt: string | null;
|
||||
target: CredentialAccessTarget;
|
||||
}
|
||||
|
||||
/** A credential shared with the caller, with the grant that admits them. */
|
||||
export interface SharedCredentialGrant {
|
||||
accessId: number;
|
||||
credentialId: number;
|
||||
ownerId: string;
|
||||
permissionLevel: string;
|
||||
expiresAt: string | null;
|
||||
}
|
||||
|
||||
function activeFilter(now: string): SQL {
|
||||
return or(
|
||||
isNull(credentialAccess.expiresAt),
|
||||
gte(credentialAccess.expiresAt, now),
|
||||
)!;
|
||||
}
|
||||
|
||||
function granteeFilter(userId: string, roleIds: number[]): SQL {
|
||||
return roleIds.length === 0
|
||||
? eq(credentialAccess.userId, userId)
|
||||
: or(
|
||||
eq(credentialAccess.userId, userId),
|
||||
inArray(credentialAccess.roleId, roleIds),
|
||||
)!;
|
||||
}
|
||||
|
||||
export class CredentialAccessRepository {
|
||||
constructor(
|
||||
private readonly context: DatabaseContext,
|
||||
private readonly onWrite?: () => void | Promise<void>,
|
||||
) {}
|
||||
|
||||
async listForCredential(
|
||||
credentialId: number,
|
||||
): Promise<CredentialAccessListItem[]> {
|
||||
const granter = alias(users, "granter");
|
||||
const rows = await this.context.drizzle
|
||||
.select({
|
||||
access: credentialAccess,
|
||||
username: users.username,
|
||||
roleName: roles.name,
|
||||
roleDisplayName: roles.displayName,
|
||||
grantedByUsername: granter.username,
|
||||
})
|
||||
.from(credentialAccess)
|
||||
.leftJoin(users, eq(credentialAccess.userId, users.id))
|
||||
.leftJoin(roles, eq(credentialAccess.roleId, roles.id))
|
||||
.leftJoin(granter, eq(credentialAccess.grantedBy, granter.id))
|
||||
.where(eq(credentialAccess.credentialId, credentialId));
|
||||
return rows.map((row) => ({
|
||||
...row.access,
|
||||
targetType: row.access.roleId ? ("role" as const) : ("user" as const),
|
||||
username: row.username,
|
||||
roleName: row.roleName,
|
||||
roleDisplayName: row.roleDisplayName,
|
||||
grantedByUsername: row.grantedByUsername,
|
||||
}));
|
||||
}
|
||||
|
||||
async upsert(
|
||||
input: UpsertCredentialAccessInput,
|
||||
): Promise<{ id: number; created: boolean }> {
|
||||
const targetFilter =
|
||||
input.target.targetType === "user"
|
||||
? eq(credentialAccess.userId, input.target.targetUserId)
|
||||
: eq(credentialAccess.roleId, input.target.targetRoleId);
|
||||
const existing = await this.context.drizzle
|
||||
.select({ id: credentialAccess.id })
|
||||
.from(credentialAccess)
|
||||
.where(
|
||||
and(
|
||||
eq(credentialAccess.credentialId, input.credentialId),
|
||||
targetFilter,
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (existing[0]) {
|
||||
await this.context.drizzle
|
||||
.update(credentialAccess)
|
||||
.set({
|
||||
permissionLevel: input.permissionLevel,
|
||||
expiresAt: input.expiresAt,
|
||||
grantedBy: input.grantedBy,
|
||||
})
|
||||
.where(eq(credentialAccess.id, existing[0].id));
|
||||
await this.afterWrite();
|
||||
return { id: existing[0].id, created: false };
|
||||
}
|
||||
|
||||
const [created] = await insertReturning(this.context, credentialAccess, {
|
||||
credentialId: input.credentialId,
|
||||
userId:
|
||||
input.target.targetType === "user" ? input.target.targetUserId : null,
|
||||
roleId:
|
||||
input.target.targetType === "role" ? input.target.targetRoleId : null,
|
||||
grantedBy: input.grantedBy,
|
||||
permissionLevel: input.permissionLevel,
|
||||
expiresAt: input.expiresAt,
|
||||
});
|
||||
await this.afterWrite();
|
||||
return { id: created.id, created: true };
|
||||
}
|
||||
|
||||
async findById(
|
||||
accessId: number,
|
||||
credentialId: number,
|
||||
): Promise<CredentialAccessRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(credentialAccess)
|
||||
.where(
|
||||
and(
|
||||
eq(credentialAccess.id, accessId),
|
||||
eq(credentialAccess.credentialId, credentialId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async revoke(accessId: number, credentialId: number): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.delete(credentialAccess)
|
||||
.where(
|
||||
and(
|
||||
eq(credentialAccess.id, accessId),
|
||||
eq(credentialAccess.credentialId, credentialId),
|
||||
),
|
||||
);
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
/** The strongest unexpired grant admitting this user to the credential. */
|
||||
async findActiveGrant(
|
||||
credentialId: number,
|
||||
userId: string,
|
||||
roleIds: number[],
|
||||
now = new Date().toISOString(),
|
||||
): Promise<CredentialAccessRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(credentialAccess)
|
||||
.where(
|
||||
and(
|
||||
eq(credentialAccess.credentialId, credentialId),
|
||||
granteeFilter(userId, roleIds),
|
||||
activeFilter(now),
|
||||
),
|
||||
);
|
||||
return (
|
||||
rows.find((row) => row.permissionLevel === "manage") ?? rows[0] ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/** Every credential shared with this user (directly or via a role). */
|
||||
async listSharedWithUser(
|
||||
userId: string,
|
||||
roleIds: number[],
|
||||
now = new Date().toISOString(),
|
||||
): Promise<SharedCredentialGrant[]> {
|
||||
const rows = await this.context.drizzle
|
||||
.select({
|
||||
accessId: credentialAccess.id,
|
||||
credentialId: credentialAccess.credentialId,
|
||||
ownerId: sshCredentials.userId,
|
||||
permissionLevel: credentialAccess.permissionLevel,
|
||||
expiresAt: credentialAccess.expiresAt,
|
||||
})
|
||||
.from(credentialAccess)
|
||||
.innerJoin(
|
||||
sshCredentials,
|
||||
eq(credentialAccess.credentialId, sshCredentials.id),
|
||||
)
|
||||
.where(and(granteeFilter(userId, roleIds), activeFilter(now)));
|
||||
// Direct and role grants can overlap; keep the strongest per credential.
|
||||
const best = new Map<number, SharedCredentialGrant>();
|
||||
for (const row of rows) {
|
||||
if (row.ownerId === userId) continue;
|
||||
const current = best.get(row.credentialId);
|
||||
if (!current || row.permissionLevel === "manage")
|
||||
best.set(row.credentialId, row);
|
||||
}
|
||||
return Array.from(best.values());
|
||||
}
|
||||
|
||||
/** Active grants on one credential, expanded to user and role targets. */
|
||||
async listActiveGrants(
|
||||
credentialId: number,
|
||||
now = new Date().toISOString(),
|
||||
): Promise<CredentialAccessRecord[]> {
|
||||
return this.context.drizzle
|
||||
.select()
|
||||
.from(credentialAccess)
|
||||
.where(
|
||||
and(eq(credentialAccess.credentialId, credentialId), activeFilter(now)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Grants a role holds, with the credential owner - for new-member snapshots. */
|
||||
async listRoleGrants(
|
||||
roleId: number,
|
||||
): Promise<
|
||||
Array<{ accessId: number; credentialId: number; ownerId: string }>
|
||||
> {
|
||||
return this.context.drizzle
|
||||
.select({
|
||||
accessId: credentialAccess.id,
|
||||
credentialId: credentialAccess.credentialId,
|
||||
ownerId: sshCredentials.userId,
|
||||
})
|
||||
.from(credentialAccess)
|
||||
.innerJoin(
|
||||
sshCredentials,
|
||||
eq(credentialAccess.credentialId, sshCredentials.id),
|
||||
)
|
||||
.where(eq(credentialAccess.roleId, roleId));
|
||||
}
|
||||
|
||||
async deleteForUserReferences(userId: string): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.delete(credentialAccess)
|
||||
.where(
|
||||
or(
|
||||
eq(credentialAccess.userId, userId),
|
||||
eq(credentialAccess.grantedBy, userId),
|
||||
),
|
||||
);
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async reassignGrantedBy(fromUserId: string, toUserId: string): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.update(credentialAccess)
|
||||
.set({ grantedBy: toUserId })
|
||||
.where(eq(credentialAccess.grantedBy, fromUserId));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
await this.onWrite?.();
|
||||
}
|
||||
}
|
||||
@@ -348,6 +348,54 @@ export class CredentialRepository {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-keys every credential of one user to another: decrypt under the old
|
||||
* owner's key, encrypt under the new one, change the owner. Used when an
|
||||
* account is deleted and its data is inherited rather than dropped.
|
||||
*/
|
||||
async transferAllToUser(
|
||||
fromUserId: string,
|
||||
toUserId: string,
|
||||
): Promise<number[]> {
|
||||
const fromKey = DataCrypto.validateUserAccess(fromUserId);
|
||||
const toKey = DataCrypto.validateUserAccess(toUserId);
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(sshCredentials)
|
||||
.where(eq(sshCredentials.userId, fromUserId));
|
||||
const moved: number[] = [];
|
||||
for (const row of rows) {
|
||||
const plain = DataCrypto.decryptRecord(
|
||||
"ssh_credentials",
|
||||
row,
|
||||
fromUserId,
|
||||
fromKey,
|
||||
);
|
||||
const {
|
||||
id: _id,
|
||||
userId: _userId,
|
||||
...fields
|
||||
} = plain as Record<string, unknown>;
|
||||
const encrypted = DataCrypto.encryptRecord(
|
||||
"ssh_credentials",
|
||||
{ ...fields, id: row.id },
|
||||
toUserId,
|
||||
toKey,
|
||||
) as Record<string, unknown>;
|
||||
delete encrypted.id;
|
||||
await this.context.drizzle
|
||||
.update(sshCredentials)
|
||||
.set({
|
||||
...(encrypted as Partial<NewCredentialRecord>),
|
||||
userId: toUserId,
|
||||
})
|
||||
.where(eq(sshCredentials.id, row.id));
|
||||
moved.push(row.id);
|
||||
}
|
||||
if (moved.length) await this.afterWrite();
|
||||
return moved;
|
||||
}
|
||||
|
||||
private encryptCredentialRecordForWrite<T extends Record<string, unknown>>(
|
||||
record: T,
|
||||
userId: string,
|
||||
|
||||
@@ -32,12 +32,21 @@ import { UiPreferenceRepository } from "./ui-preference-repository.js";
|
||||
import { NetworkTopologyRepository } from "./network-topology-repository.js";
|
||||
import { OpenTabRepository } from "./open-tab-repository.js";
|
||||
import { OpksshTokenRepository } from "./opkssh-token-repository.js";
|
||||
import { PluginRepository } from "./plugin-repository.js";
|
||||
import { PluginPermissionGrantRepository } from "./plugin-permission-grant-repository.js";
|
||||
import { PluginRegistryRepository } from "./plugin-registry-repository.js";
|
||||
import { PluginInstallCountRepository } from "./plugin-install-count-repository.js";
|
||||
import { RbacAccessRepository } from "./rbac-access-repository.js";
|
||||
import { RecentActivityRepository } from "./recent-activity-repository.js";
|
||||
import { RoleRepository } from "./role-repository.js";
|
||||
import { SessionRecordingRepository } from "./session-recording-repository.js";
|
||||
import { SessionRepository } from "./session-repository.js";
|
||||
import { SessionShareRepository } from "./session-share-repository.js";
|
||||
import { CollabRoomRepository } from "./collab-room-repository.js";
|
||||
import { SecretSourceRepository } from "./secret-source-repository.js";
|
||||
import { CredentialAccessRepository } from "./credential-access-repository.js";
|
||||
import { SharedCredentialSecretsRepository } from "./shared-credential-secrets-repository.js";
|
||||
import { FolderAccessRepository } from "./folder-access-repository.js";
|
||||
import { SettingsRepository } from "./settings-repository.js";
|
||||
import { SharedHostAuthOverrideRepository } from "./shared-host-auth-override-repository.js";
|
||||
import { SharedHostSecretsRepository } from "./shared-host-secrets-repository.js";
|
||||
@@ -360,6 +369,38 @@ export function createCurrentOpksshTokenRepository(): OpksshTokenRepository {
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentPluginRepository(): PluginRepository {
|
||||
return new PluginRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
createCurrentRepositoryWriteHook("plugin_repository_write"),
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentPluginPermissionGrantRepository(): PluginPermissionGrantRepository {
|
||||
return new PluginPermissionGrantRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
createCurrentRepositoryWriteHook(
|
||||
"plugin_permission_grant_repository_write",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentPluginRegistryRepository(): PluginRegistryRepository {
|
||||
return new PluginRegistryRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
createCurrentRepositoryWriteHook("plugin_registry_repository_write"),
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentPluginInstallCountRepository(): PluginInstallCountRepository {
|
||||
return new PluginInstallCountRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
createCurrentRepositoryLazyWriteHook(
|
||||
"plugin_install_count_repository_write",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentRbacAccessRepository(): RbacAccessRepository {
|
||||
return new RbacAccessRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
@@ -395,6 +436,13 @@ export function createCurrentSessionRepository(): SessionRepository {
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentCollabRoomRepository(): CollabRoomRepository {
|
||||
return new CollabRoomRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
createCurrentRepositoryWriteHook("collab_room_repository_write"),
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentSessionShareRepository(): SessionShareRepository {
|
||||
return new SessionShareRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
@@ -499,6 +547,36 @@ export function createCurrentUserRepository(): UserRepository {
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentFolderAccessRepository(): FolderAccessRepository {
|
||||
return new FolderAccessRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
createCurrentRepositoryWriteHook("folder_access_repository_write"),
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentCredentialAccessRepository(): CredentialAccessRepository {
|
||||
return new CredentialAccessRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
createCurrentRepositoryWriteHook("credential_access_repository_write"),
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentSharedCredentialSecretsRepository(): SharedCredentialSecretsRepository {
|
||||
return new SharedCredentialSecretsRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
createCurrentRepositoryWriteHook(
|
||||
"shared_credential_secrets_repository_write",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentSecretSourceRepository(): SecretSourceRepository {
|
||||
return new SecretSourceRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
createCurrentRepositoryWriteHook("secret_source_repository_write"),
|
||||
);
|
||||
}
|
||||
|
||||
export function createCurrentVaultProfileRepository(): VaultProfileRepository {
|
||||
return new VaultProfileRepository(
|
||||
createCurrentRepositoryContext(),
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import { and, eq, inArray, like, or } from "drizzle-orm";
|
||||
import { folderAccess, roles, users } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
|
||||
export type FolderAccessRecord = typeof folderAccess.$inferSelect;
|
||||
|
||||
export interface FolderAccessListItem extends FolderAccessRecord {
|
||||
targetType: "user" | "role";
|
||||
username: string | null;
|
||||
roleName: string | null;
|
||||
roleDisplayName: string | null;
|
||||
}
|
||||
|
||||
export type FolderAccessTarget =
|
||||
| { targetType: "user"; targetUserId: string }
|
||||
| { targetType: "role"; targetRoleId: number };
|
||||
|
||||
/** "A / B / C" → ["A", "A / B", "A / B / C"]: a host inherits rules on every ancestor. */
|
||||
export function folderAncestors(folder: string): string[] {
|
||||
const parts = folder.split(" / ");
|
||||
return parts.map((_, i) => parts.slice(0, i + 1).join(" / "));
|
||||
}
|
||||
|
||||
export class FolderAccessRepository {
|
||||
constructor(
|
||||
private readonly context: DatabaseContext,
|
||||
private readonly onWrite?: () => void | Promise<void>,
|
||||
) {}
|
||||
|
||||
async upsert(input: {
|
||||
ownerUserId: string;
|
||||
folder: string;
|
||||
grantedBy: string;
|
||||
permissionLevel: string;
|
||||
expiresAt: string | null;
|
||||
target: FolderAccessTarget;
|
||||
}): Promise<FolderAccessRecord> {
|
||||
const targetFilter =
|
||||
input.target.targetType === "user"
|
||||
? eq(folderAccess.userId, input.target.targetUserId)
|
||||
: eq(folderAccess.roleId, input.target.targetRoleId);
|
||||
const existing = await this.context.drizzle
|
||||
.select()
|
||||
.from(folderAccess)
|
||||
.where(
|
||||
and(
|
||||
eq(folderAccess.ownerUserId, input.ownerUserId),
|
||||
eq(folderAccess.folder, input.folder),
|
||||
targetFilter,
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (existing[0]) {
|
||||
await this.context.drizzle
|
||||
.update(folderAccess)
|
||||
.set({
|
||||
permissionLevel: input.permissionLevel,
|
||||
expiresAt: input.expiresAt,
|
||||
grantedBy: input.grantedBy,
|
||||
})
|
||||
.where(eq(folderAccess.id, existing[0].id));
|
||||
await this.afterWrite();
|
||||
return {
|
||||
...existing[0],
|
||||
permissionLevel: input.permissionLevel,
|
||||
expiresAt: input.expiresAt,
|
||||
};
|
||||
}
|
||||
const [created] = await insertReturning(this.context, folderAccess, {
|
||||
ownerUserId: input.ownerUserId,
|
||||
folder: input.folder,
|
||||
userId:
|
||||
input.target.targetType === "user" ? input.target.targetUserId : null,
|
||||
roleId:
|
||||
input.target.targetType === "role" ? input.target.targetRoleId : null,
|
||||
grantedBy: input.grantedBy,
|
||||
permissionLevel: input.permissionLevel,
|
||||
expiresAt: input.expiresAt,
|
||||
});
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
|
||||
/** Rules that apply to a host in this folder: the folder's own and its ancestors'. */
|
||||
async listApplicable(
|
||||
ownerUserId: string,
|
||||
folder: string,
|
||||
now = new Date().toISOString(),
|
||||
): Promise<FolderAccessRecord[]> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(folderAccess)
|
||||
.where(
|
||||
and(
|
||||
eq(folderAccess.ownerUserId, ownerUserId),
|
||||
inArray(folderAccess.folder, folderAncestors(folder)),
|
||||
),
|
||||
);
|
||||
return rows.filter((row) => !row.expiresAt || row.expiresAt >= now);
|
||||
}
|
||||
|
||||
async listForFolder(
|
||||
ownerUserId: string,
|
||||
folder: string,
|
||||
): Promise<FolderAccessListItem[]> {
|
||||
const rows = await this.context.drizzle
|
||||
.select({
|
||||
rule: folderAccess,
|
||||
username: users.username,
|
||||
roleName: roles.name,
|
||||
roleDisplayName: roles.displayName,
|
||||
})
|
||||
.from(folderAccess)
|
||||
.leftJoin(users, eq(folderAccess.userId, users.id))
|
||||
.leftJoin(roles, eq(folderAccess.roleId, roles.id))
|
||||
.where(
|
||||
and(
|
||||
eq(folderAccess.ownerUserId, ownerUserId),
|
||||
eq(folderAccess.folder, folder),
|
||||
),
|
||||
);
|
||||
return rows.map((row) => ({
|
||||
...row.rule,
|
||||
targetType: row.rule.roleId ? ("role" as const) : ("user" as const),
|
||||
username: row.username,
|
||||
roleName: row.roleName,
|
||||
roleDisplayName: row.roleDisplayName,
|
||||
}));
|
||||
}
|
||||
|
||||
async findById(
|
||||
id: number,
|
||||
ownerUserId: string,
|
||||
): Promise<FolderAccessRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(folderAccess)
|
||||
.where(
|
||||
and(eq(folderAccess.id, id), eq(folderAccess.ownerUserId, ownerUserId)),
|
||||
)
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async deleteById(id: number, ownerUserId: string): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.delete(folderAccess)
|
||||
.where(
|
||||
and(eq(folderAccess.id, id), eq(folderAccess.ownerUserId, ownerUserId)),
|
||||
);
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
/** Follows a folder rename, including subfolders. */
|
||||
async renameFolder(
|
||||
ownerUserId: string,
|
||||
oldName: string,
|
||||
newName: string,
|
||||
): Promise<void> {
|
||||
const prefix = `${oldName} / `;
|
||||
const rows = await this.context.drizzle
|
||||
.select({ id: folderAccess.id, folder: folderAccess.folder })
|
||||
.from(folderAccess)
|
||||
.where(
|
||||
and(
|
||||
eq(folderAccess.ownerUserId, ownerUserId),
|
||||
or(
|
||||
eq(folderAccess.folder, oldName),
|
||||
like(folderAccess.folder, `${prefix}%`),
|
||||
),
|
||||
),
|
||||
);
|
||||
for (const row of rows) {
|
||||
const renamed =
|
||||
row.folder === oldName
|
||||
? newName
|
||||
: `${newName} / ${row.folder.slice(prefix.length)}`;
|
||||
await this.context.drizzle
|
||||
.update(folderAccess)
|
||||
.set({ folder: renamed })
|
||||
.where(eq(folderAccess.id, row.id));
|
||||
}
|
||||
if (rows.length) await this.afterWrite();
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
await this.onWrite?.();
|
||||
}
|
||||
}
|
||||
@@ -168,6 +168,47 @@ export class HostRepository {
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
/** Re-keys every host of one user to another; see CredentialRepository.transferAllToUser. */
|
||||
async transferAllToUser(
|
||||
fromUserId: string,
|
||||
toUserId: string,
|
||||
): Promise<number[]> {
|
||||
const fromKey = DataCrypto.validateUserAccess(fromUserId);
|
||||
const toKey = DataCrypto.validateUserAccess(toUserId);
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(hosts)
|
||||
.where(eq(hosts.userId, fromUserId));
|
||||
const moved: number[] = [];
|
||||
for (const row of rows) {
|
||||
const plain = DataCrypto.decryptRecord(
|
||||
"ssh_data",
|
||||
row,
|
||||
fromUserId,
|
||||
fromKey,
|
||||
);
|
||||
const {
|
||||
id: _id,
|
||||
userId: _userId,
|
||||
...fields
|
||||
} = plain as Record<string, unknown>;
|
||||
const encrypted = DataCrypto.encryptRecord(
|
||||
"ssh_data",
|
||||
{ ...fields, id: row.id },
|
||||
toUserId,
|
||||
toKey,
|
||||
) as Record<string, unknown>;
|
||||
delete encrypted.id;
|
||||
await this.context.drizzle
|
||||
.update(hosts)
|
||||
.set({ ...(encrypted as Partial<HostUpdate>), userId: toUserId })
|
||||
.where(eq(hosts.id, row.id));
|
||||
moved.push(row.id);
|
||||
}
|
||||
if (moved.length) await this.afterWrite();
|
||||
return moved;
|
||||
}
|
||||
|
||||
async updateEncryptedForUser(
|
||||
userId: string,
|
||||
hostId: number,
|
||||
|
||||
@@ -112,6 +112,19 @@ export class HostResolutionRepository {
|
||||
return this.decryptOne("ssh_data", rows[0], userId);
|
||||
}
|
||||
|
||||
async findHostIdBySyncIdForUser(
|
||||
syncId: string,
|
||||
userId: string,
|
||||
): Promise<number | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select({ id: hosts.id })
|
||||
.from(hosts)
|
||||
.where(and(eq(hosts.syncId, syncId), eq(hosts.userId, userId)))
|
||||
.limit(1);
|
||||
|
||||
return rows[0]?.id ?? null;
|
||||
}
|
||||
|
||||
async findHostUpdateState(
|
||||
hostId: number,
|
||||
): Promise<HostUpdateStateRecord | null> {
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { pluginInstallCounts } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning, updateReturning } from "./returning.js";
|
||||
|
||||
export type PluginInstallCountRecord = typeof pluginInstallCounts.$inferSelect;
|
||||
|
||||
export interface PluginInstallCountUpsertInput {
|
||||
pluginId: string;
|
||||
registryId: string;
|
||||
count: number;
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export class PluginInstallCountRepository {
|
||||
constructor(
|
||||
private readonly context: DatabaseContext,
|
||||
private readonly onWrite?: () => void | Promise<void>,
|
||||
) {}
|
||||
|
||||
async listByPlugin(pluginId: string): Promise<PluginInstallCountRecord[]> {
|
||||
return this.context.drizzle
|
||||
.select()
|
||||
.from(pluginInstallCounts)
|
||||
.where(eq(pluginInstallCounts.pluginId, pluginId));
|
||||
}
|
||||
|
||||
async findByPluginAndRegistry(
|
||||
pluginId: string,
|
||||
registryId: string,
|
||||
): Promise<PluginInstallCountRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(pluginInstallCounts)
|
||||
.where(
|
||||
and(
|
||||
eq(pluginInstallCounts.pluginId, pluginId),
|
||||
eq(pluginInstallCounts.registryId, registryId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async upsert(
|
||||
input: PluginInstallCountUpsertInput,
|
||||
now = new Date().toISOString(),
|
||||
): Promise<PluginInstallCountRecord> {
|
||||
const existing = await this.findByPluginAndRegistry(
|
||||
input.pluginId,
|
||||
input.registryId,
|
||||
);
|
||||
|
||||
if (existing) {
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
pluginInstallCounts,
|
||||
{
|
||||
count: input.count,
|
||||
source: input.source ?? existing.source,
|
||||
updatedAt: now,
|
||||
},
|
||||
eq(pluginInstallCounts.id, existing.id),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return updated;
|
||||
}
|
||||
|
||||
const [created] = await insertReturning(this.context, pluginInstallCounts, {
|
||||
pluginId: input.pluginId,
|
||||
registryId: input.registryId,
|
||||
count: input.count,
|
||||
source: input.source ?? "aggregate-telemetry",
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
|
||||
async deleteByPlugin(pluginId: string): Promise<number> {
|
||||
const result = await this.context.drizzle
|
||||
.delete(pluginInstallCounts)
|
||||
.where(eq(pluginInstallCounts.pluginId, pluginId));
|
||||
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
await this.onWrite?.();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { pluginPermissionGrants } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
|
||||
export type PluginPermissionGrantRecord =
|
||||
typeof pluginPermissionGrants.$inferSelect;
|
||||
|
||||
export interface PluginPermissionGrantCreateInput {
|
||||
pluginId: string;
|
||||
capability: string;
|
||||
grantedBy: string;
|
||||
}
|
||||
|
||||
export class PluginPermissionGrantRepository {
|
||||
constructor(
|
||||
private readonly context: DatabaseContext,
|
||||
private readonly onWrite?: () => void | Promise<void>,
|
||||
) {}
|
||||
|
||||
async listByPlugin(pluginId: string): Promise<PluginPermissionGrantRecord[]> {
|
||||
return this.context.drizzle
|
||||
.select()
|
||||
.from(pluginPermissionGrants)
|
||||
.where(eq(pluginPermissionGrants.pluginId, pluginId));
|
||||
}
|
||||
|
||||
async findGrant(
|
||||
pluginId: string,
|
||||
capability: string,
|
||||
): Promise<PluginPermissionGrantRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(pluginPermissionGrants)
|
||||
.where(
|
||||
and(
|
||||
eq(pluginPermissionGrants.pluginId, pluginId),
|
||||
eq(pluginPermissionGrants.capability, capability),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async grant(
|
||||
input: PluginPermissionGrantCreateInput,
|
||||
now = new Date().toISOString(),
|
||||
): Promise<PluginPermissionGrantRecord> {
|
||||
const [created] = await insertReturning(
|
||||
this.context,
|
||||
pluginPermissionGrants,
|
||||
{
|
||||
pluginId: input.pluginId,
|
||||
capability: input.capability,
|
||||
grantedBy: input.grantedBy,
|
||||
grantedAt: now,
|
||||
},
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
|
||||
async revoke(pluginId: string, capability: string): Promise<boolean> {
|
||||
const result = await this.context.drizzle
|
||||
.delete(pluginPermissionGrants)
|
||||
.where(
|
||||
and(
|
||||
eq(pluginPermissionGrants.pluginId, pluginId),
|
||||
eq(pluginPermissionGrants.capability, capability),
|
||||
),
|
||||
);
|
||||
|
||||
const affected = rowsAffected(result) > 0;
|
||||
if (affected) await this.afterWrite();
|
||||
return affected;
|
||||
}
|
||||
|
||||
async deleteByPlugin(pluginId: string): Promise<number> {
|
||||
const result = await this.context.drizzle
|
||||
.delete(pluginPermissionGrants)
|
||||
.where(eq(pluginPermissionGrants.pluginId, pluginId));
|
||||
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
await this.onWrite?.();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { pluginRegistries } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import {
|
||||
deleteReturning,
|
||||
insertReturning,
|
||||
updateReturning,
|
||||
} from "./returning.js";
|
||||
|
||||
export type PluginRegistryRecord = typeof pluginRegistries.$inferSelect;
|
||||
|
||||
export interface PluginRegistryCreateInput {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
kind?: string;
|
||||
enabled?: boolean;
|
||||
signingKey?: string | null;
|
||||
}
|
||||
|
||||
export interface PluginRegistryUpdateInput {
|
||||
name?: string;
|
||||
url?: string;
|
||||
kind?: string;
|
||||
enabled?: boolean;
|
||||
signingKey?: string | null;
|
||||
lastCheckedAt?: string | null;
|
||||
lastIndexHash?: string | null;
|
||||
}
|
||||
|
||||
export class PluginRegistryRepository {
|
||||
constructor(
|
||||
private readonly context: DatabaseContext,
|
||||
private readonly onWrite?: () => void | Promise<void>,
|
||||
) {}
|
||||
|
||||
async listAll(): Promise<PluginRegistryRecord[]> {
|
||||
return this.context.drizzle.select().from(pluginRegistries);
|
||||
}
|
||||
|
||||
async findById(registryId: string): Promise<PluginRegistryRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(pluginRegistries)
|
||||
.where(eq(pluginRegistries.id, registryId))
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async create(
|
||||
input: PluginRegistryCreateInput,
|
||||
): Promise<PluginRegistryRecord> {
|
||||
const [created] = await insertReturning(this.context, pluginRegistries, {
|
||||
id: input.id,
|
||||
name: input.name,
|
||||
url: input.url,
|
||||
kind: input.kind ?? "community",
|
||||
enabled: input.enabled ?? true,
|
||||
signingKey: input.signingKey ?? null,
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
|
||||
async update(
|
||||
registryId: string,
|
||||
input: PluginRegistryUpdateInput,
|
||||
): Promise<PluginRegistryRecord | null> {
|
||||
const existing = await this.findById(registryId);
|
||||
if (!existing) return null;
|
||||
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
pluginRegistries,
|
||||
{
|
||||
name: input.name ?? existing.name,
|
||||
url: input.url ?? existing.url,
|
||||
kind: input.kind ?? existing.kind,
|
||||
enabled: input.enabled ?? existing.enabled,
|
||||
signingKey:
|
||||
input.signingKey === undefined
|
||||
? existing.signingKey
|
||||
: input.signingKey,
|
||||
lastCheckedAt:
|
||||
input.lastCheckedAt === undefined
|
||||
? existing.lastCheckedAt
|
||||
: input.lastCheckedAt,
|
||||
lastIndexHash:
|
||||
input.lastIndexHash === undefined
|
||||
? existing.lastIndexHash
|
||||
: input.lastIndexHash,
|
||||
},
|
||||
eq(pluginRegistries.id, registryId),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async delete(registryId: string): Promise<boolean> {
|
||||
const deleted = await deleteReturning(
|
||||
this.context,
|
||||
pluginRegistries,
|
||||
eq(pluginRegistries.id, registryId),
|
||||
);
|
||||
|
||||
if (deleted.length > 0) {
|
||||
await this.afterWrite();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async deleteAll(): Promise<number> {
|
||||
const all = await this.listAll();
|
||||
const result = await this.context.drizzle.delete(pluginRegistries);
|
||||
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
return all.length;
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
await this.onWrite?.();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { plugins } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import {
|
||||
deleteReturning,
|
||||
insertReturning,
|
||||
updateReturning,
|
||||
} from "./returning.js";
|
||||
|
||||
export type PluginRecord = typeof plugins.$inferSelect;
|
||||
|
||||
export interface PluginCreateInput {
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
tier?: string;
|
||||
source?: string;
|
||||
registryId?: string | null;
|
||||
state?: string;
|
||||
autoUpdate?: boolean;
|
||||
manifestJson: string;
|
||||
}
|
||||
|
||||
export interface PluginUpdateInput {
|
||||
name?: string;
|
||||
version?: string;
|
||||
tier?: string;
|
||||
source?: string;
|
||||
registryId?: string | null;
|
||||
state?: string;
|
||||
autoUpdate?: boolean;
|
||||
manifestJson?: string;
|
||||
}
|
||||
|
||||
export class PluginRepository {
|
||||
constructor(
|
||||
private readonly context: DatabaseContext,
|
||||
private readonly onWrite?: () => void | Promise<void>,
|
||||
) {}
|
||||
|
||||
async listAll(): Promise<PluginRecord[]> {
|
||||
return this.context.drizzle.select().from(plugins);
|
||||
}
|
||||
|
||||
async findById(pluginId: string): Promise<PluginRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(plugins)
|
||||
.where(eq(plugins.id, pluginId))
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async create(
|
||||
input: PluginCreateInput,
|
||||
now = new Date().toISOString(),
|
||||
): Promise<PluginRecord> {
|
||||
const [created] = await insertReturning(this.context, plugins, {
|
||||
id: input.id,
|
||||
name: input.name,
|
||||
version: input.version,
|
||||
tier: input.tier ?? "available",
|
||||
source: input.source ?? "community",
|
||||
registryId: input.registryId ?? null,
|
||||
state: input.state ?? "disabled",
|
||||
autoUpdate: input.autoUpdate ?? false,
|
||||
manifestJson: input.manifestJson,
|
||||
installedAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
|
||||
async update(
|
||||
pluginId: string,
|
||||
input: PluginUpdateInput,
|
||||
now = new Date().toISOString(),
|
||||
): Promise<PluginRecord | null> {
|
||||
const existing = await this.findById(pluginId);
|
||||
if (!existing) return null;
|
||||
|
||||
const [updated] = await updateReturning(
|
||||
this.context,
|
||||
plugins,
|
||||
{
|
||||
name: input.name ?? existing.name,
|
||||
version: input.version ?? existing.version,
|
||||
tier: input.tier ?? existing.tier,
|
||||
source: input.source ?? existing.source,
|
||||
registryId:
|
||||
input.registryId === undefined
|
||||
? existing.registryId
|
||||
: input.registryId,
|
||||
state: input.state ?? existing.state,
|
||||
autoUpdate: input.autoUpdate ?? existing.autoUpdate,
|
||||
manifestJson: input.manifestJson ?? existing.manifestJson,
|
||||
updatedAt: now,
|
||||
},
|
||||
eq(plugins.id, pluginId),
|
||||
);
|
||||
|
||||
await this.afterWrite();
|
||||
return updated ?? null;
|
||||
}
|
||||
|
||||
async delete(pluginId: string): Promise<boolean> {
|
||||
const deleted = await deleteReturning(
|
||||
this.context,
|
||||
plugins,
|
||||
eq(plugins.id, pluginId),
|
||||
);
|
||||
|
||||
if (deleted.length > 0) {
|
||||
await this.afterWrite();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async deleteAll(): Promise<number> {
|
||||
const all = await this.listAll();
|
||||
const result = await this.context.drizzle.delete(plugins);
|
||||
|
||||
if (rowsAffected(result) > 0) {
|
||||
await this.afterWrite();
|
||||
}
|
||||
return all.length;
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
await this.onWrite?.();
|
||||
}
|
||||
}
|
||||
@@ -207,6 +207,18 @@ export class RbacAccessRepository {
|
||||
return rowsAffected(result);
|
||||
}
|
||||
|
||||
/** Grants the departing user handed out now count as the successor's. */
|
||||
async reassignHostAccessGrantedBy(
|
||||
fromUserId: string,
|
||||
toUserId: string,
|
||||
): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.update(hostAccess)
|
||||
.set({ grantedBy: toUserId })
|
||||
.where(eq(hostAccess.grantedBy, fromUserId));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async deleteHostAccessForUserReferences(userId: string): Promise<number> {
|
||||
const directResult = await this.context.drizzle
|
||||
.delete(hostAccess)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { hostAccess, roles, userRoles } from "../db/schema.js";
|
||||
import { hostAccess, roles, userRoles, users } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { rowsAffected } from "./mutation-result.js";
|
||||
import { deleteReturning, insertReturning } from "./returning.js";
|
||||
@@ -8,7 +8,7 @@ export type RoleRecord = typeof roles.$inferSelect;
|
||||
export type NewRoleRecord = typeof roles.$inferInsert;
|
||||
export type RoleUpdate = Pick<
|
||||
Partial<NewRoleRecord>,
|
||||
"displayName" | "description" | "updatedAt"
|
||||
"displayName" | "description" | "permissions" | "updatedAt"
|
||||
>;
|
||||
|
||||
export type UserRoleWithRole = {
|
||||
@@ -21,6 +21,13 @@ export type UserRoleWithRole = {
|
||||
grantedAt: string;
|
||||
};
|
||||
|
||||
export type RoleMemberRecord = {
|
||||
userId: string;
|
||||
username: string;
|
||||
grantedAt: string;
|
||||
grantedBy: string | null;
|
||||
};
|
||||
|
||||
export type UserRolePermissionRecord = {
|
||||
permissions: string | null;
|
||||
};
|
||||
@@ -226,6 +233,20 @@ export class RoleRepository {
|
||||
return rows.map((row) => row.userId);
|
||||
}
|
||||
|
||||
async listRoleMembers(roleId: number): Promise<RoleMemberRecord[]> {
|
||||
return this.context.drizzle
|
||||
.select({
|
||||
userId: userRoles.userId,
|
||||
username: users.username,
|
||||
grantedAt: userRoles.grantedAt,
|
||||
grantedBy: userRoles.grantedBy,
|
||||
})
|
||||
.from(userRoles)
|
||||
.innerJoin(users, eq(userRoles.userId, users.id))
|
||||
.where(eq(userRoles.roleId, roleId))
|
||||
.orderBy(users.username);
|
||||
}
|
||||
|
||||
async listUserRolePermissions(
|
||||
userId: string,
|
||||
): Promise<UserRolePermissionRecord[]> {
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { desc, eq, or } from "drizzle-orm";
|
||||
import { secretSources } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
import { insertReturning } from "./returning.js";
|
||||
import { DataCrypto } from "../../utils/data-crypto.js";
|
||||
import { FieldCrypto } from "../../utils/field-crypto.js";
|
||||
|
||||
export type SecretSourceRecord = typeof secretSources.$inferSelect;
|
||||
export type SecretSourceKind = "onepassword-connect";
|
||||
|
||||
/** A row with the token still encrypted - safe to hand to the API. */
|
||||
export type SecretSourcePublic = Omit<SecretSourceRecord, "token"> & {
|
||||
hasToken: boolean;
|
||||
};
|
||||
|
||||
export interface SecretSourceCreateInput {
|
||||
id: string;
|
||||
userId: string;
|
||||
name: string;
|
||||
kind: SecretSourceKind;
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
shared: boolean;
|
||||
}
|
||||
|
||||
export interface SecretSourceUpdateInput {
|
||||
name?: string;
|
||||
baseUrl?: string;
|
||||
token?: string;
|
||||
shared?: boolean;
|
||||
}
|
||||
|
||||
export function toPublicSecretSource(
|
||||
row: SecretSourceRecord,
|
||||
): SecretSourcePublic {
|
||||
const { token, ...rest } = row;
|
||||
return { ...rest, hasToken: token.length > 0 };
|
||||
}
|
||||
|
||||
/**
|
||||
* The token is encrypted with the owner's data key under the row id, like
|
||||
* vault_tokens - so a shared source only decrypts while its owner's key is
|
||||
* loaded, which the resolver reports as a clear error.
|
||||
*/
|
||||
export class SecretSourceRepository {
|
||||
constructor(
|
||||
private readonly context: DatabaseContext,
|
||||
private readonly onWrite?: () => void | Promise<void>,
|
||||
) {}
|
||||
|
||||
private encryptToken(id: string, ownerId: string, token: string): string {
|
||||
const key = DataCrypto.validateUserAccess(ownerId);
|
||||
return FieldCrypto.encryptField(token, key, id, "token");
|
||||
}
|
||||
|
||||
decryptToken(row: SecretSourceRecord): string {
|
||||
const key = DataCrypto.getUserDataKey(row.userId);
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
"The secret source owner's data is locked; they need to sign in first",
|
||||
);
|
||||
}
|
||||
return FieldCrypto.decryptField(row.token, key, row.id, "token");
|
||||
}
|
||||
|
||||
async listVisibleToUser(userId: string): Promise<SecretSourceRecord[]> {
|
||||
return this.context.drizzle
|
||||
.select()
|
||||
.from(secretSources)
|
||||
.where(
|
||||
or(eq(secretSources.userId, userId), eq(secretSources.shared, true)),
|
||||
)
|
||||
.orderBy(desc(secretSources.updatedAt));
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<SecretSourceRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(secretSources)
|
||||
.where(eq(secretSources.id, id))
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async create(input: SecretSourceCreateInput): Promise<SecretSourceRecord> {
|
||||
const [created] = await insertReturning(this.context, secretSources, {
|
||||
id: input.id,
|
||||
userId: input.userId,
|
||||
name: input.name,
|
||||
kind: input.kind,
|
||||
baseUrl: input.baseUrl,
|
||||
token: this.encryptToken(input.id, input.userId, input.token),
|
||||
shared: input.shared,
|
||||
});
|
||||
await this.afterWrite();
|
||||
return created;
|
||||
}
|
||||
|
||||
async update(
|
||||
row: SecretSourceRecord,
|
||||
input: SecretSourceUpdateInput,
|
||||
): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.update(secretSources)
|
||||
.set({
|
||||
...(input.name !== undefined ? { name: input.name } : {}),
|
||||
...(input.baseUrl !== undefined ? { baseUrl: input.baseUrl } : {}),
|
||||
...(input.shared !== undefined ? { shared: input.shared } : {}),
|
||||
...(input.token !== undefined
|
||||
? { token: this.encryptToken(row.id, row.userId, input.token) }
|
||||
: {}),
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
.where(eq(secretSources.id, row.id));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async deleteById(id: string): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.delete(secretSources)
|
||||
.where(eq(secretSources.id, id));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async deleteByUserId(userId: string): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.delete(secretSources)
|
||||
.where(eq(secretSources.userId, userId));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
await this.onWrite?.();
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,9 @@ export type SessionShareRecord = typeof sessionShares.$inferSelect;
|
||||
export type SessionShareParticipantRecord =
|
||||
typeof sessionShareParticipants.$inferSelect;
|
||||
|
||||
export type SessionShareType = "link" | "user";
|
||||
// "room" shares are minted internally by the collab-room routes and are
|
||||
// joinable by any member of the room whose stage references them.
|
||||
export type SessionShareType = "link" | "user" | "room";
|
||||
export type SessionSharePermissionLevel = "read-only" | "read-write";
|
||||
|
||||
export interface SessionShareCreateInput {
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { credentialAccess, sharedCredentialSecrets } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
|
||||
export type SharedCredentialSecretRecord =
|
||||
typeof sharedCredentialSecrets.$inferSelect;
|
||||
export type NewSharedCredentialSecretRecord =
|
||||
typeof sharedCredentialSecrets.$inferInsert;
|
||||
|
||||
export class SharedCredentialSecretsRepository {
|
||||
constructor(
|
||||
private readonly context: DatabaseContext,
|
||||
private readonly onWrite?: () => void | Promise<void>,
|
||||
) {}
|
||||
|
||||
async upsert(record: NewSharedCredentialSecretRecord): Promise<void> {
|
||||
const existing = await this.context.drizzle
|
||||
.select({ id: sharedCredentialSecrets.id })
|
||||
.from(sharedCredentialSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
sharedCredentialSecrets.credentialAccessId,
|
||||
record.credentialAccessId,
|
||||
),
|
||||
eq(sharedCredentialSecrets.targetUserId, record.targetUserId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (existing[0]) {
|
||||
await this.context.drizzle
|
||||
.update(sharedCredentialSecrets)
|
||||
.set({ ...record, updatedAt: new Date().toISOString() })
|
||||
.where(eq(sharedCredentialSecrets.id, existing[0].id));
|
||||
} else {
|
||||
await this.context.drizzle.insert(sharedCredentialSecrets).values(record);
|
||||
}
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
/** The recipient's snapshot for a credential, whichever grant produced it. */
|
||||
async findForCredentialUser(
|
||||
credentialId: number,
|
||||
targetUserId: string,
|
||||
): Promise<SharedCredentialSecretRecord | null> {
|
||||
const rows = await this.context.drizzle
|
||||
.select()
|
||||
.from(sharedCredentialSecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(sharedCredentialSecrets.credentialId, credentialId),
|
||||
eq(sharedCredentialSecrets.targetUserId, targetUserId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
async deleteForRoleMember(
|
||||
roleId: number,
|
||||
targetUserId: string,
|
||||
): Promise<void> {
|
||||
const grants = await this.context.drizzle
|
||||
.select({ id: credentialAccess.id })
|
||||
.from(credentialAccess)
|
||||
.where(eq(credentialAccess.roleId, roleId));
|
||||
if (grants.length === 0) return;
|
||||
await this.context.drizzle.delete(sharedCredentialSecrets).where(
|
||||
and(
|
||||
inArray(
|
||||
sharedCredentialSecrets.credentialAccessId,
|
||||
grants.map((g) => g.id),
|
||||
),
|
||||
eq(sharedCredentialSecrets.targetUserId, targetUserId),
|
||||
),
|
||||
);
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
async deleteByTargetUserId(userId: string): Promise<void> {
|
||||
await this.context.drizzle
|
||||
.delete(sharedCredentialSecrets)
|
||||
.where(eq(sharedCredentialSecrets.targetUserId, userId));
|
||||
await this.afterWrite();
|
||||
}
|
||||
|
||||
private async afterWrite(): Promise<void> {
|
||||
await this.onWrite?.();
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,33 @@ export class SharedHostAuthOverrideRepository {
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
/** Recipient overrides for a host keyed by protocol, in one query. */
|
||||
async listCredentialIds(
|
||||
hostId: number,
|
||||
userId: string,
|
||||
): Promise<Partial<Record<AuthOverrideProtocol, number>>> {
|
||||
const rows = await this.context.drizzle
|
||||
.select({
|
||||
protocol: sharedHostAuthOverrides.protocol,
|
||||
credentialId: sharedHostAuthOverrides.credentialId,
|
||||
})
|
||||
.from(sharedHostAuthOverrides)
|
||||
.where(
|
||||
and(
|
||||
eq(sharedHostAuthOverrides.hostId, hostId),
|
||||
eq(sharedHostAuthOverrides.userId, userId),
|
||||
),
|
||||
);
|
||||
|
||||
const result: Partial<Record<AuthOverrideProtocol, number>> = {};
|
||||
for (const row of rows) {
|
||||
if (row.credentialId) {
|
||||
result[row.protocol as AuthOverrideProtocol] = row.credentialId;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async findCredentialId(
|
||||
hostId: number,
|
||||
userId: string,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, asc, eq, sql } from "drizzle-orm";
|
||||
import { and, asc, eq, like, or, sql } from "drizzle-orm";
|
||||
import { randomUUID } from "crypto";
|
||||
import { snippetFolders, snippets } from "../db/schema.js";
|
||||
import type { DatabaseContext } from "./database-context.js";
|
||||
@@ -108,6 +108,25 @@ export class SnippetRepository {
|
||||
return this.listFolders(userId);
|
||||
}
|
||||
|
||||
/** Snippets in a folder or any of its subfolders ("Parent / Child"). */
|
||||
async listOwnedSnippetsInFolder(
|
||||
userId: string,
|
||||
folder: string,
|
||||
): Promise<SnippetRecord[]> {
|
||||
return this.context.drizzle
|
||||
.select()
|
||||
.from(snippets)
|
||||
.where(
|
||||
and(
|
||||
eq(snippets.userId, userId),
|
||||
or(
|
||||
eq(snippets.folder, folder),
|
||||
like(snippets.folder, `${folder} / %`),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async listOwnedSnippets(userId: string): Promise<SnippetRecord[]> {
|
||||
return this.context.drizzle
|
||||
.select()
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
Trigger,
|
||||
} from "../../../types/automations.js";
|
||||
import { AUTOMATION_DEFINITION_VERSION } from "../../../types/automations.js";
|
||||
import { PermissionManager } from "../../utils/permission-manager.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
import {
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
const router = express.Router();
|
||||
|
||||
const authManager = AuthManager.getInstance();
|
||||
const permissionManager = PermissionManager.getInstance();
|
||||
const authenticateJWT = authManager.createAuthMiddleware();
|
||||
const requireDataAccess = authManager.createDataAccessMiddleware();
|
||||
|
||||
@@ -244,6 +246,7 @@ async function syncSchedule(
|
||||
router.get(
|
||||
"/",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("automations.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -282,6 +285,7 @@ router.get(
|
||||
router.get(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("automations.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -333,6 +337,7 @@ router.get(
|
||||
router.post(
|
||||
"/",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("automations.create"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -423,6 +428,7 @@ router.post(
|
||||
router.put(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("automations.edit"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -531,6 +537,7 @@ router.put(
|
||||
router.delete(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("automations.delete"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -600,6 +607,7 @@ router.delete(
|
||||
router.post(
|
||||
"/:id/run",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("automations.run"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -673,6 +681,7 @@ router.post(
|
||||
router.get(
|
||||
"/runs/history",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("automations.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -715,6 +724,7 @@ router.get(
|
||||
router.get(
|
||||
"/runs/:runId/steps",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("automations.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import type { Request, RequestHandler, Response, Router } from "express";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
import { createCurrentSettingsRepository } from "../repositories/factory.js";
|
||||
import {
|
||||
BRANDING_KEYS,
|
||||
parseBrandingAppName,
|
||||
parseBrandingLogoDataUrl,
|
||||
parseBrandingTagline,
|
||||
resolveBrandingSettings,
|
||||
} from "./branding-settings.js";
|
||||
|
||||
const PATCHABLE_FIELDS = ["appName", "tagline", "logo"] as const;
|
||||
type PatchableField = (typeof PATCHABLE_FIELDS)[number];
|
||||
|
||||
function invalidField(res: Response, field: string): void {
|
||||
res.status(400).json({
|
||||
error: `Invalid value for ${field}`,
|
||||
code: "BRANDING_SETTINGS_INVALID",
|
||||
field,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates a PATCH body and returns the settings-table writes/deletes it
|
||||
* implies, or null after the response has already been failed with a 400.
|
||||
* `logo: null` clears the custom logo (falls back to the bundled default).
|
||||
*/
|
||||
async function buildBrandingWrites(
|
||||
body: unknown,
|
||||
res: Response,
|
||||
): Promise<{
|
||||
writes: Array<{ key: string; value: string }>;
|
||||
deletes: string[];
|
||||
} | null> {
|
||||
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
||||
res.status(400).json({
|
||||
error: "Invalid request body",
|
||||
code: "BRANDING_SETTINGS_INVALID",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const field of Object.keys(body)) {
|
||||
if (!(PATCHABLE_FIELDS as readonly string[]).includes(field)) {
|
||||
res.status(400).json({
|
||||
error: `Unknown setting field: ${field}`,
|
||||
code: "BRANDING_SETTINGS_UNKNOWN_FIELD",
|
||||
field,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const input = body as Partial<Record<PatchableField, unknown>>;
|
||||
const writes: Array<{ key: string; value: string }> = [];
|
||||
const deletes: string[] = [];
|
||||
|
||||
if (input.appName !== undefined) {
|
||||
const appName = parseBrandingAppName(input.appName);
|
||||
if (appName === null) {
|
||||
invalidField(res, "appName");
|
||||
return null;
|
||||
}
|
||||
writes.push({ key: BRANDING_KEYS.appName, value: appName });
|
||||
}
|
||||
|
||||
if (input.tagline !== undefined) {
|
||||
const tagline = parseBrandingTagline(input.tagline);
|
||||
if (tagline === null) {
|
||||
invalidField(res, "tagline");
|
||||
return null;
|
||||
}
|
||||
writes.push({ key: BRANDING_KEYS.tagline, value: tagline });
|
||||
}
|
||||
|
||||
if (input.logo !== undefined) {
|
||||
if (input.logo === null) {
|
||||
deletes.push(BRANDING_KEYS.logo);
|
||||
} else {
|
||||
const logo = await parseBrandingLogoDataUrl(input.logo);
|
||||
if (logo === null) {
|
||||
invalidField(res, "logo");
|
||||
return null;
|
||||
}
|
||||
writes.push({ key: BRANDING_KEYS.logo, value: logo });
|
||||
}
|
||||
}
|
||||
|
||||
return { writes, deletes };
|
||||
}
|
||||
|
||||
export function registerBrandingRoutes(
|
||||
router: Router,
|
||||
requireAdmin: RequestHandler,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
* /users/branding:
|
||||
* get:
|
||||
* summary: Get white-label branding
|
||||
* description: Returns the effective app name, tagline and logo. Public (no auth) so the pre-login screen and app bootstrap can apply branding before any session exists.
|
||||
* tags:
|
||||
* - Users
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Effective branding settings.
|
||||
* 500:
|
||||
* description: Failed to load branding settings.
|
||||
*/
|
||||
router.get("/branding", async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const settings = await resolveBrandingSettings(
|
||||
createCurrentSettingsRepository(),
|
||||
);
|
||||
res.json(settings);
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to load branding settings", err);
|
||||
res.status(500).json({ error: "Failed to load branding settings" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/branding:
|
||||
* patch:
|
||||
* summary: Update white-label branding (admin only)
|
||||
* description: Persists a partial update to appName, tagline and/or logo (a PNG/JPEG/WEBP data URL; pass null to clear the logo). Invalid values are rejected with a 400.
|
||||
* tags:
|
||||
* - Users
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated effective branding settings.
|
||||
* 400:
|
||||
* description: Invalid or unknown setting field.
|
||||
* 401:
|
||||
* description: Not authenticated.
|
||||
* 403:
|
||||
* description: Admin access required.
|
||||
* 500:
|
||||
* description: Failed to save branding settings.
|
||||
*/
|
||||
router.patch(
|
||||
"/branding",
|
||||
requireAdmin,
|
||||
async (req: Request, res: Response) => {
|
||||
const result = await buildBrandingWrites(req.body, res);
|
||||
if (result === null) return;
|
||||
|
||||
try {
|
||||
const settings = createCurrentSettingsRepository();
|
||||
if (result.writes.length > 0) {
|
||||
await settings.setMany(result.writes);
|
||||
}
|
||||
for (const key of result.deletes) {
|
||||
await settings.delete(key);
|
||||
}
|
||||
const resolved = await resolveBrandingSettings(settings);
|
||||
res.json(resolved);
|
||||
} catch (err) {
|
||||
databaseLogger.error("Failed to save branding settings", err);
|
||||
res.status(500).json({ error: "Failed to save branding settings" });
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import sharp from "sharp";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
|
||||
/**
|
||||
* White-label branding: admin-configurable app name, logo and tagline shown
|
||||
* on the login screen and the browser tab. Persisted in the generic
|
||||
* key/value `settings` table -- no schema migration needed.
|
||||
*/
|
||||
export interface BrandingSettings {
|
||||
appName: string;
|
||||
tagline: string;
|
||||
/** PNG data URL, or null when no custom logo is configured. */
|
||||
logo: string | null;
|
||||
}
|
||||
|
||||
export const BRANDING_KEYS = {
|
||||
appName: "branding_app_name",
|
||||
tagline: "branding_tagline",
|
||||
logo: "branding_logo",
|
||||
} as const;
|
||||
|
||||
export const BRANDING_DEFAULT_APP_NAME = "Termix";
|
||||
const APP_NAME_MAX_LENGTH = 60;
|
||||
const TAGLINE_MAX_LENGTH = 160;
|
||||
|
||||
/**
|
||||
* Cap applies to the decoded image bytes, not the base64 text. The settings
|
||||
* table is fully cached in memory per backend process (see
|
||||
* settings-cache.ts), so an oversized logo would be permanently resident RAM
|
||||
* on every instance, not just a one-time upload cost.
|
||||
*/
|
||||
export const BRANDING_LOGO_MAX_BYTES = 750 * 1024;
|
||||
const BRANDING_LOGO_MAX_INPUT_PIXELS = 20_000_000;
|
||||
|
||||
interface SettingSource {
|
||||
get(key: string): Promise<string | null>;
|
||||
}
|
||||
|
||||
export async function resolveBrandingSettings(
|
||||
settings: SettingSource,
|
||||
): Promise<BrandingSettings> {
|
||||
const [appName, tagline, logo] = await Promise.all([
|
||||
settings.get(BRANDING_KEYS.appName),
|
||||
settings.get(BRANDING_KEYS.tagline),
|
||||
settings.get(BRANDING_KEYS.logo),
|
||||
]);
|
||||
|
||||
return {
|
||||
appName: appName?.trim() || BRANDING_DEFAULT_APP_NAME,
|
||||
tagline: tagline ?? "",
|
||||
logo: logo || null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Trimmed, 1-60 chars. Falls back to the default when cleared. */
|
||||
export function parseBrandingAppName(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return BRANDING_DEFAULT_APP_NAME;
|
||||
if (trimmed.length > APP_NAME_MAX_LENGTH) return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/** Trimmed, 0-160 chars. An empty string means "use the built-in default". */
|
||||
export function parseBrandingTagline(value: unknown): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length > TAGLINE_MAX_LENGTH) return null;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates and re-encodes an uploaded logo. Only raster formats are
|
||||
* accepted (no SVG), sidestepping SVG-script XSS entirely rather than trying
|
||||
* to sanitize markup. The image is always re-encoded to PNG through sharp:
|
||||
* this both proves the payload is a genuine image (not a disguised file
|
||||
* behind a spoofed data-URL prefix) and strips any embedded metadata.
|
||||
*
|
||||
* Returns null on any validation failure; the caller is expected to reject
|
||||
* the request with a 400 without echoing back details of what was rejected.
|
||||
*/
|
||||
export async function parseBrandingLogoDataUrl(
|
||||
value: unknown,
|
||||
): Promise<string | null> {
|
||||
if (typeof value !== "string") return null;
|
||||
const match = value.match(
|
||||
/^data:image\/(png|jpe?g|webp);base64,([a-zA-Z0-9+/]+=*)$/,
|
||||
);
|
||||
if (!match) return null;
|
||||
|
||||
const [, , base64] = match;
|
||||
let buffer: Buffer;
|
||||
try {
|
||||
buffer = Buffer.from(base64, "base64");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (buffer.length === 0 || buffer.length > BRANDING_LOGO_MAX_BYTES * 4) {
|
||||
// Reject wildly oversized input before decoding it with sharp; the final
|
||||
// size check happens below on the re-encoded PNG.
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const source = sharp(buffer, {
|
||||
failOn: "error",
|
||||
limitInputPixels: BRANDING_LOGO_MAX_INPUT_PIXELS,
|
||||
});
|
||||
const metadata = await source.metadata();
|
||||
if (
|
||||
!metadata.format ||
|
||||
!["png", "jpeg", "webp"].includes(metadata.format)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const normalized = await source.rotate().png().toBuffer();
|
||||
if (normalized.length > BRANDING_LOGO_MAX_BYTES) return null;
|
||||
return `data:image/png;base64,${normalized.toString("base64")}`;
|
||||
} catch (err) {
|
||||
databaseLogger.warn("Rejected invalid branding logo upload", {
|
||||
operation: "branding_logo_invalid",
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { createCurrentCredentialRepository } from "../repositories/factory.js";
|
||||
export function registerCredentialBulkRoutes(
|
||||
router: Router,
|
||||
authenticateJWT: RequestHandler,
|
||||
requireEditPermission: RequestHandler,
|
||||
requireDataAccess: RequestHandler,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
@@ -42,6 +44,8 @@ export function registerCredentialBulkRoutes(
|
||||
router.put(
|
||||
"/reorder",
|
||||
authenticateJWT,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { positions } = req.body as {
|
||||
|
||||
@@ -359,6 +359,9 @@ async function deploySSHKeyToHost(
|
||||
export function registerCredentialDeployRoutes(
|
||||
router: Router,
|
||||
authenticateJWT: RequestHandler,
|
||||
requireCredentialViewPermission: RequestHandler,
|
||||
requireHostEditPermission: RequestHandler,
|
||||
requireDataAccess: RequestHandler,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
@@ -398,6 +401,9 @@ export function registerCredentialDeployRoutes(
|
||||
router.post(
|
||||
"/:id/deploy-to-host",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireHostEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const id = Array.isArray(req.params.id)
|
||||
? req.params.id[0]
|
||||
|
||||
@@ -63,6 +63,8 @@ function generateSSHKeyPair(
|
||||
export function registerCredentialKeyRoutes(
|
||||
router: Router,
|
||||
authenticateJWT: RequestHandler,
|
||||
requireCredentialViewPermission: RequestHandler,
|
||||
requireDataAccess: RequestHandler,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
@@ -94,6 +96,8 @@ export function registerCredentialKeyRoutes(
|
||||
router.post(
|
||||
"/detect-key-type",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const { privateKey, keyPassword } = req.body;
|
||||
|
||||
@@ -150,6 +154,8 @@ export function registerCredentialKeyRoutes(
|
||||
router.post(
|
||||
"/detect-public-key-type",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const { publicKey } = req.body;
|
||||
|
||||
@@ -209,6 +215,8 @@ export function registerCredentialKeyRoutes(
|
||||
router.post(
|
||||
"/validate-key-pair",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const { privateKey, publicKey, keyPassword } = req.body;
|
||||
|
||||
@@ -274,6 +282,8 @@ export function registerCredentialKeyRoutes(
|
||||
router.post(
|
||||
"/generate-key-pair",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const { keyType = "ssh-ed25519", keySize = 2048, passphrase } = req.body;
|
||||
|
||||
@@ -339,6 +349,8 @@ export function registerCredentialKeyRoutes(
|
||||
router.post(
|
||||
"/generate-public-key",
|
||||
authenticateJWT,
|
||||
requireCredentialViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const { privateKey, keyPassword } = req.body;
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import express, { type Request, type Response } from "express";
|
||||
import { authLogger } from "../../utils/logger.js";
|
||||
import { PermissionManager } from "../../utils/permission-manager.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { parseSSHKey } from "../../utils/ssh-key-utils.js";
|
||||
import { registerCredentialKeyRoutes } from "./credential-key-routes.js";
|
||||
@@ -14,6 +15,9 @@ import {
|
||||
} from "../../utils/audit-logger.js";
|
||||
import {
|
||||
createCurrentCredentialRepository,
|
||||
createCurrentUserRepository,
|
||||
createCurrentCredentialAccessRepository,
|
||||
createCurrentRoleRepository,
|
||||
createCurrentHostResolutionRepository,
|
||||
createCurrentHostRepository,
|
||||
createCurrentSyncTombstoneRepository,
|
||||
@@ -26,6 +30,7 @@ function isNonEmptyString(val: unknown): val is string {
|
||||
}
|
||||
|
||||
const authManager = AuthManager.getInstance();
|
||||
const permissionManager = PermissionManager.getInstance();
|
||||
const authenticateJWT = authManager.createAuthMiddleware();
|
||||
const requireDataAccess = authManager.createDataAccessMiddleware();
|
||||
|
||||
@@ -78,6 +83,7 @@ const requireDataAccess = authManager.createDataAccessMiddleware();
|
||||
router.post(
|
||||
"/",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.create"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -250,6 +256,7 @@ router.post(
|
||||
router.get(
|
||||
"/",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -262,8 +269,11 @@ router.get(
|
||||
try {
|
||||
const credentials =
|
||||
await createCurrentCredentialRepository().listDecryptedByUserId(userId);
|
||||
const own = credentials.map((cred) => formatCredentialOutput(cred));
|
||||
|
||||
res.json(credentials.map((cred) => formatCredentialOutput(cred)));
|
||||
// Credentials shared with this user, read from their own snapshots.
|
||||
const shared = await listSharedCredentialsForUser(userId);
|
||||
res.json([...own, ...shared]);
|
||||
} catch (err) {
|
||||
authLogger.error("Failed to fetch credentials", err);
|
||||
res.status(500).json({ error: "Failed to fetch credentials" });
|
||||
@@ -290,6 +300,7 @@ router.get(
|
||||
router.get(
|
||||
"/folders",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -311,7 +322,12 @@ router.get(
|
||||
// Registered here (before the PUT /:id route below) so the literal
|
||||
// "/reorder" path segment is matched before Express falls through to the
|
||||
// PUT /:id param route and treats "reorder" as an id.
|
||||
registerCredentialBulkRoutes(router, authenticateJWT);
|
||||
registerCredentialBulkRoutes(
|
||||
router,
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.edit"),
|
||||
requireDataAccess,
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
@@ -340,6 +356,7 @@ registerCredentialBulkRoutes(router, authenticateJWT);
|
||||
router.get(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -351,11 +368,14 @@ router.get(
|
||||
}
|
||||
|
||||
try {
|
||||
const credentialRepository = createCurrentCredentialRepository();
|
||||
const ownCredential = await credentialRepository.findDecryptedByIdForUser(
|
||||
userId,
|
||||
parseInt(id),
|
||||
);
|
||||
const credential =
|
||||
await createCurrentCredentialRepository().findDecryptedByIdForUser(
|
||||
userId,
|
||||
parseInt(id),
|
||||
);
|
||||
ownCredential ??
|
||||
(await findSharedCredentialForUser(parseInt(id), userId));
|
||||
|
||||
if (!credential) {
|
||||
return res.status(404).json({ error: "Credential not found" });
|
||||
@@ -432,6 +452,7 @@ router.get(
|
||||
router.post(
|
||||
"/:id/duplicate",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.create"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -585,6 +606,7 @@ router.post(
|
||||
router.put(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.edit"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -604,13 +626,21 @@ router.put(
|
||||
});
|
||||
|
||||
try {
|
||||
const existingCredential =
|
||||
await createCurrentCredentialRepository().findDecryptedByIdForUser(
|
||||
userId,
|
||||
credentialId,
|
||||
);
|
||||
// A recipient holding "manage" edits the owner's row on the owner's
|
||||
// behalf; the row stays encrypted under the owner's key and every
|
||||
// recipient's snapshot is rebuilt below.
|
||||
const editableOwnerId = await resolveEditableCredentialOwner(
|
||||
credentialId,
|
||||
userId,
|
||||
);
|
||||
const existingCredential = editableOwnerId
|
||||
? await createCurrentCredentialRepository().findDecryptedByIdForUser(
|
||||
editableOwnerId,
|
||||
credentialId,
|
||||
)
|
||||
: null;
|
||||
|
||||
if (!existingCredential) {
|
||||
if (!existingCredential || !editableOwnerId) {
|
||||
return res.status(404).json({ error: "Credential not found" });
|
||||
}
|
||||
|
||||
@@ -673,14 +703,14 @@ router.put(
|
||||
|
||||
const credentialRepository = createCurrentCredentialRepository();
|
||||
const updated = await credentialRepository.updateEncryptedForUser(
|
||||
userId,
|
||||
editableOwnerId,
|
||||
credentialId,
|
||||
updateFields,
|
||||
);
|
||||
const updatedCredential =
|
||||
updated ??
|
||||
(await credentialRepository.findDecryptedByIdForUser(
|
||||
userId,
|
||||
editableOwnerId,
|
||||
credentialId,
|
||||
));
|
||||
|
||||
@@ -688,7 +718,13 @@ router.put(
|
||||
await import("../../utils/shared-host-secrets-manager.js");
|
||||
await SharedHostSecretsManager.getInstance().resyncHostsForCredential(
|
||||
credentialId,
|
||||
userId,
|
||||
editableOwnerId,
|
||||
);
|
||||
const { SharedCredentialSecretsManager } =
|
||||
await import("../../utils/shared-credential-secrets-manager.js");
|
||||
await SharedCredentialSecretsManager.getInstance().resyncCredential(
|
||||
credentialId,
|
||||
editableOwnerId,
|
||||
);
|
||||
|
||||
authLogger.success("SSH credential updated", {
|
||||
@@ -747,6 +783,7 @@ router.put(
|
||||
router.delete(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.delete"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -878,6 +915,7 @@ router.delete(
|
||||
router.post(
|
||||
"/:id/apply-to-host/:hostId",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.edit"),
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const credentialId = Array.isArray(req.params.id)
|
||||
@@ -958,6 +996,7 @@ router.post(
|
||||
router.get(
|
||||
"/:id/hosts",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.view"),
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const credentialId = Array.isArray(req.params.id)
|
||||
@@ -986,6 +1025,78 @@ router.get(
|
||||
},
|
||||
);
|
||||
|
||||
/** The owner id if the caller may edit this credential (owner or "manage"), else null. */
|
||||
async function resolveEditableCredentialOwner(
|
||||
credentialId: number,
|
||||
userId: string,
|
||||
): Promise<string | null> {
|
||||
const row = await createCurrentCredentialRepository().findById(credentialId);
|
||||
if (!row) return null;
|
||||
if (row.userId === userId) return userId;
|
||||
const roleIds = await createCurrentRoleRepository().listUserRoleIds(userId);
|
||||
const grant = await createCurrentCredentialAccessRepository().findActiveGrant(
|
||||
credentialId,
|
||||
userId,
|
||||
roleIds,
|
||||
);
|
||||
return grant?.permissionLevel === "manage" ? row.userId : null;
|
||||
}
|
||||
|
||||
async function findSharedCredentialForUser(
|
||||
credentialId: number,
|
||||
userId: string,
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
const shared = (await listSharedCredentialsForUser(userId)).find(
|
||||
(cred) => cred.id === credentialId,
|
||||
);
|
||||
return shared ?? null;
|
||||
}
|
||||
|
||||
/** Shared credentials shaped like the caller's own, plus who shared them. */
|
||||
async function listSharedCredentialsForUser(
|
||||
userId: string,
|
||||
): Promise<Record<string, unknown>[]> {
|
||||
const roleIds = await createCurrentRoleRepository().listUserRoleIds(userId);
|
||||
const grants =
|
||||
await createCurrentCredentialAccessRepository().listSharedWithUser(
|
||||
userId,
|
||||
roleIds,
|
||||
);
|
||||
if (grants.length === 0) return [];
|
||||
const credentialRepository = createCurrentCredentialRepository();
|
||||
const userRepository = createCurrentUserRepository();
|
||||
const { findUsableCredential } =
|
||||
await import("../../hosts/usable-credential.js");
|
||||
const results: Record<string, unknown>[] = [];
|
||||
for (const grant of grants) {
|
||||
const row = await credentialRepository.findById(grant.credentialId);
|
||||
if (!row) continue;
|
||||
let secrets: Record<string, unknown> | null = null;
|
||||
try {
|
||||
secrets = (await findUsableCredential(
|
||||
grant.credentialId,
|
||||
userId,
|
||||
)) as Record<string, unknown> | null;
|
||||
} catch {
|
||||
secrets = null;
|
||||
}
|
||||
const owner = await userRepository.findById(grant.ownerId);
|
||||
results.push({
|
||||
...formatCredentialOutput({
|
||||
...row,
|
||||
username: secrets?.username ?? row.username,
|
||||
publicKey: secrets?.publicKey ?? null,
|
||||
certPublicKey: secrets?.certPublicKey ?? null,
|
||||
}),
|
||||
isShared: true,
|
||||
ownerUsername: owner?.username ?? null,
|
||||
permissionLevel: grant.permissionLevel,
|
||||
sharedExpiresAt: grant.expiresAt,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
function formatCredentialOutput(
|
||||
credential: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
@@ -1076,6 +1187,7 @@ function formatSSHHostOutput(
|
||||
router.put(
|
||||
"/folders/rename",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.edit"),
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { oldName, newName } = req.body;
|
||||
@@ -1107,8 +1219,19 @@ router.put(
|
||||
},
|
||||
);
|
||||
|
||||
registerCredentialKeyRoutes(router, authenticateJWT);
|
||||
registerCredentialKeyRoutes(
|
||||
router,
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.view"),
|
||||
requireDataAccess,
|
||||
);
|
||||
|
||||
registerCredentialDeployRoutes(router, authenticateJWT);
|
||||
registerCredentialDeployRoutes(
|
||||
router,
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.view"),
|
||||
permissionManager.requirePermission("hosts.edit"),
|
||||
requireDataAccess,
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -39,14 +39,34 @@ import {
|
||||
createCurrentUserRepository,
|
||||
createCurrentTransferRecentRepository,
|
||||
createCurrentVaultProfileRepository,
|
||||
createCurrentSecretSourceRepository,
|
||||
createCurrentSharedCredentialSecretsRepository,
|
||||
createCurrentCredentialAccessRepository,
|
||||
createCurrentVaultTokenRepository,
|
||||
} from "../repositories/factory.js";
|
||||
|
||||
export async function deleteUserAndRelatedData(userId: string): Promise<void> {
|
||||
export async function deleteUserAndRelatedData(
|
||||
userId: string,
|
||||
options: { successorUserId?: string } = {},
|
||||
): Promise<void> {
|
||||
try {
|
||||
// With a successor, hosts and credentials (and the shares on them)
|
||||
// change owner instead of disappearing with the account.
|
||||
if (options.successorUserId) {
|
||||
const { transferOwnership } =
|
||||
await import("../../utils/transfer-ownership.js");
|
||||
await transferOwnership(userId, options.successorUserId);
|
||||
}
|
||||
|
||||
await createCurrentSharedHostSecretsRepository().deleteByTargetUserId(
|
||||
userId,
|
||||
);
|
||||
await createCurrentSharedCredentialSecretsRepository().deleteByTargetUserId(
|
||||
userId,
|
||||
);
|
||||
await createCurrentCredentialAccessRepository().deleteForUserReferences(
|
||||
userId,
|
||||
);
|
||||
|
||||
// Retained rather than deleted: these outlive the account by design.
|
||||
// See anonymizeByUserId on each repository.
|
||||
@@ -98,6 +118,7 @@ export async function deleteUserAndRelatedData(userId: string): Promise<void> {
|
||||
await createCurrentOpksshTokenRepository().deleteByUserId(userId);
|
||||
await createCurrentVaultTokenRepository().deleteByUserId(userId);
|
||||
await createCurrentVaultProfileRepository().deleteByUserId(userId);
|
||||
await createCurrentSecretSourceRepository().deleteByUserId(userId);
|
||||
await createCurrentTermixIdentityCaRepository().deleteByUserId(userId);
|
||||
await createCurrentTermixIdentityRepository().deleteByUserId(userId);
|
||||
await createCurrentTmuxSessionTagRepository().deleteByUserId(userId);
|
||||
|
||||
@@ -33,6 +33,11 @@ export function extractBearerOrCookieToken(req: Request): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function isNativeTokenExportRequest(req: Request): boolean {
|
||||
const userAgent = req.get("user-agent") || "";
|
||||
return /^(Termix-Mobile|Termix-Desktop)\//.test(userAgent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides who the desktop auto-session endpoint should silently log in as.
|
||||
*
|
||||
|
||||
@@ -12,6 +12,7 @@ const faviconCache = new Map<
|
||||
>();
|
||||
const CACHE_SIZE = 100;
|
||||
const CACHE_TTL_MS = 1000 * 60 * 60 * 24; // 24 hours
|
||||
const MAX_FAVICON_BYTES = 512 * 1024;
|
||||
|
||||
function evictIfNeeded() {
|
||||
if (faviconCache.size >= CACHE_SIZE) {
|
||||
@@ -25,14 +26,31 @@ function fetchUrl(url: string): Promise<{ data: Buffer; contentType: string }> {
|
||||
const mod = url.startsWith("https") ? https : http;
|
||||
const req = mod.get(url, { timeout: 5000 }, (res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||
let bytes = 0;
|
||||
let settled = false;
|
||||
const fail = (error: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
res.destroy();
|
||||
reject(error);
|
||||
};
|
||||
res.on("data", (chunk: Buffer) => {
|
||||
bytes += chunk.length;
|
||||
if (bytes > MAX_FAVICON_BYTES) {
|
||||
fail(new Error("Favicon response too large"));
|
||||
return;
|
||||
}
|
||||
chunks.push(chunk);
|
||||
});
|
||||
res.on("end", () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve({
|
||||
data: Buffer.concat(chunks),
|
||||
contentType: res.headers["content-type"] || "image/x-icon",
|
||||
});
|
||||
});
|
||||
res.on("error", reject);
|
||||
res.on("error", fail);
|
||||
});
|
||||
req.on("error", reject);
|
||||
req.on("timeout", () => {
|
||||
@@ -95,7 +113,7 @@ homepageFaviconRouter.get("/", async (req: Request, res: Response) => {
|
||||
res.setHeader("Content-Type", contentType);
|
||||
res.setHeader("Cache-Control", "public, max-age=86400");
|
||||
res.send(data);
|
||||
} catch (err) {
|
||||
} catch {
|
||||
homepageLogger.warn("Failed to fetch favicon", { domain });
|
||||
res.status(500).json({ error: "Failed to fetch favicon" });
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import express, { type Request, type Response } from "express";
|
||||
import https from "https";
|
||||
import http from "http";
|
||||
import { lookup } from "dns/promises";
|
||||
import { isIP } from "net";
|
||||
import { homepageLogger } from "../../utils/logger.js";
|
||||
import { isBlockedAddress } from "../../utils/safe-outbound-fetch.js";
|
||||
import {
|
||||
readResponseTextLimited,
|
||||
safeOutboundFetch,
|
||||
} from "../../utils/safe-outbound-fetch.js";
|
||||
|
||||
export const homepageProxyRouter = express.Router();
|
||||
|
||||
@@ -17,68 +16,20 @@ interface ProxyCacheEntry {
|
||||
const proxyCache = new Map<string, ProxyCacheEntry>();
|
||||
const CACHE_SIZE = 50;
|
||||
const FETCH_TIMEOUT_MS = 8000;
|
||||
|
||||
async function resolvePublicUrl(rawUrl: string): Promise<{
|
||||
url: URL;
|
||||
address: string;
|
||||
}> {
|
||||
const url = new URL(rawUrl);
|
||||
if (
|
||||
!["http:", "https:"].includes(url.protocol) ||
|
||||
url.username ||
|
||||
url.password
|
||||
) {
|
||||
throw new Error("Invalid URL");
|
||||
}
|
||||
|
||||
const hostname = url.hostname.replace(/^\[|\]$/g, "");
|
||||
const addresses = isIP(hostname)
|
||||
? [{ address: hostname }]
|
||||
: await lookup(hostname, { all: true, verbatim: true });
|
||||
if (
|
||||
addresses.length === 0 ||
|
||||
addresses.some(({ address }) => isBlockedAddress(address))
|
||||
) {
|
||||
throw new Error("Private destinations are not allowed");
|
||||
}
|
||||
|
||||
return { url, address: addresses[0].address };
|
||||
}
|
||||
const MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
|
||||
const MAX_CACHE_TTL_SECONDS = 24 * 60 * 60;
|
||||
|
||||
async function fetchJson(rawUrl: string): Promise<unknown> {
|
||||
const { url, address } = await resolvePublicUrl(rawUrl);
|
||||
return new Promise((resolve, reject) => {
|
||||
const mod = url.protocol === "https:" ? https : http;
|
||||
const req = mod.get(
|
||||
{
|
||||
protocol: url.protocol,
|
||||
hostname: address,
|
||||
port: url.port || undefined,
|
||||
path: `${url.pathname}${url.search}`,
|
||||
headers: { Host: url.host },
|
||||
servername: url.protocol === "https:" ? url.hostname : undefined,
|
||||
timeout: FETCH_TIMEOUT_MS,
|
||||
},
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||
res.on("end", () => {
|
||||
try {
|
||||
const text = Buffer.concat(chunks).toString("utf-8");
|
||||
resolve(JSON.parse(text));
|
||||
} catch {
|
||||
reject(new Error("Response is not valid JSON"));
|
||||
}
|
||||
});
|
||||
res.on("error", reject);
|
||||
},
|
||||
);
|
||||
req.on("error", reject);
|
||||
req.on("timeout", () => {
|
||||
req.destroy();
|
||||
reject(new Error("Fetch timeout"));
|
||||
});
|
||||
const response = await safeOutboundFetch(rawUrl, {
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) throw new Error(`Proxy fetch failed: ${response.status}`);
|
||||
const text = await readResponseTextLimited(response, MAX_RESPONSE_BYTES);
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
throw new Error("Response is not valid JSON");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,7 +60,9 @@ async function fetchJson(rawUrl: string): Promise<unknown> {
|
||||
*/
|
||||
homepageProxyRouter.get("/", async (req: Request, res: Response) => {
|
||||
const targetUrl = req.query.url as string;
|
||||
const ttl = Math.max(10, Number(req.query.ttl) || 60) * 1000;
|
||||
const ttl =
|
||||
Math.min(MAX_CACHE_TTL_SECONDS, Math.max(10, Number(req.query.ttl) || 60)) *
|
||||
1000;
|
||||
|
||||
if (!targetUrl) return res.status(400).json({ error: "url is required" });
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import express, { type Request, type Response } from "express";
|
||||
import { homepageLogger } from "../../utils/logger.js";
|
||||
import { safeOutboundFetch } from "../../utils/safe-outbound-fetch.js";
|
||||
import {
|
||||
readResponseTextLimited,
|
||||
safeOutboundFetch,
|
||||
} from "../../utils/safe-outbound-fetch.js";
|
||||
|
||||
export const homepageRssRouter = express.Router();
|
||||
|
||||
@@ -8,6 +11,7 @@ const rssCache = new Map<string, { data: RssItem[]; expires: number }>();
|
||||
const CACHE_TTL_MS = 1000 * 60 * 15; // 15 minutes
|
||||
const CACHE_SIZE = 50;
|
||||
const FETCH_TIMEOUT_MS = 8000;
|
||||
const MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
interface RssItem {
|
||||
title: string;
|
||||
@@ -21,7 +25,7 @@ function fetchXml(url: string): Promise<string> {
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
}).then(async (res) => {
|
||||
if (!res.ok) throw new Error(`RSS fetch failed: ${res.status}`);
|
||||
return res.text();
|
||||
return readResponseTextLimited(res, MAX_RESPONSE_BYTES);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -131,7 +135,7 @@ homepageRssRouter.get("/", async (req: Request, res: Response) => {
|
||||
rssCache.set(feedUrl, { data: items, expires: Date.now() + CACHE_TTL_MS });
|
||||
|
||||
res.json(items.slice(0, max));
|
||||
} catch (err) {
|
||||
} catch {
|
||||
homepageLogger.warn("Failed to fetch RSS feed", { feedUrl });
|
||||
res.status(500).json({ error: "Failed to fetch feed" });
|
||||
}
|
||||
|
||||
@@ -7,12 +7,19 @@ import { createCurrentHostRepository } from "../repositories/factory.js";
|
||||
|
||||
type HostAutostartRoutesDeps = {
|
||||
authenticateJWT: RequestHandler;
|
||||
requireViewPermission: RequestHandler;
|
||||
requireEditPermission: RequestHandler;
|
||||
requireDataAccess: RequestHandler;
|
||||
};
|
||||
|
||||
export function registerHostAutostartRoutes(
|
||||
router: Router,
|
||||
{ authenticateJWT, requireDataAccess }: HostAutostartRoutesDeps,
|
||||
{
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
}: HostAutostartRoutesDeps,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
@@ -44,6 +51,7 @@ export function registerHostAutostartRoutes(
|
||||
router.post(
|
||||
"/autostart/enable",
|
||||
authenticateJWT,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -204,6 +212,8 @@ export function registerHostAutostartRoutes(
|
||||
router.delete(
|
||||
"/autostart/disable",
|
||||
authenticateJWT,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { sshConfigId } = req.body;
|
||||
@@ -259,6 +269,8 @@ export function registerHostAutostartRoutes(
|
||||
router.get(
|
||||
"/autostart/status",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
prepareHostImports,
|
||||
remapImportedJumpHosts,
|
||||
} from "./host-import-order.js";
|
||||
import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import type { Request, RequestHandler, Response, Router } from "express";
|
||||
@@ -8,6 +12,7 @@ import {
|
||||
createCurrentHostResolutionRepository,
|
||||
} from "../repositories/factory.js";
|
||||
import { validateParentHostId } from "./host-parent-validation.js";
|
||||
import { serializeWebUiConfig } from "./host-web-endpoints.js";
|
||||
import {
|
||||
isNonEmptyString,
|
||||
isValidPort,
|
||||
@@ -105,9 +110,22 @@ export function parseSSHConfig(content: string): SSHConfigHost[] {
|
||||
return results;
|
||||
}
|
||||
|
||||
export function importedHostUsername(
|
||||
connectionType: string,
|
||||
authType: unknown,
|
||||
username: unknown,
|
||||
): string | null {
|
||||
if (isNonEmptyString(username)) return username;
|
||||
if (connectionType !== "ssh" || authType === "credential") return "";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function registerHostBulkRoutes(
|
||||
router: Router,
|
||||
authenticateJWT: RequestHandler,
|
||||
requireCreatePermission: RequestHandler,
|
||||
requireEditPermission: RequestHandler,
|
||||
requireDataAccess: RequestHandler,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
@@ -172,6 +190,8 @@ export function registerHostBulkRoutes(
|
||||
router.patch(
|
||||
"/bulk-update",
|
||||
authenticateJWT,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { hostIds, updates } = req.body;
|
||||
@@ -265,10 +285,16 @@ export function registerHostBulkRoutes(
|
||||
simpleUpdates.enableFileManager = updates.enableFileManager;
|
||||
if (typeof updates.enableDocker === "boolean")
|
||||
simpleUpdates.enableDocker = updates.enableDocker;
|
||||
if (typeof updates.enableWebUi === "boolean") {
|
||||
simpleUpdates.enableWebUi = updates.enableWebUi;
|
||||
if (!updates.enableWebUi) simpleUpdates.webUiConfig = null;
|
||||
}
|
||||
if (typeof updates.enableTmuxMonitor === "boolean")
|
||||
simpleUpdates.enableTmuxMonitor = updates.enableTmuxMonitor;
|
||||
if (typeof updates.enableTerminalToolbar === "boolean")
|
||||
simpleUpdates.enableTerminalToolbar = updates.enableTerminalToolbar;
|
||||
if (typeof updates.enableAiAssistant === "boolean")
|
||||
simpleUpdates.enableAiAssistant = updates.enableAiAssistant;
|
||||
// Disabling Proxmox is a plain flag flip; enabling is handled per-host
|
||||
// below so each host can default to its own stored credential.
|
||||
if (updates.enableProxmox === false)
|
||||
@@ -376,6 +402,8 @@ export function registerHostBulkRoutes(
|
||||
router.put(
|
||||
"/reorder",
|
||||
authenticateJWT,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { positions } = req.body as {
|
||||
@@ -422,6 +450,9 @@ export function registerHostBulkRoutes(
|
||||
router.post(
|
||||
"/bulk-import",
|
||||
authenticateJWT,
|
||||
requireCreatePermission,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const {
|
||||
@@ -442,6 +473,14 @@ export function registerHostBulkRoutes(
|
||||
.json({ error: "Maximum 100 hosts allowed per import" });
|
||||
}
|
||||
|
||||
let orderedHosts: ReturnType<typeof prepareHostImports>;
|
||||
try {
|
||||
orderedHosts = prepareHostImports(hostsToImport);
|
||||
} catch (error) {
|
||||
return res.status(400).json({ error: getErrorMessage(error) });
|
||||
}
|
||||
const importedIds = new Map<unknown, number>();
|
||||
|
||||
const results = {
|
||||
success: 0,
|
||||
updated: 0,
|
||||
@@ -533,9 +572,7 @@ export function registerHostBulkRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < hostsToImport.length; i++) {
|
||||
const hostData = normalizeImportedHost(hostsToImport[i]);
|
||||
|
||||
for (const { host: hostData, index: i, exportId } of orderedHosts) {
|
||||
try {
|
||||
const effectiveConnectionType = hostData.connectionType || "ssh";
|
||||
|
||||
@@ -558,10 +595,12 @@ export function registerHostBulkRoutes(
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
effectiveConnectionType === "ssh" &&
|
||||
!isNonEmptyString(hostData.username)
|
||||
) {
|
||||
const username = importedHostUsername(
|
||||
effectiveConnectionType,
|
||||
hostData.authType,
|
||||
hostData.username,
|
||||
);
|
||||
if (username === null) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host ${i + 1}: Username required for SSH connections`,
|
||||
@@ -578,13 +617,14 @@ export function registerHostBulkRoutes(
|
||||
"credential",
|
||||
"none",
|
||||
"opkssh",
|
||||
"stepca",
|
||||
"tailscale",
|
||||
"vault",
|
||||
].includes(hostData.authType)
|
||||
) {
|
||||
results.failed++;
|
||||
results.errors.push(
|
||||
`Host ${i + 1}: Invalid authType. Must be 'password', 'key', 'credential', 'none', 'opkssh', 'tailscale', or 'vault'`,
|
||||
`Host ${i + 1}: Invalid authType. Must be 'password', 'key', 'credential', 'none', 'opkssh', 'stepca', 'tailscale', or 'vault'`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
@@ -657,23 +697,30 @@ export function registerHostBulkRoutes(
|
||||
}
|
||||
}
|
||||
|
||||
const jumpHosts = remapImportedJumpHosts(
|
||||
hostData.jumpHosts,
|
||||
importedIds,
|
||||
);
|
||||
const sshDataObj: Record<string, unknown> = {
|
||||
userId: userId,
|
||||
connectionType: effectiveConnectionType,
|
||||
name: hostData.name || `${hostData.username || ""}@${hostData.ip}`,
|
||||
name: hostData.name || `${username}@${hostData.ip}`,
|
||||
folder: hostData.folder || "Default",
|
||||
tags: Array.isArray(hostData.tags) ? hostData.tags.join(",") : "",
|
||||
ip: hostData.ip,
|
||||
port: hostData.port,
|
||||
username: hostData.username || null,
|
||||
username,
|
||||
pin: hostData.pin || false,
|
||||
enableTerminal: hostData.enableTerminal !== false,
|
||||
enableTunnel: hostData.enableTunnel !== false,
|
||||
enableFileManager: hostData.enableFileManager !== false,
|
||||
enableDocker: hostData.enableDocker || false,
|
||||
enableWebUi: hostData.enableWebUi || false,
|
||||
enableProxmox: hostData.enableProxmox || false,
|
||||
enableTmuxMonitor: hostData.enableTmuxMonitor || false,
|
||||
enableTerminalToolbar: hostData.enableTerminalToolbar !== false,
|
||||
enableAiAssistant: hostData.enableAiAssistant || false,
|
||||
enableCommandHistory: hostData.enableCommandHistory !== false,
|
||||
showTerminalInSidebar: hostData.showTerminalInSidebar ? 1 : 0,
|
||||
showFileManagerInSidebar: hostData.showFileManagerInSidebar ? 1 : 0,
|
||||
showTunnelInSidebar: hostData.showTunnelInSidebar ? 1 : 0,
|
||||
@@ -684,9 +731,7 @@ export function registerHostBulkRoutes(
|
||||
tunnelConnections: hostData.tunnelConnections
|
||||
? JSON.stringify(hostData.tunnelConnections)
|
||||
: "[]",
|
||||
jumpHosts: hostData.jumpHosts
|
||||
? JSON.stringify(hostData.jumpHosts)
|
||||
: null,
|
||||
jumpHosts: jumpHosts ? JSON.stringify(jumpHosts) : null,
|
||||
quickActions: hostData.quickActions
|
||||
? JSON.stringify(hostData.quickActions)
|
||||
: null,
|
||||
@@ -696,6 +741,9 @@ export function registerHostBulkRoutes(
|
||||
dockerConfig: hostData.dockerConfig
|
||||
? JSON.stringify(hostData.dockerConfig)
|
||||
: null,
|
||||
webUiConfig: hostData.enableWebUi
|
||||
? serializeWebUiConfig(hostData.webUiConfig)
|
||||
: null,
|
||||
proxmoxConfig: hostData.proxmoxConfig
|
||||
? JSON.stringify(hostData.proxmoxConfig)
|
||||
: null,
|
||||
@@ -773,15 +821,21 @@ export function registerHostBulkRoutes(
|
||||
const existing = existingHostMap?.get(lookupKey);
|
||||
|
||||
if (existing) {
|
||||
await hostRepository.updateEncryptedForUser(
|
||||
const saved = await hostRepository.updateEncryptedForUser(
|
||||
userId,
|
||||
existing.id,
|
||||
sshDataObj,
|
||||
);
|
||||
if (!saved) throw new Error("Host no longer exists");
|
||||
if (exportId !== undefined) importedIds.set(exportId, existing.id);
|
||||
results.updated++;
|
||||
} else {
|
||||
sshDataObj.createdAt = new Date().toISOString();
|
||||
await hostRepository.createEncryptedForUser(userId, sshDataObj);
|
||||
const saved = await hostRepository.createEncryptedForUser(
|
||||
userId,
|
||||
sshDataObj,
|
||||
);
|
||||
if (exportId !== undefined) importedIds.set(exportId, saved.id);
|
||||
results.success++;
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -832,6 +886,9 @@ export function registerHostBulkRoutes(
|
||||
router.post(
|
||||
"/ssh-config-import",
|
||||
authenticateJWT,
|
||||
requireCreatePermission,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { content, overwrite } = req.body;
|
||||
@@ -938,9 +995,11 @@ export function registerHostBulkRoutes(
|
||||
enableTunnel: true,
|
||||
enableFileManager: true,
|
||||
enableDocker: false,
|
||||
enableWebUi: false,
|
||||
enableProxmox: false,
|
||||
enableTmuxMonitor: false,
|
||||
enableTerminalToolbar: true,
|
||||
enableAiAssistant: false,
|
||||
showTerminalInSidebar: 0,
|
||||
showFileManagerInSidebar: 0,
|
||||
showTunnelInSidebar: 0,
|
||||
@@ -955,6 +1014,7 @@ export function registerHostBulkRoutes(
|
||||
quickActions: null,
|
||||
statsConfig: null,
|
||||
dockerConfig: null,
|
||||
webUiConfig: null,
|
||||
proxmoxConfig: null,
|
||||
terminalConfig: null,
|
||||
forceKeyboardInteractive: "false",
|
||||
|
||||
@@ -7,6 +7,8 @@ import { isNonEmptyString } from "./host-normalizers.js";
|
||||
export function registerHostCommandHistoryRoutes(
|
||||
router: Router,
|
||||
authenticateJWT: RequestHandler,
|
||||
requireViewPermission: RequestHandler,
|
||||
requireDataAccess: RequestHandler,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
@@ -33,6 +35,8 @@ export function registerHostCommandHistoryRoutes(
|
||||
router.get(
|
||||
"/command-history/:hostId",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const hostIdParam = Array.isArray(req.params.hostId)
|
||||
@@ -98,6 +102,8 @@ export function registerHostCommandHistoryRoutes(
|
||||
router.delete(
|
||||
"/command-history",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { hostId, command } = req.body;
|
||||
|
||||
@@ -7,6 +7,8 @@ import { isNonEmptyString } from "./host-normalizers.js";
|
||||
export function registerHostFileManagerBookmarkRoutes(
|
||||
router: Router,
|
||||
authenticateJWT: RequestHandler,
|
||||
requireViewPermission: RequestHandler,
|
||||
requireDataAccess: RequestHandler,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
@@ -33,6 +35,8 @@ export function registerHostFileManagerBookmarkRoutes(
|
||||
router.get(
|
||||
"/file_manager/recent",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const hostIdQuery = Array.isArray(req.query.hostId)
|
||||
@@ -98,6 +102,8 @@ export function registerHostFileManagerBookmarkRoutes(
|
||||
router.post(
|
||||
"/file_manager/recent",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { hostId, path, name } = req.body;
|
||||
@@ -155,6 +161,8 @@ export function registerHostFileManagerBookmarkRoutes(
|
||||
router.delete(
|
||||
"/file_manager/recent",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { hostId, path } = req.body;
|
||||
@@ -203,6 +211,8 @@ export function registerHostFileManagerBookmarkRoutes(
|
||||
router.get(
|
||||
"/file_manager/pinned",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const hostIdQuery = Array.isArray(req.query.hostId)
|
||||
@@ -269,6 +279,8 @@ export function registerHostFileManagerBookmarkRoutes(
|
||||
router.post(
|
||||
"/file_manager/pinned",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { hostId, path, name } = req.body;
|
||||
@@ -327,6 +339,8 @@ export function registerHostFileManagerBookmarkRoutes(
|
||||
router.delete(
|
||||
"/file_manager/pinned",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { hostId, path } = req.body;
|
||||
@@ -375,6 +389,8 @@ export function registerHostFileManagerBookmarkRoutes(
|
||||
router.get(
|
||||
"/file_manager/shortcuts",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const hostIdQuery = Array.isArray(req.query.hostId)
|
||||
@@ -441,6 +457,8 @@ export function registerHostFileManagerBookmarkRoutes(
|
||||
router.post(
|
||||
"/file_manager/shortcuts",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { hostId, path, name } = req.body;
|
||||
@@ -499,6 +517,8 @@ export function registerHostFileManagerBookmarkRoutes(
|
||||
router.delete(
|
||||
"/file_manager/shortcuts",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { hostId, path } = req.body;
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
createCurrentCredentialRepository,
|
||||
createCurrentFileManagerBookmarkRepository,
|
||||
createCurrentHostFolderRepository,
|
||||
createCurrentFolderAccessRepository,
|
||||
createCurrentRecentActivityRepository,
|
||||
createCurrentRbacAccessRepository,
|
||||
createCurrentSshCredentialUsageRepository,
|
||||
@@ -17,12 +18,25 @@ import { isNonEmptyString } from "./host-normalizers.js";
|
||||
|
||||
type HostFolderRoutesDeps = {
|
||||
authenticateJWT: RequestHandler;
|
||||
requireViewPermission: RequestHandler;
|
||||
requireEditPermission: RequestHandler;
|
||||
requireDeletePermission: RequestHandler;
|
||||
requireCredentialEditPermission: RequestHandler;
|
||||
requireDataAccess: RequestHandler;
|
||||
statsServerUrl: string;
|
||||
};
|
||||
|
||||
export function registerHostFolderRoutes(
|
||||
router: Router,
|
||||
{ authenticateJWT, statsServerUrl }: HostFolderRoutesDeps,
|
||||
{
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireEditPermission,
|
||||
requireDeletePermission,
|
||||
requireCredentialEditPermission,
|
||||
requireDataAccess,
|
||||
statsServerUrl,
|
||||
}: HostFolderRoutesDeps,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
@@ -54,6 +68,9 @@ export function registerHostFolderRoutes(
|
||||
router.put(
|
||||
"/folders/rename",
|
||||
authenticateJWT,
|
||||
requireEditPermission,
|
||||
requireCredentialEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { oldName, newName } = req.body;
|
||||
@@ -76,6 +93,11 @@ export function registerHostFolderRoutes(
|
||||
oldName,
|
||||
newName,
|
||||
);
|
||||
await createCurrentFolderAccessRepository().renameFolder(
|
||||
userId,
|
||||
oldName,
|
||||
newName,
|
||||
);
|
||||
|
||||
res.json({
|
||||
message: "Folder renamed successfully",
|
||||
@@ -113,6 +135,8 @@ export function registerHostFolderRoutes(
|
||||
router.get(
|
||||
"/folders",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
@@ -170,6 +194,8 @@ export function registerHostFolderRoutes(
|
||||
router.put(
|
||||
"/folders/metadata",
|
||||
authenticateJWT,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { name, color, icon, credentialId } = req.body;
|
||||
@@ -275,6 +301,8 @@ export function registerHostFolderRoutes(
|
||||
router.put(
|
||||
"/folders/reorder",
|
||||
authenticateJWT,
|
||||
requireEditPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { positions } = req.body as {
|
||||
@@ -346,6 +374,8 @@ export function registerHostFolderRoutes(
|
||||
router.delete(
|
||||
"/folders/:name/hosts",
|
||||
authenticateJWT,
|
||||
requireDeletePermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const folderName = Array.isArray(req.params.name)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { normalizeImportedHost } from "./host-normalizers.js";
|
||||
|
||||
export function prepareHostImports(input: Record<string, unknown>[]) {
|
||||
const hosts = input.map((value, index) => ({
|
||||
host: normalizeImportedHost(value),
|
||||
index,
|
||||
exportId: value.exportId ?? value.id,
|
||||
}));
|
||||
const byId = new Map<unknown, (typeof hosts)[number]>();
|
||||
for (const entry of hosts) {
|
||||
if (entry.exportId === undefined) continue;
|
||||
if (!Number.isSafeInteger(entry.exportId) || Number(entry.exportId) <= 0)
|
||||
throw new Error(`Host ${entry.index + 1}: invalid exportId`);
|
||||
if (byId.has(entry.exportId))
|
||||
throw new Error(`Duplicate exported host ID: ${entry.exportId}`);
|
||||
byId.set(entry.exportId, entry);
|
||||
}
|
||||
const ordered: typeof hosts = [];
|
||||
const visiting = new Set<number>();
|
||||
const visited = new Set<number>();
|
||||
const visit = (entry: (typeof hosts)[number]) => {
|
||||
if (visited.has(entry.index)) return;
|
||||
if (visiting.has(entry.index))
|
||||
throw new Error("Jump-host dependency cycle in import");
|
||||
visiting.add(entry.index);
|
||||
const jumps = entry.host.jumpHosts ?? [];
|
||||
if (!Array.isArray(jumps))
|
||||
throw new Error(`Host ${entry.index + 1}: jumpHosts must be an array`);
|
||||
for (const jump of jumps) {
|
||||
const dependency = byId.get(jump?.hostId);
|
||||
if (!dependency)
|
||||
throw new Error(
|
||||
`Host ${entry.index + 1}: jump host ${jump?.hostId} is missing from the export. Re-export and include all jump hosts.`,
|
||||
);
|
||||
visit(dependency);
|
||||
}
|
||||
visiting.delete(entry.index);
|
||||
visited.add(entry.index);
|
||||
ordered.push(entry);
|
||||
};
|
||||
hosts.forEach(visit);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
export function remapImportedJumpHosts(
|
||||
jumps: unknown,
|
||||
importedIds: Map<unknown, number>,
|
||||
) {
|
||||
if (!Array.isArray(jumps)) return null;
|
||||
return jumps.map((jump) => {
|
||||
const hostId = importedIds.get(jump.hostId);
|
||||
if (hostId === undefined)
|
||||
throw new Error(`Jump host ${jump.hostId} failed to import`);
|
||||
return { hostId };
|
||||
});
|
||||
}
|
||||
@@ -7,12 +7,17 @@ import { createCurrentHostResolutionRepository } from "../repositories/factory.j
|
||||
|
||||
interface HostNetworkRoutesDeps {
|
||||
authenticateJWT: RequestHandler;
|
||||
requireViewPermission: RequestHandler;
|
||||
requireDataAccess: RequestHandler;
|
||||
}
|
||||
|
||||
export function registerHostNetworkRoutes(
|
||||
router: Router,
|
||||
{ authenticateJWT, requireDataAccess }: HostNetworkRoutesDeps,
|
||||
{
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
}: HostNetworkRoutesDeps,
|
||||
): void {
|
||||
/**
|
||||
* @openapi
|
||||
@@ -62,6 +67,7 @@ export function registerHostNetworkRoutes(
|
||||
router.post(
|
||||
"/db/proxy/test",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
try {
|
||||
@@ -93,6 +99,7 @@ export function registerHostNetworkRoutes(
|
||||
router.post(
|
||||
"/db/host/:id/wake",
|
||||
authenticateJWT,
|
||||
requireViewPermission,
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const hostId = Number.parseInt(String(req.params.id), 10);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AuthOverrideProtocol } from "../../../types/auth-protocols.js";
|
||||
import { parseWebUiConfig } from "./host-web-endpoints.js";
|
||||
|
||||
export function isNonEmptyString(value: unknown): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0;
|
||||
@@ -14,6 +15,34 @@ export function isOptionalBoolean(
|
||||
return value === undefined || typeof value === "boolean";
|
||||
}
|
||||
|
||||
export function applyHostKeyTypeUpdate(
|
||||
target: Record<string, unknown>,
|
||||
keyType: unknown,
|
||||
): void {
|
||||
if (keyType !== undefined) {
|
||||
target.keyType = keyType || null;
|
||||
}
|
||||
}
|
||||
|
||||
const PROTOCOL_ENABLE_FIELDS = [
|
||||
"enableSsh",
|
||||
"enableRdp",
|
||||
"enableVnc",
|
||||
"enableTelnet",
|
||||
] as const;
|
||||
|
||||
export function normalizeProtocolEnableFields(
|
||||
values: Record<string, unknown>,
|
||||
): Partial<Record<(typeof PROTOCOL_ENABLE_FIELDS)[number], 0 | 1>> {
|
||||
return Object.fromEntries(
|
||||
PROTOCOL_ENABLE_FIELDS.flatMap((field) =>
|
||||
typeof values[field] === "boolean"
|
||||
? [[field, values[field] ? 1 : 0]]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const OWNER_PRIVATE_AUTH_FIELDS = {
|
||||
ssh: [
|
||||
"authType",
|
||||
@@ -152,9 +181,12 @@ export type NormalizedImportedHost = Record<string, unknown> & {
|
||||
enableTunnel?: unknown;
|
||||
enableFileManager?: unknown;
|
||||
enableDocker?: unknown;
|
||||
enableWebUi?: unknown;
|
||||
enableProxmox?: unknown;
|
||||
enableTmuxMonitor?: unknown;
|
||||
enableTerminalToolbar?: unknown;
|
||||
enableAiAssistant?: unknown;
|
||||
enableCommandHistory?: unknown;
|
||||
showTerminalInSidebar?: unknown;
|
||||
showFileManagerInSidebar?: unknown;
|
||||
showTunnelInSidebar?: unknown;
|
||||
@@ -167,6 +199,7 @@ export type NormalizedImportedHost = Record<string, unknown> & {
|
||||
quickActions?: unknown;
|
||||
statsConfig?: unknown;
|
||||
dockerConfig?: unknown;
|
||||
webUiConfig?: unknown;
|
||||
proxmoxConfig?: unknown;
|
||||
enableProxmoxStats?: unknown;
|
||||
proxmoxStatsConfig?: unknown;
|
||||
@@ -331,10 +364,13 @@ const CONNECT_LEVEL_FIELDS = new Set([
|
||||
"enableTunnel",
|
||||
"enableFileManager",
|
||||
"enableDocker",
|
||||
"enableWebUi",
|
||||
"webUiConfig",
|
||||
"enableProxmox",
|
||||
"enableProxmoxStats",
|
||||
"enableTmuxMonitor",
|
||||
"enableTerminalToolbar",
|
||||
"enableAiAssistant",
|
||||
"showTerminalInSidebar",
|
||||
"showFileManagerInSidebar",
|
||||
"showTunnelInSidebar",
|
||||
@@ -346,6 +382,7 @@ const CONNECT_LEVEL_FIELDS = new Set([
|
||||
"enableTelnet",
|
||||
"sshPort",
|
||||
"rdpPort",
|
||||
"rdpAuthType",
|
||||
"vncPort",
|
||||
"telnetPort",
|
||||
"defaultPath",
|
||||
@@ -432,10 +469,12 @@ export function transformHostResponse(
|
||||
enableTunnel: !!host.enableTunnel,
|
||||
enableFileManager: host.enableFileManager !== false,
|
||||
enableDocker: !!host.enableDocker,
|
||||
enableWebUi: !!host.enableWebUi,
|
||||
enableProxmox: !!host.enableProxmox,
|
||||
enableProxmoxStats: !!host.enableProxmoxStats,
|
||||
enableTmuxMonitor: !!host.enableTmuxMonitor,
|
||||
enableTerminalToolbar: host.enableTerminalToolbar !== false,
|
||||
enableAiAssistant: !!host.enableAiAssistant,
|
||||
showTerminalInSidebar: !!host.showTerminalInSidebar,
|
||||
showFileManagerInSidebar: !!host.showFileManagerInSidebar,
|
||||
showTunnelInSidebar: !!host.showTunnelInSidebar,
|
||||
@@ -484,6 +523,9 @@ export function transformHostResponse(
|
||||
dockerConfig: host.dockerConfig
|
||||
? JSON.parse(host.dockerConfig as string)
|
||||
: undefined,
|
||||
// Guarded, unlike dockerConfig directly above: parseWebUiConfig never
|
||||
// throws, so a half-written config cannot take out the whole host listing.
|
||||
webUiConfig: parseWebUiConfig(host.webUiConfig),
|
||||
proxmoxConfig: host.proxmoxConfig
|
||||
? JSON.parse(host.proxmoxConfig as string)
|
||||
: undefined,
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Request, Response, Router } from "express";
|
||||
import { escapeHtml } from "./opkssh-html.js";
|
||||
|
||||
function resultPage(ok: boolean, message: string): string {
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><title>Termix</title>
|
||||
<style>body{font-family:system-ui,sans-serif;background:#111;color:#eee;display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
|
||||
main{max-width:28rem;padding:2rem;border:1px solid #333;background:#181818}h1{font-size:1.1rem;margin:0 0 .5rem}p{margin:0;color:#aaa}</style></head>
|
||||
<body><main><h1>${ok ? "Signed in" : "Sign-in failed"}</h1><p>${escapeHtml(message)}</p></main></body></html>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The OIDC redirect target for Step CA sign-ins. Unauthenticated on purpose:
|
||||
* the browser that finishes the sign-in may not be the one running Termix,
|
||||
* so the request is matched to its session by the OAuth state.
|
||||
*/
|
||||
export function registerHostStepCaRoutes(router: Router): void {
|
||||
router.get("/step-ca-callback", async (req: Request, res: Response) => {
|
||||
const { completeStepCaAuth } = await import("../../hosts/step-ca-auth.js");
|
||||
const stringQuery = (name: string): string | undefined => {
|
||||
const value = req.query[name];
|
||||
return typeof value === "string" ? value : undefined;
|
||||
};
|
||||
const result = await completeStepCaAuth({
|
||||
state: stringQuery("state"),
|
||||
code: stringQuery("code"),
|
||||
error: stringQuery("error"),
|
||||
error_description: stringQuery("error_description"),
|
||||
});
|
||||
res
|
||||
.status(result.ok ? 200 : 400)
|
||||
.type("html")
|
||||
.send(resultPage(result.ok, result.message));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import {
|
||||
MAX_WEB_ENDPOINTS,
|
||||
MAX_WEB_ENDPOINT_LABEL_LENGTH,
|
||||
} from "../../../types/index.js";
|
||||
import type { WebEndpoint, WebUiConfig } from "../../../types/index.js";
|
||||
|
||||
export { MAX_WEB_ENDPOINTS, MAX_WEB_ENDPOINT_LABEL_LENGTH };
|
||||
|
||||
const SCHEMES = new Set(["http", "https"]);
|
||||
const ACCESS_VALUES = new Set(["direct", "tunnel"]);
|
||||
const RENDER_VALUES = new Set(["external", "embedded"]);
|
||||
|
||||
const MIN_PORT = 1;
|
||||
const MAX_PORT = 65535;
|
||||
|
||||
function isValidPort(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === "number" &&
|
||||
Number.isInteger(value) &&
|
||||
value >= MIN_PORT &&
|
||||
value <= MAX_PORT
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* C0 controls and DEL. Checked by codepoint rather than by regex character
|
||||
* class so no escaping subtlety can let one through: a path like
|
||||
* "\t//evil.example" defeats a naive startsWith("//") guard, because the
|
||||
* browser strips the control character and then follows the authority.
|
||||
*/
|
||||
function hasControlCharacter(value: string): boolean {
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
const code = value.charCodeAt(index);
|
||||
if (code <= 0x1f || code === 0x7f) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerces a path to begin with "/", or returns null to drop the endpoint.
|
||||
*
|
||||
* This is THE enforcement point for a value that reaches an href and an
|
||||
* iframe src -- the editor's checks are UX. Anything that could redirect the
|
||||
* frame away from the endpoint is rejected rather than sanitized, because
|
||||
* sanitizing invites a second, subtly different implementation elsewhere.
|
||||
*/
|
||||
function normalizePath(raw: unknown): string | null {
|
||||
if (raw === undefined || raw === null || raw === "") return "/";
|
||||
if (typeof raw !== "string") return null;
|
||||
if (hasControlCharacter(raw)) return null;
|
||||
|
||||
const path = raw.startsWith("/") ? raw : `/${raw}`;
|
||||
|
||||
if (path.startsWith("//")) return null;
|
||||
if (/^\/[a-z][a-z0-9+.-]*:/i.test(path)) return null;
|
||||
if (path.includes("\\")) return null;
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* A bare host literal, or null to drop the endpoint, or undefined to leave the
|
||||
* field unset (the route then falls back to loopback).
|
||||
*
|
||||
* The value lands both in a TCP listener and in a URL authority, so nothing
|
||||
* carrying a scheme, port, path or credentials may survive.
|
||||
*/
|
||||
function normalizeBindHost(raw: unknown): string | null | undefined {
|
||||
if (raw === undefined || raw === null || raw === "") return undefined;
|
||||
if (typeof raw !== "string") return null;
|
||||
|
||||
const value = raw.trim();
|
||||
if (!value) return undefined;
|
||||
if (value.length > 253) return null;
|
||||
if (hasControlCharacter(value)) return null;
|
||||
|
||||
const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
|
||||
const HOSTNAME =
|
||||
/^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/;
|
||||
const IPV6_BRACKETED = /^\[[0-9A-Fa-f:.]+\]$/;
|
||||
|
||||
if (IPV4.test(value)) {
|
||||
return value.split(".").every((part) => Number(part) <= 255) ? value : null;
|
||||
}
|
||||
if (IPV6_BRACKETED.test(value) || HOSTNAME.test(value)) return value;
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeEndpoint(raw: unknown): WebEndpoint | null {
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
const input = raw as Record<string, unknown>;
|
||||
|
||||
const id = typeof input.id === "string" ? input.id.trim() : "";
|
||||
if (!id) return null;
|
||||
|
||||
const label = typeof input.label === "string" ? input.label.trim() : "";
|
||||
if (!label) return null;
|
||||
|
||||
const scheme = input.scheme;
|
||||
if (typeof scheme !== "string" || !SCHEMES.has(scheme)) return null;
|
||||
|
||||
if (!isValidPort(input.port)) return null;
|
||||
|
||||
const path = normalizePath(input.path);
|
||||
if (path === null) return null;
|
||||
|
||||
const access = input.access;
|
||||
if (typeof access !== "string" || !ACCESS_VALUES.has(access)) return null;
|
||||
|
||||
const render = input.render;
|
||||
if (typeof render !== "string" || !RENDER_VALUES.has(render)) return null;
|
||||
|
||||
const isTunnel = access === "tunnel";
|
||||
|
||||
const endpoint: WebEndpoint = {
|
||||
id,
|
||||
label: label.slice(0, MAX_WEB_ENDPOINT_LABEL_LENGTH),
|
||||
scheme: scheme as WebEndpoint["scheme"],
|
||||
port: input.port,
|
||||
path,
|
||||
access: access as WebEndpoint["access"],
|
||||
render: render as WebEndpoint["render"],
|
||||
// Meaningless for a tunnel, whose host component is loopback and already
|
||||
// exempt from certificate checks. Cleared rather than carried so nothing
|
||||
// downstream has to re-derive that.
|
||||
ignoreCert: !isTunnel && input.ignoreCert === true,
|
||||
};
|
||||
|
||||
// Both are tunnel-only. Silently ignored on a direct endpoint rather than
|
||||
// rejected: they describe a forward that a direct endpoint never creates.
|
||||
if (isTunnel) {
|
||||
const bindHost = normalizeBindHost(input.bindHost);
|
||||
if (bindHost === null) return null;
|
||||
if (bindHost !== undefined) endpoint.bindHost = bindHost;
|
||||
|
||||
if (input.localPort !== undefined && input.localPort !== null) {
|
||||
if (!isValidPort(input.localPort)) return null;
|
||||
endpoint.localPort = input.localPort;
|
||||
}
|
||||
}
|
||||
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops any endpoint it refuses rather than rejecting the whole host -- one
|
||||
* bad row must not make a host unsaveable or unlistable. The editor is
|
||||
* responsible for telling the user before that happens
|
||||
* (src/ui/lib/web-endpoint-validation.ts).
|
||||
*/
|
||||
export function normalizeWebEndpoints(raw: unknown): WebEndpoint[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const seen = new Set<string>();
|
||||
const endpoints: WebEndpoint[] = [];
|
||||
|
||||
for (const candidate of raw) {
|
||||
if (endpoints.length >= MAX_WEB_ENDPOINTS) break;
|
||||
const endpoint = normalizeEndpoint(candidate);
|
||||
if (!endpoint) continue;
|
||||
if (seen.has(endpoint.id)) continue;
|
||||
seen.add(endpoint.id);
|
||||
endpoints.push(endpoint);
|
||||
}
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
/**
|
||||
* Never throws. A malformed stored value yields an empty endpoint list, so a
|
||||
* half-written config cannot take out the whole host listing -- which is what
|
||||
* dockerConfig's bare JSON.parse does today.
|
||||
*/
|
||||
export function parseWebUiConfig(raw: unknown): WebUiConfig {
|
||||
if (raw === undefined || raw === null) return { endpoints: [] };
|
||||
|
||||
let value: unknown = raw;
|
||||
if (typeof raw === "string") {
|
||||
try {
|
||||
value = JSON.parse(raw);
|
||||
} catch {
|
||||
return { endpoints: [] };
|
||||
}
|
||||
}
|
||||
|
||||
if (!value || typeof value !== "object") return { endpoints: [] };
|
||||
return {
|
||||
endpoints: normalizeWebEndpoints(
|
||||
(value as { endpoints?: unknown }).endpoints,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** Null when nothing survives normalization, so the column is cleared. */
|
||||
export function serializeWebUiConfig(config: unknown): string | null {
|
||||
const endpoints = normalizeWebEndpoints(
|
||||
(config as { endpoints?: unknown } | null | undefined)?.endpoints,
|
||||
);
|
||||
if (endpoints.length === 0) return null;
|
||||
return JSON.stringify({ endpoints });
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import { applyFolderAccessRules } from "../../utils/folder-access-inheritance.js";
|
||||
import { findUsableCredential } from "../../hosts/usable-credential.js";
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import express, { type Request, type Response } from "express";
|
||||
import axios from "axios";
|
||||
@@ -12,7 +14,7 @@ import {
|
||||
pickResolvedPassword,
|
||||
pickResolvedUsername,
|
||||
} from "../../hosts/credential-username.js";
|
||||
import { notifyAutomationInternalEvent } from "../../hosts/metrics/automation-bridge.js";
|
||||
import { notifyAutomationInternalEvent } from "../../hosts/automation-events.js";
|
||||
import {
|
||||
createCurrentCommandHistoryRepository,
|
||||
createCurrentCredentialRepository,
|
||||
@@ -28,12 +30,15 @@ import {
|
||||
createCurrentHostRepository,
|
||||
createCurrentUserRepository,
|
||||
createCurrentSyncTombstoneRepository,
|
||||
createCurrentSharedHostAuthOverrideRepository,
|
||||
} from "../repositories/factory.js";
|
||||
import {
|
||||
applyHostKeyTypeUpdate,
|
||||
containsOwnerPrivateAuthUpdate,
|
||||
isNonEmptyString,
|
||||
isOptionalBoolean,
|
||||
isValidPort,
|
||||
normalizeProtocolEnableFields,
|
||||
OWNER_PRIVATE_AUTH_FIELDS,
|
||||
OWNER_PRIVATE_TERMINAL_CONFIG_FIELDS,
|
||||
sanitizeHostForRecipient,
|
||||
@@ -42,6 +47,7 @@ import {
|
||||
} from "./host-normalizers.js";
|
||||
import { validateParentHostId } from "./host-parent-validation.js";
|
||||
import { registerHostOpksshRoutes } from "./host-opkssh-routes.js";
|
||||
import { registerHostStepCaRoutes } from "./host-step-ca-routes.js";
|
||||
import { registerHostFolderRoutes } from "./host-folder-routes.js";
|
||||
import { registerHostFileManagerBookmarkRoutes } from "./host-file-manager-bookmark-routes.js";
|
||||
import { registerHostCommandHistoryRoutes } from "./host-command-history-routes.js";
|
||||
@@ -62,6 +68,11 @@ import type {
|
||||
HostResolutionCredentialRecord,
|
||||
HostResolutionHostRecord,
|
||||
} from "../repositories/host-resolution-repository.js";
|
||||
import { AUTH_PROTOCOL_METADATA } from "../../../types/auth-protocols.js";
|
||||
import {
|
||||
parseWebUiConfig,
|
||||
serializeWebUiConfig,
|
||||
} from "./host-web-endpoints.js";
|
||||
import {
|
||||
requiresPersonalHostAuthentication,
|
||||
resolveRecipientSharedHostAuthentication,
|
||||
@@ -125,6 +136,7 @@ registerHostInternalRoutes(router);
|
||||
router.post(
|
||||
["/db/host", "/enroll"],
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.create"),
|
||||
requireDataAccess,
|
||||
requireHostEnrollmentAccessForPath,
|
||||
upload.single("key"),
|
||||
@@ -190,9 +202,11 @@ router.post(
|
||||
enableFileManager,
|
||||
scpLegacy,
|
||||
enableDocker,
|
||||
enableWebUi,
|
||||
enableProxmox,
|
||||
enableTmuxMonitor,
|
||||
enableTerminalToolbar,
|
||||
enableAiAssistant,
|
||||
allowSessionSharing,
|
||||
showTerminalInSidebar,
|
||||
showFileManagerInSidebar,
|
||||
@@ -205,6 +219,7 @@ router.post(
|
||||
quickActions,
|
||||
statsConfig,
|
||||
dockerConfig,
|
||||
webUiConfig,
|
||||
proxmoxConfig,
|
||||
enableProxmoxStats,
|
||||
proxmoxStatsConfig,
|
||||
@@ -261,7 +276,8 @@ router.post(
|
||||
!isNonEmptyString(userId) ||
|
||||
!isNonEmptyString(ip) ||
|
||||
!isValidPort(port) ||
|
||||
!isOptionalBoolean(shareSshAuth)
|
||||
!isOptionalBoolean(shareSshAuth) ||
|
||||
![enableSsh, enableRdp, enableVnc, enableTelnet].every(isOptionalBoolean)
|
||||
) {
|
||||
sshLogger.warn("Invalid SSH data input validation failed", {
|
||||
operation: "host_create",
|
||||
@@ -332,9 +348,11 @@ router.post(
|
||||
enableFileManager: enableFileManager ? 1 : 0,
|
||||
scpLegacy: scpLegacy ? 1 : 0,
|
||||
enableDocker: enableDocker ? 1 : 0,
|
||||
enableWebUi: enableWebUi ? 1 : 0,
|
||||
enableProxmox: enableProxmox ? 1 : 0,
|
||||
enableTmuxMonitor: enableTmuxMonitor ? 1 : 0,
|
||||
enableTerminalToolbar: enableTerminalToolbar === false ? 0 : 1,
|
||||
enableAiAssistant: enableAiAssistant ? 1 : 0,
|
||||
allowSessionSharing: allowSessionSharing === false ? 0 : 1,
|
||||
showTerminalInSidebar: showTerminalInSidebar ? 1 : 0,
|
||||
showFileManagerInSidebar: showFileManagerInSidebar ? 1 : 0,
|
||||
@@ -352,6 +370,13 @@ router.post(
|
||||
? dockerConfig
|
||||
: JSON.stringify(dockerConfig)
|
||||
: null,
|
||||
webUiConfig: enableWebUi
|
||||
? serializeWebUiConfig(
|
||||
typeof webUiConfig === "string"
|
||||
? safeParseJson(webUiConfig)
|
||||
: webUiConfig,
|
||||
)
|
||||
: null,
|
||||
proxmoxConfig: proxmoxConfig
|
||||
? typeof proxmoxConfig === "string"
|
||||
? proxmoxConfig
|
||||
@@ -392,10 +417,7 @@ router.post(
|
||||
portKnockSequence: portKnockSequence
|
||||
? JSON.stringify(portKnockSequence)
|
||||
: null,
|
||||
enableSsh: enableSsh ? 1 : 0,
|
||||
enableRdp: enableRdp ? 1 : 0,
|
||||
enableVnc: enableVnc ? 1 : 0,
|
||||
enableTelnet: enableTelnet ? 1 : 0,
|
||||
...normalizeProtocolEnableFields(hostData),
|
||||
sshPort: sshPort || port || 22,
|
||||
rdpPort: rdpPort || 3389,
|
||||
vncPort: vncPort || 5900,
|
||||
@@ -498,6 +520,20 @@ router.post(
|
||||
}
|
||||
|
||||
const createdHost = result;
|
||||
// Standing folder shares apply to the newcomer.
|
||||
try {
|
||||
await applyFolderAccessRules(
|
||||
createdHost.id,
|
||||
userId!,
|
||||
createdHost.folder,
|
||||
);
|
||||
} catch (folderAccessError) {
|
||||
sshLogger.warn("Failed to inherit folder access on host create", {
|
||||
operation: "host_create_folder_access",
|
||||
hostId: createdHost.id,
|
||||
error: getErrorMessage(folderAccessError),
|
||||
});
|
||||
}
|
||||
const baseHost = transformHostResponse(createdHost);
|
||||
|
||||
const resolvedHost =
|
||||
@@ -712,11 +748,7 @@ router.post(
|
||||
let resolvedUsername = username;
|
||||
|
||||
if (authType === "credential" && credentialId) {
|
||||
const cred =
|
||||
await createCurrentHostResolutionRepository().findCredentialByIdForUser(
|
||||
Number(credentialId),
|
||||
userId,
|
||||
);
|
||||
const cred = await findUsableCredential(Number(credentialId), userId);
|
||||
|
||||
if (!cred) {
|
||||
return res.status(404).json({ error: "Credential not found" });
|
||||
@@ -753,10 +785,12 @@ router.post(
|
||||
enableTunnel: false,
|
||||
enableFileManager: true,
|
||||
enableDocker: false,
|
||||
enableWebUi: false,
|
||||
enableProxmox: false,
|
||||
enableProxmoxStats: false,
|
||||
enableTmuxMonitor: false,
|
||||
enableTerminalToolbar: true,
|
||||
enableAiAssistant: false,
|
||||
showTerminalInSidebar: true,
|
||||
showFileManagerInSidebar: false,
|
||||
showTunnelInSidebar: false,
|
||||
@@ -817,6 +851,7 @@ router.post(
|
||||
router.put(
|
||||
"/db/host/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.edit"),
|
||||
requireDataAccess,
|
||||
upload.single("key"),
|
||||
async (req: Request, res: Response) => {
|
||||
@@ -882,9 +917,11 @@ router.put(
|
||||
enableFileManager,
|
||||
scpLegacy,
|
||||
enableDocker,
|
||||
enableWebUi,
|
||||
enableProxmox,
|
||||
enableTmuxMonitor,
|
||||
enableTerminalToolbar,
|
||||
enableAiAssistant,
|
||||
allowSessionSharing,
|
||||
showTerminalInSidebar,
|
||||
showFileManagerInSidebar,
|
||||
@@ -897,6 +934,7 @@ router.put(
|
||||
quickActions,
|
||||
statsConfig,
|
||||
dockerConfig,
|
||||
webUiConfig,
|
||||
proxmoxConfig,
|
||||
enableProxmoxStats,
|
||||
proxmoxStatsConfig,
|
||||
@@ -954,6 +992,9 @@ router.put(
|
||||
!isNonEmptyString(ip) ||
|
||||
!isValidPort(port) ||
|
||||
!isOptionalBoolean(shareSshAuth) ||
|
||||
![enableSsh, enableRdp, enableVnc, enableTelnet].every(
|
||||
isOptionalBoolean,
|
||||
) ||
|
||||
!hostId
|
||||
) {
|
||||
sshLogger.warn("Invalid SSH data input validation failed for update", {
|
||||
@@ -1025,9 +1066,11 @@ router.put(
|
||||
enableFileManager: enableFileManager ? 1 : 0,
|
||||
scpLegacy: scpLegacy ? 1 : 0,
|
||||
enableDocker: enableDocker ? 1 : 0,
|
||||
enableWebUi: enableWebUi ? 1 : 0,
|
||||
enableProxmox: enableProxmox ? 1 : 0,
|
||||
enableTmuxMonitor: enableTmuxMonitor ? 1 : 0,
|
||||
enableTerminalToolbar: enableTerminalToolbar === false ? 0 : 1,
|
||||
enableAiAssistant: enableAiAssistant ? 1 : 0,
|
||||
allowSessionSharing: allowSessionSharing === false ? 0 : 1,
|
||||
showTerminalInSidebar: showTerminalInSidebar ? 1 : 0,
|
||||
showFileManagerInSidebar: showFileManagerInSidebar ? 1 : 0,
|
||||
@@ -1045,6 +1088,13 @@ router.put(
|
||||
? dockerConfig
|
||||
: JSON.stringify(dockerConfig)
|
||||
: null,
|
||||
webUiConfig: enableWebUi
|
||||
? serializeWebUiConfig(
|
||||
typeof webUiConfig === "string"
|
||||
? safeParseJson(webUiConfig)
|
||||
: webUiConfig,
|
||||
)
|
||||
: null,
|
||||
proxmoxConfig: proxmoxConfig
|
||||
? typeof proxmoxConfig === "string"
|
||||
? proxmoxConfig
|
||||
@@ -1085,10 +1135,7 @@ router.put(
|
||||
portKnockSequence: portKnockSequence
|
||||
? JSON.stringify(portKnockSequence)
|
||||
: null,
|
||||
enableSsh: enableSsh ? 1 : 0,
|
||||
enableRdp: enableRdp ? 1 : 0,
|
||||
enableVnc: enableVnc ? 1 : 0,
|
||||
enableTelnet: enableTelnet ? 1 : 0,
|
||||
...normalizeProtocolEnableFields(hostData),
|
||||
sshPort: sshPort || port || 22,
|
||||
rdpPort: rdpPort || 3389,
|
||||
vncPort: vncPort || 5900,
|
||||
@@ -1157,9 +1204,7 @@ router.put(
|
||||
if (keyPassword !== undefined) {
|
||||
sshDataObj.keyPassword = keyPassword || null;
|
||||
}
|
||||
if (keyType) {
|
||||
sshDataObj.keyType = keyType;
|
||||
}
|
||||
applyHostKeyTypeUpdate(sshDataObj, keyType);
|
||||
sshDataObj.password = password || null;
|
||||
} else if (effectiveAuthType === "credential") {
|
||||
sshDataObj.password = password || null;
|
||||
@@ -1370,6 +1415,21 @@ router.put(
|
||||
sshDataObj,
|
||||
);
|
||||
|
||||
// A host that moved into a folder inherits that folder's standing shares.
|
||||
try {
|
||||
await applyFolderAccessRules(
|
||||
Number(hostId),
|
||||
ownerId,
|
||||
sshDataObj.folder as string | null | undefined,
|
||||
);
|
||||
} catch (folderAccessError) {
|
||||
sshLogger.warn("Failed to inherit folder access on host update", {
|
||||
operation: "host_update_folder_access",
|
||||
hostId: parseInt(hostId),
|
||||
error: getErrorMessage(folderAccessError),
|
||||
});
|
||||
}
|
||||
|
||||
// Keep every recipient's re-encrypted secret snapshots in sync with
|
||||
// the updated host record.
|
||||
try {
|
||||
@@ -1455,9 +1515,94 @@ router.put(
|
||||
* 500:
|
||||
* description: Failed to fetch SSH data.
|
||||
*/
|
||||
/**
|
||||
* @openapi
|
||||
* /host/db/host/{id}/terminal-config:
|
||||
* patch:
|
||||
* summary: Update a host's terminal behaviour flags
|
||||
* description: Merges the given flags into the host's terminalConfig. Owner or a recipient with edit access. Currently supports autoTmux; used by the "enable Auto-Tmux" action shown when a persisted session expires.
|
||||
* tags:
|
||||
* - Hosts
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* autoTmux:
|
||||
* type: boolean
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Updated.
|
||||
* 403:
|
||||
* description: No edit access.
|
||||
* 404:
|
||||
* description: Host not found.
|
||||
*/
|
||||
router.patch(
|
||||
"/db/host/:id/terminal-config",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.edit"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId!;
|
||||
const hostId = parseInt(String(req.params.id), 10);
|
||||
const { autoTmux } = req.body ?? {};
|
||||
|
||||
if (isNaN(hostId)) {
|
||||
return res.status(400).json({ error: "Invalid host ID" });
|
||||
}
|
||||
if (typeof autoTmux !== "boolean") {
|
||||
return res.status(400).json({ error: "autoTmux must be a boolean" });
|
||||
}
|
||||
|
||||
try {
|
||||
const access = await permissionManager.canAccessHost(
|
||||
userId,
|
||||
hostId,
|
||||
"edit",
|
||||
);
|
||||
if (!access.hasAccess) {
|
||||
return res.status(403).json({ error: "Access denied to host" });
|
||||
}
|
||||
const ownerId =
|
||||
await createCurrentHostResolutionRepository().findHostOwnerId(hostId);
|
||||
const host = ownerId
|
||||
? await createCurrentHostRepository().findByIdForUser(ownerId, hostId)
|
||||
: null;
|
||||
if (!host || !ownerId) {
|
||||
return res.status(404).json({ error: "Host not found" });
|
||||
}
|
||||
|
||||
let terminalConfig: Record<string, unknown> = {};
|
||||
if (host.terminalConfig) {
|
||||
try {
|
||||
terminalConfig = JSON.parse(host.terminalConfig);
|
||||
} catch {
|
||||
terminalConfig = {};
|
||||
}
|
||||
}
|
||||
await createCurrentHostRepository().updateForUser(ownerId, hostId, {
|
||||
terminalConfig: JSON.stringify({ ...terminalConfig, autoTmux }),
|
||||
});
|
||||
|
||||
res.json({ success: true, autoTmux });
|
||||
} catch (error) {
|
||||
sshLogger.error("Failed to update host terminal config", error, {
|
||||
operation: "host_terminal_config_update",
|
||||
hostId,
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to update terminal config" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.get(
|
||||
"/db/host",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -1601,6 +1746,7 @@ router.get(
|
||||
router.get(
|
||||
"/db/host/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const hostId = Array.isArray(req.params.id)
|
||||
@@ -1695,6 +1841,78 @@ router.get(
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns the minimum authentication material needed by the desktop app to
|
||||
* connect to a shared host from the recipient's own network. The response is
|
||||
* deliberately transient: callers must not persist it or include it in logs.
|
||||
*/
|
||||
router.get(
|
||||
"/db/host/:id/local-connection-auth",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const hostId = Number(req.params.id);
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
if (!isNonEmptyString(userId) || !Number.isInteger(hostId) || hostId <= 0) {
|
||||
return res.status(400).json({ error: "Invalid userId or hostId" });
|
||||
}
|
||||
|
||||
try {
|
||||
const access = await permissionManager.canAccessHost(
|
||||
userId,
|
||||
hostId,
|
||||
"connect",
|
||||
);
|
||||
if (!access.hasAccess || !access.isShared) {
|
||||
return res.status(404).json({ error: "Shared host not found" });
|
||||
}
|
||||
|
||||
const repository = createCurrentHostResolutionRepository();
|
||||
const ownerId = await repository.findHostOwnerId(hostId);
|
||||
const host = ownerId
|
||||
? await repository.findHostById(hostId, ownerId)
|
||||
: null;
|
||||
if (!host) {
|
||||
return res.status(404).json({ error: "Shared host not found" });
|
||||
}
|
||||
|
||||
const resolved = await resolveHostCredentials(
|
||||
{
|
||||
...transformHostResponse(host),
|
||||
isShared: true,
|
||||
permissionLevel: access.permissionLevel,
|
||||
},
|
||||
userId,
|
||||
);
|
||||
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
return res.json({
|
||||
username: resolved.username,
|
||||
authType: resolved.authType,
|
||||
password: resolved.password || null,
|
||||
key: resolved.key || null,
|
||||
keyPassword: resolved.keyPassword || null,
|
||||
keyType: resolved.keyType || null,
|
||||
});
|
||||
} catch (error) {
|
||||
sshLogger.error(
|
||||
"Failed to resolve shared host local authentication",
|
||||
error,
|
||||
{
|
||||
operation: "shared_host_local_auth_resolve",
|
||||
hostId,
|
||||
userId,
|
||||
},
|
||||
);
|
||||
return res
|
||||
.status(500)
|
||||
.json({ error: "Failed to resolve shared host authentication" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /host/db/host/{id}/password:
|
||||
@@ -1843,6 +2061,7 @@ router.get(
|
||||
);
|
||||
|
||||
const baseExportData = {
|
||||
exportId: resolvedHost.id,
|
||||
connectionType: exportedConnectionType,
|
||||
name: resolvedHost.name,
|
||||
ip: resolvedHost.ip,
|
||||
@@ -1896,14 +2115,17 @@ router.get(
|
||||
overrideCredentialUsername:
|
||||
!!resolvedHost.overrideCredentialUsername,
|
||||
enableTerminal: !!resolvedHost.enableTerminal,
|
||||
enableCommandHistory: resolvedHost.enableCommandHistory !== false,
|
||||
enableTunnel: !!resolvedHost.enableTunnel,
|
||||
enableFileManager: resolvedHost.enableFileManager !== false,
|
||||
scpLegacy: !!resolvedHost.scpLegacy,
|
||||
enableDocker: !!resolvedHost.enableDocker,
|
||||
enableWebUi: !!resolvedHost.enableWebUi,
|
||||
enableProxmox: !!resolvedHost.enableProxmox,
|
||||
enableProxmoxStats: !!resolvedHost.enableProxmoxStats,
|
||||
enableTmuxMonitor: !!resolvedHost.enableTmuxMonitor,
|
||||
enableTerminalToolbar: resolvedHost.enableTerminalToolbar !== false,
|
||||
enableAiAssistant: !!resolvedHost.enableAiAssistant,
|
||||
showTerminalInSidebar: !!resolvedHost.showTerminalInSidebar,
|
||||
showFileManagerInSidebar: !!resolvedHost.showFileManagerInSidebar,
|
||||
showTunnelInSidebar: !!resolvedHost.showTunnelInSidebar,
|
||||
@@ -1923,6 +2145,7 @@ router.get(
|
||||
statsConfig: resolvedHost.statsConfig
|
||||
? JSON.parse(resolvedHost.statsConfig as string)
|
||||
: null,
|
||||
webUiConfig: parseWebUiConfig(resolvedHost.webUiConfig),
|
||||
dockerConfig: resolvedHost.dockerConfig
|
||||
? JSON.parse(resolvedHost.dockerConfig as string)
|
||||
: null,
|
||||
@@ -2022,6 +2245,7 @@ router.get(
|
||||
);
|
||||
|
||||
const baseExportData = {
|
||||
exportId: resolvedHost.id,
|
||||
connectionType: exportedConnectionType,
|
||||
name: resolvedHost.name,
|
||||
ip: resolvedHost.ip,
|
||||
@@ -2057,13 +2281,16 @@ router.get(
|
||||
overrideCredentialUsername:
|
||||
!!resolvedHost.overrideCredentialUsername,
|
||||
enableTerminal: !!resolvedHost.enableTerminal,
|
||||
enableCommandHistory: resolvedHost.enableCommandHistory !== false,
|
||||
enableTunnel: !!resolvedHost.enableTunnel,
|
||||
enableFileManager: resolvedHost.enableFileManager !== false,
|
||||
enableDocker: !!resolvedHost.enableDocker,
|
||||
enableWebUi: !!resolvedHost.enableWebUi,
|
||||
enableProxmox: !!resolvedHost.enableProxmox,
|
||||
enableTmuxMonitor: !!resolvedHost.enableTmuxMonitor,
|
||||
enableTerminalToolbar:
|
||||
resolvedHost.enableTerminalToolbar !== false,
|
||||
enableAiAssistant: !!resolvedHost.enableAiAssistant,
|
||||
showTerminalInSidebar: !!resolvedHost.showTerminalInSidebar,
|
||||
showFileManagerInSidebar: !!resolvedHost.showFileManagerInSidebar,
|
||||
showTunnelInSidebar: !!resolvedHost.showTunnelInSidebar,
|
||||
@@ -2085,6 +2312,7 @@ router.get(
|
||||
statsConfig: resolvedHost.statsConfig
|
||||
? JSON.parse(resolvedHost.statsConfig as string)
|
||||
: null,
|
||||
webUiConfig: parseWebUiConfig(resolvedHost.webUiConfig),
|
||||
dockerConfig: resolvedHost.dockerConfig
|
||||
? JSON.parse(resolvedHost.dockerConfig as string)
|
||||
: null,
|
||||
@@ -2223,6 +2451,7 @@ router.get(
|
||||
router.delete(
|
||||
"/db/host/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.delete"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -2354,11 +2583,18 @@ router.delete(
|
||||
},
|
||||
);
|
||||
|
||||
registerHostFileManagerBookmarkRoutes(router, authenticateJWT);
|
||||
registerHostFileManagerBookmarkRoutes(
|
||||
router,
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.view"),
|
||||
requireDataAccess,
|
||||
);
|
||||
|
||||
router.get(
|
||||
"/transfer/recent",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const sourceHostIdQuery = Array.isArray(req.query.sourceHostId)
|
||||
@@ -2395,6 +2631,8 @@ router.get(
|
||||
router.post(
|
||||
"/transfer/recent",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
const { sourceHostId, destHostId, destPath, destPathLabel } = req.body;
|
||||
@@ -2426,7 +2664,12 @@ router.post(
|
||||
}
|
||||
},
|
||||
);
|
||||
registerHostCommandHistoryRoutes(router, authenticateJWT);
|
||||
registerHostCommandHistoryRoutes(
|
||||
router,
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.view"),
|
||||
requireDataAccess,
|
||||
);
|
||||
|
||||
async function resolveHostCredentials(
|
||||
host: Record<string, unknown>,
|
||||
@@ -2455,6 +2698,24 @@ async function resolveHostCredentials(
|
||||
required: needsPersonalCredential,
|
||||
ownerAuthShared: !!host.shareSshAuth,
|
||||
};
|
||||
// Owner auth for the remote desktop protocols is always snapshotted
|
||||
// for recipients; only their own override credential varies per user.
|
||||
const authOverrides: Record<string, unknown> = {
|
||||
ssh: baseSshOverrideState,
|
||||
};
|
||||
const overrideCredentialIds =
|
||||
await createCurrentSharedHostAuthOverrideRepository().listCredentialIds(
|
||||
host.id,
|
||||
requestingUserId,
|
||||
);
|
||||
for (const protocol of ["rdp", "vnc", "telnet"] as const) {
|
||||
if (!host[AUTH_PROTOCOL_METADATA[protocol].enableField]) continue;
|
||||
authOverrides[protocol] = {
|
||||
credentialId: overrideCredentialIds[protocol],
|
||||
required: false,
|
||||
ownerAuthShared: true,
|
||||
};
|
||||
}
|
||||
const recipientHost: Record<string, unknown> = {
|
||||
...host,
|
||||
credentialId: null,
|
||||
@@ -2462,9 +2723,7 @@ async function resolveHostCredentials(
|
||||
key: null,
|
||||
keyPassword: null,
|
||||
keyType: null,
|
||||
authOverrides: {
|
||||
ssh: baseSshOverrideState,
|
||||
},
|
||||
authOverrides,
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -2480,6 +2739,7 @@ async function resolveHostCredentials(
|
||||
return {
|
||||
...recipientHost,
|
||||
authOverrides: {
|
||||
...authOverrides,
|
||||
ssh: {
|
||||
credentialId: resolution.credentialId,
|
||||
required: false,
|
||||
@@ -2505,6 +2765,7 @@ async function resolveHostCredentials(
|
||||
return {
|
||||
...recipientHost,
|
||||
authOverrides: {
|
||||
...authOverrides,
|
||||
ssh: {
|
||||
required: false,
|
||||
ownerAuthShared: true,
|
||||
@@ -2524,6 +2785,7 @@ async function resolveHostCredentials(
|
||||
return {
|
||||
...recipientHost,
|
||||
authOverrides: {
|
||||
...authOverrides,
|
||||
ssh: {
|
||||
required: false,
|
||||
ownerAuthShared: true,
|
||||
@@ -2547,6 +2809,7 @@ async function resolveHostCredentials(
|
||||
return {
|
||||
...recipientHost,
|
||||
authOverrides: {
|
||||
...authOverrides,
|
||||
ssh: {
|
||||
required: false,
|
||||
ownerAuthShared: !!host.shareSshAuth,
|
||||
@@ -2567,10 +2830,7 @@ async function resolveHostCredentials(
|
||||
|
||||
const credential =
|
||||
preloadedCredentials?.get(credentialId) ??
|
||||
(await createCurrentHostResolutionRepository().findCredentialByIdForUser(
|
||||
credentialId,
|
||||
credentialOwnerId,
|
||||
));
|
||||
(await findUsableCredential(credentialId, credentialOwnerId));
|
||||
|
||||
if (credential) {
|
||||
const resolvedHost: Record<string, unknown> = {
|
||||
@@ -2605,13 +2865,27 @@ async function resolveHostCredentials(
|
||||
|
||||
registerHostFolderRoutes(router, {
|
||||
authenticateJWT,
|
||||
requireViewPermission: permissionManager.requirePermission("hosts.view"),
|
||||
requireEditPermission: permissionManager.requirePermission("hosts.edit"),
|
||||
requireDeletePermission: permissionManager.requirePermission("hosts.delete"),
|
||||
requireCredentialEditPermission:
|
||||
permissionManager.requirePermission("credentials.edit"),
|
||||
requireDataAccess,
|
||||
statsServerUrl: STATS_SERVER_URL,
|
||||
});
|
||||
|
||||
registerHostBulkRoutes(router, authenticateJWT);
|
||||
registerHostBulkRoutes(
|
||||
router,
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.create"),
|
||||
permissionManager.requirePermission("hosts.edit"),
|
||||
requireDataAccess,
|
||||
);
|
||||
|
||||
registerHostAutostartRoutes(router, {
|
||||
authenticateJWT,
|
||||
requireViewPermission: permissionManager.requirePermission("hosts.view"),
|
||||
requireEditPermission: permissionManager.requirePermission("hosts.edit"),
|
||||
requireDataAccess,
|
||||
});
|
||||
|
||||
@@ -2656,6 +2930,8 @@ registerHostAutostartRoutes(router, {
|
||||
router.get(
|
||||
"/ssh/opkssh/token/:hostId",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.view"),
|
||||
requireDataAccess,
|
||||
requireDataAccess,
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const userId = req.userId;
|
||||
@@ -2727,6 +3003,8 @@ router.get(
|
||||
router.delete(
|
||||
"/ssh/opkssh/token/:hostId",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.edit"),
|
||||
requireDataAccess,
|
||||
requireDataAccess,
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const userId = req.userId;
|
||||
@@ -2756,10 +3034,26 @@ router.delete(
|
||||
);
|
||||
|
||||
registerHostOpksshRoutes(router);
|
||||
registerHostStepCaRoutes(router);
|
||||
|
||||
registerHostNetworkRoutes(router, {
|
||||
authenticateJWT,
|
||||
requireViewPermission: permissionManager.requirePermission("hosts.view"),
|
||||
requireDataAccess,
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
/**
|
||||
* A webUiConfig arriving as a JSON string (an import, or a client that
|
||||
* stringified it) must still reach serializeWebUiConfig as an object.
|
||||
* Malformed input becomes null, which serializes to a cleared column rather
|
||||
* than throwing inside a host save.
|
||||
*/
|
||||
function safeParseJson(raw: string): unknown {
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ const VALID_ACTION_TYPES = [
|
||||
"sendControlCode",
|
||||
"sendText",
|
||||
"runSnippet",
|
||||
"nextTab",
|
||||
"previousTab",
|
||||
"openCommandPalette",
|
||||
];
|
||||
|
||||
export function isValidKeyCombo(combo: unknown): boolean {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { sshLogger } from "../../utils/logger.js";
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
export function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// Mounted at /plugin-api. Every installed plugin that exposes backend routes
|
||||
// registers a sub-router here under its own plugin id, and this dispatcher
|
||||
// forwards matching requests to it. Nothing registers yet, this only proves
|
||||
// the path resolves end to end (nginx -> Express -> 404) ahead of the plugin
|
||||
// loader landing.
|
||||
//
|
||||
// WebSocket note: plugin WS traffic does NOT get its own port from the
|
||||
// 30001-30006 range. It rides the existing WS servers (e.g. the terminal or
|
||||
// tunnel WS servers) using a named-channel envelope, the same way other
|
||||
// features multiplex over a shared connection. This is a settled decision,
|
||||
// not a placeholder, so it should not need revisiting when plugin WS support
|
||||
// is implemented.
|
||||
|
||||
import express, { type Request, type Response, type Router } from "express";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const activePluginRouters = new Map<string, Router>();
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /plugin-api/{pluginId}/{path}:
|
||||
* get:
|
||||
* summary: Dispatch a request to an installed plugin's backend router
|
||||
* description: >
|
||||
* Forwards the request to the sub-router registered by the plugin with
|
||||
* the given id. Returns 404 if the plugin is not installed or not
|
||||
* currently running. All HTTP methods are dispatched the same way.
|
||||
* tags:
|
||||
* - Plugins
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: pluginId
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Response from the plugin's router.
|
||||
* 404:
|
||||
* description: Plugin not installed or not running.
|
||||
*/
|
||||
router.use("/:pluginId", (req: Request, res: Response, next) => {
|
||||
const pluginId = String(req.params.pluginId);
|
||||
const pluginRouter = activePluginRouters.get(pluginId);
|
||||
|
||||
if (!pluginRouter) {
|
||||
databaseLogger.warn("Plugin API request for unregistered plugin", {
|
||||
operation: "plugin_api_dispatch",
|
||||
pluginId,
|
||||
});
|
||||
res.status(404).json({ error: "Plugin not installed or not running" });
|
||||
return;
|
||||
}
|
||||
|
||||
pluginRouter(req, res, next);
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,17 @@
|
||||
export function parseProxmoxJumpHosts(raw: unknown): unknown[] | null {
|
||||
if (!raw) return null;
|
||||
if (Array.isArray(raw)) return raw;
|
||||
if (typeof raw !== "string") return null;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function serializeProxmoxJumpHosts(raw: unknown): string | null {
|
||||
const parsed = parseProxmoxJumpHosts(raw);
|
||||
return parsed ? JSON.stringify(parsed) : null;
|
||||
}
|
||||
@@ -13,7 +13,12 @@ import { SSHHostKeyVerifier } from "../../hosts/host-key-verifier.js";
|
||||
import { resolveHostById } from "../../hosts/host-resolver.js";
|
||||
import { createJumpHostChain } from "../../hosts/jump-host-chain.js";
|
||||
import { resolveProxmoxImportAuth } from "./proxmox-import-auth.js";
|
||||
import {
|
||||
parseProxmoxJumpHosts,
|
||||
serializeProxmoxJumpHosts,
|
||||
} from "./proxmox-jump-hosts.js";
|
||||
import { isSafeNodeName } from "../../hosts/proxmox-shared.js";
|
||||
import { execElevated } from "../../hosts/metrics/managers/exec-elevated.js";
|
||||
|
||||
const router = express.Router();
|
||||
const proxmoxLogger = logger;
|
||||
@@ -67,6 +72,26 @@ function execCommand(
|
||||
});
|
||||
}
|
||||
|
||||
export async function execPveshCommand(
|
||||
client: SSHClient,
|
||||
command: string,
|
||||
sudoPassword: string | undefined,
|
||||
timeoutMs = 25000,
|
||||
): Promise<string> {
|
||||
if (!sudoPassword) {
|
||||
return execCommand(client, command, timeoutMs);
|
||||
}
|
||||
|
||||
const result = await execElevated(client, command, sudoPassword, {
|
||||
forceSudo: true,
|
||||
timeoutMs,
|
||||
});
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr || `Command exited with code ${result.code}`);
|
||||
}
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
// Parse all IPs from LXC net config, then return the one matching the preferred prefix.
|
||||
function parseLxcIp(
|
||||
config: Record<string, unknown>,
|
||||
@@ -183,20 +208,6 @@ type ProxmoxSyncResult = {
|
||||
errors: string[];
|
||||
};
|
||||
|
||||
function parseJumpHostsField(raw: unknown): unknown[] | null {
|
||||
if (!raw) return null;
|
||||
if (Array.isArray(raw)) return raw;
|
||||
if (typeof raw === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseJsonObject(value: unknown): Record<string, unknown> {
|
||||
if (!value) return {};
|
||||
if (typeof value === "object") return value as Record<string, unknown>;
|
||||
@@ -417,9 +428,10 @@ async function discoverProxmoxGuestsForHost(
|
||||
throw error;
|
||||
}
|
||||
|
||||
const resourcesJson = await execCommand(
|
||||
const resourcesJson = await execPveshCommand(
|
||||
client,
|
||||
"pvesh get /cluster/resources --output-format json 2>/dev/null",
|
||||
host.sudoPassword,
|
||||
);
|
||||
|
||||
let resources: Array<Record<string, unknown>>;
|
||||
@@ -468,9 +480,10 @@ async function discoverProxmoxGuestsForHost(
|
||||
if (g.type === "lxc") {
|
||||
let configIp: string | null = null;
|
||||
try {
|
||||
const cfgJson = await execCommand(
|
||||
const cfgJson = await execPveshCommand(
|
||||
client,
|
||||
`pvesh get /nodes/${g.node}/lxc/${g.vmid}/config --output-format json 2>/dev/null`,
|
||||
host.sudoPassword,
|
||||
25000,
|
||||
);
|
||||
configIp = parseLxcIp(JSON.parse(cfgJson), config.preferredPrefixes);
|
||||
@@ -482,9 +495,10 @@ async function discoverProxmoxGuestsForHost(
|
||||
// Fall back to the live interface list for running containers.
|
||||
if (g.status === "running") {
|
||||
try {
|
||||
const ifRaw = await execCommand(
|
||||
const ifRaw = await execPveshCommand(
|
||||
client,
|
||||
`pvesh get /nodes/${g.node}/lxc/${g.vmid}/interfaces --output-format json 2>/dev/null`,
|
||||
host.sudoPassword,
|
||||
12000,
|
||||
);
|
||||
const data = JSON.parse(ifRaw);
|
||||
@@ -514,9 +528,10 @@ async function discoverProxmoxGuestsForHost(
|
||||
}
|
||||
if (g.type === "qemu" && g.status === "running") {
|
||||
try {
|
||||
const ifJson = await execCommand(
|
||||
const ifJson = await execPveshCommand(
|
||||
client,
|
||||
`pvesh get /nodes/${g.node}/qemu/${g.vmid}/agent/network-get-interfaces --output-format json 2>/dev/null`,
|
||||
host.sudoPassword,
|
||||
12000,
|
||||
);
|
||||
const data = JSON.parse(ifJson);
|
||||
@@ -599,7 +614,7 @@ async function discoverProxmoxGuestsForHost(
|
||||
guests,
|
||||
credentialId: hostCredentialId,
|
||||
defaultCredentialId: config.defaultCredentialId,
|
||||
jumpHosts: parseJumpHostsField(
|
||||
jumpHosts: parseProxmoxJumpHosts(
|
||||
(host as unknown as { jumpHosts?: unknown }).jumpHosts,
|
||||
),
|
||||
config,
|
||||
@@ -770,9 +785,7 @@ async function syncProxmoxHost(
|
||||
telnetPort: null,
|
||||
defaultPath: "/",
|
||||
tunnelConnections: "[]",
|
||||
jumpHosts:
|
||||
(discovery.host as unknown as { jumpHosts?: string | null })
|
||||
.jumpHosts ?? null,
|
||||
jumpHosts: serializeProxmoxJumpHosts(discovery.jumpHosts),
|
||||
quickActions: null,
|
||||
statsConfig: null,
|
||||
dockerConfig: null,
|
||||
|
||||
@@ -3,7 +3,11 @@ import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import express, { type Response } from "express";
|
||||
import { databaseLogger } from "../../utils/logger.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { getRequestMeta } from "../../utils/audit-logger.js";
|
||||
import {
|
||||
getRequestMeta,
|
||||
getAuditUsername,
|
||||
logAudit,
|
||||
} from "../../utils/audit-logger.js";
|
||||
import { isAuthOverrideProtocol } from "../../../types/auth-protocols.js";
|
||||
import {
|
||||
SharedHostAuthOverrideService,
|
||||
@@ -15,11 +19,14 @@ import {
|
||||
type SharePermissionLevel,
|
||||
} from "../../utils/permission-manager.js";
|
||||
import {
|
||||
PERMISSION_CATALOG,
|
||||
getPermissionCatalog,
|
||||
isValidPermission,
|
||||
} from "../../utils/permission-catalog.js";
|
||||
import {
|
||||
createCurrentHostFolderRepository,
|
||||
createCurrentFolderAccessRepository,
|
||||
createCurrentCredentialRepository,
|
||||
createCurrentCredentialAccessRepository,
|
||||
createCurrentHostResolutionRepository,
|
||||
createCurrentRbacAccessRepository,
|
||||
createCurrentRoleRepository,
|
||||
@@ -154,6 +161,7 @@ export function parseShareTargets(
|
||||
router.post(
|
||||
"/host/:id/share",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.share"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
||||
const hostId = parseInt(id, 10);
|
||||
@@ -365,6 +373,7 @@ router.post(
|
||||
router.post(
|
||||
"/folder/share",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("hosts.share"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const userId = req.userId!;
|
||||
const { folder } = req.body ?? {};
|
||||
@@ -422,6 +431,22 @@ router.post(
|
||||
);
|
||||
|
||||
const expiresAt = expiryFromDuration(durationHours);
|
||||
|
||||
// Remember the share on the folder itself so hosts added later inherit it.
|
||||
const folderAccessRepository = createCurrentFolderAccessRepository();
|
||||
for (const target of targets) {
|
||||
await folderAccessRepository.upsert({
|
||||
ownerUserId: userId,
|
||||
folder,
|
||||
grantedBy: userId,
|
||||
permissionLevel,
|
||||
expiresAt,
|
||||
target:
|
||||
target.type === "user"
|
||||
? { targetType: "user", targetUserId: target.id as string }
|
||||
: { targetType: "role", targetRoleId: target.id as number },
|
||||
});
|
||||
}
|
||||
const rbacAccessRepository = createCurrentRbacAccessRepository();
|
||||
const { SharedHostSecretsManager } =
|
||||
await import("../../utils/shared-host-secrets-manager.js");
|
||||
@@ -575,6 +600,78 @@ router.post(
|
||||
* 500:
|
||||
* description: Failed to update grant.
|
||||
*/
|
||||
/**
|
||||
* @openapi
|
||||
* /rbac/folder/access:
|
||||
* get:
|
||||
* summary: Standing shares on one of your folders (inherited by hosts added later)
|
||||
* tags:
|
||||
* - RBAC
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: folder
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
*/
|
||||
router.get(
|
||||
"/folder/access",
|
||||
authenticateJWT,
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const folder = String(req.query.folder ?? "");
|
||||
if (!isNonEmptyString(folder)) {
|
||||
return res.status(400).json({ error: "folder is required" });
|
||||
}
|
||||
try {
|
||||
res.json({
|
||||
rules: await createCurrentFolderAccessRepository().listForFolder(
|
||||
req.userId!,
|
||||
folder,
|
||||
),
|
||||
});
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to list folder access rules", error, {
|
||||
operation: "list_folder_access",
|
||||
});
|
||||
res.status(500).json({ error: "Failed to list folder access" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /rbac/folder/access/{id}:
|
||||
* delete:
|
||||
* summary: Stop a folder share from applying to hosts added later
|
||||
* description: Grants already fanned out to hosts stay; revoke those per host.
|
||||
* tags:
|
||||
* - RBAC
|
||||
*/
|
||||
router.delete(
|
||||
"/folder/access/:id",
|
||||
authenticateJWT,
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const ruleId = parseInt(String(req.params.id), 10);
|
||||
if (isNaN(ruleId)) {
|
||||
return res.status(400).json({ error: "Invalid rule ID" });
|
||||
}
|
||||
try {
|
||||
const repository = createCurrentFolderAccessRepository();
|
||||
if (!(await repository.findById(ruleId, req.userId!))) {
|
||||
return res.status(404).json({ error: "Rule not found" });
|
||||
}
|
||||
await repository.deleteById(ruleId, req.userId!);
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to delete folder access rule", error, {
|
||||
operation: "delete_folder_access",
|
||||
ruleId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to delete folder access" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.patch(
|
||||
"/host/:id/access/:accessId",
|
||||
authenticateJWT,
|
||||
@@ -939,7 +1036,7 @@ router.get(
|
||||
router.post(
|
||||
"/roles",
|
||||
authenticateJWT,
|
||||
permissionManager.requireAdmin(),
|
||||
permissionManager.requirePermission("admin.roles.manage"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const { name, displayName, description } = req.body;
|
||||
|
||||
@@ -1031,7 +1128,7 @@ router.post(
|
||||
router.put(
|
||||
"/roles/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requireAdmin(),
|
||||
permissionManager.requirePermission("admin.roles.manage"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
||||
const roleId = parseInt(id, 10);
|
||||
@@ -1141,7 +1238,7 @@ router.get(
|
||||
"/permissions/catalog",
|
||||
authenticateJWT,
|
||||
async (_req: AuthenticatedRequest, res: Response) => {
|
||||
res.json({ catalog: PERMISSION_CATALOG });
|
||||
res.json({ catalog: getPermissionCatalog() });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1174,7 +1271,7 @@ router.get(
|
||||
router.delete(
|
||||
"/roles/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requireAdmin(),
|
||||
permissionManager.requirePermission("admin.roles.manage"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
||||
const roleId = parseInt(id, 10);
|
||||
@@ -1217,6 +1314,53 @@ router.delete(
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /rbac/roles/{id}/members:
|
||||
* get:
|
||||
* summary: List the users holding a role
|
||||
* tags:
|
||||
* - RBAC
|
||||
* parameters:
|
||||
* - in: path
|
||||
* name: id
|
||||
* required: true
|
||||
* schema:
|
||||
* type: integer
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Role members.
|
||||
* 404:
|
||||
* description: Role not found.
|
||||
*/
|
||||
router.get(
|
||||
"/roles/:id/members",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("admin.roles.manage"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
||||
const roleId = parseInt(id, 10);
|
||||
|
||||
if (isNaN(roleId)) {
|
||||
return res.status(400).json({ error: "Invalid role ID" });
|
||||
}
|
||||
|
||||
try {
|
||||
const roleRepository = createCurrentRoleRepository();
|
||||
if (!(await roleRepository.findRoleById(roleId))) {
|
||||
return res.status(404).json({ error: "Role not found" });
|
||||
}
|
||||
res.json({ members: await roleRepository.listRoleMembers(roleId) });
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to list role members", error, {
|
||||
operation: "list_role_members",
|
||||
roleId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to list role members" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /rbac/users/{userId}/roles:
|
||||
@@ -1257,7 +1401,7 @@ router.delete(
|
||||
router.post(
|
||||
"/users/:userId/roles",
|
||||
authenticateJWT,
|
||||
permissionManager.requireAdmin(),
|
||||
permissionManager.requirePermission("admin.roles.manage"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const targetUserId = Array.isArray(req.params.userId)
|
||||
? req.params.userId[0]
|
||||
@@ -1313,6 +1457,12 @@ router.post(
|
||||
roleId,
|
||||
targetUserId,
|
||||
);
|
||||
const { SharedCredentialSecretsManager } =
|
||||
await import("../../utils/shared-credential-secrets-manager.js");
|
||||
await SharedCredentialSecretsManager.getInstance().snapshotForRoleMember(
|
||||
roleId,
|
||||
targetUserId,
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to snapshot shared host secrets for new role member",
|
||||
@@ -1382,7 +1532,7 @@ router.post(
|
||||
router.delete(
|
||||
"/users/:userId/roles/:roleId",
|
||||
authenticateJWT,
|
||||
permissionManager.requireAdmin(),
|
||||
permissionManager.requirePermission("admin.roles.manage"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const targetUserId = Array.isArray(req.params.userId)
|
||||
? req.params.userId[0]
|
||||
@@ -1422,6 +1572,12 @@ router.delete(
|
||||
roleId,
|
||||
targetUserId,
|
||||
);
|
||||
const { createCurrentSharedCredentialSecretsRepository } =
|
||||
await import("../repositories/factory.js");
|
||||
await createCurrentSharedCredentialSecretsRepository().deleteForRoleMember(
|
||||
roleId,
|
||||
targetUserId,
|
||||
);
|
||||
} catch (cleanupError) {
|
||||
databaseLogger.warn(
|
||||
"Failed to clean shared host secrets after role removal",
|
||||
@@ -1510,6 +1666,239 @@ router.get(
|
||||
},
|
||||
);
|
||||
|
||||
// CREDENTIAL SHARING
|
||||
|
||||
const CREDENTIAL_LEVELS = ["use", "manage"] as const;
|
||||
type CredentialLevel = (typeof CREDENTIAL_LEVELS)[number];
|
||||
|
||||
/** Owner, or a recipient holding "manage". */
|
||||
async function canManageCredentialSharing(
|
||||
userId: string,
|
||||
credentialId: number,
|
||||
): Promise<{ allowed: boolean; ownerId: string | null }> {
|
||||
const row = await createCurrentCredentialRepository().findById(credentialId);
|
||||
if (!row) return { allowed: false, ownerId: null };
|
||||
if (row.userId === userId) return { allowed: true, ownerId: row.userId };
|
||||
const roleIds = await createCurrentRoleRepository().listUserRoleIds(userId);
|
||||
const grant = await createCurrentCredentialAccessRepository().findActiveGrant(
|
||||
credentialId,
|
||||
userId,
|
||||
roleIds,
|
||||
);
|
||||
return { allowed: grant?.permissionLevel === "manage", ownerId: row.userId };
|
||||
}
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /rbac/credential/{id}/share:
|
||||
* post:
|
||||
* summary: Share a credential with users or roles
|
||||
* description: Recipients get a copy of the secrets re-encrypted under their own key. "use" lets them attach it to hosts and connect; "manage" also lets them edit and re-share. Owner or a "manage" recipient only.
|
||||
* tags:
|
||||
* - RBAC
|
||||
*/
|
||||
router.post(
|
||||
"/credential/:id/share",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.share"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
||||
const credentialId = parseInt(id, 10);
|
||||
const userId = req.userId!;
|
||||
if (isNaN(credentialId)) {
|
||||
return res.status(400).json({ error: "Invalid credential ID" });
|
||||
}
|
||||
const targets = parseShareTargets(req.body ?? {});
|
||||
if (!targets) {
|
||||
return res.status(400).json({
|
||||
error:
|
||||
"targets must be a non-empty array of { type: 'user'|'role', id } entries",
|
||||
});
|
||||
}
|
||||
const { durationHours, permissionLevel = "use" } = req.body ?? {};
|
||||
if (!CREDENTIAL_LEVELS.includes(permissionLevel)) {
|
||||
return res.status(400).json({
|
||||
error: "Invalid permission level",
|
||||
validLevels: CREDENTIAL_LEVELS,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const sharing = await canManageCredentialSharing(userId, credentialId);
|
||||
if (!sharing.allowed || !sharing.ownerId) {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Not allowed to share this credential" });
|
||||
}
|
||||
const ownerId = sharing.ownerId;
|
||||
|
||||
const userRepository = createCurrentUserRepository();
|
||||
const roleRepository = createCurrentRoleRepository();
|
||||
for (const target of targets) {
|
||||
const found =
|
||||
target.type === "user"
|
||||
? await userRepository.findById(target.id as string)
|
||||
: await roleRepository.findRoleById(target.id as number);
|
||||
if (!found) {
|
||||
return res.status(404).json({
|
||||
error: `Target ${target.type} not found`,
|
||||
targetId: target.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const expiresAt = expiryFromDuration(durationHours);
|
||||
const accessRepository = createCurrentCredentialAccessRepository();
|
||||
const { SharedCredentialSecretsManager } =
|
||||
await import("../../utils/shared-credential-secrets-manager.js");
|
||||
const manager = SharedCredentialSecretsManager.getInstance();
|
||||
|
||||
for (const target of targets) {
|
||||
if (target.type === "user" && target.id === ownerId) continue;
|
||||
const grant = await accessRepository.upsert({
|
||||
credentialId,
|
||||
grantedBy: userId,
|
||||
permissionLevel: permissionLevel as CredentialLevel,
|
||||
expiresAt,
|
||||
target:
|
||||
target.type === "user"
|
||||
? { targetType: "user", targetUserId: target.id as string }
|
||||
: { targetType: "role", targetRoleId: target.id as number },
|
||||
});
|
||||
try {
|
||||
if (target.type === "user") {
|
||||
await manager.snapshotForUser(
|
||||
grant.id,
|
||||
credentialId,
|
||||
target.id as string,
|
||||
ownerId,
|
||||
);
|
||||
} else {
|
||||
await manager.snapshotForRole(
|
||||
grant.id,
|
||||
credentialId,
|
||||
target.id as number,
|
||||
ownerId,
|
||||
);
|
||||
}
|
||||
} catch (snapshotError) {
|
||||
databaseLogger.warn("Credential shared but secret snapshot failed", {
|
||||
operation: "rbac_credential_share_snapshot_failed",
|
||||
credentialId,
|
||||
accessId: grant.id,
|
||||
error: getErrorMessage(snapshotError),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
await logAudit({
|
||||
userId,
|
||||
username: await getAuditUsername(userId),
|
||||
action: "credential_share",
|
||||
resourceType: "credential",
|
||||
resourceId: String(credentialId),
|
||||
details: JSON.stringify({ targets, permissionLevel, expiresAt }),
|
||||
ipAddress,
|
||||
userAgent,
|
||||
success: true,
|
||||
});
|
||||
|
||||
res.json({ success: true, permissionLevel, expiresAt });
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to share credential", error, {
|
||||
operation: "share_credential",
|
||||
credentialId,
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to share credential" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /rbac/credential/{id}/access:
|
||||
* get:
|
||||
* summary: List who a credential is shared with
|
||||
* tags:
|
||||
* - RBAC
|
||||
*/
|
||||
router.get(
|
||||
"/credential/:id/access",
|
||||
authenticateJWT,
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
||||
const credentialId = parseInt(id, 10);
|
||||
if (isNaN(credentialId)) {
|
||||
return res.status(400).json({ error: "Invalid credential ID" });
|
||||
}
|
||||
try {
|
||||
const sharing = await canManageCredentialSharing(
|
||||
req.userId!,
|
||||
credentialId,
|
||||
);
|
||||
if (!sharing.allowed) {
|
||||
return res.status(403).json({ error: "Not allowed" });
|
||||
}
|
||||
res.json({
|
||||
access:
|
||||
await createCurrentCredentialAccessRepository().listForCredential(
|
||||
credentialId,
|
||||
),
|
||||
});
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to list credential access", error, {
|
||||
operation: "list_credential_access",
|
||||
credentialId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to list credential access" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /rbac/credential/{id}/access/{accessId}:
|
||||
* delete:
|
||||
* summary: Revoke a credential share (recipients' copies are removed with it)
|
||||
* tags:
|
||||
* - RBAC
|
||||
*/
|
||||
router.delete(
|
||||
"/credential/:id/access/:accessId",
|
||||
authenticateJWT,
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const credentialId = parseInt(String(req.params.id), 10);
|
||||
const accessId = parseInt(String(req.params.accessId), 10);
|
||||
if (isNaN(credentialId) || isNaN(accessId)) {
|
||||
return res.status(400).json({ error: "Invalid ID" });
|
||||
}
|
||||
try {
|
||||
const sharing = await canManageCredentialSharing(
|
||||
req.userId!,
|
||||
credentialId,
|
||||
);
|
||||
if (!sharing.allowed) {
|
||||
return res.status(403).json({ error: "Not allowed" });
|
||||
}
|
||||
const repository = createCurrentCredentialAccessRepository();
|
||||
if (!(await repository.findById(accessId, credentialId))) {
|
||||
return res.status(404).json({ error: "Access grant not found" });
|
||||
}
|
||||
await repository.revoke(accessId, credentialId);
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to revoke credential access", error, {
|
||||
operation: "revoke_credential_access",
|
||||
credentialId,
|
||||
accessId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to revoke credential access" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// SNIPPET SHARING
|
||||
|
||||
/**
|
||||
@@ -1524,6 +1913,7 @@ router.get(
|
||||
router.post(
|
||||
"/snippet/:id/share",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.share"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
||||
const snippetId = parseInt(id, 10);
|
||||
@@ -1639,6 +2029,131 @@ router.post(
|
||||
* tags:
|
||||
* - RBAC
|
||||
*/
|
||||
/**
|
||||
* @openapi
|
||||
* /rbac/snippet-folder/share:
|
||||
* post:
|
||||
* summary: Share every snippet in a folder
|
||||
* description: Grants view access to each owned snippet in the folder (and its subfolders) to the given users or roles.
|
||||
* tags:
|
||||
* - RBAC
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* folder:
|
||||
* type: string
|
||||
* targets:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* type:
|
||||
* type: string
|
||||
* enum: [user, role]
|
||||
* id:
|
||||
* oneOf:
|
||||
* - type: string
|
||||
* - type: integer
|
||||
* durationHours:
|
||||
* type: number
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Folder shared.
|
||||
* 404:
|
||||
* description: A target was not found.
|
||||
*/
|
||||
router.post(
|
||||
"/snippet-folder/share",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.share"),
|
||||
async (req: AuthenticatedRequest, res: Response) => {
|
||||
const userId = req.userId!;
|
||||
const { folder, durationHours } = req.body ?? {};
|
||||
|
||||
if (!isNonEmptyString(folder)) {
|
||||
return res.status(400).json({ error: "Folder name is required" });
|
||||
}
|
||||
|
||||
const targets = parseShareTargets(req.body ?? {});
|
||||
if (!targets) {
|
||||
return res.status(400).json({
|
||||
error:
|
||||
"targets must be a non-empty array of { type: 'user'|'role', id } entries",
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const userRepository = createCurrentUserRepository();
|
||||
const roleRepository = createCurrentRoleRepository();
|
||||
for (const target of targets) {
|
||||
const found =
|
||||
target.type === "user"
|
||||
? await userRepository.findById(target.id as string)
|
||||
: await roleRepository.findRoleById(target.id as number);
|
||||
if (!found) {
|
||||
return res.status(404).json({
|
||||
error: `Target ${target.type} not found`,
|
||||
targetId: target.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const snippetsInFolder =
|
||||
await createCurrentSnippetRepository().listOwnedSnippetsInFolder(
|
||||
userId,
|
||||
folder,
|
||||
);
|
||||
const expiresAt = expiryFromDuration(durationHours);
|
||||
const rbacAccessRepository = createCurrentRbacAccessRepository();
|
||||
|
||||
for (const snippet of snippetsInFolder) {
|
||||
for (const target of targets) {
|
||||
if (target.type === "user" && target.id === userId) continue;
|
||||
await rbacAccessRepository.upsertSnippetAccess({
|
||||
snippetId: snippet.id,
|
||||
grantedBy: userId,
|
||||
expiresAt,
|
||||
...(target.type === "user"
|
||||
? {
|
||||
targetType: "user" as const,
|
||||
targetUserId: target.id as string,
|
||||
}
|
||||
: {
|
||||
targetType: "role" as const,
|
||||
targetRoleId: target.id as number,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
databaseLogger.success("Snippet folder shared successfully", {
|
||||
operation: "rbac_snippet_folder_share",
|
||||
userId,
|
||||
folder,
|
||||
snippetsShared: snippetsInFolder.length,
|
||||
targets: targets.length,
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
expiresAt,
|
||||
snippetsShared: snippetsInFolder.length,
|
||||
});
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to share snippet folder", error, {
|
||||
operation: "share_snippet_folder",
|
||||
folder,
|
||||
userId,
|
||||
});
|
||||
res.status(500).json({ error: "Failed to share snippet folder" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.delete(
|
||||
"/snippet/:id/access/:accessId",
|
||||
authenticateJWT,
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import crypto from "crypto";
|
||||
import express, { type Request, type Response } from "express";
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { PermissionManager } from "../../utils/permission-manager.js";
|
||||
import { authLogger } from "../../utils/logger.js";
|
||||
import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import {
|
||||
logAudit,
|
||||
getAuditUsername,
|
||||
getRequestMeta,
|
||||
} from "../../utils/audit-logger.js";
|
||||
import { testConnectSource } from "../../utils/onepassword-connect.js";
|
||||
import { readSecretSourcePrivateAllowlist } from "../../utils/secret-source-egress.js";
|
||||
import { clearExternalSecretCache } from "../../hosts/external-secrets.js";
|
||||
import { createCurrentSecretSourceRepository } from "../repositories/factory.js";
|
||||
import {
|
||||
toPublicSecretSource,
|
||||
type SecretSourceRecord,
|
||||
} from "../repositories/secret-source-repository.js";
|
||||
|
||||
const router = express.Router();
|
||||
const authManager = AuthManager.getInstance();
|
||||
const authenticateJWT = authManager.createAuthMiddleware();
|
||||
const requireDataAccess = authManager.createDataAccessMiddleware();
|
||||
const permissionManager = PermissionManager.getInstance();
|
||||
|
||||
const KINDS = ["onepassword-connect"] as const;
|
||||
|
||||
function isNonEmptyString(value: unknown): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0;
|
||||
}
|
||||
|
||||
function validBaseUrl(raw: unknown): string | null {
|
||||
if (!isNonEmptyString(raw)) return null;
|
||||
try {
|
||||
const url = new URL(raw.trim());
|
||||
if (!["http:", "https:"].includes(url.protocol)) return null;
|
||||
return url.toString().replace(/\/+$/, "");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadOwned(
|
||||
id: string,
|
||||
userId: string,
|
||||
res: Response,
|
||||
): Promise<SecretSourceRecord | null> {
|
||||
const source = await createCurrentSecretSourceRepository().findById(id);
|
||||
if (!source) {
|
||||
res.status(404).json({ error: "Secret source not found" });
|
||||
return null;
|
||||
}
|
||||
if (source.userId !== userId) {
|
||||
res.status(403).json({ error: "Only the owner can change this source" });
|
||||
return null;
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /secret-sources:
|
||||
* get:
|
||||
* summary: List secret sources visible to the caller (own + shared)
|
||||
* tags:
|
||||
* - Secret Sources
|
||||
*/
|
||||
router.get(
|
||||
"/",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.view"),
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId!;
|
||||
try {
|
||||
const rows =
|
||||
await createCurrentSecretSourceRepository().listVisibleToUser(userId);
|
||||
res.json({
|
||||
sources: rows.map((row) => ({
|
||||
...toPublicSecretSource(row),
|
||||
owned: row.userId === userId,
|
||||
})),
|
||||
});
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to list secret sources", error);
|
||||
res.status(500).json({ error: "Failed to list secret sources" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /secret-sources:
|
||||
* post:
|
||||
* summary: Create a secret source (1Password Connect)
|
||||
* description: Sharing a source with every user requires admin. The token is encrypted with the owner's data key.
|
||||
* tags:
|
||||
* - Secret Sources
|
||||
*/
|
||||
router.post(
|
||||
"/",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.create"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId!;
|
||||
const {
|
||||
name,
|
||||
kind = "onepassword-connect",
|
||||
baseUrl,
|
||||
token,
|
||||
shared,
|
||||
} = req.body ?? {};
|
||||
const url = validBaseUrl(baseUrl);
|
||||
if (!isNonEmptyString(name) || !url || !isNonEmptyString(token)) {
|
||||
return res.status(400).json({
|
||||
error: "name, a valid http(s) baseUrl and token are required",
|
||||
});
|
||||
}
|
||||
if (!KINDS.includes(kind)) {
|
||||
return res.status(400).json({ error: "Unsupported secret source kind" });
|
||||
}
|
||||
if (shared === true && !(await permissionManager.isAdmin(userId))) {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Only admins can share a secret source" });
|
||||
}
|
||||
try {
|
||||
const created = await createCurrentSecretSourceRepository().create({
|
||||
id: crypto.randomUUID(),
|
||||
userId,
|
||||
name: name.trim(),
|
||||
kind,
|
||||
baseUrl: url,
|
||||
token: token.trim(),
|
||||
shared: shared === true,
|
||||
});
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
await logAudit({
|
||||
userId,
|
||||
username: await getAuditUsername(userId),
|
||||
action: "secret_source_create",
|
||||
resourceType: "secret_source",
|
||||
resourceId: created.id,
|
||||
resourceName: created.name,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
success: true,
|
||||
});
|
||||
res.json({ source: { ...toPublicSecretSource(created), owned: true } });
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to create secret source", error);
|
||||
res.status(500).json({ error: "Failed to create secret source" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /secret-sources/{id}:
|
||||
* put:
|
||||
* summary: Update a secret source (owner only; omit token to keep it)
|
||||
* tags:
|
||||
* - Secret Sources
|
||||
*/
|
||||
router.put(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.edit"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId!;
|
||||
const { name, baseUrl, token, shared } = req.body ?? {};
|
||||
try {
|
||||
const source = await loadOwned(String(req.params.id), userId, res);
|
||||
if (!source) return;
|
||||
const url = baseUrl === undefined ? undefined : validBaseUrl(baseUrl);
|
||||
if (baseUrl !== undefined && !url) {
|
||||
return res.status(400).json({ error: "baseUrl must be http(s)" });
|
||||
}
|
||||
if (
|
||||
shared === true &&
|
||||
!source.shared &&
|
||||
!(await permissionManager.isAdmin(userId))
|
||||
) {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Only admins can share a secret source" });
|
||||
}
|
||||
await createCurrentSecretSourceRepository().update(source, {
|
||||
...(isNonEmptyString(name) ? { name: name.trim() } : {}),
|
||||
...(url ? { baseUrl: url } : {}),
|
||||
...(isNonEmptyString(token) ? { token: token.trim() } : {}),
|
||||
...(typeof shared === "boolean" ? { shared } : {}),
|
||||
});
|
||||
clearExternalSecretCache();
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to update secret source", error);
|
||||
res.status(500).json({ error: "Failed to update secret source" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /secret-sources/{id}:
|
||||
* delete:
|
||||
* summary: Delete a secret source (owner only)
|
||||
* tags:
|
||||
* - Secret Sources
|
||||
*/
|
||||
router.delete(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.delete"),
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId!;
|
||||
try {
|
||||
const source = await loadOwned(String(req.params.id), userId, res);
|
||||
if (!source) return;
|
||||
await createCurrentSecretSourceRepository().deleteById(source.id);
|
||||
clearExternalSecretCache();
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
await logAudit({
|
||||
userId,
|
||||
username: await getAuditUsername(userId),
|
||||
action: "secret_source_delete",
|
||||
resourceType: "secret_source",
|
||||
resourceId: source.id,
|
||||
resourceName: source.name,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
success: true,
|
||||
});
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to delete secret source", error);
|
||||
res.status(500).json({ error: "Failed to delete secret source" });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /secret-sources/{id}/test:
|
||||
* post:
|
||||
* summary: Check that the source is reachable and the token is accepted
|
||||
* tags:
|
||||
* - Secret Sources
|
||||
*/
|
||||
router.post(
|
||||
"/:id/test",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("credentials.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId!;
|
||||
try {
|
||||
const repository = createCurrentSecretSourceRepository();
|
||||
const source = await repository.findById(String(req.params.id));
|
||||
if (!source || (source.userId !== userId && !source.shared)) {
|
||||
return res.status(404).json({ error: "Secret source not found" });
|
||||
}
|
||||
const vaults = await testConnectSource({
|
||||
baseUrl: source.baseUrl,
|
||||
token: repository.decryptToken(source),
|
||||
allowedPrivateHosts: await readSecretSourcePrivateAllowlist(),
|
||||
});
|
||||
res.json({ ok: true, vaults });
|
||||
} catch (error) {
|
||||
res.status(200).json({ ok: false, error: getErrorMessage(error) });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -85,7 +85,7 @@ async function pruneOldLogs(): Promise<void> {
|
||||
|
||||
// Run prune once at startup, then every 24 hours
|
||||
pruneOldLogs();
|
||||
setInterval(pruneOldLogs, 24 * 60 * 60 * 1000);
|
||||
setInterval(pruneOldLogs, 24 * 60 * 60 * 1000).unref();
|
||||
|
||||
const authManager = AuthManager.getInstance();
|
||||
const authenticateJWT = authManager.createAuthMiddleware();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import express, { type Request, type Response } from "express";
|
||||
import { authLogger, databaseLogger } from "../../utils/logger.js";
|
||||
import { PermissionManager } from "../../utils/permission-manager.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { SSH_ALGORITHMS } from "../../utils/ssh-algorithms.js";
|
||||
import { extractSnippetReorderUpdates } from "./snippets-reorder.js";
|
||||
@@ -11,8 +12,8 @@ import {
|
||||
resolveSnippetCommand,
|
||||
} from "./snippets-execution.js";
|
||||
import { logAudit, getRequestMeta } from "../../utils/audit-logger.js";
|
||||
import { resolveHostById } from "../../hosts/host-resolver.js";
|
||||
import {
|
||||
createCurrentHostResolutionRepository,
|
||||
createCurrentRbacAccessRepository,
|
||||
createCurrentRoleRepository,
|
||||
createCurrentSnippetRepository,
|
||||
@@ -68,6 +69,7 @@ async function getAccessibleSnippet(snippetId: number, userId: string) {
|
||||
}
|
||||
|
||||
const authManager = AuthManager.getInstance();
|
||||
const permissionManager = PermissionManager.getInstance();
|
||||
const authenticateJWT = authManager.createAuthMiddleware();
|
||||
const requireDataAccess = authManager.createDataAccessMiddleware();
|
||||
|
||||
@@ -90,6 +92,7 @@ const requireDataAccess = authManager.createDataAccessMiddleware();
|
||||
router.get(
|
||||
"/folders",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -144,6 +147,7 @@ router.get(
|
||||
router.post(
|
||||
"/folders",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.create"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -226,6 +230,7 @@ router.post(
|
||||
router.put(
|
||||
"/folders/:name/metadata",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.edit"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -306,6 +311,7 @@ router.put(
|
||||
router.put(
|
||||
"/folders/rename",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.edit"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -382,6 +388,7 @@ router.put(
|
||||
router.delete(
|
||||
"/folders/:name",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.delete"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -466,6 +473,7 @@ router.delete(
|
||||
router.put(
|
||||
"/reorder",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.edit"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -579,32 +587,16 @@ router.post(
|
||||
}
|
||||
|
||||
const { Client } = await import("ssh2");
|
||||
const repository = createCurrentHostResolutionRepository();
|
||||
const host = await repository.findHostById(parseInt(hostId), userId);
|
||||
const host = await resolveHostById(parseInt(hostId), userId);
|
||||
|
||||
if (!host || host.userId !== userId) {
|
||||
if (!host) {
|
||||
return res.status(404).json({ error: "Host not found" });
|
||||
}
|
||||
|
||||
let password = host.password;
|
||||
let privateKey = host.key;
|
||||
let passphrase = host.keyPassword;
|
||||
let authType = host.authType;
|
||||
|
||||
if (host.credentialId) {
|
||||
const cred = await repository.findCredentialByIdForUser(
|
||||
host.credentialId as number,
|
||||
userId,
|
||||
);
|
||||
|
||||
if (cred) {
|
||||
authType = (cred.authType || authType) as string;
|
||||
password = (cred.password || undefined) as string | undefined;
|
||||
privateKey = (cred.privateKey || cred.key || undefined) as
|
||||
string | undefined;
|
||||
passphrase = (cred.keyPassword || undefined) as string | undefined;
|
||||
}
|
||||
}
|
||||
const password = host.password;
|
||||
const privateKey = host.key;
|
||||
const passphrase = host.keyPassword;
|
||||
const authType = host.authType;
|
||||
|
||||
const conn = new Client();
|
||||
let output = "";
|
||||
@@ -796,6 +788,7 @@ router.post(
|
||||
router.get(
|
||||
"/export",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -872,6 +865,7 @@ router.get(
|
||||
router.post(
|
||||
"/bulk-import",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.create"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -932,6 +926,7 @@ router.post(
|
||||
router.get(
|
||||
"/",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -1003,6 +998,7 @@ router.get(
|
||||
router.get(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.view"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -1073,6 +1069,7 @@ router.get(
|
||||
router.post(
|
||||
"/",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.create"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -1183,6 +1180,7 @@ router.post(
|
||||
router.put(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.edit"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
@@ -1261,6 +1259,7 @@ router.put(
|
||||
router.delete(
|
||||
"/:id",
|
||||
authenticateJWT,
|
||||
permissionManager.requirePermission("snippets.delete"),
|
||||
requireDataAccess,
|
||||
async (req: Request, res: Response) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { SyncEntityType } from "../repositories/sync-tombstone-repository.js";
|
||||
|
||||
export type SyncReferenceEntity = "sshCredentials" | "vaultProfiles";
|
||||
export type SyncReferenceEntity = "hosts" | "sshCredentials" | "vaultProfiles";
|
||||
|
||||
interface SyncReference {
|
||||
field: string;
|
||||
@@ -8,12 +8,14 @@ interface SyncReference {
|
||||
entityType: SyncReferenceEntity;
|
||||
}
|
||||
|
||||
const CREDENTIAL_REFERENCE: SyncReference = {
|
||||
field: "credentialId",
|
||||
syncField: "credentialSyncId",
|
||||
entityType: "sshCredentials",
|
||||
};
|
||||
|
||||
const HOST_REFERENCES: SyncReference[] = [
|
||||
{
|
||||
field: "credentialId",
|
||||
syncField: "credentialSyncId",
|
||||
entityType: "sshCredentials",
|
||||
},
|
||||
CREDENTIAL_REFERENCE,
|
||||
{
|
||||
field: "rdpCredentialId",
|
||||
syncField: "rdpCredentialSyncId",
|
||||
@@ -34,11 +36,51 @@ const HOST_REFERENCES: SyncReference[] = [
|
||||
syncField: "vaultProfileSyncId",
|
||||
entityType: "vaultProfiles",
|
||||
},
|
||||
{
|
||||
field: "parentHostId",
|
||||
syncField: "parentHostSyncId",
|
||||
entityType: "hosts",
|
||||
},
|
||||
];
|
||||
|
||||
export function orderSyncRows(
|
||||
entityType: SyncEntityType,
|
||||
rows: Record<string, unknown>[],
|
||||
): Record<string, unknown>[] {
|
||||
if (entityType !== "hosts") return rows;
|
||||
|
||||
const bySyncId = new Map(
|
||||
rows
|
||||
.filter((row) => typeof row.syncId === "string")
|
||||
.map((row) => [row.syncId as string, row]),
|
||||
);
|
||||
const ordered: Record<string, unknown>[] = [];
|
||||
const visited = new Set<Record<string, unknown>>();
|
||||
const visiting = new Set<Record<string, unknown>>();
|
||||
|
||||
const visit = (row: Record<string, unknown>) => {
|
||||
if (visited.has(row)) return;
|
||||
if (visiting.has(row)) return;
|
||||
visiting.add(row);
|
||||
|
||||
const parentSyncId = row.parentHostSyncId;
|
||||
if (typeof parentSyncId === "string") {
|
||||
const parent = bySyncId.get(parentSyncId);
|
||||
if (parent) visit(parent);
|
||||
}
|
||||
|
||||
visiting.delete(row);
|
||||
visited.add(row);
|
||||
ordered.push(row);
|
||||
};
|
||||
|
||||
rows.forEach(visit);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
const REFERENCES: Partial<Record<SyncEntityType, SyncReference[]>> = {
|
||||
hosts: HOST_REFERENCES,
|
||||
sshFolders: [HOST_REFERENCES[0]],
|
||||
sshFolders: [CREDENTIAL_REFERENCE],
|
||||
};
|
||||
|
||||
export async function serializeSyncReferences(
|
||||
|
||||
@@ -23,10 +23,12 @@ import {
|
||||
import type { SyncEntityType } from "../repositories/sync-tombstone-repository.js";
|
||||
import {
|
||||
deserializeSyncReferences,
|
||||
orderSyncRows,
|
||||
serializeSyncReferences,
|
||||
type SyncReferenceEntity,
|
||||
} from "./sync-references.js";
|
||||
import { timestampAtOrAfter } from "../sync-timestamp.js";
|
||||
import { validateParentHostId } from "./host-parent-validation.js";
|
||||
|
||||
const router = express.Router();
|
||||
const authManager = AuthManager.getInstance();
|
||||
@@ -115,6 +117,15 @@ async function findReferenceSyncId(
|
||||
id: number,
|
||||
userId: string,
|
||||
): Promise<string | null> {
|
||||
if (entityType === "hosts") {
|
||||
const [row] = await context.drizzle
|
||||
.select({ syncId: hosts.syncId })
|
||||
.from(hosts)
|
||||
.where(and(eq(hosts.id, id), eq(hosts.userId, userId)))
|
||||
.limit(1);
|
||||
return row?.syncId ?? null;
|
||||
}
|
||||
|
||||
if (entityType === "sshCredentials") {
|
||||
const [row] = await context.drizzle
|
||||
.select({ syncId: sshCredentials.syncId })
|
||||
@@ -138,6 +149,15 @@ async function findReferenceId(
|
||||
syncId: string,
|
||||
userId: string,
|
||||
): Promise<number | null> {
|
||||
if (entityType === "hosts") {
|
||||
const [row] = await context.drizzle
|
||||
.select({ id: hosts.id })
|
||||
.from(hosts)
|
||||
.where(and(eq(hosts.syncId, syncId), eq(hosts.userId, userId)))
|
||||
.limit(1);
|
||||
return row?.id ?? null;
|
||||
}
|
||||
|
||||
if (entityType === "sshCredentials") {
|
||||
const [row] = await context.drizzle
|
||||
.select({ id: sshCredentials.id })
|
||||
@@ -281,7 +301,7 @@ router.get(
|
||||
}),
|
||||
);
|
||||
|
||||
res.json({ rows: decrypted });
|
||||
res.json({ rows: orderSyncRows(entityType, decrypted) });
|
||||
} catch (err) {
|
||||
databaseLogger.error(`Failed to pull sync rows for ${entityType}`, err, {
|
||||
operation: "sync_pull",
|
||||
@@ -409,6 +429,17 @@ router.post(
|
||||
(referenceType, referenceSyncId) =>
|
||||
findReferenceId(context, referenceType, referenceSyncId, userId),
|
||||
);
|
||||
if (
|
||||
entityType === "hosts" &&
|
||||
typeof resolvedPayload.parentHostId === "number"
|
||||
) {
|
||||
const parentError = await validateParentHostId(
|
||||
userId,
|
||||
typeof existing?.id === "number" ? existing.id : null,
|
||||
resolvedPayload.parentHostId,
|
||||
);
|
||||
if (parentError) return res.status(400).json({ error: parentError });
|
||||
}
|
||||
const writePayload = stripWritePayload(entityType, resolvedPayload);
|
||||
const encryptedPayload = encryptIfNeeded(
|
||||
entityType,
|
||||
|
||||
@@ -26,6 +26,7 @@ const pickPreferences = (row?: UserPreferenceRecord | null) => ({
|
||||
hostTrayOnClick: row?.hostTrayOnClick ?? null,
|
||||
pinAppRail: row?.pinAppRail ?? null,
|
||||
expandAppRailOnHover: row?.expandAppRailOnHover ?? null,
|
||||
showPinAppRailButton: row?.showPinAppRailButton ?? null,
|
||||
foldersCollapsed: row?.foldersCollapsed ?? null,
|
||||
confirmSnippetExecution: row?.confirmSnippetExecution ?? null,
|
||||
disableUpdateCheck: row?.disableUpdateCheck ?? null,
|
||||
@@ -105,6 +106,9 @@ export function validateDefaultsJson(value: string): boolean {
|
||||
* expandAppRailOnHover:
|
||||
* type: boolean
|
||||
* nullable: true
|
||||
* showPinAppRailButton:
|
||||
* type: boolean
|
||||
* nullable: true
|
||||
* foldersCollapsed:
|
||||
* type: boolean
|
||||
* nullable: true
|
||||
@@ -186,6 +190,8 @@ router.get("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
* type: boolean
|
||||
* expandAppRailOnHover:
|
||||
* type: boolean
|
||||
* showPinAppRailButton:
|
||||
* type: boolean
|
||||
* confirmSnippetExecution:
|
||||
* type: boolean
|
||||
* disableUpdateCheck:
|
||||
@@ -217,6 +223,7 @@ router.put("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
commandPaletteEnabled,
|
||||
pinAppRail,
|
||||
expandAppRailOnHover,
|
||||
showPinAppRailButton,
|
||||
confirmSnippetExecution,
|
||||
disableUpdateCheck,
|
||||
confirmTabClose,
|
||||
@@ -239,6 +246,7 @@ router.put("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
commandPaletteEnabled?: boolean | null;
|
||||
pinAppRail?: boolean | null;
|
||||
expandAppRailOnHover?: boolean | null;
|
||||
showPinAppRailButton?: boolean | null;
|
||||
confirmSnippetExecution?: boolean | null;
|
||||
disableUpdateCheck?: boolean | null;
|
||||
confirmTabClose?: boolean | null;
|
||||
@@ -384,6 +392,7 @@ router.put("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
commandPaletteEnabled,
|
||||
pinAppRail,
|
||||
expandAppRailOnHover,
|
||||
showPinAppRailButton,
|
||||
confirmSnippetExecution,
|
||||
disableUpdateCheck,
|
||||
confirmTabClose,
|
||||
@@ -413,6 +422,8 @@ router.put("/", authenticateJWT, async (req: Request, res: Response) => {
|
||||
if (pinAppRail !== undefined) updates.pinAppRail = pinAppRail;
|
||||
if (expandAppRailOnHover !== undefined)
|
||||
updates.expandAppRailOnHover = expandAppRailOnHover;
|
||||
if (showPinAppRailButton !== undefined)
|
||||
updates.showPinAppRailButton = showPinAppRailButton;
|
||||
if (confirmSnippetExecution !== undefined)
|
||||
updates.confirmSnippetExecution = confirmSnippetExecution;
|
||||
if (disableUpdateCheck !== undefined)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import type { RequestHandler, Router } from "express";
|
||||
import { restartGuacServer } from "../../hosts/guacamole/guacamole-server.js";
|
||||
import {
|
||||
@@ -7,8 +8,19 @@ import {
|
||||
setGlobalLogLevel,
|
||||
} from "../../utils/logger.js";
|
||||
import { logAudit, getRequestMeta } from "../../utils/audit-logger.js";
|
||||
import {
|
||||
AUDIT_FORWARD_TOKEN_SETTING,
|
||||
AUDIT_FORWARD_URL_ENV,
|
||||
AUDIT_FORWARD_URL_SETTING,
|
||||
} from "../../utils/audit-forwarder.js";
|
||||
import { getTelemetryEnvOverride } from "../../utils/analytics.js";
|
||||
import { AI_PRIVATE_ALLOWLIST_KEY, parseAllowlist } from "../../ai/egress.js";
|
||||
import { STEP_CA_PRIVATE_ALLOWLIST_KEY } from "../../utils/step-ca-egress.js";
|
||||
import { SECRET_SOURCE_PRIVATE_ALLOWLIST_KEY } from "../../utils/secret-source-egress.js";
|
||||
import {
|
||||
NOTIFICATION_PRIVATE_ALLOWLIST_KEY,
|
||||
parseNotificationAllowlist,
|
||||
} from "../../utils/notification-egress.js";
|
||||
import {
|
||||
createCurrentSettingsRepository,
|
||||
createCurrentUserRepository,
|
||||
@@ -35,6 +47,7 @@ export type HostDefaults = {
|
||||
cursorBlink?: boolean;
|
||||
enableSessionLogging?: boolean;
|
||||
enableCommandHistory?: boolean;
|
||||
autoTmux?: boolean;
|
||||
};
|
||||
|
||||
async function getAdminActor(
|
||||
@@ -669,6 +682,125 @@ export function registerUserSettingsRoutes(
|
||||
* enabled:
|
||||
* type: boolean
|
||||
*/
|
||||
/**
|
||||
* @openapi
|
||||
* /users/audit-forwarding:
|
||||
* get:
|
||||
* summary: Get audit log forwarding settings (admin only)
|
||||
* tags:
|
||||
* - Users
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Forwarding target. The token itself is never returned.
|
||||
*/
|
||||
router.get("/audit-forwarding", authenticateJWT, async (req, res) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
try {
|
||||
if (!(await getAdminActor(userId))) {
|
||||
return res.status(403).json({ error: "Not authorized" });
|
||||
}
|
||||
const settingsRepository = createCurrentSettingsRepository();
|
||||
const url =
|
||||
(await settingsRepository.get(AUDIT_FORWARD_URL_SETTING)) ?? "";
|
||||
const hasToken = !!(await settingsRepository.get(
|
||||
AUDIT_FORWARD_TOKEN_SETTING,
|
||||
));
|
||||
res.json({
|
||||
url,
|
||||
hasToken,
|
||||
envConfigured: !!process.env[AUDIT_FORWARD_URL_ENV]?.trim(),
|
||||
});
|
||||
} catch (err) {
|
||||
authLogger.error("Failed to get audit forwarding settings", err);
|
||||
res
|
||||
.status(500)
|
||||
.json({ error: "Failed to get audit forwarding settings" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/audit-forwarding:
|
||||
* patch:
|
||||
* summary: Update audit log forwarding settings (admin only)
|
||||
* description: Sets the collector URL audit entries are shipped to. An empty URL disables forwarding and clears the stored token. Omitting token keeps the stored one.
|
||||
* tags:
|
||||
* - Users
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* url:
|
||||
* type: string
|
||||
* token:
|
||||
* type: string
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Setting updated.
|
||||
* 403:
|
||||
* description: Not authorized.
|
||||
*/
|
||||
router.patch("/audit-forwarding", authenticateJWT, async (req, res) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
try {
|
||||
const actor = await getAdminActor(userId);
|
||||
if (!actor) {
|
||||
return res.status(403).json({ error: "Not authorized" });
|
||||
}
|
||||
const { url, token } = req.body ?? {};
|
||||
if (
|
||||
typeof url !== "string" ||
|
||||
(token !== undefined && typeof token !== "string")
|
||||
) {
|
||||
return res.status(400).json({ error: "url must be a string" });
|
||||
}
|
||||
const trimmedUrl = url.trim();
|
||||
if (trimmedUrl && !/^https?:\/\//i.test(trimmedUrl)) {
|
||||
return res.status(400).json({ error: "url must be http(s)" });
|
||||
}
|
||||
|
||||
const settingsRepository = createCurrentSettingsRepository();
|
||||
if (!trimmedUrl) {
|
||||
await settingsRepository.delete(AUDIT_FORWARD_URL_SETTING);
|
||||
await settingsRepository.delete(AUDIT_FORWARD_TOKEN_SETTING);
|
||||
} else {
|
||||
await settingsRepository.set(AUDIT_FORWARD_URL_SETTING, trimmedUrl);
|
||||
if (token !== undefined) {
|
||||
if (token.trim()) {
|
||||
await settingsRepository.set(
|
||||
AUDIT_FORWARD_TOKEN_SETTING,
|
||||
token.trim(),
|
||||
);
|
||||
} else {
|
||||
await settingsRepository.delete(AUDIT_FORWARD_TOKEN_SETTING);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
await logAudit({
|
||||
userId,
|
||||
username: actor.username ?? userId,
|
||||
action: "update_audit_forwarding",
|
||||
resourceType: "setting",
|
||||
details: JSON.stringify({ enabled: !!trimmedUrl }),
|
||||
ipAddress,
|
||||
userAgent,
|
||||
success: true,
|
||||
});
|
||||
|
||||
res.json({ url: trimmedUrl, hasToken: !!token?.trim() });
|
||||
} catch (err) {
|
||||
authLogger.error("Failed to update audit forwarding settings", err);
|
||||
res
|
||||
.status(500)
|
||||
.json({ error: "Failed to update audit forwarding settings" });
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/session-sharing-enabled", authenticateJWT, async (_req, res) => {
|
||||
try {
|
||||
res.json({
|
||||
@@ -954,6 +1086,250 @@ export function registerUserSettingsRoutes(
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET/PATCH a comma-list of private hosts an outbound feature may reach.
|
||||
* Shared by notifications and Step CA; each keeps its own setting key.
|
||||
*/
|
||||
const registerPrivateEndpointAllowlist = (
|
||||
path: string,
|
||||
settingKey: string,
|
||||
auditAction: string,
|
||||
label: string,
|
||||
) => {
|
||||
router.get(path, authenticateJWT, async (req, res) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
try {
|
||||
if (!(await getAdminActor(userId))) {
|
||||
return res.status(403).json({ error: "Not authorized" });
|
||||
}
|
||||
const raw = await createCurrentSettingsRepository().get(settingKey);
|
||||
res.json({ hosts: parseNotificationAllowlist(raw) });
|
||||
} catch (err) {
|
||||
authLogger.error(`Failed to get ${label} allowlist`, err);
|
||||
res.status(500).json({ error: "Failed to get the allowlist" });
|
||||
}
|
||||
});
|
||||
|
||||
router.patch(path, authenticateJWT, async (req, res) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
try {
|
||||
const actor = await getAdminActor(userId);
|
||||
if (!actor) {
|
||||
return res.status(403).json({ error: "Not authorized" });
|
||||
}
|
||||
|
||||
const { hosts } = req.body;
|
||||
if (!Array.isArray(hosts)) {
|
||||
return res.status(400).json({ error: "hosts must be an array" });
|
||||
}
|
||||
if (hosts.length > 50) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "At most 50 hosts are allowed" });
|
||||
}
|
||||
const cleaned: string[] = [];
|
||||
for (const entry of hosts) {
|
||||
if (typeof entry !== "string") {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "Each host must be a string" });
|
||||
}
|
||||
const host = entry.trim().toLowerCase();
|
||||
if (!host) continue;
|
||||
if (!/^[a-z0-9._:-]+$/.test(host)) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: `${entry} is not a valid hostname` });
|
||||
}
|
||||
if (!cleaned.includes(host)) cleaned.push(host);
|
||||
}
|
||||
|
||||
await createCurrentSettingsRepository().set(
|
||||
settingKey,
|
||||
JSON.stringify(cleaned),
|
||||
);
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
await logAudit({
|
||||
userId,
|
||||
username: actor.username ?? userId,
|
||||
action: auditAction,
|
||||
resourceType: "setting",
|
||||
details: JSON.stringify({ hosts: cleaned }),
|
||||
ipAddress,
|
||||
userAgent,
|
||||
success: true,
|
||||
});
|
||||
res.json({ hosts: cleaned });
|
||||
} catch (err) {
|
||||
authLogger.error(`Failed to update ${label} allowlist`, err);
|
||||
res.status(500).json({ error: "Failed to update the allowlist" });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/notification-private-endpoints:
|
||||
* get:
|
||||
* summary: Get the private hosts notification channels may contact (admin only)
|
||||
* tags:
|
||||
* - Users
|
||||
* patch:
|
||||
* summary: Replace that allowlist (admin only)
|
||||
* tags:
|
||||
* - Users
|
||||
*/
|
||||
registerPrivateEndpointAllowlist(
|
||||
"/notification-private-endpoints",
|
||||
NOTIFICATION_PRIVATE_ALLOWLIST_KEY,
|
||||
"update_notification_private_endpoints",
|
||||
"notification endpoint",
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/step-ca-private-endpoints:
|
||||
* get:
|
||||
* summary: Get the private hosts the Step CA certificate flow may contact (admin only)
|
||||
* tags:
|
||||
* - Users
|
||||
* patch:
|
||||
* summary: Replace that allowlist (admin only)
|
||||
* tags:
|
||||
* - Users
|
||||
*/
|
||||
registerPrivateEndpointAllowlist(
|
||||
"/step-ca-private-endpoints",
|
||||
STEP_CA_PRIVATE_ALLOWLIST_KEY,
|
||||
"update_step_ca_private_endpoints",
|
||||
"Step CA endpoint",
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/secret-source-private-endpoints:
|
||||
* get:
|
||||
* summary: Get the private hosts secret sources (1Password Connect) may contact (admin only)
|
||||
* tags:
|
||||
* - Users
|
||||
* patch:
|
||||
* summary: Replace that allowlist (admin only)
|
||||
* tags:
|
||||
* - Users
|
||||
*/
|
||||
registerPrivateEndpointAllowlist(
|
||||
"/secret-source-private-endpoints",
|
||||
SECRET_SOURCE_PRIVATE_ALLOWLIST_KEY,
|
||||
"update_secret_source_private_endpoints",
|
||||
"secret source endpoint",
|
||||
);
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/step-ca-settings:
|
||||
* get:
|
||||
* summary: Step CA settings. Admins get the values; everyone else only whether it is configured.
|
||||
* tags:
|
||||
* - Users
|
||||
* patch:
|
||||
* summary: Set the Step CA URL, root fingerprint and OIDC provisioner (admin only). Empty values clear the configuration.
|
||||
* tags:
|
||||
* - Users
|
||||
*/
|
||||
router.get("/step-ca-settings", authenticateJWT, async (req, res) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
try {
|
||||
const { readStepCaSettings } =
|
||||
await import("../../hosts/step-ca-auth.js");
|
||||
const settings = await readStepCaSettings();
|
||||
if (!(await getAdminActor(userId))) {
|
||||
return res.json({ configured: settings !== null });
|
||||
}
|
||||
res.json({
|
||||
configured: settings !== null,
|
||||
caUrl: settings?.caUrl ?? "",
|
||||
fingerprint: settings?.fingerprint ?? "",
|
||||
provisioner: settings?.provisioner ?? "",
|
||||
});
|
||||
} catch (err) {
|
||||
authLogger.error("Failed to get Step CA settings", err);
|
||||
res.status(500).json({ error: "Failed to get Step CA settings" });
|
||||
}
|
||||
});
|
||||
|
||||
router.patch("/step-ca-settings", authenticateJWT, async (req, res) => {
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
try {
|
||||
const actor = await getAdminActor(userId);
|
||||
if (!actor) {
|
||||
return res.status(403).json({ error: "Not authorized" });
|
||||
}
|
||||
const { caUrl, fingerprint, provisioner } = req.body ?? {};
|
||||
if (
|
||||
[caUrl, fingerprint, provisioner].some((v) => typeof v !== "string")
|
||||
) {
|
||||
return res.status(400).json({
|
||||
error: "caUrl, fingerprint and provisioner must be strings",
|
||||
});
|
||||
}
|
||||
const values = {
|
||||
caUrl: caUrl.trim(),
|
||||
fingerprint: fingerprint.trim(),
|
||||
provisioner: provisioner.trim(),
|
||||
};
|
||||
const clearing =
|
||||
!values.caUrl && !values.fingerprint && !values.provisioner;
|
||||
if (!clearing) {
|
||||
const { normalizeCaUrl, normalizeFingerprint } =
|
||||
await import("../../utils/step-ca-client.js");
|
||||
try {
|
||||
values.caUrl = normalizeCaUrl(values.caUrl);
|
||||
values.fingerprint = normalizeFingerprint(values.fingerprint);
|
||||
} catch (err) {
|
||||
return res.status(400).json({ error: getErrorMessage(err) });
|
||||
}
|
||||
if (!values.provisioner) {
|
||||
return res.status(400).json({ error: "provisioner is required" });
|
||||
}
|
||||
}
|
||||
|
||||
const { STEP_CA_SETTING_KEYS } =
|
||||
await import("../../hosts/step-ca-auth.js");
|
||||
const settings = createCurrentSettingsRepository();
|
||||
if (clearing) {
|
||||
await settings.delete(STEP_CA_SETTING_KEYS.url);
|
||||
await settings.delete(STEP_CA_SETTING_KEYS.fingerprint);
|
||||
await settings.delete(STEP_CA_SETTING_KEYS.provisioner);
|
||||
} else {
|
||||
await settings.set(STEP_CA_SETTING_KEYS.url, values.caUrl);
|
||||
await settings.set(
|
||||
STEP_CA_SETTING_KEYS.fingerprint,
|
||||
values.fingerprint,
|
||||
);
|
||||
await settings.set(
|
||||
STEP_CA_SETTING_KEYS.provisioner,
|
||||
values.provisioner,
|
||||
);
|
||||
}
|
||||
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
await logAudit({
|
||||
userId,
|
||||
username: actor.username ?? userId,
|
||||
action: "update_step_ca_settings",
|
||||
resourceType: "setting",
|
||||
details: JSON.stringify({ configured: !clearing, caUrl: values.caUrl }),
|
||||
ipAddress,
|
||||
userAgent,
|
||||
success: true,
|
||||
});
|
||||
res.json({ configured: !clearing, ...values });
|
||||
} catch (err) {
|
||||
authLogger.error("Failed to update Step CA settings", err);
|
||||
res.status(500).json({ error: "Failed to update Step CA settings" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /users/host-defaults:
|
||||
|
||||
@@ -130,7 +130,54 @@ export function registerUserTotpRoutes(
|
||||
}
|
||||
|
||||
if (userRecord.totpEnabled) {
|
||||
return res.status(400).json({ error: "TOTP is already enabled" });
|
||||
const credential = req.body?.credential;
|
||||
if (!credential) {
|
||||
return res.status(400).json({
|
||||
error: "A TOTP code or password is required",
|
||||
});
|
||||
}
|
||||
|
||||
const userDataKey = authManager.getUserDataKey(userId);
|
||||
let verified = await verifyTotpReauth(
|
||||
userRecord,
|
||||
credential,
|
||||
userDataKey,
|
||||
);
|
||||
if (!verified && !userRecord.isOidc && userRecord.passwordHash) {
|
||||
verified = await bcrypt.compare(credential, userRecord.passwordHash);
|
||||
}
|
||||
if (!verified) {
|
||||
return res.status(401).json({
|
||||
error: "Incorrect password or invalid TOTP code",
|
||||
});
|
||||
}
|
||||
|
||||
const existingSecret = userDataKey
|
||||
? LazyFieldEncryption.safeGetFieldValue(
|
||||
userRecord.totpSecret,
|
||||
userDataKey,
|
||||
userId,
|
||||
"totpSecret",
|
||||
)
|
||||
: userRecord.totpSecret;
|
||||
if (!existingSecret) {
|
||||
return res.status(409).json({ error: "TOTP secret is unavailable" });
|
||||
}
|
||||
|
||||
const otpauthUrl = speakeasy.otpauthURL({
|
||||
secret: existingSecret,
|
||||
label: `Termix (${userRecord.username})`,
|
||||
encoding: "base32",
|
||||
});
|
||||
authLogger.info("Additional TOTP authenticator enrollment started", {
|
||||
operation: "totp_add_authenticator",
|
||||
userId,
|
||||
});
|
||||
return res.json({
|
||||
secret: existingSecret,
|
||||
qr_code: await QRCode.toDataURL(otpauthUrl),
|
||||
additional: true,
|
||||
});
|
||||
}
|
||||
|
||||
const secret = speakeasy.generateSecret({
|
||||
|
||||
@@ -400,12 +400,12 @@ export function registerUserWebAuthnRoutes(
|
||||
* /users/webauthn/authenticate/verify:
|
||||
* post:
|
||||
* summary: Finish passkey login
|
||||
* description: Verifies the WebAuthn assertion and issues a session token (or a TOTP challenge).
|
||||
* description: Verifies the WebAuthn assertion and issues a session token. Verified WebAuthn user verification satisfies 2FA; possession-only keys retain the configured TOTP challenge.
|
||||
* tags:
|
||||
* - WebAuthn
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Login succeeded or TOTP verification required.
|
||||
* description: Login succeeded.
|
||||
* 400:
|
||||
* description: Challenge expired or invalid response.
|
||||
* 401:
|
||||
@@ -488,7 +488,10 @@ export function registerUserWebAuthnRoutes(
|
||||
},
|
||||
);
|
||||
|
||||
if (userRecord.totpEnabled) {
|
||||
if (
|
||||
userRecord.totpEnabled &&
|
||||
verification.authenticationInfo.userVerified !== true
|
||||
) {
|
||||
const deviceFingerprint = generateDeviceFingerprint(
|
||||
deviceInfo,
|
||||
getDeviceId(req),
|
||||
|
||||
@@ -22,6 +22,7 @@ import { deleteUserAndRelatedData } from "./delete-user-data.js";
|
||||
import {
|
||||
isLoopbackRequest,
|
||||
extractBearerOrCookieToken,
|
||||
isNativeTokenExportRequest,
|
||||
resolveDesktopAutoSessionUser,
|
||||
} from "./desktop-auto-session.js";
|
||||
import { shouldShowDonationModal } from "./donation-modal-utils.js";
|
||||
@@ -41,6 +42,7 @@ import {
|
||||
} from "./user-oidc-utils.js";
|
||||
import { registerUserApiKeyRoutes } from "./user-api-key-routes.js";
|
||||
import { registerUserImageStorageRoutes } from "./user-image-storage-routes.js";
|
||||
import { registerBrandingRoutes } from "./branding-routes.js";
|
||||
import { registerUserSettingsRoutes } from "./user-settings-routes.js";
|
||||
import { registerTouchInputSettingsRoutes } from "./touch-input-settings-routes.js";
|
||||
import { registerAcmeSSLRoutes } from "./acme-ssl-routes.js";
|
||||
@@ -54,7 +56,7 @@ import { registerUserDataAccessRoutes } from "./user-data-access-routes.js";
|
||||
import { registerSSOProviderRoutes } from "./sso-provider-routes.js";
|
||||
import { registerLDAPAuthRoutes } from "./ldap-auth-routes.js";
|
||||
import { logAudit, getRequestMeta } from "../../utils/audit-logger.js";
|
||||
import { notifyAutomationInternalEvent } from "../../hosts/metrics/automation-bridge.js";
|
||||
import { notifyAutomationInternalEvent } from "../../hosts/automation-events.js";
|
||||
import {
|
||||
createCurrentSettingsRepository,
|
||||
getCurrentSettingValue,
|
||||
@@ -91,6 +93,11 @@ async function syncSharedCredentialsForUserRoles(
|
||||
const { SharedHostSecretsManager } =
|
||||
await import("../../utils/shared-host-secrets-manager.js");
|
||||
await SharedHostSecretsManager.getInstance().snapshotForUserRoles(userId);
|
||||
const { SharedCredentialSecretsManager } =
|
||||
await import("../../utils/shared-credential-secrets-manager.js");
|
||||
await SharedCredentialSecretsManager.getInstance().snapshotForUserRoles(
|
||||
userId,
|
||||
);
|
||||
} catch (error) {
|
||||
authLogger.warn("Failed to sync role shared host secrets", {
|
||||
operation,
|
||||
@@ -2168,7 +2175,7 @@ router.post(
|
||||
* /users/me/token:
|
||||
* get:
|
||||
* summary: Get current session token
|
||||
* description: Returns the JWT for the currently authenticated session. Intended for mobile WebView clients that cannot read HTTP-only cookies.
|
||||
* description: Returns the JWT for the currently authenticated native Mobile or Desktop client. Browser sessions cannot export their HTTP-only cookie.
|
||||
* tags:
|
||||
* - Users
|
||||
* responses:
|
||||
@@ -2183,8 +2190,16 @@ router.post(
|
||||
* type: string
|
||||
* 401:
|
||||
* description: Not authenticated.
|
||||
* 403:
|
||||
* description: Token export is not available to browser clients.
|
||||
*/
|
||||
router.get("/me/token", authenticateJWT, (req: Request, res: Response) => {
|
||||
if (!isNativeTokenExportRequest(req)) {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ error: "Token export is limited to native clients" });
|
||||
}
|
||||
|
||||
// authenticateJWT accepts either the jwt cookie or an Authorization:
|
||||
// Bearer header (see auth-manager.ts's createAuthMiddleware) -- this must
|
||||
// check both too, or a request that only carried the header (e.g. the
|
||||
@@ -2971,7 +2986,21 @@ router.delete("/delete-user", authenticateJWT, async (req, res) => {
|
||||
|
||||
const targetUserId = targetUser.id;
|
||||
|
||||
await deleteUserAndRelatedData(targetUserId);
|
||||
// Inherit rather than drop: the deleting admin takes over the hosts and
|
||||
// credentials unless another successor is named; "none" discards them.
|
||||
const { successorUserId: requestedSuccessor } = req.body ?? {};
|
||||
let successorUserId: string | undefined = userId;
|
||||
if (requestedSuccessor === "none") {
|
||||
successorUserId = undefined;
|
||||
} else if (isNonEmptyString(requestedSuccessor)) {
|
||||
const successor = await userRepository.findById(requestedSuccessor);
|
||||
if (!successor || successor.id === targetUserId) {
|
||||
return res.status(400).json({ error: "Invalid successor user" });
|
||||
}
|
||||
successorUserId = successor.id;
|
||||
}
|
||||
|
||||
await deleteUserAndRelatedData(targetUserId, { successorUserId });
|
||||
|
||||
authLogger.warn("User account deleted by admin", {
|
||||
operation: "admin_delete_user",
|
||||
@@ -3033,6 +3062,7 @@ registerAcmeSSLRoutes(router, authenticateJWT);
|
||||
|
||||
registerUserApiKeyRoutes(router, requireAdmin);
|
||||
registerUserImageStorageRoutes(router, requireAdmin);
|
||||
registerBrandingRoutes(router, requireAdmin);
|
||||
|
||||
registerSSOProviderRoutes(router);
|
||||
registerLDAPAuthRoutes(router);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { WebSocket } from "ws";
|
||||
import { resolveExternalSecretRefs } from "./external-secrets.js";
|
||||
import { sshLogger, authLogger } from "../utils/logger.js";
|
||||
import { createCurrentHostResolutionRepository } from "../database/repositories/factory.js";
|
||||
interface ResolvedCredentials {
|
||||
@@ -63,6 +64,11 @@ export class SSHAuthManager {
|
||||
);
|
||||
|
||||
if (cred) {
|
||||
// Credentials may hold secret references instead of secrets.
|
||||
await resolveExternalSecretRefs(
|
||||
cred as unknown as Record<string, unknown>,
|
||||
this.context.userId,
|
||||
);
|
||||
resolvedCredentials = {
|
||||
username: (cred.username as string) || hostConfig.username,
|
||||
password: (cred.password as string) || undefined,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* One-line hand-off from any hosts feature to the automations engine for a
|
||||
* generic named event (not tied to metrics polling).
|
||||
*
|
||||
* Fire-and-forget and imported lazily: a failure in the automations layer
|
||||
* must never disturb the caller, and a static import would create a cycle
|
||||
* (automations reads repositories, which several hosts modules also pull in).
|
||||
*
|
||||
* PLUGIN-EVENT: this whole module is the "publish an internal event" half of
|
||||
* the phase-2 ctx.events bus. Once that exists, callers should emit onto
|
||||
* ctx.events instead of calling this directly, and the automations engine
|
||||
* subscribes there rather than being imported ad hoc.
|
||||
*/
|
||||
|
||||
export function notifyAutomationInternalEvent(
|
||||
event: string,
|
||||
userId: string,
|
||||
hostId?: number,
|
||||
details?: Record<string, unknown>,
|
||||
): void {
|
||||
if (!userId) return;
|
||||
import("../automations/triggers.js")
|
||||
.then((triggers) =>
|
||||
triggers.onInternalEvent({ event, userId, hostId, details }),
|
||||
)
|
||||
.catch(() => {});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Duplex } from "node:stream";
|
||||
import type { RawData, WebSocket } from "ws";
|
||||
|
||||
export function waitForWebSocketOpen(
|
||||
socket: WebSocket,
|
||||
timeoutMs: number,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
socket.off("open", onOpen);
|
||||
socket.off("error", onError);
|
||||
};
|
||||
const onOpen = () => {
|
||||
cleanup();
|
||||
resolve();
|
||||
};
|
||||
const onError = (error: Error) => {
|
||||
cleanup();
|
||||
socket.terminate();
|
||||
reject(error);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
socket.terminate();
|
||||
reject(new Error("Cloudflare tunnel timeout"));
|
||||
}, timeoutMs);
|
||||
|
||||
socket.once("open", onOpen);
|
||||
socket.once("error", onError);
|
||||
});
|
||||
}
|
||||
|
||||
export function createWebSocketDuplex(socket: WebSocket): Duplex {
|
||||
const duplex = new Duplex({
|
||||
read() {},
|
||||
write(chunk, _encoding, callback) {
|
||||
try {
|
||||
socket.send(chunk, (error) => callback(error || undefined));
|
||||
} catch (error) {
|
||||
callback(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
},
|
||||
destroy(error, callback) {
|
||||
cleanup();
|
||||
socket.terminate();
|
||||
callback(error);
|
||||
},
|
||||
});
|
||||
|
||||
const onMessage = (data: RawData) => duplex.push(data);
|
||||
const onClose = () => duplex.destroy();
|
||||
const onError = () => duplex.destroy();
|
||||
const cleanup = () => {
|
||||
socket.off("message", onMessage);
|
||||
socket.off("close", onClose);
|
||||
socket.off("error", onError);
|
||||
};
|
||||
|
||||
socket.on("message", onMessage);
|
||||
socket.on("close", onClose);
|
||||
socket.on("error", onError);
|
||||
return duplex;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
const WINDOW_MS = 60_000;
|
||||
const MAX_ATTEMPTS = 60;
|
||||
const attempts = new Map<string, { count: number; windowStart: number }>();
|
||||
|
||||
export function isCollabGuestRateLimited(ip: string): boolean {
|
||||
const now = Date.now();
|
||||
const entry = attempts.get(ip);
|
||||
if (!entry || now - entry.windowStart > WINDOW_MS) {
|
||||
attempts.set(ip, { count: 1, windowStart: now });
|
||||
return false;
|
||||
}
|
||||
entry.count += 1;
|
||||
return entry.count > MAX_ATTEMPTS;
|
||||
}
|
||||
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [ip, entry] of attempts) {
|
||||
if (now - entry.windowStart > WINDOW_MS) attempts.delete(ip);
|
||||
}
|
||||
}, 5 * WINDOW_MS).unref();
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { WebSocket } from "ws";
|
||||
import { collabRuntimeStore } from "./runtime-store.js";
|
||||
|
||||
const PRESENCE_HEARTBEAT_MS = 15_000;
|
||||
|
||||
export interface CollabRoomClient {
|
||||
ws: WebSocket;
|
||||
userId: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Local WebSocket fan-out plus optional Redis pub/sub for multi-instance room
|
||||
* events and presence. The terminal WS server feeds subscribe/unsubscribe.
|
||||
*/
|
||||
class CollabRoomHub {
|
||||
private rooms = new Map<string, Set<CollabRoomClient>>();
|
||||
|
||||
constructor() {
|
||||
collabRuntimeStore.onEvent((roomId, message) => {
|
||||
if (
|
||||
"type" in message &&
|
||||
typeof message.type === "string" &&
|
||||
message.type.startsWith("collab_internal_")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.broadcastLocal(roomId, message);
|
||||
});
|
||||
setInterval(() => {
|
||||
for (const roomId of this.rooms.keys()) void this.refreshPresence(roomId);
|
||||
}, PRESENCE_HEARTBEAT_MS).unref();
|
||||
}
|
||||
|
||||
subscribe(roomId: string, client: CollabRoomClient): void {
|
||||
let clients = this.rooms.get(roomId);
|
||||
if (!clients) {
|
||||
clients = new Set();
|
||||
this.rooms.set(roomId, clients);
|
||||
}
|
||||
for (const existing of clients) {
|
||||
if (existing.ws === client.ws) return;
|
||||
}
|
||||
clients.add(client);
|
||||
void this.refreshPresence(roomId);
|
||||
}
|
||||
|
||||
/** Drops the socket from one room, or from every room when roomId is omitted. */
|
||||
unsubscribe(ws: WebSocket, roomId?: string): void {
|
||||
for (const [id, clients] of this.rooms) {
|
||||
if (roomId && id !== roomId) continue;
|
||||
let removed = false;
|
||||
for (const client of clients) {
|
||||
if (client.ws === ws) {
|
||||
clients.delete(client);
|
||||
removed = true;
|
||||
}
|
||||
}
|
||||
if (clients.size === 0) this.rooms.delete(id);
|
||||
if (removed) void this.refreshPresence(id);
|
||||
}
|
||||
}
|
||||
|
||||
broadcast(roomId: string, message: object): void {
|
||||
this.broadcastLocal(roomId, message);
|
||||
void collabRuntimeStore.publish(roomId, message);
|
||||
}
|
||||
|
||||
async onlineUsers(
|
||||
roomId: string,
|
||||
): Promise<Array<{ userId: string; username: string }>> {
|
||||
return collabRuntimeStore.onlineUsers(
|
||||
roomId,
|
||||
this.localOnlineUsers(roomId),
|
||||
);
|
||||
}
|
||||
|
||||
private broadcastLocal(roomId: string, message: object): void {
|
||||
const clients = this.rooms.get(roomId);
|
||||
if (!clients) return;
|
||||
const payload = JSON.stringify(message);
|
||||
for (const client of clients) {
|
||||
if (client.ws.readyState !== client.ws.OPEN) continue;
|
||||
try {
|
||||
client.ws.send(payload);
|
||||
} catch {
|
||||
/* keep broadcasting to the rest */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private localOnlineUsers(
|
||||
roomId: string,
|
||||
): Array<{ userId: string; username: string }> {
|
||||
const clients = this.rooms.get(roomId);
|
||||
if (!clients) return [];
|
||||
const seen = new Map<string, string>();
|
||||
for (const client of clients) {
|
||||
seen.set(client.userId, client.username);
|
||||
}
|
||||
return Array.from(seen, ([userId, username]) => ({ userId, username }));
|
||||
}
|
||||
|
||||
private async refreshPresence(roomId: string): Promise<void> {
|
||||
const localUsers = this.localOnlineUsers(roomId);
|
||||
await collabRuntimeStore.updatePresence(roomId, localUsers);
|
||||
this.broadcast(roomId, {
|
||||
type: "collab_online",
|
||||
roomId,
|
||||
users: await this.onlineUsers(roomId),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const collabRoomHub = new CollabRoomHub();
|
||||
@@ -0,0 +1,16 @@
|
||||
import { createCurrentCollabRoomRepository } from "../../database/repositories/factory.js";
|
||||
|
||||
/**
|
||||
* Whether a user may join a room-stage share: the share must be the stage of
|
||||
* a live room they are a member of. Membership is the authorization - room
|
||||
* stages are read-only and never expose host credentials or config.
|
||||
*/
|
||||
export async function canJoinRoomStageShare(
|
||||
shareId: string,
|
||||
userId: string,
|
||||
): Promise<boolean> {
|
||||
const repository = createCurrentCollabRoomRepository();
|
||||
const room = await repository.findByStageShareId(shareId);
|
||||
if (!room) return false;
|
||||
return !!(await repository.findMember(room.id, userId));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,286 @@
|
||||
import crypto from "crypto";
|
||||
import { createClient } from "redis";
|
||||
import { sshLogger } from "../../utils/logger.js";
|
||||
|
||||
export interface CollabControlRequest {
|
||||
userId: string;
|
||||
username: string;
|
||||
requestedAt: string;
|
||||
}
|
||||
|
||||
interface PresenceEntry {
|
||||
instanceId: string;
|
||||
userId: string;
|
||||
username: string;
|
||||
}
|
||||
|
||||
interface EventEnvelope {
|
||||
source: string;
|
||||
roomId: string;
|
||||
message: object;
|
||||
}
|
||||
|
||||
const KEY_PREFIX = process.env.TERMIX_REDIS_PREFIX?.trim() || "termix:collab";
|
||||
const EVENT_CHANNEL = `${KEY_PREFIX}:events`;
|
||||
const PRESENCE_TTL_MS = 45_000;
|
||||
const STATE_TTL_SECONDS = 12 * 60 * 60;
|
||||
const CONNECT_RETRY_MS = 15_000;
|
||||
|
||||
export class CollabRuntimeStore {
|
||||
private readonly instanceId = crypto.randomUUID();
|
||||
private publisher: ReturnType<typeof createClient> | null = null;
|
||||
private subscriber: ReturnType<typeof createClient> | null = null;
|
||||
private connecting: Promise<boolean> | null = null;
|
||||
private nextConnectAttempt = 0;
|
||||
private eventListeners = new Set<(roomId: string, message: object) => void>();
|
||||
private localControllers = new Map<string, string>();
|
||||
private localRequests = new Map<string, Map<string, CollabControlRequest>>();
|
||||
private presenceMembers = new Map<string, Set<string>>();
|
||||
|
||||
onEvent(listener: (roomId: string, message: object) => void): void {
|
||||
this.eventListeners.add(listener);
|
||||
void this.ensureConnected();
|
||||
}
|
||||
|
||||
async publish(roomId: string, message: object): Promise<void> {
|
||||
if (!(await this.ensureConnected()) || !this.publisher) return;
|
||||
await this.publisher
|
||||
.publish(
|
||||
EVENT_CHANNEL,
|
||||
JSON.stringify({ source: this.instanceId, roomId, message }),
|
||||
)
|
||||
.catch((error) => this.logRedisFailure("publish", error));
|
||||
}
|
||||
|
||||
async getController(roomId: string): Promise<string | null> {
|
||||
if (await this.ensureConnected()) {
|
||||
const value = await this.publisher
|
||||
?.get(`${KEY_PREFIX}:controller:${roomId}`)
|
||||
.catch((error) => {
|
||||
this.logRedisFailure("get_controller", error);
|
||||
return undefined;
|
||||
});
|
||||
if (value !== undefined) return value;
|
||||
}
|
||||
return this.localControllers.get(roomId) ?? null;
|
||||
}
|
||||
|
||||
async setController(roomId: string, userId: string | null): Promise<void> {
|
||||
if (userId) this.localControllers.set(roomId, userId);
|
||||
else this.localControllers.delete(roomId);
|
||||
if (!(await this.ensureConnected()) || !this.publisher) return;
|
||||
const key = `${KEY_PREFIX}:controller:${roomId}`;
|
||||
const operation = userId
|
||||
? this.publisher.set(key, userId, { EX: STATE_TTL_SECONDS })
|
||||
: this.publisher.del(key);
|
||||
await operation.catch((error) =>
|
||||
this.logRedisFailure("set_controller", error),
|
||||
);
|
||||
}
|
||||
|
||||
async listRequests(roomId: string): Promise<CollabControlRequest[]> {
|
||||
if (await this.ensureConnected()) {
|
||||
const values = await this.publisher
|
||||
?.hVals(`${KEY_PREFIX}:requests:${roomId}`)
|
||||
.catch((error) => {
|
||||
this.logRedisFailure("list_requests", error);
|
||||
return null;
|
||||
});
|
||||
if (values) {
|
||||
return values
|
||||
.flatMap((value) => this.parse<CollabControlRequest>(value) ?? [])
|
||||
.sort((a, b) => a.requestedAt.localeCompare(b.requestedAt));
|
||||
}
|
||||
}
|
||||
return Array.from(this.localRequests.get(roomId)?.values() ?? []).sort(
|
||||
(a, b) => a.requestedAt.localeCompare(b.requestedAt),
|
||||
);
|
||||
}
|
||||
|
||||
async upsertRequest(
|
||||
roomId: string,
|
||||
request: CollabControlRequest,
|
||||
): Promise<void> {
|
||||
let requests = this.localRequests.get(roomId);
|
||||
if (!requests) {
|
||||
requests = new Map();
|
||||
this.localRequests.set(roomId, requests);
|
||||
}
|
||||
requests.set(request.userId, request);
|
||||
if (!(await this.ensureConnected()) || !this.publisher) return;
|
||||
const key = `${KEY_PREFIX}:requests:${roomId}`;
|
||||
await this.publisher
|
||||
.multi()
|
||||
.hSet(key, request.userId, JSON.stringify(request))
|
||||
.expire(key, STATE_TTL_SECONDS)
|
||||
.exec()
|
||||
.catch((error) => this.logRedisFailure("upsert_request", error));
|
||||
}
|
||||
|
||||
async removeRequest(roomId: string, userId: string): Promise<void> {
|
||||
const requests = this.localRequests.get(roomId);
|
||||
requests?.delete(userId);
|
||||
if (requests?.size === 0) this.localRequests.delete(roomId);
|
||||
if (!(await this.ensureConnected()) || !this.publisher) return;
|
||||
await this.publisher
|
||||
.hDel(`${KEY_PREFIX}:requests:${roomId}`, userId)
|
||||
.catch((error) => this.logRedisFailure("remove_request", error));
|
||||
}
|
||||
|
||||
async clearRequests(roomId: string): Promise<void> {
|
||||
this.localRequests.delete(roomId);
|
||||
if (!(await this.ensureConnected()) || !this.publisher) return;
|
||||
await this.publisher
|
||||
.del(`${KEY_PREFIX}:requests:${roomId}`)
|
||||
.catch((error) => this.logRedisFailure("clear_requests", error));
|
||||
}
|
||||
|
||||
async updatePresence(
|
||||
roomId: string,
|
||||
users: Array<{ userId: string; username: string }>,
|
||||
): Promise<void> {
|
||||
if (!(await this.ensureConnected()) || !this.publisher) return;
|
||||
const key = `${KEY_PREFIX}:presence:${roomId}`;
|
||||
const previous = this.presenceMembers.get(roomId) ?? new Set<string>();
|
||||
const expiresAt = Date.now() + PRESENCE_TTL_MS;
|
||||
const current = new Set(
|
||||
users.map((user) =>
|
||||
JSON.stringify({
|
||||
instanceId: this.instanceId,
|
||||
...user,
|
||||
} satisfies PresenceEntry),
|
||||
),
|
||||
);
|
||||
const transaction = this.publisher.multi();
|
||||
if (previous.size > 0) transaction.zRem(key, Array.from(previous));
|
||||
for (const member of current) {
|
||||
transaction.zAdd(key, { score: expiresAt, value: member });
|
||||
}
|
||||
transaction.expire(key, Math.ceil(PRESENCE_TTL_MS / 1000) * 2);
|
||||
await transaction
|
||||
.exec()
|
||||
.then(() => {
|
||||
if (current.size > 0) this.presenceMembers.set(roomId, current);
|
||||
else this.presenceMembers.delete(roomId);
|
||||
})
|
||||
.catch((error) => this.logRedisFailure("update_presence", error));
|
||||
}
|
||||
|
||||
async onlineUsers(
|
||||
roomId: string,
|
||||
localUsers: Array<{ userId: string; username: string }>,
|
||||
): Promise<Array<{ userId: string; username: string }>> {
|
||||
if (!(await this.ensureConnected()) || !this.publisher) return localUsers;
|
||||
const key = `${KEY_PREFIX}:presence:${roomId}`;
|
||||
const now = Date.now();
|
||||
const transaction = this.publisher
|
||||
.multi()
|
||||
.zRemRangeByScore(key, 0, now)
|
||||
.zRangeByScore(key, now + 1, "+inf");
|
||||
const result = await transaction.exec().catch((error) => {
|
||||
this.logRedisFailure("online_users", error);
|
||||
return null;
|
||||
});
|
||||
const members = result?.[1] as string[] | undefined;
|
||||
if (!members) return localUsers;
|
||||
const seen = new Map<string, string>();
|
||||
for (const member of members) {
|
||||
const entry = this.parse<PresenceEntry>(member);
|
||||
if (entry) seen.set(entry.userId, entry.username);
|
||||
}
|
||||
return Array.from(seen, ([userId, username]) => ({ userId, username }));
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
await Promise.allSettled([
|
||||
this.publisher?.isOpen ? this.publisher.quit() : Promise.resolve(),
|
||||
this.subscriber?.isOpen ? this.subscriber.quit() : Promise.resolve(),
|
||||
]);
|
||||
this.publisher = null;
|
||||
this.subscriber = null;
|
||||
}
|
||||
|
||||
private async ensureConnected(): Promise<boolean> {
|
||||
const url = process.env.REDIS_URL?.trim();
|
||||
if (!url) return false;
|
||||
if (this.publisher?.isReady && this.subscriber?.isReady) return true;
|
||||
if (Date.now() < this.nextConnectAttempt) return false;
|
||||
if (this.connecting) return this.connecting;
|
||||
this.connecting = this.connect(url).finally(() => {
|
||||
this.connecting = null;
|
||||
});
|
||||
return this.connecting;
|
||||
}
|
||||
|
||||
private async connect(url: string): Promise<boolean> {
|
||||
try {
|
||||
this.publisher = createClient({
|
||||
url,
|
||||
socket: { connectTimeout: 1500, reconnectStrategy: false },
|
||||
});
|
||||
this.subscriber = this.publisher.duplicate();
|
||||
this.publisher.on("error", (error) =>
|
||||
this.logRedisFailure("client", error),
|
||||
);
|
||||
this.subscriber.on("error", (error) =>
|
||||
this.logRedisFailure("subscriber", error),
|
||||
);
|
||||
await Promise.all([this.publisher.connect(), this.subscriber.connect()]);
|
||||
await this.subscriber.subscribe(EVENT_CHANNEL, (raw) => {
|
||||
const envelope = this.parse<EventEnvelope>(raw);
|
||||
if (
|
||||
!envelope ||
|
||||
typeof envelope.source !== "string" ||
|
||||
typeof envelope.roomId !== "string" ||
|
||||
!envelope.message ||
|
||||
typeof envelope.message !== "object" ||
|
||||
envelope.source === this.instanceId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
for (const listener of this.eventListeners) {
|
||||
try {
|
||||
listener(envelope.roomId, envelope.message);
|
||||
} catch (error) {
|
||||
this.logRedisFailure("event_listener", error);
|
||||
}
|
||||
}
|
||||
});
|
||||
sshLogger.info("Collaboration Redis runtime connected", {
|
||||
operation: "collab_redis_connected",
|
||||
});
|
||||
this.nextConnectAttempt = 0;
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.nextConnectAttempt = Date.now() + CONNECT_RETRY_MS;
|
||||
this.logRedisFailure("connect", error);
|
||||
await Promise.allSettled([
|
||||
this.publisher?.disconnect(),
|
||||
this.subscriber?.disconnect(),
|
||||
]);
|
||||
this.publisher = null;
|
||||
this.subscriber = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private parse<T>(value: string): T | null {
|
||||
try {
|
||||
return JSON.parse(value) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private logRedisFailure(operation: string, error: unknown): void {
|
||||
sshLogger.warn(
|
||||
"Collaboration Redis runtime unavailable; using local state",
|
||||
{
|
||||
operation: `collab_redis_${operation}`,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const collabRuntimeStore = new CollabRuntimeStore();
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Who besides the presenter may drive the current stage, per room.
|
||||
*
|
||||
* Redis-backed when REDIS_URL is configured, with a local fallback for
|
||||
* single-instance deployments. Every stage switch clears it.
|
||||
*/
|
||||
import { collabRuntimeStore } from "./runtime-store.js";
|
||||
|
||||
export function getStageController(roomId: string): Promise<string | null> {
|
||||
return collabRuntimeStore.getController(roomId);
|
||||
}
|
||||
|
||||
export function setStageController(
|
||||
roomId: string,
|
||||
userId: string | null,
|
||||
): Promise<void> {
|
||||
return collabRuntimeStore.setController(roomId, userId);
|
||||
}
|
||||
@@ -18,7 +18,15 @@ import {
|
||||
hostAddressMismatch,
|
||||
HOST_ADDRESS_MISMATCH_MESSAGE,
|
||||
HOST_NOT_ON_THIS_SERVER_MESSAGE,
|
||||
} from "../terminal/host-identity.js";
|
||||
} from "../host-identity.js";
|
||||
import { extractWebSocketToken } from "../../utils/ws-auth.js";
|
||||
import {
|
||||
asObject,
|
||||
asString,
|
||||
MAX_WS_MESSAGE_BYTES,
|
||||
parseWsMessage,
|
||||
toTerminalDimension,
|
||||
} from "../../utils/ws-message.js";
|
||||
|
||||
const sshLogger = systemLogger;
|
||||
|
||||
@@ -35,8 +43,9 @@ interface SSHSession {
|
||||
const activeSessions = new Map<string, SSHSession>();
|
||||
|
||||
const wss = new WebSocketServer({
|
||||
host: "0.0.0.0",
|
||||
host: "127.0.0.1",
|
||||
port: 30009,
|
||||
maxPayload: MAX_WS_MESSAGE_BYTES,
|
||||
});
|
||||
|
||||
wss.on("error", (error) => {
|
||||
@@ -285,26 +294,7 @@ async function createJumpHostChain(
|
||||
}
|
||||
|
||||
wss.on("connection", async (ws: WebSocket, req) => {
|
||||
let token: string | undefined;
|
||||
|
||||
const cookieHeader = req.headers.cookie;
|
||||
if (cookieHeader) {
|
||||
const match = cookieHeader.match(/(?:^|;\s*)jwt=([^;]+)/);
|
||||
if (match) token = decodeURIComponent(match[1]);
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (authHeader?.startsWith("Bearer ")) {
|
||||
token = authHeader.slice("Bearer ".length);
|
||||
}
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
const urlObj = new URL(req.url || "", "http://localhost");
|
||||
const qp = urlObj.searchParams.get("token");
|
||||
if (qp) token = qp;
|
||||
}
|
||||
const token = extractWebSocketToken(req);
|
||||
|
||||
if (!token) {
|
||||
ws.close(1008, "Authentication required");
|
||||
@@ -312,7 +302,17 @@ wss.on("connection", async (ws: WebSocket, req) => {
|
||||
}
|
||||
|
||||
const authManagerInstance = AuthManager.getInstance();
|
||||
const payload = await authManagerInstance.verifyJWTToken(token);
|
||||
let payload;
|
||||
try {
|
||||
payload = await authManagerInstance.verifyJWTToken(token);
|
||||
} catch (error) {
|
||||
sshLogger.warn("Docker console JWT verification failed", {
|
||||
operation: "docker_console_auth_error",
|
||||
error: getErrorMessage(error),
|
||||
});
|
||||
ws.close(1008, "Authentication required");
|
||||
return;
|
||||
}
|
||||
if (!payload?.userId || payload.pendingTOTP) {
|
||||
ws.close(1008, "Authentication required");
|
||||
return;
|
||||
@@ -334,20 +334,29 @@ wss.on("connection", async (ws: WebSocket, req) => {
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
const cleanup = () => {
|
||||
clearInterval(wsPingInterval);
|
||||
if (!sshSession) return;
|
||||
sshSession.stream?.end();
|
||||
sshSession.client.end();
|
||||
activeSessions.delete(sessionId);
|
||||
sshSession = null;
|
||||
};
|
||||
|
||||
ws.on("message", async (data) => {
|
||||
try {
|
||||
const message = JSON.parse(data.toString());
|
||||
const message = parseWsMessage(data);
|
||||
|
||||
switch (message.type) {
|
||||
case "connect": {
|
||||
const { hostConfig, containerId, shell, cols, rows } =
|
||||
message.data as {
|
||||
hostConfig: SSHHost;
|
||||
containerId: string;
|
||||
shell?: string;
|
||||
cols?: number;
|
||||
rows?: number;
|
||||
};
|
||||
const connectData = asObject(message.data);
|
||||
const hostConfig = asObject(
|
||||
connectData.hostConfig,
|
||||
) as unknown as SSHHost;
|
||||
const containerId = asString(connectData.containerId);
|
||||
const shell = asString(connectData.shell) || undefined;
|
||||
const cols = toTerminalDimension(connectData.cols) || 80;
|
||||
const rows = toTerminalDimension(connectData.rows) || 24;
|
||||
|
||||
const hostId = hostConfig?.id;
|
||||
|
||||
@@ -613,8 +622,8 @@ wss.on("connection", async (ws: WebSocket, req) => {
|
||||
{
|
||||
pty: {
|
||||
term: "xterm-256color",
|
||||
cols: cols || 80,
|
||||
rows: rows || 24,
|
||||
cols,
|
||||
rows,
|
||||
},
|
||||
},
|
||||
(err, stream) => {
|
||||
@@ -712,7 +721,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
|
||||
sshLogger.error("Failed to connect to container", error, {
|
||||
operation: "console_connect",
|
||||
sessionId,
|
||||
containerId: message.data.containerId,
|
||||
containerId,
|
||||
});
|
||||
|
||||
ws.send(
|
||||
@@ -730,15 +739,19 @@ wss.on("connection", async (ws: WebSocket, req) => {
|
||||
|
||||
case "input": {
|
||||
if (sshSession && sshSession.stream) {
|
||||
sshSession.stream.write(message.data);
|
||||
const input = asString(message.data);
|
||||
if (input) sshSession.stream.write(input);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "resize": {
|
||||
if (sshSession && sshSession.stream) {
|
||||
const { cols, rows } = message.data;
|
||||
sshSession.stream.setWindow(rows, cols, rows, cols);
|
||||
const dimensions = asObject(message.data);
|
||||
const cols = toTerminalDimension(dimensions.cols);
|
||||
const rows = toTerminalDimension(dimensions.rows);
|
||||
if (cols && rows)
|
||||
sshSession.stream.setWindow(rows, cols, rows, cols);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -790,7 +803,6 @@ wss.on("connection", async (ws: WebSocket, req) => {
|
||||
});
|
||||
|
||||
ws.on("close", () => {
|
||||
clearInterval(wsPingInterval);
|
||||
sshLogger.info("Docker console disconnected", {
|
||||
operation: "docker_console_disconnect",
|
||||
sessionId,
|
||||
@@ -798,13 +810,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
|
||||
hostId: sshSession?.hostId,
|
||||
containerId: sshSession?.containerId,
|
||||
});
|
||||
if (sshSession) {
|
||||
if (sshSession.stream) {
|
||||
sshSession.stream.end();
|
||||
}
|
||||
sshSession.client.end();
|
||||
activeSessions.delete(sessionId);
|
||||
}
|
||||
cleanup();
|
||||
});
|
||||
|
||||
ws.on("error", (error) => {
|
||||
@@ -813,13 +819,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
|
||||
sessionId,
|
||||
});
|
||||
|
||||
if (sshSession) {
|
||||
if (sshSession.stream) {
|
||||
sshSession.stream.end();
|
||||
}
|
||||
sshSession.client.end();
|
||||
activeSessions.delete(sessionId);
|
||||
}
|
||||
cleanup();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -16,15 +16,19 @@ import {
|
||||
getRequestUserId,
|
||||
registerDockerSshRoutes,
|
||||
} from "./routes.js";
|
||||
import { listenOnServicePort } from "../../utils/service-listen.js";
|
||||
|
||||
const sshLogger = logger;
|
||||
|
||||
const app = express();
|
||||
app.set("trust proxy", "loopback");
|
||||
|
||||
app.use(createCompressionMiddleware());
|
||||
app.use(createCorsMiddleware(["GET", "POST", "PUT", "DELETE", "OPTIONS"]));
|
||||
|
||||
app.use(cookieParser());
|
||||
const authManager = AuthManager.getInstance();
|
||||
app.use(authManager.createAuthMiddleware());
|
||||
app.use(express.json({ limit: "100mb" }));
|
||||
app.use(express.urlencoded({ limit: "100mb", extended: true }));
|
||||
app.use((_req, res, next) => {
|
||||
@@ -32,9 +36,6 @@ app.use((_req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
const authManager = AuthManager.getInstance();
|
||||
app.use(authManager.createAuthMiddleware());
|
||||
|
||||
registerDockerSshRoutes(app);
|
||||
|
||||
registerDockerContainerRoutes(app, {
|
||||
@@ -47,14 +48,20 @@ registerDockerContainerRoutes(app, {
|
||||
|
||||
const PORT = 30007;
|
||||
|
||||
app.listen(PORT, async () => {
|
||||
try {
|
||||
await authManager.initialize();
|
||||
} catch (err) {
|
||||
sshLogger.error("Failed to initialize Docker backend", err, {
|
||||
operation: "startup",
|
||||
});
|
||||
}
|
||||
listenOnServicePort({
|
||||
app,
|
||||
port: PORT,
|
||||
logger: sshLogger,
|
||||
serviceName: "docker",
|
||||
onListening: async () => {
|
||||
try {
|
||||
await authManager.initialize();
|
||||
} catch (err) {
|
||||
sshLogger.error("Failed to initialize Docker backend", err, {
|
||||
operation: "startup",
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import { usesIssuedCertificate } from "../issued-certificate-auth.js";
|
||||
import express from "express";
|
||||
import axios from "axios";
|
||||
import { Client as SSHClient } from "ssh2";
|
||||
@@ -300,7 +301,7 @@ export function registerDockerSshRoutes(app: express.Express): void {
|
||||
if (resolvedCredentials.password) {
|
||||
config.password = resolvedCredentials.password;
|
||||
}
|
||||
} else if (resolvedCredentials.authType === "opkssh") {
|
||||
} else if (usesIssuedCertificate(resolvedCredentials.authType)) {
|
||||
try {
|
||||
const { getOPKSSHToken } = await import("../opkssh-auth.js");
|
||||
const token = await getOPKSSHToken(userId, hostId);
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { createCurrentSecretSourceRepository } from "../database/repositories/factory.js";
|
||||
import type { SecretSourceRecord } from "../database/repositories/secret-source-repository.js";
|
||||
import {
|
||||
isSecretReference,
|
||||
parseSecretReference,
|
||||
resolveConnectReference,
|
||||
} from "../utils/onepassword-connect.js";
|
||||
import { readSecretSourcePrivateAllowlist } from "../utils/secret-source-egress.js";
|
||||
|
||||
/**
|
||||
* Expands "op://vault/item/field" references in a resolved host's secret
|
||||
* fields into the actual secrets, fetched from the user's secret source.
|
||||
*
|
||||
* Runs once per host resolution, at the single point where every subsystem
|
||||
* gets its plaintext credentials - so terminal, SFTP, Docker, metrics and
|
||||
* tunnels all see real secrets without knowing references exist.
|
||||
*
|
||||
* Host resolution is hot (status polls, fleets), so resolved values are
|
||||
* cached briefly in memory; a rotated secret shows up within CACHE_TTL_MS.
|
||||
*/
|
||||
|
||||
export const SECRET_FIELDS = [
|
||||
"password",
|
||||
"key",
|
||||
"keyPassword",
|
||||
"sudoPassword",
|
||||
"socks5Password",
|
||||
"rdpPassword",
|
||||
"vncPassword",
|
||||
"telnetPassword",
|
||||
] as const;
|
||||
|
||||
const CACHE_TTL_MS = 60_000;
|
||||
const cache = new Map<string, { value: string; expiresAt: number }>();
|
||||
|
||||
/** Test seam. */
|
||||
export function clearExternalSecretCache(): void {
|
||||
cache.clear();
|
||||
}
|
||||
|
||||
export type SecretResolver = (
|
||||
source: SecretSourceRecord,
|
||||
reference: string,
|
||||
) => Promise<string>;
|
||||
|
||||
async function defaultResolver(
|
||||
source: SecretSourceRecord,
|
||||
reference: string,
|
||||
): Promise<string> {
|
||||
const ref = parseSecretReference(reference);
|
||||
if (!ref) throw new Error(`Invalid secret reference: ${reference}`);
|
||||
const repository = createCurrentSecretSourceRepository();
|
||||
return resolveConnectReference(
|
||||
{
|
||||
baseUrl: source.baseUrl,
|
||||
token: repository.decryptToken(source),
|
||||
allowedPrivateHosts: await readSecretSourcePrivateAllowlist(),
|
||||
},
|
||||
ref,
|
||||
);
|
||||
}
|
||||
|
||||
/** The user's own source first, else a shared one. */
|
||||
export async function pickSecretSource(
|
||||
userId: string,
|
||||
): Promise<SecretSourceRecord | null> {
|
||||
const sources =
|
||||
await createCurrentSecretSourceRepository().listVisibleToUser(userId);
|
||||
return (
|
||||
sources.find((source) => source.userId === userId) ?? sources[0] ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export async function resolveSecretReference(
|
||||
userId: string,
|
||||
reference: string,
|
||||
deps: {
|
||||
resolver?: SecretResolver;
|
||||
pickSource?: (userId: string) => Promise<SecretSourceRecord | null>;
|
||||
now?: () => number;
|
||||
} = {},
|
||||
): Promise<string> {
|
||||
const now = deps.now ?? Date.now;
|
||||
const source = await (deps.pickSource ?? pickSecretSource)(userId);
|
||||
if (!source) {
|
||||
throw new Error(
|
||||
"This host uses a secret reference but no secret source is configured",
|
||||
);
|
||||
}
|
||||
const cacheKey = `${source.id}:${reference.trim()}`;
|
||||
const cached = cache.get(cacheKey);
|
||||
if (cached && cached.expiresAt > now()) return cached.value;
|
||||
|
||||
const value = await (deps.resolver ?? defaultResolver)(source, reference);
|
||||
cache.set(cacheKey, { value, expiresAt: now() + CACHE_TTL_MS });
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Replaces every reference in the host's secret fields, in place. */
|
||||
export async function resolveExternalSecretRefs(
|
||||
host: Record<string, unknown>,
|
||||
userId: string,
|
||||
deps?: Parameters<typeof resolveSecretReference>[2],
|
||||
): Promise<void> {
|
||||
for (const field of SECRET_FIELDS) {
|
||||
const value = host[field];
|
||||
if (!isSecretReference(value)) continue;
|
||||
host[field] = await resolveSecretReference(userId, value, deps);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import Busboy from "busboy";
|
||||
import type { AuthenticatedRequest } from "../../../types/index.js";
|
||||
import { fileLogger } from "../../utils/logger.js";
|
||||
import {
|
||||
execBuffer,
|
||||
execChannel,
|
||||
execWithSudo,
|
||||
execWithSudoBuffer,
|
||||
@@ -64,7 +65,7 @@ export function registerFileContentRoutes(
|
||||
app.get("/ssh/file_manager/ssh/identifySymlink", (req, res) => {
|
||||
const sessionId = req.query.sessionId as string;
|
||||
const sshConn = sshSessions[sessionId];
|
||||
const linkPath = decodeURIComponent(req.query.path as string);
|
||||
const linkPath = req.query.path as string;
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
if (!sessionId) {
|
||||
@@ -165,7 +166,7 @@ export function registerFileContentRoutes(
|
||||
app.get("/ssh/file_manager/ssh/resolvePath", (req, res) => {
|
||||
const sessionId = req.query.sessionId as string;
|
||||
const sshConn = sshSessions[sessionId];
|
||||
const rawPath = decodeURIComponent(req.query.path as string);
|
||||
const rawPath = req.query.path as string;
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
if (!sessionId) {
|
||||
@@ -262,10 +263,10 @@ export function registerFileContentRoutes(
|
||||
* 500:
|
||||
* description: Failed to read file.
|
||||
*/
|
||||
app.get("/ssh/file_manager/ssh/readFile", (req, res) => {
|
||||
app.get("/ssh/file_manager/ssh/readFile", async (req, res) => {
|
||||
const sessionId = req.query.sessionId as string;
|
||||
const sshConn = sshSessions[sessionId];
|
||||
const filePath = decodeURIComponent(req.query.path as string);
|
||||
const filePath = req.query.path as string;
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
if (!sessionId) {
|
||||
@@ -295,166 +296,133 @@ export function registerFileContentRoutes(
|
||||
const MAX_READ_SIZE = 500 * 1024 * 1024;
|
||||
const escapedPath = filePath.replace(/'/g, "'\"'\"'");
|
||||
|
||||
execChannel(
|
||||
sshConn,
|
||||
`stat -c%s '${escapedPath}' 2>/dev/null || wc -c < '${escapedPath}'`,
|
||||
(sizeErr, sizeStream) => {
|
||||
if (sizeErr) {
|
||||
fileLogger.error("SSH file size check error:", sizeErr);
|
||||
return res.status(500).json({ error: sizeErr.message });
|
||||
}
|
||||
const isPermissionDenied = (message: string) =>
|
||||
message.toLowerCase().includes("permission denied");
|
||||
const isFileNotFound = (message: string) => {
|
||||
const lower = message.toLowerCase();
|
||||
return (
|
||||
lower.includes("no such file or directory") ||
|
||||
lower.includes("cannot access") ||
|
||||
lower.includes("not found") ||
|
||||
lower.includes("resource not found")
|
||||
);
|
||||
};
|
||||
|
||||
let sizeData = "";
|
||||
let sizeErrorData = "";
|
||||
try {
|
||||
let sizeResult = await execBuffer(
|
||||
sshConn,
|
||||
`stat -c%s '${escapedPath}' 2>/dev/null || wc -c < '${escapedPath}'`,
|
||||
);
|
||||
let sizeError = sizeResult.stderr || sizeResult.stdout.toString("utf8");
|
||||
|
||||
sizeStream.on("data", (chunk: Buffer) => {
|
||||
sizeData += chunk.toString();
|
||||
if (
|
||||
sizeResult.code !== 0 &&
|
||||
isPermissionDenied(sizeError) &&
|
||||
sshConn.sudoPassword
|
||||
) {
|
||||
sizeResult = await execWithSudoBuffer(
|
||||
sshConn,
|
||||
`stat -c%s '${escapedPath}'`,
|
||||
sshConn.sudoPassword,
|
||||
);
|
||||
sizeError = sizeResult.stderr || sizeResult.stdout.toString("utf8");
|
||||
}
|
||||
|
||||
if (sizeResult.code !== 0) {
|
||||
const missing = isFileNotFound(sizeError);
|
||||
const permissionDenied = isPermissionDenied(sizeError);
|
||||
fileLogger.error(`File size check failed: ${sizeError}`);
|
||||
return res.status(missing ? 404 : permissionDenied ? 403 : 500).json({
|
||||
error: `Cannot check file size: ${sizeError}`,
|
||||
fileNotFound: missing,
|
||||
needsSudo: permissionDenied,
|
||||
});
|
||||
}
|
||||
|
||||
sizeStream.stderr.on("data", (chunk: Buffer) => {
|
||||
sizeErrorData += chunk.toString();
|
||||
const fileSize = parseInt(sizeResult.stdout.toString("utf8").trim(), 10);
|
||||
if (isNaN(fileSize)) {
|
||||
fileLogger.error("Invalid file size response:", sizeResult.stdout);
|
||||
return res.status(500).json({ error: "Cannot determine file size" });
|
||||
}
|
||||
|
||||
if (fileSize > MAX_READ_SIZE) {
|
||||
fileLogger.warn("File too large for reading", {
|
||||
operation: "file_read",
|
||||
sessionId,
|
||||
filePath,
|
||||
fileSize,
|
||||
maxSize: MAX_READ_SIZE,
|
||||
});
|
||||
|
||||
sizeStream.on("close", (sizeCode) => {
|
||||
if (sizeCode !== 0) {
|
||||
const errorLower = sizeErrorData.toLowerCase();
|
||||
const isFileNotFound =
|
||||
errorLower.includes("no such file or directory") ||
|
||||
errorLower.includes("cannot access") ||
|
||||
errorLower.includes("not found") ||
|
||||
errorLower.includes("resource not found");
|
||||
|
||||
fileLogger.error(`File size check failed: ${sizeErrorData}`);
|
||||
return res.status(isFileNotFound ? 404 : 500).json({
|
||||
error: `Cannot check file size: ${sizeErrorData}`,
|
||||
fileNotFound: isFileNotFound,
|
||||
});
|
||||
}
|
||||
|
||||
const fileSize = parseInt(sizeData.trim(), 10);
|
||||
|
||||
if (isNaN(fileSize)) {
|
||||
fileLogger.error("Invalid file size response:", sizeData);
|
||||
return res
|
||||
.status(500)
|
||||
.json({ error: "Cannot determine file size" });
|
||||
}
|
||||
|
||||
if (fileSize > MAX_READ_SIZE) {
|
||||
fileLogger.warn("File too large for reading", {
|
||||
operation: "file_read",
|
||||
sessionId,
|
||||
filePath,
|
||||
fileSize,
|
||||
maxSize: MAX_READ_SIZE,
|
||||
});
|
||||
return res.status(400).json({
|
||||
error: `File too large to open in editor. Maximum size is ${MAX_READ_SIZE / 1024 / 1024}MB, file is ${(fileSize / 1024 / 1024).toFixed(2)}MB. Use download instead.`,
|
||||
fileSize,
|
||||
maxSize: MAX_READ_SIZE,
|
||||
tooLarge: true,
|
||||
});
|
||||
}
|
||||
|
||||
execChannel(sshConn, `cat '${escapedPath}'`, (err, stream) => {
|
||||
if (err) {
|
||||
fileLogger.error("SSH readFile error:", err);
|
||||
return res.status(500).json({ error: err.message });
|
||||
}
|
||||
|
||||
let binaryData = Buffer.alloc(0);
|
||||
let errorData = "";
|
||||
|
||||
stream.on("data", (chunk: Buffer) => {
|
||||
binaryData = Buffer.concat([binaryData, chunk]);
|
||||
});
|
||||
|
||||
stream.stderr.on("data", (chunk: Buffer) => {
|
||||
errorData += chunk.toString();
|
||||
});
|
||||
|
||||
stream.on("close", (code) => {
|
||||
if (code !== 0) {
|
||||
const isPermissionDenied = errorData
|
||||
.toLowerCase()
|
||||
.includes("permission denied");
|
||||
|
||||
if (isPermissionDenied && sshConn.sudoPassword) {
|
||||
execWithSudoBuffer(
|
||||
sshConn,
|
||||
`cat '${escapedPath}'`,
|
||||
sshConn.sudoPassword,
|
||||
)
|
||||
.then((result) => {
|
||||
if (result.code !== 0) {
|
||||
return res.status(403).json({
|
||||
error: `Permission denied: ${result.stderr || result.stdout.toString("utf8")}`,
|
||||
needsSudo: true,
|
||||
});
|
||||
}
|
||||
|
||||
const sudoData = result.stdout;
|
||||
const isBinary = detectBinary(sudoData);
|
||||
res.json({
|
||||
content: isBinary
|
||||
? sudoData.toString("base64")
|
||||
: sudoData.toString("utf8"),
|
||||
isBinary,
|
||||
size: sudoData.length,
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
res
|
||||
.status(403)
|
||||
.json({ error: "Permission denied", needsSudo: true });
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
fileLogger.error(
|
||||
`SSH readFile command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
|
||||
);
|
||||
|
||||
const isFileNotFound =
|
||||
errorData.includes("No such file or directory") ||
|
||||
errorData.includes("cannot access") ||
|
||||
errorData.includes("not found");
|
||||
|
||||
return res.status(isFileNotFound ? 404 : 500).json({
|
||||
error: `Command failed: ${errorData}`,
|
||||
fileNotFound: isFileNotFound,
|
||||
});
|
||||
}
|
||||
|
||||
const isBinary = detectBinary(binaryData);
|
||||
fileLogger.success("File read successfully", {
|
||||
operation: "file_read_success",
|
||||
sessionId,
|
||||
userId,
|
||||
path: filePath,
|
||||
bytes: binaryData.length,
|
||||
});
|
||||
|
||||
if (isBinary) {
|
||||
const base64Content = binaryData.toString("base64");
|
||||
res.json({
|
||||
content: base64Content,
|
||||
path: filePath,
|
||||
encoding: "base64",
|
||||
});
|
||||
} else {
|
||||
const textContent = binaryData.toString("utf8");
|
||||
res.json({
|
||||
content: textContent,
|
||||
path: filePath,
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
return res.status(400).json({
|
||||
error: `File too large to open in editor. Maximum size is ${MAX_READ_SIZE / 1024 / 1024}MB, file is ${(fileSize / 1024 / 1024).toFixed(2)}MB. Use download instead.`,
|
||||
fileSize,
|
||||
maxSize: MAX_READ_SIZE,
|
||||
tooLarge: true,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let contentResult = await execBuffer(
|
||||
sshConn,
|
||||
`cat '${escapedPath}'`,
|
||||
MAX_READ_SIZE,
|
||||
);
|
||||
let contentError =
|
||||
contentResult.stderr || contentResult.stdout.toString("utf8");
|
||||
|
||||
if (
|
||||
contentResult.code !== 0 &&
|
||||
isPermissionDenied(contentError) &&
|
||||
sshConn.sudoPassword
|
||||
) {
|
||||
contentResult = await execWithSudoBuffer(
|
||||
sshConn,
|
||||
`cat '${escapedPath}'`,
|
||||
sshConn.sudoPassword,
|
||||
MAX_READ_SIZE,
|
||||
);
|
||||
contentError =
|
||||
contentResult.stderr || contentResult.stdout.toString("utf8");
|
||||
}
|
||||
|
||||
if (contentResult.exceededLimit) {
|
||||
return res.status(400).json({
|
||||
error: `File grew beyond the ${MAX_READ_SIZE / 1024 / 1024}MB read limit`,
|
||||
maxSize: MAX_READ_SIZE,
|
||||
tooLarge: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (contentResult.code !== 0) {
|
||||
const missing = isFileNotFound(contentError);
|
||||
const permissionDenied = isPermissionDenied(contentError);
|
||||
fileLogger.error(
|
||||
`SSH readFile command failed with code ${contentResult.code}: ${contentError.replace(/\n/g, " ").trim()}`,
|
||||
);
|
||||
return res.status(missing ? 404 : permissionDenied ? 403 : 500).json({
|
||||
error: `Command failed: ${contentError}`,
|
||||
fileNotFound: missing,
|
||||
needsSudo: permissionDenied,
|
||||
});
|
||||
}
|
||||
|
||||
const isBinary = detectBinary(contentResult.stdout);
|
||||
fileLogger.success("File read successfully", {
|
||||
operation: "file_read_success",
|
||||
sessionId,
|
||||
userId,
|
||||
path: filePath,
|
||||
bytes: contentResult.stdout.length,
|
||||
});
|
||||
return res.json({
|
||||
content: contentResult.stdout.toString(isBinary ? "base64" : "utf8"),
|
||||
path: filePath,
|
||||
encoding: isBinary ? "base64" : "utf8",
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
fileLogger.error("SSH readFile error:", error);
|
||||
return res.status(500).json({ error: message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -1369,6 +1337,20 @@ export function registerFileContentRoutes(
|
||||
let fileName: string | undefined;
|
||||
let uploadStartTime: number;
|
||||
let resolved = false;
|
||||
let requestAborted = false;
|
||||
let cleanupStarted = false;
|
||||
let destroyUpload: (() => void) | undefined;
|
||||
|
||||
const abortUpload = () => {
|
||||
if (req.complete || cleanupStarted) return;
|
||||
requestAborted = true;
|
||||
cleanupStarted = true;
|
||||
destroyUpload?.();
|
||||
};
|
||||
|
||||
req.once("aborted", abortUpload);
|
||||
req.once("error", abortUpload);
|
||||
req.once("close", abortUpload);
|
||||
|
||||
const bb = Busboy({ headers: req.headers });
|
||||
|
||||
@@ -1433,10 +1415,27 @@ export function registerFileContentRoutes(
|
||||
getSessionSftp(sshConn)
|
||||
.then((sftp) => {
|
||||
const writeStream = sftp.createWriteStream(fullPath);
|
||||
const removePartialFile = () => {
|
||||
writeStream.destroy();
|
||||
sftp.unlink(fullPath, (err) => {
|
||||
if (err) {
|
||||
fileLogger.error(
|
||||
"Failed to remove partial file after aborted upload:",
|
||||
err,
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
destroyUpload = removePartialFile;
|
||||
|
||||
if (requestAborted) {
|
||||
removePartialFile();
|
||||
return;
|
||||
}
|
||||
|
||||
writeStream.on("error", (err) => {
|
||||
fileLogger.error("SFTP write stream error during upload:", err);
|
||||
if (!resolved) {
|
||||
if (!resolved && !requestAborted) {
|
||||
resolved = true;
|
||||
res
|
||||
.status(500)
|
||||
@@ -1444,8 +1443,8 @@ export function registerFileContentRoutes(
|
||||
}
|
||||
});
|
||||
|
||||
writeStream.on("finish", () => {
|
||||
if (resolved) return;
|
||||
const completeUpload = () => {
|
||||
if (resolved || requestAborted) return;
|
||||
resolved = true;
|
||||
fileLogger.success("Streaming file upload completed", {
|
||||
operation: "file_upload_stream_complete",
|
||||
@@ -1462,32 +1461,27 @@ export function registerFileContentRoutes(
|
||||
message: `File uploaded: ${fullPath}`,
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
let sourceEnded = false;
|
||||
fileStream.on("end", () => {
|
||||
sourceEnded = true;
|
||||
});
|
||||
writeStream.on("finish", completeUpload);
|
||||
// ssh2's SFTP WriteStream destroys itself inside _final (autoClose),
|
||||
// and a Writable destroyed before its final callback never emits
|
||||
// 'finish' on current Node. 'close' fires once the handle has been
|
||||
// closed after the last write was acknowledged, so it is the
|
||||
// completion signal that reliably arrives -- but only trust it
|
||||
// when the whole body was consumed and nothing aborted the upload.
|
||||
writeStream.on("close", () => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
fileLogger.success("Streaming file upload completed", {
|
||||
operation: "file_upload_stream_complete",
|
||||
sessionId,
|
||||
userId,
|
||||
path: fullPath,
|
||||
duration: Date.now() - uploadStartTime,
|
||||
});
|
||||
res.json({
|
||||
message: "File uploaded successfully",
|
||||
path: fullPath,
|
||||
toast: {
|
||||
type: "success",
|
||||
message: `File uploaded: ${fullPath}`,
|
||||
},
|
||||
});
|
||||
if (sourceEnded) completeUpload();
|
||||
});
|
||||
|
||||
fileStream.on("error", (err) => {
|
||||
fileLogger.error("File read stream error during upload:", err);
|
||||
writeStream.destroy();
|
||||
if (!resolved) {
|
||||
if (!resolved && !requestAborted) {
|
||||
resolved = true;
|
||||
res
|
||||
.status(500)
|
||||
@@ -1502,7 +1496,7 @@ export function registerFileContentRoutes(
|
||||
.catch((err: Error) => {
|
||||
fileStream.resume();
|
||||
fileLogger.error("SFTP session error during stream upload:", err);
|
||||
if (!resolved) {
|
||||
if (!resolved && !requestAborted) {
|
||||
resolved = true;
|
||||
res.status(500).json({ error: `SFTP error: ${err.message}` });
|
||||
}
|
||||
@@ -1512,7 +1506,7 @@ export function registerFileContentRoutes(
|
||||
|
||||
bb.on("error", (err: Error) => {
|
||||
fileLogger.error("Busboy parse error during stream upload:", err);
|
||||
if (!resolved) {
|
||||
if (!resolved && !requestAborted) {
|
||||
resolved = true;
|
||||
res.status(500).json({ error: `Upload parse error: ${err.message}` });
|
||||
}
|
||||
@@ -1601,7 +1595,8 @@ export function registerFileContentRoutes(
|
||||
fail(500, `Upload failed: ${err.message}`);
|
||||
});
|
||||
|
||||
writeStream.on("finish", () => {
|
||||
let sourceEnded = false;
|
||||
const completeChunk = () => {
|
||||
if (resolved) return;
|
||||
resolved = true;
|
||||
const nextOffset = offset + bytesWritten;
|
||||
@@ -1624,6 +1619,12 @@ export function registerFileContentRoutes(
|
||||
nextOffset,
|
||||
complete: nextOffset >= totalSize,
|
||||
});
|
||||
};
|
||||
writeStream.on("finish", completeChunk);
|
||||
// See uploadFileStream: ssh2's WriteStream does not emit 'finish'
|
||||
// on current Node; 'close' after the body ended is completion.
|
||||
writeStream.on("close", () => {
|
||||
if (sourceEnded) completeChunk();
|
||||
});
|
||||
|
||||
req.on("error", (err) => {
|
||||
@@ -1631,9 +1632,21 @@ export function registerFileContentRoutes(
|
||||
fail(500, `Upload stream error: ${err.message}`);
|
||||
});
|
||||
|
||||
if (Buffer.isBuffer(req.body)) {
|
||||
// Some middleware already drained the request into req.body;
|
||||
// there is nothing left to pipe, so write what it collected.
|
||||
bytesWritten = req.body.length;
|
||||
sourceEnded = true;
|
||||
writeStream.end(req.body);
|
||||
return;
|
||||
}
|
||||
|
||||
req.on("data", (chunk: Buffer) => {
|
||||
bytesWritten += chunk.length;
|
||||
});
|
||||
req.on("end", () => {
|
||||
sourceEnded = true;
|
||||
});
|
||||
|
||||
req.pipe(writeStream as unknown as NodeJS.WritableStream);
|
||||
})
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import { usesIssuedCertificate } from "../issued-certificate-auth.js";
|
||||
import express from "express";
|
||||
import {
|
||||
logAudit,
|
||||
@@ -9,7 +10,7 @@ import { createCorsMiddleware } from "../../utils/cors-config.js";
|
||||
import { createCompressionMiddleware } from "../../utils/compression-config.js";
|
||||
import cookieParser from "cookie-parser";
|
||||
import axios from "axios";
|
||||
import ssh2Pkg, { Client as SSHClient } from "ssh2";
|
||||
import ssh2Pkg, { Client as SSHClient, type ConnectConfig } from "ssh2";
|
||||
import { SSH_ALGORITHMS } from "../../utils/ssh-algorithms.js";
|
||||
import { createCurrentHostResolutionRepository } from "../../database/repositories/factory.js";
|
||||
import { fileLogger } from "../../utils/logger.js";
|
||||
@@ -28,7 +29,7 @@ import type {
|
||||
ConnectionStage,
|
||||
} from "../../../types/connection-log.js";
|
||||
import { SSHHostKeyVerifier } from "../host-key-verifier.js";
|
||||
import { resolveHostById } from "../host-resolver.js";
|
||||
import { resolveHostById, resolveHostBySyncId } from "../host-resolver.js";
|
||||
import {
|
||||
startHostTransfer,
|
||||
getTransferStatus,
|
||||
@@ -62,11 +63,13 @@ import {
|
||||
hostAddressMismatch,
|
||||
HostAddressMismatchError,
|
||||
HostNotOnThisServerError,
|
||||
} from "../terminal/host-identity.js";
|
||||
resolveServerHostId,
|
||||
} from "../host-identity.js";
|
||||
import { registerFileDownloadRoutes } from "./download-routes.js";
|
||||
import { registerFileActionRoutes } from "./action-routes.js";
|
||||
import { applyAgentAuth } from "../terminal-auth-helpers.js";
|
||||
import { applyCACertIfPresent } from "./ca-cert-auth.js";
|
||||
import { listenOnServicePort } from "../../utils/service-listen.js";
|
||||
|
||||
/**
|
||||
* The host id came from whichever database the client is displaying. If this
|
||||
@@ -117,21 +120,33 @@ function assertResolvedHost(
|
||||
}
|
||||
|
||||
const app = express();
|
||||
app.set("trust proxy", "loopback");
|
||||
|
||||
app.use(createCompressionMiddleware());
|
||||
app.use(createCorsMiddleware(["GET", "POST", "PUT", "DELETE", "OPTIONS"]));
|
||||
app.use(cookieParser());
|
||||
const authManager = AuthManager.getInstance();
|
||||
app.use(authManager.createAuthMiddleware());
|
||||
app.use(express.json({ limit: "1gb" }));
|
||||
app.use(express.urlencoded({ limit: "1gb", extended: true }));
|
||||
app.use(express.raw({ limit: "5gb", type: "application/octet-stream" }));
|
||||
// uploadFileChunk streams its octet-stream body straight into SFTP; the raw
|
||||
// body parser would otherwise buffer the whole chunk in memory first and,
|
||||
// worse, drain the request so nothing is left for the route to pipe (the
|
||||
// remote file ended up empty and the request never completed).
|
||||
const rawBodyParser = express.raw({
|
||||
limit: "5gb",
|
||||
type: "application/octet-stream",
|
||||
});
|
||||
const STREAMED_BODY_ROUTES = new Set(["/ssh/file_manager/ssh/uploadFileChunk"]);
|
||||
app.use((req, res, next) => {
|
||||
if (STREAMED_BODY_ROUTES.has(req.path)) return next();
|
||||
rawBodyParser(req, res, next);
|
||||
});
|
||||
app.use((_req, res, next) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
next();
|
||||
});
|
||||
|
||||
const authManager = AuthManager.getInstance();
|
||||
app.use(authManager.createAuthMiddleware());
|
||||
|
||||
const sshSessions: Record<string, SSHSession> = {};
|
||||
const pendingTOTPSessions: Record<string, PendingTOTPSession> = {};
|
||||
// Keyed by "sessionId:path" to prevent concurrent requests for the same path
|
||||
@@ -289,7 +304,7 @@ async function buildDedicatedTransferConnectConfig(
|
||||
throw new Error("Password required for transfer connection");
|
||||
}
|
||||
config.password = host.password;
|
||||
} else if (authType === "opkssh") {
|
||||
} else if (usesIssuedCertificate(authType)) {
|
||||
const { getOPKSSHToken } = await import("../opkssh-auth.js");
|
||||
const token = await getOPKSSHToken(userId, host.id);
|
||||
if (!token) {
|
||||
@@ -828,6 +843,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
|
||||
let resolvedSocks5Username = socks5Username;
|
||||
let resolvedSocks5Password = socks5Password;
|
||||
let resolvedSocks5ProxyChain = socks5ProxyChain;
|
||||
let resolvedVaultProfileId: number | null = null;
|
||||
if (hostId && userId && !password && !sshKey) {
|
||||
try {
|
||||
const { resolveHostById, resolveHostBySyncId } =
|
||||
@@ -854,6 +870,9 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
|
||||
hostKeepaliveInterval = resolvedHost.terminalConfig?.keepaliveInterval;
|
||||
hostKeepaliveCountMax = resolvedHost.terminalConfig?.keepaliveCountMax;
|
||||
resolvedScpLegacy = resolvedHost.scpLegacy ?? false;
|
||||
resolvedVaultProfileId =
|
||||
(resolvedHost.vaultProfile as { id?: number } | undefined)?.id ??
|
||||
null;
|
||||
if (resolvedHost.useSocks5) {
|
||||
resolvedUseSocks5 = resolvedHost.useSocks5;
|
||||
resolvedSocks5Host = resolvedHost.socks5Host;
|
||||
@@ -923,6 +942,9 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
|
||||
hostKeepaliveInterval = resolvedHost.terminalConfig?.keepaliveInterval;
|
||||
hostKeepaliveCountMax = resolvedHost.terminalConfig?.keepaliveCountMax;
|
||||
resolvedScpLegacy = resolvedHost.scpLegacy ?? false;
|
||||
resolvedVaultProfileId =
|
||||
(resolvedHost.vaultProfile as { id?: number } | undefined)?.id ??
|
||||
null;
|
||||
if (resolvedHost.useSocks5) {
|
||||
resolvedUseSocks5 = resolvedHost.useSocks5;
|
||||
resolvedSocks5Host = resolvedHost.socks5Host;
|
||||
@@ -968,7 +990,15 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
const preloadedHostData = await SSHHostKeyVerifier.preloadHostData(hostId);
|
||||
let serverHostId = hostId;
|
||||
if (hostSyncId && userId) {
|
||||
const resolvedHost = await resolveHostBySyncId(hostSyncId, userId);
|
||||
assertResolvedHost(ip, hostSyncId, resolvedHost, hostId, userId);
|
||||
serverHostId = resolveServerHostId(hostId, resolvedHost) ?? hostId;
|
||||
}
|
||||
|
||||
const preloadedHostData =
|
||||
await SSHHostKeyVerifier.preloadHostData(serverHostId);
|
||||
const keepalive = resolveSshKeepalive(
|
||||
hostKeepaliveInterval,
|
||||
hostKeepaliveCountMax,
|
||||
@@ -985,7 +1015,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
|
||||
tcpKeepAlive: true,
|
||||
tcpKeepAliveInitialDelay: 30000,
|
||||
hostVerifier: await SSHHostKeyVerifier.createHostVerifier(
|
||||
hostId,
|
||||
serverHostId,
|
||||
resolvedIp,
|
||||
resolvedPort,
|
||||
null,
|
||||
@@ -1120,10 +1150,10 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
|
||||
connectionLogs.push(
|
||||
createConnectionLog("info", "sftp_auth", "Using password authentication"),
|
||||
);
|
||||
} else if (resolvedCredentials.authType === "opkssh") {
|
||||
} else if (usesIssuedCertificate(resolvedCredentials.authType)) {
|
||||
try {
|
||||
const { getOPKSSHToken } = await import("../opkssh-auth.js");
|
||||
const token = await getOPKSSHToken(userId, hostId);
|
||||
const token = await getOPKSSHToken(userId, serverHostId);
|
||||
|
||||
if (!token) {
|
||||
connectionLogs.push(
|
||||
@@ -1174,6 +1204,38 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
|
||||
connectionLogs,
|
||||
});
|
||||
}
|
||||
} else if (resolvedCredentials.authType === "vault") {
|
||||
try {
|
||||
const { setupVaultSshSignerAuth } =
|
||||
await import("../vault-ssh-connect.js");
|
||||
await setupVaultSshSignerAuth(config as ConnectConfig, client, {
|
||||
id: serverHostId,
|
||||
username: resolvedUsername,
|
||||
userId,
|
||||
vaultProfile: { id: resolvedVaultProfileId },
|
||||
});
|
||||
connectionLogs.push(
|
||||
createConnectionLog(
|
||||
"info",
|
||||
"sftp_auth",
|
||||
"Using cached Vault-signed certificate",
|
||||
),
|
||||
);
|
||||
} catch (vaultError) {
|
||||
const message = getErrorMessage(vaultError);
|
||||
fileLogger.warn("Vault authentication unavailable for file manager", {
|
||||
operation: "file_connect_vault_auth",
|
||||
sessionId,
|
||||
hostId,
|
||||
error: message,
|
||||
});
|
||||
connectionLogs.push(createConnectionLog("error", "sftp_auth", message));
|
||||
return res.status(401).json({
|
||||
error: message,
|
||||
requiresVaultAuth: true,
|
||||
connectionLogs,
|
||||
});
|
||||
}
|
||||
} else if (resolvedCredentials.authType === "agent") {
|
||||
const result = await applyAgentAuth(config, resolvedTerminalConfig);
|
||||
if ("error" in result) {
|
||||
@@ -1255,7 +1317,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
|
||||
operation: "file_ssh_connected",
|
||||
sessionId,
|
||||
userId,
|
||||
hostId,
|
||||
hostId: serverHostId,
|
||||
ip,
|
||||
port,
|
||||
username,
|
||||
@@ -1283,7 +1345,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
|
||||
userId,
|
||||
ip,
|
||||
port,
|
||||
hostId,
|
||||
hostId: serverHostId,
|
||||
username,
|
||||
sudoPassword: resolvedCredentials.sudoPassword,
|
||||
scpLegacy: resolvedScpLegacy,
|
||||
@@ -1298,7 +1360,7 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
|
||||
username: await getAuditUsername(userId),
|
||||
action: "file_manager_connect",
|
||||
resourceType: "host",
|
||||
resourceId: hostId ? String(hostId) : undefined,
|
||||
resourceId: serverHostId ? String(serverHostId) : undefined,
|
||||
resourceName: `${username}@${ip}:${port}`,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
@@ -3128,16 +3190,27 @@ process.on("SIGTERM", () => {
|
||||
const PORT = 30004;
|
||||
|
||||
try {
|
||||
const server = app.listen(PORT, async () => {
|
||||
try {
|
||||
await authManager.initialize();
|
||||
} catch (err) {
|
||||
fileLogger.error("Failed to initialize AuthManager", err, {
|
||||
operation: "auth_init_error",
|
||||
});
|
||||
}
|
||||
const server = listenOnServicePort({
|
||||
app,
|
||||
port: PORT,
|
||||
logger: fileLogger,
|
||||
serviceName: "file-manager",
|
||||
onListening: async () => {
|
||||
try {
|
||||
await authManager.initialize();
|
||||
} catch (err) {
|
||||
fileLogger.error("Failed to initialize AuthManager", err, {
|
||||
operation: "auth_init_error",
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Uploads are streamed and may legitimately take longer than Node's default
|
||||
// five-minute request deadline. Connection liveness is handled by the proxy
|
||||
// and socket-level timeouts instead of a total request duration cap.
|
||||
server.requestTimeout = 0;
|
||||
|
||||
server.on("error", (err) => {
|
||||
fileLogger.error("File Manager server error", err, {
|
||||
operation: "file_manager_server_error",
|
||||
|
||||
@@ -54,7 +54,7 @@ export function registerFileListingRoutes(
|
||||
app.get("/ssh/file_manager/ssh/listFiles", (req, res) => {
|
||||
const sessionId = req.query.sessionId as string;
|
||||
const sshConn = sshSessions[sessionId];
|
||||
const sshPath = decodeURIComponent((req.query.path as string) || "/");
|
||||
const sshPath = (req.query.path as string) || "/";
|
||||
const userId = (req as AuthenticatedRequest).userId;
|
||||
|
||||
if (!sessionId) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
getSessionSftp,
|
||||
type SSHSession,
|
||||
} from "./session.js";
|
||||
import { ensureDirectoryTreeSftp } from "./transfer-sftp-dir.js";
|
||||
import { buildDeleteCommand } from "./operation-commands.js";
|
||||
import {
|
||||
emptyTrash,
|
||||
@@ -354,99 +355,20 @@ export function registerFileOperationRoutes(
|
||||
userId,
|
||||
path: fullPath,
|
||||
});
|
||||
const escapedPath = fullPath.replace(/'/g, "'\"'\"'");
|
||||
|
||||
const createCommand = `mkdir -p '${escapedPath}' && echo "SUCCESS" && exit 0`;
|
||||
|
||||
execChannel(sshConn, createCommand, (err, stream) => {
|
||||
if (err) {
|
||||
fileLogger.error("SSH createFolder error:", err);
|
||||
if (!res.headersSent) {
|
||||
return res.status(500).json({ error: err.message });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let outputData = "";
|
||||
let errorData = "";
|
||||
|
||||
stream.on("data", (chunk: Buffer) => {
|
||||
outputData += chunk.toString();
|
||||
try {
|
||||
await ensureDirectoryTreeSftp(await getSessionSftp(sshConn), fullPath);
|
||||
res.json({
|
||||
message: "Folder created successfully",
|
||||
path: fullPath,
|
||||
toast: { type: "success", message: `Folder created: ${fullPath}` },
|
||||
});
|
||||
|
||||
stream.stderr.on("data", (chunk: Buffer) => {
|
||||
errorData += chunk.toString();
|
||||
|
||||
if (chunk.toString().includes("Permission denied")) {
|
||||
fileLogger.error(`Permission denied creating folder: ${fullPath}`);
|
||||
if (!res.headersSent) {
|
||||
return res.status(403).json({
|
||||
error: `Permission denied: Cannot create folder ${fullPath}. Check directory permissions.`,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
fileLogger.error("SFTP createFolder failed", error);
|
||||
const code = (error as { code?: string | number }).code;
|
||||
res.status(code === 3 || code === "EACCES" ? 403 : 500).json({
|
||||
error: (error as Error).message,
|
||||
});
|
||||
|
||||
stream.on("close", (code) => {
|
||||
if (outputData.includes("SUCCESS")) {
|
||||
fileLogger.success("Directory created successfully", {
|
||||
operation: "file_mkdir_success",
|
||||
sessionId,
|
||||
userId,
|
||||
path: fullPath,
|
||||
});
|
||||
if (!res.headersSent) {
|
||||
res.json({
|
||||
message: "Folder created successfully",
|
||||
path: fullPath,
|
||||
toast: {
|
||||
type: "success",
|
||||
message: `Folder created: ${fullPath}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (code !== 0) {
|
||||
fileLogger.error(
|
||||
`SSH createFolder command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
|
||||
);
|
||||
if (!res.headersSent) {
|
||||
return res.status(500).json({
|
||||
error: `Command failed: ${errorData}`,
|
||||
toast: {
|
||||
type: "error",
|
||||
message: `Folder creation failed: ${errorData}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
fileLogger.success("Directory created successfully", {
|
||||
operation: "file_mkdir_success",
|
||||
sessionId,
|
||||
userId,
|
||||
path: fullPath,
|
||||
});
|
||||
if (!res.headersSent) {
|
||||
res.json({
|
||||
message: "Folder created successfully",
|
||||
path: fullPath,
|
||||
toast: { type: "success", message: `Folder created: ${fullPath}` },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
stream.on("error", (streamErr) => {
|
||||
fileLogger.error("SSH createFolder stream error:", streamErr);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({ error: `Stream error: ${streamErr.message}` });
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -76,10 +76,15 @@ export function execWithSudoBuffer(
|
||||
session: SSHSession,
|
||||
command: string,
|
||||
sudoPassword: string,
|
||||
): Promise<{ stdout: Buffer; stderr: string; code: number }> {
|
||||
maxStdoutBytes?: number,
|
||||
): Promise<{
|
||||
stdout: Buffer;
|
||||
stderr: string;
|
||||
code: number;
|
||||
exceededLimit?: boolean;
|
||||
}> {
|
||||
return new Promise((resolve) => {
|
||||
const escapedPassword = sudoPassword.replace(/'/g, "'\"'\"'");
|
||||
const sudoCommand = `echo '${escapedPassword}' | sudo -S ${command} 2>&1`;
|
||||
const sudoCommand = `sudo -S -p '' ${command} 2>&1`;
|
||||
|
||||
execChannel(session, sudoCommand, (err, stream) => {
|
||||
if (err) {
|
||||
@@ -88,9 +93,33 @@ export function execWithSudoBuffer(
|
||||
}
|
||||
|
||||
const stdoutChunks: Buffer[] = [];
|
||||
let stdoutBytes = 0;
|
||||
let stderr = "";
|
||||
let settled = false;
|
||||
|
||||
const finish = (
|
||||
code: number,
|
||||
extra: { exceededLimit?: boolean } = {},
|
||||
) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve({
|
||||
stdout: Buffer.concat(stdoutChunks),
|
||||
stderr,
|
||||
code,
|
||||
...extra,
|
||||
});
|
||||
};
|
||||
|
||||
stream.on("data", (chunk: Buffer) => {
|
||||
if (settled) return;
|
||||
stdoutBytes += chunk.length;
|
||||
if (maxStdoutBytes !== undefined && stdoutBytes > maxStdoutBytes) {
|
||||
stderr = `Command output exceeds ${maxStdoutBytes} bytes`;
|
||||
finish(1, { exceededLimit: true });
|
||||
stream.close();
|
||||
return;
|
||||
}
|
||||
stdoutChunks.push(chunk);
|
||||
});
|
||||
|
||||
@@ -99,6 +128,7 @@ export function execWithSudoBuffer(
|
||||
});
|
||||
|
||||
stream.on("close", (code: number) => {
|
||||
if (settled) return;
|
||||
let stdout = Buffer.concat(stdoutChunks);
|
||||
const sudoPromptMatch = stdout
|
||||
.toString("utf8", 0, Math.min(stdout.length, 256))
|
||||
@@ -106,15 +136,74 @@ export function execWithSudoBuffer(
|
||||
if (sudoPromptMatch) {
|
||||
stdout = stdout.subarray(Buffer.byteLength(sudoPromptMatch[0]));
|
||||
}
|
||||
settled = true;
|
||||
resolve({ stdout, stderr, code: code || 0 });
|
||||
});
|
||||
|
||||
stream.on("error", (streamErr: Error) => {
|
||||
stderr = streamErr.message;
|
||||
finish(1);
|
||||
});
|
||||
|
||||
stream.write(`${sudoPassword}\n`);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function execBuffer(
|
||||
session: SSHSession,
|
||||
command: string,
|
||||
maxStdoutBytes?: number,
|
||||
): Promise<{
|
||||
stdout: Buffer;
|
||||
stderr: string;
|
||||
code: number;
|
||||
exceededLimit?: boolean;
|
||||
}> {
|
||||
return new Promise((resolve) => {
|
||||
execChannel(session, command, (err, stream) => {
|
||||
if (err) {
|
||||
resolve({ stdout: Buffer.alloc(0), stderr: err.message, code: 1 });
|
||||
return;
|
||||
}
|
||||
|
||||
const stdoutChunks: Buffer[] = [];
|
||||
let stdoutBytes = 0;
|
||||
let stderr = "";
|
||||
let settled = false;
|
||||
|
||||
const finish = (
|
||||
code: number,
|
||||
extra: { exceededLimit?: boolean } = {},
|
||||
) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve({
|
||||
stdout: Buffer.concat(stdoutChunks),
|
||||
stderr: streamErr.message,
|
||||
code: 1,
|
||||
stderr,
|
||||
code,
|
||||
...extra,
|
||||
});
|
||||
};
|
||||
|
||||
stream.on("data", (chunk: Buffer) => {
|
||||
if (settled) return;
|
||||
stdoutBytes += chunk.length;
|
||||
if (maxStdoutBytes !== undefined && stdoutBytes > maxStdoutBytes) {
|
||||
stderr = `Command output exceeds ${maxStdoutBytes} bytes`;
|
||||
finish(1, { exceededLimit: true });
|
||||
stream.close();
|
||||
return;
|
||||
}
|
||||
stdoutChunks.push(chunk);
|
||||
});
|
||||
stream.stderr.on("data", (chunk: Buffer) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
stream.on("close", (code: number) => finish(code || 0));
|
||||
stream.on("error", (streamErr: Error) => {
|
||||
stderr = stderr || streamErr.message;
|
||||
finish(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
export const GUACD_DRIVE_PATH_ENV = "GUACD_DRIVE_PATH";
|
||||
const DEFAULT_DRIVE_ROOT = "/drive";
|
||||
|
||||
/**
|
||||
* Fills in where guacd keeps the files behind RDP drive redirection.
|
||||
*
|
||||
* The folder lives on the guacd host, not on Termix's - with the stock
|
||||
* compose it is a directory in the shared termix-data volume, configured
|
||||
* through GUACD_DRIVE_PATH. Each user gets a folder of their own underneath:
|
||||
* a shared drive would show everyone's uploads to everyone else. A host that
|
||||
* names its own drive-path keeps it.
|
||||
*/
|
||||
export function withDriveSettings(
|
||||
guacConfig: Record<string, unknown>,
|
||||
userId: string,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): Record<string, unknown> {
|
||||
if (!guacConfig["enable-drive"] || guacConfig["drive-path"]) {
|
||||
return guacConfig;
|
||||
}
|
||||
const root = (
|
||||
env[GUACD_DRIVE_PATH_ENV]?.trim() || DEFAULT_DRIVE_ROOT
|
||||
).replace(/\/+$/, "");
|
||||
return {
|
||||
...guacConfig,
|
||||
"drive-path": `${root}/${userId}`,
|
||||
"create-drive-path": true,
|
||||
};
|
||||
}
|
||||
@@ -57,30 +57,12 @@ export interface GuacSessionInfo {
|
||||
const guacSessionByConnectId = new Map<string, GuacSessionInfo>();
|
||||
// Keyed by guacd's own guacamoleConnectionId, for join-time lookups.
|
||||
const guacSessionByGuacamoleId = new Map<string, GuacSessionInfo>();
|
||||
const pendingConnectResolvers = new Map<
|
||||
string,
|
||||
(info: GuacSessionInfo | null) => void
|
||||
>();
|
||||
|
||||
export function waitForGuacdOpen(
|
||||
termixConnectId: string,
|
||||
timeoutMs = 10000,
|
||||
): Promise<GuacSessionInfo | null> {
|
||||
const existing = guacSessionByConnectId.get(termixConnectId);
|
||||
if (existing) return Promise.resolve(existing);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (info: GuacSessionInfo | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
pendingConnectResolvers.delete(termixConnectId);
|
||||
resolve(info);
|
||||
};
|
||||
|
||||
pendingConnectResolvers.set(termixConnectId, finish);
|
||||
setTimeout(() => finish(null), timeoutMs);
|
||||
});
|
||||
export function getGuacSessionByConnectId(
|
||||
connectId: string,
|
||||
userId: string,
|
||||
): GuacSessionInfo | null {
|
||||
const info = guacSessionByConnectId.get(connectId);
|
||||
return info?.ownerUserId === userId ? info : null;
|
||||
}
|
||||
|
||||
export function getGuacSessionInfo(
|
||||
@@ -140,6 +122,7 @@ async function persistGuacamoleRecording(
|
||||
}
|
||||
|
||||
const websocketOptions = {
|
||||
host: "127.0.0.1",
|
||||
port: GUAC_WS_PORT,
|
||||
};
|
||||
|
||||
@@ -230,9 +213,6 @@ function createGuacServer(): GuacamoleLite {
|
||||
};
|
||||
guacSessionByConnectId.set(termixMeta.termixConnectId, info);
|
||||
guacSessionByGuacamoleId.set(guacamoleConnectionId, info);
|
||||
|
||||
const resolver = pendingConnectResolvers.get(termixMeta.termixConnectId);
|
||||
if (resolver) resolver(info);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import net from "net";
|
||||
|
||||
const RFB_BANNER_LENGTH = 12;
|
||||
const VNC_AUTH_SECURITY_TYPE = 2;
|
||||
const MACOS_RFB_BANNER = Buffer.from("RFB 003.889\n", "ascii");
|
||||
const STANDARD_RFB_BANNER = Buffer.from("RFB 003.008\n", "ascii");
|
||||
|
||||
export interface VncCompatibilityProxy {
|
||||
port: number;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
export async function createMacosVncCompatibilityProxy({
|
||||
targetHost,
|
||||
targetPort,
|
||||
bindHost,
|
||||
}: {
|
||||
targetHost: string;
|
||||
targetPort: number;
|
||||
bindHost: string;
|
||||
}): Promise<VncCompatibilityProxy> {
|
||||
const sockets = new Set<net.Socket>();
|
||||
const server = net.createServer((client) => {
|
||||
const upstream = net.createConnection(targetPort, targetHost);
|
||||
sockets.add(client);
|
||||
sockets.add(upstream);
|
||||
|
||||
const forget = (socket: net.Socket) => sockets.delete(socket);
|
||||
client.once("close", () => forget(client));
|
||||
upstream.once("close", () => forget(upstream));
|
||||
client.once("error", () => upstream.destroy());
|
||||
upstream.once("error", () => client.destroy());
|
||||
client.pipe(upstream);
|
||||
|
||||
let pending = Buffer.alloc(0);
|
||||
const forwardMacosSecurityTypes = (chunk: Buffer) => {
|
||||
pending = Buffer.concat([pending, chunk]);
|
||||
if (pending.length < 1) return;
|
||||
|
||||
const securityTypeCount = pending[0];
|
||||
if (securityTypeCount === 0) {
|
||||
upstream.off("data", forwardMacosSecurityTypes);
|
||||
client.write(pending);
|
||||
upstream.pipe(client);
|
||||
return;
|
||||
}
|
||||
if (pending.length < 1 + securityTypeCount) return;
|
||||
|
||||
upstream.off("data", forwardMacosSecurityTypes);
|
||||
const securityTypes = pending.subarray(1, 1 + securityTypeCount);
|
||||
if (securityTypes.includes(VNC_AUTH_SECURITY_TYPE)) {
|
||||
client.write(Buffer.from([1, VNC_AUTH_SECURITY_TYPE]));
|
||||
} else {
|
||||
client.write(pending.subarray(0, 1 + securityTypeCount));
|
||||
}
|
||||
client.write(pending.subarray(1 + securityTypeCount));
|
||||
upstream.pipe(client);
|
||||
};
|
||||
|
||||
const forwardServerBanner = (chunk: Buffer) => {
|
||||
pending = Buffer.concat([pending, chunk]);
|
||||
if (pending.length < RFB_BANNER_LENGTH) return;
|
||||
|
||||
upstream.off("data", forwardServerBanner);
|
||||
const banner = pending.subarray(0, RFB_BANNER_LENGTH);
|
||||
const remainder = pending.subarray(RFB_BANNER_LENGTH);
|
||||
if (banner.equals(MACOS_RFB_BANNER)) {
|
||||
client.write(STANDARD_RFB_BANNER);
|
||||
pending = Buffer.alloc(0);
|
||||
upstream.on("data", forwardMacosSecurityTypes);
|
||||
if (remainder.length > 0) forwardMacosSecurityTypes(remainder);
|
||||
} else {
|
||||
client.write(banner);
|
||||
client.write(remainder);
|
||||
upstream.pipe(client);
|
||||
}
|
||||
};
|
||||
upstream.on("data", forwardServerBanner);
|
||||
});
|
||||
|
||||
const port = await new Promise<number>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, bindHost, () => {
|
||||
server.off("error", reject);
|
||||
resolve((server.address() as net.AddressInfo).port);
|
||||
});
|
||||
});
|
||||
server.unref();
|
||||
|
||||
return {
|
||||
port,
|
||||
close: () => {
|
||||
server.close();
|
||||
for (const socket of sockets) socket.destroy();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -34,3 +34,31 @@ export function resolveRdpDomain(
|
||||
? promptedDomain
|
||||
: storedDomain;
|
||||
}
|
||||
|
||||
type SharedRdpAuthResolution =
|
||||
| { source: "personal-override" }
|
||||
| { source: "owner-shared"; authType: string }
|
||||
| { source: "secretless" }
|
||||
| { source: "required" }
|
||||
| null;
|
||||
|
||||
export function resolveRdpAuthTypeForConnect({
|
||||
storedAuthType,
|
||||
credentialId,
|
||||
sharedResolution,
|
||||
}: {
|
||||
storedAuthType?: string | null;
|
||||
credentialId?: number | null;
|
||||
sharedResolution?: SharedRdpAuthResolution;
|
||||
}): string {
|
||||
if (sharedResolution === undefined) {
|
||||
return storedAuthType || (credentialId ? "credential" : "direct");
|
||||
}
|
||||
if (sharedResolution?.source === "personal-override") return "credential";
|
||||
if (sharedResolution?.source === "owner-shared") {
|
||||
return sharedResolution.authType;
|
||||
}
|
||||
return sharedResolution?.source === "secretless" && storedAuthType === "none"
|
||||
? "none"
|
||||
: "direct";
|
||||
}
|
||||
@@ -2,9 +2,15 @@ import { getErrorMessage } from "../../utils/error-message.js";
|
||||
import express from "express";
|
||||
import { GuacamoleTokenService } from "./token-service.js";
|
||||
import { withRecordingSettings } from "./recording-settings.js";
|
||||
import { withDriveSettings } from "./drive-settings.js";
|
||||
import { guacLogger } from "../../utils/logger.js";
|
||||
import { AuthManager } from "../../utils/auth-manager.js";
|
||||
import { PermissionManager } from "../../utils/permission-manager.js";
|
||||
import {
|
||||
resolveRecipientSharedHostAuthentication,
|
||||
type RecipientSharedHostAuthResolution,
|
||||
} from "../../utils/shared-host-auth-resolver.js";
|
||||
import type { AuthOverrideProtocol } from "../../../types/auth-protocols.js";
|
||||
import net from "net";
|
||||
import crypto from "crypto";
|
||||
import path from "path";
|
||||
@@ -15,14 +21,19 @@ import {
|
||||
} from "../../database/repositories/factory.js";
|
||||
import { resolveGuacdOptions } from "../../utils/guacd-config.js";
|
||||
import { createJumpHostChain } from "../jump-host-chain.js";
|
||||
import { waitForGuacdOpen } from "./guacamole-server.js";
|
||||
import { getGuacSessionByConnectId } from "./guacamole-server.js";
|
||||
import {
|
||||
logAudit,
|
||||
getAuditUsername,
|
||||
getRequestMeta,
|
||||
} from "../../utils/audit-logger.js";
|
||||
import { resolveJumpTunnelEndpoint } from "./jump-tunnel-endpoint.js";
|
||||
import { buildRdpSettings, resolveRdpDomain } from "./rdp-settings.js";
|
||||
import {
|
||||
buildRdpSettings,
|
||||
resolveRdpAuthTypeForConnect,
|
||||
resolveRdpDomain,
|
||||
} from "./rdp-settings.js";
|
||||
import { createMacosVncCompatibilityProxy } from "./macos-vnc-proxy.js";
|
||||
|
||||
const router = express.Router();
|
||||
const tokenService = GuacamoleTokenService.getInstance();
|
||||
@@ -31,6 +42,16 @@ const DATA_DIR = process.env.DATA_DIR || "./db/data";
|
||||
|
||||
router.use(authManager.createAuthMiddleware());
|
||||
|
||||
router.get("/connection/:connectId", (req: AuthenticatedRequest, res) => {
|
||||
if (!req.userId)
|
||||
return res.status(401).json({ error: "Authentication required" });
|
||||
const session = getGuacSessionByConnectId(
|
||||
String(req.params.connectId),
|
||||
req.userId,
|
||||
);
|
||||
res.json({ guacamoleConnectionId: session?.guacamoleConnectionId ?? null });
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /guacamole/token:
|
||||
@@ -195,7 +216,10 @@ router.post("/token", async (req, res) => {
|
||||
* guacamoleConnectionId:
|
||||
* type: string
|
||||
* nullable: true
|
||||
* description: guacd's own connection id for this session, once the handshake completes. Used to mint session-share join tokens.
|
||||
* description: Null until the WebSocket handshake completes. Query /guacamole/connection/{connectId} for the session-sharing ID.
|
||||
* termixConnectId:
|
||||
* type: string
|
||||
* description: Correlation ID for looking up this connection after the WebSocket opens.
|
||||
* 400:
|
||||
* description: Invalid request or unsupported connection type
|
||||
* 403:
|
||||
@@ -318,6 +342,7 @@ router.post(
|
||||
const hostRecord = host as Record<string, unknown>;
|
||||
const hostRepository = hostResolutionRepository;
|
||||
const isSharedConnection = host.userId !== userId;
|
||||
let sharedAuthResolution: RecipientSharedHostAuthResolution | null = null;
|
||||
|
||||
if (isSharedConnection) {
|
||||
// Recipients never read the owner's raw secrets; wipe them and use
|
||||
@@ -331,30 +356,35 @@ router.post(
|
||||
host.telnetPassword = null;
|
||||
|
||||
try {
|
||||
const { SharedHostSecretsManager } =
|
||||
await import("../../utils/shared-host-secrets-manager.js");
|
||||
const secret =
|
||||
await SharedHostSecretsManager.getInstance().getSecretForUser(
|
||||
hostId,
|
||||
userId,
|
||||
connectionType as "rdp" | "vnc" | "telnet",
|
||||
);
|
||||
if (secret) {
|
||||
const resolution = await resolveRecipientSharedHostAuthentication(
|
||||
host,
|
||||
hostId,
|
||||
userId,
|
||||
connectionType as AuthOverrideProtocol,
|
||||
);
|
||||
sharedAuthResolution = resolution;
|
||||
const auth =
|
||||
resolution.source === "personal-override"
|
||||
? { ...resolution.credential, domain: null }
|
||||
: resolution.source === "owner-shared"
|
||||
? resolution.secret
|
||||
: null;
|
||||
if (auth) {
|
||||
if (connectionType === "rdp") {
|
||||
host.rdpUser = secret.username ?? null;
|
||||
host.rdpPassword = secret.password ?? null;
|
||||
if (secret.domain) host.rdpDomain = secret.domain;
|
||||
host.rdpUser = auth.username ?? null;
|
||||
host.rdpPassword = auth.password ?? null;
|
||||
if (auth.domain) host.rdpDomain = auth.domain;
|
||||
} else if (connectionType === "vnc") {
|
||||
host.vncUser = secret.username ?? null;
|
||||
host.vncPassword = secret.password ?? null;
|
||||
host.vncUser = auth.username ?? null;
|
||||
host.vncPassword = auth.password ?? null;
|
||||
} else if (connectionType === "telnet") {
|
||||
host.telnetUser = secret.username ?? null;
|
||||
host.telnetPassword = secret.password ?? null;
|
||||
host.telnetUser = auth.username ?? null;
|
||||
host.telnetPassword = auth.password ?? null;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
guacLogger.warn("Failed to resolve shared host secret", {
|
||||
operation: "guac_shared_secret_resolve",
|
||||
guacLogger.warn("Failed to resolve shared host auth", {
|
||||
operation: "guac_shared_auth_resolve",
|
||||
hostId,
|
||||
protocol: connectionType,
|
||||
error: getErrorMessage(e, "Unknown"),
|
||||
@@ -440,10 +470,11 @@ router.post(
|
||||
let username: string;
|
||||
let password: string;
|
||||
|
||||
const rdpAuthTypeForConnect = isSharedConnection
|
||||
? null
|
||||
: (host.rdpAuthType as string) ||
|
||||
(host.rdpCredentialId ? "credential" : "direct");
|
||||
const rdpAuthTypeForConnect = resolveRdpAuthTypeForConnect({
|
||||
storedAuthType: host.rdpAuthType as string | null,
|
||||
credentialId: host.rdpCredentialId as number | null,
|
||||
sharedResolution: isSharedConnection ? sharedAuthResolution : undefined,
|
||||
});
|
||||
|
||||
switch (connectionType) {
|
||||
case "rdp":
|
||||
@@ -495,20 +526,24 @@ router.post(
|
||||
}
|
||||
}
|
||||
|
||||
let tunnelEndpoint: ReturnType<typeof resolveJumpTunnelEndpoint> | null =
|
||||
null;
|
||||
if (jumpHosts.length > 0 || (connectionType === "vnc" && !username)) {
|
||||
let guacdUrl: string | undefined;
|
||||
try {
|
||||
guacdUrl =
|
||||
(await createCurrentSettingsRepository().get("guac_url")) ??
|
||||
undefined;
|
||||
} catch {
|
||||
// Environment/default guacd configuration remains available.
|
||||
}
|
||||
const guacdHost =
|
||||
perConnectionGuacdHost || resolveGuacdOptions(guacdUrl).host;
|
||||
tunnelEndpoint = resolveJumpTunnelEndpoint(guacdHost);
|
||||
}
|
||||
|
||||
if (jumpHosts.length > 0) {
|
||||
try {
|
||||
let guacdUrl: string | undefined;
|
||||
try {
|
||||
guacdUrl =
|
||||
(await createCurrentSettingsRepository().get("guac_url")) ??
|
||||
undefined;
|
||||
} catch {
|
||||
// Environment/default guacd configuration remains available.
|
||||
}
|
||||
const guacdHost =
|
||||
perConnectionGuacdHost || resolveGuacdOptions(guacdUrl).host;
|
||||
const tunnelEndpoint = resolveJumpTunnelEndpoint(guacdHost);
|
||||
|
||||
// The chain dials the first hop through that hop's own SOCKS5
|
||||
// settings; the target host's proxy config does not apply to it.
|
||||
const jumpClient = await createJumpHostChain(jumpHosts, userId);
|
||||
@@ -543,7 +578,7 @@ router.post(
|
||||
);
|
||||
});
|
||||
server.on("error", reject);
|
||||
server.listen(0, tunnelEndpoint.bindHost, () => {
|
||||
server.listen(0, tunnelEndpoint!.bindHost, () => {
|
||||
const addr = server.address() as net.AddressInfo;
|
||||
// Auto-cleanup after 1 hour
|
||||
setTimeout(
|
||||
@@ -556,7 +591,7 @@ router.post(
|
||||
resolve(addr.port);
|
||||
});
|
||||
});
|
||||
hostname = tunnelEndpoint.advertisedHost;
|
||||
hostname = tunnelEndpoint!.advertisedHost;
|
||||
port = tunnelPort;
|
||||
guacLogger.info("SSH tunnel established for guacamole", {
|
||||
operation: "guac_ssh_tunnel",
|
||||
@@ -574,6 +609,36 @@ router.post(
|
||||
}
|
||||
}
|
||||
|
||||
if (connectionType === "vnc" && !username) {
|
||||
try {
|
||||
const proxy = await createMacosVncCompatibilityProxy({
|
||||
targetHost: hostname,
|
||||
targetPort: port,
|
||||
bindHost: tunnelEndpoint!.bindHost,
|
||||
});
|
||||
hostname = tunnelEndpoint!.advertisedHost;
|
||||
port = proxy.port;
|
||||
setTimeout(proxy.close, 60 * 60 * 1000).unref();
|
||||
guacLogger.info("VNC compatibility proxy established", {
|
||||
operation: "guac_vnc_compatibility_proxy",
|
||||
hostId,
|
||||
proxyPort: port,
|
||||
});
|
||||
} catch (proxyError) {
|
||||
guacLogger.error(
|
||||
"Failed to establish VNC compatibility proxy",
|
||||
proxyError,
|
||||
{
|
||||
operation: "guac_vnc_compatibility_proxy_error",
|
||||
hostId,
|
||||
},
|
||||
);
|
||||
return res.status(500).json({
|
||||
error: "Failed to establish VNC compatibility proxy",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const guacdOverrides = {
|
||||
...(perConnectionGuacdHost
|
||||
? { guacdHost: perConnectionGuacdHost }
|
||||
@@ -617,10 +682,7 @@ router.post(
|
||||
|
||||
switch (connectionType) {
|
||||
case "rdp":
|
||||
if (guacConfig["enable-drive"] && !guacConfig["drive-path"]) {
|
||||
guacConfig["drive-path"] = "/drive";
|
||||
guacConfig["create-drive-path"] = true;
|
||||
}
|
||||
guacConfig = withDriveSettings(guacConfig, userId);
|
||||
token = tokenService.createRdpToken(
|
||||
hostname,
|
||||
username,
|
||||
@@ -677,8 +739,6 @@ router.post(
|
||||
return res.status(400).json({ error: "Invalid connection type" });
|
||||
}
|
||||
|
||||
const sessionInfo = await waitForGuacdOpen(termixConnectId, 10000);
|
||||
|
||||
const { ipAddress, userAgent } = getRequestMeta(req);
|
||||
await logAudit({
|
||||
userId,
|
||||
@@ -694,7 +754,8 @@ router.post(
|
||||
|
||||
res.json({
|
||||
token,
|
||||
guacamoleConnectionId: sessionInfo?.guacamoleConnectionId ?? null,
|
||||
termixConnectId,
|
||||
guacamoleConnectionId: null,
|
||||
});
|
||||
} catch (error) {
|
||||
guacLogger.error("Failed to generate guacamole token for host", error, {
|
||||
|
||||
@@ -64,6 +64,13 @@ export function resolveServerJumpHosts(
|
||||
return clientJumpHosts?.length ? clientJumpHosts : serverJumpHosts;
|
||||
}
|
||||
|
||||
export function resolveServerHostId(
|
||||
clientHostId: number | null,
|
||||
resolvedHost: { id?: unknown } | null,
|
||||
): number | null {
|
||||
return typeof resolvedHost?.id === "number" ? resolvedHost.id : clientHostId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown where a mismatch is reported by rejecting rather than by messaging
|
||||
* the socket. Callers whose host-resolution is wrapped in a "failed to resolve
|
||||
@@ -1,3 +1,4 @@
|
||||
import { authFailureTracker } from "./metrics/state.js";
|
||||
import type { WebSocket } from "ws";
|
||||
import { createCurrentHostResolutionRepository } from "../database/repositories/factory.js";
|
||||
import { sshLogger } from "../utils/logger.js";
|
||||
@@ -327,6 +328,7 @@ export class SSHHostKeyVerifier {
|
||||
algorithm,
|
||||
currentChangeCount,
|
||||
);
|
||||
authFailureTracker.resetHostKeyFailure(hostId);
|
||||
}
|
||||
|
||||
private static async promptUserForNewKey(
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { getErrorMessage } from "../utils/error-message.js";
|
||||
import { findUsableCredential } from "./usable-credential.js";
|
||||
import { resolveExternalSecretRefs } from "./external-secrets.js";
|
||||
import {
|
||||
createCurrentHostResolutionRepository,
|
||||
createCurrentVaultProfileRepository,
|
||||
@@ -189,7 +191,7 @@ export async function resolveHostById(
|
||||
|
||||
if (effectiveCredentialId) {
|
||||
try {
|
||||
const cred = (await repository.findCredentialByIdForUser(
|
||||
const cred = (await findUsableCredential(
|
||||
effectiveCredentialId,
|
||||
ownerId,
|
||||
)) as Record<string, unknown> | null;
|
||||
@@ -229,6 +231,14 @@ export async function resolveHostById(
|
||||
ownerEquivalent ? ownerId : userId,
|
||||
);
|
||||
|
||||
// "op://..." references become real secrets here, once, for everyone
|
||||
// downstream. They resolve in the context of whoever owns the secret
|
||||
// fields: the owner for their own host, the recipient for an override.
|
||||
await resolveExternalSecretRefs(
|
||||
host as Record<string, unknown>,
|
||||
sharedAuthResolution === "recipient-override" ? userId : ownerId,
|
||||
);
|
||||
|
||||
// Resolve a Vault SSH signer profile (shared settings, no secrets). The
|
||||
// certificate itself is obtained per-user at connect time via Vault OIDC.
|
||||
if (host.vaultProfileId && sharedAuthResolution !== "recipient-override") {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { HostSessionStatus } from "./host-session-status.js";
|
||||
|
||||
describe("HostSessionStatus", () => {
|
||||
it("reports only the first connection and last disconnection per host", () => {
|
||||
const status = new HostSessionStatus();
|
||||
const listener = vi.fn();
|
||||
status.subscribe(listener);
|
||||
|
||||
const closeFirst = status.register(7);
|
||||
const closeSecond = status.register(7);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenLastCalledWith(7, true);
|
||||
|
||||
closeFirst();
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
|
||||
closeSecond();
|
||||
expect(listener).toHaveBeenLastCalledWith(7, false);
|
||||
expect(listener).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("makes connection cleanup idempotent", () => {
|
||||
const status = new HostSessionStatus();
|
||||
const listener = vi.fn();
|
||||
status.subscribe(listener);
|
||||
|
||||
const close = status.register(9);
|
||||
close();
|
||||
close();
|
||||
|
||||
expect(listener.mock.calls).toEqual([
|
||||
[9, true],
|
||||
[9, false],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
type HostSessionStatusListener = (hostId: number, online: boolean) => void;
|
||||
|
||||
export class HostSessionStatus {
|
||||
private counts = new Map<number, number>();
|
||||
private listeners = new Set<HostSessionStatusListener>();
|
||||
|
||||
register(hostId: number): () => void {
|
||||
const count = this.counts.get(hostId) ?? 0;
|
||||
this.counts.set(hostId, count + 1);
|
||||
if (count === 0) this.emit(hostId, true);
|
||||
|
||||
let active = true;
|
||||
return () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
|
||||
const next = (this.counts.get(hostId) ?? 1) - 1;
|
||||
if (next > 0) {
|
||||
this.counts.set(hostId, next);
|
||||
return;
|
||||
}
|
||||
|
||||
this.counts.delete(hostId);
|
||||
this.emit(hostId, false);
|
||||
};
|
||||
}
|
||||
|
||||
subscribe(listener: HostSessionStatusListener): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
private emit(hostId: number, online: boolean): void {
|
||||
for (const listener of this.listeners) listener(hostId, online);
|
||||
}
|
||||
}
|
||||
|
||||
export const hostSessionStatus = new HostSessionStatus();
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Auth types whose SSH certificate is issued on demand through a browser
|
||||
* sign-in and cached per user and host (opkssh_tokens). They share the
|
||||
* whole connect path; only the issuing flow differs.
|
||||
*/
|
||||
export const ISSUED_CERTIFICATE_AUTH_TYPES = ["opkssh", "stepca"] as const;
|
||||
|
||||
export function usesIssuedCertificate(authType: string | null | undefined) {
|
||||
return (ISSUED_CERTIFICATE_AUTH_TYPES as readonly string[]).includes(
|
||||
authType ?? "",
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,9 @@
|
||||
* automations layer must never disturb metric collection, and a static import
|
||||
* would create a cycle (automations reads repositories, which the metrics
|
||||
* module also pulls in).
|
||||
*
|
||||
* For the generic (non-metrics) internal event notifier, see
|
||||
* `hosts/automation-events.ts` -- that one is shared across features.
|
||||
*/
|
||||
|
||||
import type { MetricsSnapshot } from "../../automations/conditions.js";
|
||||
@@ -46,17 +49,3 @@ export function notifyAutomationHealthCheck(
|
||||
)
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
export function notifyAutomationInternalEvent(
|
||||
event: string,
|
||||
userId: string,
|
||||
hostId?: number,
|
||||
details?: Record<string, unknown>,
|
||||
): void {
|
||||
if (!userId) return;
|
||||
import("../../automations/triggers.js")
|
||||
.then((triggers) =>
|
||||
triggers.onInternalEvent({ event, userId, hostId, details }),
|
||||
)
|
||||
.catch(() => {});
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Client } from "ssh2";
|
||||
import { usesIssuedCertificate } from "../issued-certificate-auth.js";
|
||||
|
||||
export type StatsCapableHost = {
|
||||
connectionType?: string;
|
||||
@@ -13,7 +14,8 @@ export type TcpPingStatsConfig = {
|
||||
export function supportsMetrics(host: StatsCapableHost): boolean {
|
||||
const connectionType = host.connectionType || "ssh";
|
||||
if (connectionType !== "ssh") return false;
|
||||
if (host.authType === "none" || host.authType === "opkssh") return false;
|
||||
if (host.authType === "none" || usesIssuedCertificate(host.authType))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
isHostKeyVerificationError,
|
||||
statusAfterAuthentication,
|
||||
statusAfterReachabilityCheck,
|
||||
} from "./host-status.js";
|
||||
|
||||
describe("isHostKeyVerificationError", () => {
|
||||
it.each([
|
||||
"Host denied (verification failed)",
|
||||
"Host key changed - please connect via Terminal to verify the new key",
|
||||
])("classifies %s", (message) => {
|
||||
expect(isHostKeyVerificationError(new Error(message))).toBe(true);
|
||||
});
|
||||
|
||||
it("does not classify ordinary authentication failures", () => {
|
||||
expect(isHostKeyVerificationError(new Error("Permission denied"))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("host availability status", () => {
|
||||
it("does not call a TCP-reachable host online before authentication", () => {
|
||||
expect(statusAfterReachabilityCheck(true)).toBe("reachable");
|
||||
|
||||
Loaded 100 of 692 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user