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]
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,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