mirror of
https://github.com/Termix-SSH/Termix.git
synced 2026-08-29 18:31:33 +00:00
release-2.5.1 (#1067)
* chore(deps): bump node from 24-slim to 26-slim in /docker in the docker-major-updates group (#1021) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore(deps): bump node in /docker in the docker-major-updates group Bumps the docker-major-updates group in /docker with 1 update: node. Updates `node` from 24-slim to 26-slim --- updated-dependencies: - dependency-name: node dependency-version: 26-slim dependency-type: direct:production dependency-group: docker-major-updates ... Signed-off-by: dependabot[bot] <support@github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-patch-updates group with 24 updates (#1023) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore(deps-dev): bump the dev-patch-updates group with 24 updates Bumps the dev-patch-updates group with 24 updates: | Package | From | To | | --- | --- | --- | | [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) | `2.5.1` | `2.5.2` | | [@codemirror/commands](https://github.com/codemirror/commands) | `6.10.3` | `6.10.4` | | [@codemirror/view](https://github.com/codemirror/view) | `6.43.1` | `6.43.5` | | [@radix-ui/react-accordion](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/accordion) | `1.2.14` | `1.2.15` | | [@radix-ui/react-alert-dialog](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/alert-dialog) | `1.1.17` | `1.1.18` | | [@radix-ui/react-checkbox](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/checkbox) | `1.3.5` | `1.3.6` | | [@radix-ui/react-dialog](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/dialog) | `1.1.17` | `1.1.18` | | [@radix-ui/react-dropdown-menu](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/dropdown-menu) | `2.1.18` | `2.1.19` | | [@radix-ui/react-label](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/label) | `2.1.10` | `2.1.11` | | [@radix-ui/react-popover](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/popover) | `1.1.17` | `1.1.18` | | [@radix-ui/react-progress](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/progress) | `1.1.10` | `1.1.11` | | [@radix-ui/react-scroll-area](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/scroll-area) | `1.2.12` | `1.2.13` | | [@radix-ui/react-select](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/select) | `2.3.1` | `2.3.2` | | [@radix-ui/react-separator](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/separator) | `1.1.10` | `1.1.11` | | [@radix-ui/react-slider](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/slider) | `1.4.1` | `1.4.2` | | [@radix-ui/react-switch](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/switch) | `1.3.1` | `1.3.2` | | [@radix-ui/react-tabs](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/tabs) | `1.1.15` | `1.1.16` | | [@radix-ui/react-tooltip](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/tooltip) | `1.2.10` | `1.2.11` | | [@tailwindcss/vite](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/@tailwindcss-vite) | `4.3.1` | `4.3.2` | | [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.2` | `6.0.3` | | [i18next](https://github.com/i18next/i18next) | `26.3.1` | `26.3.4` | | [radix-ui](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/radix-ui) | `1.6.0` | `1.6.1` | | [sharp](https://github.com/lovell/sharp) | `0.35.2` | `0.35.3` | | [tailwindcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/tailwindcss) | `4.3.1` | `4.3.2` | Updates `@biomejs/biome` from 2.5.1 to 2.5.2 - [Release notes](https://github.com/biomejs/biome/releases) - [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md) - [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.5.2/packages/@biomejs/biome) Updates `@codemirror/commands` from 6.10.3 to 6.10.4 - [Changelog](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/commands/commits) Updates `@codemirror/view` from 6.43.1 to 6.43.5 - [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/view/commits) Updates `@radix-ui/react-accordion` from 1.2.14 to 1.2.15 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/accordion/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/accordion) Updates `@radix-ui/react-alert-dialog` from 1.1.17 to 1.1.18 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/alert-dialog/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/alert-dialog) Updates `@radix-ui/react-checkbox` from 1.3.5 to 1.3.6 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/checkbox/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/checkbox) Updates `@radix-ui/react-dialog` from 1.1.17 to 1.1.18 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/dialog/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/dialog) Updates `@radix-ui/react-dropdown-menu` from 2.1.18 to 2.1.19 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/dropdown-menu/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/dropdown-menu) Updates `@radix-ui/react-label` from 2.1.10 to 2.1.11 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/label/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/label) Updates `@radix-ui/react-popover` from 1.1.17 to 1.1.18 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/popover/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/popover) Updates `@radix-ui/react-progress` from 1.1.10 to 1.1.11 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/progress/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/progress) Updates `@radix-ui/react-scroll-area` from 1.2.12 to 1.2.13 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/scroll-area/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/scroll-area) Updates `@radix-ui/react-select` from 2.3.1 to 2.3.2 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/select/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/select) Updates `@radix-ui/react-separator` from 1.1.10 to 1.1.11 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/separator/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/separator) Updates `@radix-ui/react-slider` from 1.4.1 to 1.4.2 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/slider/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/slider) Updates `@radix-ui/react-switch` from 1.3.1 to 1.3.2 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/switch/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/switch) Updates `@radix-ui/react-tabs` from 1.1.15 to 1.1.16 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/tabs/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/tabs) Updates `@radix-ui/react-tooltip` from 1.2.10 to 1.2.11 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/tooltip/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/tooltip) Updates `@tailwindcss/vite` from 4.3.1 to 4.3.2 - [Release notes](https://github.com/tailwindlabs/tailwindcss/releases) - [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md) - [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.2/packages/@tailwindcss-vite) Updates `@vitejs/plugin-react` from 6.0.2 to 6.0.3 - [Release notes](https://github.com/vitejs/vite-plugin-react/releases) - [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.0.3/packages/plugin-react) Updates `i18next` from 26.3.1 to 26.3.4 - [Release notes](https://github.com/i18next/i18next/releases) - [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md) - [Commits](https://github.com/i18next/i18next/compare/v26.3.1...v26.3.4) Updates `radix-ui` from 1.6.0 to 1.6.1 - [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/radix-ui/CHANGELOG.md) - [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/radix-ui) Updates `sharp` from 0.35.2 to 0.35.3 - [Release notes](https://github.com/lovell/sharp/releases) - [Commits](https://github.com/lovell/sharp/compare/v0.35.2...v0.35.3) Updates `tailwindcss` from 4.3.1 to 4.3.2 - [Release notes](https://github.com/tailwindlabs/tailwindcss/releases) - [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md) - [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.2/packages/tailwindcss) --- updated-dependencies: - dependency-name: "@biomejs/biome" dependency-version: 2.5.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@codemirror/commands" dependency-version: 6.10.4 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@codemirror/view" dependency-version: 6.43.5 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-accordion" dependency-version: 1.2.15 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-alert-dialog" dependency-version: 1.1.18 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-checkbox" dependency-version: 1.3.6 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-dialog" dependency-version: 1.1.18 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-dropdown-menu" dependency-version: 2.1.19 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-label" dependency-version: 2.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-popover" dependency-version: 1.1.18 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-progress" dependency-version: 1.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-scroll-area" dependency-version: 1.2.13 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-select" dependency-version: 2.3.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-separator" dependency-version: 1.1.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-slider" dependency-version: 1.4.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-switch" dependency-version: 1.3.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-tabs" dependency-version: 1.1.16 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@radix-ui/react-tooltip" dependency-version: 1.2.11 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@tailwindcss/vite" dependency-version: 4.3.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitejs/plugin-react" dependency-version: 6.0.3 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: i18next dependency-version: 26.3.4 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: radix-ui dependency-version: 1.6.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: sharp dependency-version: 0.35.3 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: tailwindcss dependency-version: 4.3.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump the prod-patch-updates group with 2 updates (#1025) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore(deps): bump the prod-patch-updates group with 2 updates Bumps the prod-patch-updates group with 2 updates: [axios](https://github.com/axios/axios) and [nanoid](https://github.com/ai/nanoid). Updates `axios` from 1.18.0 to 1.18.1 - [Release notes](https://github.com/axios/axios/releases) - [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) - [Commits](https://github.com/axios/axios/compare/v1.18.0...v1.18.1) Updates `nanoid` from 5.1.15 to 5.1.16 - [Release notes](https://github.com/ai/nanoid/releases) - [Changelog](https://github.com/ai/nanoid/blob/main/CHANGELOG.md) - [Commits](https://github.com/ai/nanoid/compare/5.1.15...5.1.16) --- updated-dependencies: - dependency-name: axios dependency-version: 1.18.1 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates - dependency-name: nanoid dependency-version: 5.1.16 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump the prod-minor-updates group with 3 updates (#1026) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore(deps): bump the prod-minor-updates group with 3 updates Bumps the prod-minor-updates group with 3 updates: [js-yaml](https://github.com/nodeca/js-yaml), [motion](https://github.com/motiondivision/motion) and [undici](https://github.com/nodejs/undici). Updates `js-yaml` from 5.0.0 to 5.2.1 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/5.0.0...5.2.1) Updates `motion` from 12.40.0 to 12.42.2 - [Changelog](https://github.com/motiondivision/motion/blob/main/CHANGELOG.md) - [Commits](https://github.com/motiondivision/motion/compare/v12.40.0...v12.42.2) Updates `undici` from 8.5.0 to 8.7.0 - [Release notes](https://github.com/nodejs/undici/releases) - [Commits](https://github.com/nodejs/undici/compare/v8.5.0...v8.7.0) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 5.2.1 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: motion dependency-version: 12.42.2 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates - dependency-name: undici dependency-version: 8.7.0 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: prod-minor-updates ... Signed-off-by: dependabot[bot] <support@github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump electron from 42.4.1 to 43.0.0 in the major-updates group (#1027) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore(deps-dev): bump electron in the major-updates group Bumps the major-updates group with 1 update: [electron](https://github.com/electron/electron). Updates `electron` from 42.4.1 to 43.0.0 - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v42.4.1...v43.0.0) --- updated-dependencies: - dependency-name: electron dependency-version: 43.0.0 dependency-type: direct:development update-type: version-update:semver-major dependency-group: major-updates ... Signed-off-by: dependabot[bot] <support@github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Fix MC syntax highlighting artifacts (#996) * Filter dashboard status hosts (#997) * Persist dashboard service link changes (#999) * Fix snippet text overflow (#1000) * Persist remote desktop credential auth (#1001) * Guard language switching failures (#1002) * Resolve tunnel source credentials (#1003) * Support Vault auth for monitors (#1004) * Fix Windows file delete command (#1005) * Fix release artifact checkout ref (#1006) * Fix command palette escape in fullscreen (#1008) * Fix alerts and audit log data normalization (#1010) * Fix macOS VNC protocol negotiation (#1012) * Fix port knocking before SSH connect (#1013) * Allow Escape to close link confirmation (#1014) * Prevent Electron modifier wheel zoom (#1016) * Fix credential auth optional password (#1009) * Retry transient terminal DNS lookups (#1011) * Retry transient terminal DNS lookups * Apply DNS retry to SSH entry points * Fix OIDC redirect forwarded port handling (#1007) * Preserve recent open tabs on startup (#1015) * Fix fish prompt OSC highlighting (#998) * Fix terminal font selection (#1018) * fix: font legibility (#1019) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * fix: font legibility Text was entirely unreadable in places for me. Especially with themes like Catppuccin. The muted-foreground text and the tags too similiar to the background. --------- Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: russell <git@0896c69e.com> * fix(file-manager): chunked uploads fail with 'Expected multipart/form-data request' (#1020) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * fix(file-manager): use postForm for chunked uploads so multipart content-type is sent The fileManagerApi axios instance defaults to Content-Type: application/json. Axios 1.x's default transformRequest converts a FormData body to JSON whenever the request content type is application/json, so every chunk POSTed to /ssh/uploadFileChunk arrived as a JSON body like {"chunk":{}} and the backend rejected it with 400 'Expected multipart/form-data request'. This breaks all uploads of files larger than the 1.5 GiB chunking threshold. The non-chunked path already uses postForm for /ssh/uploadFileStream; use it for the chunk path too so axios keeps the FormData intact and the browser sets the multipart boundary. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * feat: implement OIDC back-channel logout support with session management (#1028) * feat: implement OIDC back-channel logout support with session management * Fix OIDC back-channel logout handling * Require logout token replay identifiers --------- Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> * Add API key host enrollment endpoint (#1029) * Fix tmux detection for non-POSIX shells (#1030) * Fix OPKSSH js-yaml ESM import (#1031) * Fix Android Vietnamese IME input (#1032) * Fix Firefox RDP clipboard paste (#1033) * Fix Proxmox discovery over HTTPS (#1041) * Fix external editor actions in file preview (#1042) * Allow pinned hosts with name sorting (#1043) * Fix Firefox desktop OIDC callback (#1044) * feat(session): add recording and replay (#1049) * Fix status checks through jump hosts (#1045) * Add terminal font size shortcuts (#1047) * feat: add Open File Manager to tab right-click menu (#1051) Co-authored-by: SankeerthNara <sankeerthnara@gmail.com> * perf: frontend request cache, poll pause, and code-split shell (#1052) Host/status caching, shell code-split, SSH pool waits, host-metrics concurrency, background-tab idle, per-host status subscriptions, homepage poll quieting, and virtualized host sidebar + file manager lists. * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * Merge commit from fork * feat: save quick connect sessions as hosts (#1055) * fix: restore sudo password autofill settings (#1056) * fix: preserve file editor position on save (#1057) * fix: sync cloud preference storage mode (#1058) * fix: render RDP sessions at native pixel density (#1059) * fix: restore database import in embedded desktop mode (#1060) * Update Auto-complete.tsx (#1061) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore: donation bar reporting wrong result * feat: add Open File Manager to tab right-click menu (#1046) * Revert "feat: add Open File Manager to tab right-click menu (#1046)" (#1050) This reverts commit0712fdd731. * Remove donation badge from README Removed donation badge from README. * Delete .github/workflows/donation-goal.yml * Update Auto-complete.tsx --------- Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> * feat(auth): opt-in OIDC DEK unlock for API-key requests (ALLOW_APIKEY_DATA_UNLOCK) (#1064) * chore: fix release workflow to merge docs branch * fix: svg donation generator push fail * fix: svg donation generator push fail * Update termix.rb * fix: svg donation generator push fail * chore: move donation badge to badges branch to avoid ruleset conflicts * chore: remove unneeded token from donation badge workflow * chore: debug donation badge commit step * fix: escape < character in donation SVG * fix: point donation badge to badges branch * chore: remove unused donation badge svg from main * Add Rack Genius logo to README Added Rack Genius logo to the README. * chore: improve donation goal svg generator to include stablecoins * chore: donation goal generator syntax error * chore: donation goal generator incorrect docs url usage * chore: donation bar reporting wrong result * feat: add Open File Manager to tab right-click menu (#1046) * Revert "feat: add Open File Manager to tab right-click menu (#1046)" (#1050) This reverts commit0712fdd731. * Remove donation badge from README Removed donation badge from README. * Delete .github/workflows/donation-goal.yml * feat(auth): opt-in OIDC DEK unlock for API-key requests API keys authenticate but cannot touch the encrypted credential/host store ('User data not unlocked') unless the user has a live interactive session, making them unusable for headless automation. For OIDC users the DEK is server-derivable (deriveOIDCSystemKey), so handleApiKeyAuth can unlock it without a password. Gated behind ALLOW_APIKEY_DATA_UNLOCK (default off) because enabling it widens the blast radius of a leaked API key. OIDC-only; password users are untouched. Refs #1063 --------- Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: Luke Gustafson <88517757+LukeGus@users.noreply.github.com> Co-authored-by: Sankeerth Nara <sankeerthnara@gmail.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> * chore: package lock sync * Add Proxmox guest auto sync (#1053) * draft: database layer refactor (#1054) * feat(sshid) - sshid.io equivalent for termix (#919) * feat(ssh-id): database schema, migrations and field encryption Adds ssh_identities, ssh_identity_keys and ssh_identity_ca tables (public keys stored plaintext for the unauthenticated resolver; CA private key registered for per-user field encryption), with UNIQUE(user_id), an index on ssh_identity_keys(identity_id), and idempotent CREATE TABLE migrations. * feat(ssh-id): backend API — resolver, key management, CA and certificates Mounts /sshid (nginx route added). Public text/plain authorized_keys resolver (+ exact /:algo filter, HTML viewer) and CA public-key endpoint; no-store + noindex headers on every resolver response including early 404s. Authenticated management: claim/rename/delete handle, add/import/generate/enable/delete keys, and a per-user CA (create/rotate/delete) with pure-Node OpenSSH certificate issuance. Audit logging on all mutations; UNIQUE races map to a precise 409. Unit tests for key parsing and certificate signing (ssh-keygen-validated). * feat(ssh-id): frontend panel, API client and i18n SSH ID panel wired into the app rail and AppShell: claim handle, resolver URL + curl one-liner, key list, generate, paste/import, CA enable/rotate/remove with server trust command, and per-key certificate issuance. API client re-exported through main-axios.ts; all strings i18n'd. * style(ssh-id): align panel and resolver page with Termix theme - Rebuild the SSH ID sidebar panel with the theme's square components (SectionCard / SettingRow / FakeSwitch) instead of rounded ad-hoc cards; use accent-brand and destructive tokens rather than raw red/green. - Fix panel scrolling: move overflow to a block scroll container so the cards keep their natural height instead of being clipped. - Restyle the public resolver HTML page (/sshid/u/:handle) to the Termix dark theme: square corners, #18181b/#303032 palette, #f59145 accent, uppercase section labels. - Tidy copy: 'Save To Credentials' label, drop the redundant generate intro, and correct the generate tooltip (the key is stored when saving to vault). * feat: rename to Termix ID, improve UI, backend inconsistencies, and general bug fixes --------- Co-authored-by: LukeGus <bugattiguy527@gmail.com> * ci(deps): bump actions/checkout from 6 to 7 in the github-actions group (#922) Bumps the github-actions group with 1 update: [actions/checkout](https://github.com/actions/checkout). Updates `actions/checkout` from 6 to 7 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps-dev): bump the dev-patch-updates group with 11 updates (#923) Bumps the dev-patch-updates group with 11 updates: | Package | From | To | | --- | --- | --- | | [@codemirror/search](https://github.com/codemirror/search) | `6.7.0` | `6.7.1` | | [@codemirror/view](https://github.com/codemirror/view) | `6.43.0` | `6.43.1` | | [@tailwindcss/vite](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/@tailwindcss-vite) | `4.3.0` | `4.3.1` | | [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.1.8` | `4.1.9` | | [@vitest/ui](https://github.com/vitest-dev/vitest/tree/HEAD/packages/ui) | `4.1.8` | `4.1.9` | | [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.5.2` | `0.5.3` | | [lint-staged](https://github.com/lint-staged/lint-staged) | `17.0.7` | `17.0.8` | | [prettier](https://github.com/prettier/prettier) | `3.8.3` | `3.8.4` | | [sharp](https://github.com/lovell/sharp) | `0.35.1` | `0.35.2` | | [tailwindcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/tailwindcss) | `4.3.0` | `4.3.1` | | [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `4.1.8` | `4.1.9` | Updates `@codemirror/search` from 6.7.0 to 6.7.1 - [Changelog](https://github.com/codemirror/search/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/search/commits) Updates `@codemirror/view` from 6.43.0 to 6.43.1 - [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md) - [Commits](https://github.com/codemirror/view/commits) Updates `@tailwindcss/vite` from 4.3.0 to 4.3.1 - [Release notes](https://github.com/tailwindlabs/tailwindcss/releases) - [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md) - [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.1/packages/@tailwindcss-vite) Updates `@vitest/coverage-v8` from 4.1.8 to 4.1.9 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/coverage-v8) Updates `@vitest/ui` from 4.1.8 to 4.1.9 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/ui) Updates `eslint-plugin-react-refresh` from 0.5.2 to 0.5.3 - [Release notes](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/releases) - [Changelog](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/blob/main/CHANGELOG.md) - [Commits](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/compare/v0.5.2...v0.5.3) Updates `lint-staged` from 17.0.7 to 17.0.8 - [Release notes](https://github.com/lint-staged/lint-staged/releases) - [Changelog](https://github.com/lint-staged/lint-staged/blob/main/CHANGELOG.md) - [Commits](https://github.com/lint-staged/lint-staged/compare/v17.0.7...v17.0.8) Updates `prettier` from 3.8.3 to 3.8.4 - [Release notes](https://github.com/prettier/prettier/releases) - [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md) - [Commits](https://github.com/prettier/prettier/compare/3.8.3...3.8.4) Updates `sharp` from 0.35.1 to 0.35.2 - [Release notes](https://github.com/lovell/sharp/releases) - [Commits](https://github.com/lovell/sharp/compare/v0.35.1...v0.35.2) Updates `tailwindcss` from 4.3.0 to 4.3.1 - [Release notes](https://github.com/tailwindlabs/tailwindcss/releases) - [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md) - [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.1/packages/tailwindcss) Updates `vitest` from 4.1.8 to 4.1.9 - [Release notes](https://github.com/vitest-dev/vitest/releases) - [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md) - [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.9/packages/vitest) --- updated-dependencies: - dependency-name: "@codemirror/search" dependency-version: 6.7.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@codemirror/view" dependency-version: 6.43.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@tailwindcss/vite" dependency-version: 4.3.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitest/coverage-v8" dependency-version: 4.1.9 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: "@vitest/ui" dependency-version: 4.1.9 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: eslint-plugin-react-refresh dependency-version: 0.5.3 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: lint-staged dependency-version: 17.0.8 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: prettier dependency-version: 3.8.4 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: sharp dependency-version: 0.35.2 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: tailwindcss dependency-version: 4.3.1 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates - dependency-name: vitest dependency-version: 4.1.9 dependency-type: direct:development update-type: version-update:semver-patch dependency-group: dev-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump nanoid in the prod-patch-updates group (#925) Bumps the prod-patch-updates group with 1 update: [nanoid](https://github.com/ai/nanoid). Updates `nanoid` from 5.1.11 to 5.1.15 - [Release notes](https://github.com/ai/nanoid/releases) - [Changelog](https://github.com/ai/nanoid/blob/main/CHANGELOG.md) - [Commits](https://github.com/ai/nanoid/compare/5.1.11...5.1.15) --- updated-dependencies: - dependency-name: nanoid dependency-version: 5.1.15 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: prod-patch-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump the major-updates group with 5 updates (#926) Bumps the major-updates group with 5 updates: | Package | From | To | | --- | --- | --- | | [js-yaml](https://github.com/nodeca/js-yaml) | `4.2.0` | `5.0.0` | | [@eslint/js](https://github.com/eslint/eslint/tree/HEAD/packages/js) | `9.39.4` | `10.0.1` | | [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `25.9.2` | `26.0.0` | | [concurrently](https://github.com/open-cli-tools/concurrently) | `9.2.1` | `10.0.3` | | [eslint](https://github.com/eslint/eslint) | `9.39.4` | `10.5.0` | Updates `js-yaml` from 4.2.0 to 5.0.0 - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/4.2.0...5.0.0) Updates `@eslint/js` from 9.39.4 to 10.0.1 - [Release notes](https://github.com/eslint/eslint/releases) - [Commits](https://github.com/eslint/eslint/commits/v10.0.1/packages/js) Updates `@types/node` from 25.9.2 to 26.0.0 - [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases) - [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node) Updates `concurrently` from 9.2.1 to 10.0.3 - [Release notes](https://github.com/open-cli-tools/concurrently/releases) - [Commits](https://github.com/open-cli-tools/concurrently/compare/v9.2.1...v10.0.3) Updates `eslint` from 9.39.4 to 10.5.0 - [Release notes](https://github.com/eslint/eslint/releases) - [Commits](https://github.com/eslint/eslint/compare/v9.39.4...v10.5.0) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 5.0.0 dependency-type: direct:production update-type: version-update:semver-major dependency-group: major-updates - dependency-name: "@eslint/js" dependency-version: 10.0.1 dependency-type: direct:development update-type: version-update:semver-major dependency-group: major-updates - dependency-name: "@types/node" dependency-version: 26.0.0 dependency-type: direct:development update-type: version-update:semver-major dependency-group: major-updates - dependency-name: concurrently dependency-version: 10.0.3 dependency-type: direct:development update-type: version-update:semver-major dependency-group: major-updates - dependency-name: eslint dependency-version: 10.5.0 dependency-type: direct:development update-type: version-update:semver-major dependency-group: major-updates ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * feat(ssh): add HashiCorp Vault SSH signer authentication * fix: small fixes to vault feature to align with Termix codebase * chore: add view docs links for vault/termix id * fix: file upload fails with 400 and missing schema migrations on upgrade (#929) Two bugs introduced in v2.4.1: 1. uploadFileStream uses fileManagerApi.post() which triggers axios's transformRequest to JSON-serialize the FormData because the instance default Content-Type is application/json. Change to postForm() which sets Content-Type: multipart/form-data so the browser XHR sends the correct multipart body with boundary. 2. Two schema items added to schema.ts were not included in migrateSchema() in db/index.ts, causing 500 errors on existing installations upgrading from v2.4.0: - user_preferences.status_color_scheme (no such column) - dashboard_service_links table (no such table) Fixes #928 Co-authored-by: sash <sash@fominykh.io> * fix: support PuTTY PPK ssh keys (#930) * fix: chunk large file manager uploads (#932) * fix: route dashboard hosts by protocol (#934) * fix: resolve tunnel endpoints reliably (#935) * Fix Electron OIDC browser auth failures (#936) * Allow RDP connections without stored credentials (#937) * Sync role credential shares for OIDC users (#938) * Fix terminal link dialog layering (#940) * Confirm large files before opening editor (#942) * Confirm closing active host connections (#943) * Preserve file path case in file manager UI (#941) * fix: preserve unicode guacamole tokens (#933) * Persist VNC authentication settings (#944) * Fix Guacamole websocket base path (#946) * Promote file manager terminals to tabs (#939) * Guard Guacamole disconnect during startup (#945) * chore: increment ver * feat: bitwarden ssh agent integration * feat: serial connections support * fix: various small bug fixes * feat: open all sessions in a folder and terminal custom theme color support * feat: cross host file manager clipboard and several small bug fixes * feat: tailscale/wireguard support and added a new status state for when backend is checking status * feat: grafana like server stats history, new alert system, ntfy/webhook support * feat: new grid and widget based homepage function * feat: new donate button in dashboard * fix: alert ui incorrectly using termix css and fixed issue with alert system not loading * chore: start database layer refactor * docs: plan database layer refactor * docs: audit database layer refactor phase zero * chore: add database runtime adapter skeleton * chore: add settings repository skeleton * chore: add user session repository skeleton * chore: add host credential repository skeleton * chore: add field encryption boundary * chore: migrate settings route slice * chore: migrate user settings routes * chore: migrate host metrics settings routes * chore: migrate acme settings route * chore: migrate terminal settings route * chore: migrate tailscale settings read * chore: migrate guacamole settings reads * chore: migrate session timeout settings reads * chore: migrate auth route settings reads * chore: migrate host metrics settings reads * chore: migrate startup settings reads * chore: migrate user settings cleanup * chore: migrate password reset settings * chore: migrate oidc legacy settings read * chore: migrate user route settings slice * chore: migrate oidc state settings * chore: migrate user login settings reads * chore: migrate user crypto settings * chore: consolidate startup settings defaults * chore: consolidate database settings import export * chore: migrate core session auth paths * chore: migrate remaining session auth paths * chore: migrate admin user routes * chore: migrate user route admin checks * chore: migrate user lifecycle routes * chore: migrate auth user lookups * chore: migrate oidc user routes * chore: migrate api key repository paths * docs: add database gray rollout guide * chore: migrate trusted device paths * chore: migrate user session route user lookups * chore: add database repository rollout guard * chore: expose repository rollout status * chore: warn on repository rollout misconfiguration * chore: migrate remaining user lookup helpers * chore: migrate ssh user lookups * chore: migrate user settings admin lookups * chore: migrate acme ssl user lookups * chore: migrate audit log admin checks * chore: migrate oidc account user updates * chore: migrate password reset user updates * chore: migrate user deletion core records * chore: migrate snippet audit user lookups * chore: migrate ldap user sync paths * chore: migrate totp user updates * chore: migrate rbac user checks * chore: migrate rbac role paths * chore: migrate permission role lookups * chore: migrate rbac access list reads * chore: migrate shared rbac reads * chore: migrate rbac access writes * chore: migrate permission host access * chore: migrate role host access lookup * chore: migrate snippet access lookup * chore: migrate shared credential access lookups * chore: migrate host access cleanup writes * chore: migrate host list access checks * chore: migrate host access cleanup routes * chore: migrate shared credential role lookups * chore: migrate user role cleanup * chore: migrate admin role sync * chore: migrate ldap role sync * chore: migrate user role assignment * chore: migrate sso provider access * chore: migrate audit log access * chore: migrate user preference access * chore: migrate open tab access * chore: migrate dismissed alert access * chore: migrate homepage layout access * chore: migrate network topology access * chore: migrate dashboard service link access * chore: migrate command history access * chore: migrate recent activity cleanup * chore: migrate ssh credential usage access * chore: migrate transfer recent access * chore: migrate file manager bookmark access * chore: migrate c2s tunnel preset access * chore: migrate homepage item access * chore: migrate session recording access * chore: migrate tmux session tag access * chore: migrate opkssh token access * chore: migrate vault token access * chore: migrate vault profile access * chore: migrate host metrics preference access * chore: migrate host health access * chore: migrate host metrics history access * chore: migrate alert persistence access * chore: route alert host lookup through repository * chore: migrate user data export reads * chore: route host metrics stats sync through repository * chore: migrate host folder persistence * chore: migrate host resolution reads * chore: route jump host resolution reads * chore: route docker console jump host reads * chore: route docker ssh resolution reads * chore: route proxmox discovery resolution reads * chore: route file manager activity host reads * chore: route host metrics resolution reads * chore: route ssh auth credential reads * chore: route tunnel endpoint credential reads * chore: route credential deployment resolution reads * chore: route command history host flag reads * chore: route snippet execution resolution reads * chore: route terminal host resolution reads * chore: route vault oidc host resolution reads * chore: route wake on lan host reads * chore: route internal host list reads * chore: route host key verification persistence * chore: route credential read paths * chore: route credential host usage reads * chore: route credential folder rename * chore: route host owner access checks * chore: route shared credential source reads * chore: route user host credential cleanup * chore: route credential delete reads * chore: route credential update reads * chore: route host credential reads * chore: route host read paths * chore: route host projection reads * chore: route host list reads * chore: route snippet read paths * chore: route snippet folder writes * chore: route snippet crud paths * chore: route snippet bulk import * chore: route rbac ownership reads * chore: route user count reads * chore: route cleanup snippets folders * chore: route shared credential persistence * chore: route dashboard activity * chore: route guacamole host reads * chore: route host bulk lookups * chore: remove unlock-only simple db ops * chore: route host autostart persistence * chore: route ldap provisioning through users * chore: route credential encrypted writes * chore: route host encrypted writes * chore: route bulk host encrypted writes * chore: route termix id credentials * chore: route termix id ca persistence * chore: route termix identity persistence * chore: route credential system migration * chore: isolate user encryption migration storage * chore: remove legacy simple db ops * chore: isolate legacy sqlite migration copy * chore: route database settings import export * chore: route database host credential export * chore: route database host credential import * chore: route database file-manager import export * chore: route database alert usage import export * chore: route database user checks * chore: isolate auth lazy migration storage * chore: route explicit database saves * chore: initialize database save boundary * chore: route migration snapshot saves * chore: isolate sqlite import constraints * chore: route import sqlite boundary * chore: route user encryption migration store * chore: centralize current repository runtime * chore: route more current repositories * chore: route activity repository runtimes * chore: route token repository runtimes * chore: route health repository runtimes * chore: route identity repository runtimes * chore: route rbac repository runtime * chore: centralize current sqlite runtime access * chore: route user deletion key cleanup * chore: route user deletion vault cleanup * chore: route user deletion homepage cleanup * chore: route user deletion health cleanup * chore: route user deletion alert cleanup * chore: route user deletion identity cleanup * chore: add database layer preupgrade backup * Fix database repository type errors * fix: complete post-merge compile fixes for database refactor Restore missing DatabaseSaveTrigger/getDb imports, session log format fallback, OIDC provider resolution, guacamole recording insert, and passwordFallbackOnly typing after merging current dev. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: DivByZero <mr.oplus@yahoo.fr> Co-authored-by: LukeGus <bugattiguy527@gmail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: devdanetra <46488477+devdanetra@users.noreply.github.com> Co-authored-by: Aleksandr Fominykh <neoformalex@users.noreply.github.com> Co-authored-by: sash <sash@fominykh.io> * refactor(db): collapse repository rollout scaffolding into single factory Repositories are now the only data path. Replaces the 41 current-*-repository wrapper files, the DATABASE_LAYER_REPOSITORY_ROLLOUT flag/alias map and the unused database/runtime adapter with repositories/factory.ts, a plain DatabaseContext type and an in-memory TestSqliteDatabase test harness. * refactor(db): route remaining raw DB access through repositories proxmox, session-log, oidc-utils, webauthn and guacamole recording now use repositories (new WebauthnCredentialRepository; SsoProviderRepository listEnabled; HostRepository findDecryptedByIdAs/listProxmoxEnabled). Remaining raw access: db boot code, simple-db-ops and docker.ts, which are removed/restructured in later phases. * feat(crypto): add UserKeyManager with system-wrapped per-user DEKs New utils/user-keys.ts: one random 32-byte DEK per user, wrapped AES-256-GCM under an HKDF key derived from the system ENCRYPTION_KEY (per-user info string + AAD binding, versioned v3 wrap format stored in settings). Synchronous unwrap-on-demand with a 15-minute cache so the existing DataCrypto facade keeps its sync call sites. Not wired up yet. * feat(crypto): boot-time DEK migration to system-wrapped v3 format utils/crypto-migration/dek-migration.ts carries the legacy unwrap paths (PBKDF2 password KEK, OIDC/WebAuthn system keys, hardcoded-default fallback) and migrates every server-unwrappable DEK to the v3 wrap at startup. Password-wrapped DEKs migrate at next login or from a live session via adoptRecoveredDEK. Legacy rows are kept for now; cleanup flips on once the new path is authoritative. * refactor(crypto): make system-wrapped DEKs the authoritative key path DataCrypto and AuthManager now read keys through UserKeyManager: DEKs are always unwrappable server-side, so the in-memory unlock session, DEK-in-JWT wrapping, session-expiry data locks and ALLOW_APIKEY_DATA_UNLOCK are gone. utils/user-crypto.ts is deleted; boot migration now cleans legacy wraps. A one-release shim adopts DEKs from legacy dataKeyWrap tokens so active password users migrate without re-login. Password login migrates legacy password-wrapped DEKs via migratePasswordUserAtLogin. * refactor(crypto): remove pending share queue and credential sharing key With server-unwrappable DEKs both sides of a share are always available, so the needsReEncryption queue, CREDENTIAL_SHARING_KEY and the system_* shadow columns on ssh_credentials are gone. A one-time boot cleanup re-creates legacy pending share copies where possible (dropping unresolvable ones with a warning) and drops the legacy columns. * feat(auth): non-destructive password resets and admin reset endpoint Password resets no longer destroy user data: the DEK is system-wrapped, so forgot-password and admin resets are just a hash update plus session revoke. The wipe branch survives only for accounts that never logged in since the encryption upgrade and now requires explicit confirmDataWipe (surfaced as a 409 DATA_WIPE_REQUIRED; the reset UI asks for confirmation). Adds POST /users/admin/reset-password and removes the dead re-encryption paths. * refactor(ssh): consolidate four jump-host chain copies into one module terminal, host-metrics and docker now use ssh/jump-host-chain.ts (already shared by file-manager, tmux-monitor and docker-console); docker's inline copy also drops its raw SimpleDBOps host/credential lookups in favor of repositories. * refactor(ssh): single shared createConnectionLog helper file-manager-log.ts becomes ssh/connection-log.ts; the copies in docker.ts and host-metrics-helpers.ts are gone. * refactor(ssh): split docker module into layered directory ssh/docker/{index,routes,session-manager,container-routes,console}.ts: server boot and wiring in index, HTTP handlers in routes, SSH session registry and command execution in session-manager. Code motion only; port 30007/30009 and endpoints unchanged. Swagger now scans ssh subdirectories. * refactor(ssh): split tunnel module into layered directory ssh/tunnel/{index,routes,manager}.ts: server boot in index, HTTP handlers in routes, tunnel state and engine (connect/retry/autostart) in manager. Code motion only; port 30003 and endpoints unchanged. * refactor(backend): reorganize top-level layout - ssh/ renamed to hosts/ (it covers SSH, RDP, VNC, Telnet, Docker, metrics) - serial/serial.ts and guacamole/ moved inside hosts/ - dashboard.ts and homepage.ts moved to services/ - swagger.ts moved to utils/ with adjusted scan globs Import paths and the generate:openapi script updated; ports and endpoints unchanged. * refactor(tests): move backend tests into src/backend/tests mirror tree Backend *.test.ts files (and the test-support harness) no longer sit next to source files; they live under src/backend/tests/ mirroring the source layout. Imports rewritten accordingly; CLAUDE.md convention updated. * refactor(hosts): group host modules into per-feature directories file-manager/, metrics/ (incl. widgets, managers, alert-engine), terminal/, tmux/ and tunnel/ each own their files; docker/ gains container-runtime. Genuinely shared helpers (jump-host chain, host resolver, connection pool, opkssh, vault, serial) stay at hosts/ root. Pure file moves with import path updates; mirrored test paths follow. * refactor(backend): final cleanup pass - re-register WebAuthn passkey routes (registration was dropped in the #1054 merge, breaking passkey login) and document all six endpoints - delete utils/simple-db-ops.ts (last caller migrated to DataCrypto) - starter: use the typed serverReady export, collapse the four-way version lookup to env then package.json candidates - add OpenAPI JSDoc to c2s-tunnel-presets endpoints - strip block-divider comment banners * feat: remove legacy "data_unlocked" field * feat: refactor rbac/sharing to support new permissions and auth types * feat: refactor rbac/sharing to support new permissions and auth types * feat: add "id" to user profile hide list * chore: root cleanup * feat: add more donation references and a 30-day donation reminder * chore: update readme * feat: automate beta tests * feat: add links to milestones * fix: hoist github/google SSO defaults to module scope (#1065) * fix(ssh-tools): allow clipboard paste in key recording field (#1066) The broadcast key-recording input was marked readOnly, which makes browsers block paste entirely (no context-menu Paste, Ctrl+V does nothing). handleKeyDown also called preventDefault() unconditionally, swallowing the Ctrl+V shortcut before a paste event could even fire. Let Ctrl/Cmd+V pass through in handleKeyDown, drop readOnly, and add an onPaste handler that reads the clipboard text and broadcasts it to the selected terminals like any other captured keystroke. Signed-off-by: emreumar <emreumar@users.noreply.github.com> Co-authored-by: emreumar <emreumar@users.noreply.github.com> * chore: write release notes * chore: update release notes * chore: update readmes * chore: add crypto only reminder in en.json * fix: macOS and cask errors on release workflow * chore: sync Crowdin translations for 2.5.1 --------- Signed-off-by: dependabot[bot] <support@github.com> Signed-off-by: emreumar <emreumar@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: ZacharyZcR <zacharyzcr1984@gmail.com> Co-authored-by: Russell Poovey <09.our_seekers@icloud.com> Co-authored-by: russell <git@0896c69e.com> Co-authored-by: Subedi Bibek <77529535+questbibek@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Alexander Elsner <101340634+Bensonheimer992@users.noreply.github.com> Co-authored-by: SankeerthNara <sankeerthnara@gmail.com> Co-authored-by: Stephan Groth <96803994+Kalvalax@users.noreply.github.com> Co-authored-by: DivByZero <mr.oplus@yahoo.fr> Co-authored-by: devdanetra <46488477+devdanetra@users.noreply.github.com> Co-authored-by: Aleksandr Fominykh <neoformalex@users.noreply.github.com> Co-authored-by: sash <sash@fominykh.io> Co-authored-by: lhojun <ldgs3324@gmail.com> Co-authored-by: Yunus Emre Umar <77045015+emre155@users.noreply.github.com> Co-authored-by: emreumar <emreumar@users.noreply.github.com>
This commit is contained in:
co-authored by
emreumar
dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
ZacharyZcR
Russell Poovey
russell
Subedi Bibek
Claude Fable 5
Alexander Elsner
SankeerthNara
Stephan Groth
DivByZero
devdanetra
Aleksandr Fominykh
sash
lhojun
Yunus Emre Umar
parent
fba645e92e
commit
ddbdd5c437
@@ -1,132 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("../database/db/index.js", () => ({
|
||||
db: {
|
||||
insert: vi.fn().mockReturnValue({
|
||||
values: vi.fn().mockResolvedValue(undefined),
|
||||
}),
|
||||
$client: {
|
||||
prepare: vi.fn().mockReturnValue({
|
||||
get: vi.fn().mockReturnValue({ count: 0 }),
|
||||
run: vi.fn(),
|
||||
}),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { logAudit, getRequestMeta } from "./audit-logger.js";
|
||||
import { db } from "../database/db/index.js";
|
||||
|
||||
const mockDb = db as {
|
||||
insert: ReturnType<typeof vi.fn>;
|
||||
$client: { prepare: ReturnType<typeof vi.fn> };
|
||||
};
|
||||
|
||||
describe("logAudit", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockDb.insert.mockReturnValue({
|
||||
values: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
mockDb.$client.prepare.mockReturnValue({
|
||||
get: vi.fn().mockReturnValue({ count: 0 }),
|
||||
run: vi.fn(),
|
||||
});
|
||||
});
|
||||
|
||||
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(mockDb.insert).toHaveBeenCalledOnce();
|
||||
const valuesFn = mockDb.insert.mock.results[0].value.values;
|
||||
expect(valuesFn).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 () => {
|
||||
mockDb.insert.mockReturnValue({
|
||||
values: vi.fn().mockRejectedValue(new Error("db error")),
|
||||
});
|
||||
|
||||
await expect(
|
||||
logAudit({
|
||||
userId: "u",
|
||||
username: "u",
|
||||
action: "x",
|
||||
resourceType: "y",
|
||||
success: false,
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("triggers pruning when row count exceeds threshold", async () => {
|
||||
const prepareMock = vi.fn();
|
||||
const runMock = vi.fn();
|
||||
prepareMock.mockImplementation((sql: string) => {
|
||||
if (sql.includes("COUNT(*)")) {
|
||||
return { get: () => ({ count: 10001 }) };
|
||||
}
|
||||
return { run: runMock };
|
||||
});
|
||||
mockDb.$client.prepare = prepareMock;
|
||||
|
||||
await logAudit({
|
||||
userId: "u",
|
||||
username: "u",
|
||||
action: "x",
|
||||
resourceType: "y",
|
||||
success: true,
|
||||
});
|
||||
|
||||
const deleteCalled = prepareMock.mock.calls.some((args: unknown[]) =>
|
||||
String(args[0]).includes("DELETE"),
|
||||
);
|
||||
expect(deleteCalled).toBe(true);
|
||||
expect(runMock).toHaveBeenCalledWith(1001);
|
||||
});
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,5 @@
|
||||
import type { Request } from "express";
|
||||
import { db } from "../database/db/index.js";
|
||||
import { auditLogs } from "../database/db/schema.js";
|
||||
|
||||
const PRUNE_MAX = 10000;
|
||||
const PRUNE_TARGET = 9000;
|
||||
import { createCurrentAuditLogRepository } from "../database/repositories/factory.js";
|
||||
|
||||
export interface AuditLogParams {
|
||||
userId: string;
|
||||
@@ -21,7 +17,7 @@ export interface AuditLogParams {
|
||||
|
||||
export async function logAudit(params: AuditLogParams): Promise<void> {
|
||||
try {
|
||||
await db.insert(auditLogs).values({
|
||||
await createCurrentAuditLogRepository().create({
|
||||
userId: params.userId,
|
||||
username: params.username,
|
||||
action: params.action,
|
||||
@@ -34,21 +30,6 @@ export async function logAudit(params: AuditLogParams): Promise<void> {
|
||||
success: params.success,
|
||||
errorMessage: params.errorMessage ?? null,
|
||||
});
|
||||
|
||||
const countResult = db.$client
|
||||
.prepare("SELECT COUNT(*) as count FROM audit_logs")
|
||||
.get() as { count: number };
|
||||
|
||||
if (countResult.count >= PRUNE_MAX) {
|
||||
const deleteCount = countResult.count - PRUNE_TARGET;
|
||||
db.$client
|
||||
.prepare(
|
||||
`DELETE FROM audit_logs WHERE id IN (
|
||||
SELECT id FROM audit_logs ORDER BY timestamp ASC LIMIT ?
|
||||
)`,
|
||||
)
|
||||
.run(deleteCount);
|
||||
}
|
||||
} catch {
|
||||
// audit logging must never throw and break the caller
|
||||
}
|
||||
|
||||
+322
-517
File diff suppressed because it is too large
Load Diff
@@ -36,6 +36,7 @@ export function createCorsMiddleware(
|
||||
"User-Agent",
|
||||
"X-Electron-App",
|
||||
"Cache-Control",
|
||||
"x-admin-target-user",
|
||||
...extraHeaders,
|
||||
];
|
||||
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
import { db } from "../database/db/index.js";
|
||||
import { sshCredentials, sharedCredentials } from "../database/db/schema.js";
|
||||
import { eq, and, or, isNull } from "drizzle-orm";
|
||||
import { DataCrypto } from "./data-crypto.js";
|
||||
import { SystemCrypto } from "./system-crypto.js";
|
||||
import { FieldCrypto } from "./field-crypto.js";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
|
||||
export class CredentialSystemEncryptionMigration {
|
||||
async migrateUserCredentials(userId: string): Promise<{
|
||||
migrated: number;
|
||||
failed: number;
|
||||
skipped: number;
|
||||
}> {
|
||||
try {
|
||||
const userDEK = DataCrypto.getUserDataKey(userId);
|
||||
if (!userDEK) {
|
||||
throw new Error("User must be logged in to migrate credentials");
|
||||
}
|
||||
|
||||
const systemCrypto = SystemCrypto.getInstance();
|
||||
const CSKEK = await systemCrypto.getCredentialSharingKey();
|
||||
|
||||
const credentials = await db
|
||||
.select()
|
||||
.from(sshCredentials)
|
||||
.where(
|
||||
and(
|
||||
eq(sshCredentials.userId, userId),
|
||||
or(
|
||||
isNull(sshCredentials.systemPassword),
|
||||
isNull(sshCredentials.systemKey),
|
||||
isNull(sshCredentials.systemKeyPassword),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
let migrated = 0;
|
||||
let failed = 0;
|
||||
const skipped = 0;
|
||||
|
||||
for (const cred of credentials) {
|
||||
try {
|
||||
const plainPassword = cred.password
|
||||
? FieldCrypto.decryptField(
|
||||
cred.password,
|
||||
userDEK,
|
||||
cred.id.toString(),
|
||||
"password",
|
||||
)
|
||||
: null;
|
||||
|
||||
const plainKey = cred.key
|
||||
? FieldCrypto.decryptField(
|
||||
cred.key,
|
||||
userDEK,
|
||||
cred.id.toString(),
|
||||
"key",
|
||||
)
|
||||
: null;
|
||||
|
||||
const plainKeyPassword = cred.keyPassword
|
||||
? FieldCrypto.decryptField(
|
||||
cred.keyPassword,
|
||||
userDEK,
|
||||
cred.id.toString(),
|
||||
"keyPassword",
|
||||
)
|
||||
: null;
|
||||
|
||||
const systemPassword = plainPassword
|
||||
? FieldCrypto.encryptField(
|
||||
plainPassword,
|
||||
CSKEK,
|
||||
cred.id.toString(),
|
||||
"password",
|
||||
)
|
||||
: null;
|
||||
|
||||
const systemKey = plainKey
|
||||
? FieldCrypto.encryptField(
|
||||
plainKey,
|
||||
CSKEK,
|
||||
cred.id.toString(),
|
||||
"key",
|
||||
)
|
||||
: null;
|
||||
|
||||
const systemKeyPassword = plainKeyPassword
|
||||
? FieldCrypto.encryptField(
|
||||
plainKeyPassword,
|
||||
CSKEK,
|
||||
cred.id.toString(),
|
||||
"key_password",
|
||||
)
|
||||
: null;
|
||||
|
||||
await db
|
||||
.update(sshCredentials)
|
||||
.set({
|
||||
systemPassword,
|
||||
systemKey,
|
||||
systemKeyPassword,
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
.where(eq(sshCredentials.id, cred.id));
|
||||
|
||||
await db
|
||||
.update(sharedCredentials)
|
||||
.set({ needsReEncryption: true })
|
||||
.where(eq(sharedCredentials.originalCredentialId, cred.id));
|
||||
|
||||
migrated++;
|
||||
} catch (error) {
|
||||
databaseLogger.warn(
|
||||
`Skipping credential migration for credential ${cred.id}: ${error instanceof Error ? error.message : "Unknown error"}`,
|
||||
{
|
||||
operation: "credential_migration_skip",
|
||||
credentialId: cred.id,
|
||||
userId,
|
||||
},
|
||||
);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
return { migrated, failed, skipped };
|
||||
} catch (error) {
|
||||
databaseLogger.warn("Credential system encryption migration incomplete", {
|
||||
operation: "credential_migration_incomplete",
|
||||
userId,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
import crypto from "crypto";
|
||||
import { databaseLogger } from "../logger.js";
|
||||
import { SystemCrypto } from "../system-crypto.js";
|
||||
import { UserKeyManager } from "../user-keys.js";
|
||||
import {
|
||||
createCurrentSettingsRepository,
|
||||
createCurrentUserRepository,
|
||||
getCurrentSettingValue,
|
||||
} from "../../database/repositories/factory.js";
|
||||
|
||||
// Legacy (pre-v3) wrap formats, kept only to migrate existing installs.
|
||||
// Password users: DEK wrapped by PBKDF2(password) using user_kek_salt_*.
|
||||
// OIDC/WebAuthn users: DEK wrapped by a key derived from the system
|
||||
// ENCRYPTION_KEY (or *_SYSTEM_SECRET env overrides), so the server can
|
||||
// unwrap those eagerly at boot. Password wraps need the password (login)
|
||||
// or the DEK recovered from a live session's JWT.
|
||||
|
||||
interface LegacyEncryptedDEK {
|
||||
data: string;
|
||||
iv: string;
|
||||
tag: string;
|
||||
algorithm: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface LegacyKekSalt {
|
||||
salt: string;
|
||||
iterations: number;
|
||||
algorithm: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
const KEY_LENGTH = 32;
|
||||
|
||||
export function legacySettingsKeys(userId: string): {
|
||||
passwordWrap: string;
|
||||
kekSalt: string;
|
||||
oidcWrap: string;
|
||||
webauthnWrap: string;
|
||||
} {
|
||||
return {
|
||||
passwordWrap: `user_encrypted_dek_${userId}`,
|
||||
kekSalt: `user_kek_salt_${userId}`,
|
||||
oidcWrap: `user_encrypted_dek_oidc_${userId}`,
|
||||
webauthnWrap: `user_encrypted_dek_webauthn_${userId}`,
|
||||
};
|
||||
}
|
||||
|
||||
function parseJson<T>(raw: string | null): T | null {
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return JSON.parse(raw) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function decryptLegacyDEK(encrypted: LegacyEncryptedDEK, kek: Buffer): Buffer {
|
||||
const decipher = crypto.createDecipheriv(
|
||||
"aes-256-gcm",
|
||||
kek,
|
||||
Buffer.from(encrypted.iv, "hex"),
|
||||
);
|
||||
decipher.setAuthTag(Buffer.from(encrypted.tag, "hex"));
|
||||
return Buffer.concat([
|
||||
decipher.update(Buffer.from(encrypted.data, "hex")),
|
||||
decipher.final(),
|
||||
]);
|
||||
}
|
||||
|
||||
function deriveLegacyKEK(password: string, kekSalt: LegacyKekSalt): Buffer {
|
||||
return crypto.pbkdf2Sync(
|
||||
password,
|
||||
Buffer.from(kekSalt.salt, "hex"),
|
||||
kekSalt.iterations,
|
||||
KEY_LENGTH,
|
||||
"sha256",
|
||||
);
|
||||
}
|
||||
|
||||
async function deriveOIDCSystemKey(userId: string): Promise<Buffer> {
|
||||
if (process.env.OIDC_SYSTEM_SECRET) {
|
||||
return crypto.pbkdf2Sync(
|
||||
process.env.OIDC_SYSTEM_SECRET,
|
||||
Buffer.from(userId, "utf8"),
|
||||
100000,
|
||||
KEY_LENGTH,
|
||||
"sha256",
|
||||
);
|
||||
}
|
||||
|
||||
const systemSecret = await SystemCrypto.getInstance().getEncryptionKey();
|
||||
return Buffer.from(
|
||||
crypto.hkdfSync(
|
||||
"sha256",
|
||||
systemSecret,
|
||||
Buffer.from(userId, "utf8"),
|
||||
Buffer.from("termix:oidc-user-kek", "utf8"),
|
||||
KEY_LENGTH,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function deriveWebAuthnSystemKey(userId: string): Promise<Buffer> {
|
||||
const configuredSecret =
|
||||
process.env.WEBAUTHN_SYSTEM_SECRET || process.env.OIDC_SYSTEM_SECRET;
|
||||
if (configuredSecret) {
|
||||
return crypto.pbkdf2Sync(
|
||||
configuredSecret,
|
||||
Buffer.from(`webauthn:${userId}`, "utf8"),
|
||||
100000,
|
||||
KEY_LENGTH,
|
||||
"sha256",
|
||||
);
|
||||
}
|
||||
|
||||
const systemSecret = await SystemCrypto.getInstance().getEncryptionKey();
|
||||
return Buffer.from(
|
||||
crypto.hkdfSync(
|
||||
"sha256",
|
||||
systemSecret,
|
||||
Buffer.from(userId, "utf8"),
|
||||
Buffer.from("termix:webauthn-user-kek", "utf8"),
|
||||
KEY_LENGTH,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function deriveLegacyDefaultKey(
|
||||
userId: string,
|
||||
type: "oidc" | "webauthn",
|
||||
): Buffer {
|
||||
const secret =
|
||||
type === "oidc"
|
||||
? "termix-oidc-system-secret-default"
|
||||
: "termix-webauthn-system-secret-default";
|
||||
const salt = Buffer.from(
|
||||
type === "oidc" ? userId : `webauthn:${userId}`,
|
||||
"utf8",
|
||||
);
|
||||
return crypto.pbkdf2Sync(secret, salt, 100000, KEY_LENGTH, "sha256");
|
||||
}
|
||||
|
||||
async function tryUnwrapSystemWrapped(
|
||||
userId: string,
|
||||
raw: string | null,
|
||||
type: "oidc" | "webauthn",
|
||||
): Promise<Buffer | null> {
|
||||
const encrypted = parseJson<LegacyEncryptedDEK>(raw);
|
||||
if (!encrypted?.data || !encrypted.iv || !encrypted.tag) return null;
|
||||
|
||||
const candidates = [
|
||||
type === "oidc"
|
||||
? await deriveOIDCSystemKey(userId)
|
||||
: await deriveWebAuthnSystemKey(userId),
|
||||
deriveLegacyDefaultKey(userId, type),
|
||||
];
|
||||
|
||||
for (const key of candidates) {
|
||||
try {
|
||||
const dek = decryptLegacyDEK(encrypted, key);
|
||||
if (dek.length === KEY_LENGTH) return dek;
|
||||
} catch {
|
||||
// wrong key for this wrap; try the next candidate
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasAnyLegacyWrap(userId: string): boolean {
|
||||
const keys = legacySettingsKeys(userId);
|
||||
return (
|
||||
getCurrentSettingValue(keys.passwordWrap) !== null ||
|
||||
getCurrentSettingValue(keys.kekSalt) !== null ||
|
||||
getCurrentSettingValue(keys.oidcWrap) !== null ||
|
||||
getCurrentSettingValue(keys.webauthnWrap) !== null
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteLegacyWraps(userId: string): Promise<void> {
|
||||
const keys = legacySettingsKeys(userId);
|
||||
const settings = createCurrentSettingsRepository();
|
||||
await settings.delete(keys.passwordWrap);
|
||||
await settings.delete(keys.kekSalt);
|
||||
await settings.delete(keys.oidcWrap);
|
||||
await settings.delete(keys.webauthnWrap);
|
||||
}
|
||||
|
||||
// Server-side unwrap for one user, in preference order. The primary
|
||||
// user_encrypted_dek_* slot is only tried when no KEK salt exists: with a
|
||||
// salt present it is password-wrapped and unrecoverable here.
|
||||
async function unwrapServerSide(userId: string): Promise<Buffer | null> {
|
||||
const keys = legacySettingsKeys(userId);
|
||||
|
||||
const fromOidc = await tryUnwrapSystemWrapped(
|
||||
userId,
|
||||
getCurrentSettingValue(keys.oidcWrap),
|
||||
"oidc",
|
||||
);
|
||||
if (fromOidc) return fromOidc;
|
||||
|
||||
const fromWebauthn = await tryUnwrapSystemWrapped(
|
||||
userId,
|
||||
getCurrentSettingValue(keys.webauthnWrap),
|
||||
"webauthn",
|
||||
);
|
||||
if (fromWebauthn) return fromWebauthn;
|
||||
|
||||
if (getCurrentSettingValue(keys.kekSalt) === null) {
|
||||
const fromPrimary = await tryUnwrapSystemWrapped(
|
||||
userId,
|
||||
getCurrentSettingValue(keys.passwordWrap),
|
||||
"oidc",
|
||||
);
|
||||
if (fromPrimary) return fromPrimary;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface BootDekMigrationSummary {
|
||||
totalUsers: number;
|
||||
alreadyMigrated: number;
|
||||
migrated: number;
|
||||
created: number;
|
||||
pendingPasswordLogin: number;
|
||||
}
|
||||
|
||||
export interface BootDekMigrationOptions {
|
||||
cleanupLegacy?: boolean;
|
||||
}
|
||||
|
||||
export async function runBootDekMigration(
|
||||
options: BootDekMigrationOptions = {},
|
||||
): Promise<BootDekMigrationSummary> {
|
||||
const cleanupLegacy = options.cleanupLegacy ?? false;
|
||||
const userKeys = UserKeyManager.getInstance();
|
||||
const users = await createCurrentUserRepository().listAll();
|
||||
|
||||
const summary: BootDekMigrationSummary = {
|
||||
totalUsers: users.length,
|
||||
alreadyMigrated: 0,
|
||||
migrated: 0,
|
||||
created: 0,
|
||||
pendingPasswordLogin: 0,
|
||||
};
|
||||
|
||||
for (const user of users) {
|
||||
if (userKeys.hasUserDEK(user.id)) {
|
||||
summary.alreadyMigrated++;
|
||||
if (cleanupLegacy && hasAnyLegacyWrap(user.id)) {
|
||||
await deleteLegacyWraps(user.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const dek = await unwrapServerSide(user.id);
|
||||
if (dek) {
|
||||
await userKeys.persistDEK(user.id, dek);
|
||||
summary.migrated++;
|
||||
if (cleanupLegacy) {
|
||||
await deleteLegacyWraps(user.id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (hasAnyLegacyWrap(user.id)) {
|
||||
summary.pendingPasswordLogin++;
|
||||
continue;
|
||||
}
|
||||
|
||||
await userKeys.createUserDEK(user.id);
|
||||
summary.created++;
|
||||
}
|
||||
|
||||
databaseLogger.info("User key migration pass finished", {
|
||||
operation: "dek_migration_boot",
|
||||
...summary,
|
||||
});
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
// Password login is the only remaining way to recover a password-wrapped DEK.
|
||||
export async function migratePasswordUserAtLogin(
|
||||
userId: string,
|
||||
password: string,
|
||||
): Promise<boolean> {
|
||||
const userKeys = UserKeyManager.getInstance();
|
||||
|
||||
if (userKeys.hasUserDEK(userId)) {
|
||||
if (hasAnyLegacyWrap(userId)) {
|
||||
await deleteLegacyWraps(userId);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const keys = legacySettingsKeys(userId);
|
||||
const kekSalt = parseJson<LegacyKekSalt>(
|
||||
getCurrentSettingValue(keys.kekSalt),
|
||||
);
|
||||
const encrypted = parseJson<LegacyEncryptedDEK>(
|
||||
getCurrentSettingValue(keys.passwordWrap),
|
||||
);
|
||||
if (!kekSalt?.salt || !encrypted?.data) return false;
|
||||
|
||||
let kek: Buffer | null = null;
|
||||
try {
|
||||
kek = deriveLegacyKEK(password, kekSalt);
|
||||
const dek = decryptLegacyDEK(encrypted, kek);
|
||||
if (dek.length !== KEY_LENGTH) return false;
|
||||
|
||||
await userKeys.persistDEK(userId, dek);
|
||||
await deleteLegacyWraps(userId);
|
||||
|
||||
databaseLogger.info("Migrated password-wrapped user key at login", {
|
||||
operation: "dek_migration_login",
|
||||
userId,
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
kek?.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
// Adopt a DEK recovered from a live session (the legacy JWT dataKeyWrap).
|
||||
export async function adoptRecoveredDEK(
|
||||
userId: string,
|
||||
dek: Buffer,
|
||||
): Promise<void> {
|
||||
const userKeys = UserKeyManager.getInstance();
|
||||
if (userKeys.hasUserDEK(userId)) return;
|
||||
|
||||
await userKeys.persistDEK(userId, dek);
|
||||
await deleteLegacyWraps(userId);
|
||||
|
||||
databaseLogger.info("Migrated user key from active session", {
|
||||
operation: "dek_migration_session",
|
||||
userId,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { databaseLogger } from "../logger.js";
|
||||
import { DatabaseSaveTrigger } from "../database-save-trigger.js";
|
||||
import { getCurrentRepositorySqlite } from "../../database/repositories/factory.js";
|
||||
|
||||
interface SqliteLike {
|
||||
prepare(sql: string): {
|
||||
all(...params: unknown[]): unknown[];
|
||||
get(...params: unknown[]): unknown;
|
||||
run(...params: unknown[]): unknown;
|
||||
};
|
||||
exec(sql: string): unknown;
|
||||
}
|
||||
|
||||
function tableHasColumn(
|
||||
sqlite: SqliteLike,
|
||||
table: string,
|
||||
column: string,
|
||||
): boolean {
|
||||
const rows = sqlite.prepare(`PRAGMA table_info(${table})`).all() as Array<{
|
||||
name: string;
|
||||
}>;
|
||||
return rows.some((row) => row.name === column);
|
||||
}
|
||||
|
||||
function dropColumnIfExists(
|
||||
sqlite: SqliteLike,
|
||||
table: string,
|
||||
column: string,
|
||||
): boolean {
|
||||
if (!tableHasColumn(sqlite, table, column)) return false;
|
||||
sqlite.exec(`ALTER TABLE ${table} DROP COLUMN ${column}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// One-time cleanup of the pre-2.5 sharing machinery: the
|
||||
// CREDENTIAL_SHARING_KEY shadow columns are dropped. Pending share copies are
|
||||
// no longer re-created here; the shared_host_secrets migration rebuilds every
|
||||
// active share from the live host_access grants instead.
|
||||
export async function runLegacySharedCredentialCleanup(): Promise<{
|
||||
columnsDropped: number;
|
||||
}> {
|
||||
const sqlite = getCurrentRepositorySqlite() as unknown as SqliteLike;
|
||||
const result = { columnsDropped: 0 };
|
||||
|
||||
for (const [table, column] of [
|
||||
["ssh_credentials", "system_password"],
|
||||
["ssh_credentials", "system_key"],
|
||||
["ssh_credentials", "system_key_password"],
|
||||
] as const) {
|
||||
if (dropColumnIfExists(sqlite, table, column)) {
|
||||
result.columnsDropped++;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.columnsDropped) {
|
||||
await DatabaseSaveTrigger.forceSave("legacy_share_cleanup");
|
||||
databaseLogger.info("Legacy shared-credential cleanup finished", {
|
||||
operation: "legacy_share_cleanup",
|
||||
...result,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { databaseLogger } from "../logger.js";
|
||||
import { DataCrypto } from "../data-crypto.js";
|
||||
import { DatabaseSaveTrigger } from "../database-save-trigger.js";
|
||||
import {
|
||||
createCurrentSettingsRepository,
|
||||
getCurrentRepositorySqlite,
|
||||
} from "../../database/repositories/factory.js";
|
||||
import { SharedHostSecretsManager } from "../shared-host-secrets-manager.js";
|
||||
|
||||
const MIGRATION_FLAG = "shared_host_secrets_migrated_v1";
|
||||
|
||||
interface GrantRow {
|
||||
hostAccessId: number;
|
||||
hostId: number;
|
||||
userId: string | null;
|
||||
roleId: number | null;
|
||||
ownerId: string;
|
||||
}
|
||||
|
||||
// One-time 2.5.x migration: rebuild every active share as per-protocol
|
||||
// secret snapshots in shared_host_secrets, then drop the SSH-only
|
||||
// shared_credentials table it replaces. Grants whose owner or recipient DEK
|
||||
// is unavailable are skipped (logged), never fatal to boot.
|
||||
export async function runSharedHostSecretsMigration(): Promise<{
|
||||
snapshotted: number;
|
||||
skipped: number;
|
||||
} | null> {
|
||||
const settingsRepository = createCurrentSettingsRepository();
|
||||
|
||||
try {
|
||||
if ((await settingsRepository.get(MIGRATION_FLAG)) === "done") {
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sqlite = getCurrentRepositorySqlite();
|
||||
const result = { snapshotted: 0, skipped: 0 };
|
||||
|
||||
try {
|
||||
const grants = sqlite
|
||||
.prepare(
|
||||
`SELECT ha.id AS hostAccessId, ha.host_id AS hostId,
|
||||
ha.user_id AS userId, ha.role_id AS roleId,
|
||||
h.user_id AS ownerId
|
||||
FROM host_access ha
|
||||
JOIN ssh_data h ON h.id = ha.host_id
|
||||
WHERE ha.expires_at IS NULL OR ha.expires_at >= ?`,
|
||||
)
|
||||
.all(new Date().toISOString()) as GrantRow[];
|
||||
|
||||
const manager = SharedHostSecretsManager.getInstance();
|
||||
|
||||
for (const grant of grants) {
|
||||
const targetUserIds = grant.userId
|
||||
? [grant.userId]
|
||||
: grant.roleId
|
||||
? (
|
||||
sqlite
|
||||
.prepare(`SELECT user_id FROM user_roles WHERE role_id = ?`)
|
||||
.all(grant.roleId) as Array<{ user_id: string }>
|
||||
).map((row) => row.user_id)
|
||||
: [];
|
||||
|
||||
for (const targetUserId of targetUserIds) {
|
||||
if (targetUserId === grant.ownerId) continue;
|
||||
|
||||
if (
|
||||
!DataCrypto.canUserAccessData(grant.ownerId) ||
|
||||
!DataCrypto.canUserAccessData(targetUserId)
|
||||
) {
|
||||
result.skipped++;
|
||||
databaseLogger.warn(
|
||||
"Skipping share snapshot migration: missing DEK",
|
||||
{
|
||||
operation: "shared_host_secrets_migration_skip",
|
||||
hostAccessId: grant.hostAccessId,
|
||||
targetUserId,
|
||||
},
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await manager.snapshotForUser(
|
||||
grant.hostAccessId,
|
||||
grant.hostId,
|
||||
targetUserId,
|
||||
grant.ownerId,
|
||||
);
|
||||
result.snapshotted++;
|
||||
} catch (error) {
|
||||
result.skipped++;
|
||||
databaseLogger.warn("Failed to migrate share snapshot", {
|
||||
operation: "shared_host_secrets_migration_failed",
|
||||
hostAccessId: grant.hostAccessId,
|
||||
targetUserId,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sqlite.exec("DROP TABLE IF EXISTS shared_credentials");
|
||||
await settingsRepository.set(MIGRATION_FLAG, "done");
|
||||
await DatabaseSaveTrigger.forceSave("shared_host_secrets_migration");
|
||||
|
||||
databaseLogger.info("Shared host secrets migration finished", {
|
||||
operation: "shared_host_secrets_migration",
|
||||
...result,
|
||||
});
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
databaseLogger.error("Shared host secrets migration failed", error, {
|
||||
operation: "shared_host_secrets_migration",
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,20 @@
|
||||
import { FieldCrypto } from "./field-crypto.js";
|
||||
import { LazyFieldEncryption } from "./lazy-field-encryption.js";
|
||||
import { UserCrypto } from "./user-crypto.js";
|
||||
import { UserKeyManager } from "./user-keys.js";
|
||||
import { DatabaseSaveTrigger } from "./database-save-trigger.js";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
|
||||
interface DatabaseInstance {
|
||||
prepare: (sql: string) => {
|
||||
all: (param?: unknown) => DatabaseRecord[];
|
||||
get: (param?: unknown) => DatabaseRecord;
|
||||
run: (...params: unknown[]) => unknown;
|
||||
};
|
||||
}
|
||||
|
||||
interface DatabaseRecord {
|
||||
id: number | string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
import {
|
||||
createCurrentUserEncryptionMigrationStore,
|
||||
RawSqliteUserEncryptionMigrationStore,
|
||||
type LegacyDatabaseInstance,
|
||||
type UserEncryptionMigrationStore,
|
||||
} from "./user-encryption-migration-store.js";
|
||||
|
||||
class DataCrypto {
|
||||
private static userCrypto: UserCrypto;
|
||||
private static userKeys: UserKeyManager;
|
||||
|
||||
static initialize() {
|
||||
this.userCrypto = UserCrypto.getInstance();
|
||||
this.userKeys = UserKeyManager.getInstance();
|
||||
}
|
||||
|
||||
static encryptRecord<T extends Record<string, unknown>>(
|
||||
@@ -30,14 +24,14 @@ class DataCrypto {
|
||||
userDataKey: Buffer,
|
||||
): T {
|
||||
const encryptedRecord: Record<string, unknown> = { ...record };
|
||||
const recordId = record.id || "temp-" + Date.now();
|
||||
const recordId = String(record.id || "temp-" + Date.now());
|
||||
|
||||
for (const [fieldName, value] of Object.entries(record)) {
|
||||
if (FieldCrypto.shouldEncryptField(tableName, fieldName) && value) {
|
||||
encryptedRecord[fieldName] = FieldCrypto.encryptField(
|
||||
value as string,
|
||||
userDataKey,
|
||||
recordId as string,
|
||||
recordId,
|
||||
fieldName,
|
||||
);
|
||||
}
|
||||
@@ -55,14 +49,14 @@ class DataCrypto {
|
||||
if (!record) return record;
|
||||
|
||||
const decryptedRecord: Record<string, unknown> = { ...record };
|
||||
const recordId = record.id;
|
||||
const recordId = String(record.id);
|
||||
|
||||
for (const [fieldName, value] of Object.entries(record)) {
|
||||
if (FieldCrypto.shouldEncryptField(tableName, fieldName) && value) {
|
||||
decryptedRecord[fieldName] = LazyFieldEncryption.safeGetFieldValue(
|
||||
value as string,
|
||||
userDataKey,
|
||||
recordId as string,
|
||||
recordId,
|
||||
fieldName,
|
||||
);
|
||||
}
|
||||
@@ -86,7 +80,34 @@ class DataCrypto {
|
||||
static async migrateUserSensitiveFields(
|
||||
userId: string,
|
||||
userDataKey: Buffer,
|
||||
db: DatabaseInstance,
|
||||
db: LegacyDatabaseInstance,
|
||||
): Promise<{
|
||||
migrated: boolean;
|
||||
migratedTables: string[];
|
||||
migratedFieldsCount: number;
|
||||
}> {
|
||||
try {
|
||||
const store = new RawSqliteUserEncryptionMigrationStore(db);
|
||||
return await this.migrateUserSensitiveFieldsInStore(
|
||||
userId,
|
||||
userDataKey,
|
||||
store,
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.error("User sensitive fields migration failed", error, {
|
||||
operation: "user_sensitive_migration_failed",
|
||||
userId,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
});
|
||||
|
||||
return { migrated: false, migratedTables: [], migratedFieldsCount: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
private static async migrateUserSensitiveFieldsInStore(
|
||||
userId: string,
|
||||
userDataKey: Buffer,
|
||||
store: UserEncryptionMigrationStore,
|
||||
): Promise<{
|
||||
migrated: boolean;
|
||||
migratedTables: string[];
|
||||
@@ -101,16 +122,14 @@ class DataCrypto {
|
||||
await LazyFieldEncryption.checkUserNeedsMigration(
|
||||
userId,
|
||||
userDataKey,
|
||||
db,
|
||||
store,
|
||||
);
|
||||
|
||||
if (!needsMigration) {
|
||||
return { migrated: false, migratedTables: [], migratedFieldsCount: 0 };
|
||||
}
|
||||
|
||||
const sshDataRecords = db
|
||||
.prepare("SELECT * FROM ssh_data WHERE user_id = ?")
|
||||
.all(userId) as DatabaseRecord[];
|
||||
const sshDataRecords = store.listHostRecords(userId);
|
||||
for (const record of sshDataRecords) {
|
||||
const sensitiveFields =
|
||||
LazyFieldEncryption.getSensitiveFieldsForTable("ssh_data");
|
||||
@@ -123,22 +142,7 @@ class DataCrypto {
|
||||
);
|
||||
|
||||
if (needsUpdate) {
|
||||
const updateQuery = `
|
||||
UPDATE ssh_data
|
||||
SET password = ?, key = ?, key_password = ?, key_type = ?, autostart_password = ?, autostart_key = ?, autostart_key_password = ?, sudo_password = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`;
|
||||
db.prepare(updateQuery).run(
|
||||
updatedRecord.password || null,
|
||||
updatedRecord.key || null,
|
||||
updatedRecord.key_password || null,
|
||||
updatedRecord.key_type || null,
|
||||
updatedRecord.autostart_password || null,
|
||||
updatedRecord.autostart_key || null,
|
||||
updatedRecord.autostart_key_password || null,
|
||||
updatedRecord.sudo_password || null,
|
||||
record.id,
|
||||
);
|
||||
store.updateHostSensitiveFields(record.id, updatedRecord);
|
||||
|
||||
migratedFieldsCount += migratedFields.length;
|
||||
if (!migratedTables.includes("ssh_data")) {
|
||||
@@ -148,9 +152,7 @@ class DataCrypto {
|
||||
}
|
||||
}
|
||||
|
||||
const sshCredentialsRecords = db
|
||||
.prepare("SELECT * FROM ssh_credentials WHERE user_id = ?")
|
||||
.all(userId) as DatabaseRecord[];
|
||||
const sshCredentialsRecords = store.listCredentialRecords(userId);
|
||||
for (const record of sshCredentialsRecords) {
|
||||
const sensitiveFields =
|
||||
LazyFieldEncryption.getSensitiveFieldsForTable("ssh_credentials");
|
||||
@@ -163,20 +165,7 @@ class DataCrypto {
|
||||
);
|
||||
|
||||
if (needsUpdate) {
|
||||
const updateQuery = `
|
||||
UPDATE ssh_credentials
|
||||
SET password = ?, key = ?, key_password = ?, private_key = ?, public_key = ?, key_type = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`;
|
||||
db.prepare(updateQuery).run(
|
||||
updatedRecord.password || null,
|
||||
updatedRecord.key || null,
|
||||
updatedRecord.key_password || null,
|
||||
updatedRecord.private_key || null,
|
||||
updatedRecord.public_key || null,
|
||||
updatedRecord.key_type || null,
|
||||
record.id,
|
||||
);
|
||||
store.updateCredentialSensitiveFields(record.id, updatedRecord);
|
||||
|
||||
migratedFieldsCount += migratedFields.length;
|
||||
if (!migratedTables.includes("ssh_credentials")) {
|
||||
@@ -186,9 +175,7 @@ class DataCrypto {
|
||||
}
|
||||
}
|
||||
|
||||
const userRecord = db
|
||||
.prepare("SELECT * FROM users WHERE id = ?")
|
||||
.get(userId) as DatabaseRecord | undefined;
|
||||
const userRecord = store.getUserRecord(userId);
|
||||
if (userRecord) {
|
||||
const sensitiveFields =
|
||||
LazyFieldEncryption.getSensitiveFieldsForTable("users");
|
||||
@@ -201,18 +188,7 @@ class DataCrypto {
|
||||
);
|
||||
|
||||
if (needsUpdate) {
|
||||
const updateQuery = `
|
||||
UPDATE users
|
||||
SET totp_secret = ?, totp_backup_codes = ?, client_secret = ?, oidc_identifier = ?
|
||||
WHERE id = ?
|
||||
`;
|
||||
db.prepare(updateQuery).run(
|
||||
updatedRecord.totp_secret || null,
|
||||
updatedRecord.totp_backup_codes || null,
|
||||
updatedRecord.client_secret || null,
|
||||
updatedRecord.oidc_identifier || null,
|
||||
userId,
|
||||
);
|
||||
store.updateUserSensitiveFields(userId, updatedRecord);
|
||||
|
||||
migratedFieldsCount += migratedFields.length;
|
||||
if (!migratedTables.includes("users")) {
|
||||
@@ -234,188 +210,35 @@ class DataCrypto {
|
||||
}
|
||||
}
|
||||
|
||||
static getUserDataKey(userId: string): Buffer | null {
|
||||
return this.userCrypto.getUserDataKey(userId);
|
||||
static async migrateCurrentUserSensitiveFields(
|
||||
userId: string,
|
||||
userDataKey: Buffer,
|
||||
): Promise<{
|
||||
migrated: boolean;
|
||||
migratedTables: string[];
|
||||
migratedFieldsCount: number;
|
||||
}> {
|
||||
const result = await this.migrateUserSensitiveFieldsInStore(
|
||||
userId,
|
||||
userDataKey,
|
||||
await createCurrentUserEncryptionMigrationStore(),
|
||||
);
|
||||
|
||||
if (result.migrated) {
|
||||
await DatabaseSaveTrigger.forceSave(
|
||||
"user_sensitive_migration_explicit_save",
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static async reencryptUserDataAfterPasswordReset(
|
||||
userId: string,
|
||||
newUserDataKey: Buffer,
|
||||
db: DatabaseInstance,
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
reencryptedTables: string[];
|
||||
reencryptedFieldsCount: number;
|
||||
errors: string[];
|
||||
}> {
|
||||
const result = {
|
||||
success: false,
|
||||
reencryptedTables: [] as string[],
|
||||
reencryptedFieldsCount: 0,
|
||||
errors: [] as string[],
|
||||
};
|
||||
|
||||
try {
|
||||
const tablesToReencrypt = [
|
||||
{
|
||||
table: "ssh_data",
|
||||
fields: [
|
||||
"password",
|
||||
"key",
|
||||
"key_password",
|
||||
"sudo_password",
|
||||
"autostart_password",
|
||||
"autostart_key",
|
||||
"autostart_key_password",
|
||||
],
|
||||
},
|
||||
{
|
||||
table: "ssh_credentials",
|
||||
fields: [
|
||||
"password",
|
||||
"key",
|
||||
"private_key",
|
||||
"public_key",
|
||||
"key_password",
|
||||
],
|
||||
},
|
||||
{
|
||||
table: "users",
|
||||
fields: [
|
||||
"client_secret",
|
||||
"totp_secret",
|
||||
"totp_backup_codes",
|
||||
"oidc_identifier",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
for (const { table, fields } of tablesToReencrypt) {
|
||||
try {
|
||||
const selectQuery =
|
||||
table === "users"
|
||||
? `SELECT * FROM ${table} WHERE id = ?`
|
||||
: `SELECT * FROM ${table} WHERE user_id = ?`;
|
||||
const records = db
|
||||
.prepare(selectQuery)
|
||||
.all(userId) as DatabaseRecord[];
|
||||
|
||||
for (const record of records) {
|
||||
const recordId = record.id.toString();
|
||||
const updatedRecord: DatabaseRecord = { ...record };
|
||||
let needsUpdate = false;
|
||||
|
||||
for (const fieldName of fields) {
|
||||
const fieldValue = record[fieldName];
|
||||
|
||||
if (
|
||||
fieldValue &&
|
||||
typeof fieldValue === "string" &&
|
||||
fieldValue.trim() !== ""
|
||||
) {
|
||||
try {
|
||||
const reencryptedValue = FieldCrypto.encryptField(
|
||||
fieldValue,
|
||||
newUserDataKey,
|
||||
recordId,
|
||||
fieldName,
|
||||
);
|
||||
|
||||
updatedRecord[fieldName] = reencryptedValue;
|
||||
needsUpdate = true;
|
||||
result.reencryptedFieldsCount++;
|
||||
} catch (error) {
|
||||
const errorMsg = `Failed to re-encrypt ${fieldName} for ${table} record ${recordId}: ${error instanceof Error ? error.message : "Unknown error"}`;
|
||||
result.errors.push(errorMsg);
|
||||
databaseLogger.warn(
|
||||
"Field re-encryption failed during password reset",
|
||||
{
|
||||
operation: "password_reset_reencrypt_failed",
|
||||
userId,
|
||||
table,
|
||||
recordId,
|
||||
fieldName,
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "Unknown error",
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (needsUpdate) {
|
||||
const updateFields = fields.filter(
|
||||
(field) => updatedRecord[field] !== record[field],
|
||||
);
|
||||
if (updateFields.length > 0) {
|
||||
const setClause = updateFields
|
||||
.map((f) => `${f} = ?`)
|
||||
.join(", ");
|
||||
const updateQuery =
|
||||
table === "users"
|
||||
? `UPDATE ${table} SET ${setClause} WHERE id = ?`
|
||||
: `UPDATE ${table} SET ${setClause}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`;
|
||||
const updateValues = updateFields.map(
|
||||
(field) => updatedRecord[field],
|
||||
);
|
||||
updateValues.push(record.id);
|
||||
|
||||
db.prepare(updateQuery).run(...updateValues);
|
||||
|
||||
if (!result.reencryptedTables.includes(table)) {
|
||||
result.reencryptedTables.push(table);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (tableError) {
|
||||
const errorMsg = `Failed to re-encrypt table ${table}: ${tableError instanceof Error ? tableError.message : "Unknown error"}`;
|
||||
result.errors.push(errorMsg);
|
||||
databaseLogger.error(
|
||||
"Table re-encryption failed during password reset",
|
||||
tableError,
|
||||
{
|
||||
operation: "password_reset_table_reencrypt_failed",
|
||||
userId,
|
||||
table,
|
||||
error:
|
||||
tableError instanceof Error
|
||||
? tableError.message
|
||||
: "Unknown error",
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
result.success = result.errors.length === 0;
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"User data re-encryption failed after password reset",
|
||||
error,
|
||||
{
|
||||
operation: "password_reset_reencrypt_failed",
|
||||
userId,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
},
|
||||
);
|
||||
|
||||
result.errors.push(
|
||||
`Critical error during re-encryption: ${error instanceof Error ? error.message : "Unknown error"}`,
|
||||
);
|
||||
return result;
|
||||
}
|
||||
static getUserDataKey(userId: string): Buffer | null {
|
||||
return this.userKeys.tryGetUserDEK(userId);
|
||||
}
|
||||
|
||||
static validateUserAccess(userId: string): Buffer {
|
||||
const userDataKey = this.getUserDataKey(userId);
|
||||
if (!userDataKey) {
|
||||
throw new Error(`User ${userId} data not unlocked`);
|
||||
}
|
||||
return userDataKey;
|
||||
return this.userKeys.getUserDEK(userId);
|
||||
}
|
||||
|
||||
static encryptRecordForUser<T extends Record<string, unknown>>(
|
||||
@@ -446,7 +269,7 @@ class DataCrypto {
|
||||
}
|
||||
|
||||
static canUserAccessData(userId: string): boolean {
|
||||
return this.userCrypto.isUserUnlocked(userId);
|
||||
return this.userKeys.tryGetUserDEK(userId) !== null;
|
||||
}
|
||||
|
||||
static testUserEncryption(userId: string): boolean {
|
||||
@@ -473,48 +296,6 @@ class DataCrypto {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static async encryptRecordWithSystemKey<T extends Record<string, unknown>>(
|
||||
tableName: string,
|
||||
record: T,
|
||||
systemKey: Buffer,
|
||||
): Promise<Partial<T>> {
|
||||
const systemEncrypted: Record<string, unknown> = {};
|
||||
const recordId = record.id || "temp-" + Date.now();
|
||||
|
||||
if (tableName !== "ssh_credentials") {
|
||||
return systemEncrypted as Partial<T>;
|
||||
}
|
||||
|
||||
if (record.password && typeof record.password === "string") {
|
||||
systemEncrypted.systemPassword = FieldCrypto.encryptField(
|
||||
record.password as string,
|
||||
systemKey,
|
||||
recordId as string,
|
||||
"password",
|
||||
);
|
||||
}
|
||||
|
||||
if (record.key && typeof record.key === "string") {
|
||||
systemEncrypted.systemKey = FieldCrypto.encryptField(
|
||||
record.key as string,
|
||||
systemKey,
|
||||
recordId as string,
|
||||
"key",
|
||||
);
|
||||
}
|
||||
|
||||
if (record.keyPassword && typeof record.keyPassword === "string") {
|
||||
systemEncrypted.systemKeyPassword = FieldCrypto.encryptField(
|
||||
record.keyPassword as string,
|
||||
systemKey,
|
||||
recordId as string,
|
||||
"key_password",
|
||||
);
|
||||
}
|
||||
|
||||
return systemEncrypted as Partial<T>;
|
||||
}
|
||||
}
|
||||
|
||||
export { DataCrypto };
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,198 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
|
||||
export const DATABASE_LAYER_PREUPGRADE_BACKUP_MARKER =
|
||||
".database-layer-preupgrade-backup.json";
|
||||
export const DATABASE_LAYER_PREUPGRADE_BACKUP_PREFIX =
|
||||
"pre-database-layer-refactor";
|
||||
export const DATABASE_LAYER_SKIP_PREUPGRADE_BACKUP_ENV =
|
||||
"DATABASE_LAYER_SKIP_PREUPGRADE_BACKUP";
|
||||
export const DATABASE_LAYER_PREUPGRADE_BACKUP_KEEP_ENV =
|
||||
"DATABASE_LAYER_PREUPGRADE_BACKUP_KEEP";
|
||||
|
||||
interface PreupgradeBackupOptions {
|
||||
dataDir?: string;
|
||||
version?: string;
|
||||
now?: Date;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
interface BackupFileEntry {
|
||||
source: string;
|
||||
backup: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface PreupgradeBackupManifest {
|
||||
reason: "pre-database-layer-refactor";
|
||||
createdAt: string;
|
||||
sourceVersion: string;
|
||||
dataDir: string;
|
||||
backupDir: string;
|
||||
files: BackupFileEntry[];
|
||||
}
|
||||
|
||||
export interface PreupgradeBackupResult {
|
||||
status: "created" | "skipped";
|
||||
reason: "backup_created" | "skip_env" | "marker_exists" | "no_database_file";
|
||||
backupDir?: string;
|
||||
markerPath: string;
|
||||
}
|
||||
|
||||
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
|
||||
|
||||
function timestampForPath(now: Date): string {
|
||||
return now.toISOString().replace(/[:.]/g, "-");
|
||||
}
|
||||
|
||||
function parseKeepCount(env: NodeJS.ProcessEnv): number {
|
||||
const raw = env[DATABASE_LAYER_PREUPGRADE_BACKUP_KEEP_ENV];
|
||||
if (!raw) return 3;
|
||||
|
||||
const parsed = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(parsed) || parsed < 1) return 3;
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function copyIfExists(
|
||||
source: string,
|
||||
backupDir: string,
|
||||
): BackupFileEntry | null {
|
||||
if (!fs.existsSync(source)) return null;
|
||||
|
||||
const backup = path.join(backupDir, path.basename(source));
|
||||
fs.copyFileSync(source, backup);
|
||||
|
||||
return {
|
||||
source,
|
||||
backup,
|
||||
size: fs.statSync(backup).size,
|
||||
};
|
||||
}
|
||||
|
||||
function cleanupOldBackups(backupsRoot: string, keepCount: number): void {
|
||||
if (!fs.existsSync(backupsRoot)) return;
|
||||
|
||||
const entries = fs
|
||||
.readdirSync(backupsRoot, { withFileTypes: true })
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.isDirectory() &&
|
||||
entry.name.startsWith(`${DATABASE_LAYER_PREUPGRADE_BACKUP_PREFIX}-`),
|
||||
)
|
||||
.map((entry) => {
|
||||
const fullPath = path.join(backupsRoot, entry.name);
|
||||
return {
|
||||
fullPath,
|
||||
mtimeMs: fs.statSync(fullPath).mtimeMs,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
||||
|
||||
for (const entry of entries.slice(keepCount)) {
|
||||
fs.rmSync(entry.fullPath, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export function ensureDatabaseLayerPreupgradeBackup(
|
||||
options: PreupgradeBackupOptions = {},
|
||||
): PreupgradeBackupResult {
|
||||
const env = options.env ?? process.env;
|
||||
const dataDir = path.resolve(options.dataDir ?? env.DATA_DIR ?? "./db/data");
|
||||
const markerPath = path.join(
|
||||
dataDir,
|
||||
DATABASE_LAYER_PREUPGRADE_BACKUP_MARKER,
|
||||
);
|
||||
|
||||
if (
|
||||
TRUE_VALUES.has(
|
||||
env[DATABASE_LAYER_SKIP_PREUPGRADE_BACKUP_ENV]?.trim().toLowerCase() ??
|
||||
"",
|
||||
)
|
||||
) {
|
||||
databaseLogger.warn("Database layer pre-upgrade backup skipped by env", {
|
||||
operation: "database_layer_preupgrade_backup_skipped",
|
||||
envKey: DATABASE_LAYER_SKIP_PREUPGRADE_BACKUP_ENV,
|
||||
});
|
||||
return { status: "skipped", reason: "skip_env", markerPath };
|
||||
}
|
||||
|
||||
if (fs.existsSync(markerPath)) {
|
||||
return { status: "skipped", reason: "marker_exists", markerPath };
|
||||
}
|
||||
|
||||
const encryptedDbPath = path.join(dataDir, "db.sqlite.encrypted");
|
||||
const encryptedMetadataPath = `${encryptedDbPath}.meta`;
|
||||
const plaintextDbPath = path.join(dataDir, "db.sqlite");
|
||||
const envPath = path.join(dataDir, ".env");
|
||||
const databaseFiles = [
|
||||
encryptedDbPath,
|
||||
encryptedMetadataPath,
|
||||
plaintextDbPath,
|
||||
].filter((file) => fs.existsSync(file));
|
||||
|
||||
if (databaseFiles.length === 0) {
|
||||
return { status: "skipped", reason: "no_database_file", markerPath };
|
||||
}
|
||||
|
||||
const backupsRoot = path.join(dataDir, "backups");
|
||||
const backupDir = path.join(
|
||||
backupsRoot,
|
||||
`${DATABASE_LAYER_PREUPGRADE_BACKUP_PREFIX}-${timestampForPath(
|
||||
options.now ?? new Date(),
|
||||
)}`,
|
||||
);
|
||||
|
||||
try {
|
||||
fs.mkdirSync(backupDir, { recursive: true });
|
||||
|
||||
const files = [...databaseFiles, envPath]
|
||||
.map((source) => copyIfExists(source, backupDir))
|
||||
.filter((entry): entry is BackupFileEntry => entry !== null);
|
||||
|
||||
const manifest: PreupgradeBackupManifest = {
|
||||
reason: "pre-database-layer-refactor",
|
||||
createdAt: (options.now ?? new Date()).toISOString(),
|
||||
sourceVersion: options.version ?? env.VERSION ?? "unknown",
|
||||
dataDir,
|
||||
backupDir,
|
||||
files,
|
||||
};
|
||||
|
||||
fs.writeFileSync(
|
||||
path.join(backupDir, "manifest.json"),
|
||||
JSON.stringify(manifest, null, 2),
|
||||
);
|
||||
fs.writeFileSync(markerPath, JSON.stringify(manifest, null, 2));
|
||||
|
||||
cleanupOldBackups(backupsRoot, parseKeepCount(env));
|
||||
|
||||
databaseLogger.info("Database layer pre-upgrade backup created", {
|
||||
operation: "database_layer_preupgrade_backup_created",
|
||||
backupDir,
|
||||
files: files.map((file) => path.basename(file.backup)),
|
||||
});
|
||||
|
||||
return {
|
||||
status: "created",
|
||||
reason: "backup_created",
|
||||
backupDir,
|
||||
markerPath,
|
||||
};
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to create database layer pre-upgrade backup",
|
||||
error,
|
||||
{
|
||||
operation: "database_layer_preupgrade_backup_failed",
|
||||
dataDir,
|
||||
backupDir,
|
||||
},
|
||||
);
|
||||
throw new Error(
|
||||
`Failed to create database layer pre-upgrade backup. Set ${DATABASE_LAYER_SKIP_PREUPGRADE_BACKUP_ENV}=1 only if you already have a verified external backup.`,
|
||||
{ cause: error },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import Database from "better-sqlite3";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
import { DatabaseFileEncryption } from "./database-file-encryption.js";
|
||||
import { LegacySqliteDatabaseCopyStore } from "./legacy-sqlite-database-copy-store.js";
|
||||
|
||||
export interface MigrationResult {
|
||||
success: boolean;
|
||||
@@ -124,80 +124,6 @@ export class DatabaseMigration {
|
||||
}
|
||||
}
|
||||
|
||||
private async verifyMigration(
|
||||
originalDb: Database.Database,
|
||||
memoryDb: Database.Database,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
memoryDb.exec("PRAGMA foreign_keys = OFF");
|
||||
|
||||
const originalTables = originalDb
|
||||
.prepare(
|
||||
`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type='table' AND name NOT LIKE 'sqlite_%'
|
||||
ORDER BY name
|
||||
`,
|
||||
)
|
||||
.all() as { name: string }[];
|
||||
|
||||
const memoryTables = memoryDb
|
||||
.prepare(
|
||||
`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type='table' AND name NOT LIKE 'sqlite_%'
|
||||
ORDER BY name
|
||||
`,
|
||||
)
|
||||
.all() as { name: string }[];
|
||||
|
||||
if (originalTables.length !== memoryTables.length) {
|
||||
databaseLogger.error(
|
||||
"Table count mismatch during migration verification",
|
||||
null,
|
||||
{
|
||||
operation: "migration_verify_failed",
|
||||
originalCount: originalTables.length,
|
||||
memoryCount: memoryTables.length,
|
||||
},
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const table of originalTables) {
|
||||
const originalCount = originalDb
|
||||
.prepare(`SELECT COUNT(*) as count FROM ${table.name}`)
|
||||
.get() as { count: number };
|
||||
const memoryCount = memoryDb
|
||||
.prepare(`SELECT COUNT(*) as count FROM ${table.name}`)
|
||||
.get() as { count: number };
|
||||
|
||||
if (originalCount.count !== memoryCount.count) {
|
||||
databaseLogger.error(
|
||||
"Row count mismatch for table during migration verification",
|
||||
null,
|
||||
{
|
||||
operation: "migration_verify_table_failed",
|
||||
table: table.name,
|
||||
originalRows: originalCount.count,
|
||||
memoryRows: memoryCount.count,
|
||||
},
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
memoryDb.exec("PRAGMA foreign_keys = ON");
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
databaseLogger.error("Migration verification failed", error, {
|
||||
operation: "migration_verify_error",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async migrateDatabase(): Promise<MigrationResult> {
|
||||
const startTime = Date.now();
|
||||
let backupPath: string | undefined;
|
||||
@@ -207,121 +133,46 @@ export class DatabaseMigration {
|
||||
try {
|
||||
backupPath = this.createBackup();
|
||||
|
||||
const originalDb = new Database(this.unencryptedDbPath, {
|
||||
readonly: true,
|
||||
const copyResult =
|
||||
new LegacySqliteDatabaseCopyStore().copyDatabaseToMemoryBuffer(
|
||||
this.unencryptedDbPath,
|
||||
);
|
||||
migratedTables = copyResult.migratedTables;
|
||||
migratedRows = copyResult.migratedRows;
|
||||
|
||||
await DatabaseFileEncryption.encryptDatabaseFromBuffer(
|
||||
copyResult.buffer,
|
||||
this.encryptedDbPath,
|
||||
);
|
||||
|
||||
if (
|
||||
!DatabaseFileEncryption.isEncryptedDatabaseFile(this.encryptedDbPath)
|
||||
) {
|
||||
throw new Error("Encrypted database file verification failed");
|
||||
}
|
||||
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const migratedPath = `${this.unencryptedDbPath}.migrated-${timestamp}`;
|
||||
|
||||
fs.renameSync(this.unencryptedDbPath, migratedPath);
|
||||
|
||||
databaseLogger.success("Database migration completed successfully", {
|
||||
operation: "migration_complete",
|
||||
migratedTables,
|
||||
migratedRows,
|
||||
duration: Date.now() - startTime,
|
||||
backupPath,
|
||||
migratedPath,
|
||||
encryptedDbPath: this.encryptedDbPath,
|
||||
});
|
||||
|
||||
const memoryDb = new Database(":memory:");
|
||||
|
||||
try {
|
||||
const tables = originalDb
|
||||
.prepare(
|
||||
`
|
||||
SELECT name, sql FROM sqlite_master
|
||||
WHERE type='table' AND name NOT LIKE 'sqlite_%'
|
||||
`,
|
||||
)
|
||||
.all() as { name: string; sql: string }[];
|
||||
|
||||
for (const table of tables) {
|
||||
memoryDb.exec(table.sql);
|
||||
migratedTables++;
|
||||
}
|
||||
|
||||
memoryDb.exec("PRAGMA foreign_keys = OFF");
|
||||
|
||||
for (const table of tables) {
|
||||
const rows = originalDb
|
||||
.prepare(`SELECT * FROM ${table.name}`)
|
||||
.all() as Record<string, unknown>[];
|
||||
|
||||
if (rows.length > 0) {
|
||||
const columns = Object.keys(rows[0]);
|
||||
const placeholders = columns.map(() => "?").join(", ");
|
||||
const insertStmt = memoryDb.prepare(
|
||||
`INSERT INTO ${table.name} (${columns.join(", ")}) VALUES (${placeholders})`,
|
||||
);
|
||||
|
||||
const insertTransaction = memoryDb.transaction(
|
||||
(dataRows: Record<string, unknown>[]) => {
|
||||
for (const row of dataRows) {
|
||||
const values = columns.map((col) => row[col]);
|
||||
insertStmt.run(values);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
insertTransaction(rows);
|
||||
migratedRows += rows.length;
|
||||
}
|
||||
}
|
||||
|
||||
memoryDb.exec("PRAGMA foreign_keys = ON");
|
||||
|
||||
const fkCheckResult = memoryDb
|
||||
.prepare("PRAGMA foreign_key_check")
|
||||
.all();
|
||||
if (fkCheckResult.length > 0) {
|
||||
databaseLogger.error(
|
||||
"Foreign key constraints violations detected after migration",
|
||||
null,
|
||||
{
|
||||
operation: "migration_fk_check_failed",
|
||||
violations: fkCheckResult,
|
||||
},
|
||||
);
|
||||
throw new Error(
|
||||
`Foreign key violations detected: ${JSON.stringify(fkCheckResult)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const verificationPassed = await this.verifyMigration(
|
||||
originalDb,
|
||||
memoryDb,
|
||||
);
|
||||
if (!verificationPassed) {
|
||||
throw new Error("Migration integrity verification failed");
|
||||
}
|
||||
|
||||
const buffer = memoryDb.serialize();
|
||||
|
||||
await DatabaseFileEncryption.encryptDatabaseFromBuffer(
|
||||
buffer,
|
||||
this.encryptedDbPath,
|
||||
);
|
||||
|
||||
if (
|
||||
!DatabaseFileEncryption.isEncryptedDatabaseFile(this.encryptedDbPath)
|
||||
) {
|
||||
throw new Error("Encrypted database file verification failed");
|
||||
}
|
||||
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
|
||||
const migratedPath = `${this.unencryptedDbPath}.migrated-${timestamp}`;
|
||||
|
||||
fs.renameSync(this.unencryptedDbPath, migratedPath);
|
||||
|
||||
databaseLogger.success("Database migration completed successfully", {
|
||||
operation: "migration_complete",
|
||||
migratedTables,
|
||||
migratedRows,
|
||||
duration: Date.now() - startTime,
|
||||
backupPath,
|
||||
migratedPath,
|
||||
encryptedDbPath: this.encryptedDbPath,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
migratedTables,
|
||||
migratedRows,
|
||||
backupPath,
|
||||
duration: Date.now() - startTime,
|
||||
};
|
||||
} finally {
|
||||
originalDb.close();
|
||||
memoryDb.close();
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
migratedTables,
|
||||
migratedRows,
|
||||
backupPath,
|
||||
duration: Date.now() - startTime,
|
||||
};
|
||||
} catch (error) {
|
||||
const errorMessage =
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import crypto from "crypto";
|
||||
import { FieldCrypto } from "./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,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,6 @@
|
||||
import { FieldCrypto } from "./field-crypto.js";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
|
||||
interface DatabaseInstance {
|
||||
prepare: (sql: string) => {
|
||||
all: (param?: unknown) => unknown[];
|
||||
get: (param?: unknown) => unknown;
|
||||
run: (...params: unknown[]) => unknown;
|
||||
};
|
||||
}
|
||||
import type { UserEncryptionMigrationStore } from "./user-encryption-migration-store.js";
|
||||
|
||||
export class LazyFieldEncryption {
|
||||
private static readonly LEGACY_FIELD_NAME_MAP: Record<string, string> = {
|
||||
@@ -367,7 +360,7 @@ export class LazyFieldEncryption {
|
||||
static async checkUserNeedsMigration(
|
||||
userId: string,
|
||||
userKEK: Buffer,
|
||||
db: DatabaseInstance,
|
||||
store: UserEncryptionMigrationStore,
|
||||
): Promise<{
|
||||
needsMigration: boolean;
|
||||
plaintextFields: Array<{
|
||||
@@ -384,11 +377,7 @@ export class LazyFieldEncryption {
|
||||
let needsMigration = false;
|
||||
|
||||
try {
|
||||
const sshHosts = db
|
||||
.prepare("SELECT * FROM ssh_data WHERE user_id = ?")
|
||||
.all(userId) as Array<
|
||||
Record<string, unknown> & { id: string | number }
|
||||
>;
|
||||
const sshHosts = store.listHostRecords(userId);
|
||||
for (const host of sshHosts) {
|
||||
const sensitiveFields = this.getSensitiveFieldsForTable("ssh_data");
|
||||
const hostPlaintextFields: string[] = [];
|
||||
@@ -418,11 +407,7 @@ export class LazyFieldEncryption {
|
||||
}
|
||||
}
|
||||
|
||||
const sshCredentials = db
|
||||
.prepare("SELECT * FROM ssh_credentials WHERE user_id = ?")
|
||||
.all(userId) as Array<
|
||||
Record<string, unknown> & { id: string | number }
|
||||
>;
|
||||
const sshCredentials = store.listCredentialRecords(userId);
|
||||
for (const credential of sshCredentials) {
|
||||
const sensitiveFields =
|
||||
this.getSensitiveFieldsForTable("ssh_credentials");
|
||||
@@ -453,16 +438,18 @@ export class LazyFieldEncryption {
|
||||
}
|
||||
}
|
||||
|
||||
const user = db.prepare("SELECT * FROM users WHERE id = ?").get(userId);
|
||||
const user = store.getUserRecord(userId);
|
||||
if (user) {
|
||||
const sensitiveFields = this.getSensitiveFieldsForTable("users");
|
||||
const userPlaintextFields: string[] = [];
|
||||
|
||||
for (const field of sensitiveFields) {
|
||||
const column = this.propertyToColumn(field);
|
||||
const value = user[column];
|
||||
if (
|
||||
user[column] &&
|
||||
this.fieldNeedsMigration(user[column], userKEK, userId, field)
|
||||
typeof value === "string" &&
|
||||
value &&
|
||||
this.fieldNeedsMigration(value, userKEK, userId, field)
|
||||
) {
|
||||
userPlaintextFields.push(field);
|
||||
needsMigration = true;
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import Database from "better-sqlite3";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
|
||||
interface LegacyTableDefinition {
|
||||
name: string;
|
||||
sql: string;
|
||||
}
|
||||
|
||||
export interface LegacyDatabaseCopyResult {
|
||||
buffer: Buffer;
|
||||
migratedTables: number;
|
||||
migratedRows: number;
|
||||
}
|
||||
|
||||
export class LegacySqliteDatabaseCopyStore {
|
||||
copyDatabaseToMemoryBuffer(sourcePath: string): LegacyDatabaseCopyResult {
|
||||
const originalDb = new Database(sourcePath, { readonly: true });
|
||||
const memoryDb = new Database(":memory:");
|
||||
|
||||
try {
|
||||
const tables = this.listTableDefinitions(originalDb);
|
||||
let migratedTables = 0;
|
||||
let migratedRows = 0;
|
||||
|
||||
for (const table of tables) {
|
||||
memoryDb.exec(table.sql);
|
||||
migratedTables++;
|
||||
}
|
||||
|
||||
memoryDb.exec("PRAGMA foreign_keys = OFF");
|
||||
|
||||
for (const table of tables) {
|
||||
migratedRows += this.copyTableRows(originalDb, memoryDb, table.name);
|
||||
}
|
||||
|
||||
memoryDb.exec("PRAGMA foreign_keys = ON");
|
||||
this.assertNoForeignKeyViolations(memoryDb);
|
||||
this.assertRowCountsMatch(originalDb, memoryDb);
|
||||
|
||||
return {
|
||||
buffer: memoryDb.serialize(),
|
||||
migratedTables,
|
||||
migratedRows,
|
||||
};
|
||||
} finally {
|
||||
originalDb.close();
|
||||
memoryDb.close();
|
||||
}
|
||||
}
|
||||
|
||||
private listTableDefinitions(db: Database.Database): LegacyTableDefinition[] {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT name, sql FROM sqlite_master
|
||||
WHERE type='table' AND name NOT LIKE 'sqlite_%'
|
||||
ORDER BY name
|
||||
`,
|
||||
)
|
||||
.all() as LegacyTableDefinition[];
|
||||
}
|
||||
|
||||
private listTableNames(db: Database.Database): string[] {
|
||||
return db
|
||||
.prepare(
|
||||
`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type='table' AND name NOT LIKE 'sqlite_%'
|
||||
ORDER BY name
|
||||
`,
|
||||
)
|
||||
.all()
|
||||
.map((table) => (table as { name: string }).name);
|
||||
}
|
||||
|
||||
private copyTableRows(
|
||||
originalDb: Database.Database,
|
||||
memoryDb: Database.Database,
|
||||
tableName: string,
|
||||
): number {
|
||||
const rows = originalDb
|
||||
.prepare(`SELECT * FROM ${tableName}`)
|
||||
.all() as Record<string, unknown>[];
|
||||
|
||||
if (rows.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const columns = Object.keys(rows[0]);
|
||||
const placeholders = columns.map(() => "?").join(", ");
|
||||
const insertStmt = memoryDb.prepare(
|
||||
`INSERT INTO ${tableName} (${columns.join(", ")}) VALUES (${placeholders})`,
|
||||
);
|
||||
|
||||
const insertTransaction = memoryDb.transaction(
|
||||
(dataRows: Record<string, unknown>[]) => {
|
||||
for (const row of dataRows) {
|
||||
insertStmt.run(columns.map((column) => row[column]));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
insertTransaction(rows);
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
private assertNoForeignKeyViolations(memoryDb: Database.Database): void {
|
||||
const fkCheckResult = memoryDb.prepare("PRAGMA foreign_key_check").all();
|
||||
if (fkCheckResult.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
databaseLogger.error(
|
||||
"Foreign key constraints violations detected after migration",
|
||||
null,
|
||||
{
|
||||
operation: "migration_fk_check_failed",
|
||||
violations: fkCheckResult,
|
||||
},
|
||||
);
|
||||
throw new Error(
|
||||
`Foreign key violations detected: ${JSON.stringify(fkCheckResult)}`,
|
||||
);
|
||||
}
|
||||
|
||||
private assertRowCountsMatch(
|
||||
originalDb: Database.Database,
|
||||
memoryDb: Database.Database,
|
||||
): void {
|
||||
const originalTables = this.listTableNames(originalDb);
|
||||
const memoryTables = this.listTableNames(memoryDb);
|
||||
|
||||
if (originalTables.length !== memoryTables.length) {
|
||||
databaseLogger.error(
|
||||
"Table count mismatch during migration verification",
|
||||
null,
|
||||
{
|
||||
operation: "migration_verify_failed",
|
||||
originalCount: originalTables.length,
|
||||
memoryCount: memoryTables.length,
|
||||
},
|
||||
);
|
||||
throw new Error("Migration integrity verification failed");
|
||||
}
|
||||
|
||||
for (const tableName of originalTables) {
|
||||
const originalCount = originalDb
|
||||
.prepare(`SELECT COUNT(*) as count FROM ${tableName}`)
|
||||
.get() as { count: number };
|
||||
const memoryCount = memoryDb
|
||||
.prepare(`SELECT COUNT(*) as count FROM ${tableName}`)
|
||||
.get() as { count: number };
|
||||
|
||||
if (originalCount.count !== memoryCount.count) {
|
||||
databaseLogger.error(
|
||||
"Row count mismatch for table during migration verification",
|
||||
null,
|
||||
{
|
||||
operation: "migration_verify_table_failed",
|
||||
table: tableName,
|
||||
originalRows: originalCount.count,
|
||||
memoryRows: memoryCount.count,
|
||||
},
|
||||
);
|
||||
throw new Error("Migration integrity verification failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { loginRateLimiter } from "./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);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { statsLogger } from "./logger.js";
|
||||
import { safeOutboundFetch } from "./safe-outbound-fetch.js";
|
||||
|
||||
export interface AlertPayload {
|
||||
hostName: string;
|
||||
@@ -36,7 +37,7 @@ async function fetchWithRetry(
|
||||
options: RequestInit,
|
||||
): Promise<void> {
|
||||
const attempt = async () => {
|
||||
const res = await fetch(url, options);
|
||||
const res = await safeOutboundFetch(url, options);
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
const CALLBACK_PATH = "/oidc-callback";
|
||||
|
||||
export function getDesktopOidcCallbackUrl(value: unknown): string | null {
|
||||
if (typeof value !== "string" || !/^\d+$/.test(value)) return null;
|
||||
|
||||
const port = Number(value);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
|
||||
|
||||
return `http://localhost:${port}${CALLBACK_PATH}`;
|
||||
}
|
||||
|
||||
export function isOidcTokenCallback(value: string): boolean {
|
||||
if (value.startsWith("termix-mobile:")) return true;
|
||||
|
||||
try {
|
||||
const url = new URL(value);
|
||||
return (
|
||||
url.protocol === "http:" &&
|
||||
(url.hostname === "localhost" || url.hostname === "127.0.0.1") &&
|
||||
url.pathname === CALLBACK_PATH
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
// Single source of truth for role permission strings. The admin role editor
|
||||
// renders this catalog and PUT /rbac/roles/:id validates against it;
|
||||
// PermissionManager.hasPermission resolves wildcards ("*", "<group>.*").
|
||||
export interface PermissionCatalogEntry {
|
||||
group: string;
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
export const PERMISSION_CATALOG: PermissionCatalogEntry[] = [
|
||||
{
|
||||
group: "hosts",
|
||||
permissions: [
|
||||
"hosts.view",
|
||||
"hosts.create",
|
||||
"hosts.edit",
|
||||
"hosts.delete",
|
||||
"hosts.share",
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "snippets",
|
||||
permissions: [
|
||||
"snippets.view",
|
||||
"snippets.create",
|
||||
"snippets.edit",
|
||||
"snippets.delete",
|
||||
"snippets.share",
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "credentials",
|
||||
permissions: [
|
||||
"credentials.view",
|
||||
"credentials.create",
|
||||
"credentials.edit",
|
||||
"credentials.delete",
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "admin",
|
||||
permissions: [
|
||||
"admin.users.view",
|
||||
"admin.users.manage",
|
||||
"admin.roles.manage",
|
||||
"admin.settings.manage",
|
||||
"admin.sessions.manage",
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const VALID_PERMISSIONS = new Set<string>(
|
||||
PERMISSION_CATALOG.flatMap((entry) => [
|
||||
...entry.permissions,
|
||||
`${entry.group}.*`,
|
||||
]).concat("*"),
|
||||
);
|
||||
|
||||
export function isValidPermission(permission: string): boolean {
|
||||
return VALID_PERMISSIONS.has(permission);
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
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("./logger.js", () => ({
|
||||
databaseLogger: {
|
||||
debug: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
success: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const { PermissionManager } = await import("./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);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,10 @@
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
import { db } from "../database/db/index.js";
|
||||
import {
|
||||
hostAccess,
|
||||
roles,
|
||||
userRoles,
|
||||
hosts,
|
||||
users,
|
||||
} from "../database/db/schema.js";
|
||||
import { eq, and, or, isNull, gte, sql } from "drizzle-orm";
|
||||
createCurrentRbacAccessRepository,
|
||||
createCurrentRoleRepository,
|
||||
createCurrentUserRepository,
|
||||
createCurrentHostResolutionRepository,
|
||||
} from "../database/repositories/factory.js";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
|
||||
interface AuthenticatedRequest extends Request {
|
||||
@@ -15,11 +12,33 @@ interface AuthenticatedRequest extends Request {
|
||||
dataKey?: Buffer;
|
||||
}
|
||||
|
||||
const SHARE_PERMISSION_LEVELS = ["connect", "view", "edit", "manage"] as const;
|
||||
|
||||
type SharePermissionLevel = (typeof SHARE_PERMISSION_LEVELS)[number];
|
||||
|
||||
type HostAction = SharePermissionLevel | "delete";
|
||||
|
||||
const LEVEL_RANK: Record<SharePermissionLevel, number> = {
|
||||
connect: 1,
|
||||
view: 2,
|
||||
edit: 3,
|
||||
manage: 4,
|
||||
};
|
||||
|
||||
function normalizeSharePermissionLevel(
|
||||
level: string | null | undefined,
|
||||
): SharePermissionLevel {
|
||||
return SHARE_PERMISSION_LEVELS.includes(level as SharePermissionLevel)
|
||||
? (level as SharePermissionLevel)
|
||||
: "connect";
|
||||
}
|
||||
|
||||
interface HostAccessInfo {
|
||||
hasAccess: boolean;
|
||||
isOwner: boolean;
|
||||
isShared: boolean;
|
||||
permissionLevel?: "view";
|
||||
isAdminBypass?: boolean;
|
||||
permissionLevel?: SharePermissionLevel;
|
||||
expiresAt?: string | null;
|
||||
}
|
||||
|
||||
@@ -65,15 +84,7 @@ class PermissionManager {
|
||||
|
||||
private async cleanupExpiredAccess(): Promise<void> {
|
||||
try {
|
||||
const now = new Date().toISOString();
|
||||
await db
|
||||
.delete(hostAccess)
|
||||
.where(
|
||||
and(
|
||||
sql`${hostAccess.expiresAt} IS NOT NULL`,
|
||||
sql`${hostAccess.expiresAt} <= ${now}`,
|
||||
),
|
||||
);
|
||||
await createCurrentRbacAccessRepository().deleteExpiredHostAccess();
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to cleanup expired host access", error, {
|
||||
operation: "host_access_cleanup_failed",
|
||||
@@ -96,13 +107,8 @@ class PermissionManager {
|
||||
}
|
||||
|
||||
try {
|
||||
const userRoleRecords = await db
|
||||
.select({
|
||||
permissions: roles.permissions,
|
||||
})
|
||||
.from(userRoles)
|
||||
.innerJoin(roles, eq(userRoles.roleId, roles.id))
|
||||
.where(eq(userRoles.userId, userId));
|
||||
const userRoleRecords =
|
||||
await createCurrentRoleRepository().listUserRolePermissions(userId);
|
||||
|
||||
const allPermissions = new Set<string>();
|
||||
for (const record of userRoleRecords) {
|
||||
@@ -162,16 +168,12 @@ class PermissionManager {
|
||||
async canAccessHost(
|
||||
userId: string,
|
||||
hostId: number,
|
||||
action: "read" | "write" | "execute" | "delete" | "share" = "read",
|
||||
action: HostAction = "connect",
|
||||
): Promise<HostAccessInfo> {
|
||||
try {
|
||||
const host = await db
|
||||
.select()
|
||||
.from(hosts)
|
||||
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
|
||||
.limit(1);
|
||||
const hostResolutionRepository = createCurrentHostResolutionRepository();
|
||||
|
||||
if (host.length > 0) {
|
||||
if (await hostResolutionRepository.isHostOwnedByUser(hostId, userId)) {
|
||||
return {
|
||||
hasAccess: true,
|
||||
isOwner: true,
|
||||
@@ -179,43 +181,20 @@ class PermissionManager {
|
||||
};
|
||||
}
|
||||
|
||||
const userRoleIds = await db
|
||||
.select({ roleId: userRoles.roleId })
|
||||
.from(userRoles)
|
||||
.where(eq(userRoles.userId, userId));
|
||||
const roleIds = userRoleIds.map((r) => r.roleId);
|
||||
const roleIds =
|
||||
await createCurrentRoleRepository().listUserRoleIds(userId);
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const sharedAccess = await db
|
||||
.select()
|
||||
.from(hostAccess)
|
||||
.where(
|
||||
and(
|
||||
eq(hostAccess.hostId, hostId),
|
||||
or(
|
||||
eq(hostAccess.userId, userId),
|
||||
roleIds.length > 0
|
||||
? sql`${hostAccess.roleId} IN (${sql.join(
|
||||
roleIds.map((id) => sql`${id}`),
|
||||
sql`, `,
|
||||
)})`
|
||||
: sql`false`,
|
||||
),
|
||||
or(isNull(hostAccess.expiresAt), gte(hostAccess.expiresAt, now)),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
const access =
|
||||
await createCurrentRbacAccessRepository().findActiveHostAccess(
|
||||
hostId,
|
||||
userId,
|
||||
roleIds,
|
||||
);
|
||||
|
||||
if (sharedAccess.length > 0) {
|
||||
const access = sharedAccess[0];
|
||||
if (access) {
|
||||
const ownerId = await hostResolutionRepository.findHostOwnerId(hostId);
|
||||
|
||||
const hostOwnerCheck = await db
|
||||
.select({ ownerId: hosts.userId })
|
||||
.from(hosts)
|
||||
.where(eq(hosts.id, hostId))
|
||||
.limit(1);
|
||||
|
||||
if (hostOwnerCheck.length > 0 && hostOwnerCheck[0].ownerId === userId) {
|
||||
if (ownerId === userId) {
|
||||
return {
|
||||
hasAccess: true,
|
||||
isOwner: true,
|
||||
@@ -223,39 +202,52 @@ class PermissionManager {
|
||||
};
|
||||
}
|
||||
|
||||
if (action === "write" || action === "delete") {
|
||||
const grantedLevel = normalizeSharePermissionLevel(
|
||||
access.permissionLevel,
|
||||
);
|
||||
|
||||
if (
|
||||
action === "delete" ||
|
||||
LEVEL_RANK[grantedLevel] < LEVEL_RANK[action]
|
||||
) {
|
||||
if (await this.isAdmin(userId)) {
|
||||
return this.adminBypassAccess();
|
||||
}
|
||||
return {
|
||||
hasAccess: false,
|
||||
isOwner: false,
|
||||
isShared: true,
|
||||
permissionLevel: access.permissionLevel as "view",
|
||||
permissionLevel: grantedLevel,
|
||||
expiresAt: access.expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
await db
|
||||
.update(hostAccess)
|
||||
.set({
|
||||
lastAccessedAt: now,
|
||||
})
|
||||
.where(eq(hostAccess.id, access.id));
|
||||
} catch (error) {
|
||||
databaseLogger.warn("Failed to update host access timestamp", {
|
||||
operation: "update_host_access_timestamp",
|
||||
error,
|
||||
});
|
||||
if (action === "connect") {
|
||||
try {
|
||||
await createCurrentRbacAccessRepository().touchHostAccess(
|
||||
access.id,
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.warn("Failed to update host access timestamp", {
|
||||
operation: "update_host_access_timestamp",
|
||||
error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
hasAccess: true,
|
||||
isOwner: false,
|
||||
isShared: true,
|
||||
permissionLevel: access.permissionLevel as "view",
|
||||
permissionLevel: grantedLevel,
|
||||
expiresAt: access.expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
if (await this.isAdmin(userId)) {
|
||||
return this.adminBypassAccess();
|
||||
}
|
||||
|
||||
return {
|
||||
hasAccess: false,
|
||||
isOwner: false,
|
||||
@@ -276,30 +268,30 @@ class PermissionManager {
|
||||
}
|
||||
}
|
||||
|
||||
// Admins get owner-equivalent access to every host; each connect is
|
||||
// audit-logged in the host resolver.
|
||||
private adminBypassAccess(): HostAccessInfo {
|
||||
return {
|
||||
hasAccess: true,
|
||||
isOwner: false,
|
||||
isShared: false,
|
||||
isAdminBypass: true,
|
||||
permissionLevel: "manage",
|
||||
};
|
||||
}
|
||||
|
||||
async isAdmin(userId: string): Promise<boolean> {
|
||||
try {
|
||||
const user = await db
|
||||
.select({ isAdmin: users.isAdmin })
|
||||
.from(users)
|
||||
.where(eq(users.id, userId))
|
||||
.limit(1);
|
||||
const user = await createCurrentUserRepository().findById(userId);
|
||||
|
||||
if (user.length > 0 && user[0].isAdmin) {
|
||||
if (user?.isAdmin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const adminRoles = await db
|
||||
.select({ roleName: roles.name })
|
||||
.from(userRoles)
|
||||
.innerJoin(roles, eq(userRoles.roleId, roles.id))
|
||||
.where(
|
||||
and(
|
||||
eq(userRoles.userId, userId),
|
||||
or(eq(roles.name, "admin"), eq(roles.name, "super_admin")),
|
||||
),
|
||||
);
|
||||
|
||||
return adminRoles.length > 0;
|
||||
return createCurrentRoleRepository().userHasAnyRoleName(userId, [
|
||||
"admin",
|
||||
"super_admin",
|
||||
]);
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to check admin status", error, {
|
||||
operation: "is_admin",
|
||||
@@ -343,7 +335,7 @@ class PermissionManager {
|
||||
|
||||
requireHostAccess(
|
||||
hostIdParam: string = "id",
|
||||
action: "read" | "write" | "execute" | "delete" | "share" = "read",
|
||||
action: HostAction = "connect",
|
||||
) {
|
||||
return async (
|
||||
req: AuthenticatedRequest,
|
||||
@@ -418,5 +410,11 @@ class PermissionManager {
|
||||
}
|
||||
}
|
||||
|
||||
export { PermissionManager };
|
||||
export type { AuthenticatedRequest, HostAccessInfo, PermissionCheckResult };
|
||||
export { PermissionManager, SHARE_PERMISSION_LEVELS, LEVEL_RANK };
|
||||
export type {
|
||||
AuthenticatedRequest,
|
||||
HostAccessInfo,
|
||||
PermissionCheckResult,
|
||||
SharePermissionLevel,
|
||||
HostAction,
|
||||
};
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
getRequestBasePath,
|
||||
getRequestBaseUrl,
|
||||
getRequestBaseUrlWithForceHTTPS,
|
||||
normalizeBasePath,
|
||||
} from "./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");
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,44 @@ function firstHeaderValue(value: string | string[] | undefined): string {
|
||||
return raw.split(",")[0].trim();
|
||||
}
|
||||
|
||||
function normalizePort(value: string | string[] | undefined): string {
|
||||
const raw = firstHeaderValue(value);
|
||||
if (!/^\d+$/.test(raw)) return "";
|
||||
|
||||
const port = Number(raw);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) return "";
|
||||
|
||||
return String(port);
|
||||
}
|
||||
|
||||
function splitHostHeader(value: string | string[] | undefined): {
|
||||
host: string;
|
||||
port: string;
|
||||
} {
|
||||
const raw = firstHeaderValue(value) || "localhost";
|
||||
|
||||
if (raw.startsWith("[")) {
|
||||
const match = raw.match(/^(\[[^\]]+\])(?::(.+))?$/);
|
||||
return {
|
||||
host: match?.[1] || raw,
|
||||
port: normalizePort(match?.[2]),
|
||||
};
|
||||
}
|
||||
|
||||
const parts = raw.split(":");
|
||||
if (parts.length === 2) {
|
||||
return {
|
||||
host: parts[0] || "localhost",
|
||||
port: normalizePort(parts[1]),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
host: raw,
|
||||
port: "",
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeBasePath(value: unknown): string {
|
||||
if (typeof value !== "string") return "";
|
||||
let basePath = value.split(",")[0].trim();
|
||||
@@ -45,38 +83,23 @@ export function getRequestOrigin(req: Request | IncomingMessage): string {
|
||||
: "http";
|
||||
}
|
||||
|
||||
const portHeader = req.headers["x-forwarded-port"];
|
||||
let port: string | undefined =
|
||||
typeof portHeader === "string"
|
||||
? portHeader.split(",")[0].trim()
|
||||
: undefined;
|
||||
let port = normalizePort(req.headers["x-forwarded-port"]);
|
||||
const { host, port: hostPort } = splitHostHeader(
|
||||
req.headers["x-forwarded-host"] || req.headers.host,
|
||||
);
|
||||
port ||= hostPort;
|
||||
|
||||
const hostHeaderRaw =
|
||||
req.headers["x-forwarded-host"] || req.headers.host || "localhost";
|
||||
const hostHeader =
|
||||
typeof hostHeaderRaw === "string"
|
||||
? hostHeaderRaw.split(",")[0].trim()
|
||||
: String(hostHeaderRaw);
|
||||
|
||||
if (!port && hostHeader.includes(":")) {
|
||||
const parts = hostHeader.split(":");
|
||||
if (parts.length === 2 && !parts[0].includes("[")) {
|
||||
port = parts[1];
|
||||
}
|
||||
}
|
||||
|
||||
const hostWithoutPort = hostHeader.split(":")[0];
|
||||
if (port) {
|
||||
const isDefaultPort =
|
||||
(protocol === "http" && port === "80") ||
|
||||
(protocol === "https" && port === "443");
|
||||
|
||||
return isDefaultPort
|
||||
? `${protocol}://${hostWithoutPort}`
|
||||
: `${protocol}://${hostWithoutPort}:${port}`;
|
||||
? `${protocol}://${host}`
|
||||
: `${protocol}://${host}:${port}`;
|
||||
}
|
||||
|
||||
return `${protocol}://${hostWithoutPort}`;
|
||||
return `${protocol}://${host}`;
|
||||
}
|
||||
|
||||
export function getRequestOriginWithForceHTTPS(
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { lookup } from "dns";
|
||||
import { BlockList, isIP } from "net";
|
||||
import { Agent } from "undici";
|
||||
|
||||
const blockedAddresses = new BlockList();
|
||||
|
||||
for (const [network, prefix] of [
|
||||
["0.0.0.0", 8],
|
||||
["10.0.0.0", 8],
|
||||
["100.64.0.0", 10],
|
||||
["127.0.0.0", 8],
|
||||
["169.254.0.0", 16],
|
||||
["172.16.0.0", 12],
|
||||
["192.168.0.0", 16],
|
||||
["198.18.0.0", 15],
|
||||
["224.0.0.0", 4],
|
||||
["240.0.0.0", 4],
|
||||
] as const) {
|
||||
blockedAddresses.addSubnet(network, prefix, "ipv4");
|
||||
}
|
||||
|
||||
for (const [network, prefix] of [
|
||||
["::", 128],
|
||||
["::1", 128],
|
||||
["::ffff:0:0", 96],
|
||||
["fc00::", 7],
|
||||
["fe80::", 10],
|
||||
["ff00::", 8],
|
||||
] as const) {
|
||||
blockedAddresses.addSubnet(network, prefix, "ipv6");
|
||||
}
|
||||
|
||||
function isBlockedAddress(address: string): boolean {
|
||||
const family = isIP(address);
|
||||
return (
|
||||
family === 0 ||
|
||||
blockedAddresses.check(address, family === 4 ? "ipv4" : "ipv6")
|
||||
);
|
||||
}
|
||||
|
||||
export async function safeOutboundFetch(
|
||||
rawUrl: string,
|
||||
options: RequestInit,
|
||||
): Promise<Response> {
|
||||
const url = new URL(rawUrl);
|
||||
if (
|
||||
!["http:", "https:"].includes(url.protocol) ||
|
||||
url.username ||
|
||||
url.password
|
||||
) {
|
||||
throw new Error("Invalid outbound URL");
|
||||
}
|
||||
|
||||
const hostname = url.hostname.replace(/^\[|\]$/g, "");
|
||||
if (isIP(hostname) && isBlockedAddress(hostname)) {
|
||||
throw new Error("Private destinations are not allowed");
|
||||
}
|
||||
|
||||
const dispatcher = new Agent({
|
||||
connect: {
|
||||
lookup(host, lookupOptions, callback) {
|
||||
lookup(
|
||||
host,
|
||||
{ ...lookupOptions, all: true, verbatim: true },
|
||||
(error, addresses) => {
|
||||
if (error) return callback(error, "", 0);
|
||||
if (
|
||||
!addresses.length ||
|
||||
addresses.some(({ address }) => isBlockedAddress(address))
|
||||
) {
|
||||
return callback(
|
||||
new Error("Private destinations are not allowed"),
|
||||
"",
|
||||
0,
|
||||
);
|
||||
}
|
||||
const selected = addresses[0];
|
||||
callback(null, selected.address, selected.family);
|
||||
},
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
return await fetch(url, {
|
||||
...options,
|
||||
redirect: "error",
|
||||
dispatcher,
|
||||
} as RequestInit & { dispatcher: Agent });
|
||||
} finally {
|
||||
await dispatcher.close();
|
||||
}
|
||||
}
|
||||
@@ -1,768 +0,0 @@
|
||||
import { db } from "../database/db/index.js";
|
||||
import {
|
||||
sharedCredentials,
|
||||
sshCredentials,
|
||||
hostAccess,
|
||||
userRoles,
|
||||
hosts,
|
||||
} from "../database/db/schema.js";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
import { DataCrypto } from "./data-crypto.js";
|
||||
import { FieldCrypto } from "./field-crypto.js";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
|
||||
interface CredentialData {
|
||||
username: string;
|
||||
authType: string;
|
||||
password?: string;
|
||||
key?: string;
|
||||
keyPassword?: string;
|
||||
keyType?: string;
|
||||
}
|
||||
|
||||
class SharedCredentialManager {
|
||||
private static instance: SharedCredentialManager;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
static getInstance(): SharedCredentialManager {
|
||||
if (!this.instance) {
|
||||
this.instance = new SharedCredentialManager();
|
||||
}
|
||||
return this.instance;
|
||||
}
|
||||
|
||||
async createSharedCredentialForUser(
|
||||
hostAccessId: number,
|
||||
originalCredentialId: number,
|
||||
targetUserId: string,
|
||||
ownerId: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const existing = await db
|
||||
.select({ id: sharedCredentials.id })
|
||||
.from(sharedCredentials)
|
||||
.where(
|
||||
and(
|
||||
eq(sharedCredentials.hostAccessId, hostAccessId),
|
||||
eq(sharedCredentials.targetUserId, targetUserId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (existing.length > 0) return;
|
||||
|
||||
const ownerDEK = DataCrypto.getUserDataKey(ownerId);
|
||||
|
||||
if (ownerDEK) {
|
||||
const targetDEK = DataCrypto.getUserDataKey(targetUserId);
|
||||
if (!targetDEK) {
|
||||
await this.createPendingSharedCredential(
|
||||
hostAccessId,
|
||||
originalCredentialId,
|
||||
targetUserId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const credentialData = await this.getDecryptedCredential(
|
||||
originalCredentialId,
|
||||
ownerId,
|
||||
ownerDEK,
|
||||
);
|
||||
|
||||
const encryptedForTarget = this.encryptCredentialForUser(
|
||||
credentialData,
|
||||
targetUserId,
|
||||
targetDEK,
|
||||
hostAccessId,
|
||||
);
|
||||
|
||||
await db.insert(sharedCredentials).values({
|
||||
hostAccessId,
|
||||
originalCredentialId,
|
||||
targetUserId,
|
||||
...encryptedForTarget,
|
||||
needsReEncryption: false,
|
||||
});
|
||||
} else {
|
||||
const targetDEK = DataCrypto.getUserDataKey(targetUserId);
|
||||
if (!targetDEK) {
|
||||
await this.createPendingSharedCredential(
|
||||
hostAccessId,
|
||||
originalCredentialId,
|
||||
targetUserId,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const credentialData =
|
||||
await this.getDecryptedCredentialViaSystemKey(originalCredentialId);
|
||||
|
||||
const encryptedForTarget = this.encryptCredentialForUser(
|
||||
credentialData,
|
||||
targetUserId,
|
||||
targetDEK,
|
||||
hostAccessId,
|
||||
);
|
||||
|
||||
await db.insert(sharedCredentials).values({
|
||||
hostAccessId,
|
||||
originalCredentialId,
|
||||
targetUserId,
|
||||
...encryptedForTarget,
|
||||
needsReEncryption: false,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to create shared credential", error, {
|
||||
operation: "create_shared_credential",
|
||||
hostAccessId,
|
||||
targetUserId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async createSharedCredentialsForRole(
|
||||
hostAccessId: number,
|
||||
originalCredentialId: number,
|
||||
roleId: number,
|
||||
ownerId: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const roleUsers = await db
|
||||
.select({ userId: userRoles.userId })
|
||||
.from(userRoles)
|
||||
.where(eq(userRoles.roleId, roleId));
|
||||
|
||||
for (const { userId } of roleUsers) {
|
||||
try {
|
||||
await this.createSharedCredentialForUser(
|
||||
hostAccessId,
|
||||
originalCredentialId,
|
||||
userId,
|
||||
ownerId,
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to create shared credential for role member",
|
||||
error,
|
||||
{
|
||||
operation: "create_shared_credentials_role",
|
||||
hostAccessId,
|
||||
roleId,
|
||||
userId,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to create shared credentials for role",
|
||||
error,
|
||||
{
|
||||
operation: "create_shared_credentials_role",
|
||||
hostAccessId,
|
||||
roleId,
|
||||
},
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async createSharedCredentialsForRoleMember(
|
||||
roleId: number,
|
||||
targetUserId: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const hostsSharedWithRole = await db
|
||||
.select()
|
||||
.from(hostAccess)
|
||||
.innerJoin(hosts, eq(hostAccess.hostId, hosts.id))
|
||||
.where(eq(hostAccess.roleId, roleId));
|
||||
|
||||
for (const { host_access, ssh_data } of hostsSharedWithRole) {
|
||||
const activeCredentialId =
|
||||
ssh_data.credentialId ??
|
||||
ssh_data.rdpCredentialId ??
|
||||
ssh_data.vncCredentialId ??
|
||||
ssh_data.telnetCredentialId;
|
||||
|
||||
if (!activeCredentialId) continue;
|
||||
|
||||
try {
|
||||
await this.createSharedCredentialForUser(
|
||||
host_access.id,
|
||||
activeCredentialId,
|
||||
targetUserId,
|
||||
ssh_data.userId,
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to create shared credential for role member",
|
||||
error,
|
||||
{
|
||||
operation: "create_shared_credentials_role_member",
|
||||
roleId,
|
||||
targetUserId,
|
||||
hostId: ssh_data.id,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to create shared credentials for role member",
|
||||
error,
|
||||
{
|
||||
operation: "create_shared_credentials_role_member",
|
||||
roleId,
|
||||
targetUserId,
|
||||
},
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async createSharedCredentialsForUserRoles(userId: string): Promise<void> {
|
||||
try {
|
||||
const roleRows = await db
|
||||
.select({ roleId: userRoles.roleId })
|
||||
.from(userRoles)
|
||||
.where(eq(userRoles.userId, userId));
|
||||
|
||||
for (const { roleId } of roleRows) {
|
||||
await this.createSharedCredentialsForRoleMember(roleId, userId);
|
||||
}
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to create shared credentials for user roles",
|
||||
error,
|
||||
{
|
||||
operation: "create_shared_credentials_user_roles",
|
||||
userId,
|
||||
},
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getSharedCredentialForUser(
|
||||
hostId: number,
|
||||
userId: string,
|
||||
): Promise<CredentialData | null> {
|
||||
try {
|
||||
const userDEK = DataCrypto.getUserDataKey(userId);
|
||||
if (!userDEK) {
|
||||
throw new Error(`User ${userId} data not unlocked`);
|
||||
}
|
||||
|
||||
const sharedCred = await db
|
||||
.select()
|
||||
.from(sharedCredentials)
|
||||
.innerJoin(
|
||||
hostAccess,
|
||||
eq(sharedCredentials.hostAccessId, hostAccess.id),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(hostAccess.hostId, hostId),
|
||||
eq(sharedCredentials.targetUserId, userId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (sharedCred.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cred = sharedCred[0].shared_credentials;
|
||||
|
||||
if (cred.needsReEncryption) {
|
||||
await this.reEncryptSharedCredential(cred.id, userId);
|
||||
|
||||
const refreshed = await db
|
||||
.select()
|
||||
.from(sharedCredentials)
|
||||
.where(eq(sharedCredentials.id, cred.id))
|
||||
.limit(1);
|
||||
|
||||
if (refreshed.length === 0 || refreshed[0].needsReEncryption) {
|
||||
databaseLogger.warn(
|
||||
"Shared credential needs re-encryption but cannot be accessed yet",
|
||||
{
|
||||
operation: "get_shared_credential_pending",
|
||||
hostId,
|
||||
userId,
|
||||
},
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.decryptSharedCredential(refreshed[0], userDEK);
|
||||
}
|
||||
|
||||
return this.decryptSharedCredential(cred, userDEK);
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to get shared credential", error, {
|
||||
operation: "get_shared_credential",
|
||||
hostId,
|
||||
userId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async updateSharedCredentialsForOriginal(
|
||||
credentialId: number,
|
||||
ownerId: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const sharedCreds = await db
|
||||
.select()
|
||||
.from(sharedCredentials)
|
||||
.where(eq(sharedCredentials.originalCredentialId, credentialId));
|
||||
|
||||
const ownerDEK = DataCrypto.getUserDataKey(ownerId);
|
||||
let credentialData: CredentialData;
|
||||
|
||||
if (ownerDEK) {
|
||||
credentialData = await this.getDecryptedCredential(
|
||||
credentialId,
|
||||
ownerId,
|
||||
ownerDEK,
|
||||
);
|
||||
} else {
|
||||
try {
|
||||
credentialData =
|
||||
await this.getDecryptedCredentialViaSystemKey(credentialId);
|
||||
} catch (error) {
|
||||
databaseLogger.warn(
|
||||
"Cannot update shared credentials: owner offline and credential not migrated",
|
||||
{
|
||||
operation: "update_shared_credentials_failed",
|
||||
credentialId,
|
||||
ownerId,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
},
|
||||
);
|
||||
await db
|
||||
.update(sharedCredentials)
|
||||
.set({ needsReEncryption: true })
|
||||
.where(eq(sharedCredentials.originalCredentialId, credentialId));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
for (const sharedCred of sharedCreds) {
|
||||
const targetDEK = DataCrypto.getUserDataKey(sharedCred.targetUserId);
|
||||
|
||||
if (!targetDEK) {
|
||||
await db
|
||||
.update(sharedCredentials)
|
||||
.set({ needsReEncryption: true })
|
||||
.where(eq(sharedCredentials.id, sharedCred.id));
|
||||
continue;
|
||||
}
|
||||
|
||||
const encryptedForTarget = this.encryptCredentialForUser(
|
||||
credentialData,
|
||||
sharedCred.targetUserId,
|
||||
targetDEK,
|
||||
sharedCred.hostAccessId,
|
||||
);
|
||||
|
||||
await db
|
||||
.update(sharedCredentials)
|
||||
.set({
|
||||
...encryptedForTarget,
|
||||
needsReEncryption: false,
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
.where(eq(sharedCredentials.id, sharedCred.id));
|
||||
}
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to update shared credentials", error, {
|
||||
operation: "update_shared_credentials",
|
||||
credentialId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async deleteSharedCredentialsForOriginal(
|
||||
credentialId: number,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await db
|
||||
.delete(sharedCredentials)
|
||||
.where(eq(sharedCredentials.originalCredentialId, credentialId));
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to delete shared credentials", error, {
|
||||
operation: "delete_shared_credentials",
|
||||
credentialId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async reEncryptPendingCredentialsForUser(userId: string): Promise<void> {
|
||||
try {
|
||||
const userDEK = DataCrypto.getUserDataKey(userId);
|
||||
if (!userDEK) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pendingCreds = await db
|
||||
.select()
|
||||
.from(sharedCredentials)
|
||||
.where(
|
||||
and(
|
||||
eq(sharedCredentials.targetUserId, userId),
|
||||
eq(sharedCredentials.needsReEncryption, true),
|
||||
),
|
||||
);
|
||||
|
||||
for (const cred of pendingCreds) {
|
||||
await this.reEncryptSharedCredential(cred.id, userId);
|
||||
}
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to re-encrypt pending credentials", error, {
|
||||
operation: "reencrypt_pending_credentials",
|
||||
userId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async getDecryptedCredential(
|
||||
credentialId: number,
|
||||
ownerId: string,
|
||||
ownerDEK: Buffer,
|
||||
): Promise<CredentialData> {
|
||||
const creds = await db
|
||||
.select()
|
||||
.from(sshCredentials)
|
||||
.where(
|
||||
and(
|
||||
eq(sshCredentials.id, credentialId),
|
||||
eq(sshCredentials.userId, ownerId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (creds.length === 0) {
|
||||
throw new Error(`Credential ${credentialId} not found`);
|
||||
}
|
||||
|
||||
const cred = creds[0];
|
||||
|
||||
return {
|
||||
username: cred.username,
|
||||
authType: cred.authType,
|
||||
password: cred.password
|
||||
? this.decryptField(cred.password, ownerDEK, credentialId, "password")
|
||||
: undefined,
|
||||
key: cred.key
|
||||
? this.decryptField(cred.key, ownerDEK, credentialId, "key")
|
||||
: undefined,
|
||||
keyPassword: cred.keyPassword
|
||||
? this.decryptField(
|
||||
cred.keyPassword,
|
||||
ownerDEK,
|
||||
credentialId,
|
||||
"keyPassword",
|
||||
)
|
||||
: undefined,
|
||||
keyType: cred.keyType,
|
||||
};
|
||||
}
|
||||
|
||||
private async getDecryptedCredentialViaSystemKey(
|
||||
credentialId: number,
|
||||
): Promise<CredentialData> {
|
||||
const creds = await db
|
||||
.select()
|
||||
.from(sshCredentials)
|
||||
.where(eq(sshCredentials.id, credentialId))
|
||||
.limit(1);
|
||||
|
||||
if (creds.length === 0) {
|
||||
throw new Error(`Credential ${credentialId} not found`);
|
||||
}
|
||||
|
||||
const cred = creds[0];
|
||||
|
||||
if (!cred.systemPassword && !cred.systemKey && !cred.systemKeyPassword) {
|
||||
throw new Error(
|
||||
"Credential not yet migrated for offline sharing. " +
|
||||
"Please ask credential owner to log in to enable sharing.",
|
||||
);
|
||||
}
|
||||
|
||||
const { SystemCrypto } = await import("./system-crypto.js");
|
||||
const systemCrypto = SystemCrypto.getInstance();
|
||||
const CSKEK = await systemCrypto.getCredentialSharingKey();
|
||||
|
||||
return {
|
||||
username: cred.username,
|
||||
authType: cred.authType,
|
||||
password: cred.systemPassword
|
||||
? this.decryptField(
|
||||
cred.systemPassword,
|
||||
CSKEK,
|
||||
credentialId,
|
||||
"password",
|
||||
)
|
||||
: undefined,
|
||||
key: cred.systemKey
|
||||
? this.decryptField(cred.systemKey, CSKEK, credentialId, "key")
|
||||
: undefined,
|
||||
keyPassword: cred.systemKeyPassword
|
||||
? this.decryptField(
|
||||
cred.systemKeyPassword,
|
||||
CSKEK,
|
||||
credentialId,
|
||||
"key_password",
|
||||
)
|
||||
: undefined,
|
||||
keyType: cred.keyType,
|
||||
};
|
||||
}
|
||||
|
||||
private encryptCredentialForUser(
|
||||
credentialData: CredentialData,
|
||||
targetUserId: string,
|
||||
targetDEK: Buffer,
|
||||
hostAccessId: number,
|
||||
): {
|
||||
encryptedUsername: string;
|
||||
encryptedAuthType: string;
|
||||
encryptedPassword: string | null;
|
||||
encryptedKey: string | null;
|
||||
encryptedKeyPassword: string | null;
|
||||
encryptedKeyType: string | null;
|
||||
} {
|
||||
const recordId = `shared-${hostAccessId}-${targetUserId}`;
|
||||
|
||||
return {
|
||||
encryptedUsername: FieldCrypto.encryptField(
|
||||
credentialData.username,
|
||||
targetDEK,
|
||||
recordId,
|
||||
"username",
|
||||
),
|
||||
encryptedAuthType: credentialData.authType,
|
||||
encryptedPassword: credentialData.password
|
||||
? FieldCrypto.encryptField(
|
||||
credentialData.password,
|
||||
targetDEK,
|
||||
recordId,
|
||||
"password",
|
||||
)
|
||||
: null,
|
||||
encryptedKey: credentialData.key
|
||||
? FieldCrypto.encryptField(
|
||||
credentialData.key,
|
||||
targetDEK,
|
||||
recordId,
|
||||
"key",
|
||||
)
|
||||
: null,
|
||||
encryptedKeyPassword: credentialData.keyPassword
|
||||
? FieldCrypto.encryptField(
|
||||
credentialData.keyPassword,
|
||||
targetDEK,
|
||||
recordId,
|
||||
"key_password",
|
||||
)
|
||||
: null,
|
||||
encryptedKeyType: credentialData.keyType || null,
|
||||
};
|
||||
}
|
||||
|
||||
private decryptSharedCredential(
|
||||
sharedCred: typeof sharedCredentials.$inferSelect,
|
||||
userDEK: Buffer,
|
||||
): CredentialData {
|
||||
const recordId = `shared-${sharedCred.hostAccessId}-${sharedCred.targetUserId}`;
|
||||
|
||||
return {
|
||||
username: FieldCrypto.decryptField(
|
||||
sharedCred.encryptedUsername,
|
||||
userDEK,
|
||||
recordId,
|
||||
"username",
|
||||
),
|
||||
authType: sharedCred.encryptedAuthType,
|
||||
password: sharedCred.encryptedPassword
|
||||
? FieldCrypto.decryptField(
|
||||
sharedCred.encryptedPassword,
|
||||
userDEK,
|
||||
recordId,
|
||||
"password",
|
||||
)
|
||||
: undefined,
|
||||
key: sharedCred.encryptedKey
|
||||
? FieldCrypto.decryptField(
|
||||
sharedCred.encryptedKey,
|
||||
userDEK,
|
||||
recordId,
|
||||
"key",
|
||||
)
|
||||
: undefined,
|
||||
keyPassword: sharedCred.encryptedKeyPassword
|
||||
? FieldCrypto.decryptField(
|
||||
sharedCred.encryptedKeyPassword,
|
||||
userDEK,
|
||||
recordId,
|
||||
"key_password",
|
||||
)
|
||||
: undefined,
|
||||
keyType: sharedCred.encryptedKeyType || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
private decryptField(
|
||||
encryptedValue: string,
|
||||
dek: Buffer,
|
||||
recordId: number | string,
|
||||
fieldName: string,
|
||||
): string {
|
||||
try {
|
||||
return FieldCrypto.decryptField(
|
||||
encryptedValue,
|
||||
dek,
|
||||
recordId.toString(),
|
||||
fieldName,
|
||||
);
|
||||
} catch {
|
||||
databaseLogger.warn("Field decryption failed, returning as-is", {
|
||||
operation: "decrypt_field",
|
||||
fieldName,
|
||||
recordId,
|
||||
});
|
||||
return encryptedValue;
|
||||
}
|
||||
}
|
||||
|
||||
private async createPendingSharedCredential(
|
||||
hostAccessId: number,
|
||||
originalCredentialId: number,
|
||||
targetUserId: string,
|
||||
): Promise<void> {
|
||||
await db.insert(sharedCredentials).values({
|
||||
hostAccessId,
|
||||
originalCredentialId,
|
||||
targetUserId,
|
||||
encryptedUsername: "",
|
||||
encryptedAuthType: "",
|
||||
needsReEncryption: true,
|
||||
});
|
||||
|
||||
databaseLogger.info("Created pending shared credential", {
|
||||
operation: "create_pending_shared_credential",
|
||||
hostAccessId,
|
||||
targetUserId,
|
||||
});
|
||||
}
|
||||
|
||||
private async reEncryptSharedCredential(
|
||||
sharedCredId: number,
|
||||
userId: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const sharedCred = await db
|
||||
.select()
|
||||
.from(sharedCredentials)
|
||||
.where(eq(sharedCredentials.id, sharedCredId))
|
||||
.limit(1);
|
||||
|
||||
if (sharedCred.length === 0) {
|
||||
databaseLogger.warn("Re-encrypt: shared credential not found", {
|
||||
operation: "reencrypt_not_found",
|
||||
sharedCredId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const cred = sharedCred[0];
|
||||
|
||||
const access = await db
|
||||
.select()
|
||||
.from(hostAccess)
|
||||
.innerJoin(hosts, eq(hostAccess.hostId, hosts.id))
|
||||
.where(eq(hostAccess.id, cred.hostAccessId))
|
||||
.limit(1);
|
||||
|
||||
if (access.length === 0) {
|
||||
databaseLogger.warn("Re-encrypt: host access not found", {
|
||||
operation: "reencrypt_access_not_found",
|
||||
sharedCredId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const ownerId = access[0].ssh_data.userId;
|
||||
|
||||
const userDEK = DataCrypto.getUserDataKey(userId);
|
||||
if (!userDEK) {
|
||||
databaseLogger.warn("Re-encrypt: user DEK not available", {
|
||||
operation: "reencrypt_user_offline",
|
||||
sharedCredId,
|
||||
userId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const ownerDEK = DataCrypto.getUserDataKey(ownerId);
|
||||
let credentialData: CredentialData;
|
||||
|
||||
if (ownerDEK) {
|
||||
credentialData = await this.getDecryptedCredential(
|
||||
cred.originalCredentialId,
|
||||
ownerId,
|
||||
ownerDEK,
|
||||
);
|
||||
} else {
|
||||
try {
|
||||
credentialData = await this.getDecryptedCredentialViaSystemKey(
|
||||
cred.originalCredentialId,
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.warn(
|
||||
"Re-encrypt: system key decryption failed, credential may not be migrated yet",
|
||||
{
|
||||
operation: "reencrypt_system_key_failed",
|
||||
sharedCredId,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const encryptedForTarget = this.encryptCredentialForUser(
|
||||
credentialData,
|
||||
userId,
|
||||
userDEK,
|
||||
cred.hostAccessId,
|
||||
);
|
||||
|
||||
await db
|
||||
.update(sharedCredentials)
|
||||
.set({
|
||||
...encryptedForTarget,
|
||||
needsReEncryption: false,
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
.where(eq(sharedCredentials.id, sharedCredId));
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to re-encrypt shared credential", error, {
|
||||
operation: "reencrypt_shared_credential",
|
||||
sharedCredId,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { SharedCredentialManager };
|
||||
@@ -0,0 +1,544 @@
|
||||
import {
|
||||
createCurrentHostResolutionRepository,
|
||||
createCurrentRbacAccessRepository,
|
||||
createCurrentRoleRepository,
|
||||
createCurrentSharedHostSecretsRepository,
|
||||
} from "../database/repositories/factory.js";
|
||||
import type {
|
||||
SharedHostSecretRecord,
|
||||
ShareProtocol,
|
||||
} from "../database/repositories/shared-host-secrets-repository.js";
|
||||
import type { HostResolutionHostRecord } from "../database/repositories/host-resolution-repository.js";
|
||||
import { DataCrypto } from "./data-crypto.js";
|
||||
import { FieldCrypto } from "./field-crypto.js";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
|
||||
export interface SharedSecretData {
|
||||
username?: string;
|
||||
authType: string;
|
||||
password?: string;
|
||||
key?: string;
|
||||
keyPassword?: string;
|
||||
keyType?: string;
|
||||
domain?: string;
|
||||
}
|
||||
|
||||
interface ProtocolSnapshot {
|
||||
protocol: ShareProtocol;
|
||||
sourceType: "credential" | "inline";
|
||||
originalCredentialId: number | null;
|
||||
data: SharedSecretData;
|
||||
}
|
||||
|
||||
function snapshotRecordId(
|
||||
hostAccessId: number,
|
||||
targetUserId: string,
|
||||
protocol: ShareProtocol,
|
||||
): string {
|
||||
return `shared-${hostAccessId}-${targetUserId}-${protocol}`;
|
||||
}
|
||||
|
||||
// Mirrors the connection-type migration fallback in transformHostResponse():
|
||||
// old hosts only set connectionType, the per-protocol enable flags came later.
|
||||
function enabledProtocols(
|
||||
host: HostResolutionHostRecord,
|
||||
): Record<ShareProtocol, boolean> {
|
||||
const ct = host.connectionType;
|
||||
const rdp = !!host.enableRdp;
|
||||
const vnc = !!host.enableVnc;
|
||||
const telnet = !!host.enableTelnet;
|
||||
const isMigratedNonSsh = !rdp && !vnc && !telnet && !!ct && ct !== "ssh";
|
||||
|
||||
return {
|
||||
ssh: isMigratedNonSsh ? false : host.enableSsh !== false,
|
||||
rdp: isMigratedNonSsh ? ct === "rdp" : rdp,
|
||||
vnc: isMigratedNonSsh ? ct === "vnc" : vnc,
|
||||
telnet: isMigratedNonSsh ? ct === "telnet" : telnet,
|
||||
};
|
||||
}
|
||||
|
||||
// Per-recipient copies of a shared host's connection secrets, re-encrypted
|
||||
// under the recipient's DEK. Every enabled protocol gets its own snapshot;
|
||||
// secret-less auth types (opkssh, vault, agent, none, ...) produce none.
|
||||
class SharedHostSecretsManager {
|
||||
private static instance: SharedHostSecretsManager;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
static getInstance(): SharedHostSecretsManager {
|
||||
if (!this.instance) {
|
||||
this.instance = new SharedHostSecretsManager();
|
||||
}
|
||||
return this.instance;
|
||||
}
|
||||
|
||||
async snapshotForUser(
|
||||
hostAccessId: number,
|
||||
hostId: number,
|
||||
targetUserId: string,
|
||||
ownerId: string,
|
||||
): Promise<void> {
|
||||
if (targetUserId === ownerId) return;
|
||||
|
||||
try {
|
||||
const targetDEK = DataCrypto.validateUserAccess(targetUserId);
|
||||
DataCrypto.validateUserAccess(ownerId);
|
||||
|
||||
const host = await createCurrentHostResolutionRepository().findHostById(
|
||||
hostId,
|
||||
ownerId,
|
||||
);
|
||||
if (!host) {
|
||||
throw new Error(`Host ${hostId} not found`);
|
||||
}
|
||||
|
||||
const snapshots = await this.collectProtocolSnapshots(host, ownerId);
|
||||
const repository = createCurrentSharedHostSecretsRepository();
|
||||
|
||||
for (const snapshot of snapshots) {
|
||||
const recordId = snapshotRecordId(
|
||||
hostAccessId,
|
||||
targetUserId,
|
||||
snapshot.protocol,
|
||||
);
|
||||
const encrypt = (value: string | undefined, fieldName: string) =>
|
||||
value
|
||||
? FieldCrypto.encryptField(value, targetDEK, recordId, fieldName)
|
||||
: null;
|
||||
|
||||
await repository.upsert({
|
||||
hostAccessId,
|
||||
targetUserId,
|
||||
protocol: snapshot.protocol,
|
||||
sourceType: snapshot.sourceType,
|
||||
originalCredentialId: snapshot.originalCredentialId,
|
||||
encryptedUsername: encrypt(snapshot.data.username, "username"),
|
||||
encryptedAuthType: snapshot.data.authType,
|
||||
encryptedPassword: encrypt(snapshot.data.password, "password"),
|
||||
encryptedKey: encrypt(snapshot.data.key, "key"),
|
||||
encryptedKeyPassword: encrypt(
|
||||
snapshot.data.keyPassword,
|
||||
"key_password",
|
||||
),
|
||||
encryptedKeyType: snapshot.data.keyType || null,
|
||||
encryptedDomain: encrypt(snapshot.data.domain, "domain"),
|
||||
});
|
||||
}
|
||||
|
||||
await repository.deleteForHostAccessAndTarget(
|
||||
hostAccessId,
|
||||
targetUserId,
|
||||
snapshots.map((snapshot) => snapshot.protocol),
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to snapshot shared host secrets", error, {
|
||||
operation: "shared_host_secrets_snapshot",
|
||||
hostAccessId,
|
||||
hostId,
|
||||
targetUserId,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async snapshotForRole(
|
||||
hostAccessId: number,
|
||||
hostId: number,
|
||||
roleId: number,
|
||||
ownerId: string,
|
||||
): Promise<void> {
|
||||
const roleUserIds =
|
||||
await createCurrentRoleRepository().listRoleUserIds(roleId);
|
||||
|
||||
for (const userId of roleUserIds) {
|
||||
try {
|
||||
await this.snapshotForUser(hostAccessId, hostId, userId, ownerId);
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to snapshot shared host secrets for role member",
|
||||
error,
|
||||
{
|
||||
operation: "shared_host_secrets_snapshot_role",
|
||||
hostAccessId,
|
||||
roleId,
|
||||
userId,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async snapshotForRoleMember(
|
||||
roleId: number,
|
||||
targetUserId: string,
|
||||
): Promise<void> {
|
||||
const hostsSharedWithRole =
|
||||
await createCurrentRbacAccessRepository().listRoleHostAccessCredentialSources(
|
||||
roleId,
|
||||
);
|
||||
|
||||
for (const sharedHost of hostsSharedWithRole) {
|
||||
try {
|
||||
await this.snapshotForUser(
|
||||
sharedHost.hostAccessId,
|
||||
sharedHost.hostId,
|
||||
targetUserId,
|
||||
sharedHost.hostOwnerId,
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to snapshot shared host secrets for role member",
|
||||
error,
|
||||
{
|
||||
operation: "shared_host_secrets_snapshot_role_member",
|
||||
roleId,
|
||||
targetUserId,
|
||||
hostId: sharedHost.hostId,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async snapshotForUserRoles(userId: string): Promise<void> {
|
||||
const roleIds = await createCurrentRoleRepository().listUserRoleIds(userId);
|
||||
|
||||
for (const roleId of roleIds) {
|
||||
await this.snapshotForRoleMember(roleId, userId);
|
||||
}
|
||||
}
|
||||
|
||||
// Re-snapshot every active grant on a host. Called after the owner (or an
|
||||
// editor) changes the host so recipients keep working secrets.
|
||||
async resyncHost(hostId: number): Promise<void> {
|
||||
const hostResolutionRepository = createCurrentHostResolutionRepository();
|
||||
const ownerId = await hostResolutionRepository.findHostOwnerId(hostId);
|
||||
if (!ownerId) return;
|
||||
|
||||
const grants =
|
||||
await createCurrentRbacAccessRepository().listActiveHostAccessGrants(
|
||||
hostId,
|
||||
);
|
||||
if (grants.length === 0) return;
|
||||
|
||||
const roleRepository = createCurrentRoleRepository();
|
||||
|
||||
for (const grant of grants) {
|
||||
const targetUserIds = grant.userId
|
||||
? [grant.userId]
|
||||
: grant.roleId
|
||||
? await roleRepository.listRoleUserIds(grant.roleId)
|
||||
: [];
|
||||
|
||||
for (const targetUserId of targetUserIds) {
|
||||
if (targetUserId === ownerId) continue;
|
||||
try {
|
||||
await this.snapshotForUser(grant.id, hostId, targetUserId, ownerId);
|
||||
} catch (error) {
|
||||
databaseLogger.warn(
|
||||
"Skipping shared host secret resync for recipient",
|
||||
{
|
||||
operation: "shared_host_secrets_resync_skip",
|
||||
hostId,
|
||||
hostAccessId: grant.id,
|
||||
targetUserId,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Re-snapshot every shared host that references a credential after the
|
||||
// owner edits that credential.
|
||||
async resyncHostsForCredential(
|
||||
credentialId: number,
|
||||
ownerId: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const hostIds =
|
||||
await createCurrentSharedHostSecretsRepository().findHostIdsReferencingCredential(
|
||||
ownerId,
|
||||
credentialId,
|
||||
);
|
||||
|
||||
for (const hostId of hostIds) {
|
||||
await this.resyncHost(hostId);
|
||||
}
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to resync shared host secrets for credential",
|
||||
error,
|
||||
{
|
||||
operation: "shared_host_secrets_resync_credential",
|
||||
credentialId,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getSecretForUser(
|
||||
hostId: number,
|
||||
userId: string,
|
||||
protocol: ShareProtocol,
|
||||
): Promise<SharedSecretData | null> {
|
||||
try {
|
||||
const userDEK = DataCrypto.validateUserAccess(userId);
|
||||
|
||||
const secret =
|
||||
await createCurrentSharedHostSecretsRepository().findForHostUserProtocol(
|
||||
hostId,
|
||||
userId,
|
||||
protocol,
|
||||
);
|
||||
|
||||
if (!secret) return null;
|
||||
|
||||
return this.decryptSnapshot(secret, userDEK);
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to get shared host secret", error, {
|
||||
operation: "shared_host_secrets_get",
|
||||
hostId,
|
||||
userId,
|
||||
protocol,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteForHostAccess(hostAccessId: number): Promise<void> {
|
||||
try {
|
||||
await createCurrentSharedHostSecretsRepository().deleteByHostAccessId(
|
||||
hostAccessId,
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to delete shared host secrets for access grant",
|
||||
error,
|
||||
{
|
||||
operation: "shared_host_secrets_delete_access",
|
||||
hostAccessId,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteForUser(userId: string): Promise<void> {
|
||||
try {
|
||||
await createCurrentSharedHostSecretsRepository().deleteByTargetUserId(
|
||||
userId,
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to delete shared host secrets for user",
|
||||
error,
|
||||
{
|
||||
operation: "shared_host_secrets_delete_user",
|
||||
userId,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteForCredential(credentialId: number): Promise<void> {
|
||||
try {
|
||||
await createCurrentSharedHostSecretsRepository().deleteByOriginalCredentialId(
|
||||
credentialId,
|
||||
);
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to delete shared host secrets for credential",
|
||||
error,
|
||||
{
|
||||
operation: "shared_host_secrets_delete_credential",
|
||||
credentialId,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async collectProtocolSnapshots(
|
||||
host: HostResolutionHostRecord,
|
||||
ownerId: string,
|
||||
): Promise<ProtocolSnapshot[]> {
|
||||
const repository = createCurrentHostResolutionRepository();
|
||||
const enabled = enabledProtocols(host);
|
||||
const snapshots: ProtocolSnapshot[] = [];
|
||||
|
||||
if (enabled.ssh) {
|
||||
if (host.credentialId) {
|
||||
const credential = await repository.findCredentialByIdForUser(
|
||||
host.credentialId,
|
||||
ownerId,
|
||||
);
|
||||
if (credential) {
|
||||
snapshots.push({
|
||||
protocol: "ssh",
|
||||
sourceType: "credential",
|
||||
originalCredentialId: host.credentialId,
|
||||
data: {
|
||||
username: credential.username || undefined,
|
||||
authType: credential.authType,
|
||||
password: credential.password || undefined,
|
||||
key: credential.privateKey || credential.key || undefined,
|
||||
keyPassword: credential.keyPassword || undefined,
|
||||
keyType: credential.keyType || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (
|
||||
(host.authType === "password" && host.password) ||
|
||||
(host.authType === "key" && host.key)
|
||||
) {
|
||||
snapshots.push({
|
||||
protocol: "ssh",
|
||||
sourceType: "inline",
|
||||
originalCredentialId: null,
|
||||
data: {
|
||||
username: host.username || undefined,
|
||||
authType: host.authType,
|
||||
password: host.password || undefined,
|
||||
key: host.key || undefined,
|
||||
keyPassword: host.keyPassword || undefined,
|
||||
keyType: host.keyType || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (enabled.rdp) {
|
||||
const rdpAuthType =
|
||||
host.rdpAuthType || (host.rdpCredentialId ? "credential" : "direct");
|
||||
if (rdpAuthType === "credential" && host.rdpCredentialId) {
|
||||
const credential = await repository.findCredentialByIdForUser(
|
||||
host.rdpCredentialId,
|
||||
ownerId,
|
||||
);
|
||||
if (credential) {
|
||||
snapshots.push({
|
||||
protocol: "rdp",
|
||||
sourceType: "credential",
|
||||
originalCredentialId: host.rdpCredentialId,
|
||||
data: {
|
||||
username: credential.username || undefined,
|
||||
authType: "credential",
|
||||
password: credential.password || undefined,
|
||||
domain: host.rdpDomain || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (host.rdpUser || host.rdpPassword) {
|
||||
snapshots.push({
|
||||
protocol: "rdp",
|
||||
sourceType: "inline",
|
||||
originalCredentialId: null,
|
||||
data: {
|
||||
username: host.rdpUser || undefined,
|
||||
authType: "direct",
|
||||
password: host.rdpPassword || undefined,
|
||||
domain: host.rdpDomain || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (enabled.vnc) {
|
||||
const vncAuthType =
|
||||
host.vncAuthType || (host.vncCredentialId ? "credential" : "direct");
|
||||
if (vncAuthType === "credential" && host.vncCredentialId) {
|
||||
const credential = await repository.findCredentialByIdForUser(
|
||||
host.vncCredentialId,
|
||||
ownerId,
|
||||
);
|
||||
if (credential) {
|
||||
snapshots.push({
|
||||
protocol: "vnc",
|
||||
sourceType: "credential",
|
||||
originalCredentialId: host.vncCredentialId,
|
||||
data: {
|
||||
username: credential.username || undefined,
|
||||
authType: "credential",
|
||||
password: credential.password || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (host.vncUser || host.vncPassword) {
|
||||
snapshots.push({
|
||||
protocol: "vnc",
|
||||
sourceType: "inline",
|
||||
originalCredentialId: null,
|
||||
data: {
|
||||
username: host.vncUser || undefined,
|
||||
authType: "direct",
|
||||
password: host.vncPassword || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (enabled.telnet) {
|
||||
const telnetAuthType =
|
||||
host.telnetAuthType ||
|
||||
(host.telnetCredentialId ? "credential" : "direct");
|
||||
if (telnetAuthType === "credential" && host.telnetCredentialId) {
|
||||
const credential = await repository.findCredentialByIdForUser(
|
||||
host.telnetCredentialId,
|
||||
ownerId,
|
||||
);
|
||||
if (credential) {
|
||||
snapshots.push({
|
||||
protocol: "telnet",
|
||||
sourceType: "credential",
|
||||
originalCredentialId: host.telnetCredentialId,
|
||||
data: {
|
||||
username: credential.username || undefined,
|
||||
authType: "credential",
|
||||
password: credential.password || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (host.telnetUser || host.telnetPassword) {
|
||||
snapshots.push({
|
||||
protocol: "telnet",
|
||||
sourceType: "inline",
|
||||
originalCredentialId: null,
|
||||
data: {
|
||||
username: host.telnetUser || undefined,
|
||||
authType: "direct",
|
||||
password: host.telnetPassword || undefined,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return snapshots;
|
||||
}
|
||||
|
||||
private decryptSnapshot(
|
||||
secret: SharedHostSecretRecord,
|
||||
userDEK: Buffer,
|
||||
): SharedSecretData {
|
||||
const recordId = snapshotRecordId(
|
||||
secret.hostAccessId,
|
||||
secret.targetUserId,
|
||||
secret.protocol as ShareProtocol,
|
||||
);
|
||||
const decrypt = (value: string | null, fieldName: string) =>
|
||||
value
|
||||
? FieldCrypto.decryptField(value, userDEK, recordId, fieldName)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
username: decrypt(secret.encryptedUsername, "username"),
|
||||
authType: secret.encryptedAuthType || "password",
|
||||
password: decrypt(secret.encryptedPassword, "password"),
|
||||
key: decrypt(secret.encryptedKey, "key"),
|
||||
keyPassword: decrypt(secret.encryptedKeyPassword, "key_password"),
|
||||
keyType: secret.encryptedKeyType || undefined,
|
||||
domain: decrypt(secret.encryptedDomain, "domain"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export { SharedHostSecretsManager };
|
||||
@@ -1,191 +0,0 @@
|
||||
import { getDb, DatabaseSaveTrigger } from "../database/db/index.js";
|
||||
import { DataCrypto } from "./data-crypto.js";
|
||||
import type { SQLiteTable } from "drizzle-orm/sqlite-core";
|
||||
import type { SQL } from "drizzle-orm";
|
||||
|
||||
type TableName =
|
||||
| "users"
|
||||
| "ssh_data"
|
||||
| "ssh_credentials"
|
||||
| "termix_identity_ca"
|
||||
| "recent_activity"
|
||||
| "socks5_proxy_presets";
|
||||
|
||||
class SimpleDBOps {
|
||||
static async insert<T extends Record<string, unknown>>(
|
||||
table: SQLiteTable,
|
||||
tableName: TableName,
|
||||
data: T,
|
||||
userId: string,
|
||||
): Promise<T> {
|
||||
const userDataKey = DataCrypto.validateUserAccess(userId);
|
||||
|
||||
const tempId = data.id || `temp-${userId}-${Date.now()}`;
|
||||
const dataWithTempId = { ...data, id: tempId };
|
||||
|
||||
const encryptedData = DataCrypto.encryptRecord(
|
||||
tableName,
|
||||
dataWithTempId,
|
||||
userId,
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
if (tableName === "ssh_credentials") {
|
||||
const { SystemCrypto } = await import("./system-crypto.js");
|
||||
const systemCrypto = SystemCrypto.getInstance();
|
||||
const systemKey = await systemCrypto.getCredentialSharingKey();
|
||||
|
||||
const systemEncrypted = await DataCrypto.encryptRecordWithSystemKey(
|
||||
tableName,
|
||||
dataWithTempId,
|
||||
systemKey,
|
||||
);
|
||||
|
||||
Object.assign(encryptedData, systemEncrypted);
|
||||
}
|
||||
|
||||
if (!data.id) {
|
||||
delete encryptedData.id;
|
||||
}
|
||||
|
||||
const result = await getDb()
|
||||
.insert(table)
|
||||
.values(encryptedData)
|
||||
.returning();
|
||||
|
||||
DatabaseSaveTrigger.triggerSave(`insert_${tableName}`);
|
||||
|
||||
const decryptedResult = DataCrypto.decryptRecord(
|
||||
tableName,
|
||||
result[0],
|
||||
userId,
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
return decryptedResult as T;
|
||||
}
|
||||
|
||||
static async select<T extends Record<string, unknown>>(
|
||||
query: unknown,
|
||||
tableName: TableName,
|
||||
userId: string,
|
||||
): Promise<T[]> {
|
||||
const userDataKey = DataCrypto.getUserDataKey(userId);
|
||||
if (!userDataKey) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const results = await query;
|
||||
|
||||
const decryptedResults = DataCrypto.decryptRecords<T>(
|
||||
tableName,
|
||||
results as T[],
|
||||
userId,
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
return decryptedResults;
|
||||
}
|
||||
|
||||
static async selectOne<T extends Record<string, unknown>>(
|
||||
query: unknown,
|
||||
tableName: TableName,
|
||||
userId: string,
|
||||
): Promise<T | undefined> {
|
||||
const userDataKey = DataCrypto.getUserDataKey(userId);
|
||||
if (!userDataKey) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const result = await query;
|
||||
if (!result) return undefined;
|
||||
|
||||
const decryptedResult = DataCrypto.decryptRecord<T>(
|
||||
tableName,
|
||||
result as T,
|
||||
userId,
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
return decryptedResult;
|
||||
}
|
||||
|
||||
static async update<T extends Record<string, unknown>>(
|
||||
table: SQLiteTable,
|
||||
tableName: TableName,
|
||||
where: unknown,
|
||||
data: Partial<T>,
|
||||
userId: string,
|
||||
): Promise<T[]> {
|
||||
const userDataKey = DataCrypto.validateUserAccess(userId);
|
||||
|
||||
const encryptedData = DataCrypto.encryptRecord(
|
||||
tableName,
|
||||
data,
|
||||
userId,
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
if (tableName === "ssh_credentials") {
|
||||
const { SystemCrypto } = await import("./system-crypto.js");
|
||||
const systemCrypto = SystemCrypto.getInstance();
|
||||
const systemKey = await systemCrypto.getCredentialSharingKey();
|
||||
|
||||
const systemEncrypted = await DataCrypto.encryptRecordWithSystemKey(
|
||||
tableName,
|
||||
data,
|
||||
systemKey,
|
||||
);
|
||||
|
||||
Object.assign(encryptedData, systemEncrypted);
|
||||
}
|
||||
|
||||
const result = await getDb()
|
||||
.update(table)
|
||||
.set(encryptedData)
|
||||
.where(where as SQL | undefined)
|
||||
.returning();
|
||||
|
||||
DatabaseSaveTrigger.triggerSave(`update_${tableName}`);
|
||||
|
||||
const decryptedResults = DataCrypto.decryptRecords(
|
||||
tableName,
|
||||
result,
|
||||
userId,
|
||||
userDataKey,
|
||||
);
|
||||
|
||||
return decryptedResults as T[];
|
||||
}
|
||||
|
||||
static async delete(
|
||||
table: SQLiteTable,
|
||||
tableName: TableName,
|
||||
where: unknown,
|
||||
): Promise<unknown[]> {
|
||||
const result = await getDb()
|
||||
.delete(table)
|
||||
.where(where as SQL | undefined)
|
||||
.returning();
|
||||
|
||||
DatabaseSaveTrigger.triggerSave(`delete_${tableName}`);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
static async healthCheck(userId: string): Promise<boolean> {
|
||||
return DataCrypto.canUserAccessData(userId);
|
||||
}
|
||||
|
||||
static isUserDataUnlocked(userId: string): boolean {
|
||||
return DataCrypto.getUserDataKey(userId) !== null;
|
||||
}
|
||||
|
||||
static async selectEncrypted(query: unknown): Promise<unknown[]> {
|
||||
const results = await query;
|
||||
|
||||
return results as unknown[];
|
||||
}
|
||||
}
|
||||
|
||||
export { SimpleDBOps, type TableName };
|
||||
@@ -1,143 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import {
|
||||
parseSSHKey,
|
||||
parsePublicKey,
|
||||
preparePrivateKeyForSSH2,
|
||||
getFriendlyKeyTypeName,
|
||||
validateKeyPair,
|
||||
} from "./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,170 @@
|
||||
import swaggerJSDoc from "@deadendjs/swagger-jsdoc";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { promises as fs } from "fs";
|
||||
import { systemLogger } from "./logger.js";
|
||||
|
||||
type SwaggerJSDocOptions = Parameters<typeof swaggerJSDoc>[0];
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const swaggerOptions: SwaggerJSDocOptions = {
|
||||
definition: {
|
||||
openapi: "3.0.3",
|
||||
info: {
|
||||
title: "Termix API",
|
||||
version: "0.0.0",
|
||||
description: "Termix Backend API Reference",
|
||||
},
|
||||
servers: [
|
||||
{
|
||||
url: "http://localhost:30001",
|
||||
description: "Main database and authentication server",
|
||||
},
|
||||
{
|
||||
url: "http://localhost:30003",
|
||||
description: "SSH tunnel management server",
|
||||
},
|
||||
{
|
||||
url: "http://localhost:30004",
|
||||
description: "SSH file manager server",
|
||||
},
|
||||
{
|
||||
url: "http://localhost:30005",
|
||||
description: "Server statistics and monitoring server",
|
||||
},
|
||||
{
|
||||
url: "http://localhost:30006",
|
||||
description: "Dashboard server",
|
||||
},
|
||||
{
|
||||
url: "http://localhost:30007",
|
||||
description: "Docker management server",
|
||||
},
|
||||
{
|
||||
url: "http://localhost:30011",
|
||||
description: "Serial connection server",
|
||||
},
|
||||
],
|
||||
components: {
|
||||
securitySchemes: {
|
||||
bearerAuth: {
|
||||
type: "http",
|
||||
scheme: "bearer",
|
||||
bearerFormat: "JWT",
|
||||
},
|
||||
},
|
||||
schemas: {
|
||||
Error: {
|
||||
type: "object",
|
||||
properties: {
|
||||
error: { type: "string" },
|
||||
details: { type: "string" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
security: [
|
||||
{
|
||||
bearerAuth: [],
|
||||
},
|
||||
],
|
||||
tags: [
|
||||
{
|
||||
name: "Alerts",
|
||||
description: "System alerts and notifications management",
|
||||
},
|
||||
{
|
||||
name: "Credentials",
|
||||
description: "SSH credential management",
|
||||
},
|
||||
{
|
||||
name: "Network Topology",
|
||||
description: "Network topology visualization and management",
|
||||
},
|
||||
{
|
||||
name: "RBAC",
|
||||
description: "Role-based access control for host sharing",
|
||||
},
|
||||
{
|
||||
name: "Snippets",
|
||||
description: "Command snippet management",
|
||||
},
|
||||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command history",
|
||||
},
|
||||
{
|
||||
name: "Users",
|
||||
description: "User management and authentication",
|
||||
},
|
||||
{
|
||||
name: "Dashboard",
|
||||
description: "Dashboard statistics and activity",
|
||||
},
|
||||
{
|
||||
name: "Docker",
|
||||
description: "Docker container management",
|
||||
},
|
||||
{
|
||||
name: "SSH Tunnels",
|
||||
description: "SSH tunnel connection management",
|
||||
},
|
||||
{
|
||||
name: "Host Metrics",
|
||||
description: "Host status monitoring, metrics collection, and managers",
|
||||
},
|
||||
{
|
||||
name: "File Manager",
|
||||
description: "SSH file management operations",
|
||||
},
|
||||
],
|
||||
},
|
||||
apis: [
|
||||
path
|
||||
.join(__dirname, "..", "database", "routes", "*.js")
|
||||
.replace(/\\/g, "/"),
|
||||
path.join(__dirname, "..", "services", "*.js").replace(/\\/g, "/"),
|
||||
path.join(__dirname, "..", "hosts", "*.js").replace(/\\/g, "/"),
|
||||
path.join(__dirname, "..", "hosts", "**", "*.js").replace(/\\/g, "/"),
|
||||
],
|
||||
};
|
||||
|
||||
async function generateOpenAPISpec() {
|
||||
try {
|
||||
systemLogger.info("Generating OpenAPI specification", {
|
||||
operation: "openapi_generate_start",
|
||||
});
|
||||
|
||||
const swaggerSpec = await swaggerJSDoc(swaggerOptions);
|
||||
|
||||
const outputPath = path.join(
|
||||
__dirname,
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"..",
|
||||
"openapi.json",
|
||||
);
|
||||
|
||||
await fs.writeFile(
|
||||
outputPath,
|
||||
JSON.stringify(swaggerSpec, null, 2),
|
||||
"utf-8",
|
||||
);
|
||||
|
||||
systemLogger.success("OpenAPI specification generated", {
|
||||
operation: "openapi_generate_success",
|
||||
});
|
||||
} catch (error) {
|
||||
systemLogger.error("Failed to generate OpenAPI specification", error, {
|
||||
operation: "openapi_generation",
|
||||
});
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
generateOpenAPISpec();
|
||||
|
||||
export { swaggerOptions, generateOpenAPISpec };
|
||||
@@ -9,7 +9,6 @@ class SystemCrypto {
|
||||
private databaseKey: Buffer | null = null;
|
||||
private encryptionKey: Buffer | null = null;
|
||||
private internalAuthToken: string | null = null;
|
||||
private credentialSharingKey: Buffer | null = null;
|
||||
|
||||
private constructor() {}
|
||||
|
||||
@@ -196,52 +195,6 @@ class SystemCrypto {
|
||||
return this.internalAuthToken!;
|
||||
}
|
||||
|
||||
async initializeCredentialSharingKey(): Promise<void> {
|
||||
try {
|
||||
const dataDir = process.env.DATA_DIR || "./db/data";
|
||||
const envPath = path.join(dataDir, ".env");
|
||||
|
||||
const envKey = process.env.CREDENTIAL_SHARING_KEY;
|
||||
if (envKey && envKey.length >= 64) {
|
||||
this.credentialSharingKey = Buffer.from(envKey, "hex");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const envContent = await fs.readFile(envPath, "utf8");
|
||||
const csKeyMatch = envContent.match(/^CREDENTIAL_SHARING_KEY=(.+)$/m);
|
||||
if (csKeyMatch && csKeyMatch[1] && csKeyMatch[1].length >= 64) {
|
||||
this.credentialSharingKey = Buffer.from(csKeyMatch[1], "hex");
|
||||
process.env.CREDENTIAL_SHARING_KEY = csKeyMatch[1];
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// expected - env file may not exist
|
||||
}
|
||||
|
||||
await this.generateAndGuideCredentialSharingKey();
|
||||
} catch (error) {
|
||||
databaseLogger.error(
|
||||
"Failed to initialize credential sharing key",
|
||||
error,
|
||||
{
|
||||
operation: "cred_sharing_key_init_failed",
|
||||
dataDir: process.env.DATA_DIR || "./db/data",
|
||||
},
|
||||
);
|
||||
throw new Error("Credential sharing key initialization failed", {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async getCredentialSharingKey(): Promise<Buffer> {
|
||||
if (!this.credentialSharingKey) {
|
||||
await this.initializeCredentialSharingKey();
|
||||
}
|
||||
return this.credentialSharingKey!;
|
||||
}
|
||||
|
||||
private async generateAndGuideUser(): Promise<void> {
|
||||
const newSecret = crypto.randomBytes(32).toString("hex");
|
||||
const instanceId = crypto.randomBytes(8).toString("hex");
|
||||
@@ -311,26 +264,6 @@ class SystemCrypto {
|
||||
);
|
||||
}
|
||||
|
||||
private async generateAndGuideCredentialSharingKey(): Promise<void> {
|
||||
const newKey = crypto.randomBytes(32);
|
||||
const newKeyHex = newKey.toString("hex");
|
||||
const instanceId = crypto.randomBytes(8).toString("hex");
|
||||
|
||||
this.credentialSharingKey = newKey;
|
||||
|
||||
await this.updateEnvFile("CREDENTIAL_SHARING_KEY", newKeyHex);
|
||||
|
||||
databaseLogger.success(
|
||||
"Credential sharing key auto-generated and saved to .env",
|
||||
{
|
||||
operation: "cred_sharing_key_auto_generated",
|
||||
instanceId,
|
||||
envVarName: "CREDENTIAL_SHARING_KEY",
|
||||
note: "Used for offline credential sharing - no restart required",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async validateJWTSecret(): Promise<boolean> {
|
||||
try {
|
||||
const secret = await this.getJWTSecret();
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import type { Request } from "express";
|
||||
import {
|
||||
detectPlatform,
|
||||
parseUserAgent,
|
||||
generateDeviceFingerprint,
|
||||
} from "./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}$/);
|
||||
});
|
||||
});
|
||||
@@ -1,758 +0,0 @@
|
||||
import crypto from "crypto";
|
||||
import { getDb } from "../database/db/index.js";
|
||||
import { settings } from "../database/db/schema.js";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
|
||||
interface KEKSalt {
|
||||
salt: string;
|
||||
iterations: number;
|
||||
algorithm: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface EncryptedDEK {
|
||||
data: string;
|
||||
iv: string;
|
||||
tag: string;
|
||||
algorithm: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface UserSession {
|
||||
dataKey: Buffer;
|
||||
expiresAt: number;
|
||||
lastActivity?: number;
|
||||
}
|
||||
|
||||
class UserCrypto {
|
||||
private static instance: UserCrypto;
|
||||
private userSessions: Map<string, UserSession> = new Map();
|
||||
private sessionExpiredCallback?: (userId: string) => void;
|
||||
|
||||
private static readonly PBKDF2_ITERATIONS = 100000;
|
||||
private static readonly KEK_LENGTH = 32;
|
||||
private static readonly DEK_LENGTH = 32;
|
||||
|
||||
private constructor() {
|
||||
setInterval(
|
||||
() => {
|
||||
this.cleanupExpiredSessions();
|
||||
},
|
||||
5 * 60 * 1000,
|
||||
);
|
||||
}
|
||||
|
||||
static getInstance(): UserCrypto {
|
||||
if (!this.instance) {
|
||||
this.instance = new UserCrypto();
|
||||
}
|
||||
return this.instance;
|
||||
}
|
||||
|
||||
setSessionExpiredCallback(callback: (userId: string) => void): void {
|
||||
this.sessionExpiredCallback = callback;
|
||||
}
|
||||
|
||||
async setupUserEncryption(userId: string, password: string): Promise<void> {
|
||||
const kekSalt = await this.generateKEKSalt();
|
||||
await this.storeKEKSalt(userId, kekSalt);
|
||||
|
||||
const KEK = this.deriveKEK(password, kekSalt);
|
||||
const DEK = crypto.randomBytes(UserCrypto.DEK_LENGTH);
|
||||
const encryptedDEK = this.encryptDEK(DEK, KEK);
|
||||
await this.storeEncryptedDEK(userId, encryptedDEK);
|
||||
|
||||
KEK.fill(0);
|
||||
DEK.fill(0);
|
||||
}
|
||||
|
||||
async setupOIDCUserEncryption(
|
||||
userId: string,
|
||||
sessionDurationMs: number,
|
||||
): Promise<void> {
|
||||
const existingEncryptedDEK = await this.getEncryptedDEK(userId);
|
||||
|
||||
let DEK: Buffer;
|
||||
|
||||
if (existingEncryptedDEK) {
|
||||
const systemKey = this.deriveOIDCSystemKey(userId);
|
||||
DEK = this.decryptDEK(existingEncryptedDEK, systemKey);
|
||||
systemKey.fill(0);
|
||||
} else {
|
||||
DEK = crypto.randomBytes(UserCrypto.DEK_LENGTH);
|
||||
const systemKey = this.deriveOIDCSystemKey(userId);
|
||||
|
||||
try {
|
||||
const encryptedDEK = this.encryptDEK(DEK, systemKey);
|
||||
await this.storeEncryptedDEK(userId, encryptedDEK);
|
||||
|
||||
const storedEncryptedDEK = await this.getEncryptedDEK(userId);
|
||||
if (
|
||||
storedEncryptedDEK &&
|
||||
storedEncryptedDEK.data !== encryptedDEK.data
|
||||
) {
|
||||
DEK.fill(0);
|
||||
DEK = this.decryptDEK(storedEncryptedDEK, systemKey);
|
||||
} else if (!storedEncryptedDEK) {
|
||||
throw new Error("Failed to store and retrieve user encryption key.");
|
||||
}
|
||||
} finally {
|
||||
systemKey.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
this.userSessions.set(userId, {
|
||||
dataKey: Buffer.from(DEK),
|
||||
expiresAt: now + sessionDurationMs,
|
||||
});
|
||||
|
||||
DEK.fill(0);
|
||||
}
|
||||
|
||||
async authenticateUser(
|
||||
userId: string,
|
||||
password: string,
|
||||
sessionDurationMs: number,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const kekSalt = await this.getKEKSalt(userId);
|
||||
if (!kekSalt) return false;
|
||||
|
||||
const KEK = this.deriveKEK(password, kekSalt);
|
||||
const encryptedDEK = await this.getEncryptedDEK(userId);
|
||||
if (!encryptedDEK) {
|
||||
KEK.fill(0);
|
||||
return false;
|
||||
}
|
||||
|
||||
const DEK = this.decryptDEK(encryptedDEK, KEK);
|
||||
KEK.fill(0);
|
||||
|
||||
if (!DEK || DEK.length === 0) {
|
||||
databaseLogger.error("DEK is empty or invalid after decryption", {
|
||||
operation: "user_crypto_auth_debug",
|
||||
userId,
|
||||
dekLength: DEK ? DEK.length : 0,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
const oldSession = this.userSessions.get(userId);
|
||||
if (oldSession) {
|
||||
oldSession.dataKey.fill(0);
|
||||
}
|
||||
|
||||
this.userSessions.set(userId, {
|
||||
dataKey: Buffer.from(DEK),
|
||||
expiresAt: now + sessionDurationMs,
|
||||
});
|
||||
|
||||
DEK.fill(0);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
databaseLogger.warn("User authentication failed", {
|
||||
operation: "user_crypto_auth_failed",
|
||||
userId,
|
||||
error: error instanceof Error ? error.message : "Unknown",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async authenticateOIDCUser(
|
||||
userId: string,
|
||||
sessionDurationMs: number,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const oidcEncryptedDEK = await this.getOIDCEncryptedDEK(userId);
|
||||
|
||||
if (oidcEncryptedDEK) {
|
||||
const systemKey = this.deriveOIDCSystemKey(userId);
|
||||
const DEK = this.decryptDEK(oidcEncryptedDEK, systemKey);
|
||||
systemKey.fill(0);
|
||||
|
||||
if (!DEK || DEK.length === 0) {
|
||||
databaseLogger.error(
|
||||
"Failed to decrypt OIDC DEK for dual-auth user",
|
||||
{
|
||||
operation: "oidc_auth_dual_decrypt_failed",
|
||||
userId,
|
||||
},
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const oldSession = this.userSessions.get(userId);
|
||||
if (oldSession) {
|
||||
oldSession.dataKey.fill(0);
|
||||
}
|
||||
|
||||
this.userSessions.set(userId, {
|
||||
dataKey: Buffer.from(DEK),
|
||||
expiresAt: now + sessionDurationMs,
|
||||
});
|
||||
|
||||
DEK.fill(0);
|
||||
return true;
|
||||
}
|
||||
|
||||
const kekSalt = await this.getKEKSalt(userId);
|
||||
const encryptedDEK = await this.getEncryptedDEK(userId);
|
||||
|
||||
if (!kekSalt || !encryptedDEK) {
|
||||
await this.setupOIDCUserEncryption(userId, sessionDurationMs);
|
||||
return true;
|
||||
}
|
||||
|
||||
const systemKey = this.deriveOIDCSystemKey(userId);
|
||||
const DEK = this.decryptDEK(encryptedDEK, systemKey);
|
||||
systemKey.fill(0);
|
||||
|
||||
if (!DEK || DEK.length === 0) {
|
||||
await this.setupOIDCUserEncryption(userId, sessionDurationMs);
|
||||
return true;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
const oldSession = this.userSessions.get(userId);
|
||||
if (oldSession) {
|
||||
oldSession.dataKey.fill(0);
|
||||
}
|
||||
|
||||
this.userSessions.set(userId, {
|
||||
dataKey: Buffer.from(DEK),
|
||||
expiresAt: now + sessionDurationMs,
|
||||
});
|
||||
|
||||
DEK.fill(0);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
databaseLogger.error("OIDC authentication failed", error, {
|
||||
operation: "oidc_auth_error",
|
||||
userId,
|
||||
error: error instanceof Error ? error.message : "Unknown",
|
||||
});
|
||||
await this.setupOIDCUserEncryption(userId, sessionDurationMs);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
async setupWebAuthnUserEncryption(userId: string): Promise<void> {
|
||||
const existingDEK = this.getUserDataKey(userId);
|
||||
|
||||
if (!existingDEK) {
|
||||
throw new Error(
|
||||
"Cannot enable WebAuthn encryption - user session not active. Please log in first.",
|
||||
);
|
||||
}
|
||||
|
||||
const systemKey = this.deriveWebAuthnSystemKey(userId);
|
||||
const encryptedDEK = this.encryptDEK(existingDEK, systemKey);
|
||||
systemKey.fill(0);
|
||||
|
||||
await this.storeWebAuthnEncryptedDEK(userId, encryptedDEK);
|
||||
}
|
||||
|
||||
async authenticateWebAuthnUser(
|
||||
userId: string,
|
||||
sessionDurationMs: number,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const encryptedDEK = await this.getWebAuthnEncryptedDEK(userId);
|
||||
if (!encryptedDEK) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const systemKey = this.deriveWebAuthnSystemKey(userId);
|
||||
const DEK = this.decryptDEK(encryptedDEK, systemKey);
|
||||
systemKey.fill(0);
|
||||
|
||||
if (!DEK || DEK.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const oldSession = this.userSessions.get(userId);
|
||||
if (oldSession) {
|
||||
oldSession.dataKey.fill(0);
|
||||
}
|
||||
|
||||
this.userSessions.set(userId, {
|
||||
dataKey: Buffer.from(DEK),
|
||||
expiresAt: Date.now() + sessionDurationMs,
|
||||
});
|
||||
|
||||
DEK.fill(0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
databaseLogger.warn("WebAuthn authentication failed", {
|
||||
operation: "webauthn_auth_failed",
|
||||
userId,
|
||||
error: error instanceof Error ? error.message : "Unknown",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
getUserDataKey(userId: string): Buffer | null {
|
||||
const session = this.userSessions.get(userId);
|
||||
if (!session) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
|
||||
if (now > session.expiresAt) {
|
||||
this.userSessions.delete(userId);
|
||||
session.dataKey.fill(0);
|
||||
if (this.sessionExpiredCallback) {
|
||||
this.sessionExpiredCallback(userId);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return session.dataKey;
|
||||
}
|
||||
|
||||
restoreUserDataKey(userId: string, dataKey: Buffer, expiresAt: number): void {
|
||||
const oldSession = this.userSessions.get(userId);
|
||||
if (oldSession) {
|
||||
oldSession.dataKey.fill(0);
|
||||
}
|
||||
|
||||
this.userSessions.set(userId, {
|
||||
dataKey: Buffer.from(dataKey),
|
||||
expiresAt,
|
||||
lastActivity: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
logoutUser(userId: string): void {
|
||||
const session = this.userSessions.get(userId);
|
||||
if (session) {
|
||||
session.dataKey.fill(0);
|
||||
this.userSessions.delete(userId);
|
||||
}
|
||||
}
|
||||
|
||||
isUserUnlocked(userId: string): boolean {
|
||||
return this.getUserDataKey(userId) !== null;
|
||||
}
|
||||
|
||||
async changeUserPassword(
|
||||
userId: string,
|
||||
oldPassword: string,
|
||||
newPassword: string,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const isValid = await this.validatePassword(userId, oldPassword);
|
||||
if (!isValid) return false;
|
||||
|
||||
const kekSalt = await this.getKEKSalt(userId);
|
||||
if (!kekSalt) return false;
|
||||
|
||||
const oldKEK = this.deriveKEK(oldPassword, kekSalt);
|
||||
const encryptedDEK = await this.getEncryptedDEK(userId);
|
||||
if (!encryptedDEK) return false;
|
||||
|
||||
const DEK = this.decryptDEK(encryptedDEK, oldKEK);
|
||||
|
||||
const newKekSalt = await this.generateKEKSalt();
|
||||
const newKEK = this.deriveKEK(newPassword, newKekSalt);
|
||||
|
||||
const newEncryptedDEK = this.encryptDEK(DEK, newKEK);
|
||||
|
||||
await this.storeKEKSalt(userId, newKekSalt);
|
||||
await this.storeEncryptedDEK(userId, newEncryptedDEK);
|
||||
|
||||
const { saveMemoryDatabaseToFile } =
|
||||
await import("../database/db/index.js");
|
||||
await saveMemoryDatabaseToFile();
|
||||
|
||||
oldKEK.fill(0);
|
||||
newKEK.fill(0);
|
||||
DEK.fill(0);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
databaseLogger.error("Password change failed", error, {
|
||||
operation: "password_change_error",
|
||||
userId,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async resetUserPasswordWithPreservedDEK(
|
||||
userId: string,
|
||||
newPassword: string,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const existingDEK = this.getUserDataKey(userId);
|
||||
if (!existingDEK) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const newKekSalt = await this.generateKEKSalt();
|
||||
const newKEK = this.deriveKEK(newPassword, newKekSalt);
|
||||
|
||||
const newEncryptedDEK = this.encryptDEK(existingDEK, newKEK);
|
||||
|
||||
await this.storeKEKSalt(userId, newKekSalt);
|
||||
await this.storeEncryptedDEK(userId, newEncryptedDEK);
|
||||
|
||||
const { saveMemoryDatabaseToFile } =
|
||||
await import("../database/db/index.js");
|
||||
await saveMemoryDatabaseToFile();
|
||||
|
||||
newKEK.fill(0);
|
||||
|
||||
const session = this.userSessions.get(userId);
|
||||
if (session) {
|
||||
session.lastActivity = Date.now();
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
databaseLogger.error("Password reset with preserved DEK failed", error, {
|
||||
operation: "password_reset_preserve_error",
|
||||
userId,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async convertToOIDCEncryption(userId: string): Promise<void> {
|
||||
try {
|
||||
const existingEncryptedDEK = await this.getEncryptedDEK(userId);
|
||||
const existingKEKSalt = await this.getKEKSalt(userId);
|
||||
|
||||
if (!existingEncryptedDEK && !existingKEKSalt) {
|
||||
databaseLogger.warn("No existing encryption to convert for user", {
|
||||
operation: "convert_to_oidc_encryption_skip",
|
||||
userId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const existingDEK = this.getUserDataKey(userId);
|
||||
|
||||
if (!existingDEK) {
|
||||
throw new Error(
|
||||
"Cannot convert to OIDC encryption - user session not active. Please log in with password first.",
|
||||
);
|
||||
}
|
||||
|
||||
const systemKey = this.deriveOIDCSystemKey(userId);
|
||||
const oidcEncryptedDEK = this.encryptDEK(existingDEK, systemKey);
|
||||
systemKey.fill(0);
|
||||
|
||||
const key = `user_encrypted_dek_oidc_${userId}`;
|
||||
const value = JSON.stringify(oidcEncryptedDEK);
|
||||
|
||||
const { getDb } = await import("../database/db/index.js");
|
||||
const { settings } = await import("../database/db/schema.js");
|
||||
const { eq } = await import("drizzle-orm");
|
||||
|
||||
const existing = await getDb()
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(eq(settings.key, key));
|
||||
|
||||
if (existing.length > 0) {
|
||||
await getDb()
|
||||
.update(settings)
|
||||
.set({ value })
|
||||
.where(eq(settings.key, key));
|
||||
} else {
|
||||
await getDb().insert(settings).values({ key, value });
|
||||
}
|
||||
|
||||
databaseLogger.info(
|
||||
"Converted user encryption to dual-auth (password + OIDC)",
|
||||
{
|
||||
operation: "convert_to_oidc_encryption_preserved",
|
||||
userId,
|
||||
},
|
||||
);
|
||||
|
||||
const { saveMemoryDatabaseToFile } =
|
||||
await import("../database/db/index.js");
|
||||
await saveMemoryDatabaseToFile();
|
||||
} catch (error) {
|
||||
databaseLogger.error("Failed to convert to OIDC encryption", error, {
|
||||
operation: "convert_to_oidc_encryption_error",
|
||||
userId,
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async validatePassword(
|
||||
userId: string,
|
||||
password: string,
|
||||
): Promise<boolean> {
|
||||
try {
|
||||
const kekSalt = await this.getKEKSalt(userId);
|
||||
if (!kekSalt) return false;
|
||||
|
||||
const KEK = this.deriveKEK(password, kekSalt);
|
||||
const encryptedDEK = await this.getEncryptedDEK(userId);
|
||||
if (!encryptedDEK) return false;
|
||||
|
||||
const DEK = this.decryptDEK(encryptedDEK, KEK);
|
||||
|
||||
KEK.fill(0);
|
||||
DEK.fill(0);
|
||||
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private cleanupExpiredSessions(): void {
|
||||
const now = Date.now();
|
||||
const expiredUsers: string[] = [];
|
||||
|
||||
for (const [userId, session] of this.userSessions.entries()) {
|
||||
if (now > session.expiresAt) {
|
||||
session.dataKey.fill(0);
|
||||
expiredUsers.push(userId);
|
||||
}
|
||||
}
|
||||
|
||||
expiredUsers.forEach((userId) => {
|
||||
this.userSessions.delete(userId);
|
||||
});
|
||||
}
|
||||
|
||||
private async generateKEKSalt(): Promise<KEKSalt> {
|
||||
return {
|
||||
salt: crypto.randomBytes(32).toString("hex"),
|
||||
iterations: UserCrypto.PBKDF2_ITERATIONS,
|
||||
algorithm: "pbkdf2-sha256",
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private deriveKEK(password: string, kekSalt: KEKSalt): Buffer {
|
||||
return crypto.pbkdf2Sync(
|
||||
password,
|
||||
Buffer.from(kekSalt.salt, "hex"),
|
||||
kekSalt.iterations,
|
||||
UserCrypto.KEK_LENGTH,
|
||||
"sha256",
|
||||
);
|
||||
}
|
||||
|
||||
private deriveOIDCSystemKey(userId: string): Buffer {
|
||||
const systemSecret =
|
||||
process.env.OIDC_SYSTEM_SECRET || "termix-oidc-system-secret-default";
|
||||
const salt = Buffer.from(userId, "utf8");
|
||||
return crypto.pbkdf2Sync(
|
||||
systemSecret,
|
||||
salt,
|
||||
100000,
|
||||
UserCrypto.KEK_LENGTH,
|
||||
"sha256",
|
||||
);
|
||||
}
|
||||
|
||||
private deriveWebAuthnSystemKey(userId: string): Buffer {
|
||||
const systemSecret =
|
||||
process.env.WEBAUTHN_SYSTEM_SECRET ||
|
||||
process.env.OIDC_SYSTEM_SECRET ||
|
||||
"termix-webauthn-system-secret-default";
|
||||
const salt = Buffer.from(`webauthn:${userId}`, "utf8");
|
||||
return crypto.pbkdf2Sync(
|
||||
systemSecret,
|
||||
salt,
|
||||
100000,
|
||||
UserCrypto.KEK_LENGTH,
|
||||
"sha256",
|
||||
);
|
||||
}
|
||||
|
||||
private encryptDEK(dek: Buffer, kek: Buffer): EncryptedDEK {
|
||||
const iv = crypto.randomBytes(16);
|
||||
const cipher = crypto.createCipheriv("aes-256-gcm", kek, iv);
|
||||
|
||||
let encrypted = cipher.update(dek);
|
||||
encrypted = Buffer.concat([encrypted, cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
|
||||
return {
|
||||
data: encrypted.toString("hex"),
|
||||
iv: iv.toString("hex"),
|
||||
tag: tag.toString("hex"),
|
||||
algorithm: "aes-256-gcm",
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private decryptDEK(encryptedDEK: EncryptedDEK, kek: Buffer): Buffer {
|
||||
const decipher = crypto.createDecipheriv(
|
||||
"aes-256-gcm",
|
||||
kek,
|
||||
Buffer.from(encryptedDEK.iv, "hex"),
|
||||
);
|
||||
|
||||
decipher.setAuthTag(Buffer.from(encryptedDEK.tag, "hex"));
|
||||
let decrypted = decipher.update(Buffer.from(encryptedDEK.data, "hex"));
|
||||
decrypted = Buffer.concat([decrypted, decipher.final()]);
|
||||
|
||||
return decrypted;
|
||||
}
|
||||
|
||||
private async storeKEKSalt(userId: string, kekSalt: KEKSalt): Promise<void> {
|
||||
const key = `user_kek_salt_${userId}`;
|
||||
const value = JSON.stringify(kekSalt);
|
||||
|
||||
const existing = await getDb()
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(eq(settings.key, key));
|
||||
|
||||
if (existing.length > 0) {
|
||||
await getDb()
|
||||
.update(settings)
|
||||
.set({ value })
|
||||
.where(eq(settings.key, key));
|
||||
} else {
|
||||
await getDb().insert(settings).values({ key, value });
|
||||
}
|
||||
}
|
||||
|
||||
private async getKEKSalt(userId: string): Promise<KEKSalt | null> {
|
||||
try {
|
||||
const key = `user_kek_salt_${userId}`;
|
||||
const result = await getDb()
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(eq(settings.key, key));
|
||||
|
||||
if (result.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return JSON.parse(result[0].value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async storeEncryptedDEK(
|
||||
userId: string,
|
||||
encryptedDEK: EncryptedDEK,
|
||||
): Promise<void> {
|
||||
const key = `user_encrypted_dek_${userId}`;
|
||||
const value = JSON.stringify(encryptedDEK);
|
||||
|
||||
const existing = await getDb()
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(eq(settings.key, key));
|
||||
|
||||
if (existing.length > 0) {
|
||||
await getDb()
|
||||
.update(settings)
|
||||
.set({ value })
|
||||
.where(eq(settings.key, key));
|
||||
} else {
|
||||
await getDb().insert(settings).values({ key, value });
|
||||
}
|
||||
}
|
||||
|
||||
private async getEncryptedDEK(userId: string): Promise<EncryptedDEK | null> {
|
||||
try {
|
||||
const key = `user_encrypted_dek_${userId}`;
|
||||
const result = await getDb()
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(eq(settings.key, key));
|
||||
|
||||
if (result.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return JSON.parse(result[0].value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async getOIDCEncryptedDEK(
|
||||
userId: string,
|
||||
): Promise<EncryptedDEK | null> {
|
||||
try {
|
||||
const key = `user_encrypted_dek_oidc_${userId}`;
|
||||
const result = await getDb()
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(eq(settings.key, key));
|
||||
|
||||
if (result.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return JSON.parse(result[0].value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async storeWebAuthnEncryptedDEK(
|
||||
userId: string,
|
||||
encryptedDEK: EncryptedDEK,
|
||||
): Promise<void> {
|
||||
const key = `user_encrypted_dek_webauthn_${userId}`;
|
||||
const value = JSON.stringify(encryptedDEK);
|
||||
|
||||
const existing = await getDb()
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(eq(settings.key, key));
|
||||
|
||||
if (existing.length > 0) {
|
||||
await getDb()
|
||||
.update(settings)
|
||||
.set({ value })
|
||||
.where(eq(settings.key, key));
|
||||
} else {
|
||||
await getDb().insert(settings).values({ key, value });
|
||||
}
|
||||
}
|
||||
|
||||
private async getWebAuthnEncryptedDEK(
|
||||
userId: string,
|
||||
): Promise<EncryptedDEK | null> {
|
||||
try {
|
||||
const key = `user_encrypted_dek_webauthn_${userId}`;
|
||||
const result = await getDb()
|
||||
.select()
|
||||
.from(settings)
|
||||
.where(eq(settings.key, key));
|
||||
|
||||
if (result.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return JSON.parse(result[0].value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export { UserCrypto, type KEKSalt, type EncryptedDEK };
|
||||
@@ -1,15 +1,10 @@
|
||||
import { getDb } from "../database/db/index.js";
|
||||
import {
|
||||
users,
|
||||
hosts,
|
||||
sshCredentials,
|
||||
fileManagerRecent,
|
||||
fileManagerPinned,
|
||||
fileManagerShortcuts,
|
||||
transferRecent,
|
||||
dismissedAlerts,
|
||||
} from "../database/db/schema.js";
|
||||
import { eq } from "drizzle-orm";
|
||||
createCurrentDismissedAlertRepository,
|
||||
createCurrentFileManagerBookmarkRepository,
|
||||
createCurrentTransferRecentRepository,
|
||||
createCurrentUserDataExportRepository,
|
||||
createCurrentUserRepository,
|
||||
} from "../database/repositories/factory.js";
|
||||
import { DataCrypto } from "./data-crypto.js";
|
||||
import { databaseLogger } from "./logger.js";
|
||||
|
||||
@@ -54,16 +49,11 @@ class UserDataExport {
|
||||
} = options;
|
||||
|
||||
try {
|
||||
const user = await getDb()
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.id, userId));
|
||||
if (!user || user.length === 0) {
|
||||
const userRecord = await createCurrentUserRepository().findById(userId);
|
||||
if (!userRecord) {
|
||||
throw new Error(`User not found: ${userId}`);
|
||||
}
|
||||
|
||||
const userRecord = user[0];
|
||||
|
||||
let userDataKey: Buffer | null = null;
|
||||
if (format === "plaintext") {
|
||||
userDataKey = DataCrypto.getUserDataKey(userId);
|
||||
@@ -74,10 +64,8 @@ class UserDataExport {
|
||||
}
|
||||
}
|
||||
|
||||
const sshHosts = await getDb()
|
||||
.select()
|
||||
.from(hosts)
|
||||
.where(eq(hosts.userId, userId));
|
||||
const exportRepository = createCurrentUserDataExportRepository();
|
||||
const sshHosts = await exportRepository.listHostsByUserId(userId);
|
||||
const processedSshHosts =
|
||||
format === "plaintext" && userDataKey
|
||||
? sshHosts.map((host) =>
|
||||
@@ -87,10 +75,8 @@ class UserDataExport {
|
||||
|
||||
let sshCredentialsData: unknown[] = [];
|
||||
if (includeCredentials) {
|
||||
const credentials = await getDb()
|
||||
.select()
|
||||
.from(sshCredentials)
|
||||
.where(eq(sshCredentials.userId, userId));
|
||||
const credentials =
|
||||
await exportRepository.listCredentialsByUserId(userId);
|
||||
sshCredentialsData =
|
||||
format === "plaintext" && userDataKey
|
||||
? credentials.map((cred) =>
|
||||
@@ -106,28 +92,20 @@ class UserDataExport {
|
||||
|
||||
const [recentFiles, pinnedFiles, shortcuts, transferRecentData] =
|
||||
await Promise.all([
|
||||
getDb()
|
||||
.select()
|
||||
.from(fileManagerRecent)
|
||||
.where(eq(fileManagerRecent.userId, userId)),
|
||||
getDb()
|
||||
.select()
|
||||
.from(fileManagerPinned)
|
||||
.where(eq(fileManagerPinned.userId, userId)),
|
||||
getDb()
|
||||
.select()
|
||||
.from(fileManagerShortcuts)
|
||||
.where(eq(fileManagerShortcuts.userId, userId)),
|
||||
getDb()
|
||||
.select()
|
||||
.from(transferRecent)
|
||||
.where(eq(transferRecent.userId, userId)),
|
||||
createCurrentFileManagerBookmarkRepository().listRecentByUserId(
|
||||
userId,
|
||||
),
|
||||
createCurrentFileManagerBookmarkRepository().listPinnedByUserId(
|
||||
userId,
|
||||
),
|
||||
createCurrentFileManagerBookmarkRepository().listShortcutsByUserId(
|
||||
userId,
|
||||
),
|
||||
createCurrentTransferRecentRepository().listByUserId(userId),
|
||||
]);
|
||||
|
||||
const alerts = await getDb()
|
||||
.select()
|
||||
.from(dismissedAlerts)
|
||||
.where(eq(dismissedAlerts.userId, userId));
|
||||
const alerts =
|
||||
await createCurrentDismissedAlertRepository().listByUserId(userId);
|
||||
|
||||
const exportData: UserExportData = {
|
||||
version: this.EXPORT_VERSION,
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { getCurrentRepositorySqlite } from "../database/repositories/factory.js";
|
||||
|
||||
export interface UserEncryptionMigrationRecord {
|
||||
id: number | string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface UserEncryptionMigrationStore {
|
||||
listHostRecords(userId: string): UserEncryptionMigrationRecord[];
|
||||
listCredentialRecords(userId: string): UserEncryptionMigrationRecord[];
|
||||
getUserRecord(userId: string): UserEncryptionMigrationRecord | undefined;
|
||||
updateHostSensitiveFields(
|
||||
recordId: number | string,
|
||||
record: Record<string, unknown>,
|
||||
): void;
|
||||
updateCredentialSensitiveFields(
|
||||
recordId: number | string,
|
||||
record: Record<string, unknown>,
|
||||
): void;
|
||||
updateUserSensitiveFields(
|
||||
userId: string,
|
||||
record: Record<string, unknown>,
|
||||
): void;
|
||||
updatePasswordResetFields(
|
||||
table: "ssh_data" | "ssh_credentials" | "users",
|
||||
recordId: number | string,
|
||||
fields: string[],
|
||||
record: Record<string, unknown>,
|
||||
): void;
|
||||
}
|
||||
|
||||
export interface LegacyDatabaseInstance {
|
||||
prepare: (sql: string) => {
|
||||
all: (param?: unknown) => UserEncryptionMigrationRecord[];
|
||||
get: (param?: unknown) => UserEncryptionMigrationRecord | undefined;
|
||||
run: (...params: unknown[]) => unknown;
|
||||
};
|
||||
}
|
||||
|
||||
export class RawSqliteUserEncryptionMigrationStore implements UserEncryptionMigrationStore {
|
||||
constructor(private readonly db: LegacyDatabaseInstance) {}
|
||||
|
||||
listHostRecords(userId: string): UserEncryptionMigrationRecord[] {
|
||||
return this.db
|
||||
.prepare("SELECT * FROM ssh_data WHERE user_id = ?")
|
||||
.all(userId);
|
||||
}
|
||||
|
||||
listCredentialRecords(userId: string): UserEncryptionMigrationRecord[] {
|
||||
return this.db
|
||||
.prepare("SELECT * FROM ssh_credentials WHERE user_id = ?")
|
||||
.all(userId);
|
||||
}
|
||||
|
||||
getUserRecord(userId: string): UserEncryptionMigrationRecord | undefined {
|
||||
return this.db.prepare("SELECT * FROM users WHERE id = ?").get(userId);
|
||||
}
|
||||
|
||||
updateHostSensitiveFields(
|
||||
recordId: number | string,
|
||||
record: Record<string, unknown>,
|
||||
): void {
|
||||
this.db
|
||||
.prepare(
|
||||
`
|
||||
UPDATE ssh_data
|
||||
SET password = ?, key = ?, key_password = ?, key_type = ?, autostart_password = ?, autostart_key = ?, autostart_key_password = ?, sudo_password = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`,
|
||||
)
|
||||
.run(
|
||||
record.password || null,
|
||||
record.key || null,
|
||||
record.key_password || null,
|
||||
record.key_type || null,
|
||||
record.autostart_password || null,
|
||||
record.autostart_key || null,
|
||||
record.autostart_key_password || null,
|
||||
record.sudo_password || null,
|
||||
recordId,
|
||||
);
|
||||
}
|
||||
|
||||
updateCredentialSensitiveFields(
|
||||
recordId: number | string,
|
||||
record: Record<string, unknown>,
|
||||
): void {
|
||||
this.db
|
||||
.prepare(
|
||||
`
|
||||
UPDATE ssh_credentials
|
||||
SET password = ?, key = ?, key_password = ?, private_key = ?, public_key = ?, key_type = ?, updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?
|
||||
`,
|
||||
)
|
||||
.run(
|
||||
record.password || null,
|
||||
record.key || null,
|
||||
record.key_password || null,
|
||||
record.private_key || null,
|
||||
record.public_key || null,
|
||||
record.key_type || null,
|
||||
recordId,
|
||||
);
|
||||
}
|
||||
|
||||
updateUserSensitiveFields(
|
||||
userId: string,
|
||||
record: Record<string, unknown>,
|
||||
): void {
|
||||
this.db
|
||||
.prepare(
|
||||
`
|
||||
UPDATE users
|
||||
SET totp_secret = ?, totp_backup_codes = ?, client_secret = ?, oidc_identifier = ?
|
||||
WHERE id = ?
|
||||
`,
|
||||
)
|
||||
.run(
|
||||
record.totp_secret || null,
|
||||
record.totp_backup_codes || null,
|
||||
record.client_secret || null,
|
||||
record.oidc_identifier || null,
|
||||
userId,
|
||||
);
|
||||
}
|
||||
|
||||
updatePasswordResetFields(
|
||||
table: "ssh_data" | "ssh_credentials" | "users",
|
||||
recordId: number | string,
|
||||
fields: string[],
|
||||
record: Record<string, unknown>,
|
||||
): void {
|
||||
const setClause = fields.map((field) => `${field} = ?`).join(", ");
|
||||
const updateQuery =
|
||||
table === "users"
|
||||
? `UPDATE ${table} SET ${setClause} WHERE id = ?`
|
||||
: `UPDATE ${table} SET ${setClause}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`;
|
||||
const updateValues = fields.map((field) => record[field]);
|
||||
updateValues.push(recordId);
|
||||
|
||||
this.db.prepare(updateQuery).run(...updateValues);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createCurrentUserEncryptionMigrationStore(): Promise<UserEncryptionMigrationStore> {
|
||||
return new RawSqliteUserEncryptionMigrationStore(
|
||||
getCurrentRepositorySqlite(),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import crypto from "crypto";
|
||||
import { SystemCrypto } from "./system-crypto.js";
|
||||
import {
|
||||
createCurrentSettingsRepository,
|
||||
getCurrentSettingValue,
|
||||
} from "../database/repositories/factory.js";
|
||||
import { authLogger } from "./logger.js";
|
||||
|
||||
const DEK_LENGTH = 32;
|
||||
const WRAP_VERSION = 3;
|
||||
const WRAP_ALGORITHM = "aes-256-gcm";
|
||||
const WRAP_INFO_PREFIX = "termix:dek-wrap:v3:";
|
||||
const CACHE_TTL_MS = 15 * 60 * 1000;
|
||||
|
||||
export type UserKeyUnavailableReason = "pending_migration" | "missing";
|
||||
|
||||
export class UserKeyUnavailableError extends Error {
|
||||
constructor(
|
||||
readonly userId: string,
|
||||
readonly reason: UserKeyUnavailableReason,
|
||||
) {
|
||||
super(
|
||||
reason === "pending_migration"
|
||||
? `User ${userId} data stays locked until their next login migrates their encryption key`
|
||||
: `User ${userId} has no data encryption key`,
|
||||
);
|
||||
this.name = "UserKeyUnavailableError";
|
||||
}
|
||||
}
|
||||
|
||||
interface WrappedDek {
|
||||
v: number;
|
||||
alg: string;
|
||||
iv: string;
|
||||
ct: string;
|
||||
tag: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface CacheEntry {
|
||||
dek: Buffer;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export function userDekSettingsKey(userId: string): string {
|
||||
return `user_dek_v3_${userId}`;
|
||||
}
|
||||
|
||||
const LEGACY_WRAP_KEY_PREFIXES = [
|
||||
"user_encrypted_dek_",
|
||||
"user_kek_salt_",
|
||||
] as const;
|
||||
|
||||
export class UserKeyManager {
|
||||
private static instance: UserKeyManager | null = null;
|
||||
|
||||
private masterKey: Buffer | null = null;
|
||||
private cache = new Map<string, CacheEntry>();
|
||||
|
||||
static getInstance(): UserKeyManager {
|
||||
if (!UserKeyManager.instance) {
|
||||
UserKeyManager.instance = new UserKeyManager();
|
||||
}
|
||||
return UserKeyManager.instance;
|
||||
}
|
||||
|
||||
async initialize(masterKey?: Buffer): Promise<void> {
|
||||
this.masterKey =
|
||||
masterKey ?? (await SystemCrypto.getInstance().getEncryptionKey());
|
||||
this.cache.clear();
|
||||
}
|
||||
|
||||
getUserDEK(userId: string): Buffer {
|
||||
const cached = this.cache.get(userId);
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
return cached.dek;
|
||||
}
|
||||
|
||||
const raw = getCurrentSettingValue(userDekSettingsKey(userId));
|
||||
if (!raw) {
|
||||
throw new UserKeyUnavailableError(
|
||||
userId,
|
||||
this.hasLegacyWrap(userId) ? "pending_migration" : "missing",
|
||||
);
|
||||
}
|
||||
|
||||
const dek = this.unwrap(userId, raw);
|
||||
this.cacheDek(userId, dek);
|
||||
return dek;
|
||||
}
|
||||
|
||||
tryGetUserDEK(userId: string): Buffer | null {
|
||||
try {
|
||||
return this.getUserDEK(userId);
|
||||
} catch (error) {
|
||||
if (error instanceof UserKeyUnavailableError) {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
hasUserDEK(userId: string): boolean {
|
||||
if (this.cache.has(userId)) return true;
|
||||
return getCurrentSettingValue(userDekSettingsKey(userId)) !== null;
|
||||
}
|
||||
|
||||
async createUserDEK(userId: string): Promise<Buffer> {
|
||||
if (this.hasUserDEK(userId)) {
|
||||
throw new Error(`User ${userId} already has a data encryption key`);
|
||||
}
|
||||
|
||||
const dek = crypto.randomBytes(DEK_LENGTH);
|
||||
await this.persistDEK(userId, dek);
|
||||
return dek;
|
||||
}
|
||||
|
||||
async persistDEK(userId: string, dek: Buffer): Promise<void> {
|
||||
if (dek.length !== DEK_LENGTH) {
|
||||
throw new Error(`DEK must be ${DEK_LENGTH} bytes`);
|
||||
}
|
||||
|
||||
const wrapped = this.wrap(userId, dek);
|
||||
await createCurrentSettingsRepository().upsert(
|
||||
userDekSettingsKey(userId),
|
||||
JSON.stringify(wrapped),
|
||||
);
|
||||
this.cacheDek(userId, dek);
|
||||
}
|
||||
|
||||
async rotateUserDEK(userId: string): Promise<Buffer> {
|
||||
const dek = crypto.randomBytes(DEK_LENGTH);
|
||||
await this.persistDEK(userId, dek);
|
||||
authLogger.warn(`Replaced data encryption key for user ${userId}`, {
|
||||
operation: "user_dek_rotated",
|
||||
userId,
|
||||
});
|
||||
return dek;
|
||||
}
|
||||
|
||||
async deleteUserDEK(userId: string): Promise<void> {
|
||||
await createCurrentSettingsRepository().delete(userDekSettingsKey(userId));
|
||||
this.invalidate(userId);
|
||||
}
|
||||
|
||||
invalidate(userId: string): void {
|
||||
this.cache.delete(userId);
|
||||
}
|
||||
|
||||
clearCache(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
|
||||
private hasLegacyWrap(userId: string): boolean {
|
||||
return LEGACY_WRAP_KEY_PREFIXES.some(
|
||||
(prefix) => getCurrentSettingValue(`${prefix}${userId}`) !== null,
|
||||
);
|
||||
}
|
||||
|
||||
private cacheDek(userId: string, dek: Buffer): void {
|
||||
this.cache.set(userId, { dek, expiresAt: Date.now() + CACHE_TTL_MS });
|
||||
}
|
||||
|
||||
private deriveWrapKey(userId: string): Buffer {
|
||||
if (!this.masterKey) {
|
||||
throw new Error("UserKeyManager is not initialized");
|
||||
}
|
||||
|
||||
return Buffer.from(
|
||||
crypto.hkdfSync(
|
||||
"sha256",
|
||||
this.masterKey,
|
||||
Buffer.alloc(0),
|
||||
`${WRAP_INFO_PREFIX}${userId}`,
|
||||
DEK_LENGTH,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private wrap(userId: string, dek: Buffer): WrappedDek {
|
||||
const wrapKey = this.deriveWrapKey(userId);
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv(WRAP_ALGORITHM, wrapKey, iv);
|
||||
cipher.setAAD(Buffer.from(userId, "utf8"));
|
||||
const ct = Buffer.concat([cipher.update(dek), cipher.final()]);
|
||||
|
||||
return {
|
||||
v: WRAP_VERSION,
|
||||
alg: WRAP_ALGORITHM,
|
||||
iv: iv.toString("base64"),
|
||||
ct: ct.toString("base64"),
|
||||
tag: cipher.getAuthTag().toString("base64"),
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private unwrap(userId: string, raw: string): Buffer {
|
||||
let wrapped: WrappedDek;
|
||||
try {
|
||||
wrapped = JSON.parse(raw) as WrappedDek;
|
||||
} catch {
|
||||
throw new Error(`Stored key wrap for user ${userId} is not valid JSON`);
|
||||
}
|
||||
|
||||
if (wrapped.v !== WRAP_VERSION || wrapped.alg !== WRAP_ALGORITHM) {
|
||||
throw new Error(
|
||||
`Unsupported key wrap (v=${wrapped.v}, alg=${wrapped.alg}) for user ${userId}`,
|
||||
);
|
||||
}
|
||||
|
||||
const wrapKey = this.deriveWrapKey(userId);
|
||||
const decipher = crypto.createDecipheriv(
|
||||
WRAP_ALGORITHM,
|
||||
wrapKey,
|
||||
Buffer.from(wrapped.iv, "base64"),
|
||||
);
|
||||
decipher.setAAD(Buffer.from(userId, "utf8"));
|
||||
decipher.setAuthTag(Buffer.from(wrapped.tag, "base64"));
|
||||
|
||||
return Buffer.concat([
|
||||
decipher.update(Buffer.from(wrapped.ct, "base64")),
|
||||
decipher.final(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("dgram", () => {
|
||||
const socket = {
|
||||
once: vi.fn(),
|
||||
bind: vi.fn(),
|
||||
setBroadcast: vi.fn(),
|
||||
send: vi.fn(),
|
||||
close: vi.fn(),
|
||||
};
|
||||
return { default: { createSocket: vi.fn(() => socket) } };
|
||||
});
|
||||
|
||||
import dgram from "dgram";
|
||||
import { isValidMac, buildMagicPacket, sendWakeOnLan } from "./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