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

@@ -7,10 +7,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
/**
* `migrateSchema()` carried a `SELECT id FROM <table> LIMIT 1` probe for a
* number of tables that the primary bootstrap already creates. The probe never
* threw, so the `CREATE TABLE IF NOT EXISTS` in its catch never ran — and two
* threw, so the `CREATE TABLE IF NOT EXISTS` in its catch never ran — and one
* of those unreachable copies had drifted away from the real definition
* (`sessions` had lost `ON DELETE CASCADE`; `session_recordings` still had the
* pre-#1128 `user_id NOT NULL` with `ON DELETE CASCADE` and no `username`).
* (`sessions` had lost `ON DELETE CASCADE`).
*
* They are gone now. What has to stay true is that the bootstrap alone
* produces every one of those tables, from an empty database and from a
@@ -21,17 +20,13 @@ describe("bootstrap creates the tables the removed probes covered", () => {
// Exactly the tables whose unreachable re-creation was deleted.
const TABLES = [
"c2s_tunnel_presets",
"sessions",
"trusted_devices",
"host_access",
"roles",
"user_roles",
"audit_logs",
"session_recordings",
"api_keys",
"session_shares",
"session_share_participants",
];
beforeEach(() => {
@@ -102,16 +97,6 @@ describe("bootstrap creates the tables the removed probes covered", () => {
await db.initializeDatabase();
const sqlite = db.getSqlite();
// session_recordings: nullable user_id with the attribution kept, per
// "audit trails survive the account" — not the NOT NULL + CASCADE the
// dead copy still carried.
const columns = sqlite
.prepare("PRAGMA table_info(session_recordings)")
.all() as Array<{ name: string; notnull: number }>;
const userId = columns.find((c) => c.name === "user_id");
expect(userId?.notnull).toBe(0);
expect(columns.some((c) => c.name === "username")).toBe(true);
// sessions: the dead copy had dropped ON DELETE CASCADE.
const sql = sqlite
.prepare(
@@ -69,8 +69,9 @@ describe("generated schemas", () => {
expect(tablesOf(pgSchema)).toEqual(tablesOf(sqliteSchema));
expect(tablesOf(mysqlSchema)).toEqual(tablesOf(sqliteSchema));
// Guard against a generator that silently emits nothing.
expect(tablesOf(sqliteSchema).length).toBeGreaterThan(40);
// Guard against a generator that silently emits nothing. Core keeps
// shrinking as feature tables move into plugins, so this stays loose.
expect(tablesOf(sqliteSchema).length).toBeGreaterThan(25);
});
it("maps each column to the right storage type per dialect", () => {
@@ -1,110 +0,0 @@
import fs from "fs";
import os from "os";
import path from "path";
import Database from "better-sqlite3";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
/**
* The Proxmox Stats feature adds `enable_proxmox_stats` and
* `proxmox_stats_config` to `ssh_data`, backfilled via `addColumnIfNotExists`
* next to the existing `enable_proxmox`/`proxmox_config` columns. Verify the
* migration adds both columns, with the right default, on a database that
* predates them.
*/
describe("proxmox stats columns migration", () => {
let dataDir: string;
beforeEach(() => {
dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "termix-proxmox-stats-"));
vi.resetModules();
process.env.DATA_DIR = dataDir;
process.env.DB_FILE_ENCRYPTION = "false";
process.env.ALLOW_EMPTY_DATA_DIR = "true";
});
afterEach(() => {
delete process.env.DATA_DIR;
delete process.env.DB_FILE_ENCRYPTION;
delete process.env.ALLOW_EMPTY_DATA_DIR;
fs.rmSync(dataDir, { recursive: true, force: true });
});
function writePreUpgradeDatabase(): void {
const seed = new Database(":memory:");
seed.exec(`
CREATE TABLE users (
id TEXT PRIMARY KEY,
username TEXT NOT NULL,
password_hash TEXT NOT NULL
);
CREATE TABLE ssh_data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
name TEXT,
ip TEXT NOT NULL,
port INTEGER NOT NULL,
username TEXT NOT NULL,
auth_type TEXT NOT NULL DEFAULT 'password',
enable_proxmox INTEGER NOT NULL DEFAULT 0,
proxmox_config TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO users (id, username, password_hash)
VALUES ('owner', 'alice', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type, enable_proxmox)
VALUES (1, 'owner', 'pve node', '10.0.0.9', 22, 'root', 'password', 1);
`);
fs.writeFileSync(path.join(dataDir, "db.sqlite"), seed.serialize());
seed.close();
}
it("adds enable_proxmox_stats (default 0) and proxmox_stats_config (nullable) columns", async () => {
writePreUpgradeDatabase();
const db = await import("../../../database/db/index.js");
await db.initializeDatabase();
const sqlite = db.getSqlite();
const columns = sqlite
.prepare("PRAGMA table_info(ssh_data)")
.all() as Array<{ name: string; notnull: number; dflt_value: string | null }>;
const enableCol = columns.find((c) => c.name === "enable_proxmox_stats");
expect(enableCol).toBeDefined();
expect(enableCol?.notnull).toBe(1);
const configCol = columns.find((c) => c.name === "proxmox_stats_config");
expect(configCol).toBeDefined();
expect(configCol?.notnull).toBe(0);
const row = sqlite
.prepare(
"SELECT enable_proxmox_stats, proxmox_stats_config FROM ssh_data WHERE id = 1",
)
.get() as { enable_proxmox_stats: number; proxmox_stats_config: string | null };
// Pre-existing rows default to disabled, independent of enable_proxmox.
expect(row.enable_proxmox_stats).toBe(0);
expect(row.proxmox_stats_config).toBeNull();
});
it("creates the proxmox_node_history and proxmox_stats_preferences tables", async () => {
writePreUpgradeDatabase();
const db = await import("../../../database/db/index.js");
await db.initializeDatabase();
const sqlite = db.getSqlite();
const tables = sqlite
.prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
.pluck()
.all() as string[];
expect(tables).toContain("proxmox_node_history");
expect(tables).toContain("proxmox_stats_preferences");
});
});
@@ -0,0 +1,67 @@
import fs from "fs";
import os from "os";
import path from "path";
import Database from "better-sqlite3";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
describe("RDP domain across database boots", () => {
let dataDir: string;
beforeEach(() => {
dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "termix-rdp-domain-"));
vi.resetModules();
vi.stubEnv("DATA_DIR", dataDir);
vi.stubEnv("DB_FILE_ENCRYPTION", "false");
vi.stubEnv("ALLOW_EMPTY_DATA_DIR", "true");
});
afterEach(() => {
vi.unstubAllEnvs();
fs.rmSync(dataDir, { recursive: true, force: true });
});
it.each([
{ saved: "CORP", legacy: null, expected: "CORP" },
{ saved: "CORP", legacy: "OLD", expected: "CORP" },
{ saved: "", legacy: "OLD", expected: "" },
{ saved: null, legacy: "LEGACY", expected: null },
])("preserves $saved with legacy domain $legacy across boots", async ({
saved,
legacy,
expected,
}) => {
const seed = new Database(":memory:");
seed.exec(
fs.readFileSync(
new URL("../../fixtures/sqlite-2.8-schema.sql", import.meta.url),
"utf8",
),
);
seed.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('owner', 'alice', 'hash');
`);
seed.prepare(`
INSERT INTO ssh_data
(id, user_id, ip, port, username, auth_type, connection_type,
rdp_auth_type, rdp_user, rdp_password, rdp_domain, domain)
VALUES (1, 'owner', '192.0.2.1', 3389, '', 'password', 'rdp',
'credential', NULL, NULL, ?, ?)
`).run(saved, legacy);
fs.writeFileSync(path.join(dataDir, "db.sqlite"), seed.serialize());
seed.close();
for (let boot = 0; boot < 2; boot++) {
vi.resetModules();
const db = await import("../../../database/db/index.js");
await db.initializeDatabase();
expect(
db.getSqlite()
.prepare("SELECT rdp_domain FROM ssh_data WHERE id = 1")
.pluck()
.get(),
).toBe(expected);
await db.saveMemoryDatabaseToFile();
}
});
});
@@ -48,14 +48,17 @@ describe("the encrypted-export ssh_data DDL agrees with its INSERT", () => {
expect(missing).toEqual([]);
});
it("carries the web endpoint columns in both halves", () => {
// Named explicitly rather than derived: the generic check above passes if
// BOTH halves omit a column, which is precisely how this feature's columns
// would go missing.
for (const column of ["enable_web_ui", "web_ui_config"]) {
expect(createBody).toContain(column);
expect(insertMatch?.[1]).toContain(column);
it("leaves plugin host settings to their own table", () => {
// Moved columns must not creep back: plugins own these values now.
for (const column of [
"enable_web_ui",
"web_ui_config",
"enable_terminal",
]) {
expect(createBody).not.toContain(column);
expect(insertMatch?.[1]).not.toContain(column);
}
expect(text).toContain("CREATE TABLE plugin_settings (");
});
it("binds exactly one placeholder per column", () => {
@@ -76,8 +79,8 @@ describe("the encrypted-export ssh_data DDL agrees with its INSERT", () => {
expect((values ?? "").split("?").length - 1).toBe(columns.length);
});
it("carries the web endpoint values in the bound parameter list", () => {
expect(text).toContain("decrypted.enableWebUi");
expect(text).toContain("decrypted.webUiConfig");
it("copies non-secret host plugin settings into the export", () => {
expect(text).toContain("INSERT INTO plugin_settings");
expect(text).toContain("if (row.encrypted) continue;");
});
});
@@ -1,98 +0,0 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
/**
* This codebase enumerates host columns by hand in a lot of places, and
* "added a column, missed one update path" is its most repeated bug -- during
* the first attempt at this feature a field was missed at one of these points
* six separate times, each surfacing as a different mystery (endpoints that
* saved but never appeared, config that vanished on reload).
*
* Every one of these files already enumerates the Docker pair, which is the
* exact shape the web endpoint pair copies. So "mentions enableDocker but not
* enableWebUi" is a reliable proxy for "was not updated", and it fails loudly
* the moment someone adds the tenth enumeration point without this one.
*
* This is a coarse guard on purpose: it cannot tell whether the field is used
* CORRECTLY, only that the file knows it exists. Behavioural coverage lives in
* the route tests.
*/
function source(relative: string): string {
return readFileSync(path.resolve(relative), "utf8");
}
const ENUMERATION_POINTS = [
"src/backend/database/database.ts",
"src/backend/database/db/index.ts",
"src/backend/database/routes/host-normalizers.ts",
"src/backend/database/routes/host.ts",
"src/backend/database/routes/host-bulk-routes.ts",
"src/ui/sidebar/host-export-payload.ts",
"src/ui/sidebar/HostManagerData.ts",
"src/ui/sidebar/HostEditorData.ts",
"src/ui/shell/tabUtils.tsx",
];
describe("web endpoint column enumeration", () => {
it.each(ENUMERATION_POINTS)(
"%s enumerates the enable flag alongside enableDocker",
(file) => {
const text = source(file);
// Guards the guard: if the Docker anchor ever disappears from a file,
// this test would otherwise pass vacuously forever.
expect(text).toMatch(/enableDocker|enable_docker/);
expect(text).toMatch(/enableWebUi|enable_web_ui/);
},
);
it.each(ENUMERATION_POINTS)(
"%s enumerates the config column alongside dockerConfig",
(file) => {
const text = source(file);
expect(text).toMatch(/dockerConfig|docker_config/);
expect(text).toMatch(/webUiConfig|web_ui_config/);
},
);
it("parses webUiConfig through the guarded parser, not a bare JSON.parse", () => {
// dockerConfig uses a bare JSON.parse, so one malformed value takes out
// the whole host listing. Do not copy that.
const text = source("src/backend/database/routes/host-normalizers.ts");
expect(text).toContain("parseWebUiConfig");
expect(text).not.toMatch(/JSON\.parse\(\s*host\.webUiConfig/);
});
it("clears webUiConfig on disable in both host.ts write paths", () => {
// Three write paths disagreed on this during the first attempt. The export
// payload ships webUiConfig unconditionally, so a host disabled without
// clearing still exports its endpoint list -- internal hostnames, ports and
// paths -- while the UI reads as off everywhere, and re-enabling silently
// resurrects stale endpoints.
const text = source("src/backend/database/routes/host.ts");
// Create and update. Anchored on the exact conditional, not a loose
// pattern: a looser regex here passed even with the guard deleted.
const occurrences = text.split("webUiConfig: enableWebUi").length - 1;
expect(occurrences).toBe(2);
});
it("clears webUiConfig on a bulk disable", () => {
const text = source("src/backend/database/routes/host-bulk-routes.ts");
expect(text).toContain(
"if (!updates.enableWebUi) simpleUpdates.webUiConfig = null;",
);
});
it("shares webUiConfig with connect-level recipients", () => {
// A connect-level recipient is ALREADY authorized to open these tunnels
// (the open route gates on canAccessHost(..., "connect")), so withholding
// the config only breaks discovery while the flag advertises the feature.
// The dockerConfig precedent does not transfer: Docker's tab works without
// its config, whereas a web endpoint IS its config.
const text = source("src/backend/database/routes/host-normalizers.ts");
const block = text.slice(text.indexOf("CONNECT_LEVEL_FIELDS"));
const list = block.slice(0, block.indexOf("]"));
expect(list).toContain("enableWebUi");
expect(list).toContain("webUiConfig");
});
});
@@ -1,275 +0,0 @@
import { describe, expect, it } from "vitest";
import {
MAX_WEB_ENDPOINTS,
normalizeWebEndpoints,
parseWebUiConfig,
serializeWebUiConfig,
} from "../../database/routes/host-web-endpoints.js";
function valid(overrides: Record<string, unknown> = {}) {
return {
id: "e1",
label: "Proxmox",
scheme: "https",
port: 8006,
path: "/",
access: "direct",
render: "external",
...overrides,
};
}
describe("normalizeWebEndpoints", () => {
it("keeps a valid endpoint", () => {
expect(normalizeWebEndpoints([valid()])).toEqual([
{
id: "e1",
label: "Proxmox",
scheme: "https",
port: 8006,
path: "/",
access: "direct",
render: "external",
ignoreCert: false,
},
]);
});
it("drops an unknown or dangerous scheme", () => {
expect(normalizeWebEndpoints([valid({ scheme: "ftp" })])).toEqual([]);
expect(normalizeWebEndpoints([valid({ scheme: "javascript" })])).toEqual(
[],
);
});
it("drops out-of-range ports", () => {
expect(normalizeWebEndpoints([valid({ port: 0 })])).toEqual([]);
expect(normalizeWebEndpoints([valid({ port: 65536 })])).toEqual([]);
expect(normalizeWebEndpoints([valid({ port: 8.5 })])).toEqual([]);
// A numeric string is not a number; accepting it would let "8006abc"
// through some other coercion path later.
expect(normalizeWebEndpoints([valid({ port: "8006" })])).toEqual([]);
});
it("coerces a path that does not start with a slash", () => {
expect(normalizeWebEndpoints([valid({ path: "admin" })])[0].path).toBe(
"/admin",
);
});
it("defaults a missing path to /", () => {
expect(normalizeWebEndpoints([valid({ path: undefined })])[0].path).toBe(
"/",
);
});
it("drops a path carrying a scheme or authority", () => {
expect(normalizeWebEndpoints([valid({ path: "//evil.example" })])).toEqual(
[],
);
expect(
normalizeWebEndpoints([valid({ path: "http://evil.example/x" })]),
).toEqual([]);
expect(normalizeWebEndpoints([valid({ path: "/x" })])).toHaveLength(1);
});
it("drops a path whose protocol-relative prefix hides behind a control character", () => {
// "\t//evil.example" slips a naive startsWith("//") guard: the browser
// strips the control character and follows the authority.
for (const prefix of ["\t", "\n", "\r"]) {
expect(
normalizeWebEndpoints([valid({ path: `${prefix}//evil.example` })]),
).toEqual([]);
}
});
it("drops a path containing a control character anywhere", () => {
expect(normalizeWebEndpoints([valid({ path: "/a\tb" })])).toEqual([]);
expect(
normalizeWebEndpoints([
valid({ path: `/a${String.fromCharCode(0x7f)}b` }),
]),
).toEqual([]);
});
it("keeps a path containing a plain space", () => {
expect(normalizeWebEndpoints([valid({ path: "/a b" })])[0].path).toBe(
"/a b",
);
});
it("truncates an over-long label", () => {
expect(
normalizeWebEndpoints([valid({ label: "x".repeat(200) })])[0].label,
).toHaveLength(64);
});
it("drops an endpoint with a blank label or id", () => {
expect(normalizeWebEndpoints([valid({ label: " " })])).toEqual([]);
expect(normalizeWebEndpoints([valid({ id: "" })])).toEqual([]);
});
it("keeps only the first of a duplicate id", () => {
const result = normalizeWebEndpoints([
valid({ id: "dup", label: "first" }),
valid({ id: "dup", label: "second" }),
]);
expect(result).toHaveLength(1);
expect(result[0].label).toBe("first");
});
it("caps the list length", () => {
const many = Array.from({ length: MAX_WEB_ENDPOINTS + 5 }, (_, i) =>
valid({ id: `e${i}` }),
);
expect(normalizeWebEndpoints(many)).toHaveLength(MAX_WEB_ENDPOINTS);
});
it("returns empty for non-array input", () => {
expect(normalizeWebEndpoints(undefined)).toEqual([]);
expect(normalizeWebEndpoints(null)).toEqual([]);
expect(normalizeWebEndpoints("nope")).toEqual([]);
expect(normalizeWebEndpoints({ endpoints: [] })).toEqual([]);
});
it("drops an unknown access or render value", () => {
expect(normalizeWebEndpoints([valid({ access: "magic" })])).toEqual([]);
expect(normalizeWebEndpoints([valid({ render: "magic" })])).toEqual([]);
});
it("clears ignoreCert for tunnel access and keeps it for direct", () => {
expect(
normalizeWebEndpoints([valid({ access: "tunnel", ignoreCert: true })])[0]
.ignoreCert,
).toBe(false);
expect(
normalizeWebEndpoints([valid({ access: "direct", ignoreCert: true })])[0]
.ignoreCert,
).toBe(true);
});
});
describe("bindHost", () => {
const tunnelRow = (bindHost?: unknown) => ({
...valid({ access: "tunnel" }),
...(bindHost === undefined ? {} : { bindHost }),
});
it("keeps a loopback bind", () => {
expect(normalizeWebEndpoints([tunnelRow("127.0.0.1")])[0].bindHost).toBe(
"127.0.0.1",
);
});
it("keeps an all-interfaces bind, which is the exposed opt-in", () => {
expect(normalizeWebEndpoints([tunnelRow("0.0.0.0")])[0].bindHost).toBe(
"0.0.0.0",
);
});
it("omits it entirely when blank, so the route falls back to loopback", () => {
expect(normalizeWebEndpoints([tunnelRow("")])[0].bindHost).toBeUndefined();
expect(normalizeWebEndpoints([tunnelRow()])[0].bindHost).toBeUndefined();
});
it("drops the endpoint when the bind address is not a bare host", () => {
// It lands in a listener AND in a URL authority, so nothing carrying a
// scheme, port, path or credentials may survive.
for (const bad of [
"http://evil.example",
"127.0.0.1:8080",
"host/path",
"user@host",
"has space",
"999.1.1.1",
"-bad.example",
42,
]) {
expect(normalizeWebEndpoints([tunnelRow(bad)])).toEqual([]);
}
});
it("accepts a bracketed IPv6 literal and a hostname", () => {
expect(normalizeWebEndpoints([tunnelRow("[::1]")])[0].bindHost).toBe(
"[::1]",
);
expect(normalizeWebEndpoints([tunnelRow("nas.local")])[0].bindHost).toBe(
"nas.local",
);
});
it("ignores it on a direct endpoint, which never binds anything", () => {
expect(
normalizeWebEndpoints([
valid({ access: "direct", bindHost: "0.0.0.0" }),
])[0].bindHost,
).toBeUndefined();
});
});
describe("localPort", () => {
const tunnelRow = (localPort?: unknown) => ({
...valid({ access: "tunnel" }),
...(localPort === undefined ? {} : { localPort }),
});
it("keeps a fixed port so a container can publish it", () => {
expect(normalizeWebEndpoints([tunnelRow(38080)])[0].localPort).toBe(38080);
});
it("omits it when unset, leaving the kernel to pick", () => {
expect(normalizeWebEndpoints([tunnelRow()])[0].localPort).toBeUndefined();
});
it("drops the endpoint for a port outside the valid range", () => {
for (const bad of [0, -1, 65536, 8.5, "38080"]) {
expect(normalizeWebEndpoints([tunnelRow(bad)])).toEqual([]);
}
});
it("ignores it on a direct endpoint, which binds nothing", () => {
expect(
normalizeWebEndpoints([valid({ access: "direct", localPort: 38080 })])[0]
.localPort,
).toBeUndefined();
});
});
describe("parseWebUiConfig", () => {
it("parses a stored JSON string", () => {
expect(
parseWebUiConfig(JSON.stringify({ endpoints: [valid()] })).endpoints,
).toHaveLength(1);
});
it("accepts an already-parsed object", () => {
expect(parseWebUiConfig({ endpoints: [valid()] }).endpoints).toHaveLength(
1,
);
});
it("returns empty endpoints for malformed JSON instead of throwing", () => {
// A half-written config must not take out the whole host listing, which
// is what dockerConfig's bare JSON.parse does today.
expect(parseWebUiConfig("{ not json")).toEqual({ endpoints: [] });
});
it("returns empty endpoints for null and undefined", () => {
expect(parseWebUiConfig(null)).toEqual({ endpoints: [] });
expect(parseWebUiConfig(undefined)).toEqual({ endpoints: [] });
});
});
describe("serializeWebUiConfig", () => {
it("round-trips through normalization", () => {
expect(
parseWebUiConfig(serializeWebUiConfig({ endpoints: [valid()] }))
.endpoints[0].id,
).toBe("e1");
});
it("returns null when there are no valid endpoints", () => {
expect(serializeWebUiConfig({ endpoints: [] })).toBeNull();
expect(serializeWebUiConfig(null)).toBeNull();
});
});
@@ -0,0 +1,157 @@
/**
* plugin_settings cleanup when a user or host goes.
*
* scope_id is polymorphic, so it carries no foreign key and the engine will
* not cascade it. The repositories delete these rows explicitly, and these
* tests exist so a later refactor that drops those calls fails here rather
* than leaving orphaned settings behind forever.
*/
import { asc } from "drizzle-orm";
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./repositories/test-support.js";
import { HostRepository } from "../../database/repositories/host-repository.js";
import { UserRepository } from "../../database/repositories/user-repository.js";
import type { DatabaseContext } from "../../database/repositories/database-context.js";
import { pluginSettings } from "../../database/db/schema.js";
let adapter: TestSqliteDatabase | null = null;
let ctx: DatabaseContext | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
ctx = null;
}
});
async function seed(): Promise<DatabaseContext> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
ctx = context;
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES
(7, 'user-1', 'seven', '10.0.0.7', 22, 'root', 'password'),
(8, 'user-1', 'eight', '10.0.0.8', 22, 'root', 'password'),
(9, 'user-2', 'nine', '10.0.0.9', 22, 'root', 'password');
INSERT INTO plugins (id, name, version, manifest_json)
VALUES ('sample', 'Sample', '1.0.0', '{}');
`);
return context;
}
async function addSetting(
scope: string,
scopeId: string | null,
key = "k",
): Promise<void> {
await adapter!.exec(
`INSERT INTO plugin_settings (plugin_id, scope, scope_id, key, value)
VALUES ('sample', '${scope}', ${scopeId === null ? "NULL" : `'${scopeId}'`}, '${key}', '"v"')`,
);
}
async function remaining(): Promise<
{ scope: string; scopeId: string | null }[]
> {
const rows = await ctx!.drizzle
.select({
scope: pluginSettings.scope,
scopeId: pluginSettings.scopeId,
})
.from(pluginSettings)
.orderBy(asc(pluginSettings.scope), asc(pluginSettings.scopeId));
return rows;
}
describe("user deletion", () => {
it("removes that user's plugin settings", async () => {
const context = await seed();
await addSetting("user", "user-1");
await new UserRepository(context).delete("user-1");
expect(await remaining()).toEqual([]);
});
it("leaves another user's settings alone", async () => {
const context = await seed();
await addSetting("user", "user-1");
await addSetting("user", "user-2");
await new UserRepository(context).delete("user-1");
expect(await remaining()).toEqual([{ scope: "user", scopeId: "user-2" }]);
});
it("removes the user's ctx.secrets rows too", async () => {
const context = await seed();
await addSetting("secret", "user-1");
await addSetting("secret", "user-2");
await new UserRepository(context).delete("user-1");
expect(await remaining()).toEqual([{ scope: "secret", scopeId: "user-2" }]);
});
it("leaves admin-scope settings alone", async () => {
const context = await seed();
await addSetting("admin", null);
await addSetting("user", "user-1");
await new UserRepository(context).delete("user-1");
expect(await remaining()).toEqual([{ scope: "admin", scopeId: null }]);
});
});
describe("host deletion", () => {
it("removes that host's plugin settings", async () => {
const context = await seed();
await addSetting("host", "7");
await new HostRepository(context).deleteForUser("user-1", 7);
expect(await remaining()).toEqual([]);
});
it("leaves another host's settings alone", async () => {
const context = await seed();
await addSetting("host", "7");
await addSetting("host", "8");
await new HostRepository(context).deleteForUser("user-1", 7);
expect(await remaining()).toEqual([{ scope: "host", scopeId: "8" }]);
});
it("clears settings for every host in the bulk delete path", async () => {
const context = await seed();
await addSetting("host", "7");
await addSetting("host", "8");
await addSetting("host", "9");
await new HostRepository(context).deleteByUserId("user-1");
// Host 9 belongs to another user and keeps its settings.
expect(await remaining()).toEqual([{ scope: "host", scopeId: "9" }]);
});
it("does not confuse a host id with a user id", async () => {
const context = await seed();
await addSetting("host", "7");
await addSetting("user", "7");
await new HostRepository(context).deleteForUser("user-1", 7);
expect(await remaining()).toEqual([{ scope: "user", scopeId: "7" }]);
});
});
@@ -1,471 +0,0 @@
import crypto from "node:crypto";
import { sql } from "drizzle-orm";
import { afterEach, describe, expect, it, vi } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { AlertRepository } from "../../../database/repositories/alert-repository.js";
import { DataCrypto } from "../../../utils/data-crypto.js";
describe("AlertRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<AlertRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'user-1', 'alpha', '127.0.0.1', 22, 'root', 'password');
`);
return new AlertRepository(context, onWrite);
}
it("manages notification channels", async () => {
let writes = 0;
const repo = await createRepository(() => {
writes += 1;
});
const created = await repo.createNotificationChannel({
userId: "user-1",
name: "Ops",
type: "webhook",
config: '{"url":"https://example.test"}',
enabled: true,
});
expect(created).toMatchObject({
user_id: "user-1",
name: "Ops",
type: "webhook",
enabled: 1,
});
const updated = await repo.updateNotificationChannel(created.id, "user-1", {
name: "Ops disabled",
enabled: false,
});
expect(updated).toMatchObject({ name: "Ops disabled", enabled: 0 });
expect(await repo.listNotificationChannels("user-1")).toHaveLength(1);
expect(await repo.deleteNotificationChannel(created.id, "user-2")).toBe(
false,
);
expect(await repo.deleteNotificationChannel(created.id, "user-1")).toBe(
true,
);
expect(await repo.listNotificationChannels("user-1")).toHaveLength(0);
expect(writes).toBe(3);
});
it("manages alert rules and linked channels", async () => {
const repo = await createRepository();
const ownedChannel = await repo.createNotificationChannel({
userId: "user-1",
name: "Owned",
type: "ntfy",
config: '{"url":"https://ntfy.test","topic":"termix"}',
enabled: true,
});
const foreignChannel = await repo.createNotificationChannel({
userId: "user-2",
name: "Foreign",
type: "webhook",
config: '{"url":"https://example.test"}',
enabled: true,
});
const created = await repo.createAlertRule({
userId: "user-1",
hostId: null,
name: "CPU high",
enabled: true,
triggerType: "cpu_threshold",
thresholdValue: 80,
thresholdDurationSeconds: 30,
cooldownMinutes: 5,
channels: [ownedChannel.id, foreignChannel.id],
now: "2026-01-01T00:00:00.000Z",
});
expect(created).toMatchObject({
user_id: "user-1",
host_id: null,
name: "CPU high",
trigger_type: "cpu_threshold",
threshold_value: 80,
channels: [ownedChannel.id],
});
const updated = await repo.updateAlertRule(created.id, "user-1", {
name: "CPU very high",
hostId: 1,
channels: [],
now: "2026-01-02T00:00:00.000Z",
});
expect(updated).toMatchObject({
name: "CPU very high",
host_id: 1,
channels: [],
updated_at: "2026-01-02T00:00:00.000Z",
});
const rules = await repo.listAlertRules("user-1");
expect(rules).toHaveLength(1);
expect(rules[0].channels).toEqual([]);
expect(await repo.deleteAlertRule(created.id, "user-2")).toBe(false);
expect(await repo.deleteAlertRule(created.id, "user-1")).toBe(true);
});
it("lists, acknowledges, and prunes firings", async () => {
const repo = await createRepository();
const rule = await repo.createAlertRule({
userId: "user-1",
hostId: 1,
name: "Host offline",
enabled: true,
triggerType: "host_offline",
thresholdValue: null,
thresholdDurationSeconds: null,
cooldownMinutes: 15,
channels: [],
now: "2026-01-01T00:00:00.000Z",
});
await repo.createFiring({
userId: "user-1",
ruleId: rule.id,
hostId: 1,
hostName: "alpha",
value: null,
message: "down",
severity: "critical",
});
const listed = await repo.listAlertFirings({
userId: "user-1",
limit: 10,
offset: 0,
});
expect(listed.total).toBe(1);
expect(listed.firings[0]).toMatchObject({
rule_id: rule.id,
host_name: "alpha",
acknowledged: 0,
rule_name: "Host offline",
});
await repo.acknowledgeFiring(listed.firings[0].id, "user-1");
const unacknowledged = await repo.listAlertFirings({
userId: "user-1",
acknowledged: false,
limit: 10,
offset: 0,
});
expect(unacknowledged.total).toBe(0);
await repo.acknowledgeAllFirings("user-1");
await repo.pruneFiringsOlderThan("user-1", 0);
});
it("loads enabled rules and notification channels for the alert engine", async () => {
const repo = await createRepository();
const channel = await repo.createNotificationChannel({
userId: "user-1",
name: "Ops",
type: "webhook",
config: '{"url":"https://example.test"}',
enabled: true,
});
const disabledChannel = await repo.createNotificationChannel({
userId: "user-1",
name: "Disabled",
type: "webhook",
config: '{"url":"https://disabled.test"}',
enabled: false,
});
const rule = await repo.createAlertRule({
userId: "user-1",
hostId: null,
name: "CPU high",
enabled: true,
triggerType: "cpu_threshold",
thresholdValue: 90,
thresholdDurationSeconds: 0,
cooldownMinutes: 15,
channels: [channel.id, disabledChannel.id],
now: "2026-01-01T00:00:00.000Z",
});
expect(await repo.listEnabledRulesForHost(1)).toMatchObject([
{
id: rule.id,
userId: "user-1",
triggerType: "cpu_threshold",
enabled: true,
},
]);
expect(await repo.findRuleById(rule.id)).toMatchObject({
id: rule.id,
cooldownMinutes: 15,
});
expect(await repo.listEnabledChannelsForRule(rule.id)).toEqual([
{
id: channel.id,
type: "webhook",
config: '{"url":"https://example.test"}',
enabled: true,
},
]);
});
it("keeps another user's wildcard rules off a host they do not own", async () => {
const repo = await createRepository();
await adapter!.exec(`
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (2, 'user-2', 'bravo', '127.0.0.2', 22, 'root', 'password');
`);
const ownerRule = await repo.createAlertRule({
userId: "user-1",
hostId: null,
name: "Owner wildcard",
enabled: true,
triggerType: "cpu_threshold",
thresholdValue: 90,
thresholdDurationSeconds: 0,
cooldownMinutes: 15,
channels: [],
now: "2026-01-01T00:00:00.000Z",
});
const otherRule = await repo.createAlertRule({
userId: "user-2",
hostId: null,
name: "Other wildcard",
enabled: true,
triggerType: "cpu_threshold",
thresholdValue: 90,
thresholdDurationSeconds: 0,
cooldownMinutes: 15,
channels: [],
now: "2026-01-01T00:00:00.000Z",
});
// Host 1 belongs to user-1, so only user-1's wildcard rule may fire.
const forHostOne = await repo.listEnabledRulesForHost(1);
expect(forHostOne.map((rule) => rule.id)).toEqual([ownerRule.id]);
const forHostTwo = await repo.listEnabledRulesForHost(2);
expect(forHostTwo.map((rule) => rule.id)).toEqual([otherRule.id]);
});
it("still matches a rule pinned to a specific host", async () => {
const repo = await createRepository();
const pinned = await repo.createAlertRule({
userId: "user-1",
hostId: 1,
name: "Pinned",
enabled: true,
triggerType: "disk_threshold",
thresholdValue: 90,
thresholdDurationSeconds: 0,
cooldownMinutes: 15,
channels: [],
now: "2026-01-01T00:00:00.000Z",
});
expect((await repo.listEnabledRulesForHost(1)).map((r) => r.id)).toEqual([
pinned.id,
]);
});
it("encrypts channel configs at rest and returns them decrypted", async () => {
const key = crypto.randomBytes(32);
const spy = vi
.spyOn(DataCrypto, "getUserDataKey")
.mockImplementation(() => key);
try {
const repo = await createRepository();
const secret = '{"url":"https://ntfy.test","token":"super-secret"}';
const created = await repo.createNotificationChannel({
userId: "user-1",
name: "Ntfy",
type: "ntfy",
config: secret,
enabled: true,
});
expect(created.config).toBe(secret);
// The stored bytes must not contain the token in the clear.
const stored = await adapter!.query<{ config: string }>(
sql`SELECT config FROM notification_channels WHERE id = ${created.id}`,
);
expect(stored[0].config).not.toContain("super-secret");
// Every read path hands back plaintext.
const listed = await repo.listNotificationChannels("user-1");
expect(listed[0].config).toBe(secret);
expect(
(await repo.findNotificationChannelForUser(created.id, "user-1"))
?.config,
).toBe(secret);
const rule = await repo.createAlertRule({
userId: "user-1",
hostId: null,
name: "CPU",
enabled: true,
triggerType: "cpu_threshold",
thresholdValue: 90,
thresholdDurationSeconds: 0,
cooldownMinutes: 15,
channels: [created.id],
now: "2026-01-01T00:00:00.000Z",
});
const engineChannels = await repo.listEnabledChannelsForRule(rule.id);
expect(engineChannels[0].config).toBe(secret);
const rotated = '{"url":"https://ntfy.test","token":"rotated"}';
const updated = await repo.updateNotificationChannel(
created.id,
"user-1",
{ config: rotated },
);
expect(updated?.config).toBe(rotated);
} finally {
spy.mockRestore();
}
});
it("still reads channel configs written before encryption", async () => {
const repo = await createRepository();
const plaintext = '{"url":"https://legacy.test"}';
const created = await repo.createNotificationChannel({
userId: "user-1",
name: "Legacy",
type: "webhook",
config: plaintext,
enabled: true,
});
const key = crypto.randomBytes(32);
const spy = vi
.spyOn(DataCrypto, "getUserDataKey")
.mockImplementation(() => key);
try {
const found = await repo.findNotificationChannelForUser(
created.id,
"user-1",
);
expect(found?.config).toBe(plaintext);
} finally {
spy.mockRestore();
}
});
it("loads host display names for alert payloads", async () => {
const repo = await createRepository();
expect(await repo.getHostDisplayName(1)).toBe("alpha");
expect(await repo.getHostDisplayName(999)).toBeNull();
});
it("deletes all alert data for a user", async () => {
let writes = 0;
const repo = await createRepository(() => {
writes += 1;
});
const userChannel = await repo.createNotificationChannel({
userId: "user-1",
name: "Ops",
type: "webhook",
config: '{"url":"https://example.test"}',
enabled: true,
});
const otherChannel = await repo.createNotificationChannel({
userId: "user-2",
name: "Other",
type: "webhook",
config: '{"url":"https://other.test"}',
enabled: true,
});
const userRule = await repo.createAlertRule({
userId: "user-1",
hostId: 1,
name: "CPU high",
enabled: true,
triggerType: "cpu_threshold",
thresholdValue: 80,
thresholdDurationSeconds: 30,
cooldownMinutes: 5,
channels: [userChannel.id],
now: "2026-01-01T00:00:00.000Z",
});
const otherRule = await repo.createAlertRule({
userId: "user-2",
hostId: null,
name: "Memory high",
enabled: true,
triggerType: "memory_threshold",
thresholdValue: 90,
thresholdDurationSeconds: 60,
cooldownMinutes: 10,
channels: [otherChannel.id],
now: "2026-01-01T00:00:00.000Z",
});
await repo.createFiring({
userId: "user-1",
ruleId: userRule.id,
hostId: 1,
hostName: "alpha",
value: 95,
message: "high",
severity: "warning",
});
await repo.createFiring({
userId: "user-2",
ruleId: otherRule.id,
hostId: 1,
hostName: "alpha",
value: 91,
message: "other",
severity: "warning",
});
await expect(repo.deleteByUserId("user-1")).resolves.toEqual({
firingsDeleted: 1,
ruleLinksDeleted: 1,
rulesDeleted: 1,
channelsDeleted: 1,
});
await expect(repo.deleteByUserId("missing")).resolves.toEqual({
firingsDeleted: 0,
ruleLinksDeleted: 0,
rulesDeleted: 0,
channelsDeleted: 0,
});
expect(await repo.listNotificationChannels("user-1")).toEqual([]);
expect(await repo.listAlertRules("user-1")).toEqual([]);
expect(
await repo.listAlertFirings({ userId: "user-1", limit: 10, offset: 0 }),
).toEqual({ firings: [], total: 0 });
expect(await repo.listNotificationChannels("user-2")).toHaveLength(1);
expect(await repo.listAlertRules("user-2")).toHaveLength(1);
expect(await repo.listEnabledChannelsForRule(otherRule.id)).toHaveLength(1);
expect(writes).toBe(7);
});
});
@@ -1,105 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { C2sTunnelPresetRepository } from "../../../database/repositories/c2s-tunnel-preset-repository.js";
describe("C2sTunnelPresetRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<C2sTunnelPresetRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
`);
return new C2sTunnelPresetRepository(context, onWrite);
}
it("creates and lists presets ordered by name", async () => {
const repo = await createRepository();
await repo.createForUser("user-1", {
name: "Zulu",
config: "[]",
platform: "linux",
computerName: "workstation",
});
await repo.createForUser("user-1", { name: "Alpha", config: "[]" });
await repo.createForUser("user-2", { name: "Other", config: "[]" });
const presets = await repo.listByUserId("user-1");
expect(presets.map((preset) => preset.name)).toEqual(["Alpha", "Zulu"]);
expect(presets[1]).toMatchObject({
platform: "linux",
computerName: "workstation",
});
});
it("finds, updates, and deletes user-owned presets", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const preset = await repo.createForUser("user-1", {
name: "Home",
config: "[]",
});
expect(writeCount).toBe(1);
expect(await repo.findByIdForUser("user-2", preset.id)).toBeNull();
expect(await repo.hasNameForUser("user-1", "Home")).toBe(true);
expect(await repo.hasNameForUser("user-1", "Home", preset.id)).toBe(false);
const updated = await repo.updateForUser("user-1", preset.id, {
name: "Renamed",
platform: "darwin",
});
expect(updated).toMatchObject({
id: preset.id,
name: "Renamed",
platform: "darwin",
});
expect(writeCount).toBe(2);
expect(
await repo.updateForUser("user-2", preset.id, { name: "Nope" }),
).toBeNull();
expect(writeCount).toBe(2);
expect(await repo.deleteForUser("user-2", preset.id)).toBe(false);
expect(await repo.deleteForUser("user-1", preset.id)).toBe(true);
expect(writeCount).toBe(3);
});
it("deletes all presets for a user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.createForUser("user-1", { name: "One", config: "[]" });
await repo.createForUser("user-1", { name: "Two", config: "[]" });
await repo.createForUser("user-2", { name: "Other", config: "[]" });
await expect(repo.deleteByUserId("user-1")).resolves.toBe(2);
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
expect(await repo.listByUserId("user-1")).toEqual([]);
expect(
(await repo.listByUserId("user-2")).map((preset) => preset.name),
).toEqual(["Other"]);
expect(writeCount).toBe(4);
});
});
@@ -1,76 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { CommandHistoryRepository } from "../../../database/repositories/command-history-repository.js";
describe("CommandHistoryRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<CommandHistoryRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'user-1', 'one', '10.0.0.1', 22, 'root', 'password'), (2, 'user-1', 'two', '10.0.0.1', 22, 'root', 'password'), (3, 'user-2', 'other', '10.0.0.1', 22, 'root', 'password');
`);
return new CommandHistoryRepository(context, onWrite);
}
it("creates and lists unique commands by latest execution", async () => {
const repo = await createRepository();
await repo.create("user-1", 1, "ls", "2026-06-27T00:00:00.000Z");
await repo.create("user-1", 1, "pwd", "2026-06-27T01:00:00.000Z");
await repo.create("user-1", 1, "ls", "2026-06-27T02:00:00.000Z");
await repo.create("user-2", 3, "whoami", "2026-06-27T03:00:00.000Z");
expect(await repo.listUniqueCommandsForHost("user-1", 1)).toEqual([
"ls",
"pwd",
]);
expect(await repo.listCommandsForHost("user-1", 1)).toEqual([
"ls",
"pwd",
"ls",
]);
});
it("deletes commands by command, host, host list, and user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.create("user-1", 1, "ls");
await repo.create("user-1", 1, "ls");
await repo.create("user-1", 2, "pwd");
await repo.create("user-2", 3, "whoami");
expect(writeCount).toBe(4);
expect(await repo.deleteCommandForHost("user-1", 1, "missing")).toBe(0);
expect(writeCount).toBe(4);
expect(await repo.deleteCommandForHost("user-1", 1, "ls")).toBe(2);
expect(writeCount).toBe(5);
expect(await repo.deleteByUserAndHost("user-1", 2)).toBe(1);
expect(await repo.deleteByHostIds([])).toBe(0);
expect(await repo.deleteByHostIds([3])).toBe(1);
expect(writeCount).toBe(7);
await repo.create("user-1", 1, "date");
expect(await repo.deleteByUserId("user-1")).toBe(1);
expect(writeCount).toBe(9);
});
});
@@ -1,120 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { DashboardServiceLinkRepository } from "../../../database/repositories/dashboard-service-link-repository.js";
describe("DashboardServiceLinkRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<DashboardServiceLinkRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
`);
return new DashboardServiceLinkRepository(context, onWrite);
}
it("creates and lists links ordered by order then id", async () => {
const repo = await createRepository();
const first = await repo.createForUser(
"user-1",
{ label: "Docs", url: "https://docs.example.com" },
"2026-06-27T00:00:00.000Z",
);
const second = await repo.createForUser("user-1", {
label: "Status",
url: "https://status.example.com",
});
await repo.createForUser("user-2", {
label: "Other",
url: "https://other.example.com",
});
expect(first).toMatchObject({
userId: "user-1",
label: "Docs",
order: 0,
createdAt: "2026-06-27T00:00:00.000Z",
});
expect(second.order).toBe(1);
expect(
(await repo.listByUserId("user-1")).map((link) => link.label),
).toEqual(["Docs", "Status"]);
});
it("finds, updates, and deletes a user-owned link", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const link = await repo.createForUser("user-1", {
label: "Docs",
url: "https://docs.example.com",
});
expect(writeCount).toBe(1);
expect(await repo.findByIdForUser("user-2", link.id)).toBeNull();
const updated = await repo.updateForUser("user-1", link.id, {
label: "Docs renamed",
});
expect(updated).toMatchObject({
id: link.id,
label: "Docs renamed",
url: "https://docs.example.com",
});
expect(writeCount).toBe(2);
expect(await repo.updateForUser("user-2", link.id, { label: "Nope" })).toBe(
null,
);
expect(writeCount).toBe(2);
expect(await repo.deleteForUser("user-2", link.id)).toBeNull();
expect(await repo.deleteForUser("user-1", link.id)).toEqual({
syncId: expect.any(String),
});
expect(writeCount).toBe(3);
});
it("deletes all dashboard links for a user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.createForUser("user-1", {
label: "Docs",
url: "https://docs.example.com",
});
await repo.createForUser("user-1", {
label: "Status",
url: "https://status.example.com",
});
await repo.createForUser("user-2", {
label: "Other",
url: "https://other.example.com",
});
await expect(repo.deleteByUserId("user-1")).resolves.toBe(2);
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
expect(await repo.listByUserId("user-1")).toEqual([]);
expect(
(await repo.listByUserId("user-2")).map((link) => link.label),
).toEqual(["Other"]);
expect(writeCount).toBe(4);
});
});
@@ -1,93 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { DismissedAlertRepository } from "../../../database/repositories/dismissed-alert-repository.js";
describe("DismissedAlertRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<DismissedAlertRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
`);
return new DismissedAlertRepository(context, onWrite);
}
it("creates, lists, and finds dismissed alerts by user", async () => {
const repo = await createRepository();
await repo.create("user-1", "alert-1");
await repo.create("user-1", "alert-2");
await repo.create("user-2", "alert-3");
expect(await repo.listAlertIdsByUserId("user-1")).toEqual([
"alert-1",
"alert-2",
]);
expect((await repo.findForUser("user-1", "alert-1"))?.alertId).toBe(
"alert-1",
);
expect(await repo.findForUser("user-1", "alert-3")).toBeNull();
expect(
(await repo.listByUserId("user-1")).map((row) => row.alertId),
).toEqual(["alert-1", "alert-2"]);
});
it("creates import alerts without duplicating user alert pairs", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await expect(
repo.createForImport("user-1", "alert-1", "2026-01-01T00:00:00.000Z"),
).resolves.toBe(true);
await expect(
repo.createForImport("user-1", "alert-1", "2026-01-02T00:00:00.000Z"),
).resolves.toBe(false);
const alerts = await repo.listByUserId("user-1");
expect(alerts).toHaveLength(1);
expect(alerts[0]).toMatchObject({
alertId: "alert-1",
dismissedAt: "2026-01-01T00:00:00.000Z",
});
expect(writeCount).toBe(1);
});
it("deletes dismissed alerts and only triggers writes for changed rows", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.create("user-1", "alert-1");
await repo.create("user-1", "alert-2");
await repo.create("user-2", "alert-3");
expect(writeCount).toBe(3);
expect(await repo.deleteForUser("user-1", "missing")).toBe(false);
expect(writeCount).toBe(3);
expect(await repo.deleteForUser("user-1", "alert-1")).toBe(true);
expect(writeCount).toBe(4);
expect(await repo.listAlertIdsByUserId("user-1")).toEqual(["alert-2"]);
expect(await repo.deleteByUserId("user-1")).toBe(1);
expect(writeCount).toBe(5);
expect(await repo.deleteByUserId("user-1")).toBe(0);
expect(writeCount).toBe(5);
});
});
@@ -1,193 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { FileManagerBookmarkRepository } from "../../../database/repositories/file-manager-bookmark-repository.js";
describe("FileManagerBookmarkRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<FileManagerBookmarkRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'user-1', 'one', '10.0.0.1', 22, 'root', 'password'), (2, 'user-1', 'two', '10.0.0.1', 22, 'root', 'password'), (3, 'user-2', 'other', '10.0.0.1', 22, 'root', 'password');
`);
return new FileManagerBookmarkRepository(context, onWrite);
}
it("upserts and lists recent files by last-opened time", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsertRecent(
"user-1",
{ hostId: 1, path: "/var/log/app.log" },
"2026-01-01T00:00:00.000Z",
);
await repo.upsertRecent(
"user-1",
{ hostId: 1, path: "/opt/app/config.json", name: "Config" },
"2026-01-02T00:00:00.000Z",
);
await repo.upsertRecent(
"user-1",
{ hostId: 1, path: "/var/log/app.log" },
"2026-01-03T00:00:00.000Z",
);
const recent = await repo.listRecentForHost("user-1", 1);
expect(recent.map((entry) => entry.path)).toEqual([
"/var/log/app.log",
"/opt/app/config.json",
]);
expect(recent[0].lastOpened).toBe("2026-01-03T00:00:00.000Z");
expect(recent[0].name).toBe("app.log");
expect(writeCount).toBe(3);
expect(
await repo.deleteRecentForHostPath("user-1", {
hostId: 1,
path: "/var/log/app.log",
}),
).toBe(1);
expect(writeCount).toBe(4);
});
it("creates pinned files and shortcuts without duplicating paths", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
expect(
await repo.createPinned(
"user-1",
{ hostId: 1, path: "/srv/www", name: "Web" },
"2026-01-01T00:00:00.000Z",
),
).toBe(true);
expect(
await repo.createPinned("user-1", { hostId: 1, path: "/srv/www" }),
).toBe(false);
expect((await repo.listPinnedForHost("user-1", 1))[0]).toMatchObject({
name: "Web",
path: "/srv/www",
});
expect(
await repo.createShortcut(
"user-1",
{ hostId: 1, path: "/etc/nginx" },
"2026-01-02T00:00:00.000Z",
),
).toBe(true);
expect(
await repo.createShortcut("user-1", { hostId: 1, path: "/etc/nginx" }),
).toBe(false);
expect((await repo.listShortcutsForHost("user-1", 1))[0]).toMatchObject({
name: "nginx",
path: "/etc/nginx",
});
expect(writeCount).toBe(2);
expect(
await repo.deletePinnedForHostPath("user-1", {
hostId: 1,
path: "/srv/www",
}),
).toBe(1);
expect(
await repo.deleteShortcutForHostPath("user-1", {
hostId: 1,
path: "/etc/nginx",
}),
).toBe(1);
expect(writeCount).toBe(4);
});
it("creates import bookmarks without duplicating user path/name pairs", async () => {
const repo = await createRepository();
await expect(
repo.createRecentForImport(
"user-1",
{ hostId: 1, path: "/tmp/a.txt", name: "A" },
"2026-01-01T00:00:00.000Z",
),
).resolves.toBe(true);
await expect(
repo.createRecentForImport("user-1", {
hostId: 2,
path: "/tmp/a.txt",
name: "A",
}),
).resolves.toBe(false);
await expect(
repo.createPinnedForImport("user-1", {
hostId: 1,
path: "/srv/www",
name: "Web",
}),
).resolves.toBe(true);
await expect(
repo.createPinnedForImport("user-1", {
hostId: 2,
path: "/srv/www",
name: "Web",
}),
).resolves.toBe(false);
await expect(
repo.createShortcutForImport("user-1", {
hostId: 1,
path: "/etc/nginx",
name: "Nginx",
}),
).resolves.toBe(true);
await expect(
repo.createShortcutForImport("user-1", {
hostId: 2,
path: "/etc/nginx",
name: "Nginx",
}),
).resolves.toBe(false);
});
it("deletes bookmarks by user, host, and host list", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsertRecent("user-1", { hostId: 1, path: "/one" });
await repo.createPinned("user-1", { hostId: 2, path: "/two" });
await repo.createShortcut("user-2", { hostId: 3, path: "/three" });
expect(writeCount).toBe(3);
expect(await repo.deleteByHostId(1)).toBe(1);
expect(await repo.deleteByHostId(1)).toBe(0);
expect(await repo.deleteByHostIds([])).toBe(0);
expect(await repo.deleteByHostIds([2])).toBe(1);
expect(writeCount).toBe(5);
expect(await repo.deleteByUserId("user-2")).toBe(1);
expect(await repo.deleteByUserId("user-2")).toBe(0);
expect(writeCount).toBe(6);
});
});
@@ -1,103 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { FleetRepository } from "../../../database/repositories/fleet-repository.js";
describe("FleetRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<{ repository: FleetRepository }> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type, tags)
VALUES
(1, 'user-1', 'web-1', '10.0.0.1', 22, 'root', 'password', 'prod-web,edge'),
(2, 'user-1', 'web-2', '10.0.0.2', 22, 'root', 'password', 'prod-web'),
(3, 'user-1', 'db-1', '10.0.0.3', 22, 'root', 'password', 'prod-db'),
(4, 'user-1', 'static-only', '10.0.0.4', 22, 'root', 'password', NULL),
(5, 'user-2', 'other-user-host', '10.0.0.5', 22, 'root', 'password', 'prod-web');
`);
return { repository: new FleetRepository(context, onWrite) };
}
it("unions static membership and tag-matched hosts, deduplicated by id", async () => {
let writes = 0;
const { repository } = await createRepository(() => {
writes += 1;
});
const fleet = await repository.create("user-1", {
name: "web fleet",
tagRules: ["prod-web"],
});
// host 1 matches by tag AND is added statically - must appear once.
await repository.addMember(fleet.id, 1);
// host 4 has no tags - only reachable via static membership.
await repository.addMember(fleet.id, 4);
const members = await repository.listEffectiveMembers("user-1", fleet.id);
const ids = members.map((m) => m.id).sort((a, b) => a - b);
expect(ids).toEqual([1, 2, 4]);
expect(writes).toBeGreaterThan(0);
});
it("never returns another user's hosts even if tags match", async () => {
const { repository } = await createRepository();
const fleet = await repository.create("user-1", {
name: "web fleet",
tagRules: ["prod-web"],
});
const members = await repository.listEffectiveMembers("user-1", fleet.id);
expect(members.map((m) => m.id)).not.toContain(5);
});
it("returns only static members when a fleet has no tag rules", async () => {
const { repository } = await createRepository();
const fleet = await repository.create("user-1", { name: "static fleet" });
await repository.addMember(fleet.id, 3);
const members = await repository.listEffectiveMembers("user-1", fleet.id);
expect(members.map((m) => m.id)).toEqual([3]);
});
it("removeMember only drops the static row, not tag-based membership", async () => {
const { repository } = await createRepository();
const fleet = await repository.create("user-1", {
name: "web fleet",
tagRules: ["prod-web"],
});
await repository.addMember(fleet.id, 1);
await expect(repository.removeMember(fleet.id, 1)).resolves.toBe(true);
// host 1 still matches the tag rule, so it remains an effective member.
const members = await repository.listEffectiveMembers("user-1", fleet.id);
expect(members.map((m) => m.id)).toContain(1);
});
it("returns an empty list for a fleet the caller does not own", async () => {
const { repository } = await createRepository();
const fleet = await repository.create("user-1", { name: "private" });
await expect(
repository.listEffectiveMembers("user-2", fleet.id),
).resolves.toEqual([]);
});
});
@@ -1,131 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { HomepageItemRepository } from "../../../database/repositories/homepage-item-repository.js";
describe("HomepageItemRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<HomepageItemRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
`);
return new HomepageItemRepository(context, onWrite);
}
it("creates and lists homepage items by id", async () => {
const repo = await createRepository();
const first = await repo.createForUser(
"user-1",
{ typeId: "clock", title: "Clock", config: "{}" },
"2026-06-27T00:00:00.000Z",
);
const second = await repo.createForUser("user-1", {
typeId: "terminal",
title: null,
config: '{"hostId":1}',
});
await repo.createForUser("user-2", {
typeId: "other",
title: "Other",
config: "{}",
});
expect(first).toMatchObject({
userId: "user-1",
typeId: "clock",
title: "Clock",
config: "{}",
createdAt: "2026-06-27T00:00:00.000Z",
});
expect((await repo.listByUserId("user-1")).map((item) => item.id)).toEqual([
first.id,
second.id,
]);
});
it("finds, updates, and deletes user-owned homepage items", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const item = await repo.createForUser("user-1", {
typeId: "clock",
title: "Clock",
config: "{}",
});
expect(writeCount).toBe(1);
expect(await repo.findByIdForUser("user-2", item.id)).toBeNull();
const updated = await repo.updateForUser(
"user-1",
item.id,
{ title: "Clock renamed", config: '{"timezone":"UTC"}' },
"2026-06-27T01:00:00.000Z",
);
expect(updated).toMatchObject({
id: item.id,
title: "Clock renamed",
config: '{"timezone":"UTC"}',
updatedAt: "2026-06-27T01:00:00.000Z",
});
expect(writeCount).toBe(2);
expect(
await repo.updateForUser("user-2", item.id, { title: "Nope" }),
).toBeNull();
expect(writeCount).toBe(2);
expect(await repo.deleteForUser("user-2", item.id)).toBeNull();
expect(await repo.deleteForUser("user-1", item.id)).toEqual({
syncId: expect.any(String),
});
expect(writeCount).toBe(3);
});
it("deletes all homepage items for a user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.createForUser("user-1", {
typeId: "clock",
title: "Clock",
config: "{}",
});
await repo.createForUser("user-1", {
typeId: "terminal",
title: "Terminal",
config: "{}",
});
await repo.createForUser("user-2", {
typeId: "other",
title: "Other",
config: "{}",
});
await expect(repo.deleteByUserId("user-1")).resolves.toBe(2);
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
expect(await repo.listByUserId("user-1")).toEqual([]);
expect(
(await repo.listByUserId("user-2")).map((item) => item.title),
).toEqual(["Other"]);
expect(writeCount).toBe(4);
});
});
@@ -1,85 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { HomepageLayoutRepository } from "../../../database/repositories/homepage-layout-repository.js";
describe("HomepageLayoutRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<HomepageLayoutRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
`);
return new HomepageLayoutRepository(context, onWrite);
}
it("finds, creates, and updates a layout by user id", async () => {
const repo = await createRepository();
expect(await repo.findByUserId("user-1")).toBeNull();
const created = await repo.upsertForUser(
"user-1",
JSON.stringify({ entries: [{ id: "w1" }], zoom: 1 }),
"2026-06-27T00:00:00.000Z",
);
expect(created).toMatchObject({
userId: "user-1",
layout: '{"entries":[{"id":"w1"}],"zoom":1}',
updatedAt: "2026-06-27T00:00:00.000Z",
});
const updated = await repo.upsertForUser(
"user-1",
JSON.stringify({ entries: [], zoom: 1.25 }),
"2026-06-27T01:00:00.000Z",
);
expect(updated).toMatchObject({
id: created.id,
userId: "user-1",
layout: '{"entries":[],"zoom":1.25}',
updatedAt: "2026-06-27T01:00:00.000Z",
});
});
it("triggers writes after create and update", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsertForUser("user-1", "{}");
await repo.upsertForUser("user-1", '{"zoom":2}');
expect(writeCount).toBe(2);
});
it("deletes a layout for a user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsertForUser("user-1", '{"zoom":1}');
await repo.upsertForUser("user-2", '{"zoom":2}');
await expect(repo.deleteByUserId("user-1")).resolves.toBe(1);
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
expect(await repo.findByUserId("user-1")).toBeNull();
expect((await repo.findByUserId("user-2"))?.layout).toBe('{"zoom":2}');
expect(writeCount).toBe(3);
});
});
@@ -483,7 +483,6 @@ describe("HostRepository and CredentialRepository", () => {
port: 22,
username: "root",
authType: "password",
statsConfig: JSON.stringify({ cpu: true }),
});
const second = await repo.hosts.create({
userId: "user-1",
@@ -0,0 +1,116 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { HostDefaultsRepository } from "../../../database/repositories/host-defaults-repository.js";
describe("HostDefaultsRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(): Promise<HostDefaultsRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_folders (id, user_id, name)
VALUES (1, 'user-1', 'prod'), (2, 'user-2', 'prod');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, folder, auth_type)
VALUES
(1, 'user-1', 'one', '10.0.0.1', 22, 'root', 'prod', 'password'),
(2, 'user-2', 'two', '10.0.0.2', 22, 'root', null, 'password');
`);
return new HostDefaultsRepository(context);
}
it("keeps each level apart, the server level included", async () => {
const repository = await createRepository();
await repository.apply(
{ level: "admin" },
[{ namespace: "core", key: "sshPort", value: "2022" }],
[],
"user-1",
);
await repository.apply(
{ level: "user", userId: "user-1" },
[{ namespace: "core", key: "sshPort", value: "2023" }],
[],
"user-1",
);
await repository.apply(
{ level: "folder", userId: "user-1", folderId: 1 },
[{ namespace: "term", key: "fontSize", value: "16" }],
[],
"user-1",
);
expect(await repository.listScope({ level: "admin" })).toHaveLength(1);
const forUser = await repository.listForUsers(["user-1"]);
expect(forUser.map((row) => `${row.level}:${row.value}`).sort()).toEqual([
"admin:2022",
"folder:16",
"user:2023",
]);
expect(await repository.listForUsers(["user-2"])).toHaveLength(1);
});
it("updates a key in place and clears one", async () => {
const repository = await createRepository();
const scope = { level: "user" as const, userId: "user-1" };
await repository.apply(
scope,
[{ namespace: "core", key: "sshPort", value: "1" }],
[],
null,
);
await repository.apply(
scope,
[{ namespace: "core", key: "sshPort", value: "2" }],
[],
null,
);
expect((await repository.listScope(scope)).map((row) => row.value)).toEqual(
["2"],
);
await repository.apply(
scope,
[],
[{ namespace: "core", key: "sshPort" }],
null,
);
expect(await repository.listScope(scope)).toEqual([]);
});
it("finds or creates a folder row for a path", async () => {
const repository = await createRepository();
expect(await repository.ensureFolder("user-1", "prod")).toBe(1);
const created = await repository.ensureFolder("user-1", "prod / web");
expect(await repository.findFolder(created)).toMatchObject({
userId: "user-1",
name: "prod / web",
});
});
it("reads and writes hosts in bulk", async () => {
const repository = await createRepository();
expect(
(await repository.listHosts({ userIds: ["user-1"] })).map(
(row) => row.id,
),
).toEqual([1]);
await repository.updateHosts([
{ id: 1, values: { sshPort: 2022, defaultOverrides: '{"core":[]}' } },
]);
const [row] = await repository.listHosts({ hostIds: [1] });
expect(row.sshPort).toBe(2022);
expect(row.defaultOverrides).toBe('{"core":[]}');
expect(await repository.listHostPlacement(["user-1"])).toEqual([
{ id: 1, userId: "user-1", folder: "prod", parentHostId: null },
]);
});
});
@@ -1,155 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { HostHealthRepository } from "../../../database/repositories/host-health-repository.js";
describe("HostHealthRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<HostHealthRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'user-1', 'one', '10.0.0.1', 22, 'root', 'password'), (2, 'user-2', 'two', '10.0.0.1', 22, 'root', 'password');
INSERT INTO host_health_checks (
user_id, host_id, checks, interval_seconds, created_at, updated_at
)
VALUES (
'user-1',
1,
'[{"id":"tcp","name":"TCP","type":"tcp","target":"localhost","port":22}]',
300,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z'
);
`);
return new HostHealthRepository(context, onWrite);
}
it("finds and upserts check configuration", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const existing = await repo.findChecksByUserAndHost("user-1", 1);
expect(existing?.intervalSeconds).toBe(300);
const updated = await repo.upsertChecks(
"user-1",
1,
'[{"id":"http"}]',
60,
"2026-02-01T00:00:00.000Z",
);
expect(updated).toMatchObject({
id: existing?.id,
checks: '[{"id":"http"}]',
intervalSeconds: 60,
updatedAt: "2026-02-01T00:00:00.000Z",
});
const created = await repo.upsertChecks(
"user-2",
2,
'[{"id":"tcp"}]',
120,
"2026-03-01T00:00:00.000Z",
);
expect(created).toMatchObject({
userId: "user-2",
hostId: 2,
checks: '[{"id":"tcp"}]',
intervalSeconds: 120,
createdAt: "2026-03-01T00:00:00.000Z",
updatedAt: "2026-03-01T00:00:00.000Z",
});
expect(writeCount).toBe(2);
});
it("records and prunes history", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
expect(
await repo.recordHistory(
"user-1",
1,
[{ checkId: "one", ok: true, latencyMs: 12, detail: "open" }],
1,
"2026-01-01T00:00:00.000Z",
),
).toBe(1);
expect(
await repo.recordHistory(
"user-1",
1,
[{ checkId: "two", ok: false, latencyMs: null, detail: "closed" }],
1,
"2026-01-02T00:00:00.000Z",
),
).toBe(1);
const history = await repo.listHistory("user-1", 1, 10);
expect(history).toHaveLength(1);
expect(history[0]).toMatchObject({
userId: "user-1",
hostId: 1,
checkId: "two",
ok: false,
latencyMs: null,
detail: "closed",
});
expect(writeCount).toBe(2);
});
it("deletes all health checks and history for a user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsertChecks("user-2", 2, '[{"id":"tcp"}]', 120);
await repo.recordHistory(
"user-1",
1,
[{ checkId: "one", ok: true, latencyMs: 12, detail: "open" }],
10,
);
await repo.recordHistory(
"user-2",
2,
[{ checkId: "two", ok: false, latencyMs: null, detail: "closed" }],
10,
);
await expect(repo.deleteByUserId("user-1")).resolves.toEqual({
checksDeleted: 1,
historyDeleted: 1,
});
await expect(repo.deleteByUserId("missing")).resolves.toEqual({
checksDeleted: 0,
historyDeleted: 0,
});
expect(await repo.findChecksByUserAndHost("user-1", 1)).toBeNull();
expect(await repo.listHistory("user-1", 1, 10)).toEqual([]);
expect((await repo.findChecksByUserAndHost("user-2", 2))?.hostId).toBe(2);
expect(await repo.listHistory("user-2", 2, 10)).toHaveLength(1);
expect(writeCount).toBe(4);
});
});
@@ -1,80 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { HostMetricsHistoryRepository } from "../../../database/repositories/host-metrics-history-repository.js";
describe("HostMetricsHistoryRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<HostMetricsHistoryRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash) VALUES
('user-1', 'user-1', 'hash'),
('user-2', 'user-2', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'user-1', 'one', '10.0.0.1', 22, 'root', 'password'), (2, 'user-2', 'two', '10.0.0.1', 22, 'root', 'password');
INSERT INTO host_metrics_history (
host_id, ts, cpu_percent, mem_percent, disk_percent, net_rx_bytes, net_tx_bytes
)
VALUES
(1, '2026-01-01 00:00:00', 10, 20, 30, 100, 200),
(1, '2026-01-02 00:00:00', 11, 21, 31, 101, 201),
(1, '2999-01-01 00:00:00', 12, 22, 32, 102, 202),
(2, '2026-01-02 00:00:00', 99, 99, 99, 999, 999);
`);
return new HostMetricsHistoryRepository(context, onWrite);
}
it("creates and lists metrics history rows by range", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.create({
hostId: 1,
cpuPercent: 12,
memPercent: 22,
diskPercent: 32,
netRxBytes: 102,
netTxBytes: 202,
});
const rows = await repo.listRange(
1,
"2026-01-01 00:00:00",
"2026-01-02 23:59:59",
);
expect(rows.map((row) => row.cpuPercent)).toEqual([10, 11]);
expect(writeCount).toBe(1);
});
it("prunes old history for a host only", async () => {
const repo = await createRepository();
await repo.pruneOlderThan(1, 1);
const rows = await repo.listRange(
1,
"2000-01-01 00:00:00",
"2999-12-31 23:59:59",
);
expect(rows.map((row) => row.ts)).toEqual(["2999-01-01 00:00:00"]);
expect(
await repo.listRange(2, "2026-01-01 00:00:00", "2026-01-03 00:00:00"),
).toHaveLength(1);
});
});
@@ -1,119 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { HostMetricsPreferenceRepository } from "../../../database/repositories/host-metrics-preference-repository.js";
describe("HostMetricsPreferenceRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<HostMetricsPreferenceRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, stats_config, ip, port, username, auth_type)
VALUES (1, 'user-1', 'one', '{}', '10.0.0.1', 22, 'root', 'password'), (2, 'user-2', 'two', '{}', '10.0.0.1', 22, 'root', 'password');
INSERT INTO host_metrics_preferences (
user_id, host_id, layout, created_at, updated_at
)
VALUES (
'user-1',
1,
'{"slots":[],"columns":3}',
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z'
);
`);
return new HostMetricsPreferenceRepository(context, onWrite);
}
it("finds a saved layout by user and host", async () => {
const repo = await createRepository();
const existing = await repo.findByUserAndHost("user-1", 1);
expect(existing?.layout).toBe('{"slots":[],"columns":3}');
expect(await repo.findByUserAndHost("user-1", 2)).toBeNull();
});
it("updates and inserts layouts with write notifications", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const updated = await repo.upsertLayout(
"user-1",
1,
'{"slots":[{"id":"cpu"}],"columns":2}',
"2026-02-01T00:00:00.000Z",
);
expect(updated).toMatchObject({
id: 1,
layout: '{"slots":[{"id":"cpu"}],"columns":2}',
updatedAt: "2026-02-01T00:00:00.000Z",
});
const created = await repo.upsertLayout(
"user-2",
2,
'{"slots":[{"id":"mem"}],"columns":1}',
"2026-03-01T00:00:00.000Z",
);
expect(created).toMatchObject({
userId: "user-2",
hostId: 2,
layout: '{"slots":[{"id":"mem"}],"columns":1}',
createdAt: "2026-03-01T00:00:00.000Z",
updatedAt: "2026-03-01T00:00:00.000Z",
});
expect(writeCount).toBe(2);
});
it("updates host stats config for the owning user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await expect(
repo.updateHostStatsConfig(
"user-1",
1,
'{"enabledWidgets":["cpu","memory"]}',
),
).resolves.toBe(true);
await expect(
repo.updateHostStatsConfig("user-2", 1, '{"enabledWidgets":["disk"]}'),
).resolves.toBe(false);
expect(writeCount).toBe(1);
});
it("deletes all metric preferences for a user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsertLayout("user-2", 2, '{"slots":["mem"]}');
await expect(repo.deleteByUserId("user-1")).resolves.toBe(1);
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
expect(await repo.findByUserAndHost("user-1", 1)).toBeNull();
expect((await repo.findByUserAndHost("user-2", 2))?.layout).toBe(
'{"slots":["mem"]}',
);
expect(writeCount).toBe(2);
});
});
@@ -0,0 +1,178 @@
import crypto from "node:crypto";
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import {
HostProtocolAuthRepository,
decryptProtocolLogin,
protocolAuthRecordId,
type HostProtocolLogin,
} from "../../../database/repositories/host-protocol-auth-repository.js";
import { FieldCrypto } from "../../../utils/field-crypto.js";
const ownerKey = crypto.randomBytes(32);
const otherKey = crypto.randomBytes(32);
function login(overrides: Partial<HostProtocolLogin> = {}): HostProtocolLogin {
return {
protocol: "spice",
authType: "direct",
credentialId: null,
username: "viewer",
password: "spice-pass",
fields: { display: "2" },
secretFields: { ticket: "t-secret" },
...overrides,
};
}
describe("HostProtocolAuthRepository", () => {
let adapter: TestSqliteDatabase | null = null;
let writes = 0;
afterEach(async () => {
await adapter?.close();
adapter = null;
});
async function createRepository(): Promise<HostProtocolAuthRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash) VALUES
('owner-1', 'owner-1', 'hash'),
('owner-2', 'owner-2', 'hash');
INSERT INTO ssh_credentials (id, user_id, name, username, auth_type) VALUES
(5, 'owner-1', 'cred-5', 'root', 'password');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type) VALUES
(42, 'owner-1', 'prod', '10.0.0.42', 22, 'root', 'password'),
(43, 'owner-1', 'stage', '10.0.0.43', 22, 'root', 'password'),
(44, 'owner-2', 'other', '10.0.0.44', 22, 'root', 'password');
`);
writes = 0;
return new HostProtocolAuthRepository(context, () => {
writes++;
});
}
it("round-trips a login with its secrets encrypted at rest", async () => {
const repository = await createRepository();
await repository.upsert("owner-1", 42, login(), ownerKey);
const row = await repository.findRow(42, "spice");
expect(row).toMatchObject({
hostId: 42,
userId: "owner-1",
protocol: "spice",
authType: "direct",
username: "viewer",
fields: JSON.stringify({ display: "2" }),
});
expect(FieldCrypto.isEncrypted(row!.password!)).toBe(true);
expect(row!.password).not.toContain("spice-pass");
expect(row!.secretFields).not.toContain("t-secret");
expect(await repository.find(42, "spice", ownerKey)).toEqual(login());
expect(writes).toBe(1);
});
it("updates in place, one row per host and protocol", async () => {
const repository = await createRepository();
await repository.upsert("owner-1", 42, login(), ownerKey);
await repository.upsert(
"owner-1",
42,
login({ username: "other", password: null, secretFields: {} }),
ownerKey,
);
expect(await repository.listRowsForHost(42)).toHaveLength(1);
expect(await repository.find(42, "spice", ownerKey)).toMatchObject({
username: "other",
password: null,
secretFields: {},
});
});
it("opens nothing with another user's key", async () => {
const repository = await createRepository();
await repository.upsert("owner-1", 42, login(), ownerKey);
expect(await repository.find(42, "spice", otherKey)).toMatchObject({
username: "viewer",
password: null,
secretFields: {},
});
});
it("treats a tampered secret as missing", async () => {
const repository = await createRepository();
await repository.upsert("owner-1", 42, login(), ownerKey);
const row = (await repository.findRow(42, "spice"))!;
const envelope = JSON.parse(row.password!);
envelope.data = envelope.data.replace(/^./, (c: string) =>
c === "0" ? "1" : "0",
);
expect(
decryptProtocolLogin(
{ ...row, password: JSON.stringify(envelope) },
ownerKey,
).password,
).toBeNull();
});
it("binds each secret to its host and protocol", async () => {
const repository = await createRepository();
await repository.upsert("owner-1", 42, login(), ownerKey);
const row = (await repository.findRow(42, "spice"))!;
expect(JSON.parse(row.password!).recordId).toBe(
protocolAuthRecordId(42, "spice"),
);
expect(() =>
FieldCrypto.decryptField(row.password!, ownerKey, "", "secretFields"),
).toThrow();
});
it("finds the owner's hosts whose login uses a credential", async () => {
const repository = await createRepository();
await repository.upsert(
"owner-1",
42,
login({ authType: "credential", credentialId: 5, password: null }),
ownerKey,
);
await repository.upsert(
"owner-1",
43,
login({ protocol: "x2go" }),
ownerKey,
);
expect(await repository.listHostIdsForCredential("owner-1", 5)).toEqual([
42,
]);
expect(await repository.listHostIdsForCredential("owner-2", 5)).toEqual([]);
expect(
(await repository.listRowsForUser("owner-1"))
.map((row) => row.hostId)
.sort(),
).toEqual([42, 43]);
});
it("deletes one protocol's login", async () => {
const repository = await createRepository();
await repository.upsert("owner-1", 42, login(), ownerKey);
await repository.upsert(
"owner-1",
42,
login({ protocol: "x2go" }),
ownerKey,
);
expect(await repository.delete(42, "spice")).toBe(true);
expect(await repository.delete(42, "spice")).toBe(false);
expect(
(await repository.listRowsForHost(42)).map((row) => row.protocol),
).toEqual(["x2go"]);
});
});
@@ -129,7 +129,6 @@ describe("HostRepository Proxmox sync inserts", () => {
enableTerminal: true,
enableFileManager: true,
enableTunnel: true,
enableDocker: false,
enableSsh: true,
enableRdp: false,
rdpUser: null,
@@ -148,8 +147,6 @@ describe("HostRepository Proxmox sync inserts", () => {
tunnelConnections: "[]",
jumpHosts: null,
quickActions: null,
statsConfig: null,
dockerConfig: null,
terminalConfig: null,
forceKeyboardInteractive: "false",
useSocks5: 0,
@@ -192,10 +192,6 @@ describe("HostResolutionRepository", () => {
await expect(repository.findHostUpdateState(1)).resolves.toEqual({
userId: "user-1",
credentialId: 7,
rdpCredentialId: null,
vncCredentialId: null,
telnetCredentialId: null,
vaultProfileId: null,
authType: "password",
parentHostId: null,
folder: null,
@@ -244,29 +240,6 @@ describe("HostResolutionRepository", () => {
);
});
it("lists tunnel-enabled hosts with tunnel data through each owner decryption boundary", async () => {
vi.mocked(DataCrypto.getUserDataKey).mockImplementation((userId) =>
Buffer.from(`${userId}-key`),
);
const repository = await createRepository();
const rows = await repository.listHostsWithTunnelConnections();
expect(rows.map((row) => row.id)).toEqual([1, 3]);
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
"ssh_data",
expect.objectContaining({ id: 1 }),
"user-1",
Buffer.from("user-1-key"),
);
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
"ssh_data",
expect.objectContaining({ id: 3 }),
"user-2",
Buffer.from("user-2-key"),
);
});
it("skips owner-scoped host list rows when that user's data is locked", async () => {
vi.mocked(DataCrypto.getUserDataKey).mockImplementation((userId) =>
userId === "user-1" ? Buffer.from("user-1-key") : null,
@@ -1,73 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { NetworkTopologyRepository } from "../../../database/repositories/network-topology-repository.js";
describe("NetworkTopologyRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<NetworkTopologyRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
`);
return new NetworkTopologyRepository(context, onWrite);
}
it("finds, creates, and updates topology by user id", async () => {
const repo = await createRepository();
expect(await repo.findByUserId("user-1")).toBeNull();
await repo.upsertForUser(
"user-1",
JSON.stringify({ nodes: [{ id: "host-1" }], edges: [] }),
"2026-06-27T00:00:00.000Z",
);
expect(await repo.findByUserId("user-1")).toMatchObject({
userId: "user-1",
topology: '{"nodes":[{"id":"host-1"}],"edges":[]}',
updatedAt: "2026-06-27T00:00:00.000Z",
});
await repo.upsertForUser(
"user-1",
JSON.stringify({ nodes: [], edges: [{ id: "edge-1" }] }),
"2026-06-27T01:00:00.000Z",
);
expect(await repo.findByUserId("user-1")).toMatchObject({
userId: "user-1",
topology: '{"nodes":[],"edges":[{"id":"edge-1"}]}',
updatedAt: "2026-06-27T01:00:00.000Z",
});
});
it("deletes topology and only triggers writes for changed rows", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsertForUser("user-1", "{}");
await repo.upsertForUser("user-1", '{"nodes":[]}');
expect(writeCount).toBe(2);
expect(await repo.deleteByUserId("missing")).toBe(0);
expect(writeCount).toBe(2);
expect(await repo.deleteByUserId("user-1")).toBe(1);
expect(writeCount).toBe(3);
expect(await repo.findByUserId("user-1")).toBeNull();
});
});
@@ -1,105 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { OpksshTokenRepository } from "../../../database/repositories/opkssh-token-repository.js";
describe("OpksshTokenRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<OpksshTokenRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'user-1', 'one', '10.0.0.1', 22, 'root', 'password'), (2, 'user-1', 'two', '10.0.0.1', 22, 'root', 'password'), (3, 'user-2', 'other', '10.0.0.1', 22, 'root', 'password');
INSERT INTO opkssh_tokens (
user_id, host_id, ssh_cert, private_key, email, expires_at
)
VALUES
('user-1', 1, 'cert-1', 'key-1', 'alice@example.com', '2099-01-01T00:00:00.000Z'),
('user-1', 2, 'cert-2', 'key-2', 'alice2@example.com', '2099-01-01T00:00:00.000Z'),
('user-2', 3, 'cert-3', 'key-3', 'bob@example.com', '2099-01-01T00:00:00.000Z');
`);
return new OpksshTokenRepository(context, onWrite);
}
it("finds and upserts a token by user and host", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const existing = await repo.findByUserAndHost("user-1", 1);
expect(existing?.sshCert).toBe("cert-1");
await repo.upsert({
userId: "user-1",
hostId: 1,
sshCert: "new-cert",
privateKey: "new-key",
email: "new@example.com",
sub: "sub",
issuer: "issuer",
audience: "aud",
expiresAt: "2099-02-01T00:00:00.000Z",
createdAt: "2026-01-01T00:00:00.000Z",
});
const updated = await repo.findByUserAndHost("user-1", 1);
expect(updated).toMatchObject({
sshCert: "new-cert",
privateKey: "new-key",
email: "new@example.com",
sub: "sub",
issuer: "issuer",
audience: "aud",
expiresAt: "2099-02-01T00:00:00.000Z",
createdAt: "2026-01-01T00:00:00.000Z",
});
expect(writeCount).toBe(1);
});
it("updates last-used and deletes one token", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
expect(
await repo.updateLastUsed("user-1", 1, "2026-01-02T00:00:00.000Z"),
).toBe(true);
expect(await repo.updateLastUsed("missing", 1)).toBe(false);
expect((await repo.findByUserAndHost("user-1", 1))?.lastUsed).toBe(
"2026-01-02T00:00:00.000Z",
);
expect(await repo.deleteByUserAndHost("user-1", 1)).toBe(true);
expect(await repo.deleteByUserAndHost("user-1", 1)).toBe(false);
expect(await repo.findByUserAndHost("user-1", 1)).toBeNull();
expect(writeCount).toBe(2);
});
it("deletes tokens by user id", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
expect(await repo.deleteByUserId("user-1")).toBe(2);
expect(await repo.deleteByUserId("user-1")).toBe(0);
expect(await repo.findByUserAndHost("user-1", 1)).toBeNull();
expect(await repo.findByUserAndHost("user-2", 3)).not.toBeNull();
expect(writeCount).toBe(1);
});
});
@@ -1,117 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { PluginInstallCountRepository } from "../../../database/repositories/plugin-install-count-repository.js";
describe("PluginInstallCountRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<PluginInstallCountRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
return new PluginInstallCountRepository(context, onWrite);
}
it("inserts a count on first upsert", async () => {
let writes = 0;
const repo = await createRepository(() => {
writes += 1;
});
const created = await repo.upsert({
pluginId: "plugin-a",
registryId: "registry-official",
count: 42,
source: "github-releases",
});
expect(created).toMatchObject({
pluginId: "plugin-a",
registryId: "registry-official",
count: 42,
source: "github-releases",
});
expect(writes).toBe(1);
});
it("updates the existing row on a repeat upsert for the same plugin/registry pair", async () => {
let writes = 0;
const repo = await createRepository(() => {
writes += 1;
});
const first = await repo.upsert({
pluginId: "plugin-a",
registryId: "registry-official",
count: 10,
});
const second = await repo.upsert({
pluginId: "plugin-a",
registryId: "registry-official",
count: 25,
});
expect(second.id).toBe(first.id);
expect(second.count).toBe(25);
expect(writes).toBe(2);
const rows = await repo.listByPlugin("plugin-a");
expect(rows).toHaveLength(1);
});
it("keeps counts from different registries for the same plugin separate", async () => {
const repo = await createRepository();
await repo.upsert({
pluginId: "plugin-a",
registryId: "registry-official",
count: 10,
});
await repo.upsert({
pluginId: "plugin-a",
registryId: "registry-community",
count: 5,
});
const rows = await repo.listByPlugin("plugin-a");
expect(rows.map((r) => r.registryId).sort()).toEqual([
"registry-community",
"registry-official",
]);
expect(
await repo.findByPluginAndRegistry("plugin-a", "registry-official"),
).toMatchObject({ count: 10 });
expect(
await repo.findByPluginAndRegistry("plugin-a", "missing-registry"),
).toBeNull();
});
it("deletes all counts for a plugin", async () => {
const repo = await createRepository();
await repo.upsert({
pluginId: "plugin-a",
registryId: "registry-official",
count: 10,
});
await repo.upsert({
pluginId: "plugin-a",
registryId: "registry-community",
count: 5,
});
expect(await repo.deleteByPlugin("plugin-a")).toBe(2);
expect(await repo.listByPlugin("plugin-a")).toEqual([]);
expect(await repo.deleteByPlugin("plugin-a")).toBe(0);
});
});
@@ -1,128 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { PluginRegistryRepository } from "../../../database/repositories/plugin-registry-repository.js";
describe("PluginRegistryRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<PluginRegistryRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
return new PluginRegistryRepository(context, onWrite);
}
it("creates, finds, and lists registries", async () => {
const repo = await createRepository();
await repo.create({
id: "registry-official",
name: "Official Registry",
url: "https://plugins.termix.site/index.json",
kind: "official",
});
await repo.create({
id: "registry-custom",
name: "Custom Registry",
url: "https://example.com/index.json",
});
const found = await repo.findById("registry-official");
expect(found).toMatchObject({
id: "registry-official",
name: "Official Registry",
kind: "official",
enabled: true,
});
const custom = await repo.findById("registry-custom");
expect(custom).toMatchObject({ kind: "community", enabled: true });
const all = await repo.listAll();
expect(all.map((r) => r.id).sort()).toEqual([
"registry-custom",
"registry-official",
]);
expect(await repo.findById("missing")).toBeNull();
});
it("updates only the provided fields", async () => {
let writes = 0;
const repo = await createRepository(() => {
writes += 1;
});
await repo.create({
id: "registry-custom",
name: "Custom Registry",
url: "https://example.com/index.json",
});
expect(writes).toBe(1);
const updated = await repo.update("registry-custom", {
enabled: false,
lastCheckedAt: "2026-01-01T00:00:00.000Z",
lastIndexHash: "abc123",
});
expect(updated).toMatchObject({
id: "registry-custom",
name: "Custom Registry",
enabled: false,
lastCheckedAt: "2026-01-01T00:00:00.000Z",
lastIndexHash: "abc123",
});
expect(writes).toBe(2);
expect(await repo.update("missing", { enabled: false })).toBeNull();
expect(writes).toBe(2);
});
it("deletes a registry and reports whether a row was removed", async () => {
let writes = 0;
const repo = await createRepository(() => {
writes += 1;
});
await repo.create({
id: "registry-custom",
name: "Custom Registry",
url: "https://example.com/index.json",
});
expect(writes).toBe(1);
expect(await repo.delete("missing")).toBe(false);
expect(writes).toBe(1);
expect(await repo.delete("registry-custom")).toBe(true);
expect(writes).toBe(2);
expect(await repo.findById("registry-custom")).toBeNull();
});
it("deletes all registries and returns the count removed", async () => {
const repo = await createRepository();
await repo.create({
id: "registry-a",
name: "A",
url: "https://a.example.com/index.json",
});
await repo.create({
id: "registry-b",
name: "B",
url: "https://b.example.com/index.json",
});
expect(await repo.deleteAll()).toBe(2);
expect(await repo.listAll()).toEqual([]);
expect(await repo.deleteAll()).toBe(0);
});
});
@@ -0,0 +1,117 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { sql } from "drizzle-orm";
import { readFileSync } from "node:fs";
import { TestSqliteDatabase, testDialect } from "./test-support.js";
import { PluginSettingsRepository } from "../../../database/repositories/plugin-settings-repository.js";
describe("PluginSettingsRepository", () => {
let adapter: TestSqliteDatabase;
let repo: PluginSettingsRepository;
const pluginId = "p".repeat(255);
beforeEach(async () => {
adapter = new TestSqliteDatabase();
repo = new PluginSettingsRepository(await adapter.connect());
await adapter.run(sql`
INSERT INTO plugins (id, name, version, manifest_json)
VALUES (${pluginId}, 'Settings test', '1.0.0', '{}')
`);
});
afterEach(async () => {
await adapter.close();
});
it("round-trips every supported scope and updates admin settings", async () => {
for (const scope of ["admin", "user", "host", "secret"] as const) {
const scopeId = scope === "admin" ? null : "42";
await repo.set(pluginId, scope, scopeId, "shared-key", scope);
expect(
await repo.get(pluginId, scope, scopeId, "shared-key"),
).toMatchObject({
scope,
value: scope,
});
}
await repo.set(pluginId, "admin", null, "shared-key", "updated");
expect(await repo.getAll(pluginId, "admin", null)).toHaveLength(1);
expect(await repo.get(pluginId, "admin", null, "shared-key")).toMatchObject(
{
value: "updated",
},
);
});
it("preserves full-length Unicode identifiers and distinct key suffixes", async () => {
const scopeId = "\u{1f511}".repeat(255);
const prefix = "\u{1f511}".repeat(254);
await repo.set(pluginId, "user", scopeId, `${prefix}a`, "first");
await repo.set(pluginId, "user", scopeId, `${prefix}b`, "second");
expect(await repo.getAll(pluginId, "user", scopeId)).toHaveLength(2);
expect(
await repo.get(pluginId, "user", scopeId, `${prefix}a`),
).toMatchObject({
value: "first",
});
expect(
await repo.get(pluginId, "user", scopeId, `${prefix}b`),
).toMatchObject({
value: "second",
});
});
it("still rejects duplicate non-null scope keys at the database boundary", async () => {
await repo.set(pluginId, "host", "42", "setting", "original");
await expect(
adapter.run(sql`
INSERT INTO plugin_settings (plugin_id, scope, scope_id, ${sql.identifier("key")}, value)
VALUES (${pluginId}, 'host', '42', 'setting', 'duplicate')
`),
).rejects.toThrow();
expect(await repo.get(pluginId, "host", "42", "setting")).toMatchObject({
value: "original",
});
});
it.runIf(testDialect() === "mysql")(
"preserves existing settings through the enum upgrade",
async () => {
const migrationDir = new URL(
"../../../../../drizzle/mysql/",
import.meta.url,
);
const create = readFileSync(
new URL("0029_open_captain_america.sql", migrationDir),
"utf8",
)
.split("--> statement-breakpoint")[0]
.replace("`plugin_settings`", "`plugin_settings_upgrade_test`")
.replace("enum('admin','user','host','secret')", "varchar(255)")
.replace(/\);\s*$/, ") DEFAULT CHARSET=utf8mb3;");
const upgrade = readFileSync(
new URL("0061_plugin_settings_scope_enum.sql", migrationDir),
"utf8",
).replace("`plugin_settings`", "`plugin_settings_upgrade_test`");
await adapter.run(sql.raw(create));
try {
for (const scope of ["admin", "user", "host", "secret"]) {
await adapter.run(sql`
INSERT INTO plugin_settings_upgrade_test (plugin_id, scope, scope_id, ${sql.identifier("key")}, value, encrypted)
VALUES (${pluginId}, ${scope}, ${scope === "admin" ? null : "42"}, 'setting', ${scope}, true)
`);
}
const before = await adapter.query(
sql`SELECT * FROM plugin_settings_upgrade_test ORDER BY id`,
);
await adapter.run(sql.raw(upgrade));
expect(
await adapter.query(
sql`SELECT * FROM plugin_settings_upgrade_test ORDER BY id`,
),
).toEqual(before);
} finally {
await adapter.run(sql`DROP TABLE plugin_settings_upgrade_test`);
}
},
);
});
@@ -0,0 +1,96 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { PluginStorageRepository } from "../../../database/repositories/plugin-storage-repository.js";
describe("PluginStorageRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<PluginStorageRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO plugins (id, name, version, manifest_json)
VALUES ('plugin-a', 'Plugin A', '1.0.0', '{}');
INSERT INTO plugins (id, name, version, manifest_json)
VALUES ('plugin-b', 'Plugin B', '1.0.0', '{}');
`);
return new PluginStorageRepository(context, onWrite);
}
it("round-trips a value", async () => {
const repo = await createRepository();
expect(await repo.get("plugin-a", "missing")).toBeNull();
await repo.set("plugin-a", "token", '{"v":1}');
expect(await repo.get("plugin-a", "token")).toBe('{"v":1}');
});
it("overwrites rather than duplicating an existing key", async () => {
const repo = await createRepository();
await repo.set("plugin-a", "counter", "1");
await repo.set("plugin-a", "counter", "2");
expect(await repo.get("plugin-a", "counter")).toBe("2");
expect(await repo.listKeys("plugin-a")).toEqual(["counter"]);
});
it("keeps each plugin's keys separate", async () => {
const repo = await createRepository();
await repo.set("plugin-a", "shared-key", "from-a");
await repo.set("plugin-b", "shared-key", "from-b");
expect(await repo.get("plugin-a", "shared-key")).toBe("from-a");
expect(await repo.get("plugin-b", "shared-key")).toBe("from-b");
});
it("deletes a key and reports whether a row changed", async () => {
let writes = 0;
const repo = await createRepository(() => {
writes += 1;
});
await repo.set("plugin-a", "k", "v");
expect(writes).toBe(1);
expect(await repo.delete("plugin-a", "nope")).toBe(false);
expect(writes).toBe(1);
expect(await repo.delete("plugin-a", "k")).toBe(true);
expect(writes).toBe(2);
expect(await repo.get("plugin-a", "k")).toBeNull();
});
it("deletes everything belonging to one plugin", async () => {
const repo = await createRepository();
await repo.set("plugin-a", "one", "1");
await repo.set("plugin-a", "two", "2");
await repo.set("plugin-b", "keep", "3");
expect(await repo.deleteByPlugin("plugin-a")).toBe(2);
expect(await repo.listKeys("plugin-a")).toEqual([]);
expect(await repo.listKeys("plugin-b")).toEqual(["keep"]);
});
it("drops rows when the owning plugin is removed", async () => {
const repo = await createRepository();
await repo.set("plugin-a", "k", "v");
await adapter!.exec(`DELETE FROM plugins WHERE id = 'plugin-a';`);
expect(await repo.listKeys("plugin-a")).toEqual([]);
});
});
@@ -1,80 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { ProxmoxNodeHistoryRepository } from "../../../database/repositories/proxmox-node-history-repository.js";
describe("ProxmoxNodeHistoryRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<ProxmoxNodeHistoryRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash) VALUES
('user-1', 'user-1', 'hash'),
('user-2', 'user-2', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'user-1', 'pve1', '10.0.0.1', 22, 'root', 'password'), (2, 'user-2', 'pve2', '10.0.0.2', 22, 'root', 'password');
INSERT INTO proxmox_node_history (
host_id, ts, cpu_percent, mem_percent, disk_percent, net_rx_bytes, net_tx_bytes
)
VALUES
(1, '2026-01-01 00:00:00', 10, 20, 30, 100, 200),
(1, '2026-01-02 00:00:00', 11, 21, 31, 101, 201),
(1, '2999-01-01 00:00:00', 12, 22, 32, 102, 202),
(2, '2026-01-02 00:00:00', 99, 99, 99, 999, 999);
`);
return new ProxmoxNodeHistoryRepository(context, onWrite);
}
it("creates and lists node history rows by range", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.create({
hostId: 1,
cpuPercent: 12,
memPercent: 22,
diskPercent: 32,
netRxBytes: 102,
netTxBytes: 202,
});
const rows = await repo.listRange(
1,
"2026-01-01 00:00:00",
"2026-01-02 23:59:59",
);
expect(rows.map((row) => row.cpuPercent)).toEqual([10, 11]);
expect(writeCount).toBe(1);
});
it("prunes old history for a host only", async () => {
const repo = await createRepository();
await repo.pruneOlderThan(1, 1);
const rows = await repo.listRange(
1,
"2000-01-01 00:00:00",
"2999-12-31 23:59:59",
);
expect(rows.map((row) => row.ts)).toEqual(["2999-01-01 00:00:00"]);
expect(
await repo.listRange(2, "2026-01-01 00:00:00", "2026-01-03 00:00:00"),
).toHaveLength(1);
});
});
@@ -36,12 +36,8 @@ describe("RbacAccessRepository", () => {
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type) VALUES
(44, 'admin', 'host-44', '10.0.0.45', 22, 'root', 'password');
INSERT INTO ssh_data (
id, user_id, name, ip, port, username, credential_id, rdp_credential_id, vnc_credential_id, telnet_credential_id, folder, tags, auth_type)
VALUES (42, 'owner-1', 'prod', '10.0.0.42', 22, 'root', 123, 124, 125, 126, 'servers', 'linux', 'password');
INSERT INTO snippets (id, user_id, name, content)
VALUES
(99, 'owner-1', 'deploy', 'echo deploy'),
(100, 'owner-1', 'rollback', 'echo rollback');
id, user_id, name, ip, port, username, credential_id, folder, tags, auth_type)
VALUES (42, 'owner-1', 'prod', '10.0.0.42', 22, 'root', 123, 'servers', 'linux', 'password');
INSERT INTO host_access (
id, host_id, user_id, role_id, granted_by, permission_level, expires_at, created_at
)
@@ -49,12 +45,6 @@ describe("RbacAccessRepository", () => {
(1, 42, 'user-1', NULL, 'admin', 'view', NULL, '2026-06-26T00:00:00.000Z'),
(2, 42, NULL, 7, 'admin', 'view', '2026-06-27T00:00:00.000Z', '2026-06-26T01:00:00.000Z'),
(5, 44, 'user-1', NULL, 'admin', 'view', '2026-06-25T00:00:00.000Z', '2026-06-24T00:00:00.000Z');
INSERT INTO snippet_access (
id, snippet_id, user_id, role_id, granted_by, permission_level, expires_at, created_at
)
VALUES
(3, 99, 'user-1', NULL, 'admin', 'view', NULL, '2026-06-26T00:00:00.000Z'),
(4, 99, NULL, 7, 'admin', 'view', '2026-06-27T00:00:00.000Z', '2026-06-26T01:00:00.000Z');
INSERT INTO shared_host_secrets (
id, host_access_id, target_user_id, protocol, source_type, original_credential_id, encrypted_username, encrypted_auth_type
)
@@ -95,29 +85,6 @@ describe("RbacAccessRepository", () => {
]);
});
it("lists snippet access with user and role target metadata", async () => {
const repo = await createRepository();
const accessList = await repo.listSnippetAccess(99);
expect(accessList.map((access) => access.targetType)).toEqual([
"role",
"user",
]);
expect(accessList[0]).toMatchObject({
id: 4,
roleId: 7,
roleName: "ops",
grantedByUsername: "admin",
});
expect(accessList[1]).toMatchObject({
id: 3,
userId: "user-1",
username: "alice",
grantedByUsername: "admin",
});
});
it("lists shared hosts for direct and role access", async () => {
const repo = await createRepository();
@@ -171,9 +138,6 @@ describe("RbacAccessRepository", () => {
{
hostAccessId: 2,
credentialId: 123,
rdpCredentialId: 124,
vncCredentialId: 125,
telnetCredentialId: 126,
hostId: 42,
hostOwnerId: "owner-1",
},
@@ -253,67 +217,6 @@ describe("RbacAccessRepository", () => {
expect(writeCount).toBe(1);
});
it("lists shared snippets and preserves route-level direct-over-role behavior", async () => {
const repo = await createRepository();
const sharedSnippets = await repo.listSharedSnippets(
"user-1",
[7],
activeAccessTime,
);
expect(sharedSnippets).toHaveLength(1);
expect(sharedSnippets[0]).toMatchObject({
id: 99,
name: "deploy",
ownerUsername: "owner",
permissionLevel: "view",
});
});
it("lists visible shared snippets for the main snippets route", async () => {
const repo = await createRepository();
const sharedSnippets = await repo.listVisibleSharedSnippets(
"user-1",
[7],
activeAccessTime,
);
expect(sharedSnippets.map((snippet) => snippet.id)).toEqual([99, 99]);
expect(sharedSnippets[0]).toMatchObject({
userId: "owner-1",
name: "deploy",
content: "echo deploy",
ownerUsername: "owner",
});
});
it("finds an accessible shared snippet for direct or role access", async () => {
const repo = await createRepository();
await expect(
repo.findAccessibleSharedSnippet(99, "user-2", [7], activeAccessTime),
).resolves.toMatchObject({
id: 99,
userId: "owner-1",
name: "deploy",
content: "echo deploy",
ownerUsername: "owner",
permissionLevel: "view",
hostFilter: null,
});
await expect(
repo.findAccessibleSharedSnippet(
99,
"user-2",
[7],
"2026-06-28T00:00:00.000Z",
),
).resolves.toBeNull();
});
it("upserts host access and updates overrides", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
@@ -432,39 +335,4 @@ describe("RbacAccessRepository", () => {
expect(await repo.deleteHostAccessForUserReferences("admin")).toBe(0);
expect(writeCount).toBe(1);
});
it("upserts and revokes snippet access", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const updated = await repo.upsertSnippetAccess({
snippetId: 99,
targetType: "user",
targetUserId: "user-1",
grantedBy: "admin",
expiresAt: "2026-06-28T00:00:00.000Z",
});
expect(updated).toEqual({ id: 3, created: false });
expect(
(await repo.listSnippetAccess(99)).find((row) => row.id === 3),
).toMatchObject({ expiresAt: "2026-06-28T00:00:00.000Z" });
const created = await repo.upsertSnippetAccess({
snippetId: 100,
targetType: "role",
targetRoleId: 7,
grantedBy: "admin",
expiresAt: null,
});
expect(created.created).toBe(true);
await repo.revokeSnippetAccess(3, 99);
expect((await repo.listSnippetAccess(99)).map((row) => row.id)).toEqual([
4,
]);
expect(writeCount).toBe(3);
});
});
@@ -1,139 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { SessionRecordingRepository } from "../../../database/repositories/session-recording-repository.js";
describe("SessionRecordingRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<SessionRecordingRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'user-1', 'one', '10.0.0.1', 22, 'root', 'password'), (2, 'user-1', 'two', '10.0.0.2', 22, 'root', 'password'), (3, 'user-2', 'other', '10.0.0.3', 22, 'root', 'password');
`);
return new SessionRecordingRepository(context, onWrite);
}
it("creates and lists session recordings with host metadata", async () => {
const repo = await createRepository();
const first = await repo.create({
userId: "user-1",
hostId: 1,
startedAt: "2026-06-27T00:00:00.000Z",
endedAt: "2026-06-27T00:01:00.000Z",
duration: 60,
recordingPath: "/tmp/one.log",
});
await repo.create({
userId: "user-1",
hostId: 2,
startedAt: "2026-06-27T00:02:00.000Z",
recordingPath: "/tmp/two.log",
});
await repo.create({
userId: "user-2",
hostId: 3,
startedAt: "2026-06-27T00:03:00.000Z",
});
expect(first).toMatchObject({
userId: "user-1",
hostId: 1,
duration: 60,
recordingPath: "/tmp/one.log",
});
const rows = await repo.listByUserIdWithHost("user-1");
expect(rows.map((row) => row.hostName)).toEqual(["two", "one"]);
expect(rows[0]).toMatchObject({
hostIp: "10.0.0.2",
recordingPath: "/tmp/two.log",
protocol: "ssh",
format: "text",
});
});
it("finds paths and prunes old recordings", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const old = await repo.create({
userId: "user-1",
hostId: 1,
startedAt: "2026-01-01T00:00:00.000Z",
recordingPath: "/tmp/old.log",
});
const current = await repo.create({
userId: "user-1",
hostId: 1,
startedAt: "2026-06-27T00:00:00.000Z",
recordingPath: "/tmp/current.log",
});
expect(writeCount).toBe(2);
expect(await repo.findPathByIdForUser("user-2", old.id)).toBeNull();
expect(await repo.findPathByIdForUser("user-1", old.id)).toMatchObject({
recordingPath: "/tmp/old.log",
});
expect(await repo.listPathsOlderThan("2026-02-01T00:00:00.000Z")).toEqual([
{ id: old.id, recordingPath: "/tmp/old.log" },
]);
expect(await repo.deleteById(old.id)).toBe(true);
expect(await repo.deleteById(old.id)).toBe(false);
expect(await repo.findByIdForUser("user-1", current.id)).toMatchObject({
id: current.id,
});
expect(writeCount).toBe(3);
});
it("deletes recordings by user and host references", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const first = await repo.create({
userId: "user-1",
hostId: 1,
startedAt: "2026-06-27T00:00:00.000Z",
});
await repo.create({
userId: "user-1",
hostId: 2,
startedAt: "2026-06-27T00:01:00.000Z",
});
await repo.create({
userId: "user-2",
hostId: 3,
startedAt: "2026-06-27T00:02:00.000Z",
});
expect(writeCount).toBe(3);
expect(await repo.deleteForUser("user-2", first.id)).toBe(false);
expect(await repo.deleteForUser("user-1", first.id)).toBe(true);
expect(await repo.deleteByHostIds([])).toBe(0);
expect(await repo.deleteByHostIds([2])).toBe(1);
expect(writeCount).toBe(5);
expect(await repo.deleteByUserId("user-2")).toBe(1);
expect(await repo.deleteByHostId(3)).toBe(0);
expect(writeCount).toBe(6);
});
});
@@ -1,353 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { SessionShareRepository } from "../../../database/repositories/session-share-repository.js";
describe("SessionShareRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<SessionShareRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('owner-1', 'alice', 'hash'), ('guest-1', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'owner-1', 'host-one', '10.0.0.1', 22, 'root', 'password'), (2, 'owner-1', 'host-two', '10.0.0.2', 22, 'root', 'password');
`);
return new SessionShareRepository(context, onWrite);
}
const FAR_FUTURE = "2999-01-01T00:00:00.000Z";
const FAR_PAST = "2000-01-01T00:00:00.000Z";
it("creates a share and finds it by id", async () => {
const repo = await createRepository();
const created = await repo.create({
id: "share-1",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "link",
linkToken: "token-abc",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
expect(created).toMatchObject({
id: "share-1",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
linkToken: "token-abc",
permissionLevel: "read-only",
});
const found = await repo.findById("share-1");
expect(found).toMatchObject({ id: "share-1", sessionId: "session-1" });
});
it("findByLinkToken excludes revoked shares", async () => {
const repo = await createRepository();
await repo.create({
id: "share-revoked",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "link",
linkToken: "token-revoked",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
expect(await repo.findByLinkToken("token-revoked")).not.toBeNull();
await repo.revoke("share-revoked", "owner-1");
expect(await repo.findByLinkToken("token-revoked")).toBeNull();
});
it("findByLinkToken excludes expired shares", async () => {
const repo = await createRepository();
await repo.create({
id: "share-expired",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "link",
linkToken: "token-expired",
permissionLevel: "read-only",
expiresAt: FAR_PAST,
});
expect(await repo.findByLinkToken("token-expired")).toBeNull();
});
it("findByLinkToken returns active, non-expired, non-revoked shares", async () => {
const repo = await createRepository();
await repo.create({
id: "share-active",
hostId: 1,
ownerUserId: "owner-1",
protocol: "vnc",
sessionId: "guac-session-1",
shareType: "link",
linkToken: "token-active",
permissionLevel: "read-write",
expiresAt: FAR_FUTURE,
});
const found = await repo.findByLinkToken("token-active");
expect(found).toMatchObject({
id: "share-active",
protocol: "vnc",
permissionLevel: "read-write",
});
});
it("findSharesTargetingUser returns only active user-targeted shares with host/owner metadata", async () => {
const repo = await createRepository();
await repo.create({
id: "share-user-active",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "user",
targetUserId: "guest-1",
permissionLevel: "read-write",
expiresAt: FAR_FUTURE,
});
// Expired user share for the same target - must be excluded
await repo.create({
id: "share-user-expired",
hostId: 2,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-2",
shareType: "user",
targetUserId: "guest-1",
permissionLevel: "read-only",
expiresAt: FAR_PAST,
});
// Link share, not targeting a user - must be excluded even though it's active
await repo.create({
id: "share-link-active",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-3",
shareType: "link",
linkToken: "token-unrelated",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
const shares = await repo.findSharesTargetingUser("guest-1");
expect(shares).toHaveLength(1);
expect(shares[0]).toMatchObject({
id: "share-user-active",
hostName: "host-one",
ownerUsername: "alice",
});
});
it("revoke only affects the requesting owner's own share", async () => {
const repo = await createRepository();
await repo.create({
id: "share-owned",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "link",
linkToken: "token-owned",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
expect(await repo.revoke("share-owned", "guest-1")).toBe(false);
expect(await repo.revoke("share-owned", "owner-1")).toBe(true);
});
it("revokeAsAdmin revokes regardless of owner", async () => {
const repo = await createRepository();
await repo.create({
id: "share-admin-target",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "link",
linkToken: "token-admin",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
expect(await repo.revokeAsAdmin("share-admin-target")).toBe(true);
expect(await repo.findByLinkToken("token-admin")).toBeNull();
});
it("deleteExpiredShares removes only expired rows", async () => {
const repo = await createRepository();
await repo.create({
id: "share-old",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "link",
linkToken: "token-old",
permissionLevel: "read-only",
expiresAt: FAR_PAST,
});
await repo.create({
id: "share-current",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-2",
shareType: "link",
linkToken: "token-current",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
const deletedCount = await repo.deleteExpiredShares();
expect(deletedCount).toBe(1);
expect(await repo.findById("share-old")).toBeNull();
expect(await repo.findById("share-current")).not.toBeNull();
});
it("touchShareUsage increments joinCount and sets lastJoinedAt", async () => {
const repo = await createRepository();
await repo.create({
id: "share-touch",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "link",
linkToken: "token-touch",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
await repo.touchShareUsage("share-touch", "2026-01-01T00:00:00.000Z");
let row = await repo.findById("share-touch");
expect(row?.joinCount).toBe(1);
expect(row?.lastJoinedAt).toBe("2026-01-01T00:00:00.000Z");
await repo.touchShareUsage("share-touch", "2026-01-02T00:00:00.000Z");
row = await repo.findById("share-touch");
expect(row?.joinCount).toBe(2);
});
it("records and closes participant joins", async () => {
const repo = await createRepository();
await repo.create({
id: "share-participants",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "link",
linkToken: "token-participants",
permissionLevel: "read-write",
expiresAt: FAR_FUTURE,
});
const participant = await repo.recordParticipantJoin(
"share-participants",
null,
"Guest",
);
expect(participant).toMatchObject({
shareId: "share-participants",
userId: null,
guestLabel: "Guest",
});
expect(participant.leftAt).toBeNull();
await repo.recordParticipantLeave(participant.id);
});
it("write hook fires on mutating operations", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.create({
id: "share-write-hook",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "link",
linkToken: "token-write-hook",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
expect(writeCount).toBe(1);
await repo.revoke("share-write-hook", "owner-1");
expect(writeCount).toBe(2);
});
it("deleteSharesForHost removes all shares for a host", async () => {
const repo = await createRepository();
await repo.create({
id: "share-host-1a",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-1",
shareType: "link",
linkToken: "token-h1a",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
await repo.create({
id: "share-host-1b",
hostId: 1,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-2",
shareType: "link",
linkToken: "token-h1b",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
await repo.create({
id: "share-host-2",
hostId: 2,
ownerUserId: "owner-1",
protocol: "ssh",
sessionId: "session-3",
shareType: "link",
linkToken: "token-h2",
permissionLevel: "read-only",
expiresAt: FAR_FUTURE,
});
expect(await repo.deleteSharesForHost(1)).toBe(2);
expect(await repo.findById("share-host-2")).not.toBeNull();
});
});
@@ -31,10 +31,13 @@ describe("SharedHostSecretsRepository", () => {
INSERT INTO ssh_credentials (id, user_id, name, username, auth_type) VALUES
(123, 'user-1', 'cred-123', 'root', 'password'),
(124, 'user-1', 'cred-124', 'root', 'password');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, credential_id, rdp_credential_id, auth_type)
VALUES (42, 'owner-1', 'prod', '10.0.0.42', 22, 'root', 123, 124, 'password'),
(43, 'owner-1', 'staging', '10.0.0.43', 22, 'root', NULL, NULL, 'password'),
(44, 'owner-2', 'other', '10.0.0.44', 22, 'root', 123, NULL, 'password');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, credential_id, auth_type)
VALUES (42, 'owner-1', 'prod', '10.0.0.42', 22, 'root', 123, 'password'),
(43, 'owner-1', 'staging', '10.0.0.43', 22, 'root', NULL, 'password'),
(44, 'owner-2', 'other', '10.0.0.44', 22, 'root', 123, 'password');
INSERT INTO host_protocol_auth (host_id, user_id, protocol, auth_type, credential_id)
VALUES (42, 'owner-1', 'spice', 'credential', 124),
(43, 'owner-1', 'spice', 'direct', NULL);
INSERT INTO host_access (id, host_id, user_id, role_id, granted_by)
VALUES
(1, 42, 'user-1', NULL, 'owner-1'),
@@ -1,356 +0,0 @@
import { sql } from "drizzle-orm";
import { afterEach, describe, expect, it, vi } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { SnippetRepository } from "../../../database/repositories/snippet-repository.js";
describe("SnippetRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(onWrite?: () => void): Promise<{
repository: SnippetRepository;
}> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash) VALUES
('user-1', 'user-1', 'hash'),
('user-2', 'user-2', 'hash');
INSERT INTO snippets (
id, user_id, name, content, description, folder, "order", host_filter
)
VALUES
(1, 'user-1', 'root', 'uptime', NULL, NULL, 2, NULL),
(2, 'user-1', 'deploy', 'make deploy', 'Deploy app', 'ops', 1, 'linux'),
(3, 'user-2', 'other', 'whoami', NULL, NULL, 1, NULL);
INSERT INTO snippet_folders (id, user_id, name, color, icon)
VALUES
(1, 'user-1', 'ops', '#123456', 'terminal'),
(2, 'user-1', 'db', NULL, NULL),
(3, 'user-2', 'other', NULL, NULL);
`);
return {
repository: new SnippetRepository(context, onWrite),
};
}
it("finds owned snippets only", async () => {
const { repository } = await createRepository();
await expect(repository.findOwnedById("user-1", 1)).resolves.toMatchObject({
id: 1,
userId: "user-1",
name: "root",
});
await expect(repository.findOwnedById("user-1", 3)).resolves.toBeNull();
await expect(repository.findOwnedById("user-1", 999)).resolves.toBeNull();
});
it("lists folders by name for a user", async () => {
const { repository } = await createRepository();
const rows = await repository.listFolders("user-1");
expect(rows.map((row) => row.name)).toEqual(["db", "ops"]);
});
it("lists export data for a user", async () => {
const { repository } = await createRepository();
const snippets = await repository.listSnippetsForExport("user-1");
const folders = await repository.listFoldersForExport("user-1");
expect(snippets.map((row) => row.name)).toEqual(["root", "deploy"]);
expect(folders.map((row) => row.name)).toEqual(["db", "ops"]);
});
it("lists owned snippets for route merging", async () => {
const { repository } = await createRepository();
const rows = await repository.listOwnedSnippets("user-1");
expect(rows.map((row) => row.name)).toEqual(["root", "deploy"]);
});
it("reorders snippets", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
await repository.reorderSnippets("user-1", [
{ id: 1, order: 9, folder: " ops " },
{ id: 999, order: 1 },
]);
await expect(repository.findOwnedById("user-1", 1)).resolves.toMatchObject({
order: 9,
folder: "ops",
});
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("creates snippets with the next folder order", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
const created = await repository.createSnippet("user-1", {
name: " new ",
content: " echo ok ",
description: " desc ",
folder: "ops",
hostFilter: { os: "linux" },
});
expect(created).toMatchObject({
userId: "user-1",
name: "new",
content: "echo ok",
description: "desc",
folder: "ops",
order: 2,
hostFilter: JSON.stringify({ os: "linux" }),
});
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("updates snippets and returns the original row for audit names", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
const result = await repository.updateSnippet("user-1", 2, {
name: " deploy new ",
content: " make deploy2 ",
description: null,
folder: null,
order: 7,
hostFilter: null,
});
const missing = await repository.updateSnippet("user-1", 3, {
name: "nope",
});
expect(result?.existing).toMatchObject({ name: "deploy" });
expect(result?.updated).toMatchObject({
name: "deploy new",
content: "make deploy2",
description: null,
folder: null,
order: 7,
hostFilter: null,
});
expect(missing).toBeNull();
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("deletes snippets and returns the deleted row for audit names", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
const deleted = await repository.deleteSnippet("user-1", 2);
const missing = await repository.deleteSnippet("user-1", 3);
expect(deleted).toMatchObject({ id: 2, name: "deploy" });
expect(missing).toBeNull();
await expect(repository.findOwnedById("user-1", 2)).resolves.toBeNull();
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("deletes all snippets and folders for a user", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
await expect(repository.deleteByUserId("user-1")).resolves.toEqual({
snippetsDeleted: 2,
foldersDeleted: 2,
});
expect(
await adapter!.query(sql`SELECT id FROM snippets ORDER BY id`),
).toEqual([{ id: 3 }]);
expect(
await adapter!.query(sql`SELECT id FROM snippet_folders ORDER BY id`),
).toEqual([{ id: 3 }]);
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("bulk imports folders and snippets", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
const result = await repository.bulkImport(
"user-1",
[
{
name: " new snippet ",
content: " echo hi ",
description: " desc ",
folder: " new folder ",
hostFilter: "linux",
},
{ name: "", content: "bad" },
{ name: "deploy", content: "skip", folder: "ops" },
],
[
{ name: " new folder ", color: " #fff ", icon: " star " },
{ name: "ops" },
{ name: "" },
],
false,
);
expect(result).toEqual({
snippetsImported: 1,
snippetsSkipped: 1,
snippetsUpdated: 0,
foldersImported: 1,
foldersSkipped: 1,
failed: 2,
errors: [
"Folder missing name",
"Snippet 2: name and content are required",
],
});
await expect(repository.findOwnedById("user-1", 4)).resolves.toMatchObject({
name: "new snippet",
content: "echo hi",
description: "desc",
folder: "new folder",
order: 0,
hostFilter: "linux",
});
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("bulk import overwrites existing snippets", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
const result = await repository.bulkImport(
"user-1",
[
{
name: "deploy",
content: "make deploy v2",
folder: "ops",
order: 5,
hostFilter: "prod",
},
],
undefined,
true,
);
expect(result).toMatchObject({
snippetsImported: 0,
snippetsSkipped: 0,
snippetsUpdated: 1,
failed: 0,
});
await expect(repository.findOwnedById("user-1", 2)).resolves.toMatchObject({
content: "make deploy v2",
order: 5,
hostFilter: "prod",
});
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("creates folders and rejects duplicate names", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
const created = await repository.createFolder(
"user-1",
" new ",
" #fff ",
" star ",
);
const duplicate = await repository.createFolder(
"user-1",
"ops",
null,
null,
);
expect(created).toMatchObject({
userId: "user-1",
name: "new",
color: "#fff",
icon: "star",
});
expect(duplicate).toBeNull();
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("updates folder metadata", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
const updated = await repository.updateFolderMetadata(
"user-1",
"ops",
" #abc ",
undefined,
);
const missing = await repository.updateFolderMetadata(
"user-1",
"missing",
null,
null,
);
expect(updated).toMatchObject({
name: "ops",
color: "#abc",
icon: "terminal",
});
expect(missing).toBeNull();
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("renames folders and attached snippets", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
await expect(
repository.renameFolder("user-1", "missing", "new"),
).resolves.toEqual({ status: "missing" });
await expect(
repository.renameFolder("user-1", "ops", "db"),
).resolves.toEqual({
status: "conflict",
});
await expect(
repository.renameFolder("user-1", "ops", "deploys"),
).resolves.toEqual({ status: "renamed" });
await expect(repository.listFolders("user-1")).resolves.toEqual(
expect.arrayContaining([expect.objectContaining({ name: "deploys" })]),
);
await expect(repository.findOwnedById("user-1", 2)).resolves.toMatchObject({
folder: "deploys",
});
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("deletes folders and moves snippets to the root", async () => {
const onWrite = vi.fn();
const { repository } = await createRepository(onWrite);
await repository.deleteFolder("user-1", "ops");
expect(
(await repository.listFolders("user-1")).map((row) => row.name),
).toEqual(["db"]);
await expect(repository.findOwnedById("user-1", 2)).resolves.toMatchObject({
folder: null,
});
expect(onWrite).toHaveBeenCalledTimes(1);
});
});
@@ -1,104 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { SsoProviderRepository } from "../../../database/repositories/sso-provider-repository.js";
describe("SsoProviderRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<SsoProviderRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
return new SsoProviderRepository(context, onWrite);
}
it("creates, lists, finds, updates, and deletes providers", async () => {
const repo = await createRepository();
const disabled = await repo.create({
name: "Disabled",
type: "oidc",
enabled: false,
displayOrder: 1,
config: "{}",
});
const enabled = await repo.create({
name: "GitHub",
type: "github",
enabled: true,
displayOrder: 0,
config: '{"client_id":"id"}',
});
expect((await repo.listEnabledPublic()).map((row) => row.id)).toEqual([
enabled.id,
]);
expect((await repo.listAll()).map((row) => row.id)).toEqual([
enabled.id,
disabled.id,
]);
expect((await repo.findById(enabled.id))?.name).toBe("GitHub");
expect((await repo.findFirstEnabledOidcLike())?.id).toBe(enabled.id);
const updated = await repo.update(enabled.id, {
name: "GitHub SSO",
config: '{"client_id":"updated"}',
updatedAt: "2026-06-27T00:00:00.000Z",
});
expect(updated?.name).toBe("GitHub SSO");
expect(updated?.config).toContain("updated");
expect(await repo.delete(enabled.id)).toBe(true);
expect(await repo.findById(enabled.id)).toBeNull();
expect(await repo.delete(enabled.id)).toBe(false);
});
it("counts users associated with a provider", async () => {
const repo = await createRepository();
const provider = await repo.create({
name: "LDAP",
type: "ldap",
enabled: true,
displayOrder: 0,
config: "{}",
});
await adapter!.exec(`
INSERT INTO users (id, username, password_hash, sso_provider_id)
VALUES ('user-1', 'u1', 'hash', ${provider.id}),
('user-2', 'u2', 'hash', ${provider.id}),
('user-3', 'u3', 'hash', NULL);
`);
expect(await repo.countUsersByProviderId(provider.id)).toBe(2);
});
it("runs the write hook after provider writes", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const provider = await repo.create({
name: "OIDC",
type: "oidc",
enabled: true,
displayOrder: 0,
config: "{}",
});
await repo.update(provider.id, { enabled: false });
await repo.delete(provider.id);
await repo.delete(provider.id);
expect(writeCount).toBe(3);
});
});
@@ -1,109 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { SyncTombstoneRepository } from "../../../database/repositories/sync-tombstone-repository.js";
describe("SyncTombstoneRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<SyncTombstoneRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
`);
return new SyncTombstoneRepository(context, onWrite);
}
it("records a tombstone and lists it back for the owning user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.record("user-1", "hosts", "sync-abc");
expect(writeCount).toBe(1);
const rows = await repo.listSince("user-1", "hosts", null);
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
userId: "user-1",
entityType: "hosts",
syncId: "sync-abc",
});
});
it("does not record a tombstone for an empty syncId", async () => {
const repo = await createRepository();
await repo.record("user-1", "hosts", "");
const rows = await repo.listSince("user-1", "hosts", null);
expect(rows).toHaveLength(0);
});
it("recordMany writes multiple tombstones and filters out falsy ids", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.recordMany("user-1", "hosts", ["a", "", "b", "c"]);
expect(writeCount).toBe(1);
const rows = await repo.listSince("user-1", "hosts", null);
expect(rows.map((r) => r.syncId).sort()).toEqual(["a", "b", "c"]);
});
it("recordMany is a no-op when given no syncIds", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.recordMany("user-1", "hosts", []);
expect(writeCount).toBe(0);
});
it("scopes listSince by userId and entityType", async () => {
const repo = await createRepository();
await repo.record("user-1", "hosts", "sync-1");
await repo.record("user-1", "snippets", "sync-2");
await repo.record("user-2", "hosts", "sync-3");
const rows = await repo.listSince("user-1", "hosts", null);
expect(rows).toHaveLength(1);
expect(rows[0].syncId).toBe("sync-1");
});
it("filters listSince by the since timestamp", async () => {
const adapterLocal = new TestSqliteDatabase();
adapter = adapterLocal;
const context = await adapterLocal.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash');
INSERT INTO sync_tombstones (user_id, entity_type, sync_id, deleted_at)
VALUES
('user-1', 'hosts', 'old', '2026-01-01T00:00:00.000Z'),
('user-1', 'hosts', 'new', '2026-06-01T00:00:00.000Z');
`);
const repo = new SyncTombstoneRepository(context);
const rows = await repo.listSince(
"user-1",
"hosts",
"2026-03-01T00:00:00.000Z",
);
expect(rows).toHaveLength(1);
expect(rows[0].syncId).toBe("new");
});
});
@@ -1,111 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { SyncTombstoneRepository } from "../../../database/repositories/sync-tombstone-repository.js";
import {
normalizeSyncTimestamp,
timestampAtOrAfter,
} from "../../../database/sync-timestamp.js";
import { sshCredentials } from "../../../database/db/schema.js";
import type { DatabaseContext } from "../../../database/repositories/database-context.js";
import { and, eq } from "drizzle-orm";
// The desktop sync engine always sends its cursor as new Date().toISOString().
const ISO_CURSOR = "2026-07-29T09:00:00.000Z";
describe("sync cursors across timestamp layouts", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
/**
* The harness migrates the schema itself, so the seeds below are INSERTs into
* the real tables. Both `sync_tombstones.user_id` and `ssh_credentials.user_id`
* are foreign keys into `users`, which the harness enforces, so the owning row
* has to exist before either seed runs.
*/
async function connect(): Promise<{
db: TestSqliteDatabase;
context: DatabaseContext;
}> {
const db = new TestSqliteDatabase();
adapter = db;
const context = await db.connect();
await db.exec(`
INSERT INTO users (id, username, password_hash) VALUES
('user-1', 'user', 'hash');
`);
return { db, context };
}
it("normalizes both layouts to one comparable form", () => {
expect(normalizeSyncTimestamp("2026-07-29T10:11:21.123Z")).toBe(
"2026-07-29 10:11:21",
);
expect(normalizeSyncTimestamp("2026-07-29 10:11:21")).toBe(
"2026-07-29 10:11:21",
);
});
it("returns tombstones recorded after an ISO cursor, whatever layout they were stored in", async () => {
const { db, context } = await connect();
await db.exec(`
INSERT INTO sync_tombstones (user_id, entity_type, sync_id, deleted_at) VALUES
('user-1', 'sshCredentials', 'sqlite-layout', '2026-07-29 10:07:32'),
('user-1', 'sshCredentials', 'iso-layout', '2026-07-29T10:07:32.500Z'),
('user-1', 'sshCredentials', 'too-old', '2026-07-29 08:00:00');
`);
const repo = new SyncTombstoneRepository(context);
const rows = await repo.listSince("user-1", "sshCredentials", ISO_CURSOR);
expect(rows.map((row) => row.syncId).sort()).toEqual([
"iso-layout",
"sqlite-layout",
]);
});
it("returns rows written by CURRENT_TIMESTAMP against an ISO cursor", async () => {
const { db, context } = await connect();
await db.exec(`
INSERT INTO ssh_credentials (user_id, name, auth_type, updated_at) VALUES
('user-1', 'newer-sqlite-layout', 'password', '2026-07-29 10:11:21'),
('user-1', 'newer-iso-layout', 'password', '2026-07-29T10:11:21.123Z'),
('user-1', 'older', 'password', '2026-07-29 08:59:59');
`);
const rows = await context.drizzle
.select({ name: sshCredentials.name })
.from(sshCredentials)
.where(
and(
eq(sshCredentials.userId, "user-1"),
timestampAtOrAfter(sshCredentials.updatedAt, ISO_CURSOR),
),
);
expect(rows.map((row) => row.name).sort()).toEqual([
"newer-iso-layout",
"newer-sqlite-layout",
]);
});
it("keeps rows written in the same second as the cursor", async () => {
const { db, context } = await connect();
await db.exec(`
INSERT INTO ssh_credentials (user_id, name, auth_type, updated_at)
VALUES ('user-1', 'same-second', 'password', '2026-07-29 09:00:00');
`);
const rows = await context.drizzle
.select({ name: sshCredentials.name })
.from(sshCredentials)
.where(timestampAtOrAfter(sshCredentials.updatedAt, ISO_CURSOR));
expect(rows.map((row) => row.name)).toEqual(["same-second"]);
});
});
@@ -1,224 +0,0 @@
import { sql } from "drizzle-orm";
import { afterEach, describe, expect, vi } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { DataCrypto } from "../../../utils/data-crypto.js";
import { TermixIdentityCaRepository } from "../../../database/repositories/termix-identity-ca-repository.js";
describe("TermixIdentityCaRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
vi.restoreAllMocks();
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(onWrite = vi.fn()): Promise<{
repo: TermixIdentityCaRepository;
onWrite: ReturnType<typeof vi.fn>;
}> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash');
INSERT INTO termix_identities (id, user_id, handle)
VALUES (7, 'user-1', 'alice');
`);
return {
repo: new TermixIdentityCaRepository(context, onWrite),
onWrite,
};
}
function mockCrypto(): void {
vi.spyOn(DataCrypto, "validateUserAccess").mockReturnValue(
Buffer.from("user-key"),
);
vi.spyOn(DataCrypto, "getUserDataKey").mockReturnValue(
Buffer.from("user-key"),
);
vi.spyOn(DataCrypto, "encryptRecord").mockImplementation(
(_tableName, record) =>
({
...record,
privateKey: "encrypted-ca-private",
}) as typeof record,
);
vi.spyOn(DataCrypto, "decryptRecord").mockImplementation(
(_tableName, record) =>
({
...record,
privateKey:
record.privateKey === "encrypted-ca-private"
? "decrypted-ca-private"
: record.privateKey,
}) as typeof record,
);
}
it("creates CA private keys with the real row id before encryption", async () => {
const { repo, onWrite } = await createRepository();
mockCrypto();
const created = await repo.createEncryptedForUser("user-1", {
identityId: 7,
userId: "user-1",
publicKey: "ssh-ed25519 public",
privateKey: "plain-ca-private",
validityDays: 120,
});
const [raw] = (await adapter!.query(
sql`SELECT id, public_key, private_key, validity_days FROM termix_identity_ca WHERE identity_id = 7`,
)) as {
id: number;
public_key: string;
private_key: string;
validity_days: number;
}[];
expect(created.privateKey).toBe("decrypted-ca-private");
expect(raw.private_key).toBe("encrypted-ca-private");
expect(raw.public_key).toBe("ssh-ed25519 public");
expect(raw.validity_days).toBe(120);
expect(DataCrypto.encryptRecord).toHaveBeenCalledWith(
"termix_identity_ca",
{ id: raw.id, privateKey: "plain-ca-private" },
"user-1",
Buffer.from("user-key"),
);
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("reads public CA metadata without decrypting private key material", async () => {
const { repo } = await createRepository();
const decryptSpy = vi.spyOn(DataCrypto, "decryptRecord");
await adapter!.run(
sql`INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days)
VALUES (7, 'user-1', 'ssh-ed25519 public', 'encrypted-ca-private', 45)`,
);
await expect(repo.findPublicByIdentityId(7)).resolves.toEqual({
publicKey: "ssh-ed25519 public",
validityDays: 45,
});
expect(decryptSpy).not.toHaveBeenCalled();
});
it("decrypts CA private keys through the user data boundary", async () => {
const { repo } = await createRepository();
mockCrypto();
await adapter!.run(
sql`INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days)
VALUES (7, 'user-1', 'ssh-ed25519 public', 'encrypted-ca-private', 45)`,
);
const ca = await repo.findDecryptedByIdentityId("user-1", 7);
expect(ca).toMatchObject({
identityId: 7,
publicKey: "ssh-ed25519 public",
privateKey: "decrypted-ca-private",
validityDays: 45,
});
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
"termix_identity_ca",
expect.objectContaining({ identityId: 7 }),
"user-1",
Buffer.from("user-key"),
);
});
it("updates CA private keys through encrypted writes", async () => {
const { repo, onWrite } = await createRepository();
mockCrypto();
await adapter!.run(
sql`INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days) VALUES (7, 'user-1', 'ssh-ed25519 old', 'encrypted-ca-private', 45)`,
);
onWrite.mockClear();
const updated = await repo.updateEncryptedForIdentity("user-1", 7, {
publicKey: "ssh-ed25519 new",
privateKey: "plain-updated-ca-private",
validityDays: 90,
});
const [raw] = (await adapter!.query(
sql`SELECT public_key, private_key, validity_days FROM termix_identity_ca WHERE identity_id = 7`,
)) as {
public_key: string;
private_key: string;
validity_days: number;
}[];
expect(updated).toMatchObject({
publicKey: "ssh-ed25519 new",
privateKey: "decrypted-ca-private",
validityDays: 90,
});
expect(raw).toEqual({
public_key: "ssh-ed25519 new",
private_key: "encrypted-ca-private",
validity_days: 90,
});
expect(DataCrypto.encryptRecord).toHaveBeenCalledWith(
"termix_identity_ca",
expect.objectContaining({
privateKey: "plain-updated-ca-private",
}),
"user-1",
Buffer.from("user-key"),
);
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("deletes CA rows through the write boundary", async () => {
const { repo, onWrite } = await createRepository();
await adapter!.run(
sql`INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days) VALUES (7, 'user-1', 'ssh-ed25519 public', 'encrypted-ca-private', 45)`,
);
onWrite.mockClear();
await expect(repo.deleteByIdentityId(7)).resolves.toBe(true);
await expect(repo.deleteByIdentityId(7)).resolves.toBe(false);
expect(
(
await adapter!.query(
sql`SELECT COUNT(*) AS count FROM termix_identity_ca`,
)
).map((row) => Number((row as { count: unknown }).count)),
).toEqual([0]);
expect(onWrite).toHaveBeenCalledTimes(1);
});
it("deletes CA rows for a user", async () => {
const { repo, onWrite } = await createRepository();
await adapter!.run(
sql`INSERT INTO users (id, username, password_hash) VALUES ('user-2', 'bob', 'hash')`,
);
await adapter!.run(
sql`INSERT INTO termix_identities (id, user_id, handle) VALUES (8, 'user-2', 'bob')`,
);
await adapter!.run(
sql`INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days) VALUES (7, 'user-1', 'ssh-ed25519 public', 'encrypted-ca-private', 45)`,
);
await adapter!.run(
sql`INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days) VALUES (8, 'user-2', 'ssh-ed25519 other', 'encrypted-other', 90)`,
);
onWrite.mockClear();
await expect(repo.deleteByUserId("user-1")).resolves.toBe(1);
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
expect(
await adapter!.query(
sql`SELECT user_id, public_key FROM termix_identity_ca ORDER BY user_id`,
),
).toEqual([{ user_id: "user-2", public_key: "ssh-ed25519 other" }]);
expect(onWrite).toHaveBeenCalledTimes(1);
});
});
@@ -1,170 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { TermixIdentityRepository } from "../../../database/repositories/termix-identity-repository.js";
describe("TermixIdentityRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(onWrite = vi.fn()): Promise<{
repo: TermixIdentityRepository;
onWrite: ReturnType<typeof vi.fn>;
}> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_credentials (id, user_id, name, username, auth_type) VALUES
(10, 'user-1', 'cred-10', 'root', 'password'),
(20, 'user-1', 'cred-20', 'root', 'password');
`);
return {
repo: new TermixIdentityRepository(context, onWrite),
onWrite,
};
}
it("creates, updates, finds, and deletes identities", async () => {
const { repo, onWrite } = await createRepository();
const created = await repo.createIdentity({
userId: "user-1",
handle: "alice",
description: "workstation keys",
});
expect(created.id).toBeGreaterThan(0);
expect(await repo.isHandleTaken("alice")).toBe(true);
expect(await repo.findIdentityForUser("user-1")).toMatchObject({
handle: "alice",
});
expect(await repo.findIdentityByHandle("alice")).toMatchObject({
userId: "user-1",
});
const updated = await repo.updateIdentityForUser("user-1", {
handle: "alice-renamed",
description: null,
});
expect(updated).toMatchObject({
handle: "alice-renamed",
description: null,
});
await expect(repo.deleteIdentityForUser("user-1")).resolves.toBe(true);
await expect(repo.deleteIdentityForUser("user-1")).resolves.toBe(false);
await expect(repo.findIdentityForUser("user-1")).resolves.toBeNull();
expect(onWrite).toHaveBeenCalledTimes(3);
});
it("creates, lists, updates, deletes, and links public keys", async () => {
const { repo, onWrite } = await createRepository();
const identity = await repo.createIdentity({
userId: "user-1",
handle: "alice",
description: null,
});
onWrite.mockClear();
const first = await repo.createKey({
identityId: identity.id,
userId: "user-1",
publicKey: "ssh-ed25519 AAAA1",
keyType: "ssh-ed25519",
algorithm: "ED25519",
label: "laptop",
comment: null,
source: "credential",
credentialId: 10,
});
await repo.createKey({
identityId: identity.id,
userId: "user-1",
publicKey: "ssh-rsa AAAA2",
keyType: "ssh-rsa",
algorithm: "RSA",
label: "disabled",
comment: null,
source: "manual",
credentialId: 20,
enabled: false,
});
expect(await repo.listKeysByIdentityId(identity.id)).toHaveLength(2);
expect(await repo.listEnabledKeysByIdentityId(identity.id)).toMatchObject([
{ id: first.id, publicKey: "ssh-ed25519 AAAA1" },
]);
expect(await repo.listLinkedCredentialIds(identity.id)).toEqual([10]);
const updated = await repo.updateKeyForUser("user-1", first.id, {
enabled: false,
label: "revoked",
});
expect(updated).toMatchObject({ enabled: false, label: "revoked" });
await expect(
repo.findKeyForUser("user-1", first.id),
).resolves.toMatchObject({ label: "revoked" });
await expect(repo.deleteKeyForUser("user-1", first.id)).resolves.toBe(true);
await expect(repo.deleteKeyForUser("user-1", first.id)).resolves.toBe(
false,
);
expect(onWrite).toHaveBeenCalledTimes(4);
});
it("deletes identities and keys for a user", async () => {
const { repo, onWrite } = await createRepository();
const userIdentity = await repo.createIdentity({
userId: "user-1",
handle: "alice",
description: null,
});
const otherIdentity = await repo.createIdentity({
userId: "user-2",
handle: "bob",
description: null,
});
await repo.createKey({
identityId: userIdentity.id,
userId: "user-1",
publicKey: "ssh-ed25519 AAAA1",
keyType: "ssh-ed25519",
algorithm: "ED25519",
source: "manual",
});
await repo.createKey({
identityId: otherIdentity.id,
userId: "user-2",
publicKey: "ssh-ed25519 AAAA2",
keyType: "ssh-ed25519",
algorithm: "ED25519",
source: "manual",
});
onWrite.mockClear();
await expect(repo.deleteByUserId("user-1")).resolves.toEqual({
identitiesDeleted: 1,
keysDeleted: 1,
});
await expect(repo.deleteByUserId("missing")).resolves.toEqual({
identitiesDeleted: 0,
keysDeleted: 0,
});
expect(await repo.findIdentityForUser("user-1")).toBeNull();
expect(await repo.listKeysByIdentityId(userIdentity.id)).toEqual([]);
expect(await repo.findIdentityForUser("user-2")).toMatchObject({
handle: "bob",
});
expect(await repo.listKeysByIdentityId(otherIdentity.id)).toHaveLength(1);
expect(onWrite).toHaveBeenCalledTimes(1);
});
});
@@ -10,6 +10,7 @@ import {
} from "drizzle-orm";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "node:url";
import * as schema from "../../../database/db/schema.js";
import type { DatabaseContext } from "../../../database/repositories/database-context.js";
import type { DatabaseDialect } from "../../../database/db/dialect.js";
@@ -448,7 +449,10 @@ let cachedSqliteSchema: string | null = null;
function sqliteSchemaSql(): string {
if (cachedSqliteSchema) return cachedSqliteSchema;
const dir = path.resolve(process.cwd(), "drizzle", "sqlite");
// Resolved from this file, not cwd: plugin suites run with their own
// directory as cwd and would not find drizzle/ otherwise.
const here = path.dirname(fileURLToPath(import.meta.url));
const dir = path.resolve(here, "../../../../..", "drizzle", "sqlite");
const files = fs
.readdirSync(dir)
.filter((name) => name.endsWith(".sql"))
@@ -1,105 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { TmuxSessionTagRepository } from "../../../database/repositories/tmux-session-tag-repository.js";
describe("TmuxSessionTagRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<TmuxSessionTagRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'user-1', 'one', '10.0.0.1', 22, 'root', 'password'), (2, 'user-2', 'two', '10.0.0.1', 22, 'root', 'password');
INSERT INTO tmux_session_tags (user_id, host_id, session_name, tag)
VALUES
('user-1', 1, 'api', 'prod'),
('user-1', 1, 'api', 'critical'),
('user-1', 1, 'worker', 'batch'),
('user-2', 2, 'api', 'other');
`);
return new TmuxSessionTagRepository(context, onWrite);
}
it("groups tags by session for a user and host", async () => {
const repo = await createRepository();
const tags = await repo.listByUserAndHost("user-1", 1);
expect(tags.get("api")).toEqual(["prod", "critical"]);
expect(tags.get("worker")).toEqual(["batch"]);
expect(tags.has("missing")).toBe(false);
});
it("renames and deletes session tags by host/session", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
expect(await repo.renameSessionForHost(1, "api", "api-renamed")).toBe(2);
expect(await repo.renameSessionForHost(1, "missing", "noop")).toBe(0);
const renamed = await repo.listByUserAndHost("user-1", 1);
expect(renamed.get("api-renamed")).toEqual(["prod", "critical"]);
expect(renamed.has("api")).toBe(false);
expect(await repo.deleteSessionForHost(1, "api-renamed")).toBe(2);
expect(await repo.deleteSessionForHost(1, "api-renamed")).toBe(0);
expect(writeCount).toBe(2);
});
it("replaces tags for one user/host/session", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
expect(
await repo.replaceForUserHostSession("user-1", 1, "api", [
"blue",
"green",
]),
).toBe(4);
const tags = await repo.listByUserAndHost("user-1", 1);
expect(tags.get("api")).toEqual(["blue", "green"]);
expect(tags.get("worker")).toEqual(["batch"]);
expect(
await repo.replaceForUserHostSession("user-1", 1, "worker", []),
).toBe(1);
expect(
await repo.replaceForUserHostSession("user-1", 1, "missing", []),
).toBe(0);
expect(writeCount).toBe(2);
});
it("deletes all tags for a user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await expect(repo.deleteByUserId("user-1")).resolves.toBe(3);
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
expect(await repo.listByUserAndHost("user-1", 1)).toEqual(new Map());
expect(await repo.listByUserAndHost("user-2", 2)).toEqual(
new Map([["api", ["other"]]]),
);
expect(writeCount).toBe(1);
});
});
@@ -1,119 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { TransferRecentRepository } from "../../../database/repositories/transfer-recent-repository.js";
describe("TransferRecentRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<TransferRecentRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
VALUES (1, 'user-1', 'source', '10.0.0.1', 22, 'root', 'password'), (2, 'user-1', 'dest-a', '10.0.0.1', 22, 'root', 'password'), (3, 'user-1', 'dest-b', '10.0.0.1', 22, 'root', 'password'), (4, 'user-2', 'other', '10.0.0.1', 22, 'root', 'password');
`);
return new TransferRecentRepository(context, onWrite);
}
it("upserts, lists, and prunes recent transfer destinations", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsertForDestination(
"user-1",
{ sourceHostId: 1, destHostId: 2, destPath: "/var/www" },
"2026-01-01T00:00:00.000Z",
);
await repo.upsertForDestination(
"user-1",
{
sourceHostId: 1,
destHostId: 3,
destPath: "/opt/app",
destPathLabel: "App",
},
"2026-01-02T00:00:00.000Z",
);
await repo.upsertForDestination(
"user-1",
{ sourceHostId: 1, destHostId: 2, destPath: "/var/www" },
"2026-01-03T00:00:00.000Z",
);
const recent = await repo.listBySourceHost("user-1", 1);
expect(recent).toHaveLength(2);
expect(recent.map((entry) => entry.destPath)).toEqual([
"/var/www",
"/opt/app",
]);
expect(recent[0].lastUsed).toBe("2026-01-03T00:00:00.000Z");
expect(recent[0].destPathLabel).toBe("/var/www");
expect(writeCount).toBe(3);
expect(await repo.pruneSourceHost("user-1", 1, 1)).toBe(1);
expect(await repo.pruneSourceHost("user-1", 1, 1)).toBe(0);
expect(await repo.listBySourceHost("user-1", 1)).toHaveLength(1);
expect(writeCount).toBe(4);
});
it("deletes recent transfer destinations by user and host references", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsertForDestination("user-1", {
sourceHostId: 1,
destHostId: 2,
destPath: "/one",
});
await repo.upsertForDestination("user-1", {
sourceHostId: 2,
destHostId: 3,
destPath: "/two",
});
await repo.upsertForDestination("user-2", {
sourceHostId: 4,
destHostId: 1,
destPath: "/other",
});
expect(writeCount).toBe(3);
expect(await repo.deleteByHostId(1)).toBe(2);
expect(await repo.deleteByHostId(1)).toBe(0);
expect(writeCount).toBe(4);
await repo.upsertForDestination("user-1", {
sourceHostId: 1,
destHostId: 2,
destPath: "/three",
});
expect(await repo.deleteByHostIds([])).toBe(0);
expect(await repo.deleteByHostIds([2, 3])).toBe(2);
expect(writeCount).toBe(6);
await repo.upsertForDestination("user-2", {
sourceHostId: 4,
destHostId: 1,
destPath: "/last",
});
expect(await repo.deleteByUserId("user-2")).toBe(1);
expect(await repo.deleteByUserId("user-2")).toBe(0);
expect(writeCount).toBe(8);
});
});
@@ -54,7 +54,6 @@ describe("UserRepository and SessionRepository", () => {
});
expect(await repo.users.countAdmins()).toBe(1);
expect(await repo.users.countTotpEnabled()).toBe(0);
expect((await repo.users.listAll()).map((user) => user.id)).toEqual([
"user-1",
]);
@@ -66,11 +65,9 @@ describe("UserRepository and SessionRepository", () => {
const updated = await repo.users.update("user-1", {
oidcIdentifier: "oidc:admin",
totpEnabled: true,
});
expect(updated?.oidcIdentifier).toBe("oidc:admin");
expect(await repo.users.countTotpEnabled()).toBe(1);
expect((await repo.users.findByOidcIdentifier("oidc:admin"))?.id).toBe(
expect((await repo.users.findByExternalIdentifier("oidc:admin"))?.id).toBe(
"user-1",
);
@@ -1,115 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { VaultProfileRepository } from "../../../database/repositories/vault-profile-repository.js";
describe("VaultProfileRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<VaultProfileRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO vault_profiles (
id, user_id, name, vault_addr, ssh_role, shared, updated_at
)
VALUES (1, 'user-1', 'owned', 'https://vault.one', 'role-one', 0, '2026-01-01T00:00:00.000Z'),
(2, 'user-2', 'shared', 'https://vault.two', 'role-two', 1, '2026-01-02T00:00:00.000Z'),
(3, 'user-2', 'hidden', 'https://vault.three', 'role-three', 0, '2026-01-03T00:00:00.000Z');
`);
return new VaultProfileRepository(context, onWrite);
}
it("lists profiles owned by or shared with the user", async () => {
const repo = await createRepository();
const rows = await repo.listVisibleToUser("user-1");
expect(rows.map((row) => row.id)).toEqual([2, 1]);
});
it("creates and reads a profile", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const created = await repo.create({
userId: "user-1",
name: "new",
description: "desc",
folder: "folder",
tags: "prod,ssh",
vaultAddr: "https://vault.new",
vaultNamespace: "ns",
oidcMount: "oidc",
oidcRole: "oidc-role",
sshMount: "ssh",
sshRole: "ssh-role",
validPrincipals: "root",
keyType: "ed25519",
shared: true,
});
const found = await repo.findById(created.id);
expect(found).toMatchObject({
userId: "user-1",
name: "new",
vaultAddr: "https://vault.new",
sshRole: "ssh-role",
shared: true,
});
expect(writeCount).toBe(1);
});
it("updates and deletes profiles", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const updated = await repo.updateById(1, {
name: "renamed",
shared: true,
updatedAt: "2026-02-01T00:00:00.000Z",
});
expect(updated).toMatchObject({
id: 1,
name: "renamed",
shared: true,
updatedAt: "2026-02-01T00:00:00.000Z",
});
expect(await repo.updateById(999, { name: "missing" })).toBeNull();
expect(await repo.deleteById(1)).toEqual({ syncId: null });
expect(await repo.deleteById(1)).toBeNull();
expect(await repo.findById(1)).toBeNull();
expect(writeCount).toBe(2);
});
it("deletes all profiles for a user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await expect(repo.deleteByUserId("user-2")).resolves.toBe(2);
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
expect(await repo.findById(2)).toBeNull();
expect(await repo.findById(3)).toBeNull();
expect((await repo.findById(1))?.userId).toBe("user-1");
expect(writeCount).toBe(1);
});
});
@@ -1,107 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { VaultTokenRepository } from "../../../database/repositories/vault-token-repository.js";
describe("VaultTokenRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<VaultTokenRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
INSERT INTO vault_profiles (id, user_id, name, vault_addr, ssh_role)
VALUES (1, 'user-1', 'one', 'http://vault', 'r'), (2, 'user-2', 'two', 'http://vault', 'r');
INSERT INTO vault_tokens (
user_id, profile_id, ssh_cert, private_key, expires_at
)
VALUES
('user-1', 1, 'cert-1', 'key-1', '2099-01-01T00:00:00.000Z'),
('user-2', 2, 'cert-2', 'key-2', '2099-01-01T00:00:00.000Z');
`);
return new VaultTokenRepository(context, onWrite);
}
it("finds and upserts a token by user and profile", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const existing = await repo.findByUserAndProfile("user-1", 1);
expect(existing?.sshCert).toBe("cert-1");
await repo.upsert({
userId: "user-1",
profileId: 1,
sshCert: "new-cert",
privateKey: "new-key",
expiresAt: "2099-02-01T00:00:00.000Z",
createdAt: "2026-01-01T00:00:00.000Z",
});
const updated = await repo.findByUserAndProfile("user-1", 1);
expect(updated).toMatchObject({
sshCert: "new-cert",
privateKey: "new-key",
expiresAt: "2099-02-01T00:00:00.000Z",
createdAt: "2026-01-01T00:00:00.000Z",
});
expect(writeCount).toBe(1);
});
it("updates last-used and deletes one token", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
expect(
await repo.updateLastUsed("user-1", 1, "2026-01-02T00:00:00.000Z"),
).toBe(true);
expect(await repo.updateLastUsed("missing", 1)).toBe(false);
expect((await repo.findByUserAndProfile("user-1", 1))?.lastUsed).toBe(
"2026-01-02T00:00:00.000Z",
);
expect(await repo.deleteByUserAndProfile("user-1", 1)).toBe(true);
expect(await repo.deleteByUserAndProfile("user-1", 1)).toBe(false);
expect(await repo.findByUserAndProfile("user-1", 1)).toBeNull();
expect(await repo.findByUserAndProfile("user-2", 2)).not.toBeNull();
expect(writeCount).toBe(2);
});
it("deletes all tokens for a user", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
await repo.upsert({
userId: "user-1",
profileId: 2,
sshCert: "cert-extra",
privateKey: "key-extra",
expiresAt: "2099-03-01T00:00:00.000Z",
});
await expect(repo.deleteByUserId("user-1")).resolves.toBe(2);
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
expect(await repo.findByUserAndProfile("user-1", 1)).toBeNull();
expect(await repo.findByUserAndProfile("user-1", 2)).toBeNull();
expect(await repo.findByUserAndProfile("user-2", 2)).not.toBeNull();
expect(writeCount).toBe(2);
});
});
@@ -1,204 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "./test-support.js";
import { WorkspaceRepository } from "../../../database/repositories/workspace-repository.js";
describe("WorkspaceRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<WorkspaceRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
`);
return new WorkspaceRepository(context, onWrite);
}
it("creates and lists manual workspaces scoped to the owning user", async () => {
const repo = await createRepository();
await repo.create("user-1", { name: "Prod Debugging", payload: "{}" });
await repo.create("user-2", { name: "Other user's", payload: "{}" });
const list = await repo.listByUser("user-1");
expect(list).toHaveLength(1);
expect(list[0]).toMatchObject({
userId: "user-1",
name: "Prod Debugging",
kind: "manual",
isDefault: false,
});
expect(list[0].syncId).toBeTruthy();
});
it("finds a workspace by id scoped to the owner", async () => {
const repo = await createRepository();
const created = await repo.create("user-1", {
name: "Test A",
payload: "{}",
});
expect(await repo.findById("user-1", created.id)).toMatchObject({
id: created.id,
});
expect(await repo.findById("user-2", created.id)).toBeNull();
});
it("upsertLastSession creates then updates a single row, never a second one", async () => {
const repo = await createRepository();
const first = await repo.upsertLastSession("user-1", '{"tabs":[]}');
expect(first.kind).toBe("last_session");
const second = await repo.upsertLastSession(
"user-1",
'{"tabs":[{"slotId":"a"}]}',
);
expect(second.id).toBe(first.id);
expect(second.payload).toBe('{"tabs":[{"slotId":"a"}]}');
const all = await repo.listByUser("user-1");
expect(all.filter((w) => w.kind === "last_session")).toHaveLength(1);
});
it("update renames/recolors a manual workspace but rejects last_session", async () => {
const repo = await createRepository();
const manual = await repo.create("user-1", {
name: "Old Name",
payload: "{}",
});
const lastSession = await repo.upsertLastSession("user-1", "{}");
const updated = await repo.update("user-1", manual.id, {
name: "New Name",
color: "#fff",
});
expect(updated).toMatchObject({ name: "New Name", color: "#fff" });
const rejected = await repo.update("user-1", lastSession.id, {
name: "Should not work",
});
expect(rejected).toBeNull();
});
it("updateContent overwrites payload for a manual workspace but rejects last_session", async () => {
const repo = await createRepository();
const manual = await repo.create("user-1", {
name: "Test A",
payload: "{}",
});
const lastSession = await repo.upsertLastSession("user-1", "{}");
const updated = await repo.updateContent(
"user-1",
manual.id,
'{"tabs":[1]}',
);
expect(updated?.payload).toBe('{"tabs":[1]}');
const rejected = await repo.updateContent(
"user-1",
lastSession.id,
'{"tabs":[2]}',
);
expect(rejected).toBeNull();
});
it("setDefault clears any prior default and rejects last_session", async () => {
const repo = await createRepository();
const a = await repo.create("user-1", { name: "A", payload: "{}" });
const b = await repo.create("user-1", { name: "B", payload: "{}" });
const lastSession = await repo.upsertLastSession("user-1", "{}");
await repo.setDefault("user-1", a.id);
expect((await repo.findById("user-1", a.id))?.isDefault).toBe(true);
await repo.setDefault("user-1", b.id);
expect((await repo.findById("user-1", a.id))?.isDefault).toBe(false);
expect((await repo.findById("user-1", b.id))?.isDefault).toBe(true);
const rejected = await repo.setDefault("user-1", lastSession.id);
expect(rejected).toBeNull();
});
it("unsetDefault clears isDefault on a manual workspace and rejects last_session", async () => {
const repo = await createRepository();
const a = await repo.create("user-1", { name: "A", payload: "{}" });
const lastSession = await repo.upsertLastSession("user-1", "{}");
await repo.setDefault("user-1", a.id);
expect((await repo.findById("user-1", a.id))?.isDefault).toBe(true);
await repo.unsetDefault("user-1", a.id);
expect((await repo.findById("user-1", a.id))?.isDefault).toBe(false);
const rejected = await repo.unsetDefault("user-1", lastSession.id);
expect(rejected).toBeNull();
});
it("touchLastUsed sets lastUsedAt", async () => {
const repo = await createRepository();
const workspace = await repo.create("user-1", {
name: "A",
payload: "{}",
});
expect(workspace.lastUsedAt).toBeNull();
await repo.touchLastUsed(
"user-1",
workspace.id,
"2026-08-11T00:00:00.000Z",
);
expect((await repo.findById("user-1", workspace.id))?.lastUsedAt).toBe(
"2026-08-11T00:00:00.000Z",
);
});
it("delete removes a manual workspace but rejects last_session", async () => {
const repo = await createRepository();
const manual = await repo.create("user-1", { name: "A", payload: "{}" });
const lastSession = await repo.upsertLastSession("user-1", "{}");
await expect(repo.delete("user-1", lastSession.id)).resolves.toBe(false);
await expect(repo.delete("user-1", manual.id)).resolves.toBe(true);
expect(await repo.findById("user-1", manual.id)).toBeNull();
});
it("triggers writes on create/update/delete", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const created = await repo.create("user-1", {
name: "A",
payload: "{}",
});
await repo.update("user-1", created.id, { name: "B" });
await repo.delete("user-1", created.id);
expect(writeCount).toBe(3);
});
it("deleteByUserId removes every workspace owned by the user", async () => {
const repo = await createRepository();
await repo.create("user-1", { name: "A", payload: "{}" });
await repo.create("user-1", { name: "B", payload: "{}" });
await repo.create("user-2", { name: "C", payload: "{}" });
await expect(repo.deleteByUserId("user-1")).resolves.toBe(2);
expect(await repo.listByUser("user-1")).toHaveLength(0);
expect(await repo.listByUser("user-2")).toHaveLength(1);
});
});
@@ -0,0 +1,96 @@
/**
* The 2.8 login URLs 2.8 clients still call. They forward to the login
* pipeline and, with the method's plugin gone, sign nobody in.
*/
import http from "node:http";
import type { AddressInfo } from "node:net";
import express from "express";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../../../utils/logger.js", () => {
const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() };
return { authLogger: log, databaseLogger: log, logger: log };
});
vi.mock("../../../auth/core-auth.js", () => ({
ensureCoreLoginProviders: () => {},
}));
vi.mock("../../../utils/trusted-proxy-auth.js", () => ({
isTrustedProxyAuthEnabled: () => false,
}));
const { registerAuthCompatRoutes } =
await import("../../../database/routes/auth-compat-routes.js");
const { registerLoginMethod, resetAuthRegistryForTests } =
await import("../../../auth/registry.js");
let server: http.Server;
let base: string;
beforeEach(async () => {
resetAuthRegistryForTests();
const router = express.Router();
router.use(express.json());
registerAuthCompatRoutes(router);
const app = express();
app.use("/users", router);
server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, resolve));
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterEach(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
function get(path: string) {
return fetch(`${base}${path}`, { redirect: "manual" });
}
function registerSso() {
return registerLoginMethod({
id: "oidc",
pluginId: "sso",
labelKey: "loginWithSso",
kind: "redirect",
external: true,
describe: async () => [
{ id: "3", label: "Keycloak", enabled: true, type: "oidc" },
],
start: async (_request, instanceId) => ({
redirectUrl: `https://idp.example/auth?provider=${instanceId}`,
}),
});
}
describe("the old client routes", () => {
it("starts an SSO login through the oidc method", async () => {
registerSso();
const response = await get("/users/oidc/authorize?providerId=3");
expect(response.status).toBe(200);
expect(await response.json()).toMatchObject({
auth_url: "https://idp.example/auth?provider=3",
});
});
it("lists providers in the 2.8 shape", async () => {
registerSso();
const response = await get("/users/sso-providers");
expect(await response.json()).toEqual([
{ id: 3, name: "Keycloak", type: "oidc", displayOrder: 0 },
]);
});
it("answers 404 once the plugins are gone", async () => {
const dispose = registerSso();
dispose();
expect((await get("/users/oidc/authorize?providerId=3")).status).toBe(404);
expect(await (await get("/users/sso-providers")).json()).toEqual([]);
const ldap = await fetch(`${base}/users/ldap/login`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ providerId: 4, username: "bob", password: "x" }),
});
expect(ldap.status).toBe(404);
});
});
@@ -1,521 +0,0 @@
import crypto from "node:crypto";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Request, Response, Router } from "express";
import type { AutomationDefinition } from "../../../../types/automations.js";
/**
* Route-level behaviour: validation, ownership and webhook token handling. The repository and engine are mocked; what matters here is what
* the HTTP layer accepts, rejects and hands back.
*/
const state = vi.hoisted(() => ({
currentUserId: "user-1",
rows: [] as Array<Record<string, unknown>>,
nextId: 1,
}));
vi.mock("../../../database/db/index.js", () => ({ db: {} }));
vi.mock("../../../utils/logger.js", () => ({
databaseLogger: {
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
success: vi.fn(),
},
}));
const repository = vi.hoisted(() => ({
list: vi.fn(),
findForUser: vi.fn(),
create: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
listAllEnabled: vi.fn(),
listRuns: vi.fn(),
findRunForUser: vi.fn(),
listRunSteps: vi.fn(),
upsertSchedule: vi.fn(),
deleteSchedule: vi.fn(),
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentAutomationRepository: () => repository,
}));
const run = vi.hoisted(() => vi.fn());
vi.mock("../../../automations/engine.js", () => ({
AutomationEngine: { getInstance: () => ({ run }) },
}));
vi.mock("../../../utils/permission-manager.js", () => ({
PermissionManager: {
getInstance: () => ({
requirePermission:
() => (_req: unknown, _res: unknown, next: () => void) =>
next(),
}),
},
}));
vi.mock("../../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() =>
(req: Record<string, unknown>, _res: unknown, next: () => void) => {
req.userId = state.currentUserId;
next();
},
createDataAccessMiddleware:
() => (_req: unknown, _res: unknown, next: () => void) =>
next(),
}),
},
}));
vi.mock("../../../utils/audit-logger.js", () => ({
logAudit: vi.fn(async () => undefined),
getAuditUsername: vi.fn(async () => "alice"),
getRequestMeta: () => ({ ipAddress: "127.0.0.1", userAgent: "test" }),
}));
const { default: router } =
await import("../../../database/routes/automations.js");
function findHandler(method: string, path: string) {
const stack = (router as unknown as Router).stack as Array<{
route?: {
path: string;
methods: Record<string, boolean>;
stack: Array<{ handle: (req: Request, res: Response) => unknown }>;
};
}>;
const layer = stack.find(
(l) => l.route?.path === path && l.route?.methods[method],
);
if (!layer?.route) throw new Error(`No route for ${method} ${path}`);
return layer.route.stack[layer.route.stack.length - 1].handle;
}
/** Runs the whole middleware chain for the route, not just its handler. */
async function invoke(
method: string,
path: string,
overrides: {
body?: Record<string, unknown>;
params?: Record<string, unknown>;
query?: Record<string, unknown>;
} = {},
) {
const stack = (router as unknown as Router).stack as Array<{
route?: {
path: string;
methods: Record<string, boolean>;
stack: Array<{ handle: (...args: unknown[]) => unknown }>;
};
}>;
const layer = stack.find(
(l) => l.route?.path === path && l.route?.methods[method],
);
if (!layer?.route) throw new Error(`No route for ${method} ${path}`);
const req = {
userId: state.currentUserId,
body: overrides.body ?? {},
params: overrides.params ?? {},
query: overrides.query ?? {},
headers: {},
} as unknown as Request;
const res = {
statusCode: 200,
jsonBody: null as unknown,
status(code: number) {
(this as unknown as { statusCode: number }).statusCode = code;
return this;
},
json(payload: unknown) {
(this as unknown as { jsonBody: unknown }).jsonBody = payload;
return this;
},
} as unknown as Response & { statusCode: number; jsonBody: unknown };
for (const entry of layer.route.stack) {
let advanced = false;
await entry.handle(req, res, () => {
advanced = true;
});
if (!advanced) break;
}
return res as unknown as {
statusCode: number;
jsonBody: Record<string, unknown> | null;
};
}
function definition(
overrides: Partial<AutomationDefinition> = {},
): AutomationDefinition {
return {
version: 1,
trigger: {
kind: "metric_threshold",
hostSelector: { kind: "host", hostId: 7 },
metric: { path: "disk.percent", mount: "/data" },
operator: ">",
value: 90,
cooldownMinutes: 15,
},
steps: [{ id: "a", type: "notify", channelIds: [1] }],
...overrides,
} as AutomationDefinition;
}
beforeEach(() => {
state.currentUserId = "user-1";
state.rows = [];
state.nextId = 1;
vi.clearAllMocks();
repository.list.mockImplementation(async (userId: string) =>
state.rows.filter((row) => row.user_id === userId),
);
repository.findForUser.mockImplementation(
async (id: number, userId: string) =>
state.rows.find((row) => row.id === id && row.user_id === userId) ?? null,
);
repository.create.mockImplementation(
async (input: Record<string, unknown>) => {
const row = {
id: state.nextId++,
user_id: input.userId,
name: input.name,
definition: input.definition,
enabled: input.enabled === false ? 0 : 1,
channels: input.channels ?? [],
};
state.rows.push(row);
return row;
},
);
repository.delete.mockImplementation(async (id: number, userId: string) => {
const index = state.rows.findIndex(
(row) => row.id === id && row.user_id === userId,
);
if (index === -1) return false;
state.rows.splice(index, 1);
return true;
});
repository.listAllEnabled.mockImplementation(async () =>
state.rows.map((row) => ({
id: row.id,
userId: row.user_id,
definition: row.definition,
enabled: true,
})),
);
repository.upsertSchedule.mockResolvedValue(undefined);
repository.deleteSchedule.mockResolvedValue(undefined);
run.mockResolvedValue({ runId: 1, status: "success" });
});
describe("POST /", () => {
it("creates an automation from a valid definition", async () => {
const res = await invoke("post", "/", {
body: { name: "Disk watch", definition: definition() },
});
expect(res.statusCode).toBe(201);
expect(res.jsonBody?.name).toBe("Disk watch");
});
it("requires a name", async () => {
const res = await invoke("post", "/", {
body: { definition: definition() },
});
expect(res.statusCode).toBe(400);
expect(String(res.jsonBody?.error)).toMatch(/name/i);
});
it("rejects an unknown trigger kind", async () => {
const res = await invoke("post", "/", {
body: {
name: "Bad",
definition: { version: 1, trigger: { kind: "nope" }, steps: [] },
},
});
expect(res.statusCode).toBe(400);
expect(String(res.jsonBody?.error)).toMatch(/trigger/i);
});
it("rejects an unknown operator", async () => {
const res = await invoke("post", "/", {
body: {
name: "Bad",
definition: definition({
trigger: {
kind: "metric_threshold",
hostSelector: { kind: "all" },
metric: { path: "cpu.percent" },
operator: "~=",
value: 1,
cooldownMinutes: 5,
},
} as Partial<AutomationDefinition>),
},
});
expect(res.statusCode).toBe(400);
expect(String(res.jsonBody?.error)).toMatch(/operator/i);
});
it("rejects an unknown step type", async () => {
const res = await invoke("post", "/", {
body: {
name: "Bad",
definition: definition({
steps: [{ id: "a", type: "launch_missiles" }],
} as Partial<AutomationDefinition>),
},
});
expect(res.statusCode).toBe(400);
expect(String(res.jsonBody?.error)).toMatch(/step type/i);
});
it("rejects duplicate step ids, including inside a branch", async () => {
const res = await invoke("post", "/", {
body: {
name: "Bad",
definition: definition({
steps: [
{ id: "dup", type: "wait", seconds: 1 },
{
id: "branch",
type: "if",
condition: { left: "1", operator: "==", right: "1" },
then: [{ id: "dup", type: "wait", seconds: 1 }],
},
],
} as Partial<AutomationDefinition>),
},
});
expect(res.statusCode).toBe(400);
expect(String(res.jsonBody?.error)).toMatch(/duplicate/i);
});
it("rejects an invalid cron expression", async () => {
const res = await invoke("post", "/", {
body: {
name: "Bad",
definition: definition({
trigger: { kind: "schedule", cron: "not a cron" },
} as Partial<AutomationDefinition>),
},
});
expect(res.statusCode).toBe(400);
expect(String(res.jsonBody?.error)).toMatch(/cron/i);
});
it("rejects an interval under a minute", async () => {
const res = await invoke("post", "/", {
body: {
name: "Bad",
definition: definition({
trigger: { kind: "schedule", intervalSeconds: 5 },
} as Partial<AutomationDefinition>),
},
});
expect(res.statusCode).toBe(400);
expect(String(res.jsonBody?.error)).toMatch(/60 seconds/i);
});
it("registers a schedule for a schedule trigger", async () => {
await invoke("post", "/", {
body: {
name: "Nightly",
definition: definition({
trigger: { kind: "schedule", cron: "0 2 * * *" },
} as Partial<AutomationDefinition>),
},
});
expect(repository.upsertSchedule).toHaveBeenCalled();
});
it("returns a webhook token once and stores only its hash", async () => {
const res = await invoke("post", "/", {
body: {
name: "Hooked",
definition: definition({
trigger: { kind: "webhook", tokenHash: "" },
} as Partial<AutomationDefinition>),
},
});
expect(res.statusCode).toBe(201);
const token = res.jsonBody?.webhookToken as string;
expect(token).toMatch(/^[a-f0-9]{64}$/);
const stored = JSON.parse(state.rows[0].definition as string);
expect(stored.trigger.tokenHash).not.toBe(token);
expect(stored.trigger.tokenHash).toBe(
crypto.createHash("sha256").update(token).digest("hex"),
);
// The hash is never echoed back to the client.
const body = res.jsonBody as { definition: AutomationDefinition };
expect((body.definition.trigger as { tokenHash: string }).tokenHash).toBe(
"",
);
});
it("stores the automation against the caller, not a supplied user id", async () => {
// Authorization here is ownership, the same as the other data routes:
// every read and write is scoped to req.userId, so a client cannot create
// an automation that belongs to somebody else.
await invoke("post", "/", {
body: {
name: "Mine",
definition: definition(),
userId: "user-2",
user_id: "user-2",
},
});
expect(state.rows).toHaveLength(1);
expect(state.rows[0].user_id).toBe("user-1");
});
});
describe("GET /", () => {
it("only returns the caller's automations", async () => {
state.rows.push({
id: 1,
user_id: "user-2",
name: "Theirs",
definition: JSON.stringify(definition()),
channels: [],
});
const res = await invoke("get", "/");
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toHaveLength(0);
});
});
describe("DELETE /:id", () => {
it("will not delete another user's automation", async () => {
state.rows.push({
id: 1,
user_id: "user-2",
name: "Theirs",
definition: JSON.stringify(definition()),
channels: [],
});
const res = await invoke("delete", "/:id", { params: { id: "1" } });
expect(res.statusCode).toBe(404);
expect(state.rows).toHaveLength(1);
});
});
describe("POST /:id/run", () => {
function seedOwned() {
state.rows.push({
id: 1,
user_id: "user-1",
name: "Mine",
definition: JSON.stringify(definition()),
channels: [],
});
}
it("runs an owned automation", async () => {
seedOwned();
const res = await invoke("post", "/:id/run", { params: { id: "1" } });
expect(res.statusCode).toBe(200);
expect(run).toHaveBeenCalledWith(
expect.objectContaining({ automationId: 1, triggerType: "manual" }),
);
});
it("passes the dry-run flag through", async () => {
seedOwned();
await invoke("post", "/:id/run", {
params: { id: "1" },
body: { dryRun: true },
});
expect(run).toHaveBeenCalledWith(expect.objectContaining({ dryRun: true }));
});
it("refuses to run someone else's automation", async () => {
state.rows.push({
id: 1,
user_id: "user-2",
name: "Theirs",
definition: JSON.stringify(definition()),
channels: [],
});
const res = await invoke("post", "/:id/run", { params: { id: "1" } });
expect(res.statusCode).toBe(404);
expect(run).not.toHaveBeenCalled();
});
});
describe("POST /webhook/:token", () => {
function seedWebhook(token: string) {
state.rows.push({
id: 1,
user_id: "user-1",
name: "Hooked",
definition: JSON.stringify(
definition({
trigger: {
kind: "webhook",
tokenHash: crypto.createHash("sha256").update(token).digest("hex"),
},
} as Partial<AutomationDefinition>),
),
channels: [],
});
}
it("runs the automation matching the token", async () => {
const token = "a".repeat(64);
seedWebhook(token);
const res = await invoke("post", "/webhook/:token", {
params: { token },
body: { hello: "world" },
});
expect(res.statusCode).toBe(202);
expect(run).toHaveBeenCalledWith(
expect.objectContaining({ automationId: 1, triggerType: "webhook" }),
);
});
it("rejects a token that does not match", async () => {
seedWebhook("a".repeat(64));
const res = await invoke("post", "/webhook/:token", {
params: { token: "b".repeat(64) },
});
expect(res.statusCode).toBe(404);
expect(run).not.toHaveBeenCalled();
});
it("rejects a token too short to be real", async () => {
seedWebhook("a".repeat(64));
const res = await invoke("post", "/webhook/:token", {
params: { token: "short" },
});
expect(res.statusCode).toBe(404);
expect(run).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,139 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import http from "node:http";
import type { AddressInfo } from "node:net";
import express from "express";
const state = vi.hoisted(() => ({
unlocked: true,
activity: [] as unknown[],
recordResult: { status: "logged", id: 1 } as {
status: string;
id?: number;
},
}));
vi.mock("../../../utils/logger.js", () => ({
dashboardLogger: { warn: vi.fn(), error: vi.fn(), success: vi.fn() },
}));
vi.mock("../../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() => (req: express.Request, _res: unknown, next: () => void) => {
(req as unknown as { userId: string }).userId = "user-1";
next();
},
}),
},
}));
vi.mock("../../../utils/data-crypto.js", () => ({
DataCrypto: {
getUserDataKey: () => (state.unlocked ? "key" : null),
},
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentRecentActivityRepository: () => ({
listByUserId: async () => state.activity,
deleteByUserId: async () => {},
}),
}));
vi.mock("../../../services/recent-activity.js", () => ({
recordRecentActivity: async () => state.recordResult,
}));
const { default: dashboardRoutes } =
await import("../../../database/routes/dashboard-routes.js");
let server: http.Server;
let baseUrl: string;
beforeEach(async () => {
state.unlocked = true;
state.activity = [];
state.recordResult = { status: "logged", id: 1 };
const app = express();
app.use(express.json());
app.use("/dashboard", dashboardRoutes);
server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo;
baseUrl = `http://127.0.0.1:${port}`;
});
afterEach(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
describe("GET /dashboard/uptime", () => {
it("returns a formatted uptime", async () => {
const res = await fetch(`${baseUrl}/dashboard/uptime`);
expect(res.status).toBe(200);
const body = await res.json();
expect(body).toMatchObject({
uptimeMs: expect.any(Number),
formatted: expect.stringMatching(/^\d+d \d+h \d+m$/),
});
});
});
describe("GET /dashboard/activity/recent", () => {
it("401s when the user's data key is not unlocked", async () => {
state.unlocked = false;
const res = await fetch(`${baseUrl}/dashboard/activity/recent`);
expect(res.status).toBe(401);
});
it("returns the user's recent activity", async () => {
state.activity = [{ id: 1, type: "terminal" }];
const res = await fetch(`${baseUrl}/dashboard/activity/recent`);
expect(res.status).toBe(200);
expect(await res.json()).toEqual(state.activity);
});
});
describe("POST /dashboard/activity/log", () => {
it("rejects a body missing required fields", async () => {
const res = await fetch(`${baseUrl}/dashboard/activity/log`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ type: "terminal" }),
});
expect(res.status).toBe(400);
});
it("logs a valid activity", async () => {
const res = await fetch(`${baseUrl}/dashboard/activity/log`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ type: "terminal", hostId: 1, hostName: "prod" }),
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ message: "Activity logged", id: 1 });
});
it("404s a host the user cannot access", async () => {
state.recordResult = { status: "denied" };
const res = await fetch(`${baseUrl}/dashboard/activity/log`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ type: "terminal", hostId: 1, hostName: "prod" }),
});
expect(res.status).toBe(404);
});
});
describe("DELETE /dashboard/activity/reset", () => {
it("clears the user's recent activity", async () => {
const res = await fetch(`${baseUrl}/dashboard/activity/reset`, {
method: "DELETE",
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ message: "Recent activity cleared" });
});
});
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import type { Request } from "express";
import type { UserRecord } from "../../../database/repositories/user-repository.js";
import {
allowsDesktopAutoSession,
isLoopbackRequest,
extractBearerOrCookieToken,
isNativeTokenExportRequest,
@@ -14,7 +15,6 @@ function makeUser(overrides: Partial<UserRecord> = {}): UserRecord {
username: "local",
passwordHash: "",
isOidc: false,
totpEnabled: false,
isAdmin: false,
registeredAt: "2026-01-01T00:00:00.000Z",
...overrides,
@@ -146,11 +146,6 @@ describe("resolveDesktopAutoSessionUser", () => {
expect(resolveDesktopAutoSessionUser([user])).toBe(user);
});
it("returns the sole local user even when TOTP-enabled", () => {
const user = makeUser({ totpEnabled: true });
expect(resolveDesktopAutoSessionUser([user])).toBe(user);
});
it("returns the auto-provisioned passwordless placeholder", () => {
const user = makeUser({ passwordHash: "" });
expect(resolveDesktopAutoSessionUser([user])).toBe(user);
@@ -190,3 +185,20 @@ describe("resolveDesktopAutoSessionUser", () => {
expect(result).toBe(earliest);
});
});
describe("allowsDesktopAutoSession", () => {
it("allows the embedded desktop backend and a development backend", () => {
expect(
allowsDesktopAutoSession({
ELECTRON_EMBEDDED: "true",
NODE_ENV: "production",
}),
).toBe(true);
expect(allowsDesktopAutoSession({ NODE_ENV: "development" })).toBe(true);
expect(allowsDesktopAutoSession({})).toBe(true);
});
it("never allows it on a production server", () => {
expect(allowsDesktopAutoSession({ NODE_ENV: "production" })).toBe(false);
});
});
@@ -1,435 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { Request, Response, Router } from "express";
const state = vi.hoisted(() => ({
currentUserId: "user-1",
fleets: new Map<number, { id: number; userId: string; name: string }>(),
members: new Map<number, { id: number; name: string }[]>(),
hostAccess: new Map<string, { hasAccess: boolean; isOwner: boolean }>(),
hosts: new Map<number, Record<string, unknown>>(),
}));
vi.mock("../../../database/db/index.js", () => ({ db: {} }));
vi.mock("../../../utils/logger.js", () => ({
authLogger: {
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
success: vi.fn(),
},
databaseLogger: {
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
success: vi.fn(),
},
}));
vi.mock("../../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() =>
(req: Record<string, unknown>, _res: unknown, next: () => void) => {
req.userId = state.currentUserId;
next();
},
createDataAccessMiddleware:
() => (_req: unknown, _res: unknown, next: () => void) =>
next(),
}),
},
}));
vi.mock("../../../utils/permission-manager.js", () => ({
PermissionManager: {
getInstance: () => ({
canAccessHost: async (userId: string, hostId: number, level: string) => {
const key = `${userId}:${hostId}:${level}`;
const found = state.hostAccess.get(key);
if (found) return found;
// default: full access unless a test explicitly denies it
return { hasAccess: true, isOwner: true, permissionLevel: "manage" };
},
}),
},
}));
vi.mock("../../../hosts/host-resolver.js", () => ({
resolveHostById: async (hostId: number) => state.hosts.get(hostId) ?? null,
}));
vi.mock("../../../hosts/ssh-client-factory.js", () => ({
getFleetPoolKey: () => "pool-key",
createFleetSshFactory: () => async () => ({}),
}));
vi.mock("../../../hosts/ssh-connection-pool.js", () => ({
withConnection: async (
_key: string,
_factory: unknown,
fn: (client: unknown) => unknown,
) => fn({}),
}));
vi.mock("../../../hosts/metrics/widgets/common-utils.js", () => ({
execCommand: vi.fn(async () => ({ stdout: "ok", stderr: "", code: 0 })),
}));
vi.mock("../../../hosts/metrics/managers/platform.js", () => ({
detectPlatform: vi.fn(async () => ({ pkg: "apt", osPrettyName: "Debian" })),
}));
vi.mock("../../../hosts/metrics/managers/exec-elevated.js", async () => {
class ElevationError extends Error {
code: string;
constructor(code: string, message: string) {
super(message);
this.code = code;
}
}
return {
execElevated: vi.fn(),
ElevationError,
};
});
vi.mock("../../../hosts/metrics/managers/packages.js", () => ({
buildPackageActionCommand: vi.fn(() => "apt-get install -y foo"),
}));
vi.mock("../../../hosts/metrics/managers/validation.js", () => ({
isValidPackageName: (v: unknown) => typeof v === "string" && v.length > 0,
}));
vi.mock("../../../database/routes/snippets-execution.js", () => ({
resolveSnippetCommand: (command: string) => command,
}));
vi.mock("../../../database/routes/rbac.js", () => ({
isSharePermissionLevel: (v: unknown) =>
["connect", "view", "edit", "manage"].includes(v as string),
expiryFromDuration: () => null,
parseShareTargets: () => null,
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentFleetRepository: () => ({
findById: async (userId: string, fleetId: number) => {
const fleet = state.fleets.get(fleetId);
return fleet && fleet.userId === userId ? fleet : null;
},
listEffectiveMembers: async (_userId: string, fleetId: number) =>
state.members.get(fleetId) ?? [],
listStaticMemberIds: async () => [],
listByUser: async (userId: string) =>
[...state.fleets.values()].filter((f) => f.userId === userId),
}),
createCurrentFleetInventoryRepository: () => ({
listForHosts: async () => [],
upsert: async () => ({}),
}),
createCurrentRbacAccessRepository: () => ({}),
createCurrentRoleRepository: () => ({}),
createCurrentUserRepository: () => ({}),
}));
const {
default: router,
parseInventoryProbe,
buildRemoveCommand,
} = await import("../../../database/routes/fleet-routes.js");
function findLayer(method: string, path: string) {
const stack = (router as unknown as Router).stack as Array<{
route?: {
path: string;
methods: Record<string, boolean>;
stack: Array<{ handle: (req: Request, res: Response) => unknown }>;
};
}>;
const layer = stack.find(
(l) => l.route?.path === path && l.route?.methods[method],
);
if (!layer?.route) throw new Error(`No route for ${method} ${path}`);
return layer.route.stack[layer.route.stack.length - 1].handle;
}
function makeReqRes(overrides: {
body?: Record<string, unknown>;
params?: Record<string, unknown>;
}) {
const req = {
userId: state.currentUserId,
body: overrides.body ?? {},
params: overrides.params ?? {},
headers: {},
} as unknown as Request;
const res = {
statusCode: 200,
jsonBody: null as unknown,
status(code: number) {
(this as unknown as { statusCode: number }).statusCode = code;
return this;
},
json(payload: unknown) {
(this as unknown as { jsonBody: unknown }).jsonBody = payload;
return this;
},
} as unknown as Response & { statusCode: number; jsonBody: unknown };
return { req, res };
}
async function invoke(
method: string,
path: string,
overrides: {
body?: Record<string, unknown>;
params?: Record<string, unknown>;
} = {},
) {
const handler = findLayer(method, path);
const { req, res } = makeReqRes(overrides);
await handler(req, res);
return res as unknown as {
statusCode: number;
jsonBody: Record<string, unknown> | null;
};
}
beforeEach(() => {
state.currentUserId = "user-1";
state.fleets = new Map([[1, { id: 1, userId: "user-1", name: "web fleet" }]]);
state.members = new Map([
[
1,
[
{ id: 10, name: "host-a" },
{ id: 11, name: "host-b" },
],
],
]);
state.hostAccess = new Map();
state.hosts = new Map([
[
10,
{
id: 10,
userId: "user-1",
name: "host-a",
ip: "10.0.0.1",
port: 22,
username: "root",
sudoPassword: "secret",
},
],
[
11,
{
id: 11,
userId: "user-1",
name: "host-b",
ip: "10.0.0.2",
port: 22,
username: "root",
sudoPassword: "secret",
},
],
]);
});
describe("GET /:id/members", () => {
it("404s for a fleet the caller does not own", async () => {
const res = await invoke("get", "/:id/members", {
params: { id: "999" },
});
expect(res.statusCode).toBe(404);
});
it("400s on a non-numeric fleet id", async () => {
const res = await invoke("get", "/:id/members", {
params: { id: "not-a-number" },
});
expect(res.statusCode).toBe(400);
});
});
describe("POST /:id/execute", () => {
it("400s when command is missing", async () => {
const res = await invoke("post", "/:id/execute", {
params: { id: "1" },
body: {},
});
expect(res.statusCode).toBe(400);
});
it("reports per-host success with the {hostId, hostName, success} shape", async () => {
const res = await invoke("post", "/:id/execute", {
params: { id: "1" },
body: { command: "uptime" },
});
expect(res.statusCode).toBe(200);
const results = res.jsonBody?.results as Array<Record<string, unknown>>;
expect(results).toHaveLength(2);
expect(results[0]).toMatchObject({
hostId: 10,
hostName: "host-a",
success: true,
});
});
it("isolates one host's access denial - the other host still succeeds", async () => {
state.hostAccess.set("user-1:10:edit", {
hasAccess: false,
isOwner: false,
});
const res = await invoke("post", "/:id/execute", {
params: { id: "1" },
body: { command: "uptime" },
});
const results = res.jsonBody?.results as Array<Record<string, unknown>>;
const denied = results.find((r) => r.hostId === 10);
const allowed = results.find((r) => r.hostId === 11);
expect(denied).toMatchObject({ success: false });
expect(String(denied?.error)).toMatch(/edit/);
expect(allowed).toMatchObject({ success: true });
});
it("404s for a fleet the caller does not own", async () => {
const res = await invoke("post", "/:id/execute", {
params: { id: "999" },
body: { command: "uptime" },
});
expect(res.statusCode).toBe(404);
});
});
describe("POST /:id/packages", () => {
it("400s on an invalid action", async () => {
const res = await invoke("post", "/:id/packages", {
params: { id: "1" },
body: { action: "reformat-disk" },
});
expect(res.statusCode).toBe(400);
});
it("surfaces an ElevationError as a per-host error, not a request failure", async () => {
const { execElevated, ElevationError } =
await import("../../../hosts/metrics/managers/exec-elevated.js");
(execElevated as ReturnType<typeof vi.fn>).mockRejectedValue(
new ElevationError("SUDO_REQUIRED", "sudo password required"),
);
const res = await invoke("post", "/:id/packages", {
params: { id: "1" },
body: { action: "install", package: "curl" },
});
expect(res.statusCode).toBe(200);
const results = res.jsonBody?.results as Array<Record<string, unknown>>;
expect(results.every((r) => r.success === false)).toBe(true);
expect(results[0].error).toMatch(/sudo password required/);
});
it("requires manage-level access, not just edit", async () => {
state.hostAccess.set("user-1:10:manage", {
hasAccess: false,
isOwner: false,
});
state.hostAccess.set("user-1:11:manage", {
hasAccess: false,
isOwner: false,
});
const { execElevated } =
await import("../../../hosts/metrics/managers/exec-elevated.js");
(execElevated as ReturnType<typeof vi.fn>).mockResolvedValue({
code: 0,
stdout: "done",
stderr: "",
});
const res = await invoke("post", "/:id/packages", {
params: { id: "1" },
body: { action: "upgrade-all" },
});
const results = res.jsonBody?.results as Array<Record<string, unknown>>;
expect(results.every((r) => r.success === false)).toBe(true);
expect(String(results[0].error)).toMatch(/manage/);
});
});
describe("POST /:id/members", () => {
it("404s when the caller cannot access the target host", async () => {
state.hostAccess.set("user-1:99:connect", {
hasAccess: false,
isOwner: false,
});
const res = await invoke("post", "/:id/members", {
params: { id: "1" },
body: { hostId: 99 },
});
expect(res.statusCode).toBe(404);
});
});
describe("parseInventoryProbe", () => {
it("extracts kernel, arch, hostname, and uptime from key=value lines", () => {
const out = [
"kernel=6.1.0-generic",
"arch=x86_64",
"hostname=web-1",
"uptime_seconds=123456",
].join("\n");
expect(parseInventoryProbe(out)).toEqual({
kernel: "6.1.0-generic",
architecture: "x86_64",
hostname: "web-1",
uptimeSeconds: 123456,
});
});
it("nulls out fields missing from the probe output", () => {
expect(parseInventoryProbe("kernel=6.1.0")).toEqual({
kernel: "6.1.0",
architecture: null,
hostname: null,
uptimeSeconds: null,
});
});
it("nulls uptimeSeconds when the value is not a bare integer", () => {
const out = "uptime_seconds=";
expect(parseInventoryProbe(out).uptimeSeconds).toBeNull();
});
it("ignores lines with no '=' separator", () => {
const out = ["garbage line", "kernel=6.1.0"].join("\n");
expect(parseInventoryProbe(out).kernel).toBe("6.1.0");
});
});
describe("buildRemoveCommand", () => {
it("builds the correct remove command per package manager", () => {
expect(buildRemoveCommand("apt", "curl")).toContain(
"apt-get -y remove curl",
);
expect(buildRemoveCommand("dnf", "curl")).toBe("dnf -y remove curl");
expect(buildRemoveCommand("yum", "curl")).toBe("yum -y remove curl");
expect(buildRemoveCommand("pacman", "curl")).toBe(
"pacman -R --noconfirm curl",
);
});
it("returns null when no package manager was detected", () => {
expect(buildRemoveCommand(null, "curl")).toBeNull();
});
});
@@ -0,0 +1,206 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import express, { type RequestHandler } from "express";
import request from "supertest";
const state = vi.hoisted(() => ({
isAdmin: true,
access: { hasAccess: true, isOwner: true },
saved: [] as unknown[],
resets: [] as unknown[],
audits: [] as unknown[],
folders: new Map<number, { id: number; userId: string; name: string }>(),
}));
vi.mock("../../../utils/logger.js", () => ({
databaseLogger: { error: vi.fn(), warn: vi.fn(), info: vi.fn() },
}));
vi.mock("../../../utils/audit-logger.js", () => ({
logAudit: async (entry: unknown) => {
state.audits.push(entry);
},
getAuditUsername: async () => "admin",
getRequestMeta: () => ({ ipAddress: "127.0.0.1", userAgent: "test" }),
}));
vi.mock("../../../utils/permission-manager.js", () => ({
PermissionManager: {
getInstance: () => ({
canAccessHost: async () => state.access,
hasPermission: async () => state.isAdmin,
}),
},
}));
vi.mock("../../../hosts/usable-credential.js", () => ({
findUsableCredential: async () => ({}),
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentHostDefaultsRepository: () => ({
findFolder: async (id: number) => state.folders.get(id) ?? null,
ensureFolder: async () => 42,
listHosts: async () => [{ id: 1, userId: "u1" }],
}),
}));
vi.mock("../../../hosts/defaults/materialize.js", () => ({
currentCatalog: () => ({ catalog: new Map() }),
materializeHosts: async () => ({ changedHostIds: [1, 2] }),
}));
vi.mock("../../../hosts/defaults/recompute.js", () => ({
getRecomputeJob: (id: string) =>
id === "job-1" ? { id, status: "done", changedHosts: 3 } : undefined,
recompute: async () => ({ changedHostIds: [5] }),
startRecomputeJob: () => ({ id: "job-1" }),
targetForScope: () => ({ all: true }),
}));
vi.mock("../../../hosts/defaults/service.js", () => ({
levelsAbove: async () => ({ admin: new Map(), user: new Map(), folders: [] }),
readLevel: async () => ({ "core.sshPort": 2022 }),
resolveAll: () => ({}),
resolveForEditor: async () => ({
"core.sshPort": { value: 2022, source: { level: "user" } },
}),
saveLevel: async (scope: unknown, change: unknown) => {
state.saved.push({ scope, change });
},
validateLevelChange: async (
_scope: unknown,
input: { set?: Record<string, unknown> },
) =>
input.set && "bad.key" in input.set
? { set: new Map(), unset: new Set(), errors: { "bad.key": "no" } }
: {
set: new Map(Object.entries(input.set ?? {})),
unset: new Set(),
errors: {},
},
}));
vi.mock("../../../hosts/defaults/overrides.js", () => ({
changeHostOverrides: async (hostIds: number[], change: unknown) => {
state.resets.push({ hostIds, change });
},
}));
vi.mock("../../../database/routes/host-bulk-routes.js", async () => {
const actual = await vi.importActual<
typeof import("../../../database/routes/host-bulk-routes.js")
>("../../../database/routes/host-bulk-routes.js");
return { readDefaultsReset: actual.readDefaultsReset };
});
const { registerHostDefaultsRoutes } =
await import("../../../database/routes/host-defaults-routes.js");
const pass: RequestHandler = (_req, _res, next) => next();
const adminOnly: RequestHandler = (_req, res, next) =>
state.isAdmin ? next() : void res.status(403).json({ error: "no" });
function app() {
const router = express.Router();
router.use((req, _res, next) => {
(req as unknown as { userId: string }).userId = "u1";
next();
});
registerHostDefaultsRoutes(router, {
authenticateJWT: pass,
requireEditPermission: pass,
requireDataAccess: pass,
requireAdminSettings: adminOnly,
});
const server = express();
server.use(express.json());
server.use("/host", router);
return server;
}
beforeEach(() => {
state.isAdmin = true;
state.access = { hasAccess: true, isOwner: true };
state.saved = [];
state.resets = [];
state.audits = [];
state.folders = new Map([
[1, { id: 1, userId: "u1", name: "Prod" }],
[2, { id: 2, userId: "u2", name: "Theirs" }],
]);
});
describe("host defaults routes", () => {
it("keeps the server level to admins", async () => {
state.isAdmin = false;
expect((await request(app()).get("/host/defaults/admin")).status).toBe(403);
expect(
(await request(app()).put("/host/defaults/admin").send({ set: {} }))
.status,
).toBe(403);
});
it("saves the server level as a background job, audited", async () => {
const response = await request(app())
.put("/host/defaults/admin")
.send({ set: { "core.sshPort": 2022 } });
expect(response.body).toEqual({ jobId: "job-1" });
expect(state.audits).toHaveLength(1);
const job = await request(app()).get("/host/defaults/jobs/job-1");
expect(job.body.changedHosts).toBe(3);
});
it("saves a user's own level and says how many hosts changed", async () => {
const response = await request(app())
.put("/host/defaults/user")
.send({ set: { "core.sshPort": 2022 } });
expect(response.body).toEqual({ changedHosts: 1 });
expect(state.saved[0]).toMatchObject({
scope: { level: "user", userId: "u1" },
});
});
it("reports rejected values", async () => {
const response = await request(app())
.put("/host/defaults/user")
.send({ set: { "bad.key": 1 } });
expect(response.status).toBe(400);
expect(response.body.errors).toEqual({ "bad.key": "no" });
});
it("only opens a folder the user owns", async () => {
expect((await request(app()).get("/host/defaults/folders/1")).status).toBe(
200,
);
expect((await request(app()).get("/host/defaults/folders/2")).status).toBe(
404,
);
const created = await request(app())
.post("/host/defaults/folders")
.send({ name: "New" });
expect(created.body).toEqual({ id: 42 });
});
it("previews a change without saving it", async () => {
const response = await request(app())
.post("/host/defaults/preview")
.send({ level: "user", set: { "core.sshPort": 1 } });
expect(response.body).toEqual({ changedHosts: 2 });
expect(state.saved).toEqual([]);
});
it("resolves a host's defaults for the editor", async () => {
const response = await request(app()).get(
"/host/defaults/resolve?hostId=1",
);
expect(response.body.values["core.sshPort"].value).toBe(2022);
});
it("resets a host, but never a shared editor over the owner's login", async () => {
await request(app())
.post("/host/db/host/7/reset-defaults")
.send({ keys: ["core.sshPort"] });
expect(state.resets).toHaveLength(1);
state.access = { hasAccess: true, isOwner: false };
const all = await request(app())
.post("/host/db/host/7/reset-defaults")
.send({ all: true });
expect(all.status).toBe(403);
expect(
(await request(app()).post("/host/db/host/7/reset-defaults").send({}))
.status,
).toBe(400);
});
});
@@ -98,7 +98,6 @@ describe("applyHostEnrollmentDefaults", () => {
ip: "server.example",
port: 22,
authType: "none",
enableTerminal: true,
enableSsh: true,
});
});
@@ -109,12 +108,12 @@ describe("applyHostEnrollmentDefaults", () => {
ip: "server.example",
port: 2222,
authType: "password",
enableTerminal: false,
enableSsh: false,
}),
).toMatchObject({
port: 2222,
authType: "password",
enableTerminal: false,
enableSsh: false,
});
});
});
@@ -5,8 +5,23 @@ const mocks = vi.hoisted(() => ({
create: vi.fn(),
update: vi.fn(),
list: vi.fn(),
applyPluginSettings: vi.fn(),
}));
vi.mock("../../../database/routes/host-plugin-settings.js", () => ({
applyPluginHostImportSettings: mocks.applyPluginSettings,
setHostPluginEnabled: vi.fn(),
}));
vi.mock("../../../hosts/defaults/index.js", () => ({
applyHostDefaultsToWrite: async () => ({ core: [] }),
applyDefaultsAfterHostWrite: async () => {},
}));
vi.mock("../../../hosts/defaults/overrides.js", () => ({
changeHostOverrides: async () => {},
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentHostDefaultsRepository: () => ({
listHosts: async () => [],
}),
createCurrentCredentialRepository: () => ({
listDecryptedByUserId: async () => [],
}),
@@ -37,8 +52,12 @@ const host = {
port: 22,
username: "alice",
authType: "none",
enableCommandHistory: false,
enableTerminalToolbar: false,
pluginSettings: {
"ssh-terminal": {
enableCommandHistory: false,
enableTerminalToolbar: false,
},
},
terminalConfig: { macOptionIsMeta: false },
};
beforeEach(() => {
@@ -49,7 +68,7 @@ beforeEach(() => {
});
it.each([false, true])(
"preserves disabled terminal settings through export selection and import (overwrite=%s)",
"carries plugin host settings through export selection and import (overwrite=%s)",
async (overwrite) => {
const payload = buildExportPayload(
{ hosts: [host] },
@@ -71,10 +90,10 @@ it.each([false, true])(
const write = overwrite ? mocks.update : mocks.create;
expect(write).toHaveBeenCalledTimes(1);
const saved = write.mock.calls[0].at(-1);
expect(saved).toMatchObject({
enableCommandHistory: false,
enableTerminalToolbar: false,
});
expect(mocks.applyPluginSettings).toHaveBeenCalledWith(
overwrite ? 19 : 71,
expect.objectContaining({ pluginSettings: host.pluginSettings }),
);
expect(JSON.parse(saved.terminalConfig)).toEqual({
macOptionIsMeta: false,
});
@@ -94,49 +113,66 @@ async function importHosts(
return res;
}
it("imports forward jump references first and replaces source IDs with destination IDs", async () => {
mocks.create
.mockResolvedValueOnce({ id: 501 })
.mockResolvedValueOnce({ id: 502 });
const raw = {
hosts: [
{ ...host, exportId: 10, jumpHosts: [{ hostId: 20 }] },
{ ...host, ip: "192.0.2.2", exportId: 20 },
],
};
const payload = buildExportPayload(raw, null, new Set(["jumpHosts"]), false);
const res = await importHosts(payload.hosts);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ success: 2, failed: 0 }),
);
expect(mocks.create.mock.calls[0][1].ip).toBe("192.0.2.2");
expect(JSON.parse(mocks.create.mock.calls[1][1].jumpHosts)).toEqual([
{ hostId: 501 },
]);
expect(mocks.create.mock.calls[1][1]).not.toHaveProperty("exportId");
expect(mocks.create.mock.calls[1][1]).not.toHaveProperty("id");
});
it.each([20, "20"])(
"imports forward jump reference %j and replaces source IDs with destination IDs",
async (jumpId) => {
mocks.create
.mockResolvedValueOnce({ id: 501 })
.mockResolvedValueOnce({ id: 502 });
const raw = {
hosts: [
{ ...host, exportId: 10, jumpHosts: [{ hostId: jumpId }] },
{ ...host, ip: "192.0.2.2", exportId: 20 },
],
};
const payload = buildExportPayload(
raw,
null,
new Set(["jumpHosts"]),
false,
);
const res = await importHosts(payload.hosts);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ success: 2, failed: 0 }),
);
expect(mocks.create.mock.calls[0][1].ip).toBe("192.0.2.2");
expect(JSON.parse(mocks.create.mock.calls[1][1].jumpHosts)).toEqual([
{ hostId: 501 },
]);
expect(mocks.create.mock.calls[1][1]).not.toHaveProperty("exportId");
expect(mocks.create.mock.calls[1][1]).not.toHaveProperty("id");
},
);
it("maps overwritten jump hosts to their existing destination ID", async () => {
mocks.list.mockResolvedValue([{ ...host, ip: "192.0.2.2", id: 801 }]);
const res = await importHosts(
[
{ ...host, exportId: 10, jumpHosts: [{ hostId: 20 }] },
{ ...host, ip: "192.0.2.2", exportId: 20 },
],
true,
);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ success: 1, updated: 1, failed: 0 }),
);
expect(JSON.parse(mocks.create.mock.calls[0][1].jumpHosts)).toEqual([
{ hostId: 801 },
]);
});
it.each([20, "20"])(
"maps overwritten jump reference %j to its existing destination ID",
async (jumpId) => {
mocks.list.mockResolvedValue([{ ...host, ip: "192.0.2.2", id: 801 }]);
const res = await importHosts(
[
{ ...host, exportId: 10, jumpHosts: [{ hostId: jumpId }] },
{ ...host, ip: "192.0.2.2", exportId: 20 },
],
true,
);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ success: 1, updated: 1, failed: 0 }),
);
expect(JSON.parse(mocks.create.mock.calls[0][1].jumpHosts)).toEqual([
{ hostId: 801 },
]);
},
);
it.each([
[{ ...host, jumpHosts: [{ hostId: 20 }] }],
[{ ...host, jumpHosts: [{ hostId: "20" }] }],
[{ ...host, exportId: 10, jumpHosts: [{ hostId: 10 }] }],
[{ ...host, exportId: 10, jumpHosts: [{ hostId: "10" }] }],
[
{ ...host, exportId: 10, jumpHosts: [{ hostId: "20oops" }] },
{ ...host, exportId: 20 },
],
[
{ ...host, exportId: 10 },
{ ...host, exportId: 10 },
@@ -1,4 +1,5 @@
import { describe, it, expect } from "vitest";
import { afterEach, describe, it, expect } from "vitest";
import { setHostProtocolSource } from "../../../hosts/protocol-auth/registry.js";
import {
applyHostKeyTypeUpdate,
containsOwnerPrivateAuthUpdate,
@@ -47,13 +48,13 @@ describe("containsOwnerPrivateAuthUpdate", () => {
);
});
it("keeps protocol field definitions isolated", () => {
expect(containsOwnerPrivateAuthUpdate({ rdpCredentialId: 7 }, "rdp")).toBe(
true,
);
expect(containsOwnerPrivateAuthUpdate({ rdpCredentialId: 7 }, "ssh")).toBe(
false,
);
it("leaves plugin protocol logins to their own guard", () => {
expect(
containsOwnerPrivateAuthUpdate(
{ protocolAuth: { spice: { credentialId: 7 } } },
"ssh",
),
).toBe(false);
});
it("allows shared editors to update non-authentication host settings", () => {
@@ -105,15 +106,10 @@ describe("normalizeProtocolEnableFields", () => {
expect(normalizeProtocolEnableFields({ name: "server" })).toEqual({});
});
it("converts explicitly provided protocol booleans to database integers", () => {
it("converts an explicitly provided SSH switch to a database integer", () => {
expect(
normalizeProtocolEnableFields({
enableSsh: true,
enableRdp: false,
enableVnc: undefined,
enableTelnet: true,
}),
).toEqual({ enableSsh: 1, enableRdp: 0, enableTelnet: 1 });
normalizeProtocolEnableFields({ enableSsh: true, enableRdp: false }),
).toEqual({ enableSsh: 1 });
});
});
@@ -174,14 +170,43 @@ describe("normalizeImportedHost", () => {
expect(host.connectionType).toBe("ssh");
expect(host.port).toBe(22);
expect(host.enableSsh).toBe(true);
expect(host.enableRdp).toBe(false);
});
it("infers rdp from enableRdp and uses default rdp port", () => {
const host = normalizeImportedHost({ enableRdp: true, ip: "10.0.0.2" });
expect(host.connectionType).toBe("rdp");
expect(host.port).toBe(3389);
expect(host.enableRdp).toBe(true);
describe("with a plugin protocol declared", () => {
afterEach(() => setHostProtocolSource(() => []));
function declareSpice() {
setHostProtocolSource(() => [
{
id: "spice",
defaultPort: 5930,
pluginId: "spice-plugin",
pluginName: "Spice",
},
]);
}
it("infers the protocol from its enable flag and uses its default port", () => {
declareSpice();
const host = normalizeImportedHost({ enableSpice: true, ip: "10.0.0.2" });
expect(host.connectionType).toBe("spice");
expect(host.port).toBe(5930);
expect(host.enableSsh).toBe(false);
});
it("reads the protocol's own port field", () => {
declareSpice();
const host = normalizeImportedHost({
connectionType: "spice",
spicePort: 5999,
});
expect(host.port).toBe(5999);
});
it("ignores the flag of a protocol nobody declares", () => {
const host = normalizeImportedHost({ enableSpice: true });
expect(host.connectionType).toBe("ssh");
});
});
it("honors an explicit port over protocol defaults", () => {
@@ -273,87 +298,53 @@ describe("stripSensitiveFields", () => {
).toBeUndefined();
});
it("strips rdp/vnc/telnet passwords and adds their presence flags", () => {
const result = stripSensitiveFields({
name: "rdp-box",
rdpPassword: "rdp-secret",
vncPassword: "vnc-secret",
telnetPassword: "telnet-secret",
});
expect(result.rdpPassword).toBeUndefined();
expect(result.vncPassword).toBeUndefined();
expect(result.telnetPassword).toBeUndefined();
expect(result.hasRdpPassword).toBe(true);
expect(result.hasVncPassword).toBe(true);
expect(result.hasTelnetPassword).toBe(true);
});
it("marks rdp/vnc/telnet presence flags false when absent", () => {
const result = stripSensitiveFields({ name: "rdp-box" });
expect(result.hasRdpPassword).toBe(false);
expect(result.hasVncPassword).toBe(false);
expect(result.hasTelnetPassword).toBe(false);
it("leaves protocol login summaries alone for the owner", () => {
const protocolAuth = {
spice: { authType: "direct", hasPassword: true, secretFieldKeys: [] },
};
expect(stripSensitiveFields({ protocolAuth }).protocolAuth).toEqual(
protocolAuth,
);
});
});
describe("transformHostResponse", () => {
it("parses tags and coerces enable flags to booleans", () => {
it("parses tags and coerces flags to booleans", () => {
const result = transformHostResponse({
tags: "a,b,c",
enableTerminal: 1,
enableTunnel: 0,
shareSshAuth: 1,
pin: 1,
});
expect(result.tags).toEqual(["a", "b", "c"]);
expect(result.enableTerminal).toBe(true);
expect(result.enableTunnel).toBe(false);
expect(result.shareSshAuth).toBe(true);
expect(result.pin).toBe(true);
});
it("parses JSON array fields and defaults them to []", () => {
const result = transformHostResponse({
tunnelConnections: '[{"sourcePort":8080}]',
jumpHosts: null,
jumpHosts: '[{"hostId":8}]',
portKnockSequence: null,
});
expect(result.tunnelConnections).toEqual([{ sourcePort: 8080 }]);
expect(result.jumpHosts).toEqual([]);
expect(result.jumpHosts).toEqual([{ hostId: 8 }]);
expect(result.portKnockSequence).toEqual([]);
});
it("infers protocol flags for a migrated non-ssh host", () => {
it("leaves the 2.8 quick_actions column out, for its plugin to put back", () => {
const result = transformHostResponse({
connectionType: "rdp",
enableSsh: true,
quickActions: '[{"name":"x","snippetId":1}]',
});
expect(result.enableSsh).toBe(false);
expect(result.enableRdp).toBe(true);
expect(result.quickActions).toBeUndefined();
});
it("applies default protocol ports", () => {
it("passes the stored SSH switch through", () => {
// The remote desktop migration corrects connection_type-only hosts once.
expect(transformHostResponse({ enableSsh: false }).enableSsh).toBe(false);
});
it("applies the default SSH port", () => {
const result = transformHostResponse({ port: 22 });
expect(result.sshPort).toBe(22);
expect(result.rdpPort).toBe(3389);
expect(result.vncPort).toBe(5900);
expect(result.telnetPort).toBe(23);
});
it("coerces enableProxmox and parses proxmoxConfig", () => {
const result = transformHostResponse({
enableProxmox: 1,
proxmoxConfig: '{"defaultCredentialId":3,"windowsPatterns":"win"}',
});
expect(result.enableProxmox).toBe(true);
expect(result.proxmoxConfig).toEqual({
defaultCredentialId: 3,
windowsPatterns: "win",
});
});
it("defaults enableProxmox to false when absent", () => {
const result = transformHostResponse({ port: 22 });
expect(result.enableProxmox).toBe(false);
expect(result.proxmoxConfig).toBeUndefined();
expect(result).not.toHaveProperty("rdpPort");
});
});
@@ -379,8 +370,17 @@ describe("sanitizeHostForRecipient", () => {
password: "hunter2",
key: "PRIVATE",
sudoPassword: "sudo",
rdpPassword: "rdp",
socks5Password: "socks",
protocolAuth: {
spice: {
authType: "direct",
credentialId: null,
username: "viewer",
fields: { display: "0" },
hasPassword: true,
secretFieldKeys: ["ticket"],
},
},
enableSsh: true,
enableRdp: true,
sshPort: 22,
@@ -398,8 +398,15 @@ describe("sanitizeHostForRecipient", () => {
expect(result.password).toBeUndefined();
expect(result.key).toBeUndefined();
expect(result.sudoPassword).toBeUndefined();
expect(result.rdpPassword).toBeUndefined();
expect(result.socks5Password).toBeUndefined();
expect(result.protocolAuth).toEqual({
spice: {
authType: "direct",
credentialId: null,
username: "viewer",
fields: { display: "0" },
},
});
expect(result.credentialId).toBeUndefined();
expect(result.overrideCredentialUsername).toBeUndefined();
expect(result.terminalConfig).toEqual({ theme: "termix" });
@@ -431,7 +438,6 @@ describe("sanitizeHostForRecipient", () => {
{
...sharedHost,
permissionLevel: "connect",
rdpAuthType: "none",
authOverrides: {
ssh: {
credentialId: 9,
@@ -444,9 +450,7 @@ describe("sanitizeHostForRecipient", () => {
);
expect(result.name).toBe("prod");
expect(result.ip).toBe("10.0.0.42");
expect(result.enableRdp).toBe(true);
expect(result.rdpPort).toBe(3389);
expect(result.rdpAuthType).toBe("none");
expect(result.protocolAuth).toEqual({ spice: { authType: "direct" } });
expect(result.permissionLevel).toBe("connect");
expect(result.shareSshAuth).toBe(true);
expect(result.authOverrides).toEqual({
@@ -461,3 +465,54 @@ describe("sanitizeHostForRecipient", () => {
expect(result.password).toBeUndefined();
});
});
describe("transformHostResponse terminal fields", () => {
const row = (extra: Record<string, unknown>) =>
transformHostResponse({ id: 1, tags: "", ...extra });
it("sends the SSH options and core's own terminalConfig keys only", () => {
const host = row({
sshOptions: JSON.stringify({ keepaliveInterval: 20 }),
terminalConfig: JSON.stringify({
startupSnippetId: 3,
theme: "nord",
keepaliveInterval: 5,
}),
});
expect(host.sshOptions).toEqual({ keepaliveInterval: 20 });
expect(host.terminalConfig).toEqual({ keepaliveInterval: 20 });
});
it("reads the options out of terminal_config before the boot copy", () => {
const host = row({
sshOptions: null,
terminalConfig: JSON.stringify({ agentForwarding: true }),
});
expect(host.sshOptions).toEqual({ agentForwarding: true });
});
it("surfaces a 2.8 sudo password for the sanitizers to strip", () => {
const host = row({
sudoPassword: null,
terminalConfig: JSON.stringify({ sudoPassword: "legacy" }),
});
const stripped = stripSensitiveFields(host);
expect(stripped.hasSudoPassword).toBe(true);
expect(stripped).not.toHaveProperty("sudoPassword");
expect(JSON.stringify(stripped)).not.toContain("legacy");
});
it("hides the owner's agent socket from a shared recipient", () => {
const shared = sanitizeHostForRecipient(
row({
sshOptions: JSON.stringify({
agentSocketPath: "/run/agent",
keepaliveInterval: 9,
}),
}),
"edit",
);
expect(shared.sshOptions).toEqual({ keepaliveInterval: 9 });
expect(shared.terminalConfig).toEqual({ keepaliveInterval: 9 });
});
});
@@ -0,0 +1,494 @@
/**
* The pluginSettings map attached to host responses.
*
* The host editor needs these with the host, not one request per plugin per
* host, so the shape and the query count both matter.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { PluginManifest } from "@termix/plugin-sdk/manifest";
interface Row {
pluginId: string;
scope: string;
scopeId: string | null;
key: string;
value: string | null;
encrypted: boolean;
}
const rows: Row[] = [];
const loaded: { id: string; manifest: PluginManifest; state: string }[] = [];
const getAllForScopeIds = vi.fn(async (scope: string, scopeIds: string[]) =>
rows.filter(
(row) => row.scope === scope && scopeIds.includes(row.scopeId ?? ""),
),
);
const setCalls: Array<[string, string, string, string, string]> = [];
const set = vi.fn(
async (
pluginId: string,
scope: string,
scopeId: string,
key: string,
value: string,
) => {
setCalls.push([pluginId, scope, scopeId, key, value]);
},
);
vi.mock("../../../utils/logger.js", () => {
const logger = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
success: vi.fn(),
};
return { sshLogger: logger, pluginLogger: logger, databaseLogger: logger };
});
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentPluginSettingsRepository: () => ({ getAllForScopeIds, set }),
}));
vi.mock("../../../hosts/defaults/overrides.js", () => ({
changeHostOverrides: async () => {},
}));
vi.mock("../../../plugins/index.js", () => ({
getPluginRuntime: () => ({ loader: { list: () => loaded } }),
}));
vi.mock("../../../utils/system-secret-crypto.js", () => ({
isSystemEncrypted: (value: string) => value.startsWith("sysenc:v1:"),
encryptSystemSecret: async (plaintext: string) => plaintext,
decryptSystemSecret: async (stored: string) => stored,
}));
vi.mock("../../../utils/crypto-migration/raw-rows.js", () => ({
runStatement: vi.fn(async () => {}),
}));
const registryProviders = new Map<string, unknown>();
vi.mock("../../../plugins/registry.js", () => ({
consume: (key: string) => registryProviders.get(key),
}));
const {
attachHostPluginSettings,
loadHostPluginSettings,
withHostPluginSettings,
writeHostPluginSettings,
applyPluginHostImportSettings,
setHostPluginEnabled,
checkHostPluginSettingsInput,
} = await import("../../../database/routes/host-plugin-settings.js");
function manifest(id: string, host: unknown): PluginManifest {
return {
id,
name: id,
version: "1.0.0",
description: "",
author: { name: "t" },
license: "MIT",
category: "Productivity",
engine: { termix: ">=2.9.0", api: "1" },
capabilities: [],
contributes: { settings: { host } },
} as PluginManifest;
}
const DOCKER = manifest("docker", {
enableKey: "enableDocker",
enableLabelKey: "k",
fields: [{ key: "socketPath", type: "string", labelKey: "k" }],
});
beforeEach(() => {
rows.length = 0;
loaded.length = 0;
setCalls.length = 0;
registryProviders.clear();
getAllForScopeIds.mockClear();
set.mockClear();
});
describe("loadHostPluginSettings", () => {
it("returns nothing when no plugin declares host settings", async () => {
loaded.push({
id: "other",
manifest: manifest("other", undefined),
state: "active",
});
const result = await loadHostPluginSettings([1, 2]);
expect(result.size).toBe(0);
expect(getAllForScopeIds).not.toHaveBeenCalled();
});
it("ignores a plugin that is not running", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "disabled" });
const result = await loadHostPluginSettings([1]);
expect(result.size).toBe(0);
});
it("uses one query for the whole list", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
await loadHostPluginSettings([1, 2, 3, 4, 5]);
expect(getAllForScopeIds).toHaveBeenCalledTimes(1);
expect(getAllForScopeIds).toHaveBeenCalledWith("host", [
"1",
"2",
"3",
"4",
"5",
]);
});
it("merges stored values over declared defaults", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
rows.push({
pluginId: "docker",
scope: "host",
scopeId: "1",
key: "enableDocker",
value: JSON.stringify(true),
encrypted: false,
});
const result = await loadHostPluginSettings([1, 2]);
expect(result.get(1)).toEqual({
docker: { enableDocker: true, socketPath: undefined },
});
// Host 2 has nothing stored, so it falls back to the declared default.
expect(result.get(2)).toEqual({
docker: { enableDocker: false, socketPath: undefined },
});
});
it("keeps one host's values out of another's", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
rows.push({
pluginId: "docker",
scope: "host",
scopeId: "1",
key: "socketPath",
value: JSON.stringify("/var/run/docker.sock"),
encrypted: false,
});
const result = await loadHostPluginSettings([1, 2]);
expect(result.get(1)!.docker.socketPath).toBe("/var/run/docker.sock");
expect(result.get(2)!.docker.socketPath).toBeUndefined();
});
it("redacts a host-scope secret", async () => {
loaded.push({
id: "vault",
manifest: manifest("vault", {
fields: [{ key: "token", type: "secret", labelKey: "k" }],
}),
state: "active",
});
rows.push({
pluginId: "vault",
scope: "host",
scopeId: "1",
key: "token",
value: JSON.stringify("s.verysecret"),
encrypted: true,
});
const result = await loadHostPluginSettings([1]);
expect(result.get(1)!.vault.token).toEqual({ set: true });
expect(JSON.stringify(result.get(1))).not.toContain("verysecret");
});
it("survives a failed settings read rather than failing the host list", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
getAllForScopeIds.mockRejectedValueOnce(new Error("database is away"));
await expect(loadHostPluginSettings([1])).resolves.toEqual(new Map());
});
it("does nothing for an empty host list", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
expect((await loadHostPluginSettings([])).size).toBe(0);
expect(getAllForScopeIds).not.toHaveBeenCalled();
});
});
describe("attachHostPluginSettings", () => {
it("attaches values to the matching host", () => {
const hosts = [{ id: 1 }, { id: 2 }] as Record<string, unknown>[];
const settings = new Map([[1, { docker: { enableDocker: true } }]]);
attachHostPluginSettings(hosts, settings);
expect(hosts[0].pluginSettings).toEqual({ docker: { enableDocker: true } });
expect(hosts[1].pluginSettings).toBeUndefined();
});
it("leaves hosts alone when there is nothing to attach", () => {
const hosts = [{ id: 1 }] as Record<string, unknown>[];
attachHostPluginSettings(hosts, new Map());
expect(hosts[0]).toEqual({ id: 1 });
});
});
describe("withHostPluginSettings", () => {
it("adds the map to a single host", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
const result = await withHostPluginSettings({ id: 1, name: "web" });
expect(result.name).toBe("web");
expect(result.pluginSettings).toEqual({
docker: { enableDocker: false, socketPath: undefined },
});
});
it("returns the host unchanged when nothing contributes", async () => {
const host = { id: 1, name: "web" };
expect(await withHostPluginSettings(host)).toBe(host);
});
it("returns the host unchanged when its id is not a number", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
const host = { name: "web" };
expect(await withHostPluginSettings(host)).toBe(host);
});
});
describe("writeHostPluginSettings", () => {
it("writes each value through the settings service, under the plugin's own namespace", async () => {
await writeHostPluginSettings(DOCKER, 7, {
enableDocker: true,
socketPath: "/var/run/docker.sock",
});
expect(setCalls).toEqual([
["docker", "host", "7", "enableDocker", "true"],
["docker", "host", "7", "socketPath", '"/var/run/docker.sock"'],
]);
});
it("refuses a key the manifest does not declare", async () => {
await writeHostPluginSettings(DOCKER, 7, { injected: "x" });
expect(setCalls).toEqual([]);
});
it("skips a field whose value is undefined", async () => {
await writeHostPluginSettings(DOCKER, 7, {
enableDocker: true,
socketPath: undefined,
});
expect(setCalls).toEqual([["docker", "host", "7", "enableDocker", "true"]]);
});
});
describe("applyPluginHostImportSettings", () => {
it("runs every enabled plugin's registered normalizer and writes what it returns", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
loaded.push({
id: "web-endpoint",
manifest: manifest("web-endpoint", {
enableKey: "enableWebUi",
enableLabelKey: "k",
fields: [{ key: "webUiConfig", type: "json", labelKey: "k" }],
}),
state: "active",
});
registryProviders.set("docker.hostImportNormalizer", () => ({
enableDocker: true,
}));
registryProviders.set("web-endpoint.hostImportNormalizer", () => null);
await applyPluginHostImportSettings(7, { enableDocker: true });
expect(setCalls).toEqual([["docker", "host", "7", "enableDocker", "true"]]);
});
it("skips a plugin with no registered normalizer", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
await applyPluginHostImportSettings(7, {});
expect(setCalls).toEqual([]);
});
it("logs and continues past a normalizer that throws", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
loaded.push({
id: "web-endpoint",
manifest: manifest("web-endpoint", {
enableKey: "enableWebUi",
enableLabelKey: "k",
fields: [{ key: "webUiConfig", type: "json", labelKey: "k" }],
}),
state: "active",
});
registryProviders.set("docker.hostImportNormalizer", () => {
throw new Error("boom");
});
registryProviders.set("web-endpoint.hostImportNormalizer", () => ({
enableWebUi: true,
}));
await expect(applyPluginHostImportSettings(7, {})).resolves.toBeUndefined();
expect(setCalls).toEqual([
["web-endpoint", "host", "7", "enableWebUi", "true"],
]);
});
});
describe("share levels, legacy fields and generic writes", () => {
const DESKTOP = manifest("remote-desktop", {
fields: [
{ key: "enableRdp", type: "boolean", labelKey: "k" },
{
key: "guacamoleConfig",
type: "json",
labelKey: "k",
shareRead: "edit",
},
{ key: "gatewayToken", type: "secret", labelKey: "k" },
],
});
it("hides a field above a recipient's share level", () => {
loaded.push({ id: "remote-desktop", manifest: DESKTOP, state: "active" });
const values = new Map([
[
1,
{
"remote-desktop": { enableRdp: true, guacamoleConfig: { a: 1 } },
},
],
]);
const connect = { id: 1, isShared: true, permissionLevel: "connect" };
const edit = { id: 1, isShared: true, permissionLevel: "edit" };
const owner = { id: 1 };
attachHostPluginSettings([connect, edit, owner], values);
expect(connect).toMatchObject({
pluginSettings: { "remote-desktop": { enableRdp: true } },
});
expect(
(connect as { pluginSettings: Record<string, Record<string, unknown>> })
.pluginSettings["remote-desktop"],
).not.toHaveProperty("guacamoleConfig");
expect(edit).toMatchObject({
pluginSettings: { "remote-desktop": { guacamoleConfig: { a: 1 } } },
});
expect(owner).toMatchObject({
pluginSettings: { "remote-desktop": { guacamoleConfig: { a: 1 } } },
});
});
it("adds a plugin's legacy payload fields without overwriting core's", () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
registryProviders.set(
"docker.hostPayloadLegacy",
(own: Record<string, unknown>) => ({
enableDocker: own.enableDocker,
name: "overwritten?",
}),
);
const host: Record<string, unknown> = { id: 2, name: "web" };
attachHostPluginSettings(
[host],
new Map([[2, { docker: { enableDocker: true } }]]),
);
expect(host.enableDocker).toBe(true);
expect(host.name).toBe("web");
});
it("adds a plugin's keys to an object core already sends, never over core's", () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
registryProviders.set("docker.hostPayloadLegacy", () => ({
terminalConfig: { theme: "nord", startupSnippetId: 99 },
}));
const host: Record<string, unknown> = {
id: 2,
terminalConfig: { startupSnippetId: 1 },
};
attachHostPluginSettings(
[host],
new Map([[2, { docker: { enableDocker: true } }]]),
);
expect(host.terminalConfig).toEqual({ theme: "nord", startupSnippetId: 1 });
});
it("imports an export's plugin values, leaving secrets out", async () => {
loaded.push({ id: "remote-desktop", manifest: DESKTOP, state: "active" });
await applyPluginHostImportSettings(9, {
pluginSettings: {
"remote-desktop": { enableRdp: true, gatewayToken: { set: true } },
},
});
expect(setCalls).toEqual([
["remote-desktop", "host", "9", "enableRdp", "true"],
]);
});
it("flips a plugin's host switch for many hosts", async () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
expect(await setHostPluginEnabled("docker", [3, 4], true)).toBe(true);
expect(setCalls.map((call) => [call[2], call[3], call[4]])).toEqual([
["3", "enableDocker", "true"],
["4", "enableDocker", "true"],
]);
expect(await setHostPluginEnabled("missing", [3], true)).toBe(false);
});
});
describe("checkHostPluginSettingsInput", () => {
it("passes declared keys through to the plugin that owns them", () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
const result = checkHostPluginSettingsInput({
docker: { enableDocker: true, socketPath: "/run/docker.sock" },
});
expect(result.errors).toEqual([]);
expect(result.skipped).toEqual([]);
expect(result.writes).toEqual([
{
manifest: DOCKER,
values: { enableDocker: true, socketPath: "/run/docker.sock" },
},
]);
});
it("refuses a key the plugin does not declare and a value it rejects", () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "active" });
const { errors } = checkHostPluginSettingsInput({
docker: { dockerConfig: {}, enableDocker: "sure" },
});
expect(errors).toHaveLength(2);
expect(errors[0]).toContain("docker.dockerConfig");
expect(errors[1]).toContain("docker.enableDocker");
});
it("skips a plugin that is not running", () => {
loaded.push({ id: "docker", manifest: DOCKER, state: "disabled" });
const result = checkHostPluginSettingsInput({
docker: { enableDocker: true },
});
expect(result).toEqual({ writes: [], skipped: ["docker"], errors: [] });
});
});
@@ -0,0 +1,197 @@
import http from "node:http";
import type { AddressInfo } from "node:net";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import express, { type RequestHandler } from "express";
const state = vi.hoisted(() => ({
settings: {} as Record<string, string>,
locked: false,
accessible: new Set<number>([1, 2]),
statuses: new Map<number, { status: string; lastChecked: string }>(),
}));
const service = vi.hoisted(() => ({
statusesFor: vi.fn(),
get: vi.fn(),
check: vi.fn(),
refresh: vi.fn(),
retimeAll: vi.fn(),
}));
vi.mock("../../../utils/logger.js", () => ({
sshLogger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
}));
vi.mock("../../../utils/data-crypto.js", () => ({
DataCrypto: { getUserDataKey: () => (state.locked ? null : "key") },
}));
vi.mock("../../../utils/permission-manager.js", () => ({
PermissionManager: {
getInstance: () => ({
filterAccessibleHostIds: async (_user: string, ids: number[]) =>
new Set(ids.filter((id) => state.accessible.has(id))),
canAccessHost: async (_user: string, id: number) => ({
hasAccess: state.accessible.has(id),
}),
}),
},
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentSettingsRepository: () => ({
get: async (key: string) => state.settings[key] ?? null,
set: async (key: string, value: string) => {
state.settings[key] = value;
},
}),
}));
vi.mock("../../../hosts/status/host-status-service.js", () => ({
DEFAULT_STATUS_INTERVAL: 60,
GLOBAL_STATUS_INTERVAL_KEY: "global_status_check_interval",
hostStatusService: service,
}));
const { registerHostStatusRoutes, parseStatusHostIds } =
await import("../../../database/routes/host-status-routes.js");
let server: http.Server | null = null;
let base = "";
async function start(isAdmin = true) {
const router = express.Router();
const authenticateJWT: RequestHandler = (req, _res, next) => {
(req as unknown as { userId: string }).userId = "user-1";
next();
};
const requireAdmin: RequestHandler = (_req, res, next) =>
isAdmin ? next() : void res.status(403).json({ error: "Admin only" });
registerHostStatusRoutes(router, { authenticateJWT, requireAdmin });
const app = express();
app.use(express.json());
app.use("/host", router);
server = http.createServer(app);
await new Promise<void>((resolve) => server!.listen(0, resolve));
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
}
async function call(method: string, path: string, body?: unknown) {
const response = await fetch(`${base}${path}`, {
method,
headers: body ? { "content-type": "application/json" } : {},
body: body ? JSON.stringify(body) : undefined,
});
return { status: response.status, body: await response.json() };
}
beforeEach(() => {
state.settings = {};
state.locked = false;
state.accessible = new Set([1, 2]);
state.statuses = new Map([
[1, { status: "online", lastChecked: "t" }],
[2, { status: "offline", lastChecked: "t" }],
[3, { status: "reachable", lastChecked: "t" }],
]);
service.statusesFor.mockImplementation(async () => state.statuses);
service.get.mockImplementation(
(id: number) => state.statuses.get(id) ?? null,
);
service.check.mockResolvedValue(null);
});
afterEach(async () => {
if (server)
await new Promise<void>((resolve) => server!.close(() => resolve()));
server = null;
vi.clearAllMocks();
});
describe("GET /host/status", () => {
it("only returns hosts the user can reach", async () => {
await start();
const { status, body } = await call("GET", "/host/status");
expect(status).toBe(200);
expect(Object.keys(body)).toEqual(["1", "2"]);
expect(service.statusesFor).toHaveBeenCalledWith("user-1", null);
});
it("narrows to the requested hosts", async () => {
await start();
const { body } = await call("GET", "/host/status?hostIds=2");
expect(Object.keys(body)).toEqual(["2"]);
expect(service.statusesFor).toHaveBeenCalledWith("user-1", new Set([2]));
});
it("answers 401 while the user's data is locked", async () => {
await start();
state.locked = true;
expect((await call("GET", "/host/status")).status).toBe(401);
});
});
describe("GET /host/status/:id", () => {
it("returns one host's status", async () => {
await start();
const { status, body } = await call("GET", "/host/status/1");
expect(status).toBe(200);
expect(body.status).toBe("online");
});
it("hides a host the user cannot reach", async () => {
await start();
expect((await call("GET", "/host/status/3")).status).toBe(404);
});
});
describe("status settings", () => {
it("reads the default interval", async () => {
await start();
expect((await call("GET", "/host/status/settings")).body).toEqual({
statusCheckInterval: 60,
});
});
it("saves a new interval and re-times the checks", async () => {
await start();
const { status } = await call("PUT", "/host/status/settings", {
statusCheckInterval: 90,
});
expect(status).toBe(200);
expect(state.settings.global_status_check_interval).toBe("90");
expect(service.retimeAll).toHaveBeenCalledOnce();
});
it("rejects an interval out of range", async () => {
await start();
expect(
(await call("PUT", "/host/status/settings", { statusCheckInterval: 1 }))
.status,
).toBe(400);
});
it("is admin only", async () => {
await start(false);
expect((await call("GET", "/host/status/settings")).status).toBe(403);
expect(
(await call("PUT", "/host/status/settings", { statusCheckInterval: 90 }))
.status,
).toBe(403);
});
});
describe("POST /host/status/refresh", () => {
it("restarts the user's checks", async () => {
await start();
expect((await call("POST", "/host/status/refresh")).status).toBe(200);
expect(service.refresh).toHaveBeenCalledWith("user-1");
});
});
describe("parseStatusHostIds", () => {
it("tells an unrestricted request from an empty host set", () => {
expect(parseStatusHostIds(undefined)).toBeNull();
expect(parseStatusHostIds("")).toEqual(new Set());
});
it("keeps only valid positive host ids", () => {
expect(parseStatusHostIds("7,2,7,-1,nope,1.5")).toEqual(new Set([7, 2]));
});
});
@@ -0,0 +1,97 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
stored: null as Record<string, unknown> | null,
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentHostResolutionRepository: () => ({
findHostById: async () => state.stored,
}),
}));
const { mergeStoredTerminalFields, parseTerminalConfig } =
await import("../../../database/routes/host-terminal-fields.js");
beforeEach(() => {
state.stored = {
terminalConfig: JSON.stringify({
theme: "nord",
sudoPassword: "legacy-sudo",
agentSocketPath: "/owner/agent",
startupSnippetId: 1,
}),
sshOptions: JSON.stringify({ agentSocketPath: "/owner/agent" }),
};
});
async function merge(
hostData: Record<string, unknown>,
isOwner = true,
sshOptions?: string,
) {
const row: Record<string, unknown> = {
terminalConfig: "replaced wholesale",
...(sshOptions !== undefined ? { sshOptions } : {}),
};
const error = await mergeStoredTerminalFields(row, hostData, 1, "o", isOwner);
return { error, row };
}
describe("parseTerminalConfig", () => {
it("reads objects and JSON, and nothing else", () => {
expect(parseTerminalConfig({ a: 1 })).toEqual({ a: 1 });
expect(parseTerminalConfig('{"a":1}')).toEqual({ a: 1 });
expect(parseTerminalConfig("nope")).toBeNull();
expect(parseTerminalConfig([1])).toBeNull();
});
});
describe("mergeStoredTerminalFields", () => {
it("merges an editor save into the stored 2.8 keys instead of dropping them", async () => {
const { error, row } = await merge({
terminalConfig: { startupSnippetId: 4 },
});
expect(error).toBeNull();
expect(JSON.parse(row.terminalConfig as string)).toEqual({
theme: "nord",
sudoPassword: "legacy-sudo",
agentSocketPath: "/owner/agent",
startupSnippetId: 4,
});
});
it("leaves terminal_config alone when the payload has none", async () => {
const { row } = await merge({});
expect(row).not.toHaveProperty("terminalConfig");
});
it("drops the legacy sudo copy once the owner saves one on its own", async () => {
const { row } = await merge({ sudoPassword: "" });
expect(JSON.parse(row.terminalConfig as string)).not.toHaveProperty(
"sudoPassword",
);
});
it("keeps the owner's private keys through a shared editor's save", async () => {
const { row } = await merge(
{ terminalConfig: { startupSnippetId: 2 } },
false,
JSON.stringify({ keepaliveInterval: 9 }),
);
expect(JSON.parse(row.terminalConfig as string)).toMatchObject({
sudoPassword: "legacy-sudo",
agentSocketPath: "/owner/agent",
startupSnippetId: 2,
});
expect(JSON.parse(row.sshOptions as string)).toEqual({
keepaliveInterval: 9,
agentSocketPath: "/owner/agent",
});
});
it("refuses a terminalConfig it cannot read", async () => {
const { error } = await merge({ terminalConfig: "not json" });
expect(error).toBe("Invalid terminal config");
});
});
@@ -1,10 +1,44 @@
import { describe, it, expect } from "vitest";
import { afterEach, beforeEach, describe, it, expect } from "vitest";
import {
isValidKeyCombo,
isValidKeybindingAction,
isValidKeybinding,
setKeybindingActionSource,
} from "../../../database/routes/keybinding-validation.js";
// What installed plugins declare in contributes.keybindingActions.
beforeEach(() => {
setKeybindingActionSource(() => [
{ pluginId: "terminal-fixture", id: "copy" },
{ pluginId: "terminal-fixture", id: "paste" },
{
pluginId: "terminal-fixture",
id: "sendControlCode",
params: {
controlCode: { type: "string", required: true, pattern: "^[a-zA-Z]$" },
},
},
{
pluginId: "terminal-fixture",
id: "sendText",
params: {
text: { type: "string", required: true },
appendEnter: { type: "boolean" },
},
},
{
pluginId: "commands-fixture",
id: "runSnippet",
params: {
snippetId: { type: "string", required: true, pattern: "^[0-9]+$" },
appendEnter: { type: "boolean" },
},
},
]);
});
afterEach(() => setKeybindingActionSource(() => []));
const validCombo = {
key: "c",
isCode: false,
@@ -36,15 +70,26 @@ describe("isValidKeybindingAction", () => {
expect(isValidKeybindingAction({ type: "paste" })).toBe(true);
});
it.each(["nextTab", "previousTab", "openCommandPalette"])(
it.each(["nextTab", "previousTab", "openCommandPalette", "reconnectSession"])(
"accepts the global %s action",
(type) => {
expect(isValidKeybindingAction({ type })).toBe(true);
},
);
it("rejects an unknown action type", () => {
expect(isValidKeybindingAction({ type: "explode" })).toBe(false);
it("keeps a type no installed plugin declares, if it looks sane", () => {
expect(isValidKeybindingAction({ type: "gone.action", arg: "x" })).toBe(
true,
);
expect(isValidKeybindingAction({ type: "gone", nested: { a: 1 } })).toBe(
false,
);
expect(isValidKeybindingAction({ type: "bad type!" })).toBe(false);
expect(isValidKeybindingAction({ type: 5 })).toBe(false);
});
it("refuses a parameter the declaration does not list", () => {
expect(isValidKeybindingAction({ type: "copy", text: "x" })).toBe(false);
});
it("requires text for sendText", () => {
@@ -72,6 +117,9 @@ describe("isValidKeybindingAction", () => {
isValidKeybindingAction({ type: "runSnippet", snippetId: "42" }),
).toBe(true);
expect(isValidKeybindingAction({ type: "runSnippet" })).toBe(false);
expect(
isValidKeybindingAction({ type: "runSnippet", snippetId: "abc" }),
).toBe(false);
});
});
@@ -0,0 +1,115 @@
/**
* contributes.http.legacyPaths: an old URL under "/<plugin id>/" reaches the
* plugin's router with that prefix removed, and nothing else is caught.
* contributes.http.legacyRedirects: an old URL anywhere redirects to the
* plugin's own URL, keeping the subpath and the query.
*/
import express from "express";
import request from "supertest";
import { describe, expect, it, vi } from "vitest";
const routers = vi.hoisted(() => new Map<string, express.Router>());
const installed = vi.hoisted(() => new Set<string>());
vi.mock("../../../plugins/http.js", () => ({
getPluginRouter: (id: string) => routers.get(id),
isPluginInstalled: (id: string) => installed.has(id),
}));
const { mountPluginLegacyPaths } =
await import("../../../database/routes/plugin-api-routes.js");
type Active = Parameters<typeof mountPluginLegacyPaths>[1] extends () => Array<
infer T
>
? T
: never;
function appWith(
active: Array<Omit<Active, "legacyRedirects"> & Partial<Active>>,
) {
const app = express();
app.get("/core/route", (_req, res) => res.json({ from: "core" }));
mountPluginLegacyPaths(app, () =>
active.map((entry) => ({ legacyRedirects: [], ...entry })),
);
app.use((_req, res) => res.status(404).json({ from: "fallthrough" }));
return app;
}
describe("mountPluginLegacyPaths", () => {
const router = express.Router();
router.post("/webhook/:token", (req, res) =>
res.json({ token: req.params.token }),
);
routers.set("automations", router);
it("serves an old URL through the plugin's router", async () => {
const app = appWith([
{ id: "automations", legacyPaths: ["/automations/webhook"] },
]);
const response = await request(app).post("/automations/webhook/abc123");
expect(response.status).toBe(200);
expect(response.body).toEqual({ token: "abc123" });
});
it("leaves paths outside the declared prefixes alone", async () => {
const app = appWith([
{ id: "automations", legacyPaths: ["/automations/webhook"] },
]);
expect((await request(app).get("/automations/other")).body).toEqual({
from: "fallthrough",
});
expect((await request(app).get("/core/route")).body).toEqual({
from: "core",
});
});
it("answers 404 for a plugin that is not installed", async () => {
const app = appWith([{ id: "gone", legacyPaths: ["/gone/hook"] }]);
const response = await request(app).post("/gone/hook/x");
expect(response.status).toBe(404);
});
it("answers 503 for an installed plugin that serves no router", async () => {
installed.add("paused");
const app = appWith([{ id: "paused", legacyPaths: ["/paused/hook"] }]);
const response = await request(app).post("/paused/hook/x");
expect(response.status).toBe(503);
});
});
describe("legacy redirects", () => {
const app = appWith([
{
id: "idp",
legacyPaths: [],
legacyRedirects: [
{ from: "/host/idp-callback", to: "/callback" },
{ from: "/old-id/u", to: "/u", status: 308 },
],
},
]);
it("redirects to the plugin's URL with the query", async () => {
const response = await request(app).get(
"/host/idp-callback?code=abc&state=xyz",
);
expect(response.status).toBe(307);
expect(response.headers.location).toBe(
"/plugin-api/idp/callback?code=abc&state=xyz",
);
});
it("keeps a subpath and honours a permanent status", async () => {
const response = await request(app).get("/old-id/u/alice/ca");
expect(response.status).toBe(308);
expect(response.headers.location).toBe("/plugin-api/idp/u/alice/ca");
});
it("does not catch a path that only shares a prefix", async () => {
const response = await request(app).get("/host/idp-callbacks");
expect(response.body).toEqual({ from: "fallthrough" });
});
});
@@ -0,0 +1,582 @@
/**
* The plugin control plane: listing installed plugins (with their declared
* and granted capabilities) and granting/revoking a capability. Enable/disable
* is not re-tested here beyond what already existed; the grant/revoke routes
* are the new surface this file covers.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import express from "express";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
interface PluginRow {
id: string;
name: string;
version: string;
tier: string;
source: string;
state: string;
lastError?: string | null;
manifestJson: string;
}
const state = vi.hoisted(() => ({
plugins: new Map<string, PluginRow>(),
grants: [] as {
pluginId: string;
capability: string;
grantedBy: string | null;
source?: string;
}[],
// Which users have admin.plugins.manage, keyed by userId.
managers: new Set<string>(["admin-1"]),
// Plugins the loader reports as running.
active: new Set<string>(),
}));
vi.mock("../../../upgrade/boot-migrations.js", () => ({
runPluginDataMigrations: async () => {},
}));
vi.mock("../../../utils/crypto-migration/raw-rows.js", () => ({
runStatement: vi.fn(async () => {}),
}));
vi.mock("../../../utils/logger.js", () => ({
databaseLogger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
success: vi.fn(),
},
}));
/**
* The caller identifies as whichever user the x-test-user-id header names,
* mirroring the real JWT middleware's job of setting req.userId -- these
* tests only need to vary which user is calling, not verify real tokens.
*/
vi.mock("../../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() =>
(
req: Record<string, unknown> & { headers: Record<string, string> },
_res: unknown,
next: () => void,
) => {
req.userId = req.headers["x-test-user-id"] ?? "admin-1";
next();
},
}),
},
}));
vi.mock("../../../utils/permission-manager.js", () => ({
PermissionManager: {
getInstance: () => ({
// The list route asks directly rather than gating the whole mount, so
// it can return a narrower shape to a non-admin instead of a 403.
hasPermission: async (userId: string) => state.managers.has(userId),
requirePermission:
(_permission: string) =>
(
req: Record<string, unknown>,
res: {
status: (code: number) => { json: (body: unknown) => void };
},
next: () => void,
) => {
const userId = req.userId as string;
if (!state.managers.has(userId)) {
res.status(403).json({ error: "Insufficient permissions" });
return;
}
next();
},
}),
},
}));
vi.mock("../../../plugins/index.js", () => ({
getPluginRuntime: () => ({
loader: {
list: () => [],
get: (id: string) =>
state.active.has(id)
? {
id,
state: "active",
dir: "/nonexistent/plugin",
manifest: { id, locales: "locales" },
}
: undefined,
},
}),
activatePlugin: vi.fn(),
deactivatePlugin: vi.fn(),
}));
vi.mock("../../../plugins/permissions.js", () => ({
invalidatePluginPermissionCache: vi.fn(),
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentPluginRepository: () => ({
listAll: async () => [...state.plugins.values()],
findById: async (id: string) => state.plugins.get(id) ?? null,
update: async (id: string, changes: Partial<PluginRow>) => {
const existing = state.plugins.get(id);
if (existing) state.plugins.set(id, { ...existing, ...changes });
},
}),
createCurrentPluginPermissionGrantRepository: () => ({
listByPlugin: async (pluginId: string) =>
state.grants
.filter((g) => g.pluginId === pluginId)
.map((g) => ({ capability: g.capability })),
findGrant: async (pluginId: string, capability: string) =>
state.grants.find(
(g) => g.pluginId === pluginId && g.capability === capability,
) ?? null,
grant: async (input: {
pluginId: string;
capability: string;
grantedBy: string | null;
source?: string;
}) => {
state.grants.push(input);
return input;
},
revoke: async (pluginId: string, capability: string) => {
const before = state.grants.length;
state.grants = state.grants.filter(
(g) => !(g.pluginId === pluginId && g.capability === capability),
);
return state.grants.length < before;
},
}),
}));
const pluginRoutes = (await import("../../../database/routes/plugins.js"))
.default;
function makePlugin(overrides: Partial<PluginRow> = {}): PluginRow {
return {
id: "sample-plugin",
name: "Sample Plugin",
version: "1.0.0",
tier: "community",
source: "community",
state: "enabled",
manifestJson: JSON.stringify({
capabilities: ["hosts:read", "kv:own"],
}),
...overrides,
};
}
describe("plugins route", () => {
let server: Server | null = null;
let baseUrl = "";
beforeEach(async () => {
state.plugins = new Map();
state.grants = [];
state.managers = new Set(["admin-1"]);
state.active = new Set();
const app = express();
app.use(express.json());
app.use("/plugins", pluginRoutes);
server = await new Promise<Server>((resolve) => {
const created = app.listen(0, "127.0.0.1", () => resolve(created));
});
baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterEach(async () => {
await new Promise<void>((resolve) => server?.close(() => resolve()));
server = null;
});
describe("GET /plugins/public", () => {
it("lists only enabled plugins that opt into guest pages", async () => {
state.plugins.set(
"guest-plugin",
makePlugin({
id: "guest-plugin",
manifestJson: JSON.stringify({
capabilities: ["hosts:read"],
contributes: { guest: true, guestViews: ["shared"] },
}),
}),
);
state.plugins.set(
"off-guest",
makePlugin({
id: "off-guest",
state: "disabled",
manifestJson: JSON.stringify({ contributes: { guest: true } }),
}),
);
state.plugins.set("sample-plugin", makePlugin());
const res = await fetch(`${baseUrl}/plugins/public`);
const body = await res.json();
expect(res.status).toBe(200);
expect(body.map((plugin: { id: string }) => plugin.id)).toEqual([
"guest-plugin",
]);
expect(body[0].contributes).toEqual({
guest: true,
guestViews: ["shared"],
});
expect(body[0]).not.toHaveProperty("capabilities");
expect(body[0]).not.toHaveProperty("lastError");
});
it("skips a plugin whose manifest does not parse", async () => {
state.plugins.set(
"broken",
makePlugin({ id: "broken", manifestJson: "{" }),
);
const res = await fetch(`${baseUrl}/plugins/public`);
expect(await res.json()).toEqual([]);
});
});
describe("GET /plugins/public-manifest", () => {
it("lists only running plugins with login or second-factor UI, and nothing sensitive", async () => {
state.plugins.set(
"login-plugin",
makePlugin({
id: "login-plugin",
manifestJson: JSON.stringify({
capabilities: ["auth:provide", "credentials:read"],
contributes: {
auth: { loginMethods: ["corp-sso"], sshAuthTypes: ["corp"] },
settings: { admin: [{ key: "clientSecret", type: "secret" }] },
permissions: [{ name: "manage" }],
},
}),
}),
);
state.plugins.set(
"factor-plugin",
makePlugin({
id: "factor-plugin",
manifestJson: JSON.stringify({
contributes: { auth: { secondFactors: ["pin"] } },
}),
}),
);
state.plugins.set(
"stopped-login",
makePlugin({
id: "stopped-login",
manifestJson: JSON.stringify({
contributes: { auth: { loginMethods: ["other"] } },
}),
}),
);
state.plugins.set(
"disabled-login",
makePlugin({
id: "disabled-login",
state: "disabled",
manifestJson: JSON.stringify({
contributes: { auth: { loginMethods: ["x"] } },
}),
}),
);
state.plugins.set("sample-plugin", makePlugin());
state.active = new Set([
"login-plugin",
"factor-plugin",
"disabled-login",
"sample-plugin",
]);
const res = await fetch(`${baseUrl}/plugins/public-manifest`);
const body = await res.json();
expect(res.status).toBe(200);
expect(body.map((plugin: { id: string }) => plugin.id)).toEqual([
"login-plugin",
"factor-plugin",
]);
expect(body[0].contributes).toEqual({
auth: { loginMethods: ["corp-sso"], secondFactors: [] },
});
for (const plugin of body) {
expect(Object.keys(plugin).sort()).toEqual(
[
"assetVersion",
"contributes",
"css",
"dependencies",
"enabled",
"frontend",
"id",
"locales",
"name",
"optionalDependencies",
"state",
"version",
].sort(),
);
}
const raw = JSON.stringify(body);
expect(raw).not.toContain("clientSecret");
expect(raw).not.toContain("credentials:read");
expect(raw).not.toContain("sshAuthTypes");
});
});
it("lists a plugin's declared and granted capabilities", async () => {
state.plugins.set("sample-plugin", makePlugin());
state.grants.push({
pluginId: "sample-plugin",
capability: "hosts:read",
grantedBy: "admin-1",
});
const res = await fetch(`${baseUrl}/plugins`);
const body = await res.json();
expect(body).toEqual([
expect.objectContaining({
id: "sample-plugin",
capabilities: ["hosts:read", "kv:own"],
grantedCapabilities: ["hosts:read"],
}),
]);
});
it("grants a declared capability", async () => {
state.plugins.set("sample-plugin", makePlugin());
const res = await fetch(`${baseUrl}/plugins/sample-plugin/grants`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ capability: "hosts:read" }),
});
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
id: "sample-plugin",
capability: "hosts:read",
granted: true,
});
expect(state.grants).toEqual([
{
pluginId: "sample-plugin",
capability: "hosts:read",
grantedBy: "admin-1",
},
]);
});
it("rejects granting a capability the manifest does not declare", async () => {
state.plugins.set("sample-plugin", makePlugin());
const res = await fetch(`${baseUrl}/plugins/sample-plugin/grants`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ capability: "ssh.exec" }),
});
expect(res.status).toBe(400);
expect(state.grants).toEqual([]);
});
it("404s granting a capability for a plugin that does not exist", async () => {
const res = await fetch(`${baseUrl}/plugins/ghost/grants`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ capability: "hosts:read" }),
});
expect(res.status).toBe(404);
});
it("does not duplicate an already-granted capability", async () => {
state.plugins.set("sample-plugin", makePlugin());
await fetch(`${baseUrl}/plugins/sample-plugin/grants`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ capability: "hosts:read" }),
});
await fetch(`${baseUrl}/plugins/sample-plugin/grants`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ capability: "hosts:read" }),
});
expect(state.grants).toHaveLength(1);
});
it("revokes a granted capability", async () => {
state.plugins.set("sample-plugin", makePlugin());
state.grants.push({
pluginId: "sample-plugin",
capability: "hosts:read",
grantedBy: "admin-1",
});
const res = await fetch(
`${baseUrl}/plugins/sample-plugin/grants/${encodeURIComponent("hosts:read")}`,
{ method: "DELETE" },
);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({
id: "sample-plugin",
capability: "hosts:read",
granted: false,
});
expect(state.grants).toEqual([]);
});
it("404s revoking a capability that was not granted", async () => {
state.plugins.set("sample-plugin", makePlugin());
const res = await fetch(
`${baseUrl}/plugins/sample-plugin/grants/${encodeURIComponent("hosts:read")}`,
{ method: "DELETE" },
);
expect(res.status).toBe(404);
});
describe("admin.plugins.manage gate", () => {
it("lets a non-admin list plugins", async () => {
// GET stays open to any authenticated user on purpose: the app shell
// calls it for every session to know which plugin tabs to register.
state.plugins.set("sample-plugin", makePlugin());
const res = await fetch(`${baseUrl}/plugins`, {
headers: { "x-test-user-id": "regular-user" },
});
expect(res.status).toBe(200);
});
// What a plugin may do, what it has been granted and why it failed are
// operational details. The shell needs none of them to render a tab.
it("hides capabilities, grants and lastError from a non-admin", async () => {
state.plugins.set(
"sample-plugin",
makePlugin({ lastError: "port already in use" }),
);
state.grants.push({
pluginId: "sample-plugin",
capability: "hosts:read",
grantedBy: "admin-1",
});
const res = await fetch(`${baseUrl}/plugins`, {
headers: { "x-test-user-id": "regular-user" },
});
const [plugin] = await res.json();
expect(plugin).toEqual({
id: "sample-plugin",
name: "Sample Plugin",
version: "1.0.0",
enabled: true,
state: "enabled",
contributes: null,
dependencies: {},
optionalDependencies: {},
frontend: false,
css: false,
assetVersion: null,
locales: [],
});
});
it("shows the full record to a holder of admin.plugins.manage", async () => {
state.plugins.set(
"sample-plugin",
makePlugin({ lastError: "port already in use" }),
);
state.grants.push({
pluginId: "sample-plugin",
capability: "hosts:read",
grantedBy: "admin-1",
});
const res = await fetch(`${baseUrl}/plugins`, {
headers: { "x-test-user-id": "admin-1" },
});
const [plugin] = await res.json();
expect(plugin).toMatchObject({
id: "sample-plugin",
capabilities: ["hosts:read", "kv:own"],
grantedCapabilities: ["hosts:read"],
lastError: "port already in use",
});
});
it("403s a non-admin enabling or disabling a plugin", async () => {
state.plugins.set("sample-plugin", makePlugin());
const res = await fetch(`${baseUrl}/plugins/sample-plugin/state`, {
method: "PATCH",
headers: {
"content-type": "application/json",
"x-test-user-id": "regular-user",
},
body: JSON.stringify({ enabled: false }),
});
expect(res.status).toBe(403);
expect(state.plugins.get("sample-plugin")?.state).toBe("enabled");
});
it("403s a non-admin granting a capability", async () => {
state.plugins.set("sample-plugin", makePlugin());
const res = await fetch(`${baseUrl}/plugins/sample-plugin/grants`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-test-user-id": "regular-user",
},
body: JSON.stringify({ capability: "hosts:read" }),
});
expect(res.status).toBe(403);
expect(state.grants).toEqual([]);
});
it("403s a non-admin revoking a capability", async () => {
state.plugins.set("sample-plugin", makePlugin());
state.grants.push({
pluginId: "sample-plugin",
capability: "hosts:read",
grantedBy: "admin-1",
});
const res = await fetch(
`${baseUrl}/plugins/sample-plugin/grants/${encodeURIComponent("hosts:read")}`,
{
method: "DELETE",
headers: { "x-test-user-id": "regular-user" },
},
);
expect(res.status).toBe(403);
expect(state.grants).toHaveLength(1);
});
});
});
@@ -1,58 +0,0 @@
import { describe, expect, it } from "vitest";
import { resolveProxmoxImportAuth } from "../../../database/routes/proxmox-import-auth.js";
// The frontend carries its own copy of this decision in
// src/ui/components/proxmox/proxmox-import-auth.ts. The two drifting apart is
// what produced the reported bug, so both are held to the same matrix.
describe("resolveProxmoxImportAuth", () => {
it("uses the default credential for key auth when one is configured", () => {
expect(resolveProxmoxImportAuth("key", 7)).toEqual({
authType: "credential",
credentialId: 7,
overrideCredentialUsername: 0,
});
});
it("uses the default credential for password auth when one is configured", () => {
expect(resolveProxmoxImportAuth("password", 7)).toEqual({
authType: "credential",
credentialId: 7,
overrideCredentialUsername: 0,
});
});
it("falls back to none when a secret-backed default has no credential", () => {
for (const authType of ["password", "key", "credential"]) {
expect(resolveProxmoxImportAuth(authType, null)).toEqual({
authType: "none",
credentialId: null,
overrideCredentialUsername: 0,
});
}
});
it("uses the credential when no default auth type is configured", () => {
expect(resolveProxmoxImportAuth(undefined, 42)).toEqual({
authType: "credential",
credentialId: 42,
overrideCredentialUsername: 0,
});
expect(resolveProxmoxImportAuth(undefined, null)).toEqual({
authType: "none",
credentialId: null,
overrideCredentialUsername: 0,
});
});
it("keeps secretless auth types, with or without a credential", () => {
for (const authType of ["none", "agent", "opkssh", "tailscale", "vault"]) {
for (const credentialId of [null, 7]) {
expect(resolveProxmoxImportAuth(authType, credentialId)).toEqual({
authType,
credentialId: null,
overrideCredentialUsername: 0,
});
}
}
});
});
@@ -1,26 +0,0 @@
import { describe, expect, it } from "vitest";
import {
parseProxmoxJumpHosts,
serializeProxmoxJumpHosts,
} from "../../../database/routes/proxmox-jump-hosts.js";
describe("Proxmox jump-host persistence", () => {
const jumpHosts = [{ hostId: 7 }, { hostId: 9 }];
it("serializes resolved arrays before inserting a synced guest", () => {
expect(serializeProxmoxJumpHosts(jumpHosts)).toBe(
'[{"hostId":7},{"hostId":9}]',
);
});
it("keeps stored JSON strings stable", () => {
const stored = '[{"hostId":7}]';
expect(serializeProxmoxJumpHosts(stored)).toBe(stored);
expect(parseProxmoxJumpHosts(stored)).toEqual([{ hostId: 7 }]);
});
it("turns missing or malformed values into null", () => {
expect(serializeProxmoxJumpHosts(null)).toBeNull();
expect(serializeProxmoxJumpHosts("invalid")).toBeNull();
});
});
@@ -1,49 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Client } from "ssh2";
const execElevated = vi.fn();
vi.mock("../../../hosts/metrics/managers/exec-elevated.js", () => ({
execElevated: (...args: unknown[]) => execElevated(...args),
}));
import { execPveshCommand } from "../../../database/routes/proxmox.js";
const client = {} as Client;
describe("Proxmox discovery sudo execution", () => {
beforeEach(() => {
execElevated.mockReset();
});
it("forces pvesh through the stored sudo credentials", async () => {
execElevated.mockResolvedValue({
stdout: '[{"type":"qemu"}]',
stderr: "",
code: 0,
usedSudo: true,
});
await expect(
execPveshCommand(client, "pvesh get /cluster/resources", "secret", 12000),
).resolves.toBe('[{"type":"qemu"}]');
expect(execElevated).toHaveBeenCalledWith(
client,
"pvesh get /cluster/resources",
"secret",
{ forceSudo: true, timeoutMs: 12000 },
);
});
it("surfaces a failed elevated pvesh command", async () => {
execElevated.mockResolvedValue({
stdout: "",
stderr: "pvesh failed",
code: 255,
usedSudo: true,
});
await expect(
execPveshCommand(client, "pvesh get /cluster/resources", "secret"),
).rejects.toThrow("pvesh failed");
});
});
@@ -263,12 +263,21 @@ describe("shared host authentication override routes", () => {
expect(unauthenticatedResponse.status).toBe(401);
});
it("serves every real protocol and rejects invalid protocol names", async () => {
const rdpResponse = await invoke("get", {}, "rdp");
expect(rdpResponse.status).toBe(200);
expect(rdpResponse.body.protocol).toBe("rdp");
it("serves any protocol a plugin declares and rejects the rest", async () => {
const { setHostProtocolSource } =
await import("../../../hosts/protocol-auth/registry.js");
setHostProtocolSource(() => [
{ id: "spice", pluginId: "spice-plugin", pluginName: "Spice" },
]);
const declared = await invoke("get", {}, "spice");
setHostProtocolSource(() => []);
expect(declared.status).toBe(200);
expect(declared.body.protocol).toBe("spice");
expect(state.writes).toEqual([]);
const undeclared = await invoke("get", {}, "spice");
expect(undeclared.status).toBe(400);
const invalidResponse = await invoke("get", {}, "smtp");
expect(invalidResponse).toEqual({
status: 400,
@@ -1,28 +0,0 @@
import { describe, expect, it } from "vitest";
import {
isValidServiceLinkUrl,
normalizeServiceLinkUrl,
} from "../../../database/routes/service-link-url.js";
describe("service link URL handling", () => {
it("keeps explicit http and https URLs", () => {
expect(normalizeServiceLinkUrl("https://example.com")).toBe(
"https://example.com",
);
expect(normalizeServiceLinkUrl("http://192.168.1.10:8080")).toBe(
"http://192.168.1.10:8080",
);
});
it("adds http to bare service addresses", () => {
expect(normalizeServiceLinkUrl("192.168.1.10:8080")).toBe(
"http://192.168.1.10:8080",
);
expect(normalizeServiceLinkUrl("termix.local")).toBe("http://termix.local");
});
it("rejects unsupported schemes", () => {
expect(isValidServiceLinkUrl("ssh://example.com")).toBe(false);
expect(isValidServiceLinkUrl("javascript:alert(1)")).toBe(false);
});
});
@@ -1,144 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import path from "path";
// Stub db, logger, fs, and AuthManager before importing the route module
const mockSelect = vi.fn();
const mockDelete = vi.fn();
const mockInsert = vi.fn();
vi.mock("../../../database/db/index.js", () => ({
db: {
select: mockSelect,
delete: mockDelete,
insert: mockInsert,
},
}));
vi.mock("../../../utils/logger.js", () => ({
apiLogger: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), success: vi.fn() },
}));
vi.mock("../../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() => (_req: unknown, _res: unknown, next: () => void) =>
next(),
}),
},
}));
// The route module calls PermissionManager.getInstance() at import time and
// pulls in the repository factory, which loads the drizzle schema and the
// better-sqlite3 native binding. Importing that tree costs seconds under a
// concurrent full run — enough to blow the 5s test timeout — and none of it is
// under test here.
vi.mock("../../../utils/permission-manager.js", () => ({
PermissionManager: {
getInstance: () => ({
canAccessHost: vi.fn(),
}),
},
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentSessionRecordingRepository: vi.fn(),
createCurrentSettingsRepository: vi.fn(),
getCurrentSettingValue: vi.fn(),
}));
const mockReadFile = vi.fn();
const mockStat = vi.fn();
const mockUnlink = vi.fn();
const mockExistsSync = vi.fn();
vi.mock("fs", async (importOriginal) => {
const actual = await importOriginal<typeof import("fs")>();
return {
...actual,
promises: { readFile: mockReadFile, unlink: mockUnlink },
existsSync: mockExistsSync,
statSync: mockStat,
};
});
// Build a chainable drizzle-like query stub
function makeChain(resolveValue: unknown) {
const chain: Record<string, unknown> = {};
const methods = [
"from",
"leftJoin",
"where",
"orderBy",
"limit",
"set",
"values",
];
for (const m of methods) {
chain[m] = vi.fn(() => chain);
}
(chain as unknown as Promise<unknown>).then = (cb: (v: unknown) => unknown) =>
Promise.resolve(resolveValue).then(cb);
(chain as unknown as Promise<unknown>).catch = (
cb: (e: unknown) => unknown,
) => Promise.resolve(resolveValue).catch(cb);
return chain;
}
describe("session-log-routes", () => {
beforeEach(() => {
vi.clearAllMocks();
process.env.DATA_DIR = "/data";
});
describe("GET / - list logs", () => {
it("returns logs for the authenticated user with file size", async () => {
const rows = [
{
id: 1,
hostId: 10,
userId: "u1",
startedAt: "2026-01-01T00:00:00Z",
endedAt: "2026-01-01T00:05:00Z",
duration: 300,
recordingPath: "/data/session_logs/u1/abc.log",
hostName: "my-server",
hostIp: "10.0.0.1",
},
];
const chain = makeChain(rows);
mockSelect.mockReturnValue(chain);
mockStat.mockReturnValue({ size: 4096 });
// Directly call the route handler extracted from the module
const { default: router } =
await import("../../../database/routes/session-log-routes.js");
expect(router).toBeDefined();
});
});
describe("path traversal guard", () => {
it("rejects paths outside the allowed session_logs directory", () => {
const allowedBase = path.resolve("/data", "session_logs");
const malicious = path.resolve("/data/session_logs/../../etc/passwd");
expect(malicious.startsWith(allowedBase)).toBe(false);
});
it("allows a legitimate session log path", () => {
const allowedBase = path.resolve("/data", "session_logs");
const valid = path.resolve("/data/session_logs/user1/abc.log");
expect(valid.startsWith(allowedBase)).toBe(true);
});
});
describe("formatters (pure logic)", () => {
it("stat returns size when file exists", () => {
mockExistsSync.mockReturnValue(true);
mockStat.mockReturnValue({ size: 1234 });
const exists = mockExistsSync("/some/file.log");
const { size } = mockStat("/some/file.log");
expect(exists).toBe(true);
expect(size).toBe(1234);
});
});
});
@@ -1,79 +0,0 @@
import { describe, expect, it } from "vitest";
import {
createSnippetExecutionResult,
getSnippetExecutionTimeoutMs,
resolveSnippetCommand,
} from "../../../database/routes/snippets-execution.js";
describe("snippet execution", () => {
it("treats stderr as diagnostic output when the command succeeds", () => {
expect(createSnippetExecutionResult(0, "done\n", "warning\n")).toEqual({
success: true,
output: "done\n",
error: "warning\n",
});
});
it("uses the exit code to report command failure", () => {
expect(createSnippetExecutionResult(1, "", "failed\n")).toEqual({
success: false,
output: "",
error: "failed\n",
});
});
it("preserves the previous fallback when no exit code is available", () => {
expect(createSnippetExecutionResult(null, "done\n", "")).toEqual({
success: true,
output: "done\n",
});
expect(createSnippetExecutionResult(null, "", "failed\n").success).toBe(
false,
);
});
it("disables the command timeout by default", () => {
expect(getSnippetExecutionTimeoutMs(undefined)).toBeUndefined();
});
it("converts a configured timeout from seconds to milliseconds", () => {
expect(getSnippetExecutionTimeoutMs("45")).toBe(45_000);
});
it.each(["", "0", "-1", "invalid"])(
"ignores invalid timeout value %j",
(value) => {
expect(getSnippetExecutionTimeoutMs(value)).toBeUndefined();
},
);
});
describe("resolveSnippetCommand", () => {
const host = { ip: "10.0.0.5", username: "root", port: 22, name: "web-01" };
it("substitutes host variables per target host", () => {
expect(
resolveSnippetCommand("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(resolveSnippetCommand("ping ${HOST}", host)).toBe("ping 10.0.0.5");
});
it("substitutes input placeholders from inputValues", () => {
expect(
resolveSnippetCommand("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(resolveSnippetCommand("ping $HOST", null)).toBe("ping $HOST");
});
it("leaves input placeholders literal when no value was supplied", () => {
expect(resolveSnippetCommand("echo $INPUT_1", null)).toBe("echo $INPUT_1");
});
});
@@ -1,20 +0,0 @@
import fs from "fs";
import path from "path";
import { describe, expect, it } from "vitest";
describe("snippet execution host access", () => {
it("uses the shared-host-aware resolver", () => {
const source = fs.readFileSync(
path.resolve(__dirname, "../../../database/routes/snippets.ts"),
"utf8",
);
const executeRoute = source.slice(
source.indexOf('router.post(\n "/execute"'),
);
expect(executeRoute).toContain(
"const host = await resolveHostById(parseInt(hostId), userId)",
);
expect(executeRoute).not.toContain("host.userId !== userId");
});
});
@@ -1,127 +0,0 @@
import { describe, it, expect } from "vitest";
import crypto from "crypto";
import fs from "fs";
import os from "os";
import path from "path";
import { execFileSync } from "child_process";
import {
generateCa,
signUserCertificate,
ed25519RawFromLine,
} from "../../../database/routes/ssh-certificate.js";
function publicKeyObjectFromLine(line: string) {
const raw = ed25519RawFromLine(line);
if (!raw) throw new Error("not ed25519");
return crypto.createPublicKey({
key: { kty: "OKP", crv: "Ed25519", x: raw.toString("base64url") },
format: "jwk",
});
}
// Split a cert blob into the signed body and the raw 64-byte ed25519 signature.
function splitCert(certLine: string): { body: Buffer; rawSig: Buffer } {
const blob = Buffer.from(certLine.split(/\s+/)[1], "base64");
// trailing signature string = str( str("ssh-ed25519") + str(64-byte sig) )
const sigBlobLen = 4 + "ssh-ed25519".length + 4 + 64; // 83
const body = blob.subarray(0, blob.length - (4 + sigBlobLen));
const rawSig = blob.subarray(blob.length - 64);
return { body, rawSig };
}
describe("generateCa", () => {
it("produces a valid ed25519 public line and PKCS8 private key", () => {
const ca = generateCa();
expect(ca.publicKeyLine.startsWith("ssh-ed25519 ")).toBe(true);
expect(ed25519RawFromLine(ca.publicKeyLine)?.length).toBe(32);
expect(ca.privateKeyPem).toContain("BEGIN PRIVATE KEY");
// The PEM must load as a usable signing key.
expect(() =>
crypto.createPrivateKey({
key: ca.privateKeyPem,
format: "pem",
type: "pkcs8",
}),
).not.toThrow();
});
});
describe("signUserCertificate", () => {
it("returns null for non-ed25519 user keys", () => {
const ca = generateCa();
const cert = signUserCertificate({
userPublicKeyLine: "ssh-rsa AAAAB3Nz",
caPrivateKeyPem: ca.privateKeyPem,
caPublicKeyLine: ca.publicKeyLine,
keyId: "x",
principals: [],
validAfter: 0,
validBefore: 1,
});
expect(cert).toBeNull();
});
it("produces a cert whose signature verifies against the CA key", () => {
const ca = generateCa();
const user = generateCa(); // reuse: a valid ed25519 public line
const cert = signUserCertificate({
userPublicKeyLine: user.publicKeyLine,
caPrivateKeyPem: ca.privateKeyPem,
caPublicKeyLine: ca.publicKeyLine,
keyId: "termix:@alice",
principals: ["root", "ubuntu"],
validAfter: 1000,
validBefore: 2000,
});
expect(cert).not.toBeNull();
expect(cert!.startsWith("ssh-ed25519-cert-v01@openssh.com ")).toBe(true);
const { body, rawSig } = splitCert(cert!);
const caPub = publicKeyObjectFromLine(ca.publicKeyLine);
expect(crypto.verify(null, body, caPub, rawSig)).toBe(true);
// A different CA must NOT verify.
const otherPub = publicKeyObjectFromLine(generateCa().publicKeyLine);
expect(crypto.verify(null, body, otherPub, rawSig)).toBe(false);
});
it("is accepted and correctly parsed by ssh-keygen -L", () => {
let sshKeygen: string;
try {
sshKeygen = execFileSync("ssh-keygen", ["--help"], { encoding: "utf8" });
void sshKeygen;
} catch (e) {
// ssh-keygen prints usage to stderr and exits non-zero for --help; that's
// fine — it means the binary exists. Only skip if it's truly missing.
if ((e as { code?: string }).code === "ENOENT") return;
}
const ca = generateCa();
const user = generateCa();
const now = Math.floor(Date.now() / 1000);
const cert = signUserCertificate({
userPublicKeyLine: user.publicKeyLine,
caPrivateKeyPem: ca.privateKeyPem,
caPublicKeyLine: ca.publicKeyLine,
keyId: "termix-test-id",
principals: ["deploy"],
validAfter: now,
validBefore: now + 3600,
});
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "termix-cert-"));
const file = path.join(dir, "id-cert.pub");
try {
fs.writeFileSync(file, cert + "\n");
const out = execFileSync("ssh-keygen", ["-L", "-f", file], {
encoding: "utf8",
});
expect(out).toContain("user certificate");
expect(out).toContain('Key ID: "termix-test-id"');
expect(out).toContain("deploy");
expect(out).toMatch(/permit-pty/);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
@@ -1,24 +0,0 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("../../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({ createAdminMiddleware: vi.fn() }),
},
}));
const { isValidOidcIssuer } =
await import("../../../database/routes/sso-provider-routes.js");
describe("isValidOidcIssuer", () => {
it("rejects userinfo endpoints used as issuer URLs", () => {
expect(
isValidOidcIssuer("https://auth.example/application/o/userinfo/"),
).toBe(false);
});
it("accepts an Authentik application issuer", () => {
expect(isValidOidcIssuer("https://auth.example/application/o/termix")).toBe(
true,
);
});
});
@@ -1,83 +0,0 @@
import Database from "better-sqlite3";
import { drizzle } from "drizzle-orm/better-sqlite3";
import { and, eq } from "drizzle-orm";
import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core";
import { describe, expect, it } from "vitest";
import { locateSyncRow } from "../../../database/routes/sync.js";
import { hosts, userPreferences } from "../../../database/db/schema.js";
/**
* A sync push locates the stored row twice: once to see whether it exists,
* once to write it. Those lookups used to be spelled out separately, and only
* the read knew about singleton entities — the write always keyed on
* `table.id`.
*
* `user_preferences` is the only singleton, and the one synced table whose
* primary key is `user_id` with no `id` column at all. `table.id` was
* therefore `undefined` and drizzle emitted a comparison with nothing on its
* left: `( = ? and "user_preferences"."user_id" = ?)`. The insert branch was
* fine, so the first push of preferences succeeded and every push after it —
* the steady state — failed with `SqliteError: near "=": syntax error`.
*/
describe("locateSyncRow", () => {
const dialect = new SQLiteSyncDialect();
const toSql = (condition: Parameters<typeof dialect.sqlToQuery>[0]): string =>
dialect.sqlToQuery(condition).sql;
/** `= ?` with no operand to its left — what used to reach SQLite. */
const EMPTY_LEFT_OPERAND = /(^|\(|\band\b|\bor\b)\s*=\s*\?/;
it("keys a singleton entity on its owner", () => {
const sql = toSql(locateSyncRow("userPreferences", "user-1", "ignored"));
expect(sql).toContain('"user_id"');
expect(sql).not.toContain('"sync_id"');
expect(sql).not.toMatch(EMPTY_LEFT_OPERAND);
});
it("keys a regular entity on its sync id and owner", () => {
const sql = toSql(locateSyncRow("hosts", "user-1", "sync-abc"));
expect(sql).toContain('"sync_id"');
expect(sql).toContain('"user_id"');
expect(sql).not.toMatch(EMPTY_LEFT_OPERAND);
});
it("is the shape the id-keyed lookup could not produce", () => {
// Guards the assertions above: the pattern really does catch the old SQL.
const previous = and(
eq((userPreferences as unknown as typeof hosts).id, 1),
eq(userPreferences.userId, "user-1"),
)!;
expect(toSql(previous)).toMatch(EMPTY_LEFT_OPERAND);
});
it("updates a preferences row that already exists", () => {
const sqlite = new Database(":memory:");
sqlite.exec(`
CREATE TABLE user_preferences (
user_id TEXT PRIMARY KEY,
theme TEXT
);
`);
const db = drizzle(sqlite, { schema: { userPreferences } });
// The steady state: a row exists, so the push takes the update path.
sqlite
.prepare("INSERT INTO user_preferences (user_id, theme) VALUES (?, ?)")
.run("user-1", "dark");
const updated = db
.update(userPreferences)
.set({ theme: "light" })
.where(locateSyncRow("userPreferences", "user-1", "ignored"))
.returning({ theme: userPreferences.theme })
.all();
expect(updated).toEqual([{ theme: "light" }]);
sqlite.close();
});
});
@@ -1,97 +0,0 @@
import { describe, expect, it } from "vitest";
import syncRouter, {
isValidEntityType,
stripWritePayload,
} from "../../../database/routes/sync.js";
describe("sync route order", () => {
it("registers POST /tombstones before the POST /:entityType wildcard", () => {
const postPaths = (
syncRouter as unknown as {
stack: Array<{ route?: { path: string; methods: { post?: boolean } } }>;
}
).stack
.filter((layer) => layer.route?.methods?.post)
.map((layer) => layer.route!.path);
// "/tombstones" is a valid value for :entityType as far as Express is
// concerned, so registering the wildcard first makes the tombstone
// endpoint unreachable -- every deletion push answers 400 "Unknown entity
// type" instead of applying the deletion.
expect(postPaths).toContain("/tombstones");
expect(postPaths.indexOf("/tombstones")).toBeLessThan(
postPaths.indexOf("/:entityType"),
);
});
});
describe("isValidEntityType", () => {
it("accepts every whitelisted sync entity type", () => {
for (const type of [
"hosts",
"sshCredentials",
"sshFolders",
"snippets",
"snippetFolders",
"vaultProfiles",
"dashboardServiceLinks",
"homepageItems",
"userPreferences",
]) {
expect(isValidEntityType(type)).toBe(true);
}
});
it("rejects unknown or non-string entity types", () => {
expect(isValidEntityType("hostAccess")).toBe(false);
expect(isValidEntityType("")).toBe(false);
expect(isValidEntityType(undefined)).toBe(false);
expect(isValidEntityType(42)).toBe(false);
});
});
describe("stripWritePayload", () => {
it("strips id, userId, and syncId from every entity type", () => {
const payload = {
id: 1,
userId: "user-1",
syncId: "abc",
name: "prod-db",
};
expect(stripWritePayload("sshFolders", payload)).toEqual({
name: "prod-db",
});
});
it("also strips desktop-only fields flagged read-only for hosts", () => {
const payload = {
id: 1,
userId: "user-1",
syncId: "abc",
name: "web",
connectionOrigin: "remote",
};
expect(stripWritePayload("hosts", payload)).toEqual({ name: "web" });
});
it("keeps preference storage mode local to each device", () => {
expect(
stripWritePayload("userPreferences", {
syncId: "userPreferences:singleton",
theme: "dark",
storageMode: "cloud",
}),
).toEqual({ theme: "dark" });
});
it("does not mutate the original payload object", () => {
const payload = { id: 1, userId: "user-1", syncId: "abc", name: "x" };
stripWritePayload("snippets", payload);
expect(payload).toEqual({
id: 1,
userId: "user-1",
syncId: "abc",
name: "x",
});
});
});
@@ -1,304 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EventEmitter } from "events";
import fs from "fs/promises";
import os from "os";
import path from "path";
import express, {
type Request,
type RequestHandler,
type Response,
} from "express";
const state = vi.hoisted(() => ({
userId: "admin-1",
settings: {} as Record<string, string>,
sessions: [] as unknown[],
}));
vi.mock("../../../utils/logger.js", () => ({
authLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
databaseLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
}));
vi.mock("../../../hosts/terminal/session-manager.js", () => ({
sessionManager: {
getUserSessions: () => state.sessions,
},
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentSettingsRepository: () => ({
get: async (key: string) => state.settings[key] ?? null,
set: async (key: string, value: string) => {
state.settings[key] = value;
},
setMany: async (writes: Array<{ key: string; value: string }>) => {
for (const write of writes) state.settings[write.key] = write.value;
},
}),
}));
const { registerUserImageStorageRoutes } =
await import("../../../database/routes/user-image-storage-routes.js");
const requireAdmin: RequestHandler = (_req, _res, next) => next();
const router = express.Router();
registerUserImageStorageRoutes(router, requireAdmin);
interface RouteLayer {
route?: {
path: string;
methods: Record<string, boolean>;
stack: Array<{ handle: RequestHandler }>;
};
}
function handlerFor(pathName: string, method: string): RequestHandler {
const layer = (router as unknown as { stack: RouteLayer[] }).stack.find(
(candidate) =>
candidate.route?.path === pathName && candidate.route.methods[method],
);
if (!layer) throw new Error(`Route not registered: ${method} ${pathName}`);
return layer.route!.stack[layer.route!.stack.length - 1]!.handle;
}
const getHandler = handlerFor("/terminal-image-storage-settings", "get");
const patchHandler = handlerFor("/terminal-image-storage-settings", "patch");
const testHandler = handlerFor("/terminal-image-storage-settings/test", "post");
async function invoke(handler: RequestHandler, body?: unknown) {
const req = {
userId: state.userId,
body: body ?? {},
headers: {},
} as unknown as Request;
const result = { statusCode: 200, body: null as unknown };
const res = {
status(code: number) {
result.statusCode = code;
return this;
},
json(payload: unknown) {
result.body = payload;
return this;
},
} as unknown as Response;
await handler(req, res, () => {});
return result;
}
/** Fake ssh2 exec channel: every command exits 0. */
function fakeSshConn() {
return {
exec(
_command: string,
callback: (error: Error | undefined, stream?: unknown) => void,
) {
const stream = new EventEmitter() as EventEmitter & {
resume: () => void;
};
stream.resume = () => queueMicrotask(() => stream.emit("close", 0));
callback(undefined, stream);
},
};
}
const LEGACY_ENV_NAMES = [
"TERMIX_IMAGE_STORAGE_MODE",
"TERMIX_IMAGE_DIR",
"TERMIX_IMAGE_HOST_PATH",
"TERMIX_IMAGE_TTL_MS",
"TERMIX_MAX_IMAGE_COUNT",
"TERMIX_MAX_IMAGE_STORAGE_BYTES",
"DATA_DIR",
];
let savedEnv: Record<string, string | undefined>;
let localDir: string;
beforeEach(async () => {
state.settings = {};
state.sessions = [];
savedEnv = Object.fromEntries(
LEGACY_ENV_NAMES.map((name) => [name, process.env[name]]),
);
for (const name of LEGACY_ENV_NAMES) delete process.env[name];
// The settings validator rejects backslashes, so use a POSIX-style form of
// the real temp dir. Windows still resolves it, so file checks keep working.
localDir = (
await fs.mkdtemp(path.join(os.tmpdir(), "termix-image-test-"))
).replace(/\\/g, "/");
});
afterEach(async () => {
for (const name of LEGACY_ENV_NAMES) {
if (savedEnv[name] === undefined) delete process.env[name];
else process.env[name] = savedEnv[name];
}
await fs.rm(localDir, { recursive: true, force: true });
});
describe("GET /users/terminal-image-storage-settings", () => {
it("returns the public settings shape without the backend localDir", async () => {
state.settings["terminal_image_storage_mode"] = "local";
state.settings["terminal_image_local_dir"] = localDir;
state.settings["terminal_image_host_path"] = "/mnt/images";
const response = await invoke(getHandler);
expect(response.statusCode).toBe(200);
expect(response.body).toEqual({
mode: "local",
hostPath: "/mnt/images",
ttlMs: 3_600_000,
maxCount: 100,
maxBytes: 5_368_709_120,
localMappingConfigured: true,
});
expect(JSON.stringify(response.body)).not.toContain(localDir);
});
});
describe("PATCH /users/terminal-image-storage-settings", () => {
it("rejects an invalid mode with a safe 400", async () => {
const response = await invoke(patchHandler, { mode: "nfs" });
expect(response.statusCode).toBe(400);
expect(response.body).toEqual({
error: "Invalid value for mode",
code: "IMAGE_STORAGE_SETTINGS_INVALID",
field: "mode",
});
});
it("rejects a relative localDir", async () => {
const response = await invoke(patchHandler, { localDir: "images/tmp" });
expect(response.statusCode).toBe(400);
expect(response.body).toMatchObject({
code: "IMAGE_STORAGE_SETTINGS_INVALID",
field: "localDir",
});
expect(JSON.stringify(response.body)).not.toContain("images/tmp");
});
it("rejects out-of-range numeric limits", async () => {
const response = await invoke(patchHandler, { maxBytes: 1024 });
expect(response.statusCode).toBe(400);
expect(response.body).toMatchObject({
code: "IMAGE_STORAGE_SETTINGS_INVALID",
field: "maxBytes",
});
});
it("rejects unknown fields without writing anything", async () => {
const response = await invoke(patchHandler, { shellPath: "/tmp/x" });
expect(response.statusCode).toBe(400);
expect(response.body).toMatchObject({
code: "IMAGE_STORAGE_SETTINGS_UNKNOWN_FIELD",
});
expect(state.settings).toEqual({});
});
// On Windows path.resolve turns the stored dir back into a backslash path,
// which the validator rejects on read, so the round trip only holds on POSIX.
it.skipIf(process.platform === "win32")(
"persists a valid partial update and returns the public shape",
async () => {
const response = await invoke(patchHandler, {
mode: "local",
localDir,
hostPath: "/host/images",
ttlMs: 60_000,
maxCount: 5,
maxBytes: 10_485_760,
});
expect(response.statusCode).toBe(200);
expect(state.settings).toEqual({
terminal_image_storage_mode: "local",
terminal_image_local_dir: path.resolve(localDir),
terminal_image_host_path: "/host/images",
terminal_image_ttl_ms: "60000",
terminal_image_max_count: "5",
terminal_image_max_storage_bytes: "10485760",
});
expect(response.body).toMatchObject({
mode: "local",
hostPath: "/host/images",
ttlMs: 60_000,
maxCount: 5,
maxBytes: 10_485_760,
localMappingConfigured: true,
});
expect(JSON.stringify(response.body)).not.toContain(localDir);
},
);
});
describe("POST /users/terminal-image-storage-settings/test", () => {
it("requires an instanceId", async () => {
const response = await invoke(testHandler, {});
expect(response.statusCode).toBe(400);
expect(response.body).toMatchObject({ code: "IMAGE_SESSION_MISSING" });
});
it("reports unavailable storage when no session is connected", async () => {
const response = await invoke(testHandler, { instanceId: "tab-1" });
expect(response.statusCode).toBe(200);
expect(response.body).toEqual({
mode: "auto",
connected: false,
remoteSftpAvailable: false,
localHostVisible: null,
selectedMode: "unavailable",
localMappingConfigured: false,
});
});
it("probes local visibility through the connected session only", async () => {
state.settings["terminal_image_local_dir"] = localDir;
state.settings["terminal_image_host_path"] = "/host/images";
state.sessions = [
{
tabInstanceId: "tab-1",
isConnected: true,
sshConn: fakeSshConn(),
},
];
const response = await invoke(testHandler, { instanceId: "tab-1" });
expect(response.statusCode).toBe(200);
expect(response.body).toEqual({
mode: "auto",
connected: true,
remoteSftpAvailable: true,
localHostVisible: true,
selectedMode: "local",
localMappingConfigured: true,
});
// The bounded probe cleans up after itself.
expect(
(await fs.readdir(localDir)).filter((f) => f.includes("probe")),
).toEqual([]);
});
it("does not probe sessions owned by other instance IDs", async () => {
state.sessions = [
{
tabInstanceId: "tab-2",
isConnected: true,
sshConn: fakeSshConn(),
},
];
const response = await invoke(testHandler, { instanceId: "tab-1" });
expect(response.statusCode).toBe(200);
expect(response.body).toMatchObject({
connected: false,
remoteSftpAvailable: false,
localHostVisible: null,
selectedMode: "unavailable",
});
});
});
@@ -1,192 +0,0 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import {
DEFAULT_IMAGE_HOST_PATH,
DEFAULT_IMAGE_MAX_BYTES,
DEFAULT_IMAGE_MAX_COUNT,
DEFAULT_IMAGE_TTL_MS,
defaultImageLocalDir,
parseImageHostPath,
parseImageLocalDir,
parseTerminalImageStorageMode,
resolveTerminalImageStorageSettings,
TERMINAL_IMAGE_STORAGE_KEYS,
} from "../../../database/routes/terminal-image-storage-settings.js";
import { SettingsRepository } from "../../../database/repositories/settings-repository.js";
import { TestSqliteDatabase } from "../repositories/test-support.js";
// parseImageLocalDir resolves against the host platform, so a POSIX literal
// becomes a drive-rooted path on Windows. Compare against the same resolution.
function localDir(posixPath: string): string {
return path.resolve(posixPath);
}
function stubSettings(values: Record<string, string> = {}) {
return {
get: async (key: string) => values[key] ?? null,
};
}
const EMPTY_ENV: NodeJS.ProcessEnv = {};
describe("terminal image storage settings", () => {
describe("mode parsing", () => {
it("accepts the three documented modes case-insensitively", () => {
expect(parseTerminalImageStorageMode("auto")).toBe("auto");
expect(parseTerminalImageStorageMode("LOCAL")).toBe("local");
expect(parseTerminalImageStorageMode(" remote-sftp ")).toBe(
"remote-sftp",
);
});
it("rejects unknown modes and non-strings", () => {
expect(parseTerminalImageStorageMode("s3")).toBeNull();
expect(parseTerminalImageStorageMode("")).toBeNull();
expect(parseTerminalImageStorageMode(undefined)).toBeNull();
});
});
describe("path validation", () => {
it("accepts absolute local directories and normalizes them", () => {
expect(parseImageLocalDir("/var/lib/termix/images")).toBe(
localDir("/var/lib/termix/images"),
);
expect(parseImageLocalDir("/var/lib/termix/../termix/images")).toBeNull();
});
it("rejects relative, empty and NUL-containing local directories", () => {
expect(parseImageLocalDir("images")).toBeNull();
expect(parseImageLocalDir("./db/data/images")).toBeNull();
expect(parseImageLocalDir("")).toBeNull();
expect(parseImageLocalDir("/tmp/a\0b")).toBeNull();
});
it("requires the agent-visible host path to be POSIX-absolute", () => {
expect(parseImageHostPath("/tmp/termix-image-v0")).toBe(
"/tmp/termix-image-v0",
);
expect(parseImageHostPath("tmp/termix-image-v0")).toBeNull();
expect(parseImageHostPath("C:\\images")).toBeNull();
expect(parseImageHostPath("/tmp/a\0b")).toBeNull();
});
});
describe("resolution precedence", () => {
it("uses built-in defaults when neither the database nor env has values", async () => {
const resolved = await resolveTerminalImageStorageSettings(
stubSettings(),
EMPTY_ENV,
);
expect(resolved.mode).toBe("auto");
expect(resolved.localDir).toBe(defaultImageLocalDir(EMPTY_ENV));
expect(resolved.hostPath).toBe(DEFAULT_IMAGE_HOST_PATH);
expect(resolved.ttlMs).toBe(DEFAULT_IMAGE_TTL_MS);
expect(resolved.maxCount).toBe(DEFAULT_IMAGE_MAX_COUNT);
expect(resolved.maxBytes).toBe(DEFAULT_IMAGE_MAX_BYTES);
});
it("seeds defaults from legacy TERMIX_IMAGE_* env when no DB value exists", async () => {
const resolved = await resolveTerminalImageStorageSettings(
stubSettings(),
{
TERMIX_IMAGE_DIR: "/host-tmp/images",
TERMIX_IMAGE_HOST_PATH: "/tmp/images",
TERMIX_IMAGE_TTL_MS: "60000",
TERMIX_MAX_IMAGE_COUNT: "5",
TERMIX_MAX_IMAGE_STORAGE_BYTES: "10485760",
},
);
expect(resolved.localDir).toBe(localDir("/host-tmp/images"));
expect(resolved.hostPath).toBe("/tmp/images");
expect(resolved.ttlMs).toBe(60_000);
expect(resolved.maxCount).toBe(5);
expect(resolved.maxBytes).toBe(10_485_760);
});
it("lets persisted DB values win over legacy env values", async () => {
const resolved = await resolveTerminalImageStorageSettings(
stubSettings({
[TERMINAL_IMAGE_STORAGE_KEYS.localDir]: "/db/images",
[TERMINAL_IMAGE_STORAGE_KEYS.ttlMs]: "1000",
[TERMINAL_IMAGE_STORAGE_KEYS.maxCount]: "7",
}),
{
TERMIX_IMAGE_DIR: "/host-tmp/images",
TERMIX_IMAGE_TTL_MS: "60000",
TERMIX_MAX_IMAGE_COUNT: "5",
},
);
expect(resolved.localDir).toBe(localDir("/db/images"));
expect(resolved.ttlMs).toBe(1_000);
expect(resolved.maxCount).toBe(7);
});
it("falls through to env and defaults when the DB value is invalid", async () => {
const resolved = await resolveTerminalImageStorageSettings(
stubSettings({
[TERMINAL_IMAGE_STORAGE_KEYS.localDir]: "relative/path",
[TERMINAL_IMAGE_STORAGE_KEYS.ttlMs]: "not-a-number",
}),
{ TERMIX_IMAGE_DIR: "/host-tmp/images" },
);
expect(resolved.localDir).toBe(localDir("/host-tmp/images"));
expect(resolved.ttlMs).toBe(DEFAULT_IMAGE_TTL_MS);
});
it("keeps legacy explicit local mappings on local mode", async () => {
const resolved = await resolveTerminalImageStorageSettings(
stubSettings(),
{ TERMIX_IMAGE_DIR: "/host-tmp/images" },
);
expect(resolved.mode).toBe("local");
// hostPath falls back to the legacy local dir, which resolves natively.
expect(resolved.hostPath).toBe(localDir("/host-tmp/images"));
expect(resolved.localMappingConfigured).toBe(true);
});
it("lets a persisted DB mode override the legacy local mapping", async () => {
const resolved = await resolveTerminalImageStorageSettings(
stubSettings({
[TERMINAL_IMAGE_STORAGE_KEYS.mode]: "remote-sftp",
}),
{ TERMIX_IMAGE_DIR: "/host-tmp/images" },
);
expect(resolved.mode).toBe("remote-sftp");
});
it("clamps out-of-range numeric values like the legacy env parsing did", async () => {
const resolved = await resolveTerminalImageStorageSettings(
stubSettings(),
{
TERMIX_IMAGE_TTL_MS: "-5",
TERMIX_MAX_IMAGE_COUNT: "0",
TERMIX_MAX_IMAGE_STORAGE_BYTES: "10",
},
);
expect(resolved.ttlMs).toBe(0);
expect(resolved.maxCount).toBe(1);
expect(resolved.maxBytes).toBe(1_048_576);
});
it("reads persisted values through the real settings repository", async () => {
const adapter = new TestSqliteDatabase();
try {
const context = await adapter.connect();
const repository = new SettingsRepository(context);
await repository.set(TERMINAL_IMAGE_STORAGE_KEYS.mode, "local");
await repository.set(
TERMINAL_IMAGE_STORAGE_KEYS.localDir,
"/persisted/images",
);
const resolved = await resolveTerminalImageStorageSettings(repository, {
TERMIX_IMAGE_DIR: "/host-tmp/images",
});
expect(resolved.mode).toBe("local");
expect(resolved.localDir).toBe(localDir("/persisted/images"));
} finally {
await adapter.close();
}
});
});
});
@@ -1,571 +0,0 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { EventEmitter } from "events";
import fs from "fs/promises";
import os from "os";
import path from "path";
import { randomUUID } from "crypto";
import {
REMOTE_IMAGE_DIR,
selectImageStorageMode,
storeImageLocally,
storeImageViaSftp,
TerminalImageStorageError,
type ImageSftpClient,
} from "../../../database/routes/terminal-image-storage.js";
import type { TerminalImageStorageSettings } from "../../../database/routes/terminal-image-storage-settings.js";
const PNG_BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
function settings(
overrides: Partial<TerminalImageStorageSettings>,
): TerminalImageStorageSettings {
return {
mode: "local",
localDir: "/nonexistent",
hostPath: "/tmp/termix-image-v0",
ttlMs: 3_600_000,
maxCount: 100,
maxBytes: 5_368_709_120,
localMappingConfigured: false,
...overrides,
};
}
describe("selectImageStorageMode", () => {
it("keeps explicit modes deterministic regardless of capability", () => {
expect(
selectImageStorageMode(settings({ mode: "local" }), {
remoteSftpAvailable: true,
}),
).toBe("local");
expect(
selectImageStorageMode(settings({ mode: "remote-sftp" }), {
remoteSftpAvailable: false,
}),
).toBe("remote-sftp");
});
it("falls back on capability only in auto mode", () => {
expect(
selectImageStorageMode(settings({ mode: "auto" }), {
remoteSftpAvailable: true,
}),
).toBe("remote-sftp");
expect(
selectImageStorageMode(settings({ mode: "auto" }), {
remoteSftpAvailable: false,
}),
).toBe("unavailable");
expect(
selectImageStorageMode(
settings({ mode: "auto", localMappingConfigured: true }),
{ remoteSftpAvailable: false, localHostVisible: true },
),
).toBe("local");
});
});
describe("storeImageLocally", () => {
let dir: string;
beforeEach(async () => {
dir = await fs.mkdtemp(path.join(os.tmpdir(), "termix-images-test-"));
});
afterEach(async () => {
await fs.rm(dir, { recursive: true, force: true });
});
async function seedFile(bytes: number, mtimeMs?: number): Promise<string> {
const name = `${randomUUID()}.png`;
const filePath = path.join(dir, name);
await fs.writeFile(filePath, Buffer.alloc(bytes));
if (mtimeMs !== undefined) {
const date = new Date(mtimeMs);
await fs.utimes(filePath, date, date);
}
return name;
}
it("writes a UUID-named PNG and returns the agent-visible host path", async () => {
const stored = await storeImageLocally(
PNG_BYTES,
settings({ localDir: dir, hostPath: "/host-view/images" }),
);
expect(stored.storage).toBe("local");
expect(stored.filename).toBe(`${stored.id}.png`);
expect(stored.shellPath).toBe(
path.posix.join("/host-view/images", stored.filename),
);
expect(stored.shellPath).not.toContain(dir);
await expect(fs.readFile(path.join(dir, stored.filename))).resolves.toEqual(
PNG_BYTES,
);
});
it("rejects with IMAGE_STORAGE_LIMIT_REACHED when the count cap is full", async () => {
await seedFile(10);
const error = await storeImageLocally(
PNG_BYTES,
settings({ localDir: dir, maxCount: 1 }),
).catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_STORAGE_LIMIT_REACHED",
);
});
it("rejects with IMAGE_STORAGE_LIMIT_REACHED when the byte cap is full", async () => {
await seedFile(900);
const error = await storeImageLocally(
Buffer.alloc(200),
settings({ localDir: dir, maxBytes: 1_000 }),
).catch((caught: unknown) => caught);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_STORAGE_LIMIT_REACHED",
);
});
it("cleans expired files during upload so they no longer count", async () => {
await seedFile(10, Date.now() - 2 * 3_600_000);
const stored = await storeImageLocally(
PNG_BYTES,
settings({ localDir: dir, maxCount: 1, ttlMs: 3_600_000 }),
);
expect(stored.storage).toBe("local");
const remaining = await fs.readdir(dir);
expect(remaining).toEqual([stored.filename]);
});
it("fails closed when local storage inspection is unavailable", async () => {
const blocked = path.join(dir, "blocked-file");
await fs.writeFile(blocked, "not a directory");
const error = await storeImageLocally(
PNG_BYTES,
settings({ localDir: blocked }),
).catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_LOCAL_INSPECTION_FAILED",
);
});
it("reports inspection failures before attempting a write", async () => {
const blocked = path.join(dir, "blocked");
await fs.writeFile(blocked, "not a directory");
const error = await storeImageLocally(
PNG_BYTES,
settings({ localDir: path.join(blocked, "images") }),
).catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_LOCAL_INSPECTION_FAILED",
);
});
});
describe("storeImageViaSftp", () => {
function fakeSftp(behavior: {
mkdirError?: Error;
writeError?: Error;
stallWrite?: boolean;
stallLock?: boolean;
stallReaddir?: boolean;
stallRmdir?: boolean;
stallUnlink?: boolean;
readdirEntries?: Array<{ filename: string; mtime?: number; size?: number }>;
readdirError?: Error;
statMode?: number;
}): {
sftp: ImageSftpClient;
written: Map<string, Buffer>;
calls: {
mkdir: Array<{ dir: string; mode?: number }>;
createWriteStream: Array<{ path: string; mode?: number }>;
};
streams: Array<
NodeJS.WritableStream & { destroy: () => void; destroyed: boolean }
>;
} {
const written = new Map<string, Buffer>();
const streams: Array<
NodeJS.WritableStream & { destroy: () => void; destroyed: boolean }
> = [];
const calls = { mkdir: [], createWriteStream: [] } as {
mkdir: Array<{ dir: string; mode?: number }>;
createWriteStream: Array<{ path: string; mode?: number }>;
};
const sftp = {
mkdir: (
dir: string,
attrsOrCallback: { mode?: number } | ((err?: Error) => void),
maybeCallback?: (err?: Error) => void,
) => {
const callback =
typeof attrsOrCallback === "function"
? attrsOrCallback
: maybeCallback!;
calls.mkdir.push({
dir,
mode:
typeof attrsOrCallback === "function"
? undefined
: attrsOrCallback.mode,
});
if (
behavior.stallLock &&
dir === `${REMOTE_IMAGE_DIR}/.termix-write-lock`
) {
return;
}
callback(dir === REMOTE_IMAGE_DIR ? behavior.mkdirError : undefined);
},
stat: (
_dir: string,
callback: (error: Error | undefined, attrs?: { mode?: number }) => void,
) => callback(undefined, { mode: behavior.statMode ?? 0o40700 }),
chmod: (_dir: string, _mode: number, callback: (error?: Error) => void) =>
callback(),
readdir: (
_dir: string,
callback: (
error: Error | undefined,
entries: Array<{
filename: string;
attrs?: { mtime?: number; size?: number };
}>,
) => void,
) => {
if (behavior.stallReaddir) return;
callback(
behavior.readdirError,
behavior.readdirEntries?.map((entry) => ({
filename: entry.filename,
attrs: entry,
})) ?? [],
);
},
createWriteStream: (remotePath: string, options?: { mode?: number }) => {
calls.createWriteStream.push({ path: remotePath, mode: options?.mode });
const stream = new EventEmitter() as NodeJS.WritableStream & {
end: (data: Buffer) => void;
destroy: () => void;
destroyed: boolean;
};
stream.destroyed = false;
stream.destroy = () => {
stream.destroyed = true;
};
streams.push(stream);
stream.end = (data: Buffer) => {
if (behavior.stallWrite) return;
queueMicrotask(() => {
if (behavior.writeError) {
stream.emit("error", behavior.writeError);
return;
}
written.set(remotePath, data);
stream.emit("close");
});
};
return stream;
},
unlink: (_remotePath: string, callback: (error?: Error) => void) => {
if (behavior.stallUnlink) return;
callback();
},
rmdir: (_dir: string, callback: (error?: Error) => void) => {
if (behavior.stallRmdir) return;
callback();
},
} as unknown as ImageSftpClient;
return { sftp, written, calls, streams };
}
it("writes into the remote image directory and returns its POSIX path", async () => {
const { sftp, written } = fakeSftp({});
const stored = await storeImageViaSftp(sftp, PNG_BYTES);
expect(stored.storage).toBe("remote-sftp");
expect(stored.shellPath).toBe(`${REMOTE_IMAGE_DIR}/${stored.id}.png`);
expect(written.get(stored.shellPath)).toEqual(PNG_BYTES);
});
it("requests restrictive modes for the remote directory and file", async () => {
const { sftp, calls } = fakeSftp({});
const stored = await storeImageViaSftp(sftp, PNG_BYTES);
expect(stored.storage).toBe("remote-sftp");
expect(calls.mkdir).toEqual([
{ dir: REMOTE_IMAGE_DIR, mode: 0o700 },
{ dir: `${REMOTE_IMAGE_DIR}/.termix-write-lock`, mode: 0o700 },
]);
expect(calls.createWriteStream).toEqual([
{ path: stored.shellPath, mode: 0o600 },
]);
});
it("removes expired UUID PNGs with best-effort remote retention", async () => {
const nowMs = 10_000_000;
const expiredName = `${randomUUID()}.png`;
const freshName = `${randomUUID()}.png`;
const unlinked: string[] = [];
const base = fakeSftp({});
const sftp = base.sftp as ImageSftpClient & {
readdir: (
dir: string,
callback: (
err: Error | undefined,
entries: Array<{ filename: string; attrs?: { mtime?: number } }>,
) => void,
) => void;
unlink: (remotePath: string, callback: (err?: Error) => void) => void;
};
sftp.readdir = (_dir, callback) =>
callback(undefined, [
{ filename: expiredName, attrs: { mtime: (nowMs - 7_200_000) / 1000 } },
{ filename: freshName, attrs: { mtime: nowMs / 1000 } },
{ filename: "other.txt", attrs: { mtime: 0 } },
]);
sftp.unlink = (remotePath, callback) => {
unlinked.push(remotePath);
callback();
};
await storeImageViaSftp(sftp, PNG_BYTES, {
ttlMs: 3_600_000,
nowMs,
});
expect(unlinked).toEqual([`${REMOTE_IMAGE_DIR}/${expiredName}`]);
});
it("fails closed when remote quota inspection fails", async () => {
const { sftp } = fakeSftp({
readdirError: new Error("remote listing failed"),
});
const error = await storeImageViaSftp(sftp, PNG_BYTES, {
maxCount: 10,
maxBytes: 1024,
}).catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_REMOTE_QUOTA_UNAVAILABLE",
);
});
it("rejects remote writes at the configured count limit", async () => {
const { sftp } = fakeSftp({
readdirEntries: [{ filename: `${randomUUID()}.png`, size: 12 }],
});
const error = await storeImageViaSftp(sftp, PNG_BYTES, {
maxCount: 1,
maxBytes: 1024,
}).catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_STORAGE_LIMIT_REACHED",
);
});
it("destroys a stalled SFTP write after its timeout", async () => {
const { sftp, streams } = fakeSftp({ stallWrite: true });
const error = await storeImageViaSftp(sftp, PNG_BYTES, {
writeTimeoutMs: 25,
}).catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_REMOTE_WRITE_FAILED",
);
expect(streams[0]!.destroyed).toBe(true);
});
it("rejects an existing remote path that is not a directory", async () => {
const { sftp } = fakeSftp({
mkdirError: new Error("Failure: file already exists"),
statMode: 0o100644,
});
const error = await storeImageViaSftp(sftp, PNG_BYTES).catch(
(caught: unknown) => caught,
);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_REMOTE_WRITE_FAILED",
);
});
it("preserves SFTP client context for directory inspection", async () => {
const base = fakeSftp({ mkdirError: new Error("already exists") });
const sftp = base.sftp;
sftp.lstat = function (
this: ImageSftpClient,
_dir: string,
callback: (error: Error | undefined, attrs?: { mode?: number }) => void,
) {
if (this !== sftp) {
callback(new Error("SFTP context lost"));
return;
}
callback(undefined, { mode: 0o40700 });
};
const result = await storeImageViaSftp(sftp, PNG_BYTES);
expect(result.storage).toBe("remote-sftp");
});
it("tolerates mkdir failures for an already-existing directory", async () => {
const { sftp } = fakeSftp({
mkdirError: new Error("Failure: file already exists"),
});
await expect(storeImageViaSftp(sftp, PNG_BYTES)).resolves.toMatchObject({
storage: "remote-sftp",
});
});
it("cleans up a partially created remote file after a write failure", async () => {
const { sftp } = fakeSftp({ writeError: new Error("write failed") });
const unlinked: string[] = [];
(sftp as ImageSftpClient).unlink = (remotePath, callback) => {
unlinked.push(remotePath);
callback();
};
const error = await storeImageViaSftp(sftp, PNG_BYTES).catch(
(caught: unknown) => caught,
);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect(unlinked).toHaveLength(1);
expect(unlinked[0]).toMatch(
new RegExp(`${REMOTE_IMAGE_DIR}/[0-9a-f-]+\\.png`),
);
});
it("preserves the write error when partial-file cleanup stalls", async () => {
const { sftp } = fakeSftp({
writeError: new Error("write failed"),
stallUnlink: true,
});
const error = await storeImageViaSftp(sftp, PNG_BYTES).catch(
(caught: unknown) => caught,
);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_REMOTE_WRITE_FAILED",
);
}, 5_000);
it("recovers a stale remote lock before writing", async () => {
const base = fakeSftp({});
const sftp = base.sftp as ImageSftpClient;
const lockPath = `${REMOTE_IMAGE_DIR}/.termix-write-lock`;
let lockAttempt = 0;
const removed: string[] = [];
const originalMkdir = sftp.mkdir.bind(sftp);
sftp.mkdir = (dir, attrs, callback) => {
if (dir === lockPath && lockAttempt++ === 0) {
(typeof attrs === "function" ? attrs : callback!)(new Error("exists"));
return;
}
originalMkdir(dir, attrs, callback);
};
sftp.lstat = (_dir, callback) =>
callback(undefined, {
mode: 0o40700,
mtime: (Date.now() - 60_000) / 1000,
});
sftp.rmdir = (dir, callback) => {
removed.push(dir);
callback();
};
await expect(storeImageViaSftp(sftp, PNG_BYTES)).resolves.toMatchObject({
storage: "remote-sftp",
});
expect(removed).toContain(lockPath);
});
it("does not replace a successful write with an unlock failure", async () => {
const base = fakeSftp({});
const sftp = base.sftp as ImageSftpClient;
const lockPath = `${REMOTE_IMAGE_DIR}/.termix-write-lock`;
const originalMkdir = sftp.mkdir.bind(sftp);
sftp.mkdir = (dir, attrs, callback) => originalMkdir(dir, attrs, callback);
sftp.rmdir = (dir, callback) => {
if (dir === lockPath) callback(new Error("unlock failed"));
else callback();
};
const error = await storeImageViaSftp(sftp, PNG_BYTES).catch(
(caught: unknown) => caught,
);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_REMOTE_WRITE_FAILED",
);
});
it("fails closed when remote lock acquisition stalls", async () => {
const { sftp } = fakeSftp({ stallLock: true });
const error = await storeImageViaSftp(sftp, PNG_BYTES).catch(
(caught: unknown) => caught,
);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_REMOTE_WRITE_FAILED",
);
}, 12_000);
it("fails closed when remote quota inspection stalls", async () => {
const { sftp } = fakeSftp({ stallReaddir: true });
const error = await storeImageViaSftp(sftp, PNG_BYTES, {
maxCount: 10,
maxBytes: 1024,
}).catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_REMOTE_WRITE_FAILED",
);
}, 7_000);
it("fails closed when remote expiry cleanup stalls", async () => {
const { sftp } = fakeSftp({ stallReaddir: true });
const error = await storeImageViaSftp(sftp, PNG_BYTES, {
ttlMs: 1_000,
}).catch((caught: unknown) => caught);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_REMOTE_WRITE_FAILED",
);
}, 7_000);
it("fails closed when remote lock release stalls", async () => {
const { sftp } = fakeSftp({ stallRmdir: true });
const error = await storeImageViaSftp(sftp, PNG_BYTES).catch(
(caught: unknown) => caught,
);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_REMOTE_WRITE_FAILED",
);
}, 5_000);
it("maps SFTP failures to IMAGE_REMOTE_WRITE_FAILED", async () => {
const { sftp } = fakeSftp({ writeError: new Error("Permission denied") });
const error = await storeImageViaSftp(sftp, PNG_BYTES).catch(
(caught: unknown) => caught,
);
expect(error).toBeInstanceOf(TerminalImageStorageError);
expect((error as TerminalImageStorageError).code).toBe(
"IMAGE_REMOTE_WRITE_FAILED",
);
expect((error as TerminalImageStorageError).message).toBe(
"Failed to write image to the remote host",
);
});
});
@@ -1,541 +0,0 @@
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
import { EventEmitter } from "events";
import fs from "fs/promises";
import os from "os";
import path from "path";
import { randomUUID } from "crypto";
import sharp from "sharp";
import type { Request, RequestHandler, Response } from "express";
import type { ImageSftpClient } from "../../../database/routes/terminal-image-storage.js";
import { databaseLogger } from "../../../utils/logger.js";
const state = vi.hoisted(() => ({
userId: "user-1",
settings: {} as Record<string, string>,
sessions: [] as unknown[],
}));
vi.mock("../../../utils/logger.js", () => ({
authLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
databaseLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
}));
vi.mock("../../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() => (_req: unknown, _res: unknown, next: () => void) =>
next(),
createDataAccessMiddleware:
() => (_req: unknown, _res: unknown, next: () => void) =>
next(),
}),
},
}));
vi.mock("../../../hosts/terminal/session-manager.js", () => ({
sessionManager: {
getUserSessions: () => state.sessions,
},
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentSettingsRepository: () => ({
get: async (key: string) => state.settings[key] ?? null,
}),
createCurrentHostResolutionRepository: () => ({}),
createCurrentCommandHistoryRepository: () => ({}),
}));
const { default: router } =
await import("../../../database/routes/terminal.js");
interface RouteLayer {
route?: {
path: string;
methods: Record<string, boolean>;
stack: Array<{ handle: RequestHandler }>;
};
}
const imageUploadLayer = (
router as unknown as { stack: RouteLayer[] }
).stack.find(
(layer) => layer.route?.path === "/image-upload" && layer.route.methods.post,
);
const imageUploadHandler =
imageUploadLayer!.route!.stack[imageUploadLayer!.route!.stack.length - 1]!
.handle;
function fakeSftp(behavior: { writeError?: Error } = {}): {
sftp: ImageSftpClient;
written: Map<string, Buffer>;
end: ReturnType<typeof vi.fn>;
} {
const written = new Map<string, Buffer>();
const end = vi.fn();
const sftp = {
mkdir: (
_dir: string,
attrsOrCallback: { mode?: number } | ((err?: Error) => void),
maybeCallback?: (err?: Error) => void,
) => {
const callback =
typeof attrsOrCallback === "function"
? attrsOrCallback
: maybeCallback!;
callback();
},
createWriteStream: (remotePath: string, _options?: { mode?: number }) => {
const stream = new EventEmitter() as NodeJS.WritableStream & {
end: (data: Buffer) => void;
};
stream.end = (data: Buffer) => {
queueMicrotask(() => {
if (behavior.writeError) {
stream.emit("error", behavior.writeError);
return;
}
written.set(remotePath, data);
stream.emit("close");
});
};
return stream;
},
readdir: (
_dir: string,
callback: (
error: Error | undefined,
entries: Array<{
filename: string;
attrs?: { size?: number; mtime?: number };
}>,
) => void,
) => callback(undefined, []),
unlink: (_path: string, callback: (error?: Error) => void) => callback(),
rmdir: (_dir: string, callback: (error?: Error) => void) => callback(),
end,
} as unknown as ImageSftpClient & { end: ReturnType<typeof vi.fn> };
return { sftp, written, end };
}
function connectedSession(instanceId: string, sftp: ImageSftpClient) {
return {
tabInstanceId: instanceId,
isConnected: true,
sshConn: {
sftp: (
callback: (err: Error | undefined, sftp: ImageSftpClient) => void,
) => callback(undefined, sftp),
},
};
}
async function invoke(options: {
file?: { buffer: Buffer; mimetype: string; size: number };
instanceId?: string;
metadata?: { source?: string; clientUploadTimestamp?: string };
}) {
const body: Record<string, string> = {};
if (options.instanceId) body.instanceId = options.instanceId;
if (options.metadata?.source !== undefined)
body.source = options.metadata.source;
if (options.metadata?.clientUploadTimestamp !== undefined)
body.clientUploadTimestamp = options.metadata.clientUploadTimestamp;
const req = {
userId: state.userId,
body,
file: options.file,
headers: {},
} as unknown as Request;
const result = { statusCode: 200, body: null as unknown };
const res = {
status(code: number) {
result.statusCode = code;
return this;
},
json(body: unknown) {
result.body = body;
return this;
},
} as unknown as Response;
await imageUploadHandler(req, res, () => {});
return result;
}
const LEGACY_ENV_NAMES = [
"TERMIX_IMAGE_STORAGE_MODE",
"TERMIX_IMAGE_DIR",
"TERMIX_IMAGE_HOST_PATH",
"TERMIX_IMAGE_TTL_MS",
"TERMIX_MAX_IMAGE_COUNT",
"TERMIX_MAX_IMAGE_STORAGE_BYTES",
"DATA_DIR",
];
let pngBuffer: Buffer;
let savedEnv: Record<string, string | undefined>;
beforeAll(async () => {
pngBuffer = await sharp({
create: { width: 2, height: 2, channels: 3, background: "#ffffff" },
})
.png()
.toBuffer();
});
beforeEach(() => {
state.settings = {};
state.sessions = [];
savedEnv = Object.fromEntries(
LEGACY_ENV_NAMES.map((name) => [name, process.env[name]]),
);
for (const name of LEGACY_ENV_NAMES) delete process.env[name];
});
afterEach(() => {
for (const name of LEGACY_ENV_NAMES) {
if (savedEnv[name] === undefined) delete process.env[name];
else process.env[name] = savedEnv[name];
}
});
describe("terminal image upload route", () => {
it("rejects requests without an image file", async () => {
const response = await invoke({ instanceId: "tab-1" });
expect(response.statusCode).toBe(400);
expect(response.body).toMatchObject({ code: "IMAGE_FILE_MISSING" });
});
it("requires a connected terminal in explicit remote-sftp mode", async () => {
state.settings["terminal_image_storage_mode"] = "remote-sftp";
const response = await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
instanceId: "tab-1",
});
expect(response.statusCode).toBe(409);
expect(response.body).toMatchObject({
code: "IMAGE_TERMINAL_NOT_CONNECTED",
});
});
it("writes over SFTP in auto mode when a session is connected", async () => {
const { sftp, written, end } = fakeSftp();
state.sessions = [connectedSession("tab-1", sftp)];
const response = await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
instanceId: "tab-1",
});
expect(response.statusCode).toBe(200);
const body = response.body as {
id: string;
filename: string;
shellPath: string;
storage: string;
};
expect(body.storage).toBe("remote-sftp");
expect(body.filename).toBe(`${body.id}.png`);
expect(body.shellPath).toBe(`/tmp/termix-images/${body.filename}`);
// Sharp normalized the upload to PNG before the write.
const writtenBytes = written.get(body.shellPath)!;
expect(writtenBytes.subarray(1, 4).toString()).toBe("PNG");
expect(end).toHaveBeenCalledTimes(1);
});
it("maps SFTP failures to 502 without leaking the raw remote error", async () => {
const { sftp, end } = fakeSftp({
writeError: new Error("Permission denied"),
});
state.sessions = [connectedSession("tab-1", sftp)];
const response = await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
instanceId: "tab-1",
});
expect(response.statusCode).toBe(502);
expect(response.body).toEqual({
error: "Failed to write image to the remote host",
code: "IMAGE_REMOTE_WRITE_FAILED",
});
expect(JSON.stringify(response.body)).not.toContain("Permission denied");
expect(end).toHaveBeenCalledTimes(1);
});
it("rejects undecodable image data", async () => {
const { sftp } = fakeSftp();
state.sessions = [connectedSession("tab-1", sftp)];
const response = await invoke({
file: {
buffer: Buffer.from("definitely not an image"),
mimetype: "image/png",
size: 23,
},
instanceId: "tab-1",
});
expect(response.statusCode).toBe(400);
expect(response.body).toMatchObject({ code: "IMAGE_DECODE_FAILED" });
});
describe("local mapped storage", () => {
let dir: string;
beforeEach(async () => {
// The settings validator rejects backslashes, so store the temp dir in
// POSIX form. Windows still resolves it for the real file checks.
dir = (
await fs.mkdtemp(path.join(os.tmpdir(), "termix-route-test-"))
).replace(/\\/g, "/");
});
afterEach(async () => {
await fs.rm(dir, { recursive: true, force: true });
});
it("stores locally without a terminal session and hides backend paths", async () => {
state.settings["terminal_image_storage_mode"] = "local";
state.settings["terminal_image_local_dir"] = dir;
state.settings["terminal_image_host_path"] = "/host-view/images";
const response = await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
});
expect(response.statusCode).toBe(200);
const body = response.body as {
id: string;
filename: string;
shellPath: string;
storage: string;
};
expect(body.storage).toBe("local");
expect(body.shellPath).toBe(`/host-view/images/${body.filename}`);
expect(JSON.stringify(body)).not.toContain(dir);
const stored = await fs.readFile(path.join(dir, body.filename));
expect(stored.subarray(1, 4).toString()).toBe("PNG");
});
it("answers 507 when the configured image count cap is reached", async () => {
state.settings["terminal_image_storage_mode"] = "local";
state.settings["terminal_image_local_dir"] = dir;
state.settings["terminal_image_host_path"] = "/host-view/images";
state.settings["terminal_image_max_count"] = "1";
await fs.writeFile(
path.join(dir, `${randomUUID()}.png`),
Buffer.alloc(16),
);
const response = await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
});
expect(response.statusCode).toBe(507);
expect(response.body).toMatchObject({
error: "Image storage limit reached",
code: "IMAGE_STORAGE_LIMIT_REACHED",
});
});
it("keeps legacy explicit local mappings on local mode", async () => {
process.env.TERMIX_IMAGE_DIR = dir;
process.env.TERMIX_IMAGE_HOST_PATH = "/host-view/images";
const response = await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
});
expect(response.statusCode).toBe(200);
expect(response.body).toMatchObject({ storage: "local" });
});
it("returns 503 when local storage inspection fails", async () => {
const blocked = `${dir}/blocked-file`;
await fs.writeFile(blocked, "not a directory");
state.settings["terminal_image_storage_mode"] = "local";
state.settings["terminal_image_local_dir"] = blocked;
state.settings["terminal_image_host_path"] = "/host-view/images";
const response = await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
});
expect(response.statusCode).toBe(503);
expect(response.body).toEqual({
error: "Unable to inspect local image storage",
code: "IMAGE_LOCAL_INSPECTION_FAILED",
});
expect(JSON.stringify(response.body)).not.toContain(blocked);
});
it("rejects auto mode when no verified storage capability is available", async () => {
process.env.DATA_DIR = dir;
const response = await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
instanceId: "tab-missing",
});
expect(response.statusCode).toBe(503);
expect(response.body).toMatchObject({
code: "IMAGE_STORAGE_UNAVAILABLE",
});
});
});
describe("diagnostic metadata", () => {
interface UploadLogMeta {
operation?: string;
requestId?: string;
sequence?: number;
source?: string;
clientUploadTimestamp?: string;
serverReceivedAt?: string;
bytes?: number;
}
function uploadLogEntries(): UploadLogMeta[] {
return vi
.mocked(databaseLogger.info)
.mock.calls.filter(
(call) =>
(call[1] as UploadLogMeta | undefined)?.operation ===
"terminal_image_upload_received",
)
.map((call) => call[1] as UploadLogMeta);
}
beforeEach(() => {
vi.mocked(databaseLogger.info).mockClear();
});
it("logs correlation id, receipt time, and propagated source metadata", async () => {
const { sftp } = fakeSftp();
state.sessions = [connectedSession("tab-1", sftp)];
const response = await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
instanceId: "tab-1",
metadata: {
source: "clipboard",
clientUploadTimestamp: "2026-08-15T12:00:00.000Z",
},
});
expect(response.statusCode).toBe(200);
const entries = uploadLogEntries();
expect(entries).toHaveLength(1);
const meta = entries[0]!;
expect(meta.requestId).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
);
expect(typeof meta.sequence).toBe("number");
expect(meta.source).toBe("clipboard");
expect(meta.clientUploadTimestamp).toBe("2026-08-15T12:00:00.000Z");
expect(Number.isNaN(Date.parse(meta.serverReceivedAt ?? ""))).toBe(false);
expect(meta.bytes).toBe(pngBuffer.length);
});
it("logs a monotonically increasing upload sequence", async () => {
const { sftp } = fakeSftp();
state.sessions = [connectedSession("tab-1", sftp)];
await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
instanceId: "tab-1",
metadata: { source: "file" },
});
await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
instanceId: "tab-1",
metadata: { source: "clipboard" },
});
const sequences = uploadLogEntries().map((entry) => entry.sequence!);
expect(sequences).toHaveLength(2);
expect(sequences[1]).toBe(sequences[0]! + 1);
});
it("accepts missing metadata and keeps raw paths out of the log", async () => {
const dir = (
await fs.mkdtemp(path.join(os.tmpdir(), "termix-meta-test-"))
).replace(/\\/g, "/");
try {
state.settings["terminal_image_storage_mode"] = "local";
state.settings["terminal_image_local_dir"] = dir;
state.settings["terminal_image_host_path"] = "/host-view/images";
const response = await invoke({
file: {
buffer: pngBuffer,
mimetype: "image/png",
size: pngBuffer.length,
},
});
expect(response.statusCode).toBe(200);
const entries = uploadLogEntries();
expect(entries).toHaveLength(1);
expect(entries[0]!.source).toBeUndefined();
expect(entries[0]!.clientUploadTimestamp).toBeUndefined();
expect(JSON.stringify(entries[0])).not.toContain(dir);
} finally {
await fs.rm(dir, { recursive: true, force: true });
}
});
});
});
@@ -1,76 +0,0 @@
import { describe, expect, it } from "vitest";
import {
exceedsImageStorageLimit,
exceedsNormalizedImageSize,
imageExtensionForFormat,
createConcurrencyLimiter,
isExpiredImage,
isImageFilename,
} from "../../../database/routes/terminal-image-utils.js";
describe("terminal image utilities", () => {
it("accepts UUID-based image filenames", () => {
expect(isImageFilename("b797234d-eb5d-4b1b-b7f3-17c26f257506.jpeg")).toBe(
true,
);
});
it("rejects unsafe or unrelated filenames", () => {
expect(isImageFilename("../secrets.txt")).toBe(false);
expect(isImageFilename("not-an-image.jpeg")).toBe(false);
expect(isImageFilename("b797234d-eb5d-4b1b-b7f3-17c26f257506")).toBe(false);
});
it("maps decoded raster formats while excluding SVG", () => {
expect(imageExtensionForFormat("jpeg")).toBe("jpg");
expect(imageExtensionForFormat("heif")).toBe("heif");
expect(imageExtensionForFormat("tiff")).toBe("tiff");
expect(imageExtensionForFormat("svg")).toBeUndefined();
expect(imageExtensionForFormat(undefined)).toBeUndefined();
});
it("rejects normalized output beyond the byte ceiling", () => {
expect(exceedsNormalizedImageSize(10_000_001, 10_000_000)).toBe(true);
expect(exceedsNormalizedImageSize(10_000_000, 10_000_000)).toBe(false);
});
it("expires files older than the configured TTL", () => {
expect(isExpiredImage(1_000, 3_000, 1_000)).toBe(true);
expect(isExpiredImage(2_500, 3_000, 1_000)).toBe(false);
});
it("treats a zero TTL as retention disabled", () => {
expect(isExpiredImage(1_000, 999_999, 0)).toBe(false);
});
it("bounds the admission queue", async () => {
const limiter = createConcurrencyLimiter(1, 0);
const release = await limiter.acquire();
await expect(limiter.acquire()).rejects.toThrow("queue is full");
release();
});
it("rejects uploads that exceed the count or byte limit", () => {
expect(exceedsImageStorageLimit(100, 10, 1, 100, 1000)).toBe(true);
expect(exceedsImageStorageLimit(1, 900, 101, 100, 1000)).toBe(true);
expect(exceedsImageStorageLimit(1, 900, 100, 100, 1000)).toBe(false);
});
it("bounds concurrent work", async () => {
const limiter = createConcurrencyLimiter(1);
let active = 0;
let peak = 0;
const task = async () => {
const release = await limiter.acquire();
active += 1;
peak = Math.max(peak, active);
await new Promise((resolve) => setTimeout(resolve, 5));
active -= 1;
release();
};
await Promise.all([task(), task(), task()]);
expect(peak).toBe(1);
expect(limiter.active).toBe(0);
});
});
@@ -1,95 +0,0 @@
import { describe, it, expect } from "vitest";
import {
classifyAlgo,
parsePublicKey,
matchesAlgoFilter,
MAX_PUBLIC_KEY_LENGTH,
} from "../../../database/routes/termix-id-keys.js";
// Build a valid OpenSSH public-key line for a given type by encoding a wire
// blob whose first string field equals the type (what parsePublicKey checks).
function makeKey(type: string, comment = ""): string {
const typeBuf = Buffer.from(type, "utf8");
const header = Buffer.alloc(4);
header.writeUInt32BE(typeBuf.length, 0);
const body = Buffer.alloc(40); // arbitrary trailing key material
const blob = Buffer.concat([header, typeBuf, body]).toString("base64");
return `${type} ${blob}${comment ? ` ${comment}` : ""}`;
}
describe("classifyAlgo", () => {
it("maps known types to normalized groups", () => {
expect(classifyAlgo("ssh-rsa")).toBe("RSA");
expect(classifyAlgo("rsa-sha2-512")).toBe("RSA");
expect(classifyAlgo("ssh-ed25519")).toBe("ED25519");
expect(classifyAlgo("ecdsa-sha2-nistp256")).toBe("ECDSA");
expect(classifyAlgo("ssh-dss")).toBe("DSA");
expect(classifyAlgo("sk-ssh-ed25519@openssh.com")).toBe("ED25519-SK");
expect(classifyAlgo("sk-ecdsa-sha2-nistp256@openssh.com")).toBe("ECDSA-SK");
});
it("falls back by substring for unknown variants", () => {
expect(classifyAlgo("ecdsa-sha2-nistp999")).toBe("ECDSA");
expect(classifyAlgo("rsa-sha2-256-cert")).toBe("RSA");
expect(classifyAlgo("something-weird")).toBe("SOMETHING-WEIRD");
});
});
describe("parsePublicKey", () => {
it("parses a valid ed25519 key and extracts the comment", () => {
const parsed = parsePublicKey(makeKey("ssh-ed25519", "alice@laptop"));
expect(parsed).not.toBeNull();
expect(parsed?.type).toBe("ssh-ed25519");
expect(parsed?.algorithm).toBe("ED25519");
expect(parsed?.comment).toBe("alice@laptop");
// Comment is stripped from the normalized (dedupe) form.
expect(parsed?.normalized.includes("alice@laptop")).toBe(false);
});
it("parses SK (FIDO) key types", () => {
expect(
parsePublicKey(makeKey("sk-ssh-ed25519@openssh.com"))?.algorithm,
).toBe("ED25519-SK");
});
it.each([
[null],
[undefined],
[""],
[" "],
["ssh-ed25519"], // missing blob
["ssh-ed25519 not_base64!!"], // bad base64 charset
["ssh-rsa AAAAB3Nz"], // blob whose embedded type != declared type
])("rejects malformed input %p", (input) => {
expect(parsePublicKey(input as string)).toBeNull();
});
it("rejects an over-length line (amplification guard)", () => {
const valid = makeKey("ssh-ed25519");
const padded = valid + " " + "A".repeat(MAX_PUBLIC_KEY_LENGTH);
expect(padded.length).toBeGreaterThan(MAX_PUBLIC_KEY_LENGTH);
expect(parsePublicKey(padded)).toBeNull();
});
it("rejects a blob whose embedded type does not match the prefix", () => {
// Declared ssh-rsa but the wire blob says ssh-ed25519.
const blob = makeKey("ssh-ed25519").split(" ")[1];
expect(parsePublicKey(`ssh-rsa ${blob}`)).toBeNull();
});
});
describe("matchesAlgoFilter", () => {
it("returns all keys when no filter", () => {
expect(matchesAlgoFilter("ED25519", null)).toBe(true);
});
it("matches exactly and is case-insensitive", () => {
expect(matchesAlgoFilter("ED25519", "ed25519")).toBe(true);
expect(matchesAlgoFilter("RSA", "RSA")).toBe(true);
});
it("does NOT let ED25519 match ED25519-SK (the over-match bug)", () => {
expect(matchesAlgoFilter("ED25519-SK", "ED25519")).toBe(false);
expect(matchesAlgoFilter("ECDSA-SK", "ECDSA")).toBe(false);
});
});
@@ -1,162 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mockSelect = vi.fn();
const mockUpdate = vi.fn();
const mockInsert = vi.fn();
const mockDelete = vi.fn();
vi.mock("../../../database/db/index.js", () => ({
db: {
select: mockSelect,
update: mockUpdate,
insert: mockInsert,
delete: mockDelete,
},
}));
vi.mock("../../../utils/logger.js", () => ({
apiLogger: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), success: vi.fn() },
authLogger: {
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
success: vi.fn(),
},
}));
vi.mock("../../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() =>
(req: Record<string, unknown>, _res: unknown, next: () => void) => {
req.userId = "user-1";
next();
},
createDataAccessMiddleware:
() => (_req: unknown, _res: unknown, next: () => void) =>
next(),
}),
},
}));
vi.mock("../../../utils/audit-logger.js", () => ({
logAudit: vi.fn(),
getRequestMeta: vi.fn(() => ({})),
}));
vi.mock("../../../utils/data-crypto.js", () => ({
DataCrypto: { getInstance: () => ({ encrypt: vi.fn(), decrypt: vi.fn() }) },
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentTermixIdentityCaRepository: vi.fn(() => ({
findPublicByIdentityId: vi.fn(),
findDecryptedByIdentityId: vi.fn(),
createEncryptedForUser: vi.fn(),
updateEncryptedForIdentity: vi.fn(),
deleteByIdentityId: vi.fn(),
})),
createCurrentTermixIdentityRepository: vi.fn(() => ({
findIdentityForUser: vi.fn(),
findIdentityByHandle: vi.fn(),
isHandleTaken: vi.fn(),
createIdentity: vi.fn(),
updateIdentityForUser: vi.fn(),
deleteIdentityForUser: vi.fn(),
listKeysByIdentityId: vi.fn(),
listEnabledKeysByIdentityId: vi.fn(),
listLinkedCredentialIds: vi.fn(),
createKey: vi.fn(),
updateKeyForUser: vi.fn(),
deleteKeyForUser: vi.fn(),
findKeyForUser: vi.fn(),
})),
}));
vi.mock("../../../database/routes/termix-id-keys.js", () => ({
termixIdKeysRouter: { use: vi.fn() },
matchesAlgoFilter: vi.fn(() => true),
}));
// Chainable Drizzle stub — supports arbitrary method chains and resolves via .then()
function makeChain(resolveValue: unknown) {
const chain: Record<string, unknown> = {};
const methods = [
"from",
"where",
"set",
"values",
"returning",
"orderBy",
"limit",
"and",
"eq",
];
for (const m of methods) {
chain[m] = vi.fn(() => chain);
}
(chain as unknown as Promise<unknown>).then = (
cb: (v: unknown) => unknown,
eb?: (e: unknown) => unknown,
) => Promise.resolve(resolveValue).then(cb, eb);
(chain as unknown as Promise<unknown>).catch = (
cb: (e: unknown) => unknown,
) => Promise.resolve(resolveValue).catch(cb);
return chain;
}
const IDENTITY_ROW = { id: 42, userId: "user-1", handle: "alice" };
describe("GET /termix-id/linked-credentials", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("returns empty list when user has no identity", async () => {
// First select (getIdentityForUser) returns nothing; second should not be called
mockSelect.mockReturnValueOnce(makeChain([]));
const { default: router } =
await import("../../../database/routes/termix-id.js");
expect(router).toBeDefined();
expect(router).toBeDefined();
}, 15_000);
it("returns empty list when identity has no keys", async () => {
mockSelect
.mockReturnValueOnce(makeChain([IDENTITY_ROW])) // identity lookup
.mockReturnValueOnce(makeChain([])); // keys lookup
const { default: router } =
await import("../../../database/routes/termix-id.js");
expect(router).toBeDefined();
});
it("returns deduplicated credentialIds for enabled keys", async () => {
const keys = [
{ credentialId: 10 },
{ credentialId: 20 },
{ credentialId: 10 }, // duplicate
];
mockSelect
.mockReturnValueOnce(makeChain([IDENTITY_ROW]))
.mockReturnValueOnce(makeChain(keys));
const { default: router } =
await import("../../../database/routes/termix-id.js");
expect(router).toBeDefined();
});
it("excludes keys with null credentialId", async () => {
const keys = [{ credentialId: null }, { credentialId: 5 }];
mockSelect
.mockReturnValueOnce(makeChain([IDENTITY_ROW]))
.mockReturnValueOnce(makeChain(keys));
const { default: router } =
await import("../../../database/routes/termix-id.js");
expect(router).toBeDefined();
});
});
@@ -0,0 +1,155 @@
import http from "node:http";
import type { AddressInfo } from "node:net";
import express, { type RequestHandler } from "express";
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
const state = vi.hoisted(() => ({
admins: new Set<string>(["admin-1"]),
writes: [] as Array<[unknown, unknown]>,
reloads: 0,
audits: [] as Array<{ action: string; success: boolean }>,
}));
vi.mock("../../../utils/logger.js", () => ({
authLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
}));
vi.mock("../../../utils/audit-logger.js", () => ({
logAudit: async (entry: { action: string; success: boolean }) => {
state.audits.push({ action: entry.action, success: entry.success });
},
getRequestMeta: () => ({ ipAddress: "127.0.0.1", userAgent: "test" }),
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentUserRepository: () => ({
findById: async (id: string) => ({
id,
username: id,
isAdmin: state.admins.has(id),
}),
}),
}));
vi.mock("../../../tls/tls-service.js", async () => {
const { TlsValidationError } = await import("../../../tls/certificate.js");
return {
getTlsStatus: async () => ({
enabled: true,
certificate: null,
renewal: null,
}),
writeTlsCertificate: async (cert: unknown, key: unknown) => {
if (key === "mismatch") {
throw new TlsValidationError(
"The certificate and private key do not match",
);
}
state.writes.push([cert, key]);
return { subject: "CN=x", notAfter: "2030-01-01T00:00:00.000Z" };
},
reloadTls: async () => {
state.reloads++;
return { applied: true, message: "reloaded" };
},
};
});
const { registerTlsRoutes } =
await import("../../../database/routes/tls-routes.js");
const authenticate: RequestHandler = (req, _res, next) => {
(req as unknown as { userId?: string }).userId =
req.header("x-user") ?? undefined;
next();
};
let server: http.Server;
let base: string;
beforeAll(async () => {
const router = express.Router();
registerTlsRoutes(router, authenticate);
const app = express();
app.use(express.json());
app.use("/users", router);
server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, resolve));
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
beforeEach(() => {
state.writes = [];
state.reloads = 0;
state.audits = [];
});
const upload = (user: string, body: unknown) =>
fetch(`${base}/users/tls-certificate`, {
method: "POST",
headers: { "content-type": "application/json", "x-user": user },
body: JSON.stringify(body),
});
describe("TLS certificate routes", () => {
it("returns the status to an admin only", async () => {
const ok = await fetch(`${base}/users/tls-certificate`, {
headers: { "x-user": "admin-1" },
});
expect(ok.status).toBe(200);
expect(await ok.json()).toMatchObject({ enabled: true, renewal: null });
const denied = await fetch(`${base}/users/tls-certificate`, {
headers: { "x-user": "user-1" },
});
expect(denied.status).toBe(403);
});
it("installs an uploaded pair and reloads", async () => {
const response = await upload("admin-1", {
certificate: "CERT",
privateKey: "KEY",
});
expect(response.status).toBe(200);
expect((await response.json()).reloadMessage).toBe("reloaded");
expect(state.writes).toEqual([["CERT", "KEY"]]);
expect(state.reloads).toBe(1);
expect(state.audits).toEqual([
{ action: "tls_certificate_upload", success: true },
]);
});
it("answers 400 for a mismatched pair without reloading", async () => {
const response = await upload("admin-1", {
certificate: "CERT",
privateKey: "mismatch",
});
expect(response.status).toBe(400);
expect((await response.json()).error).toMatch(/do not match/);
expect(state.reloads).toBe(0);
expect(state.audits).toEqual([
{ action: "tls_certificate_upload", success: false },
]);
});
it("refuses a non-admin upload", async () => {
const response = await upload("user-1", {
certificate: "CERT",
privateKey: "KEY",
});
expect(response.status).toBe(403);
expect(state.writes).toEqual([]);
});
});
@@ -1,190 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import bcrypt from "bcryptjs";
import speakeasy from "speakeasy";
const userUpdate = vi.fn().mockResolvedValue(null);
const findById = vi.fn();
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentUserRepository: () => ({ findById, update: userUpdate }),
createCurrentTrustedDeviceRepository: () => ({}),
createCurrentUserSessionRepository: () => ({}),
}));
vi.mock("../../../utils/logger.js", () => ({
authLogger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
success: vi.fn(),
},
}));
vi.mock("../../../utils/database-save-trigger.js", () => ({
DatabaseSaveTrigger: { forceSave: vi.fn().mockResolvedValue(undefined) },
}));
const { registerUserTotpRoutes } =
await import("../../../database/routes/user-totp-routes.js");
const secret = speakeasy.generateSecret({ name: "test" }).base32;
const PASSWORD = "correct-horse";
/**
* The disable dialog has one field, labelled "Enter TOTP code or password",
* and its caller passes that single value as `disableTOTP(input)` — which
* lands in the `password` argument, leaving `totp_code` undefined.
*
* 2.5.1 changed the route to require both, so from then on the first check
* rejected every attempt regardless of what was typed. Nobody could turn 2FA
* off, and the client reported it as the generic "Failed to disable 2FA".
*/
describe("POST /totp/disable", () => {
let handler: (req: unknown, res: unknown) => Promise<void>;
let setupHandler: (req: unknown, res: unknown) => Promise<void>;
beforeEach(() => {
vi.clearAllMocks();
const routes = new Map<string, (req: unknown, res: unknown) => unknown>();
const router = {
post: (path: string, ...rest: unknown[]) => {
routes.set(path, rest[rest.length - 1] as never);
},
get: () => {},
put: () => {},
delete: () => {},
};
registerUserTotpRoutes(
router as never,
{
authenticateJWT: (() => {}) as never,
authManager: { getUserDataKey: () => null } as never,
isNativeAppRequest: () => false,
} as never,
);
handler = routes.get("/totp/disable") as never;
setupHandler = routes.get("/totp/setup") as never;
findById.mockResolvedValue({
id: "user-1",
username: "test-user",
isOidc: false,
passwordHash: bcrypt.hashSync(PASSWORD, 4),
totpSecret: secret,
totpBackupCodes: JSON.stringify(["BACKUP01"]),
totpEnabled: true,
});
});
function call(body: Record<string, unknown>) {
const res = {
statusCode: 200,
body: undefined as unknown,
status(code: number) {
this.statusCode = code;
return this;
},
json(payload: unknown) {
this.body = payload;
return this;
},
};
return handler({ userId: "user-1", body }, res).then(() => res);
}
function callSetup(body: Record<string, unknown>) {
const res = {
statusCode: 200,
body: undefined as unknown,
status(code: number) {
this.statusCode = code;
return this;
},
json(payload: unknown) {
this.body = payload;
return this;
},
};
return setupHandler({ userId: "user-1", body }, res).then(() => res);
}
it("reveals the existing enrollment only after re-authentication", async () => {
const denied = await callSetup({ credential: "wrong" });
expect(denied.statusCode).toBe(401);
const allowed = await callSetup({ credential: PASSWORD });
expect(allowed.statusCode).toBe(200);
expect(allowed.body).toEqual(
expect.objectContaining({ secret, additional: true }),
);
expect(userUpdate).not.toHaveBeenCalled();
});
it("requires a credential before adding another authenticator", async () => {
const res = await callSetup({});
expect(res.statusCode).toBe(400);
expect(userUpdate).not.toHaveBeenCalled();
});
it("accepts the TOTP code on its own", async () => {
// What the dialog sends: one value, in whichever field the client used.
const res = await call({
totp_code: speakeasy.totp({ secret, encoding: "base32" }),
});
expect(res.statusCode).toBe(200);
expect(userUpdate).toHaveBeenCalledWith(
"user-1",
expect.objectContaining({ totpEnabled: false, totpSecret: null }),
);
});
it("accepts the account password on its own", async () => {
// The single field is labelled "TOTP code or password", and the client
// passes it as the password argument — this is the exact failing call.
const res = await call({ password: PASSWORD });
expect(res.statusCode).toBe(200);
expect(userUpdate).toHaveBeenCalled();
});
it("accepts a backup code", async () => {
const res = await call({ totp_code: "BACKUP01" });
expect(res.statusCode).toBe(200);
});
it("still refuses a wrong value", async () => {
const res = await call({ password: "not-my-password" });
expect(res.statusCode).toBe(401);
expect(userUpdate).not.toHaveBeenCalled();
});
it("refuses an empty request rather than disabling anything", async () => {
const res = await call({});
expect(res.statusCode).toBe(400);
expect(userUpdate).not.toHaveBeenCalled();
});
it("does not let an OIDC user disable it with a password", async () => {
// No password to compare against; only a TOTP or backup code will do.
findById.mockResolvedValue({
id: "user-1",
isOidc: true,
passwordHash: null,
totpSecret: secret,
totpBackupCodes: JSON.stringify([]),
totpEnabled: true,
});
const res = await call({ password: "anything" });
expect(res.statusCode).toBe(401);
expect(userUpdate).not.toHaveBeenCalled();
});
});
@@ -1,92 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Request, RequestHandler, Response } from "express";
import { TOUCH_INPUT_DEFAULTS } from "../../../../types/touch-input-settings.js";
const state = vi.hoisted(() => ({
userId: "admin",
admins: new Set(["admin"]),
stored: null as string | null,
}));
vi.mock("../../../utils/logger.js", () => ({
authLogger: { error: vi.fn() },
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentUserRepository: () => ({
findById: async (id: string) => ({ id, isAdmin: state.admins.has(id) }),
}),
createCurrentSettingsRepository: () => ({
get: async () => state.stored,
set: async (_key: string, value: string) => {
state.stored = value;
},
}),
}));
const { registerTouchInputSettingsRoutes } =
await import("../../../database/routes/touch-input-settings-routes.js");
type Registered = { method: string; path: string; handler: RequestHandler };
const registered: Registered[] = [];
const router = {
get: (path: string, ...handlers: RequestHandler[]) =>
registered.push({ method: "get", path, handler: handlers.at(-1)! }),
patch: (path: string, ...handlers: RequestHandler[]) =>
registered.push({ method: "patch", path, handler: handlers.at(-1)! }),
} as unknown as import("express").Router;
registerTouchInputSettingsRoutes(router, (_req, _res, next) => next());
async function invoke(method: string, body: unknown = {}) {
const handler = registered.find((entry) => entry.method === method)!.handler;
const req = { userId: state.userId, body } as unknown as Request;
const result = { statusCode: 200, body: null as unknown };
const res = {
status(code: number) {
result.statusCode = code;
return this;
},
json(bodyValue: unknown) {
result.body = bodyValue;
return this;
},
} as Response;
await handler(req, res, () => {});
return result;
}
beforeEach(() => {
state.userId = "admin";
state.stored = null;
});
describe("touch input settings routes", () => {
it("allows authenticated non-admin users to read normalized defaults", async () => {
state.userId = "user";
const response = await invoke("get");
expect(response.statusCode).toBe(200);
expect(response.body).toEqual(TOUCH_INPUT_DEFAULTS);
});
it("only allows admins to write", async () => {
state.userId = "user";
const response = await invoke("patch", { enabled: false });
expect(response.statusCode).toBe(403);
expect(state.stored).toBeNull();
});
it("rejects out-of-range values and persists normalized updates", async () => {
const invalid = await invoke("patch", { maximumTicksPerFrame: 101 });
expect(invalid.statusCode).toBe(400);
const valid = await invoke("patch", {
dragThresholdPx: 9,
momentumEnabled: false,
});
expect(valid.statusCode).toBe(200);
expect(JSON.parse(state.stored!)).toEqual({
...TOUCH_INPUT_DEFAULTS,
dragThresholdPx: 9,
momentumEnabled: false,
});
});
});
@@ -0,0 +1,128 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import http from "node:http";
import type { AddressInfo } from "node:net";
import express from "express";
import { UI_ONBOARDING_VERSION } from "../../../../types/ui-preferences.js";
const state = vi.hoisted(() => ({
row: null as { data: string } | null,
registeredAt: null as string | null,
}));
vi.mock("../../../utils/logger.js", () => ({
databaseLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
}));
vi.mock("../../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() => (req: express.Request, _res: unknown, next: () => void) => {
(req as unknown as { userId: string }).userId = "user-1";
next();
},
}),
},
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentUiPreferenceRepository: () => ({
findByUserId: async () => state.row,
upsert: async (_userId: string, data: string) => {
state.row = { data };
},
}),
createCurrentUserRepository: () => ({
findById: async () => ({ registeredAt: state.registeredAt }),
}),
}));
const { default: uiPreferenceRoutes } =
await import("../../../database/routes/ui-preferences.js");
let server: http.Server;
let baseUrl: string;
const OLD = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();
const NEW = new Date().toISOString();
async function put(body: unknown) {
const res = await fetch(`${baseUrl}/ui-preferences`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
return res.json();
}
async function get() {
const res = await fetch(`${baseUrl}/ui-preferences`);
return (await res.json()).preferences;
}
beforeEach(async () => {
state.row = null;
state.registeredAt = OLD;
const app = express();
app.use(express.json());
app.use("/ui-preferences", uiPreferenceRoutes);
server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo;
baseUrl = `http://127.0.0.1:${port}`;
});
afterEach(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
describe("ui-preferences onboarding backfill", () => {
it("treats an old account with no row as onboarded", async () => {
expect((await get()).onboarding.completedVersion).toBe(
UI_ONBOARDING_VERSION,
);
});
it("keeps an old account onboarded after its first write", async () => {
await put({ overrides: { "plugin:x": { a: 1 } } });
const stored = JSON.parse(state.row!.data);
expect(stored.onboarding.completedVersion).toBe(UI_ONBOARDING_VERSION);
expect((await get()).onboarding.completedVersion).toBe(
UI_ONBOARDING_VERSION,
);
});
it("repairs a row an earlier write stored as not completed", async () => {
state.row = {
data: JSON.stringify({
onboarding: { completedVersion: 0, completedAt: null, skipped: false },
}),
};
expect((await get()).onboarding.completedVersion).toBe(
UI_ONBOARDING_VERSION,
);
});
it("still shows onboarding to a new account", async () => {
state.registeredAt = NEW;
await put({ preset: "simple" });
expect((await get()).onboarding.completedVersion).toBe(0);
});
it("does not hide a newer onboarding version from someone who finished an older one", async () => {
state.row = {
data: JSON.stringify({
onboarding: {
completedVersion: UI_ONBOARDING_VERSION - 1,
completedAt: OLD,
skipped: false,
},
}),
};
expect((await get()).onboarding.completedVersion).toBe(
UI_ONBOARDING_VERSION - 1,
);
});
});
@@ -11,12 +11,13 @@ const state = vi.hoisted(() => ({
isAdmin: boolean;
isOidc: boolean;
passwordHash: string | null;
totpEnabled: boolean;
}
>(),
unlockedUsers: new Set<string>(),
updates: [] as { id: string; changes: Record<string, unknown> }[],
auditCalls: [] as Record<string, unknown>[],
secondFactors: [] as { userId: string; pluginId: string; factorId: string }[],
trustedDevicesCleared: [] as string[],
}));
vi.mock("../../../database/db/index.js", () => ({ db: {} }));
@@ -89,10 +90,45 @@ vi.mock("../../../database/repositories/factory.js", () => ({
switchUserRoleName: async () => {},
assignRoleNameToUser: async () => {},
}),
createCurrentUserAuthRepository: () => ({
listSecondFactors: async (userId: string) =>
state.secondFactors.filter((row) => row.userId === userId),
listUserIdsWithSecondFactors: async () =>
new Set(state.secondFactors.map((row) => row.userId)),
removeSecondFactor: async (
userId: string,
pluginId: string,
factorId: string,
) => {
state.secondFactors = state.secondFactors.filter(
(row) =>
!(
row.userId === userId &&
row.pluginId === pluginId &&
row.factorId === factorId
),
);
return true;
},
clearSecondFactors: async (userId: string) => {
const before = state.secondFactors.length;
state.secondFactors = state.secondFactors.filter(
(row) => row.userId !== userId,
);
return before - state.secondFactors.length;
},
}),
createCurrentTrustedDeviceRepository: () => ({
deleteByUserId: async (userId: string) => {
state.trustedDevicesCleared.push(userId);
},
}),
getCurrentSettingValue: () => null,
}));
const { registerUserAdminRoutes } =
await import("../../../database/routes/user-admin-routes.js");
const { registerSecondFactor } = await import("../../../auth/registry.js");
// Capture the handlers registered on the router so we can invoke them directly
// without spinning up an HTTP server.
@@ -180,6 +216,8 @@ async function invoke(
beforeEach(() => {
state.currentUserId = "admin1";
state.secondFactors = [];
state.trustedDevicesCleared = [];
state.users = new Map([
[
"admin1",
@@ -189,7 +227,6 @@ beforeEach(() => {
isAdmin: true,
isOidc: false,
passwordHash: "hash",
totpEnabled: false,
},
],
[
@@ -200,7 +237,6 @@ beforeEach(() => {
isAdmin: false,
isOidc: false,
passwordHash: "hash",
totpEnabled: true,
},
],
[
@@ -211,7 +247,6 @@ beforeEach(() => {
isAdmin: false,
isOidc: false,
passwordHash: "hash",
totpEnabled: false,
},
],
]);
@@ -221,15 +256,19 @@ beforeEach(() => {
});
describe("GET /list", () => {
it("includes data_unlocked and totp_enabled for admin callers", async () => {
it("includes data_unlocked and second_factor_enabled for admin callers", async () => {
state.secondFactors = [
{ userId: "target1", pluginId: "totp", factorId: "totp" },
];
const res = await invoke("get", "/list");
expect(res.statusCode).toBe(200);
const users = (res.jsonBody as { users: Record<string, unknown>[] }).users;
const target = users.find((u) => u.userId === "target1")!;
expect(target.data_unlocked).toBe(true);
expect(target.totp_enabled).toBe(true);
expect(target.second_factor_enabled).toBe(true);
const locked = users.find((u) => u.userId === "locked1")!;
expect(locked.data_unlocked).toBe(false);
expect(locked.second_factor_enabled).toBe(false);
});
it("omits management fields for non-admin callers", async () => {
@@ -237,7 +276,7 @@ describe("GET /list", () => {
const res = await invoke("get", "/list");
const users = (res.jsonBody as { users: Record<string, unknown>[] }).users;
expect(users[0].data_unlocked).toBeUndefined();
expect(users[0].totp_enabled).toBeUndefined();
expect(users[0].second_factor_enabled).toBeUndefined();
});
it("returns every user when no limit is given", async () => {
@@ -299,46 +338,6 @@ describe("GET /list", () => {
});
});
describe("POST /admin/totp/disable", () => {
it("clears TOTP fields for the target and audits", async () => {
const res = await invoke("post", "/admin/totp/disable", {
body: { userId: "target1" },
});
expect(res.statusCode).toBe(200);
const update = state.updates.find((u) => u.id === "target1");
expect(update?.changes).toMatchObject({
totpSecret: null,
totpEnabled: false,
totpBackupCodes: null,
});
expect(
state.auditCalls.some((c) => c.action === "admin_disable_totp"),
).toBe(true);
});
it("403s when the caller is not an admin", async () => {
state.currentUserId = "target1";
const res = await invoke("post", "/admin/totp/disable", {
body: { userId: "locked1" },
});
expect(res.statusCode).toBe(403);
});
it("400s when TOTP is not enabled for the target", async () => {
const res = await invoke("post", "/admin/totp/disable", {
body: { userId: "locked1" },
});
expect(res.statusCode).toBe(400);
});
it("404s for an unknown target", async () => {
const res = await invoke("post", "/admin/totp/disable", {
body: { userId: "ghost" },
});
expect(res.statusCode).toBe(404);
});
});
describe("GET /admin/export/:userId", () => {
it("423s when the target's data is locked", async () => {
const res = await invoke("get", "/admin/export/:userId", {
@@ -356,3 +355,72 @@ describe("GET /admin/export/:userId", () => {
expect(res.statusCode).toBe(403);
});
});
describe("DELETE /admin/:userId/second-factors", () => {
it("clears every factor, including one whose plugin is gone, and audits", async () => {
const reset = vi.fn(async () => {});
const dispose = registerSecondFactor({
id: "totp",
pluginId: "totp",
labelKey: "factor",
isEnrolled: async () => false,
verify: async () => false,
reset,
});
state.secondFactors = [
{ userId: "target1", pluginId: "totp", factorId: "totp" },
{ userId: "target1", pluginId: "gone-plugin", factorId: "yubikey" },
{ userId: "locked1", pluginId: "totp", factorId: "totp" },
];
const res = await invoke("delete", "/admin/:userId/second-factors", {
params: { userId: "target1" },
});
dispose();
expect(res.statusCode).toBe(200);
expect(state.secondFactors).toEqual([
{ userId: "locked1", pluginId: "totp", factorId: "totp" },
]);
expect(state.trustedDevicesCleared).toContain("target1");
// The running plugin's own reset dropped its secret.
expect(reset).toHaveBeenCalledWith("target1");
const audit = state.auditCalls.find(
(c) => c.action === "admin_reset_second_factors",
);
expect(audit).toMatchObject({ resourceId: "target1", success: true });
expect(JSON.parse(audit!.details as string).removed).toEqual(
expect.arrayContaining([
{ pluginId: "gone-plugin", factorId: "yubikey" },
]),
);
});
it("lists factors with their availability", async () => {
state.secondFactors = [
{ userId: "target1", pluginId: "gone-plugin", factorId: "yubikey" },
];
const res = await invoke("get", "/admin/:userId/second-factors", {
params: { userId: "target1" },
});
expect(res.statusCode).toBe(200);
expect((res.jsonBody as { factors: unknown[] }).factors).toEqual(
expect.arrayContaining([
expect.objectContaining({ factorId: "yubikey", available: false }),
]),
);
});
it("403s when the caller is not an admin", async () => {
state.currentUserId = "target1";
const res = await invoke("delete", "/admin/:userId/second-factors", {
params: { userId: "locked1" },
});
expect(res.statusCode).toBe(403);
});
it("404s for an unknown target", async () => {
const res = await invoke("delete", "/admin/:userId/second-factors", {
params: { userId: "ghost" },
});
expect(res.statusCode).toBe(404);
});
});
@@ -0,0 +1,242 @@
/**
* Linking an external (SSO or LDAP) account to a password account and back.
* The linked account keeps its sign-in identities, so it signs in through the
* same provider afterwards; unlinking drops them.
*/
import http from "node:http";
import type { AddressInfo } from "node:net";
import express from "express";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
interface User {
id: string;
username: string;
isAdmin: boolean;
isOidc: boolean;
passwordHash: string;
oidcIdentifier?: string | null;
clientId?: string;
}
const h = vi.hoisted(() => ({
users: new Map<string, User>(),
identities: [] as Array<{
userId: string;
providerId: string;
subject: string;
}>,
deleted: [] as string[],
revoked: [] as string[],
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentUserRepository: () => ({
findById: async (id: string) => h.users.get(id) ?? null,
findByUsername: async (username: string) =>
[...h.users.values()].find((user) => user.username === username) ?? null,
update: async (id: string, changes: Partial<User>) => {
Object.assign(h.users.get(id)!, changes);
},
}),
createCurrentUserAuthRepository: () => ({
listIdentitiesForUser: async (userId: string) =>
h.identities.filter((row) => row.userId === userId),
moveIdentities: async (from: string, to: string) => {
for (const row of h.identities) if (row.userId === from) row.userId = to;
},
unlinkIdentitiesForUser: async (userId: string) => {
h.identities = h.identities.filter((row) => row.userId !== userId);
},
}),
}));
vi.mock("../../../database/routes/delete-user-data.js", () => ({
deleteUserAndRelatedData: async (userId: string) => {
h.deleted.push(userId);
h.users.delete(userId);
},
}));
vi.mock("../../../utils/database-save-trigger.js", () => ({
DatabaseSaveTrigger: { forceSave: vi.fn(async () => {}) },
}));
vi.mock("../../../utils/auth-manager.js", () => ({ AuthManager: {} }));
vi.mock("../../../utils/logger.js", () => {
const log = {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
success: vi.fn(),
};
return { authLogger: log };
});
const { registerUserExternalAccountRoutes } =
await import("../../../database/routes/user-external-account-routes.js");
let server: http.Server;
let base: string;
beforeEach(async () => {
h.users = new Map([
[
"admin",
{
id: "admin",
username: "admin",
isAdmin: true,
isOidc: false,
passwordHash: "x",
},
],
[
"sso",
{
id: "sso",
username: "alice-sso",
isAdmin: false,
isOidc: true,
passwordHash: "",
oidcIdentifier: "ldap:4:alice",
},
],
[
"local",
{
id: "local",
username: "alice",
isAdmin: false,
isOidc: false,
passwordHash: "hash",
},
],
]);
h.identities = [{ userId: "sso", providerId: "ldap:4", subject: "alice" }];
h.deleted = [];
h.revoked = [];
const router = express.Router();
router.use(express.json());
registerUserExternalAccountRoutes(router, {
authenticateJWT: (req, _res, next) => {
(req as unknown as { userId: string }).userId =
req.header("x-user") ?? "";
next();
},
authManager: {
revokeAllUserSessions: async (userId: string) => {
h.revoked.push(userId);
},
logoutUser: () => {},
} as never,
});
const app = express();
app.use("/users", router);
server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, resolve));
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
afterEach(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
function post(path: string, body: unknown, user = "admin") {
return fetch(`${base}/users${path}`, {
method: "POST",
headers: { "content-type": "application/json", "x-user": user },
body: JSON.stringify(body),
});
}
describe("linking an external account to a password account", () => {
it("moves the identities and the old identifier, then removes the external account", async () => {
const response = await post("/link-oidc-to-password", {
oidcUserId: "sso",
targetUsername: "alice",
});
expect(response.status).toBe(200);
expect(h.users.get("local")).toMatchObject({
isOidc: true,
oidcIdentifier: "ldap:4:alice",
});
expect(h.identities).toEqual([
{ userId: "local", providerId: "ldap:4", subject: "alice" },
]);
expect(h.revoked).toEqual(["sso"]);
expect(h.deleted).toEqual(["sso"]);
});
it("takes the new path and field name", async () => {
const response = await post("/link-external-to-password", {
externalUserId: "sso",
targetUsername: "alice",
});
expect(response.status).toBe(200);
expect(h.identities[0].userId).toBe("local");
});
it("refuses a target that already signs in externally", async () => {
h.identities.push({ userId: "local", providerId: "ldap:4", subject: "x" });
const response = await post("/link-external-to-password", {
externalUserId: "sso",
targetUsername: "alice",
});
expect(response.status).toBe(400);
});
it("is for admins only", async () => {
const response = await post(
"/link-oidc-to-password",
{ oidcUserId: "sso", targetUsername: "alice" },
"local",
);
expect(response.status).toBe(403);
expect(h.identities[0].userId).toBe("sso");
});
it("refuses a target that is not a password account", async () => {
const response = await post("/link-oidc-to-password", {
oidcUserId: "sso",
targetUsername: "alice-sso",
});
expect(response.status).toBe(400);
});
});
describe("unlinking", () => {
it("drops the identities so the provider no longer signs in as the user", async () => {
await post("/link-oidc-to-password", {
oidcUserId: "sso",
targetUsername: "alice",
});
const response = await post("/unlink-oidc-from-password", {
userId: "local",
});
expect(response.status).toBe(200);
expect(h.users.get("local")).toMatchObject({
isOidc: false,
oidcIdentifier: null,
});
expect(h.identities).toEqual([]);
});
it("takes the new path", async () => {
await post("/link-external-to-password", {
externalUserId: "sso",
targetUsername: "alice",
});
const response = await post("/unlink-external-from-password", {
userId: "local",
});
expect(response.status).toBe(200);
expect(h.identities).toEqual([]);
});
it("refuses to leave an account with no way in", async () => {
const response = await post("/unlink-oidc-from-password", {
userId: "sso",
});
expect(response.status).toBe(400);
expect(h.identities).toHaveLength(1);
});
});
@@ -1,609 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
// user-oidc-utils imports the logger; stub it so importing stays side-effect-free.
vi.mock("../../../utils/logger.js", () => ({
authLogger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
success: vi.fn(),
},
}));
const {
isOIDCUserAllowed,
getOIDCConfigFromEnv,
extractOidcGroups,
extractOidcGroupsFromSources,
validateLogoutTokenClaims,
parseOidcRoleMap,
resolveOidcMappedRoles,
verifyOIDCToken,
describeFetchFailure,
isOIDCEnvOverrideEnabled,
} = await import("../../../database/routes/user-oidc-utils.js");
const BACKCHANNEL_LOGOUT_EVENT =
"http://schemas.openid.net/event/backchannel-logout";
afterEach(() => {
vi.restoreAllMocks();
});
describe("describeFetchFailure", () => {
it("unwraps the undici cause, which carries the reason that matters", () => {
// Every transport failure surfaces as this same outer message.
const error = new TypeError("fetch failed", {
cause: Object.assign(new Error("getaddrinfo ENOTFOUND idp.example"), {
code: "ENOTFOUND",
}),
});
expect(describeFetchFailure(error)).toBe(
"fetch failed: getaddrinfo ENOTFOUND idp.example (ENOTFOUND)",
);
});
it("falls back to the outer message when there is no cause", () => {
expect(describeFetchFailure(new Error("boom"))).toBe("boom");
});
it("handles a non-Error throw", () => {
expect(describeFetchFailure("nope")).toBe("nope");
});
});
describe("verifyOIDCToken JWKS diagnostics", () => {
const issuer = "https://login.microsoftonline.com/example/v2.0";
const token = "header.payload.signature";
it("reports every attempted URL and why it failed", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response("not found", { status: 404 }),
);
const error = await verifyOIDCToken(token, issuer, "client").catch(
(e) => e as Error,
);
expect(error.message).toMatch(/^Failed to fetch JWKS from any URL/);
expect(error.message).toContain(
`${issuer}/.well-known/openid-configuration: HTTP 404`,
);
expect(error.message).toContain(
`${issuer}/.well-known/jwks.json: HTTP 404`,
);
expect(error.message).toContain(`${issuer}/jwks/: HTTP 404`);
});
it("reports a transport failure with its underlying cause", async () => {
vi.spyOn(globalThis, "fetch").mockRejectedValue(
new TypeError("fetch failed", {
cause: Object.assign(new Error("self-signed certificate"), {
code: "SELF_SIGNED_CERT_IN_CHAIN",
}),
}),
);
const error = await verifyOIDCToken(token, issuer, "client").catch(
(e) => e as Error,
);
expect(error.message).toContain(
"self-signed certificate (SELF_SIGNED_CERT_IN_CHAIN)",
);
});
it("says so when discovery succeeds but advertises no jwks_uri", async () => {
vi.spyOn(globalThis, "fetch")
.mockResolvedValueOnce(
new Response(JSON.stringify({ issuer }), { status: 200 }),
)
.mockResolvedValue(new Response("not found", { status: 404 }));
const error = await verifyOIDCToken(token, issuer, "client").catch(
(e) => e as Error,
);
expect(error.message).toContain("no jwks_uri in the discovery document");
});
it("says so when a JWKS response carries no keys array", async () => {
vi.spyOn(globalThis, "fetch")
.mockResolvedValueOnce(
new Response(JSON.stringify({ jwks_uri: "https://idp.example/keys" }), {
status: 200,
}),
)
.mockResolvedValue(
new Response(JSON.stringify({ error: "unauthorized" }), {
status: 200,
}),
);
const error = await verifyOIDCToken(token, issuer, "client").catch(
(e) => e as Error,
);
expect(error.message).toContain(
'https://idp.example/keys: response contains no "keys" array',
);
});
});
describe("verifyOIDCToken", () => {
it("accepts a discovery document URL as the configured issuer", async () => {
const { exportJWK, generateKeyPair, SignJWT } = await import("jose");
const { publicKey, privateKey } = await generateKeyPair("RS256");
const jwk = await exportJWK(publicKey);
jwk.kid = "google-key";
const issuer = "https://accounts.google.com";
const clientId = "termix-client";
const token = await new SignJWT({ sub: "user-1" })
.setProtectedHeader({ alg: "RS256", kid: jwk.kid })
.setIssuer(issuer)
.setAudience(clientId)
.setExpirationTime("5m")
.sign(privateKey);
const fetchMock = vi
.spyOn(globalThis, "fetch")
.mockResolvedValueOnce(
new Response(JSON.stringify({ jwks_uri: `${issuer}/keys` }), {
status: 200,
}),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ keys: [jwk] }), { status: 200 }),
);
const payload = await verifyOIDCToken(
token,
`${issuer}/.well-known/openid-configuration`,
clientId,
);
expect(payload.sub).toBe("user-1");
expect(fetchMock).toHaveBeenNthCalledWith(
1,
`${issuer}/.well-known/openid-configuration`,
{},
);
});
it("uses the protected-header algorithm when the provider JWK omits alg", async () => {
const { exportJWK, generateKeyPair, SignJWT } = await import("jose");
const { publicKey, privateKey } = await generateKeyPair("RS256");
const jwk = await exportJWK(publicKey);
jwk.kid = "entra-key";
const issuer = "https://login.microsoftonline.com/example/v2.0";
const clientId = "termix-client";
const token = await new SignJWT({ sub: "user-1" })
.setProtectedHeader({ alg: "RS256", kid: jwk.kid })
.setIssuer(issuer)
.setAudience(clientId)
.setExpirationTime("5m")
.sign(privateKey);
const fetchMock = vi
.spyOn(globalThis, "fetch")
.mockResolvedValueOnce(
new Response(JSON.stringify({ jwks_uri: "https://idp.example/keys" }), {
status: 200,
}),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ keys: [jwk] }), { status: 200 }),
);
const payload = await verifyOIDCToken(token, issuer, clientId);
expect(payload.sub).toBe("user-1");
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});
describe("isOIDCUserAllowed", () => {
it("allows everyone when the allow-list is empty", () => {
expect(isOIDCUserAllowed("", "alice", "alice@x.com")).toBe(true);
expect(isOIDCUserAllowed(" ", "alice")).toBe(true);
});
it("allows everyone with the '*' wildcard", () => {
expect(isOIDCUserAllowed("*", "anyone", "anyone@x.com")).toBe(true);
});
it("matches an exact identifier (case-insensitive)", () => {
expect(isOIDCUserAllowed("alice,bob", "alice")).toBe(true);
expect(isOIDCUserAllowed("Alice", "alice")).toBe(true);
expect(isOIDCUserAllowed("alice", "ALICE")).toBe(true);
});
it("matches against the email as well as the identifier", () => {
expect(isOIDCUserAllowed("alice@x.com", "sub-123", "alice@x.com")).toBe(
true,
);
});
it("matches an @domain suffix pattern", () => {
expect(isOIDCUserAllowed("@company.com", "sub-1", "bob@company.com")).toBe(
true,
);
expect(isOIDCUserAllowed("@company.com", "sub-1", "bob@COMPANY.COM")).toBe(
true,
);
});
it("denies users not on the list", () => {
expect(isOIDCUserAllowed("alice,bob", "charlie", "charlie@x.com")).toBe(
false,
);
expect(isOIDCUserAllowed("@company.com", "sub-1", "bob@other.com")).toBe(
false,
);
});
it("ignores blank entries and surrounding whitespace in the list", () => {
expect(isOIDCUserAllowed(" alice , , bob ", "bob")).toBe(true);
});
it("does not match the email against an identifier-only pattern when email differs", () => {
expect(isOIDCUserAllowed("alice", "sub-123", "alice@x.com")).toBe(false);
});
it("matches *@domain.com wildcard pattern against emails", () => {
expect(
isOIDCUserAllowed("*@company.com", "sub-1", "john@company.com"),
).toBe(true);
expect(
isOIDCUserAllowed("*@company.com", "sub-1", "jane@COMPANY.COM"),
).toBe(true);
expect(isOIDCUserAllowed("*@company.com", "sub-1", "user@other.com")).toBe(
false,
);
});
it("matches glob patterns with multiple wildcards", () => {
expect(isOIDCUserAllowed("admin*", "admin_user")).toBe(true);
expect(isOIDCUserAllowed("admin*", "user_admin")).toBe(false);
});
});
describe("getOIDCConfigFromEnv", () => {
const REQUIRED = [
"OIDC_CLIENT_ID",
"OIDC_CLIENT_SECRET",
"OIDC_ISSUER_URL",
"OIDC_AUTHORIZATION_URL",
"OIDC_TOKEN_URL",
];
const OPTIONAL = [
"OIDC_USERINFO_URL",
"OIDC_IDENTIFIER_PATH",
"OIDC_NAME_PATH",
"OIDC_SCOPES",
"OIDC_ALLOWED_USERS",
"OIDC_ADMIN_GROUP",
"OIDC_ENV_OVERRIDE",
];
const saved: Record<string, string | undefined> = {};
beforeEach(() => {
for (const key of [...REQUIRED, ...OPTIONAL]) {
saved[key] = process.env[key];
delete process.env[key];
}
});
afterEach(() => {
for (const key of [...REQUIRED, ...OPTIONAL]) {
if (saved[key] === undefined) delete process.env[key];
else process.env[key] = saved[key];
}
});
it("returns null when any required variable is missing", () => {
process.env.OIDC_CLIENT_ID = "id";
process.env.OIDC_CLIENT_SECRET = "secret";
// issuer/authorization/token urls intentionally missing
expect(getOIDCConfigFromEnv()).toBeNull();
});
it("builds a config with defaults when all required vars are present", () => {
process.env.OIDC_CLIENT_ID = "id";
process.env.OIDC_CLIENT_SECRET = "secret";
process.env.OIDC_ISSUER_URL = "https://idp.example";
process.env.OIDC_AUTHORIZATION_URL = "https://idp.example/auth";
process.env.OIDC_TOKEN_URL = "https://idp.example/token";
const config = getOIDCConfigFromEnv();
expect(config).not.toBeNull();
expect(config?.client_id).toBe("id");
expect(config?.identifier_path).toBe("sub");
expect(config?.name_path).toBe("name");
expect(config?.scopes).toBe("openid email profile");
expect(config?.userinfo_url).toBe("");
});
it("honors overrides for optional vars", () => {
process.env.OIDC_CLIENT_ID = "id";
process.env.OIDC_CLIENT_SECRET = "secret";
process.env.OIDC_ISSUER_URL = "https://idp.example";
process.env.OIDC_AUTHORIZATION_URL = "https://idp.example/auth";
process.env.OIDC_TOKEN_URL = "https://idp.example/token";
process.env.OIDC_IDENTIFIER_PATH = "email";
process.env.OIDC_SCOPES = "openid";
const config = getOIDCConfigFromEnv();
expect(config?.identifier_path).toBe("email");
expect(config?.scopes).toBe("openid");
});
it("only enables database recovery override when explicitly requested", () => {
expect(isOIDCEnvOverrideEnabled()).toBe(false);
process.env.OIDC_ENV_OVERRIDE = "true";
expect(isOIDCEnvOverrideEnabled()).toBe(true);
});
});
describe("extractOidcGroups", () => {
it("reads the standard groups claim as an array", () => {
expect(extractOidcGroups({ groups: ["admin", "user"] })).toEqual([
"admin",
"user",
]);
});
it("splits a comma-separated string claim", () => {
expect(extractOidcGroups({ roles: "admin, user" })).toEqual([
"admin",
"user",
]);
});
it("falls back through groups, roles, then group", () => {
expect(extractOidcGroups({ group: "ops" })).toEqual(["ops"]);
});
it("reads a custom claim path when provided", () => {
const userInfo = {
"zitadel:grants:groups:123": ["user", "admin"],
groups: ["ignored"],
};
expect(extractOidcGroups(userInfo, "zitadel:grants:groups:123")).toEqual([
"user",
"admin",
]);
});
it("uses object keys as group names (Zitadel roles object)", () => {
const userInfo = {
"urn:zitadel:iam:org:project:roles": { admin: {}, user: {} },
};
expect(
extractOidcGroups(userInfo, "urn:zitadel:iam:org:project:roles"),
).toEqual(["admin", "user"]);
});
it("falls back to defaults when the custom claim is absent", () => {
expect(extractOidcGroups({ groups: ["admin"] }, "missing")).toEqual([
"admin",
]);
});
it("returns an empty array when no groups are present", () => {
expect(extractOidcGroups({})).toEqual([]);
});
});
describe("extractOidcGroupsFromSources", () => {
it("preserves ID token groups when userinfo omits them", () => {
expect(
extractOidcGroupsFromSources([
{ groups: ["admins", "users"] },
{ sub: "user-1", name: "Example User" },
]),
).toEqual(["admins", "users"]);
});
it("combines and deduplicates groups from both verified sources", () => {
expect(
extractOidcGroupsFromSources([
{ roles: ["users", "operators"] },
{ roles: ["operators", "admins"] },
]),
).toEqual(["users", "operators", "admins"]);
});
it("supports a configured group claim across sources", () => {
expect(
extractOidcGroupsFromSources(
[{ custom_groups: ["admins"] }, { custom_groups: ["users"] }],
"custom_groups",
),
).toEqual(["admins", "users"]);
});
});
describe("validateLogoutTokenClaims", () => {
const validClaims = {
sub: "subject-1",
sid: "session-1",
iat: 1_783_641_600,
jti: "logout-1",
events: { [BACKCHANNEL_LOGOUT_EVENT]: {} },
};
it("accepts a spec-compliant back-channel logout payload", () => {
expect(validateLogoutTokenClaims(validClaims)).toEqual({
sub: "subject-1",
sid: "session-1",
jti: "logout-1",
});
});
it("requires the logout event to contain an object", () => {
expect(() =>
validateLogoutTokenClaims({
...validClaims,
events: { [BACKCHANNEL_LOGOUT_EVENT]: true },
}),
).toThrow("missing back-channel logout event");
});
it("requires iat and jti claims", () => {
expect(() =>
validateLogoutTokenClaims({ ...validClaims, iat: undefined }),
).toThrow("missing iat claim");
expect(() =>
validateLogoutTokenClaims({ ...validClaims, jti: "" }),
).toThrow("missing jti claim");
});
it("rejects nonce and requires sub or sid", () => {
expect(() =>
validateLogoutTokenClaims({ ...validClaims, nonce: "forbidden" }),
).toThrow("must not contain a nonce");
expect(() =>
validateLogoutTokenClaims({ ...validClaims, sub: null, sid: null }),
).toThrow("must contain sub and/or sid");
});
});
describe("parseOidcRoleMap", () => {
it("returns an empty map for blank input", () => {
expect(parseOidcRoleMap(undefined).size).toBe(0);
expect(parseOidcRoleMap(null).size).toBe(0);
expect(parseOidcRoleMap(" ").size).toBe(0);
});
it("parses comma-separated group:role pairs", () => {
const map = parseOidcRoleMap(
"devops-interns:devops-intern,devops-seniors:devops-senior",
);
expect(map.get("devops-interns")).toBe("devops-intern");
expect(map.get("devops-seniors")).toBe("devops-senior");
expect(map.size).toBe(2);
});
it("parses newline-separated pairs and trims whitespace", () => {
const map = parseOidcRoleMap(" a : role-a \n b:role-b \n");
expect(map.get("a")).toBe("role-a");
expect(map.get("b")).toBe("role-b");
});
it("normalizes leading slashes and case in group names", () => {
const map = parseOidcRoleMap("/DevOps-Interns:devops-intern");
expect(map.get("devops-interns")).toBe("devops-intern");
});
it("skips malformed entries instead of throwing", () => {
const map = parseOidcRoleMap("no-colon,:missing-group,missing-role:,ok:r");
expect(map.size).toBe(1);
expect(map.get("ok")).toBe("r");
});
it("splits on the last colon so group names may contain colons", () => {
const map = parseOidcRoleMap("ns:team:role-x");
expect(map.get("ns:team")).toBe("role-x");
});
it("preserves role-name case verbatim", () => {
// Role names must match roles.name exactly, so they are not lowercased.
expect(parseOidcRoleMap("g:DevOps_Senior").get("g")).toBe("DevOps_Senior");
});
});
describe("resolveOidcMappedRoles", () => {
const roleMap = parseOidcRoleMap(
"devops-interns:devops-intern,devops-seniors:devops-senior",
);
it("reports every mapped role as managed regardless of membership", () => {
const { managed } = resolveOidcMappedRoles([], roleMap);
expect([...managed].sort()).toEqual(["devops-intern", "devops-senior"]);
});
it("desires only the roles whose groups the user is in", () => {
const { desired } = resolveOidcMappedRoles(["devops-interns"], roleMap);
expect([...desired]).toEqual(["devops-intern"]);
});
it("matches full group paths emitted by Keycloak", () => {
const { desired } = resolveOidcMappedRoles(["/devops-seniors"], roleMap);
expect([...desired]).toEqual(["devops-senior"]);
});
it("ignores groups that are not mapped", () => {
const { desired } = resolveOidcMappedRoles(
["finance", "devops-interns"],
roleMap,
);
expect([...desired]).toEqual(["devops-intern"]);
});
it("supports a user in multiple mapped groups", () => {
const { desired } = resolveOidcMappedRoles(
["devops-interns", "devops-seniors"],
roleMap,
);
expect([...desired].sort()).toEqual(["devops-intern", "devops-senior"]);
});
it("desires nothing when the map is empty", () => {
const { desired, managed } = resolveOidcMappedRoles(
["devops-interns"],
new Map(),
);
expect(desired.size).toBe(0);
expect(managed.size).toBe(0);
});
});
// Imported as a namespace rather than destructured into the shared block at the
// top of the file, so this suite stays independent of what that block binds.
const oidcUtils = await import("../../../database/routes/user-oidc-utils.js");
describe("verifyOIDCToken token shape", () => {
const issuer = "https://idp.example.com/application/o/termix";
// The shape check runs before any network call, so no fetch stub is needed.
const fetchSpy = vi.fn();
beforeEach(() => {
vi.stubGlobal("fetch", fetchSpy);
});
afterEach(() => {
vi.unstubAllGlobals();
fetchSpy.mockReset();
});
it("reports an encrypted (JWE) token as a format error", async () => {
const jwe = ["header", "key", "iv", "ciphertext", "tag"].join(".");
await expect(
oidcUtils.verifyOIDCToken(jwe, issuer, "client"),
).rejects.toThrow(oidcUtils.OIDCTokenFormatError);
await expect(
oidcUtils.verifyOIDCToken(jwe, issuer, "client"),
).rejects.toThrow(/JWE \(encrypted\)/);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("reports any other non-JWS segment count as a format error", async () => {
await expect(
oidcUtils.verifyOIDCToken("header.payload", issuer, "client"),
).rejects.toThrow(/expected 3 segments, got 2/);
await expect(
oidcUtils.verifyOIDCToken("opaque", issuer, "client"),
).rejects.toThrow(/expected 3 segments, got 1/);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("lets a three-segment token through to key resolution", async () => {
fetchSpy.mockResolvedValue({ ok: false });
// Reaches JWKS fetching, so it fails on the key lookup rather than the shape.
await expect(
oidcUtils.verifyOIDCToken("header.payload.signature", issuer, "client"),
).rejects.not.toThrow(oidcUtils.OIDCTokenFormatError);
expect(fetchSpy).toHaveBeenCalled();
});
});
@@ -6,6 +6,8 @@ const calls = vi.hoisted(() => ({
deletedFor: [] as string[],
rotatedFor: [] as string[],
legacyWrapsDeletedFor: [] as string[],
dataWipedEvents: [] as Array<{ userId: string }>,
secondFactorsReset: [] as string[],
}));
function deletingRepo(label: string) {
@@ -26,14 +28,20 @@ vi.mock("../../../database/repositories/factory.js", () => ({
}),
createCurrentSettingsRepository: () => ({}),
createCurrentSshCredentialUsageRepository: deletingRepo("usage"),
createCurrentFileManagerBookmarkRepository: deletingRepo("bookmarks"),
createCurrentRecentActivityRepository: deletingRepo("activity"),
createCurrentDismissedAlertRepository: deletingRepo("alerts"),
createCurrentSnippetRepository: deletingRepo("snippets"),
createCurrentHostRepository: deletingRepo("hosts"),
createCurrentCredentialRepository: deletingRepo("credentials"),
}));
vi.mock("../../../plugins/events.js", () => ({
pluginEvents: {
emit: (_topic: string, payload: { userId: string }) => {
calls.dataWipedEvents.push(payload);
},
},
TOPICS: { userDataWiped: "user.data_wiped" },
}));
vi.mock("../../../utils/user-keys.js", () => ({
UserKeyManager: {
getInstance: () => ({
@@ -51,6 +59,13 @@ vi.mock("../../../utils/crypto-migration/dek-migration.js", () => ({
},
}));
vi.mock("../../../auth/second-factor-admin.js", () => ({
resetUserSecondFactors: async (userId: string) => {
calls.secondFactorsReset.push(userId);
return [];
},
}));
import { resetUserPassword } from "../../../database/routes/user-password-reset-routes.js";
function fakeAuthManager(unlocked: boolean): AuthManager {
@@ -62,9 +77,11 @@ function fakeAuthManager(unlocked: boolean): AuthManager {
beforeEach(() => {
calls.userUpdates = [];
calls.secondFactorsReset = [];
calls.deletedFor = [];
calls.rotatedFor = [];
calls.legacyWrapsDeletedFor = [];
calls.dataWipedEvents = [];
});
describe("resetUserPassword", () => {
@@ -107,17 +124,13 @@ describe("resetUserPassword", () => {
expect(outcome).toEqual({ status: "reset", dataWiped: true });
expect(calls.deletedFor).toEqual([
"usage:user-1",
"bookmarks:user-1",
"activity:user-1",
"alerts:user-1",
"snippets:user-1",
"hosts:user-1",
"credentials:user-1",
]);
expect(calls.dataWipedEvents).toEqual([{ userId: "user-1" }]);
expect(calls.rotatedFor).toEqual(["user-1"]);
expect(calls.legacyWrapsDeletedFor).toEqual(["user-1"]);
expect(
calls.userUpdates.some(([, update]) => update.totpEnabled === false),
).toBe(true);
expect(calls.secondFactorsReset).toEqual(["user-1"]);
});
});
@@ -1,21 +0,0 @@
import { describe, expect, it } from "vitest";
import { validateDefaultsJson } from "../../../database/routes/user-preferences.js";
describe("user connection defaults validation", () => {
it("accepts JSON objects", () => {
expect(validateDefaultsJson('{"fontSize":16}')).toBe(true);
expect(validateDefaultsJson("{}")).toBe(true);
});
it("rejects malformed JSON and non-object values", () => {
expect(validateDefaultsJson("{")).toBe(false);
expect(validateDefaultsJson("null")).toBe(false);
expect(validateDefaultsJson("[]")).toBe(false);
});
it("rejects payloads larger than 32 KiB", () => {
expect(
validateDefaultsJson(JSON.stringify({ value: "x".repeat(32_768) })),
).toBe(false);
});
});
@@ -0,0 +1,79 @@
/**
* The old admin host defaults routes are gone: host defaults live under
* /host/defaults now. The GET used to hand the admin's proxy password to any
* signed-in user.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import express, { type RequestHandler } from "express";
import request from "supertest";
const state = vi.hoisted(() => ({
settings: {} as Record<string, string>,
admin: true,
}));
vi.mock("../../../utils/logger.js", () => ({
authLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
databaseLogger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
getGlobalLogLevel: () => "info",
setGlobalLogLevel: vi.fn(),
}));
vi.mock("../../../utils/audit-logger.js", () => ({
logAudit: vi.fn(async () => {}),
getRequestMeta: () => ({ ipAddress: "127.0.0.1", userAgent: "test" }),
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentSettingsRepository: () => ({
get: async (key: string) => state.settings[key] ?? null,
set: async (key: string, value: string) => {
state.settings[key] = value;
},
}),
createCurrentUserRepository: () => ({
findById: async (id: string) => ({
id,
username: "admin",
isAdmin: state.admin,
}),
}),
}));
const { registerUserSettingsRoutes } =
await import("../../../database/routes/user-settings-routes.js");
const authenticate: RequestHandler = (req, _res, next) => {
(req as unknown as { userId: string }).userId = "u1";
next();
};
function app() {
const router = express.Router();
registerUserSettingsRoutes(router, authenticate);
const server = express();
server.use(express.json());
server.use("/users", router);
return server;
}
beforeEach(() => {
state.settings = {};
state.admin = true;
});
describe("/users/host-defaults", () => {
it("is no longer served, so the stored row never leaves the server", async () => {
state.settings.host_defaults = JSON.stringify({
useSocks5: true,
socks5Password: "secret",
});
const read = await request(app()).get("/users/host-defaults");
expect(read.status).toBe(404);
expect(JSON.stringify(read.body)).not.toContain("secret");
const write = await request(app())
.patch("/users/host-defaults")
.send({ useSocks5: false });
expect(write.status).toBe(404);
expect(JSON.parse(state.settings.host_defaults).useSocks5).toBe(true);
});
});
@@ -1,82 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import bcrypt from "bcryptjs";
import speakeasy from "speakeasy";
// The route module imports repository factories and the logger; stub both so
// importing stays inert.
const userRepositoryUpdate = vi.fn().mockResolvedValue(null);
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentUserRepository: () => ({
update: userRepositoryUpdate,
}),
}));
vi.mock("../../../utils/logger.js", () => ({
authLogger: {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
success: vi.fn(),
},
}));
const { verifyTotpReauth } =
await import("../../../database/routes/user-totp-routes.js");
type AnyUser = Parameters<typeof verifyTotpReauth>[0];
const secret = speakeasy.generateSecret({ name: "test" }).base32;
function makeUser(overrides: Partial<AnyUser> = {}): AnyUser {
return {
id: "user-1",
isOidc: false,
passwordHash: bcrypt.hashSync("correct-horse", 4),
totpSecret: secret,
totpBackupCodes: JSON.stringify(["BACKUP01", "BACKUP02"]),
totpEnabled: true,
...overrides,
} as AnyUser;
}
describe("verifyTotpReauth", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("does not accept the account password as a second factor", async () => {
expect(await verifyTotpReauth(makeUser(), "correct-horse")).toBe(false);
});
it("accepts a valid TOTP code without a password", async () => {
const token = speakeasy.totp({ secret, encoding: "base32" });
expect(await verifyTotpReauth(makeUser(), token)).toBe(true);
});
it("accepts a valid backup code and consumes it", async () => {
const result = await verifyTotpReauth(makeUser(), "BACKUP01");
expect(result).toBe(true);
expect(userRepositoryUpdate).toHaveBeenCalledWith("user-1", {
totpBackupCodes: JSON.stringify(["BACKUP02"]),
});
});
it("rejects a wrong password / invalid code", async () => {
expect(await verifyTotpReauth(makeUser(), "wrong")).toBe(false);
expect(userRepositoryUpdate).not.toHaveBeenCalled();
});
it("ignores the password path for OIDC users but still accepts TOTP", async () => {
const token = speakeasy.totp({ secret, encoding: "base32" });
const oidcUser = makeUser({ isOidc: true, passwordHash: null });
expect(await verifyTotpReauth(oidcUser, token)).toBe(true);
expect(await verifyTotpReauth(oidcUser, "anything")).toBe(false);
});
it("handles malformed backup-code JSON without throwing", async () => {
const user = makeUser({ totpBackupCodes: "not json" });
expect(await verifyTotpReauth(user, "BACKUP01")).toBe(false);
});
});
@@ -1,140 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Request, Response, Router } from "express";
import type { AuthManager } from "../../../utils/auth-manager.js";
const mocks = vi.hoisted(() => ({
verify: vi.fn(),
user: vi.fn(),
update: vi.fn(),
}));
vi.mock("@simplewebauthn/server", () => ({
generateAuthenticationOptions: vi
.fn()
.mockResolvedValue({ challenge: "challenge" }),
verifyAuthenticationResponse: mocks.verify,
generateRegistrationOptions: vi.fn(),
verifyRegistrationResponse: vi.fn(),
}));
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentUserRepository: () => ({ findById: mocks.user }),
createCurrentWebauthnCredentialRepository: () => ({
findByCredentialId: vi.fn().mockResolvedValue({
id: 1,
credentialId: "key",
userId: "user",
publicKey: "YQ",
counter: 0,
transports: "[]",
}),
updateAuthState: mocks.update,
}),
getCurrentSettingValue: vi.fn(),
}));
vi.mock("../../../utils/logger.js", () => ({ authLogger: { warn: vi.fn() } }));
vi.mock("../../../utils/user-agent-parser.js", () => ({
parseUserAgent: () => ({ type: "browser", deviceInfo: "test" }),
generateDeviceFingerprint: () => "device",
getDeviceId: () => "id",
}));
const { registerUserWebAuthnRoutes } =
await import("../../../database/routes/user-webauthn-routes.js");
type Handler = (req: Request, res: Response) => Promise<unknown>;
const handlers = new Map<string, Handler>();
const manager = {
authenticateWebAuthnUser: vi.fn().mockResolvedValue(true),
isTrustedDevice: vi.fn().mockResolvedValue(false),
generateJWTToken: vi.fn().mockResolvedValue("token"),
getSecureCookieOptions: vi.fn().mockReturnValue({ httpOnly: true }),
};
registerUserWebAuthnRoutes(
{
post: (path: string, ...callbacks: Handler[]) =>
handlers.set(path, callbacks.at(-1)!),
get: vi.fn(),
delete: vi.fn(),
} as unknown as Router,
{
authenticateJWT: vi.fn(),
authManager: manager as unknown as AuthManager,
isNativeAppRequest: () => false,
},
);
function response() {
const res = { json: vi.fn(), status: vi.fn(), cookie: vi.fn() };
res.status.mockReturnValue(res);
return res;
}
async function login(userVerification: string) {
const options = response();
await handlers.get("/webauthn/authenticate/options")!(
{
body: { userVerification },
get: () => "https://termix.test",
} as unknown as Request,
options as unknown as Response,
);
const challengeId = options.json.mock.calls[0][0].challengeId;
const res = response();
await handlers.get("/webauthn/authenticate/verify")!(
{
body: { challengeId, response: { id: "key" }, rememberMe: true },
} as Request,
res as unknown as Response,
);
return res;
}
beforeEach(() => {
vi.clearAllMocks();
mocks.user.mockResolvedValue({
id: "user",
username: "alice",
totpEnabled: true,
});
manager.isTrustedDevice.mockResolvedValue(false);
mocks.verify.mockResolvedValue({
verified: true,
authenticationInfo: { userVerified: false, newCounter: 1 },
});
});
describe("WebAuthn second factor policy", () => {
it.each(["discouraged", "preferred", "required"])(
"does not let request preference %s bypass TOTP without verified UV",
async (preference) => {
const res = await login(preference);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ requires_totp: true, temp_token: "token" }),
);
expect(manager.generateJWTToken).toHaveBeenCalledWith("user", {
pendingTOTP: true,
expiresIn: "10m",
});
expect(res.cookie).not.toHaveBeenCalled();
},
);
it("allows verified user verification to satisfy TOTP", async () => {
mocks.verify.mockResolvedValue({
verified: true,
authenticationInfo: { userVerified: true, newCounter: 1 },
});
const res = await login("preferred");
expect(res.cookie).toHaveBeenCalledWith("jwt", "token", { httpOnly: true });
expect(manager.isTrustedDevice).not.toHaveBeenCalled();
});
it("preserves trusted-device exemption", async () => {
manager.isTrustedDevice.mockResolvedValue(true);
const res = await login("discouraged");
expect(manager.isTrustedDevice).toHaveBeenCalledWith("user", "device");
expect(res.cookie).toHaveBeenCalled();
});
it("never creates a session for an invalid assertion", async () => {
mocks.verify.mockResolvedValue({ verified: false });
const res = await login("preferred");
expect(res.status).toHaveBeenCalledWith(401);
expect(manager.generateJWTToken).not.toHaveBeenCalled();
expect(res.cookie).not.toHaveBeenCalled();
});
it("allows users without TOTP to log in with a possession-only key", async () => {
mocks.user.mockResolvedValue({ id: "user", totpEnabled: false });
expect((await login("discouraged")).cookie).toHaveBeenCalled();
});
});
@@ -1,511 +0,0 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { Request, Response, Router } from "express";
type WorkspaceRow = {
id: number;
userId: string;
name: string;
color: string | null;
icon: string | null;
kind: "manual" | "last_session";
isDefault: boolean;
payload: string;
syncId: string;
createdAt: string;
updatedAt: string;
lastUsedAt: string | null;
};
const state = vi.hoisted(() => ({
currentUserId: "user-1",
workspaces: new Map<number, WorkspaceRow>(),
nextId: 1,
}));
vi.mock("../../../database/db/index.js", () => ({ db: {} }));
vi.mock("../../../utils/logger.js", () => ({
databaseLogger: {
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
success: vi.fn(),
},
}));
vi.mock("../../../utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() =>
(req: Record<string, unknown>, _res: unknown, next: () => void) => {
req.userId = state.currentUserId;
next();
},
createDataAccessMiddleware:
() => (_req: unknown, _res: unknown, next: () => void) =>
next(),
}),
},
}));
function findByIdForUser(userId: string, id: number): WorkspaceRow | null {
const row = state.workspaces.get(id);
return row && row.userId === userId ? row : null;
}
vi.mock("../../../database/repositories/factory.js", () => ({
createCurrentWorkspaceRepository: () => ({
listByUser: async (userId: string) =>
[...state.workspaces.values()].filter((w) => w.userId === userId),
findById: async (userId: string, id: number) => findByIdForUser(userId, id),
findLastSession: async (userId: string) =>
[...state.workspaces.values()].find(
(w) => w.userId === userId && w.kind === "last_session",
) ?? null,
upsertLastSession: async (userId: string, payload: string) => {
const existing = [...state.workspaces.values()].find(
(w) => w.userId === userId && w.kind === "last_session",
);
if (existing) {
existing.payload = payload;
existing.updatedAt = new Date().toISOString();
return existing;
}
const row: WorkspaceRow = {
id: state.nextId++,
userId,
name: "Last Session",
color: null,
icon: null,
kind: "last_session",
isDefault: false,
payload,
syncId: `sync-${state.nextId}`,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
lastUsedAt: null,
};
state.workspaces.set(row.id, row);
return row;
},
create: async (
userId: string,
input: {
name: string;
color?: string | null;
icon?: string | null;
payload: string;
},
) => {
const row: WorkspaceRow = {
id: state.nextId++,
userId,
name: input.name,
color: input.color ?? null,
icon: input.icon ?? null,
kind: "manual",
isDefault: false,
payload: input.payload,
syncId: `sync-${state.nextId}`,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
lastUsedAt: null,
};
state.workspaces.set(row.id, row);
return row;
},
update: async (
userId: string,
id: number,
input: { name?: string; color?: string | null; icon?: string | null },
) => {
const row = findByIdForUser(userId, id);
if (!row || row.kind !== "manual") return null;
if (input.name !== undefined) row.name = input.name;
if (input.color !== undefined) row.color = input.color;
if (input.icon !== undefined) row.icon = input.icon;
return row;
},
updateContent: async (userId: string, id: number, payload: string) => {
const row = findByIdForUser(userId, id);
if (!row || row.kind !== "manual") return null;
row.payload = payload;
return row;
},
setDefault: async (userId: string, id: number) => {
const row = findByIdForUser(userId, id);
if (!row || row.kind !== "manual") return null;
for (const w of state.workspaces.values()) {
if (w.userId === userId && w.kind === "manual") w.isDefault = false;
}
row.isDefault = true;
return row;
},
unsetDefault: async (userId: string, id: number) => {
const row = findByIdForUser(userId, id);
if (!row || row.kind !== "manual") return null;
row.isDefault = false;
return row;
},
touchLastUsed: async (userId: string, id: number) => {
const row = findByIdForUser(userId, id);
if (row) row.lastUsedAt = new Date().toISOString();
},
delete: async (userId: string, id: number) => {
const row = findByIdForUser(userId, id);
if (!row || row.kind !== "manual") return false;
state.workspaces.delete(id);
return true;
},
}),
}));
const { default: router } =
await import("../../../database/routes/workspaces.js");
function findLayer(method: string, path: string) {
const stack = (router as unknown as Router).stack as Array<{
route?: {
path: string;
methods: Record<string, boolean>;
stack: Array<{ handle: (req: Request, res: Response) => unknown }>;
};
}>;
const layer = stack.find(
(l) => l.route?.path === path && l.route?.methods[method],
);
if (!layer?.route) throw new Error(`No route for ${method} ${path}`);
return layer.route.stack[layer.route.stack.length - 1].handle;
}
function makeReqRes(overrides: {
body?: Record<string, unknown>;
params?: Record<string, unknown>;
}) {
const req = {
userId: state.currentUserId,
body: overrides.body ?? {},
params: overrides.params ?? {},
headers: {},
} as unknown as Request;
const res = {
statusCode: 200,
jsonBody: null as unknown,
status(code: number) {
(this as unknown as { statusCode: number }).statusCode = code;
return this;
},
json(payload: unknown) {
(this as unknown as { jsonBody: unknown }).jsonBody = payload;
return this;
},
} as unknown as Response & { statusCode: number; jsonBody: unknown };
return { req, res };
}
async function invoke(
method: string,
path: string,
overrides: {
body?: Record<string, unknown>;
params?: Record<string, unknown>;
} = {},
) {
const handler = findLayer(method, path);
const { req, res } = makeReqRes(overrides);
await handler(req, res);
return res as unknown as {
statusCode: number;
jsonBody: Record<string, unknown> | null;
};
}
beforeEach(() => {
state.currentUserId = "user-1";
state.workspaces = new Map();
state.nextId = 1;
});
describe("GET /", () => {
it("returns the list with a computed tabCount", async () => {
await invoke("post", "/", {
body: {
name: "Test A",
payload: { version: 1, tabs: [{ slotId: "a" }, { slotId: "b" }] },
},
});
const res = await invoke("get", "/");
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toHaveLength(1);
expect(
(res.jsonBody as unknown as { tabCount: number }[])[0].tabCount,
).toBe(2);
});
});
describe("POST /", () => {
it("400s when name is missing", async () => {
const res = await invoke("post", "/", {
body: { payload: { version: 1, tabs: [] } },
});
expect(res.statusCode).toBe(400);
});
it("400s when payload has no tabs array", async () => {
const res = await invoke("post", "/", {
body: { name: "Test A", payload: { version: 1 } },
});
expect(res.statusCode).toBe(400);
});
it("200s and creates a manual workspace", async () => {
const res = await invoke("post", "/", {
body: { name: "Test A", payload: { version: 1, tabs: [] } },
});
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toMatchObject({ name: "Test A", kind: "manual" });
});
});
describe("PATCH /:id", () => {
it("rejects renaming the last_session row", async () => {
const created = await invoke("put", "/last-session", {
body: { payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("patch", "/:id", {
params: { id: String(id) },
body: { name: "Nope" },
});
expect(res.statusCode).toBe(404);
});
it("renames a manual workspace", async () => {
const created = await invoke("post", "/", {
body: { name: "Old", payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("patch", "/:id", {
params: { id: String(id) },
body: { name: "New" },
});
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toMatchObject({ name: "New" });
});
it("404s for a nonexistent id", async () => {
const res = await invoke("patch", "/:id", {
params: { id: "999" },
body: { name: "New" },
});
expect(res.statusCode).toBe(404);
});
});
describe("PUT /:id/content", () => {
it("updates payload for a manual workspace", async () => {
const created = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("put", "/:id/content", {
params: { id: String(id) },
body: { payload: { version: 1, tabs: [{ slotId: "x" }] } },
});
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toMatchObject({ tabCount: 1 });
});
it("404s on wrong owner", async () => {
const created = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
state.currentUserId = "user-2";
const res = await invoke("put", "/:id/content", {
params: { id: String(id) },
body: { payload: { version: 1, tabs: [] } },
});
expect(res.statusCode).toBe(404);
});
});
describe("DELETE /:id", () => {
it("rejects deleting the last_session row", async () => {
const created = await invoke("put", "/last-session", {
body: { payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("delete", "/:id", { params: { id: String(id) } });
expect(res.statusCode).toBe(404);
});
it("404s for a nonexistent id", async () => {
const res = await invoke("delete", "/:id", { params: { id: "999" } });
expect(res.statusCode).toBe(404);
});
it("deletes a manual workspace", async () => {
const created = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("delete", "/:id", { params: { id: String(id) } });
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toEqual({ success: true });
});
});
describe("POST /:id/duplicate", () => {
it("produces a second independent row", async () => {
const created = await invoke("post", "/", {
body: {
name: "A",
payload: { version: 1, tabs: [{ slotId: "a" }] },
},
});
const id = (created.jsonBody as unknown as { id: number }).id;
const dup = await invoke("post", "/:id/duplicate", {
params: { id: String(id) },
body: { name: "A (copy)" },
});
expect(dup.statusCode).toBe(200);
expect(dup.jsonBody).toMatchObject({ name: "A (copy)", tabCount: 1 });
const updateOriginal = await invoke("put", "/:id/content", {
params: { id: String(id) },
body: { payload: { version: 1, tabs: [] } },
});
expect(updateOriginal.jsonBody).toMatchObject({ tabCount: 0 });
const dupId = (dup.jsonBody as unknown as { id: number }).id;
const refetched = await invoke("get", "/");
const dupRow = (
refetched.jsonBody as unknown as { id: number; tabCount: number }[]
).find((w) => w.id === dupId);
expect(dupRow?.tabCount).toBe(1);
});
});
describe("POST /:id/set-default", () => {
it("clears a previous default and sets the new one", async () => {
const a = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const b = await invoke("post", "/", {
body: { name: "B", payload: { version: 1, tabs: [] } },
});
const aId = (a.jsonBody as unknown as { id: number }).id;
const bId = (b.jsonBody as unknown as { id: number }).id;
await invoke("post", "/:id/set-default", { params: { id: String(aId) } });
const second = await invoke("post", "/:id/set-default", {
params: { id: String(bId) },
});
expect(second.jsonBody).toMatchObject({ isDefault: true });
const list = await invoke("get", "/");
const aRow = (
list.jsonBody as unknown as { id: number; isDefault: boolean }[]
).find((w) => w.id === aId);
expect(aRow?.isDefault).toBe(false);
});
it("is idempotent when re-called on an already-default row", async () => {
const a = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const aId = (a.jsonBody as unknown as { id: number }).id;
await invoke("post", "/:id/set-default", { params: { id: String(aId) } });
const again = await invoke("post", "/:id/set-default", {
params: { id: String(aId) },
});
expect(again.statusCode).toBe(200);
expect(again.jsonBody).toMatchObject({ isDefault: true });
});
});
describe("POST /:id/unset-default", () => {
it("clears isDefault on a manual workspace", async () => {
const a = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const aId = (a.jsonBody as unknown as { id: number }).id;
await invoke("post", "/:id/set-default", { params: { id: String(aId) } });
const res = await invoke("post", "/:id/unset-default", {
params: { id: String(aId) },
});
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toMatchObject({ isDefault: false });
});
it("rejects unsetting the last_session row", async () => {
const created = await invoke("put", "/last-session", {
body: { payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("post", "/:id/unset-default", {
params: { id: String(id) },
});
expect(res.statusCode).toBe(404);
});
});
describe("POST /:id/apply", () => {
it("touches lastUsedAt and returns the parsed payload", async () => {
const created = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [{ slotId: "a" }] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("post", "/:id/apply", {
params: { id: String(id) },
});
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toMatchObject({
payload: { version: 1, tabs: [{ slotId: "a" }] },
});
expect(
(res.jsonBody as unknown as { lastUsedAt: string | null }).lastUsedAt,
).toBeTruthy();
});
});
describe("PUT /last-session and GET /last-session", () => {
it("returns null before any save", async () => {
const res = await invoke("get", "/last-session");
expect(res.jsonBody).toBeNull();
});
it("upserts idempotently - two calls produce one row", async () => {
await invoke("put", "/last-session", {
body: { payload: { version: 1, tabs: [] } },
});
await invoke("put", "/last-session", {
body: { payload: { version: 1, tabs: [{ slotId: "a" }] } },
});
const list = await invoke("get", "/");
const lastSessionRows = (
list.jsonBody as unknown as { kind: string }[]
).filter((w) => w.kind === "last_session");
expect(lastSessionRows).toHaveLength(1);
const res = await invoke("get", "/last-session");
expect(res.jsonBody).toMatchObject({ tabCount: 1 });
});
});
@@ -1,93 +0,0 @@
import { describe, expect, it } from "vitest";
import {
deserializeSyncReferences,
orderSyncRows,
serializeSyncReferences,
} from "../../database/routes/sync-references.js";
describe("sync references", () => {
it("serializes database-local host IDs as stable sync IDs", async () => {
const row = await serializeSyncReferences(
"hosts",
{
id: 7,
credentialId: 12,
rdpCredentialId: 13,
vncCredentialId: null,
telnetCredentialId: null,
vaultProfileId: 4,
parentHostId: 3,
},
async (entityType, id) => `${entityType}-${id}`,
);
expect(row).toMatchObject({
credentialSyncId: "sshCredentials-12",
rdpCredentialSyncId: "sshCredentials-13",
vncCredentialSyncId: null,
telnetCredentialSyncId: null,
vaultProfileSyncId: "vaultProfiles-4",
parentHostSyncId: "hosts-3",
});
expect(row).not.toHaveProperty("credentialId");
expect(row).not.toHaveProperty("vaultProfileId");
});
it("resolves stable sync IDs to IDs from the receiving database", async () => {
const ids = new Map([
["sshCredentials:credential-sync", 91],
["vaultProfiles:vault-sync", 37],
["hosts:parent-sync", 52],
]);
const row = await deserializeSyncReferences(
"hosts",
{
credentialId: 12,
credentialSyncId: "credential-sync",
rdpCredentialSyncId: null,
vncCredentialSyncId: null,
telnetCredentialSyncId: null,
vaultProfileSyncId: "vault-sync",
parentHostSyncId: "parent-sync",
},
async (entityType, syncId) => ids.get(`${entityType}:${syncId}`) ?? null,
);
expect(row).toMatchObject({
credentialId: 91,
rdpCredentialId: null,
vncCredentialId: null,
telnetCredentialId: null,
vaultProfileId: 37,
parentHostId: 52,
});
expect(row).not.toHaveProperty("credentialSyncId");
});
it("orders parent hosts before children", () => {
const parent = { syncId: "parent", parentHostSyncId: null };
const child = { syncId: "child", parentHostSyncId: "parent" };
const grandchild = { syncId: "grandchild", parentHostSyncId: "child" };
expect(orderSyncRows("hosts", [grandchild, child, parent])).toEqual([
parent,
child,
grandchild,
]);
});
it("leaves other entity types in their existing order", () => {
const rows = [{ syncId: "second" }, { syncId: "first" }];
expect(orderSyncRows("sshFolders", rows)).toBe(rows);
});
it("rejects a row whose referenced dependency has not synced", async () => {
await expect(
deserializeSyncReferences(
"sshFolders",
{ credentialSyncId: "missing" },
async () => null,
),
).rejects.toThrow("Missing sshCredentials dependency");
});
});
@@ -27,7 +27,7 @@ async function invoke(fetchGitHubAPI: ReturnType<typeof vi.fn>) {
compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText,
{
process: { env: { VERSION: "2.7.1" } },
getLocalVersion: () => "2.7.1",
databaseLogger: { warn: vi.fn(), error: vi.fn() },
fetchGitHubAPI,
REPO_OWNER: "Termix-SSH",