release-2.9.0 (#1532)

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

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

* Fix/backend optional sharp (#1455)

Fix/backend optional sharp

* feat: issue #1218 (#1218)

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

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

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

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

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

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

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

* feat: issue #1264 (#1264)

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

* feat: 2FA With FortiToken (#1288)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix: sudo password not autofilling (#1248)

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

* fix: node-MainThread (#1300)

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

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

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

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

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

* chore: increment ver

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

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

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


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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps-dev): bump the dev-patch-updates group with 13 updates (#1459)

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

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


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

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

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

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

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

Updates `@testing-library/user-event` from 14.6.5 to 14.6.7
- [Release notes](https://github.com/testing-library/user-event/releases)
- [Changelog](https://github.com/testing-library/user-event/blob/main/CHANGELOG.md)
- [Commits](https://github.com/testing-library/user-event/compare/v14.6.5...v14.6.7)

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

Updates `@vitejs/plugin-react` from 6.1.0 to 6.1.1
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.1.1/packages/plugin-react)

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

Updates `eslint-plugin-react-refresh` from 0.5.4 to 0.5.7
- [Release notes](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/releases)
- [Changelog](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/compare/v0.5.4...v0.5.7)

Updates `i18next` from 26.4.0 to 26.4.2
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.4.0...v26.4.2)

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

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

---
updated-dependencies:
- dependency-name: "@codemirror/commands"
  dependency-version: 6.11.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@codemirror/search"
  dependency-version: 6.7.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@codemirror/view"
  dependency-version: 6.43.12
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@testing-library/dom"
  dependency-version: 10.4.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@testing-library/react"
  dependency-version: 16.3.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@testing-library/user-event"
  dependency-version: 14.6.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@types/ssh2"
  dependency-version: 1.15.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.1.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: cytoscape
  dependency-version: 3.34.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: eslint-plugin-react-refresh
  dependency-version: 0.5.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: i18next
  dependency-version: 26.4.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: prettier
  dependency-version: 3.9.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
- dependency-name: react-i18next
  dependency-version: 17.0.14
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-patch-updates
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* chore(deps): bump the prod-patch-updates group with 6 updates (#1461)

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

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


Updates `@tanstack/react-virtual` from 3.14.10 to 3.14.13
- [Release notes](https://github.com/TanStack/virtual/releases)
- [Changelog](https://github.com/TanStack/virtual/blob/main/packages/react-virtual/CHANGELOG.md)
- [Commits](https://github.com/TanStack/virtual/commits/@tanstack/react-virtual@3.14.13/packages/react-virtual)

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

Updates `jose` from 6.2.9 to 6.2.12
- [Release notes](https://github.com/panva/jose/releases)
- [Changelog](https://github.com/panva/jose/blob/main/CHANGELOG.md)
- [Commits](https://github.com/panva/jose/compare/v6.2.9...v6.2.12)

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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

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

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

* feat: add allowlisted host view for plugins

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

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

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

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

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

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

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

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

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

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

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

fix: stop plugin workers seeing plaintext credentials in error messages

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

  Authentication failed for root using password <SECRET>

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

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

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

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

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

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

fix: correct the nginx plugin-api location regex

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat: move fleets into a first-party plugin

* feat: move automations into a first-party plugin

* feat: remove legacy alert rules, superseded by automations

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

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

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

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

* feat: move workspaces into a first-party plugin

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

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

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

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

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

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

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

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

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

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

* feat: rebuild workspaces as the reference plugin

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

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

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

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

* feat: add the snippets plugin (B2)

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

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

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

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

* chore: regenerate drizzle migration journals for B5

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

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

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

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

* feat: convert file manager into a plugin

* feat: convert ssh tunnels into a plugin

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

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

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

* feat: convert serial console into the serial plugin

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

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

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

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

* feat: finish the docker plugin (B15)

* feat: finish the automations plugin (B17)

* feat: finish the ai plugin (B18)

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

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

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

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

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

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

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

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

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

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

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

* chore: lock the plugin boundary and remove 2.9.0 leftovers

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

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

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

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

* feat: improve UI loading time and jitter

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

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

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

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

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

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

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

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

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

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

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

* test(mysql): refresh reviewed plugin upgrade SQL

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

* fix(hosts): normalize imported jump host references

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

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

* test(mysql): refresh reviewed plugin upgrade SQL

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

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

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

* test(mysql): refresh reviewed plugin upgrade SQL

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

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

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

* test(mysql): refresh reviewed plugin upgrade SQL

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

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

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

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

* test(mysql): refresh reviewed plugin upgrade SQL

* fix(dashboard): reuse translated host status labels

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

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

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

* test(mysql): refresh reviewed plugin upgrade SQL

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

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

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

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

* test(mysql): refresh reviewed plugin upgrade SQL

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

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

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

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

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

* test(mysql): refresh reviewed plugin upgrade SQL

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

* fix: keep rounded-full circular in production builds

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix(homepage): check allowlisted private service reachability

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

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

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

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

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

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

* chore: simplify plugin readmes, changelogs and manifest descriptions

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

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

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

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

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

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

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

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

* feat: add plugin sdk build to beta release

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

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

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

* chore: untrack plugin sdk ARCHITECTURE.md

* chore: remove references to plugin sdk ARCHITECTURE.md

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

* feat: add descriptions to plugin host enable toggles

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

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

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

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

* test(credentials): avoid flaky Ed25519 key generation

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

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

* test(credentials): avoid flaky Ed25519 key generation

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

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

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

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

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

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

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

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

* feat: improve quick connect system using plugin api

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

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

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

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

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

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

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

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

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

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

* feat: redesign user host defaults system

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat: bring back the alert feed homepage widget

* feat: pick target terminals for snippets again

* feat: share button on connection tabs again

* feat: recent servers list when linking the desktop app

* feat: list the fixed app shortcuts in keyboard shortcuts

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

* fix: translate leftover hardcoded ui text

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

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

* chore: openapi docs for host metrics manager routes

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

* fix: declare terminal.listSessions use for snippet targets

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

* feat: restore the alert feed homepage widget

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

* fix: docker container logs use the base background color

* chore: fix dependabot alerts and apply safe npm upgrades

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

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

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

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

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

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

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

* fix: add description to the web endpoint enable switch

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

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

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

* fix: remove duplicate top border on split screen menu

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

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

* fix: onboarding rerunning for existing users after upgrading

* fix: fleet detail buttons overflowing the sidebar

* fix: session log player scrolling off screen horizontally

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

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

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

* chore: update release notes

* fix: remote desktop tabs reconnecting on every tab switch

* fix: build plugin sdk before linting in release workflow

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

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

* chore: sync Crowdin translations for 2.9.0

---------

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

No files matched your search

@@ -1,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);
});
});