release-2.9.0 (#1532)

* fix(macos): skip single-instance lock in Mac App Store builds (#1454)

fix(macos): skip single-instance lock in Mac App Store builds

* Fix/backend optional sharp (#1455)

Fix/backend optional sharp

* feat: issue #1218 (#1218)

https://github.com/Termix-SSH/Support/issues/1218

* feat: Add option to use saved global custom theme under Connection Defaults (#1209)

https://github.com/Termix-SSH/Support/issues/1209

* feat: Add Fleet Sharing functionality to the UI (#1228)

https://github.com/Termix-SSH/Support/issues/1228

* feat: Add a list view to the Docker management page (#1237)

https://github.com/Termix-SSH/Support/issues/1237

* feat: issue #1264 (#1264)

https://github.com/Termix-SSH/Support/issues/1264

* feat: 2FA With FortiToken (#1288)

https://github.com/Termix-SSH/Support/issues/1288

* feat: Allow to disable showing paths to folders (#1274)

https://github.com/Termix-SSH/Support/issues/1274

* feat: Sync Network Graph between Desktop and Remote Server (#1245)

https://github.com/Termix-SSH/Support/issues/1245

* feat: Version Number on offline servers (#1291)

https://github.com/Termix-SSH/Support/issues/1291

* feat: Support OrbStack Docker socket path on macOS / Fix "Docker is not installed" on mac... (#1302)

https://github.com/Termix-SSH/Support/issues/1302

* feat: Sidebar host click should focus existing tab instead of opening a new connection (#1289)

https://github.com/Termix-SSH/Support/issues/1289

* fix: Search in side bar shows overlapping hosts when grouped by tags (#1303)

https://github.com/Termix-SSH/Support/issues/1303

* fix: I can't send a file on its own. (#1304)

https://github.com/Termix-SSH/Support/issues/1304

* fix: sudo password not autofilling (#1248)

https://github.com/Termix-SSH/Support/issues/1248

* fix: node-MainThread (#1300)

https://github.com/Termix-SSH/Support/issues/1300

* fix: Tunnel authentication with shared credentials (#1295)

https://github.com/Termix-SSH/Support/issues/1295

* fix: host key updates not syncing, metrics 404 race on first connect

Host key writes never bumped updatedAt so sync never picked them up.
Also retry the first metrics fetch briefly instead of failing right away.

* chore: increment ver

* feat: add category and icon fields to plugin manifest schema

* ci(deps): bump the github-actions group with 2 updates (#1458)

Bumps the github-actions group with 2 updates: [crowdin/github-action](https://github.com/crowdin/github-action) and [actions/github-script](https://github.com/actions/github-script).


Updates `crowdin/github-action` from 2 to 3
- [Release notes](https://github.com/crowdin/github-action/releases)
- [Commits](https://github.com/crowdin/github-action/compare/v2...v3)

Updates `actions/github-script` from 7 to 9
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v7...v9)

---
updated-dependencies:
- dependency-name: crowdin/github-action
  dependency-version: '3'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: actions/github-script
  dependency-version: '9'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

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 13 updates (#1459)

Bumps the dev-patch-updates group with 13 updates:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/commands](https://github.com/codemirror/commands) | `6.11.0` | `6.11.1` |
| [@codemirror/search](https://github.com/codemirror/search) | `6.7.1` | `6.7.2` |
| [@codemirror/view](https://github.com/codemirror/view) | `6.43.9` | `6.43.12` |
| [@testing-library/dom](https://github.com/testing-library/dom-testing-library) | `10.4.1` | `10.4.2` |
| [@testing-library/react](https://github.com/testing-library/react-testing-library) | `16.3.2` | `16.3.3` |
| [@testing-library/user-event](https://github.com/testing-library/user-event) | `14.6.5` | `14.6.7` |
| [@types/ssh2](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/ssh2) | `1.15.5` | `1.15.6` |
| [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.1.0` | `6.1.1` |
| [cytoscape](https://github.com/cytoscape/cytoscape.js) | `3.34.1` | `3.34.3` |
| [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.4` | `0.5.7` |
| [i18next](https://github.com/i18next/i18next) | `26.4.0` | `26.4.2` |
| [prettier](https://github.com/prettier/prettier) | `3.9.6` | `3.9.8` |
| [react-i18next](https://github.com/i18next/react-i18next) | `17.0.12` | `17.0.14` |


Updates `@codemirror/commands` from 6.11.0 to 6.11.1
- [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/commands/commits)

Updates `@codemirror/search` from 6.7.1 to 6.7.2
- [Changelog](https://github.com/codemirror/search/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/search/commits)

Updates `@codemirror/view` from 6.43.9 to 6.43.12
- [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/view/commits)

Updates `@testing-library/dom` from 10.4.1 to 10.4.2
- [Release notes](https://github.com/testing-library/dom-testing-library/releases)
- [Changelog](https://github.com/testing-library/dom-testing-library/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/dom-testing-library/compare/v10.4.1...v10.4.2)

Updates `@testing-library/react` from 16.3.2 to 16.3.3
- [Release notes](https://github.com/testing-library/react-testing-library/releases)
- [Changelog](https://github.com/testing-library/react-testing-library/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/react-testing-library/compare/v16.3.2...v16.3.3)

Updates `@testing-library/user-event` from 14.6.5 to 14.6.7
- [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.5...v14.6.7)

Updates `@types/ssh2` from 1.15.5 to 1.15.6
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/ssh2)

Updates `@vitejs/plugin-react` from 6.1.0 to 6.1.1
- [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.1/packages/plugin-react)

Updates `cytoscape` from 3.34.1 to 3.34.3
- [Release notes](https://github.com/cytoscape/cytoscape.js/releases)
- [Commits](https://github.com/cytoscape/cytoscape.js/compare/v3.34.1...v3.34.3)

Updates `eslint-plugin-react-refresh` from 0.5.4 to 0.5.7
- [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.4...v0.5.7)

Updates `i18next` from 26.4.0 to 26.4.2
- [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.4.0...v26.4.2)

Updates `prettier` from 3.9.6 to 3.9.8
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.9.6...3.9.8)

Updates `react-i18next` from 17.0.12 to 17.0.14
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/react-i18next/compare/v17.0.12...v17.0.14)

---
updated-dependencies:
- dependency-name: "@codemirror/commands"
  dependency-version: 6.11.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@codemirror/search"
  dependency-version: 6.7.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@codemirror/view"
  dependency-version: 6.43.12
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@testing-library/dom"
  dependency-version: 10.4.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@testing-library/react"
  dependency-version: 16.3.3
  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.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@types/ssh2"
  dependency-version: 1.15.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.1.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: cytoscape
  dependency-version: 3.34.3
  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.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: i18next
  dependency-version: 26.4.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: prettier
  dependency-version: 3.9.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: react-i18next
  dependency-version: 17.0.14
  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 6 updates (#1461)

Bumps the prod-patch-updates group with 6 updates:

| Package | From | To |
| --- | --- | --- |
| [@tanstack/react-virtual](https://github.com/TanStack/virtual/tree/HEAD/packages/react-virtual) | `3.14.10` | `3.14.13` |
| [compression](https://github.com/expressjs/compression) | `1.8.1` | `1.8.2` |
| [jose](https://github.com/panva/jose) | `6.2.9` | `6.2.12` |
| [jszip](https://github.com/Stuk/jszip) | `3.10.1` | `3.10.2` |
| [socks](https://github.com/JoshGlazebrook/socks) | `2.8.9` | `2.8.10` |
| [undici](https://github.com/nodejs/undici) | `8.10.0` | `8.10.2` |


Updates `@tanstack/react-virtual` from 3.14.10 to 3.14.13
- [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.13/packages/react-virtual)

Updates `compression` from 1.8.1 to 1.8.2
- [Release notes](https://github.com/expressjs/compression/releases)
- [Changelog](https://github.com/expressjs/compression/blob/master/HISTORY.md)
- [Commits](https://github.com/expressjs/compression/compare/v1.8.1...v1.8.2)

Updates `jose` from 6.2.9 to 6.2.12
- [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.9...v6.2.12)

Updates `jszip` from 3.10.1 to 3.10.2
- [Changelog](https://github.com/Stuk/jszip/blob/main/CHANGES.md)
- [Commits](https://github.com/Stuk/jszip/compare/v3.10.1...v3.10.2)

Updates `socks` from 2.8.9 to 2.8.10
- [Release notes](https://github.com/JoshGlazebrook/socks/releases)
- [Commits](https://github.com/JoshGlazebrook/socks/compare/2.8.9...2.8.10)

Updates `undici` from 8.10.0 to 8.10.2
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v8.10.0...v8.10.2)

---
updated-dependencies:
- dependency-name: "@tanstack/react-virtual"
  dependency-version: 3.14.13
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: compression
  dependency-version: 1.8.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: jose
  dependency-version: 6.2.12
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: jszip
  dependency-version: 3.10.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: socks
  dependency-version: 2.8.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: prod-patch-updates
- dependency-name: undici
  dependency-version: 8.10.2
  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>

* feat: add plugin worker protocol, bootstrap and plugin_storage table

Worker-side ctx proxy plus the message envelope it talks over, and the
per-plugin key/value table behind ctx.storage with migrations for all
three dialects. Rows cascade with the plugin so uninstalling leaves
nothing behind.

* feat: add allowlisted host view for plugins

An allowlist rather than a list of fields to strip. A blocklist rots:
the moment a new secret-bearing column lands on SSHHost it starts
leaking silently. With an allowlist a new field stays invisible to
plugins until someone adds it here on purpose.

* feat: add plugin loader with manifest validation and crash restart

Validates an unpacked plugin, spawns a worker_threads worker and manages
activate/deactivate/crash-restart with backoff, disabling after three
tries.

The crash counter clears only after a plugin stays up past a stability
window, not on activation. Clearing it on activation let a plugin that
activates cleanly and then dies restart forever, because every attempt
looked like the first.

loader.ts documents what the worker boundary does and does not buy you.
Node's permission model is process-wide, not per-worker, so it cannot be
enabled for plugin workers alone and is not claimed here.

* feat: route internal events through a shared plugin event bus

Formalises three ad-hoc publish paths that already existed:
automation-events.ts, metrics/automation-bridge.ts and the
hostSessionStatus singleton, now the host.session.status topic.

Both invariants the old code relied on are preserved. Publishing stays
fire-and-forget, so a failing subscriber cannot disturb a metrics poll or
a host delete. The automations engine subscribes to the bus at scheduler
start instead of being imported ad hoc, which keeps the edge
one-directional: automations may import repositories, hosts modules must
not import automations.

* feat: add plugin ctx broker with permission gate and audit

Every ctx call a plugin makes is checked against its granted
capabilities, performed by the main thread, then audited. A capability
must be both declared in the manifest and granted in the database, so
widening a plugin's reach always needs a new manifest the user can see,
never just a database row.

Audit attribution is set by the broker, not the plugin. The plugin
supplies only the details, so it cannot forge the actor.

fix: stop plugin workers seeing plaintext credentials in error messages

A failing ctx.ssh.connect handed the worker the raw error from deep in
the SSH stack, which embeds the connect config. The worker received, in
full:

  Authentication failed for root using password <SECRET>

where <SECRET> was the host's real plaintext password. Any plugin with
ssh.exec could read it by catching the error, defeating the whole point
of the handle-based ssh API.

Errors crossing the boundary are now sanitised. Only PluginFacingError
and PluginPermissionError, both authored here, reach a plugin verbatim;
anything else becomes a generic message and the real one goes to the
log. This uses a marker class rather than matching on message text,
because matching would start leaking again the moment an upstream error
happened to contain a familiar phrase.

Covered by credential-isolation.test.ts, which plants a sentinel in
every secret-bearing field and asserts it appears in no message the
worker ever receives.

* feat: dispatch plugin HTTP routes and wire the runtime into startup

ctx.http.route now registers a real router on the /plugin-api/:pluginId
dispatcher, replacing its stub 404. A plugin never touches the Express
req/res: it gets a plain summary and returns a plain object, so sockets
and session cookies stay on this side of the boundary. Authorization and
cookie headers are not forwarded.

Plugins load last in the start-up sequence, after the server is fully
wired, and are terminated before the database on shutdown so none can
outlive it. A plugin that fails to load cannot stop the backend.

fix: correct the nginx plugin-api location regex

The pattern was ^/plugin-api/(/.*)?$, which needs a double slash and so
never matched /plugin-api/<id>/<route>. Every other block in the file
uses ^/prefix(/.*)?$. Left alone, plugin routes would work in dev and
404 only behind Docker.

* fix: update stale SFTP transfer test for single file destination paths

The test still asserted transferToHost was called with the destination
directory "/srv". Commit 7727fa09 (#1304) deliberately changed a single
file transfer to send the full destination path including the filename,
so the correct expectation is "/srv/remote-1.txt". The code was right
and the test was left behind.

* feat: ship the ssh terminal as a first-party in-process plugin

Adds a hardcoded process:transport-owner tier so the terminal can own its
WebSocket server and ssh2 clients, which cannot cross the worker boundary.

* feat: ship docker as a first-party in-process plugin

Moves docker backend and frontend into plugins/docker/, alongside
ssh-terminal. Adds a host editor tab seam, a dashboard card registry,
and a build step to compile plugin backends into dist.

* feat: ship host metrics as a first-party in-process plugin

* fix: harden plugin auth and add per-request identity for ctx calls

Require auth on /plugin-api, gate plugin enable/grant/revoke routes
behind admin.plugins.manage, and thread the calling user through
worker ctx.hosts/ctx.ssh calls instead of always using the install
owner. Also adds the plugin permissions grant/revoke UI.

* feat: ship the AI assistant as a first-party in-process plugin

Moves src/backend/ai and its routes into plugins/ai, mounted through a
small /ai dispatcher instead of its own port. Moves the ai-enabled and
ai-private-endpoints settings routes out of user-settings-routes.ts
into the plugin too, so it has no leftover core dependents.

* fix: remove compiled plugin JS left behind in plugins/ after build

copy-bundled-plugins.cjs compiled and rewrote plugin backend TS in
place, copied it to dist/plugins, but never deleted the .js it had
just emitted next to the .ts sources. Those files shadowed the real
source for vitest/tsx and had import paths rewritten for the dist
layout, so tests failed with "Cannot find module" once a local build
had run. Affects docker, host-metrics and ai, not just this one.

* feat: add a permission-gated backend service registry for plugins

* feat: add a permission-gated UI action registry and action slots for plugins

Moves the terminal toolbar's hardwired AI button into a slot the ssh-terminal
plugin offers and the ai plugin fills, gated on ai.services.use.

* feat: add cross-plugin secret references gated by the provider's RBAC permission

* feat: move proxmox discovery/import/sync into a first-party plugin

* feat: move remote desktop (RDP/VNC/Telnet) into a first-party plugin

Relocates guacamole backend/frontend source and tests into
plugins/remote-desktop, following the ssh-terminal/docker pattern.

* feat: wire remote-desktop plugin into core and rename i18n keys

Repoints core consumers (dispatcher, collab, session-sharing, tab
utils) at the plugin, adds isTabTypeAvailable gating for rdp/vnc/
telnet, widens hostCapability to accept an array, and renames the
guacamole i18n namespace to remoteDesktop.

* feat: move fleets into a first-party plugin

* feat: move automations into a first-party plugin

* feat: remove legacy alert rules, superseded by automations

Alert rules already auto-migrate into automations on boot and the old
engine stands down after. Deletes the rule/firing tables, routes, UI,
and AI tools; keeps notification channels since automations still use
them. Also fixes automations' notify step, which still called the
deleted repository.

* feat: move network topology into a first-party plugin

* feat: move tailscale device discovery and settings into a plugin

Adds plugins/tailscale/ with a devices sidebar tab, admin settings
section, and re-auth dialog. Host Metrics tailscale manager card and
SSH re-auth banner parsing stay in core.

* feat: move workspaces into a first-party plugin

* feat: move web endpoint into a first-party plugin

* feat: collapse plugin runtime to one tier behind a plugin SDK

* feat: make each plugin an npm workspace built by a termix-plugin CLI

* feat: give plugins their own tables, migrations and sync entities

* feat: serve plugin http and websockets from one mount instead of ports

* feat: namespace plugin permissions and keep them valid when a plugin is off

* feat: give plugins their own settings and one settings screen

* feat: load plugin frontends at runtime and remove plugin ids from the shell

* fix: mock the ai status fetch in its activate test

* feat: add auth extension points and one ssh connect pipeline

* feat: rebuild workspaces as the reference plugin

* fix: gate second factors after SSO/LDAP behind an admin setting

* feat: convert network-topology to a full plugin (B1)

* feat: move snippets backend and tables into a plugin (B2)

* feat: point core frontend snippets pickers at the plugin (B2)

* feat: add the snippets plugin (B2)

* feat: wire ai, automations, fleets and ssh-terminal to snippets (B2)

* feat: finish the tailscale plugin, including SSH auth (B3)

* feat: finish the fleets plugin, add ctx.hosts and host-commands SDK (B4)

* chore: update proxmox and host-metrics locale files for B5

* chore: regenerate drizzle migration journals for B5

* feat: add ctx.hosts create/update to the SDK, host-metrics drops proxmox

* feat: move proxmox node stats and collectors into the proxmox plugin

* feat: drop proxmox host columns, use plugin settings instead

* feat: finish the fleets plugin, add ctx.hosts and host-commands SDK (B4)

* feat: convert file manager into a plugin

* feat: convert ssh tunnels into a plugin

* feat: finish the web-endpoint plugin, add ctx.desktop (B8)

* feat: move the terminal fully into the ssh-terminal plugin (B9)

* feat: convert tmux monitoring into a plugin (B10)

* feat: convert serial console into the serial plugin

* feat: move session sharing and collab rooms into a plugin (B12)

* feat: turn session recording into a plugin (B13)

* feat: finish the remote-desktop plugin (B14)

* feat: finish the host-metrics plugin, move host status into core (B16)

* feat: finish the docker plugin (B15)

* feat: finish the automations plugin (B17)

* feat: finish the ai plugin (B18)

* feat: finish the homepage plugin, move service links and canvas out of core (B19)

* feat: convert wake-on-lan into a plugin (B20)

* feat: convert secret-sources into a plugin (B20)

* feat: move totp and passkeys into plugins (C1)

* feat: move sso and ldap logins into plugins (C2)

* feat: move opkssh and warpgate into plugins (C3)

* feat: move step-ca into a plugin (C4)

* feat: move vault ssh signing into a plugin (C5)

* feat: move termix identity into a plugin (C6)

* feat: move acme certificate automation into a plugin (C7)

* fix: finish 2.9.0 plugin moves and get every check green

* chore: lock the plugin boundary and remove 2.9.0 leftovers

* fix: harden the plugin runtime after the 2.9.0 security review

* feat: add plugin packing, signing, pinned trust and tmxplug bundling

* test: prove 2.8 to 2.9.0 upgrade is lossless and fix what it caught

* fix: give bundled plugin backends a real require for CJS deps

* feat: improve UI loading time and jitter

* feat: show credential sharing inline in the sidebar like host sharing

* feat: tailscale add host and copy ip, fix outbound fetch hang and plugin ESM warning

* feat: unify alerts into one plugin, channels, rules and inbox

* feat: rebuild desktop sync as linked server accounts, fix packaged plugin bundles and UI scaling

* fix: set blacksmith builder cache-key to stop broken gha cache fallback

* fix: link plugin-sdk workspace before npm ci in docker deps stage

* fix: link every plugin workspace before npm ci in docker deps stage

* fix(host-metrics): exclude image and firmware filesystems (#1469)

* fix(host-metrics): exclude image and firmware filesystems

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(hosts): normalize imported jump host references (#1470)

* fix(hosts): normalize imported jump host references

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(ci): build plugin SDK and repair MySQL settings migration (#1471)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(file-manager): keep inline rename consistent (#1476)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(file-manager): keep inline rename consistent

* fix(dashboard): reuse translated host status labels (#1475)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(dashboard): reuse translated host status labels

* docs(api): clarify local and remote version fields (#1474)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* docs(api): clarify local and remote version fields

* fix(file-manager): preserve selected backgrounds on hover (#1473)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(file-manager): preserve selection feedback on hover

* test(ui): await dialog focus cleanup before teardown

* fix(file-manager): restore Ctrl/Cmd+F file search (#1472)

* fix(ci): build plugin SDK before dependent checks

* fix(mysql): keep plugin settings scope indexes within limits

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(file-manager): focus file search with Ctrl or Cmd F

* fix: keep rounded-full circular in production builds

* fix(file-manager): cancel uploads and stop remote writes (#1477)

* fix(file-manager): cancel uploads and stop remote writes

* test(css): exercise the configured PostCSS plugin chain

* fix(file-manager): apply compact density to directory tree (#1478)

* fix(file-manager): apply compact density to directory tree

* test(css): exercise the configured PostCSS plugin chain

* fix(file-manager): preserve font sizes in compact mode (#1480)

* fix(file-manager): preserve font sizes in compact mode

* test(css): exercise the configured PostCSS plugin chain

* fix(file-manager): prioritize file names in narrow lists (#1483)

* fix(file-manager): prioritize file names in narrow lists

* test(css): exercise the configured PostCSS plugin chain

* test(identity): preserve full Ed25519 public keys in fixtures

* test(remote-desktop): always mutate ciphertext in tamper test

* fix(remote-desktop): probe the saved host guacd endpoint (#1481)

* fix(remote-desktop): probe the saved host guacd endpoint

* test(css): exercise the configured PostCSS plugin chain

* test(identity): preserve full Ed25519 public keys in fixtures

* fix(homepage): check allowlisted private service reachability (#1479)

* fix(homepage): check allowlisted private service reachability

* test(css): exercise the configured PostCSS plugin chain

* fix(remote-desktop): stop unsolicited clipboard read prompts (#1482)

* fix(remote-desktop): read clipboard only on explicit paste

* test(css): exercise the configured PostCSS plugin chain

* test(identity): preserve full Ed25519 public keys in fixtures

* test(remote-desktop): always mutate ciphertext in tamper test

* chore: simplify plugin readmes, changelogs and manifest descriptions

* fix: keep plugins loaded after signing in from the login screen

* fix(file-manager): accept OS file drops over existing rows (#1484)

* fix(file-manager): accept OS file drops over existing rows

* test(file-manager): target the file label in drop tests

* test(css): exercise the configured PostCSS plugin chain

* test(identity): preserve full Ed25519 public keys in fixtures

* test(remote-desktop): always mutate ciphertext in tamper test

* fix(file-manager): pipeline SFTP download reads (#1485)

* feat: add plugin sdk build to beta release

* fix: make link-store secret check immune to random base64 matches

* fix(ldap): preserve the directory-provided bind DN (#1486)

* fix: compute beta changes across dev branches and move the beta tag

* chore: untrack plugin sdk ARCHITECTURE.md

* chore: remove references to plugin sdk ARCHITECTURE.md

* feat: merge host editor terminal tabs into one owned by ssh-terminal

* feat: add descriptions to plugin host enable toggles

* fix(file-manager): show download progress in file viewers (#1487)

* fix(electron): signal backend readiness over IPC (#1488)

* fix(split-screen): allow layout creation without randomUUID (#1490)

* fix(split-screen): allow layout creation without randomUUID

* test(credentials): avoid flaky Ed25519 key generation

* fix(sidebar): remeasure visible rows after density changes (#1489)

* fix(sidebar): remeasure visible rows after density changes

* test(credentials): avoid flaky Ed25519 key generation

* feat(split-screen): redesign split screen with free-form panes and pane picker

* feat(sidebar): add host click behavior setting, default to always opening a new tab

* feat(snippets): redesign panel to match the host list

* fix(session-recording): stop session logs panel from refetching in a loop

* feat(snippets): bring back sharing, target hosts and drag reorder

* feat(ssh-terminal): add toolbar position, start state, display and fade host settings

* feat(ssh-terminal): add host setting to turn off password prompt auto-fill

* fix(ai): stop streams getting cut off and keep tool steps across messages

* feat: improve quick connect system using plugin api

* fix: proxmox guest sync, startup snippet sync, drop dead cloudflare ssh transport

* feat: move terminal settings, look and ssh tools into ssh-terminal plugin

* feat: move snippets, keybinding actions and macros out of core into plugins

* feat: store rdp, vnc and telnet logins in a generic per-protocol table

* feat: type the plugin host record, move plugin strings out of core and add lint checks

* feat: replace core homepage widget registry with generic extension points

* feat: plugins only see their own host settings in the browser

* feat: harden plugin api for separate repos, signed updates and generic external login

* fix: keep plugin css below core utilities and version plugin assets by their css

* fix: load and save plugin host settings in the editor and tighten settings row spacing

* feat: redesign user host defaults system

* fix(remote-desktop): release held keys on focus loss (#1498)

* fix(session-sharing): replace local presentation after takeover (#1500)

* fix(file-manager): refresh disk usage with directory listing (#1503)

* fix(ssh-terminal): preserve input order during local echo reconciliation (#1505)

* feat(remote-desktop): expose display zoom controls for RDP (#1514)

* fix(file-manager): restore text selection and copying in Markdown previews (#1518)

* fix(sidebar): keep compact host addresses visible (#1524)

* fix(hosts): preserve plugin settings when reopening the editor (#1499)

* fix(ssh-terminal): close owner sockets when presentations unmount (#1501)

* fix(session-sharing): synchronize shared SSH terminal dimensions (#1502)

* fix(session-sharing): show participant presence in member terminals (#1504)

* fix(ai): sync provider configuration and keys across linked devices (#1506)

* feat(ssh-terminal): add a duplicate tab action (#1510)

* feat(file-manager): allow disabling move-to-trash confirmation (#1511)

* feat(file-manager): default to the remote login directory (#1512)

* feat(homepage): synchronize canvas layouts across devices (#1515)

* fix(shortcuts): prevent accidental double-Shift palette activation (#1519)

* feat(tmux-monitor): add a unified multi-host view (#1520)

* fix(electron): allow explicit quit with active connections (#1522)

* feat: reconnect all disconnected terminal tabs (#1523)

* fix(hosts): preserve recording and sharing settings in the dev editor (#1509)

* fix(database): preserve RDP domain during startup backfill (#1497)

* feat(sidebar): add keyboard type-ahead search for hosts (#1516)

* feat(automations): add per-host maintenance mode and recurring schedules (#1521)

* feat(tmux): add a per-host mouse toggle and preserve remote configuration (#1513)

* fix(session-sharing): use the linked server for desktop meetings and links (#1507)

* fix(tunnels): support TOTP for client tunnels and jump hosts (#1508)

* fix: type errors and lint failures from merged plugin prs

* feat(installer): make the Windows desktop shortcut optional (#1517)

* fix: ship the plugin sdk and serialport in desktop builds

* fix: prefer ipv4 when resolving ssh host names (#1365)

* fix: readable terminal selection with the light theme (#1319)

* fix: build desktop session share links on the linked server (#1350)

* fix: show meeting guests to members and hide the roster from guests (#1353)

* fix: reliable file manager saves with sudo prompt and no base64 guessing (#1335)

* fix: show disk usage for the mount being browsed (#1347)

* fix: load the linux tray icon reliably and log tray failures (#1332)

* fix: cover the gnome close path in the desktop quit test (#1332)

* fix: prompt for jump host TOTP in terminal, file manager and metrics (#1312)

* feat: optional auto reconnect for dropped ssh sessions (#1321)

* feat: tighter compact host rows with inline tags (#1325)

* feat: bring back the alert feed homepage widget

* feat: pick target terminals for snippets again

* feat: share button on connection tabs again

* feat: recent servers list when linking the desktop app

* feat: list the fixed app shortcuts in keyboard shortcuts

* fix: translate hardcoded toasts and drop em dashes from ui text

* fix: translate leftover hardcoded ui text

* fix: toolbar files button opens at the shell directory again

* fix: show the remote desktop note under connection origin again

* chore: openapi docs for host metrics manager routes

* chore: openapi docs for undocumented routes and fix two broken doc blocks

* fix: declare terminal.listSessions use for snippet targets

* revert: drop the alert feed widget, the notification center replaces it

* feat: restore the alert feed homepage widget

* fix: quick connect fills the host address from plugin auth editors like tailscale

* fix: docker container logs use the base background color

* chore: fix dependabot alerts and apply safe npm upgrades

* fix: proxmox stats tab reads its switch from plugin host settings

* fix: count plugin ssh logins toward host status and stop showing reachable as a warning

* fix: hide the built-in source pill in the host editor

* fix: host status shows online when the port answers and only warns on a failed login

* fix: drop the top border on the split layout menu

* fix: host defaults tabs sit where the host editor puts them and skip plugins with nothing to default

* fix: remote desktop auth method labels and notes for vnc and telnet

* fix: add description to the web endpoint enable switch

* fix: crowdin sync and pretranslate for plugin locales, run plugin tests on release

* feat: move telemetry out of core into a usage statistics plugin

* fix: recent activity card no longer cuts off host names early

* fix: remove duplicate top border on split screen menu

* fix: redesign session log player controls, fix tooltip overlap and drop dot separators

* fix: file manager and sftp text showing raw i18n keys

* fix: onboarding rerunning for existing users after upgrading

* fix: fleet detail buttons overflowing the sidebar

* fix: session log player scrolling off screen horizontally

* fix: network graph lag when adding hosts and on every render

* fix: maintenance index name, shared host read only view and badge polling

* fix: meeting tabs, workspace tab merging, rail panels as tabs and general ui lag

* chore: update release notes

* fix: remote desktop tabs reconnecting on every tab switch

* fix: build plugin sdk before linting in release workflow

* chore: lint, format, and bump version to 2.9.0

* chore: skip crowdin pre-translate in release for now

* chore: sync Crowdin translations for 2.9.0

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Koi <38512047+datlt4@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-10-01 16:20:16 -05:00
1 parent 49fa488093
commit 3643e7af97
4405 files changed
+1341026 -289722

No files matched your search

@@ -0,0 +1,19 @@
import { serializeWebUiConfig } from "../shared/web-endpoint-config.js";
/**
* Registered as ctx.registry.provide("web-endpoint.hostImportNormalizer", ...)
* so host-bulk-routes.ts's Termix-JSON import path can validate this
* plugin's fields without importing anything from the plugin. Matches the
* shape core's PluginHostImportNormalizer type expects.
*/
export function hostImportNormalizer(
raw: Record<string, unknown>,
): Record<string, unknown> | null {
if (raw.enableWebUi === undefined && raw.webUiConfig === undefined) {
return null;
}
return {
enableWebUi: !!raw.enableWebUi,
webUiConfig: raw.webUiConfig ? serializeWebUiConfig(raw.webUiConfig) : null,
};
}
+25
View File
@@ -0,0 +1,25 @@
import type { Router } from "express";
import type { PluginContext } from "@termix/plugin-sdk/backend";
import { createWebEndpointRoutes } from "./routes.js";
import { hostImportNormalizer } from "./host-import.js";
export async function activate(ctx: PluginContext) {
const router = ctx.http.router<Router>();
router.use(createWebEndpointRoutes(ctx));
ctx.registry.provide(
"web-endpoint.hostImportNormalizer",
hostImportNormalizer,
);
ctx.disposables.add(
() =>
void ctx.registry.revoke(
"web-endpoint.hostImportNormalizer",
hostImportNormalizer,
),
);
ctx.log.info("Web Endpoint routes mounted at /plugin-api/web-endpoint");
}
export async function deactivate() {}
+301
View File
@@ -0,0 +1,301 @@
import express, { type Router } from "express";
import type { PluginContext } from "@termix/plugin-sdk/backend";
import {
parseWebUiConfig,
type WebEndpoint,
} from "../shared/web-endpoint-config.js";
/** Matches the spec's ten minutes. */
const WEB_ENDPOINT_IDLE_TIMEOUT_MS = 10 * 60 * 1000;
/** The tunnels plugin, as ctx.services.get("tunnels.access") returns it. */
interface TunnelsAccess {
forward(
sourceHostId: number,
target: {
targetHost: string;
targetPort: number;
bindHost?: string;
bindPort?: number;
},
options?: { name?: string; idleTimeoutMs?: number },
): Promise<{ bindHost: string; bindPort: number }>;
}
/**
* Reserved by the tunnels plugin for on-demand forwards: never retried, and
* the host id in it is what the tunnels plugin checks before letting anyone
* stop one by name.
*/
export function webEndpointTunnelName(
hostId: number,
endpointId: string,
): string {
return `web:${hostId}:${endpointId}`;
}
async function loadEndpoint(
ctx: PluginContext,
hostId: number,
endpointId: string,
): Promise<
{ error: { status: number; message: string } } | { endpoint: WebEndpoint }
> {
const host = await ctx.hosts.get(hostId);
if (!host) {
return {
error: { status: 403, message: "Host not found or access denied" },
};
}
// A bulk update that only flips enableWebUi off can leave stale endpoints
// in webUiConfig. The UI reads as off in that state, so a listed endpoint
// is not on its own a licence to open a tunnel.
const enabled = await ctx.settings.getHost<boolean>(hostId, "enableWebUi");
if (!enabled) {
return {
error: {
status: 400,
message: "Web endpoints are not enabled for this host",
},
};
}
// Re-normalized rather than trusted: the stored value predates any later
// tightening of the rules, and this is the value a forward or a window is
// built from.
const rawConfig = await ctx.settings.getHost(hostId, "webUiConfig");
const endpoint = parseWebUiConfig(rawConfig).endpoints.find(
(candidate) => candidate.id === endpointId,
);
if (!endpoint) {
return { error: { status: 400, message: "Web endpoint not found" } };
}
return { endpoint };
}
async function openTunnel(
ctx: PluginContext,
hostId: number,
endpointId: string,
endpoint: WebEndpoint,
): Promise<{ bindHost: string; bindPort: number }> {
const userId = ctx.currentActor();
let tunnels: TunnelsAccess | undefined;
try {
tunnels = ctx.services.get<TunnelsAccess>("tunnels.access", { userId });
} catch {
tunnels = undefined;
}
// A missing provider hands back an empty handle rather than throwing.
if (typeof tunnels?.forward !== "function") {
throw Object.assign(new Error("The tunnels plugin is not available"), {
status: 503,
});
}
try {
return await tunnels.forward(
hostId,
{
targetHost: "127.0.0.1",
targetPort: endpoint.port,
// Loopback unless the endpoint asks otherwise. A non-loopback bind
// publishes the target's web UI to anyone who can reach the port,
// with no authentication in front of it, and is only ever an
// explicit per-endpoint choice.
bindHost: endpoint.bindHost || "127.0.0.1",
// A fixed port when the endpoint names one, since a container can
// only publish ports it knows in advance. Otherwise the kernel picks.
bindPort: endpoint.localPort ?? undefined,
},
{
name: webEndpointTunnelName(hostId, endpointId),
idleTimeoutMs: WEB_ENDPOINT_IDLE_TIMEOUT_MS,
},
);
} catch (error) {
const reason = error instanceof Error ? error.message : String(error);
ctx.log.error(
`Failed to open web endpoint tunnel for host ${hostId}: ${reason}`,
error instanceof Error ? error : undefined,
);
throw Object.assign(new Error(reason), { status: 502 });
}
}
/** A bare IPv6 literal has to be bracketed to be a legal URL authority. */
function bracketIfIpv6(host: string): string {
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
}
function endpointUrl(
hostAddress: string,
endpoint: WebEndpoint,
localPort?: number,
): string {
const path = endpoint.path && endpoint.path.length > 0 ? endpoint.path : "/";
if (endpoint.access === "tunnel") {
// Electron's isolated window always dials the backend's own loopback,
// exactly like the renderer's own currentTunnelHost(true) does.
return `${endpoint.scheme}://127.0.0.1:${localPort}${path}`;
}
return `${endpoint.scheme}://${bracketIfIpv6(hostAddress)}:${endpoint.port}${path}`;
}
export function createWebEndpointRoutes(ctx: PluginContext): Router {
const router = express.Router();
/**
* @openapi
* /plugin-api/web-endpoint/open:
* post:
* summary: Open a tunnel to a host's web endpoint
* description: For endpoints reached through SSH. Returns the local port the tunnel listens on.
* tags: [Web Endpoint]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required: [hostId, endpointId]
* properties:
* hostId: { type: integer }
* endpointId: { type: string }
* responses:
* 200: { description: The local port. }
* 400: { description: Invalid request, or the endpoint does not use a tunnel. }
* 401: { description: Not signed in. }
* 404: { description: Host or endpoint not found. }
*/
router.post("/open", async (req, res) => {
const userId = ctx.currentActor();
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const { hostId, endpointId } = req.body ?? {};
if (
!Number.isInteger(hostId) ||
hostId < 1 ||
typeof endpointId !== "string"
) {
return res.status(400).json({ error: "Invalid web endpoint request" });
}
// Deliberately NOT gated to the desktop. The forward binds wherever this
// backend runs, and the endpoint's own bindHost decides whether that is
// reachable from the browser.
const resolved = await loadEndpoint(ctx, hostId, endpointId);
if ("error" in resolved) {
return res
.status(resolved.error.status)
.json({ error: resolved.error.message });
}
if (resolved.endpoint.access !== "tunnel") {
return res
.status(400)
.json({ error: "This endpoint does not use a tunnel" });
}
try {
const handle = await openTunnel(
ctx,
hostId,
endpointId,
resolved.endpoint,
);
return res.status(200).json({ port: handle.bindPort });
} catch (error) {
const status = (error as { status?: number }).status ?? 500;
const message = error instanceof Error ? error.message : String(error);
return res.status(status).json({ error: message });
}
});
/**
* Opens the endpoint in an isolated Electron window instead of a tab.
* Every part of the target URL is resolved server-side (the host's own
* declared address for a direct endpoint, or the tunnel port this route
* just opened for a tunnel one) so ctx.desktop.openIsolatedWindow's
* capability check and audit line cover the whole decision, not just the
* final "open a window" step.
*/
/**
* @openapi
* /plugin-api/web-endpoint/open-window:
* post:
* summary: Open a host's web endpoint in a desktop window
* tags: [Web Endpoint]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required: [hostId, endpointId]
* properties:
* hostId: { type: integer }
* endpointId: { type: string }
* ignoreCert: { type: boolean, description: Accept a self-signed certificate for this window. }
* responses:
* 200: { description: The window opened. }
* 400: { description: Invalid request. }
* 401: { description: Not signed in. }
* 404: { description: Host not found or access denied. }
*/
router.post("/open-window", async (req, res) => {
const userId = ctx.currentActor();
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
}
const { hostId, endpointId, ignoreCert } = req.body ?? {};
if (
!Number.isInteger(hostId) ||
hostId < 1 ||
typeof endpointId !== "string"
) {
return res.status(400).json({ error: "Invalid web endpoint request" });
}
const resolved = await loadEndpoint(ctx, hostId, endpointId);
if ("error" in resolved) {
return res
.status(resolved.error.status)
.json({ error: resolved.error.message });
}
const { endpoint } = resolved;
try {
let localPort: number | undefined;
if (endpoint.access === "tunnel") {
const handle = await openTunnel(ctx, hostId, endpointId, endpoint);
localPort = handle.bindPort;
}
const host = await ctx.hosts.get(hostId);
if (!host) {
return res
.status(403)
.json({ error: "Host not found or access denied" });
}
const url = endpointUrl(host.ip, endpoint, localPort);
const result = await ctx.desktop.openIsolatedWindow({
url,
title: endpoint.label,
ignoreCert: endpoint.access === "direct" && ignoreCert === true,
});
return res.status(200).json(result);
} catch (error) {
const status = (error as { status?: number }).status ?? 502;
const message = error instanceof Error ? error.message : String(error);
return res.status(status).json({ error: message });
}
});
return router;
}
@@ -0,0 +1,523 @@
import { useEffect, useState } from "react";
import { Globe } from "lucide-react";
import {
useTranslation,
type HostEditorSectionProps,
} from "@termix/plugin-sdk/frontend";
import {
Button,
Checkbox,
FakeSwitch,
Input,
SectionCard,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
SettingRow,
} from "@termix/plugin-sdk/ui";
import { resolveConnectionOrigin } from "@termix/plugin-sdk/ui";
import { isElectron } from "@termix/plugin-sdk/ui";
import {
MAX_WEB_ENDPOINTS,
MAX_WEB_ENDPOINT_LABEL_LENGTH,
type WebEndpoint,
} from "../shared/web-endpoint-config";
import {
webEndpointRefusalReason,
type WebEndpointRefusalReason,
} from "./web-endpoint-url";
import {
MAX_WEB_ENDPOINT_PORT,
MIN_WEB_ENDPOINT_PORT,
isWebEndpointPortValid,
webEndpointErrorKey,
webEndpointRowError,
} from "./web-endpoint-validation";
type PluginSettingsForm = Record<string, Record<string, unknown>>;
/**
* crypto.randomUUID is undefined outside a secure context, so a plain-http web
* deployment -- a first-class target for the direct+external path -- would
* throw on "Add endpoint".
*/
function endpointId(): string {
return typeof crypto.randomUUID === "function"
? crypto.randomUUID()
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
}
// Only the tunnel-bind reasons render here; this preview sits inside the
// tunnel-access block. The direct cookie refusal is enforced at open time in
// WebEndpointTab / openWebEndpointExternally, where the target host is known.
const BIND_HOST_REFUSAL_MESSAGES: Record<
Exclude<WebEndpointRefusalReason, "direct-shares-session-cookie">,
string
> = {
"loopback-bind-on-remote-backend": "hosts.webUiBindHostUnreachable",
"shares-session-cookie-with-termix": "hosts.webUiBindHostSharesSessionCookie",
};
/**
* True when the bind address reaches beyond the machine running the backend. A
* forward bound there serves the target's web UI to anyone who can reach the
* port, with no authentication in front of it, so the editor says so plainly
* rather than leaving it to be discovered.
*/
function isExposedBindHost(bindHost: string | undefined): boolean {
const value = (bindHost ?? "").trim();
if (!value) return false;
return !["127.0.0.1", "localhost", "::1", "[::1]"].includes(
value.toLowerCase(),
);
}
function newEndpoint(label: string): WebEndpoint {
return {
id: endpointId(),
label,
scheme: "https",
port: 443,
path: "/",
access: "direct",
render: "embedded",
};
}
/**
* The host editor's Web UI tab. Writes into the form's pluginSettings for
* this plugin, which the editor saves through the plugin's host settings
* route after the host itself, exactly as the tunnels plugin's own section
* does.
*
* Owns the async connection-origin resolution for the tunnel gate itself
* (tunnelAvailable = enableSsh && originIsLocal), deliberately NOT gated on
* isElectron(): the forward binds wherever the backend runs, exactly as the
* tunnels plugin does, and a web deployment reaches it at the host serving
* Termix provided the endpoint opted out of a loopback bind.
*
* connectionType is passed as "ssh" deliberately: a tunnel endpoint always
* rides an SSH connection, and "ssh" keeps resolveConnectionOrigin out of its
* RDP/VNC/Telnet guacamole special case, which always resolves to "remote".
*
* Note the deliberate asymmetry with the sidebar: the sidebar entry appears 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, not an oversight.
*/
export function HostEditorWebUiSection({
form,
updateForm,
protocols,
}: HostEditorSectionProps) {
const { t } = useTranslation();
const [originIsLocal, setOriginIsLocal] = useState(false);
const connectionOrigin = (form?.connectionOrigin as string | null) ?? null;
useEffect(() => {
let cancelled = false;
void resolveConnectionOrigin({
connectionOrigin: connectionOrigin as "local" | "remote" | null,
}).then((origin) => {
if (!cancelled) setOriginIsLocal(origin === "local");
});
return () => {
cancelled = true;
};
}, [connectionOrigin]);
const tunnelAvailable = protocols.enableSsh && originIsLocal;
const settings = ((form?.pluginSettings as PluginSettingsForm | undefined)?.[
"web-endpoint"
] ?? {}) as Record<string, unknown>;
const enableWebUi = settings.enableWebUi === true;
const webUiConfig = (settings.webUiConfig ?? { endpoints: [] }) as {
endpoints: WebEndpoint[];
};
const endpoints = webUiConfig.endpoints ?? [];
const setSettings = (patch: Record<string, unknown>) =>
updateForm((current) => {
const all = (current.pluginSettings ?? {}) as PluginSettingsForm;
return {
...current,
pluginSettings: {
...all,
"web-endpoint": { ...(all["web-endpoint"] ?? {}), ...patch },
},
};
});
const commit = (next: WebEndpoint[]) =>
setSettings({ webUiConfig: { endpoints: next } });
const update = (index: number, patch: Partial<WebEndpoint>) =>
commit(
endpoints.map((endpoint, i) =>
i === index ? { ...endpoint, ...patch } : endpoint,
),
);
// Labels identify an endpoint in the sidebar picker, so a fresh row must not
// silently collide with one already there.
const uniqueLabel = (base: string) => {
const taken = new Set(endpoints.map((e) => e.label.trim()));
if (!taken.has(base)) return base;
for (let n = 2; ; n += 1) {
const candidate = `${base} ${n}`;
if (!taken.has(candidate)) return candidate;
}
};
const addEndpoint = () =>
commit([
...endpoints,
newEndpoint(uniqueLabel(t("hosts.webUiNewEndpointLabel"))),
]);
return (
// Two cards, as the tunnels tab does: settings first, then the list it
// governs, each with its own header.
<>
<SectionCard
title={t("hosts.webUiIntegration")}
icon={<Globe className="size-3.5" />}
>
<div className="flex flex-col gap-4 py-3">
<SettingRow
label={t("hosts.enableWebUi")}
description={t("hosts.enableWebUiDesc")}
>
<FakeSwitch
checked={enableWebUi}
onChange={(v: boolean) => setSettings({ enableWebUi: v })}
/>
</SettingRow>
<div className="text-xs text-muted-foreground p-3 bg-muted/30 border border-border space-y-1">
<p>{t("hosts.webUiRequirementsText")}</p>
</div>
</div>
</SectionCard>
<SectionCard
title={t("hosts.webUiEndpointsSection")}
icon={<Globe className="size-3.5" />}
action={
enableWebUi ? (
// Same header control, and the same classes, as the tunnels list.
<Button
variant="outline"
size="sm"
className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
disabled={endpoints.length >= MAX_WEB_ENDPOINTS}
onClick={addEndpoint}
>
{t("hosts.webUiAddEndpoint")}
</Button>
) : undefined
}
>
<div className="flex flex-col gap-3 py-3">
{!enableWebUi ? (
<p className="text-xs text-muted-foreground">
{t("hosts.webUiEndpointsDisabled")}
</p>
) : endpoints.length === 0 ? (
<p className="text-xs text-muted-foreground">
{t("hosts.webUiNoEndpoints")}
</p>
) : (
<>
{endpoints.map((endpoint, index) => {
const rowError = webEndpointRowError(endpoint);
return (
<div
key={endpoint.id}
className="flex flex-col gap-3 p-3 border border-border bg-muted/20 relative group"
>
<div className="flex items-center justify-between mb-1">
<span className="text-xs font-bold text-muted-foreground">
{t("hosts.webUiEndpointLabel", { number: index + 1 })}
</span>
<Button
variant="ghost"
size="sm"
aria-label={t("hosts.webUiRemoveEndpoint")}
className="h-6 text-[10px] px-2 text-destructive"
onClick={() =>
commit(endpoints.filter((_, i) => i !== index))
}
>
{t("common.delete")}
</Button>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-[10px] font-bold text-muted-foreground">
{t("hosts.webUiLabel")}
</label>
<Input
aria-label={t("hosts.webUiLabel")}
value={endpoint.label}
onChange={(e) =>
update(index, { label: e.target.value })
}
maxLength={MAX_WEB_ENDPOINT_LABEL_LENGTH}
className="h-7 text-xs"
/>
</div>
{rowError && (
<p className="text-[11px] text-destructive">
{t(webEndpointErrorKey(rowError), { row: index + 1 })}
</p>
)}
<div className="flex flex-col gap-1.5">
<label className="text-[10px] font-bold text-muted-foreground">
{t("hosts.webUiAddress")}
</label>
<div className="flex items-center gap-2">
<Select
value={endpoint.scheme}
onValueChange={(value) =>
update(index, {
scheme: value as WebEndpoint["scheme"],
})
}
>
<SelectTrigger
aria-label={t("hosts.webUiScheme")}
size="sm"
className="h-7 w-24 text-xs"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="https" className="text-xs">
https
</SelectItem>
<SelectItem value="http" className="text-xs">
http
</SelectItem>
</SelectContent>
</Select>
<Input
aria-label={t("hosts.webUiPort")}
type="number"
min={MIN_WEB_ENDPOINT_PORT}
max={MAX_WEB_ENDPOINT_PORT}
value={endpoint.port}
onChange={(e) => {
// Number("") is 0, which the normalizer rejects --
// so clearing the field would otherwise write an
// endpoint that is silently dropped on save.
// Commit only a value the normalizer would keep;
// anything else leaves the last good port.
const parsed = Number(e.target.value);
if (isWebEndpointPortValid(parsed)) {
update(index, { port: parsed });
}
}}
className="h-7 w-20 text-xs"
/>
<Input
aria-label={t("hosts.webUiPath")}
value={endpoint.path ?? "/"}
onChange={(e) =>
update(index, { path: e.target.value })
}
className="h-7 flex-1 text-xs"
/>
</div>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-[10px] font-bold text-muted-foreground">
{t("hosts.webUiOpening")}
</label>
<div className="flex items-center gap-2">
<Select
value={endpoint.access}
onValueChange={(value) =>
update(index, {
access: value as WebEndpoint["access"],
// Meaningless for a tunnel, whose host component
// is loopback and already exempt.
ignoreCert:
value === "direct"
? endpoint.ignoreCert
: false,
})
}
>
<SelectTrigger
aria-label={t("hosts.webUiAccess")}
size="sm"
className="h-7 flex-1 text-xs"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="direct" className="text-xs">
{t("hosts.webUiAccessDirect")}
</SelectItem>
<SelectItem
value="tunnel"
disabled={!tunnelAvailable}
>
{t("hosts.webUiAccessTunnel")}
</SelectItem>
</SelectContent>
</Select>
<Select
value={endpoint.render}
onValueChange={(value) =>
update(index, {
render: value as WebEndpoint["render"],
})
}
>
<SelectTrigger
aria-label={t("hosts.webUiRender")}
size="sm"
className="h-7 flex-1 text-xs"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem
value="external"
className="text-xs"
disabled={!isElectron()}
>
{t("hosts.webUiRenderExternal")}
</SelectItem>
<SelectItem value="embedded" className="text-xs">
{t("hosts.webUiRenderEmbedded")}
</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{endpoint.access === "tunnel" && (
<div className="flex flex-col gap-1.5">
<label className="text-[10px] font-bold text-muted-foreground">
{t("hosts.bindHost")}
</label>
<Input
aria-label={t("hosts.bindHost")}
placeholder="127.0.0.1"
value={endpoint.bindHost ?? ""}
onChange={(e) =>
update(index, { bindHost: e.target.value })
}
className="h-7 text-xs"
/>
<p className="text-[11px] opacity-70">
{t("hosts.webUiBindHostDesc")}
</p>
<label className="text-[10px] font-bold text-muted-foreground">
{t("hosts.webUiLocalPort")}
</label>
<Input
aria-label={t("hosts.webUiLocalPort")}
type="number"
min={MIN_WEB_ENDPOINT_PORT}
max={MAX_WEB_ENDPOINT_PORT}
placeholder={t("hosts.webUiLocalPortAuto")}
value={endpoint.localPort ?? ""}
onChange={(e) => {
const raw = e.target.value;
if (raw === "") {
update(index, { localPort: undefined });
return;
}
const parsed = Number(raw);
if (isWebEndpointPortValid(parsed)) {
update(index, { localPort: parsed });
}
}}
className="h-7 text-xs"
/>
<p className="text-[11px] opacity-70">
{t("hosts.webUiLocalPortDesc")}
</p>
{isExposedBindHost(endpoint.bindHost) && (
<p className="text-[11px] text-destructive">
{t("hosts.webUiBindHostExposed")}
</p>
)}
{(() => {
// Said while configuring, not only when the tab fails
// to load: a loopback bind on a backend that is not
// this machine opens fine and then leaves the browser
// with nothing to connect to, and a tunnel reached at
// Termix's own hostname would hand the tunnelled
// service this session.
const refusal = webEndpointRefusalReason(
endpoint,
isElectron(),
undefined,
);
if (!refusal) return null;
// Unreachable from this tunnel-only block; narrows
// the union to the reasons this preview renders.
if (refusal === "direct-shares-session-cookie") {
return null;
}
return (
<p className="text-[11px] text-destructive">
{t(BIND_HOST_REFUSAL_MESSAGES[refusal])}
</p>
);
})()}
</div>
)}
{endpoint.render === "embedded" && (
<p className="text-[11px] opacity-70">
{t("hosts.webUiRenderEmbeddedDesc")}
</p>
)}
{endpoint.access === "direct" && (
<div className="flex flex-col gap-1">
<label className="flex items-center gap-2 text-xs">
<Checkbox
checked={endpoint.ignoreCert === true}
onCheckedChange={(value) =>
update(index, { ignoreCert: value === true })
}
/>
{t("hosts.webUiIgnoreCert")}
</label>
<p className="text-[11px] opacity-70">
{t("hosts.webUiIgnoreCertDesc")}
</p>
</div>
)}
</div>
);
})}
{!tunnelAvailable && (
// Shown whenever tunnelling is unavailable, not only once a row
// already asks for it: the Tunnel option renders disabled, and
// a disabled control with no stated reason reads as the
// dropdown being broken.
<p className="text-[11px] opacity-70">
{t("hosts.webUiAccessTunnelUnavailable")}
</p>
)}
</>
)}
</div>
</SectionCard>
</>
);
}
@@ -0,0 +1,231 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "@termix/plugin-sdk/frontend";
import { Globe, RotateCw } from "lucide-react";
import { toast } from "sonner";
import {
currentTunnelHost,
resolveWebEndpointUrl,
webEndpointRefusalReason,
type WebEndpointRefusalReason,
} from "./web-endpoint-url";
import {
allowInvalidCertificateForOrigin,
openWebEndpointExternally,
openWebEndpointTunnel,
requireNumericHostId,
} from "./web-endpoint-api";
import { copyToClipboard } from "@termix/plugin-sdk/ui";
import { isElectron } from "@termix/plugin-sdk/ui";
import { Button } from "@termix/plugin-sdk/ui";
import type { PluginHostRecord as Host } from "@termix/plugin-sdk/frontend";
import type { WebEndpoint } from "../shared/web-endpoint-config";
const REFUSAL_MESSAGES: Record<WebEndpointRefusalReason, string> = {
"loopback-bind-on-remote-backend": "webEndpoint.tunnelUnreachableFromBrowser",
"shares-session-cookie-with-termix": "webEndpoint.tunnelSharesSessionCookie",
"direct-shares-session-cookie": "webEndpoint.directSharesSessionCookie",
};
/**
* Renders one web endpoint in an iframe.
*
* Takes the whole host plus the endpoint's ID -- not the endpoint object --
* so a tab whose endpoint was deleted while it was open (or that never matched
* one, if the host's webUiConfig raced the tab's mount) can be detected here
* and shown a plain "no longer exists" message instead of throwing on
* endpoint.scheme.
*/
export function WebEndpointTab({
host,
endpointId,
}: {
host: Host;
endpointId?: string;
}) {
const { t } = useTranslation();
const webUiConfig = (
host.pluginSettings as Record<string, Record<string, unknown>> | undefined
)?.["web-endpoint"]?.webUiConfig as { endpoints?: WebEndpoint[] } | undefined;
const endpoint = (webUiConfig?.endpoints ?? []).find(
(candidate) => candidate.id === endpointId,
);
const [url, setUrl] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
/**
* Bumped on every resolution that lands, and folded into the iframe's key
* alongside the URL. A direct endpoint's URL never changes, and a live
* tunnel returns the SAME port on every open -- so the URL alone is not
* enough to key on: React bails out of a same-value setState, the key would
* not change, and Reload would silently do nothing in the two most common
* cases.
*/
const [generation, setGeneration] = useState(0);
/**
* Guards two in-flight resolutions completing out of order -- a
* double-clicked Reload, or a manual reload racing the mount effect. Only
* the most recently started resolution may apply its result.
*/
const resolveGenerationRef = useRef(0);
const resolve = useCallback(async () => {
if (!endpoint) return;
const mine = ++resolveGenerationRef.current;
setError(null);
try {
// Checked BEFORE the open call, not after. A tunnel must not be opened
// from a browser when a loopback bind on a remote backend would leave
// nothing to connect to, or when the tunnel URL would land on the page's
// own host string. A DIRECT endpoint on the same host that serves Termix
// leaks the session cookie exactly the same way -- cookies ignore the
// port -- so it is refused here too, before any navigation, rather than
// framing the URL and leaking on the first request.
const refusal = webEndpointRefusalReason(endpoint, isElectron(), host.ip);
if (refusal) {
throw new Error(t(REFUSAL_MESSAGES[refusal]));
}
if (!("credentialless" in HTMLIFrameElement.prototype)) {
throw new Error(t("webEndpoint.isolationUnavailable"));
}
// Always re-resolved rather than reloading the frame: the backend closes
// an idle tunnel after ten minutes and re-binds a fresh kernel-assigned
// port, so a cached port may be gone.
const localPort =
endpoint.access === "tunnel"
? await openWebEndpointTunnel(
requireNumericHostId(host.id),
endpoint.id,
)
: undefined;
const resolved = resolveWebEndpointUrl({
hostAddress: host.ip,
endpoint,
localPort,
// Non-null for a tunnel by the time we get here: a null separated host
// is exactly what the refusal above catches.
tunnelHost: currentTunnelHost(isElectron()) ?? undefined,
});
if (endpoint.access === "direct" && endpoint.ignoreCert) {
await allowInvalidCertificateForOrigin(new URL(resolved).origin);
}
if (mine !== resolveGenerationRef.current) return;
setUrl(resolved);
setGeneration((g) => g + 1);
} catch (caught) {
if (mine !== resolveGenerationRef.current) return;
setError(caught instanceof Error ? caught.message : String(caught));
}
// Depends on the endpoint's FIELDS, not the object: host.webUiConfig is
// re-derived on every render of the host list, so a dependency on
// `endpoint` itself would reopen the tunnel on every parent render.
// bindHost and localPort are included because the refusal guard reads them.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
host.id,
host.ip,
endpoint?.id,
endpoint?.access,
endpoint?.scheme,
endpoint?.port,
endpoint?.path,
endpoint?.ignoreCert,
endpoint?.bindHost,
endpoint?.localPort,
]);
useEffect(() => {
void resolve();
}, [resolve]);
if (!endpoint) {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-xs text-muted-foreground">
<Globe className="size-5 opacity-60" />
<p>{t("webEndpoint.notFound")}</p>
</div>
);
}
if (error) {
return (
<div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-xs">
<Globe className="size-5 opacity-60" />
<p className="text-center">{error}</p>
<Button variant="outline" size="sm" onClick={() => void resolve()}>
{t("webEndpoint.retry")}
</Button>
</div>
);
}
return (
<div className="flex h-full flex-col">
<div className="flex items-center gap-2 border-b border-border px-2 py-1 text-xs">
<Button
variant="ghost"
size="icon-sm"
onClick={() => void resolve()}
title={t("webEndpoint.reload")}
>
<RotateCw />
</Button>
<span className="truncate text-muted-foreground">{url ?? ""}</span>
<Button
variant="ghost"
size="xs"
className="ml-auto"
onClick={() => {
if (!url) return;
void copyToClipboard(url).then((ok) => {
if (ok) toast.success(t("webEndpoint.urlCopied"));
else toast.error(t("webEndpoint.copyFailed"));
});
}}
>
{t("webEndpoint.copyUrl")}
</Button>
{isElectron() && (
<Button
variant="ghost"
size="xs"
onClick={() => {
void openWebEndpointExternally(host, endpoint).catch((error) =>
toast.error(error.message),
);
}}
>
{t("webEndpoint.openIsolatedWindow")}
</Button>
)}
</div>
<p className="px-2 py-1 text-xs text-muted-foreground">
{t("webEndpoint.isolationNotice")}
</p>
{url && (
// Keyed on generation as well as url: a re-resolved tunnel usually
// returns the SAME port, so url alone would not change and React would
// never remount the frame.
<iframe
key={`${generation}:${url}`}
title={endpoint.label}
ref={(frame) => {
if (!frame) return;
// Set isolation before the first navigation, including redirects.
(
frame as HTMLIFrameElement & { credentialless: boolean }
).credentialless = true;
frame.src = url;
}}
sandbox="allow-scripts allow-forms"
referrerPolicy="no-referrer"
className="h-full w-full flex-1 border-0"
/>
)}
</div>
);
}
+131
View File
@@ -0,0 +1,131 @@
import { Globe } from "lucide-react";
import i18next from "i18next";
import { toast } from "sonner";
import type {
HostEditorSectionProps,
PluginHostRecord,
ShellApi,
TabProps,
TermixApp,
} from "@termix/plugin-sdk/frontend";
import type { PluginHostRecord as Host } from "@termix/plugin-sdk/frontend";
import type { WebEndpoint } from "../shared/web-endpoint-config";
import { WebEndpointTab } from "./WebEndpointTab";
import { HostEditorWebUiSection } from "./HostEditorWebUiSection";
import {
openWebEndpointExternally,
setWebEndpointApi,
} from "./web-endpoint-api";
const TAB_TYPE = "web-endpoint";
function webEndpointSettings(host: PluginHostRecord): {
enableWebUi: boolean;
webUiConfig: { endpoints: WebEndpoint[] };
} {
const settings = (
host.pluginSettings as Record<string, Record<string, unknown>> | undefined
)?.["web-endpoint"];
return {
enableWebUi: settings?.enableWebUi === true,
webUiConfig: (settings?.webUiConfig as
{ endpoints: WebEndpoint[] } | undefined) ?? {
endpoints: [],
},
};
}
function endpointsOf(host: PluginHostRecord): WebEndpoint[] {
const { enableWebUi, webUiConfig } = webEndpointSettings(host);
if (!enableWebUi) return [];
return webUiConfig.endpoints ?? [];
}
function openEndpoint(
host: PluginHostRecord,
endpoint: WebEndpoint,
shell: ShellApi,
): void {
if (endpoint.render === "external") {
// No tab at all: the real browser opens it. On the desktop the plugin
// asks the backend to open it in an isolated window.
openWebEndpointExternally(
host as unknown as { id: string; ip: string },
endpoint,
).catch((error: unknown) => {
toast.error(
error instanceof Error
? error.message
: i18next.t("web-endpoint:hosts.webUiOpenFailed"),
);
});
return;
}
shell.openTab(host, TAB_TYPE, {
label: endpoint.label,
data: { endpointId: endpoint.id },
});
}
function EndpointTab({ host, tab }: TabProps) {
// Resolved against the host on every render, so an endpoint deleted while
// its tab is open shows a plain message instead of throwing.
const endpointId = tab.data?.endpointId;
return (
<WebEndpointTab
host={host as unknown as Host}
endpointId={typeof endpointId === "string" ? endpointId : undefined}
/>
);
}
function WebUiSection(props: HostEditorSectionProps) {
return <HostEditorWebUiSection {...props} />;
}
export function activate(app: TermixApp): void {
setWebEndpointApi(app.api);
app.onDispose(() => setWebEndpointApi(null));
app.registerTab(TAB_TYPE, EndpointTab, {
icon: Globe,
titleKey: "hosts.tabWebUi",
requiresHost: true,
noHostMessageKey: "webEndpoint.noHostSelected",
// A restored tab could never hold a valid URL: the backend closes an idle
// tunnel after ten minutes and binds a fresh port on the next open. So
// these tabs are session-only and never saved.
persistent: false,
inLayouts: false,
});
// One entry per host, not one per endpoint: with several it opens a picker.
// Gated on enableWebUi alone, since a direct endpoint needs no SSH.
app.registerHostAction({
id: TAB_TYPE,
titleKey: "hosts.tabWebUi",
icon: Globe,
kind: "open",
order: 80,
when: (host) => endpointsOf(host).length > 0,
label: (host) => {
const endpoints = endpointsOf(host);
return endpoints.length === 1 ? endpoints[0].label : undefined;
},
items: (host) =>
endpointsOf(host).map((endpoint) => ({
id: endpoint.id,
label: endpoint.label,
run: (target, shell) => openEndpoint(target, endpoint, shell),
})),
});
app.registerHostEditorSection({
id: "web-ui",
group: "ssh",
titleKey: "hosts.tabWebUi",
icon: Globe,
order: 40,
component: WebUiSection,
});
}
@@ -0,0 +1,155 @@
import axios from "axios";
import type { PluginApiClient } from "@termix/plugin-sdk/frontend";
import { isElectron } from "@termix/plugin-sdk/ui";
import type { WebEndpoint } from "../shared/web-endpoint-config";
let pluginApi: PluginApiClient | null = null;
function genericFailure(error: unknown, action: string): never {
if (!axios.isAxiosError(error) && error instanceof Error) throw error;
const status = axios.isAxiosError(error) ? error.response?.status : undefined;
throw new WebEndpointTunnelError(`Could not ${action}`, status);
}
/** Set from activate with app.api, cleared on deactivate. */
export function setWebEndpointApi(api: PluginApiClient | null): void {
pluginApi = api;
}
/**
* Thrown when the backend rejects a web endpoint tunnel open with a specific,
* actionable reason -- most commonly a 502 carrying the real cause: SSH auth
* rejected, host unreachable, or nothing listening on the target port.
* Preserves that reason instead of collapsing three actionable errors into
* one generic failure.
*/
export class WebEndpointTunnelError extends Error {
constructor(
message: string,
public readonly status?: number,
) {
super(message);
this.name = "WebEndpointTunnelError";
}
}
/**
* Opens (or reuses) the SSH forward for a tunnel-access web endpoint and
* returns the port it is listening on. The port is NOT stable across opens:
* the backend closes an idle tunnel and re-binds a fresh kernel-assigned port,
* so callers must re-resolve rather than cache it.
*/
export async function openWebEndpointTunnel(
hostId: number,
endpointId: string,
): Promise<number> {
try {
if (!pluginApi) throw new Error("The web endpoint plugin is not active");
// Relative to the plugin mount, /plugin-api/web-endpoint.
const response = await pluginApi.post("/open", {
hostId,
endpointId,
});
const port = (response?.data as { port?: number } | undefined)?.port;
if (!port) {
throw new Error("The endpoint tunnel returned no port");
}
return port;
} catch (error) {
if (axios.isAxiosError(error)) {
// Typed unknown, not string: the guard below is only meaningful if the
// type does not already promise what it checks.
const data = error.response?.data as
{ error?: unknown; message?: unknown } | undefined;
const backendMessage = data?.error ?? data?.message;
// A body shaped { error: <object> } would otherwise render as
// "[object Object]". Every response on this route sends a string today,
// but a proxy or a future handler need not.
if (typeof backendMessage === "string" && backendMessage) {
throw new WebEndpointTunnelError(
backendMessage,
error.response?.status,
);
}
}
return genericFailure(error, "open web endpoint tunnel");
}
}
/**
* Registers one exact origin as allowed to present an invalid TLS certificate.
* Only meaningful on the desktop, and only for direct endpoints -- a tunnel
* endpoint's host component is loopback, which the main process already
* exempts.
*/
export async function allowInvalidCertificateForOrigin(
origin: string,
): Promise<void> {
if (!isElectron()) return;
try {
await window.electronAPI?.invoke?.(
"allow-invalid-certificate-for-origin",
origin,
);
} catch {
// The user's build may predate the handler; the load then simply fails the
// certificate check as it would have before.
}
}
/**
* A web endpoint tunnel opens through the backend's numeric host id.
* Quick-connect hosts (ids like "quick-connect-<n>") have no row on the
* server, so there is nothing to open a tunnel through -- unlike a direct
* endpoint, which never touches the backend and works regardless.
*/
export function requireNumericHostId(id: string): number {
const numericId = Number(id);
if (!Number.isInteger(numericId) || numericId <= 0) {
throw new Error(
"This endpoint needs an SSH tunnel, which requires a saved host",
);
}
return numericId;
}
/**
* Desktop windows use a dedicated ephemeral session, including login popups.
*
* The backend resolves and validates the target URL (the host's own declared
* address for a direct endpoint, or the tunnel port it opens for a tunnel
* one) and opens the window itself through ctx.desktop.openIsolatedWindow, so
* the capability check and audit line cover the whole decision -- this call
* only asks for it and reports whether it worked.
*/
export async function openWebEndpointExternally(
host: { id: string; ip: string },
endpoint: WebEndpoint,
): Promise<void> {
if (!isElectron()) {
throw new Error(
"Isolated windows require the desktop app. Choose Embedded in the endpoint settings.",
);
}
if (!pluginApi) throw new Error("The web endpoint plugin is not active");
try {
await pluginApi.post("/open-window", {
hostId: requireNumericHostId(host.id),
endpointId: endpoint.id,
ignoreCert: endpoint.ignoreCert === true,
});
} catch (error) {
if (axios.isAxiosError(error)) {
const data = error.response?.data as
{ error?: unknown; message?: unknown } | undefined;
const backendMessage = data?.error ?? data?.message;
if (typeof backendMessage === "string" && backendMessage) {
throw new WebEndpointTunnelError(
backendMessage,
error.response?.status,
);
}
}
return genericFailure(error, "open isolated web endpoint");
}
}
@@ -0,0 +1,211 @@
import type { WebEndpoint } from "../shared/web-endpoint-config";
/**
* Builds the URL a web endpoint opens at.
*
* Direct access points at the host's own address. Tunnel access points at a
* port the backend has forwarded to the endpoint's port on the host -- so the
* endpoint's own port is deliberately absent from a tunnel URL.
*
* Expects an endpoint whose `path` has already been normalized by
* `normalizeWebEndpoints` (it always begins with "/"); a raw unvalidated path
* would produce a malformed URL.
*/
export function resolveWebEndpointUrl({
hostAddress,
endpoint,
localPort,
tunnelHost,
}: {
hostAddress: string;
endpoint: WebEndpoint;
localPort?: number;
/**
* Where the caller can reach the forward the backend bound. Must never be
* the host string the browser is currently reaching Termix at -- see
* `separatedTunnelHost`. Defaults to loopback.
*/
tunnelHost?: string;
}): string {
const path = endpoint.path && endpoint.path.length > 0 ? endpoint.path : "/";
if (endpoint.access === "tunnel") {
if (!localPort) {
throw new Error("A tunnel endpoint needs a local port to resolve a URL");
}
const authority = bracketIfIpv6(tunnelHost?.trim() || "127.0.0.1");
return `${endpoint.scheme}://${authority}:${localPort}${path}`;
}
return `${endpoint.scheme}://${bracketIfIpv6(hostAddress)}:${endpoint.port}${path}`;
}
/** A bare IPv6 literal has to be bracketed to be a legal URL authority. */
function bracketIfIpv6(host: string): string {
return host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
}
/** Host spellings that mean "this machine". */
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
/**
* Each loopback spelling mapped to a DIFFERENT one that reaches the same
* machine. Being a different string is the entire point.
*/
const LOOPBACK_ALIASES: Record<string, string> = {
localhost: "127.0.0.1",
"127.0.0.1": "localhost",
"::1": "127.0.0.1",
"[::1]": "127.0.0.1",
};
/**
* A host string that reaches the same machine as `pageHost` but is a
* different key in the browser's cookie jar -- or null when none can be
* derived.
*
* This is a security mitigation, not a cosmetic choice. Cookies are keyed by
* host and IGNORE the port, and SameSite computes "site" as scheme +
* registrable domain -- also ignoring the port. So a forward reached at the
* very host string serving Termix is same-site with Termix, and two things
* follow:
*
* 1. the browser attaches Termix's `jwt` cookie to every request the framed
* third-party server sees, including its access log; and
* 2. a `Set-Cookie: jwt=...` from that server lands in the jar Termix's own
* API calls read from -- and both auth middlewares read the cookie
* BEFORE the Authorization header, so it decides who Termix acts as.
*
* Both directions were reproduced against a real SSH forward.
*
* Only loopback literals get an alias. A same-registrable-domain name would
* not be safe even though it is a different host: the target could answer
* `Set-Cookie: jwt=...; Domain=example.com`, which reaches Termix anyway.
* Loopback literals cannot carry a Domain attribute, so they are the only
* spellings that close both directions.
*/
export function separatedTunnelHost(pageHost: string): string | null {
return LOOPBACK_ALIASES[pageHost.trim().toLowerCase()] ?? null;
}
/** Lowercase, trim, drop surrounding IPv6 brackets and a single trailing dot. */
function normalizeHost(host: string): string {
let h = host.trim().toLowerCase();
if (h.startsWith("[") && h.endsWith("]")) h = h.slice(1, -1);
if (h.endsWith(".")) h = h.slice(0, -1);
return h;
}
/**
* Whether a browser would attach Termix's `jwt` cookie to a request for
* `targetHost` while the page is served from `pageHost` -- or accept a
* `Set-Cookie` from `targetHost` into the jar Termix's own API reads.
*
* The web client sets `jwt` host-only (no `Domain`), so the port is irrelevant
* and the disclosure direction is exactly an equal host. The reverse direction
* -- the target answering `Set-Cookie: jwt=...; Domain=<parent>` -- reaches
* Termix whenever the two share a domain, so a parent/sub relationship counts
* too. The suffix check is anchored on a dot boundary so `eviltermix.example`
* is not treated as same-site with `termix.example`.
*
* A precise registrable-domain (eTLD+1) test would also catch sibling
* subdomains under a shared parent, but needs a public-suffix list this app
* does not bundle; the exact/parent/sub check closes the reported same-host
* case only. This is defense in depth, not cookie isolation: embedded frames
* must use credentialless plus an opaque sandbox origin, including redirects.
*/
export function sharesCookieSiteWithPage(
targetHost: string,
pageHost: string,
): boolean {
const t = normalizeHost(targetHost);
const p = normalizeHost(pageHost);
if (!t || !p) return false;
if (t === p) return true;
return t.endsWith("." + p) || p.endsWith("." + t);
}
function defaultPageHost(): string {
return typeof window === "undefined" ? "127.0.0.1" : window.location.hostname;
}
/**
* Why a web endpoint must not be opened from this client.
*
* `loopback-bind-on-remote-backend` -- the forward binds where the backend
* runs. In a browser that is the server, so a loopback bind answers only to
* the server itself: the open succeeds, the port exists, and the browser
* still gets nothing.
*
* `shares-session-cookie-with-termix` -- the tunnel URL would resolve to the
* same host string the page is served from, handing Termix's session token to
* the tunnelled service. See `separatedTunnelHost`.
*
* `direct-shares-session-cookie` -- the same leak without a tunnel: a direct
* endpoint's target host shares Termix's cookie site, so the browser attaches
* the `jwt` to it (and accepts one back). A different port is not a different
* cookie key. See `sharesCookieSiteWithPage`.
*/
export type WebEndpointRefusalReason =
| "loopback-bind-on-remote-backend"
| "shares-session-cookie-with-termix"
| "direct-shares-session-cookie";
/**
* Why a web endpoint must not be opened from this client, or null when it may.
*
* Covers both access modes. A tunnel is refused when its forward would either
* be unreachable (loopback bind on a remote backend) or resolve to the page's
* own host string (`shares-session-cookie-with-termix`). A DIRECT endpoint is
* refused when its target host shares Termix's cookie site
* (`direct-shares-session-cookie`) -- the same leak, reached without a tunnel:
* cookies ignore the port, so a UI on the very host serving Termix receives
* the session. `hostAddress` is the direct endpoint's target host and is
* ignored for tunnels.
*
* The desktop is exempt: its session is Bearer-only with no `jwt` in the jar,
* and its API base ("localhost") is already separated from where tunnels
* resolve ("127.0.0.1").
*/
export function webEndpointRefusalReason(
endpoint: Pick<WebEndpoint, "access" | "bindHost">,
runningInElectron: boolean,
hostAddress: string | undefined,
pageHost: string = defaultPageHost(),
): WebEndpointRefusalReason | null {
if (runningInElectron) return null;
if (endpoint.access === "direct") {
if (hostAddress && sharesCookieSiteWithPage(hostAddress, pageHost)) {
return "direct-shares-session-cookie";
}
return null;
}
if (endpoint.access !== "tunnel") return null;
const bindHost = (endpoint.bindHost ?? "").trim().toLowerCase();
// Reported first when both apply: the bind address is what the user has to
// change either way, and it is the more specific instruction.
if (!bindHost || LOOPBACK_HOSTS.has(bindHost)) {
return "loopback-bind-on-remote-backend";
}
if (!separatedTunnelHost(pageHost)) {
return "shares-session-cookie-with-termix";
}
return null;
}
/**
* Where this client should reach a forward the backend bound, or null when no
* host string is both reachable and safe -- in which case
* `unreachableTunnelReason` explains why and the caller must not open.
*/
export function currentTunnelHost(
runningInElectron: boolean,
pageHost: string = defaultPageHost(),
): string | null {
if (runningInElectron) return "127.0.0.1";
return separatedTunnelHost(pageHost);
}
@@ -0,0 +1,119 @@
import type { WebEndpoint } from "../shared/web-endpoint-config";
/**
* Editor-side validation for web endpoint rows.
*
* The authority on what a stored endpoint may look like is
* `normalizeWebEndpoints` in ../shared/web-endpoint-config.ts, and it DROPS
* any row it refuses rather than reporting it -- so without a check here the
* user adds a row, saves, sees no error, and finds the endpoint gone on
* reload.
*
* This deliberately does NOT restate that module's full rule set: it covers
* only the conditions a user can reach by typing, with per-field errors a
* drop/keep normalizer cannot give. tests/backend/web-endpoint-config.test.ts
* covers the normalizer; this file's own tests cover the same inputs here.
*/
export const MIN_WEB_ENDPOINT_PORT = 1;
export const MAX_WEB_ENDPOINT_PORT = 65535;
export type WebEndpointFieldError =
"label" | "duplicateLabel" | "port" | "path";
const ERROR_KEYS: Record<WebEndpointFieldError, string> = {
label: "hosts.webUiErrorLabelRequired",
duplicateLabel: "hosts.webUiErrorLabelDuplicate",
port: "hosts.webUiErrorPortRange",
path: "hosts.webUiErrorPathInvalid",
};
/**
* The i18n key for a field error. Every key takes a `row` interpolation so the
* message can say which endpoint is at fault.
*/
export function webEndpointErrorKey(error: WebEndpointFieldError): string {
return ERROR_KEYS[error];
}
export function isWebEndpointPortValid(port: unknown): boolean {
return (
typeof port === "number" &&
Number.isInteger(port) &&
port >= MIN_WEB_ENDPOINT_PORT &&
port <= MAX_WEB_ENDPOINT_PORT
);
}
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;
}
/**
* True if the normalizer would accept this path. An empty or absent path is
* fine -- the normalizer defaults it to "/" -- and so is a path with no
* leading slash, which the normalizer coerces.
*/
export function isWebEndpointPathValid(
raw: string | undefined | null,
): boolean {
if (raw === undefined || raw === null || raw === "") return true;
if (hasControlCharacter(raw)) return false;
const path = raw.startsWith("/") ? raw : `/${raw}`;
// A protocol-relative or absolute path would send the iframe or the link
// somewhere other than the endpoint.
if (path.startsWith("//")) return false;
if (/^\/[a-z][a-z0-9+.-]*:/i.test(path)) return false;
if (path.includes("\\")) return false;
return true;
}
/**
* The first thing wrong with one row, or null if the normalizer would keep it.
* Label is checked before port so the message points at the field the user
* most likely just left blank.
*/
export function webEndpointRowError(
endpoint: WebEndpoint,
): WebEndpointFieldError | null {
if (typeof endpoint.label !== "string" || endpoint.label.trim() === "") {
return "label";
}
if (!isWebEndpointPortValid(endpoint.port)) return "port";
if (!isWebEndpointPathValid(endpoint.path)) return "path";
return null;
}
/**
* The first row the normalizer would drop, so a save can be blocked with a
* message naming it. Returns null when every row would survive.
*
* Duplicate LABELS are reported even though the normalizer tolerates them:
* the sidebar picker shows labels, so two identical ones are indistinguishable
* to the user. Duplicate ids are generated, never typed.
*/
export function findInvalidWebEndpoint(
endpoints: WebEndpoint[] | undefined | null,
): { index: number; error: WebEndpointFieldError } | null {
if (!Array.isArray(endpoints)) return null;
const seen = new Set<string>();
for (let index = 0; index < endpoints.length; index += 1) {
const endpoint = endpoints[index];
const error = webEndpointRowError(endpoint);
if (error) return { index, error };
const label = endpoint.label.trim().toLowerCase();
if (seen.has(label)) return { index, error: "duplicateLabel" };
seen.add(label);
}
return null;
}
@@ -0,0 +1,253 @@
/**
* The plugin's own copy of what used to be core's host-web-endpoints.ts,
* now that webUiConfig lives in this plugin's host-scope settings instead of
* an ssh_data column. Same rules, same shape.
*
* Shared between backend and frontend (validation runs in both: the backend
* is the real enforcement point, the editor mirrors it for instant feedback),
* so this file has no runtime dependencies of its own.
*/
export type WebEndpointAccess = "direct" | "tunnel";
export type WebEndpointRender = "external" | "embedded";
/** One web UI a host serves, declared in this plugin's host settings. */
export interface WebEndpoint {
/**
* Stable identifier. Must NOT be derived from the port: it keys both the
* tunnel name and the tab identity, so editing a port has to leave a live
* tunnel findable under the same name.
*/
id: string;
label: string;
scheme: "http" | "https";
port: number;
/** Defaults to "/". Normalized at the storage boundary, never here. */
path?: string;
access: WebEndpointAccess;
render: WebEndpointRender;
/**
* Direct endpoints only. Allows an invalid TLS certificate for this
* endpoint's exact origin. A no-op for tunnel access, whose host component
* is loopback and therefore already exempt.
*/
ignoreCert?: boolean;
/**
* Tunnel endpoints only. Where the backend binds the forward, exactly as
* the tunnels plugin exposes it. Defaults to 127.0.0.1, reachable only from
* the machine running the backend. A web deployment runs the backend on a
* server, so reaching the forward from a browser needs an address that
* machine answers on -- which also exposes the target's web UI to anyone
* who can reach the port, with no login in front of it.
*/
bindHost?: string;
/**
* Tunnel endpoints only. Which port the forward listens on, as the tunnels
* plugin's Source Port does. Left unset the kernel picks a free one, which
* is fine when backend and browser share a machine -- but a container can
* only publish ports it knows in advance.
*/
localPort?: number;
}
export interface WebUiConfig {
endpoints: WebEndpoint[];
}
/** A host may declare at most this many web endpoints. */
export const MAX_WEB_ENDPOINTS = 16;
/** Endpoint labels are truncated to this length. */
export const MAX_WEB_ENDPOINT_LABEL_LENGTH = 64;
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/frontend/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.
*/
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 setting is cleared. */
export function serializeWebUiConfig(config: unknown): WebUiConfig | null {
const endpoints = normalizeWebEndpoints(
(config as { endpoints?: unknown } | null | undefined)?.endpoints,
);
if (endpoints.length === 0) return null;
return { endpoints };
}