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 commit 0712fdd731.

* 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 commit 0712fdd731.

* 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:
Luke Gustafson
2026-07-19 12:29:52 -05:00
committed by GitHub
co-authored by emreumar dependabot[bot] ZacharyZcR Russell Poovey russell Subedi Bibek Claude Fable 5 Alexander Elsner SankeerthNara Stephan Groth DivByZero devdanetra Aleksandr Fominykh sash lhojun Yunus Emre Umar
parent fba645e92e
commit ddbdd5c437
562 changed files with 52303 additions and 23645 deletions
@@ -0,0 +1,622 @@
import { and, count, desc, eq, inArray, isNull, or } from "drizzle-orm";
import {
alertFirings,
alertRuleChannels,
alertRules,
hosts,
notificationChannels,
} from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
type AlertRuleRecord = typeof alertRules.$inferSelect;
type NotificationChannelRecord = typeof notificationChannels.$inferSelect;
type AlertFiringRecord = typeof alertFirings.$inferSelect;
export interface NotificationChannelRow {
id: number;
user_id: string;
name: string;
type: string;
config: string;
enabled: number;
created_at: string;
}
export interface AlertRuleRow {
id: number;
user_id: string;
host_id: number | null;
name: string;
enabled: number;
trigger_type: string;
threshold_value: number | null;
threshold_duration_seconds: number | null;
cooldown_minutes: number;
created_at: string;
updated_at: string;
}
export interface AlertRuleWithChannelsRow extends AlertRuleRow {
channels: number[];
}
export interface AlertFiringRow {
id: number;
user_id: string;
rule_id: number;
host_id: number;
host_name: string;
fired_at: string;
resolved_at: string | null;
value: number | null;
message: string;
severity: string;
acknowledged: number;
rule_name: string | null;
}
export interface AlertEngineRule {
id: number;
userId: string;
hostId: number | null;
name: string;
enabled: boolean;
triggerType: string;
thresholdValue: number | null;
thresholdDurationSeconds: number | null;
cooldownMinutes: number;
}
export interface AlertEngineChannel {
id: number;
type: string;
config: string;
enabled: boolean;
}
export class AlertRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listNotificationChannels(
userId: string,
): Promise<NotificationChannelRow[]> {
const rows = await this.context.drizzle
.select()
.from(notificationChannels)
.where(eq(notificationChannels.userId, userId))
.orderBy(notificationChannels.id);
return rows.map(mapChannelRow);
}
async findNotificationChannelForUser(
id: number,
userId: string,
): Promise<NotificationChannelRow | null> {
const rows = await this.context.drizzle
.select()
.from(notificationChannels)
.where(
and(
eq(notificationChannels.id, id),
eq(notificationChannels.userId, userId),
),
)
.limit(1);
return rows[0] ? mapChannelRow(rows[0]) : null;
}
async createNotificationChannel(input: {
userId: string;
name: string;
type: string;
config: string;
enabled: boolean;
}): Promise<NotificationChannelRow> {
const [created] = await this.context.drizzle
.insert(notificationChannels)
.values({
userId: input.userId,
name: input.name,
type: input.type,
config: input.config,
enabled: input.enabled,
})
.returning();
await this.afterWrite();
return mapChannelRow(created);
}
async updateNotificationChannel(
id: number,
userId: string,
input: {
name?: string;
type?: string;
config?: string;
enabled?: boolean;
},
): Promise<NotificationChannelRow | null> {
if (Object.keys(input).length === 0) {
return this.findNotificationChannelForUser(id, userId);
}
const [updated] = await this.context.drizzle
.update(notificationChannels)
.set(input)
.where(
and(
eq(notificationChannels.id, id),
eq(notificationChannels.userId, userId),
),
)
.returning();
if (!updated) return null;
await this.afterWrite();
return mapChannelRow(updated);
}
async deleteNotificationChannel(
id: number,
userId: string,
): Promise<boolean> {
const deleted = await this.context.drizzle
.delete(notificationChannels)
.where(
and(
eq(notificationChannels.id, id),
eq(notificationChannels.userId, userId),
),
)
.returning({ id: notificationChannels.id });
if (deleted.length === 0) return false;
await this.afterWrite();
return true;
}
async listAlertRules(userId: string): Promise<AlertRuleWithChannelsRow[]> {
const rules = await this.context.drizzle
.select()
.from(alertRules)
.where(eq(alertRules.userId, userId))
.orderBy(alertRules.id);
const result: AlertRuleWithChannelsRow[] = [];
for (const rule of rules) {
result.push({
...mapRuleRow(rule),
channels: await this.listChannelIdsForRule(rule.id),
});
}
return result;
}
async createAlertRule(input: {
userId: string;
hostId: number | null;
name: string;
enabled: boolean;
triggerType: string;
thresholdValue: number | null;
thresholdDurationSeconds: number | null;
cooldownMinutes: number;
channels: number[];
now: string;
}): Promise<AlertRuleWithChannelsRow> {
const [created] = await this.context.drizzle
.insert(alertRules)
.values({
userId: input.userId,
hostId: input.hostId,
name: input.name,
enabled: input.enabled,
triggerType: input.triggerType,
thresholdValue: input.thresholdValue,
thresholdDurationSeconds: input.thresholdDurationSeconds,
cooldownMinutes: input.cooldownMinutes,
createdAt: input.now,
updatedAt: input.now,
})
.returning();
const channels = await this.replaceRuleChannels(
created.id,
input.userId,
input.channels,
);
await this.afterWrite();
return { ...mapRuleRow(created), channels };
}
async findAlertRuleForUser(
id: number,
userId: string,
): Promise<AlertRuleRow | null> {
const rows = await this.context.drizzle
.select()
.from(alertRules)
.where(and(eq(alertRules.id, id), eq(alertRules.userId, userId)))
.limit(1);
return rows[0] ? mapRuleRow(rows[0]) : null;
}
async updateAlertRule(
id: number,
userId: string,
input: {
name?: string;
hostId?: number | null;
enabled?: boolean;
triggerType?: string;
thresholdValue?: number | null;
thresholdDurationSeconds?: number | null;
cooldownMinutes?: number;
channels?: number[];
now: string;
},
): Promise<AlertRuleWithChannelsRow | null> {
const [updated] = await this.context.drizzle
.update(alertRules)
.set({
...(input.name !== undefined ? { name: input.name } : {}),
...(input.hostId !== undefined ? { hostId: input.hostId } : {}),
...(input.enabled !== undefined ? { enabled: input.enabled } : {}),
...(input.triggerType !== undefined
? { triggerType: input.triggerType }
: {}),
...(input.thresholdValue !== undefined
? { thresholdValue: input.thresholdValue }
: {}),
...(input.thresholdDurationSeconds !== undefined
? { thresholdDurationSeconds: input.thresholdDurationSeconds }
: {}),
...(input.cooldownMinutes !== undefined
? { cooldownMinutes: input.cooldownMinutes }
: {}),
updatedAt: input.now,
})
.where(and(eq(alertRules.id, id), eq(alertRules.userId, userId)))
.returning();
if (!updated) return null;
const channels =
input.channels === undefined
? await this.listChannelIdsForRule(id)
: await this.replaceRuleChannels(id, userId, input.channels);
await this.afterWrite();
return { ...mapRuleRow(updated), channels };
}
async deleteAlertRule(id: number, userId: string): Promise<boolean> {
const deleted = await this.context.drizzle
.delete(alertRules)
.where(and(eq(alertRules.id, id), eq(alertRules.userId, userId)))
.returning({ id: alertRules.id });
if (deleted.length === 0) return false;
await this.afterWrite();
return true;
}
async listAlertFirings(input: {
userId: string;
acknowledged?: boolean;
limit: number;
offset: number;
}): Promise<{ firings: AlertFiringRow[]; total: number }> {
const filters = [eq(alertFirings.userId, input.userId)];
if (input.acknowledged !== undefined) {
filters.push(eq(alertFirings.acknowledged, input.acknowledged));
}
const where = and(...filters);
const rows = await this.context.drizzle
.select({
firing: alertFirings,
ruleName: alertRules.name,
})
.from(alertFirings)
.leftJoin(alertRules, eq(alertRules.id, alertFirings.ruleId))
.where(where)
.orderBy(desc(alertFirings.firedAt))
.limit(input.limit)
.offset(input.offset);
const totalRows = await this.context.drizzle
.select({ total: count() })
.from(alertFirings)
.where(where);
return {
firings: rows.map((row) => mapFiringRow(row.firing, row.ruleName)),
total: totalRows[0]?.total ?? 0,
};
}
async acknowledgeFiring(id: number, userId: string): Promise<void> {
await this.context.drizzle
.update(alertFirings)
.set({ acknowledged: true })
.where(and(eq(alertFirings.id, id), eq(alertFirings.userId, userId)));
await this.afterWrite();
}
async acknowledgeAllFirings(userId: string): Promise<void> {
await this.context.drizzle
.update(alertFirings)
.set({ acknowledged: true })
.where(eq(alertFirings.userId, userId));
await this.afterWrite();
}
async listEnabledRulesForHost(hostId: number): Promise<AlertEngineRule[]> {
const rows = await this.context.drizzle
.select()
.from(alertRules)
.where(
and(
eq(alertRules.enabled, true),
or(eq(alertRules.hostId, hostId), isNull(alertRules.hostId)),
),
);
return rows.map(mapEngineRule);
}
async listEnabledRulesForHostUser(
hostId: number,
userId: string,
): Promise<AlertEngineRule[]> {
const rows = await this.context.drizzle
.select()
.from(alertRules)
.where(
and(
eq(alertRules.enabled, true),
eq(alertRules.userId, userId),
or(eq(alertRules.hostId, hostId), isNull(alertRules.hostId)),
),
);
return rows.map(mapEngineRule);
}
async findRuleById(id: number): Promise<AlertEngineRule | null> {
const rows = await this.context.drizzle
.select()
.from(alertRules)
.where(eq(alertRules.id, id))
.limit(1);
return rows[0] ? mapEngineRule(rows[0]) : null;
}
async createFiring(input: {
userId: string;
ruleId: number;
hostId: number;
hostName: string;
value: number | null;
message: string;
severity: string;
}): Promise<void> {
await this.context.drizzle.insert(alertFirings).values(input);
await this.afterWrite();
}
pruneFiringsOlderThan(userId: string, days: number): void {
this.context.sqlite
?.prepare(
"DELETE FROM alert_firings WHERE user_id = ? AND fired_at < datetime('now', ?)",
)
.run(userId, `-${days} days`);
}
async deleteByUserId(userId: string): Promise<{
firingsDeleted: number;
ruleLinksDeleted: number;
rulesDeleted: number;
channelsDeleted: number;
}> {
const ruleIds = (
await this.context.drizzle
.select({ id: alertRules.id })
.from(alertRules)
.where(eq(alertRules.userId, userId))
).map((row) => row.id);
const channelIds = (
await this.context.drizzle
.select({ id: notificationChannels.id })
.from(notificationChannels)
.where(eq(notificationChannels.userId, userId))
).map((row) => row.id);
const firingRows = await this.context.drizzle
.delete(alertFirings)
.where(eq(alertFirings.userId, userId))
.returning({ id: alertFirings.id });
const linkFilters = [
...(ruleIds.length > 0
? [inArray(alertRuleChannels.ruleId, ruleIds)]
: []),
...(channelIds.length > 0
? [inArray(alertRuleChannels.channelId, channelIds)]
: []),
];
const linkRows =
linkFilters.length === 0
? []
: await this.context.drizzle
.delete(alertRuleChannels)
.where(or(...linkFilters))
.returning({ id: alertRuleChannels.id });
const ruleRows = await this.context.drizzle
.delete(alertRules)
.where(eq(alertRules.userId, userId))
.returning({ id: alertRules.id });
const channelRows = await this.context.drizzle
.delete(notificationChannels)
.where(eq(notificationChannels.userId, userId))
.returning({ id: notificationChannels.id });
if (
firingRows.length > 0 ||
linkRows.length > 0 ||
ruleRows.length > 0 ||
channelRows.length > 0
) {
await this.afterWrite();
}
return {
firingsDeleted: firingRows.length,
ruleLinksDeleted: linkRows.length,
rulesDeleted: ruleRows.length,
channelsDeleted: channelRows.length,
};
}
async listEnabledChannelsForRule(
ruleId: number,
): Promise<AlertEngineChannel[]> {
const rows = await this.context.drizzle
.select({
id: notificationChannels.id,
type: notificationChannels.type,
config: notificationChannels.config,
enabled: notificationChannels.enabled,
})
.from(notificationChannels)
.innerJoin(
alertRuleChannels,
eq(alertRuleChannels.channelId, notificationChannels.id),
)
.where(
and(
eq(alertRuleChannels.ruleId, ruleId),
eq(notificationChannels.enabled, true),
),
);
return rows;
}
async getHostDisplayName(hostId: number): Promise<string | null> {
const rows = await this.context.drizzle
.select({ name: hosts.name, ip: hosts.ip })
.from(hosts)
.where(eq(hosts.id, hostId))
.limit(1);
const row = rows[0];
return row ? row.name || row.ip : null;
}
private async replaceRuleChannels(
ruleId: number,
userId: string,
channelIds: number[],
): Promise<number[]> {
await this.context.drizzle
.delete(alertRuleChannels)
.where(eq(alertRuleChannels.ruleId, ruleId));
const linked: number[] = [];
for (const channelId of channelIds) {
const channel = await this.findNotificationChannelForUser(
channelId,
userId,
);
if (!channel) continue;
await this.context.drizzle
.insert(alertRuleChannels)
.values({ ruleId, channelId });
linked.push(channelId);
}
return linked;
}
private async listChannelIdsForRule(ruleId: number): Promise<number[]> {
const rows = await this.context.drizzle
.select({ channelId: alertRuleChannels.channelId })
.from(alertRuleChannels)
.where(eq(alertRuleChannels.ruleId, ruleId));
return rows.map((row) => row.channelId);
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
function mapChannelRow(row: NotificationChannelRecord): NotificationChannelRow {
return {
id: row.id,
user_id: row.userId,
name: row.name,
type: row.type,
config: row.config,
enabled: row.enabled ? 1 : 0,
created_at: row.createdAt,
};
}
function mapRuleRow(row: AlertRuleRecord): AlertRuleRow {
return {
id: row.id,
user_id: row.userId,
host_id: row.hostId,
name: row.name,
enabled: row.enabled ? 1 : 0,
trigger_type: row.triggerType,
threshold_value: row.thresholdValue,
threshold_duration_seconds: row.thresholdDurationSeconds,
cooldown_minutes: row.cooldownMinutes,
created_at: row.createdAt,
updated_at: row.updatedAt,
};
}
function mapFiringRow(
row: AlertFiringRecord,
ruleName: string | null,
): AlertFiringRow {
return {
id: row.id,
user_id: row.userId,
rule_id: row.ruleId,
host_id: row.hostId,
host_name: row.hostName,
fired_at: row.firedAt,
resolved_at: row.resolvedAt,
value: row.value,
message: row.message,
severity: row.severity,
acknowledged: row.acknowledged ? 1 : 0,
rule_name: ruleName,
};
}
function mapEngineRule(row: AlertRuleRecord): AlertEngineRule {
return {
id: row.id,
userId: row.userId,
hostId: row.hostId,
name: row.name,
enabled: row.enabled,
triggerType: row.triggerType,
thresholdValue: row.thresholdValue,
thresholdDurationSeconds: row.thresholdDurationSeconds,
cooldownMinutes: row.cooldownMinutes,
};
}
@@ -0,0 +1,103 @@
import { eq, and } from "drizzle-orm";
import { apiKeys, users } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type ApiKeyRecord = typeof apiKeys.$inferSelect;
export type NewApiKeyRecord = typeof apiKeys.$inferInsert;
export interface ApiKeyListRecord {
id: string;
name: string;
userId: string;
username: string | null;
tokenPrefix: string;
createdAt: string;
expiresAt: string | null;
lastUsedAt: string | null;
isActive: boolean;
}
export class ApiKeyRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async create(apiKey: NewApiKeyRecord): Promise<ApiKeyRecord> {
const rows = await this.context.drizzle
.insert(apiKeys)
.values(apiKey)
.returning();
await this.afterWrite();
return rows[0];
}
async listAllWithUsers(): Promise<ApiKeyListRecord[]> {
return this.context.drizzle
.select({
id: apiKeys.id,
name: apiKeys.name,
userId: apiKeys.userId,
username: users.username,
tokenPrefix: apiKeys.tokenPrefix,
createdAt: apiKeys.createdAt,
expiresAt: apiKeys.expiresAt,
lastUsedAt: apiKeys.lastUsedAt,
isActive: apiKeys.isActive,
})
.from(apiKeys)
.leftJoin(users, eq(apiKeys.userId, users.id))
.orderBy(apiKeys.createdAt);
}
async findById(id: string): Promise<ApiKeyRecord | null> {
const rows = await this.context.drizzle
.select()
.from(apiKeys)
.where(eq(apiKeys.id, id))
.limit(1);
return rows[0] ?? null;
}
async listActiveByTokenPrefix(tokenPrefix: string): Promise<ApiKeyRecord[]> {
return this.context.drizzle
.select()
.from(apiKeys)
.where(
and(eq(apiKeys.tokenPrefix, tokenPrefix), eq(apiKeys.isActive, true)),
);
}
async updateLastUsedAt(id: string, lastUsedAt: string): Promise<void> {
await this.context.drizzle
.update(apiKeys)
.set({ lastUsedAt })
.where(eq(apiKeys.id, id));
await this.afterWrite();
}
async delete(id: string): Promise<ApiKeyRecord | null> {
const rows = await this.context.drizzle
.delete(apiKeys)
.where(eq(apiKeys.id, id))
.returning();
await this.afterWrite();
return rows[0] ?? null;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(apiKeys)
.where(eq(apiKeys.userId, userId))
.returning({ id: apiKeys.id });
await this.afterWrite();
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,135 @@
import { and, asc, desc, eq, gte, inArray, lte, sql } from "drizzle-orm";
import { auditLogs } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type AuditLogRecord = typeof auditLogs.$inferSelect;
export type NewAuditLogRecord = typeof auditLogs.$inferInsert;
export type AuditLogFilters = {
userId?: string;
action?: string;
resourceType?: string;
success?: boolean;
startDate?: string;
endDate?: string;
};
export type AuditLogPage = {
logs: AuditLogRecord[];
total: number;
};
const PRUNE_MAX = 10000;
const PRUNE_TARGET = 9000;
export class AuditLogRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async create(entry: NewAuditLogRecord): Promise<void> {
await this.context.drizzle.insert(auditLogs).values(entry);
await this.pruneIfNeeded();
await this.afterWrite();
}
async listPage(input: {
filters: AuditLogFilters;
limit: number;
offset: number;
}): Promise<AuditLogPage> {
const whereClause = this.buildWhere(input.filters);
const [logs, totalResult] = await Promise.all([
this.context.drizzle
.select()
.from(auditLogs)
.where(whereClause)
.orderBy(desc(auditLogs.timestamp))
.limit(input.limit)
.offset(input.offset),
this.context.drizzle
.select({ count: sql<number>`COUNT(*)` })
.from(auditLogs)
.where(whereClause),
]);
return {
logs,
total: totalResult[0]?.count ?? 0,
};
}
async listDistinctActions(): Promise<string[]> {
const rows = await this.context.drizzle
.selectDistinct({ action: auditLogs.action })
.from(auditLogs)
.orderBy(asc(auditLogs.action));
return rows.map((row) => row.action);
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(auditLogs)
.where(eq(auditLogs.userId, userId))
.returning({ id: auditLogs.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private buildWhere(filters: AuditLogFilters) {
const conditions = [];
if (filters.userId) conditions.push(eq(auditLogs.userId, filters.userId));
if (filters.action) conditions.push(eq(auditLogs.action, filters.action));
if (filters.resourceType) {
conditions.push(eq(auditLogs.resourceType, filters.resourceType));
}
if (filters.success !== undefined) {
conditions.push(eq(auditLogs.success, filters.success));
}
if (filters.startDate) {
conditions.push(gte(auditLogs.timestamp, filters.startDate));
}
if (filters.endDate) {
conditions.push(lte(auditLogs.timestamp, filters.endDate));
}
return conditions.length > 0 ? and(...conditions) : undefined;
}
private async pruneIfNeeded(): Promise<void> {
const countResult = await this.context.drizzle
.select({ count: sql<number>`COUNT(*)` })
.from(auditLogs);
const count = countResult[0]?.count ?? 0;
if (count < PRUNE_MAX) {
return;
}
const deleteCount = count - PRUNE_TARGET;
const rows = await this.context.drizzle
.select({ id: auditLogs.id })
.from(auditLogs)
.orderBy(asc(auditLogs.timestamp))
.limit(deleteCount);
const ids = rows.map((row) => row.id);
if (ids.length > 0) {
await this.context.drizzle
.delete(auditLogs)
.where(inArray(auditLogs.id, ids));
}
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,136 @@
import { and, asc, eq, sql } from "drizzle-orm";
import { c2sTunnelPresets } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type C2sTunnelPresetRecord = typeof c2sTunnelPresets.$inferSelect;
export interface C2sTunnelPresetCreateInput {
name: string;
config: string;
platform?: string | null;
computerName?: string | null;
}
export type C2sTunnelPresetUpdateInput = Partial<C2sTunnelPresetCreateInput>;
export class C2sTunnelPresetRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listByUserId(userId: string): Promise<C2sTunnelPresetRecord[]> {
return this.context.drizzle
.select()
.from(c2sTunnelPresets)
.where(eq(c2sTunnelPresets.userId, userId))
.orderBy(asc(c2sTunnelPresets.name));
}
async findByIdForUser(
userId: string,
id: number,
): Promise<C2sTunnelPresetRecord | null> {
const rows = await this.context.drizzle
.select()
.from(c2sTunnelPresets)
.where(
and(eq(c2sTunnelPresets.id, id), eq(c2sTunnelPresets.userId, userId)),
)
.limit(1);
return rows[0] ?? null;
}
async hasNameForUser(
userId: string,
name: string,
excludingId?: number,
): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: c2sTunnelPresets.id })
.from(c2sTunnelPresets)
.where(
and(
eq(c2sTunnelPresets.userId, userId),
eq(c2sTunnelPresets.name, name),
),
);
return rows.some((row) => row.id !== excludingId);
}
async createForUser(
userId: string,
input: C2sTunnelPresetCreateInput,
): Promise<C2sTunnelPresetRecord> {
const [created] = await this.context.drizzle
.insert(c2sTunnelPresets)
.values({
userId,
name: input.name,
config: input.config,
platform: input.platform ?? null,
computerName: input.computerName ?? null,
})
.returning();
await this.afterWrite();
return created;
}
async updateForUser(
userId: string,
id: number,
updates: C2sTunnelPresetUpdateInput,
): Promise<C2sTunnelPresetRecord | null> {
const [updated] = await this.context.drizzle
.update(c2sTunnelPresets)
.set({
...updates,
updatedAt: sql`CURRENT_TIMESTAMP`,
})
.where(
and(eq(c2sTunnelPresets.id, id), eq(c2sTunnelPresets.userId, userId)),
)
.returning();
if (updated) {
await this.afterWrite();
}
return updated ?? null;
}
async deleteForUser(userId: string, id: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(c2sTunnelPresets)
.where(
and(eq(c2sTunnelPresets.id, id), eq(c2sTunnelPresets.userId, userId)),
)
.returning({ id: c2sTunnelPresets.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(c2sTunnelPresets)
.where(eq(c2sTunnelPresets.userId, userId))
.returning({ id: c2sTunnelPresets.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,161 @@
import { and, desc, eq, inArray, sql } from "drizzle-orm";
import { commandHistory } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type CommandHistoryRecord = typeof commandHistory.$inferSelect;
export class CommandHistoryRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async create(
userId: string,
hostId: number,
command: string,
executedAt = new Date().toISOString(),
): Promise<CommandHistoryRecord> {
const [created] = await this.context.drizzle
.insert(commandHistory)
.values({ userId, hostId, command, executedAt })
.returning();
await this.afterWrite();
return created;
}
async listUniqueCommandsForHost(
userId: string,
hostId: number,
limit = 500,
): Promise<string[]> {
const rows = await this.context.drizzle
.select({
command: commandHistory.command,
maxExecutedAt: sql<number>`MAX(${commandHistory.executedAt})`,
})
.from(commandHistory)
.where(
and(
eq(commandHistory.userId, userId),
eq(commandHistory.hostId, hostId),
),
)
.groupBy(commandHistory.command)
.orderBy(desc(sql`MAX(${commandHistory.executedAt})`))
.limit(limit);
return rows.map((row) => row.command);
}
async listCommandsForHost(
userId: string,
hostId: number,
limit = 200,
): Promise<string[]> {
const rows = await this.context.drizzle
.select({
id: commandHistory.id,
command: commandHistory.command,
})
.from(commandHistory)
.where(
and(
eq(commandHistory.userId, userId),
eq(commandHistory.hostId, hostId),
),
)
.orderBy(desc(commandHistory.executedAt))
.limit(limit);
return rows.map((row) => row.command);
}
async deleteCommandForHost(
userId: string,
hostId: number,
command: string,
): Promise<number> {
const rows = await this.context.drizzle
.delete(commandHistory)
.where(
and(
eq(commandHistory.userId, userId),
eq(commandHistory.hostId, hostId),
eq(commandHistory.command, command),
),
)
.returning({ id: commandHistory.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByUserAndHost(userId: string, hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(commandHistory)
.where(
and(
eq(commandHistory.userId, userId),
eq(commandHistory.hostId, hostId),
),
)
.returning({ id: commandHistory.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByHostId(hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(commandHistory)
.where(eq(commandHistory.hostId, hostId))
.returning({ id: commandHistory.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByHostIds(hostIds: number[]): Promise<number> {
if (hostIds.length === 0) {
return 0;
}
const rows = await this.context.drizzle
.delete(commandHistory)
.where(inArray(commandHistory.hostId, hostIds))
.returning({ id: commandHistory.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(commandHistory)
.where(eq(commandHistory.userId, userId))
.returning({ id: commandHistory.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,307 @@
import { and, desc, eq, sql } from "drizzle-orm";
import { sshCredentials, sshCredentialUsage } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
import { DataCrypto } from "../../utils/data-crypto.js";
export type CredentialRecord = typeof sshCredentials.$inferSelect;
export type NewCredentialRecord = typeof sshCredentials.$inferInsert;
export type CredentialUpdate = Partial<
Omit<NewCredentialRecord, "id" | "userId">
>;
export class CredentialRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async create(credential: NewCredentialRecord): Promise<CredentialRecord> {
const rows = await this.context.drizzle
.insert(sshCredentials)
.values(credential)
.returning();
await this.afterWrite();
return rows[0];
}
async createEncryptedForUser(
userId: string,
credential: NewCredentialRecord | Record<string, unknown>,
): Promise<CredentialRecord> {
const userDataKey = DataCrypto.validateUserAccess(userId);
const tempId = credential.id ?? Date.now();
const dataWithTempId = { ...credential, id: tempId };
const encryptedCredential = this.encryptCredentialRecordForWrite(
dataWithTempId,
userId,
userDataKey,
);
if (!credential.id) {
delete (encryptedCredential as Partial<NewCredentialRecord>).id;
}
const rows = await this.context.drizzle
.insert(sshCredentials)
.values(encryptedCredential as NewCredentialRecord)
.returning();
await this.afterWrite();
return DataCrypto.decryptRecord(
"ssh_credentials",
rows[0],
userId,
userDataKey,
);
}
async findByIdForUser(
userId: string,
credentialId: number,
): Promise<CredentialRecord | null> {
const rows = await this.context.drizzle
.select()
.from(sshCredentials)
.where(
and(
eq(sshCredentials.id, credentialId),
eq(sshCredentials.userId, userId),
),
)
.limit(1);
return rows[0] ?? null;
}
async findById(credentialId: number): Promise<CredentialRecord | null> {
const rows = await this.context.drizzle
.select()
.from(sshCredentials)
.where(eq(sshCredentials.id, credentialId))
.limit(1);
return rows[0] ?? null;
}
async listByUserId(userId: string): Promise<CredentialRecord[]> {
return this.context.drizzle
.select()
.from(sshCredentials)
.where(eq(sshCredentials.userId, userId))
.orderBy(desc(sshCredentials.updatedAt));
}
async existsForImportIdentity(
userId: string,
name: string,
username: string | null,
): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: sshCredentials.id })
.from(sshCredentials)
.where(
and(
eq(sshCredentials.userId, userId),
eq(sshCredentials.name, name),
eq(sshCredentials.username, username),
),
)
.limit(1);
return rows.length > 0;
}
async findDecryptedByIdForUser(
userId: string,
credentialId: number,
): Promise<CredentialRecord | null> {
const row = await this.findByIdForUser(userId, credentialId);
return this.decryptOne(row, userId);
}
async listDecryptedByUserId(userId: string): Promise<CredentialRecord[]> {
const rows = await this.listByUserId(userId);
return this.decryptMany(rows, userId);
}
async listFolders(userId: string): Promise<string[]> {
const rows = await this.context.drizzle
.select({ folder: sshCredentials.folder })
.from(sshCredentials)
.where(eq(sshCredentials.userId, userId));
return [...new Set(rows.map((row) => row.folder).filter(Boolean))].sort();
}
async renameFolder(
userId: string,
oldName: string,
newName: string,
): Promise<number> {
const rows = await this.context.drizzle
.update(sshCredentials)
.set({ folder: newName })
.where(
and(
eq(sshCredentials.userId, userId),
eq(sshCredentials.folder, oldName),
),
)
.returning({ id: sshCredentials.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async updateForUser(
userId: string,
credentialId: number,
update: CredentialUpdate,
): Promise<CredentialRecord | null> {
const rows = await this.context.drizzle
.update(sshCredentials)
.set(update)
.where(
and(
eq(sshCredentials.id, credentialId),
eq(sshCredentials.userId, userId),
),
)
.returning();
await this.afterWrite();
return rows[0] ?? null;
}
async updateEncryptedForUser(
userId: string,
credentialId: number,
update: CredentialUpdate,
): Promise<CredentialRecord | null> {
const userDataKey = DataCrypto.validateUserAccess(userId);
const encryptedUpdate = this.encryptCredentialRecordForWrite(
update,
userId,
userDataKey,
);
const rows = await this.context.drizzle
.update(sshCredentials)
.set(encryptedUpdate)
.where(
and(
eq(sshCredentials.id, credentialId),
eq(sshCredentials.userId, userId),
),
)
.returning();
await this.afterWrite();
return this.decryptOne(rows[0] ?? null, userId);
}
async deleteForUser(userId: string, credentialId: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(sshCredentials)
.where(
and(
eq(sshCredentials.id, credentialId),
eq(sshCredentials.userId, userId),
),
)
.returning({ id: sshCredentials.id });
await this.afterWrite();
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(sshCredentials)
.where(eq(sshCredentials.userId, userId))
.returning({ id: sshCredentials.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async recordUsage(
userId: string,
credentialId: number,
hostId: number,
usedAt = new Date().toISOString(),
): Promise<void> {
await this.context.drizzle.insert(sshCredentialUsage).values({
credentialId,
hostId,
userId,
usedAt,
});
await this.context.drizzle
.update(sshCredentials)
.set({
lastUsed: usedAt,
usageCount: sql`${sshCredentials.usageCount} + 1`,
})
.where(
and(
eq(sshCredentials.id, credentialId),
eq(sshCredentials.userId, userId),
),
);
await this.afterWrite();
}
private decryptOne<T extends Record<string, unknown>>(
record: T | null,
userId: string,
): T | null {
if (!record) return null;
const userDataKey = DataCrypto.getUserDataKey(userId);
if (!userDataKey) return null;
return DataCrypto.decryptRecord(
"ssh_credentials",
record,
userId,
userDataKey,
);
}
private decryptMany<T extends Record<string, unknown>>(
records: T[],
userId: string,
): T[] {
const userDataKey = DataCrypto.getUserDataKey(userId);
if (!userDataKey) return [];
return DataCrypto.decryptRecords(
"ssh_credentials",
records,
userId,
userDataKey,
);
}
private encryptCredentialRecordForWrite<T extends Record<string, unknown>>(
record: T,
userId: string,
userDataKey: Buffer,
): T {
return DataCrypto.encryptRecord(
"ssh_credentials",
record,
userId,
userDataKey,
);
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,129 @@
import { and, asc, eq } from "drizzle-orm";
import { dashboardServiceLinks } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type DashboardServiceLinkRecord =
typeof dashboardServiceLinks.$inferSelect;
export type DashboardServiceLinkUpdate = Partial<{
label: string;
url: string;
}>;
export class DashboardServiceLinkRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listByUserId(userId: string): Promise<DashboardServiceLinkRecord[]> {
return this.context.drizzle
.select()
.from(dashboardServiceLinks)
.where(eq(dashboardServiceLinks.userId, userId))
.orderBy(asc(dashboardServiceLinks.order), asc(dashboardServiceLinks.id));
}
async createForUser(
userId: string,
input: { label: string; url: string },
createdAt = new Date().toISOString(),
): Promise<DashboardServiceLinkRecord> {
const existing = await this.context.drizzle
.select({ order: dashboardServiceLinks.order })
.from(dashboardServiceLinks)
.where(eq(dashboardServiceLinks.userId, userId))
.orderBy(asc(dashboardServiceLinks.order));
const nextOrder =
existing.length > 0 ? existing[existing.length - 1].order + 1 : 0;
const [created] = await this.context.drizzle
.insert(dashboardServiceLinks)
.values({
userId,
label: input.label,
url: input.url,
order: nextOrder,
createdAt,
})
.returning();
await this.afterWrite();
return created;
}
async findByIdForUser(
userId: string,
id: number,
): Promise<DashboardServiceLinkRecord | null> {
const rows = await this.context.drizzle
.select()
.from(dashboardServiceLinks)
.where(
and(
eq(dashboardServiceLinks.id, id),
eq(dashboardServiceLinks.userId, userId),
),
)
.limit(1);
return rows[0] ?? null;
}
async updateForUser(
userId: string,
id: number,
updates: DashboardServiceLinkUpdate,
): Promise<DashboardServiceLinkRecord | null> {
const [updated] = await this.context.drizzle
.update(dashboardServiceLinks)
.set(updates)
.where(
and(
eq(dashboardServiceLinks.id, id),
eq(dashboardServiceLinks.userId, userId),
),
)
.returning();
if (updated) {
await this.afterWrite();
}
return updated ?? null;
}
async deleteForUser(userId: string, id: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(dashboardServiceLinks)
.where(
and(
eq(dashboardServiceLinks.id, id),
eq(dashboardServiceLinks.userId, userId),
),
)
.returning({ id: dashboardServiceLinks.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(dashboardServiceLinks)
.where(eq(dashboardServiceLinks.userId, userId))
.returning({ id: dashboardServiceLinks.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,9 @@
import type { BetterSQLite3Database } from "drizzle-orm/better-sqlite3";
import type { Database as BetterSqliteDatabase } from "better-sqlite3";
import type * as schema from "../db/schema.js";
export interface DatabaseContext {
dialect: "sqlite";
drizzle: BetterSQLite3Database<typeof schema>;
sqlite?: BetterSqliteDatabase;
}
@@ -0,0 +1,108 @@
import { and, eq } from "drizzle-orm";
import { dismissedAlerts } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type DismissedAlertRecord = typeof dismissedAlerts.$inferSelect;
export class DismissedAlertRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listByUserId(userId: string): Promise<DismissedAlertRecord[]> {
return this.context.drizzle
.select()
.from(dismissedAlerts)
.where(eq(dismissedAlerts.userId, userId));
}
async listAlertIdsByUserId(userId: string): Promise<string[]> {
const rows = await this.context.drizzle
.select({ alertId: dismissedAlerts.alertId })
.from(dismissedAlerts)
.where(eq(dismissedAlerts.userId, userId));
return rows.map((row) => row.alertId);
}
async findForUser(
userId: string,
alertId: string,
): Promise<DismissedAlertRecord | null> {
const rows = await this.context.drizzle
.select()
.from(dismissedAlerts)
.where(
and(
eq(dismissedAlerts.userId, userId),
eq(dismissedAlerts.alertId, alertId),
),
)
.limit(1);
return rows[0] ?? null;
}
async create(userId: string, alertId: string): Promise<void> {
await this.context.drizzle.insert(dismissedAlerts).values({
userId,
alertId,
});
await this.afterWrite();
}
async createForImport(
userId: string,
alertId: string,
dismissedAt = new Date().toISOString(),
): Promise<boolean> {
const existing = await this.findForUser(userId, alertId);
if (existing) {
return false;
}
await this.context.drizzle.insert(dismissedAlerts).values({
userId,
alertId,
dismissedAt,
});
await this.afterWrite();
return true;
}
async deleteForUser(userId: string, alertId: string): Promise<boolean> {
const rows = await this.context.drizzle
.delete(dismissedAlerts)
.where(
and(
eq(dismissedAlerts.userId, userId),
eq(dismissedAlerts.alertId, alertId),
),
)
.returning({ id: dismissedAlerts.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(dismissedAlerts)
.where(eq(dismissedAlerts.userId, userId))
.returning({ id: dismissedAlerts.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,356 @@
import { DatabaseSaveTrigger } from "../../utils/database-save-trigger.js";
import { getDb, getSqlite } from "../db/index.js";
import type { DatabaseContext } from "./database-context.js";
import { WebauthnCredentialRepository } from "./webauthn-credential-repository.js";
import { AlertRepository } from "./alert-repository.js";
import { ApiKeyRepository } from "./api-key-repository.js";
import { AuditLogRepository } from "./audit-log-repository.js";
import { C2sTunnelPresetRepository } from "./c2s-tunnel-preset-repository.js";
import { CommandHistoryRepository } from "./command-history-repository.js";
import { CredentialRepository } from "./credential-repository.js";
import { DashboardServiceLinkRepository } from "./dashboard-service-link-repository.js";
import { DismissedAlertRepository } from "./dismissed-alert-repository.js";
import { FileManagerBookmarkRepository } from "./file-manager-bookmark-repository.js";
import { HomepageItemRepository } from "./homepage-item-repository.js";
import { HomepageLayoutRepository } from "./homepage-layout-repository.js";
import { HostFolderRepository } from "./host-folder-repository.js";
import { HostHealthRepository } from "./host-health-repository.js";
import { HostMetricsHistoryRepository } from "./host-metrics-history-repository.js";
import { HostMetricsPreferenceRepository } from "./host-metrics-preference-repository.js";
import { HostRepository } from "./host-repository.js";
import { HostResolutionRepository } from "./host-resolution-repository.js";
import { NetworkTopologyRepository } from "./network-topology-repository.js";
import { OpenTabRepository } from "./open-tab-repository.js";
import { OpksshTokenRepository } from "./opkssh-token-repository.js";
import { RbacAccessRepository } from "./rbac-access-repository.js";
import { RecentActivityRepository } from "./recent-activity-repository.js";
import { RoleRepository } from "./role-repository.js";
import { SessionRecordingRepository } from "./session-recording-repository.js";
import { SessionRepository } from "./session-repository.js";
import { SettingsRepository } from "./settings-repository.js";
import { SharedHostSecretsRepository } from "./shared-host-secrets-repository.js";
import { SnippetRepository } from "./snippet-repository.js";
import { SshCredentialUsageRepository } from "./ssh-credential-usage-repository.js";
import { SsoProviderRepository } from "./sso-provider-repository.js";
import { TermixIdentityCaRepository } from "./termix-identity-ca-repository.js";
import { TermixIdentityRepository } from "./termix-identity-repository.js";
import { TmuxSessionTagRepository } from "./tmux-session-tag-repository.js";
import { TransferRecentRepository } from "./transfer-recent-repository.js";
import { TrustedDeviceRepository } from "./trusted-device-repository.js";
import { UserDataExportRepository } from "./user-data-export-repository.js";
import { UserPreferenceRepository } from "./user-preference-repository.js";
import { UserRepository } from "./user-repository.js";
import { VaultProfileRepository } from "./vault-profile-repository.js";
import { VaultTokenRepository } from "./vault-token-repository.js";
export function createCurrentRepositoryContext(): DatabaseContext {
return {
dialect: "sqlite",
drizzle: getDb(),
sqlite: getSqlite(),
};
}
export function createCurrentRepositoryWriteHook(
reason: string,
): () => Promise<void> {
return () => DatabaseSaveTrigger.forceSave(reason);
}
export function getCurrentRepositorySqlite() {
return getSqlite();
}
export function getCurrentSettingValue(key: string): string | null {
const row = getCurrentRepositorySqlite()
.prepare("SELECT value FROM settings WHERE key = ?")
.get(key) as { value?: string } | undefined;
return row?.value ?? null;
}
export function createCurrentWebauthnCredentialRepository(): WebauthnCredentialRepository {
return new WebauthnCredentialRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("webauthn_credential_repository_write"),
);
}
export function createCurrentAlertRepository(): AlertRepository {
return new AlertRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("alert_repository_write"),
);
}
export function createCurrentApiKeyRepository(): ApiKeyRepository {
return new ApiKeyRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("api_key_repository_write"),
);
}
export function createCurrentAuditLogRepository(): AuditLogRepository {
return new AuditLogRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("audit_log_repository_write"),
);
}
export function createCurrentC2sTunnelPresetRepository(): C2sTunnelPresetRepository {
return new C2sTunnelPresetRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("c2s_tunnel_preset_repository_write"),
);
}
export function createCurrentCommandHistoryRepository(): CommandHistoryRepository {
return new CommandHistoryRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("command_history_repository_write"),
);
}
export function createCurrentCredentialRepository(): CredentialRepository {
return new CredentialRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("credential_repository_write"),
);
}
export function createCurrentDashboardServiceLinkRepository(): DashboardServiceLinkRepository {
return new DashboardServiceLinkRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("dashboard_service_link_repository_write"),
);
}
export function createCurrentDismissedAlertRepository(): DismissedAlertRepository {
return new DismissedAlertRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("dismissed_alert_repository_write"),
);
}
export function createCurrentFileManagerBookmarkRepository(): FileManagerBookmarkRepository {
return new FileManagerBookmarkRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("file_manager_bookmarks_repository_write"),
);
}
export function createCurrentHomepageItemRepository(): HomepageItemRepository {
return new HomepageItemRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("homepage_item_repository_write"),
);
}
export function createCurrentHomepageLayoutRepository(): HomepageLayoutRepository {
return new HomepageLayoutRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("homepage_layout_repository_write"),
);
}
export function createCurrentHostFolderRepository(): HostFolderRepository {
return new HostFolderRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("host_folder_repository_write"),
);
}
export function createCurrentHostHealthRepository(): HostHealthRepository {
return new HostHealthRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("host_health_repository_write"),
);
}
export function createCurrentHostMetricsHistoryRepository(): HostMetricsHistoryRepository {
return new HostMetricsHistoryRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("host_metrics_history_repository_write"),
);
}
export function createCurrentHostMetricsPreferenceRepository(): HostMetricsPreferenceRepository {
return new HostMetricsPreferenceRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook(
"host_metrics_preference_repository_write",
),
);
}
export function createCurrentHostRepository(): HostRepository {
return new HostRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("host_repository_write"),
);
}
export function createCurrentHostResolutionRepository(): HostResolutionRepository {
return new HostResolutionRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("host_resolution_repository_write"),
);
}
export function createCurrentNetworkTopologyRepository(): NetworkTopologyRepository {
return new NetworkTopologyRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("network_topology_repository_write"),
);
}
export function createCurrentOpenTabRepository(): OpenTabRepository {
return new OpenTabRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("open_tab_repository_write"),
);
}
export function createCurrentOpksshTokenRepository(): OpksshTokenRepository {
return new OpksshTokenRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("opkssh_token_repository_write"),
);
}
export function createCurrentRbacAccessRepository(): RbacAccessRepository {
return new RbacAccessRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("rbac_access_repository_write"),
);
}
export function createCurrentRecentActivityRepository(): RecentActivityRepository {
return new RecentActivityRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("recent_activity_repository_write"),
);
}
export function createCurrentRoleRepository(): RoleRepository {
return new RoleRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("role_repository_write"),
);
}
export function createCurrentSessionRecordingRepository(): SessionRecordingRepository {
return new SessionRecordingRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("session_recording_repository_write"),
);
}
export function createCurrentSessionRepository(): SessionRepository {
return new SessionRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("session_repository_write"),
);
}
export function createCurrentSettingsRepository(): SettingsRepository {
return new SettingsRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("settings_repository_write"),
);
}
export function createCurrentSharedHostSecretsRepository(): SharedHostSecretsRepository {
return new SharedHostSecretsRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("shared_host_secrets_repository_write"),
);
}
export function createCurrentSnippetRepository(): SnippetRepository {
return new SnippetRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("snippet_repository_write"),
);
}
export function createCurrentSshCredentialUsageRepository(): SshCredentialUsageRepository {
return new SshCredentialUsageRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("ssh_credential_usage_repository_write"),
);
}
export function createCurrentSsoProviderRepository(): SsoProviderRepository {
return new SsoProviderRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("sso_provider_repository_write"),
);
}
export function createCurrentTermixIdentityCaRepository(): TermixIdentityCaRepository {
return new TermixIdentityCaRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("termix_identity_ca_repository_write"),
);
}
export function createCurrentTermixIdentityRepository(): TermixIdentityRepository {
return new TermixIdentityRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("termix_identity_repository_write"),
);
}
export function createCurrentTmuxSessionTagRepository(): TmuxSessionTagRepository {
return new TmuxSessionTagRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("tmux_session_tag_repository_write"),
);
}
export function createCurrentTransferRecentRepository(): TransferRecentRepository {
return new TransferRecentRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("transfer_recent_repository_write"),
);
}
export function createCurrentTrustedDeviceRepository(): TrustedDeviceRepository {
return new TrustedDeviceRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("trusted_device_repository_write"),
);
}
export function createCurrentUserDataExportRepository(): UserDataExportRepository {
return new UserDataExportRepository(createCurrentRepositoryContext());
}
export function createCurrentUserPreferenceRepository(): UserPreferenceRepository {
return new UserPreferenceRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("user_preference_repository_write"),
);
}
export function createCurrentUserRepository(): UserRepository {
return new UserRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("user_repository_write"),
);
}
export function createCurrentVaultProfileRepository(): VaultProfileRepository {
return new VaultProfileRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("vault_profile_repository_write"),
);
}
export function createCurrentVaultTokenRepository(): VaultTokenRepository {
return new VaultTokenRepository(
createCurrentRepositoryContext(),
createCurrentRepositoryWriteHook("vault_token_repository_write"),
);
}
@@ -0,0 +1,158 @@
import { FieldCrypto } from "../../utils/field-crypto.js";
import { LazyFieldEncryption } from "../../utils/lazy-field-encryption.js";
const FIELD_ENCRYPTION_POLICY = {
users: {
sensitive: new Set([
"passwordHash",
"clientSecret",
"totpSecret",
"totpBackupCodes",
"oidcIdentifier",
]),
plaintext: new Set(["id", "username", "isAdmin", "isOidc"]),
},
ssh_data: {
sensitive: new Set([
"password",
"key",
"keyPassword",
"sudoPassword",
"autostartPassword",
"autostartKey",
"autostartKeyPassword",
"socks5Password",
"rdpPassword",
"vncPassword",
"telnetPassword",
]),
plaintext: new Set([
"id",
"userId",
"connectionType",
"name",
"ip",
"port",
"username",
"folder",
"tags",
"authType",
"credentialId",
]),
},
ssh_credentials: {
sensitive: new Set([
"password",
"key",
"privateKey",
"publicKey",
"keyPassword",
]),
plaintext: new Set([
"id",
"userId",
"name",
"description",
"folder",
"tags",
"authType",
"username",
"keyType",
"detectedKeyType",
"usageCount",
"lastUsed",
]),
},
opkssh_tokens: {
sensitive: new Set(["sshCert", "privateKey"]),
plaintext: new Set(["id", "userId", "hostId", "createdAt", "expiresAt"]),
},
termix_identity_ca: {
sensitive: new Set(["privateKey"]),
plaintext: new Set(["id", "publicKey", "createdAt", "updatedAt"]),
},
vault_tokens: {
sensitive: new Set(["sshCert", "privateKey"]),
plaintext: new Set(["id", "userId", "profileId", "expiresAt"]),
},
} as const;
type PolicyTable = keyof typeof FIELD_ENCRYPTION_POLICY;
export type FieldClassification = "sensitive" | "plaintext" | "unknown";
export class FieldEncryptionBoundary {
static classifyField(
tableName: string,
fieldName: string,
): FieldClassification {
const policy = this.getPolicy(tableName);
if (!policy) return "unknown";
if (policy.sensitive.has(fieldName)) return "sensitive";
if (policy.plaintext.has(fieldName)) return "plaintext";
return "unknown";
}
static getSensitiveFields(tableName: string): string[] {
const policy = this.getPolicy(tableName);
return policy ? [...policy.sensitive].sort() : [];
}
static encryptRecord<T extends Record<string, unknown>>(
tableName: string,
record: T,
userDataKey: Buffer,
recordId = record.id,
): T {
const id = this.requireRecordId(recordId);
const encryptedRecord: Record<string, unknown> = { ...record };
for (const fieldName of this.getSensitiveFields(tableName)) {
const value = encryptedRecord[fieldName];
if (typeof value === "string" && value) {
encryptedRecord[fieldName] = FieldCrypto.encryptField(
value,
userDataKey,
id,
fieldName,
);
}
}
return encryptedRecord as T;
}
static decryptRecord<T extends Record<string, unknown>>(
tableName: string,
record: T,
userDataKey: Buffer,
recordId = record.id,
): T {
const id = this.requireRecordId(recordId);
const decryptedRecord: Record<string, unknown> = { ...record };
for (const fieldName of this.getSensitiveFields(tableName)) {
const value = decryptedRecord[fieldName];
if (typeof value === "string" && value) {
decryptedRecord[fieldName] = LazyFieldEncryption.safeGetFieldValue(
value,
userDataKey,
id,
fieldName,
);
}
}
return decryptedRecord as T;
}
private static getPolicy(tableName: string) {
return FIELD_ENCRYPTION_POLICY[tableName as PolicyTable];
}
private static requireRecordId(recordId: unknown): string {
if (recordId === null || recordId === undefined || recordId === "") {
throw new Error("Field encryption requires a stable record id.");
}
return String(recordId);
}
}
@@ -0,0 +1,533 @@
import { and, desc, eq, inArray } from "drizzle-orm";
import {
fileManagerPinned,
fileManagerRecent,
fileManagerShortcuts,
} from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type FileManagerRecentRecord = typeof fileManagerRecent.$inferSelect;
export type FileManagerPinnedRecord = typeof fileManagerPinned.$inferSelect;
export type FileManagerShortcutRecord =
typeof fileManagerShortcuts.$inferSelect;
export interface FileManagerBookmarkInput {
hostId: number;
path: string;
name?: string | null;
}
function resolveBookmarkName(path: string, name?: string | null): string {
return name || path.split("/").pop() || "Unknown";
}
export class FileManagerBookmarkRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listRecentForHost(
userId: string,
hostId: number,
limit = 20,
): Promise<FileManagerRecentRecord[]> {
return this.context.drizzle
.select()
.from(fileManagerRecent)
.where(
and(
eq(fileManagerRecent.userId, userId),
eq(fileManagerRecent.hostId, hostId),
),
)
.orderBy(desc(fileManagerRecent.lastOpened))
.limit(limit);
}
async listRecentByUserId(userId: string): Promise<FileManagerRecentRecord[]> {
return this.context.drizzle
.select()
.from(fileManagerRecent)
.where(eq(fileManagerRecent.userId, userId));
}
async upsertRecent(
userId: string,
input: FileManagerBookmarkInput,
lastOpened = new Date().toISOString(),
): Promise<void> {
const [existing] = await this.context.drizzle
.select({ id: fileManagerRecent.id })
.from(fileManagerRecent)
.where(
and(
eq(fileManagerRecent.userId, userId),
eq(fileManagerRecent.hostId, input.hostId),
eq(fileManagerRecent.path, input.path),
),
)
.limit(1);
if (existing) {
await this.context.drizzle
.update(fileManagerRecent)
.set({ lastOpened })
.where(eq(fileManagerRecent.id, existing.id));
} else {
await this.context.drizzle.insert(fileManagerRecent).values({
userId,
hostId: input.hostId,
path: input.path,
name: resolveBookmarkName(input.path, input.name),
lastOpened,
});
}
await this.afterWrite();
}
async createRecentForImport(
userId: string,
input: FileManagerBookmarkInput,
lastOpened = new Date().toISOString(),
): Promise<boolean> {
const exists = await this.existsRecentImportItem(userId, input);
if (exists) {
return false;
}
await this.context.drizzle.insert(fileManagerRecent).values({
userId,
hostId: input.hostId,
path: input.path,
name: resolveBookmarkName(input.path, input.name),
lastOpened,
});
await this.afterWrite();
return true;
}
async deleteRecentForHostPath(
userId: string,
input: Pick<FileManagerBookmarkInput, "hostId" | "path">,
): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerRecent)
.where(
and(
eq(fileManagerRecent.userId, userId),
eq(fileManagerRecent.hostId, input.hostId),
eq(fileManagerRecent.path, input.path),
),
)
.returning({ id: fileManagerRecent.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async listPinnedForHost(
userId: string,
hostId: number,
): Promise<FileManagerPinnedRecord[]> {
return this.context.drizzle
.select()
.from(fileManagerPinned)
.where(
and(
eq(fileManagerPinned.userId, userId),
eq(fileManagerPinned.hostId, hostId),
),
)
.orderBy(desc(fileManagerPinned.pinnedAt));
}
async listPinnedByUserId(userId: string): Promise<FileManagerPinnedRecord[]> {
return this.context.drizzle
.select()
.from(fileManagerPinned)
.where(eq(fileManagerPinned.userId, userId));
}
async createPinned(
userId: string,
input: FileManagerBookmarkInput,
pinnedAt = new Date().toISOString(),
): Promise<boolean> {
const exists = await this.existsPinned(userId, input.hostId, input.path);
if (exists) {
return false;
}
await this.context.drizzle.insert(fileManagerPinned).values({
userId,
hostId: input.hostId,
path: input.path,
name: resolveBookmarkName(input.path, input.name),
pinnedAt,
});
await this.afterWrite();
return true;
}
async createPinnedForImport(
userId: string,
input: FileManagerBookmarkInput,
pinnedAt = new Date().toISOString(),
): Promise<boolean> {
const exists = await this.existsPinnedImportItem(userId, input);
if (exists) {
return false;
}
await this.context.drizzle.insert(fileManagerPinned).values({
userId,
hostId: input.hostId,
path: input.path,
name: resolveBookmarkName(input.path, input.name),
pinnedAt,
});
await this.afterWrite();
return true;
}
async deletePinnedForHostPath(
userId: string,
input: Pick<FileManagerBookmarkInput, "hostId" | "path">,
): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerPinned)
.where(
and(
eq(fileManagerPinned.userId, userId),
eq(fileManagerPinned.hostId, input.hostId),
eq(fileManagerPinned.path, input.path),
),
)
.returning({ id: fileManagerPinned.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async listShortcutsForHost(
userId: string,
hostId: number,
): Promise<FileManagerShortcutRecord[]> {
return this.context.drizzle
.select()
.from(fileManagerShortcuts)
.where(
and(
eq(fileManagerShortcuts.userId, userId),
eq(fileManagerShortcuts.hostId, hostId),
),
)
.orderBy(desc(fileManagerShortcuts.createdAt));
}
async listShortcutsByUserId(
userId: string,
): Promise<FileManagerShortcutRecord[]> {
return this.context.drizzle
.select()
.from(fileManagerShortcuts)
.where(eq(fileManagerShortcuts.userId, userId));
}
async createShortcut(
userId: string,
input: FileManagerBookmarkInput,
createdAt = new Date().toISOString(),
): Promise<boolean> {
const exists = await this.existsShortcut(userId, input.hostId, input.path);
if (exists) {
return false;
}
await this.context.drizzle.insert(fileManagerShortcuts).values({
userId,
hostId: input.hostId,
path: input.path,
name: resolveBookmarkName(input.path, input.name),
createdAt,
});
await this.afterWrite();
return true;
}
async createShortcutForImport(
userId: string,
input: FileManagerBookmarkInput,
createdAt = new Date().toISOString(),
): Promise<boolean> {
const exists = await this.existsShortcutImportItem(userId, input);
if (exists) {
return false;
}
await this.context.drizzle.insert(fileManagerShortcuts).values({
userId,
hostId: input.hostId,
path: input.path,
name: resolveBookmarkName(input.path, input.name),
createdAt,
});
await this.afterWrite();
return true;
}
async deleteShortcutForHostPath(
userId: string,
input: Pick<FileManagerBookmarkInput, "hostId" | "path">,
): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerShortcuts)
.where(
and(
eq(fileManagerShortcuts.userId, userId),
eq(fileManagerShortcuts.hostId, input.hostId),
eq(fileManagerShortcuts.path, input.path),
),
)
.returning({ id: fileManagerShortcuts.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByUserId(userId: string): Promise<number> {
const total =
(await this.deleteRecentByUserId(userId)) +
(await this.deletePinnedByUserId(userId)) +
(await this.deleteShortcutsByUserId(userId));
if (total > 0) {
await this.afterWrite();
}
return total;
}
async deleteByHostId(hostId: number): Promise<number> {
const total =
(await this.deleteRecentByHostId(hostId)) +
(await this.deletePinnedByHostId(hostId)) +
(await this.deleteShortcutsByHostId(hostId));
if (total > 0) {
await this.afterWrite();
}
return total;
}
async deleteByHostIds(hostIds: number[]): Promise<number> {
if (hostIds.length === 0) {
return 0;
}
const total =
(await this.deleteRecentByHostIds(hostIds)) +
(await this.deletePinnedByHostIds(hostIds)) +
(await this.deleteShortcutsByHostIds(hostIds));
if (total > 0) {
await this.afterWrite();
}
return total;
}
private async existsPinned(
userId: string,
hostId: number,
path: string,
): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: fileManagerPinned.id })
.from(fileManagerPinned)
.where(
and(
eq(fileManagerPinned.userId, userId),
eq(fileManagerPinned.hostId, hostId),
eq(fileManagerPinned.path, path),
),
)
.limit(1);
return rows.length > 0;
}
private async existsRecentImportItem(
userId: string,
input: FileManagerBookmarkInput,
): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: fileManagerRecent.id })
.from(fileManagerRecent)
.where(
and(
eq(fileManagerRecent.userId, userId),
eq(fileManagerRecent.path, input.path),
eq(
fileManagerRecent.name,
resolveBookmarkName(input.path, input.name),
),
),
)
.limit(1);
return rows.length > 0;
}
private async existsPinnedImportItem(
userId: string,
input: FileManagerBookmarkInput,
): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: fileManagerPinned.id })
.from(fileManagerPinned)
.where(
and(
eq(fileManagerPinned.userId, userId),
eq(fileManagerPinned.path, input.path),
eq(
fileManagerPinned.name,
resolveBookmarkName(input.path, input.name),
),
),
)
.limit(1);
return rows.length > 0;
}
private async existsShortcutImportItem(
userId: string,
input: FileManagerBookmarkInput,
): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: fileManagerShortcuts.id })
.from(fileManagerShortcuts)
.where(
and(
eq(fileManagerShortcuts.userId, userId),
eq(fileManagerShortcuts.path, input.path),
eq(
fileManagerShortcuts.name,
resolveBookmarkName(input.path, input.name),
),
),
)
.limit(1);
return rows.length > 0;
}
private async existsShortcut(
userId: string,
hostId: number,
path: string,
): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: fileManagerShortcuts.id })
.from(fileManagerShortcuts)
.where(
and(
eq(fileManagerShortcuts.userId, userId),
eq(fileManagerShortcuts.hostId, hostId),
eq(fileManagerShortcuts.path, path),
),
)
.limit(1);
return rows.length > 0;
}
private async deleteRecentByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerRecent)
.where(eq(fileManagerRecent.userId, userId))
.returning({ id: fileManagerRecent.id });
return rows.length;
}
private async deletePinnedByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerPinned)
.where(eq(fileManagerPinned.userId, userId))
.returning({ id: fileManagerPinned.id });
return rows.length;
}
private async deleteShortcutsByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerShortcuts)
.where(eq(fileManagerShortcuts.userId, userId))
.returning({ id: fileManagerShortcuts.id });
return rows.length;
}
private async deleteRecentByHostId(hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerRecent)
.where(eq(fileManagerRecent.hostId, hostId))
.returning({ id: fileManagerRecent.id });
return rows.length;
}
private async deletePinnedByHostId(hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerPinned)
.where(eq(fileManagerPinned.hostId, hostId))
.returning({ id: fileManagerPinned.id });
return rows.length;
}
private async deleteShortcutsByHostId(hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerShortcuts)
.where(eq(fileManagerShortcuts.hostId, hostId))
.returning({ id: fileManagerShortcuts.id });
return rows.length;
}
private async deleteRecentByHostIds(hostIds: number[]): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerRecent)
.where(inArray(fileManagerRecent.hostId, hostIds))
.returning({ id: fileManagerRecent.id });
return rows.length;
}
private async deletePinnedByHostIds(hostIds: number[]): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerPinned)
.where(inArray(fileManagerPinned.hostId, hostIds))
.returning({ id: fileManagerPinned.id });
return rows.length;
}
private async deleteShortcutsByHostIds(hostIds: number[]): Promise<number> {
const rows = await this.context.drizzle
.delete(fileManagerShortcuts)
.where(inArray(fileManagerShortcuts.hostId, hostIds))
.returning({ id: fileManagerShortcuts.id });
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,114 @@
import { and, asc, eq } from "drizzle-orm";
import { homepageItems } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type HomepageItemRecord = typeof homepageItems.$inferSelect;
export interface HomepageItemCreateInput {
typeId: string;
title: string | null;
config: string;
}
export type HomepageItemUpdateInput = Partial<{
title: string | null;
config: string;
}>;
export class HomepageItemRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listByUserId(userId: string): Promise<HomepageItemRecord[]> {
return this.context.drizzle
.select()
.from(homepageItems)
.where(eq(homepageItems.userId, userId))
.orderBy(asc(homepageItems.id));
}
async createForUser(
userId: string,
input: HomepageItemCreateInput,
now = new Date().toISOString(),
): Promise<HomepageItemRecord> {
const [created] = await this.context.drizzle
.insert(homepageItems)
.values({
userId,
typeId: input.typeId,
title: input.title,
config: input.config,
createdAt: now,
updatedAt: now,
})
.returning();
await this.afterWrite();
return created;
}
async findByIdForUser(
userId: string,
id: number,
): Promise<HomepageItemRecord | null> {
const rows = await this.context.drizzle
.select()
.from(homepageItems)
.where(and(eq(homepageItems.id, id), eq(homepageItems.userId, userId)))
.limit(1);
return rows[0] ?? null;
}
async updateForUser(
userId: string,
id: number,
updates: HomepageItemUpdateInput,
updatedAt = new Date().toISOString(),
): Promise<HomepageItemRecord | null> {
const [updated] = await this.context.drizzle
.update(homepageItems)
.set({ ...updates, updatedAt })
.where(and(eq(homepageItems.id, id), eq(homepageItems.userId, userId)))
.returning();
if (updated) {
await this.afterWrite();
}
return updated ?? null;
}
async deleteForUser(userId: string, id: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(homepageItems)
.where(and(eq(homepageItems.id, id), eq(homepageItems.userId, userId)))
.returning({ id: homepageItems.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(homepageItems)
.where(eq(homepageItems.userId, userId))
.returning({ id: homepageItems.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,64 @@
import { eq } from "drizzle-orm";
import { homepageLayouts } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type HomepageLayoutRecord = typeof homepageLayouts.$inferSelect;
export class HomepageLayoutRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async findByUserId(userId: string): Promise<HomepageLayoutRecord | null> {
const rows = await this.context.drizzle
.select()
.from(homepageLayouts)
.where(eq(homepageLayouts.userId, userId))
.limit(1);
return rows[0] ?? null;
}
async upsertForUser(
userId: string,
layout: string,
updatedAt = new Date().toISOString(),
): Promise<HomepageLayoutRecord> {
const existing = await this.findByUserId(userId);
if (!existing) {
const [created] = await this.context.drizzle
.insert(homepageLayouts)
.values({ userId, layout, updatedAt })
.returning();
await this.afterWrite();
return created;
}
const [updated] = await this.context.drizzle
.update(homepageLayouts)
.set({ layout, updatedAt })
.where(eq(homepageLayouts.userId, userId))
.returning();
await this.afterWrite();
return updated;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(homepageLayouts)
.where(eq(homepageLayouts.userId, userId))
.returning({ id: homepageLayouts.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,168 @@
import { and, eq, like, or, sql } from "drizzle-orm";
import type { SQLiteColumn } from "drizzle-orm/sqlite-core";
import { hosts, sshCredentials, sshFolders } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type HostFolderRecord = typeof sshFolders.$inferSelect;
export type HostFolderHostRecord = typeof hosts.$inferSelect;
export interface RenameFolderResult {
updatedHosts: number;
updatedCredentials: number;
}
export class HostFolderRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async renameFolder(
userId: string,
oldName: string,
newName: string,
now = new Date().toISOString(),
): Promise<RenameFolderResult> {
const oldPrefix = `${oldName} / `;
const newPrefix = `${newName} / `;
const childLike = `${oldPrefix}%`;
const renameExpr = (col: SQLiteColumn) =>
sql`CASE WHEN ${col} = ${oldName} THEN ${newName} ELSE ${newPrefix} || substr(${col}, ${oldPrefix.length + 1}) END`;
const folderMatch = (col: SQLiteColumn) =>
or(eq(col, oldName), like(col, childLike));
const updatedHosts = await this.context.drizzle
.update(hosts)
.set({ folder: renameExpr(hosts.folder), updatedAt: now })
.where(and(eq(hosts.userId, userId), folderMatch(hosts.folder)))
.returning({ id: hosts.id });
const updatedCredentials = await this.context.drizzle
.update(sshCredentials)
.set({ folder: renameExpr(sshCredentials.folder), updatedAt: now })
.where(
and(
eq(sshCredentials.userId, userId),
folderMatch(sshCredentials.folder),
),
)
.returning({ id: sshCredentials.id });
await this.context.drizzle
.update(sshFolders)
.set({ name: renameExpr(sshFolders.name), updatedAt: now })
.where(and(eq(sshFolders.userId, userId), folderMatch(sshFolders.name)));
await this.afterWrite();
return {
updatedHosts: updatedHosts.length,
updatedCredentials: updatedCredentials.length,
};
}
async listFolders(userId: string): Promise<HostFolderRecord[]> {
return this.context.drizzle
.select()
.from(sshFolders)
.where(eq(sshFolders.userId, userId));
}
async upsertMetadata(
userId: string,
name: string,
color: string | null | undefined,
icon: string | null | undefined,
now = new Date().toISOString(),
): Promise<{ folder: HostFolderRecord; created: boolean }> {
const existing = await this.findFolder(userId, name);
if (existing) {
const [updated] = await this.context.drizzle
.update(sshFolders)
.set({ color, icon, updatedAt: now })
.where(and(eq(sshFolders.userId, userId), eq(sshFolders.name, name)))
.returning();
await this.afterWrite();
return { folder: updated, created: false };
}
const [created] = await this.context.drizzle
.insert(sshFolders)
.values({
userId,
name,
color,
icon,
createdAt: now,
updatedAt: now,
})
.returning();
await this.afterWrite();
return { folder: created, created: true };
}
async listHostsInFolder(
userId: string,
folderName: string,
): Promise<HostFolderHostRecord[]> {
const folderMatch = (col: SQLiteColumn) =>
or(eq(col, folderName), like(col, `${folderName} / %`));
return this.context.drizzle
.select()
.from(hosts)
.where(and(eq(hosts.userId, userId), folderMatch(hosts.folder)));
}
async deleteHostsAndFolderRecords(
userId: string,
folderName: string,
): Promise<void> {
const folderMatch = (col: SQLiteColumn) =>
or(eq(col, folderName), like(col, `${folderName} / %`));
const hostsToDelete = await this.listHostsInFolder(userId, folderName);
if (hostsToDelete.length > 0) {
await this.context.drizzle
.delete(hosts)
.where(and(eq(hosts.userId, userId), folderMatch(hosts.folder)));
}
await this.context.drizzle
.delete(sshFolders)
.where(and(eq(sshFolders.userId, userId), folderMatch(sshFolders.name)));
await this.afterWrite();
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(sshFolders)
.where(eq(sshFolders.userId, userId))
.returning({ id: sshFolders.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async findFolder(
userId: string,
name: string,
): Promise<HostFolderRecord | null> {
const rows = await this.context.drizzle
.select()
.from(sshFolders)
.where(and(eq(sshFolders.userId, userId), eq(sshFolders.name, name)))
.limit(1);
return rows[0] ?? null;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,164 @@
import { and, desc, eq } from "drizzle-orm";
import { hostHealthChecks, hostHealthHistory } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type HostHealthCheckRecord = typeof hostHealthChecks.$inferSelect;
export type HostHealthHistoryRecord = typeof hostHealthHistory.$inferSelect;
export interface HostHealthResultInput {
checkId: string;
ok: boolean;
latencyMs: number | null;
detail: string;
}
export class HostHealthRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async findChecksByUserAndHost(
userId: string,
hostId: number,
): Promise<HostHealthCheckRecord | null> {
const rows = await this.context.drizzle
.select()
.from(hostHealthChecks)
.where(
and(
eq(hostHealthChecks.userId, userId),
eq(hostHealthChecks.hostId, hostId),
),
)
.limit(1);
return rows[0] ?? null;
}
async upsertChecks(
userId: string,
hostId: number,
checks: string,
intervalSeconds: number,
now = new Date().toISOString(),
): Promise<HostHealthCheckRecord> {
const existing = await this.findChecksByUserAndHost(userId, hostId);
if (existing) {
const [updated] = await this.context.drizzle
.update(hostHealthChecks)
.set({ checks, intervalSeconds, updatedAt: now })
.where(eq(hostHealthChecks.id, existing.id))
.returning();
await this.afterWrite();
return updated;
}
const [created] = await this.context.drizzle
.insert(hostHealthChecks)
.values({
userId,
hostId,
checks,
intervalSeconds,
createdAt: now,
updatedAt: now,
})
.returning();
await this.afterWrite();
return created;
}
async recordHistory(
userId: string,
hostId: number,
results: HostHealthResultInput[],
keep: number,
now = new Date().toISOString(),
): Promise<number> {
if (results.length === 0) {
return 0;
}
await this.context.drizzle.insert(hostHealthHistory).values(
results.map((result) => ({
userId,
hostId,
checkId: result.checkId,
ts: now,
ok: result.ok,
latencyMs: result.latencyMs,
detail: result.detail,
})),
);
this.pruneHistory(userId, hostId, keep);
await this.afterWrite();
return results.length;
}
async listHistory(
userId: string,
hostId: number,
limit: number,
): Promise<HostHealthHistoryRecord[]> {
return this.context.drizzle
.select()
.from(hostHealthHistory)
.where(
and(
eq(hostHealthHistory.userId, userId),
eq(hostHealthHistory.hostId, hostId),
),
)
.orderBy(desc(hostHealthHistory.ts))
.limit(limit);
}
async deleteByUserId(userId: string): Promise<{
checksDeleted: number;
historyDeleted: number;
}> {
const historyRows = await this.context.drizzle
.delete(hostHealthHistory)
.where(eq(hostHealthHistory.userId, userId))
.returning({ id: hostHealthHistory.id });
const checkRows = await this.context.drizzle
.delete(hostHealthChecks)
.where(eq(hostHealthChecks.userId, userId))
.returning({ id: hostHealthChecks.id });
if (historyRows.length > 0 || checkRows.length > 0) {
await this.afterWrite();
}
return {
checksDeleted: checkRows.length,
historyDeleted: historyRows.length,
};
}
private pruneHistory(userId: string, hostId: number, keep: number): void {
this.context.sqlite
?.prepare(
`DELETE FROM host_health_history
WHERE id IN (
SELECT id FROM host_health_history
WHERE user_id = ? AND host_id = ?
AND id NOT IN (
SELECT id FROM host_health_history
WHERE user_id = ? AND host_id = ?
ORDER BY ts DESC LIMIT ?
)
)`,
)
.run(userId, hostId, userId, hostId, keep);
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,64 @@
import { and, asc, eq, gte, lte } from "drizzle-orm";
import { hostMetricsHistory } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type HostMetricsHistoryRecord = typeof hostMetricsHistory.$inferSelect;
export interface HostMetricsHistoryCreateInput {
hostId: number;
cpuPercent?: number | null;
memPercent?: number | null;
diskPercent?: number | null;
netRxBytes?: number | null;
netTxBytes?: number | null;
}
export class HostMetricsHistoryRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async create(input: HostMetricsHistoryCreateInput): Promise<void> {
await this.context.drizzle.insert(hostMetricsHistory).values({
hostId: input.hostId,
cpuPercent: input.cpuPercent,
memPercent: input.memPercent,
diskPercent: input.diskPercent,
netRxBytes: input.netRxBytes,
netTxBytes: input.netTxBytes,
});
await this.afterWrite();
}
pruneOlderThan(hostId: number, retentionDays: number): void {
this.context.sqlite
?.prepare(
"DELETE FROM host_metrics_history WHERE host_id = ? AND ts < datetime('now', ?)",
)
.run(hostId, `-${retentionDays} days`);
}
async listRange(
hostId: number,
fromTs: string,
toTs: string,
): Promise<HostMetricsHistoryRecord[]> {
return this.context.drizzle
.select()
.from(hostMetricsHistory)
.where(
and(
eq(hostMetricsHistory.hostId, hostId),
gte(hostMetricsHistory.ts, fromTs),
lte(hostMetricsHistory.ts, toTs),
),
)
.orderBy(asc(hostMetricsHistory.ts));
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,97 @@
import { and, eq } from "drizzle-orm";
import { hostMetricsPreferences, hosts } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type HostMetricsPreferenceRecord =
typeof hostMetricsPreferences.$inferSelect;
export class HostMetricsPreferenceRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async findByUserAndHost(
userId: string,
hostId: number,
): Promise<HostMetricsPreferenceRecord | null> {
const rows = await this.context.drizzle
.select()
.from(hostMetricsPreferences)
.where(
and(
eq(hostMetricsPreferences.userId, userId),
eq(hostMetricsPreferences.hostId, hostId),
),
)
.limit(1);
return rows[0] ?? null;
}
async upsertLayout(
userId: string,
hostId: number,
layout: string,
now = new Date().toISOString(),
): Promise<HostMetricsPreferenceRecord> {
const existing = await this.findByUserAndHost(userId, hostId);
if (existing) {
const [updated] = await this.context.drizzle
.update(hostMetricsPreferences)
.set({ layout, updatedAt: now })
.where(eq(hostMetricsPreferences.id, existing.id))
.returning();
await this.afterWrite();
return updated;
}
const [created] = await this.context.drizzle
.insert(hostMetricsPreferences)
.values({
userId,
hostId,
layout,
createdAt: now,
updatedAt: now,
})
.returning();
await this.afterWrite();
return created;
}
async updateHostStatsConfig(
userId: string,
hostId: number,
statsConfig: string,
): Promise<boolean> {
const rows = await this.context.drizzle
.update(hosts)
.set({ statsConfig })
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
.returning({ id: hosts.id });
if (rows.length === 0) return false;
await this.afterWrite();
return true;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(hostMetricsPreferences)
.where(eq(hostMetricsPreferences.userId, userId))
.returning({ id: hostMetricsPreferences.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,265 @@
import { and, eq, inArray } from "drizzle-orm";
import { hostAccess, hosts } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
import { DataCrypto } from "../../utils/data-crypto.js";
export type HostRecord = typeof hosts.$inferSelect;
export type NewHostRecord = typeof hosts.$inferInsert;
export type HostUpdate = Partial<Omit<NewHostRecord, "id" | "userId">>;
export interface HostBulkUpdateState {
id: number;
statsConfig: string | null;
credentialId: number | null;
proxmoxConfig: string | null;
}
export class HostRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async create(host: NewHostRecord): Promise<HostRecord> {
const rows = await this.context.drizzle
.insert(hosts)
.values(host)
.returning();
await this.afterWrite();
return rows[0];
}
async createEncryptedForUser(
userId: string,
host: NewHostRecord | Record<string, unknown>,
): Promise<HostRecord> {
const userDataKey = DataCrypto.validateUserAccess(userId);
const tempId = host.id ?? Date.now();
const dataWithTempId = { ...host, id: tempId };
const encryptedHost = DataCrypto.encryptRecord(
"ssh_data",
dataWithTempId,
userId,
userDataKey,
);
if (!host.id) {
delete (encryptedHost as Partial<NewHostRecord>).id;
}
const rows = await this.context.drizzle
.insert(hosts)
.values(encryptedHost as NewHostRecord)
.returning();
await this.afterWrite();
return DataCrypto.decryptRecord("ssh_data", rows[0], userId, userDataKey);
}
async findById(id: number): Promise<HostRecord | null> {
const rows = await this.context.drizzle
.select()
.from(hosts)
.where(eq(hosts.id, id))
.limit(1);
return rows[0] ?? null;
}
async findByIdForUser(
userId: string,
hostId: number,
): Promise<HostRecord | null> {
const rows = await this.context.drizzle
.select()
.from(hosts)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
.limit(1);
return rows[0] ?? null;
}
async findDecryptedByIdAs(
userId: string,
hostId: number,
): Promise<HostRecord | null> {
const row = await this.findById(hostId);
if (!row) return null;
const userDataKey = DataCrypto.getUserDataKey(userId);
if (!userDataKey) return null;
return DataCrypto.decryptRecord("ssh_data", row, userId, userDataKey);
}
async listProxmoxEnabled(): Promise<
Pick<HostRecord, "id" | "userId" | "proxmoxConfig">[]
> {
return this.context.drizzle
.select({
id: hosts.id,
userId: hosts.userId,
proxmoxConfig: hosts.proxmoxConfig,
})
.from(hosts)
.where(eq(hosts.enableProxmox, true));
}
async listByUserId(userId: string): Promise<HostRecord[]> {
return this.context.drizzle
.select()
.from(hosts)
.where(eq(hosts.userId, userId));
}
async listDecryptedByUserId(userId: string): Promise<HostRecord[]> {
const rows = await this.listByUserId(userId);
const userDataKey = DataCrypto.getUserDataKey(userId);
if (!userDataKey) return [];
return DataCrypto.decryptRecords("ssh_data", rows, userId, userDataKey);
}
async existsForImportIdentity(
userId: string,
ip: string,
port: number,
username: string,
): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: hosts.id })
.from(hosts)
.where(
and(
eq(hosts.userId, userId),
eq(hosts.ip, ip),
eq(hosts.port, port),
eq(hosts.username, username),
),
)
.limit(1);
return rows.length > 0;
}
async updateForUser(
userId: string,
hostId: number,
update: HostUpdate,
): Promise<HostRecord | null> {
const rows = await this.context.drizzle
.update(hosts)
.set(update)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
.returning();
await this.afterWrite();
return rows[0] ?? null;
}
async updateEncryptedForUser(
userId: string,
hostId: number,
update: HostUpdate,
): Promise<HostRecord | null> {
const userDataKey = DataCrypto.validateUserAccess(userId);
const encryptedUpdate = DataCrypto.encryptRecord(
"ssh_data",
update,
userId,
userDataKey,
);
const rows = await this.context.drizzle
.update(hosts)
.set(encryptedUpdate)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
.returning();
await this.afterWrite();
return rows[0]
? DataCrypto.decryptRecord("ssh_data", rows[0], userId, userDataKey)
: null;
}
async listBulkUpdateState(
userId: string,
hostIds: number[],
): Promise<HostBulkUpdateState[]> {
if (hostIds.length === 0) {
return [];
}
return this.context.drizzle
.select({
id: hosts.id,
statsConfig: hosts.statsConfig,
credentialId: hosts.credentialId,
proxmoxConfig: hosts.proxmoxConfig,
})
.from(hosts)
.where(and(inArray(hosts.id, hostIds), eq(hosts.userId, userId)));
}
async updateManyForUser(
userId: string,
hostIds: number[],
update: HostUpdate,
): Promise<number> {
if (hostIds.length === 0 || Object.keys(update).length === 0) {
return 0;
}
const rows = await this.context.drizzle
.update(hosts)
.set(update)
.where(and(inArray(hosts.id, hostIds), eq(hosts.userId, userId)))
.returning({ id: hosts.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteForUser(userId: string, hostId: number): Promise<boolean> {
await this.deleteAccessForHost(hostId);
const rows = await this.context.drizzle
.delete(hosts)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
.returning({ id: hosts.id });
await this.afterWrite();
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(hosts)
.where(eq(hosts.userId, userId))
.returning({ id: hosts.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteAccessForHost(hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(hostAccess)
.where(eq(hostAccess.hostId, hostId))
.returning({ id: hostAccess.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,356 @@
import { and, eq, inArray, isNotNull } from "drizzle-orm";
import { hostAccess, hosts, sshCredentials } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
import { DataCrypto } from "../../utils/data-crypto.js";
export type HostResolutionHostRecord = typeof hosts.$inferSelect;
export type HostResolutionCredentialRecord = typeof sshCredentials.$inferSelect;
export interface HostKeyVerificationRecord {
hostKeyFingerprint: string | null;
hostKeyType: string | null;
hostKeyAlgorithm: string | null;
hostKeyChangedCount: number | null;
name: string | null;
}
export interface HostUpdateStateRecord {
userId: string;
credentialId: number | null;
rdpCredentialId: number | null;
vncCredentialId: number | null;
telnetCredentialId: number | null;
vaultProfileId: number | null;
authType: string;
}
export interface HostListAccessEntry {
hostId: number;
permissionLevel: string;
expiresAt: string | null;
}
export type HostListRow = HostResolutionHostRecord & {
ownerId: string;
isShared: boolean;
permissionLevel?: string;
expiresAt?: string | null;
};
export class HostResolutionRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async findHostById(
hostId: number,
userId: string,
): Promise<HostResolutionHostRecord | null> {
const rows = await this.context.drizzle
.select()
.from(hosts)
.where(eq(hosts.id, hostId))
.limit(1);
return this.decryptOne("ssh_data", rows[0], userId);
}
async findHostByIdForUser(
hostId: number,
userId: string,
): Promise<HostResolutionHostRecord | null> {
const rows = await this.context.drizzle
.select()
.from(hosts)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
.limit(1);
return this.decryptOne("ssh_data", rows[0], userId);
}
async findHostUpdateState(
hostId: number,
): Promise<HostUpdateStateRecord | null> {
const rows = await this.context.drizzle
.select({
userId: hosts.userId,
credentialId: hosts.credentialId,
rdpCredentialId: hosts.rdpCredentialId,
vncCredentialId: hosts.vncCredentialId,
telnetCredentialId: hosts.telnetCredentialId,
vaultProfileId: hosts.vaultProfileId,
authType: hosts.authType,
})
.from(hosts)
.where(eq(hosts.id, hostId))
.limit(1);
return rows[0] ?? null;
}
async findHostsByUserId(userId: string): Promise<HostResolutionHostRecord[]> {
const rows = await this.context.drizzle
.select()
.from(hosts)
.where(eq(hosts.userId, userId));
return this.decryptMany("ssh_data", rows, userId);
}
async listHostRowsForAccessList(
userId: string,
accessEntries: HostListAccessEntry[],
): Promise<HostListRow[]> {
const ownHostRows = await this.context.drizzle
.select()
.from(hosts)
.where(eq(hosts.userId, userId));
const sharedHostIds = Array.from(
new Set(accessEntries.map((access) => access.hostId)),
);
const sharedHostRows =
sharedHostIds.length > 0
? await this.context.drizzle
.select()
.from(hosts)
.where(inArray(hosts.id, sharedHostIds))
: [];
const sharedHostsById = new Map(
sharedHostRows.map((host) => [host.id, host]),
);
return [
...ownHostRows.map((host) => ({
...host,
ownerId: host.userId,
isShared: false,
permissionLevel: undefined,
expiresAt: undefined,
})),
...accessEntries.flatMap((access) => {
const host = sharedHostsById.get(access.hostId);
if (!host || host.userId === userId) {
return [];
}
return [
{
...host,
ownerId: host.userId,
isShared: host.userId !== userId,
permissionLevel: access.permissionLevel,
expiresAt: access.expiresAt,
},
];
}),
];
}
async findHostOwnerId(hostId: number): Promise<string | null> {
const rows = await this.context.drizzle
.select({ ownerId: hosts.userId })
.from(hosts)
.where(eq(hosts.id, hostId))
.limit(1);
return rows[0]?.ownerId ?? null;
}
async isHostOwnedByUser(hostId: number, userId: string): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: hosts.id })
.from(hosts)
.where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
.limit(1);
return rows.length > 0;
}
async listAllHosts(): Promise<HostResolutionHostRecord[]> {
const rows = await this.context.drizzle.select().from(hosts);
return this.decryptManyByOwner("ssh_data", rows);
}
async listHostsWithTunnelConnections(): Promise<HostResolutionHostRecord[]> {
const rows = await this.context.drizzle
.select()
.from(hosts)
.where(
and(eq(hosts.enableTunnel, true), isNotNull(hosts.tunnelConnections)),
);
return this.decryptManyByOwner("ssh_data", rows);
}
async listHostsUsingCredentialForUser(
userId: string,
credentialId: number,
): Promise<HostResolutionHostRecord[]> {
const rows = await this.context.drizzle
.select()
.from(hosts)
.where(
and(eq(hosts.credentialId, credentialId), eq(hosts.userId, userId)),
);
return this.decryptMany("ssh_data", rows, userId);
}
async findHostKeyVerificationData(
hostId: number,
): Promise<HostKeyVerificationRecord | null> {
const rows = await this.context.drizzle
.select({
hostKeyFingerprint: hosts.hostKeyFingerprint,
hostKeyType: hosts.hostKeyType,
hostKeyAlgorithm: hosts.hostKeyAlgorithm,
hostKeyChangedCount: hosts.hostKeyChangedCount,
name: hosts.name,
})
.from(hosts)
.where(eq(hosts.id, hostId))
.limit(1);
return rows[0] ?? null;
}
async storeHostKey(
hostId: number,
fingerprint: string,
keyType: string,
algorithm: string,
now = new Date().toISOString(),
): Promise<void> {
await this.context.drizzle
.update(hosts)
.set({
hostKeyFingerprint: fingerprint,
hostKeyType: keyType,
hostKeyAlgorithm: algorithm,
hostKeyFirstSeen: now,
hostKeyLastVerified: now,
})
.where(eq(hosts.id, hostId));
await this.afterWrite();
}
async updateHostKey(
hostId: number,
fingerprint: string,
keyType: string,
algorithm: string,
currentChangeCount: number,
now = new Date().toISOString(),
): Promise<void> {
await this.context.drizzle
.update(hosts)
.set({
hostKeyFingerprint: fingerprint,
hostKeyType: keyType,
hostKeyAlgorithm: algorithm,
hostKeyLastVerified: now,
hostKeyChangedCount: currentChangeCount + 1,
})
.where(eq(hosts.id, hostId));
await this.afterWrite();
}
async touchHostKeyLastVerified(
hostId: number,
now = new Date().toISOString(),
): Promise<void> {
await this.context.drizzle
.update(hosts)
.set({ hostKeyLastVerified: now })
.where(eq(hosts.id, hostId));
await this.afterWrite();
}
async findCredentialByIdForUser(
credentialId: number,
userId: string,
): Promise<HostResolutionCredentialRecord | null> {
const rows = await this.context.drizzle
.select()
.from(sshCredentials)
.where(
and(
eq(sshCredentials.id, credentialId),
eq(sshCredentials.userId, userId),
),
)
.limit(1);
return this.decryptOne("ssh_credentials", rows[0], userId);
}
async findCredentialByIdForOwnerDecryptedAs(
credentialId: number,
ownerUserId: string,
decryptUserId: string,
): Promise<HostResolutionCredentialRecord | null> {
const rows = await this.context.drizzle
.select()
.from(sshCredentials)
.where(
and(
eq(sshCredentials.id, credentialId),
eq(sshCredentials.userId, ownerUserId),
),
)
.limit(1);
return this.decryptOne("ssh_credentials", rows[0], decryptUserId);
}
async findOverrideCredentialId(
hostId: number,
userId: string,
): Promise<number | null> {
const rows = await this.context.drizzle
.select({ overrideCredentialId: hostAccess.overrideCredentialId })
.from(hostAccess)
.where(and(eq(hostAccess.hostId, hostId), eq(hostAccess.userId, userId)))
.limit(1);
return rows[0]?.overrideCredentialId ?? null;
}
private decryptOne<T extends Record<string, unknown>>(
tableName: "ssh_data" | "ssh_credentials",
record: T | undefined,
userId: string,
): T | null {
if (!record) return null;
const userDataKey = DataCrypto.getUserDataKey(userId);
if (!userDataKey) return null;
return DataCrypto.decryptRecord(tableName, record, userId, userDataKey);
}
private decryptMany<T extends Record<string, unknown>>(
tableName: "ssh_data" | "ssh_credentials",
records: T[],
userId: string,
): T[] {
const userDataKey = DataCrypto.getUserDataKey(userId);
if (!userDataKey) return [];
return records.map((record) =>
DataCrypto.decryptRecord(tableName, record, userId, userDataKey),
);
}
private decryptManyByOwner<
T extends Record<string, unknown> & { userId: string },
>(tableName: "ssh_data" | "ssh_credentials", records: T[]): T[] {
return records.flatMap((record) => {
const userDataKey = DataCrypto.getUserDataKey(record.userId);
if (!userDataKey) return [];
return [
DataCrypto.decryptRecord(tableName, record, record.userId, userDataKey),
];
});
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,63 @@
import { eq } from "drizzle-orm";
import { networkTopology } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type NetworkTopologyRecord = typeof networkTopology.$inferSelect;
export class NetworkTopologyRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async findByUserId(userId: string): Promise<NetworkTopologyRecord | null> {
const rows = await this.context.drizzle
.select()
.from(networkTopology)
.where(eq(networkTopology.userId, userId))
.limit(1);
return rows[0] ?? null;
}
async upsertForUser(
userId: string,
topology: string,
updatedAt = new Date().toISOString(),
): Promise<void> {
const existing = await this.findByUserId(userId);
if (existing) {
await this.context.drizzle
.update(networkTopology)
.set({ topology, updatedAt })
.where(eq(networkTopology.userId, userId));
await this.afterWrite();
return;
}
await this.context.drizzle.insert(networkTopology).values({
userId,
topology,
updatedAt,
});
await this.afterWrite();
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(networkTopology)
.where(eq(networkTopology.userId, userId))
.returning({ id: networkTopology.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,169 @@
import { and, eq, gt } from "drizzle-orm";
import { userOpenTabs } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type OpenTabRecord = typeof userOpenTabs.$inferSelect;
export type NewOpenTabRecord = typeof userOpenTabs.$inferInsert;
export type OpenTabUpdate = Partial<
Pick<NewOpenTabRecord, "label" | "tabOrder" | "backendSessionId">
>;
export type OpenTabUpsertInput = Pick<
NewOpenTabRecord,
"id" | "tabType" | "label" | "tabOrder"
> & {
hostId?: number | null;
backendSessionId?: string | null;
};
export class OpenTabRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listRecentForUser(
userId: string,
updatedAfter: string,
): Promise<OpenTabRecord[]> {
return this.context.drizzle
.select()
.from(userOpenTabs)
.where(
and(
eq(userOpenTabs.userId, userId),
gt(userOpenTabs.updatedAt, updatedAfter),
),
)
.orderBy(userOpenTabs.tabOrder);
}
async upsertForUser(
userId: string,
input: OpenTabUpsertInput,
updatedAt = new Date().toISOString(),
): Promise<void> {
const existing = await this.findByIdForUser(userId, input.id);
if (existing) {
await this.context.drizzle
.update(userOpenTabs)
.set({
tabType: input.tabType,
hostId: input.hostId ?? null,
label: input.label,
tabOrder: input.tabOrder,
backendSessionId:
input.backendSessionId !== undefined
? input.backendSessionId
: existing.backendSessionId,
updatedAt,
})
.where(
and(eq(userOpenTabs.id, input.id), eq(userOpenTabs.userId, userId)),
);
await this.afterWrite();
return;
}
await this.context.drizzle.insert(userOpenTabs).values({
id: input.id,
userId,
tabType: input.tabType,
hostId: input.hostId ?? null,
label: input.label,
tabOrder: input.tabOrder,
backendSessionId: input.backendSessionId ?? null,
updatedAt,
});
await this.afterWrite();
}
async replaceForUser(
userId: string,
tabs: OpenTabUpsertInput[],
updatedAt = new Date().toISOString(),
): Promise<void> {
await this.context.drizzle
.delete(userOpenTabs)
.where(eq(userOpenTabs.userId, userId));
if (tabs.length > 0) {
await this.context.drizzle.insert(userOpenTabs).values(
tabs.map((tab) => ({
id: tab.id,
userId,
tabType: tab.tabType,
hostId: tab.hostId ?? null,
label: tab.label,
tabOrder: tab.tabOrder,
backendSessionId: tab.backendSessionId ?? null,
updatedAt,
})),
);
}
await this.afterWrite();
}
async updateForUser(
userId: string,
id: string,
update: OpenTabUpdate,
updatedAt = new Date().toISOString(),
): Promise<boolean> {
const rows = await this.context.drizzle
.update(userOpenTabs)
.set({ ...update, updatedAt })
.where(and(eq(userOpenTabs.id, id), eq(userOpenTabs.userId, userId)))
.returning({ id: userOpenTabs.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteForUser(userId: string, id: string): Promise<number> {
const rows = await this.context.drizzle
.delete(userOpenTabs)
.where(and(eq(userOpenTabs.id, id), eq(userOpenTabs.userId, userId)))
.returning({ id: userOpenTabs.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(userOpenTabs)
.where(eq(userOpenTabs.userId, userId))
.returning({ id: userOpenTabs.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async findByIdForUser(
userId: string,
id: string,
): Promise<OpenTabRecord | null> {
const rows = await this.context.drizzle
.select()
.from(userOpenTabs)
.where(and(eq(userOpenTabs.id, id), eq(userOpenTabs.userId, userId)))
.limit(1);
return rows[0] ?? null;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,125 @@
import { and, eq } from "drizzle-orm";
import { opksshTokens } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type OpksshTokenRecord = typeof opksshTokens.$inferSelect;
export interface OpksshTokenUpsertInput {
userId: string;
hostId: number;
sshCert: string;
privateKey: string;
email?: string | null;
sub?: string | null;
issuer?: string | null;
audience?: string | null;
expiresAt: string;
createdAt?: string;
}
export class OpksshTokenRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async upsert(input: OpksshTokenUpsertInput): Promise<void> {
const createdAt = input.createdAt ?? new Date().toISOString();
await this.context.drizzle
.insert(opksshTokens)
.values({
userId: input.userId,
hostId: input.hostId,
sshCert: input.sshCert,
privateKey: input.privateKey,
email: input.email,
sub: input.sub,
issuer: input.issuer,
audience: input.audience,
expiresAt: input.expiresAt,
})
.onConflictDoUpdate({
target: [opksshTokens.userId, opksshTokens.hostId],
set: {
sshCert: input.sshCert,
privateKey: input.privateKey,
email: input.email,
sub: input.sub,
issuer: input.issuer,
audience: input.audience,
expiresAt: input.expiresAt,
createdAt,
},
});
await this.afterWrite();
}
async findByUserAndHost(
userId: string,
hostId: number,
): Promise<OpksshTokenRecord | null> {
const rows = await this.context.drizzle
.select()
.from(opksshTokens)
.where(
and(eq(opksshTokens.userId, userId), eq(opksshTokens.hostId, hostId)),
)
.limit(1);
return rows[0] ?? null;
}
async updateLastUsed(
userId: string,
hostId: number,
lastUsed = new Date().toISOString(),
): Promise<boolean> {
const rows = await this.context.drizzle
.update(opksshTokens)
.set({ lastUsed })
.where(
and(eq(opksshTokens.userId, userId), eq(opksshTokens.hostId, hostId)),
)
.returning({ id: opksshTokens.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserAndHost(userId: string, hostId: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(opksshTokens)
.where(
and(eq(opksshTokens.userId, userId), eq(opksshTokens.hostId, hostId)),
)
.returning({ id: opksshTokens.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(opksshTokens)
.where(eq(opksshTokens.userId, userId))
.returning({ id: opksshTokens.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,721 @@
import { and, desc, eq, gte, inArray, isNull, or, sql } from "drizzle-orm";
import {
hostAccess,
hosts,
roles,
sharedHostSecrets,
snippetAccess,
snippets,
users,
} from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type RbacAccessTargetType = "user" | "role";
export interface RbacAccessListItem {
id: number;
targetType: RbacAccessTargetType;
userId: string | null;
roleId: number | null;
username: string | null;
roleName: string | null;
roleDisplayName: string | null;
grantedBy: string;
grantedByUsername: string | null;
permissionLevel: string;
expiresAt: string | null;
createdAt: string;
}
export interface RbacSharedHost {
id: number;
name: string | null;
ip: string;
port: number;
username: string;
folder: string | null;
tags: string | null;
permissionLevel: string;
expiresAt: string | null;
grantedBy: string;
ownerUsername: string;
}
export interface RbacSharedSnippet {
id: number;
name: string;
content: string;
description: string | null;
folder: string | null;
ownerUsername: string;
permissionLevel: string;
expiresAt: string | null;
}
export interface RbacVisibleSharedSnippet extends RbacSharedSnippet {
userId: string;
order: number;
createdAt: string;
updatedAt: string;
}
export interface RbacAccessibleSnippet extends RbacVisibleSharedSnippet {
hostFilter: string | null;
}
export interface RbacRoleHostAccessCredentialSource {
hostAccessId: number;
credentialId: number | null;
rdpCredentialId: number | null;
vncCredentialId: number | null;
telnetCredentialId: number | null;
hostId: number;
hostOwnerId: string;
}
export interface RbacVisibleHostAccessEntry {
hostId: number;
permissionLevel: string;
expiresAt: string | null;
}
export type RbacAccessTarget =
| { targetType: "user"; targetUserId: string }
| { targetType: "role"; targetRoleId: number };
export type UpsertHostAccessInput = RbacAccessTarget & {
hostId: number;
grantedBy: string;
permissionLevel: string;
expiresAt: string | null;
};
export type UpsertSnippetAccessInput = RbacAccessTarget & {
snippetId: number;
grantedBy: string;
expiresAt: string | null;
};
type RawAccessListItem = Omit<RbacAccessListItem, "targetType">;
function toAccessListItem(access: RawAccessListItem): RbacAccessListItem {
return {
...access,
targetType: access.userId ? "user" : "role",
};
}
export class RbacAccessRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listHostAccess(hostId: number): Promise<RbacAccessListItem[]> {
const rows = await this.context.drizzle
.select({
id: hostAccess.id,
userId: hostAccess.userId,
roleId: hostAccess.roleId,
username: users.username,
roleName: roles.name,
roleDisplayName: roles.displayName,
grantedBy: hostAccess.grantedBy,
grantedByUsername: sql<
string | null
>`(SELECT username FROM users WHERE id = ${hostAccess.grantedBy})`,
permissionLevel: hostAccess.permissionLevel,
expiresAt: hostAccess.expiresAt,
createdAt: hostAccess.createdAt,
})
.from(hostAccess)
.leftJoin(users, eq(hostAccess.userId, users.id))
.leftJoin(roles, eq(hostAccess.roleId, roles.id))
.where(eq(hostAccess.hostId, hostId))
.orderBy(desc(hostAccess.createdAt));
return rows.map(toAccessListItem);
}
async upsertHostAccess(input: UpsertHostAccessInput): Promise<{
id: number;
created: boolean;
}> {
const existing = await this.findHostAccess(input.hostId, input);
if (existing) {
await this.context.drizzle
.update(hostAccess)
.set({
permissionLevel: input.permissionLevel,
expiresAt: input.expiresAt,
})
.where(eq(hostAccess.id, existing.id));
await this.afterWrite();
return { id: existing.id, created: false };
}
const result = await this.context.drizzle.insert(hostAccess).values({
hostId: input.hostId,
userId: input.targetType === "user" ? input.targetUserId : null,
roleId: input.targetType === "role" ? input.targetRoleId : null,
grantedBy: input.grantedBy,
permissionLevel: input.permissionLevel,
expiresAt: input.expiresAt,
});
await this.afterWrite();
return { id: Number(result.lastInsertRowid), created: true };
}
async revokeHostAccess(accessId: number, hostId: number): Promise<void> {
await this.context.drizzle
.delete(hostAccess)
.where(and(eq(hostAccess.id, accessId), eq(hostAccess.hostId, hostId)));
await this.afterWrite();
}
async deleteHostAccessForHost(hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(hostAccess)
.where(eq(hostAccess.hostId, hostId))
.returning({ id: hostAccess.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteHostAccessForHosts(hostIds: number[]): Promise<number> {
if (hostIds.length === 0) {
return 0;
}
const rows = await this.context.drizzle
.delete(hostAccess)
.where(inArray(hostAccess.hostId, hostIds))
.returning({ id: hostAccess.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteHostAccessForUserReferences(userId: string): Promise<number> {
const directRows = await this.context.drizzle
.delete(hostAccess)
.where(eq(hostAccess.userId, userId))
.returning({ id: hostAccess.id });
const grantedRows = await this.context.drizzle
.delete(hostAccess)
.where(eq(hostAccess.grantedBy, userId))
.returning({ id: hostAccess.id });
const deletedCount = directRows.length + grantedRows.length;
if (deletedCount > 0) {
await this.afterWrite();
}
return deletedCount;
}
async findDirectHostAccess(
hostId: number,
userId: string,
): Promise<typeof hostAccess.$inferSelect | null> {
const rows = await this.context.drizzle
.select()
.from(hostAccess)
.where(and(eq(hostAccess.hostId, hostId), eq(hostAccess.userId, userId)))
.limit(1);
return rows[0] ?? null;
}
async updateHostAccessOverrideCredential(
accessId: number,
credentialId: number | null,
): Promise<void> {
await this.context.drizzle
.update(hostAccess)
.set({ overrideCredentialId: credentialId })
.where(eq(hostAccess.id, accessId));
await this.afterWrite();
}
async listSnippetAccess(snippetId: number): Promise<RbacAccessListItem[]> {
const rows = await this.context.drizzle
.select({
id: snippetAccess.id,
userId: snippetAccess.userId,
roleId: snippetAccess.roleId,
username: users.username,
roleName: roles.name,
roleDisplayName: roles.displayName,
grantedBy: snippetAccess.grantedBy,
grantedByUsername: sql<
string | null
>`(SELECT username FROM users WHERE id = ${snippetAccess.grantedBy})`,
permissionLevel: snippetAccess.permissionLevel,
expiresAt: snippetAccess.expiresAt,
createdAt: snippetAccess.createdAt,
})
.from(snippetAccess)
.leftJoin(users, eq(snippetAccess.userId, users.id))
.leftJoin(roles, eq(snippetAccess.roleId, roles.id))
.where(eq(snippetAccess.snippetId, snippetId))
.orderBy(desc(snippetAccess.createdAt));
return rows.map(toAccessListItem);
}
async upsertSnippetAccess(input: UpsertSnippetAccessInput): Promise<{
id: number;
created: boolean;
}> {
const existing = await this.findSnippetAccess(input.snippetId, input);
if (existing) {
await this.context.drizzle
.update(snippetAccess)
.set({ expiresAt: input.expiresAt })
.where(eq(snippetAccess.id, existing.id));
await this.afterWrite();
return { id: existing.id, created: false };
}
const result = await this.context.drizzle.insert(snippetAccess).values({
snippetId: input.snippetId,
userId: input.targetType === "user" ? input.targetUserId : null,
roleId: input.targetType === "role" ? input.targetRoleId : null,
grantedBy: input.grantedBy,
permissionLevel: "view",
expiresAt: input.expiresAt,
});
await this.afterWrite();
return { id: Number(result.lastInsertRowid), created: true };
}
async revokeSnippetAccess(
accessId: number,
snippetId: number,
): Promise<void> {
await this.context.drizzle
.delete(snippetAccess)
.where(
and(
eq(snippetAccess.id, accessId),
eq(snippetAccess.snippetId, snippetId),
),
);
await this.afterWrite();
}
async listSharedHosts(
userId: string,
roleIds: number[],
now = new Date().toISOString(),
): Promise<RbacSharedHost[]> {
return this.context.drizzle
.select({
id: hosts.id,
name: hosts.name,
ip: hosts.ip,
port: hosts.port,
username: hosts.username,
folder: hosts.folder,
tags: hosts.tags,
permissionLevel: hostAccess.permissionLevel,
expiresAt: hostAccess.expiresAt,
grantedBy: hostAccess.grantedBy,
ownerUsername: users.username,
})
.from(hostAccess)
.innerJoin(hosts, eq(hostAccess.hostId, hosts.id))
.innerJoin(users, eq(hosts.userId, users.id))
.where(
and(
this.userOrRoleHostAccessFilter(userId, roleIds),
or(isNull(hostAccess.expiresAt), gte(hostAccess.expiresAt, now)),
),
)
.orderBy(desc(hostAccess.createdAt));
}
async listVisibleHostAccessEntries(
userId: string,
roleIds: number[],
now = new Date().toISOString(),
): Promise<RbacVisibleHostAccessEntry[]> {
return this.context.drizzle
.select({
hostId: hostAccess.hostId,
permissionLevel: hostAccess.permissionLevel,
expiresAt: hostAccess.expiresAt,
})
.from(hostAccess)
.where(
and(
this.userOrRoleHostAccessFilter(userId, roleIds),
or(isNull(hostAccess.expiresAt), gte(hostAccess.expiresAt, now)),
),
)
.orderBy(desc(hostAccess.createdAt));
}
async listSharedSnippets(
userId: string,
roleIds: number[],
now = new Date().toISOString(),
): Promise<RbacSharedSnippet[]> {
const directShared = await this.context.drizzle
.select({
id: snippets.id,
name: snippets.name,
content: snippets.content,
description: snippets.description,
folder: snippets.folder,
ownerUsername: users.username,
permissionLevel: snippetAccess.permissionLevel,
expiresAt: snippetAccess.expiresAt,
})
.from(snippetAccess)
.innerJoin(snippets, eq(snippetAccess.snippetId, snippets.id))
.innerJoin(users, eq(snippets.userId, users.id))
.where(
and(
eq(snippetAccess.userId, userId),
or(
isNull(snippetAccess.expiresAt),
gte(snippetAccess.expiresAt, now),
),
),
);
if (roleIds.length === 0) {
return directShared;
}
const directIds = new Set(directShared.map((snippet) => snippet.id));
const roleShared = await this.context.drizzle
.select({
id: snippets.id,
name: snippets.name,
content: snippets.content,
description: snippets.description,
folder: snippets.folder,
ownerUsername: users.username,
permissionLevel: snippetAccess.permissionLevel,
expiresAt: snippetAccess.expiresAt,
})
.from(snippetAccess)
.innerJoin(snippets, eq(snippetAccess.snippetId, snippets.id))
.innerJoin(users, eq(snippets.userId, users.id))
.where(
and(
or(
isNull(snippetAccess.expiresAt),
gte(snippetAccess.expiresAt, now),
),
inArray(snippetAccess.roleId, roleIds),
),
);
return [
...directShared,
...roleShared.filter((snippet) => !directIds.has(snippet.id)),
];
}
async listVisibleSharedSnippets(
userId: string,
roleIds: number[],
now = new Date().toISOString(),
): Promise<RbacVisibleSharedSnippet[]> {
return this.context.drizzle
.select({
id: snippets.id,
userId: snippets.userId,
name: snippets.name,
content: snippets.content,
description: snippets.description,
folder: snippets.folder,
order: snippets.order,
createdAt: snippets.createdAt,
updatedAt: snippets.updatedAt,
ownerUsername: users.username,
permissionLevel: snippetAccess.permissionLevel,
expiresAt: snippetAccess.expiresAt,
})
.from(snippetAccess)
.innerJoin(snippets, eq(snippetAccess.snippetId, snippets.id))
.innerJoin(users, eq(snippets.userId, users.id))
.where(
and(
this.userOrRoleSnippetAccessFilter(userId, roleIds),
or(
isNull(snippetAccess.expiresAt),
gte(snippetAccess.expiresAt, now),
),
),
);
}
async findAccessibleSharedSnippet(
snippetId: number,
userId: string,
roleIds: number[],
now = new Date().toISOString(),
): Promise<RbacAccessibleSnippet | null> {
const rows = await this.context.drizzle
.select({
id: snippets.id,
userId: snippets.userId,
name: snippets.name,
content: snippets.content,
description: snippets.description,
folder: snippets.folder,
order: snippets.order,
createdAt: snippets.createdAt,
updatedAt: snippets.updatedAt,
hostFilter: snippets.hostFilter,
ownerUsername: users.username,
permissionLevel: snippetAccess.permissionLevel,
expiresAt: snippetAccess.expiresAt,
})
.from(snippetAccess)
.innerJoin(snippets, eq(snippetAccess.snippetId, snippets.id))
.innerJoin(users, eq(snippets.userId, users.id))
.where(
and(
eq(snippetAccess.snippetId, snippetId),
this.userOrRoleSnippetAccessFilter(userId, roleIds),
or(
isNull(snippetAccess.expiresAt),
gte(snippetAccess.expiresAt, now),
),
),
)
.limit(1);
return rows[0] ?? null;
}
async deleteExpiredHostAccess(
now = new Date().toISOString(),
): Promise<number> {
const rows = await this.context.drizzle
.delete(hostAccess)
.where(
and(
sql`${hostAccess.expiresAt} IS NOT NULL`,
sql`${hostAccess.expiresAt} <= ${now}`,
),
)
.returning({ id: hostAccess.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async findActiveHostAccess(
hostId: number,
userId: string,
roleIds: number[],
now = new Date().toISOString(),
): Promise<typeof hostAccess.$inferSelect | null> {
const rows = await this.context.drizzle
.select()
.from(hostAccess)
.where(
and(
eq(hostAccess.hostId, hostId),
this.userOrRoleHostAccessFilter(userId, roleIds),
or(isNull(hostAccess.expiresAt), gte(hostAccess.expiresAt, now)),
),
)
.limit(1);
return rows[0] ?? null;
}
async touchHostAccess(
accessId: number,
lastAccessedAt = new Date().toISOString(),
): Promise<void> {
await this.context.drizzle
.update(hostAccess)
.set({ lastAccessedAt })
.where(eq(hostAccess.id, accessId));
await this.afterWrite();
}
async listRoleHostAccessCredentialSources(
roleId: number,
): Promise<RbacRoleHostAccessCredentialSource[]> {
return this.context.drizzle
.select({
hostAccessId: hostAccess.id,
credentialId: hosts.credentialId,
rdpCredentialId: hosts.rdpCredentialId,
vncCredentialId: hosts.vncCredentialId,
telnetCredentialId: hosts.telnetCredentialId,
hostId: hosts.id,
hostOwnerId: hosts.userId,
})
.from(hostAccess)
.innerJoin(hosts, eq(hostAccess.hostId, hosts.id))
.where(eq(hostAccess.roleId, roleId));
}
async findSharedSecretForHostUserProtocol(
hostId: number,
userId: string,
protocol: string,
): Promise<typeof sharedHostSecrets.$inferSelect | null> {
const rows = await this.context.drizzle
.select({
secret: sharedHostSecrets,
})
.from(sharedHostSecrets)
.innerJoin(hostAccess, eq(sharedHostSecrets.hostAccessId, hostAccess.id))
.where(
and(
eq(hostAccess.hostId, hostId),
eq(sharedHostSecrets.targetUserId, userId),
eq(sharedHostSecrets.protocol, protocol),
),
)
.limit(1);
return rows[0]?.secret ?? null;
}
async listActiveHostAccessGrants(
hostId: number,
now = new Date().toISOString(),
): Promise<(typeof hostAccess.$inferSelect)[]> {
return this.context.drizzle
.select()
.from(hostAccess)
.where(
and(
eq(hostAccess.hostId, hostId),
or(isNull(hostAccess.expiresAt), gte(hostAccess.expiresAt, now)),
),
);
}
async findHostAccessById(
accessId: number,
hostId: number,
): Promise<typeof hostAccess.$inferSelect | null> {
const rows = await this.context.drizzle
.select()
.from(hostAccess)
.where(and(eq(hostAccess.id, accessId), eq(hostAccess.hostId, hostId)))
.limit(1);
return rows[0] ?? null;
}
async updateHostAccessGrant(
accessId: number,
hostId: number,
update: { permissionLevel?: string; expiresAt?: string | null },
): Promise<boolean> {
const rows = await this.context.drizzle
.update(hostAccess)
.set(update)
.where(and(eq(hostAccess.id, accessId), eq(hostAccess.hostId, hostId)))
.returning({ id: hostAccess.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async findHostAccessOwnerId(hostAccessId: number): Promise<string | null> {
const rows = await this.context.drizzle
.select({ ownerId: hosts.userId })
.from(hostAccess)
.innerJoin(hosts, eq(hostAccess.hostId, hosts.id))
.where(eq(hostAccess.id, hostAccessId))
.limit(1);
return rows[0]?.ownerId ?? null;
}
private userOrRoleHostAccessFilter(userId: string, roleIds: number[]) {
if (roleIds.length === 0) {
return eq(hostAccess.userId, userId);
}
return or(
eq(hostAccess.userId, userId),
inArray(hostAccess.roleId, roleIds),
);
}
private userOrRoleSnippetAccessFilter(userId: string, roleIds: number[]) {
if (roleIds.length === 0) {
return eq(snippetAccess.userId, userId);
}
return or(
eq(snippetAccess.userId, userId),
inArray(snippetAccess.roleId, roleIds),
);
}
private async findHostAccess(hostId: number, target: RbacAccessTarget) {
const rows = await this.context.drizzle
.select()
.from(hostAccess)
.where(
and(
eq(hostAccess.hostId, hostId),
target.targetType === "user"
? eq(hostAccess.userId, target.targetUserId)
: eq(hostAccess.roleId, target.targetRoleId),
),
)
.limit(1);
return rows[0] ?? null;
}
private async findSnippetAccess(snippetId: number, target: RbacAccessTarget) {
const rows = await this.context.drizzle
.select()
.from(snippetAccess)
.where(
and(
eq(snippetAccess.snippetId, snippetId),
target.targetType === "user"
? eq(snippetAccess.userId, target.targetUserId)
: eq(snippetAccess.roleId, target.targetRoleId),
),
)
.limit(1);
return rows[0] ?? null;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,112 @@
import { desc, eq, inArray } from "drizzle-orm";
import { recentActivity } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type RecentActivityRecord = typeof recentActivity.$inferSelect;
export type NewRecentActivityRecord = typeof recentActivity.$inferInsert;
export class RecentActivityRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listByUserId(
userId: string,
limit: number,
): Promise<RecentActivityRecord[]> {
return this.context.drizzle
.select()
.from(recentActivity)
.where(eq(recentActivity.userId, userId))
.orderBy(desc(recentActivity.timestamp))
.limit(limit);
}
async create(
activity: NewRecentActivityRecord,
): Promise<RecentActivityRecord> {
const rows = await this.context.drizzle
.insert(recentActivity)
.values(activity)
.returning();
await this.afterWrite();
return rows[0];
}
async trimUserActivity(userId: string, keepCount: number): Promise<number> {
const rows = await this.context.drizzle
.select({ id: recentActivity.id })
.from(recentActivity)
.where(eq(recentActivity.userId, userId))
.orderBy(desc(recentActivity.timestamp));
const idsToDelete = rows
.slice(keepCount)
.map((row) => row.id)
.filter((id) => typeof id === "number");
if (idsToDelete.length === 0) {
return 0;
}
const deletedRows = await this.context.drizzle
.delete(recentActivity)
.where(inArray(recentActivity.id, idsToDelete))
.returning({ id: recentActivity.id });
if (deletedRows.length > 0) {
await this.afterWrite();
}
return deletedRows.length;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(recentActivity)
.where(eq(recentActivity.userId, userId))
.returning({ id: recentActivity.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByHostId(hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(recentActivity)
.where(eq(recentActivity.hostId, hostId))
.returning({ id: recentActivity.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByHostIds(hostIds: number[]): Promise<number> {
if (hostIds.length === 0) {
return 0;
}
const rows = await this.context.drizzle
.delete(recentActivity)
.where(inArray(recentActivity.hostId, hostIds))
.returning({ id: recentActivity.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,276 @@
import { and, eq, inArray } from "drizzle-orm";
import { hostAccess, roles, userRoles } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type RoleRecord = typeof roles.$inferSelect;
export type NewRoleRecord = typeof roles.$inferInsert;
export type RoleUpdate = Pick<
Partial<NewRoleRecord>,
"displayName" | "description" | "updatedAt"
>;
export type UserRoleWithRole = {
id: number;
roleId: number;
roleName: string;
roleDisplayName: string;
description: string | null;
isSystem: boolean;
grantedAt: string;
};
export type UserRolePermissionRecord = {
permissions: string | null;
};
export type UserRoleNameSwitchResult = {
added: boolean;
removed: boolean;
};
export class RoleRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listRoles(): Promise<RoleRecord[]> {
return this.context.drizzle
.select()
.from(roles)
.orderBy(roles.isSystem, roles.name);
}
async findRoleById(id: number): Promise<RoleRecord | null> {
const rows = await this.context.drizzle
.select()
.from(roles)
.where(eq(roles.id, id))
.limit(1);
return rows[0] ?? null;
}
async findRoleByName(name: string): Promise<RoleRecord | null> {
const rows = await this.context.drizzle
.select()
.from(roles)
.where(eq(roles.name, name))
.limit(1);
return rows[0] ?? null;
}
async createRole(role: NewRoleRecord): Promise<number> {
const result = await this.context.drizzle.insert(roles).values(role);
await this.afterWrite();
return Number(result.lastInsertRowid);
}
async updateRole(id: number, update: RoleUpdate): Promise<boolean> {
const rows = await this.context.drizzle
.update(roles)
.set(update)
.where(eq(roles.id, id))
.returning({ id: roles.id });
await this.afterWrite();
return rows.length > 0;
}
async deleteRole(id: number): Promise<{ deletedUserIds: string[] }> {
const deletedUserRoles = await this.context.drizzle
.delete(userRoles)
.where(eq(userRoles.roleId, id))
.returning({ userId: userRoles.userId });
await this.context.drizzle
.delete(hostAccess)
.where(eq(hostAccess.roleId, id));
await this.context.drizzle.delete(roles).where(eq(roles.id, id));
await this.afterWrite();
return {
deletedUserIds: deletedUserRoles.map((row) => row.userId),
};
}
async findUserRole(
userId: string,
roleId: number,
): Promise<typeof userRoles.$inferSelect | null> {
const rows = await this.context.drizzle
.select()
.from(userRoles)
.where(and(eq(userRoles.userId, userId), eq(userRoles.roleId, roleId)))
.limit(1);
return rows[0] ?? null;
}
async assignRoleToUser(input: {
userId: string;
roleId: number;
grantedBy: string;
}): Promise<void> {
await this.context.drizzle.insert(userRoles).values(input);
await this.afterWrite();
}
async assignRoleNameToUser(input: {
userId: string;
roleName: string;
grantedBy: string;
}): Promise<boolean> {
const role = await this.findRoleByName(input.roleName);
if (!role) {
return false;
}
await this.context.drizzle.insert(userRoles).values({
userId: input.userId,
roleId: role.id,
grantedBy: input.grantedBy,
});
await this.afterWrite();
return true;
}
async switchUserRoleName(input: {
userId: string;
addRoleName: string;
removeRoleName: string;
grantedBy: string;
}): Promise<UserRoleNameSwitchResult> {
const [addRole, removeRole] = await Promise.all([
this.findRoleByName(input.addRoleName),
this.findRoleByName(input.removeRoleName),
]);
let added = false;
let removed = false;
if (addRole) {
await this.context.drizzle
.delete(userRoles)
.where(
and(
eq(userRoles.userId, input.userId),
eq(userRoles.roleId, addRole.id),
),
);
await this.context.drizzle.insert(userRoles).values({
userId: input.userId,
roleId: addRole.id,
grantedBy: input.grantedBy,
});
added = true;
}
if (removeRole) {
const rows = await this.context.drizzle
.delete(userRoles)
.where(
and(
eq(userRoles.userId, input.userId),
eq(userRoles.roleId, removeRole.id),
),
)
.returning({ id: userRoles.id });
removed = rows.length > 0;
}
if (added || removed) {
await this.afterWrite();
}
return { added, removed };
}
async removeRoleFromUser(userId: string, roleId: number): Promise<void> {
await this.context.drizzle
.delete(userRoles)
.where(and(eq(userRoles.userId, userId), eq(userRoles.roleId, roleId)));
await this.afterWrite();
}
async removeAllRolesFromUser(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(userRoles)
.where(eq(userRoles.userId, userId))
.returning({ id: userRoles.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async listUserRoleIds(userId: string): Promise<number[]> {
const rows = await this.context.drizzle
.select({ roleId: userRoles.roleId })
.from(userRoles)
.where(eq(userRoles.userId, userId));
return rows.map((row) => row.roleId);
}
async listRoleUserIds(roleId: number): Promise<string[]> {
const rows = await this.context.drizzle
.select({ userId: userRoles.userId })
.from(userRoles)
.where(eq(userRoles.roleId, roleId));
return rows.map((row) => row.userId);
}
async listUserRolePermissions(
userId: string,
): Promise<UserRolePermissionRecord[]> {
return this.context.drizzle
.select({ permissions: roles.permissions })
.from(userRoles)
.innerJoin(roles, eq(userRoles.roleId, roles.id))
.where(eq(userRoles.userId, userId));
}
async userHasAnyRoleName(
userId: string,
roleNames: string[],
): Promise<boolean> {
if (roleNames.length === 0) {
return false;
}
const rows = await this.context.drizzle
.select({ roleName: roles.name })
.from(userRoles)
.innerJoin(roles, eq(userRoles.roleId, roles.id))
.where(and(eq(userRoles.userId, userId), inArray(roles.name, roleNames)))
.limit(1);
return rows.length > 0;
}
async listUserRoles(userId: string): Promise<UserRoleWithRole[]> {
return this.context.drizzle
.select({
id: userRoles.id,
roleId: roles.id,
roleName: roles.name,
roleDisplayName: roles.displayName,
description: roles.description,
isSystem: roles.isSystem,
grantedAt: userRoles.grantedAt,
})
.from(userRoles)
.innerJoin(roles, eq(userRoles.roleId, roles.id))
.where(eq(userRoles.userId, userId));
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,241 @@
import { and, desc, eq, inArray, lt } from "drizzle-orm";
import { hosts, sessionRecordings } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type SessionRecordingRecord = typeof sessionRecordings.$inferSelect;
export interface SessionRecordingCreateInput {
hostId: number;
userId: string;
startedAt: string;
endedAt?: string | null;
duration?: number | null;
commands?: string | null;
dangerousActions?: string | null;
recordingPath?: string | null;
protocol?: string | null;
format?: string | null;
terminatedByOwner?: boolean | null;
terminationReason?: string | null;
}
export interface SessionRecordingListRecord {
id: number;
hostId: number;
userId: string;
startedAt: string;
endedAt: string | null;
duration: number | null;
recordingPath: string | null;
protocol: string;
format: string | null;
hostName: string | null;
hostIp: string | null;
}
export interface SessionRecordingPathRecord {
id: number;
recordingPath: string | null;
}
export class SessionRecordingRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async create(
input: SessionRecordingCreateInput,
): Promise<SessionRecordingRecord> {
const [created] = await this.context.drizzle
.insert(sessionRecordings)
.values(input)
.returning();
await this.afterWrite();
return created;
}
async updateEnded(
id: number,
input: { endedAt: string; duration: number | null },
): Promise<void> {
await this.context.drizzle
.update(sessionRecordings)
.set(input)
.where(eq(sessionRecordings.id, id));
await this.afterWrite();
}
async findById(id: number): Promise<SessionRecordingRecord | null> {
const rows = await this.context.drizzle
.select()
.from(sessionRecordings)
.where(eq(sessionRecordings.id, id))
.limit(1);
return rows[0] ?? null;
}
async findPathById(id: number): Promise<
| (SessionRecordingPathRecord & {
userId: string;
format?: string | null;
})
| null
> {
const rows = await this.context.drizzle
.select({
id: sessionRecordings.id,
recordingPath: sessionRecordings.recordingPath,
userId: sessionRecordings.userId,
format: sessionRecordings.format,
})
.from(sessionRecordings)
.where(eq(sessionRecordings.id, id))
.limit(1);
return rows[0] ?? null;
}
async listByUserIdWithHost(
userId: string,
): Promise<SessionRecordingListRecord[]> {
return this.context.drizzle
.select({
id: sessionRecordings.id,
hostId: sessionRecordings.hostId,
userId: sessionRecordings.userId,
startedAt: sessionRecordings.startedAt,
endedAt: sessionRecordings.endedAt,
duration: sessionRecordings.duration,
recordingPath: sessionRecordings.recordingPath,
protocol: sessionRecordings.protocol,
format: sessionRecordings.format,
hostName: hosts.name,
hostIp: hosts.ip,
})
.from(sessionRecordings)
.leftJoin(hosts, eq(sessionRecordings.hostId, hosts.id))
.where(eq(sessionRecordings.userId, userId))
.orderBy(desc(sessionRecordings.startedAt));
}
async findByIdForUser(
userId: string,
id: number,
): Promise<SessionRecordingRecord | null> {
const rows = await this.context.drizzle
.select()
.from(sessionRecordings)
.where(
and(eq(sessionRecordings.id, id), eq(sessionRecordings.userId, userId)),
)
.limit(1);
return rows[0] ?? null;
}
async findPathByIdForUser(
userId: string,
id: number,
): Promise<SessionRecordingPathRecord | null> {
const rows = await this.context.drizzle
.select({
id: sessionRecordings.id,
recordingPath: sessionRecordings.recordingPath,
})
.from(sessionRecordings)
.where(
and(eq(sessionRecordings.id, id), eq(sessionRecordings.userId, userId)),
)
.limit(1);
return rows[0] ?? null;
}
async listPathsOlderThan(
cutoff: string,
): Promise<SessionRecordingPathRecord[]> {
return this.context.drizzle
.select({
id: sessionRecordings.id,
recordingPath: sessionRecordings.recordingPath,
})
.from(sessionRecordings)
.where(lt(sessionRecordings.startedAt, cutoff));
}
async deleteById(id: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(sessionRecordings)
.where(eq(sessionRecordings.id, id))
.returning({ id: sessionRecordings.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteForUser(userId: string, id: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(sessionRecordings)
.where(
and(eq(sessionRecordings.id, id), eq(sessionRecordings.userId, userId)),
)
.returning({ id: sessionRecordings.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(sessionRecordings)
.where(eq(sessionRecordings.userId, userId))
.returning({ id: sessionRecordings.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByHostId(hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(sessionRecordings)
.where(eq(sessionRecordings.hostId, hostId))
.returning({ id: sessionRecordings.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByHostIds(hostIds: number[]): Promise<number> {
if (hostIds.length === 0) {
return 0;
}
const rows = await this.context.drizzle
.delete(sessionRecordings)
.where(inArray(sessionRecordings.hostId, hostIds))
.returning({ id: sessionRecordings.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,114 @@
import { and, eq, lte, ne } from "drizzle-orm";
import { sessions } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type SessionRecord = typeof sessions.$inferSelect;
export type NewSessionRecord = typeof sessions.$inferInsert;
export class SessionRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async create(session: NewSessionRecord): Promise<SessionRecord> {
const rows = await this.context.drizzle
.insert(sessions)
.values(session)
.returning();
await this.afterWrite();
return rows[0];
}
async listAll(): Promise<SessionRecord[]> {
return this.context.drizzle.select().from(sessions);
}
async findById(id: string): Promise<SessionRecord | null> {
const rows = await this.context.drizzle
.select()
.from(sessions)
.where(eq(sessions.id, id))
.limit(1);
return rows[0] ?? null;
}
async listByUserId(userId: string): Promise<SessionRecord[]> {
return this.context.drizzle
.select()
.from(sessions)
.where(eq(sessions.userId, userId));
}
async listExpired(now = new Date()): Promise<SessionRecord[]> {
return this.context.drizzle
.select()
.from(sessions)
.where(lte(sessions.expiresAt, now.toISOString()));
}
async touch(
id: string,
lastActiveAt = new Date().toISOString(),
): Promise<void> {
await this.context.drizzle
.update(sessions)
.set({ lastActiveAt })
.where(eq(sessions.id, id));
await this.afterWrite();
}
async updateToken(
id: string,
jwtToken: string,
lastActiveAt = new Date().toISOString(),
): Promise<void> {
await this.context.drizzle
.update(sessions)
.set({ jwtToken, lastActiveAt })
.where(eq(sessions.id, id));
await this.afterWrite();
}
async revoke(id: string): Promise<boolean> {
const rows = await this.context.drizzle
.delete(sessions)
.where(eq(sessions.id, id))
.returning({ id: sessions.id });
await this.afterWrite();
return rows.length > 0;
}
async revokeAllForUser(
userId: string,
exceptSessionId?: string,
): Promise<number> {
const where = exceptSessionId
? and(eq(sessions.userId, userId), ne(sessions.id, exceptSessionId))
: eq(sessions.userId, userId);
const rows = await this.context.drizzle
.delete(sessions)
.where(where)
.returning({ id: sessions.id });
await this.afterWrite();
return rows.length;
}
async deleteExpired(now = new Date()): Promise<number> {
const rows = await this.context.drizzle
.delete(sessions)
.where(lte(sessions.expiresAt, now.toISOString()))
.returning({ id: sessions.id });
await this.afterWrite();
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,69 @@
import { eq, like } from "drizzle-orm";
import { settings } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export class SettingsRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async get(key: string): Promise<string | null> {
const rows = await this.context.drizzle
.select({ value: settings.value })
.from(settings)
.where(eq(settings.key, key))
.limit(1);
return rows[0]?.value ?? null;
}
async listAll(): Promise<Array<{ key: string; value: string }>> {
return this.context.drizzle
.select({ key: settings.key, value: settings.value })
.from(settings);
}
async getBoolean(key: string, fallback = false): Promise<boolean> {
const value = await this.get(key);
if (value === null) return fallback;
return value === "true" || value === "1";
}
async set(key: string, value: string): Promise<void> {
const existing = await this.get(key);
if (existing === null) {
await this.context.drizzle.insert(settings).values({ key, value });
await this.afterWrite();
return;
}
await this.context.drizzle
.update(settings)
.set({ value })
.where(eq(settings.key, key));
await this.afterWrite();
}
async upsert(key: string, value: string): Promise<void> {
await this.set(key, value);
}
async delete(key: string): Promise<void> {
await this.context.drizzle.delete(settings).where(eq(settings.key, key));
await this.afterWrite();
}
async deleteLike(pattern: string): Promise<number> {
const rows = await this.context.drizzle
.delete(settings)
.where(like(settings.key, pattern))
.returning({ key: settings.key });
await this.afterWrite();
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,201 @@
import { and, eq, inArray, or } from "drizzle-orm";
import { hostAccess, hosts, sharedHostSecrets } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type SharedHostSecretRecord = typeof sharedHostSecrets.$inferSelect;
export type NewSharedHostSecretRecord = typeof sharedHostSecrets.$inferInsert;
export type ShareProtocol = "ssh" | "rdp" | "vnc" | "telnet";
export class SharedHostSecretsRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async upsert(record: NewSharedHostSecretRecord): Promise<void> {
const existing = await this.context.drizzle
.select({ id: sharedHostSecrets.id })
.from(sharedHostSecrets)
.where(
and(
eq(sharedHostSecrets.hostAccessId, record.hostAccessId),
eq(sharedHostSecrets.targetUserId, record.targetUserId),
eq(sharedHostSecrets.protocol, record.protocol ?? "ssh"),
),
)
.limit(1);
if (existing.length > 0) {
await this.context.drizzle
.update(sharedHostSecrets)
.set({ ...record, updatedAt: new Date().toISOString() })
.where(eq(sharedHostSecrets.id, existing[0].id));
} else {
await this.context.drizzle.insert(sharedHostSecrets).values(record);
}
await this.afterWrite();
}
async findForHostUserProtocol(
hostId: number,
targetUserId: string,
protocol: ShareProtocol,
): Promise<SharedHostSecretRecord | null> {
const rows = await this.context.drizzle
.select({ secret: sharedHostSecrets })
.from(sharedHostSecrets)
.innerJoin(hostAccess, eq(sharedHostSecrets.hostAccessId, hostAccess.id))
.where(
and(
eq(hostAccess.hostId, hostId),
eq(sharedHostSecrets.targetUserId, targetUserId),
eq(sharedHostSecrets.protocol, protocol),
),
)
.limit(1);
return rows[0]?.secret ?? null;
}
async existsForHostAccessAndTargetUser(
hostAccessId: number,
targetUserId: string,
): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: sharedHostSecrets.id })
.from(sharedHostSecrets)
.where(
and(
eq(sharedHostSecrets.hostAccessId, hostAccessId),
eq(sharedHostSecrets.targetUserId, targetUserId),
),
)
.limit(1);
return rows.length > 0;
}
async deleteForHostAccessAndTarget(
hostAccessId: number,
targetUserId: string,
keepProtocols: ShareProtocol[] = [],
): Promise<void> {
const rows = await this.context.drizzle
.select({
id: sharedHostSecrets.id,
protocol: sharedHostSecrets.protocol,
})
.from(sharedHostSecrets)
.where(
and(
eq(sharedHostSecrets.hostAccessId, hostAccessId),
eq(sharedHostSecrets.targetUserId, targetUserId),
),
);
const staleIds = rows
.filter((row) => !keepProtocols.includes(row.protocol as ShareProtocol))
.map((row) => row.id);
if (staleIds.length > 0) {
await this.context.drizzle
.delete(sharedHostSecrets)
.where(inArray(sharedHostSecrets.id, staleIds));
await this.afterWrite();
}
}
async deleteByHostAccessId(hostAccessId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(sharedHostSecrets)
.where(eq(sharedHostSecrets.hostAccessId, hostAccessId))
.returning({ id: sharedHostSecrets.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteForRoleMember(
roleId: number,
targetUserId: string,
): Promise<number> {
const rows = await this.context.drizzle
.select({ id: sharedHostSecrets.id })
.from(sharedHostSecrets)
.innerJoin(hostAccess, eq(sharedHostSecrets.hostAccessId, hostAccess.id))
.where(
and(
eq(hostAccess.roleId, roleId),
eq(sharedHostSecrets.targetUserId, targetUserId),
),
);
if (rows.length === 0) return 0;
await this.context.drizzle.delete(sharedHostSecrets).where(
inArray(
sharedHostSecrets.id,
rows.map((row) => row.id),
),
);
await this.afterWrite();
return rows.length;
}
async deleteByOriginalCredentialId(credentialId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(sharedHostSecrets)
.where(eq(sharedHostSecrets.originalCredentialId, credentialId))
.returning({ id: sharedHostSecrets.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByTargetUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(sharedHostSecrets)
.where(eq(sharedHostSecrets.targetUserId, userId))
.returning({ id: sharedHostSecrets.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async findHostIdsReferencingCredential(
ownerId: string,
credentialId: number,
): Promise<number[]> {
const rows = await this.context.drizzle
.select({ id: hosts.id })
.from(hosts)
.where(
and(
eq(hosts.userId, ownerId),
or(
eq(hosts.credentialId, credentialId),
eq(hosts.rdpCredentialId, credentialId),
eq(hosts.vncCredentialId, credentialId),
eq(hosts.telnetCredentialId, credentialId),
),
),
);
return rows.map((row) => row.id);
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,540 @@
import { and, asc, eq, sql } from "drizzle-orm";
import { snippetFolders, snippets } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type SnippetRecord = typeof snippets.$inferSelect;
export type SnippetFolderRecord = typeof snippetFolders.$inferSelect;
export interface RenameSnippetFolderResult {
status: "renamed" | "missing" | "conflict";
}
export interface SnippetReorderUpdate {
id: number;
order: number;
folder?: string;
}
export interface NewSnippetInput {
name: string;
content: string;
description?: string | null;
folder?: string | null;
order?: number | null;
hostFilter?: unknown;
}
export interface SnippetUpdateInput {
name?: string;
content?: string;
description?: string | null;
folder?: string | null;
order?: number;
hostFilter?: unknown;
}
export interface UpdateSnippetResult {
existing: SnippetRecord;
updated: SnippetRecord;
}
export interface SnippetBulkImportResult {
snippetsImported: number;
snippetsSkipped: number;
snippetsUpdated: number;
foldersImported: number;
foldersSkipped: number;
failed: number;
errors: string[];
}
interface BulkImportSnippetInput {
name?: unknown;
content?: unknown;
description?: string | null;
folder?: string | null;
order?: unknown;
hostFilter?: string | null;
}
interface BulkImportFolderInput {
name?: unknown;
color?: string | null;
icon?: string | null;
}
export class SnippetRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async findOwnedById(
userId: string,
snippetId: number,
): Promise<SnippetRecord | null> {
const rows = await this.context.drizzle
.select()
.from(snippets)
.where(and(eq(snippets.id, snippetId), eq(snippets.userId, userId)))
.limit(1);
return rows[0] ?? null;
}
async listFolders(userId: string): Promise<SnippetFolderRecord[]> {
return this.context.drizzle
.select()
.from(snippetFolders)
.where(eq(snippetFolders.userId, userId))
.orderBy(asc(snippetFolders.name));
}
async listSnippetsForExport(userId: string): Promise<SnippetRecord[]> {
return this.context.drizzle
.select()
.from(snippets)
.where(eq(snippets.userId, userId))
.orderBy(asc(snippets.folder), asc(snippets.order));
}
async listFoldersForExport(userId: string): Promise<SnippetFolderRecord[]> {
return this.listFolders(userId);
}
async listOwnedSnippets(userId: string): Promise<SnippetRecord[]> {
return this.context.drizzle
.select()
.from(snippets)
.where(eq(snippets.userId, userId))
.orderBy(
sql`CASE WHEN ${snippets.folder} IS NULL OR ${snippets.folder} = '' THEN 0 ELSE 1 END`,
asc(snippets.folder),
asc(snippets.order),
sql`${snippets.updatedAt} DESC`,
);
}
async reorderSnippets(
userId: string,
updates: SnippetReorderUpdate[],
): Promise<void> {
for (const update of updates) {
const { id, order, folder } = update;
if (!id || order === undefined) {
continue;
}
const updateFields: Partial<{
order: number;
folder: string | null;
}> = {
order,
};
if (folder !== undefined) {
updateFields.folder = folder?.trim() || null;
}
await this.context.drizzle
.update(snippets)
.set(updateFields)
.where(and(eq(snippets.id, id), eq(snippets.userId, userId)));
}
await this.afterWrite();
}
async createSnippet(
userId: string,
input: NewSnippetInput,
): Promise<SnippetRecord> {
const folderValue = input.folder?.trim() || "";
const order =
input.order === undefined || input.order === null
? await this.nextOrderForFolder(userId, folderValue)
: input.order;
const rows = await this.context.drizzle
.insert(snippets)
.values({
userId,
name: input.name.trim(),
content: input.content.trim(),
description: input.description?.trim() || null,
folder: input.folder?.trim() || null,
order,
hostFilter: input.hostFilter ? JSON.stringify(input.hostFilter) : null,
})
.returning();
await this.afterWrite();
return rows[0];
}
async updateSnippet(
userId: string,
snippetId: number,
input: SnippetUpdateInput,
): Promise<UpdateSnippetResult | null> {
const existing = await this.findOwnedById(userId, snippetId);
if (!existing) return null;
const updateFields: Partial<{
updatedAt: ReturnType<typeof sql>;
name: string;
content: string;
description: string | null;
folder: string | null;
order: number;
hostFilter: string | null;
}> = {
updatedAt: sql`CURRENT_TIMESTAMP`,
};
if (input.name !== undefined) updateFields.name = input.name.trim();
if (input.content !== undefined)
updateFields.content = input.content.trim();
if (input.description !== undefined)
updateFields.description = input.description?.trim() || null;
if (input.folder !== undefined)
updateFields.folder = input.folder?.trim() || null;
if (input.order !== undefined) updateFields.order = input.order;
if (input.hostFilter !== undefined)
updateFields.hostFilter = input.hostFilter
? JSON.stringify(input.hostFilter)
: null;
const rows = await this.context.drizzle
.update(snippets)
.set(updateFields)
.where(and(eq(snippets.id, snippetId), eq(snippets.userId, userId)))
.returning();
await this.afterWrite();
return { existing, updated: rows[0] };
}
async deleteSnippet(
userId: string,
snippetId: number,
): Promise<SnippetRecord | null> {
const existing = await this.findOwnedById(userId, snippetId);
if (!existing) return null;
await this.context.drizzle
.delete(snippets)
.where(and(eq(snippets.id, snippetId), eq(snippets.userId, userId)));
await this.afterWrite();
return existing;
}
async deleteByUserId(userId: string): Promise<{
snippetsDeleted: number;
foldersDeleted: number;
}> {
const deletedSnippets = await this.context.drizzle
.delete(snippets)
.where(eq(snippets.userId, userId))
.returning({ id: snippets.id });
const deletedFolders = await this.context.drizzle
.delete(snippetFolders)
.where(eq(snippetFolders.userId, userId))
.returning({ id: snippetFolders.id });
if (deletedSnippets.length > 0 || deletedFolders.length > 0) {
await this.afterWrite();
}
return {
snippetsDeleted: deletedSnippets.length,
foldersDeleted: deletedFolders.length,
};
}
async bulkImport(
userId: string,
snippetsToImport: unknown[] | undefined,
foldersToImport: unknown[] | undefined,
overwrite: boolean,
): Promise<SnippetBulkImportResult> {
const results: SnippetBulkImportResult = {
snippetsImported: 0,
snippetsSkipped: 0,
snippetsUpdated: 0,
foldersImported: 0,
foldersSkipped: 0,
failed: 0,
errors: [],
};
let changed = false;
if (Array.isArray(foldersToImport)) {
for (const rawFolder of foldersToImport) {
const folder = rawFolder as BulkImportFolderInput;
if (!isNonEmptyString(folder.name)) {
results.failed++;
results.errors.push(`Folder missing name`);
continue;
}
const created = await this.createFolder(
userId,
folder.name,
folder.color,
folder.icon,
false,
);
if (!created) {
results.foldersSkipped++;
continue;
}
changed = true;
results.foldersImported++;
}
}
if (Array.isArray(snippetsToImport)) {
for (let i = 0; i < snippetsToImport.length; i++) {
const snippet = snippetsToImport[i] as BulkImportSnippetInput;
if (
!isNonEmptyString(snippet.name) ||
!isNonEmptyString(snippet.content)
) {
results.failed++;
results.errors.push(
`Snippet ${i + 1}: name and content are required`,
);
continue;
}
const folderVal = snippet.folder?.trim() || null;
const existing = await this.findByNameAndFolder(
userId,
snippet.name.trim(),
folderVal,
);
if (existing) {
if (!overwrite) {
results.snippetsSkipped++;
continue;
}
await this.context.drizzle
.update(snippets)
.set({
content: snippet.content.trim(),
description: snippet.description?.trim() || null,
folder: folderVal,
order:
typeof snippet.order === "number"
? snippet.order
: existing.order,
hostFilter: snippet.hostFilter || null,
updatedAt: sql`CURRENT_TIMESTAMP`,
})
.where(
and(eq(snippets.id, existing.id), eq(snippets.userId, userId)),
);
changed = true;
results.snippetsUpdated++;
continue;
}
const maxOrder = await this.maxOrderForFolder(userId, folderVal);
await this.context.drizzle.insert(snippets).values({
userId,
name: snippet.name.trim(),
content: snippet.content.trim(),
description: snippet.description?.trim() || null,
folder: folderVal,
order:
typeof snippet.order === "number" ? snippet.order : maxOrder + 1,
hostFilter: snippet.hostFilter || null,
});
changed = true;
results.snippetsImported++;
}
}
if (changed) {
await this.afterWrite();
}
return results;
}
async createFolder(
userId: string,
name: string,
color: string | null | undefined,
icon: string | null | undefined,
triggerSave = true,
): Promise<SnippetFolderRecord | null> {
const existing = await this.findFolderByName(userId, name);
if (existing) return null;
const rows = await this.context.drizzle
.insert(snippetFolders)
.values({
userId,
name: name.trim(),
color: color?.trim() || null,
icon: icon?.trim() || null,
})
.returning();
if (triggerSave) {
await this.afterWrite();
}
return rows[0] ?? null;
}
async updateFolderMetadata(
userId: string,
name: string,
color: string | null | undefined,
icon: string | null | undefined,
): Promise<SnippetFolderRecord | null> {
const existing = await this.findFolderByName(userId, name);
if (!existing) return null;
const updateFields: Partial<{
color: string | null;
icon: string | null;
updatedAt: ReturnType<typeof sql>;
}> = {
updatedAt: sql`CURRENT_TIMESTAMP`,
};
if (color !== undefined) updateFields.color = color?.trim() || null;
if (icon !== undefined) updateFields.icon = icon?.trim() || null;
const rows = await this.context.drizzle
.update(snippetFolders)
.set(updateFields)
.where(
and(eq(snippetFolders.userId, userId), eq(snippetFolders.name, name)),
)
.returning();
await this.afterWrite();
return rows[0] ?? null;
}
async renameFolder(
userId: string,
oldName: string,
newName: string,
): Promise<RenameSnippetFolderResult> {
const existing = await this.findFolderByName(userId, oldName);
if (!existing) return { status: "missing" };
const nameExists = await this.findFolderByName(userId, newName);
if (nameExists) return { status: "conflict" };
await this.context.drizzle
.update(snippetFolders)
.set({ name: newName, updatedAt: sql`CURRENT_TIMESTAMP` })
.where(
and(
eq(snippetFolders.userId, userId),
eq(snippetFolders.name, oldName),
),
);
await this.context.drizzle
.update(snippets)
.set({ folder: newName })
.where(and(eq(snippets.userId, userId), eq(snippets.folder, oldName)));
await this.afterWrite();
return { status: "renamed" };
}
async deleteFolder(userId: string, name: string): Promise<void> {
await this.context.drizzle
.update(snippets)
.set({ folder: null })
.where(and(eq(snippets.userId, userId), eq(snippets.folder, name)));
await this.context.drizzle
.delete(snippetFolders)
.where(
and(eq(snippetFolders.userId, userId), eq(snippetFolders.name, name)),
);
await this.afterWrite();
}
private async findFolderByName(
userId: string,
name: string,
): Promise<SnippetFolderRecord | null> {
const rows = await this.context.drizzle
.select()
.from(snippetFolders)
.where(
and(eq(snippetFolders.userId, userId), eq(snippetFolders.name, name)),
)
.limit(1);
return rows[0] ?? null;
}
private async nextOrderForFolder(
userId: string,
folder: string,
): Promise<number> {
return (await this.maxOrderForFolder(userId, folder || null)) + 1;
}
private async maxOrderForFolder(
userId: string,
folder: string | null,
): Promise<number> {
const maxOrderResult = await this.context.drizzle
.select({ maxOrder: sql<number>`MAX(${snippets.order})` })
.from(snippets)
.where(
and(
eq(snippets.userId, userId),
folder
? eq(snippets.folder, folder)
: sql`(${snippets.folder} IS NULL OR ${snippets.folder} = '')`,
),
);
const maxOrder = maxOrderResult[0]?.maxOrder ?? -1;
return maxOrder;
}
private async findByNameAndFolder(
userId: string,
name: string,
folder: string | null,
): Promise<SnippetRecord | null> {
const rows = await this.context.drizzle
.select()
.from(snippets)
.where(
and(
eq(snippets.userId, userId),
eq(snippets.name, name),
folder
? eq(snippets.folder, folder)
: sql`(${snippets.folder} IS NULL OR ${snippets.folder} = '')`,
),
)
.limit(1);
return rows[0] ?? null;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
function isNonEmptyString(value: unknown): value is string {
return typeof value === "string" && value.trim().length > 0;
}
@@ -0,0 +1,23 @@
import { getCurrentRepositorySqlite } from "./factory.js";
export interface SqliteForeignKeyClient {
exec(sql: string): unknown;
}
export async function withSqliteForeignKeysDisabled<T>(
sqlite: SqliteForeignKeyClient,
operation: () => Promise<T>,
): Promise<T> {
sqlite.exec("PRAGMA foreign_keys = OFF");
try {
return await operation();
} finally {
sqlite.exec("PRAGMA foreign_keys = ON");
}
}
export async function withCurrentSqliteForeignKeysDisabled<T>(
operation: () => Promise<T>,
): Promise<T> {
return withSqliteForeignKeysDisabled(getCurrentRepositorySqlite(), operation);
}
@@ -0,0 +1,79 @@
import { eq, inArray } from "drizzle-orm";
import { sshCredentialUsage } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type SshCredentialUsageRecord = typeof sshCredentialUsage.$inferSelect;
export class SshCredentialUsageRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listByUserId(userId: string): Promise<SshCredentialUsageRecord[]> {
return this.context.drizzle
.select()
.from(sshCredentialUsage)
.where(eq(sshCredentialUsage.userId, userId));
}
async create(
credentialId: number,
hostId: number,
userId: string,
): Promise<SshCredentialUsageRecord> {
const [created] = await this.context.drizzle
.insert(sshCredentialUsage)
.values({ credentialId, hostId, userId })
.returning();
await this.afterWrite();
return created;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(sshCredentialUsage)
.where(eq(sshCredentialUsage.userId, userId))
.returning({ id: sshCredentialUsage.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByHostId(hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(sshCredentialUsage)
.where(eq(sshCredentialUsage.hostId, hostId))
.returning({ id: sshCredentialUsage.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByHostIds(hostIds: number[]): Promise<number> {
if (hostIds.length === 0) {
return 0;
}
const rows = await this.context.drizzle
.delete(sshCredentialUsage)
.where(inArray(sshCredentialUsage.hostId, hostIds))
.returning({ id: sshCredentialUsage.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,127 @@
import { asc, eq } from "drizzle-orm";
import { ssoProviders, users } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type SsoProviderRecord = typeof ssoProviders.$inferSelect;
export type NewSsoProviderRecord = typeof ssoProviders.$inferInsert;
export type SsoProviderUpdate = Partial<
Pick<
NewSsoProviderRecord,
"name" | "type" | "enabled" | "displayOrder" | "config" | "updatedAt"
>
>;
export type PublicSsoProviderRecord = Pick<
SsoProviderRecord,
"id" | "name" | "type" | "displayOrder"
>;
export class SsoProviderRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listEnabledPublic(): Promise<PublicSsoProviderRecord[]> {
return this.context.drizzle
.select({
id: ssoProviders.id,
name: ssoProviders.name,
type: ssoProviders.type,
displayOrder: ssoProviders.displayOrder,
})
.from(ssoProviders)
.where(eq(ssoProviders.enabled, true))
.orderBy(asc(ssoProviders.displayOrder), asc(ssoProviders.id));
}
async listEnabled(): Promise<SsoProviderRecord[]> {
return this.context.drizzle
.select()
.from(ssoProviders)
.where(eq(ssoProviders.enabled, true))
.orderBy(asc(ssoProviders.displayOrder), asc(ssoProviders.id));
}
async listAll(): Promise<SsoProviderRecord[]> {
return this.context.drizzle
.select()
.from(ssoProviders)
.orderBy(asc(ssoProviders.displayOrder), asc(ssoProviders.id));
}
async findById(id: number): Promise<SsoProviderRecord | null> {
const rows = await this.context.drizzle
.select()
.from(ssoProviders)
.where(eq(ssoProviders.id, id))
.limit(1);
return rows[0] ?? null;
}
async findFirstEnabledOidcLike(): Promise<SsoProviderRecord | null> {
const rows = await this.context.drizzle
.select()
.from(ssoProviders)
.where(eq(ssoProviders.enabled, true))
.orderBy(asc(ssoProviders.displayOrder), asc(ssoProviders.id));
return (
rows.find(
(row) =>
row.type === "oidc" || row.type === "github" || row.type === "google",
) ?? null
);
}
async create(provider: NewSsoProviderRecord): Promise<SsoProviderRecord> {
const rows = await this.context.drizzle
.insert(ssoProviders)
.values(provider)
.returning();
await this.afterWrite();
return rows[0];
}
async update(
id: number,
update: SsoProviderUpdate,
): Promise<SsoProviderRecord | null> {
const rows = await this.context.drizzle
.update(ssoProviders)
.set(update)
.where(eq(ssoProviders.id, id))
.returning();
await this.afterWrite();
return rows[0] ?? null;
}
async delete(id: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(ssoProviders)
.where(eq(ssoProviders.id, id))
.returning({ id: ssoProviders.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async countUsersByProviderId(providerId: number): Promise<number> {
const rows = await this.context.drizzle
.select({ id: users.id })
.from(users)
.where(eq(users.ssoProviderId, providerId));
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,163 @@
import { eq } from "drizzle-orm";
import { termixIdentityCa } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
import { DataCrypto } from "../../utils/data-crypto.js";
export type TermixIdentityCaRecord = typeof termixIdentityCa.$inferSelect;
export type NewTermixIdentityCaRecord = typeof termixIdentityCa.$inferInsert;
export type TermixIdentityCaUpdate = Partial<
Pick<
NewTermixIdentityCaRecord,
"publicKey" | "privateKey" | "validityDays" | "updatedAt"
>
>;
export class TermixIdentityCaRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async findPublicByIdentityId(
identityId: number,
): Promise<Pick<
TermixIdentityCaRecord,
"publicKey" | "validityDays"
> | null> {
const rows = await this.context.drizzle
.select({
publicKey: termixIdentityCa.publicKey,
validityDays: termixIdentityCa.validityDays,
})
.from(termixIdentityCa)
.where(eq(termixIdentityCa.identityId, identityId))
.limit(1);
return rows[0] ?? null;
}
async findDecryptedByIdentityId(
userId: string,
identityId: number,
): Promise<TermixIdentityCaRecord | null> {
const rows = await this.context.drizzle
.select()
.from(termixIdentityCa)
.where(eq(termixIdentityCa.identityId, identityId))
.limit(1);
return this.decryptOne(rows[0] ?? null, userId);
}
async createEncryptedForUser(
userId: string,
ca: NewTermixIdentityCaRecord,
): Promise<TermixIdentityCaRecord> {
const userDataKey = DataCrypto.validateUserAccess(userId);
const result = this.context.drizzle.transaction((tx) => {
const inserted = tx
.insert(termixIdentityCa)
.values({ ...ca, privateKey: "" })
.returning()
.all();
const row = inserted[0];
const encrypted = DataCrypto.encryptRecord(
"termix_identity_ca",
{ id: row.id, privateKey: ca.privateKey },
userId,
userDataKey,
);
return tx
.update(termixIdentityCa)
.set({ privateKey: encrypted.privateKey })
.where(eq(termixIdentityCa.id, row.id))
.returning()
.all()[0];
});
await this.afterWrite();
return DataCrypto.decryptRecord(
"termix_identity_ca",
result,
userId,
userDataKey,
);
}
async updateEncryptedForIdentity(
userId: string,
identityId: number,
update: TermixIdentityCaUpdate,
): Promise<TermixIdentityCaRecord | null> {
const existing = await this.findDecryptedByIdentityId(userId, identityId);
if (!existing) return null;
const userDataKey = DataCrypto.validateUserAccess(userId);
const encryptedPrivateKey = update.privateKey
? DataCrypto.encryptRecord(
"termix_identity_ca",
{ id: existing.id, privateKey: update.privateKey },
userId,
userDataKey,
).privateKey
: undefined;
const rows = await this.context.drizzle
.update(termixIdentityCa)
.set({
...update,
...(encryptedPrivateKey ? { privateKey: encryptedPrivateKey } : {}),
})
.where(eq(termixIdentityCa.identityId, identityId))
.returning();
await this.afterWrite();
return this.decryptOne(rows[0] ?? null, userId);
}
async deleteByIdentityId(identityId: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(termixIdentityCa)
.where(eq(termixIdentityCa.identityId, identityId))
.returning({ id: termixIdentityCa.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(termixIdentityCa)
.where(eq(termixIdentityCa.userId, userId))
.returning({ id: termixIdentityCa.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private decryptOne<T extends Record<string, unknown>>(
record: T | null,
userId: string,
): T | null {
if (!record) return null;
const userDataKey = DataCrypto.getUserDataKey(userId);
if (!userDataKey) return null;
return DataCrypto.decryptRecord(
"termix_identity_ca",
record,
userId,
userDataKey,
);
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,244 @@
import { and, asc, eq } from "drizzle-orm";
import { termixIdentities, termixIdentityKeys } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type TermixIdentityRecord = typeof termixIdentities.$inferSelect;
export type NewTermixIdentityRecord = typeof termixIdentities.$inferInsert;
export type TermixIdentityUpdate = Partial<
Pick<NewTermixIdentityRecord, "handle" | "description" | "updatedAt">
>;
export type TermixIdentityKeyRecord = typeof termixIdentityKeys.$inferSelect;
export type NewTermixIdentityKeyRecord = typeof termixIdentityKeys.$inferInsert;
export type TermixIdentityKeyUpdate = Partial<
Pick<NewTermixIdentityKeyRecord, "enabled" | "label">
>;
export class TermixIdentityRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async findIdentityForUser(
userId: string,
): Promise<TermixIdentityRecord | null> {
const rows = await this.context.drizzle
.select()
.from(termixIdentities)
.where(eq(termixIdentities.userId, userId))
.limit(1);
return rows[0] ?? null;
}
async findIdentityByHandle(
handle: string,
): Promise<TermixIdentityRecord | null> {
const rows = await this.context.drizzle
.select()
.from(termixIdentities)
.where(eq(termixIdentities.handle, handle))
.limit(1);
return rows[0] ?? null;
}
async isHandleTaken(handle: string): Promise<boolean> {
const rows = await this.context.drizzle
.select({ id: termixIdentities.id })
.from(termixIdentities)
.where(eq(termixIdentities.handle, handle))
.limit(1);
return rows.length > 0;
}
async createIdentity(
identity: NewTermixIdentityRecord,
): Promise<TermixIdentityRecord> {
const rows = await this.context.drizzle
.insert(termixIdentities)
.values(identity)
.returning();
await this.afterWrite();
return rows[0];
}
async updateIdentityForUser(
userId: string,
update: TermixIdentityUpdate,
): Promise<TermixIdentityRecord | null> {
const rows = await this.context.drizzle
.update(termixIdentities)
.set(update)
.where(eq(termixIdentities.userId, userId))
.returning();
if (rows.length > 0) {
await this.afterWrite();
}
return rows[0] ?? null;
}
async deleteIdentityForUser(userId: string): Promise<boolean> {
const rows = await this.context.drizzle
.delete(termixIdentities)
.where(eq(termixIdentities.userId, userId))
.returning({ id: termixIdentities.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<{
identitiesDeleted: number;
keysDeleted: number;
}> {
const keyRows = await this.context.drizzle
.delete(termixIdentityKeys)
.where(eq(termixIdentityKeys.userId, userId))
.returning({ id: termixIdentityKeys.id });
const identityRows = await this.context.drizzle
.delete(termixIdentities)
.where(eq(termixIdentities.userId, userId))
.returning({ id: termixIdentities.id });
if (keyRows.length > 0 || identityRows.length > 0) {
await this.afterWrite();
}
return {
identitiesDeleted: identityRows.length,
keysDeleted: keyRows.length,
};
}
async listKeysByIdentityId(
identityId: number,
): Promise<TermixIdentityKeyRecord[]> {
return this.context.drizzle
.select()
.from(termixIdentityKeys)
.where(eq(termixIdentityKeys.identityId, identityId))
.orderBy(asc(termixIdentityKeys.id));
}
async listEnabledKeysByIdentityId(
identityId: number,
): Promise<TermixIdentityKeyRecord[]> {
return this.context.drizzle
.select()
.from(termixIdentityKeys)
.where(
and(
eq(termixIdentityKeys.identityId, identityId),
eq(termixIdentityKeys.enabled, true),
),
)
.orderBy(asc(termixIdentityKeys.id));
}
async listLinkedCredentialIds(identityId: number): Promise<number[]> {
const rows = await this.context.drizzle
.select({ credentialId: termixIdentityKeys.credentialId })
.from(termixIdentityKeys)
.where(
and(
eq(termixIdentityKeys.identityId, identityId),
eq(termixIdentityKeys.enabled, true),
),
);
return Array.from(
new Set(
rows
.map((row) => row.credentialId)
.filter(
(credentialId): credentialId is number => credentialId !== null,
),
),
);
}
async createKey(
key: NewTermixIdentityKeyRecord,
): Promise<TermixIdentityKeyRecord> {
const rows = await this.context.drizzle
.insert(termixIdentityKeys)
.values(key)
.returning();
await this.afterWrite();
return rows[0];
}
async updateKeyForUser(
userId: string,
id: number,
update: TermixIdentityKeyUpdate,
): Promise<TermixIdentityKeyRecord | null> {
const rows = await this.context.drizzle
.update(termixIdentityKeys)
.set(update)
.where(
and(
eq(termixIdentityKeys.id, id),
eq(termixIdentityKeys.userId, userId),
),
)
.returning();
if (rows.length > 0) {
await this.afterWrite();
}
return rows[0] ?? null;
}
async deleteKeyForUser(userId: string, id: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(termixIdentityKeys)
.where(
and(
eq(termixIdentityKeys.id, id),
eq(termixIdentityKeys.userId, userId),
),
)
.returning({ id: termixIdentityKeys.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async findKeyForUser(
userId: string,
id: number,
): Promise<TermixIdentityKeyRecord | null> {
const rows = await this.context.drizzle
.select()
.from(termixIdentityKeys)
.where(
and(
eq(termixIdentityKeys.id, id),
eq(termixIdentityKeys.userId, userId),
),
)
.limit(1);
return rows[0] ?? null;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,139 @@
import { and, eq } from "drizzle-orm";
import { tmuxSessionTags } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type TmuxSessionTagRecord = typeof tmuxSessionTags.$inferSelect;
export interface TmuxSessionTagInput {
userId: string;
hostId: number;
sessionName: string;
tag: string;
}
export class TmuxSessionTagRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listByUserAndHost(
userId: string,
hostId: number,
): Promise<Map<string, string[]>> {
const rows = await this.context.drizzle
.select()
.from(tmuxSessionTags)
.where(
and(
eq(tmuxSessionTags.userId, userId),
eq(tmuxSessionTags.hostId, hostId),
),
);
const bySession = new Map<string, string[]>();
for (const row of rows) {
const tags = bySession.get(row.sessionName) ?? [];
tags.push(row.tag);
bySession.set(row.sessionName, tags);
}
return bySession;
}
async renameSessionForHost(
hostId: number,
sessionName: string,
newSessionName: string,
): Promise<number> {
const rows = await this.context.drizzle
.update(tmuxSessionTags)
.set({ sessionName: newSessionName })
.where(
and(
eq(tmuxSessionTags.hostId, hostId),
eq(tmuxSessionTags.sessionName, sessionName),
),
)
.returning({ id: tmuxSessionTags.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteSessionForHost(
hostId: number,
sessionName: string,
): Promise<number> {
const rows = await this.context.drizzle
.delete(tmuxSessionTags)
.where(
and(
eq(tmuxSessionTags.hostId, hostId),
eq(tmuxSessionTags.sessionName, sessionName),
),
)
.returning({ id: tmuxSessionTags.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async replaceForUserHostSession(
userId: string,
hostId: number,
sessionName: string,
tags: string[],
): Promise<number> {
const deletedRows = await this.context.drizzle
.delete(tmuxSessionTags)
.where(
and(
eq(tmuxSessionTags.userId, userId),
eq(tmuxSessionTags.hostId, hostId),
eq(tmuxSessionTags.sessionName, sessionName),
),
)
.returning({ id: tmuxSessionTags.id });
if (tags.length > 0) {
await this.context.drizzle.insert(tmuxSessionTags).values(
tags.map((tag) => ({
userId,
hostId,
sessionName,
tag,
})),
);
}
const changedRows = deletedRows.length + tags.length;
if (changedRows > 0) {
await this.afterWrite();
}
return changedRows;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(tmuxSessionTags)
.where(eq(tmuxSessionTags.userId, userId))
.returning({ id: tmuxSessionTags.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,171 @@
import { and, desc, eq, inArray, or } from "drizzle-orm";
import { transferRecent } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type TransferRecentRecord = typeof transferRecent.$inferSelect;
export interface TransferRecentDestinationInput {
sourceHostId: number;
destHostId: number;
destPath: string;
destPathLabel?: string | null;
}
export class TransferRecentRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listByUserId(userId: string): Promise<TransferRecentRecord[]> {
return this.context.drizzle
.select()
.from(transferRecent)
.where(eq(transferRecent.userId, userId));
}
async listBySourceHost(
userId: string,
sourceHostId: number,
limit = 10,
): Promise<TransferRecentRecord[]> {
return this.context.drizzle
.select()
.from(transferRecent)
.where(
and(
eq(transferRecent.userId, userId),
eq(transferRecent.sourceHostId, sourceHostId),
),
)
.orderBy(desc(transferRecent.lastUsed))
.limit(limit);
}
async upsertForDestination(
userId: string,
input: TransferRecentDestinationInput,
lastUsed = new Date().toISOString(),
): Promise<void> {
const [existing] = await this.context.drizzle
.select({ id: transferRecent.id })
.from(transferRecent)
.where(
and(
eq(transferRecent.userId, userId),
eq(transferRecent.sourceHostId, input.sourceHostId),
eq(transferRecent.destHostId, input.destHostId),
eq(transferRecent.destPath, input.destPath),
),
)
.limit(1);
if (existing) {
await this.context.drizzle
.update(transferRecent)
.set({ lastUsed })
.where(eq(transferRecent.id, existing.id));
} else {
await this.context.drizzle.insert(transferRecent).values({
userId,
sourceHostId: input.sourceHostId,
destHostId: input.destHostId,
destPath: input.destPath,
destPathLabel: input.destPathLabel || input.destPath,
lastUsed,
});
}
await this.afterWrite();
}
async pruneSourceHost(
userId: string,
sourceHostId: number,
keep = 10,
): Promise<number> {
const rows = await this.context.drizzle
.select({ id: transferRecent.id })
.from(transferRecent)
.where(
and(
eq(transferRecent.userId, userId),
eq(transferRecent.sourceHostId, sourceHostId),
),
)
.orderBy(desc(transferRecent.lastUsed));
const idsToDelete = rows.slice(keep).map((row) => row.id);
if (idsToDelete.length === 0) {
return 0;
}
const deleted = await this.context.drizzle
.delete(transferRecent)
.where(inArray(transferRecent.id, idsToDelete))
.returning({ id: transferRecent.id });
if (deleted.length > 0) {
await this.afterWrite();
}
return deleted.length;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(transferRecent)
.where(eq(transferRecent.userId, userId))
.returning({ id: transferRecent.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByHostId(hostId: number): Promise<number> {
const rows = await this.context.drizzle
.delete(transferRecent)
.where(
or(
eq(transferRecent.sourceHostId, hostId),
eq(transferRecent.destHostId, hostId),
),
)
.returning({ id: transferRecent.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
async deleteByHostIds(hostIds: number[]): Promise<number> {
if (hostIds.length === 0) {
return 0;
}
const rows = await this.context.drizzle
.delete(transferRecent)
.where(
or(
inArray(transferRecent.sourceHostId, hostIds),
inArray(transferRecent.destHostId, hostIds),
),
)
.returning({ id: transferRecent.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,100 @@
import { and, eq } from "drizzle-orm";
import { trustedDevices } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type TrustedDeviceRecord = typeof trustedDevices.$inferSelect;
export type NewTrustedDeviceRecord = typeof trustedDevices.$inferInsert;
export class TrustedDeviceRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async findByUserAndFingerprint(
userId: string,
deviceFingerprint: string,
): Promise<TrustedDeviceRecord | null> {
const rows = await this.context.drizzle
.select()
.from(trustedDevices)
.where(
and(
eq(trustedDevices.userId, userId),
eq(trustedDevices.deviceFingerprint, deviceFingerprint),
),
)
.limit(1);
return rows[0] ?? null;
}
async touch(
userId: string,
deviceFingerprint: string,
lastUsedAt = new Date().toISOString(),
): Promise<void> {
await this.context.drizzle
.update(trustedDevices)
.set({ lastUsedAt })
.where(
and(
eq(trustedDevices.userId, userId),
eq(trustedDevices.deviceFingerprint, deviceFingerprint),
),
);
await this.afterWrite();
}
async upsert(device: NewTrustedDeviceRecord): Promise<void> {
const existing = await this.findByUserAndFingerprint(
device.userId,
device.deviceFingerprint,
);
if (existing) {
await this.context.drizzle
.update(trustedDevices)
.set({
expiresAt: device.expiresAt,
lastUsedAt: device.lastUsedAt,
})
.where(
and(
eq(trustedDevices.userId, device.userId),
eq(trustedDevices.deviceFingerprint, device.deviceFingerprint),
),
);
} else {
await this.context.drizzle.insert(trustedDevices).values(device);
}
await this.afterWrite();
}
async deleteByUserAndFingerprint(
userId: string,
deviceFingerprint: string,
): Promise<void> {
await this.context.drizzle
.delete(trustedDevices)
.where(
and(
eq(trustedDevices.userId, userId),
eq(trustedDevices.deviceFingerprint, deviceFingerprint),
),
);
await this.afterWrite();
}
async deleteByUserId(userId: string): Promise<void> {
await this.context.drizzle
.delete(trustedDevices)
.where(eq(trustedDevices.userId, userId));
await this.afterWrite();
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,26 @@
import { eq } from "drizzle-orm";
import { hosts, sshCredentials } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type UserDataExportHostRecord = typeof hosts.$inferSelect;
export type UserDataExportCredentialRecord = typeof sshCredentials.$inferSelect;
export class UserDataExportRepository {
constructor(private readonly context: DatabaseContext) {}
async listHostsByUserId(userId: string): Promise<UserDataExportHostRecord[]> {
return this.context.drizzle
.select()
.from(hosts)
.where(eq(hosts.userId, userId));
}
async listCredentialsByUserId(
userId: string,
): Promise<UserDataExportCredentialRecord[]> {
return this.context.drizzle
.select()
.from(sshCredentials)
.where(eq(sshCredentials.userId, userId));
}
}
@@ -0,0 +1,67 @@
import { eq } from "drizzle-orm";
import { userPreferences } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type UserPreferenceRecord = typeof userPreferences.$inferSelect;
export type NewUserPreferenceRecord = typeof userPreferences.$inferInsert;
export type UserPreferenceUpdate = Partial<
Omit<NewUserPreferenceRecord, "userId">
>;
export class UserPreferenceRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async findByUserId(userId: string): Promise<UserPreferenceRecord | null> {
const rows = await this.context.drizzle
.select()
.from(userPreferences)
.where(eq(userPreferences.userId, userId))
.limit(1);
return rows[0] ?? null;
}
async upsert(
userId: string,
update: UserPreferenceUpdate,
): Promise<UserPreferenceRecord> {
const existing = await this.findByUserId(userId);
if (!existing) {
const rows = await this.context.drizzle
.insert(userPreferences)
.values({ userId, ...update })
.returning();
await this.afterWrite();
return rows[0];
}
const rows = await this.context.drizzle
.update(userPreferences)
.set(update)
.where(eq(userPreferences.userId, userId))
.returning();
await this.afterWrite();
return rows[0];
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(userPreferences)
.where(eq(userPreferences.userId, userId))
.returning({ userId: userPreferences.userId });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,161 @@
import { eq, inArray } from "drizzle-orm";
import { users } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type UserRecord = typeof users.$inferSelect;
export type NewUserRecord = typeof users.$inferInsert;
export type UserUpdate = Partial<Omit<NewUserRecord, "id">>;
export type NewFirstLocalUserRecord = Omit<NewUserRecord, "isAdmin">;
export class UserRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listAll(): Promise<UserRecord[]> {
return this.context.drizzle.select().from(users);
}
async findById(id: string): Promise<UserRecord | null> {
const rows = await this.context.drizzle
.select()
.from(users)
.where(eq(users.id, id))
.limit(1);
return rows[0] ?? null;
}
async findByUsername(username: string): Promise<UserRecord | null> {
const rows = await this.context.drizzle
.select()
.from(users)
.where(eq(users.username, username))
.limit(1);
return rows[0] ?? null;
}
async findByOidcIdentifier(
oidcIdentifier: string,
): Promise<UserRecord | null> {
const rows = await this.context.drizzle
.select()
.from(users)
.where(eq(users.oidcIdentifier, oidcIdentifier))
.limit(1);
return rows[0] ?? null;
}
async listByIds(ids: string[]): Promise<UserRecord[]> {
const uniqueIds = Array.from(new Set(ids.filter(Boolean)));
if (uniqueIds.length === 0) {
return [];
}
return this.context.drizzle
.select()
.from(users)
.where(inArray(users.id, uniqueIds));
}
async create(user: NewUserRecord): Promise<UserRecord> {
const rows = await this.context.drizzle
.insert(users)
.values(user)
.returning();
await this.afterWrite();
return rows[0];
}
async createFirstLocalUser(
user: NewFirstLocalUserRecord,
): Promise<{ user: UserRecord; isFirstUser: boolean }> {
const result = this.context.drizzle.transaction((tx) => {
const existingUsers = tx.select({ id: users.id }).from(users).all();
const isFirstUser = existingUsers.length === 0;
const rows = tx
.insert(users)
.values({ ...user, isAdmin: isFirstUser })
.returning()
.all();
return { user: rows[0], isFirstUser };
});
await this.afterWrite();
return result;
}
async createFirstSsoUser(
user: NewUserRecord,
): Promise<{ user: UserRecord; isFirstUser: boolean }> {
const result = this.context.drizzle.transaction((tx) => {
const existingUsers = tx.select({ id: users.id }).from(users).all();
const isFirstUser = existingUsers.length === 0;
const rows = tx
.insert(users)
.values({ ...user, isAdmin: isFirstUser || Boolean(user.isAdmin) })
.returning()
.all();
return { user: rows[0], isFirstUser };
});
await this.afterWrite();
return result;
}
async update(id: string, update: UserUpdate): Promise<UserRecord | null> {
const rows = await this.context.drizzle
.update(users)
.set(update)
.where(eq(users.id, id))
.returning();
await this.afterWrite();
return rows[0] ?? null;
}
async delete(id: string): Promise<boolean> {
const rows = await this.context.drizzle
.delete(users)
.where(eq(users.id, id))
.returning({ id: users.id });
await this.afterWrite();
return rows.length > 0;
}
async countAdmins(): Promise<number> {
const rows = await this.context.drizzle
.select({ id: users.id })
.from(users)
.where(eq(users.isAdmin, true));
return rows.length;
}
async countTotpEnabled(): Promise<number> {
const rows = await this.context.drizzle
.select({ id: users.id })
.from(users)
.where(eq(users.totpEnabled, true));
return rows.length;
}
async countAll(): Promise<number> {
const rows = await this.context.drizzle
.select({ id: users.id })
.from(users);
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,130 @@
import { desc, eq, or } from "drizzle-orm";
import { vaultProfiles } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type VaultProfileRecord = typeof vaultProfiles.$inferSelect;
export interface VaultProfileCreateInput {
userId: string;
name: string;
description?: string | null;
folder?: string | null;
tags?: string | null;
vaultAddr: string;
vaultNamespace?: string | null;
oidcMount?: string | null;
oidcRole?: string | null;
sshMount?: string | null;
sshRole: string;
validPrincipals?: string | null;
keyType?: string | null;
shared?: boolean;
}
export type VaultProfileUpdateInput = Partial<
Omit<VaultProfileCreateInput, "userId">
> & {
updatedAt?: string;
};
export class VaultProfileRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listVisibleToUser(userId: string): Promise<VaultProfileRecord[]> {
return this.context.drizzle
.select()
.from(vaultProfiles)
.where(
or(eq(vaultProfiles.userId, userId), eq(vaultProfiles.shared, true)),
)
.orderBy(desc(vaultProfiles.updatedAt));
}
async create(input: VaultProfileCreateInput): Promise<VaultProfileRecord> {
const [created] = await this.context.drizzle
.insert(vaultProfiles)
.values({
userId: input.userId,
name: input.name,
description: input.description,
folder: input.folder,
tags: input.tags,
vaultAddr: input.vaultAddr,
vaultNamespace: input.vaultNamespace,
oidcMount: input.oidcMount,
oidcRole: input.oidcRole,
sshMount: input.sshMount,
sshRole: input.sshRole,
validPrincipals: input.validPrincipals,
keyType: input.keyType,
shared: input.shared ?? false,
})
.returning();
await this.afterWrite();
return created;
}
async findById(id: number): Promise<VaultProfileRecord | null> {
const rows = await this.context.drizzle
.select()
.from(vaultProfiles)
.where(eq(vaultProfiles.id, id))
.limit(1);
return rows[0] ?? null;
}
async updateById(
id: number,
input: VaultProfileUpdateInput,
): Promise<VaultProfileRecord | null> {
const [updated] = await this.context.drizzle
.update(vaultProfiles)
.set({
...input,
updatedAt: input.updatedAt ?? new Date().toISOString(),
})
.where(eq(vaultProfiles.id, id))
.returning();
if (updated) {
await this.afterWrite();
}
return updated ?? null;
}
async deleteById(id: number): Promise<boolean> {
const rows = await this.context.drizzle
.delete(vaultProfiles)
.where(eq(vaultProfiles.id, id))
.returning({ id: vaultProfiles.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(vaultProfiles)
.where(eq(vaultProfiles.userId, userId))
.returning({ id: vaultProfiles.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,125 @@
import { and, eq } from "drizzle-orm";
import { vaultTokens } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type VaultTokenRecord = typeof vaultTokens.$inferSelect;
export interface VaultTokenUpsertInput {
userId: string;
profileId: number;
sshCert: string;
privateKey: string;
expiresAt: string;
createdAt?: string;
}
export class VaultTokenRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async upsert(input: VaultTokenUpsertInput): Promise<void> {
const createdAt = input.createdAt ?? new Date().toISOString();
await this.context.drizzle
.insert(vaultTokens)
.values({
userId: input.userId,
profileId: input.profileId,
sshCert: input.sshCert,
privateKey: input.privateKey,
expiresAt: input.expiresAt,
})
.onConflictDoUpdate({
target: [vaultTokens.userId, vaultTokens.profileId],
set: {
sshCert: input.sshCert,
privateKey: input.privateKey,
expiresAt: input.expiresAt,
createdAt,
},
});
await this.afterWrite();
}
async findByUserAndProfile(
userId: string,
profileId: number,
): Promise<VaultTokenRecord | null> {
const rows = await this.context.drizzle
.select()
.from(vaultTokens)
.where(
and(
eq(vaultTokens.userId, userId),
eq(vaultTokens.profileId, profileId),
),
)
.limit(1);
return rows[0] ?? null;
}
async updateLastUsed(
userId: string,
profileId: number,
lastUsed = new Date().toISOString(),
): Promise<boolean> {
const rows = await this.context.drizzle
.update(vaultTokens)
.set({ lastUsed })
.where(
and(
eq(vaultTokens.userId, userId),
eq(vaultTokens.profileId, profileId),
),
)
.returning({ id: vaultTokens.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserAndProfile(
userId: string,
profileId: number,
): Promise<boolean> {
const rows = await this.context.drizzle
.delete(vaultTokens)
.where(
and(
eq(vaultTokens.userId, userId),
eq(vaultTokens.profileId, profileId),
),
)
.returning({ id: vaultTokens.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
async deleteByUserId(userId: string): Promise<number> {
const rows = await this.context.drizzle
.delete(vaultTokens)
.where(eq(vaultTokens.userId, userId))
.returning({ id: vaultTokens.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}
@@ -0,0 +1,86 @@
import { and, eq } from "drizzle-orm";
import { webauthnCredentials } from "../db/schema.js";
import type { DatabaseContext } from "./database-context.js";
export type WebauthnCredentialRecord = typeof webauthnCredentials.$inferSelect;
export type NewWebauthnCredentialRecord =
typeof webauthnCredentials.$inferInsert;
export interface WebauthnCredentialAuthState {
counter: number;
backedUp: boolean;
deviceType: string | null;
lastUsedAt: string;
}
export class WebauthnCredentialRepository {
constructor(
private readonly context: DatabaseContext,
private readonly onWrite?: () => void | Promise<void>,
) {}
async listByUserId(userId: string): Promise<WebauthnCredentialRecord[]> {
return this.context.drizzle
.select()
.from(webauthnCredentials)
.where(eq(webauthnCredentials.userId, userId));
}
async findByCredentialId(
credentialId: string,
): Promise<WebauthnCredentialRecord | null> {
const rows = await this.context.drizzle
.select()
.from(webauthnCredentials)
.where(eq(webauthnCredentials.credentialId, credentialId))
.limit(1);
return rows[0] ?? null;
}
async create(
record: NewWebauthnCredentialRecord,
): Promise<WebauthnCredentialRecord> {
const rows = await this.context.drizzle
.insert(webauthnCredentials)
.values(record)
.returning();
await this.afterWrite();
return rows[0];
}
async updateAuthState(
id: string,
state: WebauthnCredentialAuthState,
): Promise<void> {
await this.context.drizzle
.update(webauthnCredentials)
.set(state)
.where(eq(webauthnCredentials.id, id));
await this.afterWrite();
}
async deleteForUser(userId: string, id: string): Promise<boolean> {
const rows = await this.context.drizzle
.delete(webauthnCredentials)
.where(
and(
eq(webauthnCredentials.id, id),
eq(webauthnCredentials.userId, userId),
),
)
.returning({ id: webauthnCredentials.id });
if (rows.length > 0) {
await this.afterWrite();
}
return rows.length > 0;
}
private async afterWrite(): Promise<void> {
await this.onWrite?.();
}
}