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:
692 files changed
+334737 -5210

No files matched your search

@@ -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;
+140 -17
View File
@@ -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;
+75 -15
View File
@@ -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 });
}
+322 -28
View File
@@ -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 -1
View File
@@ -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, "&amp;")
.replace(/</g, "&lt;")
@@ -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;
}
+35 -22
View File
@@ -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,
+523 -8
View File
@@ -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();
+22 -23
View File
@@ -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;
+49 -7
View File
@@ -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(
+32 -1
View File
@@ -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),
+33 -3
View File
@@ -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);