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

@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import {
dispatchCtrlW,
createCommandPaletteShortcutMatcher,
getAltDigitShortcut,
isShiftKey,
} from "../../lib/app-keyboard-shortcuts";
@@ -40,3 +41,74 @@ describe("app keyboard shortcuts", () => {
expect(dispatchCtrlW(document.createElement("div"))).toBe(false);
});
});
describe("command palette shortcut matching", () => {
const shift = () =>
new KeyboardEvent("keydown", {
key: "Shift",
code: "ShiftLeft",
shiftKey: true,
});
it("requires a fresh pair after each double Shift", () => {
const { matches } = createCommandPaletteShortcutMatcher();
expect(matches(shift(), 1000)).toBe(false);
expect(matches(shift(), 1100)).toBe(true);
expect(matches(shift(), 1200)).toBe(false);
expect(matches(shift(), 1300)).toBe(true);
});
it("does not combine slow presses", () => {
const { matches } = createCommandPaletteShortcutMatcher();
expect(matches(shift(), 1000)).toBe(false);
expect(matches(shift(), 1300)).toBe(false);
expect(matches(shift(), 1400)).toBe(true);
});
it.each([
{ key: "A", code: "KeyA", shiftKey: true },
{ key: "Shift", code: "ShiftLeft", ctrlKey: true },
{ key: "Shift", code: "ShiftLeft", metaKey: true },
{ key: "Shift", code: "ShiftLeft", altKey: true },
{ key: "Shift", code: "ShiftLeft", isComposing: true },
{ key: "Process", keyCode: 229 },
{ key: "Shift", code: "ShiftLeft", repeat: true },
])("breaks the sequence on %j", (init) => {
const { matches } = createCommandPaletteShortcutMatcher();
matches(shift(), 1000);
expect(matches(new KeyboardEvent("keydown", init), 1050)).toBe(false);
expect(matches(shift(), 1100)).toBe(false);
});
it("resets on lost focus or composition start", () => {
const { matches, reset } = createCommandPaletteShortcutMatcher();
matches(shift(), 1000);
reset();
expect(matches(shift(), 1100)).toBe(false);
});
it("respects consumed key events", () => {
const { matches } = createCommandPaletteShortcutMatcher();
matches(shift(), 1000);
const event = new KeyboardEvent("keydown", {
key: "Shift",
cancelable: true,
});
event.preventDefault();
expect(matches(event, 1050)).toBe(false);
expect(matches(shift(), 1100)).toBe(false);
});
it.each([{ ctrlKey: true }, { metaKey: true }])(
"keeps the explicit shortcut: %j",
(modifier) => {
const { matches } = createCommandPaletteShortcutMatcher();
expect(
matches(new KeyboardEvent("keydown", { code: "KeyK", ...modifier })),
).toBe(true);
expect(
matches(
new KeyboardEvent("keydown", {
code: "KeyK",
...modifier,
isComposing: true,
}),
),
).toBe(false);
},
);
});
+93
View File
@@ -0,0 +1,93 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const registered = vi.hoisted(() => ({
cards: new Map<
string,
{ defaultHeight?: number; defaultPanel?: "main" | "side" }
>(),
}));
vi.mock("@/dashboard/dashboard-cards-registry", () => ({
getRegisteredDashboardCard: (id: string) => registered.cards.get(id),
}));
const { buildDashboardSlots, presetHiddenRailTabs } =
await import("../../lib/apply-ui-preset.js");
afterEach(() => {
registered.cards.clear();
});
describe("buildDashboardSlots", () => {
it("places core cards in the main panel by default", () => {
const slots = buildDashboardSlots(["stats_bar", "quick_actions"]);
expect(slots.map((s) => s.panel)).toEqual(["main", "main"]);
expect(slots.map((s) => s.height)).toEqual([96, 160]);
});
it("keeps recent_activity in the side panel", () => {
const slots = buildDashboardSlots(["stats_bar", "recent_activity"]);
expect(slots.find((s) => s.id === "recent_activity")?.panel).toBe("side");
});
it("reads a plugin card's own height and panel from the registry", () => {
registered.cards.set("service_links", {
defaultHeight: 200,
defaultPanel: "side",
});
const slots = buildDashboardSlots(["stats_bar", "service_links"]);
const link = slots.find((s) => s.id === "service_links");
expect(link?.panel).toBe("side");
expect(link?.height).toBe(200);
});
it("defaults an unregistered plugin card to the main panel with no fixed height", () => {
const slots = buildDashboardSlots(["some_plugin_card"]);
expect(slots).toEqual([
{
key: "some_plugin_card_0",
id: "some_plugin_card",
panel: "main",
order: 0,
height: null,
},
]);
});
it("orders main and side cards independently", () => {
registered.cards.set("service_links", { defaultPanel: "side" });
const slots = buildDashboardSlots([
"stats_bar",
"service_links",
"quick_actions",
"recent_activity",
]);
expect(slots.map((s) => [s.id, s.panel, s.order])).toEqual([
["stats_bar", "main", 0],
["service_links", "side", 0],
["quick_actions", "main", 1],
["recent_activity", "side", 1],
]);
});
});
describe("presetHiddenRailTabs", () => {
const items = [
{ id: "snippets", simplePreset: true },
{ id: "docker-like" },
{ id: "pinned", hideable: false },
];
it("hides plugin items that do not opt in when the preset asks", () => {
expect(
presetHiddenRailTabs(
{ hiddenTabs: ["quick-connect"], hidePluginItems: true },
items,
),
).toEqual(["quick-connect", "docker-like"]);
});
it("leaves plugin items alone otherwise", () => {
expect(presetHiddenRailTabs({ hiddenTabs: [] }, items)).toEqual([]);
});
});
@@ -1,34 +0,0 @@
import { describe, expect, it } from "vitest";
import {
fromTriState,
parseRemoteDesktopDefaults,
parseTerminalDefaults,
resolveConnectionDefaults,
toTriState,
} from "../../lib/connection-defaults";
describe("connection defaults", () => {
it("ignores malformed persisted defaults", () => {
expect(parseTerminalDefaults("not-json")).toEqual({});
expect(parseRemoteDesktopDefaults("[]")).toEqual({});
});
it("lets host values override user defaults", () => {
expect(
resolveConnectionDefaults<{ fontSize: number; cursorBlink: boolean }>(
{ fontSize: 14, cursorBlink: true },
{ fontSize: 18 },
),
).toEqual({ fontSize: 18, cursorBlink: true });
});
it("keeps unset booleans distinct from false", () => {
expect(toTriState(undefined)).toBe("inherit");
expect(toTriState(true)).toBe("on");
expect(toTriState(false)).toBe("off");
expect(fromTriState("inherit")).toBeUndefined();
expect(fromTriState("on")).toBe(true);
expect(fromTriState("off")).toBe(false);
});
});
+62 -79
View File
@@ -1,4 +1,7 @@
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
const getLinkedSession = vi.hoisted(() => vi.fn(async () => null));
vi.mock("@/lib/linked-server", () => ({ getLinkedSession }));
import {
buildOriginWsUrl,
resolveConnectionOrigin,
@@ -15,7 +18,7 @@ describe("resolveConnectionOrigin", () => {
// Support#1240: these can now originate from the desktop, but only when a
// host opts in. Left on Default they stay remote, so an upgrade never moves
// an existing host onto a local guacd the user has not set up.
it("resolves rdp/vnc/telnet to remote when the host has no override", async () => {
it("resolves to remote with defaultRemote when the host has no override", async () => {
win.IS_ELECTRON = true;
win.electronAPI = {
invoke: async (channel: string) =>
@@ -23,54 +26,42 @@ describe("resolveConnectionOrigin", () => {
? { defaultConnectionOrigin: "local" }
: null,
};
for (const connectionType of ["rdp", "vnc", "telnet"]) {
await expect(
resolveConnectionOrigin({ connectionType, connectionOrigin: null }),
).resolves.toBe("remote");
}
});
it("honors an explicit local override for rdp/vnc/telnet", async () => {
win.IS_ELECTRON = true;
for (const connectionType of ["rdp", "vnc", "telnet"]) {
await expect(
resolveConnectionOrigin({ connectionType, connectionOrigin: "local" }),
).resolves.toBe("local");
}
});
it("honors an explicit remote override for rdp/vnc/telnet", async () => {
win.IS_ELECTRON = true;
for (const connectionType of ["rdp", "vnc", "telnet"]) {
await expect(
resolveConnectionOrigin({ connectionType, connectionOrigin: "remote" }),
).resolves.toBe("remote");
}
});
it("resolves rdp to local outside Electron, where there is only one backend", async () => {
await expect(
resolveConnectionOrigin({
connectionType: "rdp",
connectionOrigin: null,
}),
resolveConnectionOrigin(
{ connectionOrigin: null },
{ defaultRemote: true },
),
).resolves.toBe("remote");
});
it("honors an explicit override over defaultRemote", async () => {
win.IS_ELECTRON = true;
await expect(
resolveConnectionOrigin(
{ connectionOrigin: "local" },
{ defaultRemote: true },
),
).resolves.toBe("local");
await expect(
resolveConnectionOrigin(
{ connectionOrigin: "remote" },
{ defaultRemote: true },
),
).resolves.toBe("remote");
});
it("resolves to local outside Electron even with defaultRemote", async () => {
await expect(
resolveConnectionOrigin(
{ connectionOrigin: null },
{ defaultRemote: true },
),
).resolves.toBe("local");
});
it("always resolves serial to local, even with a remote override", async () => {
win.IS_ELECTRON = true;
it("resolves to local outside Electron regardless of the host override", async () => {
await expect(
resolveConnectionOrigin({
connectionType: "serial",
connectionOrigin: "remote",
}),
).resolves.toBe("local");
});
it("resolves to local outside Electron regardless of connectionType", async () => {
await expect(
resolveConnectionOrigin({
connectionType: "ssh",
connectionOrigin: "remote",
}),
).resolves.toBe("local");
@@ -80,13 +71,11 @@ describe("resolveConnectionOrigin", () => {
win.IS_ELECTRON = true;
await expect(
resolveConnectionOrigin({
connectionType: "ssh",
connectionOrigin: "remote",
}),
).resolves.toBe("remote");
await expect(
resolveConnectionOrigin({
connectionType: "ssh",
connectionOrigin: "local",
}),
).resolves.toBe("local");
@@ -104,7 +93,6 @@ describe("resolveConnectionOrigin", () => {
};
await expect(
resolveConnectionOrigin({
connectionType: "ssh",
connectionOrigin: null,
}),
).resolves.toBe("remote");
@@ -119,7 +107,6 @@ describe("resolveConnectionOrigin", () => {
};
await expect(
resolveConnectionOrigin({
connectionType: "ssh",
connectionOrigin: null,
}),
).resolves.toBe("local");
@@ -127,14 +114,15 @@ describe("resolveConnectionOrigin", () => {
});
/**
* The embedded backend authenticates a local WebSocket from `?token=`, because
* the browser WebSocket API cannot set an Authorization header. Electron's main
* process does inject a JWT cookie, but only on an exact origin match, and the
* remembered cookie belongs to the API origin (`localhost:30001`) — so nothing
* is attached to a `127.0.0.1:30009` connection.
* The embedded backend authenticates a local WebSocket from its subprotocol,
* because the browser WebSocket API cannot set an Authorization header.
* Electron's main process does inject a JWT cookie, but only on an exact
* origin match, so a socket has to carry the credential itself.
*
* The Docker console opted out of the query token and had no other credential
* left, so its handshake was closed with 1008 while logs and stats kept working.
* This caught a real bug: the Docker console opted out of the token and had no
* other credential left, so its handshake was closed with 1008 while logs and
* stats kept working. The fixtures below use the plugin socket routes these
* channels actually use now; every plugin shares the backend port.
*/
describe("buildOriginWsUrl", () => {
const store: Record<string, string> = {};
@@ -154,13 +142,13 @@ describe("buildOriginWsUrl", () => {
// Every interactive channel on the embedded backend relies on this.
const target = await buildOriginWsUrl({
origin: "local",
localPort: 30009,
localPath: "/docker/console/",
remotePath: "/docker/console/",
localPort: 30001,
localPath: "/plugin-ws/docker/console",
remotePath: "/plugin-ws/docker/console",
});
expect(target).toEqual({
url: "ws://127.0.0.1:30009/docker/console/",
url: "ws://127.0.0.1:30001/plugin-ws/docker/console",
protocols: ["termix.jwt.local-jwt"],
});
});
@@ -168,39 +156,34 @@ describe("buildOriginWsUrl", () => {
it("omits it only when a caller asks", async () => {
const target = await buildOriginWsUrl({
origin: "local",
localPort: 30009,
localPath: "/docker/console/",
remotePath: "/docker/console/",
localPort: 30001,
localPath: "/plugin-ws/docker/console",
remotePath: "/plugin-ws/docker/console",
includeJwt: false,
});
expect(target).toEqual({
url: "ws://127.0.0.1:30009/docker/console/",
url: "ws://127.0.0.1:30001/plugin-ws/docker/console",
protocols: [],
});
});
it("does not duplicate the Guacamole token on remote connections", async () => {
win.electronAPI = {
invoke: async (channel: string) => {
if (channel === "get-remote-sync-config") {
return { serverUrl: "https://termix.example" };
}
if (channel === "get-remote-sync-jwt") return "remote-jwt";
return null;
},
};
getLinkedSession.mockResolvedValueOnce({
serverUrl: "https://termix.example",
token: "remote-jwt",
} as never);
const target = await buildOriginWsUrl({
origin: "remote",
localPort: 30008,
localPath: "/guacamole/websocket/",
remotePath: "/guacamole/websocket/",
localPort: 30001,
localPath: "/plugin-ws/remote-desktop/display",
remotePath: "/plugin-ws/remote-desktop/display",
includeJwt: false,
});
expect(target).toEqual({
url: "wss://termix.example/guacamole/websocket/",
url: "wss://termix.example/plugin-ws/remote-desktop/display",
protocols: [],
});
});
@@ -210,13 +193,13 @@ describe("buildOriginWsUrl", () => {
const target = await buildOriginWsUrl({
origin: "local",
localPort: 30002,
localPath: "",
remotePath: "/ssh/websocket/",
localPort: 30001,
localPath: "/plugin-ws/ssh-terminal/terminal",
remotePath: "/plugin-ws/ssh-terminal/terminal",
});
expect(target).toEqual({
url: "ws://127.0.0.1:30002",
url: "ws://127.0.0.1:30001/plugin-ws/ssh-terminal/terminal",
protocols: [],
});
});
+19
View File
@@ -0,0 +1,19 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createId } from "@/lib/create-id";
afterEach(() => vi.unstubAllGlobals());
describe("createId", () => {
it("uses randomUUID when available", () => {
vi.stubGlobal("crypto", { randomUUID: () => "uuid-1" });
expect(createId()).toBe("uuid-1");
});
it("falls back without randomUUID, e.g. over plain http", () => {
vi.stubGlobal("crypto", {});
const first = createId();
const second = createId();
expect(first).toBeTruthy();
expect(second).not.toBe(first);
});
});
@@ -1,49 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import {
getCachedFileContent,
invalidateCachedFileContent,
shouldPrefetchFileContent,
} from "../../lib/file-content-request-cache";
describe("file content request cache", () => {
it("coalesces reads and reloads after invalidation", async () => {
const loader = vi.fn(async () => ({ content: "hello", path: "/note" }));
await Promise.all([
getCachedFileContent("session", "/note", loader),
getCachedFileContent("session", "/note", loader),
]);
expect(loader).toHaveBeenCalledOnce();
invalidateCachedFileContent("session", "/note");
await getCachedFileContent("session", "/note", loader);
expect(loader).toHaveBeenCalledTimes(2);
});
it("only prefetches known small files on an unconstrained network", () => {
expect(
shouldPrefetchFileContent(
{ name: "note", path: "/note", type: "file", size: 512 * 1024 },
512 * 1024,
),
).toBe(true);
expect(
shouldPrefetchFileContent(
{ name: "large", path: "/large", type: "file", size: 512 * 1024 + 1 },
512 * 1024,
),
).toBe(false);
expect(
shouldPrefetchFileContent(
{ name: "unknown", path: "/unknown", type: "file" },
512 * 1024,
),
).toBe(false);
expect(
shouldPrefetchFileContent(
{ name: "note", path: "/note", type: "file", size: 100 },
0,
),
).toBe(false);
});
});
@@ -0,0 +1,109 @@
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import {
HostDefaultBadge,
HostDefaultsContext,
HostOnly,
type HostDefaultsContextValue,
} from "@/lib/host-defaults-context";
import { SettingRow } from "@/components/section-card";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) =>
options?.name ? `${key}:${options.name}` : key,
}),
}));
function context(
partial: Partial<HostDefaultsContextValue> = {},
): HostDefaultsContextValue {
return {
mode: "host",
isOwn: () => false,
source: () => ({ level: "user" }),
reset: vi.fn(),
isAvailable: () => true,
...partial,
};
}
function withContext(value: HostDefaultsContextValue, ui: React.ReactNode) {
return render(
<HostDefaultsContext.Provider value={value}>
{ui}
</HostDefaultsContext.Provider>,
);
}
describe("HostDefaultBadge", () => {
it("renders nothing outside the host editor", () => {
const { container } = render(
<HostDefaultBadge settingKey="core.sshPort" />,
);
expect(container.textContent).toBe("");
});
it("says where an inherited value comes from", () => {
withContext(
context({
source: () => ({ level: "folder", folderName: "Prod" }),
}),
<HostDefaultBadge settingKey="core.sshPort" />,
);
expect(screen.getByText("hostDefaults.source.folder:Prod")).toBeTruthy();
});
it("shows nothing for a value that follows the built-in default", () => {
const { container } = withContext(
context({ source: () => ({ level: "builtin" }) }),
<HostDefaultBadge settingKey="core.sshPort" />,
);
expect(container.textContent).toBe("");
});
it("offers a reset for a host's own value", () => {
const value = context({ isOwn: () => true });
withContext(value, <HostDefaultBadge settingKey="core.sshPort" />);
fireEvent.click(screen.getByText("hostDefaults.custom"));
expect(value.reset).toHaveBeenCalledWith("core.sshPort");
});
it("offers a clear for a value set at the level being edited", () => {
withContext(
context({ mode: "defaults", isOwn: () => true, source: () => undefined }),
<HostDefaultBadge settingKey="core.sshPort" />,
);
expect(screen.getByText("hostDefaults.setHere")).toBeTruthy();
});
it("says when nothing is set", () => {
withContext(
context({ source: () => undefined }),
<HostDefaultBadge settingKey="core.username" />,
);
expect(screen.getByText("hostDefaults.notSet")).toBeTruthy();
});
});
describe("in the defaults editor", () => {
it("hides a row whose key cannot be a default at this level", () => {
withContext(
context({ mode: "defaults", isAvailable: () => false }),
<SettingRow label="Jump hosts" defaultKey="core.jumpHosts">
<span />
</SettingRow>,
);
expect(screen.queryByText("Jump hosts")).toBeNull();
});
it("hides what only one host can have", () => {
withContext(
context({ mode: "defaults" }),
<HostOnly>
<span>Address</span>
</HostOnly>,
);
expect(screen.queryByText("Address")).toBeNull();
});
});
@@ -1,135 +0,0 @@
import { describe, it, expect, vi } from "vitest";
import { dispatchKeybindingAction } from "../../lib/keybinding-dispatch";
import type { Terminal } from "@xterm/xterm";
import type { KeybindingDispatchContext } from "../../lib/keybinding-dispatch";
function makeContext(
overrides: Partial<KeybindingDispatchContext> = {},
): KeybindingDispatchContext & {
sentData: string[];
} {
const sentData: string[] = [];
const ws = {
readyState: 1,
send: vi.fn((raw: string) => {
sentData.push(JSON.parse(raw).data);
}),
};
const ctx: KeybindingDispatchContext & { sentData: string[] } = {
terminal: {
getSelection: vi.fn(() => ""),
clearSelection: vi.fn(),
paste: vi.fn(),
} as unknown as Terminal,
webSocketRef: { current: ws as unknown as WebSocket },
writeTextToClipboard: vi.fn().mockResolvedValue(true),
readTextFromClipboard: vi.fn().mockResolvedValue(""),
getSnippetById: vi.fn().mockResolvedValue(undefined),
sentData,
...overrides,
};
return ctx;
}
describe("dispatchKeybindingAction", () => {
it("copy writes the selection to clipboard and clears it", () => {
const ctx = makeContext();
(ctx.terminal.getSelection as ReturnType<typeof vi.fn>).mockReturnValue(
"hello",
);
dispatchKeybindingAction({ type: "copy" }, ctx);
expect(ctx.writeTextToClipboard).toHaveBeenCalledWith("hello");
expect(ctx.terminal.clearSelection).toHaveBeenCalled();
});
it("copy does nothing when there is no selection", () => {
const ctx = makeContext();
dispatchKeybindingAction({ type: "copy" }, ctx);
expect(ctx.writeTextToClipboard).not.toHaveBeenCalled();
expect(ctx.terminal.clearSelection).not.toHaveBeenCalled();
});
it("paste reads the clipboard and pastes into the terminal", async () => {
const ctx = makeContext({
readTextFromClipboard: vi.fn().mockResolvedValue("pasted text"),
});
dispatchKeybindingAction({ type: "paste" }, ctx);
await Promise.resolve();
await Promise.resolve();
expect(ctx.terminal.paste).toHaveBeenCalledWith("pasted text");
});
it("sendControlCode sends the corresponding control byte", () => {
const ctx = makeContext();
dispatchKeybindingAction(
{ type: "sendControlCode", controlCode: "c" },
ctx,
);
expect(ctx.sentData).toEqual(["\x03"]);
});
it("sendText sends literal text without a trailing return by default", () => {
const ctx = makeContext();
dispatchKeybindingAction({ type: "sendText", text: "ls -la" }, ctx);
expect(ctx.sentData).toEqual(["ls -la"]);
});
it("sendText appends \\r when appendEnter is true", () => {
const ctx = makeContext();
dispatchKeybindingAction(
{ type: "sendText", text: "ls -la", appendEnter: true },
ctx,
);
expect(ctx.sentData).toEqual(["ls -la\r"]);
});
it("runSnippet resolves the snippet and sends its content with a trailing return", async () => {
const ctx = makeContext({
getSnippetById: vi.fn().mockResolvedValue({ content: "uptime" }),
});
dispatchKeybindingAction({ type: "runSnippet", snippetId: "1" }, ctx);
await Promise.resolve();
await Promise.resolve();
expect(ctx.sentData).toEqual(["uptime\r"]);
});
it("runSnippet does nothing when the snippet no longer exists", async () => {
const ctx = makeContext({
getSnippetById: vi.fn().mockResolvedValue(undefined),
});
dispatchKeybindingAction({ type: "runSnippet", snippetId: "1" }, ctx);
await Promise.resolve();
await Promise.resolve();
expect(ctx.sentData).toEqual([]);
});
it("runSnippet silently resolves host variables from hostContext", async () => {
const ctx = makeContext({
getSnippetById: vi
.fn()
.mockResolvedValue({ content: "ping $HOST -p $PORT" }),
hostContext: { ip: "10.0.0.5", username: "root", port: 22 },
});
dispatchKeybindingAction({ type: "runSnippet", snippetId: "1" }, ctx);
await Promise.resolve();
await Promise.resolve();
expect(ctx.sentData).toEqual(["ping 10.0.0.5 -p 22\r"]);
});
it("runSnippet defers to onSnippetNeedsInputs instead of sending when $INPUT_n is present", async () => {
const onSnippetNeedsInputs = vi.fn();
const ctx = makeContext({
getSnippetById: vi.fn().mockResolvedValue({ content: "echo $INPUT_1" }),
onSnippetNeedsInputs,
});
dispatchKeybindingAction({ type: "runSnippet", snippetId: "1" }, ctx);
await Promise.resolve();
await Promise.resolve();
expect(ctx.sentData).toEqual([]);
expect(onSnippetNeedsInputs).toHaveBeenCalledWith({
id: "1",
content: "echo $INPUT_1",
});
});
});
@@ -1,84 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createKeyedRequestCache } from "../../lib/keyed-request-cache";
afterEach(() => vi.useRealTimers());
describe("createKeyedRequestCache", () => {
it("coalesces requests per key without mixing keys", async () => {
let resolve!: (value: string) => void;
const loader = vi.fn(() => new Promise<string>((done) => (resolve = done)));
const cache = createKeyedRequestCache<string>(5_000);
const first = cache.get("host:1", loader);
const duplicate = cache.get("host:1", loader);
const other = cache.get("host:2", async () => "other");
resolve("shared");
await expect(Promise.all([first, duplicate, other])).resolves.toEqual([
"shared",
"shared",
"other",
]);
expect(loader).toHaveBeenCalledOnce();
});
it("can show stale data immediately while forcing one refresh", async () => {
vi.useFakeTimers();
const cache = createKeyedRequestCache<string>(1_000);
await cache.get("directory", async () => "old");
await vi.advanceTimersByTimeAsync(2_000);
expect(cache.peek("directory", 30_000)).toBe("old");
const loader = vi.fn(async () => "fresh");
const [a, b] = await Promise.all([
cache.get("directory", loader, { force: true }),
cache.get("directory", loader, { force: true }),
]);
expect([a, b]).toEqual(["fresh", "fresh"]);
expect(loader).toHaveBeenCalledOnce();
});
it("evicts the least recently used entry when bounded", async () => {
const cache = createKeyedRequestCache<number>(10_000, 2);
await cache.get("a", async () => 1);
await cache.get("b", async () => 2);
expect(cache.peek("a")).toBe(1);
await cache.get("c", async () => 3);
expect(cache.peek("a")).toBe(1);
expect(cache.peek("b")).toBeNull();
expect(cache.peek("c")).toBe(3);
});
it("keeps stale data when a refresh fails", async () => {
const cache = createKeyedRequestCache<string>(1_000);
await cache.get("key", async () => "safe");
await expect(
cache.get(
"key",
async () => {
throw new Error("offline");
},
{ force: true },
),
).rejects.toThrow("offline");
expect(cache.peek("key")).toBe("safe");
});
it("does not let an invalidated request overwrite newer data", async () => {
let resolveOld!: (value: string) => void;
const cache = createKeyedRequestCache<string>(10_000);
const oldRequest = cache.get(
"key",
() => new Promise<string>((resolve) => (resolveOld = resolve)),
);
cache.set("key", "optimistic");
resolveOld("old");
await oldRequest;
expect(cache.peek("key")).toBe("optimistic");
});
});
+52
View File
@@ -0,0 +1,52 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const isElectron = vi.hoisted(() => vi.fn(() => true));
const get = vi.hoisted(() => vi.fn());
vi.mock("@/lib/electron", () => ({ isElectron }));
vi.mock("@/main-axios", () => ({ authApi: { get } }));
const { getLinkedSession, notifySyncChanged } =
await import("@/lib/linked-server");
beforeEach(() => {
notifySyncChanged();
get.mockReset();
isElectron.mockReturnValue(true);
});
describe("linked session", () => {
it("reads the session from the embedded backend and caches it", async () => {
get.mockResolvedValue({
data: { serverUrl: "https://termix.example/", token: "t" },
});
await expect(getLinkedSession()).resolves.toEqual({
serverUrl: "https://termix.example",
token: "t",
});
await getLinkedSession();
expect(get).toHaveBeenCalledTimes(1);
expect(get).toHaveBeenCalledWith("/sync/link/session");
});
it("reads it again after a sync change", async () => {
get.mockResolvedValue({ data: { serverUrl: null, token: null } });
await expect(getLinkedSession()).resolves.toBeNull();
notifySyncChanged();
get.mockResolvedValue({ data: { serverUrl: "https://x", token: "t" } });
await expect(getLinkedSession()).resolves.toEqual({
serverUrl: "https://x",
token: "t",
});
});
it("is null on the web and when the backend cannot answer", async () => {
isElectron.mockReturnValue(false);
await expect(getLinkedSession()).resolves.toBeNull();
expect(get).not.toHaveBeenCalled();
isElectron.mockReturnValue(true);
get.mockRejectedValue(new Error("down"));
await expect(getLinkedSession()).resolves.toBeNull();
});
});
@@ -1,50 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { getMacLineNavigationSequence } from "../../lib/mac-line-navigation";
function keyEvent(
init: Partial<KeyboardEvent> & Pick<KeyboardEvent, "code">,
): KeyboardEvent {
return {
type: "keydown",
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
...init,
} as KeyboardEvent;
}
describe("getMacLineNavigationSequence", () => {
it("maps Cmd+arrow keys on macOS", () => {
vi.stubGlobal("navigator", { platform: "MacIntel" });
expect(
getMacLineNavigationSequence(
keyEvent({ code: "ArrowLeft", metaKey: true }),
),
).toBe("\x01");
expect(
getMacLineNavigationSequence(
keyEvent({ code: "ArrowRight", metaKey: true }),
),
).toBe("\x05");
vi.unstubAllGlobals();
});
it("ignores modified and non-mac shortcuts", () => {
vi.stubGlobal("navigator", { platform: "MacIntel" });
expect(
getMacLineNavigationSequence(
keyEvent({ code: "ArrowLeft", metaKey: true, shiftKey: true }),
),
).toBeNull();
vi.unstubAllGlobals();
vi.stubGlobal("navigator", { platform: "Win32" });
expect(
getMacLineNavigationSequence(
keyEvent({ code: "ArrowLeft", metaKey: true }),
),
).toBeNull();
vi.unstubAllGlobals();
});
});
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import { matchesPermission } from "@/lib/permissions";
/**
* These cases mirror PermissionManager.hasPermission on the backend. If that
* changes, this file is the tripwire.
*/
describe("matchesPermission", () => {
it("grants on an exact match", () => {
expect(
matchesPermission(["ai.services.use"], false, "ai.services.use"),
).toBe(true);
});
it("grants on the superuser wildcard", () => {
expect(matchesPermission(["*"], false, "anything.at.all")).toBe(true);
});
it("grants on each dotted wildcard level", () => {
expect(matchesPermission(["ai.services.*"], false, "ai.services.use")).toBe(
true,
);
expect(matchesPermission(["ai.*"], false, "ai.services.use")).toBe(true);
});
it("grants to an admin with no explicit permissions", () => {
expect(matchesPermission([], true, "ai.services.use")).toBe(true);
});
it("denies a non-admin without a matching grant", () => {
expect(matchesPermission([], false, "ai.services.use")).toBe(false);
expect(matchesPermission(["hosts.view"], false, "ai.services.use")).toBe(
false,
);
});
it("does not treat a prefix as a wildcard without the star", () => {
expect(matchesPermission(["ai.services"], false, "ai.services.use")).toBe(
false,
);
});
it("does not let a sibling wildcard grant an unrelated permission", () => {
expect(matchesPermission(["hosts.*"], false, "ai.services.use")).toBe(
false,
);
});
it("handles a single-segment permission", () => {
expect(matchesPermission(["admin"], false, "admin")).toBe(true);
// "admin.*" covers bare "admin" too: the backend builds the same
// single-segment wildcard, so the frontend must agree.
expect(matchesPermission(["admin.*"], false, "admin")).toBe(true);
expect(matchesPermission(["other"], false, "admin")).toBe(false);
});
});
+63
View File
@@ -0,0 +1,63 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({ electron: false }));
vi.mock("@/main-axios", () => ({
authApi: { defaults: { baseURL: "http://server:8080/" } },
createRemoteOriginApiInstance: vi.fn(),
}));
vi.mock("@/lib/electron", () => ({ isElectron: () => state.electron }));
vi.mock("@/lib/device-id", () => ({ getDeviceId: () => "device-1" }));
import { pluginFetch } from "@/lib/plugin-transport";
const fetchMock = vi.fn(async () => new Response("ok"));
beforeEach(() => {
state.electron = false;
fetchMock.mockClear();
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
vi.unstubAllGlobals();
localStorage.clear();
});
describe("pluginFetch", () => {
it("fetches the plugin's own mount point with the session cookie", async () => {
await pluginFetch("ai", "chat/stream", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{}",
});
const [url, init] = fetchMock.mock.calls[0] as unknown as [
string,
RequestInit,
];
expect(url).toBe("http://server:8080/plugin-api/ai/chat/stream");
expect(init.credentials).toBe("include");
expect(init.method).toBe("POST");
const headers = init.headers as Headers;
expect(headers.get("content-type")).toBe("application/json");
expect(headers.get("x-termix-device-id")).toBe("device-1");
expect(headers.get("authorization")).toBeNull();
});
it("sends the stored token in the desktop app, like the shared client", async () => {
state.electron = true;
localStorage.setItem("jwt", "token-1");
await pluginFetch("ai", "/status");
const [url, init] = fetchMock.mock.calls[0] as unknown as [
string,
RequestInit,
];
expect(url).toBe("http://server:8080/plugin-api/ai/status");
const headers = init.headers as Headers;
expect(headers.get("x-electron-app")).toBe("true");
expect(headers.get("authorization")).toBe("Bearer token-1");
});
});
+20
View File
@@ -0,0 +1,20 @@
import { afterEach, describe, expect, it } from "vitest";
import { rem, remScale } from "@/lib/rem";
afterEach(() => {
document.documentElement.style.fontSize = "";
});
describe("rem", () => {
it("states a Normal-size pixel length in rem", () => {
expect(rem(14)).toBe("1rem");
expect(rem(160)).toBe(`${160 / 14}rem`);
});
it("reports how much the interface size scales a pixel", () => {
document.documentElement.style.fontSize = "14px";
expect(remScale()).toBe(1);
document.documentElement.style.fontSize = "17.5px";
expect(remScale()).toBe(1.25);
});
});
+25 -84
View File
@@ -1,112 +1,53 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { SSHHost } from "@/types/index";
const isElectron = vi.hoisted(() => vi.fn());
const getLinkedSession = vi.hoisted(() => vi.fn());
const remoteApi = vi.hoisted(() => ({ get: vi.fn() }));
vi.mock("@/lib/electron", () => ({ isElectron }));
vi.mock("@/main-axios", () => ({ getRemoteStatsApi: () => remoteApi }));
vi.mock("@/lib/linked-server", () => ({ getLinkedSession }));
vi.mock("@/main-axios", () => ({ getRemoteCoreApi: () => remoteApi }));
import {
getConnectedRemoteApi,
hydrateLocalSharedHostAuth,
markRemoteSharedHosts,
resolveRemoteHostId,
} from "@/lib/remote-server-api";
describe("remote server API", () => {
const invoke = vi.fn();
const LINKED = { serverUrl: "https://termix.example", token: "t" };
describe("remote server API", () => {
beforeEach(() => {
isElectron.mockReset();
getLinkedSession.mockReset();
remoteApi.get.mockReset();
invoke.mockReset();
Object.defineProperty(window, "electronAPI", {
configurable: true,
value: { invoke },
});
});
it("is available only for a configured Electron sync server", async () => {
isElectron.mockReturnValue(false);
it("is available only while this desktop is linked", async () => {
getLinkedSession.mockResolvedValueOnce(null);
await expect(getConnectedRemoteApi()).resolves.toBeNull();
isElectron.mockReturnValue(true);
invoke.mockResolvedValueOnce({ serverUrl: "https://termix.example" });
getLinkedSession.mockResolvedValueOnce(LINKED);
await expect(getConnectedRemoteApi()).resolves.toBe(remoteApi);
});
it("maps a local host to the remote numeric id by syncId", async () => {
isElectron.mockReturnValue(true);
invoke.mockResolvedValue({ serverUrl: "https://termix.example" });
remoteApi.get.mockResolvedValue({
data: { rows: [{ id: 41, syncId: "host-a" }] },
});
it("asks the linked server for its id of a host by sync id", async () => {
getLinkedSession.mockResolvedValue(LINKED);
remoteApi.get.mockResolvedValueOnce({ data: { id: 41, name: "web" } });
await expect(resolveRemoteHostId("host-a")).resolves.toBe(41);
await expect(resolveRemoteHostId("host a")).resolves.toBe(41);
expect(remoteApi.get).toHaveBeenCalledWith("/sync/v2/hosts/host%20a");
});
it("answers null for an unknown host, no sync id, or no link", async () => {
getLinkedSession.mockResolvedValue(LINKED);
remoteApi.get.mockRejectedValueOnce(new Error("404"));
await expect(resolveRemoteHostId("missing")).resolves.toBeNull();
expect(remoteApi.get).toHaveBeenCalledWith("/sync/hosts");
await expect(resolveRemoteHostId(null)).resolves.toBeNull();
getLinkedSession.mockResolvedValue(null);
await expect(resolveRemoteHostId("host-a")).resolves.toBeNull();
});
it("keeps only shared remote hosts and gives them collision-free ids", () => {
const rows = markRemoteSharedHosts([
{ id: 4, isShared: false },
{
id: 9,
isShared: true,
syncId: "shared-host",
connectionOrigin: "local",
},
] as SSHHost[]);
expect(rows).toEqual([
expect.objectContaining({
id: -9,
syncId: "shared-host",
connectionOrigin: "local",
}),
]);
});
it("hydrates a remote shared host for a local connection without persisting remote ids", async () => {
isElectron.mockReturnValue(true);
invoke.mockResolvedValue({ serverUrl: "https://termix.example" });
remoteApi.get.mockResolvedValue({
data: {
username: "recipient",
authType: "key",
key: "PRIVATE KEY",
keyPassword: "passphrase",
keyType: "ed25519",
},
});
const result = await hydrateLocalSharedHostAuth({
id: -9,
isShared: true,
syncId: "shared-host",
credentialId: 77,
username: "owner",
authType: "key",
});
expect(remoteApi.get).toHaveBeenCalledWith(
"/host/db/host/9/local-connection-auth",
);
expect(result).toEqual(
expect.objectContaining({
id: -9,
syncId: null,
credentialId: undefined,
username: "recipient",
key: "PRIVATE KEY",
keyPassword: "passphrase",
}),
);
});
it("leaves local and owned hosts untouched", async () => {
const host = { id: 9, isShared: false, username: "root" };
it("leaves hosts as they are, since shared copies carry their own auth", async () => {
const host = { id: 9, isShared: true, username: "root" };
await expect(hydrateLocalSharedHostAuth(host)).resolves.toBe(host);
expect(remoteApi.get).not.toHaveBeenCalled();
});
@@ -1,41 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const isElectron = vi.hoisted(() => vi.fn());
vi.mock("@/lib/electron", () => ({ isElectron }));
import { requestRemoteSync } from "@/lib/remote-sync-trigger";
describe("requestRemoteSync", () => {
const invoke = vi.fn();
beforeEach(() => {
isElectron.mockReset();
invoke.mockReset();
Object.defineProperty(window, "electronAPI", {
configurable: true,
value: { invoke },
});
});
it("starts a sync when the desktop is connected to a server", async () => {
isElectron.mockReturnValue(true);
invoke.mockResolvedValueOnce({ serverUrl: "https://termix.example" });
await requestRemoteSync();
expect(invoke).toHaveBeenNthCalledWith(1, "get-remote-sync-config");
expect(invoke).toHaveBeenNthCalledWith(2, "remote-sync-now");
});
it("does nothing outside Electron or without a configured server", async () => {
isElectron.mockReturnValue(false);
await requestRemoteSync();
expect(invoke).not.toHaveBeenCalled();
isElectron.mockReturnValue(true);
invoke.mockResolvedValueOnce(null);
await requestRemoteSync();
expect(invoke).toHaveBeenCalledOnce();
});
});
@@ -1,79 +0,0 @@
import { describe, it, expect } from "vitest";
import {
extractSnippetInputs,
hasSnippetInputs,
resolveSnippetContent,
} from "../../lib/snippet-variables";
describe("extractSnippetInputs", () => {
it("extracts a single unlabeled input", () => {
expect(extractSnippetInputs("ping $INPUT_1")).toEqual([
{ key: "INPUT_1", label: "Input 1" },
]);
});
it("extracts a labeled input using brace syntax", () => {
expect(
extractSnippetInputs("nc -zv $HOST ${INPUT_1:Port to check}"),
).toEqual([{ key: "INPUT_1", label: "Port to check" }]);
});
it("plain (non-braced) references have no label", () => {
expect(extractSnippetInputs("echo $INPUT_2")).toEqual([
{ key: "INPUT_2", label: "Input 2" },
]);
});
it("de-duplicates repeated references and preserves first-seen order", () => {
expect(
extractSnippetInputs("$INPUT_2 then $INPUT_1 then $INPUT_2 again"),
).toEqual([
{ key: "INPUT_2", label: "Input 2" },
{ key: "INPUT_1", label: "Input 1" },
]);
});
it("returns an empty array when there are no placeholders", () => {
expect(extractSnippetInputs("uptime")).toEqual([]);
});
});
describe("hasSnippetInputs", () => {
it("returns true when a snippet has an input placeholder", () => {
expect(hasSnippetInputs("echo $INPUT_1")).toBe(true);
});
it("returns false when a snippet has no input placeholder", () => {
expect(hasSnippetInputs("echo $HOST")).toBe(false);
});
});
describe("resolveSnippetContent", () => {
const host = { ip: "10.0.0.5", username: "root", port: 22, name: "web-01" };
it("substitutes host variables", () => {
expect(
resolveSnippetContent("ssh $USER@$HOST -p $PORT # $NAME", host),
).toBe("ssh root@10.0.0.5 -p 22 # web-01");
});
it("supports brace syntax for host variables", () => {
expect(resolveSnippetContent("ping ${HOST}", host)).toBe("ping 10.0.0.5");
});
it("substitutes input placeholders", () => {
expect(
resolveSnippetContent("nc -zv $HOST ${INPUT_1:Port}", host, {
INPUT_1: "8080",
}),
).toBe("nc -zv 10.0.0.5 8080");
});
it("leaves host variables literal when no host context is given", () => {
expect(resolveSnippetContent("ping $HOST", null)).toBe("ping $HOST");
});
it("leaves input placeholders literal when no value was supplied", () => {
expect(resolveSnippetContent("echo $INPUT_1", null)).toBe("echo $INPUT_1");
});
});
+55
View File
@@ -0,0 +1,55 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const getSyncStatus = vi.hoisted(() => vi.fn());
const notifySyncChanged = vi.hoisted(() => vi.fn());
vi.mock("@/lib/electron", () => ({ isElectron: () => true }));
vi.mock("@/api/sync-api", () => ({ getSyncStatus }));
vi.mock("@/lib/linked-server", () => ({ notifySyncChanged }));
const store = await import("@/lib/sync-status");
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
describe("sync status store", () => {
let unsubscribe: () => void = () => {};
const events: string[] = [];
const record = (event: Event) => events.push(event.type);
beforeEach(() => {
events.length = 0;
for (const type of ["hosts:refresh", "termix:hosts-changed"]) {
window.addEventListener(type, record);
}
});
afterEach(() => {
unsubscribe();
for (const type of ["hosts:refresh", "termix:hosts-changed"]) {
window.removeEventListener(type, record);
}
});
it("polls while subscribed and tells views to reload after a pass", async () => {
getSyncStatus.mockResolvedValue({
linked: true,
lastSyncAt: "2026-09-25T10:00:00Z",
entities: [],
});
const listener = vi.fn();
unsubscribe = store.subscribeSyncStatus(listener);
await flush();
expect(store.getSyncStatusSnapshot()?.linked).toBe(true);
expect(listener).toHaveBeenCalled();
// The first read only sets the baseline.
expect(events).toEqual([]);
store.setSyncStatus({
linked: true,
lastSyncAt: "2026-09-25T10:05:00Z",
entities: [],
});
expect(events).toEqual(["hosts:refresh", "termix:hosts-changed"]);
expect(notifySyncChanged).toHaveBeenCalled();
});
});
-185
View File
@@ -1,185 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import {
parseTerminalMacros,
runTerminalMacro,
type MacroStep,
type TerminalMacro,
} from "@/lib/terminal-macros";
function macro(steps: MacroStep[]): TerminalMacro {
return {
id: "macro-1",
name: "Test",
steps,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
};
}
describe("terminal macro runner", () => {
it("runs send, delay, regex wait, condition, and repeat steps", async () => {
vi.useFakeTimers();
const sent: string[] = [];
let listener = (_data: string) => {};
const run = runTerminalMacro(
macro([
{ id: "send", type: "send", text: "status", pressEnter: true },
{
id: "wait",
type: "wait",
pattern: "READY\\s+42",
timeoutMs: 1000,
onTimeout: "stop",
},
{
id: "if",
type: "if",
pattern: "READY",
then: [
{
id: "repeat",
type: "repeat",
count: 2,
steps: [
{ id: "ok", type: "send", text: "ok", pressEnter: false },
],
},
],
else: [],
},
]),
{
send: (data) => sent.push(data),
subscribe: (next) => {
listener = next;
return () => {};
},
},
);
await vi.advanceTimersByTimeAsync(1);
listener("READY 42");
await run;
expect(sent).toEqual(["status\r", "ok", "ok"]);
vi.useRealTimers();
});
it("stops when a required regex times out", async () => {
vi.useFakeTimers();
const run = runTerminalMacro(
macro([
{
id: "wait",
type: "wait",
pattern: "never",
timeoutMs: 100,
onTimeout: "stop",
},
]),
{ send: () => {}, subscribe: () => () => {} },
);
const rejection = expect(run).rejects.toThrow("Timed out");
await vi.advanceTimersByTimeAsync(101);
await rejection;
vi.useRealTimers();
});
it("sanitizes persisted macro bounds and drops unknown steps", () => {
const parsed = parseTerminalMacros(
JSON.stringify([
{
id: "m",
name: "Macro",
steps: [
{ id: "d", type: "delay", milliseconds: 999_999 },
{ id: "r", type: "repeat", count: 1000, steps: [] },
{ id: "bad", type: "execute-javascript", code: "nope" },
],
},
]),
);
expect(parsed[0].steps).toEqual([
{ id: "d", type: "delay", milliseconds: 300_000 },
{ id: "r", type: "repeat", count: 100, steps: [] },
]);
});
it("matches literal text without regex escaping when isRegex is false", async () => {
vi.useFakeTimers();
const sent: string[] = [];
let listener = (_data: string) => {};
const run = runTerminalMacro(
macro([
{
id: "wait",
type: "wait",
pattern: "progress (1/2)",
isRegex: false,
timeoutMs: 1000,
onTimeout: "stop",
},
{ id: "send", type: "send", text: "done", pressEnter: false },
]),
{
send: (data) => sent.push(data),
subscribe: (next) => {
listener = next;
return () => {};
},
},
);
await vi.advanceTimersByTimeAsync(1);
listener("progress (1/2)");
await run;
expect(sent).toEqual(["done"]);
vi.useRealTimers();
});
it("falls back to literal matching when a regex is invalid", async () => {
vi.useFakeTimers();
const sent: string[] = [];
let listener = (_data: string) => {};
const run = runTerminalMacro(
macro([
{
id: "wait",
type: "wait",
pattern: "oops(",
isRegex: true,
timeoutMs: 1000,
onTimeout: "stop",
},
{ id: "send", type: "send", text: "ok", pressEnter: false },
]),
{
send: (data) => sent.push(data),
subscribe: (next) => {
listener = next;
return () => {};
},
},
);
await vi.advanceTimersByTimeAsync(1);
listener("oops(");
await run;
expect(sent).toEqual(["ok"]);
vi.useRealTimers();
});
it("branches on literal if-step text", async () => {
const sent: string[] = [];
await runTerminalMacro(
macro([
{
id: "if",
type: "if",
pattern: "a.b",
isRegex: false,
then: [{ id: "y", type: "send", text: "yes", pressEnter: false }],
else: [{ id: "n", type: "send", text: "no", pressEnter: false }],
},
]),
{ send: (data) => sent.push(data), subscribe: () => () => {} },
);
// "a.b" as a literal must not match "axb"
expect(sent).toEqual(["no"]);
});
});
@@ -1,441 +0,0 @@
import { describe, it, expect } from "vitest";
import {
highlightTerminalOutput,
updateControlStringMode,
} from "../../lib/terminal-syntax-highlighter.js";
const ESC = "\x1b";
describe("highlightTerminalOutput", () => {
it("returns empty/whitespace text unchanged", () => {
expect(highlightTerminalOutput("")).toBe("");
expect(highlightTerminalOutput(" ")).toBe(" ");
});
it("wraps ERROR in bright red", () => {
const out = highlightTerminalOutput("Something ERROR happened");
expect(out).toContain(ESC + "[91m");
expect(out).toContain("ERROR");
});
it("wraps lowercase error in bright red (case-insensitive)", () => {
const out = highlightTerminalOutput("something error happened");
expect(out).toContain(ESC + "[91m");
});
it("wraps Error (mixed case) in bright red", () => {
const out = highlightTerminalOutput("Error: connection refused");
expect(out).toContain(ESC + "[91m");
});
it("wraps warn (lowercase) in bright yellow", () => {
const out = highlightTerminalOutput("warn: disk almost full");
expect(out).toContain(ESC + "[93m");
});
it("wraps warning (lowercase) in bright yellow", () => {
const out = highlightTerminalOutput("warning: something is off");
expect(out).toContain(ESC + "[93m");
});
it("highlights IPv4 addresses in magenta", () => {
const out = highlightTerminalOutput("connect to 192.168.1.10 now");
expect(out).toContain("192.168.1.10");
expect(out).toContain(ESC + "[35m");
});
it("leaves text with no matchable tokens unchanged", () => {
const plain = "just a normal sentence here";
expect(highlightTerminalOutput(plain)).toBe(plain);
});
it("leaves text ending in an incomplete ANSI escape untouched", () => {
const partial = `loading${ESC}[`;
expect(highlightTerminalOutput(partial)).toBe(partial);
});
it("skips TUI cursor-positioning frames (nano/vim protection)", () => {
const tuiFrame = `${ESC}[H${ESC}[2J some nano content`;
expect(highlightTerminalOutput(tuiFrame)).toBe(tuiFrame);
});
it("skips private TUI mode sequences", () => {
const tuiFrame = `${ESC}[?1049h${ESC}[?25lERROR at /var/log/app.log`;
expect(highlightTerminalOutput(tuiFrame)).toBe(tuiFrame);
});
it("skips bracketed paste mode sequences", () => {
const chunk = `${ESC}[?2004hERROR: enabled paste mode`;
expect(highlightTerminalOutput(chunk)).toBe(chunk);
});
it("skips TUI frames with box-drawing characters", () => {
const chunk = `┌─ /var/log ─┐\n│ ERROR file │`;
expect(highlightTerminalOutput(chunk)).toBe(chunk);
});
it("skips DEC line-drawing charset frames", () => {
const chunk = `${ESC}(0lqq /var/log qk${ESC}(B`;
expect(highlightTerminalOutput(chunk)).toBe(chunk);
});
it("skips OSC current-directory sequences used by fish prompts", () => {
const chunk = `${ESC}]7;file://server/home/user/docker/sonarr\x07user@server ~/docker/sonarr> `;
expect(highlightTerminalOutput(chunk)).toBe(chunk);
});
it("skips OSC title sequences", () => {
const chunk = `${ESC}]0;user@server:/var/log\x07ERROR after title`;
expect(highlightTerminalOutput(chunk)).toBe(chunk);
});
it("highlights text that already has ANSI codes", () => {
let heavy = "";
for (let i = 0; i < 12; i++) heavy += `${ESC}[32mgreen${ESC}[0m `;
heavy += "ERROR at line 5";
const out = highlightTerminalOutput(heavy);
expect(out).toContain(ESC + "[91m");
});
it("does not process lines exceeding MAX_LINE_LENGTH", () => {
const huge = "ERROR " + "x".repeat(3000);
expect(highlightTerminalOutput(huge)).toBe(huge);
});
it("highlights simple absolute paths in cyan", () => {
const out = highlightTerminalOutput("log at /var/log/nginx/access.log");
expect(out).toContain(ESC + "[36m");
expect(out).toContain("/var/log/nginx/access.log");
});
it("highlights absolute paths with glob wildcards in cyan", () => {
const out = highlightTerminalOutput("files: /usr/share/doc/*/copyright");
expect(out).toContain(ESC + "[36m");
expect(out).toContain("/usr/share/doc/*/copyright");
});
it("highlights home paths in cyan", () => {
const out = highlightTerminalOutput("file: ~/documents/notes.txt");
expect(out).toContain(ESC + "[36m");
expect(out).toContain("~/documents/notes.txt");
});
it("highlights bracket timestamps in bright black", () => {
const out = highlightTerminalOutput("[12:34:56] server started");
expect(out).toContain(ESC + "[90m");
expect(out).toContain("[12:34:56]");
});
it("does not highlight out-of-range bracket timestamps", () => {
// [99:99] is not a valid time
const out = highlightTerminalOutput("[99:99] something");
expect(out).not.toContain(ESC + "[90m");
});
it("highlights ISO date timestamps in bright black", () => {
const out = highlightTerminalOutput("2024-01-15 event occurred");
expect(out).toContain(ESC + "[90m");
expect(out).toContain("2024-01-15");
});
it("does not highlight version strings as ISO dates", () => {
// 2.4.0 or 1.2024.3 should not trigger ISO date
const out = highlightTerminalOutput("version 2.4.0 released");
expect(out).toBe("version 2.4.0 released");
});
it("highlights labeled numbers (port)", () => {
const out = highlightTerminalOutput("listening on port 8080");
expect(out).toContain(ESC + "[96m");
expect(out).toContain("8080");
});
it("highlights labeled numbers (exit)", () => {
const out = highlightTerminalOutput("process exited with exit 1");
expect(out).toContain(ESC + "[96m");
});
it("highlights labeled numbers (status)", () => {
const out = highlightTerminalOutput("returned status 404");
expect(out).toContain(ESC + "[96m");
});
it("does not highlight standalone numbers outside labeled context", () => {
const out = highlightTerminalOutput("there are 42 files here");
expect(out).toBe("there are 42 files here");
});
it("does not highlight 'up' or 'active' as success", () => {
const out = highlightTerminalOutput("service is up and running");
expect(out).not.toContain(ESC + "[92m");
});
it("highlights unambiguous success keywords (case-insensitive)", () => {
const out = highlightTerminalOutput("Test passed successfully");
expect(out).toContain(ESC + "[92m");
});
it("highlights URLs with blue+underline", () => {
const out = highlightTerminalOutput("visit https://example.com now");
expect(out).toContain(ESC + "[34m");
expect(out).toContain(ESC + "[4m");
});
it("preserves \\r in CRLF terminal output", () => {
const out = highlightTerminalOutput("ERROR occurred\r\n");
expect(out).toContain("\r\n");
});
it("processes multi-line text line by line", () => {
const text = "some output\nERROR: failed\n";
const out = highlightTerminalOutput(text);
expect(out).toContain(ESC + "[91m");
});
it("respects category options - disabling logLevels skips error highlight", () => {
const out = highlightTerminalOutput("ERROR occurred", { logLevels: false });
expect(out).not.toContain(ESC + "[91m");
});
it("respects category options - disabling paths skips path highlight", () => {
const out = highlightTerminalOutput("at /usr/share/doc/something/file", {
paths: false,
});
expect(out).not.toContain(ESC + "[36m");
});
it("respects category options - disabling urls skips url highlight", () => {
const out = highlightTerminalOutput("see https://example.com", {
urls: false,
});
expect(out).not.toContain(ESC + "[34m");
});
it("respects category options - disabling ipAddresses skips IP highlight", () => {
const out = highlightTerminalOutput("connect to 192.168.1.1", {
ipAddresses: false,
});
expect(out).not.toContain(ESC + "[35m");
});
it("respects category options - disabling timestamps skips ISO date highlight", () => {
const out = highlightTerminalOutput("2024-01-15 something", {
timestamps: false,
});
expect(out).not.toContain(ESC + "[90m");
});
it("respects category options - disabling numbers skips port highlight", () => {
const out = highlightTerminalOutput("listening on port 8080", {
numbers: false,
});
expect(out).not.toContain(ESC + "[96m");
});
it("skips highlighting when chunk contains a mid-line carriage return", () => {
// Progress bars and shell prompt redraws use \r to overwrite the current line
const chunk = "downloading...\rdownloading [====] 100%";
expect(highlightTerminalOutput(chunk)).toBe(chunk);
});
it("still processes CRLF line endings (\\r\\n is fine)", () => {
const out = highlightTerminalOutput("ERROR occurred\r\n");
expect(out).toContain(ESC + "[91m");
});
it("does not highlight shell prompt lines (user@host:path$)", () => {
const prompt = `${ESC}[01;32mpi@raspberrypi${ESC}[00m:${ESC}[01;34m/home/pi${ESC}[00m$ `;
const out = highlightTerminalOutput(prompt);
expect(out).toBe(prompt);
});
it("does not highlight plain-text shell prompt line", () => {
const prompt = "pi@raspberrypi:/home/pi$ ";
const out = highlightTerminalOutput(prompt);
expect(out).toBe(prompt);
});
it("does not highlight log keywords inside bracketed SSH headings", () => {
const out = highlightTerminalOutput("[info@archlinux] command output");
expect(out).toBe("[info@archlinux] command output");
});
it("still highlights log keywords after a bracketed SSH heading", () => {
const out = highlightTerminalOutput("[warning@host] command ERROR");
expect(out).not.toContain(`${ESC}[93mwarning`);
expect(out).toContain(`${ESC}[91mERROR`);
});
it("does not highlight a log-level-like username split across ANSI segments in a colored SSH heading", () => {
// Prompt themes often color the user and host portions of "[user@host]"
// separately, so the heading is not one contiguous plain-text segment.
const chunk = `[${ESC}[1;33mwarning${ESC}[0m@host] some command output`;
const out = highlightTerminalOutput(chunk);
expect(out).toBe(chunk);
});
it("does not highlight 'success' when immediately followed by a path (cd output)", () => {
// Some shells print "success~/new/dir" or "success/path" after a cd command
const out = highlightTerminalOutput("success~/home/user/projects");
expect(out).not.toContain(ESC + "[92m");
});
it("still highlights 'success' when not followed by a path separator", () => {
const out = highlightTerminalOutput("Build success: all tests passed");
expect(out).toContain(ESC + "[92m");
});
it("highlights output lines but not the prompt in a mixed chunk", () => {
const chunk = `ERROR: disk full\npi@raspberrypi:~$ `;
const out = highlightTerminalOutput(chunk);
// The error line should be highlighted
expect(out).toContain(ESC + "[91m");
// The prompt line should be unchanged
expect(out).toContain("pi@raspberrypi:~$ ");
const promptLine = out.split("\n")[1];
expect(promptLine).toBe("pi@raspberrypi:~$ ");
});
it("does not highlight paths inside a command-echo line (prompt + command)", () => {
// When the shell echoes the user's command, it prefixes the prompt.
// The path in the prompt portion (/home/user) must not be highlighted —
// the shell already colored it, and re-coloring it causes the doubled-path bug.
const echo = "user@host:/home/user$ cd /opt/app/bin/files";
const out = highlightTerminalOutput(echo);
expect(out).toBe(echo);
});
it("does not highlight paths in colored command-echo lines (root prompt)", () => {
const echo = `${ESC}[01;32mroot@host${ESC}[00m:${ESC}[01;34m/home/user${ESC}[00m# cd /opt/app/bin/files`;
const out = highlightTerminalOutput(echo);
expect(out).toBe(echo);
});
it("does not highlight the last line of a multi-line chunk with no trailing newline", () => {
// In a multi-line chunk, the trailing fragment without \n could be a live
// readline input line. Injecting ANSI bytes there breaks bash's cursor
// arithmetic (causes cursor jump / text shift when using arrow keys).
const chunk = "ERROR: disk full\nuser@host:/path$ cd /var/log";
const out = highlightTerminalOutput(chunk);
// First line (terminated by \n) gets highlighted
expect(out.split("\n")[0]).toContain(ESC + "[91m");
// Last unterminated fragment is left verbatim
expect(out.split("\n")[1]).toBe("user@host:/path$ cd /var/log");
});
it("still highlights a single-line chunk with no trailing newline", () => {
// A single-line chunk with no \n is plain command output, not a readline
// input fragment — highlight it normally.
const out = highlightTerminalOutput("ERROR: something failed");
expect(out).toContain(ESC + "[91m");
});
it("highlights all lines when the chunk ends with a newline", () => {
// When a chunk ends with \n every line is complete output — highlight them all.
const chunk = "ERROR: disk full\nconnect to /var/run/app.sock\n";
const out = highlightTerminalOutput(chunk);
expect(out.split("\n")[0]).toContain(ESC + "[91m");
expect(out.split("\n")[1]).toContain(ESC + "[36m");
});
});
describe("updateControlStringMode", () => {
const BEL = "\x07";
it("stays inactive for output with no control string", () => {
expect(updateControlStringMode("total 4\nfile.txt\n", false)).toEqual({
isActive: false,
wasActive: false,
});
});
it("goes active when a control string is left open at the chunk end", () => {
// What PROMPT_COMMAND emits: ESC ] 0 ; <title>, terminator not yet sent.
const chunk = `${ESC}]0;user@host:~/path/current-dir`;
expect(updateControlStringMode(chunk, false)).toEqual({
isActive: true,
wasActive: false,
});
});
it("clears on the continuation chunk that carries the terminator", () => {
// The continuation has no escape byte at all, which is why every
// single-chunk guard misses it.
const continuation = `${BEL}[user@host current-dir]$ `;
expect(updateControlStringMode(continuation, true)).toEqual({
isActive: false,
wasActive: true,
});
});
it("reports a chunk that opens and closes a control string as inactive", () => {
const chunk = `${ESC}]0;title${BEL}ready\n`;
expect(updateControlStringMode(chunk, false)).toEqual({
isActive: false,
wasActive: false,
});
});
it("accepts ST as a terminator", () => {
expect(
updateControlStringMode(`${ESC}]7;file:///tmp${ESC}\\`, false),
).toEqual({
isActive: false,
wasActive: false,
});
});
it("treats a trailing lone ESC as active, since its meaning is in the next chunk", () => {
expect(updateControlStringMode(`done${ESC}`, false)).toEqual({
isActive: true,
wasActive: false,
});
});
it("recognises DCS, APC and PM openers too", () => {
for (const opener of ["P", "^", "_"]) {
expect(
updateControlStringMode(`${ESC}${opener}payload`, false).isActive,
).toBe(true);
}
});
it("does not treat CSI as a control string", () => {
expect(updateControlStringMode(`${ESC}[31mred${ESC}[0m`, false)).toEqual({
isActive: false,
wasActive: false,
});
});
it("leaves a continuation chunk unhighlighted", () => {
// The bug: this chunk highlights cleanly on its own, and injecting SGR
// bytes into an open OSC string dumps the payload onto the screen.
const continuation = `${BEL}connect to 10.0.0.11 failed`;
expect(highlightTerminalOutput(continuation)).not.toBe(continuation);
const state = updateControlStringMode(continuation, true);
expect(state.wasActive).toBe(true);
});
it("passes through SGR mouse-tracking reports untouched (issue #1023)", () => {
// ESC[<Cb;Cx;CyM is the SGR (1006) mouse-report format. The `<` marker
// byte was missing from the parameter-byte character class, so these
// sequences weren't recognised as ANSI escapes and their raw digits
// leaked onto the screen as visible text inside `screen`/tmux sessions.
const report = `${ESC}[<35;191;1M`;
expect(highlightTerminalOutput(report)).toBe(report);
});
it("passes through a burst of SGR mouse reports untouched", () => {
const burst = `${ESC}[<35;191;1M${ESC}[<35;186;2M${ESC}[<35;46;21M`;
expect(highlightTerminalOutput(burst)).toBe(burst);
});
it("treats a chunk ending mid SGR-mouse-report as incomplete", () => {
const partial = `foo${ESC}[<35;191`;
expect(highlightTerminalOutput(partial)).toBe(partial);
});
});
+34
View File
@@ -0,0 +1,34 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { applyFontSize } from "@/lib/theme";
type ElectronWindow = { electronAPI?: unknown };
afterEach(() => {
delete (window as unknown as ElectronWindow).electronAPI;
document.documentElement.className = "";
localStorage.clear();
});
describe("interface size", () => {
it("sets the root size class and remembers it", () => {
applyFontSize("lg");
expect(document.documentElement.classList.contains("fs-lg")).toBe(true);
applyFontSize("sm");
expect(document.documentElement.className).toBe("fs-sm");
expect(localStorage.getItem("termix-font-size")).toBe("sm");
});
it("takes back the window zoom an earlier desktop build set", () => {
const setZoomFactor = vi.fn();
(window as unknown as ElectronWindow).electronAPI = { setZoomFactor };
applyFontSize("xl");
expect(setZoomFactor).toHaveBeenCalledWith(1);
expect(document.documentElement.classList.contains("fs-xl")).toBe(true);
});
it("falls back to Normal for an unknown size", () => {
applyFontSize("huge" as never);
expect(document.documentElement.classList.contains("fs-md")).toBe(true);
expect(localStorage.getItem("termix-font-size")).toBe("md");
});
});
@@ -1,30 +0,0 @@
import { renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import {
computeReconnectDelay,
useConnectionRetry,
} from "../../lib/useConnectionRetry.ts";
describe("connection retry delay", () => {
it("uses exponential backoff with bounded jitter", () => {
expect(computeReconnectDelay(1, 2000, 8000, () => 0.5)).toBe(2000);
expect(computeReconnectDelay(2, 2000, 8000, () => 0)).toBe(3600);
expect(computeReconnectDelay(2, 2000, 8000, () => 1)).toBe(4400);
});
it("never exceeds the configured cap", () => {
expect(computeReconnectDelay(8, 2000, 8000, () => 1)).toBe(8000);
});
});
describe("useConnectionRetry", () => {
it("turns a rejected async connection into a failed state", async () => {
const connect = vi.fn().mockRejectedValue(new Error("offline"));
const { result } = renderHook(() =>
useConnectionRetry({ connect, enabled: false }),
);
await waitFor(() => expect(result.current.status).toBe("error"));
expect(connect).toHaveBeenCalledOnce();
});
});
-367
View File
@@ -1,367 +0,0 @@
import { describe, expect, it } from "vitest";
import {
currentTunnelHost,
resolveWebEndpointUrl,
separatedTunnelHost,
sharesCookieSiteWithPage,
webEndpointRefusalReason,
} from "@/lib/web-endpoint-url";
import type { WebEndpoint } from "@/types/index";
function endpoint(overrides: Partial<WebEndpoint> = {}): WebEndpoint {
return {
id: "e1",
label: "Proxmox",
scheme: "https",
port: 8006,
access: "direct",
render: "external",
...overrides,
};
}
describe("resolveWebEndpointUrl", () => {
it("builds a direct URL at the host address", () => {
expect(
resolveWebEndpointUrl({
hostAddress: "192.168.1.10",
endpoint: endpoint(),
}),
).toBe("https://192.168.1.10:8006/");
});
it("builds a direct URL for a hostname", () => {
expect(
resolveWebEndpointUrl({
hostAddress: "nas.local",
endpoint: endpoint({ port: 443 }),
}),
).toBe("https://nas.local:443/");
});
it("uses the local port for tunnel access, dropping the endpoint's own port", () => {
expect(
resolveWebEndpointUrl({
hostAddress: "192.168.1.10",
endpoint: endpoint({ access: "tunnel", scheme: "http", port: 8006 }),
localPort: 41234,
}),
).toBe("http://127.0.0.1:41234/");
});
it("defaults a missing path to /", () => {
expect(
resolveWebEndpointUrl({
hostAddress: "10.0.0.5",
endpoint: endpoint({ scheme: "http", port: 80, path: undefined }),
}),
).toBe("http://10.0.0.5:80/");
});
it("keeps an explicit path and its query", () => {
expect(
resolveWebEndpointUrl({
hostAddress: "10.0.0.5",
endpoint: endpoint({
scheme: "http",
port: 9000,
path: "/admin?tab=1",
}),
}),
).toBe("http://10.0.0.5:9000/admin?tab=1");
});
it("throws when tunnel access has no local port", () => {
expect(() =>
resolveWebEndpointUrl({
hostAddress: "10.0.0.5",
endpoint: endpoint({ access: "tunnel" }),
}),
).toThrow(/local port/i);
});
it("brackets a bare IPv6 host address", () => {
expect(
resolveWebEndpointUrl({
hostAddress: "fd00::1",
endpoint: endpoint({ scheme: "http", port: 8080 }),
}),
).toBe("http://[fd00::1]:8080/");
});
it("brackets a bare IPv6 tunnel host", () => {
expect(
resolveWebEndpointUrl({
hostAddress: "10.0.0.5",
endpoint: endpoint({ access: "tunnel", scheme: "http" }),
localPort: 41234,
tunnelHost: "fd00::1",
}),
).toBe("http://[fd00::1]:41234/");
});
it("uses an explicit tunnel host when given", () => {
expect(
resolveWebEndpointUrl({
hostAddress: "10.0.0.5",
endpoint: endpoint({ access: "tunnel", scheme: "http" }),
localPort: 41234,
tunnelHost: "termix.lan",
}),
).toBe("http://termix.lan:41234/");
});
});
/**
* 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:
* the browser attaches the jwt cookie to every request the framed
* third-party server receives, and a Set-Cookie from that server lands in the
* jar Termix's own API calls read from (both auth middlewares prefer the
* cookie over the Authorization header).
*
* Both directions were reproduced against a real SSH forward. separatedTunnelHost
* is the whole mitigation: a host string that reaches the same machine but is
* a DIFFERENT cookie-jar key.
*/
describe("separatedTunnelHost", () => {
it("maps each loopback spelling to a different one", () => {
expect(separatedTunnelHost("localhost")).toBe("127.0.0.1");
expect(separatedTunnelHost("127.0.0.1")).toBe("localhost");
expect(separatedTunnelHost("::1")).toBe("127.0.0.1");
expect(separatedTunnelHost("[::1]")).toBe("127.0.0.1");
});
it("never returns the host it was given, which would be no separation", () => {
for (const host of ["localhost", "127.0.0.1", "::1", "[::1]"]) {
expect(separatedTunnelHost(host)).not.toBe(host);
}
});
it("is case- and whitespace-insensitive", () => {
expect(separatedTunnelHost(" LOCALHOST ")).toBe("127.0.0.1");
});
it("returns null for a host with no alias, rather than guessing", () => {
// A same-registrable-domain alias would NOT be safe: the target could
// answer Set-Cookie with Domain=example.com and reach Termix anyway.
// Only loopback literals qualify -- they cannot carry a Domain.
expect(separatedTunnelHost("termix.example.com")).toBeNull();
expect(separatedTunnelHost("192.168.1.50")).toBeNull();
expect(separatedTunnelHost("")).toBeNull();
});
});
describe("currentTunnelHost", () => {
it("is loopback on the desktop, whose API base is localhost", () => {
// Two different cookie-jar keys. Do not "simplify" either to match.
expect(currentTunnelHost(true)).toBe("127.0.0.1");
});
it("swaps to the other loopback spelling when Termix is served at localhost", () => {
expect(currentTunnelHost(false, "localhost")).toBe("127.0.0.1");
});
it("swaps the other way when Termix is served at 127.0.0.1", () => {
expect(currentTunnelHost(false, "127.0.0.1")).toBe("localhost");
});
it("has no answer for a page host with no loopback alias", () => {
expect(currentTunnelHost(false, "termix.example.com")).toBeNull();
expect(currentTunnelHost(false, "192.168.1.50")).toBeNull();
});
});
/**
* The cookie leak is not tunnel-only. A DIRECT endpoint points at the host's
* own address, and when that host is the same one serving Termix in a browser
* (a different port is not a different cookie key), the framed third-party
* service receives Termix's `jwt` -- and can set one back. So the refusal has
* to cover direct access too, using the endpoint's target host rather than a
* bind address.
*/
describe("sharesCookieSiteWithPage", () => {
it("is true for the exact same host, because cookies ignore the port", () => {
expect(sharesCookieSiteWithPage("termix.example", "termix.example")).toBe(
true,
);
});
it("is true for a parent or sub domain, which a Domain-scoped cookie crosses", () => {
expect(
sharesCookieSiteWithPage("app.termix.example", "termix.example"),
).toBe(true);
expect(
sharesCookieSiteWithPage("termix.example", "app.termix.example"),
).toBe(true);
});
it("is false for a genuinely different host", () => {
expect(sharesCookieSiteWithPage("192.168.1.10", "termix.example")).toBe(
false,
);
expect(sharesCookieSiteWithPage("nas.local", "termix.example")).toBe(false);
});
it("is case- and whitespace-insensitive and ignores a trailing dot", () => {
expect(
sharesCookieSiteWithPage(" TERMIX.example. ", "termix.example"),
).toBe(true);
});
it("does not treat a shared suffix off a label boundary as same-site", () => {
// "eviltermix.example" ends with "termix.example" as a string but not on a
// dot boundary -- treating it as same-site would let an attacker pick such
// a name to dodge the guard, so it must be false.
expect(
sharesCookieSiteWithPage("eviltermix.example", "termix.example"),
).toBe(false);
});
it("is false for blank input rather than guessing", () => {
expect(sharesCookieSiteWithPage("", "termix.example")).toBe(false);
expect(sharesCookieSiteWithPage("termix.example", "")).toBe(false);
});
});
describe("webEndpointRefusalReason", () => {
const tunnel = (bindHost?: string) =>
endpoint({ access: "tunnel", bindHost }) as Pick<
WebEndpoint,
"access" | "bindHost"
>;
const direct = () =>
endpoint({ access: "direct" }) as Pick<WebEndpoint, "access" | "bindHost">;
it("refuses a direct endpoint on the same host that serves Termix", () => {
// https://termix.example:8443 receives Termix's jwt: same host, and the
// port is not part of the cookie key.
expect(
webEndpointRefusalReason(
direct(),
false,
"termix.example",
"termix.example",
),
).toBe("direct-shares-session-cookie");
});
it("refuses a direct endpoint on a parent or sub domain of the page host", () => {
expect(
webEndpointRefusalReason(
direct(),
false,
"termix.example.com",
"app.termix.example.com",
),
).toBe("direct-shares-session-cookie");
expect(
webEndpointRefusalReason(
direct(),
false,
"app.termix.example.com",
"termix.example.com",
),
).toBe("direct-shares-session-cookie");
});
it("allows a direct endpoint on a genuinely different host", () => {
expect(
webEndpointRefusalReason(
direct(),
false,
"192.168.1.10",
"termix.example",
),
).toBeNull();
expect(
webEndpointRefusalReason(direct(), false, "nas.local", "termix.example"),
).toBeNull();
});
it("allows a direct same-host endpoint on the desktop, whose jar has no jwt", () => {
expect(
webEndpointRefusalReason(
direct(),
true,
"termix.example",
"termix.example",
),
).toBeNull();
});
it("passes anything on the desktop", () => {
expect(
webEndpointRefusalReason(tunnel(), true, undefined, "localhost"),
).toBeNull();
expect(
webEndpointRefusalReason(tunnel("0.0.0.0"), true, undefined, "localhost"),
).toBeNull();
});
it("refuses a loopback bind a remote backend would strand", () => {
expect(
webEndpointRefusalReason(tunnel(), false, undefined, "localhost"),
).toBe("loopback-bind-on-remote-backend");
expect(
webEndpointRefusalReason(
tunnel("127.0.0.1"),
false,
undefined,
"localhost",
),
).toBe("loopback-bind-on-remote-backend");
});
it("allows an exposed bind when the page host has a loopback alias", () => {
expect(
webEndpointRefusalReason(
tunnel("0.0.0.0"),
false,
undefined,
"localhost",
),
).toBeNull();
expect(
webEndpointRefusalReason(
tunnel("0.0.0.0"),
false,
undefined,
"127.0.0.1",
),
).toBeNull();
});
it("refuses when the tunnel URL would share Termix's cookie jar", () => {
expect(
webEndpointRefusalReason(
tunnel("0.0.0.0"),
false,
undefined,
"termix.example.com",
),
).toBe("shares-session-cookie-with-termix");
expect(
webEndpointRefusalReason(
tunnel("0.0.0.0"),
false,
undefined,
"192.168.1.50",
),
).toBe("shares-session-cookie-with-termix");
});
it("reports the reachability problem first when both apply", () => {
// The bind address is what the user has to change either way, and it is
// the more specific instruction.
expect(
webEndpointRefusalReason(
tunnel(),
false,
undefined,
"termix.example.com",
),
).toBe("loopback-bind-on-remote-backend");
});
});
@@ -1,137 +0,0 @@
import { describe, expect, it } from "vitest";
import {
findInvalidWebEndpoint,
isWebEndpointPathValid,
isWebEndpointPortValid,
webEndpointErrorKey,
webEndpointRowError,
} from "@/lib/web-endpoint-validation";
import { normalizeWebEndpoints } from "../../../backend/database/routes/host-web-endpoints.js";
import type { WebEndpoint } from "@/types/index";
function endpoint(overrides: Partial<WebEndpoint> = {}): WebEndpoint {
return {
id: "e1",
label: "Proxmox",
scheme: "https",
port: 8006,
path: "/",
access: "direct",
render: "external",
...overrides,
};
}
describe("isWebEndpointPortValid", () => {
it("accepts the whole legal range and nothing else", () => {
expect(isWebEndpointPortValid(1)).toBe(true);
expect(isWebEndpointPortValid(65535)).toBe(true);
for (const bad of [0, -1, 65536, 8.5, "8006", null, undefined, NaN]) {
expect(isWebEndpointPortValid(bad)).toBe(false);
}
});
});
describe("webEndpointRowError", () => {
it("returns null for a row the normalizer would keep", () => {
expect(webEndpointRowError(endpoint())).toBeNull();
});
it("reports a blank label before anything else", () => {
// Both label and port are wrong; the label is the likelier oversight.
expect(webEndpointRowError(endpoint({ label: " ", port: 0 }))).toBe(
"label",
);
});
it("reports a bad port and a bad path", () => {
expect(webEndpointRowError(endpoint({ port: 0 }))).toBe("port");
expect(webEndpointRowError(endpoint({ path: "//evil.example" }))).toBe(
"path",
);
});
});
describe("findInvalidWebEndpoint", () => {
it("returns null when every row would survive", () => {
expect(
findInvalidWebEndpoint([
endpoint(),
endpoint({ id: "e2", label: "NAS" }),
]),
).toBeNull();
});
it("names the offending row by index", () => {
expect(
findInvalidWebEndpoint([endpoint(), endpoint({ id: "e2", label: "" })]),
).toEqual({ index: 1, error: "label" });
});
it("reports duplicate labels, which the picker cannot tell apart", () => {
expect(
findInvalidWebEndpoint([
endpoint(),
endpoint({ id: "e2", label: "proxmox" }),
]),
).toEqual({ index: 1, error: "duplicateLabel" });
});
it("tolerates a missing list", () => {
expect(findInvalidWebEndpoint(undefined)).toBeNull();
expect(findInvalidWebEndpoint(null)).toBeNull();
});
});
describe("webEndpointErrorKey", () => {
it("maps every error to a distinct i18n key", () => {
const keys = (["label", "duplicateLabel", "port", "path"] as const).map(
webEndpointErrorKey,
);
expect(new Set(keys).size).toBe(keys.length);
for (const key of keys) expect(key).toMatch(/^hosts\./);
});
});
/**
* The editor validator and the backend normalizer are two implementations of
* overlapping rules, in two layers that cannot share code (the renderer does
* not import backend route modules). Nothing but this describe block stops
* them drifting -- and drift here is invisible in the worst way: the editor
* accepts a row, the normalizer silently drops it, and the user's endpoint
* disappears on reload with no error anywhere.
*/
describe("the editor agrees with the normalizer", () => {
const PATHS = [
"/",
"",
"/admin",
"admin",
"/admin?tab=1",
"/a b",
"//evil.example",
"http://evil.example/x",
"/x:y",
"\t//evil.example",
"\n//evil.example",
"/a\tb",
`/a${String.fromCharCode(0x7f)}b`,
"/back\\slash",
];
it.each(PATHS)("agrees on path %j", (path) => {
const editorAccepts = isWebEndpointPathValid(path);
const normalizerKeeps =
normalizeWebEndpoints([{ ...endpoint(), path }]).length === 1;
expect(editorAccepts).toBe(normalizerKeeps);
});
const PORTS = [1, 80, 8006, 65535, 0, -1, 65536, 8.5];
it.each(PORTS)("agrees on port %j", (port) => {
const editorAccepts = isWebEndpointPortValid(port);
const normalizerKeeps =
normalizeWebEndpoints([{ ...endpoint(), port }]).length === 1;
expect(editorAccepts).toBe(normalizerKeeps);
});
});