mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-10-29 22:55:24 +00:00
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:
4405 files changed
+1341026
-289722
No files matched your search
@@ -1,94 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { triggerLoginAlert } from "../../utils/alert-trigger.js";
|
||||
import { SystemCrypto } from "../../utils/system-crypto.js";
|
||||
import { sshLogger } from "../../utils/logger.js";
|
||||
|
||||
describe("triggerLoginAlert", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("reports a rejected metrics-service request", async () => {
|
||||
vi.spyOn(SystemCrypto, "getInstance").mockReturnValue({
|
||||
getInternalAuthToken: vi.fn().mockResolvedValue("internal-token"),
|
||||
} as never);
|
||||
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
||||
new Response('{"error":"Missing authentication token"}', {
|
||||
status: 401,
|
||||
}),
|
||||
);
|
||||
const warn = vi.spyOn(sshLogger, "warn").mockImplementation(() => {});
|
||||
|
||||
await triggerLoginAlert(7, "user-1", "root", "192.0.2.1");
|
||||
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
"Failed to trigger login alert",
|
||||
expect.objectContaining({
|
||||
operation: "login_alert_trigger_error",
|
||||
hostId: 7,
|
||||
error:
|
||||
'Metrics service returned 401: {"error":"Missing authentication token"}',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not log a warning when the metrics service accepts the event", async () => {
|
||||
vi.spyOn(SystemCrypto, "getInstance").mockReturnValue({
|
||||
getInternalAuthToken: vi.fn().mockResolvedValue("internal-token"),
|
||||
} as never);
|
||||
vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
||||
new Response('{"ok":true}', { status: 200 }),
|
||||
);
|
||||
const warn = vi.spyOn(sshLogger, "warn").mockImplementation(() => {});
|
||||
|
||||
await triggerLoginAlert(7, "user-1", "root", "192.0.2.1");
|
||||
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sends the internal auth token and login details the metrics service expects", async () => {
|
||||
vi.spyOn(SystemCrypto, "getInstance").mockReturnValue({
|
||||
getInternalAuthToken: vi.fn().mockResolvedValue("internal-token"),
|
||||
} as never);
|
||||
const fetchSpy = vi
|
||||
.spyOn(globalThis, "fetch")
|
||||
.mockResolvedValue(new Response('{"ok":true}', { status: 200 }));
|
||||
|
||||
await triggerLoginAlert(42, "user-1", "root", "10.0.0.5");
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledWith(
|
||||
"http://localhost:30005/internal/login-alert",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.objectContaining({
|
||||
"x-internal-auth": "internal-token",
|
||||
}),
|
||||
body: JSON.stringify({
|
||||
hostId: 42,
|
||||
userId: "user-1",
|
||||
sshUser: "root",
|
||||
fromIp: "10.0.0.5",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("logs a warning if the fetch itself throws, instead of propagating", async () => {
|
||||
vi.spyOn(SystemCrypto, "getInstance").mockReturnValue({
|
||||
getInternalAuthToken: vi.fn().mockResolvedValue("internal-token"),
|
||||
} as never);
|
||||
vi.spyOn(globalThis, "fetch").mockRejectedValue(
|
||||
new Error("connect ECONNREFUSED"),
|
||||
);
|
||||
const warn = vi.spyOn(sshLogger, "warn").mockImplementation(() => {});
|
||||
|
||||
await expect(
|
||||
triggerLoginAlert(1, "user-1", "root", "127.0.0.1"),
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
"Failed to trigger login alert",
|
||||
expect.objectContaining({ hostId: 1 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,193 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
const mockGetBoolean = vi.fn();
|
||||
const mockGet = vi.fn();
|
||||
const mockSet = vi.fn();
|
||||
const mockPost = vi.fn();
|
||||
|
||||
function makeChain(resolveValue: unknown) {
|
||||
const chain: Record<string, unknown> = {};
|
||||
const methods = ["from", "where", "groupBy"];
|
||||
for (const m of methods) {
|
||||
chain[m] = vi.fn(() => chain);
|
||||
}
|
||||
(chain as unknown as Promise<unknown>).then = (cb: (v: unknown) => unknown) =>
|
||||
Promise.resolve(resolveValue).then(cb);
|
||||
return chain;
|
||||
}
|
||||
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentSettingsRepository: () => ({
|
||||
getBoolean: mockGetBoolean,
|
||||
get: mockGet,
|
||||
set: mockSet,
|
||||
}),
|
||||
createCurrentRepositoryContext: () => ({
|
||||
drizzle: {
|
||||
select: vi.fn(() => makeChain([{ count: 0 }])),
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../database/db/schema.js", () => ({
|
||||
users: {},
|
||||
hosts: {},
|
||||
recentActivity: { type: "type", timestamp: "timestamp" },
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/logger.js", () => ({
|
||||
Logger: class {
|
||||
info = vi.fn();
|
||||
warn = vi.fn();
|
||||
error = vi.fn();
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("axios", () => ({
|
||||
default: { post: mockPost },
|
||||
}));
|
||||
|
||||
describe("analytics", () => {
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env = { ...originalEnv };
|
||||
delete process.env.ENABLE_TELEMETRY;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = { ...originalEnv };
|
||||
});
|
||||
|
||||
it("isAnalyticsEnabled defaults to true via the settings repository", async () => {
|
||||
delete process.env.ENABLE_TELEMETRY;
|
||||
mockGetBoolean.mockResolvedValue(true);
|
||||
const { isAnalyticsEnabled } = await import("../../utils/analytics.js");
|
||||
|
||||
const result = await isAnalyticsEnabled();
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockGetBoolean).toHaveBeenCalledWith("analytics_enabled", true);
|
||||
});
|
||||
|
||||
it("ENABLE_TELEMETRY=false disables analytics without consulting the database", async () => {
|
||||
process.env.ENABLE_TELEMETRY = "false";
|
||||
const { isAnalyticsEnabled } = await import("../../utils/analytics.js");
|
||||
|
||||
const result = await isAnalyticsEnabled();
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(mockGetBoolean).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ENABLE_TELEMETRY=true forces analytics on without consulting the database", async () => {
|
||||
process.env.ENABLE_TELEMETRY = "TRUE";
|
||||
const { isAnalyticsEnabled } = await import("../../utils/analytics.js");
|
||||
|
||||
const result = await isAnalyticsEnabled();
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockGetBoolean).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("getTelemetryEnvOverride returns null when unset or blank", async () => {
|
||||
const { getTelemetryEnvOverride } =
|
||||
await import("../../utils/analytics.js");
|
||||
|
||||
delete process.env.ENABLE_TELEMETRY;
|
||||
expect(getTelemetryEnvOverride()).toBe(null);
|
||||
|
||||
process.env.ENABLE_TELEMETRY = " ";
|
||||
expect(getTelemetryEnvOverride()).toBe(null);
|
||||
});
|
||||
|
||||
it("startAnalyticsHeartbeat sends nothing when ENABLE_TELEMETRY=false", async () => {
|
||||
process.env.ENABLE_TELEMETRY = "false";
|
||||
process.env.POSTHOG_API_KEY = "phc_test";
|
||||
const { startAnalyticsHeartbeat } =
|
||||
await import("../../utils/analytics.js");
|
||||
|
||||
startAnalyticsHeartbeat();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(mockPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("collectAndSendHeartbeat does not call PostHog when ENABLE_TELEMETRY=false", async () => {
|
||||
process.env.ENABLE_TELEMETRY = "false";
|
||||
process.env.POSTHOG_API_KEY = "phc_test";
|
||||
const { collectAndSendHeartbeat } =
|
||||
await import("../../utils/analytics.js");
|
||||
|
||||
await collectAndSendHeartbeat();
|
||||
|
||||
expect(mockPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("getOrCreateInstanceId returns the existing id without generating one", async () => {
|
||||
mockGet.mockResolvedValue("existing-id");
|
||||
const { getOrCreateInstanceId } = await import("../../utils/analytics.js");
|
||||
|
||||
const id = await getOrCreateInstanceId();
|
||||
|
||||
expect(id).toBe("existing-id");
|
||||
expect(mockSet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("getOrCreateInstanceId generates and persists a new id when absent", async () => {
|
||||
mockGet.mockResolvedValue(null);
|
||||
const { getOrCreateInstanceId } = await import("../../utils/analytics.js");
|
||||
|
||||
const id = await getOrCreateInstanceId();
|
||||
|
||||
expect(id).toMatch(/^[0-9a-f-]{36}$/);
|
||||
expect(mockSet).toHaveBeenCalledWith("analytics_instance_id", id);
|
||||
});
|
||||
|
||||
it("collectAndSendHeartbeat does not call PostHog when POSTHOG_API_KEY is unset", async () => {
|
||||
delete process.env.POSTHOG_API_KEY;
|
||||
const { collectAndSendHeartbeat } =
|
||||
await import("../../utils/analytics.js");
|
||||
|
||||
await collectAndSendHeartbeat();
|
||||
|
||||
expect(mockPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("collectAndSendHeartbeat does not call PostHog when analytics is disabled", async () => {
|
||||
process.env.POSTHOG_API_KEY = "phc_test";
|
||||
mockGetBoolean.mockResolvedValue(false);
|
||||
const { collectAndSendHeartbeat } =
|
||||
await import("../../utils/analytics.js");
|
||||
|
||||
await collectAndSendHeartbeat();
|
||||
|
||||
expect(mockPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("collectAndSendHeartbeat posts a heartbeat event with the expected shape when enabled", async () => {
|
||||
process.env.POSTHOG_API_KEY = "phc_test";
|
||||
mockGetBoolean.mockResolvedValue(true);
|
||||
mockGet.mockResolvedValue("instance-123");
|
||||
mockPost.mockResolvedValue({});
|
||||
const { collectAndSendHeartbeat } =
|
||||
await import("../../utils/analytics.js");
|
||||
|
||||
await collectAndSendHeartbeat();
|
||||
|
||||
expect(mockPost).toHaveBeenCalledTimes(1);
|
||||
const [url, body] = mockPost.mock.calls[0];
|
||||
expect(url).toContain("/capture/");
|
||||
expect(body).toMatchObject({
|
||||
api_key: "phc_test",
|
||||
event: "instance_heartbeat",
|
||||
distinct_id: "instance-123",
|
||||
properties: expect.objectContaining({
|
||||
user_count: 0,
|
||||
host_count: 0,
|
||||
used_terminal: 0,
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -49,26 +49,6 @@ function legacyDatabase(): Database.Database {
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE session_recordings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_id INTEGER NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
access_id INTEGER,
|
||||
started_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
ended_at TEXT,
|
||||
duration INTEGER,
|
||||
commands TEXT,
|
||||
dangerous_actions TEXT,
|
||||
recording_path TEXT,
|
||||
protocol TEXT NOT NULL DEFAULT 'ssh',
|
||||
format TEXT NOT NULL DEFAULT 'text',
|
||||
terminated_by_owner INTEGER DEFAULT 0,
|
||||
termination_reason TEXT,
|
||||
FOREIGN KEY (host_id) REFERENCES ssh_data (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (access_id) REFERENCES host_access (id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username) VALUES ('u-1', 'alice'), ('u-2', 'bob');
|
||||
INSERT INTO ssh_data (id, name) VALUES (1, 'prod-db');
|
||||
|
||||
@@ -78,12 +58,6 @@ function legacyDatabase(): Database.Database {
|
||||
('u-1', 'alice', 'host.delete', 'host', '1', 1, '2026-07-01 10:00:00'),
|
||||
('u-1', 'alice', 'credential.view', 'credential', '9', 1, '2026-07-02 11:00:00'),
|
||||
('u-2', 'bob', 'host.create', 'host', '2', 1, '2026-07-03 12:00:00');
|
||||
|
||||
INSERT INTO session_recordings
|
||||
(host_id, user_id, started_at, recording_path, protocol, format)
|
||||
VALUES
|
||||
(1, 'u-1', '2026-07-01 10:00:00', '/rec/a.guac', 'ssh', 'text'),
|
||||
(1, 'u-2', '2026-07-03 12:00:00', '/rec/b.guac', 'ssh', 'text');
|
||||
`);
|
||||
return sqlite;
|
||||
}
|
||||
@@ -93,15 +67,10 @@ describe("audit retention migration", () => {
|
||||
db = legacyDatabase();
|
||||
|
||||
expect(userDeleteIsDestructive(db, "audit_logs")).toBe(true);
|
||||
expect(userDeleteIsDestructive(db, "session_recordings")).toBe(true);
|
||||
|
||||
expect(migrateAuditRetention(db)).toEqual([
|
||||
"audit_logs",
|
||||
"session_recordings",
|
||||
]);
|
||||
expect(migrateAuditRetention(db)).toEqual(["audit_logs"]);
|
||||
|
||||
expect(userDeleteIsDestructive(db, "audit_logs")).toBe(false);
|
||||
expect(userDeleteIsDestructive(db, "session_recordings")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the audit trail when the user is deleted", () => {
|
||||
@@ -126,23 +95,6 @@ describe("audit retention migration", () => {
|
||||
expect(rows[2].user_id).toBe("u-2");
|
||||
});
|
||||
|
||||
it("backfills a username onto recordings so they stay attributable", () => {
|
||||
db = legacyDatabase();
|
||||
migrateAuditRetention(db);
|
||||
|
||||
db.exec("DELETE FROM users WHERE id = 'u-1'");
|
||||
|
||||
const rows = db
|
||||
.prepare(
|
||||
"SELECT user_id, username, recording_path FROM session_recordings ORDER BY started_at",
|
||||
)
|
||||
.all() as { user_id: string | null; username: string | null }[];
|
||||
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0].user_id).toBeNull();
|
||||
expect(rows[0].username).toBe("alice");
|
||||
});
|
||||
|
||||
it("loses no data in the copy", () => {
|
||||
db = legacyDatabase();
|
||||
const before = db
|
||||
@@ -158,18 +110,6 @@ describe("audit retention migration", () => {
|
||||
expect(after).toEqual(before);
|
||||
});
|
||||
|
||||
it("still cascades recordings when their host is deleted", () => {
|
||||
db = legacyDatabase();
|
||||
migrateAuditRetention(db);
|
||||
|
||||
db.exec("PRAGMA foreign_keys = ON");
|
||||
db.exec("DELETE FROM ssh_data WHERE id = 1");
|
||||
|
||||
expect(
|
||||
db.prepare("SELECT COUNT(*) AS n FROM session_recordings").get(),
|
||||
).toEqual({ n: 0 });
|
||||
});
|
||||
|
||||
it("is idempotent and leaves an already-migrated database alone", () => {
|
||||
db = legacyDatabase();
|
||||
migrateAuditRetention(db);
|
||||
|
||||
@@ -66,7 +66,8 @@ vi.mock("../../utils/audit-logger.js", () => ({
|
||||
getRequestMeta: () => ({ ipAddress: "", userAgent: "" }),
|
||||
}));
|
||||
|
||||
const { AuthManager } = await import("../../utils/auth-manager.js");
|
||||
const { AuthManager, setPluginImpersonationCheck, allowsAdminImpersonation } =
|
||||
await import("../../utils/auth-manager.js");
|
||||
const authManager = AuthManager.getInstance();
|
||||
const middleware = authManager.createAuthMiddleware();
|
||||
|
||||
@@ -216,4 +217,48 @@ describe("AuthManager admin impersonation", () => {
|
||||
expect(nexted).toBe(true);
|
||||
expect((req as unknown as { userId: string }).userId).toBe("regular1");
|
||||
});
|
||||
|
||||
it("rejects the header on a plugin route whose manifest did not opt in", async () => {
|
||||
setPluginImpersonationCheck((pluginId) => pluginId === "opted-in");
|
||||
try {
|
||||
const { res, nexted } = await runMiddleware(token("admin1"), {
|
||||
"x-admin-target-user": "target1",
|
||||
__url: "/plugin-api/other/items",
|
||||
});
|
||||
expect(nexted).toBe(false);
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect((res.body as { code?: string }).code).toBe(
|
||||
"IMPERSONATION_NOT_ALLOWED",
|
||||
);
|
||||
} finally {
|
||||
setPluginImpersonationCheck(() => false);
|
||||
}
|
||||
});
|
||||
|
||||
it("lets an admin act for a user on a plugin that opted in", async () => {
|
||||
setPluginImpersonationCheck((pluginId) => pluginId === "opted-in");
|
||||
try {
|
||||
const { req, nexted } = await runMiddleware(token("admin1"), {
|
||||
"x-admin-target-user": "target1",
|
||||
__url: "/plugin-api/opted-in/items?x=1",
|
||||
});
|
||||
expect(nexted).toBe(true);
|
||||
expect((req as unknown as { userId: string }).userId).toBe("target1");
|
||||
} finally {
|
||||
setPluginImpersonationCheck(() => false);
|
||||
}
|
||||
});
|
||||
|
||||
it("matches the plugin id exactly, not as a prefix", () => {
|
||||
setPluginImpersonationCheck((pluginId) => pluginId === "opted-in");
|
||||
try {
|
||||
expect(allowsAdminImpersonation("/plugin-api/opted-in")).toBe(true);
|
||||
expect(allowsAdminImpersonation("/plugin-api/opted-in-too/x")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(allowsAdminImpersonation("/users/sessions")).toBe(false);
|
||||
} finally {
|
||||
setPluginImpersonationCheck(() => false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -99,7 +99,7 @@ function sessionIds(): string[] {
|
||||
.map((row) => String(row.id));
|
||||
}
|
||||
|
||||
describe("AuthManager.revokeSessionsByOidc", () => {
|
||||
describe("AuthManager.revokeSessionsByExternalSession", () => {
|
||||
beforeAll(() => {
|
||||
mocks.sqlite!.exec(`
|
||||
CREATE TABLE sessions (
|
||||
@@ -147,7 +147,7 @@ describe("AuthManager.revokeSessionsByOidc", () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
authManager.revokeSessionsByOidc({
|
||||
authManager.revokeSessionsByExternalSession({
|
||||
ssoProviderId: 7,
|
||||
sub: "subject-1",
|
||||
sid: "session-1",
|
||||
@@ -181,7 +181,7 @@ describe("AuthManager.revokeSessionsByOidc", () => {
|
||||
});
|
||||
|
||||
await expect(
|
||||
authManager.revokeSessionsByOidc({
|
||||
authManager.revokeSessionsByExternalSession({
|
||||
ssoProviderId: 7,
|
||||
sub: "subject-1",
|
||||
}),
|
||||
@@ -192,7 +192,7 @@ describe("AuthManager.revokeSessionsByOidc", () => {
|
||||
|
||||
it("does not persist when no session matches", async () => {
|
||||
await expect(
|
||||
authManager.revokeSessionsByOidc({
|
||||
authManager.revokeSessionsByExternalSession({
|
||||
ssoProviderId: 7,
|
||||
sid: "missing",
|
||||
}),
|
||||
@@ -212,7 +212,7 @@ describe("AuthManager.revokeSessionsByOidc", () => {
|
||||
mocks.saveDatabase.mockRejectedValueOnce(new Error("disk full"));
|
||||
|
||||
await expect(
|
||||
authManager.revokeSessionsByOidc({
|
||||
authManager.revokeSessionsByExternalSession({
|
||||
ssoProviderId: 7,
|
||||
sid: "session-1",
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* The SSH connection options moving out of ssh_data.terminal_config into
|
||||
* the core ssh_options column, against a real SQLite database through the
|
||||
* same raw SQL helpers the boot path uses.
|
||||
*/
|
||||
|
||||
import Database from "better-sqlite3";
|
||||
import { drizzle } from "drizzle-orm/better-sqlite3";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({ db: null as unknown }));
|
||||
|
||||
vi.mock("../../../database/db/index.js", () => ({ getDb: () => state.db }));
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
databaseLogger: { info: vi.fn(), warn: vi.fn() },
|
||||
}));
|
||||
|
||||
const { runSshOptionsMigration } =
|
||||
await import("../../../utils/crypto-migration/ssh-options-migration.js");
|
||||
|
||||
let sqlite: Database.Database;
|
||||
|
||||
beforeEach(() => {
|
||||
sqlite = new Database(":memory:");
|
||||
sqlite.exec(`
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY,
|
||||
terminal_config TEXT,
|
||||
ssh_options TEXT
|
||||
);
|
||||
`);
|
||||
state.db = drizzle(sqlite);
|
||||
});
|
||||
|
||||
function insert(id: number, terminalConfig: unknown, sshOptions?: string) {
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO ssh_data (id, terminal_config, ssh_options) VALUES (?, ?, ?)",
|
||||
)
|
||||
.run(
|
||||
id,
|
||||
terminalConfig === null ? null : JSON.stringify(terminalConfig),
|
||||
sshOptions ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
function options(id: number): unknown {
|
||||
const row = sqlite
|
||||
.prepare("SELECT ssh_options FROM ssh_data WHERE id = ?")
|
||||
.get(id) as { ssh_options: string | null };
|
||||
return row.ssh_options === null ? null : JSON.parse(row.ssh_options);
|
||||
}
|
||||
|
||||
describe("runSshOptionsMigration", () => {
|
||||
it("copies only the connection options, leaving the look and old tunnel keys", async () => {
|
||||
insert(1, {
|
||||
theme: "dracula",
|
||||
fontSize: 16,
|
||||
keepaliveInterval: 30,
|
||||
keepaliveCountMax: 3,
|
||||
allowLegacyAlgorithms: false,
|
||||
agentSocketPath: "/run/agent.sock",
|
||||
agentIdentity: "work",
|
||||
agentForwarding: true,
|
||||
environmentVariables: [{ key: "LANG", value: "C" }],
|
||||
startupSnippetId: 4,
|
||||
cfAccessClientId: "old",
|
||||
cfTunnelHostname: "old.example.com",
|
||||
});
|
||||
|
||||
const result = await runSshOptionsMigration();
|
||||
|
||||
expect(result.hostsMoved).toBe(1);
|
||||
expect(options(1)).toEqual({
|
||||
keepaliveInterval: 30,
|
||||
keepaliveCountMax: 3,
|
||||
allowLegacyAlgorithms: false,
|
||||
agentSocketPath: "/run/agent.sock",
|
||||
agentIdentity: "work",
|
||||
agentForwarding: true,
|
||||
environmentVariables: [{ key: "LANG", value: "C" }],
|
||||
});
|
||||
const terminalConfig = sqlite
|
||||
.prepare("SELECT terminal_config FROM ssh_data WHERE id = 1")
|
||||
.get() as { terminal_config: string };
|
||||
expect(JSON.parse(terminalConfig.terminal_config).keepaliveInterval).toBe(
|
||||
30,
|
||||
);
|
||||
});
|
||||
|
||||
it("marks a host with no options as done and skips hosts with no config", async () => {
|
||||
insert(1, { theme: "dracula" });
|
||||
insert(2, null);
|
||||
|
||||
const result = await runSshOptionsMigration();
|
||||
|
||||
expect(result.hostsMoved).toBe(0);
|
||||
expect(options(1)).toEqual({});
|
||||
expect(options(2)).toBeNull();
|
||||
});
|
||||
|
||||
it("changes nothing on a second run, even after the options were edited", async () => {
|
||||
insert(1, { keepaliveInterval: 30 });
|
||||
insert(
|
||||
2,
|
||||
{ keepaliveInterval: 45 },
|
||||
JSON.stringify({ keepaliveCountMax: 9 }),
|
||||
);
|
||||
await runSshOptionsMigration();
|
||||
|
||||
sqlite
|
||||
.prepare("UPDATE ssh_data SET ssh_options = ? WHERE id = 1")
|
||||
.run(JSON.stringify({ keepaliveInterval: 90 }));
|
||||
const second = await runSshOptionsMigration();
|
||||
|
||||
expect(second.hostsMoved).toBe(0);
|
||||
expect(options(1)).toEqual({ keepaliveInterval: 90 });
|
||||
expect(options(2)).toEqual({ keepaliveCountMax: 9 });
|
||||
});
|
||||
|
||||
it("does not throw on a database without the column", async () => {
|
||||
sqlite = new Database(":memory:");
|
||||
sqlite.exec("CREATE TABLE ssh_data (id INTEGER PRIMARY KEY)");
|
||||
state.db = drizzle(sqlite);
|
||||
await expect(runSshOptionsMigration()).resolves.toEqual({
|
||||
hostsMoved: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -3,12 +3,15 @@ import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import {
|
||||
CURRENT_PREUPGRADE_BACKUP_REASON,
|
||||
DATABASE_LAYER_PREUPGRADE_BACKUP_MARKER,
|
||||
DATABASE_LAYER_PREUPGRADE_BACKUP_PREFIX,
|
||||
DATABASE_LAYER_SKIP_PREUPGRADE_BACKUP_ENV,
|
||||
ensureDatabaseLayerPreupgradeBackup,
|
||||
ensurePreupgradeBackup,
|
||||
preupgradeBackupMarker,
|
||||
} from "../../utils/database-layer-preupgrade-backup.js";
|
||||
|
||||
const MARKER = preupgradeBackupMarker(CURRENT_PREUPGRADE_BACKUP_REASON);
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(): string {
|
||||
@@ -23,7 +26,7 @@ afterEach(() => {
|
||||
}
|
||||
});
|
||||
|
||||
describe("ensureDatabaseLayerPreupgradeBackup", () => {
|
||||
describe("ensurePreupgradeBackup", () => {
|
||||
it("copies existing database files and writes a marker", () => {
|
||||
const dataDir = makeTempDir();
|
||||
const encryptedDbPath = path.join(dataDir, "db.sqlite.encrypted");
|
||||
@@ -33,7 +36,7 @@ describe("ensureDatabaseLayerPreupgradeBackup", () => {
|
||||
fs.writeFileSync(metadataPath, '{"version":"v2"}');
|
||||
fs.writeFileSync(envPath, "DATABASE_KEY=test-key");
|
||||
|
||||
const result = ensureDatabaseLayerPreupgradeBackup({
|
||||
const result = ensurePreupgradeBackup({
|
||||
dataDir,
|
||||
version: "2.5.0-test",
|
||||
now: new Date("2026-06-27T12:00:00.000Z"),
|
||||
@@ -41,12 +44,8 @@ describe("ensureDatabaseLayerPreupgradeBackup", () => {
|
||||
});
|
||||
|
||||
expect(result.status).toBe("created");
|
||||
expect(result.backupDir).toContain(DATABASE_LAYER_PREUPGRADE_BACKUP_PREFIX);
|
||||
expect(
|
||||
fs.existsSync(
|
||||
path.join(dataDir, DATABASE_LAYER_PREUPGRADE_BACKUP_MARKER),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(result.backupDir).toContain(CURRENT_PREUPGRADE_BACKUP_REASON);
|
||||
expect(fs.existsSync(path.join(dataDir, MARKER))).toBe(true);
|
||||
expect(
|
||||
fs.readFileSync(
|
||||
path.join(result.backupDir!, "db.sqlite.encrypted"),
|
||||
@@ -72,12 +71,9 @@ describe("ensureDatabaseLayerPreupgradeBackup", () => {
|
||||
it("skips when the marker already exists", () => {
|
||||
const dataDir = makeTempDir();
|
||||
fs.writeFileSync(path.join(dataDir, "db.sqlite.encrypted"), "encrypted-db");
|
||||
fs.writeFileSync(
|
||||
path.join(dataDir, DATABASE_LAYER_PREUPGRADE_BACKUP_MARKER),
|
||||
"{}",
|
||||
);
|
||||
fs.writeFileSync(path.join(dataDir, MARKER), "{}");
|
||||
|
||||
const result = ensureDatabaseLayerPreupgradeBackup({
|
||||
const result = ensurePreupgradeBackup({
|
||||
dataDir,
|
||||
env: {} as NodeJS.ProcessEnv,
|
||||
});
|
||||
@@ -89,10 +85,37 @@ describe("ensureDatabaseLayerPreupgradeBackup", () => {
|
||||
expect(fs.existsSync(path.join(dataDir, "backups"))).toBe(false);
|
||||
});
|
||||
|
||||
it("still backs up an install that has the 2.5 refactor's marker", () => {
|
||||
const dataDir = makeTempDir();
|
||||
fs.writeFileSync(path.join(dataDir, "db.sqlite"), "2.8-db");
|
||||
fs.writeFileSync(
|
||||
path.join(dataDir, DATABASE_LAYER_PREUPGRADE_BACKUP_MARKER),
|
||||
"{}",
|
||||
);
|
||||
|
||||
const first = ensurePreupgradeBackup({
|
||||
dataDir,
|
||||
env: {} as NodeJS.ProcessEnv,
|
||||
});
|
||||
expect(first.status).toBe("created");
|
||||
expect(
|
||||
fs.readFileSync(path.join(first.backupDir!, "db.sqlite"), "utf8"),
|
||||
).toBe("2.8-db");
|
||||
|
||||
const second = ensurePreupgradeBackup({
|
||||
dataDir,
|
||||
env: {} as NodeJS.ProcessEnv,
|
||||
});
|
||||
expect(second).toMatchObject({
|
||||
status: "skipped",
|
||||
reason: "marker_exists",
|
||||
});
|
||||
});
|
||||
|
||||
it("skips new installs without a database file", () => {
|
||||
const dataDir = makeTempDir();
|
||||
|
||||
const result = ensureDatabaseLayerPreupgradeBackup({
|
||||
const result = ensurePreupgradeBackup({
|
||||
dataDir,
|
||||
env: {} as NodeJS.ProcessEnv,
|
||||
});
|
||||
@@ -101,18 +124,14 @@ describe("ensureDatabaseLayerPreupgradeBackup", () => {
|
||||
status: "skipped",
|
||||
reason: "no_database_file",
|
||||
});
|
||||
expect(
|
||||
fs.existsSync(
|
||||
path.join(dataDir, DATABASE_LAYER_PREUPGRADE_BACKUP_MARKER),
|
||||
),
|
||||
).toBe(false);
|
||||
expect(fs.existsSync(path.join(dataDir, MARKER))).toBe(false);
|
||||
});
|
||||
|
||||
it("honors the explicit skip environment variable", () => {
|
||||
const dataDir = makeTempDir();
|
||||
fs.writeFileSync(path.join(dataDir, "db.sqlite.encrypted"), "encrypted-db");
|
||||
|
||||
const result = ensureDatabaseLayerPreupgradeBackup({
|
||||
const result = ensurePreupgradeBackup({
|
||||
dataDir,
|
||||
env: {
|
||||
[DATABASE_LAYER_SKIP_PREUPGRADE_BACKUP_ENV]: "1",
|
||||
@@ -132,7 +151,7 @@ describe("ensureDatabaseLayerPreupgradeBackup", () => {
|
||||
fs.writeFileSync(path.join(dataDir, "backups"), "not-a-directory");
|
||||
|
||||
expect(() =>
|
||||
ensureDatabaseLayerPreupgradeBackup({
|
||||
ensurePreupgradeBackup({
|
||||
dataDir,
|
||||
env: {} as NodeJS.ProcessEnv,
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
isElectronIpcAvailable,
|
||||
requestFromElectronMain,
|
||||
} from "../../utils/electron-ipc-bridge.js";
|
||||
|
||||
const originalEnv = process.env.ELECTRON_EMBEDDED;
|
||||
const originalSend = process.send;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.ELECTRON_EMBEDDED = "true";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env.ELECTRON_EMBEDDED = originalEnv;
|
||||
process.send = originalSend;
|
||||
});
|
||||
|
||||
describe("isElectronIpcAvailable", () => {
|
||||
it("is false outside the embedded desktop backend", () => {
|
||||
delete process.env.ELECTRON_EMBEDDED;
|
||||
process.send = (() => true) as typeof process.send;
|
||||
expect(isElectronIpcAvailable()).toBe(false);
|
||||
});
|
||||
|
||||
it("is false when there is no fork IPC channel", () => {
|
||||
process.send = undefined;
|
||||
expect(isElectronIpcAvailable()).toBe(false);
|
||||
});
|
||||
|
||||
it("is true when embedded with a live channel", () => {
|
||||
process.send = (() => true) as typeof process.send;
|
||||
expect(isElectronIpcAvailable()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("requestFromElectronMain", () => {
|
||||
it("refuses when Electron IPC is unavailable", async () => {
|
||||
process.send = undefined;
|
||||
await expect(
|
||||
requestFromElectronMain("open-isolated-window", {}),
|
||||
).rejects.toThrow(/desktop app/);
|
||||
});
|
||||
|
||||
// The module attaches its "message" listener to the real process.on only
|
||||
// once, the first time requestFromElectronMain actually reaches that point
|
||||
// (ensureListening's module-scoped flag mirrors how a real forked
|
||||
// process's IPC channel is a single persistent thing it listens on for the
|
||||
// process lifetime). vi.spyOn(process, "on") does not reliably intercept
|
||||
// that call in this environment, so this replaces process.on directly for
|
||||
// the one call the module makes and hands the captured listener a plain
|
||||
// function this file can invoke to simulate a message from main -
|
||||
// simpler and more direct than getting a spy to survive across a Node
|
||||
// global.
|
||||
let deliver: (msg: unknown) => void = () => {};
|
||||
|
||||
beforeAll(() => {
|
||||
const originalOn = process.on.bind(process);
|
||||
process.on = ((event: string, listener: (...args: unknown[]) => void) => {
|
||||
if (event === "message") {
|
||||
deliver = listener;
|
||||
return process;
|
||||
}
|
||||
return originalOn(event, listener);
|
||||
}) as typeof process.on;
|
||||
});
|
||||
|
||||
let sent: unknown[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
sent = [];
|
||||
process.send = ((msg: unknown) => {
|
||||
sent.push(msg);
|
||||
return true;
|
||||
}) as typeof process.send;
|
||||
});
|
||||
|
||||
it("resolves with main's response, matched by request id", async () => {
|
||||
const pending = requestFromElectronMain<{ success: true }>(
|
||||
"open-isolated-window",
|
||||
{ url: "https://example.test" },
|
||||
);
|
||||
const [message] = sent as Array<{
|
||||
type: string;
|
||||
id: string;
|
||||
channel: string;
|
||||
payload: unknown;
|
||||
}>;
|
||||
expect(message).toMatchObject({
|
||||
type: "backend-request",
|
||||
channel: "open-isolated-window",
|
||||
payload: { url: "https://example.test" },
|
||||
});
|
||||
|
||||
deliver({
|
||||
type: "backend-response",
|
||||
id: message.id,
|
||||
ok: true,
|
||||
result: { success: true },
|
||||
});
|
||||
await expect(pending).resolves.toEqual({ success: true });
|
||||
});
|
||||
|
||||
it("rejects with main's error", async () => {
|
||||
const pending = requestFromElectronMain("open-isolated-window", {});
|
||||
const [message] = sent as Array<{ id: string }>;
|
||||
|
||||
deliver({
|
||||
type: "backend-response",
|
||||
id: message.id,
|
||||
ok: false,
|
||||
error: "refused",
|
||||
});
|
||||
await expect(pending).rejects.toThrow(/refused/);
|
||||
});
|
||||
|
||||
it("ignores a response for a different request id", async () => {
|
||||
const pending = requestFromElectronMain("open-isolated-window", {});
|
||||
const [message] = sent as Array<{ id: string }>;
|
||||
|
||||
deliver({ type: "backend-response", id: "other", ok: true, result: {} });
|
||||
deliver({
|
||||
type: "backend-response",
|
||||
id: message.id,
|
||||
ok: true,
|
||||
result: { success: true },
|
||||
});
|
||||
await expect(pending).resolves.toEqual({ success: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { isExternalTokenCallback } from "../../utils/external-login-callback.js";
|
||||
|
||||
describe("isExternalTokenCallback", () => {
|
||||
it.each([
|
||||
"http://localhost:17850/oidc-callback",
|
||||
"http://127.0.0.1:17850/oidc-callback",
|
||||
"termix-mobile://oidc-callback",
|
||||
])("recognizes app callback %s", (url) => {
|
||||
expect(isExternalTokenCallback(url)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://localhost:17850/oidc-callback",
|
||||
"http://example.com:17850/oidc-callback",
|
||||
"http://localhost:17850/other",
|
||||
])("rejects non-app callback %s", (url) => {
|
||||
expect(isExternalTokenCallback(url)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* The status half of ssh_data.stats_config moving into the core
|
||||
* status_check_enabled and status_check_interval columns. Run against a real
|
||||
* SQLite database through the same raw SQL helpers the boot path uses.
|
||||
*/
|
||||
|
||||
import Database from "better-sqlite3";
|
||||
import { drizzle } from "drizzle-orm/better-sqlite3";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
settings: new Map<string, string>(),
|
||||
db: null as unknown,
|
||||
}));
|
||||
|
||||
vi.mock("../../database/db/index.js", () => ({ getDb: () => state.db }));
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentSettingsRepository: () => ({
|
||||
get: async (key: string) => state.settings.get(key) ?? null,
|
||||
set: async (key: string, value: string) => {
|
||||
state.settings.set(key, value);
|
||||
},
|
||||
}),
|
||||
}));
|
||||
vi.mock("../../utils/logger.js", () => ({
|
||||
databaseLogger: { info: vi.fn(), warn: vi.fn() },
|
||||
}));
|
||||
|
||||
const {
|
||||
runHostStatusConfigMigration,
|
||||
statusConfigFromStatsConfig,
|
||||
HOST_STATUS_CONFIG_MIGRATED,
|
||||
} =
|
||||
await import("../../utils/crypto-migration/host-status-config-migration.js");
|
||||
|
||||
let sqlite: Database.Database;
|
||||
|
||||
function createHosts(withStatsConfig = true) {
|
||||
sqlite = new Database(":memory:");
|
||||
sqlite.exec(`
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY,
|
||||
${withStatsConfig ? "stats_config TEXT," : ""}
|
||||
status_check_enabled INTEGER NOT NULL DEFAULT 1,
|
||||
status_check_interval INTEGER
|
||||
);
|
||||
`);
|
||||
state.db = drizzle(sqlite);
|
||||
}
|
||||
|
||||
const hosts = () =>
|
||||
sqlite
|
||||
.prepare(
|
||||
"SELECT id, status_check_enabled AS enabled, status_check_interval AS interval FROM ssh_data ORDER BY id",
|
||||
)
|
||||
.all();
|
||||
|
||||
beforeEach(() => {
|
||||
state.settings.clear();
|
||||
createHosts();
|
||||
});
|
||||
|
||||
describe("statusConfigFromStatsConfig", () => {
|
||||
it.each([
|
||||
[null, true, null],
|
||||
["{}", true, null],
|
||||
['{"statusCheckEnabled":false}', false, null],
|
||||
['{"disableTcpPing":true}', false, null],
|
||||
['{"useGlobalStatusInterval":false,"statusCheckInterval":45}', true, 45],
|
||||
['{"useGlobalStatusInterval":true,"statusCheckInterval":45}', true, null],
|
||||
['{"useGlobalStatusInterval":false,"statusCheckInterval":2}', true, null],
|
||||
[
|
||||
JSON.stringify(JSON.stringify({ statusCheckEnabled: false })),
|
||||
false,
|
||||
null,
|
||||
],
|
||||
["not json", true, null],
|
||||
])("%s", (raw, enabled, interval) => {
|
||||
expect(statusConfigFromStatsConfig(raw)).toEqual({
|
||||
statusCheckEnabled: enabled,
|
||||
statusCheckInterval: interval,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("runHostStatusConfigMigration", () => {
|
||||
it("copies each host's status options into the new columns", async () => {
|
||||
const insert = sqlite.prepare(
|
||||
"INSERT INTO ssh_data (id, stats_config) VALUES (?, ?)",
|
||||
);
|
||||
insert.run(1, JSON.stringify({ statusCheckEnabled: false }));
|
||||
insert.run(
|
||||
2,
|
||||
JSON.stringify({
|
||||
useGlobalStatusInterval: false,
|
||||
statusCheckInterval: 45,
|
||||
}),
|
||||
);
|
||||
insert.run(
|
||||
3,
|
||||
JSON.stringify({ disableTcpPing: true, metricsEnabled: false }),
|
||||
);
|
||||
insert.run(4, JSON.stringify({ metricsInterval: 10 }));
|
||||
insert.run(5, null);
|
||||
|
||||
const result = await runHostStatusConfigMigration();
|
||||
|
||||
expect(result).toEqual({ skipped: false, hostsMoved: 3 });
|
||||
expect(hosts()).toEqual([
|
||||
{ id: 1, enabled: 0, interval: null },
|
||||
{ id: 2, enabled: 1, interval: 45 },
|
||||
{ id: 3, enabled: 0, interval: null },
|
||||
{ id: 4, enabled: 1, interval: null },
|
||||
{ id: 5, enabled: 1, interval: null },
|
||||
]);
|
||||
expect(state.settings.get(HOST_STATUS_CONFIG_MIGRATED)).toBe("true");
|
||||
});
|
||||
|
||||
it("changes nothing the second time", async () => {
|
||||
sqlite
|
||||
.prepare("INSERT INTO ssh_data (id, stats_config) VALUES (?, ?)")
|
||||
.run(1, JSON.stringify({ statusCheckEnabled: false }));
|
||||
await runHostStatusConfigMigration();
|
||||
|
||||
// The user turns checks back on after the upgrade.
|
||||
sqlite.exec("UPDATE ssh_data SET status_check_enabled = 1 WHERE id = 1");
|
||||
expect(await runHostStatusConfigMigration()).toEqual({
|
||||
skipped: true,
|
||||
hostsMoved: 0,
|
||||
});
|
||||
expect(hosts()).toEqual([{ id: 1, enabled: 1, interval: null }]);
|
||||
});
|
||||
|
||||
it("finishes on a fresh install that never had stats_config", async () => {
|
||||
createHosts(false);
|
||||
sqlite.exec("INSERT INTO ssh_data (id) VALUES (1)");
|
||||
expect(await runHostStatusConfigMigration()).toEqual({
|
||||
skipped: false,
|
||||
hostsMoved: 0,
|
||||
});
|
||||
expect(state.settings.get(HOST_STATUS_CONFIG_MIGRATED)).toBe("true");
|
||||
});
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
getDesktopOidcCallbackUrl,
|
||||
isOidcTokenCallback,
|
||||
} from "../../utils/oidc-desktop-callback.js";
|
||||
|
||||
describe("getDesktopOidcCallbackUrl", () => {
|
||||
it("uses localhost so browsers do not upgrade the loopback callback", () => {
|
||||
expect(getDesktopOidcCallbackUrl("17850")).toBe(
|
||||
"http://localhost:17850/oidc-callback",
|
||||
);
|
||||
});
|
||||
|
||||
it.each(["", "0", "65536", "17850/path", ["17850"]])(
|
||||
"rejects invalid callback port %j",
|
||||
(port) => {
|
||||
expect(getDesktopOidcCallbackUrl(port)).toBeNull();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("isOidcTokenCallback", () => {
|
||||
it.each([
|
||||
"http://localhost:17850/oidc-callback",
|
||||
"http://127.0.0.1:17850/oidc-callback",
|
||||
"termix-mobile://oidc-callback",
|
||||
])("recognizes app callback %s", (url) => {
|
||||
expect(isOidcTokenCallback(url)).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://localhost:17850/oidc-callback",
|
||||
"http://example.com:17850/oidc-callback",
|
||||
"http://localhost:17850/other",
|
||||
])("rejects non-app callback %s", (url) => {
|
||||
expect(isOidcTokenCallback(url)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
isSecretReference,
|
||||
parseSecretReference,
|
||||
} from "../../utils/onepassword-connect.js";
|
||||
|
||||
describe("1Password secret references", () => {
|
||||
it("parses op://vault/item/field, ignoring a query suffix", () => {
|
||||
expect(parseSecretReference("op://Infra/prod-db/password")).toEqual({
|
||||
vault: "Infra",
|
||||
item: "prod-db",
|
||||
field: "password",
|
||||
});
|
||||
expect(
|
||||
parseSecretReference(
|
||||
"op://Infra/deploy key/private key?ssh-format=openssh",
|
||||
),
|
||||
).toEqual({ vault: "Infra", item: "deploy key", field: "private key" });
|
||||
expect(parseSecretReference("op://Infra/only-two")).toBeNull();
|
||||
expect(parseSecretReference("https://x")).toBeNull();
|
||||
});
|
||||
|
||||
it("recognises references without confusing them with secrets", () => {
|
||||
expect(isSecretReference("op://v/i/f")).toBe(true);
|
||||
expect(isSecretReference(" op://v/i/f")).toBe(true);
|
||||
expect(isSecretReference("hunter2")).toBe(false);
|
||||
expect(isSecretReference(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,97 +0,0 @@
|
||||
import crypto from "crypto";
|
||||
import { promises as fs } from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { OPKSSHBinaryManager } from "../../utils/opkssh-binary-manager.js";
|
||||
|
||||
// Mirrors the manager's own platform/arch mapping so the test's fake release
|
||||
// asset matches whatever OS and architecture actually run the suite.
|
||||
const OS_MAP: Record<string, string> = {
|
||||
win32: "windows",
|
||||
linux: "linux",
|
||||
darwin: "osx",
|
||||
};
|
||||
const ARCH_MAP: Record<string, string> = {
|
||||
x64: "amd64",
|
||||
arm64: "arm64",
|
||||
};
|
||||
const mappedOs = OS_MAP[process.platform] ?? process.platform;
|
||||
const mappedArch = ARCH_MAP[process.arch] ?? process.arch;
|
||||
const binaryName =
|
||||
process.platform === "win32"
|
||||
? `opkssh-${mappedOs}-${mappedArch}.exe`
|
||||
: `opkssh-${mappedOs}-${mappedArch}`;
|
||||
let dataDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
dataDir = await fs.mkdtemp(path.join(os.tmpdir(), "termix-opkssh-"));
|
||||
process.env.DATA_DIR = dataDir;
|
||||
process.env.OPKSSH_VERSION = "v-test";
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals();
|
||||
delete process.env.DATA_DIR;
|
||||
delete process.env.OPKSSH_VERSION;
|
||||
delete process.env.OPKSSH_SHA256;
|
||||
await fs.rm(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function mockRelease(binary: Buffer): void {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
tag_name: "v-test",
|
||||
assets: [
|
||||
{ name: binaryName, browser_download_url: "https://asset.test" },
|
||||
],
|
||||
}),
|
||||
{ status: 200 },
|
||||
),
|
||||
)
|
||||
.mockResolvedValueOnce(new Response(binary, { status: 200 })),
|
||||
);
|
||||
}
|
||||
|
||||
describe("OPKSSHBinaryManager download integrity", () => {
|
||||
it("installs a release only after its configured checksum matches", async () => {
|
||||
const binary = Buffer.from("verified-opkssh-binary");
|
||||
process.env.OPKSSH_SHA256 = crypto
|
||||
.createHash("sha256")
|
||||
.update(binary)
|
||||
.digest("hex");
|
||||
mockRelease(binary);
|
||||
|
||||
await OPKSSHBinaryManager.downloadBinary();
|
||||
|
||||
const installDir = path.join(dataDir, "opkssh");
|
||||
expect(await fs.readFile(path.join(installDir, binaryName))).toEqual(
|
||||
binary,
|
||||
);
|
||||
expect(
|
||||
await fs.readFile(path.join(installDir, "version.txt"), "utf8"),
|
||||
).toBe("v-test");
|
||||
expect(
|
||||
await fs.readFile(path.join(installDir, "checksum.txt"), "utf8"),
|
||||
).toBe(process.env.OPKSSH_SHA256);
|
||||
});
|
||||
|
||||
it("rejects a mismatched release without replacing the installed binary", async () => {
|
||||
const installDir = path.join(dataDir, "opkssh");
|
||||
const binaryPath = path.join(installDir, binaryName);
|
||||
await fs.mkdir(installDir, { recursive: true });
|
||||
await fs.writeFile(binaryPath, "known-good");
|
||||
process.env.OPKSSH_SHA256 = "0".repeat(64);
|
||||
mockRelease(Buffer.from("tampered"));
|
||||
|
||||
await expect(OPKSSHBinaryManager.downloadBinary()).rejects.toThrow(
|
||||
"checksum mismatch",
|
||||
);
|
||||
expect(await fs.readFile(binaryPath, "utf8")).toBe("known-good");
|
||||
});
|
||||
});
|
||||
@@ -3,11 +3,37 @@ import {
|
||||
PERMISSION_CATALOG,
|
||||
getPermissionCatalog,
|
||||
isValidPermission,
|
||||
registerPermissionGroup,
|
||||
unregisterPermissionGroup,
|
||||
loadKnownPermissions,
|
||||
markPluginPermissionsDisabled,
|
||||
registerPluginPermissions,
|
||||
rememberPermissionGroup,
|
||||
resetPermissionCatalog,
|
||||
SYSTEM_ROLE_DEFAULTS,
|
||||
} from "../../utils/permission-catalog.js";
|
||||
|
||||
const GROUP = "testplugin";
|
||||
const PERMISSIONS = ["testplugin.view", "testplugin.manage"];
|
||||
|
||||
function register() {
|
||||
registerPluginPermissions({
|
||||
group: GROUP,
|
||||
pluginId: GROUP,
|
||||
label: "Test Plugin",
|
||||
icon: "Sparkles",
|
||||
permissions: PERMISSIONS,
|
||||
items: PERMISSIONS.map((permission) => ({
|
||||
permission,
|
||||
titleKey: "permissions.x.title",
|
||||
descriptionKey: "permissions.x.description",
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
describe("permission catalog", () => {
|
||||
afterEach(() => {
|
||||
resetPermissionCatalog();
|
||||
});
|
||||
|
||||
it("accepts every cataloged permission and group wildcard", () => {
|
||||
for (const entry of PERMISSION_CATALOG) {
|
||||
expect(isValidPermission(`${entry.group}.*`)).toBe(true);
|
||||
@@ -27,74 +53,126 @@ describe("permission catalog", () => {
|
||||
expect(isValidPermission("")).toBe(false);
|
||||
expect(isValidPermission("hosts")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runtime permission group lifecycle", () => {
|
||||
const group = "testplugin";
|
||||
const permissions = ["testplugin.view", "testplugin.manage"];
|
||||
|
||||
afterEach(() => {
|
||||
unregisterPermissionGroup(group);
|
||||
// Both moved out to their plugins in A5; the ids did not change, so no role
|
||||
// had to be migrated.
|
||||
it("no longer carries the ai or automations groups", () => {
|
||||
const groups = PERMISSION_CATALOG.map((entry) => entry.group);
|
||||
expect(groups).not.toContain("ai");
|
||||
expect(groups).not.toContain("automations");
|
||||
});
|
||||
|
||||
it("rejects a group's permissions before it is registered", () => {
|
||||
it("no longer seeds ai or automations onto the user role", () => {
|
||||
expect(SYSTEM_ROLE_DEFAULTS.user.permissions).not.toContain("ai.*");
|
||||
expect(SYSTEM_ROLE_DEFAULTS.user.permissions).not.toContain(
|
||||
"automations.*",
|
||||
);
|
||||
expect(SYSTEM_ROLE_DEFAULTS.user.permissions).toContain("hosts.*");
|
||||
});
|
||||
|
||||
it("gives every core group a label key for the role editor", () => {
|
||||
for (const entry of PERMISSION_CATALOG) {
|
||||
expect(entry.labelKey).toBeTruthy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("plugin permission lifecycle", () => {
|
||||
afterEach(() => {
|
||||
resetPermissionCatalog();
|
||||
});
|
||||
|
||||
it("rejects a plugin's permissions before it registers", () => {
|
||||
expect(isValidPermission("testplugin.view")).toBe(false);
|
||||
expect(isValidPermission("testplugin.*")).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a group's permissions and wildcard once registered", () => {
|
||||
registerPermissionGroup({ group, permissions });
|
||||
it("accepts them once registered", () => {
|
||||
register();
|
||||
|
||||
expect(isValidPermission("testplugin.view")).toBe(true);
|
||||
expect(isValidPermission("testplugin.manage")).toBe(true);
|
||||
expect(isValidPermission("testplugin.*")).toBe(true);
|
||||
expect(isValidPermission("*")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects a group's permissions again after it is unregistered", () => {
|
||||
registerPermissionGroup({ group, permissions });
|
||||
it("carries the plugin id, label and icon into the catalog", () => {
|
||||
register();
|
||||
|
||||
const entry = getPermissionCatalog().find((row) => row.group === GROUP);
|
||||
expect(entry?.pluginId).toBe(GROUP);
|
||||
expect(entry?.label).toBe("Test Plugin");
|
||||
expect(entry?.icon).toBe("Sparkles");
|
||||
expect(entry?.enabled).toBe(true);
|
||||
expect(entry?.items).toHaveLength(2);
|
||||
});
|
||||
|
||||
// The bug A5 fixes: unregistering made PUT /rbac/roles/:id reject every role
|
||||
// that still held one of these, so an admin could not save an unrelated
|
||||
// change while the plugin was off.
|
||||
it("keeps a disabled plugin's permissions valid", () => {
|
||||
register();
|
||||
markPluginPermissionsDisabled(GROUP);
|
||||
|
||||
expect(isValidPermission("testplugin.view")).toBe(true);
|
||||
|
||||
unregisterPermissionGroup(group);
|
||||
|
||||
expect(isValidPermission("testplugin.view")).toBe(false);
|
||||
expect(isValidPermission("testplugin.*")).toBe(false);
|
||||
expect(isValidPermission("testplugin.*")).toBe(true);
|
||||
});
|
||||
|
||||
it("includes registered groups in getPermissionCatalog and drops them on unregister", () => {
|
||||
expect(getPermissionCatalog().some((entry) => entry.group === group)).toBe(
|
||||
false,
|
||||
);
|
||||
it("marks a disabled plugin's group so the editor can grey it", () => {
|
||||
register();
|
||||
markPluginPermissionsDisabled(GROUP);
|
||||
|
||||
registerPermissionGroup({ group, permissions });
|
||||
expect(getPermissionCatalog().some((entry) => entry.group === group)).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
unregisterPermissionGroup(group);
|
||||
expect(getPermissionCatalog().some((entry) => entry.group === group)).toBe(
|
||||
false,
|
||||
);
|
||||
const entry = getPermissionCatalog().find((row) => row.group === GROUP);
|
||||
expect(entry?.enabled).toBe(false);
|
||||
});
|
||||
|
||||
it("does not mutate the static PERMISSION_CATALOG array", () => {
|
||||
const originalLength = PERMISSION_CATALOG.length;
|
||||
registerPermissionGroup({ group, permissions });
|
||||
register();
|
||||
|
||||
expect(PERMISSION_CATALOG.length).toBe(originalLength);
|
||||
expect(PERMISSION_CATALOG.some((entry) => entry.group === group)).toBe(
|
||||
expect(PERMISSION_CATALOG.some((entry) => entry.group === GROUP)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("overwrites an existing runtime group when re-registered with the same name", () => {
|
||||
registerPermissionGroup({ group, permissions: ["testplugin.view"] });
|
||||
expect(isValidPermission("testplugin.manage")).toBe(false);
|
||||
it("lists a plugin group exactly once when re-registered", () => {
|
||||
register();
|
||||
register();
|
||||
|
||||
registerPermissionGroup({
|
||||
group,
|
||||
permissions: ["testplugin.view", "testplugin.manage"],
|
||||
});
|
||||
expect(isValidPermission("testplugin.manage")).toBe(true);
|
||||
const matches = getPermissionCatalog().filter(
|
||||
(entry) => entry.group === GROUP,
|
||||
);
|
||||
expect(matches).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("known permissions", () => {
|
||||
afterEach(() => {
|
||||
resetPermissionCatalog();
|
||||
});
|
||||
|
||||
// The upgrade path: a permission a role already holds stays grantable even
|
||||
// if no plugin ever registers it again.
|
||||
it("accepts a permission loaded from the record with no plugin present", () => {
|
||||
expect(isValidPermission("gone.use")).toBe(false);
|
||||
|
||||
loadKnownPermissions(["gone.use"]);
|
||||
|
||||
expect(isValidPermission("gone.use")).toBe(true);
|
||||
expect(isValidPermission("gone.*")).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a group recorded from a wildcard nothing else named", () => {
|
||||
rememberPermissionGroup("legacy");
|
||||
|
||||
expect(isValidPermission("legacy.*")).toBe(true);
|
||||
// Still rejects a concrete permission nobody ever registered.
|
||||
expect(isValidPermission("legacy.invent")).toBe(false);
|
||||
});
|
||||
|
||||
it("still rejects a permission nobody has ever registered", () => {
|
||||
loadKnownPermissions(["gone.use"]);
|
||||
|
||||
expect(isValidPermission("madeup.use")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -120,11 +120,13 @@ describe("PermissionManager.hasPermission wildcard matching", () => {
|
||||
});
|
||||
|
||||
it("resolves wildcards for a runtime-registered permission group", async () => {
|
||||
const { registerPermissionGroup, unregisterPermissionGroup } =
|
||||
const { registerPluginPermissions, resetPermissionCatalog } =
|
||||
await import("../../utils/permission-catalog.js");
|
||||
|
||||
registerPermissionGroup({
|
||||
registerPluginPermissions({
|
||||
group: "testplugin",
|
||||
pluginId: "testplugin",
|
||||
label: "Test Plugin",
|
||||
permissions: ["testplugin.view", "testplugin.manage"],
|
||||
});
|
||||
|
||||
@@ -136,7 +138,7 @@ describe("PermissionManager.hasPermission wildcard matching", () => {
|
||||
withPermissions(["*"]);
|
||||
expect(await manager.hasPermission("u1", "testplugin.view")).toBe(true);
|
||||
} finally {
|
||||
unregisterPermissionGroup("testplugin");
|
||||
resetPermissionCatalog();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
const db = vi.hoisted(() => ({ current: {} as Record<string, unknown> }));
|
||||
|
||||
vi.mock("../../database/db/index.js", () => ({
|
||||
getDb: () => db.current,
|
||||
}));
|
||||
|
||||
const { selectRows, runStatement } =
|
||||
await import("../../utils/crypto-migration/raw-rows.js");
|
||||
|
||||
describe("raw-rows", () => {
|
||||
beforeEach(() => {
|
||||
db.current = {};
|
||||
});
|
||||
|
||||
it("uses all() and run() on SQLite", async () => {
|
||||
const run = vi.fn();
|
||||
db.current = { all: async () => [{ id: 1 }], run };
|
||||
await expect(selectRows(sql`SELECT 1`)).resolves.toEqual([{ id: 1 }]);
|
||||
await runStatement(sql`UPDATE x SET y = 1`);
|
||||
expect(run).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("reads rows from node-postgres's { rows }", async () => {
|
||||
db.current = { execute: async () => ({ rows: [{ id: 2 }] }) };
|
||||
await expect(selectRows(sql`SELECT 1`)).resolves.toEqual([{ id: 2 }]);
|
||||
});
|
||||
|
||||
it("reads rows from mysql2's [rows, fields]", async () => {
|
||||
const execute = vi.fn(async () => [[{ id: 3 }], []]);
|
||||
db.current = { execute };
|
||||
await expect(selectRows(sql`SELECT 1`)).resolves.toEqual([{ id: 3 }]);
|
||||
await runStatement(sql`UPDATE x SET y = 1`);
|
||||
expect(execute).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* An admin-allowlisted private host goes through the configured proxy; a
|
||||
* public host never does, since the proxy would skip the address check.
|
||||
*/
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const h = vi.hoisted(() => ({
|
||||
calls: [] as Array<{ url: string; dispatcher: unknown }>,
|
||||
proxy: { kind: "proxy" } as unknown,
|
||||
proxyConfigured: true,
|
||||
}));
|
||||
|
||||
vi.mock("undici", () => ({
|
||||
Agent: class {
|
||||
kind = "direct";
|
||||
async close() {}
|
||||
},
|
||||
fetch: async (url: string, init: { dispatcher: unknown }) => {
|
||||
h.calls.push({ url, dispatcher: init.dispatcher });
|
||||
return new Response("ok");
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/proxy-agent.js", () => ({
|
||||
getProxyAgent: () => (h.proxyConfigured ? h.proxy : undefined),
|
||||
}));
|
||||
|
||||
const { safeOutboundFetch } =
|
||||
await import("../../utils/safe-outbound-fetch.js");
|
||||
|
||||
beforeEach(() => {
|
||||
h.calls.length = 0;
|
||||
h.proxyConfigured = true;
|
||||
});
|
||||
|
||||
describe("safeOutboundFetch and the proxy", () => {
|
||||
it("sends an allowlisted private host through the proxy", async () => {
|
||||
await safeOutboundFetch("http://10.0.0.5:11434/api", {}, ["10.0.0.5"]);
|
||||
expect(h.calls[0].dispatcher).toBe(h.proxy);
|
||||
});
|
||||
|
||||
it("keeps a public host on the checked direct connection", async () => {
|
||||
await safeOutboundFetch("https://api.example.com/v1", {}, []);
|
||||
expect(h.calls[0].dispatcher).not.toBe(h.proxy);
|
||||
});
|
||||
|
||||
it("connects directly when no proxy is configured", async () => {
|
||||
h.proxyConfigured = false;
|
||||
await safeOutboundFetch("http://10.0.0.5/api", {}, ["10.0.0.5"]);
|
||||
expect(h.calls[0].dispatcher).not.toBe(h.proxy);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,13 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createServer } from "http";
|
||||
import type { AddressInfo } from "net";
|
||||
import type { LookupAddress, LookupOptions } from "dns";
|
||||
import {
|
||||
createDnsLookupHook,
|
||||
isBlockedAddress,
|
||||
outboundIdleTimeout,
|
||||
readResponseTextLimited,
|
||||
safeOutboundFetch,
|
||||
} from "../../utils/safe-outbound-fetch.js";
|
||||
|
||||
describe("isBlockedAddress", () => {
|
||||
@@ -257,3 +261,70 @@ describe("createDnsLookupHook", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("safeOutboundFetch", () => {
|
||||
it("returns a large body the caller reads after the call", async () => {
|
||||
const body = "x".repeat(1_000_000);
|
||||
const server = createServer((_req, res) => res.end(body));
|
||||
await new Promise<void>((resolve) =>
|
||||
server.listen(0, "127.0.0.1", resolve),
|
||||
);
|
||||
const { port } = server.address() as AddressInfo;
|
||||
try {
|
||||
const response = await safeOutboundFetch(
|
||||
`http://127.0.0.1:${port}/`,
|
||||
{},
|
||||
["127.0.0.1"],
|
||||
);
|
||||
expect((await response.text()).length).toBe(body.length);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
describe("outboundIdleTimeout", () => {
|
||||
it("keeps undici's 5 minute default as the floor", () => {
|
||||
expect(outboundIdleTimeout()).toBe(300_000);
|
||||
expect(outboundIdleTimeout(30_000)).toBe(300_000);
|
||||
});
|
||||
|
||||
it("raises the idle timeout for a longer request timeout", () => {
|
||||
expect(outboundIdleTimeout(600_000)).toBe(600_000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("redirect handling", () => {
|
||||
it.each([undefined, "error", "follow", "manual"] as const)(
|
||||
"never follows redirects with mode %s",
|
||||
async (redirect) => {
|
||||
const paths: string[] = [];
|
||||
const server = createServer((req, res) => {
|
||||
paths.push(req.url!);
|
||||
res.writeHead(302, { Location: "/private-target" });
|
||||
res.end();
|
||||
});
|
||||
await new Promise<void>((resolve) =>
|
||||
server.listen(0, "127.0.0.1", resolve),
|
||||
);
|
||||
const { port } = server.address() as AddressInfo;
|
||||
try {
|
||||
const response = safeOutboundFetch(
|
||||
`http://127.0.0.1:${port}/`,
|
||||
{ redirect },
|
||||
["127.0.0.1"],
|
||||
);
|
||||
if (redirect === "manual") {
|
||||
const result = await response;
|
||||
expect(result.status).toBe(302);
|
||||
await result.body?.cancel();
|
||||
} else {
|
||||
await expect(response).rejects.toThrow();
|
||||
}
|
||||
expect(paths).toEqual(["/"]);
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,146 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import express from "express";
|
||||
import http from "http";
|
||||
import type { AddressInfo } from "net";
|
||||
import { listenOnServicePort } from "../../utils/service-listen.js";
|
||||
import { Logger } from "../../utils/logger.js";
|
||||
|
||||
function testLogger() {
|
||||
const logger = new Logger("TEST", "🧪", "#000000");
|
||||
return {
|
||||
logger,
|
||||
error: vi.spyOn(logger, "error").mockImplementation(() => {}),
|
||||
};
|
||||
}
|
||||
|
||||
function occupyPort(): Promise<{ port: number; release: () => void }> {
|
||||
return new Promise((resolve) => {
|
||||
const blocker = http.createServer();
|
||||
blocker.listen(0, "127.0.0.1", () => {
|
||||
resolve({
|
||||
port: (blocker.address() as AddressInfo).port,
|
||||
release: () => blocker.close(),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const servers: http.Server[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
while (servers.length) servers.pop()?.close();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("listenOnServicePort", () => {
|
||||
it("starts the service and reports listening on a free port", async () => {
|
||||
const { logger, error } = testLogger();
|
||||
const onListening = vi.fn();
|
||||
|
||||
const server = listenOnServicePort({
|
||||
app: express(),
|
||||
port: 0,
|
||||
logger,
|
||||
serviceName: "test",
|
||||
onListening,
|
||||
});
|
||||
servers.push(server);
|
||||
|
||||
await vi.waitFor(() => expect(onListening).toHaveBeenCalledOnce());
|
||||
expect(server.listening).toBe(true);
|
||||
expect(error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// The bug this helper exists for: express's app.listen(port, host, cb)
|
||||
// registers cb as the server's error handler too, so a port conflict
|
||||
// invoked the "service started" callback and emitted nothing at all.
|
||||
it("does not report the service as started when the port is taken", async () => {
|
||||
const { port, release } = await occupyPort();
|
||||
const { logger } = testLogger();
|
||||
const onListening = vi.fn();
|
||||
const exit = vi
|
||||
.spyOn(process, "exit")
|
||||
.mockImplementation(() => undefined as never);
|
||||
|
||||
const server = listenOnServicePort({
|
||||
app: express(),
|
||||
port,
|
||||
logger,
|
||||
serviceName: "test",
|
||||
onListening,
|
||||
});
|
||||
servers.push(server);
|
||||
|
||||
await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(1));
|
||||
expect(onListening).not.toHaveBeenCalled();
|
||||
release();
|
||||
});
|
||||
|
||||
it("names the conflicting port so the desktop can surface it", async () => {
|
||||
const { port, release } = await occupyPort();
|
||||
const { logger, error } = testLogger();
|
||||
vi.spyOn(process, "exit").mockImplementation(() => undefined as never);
|
||||
|
||||
servers.push(
|
||||
listenOnServicePort({
|
||||
app: express(),
|
||||
port,
|
||||
logger,
|
||||
serviceName: "metrics",
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(() => expect(error).toHaveBeenCalled());
|
||||
const [message, , context] = error.mock.calls[0];
|
||||
expect(message).toContain(String(port));
|
||||
expect(context).toMatchObject({
|
||||
operation: "service_port_conflict",
|
||||
port,
|
||||
service: "metrics",
|
||||
});
|
||||
release();
|
||||
});
|
||||
|
||||
it("leaves any other listen error to the process-level handlers", async () => {
|
||||
const { logger } = testLogger();
|
||||
const exit = vi
|
||||
.spyOn(process, "exit")
|
||||
.mockImplementation(() => undefined as never);
|
||||
const server = listenOnServicePort({
|
||||
app: express(),
|
||||
port: 0,
|
||||
logger,
|
||||
serviceName: "test",
|
||||
});
|
||||
servers.push(server);
|
||||
|
||||
const notPortConflict = Object.assign(new Error("boom"), { code: "EPERM" });
|
||||
expect(() => server.emit("error", notPortConflict)).toThrow("boom");
|
||||
expect(exit).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// express's app.listen() swallows a bind failure by design (see
|
||||
// service-listen.ts), so no service may reach for it again.
|
||||
describe("backend services", () => {
|
||||
function sourceFiles(dir: string): string[] {
|
||||
return readdirSync(dir).flatMap((entry) => {
|
||||
const full = path.join(dir, entry);
|
||||
if (statSync(full).isDirectory()) {
|
||||
return entry === "tests" ? [] : sourceFiles(full);
|
||||
}
|
||||
return full.endsWith(".ts") ? [full] : [];
|
||||
});
|
||||
}
|
||||
|
||||
it("never bind a port with express's app.listen()", () => {
|
||||
const offenders = sourceFiles(path.resolve("src/backend"))
|
||||
// service-listen.ts names the call only to document why it is banned.
|
||||
.filter((file) => !file.endsWith(path.join("utils", "service-listen.ts")))
|
||||
.filter((file) => /\bapp\.listen\(/.test(readFileSync(file, "utf8")));
|
||||
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -12,9 +12,19 @@ const state = vi.hoisted(() => ({
|
||||
accessToHost: new Map<number, number>(),
|
||||
grants: [] as Array<Record<string, unknown>>,
|
||||
roleMembers: new Map<number, string[]>(),
|
||||
// hostId -> that host's plugin protocol logins, decrypted
|
||||
logins: new Map<number, Array<Record<string, unknown>>>(),
|
||||
}));
|
||||
|
||||
vi.mock("../../hosts/usable-credential.js", () => ({
|
||||
findUsableCredential: async (credentialId: number) =>
|
||||
state.credentials.get(credentialId) ?? null,
|
||||
}));
|
||||
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentHostProtocolAuthRepository: () => ({
|
||||
listForHost: async (hostId: number) => state.logins.get(hostId) ?? [],
|
||||
}),
|
||||
createCurrentHostResolutionRepository: () => ({
|
||||
findHostById: async (hostId: number) => state.hosts.get(hostId) ?? null,
|
||||
findHostOwnerId: async (hostId: number) =>
|
||||
@@ -137,22 +147,20 @@ function baseHost(overrides: Record<string, unknown> = {}) {
|
||||
credentialId: null,
|
||||
shareSshAuth: false,
|
||||
enableSsh: true,
|
||||
enableRdp: false,
|
||||
enableVnc: false,
|
||||
enableTelnet: false,
|
||||
rdpAuthType: null,
|
||||
vncAuthType: null,
|
||||
telnetAuthType: null,
|
||||
rdpCredentialId: null,
|
||||
vncCredentialId: null,
|
||||
telnetCredentialId: null,
|
||||
rdpUser: null,
|
||||
rdpPassword: null,
|
||||
rdpDomain: null,
|
||||
vncUser: null,
|
||||
vncPassword: null,
|
||||
telnetUser: null,
|
||||
telnetPassword: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** A plugin protocol login as the repository hands it back, decrypted. */
|
||||
function login(protocol: string, overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
protocol,
|
||||
authType: "direct",
|
||||
credentialId: null,
|
||||
username: null,
|
||||
password: null,
|
||||
fields: {},
|
||||
secretFields: {},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -164,6 +172,7 @@ beforeEach(() => {
|
||||
state.accessToHost = new Map([[7, 42]]);
|
||||
state.grants = [];
|
||||
state.roleMembers.clear();
|
||||
state.logins.clear();
|
||||
});
|
||||
|
||||
describe("SharedHostSecretsManager", () => {
|
||||
@@ -189,7 +198,7 @@ describe("SharedHostSecretsManager", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("snapshots opted-in SSH credential auth alongside enabled non-SSH protocols", async () => {
|
||||
it("snapshots opted-in SSH credential auth alongside plugin protocol logins", async () => {
|
||||
state.credentials.set(123, {
|
||||
id: 123,
|
||||
userId: "owner",
|
||||
@@ -208,22 +217,24 @@ describe("SharedHostSecretsManager", () => {
|
||||
credentialId: 123,
|
||||
shareSshAuth: true,
|
||||
password: null,
|
||||
enableRdp: true,
|
||||
rdpUser: "rdp-admin",
|
||||
rdpPassword: "rdp-pass",
|
||||
rdpDomain: "CORP",
|
||||
enableTelnet: true,
|
||||
telnetUser: "tel-user",
|
||||
telnetPassword: "tel-pass",
|
||||
}),
|
||||
);
|
||||
state.logins.set(42, [
|
||||
login("spice", {
|
||||
username: "spice-admin",
|
||||
password: "spice-pass",
|
||||
fields: { display: "2" },
|
||||
secretFields: { ticket: "t-1" },
|
||||
}),
|
||||
login("x2go", { username: "x-user", password: "x-pass" }),
|
||||
]);
|
||||
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
|
||||
expect(state.secretRows.map((row) => row.protocol).sort()).toEqual([
|
||||
"rdp",
|
||||
"spice",
|
||||
"ssh",
|
||||
"telnet",
|
||||
"x2go",
|
||||
]);
|
||||
|
||||
expect(await manager.getSecretForUser(42, "target", "ssh")).toMatchObject({
|
||||
@@ -234,21 +245,101 @@ describe("SharedHostSecretsManager", () => {
|
||||
keyType: "ssh-ed25519",
|
||||
});
|
||||
|
||||
const rdp = await manager.getSecretForUser(42, "target", "rdp");
|
||||
expect(rdp).toMatchObject({
|
||||
username: "rdp-admin",
|
||||
password: "rdp-pass",
|
||||
domain: "CORP",
|
||||
const spice = await manager.getSecretForUser(42, "target", "spice");
|
||||
expect(spice).toMatchObject({
|
||||
username: "spice-admin",
|
||||
password: "spice-pass",
|
||||
fields: { display: "2", ticket: "t-1" },
|
||||
authType: "direct",
|
||||
});
|
||||
|
||||
const telnet = await manager.getSecretForUser(42, "target", "telnet");
|
||||
expect(telnet).toMatchObject({
|
||||
username: "tel-user",
|
||||
password: "tel-pass",
|
||||
const x2go = await manager.getSecretForUser(42, "target", "x2go");
|
||||
expect(x2go).toMatchObject({
|
||||
username: "x-user",
|
||||
password: "x-pass",
|
||||
});
|
||||
});
|
||||
|
||||
it("snapshots a credential-backed protocol login from the credential", async () => {
|
||||
state.credentials.set(55, {
|
||||
id: 55,
|
||||
userId: "owner",
|
||||
username: "cred-viewer",
|
||||
password: "cred-pass",
|
||||
});
|
||||
state.hosts.set(42, baseHost());
|
||||
state.logins.set(42, [
|
||||
login("spice", {
|
||||
authType: "credential",
|
||||
credentialId: 55,
|
||||
fields: { display: "1" },
|
||||
}),
|
||||
]);
|
||||
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
|
||||
expect(state.secretRows[0]).toMatchObject({
|
||||
protocol: "spice",
|
||||
sourceType: "credential",
|
||||
originalCredentialId: 55,
|
||||
});
|
||||
expect(await manager.getSecretForUser(42, "target", "spice")).toMatchObject(
|
||||
{
|
||||
authType: "credential",
|
||||
username: "cred-viewer",
|
||||
password: "cred-pass",
|
||||
fields: { display: "1" },
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("takes no snapshot of a login that asks at connect time", async () => {
|
||||
state.hosts.set(42, baseHost());
|
||||
state.logins.set(42, [login("spice", { authType: "none" })]);
|
||||
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
|
||||
expect(state.secretRows).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("reads a snapshot taken before 2.9.0 with its domain column", async () => {
|
||||
const recordId = "shared-7-target-legacy";
|
||||
state.secretRows.push({
|
||||
id: 1,
|
||||
hostAccessId: 7,
|
||||
targetUserId: "target",
|
||||
protocol: "legacy",
|
||||
encryptedUsername: FieldCrypto.encryptField(
|
||||
"admin",
|
||||
targetDEK,
|
||||
recordId,
|
||||
"username",
|
||||
),
|
||||
encryptedAuthType: "direct",
|
||||
encryptedDomain: FieldCrypto.encryptField(
|
||||
"CORP",
|
||||
targetDEK,
|
||||
recordId,
|
||||
"domain",
|
||||
),
|
||||
});
|
||||
|
||||
expect(
|
||||
await manager.getSecretForUser(42, "target", "legacy"),
|
||||
).toMatchObject({ username: "admin", fields: { domain: "CORP" } });
|
||||
});
|
||||
|
||||
it("drops a protocol's snapshot once its login is gone", async () => {
|
||||
state.hosts.set(42, baseHost());
|
||||
state.logins.set(42, [login("spice", { username: "u", password: "p" })]);
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
expect(state.secretRows).toHaveLength(1);
|
||||
|
||||
state.logins.set(42, []);
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
expect(state.secretRows).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("produces no snapshot rows for secret-less auth types", async () => {
|
||||
state.hosts.set(
|
||||
42,
|
||||
@@ -283,36 +374,54 @@ describe("SharedHostSecretsManager", () => {
|
||||
});
|
||||
|
||||
it("cannot be decrypted with the wrong DEK", async () => {
|
||||
state.hosts.set(
|
||||
42,
|
||||
baseHost({
|
||||
enableRdp: true,
|
||||
rdpUser: "rdp-admin",
|
||||
rdpPassword: "rdp-pass",
|
||||
state.hosts.set(42, baseHost());
|
||||
state.logins.set(42, [
|
||||
login("spice", {
|
||||
username: "spice-admin",
|
||||
password: "spice-pass",
|
||||
secretFields: { ticket: "t-1" },
|
||||
}),
|
||||
);
|
||||
]);
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
|
||||
const row = state.secretRows[0];
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(
|
||||
row.encryptedPassword as string,
|
||||
ownerDEK,
|
||||
"shared-7-target-rdp",
|
||||
"password",
|
||||
),
|
||||
).toThrow();
|
||||
for (const [column, field] of [
|
||||
["encryptedPassword", "password"],
|
||||
["encryptedFields", "fields"],
|
||||
]) {
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(
|
||||
row[column] as string,
|
||||
ownerDEK,
|
||||
"shared-7-target-spice",
|
||||
field,
|
||||
),
|
||||
).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses a tampered snapshot rather than handing it out", async () => {
|
||||
state.hosts.set(42, baseHost());
|
||||
state.logins.set(42, [login("spice", { password: "spice-pass" })]);
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
|
||||
const row = state.secretRows[0];
|
||||
const envelope = JSON.parse(row.encryptedPassword as string);
|
||||
envelope.data = envelope.data.replace(/^./, (c: string) =>
|
||||
c === "0" ? "1" : "0",
|
||||
);
|
||||
row.encryptedPassword = JSON.stringify(envelope);
|
||||
|
||||
await expect(
|
||||
manager.getSecretForUser(42, "target", "spice"),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("resyncHost re-snapshots direct grants and role members", async () => {
|
||||
state.hosts.set(
|
||||
42,
|
||||
baseHost({
|
||||
enableRdp: true,
|
||||
rdpUser: "rdp-admin",
|
||||
rdpPassword: "rdp-pass",
|
||||
}),
|
||||
);
|
||||
state.hosts.set(42, baseHost());
|
||||
state.logins.set(42, [
|
||||
login("spice", { username: "spice-admin", password: "spice-pass" }),
|
||||
]);
|
||||
state.accessToHost = new Map([
|
||||
[1, 42],
|
||||
[2, 42],
|
||||
@@ -334,29 +443,20 @@ describe("SharedHostSecretsManager", () => {
|
||||
]);
|
||||
|
||||
// Owner rotates the non-SSH password; resync updates those copies.
|
||||
state.hosts.set(
|
||||
42,
|
||||
baseHost({
|
||||
enableRdp: true,
|
||||
rdpUser: "rdp-admin",
|
||||
rdpPassword: "rotated",
|
||||
}),
|
||||
);
|
||||
state.logins.set(42, [
|
||||
login("spice", { username: "spice-admin", password: "rotated" }),
|
||||
]);
|
||||
await manager.resyncHost(42);
|
||||
|
||||
const secret = await manager.getSecretForUser(42, "target", "rdp");
|
||||
const secret = await manager.getSecretForUser(42, "target", "spice");
|
||||
expect(secret?.password).toBe("rotated");
|
||||
});
|
||||
|
||||
it("snapshotForRoleMember fans out from role grants", async () => {
|
||||
state.hosts.set(
|
||||
42,
|
||||
baseHost({
|
||||
enableRdp: true,
|
||||
rdpUser: "rdp-admin",
|
||||
rdpPassword: "rdp-pass",
|
||||
}),
|
||||
);
|
||||
state.hosts.set(42, baseHost());
|
||||
state.logins.set(42, [
|
||||
login("spice", { username: "spice-admin", password: "spice-pass" }),
|
||||
]);
|
||||
state.accessToHost = new Map([[2, 42]]);
|
||||
state.grants = [{ id: 2, hostId: 42, userId: null, roleId: 9 }];
|
||||
|
||||
@@ -366,7 +466,7 @@ describe("SharedHostSecretsManager", () => {
|
||||
expect(state.secretRows[0]).toMatchObject({
|
||||
hostAccessId: 2,
|
||||
targetUserId: "member-1",
|
||||
protocol: "rdp",
|
||||
protocol: "spice",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,103 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import crypto from "crypto";
|
||||
import {
|
||||
buildAuthorizationUrl,
|
||||
certificateFingerprint,
|
||||
createPkce,
|
||||
decodeJwtClaims,
|
||||
generateSshKeyPair,
|
||||
normalizeCaUrl,
|
||||
normalizeFingerprint,
|
||||
parseSshCertificate,
|
||||
} from "../../utils/step-ca-client.js";
|
||||
import {
|
||||
generateCa,
|
||||
signUserCertificate,
|
||||
} from "../../database/routes/ssh-certificate.js";
|
||||
|
||||
describe("step-ca client helpers", () => {
|
||||
it("normalizes the CA url and fingerprint the way step does", () => {
|
||||
expect(normalizeCaUrl(" https://ca.internal:9000/ ")).toBe(
|
||||
"https://ca.internal:9000",
|
||||
);
|
||||
expect(() => normalizeCaUrl("http://ca.internal")).toThrow(/https/);
|
||||
const fp = "AB:cd".repeat(16).replace(/:/g, "") + "";
|
||||
expect(normalizeFingerprint("AB:cd".repeat(16))).toBe(fp.toLowerCase());
|
||||
expect(() => normalizeFingerprint("abcd")).toThrow(/SHA-256/);
|
||||
});
|
||||
|
||||
it("fingerprints a PEM certificate by the sha256 of its DER", () => {
|
||||
const der = crypto.randomBytes(64);
|
||||
const pem = `-----BEGIN CERTIFICATE-----\n${der.toString("base64")}\n-----END CERTIFICATE-----\n`;
|
||||
expect(certificateFingerprint(pem)).toBe(
|
||||
crypto.createHash("sha256").update(der).digest("hex"),
|
||||
);
|
||||
});
|
||||
|
||||
it("builds a PKCE authorization request", () => {
|
||||
const { verifier, challenge } = createPkce();
|
||||
expect(challenge).toBe(
|
||||
crypto.createHash("sha256").update(verifier).digest("base64url"),
|
||||
);
|
||||
const url = new URL(
|
||||
buildAuthorizationUrl({
|
||||
authorizationEndpoint: "https://idp.example/auth?tenant=x",
|
||||
clientId: "cid",
|
||||
redirectUri: "https://termix.example/callback",
|
||||
state: "s",
|
||||
nonce: "n",
|
||||
codeChallenge: challenge,
|
||||
}),
|
||||
);
|
||||
expect(url.searchParams.get("tenant")).toBe("x");
|
||||
expect(url.searchParams.get("response_type")).toBe("code");
|
||||
expect(url.searchParams.get("code_challenge_method")).toBe("S256");
|
||||
expect(url.searchParams.get("scope")).toContain("openid");
|
||||
});
|
||||
|
||||
it("generates an ed25519 key whose public line a CA can certify, and reads the cert back", () => {
|
||||
const { publicKeyLine, privateKeyPem } = generateSshKeyPair();
|
||||
expect(publicKeyLine).toMatch(/^ssh-ed25519 [A-Za-z0-9+/=]+$/);
|
||||
expect(privateKeyPem).toContain("BEGIN PRIVATE KEY");
|
||||
|
||||
const ca = generateCa();
|
||||
const cert = signUserCertificate({
|
||||
userPublicKeyLine: publicKeyLine,
|
||||
caPrivateKeyPem: ca.privateKeyPem,
|
||||
caPublicKeyLine: ca.publicKeyLine,
|
||||
keyId: "alice@example",
|
||||
principals: ["alice", "ops"],
|
||||
validAfter: 1_700_000_000,
|
||||
validBefore: 1_700_057_600,
|
||||
});
|
||||
expect(cert).not.toBeNull();
|
||||
const info = parseSshCertificate(cert!);
|
||||
expect(info).toMatchObject({
|
||||
keyType: "ssh-ed25519-cert-v01@openssh.com",
|
||||
publicKeyLine,
|
||||
keyId: "alice@example",
|
||||
principals: ["alice", "ops"],
|
||||
});
|
||||
expect(info.validAfter.toISOString()).toBe("2023-11-14T22:13:20.000Z");
|
||||
expect(info.validBefore.getTime() - info.validAfter.getTime()).toBe(
|
||||
16 * 3600 * 1000,
|
||||
);
|
||||
expect(() => parseSshCertificate(publicKeyLine)).toThrow(/certificate/);
|
||||
expect(() =>
|
||||
parseSshCertificate("ssh-ed25519-cert-v01@openssh.com AAAA"),
|
||||
).toThrow(/certificate/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("decodeJwtClaims", () => {
|
||||
it("reads the payload without verifying and tolerates junk", () => {
|
||||
const payload = Buffer.from(
|
||||
JSON.stringify({ email: "a@b.c", nonce: "n1" }),
|
||||
).toString("base64url");
|
||||
expect(decodeJwtClaims(`x.${payload}.y`)).toEqual({
|
||||
email: "a@b.c",
|
||||
nonce: "n1",
|
||||
});
|
||||
expect(decodeJwtClaims("not-a-jwt")).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -8,14 +8,8 @@ vi.mock("../../utils/system-crypto.js", () => ({
|
||||
SystemCrypto: { getInstance: () => ({ getEncryptionKey }) },
|
||||
}));
|
||||
|
||||
const {
|
||||
decryptSsoConfigSecrets,
|
||||
decryptSystemSecret,
|
||||
encryptSsoConfigSecrets,
|
||||
encryptSystemSecret,
|
||||
isSystemEncrypted,
|
||||
SSO_SECRET_FIELDS,
|
||||
} = await import("../../utils/system-secret-crypto.js");
|
||||
const { decryptSystemSecret, encryptSystemSecret, isSystemEncrypted } =
|
||||
await import("../../utils/system-secret-crypto.js");
|
||||
|
||||
beforeEach(() => {
|
||||
getEncryptionKey.mockReset();
|
||||
@@ -103,55 +97,3 @@ describe("legacy compatibility", () => {
|
||||
await expect(decryptSystemSecret(sealed)).resolves.toBe("old-secret");
|
||||
});
|
||||
});
|
||||
|
||||
describe("SSO provider config", () => {
|
||||
it("seals only the secret fields", async () => {
|
||||
const sealed = await encryptSsoConfigSecrets({
|
||||
client_id: "termix",
|
||||
client_secret: "shhh",
|
||||
bindPassword: "ldap-pw",
|
||||
issuer_url: "https://idp.example",
|
||||
});
|
||||
|
||||
expect(sealed.client_id).toBe("termix");
|
||||
expect(sealed.issuer_url).toBe("https://idp.example");
|
||||
expect(isSystemEncrypted(sealed.client_secret as string)).toBe(true);
|
||||
expect(isSystemEncrypted(sealed.bindPassword as string)).toBe(true);
|
||||
});
|
||||
|
||||
it("round-trips a whole config", async () => {
|
||||
const original = {
|
||||
client_id: "termix",
|
||||
client_secret: "shhh",
|
||||
bindPassword: "ldap-pw",
|
||||
};
|
||||
|
||||
const restored = await decryptSsoConfigSecrets(
|
||||
await encryptSsoConfigSecrets(original),
|
||||
);
|
||||
|
||||
expect(restored).toEqual(original);
|
||||
});
|
||||
|
||||
it("covers both secret fields", () => {
|
||||
expect([...SSO_SECRET_FIELDS]).toEqual(["client_secret", "bindPassword"]);
|
||||
});
|
||||
|
||||
it("leaves a config without secrets untouched", async () => {
|
||||
const config = { client_id: "termix", scopes: "openid" };
|
||||
|
||||
await expect(encryptSsoConfigSecrets(config)).resolves.toEqual(config);
|
||||
await expect(decryptSsoConfigSecrets(config)).resolves.toEqual(config);
|
||||
});
|
||||
|
||||
it("does not let one unreadable secret take down the provider", async () => {
|
||||
const restored = await decryptSsoConfigSecrets({
|
||||
client_id: "termix",
|
||||
client_secret: "sysenc:v1:bad",
|
||||
});
|
||||
|
||||
// The rest of the config survives; login fails later with a clearer error.
|
||||
expect(restored.client_id).toBe("termix");
|
||||
expect(restored.client_secret).toBe("sysenc:v1:bad");
|
||||
});
|
||||
});
|
||||
@@ -12,12 +12,11 @@ describe("RawSqliteUserEncryptionMigrationStore", () => {
|
||||
}
|
||||
|
||||
it("owns legacy user encryption migration reads", () => {
|
||||
const { db, all, get } = createDb();
|
||||
const { db, all } = createDb();
|
||||
const store = new RawSqliteUserEncryptionMigrationStore(db);
|
||||
|
||||
expect(store.listHostRecords("user-1")).toEqual([{ id: 1 }]);
|
||||
expect(store.listCredentialRecords("user-1")).toEqual([{ id: 1 }]);
|
||||
expect(store.getUserRecord("user-1")).toEqual({ id: "user-1" });
|
||||
|
||||
expect(db.prepare).toHaveBeenCalledWith(
|
||||
"SELECT * FROM ssh_data WHERE user_id = ?",
|
||||
@@ -25,9 +24,7 @@ describe("RawSqliteUserEncryptionMigrationStore", () => {
|
||||
expect(db.prepare).toHaveBeenCalledWith(
|
||||
"SELECT * FROM ssh_credentials WHERE user_id = ?",
|
||||
);
|
||||
expect(db.prepare).toHaveBeenCalledWith("SELECT * FROM users WHERE id = ?");
|
||||
expect(all).toHaveBeenCalledWith("user-1");
|
||||
expect(get).toHaveBeenCalledWith("user-1");
|
||||
});
|
||||
|
||||
it("owns legacy sensitive field update statements", () => {
|
||||
@@ -39,9 +36,6 @@ describe("RawSqliteUserEncryptionMigrationStore", () => {
|
||||
key: "k",
|
||||
key_password: "kp",
|
||||
key_type: "ed25519",
|
||||
autostart_password: "ap",
|
||||
autostart_key: "ak",
|
||||
autostart_key_password: "akp",
|
||||
sudo_password: "sp",
|
||||
});
|
||||
store.updateCredentialSensitiveFields(13, {
|
||||
@@ -52,12 +46,6 @@ describe("RawSqliteUserEncryptionMigrationStore", () => {
|
||||
public_key: "pub",
|
||||
key_type: "rsa",
|
||||
});
|
||||
store.updateUserSensitiveFields("user-1", {
|
||||
totp_secret: "totp",
|
||||
totp_backup_codes: "codes",
|
||||
client_secret: "client",
|
||||
oidc_identifier: "oidc",
|
||||
});
|
||||
|
||||
expect(db.prepare).toHaveBeenCalledWith(
|
||||
expect.stringContaining("UPDATE ssh_data"),
|
||||
@@ -65,28 +53,8 @@ describe("RawSqliteUserEncryptionMigrationStore", () => {
|
||||
expect(db.prepare).toHaveBeenCalledWith(
|
||||
expect.stringContaining("UPDATE ssh_credentials"),
|
||||
);
|
||||
expect(db.prepare).toHaveBeenCalledWith(
|
||||
expect.stringContaining("UPDATE users"),
|
||||
);
|
||||
expect(run).toHaveBeenCalledWith(
|
||||
"p",
|
||||
"k",
|
||||
"kp",
|
||||
"ed25519",
|
||||
"ap",
|
||||
"ak",
|
||||
"akp",
|
||||
"sp",
|
||||
12,
|
||||
);
|
||||
expect(run).toHaveBeenCalledWith("p", "k", "kp", "ed25519", "sp", 12);
|
||||
expect(run).toHaveBeenCalledWith("p", "k", "kp", "priv", "pub", "rsa", 13);
|
||||
expect(run).toHaveBeenCalledWith(
|
||||
"totp",
|
||||
"codes",
|
||||
"client",
|
||||
"oidc",
|
||||
"user-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("owns password-reset dynamic field updates", () => {
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("dgram", () => {
|
||||
const socket = {
|
||||
once: vi.fn(),
|
||||
bind: vi.fn(),
|
||||
setBroadcast: vi.fn(),
|
||||
send: vi.fn(),
|
||||
close: vi.fn(),
|
||||
};
|
||||
return { default: { createSocket: vi.fn(() => socket) } };
|
||||
});
|
||||
|
||||
import dgram from "dgram";
|
||||
import {
|
||||
isValidMac,
|
||||
buildMagicPacket,
|
||||
sendWakeOnLan,
|
||||
} from "../../utils/wake-on-lan.js";
|
||||
|
||||
describe("isValidMac", () => {
|
||||
it("accepts colon-separated MAC addresses", () => {
|
||||
expect(isValidMac("01:23:45:67:89:AB")).toBe(true);
|
||||
expect(isValidMac("aa:bb:cc:dd:ee:ff")).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts hyphen-separated MAC addresses", () => {
|
||||
expect(isValidMac("01-23-45-67-89-AB")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects malformed MAC addresses", () => {
|
||||
expect(isValidMac("")).toBe(false);
|
||||
expect(isValidMac("01:23:45:67:89")).toBe(false);
|
||||
expect(isValidMac("01:23:45:67:89:AB:CD")).toBe(false);
|
||||
expect(isValidMac("0123456789AB")).toBe(false);
|
||||
expect(isValidMac("zz:23:45:67:89:ab")).toBe(false);
|
||||
expect(isValidMac("01:23:45:67:89:AB ")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildMagicPacket", () => {
|
||||
it("produces a 102-byte packet", () => {
|
||||
const packet = buildMagicPacket("01:23:45:67:89:AB");
|
||||
expect(packet.length).toBe(102);
|
||||
});
|
||||
|
||||
it("starts with six 0xFF bytes", () => {
|
||||
const packet = buildMagicPacket("01:23:45:67:89:AB");
|
||||
expect([...packet.subarray(0, 6)]).toEqual([
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
]);
|
||||
});
|
||||
|
||||
it("repeats the MAC bytes 16 times after the header", () => {
|
||||
const packet = buildMagicPacket("01:23:45:67:89:AB");
|
||||
const mac = Buffer.from([0x01, 0x23, 0x45, 0x67, 0x89, 0xab]);
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const offset = 6 + i * 6;
|
||||
expect([...packet.subarray(offset, offset + 6)]).toEqual([...mac]);
|
||||
}
|
||||
});
|
||||
|
||||
it("treats colon and hyphen separators identically", () => {
|
||||
const colon = buildMagicPacket("aa:bb:cc:dd:ee:ff");
|
||||
const hyphen = buildMagicPacket("aa-bb-cc-dd-ee-ff");
|
||||
expect(colon.equals(hyphen)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendWakeOnLan", () => {
|
||||
let mockSocket: ReturnType<typeof dgram.createSocket>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockSocket = (dgram.createSocket as ReturnType<typeof vi.fn>)();
|
||||
(mockSocket.bind as ReturnType<typeof vi.fn>).mockImplementation(
|
||||
(cb: () => void) => cb(),
|
||||
);
|
||||
(mockSocket.send as ReturnType<typeof vi.fn>).mockImplementation(
|
||||
(
|
||||
_buf: unknown,
|
||||
_off: unknown,
|
||||
_len: unknown,
|
||||
_port: unknown,
|
||||
_addr: unknown,
|
||||
cb: (err: null) => void,
|
||||
) => cb(null),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects on invalid MAC address", async () => {
|
||||
await expect(sendWakeOnLan("not-a-mac")).rejects.toThrow(
|
||||
"Invalid MAC address",
|
||||
);
|
||||
});
|
||||
|
||||
it("sends to 255.255.255.255 by default", async () => {
|
||||
await sendWakeOnLan("aa:bb:cc:dd:ee:ff");
|
||||
expect(mockSocket.send).toHaveBeenCalledWith(
|
||||
expect.any(Buffer),
|
||||
0,
|
||||
102,
|
||||
9,
|
||||
"255.255.255.255",
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
|
||||
it("sends to a custom broadcast address when provided", async () => {
|
||||
await sendWakeOnLan("aa:bb:cc:dd:ee:ff", "192.168.1.255");
|
||||
expect(mockSocket.send).toHaveBeenCalledWith(
|
||||
expect.any(Buffer),
|
||||
0,
|
||||
102,
|
||||
9,
|
||||
"192.168.1.255",
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { IncomingMessage } from "http";
|
||||
import { extractWebSocketToken } from "../../utils/ws-auth.js";
|
||||
import {
|
||||
extractWebSocketToken,
|
||||
isCookieOriginAllowed,
|
||||
} from "../../utils/ws-auth.js";
|
||||
|
||||
function request(headers: Record<string, string>): IncomingMessage {
|
||||
return { headers } as IncomingMessage;
|
||||
@@ -26,3 +29,58 @@ describe("extractWebSocketToken", () => {
|
||||
).toBe("cookie-token");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the jwt cookie on a socket", () => {
|
||||
it("counts when the page is this server", () => {
|
||||
expect(
|
||||
extractWebSocketToken(
|
||||
request({
|
||||
cookie: "jwt=cookie-token",
|
||||
host: "termix.example.com",
|
||||
origin: "https://termix.example.com",
|
||||
}),
|
||||
),
|
||||
).toBe("cookie-token");
|
||||
});
|
||||
|
||||
it("is ignored when another site opened the socket", () => {
|
||||
expect(
|
||||
extractWebSocketToken(
|
||||
request({
|
||||
cookie: "jwt=cookie-token",
|
||||
host: "termix.example.com",
|
||||
origin: "https://evil.example.com",
|
||||
}),
|
||||
),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("still takes an explicit token from another origin", () => {
|
||||
expect(
|
||||
extractWebSocketToken(
|
||||
request({
|
||||
cookie: "jwt=cookie-token",
|
||||
host: "termix.example.com",
|
||||
origin: "https://evil.example.com",
|
||||
"sec-websocket-protocol": "termix.jwt.protocol-token",
|
||||
}),
|
||||
),
|
||||
).toBe("protocol-token");
|
||||
});
|
||||
|
||||
it("allows the dev proxy, which rewrites Host to loopback", () => {
|
||||
expect(
|
||||
isCookieOriginAllowed(
|
||||
request({ host: "127.0.0.1:30001", origin: "http://localhost:5173" }),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("allows the desktop app, which is not a web origin", () => {
|
||||
expect(
|
||||
isCookieOriginAllowed(
|
||||
request({ host: "termix.example.com", origin: "file://" }),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user