mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-08-30 02:41:34 +00:00
release-2.5.1 (#1067)
* chore(deps): bump node from 24-slim to 26-slim in /docker in the docker-major-updates group (#1021) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore(deps): bump node in /docker in the docker-major-updates group Bumps the docker-major-updates group in /docker with 1 update: node. Updates `node` from 24-slim to 26-slim --- updated-dependencies: - dependency-name: node dependency-version: 26-slim dependency-type: direct:production dependency-group: docker-major-updates ... Signed-off-by: dependabot[bot] <support@github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-patch-updates group with 24 updates (#1023) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore(deps-dev): bump the dev-patch-updates group with 24 updates Bumps the dev-patch-updates group with 24 updates: | Package | From | To | | --- | --- | --- | | [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) | `2.5.1` | `2.5.2` | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.3` | `6.10.4` | | [@codemirror/view](https://github.com/codemirror/view) | `6.43.1` | `6.43.5` | | [@radix-ui/react-accordion](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/accordion) | `1.2.14` | `1.2.15` | | [@radix-ui/react-alert-dialog](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/alert-dialog) | `1.1.17` | `1.1.18` | | [@radix-ui/react-checkbox](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/checkbox) | `1.3.5` | `1.3.6` | | [@radix-ui/react-dialog](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/dialog) | `1.1.17` | `1.1.18` | | [@radix-ui/react-dropdown-menu](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/dropdown-menu) | `2.1.18` | `2.1.19` | | [@radix-ui/react-label](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/label) | `2.1.10` | `2.1.11` | | [@radix-ui/react-popover](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/popover) | `1.1.17` | `1.1.18` | | [@radix-ui/react-progress](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/progress) | `1.1.10` | `1.1.11` | | [@radix-ui/react-scroll-area](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/scroll-area) | `1.2.12` | `1.2.13` | | [@radix-ui/react-select](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/select) | `2.3.1` | `2.3.2` | | [@radix-ui/react-separator](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/separator) | `1.1.10` | `1.1.11` | | [@radix-ui/react-slider](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/slider) | `1.4.1` | `1.4.2` | | [@radix-ui/react-switch](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/switch) | `1.3.1` | `1.3.2` | | [@radix-ui/react-tabs](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/tabs) | `1.1.15` | `1.1.16` | | [@radix-ui/react-tooltip](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/tooltip) | `1.2.10` | `1.2.11` | | [@tailwindcss/vite](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/@tailwindcss-vite) | `4.3.1` | `4.3.2` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.2` | `6.0.3` | | [i18next](https://github.com/i18next/i18next) | `26.3.1` | `26.3.4` | | [radix-ui](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/radix-ui) | `1.6.0` | `1.6.1` | | [sharp](https://github.com/lovell/sharp) | `0.35.2` | `0.35.3` | | [tailwindcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/tailwindcss) | `4.3.1` | `4.3.2` | Updates `@biomejs/biome` from 2.5.1 to 2.5.2 - [Release notes](https://github.com/biomejs/biome/releases) - [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md) - [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.5.2/packages/@biomejs/biome) Updates `@codemirror/commands` from 6.10.3 to 6.10.4 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@codemirror/view` from 6.43.1 to 6.43.5 - [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/view/commits) Updates `@radix-ui/react-accordion` from 1.2.14 to 1.2.15 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/accordion/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/accordion) Updates `@radix-ui/react-alert-dialog` from 1.1.17 to 1.1.18 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/alert-dialog/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/alert-dialog) Updates `@radix-ui/react-checkbox` from 1.3.5 to 1.3.6 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/checkbox/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/checkbox) Updates `@radix-ui/react-dialog` from 1.1.17 to 1.1.18 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/dialog/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/dialog) Updates `@radix-ui/react-dropdown-menu` from 2.1.18 to 2.1.19 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/dropdown-menu/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/dropdown-menu) Updates `@radix-ui/react-label` from 2.1.10 to 2.1.11 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/label/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/label) Updates `@radix-ui/react-popover` from 1.1.17 to 1.1.18 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/popover/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/popover) Updates `@radix-ui/react-progress` from 1.1.10 to 1.1.11 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/progress/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/progress) Updates `@radix-ui/react-scroll-area` from 1.2.12 to 1.2.13 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/scroll-area/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/scroll-area) Updates `@radix-ui/react-select` from 2.3.1 to 2.3.2 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/select/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/select) Updates `@radix-ui/react-separator` from 1.1.10 to 1.1.11 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/separator/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/separator) Updates `@radix-ui/react-slider` from 1.4.1 to 1.4.2 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/slider/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/slider) Updates `@radix-ui/react-switch` from 1.3.1 to 1.3.2 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/switch/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/switch) Updates `@radix-ui/react-tabs` from 1.1.15 to 1.1.16 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/tabs/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/tabs) Updates `@radix-ui/react-tooltip` from 1.2.10 to 1.2.11 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/tooltip/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/tooltip) Updates `@tailwindcss/vite` from 4.3.1 to 4.3.2 - [Release notes](https://github.com/tailwindlabs/tailwindcss/releases) - [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md) - [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.2/packages/@tailwindcss-vite) Updates `@vitejs/plugin-react` from 6.0.2 to 6.0.3 - [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.0.3/packages/plugin-react) Updates `i18next` from 26.3.1 to 26.3.4 - [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.3.1...v26.3.4) Updates `radix-ui` from 1.6.0 to 1.6.1 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/radix-ui/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/radix-ui) Updates `sharp` from 0.35.2 to 0.35.3 - [Release notes](https://github.com/lovell/sharp/releases) - [Commits](https://github.com/lovell/sharp/compare/v0.35.2...v0.35.3) Updates `tailwindcss` from 4.3.1 to 4.3.2 - [Release notes](https://github.com/tailwindlabs/tailwindcss/releases) - [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md) - [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.2/packages/tailwindcss) --- updated-dependencies: - dependency-name: "@biomejs/biome" dependency-version: 2.5.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@codemirror/commands" dependency-version: 6.10.4 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@codemirror/view" dependency-version: 6.43.5 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-accordion" dependency-version: 1.2.15 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-alert-dialog" dependency-version: 1.1.18 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-checkbox" dependency-version: 1.3.6 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-dialog" dependency-version: 1.1.18 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-dropdown-menu" dependency-version: 2.1.19 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-label" dependency-version: 2.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-popover" dependency-version: 1.1.18 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-progress" dependency-version: 1.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-scroll-area" dependency-version: 1.2.13 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-select" dependency-version: 2.3.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-separator" dependency-version: 1.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-slider" dependency-version: 1.4.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-switch" dependency-version: 1.3.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-tabs" dependency-version: 1.1.16 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-tooltip" dependency-version: 1.2.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@tailwindcss/vite" dependency-version: 4.3.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.0.3 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: i18next dependency-version: 26.3.4 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: radix-ui dependency-version: 1.6.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: sharp dependency-version: 0.35.3 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: tailwindcss dependency-version: 4.3.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump the prod-patch-updates group with 2 updates (#1025) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore(deps): bump the prod-patch-updates group with 2 updates Bumps the prod-patch-updates group with 2 updates: [axios](https://github.com/axios/axios) and [nanoid](https://github.com/ai/nanoid). Updates `axios` from 1.18.0 to 1.18.1 - [Release notes](https://github.com/axios/axios/releases) - [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) - [Commits](https://github.com/axios/axios/compare/v1.18.0...v1.18.1) Updates `nanoid` from 5.1.15 to 5.1.16 - [Release notes](https://github.com/ai/nanoid/releases) - [Changelog](https://github.com/ai/nanoid/blob/main/CHANGELOG.md) - [Commits](https://github.com/ai/nanoid/compare/5.1.15...5.1.16) --- updated-dependencies: - dependency-name: axios dependency-version: 1.18.1 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: nanoid dependency-version: 5.1.16 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump the prod-minor-updates group with 3 updates (#1026) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore(deps): bump the prod-minor-updates group with 3 updates Bumps the prod-minor-updates group with 3 updates: [js-yaml](https://github.com/nodeca/js-yaml), [motion](https://github.com/motiondivision/motion) and [undici](https://github.com/nodejs/undici). Updates `js-yaml` from 5.0.0 to 5.2.1 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.0.0...5.2.1) Updates `motion` from 12.40.0 to 12.42.2 - [Changelog](https://github.com/motiondivision/motion/blob/main/CHANGELOG.md) - [Commits](https://github.com/motiondivision/motion/compare/v12.40.0...v12.42.2) Updates `undici` from 8.5.0 to 8.7.0 - [Release notes](https://github.com/nodejs/undici/releases) - [Commits](https://github.com/nodejs/undici/compare/v8.5.0...v8.7.0) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 5.2.1 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: motion dependency-version: 12.42.2 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: undici dependency-version: 8.7.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump electron from 42.4.1 to 43.0.0 in the major-updates group (#1027) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore(deps-dev): bump electron in the major-updates group Bumps the major-updates group with 1 update: [electron](https://github.com/electron/electron). Updates `electron` from 42.4.1 to 43.0.0 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v42.4.1...v43.0.0) --- updated-dependencies: - dependency-name: electron dependency-version: 43.0.0 dependency-type: direct:development update-type: version-update:semver-major dependency-group: major-updates ... Signed-off-by: dependabot[bot] <support@github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Fix MC syntax highlighting artifacts (#996) * Filter dashboard status hosts (#997) * Persist dashboard service link changes (#999) * Fix snippet text overflow (#1000) * Persist remote desktop credential auth (#1001) * Guard language switching failures (#1002) * Resolve tunnel source credentials (#1003) * Support Vault auth for monitors (#1004) * Fix Windows file delete command (#1005) * Fix release artifact checkout ref (#1006) * Fix command palette escape in fullscreen (#1008) * Fix alerts and audit log data normalization (#1010) * Fix macOS VNC protocol negotiation (#1012) * Fix port knocking before SSH connect (#1013) * Allow Escape to close link confirmation (#1014) * Prevent Electron modifier wheel zoom (#1016) * Fix credential auth optional password (#1009) * Retry transient terminal DNS lookups (#1011) * Retry transient terminal DNS lookups * Apply DNS retry to SSH entry points * Fix OIDC redirect forwarded port handling (#1007) * Preserve recent open tabs on startup (#1015) * Fix fish prompt OSC highlighting (#998) * Fix terminal font selection (#1018) * fix: font legibility (#1019) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * fix: font legibility Text was entirely unreadable in places for me. Especially with themes like Catppuccin. The muted-foreground text and the tags too similiar to the background. --------- Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: russell <git@0896c69e.com> * fix(file-manager): chunked uploads fail with 'Expected multipart/form-data request' (#1020) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * fix(file-manager): use postForm for chunked uploads so multipart content-type is sent The fileManagerApi axios instance defaults to Content-Type: application/json. Axios 1.x's default transformRequest converts a FormData body to JSON whenever the request content type is application/json, so every chunk POSTed to /ssh/uploadFileChunk arrived as a JSON body like {"chunk":{}} and the backend rejected it with 400 'Expected multipart/form-data request'. This breaks all uploads of files larger than the 1.5 GiB chunking threshold. The non-chunked path already uses postForm for /ssh/uploadFileStream; use it for the chunk path too so axios keeps the FormData intact and the browser sets the multipart boundary. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * feat: implement OIDC back-channel logout support with session management (#1028) * feat: implement OIDC back-channel logout support with session management * Fix OIDC back-channel logout handling * Require logout token replay identifiers --------- Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> * Add API key host enrollment endpoint (#1029) * Fix tmux detection for non-POSIX shells (#1030) * Fix OPKSSH js-yaml ESM import (#1031) * Fix Android Vietnamese IME input (#1032) * Fix Firefox RDP clipboard paste (#1033) * Fix Proxmox discovery over HTTPS (#1041) * Fix external editor actions in file preview (#1042) * Allow pinned hosts with name sorting (#1043) * Fix Firefox desktop OIDC callback (#1044) * feat(session): add recording and replay (#1049) * Fix status checks through jump hosts (#1045) * Add terminal font size shortcuts (#1047) * feat: add Open File Manager to tab right-click menu (#1051) Co-authored-by: SankeerthNara <sankeerthnara@gmail.com> * perf: frontend request cache, poll pause, and code-split shell (#1052) Host/status caching, shell code-split, SSH pool waits, host-metrics concurrency, background-tab idle, per-host status subscriptions, homepage poll quieting, and virtualized host sidebar + file manager lists. * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * feat: save quick connect sessions as hosts (#1055) * fix: restore sudo password autofill settings (#1056) * fix: preserve file editor position on save (#1057) * fix: sync cloud preference storage mode (#1058) * fix: render RDP sessions at native pixel density (#1059) * fix: restore database import in embedded desktop mode (#1060) * Update Auto-complete.tsx (#1061) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore: donation bar reporting wrong result * feat: add Open File Manager to tab right-click menu (#1046) * Revert "feat: add Open File Manager to tab right-click menu (#1046)" (#1050) This reverts commit0712fdd731. * Remove donation badge from README Removed donation badge from README. * Delete .github/workflows/donation-goal.yml * Update Auto-complete.tsx --------- Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> * feat(auth): opt-in OIDC DEK unlock for API-key requests (ALLOW_APIKEY_DATA_UNLOCK) (#1064) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore: donation bar reporting wrong result * feat: add Open File Manager to tab right-click menu (#1046) * Revert "feat: add Open File Manager to tab right-click menu (#1046)" (#1050) This reverts commit0712fdd731. * Remove donation badge from README Removed donation badge from README. * Delete .github/workflows/donation-goal.yml * feat(auth): opt-in OIDC DEK unlock for API-key requests API keys authenticate but cannot touch the encrypted credential/host store ('User data not unlocked') unless the user has a live interactive session, making them unusable for headless automation. For OIDC users the DEK is server-derivable (deriveOIDCSystemKey), so handleApiKeyAuth can unlock it without a password. Gated behind ALLOW_APIKEY_DATA_UNLOCK (default off) because enabling it widens the blast radius of a leaked API key. OIDC-only; password users are untouched. Refs #1063 --------- Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: Sankeerth Nara <sankeerthnara@gmail.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> * chore: package lock sync * Add Proxmox guest auto sync (#1053) * draft: database layer refactor (#1054) * feat(sshid) - sshid.io equivalent for termix (#919) * feat(ssh-id): database schema, migrations and field encryption Adds ssh_identities, ssh_identity_keys and ssh_identity_ca tables (public keys stored plaintext for the unauthenticated resolver; CA private key registered for per-user field encryption), with UNIQUE(user_id), an index on ssh_identity_keys(identity_id), and idempotent CREATE TABLE migrations. * feat(ssh-id): backend API — resolver, key management, CA and certificates Mounts /sshid (nginx route added). Public text/plain authorized_keys resolver (+ exact /:algo filter, HTML viewer) and CA public-key endpoint; no-store + noindex headers on every resolver response including early 404s. Authenticated management: claim/rename/delete handle, add/import/generate/enable/delete keys, and a per-user CA (create/rotate/delete) with pure-Node OpenSSH certificate issuance. Audit logging on all mutations; UNIQUE races map to a precise 409. Unit tests for key parsing and certificate signing (ssh-keygen-validated). * feat(ssh-id): frontend panel, API client and i18n SSH ID panel wired into the app rail and AppShell: claim handle, resolver URL + curl one-liner, key list, generate, paste/import, CA enable/rotate/remove with server trust command, and per-key certificate issuance. API client re-exported through main-axios.ts; all strings i18n'd. * style(ssh-id): align panel and resolver page with Termix theme - Rebuild the SSH ID sidebar panel with the theme's square components (SectionCard / SettingRow / FakeSwitch) instead of rounded ad-hoc cards; use accent-brand and destructive tokens rather than raw red/green. - Fix panel scrolling: move overflow to a block scroll container so the cards keep their natural height instead of being clipped. - Restyle the public resolver HTML page (/sshid/u/:handle) to the Termix dark theme: square corners, #18181b/#303032 palette, #f59145 accent, uppercase section labels. - Tidy copy: 'Save To Credentials' label, drop the redundant generate intro, and correct the generate tooltip (the key is stored when saving to vault). * feat: rename to Termix ID, improve UI, backend inconsistencies, and general bug fixes --------- Co-authored-by: LukeGus <bugattiguy527@gmail.com> * ci(deps): bump actions/checkout from 6 to 7 in the github-actions group (#922) Bumps the github-actions group with 1 update: [actions/checkout](https://github.com/actions/checkout). Updates `actions/checkout` from 6 to 7 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '7' 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 11 updates (#923) Bumps the dev-patch-updates group with 11 updates: | Package | From | To | | --- | --- | --- | | [@codemirror/search](https://github.com/codemirror/search) | `6.7.0` | `6.7.1` | | [@codemirror/view](https://github.com/codemirror/view) | `6.43.0` | `6.43.1` | | [@tailwindcss/vite](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/@tailwindcss-vite) | `4.3.0` | `4.3.1` | | [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.1.8` | `4.1.9` | | [@vitest/ui](https://github.com/vitest-dev/vitest/tree/HEAD/packages/ui) | `4.1.8` | `4.1.9` | | [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.2` | `0.5.3` | | [lint-staged](https://github.com/lint-staged/lint-staged) | `17.0.7` | `17.0.8` | | [prettier](https://github.com/prettier/prettier) | `3.8.3` | `3.8.4` | | [sharp](https://github.com/lovell/sharp) | `0.35.1` | `0.35.2` | | [tailwindcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/tailwindcss) | `4.3.0` | `4.3.1` | | [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.1.8` | `4.1.9` | Updates `@codemirror/search` from 6.7.0 to 6.7.1 - [Changelog](https://github.com/codemirror/search/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/search/commits) Updates `@codemirror/view` from 6.43.0 to 6.43.1 - [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/view/commits) Updates `@tailwindcss/vite` from 4.3.0 to 4.3.1 - [Release notes](https://github.com/tailwindlabs/tailwindcss/releases) - [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md) - [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.1/packages/@tailwindcss-vite) Updates `@vitest/coverage-v8` from 4.1.8 to 4.1.9 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/coverage-v8) Updates `@vitest/ui` from 4.1.8 to 4.1.9 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/ui) Updates `eslint-plugin-react-refresh` from 0.5.2 to 0.5.3 - [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.2...v0.5.3) Updates `lint-staged` from 17.0.7 to 17.0.8 - [Release notes](https://github.com/lint-staged/lint-staged/releases) - [Changelog](https://github.com/lint-staged/lint-staged/blob/main/CHANGELOG.md) - [Commits](https://github.com/lint-staged/lint-staged/compare/v17.0.7...v17.0.8) Updates `prettier` from 3.8.3 to 3.8.4 - [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.8.3...3.8.4) Updates `sharp` from 0.35.1 to 0.35.2 - [Release notes](https://github.com/lovell/sharp/releases) - [Commits](https://github.com/lovell/sharp/compare/v0.35.1...v0.35.2) Updates `tailwindcss` from 4.3.0 to 4.3.1 - [Release notes](https://github.com/tailwindlabs/tailwindcss/releases) - [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md) - [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.1/packages/tailwindcss) Updates `vitest` from 4.1.8 to 4.1.9 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/vitest) --- updated-dependencies: - dependency-name: "@codemirror/search" dependency-version: 6.7.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@codemirror/view" dependency-version: 6.43.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@tailwindcss/vite" dependency-version: 4.3.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitest/coverage-v8" dependency-version: 4.1.9 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitest/ui" dependency-version: 4.1.9 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.3 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: lint-staged dependency-version: 17.0.8 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: prettier dependency-version: 3.8.4 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: sharp dependency-version: 0.35.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: tailwindcss dependency-version: 4.3.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: vitest dependency-version: 4.1.9 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 nanoid in the prod-patch-updates group (#925) Bumps the prod-patch-updates group with 1 update: [nanoid](https://github.com/ai/nanoid). Updates `nanoid` from 5.1.11 to 5.1.15 - [Release notes](https://github.com/ai/nanoid/releases) - [Changelog](https://github.com/ai/nanoid/blob/main/CHANGELOG.md) - [Commits](https://github.com/ai/nanoid/compare/5.1.11...5.1.15) --- updated-dependencies: - dependency-name: nanoid dependency-version: 5.1.15 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> * chore(deps): bump the major-updates group with 5 updates (#926) Bumps the major-updates group with 5 updates: | Package | From | To | | --- | --- | --- | | [js-yaml](https://github.com/nodeca/js-yaml) | `4.2.0` | `5.0.0` | | [@eslint/js](https://github.com/eslint/eslint/tree/HEAD/packages/js) | `9.39.4` | `10.0.1` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `25.9.2` | `26.0.0` | | [concurrently](https://github.com/open-cli-tools/concurrently) | `9.2.1` | `10.0.3` | | [eslint](https://github.com/eslint/eslint) | `9.39.4` | `10.5.0` | Updates `js-yaml` from 4.2.0 to 5.0.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/4.2.0...5.0.0) Updates `@eslint/js` from 9.39.4 to 10.0.1 - [Release notes](https://github.com/eslint/eslint/releases) - [Commits](https://github.com/eslint/eslint/commits/v10.0.1/packages/js) Updates `@types/node` from 25.9.2 to 26.0.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `concurrently` from 9.2.1 to 10.0.3 - [Release notes](https://github.com/open-cli-tools/concurrently/releases) - [Commits](https://github.com/open-cli-tools/concurrently/compare/v9.2.1...v10.0.3) Updates `eslint` from 9.39.4 to 10.5.0 - [Release notes](https://github.com/eslint/eslint/releases) - [Commits](https://github.com/eslint/eslint/compare/v9.39.4...v10.5.0) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 5.0.0 dependency-type: direct:production update-type: version-update:semver-major dependency-group: major-updates - dependency-name: "@eslint/js" dependency-version: 10.0.1 dependency-type: direct:development update-type: version-update:semver-major dependency-group: major-updates - dependency-name: "@types/node" dependency-version: 26.0.0 dependency-type: direct:development update-type: version-update:semver-major dependency-group: major-updates - dependency-name: concurrently dependency-version: 10.0.3 dependency-type: direct:development update-type: version-update:semver-major dependency-group: major-updates - dependency-name: eslint dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-major dependency-group: major-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * feat(ssh): add HashiCorp Vault SSH signer authentication * fix: small fixes to vault feature to align with Termix codebase * chore: add view docs links for vault/termix id * fix: file upload fails with 400 and missing schema migrations on upgrade (#929) Two bugs introduced in v2.4.1: 1. uploadFileStream uses fileManagerApi.post() which triggers axios's transformRequest to JSON-serialize the FormData because the instance default Content-Type is application/json. Change to postForm() which sets Content-Type: multipart/form-data so the browser XHR sends the correct multipart body with boundary. 2. Two schema items added to schema.ts were not included in migrateSchema() in db/index.ts, causing 500 errors on existing installations upgrading from v2.4.0: - user_preferences.status_color_scheme (no such column) - dashboard_service_links table (no such table) Fixes #928 Co-authored-by: sash <sash@fominykh.io> * fix: support PuTTY PPK ssh keys (#930) * fix: chunk large file manager uploads (#932) * fix: route dashboard hosts by protocol (#934) * fix: resolve tunnel endpoints reliably (#935) * Fix Electron OIDC browser auth failures (#936) * Allow RDP connections without stored credentials (#937) * Sync role credential shares for OIDC users (#938) * Fix terminal link dialog layering (#940) * Confirm large files before opening editor (#942) * Confirm closing active host connections (#943) * Preserve file path case in file manager UI (#941) * fix: preserve unicode guacamole tokens (#933) * Persist VNC authentication settings (#944) * Fix Guacamole websocket base path (#946) * Promote file manager terminals to tabs (#939) * Guard Guacamole disconnect during startup (#945) * chore: increment ver * feat: bitwarden ssh agent integration * feat: serial connections support * fix: various small bug fixes * feat: open all sessions in a folder and terminal custom theme color support * feat: cross host file manager clipboard and several small bug fixes * feat: tailscale/wireguard support and added a new status state for when backend is checking status * feat: grafana like server stats history, new alert system, ntfy/webhook support * feat: new grid and widget based homepage function * feat: new donate button in dashboard * fix: alert ui incorrectly using termix css and fixed issue with alert system not loading * chore: start database layer refactor * docs: plan database layer refactor * docs: audit database layer refactor phase zero * chore: add database runtime adapter skeleton * chore: add settings repository skeleton * chore: add user session repository skeleton * chore: add host credential repository skeleton * chore: add field encryption boundary * chore: migrate settings route slice * chore: migrate user settings routes * chore: migrate host metrics settings routes * chore: migrate acme settings route * chore: migrate terminal settings route * chore: migrate tailscale settings read * chore: migrate guacamole settings reads * chore: migrate session timeout settings reads * chore: migrate auth route settings reads * chore: migrate host metrics settings reads * chore: migrate startup settings reads * chore: migrate user settings cleanup * chore: migrate password reset settings * chore: migrate oidc legacy settings read * chore: migrate user route settings slice * chore: migrate oidc state settings * chore: migrate user login settings reads * chore: migrate user crypto settings * chore: consolidate startup settings defaults * chore: consolidate database settings import export * chore: migrate core session auth paths * chore: migrate remaining session auth paths * chore: migrate admin user routes * chore: migrate user route admin checks * chore: migrate user lifecycle routes * chore: migrate auth user lookups * chore: migrate oidc user routes * chore: migrate api key repository paths * docs: add database gray rollout guide * chore: migrate trusted device paths * chore: migrate user session route user lookups * chore: add database repository rollout guard * chore: expose repository rollout status * chore: warn on repository rollout misconfiguration * chore: migrate remaining user lookup helpers * chore: migrate ssh user lookups * chore: migrate user settings admin lookups * chore: migrate acme ssl user lookups * chore: migrate audit log admin checks * chore: migrate oidc account user updates * chore: migrate password reset user updates * chore: migrate user deletion core records * chore: migrate snippet audit user lookups * chore: migrate ldap user sync paths * chore: migrate totp user updates * chore: migrate rbac user checks * chore: migrate rbac role paths * chore: migrate permission role lookups * chore: migrate rbac access list reads * chore: migrate shared rbac reads * chore: migrate rbac access writes * chore: migrate permission host access * chore: migrate role host access lookup * chore: migrate snippet access lookup * chore: migrate shared credential access lookups * chore: migrate host access cleanup writes * chore: migrate host list access checks * chore: migrate host access cleanup routes * chore: migrate shared credential role lookups * chore: migrate user role cleanup * chore: migrate admin role sync * chore: migrate ldap role sync * chore: migrate user role assignment * chore: migrate sso provider access * chore: migrate audit log access * chore: migrate user preference access * chore: migrate open tab access * chore: migrate dismissed alert access * chore: migrate homepage layout access * chore: migrate network topology access * chore: migrate dashboard service link access * chore: migrate command history access * chore: migrate recent activity cleanup * chore: migrate ssh credential usage access * chore: migrate transfer recent access * chore: migrate file manager bookmark access * chore: migrate c2s tunnel preset access * chore: migrate homepage item access * chore: migrate session recording access * chore: migrate tmux session tag access * chore: migrate opkssh token access * chore: migrate vault token access * chore: migrate vault profile access * chore: migrate host metrics preference access * chore: migrate host health access * chore: migrate host metrics history access * chore: migrate alert persistence access * chore: route alert host lookup through repository * chore: migrate user data export reads * chore: route host metrics stats sync through repository * chore: migrate host folder persistence * chore: migrate host resolution reads * chore: route jump host resolution reads * chore: route docker console jump host reads * chore: route docker ssh resolution reads * chore: route proxmox discovery resolution reads * chore: route file manager activity host reads * chore: route host metrics resolution reads * chore: route ssh auth credential reads * chore: route tunnel endpoint credential reads * chore: route credential deployment resolution reads * chore: route command history host flag reads * chore: route snippet execution resolution reads * chore: route terminal host resolution reads * chore: route vault oidc host resolution reads * chore: route wake on lan host reads * chore: route internal host list reads * chore: route host key verification persistence * chore: route credential read paths * chore: route credential host usage reads * chore: route credential folder rename * chore: route host owner access checks * chore: route shared credential source reads * chore: route user host credential cleanup * chore: route credential delete reads * chore: route credential update reads * chore: route host credential reads * chore: route host read paths * chore: route host projection reads * chore: route host list reads * chore: route snippet read paths * chore: route snippet folder writes * chore: route snippet crud paths * chore: route snippet bulk import * chore: route rbac ownership reads * chore: route user count reads * chore: route cleanup snippets folders * chore: route shared credential persistence * chore: route dashboard activity * chore: route guacamole host reads * chore: route host bulk lookups * chore: remove unlock-only simple db ops * chore: route host autostart persistence * chore: route ldap provisioning through users * chore: route credential encrypted writes * chore: route host encrypted writes * chore: route bulk host encrypted writes * chore: route termix id credentials * chore: route termix id ca persistence * chore: route termix identity persistence * chore: route credential system migration * chore: isolate user encryption migration storage * chore: remove legacy simple db ops * chore: isolate legacy sqlite migration copy * chore: route database settings import export * chore: route database host credential export * chore: route database host credential import * chore: route database file-manager import export * chore: route database alert usage import export * chore: route database user checks * chore: isolate auth lazy migration storage * chore: route explicit database saves * chore: initialize database save boundary * chore: route migration snapshot saves * chore: isolate sqlite import constraints * chore: route import sqlite boundary * chore: route user encryption migration store * chore: centralize current repository runtime * chore: route more current repositories * chore: route activity repository runtimes * chore: route token repository runtimes * chore: route health repository runtimes * chore: route identity repository runtimes * chore: route rbac repository runtime * chore: centralize current sqlite runtime access * chore: route user deletion key cleanup * chore: route user deletion vault cleanup * chore: route user deletion homepage cleanup * chore: route user deletion health cleanup * chore: route user deletion alert cleanup * chore: route user deletion identity cleanup * chore: add database layer preupgrade backup * Fix database repository type errors * fix: complete post-merge compile fixes for database refactor Restore missing DatabaseSaveTrigger/getDb imports, session log format fallback, OIDC provider resolution, guacamole recording insert, and passwordFallbackOnly typing after merging current dev. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: DivByZero <mr.oplus@yahoo.fr> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: devdanetra <46488477+devdanetra@users.noreply.github.com> Co-authored-by: Aleksandr Fominykh <neoformalex@users.noreply.github.com> Co-authored-by: sash <sash@fominykh.io> * refactor(db): collapse repository rollout scaffolding into single factory Repositories are now the only data path. Replaces the 41 current-*-repository wrapper files, the DATABASE_LAYER_REPOSITORY_ROLLOUT flag/alias map and the unused database/runtime adapter with repositories/factory.ts, a plain DatabaseContext type and an in-memory TestSqliteDatabase test harness. * refactor(db): route remaining raw DB access through repositories proxmox, session-log, oidc-utils, webauthn and guacamole recording now use repositories (new WebauthnCredentialRepository; SsoProviderRepository listEnabled; HostRepository findDecryptedByIdAs/listProxmoxEnabled). Remaining raw access: db boot code, simple-db-ops and docker.ts, which are removed/restructured in later phases. * feat(crypto): add UserKeyManager with system-wrapped per-user DEKs New utils/user-keys.ts: one random 32-byte DEK per user, wrapped AES-256-GCM under an HKDF key derived from the system ENCRYPTION_KEY (per-user info string + AAD binding, versioned v3 wrap format stored in settings). Synchronous unwrap-on-demand with a 15-minute cache so the existing DataCrypto facade keeps its sync call sites. Not wired up yet. * feat(crypto): boot-time DEK migration to system-wrapped v3 format utils/crypto-migration/dek-migration.ts carries the legacy unwrap paths (PBKDF2 password KEK, OIDC/WebAuthn system keys, hardcoded-default fallback) and migrates every server-unwrappable DEK to the v3 wrap at startup. Password-wrapped DEKs migrate at next login or from a live session via adoptRecoveredDEK. Legacy rows are kept for now; cleanup flips on once the new path is authoritative. * refactor(crypto): make system-wrapped DEKs the authoritative key path DataCrypto and AuthManager now read keys through UserKeyManager: DEKs are always unwrappable server-side, so the in-memory unlock session, DEK-in-JWT wrapping, session-expiry data locks and ALLOW_APIKEY_DATA_UNLOCK are gone. utils/user-crypto.ts is deleted; boot migration now cleans legacy wraps. A one-release shim adopts DEKs from legacy dataKeyWrap tokens so active password users migrate without re-login. Password login migrates legacy password-wrapped DEKs via migratePasswordUserAtLogin. * refactor(crypto): remove pending share queue and credential sharing key With server-unwrappable DEKs both sides of a share are always available, so the needsReEncryption queue, CREDENTIAL_SHARING_KEY and the system_* shadow columns on ssh_credentials are gone. A one-time boot cleanup re-creates legacy pending share copies where possible (dropping unresolvable ones with a warning) and drops the legacy columns. * feat(auth): non-destructive password resets and admin reset endpoint Password resets no longer destroy user data: the DEK is system-wrapped, so forgot-password and admin resets are just a hash update plus session revoke. The wipe branch survives only for accounts that never logged in since the encryption upgrade and now requires explicit confirmDataWipe (surfaced as a 409 DATA_WIPE_REQUIRED; the reset UI asks for confirmation). Adds POST /users/admin/reset-password and removes the dead re-encryption paths. * refactor(ssh): consolidate four jump-host chain copies into one module terminal, host-metrics and docker now use ssh/jump-host-chain.ts (already shared by file-manager, tmux-monitor and docker-console); docker's inline copy also drops its raw SimpleDBOps host/credential lookups in favor of repositories. * refactor(ssh): single shared createConnectionLog helper file-manager-log.ts becomes ssh/connection-log.ts; the copies in docker.ts and host-metrics-helpers.ts are gone. * refactor(ssh): split docker module into layered directory ssh/docker/{index,routes,session-manager,container-routes,console}.ts: server boot and wiring in index, HTTP handlers in routes, SSH session registry and command execution in session-manager. Code motion only; port 30007/30009 and endpoints unchanged. Swagger now scans ssh subdirectories. * refactor(ssh): split tunnel module into layered directory ssh/tunnel/{index,routes,manager}.ts: server boot in index, HTTP handlers in routes, tunnel state and engine (connect/retry/autostart) in manager. Code motion only; port 30003 and endpoints unchanged. * refactor(backend): reorganize top-level layout - ssh/ renamed to hosts/ (it covers SSH, RDP, VNC, Telnet, Docker, metrics) - serial/serial.ts and guacamole/ moved inside hosts/ - dashboard.ts and homepage.ts moved to services/ - swagger.ts moved to utils/ with adjusted scan globs Import paths and the generate:openapi script updated; ports and endpoints unchanged. * refactor(tests): move backend tests into src/backend/tests mirror tree Backend *.test.ts files (and the test-support harness) no longer sit next to source files; they live under src/backend/tests/ mirroring the source layout. Imports rewritten accordingly; CLAUDE.md convention updated. * refactor(hosts): group host modules into per-feature directories file-manager/, metrics/ (incl. widgets, managers, alert-engine), terminal/, tmux/ and tunnel/ each own their files; docker/ gains container-runtime. Genuinely shared helpers (jump-host chain, host resolver, connection pool, opkssh, vault, serial) stay at hosts/ root. Pure file moves with import path updates; mirrored test paths follow. * refactor(backend): final cleanup pass - re-register WebAuthn passkey routes (registration was dropped in the #1054 merge, breaking passkey login) and document all six endpoints - delete utils/simple-db-ops.ts (last caller migrated to DataCrypto) - starter: use the typed serverReady export, collapse the four-way version lookup to env then package.json candidates - add OpenAPI JSDoc to c2s-tunnel-presets endpoints - strip block-divider comment banners * feat: remove legacy "data_unlocked" field * feat: refactor rbac/sharing to support new permissions and auth types * feat: refactor rbac/sharing to support new permissions and auth types * feat: add "id" to user profile hide list * chore: root cleanup * feat: add more donation references and a 30-day donation reminder * chore: update readme * feat: automate beta tests * feat: add links to milestones * fix: hoist github/google SSO defaults to module scope (#1065) * fix(ssh-tools): allow clipboard paste in key recording field (#1066) The broadcast key-recording input was marked readOnly, which makes browsers block paste entirely (no context-menu Paste, Ctrl+V does nothing). handleKeyDown also called preventDefault() unconditionally, swallowing the Ctrl+V shortcut before a paste event could even fire. Let Ctrl/Cmd+V pass through in handleKeyDown, drop readOnly, and add an onPaste handler that reads the clipboard text and broadcasts it to the selected terminals like any other captured keystroke. Signed-off-by: emreumar <emreumar@users.noreply.github.com> Co-authored-by: emreumar <emreumar@users.noreply.github.com> * chore: write release notes * chore: update release notes * chore: update readmes * chore: add crypto only reminder in en.json * fix: macOS and cask errors on release workflow * chore: sync Crowdin translations for 2.5.1 --------- Signed-off-by: dependabot[bot] <support@github.com> Signed-off-by: emreumar <emreumar@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> Co-authored-by: Russell Poovey <09.our_seekers@icloud.com> Co-authored-by: russell <git@0896c69e.com> Co-authored-by: Subedi Bibek <77529535+questbibek@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Alexander Elsner <101340634+Bensonheimer992@users.noreply.github.com> Co-authored-by: SankeerthNara <sankeerthnara@gmail.com> Co-authored-by: Stephan Groth <96803994+Kalvalax@users.noreply.github.com> Co-authored-by: DivByZero <mr.oplus@yahoo.fr> Co-authored-by: devdanetra <46488477+devdanetra@users.noreply.github.com> Co-authored-by: Aleksandr Fominykh <neoformalex@users.noreply.github.com> Co-authored-by: sash <sash@fominykh.io> Co-authored-by: lhojun <ldgs3324@gmail.com> Co-authored-by: Yunus Emre Umar <77045015+emre155@users.noreply.github.com> Co-authored-by: emreumar <emreumar@users.noreply.github.com>
This commit is contained in:
co-authored by
emreumar
dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
ZacharyZcR
Russell Poovey
russell
Subedi Bibek
Claude Fable 5
Alexander Elsner
SankeerthNara
Stephan Groth
DivByZero
devdanetra
Aleksandr Fominykh
sash
lhojun
Yunus Emre Umar
parent
fba645e92e
commit
ddbdd5c437
@@ -0,0 +1,379 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { AlertRepository } from "../../../database/repositories/alert-repository.js";
|
||||
|
||||
describe("AlertRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<AlertRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT,
|
||||
ip TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE alert_rules (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER,
|
||||
name TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
trigger_type TEXT NOT NULL,
|
||||
threshold_value REAL,
|
||||
threshold_duration_seconds INTEGER,
|
||||
cooldown_minutes INTEGER NOT NULL DEFAULT 15,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE notification_channels (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
config TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE alert_rule_channels (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
rule_id INTEGER NOT NULL,
|
||||
channel_id INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE alert_firings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
rule_id INTEGER NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
host_name TEXT NOT NULL,
|
||||
fired_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
resolved_at TEXT,
|
||||
value REAL,
|
||||
message TEXT NOT NULL,
|
||||
severity TEXT NOT NULL DEFAULT 'warning',
|
||||
acknowledged INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO ssh_data (id, user_id, name, ip)
|
||||
VALUES (1, 'user-1', 'alpha', '127.0.0.1');
|
||||
`);
|
||||
|
||||
return new AlertRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("manages notification channels", async () => {
|
||||
let writes = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writes += 1;
|
||||
});
|
||||
|
||||
const created = await repo.createNotificationChannel({
|
||||
userId: "user-1",
|
||||
name: "Ops",
|
||||
type: "webhook",
|
||||
config: '{"url":"https://example.test"}',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
expect(created).toMatchObject({
|
||||
user_id: "user-1",
|
||||
name: "Ops",
|
||||
type: "webhook",
|
||||
enabled: 1,
|
||||
});
|
||||
|
||||
const updated = await repo.updateNotificationChannel(created.id, "user-1", {
|
||||
name: "Ops disabled",
|
||||
enabled: false,
|
||||
});
|
||||
expect(updated).toMatchObject({ name: "Ops disabled", enabled: 0 });
|
||||
|
||||
expect(await repo.listNotificationChannels("user-1")).toHaveLength(1);
|
||||
expect(await repo.deleteNotificationChannel(created.id, "user-2")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(await repo.deleteNotificationChannel(created.id, "user-1")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(await repo.listNotificationChannels("user-1")).toHaveLength(0);
|
||||
expect(writes).toBe(3);
|
||||
});
|
||||
|
||||
it("manages alert rules and linked channels", async () => {
|
||||
const repo = await createRepository();
|
||||
const ownedChannel = await repo.createNotificationChannel({
|
||||
userId: "user-1",
|
||||
name: "Owned",
|
||||
type: "ntfy",
|
||||
config: '{"url":"https://ntfy.test","topic":"termix"}',
|
||||
enabled: true,
|
||||
});
|
||||
const foreignChannel = await repo.createNotificationChannel({
|
||||
userId: "user-2",
|
||||
name: "Foreign",
|
||||
type: "webhook",
|
||||
config: '{"url":"https://example.test"}',
|
||||
enabled: true,
|
||||
});
|
||||
|
||||
const created = await repo.createAlertRule({
|
||||
userId: "user-1",
|
||||
hostId: null,
|
||||
name: "CPU high",
|
||||
enabled: true,
|
||||
triggerType: "cpu_threshold",
|
||||
thresholdValue: 80,
|
||||
thresholdDurationSeconds: 30,
|
||||
cooldownMinutes: 5,
|
||||
channels: [ownedChannel.id, foreignChannel.id],
|
||||
now: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(created).toMatchObject({
|
||||
user_id: "user-1",
|
||||
host_id: null,
|
||||
name: "CPU high",
|
||||
trigger_type: "cpu_threshold",
|
||||
threshold_value: 80,
|
||||
channels: [ownedChannel.id],
|
||||
});
|
||||
|
||||
const updated = await repo.updateAlertRule(created.id, "user-1", {
|
||||
name: "CPU very high",
|
||||
hostId: 1,
|
||||
channels: [],
|
||||
now: "2026-01-02T00:00:00.000Z",
|
||||
});
|
||||
expect(updated).toMatchObject({
|
||||
name: "CPU very high",
|
||||
host_id: 1,
|
||||
channels: [],
|
||||
updated_at: "2026-01-02T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const rules = await repo.listAlertRules("user-1");
|
||||
expect(rules).toHaveLength(1);
|
||||
expect(rules[0].channels).toEqual([]);
|
||||
expect(await repo.deleteAlertRule(created.id, "user-2")).toBe(false);
|
||||
expect(await repo.deleteAlertRule(created.id, "user-1")).toBe(true);
|
||||
});
|
||||
|
||||
it("lists, acknowledges, and prunes firings", async () => {
|
||||
const repo = await createRepository();
|
||||
const rule = await repo.createAlertRule({
|
||||
userId: "user-1",
|
||||
hostId: 1,
|
||||
name: "Host offline",
|
||||
enabled: true,
|
||||
triggerType: "host_offline",
|
||||
thresholdValue: null,
|
||||
thresholdDurationSeconds: null,
|
||||
cooldownMinutes: 15,
|
||||
channels: [],
|
||||
now: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
await repo.createFiring({
|
||||
userId: "user-1",
|
||||
ruleId: rule.id,
|
||||
hostId: 1,
|
||||
hostName: "alpha",
|
||||
value: null,
|
||||
message: "down",
|
||||
severity: "critical",
|
||||
});
|
||||
|
||||
const listed = await repo.listAlertFirings({
|
||||
userId: "user-1",
|
||||
limit: 10,
|
||||
offset: 0,
|
||||
});
|
||||
expect(listed.total).toBe(1);
|
||||
expect(listed.firings[0]).toMatchObject({
|
||||
rule_id: rule.id,
|
||||
host_name: "alpha",
|
||||
acknowledged: 0,
|
||||
rule_name: "Host offline",
|
||||
});
|
||||
|
||||
await repo.acknowledgeFiring(listed.firings[0].id, "user-1");
|
||||
const unacknowledged = await repo.listAlertFirings({
|
||||
userId: "user-1",
|
||||
acknowledged: false,
|
||||
limit: 10,
|
||||
offset: 0,
|
||||
});
|
||||
expect(unacknowledged.total).toBe(0);
|
||||
|
||||
await repo.acknowledgeAllFirings("user-1");
|
||||
repo.pruneFiringsOlderThan("user-1", 0);
|
||||
});
|
||||
|
||||
it("loads enabled rules and notification channels for the alert engine", async () => {
|
||||
const repo = await createRepository();
|
||||
const channel = await repo.createNotificationChannel({
|
||||
userId: "user-1",
|
||||
name: "Ops",
|
||||
type: "webhook",
|
||||
config: '{"url":"https://example.test"}',
|
||||
enabled: true,
|
||||
});
|
||||
const disabledChannel = await repo.createNotificationChannel({
|
||||
userId: "user-1",
|
||||
name: "Disabled",
|
||||
type: "webhook",
|
||||
config: '{"url":"https://disabled.test"}',
|
||||
enabled: false,
|
||||
});
|
||||
const rule = await repo.createAlertRule({
|
||||
userId: "user-1",
|
||||
hostId: null,
|
||||
name: "CPU high",
|
||||
enabled: true,
|
||||
triggerType: "cpu_threshold",
|
||||
thresholdValue: 90,
|
||||
thresholdDurationSeconds: 0,
|
||||
cooldownMinutes: 15,
|
||||
channels: [channel.id, disabledChannel.id],
|
||||
now: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(await repo.listEnabledRulesForHost(1)).toMatchObject([
|
||||
{
|
||||
id: rule.id,
|
||||
userId: "user-1",
|
||||
triggerType: "cpu_threshold",
|
||||
enabled: true,
|
||||
},
|
||||
]);
|
||||
expect(await repo.findRuleById(rule.id)).toMatchObject({
|
||||
id: rule.id,
|
||||
cooldownMinutes: 15,
|
||||
});
|
||||
expect(await repo.listEnabledChannelsForRule(rule.id)).toEqual([
|
||||
{
|
||||
id: channel.id,
|
||||
type: "webhook",
|
||||
config: '{"url":"https://example.test"}',
|
||||
enabled: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("loads host display names for alert payloads", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
expect(await repo.getHostDisplayName(1)).toBe("alpha");
|
||||
expect(await repo.getHostDisplayName(999)).toBeNull();
|
||||
});
|
||||
|
||||
it("deletes all alert data for a user", async () => {
|
||||
let writes = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writes += 1;
|
||||
});
|
||||
|
||||
const userChannel = await repo.createNotificationChannel({
|
||||
userId: "user-1",
|
||||
name: "Ops",
|
||||
type: "webhook",
|
||||
config: '{"url":"https://example.test"}',
|
||||
enabled: true,
|
||||
});
|
||||
const otherChannel = await repo.createNotificationChannel({
|
||||
userId: "user-2",
|
||||
name: "Other",
|
||||
type: "webhook",
|
||||
config: '{"url":"https://other.test"}',
|
||||
enabled: true,
|
||||
});
|
||||
const userRule = await repo.createAlertRule({
|
||||
userId: "user-1",
|
||||
hostId: 1,
|
||||
name: "CPU high",
|
||||
enabled: true,
|
||||
triggerType: "cpu_threshold",
|
||||
thresholdValue: 80,
|
||||
thresholdDurationSeconds: 30,
|
||||
cooldownMinutes: 5,
|
||||
channels: [userChannel.id],
|
||||
now: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
const otherRule = await repo.createAlertRule({
|
||||
userId: "user-2",
|
||||
hostId: null,
|
||||
name: "Memory high",
|
||||
enabled: true,
|
||||
triggerType: "memory_threshold",
|
||||
thresholdValue: 90,
|
||||
thresholdDurationSeconds: 60,
|
||||
cooldownMinutes: 10,
|
||||
channels: [otherChannel.id],
|
||||
now: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
await repo.createFiring({
|
||||
userId: "user-1",
|
||||
ruleId: userRule.id,
|
||||
hostId: 1,
|
||||
hostName: "alpha",
|
||||
value: 95,
|
||||
message: "high",
|
||||
severity: "warning",
|
||||
});
|
||||
await repo.createFiring({
|
||||
userId: "user-2",
|
||||
ruleId: otherRule.id,
|
||||
hostId: 1,
|
||||
hostName: "alpha",
|
||||
value: 91,
|
||||
message: "other",
|
||||
severity: "warning",
|
||||
});
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toEqual({
|
||||
firingsDeleted: 1,
|
||||
ruleLinksDeleted: 1,
|
||||
rulesDeleted: 1,
|
||||
channelsDeleted: 1,
|
||||
});
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toEqual({
|
||||
firingsDeleted: 0,
|
||||
ruleLinksDeleted: 0,
|
||||
rulesDeleted: 0,
|
||||
channelsDeleted: 0,
|
||||
});
|
||||
|
||||
expect(await repo.listNotificationChannels("user-1")).toEqual([]);
|
||||
expect(await repo.listAlertRules("user-1")).toEqual([]);
|
||||
expect(
|
||||
await repo.listAlertFirings({ userId: "user-1", limit: 10, offset: 0 }),
|
||||
).toEqual({ firings: [], total: 0 });
|
||||
expect(await repo.listNotificationChannels("user-2")).toHaveLength(1);
|
||||
expect(await repo.listAlertRules("user-2")).toHaveLength(1);
|
||||
expect(await repo.listEnabledChannelsForRule(otherRule.id)).toHaveLength(1);
|
||||
expect(writes).toBe(7);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { ApiKeyRepository } from "../../../database/repositories/api-key-repository.js";
|
||||
|
||||
describe("ApiKeyRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(onWrite?: () => void): Promise<{
|
||||
apiKeys: ApiKeyRepository;
|
||||
}> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE api_keys (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL,
|
||||
token_prefix TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TEXT,
|
||||
last_used_at TEXT,
|
||||
is_active INTEGER NOT NULL DEFAULT 1,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash) VALUES
|
||||
('user-1', 'admin', 'hash'),
|
||||
('user-2', 'target', 'hash');
|
||||
`);
|
||||
|
||||
return {
|
||||
apiKeys: new ApiKeyRepository(context, onWrite),
|
||||
};
|
||||
}
|
||||
|
||||
it("creates, lists, finds, updates last used time, and deletes keys", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.apiKeys.create({
|
||||
id: "key-1",
|
||||
userId: "user-2",
|
||||
name: "deploy",
|
||||
tokenHash: "hash",
|
||||
tokenPrefix: "tmx_12345678",
|
||||
createdAt: "2026-06-26T00:00:00.000Z",
|
||||
expiresAt: null,
|
||||
lastUsedAt: null,
|
||||
isActive: true,
|
||||
});
|
||||
|
||||
expect((await repo.apiKeys.findById("key-1"))?.name).toBe("deploy");
|
||||
expect(
|
||||
(await repo.apiKeys.listActiveByTokenPrefix("tmx_12345678")).map(
|
||||
(key) => key.id,
|
||||
),
|
||||
).toEqual(["key-1"]);
|
||||
expect(await repo.apiKeys.listAllWithUsers()).toMatchObject([
|
||||
{
|
||||
id: "key-1",
|
||||
userId: "user-2",
|
||||
username: "target",
|
||||
tokenPrefix: "tmx_12345678",
|
||||
},
|
||||
]);
|
||||
|
||||
await repo.apiKeys.updateLastUsedAt("key-1", "2026-06-26T01:00:00.000Z");
|
||||
expect((await repo.apiKeys.findById("key-1"))?.lastUsedAt).toBe(
|
||||
"2026-06-26T01:00:00.000Z",
|
||||
);
|
||||
|
||||
expect((await repo.apiKeys.delete("key-1"))?.name).toBe("deploy");
|
||||
expect(await repo.apiKeys.findById("key-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("runs the write hook after key writes", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.apiKeys.create({
|
||||
id: "key-1",
|
||||
userId: "user-1",
|
||||
name: "ops",
|
||||
tokenHash: "hash",
|
||||
tokenPrefix: "tmx_87654321",
|
||||
isActive: true,
|
||||
});
|
||||
await repo.apiKeys.updateLastUsedAt("key-1", "2026-06-26T01:00:00.000Z");
|
||||
await repo.apiKeys.delete("key-1");
|
||||
|
||||
expect(writeCount).toBe(3);
|
||||
});
|
||||
|
||||
it("deletes all API keys for a user", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.apiKeys.create({
|
||||
id: "key-1",
|
||||
userId: "user-2",
|
||||
name: "deploy",
|
||||
tokenHash: "hash-1",
|
||||
tokenPrefix: "tmx_11111111",
|
||||
isActive: true,
|
||||
});
|
||||
await repo.apiKeys.create({
|
||||
id: "key-2",
|
||||
userId: "user-2",
|
||||
name: "ops",
|
||||
tokenHash: "hash-2",
|
||||
tokenPrefix: "tmx_22222222",
|
||||
isActive: true,
|
||||
});
|
||||
await repo.apiKeys.create({
|
||||
id: "key-3",
|
||||
userId: "user-1",
|
||||
name: "admin",
|
||||
tokenHash: "hash-3",
|
||||
tokenPrefix: "tmx_33333333",
|
||||
isActive: true,
|
||||
});
|
||||
|
||||
await expect(repo.apiKeys.deleteByUserId("user-2")).resolves.toBe(2);
|
||||
|
||||
expect(await repo.apiKeys.findById("key-1")).toBeNull();
|
||||
expect(await repo.apiKeys.findById("key-2")).toBeNull();
|
||||
expect((await repo.apiKeys.findById("key-3"))?.userId).toBe("user-1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { AuditLogRepository } from "../../../database/repositories/audit-log-repository.js";
|
||||
|
||||
describe("AuditLogRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<AuditLogRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE audit_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
resource_type TEXT NOT NULL,
|
||||
resource_id TEXT,
|
||||
resource_name TEXT,
|
||||
details TEXT,
|
||||
ip_address TEXT,
|
||||
user_agent TEXT,
|
||||
success INTEGER NOT NULL,
|
||||
error_message TEXT,
|
||||
timestamp TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
`);
|
||||
|
||||
return new AuditLogRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates, filters, pages, and lists actions", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.create({
|
||||
userId: "user-1",
|
||||
username: "alice",
|
||||
action: "create_host",
|
||||
resourceType: "host",
|
||||
resourceId: "1",
|
||||
success: true,
|
||||
timestamp: "2026-06-27T00:00:00.000Z",
|
||||
});
|
||||
await repo.create({
|
||||
userId: "user-2",
|
||||
username: "bob",
|
||||
action: "delete_host",
|
||||
resourceType: "host",
|
||||
resourceId: "2",
|
||||
success: false,
|
||||
timestamp: "2026-06-27T01:00:00.000Z",
|
||||
});
|
||||
|
||||
const page = await repo.listPage({
|
||||
filters: {
|
||||
resourceType: "host",
|
||||
success: false,
|
||||
startDate: "2026-06-27T00:30:00.000Z",
|
||||
},
|
||||
limit: 10,
|
||||
offset: 0,
|
||||
});
|
||||
|
||||
expect(page.total).toBe(1);
|
||||
expect(page.logs[0]).toMatchObject({
|
||||
userId: "user-2",
|
||||
action: "delete_host",
|
||||
success: false,
|
||||
});
|
||||
expect(await repo.listDistinctActions()).toEqual([
|
||||
"create_host",
|
||||
"delete_host",
|
||||
]);
|
||||
});
|
||||
|
||||
it("deletes logs by user id and only runs write hook for deleted rows", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.create({
|
||||
userId: "user-1",
|
||||
username: "alice",
|
||||
action: "login",
|
||||
resourceType: "auth",
|
||||
success: true,
|
||||
});
|
||||
await repo.create({
|
||||
userId: "user-2",
|
||||
username: "bob",
|
||||
action: "login",
|
||||
resourceType: "auth",
|
||||
success: true,
|
||||
});
|
||||
|
||||
expect(await repo.deleteByUserId("missing")).toBe(0);
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(1);
|
||||
expect(writeCount).toBe(3);
|
||||
expect(
|
||||
(
|
||||
await repo.listPage({
|
||||
filters: {},
|
||||
limit: 10,
|
||||
offset: 0,
|
||||
})
|
||||
).logs.map((log) => log.userId),
|
||||
).toEqual(["user-2"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { C2sTunnelPresetRepository } from "../../../database/repositories/c2s-tunnel-preset-repository.js";
|
||||
|
||||
describe("C2sTunnelPresetRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<C2sTunnelPresetRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE c2s_tunnel_presets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
config TEXT NOT NULL,
|
||||
platform TEXT,
|
||||
computer_name TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
`);
|
||||
|
||||
return new C2sTunnelPresetRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates and lists presets ordered by name", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.createForUser("user-1", {
|
||||
name: "Zulu",
|
||||
config: "[]",
|
||||
platform: "linux",
|
||||
computerName: "workstation",
|
||||
});
|
||||
await repo.createForUser("user-1", { name: "Alpha", config: "[]" });
|
||||
await repo.createForUser("user-2", { name: "Other", config: "[]" });
|
||||
|
||||
const presets = await repo.listByUserId("user-1");
|
||||
|
||||
expect(presets.map((preset) => preset.name)).toEqual(["Alpha", "Zulu"]);
|
||||
expect(presets[1]).toMatchObject({
|
||||
platform: "linux",
|
||||
computerName: "workstation",
|
||||
});
|
||||
});
|
||||
|
||||
it("finds, updates, and deletes user-owned presets", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const preset = await repo.createForUser("user-1", {
|
||||
name: "Home",
|
||||
config: "[]",
|
||||
});
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
expect(await repo.findByIdForUser("user-2", preset.id)).toBeNull();
|
||||
expect(await repo.hasNameForUser("user-1", "Home")).toBe(true);
|
||||
expect(await repo.hasNameForUser("user-1", "Home", preset.id)).toBe(false);
|
||||
|
||||
const updated = await repo.updateForUser("user-1", preset.id, {
|
||||
name: "Renamed",
|
||||
platform: "darwin",
|
||||
});
|
||||
expect(updated).toMatchObject({
|
||||
id: preset.id,
|
||||
name: "Renamed",
|
||||
platform: "darwin",
|
||||
});
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(
|
||||
await repo.updateForUser("user-2", preset.id, { name: "Nope" }),
|
||||
).toBeNull();
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(await repo.deleteForUser("user-2", preset.id)).toBe(false);
|
||||
expect(await repo.deleteForUser("user-1", preset.id)).toBe(true);
|
||||
expect(writeCount).toBe(3);
|
||||
});
|
||||
|
||||
it("deletes all presets for a user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.createForUser("user-1", { name: "One", config: "[]" });
|
||||
await repo.createForUser("user-1", { name: "Two", config: "[]" });
|
||||
await repo.createForUser("user-2", { name: "Other", config: "[]" });
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toBe(2);
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
|
||||
|
||||
expect(await repo.listByUserId("user-1")).toEqual([]);
|
||||
expect(
|
||||
(await repo.listByUserId("user-2")).map((preset) => preset.name),
|
||||
).toEqual(["Other"]);
|
||||
expect(writeCount).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { CommandHistoryRepository } from "../../../database/repositories/command-history-repository.js";
|
||||
|
||||
describe("CommandHistoryRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<CommandHistoryRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE hosts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE command_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
command TEXT NOT NULL,
|
||||
executed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO hosts (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'one'), (2, 'user-1', 'two'), (3, 'user-2', 'other');
|
||||
`);
|
||||
|
||||
return new CommandHistoryRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates and lists unique commands by latest execution", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.create("user-1", 1, "ls", "2026-06-27T00:00:00.000Z");
|
||||
await repo.create("user-1", 1, "pwd", "2026-06-27T01:00:00.000Z");
|
||||
await repo.create("user-1", 1, "ls", "2026-06-27T02:00:00.000Z");
|
||||
await repo.create("user-2", 3, "whoami", "2026-06-27T03:00:00.000Z");
|
||||
|
||||
expect(await repo.listUniqueCommandsForHost("user-1", 1)).toEqual([
|
||||
"ls",
|
||||
"pwd",
|
||||
]);
|
||||
expect(await repo.listCommandsForHost("user-1", 1)).toEqual([
|
||||
"ls",
|
||||
"pwd",
|
||||
"ls",
|
||||
]);
|
||||
});
|
||||
|
||||
it("deletes commands by command, host, host list, and user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.create("user-1", 1, "ls");
|
||||
await repo.create("user-1", 1, "ls");
|
||||
await repo.create("user-1", 2, "pwd");
|
||||
await repo.create("user-2", 3, "whoami");
|
||||
expect(writeCount).toBe(4);
|
||||
|
||||
expect(await repo.deleteCommandForHost("user-1", 1, "missing")).toBe(0);
|
||||
expect(writeCount).toBe(4);
|
||||
|
||||
expect(await repo.deleteCommandForHost("user-1", 1, "ls")).toBe(2);
|
||||
expect(writeCount).toBe(5);
|
||||
|
||||
expect(await repo.deleteByUserAndHost("user-1", 2)).toBe(1);
|
||||
expect(await repo.deleteByHostIds([])).toBe(0);
|
||||
expect(await repo.deleteByHostIds([3])).toBe(1);
|
||||
expect(writeCount).toBe(7);
|
||||
|
||||
await repo.create("user-1", 1, "date");
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(1);
|
||||
expect(writeCount).toBe(9);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { DashboardServiceLinkRepository } from "../../../database/repositories/dashboard-service-link-repository.js";
|
||||
|
||||
describe("DashboardServiceLinkRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<DashboardServiceLinkRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE dashboard_service_links (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
label TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
`);
|
||||
|
||||
return new DashboardServiceLinkRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates and lists links ordered by order then id", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const first = await repo.createForUser(
|
||||
"user-1",
|
||||
{ label: "Docs", url: "https://docs.example.com" },
|
||||
"2026-06-27T00:00:00.000Z",
|
||||
);
|
||||
const second = await repo.createForUser("user-1", {
|
||||
label: "Status",
|
||||
url: "https://status.example.com",
|
||||
});
|
||||
await repo.createForUser("user-2", {
|
||||
label: "Other",
|
||||
url: "https://other.example.com",
|
||||
});
|
||||
|
||||
expect(first).toMatchObject({
|
||||
userId: "user-1",
|
||||
label: "Docs",
|
||||
order: 0,
|
||||
createdAt: "2026-06-27T00:00:00.000Z",
|
||||
});
|
||||
expect(second.order).toBe(1);
|
||||
expect(
|
||||
(await repo.listByUserId("user-1")).map((link) => link.label),
|
||||
).toEqual(["Docs", "Status"]);
|
||||
});
|
||||
|
||||
it("finds, updates, and deletes a user-owned link", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const link = await repo.createForUser("user-1", {
|
||||
label: "Docs",
|
||||
url: "https://docs.example.com",
|
||||
});
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
expect(await repo.findByIdForUser("user-2", link.id)).toBeNull();
|
||||
const updated = await repo.updateForUser("user-1", link.id, {
|
||||
label: "Docs renamed",
|
||||
});
|
||||
expect(updated).toMatchObject({
|
||||
id: link.id,
|
||||
label: "Docs renamed",
|
||||
url: "https://docs.example.com",
|
||||
});
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(await repo.updateForUser("user-2", link.id, { label: "Nope" })).toBe(
|
||||
null,
|
||||
);
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(await repo.deleteForUser("user-2", link.id)).toBe(false);
|
||||
expect(await repo.deleteForUser("user-1", link.id)).toBe(true);
|
||||
expect(writeCount).toBe(3);
|
||||
});
|
||||
|
||||
it("deletes all dashboard links for a user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.createForUser("user-1", {
|
||||
label: "Docs",
|
||||
url: "https://docs.example.com",
|
||||
});
|
||||
await repo.createForUser("user-1", {
|
||||
label: "Status",
|
||||
url: "https://status.example.com",
|
||||
});
|
||||
await repo.createForUser("user-2", {
|
||||
label: "Other",
|
||||
url: "https://other.example.com",
|
||||
});
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toBe(2);
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
|
||||
|
||||
expect(await repo.listByUserId("user-1")).toEqual([]);
|
||||
expect(
|
||||
(await repo.listByUserId("user-2")).map((link) => link.label),
|
||||
).toEqual(["Other"]);
|
||||
expect(writeCount).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { DismissedAlertRepository } from "../../../database/repositories/dismissed-alert-repository.js";
|
||||
|
||||
describe("DismissedAlertRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<DismissedAlertRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE dismissed_alerts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
alert_id TEXT NOT NULL,
|
||||
dismissed_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
`);
|
||||
|
||||
return new DismissedAlertRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates, lists, and finds dismissed alerts by user", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.create("user-1", "alert-1");
|
||||
await repo.create("user-1", "alert-2");
|
||||
await repo.create("user-2", "alert-3");
|
||||
|
||||
expect(await repo.listAlertIdsByUserId("user-1")).toEqual([
|
||||
"alert-1",
|
||||
"alert-2",
|
||||
]);
|
||||
expect((await repo.findForUser("user-1", "alert-1"))?.alertId).toBe(
|
||||
"alert-1",
|
||||
);
|
||||
expect(await repo.findForUser("user-1", "alert-3")).toBeNull();
|
||||
expect(
|
||||
(await repo.listByUserId("user-1")).map((row) => row.alertId),
|
||||
).toEqual(["alert-1", "alert-2"]);
|
||||
});
|
||||
|
||||
it("creates import alerts without duplicating user alert pairs", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.createForImport("user-1", "alert-1", "2026-01-01T00:00:00.000Z"),
|
||||
).resolves.toBe(true);
|
||||
await expect(
|
||||
repo.createForImport("user-1", "alert-1", "2026-01-02T00:00:00.000Z"),
|
||||
).resolves.toBe(false);
|
||||
|
||||
const alerts = await repo.listByUserId("user-1");
|
||||
expect(alerts).toHaveLength(1);
|
||||
expect(alerts[0]).toMatchObject({
|
||||
alertId: "alert-1",
|
||||
dismissedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("deletes dismissed alerts and only triggers writes for changed rows", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.create("user-1", "alert-1");
|
||||
await repo.create("user-1", "alert-2");
|
||||
await repo.create("user-2", "alert-3");
|
||||
expect(writeCount).toBe(3);
|
||||
|
||||
expect(await repo.deleteForUser("user-1", "missing")).toBe(false);
|
||||
expect(writeCount).toBe(3);
|
||||
|
||||
expect(await repo.deleteForUser("user-1", "alert-1")).toBe(true);
|
||||
expect(writeCount).toBe(4);
|
||||
expect(await repo.listAlertIdsByUserId("user-1")).toEqual(["alert-2"]);
|
||||
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(1);
|
||||
expect(writeCount).toBe(5);
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(0);
|
||||
expect(writeCount).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import crypto from "crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { FieldEncryptionBoundary } from "../../../database/repositories/field-encryption-boundary.js";
|
||||
|
||||
describe("FieldEncryptionBoundary", () => {
|
||||
const userDataKey = crypto.randomBytes(32);
|
||||
|
||||
it("encrypts sensitive host fields while leaving queryable metadata plaintext", () => {
|
||||
const host = {
|
||||
id: 42,
|
||||
userId: "user-1",
|
||||
name: "prod-db",
|
||||
ip: "10.0.0.5",
|
||||
username: "root",
|
||||
password: "secret",
|
||||
rdpPassword: "rdp-secret",
|
||||
};
|
||||
|
||||
const encrypted = FieldEncryptionBoundary.encryptRecord(
|
||||
"ssh_data",
|
||||
host,
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
expect(encrypted.password).not.toBe("secret");
|
||||
expect(encrypted.rdpPassword).not.toBe("rdp-secret");
|
||||
expect(encrypted.ip).toBe("10.0.0.5");
|
||||
expect(encrypted.name).toBe("prod-db");
|
||||
|
||||
const decrypted = FieldEncryptionBoundary.decryptRecord(
|
||||
"ssh_data",
|
||||
encrypted,
|
||||
userDataKey,
|
||||
);
|
||||
expect(decrypted).toMatchObject(host);
|
||||
});
|
||||
|
||||
it("encrypts credential secret fields and keeps metadata plaintext", () => {
|
||||
const credential = {
|
||||
id: 7,
|
||||
userId: "user-1",
|
||||
name: "primary credential",
|
||||
authType: "key",
|
||||
key: "private-key-material",
|
||||
keyPassword: "key-password",
|
||||
};
|
||||
|
||||
const encrypted = FieldEncryptionBoundary.encryptRecord(
|
||||
"ssh_credentials",
|
||||
credential,
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
expect(encrypted.key).not.toBe("private-key-material");
|
||||
expect(encrypted.keyPassword).not.toBe("key-password");
|
||||
expect(encrypted.name).toBe("primary credential");
|
||||
|
||||
expect(
|
||||
FieldEncryptionBoundary.decryptRecord(
|
||||
"ssh_credentials",
|
||||
encrypted,
|
||||
userDataKey,
|
||||
),
|
||||
).toMatchObject(credential);
|
||||
});
|
||||
|
||||
it("keeps empty and non-string sensitive values unchanged", () => {
|
||||
const encrypted = FieldEncryptionBoundary.encryptRecord(
|
||||
"ssh_data",
|
||||
{
|
||||
id: 1,
|
||||
password: "",
|
||||
key: null,
|
||||
},
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
expect(encrypted.password).toBe("");
|
||||
expect(encrypted.key).toBeNull();
|
||||
});
|
||||
|
||||
it("requires a stable record id instead of inventing a temporary encryption context", () => {
|
||||
expect(() =>
|
||||
FieldEncryptionBoundary.encryptRecord(
|
||||
"ssh_data",
|
||||
{ password: "secret" },
|
||||
userDataKey,
|
||||
),
|
||||
).toThrow(/stable record id/);
|
||||
});
|
||||
|
||||
it("classifies sensitive, plaintext, and unknown fields", () => {
|
||||
expect(FieldEncryptionBoundary.classifyField("ssh_data", "password")).toBe(
|
||||
"sensitive",
|
||||
);
|
||||
expect(FieldEncryptionBoundary.classifyField("ssh_data", "ip")).toBe(
|
||||
"plaintext",
|
||||
);
|
||||
expect(FieldEncryptionBoundary.classifyField("ssh_data", "newField")).toBe(
|
||||
"unknown",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { FileManagerBookmarkRepository } from "../../../database/repositories/file-manager-bookmark-repository.js";
|
||||
|
||||
describe("FileManagerBookmarkRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<FileManagerBookmarkRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE hosts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE file_manager_recent (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
last_opened TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE file_manager_pinned (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
pinned_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE file_manager_shortcuts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO hosts (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'one'), (2, 'user-1', 'two'), (3, 'user-2', 'other');
|
||||
`);
|
||||
|
||||
return new FileManagerBookmarkRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("upserts and lists recent files by last-opened time", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsertRecent(
|
||||
"user-1",
|
||||
{ hostId: 1, path: "/var/log/app.log" },
|
||||
"2026-01-01T00:00:00.000Z",
|
||||
);
|
||||
await repo.upsertRecent(
|
||||
"user-1",
|
||||
{ hostId: 1, path: "/opt/app/config.json", name: "Config" },
|
||||
"2026-01-02T00:00:00.000Z",
|
||||
);
|
||||
await repo.upsertRecent(
|
||||
"user-1",
|
||||
{ hostId: 1, path: "/var/log/app.log" },
|
||||
"2026-01-03T00:00:00.000Z",
|
||||
);
|
||||
|
||||
const recent = await repo.listRecentForHost("user-1", 1);
|
||||
|
||||
expect(recent.map((entry) => entry.path)).toEqual([
|
||||
"/var/log/app.log",
|
||||
"/opt/app/config.json",
|
||||
]);
|
||||
expect(recent[0].lastOpened).toBe("2026-01-03T00:00:00.000Z");
|
||||
expect(recent[0].name).toBe("app.log");
|
||||
expect(writeCount).toBe(3);
|
||||
|
||||
expect(
|
||||
await repo.deleteRecentForHostPath("user-1", {
|
||||
hostId: 1,
|
||||
path: "/var/log/app.log",
|
||||
}),
|
||||
).toBe(1);
|
||||
expect(writeCount).toBe(4);
|
||||
});
|
||||
|
||||
it("creates pinned files and shortcuts without duplicating paths", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(
|
||||
await repo.createPinned(
|
||||
"user-1",
|
||||
{ hostId: 1, path: "/srv/www", name: "Web" },
|
||||
"2026-01-01T00:00:00.000Z",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
await repo.createPinned("user-1", { hostId: 1, path: "/srv/www" }),
|
||||
).toBe(false);
|
||||
expect((await repo.listPinnedForHost("user-1", 1))[0]).toMatchObject({
|
||||
name: "Web",
|
||||
path: "/srv/www",
|
||||
});
|
||||
|
||||
expect(
|
||||
await repo.createShortcut(
|
||||
"user-1",
|
||||
{ hostId: 1, path: "/etc/nginx" },
|
||||
"2026-01-02T00:00:00.000Z",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
await repo.createShortcut("user-1", { hostId: 1, path: "/etc/nginx" }),
|
||||
).toBe(false);
|
||||
expect((await repo.listShortcutsForHost("user-1", 1))[0]).toMatchObject({
|
||||
name: "nginx",
|
||||
path: "/etc/nginx",
|
||||
});
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(
|
||||
await repo.deletePinnedForHostPath("user-1", {
|
||||
hostId: 1,
|
||||
path: "/srv/www",
|
||||
}),
|
||||
).toBe(1);
|
||||
expect(
|
||||
await repo.deleteShortcutForHostPath("user-1", {
|
||||
hostId: 1,
|
||||
path: "/etc/nginx",
|
||||
}),
|
||||
).toBe(1);
|
||||
expect(writeCount).toBe(4);
|
||||
});
|
||||
|
||||
it("creates import bookmarks without duplicating user path/name pairs", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await expect(
|
||||
repo.createRecentForImport(
|
||||
"user-1",
|
||||
{ hostId: 1, path: "/tmp/a.txt", name: "A" },
|
||||
"2026-01-01T00:00:00.000Z",
|
||||
),
|
||||
).resolves.toBe(true);
|
||||
await expect(
|
||||
repo.createRecentForImport("user-1", {
|
||||
hostId: 2,
|
||||
path: "/tmp/a.txt",
|
||||
name: "A",
|
||||
}),
|
||||
).resolves.toBe(false);
|
||||
|
||||
await expect(
|
||||
repo.createPinnedForImport("user-1", {
|
||||
hostId: 1,
|
||||
path: "/srv/www",
|
||||
name: "Web",
|
||||
}),
|
||||
).resolves.toBe(true);
|
||||
await expect(
|
||||
repo.createPinnedForImport("user-1", {
|
||||
hostId: 2,
|
||||
path: "/srv/www",
|
||||
name: "Web",
|
||||
}),
|
||||
).resolves.toBe(false);
|
||||
|
||||
await expect(
|
||||
repo.createShortcutForImport("user-1", {
|
||||
hostId: 1,
|
||||
path: "/etc/nginx",
|
||||
name: "Nginx",
|
||||
}),
|
||||
).resolves.toBe(true);
|
||||
await expect(
|
||||
repo.createShortcutForImport("user-1", {
|
||||
hostId: 2,
|
||||
path: "/etc/nginx",
|
||||
name: "Nginx",
|
||||
}),
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("deletes bookmarks by user, host, and host list", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsertRecent("user-1", { hostId: 1, path: "/one" });
|
||||
await repo.createPinned("user-1", { hostId: 2, path: "/two" });
|
||||
await repo.createShortcut("user-2", { hostId: 3, path: "/three" });
|
||||
expect(writeCount).toBe(3);
|
||||
|
||||
expect(await repo.deleteByHostId(1)).toBe(1);
|
||||
expect(await repo.deleteByHostId(1)).toBe(0);
|
||||
expect(await repo.deleteByHostIds([])).toBe(0);
|
||||
expect(await repo.deleteByHostIds([2])).toBe(1);
|
||||
expect(writeCount).toBe(5);
|
||||
|
||||
expect(await repo.deleteByUserId("user-2")).toBe(1);
|
||||
expect(await repo.deleteByUserId("user-2")).toBe(0);
|
||||
expect(writeCount).toBe(6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { HomepageItemRepository } from "../../../database/repositories/homepage-item-repository.js";
|
||||
|
||||
describe("HomepageItemRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<HomepageItemRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE homepage_items (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
type_id TEXT NOT NULL,
|
||||
title TEXT,
|
||||
config TEXT NOT NULL DEFAULT '{}',
|
||||
folder_id INTEGER,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
`);
|
||||
|
||||
return new HomepageItemRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates and lists homepage items by id", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const first = await repo.createForUser(
|
||||
"user-1",
|
||||
{ typeId: "clock", title: "Clock", config: "{}" },
|
||||
"2026-06-27T00:00:00.000Z",
|
||||
);
|
||||
const second = await repo.createForUser("user-1", {
|
||||
typeId: "terminal",
|
||||
title: null,
|
||||
config: '{"hostId":1}',
|
||||
});
|
||||
await repo.createForUser("user-2", {
|
||||
typeId: "other",
|
||||
title: "Other",
|
||||
config: "{}",
|
||||
});
|
||||
|
||||
expect(first).toMatchObject({
|
||||
userId: "user-1",
|
||||
typeId: "clock",
|
||||
title: "Clock",
|
||||
config: "{}",
|
||||
createdAt: "2026-06-27T00:00:00.000Z",
|
||||
});
|
||||
expect((await repo.listByUserId("user-1")).map((item) => item.id)).toEqual([
|
||||
first.id,
|
||||
second.id,
|
||||
]);
|
||||
});
|
||||
|
||||
it("finds, updates, and deletes user-owned homepage items", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const item = await repo.createForUser("user-1", {
|
||||
typeId: "clock",
|
||||
title: "Clock",
|
||||
config: "{}",
|
||||
});
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
expect(await repo.findByIdForUser("user-2", item.id)).toBeNull();
|
||||
const updated = await repo.updateForUser(
|
||||
"user-1",
|
||||
item.id,
|
||||
{ title: "Clock renamed", config: '{"timezone":"UTC"}' },
|
||||
"2026-06-27T01:00:00.000Z",
|
||||
);
|
||||
expect(updated).toMatchObject({
|
||||
id: item.id,
|
||||
title: "Clock renamed",
|
||||
config: '{"timezone":"UTC"}',
|
||||
updatedAt: "2026-06-27T01:00:00.000Z",
|
||||
});
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(
|
||||
await repo.updateForUser("user-2", item.id, { title: "Nope" }),
|
||||
).toBeNull();
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(await repo.deleteForUser("user-2", item.id)).toBe(false);
|
||||
expect(await repo.deleteForUser("user-1", item.id)).toBe(true);
|
||||
expect(writeCount).toBe(3);
|
||||
});
|
||||
|
||||
it("deletes all homepage items for a user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.createForUser("user-1", {
|
||||
typeId: "clock",
|
||||
title: "Clock",
|
||||
config: "{}",
|
||||
});
|
||||
await repo.createForUser("user-1", {
|
||||
typeId: "terminal",
|
||||
title: "Terminal",
|
||||
config: "{}",
|
||||
});
|
||||
await repo.createForUser("user-2", {
|
||||
typeId: "other",
|
||||
title: "Other",
|
||||
config: "{}",
|
||||
});
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toBe(2);
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
|
||||
|
||||
expect(await repo.listByUserId("user-1")).toEqual([]);
|
||||
expect(
|
||||
(await repo.listByUserId("user-2")).map((item) => item.title),
|
||||
).toEqual(["Other"]);
|
||||
expect(writeCount).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { HomepageLayoutRepository } from "../../../database/repositories/homepage-layout-repository.js";
|
||||
|
||||
describe("HomepageLayoutRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<HomepageLayoutRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE homepage_layouts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL UNIQUE,
|
||||
layout TEXT NOT NULL DEFAULT '{}',
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
`);
|
||||
|
||||
return new HomepageLayoutRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("finds, creates, and updates a layout by user id", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
expect(await repo.findByUserId("user-1")).toBeNull();
|
||||
|
||||
const created = await repo.upsertForUser(
|
||||
"user-1",
|
||||
JSON.stringify({ entries: [{ id: "w1" }], zoom: 1 }),
|
||||
"2026-06-27T00:00:00.000Z",
|
||||
);
|
||||
expect(created).toMatchObject({
|
||||
userId: "user-1",
|
||||
layout: '{"entries":[{"id":"w1"}],"zoom":1}',
|
||||
updatedAt: "2026-06-27T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const updated = await repo.upsertForUser(
|
||||
"user-1",
|
||||
JSON.stringify({ entries: [], zoom: 1.25 }),
|
||||
"2026-06-27T01:00:00.000Z",
|
||||
);
|
||||
expect(updated).toMatchObject({
|
||||
id: created.id,
|
||||
userId: "user-1",
|
||||
layout: '{"entries":[],"zoom":1.25}',
|
||||
updatedAt: "2026-06-27T01:00:00.000Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("triggers writes after create and update", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsertForUser("user-1", "{}");
|
||||
await repo.upsertForUser("user-1", '{"zoom":2}');
|
||||
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("deletes a layout for a user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsertForUser("user-1", '{"zoom":1}');
|
||||
await repo.upsertForUser("user-2", '{"zoom":2}');
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toBe(1);
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
|
||||
|
||||
expect(await repo.findByUserId("user-1")).toBeNull();
|
||||
expect((await repo.findByUserId("user-2"))?.layout).toBe('{"zoom":2}');
|
||||
expect(writeCount).toBe(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,691 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { CredentialRepository } from "../../../database/repositories/credential-repository.js";
|
||||
import { HostRepository } from "../../../database/repositories/host-repository.js";
|
||||
import { DataCrypto } from "../../../utils/data-crypto.js";
|
||||
|
||||
describe("HostRepository and CredentialRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepositories(
|
||||
onCredentialWrite?: () => void,
|
||||
onHostWrite?: () => void,
|
||||
): Promise<{
|
||||
credentials: CredentialRepository;
|
||||
hosts: HostRepository;
|
||||
sqlite: NonNullable<
|
||||
Awaited<ReturnType<TestSqliteDatabase["connect"]>>["sqlite"]
|
||||
>;
|
||||
}> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_credentials (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
folder TEXT,
|
||||
tags TEXT,
|
||||
auth_type TEXT NOT NULL,
|
||||
username TEXT,
|
||||
password TEXT,
|
||||
key TEXT,
|
||||
private_key TEXT,
|
||||
public_key TEXT,
|
||||
key_password TEXT,
|
||||
key_type TEXT,
|
||||
detected_key_type TEXT,
|
||||
cert_public_key TEXT,
|
||||
usage_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_used TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
connection_type TEXT NOT NULL DEFAULT 'ssh',
|
||||
name TEXT,
|
||||
ip TEXT NOT NULL,
|
||||
port INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
folder TEXT,
|
||||
tags TEXT,
|
||||
pin INTEGER NOT NULL DEFAULT 0,
|
||||
auth_type TEXT NOT NULL,
|
||||
use_warpgate INTEGER NOT NULL DEFAULT 0,
|
||||
force_keyboard_interactive TEXT,
|
||||
password TEXT,
|
||||
key TEXT,
|
||||
key_password TEXT,
|
||||
key_type TEXT,
|
||||
sudo_password TEXT,
|
||||
autostart_password TEXT,
|
||||
autostart_key TEXT,
|
||||
autostart_key_password TEXT,
|
||||
credential_id INTEGER,
|
||||
override_credential_username INTEGER,
|
||||
vault_profile_id INTEGER,
|
||||
enable_terminal INTEGER NOT NULL DEFAULT 1,
|
||||
enable_session_logging INTEGER NOT NULL DEFAULT 1,
|
||||
enable_command_history INTEGER NOT NULL DEFAULT 1,
|
||||
enable_tunnel INTEGER NOT NULL DEFAULT 1,
|
||||
tunnel_connections TEXT,
|
||||
jump_hosts TEXT,
|
||||
enable_file_manager INTEGER NOT NULL DEFAULT 1,
|
||||
scp_legacy INTEGER NOT NULL DEFAULT 0,
|
||||
enable_docker INTEGER NOT NULL DEFAULT 0,
|
||||
enable_tmux_monitor INTEGER NOT NULL DEFAULT 0,
|
||||
show_terminal_in_sidebar INTEGER NOT NULL DEFAULT 1,
|
||||
show_file_manager_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_tunnel_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_docker_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_server_stats_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
default_path TEXT,
|
||||
stats_config TEXT,
|
||||
docker_config TEXT,
|
||||
enable_proxmox INTEGER NOT NULL DEFAULT 0,
|
||||
proxmox_config TEXT,
|
||||
terminal_config TEXT,
|
||||
quick_actions TEXT,
|
||||
notes TEXT,
|
||||
enable_ssh INTEGER NOT NULL DEFAULT 1,
|
||||
enable_rdp INTEGER NOT NULL DEFAULT 0,
|
||||
enable_vnc INTEGER NOT NULL DEFAULT 0,
|
||||
enable_telnet INTEGER NOT NULL DEFAULT 0,
|
||||
ssh_port INTEGER DEFAULT 22,
|
||||
rdp_port INTEGER DEFAULT 3389,
|
||||
vnc_port INTEGER DEFAULT 5900,
|
||||
telnet_port INTEGER DEFAULT 23,
|
||||
rdp_credential_id INTEGER,
|
||||
rdp_user TEXT,
|
||||
rdp_password TEXT,
|
||||
rdp_domain TEXT,
|
||||
rdp_security TEXT,
|
||||
rdp_ignore_cert INTEGER DEFAULT 0,
|
||||
vnc_credential_id INTEGER,
|
||||
vnc_password TEXT,
|
||||
vnc_user TEXT,
|
||||
telnet_user TEXT,
|
||||
telnet_password TEXT,
|
||||
telnet_credential_id INTEGER,
|
||||
rdp_auth_type TEXT,
|
||||
vnc_auth_type TEXT,
|
||||
telnet_auth_type TEXT,
|
||||
domain TEXT,
|
||||
security TEXT,
|
||||
ignore_cert INTEGER DEFAULT 0,
|
||||
guacamole_config TEXT,
|
||||
use_socks5 INTEGER,
|
||||
socks5_host TEXT,
|
||||
socks5_port INTEGER,
|
||||
socks5_username TEXT,
|
||||
socks5_password TEXT,
|
||||
socks5_proxy_chain TEXT,
|
||||
mac_address TEXT,
|
||||
wol_broadcast_address TEXT,
|
||||
port_knock_sequence TEXT,
|
||||
host_key_fingerprint TEXT,
|
||||
host_key_type TEXT,
|
||||
host_key_algorithm TEXT DEFAULT 'sha256',
|
||||
host_key_first_seen TEXT,
|
||||
host_key_last_verified TEXT,
|
||||
host_key_changed_count INTEGER DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (credential_id) REFERENCES ssh_credentials(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE TABLE host_access (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_id INTEGER NOT NULL,
|
||||
user_id TEXT,
|
||||
role_id INTEGER,
|
||||
granted_by TEXT NOT NULL,
|
||||
permission_level TEXT NOT NULL DEFAULT 'view',
|
||||
expires_at TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_accessed_at TEXT,
|
||||
access_count INTEGER NOT NULL DEFAULT 0,
|
||||
override_credential_id INTEGER,
|
||||
FOREIGN KEY (host_id) REFERENCES ssh_data(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (granted_by) REFERENCES users(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (override_credential_id) REFERENCES ssh_credentials(id) ON DELETE SET NULL
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_credential_usage (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
credential_id INTEGER NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
used_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (credential_id) REFERENCES ssh_credentials(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (host_id) REFERENCES ssh_data(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash) VALUES
|
||||
('user-1', 'user', 'hash'),
|
||||
('user-2', 'other', 'hash');
|
||||
`);
|
||||
|
||||
return {
|
||||
credentials: new CredentialRepository(context, onCredentialWrite),
|
||||
hosts: new HostRepository(context, onHostWrite),
|
||||
sqlite: context.sqlite!,
|
||||
};
|
||||
}
|
||||
|
||||
it("creates, finds, updates, lists, and deletes credentials", async () => {
|
||||
const repo = await createRepositories();
|
||||
|
||||
const created = await repo.credentials.create({
|
||||
userId: "user-1",
|
||||
name: "primary",
|
||||
authType: "password",
|
||||
username: "root",
|
||||
password: "secret",
|
||||
folder: "prod",
|
||||
});
|
||||
|
||||
expect(created.id).toBeGreaterThan(0);
|
||||
expect(await repo.credentials.listFolders("user-1")).toEqual(["prod"]);
|
||||
expect(
|
||||
(await repo.credentials.findByIdForUser("user-1", created.id))?.name,
|
||||
).toBe("primary");
|
||||
expect((await repo.credentials.findById(created.id))?.name).toBe("primary");
|
||||
|
||||
const updated = await repo.credentials.updateForUser("user-1", created.id, {
|
||||
folder: "ops",
|
||||
tags: "linux,admin",
|
||||
});
|
||||
expect(updated?.folder).toBe("ops");
|
||||
|
||||
expect(
|
||||
await repo.credentials.findByIdForUser("user-2", created.id),
|
||||
).toBeNull();
|
||||
expect(await repo.credentials.deleteForUser("user-1", created.id)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
await repo.credentials.findByIdForUser("user-1", created.id),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("deletes user credentials through the cleanup boundary", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const repo = await createRepositories(onWrite);
|
||||
|
||||
await repo.credentials.create({
|
||||
userId: "user-1",
|
||||
name: "primary",
|
||||
authType: "password",
|
||||
});
|
||||
await repo.credentials.create({
|
||||
userId: "user-1",
|
||||
name: "secondary",
|
||||
authType: "key",
|
||||
});
|
||||
await repo.credentials.create({
|
||||
userId: "user-2",
|
||||
name: "other",
|
||||
authType: "password",
|
||||
});
|
||||
onWrite.mockClear();
|
||||
|
||||
await expect(repo.credentials.deleteByUserId("user-1")).resolves.toBe(2);
|
||||
|
||||
expect(await repo.credentials.listByUserId("user-1")).toEqual([]);
|
||||
expect((await repo.credentials.listByUserId("user-2")).length).toBe(1);
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("loads credentials through the decryption boundary", async () => {
|
||||
const repo = await createRepositories();
|
||||
vi.spyOn(DataCrypto, "getUserDataKey").mockReturnValue(
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
vi.spyOn(DataCrypto, "decryptRecords").mockImplementation(
|
||||
(_tableName, records) => records,
|
||||
);
|
||||
vi.spyOn(DataCrypto, "decryptRecord").mockImplementation(
|
||||
(_tableName, record) => record,
|
||||
);
|
||||
|
||||
const created = await repo.credentials.create({
|
||||
userId: "user-1",
|
||||
name: "primary",
|
||||
authType: "password",
|
||||
username: "root",
|
||||
password: "secret",
|
||||
folder: "prod",
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.credentials.listDecryptedByUserId("user-1"),
|
||||
).resolves.toMatchObject([{ id: created.id, password: "secret" }]);
|
||||
await expect(
|
||||
repo.credentials.findDecryptedByIdForUser("user-1", created.id),
|
||||
).resolves.toMatchObject({ id: created.id, password: "secret" });
|
||||
expect(DataCrypto.decryptRecords).toHaveBeenCalledWith(
|
||||
"ssh_credentials",
|
||||
expect.arrayContaining([expect.objectContaining({ id: created.id })]),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_credentials",
|
||||
expect.objectContaining({ id: created.id }),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
});
|
||||
|
||||
it("encrypts credential writes with the user key", async () => {
|
||||
const repo = await createRepositories();
|
||||
vi.spyOn(DataCrypto, "validateUserAccess").mockReturnValue(
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
vi.spyOn(DataCrypto, "getUserDataKey").mockReturnValue(
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
vi.spyOn(DataCrypto, "encryptRecord").mockImplementation(
|
||||
(_tableName, record) =>
|
||||
({
|
||||
...record,
|
||||
password: "user-encrypted-password",
|
||||
}) as typeof record,
|
||||
);
|
||||
vi.spyOn(DataCrypto, "decryptRecord").mockImplementation(
|
||||
(_tableName, record) => record,
|
||||
);
|
||||
|
||||
const created = await repo.credentials.createEncryptedForUser("user-1", {
|
||||
userId: "user-1",
|
||||
name: "primary",
|
||||
authType: "password",
|
||||
username: "root",
|
||||
password: "secret",
|
||||
});
|
||||
|
||||
const raw = repo.sqlite
|
||||
.prepare("SELECT password FROM ssh_credentials WHERE id = ?")
|
||||
.get(created.id) as { password: string };
|
||||
|
||||
expect(raw.password).toBe("user-encrypted-password");
|
||||
|
||||
await repo.credentials.updateEncryptedForUser("user-1", created.id, {
|
||||
password: "updated-secret",
|
||||
});
|
||||
|
||||
const updatedRaw = repo.sqlite
|
||||
.prepare("SELECT password FROM ssh_credentials WHERE id = ?")
|
||||
.get(created.id) as { password: string };
|
||||
|
||||
expect(updatedRaw.password).toBe("user-encrypted-password");
|
||||
expect(DataCrypto.encryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_credentials",
|
||||
expect.objectContaining({ password: "updated-secret" }),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
});
|
||||
|
||||
it("checks credential import identity", async () => {
|
||||
const repo = await createRepositories();
|
||||
|
||||
await repo.credentials.create({
|
||||
userId: "user-1",
|
||||
name: "primary",
|
||||
authType: "password",
|
||||
username: "root",
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.credentials.existsForImportIdentity("user-1", "primary", "root"),
|
||||
).resolves.toBe(true);
|
||||
await expect(
|
||||
repo.credentials.existsForImportIdentity("user-1", "primary", "admin"),
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("renames credential folders through the write boundary", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const repo = await createRepositories(onWrite);
|
||||
|
||||
await repo.credentials.create({
|
||||
userId: "user-1",
|
||||
name: "primary",
|
||||
authType: "password",
|
||||
folder: "prod",
|
||||
});
|
||||
await repo.credentials.create({
|
||||
userId: "user-1",
|
||||
name: "secondary",
|
||||
authType: "key",
|
||||
folder: "prod",
|
||||
});
|
||||
await repo.credentials.create({
|
||||
userId: "user-2",
|
||||
name: "other",
|
||||
authType: "password",
|
||||
folder: "prod",
|
||||
});
|
||||
onWrite.mockClear();
|
||||
|
||||
await expect(
|
||||
repo.credentials.renameFolder("user-1", "prod", "ops"),
|
||||
).resolves.toBe(2);
|
||||
|
||||
expect(await repo.credentials.listFolders("user-1")).toEqual(["ops"]);
|
||||
expect(await repo.credentials.listFolders("user-2")).toEqual(["prod"]);
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("returns empty credential reads when user data is locked", async () => {
|
||||
const repo = await createRepositories();
|
||||
vi.spyOn(DataCrypto, "getUserDataKey").mockReturnValue(null);
|
||||
|
||||
const created = await repo.credentials.create({
|
||||
userId: "user-1",
|
||||
name: "primary",
|
||||
authType: "password",
|
||||
username: "root",
|
||||
password: "secret",
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.credentials.listDecryptedByUserId("user-1"),
|
||||
).resolves.toEqual([]);
|
||||
await expect(
|
||||
repo.credentials.findDecryptedByIdForUser("user-1", created.id),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("creates, finds, updates, lists, and deletes hosts", async () => {
|
||||
const repo = await createRepositories();
|
||||
|
||||
const host = await repo.hosts.create({
|
||||
userId: "user-1",
|
||||
name: "web-1",
|
||||
ip: "10.0.0.10",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
});
|
||||
|
||||
expect(host.id).toBeGreaterThan(0);
|
||||
expect((await repo.hosts.findById(host.id))?.name).toBe("web-1");
|
||||
expect(
|
||||
(await repo.hosts.listByUserId("user-1")).map((item) => item.id),
|
||||
).toEqual([host.id]);
|
||||
|
||||
const updated = await repo.hosts.updateForUser("user-1", host.id, {
|
||||
name: "web-1-renamed",
|
||||
folder: "prod",
|
||||
});
|
||||
expect(updated?.name).toBe("web-1-renamed");
|
||||
expect(await repo.hosts.findByIdForUser("user-2", host.id)).toBeNull();
|
||||
|
||||
expect(await repo.hosts.deleteForUser("user-1", host.id)).toBe(true);
|
||||
expect(await repo.hosts.findById(host.id)).toBeNull();
|
||||
});
|
||||
|
||||
it("encrypts host writes through the repository boundary", async () => {
|
||||
const repo = await createRepositories();
|
||||
vi.spyOn(DataCrypto, "validateUserAccess").mockReturnValue(
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
vi.spyOn(DataCrypto, "encryptRecord").mockImplementation(
|
||||
(_tableName, record) =>
|
||||
({
|
||||
...record,
|
||||
password: "encrypted-host-password",
|
||||
}) as typeof record,
|
||||
);
|
||||
vi.spyOn(DataCrypto, "decryptRecord").mockImplementation(
|
||||
(_tableName, record) => record,
|
||||
);
|
||||
|
||||
const created = await repo.hosts.createEncryptedForUser("user-1", {
|
||||
userId: "user-1",
|
||||
name: "web-1",
|
||||
ip: "10.0.0.10",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
password: "secret",
|
||||
});
|
||||
|
||||
const raw = repo.sqlite
|
||||
.prepare("SELECT password FROM ssh_data WHERE id = ?")
|
||||
.get(created.id) as { password: string };
|
||||
|
||||
expect(raw.password).toBe("encrypted-host-password");
|
||||
|
||||
await repo.hosts.updateEncryptedForUser("user-1", created.id, {
|
||||
password: "updated-secret",
|
||||
});
|
||||
|
||||
const updatedRaw = repo.sqlite
|
||||
.prepare("SELECT password FROM ssh_data WHERE id = ?")
|
||||
.get(created.id) as { password: string };
|
||||
|
||||
expect(updatedRaw.password).toBe("encrypted-host-password");
|
||||
expect(DataCrypto.encryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.objectContaining({ password: "updated-secret" }),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
});
|
||||
|
||||
it("loads hosts through the decryption boundary", async () => {
|
||||
const repo = await createRepositories();
|
||||
vi.spyOn(DataCrypto, "getUserDataKey").mockReturnValue(
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
vi.spyOn(DataCrypto, "decryptRecords").mockImplementation(
|
||||
(_tableName, records) => records,
|
||||
);
|
||||
|
||||
const host = await repo.hosts.create({
|
||||
userId: "user-1",
|
||||
name: "web-1",
|
||||
ip: "10.0.0.10",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
password: "secret",
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.hosts.listDecryptedByUserId("user-1"),
|
||||
).resolves.toMatchObject([{ id: host.id, password: "secret" }]);
|
||||
expect(DataCrypto.decryptRecords).toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.arrayContaining([expect.objectContaining({ id: host.id })]),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
});
|
||||
|
||||
it("checks host import identity", async () => {
|
||||
const repo = await createRepositories();
|
||||
|
||||
await repo.hosts.create({
|
||||
userId: "user-1",
|
||||
name: "web-1",
|
||||
ip: "10.0.0.10",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.hosts.existsForImportIdentity("user-1", "10.0.0.10", 22, "root"),
|
||||
).resolves.toBe(true);
|
||||
await expect(
|
||||
repo.hosts.existsForImportIdentity("user-1", "10.0.0.10", 2222, "root"),
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("deletes user hosts through the cleanup boundary", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const repo = await createRepositories(undefined, onWrite);
|
||||
|
||||
await repo.hosts.create({
|
||||
userId: "user-1",
|
||||
name: "web-1",
|
||||
ip: "10.0.0.10",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
});
|
||||
await repo.hosts.create({
|
||||
userId: "user-1",
|
||||
name: "web-2",
|
||||
ip: "10.0.0.11",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
});
|
||||
await repo.hosts.create({
|
||||
userId: "user-2",
|
||||
name: "other",
|
||||
ip: "10.0.0.12",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
});
|
||||
onWrite.mockClear();
|
||||
|
||||
await expect(repo.hosts.deleteByUserId("user-1")).resolves.toBe(2);
|
||||
|
||||
expect(await repo.hosts.listByUserId("user-1")).toEqual([]);
|
||||
expect((await repo.hosts.listByUserId("user-2")).length).toBe(1);
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("lists bulk update state and updates multiple owned hosts", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const repo = await createRepositories(undefined, onWrite);
|
||||
|
||||
const first = await repo.hosts.create({
|
||||
userId: "user-1",
|
||||
name: "web-1",
|
||||
ip: "10.0.0.10",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
statsConfig: JSON.stringify({ cpu: true }),
|
||||
});
|
||||
const second = await repo.hosts.create({
|
||||
userId: "user-1",
|
||||
name: "web-2",
|
||||
ip: "10.0.0.11",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
});
|
||||
const other = await repo.hosts.create({
|
||||
userId: "user-2",
|
||||
name: "other",
|
||||
ip: "10.0.0.12",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
});
|
||||
onWrite.mockClear();
|
||||
|
||||
const states = await repo.hosts.listBulkUpdateState("user-1", [
|
||||
first.id,
|
||||
second.id,
|
||||
other.id,
|
||||
]);
|
||||
expect(states.map((state) => state.id)).toEqual([first.id, second.id]);
|
||||
|
||||
await expect(
|
||||
repo.hosts.updateManyForUser("user-1", [first.id, second.id, other.id], {
|
||||
folder: "ops",
|
||||
}),
|
||||
).resolves.toBe(2);
|
||||
expect((await repo.hosts.findById(first.id))?.folder).toBe("ops");
|
||||
expect((await repo.hosts.findById(other.id))?.folder).toBeNull();
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("records credential usage and increments usage counters", async () => {
|
||||
const repo = await createRepositories();
|
||||
const credential = await repo.credentials.create({
|
||||
userId: "user-1",
|
||||
name: "primary",
|
||||
authType: "password",
|
||||
});
|
||||
const host = await repo.hosts.create({
|
||||
userId: "user-1",
|
||||
name: "web-1",
|
||||
ip: "10.0.0.10",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "credential",
|
||||
credentialId: credential.id,
|
||||
});
|
||||
|
||||
await repo.credentials.recordUsage(
|
||||
"user-1",
|
||||
credential.id,
|
||||
host.id,
|
||||
"2026-06-26T00:00:00.000Z",
|
||||
);
|
||||
|
||||
const updated = await repo.credentials.findByIdForUser(
|
||||
"user-1",
|
||||
credential.id,
|
||||
);
|
||||
expect(updated?.usageCount).toBe(1);
|
||||
expect(updated?.lastUsed).toBe("2026-06-26T00:00:00.000Z");
|
||||
});
|
||||
|
||||
it("cleans host access before deleting a host", async () => {
|
||||
const repo = await createRepositories();
|
||||
const host = await repo.hosts.create({
|
||||
userId: "user-1",
|
||||
name: "shared-host",
|
||||
ip: "10.0.0.20",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
});
|
||||
|
||||
repo.sqlite
|
||||
.prepare(
|
||||
"INSERT INTO host_access (host_id, user_id, granted_by) VALUES (?, ?, ?)",
|
||||
)
|
||||
.run(host.id, "user-2", "user-1");
|
||||
|
||||
expect(await repo.hosts.deleteAccessForHost(host.id)).toBe(1);
|
||||
expect(await repo.hosts.deleteForUser("user-1", host.id)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { HostFolderRepository } from "../../../database/repositories/host-folder-repository.js";
|
||||
|
||||
describe("HostFolderRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<{
|
||||
repository: HostFolderRepository;
|
||||
sqlite: NonNullable<
|
||||
Awaited<ReturnType<TestSqliteDatabase["connect"]>>["sqlite"]
|
||||
>;
|
||||
}> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_credentials (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
folder TEXT,
|
||||
auth_type TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
connection_type TEXT NOT NULL DEFAULT 'ssh',
|
||||
name TEXT,
|
||||
ip TEXT NOT NULL,
|
||||
port INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
folder TEXT,
|
||||
tags TEXT,
|
||||
pin INTEGER NOT NULL DEFAULT 0,
|
||||
auth_type TEXT NOT NULL,
|
||||
use_warpgate INTEGER NOT NULL DEFAULT 0,
|
||||
force_keyboard_interactive TEXT,
|
||||
password TEXT,
|
||||
key TEXT,
|
||||
key_password TEXT,
|
||||
key_type TEXT,
|
||||
sudo_password TEXT,
|
||||
autostart_password TEXT,
|
||||
autostart_key TEXT,
|
||||
autostart_key_password TEXT,
|
||||
credential_id INTEGER,
|
||||
override_credential_username INTEGER,
|
||||
vault_profile_id INTEGER,
|
||||
enable_terminal INTEGER NOT NULL DEFAULT 1,
|
||||
enable_session_logging INTEGER NOT NULL DEFAULT 1,
|
||||
enable_command_history INTEGER NOT NULL DEFAULT 1,
|
||||
enable_tunnel INTEGER NOT NULL DEFAULT 1,
|
||||
tunnel_connections TEXT,
|
||||
jump_hosts TEXT,
|
||||
enable_file_manager INTEGER NOT NULL DEFAULT 1,
|
||||
scp_legacy INTEGER NOT NULL DEFAULT 0,
|
||||
enable_docker INTEGER NOT NULL DEFAULT 0,
|
||||
enable_tmux_monitor INTEGER NOT NULL DEFAULT 0,
|
||||
show_terminal_in_sidebar INTEGER NOT NULL DEFAULT 1,
|
||||
show_file_manager_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_tunnel_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_docker_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_server_stats_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
default_path TEXT,
|
||||
stats_config TEXT,
|
||||
docker_config TEXT,
|
||||
enable_proxmox INTEGER NOT NULL DEFAULT 0,
|
||||
proxmox_config TEXT,
|
||||
terminal_config TEXT,
|
||||
quick_actions TEXT,
|
||||
notes TEXT,
|
||||
enable_ssh INTEGER NOT NULL DEFAULT 1,
|
||||
enable_rdp INTEGER NOT NULL DEFAULT 0,
|
||||
enable_vnc INTEGER NOT NULL DEFAULT 0,
|
||||
enable_telnet INTEGER NOT NULL DEFAULT 0,
|
||||
ssh_port INTEGER DEFAULT 22,
|
||||
rdp_port INTEGER DEFAULT 3389,
|
||||
vnc_port INTEGER DEFAULT 5900,
|
||||
telnet_port INTEGER DEFAULT 23,
|
||||
rdp_credential_id INTEGER,
|
||||
rdp_user TEXT,
|
||||
rdp_password TEXT,
|
||||
rdp_domain TEXT,
|
||||
rdp_security TEXT,
|
||||
rdp_ignore_cert INTEGER DEFAULT 0,
|
||||
vnc_credential_id INTEGER,
|
||||
vnc_password TEXT,
|
||||
vnc_user TEXT,
|
||||
telnet_user TEXT,
|
||||
telnet_password TEXT,
|
||||
telnet_credential_id INTEGER,
|
||||
rdp_auth_type TEXT,
|
||||
vnc_auth_type TEXT,
|
||||
telnet_auth_type TEXT,
|
||||
domain TEXT,
|
||||
security TEXT,
|
||||
ignore_cert INTEGER DEFAULT 0,
|
||||
guacamole_config TEXT,
|
||||
use_socks5 INTEGER,
|
||||
socks5_host TEXT,
|
||||
socks5_port INTEGER,
|
||||
socks5_username TEXT,
|
||||
socks5_password TEXT,
|
||||
socks5_proxy_chain TEXT,
|
||||
mac_address TEXT,
|
||||
wol_broadcast_address TEXT,
|
||||
port_knock_sequence TEXT,
|
||||
host_key_fingerprint TEXT,
|
||||
host_key_type TEXT,
|
||||
host_key_algorithm TEXT DEFAULT 'sha256',
|
||||
host_key_first_seen TEXT,
|
||||
host_key_last_verified TEXT,
|
||||
host_key_changed_count INTEGER DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_folders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
color TEXT,
|
||||
icon TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO ssh_data (id, user_id, name, ip, port, username, folder, auth_type)
|
||||
VALUES
|
||||
(1, 'user-1', 'one', '10.0.0.1', 22, 'root', 'prod', 'password'),
|
||||
(2, 'user-1', 'two', '10.0.0.2', 22, 'root', 'prod / api', 'password'),
|
||||
(3, 'user-2', 'other', '10.0.0.3', 22, 'root', 'prod', 'password');
|
||||
INSERT INTO ssh_credentials (id, user_id, name, folder, auth_type)
|
||||
VALUES
|
||||
(1, 'user-1', 'cred-one', 'prod', 'password'),
|
||||
(2, 'user-1', 'cred-two', 'prod / api', 'password'),
|
||||
(3, 'user-2', 'cred-other', 'prod', 'password');
|
||||
INSERT INTO ssh_folders (id, user_id, name, color, icon)
|
||||
VALUES
|
||||
(1, 'user-1', 'prod', '#111111', 'server'),
|
||||
(2, 'user-1', 'prod / api', '#222222', 'box'),
|
||||
(3, 'user-2', 'prod', '#333333', 'user');
|
||||
`);
|
||||
|
||||
return {
|
||||
repository: new HostFolderRepository(context, onWrite),
|
||||
sqlite: context.sqlite!,
|
||||
};
|
||||
}
|
||||
|
||||
it("renames folders across hosts, credentials, and folder records", async () => {
|
||||
let writes = 0;
|
||||
const { repository, sqlite } = await createRepository(() => {
|
||||
writes += 1;
|
||||
});
|
||||
|
||||
await expect(
|
||||
repository.renameFolder(
|
||||
"user-1",
|
||||
"prod",
|
||||
"ops",
|
||||
"2026-01-01T00:00:00.000Z",
|
||||
),
|
||||
).resolves.toEqual({ updatedHosts: 2, updatedCredentials: 2 });
|
||||
|
||||
expect(
|
||||
sqlite
|
||||
.prepare("SELECT folder FROM ssh_data WHERE user_id = ? ORDER BY id")
|
||||
.all("user-1"),
|
||||
).toEqual([{ folder: "ops" }, { folder: "ops / api" }]);
|
||||
expect(
|
||||
sqlite
|
||||
.prepare(
|
||||
"SELECT folder FROM ssh_credentials WHERE user_id = ? ORDER BY id",
|
||||
)
|
||||
.all("user-1"),
|
||||
).toEqual([{ folder: "ops" }, { folder: "ops / api" }]);
|
||||
expect(
|
||||
sqlite
|
||||
.prepare("SELECT name FROM ssh_folders WHERE user_id = ? ORDER BY id")
|
||||
.all("user-1"),
|
||||
).toEqual([{ name: "ops" }, { name: "ops / api" }]);
|
||||
expect(writes).toBe(1);
|
||||
});
|
||||
|
||||
it("lists folders and upserts metadata", async () => {
|
||||
let writes = 0;
|
||||
const { repository } = await createRepository(() => {
|
||||
writes += 1;
|
||||
});
|
||||
|
||||
await expect(repository.listFolders("user-1")).resolves.toHaveLength(2);
|
||||
await expect(
|
||||
repository.upsertMetadata(
|
||||
"user-1",
|
||||
"prod",
|
||||
"#abcdef",
|
||||
"folder",
|
||||
"2026-02-01T00:00:00.000Z",
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
created: false,
|
||||
folder: { color: "#abcdef", icon: "folder" },
|
||||
});
|
||||
await expect(
|
||||
repository.upsertMetadata(
|
||||
"user-1",
|
||||
"new",
|
||||
null,
|
||||
null,
|
||||
"2026-03-01T00:00:00.000Z",
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
created: true,
|
||||
folder: { name: "new" },
|
||||
});
|
||||
expect(writes).toBe(2);
|
||||
});
|
||||
|
||||
it("lists and deletes hosts and folder records in a folder tree", async () => {
|
||||
let writes = 0;
|
||||
const { repository, sqlite } = await createRepository(() => {
|
||||
writes += 1;
|
||||
});
|
||||
|
||||
const hostsToDelete = await repository.listHostsInFolder("user-1", "prod");
|
||||
expect(hostsToDelete.map((host) => host.id)).toEqual([1, 2]);
|
||||
|
||||
await repository.deleteHostsAndFolderRecords("user-1", "prod");
|
||||
|
||||
expect(sqlite.prepare("SELECT id FROM ssh_data ORDER BY id").all()).toEqual(
|
||||
[{ id: 3 }],
|
||||
);
|
||||
expect(
|
||||
sqlite.prepare("SELECT id FROM ssh_folders ORDER BY id").all(),
|
||||
).toEqual([{ id: 3 }]);
|
||||
expect(writes).toBe(1);
|
||||
});
|
||||
|
||||
it("deletes folder records for a user", async () => {
|
||||
let writes = 0;
|
||||
const { repository, sqlite } = await createRepository(() => {
|
||||
writes += 1;
|
||||
});
|
||||
|
||||
await expect(repository.deleteByUserId("user-1")).resolves.toBe(2);
|
||||
|
||||
expect(sqlite.prepare("SELECT id FROM ssh_data ORDER BY id").all()).toEqual(
|
||||
[{ id: 1 }, { id: 2 }, { id: 3 }],
|
||||
);
|
||||
expect(
|
||||
sqlite.prepare("SELECT id FROM ssh_folders ORDER BY id").all(),
|
||||
).toEqual([{ id: 3 }]);
|
||||
expect(writes).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { HostHealthRepository } from "../../../database/repositories/host-health-repository.js";
|
||||
|
||||
describe("HostHealthRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<HostHealthRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE hosts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE host_health_checks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
checks TEXT NOT NULL,
|
||||
interval_seconds INTEGER NOT NULL DEFAULT 300,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE host_health_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
check_id TEXT NOT NULL,
|
||||
ts TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
ok INTEGER NOT NULL,
|
||||
latency_ms INTEGER,
|
||||
detail TEXT
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO hosts (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'one'), (2, 'user-2', 'two');
|
||||
INSERT INTO host_health_checks (
|
||||
user_id, host_id, checks, interval_seconds, created_at, updated_at
|
||||
)
|
||||
VALUES (
|
||||
'user-1',
|
||||
1,
|
||||
'[{"id":"tcp","name":"TCP","type":"tcp","target":"localhost","port":22}]',
|
||||
300,
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z'
|
||||
);
|
||||
`);
|
||||
|
||||
return new HostHealthRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("finds and upserts check configuration", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const existing = await repo.findChecksByUserAndHost("user-1", 1);
|
||||
expect(existing?.intervalSeconds).toBe(300);
|
||||
|
||||
const updated = await repo.upsertChecks(
|
||||
"user-1",
|
||||
1,
|
||||
'[{"id":"http"}]',
|
||||
60,
|
||||
"2026-02-01T00:00:00.000Z",
|
||||
);
|
||||
expect(updated).toMatchObject({
|
||||
id: existing?.id,
|
||||
checks: '[{"id":"http"}]',
|
||||
intervalSeconds: 60,
|
||||
updatedAt: "2026-02-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const created = await repo.upsertChecks(
|
||||
"user-2",
|
||||
2,
|
||||
'[{"id":"tcp"}]',
|
||||
120,
|
||||
"2026-03-01T00:00:00.000Z",
|
||||
);
|
||||
expect(created).toMatchObject({
|
||||
userId: "user-2",
|
||||
hostId: 2,
|
||||
checks: '[{"id":"tcp"}]',
|
||||
intervalSeconds: 120,
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
updatedAt: "2026-03-01T00:00:00.000Z",
|
||||
});
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("records and prunes history", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(
|
||||
await repo.recordHistory(
|
||||
"user-1",
|
||||
1,
|
||||
[{ checkId: "one", ok: true, latencyMs: 12, detail: "open" }],
|
||||
1,
|
||||
"2026-01-01T00:00:00.000Z",
|
||||
),
|
||||
).toBe(1);
|
||||
expect(
|
||||
await repo.recordHistory(
|
||||
"user-1",
|
||||
1,
|
||||
[{ checkId: "two", ok: false, latencyMs: null, detail: "closed" }],
|
||||
1,
|
||||
"2026-01-02T00:00:00.000Z",
|
||||
),
|
||||
).toBe(1);
|
||||
|
||||
const history = await repo.listHistory("user-1", 1, 10);
|
||||
expect(history).toHaveLength(1);
|
||||
expect(history[0]).toMatchObject({
|
||||
userId: "user-1",
|
||||
hostId: 1,
|
||||
checkId: "two",
|
||||
ok: false,
|
||||
latencyMs: null,
|
||||
detail: "closed",
|
||||
});
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("deletes all health checks and history for a user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsertChecks("user-2", 2, '[{"id":"tcp"}]', 120);
|
||||
await repo.recordHistory(
|
||||
"user-1",
|
||||
1,
|
||||
[{ checkId: "one", ok: true, latencyMs: 12, detail: "open" }],
|
||||
10,
|
||||
);
|
||||
await repo.recordHistory(
|
||||
"user-2",
|
||||
2,
|
||||
[{ checkId: "two", ok: false, latencyMs: null, detail: "closed" }],
|
||||
10,
|
||||
);
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toEqual({
|
||||
checksDeleted: 1,
|
||||
historyDeleted: 1,
|
||||
});
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toEqual({
|
||||
checksDeleted: 0,
|
||||
historyDeleted: 0,
|
||||
});
|
||||
|
||||
expect(await repo.findChecksByUserAndHost("user-1", 1)).toBeNull();
|
||||
expect(await repo.listHistory("user-1", 1, 10)).toEqual([]);
|
||||
expect((await repo.findChecksByUserAndHost("user-2", 2))?.hostId).toBe(2);
|
||||
expect(await repo.listHistory("user-2", 2, 10)).toHaveLength(1);
|
||||
expect(writeCount).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { HostMetricsHistoryRepository } from "../../../database/repositories/host-metrics-history-repository.js";
|
||||
|
||||
describe("HostMetricsHistoryRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<HostMetricsHistoryRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE hosts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE host_metrics_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_id INTEGER NOT NULL,
|
||||
ts TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
cpu_percent REAL,
|
||||
mem_percent REAL,
|
||||
disk_percent REAL,
|
||||
net_rx_bytes INTEGER,
|
||||
net_tx_bytes INTEGER
|
||||
);
|
||||
|
||||
INSERT INTO hosts (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'one'), (2, 'user-2', 'two');
|
||||
INSERT INTO host_metrics_history (
|
||||
host_id, ts, cpu_percent, mem_percent, disk_percent, net_rx_bytes, net_tx_bytes
|
||||
)
|
||||
VALUES
|
||||
(1, '2026-01-01 00:00:00', 10, 20, 30, 100, 200),
|
||||
(1, '2026-01-02 00:00:00', 11, 21, 31, 101, 201),
|
||||
(1, '2999-01-01 00:00:00', 12, 22, 32, 102, 202),
|
||||
(2, '2026-01-02 00:00:00', 99, 99, 99, 999, 999);
|
||||
`);
|
||||
|
||||
return new HostMetricsHistoryRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates and lists metrics history rows by range", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.create({
|
||||
hostId: 1,
|
||||
cpuPercent: 12,
|
||||
memPercent: 22,
|
||||
diskPercent: 32,
|
||||
netRxBytes: 102,
|
||||
netTxBytes: 202,
|
||||
});
|
||||
|
||||
const rows = await repo.listRange(
|
||||
1,
|
||||
"2026-01-01 00:00:00",
|
||||
"2026-01-02 23:59:59",
|
||||
);
|
||||
|
||||
expect(rows.map((row) => row.cpuPercent)).toEqual([10, 11]);
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("prunes old history for a host only", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
repo.pruneOlderThan(1, 1);
|
||||
|
||||
const rows = await repo.listRange(
|
||||
1,
|
||||
"2000-01-01 00:00:00",
|
||||
"2999-12-31 23:59:59",
|
||||
);
|
||||
expect(rows.map((row) => row.ts)).toEqual(["2999-01-01 00:00:00"]);
|
||||
expect(
|
||||
await repo.listRange(2, "2026-01-01 00:00:00", "2026-01-03 00:00:00"),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { HostMetricsPreferenceRepository } from "../../../database/repositories/host-metrics-preference-repository.js";
|
||||
|
||||
describe("HostMetricsPreferenceRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<HostMetricsPreferenceRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
stats_config TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE host_metrics_preferences (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
layout TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO ssh_data (id, user_id, name, stats_config)
|
||||
VALUES (1, 'user-1', 'one', '{}'), (2, 'user-2', 'two', '{}');
|
||||
INSERT INTO host_metrics_preferences (
|
||||
user_id, host_id, layout, created_at, updated_at
|
||||
)
|
||||
VALUES (
|
||||
'user-1',
|
||||
1,
|
||||
'{"slots":[],"columns":3}',
|
||||
'2026-01-01T00:00:00.000Z',
|
||||
'2026-01-01T00:00:00.000Z'
|
||||
);
|
||||
`);
|
||||
|
||||
return new HostMetricsPreferenceRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("finds a saved layout by user and host", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const existing = await repo.findByUserAndHost("user-1", 1);
|
||||
expect(existing?.layout).toBe('{"slots":[],"columns":3}');
|
||||
expect(await repo.findByUserAndHost("user-1", 2)).toBeNull();
|
||||
});
|
||||
|
||||
it("updates and inserts layouts with write notifications", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const updated = await repo.upsertLayout(
|
||||
"user-1",
|
||||
1,
|
||||
'{"slots":[{"id":"cpu"}],"columns":2}',
|
||||
"2026-02-01T00:00:00.000Z",
|
||||
);
|
||||
expect(updated).toMatchObject({
|
||||
id: 1,
|
||||
layout: '{"slots":[{"id":"cpu"}],"columns":2}',
|
||||
updatedAt: "2026-02-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const created = await repo.upsertLayout(
|
||||
"user-2",
|
||||
2,
|
||||
'{"slots":[{"id":"mem"}],"columns":1}',
|
||||
"2026-03-01T00:00:00.000Z",
|
||||
);
|
||||
expect(created).toMatchObject({
|
||||
userId: "user-2",
|
||||
hostId: 2,
|
||||
layout: '{"slots":[{"id":"mem"}],"columns":1}',
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
updatedAt: "2026-03-01T00:00:00.000Z",
|
||||
});
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("updates host stats config for the owning user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.updateHostStatsConfig(
|
||||
"user-1",
|
||||
1,
|
||||
'{"enabledWidgets":["cpu","memory"]}',
|
||||
),
|
||||
).resolves.toBe(true);
|
||||
await expect(
|
||||
repo.updateHostStatsConfig("user-2", 1, '{"enabledWidgets":["disk"]}'),
|
||||
).resolves.toBe(false);
|
||||
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("deletes all metric preferences for a user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsertLayout("user-2", 2, '{"slots":["mem"]}');
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toBe(1);
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
|
||||
|
||||
expect(await repo.findByUserAndHost("user-1", 1)).toBeNull();
|
||||
expect((await repo.findByUserAndHost("user-2", 2))?.layout).toBe(
|
||||
'{"slots":["mem"]}',
|
||||
);
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,495 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { DataCrypto } from "../../../utils/data-crypto.js";
|
||||
import { HostResolutionRepository } from "../../../database/repositories/host-resolution-repository.js";
|
||||
|
||||
vi.mock("../../../utils/data-crypto.js", () => ({
|
||||
DataCrypto: {
|
||||
getUserDataKey: vi.fn(),
|
||||
decryptRecord: vi.fn((_tableName, record) => record),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("HostResolutionRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
vi.mocked(DataCrypto.getUserDataKey).mockReset();
|
||||
vi.mocked(DataCrypto.decryptRecord).mockClear();
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<HostResolutionRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
connection_type TEXT NOT NULL DEFAULT 'ssh',
|
||||
name TEXT,
|
||||
ip TEXT NOT NULL,
|
||||
port INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
folder TEXT,
|
||||
tags TEXT,
|
||||
pin INTEGER NOT NULL DEFAULT 0,
|
||||
auth_type TEXT NOT NULL,
|
||||
use_warpgate INTEGER NOT NULL DEFAULT 0,
|
||||
force_keyboard_interactive TEXT,
|
||||
password TEXT,
|
||||
key TEXT,
|
||||
key_password TEXT,
|
||||
key_type TEXT,
|
||||
sudo_password TEXT,
|
||||
autostart_password TEXT,
|
||||
autostart_key TEXT,
|
||||
autostart_key_password TEXT,
|
||||
credential_id INTEGER,
|
||||
override_credential_username INTEGER,
|
||||
vault_profile_id INTEGER,
|
||||
enable_terminal INTEGER NOT NULL DEFAULT 1,
|
||||
enable_session_logging INTEGER NOT NULL DEFAULT 1,
|
||||
enable_command_history INTEGER NOT NULL DEFAULT 1,
|
||||
enable_tunnel INTEGER NOT NULL DEFAULT 1,
|
||||
tunnel_connections TEXT,
|
||||
jump_hosts TEXT,
|
||||
enable_file_manager INTEGER NOT NULL DEFAULT 1,
|
||||
scp_legacy INTEGER NOT NULL DEFAULT 0,
|
||||
enable_docker INTEGER NOT NULL DEFAULT 0,
|
||||
enable_tmux_monitor INTEGER NOT NULL DEFAULT 0,
|
||||
show_terminal_in_sidebar INTEGER NOT NULL DEFAULT 1,
|
||||
show_file_manager_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_tunnel_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_docker_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_server_stats_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
default_path TEXT,
|
||||
stats_config TEXT,
|
||||
docker_config TEXT,
|
||||
enable_proxmox INTEGER NOT NULL DEFAULT 0,
|
||||
proxmox_config TEXT,
|
||||
terminal_config TEXT,
|
||||
quick_actions TEXT,
|
||||
notes TEXT,
|
||||
enable_ssh INTEGER NOT NULL DEFAULT 1,
|
||||
enable_rdp INTEGER NOT NULL DEFAULT 0,
|
||||
enable_vnc INTEGER NOT NULL DEFAULT 0,
|
||||
enable_telnet INTEGER NOT NULL DEFAULT 0,
|
||||
ssh_port INTEGER DEFAULT 22,
|
||||
rdp_port INTEGER DEFAULT 3389,
|
||||
vnc_port INTEGER DEFAULT 5900,
|
||||
telnet_port INTEGER DEFAULT 23,
|
||||
rdp_credential_id INTEGER,
|
||||
rdp_user TEXT,
|
||||
rdp_password TEXT,
|
||||
rdp_domain TEXT,
|
||||
rdp_security TEXT,
|
||||
rdp_ignore_cert INTEGER DEFAULT 0,
|
||||
vnc_credential_id INTEGER,
|
||||
vnc_password TEXT,
|
||||
vnc_user TEXT,
|
||||
telnet_user TEXT,
|
||||
telnet_password TEXT,
|
||||
telnet_credential_id INTEGER,
|
||||
rdp_auth_type TEXT,
|
||||
vnc_auth_type TEXT,
|
||||
telnet_auth_type TEXT,
|
||||
domain TEXT,
|
||||
security TEXT,
|
||||
ignore_cert INTEGER DEFAULT 0,
|
||||
guacamole_config TEXT,
|
||||
use_socks5 INTEGER,
|
||||
socks5_host TEXT,
|
||||
socks5_port INTEGER,
|
||||
socks5_username TEXT,
|
||||
socks5_password TEXT,
|
||||
socks5_proxy_chain TEXT,
|
||||
mac_address TEXT,
|
||||
wol_broadcast_address TEXT,
|
||||
port_knock_sequence TEXT,
|
||||
host_key_fingerprint TEXT,
|
||||
host_key_type TEXT,
|
||||
host_key_algorithm TEXT DEFAULT 'sha256',
|
||||
host_key_first_seen TEXT,
|
||||
host_key_last_verified TEXT,
|
||||
host_key_changed_count INTEGER DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_credentials (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
folder TEXT,
|
||||
tags TEXT,
|
||||
auth_type TEXT NOT NULL,
|
||||
username TEXT,
|
||||
password TEXT,
|
||||
key TEXT,
|
||||
private_key TEXT,
|
||||
public_key TEXT,
|
||||
key_password TEXT,
|
||||
key_type TEXT,
|
||||
detected_key_type TEXT,
|
||||
cert_public_key TEXT,
|
||||
usage_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_used TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE host_access (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_id INTEGER NOT NULL,
|
||||
user_id TEXT,
|
||||
role_id INTEGER,
|
||||
granted_by TEXT NOT NULL,
|
||||
permission_level TEXT NOT NULL DEFAULT 'view',
|
||||
expires_at TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_accessed_at TEXT,
|
||||
access_count INTEGER NOT NULL DEFAULT 0,
|
||||
override_credential_id INTEGER
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO ssh_data (
|
||||
id, user_id, name, ip, port, username, auth_type, credential_id,
|
||||
tunnel_connections
|
||||
)
|
||||
VALUES
|
||||
(1, 'user-1', 'web', '10.0.0.1', 22, 'root', 'password', 7, '[{"autoStart":true}]'),
|
||||
(2, 'user-1', 'db', '10.0.0.2', 22, 'admin', 'none', NULL, NULL),
|
||||
(3, 'user-2', 'other', '10.0.0.3', 22, 'root', 'none', NULL, '[{"autoStart":false}]');
|
||||
INSERT INTO ssh_credentials (
|
||||
id, user_id, name, auth_type, username, password, private_key, key_password
|
||||
)
|
||||
VALUES
|
||||
(7, 'user-1', 'owner', 'password', 'root', 'secret', NULL, NULL),
|
||||
(8, 'user-2', 'override', 'key', 'alice', NULL, 'private', 'pass');
|
||||
INSERT INTO host_access (
|
||||
host_id, user_id, granted_by, permission_level, override_credential_id
|
||||
)
|
||||
VALUES (1, 'user-2', 'user-1', 'execute', 8);
|
||||
`);
|
||||
|
||||
return new HostResolutionRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("loads host and credential rows through the decryption boundary", async () => {
|
||||
vi.mocked(DataCrypto.getUserDataKey).mockReturnValue(
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
const repository = await createRepository();
|
||||
|
||||
await expect(repository.findHostById(1, "user-1")).resolves.toMatchObject({
|
||||
id: 1,
|
||||
userId: "user-1",
|
||||
name: "web",
|
||||
credentialId: 7,
|
||||
});
|
||||
await expect(
|
||||
repository.findHostByIdForUser(1, "user-1"),
|
||||
).resolves.toMatchObject({
|
||||
id: 1,
|
||||
userId: "user-1",
|
||||
name: "web",
|
||||
credentialId: 7,
|
||||
});
|
||||
await expect(
|
||||
repository.findHostByIdForUser(3, "user-1"),
|
||||
).resolves.toBeNull();
|
||||
await expect(
|
||||
repository.findCredentialByIdForUser(7, "user-1"),
|
||||
).resolves.toMatchObject({
|
||||
id: 7,
|
||||
userId: "user-1",
|
||||
username: "root",
|
||||
password: "secret",
|
||||
});
|
||||
await expect(
|
||||
repository.findCredentialByIdForOwnerDecryptedAs(7, "user-1", "user-2"),
|
||||
).resolves.toMatchObject({
|
||||
id: 7,
|
||||
userId: "user-1",
|
||||
username: "root",
|
||||
password: "secret",
|
||||
});
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.objectContaining({ id: 1 }),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_credentials",
|
||||
expect.objectContaining({ id: 7 }),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_credentials",
|
||||
expect.objectContaining({ id: 7 }),
|
||||
"user-2",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
});
|
||||
|
||||
it("lists user-owned hosts through the decryption boundary", async () => {
|
||||
vi.mocked(DataCrypto.getUserDataKey).mockReturnValue(
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
const repository = await createRepository();
|
||||
|
||||
const rows = await repository.findHostsByUserId("user-1");
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([1, 2]);
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.objectContaining({ id: 1 }),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.objectContaining({ id: 2 }),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
});
|
||||
|
||||
it("lists raw own and shared host rows for access list assembly", async () => {
|
||||
const repository = await createRepository();
|
||||
|
||||
const rows = await repository.listHostRowsForAccessList("user-2", [
|
||||
{ hostId: 1, permissionLevel: "execute", expiresAt: null },
|
||||
{ hostId: 3, permissionLevel: "view", expiresAt: null },
|
||||
{ hostId: 999, permissionLevel: "view", expiresAt: null },
|
||||
]);
|
||||
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(rows[0]).toMatchObject({
|
||||
id: 3,
|
||||
userId: "user-2",
|
||||
ownerId: "user-2",
|
||||
isShared: false,
|
||||
permissionLevel: undefined,
|
||||
expiresAt: undefined,
|
||||
});
|
||||
expect(rows[1]).toMatchObject({
|
||||
id: 1,
|
||||
userId: "user-1",
|
||||
ownerId: "user-1",
|
||||
isShared: true,
|
||||
permissionLevel: "execute",
|
||||
expiresAt: null,
|
||||
});
|
||||
expect(DataCrypto.decryptRecord).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("loads host owner metadata without decrypting host data", async () => {
|
||||
const repository = await createRepository();
|
||||
|
||||
await expect(repository.findHostOwnerId(1)).resolves.toBe("user-1");
|
||||
await expect(repository.findHostOwnerId(999)).resolves.toBeNull();
|
||||
await expect(repository.isHostOwnedByUser(1, "user-1")).resolves.toBe(true);
|
||||
await expect(repository.isHostOwnedByUser(1, "user-2")).resolves.toBe(
|
||||
false,
|
||||
);
|
||||
expect(DataCrypto.decryptRecord).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("loads host update state without decrypting host data", async () => {
|
||||
const repository = await createRepository();
|
||||
|
||||
await expect(repository.findHostUpdateState(1)).resolves.toEqual({
|
||||
userId: "user-1",
|
||||
credentialId: 7,
|
||||
rdpCredentialId: null,
|
||||
vncCredentialId: null,
|
||||
telnetCredentialId: null,
|
||||
vaultProfileId: null,
|
||||
authType: "password",
|
||||
});
|
||||
await expect(repository.findHostUpdateState(999)).resolves.toBeNull();
|
||||
expect(DataCrypto.decryptRecord).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lists hosts using a credential through the decryption boundary", async () => {
|
||||
vi.mocked(DataCrypto.getUserDataKey).mockReturnValue(
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
const repository = await createRepository();
|
||||
|
||||
const rows = await repository.listHostsUsingCredentialForUser("user-1", 7);
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([1]);
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.objectContaining({ id: 1 }),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
});
|
||||
|
||||
it("lists all hosts through each owner decryption boundary", async () => {
|
||||
vi.mocked(DataCrypto.getUserDataKey).mockImplementation((userId) =>
|
||||
Buffer.from(`${userId}-key`),
|
||||
);
|
||||
const repository = await createRepository();
|
||||
|
||||
const rows = await repository.listAllHosts();
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([1, 2, 3]);
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.objectContaining({ id: 1 }),
|
||||
"user-1",
|
||||
Buffer.from("user-1-key"),
|
||||
);
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.objectContaining({ id: 3 }),
|
||||
"user-2",
|
||||
Buffer.from("user-2-key"),
|
||||
);
|
||||
});
|
||||
|
||||
it("lists tunnel-enabled hosts with tunnel data through each owner decryption boundary", async () => {
|
||||
vi.mocked(DataCrypto.getUserDataKey).mockImplementation((userId) =>
|
||||
Buffer.from(`${userId}-key`),
|
||||
);
|
||||
const repository = await createRepository();
|
||||
|
||||
const rows = await repository.listHostsWithTunnelConnections();
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([1, 3]);
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.objectContaining({ id: 1 }),
|
||||
"user-1",
|
||||
Buffer.from("user-1-key"),
|
||||
);
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.objectContaining({ id: 3 }),
|
||||
"user-2",
|
||||
Buffer.from("user-2-key"),
|
||||
);
|
||||
});
|
||||
|
||||
it("skips owner-scoped host list rows when that user's data is locked", async () => {
|
||||
vi.mocked(DataCrypto.getUserDataKey).mockImplementation((userId) =>
|
||||
userId === "user-1" ? Buffer.from("user-1-key") : null,
|
||||
);
|
||||
const repository = await createRepository();
|
||||
|
||||
const rows = await repository.listAllHosts();
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([1, 2]);
|
||||
expect(DataCrypto.decryptRecord).not.toHaveBeenCalledWith(
|
||||
"ssh_data",
|
||||
expect.objectContaining({ id: 3 }),
|
||||
expect.any(String),
|
||||
expect.any(Buffer),
|
||||
);
|
||||
});
|
||||
|
||||
it("loads host key verification metadata without decrypting credentials", async () => {
|
||||
const repository = await createRepository();
|
||||
|
||||
const row = await repository.findHostKeyVerificationData(1);
|
||||
|
||||
expect(row).toMatchObject({
|
||||
hostKeyFingerprint: null,
|
||||
hostKeyType: null,
|
||||
hostKeyAlgorithm: "sha256",
|
||||
hostKeyChangedCount: 0,
|
||||
name: "web",
|
||||
});
|
||||
expect(DataCrypto.decryptRecord).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stores and updates host key verification metadata through the write boundary", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const repository = await createRepository(onWrite);
|
||||
|
||||
await repository.storeHostKey(
|
||||
1,
|
||||
"fingerprint-1",
|
||||
"ssh-rsa",
|
||||
"sha256",
|
||||
"t1",
|
||||
);
|
||||
await expect(
|
||||
repository.findHostKeyVerificationData(1),
|
||||
).resolves.toMatchObject({
|
||||
hostKeyFingerprint: "fingerprint-1",
|
||||
hostKeyType: "ssh-rsa",
|
||||
hostKeyAlgorithm: "sha256",
|
||||
hostKeyChangedCount: 0,
|
||||
});
|
||||
|
||||
await repository.touchHostKeyLastVerified(1, "t2");
|
||||
await repository.updateHostKey(
|
||||
1,
|
||||
"fingerprint-2",
|
||||
"ssh-ed25519",
|
||||
"sha256",
|
||||
0,
|
||||
"t3",
|
||||
);
|
||||
|
||||
await expect(
|
||||
repository.findHostKeyVerificationData(1),
|
||||
).resolves.toMatchObject({
|
||||
hostKeyFingerprint: "fingerprint-2",
|
||||
hostKeyType: "ssh-ed25519",
|
||||
hostKeyAlgorithm: "sha256",
|
||||
hostKeyChangedCount: 1,
|
||||
});
|
||||
expect(onWrite).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("returns null when user data is locked", async () => {
|
||||
vi.mocked(DataCrypto.getUserDataKey).mockReturnValue(null);
|
||||
const repository = await createRepository();
|
||||
|
||||
await expect(repository.findHostById(1, "user-1")).resolves.toBeNull();
|
||||
await expect(
|
||||
repository.findHostByIdForUser(1, "user-1"),
|
||||
).resolves.toBeNull();
|
||||
await expect(repository.findHostsByUserId("user-1")).resolves.toEqual([]);
|
||||
await expect(
|
||||
repository.listHostsUsingCredentialForUser("user-1", 7),
|
||||
).resolves.toEqual([]);
|
||||
await expect(
|
||||
repository.findCredentialByIdForUser(7, "user-1"),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("loads override credential ids for shared host resolution", async () => {
|
||||
const repository = await createRepository();
|
||||
|
||||
await expect(
|
||||
repository.findOverrideCredentialId(1, "user-2"),
|
||||
).resolves.toBe(8);
|
||||
await expect(
|
||||
repository.findOverrideCredentialId(1, "user-1"),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { NetworkTopologyRepository } from "../../../database/repositories/network-topology-repository.js";
|
||||
|
||||
describe("NetworkTopologyRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<NetworkTopologyRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE network_topology (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
topology TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
`);
|
||||
|
||||
return new NetworkTopologyRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("finds, creates, and updates topology by user id", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
expect(await repo.findByUserId("user-1")).toBeNull();
|
||||
|
||||
await repo.upsertForUser(
|
||||
"user-1",
|
||||
JSON.stringify({ nodes: [{ id: "host-1" }], edges: [] }),
|
||||
"2026-06-27T00:00:00.000Z",
|
||||
);
|
||||
expect(await repo.findByUserId("user-1")).toMatchObject({
|
||||
userId: "user-1",
|
||||
topology: '{"nodes":[{"id":"host-1"}],"edges":[]}',
|
||||
updatedAt: "2026-06-27T00:00:00.000Z",
|
||||
});
|
||||
|
||||
await repo.upsertForUser(
|
||||
"user-1",
|
||||
JSON.stringify({ nodes: [], edges: [{ id: "edge-1" }] }),
|
||||
"2026-06-27T01:00:00.000Z",
|
||||
);
|
||||
expect(await repo.findByUserId("user-1")).toMatchObject({
|
||||
userId: "user-1",
|
||||
topology: '{"nodes":[],"edges":[{"id":"edge-1"}]}',
|
||||
updatedAt: "2026-06-27T01:00:00.000Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes topology and only triggers writes for changed rows", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsertForUser("user-1", "{}");
|
||||
await repo.upsertForUser("user-1", '{"nodes":[]}');
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(await repo.deleteByUserId("missing")).toBe(0);
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(1);
|
||||
expect(writeCount).toBe(3);
|
||||
expect(await repo.findByUserId("user-1")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { OpenTabRepository } from "../../../database/repositories/open-tab-repository.js";
|
||||
|
||||
describe("OpenTabRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<OpenTabRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE user_open_tabs (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
tab_type TEXT NOT NULL,
|
||||
host_id INTEGER,
|
||||
label TEXT NOT NULL,
|
||||
tab_order INTEGER NOT NULL DEFAULT 0,
|
||||
backend_session_id TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
`);
|
||||
|
||||
return new OpenTabRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("lists recent tabs ordered by tab order", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.upsertForUser(
|
||||
"user-1",
|
||||
{
|
||||
id: "tab-old",
|
||||
tabType: "terminal",
|
||||
label: "Old",
|
||||
tabOrder: 1,
|
||||
},
|
||||
"2026-06-27T00:00:00.000Z",
|
||||
);
|
||||
await repo.upsertForUser(
|
||||
"user-1",
|
||||
{
|
||||
id: "tab-new",
|
||||
tabType: "stats",
|
||||
label: "New",
|
||||
tabOrder: 0,
|
||||
},
|
||||
"2026-06-27T01:00:00.000Z",
|
||||
);
|
||||
await repo.upsertForUser(
|
||||
"user-2",
|
||||
{
|
||||
id: "other",
|
||||
tabType: "terminal",
|
||||
label: "Other",
|
||||
tabOrder: 0,
|
||||
},
|
||||
"2026-06-27T02:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(
|
||||
(await repo.listRecentForUser("user-1", "2026-06-27T00:30:00.000Z")).map(
|
||||
(tab) => tab.id,
|
||||
),
|
||||
).toEqual(["tab-new"]);
|
||||
});
|
||||
|
||||
it("upserts tabs and preserves backend session when omitted", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.upsertForUser("user-1", {
|
||||
id: "tab-1",
|
||||
tabType: "terminal",
|
||||
hostId: 1,
|
||||
label: "Server",
|
||||
tabOrder: 0,
|
||||
backendSessionId: "session-1",
|
||||
});
|
||||
await repo.upsertForUser("user-1", {
|
||||
id: "tab-1",
|
||||
tabType: "terminal",
|
||||
hostId: 2,
|
||||
label: "Server renamed",
|
||||
tabOrder: 1,
|
||||
});
|
||||
|
||||
expect(
|
||||
(await repo.listRecentForUser("user-1", "2000-01-01T00:00:00.000Z"))[0],
|
||||
).toMatchObject({
|
||||
id: "tab-1",
|
||||
hostId: 2,
|
||||
label: "Server renamed",
|
||||
tabOrder: 1,
|
||||
backendSessionId: "session-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("replaces, updates, and deletes tabs for a user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.replaceForUser("user-1", [
|
||||
{ id: "tab-1", tabType: "terminal", label: "One", tabOrder: 1 },
|
||||
{ id: "tab-2", tabType: "settings", label: "Two", tabOrder: 0 },
|
||||
]);
|
||||
expect(
|
||||
(await repo.listRecentForUser("user-1", "2000-01-01T00:00:00.000Z")).map(
|
||||
(tab) => tab.id,
|
||||
),
|
||||
).toEqual(["tab-2", "tab-1"]);
|
||||
|
||||
expect(
|
||||
await repo.updateForUser("user-1", "missing", { label: "Missing" }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
await repo.updateForUser("user-1", "tab-1", { label: "Renamed" }),
|
||||
).toBe(true);
|
||||
expect(await repo.deleteForUser("user-1", "tab-2")).toBe(1);
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(1);
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(0);
|
||||
expect(writeCount).toBe(4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { OpksshTokenRepository } from "../../../database/repositories/opkssh-token-repository.js";
|
||||
|
||||
describe("OpksshTokenRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<OpksshTokenRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE hosts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE opkssh_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
ssh_cert TEXT NOT NULL,
|
||||
private_key TEXT NOT NULL,
|
||||
email TEXT,
|
||||
sub TEXT,
|
||||
issuer TEXT,
|
||||
audience TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TEXT NOT NULL,
|
||||
last_used TEXT,
|
||||
UNIQUE(user_id, host_id)
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO hosts (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'one'), (2, 'user-1', 'two'), (3, 'user-2', 'other');
|
||||
INSERT INTO opkssh_tokens (
|
||||
user_id, host_id, ssh_cert, private_key, email, expires_at
|
||||
)
|
||||
VALUES
|
||||
('user-1', 1, 'cert-1', 'key-1', 'alice@example.com', '2099-01-01T00:00:00.000Z'),
|
||||
('user-1', 2, 'cert-2', 'key-2', 'alice2@example.com', '2099-01-01T00:00:00.000Z'),
|
||||
('user-2', 3, 'cert-3', 'key-3', 'bob@example.com', '2099-01-01T00:00:00.000Z');
|
||||
`);
|
||||
|
||||
return new OpksshTokenRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("finds and upserts a token by user and host", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const existing = await repo.findByUserAndHost("user-1", 1);
|
||||
expect(existing?.sshCert).toBe("cert-1");
|
||||
|
||||
await repo.upsert({
|
||||
userId: "user-1",
|
||||
hostId: 1,
|
||||
sshCert: "new-cert",
|
||||
privateKey: "new-key",
|
||||
email: "new@example.com",
|
||||
sub: "sub",
|
||||
issuer: "issuer",
|
||||
audience: "aud",
|
||||
expiresAt: "2099-02-01T00:00:00.000Z",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const updated = await repo.findByUserAndHost("user-1", 1);
|
||||
expect(updated).toMatchObject({
|
||||
sshCert: "new-cert",
|
||||
privateKey: "new-key",
|
||||
email: "new@example.com",
|
||||
sub: "sub",
|
||||
issuer: "issuer",
|
||||
audience: "aud",
|
||||
expiresAt: "2099-02-01T00:00:00.000Z",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("updates last-used and deletes one token", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(
|
||||
await repo.updateLastUsed("user-1", 1, "2026-01-02T00:00:00.000Z"),
|
||||
).toBe(true);
|
||||
expect(await repo.updateLastUsed("missing", 1)).toBe(false);
|
||||
expect((await repo.findByUserAndHost("user-1", 1))?.lastUsed).toBe(
|
||||
"2026-01-02T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(await repo.deleteByUserAndHost("user-1", 1)).toBe(true);
|
||||
expect(await repo.deleteByUserAndHost("user-1", 1)).toBe(false);
|
||||
expect(await repo.findByUserAndHost("user-1", 1)).toBeNull();
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("deletes tokens by user id", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(2);
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(0);
|
||||
expect(await repo.findByUserAndHost("user-1", 1)).toBeNull();
|
||||
expect(await repo.findByUserAndHost("user-2", 3)).not.toBeNull();
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,562 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { RbacAccessRepository } from "../../../database/repositories/rbac-access-repository.js";
|
||||
|
||||
describe("RbacAccessRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
const activeAccessTime = "2026-06-26T12:00:00.000Z";
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<RbacAccessRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE roles (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
is_system INTEGER NOT NULL DEFAULT 0,
|
||||
permissions TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE host_access (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_id INTEGER NOT NULL,
|
||||
user_id TEXT,
|
||||
role_id INTEGER,
|
||||
granted_by TEXT NOT NULL,
|
||||
permission_level TEXT NOT NULL DEFAULT 'view',
|
||||
expires_at TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_accessed_at TEXT,
|
||||
access_count INTEGER NOT NULL DEFAULT 0,
|
||||
override_credential_id INTEGER
|
||||
);
|
||||
|
||||
CREATE TABLE shared_host_secrets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_access_id INTEGER NOT NULL,
|
||||
target_user_id TEXT NOT NULL,
|
||||
protocol TEXT NOT NULL DEFAULT 'ssh',
|
||||
source_type TEXT NOT NULL DEFAULT 'credential',
|
||||
original_credential_id INTEGER,
|
||||
encrypted_username TEXT,
|
||||
encrypted_auth_type TEXT,
|
||||
encrypted_password TEXT,
|
||||
encrypted_key TEXT,
|
||||
encrypted_key_password TEXT,
|
||||
encrypted_key_type TEXT,
|
||||
encrypted_domain TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(host_access_id, target_user_id, protocol)
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT,
|
||||
ip TEXT NOT NULL,
|
||||
port INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
credential_id INTEGER,
|
||||
rdp_credential_id INTEGER,
|
||||
vnc_credential_id INTEGER,
|
||||
telnet_credential_id INTEGER,
|
||||
folder TEXT,
|
||||
tags TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE snippets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
description TEXT,
|
||||
folder TEXT,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
host_filter TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE snippet_access (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
snippet_id INTEGER NOT NULL,
|
||||
user_id TEXT,
|
||||
role_id INTEGER,
|
||||
granted_by TEXT NOT NULL,
|
||||
permission_level TEXT NOT NULL DEFAULT 'view',
|
||||
expires_at TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash, is_admin, is_oidc)
|
||||
VALUES
|
||||
('admin', 'admin', 'hash', 1, 0),
|
||||
('user-1', 'alice', 'hash', 0, 0),
|
||||
('owner-1', 'owner', 'hash', 0, 0);
|
||||
|
||||
INSERT INTO roles (id, name, display_name, is_system)
|
||||
VALUES (7, 'ops', 'Operations', 0);
|
||||
|
||||
INSERT INTO ssh_data (
|
||||
id, user_id, name, ip, port, username, credential_id, rdp_credential_id, vnc_credential_id, telnet_credential_id, folder, tags
|
||||
)
|
||||
VALUES (42, 'owner-1', 'prod', '10.0.0.42', 22, 'root', 123, 124, 125, 126, 'servers', 'linux');
|
||||
|
||||
INSERT INTO host_access (
|
||||
id, host_id, user_id, role_id, granted_by, permission_level, expires_at, created_at
|
||||
)
|
||||
VALUES
|
||||
(1, 42, 'user-1', NULL, 'admin', 'view', NULL, '2026-06-26T00:00:00.000Z'),
|
||||
(2, 42, NULL, 7, 'admin', 'view', '2026-06-27T00:00:00.000Z', '2026-06-26T01:00:00.000Z'),
|
||||
(5, 44, 'user-1', NULL, 'admin', 'view', '2026-06-25T00:00:00.000Z', '2026-06-24T00:00:00.000Z');
|
||||
|
||||
INSERT INTO shared_host_secrets (
|
||||
id, host_access_id, target_user_id, protocol, source_type, original_credential_id, encrypted_username, encrypted_auth_type
|
||||
)
|
||||
VALUES
|
||||
(8, 2, 'user-1', 'ssh', 'credential', 123, 'enc-user', 'enc-auth'),
|
||||
(9, 2, 'user-1', 'rdp', 'inline', NULL, 'enc-rdp-user', 'direct');
|
||||
|
||||
INSERT INTO snippets (id, user_id, name, content)
|
||||
VALUES (99, 'owner-1', 'deploy', 'echo deploy');
|
||||
|
||||
INSERT INTO snippet_access (
|
||||
id, snippet_id, user_id, role_id, granted_by, permission_level, expires_at, created_at
|
||||
)
|
||||
VALUES
|
||||
(3, 99, 'user-1', NULL, 'admin', 'view', NULL, '2026-06-26T00:00:00.000Z'),
|
||||
(4, 99, NULL, 7, 'admin', 'view', '2026-06-27T00:00:00.000Z', '2026-06-26T01:00:00.000Z');
|
||||
`);
|
||||
|
||||
return new RbacAccessRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("lists host access with user and role target metadata", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const accessList = await repo.listHostAccess(42);
|
||||
|
||||
expect(accessList).toMatchObject([
|
||||
{
|
||||
id: 2,
|
||||
targetType: "role",
|
||||
userId: null,
|
||||
roleId: 7,
|
||||
username: null,
|
||||
roleName: "ops",
|
||||
roleDisplayName: "Operations",
|
||||
grantedByUsername: "admin",
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
targetType: "user",
|
||||
userId: "user-1",
|
||||
roleId: null,
|
||||
username: "alice",
|
||||
roleName: null,
|
||||
roleDisplayName: null,
|
||||
grantedByUsername: "admin",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists snippet access with user and role target metadata", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const accessList = await repo.listSnippetAccess(99);
|
||||
|
||||
expect(accessList.map((access) => access.targetType)).toEqual([
|
||||
"role",
|
||||
"user",
|
||||
]);
|
||||
expect(accessList[0]).toMatchObject({
|
||||
id: 4,
|
||||
roleId: 7,
|
||||
roleName: "ops",
|
||||
grantedByUsername: "admin",
|
||||
});
|
||||
expect(accessList[1]).toMatchObject({
|
||||
id: 3,
|
||||
userId: "user-1",
|
||||
username: "alice",
|
||||
grantedByUsername: "admin",
|
||||
});
|
||||
});
|
||||
|
||||
it("lists shared hosts for direct and role access", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const sharedHosts = await repo.listSharedHosts(
|
||||
"user-1",
|
||||
[7],
|
||||
activeAccessTime,
|
||||
);
|
||||
|
||||
expect(sharedHosts).toMatchObject([
|
||||
{
|
||||
id: 42,
|
||||
name: "prod",
|
||||
ip: "10.0.0.42",
|
||||
ownerUsername: "owner",
|
||||
permissionLevel: "view",
|
||||
},
|
||||
{
|
||||
id: 42,
|
||||
name: "prod",
|
||||
ip: "10.0.0.42",
|
||||
ownerUsername: "owner",
|
||||
permissionLevel: "view",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists visible host access entries for host list access checks", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await expect(
|
||||
repo.listVisibleHostAccessEntries("user-1", [7], activeAccessTime),
|
||||
).resolves.toEqual([
|
||||
{
|
||||
hostId: 42,
|
||||
permissionLevel: "view",
|
||||
expiresAt: "2026-06-27T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
hostId: 42,
|
||||
permissionLevel: "view",
|
||||
expiresAt: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists role host access credential sources for role assignment", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await expect(repo.listRoleHostAccessCredentialSources(7)).resolves.toEqual([
|
||||
{
|
||||
hostAccessId: 2,
|
||||
credentialId: 123,
|
||||
rdpCredentialId: 124,
|
||||
vncCredentialId: 125,
|
||||
telnetCredentialId: 126,
|
||||
hostId: 42,
|
||||
hostOwnerId: "owner-1",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("finds shared secrets per protocol and host access owner", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await expect(
|
||||
repo.findSharedSecretForHostUserProtocol(42, "user-1", "ssh"),
|
||||
).resolves.toMatchObject({
|
||||
id: 8,
|
||||
hostAccessId: 2,
|
||||
protocol: "ssh",
|
||||
sourceType: "credential",
|
||||
originalCredentialId: 123,
|
||||
targetUserId: "user-1",
|
||||
encryptedUsername: "enc-user",
|
||||
encryptedAuthType: "enc-auth",
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.findSharedSecretForHostUserProtocol(42, "user-1", "rdp"),
|
||||
).resolves.toMatchObject({
|
||||
id: 9,
|
||||
protocol: "rdp",
|
||||
sourceType: "inline",
|
||||
originalCredentialId: null,
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.findSharedSecretForHostUserProtocol(42, "user-1", "vnc"),
|
||||
).resolves.toBeNull();
|
||||
await expect(
|
||||
repo.findSharedSecretForHostUserProtocol(99, "user-1", "ssh"),
|
||||
).resolves.toBeNull();
|
||||
await expect(repo.findHostAccessOwnerId(2)).resolves.toBe("owner-1");
|
||||
await expect(repo.findHostAccessOwnerId(999)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("lists active grants, finds grants by id and updates grant level/expiry", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const grants = await repo.listActiveHostAccessGrants(42, activeAccessTime);
|
||||
expect(grants.map((grant) => grant.id).sort()).toEqual([1, 2]);
|
||||
|
||||
// Host 44's only grant expired before activeAccessTime.
|
||||
await expect(
|
||||
repo.listActiveHostAccessGrants(44, activeAccessTime),
|
||||
).resolves.toEqual([]);
|
||||
|
||||
await expect(repo.findHostAccessById(1, 42)).resolves.toMatchObject({
|
||||
id: 1,
|
||||
hostId: 42,
|
||||
permissionLevel: "view",
|
||||
});
|
||||
await expect(repo.findHostAccessById(1, 99)).resolves.toBeNull();
|
||||
|
||||
await expect(
|
||||
repo.updateHostAccessGrant(1, 42, {
|
||||
permissionLevel: "manage",
|
||||
expiresAt: "2026-07-01T00:00:00.000Z",
|
||||
}),
|
||||
).resolves.toBe(true);
|
||||
await expect(repo.findHostAccessById(1, 42)).resolves.toMatchObject({
|
||||
permissionLevel: "manage",
|
||||
expiresAt: "2026-07-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.updateHostAccessGrant(999, 42, { permissionLevel: "view" }),
|
||||
).resolves.toBe(false);
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("lists shared snippets and preserves route-level direct-over-role behavior", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const sharedSnippets = await repo.listSharedSnippets(
|
||||
"user-1",
|
||||
[7],
|
||||
activeAccessTime,
|
||||
);
|
||||
|
||||
expect(sharedSnippets).toHaveLength(1);
|
||||
expect(sharedSnippets[0]).toMatchObject({
|
||||
id: 99,
|
||||
name: "deploy",
|
||||
ownerUsername: "owner",
|
||||
permissionLevel: "view",
|
||||
});
|
||||
});
|
||||
|
||||
it("lists visible shared snippets for the main snippets route", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const sharedSnippets = await repo.listVisibleSharedSnippets(
|
||||
"user-1",
|
||||
[7],
|
||||
activeAccessTime,
|
||||
);
|
||||
|
||||
expect(sharedSnippets.map((snippet) => snippet.id)).toEqual([99, 99]);
|
||||
expect(sharedSnippets[0]).toMatchObject({
|
||||
userId: "owner-1",
|
||||
name: "deploy",
|
||||
content: "echo deploy",
|
||||
ownerUsername: "owner",
|
||||
});
|
||||
});
|
||||
|
||||
it("finds an accessible shared snippet for direct or role access", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await expect(
|
||||
repo.findAccessibleSharedSnippet(99, "user-2", [7], activeAccessTime),
|
||||
).resolves.toMatchObject({
|
||||
id: 99,
|
||||
userId: "owner-1",
|
||||
name: "deploy",
|
||||
content: "echo deploy",
|
||||
ownerUsername: "owner",
|
||||
permissionLevel: "view",
|
||||
hostFilter: null,
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.findAccessibleSharedSnippet(
|
||||
99,
|
||||
"user-2",
|
||||
[7],
|
||||
"2026-06-28T00:00:00.000Z",
|
||||
),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("upserts host access and updates overrides", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const updated = await repo.upsertHostAccess({
|
||||
hostId: 42,
|
||||
targetType: "user",
|
||||
targetUserId: "user-1",
|
||||
grantedBy: "admin",
|
||||
permissionLevel: "view",
|
||||
expiresAt: "2026-06-28T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(updated).toEqual({ id: 1, created: false });
|
||||
expect(
|
||||
(await repo.listHostAccess(42)).find((row) => row.id === 1),
|
||||
).toMatchObject({
|
||||
expiresAt: "2026-06-28T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const created = await repo.upsertHostAccess({
|
||||
hostId: 43,
|
||||
targetType: "role",
|
||||
targetRoleId: 7,
|
||||
grantedBy: "admin",
|
||||
permissionLevel: "view",
|
||||
expiresAt: null,
|
||||
});
|
||||
expect(created.created).toBe(true);
|
||||
|
||||
const directAccess = await repo.findDirectHostAccess(42, "user-1");
|
||||
expect(directAccess?.id).toBe(1);
|
||||
|
||||
await repo.updateHostAccessOverrideCredential(1, 123);
|
||||
expect(
|
||||
(await repo.findDirectHostAccess(42, "user-1"))?.overrideCredentialId,
|
||||
).toBe(123);
|
||||
|
||||
await repo.touchHostAccess(1, "2026-06-26T03:00:00.000Z");
|
||||
expect(
|
||||
(await repo.findDirectHostAccess(42, "user-1"))?.lastAccessedAt,
|
||||
).toBe("2026-06-26T03:00:00.000Z");
|
||||
|
||||
await repo.revokeHostAccess(1, 42);
|
||||
expect(await repo.findDirectHostAccess(42, "user-1")).toBeNull();
|
||||
expect(writeCount).toBe(5);
|
||||
});
|
||||
|
||||
it("finds active host access and deletes expired host access", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(
|
||||
await repo.findActiveHostAccess(
|
||||
42,
|
||||
"user-1",
|
||||
[7],
|
||||
"2026-06-26T12:00:00.000Z",
|
||||
),
|
||||
).toMatchObject({ id: 1 });
|
||||
expect(
|
||||
await repo.findActiveHostAccess(
|
||||
44,
|
||||
"user-1",
|
||||
[],
|
||||
"2026-06-26T12:00:00.000Z",
|
||||
),
|
||||
).toBeNull();
|
||||
|
||||
expect(await repo.deleteExpiredHostAccess("2026-06-26T12:00:00.000Z")).toBe(
|
||||
1,
|
||||
);
|
||||
expect(await repo.findDirectHostAccess(44, "user-1")).toBeNull();
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("deletes host access for a host and only saves when rows changed", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(await repo.deleteHostAccessForHost(42)).toBe(2);
|
||||
expect(await repo.listHostAccess(42)).toEqual([]);
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
expect(await repo.deleteHostAccessForHost(42)).toBe(0);
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("deletes host access for multiple hosts", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(await repo.deleteHostAccessForHosts([])).toBe(0);
|
||||
expect(writeCount).toBe(0);
|
||||
|
||||
expect(await repo.deleteHostAccessForHosts([42, 44])).toBe(3);
|
||||
expect(await repo.listHostAccess(42)).toEqual([]);
|
||||
expect(await repo.findDirectHostAccess(44, "user-1")).toBeNull();
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("deletes host access that references a user directly or as grantor", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(await repo.deleteHostAccessForUserReferences("admin")).toBe(3);
|
||||
expect(await repo.listHostAccess(42)).toEqual([]);
|
||||
expect(await repo.findDirectHostAccess(44, "user-1")).toBeNull();
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
expect(await repo.deleteHostAccessForUserReferences("admin")).toBe(0);
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("upserts and revokes snippet access", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const updated = await repo.upsertSnippetAccess({
|
||||
snippetId: 99,
|
||||
targetType: "user",
|
||||
targetUserId: "user-1",
|
||||
grantedBy: "admin",
|
||||
expiresAt: "2026-06-28T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(updated).toEqual({ id: 3, created: false });
|
||||
expect(
|
||||
(await repo.listSnippetAccess(99)).find((row) => row.id === 3),
|
||||
).toMatchObject({ expiresAt: "2026-06-28T00:00:00.000Z" });
|
||||
|
||||
const created = await repo.upsertSnippetAccess({
|
||||
snippetId: 100,
|
||||
targetType: "role",
|
||||
targetRoleId: 7,
|
||||
grantedBy: "admin",
|
||||
expiresAt: null,
|
||||
});
|
||||
expect(created.created).toBe(true);
|
||||
|
||||
await repo.revokeSnippetAccess(3, 99);
|
||||
expect((await repo.listSnippetAccess(99)).map((row) => row.id)).toEqual([
|
||||
4,
|
||||
]);
|
||||
expect(writeCount).toBe(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { RecentActivityRepository } from "../../../database/repositories/recent-activity-repository.js";
|
||||
|
||||
describe("RecentActivityRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<{
|
||||
repository: RecentActivityRepository;
|
||||
sqlite: NonNullable<
|
||||
Awaited<ReturnType<TestSqliteDatabase["connect"]>>["sqlite"]
|
||||
>;
|
||||
}> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE hosts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE recent_activity (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
host_name TEXT,
|
||||
timestamp TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO hosts (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'one'), (2, 'user-1', 'two'), (3, 'user-2', 'other');
|
||||
INSERT INTO recent_activity (id, user_id, type, host_id, host_name, timestamp)
|
||||
VALUES
|
||||
(1, 'user-1', 'connect', 1, 'one', '2026-06-26T00:00:00.000Z'),
|
||||
(2, 'user-1', 'disconnect', 2, 'two', '2026-06-26T00:01:00.000Z'),
|
||||
(3, 'user-2', 'connect', 3, 'other', '2026-06-26T00:02:00.000Z');
|
||||
`);
|
||||
|
||||
return {
|
||||
repository: new RecentActivityRepository(context, onWrite),
|
||||
sqlite: context.sqlite!,
|
||||
};
|
||||
}
|
||||
|
||||
it("lists, creates, and trims recent activity", async () => {
|
||||
let writeCount = 0;
|
||||
const { repository, sqlite } = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(
|
||||
(await repository.listByUserId("user-1", 2)).map((row) => row.id),
|
||||
).toEqual([2, 1]);
|
||||
|
||||
const created = await repository.create({
|
||||
userId: "user-1",
|
||||
type: "terminal",
|
||||
hostId: 1,
|
||||
hostName: "one",
|
||||
timestamp: "2026-06-26T00:03:00.000Z",
|
||||
});
|
||||
expect(created).toMatchObject({
|
||||
userId: "user-1",
|
||||
type: "terminal",
|
||||
hostId: 1,
|
||||
});
|
||||
|
||||
expect(await repository.trimUserActivity("user-1", 2)).toBe(1);
|
||||
expect(
|
||||
sqlite
|
||||
.prepare(
|
||||
"SELECT id FROM recent_activity WHERE user_id = ? ORDER BY timestamp DESC",
|
||||
)
|
||||
.all("user-1"),
|
||||
).toEqual([{ id: created.id }, { id: 2 }]);
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("deletes activity by user id and only triggers writes for changed rows", async () => {
|
||||
let writeCount = 0;
|
||||
const { repository: repo } = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(await repo.deleteByUserId("missing")).toBe(0);
|
||||
expect(writeCount).toBe(0);
|
||||
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(2);
|
||||
expect(writeCount).toBe(1);
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(0);
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("deletes activity by host id and host id list", async () => {
|
||||
let writeCount = 0;
|
||||
const { repository: repo } = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(await repo.deleteByHostId(1)).toBe(1);
|
||||
expect(await repo.deleteByHostId(1)).toBe(0);
|
||||
expect(await repo.deleteByHostIds([])).toBe(0);
|
||||
expect(await repo.deleteByHostIds([2, 3])).toBe(2);
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,278 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { RoleRepository } from "../../../database/repositories/role-repository.js";
|
||||
|
||||
describe("RoleRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<RoleRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE roles (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
is_system INTEGER NOT NULL DEFAULT 0,
|
||||
permissions TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE user_roles (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
role_id INTEGER NOT NULL,
|
||||
granted_by TEXT,
|
||||
granted_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE host_access (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_id INTEGER NOT NULL,
|
||||
user_id TEXT,
|
||||
role_id INTEGER,
|
||||
granted_by TEXT NOT NULL,
|
||||
permission_level TEXT NOT NULL DEFAULT 'view',
|
||||
expires_at TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash, is_admin, is_oidc)
|
||||
VALUES ('admin', 'admin', 'hash', 1, 0), ('user-1', 'user', 'hash', 0, 0);
|
||||
`);
|
||||
|
||||
return new RoleRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates, lists, updates, and finds roles", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const roleId = await repo.createRole({
|
||||
name: "ops",
|
||||
displayName: "Operations",
|
||||
description: "Ops access",
|
||||
isSystem: false,
|
||||
permissions: null,
|
||||
});
|
||||
|
||||
expect((await repo.findRoleByName("ops"))?.id).toBe(roleId);
|
||||
expect((await repo.findRoleById(roleId))?.displayName).toBe("Operations");
|
||||
|
||||
await repo.updateRole(roleId, {
|
||||
displayName: "Ops",
|
||||
description: null,
|
||||
updatedAt: "2026-06-26T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const roles = await repo.listRoles();
|
||||
expect(roles.map((role) => role.name)).toEqual(["ops"]);
|
||||
expect(roles[0].displayName).toBe("Ops");
|
||||
expect(roles[0].description).toBeNull();
|
||||
});
|
||||
|
||||
it("assigns, lists, and removes user roles", async () => {
|
||||
const repo = await createRepository();
|
||||
const roleId = await repo.createRole({
|
||||
name: "ops",
|
||||
displayName: "Operations",
|
||||
isSystem: false,
|
||||
permissions: JSON.stringify(["hosts.read", "hosts.*"]),
|
||||
});
|
||||
|
||||
await repo.assignRoleToUser({
|
||||
userId: "user-1",
|
||||
roleId,
|
||||
grantedBy: "admin",
|
||||
});
|
||||
|
||||
expect(await repo.findUserRole("user-1", roleId)).not.toBeNull();
|
||||
expect(await repo.listUserRoleIds("user-1")).toEqual([roleId]);
|
||||
expect(await repo.listRoleUserIds(roleId)).toEqual(["user-1"]);
|
||||
expect((await repo.listUserRoles("user-1"))[0]).toMatchObject({
|
||||
roleId,
|
||||
roleName: "ops",
|
||||
roleDisplayName: "Operations",
|
||||
isSystem: false,
|
||||
});
|
||||
expect(await repo.listUserRolePermissions("user-1")).toEqual([
|
||||
{ permissions: JSON.stringify(["hosts.read", "hosts.*"]) },
|
||||
]);
|
||||
expect(await repo.userHasAnyRoleName("user-1", ["admin", "ops"])).toBe(
|
||||
true,
|
||||
);
|
||||
expect(await repo.userHasAnyRoleName("user-1", ["admin"])).toBe(false);
|
||||
expect(await repo.userHasAnyRoleName("user-1", [])).toBe(false);
|
||||
|
||||
await repo.removeRoleFromUser("user-1", roleId);
|
||||
expect(await repo.findUserRole("user-1", roleId)).toBeNull();
|
||||
});
|
||||
|
||||
it("assigns roles by name", async () => {
|
||||
const repo = await createRepository();
|
||||
const roleId = await repo.createRole({
|
||||
name: "user",
|
||||
displayName: "User",
|
||||
isSystem: true,
|
||||
permissions: null,
|
||||
});
|
||||
|
||||
expect(
|
||||
await repo.assignRoleNameToUser({
|
||||
userId: "user-1",
|
||||
roleName: "missing",
|
||||
grantedBy: "admin",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(await repo.listUserRoleIds("user-1")).toEqual([]);
|
||||
|
||||
expect(
|
||||
await repo.assignRoleNameToUser({
|
||||
userId: "user-1",
|
||||
roleName: "user",
|
||||
grantedBy: "admin",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(await repo.listUserRoleIds("user-1")).toEqual([roleId]);
|
||||
});
|
||||
|
||||
it("switches user roles by role name", async () => {
|
||||
const repo = await createRepository();
|
||||
const userRoleId = await repo.createRole({
|
||||
name: "user",
|
||||
displayName: "User",
|
||||
isSystem: true,
|
||||
permissions: null,
|
||||
});
|
||||
const adminRoleId = await repo.createRole({
|
||||
name: "admin",
|
||||
displayName: "Admin",
|
||||
isSystem: true,
|
||||
permissions: null,
|
||||
});
|
||||
await repo.assignRoleToUser({
|
||||
userId: "user-1",
|
||||
roleId: userRoleId,
|
||||
grantedBy: "admin",
|
||||
});
|
||||
|
||||
await expect(
|
||||
repo.switchUserRoleName({
|
||||
userId: "user-1",
|
||||
addRoleName: "admin",
|
||||
removeRoleName: "user",
|
||||
grantedBy: "admin",
|
||||
}),
|
||||
).resolves.toEqual({ added: true, removed: true });
|
||||
expect(await repo.listUserRoleIds("user-1")).toEqual([adminRoleId]);
|
||||
|
||||
await expect(
|
||||
repo.switchUserRoleName({
|
||||
userId: "user-1",
|
||||
addRoleName: "missing",
|
||||
removeRoleName: "admin",
|
||||
grantedBy: "admin",
|
||||
}),
|
||||
).resolves.toEqual({ added: false, removed: true });
|
||||
expect(await repo.listUserRoleIds("user-1")).toEqual([]);
|
||||
});
|
||||
|
||||
it("deletes role assignments and returns affected users", async () => {
|
||||
const repo = await createRepository();
|
||||
const roleId = await repo.createRole({
|
||||
name: "ops",
|
||||
displayName: "Operations",
|
||||
isSystem: false,
|
||||
permissions: null,
|
||||
});
|
||||
await repo.assignRoleToUser({
|
||||
userId: "user-1",
|
||||
roleId,
|
||||
grantedBy: "admin",
|
||||
});
|
||||
|
||||
const result = await repo.deleteRole(roleId);
|
||||
|
||||
expect(result.deletedUserIds).toEqual(["user-1"]);
|
||||
expect(await repo.findRoleById(roleId)).toBeNull();
|
||||
expect(await repo.listUserRoleIds("user-1")).toEqual([]);
|
||||
});
|
||||
|
||||
it("removes all roles for a user only when assignments exist", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
const opsRoleId = await repo.createRole({
|
||||
name: "ops",
|
||||
displayName: "Operations",
|
||||
isSystem: false,
|
||||
permissions: null,
|
||||
});
|
||||
const auditRoleId = await repo.createRole({
|
||||
name: "audit",
|
||||
displayName: "Audit",
|
||||
isSystem: false,
|
||||
permissions: null,
|
||||
});
|
||||
await repo.assignRoleToUser({
|
||||
userId: "user-1",
|
||||
roleId: opsRoleId,
|
||||
grantedBy: "admin",
|
||||
});
|
||||
await repo.assignRoleToUser({
|
||||
userId: "user-1",
|
||||
roleId: auditRoleId,
|
||||
grantedBy: "admin",
|
||||
});
|
||||
|
||||
expect(await repo.removeAllRolesFromUser("missing-user")).toBe(0);
|
||||
expect(writeCount).toBe(4);
|
||||
|
||||
expect(await repo.removeAllRolesFromUser("user-1")).toBe(2);
|
||||
expect(await repo.listUserRoleIds("user-1")).toEqual([]);
|
||||
expect(writeCount).toBe(5);
|
||||
});
|
||||
|
||||
it("runs the write hook after writes", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const roleId = await repo.createRole({
|
||||
name: "ops",
|
||||
displayName: "Operations",
|
||||
isSystem: false,
|
||||
permissions: null,
|
||||
});
|
||||
await repo.assignRoleToUser({
|
||||
userId: "user-1",
|
||||
roleId,
|
||||
grantedBy: "admin",
|
||||
});
|
||||
await repo.updateRole(roleId, { displayName: "Ops" });
|
||||
await repo.removeRoleFromUser("user-1", roleId);
|
||||
await repo.deleteRole(roleId);
|
||||
|
||||
expect(writeCount).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { SessionRecordingRepository } from "../../../database/repositories/session-recording-repository.js";
|
||||
|
||||
describe("SessionRecordingRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<SessionRecordingRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
ip TEXT
|
||||
);
|
||||
|
||||
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
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO ssh_data (id, user_id, name, ip)
|
||||
VALUES (1, 'user-1', 'one', '10.0.0.1'), (2, 'user-1', 'two', '10.0.0.2'), (3, 'user-2', 'other', '10.0.0.3');
|
||||
`);
|
||||
|
||||
return new SessionRecordingRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates and lists session recordings with host metadata", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const first = await repo.create({
|
||||
userId: "user-1",
|
||||
hostId: 1,
|
||||
startedAt: "2026-06-27T00:00:00.000Z",
|
||||
endedAt: "2026-06-27T00:01:00.000Z",
|
||||
duration: 60,
|
||||
recordingPath: "/tmp/one.log",
|
||||
});
|
||||
await repo.create({
|
||||
userId: "user-1",
|
||||
hostId: 2,
|
||||
startedAt: "2026-06-27T00:02:00.000Z",
|
||||
recordingPath: "/tmp/two.log",
|
||||
});
|
||||
await repo.create({
|
||||
userId: "user-2",
|
||||
hostId: 3,
|
||||
startedAt: "2026-06-27T00:03:00.000Z",
|
||||
});
|
||||
|
||||
expect(first).toMatchObject({
|
||||
userId: "user-1",
|
||||
hostId: 1,
|
||||
duration: 60,
|
||||
recordingPath: "/tmp/one.log",
|
||||
});
|
||||
|
||||
const rows = await repo.listByUserIdWithHost("user-1");
|
||||
expect(rows.map((row) => row.hostName)).toEqual(["two", "one"]);
|
||||
expect(rows[0]).toMatchObject({
|
||||
hostIp: "10.0.0.2",
|
||||
recordingPath: "/tmp/two.log",
|
||||
protocol: "ssh",
|
||||
format: "text",
|
||||
});
|
||||
});
|
||||
|
||||
it("finds paths and prunes old recordings", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const old = await repo.create({
|
||||
userId: "user-1",
|
||||
hostId: 1,
|
||||
startedAt: "2026-01-01T00:00:00.000Z",
|
||||
recordingPath: "/tmp/old.log",
|
||||
});
|
||||
const current = await repo.create({
|
||||
userId: "user-1",
|
||||
hostId: 1,
|
||||
startedAt: "2026-06-27T00:00:00.000Z",
|
||||
recordingPath: "/tmp/current.log",
|
||||
});
|
||||
expect(writeCount).toBe(2);
|
||||
|
||||
expect(await repo.findPathByIdForUser("user-2", old.id)).toBeNull();
|
||||
expect(await repo.findPathByIdForUser("user-1", old.id)).toMatchObject({
|
||||
recordingPath: "/tmp/old.log",
|
||||
});
|
||||
expect(await repo.listPathsOlderThan("2026-02-01T00:00:00.000Z")).toEqual([
|
||||
{ id: old.id, recordingPath: "/tmp/old.log" },
|
||||
]);
|
||||
|
||||
expect(await repo.deleteById(old.id)).toBe(true);
|
||||
expect(await repo.deleteById(old.id)).toBe(false);
|
||||
expect(await repo.findByIdForUser("user-1", current.id)).toMatchObject({
|
||||
id: current.id,
|
||||
});
|
||||
expect(writeCount).toBe(3);
|
||||
});
|
||||
|
||||
it("deletes recordings by user and host references", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const first = await repo.create({
|
||||
userId: "user-1",
|
||||
hostId: 1,
|
||||
startedAt: "2026-06-27T00:00:00.000Z",
|
||||
});
|
||||
await repo.create({
|
||||
userId: "user-1",
|
||||
hostId: 2,
|
||||
startedAt: "2026-06-27T00:01:00.000Z",
|
||||
});
|
||||
await repo.create({
|
||||
userId: "user-2",
|
||||
hostId: 3,
|
||||
startedAt: "2026-06-27T00:02:00.000Z",
|
||||
});
|
||||
expect(writeCount).toBe(3);
|
||||
|
||||
expect(await repo.deleteForUser("user-2", first.id)).toBe(false);
|
||||
expect(await repo.deleteForUser("user-1", first.id)).toBe(true);
|
||||
expect(await repo.deleteByHostIds([])).toBe(0);
|
||||
expect(await repo.deleteByHostIds([2])).toBe(1);
|
||||
expect(writeCount).toBe(5);
|
||||
|
||||
expect(await repo.deleteByUserId("user-2")).toBe(1);
|
||||
expect(await repo.deleteByHostId(3)).toBe(0);
|
||||
expect(writeCount).toBe(6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { SettingsRepository } from "../../../database/repositories/settings-repository.js";
|
||||
|
||||
describe("SettingsRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(): Promise<SettingsRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
)
|
||||
`);
|
||||
return new SettingsRepository(context);
|
||||
}
|
||||
|
||||
it("creates and updates settings", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.set("allow_registration", "true");
|
||||
expect(await repo.get("allow_registration")).toBe("true");
|
||||
|
||||
await repo.set("allow_registration", "false");
|
||||
expect(await repo.get("allow_registration")).toBe("false");
|
||||
});
|
||||
|
||||
it("lists and upserts settings", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.upsert("theme", "dark");
|
||||
await repo.upsert("allow_registration", "true");
|
||||
await repo.upsert("theme", "light");
|
||||
|
||||
expect(await repo.get("theme")).toBe("light");
|
||||
expect(await repo.listAll()).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ key: "theme", value: "light" },
|
||||
{ key: "allow_registration", value: "true" },
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null or fallback when setting is missing", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
expect(await repo.get("missing")).toBeNull();
|
||||
expect(await repo.getBoolean("missing", true)).toBe(true);
|
||||
});
|
||||
|
||||
it("reads boolean settings", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.set("enabled", "1");
|
||||
await repo.set("disabled", "false");
|
||||
|
||||
expect(await repo.getBoolean("enabled")).toBe(true);
|
||||
expect(await repo.getBoolean("disabled", true)).toBe(false);
|
||||
});
|
||||
|
||||
it("deletes settings", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.set("theme", "dark");
|
||||
await repo.delete("theme");
|
||||
|
||||
expect(await repo.get("theme")).toBeNull();
|
||||
});
|
||||
|
||||
it("deletes settings by SQL LIKE pattern", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.set("user_kek_salt_user-1", "salt");
|
||||
await repo.set("user_encrypted_dek_user-1", "dek");
|
||||
await repo.set("user_kek_salt_user-2", "other");
|
||||
|
||||
expect(await repo.deleteLike("user_%_user-1")).toBe(2);
|
||||
expect(await repo.get("user_kek_salt_user-1")).toBeNull();
|
||||
expect(await repo.get("user_encrypted_dek_user-1")).toBeNull();
|
||||
expect(await repo.get("user_kek_salt_user-2")).toBe("other");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,231 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { SharedHostSecretsRepository } from "../../../database/repositories/shared-host-secrets-repository.js";
|
||||
|
||||
describe("SharedHostSecretsRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<{
|
||||
repository: SharedHostSecretsRepository;
|
||||
sqlite: NonNullable<
|
||||
Awaited<ReturnType<TestSqliteDatabase["connect"]>>["sqlite"]
|
||||
>;
|
||||
}> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite!.exec(`
|
||||
CREATE TABLE host_access (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_id INTEGER NOT NULL,
|
||||
user_id TEXT,
|
||||
role_id INTEGER,
|
||||
granted_by TEXT NOT NULL,
|
||||
permission_level TEXT NOT NULL DEFAULT 'connect',
|
||||
expires_at TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
last_accessed_at TEXT,
|
||||
access_count INTEGER NOT NULL DEFAULT 0,
|
||||
override_credential_id INTEGER
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT,
|
||||
ip TEXT NOT NULL,
|
||||
port INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
credential_id INTEGER,
|
||||
rdp_credential_id INTEGER,
|
||||
vnc_credential_id INTEGER,
|
||||
telnet_credential_id INTEGER
|
||||
);
|
||||
|
||||
CREATE TABLE shared_host_secrets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
host_access_id INTEGER NOT NULL,
|
||||
target_user_id TEXT NOT NULL,
|
||||
protocol TEXT NOT NULL DEFAULT 'ssh',
|
||||
source_type TEXT NOT NULL DEFAULT 'credential',
|
||||
original_credential_id INTEGER,
|
||||
encrypted_username TEXT,
|
||||
encrypted_auth_type TEXT,
|
||||
encrypted_password TEXT,
|
||||
encrypted_key TEXT,
|
||||
encrypted_key_password TEXT,
|
||||
encrypted_key_type TEXT,
|
||||
encrypted_domain TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(host_access_id, target_user_id, protocol)
|
||||
);
|
||||
|
||||
INSERT INTO ssh_data (id, user_id, name, ip, port, username, credential_id, rdp_credential_id)
|
||||
VALUES
|
||||
(42, 'owner-1', 'prod', '10.0.0.42', 22, 'root', 123, 124),
|
||||
(43, 'owner-1', 'staging', '10.0.0.43', 22, 'root', NULL, NULL),
|
||||
(44, 'owner-2', 'other', '10.0.0.44', 22, 'root', 123, NULL);
|
||||
|
||||
INSERT INTO host_access (id, host_id, user_id, role_id, granted_by)
|
||||
VALUES
|
||||
(1, 42, 'user-1', NULL, 'owner-1'),
|
||||
(2, 42, NULL, 7, 'owner-1'),
|
||||
(3, 43, 'user-2', NULL, 'owner-1');
|
||||
`);
|
||||
|
||||
return {
|
||||
repository: new SharedHostSecretsRepository(context, onWrite),
|
||||
sqlite: context.sqlite!,
|
||||
};
|
||||
}
|
||||
|
||||
it("upserts snapshots per protocol and finds them by host/user/protocol", async () => {
|
||||
let writeCount = 0;
|
||||
const { repository } = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repository.upsert({
|
||||
hostAccessId: 1,
|
||||
targetUserId: "user-1",
|
||||
protocol: "ssh",
|
||||
sourceType: "credential",
|
||||
originalCredentialId: 123,
|
||||
encryptedUsername: "enc-user",
|
||||
encryptedAuthType: "password",
|
||||
encryptedPassword: "enc-pass",
|
||||
});
|
||||
|
||||
await expect(
|
||||
repository.findForHostUserProtocol(42, "user-1", "ssh"),
|
||||
).resolves.toMatchObject({
|
||||
hostAccessId: 1,
|
||||
protocol: "ssh",
|
||||
encryptedPassword: "enc-pass",
|
||||
});
|
||||
|
||||
// Upsert on the same (grant, user, protocol) updates in place.
|
||||
await repository.upsert({
|
||||
hostAccessId: 1,
|
||||
targetUserId: "user-1",
|
||||
protocol: "ssh",
|
||||
sourceType: "inline",
|
||||
originalCredentialId: null,
|
||||
encryptedUsername: "enc-user-2",
|
||||
encryptedAuthType: "key",
|
||||
encryptedKey: "enc-key",
|
||||
});
|
||||
|
||||
const updated = await repository.findForHostUserProtocol(
|
||||
42,
|
||||
"user-1",
|
||||
"ssh",
|
||||
);
|
||||
expect(updated).toMatchObject({
|
||||
sourceType: "inline",
|
||||
encryptedUsername: "enc-user-2",
|
||||
encryptedKey: "enc-key",
|
||||
});
|
||||
|
||||
await expect(
|
||||
repository.findForHostUserProtocol(42, "user-1", "rdp"),
|
||||
).resolves.toBeNull();
|
||||
await expect(
|
||||
repository.findForHostUserProtocol(43, "user-1", "ssh"),
|
||||
).resolves.toBeNull();
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("deletes stale protocols while keeping the listed ones", async () => {
|
||||
const { repository } = await createRepository();
|
||||
|
||||
for (const protocol of ["ssh", "rdp", "vnc"] as const) {
|
||||
await repository.upsert({
|
||||
hostAccessId: 1,
|
||||
targetUserId: "user-1",
|
||||
protocol,
|
||||
sourceType: "inline",
|
||||
encryptedAuthType: "direct",
|
||||
});
|
||||
}
|
||||
|
||||
await repository.deleteForHostAccessAndTarget(1, "user-1", ["ssh"]);
|
||||
|
||||
await expect(
|
||||
repository.findForHostUserProtocol(42, "user-1", "ssh"),
|
||||
).resolves.not.toBeNull();
|
||||
await expect(
|
||||
repository.findForHostUserProtocol(42, "user-1", "rdp"),
|
||||
).resolves.toBeNull();
|
||||
await expect(
|
||||
repository.findForHostUserProtocol(42, "user-1", "vnc"),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("deletes by host access, target user, credential and role membership", async () => {
|
||||
const { repository } = await createRepository();
|
||||
|
||||
await repository.upsert({
|
||||
hostAccessId: 1,
|
||||
targetUserId: "user-1",
|
||||
protocol: "ssh",
|
||||
sourceType: "credential",
|
||||
originalCredentialId: 123,
|
||||
encryptedAuthType: "password",
|
||||
});
|
||||
await repository.upsert({
|
||||
hostAccessId: 2,
|
||||
targetUserId: "user-1",
|
||||
protocol: "ssh",
|
||||
sourceType: "credential",
|
||||
originalCredentialId: 123,
|
||||
encryptedAuthType: "password",
|
||||
});
|
||||
await repository.upsert({
|
||||
hostAccessId: 3,
|
||||
targetUserId: "user-2",
|
||||
protocol: "ssh",
|
||||
sourceType: "inline",
|
||||
encryptedAuthType: "password",
|
||||
});
|
||||
|
||||
// Role-membership cleanup: only grant 2 targets role 7.
|
||||
expect(await repository.deleteForRoleMember(7, "user-1")).toBe(1);
|
||||
await expect(
|
||||
repository.existsForHostAccessAndTargetUser(2, "user-1"),
|
||||
).resolves.toBe(false);
|
||||
await expect(
|
||||
repository.existsForHostAccessAndTargetUser(1, "user-1"),
|
||||
).resolves.toBe(true);
|
||||
|
||||
expect(await repository.deleteByHostAccessId(1)).toBe(1);
|
||||
expect(await repository.deleteByTargetUserId("user-2")).toBe(1);
|
||||
expect(await repository.deleteByOriginalCredentialId(123)).toBe(0);
|
||||
});
|
||||
|
||||
it("finds host ids referencing a credential for the owner", async () => {
|
||||
const { repository } = await createRepository();
|
||||
|
||||
await expect(
|
||||
repository.findHostIdsReferencingCredential("owner-1", 123),
|
||||
).resolves.toEqual([42]);
|
||||
await expect(
|
||||
repository.findHostIdsReferencingCredential("owner-1", 124),
|
||||
).resolves.toEqual([42]);
|
||||
await expect(
|
||||
repository.findHostIdsReferencingCredential("owner-1", 999),
|
||||
).resolves.toEqual([]);
|
||||
await expect(
|
||||
repository.findHostIdsReferencingCredential("owner-2", 123),
|
||||
).resolves.toEqual([44]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,379 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { SnippetRepository } from "../../../database/repositories/snippet-repository.js";
|
||||
|
||||
describe("SnippetRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(onWrite?: () => void): Promise<{
|
||||
repository: SnippetRepository;
|
||||
sqlite: NonNullable<
|
||||
Awaited<ReturnType<TestSqliteDatabase["connect"]>>["sqlite"]
|
||||
>;
|
||||
}> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE snippets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
description TEXT,
|
||||
folder TEXT,
|
||||
"order" INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
host_filter TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE snippet_folders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
color TEXT,
|
||||
icon TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO snippets (
|
||||
id, user_id, name, content, description, folder, "order", host_filter
|
||||
)
|
||||
VALUES
|
||||
(1, 'user-1', 'root', 'uptime', NULL, NULL, 2, NULL),
|
||||
(2, 'user-1', 'deploy', 'make deploy', 'Deploy app', 'ops', 1, 'linux'),
|
||||
(3, 'user-2', 'other', 'whoami', NULL, NULL, 1, NULL);
|
||||
|
||||
INSERT INTO snippet_folders (id, user_id, name, color, icon)
|
||||
VALUES
|
||||
(1, 'user-1', 'ops', '#123456', 'terminal'),
|
||||
(2, 'user-1', 'db', NULL, NULL),
|
||||
(3, 'user-2', 'other', NULL, NULL);
|
||||
`);
|
||||
|
||||
return {
|
||||
repository: new SnippetRepository(context, onWrite),
|
||||
sqlite: context.sqlite!,
|
||||
};
|
||||
}
|
||||
|
||||
it("finds owned snippets only", async () => {
|
||||
const { repository } = await createRepository();
|
||||
|
||||
await expect(repository.findOwnedById("user-1", 1)).resolves.toMatchObject({
|
||||
id: 1,
|
||||
userId: "user-1",
|
||||
name: "root",
|
||||
});
|
||||
await expect(repository.findOwnedById("user-1", 3)).resolves.toBeNull();
|
||||
await expect(repository.findOwnedById("user-1", 999)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("lists folders by name for a user", async () => {
|
||||
const { repository } = await createRepository();
|
||||
|
||||
const rows = await repository.listFolders("user-1");
|
||||
|
||||
expect(rows.map((row) => row.name)).toEqual(["db", "ops"]);
|
||||
});
|
||||
|
||||
it("lists export data for a user", async () => {
|
||||
const { repository } = await createRepository();
|
||||
|
||||
const snippets = await repository.listSnippetsForExport("user-1");
|
||||
const folders = await repository.listFoldersForExport("user-1");
|
||||
|
||||
expect(snippets.map((row) => row.name)).toEqual(["root", "deploy"]);
|
||||
expect(folders.map((row) => row.name)).toEqual(["db", "ops"]);
|
||||
});
|
||||
|
||||
it("lists owned snippets for route merging", async () => {
|
||||
const { repository } = await createRepository();
|
||||
|
||||
const rows = await repository.listOwnedSnippets("user-1");
|
||||
|
||||
expect(rows.map((row) => row.name)).toEqual(["root", "deploy"]);
|
||||
});
|
||||
|
||||
it("reorders snippets", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository } = await createRepository(onWrite);
|
||||
|
||||
await repository.reorderSnippets("user-1", [
|
||||
{ id: 1, order: 9, folder: " ops " },
|
||||
{ id: 999, order: 1 },
|
||||
]);
|
||||
|
||||
await expect(repository.findOwnedById("user-1", 1)).resolves.toMatchObject({
|
||||
order: 9,
|
||||
folder: "ops",
|
||||
});
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("creates snippets with the next folder order", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository } = await createRepository(onWrite);
|
||||
|
||||
const created = await repository.createSnippet("user-1", {
|
||||
name: " new ",
|
||||
content: " echo ok ",
|
||||
description: " desc ",
|
||||
folder: "ops",
|
||||
hostFilter: { os: "linux" },
|
||||
});
|
||||
|
||||
expect(created).toMatchObject({
|
||||
userId: "user-1",
|
||||
name: "new",
|
||||
content: "echo ok",
|
||||
description: "desc",
|
||||
folder: "ops",
|
||||
order: 2,
|
||||
hostFilter: JSON.stringify({ os: "linux" }),
|
||||
});
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("updates snippets and returns the original row for audit names", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository } = await createRepository(onWrite);
|
||||
|
||||
const result = await repository.updateSnippet("user-1", 2, {
|
||||
name: " deploy new ",
|
||||
content: " make deploy2 ",
|
||||
description: null,
|
||||
folder: null,
|
||||
order: 7,
|
||||
hostFilter: null,
|
||||
});
|
||||
const missing = await repository.updateSnippet("user-1", 3, {
|
||||
name: "nope",
|
||||
});
|
||||
|
||||
expect(result?.existing).toMatchObject({ name: "deploy" });
|
||||
expect(result?.updated).toMatchObject({
|
||||
name: "deploy new",
|
||||
content: "make deploy2",
|
||||
description: null,
|
||||
folder: null,
|
||||
order: 7,
|
||||
hostFilter: null,
|
||||
});
|
||||
expect(missing).toBeNull();
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("deletes snippets and returns the deleted row for audit names", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository } = await createRepository(onWrite);
|
||||
|
||||
const deleted = await repository.deleteSnippet("user-1", 2);
|
||||
const missing = await repository.deleteSnippet("user-1", 3);
|
||||
|
||||
expect(deleted).toMatchObject({ id: 2, name: "deploy" });
|
||||
expect(missing).toBeNull();
|
||||
await expect(repository.findOwnedById("user-1", 2)).resolves.toBeNull();
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("deletes all snippets and folders for a user", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository, sqlite } = await createRepository(onWrite);
|
||||
|
||||
await expect(repository.deleteByUserId("user-1")).resolves.toEqual({
|
||||
snippetsDeleted: 2,
|
||||
foldersDeleted: 2,
|
||||
});
|
||||
|
||||
expect(sqlite.prepare("SELECT id FROM snippets ORDER BY id").all()).toEqual(
|
||||
[{ id: 3 }],
|
||||
);
|
||||
expect(
|
||||
sqlite.prepare("SELECT id FROM snippet_folders ORDER BY id").all(),
|
||||
).toEqual([{ id: 3 }]);
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("bulk imports folders and snippets", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository } = await createRepository(onWrite);
|
||||
|
||||
const result = await repository.bulkImport(
|
||||
"user-1",
|
||||
[
|
||||
{
|
||||
name: " new snippet ",
|
||||
content: " echo hi ",
|
||||
description: " desc ",
|
||||
folder: " new folder ",
|
||||
hostFilter: "linux",
|
||||
},
|
||||
{ name: "", content: "bad" },
|
||||
{ name: "deploy", content: "skip", folder: "ops" },
|
||||
],
|
||||
[
|
||||
{ name: " new folder ", color: " #fff ", icon: " star " },
|
||||
{ name: "ops" },
|
||||
{ name: "" },
|
||||
],
|
||||
false,
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
snippetsImported: 1,
|
||||
snippetsSkipped: 1,
|
||||
snippetsUpdated: 0,
|
||||
foldersImported: 1,
|
||||
foldersSkipped: 1,
|
||||
failed: 2,
|
||||
errors: [
|
||||
"Folder missing name",
|
||||
"Snippet 2: name and content are required",
|
||||
],
|
||||
});
|
||||
await expect(repository.findOwnedById("user-1", 4)).resolves.toMatchObject({
|
||||
name: "new snippet",
|
||||
content: "echo hi",
|
||||
description: "desc",
|
||||
folder: "new folder",
|
||||
order: 0,
|
||||
hostFilter: "linux",
|
||||
});
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("bulk import overwrites existing snippets", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository } = await createRepository(onWrite);
|
||||
|
||||
const result = await repository.bulkImport(
|
||||
"user-1",
|
||||
[
|
||||
{
|
||||
name: "deploy",
|
||||
content: "make deploy v2",
|
||||
folder: "ops",
|
||||
order: 5,
|
||||
hostFilter: "prod",
|
||||
},
|
||||
],
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
snippetsImported: 0,
|
||||
snippetsSkipped: 0,
|
||||
snippetsUpdated: 1,
|
||||
failed: 0,
|
||||
});
|
||||
await expect(repository.findOwnedById("user-1", 2)).resolves.toMatchObject({
|
||||
content: "make deploy v2",
|
||||
order: 5,
|
||||
hostFilter: "prod",
|
||||
});
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("creates folders and rejects duplicate names", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository } = await createRepository(onWrite);
|
||||
|
||||
const created = await repository.createFolder(
|
||||
"user-1",
|
||||
" new ",
|
||||
" #fff ",
|
||||
" star ",
|
||||
);
|
||||
const duplicate = await repository.createFolder(
|
||||
"user-1",
|
||||
"ops",
|
||||
null,
|
||||
null,
|
||||
);
|
||||
|
||||
expect(created).toMatchObject({
|
||||
userId: "user-1",
|
||||
name: "new",
|
||||
color: "#fff",
|
||||
icon: "star",
|
||||
});
|
||||
expect(duplicate).toBeNull();
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("updates folder metadata", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository } = await createRepository(onWrite);
|
||||
|
||||
const updated = await repository.updateFolderMetadata(
|
||||
"user-1",
|
||||
"ops",
|
||||
" #abc ",
|
||||
undefined,
|
||||
);
|
||||
const missing = await repository.updateFolderMetadata(
|
||||
"user-1",
|
||||
"missing",
|
||||
null,
|
||||
null,
|
||||
);
|
||||
|
||||
expect(updated).toMatchObject({
|
||||
name: "ops",
|
||||
color: "#abc",
|
||||
icon: "terminal",
|
||||
});
|
||||
expect(missing).toBeNull();
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("renames folders and attached snippets", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository } = await createRepository(onWrite);
|
||||
|
||||
await expect(
|
||||
repository.renameFolder("user-1", "missing", "new"),
|
||||
).resolves.toEqual({ status: "missing" });
|
||||
await expect(
|
||||
repository.renameFolder("user-1", "ops", "db"),
|
||||
).resolves.toEqual({
|
||||
status: "conflict",
|
||||
});
|
||||
await expect(
|
||||
repository.renameFolder("user-1", "ops", "deploys"),
|
||||
).resolves.toEqual({ status: "renamed" });
|
||||
|
||||
await expect(repository.listFolders("user-1")).resolves.toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ name: "deploys" })]),
|
||||
);
|
||||
await expect(repository.findOwnedById("user-1", 2)).resolves.toMatchObject({
|
||||
folder: "deploys",
|
||||
});
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("deletes folders and moves snippets to the root", async () => {
|
||||
const onWrite = vi.fn();
|
||||
const { repository } = await createRepository(onWrite);
|
||||
|
||||
await repository.deleteFolder("user-1", "ops");
|
||||
|
||||
expect(
|
||||
(await repository.listFolders("user-1")).map((row) => row.name),
|
||||
).toEqual(["db"]);
|
||||
await expect(repository.findOwnedById("user-1", 2)).resolves.toMatchObject({
|
||||
folder: null,
|
||||
});
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { SshCredentialUsageRepository } from "../../../database/repositories/ssh-credential-usage-repository.js";
|
||||
|
||||
describe("SshCredentialUsageRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<SshCredentialUsageRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE hosts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_credentials (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_credential_usage (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
credential_id INTEGER NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
used_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO hosts (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'one'), (2, 'user-1', 'two'), (3, 'user-2', 'other');
|
||||
INSERT INTO ssh_credentials (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'cred-one'), (2, 'user-2', 'cred-two');
|
||||
`);
|
||||
|
||||
return new SshCredentialUsageRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates usage records", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const created = await repo.create(1, 1, "user-1");
|
||||
|
||||
expect(created).toMatchObject({
|
||||
credentialId: 1,
|
||||
hostId: 1,
|
||||
userId: "user-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("lists usage records by user", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.create(1, 1, "user-1");
|
||||
await repo.create(1, 2, "user-1");
|
||||
await repo.create(2, 3, "user-2");
|
||||
|
||||
expect(
|
||||
(await repo.listByUserId("user-1")).map((row) => row.hostId),
|
||||
).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
it("deletes usage records by user, host, and host list", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.create(1, 1, "user-1");
|
||||
await repo.create(1, 2, "user-1");
|
||||
await repo.create(2, 3, "user-2");
|
||||
expect(writeCount).toBe(3);
|
||||
|
||||
expect(await repo.deleteByHostId(1)).toBe(1);
|
||||
expect(await repo.deleteByHostId(1)).toBe(0);
|
||||
expect(await repo.deleteByHostIds([])).toBe(0);
|
||||
expect(await repo.deleteByHostIds([2])).toBe(1);
|
||||
expect(writeCount).toBe(5);
|
||||
|
||||
expect(await repo.deleteByUserId("user-2")).toBe(1);
|
||||
expect(await repo.deleteByUserId("user-2")).toBe(0);
|
||||
expect(writeCount).toBe(6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { SsoProviderRepository } from "../../../database/repositories/sso-provider-repository.js";
|
||||
|
||||
describe("SsoProviderRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
let sqlite: Awaited<ReturnType<TestSqliteDatabase["connect"]>>["sqlite"];
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
sqlite = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<SsoProviderRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
sqlite = context.sqlite;
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0,
|
||||
sso_provider_id INTEGER
|
||||
);
|
||||
|
||||
CREATE TABLE sso_providers (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
type TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
display_order INTEGER NOT NULL DEFAULT 0,
|
||||
config TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
`);
|
||||
|
||||
return new SsoProviderRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("creates, lists, finds, updates, and deletes providers", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const disabled = await repo.create({
|
||||
name: "Disabled",
|
||||
type: "oidc",
|
||||
enabled: false,
|
||||
displayOrder: 1,
|
||||
config: "{}",
|
||||
});
|
||||
const enabled = await repo.create({
|
||||
name: "GitHub",
|
||||
type: "github",
|
||||
enabled: true,
|
||||
displayOrder: 0,
|
||||
config: '{"client_id":"id"}',
|
||||
});
|
||||
|
||||
expect((await repo.listEnabledPublic()).map((row) => row.id)).toEqual([
|
||||
enabled.id,
|
||||
]);
|
||||
expect((await repo.listAll()).map((row) => row.id)).toEqual([
|
||||
enabled.id,
|
||||
disabled.id,
|
||||
]);
|
||||
expect((await repo.findById(enabled.id))?.name).toBe("GitHub");
|
||||
expect((await repo.findFirstEnabledOidcLike())?.id).toBe(enabled.id);
|
||||
|
||||
const updated = await repo.update(enabled.id, {
|
||||
name: "GitHub SSO",
|
||||
config: '{"client_id":"updated"}',
|
||||
updatedAt: "2026-06-27T00:00:00.000Z",
|
||||
});
|
||||
expect(updated?.name).toBe("GitHub SSO");
|
||||
expect(updated?.config).toContain("updated");
|
||||
|
||||
expect(await repo.delete(enabled.id)).toBe(true);
|
||||
expect(await repo.findById(enabled.id)).toBeNull();
|
||||
expect(await repo.delete(enabled.id)).toBe(false);
|
||||
});
|
||||
|
||||
it("counts users associated with a provider", async () => {
|
||||
const repo = await createRepository();
|
||||
const provider = await repo.create({
|
||||
name: "LDAP",
|
||||
type: "ldap",
|
||||
enabled: true,
|
||||
displayOrder: 0,
|
||||
config: "{}",
|
||||
});
|
||||
|
||||
sqlite?.exec(`
|
||||
INSERT INTO users (id, username, password_hash, sso_provider_id)
|
||||
VALUES ('user-1', 'u1', 'hash', ${provider.id}),
|
||||
('user-2', 'u2', 'hash', ${provider.id}),
|
||||
('user-3', 'u3', 'hash', NULL);
|
||||
`);
|
||||
|
||||
expect(await repo.countUsersByProviderId(provider.id)).toBe(2);
|
||||
});
|
||||
|
||||
it("runs the write hook after provider writes", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const provider = await repo.create({
|
||||
name: "OIDC",
|
||||
type: "oidc",
|
||||
enabled: true,
|
||||
displayOrder: 0,
|
||||
config: "{}",
|
||||
});
|
||||
await repo.update(provider.id, { enabled: false });
|
||||
await repo.delete(provider.id);
|
||||
await repo.delete(provider.id);
|
||||
|
||||
expect(writeCount).toBe(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { DataCrypto } from "../../../utils/data-crypto.js";
|
||||
import { TermixIdentityCaRepository } from "../../../database/repositories/termix-identity-ca-repository.js";
|
||||
|
||||
describe("TermixIdentityCaRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(onWrite = vi.fn()): Promise<{
|
||||
repo: TermixIdentityCaRepository;
|
||||
sqlite: NonNullable<
|
||||
Awaited<ReturnType<TestSqliteDatabase["connect"]>>["sqlite"]
|
||||
>;
|
||||
onWrite: ReturnType<typeof vi.fn>;
|
||||
}> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE termix_identities (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL UNIQUE,
|
||||
handle TEXT NOT NULL UNIQUE,
|
||||
description TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE termix_identity_ca (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
identity_id INTEGER NOT NULL UNIQUE,
|
||||
user_id TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
private_key TEXT NOT NULL,
|
||||
validity_days INTEGER NOT NULL DEFAULT 90,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (identity_id) REFERENCES termix_identities(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash');
|
||||
INSERT INTO termix_identities (id, user_id, handle)
|
||||
VALUES (7, 'user-1', 'alice');
|
||||
`);
|
||||
|
||||
return {
|
||||
repo: new TermixIdentityCaRepository(context, onWrite),
|
||||
sqlite: context.sqlite!,
|
||||
onWrite,
|
||||
};
|
||||
}
|
||||
|
||||
function mockCrypto(): void {
|
||||
vi.spyOn(DataCrypto, "validateUserAccess").mockReturnValue(
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
vi.spyOn(DataCrypto, "getUserDataKey").mockReturnValue(
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
vi.spyOn(DataCrypto, "encryptRecord").mockImplementation(
|
||||
(_tableName, record) =>
|
||||
({
|
||||
...record,
|
||||
privateKey: "encrypted-ca-private",
|
||||
}) as typeof record,
|
||||
);
|
||||
vi.spyOn(DataCrypto, "decryptRecord").mockImplementation(
|
||||
(_tableName, record) =>
|
||||
({
|
||||
...record,
|
||||
privateKey:
|
||||
record.privateKey === "encrypted-ca-private"
|
||||
? "decrypted-ca-private"
|
||||
: record.privateKey,
|
||||
}) as typeof record,
|
||||
);
|
||||
}
|
||||
|
||||
it("creates CA private keys with the real row id before encryption", async () => {
|
||||
const { repo, sqlite, onWrite } = await createRepository();
|
||||
mockCrypto();
|
||||
|
||||
const created = await repo.createEncryptedForUser("user-1", {
|
||||
identityId: 7,
|
||||
userId: "user-1",
|
||||
publicKey: "ssh-ed25519 public",
|
||||
privateKey: "plain-ca-private",
|
||||
validityDays: 120,
|
||||
});
|
||||
|
||||
const raw = sqlite
|
||||
.prepare(
|
||||
"SELECT id, public_key, private_key, validity_days FROM termix_identity_ca WHERE identity_id = ?",
|
||||
)
|
||||
.get(7) as {
|
||||
id: number;
|
||||
public_key: string;
|
||||
private_key: string;
|
||||
validity_days: number;
|
||||
};
|
||||
|
||||
expect(created.privateKey).toBe("decrypted-ca-private");
|
||||
expect(raw.private_key).toBe("encrypted-ca-private");
|
||||
expect(raw.public_key).toBe("ssh-ed25519 public");
|
||||
expect(raw.validity_days).toBe(120);
|
||||
expect(DataCrypto.encryptRecord).toHaveBeenCalledWith(
|
||||
"termix_identity_ca",
|
||||
{ id: raw.id, privateKey: "plain-ca-private" },
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reads public CA metadata without decrypting private key material", async () => {
|
||||
const { repo, sqlite } = await createRepository();
|
||||
const decryptSpy = vi.spyOn(DataCrypto, "decryptRecord");
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run(7, "user-1", "ssh-ed25519 public", "encrypted-ca-private", 45);
|
||||
|
||||
await expect(repo.findPublicByIdentityId(7)).resolves.toEqual({
|
||||
publicKey: "ssh-ed25519 public",
|
||||
validityDays: 45,
|
||||
});
|
||||
expect(decryptSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("decrypts CA private keys through the user data boundary", async () => {
|
||||
const { repo, sqlite } = await createRepository();
|
||||
mockCrypto();
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run(7, "user-1", "ssh-ed25519 public", "encrypted-ca-private", 45);
|
||||
|
||||
const ca = await repo.findDecryptedByIdentityId("user-1", 7);
|
||||
|
||||
expect(ca).toMatchObject({
|
||||
identityId: 7,
|
||||
publicKey: "ssh-ed25519 public",
|
||||
privateKey: "decrypted-ca-private",
|
||||
validityDays: 45,
|
||||
});
|
||||
expect(DataCrypto.decryptRecord).toHaveBeenCalledWith(
|
||||
"termix_identity_ca",
|
||||
expect.objectContaining({ identityId: 7 }),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
});
|
||||
|
||||
it("updates CA private keys through encrypted writes", async () => {
|
||||
const { repo, sqlite, onWrite } = await createRepository();
|
||||
mockCrypto();
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run(7, "user-1", "ssh-ed25519 old", "encrypted-ca-private", 45);
|
||||
onWrite.mockClear();
|
||||
|
||||
const updated = await repo.updateEncryptedForIdentity("user-1", 7, {
|
||||
publicKey: "ssh-ed25519 new",
|
||||
privateKey: "plain-updated-ca-private",
|
||||
validityDays: 90,
|
||||
});
|
||||
|
||||
const raw = sqlite
|
||||
.prepare(
|
||||
"SELECT public_key, private_key, validity_days FROM termix_identity_ca WHERE identity_id = ?",
|
||||
)
|
||||
.get(7) as {
|
||||
public_key: string;
|
||||
private_key: string;
|
||||
validity_days: number;
|
||||
};
|
||||
|
||||
expect(updated).toMatchObject({
|
||||
publicKey: "ssh-ed25519 new",
|
||||
privateKey: "decrypted-ca-private",
|
||||
validityDays: 90,
|
||||
});
|
||||
expect(raw).toEqual({
|
||||
public_key: "ssh-ed25519 new",
|
||||
private_key: "encrypted-ca-private",
|
||||
validity_days: 90,
|
||||
});
|
||||
expect(DataCrypto.encryptRecord).toHaveBeenCalledWith(
|
||||
"termix_identity_ca",
|
||||
expect.objectContaining({
|
||||
privateKey: "plain-updated-ca-private",
|
||||
}),
|
||||
"user-1",
|
||||
Buffer.from("user-key"),
|
||||
);
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("deletes CA rows through the write boundary", async () => {
|
||||
const { repo, sqlite, onWrite } = await createRepository();
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run(7, "user-1", "ssh-ed25519 public", "encrypted-ca-private", 45);
|
||||
onWrite.mockClear();
|
||||
|
||||
await expect(repo.deleteByIdentityId(7)).resolves.toBe(true);
|
||||
await expect(repo.deleteByIdentityId(7)).resolves.toBe(false);
|
||||
expect(
|
||||
sqlite.prepare("SELECT COUNT(*) AS count FROM termix_identity_ca").get(),
|
||||
).toEqual({ count: 0 });
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("deletes CA rows for a user", async () => {
|
||||
const { repo, sqlite, onWrite } = await createRepository();
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO users (id, username, password_hash) VALUES (?, ?, ?)",
|
||||
)
|
||||
.run("user-2", "bob", "hash");
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO termix_identities (id, user_id, handle) VALUES (?, ?, ?)",
|
||||
)
|
||||
.run(8, "user-2", "bob");
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run(7, "user-1", "ssh-ed25519 public", "encrypted-ca-private", 45);
|
||||
sqlite
|
||||
.prepare(
|
||||
"INSERT INTO termix_identity_ca (identity_id, user_id, public_key, private_key, validity_days) VALUES (?, ?, ?, ?, ?)",
|
||||
)
|
||||
.run(8, "user-2", "ssh-ed25519 other", "encrypted-other", 90);
|
||||
onWrite.mockClear();
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toBe(1);
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
|
||||
|
||||
expect(
|
||||
sqlite
|
||||
.prepare(
|
||||
"SELECT user_id, public_key FROM termix_identity_ca ORDER BY user_id",
|
||||
)
|
||||
.all(),
|
||||
).toEqual([{ user_id: "user-2", public_key: "ssh-ed25519 other" }]);
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { TermixIdentityRepository } from "../../../database/repositories/termix-identity-repository.js";
|
||||
|
||||
describe("TermixIdentityRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(onWrite = vi.fn()): Promise<{
|
||||
repo: TermixIdentityRepository;
|
||||
onWrite: ReturnType<typeof vi.fn>;
|
||||
}> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE termix_identities (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL UNIQUE,
|
||||
handle TEXT NOT NULL UNIQUE,
|
||||
description TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE termix_identity_keys (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
identity_id INTEGER NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
key_type TEXT NOT NULL,
|
||||
algorithm TEXT NOT NULL,
|
||||
label TEXT,
|
||||
comment TEXT,
|
||||
source TEXT NOT NULL DEFAULT 'manual',
|
||||
credential_id INTEGER,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (identity_id) REFERENCES termix_identities(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
`);
|
||||
|
||||
return {
|
||||
repo: new TermixIdentityRepository(context, onWrite),
|
||||
onWrite,
|
||||
};
|
||||
}
|
||||
|
||||
it("creates, updates, finds, and deletes identities", async () => {
|
||||
const { repo, onWrite } = await createRepository();
|
||||
|
||||
const created = await repo.createIdentity({
|
||||
userId: "user-1",
|
||||
handle: "alice",
|
||||
description: "workstation keys",
|
||||
});
|
||||
|
||||
expect(created.id).toBeGreaterThan(0);
|
||||
expect(await repo.isHandleTaken("alice")).toBe(true);
|
||||
expect(await repo.findIdentityForUser("user-1")).toMatchObject({
|
||||
handle: "alice",
|
||||
});
|
||||
expect(await repo.findIdentityByHandle("alice")).toMatchObject({
|
||||
userId: "user-1",
|
||||
});
|
||||
|
||||
const updated = await repo.updateIdentityForUser("user-1", {
|
||||
handle: "alice-renamed",
|
||||
description: null,
|
||||
});
|
||||
expect(updated).toMatchObject({
|
||||
handle: "alice-renamed",
|
||||
description: null,
|
||||
});
|
||||
|
||||
await expect(repo.deleteIdentityForUser("user-1")).resolves.toBe(true);
|
||||
await expect(repo.deleteIdentityForUser("user-1")).resolves.toBe(false);
|
||||
await expect(repo.findIdentityForUser("user-1")).resolves.toBeNull();
|
||||
expect(onWrite).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("creates, lists, updates, deletes, and links public keys", async () => {
|
||||
const { repo, onWrite } = await createRepository();
|
||||
const identity = await repo.createIdentity({
|
||||
userId: "user-1",
|
||||
handle: "alice",
|
||||
description: null,
|
||||
});
|
||||
onWrite.mockClear();
|
||||
|
||||
const first = await repo.createKey({
|
||||
identityId: identity.id,
|
||||
userId: "user-1",
|
||||
publicKey: "ssh-ed25519 AAAA1",
|
||||
keyType: "ssh-ed25519",
|
||||
algorithm: "ED25519",
|
||||
label: "laptop",
|
||||
comment: null,
|
||||
source: "credential",
|
||||
credentialId: 10,
|
||||
});
|
||||
await repo.createKey({
|
||||
identityId: identity.id,
|
||||
userId: "user-1",
|
||||
publicKey: "ssh-rsa AAAA2",
|
||||
keyType: "ssh-rsa",
|
||||
algorithm: "RSA",
|
||||
label: "disabled",
|
||||
comment: null,
|
||||
source: "manual",
|
||||
credentialId: 20,
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
expect(await repo.listKeysByIdentityId(identity.id)).toHaveLength(2);
|
||||
expect(await repo.listEnabledKeysByIdentityId(identity.id)).toMatchObject([
|
||||
{ id: first.id, publicKey: "ssh-ed25519 AAAA1" },
|
||||
]);
|
||||
expect(await repo.listLinkedCredentialIds(identity.id)).toEqual([10]);
|
||||
|
||||
const updated = await repo.updateKeyForUser("user-1", first.id, {
|
||||
enabled: false,
|
||||
label: "revoked",
|
||||
});
|
||||
expect(updated).toMatchObject({ enabled: false, label: "revoked" });
|
||||
await expect(
|
||||
repo.findKeyForUser("user-1", first.id),
|
||||
).resolves.toMatchObject({ label: "revoked" });
|
||||
|
||||
await expect(repo.deleteKeyForUser("user-1", first.id)).resolves.toBe(true);
|
||||
await expect(repo.deleteKeyForUser("user-1", first.id)).resolves.toBe(
|
||||
false,
|
||||
);
|
||||
expect(onWrite).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it("deletes identities and keys for a user", async () => {
|
||||
const { repo, onWrite } = await createRepository();
|
||||
const userIdentity = await repo.createIdentity({
|
||||
userId: "user-1",
|
||||
handle: "alice",
|
||||
description: null,
|
||||
});
|
||||
const otherIdentity = await repo.createIdentity({
|
||||
userId: "user-2",
|
||||
handle: "bob",
|
||||
description: null,
|
||||
});
|
||||
await repo.createKey({
|
||||
identityId: userIdentity.id,
|
||||
userId: "user-1",
|
||||
publicKey: "ssh-ed25519 AAAA1",
|
||||
keyType: "ssh-ed25519",
|
||||
algorithm: "ED25519",
|
||||
source: "manual",
|
||||
});
|
||||
await repo.createKey({
|
||||
identityId: otherIdentity.id,
|
||||
userId: "user-2",
|
||||
publicKey: "ssh-ed25519 AAAA2",
|
||||
keyType: "ssh-ed25519",
|
||||
algorithm: "ED25519",
|
||||
source: "manual",
|
||||
});
|
||||
onWrite.mockClear();
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toEqual({
|
||||
identitiesDeleted: 1,
|
||||
keysDeleted: 1,
|
||||
});
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toEqual({
|
||||
identitiesDeleted: 0,
|
||||
keysDeleted: 0,
|
||||
});
|
||||
|
||||
expect(await repo.findIdentityForUser("user-1")).toBeNull();
|
||||
expect(await repo.listKeysByIdentityId(userIdentity.id)).toEqual([]);
|
||||
expect(await repo.findIdentityForUser("user-2")).toMatchObject({
|
||||
handle: "bob",
|
||||
});
|
||||
expect(await repo.listKeysByIdentityId(otherIdentity.id)).toHaveLength(1);
|
||||
expect(onWrite).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import Database from "better-sqlite3";
|
||||
import { drizzle } from "drizzle-orm/better-sqlite3";
|
||||
import * as schema from "../../../database/db/schema.js";
|
||||
import type { DatabaseContext } from "../../../database/repositories/database-context.js";
|
||||
|
||||
export class TestSqliteDatabase {
|
||||
private sqlite: Database.Database | null = null;
|
||||
private context: DatabaseContext | null = null;
|
||||
|
||||
async connect(): Promise<DatabaseContext> {
|
||||
if (this.context) return this.context;
|
||||
|
||||
this.sqlite = new Database(":memory:");
|
||||
this.sqlite.exec("PRAGMA foreign_keys = ON");
|
||||
this.context = {
|
||||
dialect: "sqlite",
|
||||
drizzle: drizzle(this.sqlite, { schema }),
|
||||
sqlite: this.sqlite,
|
||||
};
|
||||
|
||||
return this.context;
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (this.sqlite) {
|
||||
this.sqlite.close();
|
||||
this.sqlite = null;
|
||||
this.context = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { TmuxSessionTagRepository } from "../../../database/repositories/tmux-session-tag-repository.js";
|
||||
|
||||
describe("TmuxSessionTagRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<TmuxSessionTagRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE hosts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE tmux_session_tags (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
host_id INTEGER NOT NULL,
|
||||
session_name TEXT NOT NULL,
|
||||
tag TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO hosts (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'one'), (2, 'user-2', 'two');
|
||||
INSERT INTO tmux_session_tags (user_id, host_id, session_name, tag)
|
||||
VALUES
|
||||
('user-1', 1, 'api', 'prod'),
|
||||
('user-1', 1, 'api', 'critical'),
|
||||
('user-1', 1, 'worker', 'batch'),
|
||||
('user-2', 2, 'api', 'other');
|
||||
`);
|
||||
|
||||
return new TmuxSessionTagRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("groups tags by session for a user and host", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const tags = await repo.listByUserAndHost("user-1", 1);
|
||||
|
||||
expect(tags.get("api")).toEqual(["prod", "critical"]);
|
||||
expect(tags.get("worker")).toEqual(["batch"]);
|
||||
expect(tags.has("missing")).toBe(false);
|
||||
});
|
||||
|
||||
it("renames and deletes session tags by host/session", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(await repo.renameSessionForHost(1, "api", "api-renamed")).toBe(2);
|
||||
expect(await repo.renameSessionForHost(1, "missing", "noop")).toBe(0);
|
||||
|
||||
const renamed = await repo.listByUserAndHost("user-1", 1);
|
||||
expect(renamed.get("api-renamed")).toEqual(["prod", "critical"]);
|
||||
expect(renamed.has("api")).toBe(false);
|
||||
|
||||
expect(await repo.deleteSessionForHost(1, "api-renamed")).toBe(2);
|
||||
expect(await repo.deleteSessionForHost(1, "api-renamed")).toBe(0);
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("replaces tags for one user/host/session", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(
|
||||
await repo.replaceForUserHostSession("user-1", 1, "api", [
|
||||
"blue",
|
||||
"green",
|
||||
]),
|
||||
).toBe(4);
|
||||
|
||||
const tags = await repo.listByUserAndHost("user-1", 1);
|
||||
expect(tags.get("api")).toEqual(["blue", "green"]);
|
||||
expect(tags.get("worker")).toEqual(["batch"]);
|
||||
|
||||
expect(
|
||||
await repo.replaceForUserHostSession("user-1", 1, "worker", []),
|
||||
).toBe(1);
|
||||
expect(
|
||||
await repo.replaceForUserHostSession("user-1", 1, "missing", []),
|
||||
).toBe(0);
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("deletes all tags for a user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toBe(3);
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
|
||||
|
||||
expect(await repo.listByUserAndHost("user-1", 1)).toEqual(new Map());
|
||||
expect(await repo.listByUserAndHost("user-2", 2)).toEqual(
|
||||
new Map([["api", ["other"]]]),
|
||||
);
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { TransferRecentRepository } from "../../../database/repositories/transfer-recent-repository.js";
|
||||
|
||||
describe("TransferRecentRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<TransferRecentRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE hosts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE transfer_recent (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
source_host_id INTEGER NOT NULL,
|
||||
dest_host_id INTEGER NOT NULL,
|
||||
dest_path TEXT NOT NULL,
|
||||
dest_path_label TEXT NOT NULL,
|
||||
last_used TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO hosts (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'source'), (2, 'user-1', 'dest-a'), (3, 'user-1', 'dest-b'), (4, 'user-2', 'other');
|
||||
`);
|
||||
|
||||
return new TransferRecentRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("upserts, lists, and prunes recent transfer destinations", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsertForDestination(
|
||||
"user-1",
|
||||
{ sourceHostId: 1, destHostId: 2, destPath: "/var/www" },
|
||||
"2026-01-01T00:00:00.000Z",
|
||||
);
|
||||
await repo.upsertForDestination(
|
||||
"user-1",
|
||||
{
|
||||
sourceHostId: 1,
|
||||
destHostId: 3,
|
||||
destPath: "/opt/app",
|
||||
destPathLabel: "App",
|
||||
},
|
||||
"2026-01-02T00:00:00.000Z",
|
||||
);
|
||||
await repo.upsertForDestination(
|
||||
"user-1",
|
||||
{ sourceHostId: 1, destHostId: 2, destPath: "/var/www" },
|
||||
"2026-01-03T00:00:00.000Z",
|
||||
);
|
||||
|
||||
const recent = await repo.listBySourceHost("user-1", 1);
|
||||
|
||||
expect(recent).toHaveLength(2);
|
||||
expect(recent.map((entry) => entry.destPath)).toEqual([
|
||||
"/var/www",
|
||||
"/opt/app",
|
||||
]);
|
||||
expect(recent[0].lastUsed).toBe("2026-01-03T00:00:00.000Z");
|
||||
expect(recent[0].destPathLabel).toBe("/var/www");
|
||||
expect(writeCount).toBe(3);
|
||||
|
||||
expect(await repo.pruneSourceHost("user-1", 1, 1)).toBe(1);
|
||||
expect(await repo.pruneSourceHost("user-1", 1, 1)).toBe(0);
|
||||
expect(await repo.listBySourceHost("user-1", 1)).toHaveLength(1);
|
||||
expect(writeCount).toBe(4);
|
||||
});
|
||||
|
||||
it("deletes recent transfer destinations by user and host references", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsertForDestination("user-1", {
|
||||
sourceHostId: 1,
|
||||
destHostId: 2,
|
||||
destPath: "/one",
|
||||
});
|
||||
await repo.upsertForDestination("user-1", {
|
||||
sourceHostId: 2,
|
||||
destHostId: 3,
|
||||
destPath: "/two",
|
||||
});
|
||||
await repo.upsertForDestination("user-2", {
|
||||
sourceHostId: 4,
|
||||
destHostId: 1,
|
||||
destPath: "/other",
|
||||
});
|
||||
expect(writeCount).toBe(3);
|
||||
|
||||
expect(await repo.deleteByHostId(1)).toBe(2);
|
||||
expect(await repo.deleteByHostId(1)).toBe(0);
|
||||
expect(writeCount).toBe(4);
|
||||
|
||||
await repo.upsertForDestination("user-1", {
|
||||
sourceHostId: 1,
|
||||
destHostId: 2,
|
||||
destPath: "/three",
|
||||
});
|
||||
expect(await repo.deleteByHostIds([])).toBe(0);
|
||||
expect(await repo.deleteByHostIds([2, 3])).toBe(2);
|
||||
expect(writeCount).toBe(6);
|
||||
|
||||
await repo.upsertForDestination("user-2", {
|
||||
sourceHostId: 4,
|
||||
destHostId: 1,
|
||||
destPath: "/last",
|
||||
});
|
||||
expect(await repo.deleteByUserId("user-2")).toBe(1);
|
||||
expect(await repo.deleteByUserId("user-2")).toBe(0);
|
||||
expect(writeCount).toBe(8);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { TrustedDeviceRepository } from "../../../database/repositories/trusted-device-repository.js";
|
||||
|
||||
describe("TrustedDeviceRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(onWrite?: () => void): Promise<{
|
||||
trustedDevices: TrustedDeviceRepository;
|
||||
}> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE trusted_devices (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
device_fingerprint TEXT NOT NULL,
|
||||
device_type TEXT NOT NULL,
|
||||
device_info TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TEXT NOT NULL,
|
||||
last_used_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash) VALUES
|
||||
('user-1', 'admin', 'hash'),
|
||||
('user-2', 'user', 'hash');
|
||||
`);
|
||||
|
||||
return {
|
||||
trustedDevices: new TrustedDeviceRepository(context, onWrite),
|
||||
};
|
||||
}
|
||||
|
||||
it("upserts, touches, finds, and deletes trusted devices", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
await repo.trustedDevices.upsert({
|
||||
id: "device-1",
|
||||
userId: "user-1",
|
||||
deviceFingerprint: "fingerprint",
|
||||
deviceType: "desktop",
|
||||
deviceInfo: "Firefox",
|
||||
createdAt: "2026-06-26T00:00:00.000Z",
|
||||
expiresAt: "2026-07-26T00:00:00.000Z",
|
||||
lastUsedAt: "2026-06-26T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(
|
||||
(
|
||||
await repo.trustedDevices.findByUserAndFingerprint(
|
||||
"user-1",
|
||||
"fingerprint",
|
||||
)
|
||||
)?.deviceType,
|
||||
).toBe("desktop");
|
||||
|
||||
await repo.trustedDevices.touch(
|
||||
"user-1",
|
||||
"fingerprint",
|
||||
"2026-06-26T01:00:00.000Z",
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await repo.trustedDevices.findByUserAndFingerprint(
|
||||
"user-1",
|
||||
"fingerprint",
|
||||
)
|
||||
)?.lastUsedAt,
|
||||
).toBe("2026-06-26T01:00:00.000Z");
|
||||
|
||||
await repo.trustedDevices.upsert({
|
||||
id: "device-ignored",
|
||||
userId: "user-1",
|
||||
deviceFingerprint: "fingerprint",
|
||||
deviceType: "mobile",
|
||||
deviceInfo: "Safari",
|
||||
expiresAt: "2026-08-26T00:00:00.000Z",
|
||||
lastUsedAt: "2026-06-26T02:00:00.000Z",
|
||||
});
|
||||
|
||||
const updated = await repo.trustedDevices.findByUserAndFingerprint(
|
||||
"user-1",
|
||||
"fingerprint",
|
||||
);
|
||||
expect(updated?.id).toBe("device-1");
|
||||
expect(updated?.deviceType).toBe("desktop");
|
||||
expect(updated?.expiresAt).toBe("2026-08-26T00:00:00.000Z");
|
||||
|
||||
await repo.trustedDevices.deleteByUserAndFingerprint(
|
||||
"user-1",
|
||||
"fingerprint",
|
||||
);
|
||||
expect(
|
||||
await repo.trustedDevices.findByUserAndFingerprint(
|
||||
"user-1",
|
||||
"fingerprint",
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("deletes all trusted devices for a user", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
for (const id of ["device-1", "device-2"]) {
|
||||
await repo.trustedDevices.upsert({
|
||||
id,
|
||||
userId: "user-2",
|
||||
deviceFingerprint: id,
|
||||
deviceType: "desktop",
|
||||
deviceInfo: "Firefox",
|
||||
expiresAt: "2026-07-26T00:00:00.000Z",
|
||||
});
|
||||
}
|
||||
|
||||
await repo.trustedDevices.deleteByUserId("user-2");
|
||||
|
||||
expect(
|
||||
await repo.trustedDevices.findByUserAndFingerprint("user-2", "device-1"),
|
||||
).toBeNull();
|
||||
expect(
|
||||
await repo.trustedDevices.findByUserAndFingerprint("user-2", "device-2"),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("runs the write hook after trusted device writes", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.trustedDevices.upsert({
|
||||
id: "device-1",
|
||||
userId: "user-1",
|
||||
deviceFingerprint: "fingerprint",
|
||||
deviceType: "desktop",
|
||||
deviceInfo: "Firefox",
|
||||
expiresAt: "2026-07-26T00:00:00.000Z",
|
||||
});
|
||||
await repo.trustedDevices.touch("user-1", "fingerprint");
|
||||
await repo.trustedDevices.deleteByUserAndFingerprint(
|
||||
"user-1",
|
||||
"fingerprint",
|
||||
);
|
||||
|
||||
expect(writeCount).toBe(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { UserDataExportRepository } from "../../../database/repositories/user-data-export-repository.js";
|
||||
|
||||
describe("UserDataExportRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(): Promise<UserDataExportRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
connection_type TEXT NOT NULL DEFAULT 'ssh',
|
||||
name TEXT,
|
||||
ip TEXT NOT NULL,
|
||||
port INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
folder TEXT,
|
||||
tags TEXT,
|
||||
pin INTEGER NOT NULL DEFAULT 0,
|
||||
auth_type TEXT NOT NULL,
|
||||
use_warpgate INTEGER NOT NULL DEFAULT 0,
|
||||
force_keyboard_interactive TEXT,
|
||||
password TEXT,
|
||||
key TEXT,
|
||||
key_password TEXT,
|
||||
key_type TEXT,
|
||||
sudo_password TEXT,
|
||||
autostart_password TEXT,
|
||||
autostart_key TEXT,
|
||||
autostart_key_password TEXT,
|
||||
credential_id INTEGER,
|
||||
override_credential_username INTEGER,
|
||||
vault_profile_id INTEGER,
|
||||
enable_terminal INTEGER NOT NULL DEFAULT 1,
|
||||
enable_session_logging INTEGER NOT NULL DEFAULT 1,
|
||||
enable_command_history INTEGER NOT NULL DEFAULT 1,
|
||||
enable_tunnel INTEGER NOT NULL DEFAULT 1,
|
||||
tunnel_connections TEXT,
|
||||
jump_hosts TEXT,
|
||||
enable_file_manager INTEGER NOT NULL DEFAULT 1,
|
||||
scp_legacy INTEGER NOT NULL DEFAULT 0,
|
||||
enable_docker INTEGER NOT NULL DEFAULT 0,
|
||||
enable_tmux_monitor INTEGER NOT NULL DEFAULT 0,
|
||||
show_terminal_in_sidebar INTEGER NOT NULL DEFAULT 1,
|
||||
show_file_manager_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_tunnel_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_docker_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
show_server_stats_in_sidebar INTEGER NOT NULL DEFAULT 0,
|
||||
default_path TEXT,
|
||||
stats_config TEXT,
|
||||
docker_config TEXT,
|
||||
enable_proxmox INTEGER NOT NULL DEFAULT 0,
|
||||
proxmox_config TEXT,
|
||||
terminal_config TEXT,
|
||||
quick_actions TEXT,
|
||||
notes TEXT,
|
||||
enable_ssh INTEGER NOT NULL DEFAULT 1,
|
||||
enable_rdp INTEGER NOT NULL DEFAULT 0,
|
||||
enable_vnc INTEGER NOT NULL DEFAULT 0,
|
||||
enable_telnet INTEGER NOT NULL DEFAULT 0,
|
||||
ssh_port INTEGER DEFAULT 22,
|
||||
rdp_port INTEGER DEFAULT 3389,
|
||||
vnc_port INTEGER DEFAULT 5900,
|
||||
telnet_port INTEGER DEFAULT 23,
|
||||
rdp_credential_id INTEGER,
|
||||
rdp_user TEXT,
|
||||
rdp_password TEXT,
|
||||
rdp_domain TEXT,
|
||||
rdp_security TEXT,
|
||||
rdp_ignore_cert INTEGER DEFAULT 0,
|
||||
vnc_credential_id INTEGER,
|
||||
vnc_password TEXT,
|
||||
vnc_user TEXT,
|
||||
telnet_user TEXT,
|
||||
telnet_password TEXT,
|
||||
telnet_credential_id INTEGER,
|
||||
rdp_auth_type TEXT,
|
||||
vnc_auth_type TEXT,
|
||||
telnet_auth_type TEXT,
|
||||
domain TEXT,
|
||||
security TEXT,
|
||||
ignore_cert INTEGER DEFAULT 0,
|
||||
guacamole_config TEXT,
|
||||
use_socks5 INTEGER,
|
||||
socks5_host TEXT,
|
||||
socks5_port INTEGER,
|
||||
socks5_username TEXT,
|
||||
socks5_password TEXT,
|
||||
socks5_proxy_chain TEXT,
|
||||
mac_address TEXT,
|
||||
wol_broadcast_address TEXT,
|
||||
port_knock_sequence TEXT,
|
||||
host_key_fingerprint TEXT,
|
||||
host_key_type TEXT,
|
||||
host_key_algorithm TEXT DEFAULT 'sha256',
|
||||
host_key_first_seen TEXT,
|
||||
host_key_last_verified TEXT,
|
||||
host_key_changed_count INTEGER DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE ssh_credentials (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
folder TEXT,
|
||||
tags TEXT,
|
||||
auth_type TEXT NOT NULL,
|
||||
username TEXT,
|
||||
password TEXT,
|
||||
key TEXT,
|
||||
private_key TEXT,
|
||||
public_key TEXT,
|
||||
key_password TEXT,
|
||||
key_type TEXT,
|
||||
detected_key_type TEXT,
|
||||
cert_public_key TEXT,
|
||||
usage_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_used TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
|
||||
INSERT INTO ssh_data (id, user_id, name, ip, port, username, auth_type)
|
||||
VALUES
|
||||
(1, 'user-1', 'web', '10.0.0.1', 22, 'root', 'password'),
|
||||
(2, 'user-2', 'db', '10.0.0.2', 22, 'root', 'password');
|
||||
|
||||
INSERT INTO ssh_credentials (id, user_id, name, auth_type, username, password)
|
||||
VALUES
|
||||
(1, 'user-1', 'prod', 'password', 'root', 'secret'),
|
||||
(2, 'user-2', 'other', 'password', 'root', 'secret');
|
||||
`);
|
||||
|
||||
return new UserDataExportRepository(context);
|
||||
}
|
||||
|
||||
it("lists only the current user's exportable hosts and credentials", async () => {
|
||||
const repository = await createRepository();
|
||||
|
||||
expect(await repository.listHostsByUserId("user-1")).toMatchObject([
|
||||
{
|
||||
id: 1,
|
||||
userId: "user-1",
|
||||
name: "web",
|
||||
ip: "10.0.0.1",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(await repository.listCredentialsByUserId("user-1")).toMatchObject([
|
||||
{
|
||||
id: 1,
|
||||
userId: "user-1",
|
||||
name: "prod",
|
||||
username: "root",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { UserPreferenceRepository } from "../../../database/repositories/user-preference-repository.js";
|
||||
|
||||
describe("UserPreferenceRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<UserPreferenceRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE user_preferences (
|
||||
user_id TEXT PRIMARY KEY,
|
||||
reopen_tabs_on_login INTEGER NOT NULL DEFAULT 0,
|
||||
theme TEXT,
|
||||
font_size TEXT,
|
||||
accent_color TEXT,
|
||||
language TEXT,
|
||||
storage_mode TEXT,
|
||||
command_autocomplete INTEGER,
|
||||
command_palette_enabled INTEGER,
|
||||
show_host_tags INTEGER,
|
||||
host_tray_on_click INTEGER,
|
||||
pin_app_rail INTEGER,
|
||||
expand_app_rail_on_hover INTEGER,
|
||||
folders_collapsed INTEGER,
|
||||
confirm_snippet_execution INTEGER,
|
||||
disable_update_check INTEGER,
|
||||
confirm_tab_close INTEGER,
|
||||
hidden_rail_tabs TEXT,
|
||||
compact_host_view INTEGER,
|
||||
status_color_scheme TEXT,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash');
|
||||
`);
|
||||
|
||||
return new UserPreferenceRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("finds, creates, and updates preferences by user id", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
expect(await repo.findByUserId("user-1")).toBeNull();
|
||||
|
||||
const created = await repo.upsert("user-1", {
|
||||
reopenTabsOnLogin: true,
|
||||
theme: "dark",
|
||||
storageMode: "local",
|
||||
commandAutocomplete: true,
|
||||
});
|
||||
expect(created).toMatchObject({
|
||||
userId: "user-1",
|
||||
reopenTabsOnLogin: true,
|
||||
theme: "dark",
|
||||
storageMode: "local",
|
||||
commandAutocomplete: true,
|
||||
});
|
||||
|
||||
const updated = await repo.upsert("user-1", {
|
||||
theme: "light",
|
||||
commandAutocomplete: false,
|
||||
updatedAt: "2026-06-27T00:00:00.000Z",
|
||||
});
|
||||
expect(updated).toMatchObject({
|
||||
userId: "user-1",
|
||||
reopenTabsOnLogin: true,
|
||||
theme: "light",
|
||||
storageMode: "local",
|
||||
commandAutocomplete: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("deletes preferences by user id only when rows exist", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsert("user-1", { theme: "dark" });
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
expect(await repo.deleteByUserId("missing")).toBe(0);
|
||||
expect(writeCount).toBe(1);
|
||||
|
||||
expect(await repo.deleteByUserId("user-1")).toBe(1);
|
||||
expect(writeCount).toBe(2);
|
||||
expect(await repo.findByUserId("user-1")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,296 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { SessionRepository } from "../../../database/repositories/session-repository.js";
|
||||
import { UserRepository } from "../../../database/repositories/user-repository.js";
|
||||
|
||||
describe("UserRepository and SessionRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepositories(): Promise<{
|
||||
users: UserRepository;
|
||||
sessions: SessionRepository;
|
||||
}>;
|
||||
async function createRepositories(options: {
|
||||
onUserWrite?: () => void | Promise<void>;
|
||||
onSessionWrite?: () => void | Promise<void>;
|
||||
}): Promise<{
|
||||
users: UserRepository;
|
||||
sessions: SessionRepository;
|
||||
}>;
|
||||
async function createRepositories(
|
||||
options: {
|
||||
onUserWrite?: () => void | Promise<void>;
|
||||
onSessionWrite?: () => void | Promise<void>;
|
||||
} = {},
|
||||
): Promise<{
|
||||
users: UserRepository;
|
||||
sessions: SessionRepository;
|
||||
}> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
is_oidc INTEGER NOT NULL DEFAULT 0,
|
||||
oidc_identifier TEXT,
|
||||
sso_provider_id INTEGER,
|
||||
client_id TEXT,
|
||||
client_secret TEXT,
|
||||
issuer_url TEXT,
|
||||
authorization_url TEXT,
|
||||
token_url TEXT,
|
||||
identifier_path TEXT,
|
||||
name_path TEXT,
|
||||
scopes TEXT DEFAULT 'openid email profile',
|
||||
totp_secret TEXT,
|
||||
totp_enabled INTEGER NOT NULL DEFAULT 0,
|
||||
totp_backup_codes TEXT,
|
||||
registered_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
donation_modal_dismissed INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
jwt_token TEXT NOT NULL,
|
||||
device_type TEXT NOT NULL,
|
||||
device_info TEXT NOT NULL,
|
||||
oidc_sub TEXT,
|
||||
oidc_sid TEXT,
|
||||
sso_provider_id INTEGER,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TEXT NOT NULL,
|
||||
last_active_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
`);
|
||||
|
||||
return {
|
||||
users: new UserRepository(context, options.onUserWrite),
|
||||
sessions: new SessionRepository(context, options.onSessionWrite),
|
||||
};
|
||||
}
|
||||
|
||||
it("creates, finds, updates, and deletes users", async () => {
|
||||
const repo = await createRepositories();
|
||||
|
||||
await repo.users.create({
|
||||
id: "user-1",
|
||||
username: "admin",
|
||||
passwordHash: "hash",
|
||||
isAdmin: true,
|
||||
isOidc: false,
|
||||
});
|
||||
|
||||
expect(await repo.users.countAdmins()).toBe(1);
|
||||
expect(await repo.users.countTotpEnabled()).toBe(0);
|
||||
expect((await repo.users.listAll()).map((user) => user.id)).toEqual([
|
||||
"user-1",
|
||||
]);
|
||||
expect((await repo.users.findByUsername("admin"))?.id).toBe("user-1");
|
||||
expect(
|
||||
(await repo.users.listByIds(["user-1", "user-1"])).map((u) => u.id),
|
||||
).toEqual(["user-1"]);
|
||||
expect(await repo.users.listByIds([])).toEqual([]);
|
||||
|
||||
const updated = await repo.users.update("user-1", {
|
||||
oidcIdentifier: "oidc:admin",
|
||||
totpEnabled: true,
|
||||
});
|
||||
expect(updated?.oidcIdentifier).toBe("oidc:admin");
|
||||
expect(await repo.users.countTotpEnabled()).toBe(1);
|
||||
expect((await repo.users.findByOidcIdentifier("oidc:admin"))?.id).toBe(
|
||||
"user-1",
|
||||
);
|
||||
|
||||
expect(await repo.users.delete("user-1")).toBe(true);
|
||||
expect(await repo.users.findById("user-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("creates the first local user as admin inside the repository", async () => {
|
||||
const repo = await createRepositories();
|
||||
|
||||
const first = await repo.users.createFirstLocalUser({
|
||||
id: "user-1",
|
||||
username: "first",
|
||||
passwordHash: "hash",
|
||||
isOidc: false,
|
||||
});
|
||||
const second = await repo.users.createFirstLocalUser({
|
||||
id: "user-2",
|
||||
username: "second",
|
||||
passwordHash: "hash",
|
||||
isOidc: false,
|
||||
});
|
||||
|
||||
expect(first.isFirstUser).toBe(true);
|
||||
expect(first.user.isAdmin).toBe(true);
|
||||
expect(second.isFirstUser).toBe(false);
|
||||
expect(second.user.isAdmin).toBe(false);
|
||||
expect(await repo.users.countAll()).toBe(2);
|
||||
});
|
||||
|
||||
it("creates SSO users with first-user and provider admin semantics", async () => {
|
||||
const repo = await createRepositories();
|
||||
|
||||
const first = await repo.users.createFirstSsoUser({
|
||||
id: "user-1",
|
||||
username: "first",
|
||||
passwordHash: "",
|
||||
isAdmin: false,
|
||||
isOidc: true,
|
||||
oidcIdentifier: "ldap:provider:first",
|
||||
ssoProviderId: 1,
|
||||
});
|
||||
const providerAdmin = await repo.users.createFirstSsoUser({
|
||||
id: "user-2",
|
||||
username: "provider-admin",
|
||||
passwordHash: "",
|
||||
isAdmin: true,
|
||||
isOidc: true,
|
||||
oidcIdentifier: "ldap:provider:admin",
|
||||
ssoProviderId: 1,
|
||||
});
|
||||
const regular = await repo.users.createFirstSsoUser({
|
||||
id: "user-3",
|
||||
username: "regular",
|
||||
passwordHash: "",
|
||||
isAdmin: false,
|
||||
isOidc: true,
|
||||
oidcIdentifier: "ldap:provider:regular",
|
||||
ssoProviderId: 1,
|
||||
});
|
||||
|
||||
expect(first.isFirstUser).toBe(true);
|
||||
expect(first.user.isAdmin).toBe(true);
|
||||
expect(providerAdmin.isFirstUser).toBe(false);
|
||||
expect(providerAdmin.user.isAdmin).toBe(true);
|
||||
expect(regular.isFirstUser).toBe(false);
|
||||
expect(regular.user.isAdmin).toBe(false);
|
||||
expect(await repo.users.countAll()).toBe(3);
|
||||
});
|
||||
|
||||
it("runs the user write hook after user writes", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepositories({
|
||||
onUserWrite: () => {
|
||||
writeCount += 1;
|
||||
},
|
||||
});
|
||||
|
||||
await repo.users.create({
|
||||
id: "user-1",
|
||||
username: "admin",
|
||||
passwordHash: "hash",
|
||||
isAdmin: true,
|
||||
isOidc: false,
|
||||
});
|
||||
await repo.users.update("user-1", { isAdmin: false });
|
||||
await repo.users.delete("user-1");
|
||||
|
||||
expect(writeCount).toBe(3);
|
||||
});
|
||||
|
||||
it("creates, touches, lists, and revokes sessions", async () => {
|
||||
const repo = await createRepositories();
|
||||
await repo.users.create({
|
||||
id: "user-1",
|
||||
username: "user",
|
||||
passwordHash: "hash",
|
||||
isAdmin: false,
|
||||
isOidc: false,
|
||||
});
|
||||
|
||||
await repo.sessions.create({
|
||||
id: "session-1",
|
||||
userId: "user-1",
|
||||
jwtToken: "token",
|
||||
deviceType: "desktop",
|
||||
deviceInfo: "Firefox",
|
||||
createdAt: "2026-06-26T00:00:00.000Z",
|
||||
expiresAt: "2026-06-27T00:00:00.000Z",
|
||||
lastActiveAt: "2026-06-26T00:00:00.000Z",
|
||||
});
|
||||
|
||||
await repo.sessions.touch("session-1", "2026-06-26T01:00:00.000Z");
|
||||
|
||||
expect((await repo.sessions.findById("session-1"))?.lastActiveAt).toBe(
|
||||
"2026-06-26T01:00:00.000Z",
|
||||
);
|
||||
expect(await repo.sessions.listByUserId("user-1")).toHaveLength(1);
|
||||
expect(await repo.sessions.revoke("session-1")).toBe(true);
|
||||
expect(await repo.sessions.findById("session-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("revokes all user sessions except an optional current session", async () => {
|
||||
const repo = await createRepositories();
|
||||
await repo.users.create({
|
||||
id: "user-1",
|
||||
username: "user",
|
||||
passwordHash: "hash",
|
||||
isAdmin: false,
|
||||
isOidc: false,
|
||||
});
|
||||
|
||||
for (const id of ["keep", "drop-1", "drop-2"]) {
|
||||
await repo.sessions.create({
|
||||
id,
|
||||
userId: "user-1",
|
||||
jwtToken: `${id}-token`,
|
||||
deviceType: "desktop",
|
||||
deviceInfo: "Firefox",
|
||||
expiresAt: "2026-06-27T00:00:00.000Z",
|
||||
});
|
||||
}
|
||||
|
||||
expect(await repo.sessions.revokeAllForUser("user-1", "keep")).toBe(2);
|
||||
expect(
|
||||
(await repo.sessions.listByUserId("user-1")).map((s) => s.id),
|
||||
).toEqual(["keep"]);
|
||||
});
|
||||
|
||||
it("deletes expired sessions", async () => {
|
||||
const repo = await createRepositories();
|
||||
await repo.users.create({
|
||||
id: "user-1",
|
||||
username: "user",
|
||||
passwordHash: "hash",
|
||||
isAdmin: false,
|
||||
isOidc: false,
|
||||
});
|
||||
|
||||
await repo.sessions.create({
|
||||
id: "expired",
|
||||
userId: "user-1",
|
||||
jwtToken: "expired-token",
|
||||
deviceType: "desktop",
|
||||
deviceInfo: "Firefox",
|
||||
expiresAt: "2026-06-25T00:00:00.000Z",
|
||||
});
|
||||
await repo.sessions.create({
|
||||
id: "active",
|
||||
userId: "user-1",
|
||||
jwtToken: "active-token",
|
||||
deviceType: "desktop",
|
||||
deviceInfo: "Firefox",
|
||||
expiresAt: "2026-06-27T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(
|
||||
await repo.sessions.deleteExpired(new Date("2026-06-26T00:00:00.000Z")),
|
||||
).toBe(1);
|
||||
expect(
|
||||
(await repo.sessions.listByUserId("user-1")).map((s) => s.id),
|
||||
).toEqual(["active"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { VaultProfileRepository } from "../../../database/repositories/vault-profile-repository.js";
|
||||
|
||||
describe("VaultProfileRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<VaultProfileRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE vault_profiles (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
folder TEXT,
|
||||
tags TEXT,
|
||||
vault_addr TEXT NOT NULL,
|
||||
vault_namespace TEXT,
|
||||
oidc_mount TEXT,
|
||||
oidc_role TEXT,
|
||||
ssh_mount TEXT,
|
||||
ssh_role TEXT NOT NULL,
|
||||
valid_principals TEXT,
|
||||
key_type TEXT,
|
||||
shared INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO vault_profiles (
|
||||
id, user_id, name, vault_addr, ssh_role, shared, updated_at
|
||||
)
|
||||
VALUES
|
||||
(1, 'user-1', 'owned', 'https://vault.one', 'role-one', 0, '2026-01-01T00:00:00.000Z'),
|
||||
(2, 'user-2', 'shared', 'https://vault.two', 'role-two', 1, '2026-01-02T00:00:00.000Z'),
|
||||
(3, 'user-2', 'hidden', 'https://vault.three', 'role-three', 0, '2026-01-03T00:00:00.000Z');
|
||||
`);
|
||||
|
||||
return new VaultProfileRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("lists profiles owned by or shared with the user", async () => {
|
||||
const repo = await createRepository();
|
||||
|
||||
const rows = await repo.listVisibleToUser("user-1");
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
it("creates and reads a profile", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const created = await repo.create({
|
||||
userId: "user-1",
|
||||
name: "new",
|
||||
description: "desc",
|
||||
folder: "folder",
|
||||
tags: "prod,ssh",
|
||||
vaultAddr: "https://vault.new",
|
||||
vaultNamespace: "ns",
|
||||
oidcMount: "oidc",
|
||||
oidcRole: "oidc-role",
|
||||
sshMount: "ssh",
|
||||
sshRole: "ssh-role",
|
||||
validPrincipals: "root",
|
||||
keyType: "ed25519",
|
||||
shared: true,
|
||||
});
|
||||
|
||||
const found = await repo.findById(created.id);
|
||||
expect(found).toMatchObject({
|
||||
userId: "user-1",
|
||||
name: "new",
|
||||
vaultAddr: "https://vault.new",
|
||||
sshRole: "ssh-role",
|
||||
shared: true,
|
||||
});
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("updates and deletes profiles", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const updated = await repo.updateById(1, {
|
||||
name: "renamed",
|
||||
shared: true,
|
||||
updatedAt: "2026-02-01T00:00:00.000Z",
|
||||
});
|
||||
expect(updated).toMatchObject({
|
||||
id: 1,
|
||||
name: "renamed",
|
||||
shared: true,
|
||||
updatedAt: "2026-02-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(await repo.updateById(999, { name: "missing" })).toBeNull();
|
||||
expect(await repo.deleteById(1)).toBe(true);
|
||||
expect(await repo.deleteById(1)).toBe(false);
|
||||
expect(await repo.findById(1)).toBeNull();
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("deletes all profiles for a user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await expect(repo.deleteByUserId("user-2")).resolves.toBe(2);
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
|
||||
|
||||
expect(await repo.findById(2)).toBeNull();
|
||||
expect(await repo.findById(3)).toBeNull();
|
||||
expect((await repo.findById(1))?.userId).toBe("user-1");
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { TestSqliteDatabase } from "./test-support.js";
|
||||
import { VaultTokenRepository } from "../../../database/repositories/vault-token-repository.js";
|
||||
|
||||
describe("VaultTokenRepository", () => {
|
||||
let adapter: TestSqliteDatabase | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
if (adapter) {
|
||||
await adapter.close();
|
||||
adapter = null;
|
||||
}
|
||||
});
|
||||
|
||||
async function createRepository(
|
||||
onWrite?: () => void | Promise<void>,
|
||||
): Promise<VaultTokenRepository> {
|
||||
adapter = new TestSqliteDatabase();
|
||||
const context = await adapter.connect();
|
||||
context.sqlite?.exec(`
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE vault_profiles (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE vault_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
profile_id INTEGER NOT NULL,
|
||||
ssh_cert TEXT NOT NULL,
|
||||
private_key TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TEXT NOT NULL,
|
||||
last_used TEXT,
|
||||
UNIQUE(user_id, profile_id)
|
||||
);
|
||||
|
||||
INSERT INTO users (id, username, password_hash)
|
||||
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
|
||||
INSERT INTO vault_profiles (id, user_id, name)
|
||||
VALUES (1, 'user-1', 'one'), (2, 'user-2', 'two');
|
||||
INSERT INTO vault_tokens (
|
||||
user_id, profile_id, ssh_cert, private_key, expires_at
|
||||
)
|
||||
VALUES
|
||||
('user-1', 1, 'cert-1', 'key-1', '2099-01-01T00:00:00.000Z'),
|
||||
('user-2', 2, 'cert-2', 'key-2', '2099-01-01T00:00:00.000Z');
|
||||
`);
|
||||
|
||||
return new VaultTokenRepository(context, onWrite);
|
||||
}
|
||||
|
||||
it("finds and upserts a token by user and profile", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
const existing = await repo.findByUserAndProfile("user-1", 1);
|
||||
expect(existing?.sshCert).toBe("cert-1");
|
||||
|
||||
await repo.upsert({
|
||||
userId: "user-1",
|
||||
profileId: 1,
|
||||
sshCert: "new-cert",
|
||||
privateKey: "new-key",
|
||||
expiresAt: "2099-02-01T00:00:00.000Z",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const updated = await repo.findByUserAndProfile("user-1", 1);
|
||||
expect(updated).toMatchObject({
|
||||
sshCert: "new-cert",
|
||||
privateKey: "new-key",
|
||||
expiresAt: "2099-02-01T00:00:00.000Z",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
expect(writeCount).toBe(1);
|
||||
});
|
||||
|
||||
it("updates last-used and deletes one token", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
expect(
|
||||
await repo.updateLastUsed("user-1", 1, "2026-01-02T00:00:00.000Z"),
|
||||
).toBe(true);
|
||||
expect(await repo.updateLastUsed("missing", 1)).toBe(false);
|
||||
expect((await repo.findByUserAndProfile("user-1", 1))?.lastUsed).toBe(
|
||||
"2026-01-02T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(await repo.deleteByUserAndProfile("user-1", 1)).toBe(true);
|
||||
expect(await repo.deleteByUserAndProfile("user-1", 1)).toBe(false);
|
||||
expect(await repo.findByUserAndProfile("user-1", 1)).toBeNull();
|
||||
expect(await repo.findByUserAndProfile("user-2", 2)).not.toBeNull();
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
|
||||
it("deletes all tokens for a user", async () => {
|
||||
let writeCount = 0;
|
||||
const repo = await createRepository(() => {
|
||||
writeCount += 1;
|
||||
});
|
||||
|
||||
await repo.upsert({
|
||||
userId: "user-1",
|
||||
profileId: 2,
|
||||
sshCert: "cert-extra",
|
||||
privateKey: "key-extra",
|
||||
expiresAt: "2099-03-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
await expect(repo.deleteByUserId("user-1")).resolves.toBe(2);
|
||||
await expect(repo.deleteByUserId("missing")).resolves.toBe(0);
|
||||
|
||||
expect(await repo.findByUserAndProfile("user-1", 1)).toBeNull();
|
||||
expect(await repo.findByUserAndProfile("user-1", 2)).toBeNull();
|
||||
expect(await repo.findByUserAndProfile("user-2", 2)).not.toBeNull();
|
||||
expect(writeCount).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { shouldShowDonationModal } from "../../../database/routes/donation-modal-utils.js";
|
||||
|
||||
describe("shouldShowDonationModal", () => {
|
||||
const now = Date.parse("2026-07-17T00:00:00.000Z");
|
||||
|
||||
it("returns false when the user already dismissed it", () => {
|
||||
const registeredAt = new Date(now - 60 * 24 * 60 * 60 * 1000).toISOString();
|
||||
expect(shouldShowDonationModal(registeredAt, true, now)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false before the 30 day mark", () => {
|
||||
const registeredAt = new Date(now - 29 * 24 * 60 * 60 * 1000).toISOString();
|
||||
expect(shouldShowDonationModal(registeredAt, false, now)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true at exactly 30 days", () => {
|
||||
const registeredAt = new Date(now - 30 * 24 * 60 * 60 * 1000).toISOString();
|
||||
expect(shouldShowDonationModal(registeredAt, false, now)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true well past the 30 day mark", () => {
|
||||
const registeredAt = new Date(
|
||||
now - 200 * 24 * 60 * 60 * 1000,
|
||||
).toISOString();
|
||||
expect(shouldShowDonationModal(registeredAt, false, now)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false for an unparseable registeredAt", () => {
|
||||
expect(shouldShowDonationModal("not-a-date", false, now)).toBe(false);
|
||||
});
|
||||
|
||||
it("treats a backdated registeredAt for pre-existing users as immediately eligible", () => {
|
||||
const registeredAt = new Date(now - 31 * 24 * 60 * 60 * 1000).toISOString();
|
||||
expect(shouldShowDonationModal(registeredAt, false, now)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { parseSSHConfig } from "../../../database/routes/host-bulk-routes.js";
|
||||
|
||||
describe("parseSSHConfig", () => {
|
||||
it("parses a basic Host block", () => {
|
||||
const config = `
|
||||
Host myserver
|
||||
HostName 192.168.1.10
|
||||
User alice
|
||||
Port 2222
|
||||
`;
|
||||
const result = parseSSHConfig(config);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
name: "myserver",
|
||||
hostname: "192.168.1.10",
|
||||
user: "alice",
|
||||
port: 2222,
|
||||
});
|
||||
});
|
||||
|
||||
it("parses multiple Host blocks", () => {
|
||||
const config = `
|
||||
Host web
|
||||
HostName web.example.com
|
||||
User deploy
|
||||
|
||||
Host db
|
||||
HostName db.example.com
|
||||
User postgres
|
||||
Port 5432
|
||||
`;
|
||||
const result = parseSSHConfig(config);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0].name).toBe("web");
|
||||
expect(result[1].name).toBe("db");
|
||||
expect(result[1].port).toBe(5432);
|
||||
});
|
||||
|
||||
it("ignores comment lines", () => {
|
||||
const config = `
|
||||
# This is a comment
|
||||
Host server
|
||||
# Another comment
|
||||
HostName 10.0.0.1
|
||||
User root
|
||||
`;
|
||||
const result = parseSSHConfig(config);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].hostname).toBe("10.0.0.1");
|
||||
});
|
||||
|
||||
it("skips wildcard Host entries", () => {
|
||||
const config = `
|
||||
Host *
|
||||
ServerAliveInterval 60
|
||||
|
||||
Host prod
|
||||
HostName prod.example.com
|
||||
User ubuntu
|
||||
`;
|
||||
const result = parseSSHConfig(config);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe("prod");
|
||||
});
|
||||
|
||||
it("captures IdentityFile and ProxyJump", () => {
|
||||
const config = `
|
||||
Host bastion
|
||||
HostName bastion.example.com
|
||||
User ec2-user
|
||||
IdentityFile ~/.ssh/id_rsa
|
||||
ProxyJump jumphost.example.com
|
||||
`;
|
||||
const result = parseSSHConfig(config);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].identityFile).toBe("~/.ssh/id_rsa");
|
||||
expect(result[0].proxyJump).toBe("jumphost.example.com");
|
||||
});
|
||||
|
||||
it("skips Host blocks without a HostName", () => {
|
||||
const config = `
|
||||
Host alias-only
|
||||
User foo
|
||||
`;
|
||||
const result = parseSSHConfig(config);
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("defaults port to undefined when not specified", () => {
|
||||
const config = `
|
||||
Host server
|
||||
HostName 1.2.3.4
|
||||
User root
|
||||
`;
|
||||
const result = parseSSHConfig(config);
|
||||
expect(result[0].port).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns empty array for empty input", () => {
|
||||
expect(parseSSHConfig("")).toHaveLength(0);
|
||||
expect(parseSSHConfig(" \n\n ")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
isUserDataUnlocked: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/data-crypto.js", () => ({
|
||||
DataCrypto: {
|
||||
canUserAccessData: mocks.isUserDataUnlocked,
|
||||
},
|
||||
}));
|
||||
|
||||
const { applyHostEnrollmentDefaults, requireHostEnrollmentAccessForPath } =
|
||||
await import("../../../database/routes/host-enrollment-auth.js");
|
||||
|
||||
function response() {
|
||||
const json = vi.fn();
|
||||
const status = vi.fn(() => ({ json }));
|
||||
return { status, json };
|
||||
}
|
||||
|
||||
describe("requireHostEnrollmentAccessForPath", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.isUserDataUnlocked.mockReturnValue(true);
|
||||
});
|
||||
|
||||
it("accepts an API key scoped to an unlocked user", () => {
|
||||
const res = response();
|
||||
const next = vi.fn();
|
||||
|
||||
requireHostEnrollmentAccessForPath(
|
||||
{ path: "/enroll", userId: "user-1", apiKeyId: "key-1" } as never,
|
||||
res as never,
|
||||
next,
|
||||
);
|
||||
|
||||
expect(mocks.isUserDataUnlocked).toHaveBeenCalledWith("user-1");
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("rejects regular JWT sessions", () => {
|
||||
const res = response();
|
||||
const next = vi.fn();
|
||||
|
||||
requireHostEnrollmentAccessForPath(
|
||||
{ path: "/enroll", userId: "user-1" } as never,
|
||||
res as never,
|
||||
next,
|
||||
);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(401);
|
||||
expect(res.json).toHaveBeenCalledWith({
|
||||
error: "Host enrollment requires an API key",
|
||||
code: "API_KEY_REQUIRED",
|
||||
});
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports locked encrypted data explicitly", () => {
|
||||
mocks.isUserDataUnlocked.mockReturnValue(false);
|
||||
const res = response();
|
||||
const next = vi.fn();
|
||||
|
||||
requireHostEnrollmentAccessForPath(
|
||||
{ path: "/enroll", userId: "user-1", apiKeyId: "key-1" } as never,
|
||||
res as never,
|
||||
next,
|
||||
);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(423);
|
||||
expect(res.json).toHaveBeenCalledWith({
|
||||
error: "User data is locked. Sign in before enrolling hosts.",
|
||||
code: "DATA_LOCKED",
|
||||
});
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves the existing host route unchanged", () => {
|
||||
const res = response();
|
||||
const next = vi.fn();
|
||||
|
||||
requireHostEnrollmentAccessForPath(
|
||||
{ path: "/db/host", userId: "user-1" } as never,
|
||||
res as never,
|
||||
next,
|
||||
);
|
||||
|
||||
expect(next).toHaveBeenCalledOnce();
|
||||
expect(mocks.isUserDataUnlocked).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyHostEnrollmentDefaults", () => {
|
||||
it("creates a usable SSH host from a minimal enrollment payload", () => {
|
||||
expect(applyHostEnrollmentDefaults({ ip: "server.example" })).toEqual({
|
||||
connectionType: "ssh",
|
||||
ip: "server.example",
|
||||
port: 22,
|
||||
authType: "none",
|
||||
enableTerminal: true,
|
||||
enableSsh: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves explicit enrollment settings", () => {
|
||||
expect(
|
||||
applyHostEnrollmentDefaults({
|
||||
ip: "server.example",
|
||||
port: 2222,
|
||||
authType: "password",
|
||||
enableTerminal: false,
|
||||
}),
|
||||
).toMatchObject({
|
||||
port: 2222,
|
||||
authType: "password",
|
||||
enableTerminal: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
isNonEmptyString,
|
||||
isValidPort,
|
||||
normalizeImportedHost,
|
||||
renameFolderPath,
|
||||
sanitizeHostForRecipient,
|
||||
stripSensitiveFields,
|
||||
transformHostResponse,
|
||||
} from "../../../database/routes/host-normalizers.js";
|
||||
|
||||
describe("isNonEmptyString", () => {
|
||||
it("accepts non-blank strings", () => {
|
||||
expect(isNonEmptyString("hello")).toBe(true);
|
||||
expect(isNonEmptyString(" x ")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects blank strings and non-strings", () => {
|
||||
expect(isNonEmptyString("")).toBe(false);
|
||||
expect(isNonEmptyString(" ")).toBe(false);
|
||||
expect(isNonEmptyString(123)).toBe(false);
|
||||
expect(isNonEmptyString(null)).toBe(false);
|
||||
expect(isNonEmptyString(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("renameFolderPath", () => {
|
||||
it("renames an exact folder match", () => {
|
||||
expect(renameFolderPath("Production", "Production", "Prod")).toBe("Prod");
|
||||
});
|
||||
|
||||
it("re-paths nested children under the renamed ancestor", () => {
|
||||
expect(renameFolderPath("Production / Web", "Production", "Prod")).toBe(
|
||||
"Prod / Web",
|
||||
);
|
||||
expect(
|
||||
renameFolderPath("Production / Web / app01", "Production", "Prod"),
|
||||
).toBe("Prod / Web / app01");
|
||||
});
|
||||
|
||||
it("renames a nested folder itself and keeps its parent", () => {
|
||||
expect(
|
||||
renameFolderPath("Production / Web", "Production / Web", "Frontend"),
|
||||
).toBe("Frontend");
|
||||
expect(
|
||||
renameFolderPath(
|
||||
"Production / Web / app01",
|
||||
"Production / Web",
|
||||
"Production / Frontend",
|
||||
),
|
||||
).toBe("Production / Frontend / app01");
|
||||
});
|
||||
|
||||
it("returns null for unrelated folders", () => {
|
||||
expect(renameFolderPath("Staging", "Production", "Prod")).toBeNull();
|
||||
expect(renameFolderPath("Production2", "Production", "Prod")).toBeNull();
|
||||
expect(
|
||||
renameFolderPath("ProductionExtra / Web", "Production", "Prod"),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("isValidPort", () => {
|
||||
it("accepts ports in range", () => {
|
||||
expect(isValidPort(1)).toBe(true);
|
||||
expect(isValidPort(22)).toBe(true);
|
||||
expect(isValidPort(65535)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects out-of-range or non-number ports", () => {
|
||||
expect(isValidPort(0)).toBe(false);
|
||||
expect(isValidPort(65536)).toBe(false);
|
||||
expect(isValidPort(-1)).toBe(false);
|
||||
expect(isValidPort("22")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeImportedHost", () => {
|
||||
it("defaults connectionType to ssh with port 22", () => {
|
||||
const host = normalizeImportedHost({ ip: "10.0.0.1" });
|
||||
expect(host.connectionType).toBe("ssh");
|
||||
expect(host.port).toBe(22);
|
||||
expect(host.enableSsh).toBe(true);
|
||||
expect(host.enableRdp).toBe(false);
|
||||
});
|
||||
|
||||
it("infers rdp from enableRdp and uses default rdp port", () => {
|
||||
const host = normalizeImportedHost({ enableRdp: true, ip: "10.0.0.2" });
|
||||
expect(host.connectionType).toBe("rdp");
|
||||
expect(host.port).toBe(3389);
|
||||
expect(host.enableRdp).toBe(true);
|
||||
});
|
||||
|
||||
it("honors an explicit port over protocol defaults", () => {
|
||||
const host = normalizeImportedHost({
|
||||
connectionType: "ssh",
|
||||
port: 2222,
|
||||
});
|
||||
expect(host.port).toBe(2222);
|
||||
});
|
||||
|
||||
it("resolves ip from common aliases", () => {
|
||||
expect(normalizeImportedHost({ address: "a.example" }).ip).toBe(
|
||||
"a.example",
|
||||
);
|
||||
expect(normalizeImportedHost({ hostname: "h.example" }).ip).toBe(
|
||||
"h.example",
|
||||
);
|
||||
});
|
||||
|
||||
it("normalizes tags from a comma string", () => {
|
||||
const host = normalizeImportedHost({ tags: "prod, db , , web" });
|
||||
expect(host.tags).toEqual(["prod", "db", "web"]);
|
||||
});
|
||||
|
||||
it("normalizes tags from an array", () => {
|
||||
const host = normalizeImportedHost({ tags: ["a", " b ", "", "c"] });
|
||||
expect(host.tags).toEqual(["a", "b", "c"]);
|
||||
});
|
||||
|
||||
it("infers authType credential when credentialId present", () => {
|
||||
const host = normalizeImportedHost({ credentialId: 7 });
|
||||
expect(host.credentialId).toBe(7);
|
||||
expect(host.authType).toBe("credential");
|
||||
});
|
||||
|
||||
it("infers credential auth from share aliases", () => {
|
||||
const aliasHost = normalizeImportedHost({ credentialAlias: "prod-admin" });
|
||||
expect(aliasHost.credentialAlias).toBe("prod-admin");
|
||||
expect(aliasHost.authType).toBe("credential");
|
||||
|
||||
const nameHost = normalizeImportedHost({ credentialName: "ops-key" });
|
||||
expect(nameHost.credentialAlias).toBe("ops-key");
|
||||
expect(nameHost.authType).toBe("credential");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stripSensitiveFields", () => {
|
||||
it("removes secret fields and adds boolean presence flags", () => {
|
||||
const result = stripSensitiveFields({
|
||||
name: "web",
|
||||
password: "secret",
|
||||
key: "PRIVATE KEY",
|
||||
keyPassword: "kp",
|
||||
sudoPassword: "sp",
|
||||
});
|
||||
expect(result.password).toBeUndefined();
|
||||
expect(result.key).toBeUndefined();
|
||||
expect(result.keyPassword).toBeUndefined();
|
||||
expect(result.sudoPassword).toBeUndefined();
|
||||
expect(result.hasPassword).toBe(true);
|
||||
expect(result.hasKey).toBe(true);
|
||||
expect(result.hasKeyPassword).toBe(true);
|
||||
expect(result.hasSudoPassword).toBe(true);
|
||||
expect(result.name).toBe("web");
|
||||
});
|
||||
|
||||
it("marks presence flags false when secrets are absent", () => {
|
||||
const result = stripSensitiveFields({ name: "web" });
|
||||
expect(result.hasPassword).toBe(false);
|
||||
expect(result.hasKey).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("transformHostResponse", () => {
|
||||
it("parses tags and coerces enable flags to booleans", () => {
|
||||
const result = transformHostResponse({
|
||||
tags: "a,b,c",
|
||||
enableTerminal: 1,
|
||||
enableTunnel: 0,
|
||||
pin: 1,
|
||||
});
|
||||
expect(result.tags).toEqual(["a", "b", "c"]);
|
||||
expect(result.enableTerminal).toBe(true);
|
||||
expect(result.enableTunnel).toBe(false);
|
||||
expect(result.pin).toBe(true);
|
||||
});
|
||||
|
||||
it("parses JSON array fields and defaults them to []", () => {
|
||||
const result = transformHostResponse({
|
||||
tunnelConnections: '[{"sourcePort":8080}]',
|
||||
jumpHosts: null,
|
||||
});
|
||||
expect(result.tunnelConnections).toEqual([{ sourcePort: 8080 }]);
|
||||
expect(result.jumpHosts).toEqual([]);
|
||||
});
|
||||
|
||||
it("infers protocol flags for a migrated non-ssh host", () => {
|
||||
const result = transformHostResponse({
|
||||
connectionType: "rdp",
|
||||
enableSsh: true,
|
||||
});
|
||||
expect(result.enableSsh).toBe(false);
|
||||
expect(result.enableRdp).toBe(true);
|
||||
});
|
||||
|
||||
it("applies default protocol ports", () => {
|
||||
const result = transformHostResponse({ port: 22 });
|
||||
expect(result.sshPort).toBe(22);
|
||||
expect(result.rdpPort).toBe(3389);
|
||||
expect(result.vncPort).toBe(5900);
|
||||
expect(result.telnetPort).toBe(23);
|
||||
});
|
||||
|
||||
it("coerces enableProxmox and parses proxmoxConfig", () => {
|
||||
const result = transformHostResponse({
|
||||
enableProxmox: 1,
|
||||
proxmoxConfig: '{"defaultCredentialId":3,"windowsPatterns":"win"}',
|
||||
});
|
||||
expect(result.enableProxmox).toBe(true);
|
||||
expect(result.proxmoxConfig).toEqual({
|
||||
defaultCredentialId: 3,
|
||||
windowsPatterns: "win",
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults enableProxmox to false when absent", () => {
|
||||
const result = transformHostResponse({ port: 22 });
|
||||
expect(result.enableProxmox).toBe(false);
|
||||
expect(result.proxmoxConfig).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("sanitizeHostForRecipient", () => {
|
||||
const sharedHost = {
|
||||
id: 42,
|
||||
userId: "owner",
|
||||
ownerUsername: "owner",
|
||||
isShared: true,
|
||||
permissionLevel: "view",
|
||||
name: "prod",
|
||||
ip: "10.0.0.42",
|
||||
port: 22,
|
||||
username: "root",
|
||||
folder: "servers",
|
||||
tags: ["linux"],
|
||||
notes: "secret runbook",
|
||||
quickActions: [{ name: "restart", snippetId: "1" }],
|
||||
password: "hunter2",
|
||||
key: "PRIVATE",
|
||||
sudoPassword: "sudo",
|
||||
rdpPassword: "rdp",
|
||||
socks5Password: "socks",
|
||||
enableSsh: true,
|
||||
enableRdp: true,
|
||||
sshPort: 22,
|
||||
rdpPort: 3389,
|
||||
defaultPath: "/srv",
|
||||
};
|
||||
|
||||
it("always strips secrets for recipients", () => {
|
||||
const result = sanitizeHostForRecipient({ ...sharedHost }, "view");
|
||||
expect(result.password).toBeUndefined();
|
||||
expect(result.key).toBeUndefined();
|
||||
expect(result.sudoPassword).toBeUndefined();
|
||||
expect(result.rdpPassword).toBeUndefined();
|
||||
expect(result.socks5Password).toBeUndefined();
|
||||
// view keeps configuration fields
|
||||
expect(result.notes).toBe("secret runbook");
|
||||
expect(result.quickActions).toEqual(sharedHost.quickActions);
|
||||
});
|
||||
|
||||
it("reduces connect-level hosts to connection essentials", () => {
|
||||
const result = sanitizeHostForRecipient(
|
||||
{ ...sharedHost, permissionLevel: "connect" },
|
||||
"connect",
|
||||
);
|
||||
expect(result.name).toBe("prod");
|
||||
expect(result.ip).toBe("10.0.0.42");
|
||||
expect(result.enableRdp).toBe(true);
|
||||
expect(result.rdpPort).toBe(3389);
|
||||
expect(result.permissionLevel).toBe("connect");
|
||||
expect(result.notes).toBeUndefined();
|
||||
expect(result.quickActions).toBeUndefined();
|
||||
expect(result.password).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
isValidServiceLinkUrl,
|
||||
normalizeServiceLinkUrl,
|
||||
} from "../../../database/routes/service-link-url.js";
|
||||
|
||||
describe("service link URL handling", () => {
|
||||
it("keeps explicit http and https URLs", () => {
|
||||
expect(normalizeServiceLinkUrl("https://example.com")).toBe(
|
||||
"https://example.com",
|
||||
);
|
||||
expect(normalizeServiceLinkUrl("http://192.168.1.10:8080")).toBe(
|
||||
"http://192.168.1.10:8080",
|
||||
);
|
||||
});
|
||||
|
||||
it("adds http to bare service addresses", () => {
|
||||
expect(normalizeServiceLinkUrl("192.168.1.10:8080")).toBe(
|
||||
"http://192.168.1.10:8080",
|
||||
);
|
||||
expect(normalizeServiceLinkUrl("termix.local")).toBe("http://termix.local");
|
||||
});
|
||||
|
||||
it("rejects unsupported schemes", () => {
|
||||
expect(isValidServiceLinkUrl("ssh://example.com")).toBe(false);
|
||||
expect(isValidServiceLinkUrl("javascript:alert(1)")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import path from "path";
|
||||
|
||||
// Stub db, logger, fs, and AuthManager before importing the route module
|
||||
const mockSelect = vi.fn();
|
||||
const mockDelete = vi.fn();
|
||||
const mockInsert = vi.fn();
|
||||
|
||||
vi.mock("../../../database/db/index.js", () => ({
|
||||
db: {
|
||||
select: mockSelect,
|
||||
delete: mockDelete,
|
||||
insert: mockInsert,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
apiLogger: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), success: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/auth-manager.js", () => ({
|
||||
AuthManager: {
|
||||
getInstance: () => ({
|
||||
createAuthMiddleware:
|
||||
() => (_req: unknown, _res: unknown, next: () => void) =>
|
||||
next(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
const mockReadFile = vi.fn();
|
||||
const mockStat = vi.fn();
|
||||
const mockUnlink = vi.fn();
|
||||
const mockExistsSync = vi.fn();
|
||||
|
||||
vi.mock("fs", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("fs")>();
|
||||
return {
|
||||
...actual,
|
||||
promises: { readFile: mockReadFile, unlink: mockUnlink },
|
||||
existsSync: mockExistsSync,
|
||||
statSync: mockStat,
|
||||
};
|
||||
});
|
||||
|
||||
// Build a chainable drizzle-like query stub
|
||||
function makeChain(resolveValue: unknown) {
|
||||
const chain: Record<string, unknown> = {};
|
||||
const methods = [
|
||||
"from",
|
||||
"leftJoin",
|
||||
"where",
|
||||
"orderBy",
|
||||
"limit",
|
||||
"set",
|
||||
"values",
|
||||
];
|
||||
for (const m of methods) {
|
||||
chain[m] = vi.fn(() => chain);
|
||||
}
|
||||
(chain as unknown as Promise<unknown>).then = (cb: (v: unknown) => unknown) =>
|
||||
Promise.resolve(resolveValue).then(cb);
|
||||
(chain as unknown as Promise<unknown>).catch = (
|
||||
cb: (e: unknown) => unknown,
|
||||
) => Promise.resolve(resolveValue).catch(cb);
|
||||
return chain;
|
||||
}
|
||||
|
||||
describe("session-log-routes", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
process.env.DATA_DIR = "/data";
|
||||
});
|
||||
|
||||
describe("GET / - list logs", () => {
|
||||
it("returns logs for the authenticated user with file size", async () => {
|
||||
const rows = [
|
||||
{
|
||||
id: 1,
|
||||
hostId: 10,
|
||||
userId: "u1",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
endedAt: "2026-01-01T00:05:00Z",
|
||||
duration: 300,
|
||||
recordingPath: "/data/session_logs/u1/abc.log",
|
||||
hostName: "my-server",
|
||||
hostIp: "10.0.0.1",
|
||||
},
|
||||
];
|
||||
const chain = makeChain(rows);
|
||||
mockSelect.mockReturnValue(chain);
|
||||
mockStat.mockReturnValue({ size: 4096 });
|
||||
|
||||
// Directly call the route handler extracted from the module
|
||||
const { default: router } =
|
||||
await import("../../../database/routes/session-log-routes.js");
|
||||
expect(router).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("path traversal guard", () => {
|
||||
it("rejects paths outside the allowed session_logs directory", () => {
|
||||
const allowedBase = path.resolve("/data", "session_logs");
|
||||
const malicious = path.resolve("/data/session_logs/../../etc/passwd");
|
||||
expect(malicious.startsWith(allowedBase)).toBe(false);
|
||||
});
|
||||
|
||||
it("allows a legitimate session log path", () => {
|
||||
const allowedBase = path.resolve("/data", "session_logs");
|
||||
const valid = path.resolve("/data/session_logs/user1/abc.log");
|
||||
expect(valid.startsWith(allowedBase)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatters (pure logic)", () => {
|
||||
it("stat returns size when file exists", () => {
|
||||
mockExistsSync.mockReturnValue(true);
|
||||
mockStat.mockReturnValue({ size: 1234 });
|
||||
const exists = mockExistsSync("/some/file.log");
|
||||
const { size } = mockStat("/some/file.log");
|
||||
expect(exists).toBe(true);
|
||||
expect(size).toBe(1234);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import crypto from "crypto";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { execFileSync } from "child_process";
|
||||
import {
|
||||
generateCa,
|
||||
signUserCertificate,
|
||||
ed25519RawFromLine,
|
||||
} from "../../../database/routes/ssh-certificate.js";
|
||||
|
||||
function publicKeyObjectFromLine(line: string) {
|
||||
const raw = ed25519RawFromLine(line);
|
||||
if (!raw) throw new Error("not ed25519");
|
||||
return crypto.createPublicKey({
|
||||
key: { kty: "OKP", crv: "Ed25519", x: raw.toString("base64url") },
|
||||
format: "jwk",
|
||||
});
|
||||
}
|
||||
|
||||
// Split a cert blob into the signed body and the raw 64-byte ed25519 signature.
|
||||
function splitCert(certLine: string): { body: Buffer; rawSig: Buffer } {
|
||||
const blob = Buffer.from(certLine.split(/\s+/)[1], "base64");
|
||||
// trailing signature string = str( str("ssh-ed25519") + str(64-byte sig) )
|
||||
const sigBlobLen = 4 + "ssh-ed25519".length + 4 + 64; // 83
|
||||
const body = blob.subarray(0, blob.length - (4 + sigBlobLen));
|
||||
const rawSig = blob.subarray(blob.length - 64);
|
||||
return { body, rawSig };
|
||||
}
|
||||
|
||||
describe("generateCa", () => {
|
||||
it("produces a valid ed25519 public line and PKCS8 private key", () => {
|
||||
const ca = generateCa();
|
||||
expect(ca.publicKeyLine.startsWith("ssh-ed25519 ")).toBe(true);
|
||||
expect(ed25519RawFromLine(ca.publicKeyLine)?.length).toBe(32);
|
||||
expect(ca.privateKeyPem).toContain("BEGIN PRIVATE KEY");
|
||||
// The PEM must load as a usable signing key.
|
||||
expect(() =>
|
||||
crypto.createPrivateKey({
|
||||
key: ca.privateKeyPem,
|
||||
format: "pem",
|
||||
type: "pkcs8",
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("signUserCertificate", () => {
|
||||
it("returns null for non-ed25519 user keys", () => {
|
||||
const ca = generateCa();
|
||||
const cert = signUserCertificate({
|
||||
userPublicKeyLine: "ssh-rsa AAAAB3Nz",
|
||||
caPrivateKeyPem: ca.privateKeyPem,
|
||||
caPublicKeyLine: ca.publicKeyLine,
|
||||
keyId: "x",
|
||||
principals: [],
|
||||
validAfter: 0,
|
||||
validBefore: 1,
|
||||
});
|
||||
expect(cert).toBeNull();
|
||||
});
|
||||
|
||||
it("produces a cert whose signature verifies against the CA key", () => {
|
||||
const ca = generateCa();
|
||||
const user = generateCa(); // reuse: a valid ed25519 public line
|
||||
const cert = signUserCertificate({
|
||||
userPublicKeyLine: user.publicKeyLine,
|
||||
caPrivateKeyPem: ca.privateKeyPem,
|
||||
caPublicKeyLine: ca.publicKeyLine,
|
||||
keyId: "termix:@alice",
|
||||
principals: ["root", "ubuntu"],
|
||||
validAfter: 1000,
|
||||
validBefore: 2000,
|
||||
});
|
||||
expect(cert).not.toBeNull();
|
||||
expect(cert!.startsWith("ssh-ed25519-cert-v01@openssh.com ")).toBe(true);
|
||||
|
||||
const { body, rawSig } = splitCert(cert!);
|
||||
const caPub = publicKeyObjectFromLine(ca.publicKeyLine);
|
||||
expect(crypto.verify(null, body, caPub, rawSig)).toBe(true);
|
||||
|
||||
// A different CA must NOT verify.
|
||||
const otherPub = publicKeyObjectFromLine(generateCa().publicKeyLine);
|
||||
expect(crypto.verify(null, body, otherPub, rawSig)).toBe(false);
|
||||
});
|
||||
|
||||
it("is accepted and correctly parsed by ssh-keygen -L", () => {
|
||||
let sshKeygen: string;
|
||||
try {
|
||||
sshKeygen = execFileSync("ssh-keygen", ["--help"], { encoding: "utf8" });
|
||||
void sshKeygen;
|
||||
} catch (e) {
|
||||
// ssh-keygen prints usage to stderr and exits non-zero for --help; that's
|
||||
// fine — it means the binary exists. Only skip if it's truly missing.
|
||||
if ((e as { code?: string }).code === "ENOENT") return;
|
||||
}
|
||||
|
||||
const ca = generateCa();
|
||||
const user = generateCa();
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const cert = signUserCertificate({
|
||||
userPublicKeyLine: user.publicKeyLine,
|
||||
caPrivateKeyPem: ca.privateKeyPem,
|
||||
caPublicKeyLine: ca.publicKeyLine,
|
||||
keyId: "termix-test-id",
|
||||
principals: ["deploy"],
|
||||
validAfter: now,
|
||||
validBefore: now + 3600,
|
||||
});
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "termix-cert-"));
|
||||
const file = path.join(dir, "id-cert.pub");
|
||||
try {
|
||||
fs.writeFileSync(file, cert + "\n");
|
||||
const out = execFileSync("ssh-keygen", ["-L", "-f", file], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(out).toContain("user certificate");
|
||||
expect(out).toContain('Key ID: "termix-test-id"');
|
||||
expect(out).toContain("deploy");
|
||||
expect(out).toMatch(/permit-pty/);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
classifyAlgo,
|
||||
parsePublicKey,
|
||||
matchesAlgoFilter,
|
||||
MAX_PUBLIC_KEY_LENGTH,
|
||||
} from "../../../database/routes/termix-id-keys.js";
|
||||
|
||||
// Build a valid OpenSSH public-key line for a given type by encoding a wire
|
||||
// blob whose first string field equals the type (what parsePublicKey checks).
|
||||
function makeKey(type: string, comment = ""): string {
|
||||
const typeBuf = Buffer.from(type, "utf8");
|
||||
const header = Buffer.alloc(4);
|
||||
header.writeUInt32BE(typeBuf.length, 0);
|
||||
const body = Buffer.alloc(40); // arbitrary trailing key material
|
||||
const blob = Buffer.concat([header, typeBuf, body]).toString("base64");
|
||||
return `${type} ${blob}${comment ? ` ${comment}` : ""}`;
|
||||
}
|
||||
|
||||
describe("classifyAlgo", () => {
|
||||
it("maps known types to normalized groups", () => {
|
||||
expect(classifyAlgo("ssh-rsa")).toBe("RSA");
|
||||
expect(classifyAlgo("rsa-sha2-512")).toBe("RSA");
|
||||
expect(classifyAlgo("ssh-ed25519")).toBe("ED25519");
|
||||
expect(classifyAlgo("ecdsa-sha2-nistp256")).toBe("ECDSA");
|
||||
expect(classifyAlgo("ssh-dss")).toBe("DSA");
|
||||
expect(classifyAlgo("sk-ssh-ed25519@openssh.com")).toBe("ED25519-SK");
|
||||
expect(classifyAlgo("sk-ecdsa-sha2-nistp256@openssh.com")).toBe("ECDSA-SK");
|
||||
});
|
||||
|
||||
it("falls back by substring for unknown variants", () => {
|
||||
expect(classifyAlgo("ecdsa-sha2-nistp999")).toBe("ECDSA");
|
||||
expect(classifyAlgo("rsa-sha2-256-cert")).toBe("RSA");
|
||||
expect(classifyAlgo("something-weird")).toBe("SOMETHING-WEIRD");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parsePublicKey", () => {
|
||||
it("parses a valid ed25519 key and extracts the comment", () => {
|
||||
const parsed = parsePublicKey(makeKey("ssh-ed25519", "alice@laptop"));
|
||||
expect(parsed).not.toBeNull();
|
||||
expect(parsed?.type).toBe("ssh-ed25519");
|
||||
expect(parsed?.algorithm).toBe("ED25519");
|
||||
expect(parsed?.comment).toBe("alice@laptop");
|
||||
// Comment is stripped from the normalized (dedupe) form.
|
||||
expect(parsed?.normalized.includes("alice@laptop")).toBe(false);
|
||||
});
|
||||
|
||||
it("parses SK (FIDO) key types", () => {
|
||||
expect(
|
||||
parsePublicKey(makeKey("sk-ssh-ed25519@openssh.com"))?.algorithm,
|
||||
).toBe("ED25519-SK");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[null],
|
||||
[undefined],
|
||||
[""],
|
||||
[" "],
|
||||
["ssh-ed25519"], // missing blob
|
||||
["ssh-ed25519 not_base64!!"], // bad base64 charset
|
||||
["ssh-rsa AAAAB3Nz"], // blob whose embedded type != declared type
|
||||
])("rejects malformed input %p", (input) => {
|
||||
expect(parsePublicKey(input as string)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects an over-length line (amplification guard)", () => {
|
||||
const valid = makeKey("ssh-ed25519");
|
||||
const padded = valid + " " + "A".repeat(MAX_PUBLIC_KEY_LENGTH);
|
||||
expect(padded.length).toBeGreaterThan(MAX_PUBLIC_KEY_LENGTH);
|
||||
expect(parsePublicKey(padded)).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects a blob whose embedded type does not match the prefix", () => {
|
||||
// Declared ssh-rsa but the wire blob says ssh-ed25519.
|
||||
const blob = makeKey("ssh-ed25519").split(" ")[1];
|
||||
expect(parsePublicKey(`ssh-rsa ${blob}`)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchesAlgoFilter", () => {
|
||||
it("returns all keys when no filter", () => {
|
||||
expect(matchesAlgoFilter("ED25519", null)).toBe(true);
|
||||
});
|
||||
|
||||
it("matches exactly and is case-insensitive", () => {
|
||||
expect(matchesAlgoFilter("ED25519", "ed25519")).toBe(true);
|
||||
expect(matchesAlgoFilter("RSA", "RSA")).toBe(true);
|
||||
});
|
||||
|
||||
it("does NOT let ED25519 match ED25519-SK (the over-match bug)", () => {
|
||||
expect(matchesAlgoFilter("ED25519-SK", "ED25519")).toBe(false);
|
||||
expect(matchesAlgoFilter("ECDSA-SK", "ECDSA")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mockSelect = vi.fn();
|
||||
const mockUpdate = vi.fn();
|
||||
const mockInsert = vi.fn();
|
||||
const mockDelete = vi.fn();
|
||||
|
||||
vi.mock("../../../database/db/index.js", () => ({
|
||||
db: {
|
||||
select: mockSelect,
|
||||
update: mockUpdate,
|
||||
insert: mockInsert,
|
||||
delete: mockDelete,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
apiLogger: { error: vi.fn(), warn: vi.fn(), info: vi.fn(), success: vi.fn() },
|
||||
authLogger: {
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
info: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/auth-manager.js", () => ({
|
||||
AuthManager: {
|
||||
getInstance: () => ({
|
||||
createAuthMiddleware:
|
||||
() =>
|
||||
(req: Record<string, unknown>, _res: unknown, next: () => void) => {
|
||||
req.userId = "user-1";
|
||||
next();
|
||||
},
|
||||
createDataAccessMiddleware:
|
||||
() => (_req: unknown, _res: unknown, next: () => void) =>
|
||||
next(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/audit-logger.js", () => ({
|
||||
logAudit: vi.fn(),
|
||||
getRequestMeta: vi.fn(() => ({})),
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/data-crypto.js", () => ({
|
||||
DataCrypto: { getInstance: () => ({ encrypt: vi.fn(), decrypt: vi.fn() }) },
|
||||
}));
|
||||
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentTermixIdentityCaRepository: vi.fn(() => ({
|
||||
findPublicByIdentityId: vi.fn(),
|
||||
findDecryptedByIdentityId: vi.fn(),
|
||||
createEncryptedForUser: vi.fn(),
|
||||
updateEncryptedForIdentity: vi.fn(),
|
||||
deleteByIdentityId: vi.fn(),
|
||||
})),
|
||||
createCurrentTermixIdentityRepository: vi.fn(() => ({
|
||||
findIdentityForUser: vi.fn(),
|
||||
findIdentityByHandle: vi.fn(),
|
||||
isHandleTaken: vi.fn(),
|
||||
createIdentity: vi.fn(),
|
||||
updateIdentityForUser: vi.fn(),
|
||||
deleteIdentityForUser: vi.fn(),
|
||||
listKeysByIdentityId: vi.fn(),
|
||||
listEnabledKeysByIdentityId: vi.fn(),
|
||||
listLinkedCredentialIds: vi.fn(),
|
||||
createKey: vi.fn(),
|
||||
updateKeyForUser: vi.fn(),
|
||||
deleteKeyForUser: vi.fn(),
|
||||
findKeyForUser: vi.fn(),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("../../../database/routes/termix-id-keys.js", () => ({
|
||||
termixIdKeysRouter: { use: vi.fn() },
|
||||
matchesAlgoFilter: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
// Chainable Drizzle stub — supports arbitrary method chains and resolves via .then()
|
||||
function makeChain(resolveValue: unknown) {
|
||||
const chain: Record<string, unknown> = {};
|
||||
const methods = [
|
||||
"from",
|
||||
"where",
|
||||
"set",
|
||||
"values",
|
||||
"returning",
|
||||
"orderBy",
|
||||
"limit",
|
||||
"and",
|
||||
"eq",
|
||||
];
|
||||
for (const m of methods) {
|
||||
chain[m] = vi.fn(() => chain);
|
||||
}
|
||||
(chain as unknown as Promise<unknown>).then = (
|
||||
cb: (v: unknown) => unknown,
|
||||
eb?: (e: unknown) => unknown,
|
||||
) => Promise.resolve(resolveValue).then(cb, eb);
|
||||
(chain as unknown as Promise<unknown>).catch = (
|
||||
cb: (e: unknown) => unknown,
|
||||
) => Promise.resolve(resolveValue).catch(cb);
|
||||
return chain;
|
||||
}
|
||||
|
||||
const IDENTITY_ROW = { id: 42, userId: "user-1", handle: "alice" };
|
||||
|
||||
describe("GET /termix-id/linked-credentials", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("returns empty list when user has no identity", async () => {
|
||||
// First select (getIdentityForUser) returns nothing; second should not be called
|
||||
mockSelect.mockReturnValueOnce(makeChain([]));
|
||||
|
||||
const { default: router } =
|
||||
await import("../../../database/routes/termix-id.js");
|
||||
expect(router).toBeDefined();
|
||||
|
||||
expect(router).toBeDefined();
|
||||
}, 15_000);
|
||||
|
||||
it("returns empty list when identity has no keys", async () => {
|
||||
mockSelect
|
||||
.mockReturnValueOnce(makeChain([IDENTITY_ROW])) // identity lookup
|
||||
.mockReturnValueOnce(makeChain([])); // keys lookup
|
||||
|
||||
const { default: router } =
|
||||
await import("../../../database/routes/termix-id.js");
|
||||
expect(router).toBeDefined();
|
||||
});
|
||||
|
||||
it("returns deduplicated credentialIds for enabled keys", async () => {
|
||||
const keys = [
|
||||
{ credentialId: 10 },
|
||||
{ credentialId: 20 },
|
||||
{ credentialId: 10 }, // duplicate
|
||||
];
|
||||
mockSelect
|
||||
.mockReturnValueOnce(makeChain([IDENTITY_ROW]))
|
||||
.mockReturnValueOnce(makeChain(keys));
|
||||
|
||||
const { default: router } =
|
||||
await import("../../../database/routes/termix-id.js");
|
||||
expect(router).toBeDefined();
|
||||
});
|
||||
|
||||
it("excludes keys with null credentialId", async () => {
|
||||
const keys = [{ credentialId: null }, { credentialId: 5 }];
|
||||
mockSelect
|
||||
.mockReturnValueOnce(makeChain([IDENTITY_ROW]))
|
||||
.mockReturnValueOnce(makeChain(keys));
|
||||
|
||||
const { default: router } =
|
||||
await import("../../../database/routes/termix-id.js");
|
||||
expect(router).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,275 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import type { Request, RequestHandler, Response } from "express";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
currentUserId: "admin1",
|
||||
users: new Map<
|
||||
string,
|
||||
{
|
||||
id: string;
|
||||
username: string;
|
||||
isAdmin: boolean;
|
||||
isOidc: boolean;
|
||||
passwordHash: string | null;
|
||||
totpEnabled: boolean;
|
||||
}
|
||||
>(),
|
||||
unlockedUsers: new Set<string>(),
|
||||
updates: [] as { id: string; changes: Record<string, unknown> }[],
|
||||
auditCalls: [] as Record<string, unknown>[],
|
||||
}));
|
||||
|
||||
vi.mock("../../../database/db/index.js", () => ({ db: {} }));
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
authLogger: {
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
info: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/database-save-trigger.js", () => ({
|
||||
DatabaseSaveTrigger: { forceSave: vi.fn(async () => {}) },
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/audit-logger.js", () => ({
|
||||
logAudit: async (params: Record<string, unknown>) => {
|
||||
state.auditCalls.push(params);
|
||||
},
|
||||
getRequestMeta: () => ({ ipAddress: "", userAgent: "" }),
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/data-crypto.js", () => ({
|
||||
DataCrypto: {
|
||||
canUserAccessData: (userId: string) => state.unlockedUsers.has(userId),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/auth-manager.js", () => ({
|
||||
AuthManager: { getInstance: () => ({}) },
|
||||
}));
|
||||
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentUserRepository: () => ({
|
||||
listAll: async () => [...state.users.values()],
|
||||
findById: async (id: string) => state.users.get(id) ?? null,
|
||||
findByUsername: async (username: string) =>
|
||||
[...state.users.values()].find((u) => u.username === username) ?? null,
|
||||
update: async (id: string, changes: Record<string, unknown>) => {
|
||||
state.updates.push({ id, changes });
|
||||
const user = state.users.get(id);
|
||||
if (user) Object.assign(user, changes);
|
||||
},
|
||||
}),
|
||||
createCurrentRoleRepository: () => ({
|
||||
switchUserRoleName: async () => {},
|
||||
assignRoleNameToUser: async () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
const { registerUserAdminRoutes } =
|
||||
await import("../../../database/routes/user-admin-routes.js");
|
||||
|
||||
// Capture the handlers registered on the router so we can invoke them directly
|
||||
// without spinning up an HTTP server.
|
||||
type Registered = { method: string; path: string; handler: RequestHandler };
|
||||
const registered: Registered[] = [];
|
||||
|
||||
function fakeRouter() {
|
||||
const record =
|
||||
(method: string) =>
|
||||
(path: string, ...handlers: RequestHandler[]) => {
|
||||
registered.push({ method, path, handler: handlers[handlers.length - 1] });
|
||||
};
|
||||
return {
|
||||
get: record("get"),
|
||||
post: record("post"),
|
||||
put: record("put"),
|
||||
delete: record("delete"),
|
||||
} as unknown as import("express").Router;
|
||||
}
|
||||
|
||||
registerUserAdminRoutes(fakeRouter(), (_req, _res, next) => next());
|
||||
|
||||
function findHandler(method: string, path: string): RequestHandler {
|
||||
const match = registered.find((r) => r.method === method && r.path === path);
|
||||
if (!match) throw new Error(`No handler for ${method} ${path}`);
|
||||
return match.handler;
|
||||
}
|
||||
|
||||
function makeReqRes(overrides: {
|
||||
body?: Record<string, unknown>;
|
||||
params?: Record<string, unknown>;
|
||||
}) {
|
||||
const req = {
|
||||
userId: state.currentUserId,
|
||||
body: overrides.body ?? {},
|
||||
params: overrides.params ?? {},
|
||||
headers: {},
|
||||
} as unknown as Request;
|
||||
|
||||
const res = {
|
||||
statusCode: 200,
|
||||
jsonBody: null as unknown,
|
||||
headers: {} as Record<string, string>,
|
||||
status(code: number) {
|
||||
(this as unknown as { statusCode: number }).statusCode = code;
|
||||
return this;
|
||||
},
|
||||
json(payload: unknown) {
|
||||
(this as unknown as { jsonBody: unknown }).jsonBody = payload;
|
||||
return this;
|
||||
},
|
||||
setHeader(key: string, value: string) {
|
||||
(this as unknown as { headers: Record<string, string> }).headers[key] =
|
||||
value;
|
||||
return this;
|
||||
},
|
||||
} as unknown as Response & {
|
||||
statusCode: number;
|
||||
jsonBody: unknown;
|
||||
headers: Record<string, string>;
|
||||
};
|
||||
|
||||
return { req, res };
|
||||
}
|
||||
|
||||
async function invoke(
|
||||
method: string,
|
||||
path: string,
|
||||
overrides: {
|
||||
body?: Record<string, unknown>;
|
||||
params?: Record<string, unknown>;
|
||||
} = {},
|
||||
) {
|
||||
const handler = findHandler(method, path);
|
||||
const { req, res } = makeReqRes(overrides);
|
||||
await handler(req, res as unknown as Response, () => {});
|
||||
return res as unknown as {
|
||||
statusCode: number;
|
||||
jsonBody: Record<string, unknown> | null;
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
state.currentUserId = "admin1";
|
||||
state.users = new Map([
|
||||
[
|
||||
"admin1",
|
||||
{
|
||||
id: "admin1",
|
||||
username: "admin",
|
||||
isAdmin: true,
|
||||
isOidc: false,
|
||||
passwordHash: "hash",
|
||||
totpEnabled: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"target1",
|
||||
{
|
||||
id: "target1",
|
||||
username: "target",
|
||||
isAdmin: false,
|
||||
isOidc: false,
|
||||
passwordHash: "hash",
|
||||
totpEnabled: true,
|
||||
},
|
||||
],
|
||||
[
|
||||
"locked1",
|
||||
{
|
||||
id: "locked1",
|
||||
username: "locked",
|
||||
isAdmin: false,
|
||||
isOidc: false,
|
||||
passwordHash: "hash",
|
||||
totpEnabled: false,
|
||||
},
|
||||
],
|
||||
]);
|
||||
state.unlockedUsers = new Set(["admin1", "target1"]);
|
||||
state.updates = [];
|
||||
state.auditCalls = [];
|
||||
});
|
||||
|
||||
describe("GET /list", () => {
|
||||
it("includes data_unlocked and totp_enabled for admin callers", async () => {
|
||||
const res = await invoke("get", "/list");
|
||||
expect(res.statusCode).toBe(200);
|
||||
const users = (res.jsonBody as { users: Record<string, unknown>[] }).users;
|
||||
const target = users.find((u) => u.userId === "target1")!;
|
||||
expect(target.data_unlocked).toBe(true);
|
||||
expect(target.totp_enabled).toBe(true);
|
||||
const locked = users.find((u) => u.userId === "locked1")!;
|
||||
expect(locked.data_unlocked).toBe(false);
|
||||
});
|
||||
|
||||
it("omits management fields for non-admin callers", async () => {
|
||||
state.currentUserId = "target1";
|
||||
const res = await invoke("get", "/list");
|
||||
const users = (res.jsonBody as { users: Record<string, unknown>[] }).users;
|
||||
expect(users[0].data_unlocked).toBeUndefined();
|
||||
expect(users[0].totp_enabled).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /admin/totp/disable", () => {
|
||||
it("clears TOTP fields for the target and audits", async () => {
|
||||
const res = await invoke("post", "/admin/totp/disable", {
|
||||
body: { userId: "target1" },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const update = state.updates.find((u) => u.id === "target1");
|
||||
expect(update?.changes).toMatchObject({
|
||||
totpSecret: null,
|
||||
totpEnabled: false,
|
||||
totpBackupCodes: null,
|
||||
});
|
||||
expect(
|
||||
state.auditCalls.some((c) => c.action === "admin_disable_totp"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("403s when the caller is not an admin", async () => {
|
||||
state.currentUserId = "target1";
|
||||
const res = await invoke("post", "/admin/totp/disable", {
|
||||
body: { userId: "locked1" },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("400s when TOTP is not enabled for the target", async () => {
|
||||
const res = await invoke("post", "/admin/totp/disable", {
|
||||
body: { userId: "locked1" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("404s for an unknown target", async () => {
|
||||
const res = await invoke("post", "/admin/totp/disable", {
|
||||
body: { userId: "ghost" },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /admin/export/:userId", () => {
|
||||
it("423s when the target's data is locked", async () => {
|
||||
const res = await invoke("get", "/admin/export/:userId", {
|
||||
params: { userId: "locked1" },
|
||||
});
|
||||
expect(res.statusCode).toBe(423);
|
||||
expect((res.jsonBody as { code?: string }).code).toBe("TARGET_DATA_LOCKED");
|
||||
});
|
||||
|
||||
it("403s when the caller is not an admin", async () => {
|
||||
state.currentUserId = "target1";
|
||||
const res = await invoke("get", "/admin/export/:userId", {
|
||||
params: { userId: "admin1" },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
// user-oidc-utils imports the logger; stub it so importing stays side-effect-free.
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
authLogger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const {
|
||||
isOIDCUserAllowed,
|
||||
getOIDCConfigFromEnv,
|
||||
extractOidcGroups,
|
||||
validateLogoutTokenClaims,
|
||||
} = await import("../../../database/routes/user-oidc-utils.js");
|
||||
|
||||
const BACKCHANNEL_LOGOUT_EVENT =
|
||||
"http://schemas.openid.net/event/backchannel-logout";
|
||||
|
||||
describe("isOIDCUserAllowed", () => {
|
||||
it("allows everyone when the allow-list is empty", () => {
|
||||
expect(isOIDCUserAllowed("", "alice", "alice@x.com")).toBe(true);
|
||||
expect(isOIDCUserAllowed(" ", "alice")).toBe(true);
|
||||
});
|
||||
|
||||
it("allows everyone with the '*' wildcard", () => {
|
||||
expect(isOIDCUserAllowed("*", "anyone", "anyone@x.com")).toBe(true);
|
||||
});
|
||||
|
||||
it("matches an exact identifier (case-insensitive)", () => {
|
||||
expect(isOIDCUserAllowed("alice,bob", "alice")).toBe(true);
|
||||
expect(isOIDCUserAllowed("Alice", "alice")).toBe(true);
|
||||
expect(isOIDCUserAllowed("alice", "ALICE")).toBe(true);
|
||||
});
|
||||
|
||||
it("matches against the email as well as the identifier", () => {
|
||||
expect(isOIDCUserAllowed("alice@x.com", "sub-123", "alice@x.com")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("matches an @domain suffix pattern", () => {
|
||||
expect(isOIDCUserAllowed("@company.com", "sub-1", "bob@company.com")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isOIDCUserAllowed("@company.com", "sub-1", "bob@COMPANY.COM")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("denies users not on the list", () => {
|
||||
expect(isOIDCUserAllowed("alice,bob", "charlie", "charlie@x.com")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isOIDCUserAllowed("@company.com", "sub-1", "bob@other.com")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores blank entries and surrounding whitespace in the list", () => {
|
||||
expect(isOIDCUserAllowed(" alice , , bob ", "bob")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not match the email against an identifier-only pattern when email differs", () => {
|
||||
expect(isOIDCUserAllowed("alice", "sub-123", "alice@x.com")).toBe(false);
|
||||
});
|
||||
|
||||
it("matches *@domain.com wildcard pattern against emails", () => {
|
||||
expect(
|
||||
isOIDCUserAllowed("*@company.com", "sub-1", "john@company.com"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isOIDCUserAllowed("*@company.com", "sub-1", "jane@COMPANY.COM"),
|
||||
).toBe(true);
|
||||
expect(isOIDCUserAllowed("*@company.com", "sub-1", "user@other.com")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("matches glob patterns with multiple wildcards", () => {
|
||||
expect(isOIDCUserAllowed("admin*", "admin_user")).toBe(true);
|
||||
expect(isOIDCUserAllowed("admin*", "user_admin")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getOIDCConfigFromEnv", () => {
|
||||
const REQUIRED = [
|
||||
"OIDC_CLIENT_ID",
|
||||
"OIDC_CLIENT_SECRET",
|
||||
"OIDC_ISSUER_URL",
|
||||
"OIDC_AUTHORIZATION_URL",
|
||||
"OIDC_TOKEN_URL",
|
||||
];
|
||||
const OPTIONAL = [
|
||||
"OIDC_USERINFO_URL",
|
||||
"OIDC_IDENTIFIER_PATH",
|
||||
"OIDC_NAME_PATH",
|
||||
"OIDC_SCOPES",
|
||||
"OIDC_ALLOWED_USERS",
|
||||
"OIDC_ADMIN_GROUP",
|
||||
];
|
||||
const saved: Record<string, string | undefined> = {};
|
||||
|
||||
beforeEach(() => {
|
||||
for (const key of [...REQUIRED, ...OPTIONAL]) {
|
||||
saved[key] = process.env[key];
|
||||
delete process.env[key];
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of [...REQUIRED, ...OPTIONAL]) {
|
||||
if (saved[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = saved[key];
|
||||
}
|
||||
});
|
||||
|
||||
it("returns null when any required variable is missing", () => {
|
||||
process.env.OIDC_CLIENT_ID = "id";
|
||||
process.env.OIDC_CLIENT_SECRET = "secret";
|
||||
// issuer/authorization/token urls intentionally missing
|
||||
expect(getOIDCConfigFromEnv()).toBeNull();
|
||||
});
|
||||
|
||||
it("builds a config with defaults when all required vars are present", () => {
|
||||
process.env.OIDC_CLIENT_ID = "id";
|
||||
process.env.OIDC_CLIENT_SECRET = "secret";
|
||||
process.env.OIDC_ISSUER_URL = "https://idp.example";
|
||||
process.env.OIDC_AUTHORIZATION_URL = "https://idp.example/auth";
|
||||
process.env.OIDC_TOKEN_URL = "https://idp.example/token";
|
||||
|
||||
const config = getOIDCConfigFromEnv();
|
||||
expect(config).not.toBeNull();
|
||||
expect(config?.client_id).toBe("id");
|
||||
expect(config?.identifier_path).toBe("sub");
|
||||
expect(config?.name_path).toBe("name");
|
||||
expect(config?.scopes).toBe("openid email profile");
|
||||
expect(config?.userinfo_url).toBe("");
|
||||
});
|
||||
|
||||
it("honors overrides for optional vars", () => {
|
||||
process.env.OIDC_CLIENT_ID = "id";
|
||||
process.env.OIDC_CLIENT_SECRET = "secret";
|
||||
process.env.OIDC_ISSUER_URL = "https://idp.example";
|
||||
process.env.OIDC_AUTHORIZATION_URL = "https://idp.example/auth";
|
||||
process.env.OIDC_TOKEN_URL = "https://idp.example/token";
|
||||
process.env.OIDC_IDENTIFIER_PATH = "email";
|
||||
process.env.OIDC_SCOPES = "openid";
|
||||
|
||||
const config = getOIDCConfigFromEnv();
|
||||
expect(config?.identifier_path).toBe("email");
|
||||
expect(config?.scopes).toBe("openid");
|
||||
});
|
||||
});
|
||||
|
||||
describe("extractOidcGroups", () => {
|
||||
it("reads the standard groups claim as an array", () => {
|
||||
expect(extractOidcGroups({ groups: ["admin", "user"] })).toEqual([
|
||||
"admin",
|
||||
"user",
|
||||
]);
|
||||
});
|
||||
|
||||
it("splits a comma-separated string claim", () => {
|
||||
expect(extractOidcGroups({ roles: "admin, user" })).toEqual([
|
||||
"admin",
|
||||
"user",
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back through groups, roles, then group", () => {
|
||||
expect(extractOidcGroups({ group: "ops" })).toEqual(["ops"]);
|
||||
});
|
||||
|
||||
it("reads a custom claim path when provided", () => {
|
||||
const userInfo = {
|
||||
"zitadel:grants:groups:123": ["user", "admin"],
|
||||
groups: ["ignored"],
|
||||
};
|
||||
expect(extractOidcGroups(userInfo, "zitadel:grants:groups:123")).toEqual([
|
||||
"user",
|
||||
"admin",
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses object keys as group names (Zitadel roles object)", () => {
|
||||
const userInfo = {
|
||||
"urn:zitadel:iam:org:project:roles": { admin: {}, user: {} },
|
||||
};
|
||||
expect(
|
||||
extractOidcGroups(userInfo, "urn:zitadel:iam:org:project:roles"),
|
||||
).toEqual(["admin", "user"]);
|
||||
});
|
||||
|
||||
it("falls back to defaults when the custom claim is absent", () => {
|
||||
expect(extractOidcGroups({ groups: ["admin"] }, "missing")).toEqual([
|
||||
"admin",
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns an empty array when no groups are present", () => {
|
||||
expect(extractOidcGroups({})).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateLogoutTokenClaims", () => {
|
||||
const validClaims = {
|
||||
sub: "subject-1",
|
||||
sid: "session-1",
|
||||
iat: 1_783_641_600,
|
||||
jti: "logout-1",
|
||||
events: { [BACKCHANNEL_LOGOUT_EVENT]: {} },
|
||||
};
|
||||
|
||||
it("accepts a spec-compliant back-channel logout payload", () => {
|
||||
expect(validateLogoutTokenClaims(validClaims)).toEqual({
|
||||
sub: "subject-1",
|
||||
sid: "session-1",
|
||||
jti: "logout-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("requires the logout event to contain an object", () => {
|
||||
expect(() =>
|
||||
validateLogoutTokenClaims({
|
||||
...validClaims,
|
||||
events: { [BACKCHANNEL_LOGOUT_EVENT]: true },
|
||||
}),
|
||||
).toThrow("missing back-channel logout event");
|
||||
});
|
||||
|
||||
it("requires iat and jti claims", () => {
|
||||
expect(() =>
|
||||
validateLogoutTokenClaims({ ...validClaims, iat: undefined }),
|
||||
).toThrow("missing iat claim");
|
||||
expect(() =>
|
||||
validateLogoutTokenClaims({ ...validClaims, jti: "" }),
|
||||
).toThrow("missing jti claim");
|
||||
});
|
||||
|
||||
it("rejects nonce and requires sub or sid", () => {
|
||||
expect(() =>
|
||||
validateLogoutTokenClaims({ ...validClaims, nonce: "forbidden" }),
|
||||
).toThrow("must not contain a nonce");
|
||||
expect(() =>
|
||||
validateLogoutTokenClaims({ ...validClaims, sub: null, sid: null }),
|
||||
).toThrow("must contain sub and/or sid");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AuthManager } from "../../../utils/auth-manager.js";
|
||||
|
||||
const calls = vi.hoisted(() => ({
|
||||
userUpdates: [] as Array<[string, Record<string, unknown>]>,
|
||||
deletedFor: [] as string[],
|
||||
rotatedFor: [] as string[],
|
||||
legacyWrapsDeletedFor: [] as string[],
|
||||
}));
|
||||
|
||||
function deletingRepo(label: string) {
|
||||
return () => ({
|
||||
deleteByUserId: async (userId: string) => {
|
||||
calls.deletedFor.push(`${label}:${userId}`);
|
||||
return 0;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentUserRepository: () => ({
|
||||
update: async (userId: string, update: Record<string, unknown>) => {
|
||||
calls.userUpdates.push([userId, update]);
|
||||
return { id: userId };
|
||||
},
|
||||
}),
|
||||
createCurrentSettingsRepository: () => ({}),
|
||||
createCurrentSshCredentialUsageRepository: deletingRepo("usage"),
|
||||
createCurrentFileManagerBookmarkRepository: deletingRepo("bookmarks"),
|
||||
createCurrentRecentActivityRepository: deletingRepo("activity"),
|
||||
createCurrentDismissedAlertRepository: deletingRepo("alerts"),
|
||||
createCurrentSnippetRepository: deletingRepo("snippets"),
|
||||
createCurrentHostRepository: deletingRepo("hosts"),
|
||||
createCurrentCredentialRepository: deletingRepo("credentials"),
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/user-keys.js", () => ({
|
||||
UserKeyManager: {
|
||||
getInstance: () => ({
|
||||
rotateUserDEK: async (userId: string) => {
|
||||
calls.rotatedFor.push(userId);
|
||||
return Buffer.alloc(32);
|
||||
},
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/crypto-migration/dek-migration.js", () => ({
|
||||
deleteLegacyWraps: async (userId: string) => {
|
||||
calls.legacyWrapsDeletedFor.push(userId);
|
||||
},
|
||||
}));
|
||||
|
||||
import { resetUserPassword } from "../../../database/routes/user-password-reset-routes.js";
|
||||
|
||||
function fakeAuthManager(unlocked: boolean): AuthManager {
|
||||
return {
|
||||
isUserUnlocked: () => unlocked,
|
||||
logoutUser: vi.fn(async () => {}),
|
||||
} as unknown as AuthManager;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
calls.userUpdates = [];
|
||||
calls.deletedFor = [];
|
||||
calls.rotatedFor = [];
|
||||
calls.legacyWrapsDeletedFor = [];
|
||||
});
|
||||
|
||||
describe("resetUserPassword", () => {
|
||||
it("preserves data for users with a server-wrapped key", async () => {
|
||||
const outcome = await resetUserPassword(fakeAuthManager(true), {
|
||||
userId: "user-1",
|
||||
username: "alice",
|
||||
newPassword: "new-password",
|
||||
confirmDataWipe: false,
|
||||
});
|
||||
|
||||
expect(outcome).toEqual({ status: "reset", dataWiped: false });
|
||||
expect(calls.userUpdates).toHaveLength(1);
|
||||
expect(calls.userUpdates[0][1]).toHaveProperty("passwordHash");
|
||||
expect(calls.deletedFor).toEqual([]);
|
||||
expect(calls.rotatedFor).toEqual([]);
|
||||
});
|
||||
|
||||
it("requires explicit consent before wiping an unmigrated user", async () => {
|
||||
const outcome = await resetUserPassword(fakeAuthManager(false), {
|
||||
userId: "user-1",
|
||||
username: "alice",
|
||||
newPassword: "new-password",
|
||||
confirmDataWipe: false,
|
||||
});
|
||||
|
||||
expect(outcome).toEqual({ status: "wipe_confirmation_required" });
|
||||
expect(calls.userUpdates).toEqual([]);
|
||||
expect(calls.deletedFor).toEqual([]);
|
||||
});
|
||||
|
||||
it("wipes data and rotates the key when consent is given", async () => {
|
||||
const outcome = await resetUserPassword(fakeAuthManager(false), {
|
||||
userId: "user-1",
|
||||
username: "alice",
|
||||
newPassword: "new-password",
|
||||
confirmDataWipe: true,
|
||||
});
|
||||
|
||||
expect(outcome).toEqual({ status: "reset", dataWiped: true });
|
||||
expect(calls.deletedFor).toEqual([
|
||||
"usage:user-1",
|
||||
"bookmarks:user-1",
|
||||
"activity:user-1",
|
||||
"alerts:user-1",
|
||||
"snippets:user-1",
|
||||
"hosts:user-1",
|
||||
"credentials:user-1",
|
||||
]);
|
||||
expect(calls.rotatedFor).toEqual(["user-1"]);
|
||||
expect(calls.legacyWrapsDeletedFor).toEqual(["user-1"]);
|
||||
expect(
|
||||
calls.userUpdates.some(([, update]) => update.totpEnabled === false),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import bcrypt from "bcryptjs";
|
||||
import speakeasy from "speakeasy";
|
||||
|
||||
// The route module imports repository factories and the logger; stub both so
|
||||
// importing stays inert.
|
||||
const userRepositoryUpdate = vi.fn().mockResolvedValue(null);
|
||||
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentUserRepository: () => ({
|
||||
update: userRepositoryUpdate,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
authLogger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const { verifyTotpReauth } =
|
||||
await import("../../../database/routes/user-totp-routes.js");
|
||||
|
||||
type AnyUser = Parameters<typeof verifyTotpReauth>[0];
|
||||
|
||||
const secret = speakeasy.generateSecret({ name: "test" }).base32;
|
||||
|
||||
function makeUser(overrides: Partial<AnyUser> = {}): AnyUser {
|
||||
return {
|
||||
id: "user-1",
|
||||
isOidc: false,
|
||||
passwordHash: bcrypt.hashSync("correct-horse", 4),
|
||||
totpSecret: secret,
|
||||
totpBackupCodes: JSON.stringify(["BACKUP01", "BACKUP02"]),
|
||||
totpEnabled: true,
|
||||
...overrides,
|
||||
} as AnyUser;
|
||||
}
|
||||
|
||||
describe("verifyTotpReauth", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("does not accept the account password as a second factor", async () => {
|
||||
expect(await verifyTotpReauth(makeUser(), "correct-horse")).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a valid TOTP code without a password", async () => {
|
||||
const token = speakeasy.totp({ secret, encoding: "base32" });
|
||||
expect(await verifyTotpReauth(makeUser(), token)).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a valid backup code and consumes it", async () => {
|
||||
const result = await verifyTotpReauth(makeUser(), "BACKUP01");
|
||||
expect(result).toBe(true);
|
||||
expect(userRepositoryUpdate).toHaveBeenCalledWith("user-1", {
|
||||
totpBackupCodes: JSON.stringify(["BACKUP02"]),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a wrong password / invalid code", async () => {
|
||||
expect(await verifyTotpReauth(makeUser(), "wrong")).toBe(false);
|
||||
expect(userRepositoryUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores the password path for OIDC users but still accepts TOTP", async () => {
|
||||
const token = speakeasy.totp({ secret, encoding: "base32" });
|
||||
const oidcUser = makeUser({ isOidc: true, passwordHash: null });
|
||||
expect(await verifyTotpReauth(oidcUser, token)).toBe(true);
|
||||
expect(await verifyTotpReauth(oidcUser, "anything")).toBe(false);
|
||||
});
|
||||
|
||||
it("handles malformed backup-code JSON without throwing", async () => {
|
||||
const user = makeUser({ totpBackupCodes: "not json" });
|
||||
expect(await verifyTotpReauth(user, "BACKUP01")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
pickResolvedUsername,
|
||||
pickResolvedPassword,
|
||||
expandOidcUsername,
|
||||
} from "../../hosts/credential-username.js";
|
||||
|
||||
describe("pickResolvedUsername", () => {
|
||||
it("keeps the host username when one is set, even with a credential username", () => {
|
||||
expect(pickResolvedUsername("admin", "root", false)).toBe("admin");
|
||||
});
|
||||
|
||||
it("falls back to the credential username when the host has none", () => {
|
||||
expect(pickResolvedUsername("", "root", false)).toBe("root");
|
||||
expect(pickResolvedUsername(undefined, "root", false)).toBe("root");
|
||||
expect(pickResolvedUsername(" ", "root", false)).toBe("root");
|
||||
});
|
||||
|
||||
it("treats whitespace-only host usernames as empty", () => {
|
||||
expect(pickResolvedUsername(" ", "deploy", false)).toBe("deploy");
|
||||
});
|
||||
|
||||
it("forces the host username when overrideCredentialUsername is set", () => {
|
||||
expect(pickResolvedUsername("admin", "root", true)).toBe("admin");
|
||||
expect(pickResolvedUsername("", "root", true)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined when neither username is usable", () => {
|
||||
expect(pickResolvedUsername("", "", false)).toBeUndefined();
|
||||
expect(pickResolvedUsername(undefined, undefined, false)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("pickResolvedPassword", () => {
|
||||
it("keeps the host-specific password ahead of the credential password", () => {
|
||||
expect(pickResolvedPassword("host-pass", "credential-pass")).toBe(
|
||||
"host-pass",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the credential password when the host has none", () => {
|
||||
expect(pickResolvedPassword("", "credential-pass")).toBe("credential-pass");
|
||||
expect(pickResolvedPassword(undefined, "credential-pass")).toBe(
|
||||
"credential-pass",
|
||||
);
|
||||
});
|
||||
|
||||
it("treats whitespace-only passwords as empty", () => {
|
||||
expect(pickResolvedPassword(" ", "credential-pass")).toBe(
|
||||
"credential-pass",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("expandOidcUsername", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("returns the username unchanged when it has no placeholder", async () => {
|
||||
expect(await expandOidcUsername("alice", "user-1")).toBe("alice");
|
||||
expect(await expandOidcUsername(undefined, "user-1")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("expands the placeholder with the user's OIDC identifier", async () => {
|
||||
vi.doMock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentUserRepository: () => ({
|
||||
findById: async () => ({ oidcIdentifier: "jdoe" }),
|
||||
}),
|
||||
}));
|
||||
|
||||
const { expandOidcUsername: expand } =
|
||||
await import("../../hosts/credential-username.js");
|
||||
expect(await expand("$oidc.preferred_username", "user-1")).toBe("jdoe");
|
||||
});
|
||||
|
||||
it("leaves the placeholder as-is when the user has no OIDC identifier", async () => {
|
||||
vi.doMock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentUserRepository: () => ({
|
||||
findById: async () => ({ oidcIdentifier: null }),
|
||||
}),
|
||||
}));
|
||||
|
||||
const { expandOidcUsername: expand } =
|
||||
await import("../../hosts/credential-username.js");
|
||||
expect(await expand("$oidc.preferred_username", "user-1")).toBe(
|
||||
"$oidc.preferred_username",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns the username unchanged when the DB lookup throws", async () => {
|
||||
vi.doMock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentUserRepository: () => {
|
||||
throw new Error("DB unavailable");
|
||||
},
|
||||
}));
|
||||
|
||||
const { expandOidcUsername: expand } =
|
||||
await import("../../hosts/credential-username.js");
|
||||
expect(await expand("$oidc.preferred_username", "user-1")).toBe(
|
||||
"$oidc.preferred_username",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildDeleteCommand } from "../../../hosts/file-manager/operation-commands.js";
|
||||
|
||||
describe("buildDeleteCommand", () => {
|
||||
it("builds a PowerShell 5.1 compatible delete command for Windows files", () => {
|
||||
const command = buildDeleteCommand(
|
||||
"/C:/Users/Administrator/test.txt",
|
||||
false,
|
||||
);
|
||||
|
||||
expect(command.command).toBe(
|
||||
"Remove-Item -LiteralPath 'C:\\Users\\Administrator\\test.txt' -Force -ErrorAction Stop",
|
||||
);
|
||||
expect(command.commandWithSuccess).toBe(
|
||||
`${command.command}; if ($?) { Write-Output "SUCCESS" }`,
|
||||
);
|
||||
expect(command.commandWithSuccess).not.toContain("&&");
|
||||
});
|
||||
|
||||
it("adds recursive deletion for Windows directories", () => {
|
||||
const command = buildDeleteCommand("C:/Temp/Folder", true);
|
||||
|
||||
expect(command.command).toBe(
|
||||
"Remove-Item -LiteralPath 'C:\\Temp\\Folder' -Recurse -Force -ErrorAction Stop",
|
||||
);
|
||||
});
|
||||
|
||||
it("escapes single quotes in Windows literal paths", () => {
|
||||
const command = buildDeleteCommand("/C:/Temp/O'Brien.txt", false);
|
||||
|
||||
expect(command.command).toBe(
|
||||
"Remove-Item -LiteralPath 'C:\\Temp\\O''Brien.txt' -Force -ErrorAction Stop",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps POSIX delete commands using shell success chaining", () => {
|
||||
const command = buildDeleteCommand("/tmp/O'Brien.txt", false);
|
||||
|
||||
expect(command.command).toBe("rm -f '/tmp/O'\"'\"'Brien.txt'");
|
||||
expect(command.commandWithSuccess).toBe(
|
||||
`${command.command} && echo "SUCCESS"`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
isExecutableFile,
|
||||
modeToPermissions,
|
||||
formatMtime,
|
||||
getMimeType,
|
||||
detectBinary,
|
||||
parseLsDateToTimestamp,
|
||||
} from "../../../hosts/file-manager/utils.js";
|
||||
|
||||
describe("isExecutableFile", () => {
|
||||
it("flags scripts with execute permission", () => {
|
||||
expect(isExecutableFile("-rwxr-xr-x", "deploy.sh")).toBe(true);
|
||||
expect(isExecutableFile("-rwxr-xr-x", "run.py")).toBe(true);
|
||||
});
|
||||
|
||||
it("flags known executable extensions with execute permission", () => {
|
||||
expect(isExecutableFile("-rwxr-xr-x", "tool.bin")).toBe(true);
|
||||
expect(isExecutableFile("-rwxr-xr-x", "app.exe")).toBe(true);
|
||||
});
|
||||
|
||||
it("flags extensionless files with execute permission", () => {
|
||||
expect(isExecutableFile("-rwxr-xr-x", "myprogram")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not flag files without execute permission", () => {
|
||||
expect(isExecutableFile("-rw-r--r--", "deploy.sh")).toBe(false);
|
||||
expect(isExecutableFile("-rw-r--r--", "myprogram")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not flag non-script data files even when executable", () => {
|
||||
expect(isExecutableFile("-rwxr-xr-x", "notes.txt")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("modeToPermissions", () => {
|
||||
it("renders a regular file with rwxr-xr-x", () => {
|
||||
expect(modeToPermissions(0o100755)).toBe("-rwxr-xr-x");
|
||||
});
|
||||
|
||||
it("renders a directory prefix", () => {
|
||||
expect(modeToPermissions(0o040755)).toBe("drwxr-xr-x");
|
||||
});
|
||||
|
||||
it("renders a symlink prefix", () => {
|
||||
expect(modeToPermissions(0o120777)).toBe("lrwxrwxrwx");
|
||||
});
|
||||
|
||||
it("renders a read-only file", () => {
|
||||
expect(modeToPermissions(0o100444)).toBe("-r--r--r--");
|
||||
});
|
||||
|
||||
it("renders no permissions", () => {
|
||||
expect(modeToPermissions(0o100000)).toBe("----------");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatMtime", () => {
|
||||
it("uses HH:MM format for recent timestamps", () => {
|
||||
// Within the last 6 months relative to now.
|
||||
const recent = Math.floor(Date.now() / 1000) - 60 * 60 * 24 * 5;
|
||||
const result = formatMtime(recent);
|
||||
expect(result).toMatch(/^[A-Z][a-z]{2} +\d{1,2} \d{2}:\d{2}$/);
|
||||
});
|
||||
|
||||
it("uses the year for old timestamps", () => {
|
||||
// ~2 years ago is comfortably outside the 6-month window.
|
||||
const old = Math.floor(Date.now() / 1000) - 60 * 60 * 24 * 365 * 2;
|
||||
const result = formatMtime(old);
|
||||
expect(result).toMatch(/^[A-Z][a-z]{2} +\d{1,2} +\d{4}$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getMimeType", () => {
|
||||
it("maps known extensions", () => {
|
||||
expect(getMimeType("readme.txt")).toBe("text/plain");
|
||||
expect(getMimeType("data.json")).toBe("application/json");
|
||||
expect(getMimeType("photo.JPEG")).toBe("image/jpeg");
|
||||
expect(getMimeType("archive.zip")).toBe("application/zip");
|
||||
});
|
||||
|
||||
it("falls back to octet-stream for unknown or missing extensions", () => {
|
||||
expect(getMimeType("mystery.xyz")).toBe("application/octet-stream");
|
||||
expect(getMimeType("noextension")).toBe("application/octet-stream");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseLsDateToTimestamp", () => {
|
||||
it("parses a year-format date string", () => {
|
||||
const ts = parseLsDateToTimestamp("Dec 12 2025");
|
||||
const d = new Date(ts * 1000);
|
||||
expect(d.getFullYear()).toBe(2025);
|
||||
expect(d.getMonth()).toBe(11);
|
||||
expect(d.getDate()).toBe(12);
|
||||
});
|
||||
|
||||
it("parses a time-format date string for a recent file", () => {
|
||||
const now = new Date();
|
||||
const month = [
|
||||
"Jan",
|
||||
"Feb",
|
||||
"Mar",
|
||||
"Apr",
|
||||
"May",
|
||||
"Jun",
|
||||
"Jul",
|
||||
"Aug",
|
||||
"Sep",
|
||||
"Oct",
|
||||
"Nov",
|
||||
"Dec",
|
||||
][now.getMonth()];
|
||||
const day = now.getDate();
|
||||
const ts = parseLsDateToTimestamp(`${month} ${day} 10:30`);
|
||||
const d = new Date(ts * 1000);
|
||||
expect(d.getHours()).toBe(10);
|
||||
expect(d.getMinutes()).toBe(30);
|
||||
});
|
||||
|
||||
it("returns 0 for an empty or invalid string", () => {
|
||||
expect(parseLsDateToTimestamp("")).toBe(0);
|
||||
expect(parseLsDateToTimestamp("Xyz 5 12:00")).toBe(0);
|
||||
});
|
||||
|
||||
it("produces ascending order for older vs newer dates", () => {
|
||||
const older = parseLsDateToTimestamp("Jan 1 2020");
|
||||
const newer = parseLsDateToTimestamp("Dec 31 2024");
|
||||
expect(older).toBeLessThan(newer);
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectBinary", () => {
|
||||
it("returns false for empty buffers", () => {
|
||||
expect(detectBinary(Buffer.from([]))).toBe(false);
|
||||
});
|
||||
|
||||
it("returns false for plain UTF-8 text", () => {
|
||||
expect(detectBinary(Buffer.from("hello world\nsecond line\t tab"))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns true when null bytes are present", () => {
|
||||
expect(detectBinary(Buffer.from([0x48, 0x00, 0x49, 0x00]))).toBe(true);
|
||||
});
|
||||
|
||||
it("allows common whitespace control characters", () => {
|
||||
expect(detectBinary(Buffer.from("line1\r\nline2\tend"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
guacLogger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const { GuacamoleTokenService } =
|
||||
await import("../../../hosts/guacamole/token-service.js");
|
||||
|
||||
describe("GuacamoleTokenService", () => {
|
||||
const tokenService = GuacamoleTokenService.getInstance();
|
||||
|
||||
it("disables RDP pre-authentication when no credentials are configured", () => {
|
||||
const token = tokenService.createRdpToken("windows.example.test", "", "");
|
||||
const decrypted = tokenService.decryptToken(token);
|
||||
|
||||
expect(decrypted?.connection.settings).toMatchObject({
|
||||
hostname: "windows.example.test",
|
||||
port: 3389,
|
||||
"ignore-cert": true,
|
||||
"disable-auth": true,
|
||||
});
|
||||
expect(decrypted?.connection.settings.username).toBeUndefined();
|
||||
expect(decrypted?.connection.settings.password).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps normal RDP credential authentication unchanged", () => {
|
||||
const token = tokenService.createRdpToken(
|
||||
"windows.example.test",
|
||||
"Administrator",
|
||||
"secret",
|
||||
);
|
||||
const decrypted = tokenService.decryptToken(token);
|
||||
|
||||
expect(decrypted?.connection.settings).toMatchObject({
|
||||
hostname: "windows.example.test",
|
||||
username: "Administrator",
|
||||
password: "secret",
|
||||
port: 3389,
|
||||
});
|
||||
expect(decrypted?.connection.settings["disable-auth"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves recording metadata outside guacd connection settings", () => {
|
||||
const recording = {
|
||||
hostId: 42,
|
||||
userId: "user-1",
|
||||
protocol: "vnc" as const,
|
||||
path: "recording.guac",
|
||||
startedAt: "2026-07-14T00:00:00.000Z",
|
||||
};
|
||||
const token = tokenService.createVncToken(
|
||||
"vnc.example.test",
|
||||
"user",
|
||||
"secret",
|
||||
{},
|
||||
recording,
|
||||
);
|
||||
|
||||
expect(tokenService.decryptToken(token)?.recording).toEqual(recording);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
deriveEnabledWidgets,
|
||||
defaultLayoutFromWidgets,
|
||||
isMetricCardId,
|
||||
isManagerCardId,
|
||||
METRIC_CARD_IDS,
|
||||
} from "../../../types/host-metrics.js";
|
||||
|
||||
describe("deriveEnabledWidgets", () => {
|
||||
it("returns only metric ids, in canonical order, deduped", () => {
|
||||
const slots = [
|
||||
{ id: "firewall" },
|
||||
{ id: "cpu" },
|
||||
{ id: "cpu" },
|
||||
{ id: "memory" },
|
||||
];
|
||||
expect(deriveEnabledWidgets(slots)).toEqual(["cpu", "memory", "firewall"]);
|
||||
});
|
||||
|
||||
it("excludes manager card ids (mobile contract: never leak managers)", () => {
|
||||
const slots = [
|
||||
{ id: "cpu" },
|
||||
{ id: "service_manager" },
|
||||
{ id: "log_viewer" },
|
||||
{ id: "disk" },
|
||||
];
|
||||
const out = deriveEnabledWidgets(slots);
|
||||
expect(out).toEqual(["cpu", "disk"]);
|
||||
for (const id of out) expect(isMetricCardId(id)).toBe(true);
|
||||
});
|
||||
|
||||
it("output is always a subset of the 10 known WidgetTypes", () => {
|
||||
const slots = METRIC_CARD_IDS.map((id) => ({ id })).concat([
|
||||
{ id: "user_manager" } as { id: (typeof METRIC_CARD_IDS)[number] },
|
||||
{ id: "bogus" } as { id: (typeof METRIC_CARD_IDS)[number] },
|
||||
]);
|
||||
const out = deriveEnabledWidgets(slots);
|
||||
expect(out).toEqual(METRIC_CARD_IDS);
|
||||
expect(out.length).toBe(METRIC_CARD_IDS.length);
|
||||
});
|
||||
|
||||
it("empty slots -> empty widgets", () => {
|
||||
expect(deriveEnabledWidgets([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("defaultLayoutFromWidgets", () => {
|
||||
it("builds slots in canonical order with dense ordering", () => {
|
||||
const layout = defaultLayoutFromWidgets(["disk", "cpu", "memory"]);
|
||||
expect(layout.slots.map((s) => s.id)).toEqual(["cpu", "memory", "disk"]);
|
||||
expect(layout.slots.map((s) => s.order)).toEqual([0, 1, 2]);
|
||||
expect(layout.columns).toBe(3);
|
||||
});
|
||||
|
||||
it("ignores unknown widget ids", () => {
|
||||
const layout = defaultLayoutFromWidgets(["cpu", "nope", "service_manager"]);
|
||||
expect(layout.slots.map((s) => s.id)).toEqual(["cpu"]);
|
||||
});
|
||||
|
||||
it("assigns valid colSpans (1..3)", () => {
|
||||
const layout = defaultLayoutFromWidgets([...METRIC_CARD_IDS]);
|
||||
for (const s of layout.slots) {
|
||||
expect([1, 2, 3]).toContain(s.colSpan);
|
||||
}
|
||||
});
|
||||
|
||||
it("round-trips: deriveEnabledWidgets(defaultLayout) === input order", () => {
|
||||
const layout = defaultLayoutFromWidgets(["ports", "cpu", "firewall"]);
|
||||
expect(deriveEnabledWidgets(layout.slots)).toEqual([
|
||||
"cpu",
|
||||
"ports",
|
||||
"firewall",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("card id guards", () => {
|
||||
it("classifies metric vs manager ids", () => {
|
||||
expect(isMetricCardId("cpu")).toBe(true);
|
||||
expect(isMetricCardId("service_manager")).toBe(false);
|
||||
expect(isManagerCardId("service_manager")).toBe(true);
|
||||
expect(isManagerCardId("cpu")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
host: null as Record<string, unknown> | null,
|
||||
hasAccess: true,
|
||||
isAdminBypass: false,
|
||||
overrideCredentialId: null as number | null,
|
||||
credentials: new Map<string, Record<string, unknown>>(),
|
||||
sharedSecret: null as Record<string, unknown> | null,
|
||||
auditCalls: [] as Record<string, unknown>[],
|
||||
}));
|
||||
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentHostResolutionRepository: () => ({
|
||||
findHostOwnerId: async () => (state.host?.userId as string) ?? null,
|
||||
findHostById: async () => (state.host ? { ...state.host } : null),
|
||||
findOverrideCredentialId: async () => state.overrideCredentialId,
|
||||
findCredentialByIdForUser: async (credentialId: number, userId: string) =>
|
||||
state.credentials.get(`${credentialId}:${userId}`) ?? null,
|
||||
}),
|
||||
createCurrentVaultProfileRepository: () => ({
|
||||
findById: async () => null,
|
||||
}),
|
||||
createCurrentUserRepository: () => ({
|
||||
findById: async (userId: string) => ({ id: userId, username: userId }),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/audit-logger.js", () => ({
|
||||
logAudit: async (params: Record<string, unknown>) => {
|
||||
state.auditCalls.push(params);
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/permission-manager.js", () => ({
|
||||
PermissionManager: {
|
||||
getInstance: () => ({
|
||||
canAccessHost: async () => ({
|
||||
hasAccess: state.hasAccess,
|
||||
isAdminBypass: state.isAdminBypass,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/shared-host-secrets-manager.js", () => ({
|
||||
SharedHostSecretsManager: {
|
||||
getInstance: () => ({
|
||||
getSecretForUser: async () => state.sharedSecret,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/logger.js", () => ({
|
||||
logger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { resolveHostById } from "../../hosts/host-resolver.js";
|
||||
|
||||
function baseHost(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 42,
|
||||
userId: "owner",
|
||||
name: "prod",
|
||||
ip: "10.0.0.42",
|
||||
port: 22,
|
||||
username: "root",
|
||||
authType: "password",
|
||||
password: "owner-secret",
|
||||
key: null,
|
||||
keyPassword: null,
|
||||
keyType: null,
|
||||
credentialId: null,
|
||||
vaultProfileId: null,
|
||||
sudoPassword: "owner-sudo",
|
||||
autostartPassword: "auto-pass",
|
||||
autostartKey: null,
|
||||
autostartKeyPassword: null,
|
||||
jumpHosts: null,
|
||||
tunnelConnections: null,
|
||||
statsConfig: null,
|
||||
terminalConfig: null,
|
||||
socks5ProxyChain: null,
|
||||
quickActions: null,
|
||||
overrideCredentialUsername: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
state.host = baseHost();
|
||||
state.hasAccess = true;
|
||||
state.isAdminBypass = false;
|
||||
state.overrideCredentialId = null;
|
||||
state.credentials.clear();
|
||||
state.sharedSecret = null;
|
||||
state.auditCalls = [];
|
||||
});
|
||||
|
||||
describe("resolveHostById", () => {
|
||||
it("returns null when access is denied", async () => {
|
||||
state.hasAccess = false;
|
||||
expect(await resolveHostById(42, "stranger")).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves the owner's credential on the owner path", async () => {
|
||||
// Empty host username so the credential's username is used as fallback.
|
||||
state.host = baseHost({
|
||||
authType: "credential",
|
||||
credentialId: 9,
|
||||
username: "",
|
||||
});
|
||||
state.credentials.set("9:owner", {
|
||||
id: 9,
|
||||
username: "cred-user",
|
||||
authType: "key",
|
||||
password: null,
|
||||
privateKey: "PRIVATE-KEY",
|
||||
key: null,
|
||||
keyPassword: "kp",
|
||||
keyType: "ssh-ed25519",
|
||||
certPublicKey: null,
|
||||
});
|
||||
|
||||
const host = (await resolveHostById(42, "owner")) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(host.key).toBe("PRIVATE-KEY");
|
||||
expect(host.username).toBe("cred-user");
|
||||
expect(host.authType).toBe("key");
|
||||
expect(host.sudoPassword).toBe("owner-sudo");
|
||||
});
|
||||
|
||||
it("uses the share snapshot for a non-owner and strips owner-only secrets", async () => {
|
||||
state.host = baseHost({ username: "" });
|
||||
state.sharedSecret = {
|
||||
username: "shared-user",
|
||||
authType: "password",
|
||||
password: "shared-pass",
|
||||
};
|
||||
|
||||
const host = (await resolveHostById(42, "recipient")) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(host.password).toBe("shared-pass");
|
||||
expect(host.username).toBe("shared-user");
|
||||
expect(host.sudoPassword).toBeNull();
|
||||
expect(host.autostartPassword).toBeNull();
|
||||
});
|
||||
|
||||
it("prefers the recipient's override credential over the snapshot", async () => {
|
||||
state.host = baseHost({ username: "" });
|
||||
state.overrideCredentialId = 5;
|
||||
state.credentials.set("5:recipient", {
|
||||
id: 5,
|
||||
username: "my-user",
|
||||
authType: "password",
|
||||
password: "my-pass",
|
||||
privateKey: null,
|
||||
key: null,
|
||||
keyPassword: null,
|
||||
keyType: null,
|
||||
});
|
||||
state.sharedSecret = {
|
||||
username: "shared-user",
|
||||
authType: "password",
|
||||
password: "shared-pass",
|
||||
};
|
||||
|
||||
const host = (await resolveHostById(42, "recipient")) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(host.password).toBe("my-pass");
|
||||
expect(host.username).toBe("my-user");
|
||||
});
|
||||
|
||||
it("denies a non-owner when a secret-bearing host has no snapshot", async () => {
|
||||
expect(await resolveHostById(42, "recipient")).toBeNull();
|
||||
});
|
||||
|
||||
it("lets a non-owner through on secret-less auth types without a snapshot", async () => {
|
||||
state.host = baseHost({ authType: "none", password: null });
|
||||
const host = await resolveHostById(42, "recipient");
|
||||
expect(host).not.toBeNull();
|
||||
});
|
||||
|
||||
it("resolves an admin bypass like the owner, keeping owner-only secrets", async () => {
|
||||
state.isAdminBypass = true;
|
||||
state.host = baseHost({
|
||||
authType: "credential",
|
||||
credentialId: 9,
|
||||
username: "",
|
||||
password: null,
|
||||
});
|
||||
state.credentials.set("9:owner", {
|
||||
id: 9,
|
||||
username: "cred-user",
|
||||
authType: "key",
|
||||
password: null,
|
||||
privateKey: "OWNER-PRIVATE-KEY",
|
||||
key: null,
|
||||
keyPassword: "kp",
|
||||
keyType: "ssh-ed25519",
|
||||
certPublicKey: null,
|
||||
});
|
||||
|
||||
const host = (await resolveHostById(42, "adminUser")) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
// Owner credential resolved (not the share snapshot path).
|
||||
expect(host.key).toBe("OWNER-PRIVATE-KEY");
|
||||
expect(host.username).toBe("cred-user");
|
||||
// Owner-only operational secrets are NOT stripped for the admin.
|
||||
expect(host.sudoPassword).toBe("owner-sudo");
|
||||
expect(host.autostartPassword).toBe("auto-pass");
|
||||
});
|
||||
|
||||
it("audits every admin-bypass host resolution", async () => {
|
||||
state.isAdminBypass = true;
|
||||
await resolveHostById(42, "adminUser");
|
||||
expect(state.auditCalls).toHaveLength(1);
|
||||
expect(state.auditCalls[0]).toMatchObject({
|
||||
action: "admin_connect_host",
|
||||
resourceType: "host",
|
||||
resourceId: "42",
|
||||
userId: "adminUser",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not audit an ordinary owner resolution", async () => {
|
||||
await resolveHostById(42, "owner");
|
||||
expect(state.auditCalls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,440 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
buildSudoCommand,
|
||||
shellSingleQuote,
|
||||
} from "../../../hosts/metrics/managers/exec-elevated.js";
|
||||
import { parsePlatformProbe } from "../../../hosts/metrics/managers/platform.js";
|
||||
import {
|
||||
isValidSystemdUnit,
|
||||
isValidPid,
|
||||
isValidPort,
|
||||
isValidPackageName,
|
||||
isValidUsername,
|
||||
isValidDomain,
|
||||
isValidDnsProvider,
|
||||
isValidSignal,
|
||||
isValidServiceAction,
|
||||
isAllowedPath,
|
||||
} from "../../../hosts/metrics/managers/validation.js";
|
||||
import {
|
||||
parseServiceList,
|
||||
buildServiceActionCommand,
|
||||
} from "../../../hosts/metrics/managers/services.js";
|
||||
import {
|
||||
parseProcessList,
|
||||
buildKillCommand,
|
||||
} from "../../../hosts/metrics/managers/processes.js";
|
||||
import {
|
||||
parseDfMounts,
|
||||
parseTopMemory,
|
||||
} from "../../../hosts/metrics/managers/simple-reads.js";
|
||||
import {
|
||||
parseCrontab,
|
||||
serializeCrontab,
|
||||
isValidCronSchedule,
|
||||
buildApplyCrontabCommand,
|
||||
} from "../../../hosts/metrics/managers/cron.js";
|
||||
import {
|
||||
buildPackageActionCommand,
|
||||
parseUpgradable,
|
||||
buildListUpgradableCommand,
|
||||
} from "../../../hosts/metrics/managers/packages.js";
|
||||
import {
|
||||
buildIssueCommand,
|
||||
buildRenewCommand,
|
||||
buildRevokeCommand,
|
||||
isValidCertName,
|
||||
parseCertbotCertificates,
|
||||
} from "../../../hosts/metrics/managers/ssl.js";
|
||||
import {
|
||||
buildIptablesRuleCommand,
|
||||
buildNftRuleCommand,
|
||||
} from "../../../hosts/metrics/managers/firewall.js";
|
||||
import {
|
||||
parsePasswd,
|
||||
parseSudoers,
|
||||
} from "../../../hosts/metrics/managers/users.js";
|
||||
import {
|
||||
buildHealthCheckCommand,
|
||||
parseHealthResult,
|
||||
} from "../../../hosts/metrics/managers/health.js";
|
||||
import {
|
||||
buildTailCommand,
|
||||
clampLines,
|
||||
} from "../../../hosts/metrics/managers/logs.js";
|
||||
|
||||
describe("exec-elevated", () => {
|
||||
it("single-quotes and escapes for the shell", () => {
|
||||
expect(shellSingleQuote("abc")).toBe("'abc'");
|
||||
expect(shellSingleQuote("a'b")).toBe(`'a'"'"'b'`);
|
||||
});
|
||||
it("builds the sudo -S pipeline wrapping the command in sh -c with a success marker", () => {
|
||||
expect(buildSudoCommand("systemctl restart nginx", "pw")).toBe(
|
||||
`echo 'pw' | sudo -S -p '' sh -c 'echo __TX_SUDO_OK__; systemctl restart nginx'`,
|
||||
);
|
||||
});
|
||||
it("does not merge stderr into stdout (no 2>&1)", () => {
|
||||
expect(buildSudoCommand("id", "pw")).not.toContain("2>&1");
|
||||
});
|
||||
it("escapes a password containing a quote", () => {
|
||||
expect(buildSudoCommand("id", "p'w")).toContain(`echo 'p'"'"'w'`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("platform probe parsing", () => {
|
||||
it("parses capabilities and prefers dnf over yum", () => {
|
||||
const out = [
|
||||
"systemd=1",
|
||||
"apt=0",
|
||||
"dnf=1",
|
||||
"yum=1",
|
||||
"pacman=0",
|
||||
"certbot=1",
|
||||
"acmesh=0",
|
||||
"docker=1",
|
||||
"os=Fedora Linux 40",
|
||||
].join("\n");
|
||||
const p = parsePlatformProbe(out);
|
||||
expect(p.hasSystemd).toBe(true);
|
||||
expect(p.pkg).toBe("dnf");
|
||||
expect(p.hasCertbot).toBe(true);
|
||||
expect(p.hasAcmeSh).toBe(false);
|
||||
expect(p.hasDocker).toBe(true);
|
||||
expect(p.osPrettyName).toBe("Fedora Linux 40");
|
||||
});
|
||||
it("picks apt when present", () => {
|
||||
expect(parsePlatformProbe("apt=1\ndnf=1").pkg).toBe("apt");
|
||||
});
|
||||
});
|
||||
|
||||
describe("validation (injection defense)", () => {
|
||||
it("systemd units", () => {
|
||||
expect(isValidSystemdUnit("nginx.service")).toBe(true);
|
||||
expect(isValidSystemdUnit("ssh.socket")).toBe(true);
|
||||
expect(isValidSystemdUnit("nginx.service; rm -rf /")).toBe(false);
|
||||
expect(isValidSystemdUnit("nginx")).toBe(false);
|
||||
});
|
||||
it("pids", () => {
|
||||
expect(isValidPid(123)).toBe(true);
|
||||
expect(isValidPid("123")).toBe(true);
|
||||
expect(isValidPid(0)).toBe(false);
|
||||
expect(isValidPid("1; reboot")).toBe(false);
|
||||
expect(isValidPid(-5)).toBe(false);
|
||||
});
|
||||
it("ports", () => {
|
||||
expect(isValidPort(443)).toBe(true);
|
||||
expect(isValidPort(0)).toBe(false);
|
||||
expect(isValidPort(70000)).toBe(false);
|
||||
});
|
||||
it("package names", () => {
|
||||
expect(isValidPackageName("nginx")).toBe(true);
|
||||
expect(isValidPackageName("lib-foo.bar+1")).toBe(true);
|
||||
expect(isValidPackageName("nginx && curl evil")).toBe(false);
|
||||
expect(isValidPackageName("-rf")).toBe(false);
|
||||
});
|
||||
it("usernames and domains", () => {
|
||||
expect(isValidUsername("deploy")).toBe(true);
|
||||
expect(isValidUsername("root; rm")).toBe(false);
|
||||
expect(isValidDomain("example.com")).toBe(true);
|
||||
expect(isValidDomain("*.example.com")).toBe(true);
|
||||
expect(isValidDomain("ex ample.com")).toBe(false);
|
||||
expect(isValidDomain("a;b.com")).toBe(false);
|
||||
});
|
||||
it("dns providers, signals, service actions", () => {
|
||||
expect(isValidDnsProvider("cloudflare")).toBe(true);
|
||||
expect(isValidDnsProvider("cf; rm")).toBe(false);
|
||||
expect(isValidSignal("KILL")).toBe(true);
|
||||
expect(isValidSignal("BOOM")).toBe(false);
|
||||
expect(isValidServiceAction("restart")).toBe(true);
|
||||
expect(isValidServiceAction("destroy")).toBe(false);
|
||||
});
|
||||
it("path allowlist rejects traversal and out-of-allowlist", () => {
|
||||
expect(isAllowedPath("/var/log/syslog", ["/var/log"])).toBe(true);
|
||||
expect(isAllowedPath("/var/log/../../etc/passwd", ["/var/log"])).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isAllowedPath("/etc/passwd", ["/var/log"])).toBe(false);
|
||||
expect(isAllowedPath("relative/path", ["/var/log"])).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("services", () => {
|
||||
it("parses list-units --plain", () => {
|
||||
const out =
|
||||
"nginx.service loaded active running A high performance web server\n" +
|
||||
"ssh.service loaded active running OpenBSD Secure Shell server\n" +
|
||||
"cron.service loaded inactive dead Regular background program";
|
||||
const rows = parseServiceList(out);
|
||||
expect(rows).toHaveLength(3);
|
||||
expect(rows[0]).toMatchObject({ unit: "nginx.service", active: "active" });
|
||||
expect(rows[2].active).toBe("inactive");
|
||||
});
|
||||
it("builds action command", () => {
|
||||
expect(buildServiceActionCommand("nginx.service", "restart")).toBe(
|
||||
"systemctl restart nginx.service",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("processes", () => {
|
||||
it("parses ps output", () => {
|
||||
const out =
|
||||
"1234 1 root 12.5 3.2 45000 S /usr/bin/node node server.js\n" +
|
||||
"5678 1234 deploy 0.0 1.1 12000 Sl bash -bash";
|
||||
const rows = parseProcessList(out);
|
||||
expect(rows[0]).toMatchObject({
|
||||
pid: 1234,
|
||||
user: "root",
|
||||
cpu: 12.5,
|
||||
command: "/usr/bin/node",
|
||||
});
|
||||
expect(rows[1].pid).toBe(5678);
|
||||
});
|
||||
it("builds kill command", () => {
|
||||
expect(buildKillCommand(42, "TERM")).toBe("kill -TERM 42");
|
||||
});
|
||||
});
|
||||
|
||||
describe("simple reads", () => {
|
||||
it("parses df -Pk and skips tmpfs", () => {
|
||||
const out =
|
||||
"/dev/sda1 100000 40000 60000 40% /\n" +
|
||||
"tmpfs 8000 0 8000 0% /dev/shm\n" +
|
||||
"/dev/sdb1 200000 100000 100000 50% /data";
|
||||
const mounts = parseDfMounts(out);
|
||||
expect(mounts).toHaveLength(2);
|
||||
expect(mounts[0].mount).toBe("/");
|
||||
expect(mounts[1].usePct).toBe(50);
|
||||
});
|
||||
it("parses top by memory", () => {
|
||||
const rows = parseTopMemory("1234 root 5.5 50000 node");
|
||||
expect(rows[0]).toMatchObject({ pid: 1234, mem: 5.5, command: "node" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("cron", () => {
|
||||
it("parses enabled and toggled entries", () => {
|
||||
const out = "0 2 * * * /backup.sh\n# 30 4 * * * /old.sh\nPATH=/usr/bin";
|
||||
const entries = parseCrontab(out);
|
||||
expect(entries).toHaveLength(2);
|
||||
expect(entries[0]).toMatchObject({ enabled: true, schedule: "0 2 * * *" });
|
||||
expect(entries[1].enabled).toBe(false);
|
||||
});
|
||||
it("validates schedules", () => {
|
||||
expect(isValidCronSchedule("0 2 * * *")).toBe(true);
|
||||
expect(isValidCronSchedule("@daily")).toBe(true);
|
||||
expect(isValidCronSchedule("not a schedule")).toBe(false);
|
||||
});
|
||||
it("serializes (commenting disabled entries) and round-trips", () => {
|
||||
const body = serializeCrontab([
|
||||
{ raw: "", enabled: true, schedule: "0 2 * * *", command: "/a.sh" },
|
||||
{ raw: "", enabled: false, schedule: "@daily", command: "/b.sh" },
|
||||
]);
|
||||
expect(body).toBe("0 2 * * * /a.sh\n# @daily /b.sh\n");
|
||||
const reparsed = parseCrontab(body);
|
||||
expect(reparsed[0].enabled).toBe(true);
|
||||
expect(reparsed[1].enabled).toBe(false);
|
||||
});
|
||||
it("builds apply command piping into crontab -", () => {
|
||||
expect(buildApplyCrontabCommand("x\n")).toBe(
|
||||
`printf '%s' 'x\n' | crontab -`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("packages", () => {
|
||||
it("builds per-distro commands", () => {
|
||||
expect(buildPackageActionCommand("apt", "install", "nginx")).toContain(
|
||||
"apt-get -y install nginx",
|
||||
);
|
||||
expect(buildPackageActionCommand("pacman", "upgrade-all")).toBe(
|
||||
"pacman -Syu --noconfirm",
|
||||
);
|
||||
expect(buildPackageActionCommand(null, "install", "x")).toBeNull();
|
||||
});
|
||||
it("lists per distro", () => {
|
||||
expect(buildListUpgradableCommand("apt")).toContain(
|
||||
"apt list --upgradable",
|
||||
);
|
||||
expect(buildListUpgradableCommand(null)).toBeNull();
|
||||
});
|
||||
it("parses apt upgradable", () => {
|
||||
const out =
|
||||
"nginx/focal-updates 1.18.0-2 amd64 [upgradable from: 1.18.0-1]";
|
||||
const pkgs = parseUpgradable("apt", out);
|
||||
expect(pkgs[0]).toMatchObject({
|
||||
name: "nginx",
|
||||
newVersion: "1.18.0-2",
|
||||
currentVersion: "1.18.0-1",
|
||||
});
|
||||
});
|
||||
it("parses pacman upgradable", () => {
|
||||
const pkgs = parseUpgradable("pacman", "linux 6.1 -> 6.2");
|
||||
expect(pkgs[0]).toMatchObject({ name: "linux", newVersion: "6.2" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("ssl (dual client)", () => {
|
||||
it("builds certbot issue for http + dns", () => {
|
||||
expect(
|
||||
buildIssueCommand({
|
||||
client: "certbot",
|
||||
domains: ["a.com"],
|
||||
challenge: "http-standalone",
|
||||
}),
|
||||
).toContain(
|
||||
"certbot certonly --non-interactive --agree-tos --standalone -d 'a.com'",
|
||||
);
|
||||
expect(
|
||||
buildIssueCommand({
|
||||
client: "certbot",
|
||||
domains: ["a.com"],
|
||||
challenge: "dns",
|
||||
dnsProvider: "cloudflare",
|
||||
}),
|
||||
).toContain("--dns-cloudflare");
|
||||
});
|
||||
it("builds acme.sh issue", () => {
|
||||
const cmd = buildIssueCommand({
|
||||
client: "acme.sh",
|
||||
domains: ["a.com", "b.com"],
|
||||
challenge: "dns",
|
||||
dnsProvider: "cf",
|
||||
});
|
||||
expect(cmd).toContain("--issue --dns dns_cf");
|
||||
expect(cmd).toContain("-d 'a.com'");
|
||||
expect(cmd).toContain("-d 'b.com'");
|
||||
});
|
||||
it("builds renew per client", () => {
|
||||
expect(buildRenewCommand("certbot", true)).toBe("certbot renew --dry-run");
|
||||
expect(buildRenewCommand("acme.sh", false)).toContain("--renew-all");
|
||||
});
|
||||
it("builds revoke per client", () => {
|
||||
expect(buildRevokeCommand("certbot", "example.com")).toBe(
|
||||
"certbot revoke --non-interactive --cert-name 'example.com' --delete-after-revoke",
|
||||
);
|
||||
const acme = buildRevokeCommand("acme.sh", "example.com");
|
||||
expect(acme).toContain("--revoke -d 'example.com'");
|
||||
expect(acme).toContain("--remove -d 'example.com'");
|
||||
});
|
||||
it("validates certificate names (rejects shell metachars)", () => {
|
||||
expect(isValidCertName("example.com")).toBe(true);
|
||||
expect(isValidCertName("example.com-0001")).toBe(true);
|
||||
expect(isValidCertName("*.example.com")).toBe(true);
|
||||
expect(isValidCertName("a.com; rm -rf /")).toBe(false);
|
||||
expect(isValidCertName("")).toBe(false);
|
||||
expect(isValidCertName(undefined)).toBe(false);
|
||||
});
|
||||
it("parses certbot certificates", () => {
|
||||
const out = [
|
||||
"Found the following certs:",
|
||||
" Certificate Name: example.com",
|
||||
" Domains: example.com www.example.com",
|
||||
" Expiry Date: 2026-09-01 12:00:00+00:00 (VALID: 80 days)",
|
||||
" Certificate Path: /etc/letsencrypt/live/example.com/fullchain.pem",
|
||||
].join("\n");
|
||||
const certs = parseCertbotCertificates(out);
|
||||
expect(certs[0]).toMatchObject({
|
||||
name: "example.com",
|
||||
client: "certbot",
|
||||
});
|
||||
expect(certs[0].domains).toContain("www.example.com");
|
||||
});
|
||||
});
|
||||
|
||||
describe("firewall", () => {
|
||||
it("builds iptables add/delete on INPUT only", () => {
|
||||
expect(
|
||||
buildIptablesRuleCommand("add", {
|
||||
protocol: "tcp",
|
||||
port: 443,
|
||||
target: "ACCEPT",
|
||||
}),
|
||||
).toBe("iptables -A INPUT -p tcp --dport 443 -j ACCEPT");
|
||||
expect(
|
||||
buildIptablesRuleCommand("delete", {
|
||||
protocol: "udp",
|
||||
port: 53,
|
||||
target: "DROP",
|
||||
}),
|
||||
).toBe("iptables -D INPUT -p udp --dport 53 -j DROP");
|
||||
});
|
||||
it("builds nft rules", () => {
|
||||
expect(
|
||||
buildNftRuleCommand("add", {
|
||||
protocol: "tcp",
|
||||
port: 22,
|
||||
target: "ACCEPT",
|
||||
}),
|
||||
).toContain("add rule inet filter input tcp dport 22 accept");
|
||||
});
|
||||
});
|
||||
|
||||
describe("users", () => {
|
||||
it("parses passwd for human users only", () => {
|
||||
const out =
|
||||
"root:x:0:0:root:/root:/bin/bash\n" +
|
||||
"deploy:x:1000:1000:Deploy:/home/deploy:/bin/bash\n" +
|
||||
"nobody:x:65534:65534:nobody:/:/usr/sbin/nologin";
|
||||
const users = parsePasswd(out);
|
||||
expect(users).toHaveLength(1);
|
||||
expect(users[0].name).toBe("deploy");
|
||||
});
|
||||
it("parses sudoers membership", () => {
|
||||
const out = "sudo:x:27:deploy,alice\nwheel:x:10:bob";
|
||||
expect(parseSudoers(out).sort()).toEqual(["alice", "bob", "deploy"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("health checks", () => {
|
||||
it("builds tcp and http commands", () => {
|
||||
const tcp = buildHealthCheckCommand({
|
||||
id: "1",
|
||||
name: "ssh",
|
||||
type: "tcp",
|
||||
target: "localhost",
|
||||
port: 22,
|
||||
});
|
||||
expect(tcp).toContain("/dev/tcp/");
|
||||
const http = buildHealthCheckCommand({
|
||||
id: "2",
|
||||
name: "web",
|
||||
type: "http",
|
||||
target: "example.com",
|
||||
path: "/health",
|
||||
});
|
||||
expect(http).toContain("curl -s -o /dev/null");
|
||||
expect(http).toContain("http://example.com/health");
|
||||
});
|
||||
it("parses tcp and http results", () => {
|
||||
const tcp = parseHealthResult(
|
||||
{ id: "1", name: "ssh", type: "tcp", target: "h", port: 22 },
|
||||
"ok 12",
|
||||
);
|
||||
expect(tcp).toMatchObject({ ok: true, latencyMs: 12 });
|
||||
const http = parseHealthResult(
|
||||
{ id: "2", name: "web", type: "http", target: "h" },
|
||||
"200 0.045",
|
||||
);
|
||||
expect(http).toMatchObject({ ok: true, latencyMs: 45 });
|
||||
const bad = parseHealthResult(
|
||||
{ id: "3", name: "web", type: "http", target: "h" },
|
||||
"500 0.01",
|
||||
);
|
||||
expect(bad.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("logs", () => {
|
||||
it("clamps line counts", () => {
|
||||
expect(clampLines(50)).toBe(50);
|
||||
expect(clampLines(99999)).toBe(2000);
|
||||
expect(clampLines("abc")).toBe(200);
|
||||
expect(clampLines(0)).toBe(1);
|
||||
});
|
||||
it("builds a quoted tail command without suppressing stderr", () => {
|
||||
expect(buildTailCommand("/var/log/syslog", 100)).toBe(
|
||||
"tail -n 100 '/var/log/syslog'",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { Client } from "ssh2";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import {
|
||||
supportsMetrics,
|
||||
isTcpPingEnabled,
|
||||
tcpPingThroughJumpHost,
|
||||
} from "../../../hosts/metrics/helpers.js";
|
||||
import { createConnectionLog } from "../../../hosts/connection-log.js";
|
||||
|
||||
describe("supportsMetrics", () => {
|
||||
it("supports plain ssh hosts", () => {
|
||||
expect(
|
||||
supportsMetrics({ connectionType: "ssh", authType: "password" }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("defaults missing connectionType to ssh", () => {
|
||||
expect(supportsMetrics({ authType: "key" })).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects non-ssh connection types", () => {
|
||||
expect(supportsMetrics({ connectionType: "rdp" })).toBe(false);
|
||||
expect(supportsMetrics({ connectionType: "vnc" })).toBe(false);
|
||||
expect(supportsMetrics({ connectionType: "telnet" })).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects ssh hosts that cannot run shell commands", () => {
|
||||
expect(supportsMetrics({ connectionType: "ssh", authType: "none" })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(supportsMetrics({ connectionType: "ssh", authType: "opkssh" })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTcpPingEnabled", () => {
|
||||
it("is enabled when status checks are on and tcp ping is not disabled", () => {
|
||||
expect(
|
||||
isTcpPingEnabled({ statusCheckEnabled: true, disableTcpPing: false }),
|
||||
).toBe(true);
|
||||
expect(isTcpPingEnabled({ statusCheckEnabled: true })).toBe(true);
|
||||
});
|
||||
|
||||
it("is disabled when status checks are off", () => {
|
||||
expect(isTcpPingEnabled({ statusCheckEnabled: false })).toBe(false);
|
||||
});
|
||||
|
||||
it("is disabled when tcp ping is explicitly disabled", () => {
|
||||
expect(
|
||||
isTcpPingEnabled({ statusCheckEnabled: true, disableTcpPing: true }),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createConnectionLog", () => {
|
||||
it("builds a log entry without id/timestamp", () => {
|
||||
const entry = createConnectionLog("info", "connection", "Connecting", {
|
||||
hostId: 1,
|
||||
});
|
||||
expect(entry).toEqual({
|
||||
type: "info",
|
||||
stage: "connection",
|
||||
message: "Connecting",
|
||||
details: { hostId: 1 },
|
||||
});
|
||||
expect("id" in entry).toBe(false);
|
||||
expect("timestamp" in entry).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tcpPingThroughJumpHost", () => {
|
||||
it("reports the final destination online when forwarding succeeds", async () => {
|
||||
const stream = { destroy: vi.fn() };
|
||||
const jumpClient = {
|
||||
end: vi.fn(),
|
||||
forwardOut: vi.fn((_src, _srcPort, host, port, callback) => {
|
||||
expect(host).toBe("private.example");
|
||||
expect(port).toBe(22);
|
||||
callback(undefined, stream);
|
||||
}),
|
||||
} as unknown as Pick<Client, "forwardOut" | "end">;
|
||||
|
||||
await expect(
|
||||
tcpPingThroughJumpHost(jumpClient, "private.example", 22),
|
||||
).resolves.toBe(true);
|
||||
expect(stream.destroy).toHaveBeenCalledOnce();
|
||||
expect(jumpClient.end).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("reports the final destination offline when forwarding fails", async () => {
|
||||
const jumpClient = {
|
||||
end: vi.fn(),
|
||||
forwardOut: vi.fn((_src, _srcPort, _host, _port, callback) => {
|
||||
callback(new Error("Connection refused"));
|
||||
}),
|
||||
} as unknown as Pick<Client, "forwardOut" | "end">;
|
||||
|
||||
await expect(
|
||||
tcpPingThroughJumpHost(jumpClient, "private.example", 22),
|
||||
).resolves.toBe(false);
|
||||
expect(jumpClient.end).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("reports the final destination offline when forwarding times out", async () => {
|
||||
vi.useFakeTimers();
|
||||
const jumpClient = {
|
||||
end: vi.fn(),
|
||||
forwardOut: vi.fn(),
|
||||
} as unknown as Pick<Client, "forwardOut" | "end">;
|
||||
|
||||
const result = tcpPingThroughJumpHost(
|
||||
jumpClient,
|
||||
"private.example",
|
||||
22,
|
||||
5000,
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(5000);
|
||||
|
||||
await expect(result).resolves.toBe(false);
|
||||
expect(jumpClient.end).toHaveBeenCalledOnce();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const execCommand = vi.fn();
|
||||
vi.mock("../../../../hosts/metrics/widgets/common-utils.js", () => ({
|
||||
execCommand: (...args: unknown[]) => execCommand(...args),
|
||||
}));
|
||||
|
||||
import {
|
||||
execElevated,
|
||||
ElevationError,
|
||||
} from "../../../../hosts/metrics/managers/exec-elevated.js";
|
||||
import type { Client } from "ssh2";
|
||||
|
||||
const fakeClient = {} as Client;
|
||||
|
||||
function result(stdout: string, stderr = "", code: number | null = 0) {
|
||||
return { stdout, stderr, code };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
execCommand.mockReset();
|
||||
});
|
||||
|
||||
describe("execElevated (no force)", () => {
|
||||
it("returns the direct result when the command succeeds unprivileged", async () => {
|
||||
execCommand.mockResolvedValueOnce(result("hello", "", 0));
|
||||
const r = await execElevated(fakeClient, "echo hello", "pw");
|
||||
expect(r.usedSudo).toBe(false);
|
||||
expect(r.stdout).toBe("hello");
|
||||
expect(execCommand).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does NOT escalate when stdout merely contains scary words", async () => {
|
||||
// A non-zero exit whose OUTPUT contains 'permission denied' but stderr does
|
||||
// not should be surfaced as-is, never retried under sudo.
|
||||
execCommand.mockResolvedValueOnce(
|
||||
result("log line: permission denied for user foo", "", 1),
|
||||
);
|
||||
const r = await execElevated(fakeClient, "grep denied /tmp/app.log", "pw");
|
||||
expect(r.usedSudo).toBe(false);
|
||||
expect(execCommand).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("escalates when stderr indicates a permission problem", async () => {
|
||||
execCommand
|
||||
.mockResolvedValueOnce(result("", "Permission denied", 1))
|
||||
.mockResolvedValueOnce(result("__TX_SUDO_OK__\nelevated output", "", 0));
|
||||
const r = await execElevated(fakeClient, "cat /etc/shadow", "pw");
|
||||
expect(r.usedSudo).toBe(true);
|
||||
expect(r.stdout).toBe("elevated output");
|
||||
expect(execCommand).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("throws SUDO_REQUIRED when elevation is needed but no password is set", async () => {
|
||||
execCommand.mockResolvedValueOnce(result("", "Permission denied", 1));
|
||||
await expect(
|
||||
execElevated(fakeClient, "cat /etc/shadow", undefined),
|
||||
).rejects.toMatchObject({ code: "SUDO_REQUIRED" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("execElevated (forced)", () => {
|
||||
it("strips the success marker from stdout", async () => {
|
||||
execCommand.mockResolvedValueOnce(
|
||||
result("__TX_SUDO_OK__\nthe real output\n", "", 0),
|
||||
);
|
||||
const r = await execElevated(fakeClient, "id", "pw", { forceSudo: true });
|
||||
expect(r.stdout).toBe("the real output\n");
|
||||
expect(r.usedSudo).toBe(true);
|
||||
});
|
||||
|
||||
it("does NOT throw when command output contains 'incorrect password' but sudo authenticated", async () => {
|
||||
execCommand.mockResolvedValueOnce(
|
||||
result(
|
||||
"__TX_SUDO_OK__\nUser entered an incorrect password earlier",
|
||||
"",
|
||||
0,
|
||||
),
|
||||
);
|
||||
const r = await execElevated(fakeClient, "tail /var/log/auth.log", "pw", {
|
||||
forceSudo: true,
|
||||
});
|
||||
expect(r.usedSudo).toBe(true);
|
||||
expect(r.stdout).toContain("incorrect password");
|
||||
});
|
||||
|
||||
it("throws SUDO_FAILED on a real wrong-password (no marker, sudo stderr)", async () => {
|
||||
execCommand.mockResolvedValueOnce(
|
||||
result("", "sudo: 1 incorrect password attempt", 1),
|
||||
);
|
||||
await expect(
|
||||
execElevated(fakeClient, "id", "wrong", { forceSudo: true }),
|
||||
).rejects.toMatchObject({ code: "SUDO_FAILED" });
|
||||
});
|
||||
|
||||
it("throws NOT_SUDOER when the user is not in sudoers", async () => {
|
||||
execCommand.mockResolvedValueOnce(
|
||||
result("", "deploy is not in the sudoers file.", 1),
|
||||
);
|
||||
await expect(
|
||||
execElevated(fakeClient, "id", "pw", { forceSudo: true }),
|
||||
).rejects.toMatchObject({ code: "NOT_SUDOER" });
|
||||
});
|
||||
|
||||
it("throws SUDO_REQUIRED when forced without a password", async () => {
|
||||
await expect(
|
||||
execElevated(fakeClient, "id", undefined, { forceSudo: true }),
|
||||
).rejects.toBeInstanceOf(ElevationError);
|
||||
expect(execCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
ConcurrentLimiter,
|
||||
HostPollCache,
|
||||
} from "../../../hosts/metrics/state.js";
|
||||
|
||||
describe("ConcurrentLimiter", () => {
|
||||
it("never exceeds max concurrent runners", async () => {
|
||||
const limiter = new ConcurrentLimiter(2);
|
||||
let peak = 0;
|
||||
let current = 0;
|
||||
|
||||
const job = async () => {
|
||||
current += 1;
|
||||
peak = Math.max(peak, current);
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
current -= 1;
|
||||
};
|
||||
|
||||
await Promise.all([
|
||||
limiter.run(job),
|
||||
limiter.run(job),
|
||||
limiter.run(job),
|
||||
limiter.run(job),
|
||||
]);
|
||||
|
||||
expect(peak).toBeLessThanOrEqual(2);
|
||||
expect(limiter.activeCount).toBe(0);
|
||||
expect(limiter.pendingCount).toBe(0);
|
||||
});
|
||||
|
||||
it("runs waiters in FIFO order after a slot frees", async () => {
|
||||
const limiter = new ConcurrentLimiter(1);
|
||||
const order: number[] = [];
|
||||
|
||||
const first = limiter.run(async () => {
|
||||
order.push(1);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
});
|
||||
const second = limiter.run(async () => {
|
||||
order.push(2);
|
||||
});
|
||||
const third = limiter.run(async () => {
|
||||
order.push(3);
|
||||
});
|
||||
|
||||
await Promise.all([first, second, third]);
|
||||
expect(order).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("rejects invalid maxConcurrent", () => {
|
||||
expect(() => new ConcurrentLimiter(0)).toThrow(/maxConcurrent/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("HostPollCache", () => {
|
||||
it("returns cached host within TTL for the same user", () => {
|
||||
const cache = new HostPollCache<{ id: number; name: string }>(60_000);
|
||||
cache.set(1, "user-a", { id: 1, name: "alpha" });
|
||||
expect(cache.get(1, "user-a")).toEqual({ id: 1, name: "alpha" });
|
||||
expect(cache.get(1, "user-b")).toBeNull();
|
||||
});
|
||||
|
||||
it("expires entries after TTL", () => {
|
||||
vi.useFakeTimers();
|
||||
const cache = new HostPollCache<{ id: number }>(1_000);
|
||||
cache.set(7, "u", { id: 7 });
|
||||
expect(cache.get(7, "u")).toEqual({ id: 7 });
|
||||
vi.advanceTimersByTime(1_001);
|
||||
expect(cache.get(7, "u")).toBeNull();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("invalidate drops a host or the whole cache", () => {
|
||||
const cache = new HostPollCache<{ id: number }>(60_000);
|
||||
cache.set(1, "u", { id: 1 });
|
||||
cache.set(2, "u", { id: 2 });
|
||||
cache.invalidate(1);
|
||||
expect(cache.get(1, "u")).toBeNull();
|
||||
expect(cache.get(2, "u")).toEqual({ id: 2 });
|
||||
cache.invalidate();
|
||||
expect(cache.get(2, "u")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
toFixedNum,
|
||||
kibToGiB,
|
||||
} from "../../../../hosts/metrics/widgets/common-utils.js";
|
||||
|
||||
describe("toFixedNum", () => {
|
||||
it("rounds to the requested digit count", () => {
|
||||
expect(toFixedNum(3.14159, 2)).toBe(3.14);
|
||||
expect(toFixedNum(3.14159, 0)).toBe(3);
|
||||
expect(toFixedNum(2.5, 0)).toBe(3);
|
||||
});
|
||||
|
||||
it("defaults to 2 digits", () => {
|
||||
expect(toFixedNum(1.23456)).toBe(1.23);
|
||||
});
|
||||
|
||||
it("returns null for non-finite or non-number input", () => {
|
||||
expect(toFixedNum(null)).toBeNull();
|
||||
expect(toFixedNum(undefined)).toBeNull();
|
||||
expect(toFixedNum(NaN)).toBeNull();
|
||||
expect(toFixedNum(Infinity)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("kibToGiB", () => {
|
||||
it("converts kibibytes to gibibytes", () => {
|
||||
expect(kibToGiB(1024 * 1024)).toBe(1);
|
||||
expect(kibToGiB(0)).toBe(0);
|
||||
expect(kibToGiB(2 * 1024 * 1024)).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { parseCpuLine } from "../../../../hosts/metrics/widgets/cpu-collector.js";
|
||||
|
||||
describe("parseCpuLine", () => {
|
||||
it("parses a standard /proc/stat cpu line", () => {
|
||||
// user nice system idle iowait irq softirq
|
||||
const result = parseCpuLine("cpu 100 0 50 800 30 0 20");
|
||||
expect(result).toBeDefined();
|
||||
// idle = idle(800) + iowait(30)
|
||||
expect(result?.idle).toBe(830);
|
||||
// total = sum of all fields
|
||||
expect(result?.total).toBe(100 + 0 + 50 + 800 + 30 + 0 + 20);
|
||||
});
|
||||
|
||||
it("tolerates leading/trailing whitespace", () => {
|
||||
const result = parseCpuLine(" cpu 1 2 3 4 ");
|
||||
expect(result?.total).toBe(10);
|
||||
expect(result?.idle).toBe(4);
|
||||
});
|
||||
|
||||
it("returns undefined for non-cpu lines", () => {
|
||||
expect(parseCpuLine("cpu0 1 2 3 4")).toBeUndefined();
|
||||
expect(parseCpuLine("intr 12345")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined when there are fewer than 4 numeric fields", () => {
|
||||
expect(parseCpuLine("cpu 1 2 3")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
parseSensorsOutput,
|
||||
parseSysfsThermalOutput,
|
||||
} from "../../../../hosts/metrics/widgets/temperature-collector.js";
|
||||
|
||||
describe("temperature collectors", () => {
|
||||
it("parses sysfs thermal zone output", () => {
|
||||
const result = parseSysfsThermalOutput(
|
||||
"x86_pkg_temp\t51000\nacpitz\t42\nbad\tnope\n",
|
||||
);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ label: "x86_pkg_temp", celsius: 51 },
|
||||
{ label: "acpitz", celsius: 42 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("parses lm-sensors temperature lines", () => {
|
||||
const result = parseSensorsOutput(`
|
||||
coretemp-isa-0000
|
||||
Adapter: ISA adapter
|
||||
Package id 0: +52.0°C (high = +80.0°C, crit = +100.0°C)
|
||||
Core 0: +48.5°C
|
||||
fan1: 1200 RPM
|
||||
`);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ label: "Package id 0", celsius: 52 },
|
||||
{ label: "Core 0", celsius: 48.5 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
isRetriableDnsError,
|
||||
resolveHostForSshConnect,
|
||||
resolveSshConnectConfigHost,
|
||||
shouldResolveBeforeSshConnect,
|
||||
} from "../../hosts/ssh-dns.js";
|
||||
|
||||
describe("SSH DNS resolution", () => {
|
||||
it("retries transient EAI_AGAIN errors before returning an address", async () => {
|
||||
const lookup = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(
|
||||
Object.assign(new Error("try again"), { code: "EAI_AGAIN" }),
|
||||
)
|
||||
.mockResolvedValueOnce({ address: "10.0.0.5", family: 4 });
|
||||
const wait = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
await expect(
|
||||
resolveHostForSshConnect("alp", lookup, [10], wait),
|
||||
).resolves.toEqual({
|
||||
host: "10.0.0.5",
|
||||
resolvedAddress: "10.0.0.5",
|
||||
attempts: 2,
|
||||
});
|
||||
expect(wait).toHaveBeenCalledWith(10);
|
||||
});
|
||||
|
||||
it("does not retry permanent DNS failures", async () => {
|
||||
const error = Object.assign(new Error("not found"), { code: "ENOTFOUND" });
|
||||
const lookup = vi.fn().mockRejectedValue(error);
|
||||
const wait = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
await expect(
|
||||
resolveHostForSshConnect("missing", lookup, [10], wait),
|
||||
).rejects.toBe(error);
|
||||
expect(wait).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips DNS lookup for literal IP addresses", async () => {
|
||||
const lookup = vi.fn();
|
||||
|
||||
await expect(
|
||||
resolveHostForSshConnect("192.0.2.1", lookup),
|
||||
).resolves.toEqual({
|
||||
host: "192.0.2.1",
|
||||
attempts: 0,
|
||||
});
|
||||
expect(lookup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("detects retryable DNS errors by code or message", () => {
|
||||
expect(isRetriableDnsError({ code: "EAI_AGAIN" })).toBe(true);
|
||||
expect(isRetriableDnsError(new Error("getaddrinfo EAI_AGAIN alp"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(isRetriableDnsError({ code: "ENOTFOUND" })).toBe(false);
|
||||
});
|
||||
|
||||
it("only pre-resolves hostnames", () => {
|
||||
expect(shouldResolveBeforeSshConnect("alp")).toBe(true);
|
||||
expect(shouldResolveBeforeSshConnect("127.0.0.1")).toBe(false);
|
||||
expect(shouldResolveBeforeSshConnect("[2001:db8::1]")).toBe(false);
|
||||
});
|
||||
|
||||
it("updates SSH connect config hosts in place", async () => {
|
||||
const lookup = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ address: "10.0.0.6", family: 4 });
|
||||
const config = { host: "alp", port: 22 };
|
||||
|
||||
await expect(resolveSshConnectConfigHost(config, lookup)).resolves.toEqual({
|
||||
host: "10.0.0.6",
|
||||
port: 22,
|
||||
originalHost: "alp",
|
||||
resolvedHost: "10.0.0.6",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
|
||||
const mockAccess = vi.fn();
|
||||
|
||||
vi.mock("fs/promises", () => ({
|
||||
access: mockAccess,
|
||||
}));
|
||||
|
||||
import { resolveAgentSocket } from "../../hosts/terminal-auth-helpers.js";
|
||||
|
||||
describe("resolveAgentSocket", () => {
|
||||
const originalEnv = process.env.SSH_AUTH_SOCK;
|
||||
const originalPlatform = process.platform;
|
||||
|
||||
beforeEach(() => {
|
||||
mockAccess.mockReset();
|
||||
delete process.env.SSH_AUTH_SOCK;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalEnv !== undefined) {
|
||||
process.env.SSH_AUTH_SOCK = originalEnv;
|
||||
} else {
|
||||
delete process.env.SSH_AUTH_SOCK;
|
||||
}
|
||||
Object.defineProperty(process, "platform", { value: originalPlatform });
|
||||
});
|
||||
|
||||
it("uses explicit socket path from terminalConfig over SSH_AUTH_SOCK", async () => {
|
||||
Object.defineProperty(process, "platform", { value: "linux" });
|
||||
process.env.SSH_AUTH_SOCK = "/tmp/ssh-env/agent.123";
|
||||
mockAccess.mockResolvedValue(undefined);
|
||||
|
||||
const result = await resolveAgentSocket({
|
||||
agentSocketPath: "/run/user/1000/gnupg/S.gpg-agent.ssh",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
socketPath: "/run/user/1000/gnupg/S.gpg-agent.ssh",
|
||||
});
|
||||
expect(mockAccess).toHaveBeenCalledWith(
|
||||
"/run/user/1000/gnupg/S.gpg-agent.ssh",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to SSH_AUTH_SOCK when no explicit path is provided", async () => {
|
||||
Object.defineProperty(process, "platform", { value: "linux" });
|
||||
process.env.SSH_AUTH_SOCK = "/tmp/ssh-XXXX/agent.456";
|
||||
mockAccess.mockResolvedValue(undefined);
|
||||
|
||||
const result = await resolveAgentSocket({});
|
||||
|
||||
expect(result).toEqual({ socketPath: "/tmp/ssh-XXXX/agent.456" });
|
||||
});
|
||||
|
||||
it("falls back to SSH_AUTH_SOCK when agentSocketPath is empty string", async () => {
|
||||
Object.defineProperty(process, "platform", { value: "linux" });
|
||||
process.env.SSH_AUTH_SOCK = "/tmp/ssh-XXXX/agent.789";
|
||||
mockAccess.mockResolvedValue(undefined);
|
||||
|
||||
const result = await resolveAgentSocket({ agentSocketPath: " " });
|
||||
|
||||
expect(result).toEqual({ socketPath: "/tmp/ssh-XXXX/agent.789" });
|
||||
});
|
||||
|
||||
it("returns error when neither SSH_AUTH_SOCK nor explicit path is set", async () => {
|
||||
const result = await resolveAgentSocket({});
|
||||
|
||||
expect(result).toHaveProperty("error");
|
||||
expect((result as { error: string }).error).toContain("SSH_AUTH_SOCK");
|
||||
});
|
||||
|
||||
it("returns error when terminalConfig is undefined and SSH_AUTH_SOCK is not set", async () => {
|
||||
const result = await resolveAgentSocket(undefined);
|
||||
|
||||
expect(result).toHaveProperty("error");
|
||||
});
|
||||
|
||||
it("returns error on non-Windows when socket file is missing", async () => {
|
||||
Object.defineProperty(process, "platform", { value: "linux" });
|
||||
process.env.SSH_AUTH_SOCK = "/tmp/missing-agent.sock";
|
||||
mockAccess.mockRejectedValue(new Error("ENOENT"));
|
||||
|
||||
const result = await resolveAgentSocket({});
|
||||
|
||||
expect(result).toHaveProperty("error");
|
||||
expect((result as { error: string }).error).toContain(
|
||||
"/tmp/missing-agent.sock",
|
||||
);
|
||||
});
|
||||
|
||||
it("skips file existence check on Windows", async () => {
|
||||
Object.defineProperty(process, "platform", { value: "win32" });
|
||||
process.env.SSH_AUTH_SOCK = "\\\\.\\pipe\\openssh-ssh-agent";
|
||||
|
||||
const result = await resolveAgentSocket({});
|
||||
|
||||
expect(result).toEqual({
|
||||
socketPath: "\\\\.\\pipe\\openssh-ssh-agent",
|
||||
});
|
||||
expect(mockAccess).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { EventEmitter } from "events";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { performPortKnocking } from "../../hosts/terminal-auth-helpers.js";
|
||||
|
||||
class FakeTcpSocket extends EventEmitter {
|
||||
readonly connect = vi.fn();
|
||||
readonly destroy = vi.fn();
|
||||
}
|
||||
|
||||
describe("performPortKnocking", () => {
|
||||
it("continues through TCP knock errors", async () => {
|
||||
const first = new FakeTcpSocket();
|
||||
const second = new FakeTcpSocket();
|
||||
const wait = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
const knocking = performPortKnocking(
|
||||
"192.0.2.10",
|
||||
[
|
||||
{ port: 1111, protocol: "tcp", delay: 10 },
|
||||
{ port: 2222, protocol: "tcp", delay: 0 },
|
||||
],
|
||||
{
|
||||
createTcpSocket: vi
|
||||
.fn()
|
||||
.mockReturnValueOnce(first)
|
||||
.mockReturnValueOnce(second),
|
||||
wait,
|
||||
},
|
||||
);
|
||||
|
||||
first.emit("error", new Error("closed"));
|
||||
await Promise.resolve();
|
||||
second.emit("connect");
|
||||
await knocking;
|
||||
|
||||
expect(first.connect).toHaveBeenCalledWith(1111, "192.0.2.10");
|
||||
expect(second.connect).toHaveBeenCalledWith(2222, "192.0.2.10");
|
||||
expect(first.destroy).toHaveBeenCalled();
|
||||
expect(second.destroy).toHaveBeenCalled();
|
||||
expect(wait).toHaveBeenCalledWith(10);
|
||||
});
|
||||
|
||||
it("times out TCP knocks that are silently dropped", async () => {
|
||||
const socket = new FakeTcpSocket();
|
||||
const wait = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
await performPortKnocking("192.0.2.10", [{ port: 1111, delay: 0 }], {
|
||||
createTcpSocket: () => socket as never,
|
||||
tcpTimeoutMs: 1,
|
||||
wait,
|
||||
});
|
||||
|
||||
expect(socket.connect).toHaveBeenCalledWith(1111, "192.0.2.10");
|
||||
expect(socket.destroy).toHaveBeenCalled();
|
||||
expect(wait).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// Stub all external imports before loading the module under test
|
||||
const mockCreate = vi.fn().mockResolvedValue({ id: 1 });
|
||||
const mockUpdateEnded = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
vi.mock("../../../database/db/index.js", () => ({
|
||||
getDb: () => ({}),
|
||||
}));
|
||||
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
createCurrentSessionRecordingRepository: () => ({
|
||||
create: mockCreate,
|
||||
updateEnded: mockUpdateEnded,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
sshLogger: {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// Mock individual fs.promises methods via a stub object
|
||||
const mockMkdir = vi.fn().mockResolvedValue(undefined);
|
||||
const mockWriteFile = vi.fn().mockResolvedValue(undefined);
|
||||
const mockAppendFile = vi.fn().mockResolvedValue(undefined);
|
||||
const mockUnlink = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
vi.mock("fs", () => ({
|
||||
default: {
|
||||
promises: {
|
||||
mkdir: mockMkdir,
|
||||
writeFile: mockWriteFile,
|
||||
appendFile: mockAppendFile,
|
||||
readFile: vi.fn(),
|
||||
unlink: mockUnlink,
|
||||
},
|
||||
},
|
||||
promises: {
|
||||
mkdir: mockMkdir,
|
||||
writeFile: mockWriteFile,
|
||||
appendFile: mockAppendFile,
|
||||
readFile: vi.fn(),
|
||||
unlink: mockUnlink,
|
||||
},
|
||||
}));
|
||||
|
||||
const { sessionManager } =
|
||||
await import("../../../hosts/terminal/session-manager.js");
|
||||
|
||||
describe("TerminalSessionManager - session logging", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// Re-apply resolved values after clearAllMocks
|
||||
mockMkdir.mockResolvedValue(undefined);
|
||||
mockWriteFile.mockResolvedValue(undefined);
|
||||
mockCreate.mockResolvedValue({ id: 1 });
|
||||
mockUpdateEnded.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("createSession stores sessionLoggingEnabled=true by default", () => {
|
||||
const id = sessionManager.createSession("u1", 1, "host", 80, 24);
|
||||
const session = sessionManager.getSession(id);
|
||||
expect(session?.sessionLoggingEnabled).toBe(true);
|
||||
sessionManager.destroySession(id);
|
||||
});
|
||||
|
||||
it("createSession stores sessionLoggingEnabled=false when passed", () => {
|
||||
const id = sessionManager.createSession(
|
||||
"u1",
|
||||
1,
|
||||
"host",
|
||||
80,
|
||||
24,
|
||||
undefined,
|
||||
false,
|
||||
);
|
||||
const session = sessionManager.getSession(id);
|
||||
expect(session?.sessionLoggingEnabled).toBe(false);
|
||||
sessionManager.destroySession(id);
|
||||
});
|
||||
|
||||
it("does not write log file when sessionLoggingEnabled=false", async () => {
|
||||
const id = sessionManager.createSession(
|
||||
"u1",
|
||||
1,
|
||||
"host",
|
||||
80,
|
||||
24,
|
||||
undefined,
|
||||
false,
|
||||
);
|
||||
sessionManager.bufferOutput(id, "some output");
|
||||
sessionManager.destroySession(id);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(mockWriteFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes log file and inserts DB row when sessionLoggingEnabled=true", async () => {
|
||||
const id = sessionManager.createSession(
|
||||
"u1",
|
||||
1,
|
||||
"host",
|
||||
80,
|
||||
24,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
sessionManager.bufferOutput(id, "terminal output data");
|
||||
sessionManager.destroySession(id);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(mockWriteFile).toHaveBeenCalledOnce();
|
||||
expect(mockCreate).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("does not write log file when buffer is empty", async () => {
|
||||
const id = sessionManager.createSession(
|
||||
"u1",
|
||||
1,
|
||||
"host",
|
||||
80,
|
||||
24,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
sessionManager.destroySession(id);
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
expect(mockWriteFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("bufferOutput trims old data when exceeding 512KB", () => {
|
||||
const id = sessionManager.createSession(
|
||||
"u1",
|
||||
1,
|
||||
"host",
|
||||
80,
|
||||
24,
|
||||
undefined,
|
||||
false,
|
||||
);
|
||||
const chunk = "x".repeat(300 * 1024);
|
||||
sessionManager.bufferOutput(id, chunk);
|
||||
sessionManager.bufferOutput(id, chunk);
|
||||
const session = sessionManager.getSession(id);
|
||||
expect(session!.outputBufferBytes).toBeLessThanOrEqual(512 * 1024);
|
||||
sessionManager.destroySession(id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { Client } from "ssh2";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
detectTmux,
|
||||
tmuxCommand,
|
||||
withTmuxPath,
|
||||
} from "../../../hosts/tmux/helper.js";
|
||||
|
||||
describe("tmux command path handling", () => {
|
||||
it("adds common non-login shell tmux paths", () => {
|
||||
const command = withTmuxPath("command -v tmux");
|
||||
|
||||
expect(command).toMatch(/^\/bin\/sh -c '/);
|
||||
expect(command).toContain("/opt/homebrew/bin");
|
||||
expect(command).toContain("/usr/local/bin");
|
||||
expect(command).toContain("/opt/bin");
|
||||
expect(command).toContain("/usr/pkg/bin");
|
||||
expect(command).toContain(":$PATH; export PATH; command -v tmux");
|
||||
});
|
||||
|
||||
it("wraps tmux invocations with the same path", () => {
|
||||
expect(tmuxCommand("list-sessions")).toMatch(
|
||||
/^\/bin\/sh -c 'PATH=.*:\$PATH; export PATH; tmux list-sessions'$/,
|
||||
);
|
||||
});
|
||||
|
||||
it("detects suffixed tmux versions without parsing the version number", async () => {
|
||||
const commands: string[] = [];
|
||||
const conn = {
|
||||
exec(command: string, callback: (error: null, stream: never) => void) {
|
||||
commands.push(command);
|
||||
const stream = new EventEmitter() as EventEmitter & {
|
||||
stderr: EventEmitter;
|
||||
};
|
||||
stream.stderr = new EventEmitter();
|
||||
callback(null, stream as never);
|
||||
|
||||
queueMicrotask(() => {
|
||||
if (commands.length === 1) {
|
||||
stream.emit("data", Buffer.from("tmux 3.7b\n"));
|
||||
stream.emit("close", 0);
|
||||
return;
|
||||
}
|
||||
stream.emit("close", 1);
|
||||
});
|
||||
},
|
||||
} as unknown as Client;
|
||||
|
||||
await expect(detectTmux(conn)).resolves.toEqual({
|
||||
available: true,
|
||||
sessions: [],
|
||||
});
|
||||
expect(commands[0]).toContain("tmux -V");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
SEP,
|
||||
parseSessions,
|
||||
parseWindows,
|
||||
parsePanes,
|
||||
parsePsOutput,
|
||||
parseGpuOutput,
|
||||
buildPaneMetrics,
|
||||
attachPanesToWindows,
|
||||
shellEscape,
|
||||
} from "../../../hosts/tmux/monitor-helpers.js";
|
||||
|
||||
function join(...fields: (string | number)[]): string {
|
||||
return fields.join(SEP);
|
||||
}
|
||||
|
||||
describe("parseSessions", () => {
|
||||
it("parses tmux list-sessions output", () => {
|
||||
const output = [
|
||||
join("training", 1760000000, 1760001000, 1),
|
||||
join("lab|with|pipes", 1760000500, 1760002000, 0),
|
||||
].join("\n");
|
||||
|
||||
const sessions = parseSessions(output);
|
||||
expect(sessions).toHaveLength(2);
|
||||
expect(sessions[0]).toEqual({
|
||||
name: "training",
|
||||
created: 1760000000,
|
||||
lastActivity: 1760001000,
|
||||
attachedClients: 1,
|
||||
});
|
||||
// Session names containing "|" survive because SEP is a multi-char token
|
||||
expect(sessions[1].name).toBe("lab|with|pipes");
|
||||
expect(sessions[1].attachedClients).toBe(0);
|
||||
});
|
||||
|
||||
it("returns empty array for empty output", () => {
|
||||
expect(parseSessions("")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseWindows", () => {
|
||||
it("groups windows by session", () => {
|
||||
const output = [
|
||||
join("training", 0, 1, "vim"),
|
||||
join("training", 1, 0, "logs"),
|
||||
join("api", 0, 1, "server"),
|
||||
].join("\n");
|
||||
|
||||
const windows = parseWindows(output);
|
||||
expect(windows.get("training")).toHaveLength(2);
|
||||
expect(windows.get("training")![0]).toMatchObject({
|
||||
index: 0,
|
||||
name: "vim",
|
||||
active: true,
|
||||
});
|
||||
expect(windows.get("api")![0].name).toBe("server");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parsePanes", () => {
|
||||
it("parses full pane lines including free-text fields", () => {
|
||||
const output = join(
|
||||
"training",
|
||||
0,
|
||||
"%3",
|
||||
1,
|
||||
12345,
|
||||
1,
|
||||
120,
|
||||
40,
|
||||
"python",
|
||||
"/home/user/my|dir",
|
||||
"gpu01: train.py",
|
||||
);
|
||||
|
||||
const panes = parsePanes(output);
|
||||
expect(panes).toHaveLength(1);
|
||||
expect(panes[0]).toEqual({
|
||||
sessionName: "training",
|
||||
windowIndex: 0,
|
||||
id: "%3",
|
||||
index: 1,
|
||||
pid: 12345,
|
||||
active: true,
|
||||
width: 120,
|
||||
height: 40,
|
||||
command: "python",
|
||||
path: "/home/user/my|dir",
|
||||
title: "gpu01: train.py",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parsePsOutput", () => {
|
||||
it("parses ps -eo pid,ppid,pcpu,pmem,rss,comm output", () => {
|
||||
const output = [
|
||||
" 1 0 0.0 0.1 1234 systemd",
|
||||
"12345 1 2.5 1.0 50000 bash",
|
||||
"12400 12345 95.3 12.5 800000 python3",
|
||||
"garbage line",
|
||||
].join("\n");
|
||||
|
||||
const procs = parsePsOutput(output);
|
||||
expect(procs).toHaveLength(3);
|
||||
expect(procs[2]).toEqual({
|
||||
pid: 12400,
|
||||
ppid: 12345,
|
||||
cpu: 95.3,
|
||||
mem: 12.5,
|
||||
rss: 800000,
|
||||
comm: "python3",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseGpuOutput", () => {
|
||||
it("parses nvidia-smi csv output and sums per pid", () => {
|
||||
const output = ["12400, 8000", "12400, 2000", "99999, 512"].join("\n");
|
||||
const gpu = parseGpuOutput(output);
|
||||
expect(gpu.get(12400)).toBe(10000);
|
||||
expect(gpu.get(99999)).toBe(512);
|
||||
});
|
||||
|
||||
it("handles empty output (no GPU)", () => {
|
||||
expect(parseGpuOutput("").size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPaneMetrics", () => {
|
||||
const panes = parsePanes(
|
||||
[
|
||||
join("training", 0, "%1", 0, 100, 1, 80, 24, "bash", "/", "t"),
|
||||
join("idle", 0, "%2", 0, 200, 1, 80, 24, "bash", "/", "t"),
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const processes = parsePsOutput(
|
||||
[
|
||||
// pane %1: bash(100) -> python3(110) -> worker(111)
|
||||
" 100 1 0.1 0.1 4000 bash",
|
||||
" 110 100 90.0 10.0 700000 python3",
|
||||
" 111 110 9.5 2.0 100000 dataloader",
|
||||
// pane %2: bash(200) only
|
||||
" 200 1 0.0 0.1 4000 bash",
|
||||
// unrelated process
|
||||
" 300 1 50.0 5.0 200000 chrome",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
it("aggregates descendant trees per pane", () => {
|
||||
const metrics = buildPaneMetrics(panes, processes, new Map());
|
||||
const m1 = metrics.find((m) => m.paneId === "%1")!;
|
||||
expect(m1.processCount).toBe(3);
|
||||
expect(m1.cpuPercent).toBeCloseTo(99.6, 1);
|
||||
expect(m1.memRssKb).toBe(804000);
|
||||
expect(m1.topCommand).toBe("python3");
|
||||
|
||||
const m2 = metrics.find((m) => m.paneId === "%2")!;
|
||||
expect(m2.processCount).toBe(1);
|
||||
expect(m2.cpuPercent).toBe(0);
|
||||
// Unrelated process is never attributed
|
||||
expect(m2.memRssKb).toBe(4000);
|
||||
});
|
||||
|
||||
it("attributes GPU memory through the process tree", () => {
|
||||
const gpu = new Map([
|
||||
[110, 8000],
|
||||
[300, 4000],
|
||||
]);
|
||||
const metrics = buildPaneMetrics(panes, processes, gpu);
|
||||
expect(metrics.find((m) => m.paneId === "%1")!.gpuMemMb).toBe(8000);
|
||||
expect(metrics.find((m) => m.paneId === "%2")!.gpuMemMb).toBe(0);
|
||||
});
|
||||
|
||||
it("handles a pane whose pid is missing from ps output", () => {
|
||||
const orphan = parsePanes(
|
||||
join("gone", 0, "%9", 0, 99999, 0, 80, 24, "bash", "/", "t"),
|
||||
);
|
||||
const metrics = buildPaneMetrics(orphan, processes, new Map());
|
||||
expect(metrics[0].processCount).toBe(0);
|
||||
expect(metrics[0].cpuPercent).toBe(0);
|
||||
expect(metrics[0].topCommand).toBeNull();
|
||||
});
|
||||
|
||||
it("does not loop on cyclic ppid data", () => {
|
||||
const cyclic = parsePsOutput(
|
||||
[" 100 101 1.0 0.1 1000 a", " 101 100 1.0 0.1 1000 b"].join("\n"),
|
||||
);
|
||||
const pane = parsePanes(
|
||||
join("s", 0, "%1", 0, 100, 1, 80, 24, "a", "/", "t"),
|
||||
);
|
||||
const metrics = buildPaneMetrics(pane, cyclic, new Map());
|
||||
expect(metrics[0].processCount).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("attachPanesToWindows", () => {
|
||||
it("places panes into their windows", () => {
|
||||
const windows = parseWindows(
|
||||
[join("s1", 0, 1, "main"), join("s1", 1, 0, "logs")].join("\n"),
|
||||
);
|
||||
const panes = parsePanes(
|
||||
[
|
||||
join("s1", 0, "%1", 0, 100, 1, 80, 24, "bash", "/", "t"),
|
||||
join("s1", 1, "%2", 0, 200, 0, 80, 24, "tail", "/", "t"),
|
||||
join("unknown", 5, "%3", 0, 300, 0, 80, 24, "bash", "/", "t"),
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
attachPanesToWindows(windows, panes);
|
||||
expect(windows.get("s1")![0].panes).toHaveLength(1);
|
||||
expect(windows.get("s1")![0].panes[0].id).toBe("%1");
|
||||
expect(windows.get("s1")![1].panes[0].id).toBe("%2");
|
||||
});
|
||||
});
|
||||
|
||||
describe("shellEscape", () => {
|
||||
it("wraps in single quotes and escapes embedded quotes", () => {
|
||||
expect(shellEscape("simple")).toBe("'simple'");
|
||||
expect(shellEscape("it's")).toBe("'it'\\''s'");
|
||||
expect(shellEscape("$(rm -rf /)")).toBe("'$(rm -rf /)'");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,268 @@
|
||||
import { describe, it, expect, beforeAll, afterEach, vi } from "vitest";
|
||||
import { execFileSync } from "child_process";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import ssh2Pkg from "ssh2";
|
||||
import {
|
||||
generateEphemeralKeyPair,
|
||||
parseCertValidBefore,
|
||||
startVaultOidc,
|
||||
completeVaultOidc,
|
||||
signWithVault,
|
||||
type VaultProfileConfig,
|
||||
} from "../../hosts/vault-signer-core.js";
|
||||
|
||||
const { utils: ssh2Utils } = ssh2Pkg;
|
||||
|
||||
describe("generateEphemeralKeyPair", () => {
|
||||
for (const keyType of [
|
||||
"ssh-ed25519",
|
||||
"ecdsa-sha2-nistp256",
|
||||
"ssh-rsa",
|
||||
] as const) {
|
||||
it(`generates a parseable ${keyType} keypair`, () => {
|
||||
const pair = generateEphemeralKeyPair(keyType);
|
||||
expect(pair.privateKey).toContain("BEGIN OPENSSH PRIVATE KEY");
|
||||
expect(pair.publicKey.split(/\s+/)[0]).toBe(keyType);
|
||||
|
||||
// Both halves must be parseable by the same library that signs/connects.
|
||||
const priv = ssh2Utils.parseKey(pair.privateKey);
|
||||
expect(priv instanceof Error).toBe(false);
|
||||
const pub = ssh2Utils.parseKey(pair.publicKey);
|
||||
expect(pub instanceof Error).toBe(false);
|
||||
});
|
||||
}
|
||||
|
||||
it("defaults to ed25519 for unknown key types", () => {
|
||||
const pair = generateEphemeralKeyPair("nonsense");
|
||||
expect(pair.publicKey.startsWith("ssh-ed25519")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCertValidBefore", () => {
|
||||
let cert = "";
|
||||
let signedAt = 0;
|
||||
let haveSshKeygen = true;
|
||||
|
||||
beforeAll(() => {
|
||||
const dir = mkdtempSync(path.join(os.tmpdir(), "vault-cert-test-"));
|
||||
try {
|
||||
execFileSync("ssh-keygen", [
|
||||
"-t",
|
||||
"ed25519",
|
||||
"-f",
|
||||
`${dir}/ca`,
|
||||
"-N",
|
||||
"",
|
||||
"-q",
|
||||
]);
|
||||
execFileSync("ssh-keygen", [
|
||||
"-t",
|
||||
"ed25519",
|
||||
"-f",
|
||||
`${dir}/user`,
|
||||
"-N",
|
||||
"",
|
||||
"-q",
|
||||
]);
|
||||
signedAt = Math.floor(Date.now() / 1000);
|
||||
execFileSync("ssh-keygen", [
|
||||
"-s",
|
||||
`${dir}/ca`,
|
||||
"-I",
|
||||
"test-id",
|
||||
"-n",
|
||||
"root",
|
||||
"-V",
|
||||
"+60m",
|
||||
`${dir}/user.pub`,
|
||||
]);
|
||||
cert = readFileSync(`${dir}/user-cert.pub`, "utf8").trim();
|
||||
} catch {
|
||||
haveSshKeygen = false;
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("reads valid_before from a real ssh-keygen certificate", () => {
|
||||
if (!haveSshKeygen) {
|
||||
console.warn("ssh-keygen unavailable; skipping real-cert parse test");
|
||||
return;
|
||||
}
|
||||
const validBefore = parseCertValidBefore(cert);
|
||||
// -V +60m => valid_before is roughly signedAt + 3600 (start rounds to minute)
|
||||
expect(validBefore).toBeGreaterThan(signedAt + 3300);
|
||||
expect(validBefore).toBeLessThan(signedAt + 3900);
|
||||
});
|
||||
|
||||
it("returns 0 for malformed input", () => {
|
||||
expect(parseCertValidBefore("")).toBe(0);
|
||||
expect(parseCertValidBefore("not-a-cert")).toBe(0);
|
||||
expect(parseCertValidBefore("ssh-ed25519 AAAAnotbase64!!")).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Vault HTTP flow (mocked fetch)", () => {
|
||||
const profile: VaultProfileConfig = {
|
||||
id: 1,
|
||||
vaultAddr: "https://vault.example.com:8200/",
|
||||
vaultNamespace: "team-a",
|
||||
oidcMount: "oidc",
|
||||
oidcRole: "developer",
|
||||
sshMount: "ssh-client-signer",
|
||||
sshRole: "my-role",
|
||||
validPrincipals: "root,deploy",
|
||||
keyType: "ssh-ed25519",
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function mockFetch(
|
||||
impl: (
|
||||
url: string,
|
||||
init: RequestInit,
|
||||
) => { status?: number; body: unknown },
|
||||
) {
|
||||
const calls: Array<{ url: string; init: RequestInit }> = [];
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (url: string, init: RequestInit) => {
|
||||
calls.push({ url, init });
|
||||
const { status = 200, body } = impl(url, init);
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
text: async () => JSON.stringify(body),
|
||||
} as Response;
|
||||
}),
|
||||
);
|
||||
return calls;
|
||||
}
|
||||
|
||||
it("startVaultOidc posts auth_url and extracts state", async () => {
|
||||
const calls = mockFetch(() => ({
|
||||
body: {
|
||||
data: {
|
||||
auth_url:
|
||||
"https://idp.example.com/authorize?client_id=x&state=ST-abc123&nonce=n",
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
const result = await startVaultOidc(
|
||||
profile,
|
||||
"https://termix/vault/oidc/callback",
|
||||
);
|
||||
|
||||
expect(result.state).toBe("ST-abc123");
|
||||
expect(result.clientNonce).toMatch(/^[0-9a-f]{40}$/);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0].url).toBe(
|
||||
"https://vault.example.com:8200/v1/auth/oidc/oidc/auth_url",
|
||||
);
|
||||
expect(calls[0].init.method).toBe("POST");
|
||||
const headers = calls[0].init.headers as Record<string, string>;
|
||||
expect(headers["X-Vault-Namespace"]).toBe("team-a");
|
||||
const body = JSON.parse(calls[0].init.body as string);
|
||||
expect(body).toMatchObject({
|
||||
role: "developer",
|
||||
redirect_uri: "https://termix/vault/oidc/callback",
|
||||
});
|
||||
expect(body.client_nonce).toBe(result.clientNonce);
|
||||
});
|
||||
|
||||
it("completeVaultOidc returns the client token", async () => {
|
||||
const calls = mockFetch(() => ({
|
||||
body: { auth: { client_token: "hvs.TESTTOKEN" } },
|
||||
}));
|
||||
|
||||
const token = await completeVaultOidc(profile, {
|
||||
state: "ST-abc123",
|
||||
code: "auth-code",
|
||||
clientNonce: "nonce123",
|
||||
});
|
||||
|
||||
expect(token).toBe("hvs.TESTTOKEN");
|
||||
const url = new URL(calls[0].url);
|
||||
expect(url.pathname).toBe("/v1/auth/oidc/oidc/callback");
|
||||
expect(url.searchParams.get("state")).toBe("ST-abc123");
|
||||
expect(url.searchParams.get("code")).toBe("auth-code");
|
||||
expect(url.searchParams.get("client_nonce")).toBe("nonce123");
|
||||
expect(calls[0].init.method).toBe("GET");
|
||||
});
|
||||
|
||||
it("signWithVault posts the public key and returns signed_key", async () => {
|
||||
const calls = mockFetch(() => ({
|
||||
body: {
|
||||
data: { signed_key: "ssh-ed25519-cert-v01@openssh.com AAAAcert" },
|
||||
},
|
||||
}));
|
||||
|
||||
const cert = await signWithVault(
|
||||
profile,
|
||||
"hvs.TESTTOKEN",
|
||||
"ssh-ed25519 AAAApub comment",
|
||||
);
|
||||
|
||||
expect(cert).toBe("ssh-ed25519-cert-v01@openssh.com AAAAcert");
|
||||
expect(calls[0].url).toBe(
|
||||
"https://vault.example.com:8200/v1/ssh-client-signer/sign/my-role",
|
||||
);
|
||||
const headers = calls[0].init.headers as Record<string, string>;
|
||||
expect(headers["X-Vault-Token"]).toBe("hvs.TESTTOKEN");
|
||||
expect(headers["X-Vault-Namespace"]).toBe("team-a");
|
||||
const body = JSON.parse(calls[0].init.body as string);
|
||||
expect(body).toMatchObject({
|
||||
public_key: "ssh-ed25519 AAAApub comment",
|
||||
cert_type: "user",
|
||||
valid_principals: "root,deploy",
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces Vault error messages", async () => {
|
||||
mockFetch(() => ({
|
||||
status: 400,
|
||||
body: { errors: ["role not found", "permission denied"] },
|
||||
}));
|
||||
|
||||
await expect(
|
||||
signWithVault(profile, "tok", "ssh-ed25519 AAAA"),
|
||||
).rejects.toThrow(/role not found; permission denied/);
|
||||
});
|
||||
});
|
||||
|
||||
// Live integration against a real Vault (e.g. `vault server -dev` in Docker).
|
||||
// Runs only when VAULT_ADDR + VAULT_TOKEN are set and the SSH signer mount
|
||||
// (VAULT_SSH_MOUNT/VAULT_SSH_ROLE) has been configured by the test harness.
|
||||
describe("Vault live signing", () => {
|
||||
const addr = process.env.VAULT_ADDR;
|
||||
const token = process.env.VAULT_TOKEN;
|
||||
const run = !!addr && !!token;
|
||||
|
||||
it.skipIf(!run)("signs an ephemeral key against a real Vault", async () => {
|
||||
const profile: VaultProfileConfig = {
|
||||
id: 99,
|
||||
vaultAddr: addr!,
|
||||
sshMount: process.env.VAULT_SSH_MOUNT || "ssh-client-signer",
|
||||
sshRole: process.env.VAULT_SSH_ROLE || "my-role",
|
||||
validPrincipals: "root",
|
||||
keyType: "ssh-ed25519",
|
||||
};
|
||||
|
||||
const pair = generateEphemeralKeyPair(profile.keyType);
|
||||
const before = Math.floor(Date.now() / 1000);
|
||||
const cert = await signWithVault(profile, token!, pair.publicKey);
|
||||
|
||||
expect(cert).toMatch(/-cert-v01@openssh\.com /);
|
||||
// The signed cert must parse with the same library used to connect.
|
||||
const parsed = ssh2Utils.parseKey(cert);
|
||||
expect(parsed instanceof Error).toBe(false);
|
||||
|
||||
const validBefore = parseCertValidBefore(cert);
|
||||
expect(validBefore).toBeGreaterThan(before);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const createMock = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentAuditLogRepository: vi.fn(() => ({
|
||||
create: createMock,
|
||||
})),
|
||||
}));
|
||||
|
||||
import { logAudit, getRequestMeta } from "../../utils/audit-logger.js";
|
||||
|
||||
describe("logAudit", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
createMock.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("inserts an audit log entry with all required fields", async () => {
|
||||
const params = {
|
||||
userId: "user-1",
|
||||
username: "alice",
|
||||
action: "create_host",
|
||||
resourceType: "host",
|
||||
resourceId: "42",
|
||||
resourceName: "my-server",
|
||||
ipAddress: "1.2.3.4",
|
||||
userAgent: "Mozilla/5.0",
|
||||
success: true,
|
||||
};
|
||||
|
||||
await logAudit(params);
|
||||
|
||||
expect(createMock).toHaveBeenCalledOnce();
|
||||
expect(createMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
userId: "user-1",
|
||||
username: "alice",
|
||||
action: "create_host",
|
||||
resourceType: "host",
|
||||
resourceId: "42",
|
||||
resourceName: "my-server",
|
||||
success: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not throw when insert fails", async () => {
|
||||
createMock.mockRejectedValue(new Error("db error"));
|
||||
|
||||
await expect(
|
||||
logAudit({
|
||||
userId: "u",
|
||||
username: "u",
|
||||
action: "x",
|
||||
resourceType: "y",
|
||||
success: false,
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getRequestMeta", () => {
|
||||
it("extracts ip from x-forwarded-for header", () => {
|
||||
const req = {
|
||||
headers: {
|
||||
"x-forwarded-for": "10.0.0.1, 10.0.0.2",
|
||||
"user-agent": "TestAgent/1.0",
|
||||
},
|
||||
ip: "127.0.0.1",
|
||||
};
|
||||
const meta = getRequestMeta(req as never);
|
||||
expect(meta.ipAddress).toBe("10.0.0.1");
|
||||
expect(meta.userAgent).toBe("TestAgent/1.0");
|
||||
});
|
||||
|
||||
it("falls back to req.ip when no forwarded header", () => {
|
||||
const req = {
|
||||
headers: { "user-agent": "Bot/2" },
|
||||
ip: "192.168.1.1",
|
||||
};
|
||||
const meta = getRequestMeta(req as never);
|
||||
expect(meta.ipAddress).toBe("192.168.1.1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import crypto from "crypto";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const jwtSecret = "a".repeat(64);
|
||||
const encryptionKey = crypto.randomBytes(32);
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
users: new Map<string, { id: string; isAdmin: boolean; username: string }>(),
|
||||
unlockedUsers: new Set<string>(),
|
||||
auditCalls: [] as Record<string, unknown>[],
|
||||
}));
|
||||
|
||||
vi.mock("../../database/db/index.js", () => ({
|
||||
db: {},
|
||||
getDb: () => ({}),
|
||||
saveMemoryDatabaseToFile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentSettingsRepository: () => ({ get: async () => null }),
|
||||
// No sessionId in our tokens, so the session branch is skipped.
|
||||
createCurrentSessionRepository: () => ({ findById: async () => null }),
|
||||
createCurrentUserRepository: () => ({
|
||||
findById: async (userId: string) => state.users.get(userId) ?? null,
|
||||
}),
|
||||
createCurrentApiKeyRepository: () => ({}),
|
||||
createCurrentTrustedDeviceRepository: () => ({}),
|
||||
getCurrentSettingValue: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/user-keys.js", () => ({
|
||||
UserKeyManager: {
|
||||
getInstance: () => ({
|
||||
hasUserDEK: vi.fn(() => true),
|
||||
tryGetUserDEK: vi.fn(() => null),
|
||||
invalidate: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/crypto-migration/dek-migration.js", () => ({
|
||||
adoptRecoveredDEK: vi.fn(async () => {}),
|
||||
migratePasswordUserAtLogin: vi.fn(async () => true),
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/system-crypto.js", () => ({
|
||||
SystemCrypto: {
|
||||
getInstance: () => ({
|
||||
getJWTSecret: async () => jwtSecret,
|
||||
getEncryptionKey: async () => encryptionKey,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/data-crypto.js", () => ({
|
||||
DataCrypto: {
|
||||
canUserAccessData: (userId: string) => state.unlockedUsers.has(userId),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/audit-logger.js", () => ({
|
||||
logAudit: async (params: Record<string, unknown>) => {
|
||||
state.auditCalls.push(params);
|
||||
},
|
||||
getRequestMeta: () => ({ ipAddress: "", userAgent: "" }),
|
||||
}));
|
||||
|
||||
const { AuthManager } = await import("../../utils/auth-manager.js");
|
||||
const authManager = AuthManager.getInstance();
|
||||
const middleware = authManager.createAuthMiddleware();
|
||||
|
||||
type MockRes = {
|
||||
statusCode: number | null;
|
||||
body: unknown;
|
||||
status: (code: number) => MockRes;
|
||||
json: (payload: unknown) => MockRes;
|
||||
clearCookie: () => MockRes;
|
||||
};
|
||||
|
||||
function makeRes(): MockRes {
|
||||
const res: MockRes = {
|
||||
statusCode: null,
|
||||
body: null,
|
||||
status(code: number) {
|
||||
res.statusCode = code;
|
||||
return res;
|
||||
},
|
||||
json(payload: unknown) {
|
||||
res.body = payload;
|
||||
return res;
|
||||
},
|
||||
clearCookie() {
|
||||
return res;
|
||||
},
|
||||
};
|
||||
return res;
|
||||
}
|
||||
|
||||
function runMiddleware(token: string, headers: Record<string, string> = {}) {
|
||||
const req = {
|
||||
cookies: { jwt: token },
|
||||
headers,
|
||||
method: "GET",
|
||||
originalUrl: headers["__url"] ?? "/host/db/host",
|
||||
url: headers["__url"] ?? "/host/db/host",
|
||||
secure: false,
|
||||
} as unknown as Parameters<typeof middleware>[0];
|
||||
const res = makeRes();
|
||||
let nexted = false;
|
||||
return new Promise<{ req: typeof req; res: MockRes; nexted: boolean }>(
|
||||
(resolve) => {
|
||||
const next = () => {
|
||||
nexted = true;
|
||||
resolve({ req, res, nexted });
|
||||
};
|
||||
const maybe = middleware(
|
||||
req,
|
||||
res as unknown as Parameters<typeof middleware>[1],
|
||||
next,
|
||||
);
|
||||
Promise.resolve(maybe).then(() => {
|
||||
if (!nexted) resolve({ req, res, nexted });
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function token(userId: string) {
|
||||
return jwt.sign({ userId }, jwtSecret, { expiresIn: "1h" });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
state.users = new Map([
|
||||
["admin1", { id: "admin1", isAdmin: true, username: "admin" }],
|
||||
["target1", { id: "target1", isAdmin: false, username: "target" }],
|
||||
["regular1", { id: "regular1", isAdmin: false, username: "regular" }],
|
||||
]);
|
||||
state.unlockedUsers = new Set(["admin1", "target1", "regular1"]);
|
||||
state.auditCalls = [];
|
||||
});
|
||||
|
||||
describe("AuthManager admin impersonation", () => {
|
||||
it("swaps req.userId to the target for an admin on an allowlisted path", async () => {
|
||||
const { req, nexted } = await runMiddleware(token("admin1"), {
|
||||
"x-admin-target-user": "target1",
|
||||
__url: "/host/db/host",
|
||||
});
|
||||
expect(nexted).toBe(true);
|
||||
expect((req as unknown as { userId: string }).userId).toBe("target1");
|
||||
expect(
|
||||
(req as unknown as { actingAdminUserId?: string }).actingAdminUserId,
|
||||
).toBe("admin1");
|
||||
expect(state.auditCalls).toHaveLength(1);
|
||||
expect(state.auditCalls[0]).toMatchObject({
|
||||
action: "admin_impersonated_request",
|
||||
resourceId: "target1",
|
||||
userId: "admin1",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects impersonation by a non-admin", async () => {
|
||||
const { res, nexted } = await runMiddleware(token("regular1"), {
|
||||
"x-admin-target-user": "target1",
|
||||
__url: "/host/db/host",
|
||||
});
|
||||
expect(nexted).toBe(false);
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect((res.body as { code?: string }).code).toBe("IMPERSONATION_DENIED");
|
||||
});
|
||||
|
||||
it("rejects impersonation on a non-allowlisted path", async () => {
|
||||
const { res, nexted } = await runMiddleware(token("admin1"), {
|
||||
"x-admin-target-user": "target1",
|
||||
__url: "/users/sessions",
|
||||
});
|
||||
expect(nexted).toBe(false);
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect((res.body as { code?: string }).code).toBe(
|
||||
"IMPERSONATION_NOT_ALLOWED",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns 423 when the target's data is locked", async () => {
|
||||
state.unlockedUsers = new Set(["admin1"]);
|
||||
const { res, nexted } = await runMiddleware(token("admin1"), {
|
||||
"x-admin-target-user": "target1",
|
||||
__url: "/host/db/host",
|
||||
});
|
||||
expect(nexted).toBe(false);
|
||||
expect(res.statusCode).toBe(423);
|
||||
expect((res.body as { code?: string }).code).toBe("TARGET_DATA_LOCKED");
|
||||
});
|
||||
|
||||
it("404s when the target user does not exist", async () => {
|
||||
const { res, nexted } = await runMiddleware(token("admin1"), {
|
||||
"x-admin-target-user": "ghost",
|
||||
__url: "/host/db/host",
|
||||
});
|
||||
expect(nexted).toBe(false);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("ignores the header when the target equals the admin", async () => {
|
||||
const { req, nexted } = await runMiddleware(token("admin1"), {
|
||||
"x-admin-target-user": "admin1",
|
||||
__url: "/host/db/host",
|
||||
});
|
||||
expect(nexted).toBe(true);
|
||||
expect((req as unknown as { userId: string }).userId).toBe("admin1");
|
||||
expect(state.auditCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("passes through normally when no header is present", async () => {
|
||||
const { req, nexted } = await runMiddleware(token("regular1"));
|
||||
expect(nexted).toBe(true);
|
||||
expect((req as unknown as { userId: string }).userId).toBe("regular1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
sqlite: null as {
|
||||
exec: (sql: string) => void;
|
||||
prepare: (sql: string) => {
|
||||
all: () => Array<Record<string, unknown>>;
|
||||
run: (...values: unknown[]) => unknown;
|
||||
};
|
||||
} | null,
|
||||
saveDatabase: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("../../database/db/index.js", async () => {
|
||||
const { default: Database } = await import("better-sqlite3");
|
||||
const { drizzle } = await import("drizzle-orm/better-sqlite3");
|
||||
const sqlite = new Database(":memory:");
|
||||
mocks.sqlite = sqlite;
|
||||
const db = drizzle(sqlite);
|
||||
return {
|
||||
db,
|
||||
getDb: () => db,
|
||||
saveMemoryDatabaseToFile: mocks.saveDatabase,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../utils/user-keys.js", () => ({
|
||||
UserKeyManager: {
|
||||
getInstance: () => ({
|
||||
invalidate: vi.fn(),
|
||||
tryGetUserDEK: vi.fn(() => null),
|
||||
hasUserDEK: vi.fn(() => true),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/system-crypto.js", () => ({
|
||||
SystemCrypto: { getInstance: () => ({}) },
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/data-crypto.js", () => ({
|
||||
DataCrypto: { getInstance: () => ({}) },
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/logger.js", () => ({
|
||||
authLogger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
databaseLogger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const { AuthManager } = await import("../../utils/auth-manager.js");
|
||||
const authManager = AuthManager.getInstance();
|
||||
|
||||
type SessionInput = {
|
||||
id: string;
|
||||
userId: string;
|
||||
sub: string;
|
||||
sid: string | null;
|
||||
providerId: number | null;
|
||||
};
|
||||
|
||||
function insertSession({ id, userId, sub, sid, providerId }: SessionInput) {
|
||||
mocks
|
||||
.sqlite!.prepare(
|
||||
`INSERT INTO sessions (
|
||||
id, user_id, jwt_token, device_type, device_info,
|
||||
oidc_sub, oidc_sid, sso_provider_id,
|
||||
created_at, expires_at, last_active_at
|
||||
) VALUES (?, ?, ?, 'browser', 'test', ?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(
|
||||
id,
|
||||
userId,
|
||||
`token-${id}`,
|
||||
sub,
|
||||
sid,
|
||||
providerId,
|
||||
"2026-07-10T00:00:00.000Z",
|
||||
"2026-07-11T00:00:00.000Z",
|
||||
"2026-07-10T00:00:00.000Z",
|
||||
);
|
||||
}
|
||||
|
||||
function sessionIds(): string[] {
|
||||
return mocks
|
||||
.sqlite!.prepare("SELECT id FROM sessions ORDER BY id")
|
||||
.all()
|
||||
.map((row) => String(row.id));
|
||||
}
|
||||
|
||||
describe("AuthManager.revokeSessionsByOidc", () => {
|
||||
beforeAll(() => {
|
||||
mocks.sqlite!.exec(`
|
||||
CREATE TABLE sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
jwt_token TEXT NOT NULL,
|
||||
device_type TEXT NOT NULL,
|
||||
device_info TEXT NOT NULL,
|
||||
oidc_sub TEXT,
|
||||
oidc_sid TEXT,
|
||||
sso_provider_id INTEGER,
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
last_active_at TEXT NOT NULL
|
||||
)
|
||||
`);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.sqlite!.exec("DELETE FROM sessions");
|
||||
mocks.saveDatabase.mockReset().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("revokes only the matching provider session when sid is present", async () => {
|
||||
insertSession({
|
||||
id: "matching",
|
||||
userId: "user-1",
|
||||
sub: "subject-1",
|
||||
sid: "session-1",
|
||||
providerId: 7,
|
||||
});
|
||||
insertSession({
|
||||
id: "other-provider",
|
||||
userId: "user-1",
|
||||
sub: "subject-1",
|
||||
sid: "session-1",
|
||||
providerId: 8,
|
||||
});
|
||||
insertSession({
|
||||
id: "other-session",
|
||||
userId: "user-1",
|
||||
sub: "subject-1",
|
||||
sid: "session-2",
|
||||
providerId: 7,
|
||||
});
|
||||
|
||||
await expect(
|
||||
authManager.revokeSessionsByOidc({
|
||||
ssoProviderId: 7,
|
||||
sub: "subject-1",
|
||||
sid: "session-1",
|
||||
}),
|
||||
).resolves.toBe(1);
|
||||
|
||||
expect(sessionIds()).toEqual(["other-provider", "other-session"]);
|
||||
});
|
||||
|
||||
it("revokes all provider sessions for a subject when sid is absent", async () => {
|
||||
insertSession({
|
||||
id: "first",
|
||||
userId: "user-1",
|
||||
sub: "subject-1",
|
||||
sid: "session-1",
|
||||
providerId: 7,
|
||||
});
|
||||
insertSession({
|
||||
id: "second",
|
||||
userId: "user-1",
|
||||
sub: "subject-1",
|
||||
sid: "session-2",
|
||||
providerId: 7,
|
||||
});
|
||||
insertSession({
|
||||
id: "other-subject",
|
||||
userId: "user-2",
|
||||
sub: "subject-2",
|
||||
sid: null,
|
||||
providerId: 7,
|
||||
});
|
||||
|
||||
await expect(
|
||||
authManager.revokeSessionsByOidc({
|
||||
ssoProviderId: 7,
|
||||
sub: "subject-1",
|
||||
}),
|
||||
).resolves.toBe(2);
|
||||
|
||||
expect(sessionIds()).toEqual(["other-subject"]);
|
||||
});
|
||||
|
||||
it("does not persist when no session matches", async () => {
|
||||
await expect(
|
||||
authManager.revokeSessionsByOidc({
|
||||
ssoProviderId: 7,
|
||||
sid: "missing",
|
||||
}),
|
||||
).resolves.toBe(0);
|
||||
|
||||
expect(mocks.saveDatabase).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("propagates persistence failures so the provider can retry", async () => {
|
||||
insertSession({
|
||||
id: "matching",
|
||||
userId: "user-1",
|
||||
sub: "subject-1",
|
||||
sid: "session-1",
|
||||
providerId: 7,
|
||||
});
|
||||
mocks.saveDatabase.mockRejectedValueOnce(new Error("disk full"));
|
||||
|
||||
await expect(
|
||||
authManager.revokeSessionsByOidc({
|
||||
ssoProviderId: 7,
|
||||
sid: "session-1",
|
||||
}),
|
||||
).rejects.toThrow("disk full");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import crypto from "crypto";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const jwtSecret = "a".repeat(64);
|
||||
const encryptionKey = crypto.randomBytes(32);
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
hasUserDEK: vi.fn(() => false),
|
||||
adoptRecoveredDEK: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock("../../database/db/index.js", () => ({
|
||||
db: {},
|
||||
getDb: () => ({}),
|
||||
saveMemoryDatabaseToFile: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentSettingsRepository: () => ({ get: async () => null }),
|
||||
createCurrentSessionRepository: () => ({}),
|
||||
createCurrentUserRepository: () => ({}),
|
||||
createCurrentApiKeyRepository: () => ({}),
|
||||
createCurrentTrustedDeviceRepository: () => ({}),
|
||||
getCurrentSettingValue: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/user-keys.js", () => ({
|
||||
UserKeyManager: {
|
||||
getInstance: () => ({
|
||||
hasUserDEK: mocks.hasUserDEK,
|
||||
tryGetUserDEK: vi.fn(() => null),
|
||||
invalidate: vi.fn(),
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/crypto-migration/dek-migration.js", () => ({
|
||||
adoptRecoveredDEK: mocks.adoptRecoveredDEK,
|
||||
migratePasswordUserAtLogin: vi.fn(async () => true),
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/system-crypto.js", () => ({
|
||||
SystemCrypto: {
|
||||
getInstance: () => ({
|
||||
getJWTSecret: async () => jwtSecret,
|
||||
getEncryptionKey: async () => encryptionKey,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
const { AuthManager } = await import("../../utils/auth-manager.js");
|
||||
const authManager = AuthManager.getInstance();
|
||||
|
||||
function makeLegacyDataKeyWrap(
|
||||
userId: string,
|
||||
dek: Buffer,
|
||||
): Record<string, string> {
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv("aes-256-gcm", encryptionKey, iv);
|
||||
cipher.setAAD(Buffer.from(`${userId}:`, "utf8"));
|
||||
const data = Buffer.concat([cipher.update(dek), cipher.final()]);
|
||||
return {
|
||||
version: "v1",
|
||||
iv: iv.toString("base64url"),
|
||||
tag: cipher.getAuthTag().toString("base64url"),
|
||||
data: data.toString("base64url"),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.hasUserDEK.mockReset().mockReturnValue(false);
|
||||
mocks.adoptRecoveredDEK.mockReset().mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
describe("AuthManager token handling", () => {
|
||||
it("issues tokens without a dataKeyWrap", async () => {
|
||||
const token = await authManager.generateJWTToken("user-1");
|
||||
const payload = jwt.decode(token) as Record<string, unknown>;
|
||||
|
||||
expect(payload.userId).toBe("user-1");
|
||||
expect(payload.dataKeyWrap).toBeUndefined();
|
||||
});
|
||||
|
||||
it("adopts the DEK from a legacy dataKeyWrap token on verify", async () => {
|
||||
const dek = crypto.randomBytes(32);
|
||||
const token = jwt.sign(
|
||||
{ userId: "user-1", dataKeyWrap: makeLegacyDataKeyWrap("user-1", dek) },
|
||||
jwtSecret,
|
||||
{ expiresIn: "1h" },
|
||||
);
|
||||
|
||||
const payload = await authManager.verifyJWTToken(token);
|
||||
|
||||
expect(payload?.userId).toBe("user-1");
|
||||
expect(mocks.adoptRecoveredDEK).toHaveBeenCalledOnce();
|
||||
const [userId, adopted] = mocks.adoptRecoveredDEK.mock.calls[0] as [
|
||||
string,
|
||||
Buffer,
|
||||
];
|
||||
expect(userId).toBe("user-1");
|
||||
expect(adopted.equals(dek)).toBe(true);
|
||||
});
|
||||
|
||||
it("skips adoption when the user already has a v3 key", async () => {
|
||||
mocks.hasUserDEK.mockReturnValue(true);
|
||||
const token = jwt.sign(
|
||||
{
|
||||
userId: "user-1",
|
||||
dataKeyWrap: makeLegacyDataKeyWrap("user-1", crypto.randomBytes(32)),
|
||||
},
|
||||
jwtSecret,
|
||||
{ expiresIn: "1h" },
|
||||
);
|
||||
|
||||
await authManager.verifyJWTToken(token);
|
||||
|
||||
expect(mocks.adoptRecoveredDEK).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("tolerates a tampered dataKeyWrap without failing verification", async () => {
|
||||
const wrap = makeLegacyDataKeyWrap("user-1", crypto.randomBytes(32));
|
||||
wrap.tag = Buffer.from(
|
||||
Buffer.from(wrap.tag, "base64url").map((b) => b ^ 0xff),
|
||||
).toString("base64url");
|
||||
const token = jwt.sign({ userId: "user-1", dataKeyWrap: wrap }, jwtSecret, {
|
||||
expiresIn: "1h",
|
||||
});
|
||||
|
||||
const payload = await authManager.verifyJWTToken(token);
|
||||
|
||||
expect(payload?.userId).toBe("user-1");
|
||||
expect(mocks.adoptRecoveredDEK).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,330 @@
|
||||
import crypto from "crypto";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const settingsStore = new Map<string, string>();
|
||||
let userRows: Array<{ id: string }> = [];
|
||||
|
||||
vi.mock("../../../database/repositories/factory.js", () => ({
|
||||
getCurrentSettingValue: (key: string) => settingsStore.get(key) ?? null,
|
||||
createCurrentSettingsRepository: () => ({
|
||||
upsert: async (key: string, value: string) => {
|
||||
settingsStore.set(key, value);
|
||||
},
|
||||
set: async (key: string, value: string) => {
|
||||
settingsStore.set(key, value);
|
||||
},
|
||||
delete: async (key: string) => {
|
||||
settingsStore.delete(key);
|
||||
},
|
||||
}),
|
||||
createCurrentUserRepository: () => ({
|
||||
listAll: async () => userRows,
|
||||
}),
|
||||
}));
|
||||
|
||||
const masterKey = crypto.randomBytes(32);
|
||||
|
||||
vi.mock("../../../utils/system-crypto.js", () => ({
|
||||
SystemCrypto: {
|
||||
getInstance: () => ({
|
||||
getEncryptionKey: async () => masterKey,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
import { UserKeyManager } from "../../../utils/user-keys.js";
|
||||
import {
|
||||
adoptRecoveredDEK,
|
||||
legacySettingsKeys,
|
||||
migratePasswordUserAtLogin,
|
||||
runBootDekMigration,
|
||||
} from "../../../utils/crypto-migration/dek-migration.js";
|
||||
|
||||
const manager = UserKeyManager.getInstance();
|
||||
|
||||
// Fixture helpers replicating the deleted legacy wrap formats exactly.
|
||||
function legacyEncryptDEK(dek: Buffer, kek: Buffer): string {
|
||||
const iv = crypto.randomBytes(16);
|
||||
const cipher = crypto.createCipheriv("aes-256-gcm", kek, iv);
|
||||
const encrypted = Buffer.concat([cipher.update(dek), cipher.final()]);
|
||||
return JSON.stringify({
|
||||
data: encrypted.toString("hex"),
|
||||
iv: iv.toString("hex"),
|
||||
tag: cipher.getAuthTag().toString("hex"),
|
||||
algorithm: "aes-256-gcm",
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
function oidcSystemKey(userId: string): Buffer {
|
||||
return Buffer.from(
|
||||
crypto.hkdfSync(
|
||||
"sha256",
|
||||
masterKey,
|
||||
Buffer.from(userId, "utf8"),
|
||||
Buffer.from("termix:oidc-user-kek", "utf8"),
|
||||
32,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function webauthnSystemKey(userId: string): Buffer {
|
||||
return Buffer.from(
|
||||
crypto.hkdfSync(
|
||||
"sha256",
|
||||
masterKey,
|
||||
Buffer.from(userId, "utf8"),
|
||||
Buffer.from("termix:webauthn-user-kek", "utf8"),
|
||||
32,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function legacyDefaultOidcKey(userId: string): Buffer {
|
||||
return crypto.pbkdf2Sync(
|
||||
"termix-oidc-system-secret-default",
|
||||
Buffer.from(userId, "utf8"),
|
||||
100000,
|
||||
32,
|
||||
"sha256",
|
||||
);
|
||||
}
|
||||
|
||||
function passwordKek(password: string, saltHex: string): Buffer {
|
||||
return crypto.pbkdf2Sync(
|
||||
password,
|
||||
Buffer.from(saltHex, "hex"),
|
||||
100000,
|
||||
32,
|
||||
"sha256",
|
||||
);
|
||||
}
|
||||
|
||||
function seedPasswordUser(userId: string, password: string): Buffer {
|
||||
const dek = crypto.randomBytes(32);
|
||||
const saltHex = crypto.randomBytes(32).toString("hex");
|
||||
const keys = legacySettingsKeys(userId);
|
||||
settingsStore.set(
|
||||
keys.kekSalt,
|
||||
JSON.stringify({
|
||||
salt: saltHex,
|
||||
iterations: 100000,
|
||||
algorithm: "pbkdf2-sha256",
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
settingsStore.set(
|
||||
keys.passwordWrap,
|
||||
legacyEncryptDEK(dek, passwordKek(password, saltHex)),
|
||||
);
|
||||
return dek;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
settingsStore.clear();
|
||||
userRows = [];
|
||||
await manager.initialize(masterKey);
|
||||
manager.clearCache();
|
||||
});
|
||||
|
||||
describe("runBootDekMigration", () => {
|
||||
it("migrates a pure-OIDC user whose primary slot is system-wrapped", async () => {
|
||||
const dek = crypto.randomBytes(32);
|
||||
const keys = legacySettingsKeys("oidc-user");
|
||||
settingsStore.set(
|
||||
keys.passwordWrap,
|
||||
legacyEncryptDEK(dek, oidcSystemKey("oidc-user")),
|
||||
);
|
||||
userRows = [{ id: "oidc-user" }];
|
||||
|
||||
const summary = await runBootDekMigration();
|
||||
|
||||
expect(summary.migrated).toBe(1);
|
||||
expect(manager.getUserDEK("oidc-user").equals(dek)).toBe(true);
|
||||
});
|
||||
|
||||
it("migrates via the dedicated oidc wrap slot for dual-auth users", async () => {
|
||||
const dek = seedPasswordUser("dual-user", "hunter2");
|
||||
const keys = legacySettingsKeys("dual-user");
|
||||
settingsStore.set(
|
||||
keys.oidcWrap,
|
||||
legacyEncryptDEK(dek, oidcSystemKey("dual-user")),
|
||||
);
|
||||
userRows = [{ id: "dual-user" }];
|
||||
|
||||
const summary = await runBootDekMigration();
|
||||
|
||||
expect(summary.migrated).toBe(1);
|
||||
expect(manager.getUserDEK("dual-user").equals(dek)).toBe(true);
|
||||
});
|
||||
|
||||
it("migrates webauthn-wrapped users", async () => {
|
||||
const dek = seedPasswordUser("wa-user", "hunter2");
|
||||
const keys = legacySettingsKeys("wa-user");
|
||||
settingsStore.set(
|
||||
keys.webauthnWrap,
|
||||
legacyEncryptDEK(dek, webauthnSystemKey("wa-user")),
|
||||
);
|
||||
userRows = [{ id: "wa-user" }];
|
||||
|
||||
const summary = await runBootDekMigration();
|
||||
|
||||
expect(summary.migrated).toBe(1);
|
||||
expect(manager.getUserDEK("wa-user").equals(dek)).toBe(true);
|
||||
});
|
||||
|
||||
it("migrates wraps made with the legacy hardcoded default secret", async () => {
|
||||
const dek = crypto.randomBytes(32);
|
||||
const keys = legacySettingsKeys("legacy-user");
|
||||
settingsStore.set(
|
||||
keys.oidcWrap,
|
||||
legacyEncryptDEK(dek, legacyDefaultOidcKey("legacy-user")),
|
||||
);
|
||||
userRows = [{ id: "legacy-user" }];
|
||||
|
||||
const summary = await runBootDekMigration();
|
||||
|
||||
expect(summary.migrated).toBe(1);
|
||||
expect(manager.getUserDEK("legacy-user").equals(dek)).toBe(true);
|
||||
});
|
||||
|
||||
it("leaves password-only users pending without touching their rows", async () => {
|
||||
seedPasswordUser("pw-user", "hunter2");
|
||||
userRows = [{ id: "pw-user" }];
|
||||
const keys = legacySettingsKeys("pw-user");
|
||||
const before = {
|
||||
salt: settingsStore.get(keys.kekSalt),
|
||||
wrap: settingsStore.get(keys.passwordWrap),
|
||||
};
|
||||
|
||||
const summary = await runBootDekMigration({ cleanupLegacy: true });
|
||||
|
||||
expect(summary.pendingPasswordLogin).toBe(1);
|
||||
expect(manager.hasUserDEK("pw-user")).toBe(false);
|
||||
expect(settingsStore.get(keys.kekSalt)).toBe(before.salt);
|
||||
expect(settingsStore.get(keys.passwordWrap)).toBe(before.wrap);
|
||||
});
|
||||
|
||||
it("creates a fresh DEK for users with no key material at all", async () => {
|
||||
userRows = [{ id: "new-user" }];
|
||||
|
||||
const summary = await runBootDekMigration();
|
||||
|
||||
expect(summary.created).toBe(1);
|
||||
expect(manager.hasUserDEK("new-user")).toBe(true);
|
||||
});
|
||||
|
||||
it("is idempotent across repeated runs", async () => {
|
||||
const dek = crypto.randomBytes(32);
|
||||
const keys = legacySettingsKeys("oidc-user");
|
||||
settingsStore.set(
|
||||
keys.passwordWrap,
|
||||
legacyEncryptDEK(dek, oidcSystemKey("oidc-user")),
|
||||
);
|
||||
userRows = [{ id: "oidc-user" }];
|
||||
|
||||
await runBootDekMigration();
|
||||
const second = await runBootDekMigration();
|
||||
|
||||
expect(second.alreadyMigrated).toBe(1);
|
||||
expect(second.migrated).toBe(0);
|
||||
manager.clearCache();
|
||||
expect(manager.getUserDEK("oidc-user").equals(dek)).toBe(true);
|
||||
});
|
||||
|
||||
it("cleans leftover legacy rows when v3 already exists (crash resume)", async () => {
|
||||
const dek = crypto.randomBytes(32);
|
||||
await manager.persistDEK("resume-user", dek);
|
||||
const keys = legacySettingsKeys("resume-user");
|
||||
settingsStore.set(
|
||||
keys.oidcWrap,
|
||||
legacyEncryptDEK(dek, oidcSystemKey("resume-user")),
|
||||
);
|
||||
userRows = [{ id: "resume-user" }];
|
||||
|
||||
const summary = await runBootDekMigration({ cleanupLegacy: true });
|
||||
|
||||
expect(summary.alreadyMigrated).toBe(1);
|
||||
expect(settingsStore.has(keys.oidcWrap)).toBe(false);
|
||||
expect(manager.getUserDEK("resume-user").equals(dek)).toBe(true);
|
||||
});
|
||||
|
||||
it("removes legacy wraps after migration when cleanup is enabled", async () => {
|
||||
const dek = seedPasswordUser("dual-user", "hunter2");
|
||||
const keys = legacySettingsKeys("dual-user");
|
||||
settingsStore.set(
|
||||
keys.oidcWrap,
|
||||
legacyEncryptDEK(dek, oidcSystemKey("dual-user")),
|
||||
);
|
||||
userRows = [{ id: "dual-user" }];
|
||||
|
||||
await runBootDekMigration({ cleanupLegacy: true });
|
||||
|
||||
expect(settingsStore.has(keys.oidcWrap)).toBe(false);
|
||||
expect(settingsStore.has(keys.passwordWrap)).toBe(false);
|
||||
expect(settingsStore.has(keys.kekSalt)).toBe(false);
|
||||
expect(manager.getUserDEK("dual-user").equals(dek)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("migratePasswordUserAtLogin", () => {
|
||||
it("migrates with the correct password and cleans legacy rows", async () => {
|
||||
const dek = seedPasswordUser("pw-user", "hunter2");
|
||||
const keys = legacySettingsKeys("pw-user");
|
||||
|
||||
const migrated = await migratePasswordUserAtLogin("pw-user", "hunter2");
|
||||
|
||||
expect(migrated).toBe(true);
|
||||
expect(manager.getUserDEK("pw-user").equals(dek)).toBe(true);
|
||||
expect(settingsStore.has(keys.passwordWrap)).toBe(false);
|
||||
expect(settingsStore.has(keys.kekSalt)).toBe(false);
|
||||
});
|
||||
|
||||
it("fails with a wrong password and leaves rows intact", async () => {
|
||||
seedPasswordUser("pw-user", "hunter2");
|
||||
const keys = legacySettingsKeys("pw-user");
|
||||
|
||||
const migrated = await migratePasswordUserAtLogin("pw-user", "wrong");
|
||||
|
||||
expect(migrated).toBe(false);
|
||||
expect(manager.hasUserDEK("pw-user")).toBe(false);
|
||||
expect(settingsStore.has(keys.passwordWrap)).toBe(true);
|
||||
expect(settingsStore.has(keys.kekSalt)).toBe(true);
|
||||
});
|
||||
|
||||
it("returns true and cleans up when the user is already migrated", async () => {
|
||||
const dek = seedPasswordUser("pw-user", "hunter2");
|
||||
await manager.persistDEK("pw-user", dek);
|
||||
|
||||
const migrated = await migratePasswordUserAtLogin("pw-user", "ignored");
|
||||
|
||||
expect(migrated).toBe(true);
|
||||
expect(settingsStore.has(legacySettingsKeys("pw-user").passwordWrap)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("adoptRecoveredDEK", () => {
|
||||
it("persists a session-recovered DEK and cleans legacy rows", async () => {
|
||||
seedPasswordUser("pw-user", "hunter2");
|
||||
const dek = crypto.randomBytes(32);
|
||||
|
||||
await adoptRecoveredDEK("pw-user", dek);
|
||||
|
||||
expect(manager.getUserDEK("pw-user").equals(dek)).toBe(true);
|
||||
expect(settingsStore.has(legacySettingsKeys("pw-user").passwordWrap)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not overwrite an existing v3 wrap", async () => {
|
||||
const existing = crypto.randomBytes(32);
|
||||
await manager.persistDEK("pw-user", existing);
|
||||
|
||||
await adoptRecoveredDEK("pw-user", crypto.randomBytes(32));
|
||||
|
||||
manager.clearCache();
|
||||
expect(manager.getUserDEK("pw-user").equals(existing)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
settings: new Map<string, string>(),
|
||||
grants: [] as Array<Record<string, unknown>>,
|
||||
roleMembers: new Map<number, string[]>(),
|
||||
executedSql: [] as string[],
|
||||
snapshots: [] as Array<[number, number, string, string]>,
|
||||
usersWithKeys: new Set<string>(),
|
||||
saves: [] as string[],
|
||||
}));
|
||||
|
||||
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);
|
||||
},
|
||||
}),
|
||||
getCurrentRepositorySqlite: () => ({
|
||||
prepare: (sql: string) => ({
|
||||
all: (..._params: unknown[]) => {
|
||||
if (sql.includes("FROM host_access")) return state.grants;
|
||||
if (sql.includes("FROM user_roles")) {
|
||||
const roleId = _params[0] as number;
|
||||
return (state.roleMembers.get(roleId) ?? []).map((id) => ({
|
||||
user_id: id,
|
||||
}));
|
||||
}
|
||||
return [];
|
||||
},
|
||||
}),
|
||||
exec: (sql: string) => {
|
||||
state.executedSql.push(sql);
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/shared-host-secrets-manager.js", () => ({
|
||||
SharedHostSecretsManager: {
|
||||
getInstance: () => ({
|
||||
snapshotForUser: async (
|
||||
hostAccessId: number,
|
||||
hostId: number,
|
||||
targetUserId: string,
|
||||
ownerId: string,
|
||||
) => {
|
||||
if (targetUserId === "broken") throw new Error("boom");
|
||||
state.snapshots.push([hostAccessId, hostId, targetUserId, ownerId]);
|
||||
},
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/data-crypto.js", () => ({
|
||||
DataCrypto: {
|
||||
canUserAccessData: (userId: string) => state.usersWithKeys.has(userId),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/database-save-trigger.js", () => ({
|
||||
DatabaseSaveTrigger: {
|
||||
forceSave: async (reason: string) => {
|
||||
state.saves.push(reason);
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../../utils/logger.js", () => ({
|
||||
databaseLogger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { runSharedHostSecretsMigration } from "../../../utils/crypto-migration/shared-host-secrets-migration.js";
|
||||
|
||||
beforeEach(() => {
|
||||
state.settings.clear();
|
||||
state.grants = [];
|
||||
state.roleMembers.clear();
|
||||
state.executedSql = [];
|
||||
state.snapshots = [];
|
||||
state.usersWithKeys = new Set(["owner", "alice", "bob"]);
|
||||
state.saves = [];
|
||||
});
|
||||
|
||||
describe("runSharedHostSecretsMigration", () => {
|
||||
it("re-snapshots direct and role grants, drops the legacy table and sets the flag", async () => {
|
||||
state.grants = [
|
||||
{
|
||||
hostAccessId: 1,
|
||||
hostId: 42,
|
||||
userId: "alice",
|
||||
roleId: null,
|
||||
ownerId: "owner",
|
||||
},
|
||||
{
|
||||
hostAccessId: 2,
|
||||
hostId: 42,
|
||||
userId: null,
|
||||
roleId: 9,
|
||||
ownerId: "owner",
|
||||
},
|
||||
];
|
||||
state.roleMembers.set(9, ["bob", "owner"]);
|
||||
|
||||
const result = await runSharedHostSecretsMigration();
|
||||
|
||||
expect(result).toEqual({ snapshotted: 2, skipped: 0 });
|
||||
expect(state.snapshots).toEqual([
|
||||
[1, 42, "alice", "owner"],
|
||||
[2, 42, "bob", "owner"],
|
||||
]);
|
||||
expect(
|
||||
state.executedSql.some((sql) =>
|
||||
sql.includes("DROP TABLE IF EXISTS shared_credentials"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(state.settings.get("shared_host_secrets_migrated_v1")).toBe("done");
|
||||
expect(state.saves).toContain("shared_host_secrets_migration");
|
||||
});
|
||||
|
||||
it("skips grants with missing DEKs and failed snapshots without crashing", async () => {
|
||||
state.usersWithKeys = new Set(["owner", "alice", "broken"]);
|
||||
state.grants = [
|
||||
{
|
||||
hostAccessId: 1,
|
||||
hostId: 42,
|
||||
userId: "alice",
|
||||
roleId: null,
|
||||
ownerId: "owner",
|
||||
},
|
||||
{
|
||||
hostAccessId: 2,
|
||||
hostId: 42,
|
||||
userId: "no-key",
|
||||
roleId: null,
|
||||
ownerId: "owner",
|
||||
},
|
||||
{
|
||||
hostAccessId: 3,
|
||||
hostId: 42,
|
||||
userId: "broken",
|
||||
roleId: null,
|
||||
ownerId: "owner",
|
||||
},
|
||||
];
|
||||
|
||||
const result = await runSharedHostSecretsMigration();
|
||||
|
||||
expect(result).toEqual({ snapshotted: 1, skipped: 2 });
|
||||
expect(state.settings.get("shared_host_secrets_migrated_v1")).toBe("done");
|
||||
});
|
||||
|
||||
it("does nothing when the migration flag is already set", async () => {
|
||||
state.settings.set("shared_host_secrets_migrated_v1", "done");
|
||||
state.grants = [
|
||||
{
|
||||
hostAccessId: 1,
|
||||
hostId: 42,
|
||||
userId: "alice",
|
||||
roleId: null,
|
||||
ownerId: "owner",
|
||||
},
|
||||
];
|
||||
|
||||
const result = await runSharedHostSecretsMigration();
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(state.snapshots).toEqual([]);
|
||||
expect(state.executedSql).toEqual([]);
|
||||
});
|
||||
});
|
||||
Binary file not shown.
@@ -0,0 +1,141 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import {
|
||||
DATABASE_LAYER_PREUPGRADE_BACKUP_MARKER,
|
||||
DATABASE_LAYER_PREUPGRADE_BACKUP_PREFIX,
|
||||
DATABASE_LAYER_SKIP_PREUPGRADE_BACKUP_ENV,
|
||||
ensureDatabaseLayerPreupgradeBackup,
|
||||
} from "../../utils/database-layer-preupgrade-backup.js";
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "termix-prebackup-"));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("ensureDatabaseLayerPreupgradeBackup", () => {
|
||||
it("copies existing database files and writes a marker", () => {
|
||||
const dataDir = makeTempDir();
|
||||
const encryptedDbPath = path.join(dataDir, "db.sqlite.encrypted");
|
||||
const metadataPath = `${encryptedDbPath}.meta`;
|
||||
const envPath = path.join(dataDir, ".env");
|
||||
fs.writeFileSync(encryptedDbPath, "encrypted-db");
|
||||
fs.writeFileSync(metadataPath, '{"version":"v2"}');
|
||||
fs.writeFileSync(envPath, "DATABASE_KEY=test-key");
|
||||
|
||||
const result = ensureDatabaseLayerPreupgradeBackup({
|
||||
dataDir,
|
||||
version: "2.5.0-test",
|
||||
now: new Date("2026-06-27T12:00:00.000Z"),
|
||||
env: {} as NodeJS.ProcessEnv,
|
||||
});
|
||||
|
||||
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(
|
||||
fs.readFileSync(
|
||||
path.join(result.backupDir!, "db.sqlite.encrypted"),
|
||||
"utf8",
|
||||
),
|
||||
).toBe("encrypted-db");
|
||||
expect(
|
||||
fs.readFileSync(
|
||||
path.join(result.backupDir!, "db.sqlite.encrypted.meta"),
|
||||
"utf8",
|
||||
),
|
||||
).toBe('{"version":"v2"}');
|
||||
expect(fs.readFileSync(path.join(result.backupDir!, ".env"), "utf8")).toBe(
|
||||
"DATABASE_KEY=test-key",
|
||||
);
|
||||
|
||||
const manifest = JSON.parse(
|
||||
fs.readFileSync(path.join(result.backupDir!, "manifest.json"), "utf8"),
|
||||
) as { sourceVersion: string };
|
||||
expect(manifest.sourceVersion).toBe("2.5.0-test");
|
||||
});
|
||||
|
||||
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),
|
||||
"{}",
|
||||
);
|
||||
|
||||
const result = ensureDatabaseLayerPreupgradeBackup({
|
||||
dataDir,
|
||||
env: {} as NodeJS.ProcessEnv,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "skipped",
|
||||
reason: "marker_exists",
|
||||
});
|
||||
expect(fs.existsSync(path.join(dataDir, "backups"))).toBe(false);
|
||||
});
|
||||
|
||||
it("skips new installs without a database file", () => {
|
||||
const dataDir = makeTempDir();
|
||||
|
||||
const result = ensureDatabaseLayerPreupgradeBackup({
|
||||
dataDir,
|
||||
env: {} as NodeJS.ProcessEnv,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "skipped",
|
||||
reason: "no_database_file",
|
||||
});
|
||||
expect(
|
||||
fs.existsSync(
|
||||
path.join(dataDir, DATABASE_LAYER_PREUPGRADE_BACKUP_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({
|
||||
dataDir,
|
||||
env: {
|
||||
[DATABASE_LAYER_SKIP_PREUPGRADE_BACKUP_ENV]: "1",
|
||||
} as NodeJS.ProcessEnv,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "skipped",
|
||||
reason: "skip_env",
|
||||
});
|
||||
expect(fs.existsSync(path.join(dataDir, "backups"))).toBe(false);
|
||||
});
|
||||
|
||||
it("fails closed when the backup cannot be written", () => {
|
||||
const dataDir = makeTempDir();
|
||||
fs.writeFileSync(path.join(dataDir, "db.sqlite.encrypted"), "encrypted-db");
|
||||
fs.writeFileSync(path.join(dataDir, "backups"), "not-a-directory");
|
||||
|
||||
expect(() =>
|
||||
ensureDatabaseLayerPreupgradeBackup({
|
||||
dataDir,
|
||||
env: {} as NodeJS.ProcessEnv,
|
||||
}),
|
||||
).toThrow("Failed to create database layer pre-upgrade backup");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { DatabaseSaveTrigger } from "../../utils/database-save-trigger.js";
|
||||
|
||||
describe("DatabaseSaveTrigger", () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
DatabaseSaveTrigger.cleanup();
|
||||
});
|
||||
|
||||
it("force saves through the initialized save function", async () => {
|
||||
const save = vi.fn().mockResolvedValue(undefined);
|
||||
DatabaseSaveTrigger.initialize(save);
|
||||
|
||||
await DatabaseSaveTrigger.forceSave("test_force_save");
|
||||
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
expect(DatabaseSaveTrigger.getStatus()).toMatchObject({
|
||||
initialized: true,
|
||||
pendingSave: false,
|
||||
hasPendingTimeout: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("debounces dirty saves and marks the database clean after saving", async () => {
|
||||
vi.useFakeTimers();
|
||||
const save = vi.fn().mockResolvedValue(undefined);
|
||||
DatabaseSaveTrigger.initialize(save);
|
||||
|
||||
await DatabaseSaveTrigger.triggerSave("first");
|
||||
await DatabaseSaveTrigger.triggerSave("second");
|
||||
|
||||
expect(DatabaseSaveTrigger.isDirty).toBe(true);
|
||||
expect(DatabaseSaveTrigger.getStatus().hasPendingTimeout).toBe(true);
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
expect(DatabaseSaveTrigger.isDirty).toBe(false);
|
||||
expect(DatabaseSaveTrigger.getStatus().pendingSave).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import crypto from "crypto";
|
||||
import { FieldCrypto } from "../../utils/field-crypto.js";
|
||||
|
||||
const masterKey = crypto.randomBytes(32);
|
||||
|
||||
describe("FieldCrypto.encryptField / decryptField", () => {
|
||||
it("round-trips a plaintext value", () => {
|
||||
const encrypted = FieldCrypto.encryptField(
|
||||
"s3cr3t-password",
|
||||
masterKey,
|
||||
"record-1",
|
||||
"password",
|
||||
);
|
||||
const decrypted = FieldCrypto.decryptField(
|
||||
encrypted,
|
||||
masterKey,
|
||||
"record-1",
|
||||
"password",
|
||||
);
|
||||
expect(decrypted).toBe("s3cr3t-password");
|
||||
});
|
||||
|
||||
it("returns empty string for empty input", () => {
|
||||
expect(FieldCrypto.encryptField("", masterKey, "r", "f")).toBe("");
|
||||
expect(FieldCrypto.decryptField("", masterKey, "r", "f")).toBe("");
|
||||
});
|
||||
|
||||
it("produces different ciphertext each time (random IV + salt)", () => {
|
||||
const a = FieldCrypto.encryptField("same", masterKey, "r", "f");
|
||||
const b = FieldCrypto.encryptField("same", masterKey, "r", "f");
|
||||
expect(a).not.toBe(b);
|
||||
expect(FieldCrypto.decryptField(a, masterKey, "r", "f")).toBe("same");
|
||||
expect(FieldCrypto.decryptField(b, masterKey, "r", "f")).toBe("same");
|
||||
});
|
||||
|
||||
it("fails to decrypt with the wrong master key", () => {
|
||||
const encrypted = FieldCrypto.encryptField("value", masterKey, "r", "f");
|
||||
const wrongKey = crypto.randomBytes(32);
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(encrypted, wrongKey, "r", "f"),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("fails to decrypt when the field name context differs", () => {
|
||||
const encrypted = FieldCrypto.encryptField(
|
||||
"value",
|
||||
masterKey,
|
||||
"r",
|
||||
"password",
|
||||
);
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(encrypted, masterKey, "r", "key"),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("detects tampering with the ciphertext (GCM auth tag)", () => {
|
||||
const encrypted = FieldCrypto.encryptField("value", masterKey, "r", "f");
|
||||
const parsed = JSON.parse(encrypted);
|
||||
// Flip a hex char in the encrypted data.
|
||||
parsed.data = (parsed.data[0] === "a" ? "b" : "a") + parsed.data.slice(1);
|
||||
const tampered = JSON.stringify(parsed);
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(tampered, masterKey, "r", "f"),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("throws when the encrypted payload is missing recordId context", () => {
|
||||
const encrypted = FieldCrypto.encryptField("value", masterKey, "r", "f");
|
||||
const parsed = JSON.parse(encrypted);
|
||||
delete parsed.recordId;
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(JSON.stringify(parsed), masterKey, "r", "f"),
|
||||
).toThrow(/recordId/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("FieldCrypto.shouldEncryptField", () => {
|
||||
it("identifies encrypted fields per table", () => {
|
||||
expect(FieldCrypto.shouldEncryptField("users", "passwordHash")).toBe(true);
|
||||
expect(FieldCrypto.shouldEncryptField("ssh_data", "password")).toBe(true);
|
||||
expect(
|
||||
FieldCrypto.shouldEncryptField("ssh_credentials", "privateKey"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false for non-encrypted fields and unknown tables", () => {
|
||||
expect(FieldCrypto.shouldEncryptField("users", "username")).toBe(false);
|
||||
expect(FieldCrypto.shouldEncryptField("unknown_table", "password")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import Database from "better-sqlite3";
|
||||
import fs from "fs";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { LegacySqliteDatabaseCopyStore } from "../../utils/legacy-sqlite-database-copy-store.js";
|
||||
|
||||
describe("LegacySqliteDatabaseCopyStore", () => {
|
||||
let tempDir: string | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
if (tempDir) {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
tempDir = null;
|
||||
}
|
||||
});
|
||||
|
||||
function createLegacyDatabase(): string {
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "termix-legacy-copy-"));
|
||||
const dbPath = path.join(tempDir, "db.sqlite");
|
||||
const db = new Database(dbPath);
|
||||
|
||||
try {
|
||||
db.exec(`
|
||||
PRAGMA foreign_keys = ON;
|
||||
CREATE TABLE users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE ssh_data (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
);
|
||||
INSERT INTO users (id, username) VALUES ('user-1', 'alice');
|
||||
INSERT INTO ssh_data (user_id, name) VALUES ('user-1', 'host-1');
|
||||
`);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
|
||||
return dbPath;
|
||||
}
|
||||
|
||||
it("copies legacy SQLite schema and rows into a serialized memory buffer", () => {
|
||||
const dbPath = createLegacyDatabase();
|
||||
|
||||
const result =
|
||||
new LegacySqliteDatabaseCopyStore().copyDatabaseToMemoryBuffer(dbPath);
|
||||
|
||||
expect(result.migratedTables).toBe(2);
|
||||
expect(result.migratedRows).toBe(2);
|
||||
expect(result.buffer.length).toBeGreaterThan(0);
|
||||
|
||||
const copied = new Database(result.buffer);
|
||||
try {
|
||||
expect(
|
||||
copied.prepare("SELECT username FROM users WHERE id = ?").get("user-1"),
|
||||
).toEqual({ username: "alice" });
|
||||
expect(
|
||||
copied
|
||||
.prepare("SELECT name FROM ssh_data WHERE user_id = ?")
|
||||
.get("user-1"),
|
||||
).toEqual({ name: "host-1" });
|
||||
expect(copied.prepare("PRAGMA foreign_key_check").all()).toEqual([]);
|
||||
} finally {
|
||||
copied.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { loginRateLimiter } from "../../utils/login-rate-limiter.js";
|
||||
|
||||
// The limiter is a shared singleton, so each test uses unique ip/username keys
|
||||
// and resets them to stay isolated.
|
||||
describe("loginRateLimiter login attempts", () => {
|
||||
let ip: string;
|
||||
let username: string;
|
||||
let counter = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
counter += 1;
|
||||
ip = `10.0.0.${counter}`;
|
||||
username = `user${counter}`;
|
||||
loginRateLimiter.resetAttempts(ip, username);
|
||||
});
|
||||
|
||||
it("starts unlocked with the full attempt budget", () => {
|
||||
expect(loginRateLimiter.isLocked(ip, username).locked).toBe(false);
|
||||
expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(5);
|
||||
});
|
||||
|
||||
it("decrements remaining attempts on each failure", () => {
|
||||
loginRateLimiter.recordFailedAttempt(ip, username);
|
||||
expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(4);
|
||||
loginRateLimiter.recordFailedAttempt(ip, username);
|
||||
expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(3);
|
||||
});
|
||||
|
||||
it("locks the account after 5 failed attempts", () => {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
loginRateLimiter.recordFailedAttempt(ip, username);
|
||||
}
|
||||
const result = loginRateLimiter.isLocked(ip, username);
|
||||
expect(result.locked).toBe(true);
|
||||
expect(result.remainingTime).toBeGreaterThan(0);
|
||||
expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(0);
|
||||
});
|
||||
|
||||
it("clears the lock and counters on reset (successful login)", () => {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
loginRateLimiter.recordFailedAttempt(ip, username);
|
||||
}
|
||||
expect(loginRateLimiter.isLocked(ip, username).locked).toBe(true);
|
||||
|
||||
loginRateLimiter.resetAttempts(ip, username);
|
||||
expect(loginRateLimiter.isLocked(ip, username).locked).toBe(false);
|
||||
expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(5);
|
||||
});
|
||||
|
||||
it("locks by IP even without a username", () => {
|
||||
const soloIp = `192.168.1.${counter}`;
|
||||
for (let i = 0; i < 5; i++) {
|
||||
loginRateLimiter.recordFailedAttempt(soloIp);
|
||||
}
|
||||
expect(loginRateLimiter.isLocked(soloIp).locked).toBe(true);
|
||||
loginRateLimiter.resetAttempts(soloIp);
|
||||
});
|
||||
});
|
||||
|
||||
describe("loginRateLimiter TOTP attempts", () => {
|
||||
let userId: string;
|
||||
let counter = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
counter += 1;
|
||||
userId = `totp-user${counter}`;
|
||||
loginRateLimiter.resetTOTPAttempts(userId);
|
||||
});
|
||||
|
||||
it("locks TOTP after 5 failures and resets cleanly", () => {
|
||||
expect(loginRateLimiter.isTOTPLocked(userId).locked).toBe(false);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
loginRateLimiter.recordFailedTOTPAttempt(userId);
|
||||
}
|
||||
expect(loginRateLimiter.isTOTPLocked(userId).locked).toBe(true);
|
||||
expect(loginRateLimiter.getRemainingTOTPAttempts(userId)).toBe(0);
|
||||
|
||||
loginRateLimiter.resetTOTPAttempts(userId);
|
||||
expect(loginRateLimiter.isTOTPLocked(userId).locked).toBe(false);
|
||||
expect(loginRateLimiter.getRemainingTOTPAttempts(userId)).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("loginRateLimiter password-reset-code attempts", () => {
|
||||
let username: string;
|
||||
let counter = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
counter += 1;
|
||||
username = `reset-user${counter}`;
|
||||
loginRateLimiter.resetResetCodeAttempts(username);
|
||||
});
|
||||
|
||||
it("locks reset codes after 5 failures and resets cleanly", () => {
|
||||
expect(loginRateLimiter.isResetCodeLocked(username).locked).toBe(false);
|
||||
for (let i = 0; i < 5; i++) {
|
||||
loginRateLimiter.recordResetCodeAttempt(username);
|
||||
}
|
||||
expect(loginRateLimiter.isResetCodeLocked(username).locked).toBe(true);
|
||||
|
||||
loginRateLimiter.resetResetCodeAttempts(username);
|
||||
expect(loginRateLimiter.isResetCodeLocked(username).locked).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
PERMISSION_CATALOG,
|
||||
isValidPermission,
|
||||
} from "../../utils/permission-catalog.js";
|
||||
|
||||
describe("permission catalog", () => {
|
||||
it("accepts every cataloged permission and group wildcard", () => {
|
||||
for (const entry of PERMISSION_CATALOG) {
|
||||
expect(isValidPermission(`${entry.group}.*`)).toBe(true);
|
||||
for (const permission of entry.permissions) {
|
||||
expect(isValidPermission(permission)).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts the global wildcard", () => {
|
||||
expect(isValidPermission("*")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects unknown permissions and malformed wildcards", () => {
|
||||
expect(isValidPermission("hosts.hack")).toBe(false);
|
||||
expect(isValidPermission("unknown.*")).toBe(false);
|
||||
expect(isValidPermission("")).toBe(false);
|
||||
expect(isValidPermission("hosts")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// permission-manager imports the side-effectful DB barrel and the logger at the
|
||||
// top level. Stub both so importing the module does not spin up the real
|
||||
// database / encryption stack. We then drive hasPermission via a spied
|
||||
// getUserPermissions so we test the wildcard-matching logic in isolation.
|
||||
vi.mock("../../database/db/index.js", () => ({ db: {} }));
|
||||
vi.mock("../../utils/logger.js", () => ({
|
||||
databaseLogger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const accessState = vi.hoisted(() => ({
|
||||
ownerId: "owner" as string,
|
||||
grant: null as {
|
||||
id: number;
|
||||
permissionLevel: string;
|
||||
expiresAt: string | null;
|
||||
} | null,
|
||||
touched: [] as number[],
|
||||
adminIds: new Set<string>(),
|
||||
}));
|
||||
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentHostResolutionRepository: () => ({
|
||||
isHostOwnedByUser: async (_hostId: number, userId: string) =>
|
||||
userId === accessState.ownerId,
|
||||
findHostOwnerId: async () => accessState.ownerId,
|
||||
}),
|
||||
createCurrentRbacAccessRepository: () => ({
|
||||
findActiveHostAccess: async () => accessState.grant,
|
||||
touchHostAccess: async (id: number) => {
|
||||
accessState.touched.push(id);
|
||||
},
|
||||
deleteExpiredHostAccess: async () => 0,
|
||||
}),
|
||||
createCurrentRoleRepository: () => ({
|
||||
listUserRoleIds: async () => [],
|
||||
listUserRolePermissions: async () => [],
|
||||
userHasAnyRoleName: async () => false,
|
||||
}),
|
||||
createCurrentUserRepository: () => ({
|
||||
findById: async (userId: string) =>
|
||||
accessState.adminIds.has(userId) ? { id: userId, isAdmin: true } : null,
|
||||
}),
|
||||
}));
|
||||
|
||||
const { PermissionManager } = await import("../../utils/permission-manager.js");
|
||||
|
||||
type PermissionManagerInstance = ReturnType<
|
||||
typeof PermissionManager.getInstance
|
||||
>;
|
||||
|
||||
describe("PermissionManager.hasPermission wildcard matching", () => {
|
||||
let manager: PermissionManagerInstance;
|
||||
|
||||
function withPermissions(permissions: string[]) {
|
||||
vi.spyOn(manager, "getUserPermissions").mockResolvedValue(permissions);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
manager = PermissionManager.getInstance();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("grants everything for the global wildcard '*'", async () => {
|
||||
withPermissions(["*"]);
|
||||
expect(await manager.hasPermission("u1", "hosts.read")).toBe(true);
|
||||
expect(await manager.hasPermission("u1", "anything.at.all")).toBe(true);
|
||||
});
|
||||
|
||||
it("grants an exact permission match", async () => {
|
||||
withPermissions(["hosts.read", "hosts.write"]);
|
||||
expect(await manager.hasPermission("u1", "hosts.read")).toBe(true);
|
||||
});
|
||||
|
||||
it("grants via a prefix wildcard", async () => {
|
||||
withPermissions(["hosts.*"]);
|
||||
expect(await manager.hasPermission("u1", "hosts.read")).toBe(true);
|
||||
expect(await manager.hasPermission("u1", "hosts.write")).toBe(true);
|
||||
});
|
||||
|
||||
it("grants via a deep prefix wildcard", async () => {
|
||||
withPermissions(["admin.users.*"]);
|
||||
expect(await manager.hasPermission("u1", "admin.users.delete")).toBe(true);
|
||||
});
|
||||
|
||||
it("denies when no exact or wildcard permission matches", async () => {
|
||||
withPermissions(["hosts.read"]);
|
||||
expect(await manager.hasPermission("u1", "hosts.write")).toBe(false);
|
||||
expect(await manager.hasPermission("u1", "credentials.read")).toBe(false);
|
||||
});
|
||||
|
||||
it("denies when the user has no permissions", async () => {
|
||||
withPermissions([]);
|
||||
expect(await manager.hasPermission("u1", "hosts.read")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not let a narrower wildcard grant a sibling branch", async () => {
|
||||
withPermissions(["hosts.read.*"]);
|
||||
expect(await manager.hasPermission("u1", "hosts.write")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PermissionManager.canAccessHost level hierarchy", () => {
|
||||
const manager = PermissionManager.getInstance();
|
||||
const actions = ["connect", "view", "edit", "manage"] as const;
|
||||
const levels = ["connect", "view", "edit", "manage"] as const;
|
||||
const rank = { connect: 1, view: 2, edit: 3, manage: 4 } as const;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
accessState.ownerId = "owner";
|
||||
accessState.grant = null;
|
||||
accessState.touched = [];
|
||||
accessState.adminIds = new Set();
|
||||
});
|
||||
|
||||
it("grants the owner every action including delete", async () => {
|
||||
for (const action of [...actions, "delete"] as const) {
|
||||
const info = await manager.canAccessHost("owner", 42, action);
|
||||
expect(info).toMatchObject({ hasAccess: true, isOwner: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("denies everything without a grant", async () => {
|
||||
const info = await manager.canAccessHost("stranger", 42, "connect");
|
||||
expect(info).toMatchObject({ hasAccess: false, isShared: false });
|
||||
});
|
||||
|
||||
it("enforces the connect < view < edit < manage hierarchy", async () => {
|
||||
for (const level of levels) {
|
||||
accessState.grant = { id: 5, permissionLevel: level, expiresAt: null };
|
||||
for (const action of actions) {
|
||||
const info = await manager.canAccessHost("recipient", 42, action);
|
||||
expect(info.hasAccess).toBe(rank[level] >= rank[action]);
|
||||
expect(info.permissionLevel).toBe(level);
|
||||
expect(info.isShared).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("never grants delete to a shared recipient", async () => {
|
||||
accessState.grant = { id: 5, permissionLevel: "manage", expiresAt: null };
|
||||
const info = await manager.canAccessHost("recipient", 42, "delete");
|
||||
expect(info.hasAccess).toBe(false);
|
||||
});
|
||||
|
||||
it("normalizes the legacy 'view' string mapping and unknown levels to connect", async () => {
|
||||
accessState.grant = { id: 5, permissionLevel: "bogus", expiresAt: null };
|
||||
const connect = await manager.canAccessHost("recipient", 42, "connect");
|
||||
expect(connect.hasAccess).toBe(true);
|
||||
expect(connect.permissionLevel).toBe("connect");
|
||||
|
||||
const view = await manager.canAccessHost("recipient", 42, "view");
|
||||
expect(view.hasAccess).toBe(false);
|
||||
});
|
||||
|
||||
it("only touches the grant timestamp on connect", async () => {
|
||||
accessState.grant = { id: 5, permissionLevel: "manage", expiresAt: null };
|
||||
await manager.canAccessHost("recipient", 42, "manage");
|
||||
expect(accessState.touched).toEqual([]);
|
||||
await manager.canAccessHost("recipient", 42, "connect");
|
||||
expect(accessState.touched).toEqual([5]);
|
||||
});
|
||||
|
||||
it("grants admins owner-equivalent access to any host via bypass", async () => {
|
||||
accessState.adminIds = new Set(["adminUser"]);
|
||||
for (const action of actions) {
|
||||
const info = await manager.canAccessHost("adminUser", 42, action);
|
||||
expect(info).toMatchObject({
|
||||
hasAccess: true,
|
||||
isOwner: false,
|
||||
isAdminBypass: true,
|
||||
permissionLevel: "manage",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("upgrades an under-privileged admin's share access via bypass", async () => {
|
||||
accessState.adminIds = new Set(["adminUser"]);
|
||||
accessState.grant = { id: 7, permissionLevel: "connect", expiresAt: null };
|
||||
const info = await manager.canAccessHost("adminUser", 42, "manage");
|
||||
expect(info).toMatchObject({ hasAccess: true, isAdminBypass: true });
|
||||
});
|
||||
|
||||
it("does not grant a non-admin stranger admin bypass", async () => {
|
||||
const info = await manager.canAccessHost("stranger", 42, "manage");
|
||||
expect(info.hasAccess).toBe(false);
|
||||
expect(info.isAdminBypass).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
getRequestBasePath,
|
||||
getRequestBaseUrl,
|
||||
getRequestBaseUrlWithForceHTTPS,
|
||||
getRequestOrigin,
|
||||
normalizeBasePath,
|
||||
} from "../../utils/request-origin.js";
|
||||
|
||||
function request(headers: Record<string, string | string[] | undefined>) {
|
||||
return {
|
||||
headers,
|
||||
socket: {},
|
||||
} as Parameters<typeof getRequestBasePath>[0];
|
||||
}
|
||||
|
||||
function restoreEnv(name: string, value: string | undefined) {
|
||||
if (value === undefined) {
|
||||
delete process.env[name];
|
||||
} else {
|
||||
process.env[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
describe("normalizeBasePath", () => {
|
||||
it("normalizes empty and root paths", () => {
|
||||
expect(normalizeBasePath("")).toBe("");
|
||||
expect(normalizeBasePath("/")).toBe("");
|
||||
expect(normalizeBasePath(" / ")).toBe("");
|
||||
});
|
||||
|
||||
it("normalizes configured base paths", () => {
|
||||
expect(normalizeBasePath("termix")).toBe("/termix");
|
||||
expect(normalizeBasePath("/termix/")).toBe("/termix");
|
||||
expect(normalizeBasePath("/termix, /other")).toBe("/termix");
|
||||
});
|
||||
|
||||
it("accepts forwarded prefix values that include a URL", () => {
|
||||
expect(normalizeBasePath("https://example.com/termix/")).toBe("/termix");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getRequestBasePath", () => {
|
||||
const previousBasePath = process.env.BASE_PATH;
|
||||
const previousViteBasePath = process.env.VITE_BASE_PATH;
|
||||
const previousForceHttps = process.env.OIDC_FORCE_HTTPS;
|
||||
|
||||
afterEach(() => {
|
||||
restoreEnv("BASE_PATH", previousBasePath);
|
||||
restoreEnv("VITE_BASE_PATH", previousViteBasePath);
|
||||
restoreEnv("OIDC_FORCE_HTTPS", previousForceHttps);
|
||||
});
|
||||
|
||||
it("uses BASE_PATH before forwarded headers", () => {
|
||||
process.env.BASE_PATH = "/admin/";
|
||||
process.env.VITE_BASE_PATH = "";
|
||||
|
||||
expect(
|
||||
getRequestBasePath(request({ "x-forwarded-prefix": "/termix" })),
|
||||
).toBe("/admin");
|
||||
});
|
||||
|
||||
it("falls back to VITE_BASE_PATH for deployments that already set it", () => {
|
||||
process.env.BASE_PATH = "";
|
||||
process.env.VITE_BASE_PATH = "/termix/";
|
||||
|
||||
expect(getRequestBasePath(request({}))).toBe("/termix");
|
||||
});
|
||||
|
||||
it("uses X-Forwarded-Prefix when no env base path is set", () => {
|
||||
process.env.BASE_PATH = "";
|
||||
process.env.VITE_BASE_PATH = "";
|
||||
|
||||
expect(
|
||||
getRequestBasePath(request({ "x-forwarded-prefix": "/termix/" })),
|
||||
).toBe("/termix");
|
||||
});
|
||||
|
||||
it("builds a public base URL with forwarded origin and prefix", () => {
|
||||
process.env.BASE_PATH = "";
|
||||
process.env.VITE_BASE_PATH = "";
|
||||
|
||||
expect(
|
||||
getRequestBaseUrl(
|
||||
request({
|
||||
"x-forwarded-proto": "https",
|
||||
"x-forwarded-host": "example.com",
|
||||
"x-forwarded-prefix": "/termix",
|
||||
}),
|
||||
),
|
||||
).toBe("https://example.com/termix");
|
||||
});
|
||||
|
||||
it("applies OIDC_FORCE_HTTPS to public base URLs", () => {
|
||||
process.env.BASE_PATH = "";
|
||||
process.env.VITE_BASE_PATH = "";
|
||||
process.env.OIDC_FORCE_HTTPS = "true";
|
||||
|
||||
expect(
|
||||
getRequestBaseUrlWithForceHTTPS(
|
||||
request({
|
||||
"x-forwarded-proto": "http",
|
||||
"x-forwarded-host": "example.com",
|
||||
"x-forwarded-prefix": "/termix",
|
||||
}),
|
||||
),
|
||||
).toBe("https://example.com/termix");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getRequestOrigin", () => {
|
||||
it("ignores non-numeric forwarded ports", () => {
|
||||
expect(
|
||||
getRequestOrigin(
|
||||
request({
|
||||
"x-forwarded-proto": "https",
|
||||
"x-forwarded-host": "termix.test.de",
|
||||
"x-forwarded-port": "{server_port}",
|
||||
}),
|
||||
),
|
||||
).toBe("https://termix.test.de");
|
||||
});
|
||||
|
||||
it("drops invalid ports embedded in forwarded hosts", () => {
|
||||
expect(
|
||||
getRequestOrigin(
|
||||
request({
|
||||
"x-forwarded-proto": "https",
|
||||
"x-forwarded-host": "termix.test.de:{server_port}",
|
||||
}),
|
||||
),
|
||||
).toBe("https://termix.test.de");
|
||||
});
|
||||
|
||||
it("keeps valid non-default forwarded ports", () => {
|
||||
expect(
|
||||
getRequestOrigin(
|
||||
request({
|
||||
"x-forwarded-proto": "https",
|
||||
"x-forwarded-host": "termix.test.de",
|
||||
"x-forwarded-port": "8443",
|
||||
}),
|
||||
),
|
||||
).toBe("https://termix.test.de:8443");
|
||||
});
|
||||
|
||||
it("omits default forwarded ports", () => {
|
||||
expect(
|
||||
getRequestOrigin(
|
||||
request({
|
||||
"x-forwarded-proto": "https",
|
||||
"x-forwarded-host": "termix.test.de",
|
||||
"x-forwarded-port": "443",
|
||||
}),
|
||||
),
|
||||
).toBe("https://termix.test.de");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,347 @@
|
||||
import crypto from "crypto";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const ownerDEK = crypto.randomBytes(32);
|
||||
const targetDEK = crypto.randomBytes(32);
|
||||
|
||||
type SecretRow = Record<string, unknown> & {
|
||||
id: number;
|
||||
hostAccessId: number;
|
||||
targetUserId: string;
|
||||
protocol: string;
|
||||
};
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
hosts: new Map<number, Record<string, unknown>>(),
|
||||
credentials: new Map<number, Record<string, unknown>>(),
|
||||
secretRows: [] as Array<Record<string, unknown>>,
|
||||
// hostAccessId -> hostId, used by findForHostUserProtocol
|
||||
accessToHost: new Map<number, number>(),
|
||||
grants: [] as Array<Record<string, unknown>>,
|
||||
roleMembers: new Map<number, string[]>(),
|
||||
}));
|
||||
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
createCurrentHostResolutionRepository: () => ({
|
||||
findHostById: async (hostId: number) => state.hosts.get(hostId) ?? null,
|
||||
findHostOwnerId: async (hostId: number) =>
|
||||
(state.hosts.get(hostId)?.userId as string) ?? null,
|
||||
findCredentialByIdForUser: async (credentialId: number) =>
|
||||
state.credentials.get(credentialId) ?? null,
|
||||
}),
|
||||
createCurrentSharedHostSecretsRepository: () => ({
|
||||
upsert: async (row: Record<string, unknown>) => {
|
||||
const existing = state.secretRows.find(
|
||||
(r) =>
|
||||
r.hostAccessId === row.hostAccessId &&
|
||||
r.targetUserId === row.targetUserId &&
|
||||
r.protocol === row.protocol,
|
||||
);
|
||||
if (existing) Object.assign(existing, row);
|
||||
else state.secretRows.push({ id: state.secretRows.length + 1, ...row });
|
||||
},
|
||||
deleteForHostAccessAndTarget: async (
|
||||
hostAccessId: number,
|
||||
targetUserId: string,
|
||||
keepProtocols: string[],
|
||||
) => {
|
||||
state.secretRows = state.secretRows.filter(
|
||||
(r) =>
|
||||
!(
|
||||
r.hostAccessId === hostAccessId &&
|
||||
r.targetUserId === targetUserId &&
|
||||
!keepProtocols.includes(r.protocol as string)
|
||||
),
|
||||
);
|
||||
},
|
||||
findForHostUserProtocol: async (
|
||||
hostId: number,
|
||||
targetUserId: string,
|
||||
protocol: string,
|
||||
) =>
|
||||
state.secretRows.find(
|
||||
(r) =>
|
||||
state.accessToHost.get(r.hostAccessId as number) === hostId &&
|
||||
r.targetUserId === targetUserId &&
|
||||
r.protocol === protocol,
|
||||
) ?? null,
|
||||
deleteByHostAccessId: async () => 0,
|
||||
deleteByTargetUserId: async () => 0,
|
||||
deleteByOriginalCredentialId: async () => 0,
|
||||
findHostIdsReferencingCredential: async (
|
||||
_ownerId: string,
|
||||
credentialId: number,
|
||||
) =>
|
||||
[...state.hosts.values()]
|
||||
.filter((h) => h.credentialId === credentialId)
|
||||
.map((h) => h.id as number),
|
||||
}),
|
||||
createCurrentRbacAccessRepository: () => ({
|
||||
listActiveHostAccessGrants: async (hostId: number) =>
|
||||
state.grants.filter((g) => g.hostId === hostId),
|
||||
listRoleHostAccessCredentialSources: async (roleId: number) =>
|
||||
state.grants
|
||||
.filter((g) => g.roleId === roleId)
|
||||
.map((g) => ({
|
||||
hostAccessId: g.id,
|
||||
hostId: g.hostId,
|
||||
hostOwnerId: state.hosts.get(g.hostId as number)?.userId,
|
||||
})),
|
||||
}),
|
||||
createCurrentRoleRepository: () => ({
|
||||
listRoleUserIds: async (roleId: number) =>
|
||||
state.roleMembers.get(roleId) ?? [],
|
||||
listUserRoleIds: async () => [],
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/data-crypto.js", () => ({
|
||||
DataCrypto: {
|
||||
validateUserAccess: (userId: string) => {
|
||||
if (userId === "owner") return ownerDEK;
|
||||
if (userId === "target" || userId === "member-1") return targetDEK;
|
||||
throw new Error(`User ${userId} has no data encryption key`);
|
||||
},
|
||||
getUserDataKey: (userId: string) =>
|
||||
userId === "owner"
|
||||
? ownerDEK
|
||||
: userId === "target" || userId === "member-1"
|
||||
? targetDEK
|
||||
: null,
|
||||
canUserAccessData: () => true,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../utils/logger.js", () => ({
|
||||
databaseLogger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
import { FieldCrypto } from "../../utils/field-crypto.js";
|
||||
import { SharedHostSecretsManager } from "../../utils/shared-host-secrets-manager.js";
|
||||
|
||||
const manager = SharedHostSecretsManager.getInstance();
|
||||
|
||||
function baseHost(overrides: Record<string, unknown> = {}) {
|
||||
// Records come back from the resolution repository already decrypted.
|
||||
return {
|
||||
id: 42,
|
||||
userId: "owner",
|
||||
connectionType: "ssh",
|
||||
name: "prod",
|
||||
ip: "10.0.0.42",
|
||||
username: "root",
|
||||
authType: "password",
|
||||
password: "hunter2",
|
||||
key: null,
|
||||
keyPassword: null,
|
||||
keyType: null,
|
||||
credentialId: null,
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
state.hosts.clear();
|
||||
state.credentials.clear();
|
||||
state.secretRows = [];
|
||||
state.accessToHost = new Map([[7, 42]]);
|
||||
state.grants = [];
|
||||
state.roleMembers.clear();
|
||||
});
|
||||
|
||||
describe("SharedHostSecretsManager", () => {
|
||||
it("snapshots an inline-password SSH host and the target can decrypt it", async () => {
|
||||
state.hosts.set(42, baseHost());
|
||||
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
|
||||
expect(state.secretRows).toHaveLength(1);
|
||||
const row = state.secretRows[0];
|
||||
expect(row.protocol).toBe("ssh");
|
||||
expect(row.sourceType).toBe("inline");
|
||||
expect(row.encryptedPassword).not.toBe("hunter2");
|
||||
|
||||
const secret = await manager.getSecretForUser(42, "target", "ssh");
|
||||
expect(secret).toMatchObject({
|
||||
username: "root",
|
||||
authType: "password",
|
||||
password: "hunter2",
|
||||
});
|
||||
});
|
||||
|
||||
it("snapshots every enabled protocol from credential and inline sources", async () => {
|
||||
state.credentials.set(123, {
|
||||
id: 123,
|
||||
userId: "owner",
|
||||
username: "cred-user",
|
||||
authType: "key",
|
||||
password: null,
|
||||
privateKey: "PRIVATE-KEY",
|
||||
key: null,
|
||||
keyPassword: "kp",
|
||||
keyType: "ssh-ed25519",
|
||||
});
|
||||
state.hosts.set(
|
||||
42,
|
||||
baseHost({
|
||||
authType: "credential",
|
||||
credentialId: 123,
|
||||
password: null,
|
||||
enableRdp: true,
|
||||
rdpUser: "rdp-admin",
|
||||
rdpPassword: "rdp-pass",
|
||||
rdpDomain: "CORP",
|
||||
enableTelnet: true,
|
||||
telnetUser: "tel-user",
|
||||
telnetPassword: "tel-pass",
|
||||
}),
|
||||
);
|
||||
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
|
||||
expect(state.secretRows.map((row) => row.protocol).sort()).toEqual([
|
||||
"rdp",
|
||||
"ssh",
|
||||
"telnet",
|
||||
]);
|
||||
|
||||
const ssh = await manager.getSecretForUser(42, "target", "ssh");
|
||||
expect(ssh).toMatchObject({
|
||||
username: "cred-user",
|
||||
authType: "key",
|
||||
key: "PRIVATE-KEY",
|
||||
keyPassword: "kp",
|
||||
keyType: "ssh-ed25519",
|
||||
});
|
||||
|
||||
const rdp = await manager.getSecretForUser(42, "target", "rdp");
|
||||
expect(rdp).toMatchObject({
|
||||
username: "rdp-admin",
|
||||
password: "rdp-pass",
|
||||
domain: "CORP",
|
||||
authType: "direct",
|
||||
});
|
||||
|
||||
const telnet = await manager.getSecretForUser(42, "target", "telnet");
|
||||
expect(telnet).toMatchObject({
|
||||
username: "tel-user",
|
||||
password: "tel-pass",
|
||||
});
|
||||
});
|
||||
|
||||
it("produces no snapshot rows for secret-less auth types", async () => {
|
||||
state.hosts.set(42, baseHost({ authType: "opkssh", password: null }));
|
||||
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
expect(state.secretRows).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("removes stale protocol rows on re-snapshot", async () => {
|
||||
state.hosts.set(
|
||||
42,
|
||||
baseHost({
|
||||
enableRdp: true,
|
||||
rdpUser: "rdp-admin",
|
||||
rdpPassword: "rdp-pass",
|
||||
}),
|
||||
);
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
expect(state.secretRows).toHaveLength(2);
|
||||
|
||||
// Owner turns RDP off; the RDP snapshot must disappear.
|
||||
state.hosts.set(42, baseHost());
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
expect(state.secretRows.map((row) => row.protocol)).toEqual(["ssh"]);
|
||||
});
|
||||
|
||||
it("fails fast when a participant has no DEK", async () => {
|
||||
state.hosts.set(42, baseHost());
|
||||
await expect(
|
||||
manager.snapshotForUser(7, 42, "locked-user", "owner"),
|
||||
).rejects.toThrow(/no data encryption key/);
|
||||
expect(state.secretRows).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("cannot be decrypted with the wrong DEK", async () => {
|
||||
state.hosts.set(42, baseHost());
|
||||
await manager.snapshotForUser(7, 42, "target", "owner");
|
||||
|
||||
const row = state.secretRows[0];
|
||||
expect(() =>
|
||||
FieldCrypto.decryptField(
|
||||
row.encryptedPassword as string,
|
||||
ownerDEK,
|
||||
"shared-7-target-ssh",
|
||||
"password",
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("resyncHost re-snapshots direct grants and role members", async () => {
|
||||
state.hosts.set(42, baseHost());
|
||||
state.accessToHost = new Map([
|
||||
[1, 42],
|
||||
[2, 42],
|
||||
]);
|
||||
state.grants = [
|
||||
{ id: 1, hostId: 42, userId: "target", roleId: null },
|
||||
{ id: 2, hostId: 42, userId: null, roleId: 9 },
|
||||
];
|
||||
state.roleMembers.set(9, ["member-1", "owner"]);
|
||||
|
||||
await manager.resyncHost(42);
|
||||
|
||||
// target via grant 1, member-1 via grant 2; owner skipped.
|
||||
expect(
|
||||
state.secretRows.map((row) => [row.hostAccessId, row.targetUserId]),
|
||||
).toEqual([
|
||||
[1, "target"],
|
||||
[2, "member-1"],
|
||||
]);
|
||||
|
||||
// Owner rotates the inline password; resync updates the copies.
|
||||
state.hosts.set(42, baseHost({ password: "rotated" }));
|
||||
await manager.resyncHost(42);
|
||||
|
||||
const secret = await manager.getSecretForUser(42, "target", "ssh");
|
||||
expect(secret?.password).toBe("rotated");
|
||||
});
|
||||
|
||||
it("snapshotForRoleMember fans out from role grants", async () => {
|
||||
state.hosts.set(42, baseHost());
|
||||
state.accessToHost = new Map([[2, 42]]);
|
||||
state.grants = [{ id: 2, hostId: 42, userId: null, roleId: 9 }];
|
||||
|
||||
await manager.snapshotForRoleMember(9, "member-1");
|
||||
|
||||
expect(state.secretRows).toHaveLength(1);
|
||||
expect(state.secretRows[0]).toMatchObject({
|
||||
hostAccessId: 2,
|
||||
targetUserId: "member-1",
|
||||
protocol: "ssh",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import {
|
||||
parseSSHKey,
|
||||
parsePublicKey,
|
||||
preparePrivateKeyForSSH2,
|
||||
getFriendlyKeyTypeName,
|
||||
validateKeyPair,
|
||||
} from "../../utils/ssh-key-utils.js";
|
||||
|
||||
// A real OpenSSH ed25519 keypair generated solely for these tests. It grants no
|
||||
// access to anything and exists only so the ssh2 parsing path is exercised for
|
||||
// real rather than only via the text-fallback heuristics.
|
||||
const ED25519_PRIVATE = `-----BEGIN OPENSSH PRIVATE KEY-----
|
||||
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
|
||||
QyNTUxOQAAACBR/hJLX7eMinS4wJMfG2gWSttUiuSLvqDwVYT53x0qewAAAJihJo4koSaO
|
||||
JAAAAAtzc2gtZWQyNTUxOQAAACBR/hJLX7eMinS4wJMfG2gWSttUiuSLvqDwVYT53x0qew
|
||||
AAAEDLo85Twyg0v6V1zsJaeRaxq9KPQXkqGY0HiJtVMzCXEFH+Ektft4yKdLjAkx8baBZK
|
||||
21SK5Iu+oPBVhPnfHSp7AAAAEHRlc3RAdGVybWl4LnRlc3QBAgMEBQ==
|
||||
-----END OPENSSH PRIVATE KEY-----`;
|
||||
|
||||
const ED25519_PUBLIC =
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFH+Ektft4yKdLjAkx8baBZK21SK5Iu+oPBVhPnfHSp7 test@termix.test";
|
||||
|
||||
const PPK_RSA_PRIVATE = readFileSync(
|
||||
"node_modules/ssh2/test/fixtures/keyParser/ppk_rsa",
|
||||
"utf8",
|
||||
);
|
||||
|
||||
describe("parsePublicKey", () => {
|
||||
it("detects ssh-ed25519 public keys", () => {
|
||||
const info = parsePublicKey(ED25519_PUBLIC);
|
||||
expect(info.keyType).toBe("ssh-ed25519");
|
||||
expect(info.success).toBe(true);
|
||||
});
|
||||
|
||||
it("detects ssh-rsa public keys", () => {
|
||||
const info = parsePublicKey("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABFakeData");
|
||||
expect(info.keyType).toBe("ssh-rsa");
|
||||
expect(info.success).toBe(true);
|
||||
});
|
||||
|
||||
it("detects ecdsa public keys", () => {
|
||||
const info = parsePublicKey(
|
||||
"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYData",
|
||||
);
|
||||
expect(info.keyType).toBe("ecdsa-sha2-nistp256");
|
||||
});
|
||||
|
||||
it("detects OpenSSH certificate types before plain types", () => {
|
||||
const info = parsePublicKey(
|
||||
"ssh-ed25519-cert-v01@openssh.com AAAAData comment",
|
||||
);
|
||||
expect(info.keyType).toBe("ssh-ed25519-cert-v01@openssh.com");
|
||||
});
|
||||
|
||||
it("returns unknown for unrecognized content", () => {
|
||||
const info = parsePublicKey("not-a-key");
|
||||
expect(info.keyType).toBe("unknown");
|
||||
expect(info.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseSSHKey", () => {
|
||||
it("parses a valid ed25519 private key and derives its type", () => {
|
||||
const info = parseSSHKey(ED25519_PRIVATE);
|
||||
expect(info.success).toBe(true);
|
||||
expect(info.keyType).toContain("ed25519");
|
||||
// ssh2 successfully derives the public key for a real OpenSSH key.
|
||||
expect(info.publicKey).toContain("ssh-ed25519");
|
||||
});
|
||||
|
||||
it("reports failure for garbage input", () => {
|
||||
const info = parseSSHKey("definitely not a key");
|
||||
expect(info.success).toBe(false);
|
||||
expect(info.keyType).toBe("unknown");
|
||||
});
|
||||
|
||||
it("accepts PuTTY PPK v2 private keys supported by ssh2", () => {
|
||||
const info = parseSSHKey(PPK_RSA_PRIVATE);
|
||||
expect(info.success).toBe(true);
|
||||
expect(info.keyType).toBe("ssh-rsa");
|
||||
expect(info.publicKey).toContain("ssh-rsa");
|
||||
});
|
||||
|
||||
it("prepares PuTTY PPK v2 private keys for ssh2 connections", () => {
|
||||
const prepared = preparePrivateKeyForSSH2(PPK_RSA_PRIVATE);
|
||||
expect(prepared.toString("utf8")).toContain("PuTTY-User-Key-File-2");
|
||||
});
|
||||
|
||||
it("reports unsupported PuTTY PPK versions clearly", () => {
|
||||
const info = parseSSHKey(
|
||||
"PuTTY-User-Key-File-3: ssh-ed25519\nEncryption: none\n",
|
||||
);
|
||||
expect(info.success).toBe(false);
|
||||
expect(info.error).toMatch(/Unsupported PuTTY PPK v3/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFriendlyKeyTypeName", () => {
|
||||
it("maps known key types to friendly names", () => {
|
||||
expect(getFriendlyKeyTypeName("ssh-rsa")).toBe("RSA");
|
||||
expect(getFriendlyKeyTypeName("ssh-ed25519")).toBe("Ed25519");
|
||||
expect(getFriendlyKeyTypeName("ecdsa-sha2-nistp256")).toBe("ECDSA P-256");
|
||||
expect(getFriendlyKeyTypeName("ssh-dss")).toBe("DSA");
|
||||
});
|
||||
|
||||
it("passes unknown types through unchanged", () => {
|
||||
expect(getFriendlyKeyTypeName("some-future-type")).toBe("some-future-type");
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateKeyPair", () => {
|
||||
it("validates a genuinely matching ed25519 key pair", () => {
|
||||
const result = validateKeyPair(ED25519_PRIVATE, ED25519_PUBLIC);
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.privateKeyType).toContain("ed25519");
|
||||
expect(result.publicKeyType).toBe("ssh-ed25519");
|
||||
});
|
||||
|
||||
it("fails when private and public key types mismatch", () => {
|
||||
const result = validateKeyPair(
|
||||
ED25519_PRIVATE,
|
||||
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABFakeData",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.error).toMatch(/mismatch|match/i);
|
||||
});
|
||||
|
||||
it("fails when the public key is invalid", () => {
|
||||
const result = validateKeyPair(ED25519_PRIVATE, "garbage");
|
||||
expect(result.isValid).toBe(false);
|
||||
});
|
||||
|
||||
it("fails when the private key is invalid", () => {
|
||||
const result = validateKeyPair(
|
||||
"garbage",
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAData",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.error).toMatch(/private key/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import type { Request } from "express";
|
||||
import {
|
||||
detectPlatform,
|
||||
parseUserAgent,
|
||||
generateDeviceFingerprint,
|
||||
} from "../../utils/user-agent-parser.js";
|
||||
|
||||
function reqWith(headers: Record<string, string>): Request {
|
||||
return { headers } as unknown as Request;
|
||||
}
|
||||
|
||||
describe("detectPlatform", () => {
|
||||
it("detects desktop from the x-electron-app header", () => {
|
||||
expect(detectPlatform(reqWith({ "x-electron-app": "true" }))).toBe(
|
||||
"desktop",
|
||||
);
|
||||
});
|
||||
|
||||
it("detects desktop from a Termix-Desktop user agent", () => {
|
||||
expect(
|
||||
detectPlatform(reqWith({ "user-agent": "Termix-Desktop/1.0 (Windows)" })),
|
||||
).toBe("desktop");
|
||||
});
|
||||
|
||||
it("detects mobile from a Termix-Mobile user agent", () => {
|
||||
expect(
|
||||
detectPlatform(reqWith({ "user-agent": "Termix-Mobile/Android 1.0" })),
|
||||
).toBe("mobile");
|
||||
});
|
||||
|
||||
it("detects mobile phones/tablets", () => {
|
||||
expect(
|
||||
detectPlatform(reqWith({ "user-agent": "Mozilla/5.0 (iPhone; ...)" })),
|
||||
).toBe("mobile");
|
||||
});
|
||||
|
||||
it("treats Android-on-desktop-OS as web", () => {
|
||||
expect(
|
||||
detectPlatform(
|
||||
reqWith({ "user-agent": "Mozilla/5.0 (X11; Linux x86_64) Android" }),
|
||||
),
|
||||
).toBe("web");
|
||||
});
|
||||
|
||||
it("defaults to web for a desktop browser", () => {
|
||||
expect(
|
||||
detectPlatform(
|
||||
reqWith({
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0) Chrome/120.0",
|
||||
}),
|
||||
),
|
||||
).toBe("web");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseUserAgent", () => {
|
||||
it("parses a Chrome-on-Windows web client", () => {
|
||||
const info = parseUserAgent(
|
||||
reqWith({
|
||||
"user-agent":
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.71 Safari/537.36",
|
||||
}),
|
||||
);
|
||||
expect(info.type).toBe("web");
|
||||
expect(info.browser).toBe("Chrome");
|
||||
expect(info.version).toBe("120.0");
|
||||
expect(info.os).toBe("Windows 10/11");
|
||||
});
|
||||
|
||||
it("parses Edge distinctly from Chrome", () => {
|
||||
const info = parseUserAgent(
|
||||
reqWith({
|
||||
"user-agent":
|
||||
"Mozilla/5.0 (Windows NT 10.0) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
|
||||
}),
|
||||
);
|
||||
expect(info.browser).toBe("Edge");
|
||||
});
|
||||
|
||||
it("parses a Termix desktop user agent", () => {
|
||||
const info = parseUserAgent(
|
||||
reqWith({ "user-agent": "Termix-Desktop/2.3.1 (macOS; arm64)" }),
|
||||
);
|
||||
expect(info.type).toBe("desktop");
|
||||
expect(info.browser).toBe("Termix Desktop");
|
||||
expect(info.version).toBe("2.3.1");
|
||||
expect(info.os).toBe("macOS");
|
||||
});
|
||||
|
||||
it("parses an iOS mobile user agent", () => {
|
||||
const info = parseUserAgent(
|
||||
reqWith({ "user-agent": "Termix-Mobile/iOS1.5 (OS 17_2)" }),
|
||||
);
|
||||
expect(info.type).toBe("mobile");
|
||||
expect(info.os).toContain("iOS");
|
||||
});
|
||||
});
|
||||
|
||||
describe("generateDeviceFingerprint", () => {
|
||||
it("is stable across minor browser version bumps on web", () => {
|
||||
const a = generateDeviceFingerprint({
|
||||
type: "web",
|
||||
browser: "Chrome",
|
||||
version: "120.5",
|
||||
os: "Windows 10/11",
|
||||
deviceInfo: "Chrome 120.5 on Windows 10/11",
|
||||
});
|
||||
const b = generateDeviceFingerprint({
|
||||
type: "web",
|
||||
browser: "Chrome",
|
||||
version: "120.9",
|
||||
os: "Windows 10/11",
|
||||
deviceInfo: "Chrome 120.9 on Windows 10/11",
|
||||
});
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it("differs across major browser versions on web", () => {
|
||||
const a = generateDeviceFingerprint({
|
||||
type: "web",
|
||||
browser: "Chrome",
|
||||
version: "120.0",
|
||||
os: "Windows 10/11",
|
||||
deviceInfo: "",
|
||||
});
|
||||
const b = generateDeviceFingerprint({
|
||||
type: "web",
|
||||
browser: "Chrome",
|
||||
version: "121.0",
|
||||
os: "Windows 10/11",
|
||||
deviceInfo: "",
|
||||
});
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
|
||||
it("produces a 64-char hex sha256 digest", () => {
|
||||
const fp = generateDeviceFingerprint({
|
||||
type: "desktop",
|
||||
browser: "Termix Desktop",
|
||||
version: "2.3.1",
|
||||
os: "macOS",
|
||||
deviceInfo: "",
|
||||
});
|
||||
expect(fp).toMatch(/^[0-9a-f]{64}$/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { RawSqliteUserEncryptionMigrationStore } from "../../utils/user-encryption-migration-store.js";
|
||||
|
||||
describe("RawSqliteUserEncryptionMigrationStore", () => {
|
||||
function createDb() {
|
||||
const all = vi.fn(() => [{ id: 1 }]);
|
||||
const get = vi.fn(() => ({ id: "user-1" }));
|
||||
const run = vi.fn();
|
||||
const prepare = vi.fn(() => ({ all, get, run }));
|
||||
|
||||
return { db: { prepare }, all, get, run };
|
||||
}
|
||||
|
||||
it("owns legacy user encryption migration reads", () => {
|
||||
const { db, all, get } = 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 = ?",
|
||||
);
|
||||
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", () => {
|
||||
const { db, run } = createDb();
|
||||
const store = new RawSqliteUserEncryptionMigrationStore(db);
|
||||
|
||||
store.updateHostSensitiveFields(12, {
|
||||
password: "p",
|
||||
key: "k",
|
||||
key_password: "kp",
|
||||
key_type: "ed25519",
|
||||
autostart_password: "ap",
|
||||
autostart_key: "ak",
|
||||
autostart_key_password: "akp",
|
||||
sudo_password: "sp",
|
||||
});
|
||||
store.updateCredentialSensitiveFields(13, {
|
||||
password: "p",
|
||||
key: "k",
|
||||
key_password: "kp",
|
||||
private_key: "priv",
|
||||
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"),
|
||||
);
|
||||
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", "priv", "pub", "rsa", 13);
|
||||
expect(run).toHaveBeenCalledWith(
|
||||
"totp",
|
||||
"codes",
|
||||
"client",
|
||||
"oidc",
|
||||
"user-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("owns password-reset dynamic field updates", () => {
|
||||
const { db, run } = createDb();
|
||||
const store = new RawSqliteUserEncryptionMigrationStore(db);
|
||||
|
||||
store.updatePasswordResetFields(
|
||||
"ssh_credentials",
|
||||
99,
|
||||
["password", "key"],
|
||||
{ password: "p", key: "k" },
|
||||
);
|
||||
|
||||
expect(db.prepare).toHaveBeenCalledWith(
|
||||
"UPDATE ssh_credentials SET password = ?, key = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
);
|
||||
expect(run).toHaveBeenCalledWith("p", "k", 99);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
import crypto from "crypto";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const settingsStore = new Map<string, string>();
|
||||
|
||||
vi.mock("../../database/repositories/factory.js", () => ({
|
||||
getCurrentSettingValue: (key: string) => settingsStore.get(key) ?? null,
|
||||
createCurrentSettingsRepository: () => ({
|
||||
upsert: async (key: string, value: string) => {
|
||||
settingsStore.set(key, value);
|
||||
},
|
||||
delete: async (key: string) => {
|
||||
settingsStore.delete(key);
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
import {
|
||||
UserKeyManager,
|
||||
UserKeyUnavailableError,
|
||||
userDekSettingsKey,
|
||||
} from "../../utils/user-keys.js";
|
||||
|
||||
const masterKey = crypto.randomBytes(32);
|
||||
const manager = UserKeyManager.getInstance();
|
||||
|
||||
function storedWrap(userId: string): Record<string, unknown> {
|
||||
return JSON.parse(settingsStore.get(userDekSettingsKey(userId))!);
|
||||
}
|
||||
|
||||
function putWrap(userId: string, wrap: Record<string, unknown>): void {
|
||||
settingsStore.set(userDekSettingsKey(userId), JSON.stringify(wrap));
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
settingsStore.clear();
|
||||
await manager.initialize(masterKey);
|
||||
});
|
||||
|
||||
describe("UserKeyManager", () => {
|
||||
it("creates and round-trips a DEK", async () => {
|
||||
const dek = await manager.createUserDEK("user-1");
|
||||
|
||||
expect(dek).toHaveLength(32);
|
||||
expect(manager.hasUserDEK("user-1")).toBe(true);
|
||||
|
||||
manager.clearCache();
|
||||
expect(manager.getUserDEK("user-1").equals(dek)).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses to create a second DEK for the same user", async () => {
|
||||
await manager.createUserDEK("user-1");
|
||||
await expect(manager.createUserDEK("user-1")).rejects.toThrow(
|
||||
/already has a data encryption key/,
|
||||
);
|
||||
});
|
||||
|
||||
it("throws missing for a user with no wrap and no legacy rows", () => {
|
||||
expect(() => manager.getUserDEK("ghost")).toThrow(UserKeyUnavailableError);
|
||||
try {
|
||||
manager.getUserDEK("ghost");
|
||||
} catch (error) {
|
||||
expect((error as UserKeyUnavailableError).reason).toBe("missing");
|
||||
}
|
||||
expect(manager.tryGetUserDEK("ghost")).toBeNull();
|
||||
});
|
||||
|
||||
it("throws pending_migration when only legacy wrap rows exist", () => {
|
||||
settingsStore.set("user_encrypted_dek_legacy-user", "{}");
|
||||
try {
|
||||
manager.getUserDEK("legacy-user");
|
||||
expect.unreachable();
|
||||
} catch (error) {
|
||||
expect((error as UserKeyUnavailableError).reason).toBe(
|
||||
"pending_migration",
|
||||
);
|
||||
}
|
||||
|
||||
settingsStore.clear();
|
||||
settingsStore.set("user_kek_salt_legacy-user", "{}");
|
||||
try {
|
||||
manager.getUserDEK("legacy-user");
|
||||
expect.unreachable();
|
||||
} catch (error) {
|
||||
expect((error as UserKeyUnavailableError).reason).toBe(
|
||||
"pending_migration",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("fails to unwrap with a different master key", async () => {
|
||||
const dek = await manager.createUserDEK("user-1");
|
||||
|
||||
await manager.initialize(crypto.randomBytes(32));
|
||||
expect(() => manager.getUserDEK("user-1")).toThrow();
|
||||
|
||||
await manager.initialize(masterKey);
|
||||
expect(manager.getUserDEK("user-1").equals(dek)).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects tampered iv, ciphertext and tag", async () => {
|
||||
await manager.createUserDEK("user-1");
|
||||
|
||||
for (const field of ["iv", "ct", "tag"] as const) {
|
||||
const wrap = storedWrap("user-1");
|
||||
const bytes = Buffer.from(wrap[field] as string, "base64");
|
||||
bytes[0] ^= 0xff;
|
||||
putWrap("user-1", { ...wrap, [field]: bytes.toString("base64") });
|
||||
manager.clearCache();
|
||||
expect(() => manager.getUserDEK("user-1")).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a wrap moved to another user (AAD/info binding)", async () => {
|
||||
await manager.createUserDEK("user-a");
|
||||
|
||||
putWrap("user-b", storedWrap("user-a"));
|
||||
manager.clearCache();
|
||||
expect(() => manager.getUserDEK("user-b")).toThrow();
|
||||
});
|
||||
|
||||
it("rejects unknown wrap versions and algorithms", async () => {
|
||||
await manager.createUserDEK("user-1");
|
||||
|
||||
const wrap = storedWrap("user-1");
|
||||
putWrap("user-1", { ...wrap, v: 99 });
|
||||
manager.clearCache();
|
||||
expect(() => manager.getUserDEK("user-1")).toThrow(/Unsupported key wrap/);
|
||||
|
||||
putWrap("user-1", { ...wrap, alg: "aes-128-gcm" });
|
||||
manager.clearCache();
|
||||
expect(() => manager.getUserDEK("user-1")).toThrow(/Unsupported key wrap/);
|
||||
});
|
||||
|
||||
it("persistDEK overwrites and rotateUserDEK replaces the key", async () => {
|
||||
const original = await manager.createUserDEK("user-1");
|
||||
const rotated = await manager.rotateUserDEK("user-1");
|
||||
|
||||
expect(rotated.equals(original)).toBe(false);
|
||||
manager.clearCache();
|
||||
expect(manager.getUserDEK("user-1").equals(rotated)).toBe(true);
|
||||
});
|
||||
|
||||
it("deleteUserDEK removes the wrap and cached key", async () => {
|
||||
await manager.createUserDEK("user-1");
|
||||
await manager.deleteUserDEK("user-1");
|
||||
|
||||
expect(manager.hasUserDEK("user-1")).toBe(false);
|
||||
expect(manager.tryGetUserDEK("user-1")).toBeNull();
|
||||
});
|
||||
|
||||
it("serves cached DEKs without re-reading settings", async () => {
|
||||
const dek = await manager.createUserDEK("user-1");
|
||||
|
||||
settingsStore.delete(userDekSettingsKey("user-1"));
|
||||
expect(manager.getUserDEK("user-1").equals(dek)).toBe(true);
|
||||
|
||||
manager.clearCache();
|
||||
expect(() => manager.getUserDEK("user-1")).toThrow(UserKeyUnavailableError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
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),
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user