Skip to content

Self-hosted, plugin-based server management.

v2.3.2 (#874)

Luke Gustafson52f4e51ae03b
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
index 6a176eff1..4851ec5c5 100644
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@ -14,6 +14,16 @@ on:
options:
- Development
- Production
+ workflow_call:
+ inputs:
+ version:
+ description: "Version to build (e.g., 1.8.0)"
+ required: true
+ type: string
+ build_type:
+ description: "Build type (Development or Production)"
+ required: true
+ type: string
jobs:
build:
@@ -35,8 +45,8 @@ jobs:
- name: Determine tags
id: tags
run: |
- VERSION=${{ github.event.inputs.version }}
- BUILD_TYPE=${{ github.event.inputs.build_type }}
+ VERSION=${{ inputs.version }}
+ BUILD_TYPE=${{ inputs.build_type }}
TAGS=()
ALL_TAGS=()
@@ -64,7 +74,7 @@ jobs:
password: ${{ secrets.GHCR_TOKEN }}
- name: Login to Docker Hub (prod only)
- if: ${{ github.event.inputs.build_type == 'Production' }}
+ if: ${{ inputs.build_type == 'Production' }}
uses: docker/login-action@v4
with:
username: bugattiguy527
diff --git a/.github/workflows/electron.yml b/.github/workflows/electron.yml
index 186a3e8ef..c822dc14c 100644
--- a/.github/workflows/electron.yml
+++ b/.github/workflows/electron.yml
@@ -23,11 +23,30 @@ on:
- file
- release
- submit
+ workflow_call:
+ inputs:
+ build_type:
+ description: "Platform to build for (all, windows, linux, macos)"
+ required: true
+ type: string
+ artifact_destination:
+ description: "What to do with the built app (none, file, release, submit)"
+ required: true
+ type: string
+ release_tag:
+ description: "Explicit release tag to upload assets to (defaults to latest release when empty)"
+ required: false
+ type: string
+ default: ""
+ outputs:
+ macos_universal_dmg_sha256:
+ description: "SHA256 of the universal macOS DMG (for Homebrew cask)"
+ value: ${{ jobs.build-macos.outputs.dmg_sha256 }}
jobs:
build-windows:
runs-on: blacksmith-4vcpu-windows-2025
- if: (github.event.inputs.build_type == 'all' || github.event.inputs.build_type == 'windows' || github.event.inputs.build_type == '') && github.event.inputs.artifact_destination != 'submit'
+ if: (inputs.build_type == 'all' || inputs.build_type == 'windows' || inputs.build_type == '') && inputs.artifact_destination != 'submit'
permissions:
contents: write
@@ -59,7 +78,7 @@ jobs:
- name: Upload Windows x64 NSIS Installer
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_windows_x64_nsis.exe') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_windows_x64_nsis.exe') != '' && inputs.artifact_destination != 'none'
with:
name: termix_windows_x64_nsis
path: release/termix_windows_x64_nsis.exe
@@ -67,7 +86,7 @@ jobs:
- name: Upload Windows ia32 NSIS Installer
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_windows_ia32_nsis.exe') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_windows_ia32_nsis.exe') != '' && inputs.artifact_destination != 'none'
with:
name: termix_windows_ia32_nsis
path: release/termix_windows_ia32_nsis.exe
@@ -75,7 +94,7 @@ jobs:
- name: Upload Windows x64 MSI Installer
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_windows_x64_msi.msi') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_windows_x64_msi.msi') != '' && inputs.artifact_destination != 'none'
with:
name: termix_windows_x64_msi
path: release/termix_windows_x64_msi.msi
@@ -83,7 +102,7 @@ jobs:
- name: Upload Windows ia32 MSI Installer
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_windows_ia32_msi.msi') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_windows_ia32_msi.msi') != '' && inputs.artifact_destination != 'none'
with:
name: termix_windows_ia32_msi
path: release/termix_windows_ia32_msi.msi
@@ -101,7 +120,7 @@ jobs:
- name: Upload Windows x64 Portable
uses: actions/upload-artifact@v4
- if: hashFiles('termix_windows_x64_portable.zip') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('termix_windows_x64_portable.zip') != '' && inputs.artifact_destination != 'none'
with:
name: termix_windows_x64_portable
path: termix_windows_x64_portable.zip
@@ -109,7 +128,7 @@ jobs:
- name: Upload Windows ia32 Portable
uses: actions/upload-artifact@v4
- if: hashFiles('termix_windows_ia32_portable.zip') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('termix_windows_ia32_portable.zip') != '' && inputs.artifact_destination != 'none'
with:
name: termix_windows_ia32_portable
path: termix_windows_ia32_portable.zip
@@ -117,7 +136,7 @@ jobs:
build-linux:
runs-on: blacksmith-8vcpu-ubuntu-2404
- if: (github.event.inputs.build_type == 'all' || github.event.inputs.build_type == 'linux' || github.event.inputs.build_type == '') && github.event.inputs.artifact_destination != 'submit'
+ if: (inputs.build_type == 'all' || inputs.build_type == 'linux' || inputs.build_type == '') && inputs.artifact_destination != 'submit'
permissions:
contents: write
@@ -172,7 +191,7 @@ jobs:
- name: Upload Linux x64 AppImage
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_linux_x64_appimage.AppImage') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_linux_x64_appimage.AppImage') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_x64_appimage
path: release/termix_linux_x64_appimage.AppImage
@@ -180,7 +199,7 @@ jobs:
- name: Upload Linux arm64 AppImage
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_linux_arm64_appimage.AppImage') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_linux_arm64_appimage.AppImage') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_arm64_appimage
path: release/termix_linux_arm64_appimage.AppImage
@@ -188,7 +207,7 @@ jobs:
- name: Upload Linux armv7l AppImage
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_linux_armv7l_appimage.AppImage') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_linux_armv7l_appimage.AppImage') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_armv7l_appimage
path: release/termix_linux_armv7l_appimage.AppImage
@@ -196,7 +215,7 @@ jobs:
- name: Upload Linux x64 DEB
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_linux_x64_deb.deb') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_linux_x64_deb.deb') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_x64_deb
path: release/termix_linux_x64_deb.deb
@@ -204,7 +223,7 @@ jobs:
- name: Upload Linux arm64 DEB
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_linux_arm64_deb.deb') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_linux_arm64_deb.deb') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_arm64_deb
path: release/termix_linux_arm64_deb.deb
@@ -212,7 +231,7 @@ jobs:
- name: Upload Linux armv7l DEB
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_linux_armv7l_deb.deb') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_linux_armv7l_deb.deb') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_armv7l_deb
path: release/termix_linux_armv7l_deb.deb
@@ -220,7 +239,7 @@ jobs:
- name: Upload Linux x64 tar.gz
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_linux_x64_portable.tar.gz') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_linux_x64_portable.tar.gz') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_x64_portable
path: release/termix_linux_x64_portable.tar.gz
@@ -228,7 +247,7 @@ jobs:
- name: Upload Linux arm64 tar.gz
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_linux_arm64_portable.tar.gz') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_linux_arm64_portable.tar.gz') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_arm64_portable
path: release/termix_linux_arm64_portable.tar.gz
@@ -236,7 +255,7 @@ jobs:
- name: Upload Linux armv7l tar.gz
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_linux_armv7l_portable.tar.gz') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_linux_armv7l_portable.tar.gz') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_armv7l_portable
path: release/termix_linux_armv7l_portable.tar.gz
@@ -308,7 +327,7 @@ jobs:
- name: Upload Flatpak bundle
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_linux_flatpak.flatpak') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_linux_flatpak.flatpak') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_flatpak
path: release/termix_linux_flatpak.flatpak
@@ -316,7 +335,7 @@ jobs:
- name: Upload Flatpakref
uses: actions/upload-artifact@v4
- if: hashFiles('release/com.karmaa.termix.flatpakref') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/com.karmaa.termix.flatpakref') != '' && inputs.artifact_destination != 'none'
with:
name: termix_linux_flatpakref
path: release/com.karmaa.termix.flatpakref
@@ -324,10 +343,12 @@ jobs:
build-macos:
runs-on: blacksmith-6vcpu-macos-latest
- if: (github.event.inputs.build_type == 'macos' || github.event.inputs.build_type == 'all') && github.event.inputs.artifact_destination != 'submit'
+ if: (inputs.build_type == 'macos' || inputs.build_type == 'all') && inputs.artifact_destination != 'submit'
needs: []
permissions:
contents: write
+ outputs:
+ dmg_sha256: ${{ steps.dmg-checksum.outputs.sha256 }}
steps:
- name: Checkout repository
@@ -458,7 +479,7 @@ jobs:
npx electron-builder --mac dmg --universal --x64 --arm64 --publish never
- name: Upload macOS MAS PKG
- if: steps.check_certs.outputs.has_certs == 'true' && hashFiles('release/termix_macos_universal_mas.pkg') != '' && (github.event.inputs.artifact_destination == 'file' || github.event.inputs.artifact_destination == 'release' || github.event.inputs.artifact_destination == 'submit')
+ if: steps.check_certs.outputs.has_certs == 'true' && hashFiles('release/termix_macos_universal_mas.pkg') != '' && (inputs.artifact_destination == 'file' || inputs.artifact_destination == 'release' || inputs.artifact_destination == 'submit')
uses: actions/upload-artifact@v4
with:
name: termix_macos_universal_mas
@@ -468,7 +489,7 @@ jobs:
- name: Upload macOS Universal DMG
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_macos_universal_dmg.dmg') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_macos_universal_dmg.dmg') != '' && inputs.artifact_destination != 'none'
with:
name: termix_macos_universal_dmg
path: release/termix_macos_universal_dmg.dmg
@@ -476,7 +497,7 @@ jobs:
- name: Upload macOS x64 DMG
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_macos_x64_dmg.dmg') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_macos_x64_dmg.dmg') != '' && inputs.artifact_destination != 'none'
with:
name: termix_macos_x64_dmg
path: release/termix_macos_x64_dmg.dmg
@@ -484,7 +505,7 @@ jobs:
- name: Upload macOS arm64 DMG
uses: actions/upload-artifact@v4
- if: hashFiles('release/termix_macos_arm64_dmg.dmg') != '' && github.event.inputs.artifact_destination != 'none'
+ if: hashFiles('release/termix_macos_arm64_dmg.dmg') != '' && inputs.artifact_destination != 'none'
with:
name: termix_macos_arm64_dmg
path: release/termix_macos_arm64_dmg.dmg
@@ -496,8 +517,15 @@ jobs:
VERSION=$(node -p "require('./package.json').version")
echo "version=$VERSION" >> $GITHUB_OUTPUT
+ - name: Compute universal DMG checksum
+ id: dmg-checksum
+ if: hashFiles('release/termix_macos_universal_dmg.dmg') != ''
+ run: |
+ CHECKSUM=$(shasum -a 256 "release/termix_macos_universal_dmg.dmg" | awk '{print $1}')
+ echo "sha256=$CHECKSUM" >> $GITHUB_OUTPUT
+
- name: Generate Homebrew Cask
- if: hashFiles('release/termix_macos_universal_dmg.dmg') != '' && (github.event.inputs.artifact_destination == 'file' || github.event.inputs.artifact_destination == 'release')
+ if: hashFiles('release/termix_macos_universal_dmg.dmg') != '' && (inputs.artifact_destination == 'file' || inputs.artifact_destination == 'release')
run: |
VERSION="${{ steps.homebrew-version.outputs.version }}"
DMG_PATH="release/termix_macos_universal_dmg.dmg"
@@ -515,14 +543,14 @@ jobs:
- name: Upload Homebrew Cask as artifact
uses: actions/upload-artifact@v4
- if: hashFiles('homebrew-generated/termix.rb') != '' && github.event.inputs.artifact_destination == 'file'
+ if: hashFiles('homebrew-generated/termix.rb') != '' && inputs.artifact_destination == 'file'
with:
name: termix_macos_homebrew_cask
path: homebrew-generated/termix.rb
retention-days: 30
- name: Upload Homebrew Cask to release
- if: hashFiles('homebrew-generated/termix.rb') != '' && github.event.inputs.artifact_destination == 'release'
+ if: hashFiles('homebrew-generated/termix.rb') != '' && inputs.artifact_destination == 'release'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
@@ -544,7 +572,7 @@ jobs:
submit-to-chocolatey:
runs-on: blacksmith-4vcpu-windows-2025
- if: github.event.inputs.artifact_destination == 'submit' && (github.event.inputs.build_type == 'all' || github.event.inputs.build_type == 'windows' || github.event.inputs.build_type == '')
+ if: inputs.artifact_destination == 'submit' && (inputs.build_type == 'all' || inputs.build_type == 'windows' || inputs.build_type == '')
permissions:
contents: read
@@ -649,7 +677,7 @@ jobs:
submit-to-flatpak:
runs-on: blacksmith-8vcpu-ubuntu-2404
- if: github.event.inputs.artifact_destination == 'submit' && (github.event.inputs.build_type == 'all' || github.event.inputs.build_type == 'linux' || github.event.inputs.build_type == '')
+ if: inputs.artifact_destination == 'submit' && (inputs.build_type == 'all' || inputs.build_type == 'linux' || inputs.build_type == '')
needs: []
permissions:
contents: read
@@ -736,7 +764,7 @@ jobs:
submit-to-homebrew:
runs-on: blacksmith-6vcpu-macos-latest
- if: github.event.inputs.artifact_destination == 'submit' && (github.event.inputs.build_type == 'all' || github.event.inputs.build_type == 'macos')
+ if: inputs.artifact_destination == 'submit' && (inputs.build_type == 'all' || inputs.build_type == 'macos')
needs: []
permissions:
contents: read
@@ -805,7 +833,7 @@ jobs:
upload-to-release:
runs-on: blacksmith-8vcpu-ubuntu-2404
- if: github.event.inputs.artifact_destination == 'release'
+ if: inputs.artifact_destination == 'release'
needs: [build-windows, build-linux, build-macos]
permissions:
contents: write
@@ -816,12 +844,17 @@ jobs:
with:
path: artifacts
- - name: Get latest release tag
+ - name: Resolve release tag
id: get_release
- run: |
- echo "RELEASE_TAG=$(gh release list --repo ${{ github.repository }} --limit 1 --json tagName -q '.[0].tagName')" >> $GITHUB_ENV
env:
GH_TOKEN: ${{ github.token }}
+ INPUT_TAG: ${{ inputs.release_tag }}
+ run: |
+ if [ -n "$INPUT_TAG" ]; then
+ echo "RELEASE_TAG=$INPUT_TAG" >> $GITHUB_ENV
+ else
+ echo "RELEASE_TAG=$(gh release list --repo ${{ github.repository }} --limit 1 --json tagName -q '.[0].tagName')" >> $GITHUB_ENV
+ fi
- name: Upload artifacts to latest release
run: |
@@ -841,7 +874,7 @@ jobs:
submit-to-testflight:
runs-on: blacksmith-6vcpu-macos-latest
- if: github.event.inputs.artifact_destination == 'submit' && (github.event.inputs.build_type == 'all' || github.event.inputs.build_type == 'macos')
+ if: inputs.artifact_destination == 'submit' && (inputs.build_type == 'all' || inputs.build_type == 'macos')
needs: []
permissions:
contents: write
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 000000000..94853c8b5
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,150 @@
+name: Release
+
+on:
+ workflow_dispatch:
+
+permissions:
+ contents: write
+
+jobs:
+ prep:
+ runs-on: blacksmith-2vcpu-ubuntu-2404
+ outputs:
+ version: ${{ steps.info.outputs.version }}
+ release_tag: ${{ steps.info.outputs.release_tag }}
+ mobile_version: ${{ steps.info.outputs.mobile_version }}
+ steps:
+ - name: Guard branch
+ if: github.ref != 'refs/heads/main'
+ run: |
+ echo "Releases must be run from main (got ${{ github.ref }})."
+ exit 1
+
+ - name: Checkout repository
+ uses: actions/checkout@v5
+ with:
+ fetch-depth: 1
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version-file: ".nvmrc"
+
+ - name: Resolve versions
+ id: info
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ VERSION=$(node -p "require('./package.json').version")
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
+ echo "release_tag=release-$VERSION-tag" >> "$GITHUB_OUTPUT"
+
+ MOBILE_RAW=$(gh release view -R Termix-SSH/Mobile --json tagName -q .tagName)
+ MOBILE_VERSION=$(echo "$MOBILE_RAW" | sed -E 's/^release-//; s/-tag$//')
+ if [ -z "$MOBILE_VERSION" ]; then
+ echo "Failed to resolve the latest Termix-SSH/Mobile release version."
+ exit 1
+ fi
+ echo "mobile_version=$MOBILE_VERSION" >> "$GITHUB_OUTPUT"
+
+ - name: Validate release notes
+ run: |
+ node scripts/generate-release-body.cjs \
+ --version "${{ steps.info.outputs.version }}" \
+ --mobile-version "${{ steps.info.outputs.mobile_version }}" \
+ --notes RELEASE_NOTES.md > /dev/null
+
+ docker:
+ needs: [prep]
+ uses: ./.github/workflows/docker.yml
+ with:
+ version: ${{ needs.prep.outputs.version }}
+ build_type: Production
+ secrets: inherit
+
+ create-release:
+ needs: [prep, docker]
+ runs-on: blacksmith-2vcpu-ubuntu-2404
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v5
+ with:
+ fetch-depth: 1
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version-file: ".nvmrc"
+
+ - name: Generate release body
+ run: |
+ node scripts/generate-release-body.cjs \
+ --version "${{ needs.prep.outputs.version }}" \
+ --mobile-version "${{ needs.prep.outputs.mobile_version }}" \
+ --notes RELEASE_NOTES.md > RELEASE_BODY.md
+
+ - name: Create or update GitHub release
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ TAG="${{ needs.prep.outputs.release_tag }}"
+ TITLE="release-${{ needs.prep.outputs.version }}"
+ if gh release view "$TAG" --repo ${{ github.repository }} >/dev/null 2>&1; then
+ gh release edit "$TAG" --repo ${{ github.repository }} --title "$TITLE" --notes-file RELEASE_BODY.md
+ else
+ gh release create "$TAG" --repo ${{ github.repository }} --title "$TITLE" --notes-file RELEASE_BODY.md --target "${{ github.sha }}"
+ fi
+
+ electron-release:
+ needs: [prep, create-release]
+ uses: ./.github/workflows/electron.yml
+ with:
+ build_type: all
+ artifact_destination: release
+ release_tag: ${{ needs.prep.outputs.release_tag }}
+ secrets: inherit
+
+ electron-submit:
+ needs: [electron-release]
+ uses: ./.github/workflows/electron.yml
+ with:
+ build_type: all
+ artifact_destination: submit
+ secrets: inherit
+
+ cask-commit-back:
+ needs: [prep, electron-release]
+ runs-on: blacksmith-2vcpu-ubuntu-2404
+ permissions:
+ contents: write
+ steps:
+ - name: Checkout main
+ uses: actions/checkout@v5
+ with:
+ ref: main
+ fetch-depth: 1
+ token: ${{ secrets.GHCR_TOKEN }}
+
+ - name: Bump and commit Homebrew cask
+ env:
+ VERSION: ${{ needs.prep.outputs.version }}
+ DMG_SHA256: ${{ needs.electron-release.outputs.macos_universal_dmg_sha256 }}
+ run: |
+ if [ -z "$DMG_SHA256" ]; then
+ echo "No universal DMG checksum available (macOS build unsigned or skipped); leaving cask unchanged."
+ exit 0
+ fi
+
+ sed -i "s|version \".*\"|version \"$VERSION\"|g" Casks/termix.rb
+ sed -i "s|sha256 \".*\"|sha256 \"$DMG_SHA256\"|g" Casks/termix.rb
+
+ if git diff --quiet Casks/termix.rb; then
+ echo "Cask already up to date."
+ exit 0
+ fi
+
+ git config user.name "LukeGus"
+ git config user.email "[email protected]"
+ git add Casks/termix.rb
+ git commit -m "chore: bump Homebrew cask to $VERSION"
+ git push origin HEAD:main
diff --git a/.gitignore b/.gitignore
index 5121dc4f8..b891f5f80 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,8 +7,10 @@ pnpm-debug.log*
lerna-debug.log*
node_modules
+src/mcp-server/node_modules
dist
dist-ssr
+coverage
*.local
.vscode/
diff --git a/.prettierignore b/.prettierignore
index 12156ff6d..befe2e1fd 100644
--- a/.prettierignore
+++ b/.prettierignore
@@ -5,6 +5,7 @@ dist-ssr
release
node_modules
+src/mcp-server/node_modules
package-lock.json
pnpm-lock.yaml
yarn.lock
diff --git a/README.md b/README.md
index fd52640b2..60e2548c8 100644
--- a/README.md
+++ b/README.md
@@ -80,7 +80,7 @@ Create and manage server-to-server SSH tunnels with automatic reconnection, heal
<td width="50%" valign="top">
**Remote File Manager:**
-Manage files directly on remote servers with support for viewing and editing code, images, audio, and video. Upload, download, rename, delete, and move files seamlessly with sudo support.
+Manage files directly on remote servers with support for viewing and editing code, images, audio, and video. Upload, download, rename, delete, and move files seamlessly with sudo support. Includes support for moving files from server to server.
</td>
</tr>
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
new file mode 100644
index 000000000..9c9b2a48d
--- /dev/null
+++ b/RELEASE_NOTES.md
@@ -0,0 +1,55 @@
+<!-- SUMMARY -->
+
+Bug fixes and new features including host-to-host file transfer, OIDC improvements, UI/UX updates, and numerous stability and security patches.
+
+<!-- /SUMMARY -->
+
+<!-- YOUTUBE -->
+
+https://youtu.be/At8iDk6-Q_s
+
+<!-- /YOUTUBE -->
+
+<!-- UPDATE_LOG -->
+
+- Added in-line buttons on host name row when using click to expand hosts in hosts list
+- Expose admin_group via OIDC_ADMIN_GROUP env var
+- Sync appearance preferences
+- Support native OIDC callbacks
+- Add portal Desktop DBUS permission for Flatpak URL opening
+- Restore host password copy
+- Support for single-host direct tunnels (ssh -L)
+- Host to host file transfer in file manager
+- Show ip/username without having to hover over hosts
+- Updated credential list UI to match UI/UX of host list
+- Restore rename host folder UI
+<!-- /UPDATE_LOG -->
+
+<!-- BUG_FIXES -->
+
+- Several security vulnerabilities
+- Allow navigating away from split-view to non-pane tabs
+- Restore SSH keepalive internal to use 30s to prevent random disconnects
+- Apply guacamole-lite protocol patch in Docker builds
+- Show correct icons for network interface types
+- Resolve sudo password for shared host users
+- Use jump hosts for online status check and metric collection
+- Broaden sudo prompt detection for newer distros
+- Recalculate terminal layout after web fonts load
+- Improve terminal cwd detection and initial directory command
+- Decode base64 file content as UTF-8 in file manager
+- Normalize lazy import default export for iOS compatibility
+- Prevent RDP display from snapping back after container resize
+- Removed unused code and fixed PR checks and lint warnings
+- Send name instruction for protocol >= 1.3.0 (guacd 1.5.0/1.1.0 errors)
+- Wire up OIDC to password link dialog with submit/visibility
+- Pass through command completion
+- Resolve terminal jump hosts server-side
+- Auto allow SSL certs for private network hosts
+- Removed deprecated host management button from command palette
+- Command palette opening wrong protocol
+- Export/import failing for ssh key hosts
+- Docker ssh2 native crypto not compiling in Docker
+- Persisted terminal tabs attempt SSH on RDP hosts afater migration
+- Credentials not appearing in host manager until refresh
+<!-- /BUG_FIXES -->
diff --git a/docker/Dockerfile b/docker/Dockerfile
index bb6236e0b..b9a8a1495 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -8,7 +8,10 @@ COPY package*.json ./
COPY .npmrc ./
COPY vendor ./vendor
+COPY scripts/patch-guacamole-lite.cjs ./scripts/
+
RUN npm ci --ignore-scripts && \
+ node scripts/patch-guacamole-lite.cjs && \
npm cache clean --force
# Stage 2: Build frontend
@@ -42,8 +45,11 @@ COPY package*.json ./
COPY .npmrc ./
COPY vendor ./vendor
+COPY scripts/patch-guacamole-lite.cjs ./scripts/
+
RUN npm ci --omit=dev --ignore-scripts && \
- npm rebuild better-sqlite3 bcryptjs && \
+ node scripts/patch-guacamole-lite.cjs && \
+ npm rebuild better-sqlite3 bcryptjs ssh2 && \
npm cache clean --force
# Stage 5: Final optimized image
diff --git a/docker/nginx.conf b/docker/nginx.conf
index 35d7989d0..36846d614 100644
--- a/docker/nginx.conf
+++ b/docker/nginx.conf
@@ -49,7 +49,7 @@ http {
server {
listen ${PORT};
- server_name localhost;
+ server_name _;
add_header X-Content-Type-Options nosniff always;
add_header X-XSS-Protection "1; mode=block" always;
diff --git a/electron/main.cjs b/electron/main.cjs
index 674a5d105..59dedcb3c 100644
--- a/electron/main.cjs
+++ b/electron/main.cjs
@@ -353,16 +353,83 @@ function isInsecureModeEnabled() {
);
}
-function getTlsVerificationOptions() {
+function getServerConfigPath() {
+ return path.join(app.getPath("userData"), "server-config.json");
+}
+
+function getServerConfigSync() {
+ try {
+ const configPath = getServerConfigPath();
+ if (!fs.existsSync(configPath)) return null;
+ return JSON.parse(fs.readFileSync(configPath, "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+function getOrigin(url) {
+ try {
+ return new URL(url).origin;
+ } catch {
+ return null;
+ }
+}
+
+function isPrivateNetworkHost(hostname) {
+ if (
+ hostname === "localhost" ||
+ hostname === "127.0.0.1" ||
+ hostname === "::1"
+ ) {
+ return true;
+ }
+
+ const ipv4Match = hostname.match(
+ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/,
+ );
+ if (ipv4Match) {
+ const [, a, b] = ipv4Match.map(Number);
+ return (
+ a === 10 ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 168) ||
+ (a === 169 && b === 254)
+ );
+ }
+
+ if (hostname.startsWith("fc") || hostname.startsWith("fd")) {
+ return true;
+ }
+
+ return false;
+}
+
+function isInvalidCertificateAllowedForUrl(url) {
+ if (isInsecureModeEnabled()) return true;
+
+ try {
+ const { hostname } = new URL(url);
+ if (isPrivateNetworkHost(hostname)) return true;
+ } catch {
+ // fall through
+ }
+
+ const config = getServerConfigSync();
+ if (!config?.allowInvalidCertificate || !config?.serverUrl) return false;
+
+ return getOrigin(url) === getOrigin(config.serverUrl);
+}
+
+function getTlsVerificationOptions(url) {
return {
- rejectUnauthorized: !isInsecureModeEnabled(),
+ rejectUnauthorized: !isInvalidCertificateAllowedForUrl(url),
};
}
function getWebSocketOptions(url, options = {}) {
return {
...options,
- ...(String(url).startsWith("wss:") ? getTlsVerificationOptions() : {}),
+ ...(String(url).startsWith("wss:") ? getTlsVerificationOptions(url) : {}),
};
}
@@ -376,7 +443,7 @@ function httpFetch(url, options = {}) {
method: options.method || "GET",
headers: options.headers || {},
timeout: options.timeout || 10000,
- ...(isHttps ? getTlsVerificationOptions() : {}),
+ ...(isHttps ? getTlsVerificationOptions(url) : {}),
};
const req = client.request(url, requestOptions, (res) => {
@@ -435,6 +502,25 @@ const electronCacheBuildPath = path.join(
);
const termixSessionPartition = "persist:termix";
+app.on(
+ "certificate-error",
+ (event, _webContents, url, error, certificate, callback) => {
+ if (isInvalidCertificateAllowedForUrl(url)) {
+ event.preventDefault();
+ logToFile("Allowed invalid certificate for configured server", {
+ url,
+ error,
+ issuer: certificate?.issuerName,
+ subject: certificate?.subjectName,
+ });
+ callback(true);
+ return;
+ }
+
+ callback(false);
+ },
+);
+
function getElectronBuildTimestamp() {
try {
const buildInfo = require("./build-info.cjs");
@@ -1153,14 +1239,7 @@ ipcMain.handle(
ipcMain.handle("get-server-config", () => {
try {
- const userDataPath = app.getPath("userData");
- const configPath = path.join(userDataPath, "server-config.json");
-
- if (fs.existsSync(configPath)) {
- const configData = fs.readFileSync(configPath, "utf8");
- return JSON.parse(configData);
- }
- return null;
+ return getServerConfigSync();
} catch (error) {
console.error("Error reading server config:", error);
return null;
@@ -1170,7 +1249,7 @@ ipcMain.handle("get-server-config", () => {
ipcMain.handle("save-server-config", (event, config) => {
try {
const userDataPath = app.getPath("userData");
- const configPath = path.join(userDataPath, "server-config.json");
+ const configPath = getServerConfigPath();
if (!fs.existsSync(userDataPath)) {
fs.mkdirSync(userDataPath, { recursive: true });
@@ -1319,16 +1398,6 @@ const C2S_WS_HIGH_WATERMARK = 1024 * 1024;
const C2S_WS_LOW_WATERMARK = 256 * 1024;
const C2S_STREAM_WRITE_LIMIT = 8 * 1024 * 1024;
-function getServerConfigSync() {
- try {
- const configPath = path.join(app.getPath("userData"), "server-config.json");
- if (!fs.existsSync(configPath)) return null;
- return JSON.parse(fs.readFileSync(configPath, "utf8"));
- } catch {
- return null;
- }
-}
-
function getC2SRelayUrl() {
const config = getServerConfigSync();
const serverUrl =
diff --git a/eslint.config.mjs b/eslint.config.mjs
index a2cce5ee6..ee87445c5 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -7,7 +7,7 @@ import tseslint from "typescript-eslint";
import { globalIgnores } from "eslint/config";
export default tseslint.config([
- globalIgnores(["dist", "release", "Mobile"]),
+ globalIgnores(["dist", "release", "Mobile", "src/mcp-server/node_modules"]),
{
files: ["**/*.{ts,tsx}"],
extends: [
diff --git a/flatpak/com.karmaa.termix.yml b/flatpak/com.karmaa.termix.yml
index 7b67c0e7a..b0cde5341 100644
--- a/flatpak/com.karmaa.termix.yml
+++ b/flatpak/com.karmaa.termix.yml
@@ -18,6 +18,7 @@ finish-args:
- --socket=ssh-auth
- --socket=session-bus
- --talk-name=org.freedesktop.secrets
+ - --talk-name=org.freedesktop.portal.Desktop
- --env=ELECTRON_TRASH=gio
- --env=XCURSOR_PATH=/run/host/user-share/icons:/run/host/share/icons
- --env=ELECTRON_OZONE_PLATFORM_HINT=auto
diff --git a/knip.json b/knip.json
new file mode 100644
index 000000000..c6669a435
--- /dev/null
+++ b/knip.json
@@ -0,0 +1,98 @@
+{
+ "$schema": "https://unpkg.com/knip@latest/schema.json",
+ "entry": [
+ "src/backend/starter.ts",
+ "src/backend/swagger.ts",
+ "scripts/**/*.cjs"
+ ],
+ "project": ["src/**/*.{ts,tsx}", "electron/**/*.cjs", "scripts/**/*.cjs"],
+ "ignoreBinaries": ["powershell"],
+ "ignoreDependencies": [
+ "@codemirror/autocomplete",
+ "@codemirror/commands",
+ "@codemirror/search",
+ "@codemirror/theme-one-dark",
+ "@codemirror/view",
+ "@electron/notarize",
+ "@monaco-editor/react",
+ "@radix-ui/react-accordion",
+ "@radix-ui/react-alert-dialog",
+ "@radix-ui/react-checkbox",
+ "@radix-ui/react-dialog",
+ "@radix-ui/react-dropdown-menu",
+ "@radix-ui/react-label",
+ "@radix-ui/react-popover",
+ "@radix-ui/react-progress",
+ "@radix-ui/react-scroll-area",
+ "@radix-ui/react-select",
+ "@radix-ui/react-separator",
+ "@radix-ui/react-slider",
+ "@radix-ui/react-slot",
+ "@radix-ui/react-switch",
+ "@radix-ui/react-tabs",
+ "@radix-ui/react-tooltip",
+ "@types/better-sqlite3",
+ "@types/cookie-parser",
+ "@types/cors",
+ "@types/express",
+ "@types/guacamole-common-js",
+ "@types/js-yaml",
+ "@types/jsonwebtoken",
+ "@types/multer",
+ "@types/qrcode",
+ "@types/speakeasy",
+ "@types/ssh2",
+ "@uiw/codemirror-extensions-langs",
+ "@uiw/codemirror-theme-github",
+ "@uiw/react-codemirror",
+ "@xterm/addon-clipboard",
+ "@xterm/addon-fit",
+ "@xterm/addon-unicode11",
+ "@xterm/addon-web-links",
+ "@xterm/xterm",
+ "axios",
+ "bcryptjs",
+ "better-sqlite3",
+ "body-parser",
+ "chalk",
+ "class-variance-authority",
+ "clsx",
+ "cmdk",
+ "cookie-parser",
+ "cors",
+ "cytoscape",
+ "drizzle-orm",
+ "express",
+ "guacamole-lite",
+ "guacamole-common-js",
+ "jose",
+ "js-yaml",
+ "jsonwebtoken",
+ "jszip",
+ "multer",
+ "nanoid",
+ "qrcode",
+ "i18next-browser-languagedetector",
+ "lucide-react",
+ "motion",
+ "radix-ui",
+ "react-cytoscapejs",
+ "react-h5-audio-player",
+ "react-hook-form",
+ "react-icons",
+ "react-markdown",
+ "react-pdf",
+ "react-photo-view",
+ "react-syntax-highlighter",
+ "react-xtermjs",
+ "remark-gfm",
+ "socks",
+ "speakeasy",
+ "ssh2",
+ "undici",
+ "husky",
+ "sharp",
+ "sonner",
+ "tailwind-merge"
+ ]
+}
diff --git a/package-lock.json b/package-lock.json
index 5b6672332..1adeec352 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,15 +1,14 @@
{
"name": "termix",
- "version": "2.3.1",
+ "version": "2.3.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "termix",
- "version": "2.3.1",
+ "version": "2.3.2",
"hasInstallScript": true,
"dependencies": {
- "@tanstack/react-virtual": "^3.13.26",
"axios": "^1.15.2",
"bcryptjs": "^3.0.3",
"better-sqlite3": "^12.9.0",
@@ -21,7 +20,6 @@
"drizzle-orm": "^0.45.2",
"express": "^5.2.1",
"guacamole-lite": "^1.2.0",
- "https-proxy-agent": "^7.0.6",
"jose": "^6.2.2",
"js-yaml": "^4.1.1",
"jsonwebtoken": "^9.0.3",
@@ -33,7 +31,6 @@
"socks": "^2.8.7",
"speakeasy": "^2.0.0",
"ssh2": "^1.17.0",
- "swagger-jsdoc": "^6.3.0",
"undici": "^7.0.0",
"ws": "^8.20.0"
},
@@ -68,6 +65,10 @@
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-tooltip": "^1.2.8",
"@tailwindcss/vite": "^4.2.4",
+ "@testing-library/dom": "^10.4.1",
+ "@testing-library/jest-dom": "^6.9.1",
+ "@testing-library/react": "^16.3.2",
+ "@testing-library/user-event": "^14.6.1",
"@types/better-sqlite3": "^7.6.13",
"@types/cookie-parser": "^1.4.10",
"@types/cors": "^2.8.19",
@@ -87,6 +88,8 @@
"@uiw/codemirror-theme-github": "^4.25.9",
"@uiw/react-codemirror": "^4.25.9",
"@vitejs/plugin-react": "^6.0.1",
+ "@vitest/coverage-v8": "^4.1.8",
+ "@vitest/ui": "^4.1.8",
"@xterm/addon-clipboard": "^0.2.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/addon-unicode11": "^0.9.0",
@@ -108,6 +111,7 @@
"husky": "^9.1.7",
"i18next": "^26.0.8",
"i18next-browser-languagedetector": "^8.2.1",
+ "jsdom": "^29.1.1",
"lint-staged": "^17.0.5",
"lucide-react": "^1.11.0",
"prettier": "3.8.3",
@@ -133,17 +137,26 @@
"typescript": "~6.0.3",
"typescript-eslint": "^8.59.0",
"vite": "^8.0.13",
- "vite-plugin-svgr": "^5.2.0"
+ "vite-plugin-svgr": "^5.2.0",
+ "vitest": "^4.1.8"
},
"engines": {
"node": ">=22.12.0",
"npm": ">=11"
}
},
+ "node_modules/@adobe/css-tools": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz",
+ "integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@apidevtools/json-schema-ref-parser": {
"version": "14.0.1",
"resolved": "https://registry.npmjs.org/@apidevtools/json-schema-ref-parser/-/json-schema-ref-parser-14.0.1.tgz",
"integrity": "sha512-Oc96zvmxx1fqoSEdUmfmvvb59/KDOnUoJ7s2t7bISyAn0XEz57LCCw8k2Y4Pf3mwKaZLMciESALORLgfe2frCw==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@types/json-schema": "^7.0.15",
@@ -160,6 +173,7 @@
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@apidevtools/openapi-schemas/-/openapi-schemas-2.1.0.tgz",
"integrity": "sha512-Zc1AlqrJlX3SlpupFGpiLi2EbteyP7fXmUOGup6/DnkRgjP9bgMM/ag+n91rsv0U1Gpz0H3VILA/o3bW7Ua6BQ==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
@@ -169,12 +183,14 @@
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/@apidevtools/swagger-methods/-/swagger-methods-3.0.2.tgz",
"integrity": "sha512-QAkD5kK2b1WfjDS/UQn/qQkbwF31uqRjPTrsCs5ZG9BQGAkjwvqGFjjPqAuzac/IYzpPtRzjCP1WrTuAIjMrXg==",
+ "dev": true,
"license": "MIT"
},
"node_modules/@apidevtools/swagger-parser": {
"version": "12.1.0",
"resolved": "https://registry.npmjs.org/@apidevtools/swagger-parser/-/swagger-parser-12.1.0.tgz",
"integrity": "sha512-e5mJoswsnAX0jG+J09xHFYQXb/bUc5S3pLpMxUuRUA2H8T2kni3yEoyz2R3Dltw5f4A6j6rPNMpWTK+iVDFlng==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@apidevtools/json-schema-ref-parser": "14.0.1",
@@ -188,6 +204,57 @@
"openapi-types": ">=7"
}
},
+ "node_modules/@asamuzakjp/css-color": {
+ "version": "5.1.11",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",
+ "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/generational-cache": "^1.0.1",
+ "@csstools/css-calc": "^3.2.0",
+ "@csstools/css-color-parser": "^4.1.0",
+ "@csstools/css-parser-algorithms": "^4.0.0",
+ "@csstools/css-tokenizer": "^4.0.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/dom-selector": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz",
+ "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/generational-cache": "^1.0.1",
+ "@asamuzakjp/nwsapi": "^2.3.9",
+ "bidi-js": "^1.0.3",
+ "css-tree": "^3.2.1",
+ "is-potential-custom-element-name": "^1.0.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/generational-cache": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz",
+ "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/nwsapi": {
+ "version": "2.3.9",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz",
+ "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@babel/code-frame": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
@@ -458,6 +525,29 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@bcoe/v8-coverage": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz",
+ "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@bramus/specificity": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",
+ "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "css-tree": "^3.0.0"
+ },
+ "bin": {
+ "specificity": "bin/cli.js"
+ }
+ },
"node_modules/@codemirror/autocomplete": {
"version": "6.20.2",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.2.tgz",
@@ -1231,6 +1321,146 @@
}
}
},
+ "node_modules/@csstools/color-helpers": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.0.2.tgz",
+ "integrity": "sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT-0",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
+ "node_modules/@csstools/css-calc": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.2.1.tgz",
+ "integrity": "sha512-DtdHlgXh5ZkA43cwBcAm+huzgJiwx3ZTWVjBs94kwz2xKqSimDA3lBgCjphYgwgVUMWatSM0pDd8TILB1yrVVg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^4.0.0",
+ "@csstools/css-tokenizer": "^4.0.0"
+ }
+ },
+ "node_modules/@csstools/css-color-parser": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.1.1.tgz",
+ "integrity": "sha512-eZ5XOtyhK+mggRafYUWzA0tvaYOFgdY8AkgQiCJF9qNAePnUo/zmsqqYubBBb3sQ8uNUaSKTY9s9klfRaAXL0g==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@csstools/color-helpers": "^6.0.2",
+ "@csstools/css-calc": "^3.2.1"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^4.0.0",
+ "@csstools/css-tokenizer": "^4.0.0"
+ }
+ },
+ "node_modules/@csstools/css-parser-algorithms": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",
+ "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-tokenizer": "^4.0.0"
+ }
+ },
+ "node_modules/@csstools/css-syntax-patches-for-csstree": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.5.tgz",
+ "integrity": "sha512-oNjBvzLq2GPZtJphCjLqXow/cHySHSgtxvKZb7OqSZ/xHgw6NWNhfad+6AB9cLeVm6eA9d/qMll3JdEHjy6M+A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT-0",
+ "peerDependencies": {
+ "css-tree": "^3.2.1"
+ },
+ "peerDependenciesMeta": {
+ "css-tree": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@csstools/css-tokenizer": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz",
+ "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
"node_modules/@deadendjs/swagger-jsdoc": {
"version": "8.2.0",
"resolved": "https://registry.npmjs.org/@deadendjs/swagger-jsdoc/-/swagger-jsdoc-8.2.0.tgz",
@@ -1834,6 +2064,24 @@
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
},
+ "node_modules/@exodus/bytes": {
+ "version": "1.15.1",
+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.1.tgz",
+ "integrity": "sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ },
+ "peerDependencies": {
+ "@noble/hashes": "^1.8.0 || ^2.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@noble/hashes": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@floating-ui/core": {
"version": "1.7.5",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz",
@@ -2517,6 +2765,7 @@
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-9.0.0.tgz",
"integrity": "sha512-AokJm4tuBHillT+FpMtxQ60n8ObyXBatq7jD2/JA9dxbDDokKQm8KMht5ibGzLVU9IJDIKK4TPKgMHEYMn3lMg==",
+ "dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=18"
@@ -3172,6 +3421,13 @@
"url": "https://github.com/sponsors/Boshen"
}
},
+ "node_modules/@polka/url": {
+ "version": "1.0.0-next.29",
+ "resolved": "https://registry.npmjs.org/@polka/url/-/url-1.0.0-next.29.tgz",
+ "integrity": "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@radix-ui/number": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
@@ -5401,6 +5657,13 @@
"url": "https://ko-fi.com/dangreen"
}
},
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@svgr/babel-plugin-add-jsx-attribute": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/@svgr/babel-plugin-add-jsx-attribute/-/babel-plugin-add-jsx-attribute-8.0.0.tgz",
@@ -5937,31 +6200,103 @@
"vite": "^5.2.0 || ^6 || ^7 || ^8"
}
},
- "node_modules/@tanstack/react-virtual": {
- "version": "3.13.26",
- "resolved": "https://registry.npmjs.org/@tanstack/react-virtual/-/react-virtual-3.13.26.tgz",
- "integrity": "sha512-DosdgjOxCLahkn0o+ilmZYwEjo1glfMGuRT/j3PQ18yr5XqA8N/BCaL9IJ3B5TRl+nnzyK2IOFgAILwzN3a9xQ==",
+ "node_modules/@testing-library/dom": {
+ "version": "10.4.1",
+ "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.1.tgz",
+ "integrity": "sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==",
+ "dev": true,
"license": "MIT",
"dependencies": {
- "@tanstack/virtual-core": "3.16.0"
+ "@babel/code-frame": "^7.10.4",
+ "@babel/runtime": "^7.12.5",
+ "@types/aria-query": "^5.0.1",
+ "aria-query": "5.3.0",
+ "dom-accessibility-api": "^0.5.9",
+ "lz-string": "^1.5.0",
+ "picocolors": "1.1.1",
+ "pretty-format": "^27.0.2"
},
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/tannerlinsley"
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@testing-library/dom/node_modules/aria-query": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz",
+ "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "dequal": "^2.0.3"
+ }
+ },
+ "node_modules/@testing-library/dom/node_modules/dom-accessibility-api": {
+ "version": "0.5.16",
+ "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
+ "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@testing-library/jest-dom": {
+ "version": "6.9.1",
+ "resolved": "https://registry.npmjs.org/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz",
+ "integrity": "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@adobe/css-tools": "^4.4.0",
+ "aria-query": "^5.0.0",
+ "css.escape": "^1.5.1",
+ "dom-accessibility-api": "^0.6.3",
+ "picocolors": "^1.1.1",
+ "redent": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=14",
+ "npm": ">=6",
+ "yarn": ">=1"
+ }
+ },
+ "node_modules/@testing-library/react": {
+ "version": "16.3.2",
+ "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.2.tgz",
+ "integrity": "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.12.5"
+ },
+ "engines": {
+ "node": ">=18"
},
"peerDependencies": {
- "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
- "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ "@testing-library/dom": "^10.0.0",
+ "@types/react": "^18.0.0 || ^19.0.0",
+ "@types/react-dom": "^18.0.0 || ^19.0.0",
+ "react": "^18.0.0 || ^19.0.0",
+ "react-dom": "^18.0.0 || ^19.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
}
},
- "node_modules/@tanstack/virtual-core": {
- "version": "3.16.0",
- "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.16.0.tgz",
- "integrity": "sha512-Er2N7q3WOiH6y2JLxsxNX+u2/sLqSsL0bxFgDjuiPiA7vKhZRm+IzcS17vRee3GNXr64UsesA5CAp9yTiIYw9A==",
+ "node_modules/@testing-library/user-event": {
+ "version": "14.6.1",
+ "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.1.tgz",
+ "integrity": "sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==",
+ "dev": true,
"license": "MIT",
- "funding": {
- "type": "github",
- "url": "https://github.com/sponsors/tannerlinsley"
+ "engines": {
+ "node": ">=12",
+ "npm": ">=6"
+ },
+ "peerDependencies": {
+ "@testing-library/dom": ">=7.21.4"
}
},
"node_modules/@tybys/wasm-util": {
@@ -5975,6 +6310,13 @@
"tslib": "^2.4.0"
}
},
+ "node_modules/@types/aria-query": {
+ "version": "5.0.4",
+ "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
+ "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/better-sqlite3": {
"version": "7.6.13",
"resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz",
@@ -5996,6 +6338,17 @@
"@types/node": "*"
}
},
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
"node_modules/@types/connect": {
"version": "3.4.38",
"resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz",
@@ -6036,6 +6389,13 @@
"@types/ms": "*"
}
},
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -6123,6 +6483,7 @@
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
"integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
+ "dev": true,
"license": "MIT"
},
"node_modules/@types/jsonwebtoken": {
@@ -6722,36 +7083,212 @@
}
}
},
- "node_modules/@xmldom/xmldom": {
- "version": "0.8.13",
- "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz",
- "integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==",
+ "node_modules/@vitest/coverage-v8": {
+ "version": "4.1.8",
+ "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.8.tgz",
+ "integrity": "sha512-lt3kovsyHwYe00wq4D1ti0Z974fWj4NLp6siqiyEufUpyFwK9Yhi7rBhac9JL5aA0zoMrJqc4vYPZRUnI7l7nw==",
"dev": true,
"license": "MIT",
- "engines": {
- "node": ">=10.0.0"
+ "dependencies": {
+ "@bcoe/v8-coverage": "^1.0.2",
+ "@vitest/utils": "4.1.8",
+ "ast-v8-to-istanbul": "^1.0.0",
+ "istanbul-lib-coverage": "^3.2.2",
+ "istanbul-lib-report": "^3.0.1",
+ "istanbul-reports": "^3.2.0",
+ "magicast": "^0.5.2",
+ "obug": "^2.1.1",
+ "std-env": "^4.0.0-rc.1",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@vitest/browser": "4.1.8",
+ "vitest": "4.1.8"
+ },
+ "peerDependenciesMeta": {
+ "@vitest/browser": {
+ "optional": true
+ }
}
},
- "node_modules/@xterm/addon-clipboard": {
- "version": "0.2.0",
- "resolved": "https://registry.npmjs.org/@xterm/addon-clipboard/-/addon-clipboard-0.2.0.tgz",
- "integrity": "sha512-Dl31BCtBhLaUEECUbEiVcCLvLBbaeGYdT7NofB8OJkGTD3MWgBsaLjXvfGAD4tQNHhm6mbKyYkR7XD8kiZsdNg==",
+ "node_modules/@vitest/expect": {
+ "version": "4.1.8",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.8.tgz",
+ "integrity": "sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "js-base64": "^3.7.5"
+ "@standard-schema/spec": "^1.1.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "4.1.8",
+ "@vitest/utils": "4.1.8",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
}
},
- "node_modules/@xterm/addon-fit": {
- "version": "0.11.0",
- "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz",
- "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",
+ "node_modules/@vitest/mocker": {
+ "version": "4.1.8",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.8.tgz",
+ "integrity": "sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==",
"dev": true,
- "license": "MIT"
- },
- "node_modules/@xterm/addon-unicode11": {
- "version": "0.9.0",
- "resolved": "https://registry.npmjs.org/@xterm/addon-unicode11/-/addon-unicode11-0.9.0.tgz",
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "4.1.8",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.21"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/mocker/node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "4.1.8",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.8.tgz",
+ "integrity": "sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "4.1.8",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.8.tgz",
+ "integrity": "sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.8",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "4.1.8",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.8.tgz",
+ "integrity": "sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.8",
+ "@vitest/utils": "4.1.8",
+ "magic-string": "^0.30.21",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "4.1.8",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.8.tgz",
+ "integrity": "sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/ui": {
+ "version": "4.1.8",
+ "resolved": "https://registry.npmjs.org/@vitest/ui/-/ui-4.1.8.tgz",
+ "integrity": "sha512-RUS2ZU2TsduVrI+9c12uTNaKrNUTsm6yFt3fueEUB9iKvyC2UP83F+sqIz00HQIah4UOL1TMoDAki8K0NjGvsA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.8",
+ "fflate": "^0.8.2",
+ "flatted": "^3.4.2",
+ "pathe": "^2.0.3",
+ "sirv": "^3.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "vitest": "4.1.8"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "4.1.8",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.8.tgz",
+ "integrity": "sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.8",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@xmldom/xmldom": {
+ "version": "0.8.13",
+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz",
+ "integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/@xterm/addon-clipboard": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/@xterm/addon-clipboard/-/addon-clipboard-0.2.0.tgz",
+ "integrity": "sha512-Dl31BCtBhLaUEECUbEiVcCLvLBbaeGYdT7NofB8OJkGTD3MWgBsaLjXvfGAD4tQNHhm6mbKyYkR7XD8kiZsdNg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "js-base64": "^3.7.5"
+ }
+ },
+ "node_modules/@xterm/addon-fit": {
+ "version": "0.11.0",
+ "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz",
+ "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@xterm/addon-unicode11": {
+ "version": "0.9.0",
+ "resolved": "https://registry.npmjs.org/@xterm/addon-unicode11/-/addon-unicode11-0.9.0.tgz",
"integrity": "sha512-FxDnYcyuXhNl+XSqGZL/t0U9eiNb/q3EWT5rYkQT/zuig8Gz/VagnQANKHdDWFM2lTMk9ly0EFQxxxtZUoRetw==",
"dev": true,
"license": "MIT"
@@ -6830,6 +7367,7 @@
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">= 14"
@@ -6839,6 +7377,7 @@
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
"integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"fast-deep-equal": "^3.1.3",
@@ -6855,6 +7394,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/ajv-draft-04/-/ajv-draft-04-1.0.0.tgz",
"integrity": "sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==",
+ "dev": true,
"license": "MIT",
"peerDependencies": {
"ajv": "^8.5.0"
@@ -7102,6 +7642,16 @@
"node": ">=10"
}
},
+ "node_modules/aria-query": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz",
+ "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/array-ify": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/array-ify/-/array-ify-1.0.0.tgz",
@@ -7129,6 +7679,45 @@
"node": ">=0.8"
}
},
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/ast-v8-to-istanbul": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.3.tgz",
+ "integrity": "sha512-jCMQ6ZylLPudp0CDfBmQBZUsrh1/8psbmu9ibeVWKuHWD0YrH9YABwlKu5kVEFoT0GCQQW9Z/SxfuEbbkGQCRg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "^0.3.31",
+ "estree-walker": "^3.0.3",
+ "js-tokens": "^10.0.0"
+ }
+ },
+ "node_modules/ast-v8-to-istanbul/node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": {
+ "version": "10.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-10.0.0.tgz",
+ "integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/astral-regex": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz",
@@ -7239,6 +7828,7 @@
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": "18 || 20 || >=22"
@@ -7407,6 +7997,16 @@
"node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x"
}
},
+ "node_modules/bidi-js": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",
+ "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "require-from-string": "^2.0.2"
+ }
+ },
"node_modules/bindings": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
@@ -7444,6 +8044,7 @@
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz",
"integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
@@ -7665,6 +8266,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz",
"integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==",
+ "dev": true,
"license": "MIT"
},
"node_modules/callsites": {
@@ -7722,6 +8324,16 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/chai": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/chalk": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
@@ -8346,6 +8958,7 @@
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
@@ -8356,6 +8969,27 @@
"node": ">= 8"
}
},
+ "node_modules/css-tree": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",
+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "mdn-data": "2.27.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"
+ }
+ },
+ "node_modules/css.escape": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz",
+ "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -8373,6 +9007,20 @@
"node": ">=0.10"
}
},
+ "node_modules/data-urls": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",
+ "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-mimetype": "^5.0.0",
+ "whatwg-url": "^16.0.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -8399,6 +9047,13 @@
"node": ">=0.10.0"
}
},
+ "node_modules/decimal.js": {
+ "version": "10.6.0",
+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/decode-named-character-reference": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",
@@ -8633,17 +9288,12 @@
"license": "MIT",
"optional": true
},
- "node_modules/doctrine": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",
- "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==",
- "license": "Apache-2.0",
- "dependencies": {
- "esutils": "^2.0.2"
- },
- "engines": {
- "node": ">=6.0.0"
- }
+ "node_modules/dom-accessibility-api": {
+ "version": "0.6.3",
+ "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz",
+ "integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==",
+ "dev": true,
+ "license": "MIT"
},
"node_modules/dot-case": {
"version": "3.0.4",
@@ -9135,6 +9785,13 @@
"node": ">= 0.4"
}
},
+ "node_modules/es-module-lexer": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz",
+ "integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/es-object-atoms": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
@@ -9499,6 +10156,7 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
"integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
+ "dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=0.10.0"
@@ -9538,6 +10196,16 @@
"node": ">=6"
}
},
+ "node_modules/expect-type": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",
+ "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/exponential-backoff": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz",
@@ -9640,6 +10308,7 @@
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "dev": true,
"license": "MIT"
},
"node_modules/fast-fifo": {
@@ -9666,6 +10335,7 @@
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
"integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",
+ "dev": true,
"funding": [
{
"type": "github",
@@ -9720,6 +10390,13 @@
}
}
},
+ "node_modules/fflate": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/file-entry-cache": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
@@ -9862,6 +10539,7 @@
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
"integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
+ "dev": true,
"license": "ISC",
"dependencies": {
"cross-spawn": "^7.0.6",
@@ -10417,6 +11095,26 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/html-encoding-sniffer": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",
+ "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@exodus/bytes": "^1.6.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/html-escaper": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
+ "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/html-parse-stringify": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",
@@ -10476,6 +11174,7 @@
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"agent-base": "^7.1.2",
@@ -10649,6 +11348,16 @@
"node": ">=0.8.19"
}
},
+ "node_modules/indent-string": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz",
+ "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
@@ -10800,6 +11509,13 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/is-potential-custom-element-name": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/is-promise": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
@@ -10829,45 +11545,99 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "dev": true,
"license": "ISC"
},
- "node_modules/jackspeak": {
- "version": "4.2.3",
- "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz",
- "integrity": "sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==",
- "license": "BlueOak-1.0.0",
- "dependencies": {
- "@isaacs/cliui": "^9.0.0"
- },
+ "node_modules/istanbul-lib-coverage": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
+ "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
+ "dev": true,
+ "license": "BSD-3-Clause",
"engines": {
- "node": "20 || >=22"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
+ "node": ">=8"
}
},
- "node_modules/jake": {
- "version": "10.9.4",
- "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz",
- "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==",
+ "node_modules/istanbul-lib-report": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
+ "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
"dev": true,
- "license": "Apache-2.0",
+ "license": "BSD-3-Clause",
"dependencies": {
- "async": "^3.2.6",
- "filelist": "^1.0.4",
- "picocolors": "^1.1.1"
- },
- "bin": {
- "jake": "bin/cli.js"
+ "istanbul-lib-coverage": "^3.0.0",
+ "make-dir": "^4.0.0",
+ "supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
}
},
- "node_modules/jiti": {
- "version": "2.7.0",
- "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
- "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",
+ "node_modules/istanbul-lib-report/node_modules/supports-color": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "has-flag": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/istanbul-reports": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
+ "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "html-escaper": "^2.0.0",
+ "istanbul-lib-report": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/jackspeak": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz",
+ "integrity": "sha512-ykkVRwrYvFm1nb2AJfKKYPr0emF6IiXDYUaFx4Zn9ZuIH7MrzEZ3sD5RlqGXNRpHtvUHJyOnCEFxOlNDtGo7wg==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "@isaacs/cliui": "^9.0.0"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/jake": {
+ "version": "10.9.4",
+ "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz",
+ "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "async": "^3.2.6",
+ "filelist": "^1.0.4",
+ "picocolors": "^1.1.1"
+ },
+ "bin": {
+ "jake": "bin/cli.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/jiti": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
+ "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",
"dev": true,
"license": "MIT",
"bin": {
@@ -10909,6 +11679,57 @@
"js-yaml": "bin/js-yaml.js"
}
},
+ "node_modules/jsdom": {
+ "version": "29.1.1",
+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz",
+ "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/css-color": "^5.1.11",
+ "@asamuzakjp/dom-selector": "^7.1.1",
+ "@bramus/specificity": "^2.4.2",
+ "@csstools/css-syntax-patches-for-csstree": "^1.1.3",
+ "@exodus/bytes": "^1.15.0",
+ "css-tree": "^3.2.1",
+ "data-urls": "^7.0.0",
+ "decimal.js": "^10.6.0",
+ "html-encoding-sniffer": "^6.0.0",
+ "is-potential-custom-element-name": "^1.0.1",
+ "lru-cache": "^11.3.5",
+ "parse5": "^8.0.1",
+ "saxes": "^6.0.0",
+ "symbol-tree": "^3.2.4",
+ "tough-cookie": "^6.0.1",
+ "undici": "^7.25.0",
+ "w3c-xmlserializer": "^5.0.0",
+ "webidl-conversions": "^8.0.1",
+ "whatwg-mimetype": "^5.0.0",
+ "whatwg-url": "^16.0.1",
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24.0.0"
+ },
+ "peerDependencies": {
+ "canvas": "^3.0.0"
+ },
+ "peerDependenciesMeta": {
+ "canvas": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/jsdom/node_modules/lru-cache": {
+ "version": "11.5.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.1.tgz",
+ "integrity": "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
"node_modules/jsesc": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
@@ -10940,6 +11761,7 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "dev": true,
"license": "MIT"
},
"node_modules/json-stable-stringify-without-jsonify": {
@@ -11555,12 +12377,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/lodash.mergewith": {
- "version": "4.6.2",
- "resolved": "https://registry.npmjs.org/lodash.mergewith/-/lodash.mergewith-4.6.2.tgz",
- "integrity": "sha512-GK3g5RPZWTRSeLSpgP8Xhra+pnjBC56q9FZYe1d5RN3TJ35dbkGy3YqBSMbyCrlbi+CM9Z3Jk5yTL7RCsqboyQ==",
- "license": "MIT"
- },
"node_modules/lodash.once": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
@@ -11745,6 +12561,16 @@
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
+ "node_modules/lz-string": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz",
+ "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "lz-string": "bin/bin.js"
+ }
+ },
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
@@ -11755,6 +12581,18 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
+ "node_modules/magicast": {
+ "version": "0.5.3",
+ "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.3.tgz",
+ "integrity": "sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.3",
+ "@babel/types": "^7.29.0",
+ "source-map-js": "^1.2.1"
+ }
+ },
"node_modules/make-cancellable-promise": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/make-cancellable-promise/-/make-cancellable-promise-2.0.0.tgz",
@@ -11765,6 +12603,22 @@
"url": "https://github.com/wojtekmaj/make-cancellable-promise?sponsor=1"
}
},
+ "node_modules/make-dir": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
+ "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^7.5.3"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/make-event-props": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/make-event-props/-/make-event-props-2.0.0.tgz",
@@ -12093,6 +12947,13 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/mdn-data": {
+ "version": "2.27.1",
+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",
+ "dev": true,
+ "license": "CC0-1.0"
+ },
"node_modules/media-typer": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz",
@@ -12799,10 +13660,21 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/min-indent": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz",
+ "integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
"node_modules/minimatch": {
"version": "10.2.5",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
"integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
+ "dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"brace-expansion": "^5.0.5"
@@ -12827,6 +13699,7 @@
"version": "7.1.3",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
"integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
+ "dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=16 || 14 >=14.17"
@@ -12892,6 +13765,16 @@
"integrity": "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ==",
"license": "MIT"
},
+ "node_modules/mrmime": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz",
+ "integrity": "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -13157,6 +14040,17 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/obug": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz",
+ "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT"
+ },
"node_modules/on-finished": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
@@ -13257,6 +14151,7 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
+ "dev": true,
"license": "BlueOak-1.0.0"
},
"node_modules/pako": {
@@ -13324,6 +14219,32 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/parse5": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "entities": "^8.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/parse5/node_modules/entities": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz",
+ "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@@ -13346,6 +14267,7 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -13355,6 +14277,7 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz",
"integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==",
+ "dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
"lru-cache": "^11.0.0",
@@ -13371,6 +14294,7 @@
"version": "11.5.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.0.tgz",
"integrity": "sha512-5YgH9UJd7wVb9hIouI2adWpgqrrICkt070Dnj8EUY1+B4B2P9eRLPAkAAo6NICA7CEhOIeBHl46u9zSNpNu7zA==",
+ "dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": "20 || >=22"
@@ -13396,6 +14320,13 @@
"node": ">=8"
}
},
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/pdfjs-dist": {
"version": "5.4.296",
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-5.4.296.tgz",
@@ -13588,6 +14519,51 @@
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
+ "node_modules/pretty-format": {
+ "version": "27.5.1",
+ "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
+ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1",
+ "ansi-styles": "^5.0.0",
+ "react-is": "^17.0.1"
+ },
+ "engines": {
+ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"
+ }
+ },
+ "node_modules/pretty-format/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/pretty-format/node_modules/ansi-styles": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
+ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/pretty-format/node_modules/react-is": {
+ "version": "17.0.2",
+ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
+ "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/prismjs": {
"version": "1.30.0",
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",
@@ -14449,6 +15425,20 @@
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"license": "MIT"
},
+ "node_modules/redent": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/redent/-/redent-3.0.0.tgz",
+ "integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "indent-string": "^4.0.0",
+ "strip-indent": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/refractor": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/refractor/-/refractor-5.0.0.tgz",
@@ -14549,6 +15539,7 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -14728,6 +15719,19 @@
"node": ">=11.0.0"
}
},
+ "node_modules/saxes": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "xmlchars": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=v12.22.7"
+ }
+ },
"node_modules/scheduler": {
"version": "0.27.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
@@ -14859,6 +15863,7 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
@@ -14871,6 +15876,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -14961,10 +15967,18 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
"node_modules/signal-exit": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
"integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
+ "dev": true,
"license": "ISC",
"engines": {
"node": ">=14"
@@ -15031,6 +16045,21 @@
"node": ">=10"
}
},
+ "node_modules/sirv": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/sirv/-/sirv-3.0.2.tgz",
+ "integrity": "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@polka/url": "^1.0.0-next.24",
+ "mrmime": "^2.0.0",
+ "totalist": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/slice-ansi": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz",
@@ -15164,6 +16193,13 @@
"nan": "^2.23.0"
}
},
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/stat-mode": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/stat-mode/-/stat-mode-1.0.0.tgz",
@@ -15190,6 +16226,13 @@
"node": ">= 0.8"
}
},
+ "node_modules/std-env": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz",
+ "integrity": "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
@@ -15300,6 +16343,19 @@
"url": "https://github.com/chalk/strip-ansi?sponsor=1"
}
},
+ "node_modules/strip-indent": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz",
+ "integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "min-indent": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/strip-json-comments": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
@@ -15376,67 +16432,12 @@
"dev": true,
"license": "MIT"
},
- "node_modules/swagger-jsdoc": {
- "version": "6.3.0",
- "resolved": "https://registry.npmjs.org/swagger-jsdoc/-/swagger-jsdoc-6.3.0.tgz",
- "integrity": "sha512-I+iQjVGV3t28pOkQUJv2MncthvOtkEactOn8R76SvSYhxgtIn7FoqfDHwQaN+GBnQdXQLrhgDXseKitmJcHMsA==",
- "license": "MIT",
- "dependencies": {
- "@apidevtools/swagger-parser": "^12.1.0",
- "commander": "6.2.0",
- "doctrine": "3.0.0",
- "glob": "11.1.0",
- "lodash.mergewith": "^4.6.2",
- "yaml": "2.0.0-1"
- },
- "bin": {
- "swagger-jsdoc": "bin/swagger-jsdoc.js"
- },
- "engines": {
- "node": ">=20.0.0"
- }
- },
- "node_modules/swagger-jsdoc/node_modules/commander": {
- "version": "6.2.0",
- "resolved": "https://registry.npmjs.org/commander/-/commander-6.2.0.tgz",
- "integrity": "sha512-zP4jEKbe8SHzKJYQmq8Y9gYjtO/POJLgIdKgV7B9qNmABVFVc+ctqSX6iXh4mCpJfRBOabiZ2YKPg8ciDw6C+Q==",
- "license": "MIT",
- "engines": {
- "node": ">= 6"
- }
- },
- "node_modules/swagger-jsdoc/node_modules/glob": {
- "version": "11.1.0",
- "resolved": "https://registry.npmjs.org/glob/-/glob-11.1.0.tgz",
- "integrity": "sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==",
- "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
- "license": "BlueOak-1.0.0",
- "dependencies": {
- "foreground-child": "^3.3.1",
- "jackspeak": "^4.1.1",
- "minimatch": "^10.1.1",
- "minipass": "^7.1.2",
- "package-json-from-dist": "^1.0.0",
- "path-scurry": "^2.0.0"
- },
- "bin": {
- "glob": "dist/esm/bin.mjs"
- },
- "engines": {
- "node": "20 || >=22"
- },
- "funding": {
- "url": "https://github.com/sponsors/isaacs"
- }
- },
- "node_modules/swagger-jsdoc/node_modules/yaml": {
- "version": "2.0.0-1",
- "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.0.0-1.tgz",
- "integrity": "sha512-W7h5dEhywMKenDJh2iX/LABkbFnBxasD27oyXWDS/feDsxiw0dD5ncXdYXgkvAsXIY2MpW/ZKkr9IU30DBdMNQ==",
- "license": "ISC",
- "engines": {
- "node": ">= 6"
- }
+ "node_modules/symbol-tree": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
+ "dev": true,
+ "license": "MIT"
},
"node_modules/tailwind-merge": {
"version": "3.6.0",
@@ -15579,6 +16580,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/tinyexec": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.2.tgz",
@@ -15606,6 +16614,36 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
+ "node_modules/tinyrainbow": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",
+ "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tldts": {
+ "version": "7.4.2",
+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.2.tgz",
+ "integrity": "sha512-kCwffuaH8ntKtygnWe1b4BJKWiCUH30n5KfoTr6IchcXOwR7chAOFJxFrH3vjANafUYrIA4a7SDL+nn7SiR4Sw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tldts-core": "^7.4.2"
+ },
+ "bin": {
+ "tldts": "bin/cli.js"
+ }
+ },
+ "node_modules/tldts-core": {
+ "version": "7.4.2",
+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.2.tgz",
+ "integrity": "sha512-nwEyF4vl4RSJjwSjBUmOSxc3BFPoIFdlRthJ6e+5v9P3bHNsoD06UjuqMUspqp7vsEZ1beaHi1km+optiE17yA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/tmp": {
"version": "0.2.6",
"resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.6.tgz",
@@ -15635,6 +16673,42 @@
"node": ">=0.6"
}
},
+ "node_modules/totalist": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/totalist/-/totalist-3.0.1.tgz",
+ "integrity": "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/tough-cookie": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.1.tgz",
+ "integrity": "sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "tldts": "^7.0.5"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/tr46": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",
+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "punycode": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"node_modules/tree-kill": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
@@ -16205,6 +17279,96 @@
"vite": ">=3.0.0"
}
},
+ "node_modules/vitest": {
+ "version": "4.1.8",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.8.tgz",
+ "integrity": "sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.8",
+ "@vitest/mocker": "4.1.8",
+ "@vitest/pretty-format": "4.1.8",
+ "@vitest/runner": "4.1.8",
+ "@vitest/snapshot": "4.1.8",
+ "@vitest/spy": "4.1.8",
+ "@vitest/utils": "4.1.8",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.8",
+ "@vitest/browser-preview": "4.1.8",
+ "@vitest/browser-webdriverio": "4.1.8",
+ "@vitest/coverage-istanbul": "4.1.8",
+ "@vitest/coverage-v8": "4.1.8",
+ "@vitest/ui": "4.1.8",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
"node_modules/void-elements": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/void-elements/-/void-elements-3.1.0.tgz",
@@ -16222,6 +17386,19 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/w3c-xmlserializer": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/warning": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/warning/-/warning-4.0.3.tgz",
@@ -16232,10 +17409,46 @@
"loose-envify": "^1.0.0"
}
},
+ "node_modules/webidl-conversions": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",
+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/whatwg-mimetype": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",
+ "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/whatwg-url": {
+ "version": "16.0.1",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",
+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@exodus/bytes": "^1.11.0",
+ "tr46": "^6.0.0",
+ "webidl-conversions": "^8.0.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
@@ -16253,6 +17466,23 @@
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
"license": "ISC"
},
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
@@ -16338,6 +17568,16 @@
}
}
},
+ "node_modules/xml-name-validator": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/xmlbuilder": {
"version": "15.1.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
@@ -16348,6 +17588,13 @@
"node": ">=8.0"
}
},
+ "node_modules/xmlchars": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
diff --git a/package.json b/package.json
index 62889b18e..88a8cc0b5 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "termix",
"private": true,
- "version": "2.3.1",
+ "version": "2.3.2",
"description": "Self-hosted SSH and remote desktop management.",
"author": "Karmaa",
"main": "electron/main.cjs",
@@ -17,6 +17,10 @@
"lint": "eslint .",
"lint:fix": "eslint --fix .",
"type-check": "tsc --noEmit",
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "test:ui": "vitest --ui",
+ "test:coverage": "vitest run --coverage",
"dev": "vite",
"build": "vite build && tsc -p tsconfig.node.json && node -e \"require('fs').copyFileSync('src/backend/package.json','dist/backend/package.json')\"",
"build:backend": "tsc -p tsconfig.node.json && node -e \"require('fs').copyFileSync('src/backend/package.json','dist/backend/package.json')\"",
@@ -37,7 +41,6 @@
"build:mac-dev": "npm run build && npm run electron:rebuild && npm run electron:patch-builder && electron-builder --mac dir --publish=never"
},
"dependencies": {
- "@tanstack/react-virtual": "^3.13.26",
"axios": "^1.15.2",
"bcryptjs": "^3.0.3",
"better-sqlite3": "^12.9.0",
@@ -49,7 +52,6 @@
"drizzle-orm": "^0.45.2",
"express": "^5.2.1",
"guacamole-lite": "^1.2.0",
- "https-proxy-agent": "^7.0.6",
"jose": "^6.2.2",
"js-yaml": "^4.1.1",
"jsonwebtoken": "^9.0.3",
@@ -61,7 +63,6 @@
"socks": "^2.8.7",
"speakeasy": "^2.0.0",
"ssh2": "^1.17.0",
- "swagger-jsdoc": "^6.3.0",
"undici": "^7.0.0",
"ws": "^8.20.0"
},
@@ -96,6 +97,10 @@
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-tooltip": "^1.2.8",
"@tailwindcss/vite": "^4.2.4",
+ "@testing-library/dom": "^10.4.1",
+ "@testing-library/jest-dom": "^6.9.1",
+ "@testing-library/react": "^16.3.2",
+ "@testing-library/user-event": "^14.6.1",
"@types/better-sqlite3": "^7.6.13",
"@types/cookie-parser": "^1.4.10",
"@types/cors": "^2.8.19",
@@ -115,6 +120,8 @@
"@uiw/codemirror-theme-github": "^4.25.9",
"@uiw/react-codemirror": "^4.25.9",
"@vitejs/plugin-react": "^6.0.1",
+ "@vitest/coverage-v8": "^4.1.8",
+ "@vitest/ui": "^4.1.8",
"@xterm/addon-clipboard": "^0.2.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/addon-unicode11": "^0.9.0",
@@ -136,6 +143,7 @@
"husky": "^9.1.7",
"i18next": "^26.0.8",
"i18next-browser-languagedetector": "^8.2.1",
+ "jsdom": "^29.1.1",
"lint-staged": "^17.0.5",
"lucide-react": "^1.11.0",
"prettier": "3.8.3",
@@ -161,7 +169,8 @@
"typescript": "~6.0.3",
"typescript-eslint": "^8.59.0",
"vite": "^8.0.13",
- "vite-plugin-svgr": "^5.2.0"
+ "vite-plugin-svgr": "^5.2.0",
+ "vitest": "^4.1.8"
},
"lint-staged": {
"*.{ts,tsx}": [
diff --git a/readme/HOST-TO-HOST-TRANSFER.md b/readme/HOST-TO-HOST-TRANSFER.md
new file mode 100644
index 000000000..d156e4e05
--- /dev/null
+++ b/readme/HOST-TO-HOST-TRANSFER.md
@@ -0,0 +1,185 @@
+# Host-to-host file transfer
+
+This document describes the host-to-host copy/move feature. It is intended for operators and contributors. Direct host-to-host routing via SSH tunnels is **not implemented**; that is documented under [Future work](#future-work-direct-routing-via-tunnels).
+
+## Overview
+
+Host-to-host transfer copies or moves files from one SSH host to another through the **Termix server** as a relay. The UI lives in **File Manager**: right-click files or folders and choose **Copy to host…** or **Move to host…**.
+
+Compared to copying via your laptop (`scp -3` or `ssh one 'cat …' | ssh two 'cat …'`), Termix keeps the job on the server so transfers continue if you close the browser, and you get integrated progress, cancel, retry, and cleanup.
+
+```mermaid
+flowchart LR
+ Browser[Browser_UI]
+ Termix[Termix_server]
+ Src[Source_host]
+ Dst[Destination_host]
+
+ Browser -->|start_transfer_API| Termix
+ Termix -->|dedicated_SSH_xfer_src| Src
+ Termix -->|dedicated_SSH_xfer_dst| Dst
+ Termix -->|SFTP_read_then_write| Termix
+```
+
+Data for remote-to-remote paths **always passes through the Termix process** (pipelined SFTP buffers, or a tar archive stream). There is no source→destination SSH tunnel for file bytes today.
+
+## Prerequisites
+
+1. **Two hosts** with File Manager enabled, saved in Host Manager.
+2. **Both hosts reachable from the Termix server** on SSH (each host’s jump hosts and SOCKS5 proxy chain apply to the **Termix→host** connection, not host→host).
+3. **File Manager open** on the source host (browse session connected). The destination host should show **Ready** in the transfer dialog; if it shows authentication required, open File Manager on that host once first.
+4. For **multi-file or folder** transfers, pick a **destination directory** (not a file path).
+
+The dialog shows a reminder: _“Both hosts must be reachable from the Termix server. Direct host-to-host routing is not supported.”_
+
+## Using the UI
+
+### Start a transfer
+
+1. Open File Manager on the **source** host.
+2. Select one or more files or folders.
+3. Right-click → **Copy to host…** or **Move to host…** (sidebar tree supports the same context menu).
+4. In the dialog:
+ - Choose **destination host** (other connected file-manager hosts).
+ - Set **destination path** (type a path or use **Browse destination folders**).
+ - Optionally pick a **recent destination** (collapsed by default).
+ - For multi-item transfers, choose **transfer method** (Auto / Tar archive / Per-file SFTP); a preview explains what Auto will pick.
+ - Pin folders with **Add to shortcuts** (per-destination host; uses normal file-manager shortcuts, not a separate favourites list).
+5. Confirm **Copy** or **Move**.
+
+### During transfer
+
+- A **progress toast** shows phase (compressing, transferring, extracting), bytes, speed, and **Cancel**.
+- **Transfer monitor** (desktop, when authenticated) picks up active transfers started in another tab or window.
+- Large **single files** use segmented SFTP (256 MiB segments) with **2 parallel lanes** by default (separate dedicated SSH session pairs per lane). The toast can show total speed and lane count when multiple lanes are active.
+
+### After completion or failure
+
+| Outcome | What happens |
+| ------------- | ---------------------------------------------------------------------------------------------------------------- |
+| **Success** | Toast success; destination path saved to **recent destinations** for that source host; file manager can refresh. |
+| **Partial** | Some paths failed; toast lists failed paths; source may be kept on move. |
+| **Error** | Toast with **Retry** when partial data on destination allows resume. |
+| **Cancelled** | Toast with optional **Clean up destination** to remove partial files. |
+
+**Move** deletes source files only after a successful full transfer (same as copy, then source delete). Cancelled or partial moves may leave files on both sides.
+
+### Metrics
+
+On success, expanded timing details can include: prepare destination, compress (tar), per-hop throughput (source→server, server→dest), extract, source delete, total duration.
+
+## Transfer methods
+
+| Method | When used | Behavior |
+| ------------------------ | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
+| **Stream (single file)** | Exactly one file, copy or move | Pipelined SFTP read on source → write on destination; segmented above 32 MiB; parallel lanes for throughput. |
+| **Tar archive** | Multi-file/folder when Auto or user selects Tar, and both sides are Unix with `tar` | `tar -czf` on source → one archive streamed through Termix → `tar -xzf` on destination. |
+| **Per-file SFTP** | Windows involved, tar unavailable, or Auto chooses it | Each file copied sequentially over SFTP through Termix. |
+
+**Auto** heuristics (see `src/backend/ssh/transfer-routing.ts`) consider file count, total size, largest file, and compressibility (e.g. many small files → tar; large incompressible sets → per-file SFTP).
+
+**Method preview** is locked for the current source path set until you change Auto/Tar/Per-file preference, so changing only the destination host does not re-scan the source.
+
+## Architecture (implementation)
+
+| Component | Role |
+| ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
+| [`src/backend/ssh/host-transfer.ts`](../src/backend/ssh/host-transfer.ts) | Transfer engine: sessions, SFTP pipeline, tar path, retry, cancel, progress. |
+| [`src/backend/ssh/file-manager.ts`](../src/backend/ssh/file-manager.ts) | HTTP routes, `openDedicatedTransferSession`, jump/SOCKS connect. |
+| [`src/backend/ssh/transfer-routing.ts`](../src/backend/ssh/transfer-routing.ts) | Tar vs per-file SFTP selection. |
+| [`src/backend/ssh/transfer-paths.ts`](../src/backend/ssh/transfer-paths.ts) | Path normalization (Unix/Windows). |
+| [`src/ui/.../TransferToHostDialog.tsx`](../src/ui/desktop/apps/features/file-manager/components/TransferToHostDialog.tsx) | Transfer dialog. |
+| [`src/ui/.../transferProgressMonitor.tsx`](../src/ui/desktop/apps/features/file-manager/transferProgressMonitor.tsx) | Toasts, cancel, retry, cleanup. |
+| [`src/ui/.../TransferMonitor.tsx`](../src/ui/desktop/apps/features/file-manager/TransferMonitor.tsx) | Global active-transfer polling. |
+
+**Sessions:** Browse sessions identify hosts. Each transfer opens **dedicated** SSH sessions (`xfer:{transferId}:src` / `:dst`) so browsing and transfers do not share channels. Parallel lanes add `xfer:{transferId}:src:pN` / `:dst:pN`.
+
+**Special case:** If the destination host is the **same machine as Termix** (local SSH endpoint), writes use the local filesystem via `fastGet` instead of dest SFTP; data still originates from the remote source through Termix.
+
+**Persistence:** Recent destinations are stored in `transfer_recent` (per user, per source host). Folder shortcuts use `file_manager_shortcuts` on the destination host.
+
+## HTTP API (file manager service)
+
+| Endpoint | Purpose |
+| -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `POST /ssh/file_manager/ssh/transferMethodPreview` | Scan source; return resolved tar vs item_sftp and reason. |
+| `POST /ssh/file_manager/ssh/transferToHost` | Start transfer; body includes `sourceSessionId`, `destSessionId`, `sourcePaths`, `destPath`, `move`, `methodPreference`, optional `parallelSegmentCount` (1–8, default 2). |
+| `GET /ssh/file_manager/ssh/transferStatus/:transferId` | Poll progress. |
+| `GET /ssh/file_manager/ssh/activeTransfers` | List running transfers for user. |
+| `POST /ssh/file_manager/ssh/transferCancel/:transferId` | Request cancel. |
+| `POST /ssh/file_manager/ssh/transferCleanup/:transferId` | Remove partial destination artifacts after cancel/failure. |
+| `POST /ssh/file_manager/ssh/transferRetry/:transferId` | Retry with same snapshot (resume when possible). |
+
+Database (main API): `GET/POST /host/transfer/recent` for recent destinations.
+
+## Reliability features
+
+- **Resume:** Destination file size is probed; SFTP write opens with resume when a partial file exists (per segment on large files).
+- **Retry:** Reconnects dedicated sessions; segment-level and full-copy retries with backoff; fresh SSH pairs after repeated failures (lane reset).
+- **Stall detection:** ~45 s without progress on a segment; hung transfer/reconnect probing on status polls.
+- **Cancel:** Aborts in-flight SFTP; user can clean up destination paths that were created or partially written.
+- **Overlap guard:** Refuses transfer when source and destination paths overlap in a destructive way.
+
+## Limitations
+
+1. **No direct host-to-host data path** — Termix must reach **both** hosts independently (with each host’s jump/proxy settings).
+2. **Not the same as S2S SSH tunnels** — Tunnels in Host Manager forward TCP ports; they do not carry file-manager transfers today.
+3. **Throughput** — Remote-to-remote speed is bounded by Termix CPU/RAM and min(Termix↔source, Termix↔dest) links; very large files on a small Termix box may be slower than `scp -3` from a powerful desktop.
+4. **Parallel lanes** — Writes are out of order on disk; fine for copy, not for playing media from a partially written file. Default is 2 lanes; UI may not expose lane count (API default applies).
+5. **Tar** — Requires `tar` on both Unix hosts; temporary archive under `/tmp` on source during transfer.
+6. **Windows** — Tar path disabled; per-file SFTP only for Windows endpoints.
+7. **Jump hosts on S2S tunnels** — Server-to-server **tunnel** connect does not use jump hosts; only transfer/browse SSH does. A host reachable only via jump may work for transfer but not as an S2S tunnel source until tunnel code is aligned.
+
+## Troubleshooting
+
+| Symptom | Things to check |
+| ------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
+| No destination hosts listed | Open File Manager on another host; ensure host has File Manager enabled. |
+| Destination “Authentication required” | Connect File Manager on that host once in this session. |
+| Transfer fails immediately | SSH from Termix to both hosts (firewall, jump host, SOCKS5, credentials). |
+| Slow speed | Termix link to slower side; try off-peak; for single huge files, parallel lanes help if CPU/network allow. |
+| Stuck progress | Wait for stall/reconnect; cancel and retry; check server logs for `host_transfer` / `transfer_ssh_*`. |
+| Partial files after cancel | Use **Clean up destination** in the toast. |
+| 28 GB / 25 GB style progress | Usually parallel progress accounting; status polls use destination size probes. |
+
+## Comparison to manual `scp` between remotes
+
+See [Unix & Linux: scp from one remote server to another](https://unix.stackexchange.com/questions/85292/scp-from-one-remote-server-to-another-remote-server). Naive `scp one:file two:file` runs **from the first host** and fails unless that host can SSH to the second. `scp -3` relays through your workstation. **Termix relay** is analogous to `scp -3` through the **Termix server**, with richer lifecycle management, not analogous to direct `ssh source 'scp … dest'`.
+
+---
+
+## Future work: direct routing via tunnels
+
+The following are **planned / discussed** enhancements, not shipped in the current build. They build on existing **S2S SSH tunnels** (`src/backend/ssh/tunnel.ts`), which already connect **source → endpoint** using `forwardOut` from the source host to the endpoint’s SSH port.
+
+### Why tunnels matter
+
+Many homelabs have a destination that is **only reachable from another host** (e.g. NAS on LAN behind a Pi), while Termix runs elsewhere. Today that destination cannot receive a dedicated `xfer:dst` session from Termix even if an S2S tunnel from Pi → NAS is configured and working.
+
+### Possible routes (future)
+
+| Route | Termix SSH legs | Data path | Benefit vs today |
+| --------------------------------------- | --------------- | --------------------------- | ---------------------------------------------------------------------------------------- |
+| **Relay (current)** | 2 | Termix buffers SFTP | Works when both hosts reachable from Termix. |
+| **Tunnel-bridged SFTP** | 1 (+ bridge) | Still through Termix memory | Dest reached via source `forwardOut`; fixes reachability; reuses most of current engine. |
+| **Direct remote (rsync/scp on source)** | 1 (control) | **Source → dest** bytes | Best throughput; Termix orchestrates `rsync`/`scp` on source when forward + tools allow. |
+
+### Integration ideas (not implemented)
+
+1. **`transfer-bridge` module** — Shared `forwardOut` probe and `connectDestThroughSource` (extracted from tunnel code); lookup matching `tunnel_connections` on the source host record.
+2. **Route resolver** — Auto-select relay vs bridged vs direct; expose route in method preview (“via Termix” vs “direct host-to-host”).
+3. **Reuse active S2S tunnel** — If Host Manager tunnel source→dest is already connected, reuse `endpointClient` instead of opening a second bridge.
+4. **Jump hosts on S2S tunnel source** — Align tunnel connect with file-manager jump chains so tunnel and transfer eligibility match.
+5. **Fallback** — Always fall back to current relay when probe or remote `rsync` fails (Windows, missing tools, forwarding denied).
+
+### What would be preserved
+
+Cancel, partial cleanup, retry/resume (rsync `--partial` on direct path; existing SFTP segment resume on relay/bridged), dedicated sessions, transfer monitor, recent destinations, folder shortcuts, and tar/per-file method selection (with direct-path variants for multi-file).
+
+### References
+
+- Internal plan: `.cursor/plans/host-to-host_direct_transfer_*.plan.md` (if present in your checkout).
+- Tunnel implementation: [`src/backend/ssh/tunnel.ts`](../src/backend/ssh/tunnel.ts) — `connectEndpointThroughSource`, `establishManagedS2STunnel`.
+- Transfer engine: [`src/backend/ssh/host-transfer.ts`](../src/backend/ssh/host-transfer.ts).
+
+---
diff --git a/scripts/generate-release-body.cjs b/scripts/generate-release-body.cjs
new file mode 100644
index 000000000..d213015b9
--- /dev/null
+++ b/scripts/generate-release-body.cjs
@@ -0,0 +1,121 @@
+const fs = require("fs");
+const path = require("path");
+
+function parseArgs(argv) {
+ const args = {};
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg.startsWith("--")) {
+ const key = arg.slice(2);
+ const next = argv[i + 1];
+ if (next === undefined || next.startsWith("--")) {
+ args[key] = true;
+ } else {
+ args[key] = next;
+ i++;
+ }
+ }
+ }
+ return args;
+}
+
+function fail(message) {
+ console.error(`generate-release-body: ${message}`);
+ process.exit(1);
+}
+
+function extractSection(notes, name) {
+ const pattern = new RegExp(
+ `<!--\\s*${name}\\s*-->([\\s\\S]*?)<!--\\s*/${name}\\s*-->`,
+ );
+ const match = notes.match(pattern);
+ if (!match) {
+ fail(`missing <!-- ${name} --> section in release notes`);
+ }
+ const value = match[1].trim();
+ if (!value) {
+ fail(`empty <!-- ${name} --> section in release notes`);
+ }
+ return value;
+}
+
+function youtubeId(raw) {
+ const value = raw.trim();
+ let match = value.match(/[?&]v=([A-Za-z0-9_-]+)/);
+ if (match) return match[1];
+ match = value.match(/youtu\.be\/([A-Za-z0-9_-]+)/);
+ if (match) return match[1];
+ match = value.match(/embed\/([A-Za-z0-9_-]+)/);
+ if (match) return match[1];
+ if (/^[A-Za-z0-9_-]+$/.test(value)) return value;
+ fail(`could not parse a YouTube video id from "${value}"`);
+}
+
+function buildTable(version, mobileVersion) {
+ const tag = `release-${version}-tag`;
+ const base = `https://github.com/Termix-SSH/Termix/releases/download/${tag}`;
+ const mobileBase = `https://github.com/Termix-SSH/Mobile/releases/download/release-${mobileVersion}-tag`;
+
+ const win = (file) => `${base}/${file}`;
+ const linux = (file) => `${base}/${file}`;
+ const mac = (file) => `${base}/${file}`;
+
+ return [
+ `| Architecture | Windows | Linux | Mac | Android | iOS |`,
+ `|------------------|------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|---------------------------------------------|-----------------------------------|`,
+ `| **x86-64 (64-bit)** | [EXE](${win("termix_windows_x64_nsis.exe")}) · [MSI](${win("termix_windows_x64_msi.msi")}) · [Portable](${win("termix_windows_x64_portable.zip")}) | [AppImage](${linux("termix_linux_x64_appimage.AppImage")}) · [DEB](${linux("termix_linux_x64_deb.deb")}) · [Portable](${linux("termix_linux_x64_portable.tar.gz")}) | [DMG](${mac("termix_macos_x64_dmg.dmg")}) | — | — |`,
+ `| **AArch64 (ARM64)** | — | [AppImage](${linux("termix_linux_arm64_appimage.AppImage")}) · [DEB](${linux("termix_linux_arm64_deb.deb")}) · [Portable](${linux("termix_linux_arm64_portable.tar.gz")}) | [DMG](${mac("termix_macos_arm64_dmg.dmg")}) | [APK (${mobileVersion})](${mobileBase}/termix_android.apk) | [IPA (${mobileVersion})](${mobileBase}/termix_ios.ipa) |`,
+ `| **ARMv7 (32-bit)** | — | [AppImage](${linux("termix_linux_armv7l_appimage.AppImage")}) · [DEB](${linux("termix_linux_armv7l_deb.deb")}) · [Portable](${linux("termix_linux_armv7l_portable.tar.gz")}) | — | — | — |`,
+ `| **x86-32 (32-bit)** | [EXE](${win("termix_windows_ia32_nsis.exe")}) · [MSI](${win("termix_windows_ia32_msi.msi")}) · [Portable](${win("termix_windows_ia32_portable.zip")}) | — | — | — | — |`,
+ `| **Universal** | [Chocolatey](https://docs.termix.site/install/connector/windows) | [Flatpak](https://docs.termix.site/install/connector/linux) | [DMG](${mac("termix_macos_universal_dmg.dmg")}) · [App Store](https://apps.apple.com/us/app/termix-ssh-companion/id6752672071) · [Homebrew](https://docs.termix.site/install/connector/macos) | — | — |`,
+ ].join("\n");
+}
+
+function main() {
+ const args = parseArgs(process.argv.slice(2));
+ const version = args.version;
+ const mobileVersion = args["mobile-version"];
+ const notesPath = args.notes || "RELEASE_NOTES.md";
+
+ if (!version || version === true) fail("--version is required");
+ if (!mobileVersion || mobileVersion === true)
+ fail("--mobile-version is required");
+
+ const resolvedNotes = path.resolve(notesPath);
+ if (!fs.existsSync(resolvedNotes)) {
+ fail(`release notes file not found: ${resolvedNotes}`);
+ }
+
+ const notes = fs.readFileSync(resolvedNotes, "utf8");
+ const summary = extractSection(notes, "SUMMARY");
+ const youtube = extractSection(notes, "YOUTUBE");
+ const updateLog = extractSection(notes, "UPDATE_LOG");
+ const bugFixes = extractSection(notes, "BUG_FIXES");
+
+ const videoId = youtubeId(youtube);
+ const embed = [
+ `<a href="https://youtu.be/${videoId}">`,
+ ` <img src="./repo-images/YouTube.png" alt="YouTube" width="500">`,
+ `</a>`,
+ ].join("\n");
+
+ const table = buildTable(version, mobileVersion);
+
+ const body = [
+ summary,
+ "",
+ embed,
+ "",
+ table,
+ "",
+ "Update Log:",
+ updateLog,
+ "",
+ "Bug Fixes:",
+ bugFixes,
+ ].join("\n");
+
+ process.stdout.write(body + "\n");
+}
+
+main();
diff --git a/scripts/patch-guacamole-lite.cjs b/scripts/patch-guacamole-lite.cjs
index 7d5de1be4..f38891539 100644
--- a/scripts/patch-guacamole-lite.cjs
+++ b/scripts/patch-guacamole-lite.cjs
@@ -26,11 +26,28 @@ const newVersionCheck =
const oldTimezone = "if (protocolVersion === '1_1_0') {";
const newTimezone = "if (protocolVersion !== '1_0_0') {";
+// Patch 3: send the `name` handshake instruction for protocol >= 1.3.0.
+// The Guacamole protocol added the `name` instruction in 1.3.0 (an optional
+// human-readable identifier for the joining user). guacd 1.6.0 began requiring
+// it during the VNC handshake even when negotiating older protocol versions,
+// causing connections to silently drop right after "User joined". See
+// Termix-SSH/Support#567 and #734.
+const oldConnect =
+ " this.sendInstruction(['connect'].concat(connectArgs));";
+const newConnect =
+ " if (protocolVersion === '1_3_0' || protocolVersion === '1_5_0') {\n" +
+ " this.sendInstruction(['name', this.connectionSettings.name || 'guacamole-lite']);\n" +
+ " }\n" +
+ "\n" +
+ " this.sendInstruction(['connect'].concat(connectArgs));";
+
let patched = false;
if (!content.includes(newVersionCheck)) {
if (!content.includes(oldVersionCheck)) {
- console.log("[patch-guacamole-lite] Version check target not found, skipping");
+ console.log(
+ "[patch-guacamole-lite] Version check target not found, skipping",
+ );
process.exit(0);
}
content = content.replace(oldVersionCheck, newVersionCheck);
@@ -46,6 +63,17 @@ if (!content.includes(newTimezone)) {
patched = true;
}
+if (!content.includes(newConnect)) {
+ if (!content.includes(oldConnect)) {
+ console.log(
+ "[patch-guacamole-lite] Connect target not found, skipping name patch",
+ );
+ process.exit(0);
+ }
+ content = content.replace(oldConnect, newConnect);
+ patched = true;
+}
+
if (!patched) {
console.log("[patch-guacamole-lite] Already patched");
process.exit(0);
@@ -53,5 +81,5 @@ if (!patched) {
fs.writeFileSync(filePath, content);
console.log(
- "[patch-guacamole-lite] Patched to support protocol VERSION_1_3_0 and VERSION_1_5_0 with correct timezone handshake",
+ "[patch-guacamole-lite] Patched to support protocol VERSION_1_3_0 and VERSION_1_5_0 with name handshake instruction",
);
diff --git a/src/backend/database/database.ts b/src/backend/database/database.ts
index 3694bb043..292284edf 100644
--- a/src/backend/database/database.ts
+++ b/src/backend/database/database.ts
@@ -809,6 +809,16 @@ app.post("/database/export", authenticateJWT, async (req, res) => {
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
+ CREATE TABLE transfer_recent (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id TEXT NOT NULL,
+ source_host_id INTEGER NOT NULL,
+ dest_host_id INTEGER NOT NULL,
+ dest_path TEXT NOT NULL,
+ dest_path_label TEXT NOT NULL,
+ last_used TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
+ );
+
CREATE TABLE dismissed_alerts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
@@ -1063,6 +1073,12 @@ app.post("/database/export", authenticateJWT, async (req, res) => {
VALUES (?, ?)
`);
for (const setting of settingsData) {
+ if (
+ setting.key.startsWith("reset_code_") ||
+ setting.key.startsWith("temp_reset_token_")
+ ) {
+ continue;
+ }
insertSetting.run(setting.key, setting.value);
}
} finally {
diff --git a/src/backend/database/db/index.ts b/src/backend/database/db/index.ts
index 5a64dcf00..8d50f3de7 100644
--- a/src/backend/database/db/index.ts
+++ b/src/backend/database/db/index.ts
@@ -268,6 +268,19 @@ async function initializeCompleteDatabase(): Promise<void> {
FOREIGN KEY (host_id) REFERENCES ssh_data (id) ON DELETE CASCADE
);
+ CREATE TABLE IF NOT EXISTS transfer_recent (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id TEXT NOT NULL,
+ source_host_id INTEGER NOT NULL,
+ dest_host_id INTEGER NOT NULL,
+ dest_path TEXT NOT NULL,
+ dest_path_label TEXT NOT NULL,
+ last_used TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
+ FOREIGN KEY (source_host_id) REFERENCES ssh_data (id) ON DELETE CASCADE,
+ FOREIGN KEY (dest_host_id) REFERENCES ssh_data (id) ON DELETE CASCADE
+ );
+
CREATE TABLE IF NOT EXISTS dismissed_alerts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
@@ -467,6 +480,10 @@ async function initializeCompleteDatabase(): Promise<void> {
CREATE TABLE IF NOT EXISTS user_preferences (
user_id TEXT PRIMARY KEY,
reopen_tabs_on_login INTEGER NOT NULL DEFAULT 0,
+ theme TEXT,
+ font_size TEXT,
+ accent_color TEXT,
+ language TEXT,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);
@@ -563,11 +580,12 @@ async function initializeCompleteDatabase(): Promise<void> {
.prepare("SELECT value FROM settings WHERE key = 'guac_url'")
.get();
if (!row) {
+ const defaultGuacUrl = `${process.env.GUACD_HOST || "localhost"}:${process.env.GUACD_PORT || "4822"}`;
sqlite
.prepare(
- "INSERT INTO settings (key, value) VALUES ('guac_url', 'guacd:4822')",
+ "INSERT INTO settings (key, value) VALUES ('guac_url', ?)",
)
- .run();
+ .run(defaultGuacUrl);
}
} catch (e) {
databaseLogger.warn("Could not initialize guac_url setting", {
@@ -605,6 +623,11 @@ const addColumnIfNotExists = (
};
const migrateSchema = () => {
+ addColumnIfNotExists("user_preferences", "theme", "TEXT");
+ addColumnIfNotExists("user_preferences", "font_size", "TEXT");
+ addColumnIfNotExists("user_preferences", "accent_color", "TEXT");
+ addColumnIfNotExists("user_preferences", "language", "TEXT");
+
addColumnIfNotExists("users", "is_admin", "INTEGER NOT NULL DEFAULT 0");
addColumnIfNotExists("users", "is_oidc", "INTEGER NOT NULL DEFAULT 0");
diff --git a/src/backend/database/db/schema.ts b/src/backend/database/db/schema.ts
index dc65fbe52..3907e3414 100644
--- a/src/backend/database/db/schema.ts
+++ b/src/backend/database/db/schema.ts
@@ -226,6 +226,24 @@ export const fileManagerShortcuts = sqliteTable("file_manager_shortcuts", {
.default(sql`CURRENT_TIMESTAMP`),
});
+export const transferRecent = sqliteTable("transfer_recent", {
+ id: integer("id").primaryKey({ autoIncrement: true }),
+ userId: text("user_id")
+ .notNull()
+ .references(() => users.id, { onDelete: "cascade" }),
+ sourceHostId: integer("source_host_id")
+ .notNull()
+ .references(() => hosts.id, { onDelete: "cascade" }),
+ destHostId: integer("dest_host_id")
+ .notNull()
+ .references(() => hosts.id, { onDelete: "cascade" }),
+ destPath: text("dest_path").notNull(),
+ destPathLabel: text("dest_path_label").notNull(),
+ lastUsed: text("last_used")
+ .notNull()
+ .default(sql`CURRENT_TIMESTAMP`),
+});
+
export const dismissedAlerts = sqliteTable("dismissed_alerts", {
id: integer("id").primaryKey({ autoIncrement: true }),
userId: text("user_id")
@@ -658,6 +676,10 @@ export const userPreferences = sqliteTable("user_preferences", {
reopenTabsOnLogin: integer("reopen_tabs_on_login", { mode: "boolean" })
.notNull()
.default(false),
+ theme: text("theme"),
+ fontSize: text("font_size"),
+ accentColor: text("accent_color"),
+ language: text("language"),
updatedAt: text("updated_at")
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
diff --git a/src/backend/database/routes/credential-deploy-routes.ts b/src/backend/database/routes/credential-deploy-routes.ts
new file mode 100644
index 000000000..40db47e8a
--- /dev/null
+++ b/src/backend/database/routes/credential-deploy-routes.ts
@@ -0,0 +1,554 @@
+import type {
+ AuthenticatedRequest,
+ CredentialBackend,
+} from "../../../types/index.js";
+import type { Request, RequestHandler, Response, Router } from "express";
+import { eq } from "drizzle-orm";
+import ssh2Pkg from "ssh2";
+import { db } from "../db/index.js";
+import { hosts, sshCredentials } from "../db/schema.js";
+
+const { Client } = ssh2Pkg;
+
+async function deploySSHKeyToHost(
+ hostConfig: Record<string, unknown>,
+ credData: CredentialBackend,
+): Promise<{ success: boolean; message?: string; error?: string }> {
+ const publicKey = credData.publicKey as string;
+ return new Promise((resolve) => {
+ const conn = new Client();
+
+ const connectionTimeout = setTimeout(() => {
+ conn.destroy();
+ resolve({ success: false, error: "Connection timeout" });
+ }, 120000);
+
+ conn.on("ready", async () => {
+ clearTimeout(connectionTimeout);
+
+ try {
+ await new Promise<void>((resolveCmd, rejectCmd) => {
+ const cmdTimeout = setTimeout(() => {
+ rejectCmd(new Error("mkdir command timeout"));
+ }, 10000);
+
+ conn.exec(
+ "test -d ~/.ssh || mkdir -p ~/.ssh; chmod 700 ~/.ssh",
+ (err, stream) => {
+ if (err) {
+ clearTimeout(cmdTimeout);
+ return rejectCmd(err);
+ }
+
+ stream.on("close", (code) => {
+ clearTimeout(cmdTimeout);
+ if (code === 0) {
+ resolveCmd();
+ } else {
+ rejectCmd(
+ new Error(`mkdir command failed with code ${code}`),
+ );
+ }
+ });
+
+ stream.on("data", () => {
+ // Ignore output
+ });
+ },
+ );
+ });
+
+ const keyExists = await new Promise<boolean>(
+ (resolveCheck, rejectCheck) => {
+ const checkTimeout = setTimeout(() => {
+ rejectCheck(new Error("Key check timeout"));
+ }, 5000);
+
+ let actualPublicKey = publicKey;
+ try {
+ const parsed = JSON.parse(publicKey);
+ if (parsed.data) {
+ actualPublicKey = parsed.data;
+ }
+ } catch {
+ // Ignore parse errors
+ }
+
+ const keyParts = actualPublicKey.trim().split(" ");
+ if (keyParts.length < 2) {
+ clearTimeout(checkTimeout);
+ return rejectCheck(
+ new Error(
+ "Invalid public key format - must contain at least 2 parts",
+ ),
+ );
+ }
+
+ const keyPattern = keyParts[1];
+
+ conn.exec(
+ `if [ -f ~/.ssh/authorized_keys ]; then grep -F "${keyPattern}" ~/.ssh/authorized_keys >/dev/null 2>&1; echo $?; else echo 1; fi`,
+ (err, stream) => {
+ if (err) {
+ clearTimeout(checkTimeout);
+ return rejectCheck(err);
+ }
+
+ let output = "";
+ stream.on("data", (data) => {
+ output += data.toString();
+ });
+
+ stream.on("close", () => {
+ clearTimeout(checkTimeout);
+ const exists = output.trim() === "0";
+ resolveCheck(exists);
+ });
+ },
+ );
+ },
+ );
+
+ if (keyExists) {
+ conn.end();
+ resolve({ success: true, message: "SSH key already deployed" });
+ return;
+ }
+
+ await new Promise<void>((resolveAdd, rejectAdd) => {
+ const addTimeout = setTimeout(() => {
+ rejectAdd(new Error("Key add timeout"));
+ }, 30000);
+
+ let actualPublicKey = publicKey;
+ try {
+ const parsed = JSON.parse(publicKey);
+ if (parsed.data) {
+ actualPublicKey = parsed.data;
+ }
+ } catch {
+ // Ignore parse errors
+ }
+
+ const escapedKey = actualPublicKey
+ .replace(/\\/g, "\\\\")
+ .replace(/'/g, "'\\''");
+ const escapedName = credData.name
+ .replace(/\\/g, "\\\\")
+ .replace(/'/g, "'\\''");
+
+ conn.exec(
+ `printf '%s\n' '${escapedKey} ${escapedName}@Termix' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`,
+ (err, stream) => {
+ if (err) {
+ clearTimeout(addTimeout);
+ return rejectAdd(err);
+ }
+
+ stream.on("data", () => {
+ // Consume output
+ });
+
+ stream.on("close", (code) => {
+ clearTimeout(addTimeout);
+ if (code === 0) {
+ resolveAdd();
+ } else {
+ rejectAdd(
+ new Error(`Key deployment failed with code ${code}`),
+ );
+ }
+ });
+ },
+ );
+ });
+
+ const verifySuccess = await new Promise<boolean>(
+ (resolveVerify, rejectVerify) => {
+ const verifyTimeout = setTimeout(() => {
+ rejectVerify(new Error("Key verification timeout"));
+ }, 5000);
+
+ let actualPublicKey = publicKey;
+ try {
+ const parsed = JSON.parse(publicKey);
+ if (parsed.data) {
+ actualPublicKey = parsed.data;
+ }
+ } catch {
+ // Ignore parse errors
+ }
+
+ const keyParts = actualPublicKey.trim().split(" ");
+ if (keyParts.length < 2) {
+ clearTimeout(verifyTimeout);
+ return rejectVerify(
+ new Error(
+ "Invalid public key format - must contain at least 2 parts",
+ ),
+ );
+ }
+
+ const keyPattern = keyParts[1];
+ conn.exec(
+ `grep -F "${keyPattern}" ~/.ssh/authorized_keys >/dev/null 2>&1; echo $?`,
+ (err, stream) => {
+ if (err) {
+ clearTimeout(verifyTimeout);
+ return rejectVerify(err);
+ }
+
+ let output = "";
+ stream.on("data", (data) => {
+ output += data.toString();
+ });
+
+ stream.on("close", () => {
+ clearTimeout(verifyTimeout);
+ const verified = output.trim() === "0";
+ resolveVerify(verified);
+ });
+ },
+ );
+ },
+ );
+
+ conn.end();
+
+ if (verifySuccess) {
+ resolve({ success: true, message: "SSH key deployed successfully" });
+ } else {
+ resolve({
+ success: false,
+ error: "Key deployment verification failed",
+ });
+ }
+ } catch (error) {
+ conn.end();
+ resolve({
+ success: false,
+ error: error instanceof Error ? error.message : "Deployment failed",
+ });
+ }
+ });
+
+ conn.on("error", (err) => {
+ clearTimeout(connectionTimeout);
+ let errorMessage = err.message;
+
+ if (
+ err.message.includes("All configured authentication methods failed")
+ ) {
+ errorMessage =
+ "Authentication failed. Please check your credentials and ensure the SSH service is running.";
+ } else if (
+ err.message.includes("ENOTFOUND") ||
+ err.message.includes("ENOENT")
+ ) {
+ errorMessage = "Could not resolve hostname or connect to server.";
+ } else if (err.message.includes("ECONNREFUSED")) {
+ errorMessage =
+ "Connection refused. The server may not be running or the port may be incorrect.";
+ } else if (err.message.includes("ETIMEDOUT")) {
+ errorMessage =
+ "Connection timed out. Check your network connection and server availability.";
+ } else if (
+ err.message.includes("authentication failed") ||
+ err.message.includes("Permission denied")
+ ) {
+ errorMessage =
+ "Authentication failed. Please check your username and password/key.";
+ }
+
+ resolve({ success: false, error: errorMessage });
+ });
+
+ try {
+ const connectionConfig: Record<string, unknown> = {
+ host: hostConfig.ip,
+ port: hostConfig.port || 22,
+ username: hostConfig.username,
+ readyTimeout: 60000,
+ keepaliveInterval: 30000,
+ keepaliveCountMax: 3,
+ tcpKeepAlive: true,
+ tcpKeepAliveInitialDelay: 30000,
+ algorithms: {
+ kex: [
+ "diffie-hellman-group14-sha256",
+ "diffie-hellman-group14-sha1",
+ "diffie-hellman-group1-sha1",
+ "diffie-hellman-group-exchange-sha256",
+ "diffie-hellman-group-exchange-sha1",
+ "ecdh-sha2-nistp256",
+ "ecdh-sha2-nistp384",
+ "ecdh-sha2-nistp521",
+ ],
+ cipher: [
+ "aes128-ctr",
+ "aes192-ctr",
+ "aes256-ctr",
+ "aes128-cbc",
+ "aes192-cbc",
+ "aes256-cbc",
+ "3des-cbc",
+ ],
+ hmac: [
+ "hmac-sha2-256",
+ "hmac-sha2-512",
+ "hmac-sha1",
+ "hmac-md5",
+ ],
+ compress: ["none", "[email protected]", "zlib"],
+ },
+ };
+
+ if (hostConfig.authType === "password" && hostConfig.password) {
+ connectionConfig.password = hostConfig.password;
+ } else if (hostConfig.authType === "key" && hostConfig.privateKey) {
+ try {
+ const privateKey = hostConfig.privateKey as string;
+ if (
+ !privateKey.includes("-----BEGIN") ||
+ !privateKey.includes("-----END")
+ ) {
+ throw new Error("Invalid private key format");
+ }
+
+ const cleanKey = privateKey
+ .trim()
+ .replace(/\r\n/g, "\n")
+ .replace(/\r/g, "\n");
+
+ connectionConfig.privateKey = Buffer.from(cleanKey, "utf8");
+
+ if (hostConfig.keyPassword) {
+ connectionConfig.passphrase = hostConfig.keyPassword;
+ }
+ } catch (keyError) {
+ clearTimeout(connectionTimeout);
+ resolve({
+ success: false,
+ error: `Invalid SSH key format: ${keyError instanceof Error ? keyError.message : "Unknown error"}`,
+ });
+ return;
+ }
+ } else {
+ clearTimeout(connectionTimeout);
+ resolve({
+ success: false,
+ error: `Invalid authentication configuration. Auth type: ${hostConfig.authType}, has password: ${!!hostConfig.password}, has key: ${!!hostConfig.privateKey}`,
+ });
+ return;
+ }
+
+ conn.connect(connectionConfig);
+ } catch (error) {
+ clearTimeout(connectionTimeout);
+ resolve({
+ success: false,
+ error: error instanceof Error ? error.message : "Connection failed",
+ });
+ }
+ });
+}
+
+export function registerCredentialDeployRoutes(
+ router: Router,
+ authenticateJWT: RequestHandler,
+): void {
+ /**
+ * @openapi
+ * /credentials/{id}/deploy-to-host:
+ * post:
+ * summary: Deploy SSH key to a host
+ * description: Deploys an SSH public key to a target host's authorized_keys file.
+ * tags:
+ * - Credentials
+ * parameters:
+ * - in: path
+ * name: id
+ * required: true
+ * schema:
+ * type: integer
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * targetHostId:
+ * type: integer
+ * responses:
+ * 200:
+ * description: SSH key deployed successfully.
+ * 400:
+ * description: Credential ID and target host ID are required.
+ * 401:
+ * description: Authentication required.
+ * 404:
+ * description: Credential or target host not found.
+ * 500:
+ * description: Failed to deploy SSH key.
+ */
+ router.post(
+ "/:id/deploy-to-host",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const id = Array.isArray(req.params.id)
+ ? req.params.id[0]
+ : req.params.id;
+ const credentialId = parseInt(id);
+ const { targetHostId } = req.body;
+
+ if (!credentialId || !targetHostId) {
+ return res.status(400).json({
+ success: false,
+ error: "Credential ID and target host ID are required",
+ });
+ }
+
+ try {
+ const userId = (req as AuthenticatedRequest).userId;
+ if (!userId) {
+ return res.status(401).json({
+ success: false,
+ error: "Authentication required",
+ });
+ }
+
+ const { SimpleDBOps } = await import("../../utils/simple-db-ops.js");
+ const credential = await SimpleDBOps.select(
+ db
+ .select()
+ .from(sshCredentials)
+ .where(eq(sshCredentials.id, credentialId))
+ .limit(1),
+ "ssh_credentials",
+ userId,
+ );
+
+ if (!credential || credential.length === 0) {
+ return res.status(404).json({
+ success: false,
+ error: "Credential not found",
+ });
+ }
+
+ const credData = credential[0] as unknown as CredentialBackend;
+
+ if (credData.authType !== "key") {
+ return res.status(400).json({
+ success: false,
+ error: "Only SSH key-based credentials can be deployed",
+ });
+ }
+
+ const publicKey = credData.publicKey;
+ if (!publicKey) {
+ return res.status(400).json({
+ success: false,
+ error: "Public key is required for deployment",
+ });
+ }
+ const targetHost = await SimpleDBOps.select(
+ db.select().from(hosts).where(eq(hosts.id, targetHostId)).limit(1),
+ "ssh_data",
+ userId,
+ );
+
+ if (!targetHost || targetHost.length === 0) {
+ return res.status(404).json({
+ success: false,
+ error: "Target host not found",
+ });
+ }
+
+ const hostData = targetHost[0];
+
+ const hostConfig = {
+ ip: hostData.ip,
+ port: hostData.port,
+ username: hostData.username,
+ authType: hostData.authType,
+ password: hostData.password,
+ privateKey: hostData.key,
+ keyPassword: hostData.keyPassword,
+ };
+
+ if (hostData.authType === "credential" && hostData.credentialId) {
+ const userId = (req as AuthenticatedRequest).userId;
+ if (!userId) {
+ return res.status(400).json({
+ success: false,
+ error: "Authentication required for credential resolution",
+ });
+ }
+
+ try {
+ const { SimpleDBOps } =
+ await import("../../utils/simple-db-ops.js");
+ const hostCredential = await SimpleDBOps.select(
+ db
+ .select()
+ .from(sshCredentials)
+ .where(eq(sshCredentials.id, hostData.credentialId as number))
+ .limit(1),
+ "ssh_credentials",
+ userId,
+ );
+
+ if (hostCredential && hostCredential.length > 0) {
+ const cred = hostCredential[0];
+
+ hostConfig.authType = cred.authType;
+ hostConfig.username = cred.username;
+
+ if (cred.authType === "password") {
+ hostConfig.password = cred.password;
+ } else if (cred.authType === "key") {
+ hostConfig.privateKey = cred.privateKey || cred.key;
+ hostConfig.keyPassword = cred.keyPassword;
+ }
+ } else {
+ return res.status(400).json({
+ success: false,
+ error: "Host credential not found",
+ });
+ }
+ } catch {
+ return res.status(500).json({
+ success: false,
+ error: "Failed to resolve host credentials",
+ });
+ }
+ }
+
+ const deployResult = await deploySSHKeyToHost(hostConfig, credData);
+
+ if (deployResult.success) {
+ res.json({
+ success: true,
+ message: deployResult.message || "SSH key deployed successfully",
+ });
+ } else {
+ res.status(500).json({
+ success: false,
+ error: deployResult.error || "Deployment failed",
+ });
+ }
+ } catch (error) {
+ res.status(500).json({
+ success: false,
+ error:
+ error instanceof Error ? error.message : "Failed to deploy SSH key",
+ });
+ }
+ },
+ );
+}
diff --git a/src/backend/database/routes/credential-key-routes.ts b/src/backend/database/routes/credential-key-routes.ts
new file mode 100644
index 000000000..3ff54967a
--- /dev/null
+++ b/src/backend/database/routes/credential-key-routes.ts
@@ -0,0 +1,512 @@
+import type { Request, RequestHandler, Response, Router } from "express";
+import crypto from "crypto";
+import ssh2Pkg from "ssh2";
+import { authLogger } from "../../utils/logger.js";
+import {
+ parsePublicKey,
+ parseSSHKey,
+ validateKeyPair,
+} from "../../utils/ssh-key-utils.js";
+
+const { utils: ssh2Utils } = ssh2Pkg;
+
+function generateSSHKeyPair(
+ keyType: string,
+ keySize?: number,
+ passphrase?: string,
+): {
+ success: boolean;
+ privateKey?: string;
+ publicKey?: string;
+ error?: string;
+} {
+ try {
+ let ssh2Type = keyType;
+ const options: {
+ bits?: number;
+ passphrase?: string;
+ cipher?: string;
+ } = {};
+
+ if (keyType === "ssh-rsa") {
+ ssh2Type = "rsa";
+ options.bits = keySize || 2048;
+ } else if (keyType === "ssh-ed25519") {
+ ssh2Type = "ed25519";
+ } else if (keyType === "ecdsa-sha2-nistp256") {
+ ssh2Type = "ecdsa";
+ options.bits = 256;
+ }
+
+ if (passphrase && passphrase.trim()) {
+ options.passphrase = passphrase;
+ options.cipher = "aes128-cbc";
+ }
+
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const keyPair = ssh2Utils.generateKeyPairSync(ssh2Type as any, options);
+
+ return {
+ success: true,
+ privateKey: keyPair.private,
+ publicKey: keyPair.public,
+ };
+ } catch (error) {
+ return {
+ success: false,
+ error:
+ error instanceof Error ? error.message : "SSH key generation failed",
+ };
+ }
+}
+
+export function registerCredentialKeyRoutes(
+ router: Router,
+ authenticateJWT: RequestHandler,
+): void {
+ /**
+ * @openapi
+ * /credentials/detect-key-type:
+ * post:
+ * summary: Detect SSH key type
+ * description: Detects the type of an SSH private key.
+ * tags:
+ * - Credentials
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * privateKey:
+ * type: string
+ * keyPassword:
+ * type: string
+ * responses:
+ * 200:
+ * description: Key type detection result.
+ * 400:
+ * description: Private key is required.
+ * 500:
+ * description: Failed to detect key type.
+ */
+ router.post(
+ "/detect-key-type",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const { privateKey, keyPassword } = req.body;
+
+ if (!privateKey || typeof privateKey !== "string") {
+ return res.status(400).json({ error: "Private key is required" });
+ }
+
+ try {
+ const keyInfo = parseSSHKey(privateKey, keyPassword);
+
+ const response = {
+ success: keyInfo.success,
+ keyType: keyInfo.keyType,
+ detectedKeyType: keyInfo.keyType,
+ hasPublicKey: !!keyInfo.publicKey,
+ error: keyInfo.error || null,
+ };
+
+ res.json(response);
+ } catch (error) {
+ authLogger.error("Failed to detect key type", error);
+ res.status(500).json({
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to detect key type",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /credentials/detect-public-key-type:
+ * post:
+ * summary: Detect SSH public key type
+ * description: Detects the type of an SSH public key.
+ * tags:
+ * - Credentials
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * publicKey:
+ * type: string
+ * responses:
+ * 200:
+ * description: Key type detection result.
+ * 400:
+ * description: Public key is required.
+ * 500:
+ * description: Failed to detect public key type.
+ */
+ router.post(
+ "/detect-public-key-type",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const { publicKey } = req.body;
+
+ if (!publicKey || typeof publicKey !== "string") {
+ return res.status(400).json({ error: "Public key is required" });
+ }
+
+ try {
+ const keyInfo = parsePublicKey(publicKey);
+
+ const response = {
+ success: keyInfo.success,
+ keyType: keyInfo.keyType,
+ detectedKeyType: keyInfo.keyType,
+ error: keyInfo.error || null,
+ };
+
+ res.json(response);
+ } catch (error) {
+ authLogger.error("Failed to detect public key type", error);
+ res.status(500).json({
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to detect public key type",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /credentials/validate-key-pair:
+ * post:
+ * summary: Validate SSH key pair
+ * description: Validates if a given SSH private key and public key match.
+ * tags:
+ * - Credentials
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * privateKey:
+ * type: string
+ * publicKey:
+ * type: string
+ * keyPassword:
+ * type: string
+ * responses:
+ * 200:
+ * description: Key pair validation result.
+ * 400:
+ * description: Private key and public key are required.
+ * 500:
+ * description: Failed to validate key pair.
+ */
+ router.post(
+ "/validate-key-pair",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const { privateKey, publicKey, keyPassword } = req.body;
+
+ if (!privateKey || typeof privateKey !== "string") {
+ return res.status(400).json({ error: "Private key is required" });
+ }
+
+ if (!publicKey || typeof publicKey !== "string") {
+ return res.status(400).json({ error: "Public key is required" });
+ }
+
+ try {
+ const validationResult = validateKeyPair(
+ privateKey,
+ publicKey,
+ keyPassword,
+ );
+
+ const response = {
+ isValid: validationResult.isValid,
+ privateKeyType: validationResult.privateKeyType,
+ publicKeyType: validationResult.publicKeyType,
+ generatedPublicKey: validationResult.generatedPublicKey,
+ error: validationResult.error || null,
+ };
+
+ res.json(response);
+ } catch (error) {
+ authLogger.error("Failed to validate key pair", error);
+ res.status(500).json({
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to validate key pair",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /credentials/generate-key-pair:
+ * post:
+ * summary: Generate new SSH key pair
+ * description: Generates a new SSH key pair.
+ * tags:
+ * - Credentials
+ * requestBody:
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * keyType:
+ * type: string
+ * keySize:
+ * type: integer
+ * passphrase:
+ * type: string
+ * responses:
+ * 200:
+ * description: The new key pair.
+ * 500:
+ * description: Failed to generate SSH key pair.
+ */
+ router.post(
+ "/generate-key-pair",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const { keyType = "ssh-ed25519", keySize = 2048, passphrase } = req.body;
+
+ try {
+ const result = generateSSHKeyPair(keyType, keySize, passphrase);
+
+ if (result.success && result.privateKey && result.publicKey) {
+ const response = {
+ success: true,
+ privateKey: result.privateKey,
+ publicKey: result.publicKey,
+ keyType: keyType,
+ format: "ssh",
+ algorithm: keyType,
+ keySize: keyType === "ssh-rsa" ? keySize : undefined,
+ curve: keyType === "ecdsa-sha2-nistp256" ? "nistp256" : undefined,
+ };
+
+ res.json(response);
+ } else {
+ res.status(500).json({
+ success: false,
+ error: result.error || "Failed to generate SSH key pair",
+ });
+ }
+ } catch (error) {
+ authLogger.error("Failed to generate key pair", error);
+ res.status(500).json({
+ success: false,
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to generate key pair",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /credentials/generate-public-key:
+ * post:
+ * summary: Generate public key from private key
+ * description: Generates a public key from a given private key.
+ * tags:
+ * - Credentials
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * privateKey:
+ * type: string
+ * keyPassword:
+ * type: string
+ * responses:
+ * 200:
+ * description: The generated public key.
+ * 400:
+ * description: Private key is required.
+ * 500:
+ * description: Failed to generate public key.
+ */
+ router.post(
+ "/generate-public-key",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const { privateKey, keyPassword } = req.body;
+
+ if (!privateKey || typeof privateKey !== "string") {
+ return res.status(400).json({ error: "Private key is required" });
+ }
+
+ try {
+ let privateKeyObj;
+ const parseAttempts = [];
+
+ try {
+ privateKeyObj = crypto.createPrivateKey({
+ key: privateKey,
+ passphrase: keyPassword,
+ });
+ } catch (error) {
+ parseAttempts.push(`Method 1 (with passphrase): ${error.message}`);
+ }
+
+ if (!privateKeyObj) {
+ try {
+ privateKeyObj = crypto.createPrivateKey(privateKey);
+ } catch (error) {
+ parseAttempts.push(
+ `Method 2 (without passphrase): ${error.message}`,
+ );
+ }
+ }
+
+ if (!privateKeyObj) {
+ try {
+ privateKeyObj = crypto.createPrivateKey({
+ key: privateKey,
+ format: "pem",
+ type: "pkcs8",
+ });
+ } catch (error) {
+ parseAttempts.push(`Method 3 (PKCS#8): ${error.message}`);
+ }
+ }
+
+ if (
+ !privateKeyObj &&
+ privateKey.includes("-----BEGIN RSA PRIVATE KEY-----")
+ ) {
+ try {
+ privateKeyObj = crypto.createPrivateKey({
+ key: privateKey,
+ format: "pem",
+ type: "pkcs1",
+ });
+ } catch (error) {
+ parseAttempts.push(`Method 4 (PKCS#1): ${error.message}`);
+ }
+ }
+
+ if (
+ !privateKeyObj &&
+ privateKey.includes("-----BEGIN EC PRIVATE KEY-----")
+ ) {
+ try {
+ privateKeyObj = crypto.createPrivateKey({
+ key: privateKey,
+ format: "pem",
+ type: "sec1",
+ });
+ } catch (error) {
+ parseAttempts.push(`Method 5 (SEC1): ${error.message}`);
+ }
+ }
+
+ if (!privateKeyObj) {
+ try {
+ const keyInfo = parseSSHKey(privateKey, keyPassword);
+
+ if (keyInfo.success && keyInfo.publicKey) {
+ const publicKeyString = String(keyInfo.publicKey);
+ return res.json({
+ success: true,
+ publicKey: publicKeyString,
+ keyType: keyInfo.keyType,
+ });
+ } else {
+ parseAttempts.push(
+ `SSH2 fallback: ${keyInfo.error || "No public key generated"}`,
+ );
+ }
+ } catch (error) {
+ parseAttempts.push(`SSH2 fallback exception: ${error.message}`);
+ }
+ }
+
+ if (!privateKeyObj) {
+ return res.status(400).json({
+ success: false,
+ error: "Unable to parse private key. Tried multiple formats.",
+ details: parseAttempts,
+ });
+ }
+
+ const publicKeyObj = crypto.createPublicKey(privateKeyObj);
+ const publicKeyPem = publicKeyObj.export({
+ type: "spki",
+ format: "pem",
+ });
+
+ const publicKeyString =
+ typeof publicKeyPem === "string"
+ ? publicKeyPem
+ : (publicKeyPem as Buffer).toString("utf8");
+
+ let keyType = "unknown";
+ const asymmetricKeyType = privateKeyObj.asymmetricKeyType;
+
+ if (asymmetricKeyType === "rsa") {
+ keyType = "ssh-rsa";
+ } else if (asymmetricKeyType === "ed25519") {
+ keyType = "ssh-ed25519";
+ } else if (asymmetricKeyType === "ec") {
+ keyType = "ecdsa-sha2-nistp256";
+ }
+
+ let finalPublicKey = publicKeyString;
+ let formatType = "pem";
+
+ try {
+ const ssh2PrivateKey = ssh2Utils.parseKey(privateKey, keyPassword);
+ if (!(ssh2PrivateKey instanceof Error)) {
+ const publicKeyBuffer = ssh2PrivateKey.getPublicSSH();
+ const base64Data = publicKeyBuffer.toString("base64");
+ finalPublicKey = `${keyType} ${base64Data}`;
+ formatType = "ssh";
+ }
+ } catch {
+ // Ignore validation errors
+ }
+
+ const response = {
+ success: true,
+ publicKey: finalPublicKey,
+ keyType: keyType,
+ format: formatType,
+ };
+
+ res.json(response);
+ } catch (error) {
+ authLogger.error("Failed to generate public key", error);
+ res.status(500).json({
+ success: false,
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to generate public key",
+ });
+ }
+ },
+ );
+}
diff --git a/src/backend/database/routes/credentials.ts b/src/backend/database/routes/credentials.ts
index a04fbdc7e..c81109b25 100644
--- a/src/backend/database/routes/credentials.ts
+++ b/src/backend/database/routes/credentials.ts
@@ -1,7 +1,4 @@
-import type {
- AuthenticatedRequest,
- CredentialBackend,
-} from "../../../types/index.js";
+import type { AuthenticatedRequest } from "../../../types/index.js";
import express from "express";
import { db } from "../db/index.js";
import {
@@ -15,64 +12,9 @@ import type { Request, Response } from "express";
import { authLogger } from "../../utils/logger.js";
import { SimpleDBOps } from "../../utils/simple-db-ops.js";
import { AuthManager } from "../../utils/auth-manager.js";
-import {
- parseSSHKey,
- parsePublicKey,
- validateKeyPair,
-} from "../../utils/ssh-key-utils.js";
-import crypto from "crypto";
-import ssh2Pkg from "ssh2";
-const { utils: ssh2Utils, Client } = ssh2Pkg;
-
-function generateSSHKeyPair(
- keyType: string,
- keySize?: number,
- passphrase?: string,
-): {
- success: boolean;
- privateKey?: string;
- publicKey?: string;
- error?: string;
-} {
- try {
- let ssh2Type = keyType;
- const options: {
- bits?: number;
- passphrase?: string;
- cipher?: string;
- } = {};
-
- if (keyType === "ssh-rsa") {
- ssh2Type = "rsa";
- options.bits = keySize || 2048;
- } else if (keyType === "ssh-ed25519") {
- ssh2Type = "ed25519";
- } else if (keyType === "ecdsa-sha2-nistp256") {
- ssh2Type = "ecdsa";
- options.bits = 256;
- }
-
- if (passphrase && passphrase.trim()) {
- options.passphrase = passphrase;
- options.cipher = "aes128-cbc";
- }
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const keyPair = ssh2Utils.generateKeyPairSync(ssh2Type as any, options);
-
- return {
- success: true,
- privateKey: keyPair.private,
- publicKey: keyPair.public,
- };
- } catch (error) {
- return {
- success: false,
- error:
- error instanceof Error ? error.message : "SSH key generation failed",
- };
- }
-}
+import { parseSSHKey } from "../../utils/ssh-key-utils.js";
+import { registerCredentialKeyRoutes } from "./credential-key-routes.js";
+import { registerCredentialDeployRoutes } from "./credential-deploy-routes.js";
const router = express.Router();
@@ -1058,981 +1000,8 @@ router.put(
},
);
-/**
- * @openapi
- * /credentials/detect-key-type:
- * post:
- * summary: Detect SSH key type
- * description: Detects the type of an SSH private key.
- * tags:
- * - Credentials
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * privateKey:
- * type: string
- * keyPassword:
- * type: string
- * responses:
- * 200:
- * description: Key type detection result.
- * 400:
- * description: Private key is required.
- * 500:
- * description: Failed to detect key type.
- */
-router.post(
- "/detect-key-type",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const { privateKey, keyPassword } = req.body;
-
- if (!privateKey || typeof privateKey !== "string") {
- return res.status(400).json({ error: "Private key is required" });
- }
-
- try {
- const keyInfo = parseSSHKey(privateKey, keyPassword);
-
- const response = {
- success: keyInfo.success,
- keyType: keyInfo.keyType,
- detectedKeyType: keyInfo.keyType,
- hasPublicKey: !!keyInfo.publicKey,
- error: keyInfo.error || null,
- };
-
- res.json(response);
- } catch (error) {
- authLogger.error("Failed to detect key type", error);
- res.status(500).json({
- error:
- error instanceof Error ? error.message : "Failed to detect key type",
- });
- }
- },
-);
-
-/**
- * @openapi
- * /credentials/detect-public-key-type:
- * post:
- * summary: Detect SSH public key type
- * description: Detects the type of an SSH public key.
- * tags:
- * - Credentials
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * publicKey:
- * type: string
- * responses:
- * 200:
- * description: Key type detection result.
- * 400:
- * description: Public key is required.
- * 500:
- * description: Failed to detect public key type.
- */
-router.post(
- "/detect-public-key-type",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const { publicKey } = req.body;
-
- if (!publicKey || typeof publicKey !== "string") {
- return res.status(400).json({ error: "Public key is required" });
- }
-
- try {
- const keyInfo = parsePublicKey(publicKey);
-
- const response = {
- success: keyInfo.success,
- keyType: keyInfo.keyType,
- detectedKeyType: keyInfo.keyType,
- error: keyInfo.error || null,
- };
-
- res.json(response);
- } catch (error) {
- authLogger.error("Failed to detect public key type", error);
- res.status(500).json({
- error:
- error instanceof Error
- ? error.message
- : "Failed to detect public key type",
- });
- }
- },
-);
+registerCredentialKeyRoutes(router, authenticateJWT);
-/**
- * @openapi
- * /credentials/validate-key-pair:
- * post:
- * summary: Validate SSH key pair
- * description: Validates if a given SSH private key and public key match.
- * tags:
- * - Credentials
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * privateKey:
- * type: string
- * publicKey:
- * type: string
- * keyPassword:
- * type: string
- * responses:
- * 200:
- * description: Key pair validation result.
- * 400:
- * description: Private key and public key are required.
- * 500:
- * description: Failed to validate key pair.
- */
-router.post(
- "/validate-key-pair",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const { privateKey, publicKey, keyPassword } = req.body;
-
- if (!privateKey || typeof privateKey !== "string") {
- return res.status(400).json({ error: "Private key is required" });
- }
-
- if (!publicKey || typeof publicKey !== "string") {
- return res.status(400).json({ error: "Public key is required" });
- }
-
- try {
- const validationResult = validateKeyPair(
- privateKey,
- publicKey,
- keyPassword,
- );
-
- const response = {
- isValid: validationResult.isValid,
- privateKeyType: validationResult.privateKeyType,
- publicKeyType: validationResult.publicKeyType,
- generatedPublicKey: validationResult.generatedPublicKey,
- error: validationResult.error || null,
- };
-
- res.json(response);
- } catch (error) {
- authLogger.error("Failed to validate key pair", error);
- res.status(500).json({
- error:
- error instanceof Error
- ? error.message
- : "Failed to validate key pair",
- });
- }
- },
-);
-
-/**
- * @openapi
- * /credentials/generate-key-pair:
- * post:
- * summary: Generate new SSH key pair
- * description: Generates a new SSH key pair.
- * tags:
- * - Credentials
- * requestBody:
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * keyType:
- * type: string
- * keySize:
- * type: integer
- * passphrase:
- * type: string
- * responses:
- * 200:
- * description: The new key pair.
- * 500:
- * description: Failed to generate SSH key pair.
- */
-router.post(
- "/generate-key-pair",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const { keyType = "ssh-ed25519", keySize = 2048, passphrase } = req.body;
-
- try {
- const result = generateSSHKeyPair(keyType, keySize, passphrase);
-
- if (result.success && result.privateKey && result.publicKey) {
- const response = {
- success: true,
- privateKey: result.privateKey,
- publicKey: result.publicKey,
- keyType: keyType,
- format: "ssh",
- algorithm: keyType,
- keySize: keyType === "ssh-rsa" ? keySize : undefined,
- curve: keyType === "ecdsa-sha2-nistp256" ? "nistp256" : undefined,
- };
-
- res.json(response);
- } else {
- res.status(500).json({
- success: false,
- error: result.error || "Failed to generate SSH key pair",
- });
- }
- } catch (error) {
- authLogger.error("Failed to generate key pair", error);
- res.status(500).json({
- success: false,
- error:
- error instanceof Error
- ? error.message
- : "Failed to generate key pair",
- });
- }
- },
-);
-
-/**
- * @openapi
- * /credentials/generate-public-key:
- * post:
- * summary: Generate public key from private key
- * description: Generates a public key from a given private key.
- * tags:
- * - Credentials
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * privateKey:
- * type: string
- * keyPassword:
- * type: string
- * responses:
- * 200:
- * description: The generated public key.
- * 400:
- * description: Private key is required.
- * 500:
- * description: Failed to generate public key.
- */
-router.post(
- "/generate-public-key",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const { privateKey, keyPassword } = req.body;
-
- if (!privateKey || typeof privateKey !== "string") {
- return res.status(400).json({ error: "Private key is required" });
- }
-
- try {
- let privateKeyObj;
- const parseAttempts = [];
-
- try {
- privateKeyObj = crypto.createPrivateKey({
- key: privateKey,
- passphrase: keyPassword,
- });
- } catch (error) {
- parseAttempts.push(`Method 1 (with passphrase): ${error.message}`);
- }
-
- if (!privateKeyObj) {
- try {
- privateKeyObj = crypto.createPrivateKey(privateKey);
- } catch (error) {
- parseAttempts.push(`Method 2 (without passphrase): ${error.message}`);
- }
- }
-
- if (!privateKeyObj) {
- try {
- privateKeyObj = crypto.createPrivateKey({
- key: privateKey,
- format: "pem",
- type: "pkcs8",
- });
- } catch (error) {
- parseAttempts.push(`Method 3 (PKCS#8): ${error.message}`);
- }
- }
-
- if (
- !privateKeyObj &&
- privateKey.includes("-----BEGIN RSA PRIVATE KEY-----")
- ) {
- try {
- privateKeyObj = crypto.createPrivateKey({
- key: privateKey,
- format: "pem",
- type: "pkcs1",
- });
- } catch (error) {
- parseAttempts.push(`Method 4 (PKCS#1): ${error.message}`);
- }
- }
-
- if (
- !privateKeyObj &&
- privateKey.includes("-----BEGIN EC PRIVATE KEY-----")
- ) {
- try {
- privateKeyObj = crypto.createPrivateKey({
- key: privateKey,
- format: "pem",
- type: "sec1",
- });
- } catch (error) {
- parseAttempts.push(`Method 5 (SEC1): ${error.message}`);
- }
- }
-
- if (!privateKeyObj) {
- try {
- const keyInfo = parseSSHKey(privateKey, keyPassword);
-
- if (keyInfo.success && keyInfo.publicKey) {
- const publicKeyString = String(keyInfo.publicKey);
- return res.json({
- success: true,
- publicKey: publicKeyString,
- keyType: keyInfo.keyType,
- });
- } else {
- parseAttempts.push(
- `SSH2 fallback: ${keyInfo.error || "No public key generated"}`,
- );
- }
- } catch (error) {
- parseAttempts.push(`SSH2 fallback exception: ${error.message}`);
- }
- }
-
- if (!privateKeyObj) {
- return res.status(400).json({
- success: false,
- error: "Unable to parse private key. Tried multiple formats.",
- details: parseAttempts,
- });
- }
-
- const publicKeyObj = crypto.createPublicKey(privateKeyObj);
- const publicKeyPem = publicKeyObj.export({
- type: "spki",
- format: "pem",
- });
-
- const publicKeyString =
- typeof publicKeyPem === "string"
- ? publicKeyPem
- : (publicKeyPem as Buffer).toString("utf8");
-
- let keyType = "unknown";
- const asymmetricKeyType = privateKeyObj.asymmetricKeyType;
-
- if (asymmetricKeyType === "rsa") {
- keyType = "ssh-rsa";
- } else if (asymmetricKeyType === "ed25519") {
- keyType = "ssh-ed25519";
- } else if (asymmetricKeyType === "ec") {
- keyType = "ecdsa-sha2-nistp256";
- }
-
- let finalPublicKey = publicKeyString;
- let formatType = "pem";
-
- try {
- const ssh2PrivateKey = ssh2Utils.parseKey(privateKey, keyPassword);
- if (!(ssh2PrivateKey instanceof Error)) {
- const publicKeyBuffer = ssh2PrivateKey.getPublicSSH();
- const base64Data = publicKeyBuffer.toString("base64");
- finalPublicKey = `${keyType} ${base64Data}`;
- formatType = "ssh";
- }
- } catch {
- // Ignore validation errors
- }
-
- const response = {
- success: true,
- publicKey: finalPublicKey,
- keyType: keyType,
- format: formatType,
- };
-
- res.json(response);
- } catch (error) {
- authLogger.error("Failed to generate public key", error);
- res.status(500).json({
- success: false,
- error:
- error instanceof Error
- ? error.message
- : "Failed to generate public key",
- });
- }
- },
-);
-
-async function deploySSHKeyToHost(
- hostConfig: Record<string, unknown>,
- credData: CredentialBackend,
-): Promise<{ success: boolean; message?: string; error?: string }> {
- const publicKey = credData.publicKey as string;
- return new Promise((resolve) => {
- const conn = new Client();
-
- const connectionTimeout = setTimeout(() => {
- conn.destroy();
- resolve({ success: false, error: "Connection timeout" });
- }, 120000);
-
- conn.on("ready", async () => {
- clearTimeout(connectionTimeout);
-
- try {
- await new Promise<void>((resolveCmd, rejectCmd) => {
- const cmdTimeout = setTimeout(() => {
- rejectCmd(new Error("mkdir command timeout"));
- }, 10000);
-
- conn.exec(
- "test -d ~/.ssh || mkdir -p ~/.ssh; chmod 700 ~/.ssh",
- (err, stream) => {
- if (err) {
- clearTimeout(cmdTimeout);
- return rejectCmd(err);
- }
-
- stream.on("close", (code) => {
- clearTimeout(cmdTimeout);
- if (code === 0) {
- resolveCmd();
- } else {
- rejectCmd(
- new Error(`mkdir command failed with code ${code}`),
- );
- }
- });
-
- stream.on("data", () => {
- // Ignore output
- });
- },
- );
- });
-
- const keyExists = await new Promise<boolean>(
- (resolveCheck, rejectCheck) => {
- const checkTimeout = setTimeout(() => {
- rejectCheck(new Error("Key check timeout"));
- }, 5000);
-
- let actualPublicKey = publicKey;
- try {
- const parsed = JSON.parse(publicKey);
- if (parsed.data) {
- actualPublicKey = parsed.data;
- }
- } catch {
- // Ignore parse errors
- }
-
- const keyParts = actualPublicKey.trim().split(" ");
- if (keyParts.length < 2) {
- clearTimeout(checkTimeout);
- return rejectCheck(
- new Error(
- "Invalid public key format - must contain at least 2 parts",
- ),
- );
- }
-
- const keyPattern = keyParts[1];
-
- conn.exec(
- `if [ -f ~/.ssh/authorized_keys ]; then grep -F "${keyPattern}" ~/.ssh/authorized_keys >/dev/null 2>&1; echo $?; else echo 1; fi`,
- (err, stream) => {
- if (err) {
- clearTimeout(checkTimeout);
- return rejectCheck(err);
- }
-
- let output = "";
- stream.on("data", (data) => {
- output += data.toString();
- });
-
- stream.on("close", () => {
- clearTimeout(checkTimeout);
- const exists = output.trim() === "0";
- resolveCheck(exists);
- });
- },
- );
- },
- );
-
- if (keyExists) {
- conn.end();
- resolve({ success: true, message: "SSH key already deployed" });
- return;
- }
-
- await new Promise<void>((resolveAdd, rejectAdd) => {
- const addTimeout = setTimeout(() => {
- rejectAdd(new Error("Key add timeout"));
- }, 30000);
-
- let actualPublicKey = publicKey;
- try {
- const parsed = JSON.parse(publicKey);
- if (parsed.data) {
- actualPublicKey = parsed.data;
- }
- } catch {
- // Ignore parse errors
- }
-
- const escapedKey = actualPublicKey
- .replace(/\\/g, "\\\\")
- .replace(/'/g, "'\\''");
- const escapedName = credData.name
- .replace(/\\/g, "\\\\")
- .replace(/'/g, "'\\''");
-
- conn.exec(
- `printf '%s\n' '${escapedKey} ${escapedName}@Termix' >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`,
- (err, stream) => {
- if (err) {
- clearTimeout(addTimeout);
- return rejectAdd(err);
- }
-
- stream.on("data", () => {
- // Consume output
- });
-
- stream.on("close", (code) => {
- clearTimeout(addTimeout);
- if (code === 0) {
- resolveAdd();
- } else {
- rejectAdd(
- new Error(`Key deployment failed with code ${code}`),
- );
- }
- });
- },
- );
- });
-
- const verifySuccess = await new Promise<boolean>(
- (resolveVerify, rejectVerify) => {
- const verifyTimeout = setTimeout(() => {
- rejectVerify(new Error("Key verification timeout"));
- }, 5000);
-
- let actualPublicKey = publicKey;
- try {
- const parsed = JSON.parse(publicKey);
- if (parsed.data) {
- actualPublicKey = parsed.data;
- }
- } catch {
- // Ignore parse errors
- }
-
- const keyParts = actualPublicKey.trim().split(" ");
- if (keyParts.length < 2) {
- clearTimeout(verifyTimeout);
- return rejectVerify(
- new Error(
- "Invalid public key format - must contain at least 2 parts",
- ),
- );
- }
-
- const keyPattern = keyParts[1];
- conn.exec(
- `grep -F "${keyPattern}" ~/.ssh/authorized_keys >/dev/null 2>&1; echo $?`,
- (err, stream) => {
- if (err) {
- clearTimeout(verifyTimeout);
- return rejectVerify(err);
- }
-
- let output = "";
- stream.on("data", (data) => {
- output += data.toString();
- });
-
- stream.on("close", () => {
- clearTimeout(verifyTimeout);
- const verified = output.trim() === "0";
- resolveVerify(verified);
- });
- },
- );
- },
- );
-
- conn.end();
-
- if (verifySuccess) {
- resolve({ success: true, message: "SSH key deployed successfully" });
- } else {
- resolve({
- success: false,
- error: "Key deployment verification failed",
- });
- }
- } catch (error) {
- conn.end();
- resolve({
- success: false,
- error: error instanceof Error ? error.message : "Deployment failed",
- });
- }
- });
-
- conn.on("error", (err) => {
- clearTimeout(connectionTimeout);
- let errorMessage = err.message;
-
- if (
- err.message.includes("All configured authentication methods failed")
- ) {
- errorMessage =
- "Authentication failed. Please check your credentials and ensure the SSH service is running.";
- } else if (
- err.message.includes("ENOTFOUND") ||
- err.message.includes("ENOENT")
- ) {
- errorMessage = "Could not resolve hostname or connect to server.";
- } else if (err.message.includes("ECONNREFUSED")) {
- errorMessage =
- "Connection refused. The server may not be running or the port may be incorrect.";
- } else if (err.message.includes("ETIMEDOUT")) {
- errorMessage =
- "Connection timed out. Check your network connection and server availability.";
- } else if (
- err.message.includes("authentication failed") ||
- err.message.includes("Permission denied")
- ) {
- errorMessage =
- "Authentication failed. Please check your username and password/key.";
- }
-
- resolve({ success: false, error: errorMessage });
- });
-
- try {
- const connectionConfig: Record<string, unknown> = {
- host: hostConfig.ip,
- port: hostConfig.port || 22,
- username: hostConfig.username,
- readyTimeout: 60000,
- keepaliveInterval: 30000,
- keepaliveCountMax: 3,
- tcpKeepAlive: true,
- tcpKeepAliveInitialDelay: 30000,
- algorithms: {
- kex: [
- "diffie-hellman-group14-sha256",
- "diffie-hellman-group14-sha1",
- "diffie-hellman-group1-sha1",
- "diffie-hellman-group-exchange-sha256",
- "diffie-hellman-group-exchange-sha1",
- "ecdh-sha2-nistp256",
- "ecdh-sha2-nistp384",
- "ecdh-sha2-nistp521",
- ],
- cipher: [
- "aes128-ctr",
- "aes192-ctr",
- "aes256-ctr",
- "aes128-cbc",
- "aes192-cbc",
- "aes256-cbc",
- "3des-cbc",
- ],
- hmac: [
- "hmac-sha2-256",
- "hmac-sha2-512",
- "hmac-sha1",
- "hmac-md5",
- ],
- compress: ["none", "[email protected]", "zlib"],
- },
- };
-
- if (hostConfig.authType === "password" && hostConfig.password) {
- connectionConfig.password = hostConfig.password;
- } else if (hostConfig.authType === "key" && hostConfig.privateKey) {
- try {
- const privateKey = hostConfig.privateKey as string;
- if (
- !privateKey.includes("-----BEGIN") ||
- !privateKey.includes("-----END")
- ) {
- throw new Error("Invalid private key format");
- }
-
- const cleanKey = privateKey
- .trim()
- .replace(/\r\n/g, "\n")
- .replace(/\r/g, "\n");
-
- connectionConfig.privateKey = Buffer.from(cleanKey, "utf8");
-
- if (hostConfig.keyPassword) {
- connectionConfig.passphrase = hostConfig.keyPassword;
- }
- } catch (keyError) {
- clearTimeout(connectionTimeout);
- resolve({
- success: false,
- error: `Invalid SSH key format: ${keyError instanceof Error ? keyError.message : "Unknown error"}`,
- });
- return;
- }
- } else {
- clearTimeout(connectionTimeout);
- resolve({
- success: false,
- error: `Invalid authentication configuration. Auth type: ${hostConfig.authType}, has password: ${!!hostConfig.password}, has key: ${!!hostConfig.privateKey}`,
- });
- return;
- }
-
- conn.connect(connectionConfig);
- } catch (error) {
- clearTimeout(connectionTimeout);
- resolve({
- success: false,
- error: error instanceof Error ? error.message : "Connection failed",
- });
- }
- });
-}
-
-/**
- * @openapi
- * /credentials/{id}/deploy-to-host:
- * post:
- * summary: Deploy SSH key to a host
- * description: Deploys an SSH public key to a target host's authorized_keys file.
- * tags:
- * - Credentials
- * parameters:
- * - in: path
- * name: id
- * required: true
- * schema:
- * type: integer
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * targetHostId:
- * type: integer
- * responses:
- * 200:
- * description: SSH key deployed successfully.
- * 400:
- * description: Credential ID and target host ID are required.
- * 401:
- * description: Authentication required.
- * 404:
- * description: Credential or target host not found.
- * 500:
- * description: Failed to deploy SSH key.
- */
-router.post(
- "/:id/deploy-to-host",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
- const credentialId = parseInt(id);
- const { targetHostId } = req.body;
-
- if (!credentialId || !targetHostId) {
- return res.status(400).json({
- success: false,
- error: "Credential ID and target host ID are required",
- });
- }
-
- try {
- const userId = (req as AuthenticatedRequest).userId;
- if (!userId) {
- return res.status(401).json({
- success: false,
- error: "Authentication required",
- });
- }
-
- const { SimpleDBOps } = await import("../../utils/simple-db-ops.js");
- const credential = await SimpleDBOps.select(
- db
- .select()
- .from(sshCredentials)
- .where(eq(sshCredentials.id, credentialId))
- .limit(1),
- "ssh_credentials",
- userId,
- );
-
- if (!credential || credential.length === 0) {
- return res.status(404).json({
- success: false,
- error: "Credential not found",
- });
- }
-
- const credData = credential[0] as unknown as CredentialBackend;
-
- if (credData.authType !== "key") {
- return res.status(400).json({
- success: false,
- error: "Only SSH key-based credentials can be deployed",
- });
- }
-
- const publicKey = credData.publicKey;
- if (!publicKey) {
- return res.status(400).json({
- success: false,
- error: "Public key is required for deployment",
- });
- }
- const targetHost = await SimpleDBOps.select(
- db.select().from(hosts).where(eq(hosts.id, targetHostId)).limit(1),
- "ssh_data",
- userId,
- );
-
- if (!targetHost || targetHost.length === 0) {
- return res.status(404).json({
- success: false,
- error: "Target host not found",
- });
- }
-
- const hostData = targetHost[0];
-
- const hostConfig = {
- ip: hostData.ip,
- port: hostData.port,
- username: hostData.username,
- authType: hostData.authType,
- password: hostData.password,
- privateKey: hostData.key,
- keyPassword: hostData.keyPassword,
- };
-
- if (hostData.authType === "credential" && hostData.credentialId) {
- const userId = (req as AuthenticatedRequest).userId;
- if (!userId) {
- return res.status(400).json({
- success: false,
- error: "Authentication required for credential resolution",
- });
- }
-
- try {
- const { SimpleDBOps } = await import("../../utils/simple-db-ops.js");
- const hostCredential = await SimpleDBOps.select(
- db
- .select()
- .from(sshCredentials)
- .where(eq(sshCredentials.id, hostData.credentialId as number))
- .limit(1),
- "ssh_credentials",
- userId,
- );
-
- if (hostCredential && hostCredential.length > 0) {
- const cred = hostCredential[0];
-
- hostConfig.authType = cred.authType;
- hostConfig.username = cred.username;
-
- if (cred.authType === "password") {
- hostConfig.password = cred.password;
- } else if (cred.authType === "key") {
- hostConfig.privateKey = cred.privateKey || cred.key;
- hostConfig.keyPassword = cred.keyPassword;
- }
- } else {
- return res.status(400).json({
- success: false,
- error: "Host credential not found",
- });
- }
- } catch {
- return res.status(500).json({
- success: false,
- error: "Failed to resolve host credentials",
- });
- }
- }
-
- const deployResult = await deploySSHKeyToHost(hostConfig, credData);
-
- if (deployResult.success) {
- res.json({
- success: true,
- message: deployResult.message || "SSH key deployed successfully",
- });
- } else {
- res.status(500).json({
- success: false,
- error: deployResult.error || "Deployment failed",
- });
- }
- } catch (error) {
- res.status(500).json({
- success: false,
- error:
- error instanceof Error ? error.message : "Failed to deploy SSH key",
- });
- }
- },
-);
+registerCredentialDeployRoutes(router, authenticateJWT);
export default router;
diff --git a/src/backend/database/routes/delete-user-data.ts b/src/backend/database/routes/delete-user-data.ts
new file mode 100644
index 000000000..8e99ef38f
--- /dev/null
+++ b/src/backend/database/routes/delete-user-data.ts
@@ -0,0 +1,104 @@
+import { eq } from "drizzle-orm";
+import { authLogger } from "../../utils/logger.js";
+import { db } from "../db/index.js";
+import {
+ auditLogs,
+ commandHistory,
+ dashboardPreferences,
+ dismissedAlerts,
+ fileManagerPinned,
+ fileManagerRecent,
+ fileManagerShortcuts,
+ hostAccess,
+ hosts,
+ networkTopology,
+ opksshTokens,
+ recentActivity,
+ sessionRecordings,
+ sessions,
+ sharedCredentials,
+ snippetFolders,
+ snippets,
+ sshCredentialUsage,
+ sshCredentials,
+ sshFolders,
+ transferRecent,
+ userOpenTabs,
+ userPreferences,
+ userRoles,
+ users,
+} from "../db/schema.js";
+
+export async function deleteUserAndRelatedData(userId: string): Promise<void> {
+ try {
+ await db
+ .delete(sharedCredentials)
+ .where(eq(sharedCredentials.targetUserId, userId));
+
+ await db
+ .delete(sessionRecordings)
+ .where(eq(sessionRecordings.userId, userId));
+
+ await db.delete(hostAccess).where(eq(hostAccess.userId, userId));
+ await db.delete(hostAccess).where(eq(hostAccess.grantedBy, userId));
+
+ await db.delete(sessions).where(eq(sessions.userId, userId));
+
+ await db.delete(userRoles).where(eq(userRoles.userId, userId));
+ await db.delete(auditLogs).where(eq(auditLogs.userId, userId));
+
+ await db
+ .delete(sshCredentialUsage)
+ .where(eq(sshCredentialUsage.userId, userId));
+
+ await db
+ .delete(fileManagerRecent)
+ .where(eq(fileManagerRecent.userId, userId));
+ await db
+ .delete(fileManagerPinned)
+ .where(eq(fileManagerPinned.userId, userId));
+ await db
+ .delete(fileManagerShortcuts)
+ .where(eq(fileManagerShortcuts.userId, userId));
+
+ await db.delete(transferRecent).where(eq(transferRecent.userId, userId));
+
+ await db.delete(recentActivity).where(eq(recentActivity.userId, userId));
+ await db.delete(dismissedAlerts).where(eq(dismissedAlerts.userId, userId));
+
+ await db.delete(snippets).where(eq(snippets.userId, userId));
+ await db.delete(snippetFolders).where(eq(snippetFolders.userId, userId));
+
+ await db.delete(sshFolders).where(eq(sshFolders.userId, userId));
+
+ await db.delete(commandHistory).where(eq(commandHistory.userId, userId));
+
+ await db.delete(hosts).where(eq(hosts.userId, userId));
+ await db.delete(sshCredentials).where(eq(sshCredentials.userId, userId));
+
+ await db.delete(networkTopology).where(eq(networkTopology.userId, userId));
+ await db
+ .delete(dashboardPreferences)
+ .where(eq(dashboardPreferences.userId, userId));
+ await db.delete(opksshTokens).where(eq(opksshTokens.userId, userId));
+ await db.delete(userOpenTabs).where(eq(userOpenTabs.userId, userId));
+ await db.delete(userPreferences).where(eq(userPreferences.userId, userId));
+
+ db.$client
+ .prepare("DELETE FROM settings WHERE key LIKE ?")
+ .run(`user_%_${userId}`);
+
+ await db.delete(users).where(eq(users.id, userId));
+
+ authLogger.success("User and all related data deleted successfully", {
+ operation: "delete_user_and_related_data_complete",
+ userId,
+ });
+ } catch (error) {
+ authLogger.error("Failed to delete user and related data", error, {
+ operation: "delete_user_and_related_data_failed",
+ userId,
+ });
+ throw error;
+ }
+}
diff --git a/src/backend/database/routes/host-autostart-routes.ts b/src/backend/database/routes/host-autostart-routes.ts
new file mode 100644
index 000000000..e44665098
--- /dev/null
+++ b/src/backend/database/routes/host-autostart-routes.ts
@@ -0,0 +1,322 @@
+import type { Request, RequestHandler, Response, Router } from "express";
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import { and, eq, isNotNull, or } from "drizzle-orm";
+import { DataCrypto } from "../../utils/data-crypto.js";
+import { sshLogger } from "../../utils/logger.js";
+import { db, DatabaseSaveTrigger } from "../db/index.js";
+import { hosts } from "../db/schema.js";
+
+type HostAutostartRoutesDeps = {
+ authenticateJWT: RequestHandler;
+ requireDataAccess: RequestHandler;
+};
+
+export function registerHostAutostartRoutes(
+ router: Router,
+ { authenticateJWT, requireDataAccess }: HostAutostartRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /host/autostart/enable:
+ * post:
+ * summary: Enable autostart for SSH configuration
+ * description: Enables autostart for a specific SSH configuration.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sshConfigId:
+ * type: number
+ * responses:
+ * 200:
+ * description: AutoStart enabled successfully.
+ * 400:
+ * description: Valid sshConfigId is required.
+ * 404:
+ * description: SSH configuration not found.
+ * 500:
+ * description: Internal server error.
+ */
+ router.post(
+ "/autostart/enable",
+ authenticateJWT,
+ requireDataAccess,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { sshConfigId } = req.body;
+
+ if (!sshConfigId || typeof sshConfigId !== "number") {
+ sshLogger.warn(
+ "Missing or invalid sshConfigId in autostart enable request",
+ {
+ operation: "autostart_enable",
+ userId,
+ sshConfigId,
+ },
+ );
+ return res.status(400).json({ error: "Valid sshConfigId is required" });
+ }
+
+ try {
+ const userDataKey = DataCrypto.getUserDataKey(userId);
+ if (!userDataKey) {
+ sshLogger.warn(
+ "User attempted to enable autostart without unlocked data",
+ {
+ operation: "autostart_enable_failed",
+ userId,
+ sshConfigId,
+ reason: "data_locked",
+ },
+ );
+ return res.status(400).json({
+ error: "Failed to enable autostart. Ensure user data is unlocked.",
+ });
+ }
+
+ const sshConfig = await db
+ .select()
+ .from(hosts)
+ .where(and(eq(hosts.id, sshConfigId), eq(hosts.userId, userId)));
+
+ if (sshConfig.length === 0) {
+ sshLogger.warn("SSH config not found for autostart enable", {
+ operation: "autostart_enable_failed",
+ userId,
+ sshConfigId,
+ reason: "config_not_found",
+ });
+ return res.status(404).json({
+ error: "SSH configuration not found",
+ });
+ }
+
+ const config = sshConfig[0];
+
+ const decryptedConfig = DataCrypto.decryptRecord(
+ "ssh_data",
+ config,
+ userId,
+ userDataKey,
+ );
+
+ let updatedTunnelConnections = config.tunnelConnections;
+ if (config.tunnelConnections) {
+ try {
+ const tunnelConnections = JSON.parse(config.tunnelConnections);
+
+ const resolvedConnections = await Promise.all(
+ tunnelConnections.map(async (tunnel: Record<string, unknown>) => {
+ if (
+ tunnel.autoStart &&
+ tunnel.endpointHost &&
+ !tunnel.endpointPassword &&
+ !tunnel.endpointKey
+ ) {
+ const endpointHosts = await db
+ .select()
+ .from(hosts)
+ .where(eq(hosts.userId, userId));
+
+ const endpointHost = endpointHosts.find(
+ (h) =>
+ h.name === tunnel.endpointHost ||
+ `${h.username}@${h.ip}` === tunnel.endpointHost,
+ );
+
+ if (endpointHost) {
+ const decryptedEndpoint = DataCrypto.decryptRecord(
+ "ssh_data",
+ endpointHost,
+ userId,
+ userDataKey,
+ );
+
+ return {
+ ...tunnel,
+ endpointPassword: decryptedEndpoint.password || null,
+ endpointKey: decryptedEndpoint.key || null,
+ endpointKeyPassword:
+ decryptedEndpoint.keyPassword || null,
+ endpointAuthType: endpointHost.authType,
+ };
+ }
+ }
+ return tunnel;
+ }),
+ );
+
+ updatedTunnelConnections = JSON.stringify(resolvedConnections);
+ } catch (error) {
+ sshLogger.warn("Failed to update tunnel connections", {
+ operation: "tunnel_connections_update_failed",
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+ }
+
+ await db
+ .update(hosts)
+ .set({
+ autostartPassword: decryptedConfig.password || null,
+ autostartKey: decryptedConfig.key || null,
+ autostartKeyPassword: decryptedConfig.keyPassword || null,
+ tunnelConnections: updatedTunnelConnections,
+ })
+ .where(eq(hosts.id, sshConfigId));
+
+ try {
+ await DatabaseSaveTrigger.triggerSave();
+ } catch (saveError) {
+ sshLogger.warn("Database save failed after autostart", {
+ operation: "autostart_db_save_failed",
+ error:
+ saveError instanceof Error ? saveError.message : "Unknown error",
+ });
+ }
+
+ res.json({
+ message: "AutoStart enabled successfully",
+ sshConfigId,
+ });
+ } catch (error) {
+ sshLogger.error("Error enabling autostart", error, {
+ operation: "autostart_enable_error",
+ userId,
+ sshConfigId,
+ });
+ res.status(500).json({ error: "Internal server error" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/autostart/disable:
+ * delete:
+ * summary: Disable autostart for SSH configuration
+ * description: Disables autostart for a specific SSH configuration.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sshConfigId:
+ * type: number
+ * responses:
+ * 200:
+ * description: AutoStart disabled successfully.
+ * 400:
+ * description: Valid sshConfigId is required.
+ * 500:
+ * description: Internal server error.
+ */
+ router.delete(
+ "/autostart/disable",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { sshConfigId } = req.body;
+
+ if (!sshConfigId || typeof sshConfigId !== "number") {
+ sshLogger.warn(
+ "Missing or invalid sshConfigId in autostart disable request",
+ {
+ operation: "autostart_disable",
+ userId,
+ sshConfigId,
+ },
+ );
+ return res.status(400).json({ error: "Valid sshConfigId is required" });
+ }
+
+ try {
+ await db
+ .update(hosts)
+ .set({
+ autostartPassword: null,
+ autostartKey: null,
+ autostartKeyPassword: null,
+ })
+ .where(and(eq(hosts.id, sshConfigId), eq(hosts.userId, userId)));
+
+ res.json({
+ message: "AutoStart disabled successfully",
+ sshConfigId,
+ });
+ } catch (error) {
+ sshLogger.error("Error disabling autostart", error, {
+ operation: "autostart_disable_error",
+ userId,
+ sshConfigId,
+ });
+ res.status(500).json({ error: "Internal server error" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/autostart/status:
+ * get:
+ * summary: Get autostart status
+ * description: Retrieves the autostart status for the user's SSH configurations.
+ * tags:
+ * - SSH
+ * responses:
+ * 200:
+ * description: A list of autostart configurations.
+ * 500:
+ * description: Internal server error.
+ */
+ router.get(
+ "/autostart/status",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+
+ try {
+ const autostartConfigs = await db
+ .select()
+ .from(hosts)
+ .where(
+ and(
+ eq(hosts.userId, userId),
+ or(
+ isNotNull(hosts.autostartPassword),
+ isNotNull(hosts.autostartKey),
+ ),
+ ),
+ );
+
+ const statusList = autostartConfigs.map((config) => ({
+ sshConfigId: config.id,
+ host: config.ip,
+ port: config.port,
+ username: config.username,
+ authType: config.authType,
+ }));
+
+ res.json({
+ autostart_configs: statusList,
+ total_count: statusList.length,
+ });
+ } catch (error) {
+ sshLogger.error("Error getting autostart status", error, {
+ operation: "autostart_status_error",
+ userId,
+ });
+ res.status(500).json({ error: "Internal server error" });
+ }
+ },
+ );
+}
diff --git a/src/backend/database/routes/host-bulk-routes.ts b/src/backend/database/routes/host-bulk-routes.ts
new file mode 100644
index 000000000..9edd751f8
--- /dev/null
+++ b/src/backend/database/routes/host-bulk-routes.ts
@@ -0,0 +1,470 @@
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import type { Request, RequestHandler, Response, Router } from "express";
+import { and, eq, inArray } from "drizzle-orm";
+import { sshLogger } from "../../utils/logger.js";
+import { SimpleDBOps } from "../../utils/simple-db-ops.js";
+import { db, DatabaseSaveTrigger } from "../db/index.js";
+import { hosts, sshCredentials } from "../db/schema.js";
+import {
+ isNonEmptyString,
+ isValidPort,
+ normalizeImportedHost,
+} from "./host-normalizers.js";
+
+export function registerHostBulkRoutes(
+ router: Router,
+ authenticateJWT: RequestHandler,
+): void {
+ /**
+ * @openapi
+ * /host/bulk-import:
+ * post:
+ * summary: Bulk import SSH hosts
+ * description: Bulk imports multiple SSH hosts.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hosts:
+ * type: array
+ * items:
+ * type: object
+ * responses:
+ * 200:
+ * description: Import completed.
+ * 400:
+ * description: Invalid request body.
+ */
+
+ /**
+ * @swagger
+ * /host/bulk-update:
+ * patch:
+ * summary: Bulk update partial fields on multiple SSH hosts
+ * tags: [SSH]
+ * security:
+ * - bearerAuth: []
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hostIds:
+ * type: array
+ * items:
+ * type: number
+ * updates:
+ * type: object
+ * responses:
+ * 200:
+ * description: Bulk update completed.
+ * 400:
+ * description: Invalid request body.
+ */
+ router.patch(
+ "/bulk-update",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { hostIds, updates } = req.body;
+
+ if (!Array.isArray(hostIds) || hostIds.length === 0) {
+ return res
+ .status(400)
+ .json({ error: "hostIds array is required and must not be empty" });
+ }
+
+ if (hostIds.length > 1000) {
+ return res
+ .status(400)
+ .json({ error: "Maximum 1000 hosts allowed per bulk update" });
+ }
+
+ if (
+ !updates ||
+ typeof updates !== "object" ||
+ Object.keys(updates).length === 0
+ ) {
+ return res.status(400).json({
+ error:
+ "updates object is required and must contain at least one field",
+ });
+ }
+
+ try {
+ const ownedHosts = await db
+ .select({ id: hosts.id, statsConfig: hosts.statsConfig })
+ .from(hosts)
+ .where(and(inArray(hosts.id, hostIds), eq(hosts.userId, userId)));
+
+ const ownedIds = ownedHosts.map((h) => h.id);
+ const unauthorizedIds = hostIds.filter(
+ (id: number) => !ownedIds.includes(id),
+ );
+
+ if (ownedIds.length === 0) {
+ return res.status(404).json({ error: "No matching hosts found" });
+ }
+
+ const errors: string[] = [];
+ if (unauthorizedIds.length > 0) {
+ errors.push(
+ `${unauthorizedIds.length} host(s) not found or not owned`,
+ );
+ }
+
+ const simpleUpdates: Record<string, unknown> = {};
+ if (typeof updates.pin === "boolean") simpleUpdates.pin = updates.pin;
+ if (typeof updates.folder === "string")
+ simpleUpdates.folder = updates.folder || null;
+ if (typeof updates.enableTerminal === "boolean")
+ simpleUpdates.enableTerminal = updates.enableTerminal;
+ if (typeof updates.enableTunnel === "boolean")
+ simpleUpdates.enableTunnel = updates.enableTunnel;
+ if (typeof updates.enableFileManager === "boolean")
+ simpleUpdates.enableFileManager = updates.enableFileManager;
+ if (typeof updates.enableDocker === "boolean")
+ simpleUpdates.enableDocker = updates.enableDocker;
+
+ if (Object.keys(simpleUpdates).length > 0) {
+ await db
+ .update(hosts)
+ .set(simpleUpdates)
+ .where(and(inArray(hosts.id, ownedIds), eq(hosts.userId, userId)));
+ }
+
+ if (updates.statsConfig && typeof updates.statsConfig === "object") {
+ for (const host of ownedHosts) {
+ try {
+ const existing = host.statsConfig
+ ? JSON.parse(host.statsConfig as string)
+ : {};
+ const merged = { ...existing, ...updates.statsConfig };
+ await db
+ .update(hosts)
+ .set({ statsConfig: JSON.stringify(merged) })
+ .where(and(eq(hosts.id, host.id), eq(hosts.userId, userId)));
+ } catch {
+ errors.push(`Failed to update statsConfig for host ${host.id}`);
+ }
+ }
+ }
+
+ DatabaseSaveTrigger.triggerSave("bulk_update");
+
+ return res.json({
+ updated: ownedIds.length,
+ failed: unauthorizedIds.length,
+ errors,
+ });
+ } catch (error) {
+ sshLogger.error("Failed to bulk update hosts:", error);
+ return res.status(500).json({ error: "Failed to bulk update hosts" });
+ }
+ },
+ );
+
+ router.post(
+ "/bulk-import",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { hosts: hostsToImport, overwrite } = req.body;
+
+ if (!Array.isArray(hostsToImport) || hostsToImport.length === 0) {
+ return res
+ .status(400)
+ .json({ error: "Hosts array is required and must not be empty" });
+ }
+
+ if (hostsToImport.length > 100) {
+ return res
+ .status(400)
+ .json({ error: "Maximum 100 hosts allowed per import" });
+ }
+
+ const results = {
+ success: 0,
+ updated: 0,
+ skipped: 0,
+ failed: 0,
+ errors: [] as string[],
+ };
+
+ let existingHostMap: Map<string, { id: number }> | undefined;
+ if (overwrite) {
+ try {
+ const allHosts = await SimpleDBOps.select<Record<string, unknown>>(
+ db.select().from(hosts).where(eq(hosts.userId, userId)),
+ "ssh_data",
+ userId,
+ );
+ existingHostMap = new Map();
+ for (const h of allHosts) {
+ const key = `${h.ip}:${h.port}:${h.username}`;
+ existingHostMap.set(key, { id: h.id as number });
+ }
+ } catch {
+ existingHostMap = undefined;
+ }
+ }
+
+ for (let i = 0; i < hostsToImport.length; i++) {
+ const hostData = normalizeImportedHost(hostsToImport[i]);
+
+ try {
+ const effectiveConnectionType = hostData.connectionType || "ssh";
+
+ if (!isNonEmptyString(hostData.ip) || !isValidPort(hostData.port)) {
+ results.failed++;
+ results.errors.push(
+ `Host ${i + 1}: Missing required fields (ip, port)`,
+ );
+ continue;
+ }
+
+ if (
+ effectiveConnectionType === "ssh" &&
+ !isNonEmptyString(hostData.username)
+ ) {
+ results.failed++;
+ results.errors.push(
+ `Host ${i + 1}: Username required for SSH connections`,
+ );
+ continue;
+ }
+
+ if (
+ effectiveConnectionType === "ssh" &&
+ hostData.authType &&
+ !["password", "key", "credential", "none", "opkssh"].includes(
+ hostData.authType,
+ )
+ ) {
+ results.failed++;
+ results.errors.push(
+ `Host ${i + 1}: Invalid authType. Must be 'password', 'key', 'credential', 'none', or 'opkssh'`,
+ );
+ continue;
+ }
+
+ if (
+ effectiveConnectionType === "ssh" &&
+ hostData.authType === "password" &&
+ !isNonEmptyString(hostData.password)
+ ) {
+ results.failed++;
+ results.errors.push(
+ `Host ${i + 1}: Password required for password authentication`,
+ );
+ continue;
+ }
+
+ if (
+ effectiveConnectionType === "ssh" &&
+ hostData.authType === "key" &&
+ !isNonEmptyString(hostData.key)
+ ) {
+ results.failed++;
+ results.errors.push(
+ `Host ${i + 1}: Key required for key authentication`,
+ );
+ continue;
+ }
+
+ if (
+ effectiveConnectionType === "ssh" &&
+ hostData.authType === "credential" &&
+ !hostData.credentialId
+ ) {
+ results.failed++;
+ results.errors.push(
+ `Host ${i + 1}: credentialId required for credential authentication`,
+ );
+ continue;
+ }
+
+ if (
+ effectiveConnectionType === "ssh" &&
+ hostData.authType === "credential" &&
+ hostData.credentialId
+ ) {
+ const cred = await db
+ .select({ id: sshCredentials.id })
+ .from(sshCredentials)
+ .where(
+ and(
+ eq(sshCredentials.id, hostData.credentialId),
+ eq(sshCredentials.userId, userId),
+ ),
+ )
+ .limit(1);
+
+ if (cred.length === 0) {
+ const fallback = await db
+ .select({ id: sshCredentials.id })
+ .from(sshCredentials)
+ .where(eq(sshCredentials.userId, userId))
+ .limit(1);
+
+ if (fallback.length > 0) {
+ hostData.credentialId = fallback[0].id;
+ } else {
+ results.failed++;
+ results.errors.push(
+ `Host ${i + 1}: credentialId ${hostData.credentialId} not found and no fallback credential available`,
+ );
+ continue;
+ }
+ }
+ }
+
+ const sshDataObj: Record<string, unknown> = {
+ userId: userId,
+ connectionType: effectiveConnectionType,
+ name: hostData.name || `${hostData.username || ""}@${hostData.ip}`,
+ folder: hostData.folder || "Default",
+ tags: Array.isArray(hostData.tags) ? hostData.tags.join(",") : "",
+ ip: hostData.ip,
+ port: hostData.port,
+ username: hostData.username || null,
+ pin: hostData.pin || false,
+ enableTerminal: hostData.enableTerminal !== false,
+ enableTunnel: hostData.enableTunnel !== false,
+ enableFileManager: hostData.enableFileManager !== false,
+ enableDocker: hostData.enableDocker || false,
+ showTerminalInSidebar: hostData.showTerminalInSidebar ? 1 : 0,
+ showFileManagerInSidebar: hostData.showFileManagerInSidebar ? 1 : 0,
+ showTunnelInSidebar: hostData.showTunnelInSidebar ? 1 : 0,
+ showDockerInSidebar: hostData.showDockerInSidebar ? 1 : 0,
+ showServerStatsInSidebar: hostData.showServerStatsInSidebar ? 1 : 0,
+ defaultPath: hostData.defaultPath || "/",
+ sudoPassword: hostData.sudoPassword || null,
+ tunnelConnections: hostData.tunnelConnections
+ ? JSON.stringify(hostData.tunnelConnections)
+ : "[]",
+ jumpHosts: hostData.jumpHosts
+ ? JSON.stringify(hostData.jumpHosts)
+ : null,
+ quickActions: hostData.quickActions
+ ? JSON.stringify(hostData.quickActions)
+ : null,
+ statsConfig: hostData.statsConfig
+ ? JSON.stringify(hostData.statsConfig)
+ : null,
+ dockerConfig: hostData.dockerConfig
+ ? JSON.stringify(hostData.dockerConfig)
+ : null,
+ terminalConfig: hostData.terminalConfig
+ ? JSON.stringify(hostData.terminalConfig)
+ : null,
+ forceKeyboardInteractive: hostData.forceKeyboardInteractive
+ ? "true"
+ : "false",
+ notes: hostData.notes || null,
+ useSocks5: hostData.useSocks5 ? 1 : 0,
+ socks5Host: hostData.socks5Host || null,
+ socks5Port: hostData.socks5Port || null,
+ socks5Username: hostData.socks5Username || null,
+ socks5Password: hostData.socks5Password || null,
+ socks5ProxyChain: hostData.socks5ProxyChain
+ ? JSON.stringify(hostData.socks5ProxyChain)
+ : null,
+ portKnockSequence: hostData.portKnockSequence
+ ? JSON.stringify(hostData.portKnockSequence)
+ : null,
+ overrideCredentialUsername: hostData.overrideCredentialUsername
+ ? 1
+ : 0,
+ enableSsh: hostData.enableSsh ?? effectiveConnectionType === "ssh",
+ enableRdp: hostData.enableRdp ?? false,
+ enableVnc: hostData.enableVnc ?? false,
+ enableTelnet: hostData.enableTelnet ?? false,
+ updatedAt: new Date().toISOString(),
+ };
+
+ if (effectiveConnectionType !== "ssh") {
+ sshDataObj.password = hostData.password || null;
+ sshDataObj.authType = "password";
+ sshDataObj.credentialId = null;
+ sshDataObj.key = null;
+ sshDataObj.keyPassword = null;
+ sshDataObj.keyType = null;
+ sshDataObj.rdpUser = hostData.rdpUser || null;
+ sshDataObj.rdpPassword = hostData.rdpPassword || null;
+ sshDataObj.rdpDomain = hostData.rdpDomain || null;
+ sshDataObj.rdpSecurity = hostData.rdpSecurity || null;
+ sshDataObj.rdpIgnoreCert = hostData.rdpIgnoreCert ? 1 : 0;
+ sshDataObj.rdpPort = hostData.rdpPort || 3389;
+ sshDataObj.vncUser = hostData.vncUser || null;
+ sshDataObj.vncPassword = hostData.vncPassword || null;
+ sshDataObj.vncPort = hostData.vncPort || 5900;
+ sshDataObj.telnetUser = hostData.telnetUser || null;
+ sshDataObj.telnetPassword = hostData.telnetPassword || null;
+ sshDataObj.telnetPort = hostData.telnetPort || 23;
+ sshDataObj.enableRdp = hostData.enableRdp ? 1 : 0;
+ sshDataObj.enableVnc = hostData.enableVnc ? 1 : 0;
+ sshDataObj.enableTelnet = hostData.enableTelnet ? 1 : 0;
+ sshDataObj.guacamoleConfig = hostData.guacamoleConfig
+ ? JSON.stringify(hostData.guacamoleConfig)
+ : null;
+ } else {
+ sshDataObj.password =
+ hostData.authType === "password" ? hostData.password : null;
+ sshDataObj.authType = hostData.authType || "password";
+ sshDataObj.credentialId =
+ hostData.authType === "credential" ? hostData.credentialId : null;
+ sshDataObj.key = hostData.authType === "key" ? hostData.key : null;
+ sshDataObj.keyPassword =
+ hostData.authType === "key" ? hostData.keyPassword || null : null;
+ sshDataObj.keyType =
+ hostData.authType === "key" ? hostData.keyType || "auto" : null;
+ sshDataObj.domain = null;
+ sshDataObj.security = null;
+ sshDataObj.ignoreCert = 0;
+ sshDataObj.guacamoleConfig = null;
+ }
+
+ const lookupKey = `${hostData.ip}:${hostData.port}:${hostData.username}`;
+ const existing = existingHostMap?.get(lookupKey);
+
+ if (existing) {
+ await SimpleDBOps.update(
+ hosts,
+ "ssh_data",
+ eq(hosts.id, existing.id),
+ sshDataObj,
+ userId,
+ );
+ results.updated++;
+ } else {
+ sshDataObj.createdAt = new Date().toISOString();
+ await SimpleDBOps.insert(hosts, "ssh_data", sshDataObj, userId);
+ results.success++;
+ }
+ } catch (error) {
+ results.failed++;
+ results.errors.push(
+ `Host ${i + 1}: ${error instanceof Error ? error.message : "Unknown error"}`,
+ );
+ }
+ }
+
+ res.json({
+ message: `Import completed: ${results.success} created, ${results.updated} updated, ${results.failed} failed`,
+ success: results.success,
+ updated: results.updated,
+ skipped: results.skipped,
+ failed: results.failed,
+ errors: results.errors,
+ });
+ },
+ );
+}
diff --git a/src/backend/database/routes/host-command-history-routes.ts b/src/backend/database/routes/host-command-history-routes.ts
new file mode 100644
index 000000000..d120322ba
--- /dev/null
+++ b/src/backend/database/routes/host-command-history-routes.ts
@@ -0,0 +1,148 @@
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import type { Request, RequestHandler, Response, Router } from "express";
+import { and, desc, eq } from "drizzle-orm";
+import { sshLogger } from "../../utils/logger.js";
+import { db } from "../db/index.js";
+import { commandHistory } from "../db/schema.js";
+import { isNonEmptyString } from "./host-normalizers.js";
+
+export function registerHostCommandHistoryRoutes(
+ router: Router,
+ authenticateJWT: RequestHandler,
+): void {
+ /**
+ * @openapi
+ * /host/command-history/{hostId}:
+ * get:
+ * summary: Get command history
+ * description: Retrieves the command history for a specific host.
+ * tags:
+ * - SSH
+ * parameters:
+ * - in: path
+ * name: hostId
+ * required: true
+ * schema:
+ * type: integer
+ * responses:
+ * 200:
+ * description: A list of commands.
+ * 400:
+ * description: Invalid userId or hostId.
+ * 500:
+ * description: Failed to fetch command history.
+ */
+ router.get(
+ "/command-history/:hostId",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const hostIdParam = Array.isArray(req.params.hostId)
+ ? req.params.hostId[0]
+ : req.params.hostId;
+ const hostId = parseInt(hostIdParam, 10);
+
+ if (!isNonEmptyString(userId) || !hostId) {
+ sshLogger.warn("Invalid userId or hostId for command history fetch", {
+ operation: "command_history_fetch",
+ hostId,
+ userId,
+ });
+ return res.status(400).json({ error: "Invalid userId or hostId" });
+ }
+
+ try {
+ const history = await db
+ .select({
+ id: commandHistory.id,
+ command: commandHistory.command,
+ })
+ .from(commandHistory)
+ .where(
+ and(
+ eq(commandHistory.userId, userId),
+ eq(commandHistory.hostId, hostId),
+ ),
+ )
+ .orderBy(desc(commandHistory.executedAt))
+ .limit(200);
+
+ res.json(history.map((h) => h.command));
+ } catch (err) {
+ sshLogger.error("Failed to fetch command history from database", err, {
+ operation: "command_history_fetch",
+ hostId,
+ userId,
+ });
+ res.status(500).json({ error: "Failed to fetch command history" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/command-history:
+ * delete:
+ * summary: Delete command from history
+ * description: Deletes a specific command from the history of a host.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hostId:
+ * type: integer
+ * command:
+ * type: string
+ * responses:
+ * 200:
+ * description: Command deleted from history.
+ * 400:
+ * description: Invalid data.
+ * 500:
+ * description: Failed to delete command.
+ */
+ router.delete(
+ "/command-history",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { hostId, command } = req.body;
+
+ if (!isNonEmptyString(userId) || !hostId || !command) {
+ sshLogger.warn("Invalid data for command history deletion", {
+ operation: "command_history_delete",
+ hostId,
+ userId,
+ });
+ return res.status(400).json({ error: "Invalid data" });
+ }
+
+ try {
+ await db
+ .delete(commandHistory)
+ .where(
+ and(
+ eq(commandHistory.userId, userId),
+ eq(commandHistory.hostId, hostId),
+ eq(commandHistory.command, command),
+ ),
+ );
+
+ res.json({ message: "Command deleted from history" });
+ } catch (err) {
+ sshLogger.error("Failed to delete command from history", err, {
+ operation: "command_history_delete",
+ hostId,
+ userId,
+ command,
+ });
+ res.status(500).json({ error: "Failed to delete command" });
+ }
+ },
+ );
+}
diff --git a/src/backend/database/routes/host-file-manager-bookmark-routes.ts b/src/backend/database/routes/host-file-manager-bookmark-routes.ts
new file mode 100644
index 000000000..9260f51ea
--- /dev/null
+++ b/src/backend/database/routes/host-file-manager-bookmark-routes.ts
@@ -0,0 +1,603 @@
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import type { Request, RequestHandler, Response, Router } from "express";
+import { and, desc, eq } from "drizzle-orm";
+import { sshLogger } from "../../utils/logger.js";
+import { db } from "../db/index.js";
+import {
+ fileManagerPinned,
+ fileManagerRecent,
+ fileManagerShortcuts,
+} from "../db/schema.js";
+import { isNonEmptyString } from "./host-normalizers.js";
+
+export function registerHostFileManagerBookmarkRoutes(
+ router: Router,
+ authenticateJWT: RequestHandler,
+): void {
+ /**
+ * @openapi
+ * /host/file_manager/recent:
+ * get:
+ * summary: Get recent files
+ * description: Retrieves a list of recent files for a specific host.
+ * tags:
+ * - SSH
+ * parameters:
+ * - in: query
+ * name: hostId
+ * required: true
+ * schema:
+ * type: integer
+ * responses:
+ * 200:
+ * description: A list of recent files.
+ * 400:
+ * description: Invalid userId or hostId.
+ * 500:
+ * description: Failed to fetch recent files.
+ */
+ router.get(
+ "/file_manager/recent",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const hostIdQuery = Array.isArray(req.query.hostId)
+ ? req.query.hostId[0]
+ : req.query.hostId;
+ const hostId = hostIdQuery ? parseInt(hostIdQuery as string) : null;
+
+ if (!isNonEmptyString(userId)) {
+ sshLogger.warn("Invalid userId for recent files fetch");
+ return res.status(400).json({ error: "Invalid userId" });
+ }
+
+ if (!hostId) {
+ sshLogger.warn("Host ID is required for recent files fetch");
+ return res.status(400).json({ error: "Host ID is required" });
+ }
+
+ try {
+ const recentFiles = await db
+ .select()
+ .from(fileManagerRecent)
+ .where(
+ and(
+ eq(fileManagerRecent.userId, userId),
+ eq(fileManagerRecent.hostId, hostId),
+ ),
+ )
+ .orderBy(desc(fileManagerRecent.lastOpened))
+ .limit(20);
+
+ res.json(recentFiles);
+ } catch (err) {
+ sshLogger.error("Failed to fetch recent files", err);
+ res.status(500).json({ error: "Failed to fetch recent files" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/file_manager/recent:
+ * post:
+ * summary: Add recent file
+ * description: Adds a file to the list of recent files for a host.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hostId:
+ * type: integer
+ * path:
+ * type: string
+ * name:
+ * type: string
+ * responses:
+ * 200:
+ * description: Recent file added.
+ * 400:
+ * description: Invalid data.
+ * 500:
+ * description: Failed to add recent file.
+ */
+ router.post(
+ "/file_manager/recent",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { hostId, path, name } = req.body;
+
+ if (!isNonEmptyString(userId) || !hostId || !path) {
+ sshLogger.warn("Invalid data for recent file addition");
+ return res.status(400).json({ error: "Invalid data" });
+ }
+
+ try {
+ const existing = await db
+ .select()
+ .from(fileManagerRecent)
+ .where(
+ and(
+ eq(fileManagerRecent.userId, userId),
+ eq(fileManagerRecent.hostId, hostId),
+ eq(fileManagerRecent.path, path),
+ ),
+ );
+
+ if (existing.length > 0) {
+ await db
+ .update(fileManagerRecent)
+ .set({ lastOpened: new Date().toISOString() })
+ .where(eq(fileManagerRecent.id, existing[0].id));
+ } else {
+ await db.insert(fileManagerRecent).values({
+ userId,
+ hostId,
+ path,
+ name: name || path.split("/").pop() || "Unknown",
+ lastOpened: new Date().toISOString(),
+ });
+ }
+
+ res.json({ message: "Recent file added" });
+ } catch (err) {
+ sshLogger.error("Failed to add recent file", err);
+ res.status(500).json({ error: "Failed to add recent file" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/file_manager/recent:
+ * delete:
+ * summary: Remove recent file
+ * description: Removes a file from the list of recent files for a host.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hostId:
+ * type: integer
+ * path:
+ * type: string
+ * responses:
+ * 200:
+ * description: Recent file removed.
+ * 400:
+ * description: Invalid data.
+ * 500:
+ * description: Failed to remove recent file.
+ */
+ router.delete(
+ "/file_manager/recent",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { hostId, path } = req.body;
+
+ if (!isNonEmptyString(userId) || !hostId || !path) {
+ sshLogger.warn("Invalid data for recent file deletion");
+ return res.status(400).json({ error: "Invalid data" });
+ }
+
+ try {
+ await db
+ .delete(fileManagerRecent)
+ .where(
+ and(
+ eq(fileManagerRecent.userId, userId),
+ eq(fileManagerRecent.hostId, hostId),
+ eq(fileManagerRecent.path, path),
+ ),
+ );
+
+ res.json({ message: "Recent file removed" });
+ } catch (err) {
+ sshLogger.error("Failed to remove recent file", err);
+ res.status(500).json({ error: "Failed to remove recent file" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/file_manager/pinned:
+ * get:
+ * summary: Get pinned files
+ * description: Retrieves a list of pinned files for a specific host.
+ * tags:
+ * - SSH
+ * parameters:
+ * - in: query
+ * name: hostId
+ * required: true
+ * schema:
+ * type: integer
+ * responses:
+ * 200:
+ * description: A list of pinned files.
+ * 400:
+ * description: Invalid userId or hostId.
+ * 500:
+ * description: Failed to fetch pinned files.
+ */
+ router.get(
+ "/file_manager/pinned",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const hostIdQuery = Array.isArray(req.query.hostId)
+ ? req.query.hostId[0]
+ : req.query.hostId;
+ const hostId = hostIdQuery ? parseInt(hostIdQuery as string) : null;
+
+ if (!isNonEmptyString(userId)) {
+ sshLogger.warn("Invalid userId for pinned files fetch");
+ return res.status(400).json({ error: "Invalid userId" });
+ }
+
+ if (!hostId) {
+ sshLogger.warn("Host ID is required for pinned files fetch");
+ return res.status(400).json({ error: "Host ID is required" });
+ }
+
+ try {
+ const pinnedFiles = await db
+ .select()
+ .from(fileManagerPinned)
+ .where(
+ and(
+ eq(fileManagerPinned.userId, userId),
+ eq(fileManagerPinned.hostId, hostId),
+ ),
+ )
+ .orderBy(desc(fileManagerPinned.pinnedAt));
+
+ res.json(pinnedFiles);
+ } catch (err) {
+ sshLogger.error("Failed to fetch pinned files", err);
+ res.status(500).json({ error: "Failed to fetch pinned files" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/file_manager/pinned:
+ * post:
+ * summary: Add pinned file
+ * description: Adds a file to the list of pinned files for a host.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hostId:
+ * type: integer
+ * path:
+ * type: string
+ * name:
+ * type: string
+ * responses:
+ * 200:
+ * description: File pinned.
+ * 400:
+ * description: Invalid data.
+ * 409:
+ * description: File already pinned.
+ * 500:
+ * description: Failed to pin file.
+ */
+ router.post(
+ "/file_manager/pinned",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { hostId, path, name } = req.body;
+
+ if (!isNonEmptyString(userId) || !hostId || !path) {
+ sshLogger.warn("Invalid data for pinned file addition");
+ return res.status(400).json({ error: "Invalid data" });
+ }
+
+ try {
+ const existing = await db
+ .select()
+ .from(fileManagerPinned)
+ .where(
+ and(
+ eq(fileManagerPinned.userId, userId),
+ eq(fileManagerPinned.hostId, hostId),
+ eq(fileManagerPinned.path, path),
+ ),
+ );
+
+ if (existing.length > 0) {
+ return res.status(409).json({ error: "File already pinned" });
+ }
+
+ await db.insert(fileManagerPinned).values({
+ userId,
+ hostId,
+ path,
+ name: name || path.split("/").pop() || "Unknown",
+ pinnedAt: new Date().toISOString(),
+ });
+
+ res.json({ message: "File pinned" });
+ } catch (err) {
+ sshLogger.error("Failed to pin file", err);
+ res.status(500).json({ error: "Failed to pin file" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/file_manager/pinned:
+ * delete:
+ * summary: Remove pinned file
+ * description: Removes a file from the list of pinned files for a host.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hostId:
+ * type: integer
+ * path:
+ * type: string
+ * responses:
+ * 200:
+ * description: Pinned file removed.
+ * 400:
+ * description: Invalid data.
+ * 500:
+ * description: Failed to remove pinned file.
+ */
+ router.delete(
+ "/file_manager/pinned",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { hostId, path } = req.body;
+
+ if (!isNonEmptyString(userId) || !hostId || !path) {
+ sshLogger.warn("Invalid data for pinned file deletion");
+ return res.status(400).json({ error: "Invalid data" });
+ }
+
+ try {
+ await db
+ .delete(fileManagerPinned)
+ .where(
+ and(
+ eq(fileManagerPinned.userId, userId),
+ eq(fileManagerPinned.hostId, hostId),
+ eq(fileManagerPinned.path, path),
+ ),
+ );
+
+ res.json({ message: "Pinned file removed" });
+ } catch (err) {
+ sshLogger.error("Failed to remove pinned file", err);
+ res.status(500).json({ error: "Failed to remove pinned file" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/file_manager/shortcuts:
+ * get:
+ * summary: Get shortcuts
+ * description: Retrieves a list of shortcuts for a specific host.
+ * tags:
+ * - SSH
+ * parameters:
+ * - in: query
+ * name: hostId
+ * required: true
+ * schema:
+ * type: integer
+ * responses:
+ * 200:
+ * description: A list of shortcuts.
+ * 400:
+ * description: Invalid userId or hostId.
+ * 500:
+ * description: Failed to fetch shortcuts.
+ */
+ router.get(
+ "/file_manager/shortcuts",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const hostIdQuery = Array.isArray(req.query.hostId)
+ ? req.query.hostId[0]
+ : req.query.hostId;
+ const hostId = hostIdQuery ? parseInt(hostIdQuery as string) : null;
+
+ if (!isNonEmptyString(userId)) {
+ sshLogger.warn("Invalid userId for shortcuts fetch");
+ return res.status(400).json({ error: "Invalid userId" });
+ }
+
+ if (!hostId) {
+ sshLogger.warn("Host ID is required for shortcuts fetch");
+ return res.status(400).json({ error: "Host ID is required" });
+ }
+
+ try {
+ const shortcuts = await db
+ .select()
+ .from(fileManagerShortcuts)
+ .where(
+ and(
+ eq(fileManagerShortcuts.userId, userId),
+ eq(fileManagerShortcuts.hostId, hostId),
+ ),
+ )
+ .orderBy(desc(fileManagerShortcuts.createdAt));
+
+ res.json(shortcuts);
+ } catch (err) {
+ sshLogger.error("Failed to fetch shortcuts", err);
+ res.status(500).json({ error: "Failed to fetch shortcuts" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/file_manager/shortcuts:
+ * post:
+ * summary: Add shortcut
+ * description: Adds a shortcut for a specific host.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hostId:
+ * type: integer
+ * path:
+ * type: string
+ * name:
+ * type: string
+ * responses:
+ * 200:
+ * description: Shortcut added.
+ * 400:
+ * description: Invalid data.
+ * 409:
+ * description: Shortcut already exists.
+ * 500:
+ * description: Failed to add shortcut.
+ */
+ router.post(
+ "/file_manager/shortcuts",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { hostId, path, name } = req.body;
+
+ if (!isNonEmptyString(userId) || !hostId || !path) {
+ sshLogger.warn("Invalid data for shortcut addition");
+ return res.status(400).json({ error: "Invalid data" });
+ }
+
+ try {
+ const existing = await db
+ .select()
+ .from(fileManagerShortcuts)
+ .where(
+ and(
+ eq(fileManagerShortcuts.userId, userId),
+ eq(fileManagerShortcuts.hostId, hostId),
+ eq(fileManagerShortcuts.path, path),
+ ),
+ );
+
+ if (existing.length > 0) {
+ return res.status(409).json({ error: "Shortcut already exists" });
+ }
+
+ await db.insert(fileManagerShortcuts).values({
+ userId,
+ hostId,
+ path,
+ name: name || path.split("/").pop() || "Unknown",
+ createdAt: new Date().toISOString(),
+ });
+
+ res.json({ message: "Shortcut added" });
+ } catch (err) {
+ sshLogger.error("Failed to add shortcut", err);
+ res.status(500).json({ error: "Failed to add shortcut" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/file_manager/shortcuts:
+ * delete:
+ * summary: Remove shortcut
+ * description: Removes a shortcut for a specific host.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hostId:
+ * type: integer
+ * path:
+ * type: string
+ * responses:
+ * 200:
+ * description: Shortcut removed.
+ * 400:
+ * description: Invalid data.
+ * 500:
+ * description: Failed to remove shortcut.
+ */
+ router.delete(
+ "/file_manager/shortcuts",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { hostId, path } = req.body;
+
+ if (!isNonEmptyString(userId) || !hostId || !path) {
+ sshLogger.warn("Invalid data for shortcut deletion");
+ return res.status(400).json({ error: "Invalid data" });
+ }
+
+ try {
+ await db
+ .delete(fileManagerShortcuts)
+ .where(
+ and(
+ eq(fileManagerShortcuts.userId, userId),
+ eq(fileManagerShortcuts.hostId, hostId),
+ eq(fileManagerShortcuts.path, path),
+ ),
+ );
+
+ res.json({ message: "Shortcut removed" });
+ } catch (err) {
+ sshLogger.error("Failed to remove shortcut", err);
+ res.status(500).json({ error: "Failed to remove shortcut" });
+ }
+ },
+ );
+}
diff --git a/src/backend/database/routes/host-folder-routes.ts b/src/backend/database/routes/host-folder-routes.ts
new file mode 100644
index 000000000..2964745e6
--- /dev/null
+++ b/src/backend/database/routes/host-folder-routes.ts
@@ -0,0 +1,423 @@
+import type { Request, RequestHandler, Response, Router } from "express";
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import { and, eq, inArray, or } from "drizzle-orm";
+import { databaseLogger, sshLogger } from "../../utils/logger.js";
+import { SimpleDBOps } from "../../utils/simple-db-ops.js";
+import { db, DatabaseSaveTrigger } from "../db/index.js";
+import {
+ commandHistory,
+ fileManagerPinned,
+ fileManagerRecent,
+ fileManagerShortcuts,
+ hostAccess,
+ hosts,
+ recentActivity,
+ sessionRecordings,
+ sshCredentialUsage,
+ sshCredentials,
+ sshFolders,
+ transferRecent,
+} from "../db/schema.js";
+import { isNonEmptyString } from "./host-normalizers.js";
+
+type HostFolderRoutesDeps = {
+ authenticateJWT: RequestHandler;
+ statsServerUrl: string;
+};
+
+export function registerHostFolderRoutes(
+ router: Router,
+ { authenticateJWT, statsServerUrl }: HostFolderRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /host/folders/rename:
+ * put:
+ * summary: Rename folder
+ * description: Renames a folder for SSH hosts and credentials.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * oldName:
+ * type: string
+ * newName:
+ * type: string
+ * responses:
+ * 200:
+ * description: Folder renamed successfully.
+ * 400:
+ * description: Old name and new name are required.
+ * 500:
+ * description: Failed to rename folder.
+ */
+ router.put(
+ "/folders/rename",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { oldName, newName } = req.body;
+
+ if (!isNonEmptyString(userId) || !oldName || !newName) {
+ sshLogger.warn("Invalid data for folder rename");
+ return res
+ .status(400)
+ .json({ error: "Old name and new name are required" });
+ }
+
+ if (oldName === newName) {
+ return res.json({ message: "Folder name unchanged" });
+ }
+
+ try {
+ const updatedHosts = await SimpleDBOps.update(
+ hosts,
+ "ssh_data",
+ and(eq(hosts.userId, userId), eq(hosts.folder, oldName)),
+ {
+ folder: newName,
+ updatedAt: new Date().toISOString(),
+ },
+ userId,
+ );
+
+ const updatedCredentials = await db
+ .update(sshCredentials)
+ .set({
+ folder: newName,
+ updatedAt: new Date().toISOString(),
+ })
+ .where(
+ and(
+ eq(sshCredentials.userId, userId),
+ eq(sshCredentials.folder, oldName),
+ ),
+ )
+ .returning();
+
+ DatabaseSaveTrigger.triggerSave("folder_rename");
+
+ await db
+ .update(sshFolders)
+ .set({
+ name: newName,
+ updatedAt: new Date().toISOString(),
+ })
+ .where(
+ and(eq(sshFolders.userId, userId), eq(sshFolders.name, oldName)),
+ );
+
+ res.json({
+ message: "Folder renamed successfully",
+ updatedHosts: updatedHosts.length,
+ updatedCredentials: updatedCredentials.length,
+ });
+ } catch (err) {
+ sshLogger.error("Failed to rename folder", err, {
+ operation: "folder_rename",
+ userId,
+ oldName,
+ newName,
+ });
+ res.status(500).json({ error: "Failed to rename folder" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/folders:
+ * get:
+ * summary: Get all folders
+ * description: Retrieves all folders for the authenticated user.
+ * tags:
+ * - SSH
+ * responses:
+ * 200:
+ * description: A list of folders.
+ * 400:
+ * description: Invalid user ID.
+ * 500:
+ * description: Failed to fetch folders.
+ */
+ router.get(
+ "/folders",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!isNonEmptyString(userId)) {
+ return res.status(400).json({ error: "Invalid user ID" });
+ }
+
+ try {
+ const folders = await db
+ .select()
+ .from(sshFolders)
+ .where(eq(sshFolders.userId, userId));
+
+ res.json(folders);
+ } catch (err) {
+ sshLogger.error("Failed to fetch folders", err, {
+ operation: "fetch_folders",
+ userId,
+ });
+ res.status(500).json({ error: "Failed to fetch folders" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/folders/metadata:
+ * put:
+ * summary: Update folder metadata
+ * description: Updates the metadata (color, icon) of a folder.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * name:
+ * type: string
+ * color:
+ * type: string
+ * icon:
+ * type: string
+ * responses:
+ * 200:
+ * description: Folder metadata updated successfully.
+ * 400:
+ * description: Folder name is required.
+ * 500:
+ * description: Failed to update folder metadata.
+ */
+ router.put(
+ "/folders/metadata",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { name, color, icon } = req.body;
+
+ if (!isNonEmptyString(userId) || !name) {
+ return res.status(400).json({ error: "Folder name is required" });
+ }
+
+ try {
+ const existing = await db
+ .select()
+ .from(sshFolders)
+ .where(and(eq(sshFolders.userId, userId), eq(sshFolders.name, name)))
+ .limit(1);
+
+ if (existing.length > 0) {
+ databaseLogger.info("Updating SSH folder", {
+ operation: "folder_update",
+ userId,
+ folderId: existing[0].id,
+ });
+ await db
+ .update(sshFolders)
+ .set({
+ color,
+ icon,
+ updatedAt: new Date().toISOString(),
+ })
+ .where(
+ and(eq(sshFolders.userId, userId), eq(sshFolders.name, name)),
+ );
+ } else {
+ databaseLogger.info("Creating SSH folder", {
+ operation: "folder_create",
+ userId,
+ name,
+ });
+ await db.insert(sshFolders).values({
+ userId,
+ name,
+ color,
+ icon,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ });
+ }
+
+ DatabaseSaveTrigger.triggerSave("folder_metadata_update");
+
+ res.json({ message: "Folder metadata updated successfully" });
+ } catch (err) {
+ sshLogger.error("Failed to update folder metadata", err, {
+ operation: "update_folder_metadata",
+ userId,
+ name,
+ });
+ res.status(500).json({ error: "Failed to update folder metadata" });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/folders/{name}/hosts:
+ * delete:
+ * summary: Delete all hosts in folder
+ * description: Deletes all SSH hosts within a specific folder.
+ * tags:
+ * - SSH
+ * parameters:
+ * - in: path
+ * name: name
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: Hosts deleted successfully.
+ * 400:
+ * description: Invalid folder name.
+ * 500:
+ * description: Failed to delete hosts in folder.
+ */
+ router.delete(
+ "/folders/:name/hosts",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const folderName = Array.isArray(req.params.name)
+ ? req.params.name[0]
+ : req.params.name;
+
+ if (!isNonEmptyString(userId) || !folderName) {
+ return res.status(400).json({ error: "Invalid folder name" });
+ }
+ databaseLogger.info("Deleting SSH folder", {
+ operation: "folder_delete",
+ userId,
+ folderId: folderName,
+ });
+
+ try {
+ const hostsToDelete = await db
+ .select()
+ .from(hosts)
+ .where(and(eq(hosts.userId, userId), eq(hosts.folder, folderName)));
+
+ if (hostsToDelete.length === 0) {
+ return res.json({
+ message: "No hosts found in folder",
+ deletedCount: 0,
+ });
+ }
+
+ const hostIds = hostsToDelete.map((host) => host.id);
+
+ if (hostIds.length > 0) {
+ await db
+ .delete(fileManagerRecent)
+ .where(inArray(fileManagerRecent.hostId, hostIds));
+
+ await db
+ .delete(fileManagerPinned)
+ .where(inArray(fileManagerPinned.hostId, hostIds));
+
+ await db
+ .delete(fileManagerShortcuts)
+ .where(inArray(fileManagerShortcuts.hostId, hostIds));
+
+ await db
+ .delete(transferRecent)
+ .where(
+ or(
+ inArray(transferRecent.sourceHostId, hostIds),
+ inArray(transferRecent.destHostId, hostIds),
+ ),
+ );
+
+ await db
+ .delete(commandHistory)
+ .where(inArray(commandHistory.hostId, hostIds));
+
+ await db
+ .delete(sshCredentialUsage)
+ .where(inArray(sshCredentialUsage.hostId, hostIds));
+
+ await db
+ .delete(recentActivity)
+ .where(inArray(recentActivity.hostId, hostIds));
+
+ await db
+ .delete(hostAccess)
+ .where(inArray(hostAccess.hostId, hostIds));
+
+ await db
+ .delete(sessionRecordings)
+ .where(inArray(sessionRecordings.hostId, hostIds));
+ }
+
+ await db
+ .delete(hosts)
+ .where(and(eq(hosts.userId, userId), eq(hosts.folder, folderName)));
+
+ await db
+ .delete(sshFolders)
+ .where(
+ and(eq(sshFolders.userId, userId), eq(sshFolders.name, folderName)),
+ );
+
+ DatabaseSaveTrigger.triggerSave("folder_hosts_delete");
+
+ try {
+ const axios = (await import("axios")).default;
+ for (const host of hostsToDelete) {
+ try {
+ await axios.post(
+ `${statsServerUrl}/host-deleted`,
+ { hostId: host.id },
+ {
+ headers: {
+ Authorization: req.headers.authorization || "",
+ Cookie: req.headers.cookie || "",
+ },
+ timeout: 5000,
+ },
+ );
+ } catch (err) {
+ sshLogger.warn("Failed to notify stats server of host deletion", {
+ operation: "folder_hosts_delete",
+ hostId: host.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ } catch (err) {
+ sshLogger.warn("Failed to notify stats server of folder deletion", {
+ operation: "folder_hosts_delete",
+ folderName,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+
+ res.json({
+ message: "All hosts in folder deleted successfully",
+ deletedCount: hostsToDelete.length,
+ });
+ } catch (err) {
+ sshLogger.error("Failed to delete hosts in folder", err, {
+ operation: "delete_folder_hosts",
+ userId,
+ folderName,
+ });
+ res.status(500).json({ error: "Failed to delete hosts in folder" });
+ }
+ },
+ );
+}
diff --git a/src/backend/database/routes/host-internal-routes.ts b/src/backend/database/routes/host-internal-routes.ts
new file mode 100644
index 000000000..3bafed6a7
--- /dev/null
+++ b/src/backend/database/routes/host-internal-routes.ts
@@ -0,0 +1,176 @@
+import type { Request, Response, Router } from "express";
+import { and, eq, isNotNull } from "drizzle-orm";
+import { SystemCrypto } from "../../utils/system-crypto.js";
+import { sshLogger } from "../../utils/logger.js";
+import { db } from "../db/index.js";
+import { hosts } from "../db/schema.js";
+
+export function registerHostInternalRoutes(router: Router): void {
+ /**
+ * @openapi
+ * /host/db/host/internal:
+ * get:
+ * summary: Get internal SSH host data
+ * description: Returns internal SSH host data for autostart tunnels. Requires internal auth token.
+ * tags:
+ * - SSH
+ * responses:
+ * 200:
+ * description: A list of autostart hosts.
+ * 403:
+ * description: Forbidden.
+ * 500:
+ * description: Failed to fetch autostart SSH data.
+ */
+ router.get("/db/host/internal", async (req: Request, res: Response) => {
+ try {
+ const internalToken = req.headers["x-internal-auth-token"];
+ const systemCrypto = SystemCrypto.getInstance();
+ const expectedToken = await systemCrypto.getInternalAuthToken();
+
+ if (internalToken !== expectedToken) {
+ sshLogger.warn(
+ "Unauthorized attempt to access internal SSH host endpoint",
+ {
+ source: req.ip,
+ userAgent: req.headers["user-agent"],
+ providedToken: internalToken ? "present" : "missing",
+ },
+ );
+ return res.status(403).json({ error: "Forbidden" });
+ }
+ } catch (error) {
+ sshLogger.error("Failed to validate internal auth token", error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+
+ try {
+ const autostartHosts = await db
+ .select()
+ .from(hosts)
+ .where(
+ and(eq(hosts.enableTunnel, true), isNotNull(hosts.tunnelConnections)),
+ );
+
+ const result = autostartHosts
+ .map((host) => {
+ const tunnelConnections = host.tunnelConnections
+ ? JSON.parse(host.tunnelConnections)
+ : [];
+
+ const hasAutoStartTunnels = tunnelConnections.some(
+ (tunnel: Record<string, unknown>) => tunnel.autoStart,
+ );
+
+ if (!hasAutoStartTunnels) {
+ return null;
+ }
+
+ return {
+ id: host.id,
+ userId: host.userId,
+ name: host.name || `autostart-${host.id}`,
+ ip: host.ip,
+ port: host.port,
+ username: host.username,
+ authType: host.authType,
+ keyType: host.keyType,
+ credentialId: host.credentialId,
+ enableTunnel: true,
+ tunnelConnections: tunnelConnections.filter(
+ (tunnel: Record<string, unknown>) => tunnel.autoStart,
+ ),
+ pin: !!host.pin,
+ enableTerminal: !!host.enableTerminal,
+ enableFileManager: !!host.enableFileManager,
+ showTerminalInSidebar: !!host.showTerminalInSidebar,
+ showFileManagerInSidebar: !!host.showFileManagerInSidebar,
+ showTunnelInSidebar: !!host.showTunnelInSidebar,
+ showDockerInSidebar: !!host.showDockerInSidebar,
+ showServerStatsInSidebar: !!host.showServerStatsInSidebar,
+ tags: ["autostart"],
+ };
+ })
+ .filter(Boolean);
+
+ res.json(result);
+ } catch (err) {
+ sshLogger.error("Failed to fetch autostart SSH data", err);
+ res.status(500).json({ error: "Failed to fetch autostart SSH data" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /host/db/host/internal/all:
+ * get:
+ * summary: Get all internal SSH host data
+ * description: Returns all internal SSH host data. Requires internal auth token.
+ * tags:
+ * - SSH
+ * responses:
+ * 200:
+ * description: A list of all hosts.
+ * 401:
+ * description: Invalid or missing internal authentication token.
+ * 500:
+ * description: Failed to fetch all hosts.
+ */
+ router.get("/db/host/internal/all", async (req: Request, res: Response) => {
+ try {
+ const internalToken = req.headers["x-internal-auth-token"];
+ if (!internalToken) {
+ return res
+ .status(401)
+ .json({ error: "Internal authentication token required" });
+ }
+
+ const systemCrypto = SystemCrypto.getInstance();
+ const expectedToken = await systemCrypto.getInternalAuthToken();
+
+ if (internalToken !== expectedToken) {
+ return res
+ .status(401)
+ .json({ error: "Invalid internal authentication token" });
+ }
+
+ const allHosts = await db.select().from(hosts);
+
+ const result = allHosts.map((host) => {
+ const tunnelConnections = host.tunnelConnections
+ ? JSON.parse(host.tunnelConnections)
+ : [];
+
+ return {
+ id: host.id,
+ userId: host.userId,
+ name: host.name || `${host.username}@${host.ip}`,
+ ip: host.ip,
+ port: host.port,
+ username: host.username,
+ authType: host.authType,
+ keyType: host.keyType,
+ credentialId: host.credentialId,
+ enableTunnel: !!host.enableTunnel,
+ tunnelConnections: tunnelConnections,
+ pin: !!host.pin,
+ enableTerminal: !!host.enableTerminal,
+ enableFileManager: !!host.enableFileManager,
+ showTerminalInSidebar: !!host.showTerminalInSidebar,
+ showFileManagerInSidebar: !!host.showFileManagerInSidebar,
+ showTunnelInSidebar: !!host.showTunnelInSidebar,
+ showDockerInSidebar: !!host.showDockerInSidebar,
+ showServerStatsInSidebar: !!host.showServerStatsInSidebar,
+ defaultPath: host.defaultPath,
+ createdAt: host.createdAt,
+ updatedAt: host.updatedAt,
+ };
+ });
+
+ res.json(result);
+ } catch (err) {
+ sshLogger.error("Failed to fetch all hosts for internal use", err);
+ res.status(500).json({ error: "Failed to fetch all hosts" });
+ }
+ });
+}
diff --git a/src/backend/database/routes/host-network-routes.ts b/src/backend/database/routes/host-network-routes.ts
new file mode 100644
index 000000000..1d98591e9
--- /dev/null
+++ b/src/backend/database/routes/host-network-routes.ts
@@ -0,0 +1,143 @@
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import type { Request, RequestHandler, Response, Router } from "express";
+import { and, eq } from "drizzle-orm";
+import { sendWakeOnLan, isValidMac } from "../../utils/wake-on-lan.js";
+import { sshLogger } from "../../utils/logger.js";
+import { db } from "../db/index.js";
+import { hosts } from "../db/schema.js";
+
+interface HostNetworkRoutesDeps {
+ authenticateJWT: RequestHandler;
+ requireDataAccess: RequestHandler;
+}
+
+export function registerHostNetworkRoutes(
+ router: Router,
+ { authenticateJWT, requireDataAccess }: HostNetworkRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /host/db/proxy/test:
+ * post:
+ * summary: Test proxy connectivity
+ * description: Tests connectivity through a proxy configuration to a target host.
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * singleProxy:
+ * type: object
+ * properties:
+ * host:
+ * type: string
+ * port:
+ * type: number
+ * type:
+ * type: string
+ * username:
+ * type: string
+ * password:
+ * type: string
+ * proxyChain:
+ * type: array
+ * items:
+ * type: object
+ * testTarget:
+ * type: object
+ * properties:
+ * host:
+ * type: string
+ * port:
+ * type: number
+ * responses:
+ * 200:
+ * description: Test result
+ * 500:
+ * description: Proxy connection failed
+ */
+ router.post(
+ "/db/proxy/test",
+ authenticateJWT,
+ requireDataAccess,
+ async (req: AuthenticatedRequest, res: Response) => {
+ try {
+ const { singleProxy, proxyChain, testTarget } = req.body;
+
+ const { testProxyConnectivity } =
+ await import("../../utils/proxy-helper.js");
+
+ const result = await testProxyConnectivity({
+ singleProxy,
+ proxyChain,
+ testTarget,
+ });
+
+ res.json(result);
+ } catch (error) {
+ sshLogger.error("Proxy connectivity test failed", error, {
+ operation: "proxy_test",
+ userId: req.userId,
+ });
+ res.status(500).json({
+ success: false,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+ },
+ );
+
+ router.post(
+ "/db/host/:id/wake",
+ authenticateJWT,
+ requireDataAccess,
+ async (req: Request, res: Response) => {
+ const hostId = Number.parseInt(String(req.params.id), 10);
+ const userId = (req as AuthenticatedRequest).userId;
+
+ try {
+ const host = await db
+ .select({ macAddress: hosts.macAddress })
+ .from(hosts)
+ .where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
+ .then((rows) => rows[0]);
+
+ if (!host) {
+ return res.status(404).json({ error: "Host not found" });
+ }
+
+ if (!host.macAddress || !isValidMac(host.macAddress)) {
+ return res
+ .status(400)
+ .json({ error: "No valid MAC address configured" });
+ }
+
+ await sendWakeOnLan(host.macAddress);
+
+ sshLogger.info("Wake-on-LAN packet sent", {
+ operation: "wake_on_lan",
+ userId,
+ hostId,
+ });
+
+ res.json({ success: true });
+ } catch (error) {
+ sshLogger.error("Wake-on-LAN failed", error, {
+ operation: "wake_on_lan",
+ userId,
+ hostId,
+ });
+ res.status(500).json({
+ error:
+ error instanceof Error
+ ? error.message
+ : "Failed to send WoL packet",
+ });
+ }
+ },
+ );
+}
diff --git a/src/backend/database/routes/host-normalizers.test.ts b/src/backend/database/routes/host-normalizers.test.ts
new file mode 100644
index 000000000..4bae8a2f2
--- /dev/null
+++ b/src/backend/database/routes/host-normalizers.test.ts
@@ -0,0 +1,156 @@
+import { describe, it, expect } from "vitest";
+import {
+ isNonEmptyString,
+ isValidPort,
+ normalizeImportedHost,
+ stripSensitiveFields,
+ transformHostResponse,
+} from "./host-normalizers.js";
+
+describe("isNonEmptyString", () => {
+ it("accepts non-blank strings", () => {
+ expect(isNonEmptyString("hello")).toBe(true);
+ expect(isNonEmptyString(" x ")).toBe(true);
+ });
+
+ it("rejects blank strings and non-strings", () => {
+ expect(isNonEmptyString("")).toBe(false);
+ expect(isNonEmptyString(" ")).toBe(false);
+ expect(isNonEmptyString(123)).toBe(false);
+ expect(isNonEmptyString(null)).toBe(false);
+ expect(isNonEmptyString(undefined)).toBe(false);
+ });
+});
+
+describe("isValidPort", () => {
+ it("accepts ports in range", () => {
+ expect(isValidPort(1)).toBe(true);
+ expect(isValidPort(22)).toBe(true);
+ expect(isValidPort(65535)).toBe(true);
+ });
+
+ it("rejects out-of-range or non-number ports", () => {
+ expect(isValidPort(0)).toBe(false);
+ expect(isValidPort(65536)).toBe(false);
+ expect(isValidPort(-1)).toBe(false);
+ expect(isValidPort("22")).toBe(false);
+ });
+});
+
+describe("normalizeImportedHost", () => {
+ it("defaults connectionType to ssh with port 22", () => {
+ const host = normalizeImportedHost({ ip: "10.0.0.1" });
+ expect(host.connectionType).toBe("ssh");
+ expect(host.port).toBe(22);
+ expect(host.enableSsh).toBe(true);
+ expect(host.enableRdp).toBe(false);
+ });
+
+ it("infers rdp from enableRdp and uses default rdp port", () => {
+ const host = normalizeImportedHost({ enableRdp: true, ip: "10.0.0.2" });
+ expect(host.connectionType).toBe("rdp");
+ expect(host.port).toBe(3389);
+ expect(host.enableRdp).toBe(true);
+ });
+
+ it("honors an explicit port over protocol defaults", () => {
+ const host = normalizeImportedHost({
+ connectionType: "ssh",
+ port: 2222,
+ });
+ expect(host.port).toBe(2222);
+ });
+
+ it("resolves ip from common aliases", () => {
+ expect(normalizeImportedHost({ address: "a.example" }).ip).toBe(
+ "a.example",
+ );
+ expect(normalizeImportedHost({ hostname: "h.example" }).ip).toBe(
+ "h.example",
+ );
+ });
+
+ it("normalizes tags from a comma string", () => {
+ const host = normalizeImportedHost({ tags: "prod, db , , web" });
+ expect(host.tags).toEqual(["prod", "db", "web"]);
+ });
+
+ it("normalizes tags from an array", () => {
+ const host = normalizeImportedHost({ tags: ["a", " b ", "", "c"] });
+ expect(host.tags).toEqual(["a", "b", "c"]);
+ });
+
+ it("infers authType credential when credentialId present", () => {
+ const host = normalizeImportedHost({ credentialId: 7 });
+ expect(host.credentialId).toBe(7);
+ expect(host.authType).toBe("credential");
+ });
+});
+
+describe("stripSensitiveFields", () => {
+ it("removes secret fields and adds boolean presence flags", () => {
+ const result = stripSensitiveFields({
+ name: "web",
+ password: "secret",
+ key: "PRIVATE KEY",
+ keyPassword: "kp",
+ sudoPassword: "sp",
+ });
+ expect(result.password).toBeUndefined();
+ expect(result.key).toBeUndefined();
+ expect(result.keyPassword).toBeUndefined();
+ expect(result.sudoPassword).toBeUndefined();
+ expect(result.hasPassword).toBe(true);
+ expect(result.hasKey).toBe(true);
+ expect(result.hasKeyPassword).toBe(true);
+ expect(result.hasSudoPassword).toBe(true);
+ expect(result.name).toBe("web");
+ });
+
+ it("marks presence flags false when secrets are absent", () => {
+ const result = stripSensitiveFields({ name: "web" });
+ expect(result.hasPassword).toBe(false);
+ expect(result.hasKey).toBe(false);
+ });
+});
+
+describe("transformHostResponse", () => {
+ it("parses tags and coerces enable flags to booleans", () => {
+ const result = transformHostResponse({
+ tags: "a,b,c",
+ enableTerminal: 1,
+ enableTunnel: 0,
+ pin: 1,
+ });
+ expect(result.tags).toEqual(["a", "b", "c"]);
+ expect(result.enableTerminal).toBe(true);
+ expect(result.enableTunnel).toBe(false);
+ expect(result.pin).toBe(true);
+ });
+
+ it("parses JSON array fields and defaults them to []", () => {
+ const result = transformHostResponse({
+ tunnelConnections: '[{"sourcePort":8080}]',
+ jumpHosts: null,
+ });
+ expect(result.tunnelConnections).toEqual([{ sourcePort: 8080 }]);
+ expect(result.jumpHosts).toEqual([]);
+ });
+
+ it("infers protocol flags for a migrated non-ssh host", () => {
+ const result = transformHostResponse({
+ connectionType: "rdp",
+ enableSsh: true,
+ });
+ expect(result.enableSsh).toBe(false);
+ expect(result.enableRdp).toBe(true);
+ });
+
+ it("applies default protocol ports", () => {
+ const result = transformHostResponse({ port: 22 });
+ expect(result.sshPort).toBe(22);
+ expect(result.rdpPort).toBe(3389);
+ expect(result.vncPort).toBe(5900);
+ expect(result.telnetPort).toBe(23);
+ });
+});
diff --git a/src/backend/database/routes/host-normalizers.ts b/src/backend/database/routes/host-normalizers.ts
new file mode 100644
index 000000000..bc2490cf3
--- /dev/null
+++ b/src/backend/database/routes/host-normalizers.ts
@@ -0,0 +1,281 @@
+export function isNonEmptyString(value: unknown): value is string {
+ return typeof value === "string" && value.trim().length > 0;
+}
+
+export function isValidPort(port: unknown): port is number {
+ return typeof port === "number" && port > 0 && port <= 65535;
+}
+
+function asString(value: unknown): string | undefined {
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
+}
+
+function asPort(value: unknown): number | undefined {
+ const port =
+ typeof value === "number"
+ ? value
+ : typeof value === "string"
+ ? Number.parseInt(value, 10)
+ : NaN;
+
+ return isValidPort(port) ? port : undefined;
+}
+
+function asInteger(value: unknown): number | undefined {
+ const number =
+ typeof value === "number"
+ ? value
+ : typeof value === "string"
+ ? Number.parseInt(value, 10)
+ : NaN;
+
+ return Number.isInteger(number) ? number : undefined;
+}
+
+function asBoolean(value: unknown, fallback = false): boolean {
+ if (typeof value === "boolean") return value;
+ if (typeof value === "number") return value !== 0;
+ if (typeof value === "string") {
+ const normalized = value.trim().toLowerCase();
+ if (["true", "1", "yes", "on"].includes(normalized)) return true;
+ if (["false", "0", "no", "off"].includes(normalized)) return false;
+ }
+
+ return fallback;
+}
+
+function normalizeImportTags(value: unknown): string[] {
+ if (Array.isArray(value)) {
+ return value
+ .map((tag) => asString(tag))
+ .filter((tag): tag is string => !!tag);
+ }
+ if (typeof value === "string") {
+ return value
+ .split(",")
+ .map((tag) => tag.trim())
+ .filter(Boolean);
+ }
+
+ return [];
+}
+
+export type NormalizedImportedHost = Record<string, unknown> & {
+ connectionType: string;
+ name?: string;
+ ip?: string;
+ port: number;
+ username?: string;
+ folder?: string;
+ tags: string[];
+ authType?: string;
+ password?: string;
+ key?: string;
+ keyPassword?: string;
+ keyType?: string;
+ credentialId?: number;
+ pin?: unknown;
+ enableTerminal?: unknown;
+ enableTunnel?: unknown;
+ enableFileManager?: unknown;
+ enableDocker?: unknown;
+ showTerminalInSidebar?: unknown;
+ showFileManagerInSidebar?: unknown;
+ showTunnelInSidebar?: unknown;
+ showDockerInSidebar?: unknown;
+ showServerStatsInSidebar?: unknown;
+ defaultPath?: unknown;
+ sudoPassword?: unknown;
+ tunnelConnections?: unknown;
+ jumpHosts?: unknown;
+ quickActions?: unknown;
+ statsConfig?: unknown;
+ dockerConfig?: unknown;
+ terminalConfig?: unknown;
+ forceKeyboardInteractive?: unknown;
+ notes?: unknown;
+ useSocks5?: unknown;
+ socks5Host?: unknown;
+ socks5Port?: unknown;
+ socks5Username?: unknown;
+ socks5Password?: unknown;
+ socks5ProxyChain?: unknown;
+ portKnockSequence?: unknown;
+ overrideCredentialUsername?: unknown;
+ domain?: unknown;
+ security?: unknown;
+ ignoreCert?: unknown;
+ guacamoleConfig?: unknown;
+ enableSsh: boolean;
+ enableRdp: boolean;
+ enableVnc: boolean;
+ enableTelnet: boolean;
+};
+
+export function normalizeImportedHost(
+ hostData: Record<string, unknown>,
+): NormalizedImportedHost {
+ const connectionType =
+ asString(hostData.connectionType) ||
+ (asBoolean(hostData.enableRdp)
+ ? "rdp"
+ : asBoolean(hostData.enableVnc)
+ ? "vnc"
+ : asBoolean(hostData.enableTelnet)
+ ? "telnet"
+ : "ssh");
+
+ const port =
+ asPort(hostData.port) ||
+ (connectionType === "rdp"
+ ? asPort(hostData.rdpPort) || 3389
+ : connectionType === "vnc"
+ ? asPort(hostData.vncPort) || 5900
+ : connectionType === "telnet"
+ ? asPort(hostData.telnetPort) || 23
+ : asPort(hostData.sshPort) || 22);
+
+ return {
+ ...hostData,
+ connectionType,
+ name: asString(hostData.name) || asString(hostData.label),
+ ip:
+ asString(hostData.ip) ||
+ asString(hostData.address) ||
+ asString(hostData.host) ||
+ asString(hostData.hostname),
+ port,
+ username: asString(hostData.username) || asString(hostData.user),
+ folder: asString(hostData.folder) || asString(hostData.group),
+ tags: normalizeImportTags(hostData.tags),
+ credentialId: asInteger(hostData.credentialId),
+ authType:
+ asString(hostData.authType) ||
+ asString(hostData.authMethod) ||
+ (hostData.credentialId ? "credential" : hostData.key ? "key" : undefined),
+ enableSsh:
+ hostData.enableSsh === undefined
+ ? connectionType === "ssh"
+ : asBoolean(hostData.enableSsh),
+ enableRdp:
+ hostData.enableRdp === undefined
+ ? connectionType === "rdp"
+ : asBoolean(hostData.enableRdp),
+ enableVnc:
+ hostData.enableVnc === undefined
+ ? connectionType === "vnc"
+ : asBoolean(hostData.enableVnc),
+ enableTelnet:
+ hostData.enableTelnet === undefined
+ ? connectionType === "telnet"
+ : asBoolean(hostData.enableTelnet),
+ };
+}
+
+const SENSITIVE_FIELDS = [
+ "key",
+ "keyPassword",
+ "autostartKey",
+ "autostartKeyPassword",
+ "password",
+ "sudoPassword",
+ "socks5Password",
+ "rdpPassword",
+ "vncPassword",
+ "telnetPassword",
+ "autostartPassword",
+];
+
+export function stripSensitiveFields(
+ host: Record<string, unknown>,
+): Record<string, unknown> {
+ const result = { ...host };
+ result.hasKey = !!host.key;
+ result.hasKeyPassword = !!host.keyPassword;
+ result.hasPassword = !!host.password;
+ result.hasSudoPassword = !!host.sudoPassword;
+ for (const field of SENSITIVE_FIELDS) {
+ delete result[field];
+ }
+ return result;
+}
+
+export function transformHostResponse(
+ host: Record<string, unknown>,
+): Record<string, unknown> {
+ return {
+ ...host,
+ tags:
+ typeof host.tags === "string"
+ ? host.tags
+ ? host.tags.split(",").filter(Boolean)
+ : []
+ : [],
+ pin: !!host.pin,
+ enableTerminal: !!host.enableTerminal,
+ enableTunnel: !!host.enableTunnel,
+ enableFileManager: !!host.enableFileManager,
+ enableDocker: !!host.enableDocker,
+ showTerminalInSidebar: !!host.showTerminalInSidebar,
+ showFileManagerInSidebar: !!host.showFileManagerInSidebar,
+ showTunnelInSidebar: !!host.showTunnelInSidebar,
+ showDockerInSidebar: !!host.showDockerInSidebar,
+ showServerStatsInSidebar: !!host.showServerStatsInSidebar,
+ // Old hosts only had connection_type set; the per-protocol enable flags didn't exist yet.
+ // The schema defaults (enableSsh=true, others=false) wrongly mark every old host as SSH.
+ // Detect this migration case: if no non-SSH protocol is explicitly enabled AND
+ // connectionType is set to a non-SSH value, fall back to inferring from connectionType.
+ ...(() => {
+ const ct = host.connectionType;
+ const rdp = !!host.enableRdp;
+ const vnc = !!host.enableVnc;
+ const tel = !!host.enableTelnet;
+ const isMigratedNonSsh = !rdp && !vnc && !tel && ct && ct !== "ssh";
+ return {
+ enableSsh: isMigratedNonSsh ? false : !!host.enableSsh,
+ enableRdp: isMigratedNonSsh ? ct === "rdp" : rdp,
+ enableVnc: isMigratedNonSsh ? ct === "vnc" : vnc,
+ enableTelnet: isMigratedNonSsh ? ct === "telnet" : tel,
+ };
+ })(),
+ sshPort: host.sshPort ?? host.port ?? 22,
+ rdpPort: host.rdpPort ?? 3389,
+ vncPort: host.vncPort ?? 5900,
+ telnetPort: host.telnetPort ?? 23,
+ rdpUser: host.rdpUser || undefined,
+ rdpDomain: host.rdpDomain || undefined,
+ rdpSecurity: host.rdpSecurity || undefined,
+ rdpIgnoreCert: !!host.rdpIgnoreCert,
+ vncUser: host.vncUser || undefined,
+ telnetUser: host.telnetUser || undefined,
+ tunnelConnections: host.tunnelConnections
+ ? JSON.parse(host.tunnelConnections as string)
+ : [],
+ jumpHosts: host.jumpHosts ? JSON.parse(host.jumpHosts as string) : [],
+ quickActions: host.quickActions
+ ? JSON.parse(host.quickActions as string)
+ : [],
+ statsConfig: host.statsConfig
+ ? JSON.parse(host.statsConfig as string)
+ : undefined,
+ terminalConfig: host.terminalConfig
+ ? JSON.parse(host.terminalConfig as string)
+ : undefined,
+ dockerConfig: host.dockerConfig
+ ? JSON.parse(host.dockerConfig as string)
+ : undefined,
+ forceKeyboardInteractive: host.forceKeyboardInteractive === "true",
+ socks5ProxyChain: host.socks5ProxyChain
+ ? JSON.parse(host.socks5ProxyChain as string)
+ : [],
+ portKnockSequence: host.portKnockSequence
+ ? JSON.parse(host.portKnockSequence as string)
+ : [],
+ domain: host.domain || undefined,
+ security: host.security || undefined,
+ ignoreCert: !!host.ignoreCert,
+ guacamoleConfig: host.guacamoleConfig
+ ? JSON.parse(host.guacamoleConfig as string)
+ : undefined,
+ };
+}
diff --git a/src/backend/database/routes/host-opkssh-routes.ts b/src/backend/database/routes/host-opkssh-routes.ts
new file mode 100644
index 000000000..75ab5346b
--- /dev/null
+++ b/src/backend/database/routes/host-opkssh-routes.ts
@@ -0,0 +1,841 @@
+import type { Router, Request, Response } from "express";
+import { sshLogger } from "../../utils/logger.js";
+import {
+ normalizeSelectOpParam,
+ renderOpksshErrorPage,
+ rewriteOPKSSHHtml,
+} from "./opkssh-html.js";
+
+export function registerHostOpksshRoutes(router: Router): void {
+ /**
+ * @openapi
+ * /host/opkssh-chooser/{requestId}:
+ * get:
+ * summary: Proxy OPKSSH provider chooser page and all related resources
+ * tags: [SSH]
+ * parameters:
+ * - name: requestId
+ * in: path
+ * required: true
+ * schema:
+ * type: string
+ * description: Authentication request ID
+ * responses:
+ * 200:
+ * description: Chooser page content
+ * 404:
+ * description: Session not found
+ * 500:
+ * description: Proxy error
+ */
+
+ router.use(
+ "/opkssh-chooser/:requestId",
+ async (req: Request, res: Response) => {
+ const requestId = Array.isArray(req.params.requestId)
+ ? req.params.requestId[0]
+ : req.params.requestId;
+
+ const fullPath = req.originalUrl || req.url;
+ const pathAfterRequestIdTemp =
+ fullPath.split(`/host/opkssh-chooser/${requestId}`)[1] || "";
+
+ sshLogger.info("OPKSSH chooser proxy request", {
+ operation: "opkssh_chooser_proxy_request",
+ requestId,
+ url: req.url,
+ originalUrl: req.originalUrl,
+ fullPath,
+ pathAfterRequestId: pathAfterRequestIdTemp,
+ method: req.method,
+ });
+
+ try {
+ const { getActiveAuthSession, registerOAuthState } =
+ await import("../../ssh/opkssh-auth.js");
+ const session = getActiveAuthSession(requestId);
+
+ if (!session) {
+ sshLogger.error("Session not found for chooser request", {
+ operation: "opkssh_chooser_session_not_found",
+ requestId,
+ });
+ res.status(404).send(
+ renderOpksshErrorPage({
+ title: "Session Not Found",
+ heading: "Session Not Found",
+ message: "This authentication session has expired or is invalid.",
+ requestId,
+ }),
+ );
+ return;
+ }
+
+ const axios = (await import("axios")).default;
+
+ const fullPath = req.originalUrl || req.url;
+ const pathAfterRequestId =
+ fullPath.split(`/host/opkssh-chooser/${requestId}`)[1] || "";
+ const targetPath = pathAfterRequestId || "/chooser";
+
+ if (!session.localPort || session.localPort === 0) {
+ sshLogger.error("OPKSSH session has no local port", {
+ operation: "opkssh_chooser_proxy",
+ requestId,
+ sessionStatus: session.status,
+ });
+ res.status(500).send(
+ renderOpksshErrorPage({
+ title: "Error",
+ heading: "Authentication Error",
+ message:
+ "Failed to load authentication page. OPKSSH process may not be ready yet. Please try again.",
+ requestId,
+ }),
+ );
+ return;
+ }
+
+ // /select on OPKSSH's chooser redirects (possibly via multiple local hops) to the
+ // external OAuth provider URL. The hops we may see:
+ // 1. /select -> /select/ (Go ServeMux canonicalization, same chooser port)
+ // 2. /select/?op=ALIAS -> http://localhost:CALLBACK_PORT/login (OPKSSH's separate callback listener)
+ // 3. /login on the callback listener -> https://<provider>/authorize?... (external OAuth URL)
+ if (targetPath.startsWith("/select")) {
+ const selectaxios = (await import("axios")).default;
+ const rawQs = targetPath.includes("?")
+ ? targetPath.slice(targetPath.indexOf("?"))
+ : "";
+
+ let qs = rawQs;
+ let opMappedFrom: string | undefined;
+ if (rawQs) {
+ try {
+ const params = new URLSearchParams(rawQs.replace(/^\?/, ""));
+ const rawOp = params.get("op");
+ if (rawOp) {
+ const mappedOp = normalizeSelectOpParam(
+ rawOp,
+ session.providers || [],
+ );
+ if (mappedOp !== rawOp) {
+ params.set("op", mappedOp);
+ qs = `?${params.toString()}`;
+ opMappedFrom = rawOp;
+ }
+ }
+ } catch {
+ /* keep rawQs if parsing fails */
+ }
+ }
+
+ const chooserHost = `127.0.0.1:${session.localPort}`;
+ const startUrl = `http://${chooserHost}/select/${qs}`;
+
+ sshLogger.info("Proxying OPKSSH /select", {
+ operation: "opkssh_select_proxy",
+ requestId,
+ targetUrl: startUrl,
+ opMappedFrom,
+ });
+
+ const isLocalHostname = (host: string): boolean => {
+ const bare = host.split(":")[0];
+ return (
+ bare === "127.0.0.1" || bare === "localhost" || bare === "[::1]"
+ );
+ };
+
+ interface UpstreamResponse {
+ status: number;
+ location?: string;
+ contentType: string;
+ body: string;
+ targetUrl: string;
+ elapsedMs: number;
+ }
+
+ const fetchUpstream = async (
+ url: string,
+ ): Promise<UpstreamResponse> => {
+ const started = Date.now();
+ let hostHeader = chooserHost;
+ try {
+ hostHeader = new URL(url).host;
+ } catch {
+ /* fall back to chooser host */
+ }
+ const r = await selectaxios({
+ method: "GET",
+ url,
+ maxRedirects: 0,
+ validateStatus: () => true,
+ timeout: 10000,
+ responseType: "text",
+ transformResponse: (v) => v,
+ headers: { host: hostHeader },
+ });
+ const locHeader = r.headers["location"];
+ const location = Array.isArray(locHeader)
+ ? locHeader[0]
+ : locHeader;
+ const ctHeader = r.headers["content-type"];
+ const ctRaw = Array.isArray(ctHeader) ? ctHeader[0] : ctHeader;
+ const contentType = typeof ctRaw === "string" ? ctRaw : "";
+ const body =
+ typeof r.data === "string" ? r.data : String(r.data ?? "");
+ return {
+ status: r.status,
+ location: typeof location === "string" ? location : undefined,
+ contentType,
+ body,
+ targetUrl: url,
+ elapsedMs: Date.now() - started,
+ };
+ };
+
+ const logResponse = (response: UpstreamResponse): void => {
+ sshLogger.info("OPKSSH /select upstream response", {
+ operation: "opkssh_select_upstream_response",
+ requestId,
+ targetUrl: response.targetUrl,
+ status: response.status,
+ location: response.location,
+ contentType: response.contentType,
+ elapsedMs: response.elapsedMs,
+ bodyPreview: response.body.slice(0, 256),
+ });
+ };
+
+ const MAX_HOPS = 4;
+
+ try {
+ let response = await fetchUpstream(startUrl);
+ logResponse(response);
+
+ for (let hop = 0; hop < MAX_HOPS; hop++) {
+ if (
+ response.status < 300 ||
+ response.status >= 400 ||
+ !response.location
+ ) {
+ break;
+ }
+ const loc = response.location;
+
+ // Relative path: resolve against the current upstream.
+ if (loc.startsWith("/")) {
+ let currentHost = chooserHost;
+ try {
+ currentHost = new URL(response.targetUrl).host;
+ } catch {
+ /* keep default */
+ }
+ response = await fetchUpstream(`http://${currentHost}${loc}`);
+ logResponse(response);
+ continue;
+ }
+
+ // Absolute URL: if it points to a localhost OPKSSH endpoint, capture
+ // the port. Then redirect the BROWSER to the proxied path so that
+ // Set-Cookie headers from OPKSSH's /login handler reach the browser
+ // directly — following them server-side would swallow the cookie.
+ if (/^https?:\/\//i.test(loc)) {
+ try {
+ const parsed = new URL(loc);
+ if (isLocalHostname(parsed.host)) {
+ // Capture callback listener port if not yet known.
+ if (!session.callbackPort) {
+ const port = parseInt(parsed.port, 10);
+ if (!Number.isNaN(port)) {
+ session.callbackPort = port;
+ sshLogger.info(
+ "Captured OPKSSH callback listener port from /select redirect",
+ {
+ operation: "opkssh_select_callback_port_detected",
+ requestId,
+ callbackPort: port,
+ },
+ );
+ }
+ }
+ // Redirect browser through the chooser proxy so it can receive
+ // the state cookie that OPKSSH sets on /login.
+ const browserPath = `/host/opkssh-chooser/${requestId}${parsed.pathname}${parsed.search}`;
+ sshLogger.info(
+ "Redirecting browser to OPKSSH callback listener via proxy",
+ {
+ operation: "opkssh_select_browser_redirect_to_login",
+ requestId,
+ browserPath,
+ callbackPort: session.callbackPort,
+ },
+ );
+ res.redirect(302, browserPath);
+ return;
+ }
+ // External OAuth provider URL — done, handled below.
+ break;
+ } catch {
+ break;
+ }
+ }
+
+ break;
+ }
+
+ const isExternalRedirect =
+ response.status >= 300 &&
+ response.status < 400 &&
+ !!response.location &&
+ /^https?:\/\//i.test(response.location) &&
+ (() => {
+ try {
+ return !isLocalHostname(
+ new URL(response.location as string).host,
+ );
+ } catch {
+ return false;
+ }
+ })();
+
+ if (isExternalRedirect) {
+ const oauthUrl = response.location as string;
+ try {
+ const parsed = new URL(oauthUrl);
+ const oauthState = parsed.searchParams.get("state");
+ if (oauthState) registerOAuthState(oauthState, requestId);
+ } catch {
+ /* already validated above */
+ }
+ sshLogger.info(
+ "OPKSSH /select redirecting browser to OAuth provider",
+ {
+ operation: "opkssh_select_redirect",
+ requestId,
+ oauthUrl,
+ },
+ );
+ res.redirect(302, oauthUrl);
+ return;
+ }
+
+ const bodyPreview = response.body.slice(0, 512);
+ const detailLines = [
+ `Upstream: ${response.targetUrl}`,
+ `Status: ${response.status}`,
+ response.location ? `Location: ${response.location}` : undefined,
+ `Content-Type: ${response.contentType || "(none)"}`,
+ `Elapsed: ${response.elapsedMs}ms`,
+ "",
+ bodyPreview
+ ? `Body (first 512 chars):\n${bodyPreview}`
+ : "Body: (empty)",
+ ].filter(Boolean) as string[];
+
+ sshLogger.error(
+ "OPKSSH /select did not produce an OAuth redirect",
+ {
+ operation: "opkssh_select_no_oauth_redirect",
+ requestId,
+ status: response.status,
+ location: response.location,
+ contentType: response.contentType,
+ bodyPreview,
+ },
+ );
+
+ res.status(502).send(
+ renderOpksshErrorPage({
+ title: "OPKSSH error",
+ heading: "Failed to get OAuth redirect",
+ message:
+ "OPKSSH did not return an external OAuth provider URL. " +
+ "This typically indicates a configuration mismatch between the provider's redirect_uris " +
+ "and the Termix callback path. Check the server log for the OPKSSH response body.",
+ details: detailLines.join("\n"),
+ requestId,
+ }),
+ );
+ } catch (err) {
+ sshLogger.error("Error proxying OPKSSH /select", err, {
+ operation: "opkssh_select_proxy_error",
+ requestId,
+ targetUrl: startUrl,
+ });
+ const errMsg = err instanceof Error ? err.message : String(err);
+ res.status(502).send(
+ renderOpksshErrorPage({
+ title: "OPKSSH error",
+ heading: "Failed to reach OPKSSH service",
+ message:
+ "Termix could not connect to the local OPKSSH authentication service. " +
+ "The OPKSSH process may have exited or is not listening yet.",
+ details: `Upstream: ${startUrl}\nError: ${errMsg}`,
+ requestId,
+ }),
+ );
+ }
+ return;
+ }
+
+ // Paths served by the callback listener, not the chooser.
+ // The browser is redirected here so it receives Set-Cookie from OPKSSH.
+ const isCallbackListenerPath =
+ targetPath === "/login" ||
+ targetPath.startsWith("/login?") ||
+ targetPath === "/login-callback" ||
+ targetPath.startsWith("/login-callback?");
+
+ const upstreamPort =
+ isCallbackListenerPath && session.callbackPort
+ ? session.callbackPort
+ : session.localPort;
+
+ const targetUrl = `http://127.0.0.1:${upstreamPort}${targetPath}`;
+
+ sshLogger.info("Proxying to OPKSSH chooser", {
+ operation: "opkssh_chooser_proxy_request_to_opkssh",
+ requestId,
+ targetUrl,
+ upstreamPort,
+ targetPath,
+ });
+
+ const response = await axios({
+ method: req.method,
+ url: targetUrl,
+ headers: {
+ ...req.headers,
+ host: `127.0.0.1:${upstreamPort}`,
+ },
+ data: req.body,
+ timeout: 10000,
+ validateStatus: () => true,
+ maxRedirects: 0,
+ responseType: "arraybuffer",
+ });
+
+ sshLogger.info("OPKSSH chooser response received", {
+ operation: "opkssh_chooser_proxy_response",
+ requestId,
+ statusCode: response.status,
+ contentType: response.headers["content-type"],
+ contentLength: response.headers["content-length"],
+ hasLocation: !!response.headers.location,
+ });
+
+ Object.entries(response.headers).forEach(([key, value]) => {
+ if (key.toLowerCase() === "transfer-encoding") {
+ return;
+ }
+ if (key.toLowerCase() === "location") {
+ const location = value as string;
+ if (location.startsWith("/")) {
+ res.setHeader(
+ key,
+ `/host/opkssh-chooser/${requestId}${location}`,
+ );
+ } else {
+ const localhostMatch = location.match(
+ /^http:\/\/(?:localhost|127\.0\.0\.1):(\d+)(\/.*)?$/,
+ );
+ if (localhostMatch) {
+ const port = parseInt(localhostMatch[1], 10);
+ const path = localhostMatch[2] || "/";
+ if (session.callbackPort && port === session.callbackPort) {
+ res.setHeader(
+ key,
+ `/host/opkssh-callback/${requestId}${path}`,
+ );
+ } else if (port === session.localPort) {
+ res.setHeader(
+ key,
+ `/host/opkssh-chooser/${requestId}${path}`,
+ );
+ } else {
+ const isCallback =
+ path.includes("login") || path.includes("callback");
+ const prefix = isCallback
+ ? "opkssh-callback"
+ : "opkssh-chooser";
+ res.setHeader(key, `/host/${prefix}/${requestId}${path}`);
+ }
+ } else {
+ // External redirect (e.g. to OIDC provider) — capture OAuth state for session binding
+ try {
+ const redirectUrl = new URL(location);
+ const oauthState = redirectUrl.searchParams.get("state");
+ if (oauthState) {
+ registerOAuthState(oauthState, requestId);
+ }
+ } catch {
+ // Not a valid URL, skip state capture
+ }
+ res.setHeader(key, value as string);
+ }
+ }
+ } else if (key.toLowerCase() === "set-cookie") {
+ // Rewrite cookies from OPKSSH's internal listener so they are scoped
+ // to the Termix proxy path instead of OPKSSH's internal path.
+ // The state cookie set by /login must survive to /login-callback.
+ const cookies = Array.isArray(value) ? value : [value as string];
+ const rewritten = cookies.map((cookie) => {
+ return cookie
+ .replace(/;\s*domain=[^;]*/gi, "")
+ .replace(/;\s*path=[^;]*/gi, "; Path=/host/opkssh-callback/")
+ .concat(
+ cookie.match(/;\s*path=/i)
+ ? ""
+ : "; Path=/host/opkssh-callback/",
+ );
+ });
+ res.setHeader(key, rewritten);
+ } else {
+ res.setHeader(key, value as string);
+ }
+ });
+
+ // Set a cookie to correlate this browser with the requestId.
+ // OAuth state capture from Location headers only works for 3xx redirects;
+ // if OPKSSH redirects via JavaScript, the state is never registered.
+ // This cookie survives the OIDC round-trip and identifies the session on callback.
+ res.cookie("opkssh_request_id", requestId, {
+ path: "/host/",
+ httpOnly: true,
+ sameSite: "lax",
+ maxAge: 5 * 60 * 1000,
+ });
+
+ const contentType = String(response.headers["content-type"] || "");
+ if (contentType.includes("text/html")) {
+ const html = rewriteOPKSSHHtml(
+ response.data.toString("utf-8"),
+ requestId,
+ "opkssh-chooser",
+ );
+ res.status(response.status).send(html);
+ } else {
+ res.status(response.status).send(response.data);
+ }
+ } catch (error) {
+ sshLogger.error("Error proxying OPKSSH chooser", error, {
+ operation: "opkssh_chooser_proxy_error",
+ requestId,
+ });
+ res.status(500).send(
+ renderOpksshErrorPage({
+ title: "Error",
+ heading: "Error",
+ message: "Failed to load authentication page. Please try again.",
+ requestId,
+ }),
+ );
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /host/opkssh-callback:
+ * get:
+ * summary: Static OAuth callback from OIDC provider for OPKSSH authentication
+ * tags: [SSH]
+ * responses:
+ * 200:
+ * description: Callback processed successfully
+ * 404:
+ * description: No active authentication session found
+ * 500:
+ * description: Authentication failed
+ */
+ router.get("/opkssh-callback", async (req: Request, res: Response) => {
+ try {
+ sshLogger.info("OAuth callback received", {
+ operation: "opkssh_static_callback_received",
+ host: req.headers.host,
+ });
+
+ const {
+ getUserIdFromRequest,
+ getActiveSessionsForUser,
+ getActiveAuthSession,
+ getRequestIdByOAuthState,
+ clearOAuthState,
+ } = await import("../../ssh/opkssh-auth.js");
+
+ const userId = await getUserIdFromRequest({
+ cookies: req.cookies,
+ headers: req.headers as Record<string, string | undefined>,
+ });
+
+ sshLogger.info("User ID resolved", {
+ operation: "opkssh_callback_user_lookup",
+ userId: userId || "null",
+ hasCookies: !!req.cookies?.jwt,
+ cookieKeys: Object.keys(req.cookies || {}),
+ });
+
+ let userSessions: Awaited<ReturnType<typeof getActiveSessionsForUser>> =
+ [];
+
+ if (userId) {
+ userSessions = getActiveSessionsForUser(userId);
+ } else {
+ // No JWT cookie (e.g. OAuth redirect landed in external browser).
+ // Try to find the correct session via the OAuth state parameter.
+ const oauthState = req.query.state as string | undefined;
+
+ if (oauthState) {
+ const mappedRequestId = getRequestIdByOAuthState(oauthState);
+ if (mappedRequestId) {
+ const mappedSession = getActiveAuthSession(mappedRequestId);
+ if (mappedSession) {
+ userSessions = [mappedSession];
+ clearOAuthState(oauthState);
+ sshLogger.info("Resolved session via OAuth state parameter", {
+ operation: "opkssh_callback_state_lookup",
+ requestId: mappedRequestId,
+ });
+ }
+ }
+ }
+
+ // Fallback: use the opkssh_request_id cookie set by the chooser proxy.
+ // State capture only works for 3xx redirects; if OPKSSH redirects via
+ // JavaScript in the HTML, the state is never registered in the map.
+ if (userSessions.length === 0) {
+ const cookieRequestId = req.cookies?.opkssh_request_id;
+ if (cookieRequestId) {
+ const cookieSession = getActiveAuthSession(cookieRequestId);
+ if (cookieSession) {
+ userSessions = [cookieSession];
+ res.clearCookie("opkssh_request_id", { path: "/host/" });
+ sshLogger.info("Resolved session via opkssh_request_id cookie", {
+ operation: "opkssh_callback_cookie_lookup",
+ requestId: cookieRequestId,
+ });
+ }
+ }
+ }
+
+ if (userSessions.length === 0) {
+ sshLogger.warn(
+ "OAuth callback with no JWT, no matching state, and no session cookie",
+ {
+ operation: "opkssh_callback_no_session_match",
+ hasState: !!oauthState,
+ hasCookie: !!req.cookies?.opkssh_request_id,
+ },
+ );
+ res
+ .status(401)
+ .send("Authentication callback failed: unable to identify session");
+ return;
+ }
+ }
+
+ sshLogger.info("Active sessions for user", {
+ operation: "opkssh_callback_session_lookup",
+ userId,
+ sessionCount: userSessions.length,
+ sessions: userSessions.map((s) => ({
+ requestId: s.requestId,
+ status: s.status,
+ hasCallbackPort: !!s.callbackPort,
+ callbackPort: s.callbackPort,
+ hasLocalPort: !!s.localPort,
+ localPort: s.localPort,
+ })),
+ });
+
+ if (userSessions.length === 0) {
+ sshLogger.error("No active sessions for callback", {
+ operation: "opkssh_callback_no_sessions",
+ userId,
+ });
+ res.status(404).send("No active authentication session found");
+ return;
+ }
+
+ const session = userSessions[userSessions.length - 1];
+
+ if (!session.callbackPort) {
+ sshLogger.error("Session callback port not ready", {
+ operation: "opkssh_callback_port_not_ready",
+ userId,
+ requestId: session.requestId,
+ sessionStatus: session.status,
+ hasLocalPort: !!session.localPort,
+ });
+ res.status(503).send("OPKSSH callback listener not ready yet");
+ return;
+ }
+
+ const queryString = req.url.includes("?")
+ ? req.url.substring(req.url.indexOf("?"))
+ : "";
+ // OPKSSH's internal callback listener handles `/login-callback` regardless of the
+ // path used in --remote-redirect-uri. The dynamic route below defaults to that path.
+ const redirectUrl = `/host/opkssh-callback/${session.requestId}${queryString}`;
+
+ sshLogger.info("Redirecting OAuth callback to dynamic route", {
+ operation: "opkssh_static_callback_redirect",
+ userId,
+ requestId: session.requestId,
+ callbackPort: session.callbackPort,
+ queryParams: Object.keys(req.query),
+ redirectUrl,
+ });
+
+ res.redirect(302, redirectUrl);
+ } catch (error) {
+ sshLogger.error("Error handling OPKSSH static callback", error, {
+ operation: "opkssh_static_callback_error",
+ url: req.url,
+ originalUrl: req.originalUrl,
+ });
+ res.status(500).send("Authentication callback failed");
+ }
+ });
+
+ /**
+ * @openapi
+ * /host/opkssh-callback/{requestId}:
+ * get:
+ * summary: OAuth callback from OIDC provider for OPKSSH authentication (handles all sub-paths)
+ * tags: [SSH]
+ * parameters:
+ * - name: requestId
+ * in: path
+ * required: true
+ * schema:
+ * type: string
+ * description: Authentication request ID
+ * responses:
+ * 200:
+ * description: Callback processed successfully
+ * 404:
+ * description: Invalid authentication session
+ * 500:
+ * description: Authentication failed
+ */
+ router.use(
+ "/opkssh-callback/:requestId",
+ async (req: Request, res: Response) => {
+ const requestId = Array.isArray(req.params.requestId)
+ ? req.params.requestId[0]
+ : req.params.requestId;
+
+ try {
+ const { getActiveAuthSession } =
+ await import("../../ssh/opkssh-auth.js");
+ const session = getActiveAuthSession(requestId);
+
+ if (!session) {
+ res.status(404).send(
+ renderOpksshErrorPage({
+ title: "Session Not Found",
+ heading: "Session Not Found",
+ message:
+ "Authentication session expired or invalid. Please close this window and try again.",
+ requestId,
+ }),
+ );
+ return;
+ }
+
+ const axios = (await import("axios")).default;
+ const fullPath = req.originalUrl || req.url;
+ const pathAfterRequestId =
+ fullPath.split(`/host/opkssh-callback/${requestId}`)[1] || "";
+ // pathAfterRequestId may be "", "?query=...", "/subpath", or "/subpath?query=..."
+ // OPKSSH's internal listener serves /login-callback, so when no sub-path is present
+ // (query-only or empty), prepend it.
+ const targetPath =
+ pathAfterRequestId === "" || pathAfterRequestId.startsWith("?")
+ ? `/login-callback${pathAfterRequestId}`
+ : pathAfterRequestId;
+
+ if (!session.callbackPort || session.callbackPort === 0) {
+ sshLogger.error("OPKSSH callback session has no callback port", {
+ operation: "opkssh_callback_proxy",
+ requestId,
+ sessionStatus: session.status,
+ });
+ res.status(500).send(
+ renderOpksshErrorPage({
+ title: "Error",
+ heading: "Callback Error",
+ message:
+ "OPKSSH callback listener not ready. Please try authenticating again.",
+ requestId,
+ }),
+ );
+ return;
+ }
+
+ const targetUrl = `http://127.0.0.1:${session.callbackPort}${targetPath}`;
+
+ const response = await axios({
+ method: req.method,
+ url: targetUrl,
+ headers: {
+ ...req.headers,
+ host: `127.0.0.1:${session.callbackPort}`,
+ },
+ data: req.body,
+ timeout: 10000,
+ validateStatus: () => true,
+ maxRedirects: 0,
+ responseType: "arraybuffer",
+ });
+
+ Object.entries(response.headers).forEach(([key, value]) => {
+ if (key.toLowerCase() === "transfer-encoding") {
+ return;
+ }
+ if (key.toLowerCase() === "location") {
+ const location = value as string;
+ if (location.startsWith("/")) {
+ res.setHeader(
+ key,
+ `/host/opkssh-callback/${requestId}${location}`,
+ );
+ } else {
+ res.setHeader(key, value as string);
+ }
+ } else {
+ res.setHeader(key, value as string);
+ }
+ });
+
+ const contentType = String(response.headers["content-type"] || "");
+ if (contentType.includes("text/html")) {
+ const html = rewriteOPKSSHHtml(
+ response.data.toString("utf-8"),
+ requestId,
+ "opkssh-callback",
+ );
+ res.status(response.status).send(html);
+ } else {
+ res.status(response.status).send(response.data);
+ }
+ } catch (error) {
+ sshLogger.error("Error handling OPKSSH OAuth callback", error, {
+ operation: "opkssh_oauth_callback_error",
+ requestId,
+ });
+
+ res.status(500).send(
+ renderOpksshErrorPage({
+ title: "Error",
+ heading: "Error",
+ message: "An unexpected error occurred. Please try again.",
+ requestId,
+ }),
+ );
+ }
+ },
+ );
+}
diff --git a/src/backend/database/routes/host.ts b/src/backend/database/routes/host.ts
index a758dbbaa..211ed856a 100644
--- a/src/backend/database/routes/host.ts
+++ b/src/backend/database/routes/host.ts
@@ -8,24 +8,14 @@ import {
fileManagerRecent,
fileManagerPinned,
fileManagerShortcuts,
- sshFolders,
+ transferRecent,
commandHistory,
recentActivity,
hostAccess,
userRoles,
sessionRecordings,
} from "../db/schema.js";
-import {
- eq,
- and,
- desc,
- isNotNull,
- or,
- isNull,
- gte,
- sql,
- inArray,
-} from "drizzle-orm";
+import { eq, and, or, isNull, gte, sql, inArray, desc } from "drizzle-orm";
import type { Request, Response } from "express";
import axios from "axios";
import multer from "multer";
@@ -34,10 +24,21 @@ import { SimpleDBOps } from "../../utils/simple-db-ops.js";
import { AuthManager } from "../../utils/auth-manager.js";
import { PermissionManager } from "../../utils/permission-manager.js";
import { DataCrypto } from "../../utils/data-crypto.js";
-import { SystemCrypto } from "../../utils/system-crypto.js";
-import { DatabaseSaveTrigger } from "../db/index.js";
import { parseSSHKey } from "../../utils/ssh-key-utils.js";
-import { sendWakeOnLan, isValidMac } from "../../utils/wake-on-lan.js";
+import {
+ isNonEmptyString,
+ isValidPort,
+ stripSensitiveFields,
+ transformHostResponse,
+} from "./host-normalizers.js";
+import { registerHostOpksshRoutes } from "./host-opkssh-routes.js";
+import { registerHostFolderRoutes } from "./host-folder-routes.js";
+import { registerHostFileManagerBookmarkRoutes } from "./host-file-manager-bookmark-routes.js";
+import { registerHostCommandHistoryRoutes } from "./host-command-history-routes.js";
+import { registerHostAutostartRoutes } from "./host-autostart-routes.js";
+import { registerHostInternalRoutes } from "./host-internal-routes.js";
+import { registerHostNetworkRoutes } from "./host-network-routes.js";
+import { registerHostBulkRoutes } from "./host-bulk-routes.js";
const router = express.Router();
@@ -71,451 +72,12 @@ function notifyStatsHostUpdated(
});
}
-function isNonEmptyString(value: unknown): value is string {
- return typeof value === "string" && value.trim().length > 0;
-}
-
-function isValidPort(port: unknown): port is number {
- return typeof port === "number" && port > 0 && port <= 65535;
-}
-
-function asString(value: unknown): string | undefined {
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
-}
-
-function asPort(value: unknown): number | undefined {
- const port =
- typeof value === "number"
- ? value
- : typeof value === "string"
- ? Number.parseInt(value, 10)
- : NaN;
-
- return isValidPort(port) ? port : undefined;
-}
-
-function asInteger(value: unknown): number | undefined {
- const number =
- typeof value === "number"
- ? value
- : typeof value === "string"
- ? Number.parseInt(value, 10)
- : NaN;
-
- return Number.isInteger(number) ? number : undefined;
-}
-
-function asBoolean(value: unknown, fallback = false): boolean {
- if (typeof value === "boolean") return value;
- if (typeof value === "number") return value !== 0;
- if (typeof value === "string") {
- const normalized = value.trim().toLowerCase();
- if (["true", "1", "yes", "on"].includes(normalized)) return true;
- if (["false", "0", "no", "off"].includes(normalized)) return false;
- }
-
- return fallback;
-}
-
-function normalizeImportTags(value: unknown): string[] {
- if (Array.isArray(value)) {
- return value
- .map((tag) => asString(tag))
- .filter((tag): tag is string => !!tag);
- }
- if (typeof value === "string") {
- return value
- .split(",")
- .map((tag) => tag.trim())
- .filter(Boolean);
- }
-
- return [];
-}
-
-type NormalizedImportedHost = Record<string, unknown> & {
- connectionType: string;
- name?: string;
- ip?: string;
- port: number;
- username?: string;
- folder?: string;
- tags: string[];
- authType?: string;
- password?: string;
- key?: string;
- keyPassword?: string;
- keyType?: string;
- credentialId?: number;
- pin?: unknown;
- enableTerminal?: unknown;
- enableTunnel?: unknown;
- enableFileManager?: unknown;
- enableDocker?: unknown;
- showTerminalInSidebar?: unknown;
- showFileManagerInSidebar?: unknown;
- showTunnelInSidebar?: unknown;
- showDockerInSidebar?: unknown;
- showServerStatsInSidebar?: unknown;
- defaultPath?: unknown;
- sudoPassword?: unknown;
- tunnelConnections?: unknown;
- jumpHosts?: unknown;
- quickActions?: unknown;
- statsConfig?: unknown;
- dockerConfig?: unknown;
- terminalConfig?: unknown;
- forceKeyboardInteractive?: unknown;
- notes?: unknown;
- useSocks5?: unknown;
- socks5Host?: unknown;
- socks5Port?: unknown;
- socks5Username?: unknown;
- socks5Password?: unknown;
- socks5ProxyChain?: unknown;
- portKnockSequence?: unknown;
- overrideCredentialUsername?: unknown;
- domain?: unknown;
- security?: unknown;
- ignoreCert?: unknown;
- guacamoleConfig?: unknown;
- enableSsh: boolean;
- enableRdp: boolean;
- enableVnc: boolean;
- enableTelnet: boolean;
-};
-
-function normalizeImportedHost(
- hostData: Record<string, unknown>,
-): NormalizedImportedHost {
- const connectionType =
- asString(hostData.connectionType) ||
- (asBoolean(hostData.enableRdp)
- ? "rdp"
- : asBoolean(hostData.enableVnc)
- ? "vnc"
- : asBoolean(hostData.enableTelnet)
- ? "telnet"
- : "ssh");
-
- const port =
- asPort(hostData.port) ||
- (connectionType === "rdp"
- ? asPort(hostData.rdpPort) || 3389
- : connectionType === "vnc"
- ? asPort(hostData.vncPort) || 5900
- : connectionType === "telnet"
- ? asPort(hostData.telnetPort) || 23
- : asPort(hostData.sshPort) || 22);
-
- return {
- ...hostData,
- connectionType,
- name: asString(hostData.name) || asString(hostData.label),
- ip:
- asString(hostData.ip) ||
- asString(hostData.address) ||
- asString(hostData.host) ||
- asString(hostData.hostname),
- port,
- username: asString(hostData.username) || asString(hostData.user),
- folder: asString(hostData.folder) || asString(hostData.group),
- tags: normalizeImportTags(hostData.tags),
- credentialId: asInteger(hostData.credentialId),
- authType:
- asString(hostData.authType) ||
- asString(hostData.authMethod) ||
- (hostData.credentialId ? "credential" : hostData.key ? "key" : undefined),
- enableSsh:
- hostData.enableSsh === undefined
- ? connectionType === "ssh"
- : asBoolean(hostData.enableSsh),
- enableRdp:
- hostData.enableRdp === undefined
- ? connectionType === "rdp"
- : asBoolean(hostData.enableRdp),
- enableVnc:
- hostData.enableVnc === undefined
- ? connectionType === "vnc"
- : asBoolean(hostData.enableVnc),
- enableTelnet:
- hostData.enableTelnet === undefined
- ? connectionType === "telnet"
- : asBoolean(hostData.enableTelnet),
- };
-}
-
-const SENSITIVE_FIELDS = [
- "key",
- "keyPassword",
- "autostartKey",
- "autostartKeyPassword",
-];
-
-function stripSensitiveFields(
- host: Record<string, unknown>,
-): Record<string, unknown> {
- const result = { ...host };
- result.hasKey = !!host.key;
- result.hasKeyPassword = !!host.keyPassword;
- for (const field of SENSITIVE_FIELDS) {
- delete result[field];
- }
- return result;
-}
-
-function transformHostResponse(
- host: Record<string, unknown>,
-): Record<string, unknown> {
- return {
- ...host,
- tags:
- typeof host.tags === "string"
- ? host.tags
- ? host.tags.split(",").filter(Boolean)
- : []
- : [],
- pin: !!host.pin,
- enableTerminal: !!host.enableTerminal,
- enableTunnel: !!host.enableTunnel,
- enableFileManager: !!host.enableFileManager,
- enableDocker: !!host.enableDocker,
- showTerminalInSidebar: !!host.showTerminalInSidebar,
- showFileManagerInSidebar: !!host.showFileManagerInSidebar,
- showTunnelInSidebar: !!host.showTunnelInSidebar,
- showDockerInSidebar: !!host.showDockerInSidebar,
- showServerStatsInSidebar: !!host.showServerStatsInSidebar,
- // Old hosts only had connection_type set; the per-protocol enable flags didn't exist yet.
- // The schema defaults (enableSsh=true, others=false) wrongly mark every old host as SSH.
- // Detect this migration case: if no non-SSH protocol is explicitly enabled AND
- // connectionType is set to a non-SSH value, fall back to inferring from connectionType.
- ...(() => {
- const ct = host.connectionType;
- const rdp = !!host.enableRdp;
- const vnc = !!host.enableVnc;
- const tel = !!host.enableTelnet;
- const isMigratedNonSsh = !rdp && !vnc && !tel && ct && ct !== "ssh";
- return {
- enableSsh: isMigratedNonSsh ? false : !!host.enableSsh,
- enableRdp: isMigratedNonSsh ? ct === "rdp" : rdp,
- enableVnc: isMigratedNonSsh ? ct === "vnc" : vnc,
- enableTelnet: isMigratedNonSsh ? ct === "telnet" : tel,
- };
- })(),
- sshPort: host.sshPort ?? host.port ?? 22,
- rdpPort: host.rdpPort ?? 3389,
- vncPort: host.vncPort ?? 5900,
- telnetPort: host.telnetPort ?? 23,
- rdpUser: host.rdpUser || undefined,
- rdpDomain: host.rdpDomain || undefined,
- rdpSecurity: host.rdpSecurity || undefined,
- rdpIgnoreCert: !!host.rdpIgnoreCert,
- vncUser: host.vncUser || undefined,
- telnetUser: host.telnetUser || undefined,
- tunnelConnections: host.tunnelConnections
- ? JSON.parse(host.tunnelConnections as string)
- : [],
- jumpHosts: host.jumpHosts ? JSON.parse(host.jumpHosts as string) : [],
- quickActions: host.quickActions
- ? JSON.parse(host.quickActions as string)
- : [],
- statsConfig: host.statsConfig
- ? JSON.parse(host.statsConfig as string)
- : undefined,
- terminalConfig: host.terminalConfig
- ? JSON.parse(host.terminalConfig as string)
- : undefined,
- dockerConfig: host.dockerConfig
- ? JSON.parse(host.dockerConfig as string)
- : undefined,
- forceKeyboardInteractive: host.forceKeyboardInteractive === "true",
- socks5ProxyChain: host.socks5ProxyChain
- ? JSON.parse(host.socks5ProxyChain as string)
- : [],
- portKnockSequence: host.portKnockSequence
- ? JSON.parse(host.portKnockSequence as string)
- : [],
- domain: host.domain || undefined,
- security: host.security || undefined,
- ignoreCert: !!host.ignoreCert,
- guacamoleConfig: host.guacamoleConfig
- ? JSON.parse(host.guacamoleConfig as string)
- : undefined,
- };
-}
-
const authManager = AuthManager.getInstance();
const permissionManager = PermissionManager.getInstance();
const authenticateJWT = authManager.createAuthMiddleware();
const requireDataAccess = authManager.createDataAccessMiddleware();
-/**
- * @openapi
- * /host/db/host/internal:
- * get:
- * summary: Get internal SSH host data
- * description: Returns internal SSH host data for autostart tunnels. Requires internal auth token.
- * tags:
- * - SSH
- * responses:
- * 200:
- * description: A list of autostart hosts.
- * 403:
- * description: Forbidden.
- * 500:
- * description: Failed to fetch autostart SSH data.
- */
-router.get("/db/host/internal", async (req: Request, res: Response) => {
- try {
- const internalToken = req.headers["x-internal-auth-token"];
- const systemCrypto = SystemCrypto.getInstance();
- const expectedToken = await systemCrypto.getInternalAuthToken();
-
- if (internalToken !== expectedToken) {
- sshLogger.warn(
- "Unauthorized attempt to access internal SSH host endpoint",
- {
- source: req.ip,
- userAgent: req.headers["user-agent"],
- providedToken: internalToken ? "present" : "missing",
- },
- );
- return res.status(403).json({ error: "Forbidden" });
- }
- } catch (error) {
- sshLogger.error("Failed to validate internal auth token", error);
- return res.status(500).json({ error: "Internal server error" });
- }
-
- try {
- const autostartHosts = await db
- .select()
- .from(hosts)
- .where(
- and(eq(hosts.enableTunnel, true), isNotNull(hosts.tunnelConnections)),
- );
-
- const result = autostartHosts
- .map((host) => {
- const tunnelConnections = host.tunnelConnections
- ? JSON.parse(host.tunnelConnections)
- : [];
-
- const hasAutoStartTunnels = tunnelConnections.some(
- (tunnel: Record<string, unknown>) => tunnel.autoStart,
- );
-
- if (!hasAutoStartTunnels) {
- return null;
- }
-
- return {
- id: host.id,
- userId: host.userId,
- name: host.name || `autostart-${host.id}`,
- ip: host.ip,
- port: host.port,
- username: host.username,
- authType: host.authType,
- keyType: host.keyType,
- credentialId: host.credentialId,
- enableTunnel: true,
- tunnelConnections: tunnelConnections.filter(
- (tunnel: Record<string, unknown>) => tunnel.autoStart,
- ),
- pin: !!host.pin,
- enableTerminal: !!host.enableTerminal,
- enableFileManager: !!host.enableFileManager,
- showTerminalInSidebar: !!host.showTerminalInSidebar,
- showFileManagerInSidebar: !!host.showFileManagerInSidebar,
- showTunnelInSidebar: !!host.showTunnelInSidebar,
- showDockerInSidebar: !!host.showDockerInSidebar,
- showServerStatsInSidebar: !!host.showServerStatsInSidebar,
- tags: ["autostart"],
- };
- })
- .filter(Boolean);
-
- res.json(result);
- } catch (err) {
- sshLogger.error("Failed to fetch autostart SSH data", err);
- res.status(500).json({ error: "Failed to fetch autostart SSH data" });
- }
-});
-
-/**
- * @openapi
- * /host/db/host/internal/all:
- * get:
- * summary: Get all internal SSH host data
- * description: Returns all internal SSH host data. Requires internal auth token.
- * tags:
- * - SSH
- * responses:
- * 200:
- * description: A list of all hosts.
- * 401:
- * description: Invalid or missing internal authentication token.
- * 500:
- * description: Failed to fetch all hosts.
- */
-router.get("/db/host/internal/all", async (req: Request, res: Response) => {
- try {
- const internalToken = req.headers["x-internal-auth-token"];
- if (!internalToken) {
- return res
- .status(401)
- .json({ error: "Internal authentication token required" });
- }
-
- const systemCrypto = SystemCrypto.getInstance();
- const expectedToken = await systemCrypto.getInternalAuthToken();
-
- if (internalToken !== expectedToken) {
- return res
- .status(401)
- .json({ error: "Invalid internal authentication token" });
- }
-
- const allHosts = await db.select().from(hosts);
-
- const result = allHosts.map((host) => {
- const tunnelConnections = host.tunnelConnections
- ? JSON.parse(host.tunnelConnections)
- : [];
-
- return {
- id: host.id,
- userId: host.userId,
- name: host.name || `${host.username}@${host.ip}`,
- ip: host.ip,
- port: host.port,
- username: host.username,
- authType: host.authType,
- keyType: host.keyType,
- credentialId: host.credentialId,
- enableTunnel: !!host.enableTunnel,
- tunnelConnections: tunnelConnections,
- pin: !!host.pin,
- enableTerminal: !!host.enableTerminal,
- enableFileManager: !!host.enableFileManager,
- showTerminalInSidebar: !!host.showTerminalInSidebar,
- showFileManagerInSidebar: !!host.showFileManagerInSidebar,
- showTunnelInSidebar: !!host.showTunnelInSidebar,
- showDockerInSidebar: !!host.showDockerInSidebar,
- showServerStatsInSidebar: !!host.showServerStatsInSidebar,
- defaultPath: host.defaultPath,
- createdAt: host.createdAt,
- updatedAt: host.updatedAt,
- };
- });
-
- res.json(result);
- } catch (err) {
- sshLogger.error("Failed to fetch all hosts for internal use", err);
- res.status(500).json({ error: "Failed to fetch all hosts" });
- }
-});
+registerHostInternalRoutes(router);
/**
* @openapi
@@ -1807,10 +1369,7 @@ router.get(
try {
const data = await SimpleDBOps.select(
- db
- .select()
- .from(hosts)
- .where(and(eq(hosts.id, hostId), eq(hosts.userId, userId))),
+ db.select().from(hosts).where(eq(hosts.id, hostId)),
"ssh_data",
userId,
);
@@ -2228,6 +1787,15 @@ router.delete(
.delete(fileManagerShortcuts)
.where(eq(fileManagerShortcuts.hostId, numericHostId));
+ await db
+ .delete(transferRecent)
+ .where(
+ or(
+ eq(transferRecent.sourceHostId, numericHostId),
+ eq(transferRecent.destHostId, numericHostId),
+ ),
+ );
+
await db
.delete(commandHistory)
.where(eq(commandHistory.hostId, numericHostId));
@@ -2289,728 +1857,122 @@ router.delete(
},
);
-/**
- * @openapi
- * /host/file_manager/recent:
- * get:
- * summary: Get recent files
- * description: Retrieves a list of recent files for a specific host.
- * tags:
- * - SSH
- * parameters:
- * - in: query
- * name: hostId
- * required: true
- * schema:
- * type: integer
- * responses:
- * 200:
- * description: A list of recent files.
- * 400:
- * description: Invalid userId or hostId.
- * 500:
- * description: Failed to fetch recent files.
- */
+registerHostFileManagerBookmarkRoutes(router, authenticateJWT);
+
router.get(
- "/file_manager/recent",
+ "/transfer/recent",
authenticateJWT,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
- const hostIdQuery = Array.isArray(req.query.hostId)
- ? req.query.hostId[0]
- : req.query.hostId;
- const hostId = hostIdQuery ? parseInt(hostIdQuery as string) : null;
+ const sourceHostIdQuery = Array.isArray(req.query.sourceHostId)
+ ? req.query.sourceHostId[0]
+ : req.query.sourceHostId;
+ const sourceHostId = sourceHostIdQuery
+ ? parseInt(sourceHostIdQuery as string)
+ : null;
if (!isNonEmptyString(userId)) {
- sshLogger.warn("Invalid userId for recent files fetch");
return res.status(400).json({ error: "Invalid userId" });
}
- if (!hostId) {
- sshLogger.warn("Host ID is required for recent files fetch");
- return res.status(400).json({ error: "Host ID is required" });
+ if (!sourceHostId) {
+ return res.status(400).json({ error: "Source host ID is required" });
}
try {
- const recentFiles = await db
+ const recent = await db
.select()
- .from(fileManagerRecent)
+ .from(transferRecent)
.where(
and(
- eq(fileManagerRecent.userId, userId),
- eq(fileManagerRecent.hostId, hostId),
+ eq(transferRecent.userId, userId),
+ eq(transferRecent.sourceHostId, sourceHostId),
),
)
- .orderBy(desc(fileManagerRecent.lastOpened))
- .limit(20);
+ .orderBy(desc(transferRecent.lastUsed))
+ .limit(10);
- res.json(recentFiles);
+ res.json(recent);
} catch (err) {
- sshLogger.error("Failed to fetch recent files", err);
- res.status(500).json({ error: "Failed to fetch recent files" });
+ sshLogger.error("Failed to fetch transfer recent destinations", err);
+ res.status(500).json({ error: "Failed to fetch recent destinations" });
}
},
);
-/**
- * @openapi
- * /host/file_manager/recent:
- * post:
- * summary: Add recent file
- * description: Adds a file to the list of recent files for a host.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hostId:
- * type: integer
- * path:
- * type: string
- * name:
- * type: string
- * responses:
- * 200:
- * description: Recent file added.
- * 400:
- * description: Invalid data.
- * 500:
- * description: Failed to add recent file.
- */
router.post(
- "/file_manager/recent",
+ "/transfer/recent",
authenticateJWT,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
- const { hostId, path, name } = req.body;
+ const { sourceHostId, destHostId, destPath, destPathLabel } = req.body;
- if (!isNonEmptyString(userId) || !hostId || !path) {
- sshLogger.warn("Invalid data for recent file addition");
+ if (
+ !isNonEmptyString(userId) ||
+ !sourceHostId ||
+ !destHostId ||
+ !destPath
+ ) {
return res.status(400).json({ error: "Invalid data" });
}
try {
const existing = await db
.select()
- .from(fileManagerRecent)
+ .from(transferRecent)
.where(
and(
- eq(fileManagerRecent.userId, userId),
- eq(fileManagerRecent.hostId, hostId),
- eq(fileManagerRecent.path, path),
+ eq(transferRecent.userId, userId),
+ eq(transferRecent.sourceHostId, sourceHostId),
+ eq(transferRecent.destHostId, destHostId),
+ eq(transferRecent.destPath, destPath),
),
);
if (existing.length > 0) {
await db
- .update(fileManagerRecent)
- .set({ lastOpened: new Date().toISOString() })
- .where(eq(fileManagerRecent.id, existing[0].id));
+ .update(transferRecent)
+ .set({ lastUsed: new Date().toISOString() })
+ .where(eq(transferRecent.id, existing[0].id));
} else {
- await db.insert(fileManagerRecent).values({
+ await db.insert(transferRecent).values({
userId,
- hostId,
- path,
- name: name || path.split("/").pop() || "Unknown",
- lastOpened: new Date().toISOString(),
+ sourceHostId,
+ destHostId,
+ destPath,
+ destPathLabel: destPathLabel || destPath,
+ lastUsed: new Date().toISOString(),
});
}
- res.json({ message: "Recent file added" });
- } catch (err) {
- sshLogger.error("Failed to add recent file", err);
- res.status(500).json({ error: "Failed to add recent file" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/file_manager/recent:
- * delete:
- * summary: Remove recent file
- * description: Removes a file from the list of recent files for a host.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hostId:
- * type: integer
- * path:
- * type: string
- * responses:
- * 200:
- * description: Recent file removed.
- * 400:
- * description: Invalid data.
- * 500:
- * description: Failed to remove recent file.
- */
-router.delete(
- "/file_manager/recent",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { hostId, path } = req.body;
-
- if (!isNonEmptyString(userId) || !hostId || !path) {
- sshLogger.warn("Invalid data for recent file deletion");
- return res.status(400).json({ error: "Invalid data" });
- }
-
- try {
- await db
- .delete(fileManagerRecent)
- .where(
- and(
- eq(fileManagerRecent.userId, userId),
- eq(fileManagerRecent.hostId, hostId),
- eq(fileManagerRecent.path, path),
- ),
- );
-
- res.json({ message: "Recent file removed" });
- } catch (err) {
- sshLogger.error("Failed to remove recent file", err);
- res.status(500).json({ error: "Failed to remove recent file" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/file_manager/pinned:
- * get:
- * summary: Get pinned files
- * description: Retrieves a list of pinned files for a specific host.
- * tags:
- * - SSH
- * parameters:
- * - in: query
- * name: hostId
- * required: true
- * schema:
- * type: integer
- * responses:
- * 200:
- * description: A list of pinned files.
- * 400:
- * description: Invalid userId or hostId.
- * 500:
- * description: Failed to fetch pinned files.
- */
-router.get(
- "/file_manager/pinned",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const hostIdQuery = Array.isArray(req.query.hostId)
- ? req.query.hostId[0]
- : req.query.hostId;
- const hostId = hostIdQuery ? parseInt(hostIdQuery as string) : null;
-
- if (!isNonEmptyString(userId)) {
- sshLogger.warn("Invalid userId for pinned files fetch");
- return res.status(400).json({ error: "Invalid userId" });
- }
-
- if (!hostId) {
- sshLogger.warn("Host ID is required for pinned files fetch");
- return res.status(400).json({ error: "Host ID is required" });
- }
-
- try {
- const pinnedFiles = await db
+ const allRecent = await db
.select()
- .from(fileManagerPinned)
+ .from(transferRecent)
.where(
and(
- eq(fileManagerPinned.userId, userId),
- eq(fileManagerPinned.hostId, hostId),
+ eq(transferRecent.userId, userId),
+ eq(transferRecent.sourceHostId, sourceHostId),
),
)
- .orderBy(desc(fileManagerPinned.pinnedAt));
-
- res.json(pinnedFiles);
- } catch (err) {
- sshLogger.error("Failed to fetch pinned files", err);
- res.status(500).json({ error: "Failed to fetch pinned files" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/file_manager/pinned:
- * post:
- * summary: Add pinned file
- * description: Adds a file to the list of pinned files for a host.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hostId:
- * type: integer
- * path:
- * type: string
- * name:
- * type: string
- * responses:
- * 200:
- * description: File pinned.
- * 400:
- * description: Invalid data.
- * 409:
- * description: File already pinned.
- * 500:
- * description: Failed to pin file.
- */
-router.post(
- "/file_manager/pinned",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { hostId, path, name } = req.body;
-
- if (!isNonEmptyString(userId) || !hostId || !path) {
- sshLogger.warn("Invalid data for pinned file addition");
- return res.status(400).json({ error: "Invalid data" });
- }
+ .orderBy(desc(transferRecent.lastUsed));
- try {
- const existing = await db
- .select()
- .from(fileManagerPinned)
- .where(
- and(
- eq(fileManagerPinned.userId, userId),
- eq(fileManagerPinned.hostId, hostId),
- eq(fileManagerPinned.path, path),
- ),
- );
-
- if (existing.length > 0) {
- return res.status(409).json({ error: "File already pinned" });
+ if (allRecent.length > 10) {
+ const toDelete = allRecent.slice(10);
+ for (const entry of toDelete) {
+ await db
+ .delete(transferRecent)
+ .where(eq(transferRecent.id, entry.id));
+ }
}
- await db.insert(fileManagerPinned).values({
- userId,
- hostId,
- path,
- name: name || path.split("/").pop() || "Unknown",
- pinnedAt: new Date().toISOString(),
- });
-
- res.json({ message: "File pinned" });
+ res.json({ message: "Recent destination saved" });
} catch (err) {
- sshLogger.error("Failed to pin file", err);
- res.status(500).json({ error: "Failed to pin file" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/file_manager/pinned:
- * delete:
- * summary: Remove pinned file
- * description: Removes a file from the list of pinned files for a host.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hostId:
- * type: integer
- * path:
- * type: string
- * responses:
- * 200:
- * description: Pinned file removed.
- * 400:
- * description: Invalid data.
- * 500:
- * description: Failed to remove pinned file.
- */
-router.delete(
- "/file_manager/pinned",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { hostId, path } = req.body;
-
- if (!isNonEmptyString(userId) || !hostId || !path) {
- sshLogger.warn("Invalid data for pinned file deletion");
- return res.status(400).json({ error: "Invalid data" });
- }
-
- try {
- await db
- .delete(fileManagerPinned)
- .where(
- and(
- eq(fileManagerPinned.userId, userId),
- eq(fileManagerPinned.hostId, hostId),
- eq(fileManagerPinned.path, path),
- ),
- );
-
- res.json({ message: "Pinned file removed" });
- } catch (err) {
- sshLogger.error("Failed to remove pinned file", err);
- res.status(500).json({ error: "Failed to remove pinned file" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/file_manager/shortcuts:
- * get:
- * summary: Get shortcuts
- * description: Retrieves a list of shortcuts for a specific host.
- * tags:
- * - SSH
- * parameters:
- * - in: query
- * name: hostId
- * required: true
- * schema:
- * type: integer
- * responses:
- * 200:
- * description: A list of shortcuts.
- * 400:
- * description: Invalid userId or hostId.
- * 500:
- * description: Failed to fetch shortcuts.
- */
-router.get(
- "/file_manager/shortcuts",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const hostIdQuery = Array.isArray(req.query.hostId)
- ? req.query.hostId[0]
- : req.query.hostId;
- const hostId = hostIdQuery ? parseInt(hostIdQuery as string) : null;
-
- if (!isNonEmptyString(userId)) {
- sshLogger.warn("Invalid userId for shortcuts fetch");
- return res.status(400).json({ error: "Invalid userId" });
- }
-
- if (!hostId) {
- sshLogger.warn("Host ID is required for shortcuts fetch");
- return res.status(400).json({ error: "Host ID is required" });
- }
-
- try {
- const shortcuts = await db
- .select()
- .from(fileManagerShortcuts)
- .where(
- and(
- eq(fileManagerShortcuts.userId, userId),
- eq(fileManagerShortcuts.hostId, hostId),
- ),
- )
- .orderBy(desc(fileManagerShortcuts.createdAt));
-
- res.json(shortcuts);
- } catch (err) {
- sshLogger.error("Failed to fetch shortcuts", err);
- res.status(500).json({ error: "Failed to fetch shortcuts" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/file_manager/shortcuts:
- * post:
- * summary: Add shortcut
- * description: Adds a shortcut for a specific host.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hostId:
- * type: integer
- * path:
- * type: string
- * name:
- * type: string
- * responses:
- * 200:
- * description: Shortcut added.
- * 400:
- * description: Invalid data.
- * 409:
- * description: Shortcut already exists.
- * 500:
- * description: Failed to add shortcut.
- */
-router.post(
- "/file_manager/shortcuts",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { hostId, path, name } = req.body;
-
- if (!isNonEmptyString(userId) || !hostId || !path) {
- sshLogger.warn("Invalid data for shortcut addition");
- return res.status(400).json({ error: "Invalid data" });
- }
-
- try {
- const existing = await db
- .select()
- .from(fileManagerShortcuts)
- .where(
- and(
- eq(fileManagerShortcuts.userId, userId),
- eq(fileManagerShortcuts.hostId, hostId),
- eq(fileManagerShortcuts.path, path),
- ),
- );
-
- if (existing.length > 0) {
- return res.status(409).json({ error: "Shortcut already exists" });
- }
-
- await db.insert(fileManagerShortcuts).values({
- userId,
- hostId,
- path,
- name: name || path.split("/").pop() || "Unknown",
- createdAt: new Date().toISOString(),
- });
-
- res.json({ message: "Shortcut added" });
- } catch (err) {
- sshLogger.error("Failed to add shortcut", err);
- res.status(500).json({ error: "Failed to add shortcut" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/file_manager/shortcuts:
- * delete:
- * summary: Remove shortcut
- * description: Removes a shortcut for a specific host.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hostId:
- * type: integer
- * path:
- * type: string
- * responses:
- * 200:
- * description: Shortcut removed.
- * 400:
- * description: Invalid data.
- * 500:
- * description: Failed to remove shortcut.
- */
-router.delete(
- "/file_manager/shortcuts",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { hostId, path } = req.body;
-
- if (!isNonEmptyString(userId) || !hostId || !path) {
- sshLogger.warn("Invalid data for shortcut deletion");
- return res.status(400).json({ error: "Invalid data" });
- }
-
- try {
- await db
- .delete(fileManagerShortcuts)
- .where(
- and(
- eq(fileManagerShortcuts.userId, userId),
- eq(fileManagerShortcuts.hostId, hostId),
- eq(fileManagerShortcuts.path, path),
- ),
- );
-
- res.json({ message: "Shortcut removed" });
- } catch (err) {
- sshLogger.error("Failed to remove shortcut", err);
- res.status(500).json({ error: "Failed to remove shortcut" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/command-history/{hostId}:
- * get:
- * summary: Get command history
- * description: Retrieves the command history for a specific host.
- * tags:
- * - SSH
- * parameters:
- * - in: path
- * name: hostId
- * required: true
- * schema:
- * type: integer
- * responses:
- * 200:
- * description: A list of commands.
- * 400:
- * description: Invalid userId or hostId.
- * 500:
- * description: Failed to fetch command history.
- */
-router.get(
- "/command-history/:hostId",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const hostIdParam = Array.isArray(req.params.hostId)
- ? req.params.hostId[0]
- : req.params.hostId;
- const hostId = parseInt(hostIdParam, 10);
-
- if (!isNonEmptyString(userId) || !hostId) {
- sshLogger.warn("Invalid userId or hostId for command history fetch", {
- operation: "command_history_fetch",
- hostId,
- userId,
- });
- return res.status(400).json({ error: "Invalid userId or hostId" });
- }
-
- try {
- const history = await db
- .select({
- id: commandHistory.id,
- command: commandHistory.command,
- })
- .from(commandHistory)
- .where(
- and(
- eq(commandHistory.userId, userId),
- eq(commandHistory.hostId, hostId),
- ),
- )
- .orderBy(desc(commandHistory.executedAt))
- .limit(200);
-
- res.json(history.map((h) => h.command));
- } catch (err) {
- sshLogger.error("Failed to fetch command history from database", err, {
- operation: "command_history_fetch",
- hostId,
- userId,
- });
- res.status(500).json({ error: "Failed to fetch command history" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/command-history:
- * delete:
- * summary: Delete command from history
- * description: Deletes a specific command from the history of a host.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hostId:
- * type: integer
- * command:
- * type: string
- * responses:
- * 200:
- * description: Command deleted from history.
- * 400:
- * description: Invalid data.
- * 500:
- * description: Failed to delete command.
- */
-router.delete(
- "/command-history",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { hostId, command } = req.body;
-
- if (!isNonEmptyString(userId) || !hostId || !command) {
- sshLogger.warn("Invalid data for command history deletion", {
- operation: "command_history_delete",
- hostId,
- userId,
- });
- return res.status(400).json({ error: "Invalid data" });
- }
-
- try {
- await db
- .delete(commandHistory)
- .where(
- and(
- eq(commandHistory.userId, userId),
- eq(commandHistory.hostId, hostId),
- eq(commandHistory.command, command),
- ),
- );
-
- res.json({ message: "Command deleted from history" });
- } catch (err) {
- sshLogger.error("Failed to delete command from history", err, {
- operation: "command_history_delete",
- hostId,
- userId,
- command,
- });
- res.status(500).json({ error: "Failed to delete command" });
+ sshLogger.error("Failed to save transfer recent destination", err);
+ res.status(500).json({ error: "Failed to save recent destination" });
}
},
);
+registerHostCommandHistoryRoutes(router, authenticateJWT);
async function resolveHostCredentials(
host: Record<string, unknown>,
@@ -3040,7 +2002,10 @@ async function resolveHostCredentials(
keyType: sharedCred.keyType,
};
- if (!host.overrideCredentialUsername) {
+ if (
+ !host.overrideCredentialUsername &&
+ isNonEmptyString(sharedCred.username)
+ ) {
resolvedHost.username = sharedCred.username;
}
@@ -3086,8 +2051,11 @@ async function resolveHostCredentials(
keyType: credential.keyType,
};
- if (!host.overrideCredentialUsername) {
- resolvedHost.username = credential.username;
+ if (
+ !host.overrideCredentialUsername &&
+ isNonEmptyString(credential.username)
+ ) {
+ resolvedHost.username = credential.username;
}
return resolvedHost;
@@ -3103,372 +2071,110 @@ async function resolveHostCredentials(
}
}
-/**
- * @openapi
- * /host/folders/rename:
- * put:
- * summary: Rename folder
- * description: Renames a folder for SSH hosts and credentials.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * oldName:
- * type: string
- * newName:
- * type: string
- * responses:
- * 200:
- * description: Folder renamed successfully.
- * 400:
- * description: Old name and new name are required.
- * 500:
- * description: Failed to rename folder.
- */
-router.put(
- "/folders/rename",
+registerHostFolderRoutes(router, {
authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { oldName, newName } = req.body;
-
- if (!isNonEmptyString(userId) || !oldName || !newName) {
- sshLogger.warn("Invalid data for folder rename");
- return res
- .status(400)
- .json({ error: "Old name and new name are required" });
- }
-
- if (oldName === newName) {
- return res.json({ message: "Folder name unchanged" });
- }
-
- try {
- const updatedHosts = await SimpleDBOps.update(
- hosts,
- "ssh_data",
- and(eq(hosts.userId, userId), eq(hosts.folder, oldName)),
- {
- folder: newName,
- updatedAt: new Date().toISOString(),
- },
- userId,
- );
-
- const updatedCredentials = await db
- .update(sshCredentials)
- .set({
- folder: newName,
- updatedAt: new Date().toISOString(),
- })
- .where(
- and(
- eq(sshCredentials.userId, userId),
- eq(sshCredentials.folder, oldName),
- ),
- )
- .returning();
-
- DatabaseSaveTrigger.triggerSave("folder_rename");
-
- await db
- .update(sshFolders)
- .set({
- name: newName,
- updatedAt: new Date().toISOString(),
- })
- .where(
- and(eq(sshFolders.userId, userId), eq(sshFolders.name, oldName)),
- );
-
- res.json({
- message: "Folder renamed successfully",
- updatedHosts: updatedHosts.length,
- updatedCredentials: updatedCredentials.length,
- });
- } catch (err) {
- sshLogger.error("Failed to rename folder", err, {
- operation: "folder_rename",
- userId,
- oldName,
- newName,
- });
- res.status(500).json({ error: "Failed to rename folder" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/folders:
- * get:
- * summary: Get all folders
- * description: Retrieves all folders for the authenticated user.
- * tags:
- * - SSH
- * responses:
- * 200:
- * description: A list of folders.
- * 400:
- * description: Invalid user ID.
- * 500:
- * description: Failed to fetch folders.
- */
-router.get("/folders", authenticateJWT, async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!isNonEmptyString(userId)) {
- return res.status(400).json({ error: "Invalid user ID" });
- }
-
- try {
- const folders = await db
- .select()
- .from(sshFolders)
- .where(eq(sshFolders.userId, userId));
-
- res.json(folders);
- } catch (err) {
- sshLogger.error("Failed to fetch folders", err, {
- operation: "fetch_folders",
- userId,
- });
- res.status(500).json({ error: "Failed to fetch folders" });
- }
+ statsServerUrl: STATS_SERVER_URL,
});
-/**
- * @openapi
- * /host/folders/metadata:
- * put:
- * summary: Update folder metadata
- * description: Updates the metadata (color, icon) of a folder.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * name:
- * type: string
- * color:
- * type: string
- * icon:
- * type: string
- * responses:
- * 200:
- * description: Folder metadata updated successfully.
- * 400:
- * description: Folder name is required.
- * 500:
- * description: Failed to update folder metadata.
- */
-router.put(
- "/folders/metadata",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { name, color, icon } = req.body;
-
- if (!isNonEmptyString(userId) || !name) {
- return res.status(400).json({ error: "Folder name is required" });
- }
-
- try {
- const existing = await db
- .select()
- .from(sshFolders)
- .where(and(eq(sshFolders.userId, userId), eq(sshFolders.name, name)))
- .limit(1);
-
- if (existing.length > 0) {
- databaseLogger.info("Updating SSH folder", {
- operation: "folder_update",
- userId,
- folderId: existing[0].id,
- });
- await db
- .update(sshFolders)
- .set({
- color,
- icon,
- updatedAt: new Date().toISOString(),
- })
- .where(and(eq(sshFolders.userId, userId), eq(sshFolders.name, name)));
- } else {
- databaseLogger.info("Creating SSH folder", {
- operation: "folder_create",
- userId,
- name,
- });
- await db.insert(sshFolders).values({
- userId,
- name,
- color,
- icon,
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
- });
- }
-
- DatabaseSaveTrigger.triggerSave("folder_metadata_update");
-
- res.json({ message: "Folder metadata updated successfully" });
- } catch (err) {
- sshLogger.error("Failed to update folder metadata", err, {
- operation: "update_folder_metadata",
- userId,
- name,
- });
- res.status(500).json({ error: "Failed to update folder metadata" });
- }
- },
-);
+registerHostBulkRoutes(router, authenticateJWT);
/**
* @openapi
- * /host/folders/{name}/hosts:
+ * /host/folders/{folderName}/hosts:
* delete:
- * summary: Delete all hosts in folder
- * description: Deletes all SSH hosts within a specific folder.
+ * summary: Delete all hosts in a folder
+ * description: Deletes all hosts within a specific folder.
* tags:
* - SSH
* parameters:
* - in: path
- * name: name
+ * name: folderName
* required: true
* schema:
* type: string
* responses:
* 200:
- * description: Hosts deleted successfully.
+ * description: All hosts deleted successfully.
* 400:
* description: Invalid folder name.
* 500:
- * description: Failed to delete hosts in folder.
+ * description: Failed to delete hosts.
*/
router.delete(
- "/folders/:name/hosts",
+ "/folders/:folderName/hosts",
authenticateJWT,
+ requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
- const folderName = Array.isArray(req.params.name)
- ? req.params.name[0]
- : req.params.name;
+ const folderName = decodeURIComponent(
+ Array.isArray(req.params.folderName)
+ ? req.params.folderName[0]
+ : req.params.folderName,
+ );
- if (!isNonEmptyString(userId) || !folderName) {
- return res.status(400).json({ error: "Invalid folder name" });
+ if (!folderName) {
+ return res.status(400).json({ error: "Folder name is required" });
}
- databaseLogger.info("Deleting SSH folder", {
- operation: "folder_delete",
- userId,
- folderId: folderName,
- });
try {
const hostsToDelete = await db
- .select()
+ .select({ id: hosts.id })
.from(hosts)
.where(and(eq(hosts.userId, userId), eq(hosts.folder, folderName)));
if (hostsToDelete.length === 0) {
- return res.json({
- message: "No hosts found in folder",
- deletedCount: 0,
- });
+ return res.json({ deletedCount: 0 });
}
- const hostIds = hostsToDelete.map((host) => host.id);
+ const hostIds = hostsToDelete.map((h) => h.id);
- if (hostIds.length > 0) {
+ for (const hostId of hostIds) {
await db
.delete(fileManagerRecent)
- .where(inArray(fileManagerRecent.hostId, hostIds));
-
+ .where(eq(fileManagerRecent.hostId, hostId));
await db
.delete(fileManagerPinned)
- .where(inArray(fileManagerPinned.hostId, hostIds));
-
+ .where(eq(fileManagerPinned.hostId, hostId));
await db
.delete(fileManagerShortcuts)
- .where(inArray(fileManagerShortcuts.hostId, hostIds));
-
+ .where(eq(fileManagerShortcuts.hostId, hostId));
+ await db
+ .delete(transferRecent)
+ .where(
+ or(
+ eq(transferRecent.sourceHostId, hostId),
+ eq(transferRecent.destHostId, hostId),
+ ),
+ );
await db
.delete(commandHistory)
- .where(inArray(commandHistory.hostId, hostIds));
-
+ .where(eq(commandHistory.hostId, hostId));
await db
.delete(sshCredentialUsage)
- .where(inArray(sshCredentialUsage.hostId, hostIds));
-
+ .where(eq(sshCredentialUsage.hostId, hostId));
await db
.delete(recentActivity)
- .where(inArray(recentActivity.hostId, hostIds));
-
- await db.delete(hostAccess).where(inArray(hostAccess.hostId, hostIds));
-
+ .where(eq(recentActivity.hostId, hostId));
+ await db.delete(hostAccess).where(eq(hostAccess.hostId, hostId));
await db
.delete(sessionRecordings)
- .where(inArray(sessionRecordings.hostId, hostIds));
+ .where(eq(sessionRecordings.hostId, hostId));
}
await db
.delete(hosts)
.where(and(eq(hosts.userId, userId), eq(hosts.folder, folderName)));
- await db
- .delete(sshFolders)
- .where(
- and(eq(sshFolders.userId, userId), eq(sshFolders.name, folderName)),
- );
-
- DatabaseSaveTrigger.triggerSave("folder_hosts_delete");
-
- try {
- const axios = (await import("axios")).default;
- for (const host of hostsToDelete) {
- try {
- await axios.post(
- `${STATS_SERVER_URL}/host-deleted`,
- { hostId: host.id },
- {
- headers: {
- Authorization: req.headers.authorization || "",
- Cookie: req.headers.cookie || "",
- },
- timeout: 5000,
- },
- );
- } catch (err) {
- sshLogger.warn("Failed to notify stats server of host deletion", {
- operation: "folder_hosts_delete",
- hostId: host.id,
- error: err instanceof Error ? err.message : String(err),
- });
- }
- }
- } catch (err) {
- sshLogger.warn("Failed to notify stats server of folder deletion", {
- operation: "folder_hosts_delete",
- folderName,
- error: err instanceof Error ? err.message : String(err),
- });
- }
-
- res.json({
- message: "All hosts in folder deleted successfully",
+ databaseLogger.success("All hosts in folder deleted", {
+ operation: "delete_folder_hosts",
+ userId,
+ folderName,
deletedCount: hostsToDelete.length,
});
- } catch (err) {
- sshLogger.error("Failed to delete hosts in folder", err, {
+
+ res.json({ deletedCount: hostsToDelete.length });
+ } catch (error) {
+ sshLogger.error("Failed to delete hosts in folder", error, {
operation: "delete_folder_hosts",
userId,
folderName,
@@ -3478,2223 +2184,167 @@ router.delete(
},
);
-/**
- * @openapi
- * /host/bulk-import:
- * post:
- * summary: Bulk import SSH hosts
- * description: Bulk imports multiple SSH hosts.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hosts:
- * type: array
- * items:
- * type: object
- * responses:
- * 200:
- * description: Import completed.
- * 400:
- * description: Invalid request body.
- */
+registerHostAutostartRoutes(router, {
+ authenticateJWT,
+ requireDataAccess,
+});
/**
- * @swagger
- * /host/bulk-update:
- * patch:
- * summary: Bulk update partial fields on multiple SSH hosts
+ * @openapi
+ * /host/opkssh/token/{hostId}:
+ * get:
+ * summary: Get OPKSSH token status for a host
* tags: [SSH]
* security:
* - bearerAuth: []
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hostIds:
- * type: array
- * items:
- * type: number
- * updates:
- * type: object
+ * parameters:
+ * - name: hostId
+ * in: path
+ * required: true
+ * schema:
+ * type: integer
+ * description: Host ID
* responses:
* 200:
- * description: Bulk update completed.
- * 400:
- * description: Invalid request body.
- */
-router.patch(
- "/bulk-update",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { hostIds, updates } = req.body;
-
- if (!Array.isArray(hostIds) || hostIds.length === 0) {
- return res
- .status(400)
- .json({ error: "hostIds array is required and must not be empty" });
- }
-
- if (hostIds.length > 1000) {
- return res
- .status(400)
- .json({ error: "Maximum 1000 hosts allowed per bulk update" });
- }
-
- if (
- !updates ||
- typeof updates !== "object" ||
- Object.keys(updates).length === 0
- ) {
- return res.status(400).json({
- error: "updates object is required and must contain at least one field",
- });
- }
-
- try {
- const ownedHosts = await db
- .select({ id: hosts.id, statsConfig: hosts.statsConfig })
- .from(hosts)
- .where(and(inArray(hosts.id, hostIds), eq(hosts.userId, userId)));
-
- const ownedIds = ownedHosts.map((h) => h.id);
- const unauthorizedIds = hostIds.filter(
- (id: number) => !ownedIds.includes(id),
- );
-
- if (ownedIds.length === 0) {
- return res.status(404).json({ error: "No matching hosts found" });
- }
-
- const errors: string[] = [];
- if (unauthorizedIds.length > 0) {
- errors.push(`${unauthorizedIds.length} host(s) not found or not owned`);
- }
-
- const simpleUpdates: Record<string, unknown> = {};
- if (typeof updates.pin === "boolean") simpleUpdates.pin = updates.pin;
- if (typeof updates.folder === "string")
- simpleUpdates.folder = updates.folder || null;
- if (typeof updates.enableTerminal === "boolean")
- simpleUpdates.enableTerminal = updates.enableTerminal;
- if (typeof updates.enableTunnel === "boolean")
- simpleUpdates.enableTunnel = updates.enableTunnel;
- if (typeof updates.enableFileManager === "boolean")
- simpleUpdates.enableFileManager = updates.enableFileManager;
- if (typeof updates.enableDocker === "boolean")
- simpleUpdates.enableDocker = updates.enableDocker;
-
- if (Object.keys(simpleUpdates).length > 0) {
- await db
- .update(hosts)
- .set(simpleUpdates)
- .where(and(inArray(hosts.id, ownedIds), eq(hosts.userId, userId)));
- }
-
- if (updates.statsConfig && typeof updates.statsConfig === "object") {
- for (const host of ownedHosts) {
- try {
- const existing = host.statsConfig
- ? JSON.parse(host.statsConfig as string)
- : {};
- const merged = { ...existing, ...updates.statsConfig };
- await db
- .update(hosts)
- .set({ statsConfig: JSON.stringify(merged) })
- .where(and(eq(hosts.id, host.id), eq(hosts.userId, userId)));
- } catch {
- errors.push(`Failed to update statsConfig for host ${host.id}`);
- }
- }
- }
-
- DatabaseSaveTrigger.triggerSave("bulk_update");
-
- return res.json({
- updated: ownedIds.length,
- failed: unauthorizedIds.length,
- errors,
- });
- } catch (error) {
- sshLogger.error("Failed to bulk update hosts:", error);
- return res.status(500).json({ error: "Failed to bulk update hosts" });
- }
- },
-);
-
-router.post(
- "/bulk-import",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { hosts: hostsToImport, overwrite } = req.body;
-
- if (!Array.isArray(hostsToImport) || hostsToImport.length === 0) {
- return res
- .status(400)
- .json({ error: "Hosts array is required and must not be empty" });
- }
-
- if (hostsToImport.length > 100) {
- return res
- .status(400)
- .json({ error: "Maximum 100 hosts allowed per import" });
- }
-
- const results = {
- success: 0,
- updated: 0,
- skipped: 0,
- failed: 0,
- errors: [] as string[],
- };
-
- let existingHostMap: Map<string, { id: number }> | undefined;
- if (overwrite) {
- try {
- const allHosts = await SimpleDBOps.select<Record<string, unknown>>(
- db.select().from(hosts).where(eq(hosts.userId, userId)),
- "ssh_data",
- userId,
- );
- existingHostMap = new Map();
- for (const h of allHosts) {
- const key = `${h.ip}:${h.port}:${h.username}`;
- existingHostMap.set(key, { id: h.id as number });
- }
- } catch {
- existingHostMap = undefined;
- }
- }
-
- for (let i = 0; i < hostsToImport.length; i++) {
- const hostData = normalizeImportedHost(hostsToImport[i]);
-
- try {
- const effectiveConnectionType = hostData.connectionType || "ssh";
-
- if (!isNonEmptyString(hostData.ip) || !isValidPort(hostData.port)) {
- results.failed++;
- results.errors.push(
- `Host ${i + 1}: Missing required fields (ip, port)`,
- );
- continue;
- }
-
- if (
- effectiveConnectionType === "ssh" &&
- !isNonEmptyString(hostData.username)
- ) {
- results.failed++;
- results.errors.push(
- `Host ${i + 1}: Username required for SSH connections`,
- );
- continue;
- }
-
- if (
- effectiveConnectionType === "ssh" &&
- hostData.authType &&
- !["password", "key", "credential", "none", "opkssh"].includes(
- hostData.authType,
- )
- ) {
- results.failed++;
- results.errors.push(
- `Host ${i + 1}: Invalid authType. Must be 'password', 'key', 'credential', 'none', or 'opkssh'`,
- );
- continue;
- }
-
- if (
- effectiveConnectionType === "ssh" &&
- hostData.authType === "password" &&
- !isNonEmptyString(hostData.password)
- ) {
- results.failed++;
- results.errors.push(
- `Host ${i + 1}: Password required for password authentication`,
- );
- continue;
- }
-
- if (
- effectiveConnectionType === "ssh" &&
- hostData.authType === "key" &&
- !isNonEmptyString(hostData.key)
- ) {
- results.failed++;
- results.errors.push(
- `Host ${i + 1}: Key required for key authentication`,
- );
- continue;
- }
-
- if (
- effectiveConnectionType === "ssh" &&
- hostData.authType === "credential" &&
- !hostData.credentialId
- ) {
- results.failed++;
- results.errors.push(
- `Host ${i + 1}: credentialId required for credential authentication`,
- );
- continue;
- }
-
- if (
- effectiveConnectionType === "ssh" &&
- hostData.authType === "credential" &&
- hostData.credentialId
- ) {
- const cred = await db
- .select({ id: sshCredentials.id })
- .from(sshCredentials)
- .where(
- and(
- eq(sshCredentials.id, hostData.credentialId),
- eq(sshCredentials.userId, userId),
- ),
- )
- .limit(1);
-
- if (cred.length === 0) {
- const fallback = await db
- .select({ id: sshCredentials.id })
- .from(sshCredentials)
- .where(eq(sshCredentials.userId, userId))
- .limit(1);
-
- if (fallback.length > 0) {
- hostData.credentialId = fallback[0].id;
- } else {
- results.failed++;
- results.errors.push(
- `Host ${i + 1}: credentialId ${hostData.credentialId} not found and no fallback credential available`,
- );
- continue;
- }
- }
- }
-
- const sshDataObj: Record<string, unknown> = {
- userId: userId,
- connectionType: effectiveConnectionType,
- name: hostData.name || `${hostData.username || ""}@${hostData.ip}`,
- folder: hostData.folder || "Default",
- tags: Array.isArray(hostData.tags) ? hostData.tags.join(",") : "",
- ip: hostData.ip,
- port: hostData.port,
- username: hostData.username || null,
- pin: hostData.pin || false,
- enableTerminal: hostData.enableTerminal !== false,
- enableTunnel: hostData.enableTunnel !== false,
- enableFileManager: hostData.enableFileManager !== false,
- enableDocker: hostData.enableDocker || false,
- showTerminalInSidebar: hostData.showTerminalInSidebar ? 1 : 0,
- showFileManagerInSidebar: hostData.showFileManagerInSidebar ? 1 : 0,
- showTunnelInSidebar: hostData.showTunnelInSidebar ? 1 : 0,
- showDockerInSidebar: hostData.showDockerInSidebar ? 1 : 0,
- showServerStatsInSidebar: hostData.showServerStatsInSidebar ? 1 : 0,
- defaultPath: hostData.defaultPath || "/",
- sudoPassword: hostData.sudoPassword || null,
- tunnelConnections: hostData.tunnelConnections
- ? JSON.stringify(hostData.tunnelConnections)
- : "[]",
- jumpHosts: hostData.jumpHosts
- ? JSON.stringify(hostData.jumpHosts)
- : null,
- quickActions: hostData.quickActions
- ? JSON.stringify(hostData.quickActions)
- : null,
- statsConfig: hostData.statsConfig
- ? JSON.stringify(hostData.statsConfig)
- : null,
- dockerConfig: hostData.dockerConfig
- ? JSON.stringify(hostData.dockerConfig)
- : null,
- terminalConfig: hostData.terminalConfig
- ? JSON.stringify(hostData.terminalConfig)
- : null,
- forceKeyboardInteractive: hostData.forceKeyboardInteractive
- ? "true"
- : "false",
- notes: hostData.notes || null,
- useSocks5: hostData.useSocks5 ? 1 : 0,
- socks5Host: hostData.socks5Host || null,
- socks5Port: hostData.socks5Port || null,
- socks5Username: hostData.socks5Username || null,
- socks5Password: hostData.socks5Password || null,
- socks5ProxyChain: hostData.socks5ProxyChain
- ? JSON.stringify(hostData.socks5ProxyChain)
- : null,
- portKnockSequence: hostData.portKnockSequence
- ? JSON.stringify(hostData.portKnockSequence)
- : null,
- overrideCredentialUsername: hostData.overrideCredentialUsername
- ? 1
- : 0,
- enableSsh: hostData.enableSsh ?? false,
- enableRdp: hostData.enableRdp ?? false,
- enableVnc: hostData.enableVnc ?? false,
- enableTelnet: hostData.enableTelnet ?? false,
- updatedAt: new Date().toISOString(),
- };
-
- if (effectiveConnectionType !== "ssh") {
- sshDataObj.password = hostData.password || null;
- sshDataObj.authType = "password";
- sshDataObj.credentialId = null;
- sshDataObj.key = null;
- sshDataObj.keyPassword = null;
- sshDataObj.keyType = null;
- sshDataObj.rdpUser = hostData.rdpUser || null;
- sshDataObj.rdpPassword = hostData.rdpPassword || null;
- sshDataObj.rdpDomain = hostData.rdpDomain || null;
- sshDataObj.rdpSecurity = hostData.rdpSecurity || null;
- sshDataObj.rdpIgnoreCert = hostData.rdpIgnoreCert ? 1 : 0;
- sshDataObj.rdpPort = hostData.rdpPort || 3389;
- sshDataObj.vncUser = hostData.vncUser || null;
- sshDataObj.vncPassword = hostData.vncPassword || null;
- sshDataObj.vncPort = hostData.vncPort || 5900;
- sshDataObj.telnetUser = hostData.telnetUser || null;
- sshDataObj.telnetPassword = hostData.telnetPassword || null;
- sshDataObj.telnetPort = hostData.telnetPort || 23;
- sshDataObj.enableRdp = hostData.enableRdp ? 1 : 0;
- sshDataObj.enableVnc = hostData.enableVnc ? 1 : 0;
- sshDataObj.enableTelnet = hostData.enableTelnet ? 1 : 0;
- sshDataObj.guacamoleConfig = hostData.guacamoleConfig
- ? JSON.stringify(hostData.guacamoleConfig)
- : null;
- } else {
- sshDataObj.password =
- hostData.authType === "password" ? hostData.password : null;
- sshDataObj.authType = hostData.authType || "password";
- sshDataObj.credentialId =
- hostData.authType === "credential" ? hostData.credentialId : null;
- sshDataObj.key = hostData.authType === "key" ? hostData.key : null;
- sshDataObj.keyPassword =
- hostData.authType === "key" ? hostData.keyPassword || null : null;
- sshDataObj.keyType =
- hostData.authType === "key" ? hostData.keyType || "auto" : null;
- sshDataObj.domain = null;
- sshDataObj.security = null;
- sshDataObj.ignoreCert = 0;
- sshDataObj.guacamoleConfig = null;
- }
-
- const lookupKey = `${hostData.ip}:${hostData.port}:${hostData.username}`;
- const existing = existingHostMap?.get(lookupKey);
-
- if (existing) {
- await SimpleDBOps.update(
- hosts,
- "ssh_data",
- eq(hosts.id, existing.id),
- sshDataObj,
- userId,
- );
- results.updated++;
- } else {
- sshDataObj.createdAt = new Date().toISOString();
- await SimpleDBOps.insert(hosts, "ssh_data", sshDataObj, userId);
- results.success++;
- }
- } catch (error) {
- results.failed++;
- results.errors.push(
- `Host ${i + 1}: ${error instanceof Error ? error.message : "Unknown error"}`,
- );
- }
- }
-
- res.json({
- message: `Import completed: ${results.success} created, ${results.updated} updated, ${results.failed} failed`,
- success: results.success,
- updated: results.updated,
- skipped: results.skipped,
- failed: results.failed,
- errors: results.errors,
- });
- },
-);
-
-/**
- * @openapi
- * /host/folders/{folderName}/hosts:
- * delete:
- * summary: Delete all hosts in a folder
- * description: Deletes all hosts within a specific folder.
- * tags:
- * - SSH
- * parameters:
- * - in: path
- * name: folderName
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: All hosts deleted successfully.
- * 400:
- * description: Invalid folder name.
- * 500:
- * description: Failed to delete hosts.
- */
-router.delete(
- "/folders/:folderName/hosts",
- authenticateJWT,
- requireDataAccess,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const folderName = decodeURIComponent(
- Array.isArray(req.params.folderName)
- ? req.params.folderName[0]
- : req.params.folderName,
- );
-
- if (!folderName) {
- return res.status(400).json({ error: "Folder name is required" });
- }
-
- try {
- const hostsToDelete = await db
- .select({ id: hosts.id })
- .from(hosts)
- .where(and(eq(hosts.userId, userId), eq(hosts.folder, folderName)));
-
- if (hostsToDelete.length === 0) {
- return res.json({ deletedCount: 0 });
- }
-
- const hostIds = hostsToDelete.map((h) => h.id);
-
- for (const hostId of hostIds) {
- await db
- .delete(fileManagerRecent)
- .where(eq(fileManagerRecent.hostId, hostId));
- await db
- .delete(fileManagerPinned)
- .where(eq(fileManagerPinned.hostId, hostId));
- await db
- .delete(fileManagerShortcuts)
- .where(eq(fileManagerShortcuts.hostId, hostId));
- await db
- .delete(commandHistory)
- .where(eq(commandHistory.hostId, hostId));
- await db
- .delete(sshCredentialUsage)
- .where(eq(sshCredentialUsage.hostId, hostId));
- await db
- .delete(recentActivity)
- .where(eq(recentActivity.hostId, hostId));
- await db.delete(hostAccess).where(eq(hostAccess.hostId, hostId));
- await db
- .delete(sessionRecordings)
- .where(eq(sessionRecordings.hostId, hostId));
- }
-
- await db
- .delete(hosts)
- .where(and(eq(hosts.userId, userId), eq(hosts.folder, folderName)));
-
- databaseLogger.success("All hosts in folder deleted", {
- operation: "delete_folder_hosts",
- userId,
- folderName,
- deletedCount: hostsToDelete.length,
- });
-
- res.json({ deletedCount: hostsToDelete.length });
- } catch (error) {
- sshLogger.error("Failed to delete hosts in folder", error, {
- operation: "delete_folder_hosts",
- userId,
- folderName,
- });
- res.status(500).json({ error: "Failed to delete hosts in folder" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/autostart/enable:
- * post:
- * summary: Enable autostart for SSH configuration
- * description: Enables autostart for a specific SSH configuration.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sshConfigId:
- * type: number
- * responses:
- * 200:
- * description: AutoStart enabled successfully.
- * 400:
- * description: Valid sshConfigId is required.
- * 404:
- * description: SSH configuration not found.
- * 500:
- * description: Internal server error.
- */
-router.post(
- "/autostart/enable",
- authenticateJWT,
- requireDataAccess,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { sshConfigId } = req.body;
-
- if (!sshConfigId || typeof sshConfigId !== "number") {
- sshLogger.warn(
- "Missing or invalid sshConfigId in autostart enable request",
- {
- operation: "autostart_enable",
- userId,
- sshConfigId,
- },
- );
- return res.status(400).json({ error: "Valid sshConfigId is required" });
- }
-
- try {
- const userDataKey = DataCrypto.getUserDataKey(userId);
- if (!userDataKey) {
- sshLogger.warn(
- "User attempted to enable autostart without unlocked data",
- {
- operation: "autostart_enable_failed",
- userId,
- sshConfigId,
- reason: "data_locked",
- },
- );
- return res.status(400).json({
- error: "Failed to enable autostart. Ensure user data is unlocked.",
- });
- }
-
- const sshConfig = await db
- .select()
- .from(hosts)
- .where(and(eq(hosts.id, sshConfigId), eq(hosts.userId, userId)));
-
- if (sshConfig.length === 0) {
- sshLogger.warn("SSH config not found for autostart enable", {
- operation: "autostart_enable_failed",
- userId,
- sshConfigId,
- reason: "config_not_found",
- });
- return res.status(404).json({
- error: "SSH configuration not found",
- });
- }
-
- const config = sshConfig[0];
-
- const decryptedConfig = DataCrypto.decryptRecord(
- "ssh_data",
- config,
- userId,
- userDataKey,
- );
-
- let updatedTunnelConnections = config.tunnelConnections;
- if (config.tunnelConnections) {
- try {
- const tunnelConnections = JSON.parse(config.tunnelConnections);
-
- const resolvedConnections = await Promise.all(
- tunnelConnections.map(async (tunnel: Record<string, unknown>) => {
- if (
- tunnel.autoStart &&
- tunnel.endpointHost &&
- !tunnel.endpointPassword &&
- !tunnel.endpointKey
- ) {
- const endpointHosts = await db
- .select()
- .from(hosts)
- .where(eq(hosts.userId, userId));
-
- const endpointHost = endpointHosts.find(
- (h) =>
- h.name === tunnel.endpointHost ||
- `${h.username}@${h.ip}` === tunnel.endpointHost,
- );
-
- if (endpointHost) {
- const decryptedEndpoint = DataCrypto.decryptRecord(
- "ssh_data",
- endpointHost,
- userId,
- userDataKey,
- );
-
- return {
- ...tunnel,
- endpointPassword: decryptedEndpoint.password || null,
- endpointKey: decryptedEndpoint.key || null,
- endpointKeyPassword: decryptedEndpoint.keyPassword || null,
- endpointAuthType: endpointHost.authType,
- };
- }
- }
- return tunnel;
- }),
- );
-
- updatedTunnelConnections = JSON.stringify(resolvedConnections);
- } catch (error) {
- sshLogger.warn("Failed to update tunnel connections", {
- operation: "tunnel_connections_update_failed",
- error: error instanceof Error ? error.message : "Unknown error",
- });
- }
- }
-
- await db
- .update(hosts)
- .set({
- autostartPassword: decryptedConfig.password || null,
- autostartKey: decryptedConfig.key || null,
- autostartKeyPassword: decryptedConfig.keyPassword || null,
- tunnelConnections: updatedTunnelConnections,
- })
- .where(eq(hosts.id, sshConfigId));
-
- try {
- await DatabaseSaveTrigger.triggerSave();
- } catch (saveError) {
- sshLogger.warn("Database save failed after autostart", {
- operation: "autostart_db_save_failed",
- error:
- saveError instanceof Error ? saveError.message : "Unknown error",
- });
- }
-
- res.json({
- message: "AutoStart enabled successfully",
- sshConfigId,
- });
- } catch (error) {
- sshLogger.error("Error enabling autostart", error, {
- operation: "autostart_enable_error",
- userId,
- sshConfigId,
- });
- res.status(500).json({ error: "Internal server error" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/autostart/disable:
- * delete:
- * summary: Disable autostart for SSH configuration
- * description: Disables autostart for a specific SSH configuration.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sshConfigId:
- * type: number
- * responses:
- * 200:
- * description: AutoStart disabled successfully.
- * 400:
- * description: Valid sshConfigId is required.
- * 500:
- * description: Internal server error.
- */
-router.delete(
- "/autostart/disable",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { sshConfigId } = req.body;
-
- if (!sshConfigId || typeof sshConfigId !== "number") {
- sshLogger.warn(
- "Missing or invalid sshConfigId in autostart disable request",
- {
- operation: "autostart_disable",
- userId,
- sshConfigId,
- },
- );
- return res.status(400).json({ error: "Valid sshConfigId is required" });
- }
-
- try {
- await db
- .update(hosts)
- .set({
- autostartPassword: null,
- autostartKey: null,
- autostartKeyPassword: null,
- })
- .where(and(eq(hosts.id, sshConfigId), eq(hosts.userId, userId)));
-
- res.json({
- message: "AutoStart disabled successfully",
- sshConfigId,
- });
- } catch (error) {
- sshLogger.error("Error disabling autostart", error, {
- operation: "autostart_disable_error",
- userId,
- sshConfigId,
- });
- res.status(500).json({ error: "Internal server error" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/autostart/status:
- * get:
- * summary: Get autostart status
- * description: Retrieves the autostart status for the user's SSH configurations.
- * tags:
- * - SSH
- * responses:
- * 200:
- * description: A list of autostart configurations.
- * 500:
- * description: Internal server error.
- */
-router.get(
- "/autostart/status",
- authenticateJWT,
- async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
-
- try {
- const autostartConfigs = await db
- .select()
- .from(hosts)
- .where(
- and(
- eq(hosts.userId, userId),
- or(
- isNotNull(hosts.autostartPassword),
- isNotNull(hosts.autostartKey),
- ),
- ),
- );
-
- const statusList = autostartConfigs.map((config) => ({
- sshConfigId: config.id,
- host: config.ip,
- port: config.port,
- username: config.username,
- authType: config.authType,
- }));
-
- res.json({
- autostart_configs: statusList,
- total_count: statusList.length,
- });
- } catch (error) {
- sshLogger.error("Error getting autostart status", error, {
- operation: "autostart_status_error",
- userId,
- });
- res.status(500).json({ error: "Internal server error" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/opkssh/token/{hostId}:
- * get:
- * summary: Get OPKSSH token status for a host
- * tags: [SSH]
- * security:
- * - bearerAuth: []
- * parameters:
- * - name: hostId
- * in: path
- * required: true
- * schema:
- * type: integer
- * description: Host ID
- * responses:
- * 200:
- * description: Token status retrieved successfully
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * exists:
- * type: boolean
- * description: Whether a valid token exists
- * expiresAt:
- * type: string
- * format: date-time
- * description: Token expiration timestamp
- * email:
- * type: string
- * description: User email from OIDC identity
- * 404:
- * description: No valid token found
- * 500:
- * description: Internal server error
- */
-router.get(
- "/ssh/opkssh/token/:hostId",
- authenticateJWT,
- requireDataAccess,
- async (req: AuthenticatedRequest, res: Response) => {
- const userId = req.userId;
- const hostId = parseInt(
- Array.isArray(req.params.hostId)
- ? req.params.hostId[0]
- : req.params.hostId,
- );
-
- if (!userId || isNaN(hostId)) {
- return res.status(400).json({ error: "Invalid request" });
- }
-
- try {
- const { opksshTokens } = await import("../db/schema.js");
- const token = await db
- .select()
- .from(opksshTokens)
- .where(
- and(eq(opksshTokens.userId, userId), eq(opksshTokens.hostId, hostId)),
- )
- .limit(1);
-
- if (!token || token.length === 0) {
- return res.status(404).json({ exists: false });
- }
-
- const tokenData = token[0];
- const expiresAt = new Date(tokenData.expiresAt);
-
- if (expiresAt < new Date()) {
- await db
- .delete(opksshTokens)
- .where(
- and(
- eq(opksshTokens.userId, userId),
- eq(opksshTokens.hostId, hostId),
- ),
- );
- return res.status(404).json({ exists: false });
- }
-
- res.json({
- exists: true,
- expiresAt: tokenData.expiresAt,
- email: tokenData.email,
- });
- } catch (error) {
- sshLogger.error("Error retrieving OPKSSH token status", error, {
- operation: "opkssh_token_status_error",
- userId,
- hostId,
- });
- res.status(500).json({ error: "Internal server error" });
- }
- },
-);
-
-/**
- * @openapi
- * /host/opkssh/token/{hostId}:
- * delete:
- * summary: Delete OPKSSH token for a host
- * tags: [SSH]
- * security:
- * - bearerAuth: []
- * parameters:
- * - name: hostId
- * in: path
- * required: true
- * schema:
- * type: integer
- * description: Host ID
- * responses:
- * 200:
- * description: Token deleted successfully
- * 500:
- * description: Internal server error
- */
-router.delete(
- "/ssh/opkssh/token/:hostId",
- authenticateJWT,
- requireDataAccess,
- async (req: AuthenticatedRequest, res: Response) => {
- const userId = req.userId;
- const hostId = parseInt(
- Array.isArray(req.params.hostId)
- ? req.params.hostId[0]
- : req.params.hostId,
- );
-
- if (!userId || isNaN(hostId)) {
- return res.status(400).json({ error: "Invalid request" });
- }
-
- try {
- const { deleteOPKSSHToken } = await import("../../ssh/opkssh-auth.js");
- await deleteOPKSSHToken(userId, hostId);
- res.json({ success: true });
- } catch (error) {
- sshLogger.error("Error deleting OPKSSH token", error, {
- operation: "opkssh_token_delete_error",
- userId,
- hostId,
- });
- res.status(500).json({ error: "Internal server error" });
- }
- },
-);
-
-function escapeHtml(value: string): string {
- return value
- .replace(/&/g, "&amp;")
- .replace(/</g, "&lt;")
- .replace(/>/g, "&gt;")
- .replace(/"/g, "&quot;")
- .replace(/'/g, "&#39;");
-}
-
-// Replicates openpubkey's client/choosers/web_chooser.go IssuerToName().
-// OPKSSH's /select handler keys its providerMap by this derived name, NOT by the
-// `alias` field in config.yml. We need the same mapping so we can normalize any
-// `op=` query param we receive (which can be alias, issuer with protocol, or
-// issuer without protocol depending on client version) to what OPKSSH expects.
-function opksshIssuerToName(issuer: string): string | null {
- if (!issuer) return null;
- const withScheme =
- issuer.startsWith("http://") || issuer.startsWith("https://")
- ? issuer
- : `https://${issuer}`;
- if (withScheme.startsWith("https://accounts.google.com")) return "google";
- if (withScheme.startsWith("https://login.microsoftonline.com"))
- return "azure";
- if (withScheme.startsWith("https://gitlab.com")) return "gitlab";
- if (withScheme.startsWith("https://issuer.hello.coop")) return "hello";
- if (withScheme.startsWith("https://")) {
- const host = withScheme.slice("https://".length).split("/")[0];
- return host || null;
- }
- return null;
-}
-
-function normalizeSelectOpParam(
- rawOp: string,
- providers: Array<{ alias: string; issuer: string }>,
-): string {
- if (!rawOp) return rawOp;
- const knownNames = new Set(
- providers
- .map((p) => opksshIssuerToName(p.issuer))
- .filter((n): n is string => typeof n === "string" && n.length > 0),
- );
- if (knownNames.has(rawOp)) return rawOp;
-
- const derivedFromRaw = opksshIssuerToName(rawOp);
- if (derivedFromRaw && knownNames.has(derivedFromRaw)) return derivedFromRaw;
-
- const matchByAlias = providers.find((p) => p.alias === rawOp);
- if (matchByAlias) {
- const name = opksshIssuerToName(matchByAlias.issuer);
- if (name) return name;
- }
-
- return rawOp;
-}
-
-interface OpksshErrorPageOptions {
- title: string;
- heading: string;
- message: string;
- details?: string;
- requestId?: string;
- statusCode?: number;
-}
-
-function renderOpksshErrorPage(opts: OpksshErrorPageOptions): string {
- const title = escapeHtml(opts.title);
- const heading = escapeHtml(opts.heading);
- const message = escapeHtml(opts.message);
- const detailsBlock = opts.details
- ? `<pre class="details">${escapeHtml(opts.details)}</pre>`
- : "";
- const requestIdBlock = opts.requestId
- ? `<p class="request-id">Request ID: ${escapeHtml(opts.requestId)}</p>`
- : "";
-
- return `<!DOCTYPE html>
-<html>
-<head>
- <title>${title}</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <style>
- * { margin: 0; padding: 0; box-sizing: border-box; }
- body {
- font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
- display: flex;
- justify-content: center;
- align-items: center;
- min-height: 100vh;
- background: #18181b;
- color: #fafafa;
- padding: 1rem;
- }
- .container {
- text-align: center;
- background: #27272a;
- padding: 3rem 2rem;
- border-radius: 0.625rem;
- border: 1px solid rgba(255, 255, 255, 0.1);
- max-width: 720px;
- width: 100%;
- }
- h1 {
- color: #fafafa;
- font-size: 1.5rem;
- font-weight: 600;
- margin-bottom: 0.75rem;
- }
- p {
- color: #9ca3af;
- font-size: 0.95rem;
- line-height: 1.5;
- white-space: pre-wrap;
- word-break: break-word;
- }
- p + p { margin-top: 0.5rem; }
- .details {
- color: #d4d4d8;
- text-align: left;
- font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
- font-size: 0.8rem;
- line-height: 1.45;
- margin-top: 1.25rem;
- padding: 0.875rem 1rem;
- background: #0f0f11;
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: 0.5rem;
- white-space: pre-wrap;
- word-break: break-word;
- overflow-x: auto;
- }
- .request-id {
- color: #6b7280;
- font-size: 0.75rem;
- margin-top: 1rem;
- font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
- }
- </style>
-</head>
-<body>
- <div class="container">
- <h1>${heading}</h1>
- <p>${message}</p>
- ${detailsBlock}
- ${requestIdBlock}
- </div>
-</body>
-</html>`;
-}
-
-function rewriteOPKSSHHtml(
- html: string,
- requestId: string,
- routePrefix: "opkssh-chooser" | "opkssh-callback",
-): string {
- const basePath = `/host/${routePrefix}/${requestId}`;
- const localHostPattern = "(?:localhost|127\\.0\\.0\\.1)";
-
- const attrPatterns = ["action", "href", "src", "formaction"];
- for (const attr of attrPatterns) {
- html = html.replace(
- new RegExp(`${attr}="(/[^"]*)`, "g"),
- `${attr}="${basePath}$1`,
- );
- html = html.replace(
- new RegExp(`${attr}='(/[^']*)`, "g"),
- `${attr}='${basePath}$1`,
- );
- }
-
- for (const attr of ["href", "action", "src", "formaction"]) {
- html = html.replace(
- new RegExp(
- `${attr}=["']?http:\\/\\/${localHostPattern}:\\d+\\/([^"'\\s]*)`,
- "g",
- ),
- `${attr}="${basePath}/$1`,
- );
- }
-
- html = html.replace(
- new RegExp(
- `(window\\.location\\.href\\s*=\\s*["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["'])`,
- "g",
- ),
- `$1${basePath}/$2$3`,
- );
- html = html.replace(
- new RegExp(
- `(window\\.location\\s*=\\s*["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["'])`,
- "g",
- ),
- `$1${basePath}/$2$3`,
- );
- html = html.replace(
- new RegExp(
- `(fetch\\(["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["'])`,
- "g",
- ),
- `$1${basePath}/$2$3`,
- );
-
- html = html.replace(
- new RegExp(
- `(location\\.assign\\(["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["']\\))`,
- "g",
- ),
- `$1${basePath}/$2$3`,
- );
- html = html.replace(
- new RegExp(
- `(location\\.replace\\(["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["']\\))`,
- "g",
- ),
- `$1${basePath}/$2$3`,
- );
-
- // XMLHttpRequest.open("GET", "http://localhost:PORT/path", ...)
- html = html.replace(
- new RegExp(
- `(\\.open\\(["']\\w+["']\\s*,\\s*["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["'])`,
- "g",
- ),
- `$1${basePath}/$2$3`,
- );
-
- html = html.replace(
- new RegExp(
- `(<meta[^>]+http-equiv=["']refresh["'][^>]+content=["'][^;]+;\\s*url=)http:\\/\\/${localHostPattern}:\\d+\\/([^"']+)(["'][^>]*>)`,
- "gi",
- ),
- `$1${basePath}/$2$3`,
- );
-
- html = html.replace(
- new RegExp(
- `(data-[\\w-]+=["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["'])`,
- "g",
- ),
- `$1${basePath}/$2$3`,
- );
-
- const baseTag = `<base href="${basePath}/">`;
-
- if (html.includes("<base")) {
- sshLogger.info("Replacing existing base tag", {
- operation: "opkssh_html_rewrite_base_tag",
- requestId,
- basePath,
- });
- html = html.replace(/<base[^>]*>/i, baseTag);
- } else if (html.includes("<head>")) {
- sshLogger.info("Inserting base tag into head", {
- operation: "opkssh_html_rewrite_base_tag_insert",
- requestId,
- basePath,
- });
- html = html.replace(/<head>/i, `<head>${baseTag}`);
- } else {
- sshLogger.warn("No <head> tag found, wrapping HTML", {
- operation: "opkssh_html_rewrite_no_head",
- requestId,
- htmlLength: html.length,
- htmlPreview: html.substring(0, 200),
- });
- html = `<!DOCTYPE html><html><head>${baseTag}</head><body>${html}</body></html>`;
- }
-
- sshLogger.info("HTML rewrite complete", {
- operation: "opkssh_html_rewrite_complete",
- requestId,
- routePrefix,
- hasBaseTag: html.includes("<base href="),
- staticAssetCount: (html.match(/\/static\//g) || []).length,
- });
-
- return html;
-}
-
-/**
- * @openapi
- * /host/opkssh-chooser/{requestId}:
- * get:
- * summary: Proxy OPKSSH provider chooser page and all related resources
- * tags: [SSH]
- * parameters:
- * - name: requestId
- * in: path
- * required: true
- * schema:
- * type: string
- * description: Authentication request ID
- * responses:
- * 200:
- * description: Chooser page content
- * 404:
- * description: Session not found
- * 500:
- * description: Proxy error
- */
-
-router.use(
- "/opkssh-chooser/:requestId",
- async (req: Request, res: Response) => {
- const requestId = Array.isArray(req.params.requestId)
- ? req.params.requestId[0]
- : req.params.requestId;
-
- const fullPath = req.originalUrl || req.url;
- const pathAfterRequestIdTemp =
- fullPath.split(`/host/opkssh-chooser/${requestId}`)[1] || "";
-
- sshLogger.info("OPKSSH chooser proxy request", {
- operation: "opkssh_chooser_proxy_request",
- requestId,
- url: req.url,
- originalUrl: req.originalUrl,
- fullPath,
- pathAfterRequestId: pathAfterRequestIdTemp,
- method: req.method,
- });
-
- try {
- const { getActiveAuthSession, registerOAuthState } =
- await import("../../ssh/opkssh-auth.js");
- const session = getActiveAuthSession(requestId);
-
- if (!session) {
- sshLogger.error("Session not found for chooser request", {
- operation: "opkssh_chooser_session_not_found",
- requestId,
- });
- res.status(404).send(
- renderOpksshErrorPage({
- title: "Session Not Found",
- heading: "Session Not Found",
- message: "This authentication session has expired or is invalid.",
- requestId,
- }),
- );
- return;
- }
-
- const axios = (await import("axios")).default;
-
- const fullPath = req.originalUrl || req.url;
- const pathAfterRequestId =
- fullPath.split(`/host/opkssh-chooser/${requestId}`)[1] || "";
- const targetPath = pathAfterRequestId || "/chooser";
-
- if (!session.localPort || session.localPort === 0) {
- sshLogger.error("OPKSSH session has no local port", {
- operation: "opkssh_chooser_proxy",
- requestId,
- sessionStatus: session.status,
- });
- res.status(500).send(
- renderOpksshErrorPage({
- title: "Error",
- heading: "Authentication Error",
- message:
- "Failed to load authentication page. OPKSSH process may not be ready yet. Please try again.",
- requestId,
- }),
- );
- return;
- }
-
- // /select on OPKSSH's chooser redirects (possibly via multiple local hops) to the
- // external OAuth provider URL. The hops we may see:
- // 1. /select -> /select/ (Go ServeMux canonicalization, same chooser port)
- // 2. /select/?op=ALIAS -> http://localhost:CALLBACK_PORT/login (OPKSSH's separate callback listener)
- // 3. /login on the callback listener -> https://<provider>/authorize?... (external OAuth URL)
- if (targetPath.startsWith("/select")) {
- const selectaxios = (await import("axios")).default;
- const rawQs = targetPath.includes("?")
- ? targetPath.slice(targetPath.indexOf("?"))
- : "";
-
- let qs = rawQs;
- let opMappedFrom: string | undefined;
- if (rawQs) {
- try {
- const params = new URLSearchParams(rawQs.replace(/^\?/, ""));
- const rawOp = params.get("op");
- if (rawOp) {
- const mappedOp = normalizeSelectOpParam(
- rawOp,
- session.providers || [],
- );
- if (mappedOp !== rawOp) {
- params.set("op", mappedOp);
- qs = `?${params.toString()}`;
- opMappedFrom = rawOp;
- }
- }
- } catch {
- /* keep rawQs if parsing fails */
- }
- }
-
- const chooserHost = `127.0.0.1:${session.localPort}`;
- const startUrl = `http://${chooserHost}/select/${qs}`;
-
- sshLogger.info("Proxying OPKSSH /select", {
- operation: "opkssh_select_proxy",
- requestId,
- targetUrl: startUrl,
- opMappedFrom,
- });
-
- const isLocalHostname = (host: string): boolean => {
- const bare = host.split(":")[0];
- return (
- bare === "127.0.0.1" || bare === "localhost" || bare === "[::1]"
- );
- };
-
- interface UpstreamResponse {
- status: number;
- location?: string;
- contentType: string;
- body: string;
- targetUrl: string;
- elapsedMs: number;
- }
-
- const fetchUpstream = async (
- url: string,
- ): Promise<UpstreamResponse> => {
- const started = Date.now();
- let hostHeader = chooserHost;
- try {
- hostHeader = new URL(url).host;
- } catch {
- /* fall back to chooser host */
- }
- const r = await selectaxios({
- method: "GET",
- url,
- maxRedirects: 0,
- validateStatus: () => true,
- timeout: 10000,
- responseType: "text",
- transformResponse: (v) => v,
- headers: { host: hostHeader },
- });
- const locHeader = r.headers["location"];
- const location = Array.isArray(locHeader) ? locHeader[0] : locHeader;
- const ctHeader = r.headers["content-type"];
- const ctRaw = Array.isArray(ctHeader) ? ctHeader[0] : ctHeader;
- const contentType = typeof ctRaw === "string" ? ctRaw : "";
- const body =
- typeof r.data === "string" ? r.data : String(r.data ?? "");
- return {
- status: r.status,
- location: typeof location === "string" ? location : undefined,
- contentType,
- body,
- targetUrl: url,
- elapsedMs: Date.now() - started,
- };
- };
-
- const logResponse = (response: UpstreamResponse): void => {
- sshLogger.info("OPKSSH /select upstream response", {
- operation: "opkssh_select_upstream_response",
- requestId,
- targetUrl: response.targetUrl,
- status: response.status,
- location: response.location,
- contentType: response.contentType,
- elapsedMs: response.elapsedMs,
- bodyPreview: response.body.slice(0, 256),
- });
- };
-
- const MAX_HOPS = 4;
-
- try {
- let response = await fetchUpstream(startUrl);
- logResponse(response);
-
- for (let hop = 0; hop < MAX_HOPS; hop++) {
- if (
- response.status < 300 ||
- response.status >= 400 ||
- !response.location
- ) {
- break;
- }
- const loc = response.location;
-
- // Relative path: resolve against the current upstream.
- if (loc.startsWith("/")) {
- let currentHost = chooserHost;
- try {
- currentHost = new URL(response.targetUrl).host;
- } catch {
- /* keep default */
- }
- response = await fetchUpstream(`http://${currentHost}${loc}`);
- logResponse(response);
- continue;
- }
-
- // Absolute URL: if it points to a localhost OPKSSH endpoint, capture
- // the port. Then redirect the BROWSER to the proxied path so that
- // Set-Cookie headers from OPKSSH's /login handler reach the browser
- // directly — following them server-side would swallow the cookie.
- if (/^https?:\/\//i.test(loc)) {
- try {
- const parsed = new URL(loc);
- if (isLocalHostname(parsed.host)) {
- // Capture callback listener port if not yet known.
- if (!session.callbackPort) {
- const port = parseInt(parsed.port, 10);
- if (!Number.isNaN(port)) {
- session.callbackPort = port;
- sshLogger.info(
- "Captured OPKSSH callback listener port from /select redirect",
- {
- operation: "opkssh_select_callback_port_detected",
- requestId,
- callbackPort: port,
- },
- );
- }
- }
- // Redirect browser through the chooser proxy so it can receive
- // the state cookie that OPKSSH sets on /login.
- const browserPath = `/host/opkssh-chooser/${requestId}${parsed.pathname}${parsed.search}`;
- sshLogger.info(
- "Redirecting browser to OPKSSH callback listener via proxy",
- {
- operation: "opkssh_select_browser_redirect_to_login",
- requestId,
- browserPath,
- callbackPort: session.callbackPort,
- },
- );
- res.redirect(302, browserPath);
- return;
- }
- // External OAuth provider URL — done, handled below.
- break;
- } catch {
- break;
- }
- }
-
- break;
- }
-
- const isExternalRedirect =
- response.status >= 300 &&
- response.status < 400 &&
- !!response.location &&
- /^https?:\/\//i.test(response.location) &&
- (() => {
- try {
- return !isLocalHostname(
- new URL(response.location as string).host,
- );
- } catch {
- return false;
- }
- })();
-
- if (isExternalRedirect) {
- const oauthUrl = response.location as string;
- try {
- const parsed = new URL(oauthUrl);
- const oauthState = parsed.searchParams.get("state");
- if (oauthState) registerOAuthState(oauthState, requestId);
- } catch {
- /* already validated above */
- }
- sshLogger.info(
- "OPKSSH /select redirecting browser to OAuth provider",
- {
- operation: "opkssh_select_redirect",
- requestId,
- oauthUrl,
- },
- );
- res.redirect(302, oauthUrl);
- return;
- }
-
- const bodyPreview = response.body.slice(0, 512);
- const detailLines = [
- `Upstream: ${response.targetUrl}`,
- `Status: ${response.status}`,
- response.location ? `Location: ${response.location}` : undefined,
- `Content-Type: ${response.contentType || "(none)"}`,
- `Elapsed: ${response.elapsedMs}ms`,
- "",
- bodyPreview
- ? `Body (first 512 chars):\n${bodyPreview}`
- : "Body: (empty)",
- ].filter(Boolean) as string[];
-
- sshLogger.error("OPKSSH /select did not produce an OAuth redirect", {
- operation: "opkssh_select_no_oauth_redirect",
- requestId,
- status: response.status,
- location: response.location,
- contentType: response.contentType,
- bodyPreview,
- });
-
- res.status(502).send(
- renderOpksshErrorPage({
- title: "OPKSSH error",
- heading: "Failed to get OAuth redirect",
- message:
- "OPKSSH did not return an external OAuth provider URL. " +
- "This typically indicates a configuration mismatch between the provider's redirect_uris " +
- "and the Termix callback path. Check the server log for the OPKSSH response body.",
- details: detailLines.join("\n"),
- requestId,
- }),
- );
- } catch (err) {
- sshLogger.error("Error proxying OPKSSH /select", err, {
- operation: "opkssh_select_proxy_error",
- requestId,
- targetUrl: startUrl,
- });
- const errMsg = err instanceof Error ? err.message : String(err);
- res.status(502).send(
- renderOpksshErrorPage({
- title: "OPKSSH error",
- heading: "Failed to reach OPKSSH service",
- message:
- "Termix could not connect to the local OPKSSH authentication service. " +
- "The OPKSSH process may have exited or is not listening yet.",
- details: `Upstream: ${startUrl}\nError: ${errMsg}`,
- requestId,
- }),
- );
- }
- return;
- }
-
- // Paths served by the callback listener, not the chooser.
- // The browser is redirected here so it receives Set-Cookie from OPKSSH.
- const isCallbackListenerPath =
- targetPath === "/login" ||
- targetPath.startsWith("/login?") ||
- targetPath === "/login-callback" ||
- targetPath.startsWith("/login-callback?");
-
- const upstreamPort =
- isCallbackListenerPath && session.callbackPort
- ? session.callbackPort
- : session.localPort;
-
- const targetUrl = `http://127.0.0.1:${upstreamPort}${targetPath}`;
-
- sshLogger.info("Proxying to OPKSSH chooser", {
- operation: "opkssh_chooser_proxy_request_to_opkssh",
- requestId,
- targetUrl,
- upstreamPort,
- targetPath,
- });
-
- const response = await axios({
- method: req.method,
- url: targetUrl,
- headers: {
- ...req.headers,
- host: `127.0.0.1:${upstreamPort}`,
- },
- data: req.body,
- timeout: 10000,
- validateStatus: () => true,
- maxRedirects: 0,
- responseType: "arraybuffer",
- });
-
- sshLogger.info("OPKSSH chooser response received", {
- operation: "opkssh_chooser_proxy_response",
- requestId,
- statusCode: response.status,
- contentType: response.headers["content-type"],
- contentLength: response.headers["content-length"],
- hasLocation: !!response.headers.location,
- });
-
- Object.entries(response.headers).forEach(([key, value]) => {
- if (key.toLowerCase() === "transfer-encoding") {
- return;
- }
- if (key.toLowerCase() === "location") {
- const location = value as string;
- if (location.startsWith("/")) {
- res.setHeader(key, `/host/opkssh-chooser/${requestId}${location}`);
- } else {
- const localhostMatch = location.match(
- /^http:\/\/(?:localhost|127\.0\.0\.1):(\d+)(\/.*)?$/,
- );
- if (localhostMatch) {
- const port = parseInt(localhostMatch[1], 10);
- const path = localhostMatch[2] || "/";
- if (session.callbackPort && port === session.callbackPort) {
- res.setHeader(key, `/host/opkssh-callback/${requestId}${path}`);
- } else if (port === session.localPort) {
- res.setHeader(key, `/host/opkssh-chooser/${requestId}${path}`);
- } else {
- const isCallback =
- path.includes("login") || path.includes("callback");
- const prefix = isCallback
- ? "opkssh-callback"
- : "opkssh-chooser";
- res.setHeader(key, `/host/${prefix}/${requestId}${path}`);
- }
- } else {
- // External redirect (e.g. to OIDC provider) — capture OAuth state for session binding
- try {
- const redirectUrl = new URL(location);
- const oauthState = redirectUrl.searchParams.get("state");
- if (oauthState) {
- registerOAuthState(oauthState, requestId);
- }
- } catch {
- // Not a valid URL, skip state capture
- }
- res.setHeader(key, value as string);
- }
- }
- } else if (key.toLowerCase() === "set-cookie") {
- // Rewrite cookies from OPKSSH's internal listener so they are scoped
- // to the Termix proxy path instead of OPKSSH's internal path.
- // The state cookie set by /login must survive to /login-callback.
- const cookies = Array.isArray(value) ? value : [value as string];
- const rewritten = cookies.map((cookie) => {
- return cookie
- .replace(/;\s*domain=[^;]*/gi, "")
- .replace(/;\s*path=[^;]*/gi, "; Path=/host/opkssh-callback/")
- .concat(
- cookie.match(/;\s*path=/i)
- ? ""
- : "; Path=/host/opkssh-callback/",
- );
- });
- res.setHeader(key, rewritten);
- } else {
- res.setHeader(key, value as string);
- }
- });
-
- // Set a cookie to correlate this browser with the requestId.
- // OAuth state capture from Location headers only works for 3xx redirects;
- // if OPKSSH redirects via JavaScript, the state is never registered.
- // This cookie survives the OIDC round-trip and identifies the session on callback.
- res.cookie("opkssh_request_id", requestId, {
- path: "/host/",
- httpOnly: true,
- sameSite: "lax",
- maxAge: 5 * 60 * 1000,
- });
-
- const contentType = String(response.headers["content-type"] || "");
- if (contentType.includes("text/html")) {
- const html = rewriteOPKSSHHtml(
- response.data.toString("utf-8"),
- requestId,
- "opkssh-chooser",
- );
- res.status(response.status).send(html);
- } else {
- res.status(response.status).send(response.data);
- }
- } catch (error) {
- sshLogger.error("Error proxying OPKSSH chooser", error, {
- operation: "opkssh_chooser_proxy_error",
- requestId,
- });
- res.status(500).send(
- renderOpksshErrorPage({
- title: "Error",
- heading: "Error",
- message: "Failed to load authentication page. Please try again.",
- requestId,
- }),
- );
- }
- },
-);
-
-/**
- * @openapi
- * /host/opkssh-callback:
- * get:
- * summary: Static OAuth callback from OIDC provider for OPKSSH authentication
- * tags: [SSH]
- * responses:
- * 200:
- * description: Callback processed successfully
+ * description: Token status retrieved successfully
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * exists:
+ * type: boolean
+ * description: Whether a valid token exists
+ * expiresAt:
+ * type: string
+ * format: date-time
+ * description: Token expiration timestamp
+ * email:
+ * type: string
+ * description: User email from OIDC identity
* 404:
- * description: No active authentication session found
+ * description: No valid token found
* 500:
- * description: Authentication failed
+ * description: Internal server error
*/
-router.get("/opkssh-callback", async (req: Request, res: Response) => {
- try {
- sshLogger.info("OAuth callback received", {
- operation: "opkssh_static_callback_received",
- host: req.headers.host,
- });
-
- const {
- getUserIdFromRequest,
- getActiveSessionsForUser,
- getActiveAuthSession,
- getRequestIdByOAuthState,
- clearOAuthState,
- } = await import("../../ssh/opkssh-auth.js");
-
- const userId = await getUserIdFromRequest({
- cookies: req.cookies,
- headers: req.headers as Record<string, string | undefined>,
- });
+router.get(
+ "/ssh/opkssh/token/:hostId",
+ authenticateJWT,
+ requireDataAccess,
+ async (req: AuthenticatedRequest, res: Response) => {
+ const userId = req.userId;
+ const hostId = parseInt(
+ Array.isArray(req.params.hostId)
+ ? req.params.hostId[0]
+ : req.params.hostId,
+ );
- sshLogger.info("User ID resolved", {
- operation: "opkssh_callback_user_lookup",
- userId: userId || "null",
- hasCookies: !!req.cookies?.jwt,
- cookieKeys: Object.keys(req.cookies || {}),
- });
+ if (!userId || isNaN(hostId)) {
+ return res.status(400).json({ error: "Invalid request" });
+ }
- let userSessions: Awaited<ReturnType<typeof getActiveSessionsForUser>> = [];
+ try {
+ const { opksshTokens } = await import("../db/schema.js");
+ const token = await db
+ .select()
+ .from(opksshTokens)
+ .where(
+ and(eq(opksshTokens.userId, userId), eq(opksshTokens.hostId, hostId)),
+ )
+ .limit(1);
- if (userId) {
- userSessions = getActiveSessionsForUser(userId);
- } else {
- // No JWT cookie (e.g. OAuth redirect landed in external browser).
- // Try to find the correct session via the OAuth state parameter.
- const oauthState = req.query.state as string | undefined;
-
- if (oauthState) {
- const mappedRequestId = getRequestIdByOAuthState(oauthState);
- if (mappedRequestId) {
- const mappedSession = getActiveAuthSession(mappedRequestId);
- if (mappedSession) {
- userSessions = [mappedSession];
- clearOAuthState(oauthState);
- sshLogger.info("Resolved session via OAuth state parameter", {
- operation: "opkssh_callback_state_lookup",
- requestId: mappedRequestId,
- });
- }
- }
+ if (!token || token.length === 0) {
+ return res.status(404).json({ exists: false });
}
- // Fallback: use the opkssh_request_id cookie set by the chooser proxy.
- // State capture only works for 3xx redirects; if OPKSSH redirects via
- // JavaScript in the HTML, the state is never registered in the map.
- if (userSessions.length === 0) {
- const cookieRequestId = req.cookies?.opkssh_request_id;
- if (cookieRequestId) {
- const cookieSession = getActiveAuthSession(cookieRequestId);
- if (cookieSession) {
- userSessions = [cookieSession];
- res.clearCookie("opkssh_request_id", { path: "/host/" });
- sshLogger.info("Resolved session via opkssh_request_id cookie", {
- operation: "opkssh_callback_cookie_lookup",
- requestId: cookieRequestId,
- });
- }
- }
- }
+ const tokenData = token[0];
+ const expiresAt = new Date(tokenData.expiresAt);
- if (userSessions.length === 0) {
- sshLogger.warn(
- "OAuth callback with no JWT, no matching state, and no session cookie",
- {
- operation: "opkssh_callback_no_session_match",
- hasState: !!oauthState,
- hasCookie: !!req.cookies?.opkssh_request_id,
- },
- );
- res
- .status(401)
- .send("Authentication callback failed: unable to identify session");
- return;
+ if (expiresAt < new Date()) {
+ await db
+ .delete(opksshTokens)
+ .where(
+ and(
+ eq(opksshTokens.userId, userId),
+ eq(opksshTokens.hostId, hostId),
+ ),
+ );
+ return res.status(404).json({ exists: false });
}
- }
-
- sshLogger.info("Active sessions for user", {
- operation: "opkssh_callback_session_lookup",
- userId,
- sessionCount: userSessions.length,
- sessions: userSessions.map((s) => ({
- requestId: s.requestId,
- status: s.status,
- hasCallbackPort: !!s.callbackPort,
- callbackPort: s.callbackPort,
- hasLocalPort: !!s.localPort,
- localPort: s.localPort,
- })),
- });
- if (userSessions.length === 0) {
- sshLogger.error("No active sessions for callback", {
- operation: "opkssh_callback_no_sessions",
- userId,
+ res.json({
+ exists: true,
+ expiresAt: tokenData.expiresAt,
+ email: tokenData.email,
});
- res.status(404).send("No active authentication session found");
- return;
- }
-
- const session = userSessions[userSessions.length - 1];
-
- if (!session.callbackPort) {
- sshLogger.error("Session callback port not ready", {
- operation: "opkssh_callback_port_not_ready",
+ } catch (error) {
+ sshLogger.error("Error retrieving OPKSSH token status", error, {
+ operation: "opkssh_token_status_error",
userId,
- requestId: session.requestId,
- sessionStatus: session.status,
- hasLocalPort: !!session.localPort,
+ hostId,
});
- res.status(503).send("OPKSSH callback listener not ready yet");
- return;
+ res.status(500).json({ error: "Internal server error" });
}
-
- const queryString = req.url.includes("?")
- ? req.url.substring(req.url.indexOf("?"))
- : "";
- // OPKSSH's internal callback listener handles `/login-callback` regardless of the
- // path used in --remote-redirect-uri. The dynamic route below defaults to that path.
- const redirectUrl = `/host/opkssh-callback/${session.requestId}${queryString}`;
-
- sshLogger.info("Redirecting OAuth callback to dynamic route", {
- operation: "opkssh_static_callback_redirect",
- userId,
- requestId: session.requestId,
- callbackPort: session.callbackPort,
- queryParams: Object.keys(req.query),
- redirectUrl,
- });
-
- res.redirect(302, redirectUrl);
- } catch (error) {
- sshLogger.error("Error handling OPKSSH static callback", error, {
- operation: "opkssh_static_callback_error",
- url: req.url,
- originalUrl: req.originalUrl,
- });
- res.status(500).send("Authentication callback failed");
- }
-});
+ },
+);
/**
* @openapi
- * /host/opkssh-callback/{requestId}:
- * get:
- * summary: OAuth callback from OIDC provider for OPKSSH authentication (handles all sub-paths)
+ * /host/opkssh/token/{hostId}:
+ * delete:
+ * summary: Delete OPKSSH token for a host
* tags: [SSH]
+ * security:
+ * - bearerAuth: []
* parameters:
- * - name: requestId
+ * - name: hostId
* in: path
* required: true
* schema:
- * type: string
- * description: Authentication request ID
- * responses:
- * 200:
- * description: Callback processed successfully
- * 404:
- * description: Invalid authentication session
- * 500:
- * description: Authentication failed
- */
-router.use(
- "/opkssh-callback/:requestId",
- async (req: Request, res: Response) => {
- const requestId = Array.isArray(req.params.requestId)
- ? req.params.requestId[0]
- : req.params.requestId;
-
- try {
- const { getActiveAuthSession } = await import("../../ssh/opkssh-auth.js");
- const session = getActiveAuthSession(requestId);
-
- if (!session) {
- res.status(404).send(
- renderOpksshErrorPage({
- title: "Session Not Found",
- heading: "Session Not Found",
- message:
- "Authentication session expired or invalid. Please close this window and try again.",
- requestId,
- }),
- );
- return;
- }
-
- const axios = (await import("axios")).default;
- const fullPath = req.originalUrl || req.url;
- const pathAfterRequestId =
- fullPath.split(`/host/opkssh-callback/${requestId}`)[1] || "";
- // pathAfterRequestId may be "", "?query=...", "/subpath", or "/subpath?query=..."
- // OPKSSH's internal listener serves /login-callback, so when no sub-path is present
- // (query-only or empty), prepend it.
- const targetPath =
- pathAfterRequestId === "" || pathAfterRequestId.startsWith("?")
- ? `/login-callback${pathAfterRequestId}`
- : pathAfterRequestId;
-
- if (!session.callbackPort || session.callbackPort === 0) {
- sshLogger.error("OPKSSH callback session has no callback port", {
- operation: "opkssh_callback_proxy",
- requestId,
- sessionStatus: session.status,
- });
- res.status(500).send(
- renderOpksshErrorPage({
- title: "Error",
- heading: "Callback Error",
- message:
- "OPKSSH callback listener not ready. Please try authenticating again.",
- requestId,
- }),
- );
- return;
- }
-
- const targetUrl = `http://127.0.0.1:${session.callbackPort}${targetPath}`;
-
- const response = await axios({
- method: req.method,
- url: targetUrl,
- headers: {
- ...req.headers,
- host: `127.0.0.1:${session.callbackPort}`,
- },
- data: req.body,
- timeout: 10000,
- validateStatus: () => true,
- maxRedirects: 0,
- responseType: "arraybuffer",
- });
-
- Object.entries(response.headers).forEach(([key, value]) => {
- if (key.toLowerCase() === "transfer-encoding") {
- return;
- }
- if (key.toLowerCase() === "location") {
- const location = value as string;
- if (location.startsWith("/")) {
- res.setHeader(key, `/host/opkssh-callback/${requestId}${location}`);
- } else {
- res.setHeader(key, value as string);
- }
- } else {
- res.setHeader(key, value as string);
- }
- });
-
- const contentType = String(response.headers["content-type"] || "");
- if (contentType.includes("text/html")) {
- const html = rewriteOPKSSHHtml(
- response.data.toString("utf-8"),
- requestId,
- "opkssh-callback",
- );
- res.status(response.status).send(html);
- } else {
- res.status(response.status).send(response.data);
- }
- } catch (error) {
- sshLogger.error("Error handling OPKSSH OAuth callback", error, {
- operation: "opkssh_oauth_callback_error",
- requestId,
- });
-
- res.status(500).send(
- renderOpksshErrorPage({
- title: "Error",
- heading: "Error",
- message: "An unexpected error occurred. Please try again.",
- requestId,
- }),
- );
- }
- },
-);
-
-/**
- * @openapi
- * /host/db/proxy/test:
- * post:
- * summary: Test proxy connectivity
- * description: Tests connectivity through a proxy configuration to a target host.
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * singleProxy:
- * type: object
- * properties:
- * host:
- * type: string
- * port:
- * type: number
- * type:
- * type: string
- * username:
- * type: string
- * password:
- * type: string
- * proxyChain:
- * type: array
- * items:
- * type: object
- * testTarget:
- * type: object
- * properties:
- * host:
- * type: string
- * port:
- * type: number
+ * type: integer
+ * description: Host ID
* responses:
* 200:
- * description: Test result
+ * description: Token deleted successfully
* 500:
- * description: Proxy connection failed
+ * description: Internal server error
*/
-router.post(
- "/db/proxy/test",
+router.delete(
+ "/ssh/opkssh/token/:hostId",
authenticateJWT,
requireDataAccess,
async (req: AuthenticatedRequest, res: Response) => {
- try {
- const { singleProxy, proxyChain, testTarget } = req.body;
-
- const { testProxyConnectivity } =
- await import("../../utils/proxy-helper.js");
-
- const result = await testProxyConnectivity({
- singleProxy,
- proxyChain,
- testTarget,
- });
+ const userId = req.userId;
+ const hostId = parseInt(
+ Array.isArray(req.params.hostId)
+ ? req.params.hostId[0]
+ : req.params.hostId,
+ );
- res.json(result);
- } catch (error) {
- sshLogger.error("Proxy connectivity test failed", error, {
- operation: "proxy_test",
- userId: req.userId,
- });
- res.status(500).json({
- success: false,
- error: error instanceof Error ? error.message : "Unknown error",
- });
+ if (!userId || isNaN(hostId)) {
+ return res.status(400).json({ error: "Invalid request" });
}
- },
-);
-
-router.post(
- "/db/host/:id/wake",
- authenticateJWT,
- requireDataAccess,
- async (req: Request, res: Response) => {
- const hostId = Number.parseInt(String(req.params.id), 10);
- const userId = (req as AuthenticatedRequest).userId;
try {
- const host = await db
- .select({ macAddress: hosts.macAddress })
- .from(hosts)
- .where(and(eq(hosts.id, hostId), eq(hosts.userId, userId)))
- .then((rows) => rows[0]);
-
- if (!host) {
- return res.status(404).json({ error: "Host not found" });
- }
-
- if (!host.macAddress || !isValidMac(host.macAddress)) {
- return res
- .status(400)
- .json({ error: "No valid MAC address configured" });
- }
-
- await sendWakeOnLan(host.macAddress);
-
- sshLogger.info("Wake-on-LAN packet sent", {
- operation: "wake_on_lan",
- userId,
- hostId,
- });
-
+ const { deleteOPKSSHToken } = await import("../../ssh/opkssh-auth.js");
+ await deleteOPKSSHToken(userId, hostId);
res.json({ success: true });
} catch (error) {
- sshLogger.error("Wake-on-LAN failed", error, {
- operation: "wake_on_lan",
+ sshLogger.error("Error deleting OPKSSH token", error, {
+ operation: "opkssh_token_delete_error",
userId,
hostId,
});
- res.status(500).json({
- error:
- error instanceof Error ? error.message : "Failed to send WoL packet",
- });
+ res.status(500).json({ error: "Internal server error" });
}
},
);
+registerHostOpksshRoutes(router);
+
+registerHostNetworkRoutes(router, {
+ authenticateJWT,
+ requireDataAccess,
+});
+
export default router;
diff --git a/src/backend/database/routes/open-tabs.ts b/src/backend/database/routes/open-tabs.ts
index 24b0df8c9..70c9c4445 100644
--- a/src/backend/database/routes/open-tabs.ts
+++ b/src/backend/database/routes/open-tabs.ts
@@ -32,12 +32,20 @@ router.get("/", authenticateJWT, async (req: Request, res: Response) => {
const tabs = db
.select()
.from(userOpenTabs)
- .where(and(eq(userOpenTabs.userId, userId), sql`${userOpenTabs.updatedAt} > ${cutoff}`))
+ .where(
+ and(
+ eq(userOpenTabs.userId, userId),
+ sql`${userOpenTabs.updatedAt} > ${cutoff}`,
+ ),
+ )
.orderBy(userOpenTabs.tabOrder)
.all();
return res.json(tabs);
} catch (e) {
- databaseLogger.error("Failed to get open tabs", e, { operation: "get_open_tabs", userId });
+ databaseLogger.error("Failed to get open tabs", e, {
+ operation: "get_open_tabs",
+ userId,
+ });
return res.status(500).json({ error: "Failed to get open tabs" });
}
});
@@ -77,35 +85,67 @@ router.get("/", authenticateJWT, async (req: Request, res: Response) => {
*/
router.post("/", authenticateJWT, async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
- const { id, tabType, hostId, label, tabOrder, backendSessionId } = req.body as {
- id: string;
- tabType: string;
- hostId?: number | null;
- label: string;
- tabOrder: number;
- backendSessionId?: string | null;
- };
+ const { id, tabType, hostId, label, tabOrder, backendSessionId } =
+ req.body as {
+ id: string;
+ tabType: string;
+ hostId?: number | null;
+ label: string;
+ tabOrder: number;
+ backendSessionId?: string | null;
+ };
if (!id || !tabType || !label) {
- return res.status(400).json({ error: "id, tabType, and label are required" });
+ return res
+ .status(400)
+ .json({ error: "id, tabType, and label are required" });
}
try {
const now = new Date().toISOString();
- const existing = db.select().from(userOpenTabs).where(and(eq(userOpenTabs.id, id), eq(userOpenTabs.userId, userId))).all();
+ const existing = db
+ .select()
+ .from(userOpenTabs)
+ .where(and(eq(userOpenTabs.id, id), eq(userOpenTabs.userId, userId)))
+ .all();
if (existing.length > 0) {
// Preserve existing backendSessionId when not explicitly provided
- const sessionId = backendSessionId !== undefined ? backendSessionId : existing[0].backendSessionId;
+ const sessionId =
+ backendSessionId !== undefined
+ ? backendSessionId
+ : existing[0].backendSessionId;
db.update(userOpenTabs)
- .set({ tabType, hostId: hostId ?? null, label, tabOrder, backendSessionId: sessionId ?? null, updatedAt: now })
+ .set({
+ tabType,
+ hostId: hostId ?? null,
+ label,
+ tabOrder,
+ backendSessionId: sessionId ?? null,
+ updatedAt: now,
+ })
.where(and(eq(userOpenTabs.id, id), eq(userOpenTabs.userId, userId)))
.run();
} else {
- db.insert(userOpenTabs).values({ id, userId, tabType, hostId: hostId ?? null, label, tabOrder, backendSessionId: backendSessionId ?? null, updatedAt: now }).run();
+ db.insert(userOpenTabs)
+ .values({
+ id,
+ userId,
+ tabType,
+ hostId: hostId ?? null,
+ label,
+ tabOrder,
+ backendSessionId: backendSessionId ?? null,
+ updatedAt: now,
+ })
+ .run();
}
return res.json({ success: true });
} catch (e) {
- databaseLogger.error("Failed to upsert open tab", e, { operation: "upsert_open_tab", userId, id });
+ databaseLogger.error("Failed to upsert open tab", e, {
+ operation: "upsert_open_tab",
+ userId,
+ id,
+ });
return res.status(500).json({ error: "Failed to upsert open tab" });
}
});
@@ -151,22 +191,27 @@ router.put("/", authenticateJWT, async (req: Request, res: Response) => {
db.delete(userOpenTabs).where(eq(userOpenTabs.userId, userId)).run();
if (tabs.length > 0) {
const now = new Date().toISOString();
- db.insert(userOpenTabs).values(
- tabs.map((t) => ({
- id: t.id,
- userId,
- tabType: t.tabType,
- hostId: t.hostId ?? null,
- label: t.label,
- tabOrder: t.tabOrder,
- backendSessionId: t.backendSessionId ?? null,
- updatedAt: now,
- })),
- ).run();
+ db.insert(userOpenTabs)
+ .values(
+ tabs.map((t) => ({
+ id: t.id,
+ userId,
+ tabType: t.tabType,
+ hostId: t.hostId ?? null,
+ label: t.label,
+ tabOrder: t.tabOrder,
+ backendSessionId: t.backendSessionId ?? null,
+ updatedAt: now,
+ })),
+ )
+ .run();
}
return res.json({ success: true });
} catch (e) {
- databaseLogger.error("Failed to sync open tabs", e, { operation: "sync_open_tabs", userId });
+ databaseLogger.error("Failed to sync open tabs", e, {
+ operation: "sync_open_tabs",
+ userId,
+ });
return res.status(500).json({ error: "Failed to sync open tabs" });
}
});
@@ -211,7 +256,11 @@ router.patch("/:id", authenticateJWT, async (req: Request, res: Response) => {
}
return res.json({ success: true });
} catch (e) {
- databaseLogger.error("Failed to update open tab", e, { operation: "update_open_tab", userId, id });
+ databaseLogger.error("Failed to update open tab", e, {
+ operation: "update_open_tab",
+ userId,
+ id,
+ });
return res.status(500).json({ error: "Failed to update open tab" });
}
});
@@ -243,7 +292,11 @@ router.delete("/:id", authenticateJWT, async (req: Request, res: Response) => {
.run();
return res.json({ success: true });
} catch (e) {
- databaseLogger.error("Failed to delete open tab", e, { operation: "delete_open_tab", userId, id });
+ databaseLogger.error("Failed to delete open tab", e, {
+ operation: "delete_open_tab",
+ userId,
+ id,
+ });
return res.status(500).json({ error: "Failed to delete open tab" });
}
});
@@ -279,24 +332,31 @@ router.delete("/:id", authenticateJWT, async (req: Request, res: Response) => {
* createdAt:
* type: number
*/
-router.get("/active-sessions", authenticateJWT, async (req: Request, res: Response) => {
- const userId = (req as AuthenticatedRequest).userId;
- try {
- const sessions = sessionManager.getUserSessions(userId);
- return res.json(
- sessions.map((s) => ({
- sessionId: s.id,
- hostId: s.hostId,
- hostName: s.hostName,
- tabInstanceId: s.attachedTabInstanceId ?? s.tabInstanceId ?? null,
- isConnected: s.isConnected,
- createdAt: s.createdAt,
- })),
- );
- } catch (e) {
- databaseLogger.error("Failed to get active sessions", e, { operation: "get_active_sessions", userId });
- return res.status(500).json({ error: "Failed to get active sessions" });
- }
-});
+router.get(
+ "/active-sessions",
+ authenticateJWT,
+ async (req: Request, res: Response) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ try {
+ const sessions = sessionManager.getUserSessions(userId);
+ return res.json(
+ sessions.map((s) => ({
+ sessionId: s.id,
+ hostId: s.hostId,
+ hostName: s.hostName,
+ tabInstanceId: s.attachedTabInstanceId ?? s.tabInstanceId ?? null,
+ isConnected: s.isConnected,
+ createdAt: s.createdAt,
+ })),
+ );
+ } catch (e) {
+ databaseLogger.error("Failed to get active sessions", e, {
+ operation: "get_active_sessions",
+ userId,
+ });
+ return res.status(500).json({ error: "Failed to get active sessions" });
+ }
+ },
+);
export default router;
diff --git a/src/backend/database/routes/opkssh-html.ts b/src/backend/database/routes/opkssh-html.ts
new file mode 100644
index 000000000..fa94ac3a3
--- /dev/null
+++ b/src/backend/database/routes/opkssh-html.ts
@@ -0,0 +1,280 @@
+import { sshLogger } from "../../utils/logger.js";
+
+function escapeHtml(value: string): string {
+ return value
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;")
+ .replace(/'/g, "&#39;");
+}
+
+// Replicates openpubkey's client/choosers/web_chooser.go IssuerToName().
+// OPKSSH's /select handler keys its providerMap by this derived name, NOT by the
+// `alias` field in config.yml. We need the same mapping so we can normalize any
+// `op=` query param we receive (which can be alias, issuer with protocol, or
+// issuer without protocol depending on client version) to what OPKSSH expects.
+function opksshIssuerToName(issuer: string): string | null {
+ if (!issuer) return null;
+ const withScheme =
+ issuer.startsWith("http://") || issuer.startsWith("https://")
+ ? issuer
+ : `https://${issuer}`;
+ if (withScheme.startsWith("https://accounts.google.com")) return "google";
+ if (withScheme.startsWith("https://login.microsoftonline.com"))
+ return "azure";
+ if (withScheme.startsWith("https://gitlab.com")) return "gitlab";
+ if (withScheme.startsWith("https://issuer.hello.coop")) return "hello";
+ if (withScheme.startsWith("https://")) {
+ const host = withScheme.slice("https://".length).split("/")[0];
+ return host || null;
+ }
+ return null;
+}
+
+export function normalizeSelectOpParam(
+ rawOp: string,
+ providers: Array<{ alias: string; issuer: string }>,
+): string {
+ if (!rawOp) return rawOp;
+ const knownNames = new Set(
+ providers
+ .map((p) => opksshIssuerToName(p.issuer))
+ .filter((n): n is string => typeof n === "string" && n.length > 0),
+ );
+ if (knownNames.has(rawOp)) return rawOp;
+
+ const derivedFromRaw = opksshIssuerToName(rawOp);
+ if (derivedFromRaw && knownNames.has(derivedFromRaw)) return derivedFromRaw;
+
+ const matchByAlias = providers.find((p) => p.alias === rawOp);
+ if (matchByAlias) {
+ const name = opksshIssuerToName(matchByAlias.issuer);
+ if (name) return name;
+ }
+
+ return rawOp;
+}
+
+type OpksshErrorPageOptions = {
+ title: string;
+ heading: string;
+ message: string;
+ details?: string;
+ requestId?: string;
+ statusCode?: number;
+};
+
+export function renderOpksshErrorPage(opts: OpksshErrorPageOptions): string {
+ const title = escapeHtml(opts.title);
+ const heading = escapeHtml(opts.heading);
+ const message = escapeHtml(opts.message);
+ const detailsBlock = opts.details
+ ? `<pre class="details">${escapeHtml(opts.details)}</pre>`
+ : "";
+ const requestIdBlock = opts.requestId
+ ? `<p class="request-id">Request ID: ${escapeHtml(opts.requestId)}</p>`
+ : "";
+
+ return `<!DOCTYPE html>
+<html>
+<head>
+ <title>${title}</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <style>
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ body {
+ font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ min-height: 100vh;
+ background: #18181b;
+ color: #fafafa;
+ padding: 1rem;
+ }
+ .container {
+ text-align: center;
+ background: #27272a;
+ padding: 3rem 2rem;
+ border-radius: 0.625rem;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ max-width: 720px;
+ width: 100%;
+ }
+ h1 {
+ color: #fafafa;
+ font-size: 1.5rem;
+ font-weight: 600;
+ margin-bottom: 0.75rem;
+ }
+ p {
+ color: #9ca3af;
+ font-size: 0.95rem;
+ line-height: 1.5;
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
+ p + p { margin-top: 0.5rem; }
+ .details {
+ color: #d4d4d8;
+ text-align: left;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 0.8rem;
+ line-height: 1.45;
+ margin-top: 1.25rem;
+ padding: 0.875rem 1rem;
+ background: #0f0f11;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 0.5rem;
+ white-space: pre-wrap;
+ word-break: break-word;
+ overflow-x: auto;
+ }
+ .request-id {
+ color: #6b7280;
+ font-size: 0.75rem;
+ margin-top: 1rem;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <h1>${heading}</h1>
+ <p>${message}</p>
+ ${detailsBlock}
+ ${requestIdBlock}
+ </div>
+</body>
+</html>`;
+}
+
+export function rewriteOPKSSHHtml(
+ html: string,
+ requestId: string,
+ routePrefix: "opkssh-chooser" | "opkssh-callback",
+): string {
+ const basePath = `/host/${routePrefix}/${requestId}`;
+ const localHostPattern = "(?:localhost|127\\.0\\.0\\.1)";
+
+ const attrPatterns = ["action", "href", "src", "formaction"];
+ for (const attr of attrPatterns) {
+ html = html.replace(
+ new RegExp(`${attr}="(/[^"]*)`, "g"),
+ `${attr}="${basePath}$1`,
+ );
+ html = html.replace(
+ new RegExp(`${attr}='(/[^']*)`, "g"),
+ `${attr}='${basePath}$1`,
+ );
+ }
+
+ for (const attr of ["href", "action", "src", "formaction"]) {
+ html = html.replace(
+ new RegExp(
+ `${attr}=["']?http:\\/\\/${localHostPattern}:\\d+\\/([^"'\\s]*)`,
+ "g",
+ ),
+ `${attr}="${basePath}/$1`,
+ );
+ }
+
+ html = html.replace(
+ new RegExp(
+ `(window\\.location\\.href\\s*=\\s*["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["'])`,
+ "g",
+ ),
+ `$1${basePath}/$2$3`,
+ );
+ html = html.replace(
+ new RegExp(
+ `(window\\.location\\s*=\\s*["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["'])`,
+ "g",
+ ),
+ `$1${basePath}/$2$3`,
+ );
+ html = html.replace(
+ new RegExp(
+ `(fetch\\(["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["'])`,
+ "g",
+ ),
+ `$1${basePath}/$2$3`,
+ );
+
+ html = html.replace(
+ new RegExp(
+ `(location\\.assign\\(["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["']\\))`,
+ "g",
+ ),
+ `$1${basePath}/$2$3`,
+ );
+ html = html.replace(
+ new RegExp(
+ `(location\\.replace\\(["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["']\\))`,
+ "g",
+ ),
+ `$1${basePath}/$2$3`,
+ );
+
+ // XMLHttpRequest.open("GET", "http://localhost:PORT/path", ...)
+ html = html.replace(
+ new RegExp(
+ `(\\.open\\(["']\\w+["']\\s*,\\s*["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["'])`,
+ "g",
+ ),
+ `$1${basePath}/$2$3`,
+ );
+
+ html = html.replace(
+ new RegExp(
+ `(<meta[^>]+http-equiv=["']refresh["'][^>]+content=["'][^;]+;\\s*url=)http:\\/\\/${localHostPattern}:\\d+\\/([^"']+)(["'][^>]*>)`,
+ "gi",
+ ),
+ `$1${basePath}/$2$3`,
+ );
+
+ html = html.replace(
+ new RegExp(
+ `(data-[\\w-]+=["'])http:\\/\\/${localHostPattern}:\\d+\\/([^"']*)(["'])`,
+ "g",
+ ),
+ `$1${basePath}/$2$3`,
+ );
+
+ const baseTag = `<base href="${basePath}/">`;
+
+ if (html.includes("<base")) {
+ sshLogger.info("Replacing existing base tag", {
+ operation: "opkssh_html_rewrite_base_tag",
+ requestId,
+ basePath,
+ });
+ html = html.replace(/<base[^>]*>/i, baseTag);
+ } else if (html.includes("<head>")) {
+ sshLogger.info("Inserting base tag into head", {
+ operation: "opkssh_html_rewrite_base_tag_insert",
+ requestId,
+ basePath,
+ });
+ html = html.replace(/<head>/i, `<head>${baseTag}`);
+ } else {
+ sshLogger.warn("No <head> tag found, wrapping HTML", {
+ operation: "opkssh_html_rewrite_no_head",
+ requestId,
+ htmlLength: html.length,
+ htmlPreview: html.substring(0, 200),
+ });
+ html = `<!DOCTYPE html><html><head>${baseTag}</head><body>${html}</body></html>`;
+ }
+
+ sshLogger.info("HTML rewrite complete", {
+ operation: "opkssh_html_rewrite_complete",
+ requestId,
+ routePrefix,
+ hasBaseTag: html.includes("<base href="),
+ staticAssetCount: (html.match(/\/static\//g) || []).length,
+ });
+
+ return html;
+}
diff --git a/src/backend/database/routes/user-admin-routes.ts b/src/backend/database/routes/user-admin-routes.ts
new file mode 100644
index 000000000..ee9edf070
--- /dev/null
+++ b/src/backend/database/routes/user-admin-routes.ts
@@ -0,0 +1,276 @@
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import type { RequestHandler, Router } from "express";
+import { eq } from "drizzle-orm";
+import { authLogger } from "../../utils/logger.js";
+import { db } from "../db/index.js";
+import { users } from "../db/schema.js";
+
+function isNonEmptyString(val: unknown): val is string {
+ return typeof val === "string" && val.trim().length > 0;
+}
+
+export function registerUserAdminRoutes(
+ router: Router,
+ authenticateJWT: RequestHandler,
+): void {
+ /**
+ * @openapi
+ * /users/list:
+ * get:
+ * summary: List all users
+ * description: Retrieves a list of all users in the system.
+ * tags:
+ * - Users
+ * responses:
+ * 200:
+ * description: A list of users.
+ * 403:
+ * description: Not authorized.
+ * 500:
+ * description: Failed to list users.
+ */
+ router.get("/list", authenticateJWT, async (req, res) => {
+ try {
+ const allUsers = await db
+ .select({
+ id: users.id,
+ username: users.username,
+ isAdmin: users.isAdmin,
+ isOidc: users.isOidc,
+ })
+ .from(users);
+
+ res.json({ users: allUsers });
+ } catch (err) {
+ authLogger.error("Failed to list users", err);
+ res.status(500).json({ error: "Failed to list users" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/make-admin:
+ * post:
+ * summary: Make user admin
+ * description: Grants admin privileges to a user.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * userId:
+ * type: string
+ * description: Preferred unique user identifier.
+ * username:
+ * type: string
+ * description: Legacy fallback identifier.
+ * responses:
+ * 200:
+ * description: User is now an admin.
+ * 400:
+ * description: User ID or username is required, or the user is already an admin.
+ * 403:
+ * description: Not authorized.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to make user admin.
+ */
+ router.post("/make-admin", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { userId: targetUserId, username } = req.body;
+ const resolvedUserId = isNonEmptyString(targetUserId)
+ ? targetUserId.trim()
+ : null;
+ const resolvedUsername = isNonEmptyString(username)
+ ? username.trim()
+ : null;
+
+ if (!resolvedUserId && !resolvedUsername) {
+ return res.status(400).json({ error: "User ID or username is required" });
+ }
+
+ try {
+ const adminUser = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, userId));
+ if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
+ return res.status(403).json({ error: "Not authorized" });
+ }
+
+ const targetUser = await db
+ .select()
+ .from(users)
+ .where(
+ resolvedUserId
+ ? eq(users.id, resolvedUserId)
+ : eq(users.username, resolvedUsername!),
+ )
+ .limit(1);
+ if (!targetUser || targetUser.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ if (targetUser[0].isAdmin) {
+ return res.status(400).json({ error: "User is already an admin" });
+ }
+
+ await db
+ .update(users)
+ .set({ isAdmin: true })
+ .where(
+ resolvedUserId
+ ? eq(users.id, resolvedUserId)
+ : eq(users.username, resolvedUsername!),
+ );
+
+ try {
+ const { saveMemoryDatabaseToFile } = await import("../db/index.js");
+ await saveMemoryDatabaseToFile();
+ } catch (saveError) {
+ authLogger.error(
+ "Failed to persist admin promotion to disk",
+ saveError,
+ {
+ operation: "make_admin_save_failed",
+ userId: targetUser[0].id,
+ username: targetUser[0].username,
+ },
+ );
+ }
+
+ authLogger.info("Admin privileges granted", {
+ operation: "admin_grant",
+ adminId: userId,
+ targetUserId: targetUser[0].id,
+ targetUsername: targetUser[0].username,
+ });
+ res.json({ message: `User ${targetUser[0].username} is now an admin` });
+ } catch (err) {
+ authLogger.error("Failed to make user admin", err);
+ res.status(500).json({ error: "Failed to make user admin" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/remove-admin:
+ * post:
+ * summary: Remove admin status
+ * description: Revokes admin privileges from a user.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * userId:
+ * type: string
+ * description: Preferred unique user identifier.
+ * username:
+ * type: string
+ * description: Legacy fallback identifier.
+ * responses:
+ * 200:
+ * description: Admin status removed from user.
+ * 400:
+ * description: User ID or username is required, or cannot remove your own admin status.
+ * 403:
+ * description: Not authorized.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to remove admin status.
+ */
+ router.post("/remove-admin", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { userId: targetUserId, username } = req.body;
+ const resolvedUserId = isNonEmptyString(targetUserId)
+ ? targetUserId.trim()
+ : null;
+ const resolvedUsername = isNonEmptyString(username)
+ ? username.trim()
+ : null;
+
+ if (!resolvedUserId && !resolvedUsername) {
+ return res.status(400).json({ error: "User ID or username is required" });
+ }
+
+ try {
+ const adminUser = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, userId));
+ if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
+ return res.status(403).json({ error: "Not authorized" });
+ }
+
+ if (
+ (resolvedUserId && adminUser[0].id === resolvedUserId) ||
+ (resolvedUsername && adminUser[0].username === resolvedUsername)
+ ) {
+ return res
+ .status(400)
+ .json({ error: "Cannot remove your own admin status" });
+ }
+
+ const targetUser = await db
+ .select()
+ .from(users)
+ .where(
+ resolvedUserId
+ ? eq(users.id, resolvedUserId)
+ : eq(users.username, resolvedUsername!),
+ )
+ .limit(1);
+ if (!targetUser || targetUser.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ if (!targetUser[0].isAdmin) {
+ return res.status(400).json({ error: "User is not an admin" });
+ }
+
+ await db
+ .update(users)
+ .set({ isAdmin: false })
+ .where(
+ resolvedUserId
+ ? eq(users.id, resolvedUserId)
+ : eq(users.username, resolvedUsername!),
+ );
+
+ try {
+ const { saveMemoryDatabaseToFile } = await import("../db/index.js");
+ await saveMemoryDatabaseToFile();
+ } catch (saveError) {
+ authLogger.error("Failed to persist admin removal to disk", saveError, {
+ operation: "remove_admin_save_failed",
+ userId: targetUser[0].id,
+ username: targetUser[0].username,
+ });
+ }
+
+ authLogger.info("Admin privileges revoked", {
+ operation: "admin_revoke",
+ adminId: userId,
+ targetUserId: targetUser[0].id,
+ targetUsername: targetUser[0].username,
+ });
+ res.json({
+ message: `Admin status removed from ${targetUser[0].username}`,
+ });
+ } catch (err) {
+ authLogger.error("Failed to remove admin status", err);
+ res.status(500).json({ error: "Failed to remove admin status" });
+ }
+ });
+}
diff --git a/src/backend/database/routes/user-api-key-routes.ts b/src/backend/database/routes/user-api-key-routes.ts
new file mode 100644
index 000000000..f683b0bf4
--- /dev/null
+++ b/src/backend/database/routes/user-api-key-routes.ts
@@ -0,0 +1,218 @@
+import type { RequestHandler, Router } from "express";
+import crypto from "crypto";
+import bcrypt from "bcryptjs";
+import { nanoid } from "nanoid";
+import { eq } from "drizzle-orm";
+import { authLogger } from "../../utils/logger.js";
+import { db } from "../db/index.js";
+import { apiKeys, users } from "../db/schema.js";
+
+export function registerUserApiKeyRoutes(
+ router: Router,
+ requireAdmin: RequestHandler,
+): void {
+ /**
+ * @openapi
+ * /users/api-keys:
+ * post:
+ * summary: Create an API key (admin only)
+ * description: Creates a new API key scoped to a specific user. The full token is returned only once.
+ * tags:
+ * - API Keys
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * required:
+ * - name
+ * - userId
+ * properties:
+ * name:
+ * type: string
+ * description: Human-readable name for the key.
+ * userId:
+ * type: string
+ * description: ID of the user this key is scoped to.
+ * expiresAt:
+ * type: string
+ * format: date-time
+ * description: Optional expiration date. Null means the key never expires.
+ * responses:
+ * 201:
+ * description: API key created. Contains the full token (shown only once).
+ * 400:
+ * description: Invalid input.
+ * 403:
+ * description: Admin access required.
+ * 404:
+ * description: Target user not found.
+ * 500:
+ * description: Failed to create API key.
+ */
+ router.post("/api-keys", requireAdmin, async (req, res) => {
+ try {
+ const { name, userId: targetUserId, expiresAt } = req.body;
+
+ if (typeof name !== "string" || !name.trim()) {
+ return res.status(400).json({ error: "name is required" });
+ }
+ if (typeof targetUserId !== "string" || !targetUserId.trim()) {
+ return res.status(400).json({ error: "userId is required" });
+ }
+
+ const targetUser = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, targetUserId))
+ .limit(1);
+ if (targetUser.length === 0) {
+ return res.status(404).json({ error: "Target user not found" });
+ }
+
+ let expiresAtValue: string | null = null;
+ if (expiresAt) {
+ const parsed = new Date(expiresAt);
+ if (isNaN(parsed.getTime())) {
+ return res.status(400).json({ error: "Invalid expiresAt date" });
+ }
+ if (parsed <= new Date()) {
+ return res
+ .status(400)
+ .json({ error: "expiresAt must be in the future" });
+ }
+ expiresAtValue = parsed.toISOString();
+ }
+
+ const rawToken = "tmx_" + crypto.randomBytes(32).toString("hex");
+ const tokenPrefix = rawToken.substring(0, 12);
+ const tokenHash = await bcrypt.hash(rawToken, 10);
+ const keyId = nanoid();
+ const now = new Date().toISOString();
+
+ await db.insert(apiKeys).values({
+ id: keyId,
+ userId: targetUserId,
+ name: name.trim(),
+ tokenHash,
+ tokenPrefix,
+ createdAt: now,
+ expiresAt: expiresAtValue,
+ lastUsedAt: null,
+ isActive: true,
+ });
+
+ const { saveMemoryDatabaseToFile } = await import("../db/index.js");
+ await saveMemoryDatabaseToFile();
+
+ return res.status(201).json({
+ id: keyId,
+ name: name.trim(),
+ userId: targetUserId,
+ username: targetUser[0].username,
+ tokenPrefix,
+ createdAt: now,
+ expiresAt: expiresAtValue,
+ token: rawToken,
+ });
+ } catch (err) {
+ authLogger.error("Failed to create API key", err);
+ return res.status(500).json({ error: "Failed to create API key" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/api-keys:
+ * get:
+ * summary: List all API keys (admin only)
+ * description: Returns all API keys with associated usernames. Token hashes are never returned.
+ * tags:
+ * - API Keys
+ * responses:
+ * 200:
+ * description: List of API keys.
+ * 403:
+ * description: Admin access required.
+ * 500:
+ * description: Failed to fetch API keys.
+ */
+ router.get("/api-keys", requireAdmin, async (_req, res) => {
+ try {
+ const keys = await db
+ .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);
+
+ return res.json({ apiKeys: keys });
+ } catch (err) {
+ authLogger.error("Failed to list API keys", err);
+ return res.status(500).json({ error: "Failed to fetch API keys" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/api-keys/{keyId}:
+ * delete:
+ * summary: Delete an API key (admin only)
+ * description: Permanently deletes an API key. It can no longer be used to authenticate.
+ * tags:
+ * - API Keys
+ * parameters:
+ * - in: path
+ * name: keyId
+ * required: true
+ * schema:
+ * type: string
+ * description: The ID of the API key to delete.
+ * responses:
+ * 200:
+ * description: API key deleted.
+ * 403:
+ * description: Admin access required.
+ * 404:
+ * description: API key not found.
+ * 500:
+ * description: Failed to delete API key.
+ */
+ router.delete("/api-keys/:keyId", requireAdmin, async (req, res) => {
+ try {
+ const keyId = String(req.params.keyId);
+
+ const existing = await db
+ .select()
+ .from(apiKeys)
+ .where(eq(apiKeys.id, keyId))
+ .limit(1);
+
+ if (existing.length === 0) {
+ return res.status(404).json({ error: "API key not found" });
+ }
+
+ await db.delete(apiKeys).where(eq(apiKeys.id, keyId));
+
+ const { saveMemoryDatabaseToFile } = await import("../db/index.js");
+ await saveMemoryDatabaseToFile();
+
+ return res.json({ success: true });
+ } catch (err) {
+ authLogger.error("Failed to delete API key", err, {
+ keyId: String(req.params.keyId),
+ });
+ return res.status(500).json({ error: "Failed to delete API key" });
+ }
+ });
+}
diff --git a/src/backend/database/routes/user-data-access-routes.ts b/src/backend/database/routes/user-data-access-routes.ts
new file mode 100644
index 000000000..7240a05ec
--- /dev/null
+++ b/src/backend/database/routes/user-data-access-routes.ts
@@ -0,0 +1,122 @@
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import type { RequestHandler, Router } from "express";
+import { AuthManager } from "../../utils/auth-manager.js";
+import { authLogger } from "../../utils/logger.js";
+
+interface UserDataAccessRoutesDeps {
+ authenticateJWT: RequestHandler;
+ authManager: AuthManager;
+}
+
+export function registerUserDataAccessRoutes(
+ router: Router,
+ { authenticateJWT, authManager }: UserDataAccessRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /users/unlock-data:
+ * post:
+ * summary: Unlock user data
+ * description: Re-authenticates user with password to unlock encrypted data.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * password:
+ * type: string
+ * responses:
+ * 200:
+ * description: Data unlocked successfully.
+ * 400:
+ * description: Password is required.
+ * 401:
+ * description: Invalid password.
+ * 500:
+ * description: Failed to unlock data.
+ */
+ router.post("/unlock-data", authenticateJWT, async (req, res) => {
+ const authReq = req as AuthenticatedRequest;
+ const userId = authReq.userId;
+ const { password } = req.body;
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ if (!password) {
+ return res.status(400).json({ error: "Password is required" });
+ }
+
+ try {
+ const unlocked = await authManager.authenticateUser(userId, password);
+ if (unlocked) {
+ const refreshedSession =
+ userId && authReq.sessionId
+ ? await authManager.refreshSessionToken(userId, authReq.sessionId)
+ : null;
+
+ if (refreshedSession) {
+ res.cookie(
+ "jwt",
+ refreshedSession.token,
+ authManager.getSecureCookieOptions(req, refreshedSession.maxAge),
+ );
+ }
+
+ res.json({
+ success: true,
+ message: "Data unlocked successfully",
+ });
+ } else {
+ authLogger.warn("Failed to unlock user data - invalid password", {
+ operation: "user_data_unlock_failed",
+ userId,
+ });
+ res.status(401).json({ error: "Invalid password" });
+ }
+ } catch (err) {
+ authLogger.error("Data unlock failed", err, {
+ operation: "user_data_unlock_error",
+ userId,
+ });
+ res.status(500).json({ error: "Failed to unlock data" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/data-status:
+ * get:
+ * summary: Check user data unlock status
+ * description: Checks if user data is currently unlocked.
+ * tags:
+ * - Users
+ * responses:
+ * 200:
+ * description: Data status returned.
+ * 500:
+ * description: Failed to check data status.
+ */
+ router.get("/data-status", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+
+ try {
+ const unlocked = authManager.isUserUnlocked(userId);
+ res.json({
+ unlocked,
+ message: unlocked ? "Data is unlocked" : "Data is locked",
+ });
+ } catch (err) {
+ authLogger.error("Failed to check data status", err, {
+ operation: "data_status_check_failed",
+ userId,
+ });
+ res.status(500).json({ error: "Failed to check data status" });
+ }
+ });
+}
diff --git a/src/backend/database/routes/user-oidc-account-routes.ts b/src/backend/database/routes/user-oidc-account-routes.ts
new file mode 100644
index 000000000..5151a1e78
--- /dev/null
+++ b/src/backend/database/routes/user-oidc-account-routes.ts
@@ -0,0 +1,371 @@
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import type { RequestHandler, Router } from "express";
+import { eq } from "drizzle-orm";
+import { AuthManager } from "../../utils/auth-manager.js";
+import { authLogger } from "../../utils/logger.js";
+import { db } from "../db/index.js";
+import { users } from "../db/schema.js";
+import { deleteUserAndRelatedData } from "./delete-user-data.js";
+
+type UserOidcAccountRoutesDeps = {
+ authenticateJWT: RequestHandler;
+ authManager: AuthManager;
+};
+
+function isNonEmptyString(val: unknown): val is string {
+ return typeof val === "string" && val.trim().length > 0;
+}
+
+export function registerUserOidcAccountRoutes(
+ router: Router,
+ { authenticateJWT, authManager }: UserOidcAccountRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /users/link-oidc-to-password:
+ * post:
+ * summary: Link OIDC user to password account
+ * description: Merges an OIDC-only account into a password-based account (admin only).
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * oidcUserId:
+ * type: string
+ * targetUsername:
+ * type: string
+ * responses:
+ * 200:
+ * description: Accounts linked successfully.
+ * 400:
+ * description: Invalid request or incompatible accounts.
+ * 403:
+ * description: Admin access required.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to link accounts.
+ */
+ router.post("/link-oidc-to-password", authenticateJWT, async (req, res) => {
+ const adminUserId = (req as AuthenticatedRequest).userId;
+ const { oidcUserId, targetUsername } = req.body;
+
+ if (!isNonEmptyString(oidcUserId) || !isNonEmptyString(targetUsername)) {
+ return res.status(400).json({
+ error: "OIDC user ID and target username are required",
+ });
+ }
+
+ try {
+ const adminUser = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, adminUserId));
+ if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
+ return res.status(403).json({ error: "Admin access required" });
+ }
+
+ const oidcUserRecords = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, oidcUserId));
+ if (!oidcUserRecords || oidcUserRecords.length === 0) {
+ return res.status(404).json({ error: "OIDC user not found" });
+ }
+
+ const oidcUser = oidcUserRecords[0];
+
+ if (!oidcUser.isOidc) {
+ return res.status(400).json({
+ error: "Source user is not an OIDC user",
+ });
+ }
+
+ const targetUserRecords = await db
+ .select()
+ .from(users)
+ .where(eq(users.username, targetUsername));
+ if (!targetUserRecords || targetUserRecords.length === 0) {
+ return res
+ .status(404)
+ .json({ error: "Target password user not found" });
+ }
+
+ const targetUser = targetUserRecords[0];
+
+ if (targetUser.isOidc || !targetUser.passwordHash) {
+ return res.status(400).json({
+ error: "Target user must be a password-based account",
+ });
+ }
+
+ if (targetUser.clientId && targetUser.oidcIdentifier) {
+ return res.status(400).json({
+ error: "Target user already has OIDC authentication configured",
+ });
+ }
+
+ authLogger.info("Linking OIDC user to password account", {
+ operation: "link_oidc_to_password",
+ oidcUserId,
+ oidcUsername: oidcUser.username,
+ targetUserId: targetUser.id,
+ targetUsername: targetUser.username,
+ adminUserId,
+ });
+
+ await db
+ .update(users)
+ .set({
+ isOidc: true,
+ oidcIdentifier: oidcUser.oidcIdentifier,
+ clientId: oidcUser.clientId,
+ clientSecret: oidcUser.clientSecret,
+ issuerUrl: oidcUser.issuerUrl,
+ authorizationUrl: oidcUser.authorizationUrl,
+ tokenUrl: oidcUser.tokenUrl,
+ identifierPath: oidcUser.identifierPath,
+ namePath: oidcUser.namePath,
+ scopes: oidcUser.scopes || "openid email profile",
+ })
+ .where(eq(users.id, targetUser.id));
+
+ try {
+ await authManager.convertToOIDCEncryption(targetUser.id);
+ } catch (encryptionError) {
+ authLogger.error(
+ "Failed to convert encryption to OIDC during linking",
+ encryptionError,
+ {
+ operation: "link_convert_encryption_failed",
+ userId: targetUser.id,
+ },
+ );
+ await db
+ .update(users)
+ .set({
+ isOidc: false,
+ oidcIdentifier: null,
+ clientId: "",
+ clientSecret: "",
+ issuerUrl: "",
+ authorizationUrl: "",
+ tokenUrl: "",
+ identifierPath: "",
+ namePath: "",
+ scopes: "openid email profile",
+ })
+ .where(eq(users.id, targetUser.id));
+
+ return res.status(500).json({
+ error:
+ "Failed to convert encryption for dual-auth. Please ensure the password account has encryption setup.",
+ details:
+ encryptionError instanceof Error
+ ? encryptionError.message
+ : "Unknown error",
+ });
+ }
+
+ await authManager.revokeAllUserSessions(oidcUserId);
+ authManager.logoutUser(oidcUserId);
+
+ await deleteUserAndRelatedData(oidcUserId);
+
+ try {
+ const { saveMemoryDatabaseToFile } = await import("../db/index.js");
+ await saveMemoryDatabaseToFile();
+ } catch (saveError) {
+ authLogger.error(
+ "Failed to persist account linking to disk",
+ saveError,
+ {
+ operation: "link_oidc_save_failed",
+ oidcUserId,
+ targetUserId: targetUser.id,
+ },
+ );
+ }
+
+ authLogger.success(
+ `OIDC user ${oidcUser.username} linked to password account ${targetUser.username}`,
+ {
+ operation: "link_oidc_to_password_success",
+ oidcUserId,
+ oidcUsername: oidcUser.username,
+ targetUserId: targetUser.id,
+ targetUsername: targetUser.username,
+ adminUserId,
+ },
+ );
+
+ res.json({
+ success: true,
+ message: `OIDC user ${oidcUser.username} has been linked to ${targetUser.username}. The password account can now use both password and OIDC login.`,
+ });
+ } catch (err) {
+ authLogger.error("Failed to link OIDC user to password account", err, {
+ operation: "link_oidc_to_password_failed",
+ oidcUserId,
+ targetUsername,
+ adminUserId,
+ });
+ res.status(500).json({
+ error: "Failed to link accounts",
+ details: err instanceof Error ? err.message : "Unknown error",
+ });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/unlink-oidc-from-password:
+ * post:
+ * summary: Unlink OIDC from password account
+ * description: Removes OIDC authentication from a dual-auth account (admin only).
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * userId:
+ * type: string
+ * responses:
+ * 200:
+ * description: OIDC unlinked successfully.
+ * 400:
+ * description: Invalid request or user doesn't have OIDC.
+ * 403:
+ * description: Admin privileges required.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to unlink OIDC.
+ */
+ router.post(
+ "/unlink-oidc-from-password",
+ authenticateJWT,
+ async (req, res) => {
+ const adminUserId = (req as AuthenticatedRequest).userId;
+ const { userId } = req.body;
+
+ if (!userId) {
+ return res.status(400).json({
+ error: "User ID is required",
+ });
+ }
+
+ try {
+ const adminUser = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, adminUserId));
+
+ if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
+ authLogger.warn("Non-admin attempted to unlink OIDC from password", {
+ operation: "unlink_oidc_unauthorized",
+ adminUserId,
+ targetUserId: userId,
+ });
+ return res.status(403).json({
+ error: "Admin privileges required",
+ });
+ }
+
+ const targetUserRecords = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, userId));
+
+ if (!targetUserRecords || targetUserRecords.length === 0) {
+ return res.status(404).json({
+ error: "User not found",
+ });
+ }
+
+ const targetUser = targetUserRecords[0];
+
+ if (!targetUser.isOidc) {
+ return res.status(400).json({
+ error: "User does not have OIDC authentication enabled",
+ });
+ }
+
+ if (!targetUser.passwordHash || targetUser.passwordHash === "") {
+ return res.status(400).json({
+ error:
+ "Cannot unlink OIDC from a user without password authentication. This would leave the user unable to login.",
+ });
+ }
+
+ authLogger.info("Unlinking OIDC from password account", {
+ operation: "unlink_oidc_from_password_start",
+ targetUserId: targetUser.id,
+ targetUsername: targetUser.username,
+ adminUserId,
+ });
+
+ await db
+ .update(users)
+ .set({
+ isOidc: false,
+ oidcIdentifier: null,
+ clientId: "",
+ clientSecret: "",
+ issuerUrl: "",
+ authorizationUrl: "",
+ tokenUrl: "",
+ identifierPath: "",
+ namePath: "",
+ scopes: "openid email profile",
+ })
+ .where(eq(users.id, targetUser.id));
+
+ try {
+ const { saveMemoryDatabaseToFile } = await import("../db/index.js");
+ await saveMemoryDatabaseToFile();
+ } catch (saveError) {
+ authLogger.error(
+ "Failed to save database after unlinking OIDC",
+ saveError,
+ {
+ operation: "unlink_oidc_save_failed",
+ targetUserId: targetUser.id,
+ },
+ );
+ }
+
+ authLogger.success("OIDC unlinked from password account successfully", {
+ operation: "unlink_oidc_from_password_success",
+ targetUserId: targetUser.id,
+ targetUsername: targetUser.username,
+ adminUserId,
+ });
+
+ res.json({
+ success: true,
+ message: `OIDC authentication has been removed from ${targetUser.username}. User can now only login with password.`,
+ });
+ } catch (err) {
+ authLogger.error("Failed to unlink OIDC from password account", err, {
+ operation: "unlink_oidc_from_password_failed",
+ targetUserId: userId,
+ adminUserId,
+ });
+ res.status(500).json({
+ error: "Failed to unlink OIDC",
+ details: err instanceof Error ? err.message : "Unknown error",
+ });
+ }
+ },
+ );
+}
diff --git a/src/backend/database/routes/user-oidc-utils.test.ts b/src/backend/database/routes/user-oidc-utils.test.ts
new file mode 100644
index 000000000..ab9455f98
--- /dev/null
+++ b/src/backend/database/routes/user-oidc-utils.test.ts
@@ -0,0 +1,134 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+
+// user-oidc-utils imports the logger; stub it so importing stays side-effect-free.
+vi.mock("../../utils/logger.js", () => ({
+ authLogger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ success: vi.fn(),
+ },
+}));
+
+const { isOIDCUserAllowed, getOIDCConfigFromEnv } =
+ await import("./user-oidc-utils.js");
+
+describe("isOIDCUserAllowed", () => {
+ it("allows everyone when the allow-list is empty", () => {
+ expect(isOIDCUserAllowed("", "alice", "[email protected]")).toBe(true);
+ expect(isOIDCUserAllowed(" ", "alice")).toBe(true);
+ });
+
+ it("allows everyone with the '*' wildcard", () => {
+ expect(isOIDCUserAllowed("*", "anyone", "[email protected]")).toBe(true);
+ });
+
+ it("matches an exact identifier (case-insensitive)", () => {
+ expect(isOIDCUserAllowed("alice,bob", "alice")).toBe(true);
+ expect(isOIDCUserAllowed("Alice", "alice")).toBe(true);
+ expect(isOIDCUserAllowed("alice", "ALICE")).toBe(true);
+ });
+
+ it("matches against the email as well as the identifier", () => {
+ expect(isOIDCUserAllowed("[email protected]", "sub-123", "[email protected]")).toBe(
+ true,
+ );
+ });
+
+ it("matches an @domain suffix pattern", () => {
+ expect(isOIDCUserAllowed("@company.com", "sub-1", "[email protected]")).toBe(
+ true,
+ );
+ expect(isOIDCUserAllowed("@company.com", "sub-1", "[email protected]")).toBe(
+ true,
+ );
+ });
+
+ it("denies users not on the list", () => {
+ expect(isOIDCUserAllowed("alice,bob", "charlie", "[email protected]")).toBe(
+ false,
+ );
+ expect(isOIDCUserAllowed("@company.com", "sub-1", "[email protected]")).toBe(
+ false,
+ );
+ });
+
+ it("ignores blank entries and surrounding whitespace in the list", () => {
+ expect(isOIDCUserAllowed(" alice , , bob ", "bob")).toBe(true);
+ });
+
+ it("does not match the email against an identifier-only pattern when email differs", () => {
+ expect(isOIDCUserAllowed("alice", "sub-123", "[email protected]")).toBe(false);
+ });
+});
+
+describe("getOIDCConfigFromEnv", () => {
+ const REQUIRED = [
+ "OIDC_CLIENT_ID",
+ "OIDC_CLIENT_SECRET",
+ "OIDC_ISSUER_URL",
+ "OIDC_AUTHORIZATION_URL",
+ "OIDC_TOKEN_URL",
+ ];
+ const OPTIONAL = [
+ "OIDC_USERINFO_URL",
+ "OIDC_IDENTIFIER_PATH",
+ "OIDC_NAME_PATH",
+ "OIDC_SCOPES",
+ "OIDC_ALLOWED_USERS",
+ "OIDC_ADMIN_GROUP",
+ ];
+ const saved: Record<string, string | undefined> = {};
+
+ beforeEach(() => {
+ for (const key of [...REQUIRED, ...OPTIONAL]) {
+ saved[key] = process.env[key];
+ delete process.env[key];
+ }
+ });
+
+ afterEach(() => {
+ for (const key of [...REQUIRED, ...OPTIONAL]) {
+ if (saved[key] === undefined) delete process.env[key];
+ else process.env[key] = saved[key];
+ }
+ });
+
+ it("returns null when any required variable is missing", () => {
+ process.env.OIDC_CLIENT_ID = "id";
+ process.env.OIDC_CLIENT_SECRET = "secret";
+ // issuer/authorization/token urls intentionally missing
+ expect(getOIDCConfigFromEnv()).toBeNull();
+ });
+
+ it("builds a config with defaults when all required vars are present", () => {
+ process.env.OIDC_CLIENT_ID = "id";
+ process.env.OIDC_CLIENT_SECRET = "secret";
+ process.env.OIDC_ISSUER_URL = "https://idp.example";
+ process.env.OIDC_AUTHORIZATION_URL = "https://idp.example/auth";
+ process.env.OIDC_TOKEN_URL = "https://idp.example/token";
+
+ const config = getOIDCConfigFromEnv();
+ expect(config).not.toBeNull();
+ expect(config?.client_id).toBe("id");
+ expect(config?.identifier_path).toBe("sub");
+ expect(config?.name_path).toBe("name");
+ expect(config?.scopes).toBe("openid email profile");
+ expect(config?.userinfo_url).toBe("");
+ });
+
+ it("honors overrides for optional vars", () => {
+ process.env.OIDC_CLIENT_ID = "id";
+ process.env.OIDC_CLIENT_SECRET = "secret";
+ process.env.OIDC_ISSUER_URL = "https://idp.example";
+ process.env.OIDC_AUTHORIZATION_URL = "https://idp.example/auth";
+ process.env.OIDC_TOKEN_URL = "https://idp.example/token";
+ process.env.OIDC_IDENTIFIER_PATH = "email";
+ process.env.OIDC_SCOPES = "openid";
+
+ const config = getOIDCConfigFromEnv();
+ expect(config?.identifier_path).toBe("email");
+ expect(config?.scopes).toBe("openid");
+ });
+});
diff --git a/src/backend/database/routes/user-oidc-utils.ts b/src/backend/database/routes/user-oidc-utils.ts
new file mode 100644
index 000000000..d3a887e34
--- /dev/null
+++ b/src/backend/database/routes/user-oidc-utils.ts
@@ -0,0 +1,172 @@
+import { authLogger } from "../../utils/logger.js";
+
+export type OIDCConfig = {
+ client_id: string;
+ client_secret: string;
+ issuer_url: string;
+ authorization_url: string;
+ token_url: string;
+ userinfo_url: string;
+ identifier_path: string;
+ name_path: string;
+ scopes: string;
+ allowed_users: string;
+ admin_group: string;
+};
+
+export function getOIDCConfigFromEnv(): OIDCConfig | null {
+ const client_id = process.env.OIDC_CLIENT_ID;
+ const client_secret = process.env.OIDC_CLIENT_SECRET;
+ const issuer_url = process.env.OIDC_ISSUER_URL;
+ const authorization_url = process.env.OIDC_AUTHORIZATION_URL;
+ const token_url = process.env.OIDC_TOKEN_URL;
+
+ if (
+ !client_id ||
+ !client_secret ||
+ !issuer_url ||
+ !authorization_url ||
+ !token_url
+ ) {
+ return null;
+ }
+
+ return {
+ client_id,
+ client_secret,
+ issuer_url,
+ authorization_url,
+ token_url,
+ userinfo_url: process.env.OIDC_USERINFO_URL || "",
+ identifier_path: process.env.OIDC_IDENTIFIER_PATH || "sub",
+ name_path: process.env.OIDC_NAME_PATH || "name",
+ scopes: process.env.OIDC_SCOPES || "openid email profile",
+ allowed_users: process.env.OIDC_ALLOWED_USERS || "",
+ admin_group: process.env.OIDC_ADMIN_GROUP || "",
+ };
+}
+
+export function isOIDCUserAllowed(
+ allowedUsers: string,
+ identifier: string,
+ email?: string,
+): boolean {
+ if (!allowedUsers || !allowedUsers.trim()) return true;
+ const patterns = allowedUsers
+ .split(",")
+ .map((p) => p.trim())
+ .filter(Boolean);
+ if (patterns.length === 0) return true;
+
+ const values = [
+ identifier,
+ ...(email && email !== identifier ? [email] : []),
+ ];
+ for (const pattern of patterns) {
+ if (pattern === "*") return true;
+ for (const value of values) {
+ if (!value) continue;
+ if (pattern.toLowerCase().startsWith("@")) {
+ if (value.toLowerCase().endsWith(pattern.toLowerCase())) return true;
+ } else {
+ if (value.toLowerCase() === pattern.toLowerCase()) return true;
+ }
+ }
+ }
+ return false;
+}
+
+export async function verifyOIDCToken(
+ idToken: string,
+ issuerUrl: string,
+ clientId: string,
+): Promise<Record<string, unknown>> {
+ const normalizedIssuerUrl = issuerUrl.endsWith("/")
+ ? issuerUrl.slice(0, -1)
+ : issuerUrl;
+ const possibleIssuers = [
+ issuerUrl,
+ normalizedIssuerUrl,
+ issuerUrl.replace(/\/application\/o\/[^/]+$/, ""),
+ normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, ""),
+ ];
+
+ const jwksUrls = [
+ `${normalizedIssuerUrl}/.well-known/jwks.json`,
+ `${normalizedIssuerUrl}/jwks/`,
+ `${normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, "")}/.well-known/jwks.json`,
+ ];
+
+ try {
+ const discoveryUrl = `${normalizedIssuerUrl}/.well-known/openid-configuration`;
+ const discoveryResponse = await fetch(discoveryUrl);
+ if (discoveryResponse.ok) {
+ const discovery = (await discoveryResponse.json()) as Record<
+ string,
+ unknown
+ >;
+ if (discovery.jwks_uri) {
+ jwksUrls.unshift(discovery.jwks_uri as string);
+ }
+ }
+ } catch (discoveryError) {
+ authLogger.error(`OIDC discovery failed: ${discoveryError}`);
+ }
+
+ let jwks: Record<string, unknown> | null = null;
+
+ for (const url of jwksUrls) {
+ try {
+ const response = await fetch(url);
+ if (response.ok) {
+ const jwksData = (await response.json()) as Record<string, unknown>;
+ if (jwksData && jwksData.keys && Array.isArray(jwksData.keys)) {
+ jwks = jwksData;
+ break;
+ } else {
+ authLogger.error(
+ `Invalid JWKS structure from ${url}: ${JSON.stringify(jwksData)}`,
+ );
+ }
+ } else {
+ // expected - non-ok response, try next URL
+ }
+ } catch {
+ continue;
+ }
+ }
+
+ if (!jwks) {
+ throw new Error("Failed to fetch JWKS from any URL");
+ }
+
+ if (!jwks.keys || !Array.isArray(jwks.keys)) {
+ throw new Error(
+ `Invalid JWKS response structure. Expected 'keys' array, got: ${JSON.stringify(jwks)}`,
+ );
+ }
+
+ const header = JSON.parse(
+ Buffer.from(idToken.split(".")[0], "base64").toString(),
+ );
+ const keyId = header.kid;
+
+ const publicKey = jwks.keys.find(
+ (key: Record<string, unknown>) => key.kid === keyId,
+ );
+ if (!publicKey) {
+ throw new Error(
+ `No matching public key found for key ID: ${keyId}. Available keys: ${jwks.keys.map((k: Record<string, unknown>) => k.kid).join(", ")}`,
+ );
+ }
+
+ const { importJWK, jwtVerify } = await import("jose");
+ const key = await importJWK(publicKey);
+
+ const { payload } = await jwtVerify(idToken, key, {
+ issuer: possibleIssuers,
+ audience: clientId,
+ });
+
+ return payload;
+}
diff --git a/src/backend/database/routes/user-password-reset-routes.ts b/src/backend/database/routes/user-password-reset-routes.ts
new file mode 100644
index 000000000..c7257e04f
--- /dev/null
+++ b/src/backend/database/routes/user-password-reset-routes.ts
@@ -0,0 +1,489 @@
+import type { Router } from "express";
+import crypto from "crypto";
+import bcrypt from "bcryptjs";
+import { nanoid } from "nanoid";
+import { eq } from "drizzle-orm";
+import { AuthManager } from "../../utils/auth-manager.js";
+import { authLogger } from "../../utils/logger.js";
+import { loginRateLimiter } from "../../utils/login-rate-limiter.js";
+import { db } from "../db/index.js";
+import {
+ users,
+ hosts,
+ sshCredentials,
+ fileManagerRecent,
+ fileManagerPinned,
+ fileManagerShortcuts,
+ dismissedAlerts,
+ sshCredentialUsage,
+ recentActivity,
+ snippets,
+} from "../db/schema.js";
+
+interface UserPasswordResetRoutesDeps {
+ authManager: AuthManager;
+}
+
+function isNonEmptyString(val: unknown): val is string {
+ return typeof val === "string" && val.trim().length > 0;
+}
+
+export function registerUserPasswordResetRoutes(
+ router: Router,
+ { authManager }: UserPasswordResetRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /users/initiate-reset:
+ * post:
+ * summary: Initiate password reset
+ * description: Initiates the password reset process for a user.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * username:
+ * type: string
+ * responses:
+ * 200:
+ * description: Password reset code has been generated.
+ * 400:
+ * description: Username is required.
+ * 403:
+ * description: Password reset not available for external authentication users.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to initiate password reset.
+ */
+ router.post("/initiate-reset", async (req, res) => {
+ try {
+ const row = db.$client
+ .prepare(
+ "SELECT value FROM settings WHERE key = 'allow_password_reset'",
+ )
+ .get();
+ if (row && (row as { value: string }).value !== "true") {
+ return res
+ .status(403)
+ .json({ error: "Password reset is currently disabled" });
+ }
+ } catch (e) {
+ authLogger.warn("Failed to check password reset status", {
+ operation: "password_reset_check",
+ error: e,
+ });
+ }
+
+ const { username } = req.body;
+
+ if (!isNonEmptyString(username)) {
+ return res.status(400).json({ error: "Username is required" });
+ }
+
+ try {
+ const user = await db
+ .select()
+ .from(users)
+ .where(eq(users.username, username));
+
+ if (!user || user.length === 0) {
+ authLogger.warn(
+ `Password reset attempted for non-existent user: ${username}`,
+ );
+ return res.json({
+ message:
+ "If the user exists, a password reset code has been generated. Check docker logs for the code.",
+ });
+ }
+
+ if (user[0].isOidc) {
+ return res.json({
+ message:
+ "If the user exists, a password reset code has been generated. Check docker logs for the code.",
+ });
+ }
+
+ const resetCode = crypto.randomInt(100000, 1000000).toString();
+ const expiresAt = new Date(Date.now() + 15 * 60 * 1000);
+
+ db.$client
+ .prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)")
+ .run(
+ `reset_code_${username}`,
+ JSON.stringify({
+ code: resetCode,
+ expiresAt: expiresAt.toISOString(),
+ }),
+ );
+
+ authLogger.info(
+ `Password reset code generated for user ${username} (expires at ${expiresAt.toLocaleString()}). Check admin panel or database settings table for code.`,
+ );
+
+ res.json({
+ message:
+ "Password reset code has been generated and logged. Check docker logs for the code.",
+ });
+ } catch (err) {
+ authLogger.error("Failed to initiate password reset", err);
+ res.status(500).json({ error: "Failed to initiate password reset" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/verify-reset-code:
+ * post:
+ * summary: Verify reset code
+ * description: Verifies the password reset code.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * username:
+ * type: string
+ * resetCode:
+ * type: string
+ * responses:
+ * 200:
+ * description: Reset code verified.
+ * 400:
+ * description: Invalid or expired reset code.
+ * 500:
+ * description: Failed to verify reset code.
+ */
+ router.post("/verify-reset-code", async (req, res) => {
+ const { username, resetCode } = req.body;
+
+ if (!isNonEmptyString(username) || !isNonEmptyString(resetCode)) {
+ return res
+ .status(400)
+ .json({ error: "Username and reset code are required" });
+ }
+
+ try {
+ const lockStatus = loginRateLimiter.isResetCodeLocked(username);
+ if (lockStatus.locked) {
+ authLogger.warn(
+ "Reset code verification blocked due to rate limiting",
+ {
+ operation: "reset_code_verify_blocked",
+ username,
+ remainingTime: lockStatus.remainingTime,
+ },
+ );
+ return res.status(429).json({
+ error: `Rate limited: Too many verification attempts. Please wait ${lockStatus.remainingTime} seconds before trying again.`,
+ remainingTime: lockStatus.remainingTime,
+ code: "RESET_CODE_RATE_LIMITED",
+ });
+ }
+
+ loginRateLimiter.recordResetCodeAttempt(username);
+
+ const resetDataRow = db.$client
+ .prepare("SELECT value FROM settings WHERE key = ?")
+ .get(`reset_code_${username}`);
+ if (!resetDataRow) {
+ authLogger.warn("Reset code verification failed - no code found", {
+ operation: "reset_code_verify_failed",
+ username,
+ remainingAttempts:
+ loginRateLimiter.getRemainingResetCodeAttempts(username),
+ });
+ return res.status(400).json({
+ error: "No reset code found for this user",
+ remainingAttempts:
+ loginRateLimiter.getRemainingResetCodeAttempts(username),
+ });
+ }
+
+ const resetData = JSON.parse(
+ (resetDataRow as Record<string, unknown>).value as string,
+ );
+ const now = new Date();
+ const expiresAt = new Date(resetData.expiresAt);
+
+ if (now > expiresAt) {
+ db.$client
+ .prepare("DELETE FROM settings WHERE key = ?")
+ .run(`reset_code_${username}`);
+ authLogger.warn("Reset code verification failed - code expired", {
+ operation: "reset_code_verify_failed",
+ username,
+ remainingAttempts:
+ loginRateLimiter.getRemainingResetCodeAttempts(username),
+ });
+ return res.status(400).json({
+ error: "Reset code has expired",
+ remainingAttempts:
+ loginRateLimiter.getRemainingResetCodeAttempts(username),
+ });
+ }
+
+ if (resetData.code !== resetCode) {
+ authLogger.warn("Reset code verification failed - invalid code", {
+ operation: "reset_code_verify_failed",
+ username,
+ remainingAttempts:
+ loginRateLimiter.getRemainingResetCodeAttempts(username),
+ });
+ return res.status(400).json({
+ error: "Invalid reset code",
+ remainingAttempts:
+ loginRateLimiter.getRemainingResetCodeAttempts(username),
+ });
+ }
+
+ loginRateLimiter.resetResetCodeAttempts(username);
+
+ const tempToken = nanoid();
+ const tempTokenExpiry = new Date(Date.now() + 10 * 60 * 1000);
+
+ db.$client
+ .prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)")
+ .run(
+ `temp_reset_token_${username}`,
+ JSON.stringify({
+ token: tempToken,
+ expiresAt: tempTokenExpiry.toISOString(),
+ }),
+ );
+
+ res.json({ message: "Reset code verified", tempToken });
+ } catch (err) {
+ authLogger.error("Failed to verify reset code", err);
+ res.status(500).json({ error: "Failed to verify reset code" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/complete-reset:
+ * post:
+ * summary: Complete password reset
+ * description: Completes the password reset process with a new password.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * username:
+ * type: string
+ * tempToken:
+ * type: string
+ * newPassword:
+ * type: string
+ * responses:
+ * 200:
+ * description: Password has been successfully reset.
+ * 400:
+ * description: Invalid or expired temporary token.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to complete password reset.
+ */
+ router.post("/complete-reset", async (req, res) => {
+ const { username, tempToken, newPassword } = req.body;
+
+ if (
+ !isNonEmptyString(username) ||
+ !isNonEmptyString(tempToken) ||
+ !isNonEmptyString(newPassword)
+ ) {
+ return res.status(400).json({
+ error: "Username, temporary token, and new password are required",
+ });
+ }
+
+ try {
+ const tempTokenRow = db.$client
+ .prepare("SELECT value FROM settings WHERE key = ?")
+ .get(`temp_reset_token_${username}`);
+ if (!tempTokenRow) {
+ return res.status(400).json({ error: "No temporary token found" });
+ }
+
+ const tempTokenData = JSON.parse(
+ (tempTokenRow as Record<string, unknown>).value as string,
+ );
+ const now = new Date();
+ const expiresAt = new Date(tempTokenData.expiresAt);
+
+ if (now > expiresAt) {
+ db.$client
+ .prepare("DELETE FROM settings WHERE key = ?")
+ .run(`temp_reset_token_${username}`);
+ return res.status(400).json({ error: "Temporary token has expired" });
+ }
+
+ if (tempTokenData.token !== tempToken) {
+ return res.status(400).json({ error: "Invalid temporary token" });
+ }
+
+ const user = await db
+ .select()
+ .from(users)
+ .where(eq(users.username, username));
+ if (!user || user.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+ const userId = user[0].id;
+
+ const saltRounds = parseInt(process.env.SALT || "10", 10);
+ const password_hash = await bcrypt.hash(newPassword, saltRounds);
+
+ let userIdFromJwt: string | null = null;
+ const cookie = req.cookies?.jwt;
+ let header: string | undefined;
+ if (req.headers?.authorization?.startsWith("Bearer ")) {
+ header = req.headers?.authorization?.split(" ")[1];
+ }
+ const token = cookie || header;
+
+ if (token) {
+ const payload = await authManager.verifyJWTToken(token);
+ if (payload) {
+ userIdFromJwt = payload.userId;
+ }
+ }
+
+ if (userIdFromJwt === userId) {
+ try {
+ const success = await authManager.resetUserPasswordWithPreservedDEK(
+ userId,
+ newPassword,
+ );
+
+ if (!success) {
+ throw new Error(
+ "Failed to re-encrypt user data with new password.",
+ );
+ }
+
+ await db
+ .update(users)
+ .set({ passwordHash: password_hash })
+ .where(eq(users.id, userId));
+ authManager.logoutUser(userId);
+ authLogger.success(
+ `Password reset (data preserved) for user: ${username}`,
+ {
+ operation: "password_reset_preserved",
+ userId,
+ username,
+ },
+ );
+ } catch (encryptionError) {
+ authLogger.error(
+ "Failed to setup user data encryption after password reset",
+ encryptionError,
+ {
+ operation: "password_reset_encryption_failed_preserved",
+ userId,
+ username,
+ },
+ );
+ return res.status(500).json({
+ error: "Password reset failed. Please contact administrator.",
+ });
+ }
+ } else {
+ await db
+ .update(users)
+ .set({ passwordHash: password_hash })
+ .where(eq(users.username, username));
+
+ try {
+ await db
+ .delete(sshCredentialUsage)
+ .where(eq(sshCredentialUsage.userId, userId));
+ await db
+ .delete(fileManagerRecent)
+ .where(eq(fileManagerRecent.userId, userId));
+ await db
+ .delete(fileManagerPinned)
+ .where(eq(fileManagerPinned.userId, userId));
+ await db
+ .delete(fileManagerShortcuts)
+ .where(eq(fileManagerShortcuts.userId, userId));
+ await db
+ .delete(recentActivity)
+ .where(eq(recentActivity.userId, userId));
+ await db
+ .delete(dismissedAlerts)
+ .where(eq(dismissedAlerts.userId, userId));
+ await db.delete(snippets).where(eq(snippets.userId, userId));
+ await db.delete(hosts).where(eq(hosts.userId, userId));
+ await db
+ .delete(sshCredentials)
+ .where(eq(sshCredentials.userId, userId));
+
+ await authManager.registerUser(userId, newPassword);
+ authManager.logoutUser(userId);
+
+ await db
+ .update(users)
+ .set({
+ totpEnabled: false,
+ totpSecret: null,
+ totpBackupCodes: null,
+ })
+ .where(eq(users.id, userId));
+
+ authLogger.warn(
+ `Password reset completed for user: ${username}. All encrypted data has been deleted due to lost encryption key.`,
+ {
+ operation: "password_reset_data_deleted",
+ userId,
+ username,
+ },
+ );
+ } catch (encryptionError) {
+ authLogger.error(
+ "Failed to setup user data encryption after password reset",
+ encryptionError,
+ {
+ operation: "password_reset_encryption_failed",
+ userId,
+ username,
+ },
+ );
+ return res.status(500).json({
+ error: "Password reset failed. Please contact administrator.",
+ });
+ }
+ }
+
+ authLogger.success(`Password successfully reset for user: ${username}`);
+
+ db.$client
+ .prepare("DELETE FROM settings WHERE key = ?")
+ .run(`reset_code_${username}`);
+ db.$client
+ .prepare("DELETE FROM settings WHERE key = ?")
+ .run(`temp_reset_token_${username}`);
+
+ res.json({ message: "Password has been successfully reset" });
+ } catch (err) {
+ authLogger.error("Failed to complete password reset", err);
+ res.status(500).json({ error: "Failed to complete password reset" });
+ }
+ });
+}
diff --git a/src/backend/database/routes/user-preferences.ts b/src/backend/database/routes/user-preferences.ts
index 0f10bbcd7..203418ff4 100644
--- a/src/backend/database/routes/user-preferences.ts
+++ b/src/backend/database/routes/user-preferences.ts
@@ -11,6 +11,14 @@ const router = express.Router();
const authManager = AuthManager.getInstance();
const authenticateJWT = authManager.createAuthMiddleware();
+const pickPreferences = (row?: typeof userPreferences.$inferSelect) => ({
+ reopenTabsOnLogin: row?.reopenTabsOnLogin ?? false,
+ theme: row?.theme ?? null,
+ fontSize: row?.fontSize ?? null,
+ accentColor: row?.accentColor ?? null,
+ language: row?.language ?? null,
+});
+
/**
* @openapi
* /user-preferences:
@@ -38,12 +46,12 @@ router.get("/", authenticateJWT, (req: Request, res: Response) => {
.where(eq(userPreferences.userId, userId))
.all();
- if (rows.length === 0) {
- return res.json({ reopenTabsOnLogin: false });
- }
- return res.json({ reopenTabsOnLogin: rows[0].reopenTabsOnLogin });
+ return res.json(pickPreferences(rows[0]));
} catch (e) {
- databaseLogger.error("Failed to get user preferences", e, { operation: "get_user_preferences", userId });
+ databaseLogger.error("Failed to get user preferences", e, {
+ operation: "get_user_preferences",
+ userId,
+ });
return res.status(500).json({ error: "Failed to get user preferences" });
}
});
@@ -70,10 +78,46 @@ router.get("/", authenticateJWT, (req: Request, res: Response) => {
*/
router.put("/", authenticateJWT, (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
- const { reopenTabsOnLogin } = req.body as { reopenTabsOnLogin?: boolean };
+ const { reopenTabsOnLogin, theme, fontSize, accentColor, language } =
+ req.body as {
+ reopenTabsOnLogin?: boolean;
+ theme?: string | null;
+ fontSize?: string | null;
+ accentColor?: string | null;
+ language?: string | null;
+ };
+
+ const updates: Partial<typeof userPreferences.$inferInsert> = {
+ updatedAt: new Date().toISOString(),
+ };
+
+ if (reopenTabsOnLogin !== undefined) {
+ if (typeof reopenTabsOnLogin !== "boolean") {
+ return res
+ .status(400)
+ .json({ error: "reopenTabsOnLogin must be a boolean" });
+ }
+ updates.reopenTabsOnLogin = reopenTabsOnLogin;
+ }
+
+ for (const [key, value] of Object.entries({
+ theme,
+ fontSize,
+ accentColor,
+ language,
+ })) {
+ if (value !== undefined && value !== null && typeof value !== "string") {
+ return res.status(400).json({ error: `${key} must be a string` });
+ }
+ }
+
+ if (theme !== undefined) updates.theme = theme;
+ if (fontSize !== undefined) updates.fontSize = fontSize;
+ if (accentColor !== undefined) updates.accentColor = accentColor;
+ if (language !== undefined) updates.language = language;
- if (typeof reopenTabsOnLogin !== "boolean") {
- return res.status(400).json({ error: "reopenTabsOnLogin must be a boolean" });
+ if (Object.keys(updates).length === 1) {
+ return res.status(400).json({ error: "No preferences provided" });
}
try {
@@ -84,21 +128,25 @@ router.put("/", authenticateJWT, (req: Request, res: Response) => {
.all();
if (existing.length === 0) {
- db.insert(userPreferences).values({
- userId,
- reopenTabsOnLogin,
- updatedAt: new Date().toISOString(),
- }).run();
+ db.insert(userPreferences)
+ .values({
+ userId,
+ ...updates,
+ })
+ .run();
} else {
db.update(userPreferences)
- .set({ reopenTabsOnLogin, updatedAt: new Date().toISOString() })
+ .set(updates)
.where(eq(userPreferences.userId, userId))
.run();
}
- return res.json({ success: true, reopenTabsOnLogin });
+ return res.json({ success: true, ...updates });
} catch (e) {
- databaseLogger.error("Failed to update user preferences", e, { operation: "update_user_preferences", userId });
+ databaseLogger.error("Failed to update user preferences", e, {
+ operation: "update_user_preferences",
+ userId,
+ });
return res.status(500).json({ error: "Failed to update user preferences" });
}
});
diff --git a/src/backend/database/routes/user-session-routes.ts b/src/backend/database/routes/user-session-routes.ts
new file mode 100644
index 000000000..3726ffa05
--- /dev/null
+++ b/src/backend/database/routes/user-session-routes.ts
@@ -0,0 +1,256 @@
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import type { RequestHandler, Router } from "express";
+import { eq } from "drizzle-orm";
+import { AuthManager } from "../../utils/auth-manager.js";
+import { authLogger } from "../../utils/logger.js";
+import { db } from "../db/index.js";
+import { sessions, users } from "../db/schema.js";
+
+type UserSessionRoutesDeps = {
+ authenticateJWT: RequestHandler;
+ authManager: AuthManager;
+};
+
+export function registerUserSessionRoutes(
+ router: Router,
+ { authenticateJWT, authManager }: UserSessionRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /users/sessions:
+ * get:
+ * summary: Get sessions
+ * description: Retrieves all sessions for authenticated user (or all sessions for admins).
+ * tags:
+ * - Users
+ * responses:
+ * 200:
+ * description: Sessions list returned.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to get sessions.
+ */
+ router.get("/sessions", authenticateJWT, async (req, res) => {
+ const authReq = req as AuthenticatedRequest;
+ const userId = authReq.userId;
+ const currentSessionId = authReq.sessionId;
+
+ try {
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ const userRecord = user[0];
+ let sessionList;
+
+ if (userRecord.isAdmin) {
+ sessionList = await authManager.getAllSessions();
+
+ const enrichedSessions = await Promise.all(
+ sessionList.map(async (session) => {
+ const sessionUser = await db
+ .select({ username: users.username })
+ .from(users)
+ .where(eq(users.id, session.userId))
+ .limit(1);
+
+ return {
+ id: session.id,
+ userId: session.userId,
+ username: sessionUser[0]?.username || "Unknown",
+ deviceType: session.deviceType,
+ deviceInfo: session.deviceInfo,
+ createdAt: session.createdAt,
+ expiresAt: session.expiresAt,
+ lastActiveAt: session.lastActiveAt,
+ isRevoked: session.isRevoked,
+ isCurrentSession: session.id === currentSessionId,
+ };
+ }),
+ );
+
+ return res.json({ sessions: enrichedSessions });
+ } else {
+ sessionList = await authManager.getUserSessions(userId);
+ return res.json({
+ sessions: sessionList.map((session) => ({
+ id: session.id,
+ userId: session.userId,
+ deviceType: session.deviceType,
+ deviceInfo: session.deviceInfo,
+ createdAt: session.createdAt,
+ expiresAt: session.expiresAt,
+ lastActiveAt: session.lastActiveAt,
+ isRevoked: session.isRevoked,
+ isCurrentSession: session.id === currentSessionId,
+ })),
+ });
+ }
+ } catch (err) {
+ authLogger.error("Failed to get sessions", err);
+ res.status(500).json({ error: "Failed to get sessions" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/sessions/{sessionId}:
+ * delete:
+ * summary: Revoke a specific session
+ * description: Revokes a specific session by ID.
+ * tags:
+ * - Users
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * description: The session ID to revoke
+ * responses:
+ * 200:
+ * description: Session revoked successfully.
+ * 400:
+ * description: Session ID is required.
+ * 403:
+ * description: Not authorized to revoke this session.
+ * 404:
+ * description: Session not found.
+ * 500:
+ * description: Failed to revoke session.
+ */
+ router.delete("/sessions/:sessionId", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const sessionId = Array.isArray(req.params.sessionId)
+ ? req.params.sessionId[0]
+ : req.params.sessionId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ try {
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ const userRecord = user[0];
+
+ const sessionRecords = await db
+ .select()
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+
+ if (sessionRecords.length === 0) {
+ return res.status(404).json({ error: "Session not found" });
+ }
+
+ const session = sessionRecords[0];
+
+ if (!userRecord.isAdmin && session.userId !== userId) {
+ return res
+ .status(403)
+ .json({ error: "Not authorized to revoke this session" });
+ }
+
+ const success = await authManager.revokeSession(sessionId);
+
+ if (success) {
+ authLogger.success("Session revoked", {
+ operation: "session_revoke",
+ sessionId,
+ revokedBy: userId,
+ sessionUserId: session.userId,
+ });
+ res.json({ success: true, message: "Session revoked successfully" });
+ } else {
+ res.status(500).json({ error: "Failed to revoke session" });
+ }
+ } catch (err) {
+ authLogger.error("Failed to revoke session", err);
+ res.status(500).json({ error: "Failed to revoke session" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/sessions/revoke-all:
+ * post:
+ * summary: Revoke all sessions for a user
+ * description: Revokes all sessions with option to exclude current session.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: false
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * targetUserId:
+ * type: string
+ * exceptCurrent:
+ * type: boolean
+ * responses:
+ * 200:
+ * description: Sessions revoked successfully.
+ * 403:
+ * description: Not authorized to revoke sessions for other users.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to revoke sessions.
+ */
+ router.post("/sessions/revoke-all", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { targetUserId, exceptCurrent } = req.body;
+
+ try {
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ const userRecord = user[0];
+
+ let revokeUserId = userId;
+ if (targetUserId && userRecord.isAdmin) {
+ revokeUserId = targetUserId;
+ } else if (targetUserId && targetUserId !== userId) {
+ return res.status(403).json({
+ error: "Not authorized to revoke sessions for other users",
+ });
+ }
+
+ let currentSessionId: string | undefined;
+ if (exceptCurrent) {
+ currentSessionId = (req as AuthenticatedRequest).sessionId;
+ }
+
+ const revokedCount = await authManager.revokeAllUserSessions(
+ revokeUserId,
+ currentSessionId,
+ );
+
+ authLogger.success("User sessions revoked", {
+ operation: "user_sessions_revoke_all",
+ revokeUserId,
+ revokedBy: userId,
+ exceptCurrent,
+ revokedCount,
+ });
+
+ res.json({
+ message: `${revokedCount} session(s) revoked successfully`,
+ count: revokedCount,
+ });
+ } catch (err) {
+ authLogger.error("Failed to revoke user sessions", err);
+ res.status(500).json({ error: "Failed to revoke sessions" });
+ }
+ });
+}
diff --git a/src/backend/database/routes/user-settings-routes.ts b/src/backend/database/routes/user-settings-routes.ts
new file mode 100644
index 000000000..0cd372742
--- /dev/null
+++ b/src/backend/database/routes/user-settings-routes.ts
@@ -0,0 +1,276 @@
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import type { RequestHandler, Router } from "express";
+import { eq } from "drizzle-orm";
+import { restartGuacServer } from "../../guacamole/guacamole-server.js";
+import {
+ authLogger,
+ getGlobalLogLevel,
+ setGlobalLogLevel,
+} from "../../utils/logger.js";
+import { db } from "../db/index.js";
+import { users } from "../db/schema.js";
+
+function getDefaultGuacUrl(): string {
+ return `${process.env.GUACD_HOST || "localhost"}:${process.env.GUACD_PORT || "4822"}`;
+}
+
+export function registerUserSettingsRoutes(
+ router: Router,
+ authenticateJWT: RequestHandler,
+): void {
+ /**
+ * @openapi
+ * /users/guacamole-settings:
+ * get:
+ * summary: Get Guacamole settings
+ * description: Returns current guacd enabled status and host:port URL. No authentication required.
+ * tags:
+ * - Users
+ * responses:
+ * 200:
+ * description: Guacamole settings.
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * enabled:
+ * type: boolean
+ * url:
+ * type: string
+ * 500:
+ * description: Failed to get guacamole settings.
+ */
+ router.get("/guacamole-settings", authenticateJWT, async (_req, res) => {
+ try {
+ const enabledRow = db.$client
+ .prepare("SELECT value FROM settings WHERE key = 'guac_enabled'")
+ .get() as { value: string } | undefined;
+ const urlRow = db.$client
+ .prepare("SELECT value FROM settings WHERE key = 'guac_url'")
+ .get() as { value: string } | undefined;
+ res.json({
+ enabled: enabledRow ? enabledRow.value !== "false" : true,
+ url: urlRow ? urlRow.value : getDefaultGuacUrl(),
+ });
+ } catch (err) {
+ authLogger.error("Failed to get guacamole settings", err);
+ res.status(500).json({ error: "Failed to get guacamole settings" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/guacamole-settings:
+ * patch:
+ * summary: Update Guacamole settings
+ * description: Admin-only. Updates guacd enabled status and/or host:port URL.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * enabled:
+ * type: boolean
+ * url:
+ * type: string
+ * responses:
+ * 200:
+ * description: Guacamole settings updated.
+ * 403:
+ * description: Not authorized.
+ * 500:
+ * description: Failed to update guacamole settings.
+ */
+ router.patch("/guacamole-settings", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ try {
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0 || !user[0].isAdmin) {
+ return res.status(403).json({ error: "Not authorized" });
+ }
+ const { enabled, url } = req.body;
+ if (typeof enabled === "boolean") {
+ db.$client
+ .prepare(
+ "INSERT OR REPLACE INTO settings (key, value) VALUES ('guac_enabled', ?)",
+ )
+ .run(enabled ? "true" : "false");
+ }
+ if (typeof url === "string") {
+ db.$client
+ .prepare(
+ "INSERT OR REPLACE INTO settings (key, value) VALUES ('guac_url', ?)",
+ )
+ .run(url);
+ try {
+ await restartGuacServer();
+ } catch (err) {
+ authLogger.error(
+ "Failed to restart guac server after URL update",
+ err,
+ );
+ }
+ }
+ const enabledRow = db.$client
+ .prepare("SELECT value FROM settings WHERE key = 'guac_enabled'")
+ .get() as { value: string } | undefined;
+ const urlRow = db.$client
+ .prepare("SELECT value FROM settings WHERE key = 'guac_url'")
+ .get() as { value: string } | undefined;
+ res.json({
+ enabled: enabledRow ? enabledRow.value !== "false" : true,
+ url: urlRow ? urlRow.value : getDefaultGuacUrl(),
+ });
+ } catch (err) {
+ authLogger.error("Failed to update guacamole settings", err);
+ res.status(500).json({ error: "Failed to update guacamole settings" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/log-level:
+ * get:
+ * summary: Get log level setting
+ * description: Returns the configured log verbosity level.
+ * tags:
+ * - Users
+ * responses:
+ * 200:
+ * description: Current log level.
+ */
+ router.get("/log-level", authenticateJWT, async (_req, res) => {
+ try {
+ const row = db.$client
+ .prepare("SELECT value FROM settings WHERE key = 'log_level'")
+ .get() as { value: string } | undefined;
+ res.json({
+ level: row ? row.value : getGlobalLogLevel(),
+ });
+ } catch (err) {
+ authLogger.error("Failed to get log level", err);
+ res.status(500).json({ error: "Failed to get log level" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/log-level:
+ * patch:
+ * summary: Update log level setting (admin only)
+ * description: Sets the log verbosity level.
+ * tags:
+ * - Users
+ * responses:
+ * 200:
+ * description: Log level updated.
+ * 400:
+ * description: Invalid log level.
+ * 403:
+ * description: Not authorized.
+ */
+ router.patch("/log-level", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ try {
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0 || !user[0].isAdmin) {
+ return res.status(403).json({ error: "Not authorized" });
+ }
+ const { level } = req.body;
+ const validLevels = ["debug", "info", "warn", "error"];
+ if (typeof level !== "string" || !validLevels.includes(level)) {
+ return res
+ .status(400)
+ .json({ error: "level must be one of: debug, info, warn, error" });
+ }
+ db.$client
+ .prepare(
+ "INSERT OR REPLACE INTO settings (key, value) VALUES ('log_level', ?)",
+ )
+ .run(level);
+ setGlobalLogLevel(level);
+ res.json({ level });
+ } catch (err) {
+ authLogger.error("Failed to set log level", err);
+ res.status(500).json({ error: "Failed to set log level" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/session-timeout:
+ * get:
+ * summary: Get session timeout setting
+ * description: Returns the configured session timeout in hours.
+ * tags:
+ * - Users
+ * responses:
+ * 200:
+ * description: Current session timeout hours.
+ */
+ router.get("/session-timeout", authenticateJWT, async (_req, res) => {
+ try {
+ const row = db.$client
+ .prepare(
+ "SELECT value FROM settings WHERE key = 'session_timeout_hours'",
+ )
+ .get() as { value: string } | undefined;
+ res.json({
+ timeoutHours: row ? parseInt(row.value, 10) : 24,
+ });
+ } catch (err) {
+ authLogger.error("Failed to get session timeout", err);
+ res.status(500).json({ error: "Failed to get session timeout" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/session-timeout:
+ * patch:
+ * summary: Update session timeout setting (admin only)
+ * description: Sets the session timeout in hours.
+ * tags:
+ * - Users
+ * responses:
+ * 200:
+ * description: Session timeout updated.
+ * 400:
+ * description: Invalid value.
+ * 403:
+ * description: Not authorized.
+ */
+ router.patch("/session-timeout", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ try {
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0 || !user[0].isAdmin) {
+ return res.status(403).json({ error: "Not authorized" });
+ }
+ const { timeoutHours } = req.body;
+ if (
+ typeof timeoutHours !== "number" ||
+ timeoutHours < 1 ||
+ timeoutHours > 720
+ ) {
+ return res
+ .status(400)
+ .json({ error: "timeoutHours must be between 1 and 720" });
+ }
+ db.$client
+ .prepare(
+ "INSERT OR REPLACE INTO settings (key, value) VALUES ('session_timeout_hours', ?)",
+ )
+ .run(String(timeoutHours));
+ res.json({ timeoutHours });
+ } catch (err) {
+ authLogger.error("Failed to set session timeout", err);
+ res.status(500).json({ error: "Failed to set session timeout" });
+ }
+ });
+}
diff --git a/src/backend/database/routes/user-totp-routes.ts b/src/backend/database/routes/user-totp-routes.ts
new file mode 100644
index 000000000..71afae133
--- /dev/null
+++ b/src/backend/database/routes/user-totp-routes.ts
@@ -0,0 +1,583 @@
+import type { AuthenticatedRequest } from "../../../types/index.js";
+import type { Request, RequestHandler, Router } from "express";
+import { eq } from "drizzle-orm";
+import bcrypt from "bcryptjs";
+import QRCode from "qrcode";
+import speakeasy from "speakeasy";
+import { AuthManager } from "../../utils/auth-manager.js";
+import { LazyFieldEncryption } from "../../utils/lazy-field-encryption.js";
+import { authLogger } from "../../utils/logger.js";
+import { loginRateLimiter } from "../../utils/login-rate-limiter.js";
+import {
+ generateDeviceFingerprint,
+ parseUserAgent,
+} from "../../utils/user-agent-parser.js";
+import { db } from "../db/index.js";
+import { sessions, trustedDevices, users } from "../db/schema.js";
+
+type NativeAppRequestChecker = (req: Request) => boolean;
+
+interface UserTotpRoutesDeps {
+ authenticateJWT: RequestHandler;
+ authManager: AuthManager;
+ isNativeAppRequest: NativeAppRequestChecker;
+}
+
+export function registerUserTotpRoutes(
+ router: Router,
+ { authenticateJWT, authManager, isNativeAppRequest }: UserTotpRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /users/totp/setup:
+ * post:
+ * summary: Setup TOTP
+ * description: Initiates TOTP setup by generating a secret and QR code.
+ * tags:
+ * - Users
+ * responses:
+ * 200:
+ * description: TOTP setup initiated with secret and QR code.
+ * 400:
+ * description: TOTP is already enabled.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to setup TOTP.
+ */
+ router.post("/totp/setup", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+
+ try {
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ const userRecord = user[0];
+
+ if (userRecord.totpEnabled) {
+ return res.status(400).json({ error: "TOTP is already enabled" });
+ }
+
+ const secret = speakeasy.generateSecret({
+ name: `Termix (${userRecord.username})`,
+ length: 32,
+ });
+
+ await db
+ .update(users)
+ .set({ totpSecret: secret.base32 })
+ .where(eq(users.id, userId));
+
+ const qrCodeUrl = await QRCode.toDataURL(secret.otpauth_url || "");
+
+ res.json({
+ secret: secret.base32,
+ qr_code: qrCodeUrl,
+ });
+ } catch (err) {
+ authLogger.error("Failed to setup TOTP", err);
+ res.status(500).json({ error: "Failed to setup TOTP" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/totp/enable:
+ * post:
+ * summary: Enable TOTP
+ * description: Enables TOTP after verifying the initial code.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * totp_code:
+ * type: string
+ * responses:
+ * 200:
+ * description: TOTP enabled successfully with backup codes.
+ * 400:
+ * description: TOTP code is required or TOTP already enabled.
+ * 401:
+ * description: Invalid TOTP code.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to enable TOTP.
+ */
+ router.post("/totp/enable", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { totp_code } = req.body;
+
+ if (!totp_code) {
+ return res.status(400).json({ error: "TOTP code is required" });
+ }
+
+ try {
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ const userRecord = user[0];
+
+ if (userRecord.totpEnabled) {
+ return res.status(400).json({ error: "TOTP is already enabled" });
+ }
+
+ if (!userRecord.totpSecret) {
+ return res.status(400).json({ error: "TOTP setup not initiated" });
+ }
+
+ const verified = speakeasy.totp.verify({
+ secret: userRecord.totpSecret,
+ encoding: "base32",
+ token: totp_code,
+ window: 2,
+ });
+
+ if (!verified) {
+ return res.status(401).json({ error: "Invalid TOTP code" });
+ }
+
+ const backupCodes = Array.from({ length: 8 }, () =>
+ Math.random().toString(36).substring(2, 10).toUpperCase(),
+ );
+
+ await db
+ .update(users)
+ .set({
+ totpEnabled: true,
+ totpBackupCodes: JSON.stringify(backupCodes),
+ })
+ .where(eq(users.id, userId));
+
+ await db.delete(sessions).where(eq(sessions.userId, userId));
+ await db.delete(trustedDevices).where(eq(trustedDevices.userId, userId));
+
+ try {
+ const { saveMemoryDatabaseToFile } = await import("../db/index.js");
+ await saveMemoryDatabaseToFile();
+ } catch (saveError) {
+ authLogger.error(
+ "Failed to persist TOTP enablement to disk",
+ saveError,
+ {
+ operation: "totp_enable_db_save_failed",
+ userId,
+ },
+ );
+ }
+
+ res.json({
+ message: "TOTP enabled successfully",
+ backup_codes: backupCodes,
+ });
+ } catch (err) {
+ authLogger.error("Failed to enable TOTP", err);
+ res.status(500).json({ error: "Failed to enable TOTP" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/totp/disable:
+ * post:
+ * summary: Disable TOTP
+ * description: Disables TOTP for a user.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * password:
+ * type: string
+ * totp_code:
+ * type: string
+ * responses:
+ * 200:
+ * description: TOTP disabled successfully.
+ * 400:
+ * description: Password or TOTP code is required.
+ * 401:
+ * description: Incorrect password or invalid TOTP code.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to disable TOTP.
+ */
+ router.post("/totp/disable", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { password, totp_code } = req.body;
+
+ if (!password || !totp_code) {
+ return res
+ .status(400)
+ .json({ error: "Both password and TOTP code are required" });
+ }
+
+ try {
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ const userRecord = user[0];
+
+ if (!userRecord.totpEnabled) {
+ return res.status(400).json({ error: "TOTP is not enabled" });
+ }
+
+ if (!userRecord.isOidc) {
+ const isMatch = await bcrypt.compare(password, userRecord.passwordHash);
+ if (!isMatch) {
+ return res.status(401).json({ error: "Incorrect password" });
+ }
+ }
+
+ const verified = speakeasy.totp.verify({
+ secret: userRecord.totpSecret!,
+ encoding: "base32",
+ token: totp_code,
+ window: 2,
+ });
+
+ if (!verified) {
+ return res.status(401).json({ error: "Invalid TOTP code" });
+ }
+
+ await db
+ .update(users)
+ .set({
+ totpEnabled: false,
+ totpSecret: null,
+ totpBackupCodes: null,
+ })
+ .where(eq(users.id, userId));
+ authLogger.info("Two-factor authentication disabled", {
+ operation: "totp_disable",
+ userId,
+ });
+
+ res.json({ message: "TOTP disabled successfully" });
+ } catch (err) {
+ authLogger.error("Failed to disable TOTP", err);
+ res.status(500).json({ error: "Failed to disable TOTP" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/totp/backup-codes:
+ * post:
+ * summary: Generate new backup codes
+ * description: Generates new TOTP backup codes.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * password:
+ * type: string
+ * totp_code:
+ * type: string
+ * responses:
+ * 200:
+ * description: New backup codes generated.
+ * 400:
+ * description: Password or TOTP code is required.
+ * 401:
+ * description: Incorrect password or invalid TOTP code.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: Failed to generate backup codes.
+ */
+ router.post("/totp/backup-codes", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { password, totp_code } = req.body;
+
+ if (!password || !totp_code) {
+ return res
+ .status(400)
+ .json({ error: "Both password and TOTP code are required" });
+ }
+
+ try {
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ const userRecord = user[0];
+
+ if (!userRecord.totpEnabled) {
+ return res.status(400).json({ error: "TOTP is not enabled" });
+ }
+
+ if (!userRecord.isOidc) {
+ const isMatch = await bcrypt.compare(password, userRecord.passwordHash);
+ if (!isMatch) {
+ return res.status(401).json({ error: "Incorrect password" });
+ }
+ }
+
+ const verified = speakeasy.totp.verify({
+ secret: userRecord.totpSecret!,
+ encoding: "base32",
+ token: totp_code,
+ window: 2,
+ });
+
+ if (!verified) {
+ return res.status(401).json({ error: "Invalid TOTP code" });
+ }
+
+ const backupCodes = Array.from({ length: 8 }, () =>
+ Math.random().toString(36).substring(2, 10).toUpperCase(),
+ );
+
+ await db
+ .update(users)
+ .set({ totpBackupCodes: JSON.stringify(backupCodes) })
+ .where(eq(users.id, userId));
+
+ res.json({ backup_codes: backupCodes });
+ } catch (err) {
+ authLogger.error("Failed to generate backup codes", err);
+ res.status(500).json({ error: "Failed to generate backup codes" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /users/totp/verify-login:
+ * post:
+ * summary: Verify TOTP during login
+ * description: Verifies the TOTP code during login.
+ * tags:
+ * - Users
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * temp_token:
+ * type: string
+ * totp_code:
+ * type: string
+ * responses:
+ * 200:
+ * description: TOTP verification successful.
+ * 400:
+ * description: Token and TOTP code are required.
+ * 401:
+ * description: Invalid temporary token or TOTP code.
+ * 404:
+ * description: User not found.
+ * 500:
+ * description: TOTP verification failed.
+ */
+ router.post("/totp/verify-login", async (req, res) => {
+ const { temp_token, totp_code, rememberMe } = req.body;
+
+ if (!temp_token || !totp_code) {
+ return res
+ .status(400)
+ .json({ error: "Token and TOTP code are required" });
+ }
+
+ try {
+ const decoded = await authManager.verifyJWTToken(temp_token);
+ if (!decoded || !decoded.pendingTOTP) {
+ return res.status(401).json({ error: "Invalid temporary token" });
+ }
+
+ const user = await db
+ .select()
+ .from(users)
+ .where(eq(users.id, decoded.userId));
+ if (!user || user.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
+
+ const userRecord = user[0];
+
+ const lockStatus = loginRateLimiter.isTOTPLocked(userRecord.id);
+ if (lockStatus.locked) {
+ authLogger.warn("TOTP verification blocked due to rate limiting", {
+ operation: "totp_verify_blocked",
+ userId: userRecord.id,
+ remainingTime: lockStatus.remainingTime,
+ });
+ return res.status(429).json({
+ error: `Rate limited: Too many TOTP verification attempts. Please wait ${lockStatus.remainingTime} seconds before trying again.`,
+ remainingTime: lockStatus.remainingTime,
+ code: "TOTP_RATE_LIMITED",
+ });
+ }
+
+ loginRateLimiter.recordFailedTOTPAttempt(userRecord.id);
+
+ if (!userRecord.totpEnabled || !userRecord.totpSecret) {
+ return res
+ .status(400)
+ .json({ error: "TOTP not enabled for this user" });
+ }
+
+ const userDataKey = authManager.getUserDataKey(userRecord.id);
+ if (!userDataKey) {
+ return res.status(401).json({
+ error: "Session expired - please log in again",
+ code: "SESSION_EXPIRED",
+ });
+ }
+
+ const totpSecret = LazyFieldEncryption.safeGetFieldValue(
+ userRecord.totpSecret,
+ userDataKey,
+ userRecord.id,
+ "totp_secret",
+ );
+
+ if (!totpSecret) {
+ await db
+ .update(users)
+ .set({
+ totpEnabled: false,
+ totpSecret: null,
+ totpBackupCodes: null,
+ })
+ .where(eq(users.id, userRecord.id));
+
+ return res.status(400).json({
+ error:
+ "TOTP has been disabled due to password reset. Please set up TOTP again.",
+ });
+ }
+
+ const verified = speakeasy.totp.verify({
+ secret: totpSecret,
+ encoding: "base32",
+ token: totp_code,
+ window: 2,
+ });
+
+ if (!verified) {
+ let backupCodes = [];
+ try {
+ backupCodes = userRecord.totpBackupCodes
+ ? JSON.parse(userRecord.totpBackupCodes)
+ : [];
+ } catch {
+ backupCodes = [];
+ }
+
+ if (!Array.isArray(backupCodes)) {
+ backupCodes = [];
+ }
+
+ const backupIndex = backupCodes.indexOf(totp_code);
+
+ if (backupIndex === -1) {
+ authLogger.warn("TOTP verification failed - invalid code", {
+ operation: "totp_verify_failed",
+ userId: userRecord.id,
+ remainingAttempts: loginRateLimiter.getRemainingTOTPAttempts(
+ userRecord.id,
+ ),
+ });
+ return res.status(401).json({
+ error: "Invalid TOTP code",
+ remainingAttempts: loginRateLimiter.getRemainingTOTPAttempts(
+ userRecord.id,
+ ),
+ });
+ }
+
+ backupCodes.splice(backupIndex, 1);
+ await db
+ .update(users)
+ .set({ totpBackupCodes: JSON.stringify(backupCodes) })
+ .where(eq(users.id, userRecord.id));
+ }
+
+ loginRateLimiter.resetTOTPAttempts(userRecord.id);
+
+ const deviceInfo = parseUserAgent(req);
+
+ if (rememberMe) {
+ const deviceFingerprint = generateDeviceFingerprint(deviceInfo);
+ await authManager.addTrustedDevice(
+ userRecord.id,
+ deviceFingerprint,
+ deviceInfo.type,
+ deviceInfo.deviceInfo,
+ );
+ authLogger.info("Device automatically trusted via Remember Me", {
+ operation: "totp_auto_trust",
+ userId: userRecord.id,
+ deviceType: deviceInfo.type,
+ });
+ }
+
+ const token = await authManager.generateJWTToken(userRecord.id, {
+ rememberMe: !!rememberMe,
+ deviceType: deviceInfo.type,
+ deviceInfo: deviceInfo.deviceInfo,
+ });
+
+ authLogger.success("TOTP verification successful", {
+ operation: "totp_verify_success",
+ userId: userRecord.id,
+ deviceType: deviceInfo.type,
+ deviceInfo: deviceInfo.deviceInfo,
+ });
+
+ const response: Record<string, unknown> = {
+ success: true,
+ is_admin: !!userRecord.isAdmin,
+ username: userRecord.username,
+ userId: userRecord.id,
+ is_oidc: !!userRecord.isOidc,
+ totp_enabled: !!userRecord.totpEnabled,
+ ...(isNativeAppRequest(req) ? { token } : {}),
+ };
+
+ const timeoutRow = db.$client
+ .prepare(
+ "SELECT value FROM settings WHERE key = 'session_timeout_hours'",
+ )
+ .get() as { value: string } | undefined;
+ const timeoutHours = timeoutRow
+ ? parseInt(timeoutRow.value, 10) || 24
+ : 24;
+ const maxAge = rememberMe
+ ? 30 * 24 * 60 * 60 * 1000
+ : timeoutHours * 60 * 60 * 1000;
+
+ return res
+ .cookie("jwt", token, authManager.getSecureCookieOptions(req, maxAge))
+ .json(response);
+ } catch (err) {
+ authLogger.error("TOTP verification failed", err);
+ return res.status(500).json({ error: "TOTP verification failed" });
+ }
+ });
+}
diff --git a/src/backend/database/routes/users.ts b/src/backend/database/routes/users.ts
index 64f3ee1da..4a5a6b143 100644
--- a/src/backend/database/routes/users.ts
+++ b/src/backend/database/routes/users.ts
@@ -1,225 +1,37 @@
import type { AuthenticatedRequest } from "../../../types/index.js";
import express from "express";
-import { restartGuacServer } from "../../guacamole/guacamole-server.js";
-import { setGlobalLogLevel, getGlobalLogLevel } from "../../utils/logger.js";
-import crypto from "crypto";
import { db } from "../db/index.js";
-import {
- users,
- sessions,
- trustedDevices,
- hosts,
- sshCredentials,
- fileManagerRecent,
- fileManagerPinned,
- fileManagerShortcuts,
- dismissedAlerts,
- settings,
- sshCredentialUsage,
- recentActivity,
- snippets,
- snippetFolders,
- sshFolders,
- commandHistory,
- roles,
- userRoles,
- hostAccess,
- sharedCredentials,
- auditLogs,
- sessionRecordings,
- networkTopology,
- dashboardPreferences,
- opksshTokens,
- apiKeys,
- userOpenTabs,
- userPreferences,
-} from "../db/schema.js";
+import { users, settings, roles, userRoles } from "../db/schema.js";
import { eq } from "drizzle-orm";
import bcrypt from "bcryptjs";
import { nanoid } from "nanoid";
-import speakeasy from "speakeasy";
-import QRCode from "qrcode";
import type { Request, Response } from "express";
import { authLogger } from "../../utils/logger.js";
import { AuthManager } from "../../utils/auth-manager.js";
import { DataCrypto } from "../../utils/data-crypto.js";
-import { LazyFieldEncryption } from "../../utils/lazy-field-encryption.js";
import {
parseUserAgent,
generateDeviceFingerprint,
} from "../../utils/user-agent-parser.js";
import { loginRateLimiter } from "../../utils/login-rate-limiter.js";
import { getRequestOriginWithForceHTTPS } from "../../utils/request-origin.js";
+import { deleteUserAndRelatedData } from "./delete-user-data.js";
+import {
+ getOIDCConfigFromEnv,
+ isOIDCUserAllowed,
+ verifyOIDCToken,
+} from "./user-oidc-utils.js";
+import { registerUserApiKeyRoutes } from "./user-api-key-routes.js";
+import { registerUserSettingsRoutes } from "./user-settings-routes.js";
+import { registerUserTotpRoutes } from "./user-totp-routes.js";
+import { registerUserSessionRoutes } from "./user-session-routes.js";
+import { registerUserOidcAccountRoutes } from "./user-oidc-account-routes.js";
+import { registerUserPasswordResetRoutes } from "./user-password-reset-routes.js";
+import { registerUserAdminRoutes } from "./user-admin-routes.js";
+import { registerUserDataAccessRoutes } from "./user-data-access-routes.js";
const authManager = AuthManager.getInstance();
-function getOIDCConfigFromEnv(): {
- client_id: string;
- client_secret: string;
- issuer_url: string;
- authorization_url: string;
- token_url: string;
- userinfo_url: string;
- identifier_path: string;
- name_path: string;
- scopes: string;
- allowed_users: string;
-} | null {
- const client_id = process.env.OIDC_CLIENT_ID;
- const client_secret = process.env.OIDC_CLIENT_SECRET;
- const issuer_url = process.env.OIDC_ISSUER_URL;
- const authorization_url = process.env.OIDC_AUTHORIZATION_URL;
- const token_url = process.env.OIDC_TOKEN_URL;
-
- if (
- !client_id ||
- !client_secret ||
- !issuer_url ||
- !authorization_url ||
- !token_url
- ) {
- return null;
- }
-
- return {
- client_id,
- client_secret,
- issuer_url,
- authorization_url,
- token_url,
- userinfo_url: process.env.OIDC_USERINFO_URL || "",
- identifier_path: process.env.OIDC_IDENTIFIER_PATH || "sub",
- name_path: process.env.OIDC_NAME_PATH || "name",
- scopes: process.env.OIDC_SCOPES || "openid email profile",
- allowed_users: process.env.OIDC_ALLOWED_USERS || "",
- };
-}
-
-function isOIDCUserAllowed(
- allowedUsers: string,
- identifier: string,
- email?: string,
-): boolean {
- if (!allowedUsers || !allowedUsers.trim()) return true;
- const patterns = allowedUsers
- .split(",")
- .map((p) => p.trim())
- .filter(Boolean);
- if (patterns.length === 0) return true;
-
- const values = [
- identifier,
- ...(email && email !== identifier ? [email] : []),
- ];
- for (const pattern of patterns) {
- if (pattern === "*") return true;
- for (const value of values) {
- if (!value) continue;
- if (pattern.toLowerCase().startsWith("@")) {
- if (value.toLowerCase().endsWith(pattern.toLowerCase())) return true;
- } else {
- if (value.toLowerCase() === pattern.toLowerCase()) return true;
- }
- }
- }
- return false;
-}
-
-async function verifyOIDCToken(
- idToken: string,
- issuerUrl: string,
- clientId: string,
-): Promise<Record<string, unknown>> {
- const normalizedIssuerUrl = issuerUrl.endsWith("/")
- ? issuerUrl.slice(0, -1)
- : issuerUrl;
- const possibleIssuers = [
- issuerUrl,
- normalizedIssuerUrl,
- issuerUrl.replace(/\/application\/o\/[^/]+$/, ""),
- normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, ""),
- ];
-
- const jwksUrls = [
- `${normalizedIssuerUrl}/.well-known/jwks.json`,
- `${normalizedIssuerUrl}/jwks/`,
- `${normalizedIssuerUrl.replace(/\/application\/o\/[^/]+$/, "")}/.well-known/jwks.json`,
- ];
-
- try {
- const discoveryUrl = `${normalizedIssuerUrl}/.well-known/openid-configuration`;
- const discoveryResponse = await fetch(discoveryUrl);
- if (discoveryResponse.ok) {
- const discovery = (await discoveryResponse.json()) as Record<
- string,
- unknown
- >;
- if (discovery.jwks_uri) {
- jwksUrls.unshift(discovery.jwks_uri as string);
- }
- }
- } catch (discoveryError) {
- authLogger.error(`OIDC discovery failed: ${discoveryError}`);
- }
-
- let jwks: Record<string, unknown> | null = null;
-
- for (const url of jwksUrls) {
- try {
- const response = await fetch(url);
- if (response.ok) {
- const jwksData = (await response.json()) as Record<string, unknown>;
- if (jwksData && jwksData.keys && Array.isArray(jwksData.keys)) {
- jwks = jwksData;
- break;
- } else {
- authLogger.error(
- `Invalid JWKS structure from ${url}: ${JSON.stringify(jwksData)}`,
- );
- }
- } else {
- // expected - non-ok response, try next URL
- }
- } catch {
- continue;
- }
- }
-
- if (!jwks) {
- throw new Error("Failed to fetch JWKS from any URL");
- }
-
- if (!jwks.keys || !Array.isArray(jwks.keys)) {
- throw new Error(
- `Invalid JWKS response structure. Expected 'keys' array, got: ${JSON.stringify(jwks)}`,
- );
- }
-
- const header = JSON.parse(
- Buffer.from(idToken.split(".")[0], "base64").toString(),
- );
- const keyId = header.kid;
-
- const publicKey = jwks.keys.find(
- (key: Record<string, unknown>) => key.kid === keyId,
- );
- if (!publicKey) {
- throw new Error(
- `No matching public key found for key ID: ${keyId}. Available keys: ${jwks.keys.map((k: Record<string, unknown>) => k.kid).join(", ")}`,
- );
- }
-
- const { importJWK, jwtVerify } = await import("jose");
- const key = await importJWK(publicKey);
-
- const { payload } = await jwtVerify(idToken, key, {
- issuer: possibleIssuers,
- audience: clientId,
- });
-
- return payload;
-}
-
const router = express.Router();
function isNonEmptyString(val: unknown): val is string {
@@ -236,78 +48,6 @@ function isNativeAppRequest(req: Request): boolean {
const authenticateJWT = authManager.createAuthMiddleware();
const requireAdmin = authManager.createAdminMiddleware();
-async function deleteUserAndRelatedData(userId: string): Promise<void> {
- try {
- await db
- .delete(sharedCredentials)
- .where(eq(sharedCredentials.targetUserId, userId));
-
- await db
- .delete(sessionRecordings)
- .where(eq(sessionRecordings.userId, userId));
-
- await db.delete(hostAccess).where(eq(hostAccess.userId, userId));
- await db.delete(hostAccess).where(eq(hostAccess.grantedBy, userId));
-
- await db.delete(sessions).where(eq(sessions.userId, userId));
-
- await db.delete(userRoles).where(eq(userRoles.userId, userId));
- await db.delete(auditLogs).where(eq(auditLogs.userId, userId));
-
- await db
- .delete(sshCredentialUsage)
- .where(eq(sshCredentialUsage.userId, userId));
-
- await db
- .delete(fileManagerRecent)
- .where(eq(fileManagerRecent.userId, userId));
- await db
- .delete(fileManagerPinned)
- .where(eq(fileManagerPinned.userId, userId));
- await db
- .delete(fileManagerShortcuts)
- .where(eq(fileManagerShortcuts.userId, userId));
-
- await db.delete(recentActivity).where(eq(recentActivity.userId, userId));
- await db.delete(dismissedAlerts).where(eq(dismissedAlerts.userId, userId));
-
- await db.delete(snippets).where(eq(snippets.userId, userId));
- await db.delete(snippetFolders).where(eq(snippetFolders.userId, userId));
-
- await db.delete(sshFolders).where(eq(sshFolders.userId, userId));
-
- await db.delete(commandHistory).where(eq(commandHistory.userId, userId));
-
- await db.delete(hosts).where(eq(hosts.userId, userId));
- await db.delete(sshCredentials).where(eq(sshCredentials.userId, userId));
-
- await db.delete(networkTopology).where(eq(networkTopology.userId, userId));
- await db
- .delete(dashboardPreferences)
- .where(eq(dashboardPreferences.userId, userId));
- await db.delete(opksshTokens).where(eq(opksshTokens.userId, userId));
- await db.delete(userOpenTabs).where(eq(userOpenTabs.userId, userId));
- await db.delete(userPreferences).where(eq(userPreferences.userId, userId));
-
- db.$client
- .prepare("DELETE FROM settings WHERE key LIKE ?")
- .run(`user_%_${userId}`);
-
- await db.delete(users).where(eq(users.id, userId));
-
- authLogger.success("User and all related data deleted successfully", {
- operation: "delete_user_and_related_data_complete",
- userId,
- });
- } catch (error) {
- authLogger.error("Failed to delete user and related data", error, {
- operation: "delete_user_and_related_data_failed",
- userId,
- });
- throw error;
- }
-}
-
/**
* @openapi
* /users/create:
@@ -390,33 +130,39 @@ router.post("/create", async (req, res) => {
return res.status(409).json({ error: "Username already exists" });
}
- let isFirstUser = false;
- const countResult = db.$client
- .prepare("SELECT COUNT(*) as count FROM users")
- .get();
- isFirstUser = ((countResult as { count?: number })?.count || 0) === 0;
-
const saltRounds = parseInt(process.env.SALT || "10", 10);
const password_hash = await bcrypt.hash(password, saltRounds);
const id = nanoid();
- await db.insert(users).values({
- id,
- username,
- passwordHash: password_hash,
- isAdmin: isFirstUser,
- isOidc: false,
- clientId: "",
- clientSecret: "",
- issuerUrl: "",
- authorizationUrl: "",
- tokenUrl: "",
- identifierPath: "",
- namePath: "",
- scopes: "openid email profile",
- totpSecret: null,
- totpEnabled: false,
- totpBackupCodes: null,
- });
+
+ const isFirstUser = db.$client.transaction(() => {
+ const countResult = db.$client
+ .prepare("SELECT COUNT(*) as count FROM users")
+ .get() as { count?: number };
+ const first = (countResult?.count || 0) === 0;
+ db.$client
+ .prepare(
+ "INSERT INTO users (id, username, password_hash, is_admin, is_oidc, client_id, client_secret, issuer_url, authorization_url, token_url, identifier_path, name_path, scopes, totp_secret, totp_enabled, totp_backup_codes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ )
+ .run(
+ id,
+ username,
+ password_hash,
+ first ? 1 : 0,
+ 0,
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "openid email profile",
+ null,
+ 0,
+ null,
+ );
+ return first;
+ })();
try {
const defaultRoleName = isFirstUser ? "admin" : "user";
@@ -823,7 +569,7 @@ router.get("/oidc-config/admin", requireAdmin, async (req, res) => {
*/
router.get("/oidc/authorize", async (req, res) => {
try {
- const { rememberMe, desktopCallbackPort } = req.query;
+ const { rememberMe, desktopCallbackPort, appCallbackUrl } = req.query;
const origin = getRequestOriginWithForceHTTPS(req);
const backendCallbackUri = `${origin}/users/oidc/callback`;
@@ -848,6 +594,17 @@ router.get("/oidc/authorize", async (req, res) => {
let frontendOrigin;
if (desktopCallbackPort) {
frontendOrigin = `http://127.0.0.1:${desktopCallbackPort}/oidc-callback`;
+ } else if (typeof appCallbackUrl === "string" && appCallbackUrl) {
+ let callbackUrl: URL;
+ try {
+ callbackUrl = new URL(appCallbackUrl);
+ } catch {
+ return res.status(400).json({ error: "Invalid app callback URL" });
+ }
+ if (callbackUrl.protocol !== "termix-mobile:") {
+ return res.status(400).json({ error: "Unsupported app callback URL" });
+ }
+ frontendOrigin = callbackUrl.toString();
} else if (referer) {
const refererUrl = new URL(referer);
frontendOrigin = `${refererUrl.protocol}//${refererUrl.host}`;
@@ -1151,10 +908,10 @@ router.get("/oidc/callback", async (req, res) => {
let isFirstUser = false;
if (!user || user.length === 0) {
- const countResult = db.$client
+ const preCheckCount = db.$client
.prepare("SELECT COUNT(*) as count FROM users")
.get();
- isFirstUser = ((countResult as { count?: number })?.count || 0) === 0;
+ isFirstUser = ((preCheckCount as { count?: number })?.count || 0) === 0;
if (!isFirstUser && config.allowed_users) {
const email = userInfo.email as string | undefined;
@@ -1222,22 +979,33 @@ router.get("/oidc/callback", async (req, res) => {
}
const id = nanoid();
- await db.insert(users).values({
- id,
- username: name,
- passwordHash: "",
- isAdmin: isFirstUser,
- isOidc: true,
- oidcIdentifier: identifier,
- clientId: String(config.client_id),
- clientSecret: String(config.client_secret),
- issuerUrl: String(config.issuer_url),
- authorizationUrl: String(config.authorization_url),
- tokenUrl: String(config.token_url),
- identifierPath: String(config.identifier_path),
- namePath: String(config.name_path),
- scopes: String(config.scopes),
- });
+ isFirstUser = db.$client.transaction(() => {
+ const countResult = db.$client
+ .prepare("SELECT COUNT(*) as count FROM users")
+ .get() as { count?: number };
+ const first = (countResult?.count || 0) === 0;
+ db.$client
+ .prepare(
+ "INSERT INTO users (id, username, password_hash, is_admin, is_oidc, oidc_identifier, client_id, client_secret, issuer_url, authorization_url, token_url, identifier_path, name_path, scopes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ )
+ .run(
+ id,
+ name,
+ "",
+ first ? 1 : 0,
+ 1,
+ identifier,
+ String(config.client_id),
+ String(config.client_secret),
+ String(config.issuer_url),
+ String(config.authorization_url),
+ String(config.token_url),
+ String(config.identifier_path),
+ String(config.name_path),
+ String(config.scopes),
+ );
+ return first;
+ })();
try {
const defaultRoleName = isFirstUser ? "admin" : "user";
@@ -1389,7 +1157,9 @@ router.get("/oidc/callback", async (req, res) => {
const redirectUrl = new URL(frontendOrigin);
redirectUrl.searchParams.set("success", "true");
- const isDesktopCallback = frontendOrigin.startsWith("http://127.0.0.1:");
+ const isTokenCallback =
+ frontendOrigin.startsWith("http://127.0.0.1:") ||
+ frontendOrigin.startsWith("termix-mobile:");
const maxAge =
deviceInfo.type === "desktop" || deviceInfo.type === "mobile"
@@ -1400,7 +1170,7 @@ router.get("/oidc/callback", async (req, res) => {
res.clearCookie("jwt", authManager.getClearCookieOptions(req));
- if (isDesktopCallback) {
+ if (isTokenCallback) {
redirectUrl.searchParams.set("token", token);
return res.redirect(redirectUrl.toString());
}
@@ -2239,12 +2009,14 @@ router.delete("/delete-account", authenticateJWT, async (req, res) => {
}
});
+registerUserPasswordResetRoutes(router, { authManager });
+
/**
* @openapi
- * /users/initiate-reset:
+ * /users/change-password:
* post:
- * summary: Initiate password reset
- * description: Initiates the password reset process for a user.
+ * summary: Change user password
+ * description: Changes the authenticated user's password.
* tags:
* - Users
* requestBody:
@@ -2254,96 +2026,94 @@ router.delete("/delete-account", authenticateJWT, async (req, res) => {
* schema:
* type: object
* properties:
- * username:
+ * oldPassword:
+ * type: string
+ * newPassword:
* type: string
* responses:
* 200:
- * description: Password reset code has been generated.
+ * description: Password changed successfully.
* 400:
- * description: Username is required.
- * 403:
- * description: Password reset not available for external authentication users.
- * 404:
- * description: User not found.
+ * description: Old and new passwords are required.
+ * 401:
+ * description: Incorrect current password.
* 500:
- * description: Failed to initiate password reset.
+ * description: Failed to update password and re-encrypt data.
*/
-router.post("/initiate-reset", async (req, res) => {
- try {
- const row = db.$client
- .prepare("SELECT value FROM settings WHERE key = 'allow_password_reset'")
- .get();
- if (row && (row as { value: string }).value !== "true") {
- return res
- .status(403)
- .json({ error: "Password reset is currently disabled" });
- }
- } catch (e) {
- authLogger.warn("Failed to check password reset status", {
- operation: "password_reset_check",
- error: e,
- });
+router.post("/change-password", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { oldPassword, newPassword } = req.body;
+ authLogger.info("Password change request", {
+ operation: "password_change_request",
+ userId,
+ });
+
+ if (!userId) {
+ return res.status(401).json({ error: "User not authenticated" });
}
- const { username } = req.body;
+ if (!oldPassword || !newPassword) {
+ return res
+ .status(400)
+ .json({ error: "Old and new passwords are required." });
+ }
- if (!isNonEmptyString(username)) {
- return res.status(400).json({ error: "Username is required" });
+ const user = await db.select().from(users).where(eq(users.id, userId));
+ if (!user || user.length === 0) {
+ return res.status(404).json({ error: "User not found" });
}
- try {
- const user = await db
- .select()
- .from(users)
- .where(eq(users.username, username));
+ const isMatch = await bcrypt.compare(oldPassword, user[0].passwordHash);
+ if (!isMatch) {
+ authLogger.warn("Password change failed - old password incorrect", {
+ operation: "password_change_failed",
+ userId,
+ reason: "old_password_wrong",
+ });
+ return res.status(401).json({ error: "Incorrect current password" });
+ }
- if (!user || user.length === 0) {
- authLogger.warn(
- `Password reset attempted for non-existent user: ${username}`,
- );
- return res.json({
- message:
- "If the user exists, a password reset code has been generated. Check docker logs for the code.",
- });
- }
+ const success = await authManager.changeUserPassword(
+ userId,
+ oldPassword,
+ newPassword,
+ );
+ if (!success) {
+ return res
+ .status(500)
+ .json({ error: "Failed to update password and re-encrypt data." });
+ }
- if (user[0].isOidc) {
- return res.json({
- message:
- "If the user exists, a password reset code has been generated. Check docker logs for the code.",
- });
- }
+ const saltRounds = parseInt(process.env.SALT || "10", 10);
+ const password_hash = await bcrypt.hash(newPassword, saltRounds);
+ await db
+ .update(users)
+ .set({ passwordHash: password_hash })
+ .where(eq(users.id, userId));
- const resetCode = crypto.randomInt(100000, 1000000).toString();
- const expiresAt = new Date(Date.now() + 15 * 60 * 1000);
+ authManager.logoutUser(userId);
+ authLogger.success("Password changed successfully", {
+ operation: "password_change_complete",
+ userId,
+ });
- db.$client
- .prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)")
- .run(
- `reset_code_${username}`,
- JSON.stringify({ code: resetCode, expiresAt: expiresAt.toISOString() }),
- );
+ res.json({ message: "Password changed successfully. Please log in again." });
+});
- authLogger.info(
- `Password reset code generated for user ${username} (expires at ${expiresAt.toLocaleString()}). Check admin panel or database settings table for code.`,
- );
+registerUserAdminRoutes(router, authenticateJWT);
- res.json({
- message:
- "Password reset code has been generated and logged. Check docker logs for the code.",
- });
- } catch (err) {
- authLogger.error("Failed to initiate password reset", err);
- res.status(500).json({ error: "Failed to initiate password reset" });
- }
+registerUserTotpRoutes(router, {
+ authenticateJWT,
+ authManager,
+ isNativeAppRequest,
});
/**
* @openapi
- * /users/verify-reset-code:
- * post:
- * summary: Verify reset code
- * description: Verifies the password reset code.
+ * /users/delete-user:
+ * delete:
+ * summary: Delete user (admin only)
+ * description: Allows an admin to delete another user and all related data.
* tags:
* - Users
* requestBody:
@@ -2355,2449 +2125,101 @@ router.post("/initiate-reset", async (req, res) => {
* properties:
* username:
* type: string
- * resetCode:
- * type: string
* responses:
* 200:
- * description: Reset code verified.
+ * description: User deleted successfully.
* 400:
- * description: Invalid or expired reset code.
+ * description: Username is required or cannot delete yourself.
+ * 403:
+ * description: Not authorized or cannot delete last admin.
+ * 404:
+ * description: User not found.
* 500:
- * description: Failed to verify reset code.
+ * description: Failed to delete user.
*/
-router.post("/verify-reset-code", async (req, res) => {
- const { username, resetCode } = req.body;
+router.delete("/delete-user", authenticateJWT, async (req, res) => {
+ const userId = (req as AuthenticatedRequest).userId;
+ const { username } = req.body;
- if (!isNonEmptyString(username) || !isNonEmptyString(resetCode)) {
- return res
- .status(400)
- .json({ error: "Username and reset code are required" });
+ if (!isNonEmptyString(username)) {
+ return res.status(400).json({ error: "Username is required" });
}
try {
- const lockStatus = loginRateLimiter.isResetCodeLocked(username);
- if (lockStatus.locked) {
- authLogger.warn("Reset code verification blocked due to rate limiting", {
- operation: "reset_code_verify_blocked",
- username,
- remainingTime: lockStatus.remainingTime,
- });
- return res.status(429).json({
- error: `Rate limited: Too many verification attempts. Please wait ${lockStatus.remainingTime} seconds before trying again.`,
- remainingTime: lockStatus.remainingTime,
- code: "RESET_CODE_RATE_LIMITED",
- });
+ const adminUser = await db.select().from(users).where(eq(users.id, userId));
+ if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
+ return res.status(403).json({ error: "Not authorized" });
}
- loginRateLimiter.recordResetCodeAttempt(username);
-
- const resetDataRow = db.$client
- .prepare("SELECT value FROM settings WHERE key = ?")
- .get(`reset_code_${username}`);
- if (!resetDataRow) {
- authLogger.warn("Reset code verification failed - no code found", {
- operation: "reset_code_verify_failed",
- username,
- remainingAttempts:
- loginRateLimiter.getRemainingResetCodeAttempts(username),
- });
- return res.status(400).json({
- error: "No reset code found for this user",
- remainingAttempts:
- loginRateLimiter.getRemainingResetCodeAttempts(username),
- });
+ if (adminUser[0].username === username) {
+ return res.status(400).json({ error: "Cannot delete your own account" });
}
- const resetData = JSON.parse(
- (resetDataRow as Record<string, unknown>).value as string,
- );
- const now = new Date();
- const expiresAt = new Date(resetData.expiresAt);
+ const targetUser = await db
+ .select()
+ .from(users)
+ .where(eq(users.username, username));
+ if (!targetUser || targetUser.length === 0) {
+ return res.status(404).json({ error: "User not found" });
+ }
- if (now > expiresAt) {
- db.$client
- .prepare("DELETE FROM settings WHERE key = ?")
- .run(`reset_code_${username}`);
- authLogger.warn("Reset code verification failed - code expired", {
- operation: "reset_code_verify_failed",
- username,
- remainingAttempts:
- loginRateLimiter.getRemainingResetCodeAttempts(username),
- });
- return res.status(400).json({
- error: "Reset code has expired",
- remainingAttempts:
- loginRateLimiter.getRemainingResetCodeAttempts(username),
- });
+ if (targetUser[0].isAdmin) {
+ const adminCount = db.$client
+ .prepare("SELECT COUNT(*) as count FROM users WHERE is_admin = 1")
+ .get();
+ if (((adminCount as { count?: number })?.count || 0) <= 1) {
+ return res
+ .status(403)
+ .json({ error: "Cannot delete the last admin user" });
+ }
}
- if (resetData.code !== resetCode) {
- authLogger.warn("Reset code verification failed - invalid code", {
- operation: "reset_code_verify_failed",
- username,
- remainingAttempts:
- loginRateLimiter.getRemainingResetCodeAttempts(username),
- });
- return res.status(400).json({
- error: "Invalid reset code",
- remainingAttempts:
- loginRateLimiter.getRemainingResetCodeAttempts(username),
- });
- }
-
- loginRateLimiter.resetResetCodeAttempts(username);
-
- const tempToken = nanoid();
- const tempTokenExpiry = new Date(Date.now() + 10 * 60 * 1000);
-
- db.$client
- .prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)")
- .run(
- `temp_reset_token_${username}`,
- JSON.stringify({
- token: tempToken,
- expiresAt: tempTokenExpiry.toISOString(),
- }),
- );
-
- res.json({ message: "Reset code verified", tempToken });
- } catch (err) {
- authLogger.error("Failed to verify reset code", err);
- res.status(500).json({ error: "Failed to verify reset code" });
- }
-});
-
-/**
- * @openapi
- * /users/complete-reset:
- * post:
- * summary: Complete password reset
- * description: Completes the password reset process with a new password.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * username:
- * type: string
- * tempToken:
- * type: string
- * newPassword:
- * type: string
- * responses:
- * 200:
- * description: Password has been successfully reset.
- * 400:
- * description: Invalid or expired temporary token.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to complete password reset.
- */
-router.post("/complete-reset", async (req, res) => {
- const { username, tempToken, newPassword } = req.body;
-
- if (
- !isNonEmptyString(username) ||
- !isNonEmptyString(tempToken) ||
- !isNonEmptyString(newPassword)
- ) {
- return res.status(400).json({
- error: "Username, temporary token, and new password are required",
- });
- }
-
- try {
- const tempTokenRow = db.$client
- .prepare("SELECT value FROM settings WHERE key = ?")
- .get(`temp_reset_token_${username}`);
- if (!tempTokenRow) {
- return res.status(400).json({ error: "No temporary token found" });
- }
-
- const tempTokenData = JSON.parse(
- (tempTokenRow as Record<string, unknown>).value as string,
- );
- const now = new Date();
- const expiresAt = new Date(tempTokenData.expiresAt);
-
- if (now > expiresAt) {
- db.$client
- .prepare("DELETE FROM settings WHERE key = ?")
- .run(`temp_reset_token_${username}`);
- return res.status(400).json({ error: "Temporary token has expired" });
- }
-
- if (tempTokenData.token !== tempToken) {
- return res.status(400).json({ error: "Invalid temporary token" });
- }
-
- const user = await db
- .select()
- .from(users)
- .where(eq(users.username, username));
- if (!user || user.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
- const userId = user[0].id;
-
- const saltRounds = parseInt(process.env.SALT || "10", 10);
- const password_hash = await bcrypt.hash(newPassword, saltRounds);
-
- let userIdFromJwt: string | null = null;
- const cookie = req.cookies?.jwt;
- let header: string | undefined;
- if (req.headers?.authorization?.startsWith("Bearer ")) {
- header = req.headers?.authorization?.split(" ")[1];
- }
- const token = cookie || header;
-
- if (token) {
- const payload = await authManager.verifyJWTToken(token);
- if (payload) {
- userIdFromJwt = payload.userId;
- }
- }
-
- if (userIdFromJwt === userId) {
- try {
- const success = await authManager.resetUserPasswordWithPreservedDEK(
- userId,
- newPassword,
- );
-
- if (!success) {
- throw new Error("Failed to re-encrypt user data with new password.");
- }
-
- await db
- .update(users)
- .set({ passwordHash: password_hash })
- .where(eq(users.id, userId));
- authManager.logoutUser(userId);
- authLogger.success(
- `Password reset (data preserved) for user: ${username}`,
- {
- operation: "password_reset_preserved",
- userId,
- username,
- },
- );
- } catch (encryptionError) {
- authLogger.error(
- "Failed to setup user data encryption after password reset",
- encryptionError,
- {
- operation: "password_reset_encryption_failed_preserved",
- userId,
- username,
- },
- );
- return res.status(500).json({
- error: "Password reset failed. Please contact administrator.",
- });
- }
- } else {
- await db
- .update(users)
- .set({ passwordHash: password_hash })
- .where(eq(users.username, username));
-
- try {
- await db
- .delete(sshCredentialUsage)
- .where(eq(sshCredentialUsage.userId, userId));
- await db
- .delete(fileManagerRecent)
- .where(eq(fileManagerRecent.userId, userId));
- await db
- .delete(fileManagerPinned)
- .where(eq(fileManagerPinned.userId, userId));
- await db
- .delete(fileManagerShortcuts)
- .where(eq(fileManagerShortcuts.userId, userId));
- await db
- .delete(recentActivity)
- .where(eq(recentActivity.userId, userId));
- await db
- .delete(dismissedAlerts)
- .where(eq(dismissedAlerts.userId, userId));
- await db.delete(snippets).where(eq(snippets.userId, userId));
- await db.delete(hosts).where(eq(hosts.userId, userId));
- await db
- .delete(sshCredentials)
- .where(eq(sshCredentials.userId, userId));
-
- await authManager.registerUser(userId, newPassword);
- authManager.logoutUser(userId);
-
- await db
- .update(users)
- .set({
- totpEnabled: false,
- totpSecret: null,
- totpBackupCodes: null,
- })
- .where(eq(users.id, userId));
-
- authLogger.warn(
- `Password reset completed for user: ${username}. All encrypted data has been deleted due to lost encryption key.`,
- {
- operation: "password_reset_data_deleted",
- userId,
- username,
- },
- );
- } catch (encryptionError) {
- authLogger.error(
- "Failed to setup user data encryption after password reset",
- encryptionError,
- {
- operation: "password_reset_encryption_failed",
- userId,
- username,
- },
- );
- return res.status(500).json({
- error: "Password reset failed. Please contact administrator.",
- });
- }
- }
-
- authLogger.success(`Password successfully reset for user: ${username}`);
-
- db.$client
- .prepare("DELETE FROM settings WHERE key = ?")
- .run(`reset_code_${username}`);
- db.$client
- .prepare("DELETE FROM settings WHERE key = ?")
- .run(`temp_reset_token_${username}`);
-
- res.json({ message: "Password has been successfully reset" });
- } catch (err) {
- authLogger.error("Failed to complete password reset", err);
- res.status(500).json({ error: "Failed to complete password reset" });
- }
-});
-
-/**
- * @openapi
- * /users/change-password:
- * post:
- * summary: Change user password
- * description: Changes the authenticated user's password.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * oldPassword:
- * type: string
- * newPassword:
- * type: string
- * responses:
- * 200:
- * description: Password changed successfully.
- * 400:
- * description: Old and new passwords are required.
- * 401:
- * description: Incorrect current password.
- * 500:
- * description: Failed to update password and re-encrypt data.
- */
-router.post("/change-password", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { oldPassword, newPassword } = req.body;
- authLogger.info("Password change request", {
- operation: "password_change_request",
- userId,
- });
-
- if (!userId) {
- return res.status(401).json({ error: "User not authenticated" });
- }
-
- if (!oldPassword || !newPassword) {
- return res
- .status(400)
- .json({ error: "Old and new passwords are required." });
- }
-
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- const isMatch = await bcrypt.compare(oldPassword, user[0].passwordHash);
- if (!isMatch) {
- authLogger.warn("Password change failed - old password incorrect", {
- operation: "password_change_failed",
- userId,
- reason: "old_password_wrong",
- });
- return res.status(401).json({ error: "Incorrect current password" });
- }
-
- const success = await authManager.changeUserPassword(
- userId,
- oldPassword,
- newPassword,
- );
- if (!success) {
- return res
- .status(500)
- .json({ error: "Failed to update password and re-encrypt data." });
- }
-
- const saltRounds = parseInt(process.env.SALT || "10", 10);
- const password_hash = await bcrypt.hash(newPassword, saltRounds);
- await db
- .update(users)
- .set({ passwordHash: password_hash })
- .where(eq(users.id, userId));
-
- authManager.logoutUser(userId);
- authLogger.success("Password changed successfully", {
- operation: "password_change_complete",
- userId,
- });
-
- res.json({ message: "Password changed successfully. Please log in again." });
-});
-
-/**
- * @openapi
- * /users/list:
- * get:
- * summary: List all users
- * description: Retrieves a list of all users in the system.
- * tags:
- * - Users
- * responses:
- * 200:
- * description: A list of users.
- * 403:
- * description: Not authorized.
- * 500:
- * description: Failed to list users.
- */
-router.get("/list", authenticateJWT, async (req, res) => {
- try {
- const allUsers = await db
- .select({
- id: users.id,
- username: users.username,
- isAdmin: users.isAdmin,
- isOidc: users.isOidc,
- passwordHash: users.passwordHash,
- })
- .from(users);
-
- res.json({ users: allUsers });
- } catch (err) {
- authLogger.error("Failed to list users", err);
- res.status(500).json({ error: "Failed to list users" });
- }
-});
-
-/**
- * @openapi
- * /users/make-admin:
- * post:
- * summary: Make user admin
- * description: Grants admin privileges to a user.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * userId:
- * type: string
- * description: Preferred unique user identifier.
- * username:
- * type: string
- * description: Legacy fallback identifier.
- * responses:
- * 200:
- * description: User is now an admin.
- * 400:
- * description: User ID or username is required, or the user is already an admin.
- * 403:
- * description: Not authorized.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to make user admin.
- */
-router.post("/make-admin", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { userId: targetUserId, username } = req.body;
- const resolvedUserId = isNonEmptyString(targetUserId)
- ? targetUserId.trim()
- : null;
- const resolvedUsername = isNonEmptyString(username) ? username.trim() : null;
-
- if (!resolvedUserId && !resolvedUsername) {
- return res.status(400).json({ error: "User ID or username is required" });
- }
-
- try {
- const adminUser = await db.select().from(users).where(eq(users.id, userId));
- if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
- return res.status(403).json({ error: "Not authorized" });
- }
-
- const targetUser = await db
- .select()
- .from(users)
- .where(
- resolvedUserId
- ? eq(users.id, resolvedUserId)
- : eq(users.username, resolvedUsername!),
- )
- .limit(1);
- if (!targetUser || targetUser.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- if (targetUser[0].isAdmin) {
- return res.status(400).json({ error: "User is already an admin" });
- }
-
- await db
- .update(users)
- .set({ isAdmin: true })
- .where(
- resolvedUserId
- ? eq(users.id, resolvedUserId)
- : eq(users.username, resolvedUsername!),
- );
-
- try {
- const { saveMemoryDatabaseToFile } = await import("../db/index.js");
- await saveMemoryDatabaseToFile();
- } catch (saveError) {
- authLogger.error("Failed to persist admin promotion to disk", saveError, {
- operation: "make_admin_save_failed",
- userId: targetUser[0].id,
- username: targetUser[0].username,
- });
- }
-
- authLogger.info("Admin privileges granted", {
- operation: "admin_grant",
- adminId: userId,
- targetUserId: targetUser[0].id,
- targetUsername: targetUser[0].username,
- });
- res.json({ message: `User ${targetUser[0].username} is now an admin` });
- } catch (err) {
- authLogger.error("Failed to make user admin", err);
- res.status(500).json({ error: "Failed to make user admin" });
- }
-});
-
-/**
- * @openapi
- * /users/remove-admin:
- * post:
- * summary: Remove admin status
- * description: Revokes admin privileges from a user.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * userId:
- * type: string
- * description: Preferred unique user identifier.
- * username:
- * type: string
- * description: Legacy fallback identifier.
- * responses:
- * 200:
- * description: Admin status removed from user.
- * 400:
- * description: User ID or username is required, or cannot remove your own admin status.
- * 403:
- * description: Not authorized.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to remove admin status.
- */
-router.post("/remove-admin", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { userId: targetUserId, username } = req.body;
- const resolvedUserId = isNonEmptyString(targetUserId)
- ? targetUserId.trim()
- : null;
- const resolvedUsername = isNonEmptyString(username) ? username.trim() : null;
-
- if (!resolvedUserId && !resolvedUsername) {
- return res.status(400).json({ error: "User ID or username is required" });
- }
-
- try {
- const adminUser = await db.select().from(users).where(eq(users.id, userId));
- if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
- return res.status(403).json({ error: "Not authorized" });
- }
-
- if (
- (resolvedUserId && adminUser[0].id === resolvedUserId) ||
- (resolvedUsername && adminUser[0].username === resolvedUsername)
- ) {
- return res
- .status(400)
- .json({ error: "Cannot remove your own admin status" });
- }
-
- const targetUser = await db
- .select()
- .from(users)
- .where(
- resolvedUserId
- ? eq(users.id, resolvedUserId)
- : eq(users.username, resolvedUsername!),
- )
- .limit(1);
- if (!targetUser || targetUser.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- if (!targetUser[0].isAdmin) {
- return res.status(400).json({ error: "User is not an admin" });
- }
-
- await db
- .update(users)
- .set({ isAdmin: false })
- .where(
- resolvedUserId
- ? eq(users.id, resolvedUserId)
- : eq(users.username, resolvedUsername!),
- );
-
- try {
- const { saveMemoryDatabaseToFile } = await import("../db/index.js");
- await saveMemoryDatabaseToFile();
- } catch (saveError) {
- authLogger.error("Failed to persist admin removal to disk", saveError, {
- operation: "remove_admin_save_failed",
- userId: targetUser[0].id,
- username: targetUser[0].username,
- });
- }
-
- authLogger.info("Admin privileges revoked", {
- operation: "admin_revoke",
- adminId: userId,
- targetUserId: targetUser[0].id,
- targetUsername: targetUser[0].username,
- });
- res.json({
- message: `Admin status removed from ${targetUser[0].username}`,
- });
- } catch (err) {
- authLogger.error("Failed to remove admin status", err);
- res.status(500).json({ error: "Failed to remove admin status" });
- }
-});
-
-/**
- * @openapi
- * /users/totp/setup:
- * post:
- * summary: Setup TOTP
- * description: Initiates TOTP setup by generating a secret and QR code.
- * tags:
- * - Users
- * responses:
- * 200:
- * description: TOTP setup initiated with secret and QR code.
- * 400:
- * description: TOTP is already enabled.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to setup TOTP.
- */
-router.post("/totp/setup", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
-
- try {
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- const userRecord = user[0];
-
- if (userRecord.totpEnabled) {
- return res.status(400).json({ error: "TOTP is already enabled" });
- }
-
- const secret = speakeasy.generateSecret({
- name: `Termix (${userRecord.username})`,
- length: 32,
- });
-
- await db
- .update(users)
- .set({ totpSecret: secret.base32 })
- .where(eq(users.id, userId));
-
- const qrCodeUrl = await QRCode.toDataURL(secret.otpauth_url || "");
-
- res.json({
- secret: secret.base32,
- qr_code: qrCodeUrl,
- });
- } catch (err) {
- authLogger.error("Failed to setup TOTP", err);
- res.status(500).json({ error: "Failed to setup TOTP" });
- }
-});
-
-/**
- * @openapi
- * /users/totp/enable:
- * post:
- * summary: Enable TOTP
- * description: Enables TOTP after verifying the initial code.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * totp_code:
- * type: string
- * responses:
- * 200:
- * description: TOTP enabled successfully with backup codes.
- * 400:
- * description: TOTP code is required or TOTP already enabled.
- * 401:
- * description: Invalid TOTP code.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to enable TOTP.
- */
-router.post("/totp/enable", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { totp_code } = req.body;
-
- if (!totp_code) {
- return res.status(400).json({ error: "TOTP code is required" });
- }
-
- try {
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- const userRecord = user[0];
-
- if (userRecord.totpEnabled) {
- return res.status(400).json({ error: "TOTP is already enabled" });
- }
-
- if (!userRecord.totpSecret) {
- return res.status(400).json({ error: "TOTP setup not initiated" });
- }
-
- const verified = speakeasy.totp.verify({
- secret: userRecord.totpSecret,
- encoding: "base32",
- token: totp_code,
- window: 2,
- });
-
- if (!verified) {
- return res.status(401).json({ error: "Invalid TOTP code" });
- }
-
- const backupCodes = Array.from({ length: 8 }, () =>
- Math.random().toString(36).substring(2, 10).toUpperCase(),
- );
-
- await db
- .update(users)
- .set({
- totpEnabled: true,
- totpBackupCodes: JSON.stringify(backupCodes),
- })
- .where(eq(users.id, userId));
-
- await db.delete(sessions).where(eq(sessions.userId, userId));
- await db.delete(trustedDevices).where(eq(trustedDevices.userId, userId));
-
- try {
- const { saveMemoryDatabaseToFile } = await import("../db/index.js");
- await saveMemoryDatabaseToFile();
- } catch (saveError) {
- authLogger.error("Failed to persist TOTP enablement to disk", saveError, {
- operation: "totp_enable_db_save_failed",
- userId,
- });
- }
-
- res.json({
- message: "TOTP enabled successfully",
- backup_codes: backupCodes,
- });
- } catch (err) {
- authLogger.error("Failed to enable TOTP", err);
- res.status(500).json({ error: "Failed to enable TOTP" });
- }
-});
-
-/**
- * @openapi
- * /users/totp/disable:
- * post:
- * summary: Disable TOTP
- * description: Disables TOTP for a user.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * password:
- * type: string
- * totp_code:
- * type: string
- * responses:
- * 200:
- * description: TOTP disabled successfully.
- * 400:
- * description: Password or TOTP code is required.
- * 401:
- * description: Incorrect password or invalid TOTP code.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to disable TOTP.
- */
-router.post("/totp/disable", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { password, totp_code } = req.body;
-
- if (!password && !totp_code) {
- return res.status(400).json({ error: "Password or TOTP code is required" });
- }
-
- try {
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- const userRecord = user[0];
-
- if (!userRecord.totpEnabled) {
- return res.status(400).json({ error: "TOTP is not enabled" });
- }
-
- if (password && !userRecord.isOidc) {
- const isMatch = await bcrypt.compare(password, userRecord.passwordHash);
- if (!isMatch) {
- return res.status(401).json({ error: "Incorrect password" });
- }
- } else if (totp_code) {
- const verified = speakeasy.totp.verify({
- secret: userRecord.totpSecret!,
- encoding: "base32",
- token: totp_code,
- window: 2,
- });
-
- if (!verified) {
- return res.status(401).json({ error: "Invalid TOTP code" });
- }
- } else {
- return res.status(400).json({ error: "Authentication required" });
- }
-
- await db
- .update(users)
- .set({
- totpEnabled: false,
- totpSecret: null,
- totpBackupCodes: null,
- })
- .where(eq(users.id, userId));
- authLogger.info("Two-factor authentication disabled", {
- operation: "totp_disable",
- userId,
- });
-
- res.json({ message: "TOTP disabled successfully" });
- } catch (err) {
- authLogger.error("Failed to disable TOTP", err);
- res.status(500).json({ error: "Failed to disable TOTP" });
- }
-});
-
-/**
- * @openapi
- * /users/totp/backup-codes:
- * post:
- * summary: Generate new backup codes
- * description: Generates new TOTP backup codes.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * password:
- * type: string
- * totp_code:
- * type: string
- * responses:
- * 200:
- * description: New backup codes generated.
- * 400:
- * description: Password or TOTP code is required.
- * 401:
- * description: Incorrect password or invalid TOTP code.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to generate backup codes.
- */
-router.post("/totp/backup-codes", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { password, totp_code } = req.body;
-
- if (!password && !totp_code) {
- return res.status(400).json({ error: "Password or TOTP code is required" });
- }
-
- try {
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- const userRecord = user[0];
-
- if (!userRecord.totpEnabled) {
- return res.status(400).json({ error: "TOTP is not enabled" });
- }
-
- if (password && !userRecord.isOidc) {
- const isMatch = await bcrypt.compare(password, userRecord.passwordHash);
- if (!isMatch) {
- return res.status(401).json({ error: "Incorrect password" });
- }
- } else if (totp_code) {
- const verified = speakeasy.totp.verify({
- secret: userRecord.totpSecret!,
- encoding: "base32",
- token: totp_code,
- window: 2,
- });
-
- if (!verified) {
- return res.status(401).json({ error: "Invalid TOTP code" });
- }
- } else {
- return res.status(400).json({ error: "Authentication required" });
- }
-
- const backupCodes = Array.from({ length: 8 }, () =>
- Math.random().toString(36).substring(2, 10).toUpperCase(),
- );
-
- await db
- .update(users)
- .set({ totpBackupCodes: JSON.stringify(backupCodes) })
- .where(eq(users.id, userId));
-
- res.json({ backup_codes: backupCodes });
- } catch (err) {
- authLogger.error("Failed to generate backup codes", err);
- res.status(500).json({ error: "Failed to generate backup codes" });
- }
-});
-
-/**
- * @openapi
- * /users/totp/verify-login:
- * post:
- * summary: Verify TOTP during login
- * description: Verifies the TOTP code during login.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * temp_token:
- * type: string
- * totp_code:
- * type: string
- * responses:
- * 200:
- * description: TOTP verification successful.
- * 400:
- * description: Token and TOTP code are required.
- * 401:
- * description: Invalid temporary token or TOTP code.
- * 404:
- * description: User not found.
- * 500:
- * description: TOTP verification failed.
- */
-router.post("/totp/verify-login", async (req, res) => {
- const { temp_token, totp_code, rememberMe } = req.body;
-
- if (!temp_token || !totp_code) {
- return res.status(400).json({ error: "Token and TOTP code are required" });
- }
-
- try {
- const decoded = await authManager.verifyJWTToken(temp_token);
- if (!decoded || !decoded.pendingTOTP) {
- return res.status(401).json({ error: "Invalid temporary token" });
- }
-
- const user = await db
- .select()
- .from(users)
- .where(eq(users.id, decoded.userId));
- if (!user || user.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- const userRecord = user[0];
-
- const lockStatus = loginRateLimiter.isTOTPLocked(userRecord.id);
- if (lockStatus.locked) {
- authLogger.warn("TOTP verification blocked due to rate limiting", {
- operation: "totp_verify_blocked",
- userId: userRecord.id,
- remainingTime: lockStatus.remainingTime,
- });
- return res.status(429).json({
- error: `Rate limited: Too many TOTP verification attempts. Please wait ${lockStatus.remainingTime} seconds before trying again.`,
- remainingTime: lockStatus.remainingTime,
- code: "TOTP_RATE_LIMITED",
- });
- }
-
- loginRateLimiter.recordFailedTOTPAttempt(userRecord.id);
-
- if (!userRecord.totpEnabled || !userRecord.totpSecret) {
- return res.status(400).json({ error: "TOTP not enabled for this user" });
- }
-
- const userDataKey = authManager.getUserDataKey(userRecord.id);
- if (!userDataKey) {
- return res.status(401).json({
- error: "Session expired - please log in again",
- code: "SESSION_EXPIRED",
- });
- }
-
- const totpSecret = LazyFieldEncryption.safeGetFieldValue(
- userRecord.totpSecret,
- userDataKey,
- userRecord.id,
- "totp_secret",
- );
-
- if (!totpSecret) {
- await db
- .update(users)
- .set({
- totpEnabled: false,
- totpSecret: null,
- totpBackupCodes: null,
- })
- .where(eq(users.id, userRecord.id));
-
- return res.status(400).json({
- error:
- "TOTP has been disabled due to password reset. Please set up TOTP again.",
- });
- }
-
- const verified = speakeasy.totp.verify({
- secret: totpSecret,
- encoding: "base32",
- token: totp_code,
- window: 2,
- });
-
- if (!verified) {
- let backupCodes = [];
- try {
- backupCodes = userRecord.totpBackupCodes
- ? JSON.parse(userRecord.totpBackupCodes)
- : [];
- } catch {
- backupCodes = [];
- }
-
- if (!Array.isArray(backupCodes)) {
- backupCodes = [];
- }
-
- const backupIndex = backupCodes.indexOf(totp_code);
-
- if (backupIndex === -1) {
- authLogger.warn("TOTP verification failed - invalid code", {
- operation: "totp_verify_failed",
- userId: userRecord.id,
- remainingAttempts: loginRateLimiter.getRemainingTOTPAttempts(
- userRecord.id,
- ),
- });
- return res.status(401).json({
- error: "Invalid TOTP code",
- remainingAttempts: loginRateLimiter.getRemainingTOTPAttempts(
- userRecord.id,
- ),
- });
- }
-
- backupCodes.splice(backupIndex, 1);
- await db
- .update(users)
- .set({ totpBackupCodes: JSON.stringify(backupCodes) })
- .where(eq(users.id, userRecord.id));
- }
-
- loginRateLimiter.resetTOTPAttempts(userRecord.id);
-
- const deviceInfo = parseUserAgent(req);
-
- if (rememberMe) {
- const deviceFingerprint = generateDeviceFingerprint(deviceInfo);
- await authManager.addTrustedDevice(
- userRecord.id,
- deviceFingerprint,
- deviceInfo.type,
- deviceInfo.deviceInfo,
- );
- authLogger.info("Device automatically trusted via Remember Me", {
- operation: "totp_auto_trust",
- userId: userRecord.id,
- deviceType: deviceInfo.type,
- });
- }
-
- const token = await authManager.generateJWTToken(userRecord.id, {
- rememberMe: !!rememberMe,
- deviceType: deviceInfo.type,
- deviceInfo: deviceInfo.deviceInfo,
- });
-
- authLogger.success("TOTP verification successful", {
- operation: "totp_verify_success",
- userId: userRecord.id,
- deviceType: deviceInfo.type,
- deviceInfo: deviceInfo.deviceInfo,
- });
-
- const response: Record<string, unknown> = {
- success: true,
- is_admin: !!userRecord.isAdmin,
- username: userRecord.username,
- userId: userRecord.id,
- is_oidc: !!userRecord.isOidc,
- totp_enabled: !!userRecord.totpEnabled,
- ...(isNativeAppRequest(req) ? { token } : {}),
- };
-
- const timeoutRow = db.$client
- .prepare("SELECT value FROM settings WHERE key = 'session_timeout_hours'")
- .get() as { value: string } | undefined;
- const timeoutHours = timeoutRow ? parseInt(timeoutRow.value, 10) || 24 : 24;
- const maxAge = rememberMe
- ? 30 * 24 * 60 * 60 * 1000
- : timeoutHours * 60 * 60 * 1000;
-
- return res
- .cookie("jwt", token, authManager.getSecureCookieOptions(req, maxAge))
- .json(response);
- } catch (err) {
- authLogger.error("TOTP verification failed", err);
- return res.status(500).json({ error: "TOTP verification failed" });
- }
-});
-
-/**
- * @openapi
- * /users/delete-user:
- * delete:
- * summary: Delete user (admin only)
- * description: Allows an admin to delete another user and all related data.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * username:
- * type: string
- * responses:
- * 200:
- * description: User deleted successfully.
- * 400:
- * description: Username is required or cannot delete yourself.
- * 403:
- * description: Not authorized or cannot delete last admin.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to delete user.
- */
-router.delete("/delete-user", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { username } = req.body;
-
- if (!isNonEmptyString(username)) {
- return res.status(400).json({ error: "Username is required" });
- }
-
- try {
- const adminUser = await db.select().from(users).where(eq(users.id, userId));
- if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
- return res.status(403).json({ error: "Not authorized" });
- }
-
- if (adminUser[0].username === username) {
- return res.status(400).json({ error: "Cannot delete your own account" });
- }
-
- const targetUser = await db
- .select()
- .from(users)
- .where(eq(users.username, username));
- if (!targetUser || targetUser.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- if (targetUser[0].isAdmin) {
- const adminCount = db.$client
- .prepare("SELECT COUNT(*) as count FROM users WHERE is_admin = 1")
- .get();
- if (((adminCount as { count?: number })?.count || 0) <= 1) {
- return res
- .status(403)
- .json({ error: "Cannot delete the last admin user" });
- }
- }
-
- const targetUserId = targetUser[0].id;
-
- await deleteUserAndRelatedData(targetUserId);
-
- authLogger.warn("User account deleted by admin", {
- operation: "admin_delete_user",
- adminId: userId,
- targetUserId,
- targetUsername: username,
- });
- res.json({ message: `User ${username} deleted successfully` });
- } catch (err) {
- authLogger.error("Failed to delete user", err);
-
- if (err && typeof err === "object" && "code" in err) {
- if (err.code === "SQLITE_CONSTRAINT_FOREIGNKEY") {
- res.status(400).json({
- error:
- "Cannot delete user: User has associated data that cannot be removed",
- });
- } else {
- res.status(500).json({ error: `Database error: ${err.code}` });
- }
- } else {
- res.status(500).json({ error: "Failed to delete account" });
- }
- }
-});
-
-/**
- * @openapi
- * /users/unlock-data:
- * post:
- * summary: Unlock user data
- * description: Re-authenticates user with password to unlock encrypted data.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * password:
- * type: string
- * responses:
- * 200:
- * description: Data unlocked successfully.
- * 400:
- * description: Password is required.
- * 401:
- * description: Invalid password.
- * 500:
- * description: Failed to unlock data.
- */
-router.post("/unlock-data", authenticateJWT, async (req, res) => {
- const authReq = req as AuthenticatedRequest;
- const userId = authReq.userId;
- const { password } = req.body;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- if (!password) {
- return res.status(400).json({ error: "Password is required" });
- }
-
- try {
- const unlocked = await authManager.authenticateUser(userId, password);
- if (unlocked) {
- const refreshedSession =
- userId && authReq.sessionId
- ? await authManager.refreshSessionToken(userId, authReq.sessionId)
- : null;
-
- if (refreshedSession) {
- res.cookie(
- "jwt",
- refreshedSession.token,
- authManager.getSecureCookieOptions(req, refreshedSession.maxAge),
- );
- }
-
- res.json({
- success: true,
- message: "Data unlocked successfully",
- });
- } else {
- authLogger.warn("Failed to unlock user data - invalid password", {
- operation: "user_data_unlock_failed",
- userId,
- });
- res.status(401).json({ error: "Invalid password" });
- }
- } catch (err) {
- authLogger.error("Data unlock failed", err, {
- operation: "user_data_unlock_error",
- userId,
- });
- res.status(500).json({ error: "Failed to unlock data" });
- }
-});
-
-/**
- * @openapi
- * /users/data-status:
- * get:
- * summary: Check user data unlock status
- * description: Checks if user data is currently unlocked.
- * tags:
- * - Users
- * responses:
- * 200:
- * description: Data status returned.
- * 500:
- * description: Failed to check data status.
- */
-router.get("/data-status", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
-
- try {
- const unlocked = authManager.isUserUnlocked(userId);
- res.json({
- unlocked,
- message: unlocked ? "Data is unlocked" : "Data is locked",
- });
- } catch (err) {
- authLogger.error("Failed to check data status", err, {
- operation: "data_status_check_failed",
- userId,
- });
- res.status(500).json({ error: "Failed to check data status" });
- }
-});
-
-/**
- * @openapi
- * /users/sessions:
- * get:
- * summary: Get sessions
- * description: Retrieves all sessions for authenticated user (or all sessions for admins).
- * tags:
- * - Users
- * responses:
- * 200:
- * description: Sessions list returned.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to get sessions.
- */
-router.get("/sessions", authenticateJWT, async (req, res) => {
- const authReq = req as AuthenticatedRequest;
- const userId = authReq.userId;
- const currentSessionId = authReq.sessionId;
-
- try {
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- const userRecord = user[0];
- let sessionList;
-
- if (userRecord.isAdmin) {
- sessionList = await authManager.getAllSessions();
-
- const enrichedSessions = await Promise.all(
- sessionList.map(async (session) => {
- const sessionUser = await db
- .select({ username: users.username })
- .from(users)
- .where(eq(users.id, session.userId))
- .limit(1);
-
- return {
- id: session.id,
- userId: session.userId,
- username: sessionUser[0]?.username || "Unknown",
- deviceType: session.deviceType,
- deviceInfo: session.deviceInfo,
- createdAt: session.createdAt,
- expiresAt: session.expiresAt,
- lastActiveAt: session.lastActiveAt,
- isRevoked: session.isRevoked,
- isCurrentSession: session.id === currentSessionId,
- };
- }),
- );
-
- return res.json({ sessions: enrichedSessions });
- } else {
- sessionList = await authManager.getUserSessions(userId);
- return res.json({
- sessions: sessionList.map((session) => ({
- id: session.id,
- userId: session.userId,
- deviceType: session.deviceType,
- deviceInfo: session.deviceInfo,
- createdAt: session.createdAt,
- expiresAt: session.expiresAt,
- lastActiveAt: session.lastActiveAt,
- isRevoked: session.isRevoked,
- isCurrentSession: session.id === currentSessionId,
- })),
- });
- }
- } catch (err) {
- authLogger.error("Failed to get sessions", err);
- res.status(500).json({ error: "Failed to get sessions" });
- }
-});
-
-/**
- * @openapi
- * /users/sessions/{sessionId}:
- * delete:
- * summary: Revoke a specific session
- * description: Revokes a specific session by ID.
- * tags:
- * - Users
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * description: The session ID to revoke
- * responses:
- * 200:
- * description: Session revoked successfully.
- * 400:
- * description: Session ID is required.
- * 403:
- * description: Not authorized to revoke this session.
- * 404:
- * description: Session not found.
- * 500:
- * description: Failed to revoke session.
- */
-router.delete("/sessions/:sessionId", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- const sessionId = Array.isArray(req.params.sessionId)
- ? req.params.sessionId[0]
- : req.params.sessionId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- try {
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- const userRecord = user[0];
-
- const sessionRecords = await db
- .select()
- .from(sessions)
- .where(eq(sessions.id, sessionId))
- .limit(1);
-
- if (sessionRecords.length === 0) {
- return res.status(404).json({ error: "Session not found" });
- }
-
- const session = sessionRecords[0];
-
- if (!userRecord.isAdmin && session.userId !== userId) {
- return res
- .status(403)
- .json({ error: "Not authorized to revoke this session" });
- }
-
- const success = await authManager.revokeSession(sessionId);
-
- if (success) {
- authLogger.success("Session revoked", {
- operation: "session_revoke",
- sessionId,
- revokedBy: userId,
- sessionUserId: session.userId,
- });
- res.json({ success: true, message: "Session revoked successfully" });
- } else {
- res.status(500).json({ error: "Failed to revoke session" });
- }
- } catch (err) {
- authLogger.error("Failed to revoke session", err);
- res.status(500).json({ error: "Failed to revoke session" });
- }
-});
-
-/**
- * @openapi
- * /users/sessions/revoke-all:
- * post:
- * summary: Revoke all sessions for a user
- * description: Revokes all sessions with option to exclude current session.
- * tags:
- * - Users
- * requestBody:
- * required: false
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * targetUserId:
- * type: string
- * exceptCurrent:
- * type: boolean
- * responses:
- * 200:
- * description: Sessions revoked successfully.
- * 403:
- * description: Not authorized to revoke sessions for other users.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to revoke sessions.
- */
-router.post("/sessions/revoke-all", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- const { targetUserId, exceptCurrent } = req.body;
-
- try {
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0) {
- return res.status(404).json({ error: "User not found" });
- }
-
- const userRecord = user[0];
-
- let revokeUserId = userId;
- if (targetUserId && userRecord.isAdmin) {
- revokeUserId = targetUserId;
- } else if (targetUserId && targetUserId !== userId) {
- return res.status(403).json({
- error: "Not authorized to revoke sessions for other users",
- });
- }
-
- let currentSessionId: string | undefined;
- if (exceptCurrent) {
- currentSessionId = (req as AuthenticatedRequest).sessionId;
- }
-
- const revokedCount = await authManager.revokeAllUserSessions(
- revokeUserId,
- currentSessionId,
- );
-
- authLogger.success("User sessions revoked", {
- operation: "user_sessions_revoke_all",
- revokeUserId,
- revokedBy: userId,
- exceptCurrent,
- revokedCount,
- });
-
- res.json({
- message: `${revokedCount} session(s) revoked successfully`,
- count: revokedCount,
- });
- } catch (err) {
- authLogger.error("Failed to revoke user sessions", err);
- res.status(500).json({ error: "Failed to revoke sessions" });
- }
-});
-
-/**
- * @openapi
- * /users/link-oidc-to-password:
- * post:
- * summary: Link OIDC user to password account
- * description: Merges an OIDC-only account into a password-based account (admin only).
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * oidcUserId:
- * type: string
- * targetUsername:
- * type: string
- * responses:
- * 200:
- * description: Accounts linked successfully.
- * 400:
- * description: Invalid request or incompatible accounts.
- * 403:
- * description: Admin access required.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to link accounts.
- */
-router.post("/link-oidc-to-password", authenticateJWT, async (req, res) => {
- const adminUserId = (req as AuthenticatedRequest).userId;
- const { oidcUserId, targetUsername } = req.body;
-
- if (!isNonEmptyString(oidcUserId) || !isNonEmptyString(targetUsername)) {
- return res.status(400).json({
- error: "OIDC user ID and target username are required",
- });
- }
-
- try {
- const adminUser = await db
- .select()
- .from(users)
- .where(eq(users.id, adminUserId));
- if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
- return res.status(403).json({ error: "Admin access required" });
- }
-
- const oidcUserRecords = await db
- .select()
- .from(users)
- .where(eq(users.id, oidcUserId));
- if (!oidcUserRecords || oidcUserRecords.length === 0) {
- return res.status(404).json({ error: "OIDC user not found" });
- }
-
- const oidcUser = oidcUserRecords[0];
-
- if (!oidcUser.isOidc) {
- return res.status(400).json({
- error: "Source user is not an OIDC user",
- });
- }
-
- const targetUserRecords = await db
- .select()
- .from(users)
- .where(eq(users.username, targetUsername));
- if (!targetUserRecords || targetUserRecords.length === 0) {
- return res.status(404).json({ error: "Target password user not found" });
- }
-
- const targetUser = targetUserRecords[0];
-
- if (targetUser.isOidc || !targetUser.passwordHash) {
- return res.status(400).json({
- error: "Target user must be a password-based account",
- });
- }
-
- if (targetUser.clientId && targetUser.oidcIdentifier) {
- return res.status(400).json({
- error: "Target user already has OIDC authentication configured",
- });
- }
-
- authLogger.info("Linking OIDC user to password account", {
- operation: "link_oidc_to_password",
- oidcUserId,
- oidcUsername: oidcUser.username,
- targetUserId: targetUser.id,
- targetUsername: targetUser.username,
- adminUserId,
- });
-
- await db
- .update(users)
- .set({
- isOidc: true,
- oidcIdentifier: oidcUser.oidcIdentifier,
- clientId: oidcUser.clientId,
- clientSecret: oidcUser.clientSecret,
- issuerUrl: oidcUser.issuerUrl,
- authorizationUrl: oidcUser.authorizationUrl,
- tokenUrl: oidcUser.tokenUrl,
- identifierPath: oidcUser.identifierPath,
- namePath: oidcUser.namePath,
- scopes: oidcUser.scopes || "openid email profile",
- })
- .where(eq(users.id, targetUser.id));
-
- try {
- await authManager.convertToOIDCEncryption(targetUser.id);
- } catch (encryptionError) {
- authLogger.error(
- "Failed to convert encryption to OIDC during linking",
- encryptionError,
- {
- operation: "link_convert_encryption_failed",
- userId: targetUser.id,
- },
- );
- await db
- .update(users)
- .set({
- isOidc: false,
- oidcIdentifier: null,
- clientId: "",
- clientSecret: "",
- issuerUrl: "",
- authorizationUrl: "",
- tokenUrl: "",
- identifierPath: "",
- namePath: "",
- scopes: "openid email profile",
- })
- .where(eq(users.id, targetUser.id));
-
- return res.status(500).json({
- error:
- "Failed to convert encryption for dual-auth. Please ensure the password account has encryption setup.",
- details:
- encryptionError instanceof Error
- ? encryptionError.message
- : "Unknown error",
- });
- }
-
- await authManager.revokeAllUserSessions(oidcUserId);
- authManager.logoutUser(oidcUserId);
-
- await deleteUserAndRelatedData(oidcUserId);
-
- try {
- const { saveMemoryDatabaseToFile } = await import("../db/index.js");
- await saveMemoryDatabaseToFile();
- } catch (saveError) {
- authLogger.error("Failed to persist account linking to disk", saveError, {
- operation: "link_oidc_save_failed",
- oidcUserId,
- targetUserId: targetUser.id,
- });
- }
-
- authLogger.success(
- `OIDC user ${oidcUser.username} linked to password account ${targetUser.username}`,
- {
- operation: "link_oidc_to_password_success",
- oidcUserId,
- oidcUsername: oidcUser.username,
- targetUserId: targetUser.id,
- targetUsername: targetUser.username,
- adminUserId,
- },
- );
-
- res.json({
- success: true,
- message: `OIDC user ${oidcUser.username} has been linked to ${targetUser.username}. The password account can now use both password and OIDC login.`,
- });
- } catch (err) {
- authLogger.error("Failed to link OIDC user to password account", err, {
- operation: "link_oidc_to_password_failed",
- oidcUserId,
- targetUsername,
- adminUserId,
- });
- res.status(500).json({
- error: "Failed to link accounts",
- details: err instanceof Error ? err.message : "Unknown error",
- });
- }
-});
-
-/**
- * @openapi
- * /users/unlink-oidc-from-password:
- * post:
- * summary: Unlink OIDC from password account
- * description: Removes OIDC authentication from a dual-auth account (admin only).
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * userId:
- * type: string
- * responses:
- * 200:
- * description: OIDC unlinked successfully.
- * 400:
- * description: Invalid request or user doesn't have OIDC.
- * 403:
- * description: Admin privileges required.
- * 404:
- * description: User not found.
- * 500:
- * description: Failed to unlink OIDC.
- */
-router.post("/unlink-oidc-from-password", authenticateJWT, async (req, res) => {
- const adminUserId = (req as AuthenticatedRequest).userId;
- const { userId } = req.body;
-
- if (!userId) {
- return res.status(400).json({
- error: "User ID is required",
- });
- }
-
- try {
- const adminUser = await db
- .select()
- .from(users)
- .where(eq(users.id, adminUserId));
-
- if (!adminUser || adminUser.length === 0 || !adminUser[0].isAdmin) {
- authLogger.warn("Non-admin attempted to unlink OIDC from password", {
- operation: "unlink_oidc_unauthorized",
- adminUserId,
- targetUserId: userId,
- });
- return res.status(403).json({
- error: "Admin privileges required",
- });
- }
-
- const targetUserRecords = await db
- .select()
- .from(users)
- .where(eq(users.id, userId));
-
- if (!targetUserRecords || targetUserRecords.length === 0) {
- return res.status(404).json({
- error: "User not found",
- });
- }
-
- const targetUser = targetUserRecords[0];
-
- if (!targetUser.isOidc) {
- return res.status(400).json({
- error: "User does not have OIDC authentication enabled",
- });
- }
-
- if (!targetUser.passwordHash || targetUser.passwordHash === "") {
- return res.status(400).json({
- error:
- "Cannot unlink OIDC from a user without password authentication. This would leave the user unable to login.",
- });
- }
-
- authLogger.info("Unlinking OIDC from password account", {
- operation: "unlink_oidc_from_password_start",
- targetUserId: targetUser.id,
- targetUsername: targetUser.username,
- adminUserId,
- });
-
- await db
- .update(users)
- .set({
- isOidc: false,
- oidcIdentifier: null,
- clientId: "",
- clientSecret: "",
- issuerUrl: "",
- authorizationUrl: "",
- tokenUrl: "",
- identifierPath: "",
- namePath: "",
- scopes: "openid email profile",
- })
- .where(eq(users.id, targetUser.id));
-
- try {
- const { saveMemoryDatabaseToFile } = await import("../db/index.js");
- await saveMemoryDatabaseToFile();
- } catch (saveError) {
- authLogger.error(
- "Failed to save database after unlinking OIDC",
- saveError,
- {
- operation: "unlink_oidc_save_failed",
- targetUserId: targetUser.id,
- },
- );
- }
-
- authLogger.success("OIDC unlinked from password account successfully", {
- operation: "unlink_oidc_from_password_success",
- targetUserId: targetUser.id,
- targetUsername: targetUser.username,
- adminUserId,
- });
-
- res.json({
- success: true,
- message: `OIDC authentication has been removed from ${targetUser.username}. User can now only login with password.`,
- });
- } catch (err) {
- authLogger.error("Failed to unlink OIDC from password account", err, {
- operation: "unlink_oidc_from_password_failed",
- targetUserId: userId,
- adminUserId,
- });
- res.status(500).json({
- error: "Failed to unlink OIDC",
- details: err instanceof Error ? err.message : "Unknown error",
- });
- }
-});
-
-/**
- * @openapi
- * /users/guacamole-settings:
- * get:
- * summary: Get Guacamole settings
- * description: Returns current guacd enabled status and host:port URL. No authentication required.
- * tags:
- * - Users
- * responses:
- * 200:
- * description: Guacamole settings.
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * enabled:
- * type: boolean
- * url:
- * type: string
- * 500:
- * description: Failed to get guacamole settings.
- */
-router.get("/guacamole-settings", authenticateJWT, async (req, res) => {
- try {
- const enabledRow = db.$client
- .prepare("SELECT value FROM settings WHERE key = 'guac_enabled'")
- .get() as { value: string } | undefined;
- const urlRow = db.$client
- .prepare("SELECT value FROM settings WHERE key = 'guac_url'")
- .get() as { value: string } | undefined;
- res.json({
- enabled: enabledRow ? enabledRow.value !== "false" : true,
- url: urlRow ? urlRow.value : "guacd:4822",
- });
- } catch (err) {
- authLogger.error("Failed to get guacamole settings", err);
- res.status(500).json({ error: "Failed to get guacamole settings" });
- }
-});
+ const targetUserId = targetUser[0].id;
-/**
- * @openapi
- * /users/guacamole-settings:
- * patch:
- * summary: Update Guacamole settings
- * description: Admin-only. Updates guacd enabled status and/or host:port URL.
- * tags:
- * - Users
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * enabled:
- * type: boolean
- * url:
- * type: string
- * responses:
- * 200:
- * description: Guacamole settings updated.
- * 403:
- * description: Not authorized.
- * 500:
- * description: Failed to update guacamole settings.
- */
-router.patch("/guacamole-settings", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- try {
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0 || !user[0].isAdmin) {
- return res.status(403).json({ error: "Not authorized" });
- }
- const { enabled, url } = req.body;
- if (typeof enabled === "boolean") {
- db.$client
- .prepare(
- "INSERT OR REPLACE INTO settings (key, value) VALUES ('guac_enabled', ?)",
- )
- .run(enabled ? "true" : "false");
- }
- if (typeof url === "string") {
- db.$client
- .prepare(
- "INSERT OR REPLACE INTO settings (key, value) VALUES ('guac_url', ?)",
- )
- .run(url);
- try {
- await restartGuacServer();
- } catch (err) {
- authLogger.error("Failed to restart guac server after URL update", err);
- }
- }
- const enabledRow = db.$client
- .prepare("SELECT value FROM settings WHERE key = 'guac_enabled'")
- .get() as { value: string } | undefined;
- const urlRow = db.$client
- .prepare("SELECT value FROM settings WHERE key = 'guac_url'")
- .get() as { value: string } | undefined;
- res.json({
- enabled: enabledRow ? enabledRow.value !== "false" : true,
- url: urlRow ? urlRow.value : "guacd:4822",
- });
- } catch (err) {
- authLogger.error("Failed to update guacamole settings", err);
- res.status(500).json({ error: "Failed to update guacamole settings" });
- }
-});
+ await deleteUserAndRelatedData(targetUserId);
-/**
- * @openapi
- * /users/log-level:
- * get:
- * summary: Get log level setting
- * description: Returns the configured log verbosity level.
- * tags:
- * - Users
- * responses:
- * 200:
- * description: Current log level.
- */
-router.get("/log-level", authenticateJWT, async (_req, res) => {
- try {
- const row = db.$client
- .prepare("SELECT value FROM settings WHERE key = 'log_level'")
- .get() as { value: string } | undefined;
- res.json({
- level: row ? row.value : getGlobalLogLevel(),
+ authLogger.warn("User account deleted by admin", {
+ operation: "admin_delete_user",
+ adminId: userId,
+ targetUserId,
+ targetUsername: username,
});
+ res.json({ message: `User ${username} deleted successfully` });
} catch (err) {
- authLogger.error("Failed to get log level", err);
- res.status(500).json({ error: "Failed to get log level" });
- }
-});
+ authLogger.error("Failed to delete user", err);
-/**
- * @openapi
- * /users/log-level:
- * patch:
- * summary: Update log level setting (admin only)
- * description: Sets the log verbosity level.
- * tags:
- * - Users
- * responses:
- * 200:
- * description: Log level updated.
- * 400:
- * description: Invalid log level.
- * 403:
- * description: Not authorized.
- */
-router.patch("/log-level", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- try {
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0 || !user[0].isAdmin) {
- return res.status(403).json({ error: "Not authorized" });
- }
- const { level } = req.body;
- const validLevels = ["debug", "info", "warn", "error"];
- if (typeof level !== "string" || !validLevels.includes(level)) {
- return res
- .status(400)
- .json({ error: "level must be one of: debug, info, warn, error" });
+ if (err && typeof err === "object" && "code" in err) {
+ if (err.code === "SQLITE_CONSTRAINT_FOREIGNKEY") {
+ res.status(400).json({
+ error:
+ "Cannot delete user: User has associated data that cannot be removed",
+ });
+ } else {
+ res.status(500).json({ error: `Database error: ${err.code}` });
+ }
+ } else {
+ res.status(500).json({ error: "Failed to delete account" });
}
- db.$client
- .prepare(
- "INSERT OR REPLACE INTO settings (key, value) VALUES ('log_level', ?)",
- )
- .run(level);
- setGlobalLogLevel(level);
- res.json({ level });
- } catch (err) {
- authLogger.error("Failed to set log level", err);
- res.status(500).json({ error: "Failed to set log level" });
- }
-});
-
-/**
- * @openapi
- * /users/session-timeout:
- * get:
- * summary: Get session timeout setting
- * description: Returns the configured session timeout in hours.
- * tags:
- * - Users
- * responses:
- * 200:
- * description: Current session timeout hours.
- */
-router.get("/session-timeout", authenticateJWT, async (_req, res) => {
- try {
- const row = db.$client
- .prepare("SELECT value FROM settings WHERE key = 'session_timeout_hours'")
- .get() as { value: string } | undefined;
- res.json({
- timeoutHours: row ? parseInt(row.value, 10) : 24,
- });
- } catch (err) {
- authLogger.error("Failed to get session timeout", err);
- res.status(500).json({ error: "Failed to get session timeout" });
}
});
-/**
- * @openapi
- * /users/session-timeout:
- * patch:
- * summary: Update session timeout setting (admin only)
- * description: Sets the session timeout in hours.
- * tags:
- * - Users
- * responses:
- * 200:
- * description: Session timeout updated.
- * 400:
- * description: Invalid value.
- * 403:
- * description: Not authorized.
- */
-router.patch("/session-timeout", authenticateJWT, async (req, res) => {
- const userId = (req as AuthenticatedRequest).userId;
- try {
- const user = await db.select().from(users).where(eq(users.id, userId));
- if (!user || user.length === 0 || !user[0].isAdmin) {
- return res.status(403).json({ error: "Not authorized" });
- }
- const { timeoutHours } = req.body;
- if (
- typeof timeoutHours !== "number" ||
- timeoutHours < 1 ||
- timeoutHours > 720
- ) {
- return res
- .status(400)
- .json({ error: "timeoutHours must be between 1 and 720" });
- }
- db.$client
- .prepare(
- "INSERT OR REPLACE INTO settings (key, value) VALUES ('session_timeout_hours', ?)",
- )
- .run(String(timeoutHours));
- res.json({ timeoutHours });
- } catch (err) {
- authLogger.error("Failed to set session timeout", err);
- res.status(500).json({ error: "Failed to set session timeout" });
- }
+registerUserDataAccessRoutes(router, {
+ authenticateJWT,
+ authManager,
});
-/**
- * @openapi
- * /users/api-keys:
- * post:
- * summary: Create an API key (admin only)
- * description: Creates a new API key scoped to a specific user. The full token is returned only once.
- * tags:
- * - API Keys
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * required:
- * - name
- * - userId
- * properties:
- * name:
- * type: string
- * description: Human-readable name for the key.
- * userId:
- * type: string
- * description: ID of the user this key is scoped to.
- * expiresAt:
- * type: string
- * format: date-time
- * description: Optional expiration date. Null means the key never expires.
- * responses:
- * 201:
- * description: API key created. Contains the full token (shown only once).
- * 400:
- * description: Invalid input.
- * 403:
- * description: Admin access required.
- * 404:
- * description: Target user not found.
- * 500:
- * description: Failed to create API key.
- */
-router.post("/api-keys", requireAdmin, async (req, res) => {
- try {
- const { name, userId: targetUserId, expiresAt } = req.body;
-
- if (typeof name !== "string" || !name.trim()) {
- return res.status(400).json({ error: "name is required" });
- }
- if (typeof targetUserId !== "string" || !targetUserId.trim()) {
- return res.status(400).json({ error: "userId is required" });
- }
-
- const targetUser = await db
- .select()
- .from(users)
- .where(eq(users.id, targetUserId))
- .limit(1);
- if (targetUser.length === 0) {
- return res.status(404).json({ error: "Target user not found" });
- }
-
- let expiresAtValue: string | null = null;
- if (expiresAt) {
- const parsed = new Date(expiresAt);
- if (isNaN(parsed.getTime())) {
- return res.status(400).json({ error: "Invalid expiresAt date" });
- }
- if (parsed <= new Date()) {
- return res
- .status(400)
- .json({ error: "expiresAt must be in the future" });
- }
- expiresAtValue = parsed.toISOString();
- }
-
- const rawToken = "tmx_" + crypto.randomBytes(32).toString("hex");
- const tokenPrefix = rawToken.substring(0, 12);
- const tokenHash = await bcrypt.hash(rawToken, 10);
- const keyId = nanoid();
- const now = new Date().toISOString();
-
- await db.insert(apiKeys).values({
- id: keyId,
- userId: targetUserId,
- name: name.trim(),
- tokenHash,
- tokenPrefix,
- createdAt: now,
- expiresAt: expiresAtValue,
- lastUsedAt: null,
- isActive: true,
- });
-
- const { saveMemoryDatabaseToFile } = await import("../db/index.js");
- await saveMemoryDatabaseToFile();
-
- return res.status(201).json({
- id: keyId,
- name: name.trim(),
- userId: targetUserId,
- username: targetUser[0].username,
- tokenPrefix,
- createdAt: now,
- expiresAt: expiresAtValue,
- token: rawToken,
- });
- } catch (err) {
- authLogger.error("Failed to create API key", err);
- return res.status(500).json({ error: "Failed to create API key" });
- }
+registerUserSessionRoutes(router, {
+ authenticateJWT,
+ authManager,
});
-/**
- * @openapi
- * /users/api-keys:
- * get:
- * summary: List all API keys (admin only)
- * description: Returns all API keys with associated usernames. Token hashes are never returned.
- * tags:
- * - API Keys
- * responses:
- * 200:
- * description: List of API keys.
- * 403:
- * description: Admin access required.
- * 500:
- * description: Failed to fetch API keys.
- */
-router.get("/api-keys", requireAdmin, async (_req, res) => {
- try {
- const keys = await db
- .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);
-
- return res.json({ apiKeys: keys });
- } catch (err) {
- authLogger.error("Failed to list API keys", err);
- return res.status(500).json({ error: "Failed to fetch API keys" });
- }
+registerUserOidcAccountRoutes(router, {
+ authenticateJWT,
+ authManager,
});
-/**
- * @openapi
- * /users/api-keys/{keyId}:
- * delete:
- * summary: Delete an API key (admin only)
- * description: Permanently deletes an API key. It can no longer be used to authenticate.
- * tags:
- * - API Keys
- * parameters:
- * - in: path
- * name: keyId
- * required: true
- * schema:
- * type: string
- * description: The ID of the API key to delete.
- * responses:
- * 200:
- * description: API key deleted.
- * 403:
- * description: Admin access required.
- * 404:
- * description: API key not found.
- * 500:
- * description: Failed to delete API key.
- */
-router.delete("/api-keys/:keyId", requireAdmin, async (req, res) => {
- try {
- const keyId = String(req.params.keyId);
-
- const existing = await db
- .select()
- .from(apiKeys)
- .where(eq(apiKeys.id, keyId))
- .limit(1);
-
- if (existing.length === 0) {
- return res.status(404).json({ error: "API key not found" });
- }
-
- await db.delete(apiKeys).where(eq(apiKeys.id, keyId));
-
- const { saveMemoryDatabaseToFile } = await import("../db/index.js");
- await saveMemoryDatabaseToFile();
+registerUserSettingsRoutes(router, authenticateJWT);
- return res.json({ success: true });
- } catch (err) {
- authLogger.error("Failed to delete API key", err, {
- keyId: String(req.params.keyId),
- });
- return res.status(500).json({ error: "Failed to delete API key" });
- }
-});
+registerUserApiKeyRoutes(router, requireAdmin);
export default router;
diff --git a/src/backend/guacamole/routes.ts b/src/backend/guacamole/routes.ts
index b0867f033..b7ac567a8 100644
--- a/src/backend/guacamole/routes.ts
+++ b/src/backend/guacamole/routes.ts
@@ -232,7 +232,8 @@ router.post(
const rdpRaw = !!host.enableRdp;
const vncRaw = !!host.enableVnc;
const telRaw = !!host.enableTelnet;
- const isMigratedNonSsh = !rdpRaw && !vncRaw && !telRaw && ct && ct !== "ssh";
+ const isMigratedNonSsh =
+ !rdpRaw && !vncRaw && !telRaw && ct && ct !== "ssh";
const protocolEnabledMap: Record<string, boolean> = {
rdp: isMigratedNonSsh ? ct === "rdp" : rdpRaw,
vnc: isMigratedNonSsh ? ct === "vnc" : vncRaw,
diff --git a/src/backend/ssh/docker-console.ts b/src/backend/ssh/docker-console.ts
index 4016f8c6f..2af5dc145 100644
--- a/src/backend/ssh/docker-console.ts
+++ b/src/backend/ssh/docker-console.ts
@@ -297,7 +297,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
const authManagerInstance = AuthManager.getInstance();
const payload = await authManagerInstance.verifyJWTToken(token);
- if (!payload || !payload.userId) {
+ if (!payload?.userId || payload.pendingTOTP) {
ws.close(1008, "Authentication required");
return;
}
diff --git a/src/backend/ssh/docker-container-routes.ts b/src/backend/ssh/docker-container-routes.ts
new file mode 100644
index 000000000..f9c71e50a
--- /dev/null
+++ b/src/backend/ssh/docker-container-routes.ts
@@ -0,0 +1,1093 @@
+import type express from "express";
+import { logger } from "../utils/logger.js";
+
+const sshLogger = logger;
+
+type DockerSession = {
+ isConnected: boolean;
+ lastActive: number;
+ activeOperations: number;
+ hostId?: number;
+};
+
+type PendingDockerTotpSession = unknown;
+
+type ExecuteDockerCommand = (
+ session: DockerSession,
+ command: string,
+ sessionId: string,
+ userId: string,
+ hostId?: number,
+) => Promise<string>;
+
+type DockerContainerRoutesDeps = {
+ sshSessions: Record<string, DockerSession>;
+ pendingTOTPSessions: Record<string, PendingDockerTotpSession>;
+ getRequestUserId: (req: express.Request) => string | undefined;
+ executeDockerCommand: ExecuteDockerCommand;
+ dockerTimestampPattern: RegExp;
+};
+
+export function registerDockerContainerRoutes(
+ app: express.Express,
+ {
+ sshSessions,
+ pendingTOTPSessions,
+ getRequestUserId,
+ executeDockerCommand,
+ dockerTimestampPattern: DOCKER_TIMESTAMP_RE,
+ }: DockerContainerRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /docker/containers/{sessionId}:
+ * get:
+ * summary: List all containers
+ * description: Lists all Docker containers on the host.
+ * tags:
+ * - Docker
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: query
+ * name: all
+ * schema:
+ * type: boolean
+ * responses:
+ * 200:
+ * description: A list of containers.
+ * 400:
+ * description: SSH session not found or not connected.
+ * 500:
+ * description: Failed to list containers.
+ */
+ app.get("/docker/containers/:sessionId", async (req, res) => {
+ const { sessionId } = req.params;
+ const all = req.query.all !== "false";
+ const userId = getRequestUserId(req);
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ if (pendingTOTPSessions[sessionId]) {
+ return res.status(400).json({
+ error: "Connection pending authentication",
+ code: "AUTH_PENDING",
+ });
+ }
+
+ const session = sshSessions[sessionId];
+
+ if (!session || !session.isConnected) {
+ return res.status(400).json({
+ error: "SSH session not found or not connected",
+ });
+ }
+
+ session.lastActive = Date.now();
+ session.activeOperations++;
+
+ try {
+ const allFlag = all ? "-a " : "";
+ const command = `docker ps ${allFlag}--format '{"id":"{{.ID}}","name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}","state":"{{.State}}","ports":"{{.Ports}}","created":"{{.CreatedAt}}"}'`;
+
+ const output = await executeDockerCommand(
+ session,
+ command,
+ sessionId,
+ userId,
+ session.hostId,
+ );
+
+ const containers = output
+ .split("\n")
+ .filter((line) => line.trim())
+ .map((line) => {
+ try {
+ return JSON.parse(line);
+ } catch {
+ sshLogger.warn("Failed to parse container line", {
+ operation: "parse_container",
+ line,
+ });
+ return null;
+ }
+ })
+ .filter((c) => c !== null);
+
+ session.activeOperations--;
+
+ res.json(containers);
+ } catch (error) {
+ session.activeOperations--;
+ sshLogger.error("Failed to list Docker containers", error, {
+ operation: "list_containers",
+ sessionId,
+ userId,
+ });
+
+ res.status(500).json({
+ error:
+ error instanceof Error ? error.message : "Failed to list containers",
+ });
+ }
+ });
+
+ /**
+ * @openapi
+ * /docker/containers/{sessionId}/{containerId}:
+ * get:
+ * summary: Get container details
+ * description: Retrieves detailed information about a specific container.
+ * tags:
+ * - Docker
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: path
+ * name: containerId
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: Container details.
+ * 400:
+ * description: SSH session not found or not connected.
+ * 404:
+ * description: Container not found.
+ * 500:
+ * description: Failed to get container details.
+ */
+ app.get("/docker/containers/:sessionId/:containerId", async (req, res) => {
+ const { sessionId, containerId } = req.params;
+ const userId = getRequestUserId(req);
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ const session = sshSessions[sessionId];
+
+ if (!session || !session.isConnected) {
+ return res.status(400).json({
+ error: "SSH session not found or not connected",
+ });
+ }
+
+ session.lastActive = Date.now();
+ session.activeOperations++;
+
+ try {
+ const command = `docker inspect ${containerId}`;
+ const output = await executeDockerCommand(
+ session,
+ command,
+ sessionId,
+ userId,
+ session.hostId,
+ );
+ const details = JSON.parse(output);
+
+ session.activeOperations--;
+
+ if (details && details.length > 0) {
+ res.json(details[0]);
+ } else {
+ res.status(404).json({
+ error: "Container not found",
+ code: "CONTAINER_NOT_FOUND",
+ });
+ }
+ } catch (error) {
+ session.activeOperations--;
+
+ const errorMsg = error instanceof Error ? error.message : "";
+ if (errorMsg.includes("No such container")) {
+ return res.status(404).json({
+ error: "Container not found",
+ code: "CONTAINER_NOT_FOUND",
+ });
+ }
+
+ sshLogger.error("Failed to get container details", error, {
+ operation: "get_container_details",
+ sessionId,
+ containerId,
+ userId,
+ });
+
+ res.status(500).json({
+ error: errorMsg || "Failed to get container details",
+ });
+ }
+ });
+
+ /**
+ * @openapi
+ * /docker/containers/{sessionId}/{containerId}/start:
+ * post:
+ * summary: Start container
+ * description: Starts a specific container.
+ * tags:
+ * - Docker
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: path
+ * name: containerId
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: Container started successfully.
+ * 400:
+ * description: SSH session not found or not connected.
+ * 404:
+ * description: Container not found.
+ * 500:
+ * description: Failed to start container.
+ */
+ app.post(
+ "/docker/containers/:sessionId/:containerId/start",
+ async (req, res) => {
+ const { sessionId, containerId } = req.params;
+ const userId = getRequestUserId(req);
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ const session = sshSessions[sessionId];
+
+ if (!session || !session.isConnected) {
+ return res.status(400).json({
+ error: "SSH session not found or not connected",
+ });
+ }
+
+ session.lastActive = Date.now();
+ session.activeOperations++;
+
+ try {
+ sshLogger.info("Docker container operation", {
+ operation: "docker_container_op",
+ sessionId,
+ userId,
+ hostId: session.hostId,
+ containerId,
+ action: "start",
+ });
+ await executeDockerCommand(
+ session,
+ `docker start ${containerId}`,
+ sessionId,
+ userId,
+ session.hostId,
+ );
+
+ session.activeOperations--;
+
+ res.json({
+ success: true,
+ message: "Container started successfully",
+ });
+ } catch (error) {
+ session.activeOperations--;
+
+ const errorMsg = error instanceof Error ? error.message : "";
+ if (errorMsg.includes("No such container")) {
+ return res.status(404).json({
+ success: false,
+ error: "Container not found",
+ code: "CONTAINER_NOT_FOUND",
+ });
+ }
+
+ sshLogger.error("Failed to start container", error, {
+ operation: "start_container",
+ sessionId,
+ containerId,
+ userId,
+ });
+
+ res.status(500).json({
+ success: false,
+ error: errorMsg || "Failed to start container",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /docker/containers/{sessionId}/{containerId}/stop:
+ * post:
+ * summary: Stop container
+ * description: Stops a specific container.
+ * tags:
+ * - Docker
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: path
+ * name: containerId
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: Container stopped successfully.
+ * 400:
+ * description: SSH session not found or not connected.
+ * 404:
+ * description: Container not found.
+ * 500:
+ * description: Failed to stop container.
+ */
+ app.post(
+ "/docker/containers/:sessionId/:containerId/stop",
+ async (req, res) => {
+ const { sessionId, containerId } = req.params;
+ const userId = getRequestUserId(req);
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ const session = sshSessions[sessionId];
+
+ if (!session || !session.isConnected) {
+ return res.status(400).json({
+ error: "SSH session not found or not connected",
+ });
+ }
+
+ session.lastActive = Date.now();
+ session.activeOperations++;
+
+ try {
+ sshLogger.info("Docker container operation", {
+ operation: "docker_container_op",
+ sessionId,
+ userId,
+ hostId: session.hostId,
+ containerId,
+ action: "stop",
+ });
+ await executeDockerCommand(
+ session,
+ `docker stop ${containerId}`,
+ sessionId,
+ userId,
+ session.hostId,
+ );
+
+ session.activeOperations--;
+
+ res.json({
+ success: true,
+ message: "Container stopped successfully",
+ });
+ } catch (error) {
+ session.activeOperations--;
+
+ const errorMsg = error instanceof Error ? error.message : "";
+ if (errorMsg.includes("No such container")) {
+ return res.status(404).json({
+ success: false,
+ error: "Container not found",
+ code: "CONTAINER_NOT_FOUND",
+ });
+ }
+
+ sshLogger.error("Failed to stop container", error, {
+ operation: "stop_container",
+ sessionId,
+ containerId,
+ userId,
+ });
+
+ res.status(500).json({
+ success: false,
+ error: errorMsg || "Failed to stop container",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /docker/containers/{sessionId}/{containerId}/restart:
+ * post:
+ * summary: Restart container
+ * description: Restarts a specific container.
+ * tags:
+ * - Docker
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: path
+ * name: containerId
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: Container restarted successfully.
+ * 400:
+ * description: SSH session not found or not connected.
+ * 404:
+ * description: Container not found.
+ * 500:
+ * description: Failed to restart container.
+ */
+ app.post(
+ "/docker/containers/:sessionId/:containerId/restart",
+ async (req, res) => {
+ const { sessionId, containerId } = req.params;
+ const userId = getRequestUserId(req);
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ const session = sshSessions[sessionId];
+
+ if (!session || !session.isConnected) {
+ return res.status(400).json({
+ error: "SSH session not found or not connected",
+ });
+ }
+
+ session.lastActive = Date.now();
+ session.activeOperations++;
+
+ try {
+ sshLogger.info("Docker container operation", {
+ operation: "docker_container_op",
+ sessionId,
+ userId,
+ hostId: session.hostId,
+ containerId,
+ action: "restart",
+ });
+ await executeDockerCommand(
+ session,
+ `docker restart ${containerId}`,
+ sessionId,
+ userId,
+ session.hostId,
+ );
+
+ session.activeOperations--;
+
+ res.json({
+ success: true,
+ message: "Container restarted successfully",
+ });
+ } catch (error) {
+ session.activeOperations--;
+
+ const errorMsg = error instanceof Error ? error.message : "";
+ if (errorMsg.includes("No such container")) {
+ return res.status(404).json({
+ success: false,
+ error: "Container not found",
+ code: "CONTAINER_NOT_FOUND",
+ });
+ }
+
+ sshLogger.error("Failed to restart container", error, {
+ operation: "restart_container",
+ sessionId,
+ containerId,
+ userId,
+ });
+
+ res.status(500).json({
+ success: false,
+ error: errorMsg || "Failed to restart container",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /docker/containers/{sessionId}/{containerId}/pause:
+ * post:
+ * summary: Pause container
+ * description: Pauses a specific container.
+ * tags:
+ * - Docker
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: path
+ * name: containerId
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: Container paused successfully.
+ * 400:
+ * description: SSH session not found or not connected.
+ * 404:
+ * description: Container not found.
+ * 500:
+ * description: Failed to pause container.
+ */
+ app.post(
+ "/docker/containers/:sessionId/:containerId/pause",
+ async (req, res) => {
+ const { sessionId, containerId } = req.params;
+ const userId = getRequestUserId(req);
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ const session = sshSessions[sessionId];
+
+ if (!session || !session.isConnected) {
+ return res.status(400).json({
+ error: "SSH session not found or not connected",
+ });
+ }
+
+ session.lastActive = Date.now();
+ session.activeOperations++;
+
+ try {
+ sshLogger.info("Docker container operation", {
+ operation: "docker_container_op",
+ sessionId,
+ userId,
+ hostId: session.hostId,
+ containerId,
+ action: "pause",
+ });
+ await executeDockerCommand(
+ session,
+ `docker pause ${containerId}`,
+ sessionId,
+ userId,
+ session.hostId,
+ );
+
+ session.activeOperations--;
+
+ res.json({
+ success: true,
+ message: "Container paused successfully",
+ });
+ } catch (error) {
+ session.activeOperations--;
+
+ const errorMsg = error instanceof Error ? error.message : "";
+ if (errorMsg.includes("No such container")) {
+ return res.status(404).json({
+ success: false,
+ error: "Container not found",
+ code: "CONTAINER_NOT_FOUND",
+ });
+ }
+
+ sshLogger.error("Failed to pause container", error, {
+ operation: "pause_container",
+ sessionId,
+ containerId,
+ userId,
+ });
+
+ res.status(500).json({
+ success: false,
+ error: errorMsg || "Failed to pause container",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /docker/containers/{sessionId}/{containerId}/unpause:
+ * post:
+ * summary: Unpause container
+ * description: Unpauses a specific container.
+ * tags:
+ * - Docker
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: path
+ * name: containerId
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: Container unpaused successfully.
+ * 400:
+ * description: SSH session not found or not connected.
+ * 404:
+ * description: Container not found.
+ * 500:
+ * description: Failed to unpause container.
+ */
+ app.post(
+ "/docker/containers/:sessionId/:containerId/unpause",
+ async (req, res) => {
+ const { sessionId, containerId } = req.params;
+ const userId = getRequestUserId(req);
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ const session = sshSessions[sessionId];
+
+ if (!session || !session.isConnected) {
+ return res.status(400).json({
+ error: "SSH session not found or not connected",
+ });
+ }
+
+ session.lastActive = Date.now();
+ session.activeOperations++;
+
+ try {
+ sshLogger.info("Docker container operation", {
+ operation: "docker_container_op",
+ sessionId,
+ userId,
+ hostId: session.hostId,
+ containerId,
+ action: "unpause",
+ });
+ await executeDockerCommand(
+ session,
+ `docker unpause ${containerId}`,
+ sessionId,
+ userId,
+ session.hostId,
+ );
+
+ session.activeOperations--;
+
+ res.json({
+ success: true,
+ message: "Container unpaused successfully",
+ });
+ } catch (error) {
+ session.activeOperations--;
+
+ const errorMsg = error instanceof Error ? error.message : "";
+ if (errorMsg.includes("No such container")) {
+ return res.status(404).json({
+ success: false,
+ error: "Container not found",
+ code: "CONTAINER_NOT_FOUND",
+ });
+ }
+
+ sshLogger.error("Failed to unpause container", error, {
+ operation: "unpause_container",
+ sessionId,
+ containerId,
+ userId,
+ });
+
+ res.status(500).json({
+ success: false,
+ error: errorMsg || "Failed to unpause container",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /docker/containers/{sessionId}/{containerId}/remove:
+ * delete:
+ * summary: Remove container
+ * description: Removes a specific container.
+ * tags:
+ * - Docker
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: path
+ * name: containerId
+ * required: true
+ * schema:
+ * type: string
+ * - in: query
+ * name: force
+ * schema:
+ * type: boolean
+ * responses:
+ * 200:
+ * description: Container removed successfully.
+ * 400:
+ * description: SSH session not found or not connected, or cannot remove a running container.
+ * 404:
+ * description: Container not found.
+ * 500:
+ * description: Failed to remove container.
+ */
+ app.delete(
+ "/docker/containers/:sessionId/:containerId/remove",
+ async (req, res) => {
+ const { sessionId, containerId } = req.params;
+ const force = req.query.force === "true";
+ const userId = getRequestUserId(req);
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ const session = sshSessions[sessionId];
+
+ if (!session || !session.isConnected) {
+ return res.status(400).json({
+ error: "SSH session not found or not connected",
+ });
+ }
+
+ session.lastActive = Date.now();
+ session.activeOperations++;
+
+ try {
+ sshLogger.info("Docker container operation", {
+ operation: "docker_container_op",
+ sessionId,
+ userId,
+ hostId: session.hostId,
+ containerId,
+ action: "remove",
+ });
+ const forceFlag = force ? "-f " : "";
+ await executeDockerCommand(
+ session,
+ `docker rm ${forceFlag}${containerId}`,
+ sessionId,
+ userId,
+ session.hostId,
+ );
+
+ session.activeOperations--;
+
+ res.json({
+ success: true,
+ message: "Container removed successfully",
+ });
+ } catch (error) {
+ session.activeOperations--;
+
+ const errorMsg = error instanceof Error ? error.message : "";
+ if (errorMsg.includes("No such container")) {
+ return res.status(404).json({
+ success: false,
+ error: "Container not found",
+ code: "CONTAINER_NOT_FOUND",
+ });
+ }
+
+ if (errorMsg.includes("cannot remove a running container")) {
+ return res.status(400).json({
+ success: false,
+ error:
+ "Cannot remove a running container. Stop it first or use force.",
+ code: "CONTAINER_RUNNING",
+ });
+ }
+
+ sshLogger.error("Failed to remove container", error, {
+ operation: "remove_container",
+ sessionId,
+ containerId,
+ userId,
+ });
+
+ res.status(500).json({
+ success: false,
+ error: errorMsg || "Failed to remove container",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /docker/containers/{sessionId}/{containerId}/logs:
+ * get:
+ * summary: Get container logs
+ * description: Retrieves logs for a specific container.
+ * tags:
+ * - Docker
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: path
+ * name: containerId
+ * required: true
+ * schema:
+ * type: string
+ * - in: query
+ * name: tail
+ * schema:
+ * type: integer
+ * - in: query
+ * name: timestamps
+ * schema:
+ * type: boolean
+ * - in: query
+ * name: since
+ * schema:
+ * type: string
+ * - in: query
+ * name: until
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: Container logs.
+ * 400:
+ * description: SSH session not found or not connected.
+ * 404:
+ * description: Container not found.
+ * 500:
+ * description: Failed to get container logs.
+ */
+ app.get(
+ "/docker/containers/:sessionId/:containerId/logs",
+ async (req, res) => {
+ const { sessionId, containerId } = req.params;
+ const tail = req.query.tail ? parseInt(req.query.tail as string) : 100;
+ const timestamps = req.query.timestamps === "true";
+ const since = req.query.since as string;
+ const until = req.query.until as string;
+ const userId = getRequestUserId(req);
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ const session = sshSessions[sessionId];
+
+ if (!session || !session.isConnected) {
+ return res.status(400).json({
+ error: "SSH session not found or not connected",
+ });
+ }
+
+ session.lastActive = Date.now();
+ session.activeOperations++;
+
+ try {
+ let command = `docker logs ${containerId} 2>&1`;
+
+ if (tail && tail > 0) {
+ command += ` --tail ${Math.floor(tail)}`;
+ }
+
+ if (timestamps) {
+ command += " --timestamps";
+ }
+
+ if (since && DOCKER_TIMESTAMP_RE.test(since)) {
+ command += ` --since ${since}`;
+ }
+
+ if (until && DOCKER_TIMESTAMP_RE.test(until)) {
+ command += ` --until ${until}`;
+ }
+
+ const logs = await executeDockerCommand(
+ session,
+ command,
+ sessionId,
+ userId,
+ session.hostId,
+ );
+
+ session.activeOperations--;
+
+ res.json({
+ success: true,
+ logs,
+ });
+ } catch (error) {
+ session.activeOperations--;
+
+ const errorMsg = error instanceof Error ? error.message : "";
+ if (errorMsg.includes("No such container")) {
+ return res.status(404).json({
+ success: false,
+ error: "Container not found",
+ code: "CONTAINER_NOT_FOUND",
+ });
+ }
+
+ sshLogger.error("Failed to get container logs", error, {
+ operation: "get_logs",
+ sessionId,
+ containerId,
+ userId,
+ });
+
+ res.status(500).json({
+ success: false,
+ error: errorMsg || "Failed to get container logs",
+ });
+ }
+ },
+ );
+
+ /**
+ * @openapi
+ * /docker/containers/{sessionId}/{containerId}/stats:
+ * get:
+ * summary: Get container stats
+ * description: Retrieves stats for a specific container.
+ * tags:
+ * - Docker
+ * parameters:
+ * - in: path
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: path
+ * name: containerId
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: Container stats.
+ * 400:
+ * description: SSH session not found or not connected.
+ * 404:
+ * description: Container not found.
+ * 500:
+ * description: Failed to get container stats.
+ */
+ app.get(
+ "/docker/containers/:sessionId/:containerId/stats",
+ async (req, res) => {
+ const { sessionId, containerId } = req.params;
+ const userId = getRequestUserId(req);
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ const session = sshSessions[sessionId];
+
+ if (!session || !session.isConnected) {
+ return res.status(400).json({
+ error: "SSH session not found or not connected",
+ });
+ }
+
+ session.lastActive = Date.now();
+ session.activeOperations++;
+
+ try {
+ const command = `docker stats ${containerId} --no-stream --format '{"cpu":"{{.CPUPerc}}","memory":"{{.MemUsage}}","memoryPercent":"{{.MemPerc}}","netIO":"{{.NetIO}}","blockIO":"{{.BlockIO}}","pids":"{{.PIDs}}"}'`;
+
+ const output = await executeDockerCommand(
+ session,
+ command,
+ sessionId,
+ userId,
+ session.hostId,
+ );
+ const rawStats = JSON.parse(output.trim());
+
+ const memoryParts = rawStats.memory.split(" / ");
+ const memoryUsed = memoryParts[0]?.trim() || "0B";
+ const memoryLimit = memoryParts[1]?.trim() || "0B";
+
+ const netIOParts = rawStats.netIO.split(" / ");
+ const netInput = netIOParts[0]?.trim() || "0B";
+ const netOutput = netIOParts[1]?.trim() || "0B";
+
+ const blockIOParts = rawStats.blockIO.split(" / ");
+ const blockRead = blockIOParts[0]?.trim() || "0B";
+ const blockWrite = blockIOParts[1]?.trim() || "0B";
+
+ const stats = {
+ cpu: rawStats.cpu,
+ memoryUsed,
+ memoryLimit,
+ memoryPercent: rawStats.memoryPercent,
+ netInput,
+ netOutput,
+ blockRead,
+ blockWrite,
+ pids: rawStats.pids,
+ };
+
+ session.activeOperations--;
+
+ res.json(stats);
+ } catch (error) {
+ session.activeOperations--;
+
+ const errorMsg = error instanceof Error ? error.message : "";
+ if (errorMsg.includes("No such container")) {
+ return res.status(404).json({
+ success: false,
+ error: "Container not found",
+ code: "CONTAINER_NOT_FOUND",
+ });
+ }
+
+ sshLogger.error("Failed to get container stats", error, {
+ operation: "get_stats",
+ sessionId,
+ containerId,
+ userId,
+ });
+
+ res.status(500).json({
+ success: false,
+ error: errorMsg || "Failed to get container stats",
+ });
+ }
+ },
+ );
+}
diff --git a/src/backend/ssh/docker.ts b/src/backend/ssh/docker.ts
index c28500b80..dd335f9a0 100644
--- a/src/backend/ssh/docker.ts
+++ b/src/backend/ssh/docker.ts
@@ -18,6 +18,7 @@ import {
import type { SSHHost, ProxyNode } from "../../types/index.js";
import type { LogEntry, ConnectionStage } from "../../types/connection-log.js";
import { SSHHostKeyVerifier } from "./host-key-verifier.js";
+import { registerDockerContainerRoutes } from "./docker-container-routes.js";
const sshLogger = logger;
@@ -526,6 +527,10 @@ app.use(authManager.createAuthMiddleware());
const CONTAINER_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
const DOCKER_TIMESTAMP_RE = /^[0-9T:.Z+-]+$/;
+function getRequestUserId(req: express.Request): string | undefined {
+ return (req as AuthenticatedRequest).userId;
+}
+
app.param("containerId", (req, res, next, value) => {
if (!CONTAINER_ID_RE.test(value)) {
return res.status(400).json({ error: "Invalid container ID" });
@@ -575,7 +580,7 @@ app.post("/docker/ssh/connect", async (req, res) => {
socks5Password,
socks5ProxyChain,
} = req.body;
- const userId = (req as unknown as { userId: string }).userId;
+ const userId = getRequestUserId(req);
const connectionLogs: Array<Omit<LogEntry, "id" | "timestamp">> = [];
@@ -1629,7 +1634,7 @@ app.post("/docker/ssh/disconnect", async (req, res) => {
*/
app.post("/docker/ssh/connect-totp", async (req, res) => {
const { sessionId, totpCode } = req.body;
- const userId = (req as unknown as { userId: string }).userId;
+ const userId = getRequestUserId(req);
if (!userId) {
sshLogger.error("TOTP verification rejected: no authenticated user", {
@@ -1821,7 +1826,7 @@ app.post("/docker/ssh/connect-totp", async (req, res) => {
*/
app.post("/docker/ssh/connect-warpgate", async (req, res) => {
const { sessionId } = req.body;
- const userId = (req as unknown as { userId: string }).userId;
+ const userId = getRequestUserId(req);
if (!userId) {
sshLogger.error("Warpgate verification rejected: no authenticated user", {
@@ -2004,7 +2009,7 @@ app.post("/docker/ssh/connect-warpgate", async (req, res) => {
*/
app.post("/docker/ssh/keepalive", async (req, res) => {
const { sessionId } = req.body;
- const userId = (req as AuthenticatedRequest).userId;
+ const userId = getRequestUserId(req);
if (!sessionId) {
return res.status(400).json({ error: "Session ID is required" });
@@ -2090,7 +2095,7 @@ app.get("/docker/ssh/status", async (req, res) => {
*/
app.get("/docker/validate/:sessionId", async (req, res) => {
const { sessionId } = req.params;
- const userId = (req as unknown as { userId: string }).userId;
+ const userId = getRequestUserId(req);
if (!userId) {
return res.status(401).json({ error: "Authentication required" });
@@ -2193,1056 +2198,14 @@ app.get("/docker/validate/:sessionId", async (req, res) => {
}
});
-/**
- * @openapi
- * /docker/containers/{sessionId}:
- * get:
- * summary: List all containers
- * description: Lists all Docker containers on the host.
- * tags:
- * - Docker
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: query
- * name: all
- * schema:
- * type: boolean
- * responses:
- * 200:
- * description: A list of containers.
- * 400:
- * description: SSH session not found or not connected.
- * 500:
- * description: Failed to list containers.
- */
-app.get("/docker/containers/:sessionId", async (req, res) => {
- const { sessionId } = req.params;
- const all = req.query.all !== "false";
- const userId = (req as unknown as { userId: string }).userId;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- if (pendingTOTPSessions[sessionId]) {
- return res.status(400).json({
- error: "Connection pending authentication",
- code: "AUTH_PENDING",
- });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- });
- }
-
- session.lastActive = Date.now();
- session.activeOperations++;
-
- try {
- const allFlag = all ? "-a " : "";
- const command = `docker ps ${allFlag}--format '{"id":"{{.ID}}","name":"{{.Names}}","image":"{{.Image}}","status":"{{.Status}}","state":"{{.State}}","ports":"{{.Ports}}","created":"{{.CreatedAt}}"}'`;
-
- const output = await executeDockerCommand(
- session,
- command,
- sessionId,
- userId,
- session.hostId,
- );
-
- const containers = output
- .split("\n")
- .filter((line) => line.trim())
- .map((line) => {
- try {
- return JSON.parse(line);
- } catch {
- sshLogger.warn("Failed to parse container line", {
- operation: "parse_container",
- line,
- });
- return null;
- }
- })
- .filter((c) => c !== null);
-
- session.activeOperations--;
-
- res.json(containers);
- } catch (error) {
- session.activeOperations--;
- sshLogger.error("Failed to list Docker containers", error, {
- operation: "list_containers",
- sessionId,
- userId,
- });
-
- res.status(500).json({
- error:
- error instanceof Error ? error.message : "Failed to list containers",
- });
- }
-});
-
-/**
- * @openapi
- * /docker/containers/{sessionId}/{containerId}:
- * get:
- * summary: Get container details
- * description: Retrieves detailed information about a specific container.
- * tags:
- * - Docker
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: path
- * name: containerId
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Container details.
- * 400:
- * description: SSH session not found or not connected.
- * 404:
- * description: Container not found.
- * 500:
- * description: Failed to get container details.
- */
-app.get("/docker/containers/:sessionId/:containerId", async (req, res) => {
- const { sessionId, containerId } = req.params;
- const userId = (req as unknown as { userId: string }).userId;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- });
- }
-
- session.lastActive = Date.now();
- session.activeOperations++;
-
- try {
- const command = `docker inspect ${containerId}`;
- const output = await executeDockerCommand(
- session,
- command,
- sessionId,
- userId,
- session.hostId,
- );
- const details = JSON.parse(output);
-
- session.activeOperations--;
-
- if (details && details.length > 0) {
- res.json(details[0]);
- } else {
- res.status(404).json({
- error: "Container not found",
- code: "CONTAINER_NOT_FOUND",
- });
- }
- } catch (error) {
- session.activeOperations--;
-
- const errorMsg = error instanceof Error ? error.message : "";
- if (errorMsg.includes("No such container")) {
- return res.status(404).json({
- error: "Container not found",
- code: "CONTAINER_NOT_FOUND",
- });
- }
-
- sshLogger.error("Failed to get container details", error, {
- operation: "get_container_details",
- sessionId,
- containerId,
- userId,
- });
-
- res.status(500).json({
- error: errorMsg || "Failed to get container details",
- });
- }
+registerDockerContainerRoutes(app, {
+ sshSessions,
+ pendingTOTPSessions,
+ getRequestUserId,
+ executeDockerCommand,
+ dockerTimestampPattern: DOCKER_TIMESTAMP_RE,
});
-/**
- * @openapi
- * /docker/containers/{sessionId}/{containerId}/start:
- * post:
- * summary: Start container
- * description: Starts a specific container.
- * tags:
- * - Docker
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: path
- * name: containerId
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Container started successfully.
- * 400:
- * description: SSH session not found or not connected.
- * 404:
- * description: Container not found.
- * 500:
- * description: Failed to start container.
- */
-app.post(
- "/docker/containers/:sessionId/:containerId/start",
- async (req, res) => {
- const { sessionId, containerId } = req.params;
- const userId = (req as unknown as { userId: string }).userId;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- });
- }
-
- session.lastActive = Date.now();
- session.activeOperations++;
-
- try {
- sshLogger.info("Docker container operation", {
- operation: "docker_container_op",
- sessionId,
- userId,
- hostId: session.hostId,
- containerId,
- action: "start",
- });
- await executeDockerCommand(
- session,
- `docker start ${containerId}`,
- sessionId,
- userId,
- session.hostId,
- );
-
- session.activeOperations--;
-
- res.json({
- success: true,
- message: "Container started successfully",
- });
- } catch (error) {
- session.activeOperations--;
-
- const errorMsg = error instanceof Error ? error.message : "";
- if (errorMsg.includes("No such container")) {
- return res.status(404).json({
- success: false,
- error: "Container not found",
- code: "CONTAINER_NOT_FOUND",
- });
- }
-
- sshLogger.error("Failed to start container", error, {
- operation: "start_container",
- sessionId,
- containerId,
- userId,
- });
-
- res.status(500).json({
- success: false,
- error: errorMsg || "Failed to start container",
- });
- }
- },
-);
-
-/**
- * @openapi
- * /docker/containers/{sessionId}/{containerId}/stop:
- * post:
- * summary: Stop container
- * description: Stops a specific container.
- * tags:
- * - Docker
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: path
- * name: containerId
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Container stopped successfully.
- * 400:
- * description: SSH session not found or not connected.
- * 404:
- * description: Container not found.
- * 500:
- * description: Failed to stop container.
- */
-app.post(
- "/docker/containers/:sessionId/:containerId/stop",
- async (req, res) => {
- const { sessionId, containerId } = req.params;
- const userId = (req as unknown as { userId: string }).userId;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- });
- }
-
- session.lastActive = Date.now();
- session.activeOperations++;
-
- try {
- sshLogger.info("Docker container operation", {
- operation: "docker_container_op",
- sessionId,
- userId,
- hostId: session.hostId,
- containerId,
- action: "stop",
- });
- await executeDockerCommand(
- session,
- `docker stop ${containerId}`,
- sessionId,
- userId,
- session.hostId,
- );
-
- session.activeOperations--;
-
- res.json({
- success: true,
- message: "Container stopped successfully",
- });
- } catch (error) {
- session.activeOperations--;
-
- const errorMsg = error instanceof Error ? error.message : "";
- if (errorMsg.includes("No such container")) {
- return res.status(404).json({
- success: false,
- error: "Container not found",
- code: "CONTAINER_NOT_FOUND",
- });
- }
-
- sshLogger.error("Failed to stop container", error, {
- operation: "stop_container",
- sessionId,
- containerId,
- userId,
- });
-
- res.status(500).json({
- success: false,
- error: errorMsg || "Failed to stop container",
- });
- }
- },
-);
-
-/**
- * @openapi
- * /docker/containers/{sessionId}/{containerId}/restart:
- * post:
- * summary: Restart container
- * description: Restarts a specific container.
- * tags:
- * - Docker
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: path
- * name: containerId
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Container restarted successfully.
- * 400:
- * description: SSH session not found or not connected.
- * 404:
- * description: Container not found.
- * 500:
- * description: Failed to restart container.
- */
-app.post(
- "/docker/containers/:sessionId/:containerId/restart",
- async (req, res) => {
- const { sessionId, containerId } = req.params;
- const userId = (req as unknown as { userId: string }).userId;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- });
- }
-
- session.lastActive = Date.now();
- session.activeOperations++;
-
- try {
- sshLogger.info("Docker container operation", {
- operation: "docker_container_op",
- sessionId,
- userId,
- hostId: session.hostId,
- containerId,
- action: "restart",
- });
- await executeDockerCommand(
- session,
- `docker restart ${containerId}`,
- sessionId,
- userId,
- session.hostId,
- );
-
- session.activeOperations--;
-
- res.json({
- success: true,
- message: "Container restarted successfully",
- });
- } catch (error) {
- session.activeOperations--;
-
- const errorMsg = error instanceof Error ? error.message : "";
- if (errorMsg.includes("No such container")) {
- return res.status(404).json({
- success: false,
- error: "Container not found",
- code: "CONTAINER_NOT_FOUND",
- });
- }
-
- sshLogger.error("Failed to restart container", error, {
- operation: "restart_container",
- sessionId,
- containerId,
- userId,
- });
-
- res.status(500).json({
- success: false,
- error: errorMsg || "Failed to restart container",
- });
- }
- },
-);
-
-/**
- * @openapi
- * /docker/containers/{sessionId}/{containerId}/pause:
- * post:
- * summary: Pause container
- * description: Pauses a specific container.
- * tags:
- * - Docker
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: path
- * name: containerId
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Container paused successfully.
- * 400:
- * description: SSH session not found or not connected.
- * 404:
- * description: Container not found.
- * 500:
- * description: Failed to pause container.
- */
-app.post(
- "/docker/containers/:sessionId/:containerId/pause",
- async (req, res) => {
- const { sessionId, containerId } = req.params;
- const userId = (req as unknown as { userId: string }).userId;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- });
- }
-
- session.lastActive = Date.now();
- session.activeOperations++;
-
- try {
- sshLogger.info("Docker container operation", {
- operation: "docker_container_op",
- sessionId,
- userId,
- hostId: session.hostId,
- containerId,
- action: "pause",
- });
- await executeDockerCommand(
- session,
- `docker pause ${containerId}`,
- sessionId,
- userId,
- session.hostId,
- );
-
- session.activeOperations--;
-
- res.json({
- success: true,
- message: "Container paused successfully",
- });
- } catch (error) {
- session.activeOperations--;
-
- const errorMsg = error instanceof Error ? error.message : "";
- if (errorMsg.includes("No such container")) {
- return res.status(404).json({
- success: false,
- error: "Container not found",
- code: "CONTAINER_NOT_FOUND",
- });
- }
-
- sshLogger.error("Failed to pause container", error, {
- operation: "pause_container",
- sessionId,
- containerId,
- userId,
- });
-
- res.status(500).json({
- success: false,
- error: errorMsg || "Failed to pause container",
- });
- }
- },
-);
-
-/**
- * @openapi
- * /docker/containers/{sessionId}/{containerId}/unpause:
- * post:
- * summary: Unpause container
- * description: Unpauses a specific container.
- * tags:
- * - Docker
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: path
- * name: containerId
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Container unpaused successfully.
- * 400:
- * description: SSH session not found or not connected.
- * 404:
- * description: Container not found.
- * 500:
- * description: Failed to unpause container.
- */
-app.post(
- "/docker/containers/:sessionId/:containerId/unpause",
- async (req, res) => {
- const { sessionId, containerId } = req.params;
- const userId = (req as unknown as { userId: string }).userId;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- });
- }
-
- session.lastActive = Date.now();
- session.activeOperations++;
-
- try {
- sshLogger.info("Docker container operation", {
- operation: "docker_container_op",
- sessionId,
- userId,
- hostId: session.hostId,
- containerId,
- action: "unpause",
- });
- await executeDockerCommand(
- session,
- `docker unpause ${containerId}`,
- sessionId,
- userId,
- session.hostId,
- );
-
- session.activeOperations--;
-
- res.json({
- success: true,
- message: "Container unpaused successfully",
- });
- } catch (error) {
- session.activeOperations--;
-
- const errorMsg = error instanceof Error ? error.message : "";
- if (errorMsg.includes("No such container")) {
- return res.status(404).json({
- success: false,
- error: "Container not found",
- code: "CONTAINER_NOT_FOUND",
- });
- }
-
- sshLogger.error("Failed to unpause container", error, {
- operation: "unpause_container",
- sessionId,
- containerId,
- userId,
- });
-
- res.status(500).json({
- success: false,
- error: errorMsg || "Failed to unpause container",
- });
- }
- },
-);
-
-/**
- * @openapi
- * /docker/containers/{sessionId}/{containerId}/remove:
- * delete:
- * summary: Remove container
- * description: Removes a specific container.
- * tags:
- * - Docker
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: path
- * name: containerId
- * required: true
- * schema:
- * type: string
- * - in: query
- * name: force
- * schema:
- * type: boolean
- * responses:
- * 200:
- * description: Container removed successfully.
- * 400:
- * description: SSH session not found or not connected, or cannot remove a running container.
- * 404:
- * description: Container not found.
- * 500:
- * description: Failed to remove container.
- */
-app.delete(
- "/docker/containers/:sessionId/:containerId/remove",
- async (req, res) => {
- const { sessionId, containerId } = req.params;
- const force = req.query.force === "true";
- const userId = (req as unknown as { userId: string }).userId;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- });
- }
-
- session.lastActive = Date.now();
- session.activeOperations++;
-
- try {
- sshLogger.info("Docker container operation", {
- operation: "docker_container_op",
- sessionId,
- userId,
- hostId: session.hostId,
- containerId,
- action: "remove",
- });
- const forceFlag = force ? "-f " : "";
- await executeDockerCommand(
- session,
- `docker rm ${forceFlag}${containerId}`,
- sessionId,
- userId,
- session.hostId,
- );
-
- session.activeOperations--;
-
- res.json({
- success: true,
- message: "Container removed successfully",
- });
- } catch (error) {
- session.activeOperations--;
-
- const errorMsg = error instanceof Error ? error.message : "";
- if (errorMsg.includes("No such container")) {
- return res.status(404).json({
- success: false,
- error: "Container not found",
- code: "CONTAINER_NOT_FOUND",
- });
- }
-
- if (errorMsg.includes("cannot remove a running container")) {
- return res.status(400).json({
- success: false,
- error:
- "Cannot remove a running container. Stop it first or use force.",
- code: "CONTAINER_RUNNING",
- });
- }
-
- sshLogger.error("Failed to remove container", error, {
- operation: "remove_container",
- sessionId,
- containerId,
- userId,
- });
-
- res.status(500).json({
- success: false,
- error: errorMsg || "Failed to remove container",
- });
- }
- },
-);
-
-/**
- * @openapi
- * /docker/containers/{sessionId}/{containerId}/logs:
- * get:
- * summary: Get container logs
- * description: Retrieves logs for a specific container.
- * tags:
- * - Docker
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: path
- * name: containerId
- * required: true
- * schema:
- * type: string
- * - in: query
- * name: tail
- * schema:
- * type: integer
- * - in: query
- * name: timestamps
- * schema:
- * type: boolean
- * - in: query
- * name: since
- * schema:
- * type: string
- * - in: query
- * name: until
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Container logs.
- * 400:
- * description: SSH session not found or not connected.
- * 404:
- * description: Container not found.
- * 500:
- * description: Failed to get container logs.
- */
-app.get("/docker/containers/:sessionId/:containerId/logs", async (req, res) => {
- const { sessionId, containerId } = req.params;
- const tail = req.query.tail ? parseInt(req.query.tail as string) : 100;
- const timestamps = req.query.timestamps === "true";
- const since = req.query.since as string;
- const until = req.query.until as string;
- const userId = (req as unknown as { userId: string }).userId;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- });
- }
-
- session.lastActive = Date.now();
- session.activeOperations++;
-
- try {
- let command = `docker logs ${containerId} 2>&1`;
-
- if (tail && tail > 0) {
- command += ` --tail ${Math.floor(tail)}`;
- }
-
- if (timestamps) {
- command += " --timestamps";
- }
-
- if (since && DOCKER_TIMESTAMP_RE.test(since)) {
- command += ` --since ${since}`;
- }
-
- if (until && DOCKER_TIMESTAMP_RE.test(until)) {
- command += ` --until ${until}`;
- }
-
- const logs = await executeDockerCommand(
- session,
- command,
- sessionId,
- userId,
- session.hostId,
- );
-
- session.activeOperations--;
-
- res.json({
- success: true,
- logs,
- });
- } catch (error) {
- session.activeOperations--;
-
- const errorMsg = error instanceof Error ? error.message : "";
- if (errorMsg.includes("No such container")) {
- return res.status(404).json({
- success: false,
- error: "Container not found",
- code: "CONTAINER_NOT_FOUND",
- });
- }
-
- sshLogger.error("Failed to get container logs", error, {
- operation: "get_logs",
- sessionId,
- containerId,
- userId,
- });
-
- res.status(500).json({
- success: false,
- error: errorMsg || "Failed to get container logs",
- });
- }
-});
-
-/**
- * @openapi
- * /docker/containers/{sessionId}/{containerId}/stats:
- * get:
- * summary: Get container stats
- * description: Retrieves stats for a specific container.
- * tags:
- * - Docker
- * parameters:
- * - in: path
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: path
- * name: containerId
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Container stats.
- * 400:
- * description: SSH session not found or not connected.
- * 404:
- * description: Container not found.
- * 500:
- * description: Failed to get container stats.
- */
-app.get(
- "/docker/containers/:sessionId/:containerId/stats",
- async (req, res) => {
- const { sessionId, containerId } = req.params;
- const userId = (req as unknown as { userId: string }).userId;
-
- if (!userId) {
- return res.status(401).json({ error: "Authentication required" });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- });
- }
-
- session.lastActive = Date.now();
- session.activeOperations++;
-
- try {
- const command = `docker stats ${containerId} --no-stream --format '{"cpu":"{{.CPUPerc}}","memory":"{{.MemUsage}}","memoryPercent":"{{.MemPerc}}","netIO":"{{.NetIO}}","blockIO":"{{.BlockIO}}","pids":"{{.PIDs}}"}'`;
-
- const output = await executeDockerCommand(
- session,
- command,
- sessionId,
- userId,
- session.hostId,
- );
- const rawStats = JSON.parse(output.trim());
-
- const memoryParts = rawStats.memory.split(" / ");
- const memoryUsed = memoryParts[0]?.trim() || "0B";
- const memoryLimit = memoryParts[1]?.trim() || "0B";
-
- const netIOParts = rawStats.netIO.split(" / ");
- const netInput = netIOParts[0]?.trim() || "0B";
- const netOutput = netIOParts[1]?.trim() || "0B";
-
- const blockIOParts = rawStats.blockIO.split(" / ");
- const blockRead = blockIOParts[0]?.trim() || "0B";
- const blockWrite = blockIOParts[1]?.trim() || "0B";
-
- const stats = {
- cpu: rawStats.cpu,
- memoryUsed,
- memoryLimit,
- memoryPercent: rawStats.memoryPercent,
- netInput,
- netOutput,
- blockRead,
- blockWrite,
- pids: rawStats.pids,
- };
-
- session.activeOperations--;
-
- res.json(stats);
- } catch (error) {
- session.activeOperations--;
-
- const errorMsg = error instanceof Error ? error.message : "";
- if (errorMsg.includes("No such container")) {
- return res.status(404).json({
- success: false,
- error: "Container not found",
- code: "CONTAINER_NOT_FOUND",
- });
- }
-
- sshLogger.error("Failed to get container stats", error, {
- operation: "get_stats",
- sessionId,
- containerId,
- userId,
- });
-
- res.status(500).json({
- success: false,
- error: errorMsg || "Failed to get container stats",
- });
- }
- },
-);
-
const PORT = 30007;
app.listen(PORT, async () => {
diff --git a/src/backend/ssh/file-manager-action-routes.ts b/src/backend/ssh/file-manager-action-routes.ts
new file mode 100644
index 000000000..18a610cb4
--- /dev/null
+++ b/src/backend/ssh/file-manager-action-routes.ts
@@ -0,0 +1,541 @@
+import type { Express } from "express";
+import type { AuthenticatedRequest } from "../../types/index.js";
+import { fileLogger } from "../utils/logger.js";
+import { execChannel, type SSHSession } from "./file-manager-session.js";
+
+type FileActionRoutesDeps = {
+ sshSessions: Record<string, SSHSession>;
+ scheduleSessionCleanup: (sessionId: string) => void;
+ verifySessionOwnership: (session: SSHSession, userId: string) => boolean;
+};
+
+export function registerFileActionRoutes(
+ app: Express,
+ {
+ sshSessions,
+ scheduleSessionCleanup,
+ verifySessionOwnership,
+ }: FileActionRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/copyItem:
+ * post:
+ * summary: Copy a file or directory
+ * description: Copies a file or directory on the remote host.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * sourcePath:
+ * type: string
+ * targetDir:
+ * type: string
+ * hostId:
+ * type: integer
+ * userId:
+ * type: string
+ * responses:
+ * 200:
+ * description: Item copied successfully.
+ * 400:
+ * description: Missing required parameters or SSH connection not established.
+ * 500:
+ * description: Failed to copy item.
+ */
+ app.post("/ssh/file_manager/ssh/copyItem", async (req, res) => {
+ const { sessionId, sourcePath, targetDir, hostId } = req.body;
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId || !sourcePath || !targetDir) {
+ return res.status(400).json({ error: "Missing required parameters" });
+ }
+
+ const sshConn = sshSessions[sessionId];
+ if (!sshConn || !sshConn.isConnected) {
+ return res
+ .status(400)
+ .json({ error: "SSH session not found or not connected" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ sshConn.lastActive = Date.now();
+ scheduleSessionCleanup(sessionId);
+
+ const sourceName = sourcePath.split("/").pop() || "copied_item";
+
+ const timestamp = Date.now().toString().slice(-8);
+ const uniqueName = `${sourceName}_copy_${timestamp}`;
+ const targetPath = `${targetDir}/${uniqueName}`;
+
+ const escapedSource = sourcePath.replace(/'/g, "'\"'\"'");
+ const escapedTarget = targetPath.replace(/'/g, "'\"'\"'");
+
+ const copyCommand = `cp '${escapedSource}' '${escapedTarget}' && echo "COPY_SUCCESS"`;
+
+ const commandTimeout = setTimeout(() => {
+ fileLogger.error("Copy command timed out after 60 seconds", {
+ sourcePath,
+ targetPath,
+ command: copyCommand,
+ });
+ if (!res.headersSent) {
+ res.status(500).json({
+ error: "Copy operation timed out",
+ toast: {
+ type: "error",
+ message:
+ "Copy operation timed out. SSH connection may be unstable.",
+ },
+ });
+ }
+ }, 60000);
+
+ execChannel(sshConn, copyCommand, (err, stream) => {
+ if (err) {
+ clearTimeout(commandTimeout);
+ fileLogger.error("SSH copyItem error:", err);
+ if (!res.headersSent) {
+ return res.status(500).json({ error: err.message });
+ }
+ return;
+ }
+
+ let errorData = "";
+ let stdoutData = "";
+
+ stream.on("data", (data: Buffer) => {
+ const output = data.toString();
+ stdoutData += output;
+ stream.stderr.on("data", (data: Buffer) => {
+ const output = data.toString();
+ errorData += output;
+ });
+
+ stream.on("close", (code) => {
+ clearTimeout(commandTimeout);
+
+ if (code !== 0) {
+ const fullErrorInfo =
+ errorData || stdoutData || "No error message available";
+ fileLogger.error(`SSH copyItem command failed with code ${code}`, {
+ operation: "file_copy_failed",
+ sessionId,
+ sourcePath,
+ targetPath,
+ command: copyCommand,
+ exitCode: code,
+ errorData,
+ stdoutData,
+ fullErrorInfo,
+ });
+ if (!res.headersSent) {
+ return res.status(500).json({
+ error: `Copy failed: ${fullErrorInfo}`,
+ toast: {
+ type: "error",
+ message: `Copy failed: ${fullErrorInfo}`,
+ },
+ debug: {
+ sourcePath,
+ targetPath,
+ exitCode: code,
+ command: copyCommand,
+ },
+ });
+ }
+ return;
+ }
+
+ const copySuccessful =
+ stdoutData.includes("COPY_SUCCESS") || code === 0;
+
+ if (copySuccessful) {
+ fileLogger.success("Item copied successfully", {
+ operation: "file_copy",
+ sessionId,
+ sourcePath,
+ targetPath,
+ uniqueName,
+ hostId,
+ userId,
+ });
+
+ if (!res.headersSent) {
+ res.json({
+ message: "Item copied successfully",
+ sourcePath,
+ targetPath,
+ uniqueName,
+ toast: {
+ type: "success",
+ message: `Successfully copied to: ${uniqueName}`,
+ },
+ });
+ }
+ } else {
+ fileLogger.warn("Copy completed but without success confirmation", {
+ operation: "file_copy_uncertain",
+ sessionId,
+ sourcePath,
+ targetPath,
+ code,
+ stdoutData: stdoutData.substring(0, 200),
+ });
+
+ if (!res.headersSent) {
+ res.json({
+ message: "Copy may have completed",
+ sourcePath,
+ targetPath,
+ uniqueName,
+ toast: {
+ type: "warning",
+ message: `Copy completed but verification uncertain for: ${uniqueName}`,
+ },
+ });
+ }
+ }
+ });
+
+ stream.on("error", (streamErr) => {
+ clearTimeout(commandTimeout);
+ fileLogger.error("SSH copyItem stream error:", streamErr);
+ if (!res.headersSent) {
+ res
+ .status(500)
+ .json({ error: `Stream error: ${streamErr.message}` });
+ }
+ });
+ });
+ });
+ });
+
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/executeFile:
+ * post:
+ * summary: Execute a file
+ * description: Executes a file on the remote host.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * filePath:
+ * type: string
+ * responses:
+ * 200:
+ * description: File execution result.
+ * 400:
+ * description: Missing required parameters or SSH connection not available.
+ * 500:
+ * description: Failed to execute file.
+ */
+ app.post("/ssh/file_manager/ssh/executeFile", async (req, res) => {
+ const { sessionId, filePath } = req.body;
+ const sshConn = sshSessions[sessionId];
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sshConn || !sshConn.isConnected) {
+ fileLogger.error(
+ "SSH connection not found or not connected for executeFile",
+ {
+ operation: "execute_file",
+ sessionId,
+ hasConnection: !!sshConn,
+ isConnected: sshConn?.isConnected,
+ },
+ );
+ return res.status(400).json({ error: "SSH connection not available" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!filePath) {
+ return res.status(400).json({ error: "File path is required" });
+ }
+
+ const escapedPath = filePath.replace(/'/g, "'\"'\"'");
+
+ const checkCommand = `test -x '${escapedPath}' && echo "EXECUTABLE" || echo "NOT_EXECUTABLE"`;
+
+ execChannel(sshConn, checkCommand, (checkErr, checkStream) => {
+ if (checkErr) {
+ fileLogger.error("SSH executeFile check error:", checkErr);
+ return res
+ .status(500)
+ .json({ error: "Failed to check file executability" });
+ }
+
+ let checkResult = "";
+ checkStream.on("data", (data) => {
+ checkResult += data.toString();
+ });
+
+ checkStream.on("close", () => {
+ if (!checkResult.includes("EXECUTABLE")) {
+ return res.status(400).json({ error: "File is not executable" });
+ }
+
+ const executeCommand = `cd "$(dirname '${escapedPath}')" && '${escapedPath}' 2>&1; echo "EXIT_CODE:$?"`;
+
+ execChannel(sshConn, executeCommand, (err, stream) => {
+ if (err) {
+ fileLogger.error("SSH executeFile error:", err);
+ return res.status(500).json({ error: "Failed to execute file" });
+ }
+
+ let output = "";
+ let errorOutput = "";
+
+ stream.on("data", (data) => {
+ output += data.toString();
+ });
+
+ stream.stderr.on("data", (data) => {
+ errorOutput += data.toString();
+ });
+
+ stream.on("close", (code) => {
+ const exitCodeMatch = output.match(/EXIT_CODE:(\d+)$/);
+ const actualExitCode = exitCodeMatch
+ ? parseInt(exitCodeMatch[1])
+ : code;
+ const cleanOutput = output.replace(/EXIT_CODE:\d+$/, "").trim();
+
+ fileLogger.info("File execution completed", {
+ operation: "execute_file",
+ sessionId,
+ filePath,
+ exitCode: actualExitCode,
+ outputLength: cleanOutput.length,
+ errorLength: errorOutput.length,
+ });
+
+ res.json({
+ success: true,
+ exitCode: actualExitCode,
+ output: cleanOutput,
+ error: errorOutput,
+ timestamp: new Date().toISOString(),
+ });
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.error("SSH executeFile stream error:", streamErr);
+ if (!res.headersSent) {
+ res.status(500).json({ error: "Execution stream error" });
+ }
+ });
+ });
+ });
+ });
+ });
+
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/changePermissions:
+ * post:
+ * summary: Change file permissions
+ * description: Changes the permissions of a file on the remote host.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * path:
+ * type: string
+ * permissions:
+ * type: string
+ * responses:
+ * 200:
+ * description: Permissions changed successfully.
+ * 400:
+ * description: Missing required parameters or SSH connection not available.
+ * 408:
+ * description: Permission change timed out.
+ * 500:
+ * description: Failed to change permissions.
+ */
+ app.post("/ssh/file_manager/ssh/changePermissions", async (req, res) => {
+ const { sessionId, path, permissions } = req.body;
+ const sshConn = sshSessions[sessionId];
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sshConn || !sshConn.isConnected) {
+ fileLogger.error(
+ "SSH connection not found or not connected for changePermissions",
+ {
+ operation: "change_permissions",
+ sessionId,
+ hasConnection: !!sshConn,
+ isConnected: sshConn?.isConnected,
+ },
+ );
+ return res.status(400).json({ error: "SSH connection not available" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!path) {
+ return res.status(400).json({ error: "File path is required" });
+ }
+
+ if (!permissions || !/^\d{3,4}$/.test(permissions)) {
+ return res.status(400).json({
+ error: "Valid permissions required (e.g., 755, 644)",
+ });
+ }
+
+ sshConn.lastActive = Date.now();
+ scheduleSessionCleanup(sessionId);
+
+ const octalPerms = permissions.slice(-3);
+ const escapedPath = path.replace(/'/g, "'\"'\"'");
+ const command = `chmod ${octalPerms} '${escapedPath}' && echo "SUCCESS"`;
+
+ fileLogger.info("Changing file permissions", {
+ operation: "change_permissions",
+ sessionId,
+ path,
+ permissions: octalPerms,
+ });
+
+ const commandTimeout = setTimeout(() => {
+ if (!res.headersSent) {
+ fileLogger.error("changePermissions command timeout", {
+ operation: "change_permissions",
+ sessionId,
+ path,
+ permissions: octalPerms,
+ });
+ res.status(408).json({
+ error: "Permission change timed out. SSH connection may be unstable.",
+ });
+ }
+ }, 10000);
+
+ execChannel(sshConn, command, (err, stream) => {
+ if (err) {
+ clearTimeout(commandTimeout);
+ fileLogger.error("SSH changePermissions exec error:", err, {
+ operation: "change_permissions",
+ sessionId,
+ path,
+ permissions: octalPerms,
+ });
+ if (!res.headersSent) {
+ return res
+ .status(500)
+ .json({ error: "Failed to change permissions" });
+ }
+ return;
+ }
+
+ let outputData = "";
+ let errorOutput = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ outputData += chunk.toString();
+ });
+
+ stream.stderr.on("data", (data: Buffer) => {
+ errorOutput += data.toString();
+ });
+
+ stream.on("close", (code) => {
+ clearTimeout(commandTimeout);
+
+ if (outputData.includes("SUCCESS")) {
+ fileLogger.success("File permissions changed successfully", {
+ operation: "change_permissions",
+ sessionId,
+ path,
+ permissions: octalPerms,
+ });
+
+ if (!res.headersSent) {
+ res.json({
+ success: true,
+ message: "Permissions changed successfully",
+ });
+ }
+ return;
+ }
+
+ if (code !== 0) {
+ fileLogger.error("chmod command failed", {
+ operation: "change_permissions",
+ sessionId,
+ path,
+ permissions: octalPerms,
+ exitCode: code,
+ error: errorOutput,
+ });
+ if (!res.headersSent) {
+ return res.status(500).json({
+ error: errorOutput || "Failed to change permissions",
+ });
+ }
+ return;
+ }
+
+ fileLogger.success("File permissions changed successfully", {
+ operation: "change_permissions",
+ sessionId,
+ path,
+ permissions: octalPerms,
+ });
+
+ if (!res.headersSent) {
+ res.json({
+ success: true,
+ message: "Permissions changed successfully",
+ });
+ }
+ });
+
+ stream.on("error", (streamErr) => {
+ clearTimeout(commandTimeout);
+ fileLogger.error("SSH changePermissions stream error:", streamErr, {
+ operation: "change_permissions",
+ sessionId,
+ path,
+ permissions: octalPerms,
+ });
+ if (!res.headersSent) {
+ res
+ .status(500)
+ .json({ error: "Stream error while changing permissions" });
+ }
+ });
+ });
+ });
+}
diff --git a/src/backend/ssh/file-manager-content-routes.ts b/src/backend/ssh/file-manager-content-routes.ts
new file mode 100644
index 000000000..0c18f877e
--- /dev/null
+++ b/src/backend/ssh/file-manager-content-routes.ts
@@ -0,0 +1,1305 @@
+import type { Express } from "express";
+import type { AuthenticatedRequest } from "../../types/index.js";
+import { fileLogger } from "../utils/logger.js";
+import {
+ execChannel,
+ execWithSudo,
+ execWithSudoBuffer,
+ getSessionSftp,
+ type SSHSession,
+} from "./file-manager-session.js";
+import { detectBinary } from "./file-manager-utils.js";
+
+type FileContentRoutesDeps = {
+ sshSessions: Record<string, SSHSession>;
+ verifySessionOwnership: (session: SSHSession, userId: string) => boolean;
+};
+
+export function registerFileContentRoutes(
+ app: Express,
+ { sshSessions, verifySessionOwnership }: FileContentRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/identifySymlink:
+ * get:
+ * summary: Identify symbolic link
+ * description: Identifies the target of a symbolic link.
+ * tags:
+ * - File Manager
+ * parameters:
+ * - in: query
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: query
+ * name: path
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: Symbolic link information.
+ * 400:
+ * description: Missing required parameters or SSH connection not established.
+ * 500:
+ * description: Failed to identify symbolic link.
+ */
+ app.get("/ssh/file_manager/ssh/identifySymlink", (req, res) => {
+ const sessionId = req.query.sessionId as string;
+ const sshConn = sshSessions[sessionId];
+ const linkPath = decodeURIComponent(req.query.path as string);
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!linkPath) {
+ return res.status(400).json({ error: "Link path is required" });
+ }
+
+ sshConn.lastActive = Date.now();
+
+ const escapedPath = linkPath.replace(/'/g, "'\"'\"'");
+ const command = `stat -L -c "%F" '${escapedPath}' && readlink -f '${escapedPath}'`;
+
+ execChannel(sshConn, command, (err, stream) => {
+ if (err) {
+ fileLogger.error("SSH identifySymlink error:", err);
+ return res.status(500).json({ error: err.message });
+ }
+
+ let data = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ data += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+ });
+
+ stream.on("close", (code) => {
+ if (code !== 0) {
+ fileLogger.error(
+ `SSH identifySymlink command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
+ );
+ return res
+ .status(500)
+ .json({ error: `Command failed: ${errorData}` });
+ }
+
+ const [fileType, target] = data.trim().split("\n");
+
+ res.json({
+ path: linkPath,
+ target: target,
+ type: fileType.toLowerCase().includes("directory")
+ ? "directory"
+ : "file",
+ });
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.error("SSH identifySymlink stream error:", streamErr);
+ if (!res.headersSent) {
+ res.status(500).json({ error: `Stream error: ${streamErr.message}` });
+ }
+ });
+ });
+ });
+
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/resolvePath:
+ * get:
+ * summary: Resolve a path with environment variables
+ * description: Expands environment variables and ~ in a path via the SSH session.
+ * tags:
+ * - File Manager
+ * parameters:
+ * - in: query
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: query
+ * name: path
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: The resolved absolute path.
+ * 400:
+ * description: Missing required parameters.
+ * 500:
+ * description: Failed to resolve path.
+ */
+ app.get("/ssh/file_manager/ssh/resolvePath", (req, res) => {
+ const sessionId = req.query.sessionId as string;
+ const sshConn = sshSessions[sessionId];
+ const rawPath = decodeURIComponent(req.query.path as string);
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!rawPath) {
+ return res.status(400).json({ error: "Path is required" });
+ }
+
+ sshConn.lastActive = Date.now();
+
+ let command: string;
+ if (rawPath.startsWith("~")) {
+ const rest = rawPath.substring(1).replace(/'/g, "'\"'\"'");
+ command = `echo ~'${rest}'`;
+ } else {
+ const escapedPath = rawPath.replace(/'/g, "'\"'\"'");
+ command = `echo '${escapedPath}'`;
+ }
+
+ execChannel(sshConn, command, (err, stream) => {
+ if (err) {
+ fileLogger.error("SSH resolvePath error:", err);
+ return res.status(500).json({ error: err.message });
+ }
+
+ let data = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ data += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+ });
+
+ stream.on("close", (code) => {
+ if (code !== 0) {
+ fileLogger.error(
+ `SSH resolvePath command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
+ );
+ return res.json({ resolvedPath: rawPath });
+ }
+
+ const resolved = data.trim();
+ res.json({ resolvedPath: resolved || rawPath });
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.error("SSH resolvePath stream error:", streamErr);
+ if (!res.headersSent) {
+ res.json({ resolvedPath: rawPath });
+ }
+ });
+ });
+ });
+
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/readFile:
+ * get:
+ * summary: Read a file
+ * description: Reads the content of a file from the remote host.
+ * tags:
+ * - File Manager
+ * parameters:
+ * - in: query
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: query
+ * name: path
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: The content of the file.
+ * 400:
+ * description: Missing required parameters or file too large.
+ * 404:
+ * description: File not found.
+ * 500:
+ * description: Failed to read file.
+ */
+ app.get("/ssh/file_manager/ssh/readFile", (req, res) => {
+ const sessionId = req.query.sessionId as string;
+ const sshConn = sshSessions[sessionId];
+ const filePath = decodeURIComponent(req.query.path as string);
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!filePath) {
+ return res.status(400).json({ error: "File path is required" });
+ }
+
+ fileLogger.info("Reading file", {
+ operation: "file_read",
+ sessionId,
+ userId,
+ path: filePath,
+ });
+ sshConn.lastActive = Date.now();
+
+ const MAX_READ_SIZE = 500 * 1024 * 1024;
+ const escapedPath = filePath.replace(/'/g, "'\"'\"'");
+
+ execChannel(
+ sshConn,
+ `stat -c%s '${escapedPath}' 2>/dev/null || wc -c < '${escapedPath}'`,
+ (sizeErr, sizeStream) => {
+ if (sizeErr) {
+ fileLogger.error("SSH file size check error:", sizeErr);
+ return res.status(500).json({ error: sizeErr.message });
+ }
+
+ let sizeData = "";
+ let sizeErrorData = "";
+
+ sizeStream.on("data", (chunk: Buffer) => {
+ sizeData += chunk.toString();
+ });
+
+ sizeStream.stderr.on("data", (chunk: Buffer) => {
+ sizeErrorData += chunk.toString();
+ });
+
+ sizeStream.on("close", (sizeCode) => {
+ if (sizeCode !== 0) {
+ const errorLower = sizeErrorData.toLowerCase();
+ const isFileNotFound =
+ errorLower.includes("no such file or directory") ||
+ errorLower.includes("cannot access") ||
+ errorLower.includes("not found") ||
+ errorLower.includes("resource not found");
+
+ fileLogger.error(`File size check failed: ${sizeErrorData}`);
+ return res.status(isFileNotFound ? 404 : 500).json({
+ error: `Cannot check file size: ${sizeErrorData}`,
+ fileNotFound: isFileNotFound,
+ });
+ }
+
+ const fileSize = parseInt(sizeData.trim(), 10);
+
+ if (isNaN(fileSize)) {
+ fileLogger.error("Invalid file size response:", sizeData);
+ return res
+ .status(500)
+ .json({ error: "Cannot determine file size" });
+ }
+
+ if (fileSize > MAX_READ_SIZE) {
+ fileLogger.warn("File too large for reading", {
+ operation: "file_read",
+ sessionId,
+ filePath,
+ fileSize,
+ maxSize: MAX_READ_SIZE,
+ });
+ return res.status(400).json({
+ error: `File too large to open in editor. Maximum size is ${MAX_READ_SIZE / 1024 / 1024}MB, file is ${(fileSize / 1024 / 1024).toFixed(2)}MB. Use download instead.`,
+ fileSize,
+ maxSize: MAX_READ_SIZE,
+ tooLarge: true,
+ });
+ }
+
+ execChannel(sshConn, `cat '${escapedPath}'`, (err, stream) => {
+ if (err) {
+ fileLogger.error("SSH readFile error:", err);
+ return res.status(500).json({ error: err.message });
+ }
+
+ let binaryData = Buffer.alloc(0);
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ binaryData = Buffer.concat([binaryData, chunk]);
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+ });
+
+ stream.on("close", (code) => {
+ if (code !== 0) {
+ const isPermissionDenied = errorData
+ .toLowerCase()
+ .includes("permission denied");
+
+ if (isPermissionDenied && sshConn.sudoPassword) {
+ execWithSudoBuffer(
+ sshConn,
+ `cat '${escapedPath}'`,
+ sshConn.sudoPassword,
+ )
+ .then((result) => {
+ if (result.code !== 0) {
+ return res.status(403).json({
+ error: `Permission denied: ${result.stderr || result.stdout.toString("utf8")}`,
+ needsSudo: true,
+ });
+ }
+
+ const sudoData = result.stdout;
+ const isBinary = detectBinary(sudoData);
+ res.json({
+ content: isBinary
+ ? sudoData.toString("base64")
+ : sudoData.toString("utf8"),
+ isBinary,
+ size: sudoData.length,
+ });
+ })
+ .catch(() => {
+ res
+ .status(403)
+ .json({ error: "Permission denied", needsSudo: true });
+ });
+ return;
+ }
+
+ fileLogger.error(
+ `SSH readFile command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
+ );
+
+ const isFileNotFound =
+ errorData.includes("No such file or directory") ||
+ errorData.includes("cannot access") ||
+ errorData.includes("not found");
+
+ return res.status(isFileNotFound ? 404 : 500).json({
+ error: `Command failed: ${errorData}`,
+ fileNotFound: isFileNotFound,
+ });
+ }
+
+ const isBinary = detectBinary(binaryData);
+ fileLogger.success("File read successfully", {
+ operation: "file_read_success",
+ sessionId,
+ userId,
+ path: filePath,
+ bytes: binaryData.length,
+ });
+
+ if (isBinary) {
+ const base64Content = binaryData.toString("base64");
+ res.json({
+ content: base64Content,
+ path: filePath,
+ encoding: "base64",
+ });
+ } else {
+ const textContent = binaryData.toString("utf8");
+ res.json({
+ content: textContent,
+ path: filePath,
+ encoding: "utf8",
+ });
+ }
+ });
+ });
+ });
+ },
+ );
+ });
+
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/writeFile:
+ * post:
+ * summary: Write to a file
+ * description: Writes content to a file on the remote host and preserves the existing permissions when the file already exists.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * path:
+ * type: string
+ * content:
+ * type: string
+ * responses:
+ * 200:
+ * description: File written successfully.
+ * 400:
+ * description: Missing required parameters or SSH connection not established.
+ * 500:
+ * description: Failed to write file.
+ */
+ app.post("/ssh/file_manager/ssh/writeFile", async (req, res) => {
+ const { sessionId, path: filePath, content } = req.body;
+ const sshConn = sshSessions[sessionId];
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!filePath) {
+ return res.status(400).json({ error: "File path is required" });
+ }
+
+ if (content === undefined) {
+ return res.status(400).json({ error: "File content is required" });
+ }
+
+ const contentLength =
+ typeof content === "string" ? content.length : Buffer.byteLength(content);
+ fileLogger.info("Writing file", {
+ operation: "file_write",
+ sessionId,
+ userId,
+ path: filePath,
+ bytes: contentLength,
+ });
+ sshConn.lastActive = Date.now();
+
+ let preservedMode: number | undefined;
+
+ const restoreOriginalMode = (
+ sftp: import("ssh2").SFTPWrapper | null,
+ onComplete: () => void,
+ ) => {
+ if (preservedMode === undefined) {
+ onComplete();
+ return;
+ }
+
+ const permissions = preservedMode.toString(8);
+
+ if (sftp) {
+ sftp.chmod(filePath, preservedMode, (chmodErr) => {
+ if (chmodErr) {
+ fileLogger.warn("Failed to restore file permissions after save", {
+ operation: "file_write_restore_permissions",
+ sessionId,
+ userId,
+ path: filePath,
+ permissions,
+ error: chmodErr.message,
+ });
+ } else {
+ fileLogger.info("Restored file permissions after save", {
+ operation: "file_write_restore_permissions",
+ sessionId,
+ userId,
+ path: filePath,
+ permissions,
+ });
+ }
+
+ onComplete();
+ });
+ return;
+ }
+
+ const escapedPath = filePath.replace(/'/g, "'\"'\"'");
+ const chmodCommand = `chmod ${permissions} '${escapedPath}' && echo "SUCCESS"`;
+
+ execChannel(sshConn, chmodCommand, (err, stream) => {
+ if (err) {
+ fileLogger.warn("Failed to restore file permissions after save", {
+ operation: "file_write_restore_permissions",
+ sessionId,
+ userId,
+ path: filePath,
+ permissions,
+ error: err.message,
+ });
+ onComplete();
+ return;
+ }
+
+ let outputData = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ outputData += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+ });
+
+ stream.on("close", (code) => {
+ if (outputData.includes("SUCCESS")) {
+ fileLogger.info("Restored file permissions after save", {
+ operation: "file_write_restore_permissions",
+ sessionId,
+ userId,
+ path: filePath,
+ permissions,
+ });
+ } else {
+ fileLogger.warn("Failed to restore file permissions after save", {
+ operation: "file_write_restore_permissions",
+ sessionId,
+ userId,
+ path: filePath,
+ permissions,
+ exitCode: code,
+ error:
+ errorData ||
+ "Permission restore command did not report success",
+ });
+ }
+
+ onComplete();
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.warn("Failed to restore file permissions after save", {
+ operation: "file_write_restore_permissions",
+ sessionId,
+ userId,
+ path: filePath,
+ permissions,
+ error: streamErr.message,
+ });
+ onComplete();
+ });
+ });
+ };
+
+ const trySFTP = () => {
+ try {
+ fileLogger.info("Opening SFTP channel", {
+ operation: "file_sftp_open",
+ sessionId,
+ userId,
+ path: filePath,
+ });
+ getSessionSftp(sshConn)
+ .then((sftp) => {
+ let fileBuffer;
+ try {
+ if (typeof content === "string") {
+ try {
+ const testBuffer = Buffer.from(content, "base64");
+ if (testBuffer.toString("base64") === content) {
+ fileBuffer = testBuffer;
+ } else {
+ fileBuffer = Buffer.from(content, "utf8");
+ }
+ } catch {
+ fileBuffer = Buffer.from(content, "utf8");
+ }
+ } else if (Buffer.isBuffer(content)) {
+ fileBuffer = content;
+ } else {
+ fileBuffer = Buffer.from(content);
+ }
+ } catch (bufferErr) {
+ fileLogger.error("Buffer conversion error:", bufferErr);
+ if (!res.headersSent) {
+ return res
+ .status(500)
+ .json({ error: "Invalid file content format" });
+ }
+ return;
+ }
+
+ sftp.stat(filePath, (statErr, stats) => {
+ try {
+ if (statErr) {
+ fileLogger.warn(
+ "Failed to read existing file permissions before save",
+ {
+ operation: "file_write_stat",
+ sessionId,
+ userId,
+ path: filePath,
+ error: statErr.message,
+ },
+ );
+ } else if (stats.isFile()) {
+ preservedMode = stats.mode & 0o7777;
+ }
+
+ const writeStream = sftp.createWriteStream(filePath);
+
+ let hasError = false;
+ let hasFinished = false;
+ let isFinalizing = false;
+
+ const finalizeSuccess = () => {
+ if (hasError || hasFinished) return;
+ hasFinished = true;
+ isFinalizing = false;
+ fileLogger.success("File written successfully", {
+ operation: "file_write_success",
+ sessionId,
+ userId,
+ path: filePath,
+ bytes: fileBuffer.length,
+ });
+ if (!res.headersSent) {
+ res.json({
+ message: "File written successfully",
+ path: filePath,
+ toast: {
+ type: "success",
+ message: `File written: ${filePath}`,
+ },
+ });
+ }
+ };
+
+ writeStream.on("error", (streamErr) => {
+ if (hasError || hasFinished || isFinalizing) return;
+ hasError = true;
+ isFinalizing = false;
+ fileLogger.warn(
+ `SFTP write failed, trying fallback method: ${streamErr.message}`,
+ );
+ tryFallbackMethod();
+ });
+
+ const finishWrite = () => {
+ if (hasError || hasFinished || isFinalizing) return;
+ isFinalizing = true;
+ restoreOriginalMode(sftp, finalizeSuccess);
+ };
+
+ writeStream.on("finish", () => {
+ finishWrite();
+ });
+
+ writeStream.on("close", () => {
+ finishWrite();
+ });
+
+ try {
+ writeStream.write(fileBuffer);
+ writeStream.end();
+ } catch (writeErr) {
+ if (hasError || hasFinished) return;
+ hasError = true;
+ isFinalizing = false;
+ fileLogger.warn(
+ `SFTP write operation failed, trying fallback method: ${(writeErr as Error).message}`,
+ );
+ tryFallbackMethod();
+ }
+ } catch (callbackErr) {
+ fileLogger.warn(
+ `SFTP stat callback error, trying fallback method: ${(callbackErr as Error).message}`,
+ );
+ tryFallbackMethod();
+ }
+ });
+ })
+ .catch((err: Error) => {
+ fileLogger.warn(
+ `SFTP failed, trying fallback method: ${err.message}`,
+ );
+ tryFallbackMethod();
+ });
+ } catch (sftpErr) {
+ fileLogger.warn(
+ `SFTP connection error, trying fallback method: ${(sftpErr as Error).message}`,
+ );
+ tryFallbackMethod();
+ }
+ };
+
+ const tryFallbackMethod = () => {
+ if (!sshConn?.isConnected) {
+ if (!res.headersSent) {
+ return res.status(500).json({ error: "SSH session disconnected" });
+ }
+ return;
+ }
+ try {
+ let contentBuffer: Buffer;
+ if (typeof content === "string") {
+ try {
+ contentBuffer = Buffer.from(content, "base64");
+ if (contentBuffer.toString("base64") !== content) {
+ contentBuffer = Buffer.from(content, "utf8");
+ }
+ } catch {
+ contentBuffer = Buffer.from(content, "utf8");
+ }
+ } else if (Buffer.isBuffer(content)) {
+ contentBuffer = content;
+ } else {
+ contentBuffer = Buffer.from(content);
+ }
+ const base64Content = contentBuffer.toString("base64");
+ const escapedPath = filePath.replace(/'/g, "'\"'\"'");
+
+ const writeCommand = `echo '${base64Content}' | base64 -d > '${escapedPath}' && echo "SUCCESS"`;
+
+ execChannel(sshConn, writeCommand, (err, stream) => {
+ if (err) {
+ fileLogger.error("Fallback write command failed:", err);
+ if (!res.headersSent) {
+ return res.status(500).json({
+ error: `Write failed: ${err.message}`,
+ toast: {
+ type: "error",
+ message: `Write failed: ${err.message}`,
+ },
+ });
+ }
+ return;
+ }
+
+ let outputData = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ outputData += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+ });
+
+ stream.stderr.on("error", (stderrErr) => {
+ fileLogger.error("Fallback write stderr error:", stderrErr);
+ });
+
+ stream.on("close", (code) => {
+ if (outputData.includes("SUCCESS")) {
+ restoreOriginalMode(null, () => {
+ if (!res.headersSent) {
+ res.json({
+ message: "File written successfully",
+ path: filePath,
+ toast: {
+ type: "success",
+ message: `File written: ${filePath}`,
+ },
+ });
+ }
+ });
+ } else {
+ const isPermDenied = errorData
+ .toLowerCase()
+ .includes("permission denied");
+ if (isPermDenied && sshConn.sudoPassword) {
+ execWithSudo(
+ sshConn,
+ `bash -c "echo '${base64Content}' | base64 -d > '${escapedPath}' && echo SUCCESS"`,
+ sshConn.sudoPassword,
+ )
+ .then(({ stdout, code: sudoCode }) => {
+ if (sudoCode === 0 && stdout.includes("SUCCESS")) {
+ restoreOriginalMode(null, () => {
+ if (!res.headersSent) {
+ res.json({
+ message: "File written successfully",
+ path: filePath,
+ });
+ }
+ });
+ } else if (!res.headersSent) {
+ res
+ .status(403)
+ .json({ error: "Permission denied", needsSudo: true });
+ }
+ })
+ .catch(() => {
+ if (!res.headersSent) {
+ res
+ .status(403)
+ .json({ error: "Permission denied", needsSudo: true });
+ }
+ });
+ return;
+ }
+ fileLogger.error(
+ `Fallback write failed with code ${code}: ${errorData}`,
+ );
+ if (!res.headersSent) {
+ res.status(500).json({
+ error: `Write failed: ${errorData}`,
+ needsSudo: isPermDenied,
+ toast: {
+ type: "error",
+ message: `Write failed: ${errorData}`,
+ },
+ });
+ }
+ }
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.error("Fallback write stream error:", streamErr);
+ if (!res.headersSent) {
+ res
+ .status(500)
+ .json({ error: `Write stream error: ${streamErr.message}` });
+ }
+ });
+ });
+ } catch (fallbackErr) {
+ fileLogger.error("Fallback method failed:", fallbackErr);
+ if (!res.headersSent) {
+ res.status(500).json({
+ error: `All write methods failed: ${(fallbackErr as Error).message}`,
+ });
+ }
+ }
+ };
+
+ trySFTP();
+ });
+
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/uploadFile:
+ * post:
+ * summary: Upload a file
+ * description: Uploads a file to the remote host.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * path:
+ * type: string
+ * content:
+ * type: string
+ * fileName:
+ * type: string
+ * responses:
+ * 200:
+ * description: File uploaded successfully.
+ * 400:
+ * description: Missing required parameters or SSH connection not established.
+ * 500:
+ * description: Failed to upload file.
+ */
+ app.post("/ssh/file_manager/ssh/uploadFile", async (req, res) => {
+ const { sessionId, path: filePath, content, fileName } = req.body;
+ const sshConn = sshSessions[sessionId];
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!filePath || !fileName || content === undefined) {
+ return res
+ .status(400)
+ .json({ error: "File path, name, and content are required" });
+ }
+
+ sshConn.lastActive = Date.now();
+
+ const contentSize =
+ typeof content === "string"
+ ? Buffer.byteLength(content, "utf8")
+ : content.length;
+
+ const fullPath = filePath.endsWith("/")
+ ? filePath + fileName
+ : filePath + "/" + fileName;
+ const uploadStartTime = Date.now();
+ fileLogger.info("File upload started", {
+ operation: "file_upload_start",
+ sessionId,
+ userId,
+ path: fullPath,
+ bytes: contentSize,
+ });
+
+ const trySFTP = () => {
+ try {
+ fileLogger.info("Opening SFTP channel", {
+ operation: "file_sftp_open",
+ sessionId,
+ userId,
+ path: fullPath,
+ });
+ getSessionSftp(sshConn)
+ .then((sftp) => {
+ let fileBuffer;
+ try {
+ if (typeof content === "string") {
+ fileBuffer = Buffer.from(content, "base64");
+ } else if (Buffer.isBuffer(content)) {
+ fileBuffer = content;
+ } else {
+ fileBuffer = Buffer.from(content);
+ }
+ } catch (bufferErr) {
+ fileLogger.error("Buffer conversion error:", bufferErr);
+ if (!res.headersSent) {
+ return res
+ .status(500)
+ .json({ error: "Invalid file content format" });
+ }
+ return;
+ }
+
+ const writeStream = sftp.createWriteStream(fullPath);
+
+ let hasError = false;
+ let hasFinished = false;
+
+ writeStream.on("error", (streamErr) => {
+ if (hasError || hasFinished) return;
+ hasError = true;
+ fileLogger.warn(
+ `SFTP write failed, trying fallback method: ${streamErr.message}`,
+ {
+ operation: "file_upload",
+ sessionId,
+ fileName,
+ fileSize: contentSize,
+ error: streamErr.message,
+ },
+ );
+ tryFallbackMethod();
+ });
+
+ writeStream.on("finish", () => {
+ if (hasError || hasFinished) return;
+ hasFinished = true;
+ fileLogger.success("File upload completed", {
+ operation: "file_upload_complete",
+ sessionId,
+ userId,
+ path: fullPath,
+ bytes: fileBuffer.length,
+ duration: Date.now() - uploadStartTime,
+ });
+ if (!res.headersSent) {
+ res.json({
+ message: "File uploaded successfully",
+ path: fullPath,
+ toast: {
+ type: "success",
+ message: `File uploaded: ${fullPath}`,
+ },
+ });
+ }
+ });
+
+ writeStream.on("close", () => {
+ if (hasError || hasFinished) return;
+ hasFinished = true;
+ fileLogger.success("File upload completed", {
+ operation: "file_upload_complete",
+ sessionId,
+ userId,
+ path: fullPath,
+ bytes: fileBuffer.length,
+ duration: Date.now() - uploadStartTime,
+ });
+ if (!res.headersSent) {
+ res.json({
+ message: "File uploaded successfully",
+ path: fullPath,
+ toast: {
+ type: "success",
+ message: `File uploaded: ${fullPath}`,
+ },
+ });
+ }
+ });
+
+ try {
+ writeStream.write(fileBuffer);
+ writeStream.end();
+ } catch (writeErr) {
+ if (hasError || hasFinished) return;
+ hasError = true;
+ fileLogger.warn(
+ `SFTP write operation failed, trying fallback method: ${(writeErr as Error).message}`,
+ );
+ tryFallbackMethod();
+ }
+ })
+ .catch((err: Error) => {
+ fileLogger.warn(
+ `SFTP failed, trying fallback method: ${err.message}`,
+ );
+ tryFallbackMethod();
+ });
+ } catch (sftpErr) {
+ fileLogger.warn(
+ `SFTP connection error, trying fallback method: ${(sftpErr as Error).message}`,
+ );
+ tryFallbackMethod();
+ }
+ };
+
+ const tryFallbackMethod = () => {
+ if (!sshConn?.isConnected) {
+ if (!res.headersSent) {
+ return res.status(500).json({ error: "SSH session disconnected" });
+ }
+ return;
+ }
+ try {
+ let contentBuffer: Buffer;
+ if (typeof content === "string") {
+ try {
+ contentBuffer = Buffer.from(content, "base64");
+ if (contentBuffer.toString("base64") !== content) {
+ contentBuffer = Buffer.from(content, "utf8");
+ }
+ } catch {
+ contentBuffer = Buffer.from(content, "utf8");
+ }
+ } else if (Buffer.isBuffer(content)) {
+ contentBuffer = content;
+ } else {
+ contentBuffer = Buffer.from(content);
+ }
+ const base64Content = contentBuffer.toString("base64");
+ const chunkSize = 1000000;
+ const chunks = [];
+
+ for (let i = 0; i < base64Content.length; i += chunkSize) {
+ chunks.push(base64Content.slice(i, i + chunkSize));
+ }
+
+ if (!sshConn?.isConnected) {
+ fileLogger.error("SSH connection lost before fallback upload", {
+ operation: "file_upload_fallback",
+ sessionId,
+ path: fullPath,
+ });
+ if (!res.headersSent) {
+ return res
+ .status(500)
+ .json({ error: "SSH connection lost during upload" });
+ }
+ return;
+ }
+
+ if (chunks.length === 1) {
+ const escapedPath = fullPath.replace(/'/g, "'\"'\"'");
+
+ const writeCommand = `echo '${chunks[0]}' | base64 -d > '${escapedPath}' && echo "SUCCESS"`;
+
+ execChannel(sshConn, writeCommand, (err, stream) => {
+ if (err) {
+ fileLogger.error("Fallback upload command failed:", err);
+ if (!res.headersSent) {
+ return res
+ .status(500)
+ .json({ error: `Upload failed: ${err.message}` });
+ }
+ return;
+ }
+
+ let outputData = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ outputData += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+ });
+
+ stream.stderr.on("error", (stderrErr) => {
+ fileLogger.error("Fallback upload stderr error:", stderrErr);
+ });
+
+ stream.on("close", (code) => {
+ if (outputData.includes("SUCCESS")) {
+ if (!res.headersSent) {
+ res.json({
+ message: "File uploaded successfully",
+ path: fullPath,
+ toast: {
+ type: "success",
+ message: `File uploaded: ${fullPath}`,
+ },
+ });
+ }
+ } else {
+ fileLogger.error(
+ `Fallback upload failed with code ${code}: ${errorData}`,
+ );
+ if (!res.headersSent) {
+ res.status(500).json({
+ error: `Upload failed: ${errorData}`,
+ toast: {
+ type: "error",
+ message: `Upload failed: ${errorData}`,
+ },
+ });
+ }
+ }
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.error("Fallback upload stream error:", streamErr);
+ if (!res.headersSent) {
+ res
+ .status(500)
+ .json({ error: `Upload stream error: ${streamErr.message}` });
+ }
+ });
+ });
+ } else {
+ const escapedPath = fullPath.replace(/'/g, "'\"'\"'");
+
+ let writeCommand = `> '${escapedPath}'`;
+
+ chunks.forEach((chunk) => {
+ writeCommand += ` && echo '${chunk}' | base64 -d >> '${escapedPath}'`;
+ });
+
+ writeCommand += ` && echo "SUCCESS"`;
+
+ execChannel(sshConn, writeCommand, (err, stream) => {
+ if (err) {
+ fileLogger.error("Chunked fallback upload failed:", err);
+ if (!res.headersSent) {
+ return res
+ .status(500)
+ .json({ error: `Chunked upload failed: ${err.message}` });
+ }
+ return;
+ }
+
+ let outputData = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ outputData += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+ });
+
+ stream.stderr.on("error", (stderrErr) => {
+ fileLogger.error(
+ "Chunked fallback upload stderr error:",
+ stderrErr,
+ );
+ });
+
+ stream.on("close", (code) => {
+ if (outputData.includes("SUCCESS")) {
+ if (!res.headersSent) {
+ res.json({
+ message: "File uploaded successfully",
+ path: fullPath,
+ toast: {
+ type: "success",
+ message: `File uploaded: ${fullPath}`,
+ },
+ });
+ }
+ } else {
+ fileLogger.error(
+ `Chunked fallback upload failed with code ${code}: ${errorData}`,
+ );
+ if (!res.headersSent) {
+ res.status(500).json({
+ error: `Chunked upload failed: ${errorData}`,
+ toast: {
+ type: "error",
+ message: `Chunked upload failed: ${errorData}`,
+ },
+ });
+ }
+ }
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.error(
+ "Chunked fallback upload stream error:",
+ streamErr,
+ );
+ if (!res.headersSent) {
+ res.status(500).json({
+ error: `Chunked upload stream error: ${streamErr.message}`,
+ });
+ }
+ });
+ });
+ }
+ } catch (fallbackErr) {
+ fileLogger.error("Fallback method failed:", fallbackErr);
+ if (!res.headersSent) {
+ res.status(500).json({
+ error: `All upload methods failed: ${fallbackErr.message}`,
+ });
+ }
+ }
+ };
+
+ trySFTP();
+ });
+}
diff --git a/src/backend/ssh/file-manager-download-routes.ts b/src/backend/ssh/file-manager-download-routes.ts
new file mode 100644
index 000000000..75a806388
--- /dev/null
+++ b/src/backend/ssh/file-manager-download-routes.ts
@@ -0,0 +1,228 @@
+import type { Express } from "express";
+import type { AuthenticatedRequest } from "../../types/index.js";
+import { fileLogger } from "../utils/logger.js";
+import { getMimeType } from "./file-manager-utils.js";
+import { getSessionSftp, type SSHSession } from "./file-manager-session.js";
+
+type FileDownloadRoutesDeps = {
+ sshSessions: Record<string, SSHSession>;
+ scheduleSessionCleanup: (sessionId: string) => void;
+ verifySessionOwnership: (session: SSHSession, userId: string) => boolean;
+};
+
+export function registerFileDownloadRoutes(
+ app: Express,
+ {
+ sshSessions,
+ scheduleSessionCleanup,
+ verifySessionOwnership,
+ }: FileDownloadRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/downloadFile:
+ * post:
+ * summary: Download a file
+ * description: Downloads a file from the remote host.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * path:
+ * type: string
+ * hostId:
+ * type: integer
+ * userId:
+ * type: string
+ * responses:
+ * 200:
+ * description: The file content.
+ * 400:
+ * description: Missing required parameters or file too large.
+ * 500:
+ * description: Failed to download file.
+ */
+ app.post("/ssh/file_manager/ssh/downloadFile", async (req, res) => {
+ const { sessionId, path: filePath, hostId } = req.body;
+ const userId = (req as AuthenticatedRequest).userId;
+ const downloadStartTime = Date.now();
+
+ if (!sessionId || !filePath) {
+ fileLogger.warn("Missing download parameters", {
+ operation: "file_download",
+ sessionId,
+ hasFilePath: !!filePath,
+ });
+ return res.status(400).json({ error: "Missing download parameters" });
+ }
+
+ fileLogger.info("File download started", {
+ operation: "file_download_start",
+ sessionId,
+ userId,
+ path: filePath,
+ });
+
+ const sshConn = sshSessions[sessionId];
+ if (!sshConn || !sshConn.isConnected) {
+ fileLogger.warn("SSH session not found or not connected for download", {
+ operation: "file_download",
+ sessionId,
+ isConnected: sshConn?.isConnected,
+ });
+ return res
+ .status(400)
+ .json({ error: "SSH session not found or not connected" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ sshConn.lastActive = Date.now();
+ scheduleSessionCleanup(sessionId);
+ fileLogger.info("Opening SFTP channel", {
+ operation: "file_sftp_open",
+ sessionId,
+ userId,
+ path: filePath,
+ });
+
+ getSessionSftp(sshConn)
+ .then((sftp) => {
+ sftp.stat(filePath, (statErr, stats) => {
+ if (statErr) {
+ fileLogger.error("File stat failed for download:", statErr);
+ return res
+ .status(500)
+ .json({ error: `Cannot access file: ${statErr.message}` });
+ }
+
+ if (!stats.isFile()) {
+ fileLogger.warn("Attempted to download non-file", {
+ operation: "file_download",
+ sessionId,
+ filePath,
+ isFile: stats.isFile(),
+ isDirectory: stats.isDirectory(),
+ });
+ return res
+ .status(400)
+ .json({ error: "Cannot download directories or special files" });
+ }
+
+ const MAX_FILE_SIZE = 5 * 1024 * 1024 * 1024;
+ if (stats.size > MAX_FILE_SIZE) {
+ fileLogger.warn("File too large for download", {
+ operation: "file_download",
+ sessionId,
+ filePath,
+ fileSize: stats.size,
+ maxSize: MAX_FILE_SIZE,
+ });
+ return res.status(400).json({
+ error: `File too large. Maximum size is ${MAX_FILE_SIZE / 1024 / 1024}MB, file is ${(stats.size / 1024 / 1024).toFixed(2)}MB`,
+ });
+ }
+
+ sftp.readFile(filePath, (readErr, data) => {
+ if (readErr) {
+ fileLogger.error("File read failed for download:", readErr);
+ return res
+ .status(500)
+ .json({ error: `Failed to read file: ${readErr.message}` });
+ }
+
+ const base64Content = data.toString("base64");
+ const fileName = filePath.split("/").pop() || "download";
+ fileLogger.success("File download completed", {
+ operation: "file_download_complete",
+ sessionId,
+ userId,
+ hostId,
+ path: filePath,
+ bytes: stats.size,
+ duration: Date.now() - downloadStartTime,
+ });
+
+ res.json({
+ content: base64Content,
+ fileName: fileName,
+ size: stats.size,
+ mimeType: getMimeType(fileName),
+ path: filePath,
+ });
+ });
+ });
+ })
+ .catch((err) => {
+ fileLogger.error("SFTP connection failed for download:", err);
+ return res.status(500).json({ error: "SFTP connection failed" });
+ });
+ });
+
+ app.post("/ssh/file_manager/ssh/downloadFileStream", async (req, res) => {
+ const { sessionId, path: filePath } = req.body;
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId || !filePath) {
+ return res.status(400).json({ error: "Missing download parameters" });
+ }
+
+ const sshConn = sshSessions[sessionId];
+ if (!sshConn?.isConnected) {
+ return res
+ .status(400)
+ .json({ error: "SSH session not found or not connected" });
+ }
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ sshConn.lastActive = Date.now();
+
+ try {
+ const sftp = await getSessionSftp(sshConn);
+ const stats = await new Promise<{ size: number; isFile: () => boolean }>(
+ (resolve, reject) => {
+ sftp.stat(filePath, (err, s) => (err ? reject(err) : resolve(s)));
+ },
+ );
+
+ if (!stats.isFile()) {
+ return res.status(400).json({ error: "Cannot download directories" });
+ }
+
+ const fileName = filePath.split("/").pop() || "download";
+ res.setHeader("Content-Type", "application/octet-stream");
+ res.setHeader(
+ "Content-Disposition",
+ `attachment; filename="${encodeURIComponent(fileName)}"`,
+ );
+ res.setHeader("Content-Length", String(stats.size));
+
+ const readStream = sftp.createReadStream(filePath);
+ readStream.on("error", (err) => {
+ if (!res.headersSent) {
+ res.status(500).json({ error: `Download failed: ${err.message}` });
+ } else {
+ res.destroy();
+ }
+ });
+ readStream.pipe(res);
+ } catch (err) {
+ if (!res.headersSent) {
+ res
+ .status(500)
+ .json({ error: `Download failed: ${(err as Error).message}` });
+ }
+ }
+ });
+}
diff --git a/src/backend/ssh/file-manager-list-routes.ts b/src/backend/ssh/file-manager-list-routes.ts
new file mode 100644
index 000000000..b095ce217
--- /dev/null
+++ b/src/backend/ssh/file-manager-list-routes.ts
@@ -0,0 +1,467 @@
+import type { Express } from "express";
+import type { AuthenticatedRequest } from "../../types/index.js";
+import { fileLogger } from "../utils/logger.js";
+import {
+ execChannel,
+ getSessionSftp,
+ type SSHSession,
+} from "./file-manager-session.js";
+import {
+ formatMtime,
+ isExecutableFile,
+ modeToPermissions,
+} from "./file-manager-utils.js";
+
+type FileListingRoutesDeps = {
+ sshSessions: Record<string, SSHSession>;
+ activeListRequests: Record<string, boolean>;
+ verifySessionOwnership: (session: SSHSession, userId: string) => boolean;
+};
+
+export function registerFileListingRoutes(
+ app: Express,
+ {
+ sshSessions,
+ activeListRequests,
+ verifySessionOwnership,
+ }: FileListingRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/listFiles:
+ * get:
+ * summary: List files in a directory
+ * description: Lists the files and directories in a given path on the remote host.
+ * tags:
+ * - File Manager
+ * parameters:
+ * - in: query
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
+ * - in: query
+ * name: path
+ * required: true
+ * schema:
+ * type: string
+ * responses:
+ * 200:
+ * description: A list of files and directories.
+ * 400:
+ * description: Session ID is required or SSH connection not established.
+ * 500:
+ * description: Failed to list files.
+ */
+ app.get("/ssh/file_manager/ssh/listFiles", (req, res) => {
+ const sessionId = req.query.sessionId as string;
+ const sshConn = sshSessions[sessionId];
+ const sshPath = decodeURIComponent((req.query.path as string) || "/");
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ // Drop concurrent requests for the same session+path — each would open
+ // a new SSH channel and can exceed the server's per-connection channel limit.
+ const listKey = `${sessionId}:${sshPath}`;
+ if (activeListRequests[listKey]) {
+ return res
+ .status(409)
+ .json({ error: "List request already in progress" });
+ }
+ activeListRequests[listKey] = true;
+ res.on("finish", () => {
+ delete activeListRequests[listKey];
+ });
+
+ sshConn.lastActive = Date.now();
+ sshConn.activeOperations++;
+ const trySFTP = () => {
+ try {
+ fileLogger.info("Opening SFTP channel", {
+ operation: "file_sftp_open",
+ sessionId,
+ userId,
+ path: sshPath,
+ });
+ getSessionSftp(sshConn)
+ .then((sftp) => {
+ sftp.readdir(sshPath, (readdirErr, list) => {
+ if (readdirErr) {
+ fileLogger.warn(
+ `SFTP readdir failed, trying fallback: ${readdirErr.message}`,
+ );
+ tryFallbackMethod();
+ return;
+ }
+
+ const symlinks: Array<{ index: number; path: string }> = [];
+ const files: Array<{
+ name: string;
+ type: string;
+ size: number | undefined;
+ modified: string;
+ permissions: string;
+ owner: string;
+ group: string;
+ linkTarget: string | undefined;
+ path: string;
+ executable: boolean;
+ }> = [];
+
+ for (const entry of list) {
+ if (entry.filename === "." || entry.filename === "..") continue;
+
+ const attrs = entry.attrs;
+ const permissions = modeToPermissions(attrs.mode);
+ const isDirectory = attrs.isDirectory();
+ const isLink = attrs.isSymbolicLink();
+
+ const fileEntry = {
+ name: entry.filename,
+ type: isDirectory ? "directory" : isLink ? "link" : "file",
+ size: isDirectory ? undefined : attrs.size,
+ modified: formatMtime(attrs.mtime),
+ permissions,
+ owner: String(attrs.uid),
+ group: String(attrs.gid),
+ linkTarget: undefined as string | undefined,
+ path: `${sshPath.endsWith("/") ? sshPath : sshPath + "/"}${entry.filename}`,
+ executable:
+ !isDirectory && !isLink
+ ? isExecutableFile(permissions, entry.filename)
+ : false,
+ };
+
+ if (isLink) {
+ symlinks.push({ index: files.length, path: fileEntry.path });
+ }
+
+ files.push(fileEntry);
+ }
+
+ if (symlinks.length === 0) {
+ sshConn.activeOperations--;
+ return res.json({ files, path: sshPath });
+ }
+
+ let resolved = 0;
+ let responded = false;
+
+ const sendResponse = () => {
+ if (responded) return;
+ responded = true;
+ sshConn.activeOperations--;
+ res.json({ files, path: sshPath });
+ };
+
+ const readlinkTimeout = setTimeout(sendResponse, 5000);
+
+ for (const link of symlinks) {
+ sftp.readlink(link.path, (linkErr, target) => {
+ resolved++;
+ if (!linkErr && target) {
+ files[link.index].linkTarget = target;
+ }
+ if (resolved === symlinks.length) {
+ clearTimeout(readlinkTimeout);
+ sendResponse();
+ }
+ });
+ }
+ });
+ })
+ .catch((err: Error) => {
+ fileLogger.warn(
+ `SFTP failed for listFiles, trying fallback: ${err.message}`,
+ );
+ const isChannelFailure =
+ err.message.toLowerCase().includes("channel open failure") ||
+ err.message.toLowerCase().includes("open failed");
+ if (isChannelFailure) {
+ sshConn.isConnected = false;
+ sshConn.sftp = undefined;
+ }
+ tryFallbackMethod();
+ });
+ } catch (sftpErr: unknown) {
+ const errMsg =
+ sftpErr instanceof Error ? sftpErr.message : "Unknown error";
+ fileLogger.warn(`SFTP connection error, trying fallback: ${errMsg}`);
+ tryFallbackMethod();
+ }
+ };
+
+ const tryFallbackMethod = () => {
+ if (!sshConn?.isConnected) {
+ sshConn.activeOperations--;
+ return res
+ .status(503)
+ .json({ error: "SSH session disconnected", disconnected: true });
+ }
+ try {
+ const escapedPath = sshPath.replace(/'/g, "'\"'\"'");
+ execChannel(
+ sshConn,
+ `command ls -la --color=never '${escapedPath}'`,
+ (err, stream) => {
+ if (err) {
+ sshConn.activeOperations--;
+ fileLogger.error("SSH listFiles error:", err);
+ return res.status(500).json({ error: err.message });
+ }
+
+ let data = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ data += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+ });
+
+ stream.on("close", (code) => {
+ if (code !== 0) {
+ const isPermissionDenied =
+ errorData.toLowerCase().includes("permission denied") ||
+ errorData.toLowerCase().includes("access denied");
+
+ if (isPermissionDenied) {
+ if (sshConn.sudoPassword) {
+ fileLogger.info(
+ `Permission denied for listFiles, retrying with sudo: ${sshPath}`,
+ );
+ tryWithSudo();
+ return;
+ }
+
+ sshConn.activeOperations--;
+ fileLogger.warn(
+ `Permission denied for listFiles, sudo required: ${sshPath}`,
+ );
+ return res.status(403).json({
+ error: `Permission denied: Cannot access ${sshPath}`,
+ needsSudo: true,
+ path: sshPath,
+ });
+ }
+
+ sshConn.activeOperations--;
+ fileLogger.error(
+ `SSH listFiles command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
+ );
+ return res
+ .status(500)
+ .json({ error: `Command failed: ${errorData}` });
+ }
+ sshConn.activeOperations--;
+
+ const lines = data.split("\n").filter((line) => line.trim());
+ const files = [];
+
+ for (let i = 1; i < lines.length; i++) {
+ const line = lines[i];
+ const parts = line.split(/\s+/);
+ if (parts.length >= 9) {
+ const permissions = parts[0];
+ const owner = parts[2];
+ const group = parts[3];
+ const size = parseInt(parts[4], 10);
+
+ let dateStr = "";
+ const nameStartIndex = 8;
+
+ if (parts[5] && parts[6] && parts[7]) {
+ dateStr = `${parts[5]} ${parts[6]} ${parts[7]}`;
+ }
+
+ const name = parts.slice(nameStartIndex).join(" ");
+ const isDirectory = permissions.startsWith("d");
+ const isLink = permissions.startsWith("l");
+
+ if (name === "." || name === "..") continue;
+
+ let actualName = name;
+ let linkTarget = undefined;
+ if (isLink && name.includes(" -> ")) {
+ const linkParts = name.split(" -> ");
+ actualName = linkParts[0];
+ linkTarget = linkParts[1];
+ }
+
+ files.push({
+ name: actualName,
+ type: isDirectory ? "directory" : isLink ? "link" : "file",
+ size: isDirectory ? undefined : size,
+ modified: dateStr,
+ permissions,
+ owner,
+ group,
+ linkTarget,
+ path: `${sshPath.endsWith("/") ? sshPath : sshPath + "/"}${actualName}`,
+ executable:
+ !isDirectory && !isLink
+ ? isExecutableFile(permissions, actualName)
+ : false,
+ });
+ }
+ }
+
+ res.json({ files, path: sshPath });
+ });
+ },
+ );
+ } catch (execErr: unknown) {
+ sshConn.activeOperations--;
+ const errMsg =
+ execErr instanceof Error ? execErr.message : "Unknown error";
+ fileLogger.error(`Fallback listFiles exec failed: ${errMsg}`);
+ if (!res.headersSent) {
+ return res.status(500).json({ error: errMsg });
+ }
+ }
+ };
+
+ const tryWithSudo = () => {
+ try {
+ const escapedPath = sshPath.replace(/'/g, "'\"'\"'");
+ const escapedPassword = sshConn.sudoPassword!.replace(/'/g, "'\"'\"'");
+ const sudoCommand = `echo '${escapedPassword}' | sudo -S /bin/ls -la --color=never '${escapedPath}' 2>&1`;
+
+ execChannel(sshConn, sudoCommand, (err, stream) => {
+ if (err) {
+ sshConn.activeOperations--;
+ fileLogger.error("SSH sudo listFiles error:", err);
+ return res.status(500).json({ error: err.message });
+ }
+
+ let data = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ data += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+ });
+
+ stream.on("close", (code) => {
+ sshConn.activeOperations--;
+
+ data = data.replace(/\[sudo\] password for .+?:\s*/g, "");
+
+ if (
+ data.toLowerCase().includes("sorry, try again") ||
+ data.toLowerCase().includes("incorrect password") ||
+ errorData.toLowerCase().includes("sorry, try again")
+ ) {
+ sshConn.sudoPassword = undefined;
+ return res.status(403).json({
+ error: "Sudo authentication failed. Please try again.",
+ needsSudo: true,
+ sudoFailed: true,
+ path: sshPath,
+ });
+ }
+
+ if (code !== 0 && !data.trim()) {
+ fileLogger.error(
+ `SSH sudo listFiles failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
+ );
+ return res
+ .status(500)
+ .json({ error: `Sudo command failed: ${errorData || data}` });
+ }
+
+ const lines = data.split("\n").filter((line) => line.trim());
+ const files: Array<{
+ name: string;
+ type: string;
+ size: number | undefined;
+ modified: string;
+ permissions: string;
+ owner: string;
+ group: string;
+ linkTarget: string | undefined;
+ path: string;
+ executable: boolean;
+ }> = [];
+
+ for (let i = 1; i < lines.length; i++) {
+ const line = lines[i];
+ const parts = line.split(/\s+/);
+ if (parts.length >= 9) {
+ const permissions = parts[0];
+ const owner = parts[2];
+ const group = parts[3];
+ const size = parseInt(parts[4], 10);
+
+ let dateStr = "";
+ const nameStartIndex = 8;
+
+ if (parts[5] && parts[6] && parts[7]) {
+ dateStr = `${parts[5]} ${parts[6]} ${parts[7]}`;
+ }
+
+ const name = parts.slice(nameStartIndex).join(" ");
+ const isDirectory = permissions.startsWith("d");
+ const isLink = permissions.startsWith("l");
+
+ if (name === "." || name === "..") continue;
+
+ let actualName = name;
+ let linkTarget = undefined;
+ if (isLink && name.includes(" -> ")) {
+ const linkParts = name.split(" -> ");
+ actualName = linkParts[0];
+ linkTarget = linkParts[1];
+ }
+
+ files.push({
+ name: actualName,
+ type: isDirectory ? "directory" : isLink ? "link" : "file",
+ size: isDirectory ? undefined : size,
+ modified: dateStr,
+ permissions,
+ owner,
+ group,
+ linkTarget,
+ path: `${sshPath.endsWith("/") ? sshPath : sshPath + "/"}${actualName}`,
+ executable:
+ !isDirectory && !isLink
+ ? isExecutableFile(permissions, actualName)
+ : false,
+ });
+ }
+ }
+
+ res.json({ files, path: sshPath });
+ });
+ });
+ } catch (execErr: unknown) {
+ sshConn.activeOperations--;
+ const errMsg =
+ execErr instanceof Error ? execErr.message : "Unknown error";
+ fileLogger.error(`Sudo listFiles exec failed: ${errMsg}`);
+ if (!res.headersSent) {
+ return res.status(500).json({ error: errMsg });
+ }
+ }
+ };
+
+ trySFTP();
+ });
+}
diff --git a/src/backend/ssh/file-manager-log.ts b/src/backend/ssh/file-manager-log.ts
new file mode 100644
index 000000000..e2126e782
--- /dev/null
+++ b/src/backend/ssh/file-manager-log.ts
@@ -0,0 +1,15 @@
+import type { ConnectionStage, LogEntry } from "../../types/connection-log.js";
+
+export function createConnectionLog(
+ type: "info" | "success" | "warning" | "error",
+ stage: ConnectionStage,
+ message: string,
+ details?: Record<string, unknown>,
+): Omit<LogEntry, "id" | "timestamp"> {
+ return {
+ type,
+ stage,
+ message,
+ details,
+ };
+}
diff --git a/src/backend/ssh/file-manager-operation-routes.ts b/src/backend/ssh/file-manager-operation-routes.ts
new file mode 100644
index 000000000..23c1e0dac
--- /dev/null
+++ b/src/backend/ssh/file-manager-operation-routes.ts
@@ -0,0 +1,818 @@
+import type { Express } from "express";
+import type { AuthenticatedRequest } from "../../types/index.js";
+import { fileLogger } from "../utils/logger.js";
+import {
+ execChannel,
+ execWithSudo,
+ type SSHSession,
+} from "./file-manager-session.js";
+
+type FileOperationRoutesDeps = {
+ sshSessions: Record<string, SSHSession>;
+ verifySessionOwnership: (session: SSHSession, userId: string) => boolean;
+};
+
+export function registerFileOperationRoutes(
+ app: Express,
+ { sshSessions, verifySessionOwnership }: FileOperationRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/createFile:
+ * post:
+ * summary: Create a file
+ * description: Creates an empty file on the remote host.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * path:
+ * type: string
+ * fileName:
+ * type: string
+ * responses:
+ * 200:
+ * description: File created successfully.
+ * 400:
+ * description: Missing required parameters or SSH connection not established.
+ * 403:
+ * description: Permission denied.
+ * 500:
+ * description: Failed to create file.
+ */
+ app.post("/ssh/file_manager/ssh/createFile", async (req, res) => {
+ const { sessionId, path: filePath, fileName } = req.body;
+ const sshConn = sshSessions[sessionId];
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!filePath || !fileName) {
+ return res.status(400).json({ error: "File path and name are required" });
+ }
+
+ sshConn.lastActive = Date.now();
+
+ const fullPath = filePath.endsWith("/")
+ ? filePath + fileName
+ : filePath + "/" + fileName;
+ const escapedPath = fullPath.replace(/'/g, "'\"'\"'");
+
+ const createCommand = `touch '${escapedPath}' && echo "SUCCESS" && exit 0`;
+
+ execChannel(sshConn, createCommand, (err, stream) => {
+ if (err) {
+ fileLogger.error("SSH createFile error:", err);
+ if (!res.headersSent) {
+ return res.status(500).json({ error: err.message });
+ }
+ return;
+ }
+
+ let outputData = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ outputData += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+
+ if (chunk.toString().includes("Permission denied")) {
+ fileLogger.error(`Permission denied creating file: ${fullPath}`);
+ if (!res.headersSent) {
+ return res.status(403).json({
+ error: `Permission denied: Cannot create file ${fullPath}. Check directory permissions.`,
+ });
+ }
+ return;
+ }
+ });
+
+ stream.on("close", (code) => {
+ if (outputData.includes("SUCCESS")) {
+ if (!res.headersSent) {
+ res.json({
+ message: "File created successfully",
+ path: fullPath,
+ toast: { type: "success", message: `File created: ${fullPath}` },
+ });
+ }
+ return;
+ }
+
+ if (code !== 0) {
+ fileLogger.error(
+ `SSH createFile command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
+ );
+ if (!res.headersSent) {
+ return res.status(500).json({
+ error: `Command failed: ${errorData}`,
+ toast: {
+ type: "error",
+ message: `File creation failed: ${errorData}`,
+ },
+ });
+ }
+ return;
+ }
+
+ if (!res.headersSent) {
+ res.json({
+ message: "File created successfully",
+ path: fullPath,
+ toast: { type: "success", message: `File created: ${fullPath}` },
+ });
+ }
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.error("SSH createFile stream error:", streamErr);
+ if (!res.headersSent) {
+ res.status(500).json({ error: `Stream error: ${streamErr.message}` });
+ }
+ });
+ });
+ });
+
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/createFolder:
+ * post:
+ * summary: Create a folder
+ * description: Creates a new folder on the remote host.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * path:
+ * type: string
+ * folderName:
+ * type: string
+ * responses:
+ * 200:
+ * description: Folder created successfully.
+ * 400:
+ * description: Missing required parameters or SSH connection not established.
+ * 403:
+ * description: Permission denied.
+ * 500:
+ * description: Failed to create folder.
+ */
+ app.post("/ssh/file_manager/ssh/createFolder", async (req, res) => {
+ const { sessionId, path: folderPath, folderName } = req.body;
+ const sshConn = sshSessions[sessionId];
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!folderPath || !folderName) {
+ return res
+ .status(400)
+ .json({ error: "Folder path and name are required" });
+ }
+
+ sshConn.lastActive = Date.now();
+
+ const fullPath = folderPath.endsWith("/")
+ ? folderPath + folderName
+ : folderPath + "/" + folderName;
+ fileLogger.info("Creating directory", {
+ operation: "file_mkdir",
+ sessionId,
+ userId,
+ path: fullPath,
+ });
+ const escapedPath = fullPath.replace(/'/g, "'\"'\"'");
+
+ const createCommand = `mkdir -p '${escapedPath}' && echo "SUCCESS" && exit 0`;
+
+ execChannel(sshConn, createCommand, (err, stream) => {
+ if (err) {
+ fileLogger.error("SSH createFolder error:", err);
+ if (!res.headersSent) {
+ return res.status(500).json({ error: err.message });
+ }
+ return;
+ }
+
+ let outputData = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ outputData += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+
+ if (chunk.toString().includes("Permission denied")) {
+ fileLogger.error(`Permission denied creating folder: ${fullPath}`);
+ if (!res.headersSent) {
+ return res.status(403).json({
+ error: `Permission denied: Cannot create folder ${fullPath}. Check directory permissions.`,
+ });
+ }
+ return;
+ }
+ });
+
+ stream.on("close", (code) => {
+ if (outputData.includes("SUCCESS")) {
+ fileLogger.success("Directory created successfully", {
+ operation: "file_mkdir_success",
+ sessionId,
+ userId,
+ path: fullPath,
+ });
+ if (!res.headersSent) {
+ res.json({
+ message: "Folder created successfully",
+ path: fullPath,
+ toast: {
+ type: "success",
+ message: `Folder created: ${fullPath}`,
+ },
+ });
+ }
+ return;
+ }
+
+ if (code !== 0) {
+ fileLogger.error(
+ `SSH createFolder command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
+ );
+ if (!res.headersSent) {
+ return res.status(500).json({
+ error: `Command failed: ${errorData}`,
+ toast: {
+ type: "error",
+ message: `Folder creation failed: ${errorData}`,
+ },
+ });
+ }
+ return;
+ }
+
+ fileLogger.success("Directory created successfully", {
+ operation: "file_mkdir_success",
+ sessionId,
+ userId,
+ path: fullPath,
+ });
+ if (!res.headersSent) {
+ res.json({
+ message: "Folder created successfully",
+ path: fullPath,
+ toast: { type: "success", message: `Folder created: ${fullPath}` },
+ });
+ }
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.error("SSH createFolder stream error:", streamErr);
+ if (!res.headersSent) {
+ res.status(500).json({ error: `Stream error: ${streamErr.message}` });
+ }
+ });
+ });
+ });
+
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/deleteItem:
+ * delete:
+ * summary: Delete a file or directory
+ * description: Deletes a file or directory on the remote host.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * path:
+ * type: string
+ * isDirectory:
+ * type: boolean
+ * responses:
+ * 200:
+ * description: Item deleted successfully.
+ * 400:
+ * description: Missing required parameters or SSH connection not established.
+ * 403:
+ * description: Permission denied.
+ * 500:
+ * description: Failed to delete item.
+ */
+ app.delete("/ssh/file_manager/ssh/deleteItem", async (req, res) => {
+ const { sessionId, path: itemPath, isDirectory } = req.body;
+ const sshConn = sshSessions[sessionId];
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!itemPath) {
+ return res.status(400).json({ error: "Item path is required" });
+ }
+
+ fileLogger.info("Deleting item", {
+ operation: "file_delete",
+ sessionId,
+ userId,
+ path: itemPath,
+ type: isDirectory ? "directory" : "file",
+ });
+ sshConn.lastActive = Date.now();
+ const escapedPath = itemPath.replace(/'/g, "'\"'\"'");
+
+ const deleteCommand = isDirectory
+ ? `rm -rf '${escapedPath}'`
+ : `rm -f '${escapedPath}'`;
+
+ const executeDelete = (useSudo: boolean): Promise<void> => {
+ return new Promise((resolve) => {
+ if (useSudo && sshConn.sudoPassword) {
+ execWithSudo(sshConn, deleteCommand, sshConn.sudoPassword).then(
+ (result) => {
+ if (
+ result.code === 0 ||
+ (!result.stderr.includes("Permission denied") &&
+ !result.stdout.includes("Permission denied"))
+ ) {
+ res.json({
+ message: "Item deleted successfully",
+ path: itemPath,
+ toast: {
+ type: "success",
+ message: `${isDirectory ? "Directory" : "File"} deleted: ${itemPath}`,
+ },
+ });
+ } else {
+ res.status(500).json({
+ error: `Delete failed: ${result.stderr || result.stdout}`,
+ });
+ }
+ resolve();
+ },
+ );
+ return;
+ }
+
+ execChannel(
+ sshConn,
+ `${deleteCommand} && echo "SUCCESS"`,
+ (err, stream) => {
+ if (err) {
+ fileLogger.error("SSH deleteItem error:", err);
+ res.status(500).json({ error: err.message });
+ resolve();
+ return;
+ }
+
+ let outputData = "";
+ let errorData = "";
+ let permissionDenied = false;
+
+ stream.on("data", (chunk: Buffer) => {
+ outputData += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+ if (chunk.toString().includes("Permission denied")) {
+ permissionDenied = true;
+ }
+ });
+
+ stream.on("close", (code) => {
+ if (permissionDenied) {
+ if (sshConn.sudoPassword) {
+ executeDelete(true).then(resolve);
+ return;
+ }
+ fileLogger.error(`Permission denied deleting: ${itemPath}`);
+ res.status(403).json({
+ error: `Permission denied: Cannot delete ${itemPath}.`,
+ needsSudo: true,
+ });
+ resolve();
+ return;
+ }
+
+ if (outputData.includes("SUCCESS") || code === 0) {
+ fileLogger.success("Item deleted successfully", {
+ operation: "file_delete_success",
+ sessionId,
+ userId,
+ path: itemPath,
+ });
+ res.json({
+ message: "Item deleted successfully",
+ path: itemPath,
+ toast: {
+ type: "success",
+ message: `${isDirectory ? "Directory" : "File"} deleted: ${itemPath}`,
+ },
+ });
+ } else {
+ res.status(500).json({
+ error: `Command failed: ${errorData}`,
+ });
+ }
+ resolve();
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.error("SSH deleteItem stream error:", streamErr);
+ res
+ .status(500)
+ .json({ error: `Stream error: ${streamErr.message}` });
+ resolve();
+ });
+ },
+ );
+ });
+ };
+
+ await executeDelete(false);
+ });
+
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/renameItem:
+ * put:
+ * summary: Rename a file or directory
+ * description: Renames a file or directory on the remote host.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * oldPath:
+ * type: string
+ * newName:
+ * type: string
+ * responses:
+ * 200:
+ * description: Item renamed successfully.
+ * 400:
+ * description: Missing required parameters or SSH connection not established.
+ * 403:
+ * description: Permission denied.
+ * 500:
+ * description: Failed to rename item.
+ */
+ app.put("/ssh/file_manager/ssh/renameItem", async (req, res) => {
+ const { sessionId, oldPath, newName } = req.body;
+ const sshConn = sshSessions[sessionId];
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!oldPath || !newName) {
+ return res
+ .status(400)
+ .json({ error: "Old path and new name are required" });
+ }
+
+ sshConn.lastActive = Date.now();
+
+ const oldDir = oldPath.substring(0, oldPath.lastIndexOf("/") + 1);
+ const newPath = oldDir + newName;
+ fileLogger.info("Renaming item", {
+ operation: "file_rename",
+ sessionId,
+ userId,
+ from: oldPath,
+ to: newPath,
+ });
+ const escapedOldPath = oldPath.replace(/'/g, "'\"'\"'");
+ const escapedNewPath = newPath.replace(/'/g, "'\"'\"'");
+
+ const renameCommand = `mv '${escapedOldPath}' '${escapedNewPath}' && echo "SUCCESS" && exit 0`;
+
+ execChannel(sshConn, renameCommand, (err, stream) => {
+ if (err) {
+ fileLogger.error("SSH renameItem error:", err);
+ if (!res.headersSent) {
+ return res.status(500).json({ error: err.message });
+ }
+ return;
+ }
+
+ let outputData = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ outputData += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+
+ if (chunk.toString().includes("Permission denied")) {
+ fileLogger.error(`Permission denied renaming: ${oldPath}`);
+ if (!res.headersSent) {
+ return res.status(403).json({
+ error: `Permission denied: Cannot rename ${oldPath}. Check file permissions.`,
+ });
+ }
+ return;
+ }
+ });
+
+ stream.on("close", (code) => {
+ if (outputData.includes("SUCCESS")) {
+ fileLogger.success("Item renamed successfully", {
+ operation: "file_rename_success",
+ sessionId,
+ userId,
+ from: oldPath,
+ to: newPath,
+ });
+ if (!res.headersSent) {
+ res.json({
+ message: "Item renamed successfully",
+ oldPath,
+ newPath,
+ toast: {
+ type: "success",
+ message: `Item renamed: ${oldPath} -> ${newPath}`,
+ },
+ });
+ }
+ return;
+ }
+
+ if (code !== 0) {
+ fileLogger.error(
+ `SSH renameItem command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
+ );
+ if (!res.headersSent) {
+ return res.status(500).json({
+ error: `Command failed: ${errorData}`,
+ toast: { type: "error", message: `Rename failed: ${errorData}` },
+ });
+ }
+ return;
+ }
+
+ fileLogger.success("Item renamed successfully", {
+ operation: "file_rename_success",
+ sessionId,
+ userId,
+ from: oldPath,
+ to: newPath,
+ });
+ if (!res.headersSent) {
+ res.json({
+ message: "Item renamed successfully",
+ oldPath,
+ newPath,
+ toast: {
+ type: "success",
+ message: `Item renamed: ${oldPath} -> ${newPath}`,
+ },
+ });
+ }
+ });
+
+ stream.on("error", (streamErr) => {
+ fileLogger.error("SSH renameItem stream error:", streamErr);
+ if (!res.headersSent) {
+ res.status(500).json({ error: `Stream error: ${streamErr.message}` });
+ }
+ });
+ });
+ });
+
+ /**
+ * @openapi
+ * /ssh/file_manager/ssh/moveItem:
+ * put:
+ * summary: Move a file or directory
+ * description: Moves a file or directory on the remote host.
+ * tags:
+ * - File Manager
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * sessionId:
+ * type: string
+ * oldPath:
+ * type: string
+ * newPath:
+ * type: string
+ * responses:
+ * 200:
+ * description: Item moved successfully.
+ * 400:
+ * description: Missing required parameters or SSH connection not established.
+ * 403:
+ * description: Permission denied.
+ * 408:
+ * description: Move operation timed out.
+ * 500:
+ * description: Failed to move item.
+ */
+ app.put("/ssh/file_manager/ssh/moveItem", async (req, res) => {
+ const { sessionId, oldPath, newPath } = req.body;
+ const sshConn = sshSessions[sessionId];
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
+ }
+
+ if (!sshConn?.isConnected) {
+ return res.status(400).json({ error: "SSH connection not established" });
+ }
+
+ if (!verifySessionOwnership(sshConn, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ if (!oldPath || !newPath) {
+ return res
+ .status(400)
+ .json({ error: "Old path and new path are required" });
+ }
+
+ sshConn.lastActive = Date.now();
+
+ const escapedOldPath = oldPath.replace(/'/g, "'\"'\"'");
+ const escapedNewPath = newPath.replace(/'/g, "'\"'\"'");
+
+ const moveCommand = `mv '${escapedOldPath}' '${escapedNewPath}' && echo "SUCCESS" && exit 0`;
+
+ const commandTimeout = setTimeout(() => {
+ if (!res.headersSent) {
+ res.status(408).json({
+ error: "Move operation timed out. SSH connection may be unstable.",
+ toast: {
+ type: "error",
+ message:
+ "Move operation timed out. SSH connection may be unstable.",
+ },
+ });
+ }
+ }, 60000);
+
+ execChannel(sshConn, moveCommand, (err, stream) => {
+ if (err) {
+ clearTimeout(commandTimeout);
+ fileLogger.error("SSH moveItem error:", err);
+ if (!res.headersSent) {
+ return res.status(500).json({ error: err.message });
+ }
+ return;
+ }
+
+ let outputData = "";
+ let errorData = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ outputData += chunk.toString();
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ errorData += chunk.toString();
+
+ if (chunk.toString().includes("Permission denied")) {
+ fileLogger.error(`Permission denied moving: ${oldPath}`);
+ if (!res.headersSent) {
+ return res.status(403).json({
+ error: `Permission denied: Cannot move ${oldPath}. Check file permissions.`,
+ toast: {
+ type: "error",
+ message: `Permission denied: Cannot move ${oldPath}. Check file permissions.`,
+ },
+ });
+ }
+ return;
+ }
+ });
+
+ stream.on("close", (code) => {
+ clearTimeout(commandTimeout);
+ if (outputData.includes("SUCCESS")) {
+ if (!res.headersSent) {
+ res.json({
+ message: "Item moved successfully",
+ oldPath,
+ newPath,
+ toast: {
+ type: "success",
+ message: `Item moved: ${oldPath} -> ${newPath}`,
+ },
+ });
+ }
+ return;
+ }
+
+ if (code !== 0) {
+ fileLogger.error(
+ `SSH moveItem command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
+ );
+ if (!res.headersSent) {
+ return res.status(500).json({
+ error: `Command failed: ${errorData}`,
+ toast: { type: "error", message: `Move failed: ${errorData}` },
+ });
+ }
+ return;
+ }
+
+ if (!res.headersSent) {
+ res.json({
+ message: "Item moved successfully",
+ oldPath,
+ newPath,
+ toast: {
+ type: "success",
+ message: `Item moved: ${oldPath} -> ${newPath}`,
+ },
+ });
+ }
+ });
+
+ stream.on("error", (streamErr) => {
+ clearTimeout(commandTimeout);
+ fileLogger.error("SSH moveItem stream error:", streamErr);
+ if (!res.headersSent) {
+ res.status(500).json({ error: `Stream error: ${streamErr.message}` });
+ }
+ });
+ });
+ });
+}
diff --git a/src/backend/ssh/file-manager-session.ts b/src/backend/ssh/file-manager-session.ts
new file mode 100644
index 000000000..1bbebf223
--- /dev/null
+++ b/src/backend/ssh/file-manager-session.ts
@@ -0,0 +1,192 @@
+import type { Client as SSHClient } from "ssh2";
+
+// Serializes SSH channel open requests so only one channel negotiation is
+// in-flight at a time per session. Once the channel is established the slot
+// is released immediately so the next open can proceed; the channels
+// themselves remain open concurrently.
+export class ChannelOpenSerializer {
+ private tail: Promise<void> = Promise.resolve();
+
+ run<T>(action: () => Promise<T>): Promise<T> {
+ const next = this.tail.then(
+ () => action(),
+ () => action(),
+ );
+ this.tail = next.then(
+ () => {},
+ () => {},
+ );
+ return next;
+ }
+}
+
+export interface SSHSession {
+ client: SSHClient;
+ isConnected: boolean;
+ lastActive: number;
+ timeout?: NodeJS.Timeout;
+ activeOperations: number;
+ sudoPassword?: string;
+ sftp?: import("ssh2").SFTPWrapper;
+ sftpPending?: Promise<import("ssh2").SFTPWrapper>;
+ channelOpener: ChannelOpenSerializer;
+ poolKey?: string;
+ userId?: string;
+ hostId?: number;
+ ip?: string;
+ port?: number;
+ username?: string;
+ transferDedicated?: boolean;
+ transferId?: string;
+ browseSessionId?: string;
+}
+
+export interface PendingTOTPSession {
+ client: SSHClient;
+ finish: (responses: string[]) => void;
+ config: import("ssh2").ConnectConfig;
+ createdAt: number;
+ sessionId: string;
+ hostId?: number;
+ ip?: string;
+ port?: number;
+ username?: string;
+ userId?: string;
+ prompts?: Array<{ prompt: string; echo: boolean }>;
+ totpPromptIndex?: number;
+ resolvedPassword?: string;
+ totpAttempts: number;
+ isWarpgate?: boolean;
+}
+
+export function execWithSudo(
+ session: SSHSession,
+ command: string,
+ sudoPassword: string,
+): Promise<{ stdout: string; stderr: string; code: number }> {
+ return execWithSudoBuffer(session, command, sudoPassword).then((result) => ({
+ stdout: result.stdout.toString("utf8"),
+ stderr: result.stderr,
+ code: result.code,
+ }));
+}
+
+export function execWithSudoBuffer(
+ session: SSHSession,
+ command: string,
+ sudoPassword: string,
+): Promise<{ stdout: Buffer; stderr: string; code: number }> {
+ return new Promise((resolve) => {
+ const escapedPassword = sudoPassword.replace(/'/g, "'\"'\"'");
+ const sudoCommand = `echo '${escapedPassword}' | sudo -S ${command} 2>&1`;
+
+ execChannel(session, sudoCommand, (err, stream) => {
+ if (err) {
+ resolve({ stdout: Buffer.alloc(0), stderr: err.message, code: 1 });
+ return;
+ }
+
+ const stdoutChunks: Buffer[] = [];
+ let stderr = "";
+
+ stream.on("data", (chunk: Buffer) => {
+ stdoutChunks.push(chunk);
+ });
+
+ stream.stderr.on("data", (chunk: Buffer) => {
+ stderr += chunk.toString();
+ });
+
+ stream.on("close", (code: number) => {
+ let stdout = Buffer.concat(stdoutChunks);
+ const sudoPromptMatch = stdout
+ .toString("utf8", 0, Math.min(stdout.length, 256))
+ .match(/^\[sudo\] password for .+?:\s*/);
+ if (sudoPromptMatch) {
+ stdout = stdout.subarray(Buffer.byteLength(sudoPromptMatch[0]));
+ }
+ resolve({ stdout, stderr, code: code || 0 });
+ });
+
+ stream.on("error", (streamErr: Error) => {
+ resolve({
+ stdout: Buffer.concat(stdoutChunks),
+ stderr: streamErr.message,
+ code: 1,
+ });
+ });
+ });
+ });
+}
+
+export function getSessionSftp(
+ session: SSHSession,
+): Promise<import("ssh2").SFTPWrapper> {
+ if (session.sftp) {
+ return Promise.resolve(session.sftp);
+ }
+
+ if (session.sftpPending) {
+ return session.sftpPending;
+ }
+
+ const openOnce = (): Promise<import("ssh2").SFTPWrapper> =>
+ session.channelOpener.run(
+ () =>
+ new Promise<import("ssh2").SFTPWrapper>((resolve, reject) => {
+ session.client.sftp((err, sftp) => {
+ if (err) return reject(err);
+ session.sftp = sftp;
+ sftp.on("error", () => {
+ session.sftp = undefined;
+ });
+ sftp.on("close", () => {
+ session.sftp = undefined;
+ });
+ resolve(sftp);
+ });
+ }),
+ );
+
+ session.sftpPending = openOnce()
+ .catch((err: Error) => {
+ const isChannelFailure =
+ err.message.toLowerCase().includes("channel open failure") ||
+ err.message.toLowerCase().includes("open failed");
+ if (isChannelFailure) {
+ return new Promise<import("ssh2").SFTPWrapper>((resolve, reject) =>
+ setTimeout(() => openOnce().then(resolve, reject), 500),
+ );
+ }
+ return Promise.reject(err);
+ })
+ .finally(() => {
+ session.sftpPending = undefined;
+ });
+
+ return session.sftpPending;
+}
+
+export function execChannel(
+ session: SSHSession,
+ command: string,
+ callback: (
+ err: Error | undefined,
+ stream: import("ssh2").ClientChannel,
+ ) => void,
+): void {
+ session.channelOpener
+ .run(
+ () =>
+ new Promise<import("ssh2").ClientChannel>((resolve, reject) => {
+ session.client.exec(command, (err, stream) => {
+ if (err) return reject(err);
+ resolve(stream);
+ });
+ }),
+ )
+ .then(
+ (stream) => callback(undefined, stream),
+ (err: Error) => callback(err, undefined as never),
+ );
+}
diff --git a/src/backend/ssh/file-manager-utils.test.ts b/src/backend/ssh/file-manager-utils.test.ts
new file mode 100644
index 000000000..85eddb082
--- /dev/null
+++ b/src/backend/ssh/file-manager-utils.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect } from "vitest";
+import {
+ isExecutableFile,
+ modeToPermissions,
+ formatMtime,
+ getMimeType,
+ detectBinary,
+} from "./file-manager-utils.js";
+
+describe("isExecutableFile", () => {
+ it("flags scripts with execute permission", () => {
+ expect(isExecutableFile("-rwxr-xr-x", "deploy.sh")).toBe(true);
+ expect(isExecutableFile("-rwxr-xr-x", "run.py")).toBe(true);
+ });
+
+ it("flags known executable extensions with execute permission", () => {
+ expect(isExecutableFile("-rwxr-xr-x", "tool.bin")).toBe(true);
+ expect(isExecutableFile("-rwxr-xr-x", "app.exe")).toBe(true);
+ });
+
+ it("flags extensionless files with execute permission", () => {
+ expect(isExecutableFile("-rwxr-xr-x", "myprogram")).toBe(true);
+ });
+
+ it("does not flag files without execute permission", () => {
+ expect(isExecutableFile("-rw-r--r--", "deploy.sh")).toBe(false);
+ expect(isExecutableFile("-rw-r--r--", "myprogram")).toBe(false);
+ });
+
+ it("does not flag non-script data files even when executable", () => {
+ expect(isExecutableFile("-rwxr-xr-x", "notes.txt")).toBe(false);
+ });
+});
+
+describe("modeToPermissions", () => {
+ it("renders a regular file with rwxr-xr-x", () => {
+ expect(modeToPermissions(0o100755)).toBe("-rwxr-xr-x");
+ });
+
+ it("renders a directory prefix", () => {
+ expect(modeToPermissions(0o040755)).toBe("drwxr-xr-x");
+ });
+
+ it("renders a symlink prefix", () => {
+ expect(modeToPermissions(0o120777)).toBe("lrwxrwxrwx");
+ });
+
+ it("renders a read-only file", () => {
+ expect(modeToPermissions(0o100444)).toBe("-r--r--r--");
+ });
+
+ it("renders no permissions", () => {
+ expect(modeToPermissions(0o100000)).toBe("----------");
+ });
+});
+
+describe("formatMtime", () => {
+ it("uses HH:MM format for recent timestamps", () => {
+ // Within the last 6 months relative to now.
+ const recent = Math.floor(Date.now() / 1000) - 60 * 60 * 24 * 5;
+ const result = formatMtime(recent);
+ expect(result).toMatch(/^[A-Z][a-z]{2} +\d{1,2} \d{2}:\d{2}$/);
+ });
+
+ it("uses the year for old timestamps", () => {
+ // ~2 years ago is comfortably outside the 6-month window.
+ const old = Math.floor(Date.now() / 1000) - 60 * 60 * 24 * 365 * 2;
+ const result = formatMtime(old);
+ expect(result).toMatch(/^[A-Z][a-z]{2} +\d{1,2} +\d{4}$/);
+ });
+});
+
+describe("getMimeType", () => {
+ it("maps known extensions", () => {
+ expect(getMimeType("readme.txt")).toBe("text/plain");
+ expect(getMimeType("data.json")).toBe("application/json");
+ expect(getMimeType("photo.JPEG")).toBe("image/jpeg");
+ expect(getMimeType("archive.zip")).toBe("application/zip");
+ });
+
+ it("falls back to octet-stream for unknown or missing extensions", () => {
+ expect(getMimeType("mystery.xyz")).toBe("application/octet-stream");
+ expect(getMimeType("noextension")).toBe("application/octet-stream");
+ });
+});
+
+describe("detectBinary", () => {
+ it("returns false for empty buffers", () => {
+ expect(detectBinary(Buffer.from([]))).toBe(false);
+ });
+
+ it("returns false for plain UTF-8 text", () => {
+ expect(detectBinary(Buffer.from("hello world\nsecond line\t tab"))).toBe(
+ false,
+ );
+ });
+
+ it("returns true when null bytes are present", () => {
+ expect(detectBinary(Buffer.from([0x48, 0x00, 0x49, 0x00]))).toBe(true);
+ });
+
+ it("allows common whitespace control characters", () => {
+ expect(detectBinary(Buffer.from("line1\r\nline2\tend"))).toBe(false);
+ });
+});
diff --git a/src/backend/ssh/file-manager-utils.ts b/src/backend/ssh/file-manager-utils.ts
new file mode 100644
index 000000000..b3809a18f
--- /dev/null
+++ b/src/backend/ssh/file-manager-utils.ts
@@ -0,0 +1,127 @@
+export function isExecutableFile(
+ permissions: string,
+ fileName: string,
+): boolean {
+ const hasExecutePermission =
+ permissions[3] === "x" || permissions[6] === "x" || permissions[9] === "x";
+
+ const scriptExtensions = [
+ ".sh",
+ ".py",
+ ".pl",
+ ".rb",
+ ".js",
+ ".php",
+ ".bash",
+ ".zsh",
+ ".fish",
+ ];
+ const hasScriptExtension = scriptExtensions.some((ext) =>
+ fileName.toLowerCase().endsWith(ext),
+ );
+
+ const executableExtensions = [".bin", ".exe", ".out"];
+ const hasExecutableExtension = executableExtensions.some((ext) =>
+ fileName.toLowerCase().endsWith(ext),
+ );
+
+ const hasNoExtension = !fileName.includes(".") && hasExecutePermission;
+
+ return (
+ hasExecutePermission &&
+ (hasScriptExtension || hasExecutableExtension || hasNoExtension)
+ );
+}
+
+export function modeToPermissions(mode: number): string {
+ const S_IFDIR = 0o040000;
+ const S_IFLNK = 0o120000;
+ const S_IFMT = 0o170000;
+
+ const type = mode & S_IFMT;
+ const prefix = type === S_IFDIR ? "d" : type === S_IFLNK ? "l" : "-";
+
+ const perms = [
+ mode & 0o400 ? "r" : "-",
+ mode & 0o200 ? "w" : "-",
+ mode & 0o100 ? "x" : "-",
+ mode & 0o040 ? "r" : "-",
+ mode & 0o020 ? "w" : "-",
+ mode & 0o010 ? "x" : "-",
+ mode & 0o004 ? "r" : "-",
+ mode & 0o002 ? "w" : "-",
+ mode & 0o001 ? "x" : "-",
+ ].join("");
+
+ return prefix + perms;
+}
+
+export function formatMtime(mtime: number): string {
+ const date = new Date(mtime * 1000);
+ const months = [
+ "Jan",
+ "Feb",
+ "Mar",
+ "Apr",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec",
+ ];
+ const month = months[date.getMonth()];
+ const day = date.getDate().toString().padStart(2, " ");
+ const now = new Date();
+ const sixMonthsAgo = new Date(now.getTime() - 180 * 24 * 60 * 60 * 1000);
+
+ if (date > sixMonthsAgo) {
+ const hours = date.getHours().toString().padStart(2, "0");
+ const minutes = date.getMinutes().toString().padStart(2, "0");
+ return `${month} ${day} ${hours}:${minutes}`;
+ }
+ return `${month} ${day} ${date.getFullYear()}`;
+}
+
+export function getMimeType(fileName: string): string {
+ const ext = fileName.split(".").pop()?.toLowerCase();
+ const mimeTypes: Record<string, string> = {
+ txt: "text/plain",
+ json: "application/json",
+ js: "text/javascript",
+ html: "text/html",
+ css: "text/css",
+ png: "image/png",
+ jpg: "image/jpeg",
+ jpeg: "image/jpeg",
+ gif: "image/gif",
+ pdf: "application/pdf",
+ zip: "application/zip",
+ tar: "application/x-tar",
+ gz: "application/gzip",
+ };
+ return mimeTypes[ext || ""] || "application/octet-stream";
+}
+
+export function detectBinary(buffer: Buffer): boolean {
+ if (buffer.length === 0) return false;
+
+ const sampleSize = Math.min(buffer.length, 8192);
+ let nullBytes = 0;
+
+ for (let i = 0; i < sampleSize; i++) {
+ const byte = buffer[i];
+
+ if (byte === 0) {
+ nullBytes++;
+ }
+
+ if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {
+ if (++nullBytes > 1) return true;
+ }
+ }
+
+ return nullBytes / sampleSize > 0.01;
+}
diff --git a/src/backend/ssh/file-manager.ts b/src/backend/ssh/file-manager.ts
index 733a6b0b5..3a33debe0 100644
--- a/src/backend/ssh/file-manager.ts
+++ b/src/backend/ssh/file-manager.ts
@@ -5,7 +5,7 @@ import axios from "axios";
import { Client as SSHClient } from "ssh2";
import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
import { getDb } from "../database/db/index.js";
-import { sshCredentials, hosts } from "../database/db/schema.js";
+import { hosts } from "../database/db/schema.js";
import { eq, and } from "drizzle-orm";
import { fileLogger } from "../utils/logger.js";
import { SimpleDBOps } from "../utils/simple-db-ops.js";
@@ -17,104 +17,33 @@ import {
} from "../utils/socks5-helper.js";
import type { LogEntry, ConnectionStage } from "../../types/connection-log.js";
import { SSHHostKeyVerifier } from "./host-key-verifier.js";
-
-function createConnectionLog(
- type: "info" | "success" | "warning" | "error",
- stage: ConnectionStage,
- message: string,
- details?: Record<string, unknown>,
-): Omit<LogEntry, "id" | "timestamp"> {
- return {
- type,
- stage,
- message,
- details,
- };
-}
-
-function isExecutableFile(permissions: string, fileName: string): boolean {
- const hasExecutePermission =
- permissions[3] === "x" || permissions[6] === "x" || permissions[9] === "x";
-
- const scriptExtensions = [
- ".sh",
- ".py",
- ".pl",
- ".rb",
- ".js",
- ".php",
- ".bash",
- ".zsh",
- ".fish",
- ];
- const hasScriptExtension = scriptExtensions.some((ext) =>
- fileName.toLowerCase().endsWith(ext),
- );
-
- const executableExtensions = [".bin", ".exe", ".out"];
- const hasExecutableExtension = executableExtensions.some((ext) =>
- fileName.toLowerCase().endsWith(ext),
- );
-
- const hasNoExtension = !fileName.includes(".") && hasExecutePermission;
-
- return (
- hasExecutePermission &&
- (hasScriptExtension || hasExecutableExtension || hasNoExtension)
- );
-}
-
-function modeToPermissions(mode: number): string {
- const S_IFDIR = 0o040000;
- const S_IFLNK = 0o120000;
- const S_IFMT = 0o170000;
-
- const type = mode & S_IFMT;
- const prefix = type === S_IFDIR ? "d" : type === S_IFLNK ? "l" : "-";
-
- const perms = [
- mode & 0o400 ? "r" : "-",
- mode & 0o200 ? "w" : "-",
- mode & 0o100 ? "x" : "-",
- mode & 0o040 ? "r" : "-",
- mode & 0o020 ? "w" : "-",
- mode & 0o010 ? "x" : "-",
- mode & 0o004 ? "r" : "-",
- mode & 0o002 ? "w" : "-",
- mode & 0o001 ? "x" : "-",
- ].join("");
-
- return prefix + perms;
-}
-
-function formatMtime(mtime: number): string {
- const date = new Date(mtime * 1000);
- const months = [
- "Jan",
- "Feb",
- "Mar",
- "Apr",
- "May",
- "Jun",
- "Jul",
- "Aug",
- "Sep",
- "Oct",
- "Nov",
- "Dec",
- ];
- const month = months[date.getMonth()];
- const day = date.getDate().toString().padStart(2, " ");
- const now = new Date();
- const sixMonthsAgo = new Date(now.getTime() - 180 * 24 * 60 * 60 * 1000);
-
- if (date > sixMonthsAgo) {
- const hours = date.getHours().toString().padStart(2, "0");
- const minutes = date.getMinutes().toString().padStart(2, "0");
- return `${month} ${day} ${hours}:${minutes}`;
- }
- return `${month} ${day} ${date.getFullYear()}`;
-}
+import { resolveHostById } from "./host-resolver.js";
+import type { SSHHost } from "../../types/index.js";
+import {
+ startHostTransfer,
+ getTransferStatus,
+ listActiveTransfers,
+ probeHungStreamTransfers,
+ requestTransferCancel,
+ cleanupCancelledTransfer,
+ retryHostTransfer,
+ previewArchiveTransferMethod,
+ type HostTransferDeps,
+} from "./host-transfer.js";
+import { registerFileContentRoutes } from "./file-manager-content-routes.js";
+import { createConnectionLog } from "./file-manager-log.js";
+import { createJumpHostChain } from "./jump-host-chain.js";
+import {
+ ChannelOpenSerializer,
+ execChannel,
+ getSessionSftp,
+ type PendingTOTPSession,
+ type SSHSession,
+} from "./file-manager-session.js";
+import { registerFileListingRoutes } from "./file-manager-list-routes.js";
+import { registerFileOperationRoutes } from "./file-manager-operation-routes.js";
+import { registerFileDownloadRoutes } from "./file-manager-download-routes.js";
+import { registerFileActionRoutes } from "./file-manager-action-routes.js";
const app = express();
@@ -131,519 +60,11 @@ app.use((_req, res, next) => {
const authManager = AuthManager.getInstance();
app.use(authManager.createAuthMiddleware());
-interface JumpHostConfig {
- id: number;
- ip: string;
- port: number;
- username: string;
- password?: string;
- key?: string;
- keyPassword?: string;
- keyType?: string;
- authType?: string;
- credentialId?: number;
- [key: string]: unknown;
-}
-
-async function resolveJumpHost(
- hostId: number,
- userId: string,
-): Promise<JumpHostConfig | null> {
- try {
- const hostResults = await SimpleDBOps.select(
- getDb().select().from(hosts).where(eq(hosts.id, hostId)),
- "ssh_data",
- userId,
- );
-
- if (hostResults.length === 0) {
- return null;
- }
-
- const host = hostResults[0];
- const ownerId = (host.userId || userId) as string;
-
- if (host.credentialId) {
- if (userId !== ownerId) {
- try {
- const { SharedCredentialManager } =
- await import("../utils/shared-credential-manager.js");
- const sharedCredManager = SharedCredentialManager.getInstance();
- const sharedCred = await sharedCredManager.getSharedCredentialForUser(
- hostId,
- userId,
- );
- if (sharedCred) {
- return {
- ...host,
- password: sharedCred.password,
- key: sharedCred.key,
- keyPassword: sharedCred.keyPassword,
- keyType: sharedCred.keyType,
- authType: sharedCred.key
- ? "key"
- : sharedCred.password
- ? "password"
- : "none",
- } as JumpHostConfig;
- }
- } catch {
- // fall through to owner credential lookup
- }
- }
-
- const credentials = await SimpleDBOps.select(
- getDb()
- .select()
- .from(sshCredentials)
- .where(
- and(
- eq(sshCredentials.id, host.credentialId as number),
- eq(sshCredentials.userId, ownerId),
- ),
- ),
- "ssh_credentials",
- ownerId,
- );
-
- if (credentials.length > 0) {
- const credential = credentials[0];
- return {
- ...host,
- password: credential.password as string | undefined,
- key: (credential.key || credential.privateKey) as string | undefined,
- keyPassword: credential.keyPassword as string | undefined,
- keyType: credential.keyType as string | undefined,
- authType: credential.authType as string | undefined,
- } as JumpHostConfig;
- }
- }
-
- return host as JumpHostConfig;
- } catch (error) {
- fileLogger.error("Failed to resolve jump host", error, {
- operation: "resolve_jump_host",
- hostId,
- userId,
- });
- return null;
- }
-}
-
-async function createJumpHostChain(
- jumpHosts: Array<{ hostId: number }>,
- userId: string,
- socks5Config?: SOCKS5Config | null,
-): Promise<SSHClient | null> {
- if (!jumpHosts || jumpHosts.length === 0) {
- return null;
- }
-
- let currentClient: SSHClient | null = null;
- const clients: SSHClient[] = [];
-
- try {
- const jumpHostConfigs: Array<Awaited<ReturnType<typeof resolveJumpHost>>> =
- [];
- for (let i = 0; i < jumpHosts.length; i++) {
- const config = await resolveJumpHost(jumpHosts[i].hostId, userId);
- jumpHostConfigs.push(config);
- }
-
- const totalHops = jumpHostConfigs.length;
-
- for (let i = 0; i < jumpHostConfigs.length; i++) {
- if (!jumpHostConfigs[i]) {
- fileLogger.error(`Jump host ${i + 1} not found`, undefined, {
- operation: "jump_host_chain",
- hostId: jumpHosts[i].hostId,
- hopIndex: i,
- totalHops,
- });
- clients.forEach((c) => c.end());
- return null;
- }
- }
-
- let proxySocket: import("net").Socket | null = null;
- if (socks5Config?.useSocks5) {
- const firstHop = jumpHostConfigs[0]!;
- proxySocket = await createSocks5Connection(
- firstHop.ip,
- firstHop.port || 22,
- socks5Config,
- );
- }
-
- for (let i = 0; i < jumpHostConfigs.length; i++) {
- const jumpHostConfig = jumpHostConfigs[i]!;
-
- const jumpClient = new SSHClient();
- clients.push(jumpClient);
-
- const jumpHostVerifier = await SSHHostKeyVerifier.createHostVerifier(
- jumpHostConfig.id,
- jumpHostConfig.ip,
- jumpHostConfig.port || 22,
- null,
- userId,
- true,
- );
-
- const connected = await new Promise<boolean>((resolve) => {
- const timeout = setTimeout(() => {
- resolve(false);
- }, 30000);
-
- jumpClient.on("ready", () => {
- clearTimeout(timeout);
- resolve(true);
- });
-
- jumpClient.on("error", (err) => {
- clearTimeout(timeout);
- fileLogger.error(
- `Jump host ${i + 1}/${totalHops} connection failed`,
- err,
- {
- operation: "jump_host_connect",
- hostId: jumpHostConfig.id,
- ip: jumpHostConfig.ip,
- hopIndex: i,
- totalHops,
- previousHop:
- i > 0
- ? jumpHostConfigs[i - 1]?.ip
- : proxySocket
- ? "proxy"
- : "direct",
- usedProxySocket: i === 0 && !!proxySocket,
- },
- );
- resolve(false);
- });
-
- const connectConfig: Record<string, unknown> = {
- host: jumpHostConfig.ip?.replace(/^\[|\]$/g, "") || jumpHostConfig.ip,
- port: jumpHostConfig.port || 22,
- username: jumpHostConfig.username,
- tryKeyboard: jumpHostConfig.authType !== "none",
- readyTimeout: 60000,
- hostVerifier: jumpHostVerifier,
- algorithms: {
- kex: [
- "curve25519-sha256",
- "ecdh-sha2-nistp521",
- "ecdh-sha2-nistp384",
- "ecdh-sha2-nistp256",
- "diffie-hellman-group-exchange-sha256",
- "diffie-hellman-group18-sha512",
- "diffie-hellman-group17-sha512",
- "diffie-hellman-group16-sha512",
- "diffie-hellman-group15-sha512",
- "diffie-hellman-group14-sha256",
- "diffie-hellman-group14-sha1",
- "diffie-hellman-group-exchange-sha1",
- "diffie-hellman-group1-sha1",
- ],
- serverHostKey: [
- "ssh-ed25519",
- "ecdsa-sha2-nistp521",
- "ecdsa-sha2-nistp384",
- "ecdsa-sha2-nistp256",
- "rsa-sha2-512",
- "rsa-sha2-256",
- "ssh-rsa",
- "ssh-dss",
- ],
- cipher: SSH_ALGORITHMS.cipher,
- hmac: [
- "hmac-sha2-512",
- "hmac-sha2-256",
- "hmac-sha1",
- "hmac-md5",
- ],
- compress: ["none", "[email protected]", "zlib"],
- },
- };
-
- if (jumpHostConfig.authType === "password" && jumpHostConfig.password) {
- connectConfig.password = jumpHostConfig.password;
- } else if (jumpHostConfig.authType === "key" && jumpHostConfig.key) {
- const cleanKey = jumpHostConfig.key
- .trim()
- .replace(/\r\n/g, "\n")
- .replace(/\r/g, "\n");
- connectConfig.privateKey = Buffer.from(cleanKey, "utf8");
- if (jumpHostConfig.keyPassword) {
- connectConfig.passphrase = jumpHostConfig.keyPassword;
- }
- }
-
- jumpClient.on(
- "keyboard-interactive",
- (
- _name: string,
- _instructions: string,
- _lang: string,
- prompts: Array<{ prompt: string; echo: boolean }>,
- finish: (responses: string[]) => void,
- ) => {
- const responses = prompts.map((p) => {
- if (/password/i.test(p.prompt) && jumpHostConfig.password) {
- return jumpHostConfig.password as string;
- }
- return "";
- });
- finish(responses);
- },
- );
-
- if (currentClient) {
- currentClient.forwardOut(
- "127.0.0.1",
- 0,
- jumpHostConfig.ip,
- jumpHostConfig.port || 22,
- (err, stream) => {
- if (err) {
- clearTimeout(timeout);
- resolve(false);
- return;
- }
- connectConfig.sock = stream;
- jumpClient.connect(connectConfig);
- },
- );
- } else if (proxySocket) {
- connectConfig.sock = proxySocket;
- jumpClient.connect(connectConfig);
- } else {
- jumpClient.connect(connectConfig);
- }
- });
-
- if (!connected) {
- clients.forEach((c) => c.end());
- return null;
- }
-
- currentClient = jumpClient;
- }
-
- return currentClient;
- } catch (error) {
- fileLogger.error("Failed to create jump host chain", error, {
- operation: "jump_host_chain",
- });
- clients.forEach((c) => c.end());
- return null;
- }
-}
-
-// Serializes SSH channel open requests so only one channel negotiation is
-// in-flight at a time per session. Once the channel is established the slot
-// is released immediately so the next open can proceed; the channels
-// themselves remain open concurrently (one exec per command is short-lived,
-// the SFTP channel is long-lived but only opened once).
-class ChannelOpenSerializer {
- private tail: Promise<void> = Promise.resolve();
-
- // Enqueue an action that opens a channel. The action runs after the previous
- // one completes (success or failure). Returns a promise that resolves with
- // the action's result.
- run<T>(action: () => Promise<T>): Promise<T> {
- const next = this.tail.then(
- () => action(),
- () => action(), // run even if the previous open failed
- );
- // Advance tail past this slot (swallow result so the chain keeps going)
- this.tail = next.then(
- () => {},
- () => {},
- );
- return next;
- }
-}
-
-interface SSHSession {
- client: SSHClient;
- isConnected: boolean;
- lastActive: number;
- timeout?: NodeJS.Timeout;
- activeOperations: number;
- sudoPassword?: string;
- sftp?: import("ssh2").SFTPWrapper;
- sftpPending?: Promise<import("ssh2").SFTPWrapper>;
- channelOpener: ChannelOpenSerializer;
- poolKey?: string;
- userId?: string;
-}
-
-interface PendingTOTPSession {
- client: SSHClient;
- finish: (responses: string[]) => void;
- config: import("ssh2").ConnectConfig;
- createdAt: number;
- sessionId: string;
- hostId?: number;
- ip?: string;
- port?: number;
- username?: string;
- userId?: string;
- prompts?: Array<{ prompt: string; echo: boolean }>;
- totpPromptIndex?: number;
- resolvedPassword?: string;
- totpAttempts: number;
- isWarpgate?: boolean;
-}
-
const sshSessions: Record<string, SSHSession> = {};
const pendingTOTPSessions: Record<string, PendingTOTPSession> = {};
// Keyed by "sessionId:path" to prevent concurrent requests for the same path
const activeListRequests: Record<string, boolean> = {};
-function execWithSudo(
- session: SSHSession,
- command: string,
- sudoPassword: string,
-): Promise<{ stdout: string; stderr: string; code: number }> {
- return execWithSudoBuffer(session, command, sudoPassword).then((result) => ({
- stdout: result.stdout.toString("utf8"),
- stderr: result.stderr,
- code: result.code,
- }));
-}
-
-function execWithSudoBuffer(
- session: SSHSession,
- command: string,
- sudoPassword: string,
-): Promise<{ stdout: Buffer; stderr: string; code: number }> {
- return new Promise((resolve) => {
- const escapedPassword = sudoPassword.replace(/'/g, "'\"'\"'");
- const sudoCommand = `echo '${escapedPassword}' | sudo -S ${command} 2>&1`;
-
- execChannel(session, sudoCommand, (err, stream) => {
- if (err) {
- resolve({ stdout: Buffer.alloc(0), stderr: err.message, code: 1 });
- return;
- }
-
- const stdoutChunks: Buffer[] = [];
- let stderr = "";
-
- stream.on("data", (chunk: Buffer) => {
- stdoutChunks.push(chunk);
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- stderr += chunk.toString();
- });
-
- stream.on("close", (code: number) => {
- let stdout = Buffer.concat(stdoutChunks);
- const sudoPromptMatch = stdout
- .toString("utf8", 0, Math.min(stdout.length, 256))
- .match(/^\[sudo\] password for .+?:\s*/);
- if (sudoPromptMatch) {
- stdout = stdout.subarray(Buffer.byteLength(sudoPromptMatch[0]));
- }
- resolve({ stdout, stderr, code: code || 0 });
- });
-
- stream.on("error", (streamErr: Error) => {
- resolve({
- stdout: Buffer.concat(stdoutChunks),
- stderr: streamErr.message,
- code: 1,
- });
- });
- });
- });
-}
-
-function getSessionSftp(
- session: SSHSession,
-): Promise<import("ssh2").SFTPWrapper> {
- if (session.sftp) {
- return Promise.resolve(session.sftp);
- }
-
- // Serialization: if a channel open is already in flight, join it
- if (session.sftpPending) {
- return session.sftpPending;
- }
-
- const openOnce = (): Promise<import("ssh2").SFTPWrapper> =>
- session.channelOpener.run(
- () =>
- new Promise<import("ssh2").SFTPWrapper>((resolve, reject) => {
- session.client.sftp((err, sftp) => {
- if (err) return reject(err);
- session.sftp = sftp;
- sftp.on("error", () => {
- session.sftp = undefined;
- });
- sftp.on("close", () => {
- session.sftp = undefined;
- });
- resolve(sftp);
- });
- }),
- );
-
- session.sftpPending = openOnce()
- .catch((err: Error) => {
- const isChannelFailure =
- err.message.toLowerCase().includes("channel open failure") ||
- err.message.toLowerCase().includes("open failed");
- if (isChannelFailure) {
- // Single retry after 500ms for transient server-side rate limiting
- return new Promise<import("ssh2").SFTPWrapper>((resolve, reject) =>
- setTimeout(() => openOnce().then(resolve, reject), 500),
- );
- }
- return Promise.reject(err);
- })
- .finally(() => {
- session.sftpPending = undefined;
- });
-
- return session.sftpPending;
-}
-
-// Wraps client.exec through the channel serializer so only one SSH channel
-// negotiation is in-flight at a time. The serializer slot is released as soon
-// as the channel is established (not when it closes), so channels run
-// concurrently once open — we only serialize the *open handshake*.
-function execChannel(
- session: SSHSession,
- command: string,
- callback: (
- err: Error | undefined,
- stream: import("ssh2").ClientChannel,
- ) => void,
-): void {
- session.channelOpener
- .run(
- () =>
- new Promise<import("ssh2").ClientChannel>((resolve, reject) => {
- session.client.exec(command, (err, stream) => {
- if (err) return reject(err);
- resolve(stream);
- });
- }),
- )
- .then(
- (stream) => callback(undefined, stream),
- (err: Error) => callback(err, undefined as never),
- );
-}
-
function cleanupSession(sessionId: string) {
const session = sshSessions[sessionId];
if (session) {
@@ -696,54 +117,379 @@ function verifySessionOwnership(session: SSHSession, userId: string): boolean {
return !session.userId || session.userId === userId;
}
-function getMimeType(fileName: string): string {
- const ext = fileName.split(".").pop()?.toLowerCase();
- const mimeTypes: Record<string, string> = {
- txt: "text/plain",
- json: "application/json",
- js: "text/javascript",
- html: "text/html",
- css: "text/css",
- png: "image/png",
- jpg: "image/jpeg",
- jpeg: "image/jpeg",
- gif: "image/gif",
- pdf: "application/pdf",
- zip: "application/zip",
- tar: "application/x-tar",
- gz: "application/gzip",
+function resolveBrowseHostId(
+ browseSessionId: string,
+ browseSession: SSHSession,
+): number | undefined {
+ if (browseSession.hostId) return browseSession.hostId;
+ const parsed = Number.parseInt(browseSessionId, 10);
+ return Number.isFinite(parsed) ? parsed : undefined;
+}
+
+async function buildDedicatedTransferConnectConfig(
+ host: SSHHost,
+ userId: string,
+ client: SSHClient,
+): Promise<Record<string, unknown>> {
+ const { ip, port, username } = host;
+ const config: Record<string, unknown> = {
+ host: ip?.replace(/^\[|\]$/g, "") || ip,
+ port,
+ username,
+ tryKeyboard: true,
+ keepaliveInterval: 30000,
+ keepaliveCountMax: 120,
+ readyTimeout: 60000,
+ tcpKeepAlive: true,
+ tcpKeepAliveInitialDelay: 5000,
+ hostVerifier: await SSHHostKeyVerifier.createHostVerifier(
+ host.id,
+ ip,
+ port,
+ null,
+ userId,
+ false,
+ ),
+ env: {
+ TERM: "xterm-256color",
+ LANG: "en_US.UTF-8",
+ LC_ALL: "en_US.UTF-8",
+ },
+ algorithms: {
+ kex: [
+ "curve25519-sha256",
+ "ecdh-sha2-nistp521",
+ "ecdh-sha2-nistp384",
+ "ecdh-sha2-nistp256",
+ "diffie-hellman-group-exchange-sha256",
+ "diffie-hellman-group14-sha256",
+ "diffie-hellman-group14-sha1",
+ "diffie-hellman-group-exchange-sha1",
+ "diffie-hellman-group1-sha1",
+ ],
+ serverHostKey: [
+ "ssh-ed25519",
+ "ecdsa-sha2-nistp521",
+ "ecdsa-sha2-nistp384",
+ "ecdsa-sha2-nistp256",
+ "rsa-sha2-512",
+ "rsa-sha2-256",
+ "ssh-rsa",
+ "ssh-dss",
+ ],
+ cipher: SSH_ALGORITHMS.cipher,
+ hmac: [
+ "hmac-sha2-512",
+ "hmac-sha2-256",
+ "hmac-sha1",
+ "hmac-md5",
+ ],
+ compress: ["none", "[email protected]", "zlib"],
+ },
};
- return mimeTypes[ext || ""] || "application/octet-stream";
+
+ const authType = host.authType;
+
+ if (authType === "key" && host.key?.trim()) {
+ const cleanKey = host.key
+ .trim()
+ .replace(/\r\n/g, "\n")
+ .replace(/\r/g, "\n");
+ config.privateKey = Buffer.from(cleanKey, "utf8");
+ if (host.keyPassword) config.passphrase = host.keyPassword;
+ } else if (authType === "password") {
+ if (!host.password) {
+ throw new Error("Password required for transfer connection");
+ }
+ config.password = host.password;
+ } else if (authType === "opkssh") {
+ const { getOPKSSHToken } = await import("./opkssh-auth.js");
+ const token = await getOPKSSHToken(userId, host.id);
+ if (!token) {
+ throw new Error(
+ "OPKSSH authentication required. Open a Terminal connection to this host first.",
+ );
+ }
+ const { setupOPKSSHCertAuth } = await import("./opkssh-cert-auth.js");
+ await setupOPKSSHCertAuth(
+ config as import("ssh2").ConnectConfig,
+ client,
+ token,
+ username,
+ );
+ } else if (authType !== "none") {
+ throw new Error(`Unsupported auth type for transfer: ${authType}`);
+ }
+
+ return config;
}
-function detectBinary(buffer: Buffer): boolean {
- if (buffer.length === 0) return false;
+function attachDedicatedKeyboardInteractive(
+ client: SSHClient,
+ host: SSHHost,
+): void {
+ client.on(
+ "keyboard-interactive",
+ (
+ _name: string,
+ _instructions: string,
+ _instructionsLang: string,
+ prompts: Array<{ prompt: string; echo: boolean }>,
+ finish: (responses: string[]) => void,
+ ) => {
+ const responses = prompts.map((p) => {
+ if (/password/i.test(p.prompt) && host.password) {
+ return host.password;
+ }
+ return "";
+ });
+ finish(responses);
+ },
+ );
+}
- const sampleSize = Math.min(buffer.length, 8192);
- let nullBytes = 0;
+async function startDedicatedTransferConnect(
+ client: SSHClient,
+ config: Record<string, unknown>,
+ host: SSHHost,
+ userId: string,
+): Promise<void> {
+ const proxyConfig: SOCKS5Config | null =
+ host.useSocks5 &&
+ (host.socks5Host ||
+ (host.socks5ProxyChain && host.socks5ProxyChain.length > 0))
+ ? {
+ useSocks5: host.useSocks5,
+ socks5Host: host.socks5Host,
+ socks5Port: host.socks5Port,
+ socks5Username: host.socks5Username,
+ socks5Password: host.socks5Password,
+ socks5ProxyChain: host.socks5ProxyChain,
+ }
+ : null;
- for (let i = 0; i < sampleSize; i++) {
- const byte = buffer[i];
+ const jumpHosts = host.jumpHosts;
+ const hasJumpHosts = jumpHosts && jumpHosts.length > 0;
- if (byte === 0) {
- nullBytes++;
+ if (hasJumpHosts) {
+ const jumpClient = await createJumpHostChain(
+ jumpHosts,
+ userId,
+ proxyConfig,
+ );
+ if (!jumpClient) {
+ throw new Error("Failed to connect through jump hosts for transfer");
}
- if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {
- if (++nullBytes > 1) return true;
+ await new Promise<void>((resolve, reject) => {
+ jumpClient.forwardOut(
+ "127.0.0.1",
+ 0,
+ host.ip,
+ host.port,
+ (err, stream) => {
+ if (err) {
+ jumpClient.end();
+ reject(
+ new Error(
+ `Failed to forward through jump host for transfer: ${err.message}`,
+ ),
+ );
+ return;
+ }
+ config.sock = stream;
+ client.connect(config);
+ resolve();
+ },
+ );
+ });
+ return;
+ }
+
+ if (proxyConfig) {
+ const proxySocket = await createSocks5Connection(
+ host.ip,
+ host.port,
+ proxyConfig,
+ );
+ if (proxySocket) {
+ config.sock = proxySocket;
}
}
- return nullBytes / sampleSize > 0.01;
+ client.connect(config);
}
-/**
- * @openapi
- * /ssh/file_manager/ssh/connect:
- * post:
- * summary: Connect to SSH for file management
- * description: Establishes an SSH/SFTP connection for file manager operations. Supports password, key-based, and keyboard-interactive authentication, as well as jump hosts and SOCKS5 proxies.
- * tags:
+async function openDedicatedTransferSession(
+ browseSessionId: string,
+ dedicatedSessionId: string,
+ userId: string,
+ transferId: string,
+ options?: { allowBrowseDisconnected?: boolean },
+): Promise<SSHSession> {
+ const browseSession = sshSessions[browseSessionId];
+ if (!options?.allowBrowseDisconnected && !browseSession?.isConnected) {
+ throw new Error("Browse SSH session not connected");
+ }
+ if (browseSession && !verifySessionOwnership(browseSession, userId)) {
+ throw new Error("Session access denied");
+ }
+
+ const hostId = browseSession
+ ? resolveBrowseHostId(browseSessionId, browseSession)
+ : (() => {
+ const parsed = Number.parseInt(browseSessionId, 10);
+ return Number.isFinite(parsed) ? parsed : undefined;
+ })();
+ if (!hostId) {
+ throw new Error("Cannot open transfer connection: unknown host");
+ }
+
+ const host = await resolveHostById(hostId, userId);
+ if (!host) {
+ throw new Error("Host not found for transfer connection");
+ }
+
+ if (sshSessions[dedicatedSessionId]?.isConnected) {
+ closeDedicatedTransferSession(dedicatedSessionId);
+ }
+
+ const client = new SSHClient();
+ attachDedicatedKeyboardInteractive(client, host);
+ const config = await buildDedicatedTransferConnectConfig(
+ host,
+ userId,
+ client,
+ );
+
+ fileLogger.info("Opening dedicated transfer SSH session", {
+ operation: "transfer_ssh_connect",
+ transferId,
+ browseSessionId,
+ dedicatedSessionId,
+ hostId,
+ ip: host.ip,
+ port: host.port,
+ username: host.username,
+ });
+
+ await new Promise<void>((resolve, reject) => {
+ const connectTimeout = setTimeout(() => {
+ client.end();
+ reject(new Error("Transfer SSH connection timed out"));
+ }, 60000);
+
+ const fail = (err: Error) => {
+ clearTimeout(connectTimeout);
+ reject(err);
+ };
+
+ client.once("ready", () => {
+ clearTimeout(connectTimeout);
+ resolve();
+ });
+ client.once("error", fail);
+
+ void startDedicatedTransferConnect(client, config, host, userId).catch(
+ fail,
+ );
+ });
+
+ const session: SSHSession = {
+ client,
+ isConnected: true,
+ lastActive: Date.now(),
+ activeOperations: 0,
+ channelOpener: new ChannelOpenSerializer(),
+ userId,
+ ip: host.ip,
+ port: host.port,
+ hostId: host.id,
+ username: host.username,
+ transferDedicated: true,
+ transferId,
+ browseSessionId,
+ };
+
+ client.on("close", () => {
+ fileLogger.info("Dedicated transfer SSH connection closed", {
+ operation: "transfer_ssh_disconnected",
+ transferId,
+ dedicatedSessionId,
+ browseSessionId,
+ hostId,
+ });
+ const existing = sshSessions[dedicatedSessionId];
+ if (existing) {
+ existing.isConnected = false;
+ closeDedicatedTransferSession(dedicatedSessionId);
+ }
+ });
+
+ sshSessions[dedicatedSessionId] = session;
+ return session;
+}
+
+function closeDedicatedTransferSession(sessionId: string): void {
+ const session = sshSessions[sessionId];
+ if (!session?.transferDedicated) return;
+
+ fileLogger.info("Closing dedicated transfer SSH session", {
+ operation: "transfer_ssh_close",
+ sessionId,
+ transferId: session.transferId,
+ browseSessionId: session.browseSessionId,
+ });
+
+ try {
+ if (session.sftp) {
+ session.sftp.end();
+ session.sftp = undefined;
+ }
+ } catch {
+ // expected
+ }
+ session.sftpPending = undefined;
+
+ try {
+ session.client.end();
+ } catch {
+ // expected
+ }
+
+ clearTimeout(session.timeout);
+ delete sshSessions[sessionId];
+}
+
+app.use("/ssh/file_manager/ssh", (req, res, next) => {
+ if (
+ req.path === "/connect" ||
+ req.path === "/connect-totp" ||
+ req.path === "/connect-warpgate"
+ ) {
+ return next();
+ }
+ const sessionId = (req.query.sessionId as string) || req.body?.sessionId;
+ if (!sessionId) return next();
+ const session = sshSessions[sessionId];
+ if (!session) return next();
+ const userId = (req as AuthenticatedRequest).userId;
+ if (!verifySessionOwnership(session, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+ next();
+});
+
+/**
+ * @openapi
+ * /ssh/file_manager/ssh/connect:
+ * post:
+ * summary: Connect to SSH for file management
+ * description: Establishes an SSH/SFTP connection for file manager operations. Supports password, key-based, and keyboard-interactive authentication, as well as jump hosts and SOCKS5 proxies.
+ * tags:
* - File Manager
* requestBody:
* required: true
@@ -976,11 +722,17 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
};
let hostKeepaliveInterval: number | undefined;
let hostKeepaliveCountMax: number | undefined;
+ let resolvedIp = ip;
+ let resolvedPort = port;
+ let resolvedUsername = username;
if (hostId && userId && !password && !sshKey) {
try {
const { resolveHostById } = await import("./host-resolver.js");
const resolvedHost = await resolveHostById(hostId, userId);
if (resolvedHost) {
+ resolvedIp = resolvedHost.ip;
+ resolvedPort = resolvedHost.port;
+ resolvedUsername = resolvedHost.username;
resolvedCredentials = {
password: resolvedHost.password,
sshKey: resolvedHost.key,
@@ -1011,6 +763,9 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
const { resolveHostById } = await import("./host-resolver.js");
const resolvedHost = await resolveHostById(hostId, userId);
if (resolvedHost) {
+ resolvedIp = resolvedHost.ip;
+ resolvedPort = resolvedHost.port;
+ resolvedUsername = resolvedHost.username;
resolvedCredentials = {
password: resolvedHost.password,
sshKey: resolvedHost.key,
@@ -1039,9 +794,9 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
}
const config: Record<string, unknown> = {
- host: ip?.replace(/^\[|\]$/g, "") || ip,
- port,
- username,
+ host: resolvedIp?.replace(/^\[|\]$/g, "") || resolvedIp,
+ port: resolvedPort,
+ username: resolvedUsername,
tryKeyboard: true,
keepaliveInterval:
typeof hostKeepaliveInterval === "number"
@@ -1054,8 +809,8 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
tcpKeepAliveInitialDelay: 30000,
hostVerifier: await SSHHostKeyVerifier.createHostVerifier(
hostId,
- ip,
- port,
+ resolvedIp,
+ resolvedPort,
null,
userId,
false,
@@ -1317,6 +1072,10 @@ app.post("/ssh/file_manager/ssh/connect", async (req, res) => {
activeOperations: 0,
channelOpener: new ChannelOpenSerializer(),
userId,
+ ip,
+ port,
+ hostId,
+ username,
sudoPassword: resolvedCredentials.sudoPassword,
};
scheduleSessionCleanup(sessionId);
@@ -1963,6 +1722,10 @@ app.post("/ssh/file_manager/ssh/connect-totp", async (req, res) => {
activeOperations: 0,
channelOpener: new ChannelOpenSerializer(),
userId,
+ ip: session.ip,
+ port: session.port,
+ hostId: session.hostId,
+ username: session.username,
};
scheduleSessionCleanup(sessionId);
@@ -2166,6 +1929,10 @@ app.post("/ssh/file_manager/ssh/connect-warpgate", async (req, res) => {
activeOperations: 0,
channelOpener: new ChannelOpenSerializer(),
userId,
+ ip: session.ip,
+ port: session.port,
+ hostId: session.hostId,
+ username: session.username,
};
scheduleSessionCleanup(sessionId);
@@ -2317,3149 +2084,36 @@ app.post("/ssh/file_manager/sudo-password", (req, res) => {
* /ssh/file_manager/ssh/status:
* get:
* summary: Get SSH connection status
- * description: Checks the status of an SSH connection for file manager.
- * tags:
- * - File Manager
- * parameters:
- * - in: query
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: SSH connection status.
- */
-app.get("/ssh/file_manager/ssh/status", (req, res) => {
- const sessionId = req.query.sessionId as string;
- const userId = (req as AuthenticatedRequest).userId;
- const session = sshSessions[sessionId];
- if (session && !verifySessionOwnership(session, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
- const isConnected = !!session?.isConnected;
- res.json({ status: "success", connected: isConnected });
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/keepalive:
- * post:
- * summary: Keep SSH session alive
- * description: Keeps an active SSH session for file manager alive.
- * tags:
- * - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * responses:
- * 200:
- * description: Session keepalive successful.
- * 400:
- * description: Session ID is required or session not found.
- */
-app.post("/ssh/file_manager/ssh/keepalive", async (req, res) => {
- const { sessionId } = req.body;
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- const session = sshSessions[sessionId];
-
- if (!session || !session.isConnected) {
- return res.status(400).json({
- error: "SSH session not found or not connected",
- connected: false,
- });
- }
-
- if (!verifySessionOwnership(session, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- session.lastActive = Date.now();
- scheduleSessionCleanup(sessionId);
-
- // Probe the cached SFTP channel. If stale, clear it so the next operation
- // opens a fresh one via the serialized getSessionSftp.
- if (session.sftp && !session.sftpPending) {
- try {
- await new Promise<void>((resolve, reject) => {
- session.sftp!.stat("/", (err) => (err ? reject(err) : resolve()));
- });
- } catch {
- session.sftp = undefined;
- }
- }
-
- res.json({
- status: "success",
- connected: true,
- message: "Session keepalive successful",
- lastActive: session.lastActive,
- });
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/listFiles:
- * get:
- * summary: List files in a directory
- * description: Lists the files and directories in a given path on the remote host.
- * tags:
- * - File Manager
- * parameters:
- * - in: query
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: query
- * name: path
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: A list of files and directories.
- * 400:
- * description: Session ID is required or SSH connection not established.
- * 500:
- * description: Failed to list files.
- */
-app.get("/ssh/file_manager/ssh/listFiles", (req, res) => {
- const sessionId = req.query.sessionId as string;
- const sshConn = sshSessions[sessionId];
- const sshPath = decodeURIComponent((req.query.path as string) || "/");
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- // Drop concurrent requests for the same session+path — each would open
- // a new SSH channel and can exceed the server's per-connection channel limit.
- const listKey = `${sessionId}:${sshPath}`;
- if (activeListRequests[listKey]) {
- return res.status(409).json({ error: "List request already in progress" });
- }
- activeListRequests[listKey] = true;
- res.on("finish", () => {
- delete activeListRequests[listKey];
- });
-
- sshConn.lastActive = Date.now();
- sshConn.activeOperations++;
- const trySFTP = () => {
- try {
- fileLogger.info("Opening SFTP channel", {
- operation: "file_sftp_open",
- sessionId,
- userId,
- path: sshPath,
- });
- getSessionSftp(sshConn)
- .then((sftp) => {
- sftp.readdir(sshPath, (readdirErr, list) => {
- if (readdirErr) {
- fileLogger.warn(
- `SFTP readdir failed, trying fallback: ${readdirErr.message}`,
- );
- tryFallbackMethod();
- return;
- }
-
- const symlinks: Array<{ index: number; path: string }> = [];
- const files: Array<{
- name: string;
- type: string;
- size: number | undefined;
- modified: string;
- permissions: string;
- owner: string;
- group: string;
- linkTarget: string | undefined;
- path: string;
- executable: boolean;
- }> = [];
-
- for (const entry of list) {
- if (entry.filename === "." || entry.filename === "..") continue;
-
- const attrs = entry.attrs;
- const permissions = modeToPermissions(attrs.mode);
- const isDirectory = attrs.isDirectory();
- const isLink = attrs.isSymbolicLink();
-
- const fileEntry = {
- name: entry.filename,
- type: isDirectory ? "directory" : isLink ? "link" : "file",
- size: isDirectory ? undefined : attrs.size,
- modified: formatMtime(attrs.mtime),
- permissions,
- owner: String(attrs.uid),
- group: String(attrs.gid),
- linkTarget: undefined as string | undefined,
- path: `${sshPath.endsWith("/") ? sshPath : sshPath + "/"}${entry.filename}`,
- executable:
- !isDirectory && !isLink
- ? isExecutableFile(permissions, entry.filename)
- : false,
- };
-
- if (isLink) {
- symlinks.push({ index: files.length, path: fileEntry.path });
- }
-
- files.push(fileEntry);
- }
-
- if (symlinks.length === 0) {
- sshConn.activeOperations--;
- return res.json({ files, path: sshPath });
- }
-
- let resolved = 0;
- let responded = false;
-
- const sendResponse = () => {
- if (responded) return;
- responded = true;
- sshConn.activeOperations--;
- res.json({ files, path: sshPath });
- };
-
- const readlinkTimeout = setTimeout(sendResponse, 5000);
-
- for (const link of symlinks) {
- sftp.readlink(link.path, (linkErr, target) => {
- resolved++;
- if (!linkErr && target) {
- files[link.index].linkTarget = target;
- }
- if (resolved === symlinks.length) {
- clearTimeout(readlinkTimeout);
- sendResponse();
- }
- });
- }
- });
- })
- .catch((err: Error) => {
- fileLogger.warn(
- `SFTP failed for listFiles, trying fallback: ${err.message}`,
- );
- const isChannelFailure =
- err.message.toLowerCase().includes("channel open failure") ||
- err.message.toLowerCase().includes("open failed");
- if (isChannelFailure) {
- sshConn.isConnected = false;
- sshConn.sftp = undefined;
- }
- tryFallbackMethod();
- });
- } catch (sftpErr: unknown) {
- const errMsg =
- sftpErr instanceof Error ? sftpErr.message : "Unknown error";
- fileLogger.warn(`SFTP connection error, trying fallback: ${errMsg}`);
- tryFallbackMethod();
- }
- };
-
- const tryFallbackMethod = () => {
- if (!sshConn?.isConnected) {
- sshConn.activeOperations--;
- return res
- .status(503)
- .json({ error: "SSH session disconnected", disconnected: true });
- }
- try {
- const escapedPath = sshPath.replace(/'/g, "'\"'\"'");
- execChannel(
- sshConn,
- `command ls -la --color=never '${escapedPath}'`,
- (err, stream) => {
- if (err) {
- sshConn.activeOperations--;
- fileLogger.error("SSH listFiles error:", err);
- return res.status(500).json({ error: err.message });
- }
-
- let data = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- data += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
- });
-
- stream.on("close", (code) => {
- if (code !== 0) {
- const isPermissionDenied =
- errorData.toLowerCase().includes("permission denied") ||
- errorData.toLowerCase().includes("access denied");
-
- if (isPermissionDenied) {
- if (sshConn.sudoPassword) {
- fileLogger.info(
- `Permission denied for listFiles, retrying with sudo: ${sshPath}`,
- );
- tryWithSudo();
- return;
- }
-
- sshConn.activeOperations--;
- fileLogger.warn(
- `Permission denied for listFiles, sudo required: ${sshPath}`,
- );
- return res.status(403).json({
- error: `Permission denied: Cannot access ${sshPath}`,
- needsSudo: true,
- path: sshPath,
- });
- }
-
- sshConn.activeOperations--;
- fileLogger.error(
- `SSH listFiles command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
- );
- return res
- .status(500)
- .json({ error: `Command failed: ${errorData}` });
- }
- sshConn.activeOperations--;
-
- const lines = data.split("\n").filter((line) => line.trim());
- const files = [];
-
- for (let i = 1; i < lines.length; i++) {
- const line = lines[i];
- const parts = line.split(/\s+/);
- if (parts.length >= 9) {
- const permissions = parts[0];
- const owner = parts[2];
- const group = parts[3];
- const size = parseInt(parts[4], 10);
-
- let dateStr = "";
- const nameStartIndex = 8;
-
- if (parts[5] && parts[6] && parts[7]) {
- dateStr = `${parts[5]} ${parts[6]} ${parts[7]}`;
- }
-
- const name = parts.slice(nameStartIndex).join(" ");
- const isDirectory = permissions.startsWith("d");
- const isLink = permissions.startsWith("l");
-
- if (name === "." || name === "..") continue;
-
- let actualName = name;
- let linkTarget = undefined;
- if (isLink && name.includes(" -> ")) {
- const linkParts = name.split(" -> ");
- actualName = linkParts[0];
- linkTarget = linkParts[1];
- }
-
- files.push({
- name: actualName,
- type: isDirectory ? "directory" : isLink ? "link" : "file",
- size: isDirectory ? undefined : size,
- modified: dateStr,
- permissions,
- owner,
- group,
- linkTarget,
- path: `${sshPath.endsWith("/") ? sshPath : sshPath + "/"}${actualName}`,
- executable:
- !isDirectory && !isLink
- ? isExecutableFile(permissions, actualName)
- : false,
- });
- }
- }
-
- res.json({ files, path: sshPath });
- });
- },
- );
- } catch (execErr: unknown) {
- sshConn.activeOperations--;
- const errMsg =
- execErr instanceof Error ? execErr.message : "Unknown error";
- fileLogger.error(`Fallback listFiles exec failed: ${errMsg}`);
- if (!res.headersSent) {
- return res.status(500).json({ error: errMsg });
- }
- }
- };
-
- const tryWithSudo = () => {
- try {
- const escapedPath = sshPath.replace(/'/g, "'\"'\"'");
- const escapedPassword = sshConn.sudoPassword!.replace(/'/g, "'\"'\"'");
- const sudoCommand = `echo '${escapedPassword}' | sudo -S /bin/ls -la --color=never '${escapedPath}' 2>&1`;
-
- execChannel(sshConn, sudoCommand, (err, stream) => {
- if (err) {
- sshConn.activeOperations--;
- fileLogger.error("SSH sudo listFiles error:", err);
- return res.status(500).json({ error: err.message });
- }
-
- let data = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- data += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
- });
-
- stream.on("close", (code) => {
- sshConn.activeOperations--;
-
- data = data.replace(/\[sudo\] password for .+?:\s*/g, "");
-
- if (
- data.toLowerCase().includes("sorry, try again") ||
- data.toLowerCase().includes("incorrect password") ||
- errorData.toLowerCase().includes("sorry, try again")
- ) {
- sshConn.sudoPassword = undefined;
- return res.status(403).json({
- error: "Sudo authentication failed. Please try again.",
- needsSudo: true,
- sudoFailed: true,
- path: sshPath,
- });
- }
-
- if (code !== 0 && !data.trim()) {
- fileLogger.error(
- `SSH sudo listFiles failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
- );
- return res
- .status(500)
- .json({ error: `Sudo command failed: ${errorData || data}` });
- }
-
- const lines = data.split("\n").filter((line) => line.trim());
- const files: Array<{
- name: string;
- type: string;
- size: number | undefined;
- modified: string;
- permissions: string;
- owner: string;
- group: string;
- linkTarget: string | undefined;
- path: string;
- executable: boolean;
- }> = [];
-
- for (let i = 1; i < lines.length; i++) {
- const line = lines[i];
- const parts = line.split(/\s+/);
- if (parts.length >= 9) {
- const permissions = parts[0];
- const owner = parts[2];
- const group = parts[3];
- const size = parseInt(parts[4], 10);
-
- let dateStr = "";
- const nameStartIndex = 8;
-
- if (parts[5] && parts[6] && parts[7]) {
- dateStr = `${parts[5]} ${parts[6]} ${parts[7]}`;
- }
-
- const name = parts.slice(nameStartIndex).join(" ");
- const isDirectory = permissions.startsWith("d");
- const isLink = permissions.startsWith("l");
-
- if (name === "." || name === "..") continue;
-
- let actualName = name;
- let linkTarget = undefined;
- if (isLink && name.includes(" -> ")) {
- const linkParts = name.split(" -> ");
- actualName = linkParts[0];
- linkTarget = linkParts[1];
- }
-
- files.push({
- name: actualName,
- type: isDirectory ? "directory" : isLink ? "link" : "file",
- size: isDirectory ? undefined : size,
- modified: dateStr,
- permissions,
- owner,
- group,
- linkTarget,
- path: `${sshPath.endsWith("/") ? sshPath : sshPath + "/"}${actualName}`,
- executable:
- !isDirectory && !isLink
- ? isExecutableFile(permissions, actualName)
- : false,
- });
- }
- }
-
- res.json({ files, path: sshPath });
- });
- });
- } catch (execErr: unknown) {
- sshConn.activeOperations--;
- const errMsg =
- execErr instanceof Error ? execErr.message : "Unknown error";
- fileLogger.error(`Sudo listFiles exec failed: ${errMsg}`);
- if (!res.headersSent) {
- return res.status(500).json({ error: errMsg });
- }
- }
- };
-
- trySFTP();
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/identifySymlink:
- * get:
- * summary: Identify symbolic link
- * description: Identifies the target of a symbolic link.
- * tags:
- * - File Manager
- * parameters:
- * - in: query
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: query
- * name: path
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: Symbolic link information.
- * 400:
- * description: Missing required parameters or SSH connection not established.
- * 500:
- * description: Failed to identify symbolic link.
- */
-app.get("/ssh/file_manager/ssh/identifySymlink", (req, res) => {
- const sessionId = req.query.sessionId as string;
- const sshConn = sshSessions[sessionId];
- const linkPath = decodeURIComponent(req.query.path as string);
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- if (!linkPath) {
- return res.status(400).json({ error: "Link path is required" });
- }
-
- sshConn.lastActive = Date.now();
-
- const escapedPath = linkPath.replace(/'/g, "'\"'\"'");
- const command = `stat -L -c "%F" '${escapedPath}' && readlink -f '${escapedPath}'`;
-
- execChannel(sshConn, command, (err, stream) => {
- if (err) {
- fileLogger.error("SSH identifySymlink error:", err);
- return res.status(500).json({ error: err.message });
- }
-
- let data = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- data += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
- });
-
- stream.on("close", (code) => {
- if (code !== 0) {
- fileLogger.error(
- `SSH identifySymlink command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
- );
- return res.status(500).json({ error: `Command failed: ${errorData}` });
- }
-
- const [fileType, target] = data.trim().split("\n");
-
- res.json({
- path: linkPath,
- target: target,
- type: fileType.toLowerCase().includes("directory")
- ? "directory"
- : "file",
- });
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.error("SSH identifySymlink stream error:", streamErr);
- if (!res.headersSent) {
- res.status(500).json({ error: `Stream error: ${streamErr.message}` });
- }
- });
- });
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/resolvePath:
- * get:
- * summary: Resolve a path with environment variables
- * description: Expands environment variables and ~ in a path via the SSH session.
- * tags:
- * - File Manager
- * parameters:
- * - in: query
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: query
- * name: path
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: The resolved absolute path.
- * 400:
- * description: Missing required parameters.
- * 500:
- * description: Failed to resolve path.
- */
-app.get("/ssh/file_manager/ssh/resolvePath", (req, res) => {
- const sessionId = req.query.sessionId as string;
- const sshConn = sshSessions[sessionId];
- const rawPath = decodeURIComponent(req.query.path as string);
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- if (!rawPath) {
- return res.status(400).json({ error: "Path is required" });
- }
-
- sshConn.lastActive = Date.now();
-
- let command: string;
- if (rawPath.startsWith("~")) {
- const rest = rawPath.substring(1).replace(/'/g, "'\"'\"'");
- command = `echo ~'${rest}'`;
- } else {
- const escapedPath = rawPath.replace(/'/g, "'\"'\"'");
- command = `echo '${escapedPath}'`;
- }
-
- execChannel(sshConn, command, (err, stream) => {
- if (err) {
- fileLogger.error("SSH resolvePath error:", err);
- return res.status(500).json({ error: err.message });
- }
-
- let data = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- data += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
- });
-
- stream.on("close", (code) => {
- if (code !== 0) {
- fileLogger.error(
- `SSH resolvePath command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
- );
- return res.json({ resolvedPath: rawPath });
- }
-
- const resolved = data.trim();
- res.json({ resolvedPath: resolved || rawPath });
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.error("SSH resolvePath stream error:", streamErr);
- if (!res.headersSent) {
- res.json({ resolvedPath: rawPath });
- }
- });
- });
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/readFile:
- * get:
- * summary: Read a file
- * description: Reads the content of a file from the remote host.
- * tags:
- * - File Manager
- * parameters:
- * - in: query
- * name: sessionId
- * required: true
- * schema:
- * type: string
- * - in: query
- * name: path
- * required: true
- * schema:
- * type: string
- * responses:
- * 200:
- * description: The content of the file.
- * 400:
- * description: Missing required parameters or file too large.
- * 404:
- * description: File not found.
- * 500:
- * description: Failed to read file.
- */
-app.get("/ssh/file_manager/ssh/readFile", (req, res) => {
- const sessionId = req.query.sessionId as string;
- const sshConn = sshSessions[sessionId];
- const filePath = decodeURIComponent(req.query.path as string);
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- if (!filePath) {
- return res.status(400).json({ error: "File path is required" });
- }
-
- fileLogger.info("Reading file", {
- operation: "file_read",
- sessionId,
- userId,
- path: filePath,
- });
- sshConn.lastActive = Date.now();
-
- const MAX_READ_SIZE = 500 * 1024 * 1024;
- const escapedPath = filePath.replace(/'/g, "'\"'\"'");
-
- execChannel(
- sshConn,
- `stat -c%s '${escapedPath}' 2>/dev/null || wc -c < '${escapedPath}'`,
- (sizeErr, sizeStream) => {
- if (sizeErr) {
- fileLogger.error("SSH file size check error:", sizeErr);
- return res.status(500).json({ error: sizeErr.message });
- }
-
- let sizeData = "";
- let sizeErrorData = "";
-
- sizeStream.on("data", (chunk: Buffer) => {
- sizeData += chunk.toString();
- });
-
- sizeStream.stderr.on("data", (chunk: Buffer) => {
- sizeErrorData += chunk.toString();
- });
-
- sizeStream.on("close", (sizeCode) => {
- if (sizeCode !== 0) {
- const errorLower = sizeErrorData.toLowerCase();
- const isFileNotFound =
- errorLower.includes("no such file or directory") ||
- errorLower.includes("cannot access") ||
- errorLower.includes("not found") ||
- errorLower.includes("resource not found");
-
- fileLogger.error(`File size check failed: ${sizeErrorData}`);
- return res.status(isFileNotFound ? 404 : 500).json({
- error: `Cannot check file size: ${sizeErrorData}`,
- fileNotFound: isFileNotFound,
- });
- }
-
- const fileSize = parseInt(sizeData.trim(), 10);
-
- if (isNaN(fileSize)) {
- fileLogger.error("Invalid file size response:", sizeData);
- return res.status(500).json({ error: "Cannot determine file size" });
- }
-
- if (fileSize > MAX_READ_SIZE) {
- fileLogger.warn("File too large for reading", {
- operation: "file_read",
- sessionId,
- filePath,
- fileSize,
- maxSize: MAX_READ_SIZE,
- });
- return res.status(400).json({
- error: `File too large to open in editor. Maximum size is ${MAX_READ_SIZE / 1024 / 1024}MB, file is ${(fileSize / 1024 / 1024).toFixed(2)}MB. Use download instead.`,
- fileSize,
- maxSize: MAX_READ_SIZE,
- tooLarge: true,
- });
- }
-
- execChannel(sshConn, `cat '${escapedPath}'`, (err, stream) => {
- if (err) {
- fileLogger.error("SSH readFile error:", err);
- return res.status(500).json({ error: err.message });
- }
-
- let binaryData = Buffer.alloc(0);
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- binaryData = Buffer.concat([binaryData, chunk]);
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
- });
-
- stream.on("close", (code) => {
- if (code !== 0) {
- const isPermissionDenied = errorData
- .toLowerCase()
- .includes("permission denied");
-
- if (isPermissionDenied && sshConn.sudoPassword) {
- execWithSudoBuffer(
- sshConn,
- `cat '${escapedPath}'`,
- sshConn.sudoPassword,
- )
- .then((result) => {
- if (result.code !== 0) {
- return res.status(403).json({
- error: `Permission denied: ${result.stderr || result.stdout.toString("utf8")}`,
- needsSudo: true,
- });
- }
-
- const sudoData = result.stdout;
- const isBinary = detectBinary(sudoData);
- res.json({
- content: isBinary
- ? sudoData.toString("base64")
- : sudoData.toString("utf8"),
- isBinary,
- size: sudoData.length,
- });
- })
- .catch(() => {
- res
- .status(403)
- .json({ error: "Permission denied", needsSudo: true });
- });
- return;
- }
-
- fileLogger.error(
- `SSH readFile command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
- );
-
- const isFileNotFound =
- errorData.includes("No such file or directory") ||
- errorData.includes("cannot access") ||
- errorData.includes("not found");
-
- return res.status(isFileNotFound ? 404 : 500).json({
- error: `Command failed: ${errorData}`,
- fileNotFound: isFileNotFound,
- });
- }
-
- const isBinary = detectBinary(binaryData);
- fileLogger.success("File read successfully", {
- operation: "file_read_success",
- sessionId,
- userId,
- path: filePath,
- bytes: binaryData.length,
- });
-
- if (isBinary) {
- const base64Content = binaryData.toString("base64");
- res.json({
- content: base64Content,
- path: filePath,
- encoding: "base64",
- });
- } else {
- const textContent = binaryData.toString("utf8");
- res.json({
- content: textContent,
- path: filePath,
- encoding: "utf8",
- });
- }
- });
- });
- });
- },
- );
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/writeFile:
- * post:
- * summary: Write to a file
- * description: Writes content to a file on the remote host and preserves the existing permissions when the file already exists.
- * tags:
- * - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * path:
- * type: string
- * content:
- * type: string
- * responses:
- * 200:
- * description: File written successfully.
- * 400:
- * description: Missing required parameters or SSH connection not established.
- * 500:
- * description: Failed to write file.
- */
-app.post("/ssh/file_manager/ssh/writeFile", async (req, res) => {
- const { sessionId, path: filePath, content } = req.body;
- const sshConn = sshSessions[sessionId];
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- if (!filePath) {
- return res.status(400).json({ error: "File path is required" });
- }
-
- if (content === undefined) {
- return res.status(400).json({ error: "File content is required" });
- }
-
- const contentLength =
- typeof content === "string" ? content.length : Buffer.byteLength(content);
- fileLogger.info("Writing file", {
- operation: "file_write",
- sessionId,
- userId,
- path: filePath,
- bytes: contentLength,
- });
- sshConn.lastActive = Date.now();
-
- let preservedMode: number | undefined;
-
- const restoreOriginalMode = (
- sftp: import("ssh2").SFTPWrapper | null,
- onComplete: () => void,
- ) => {
- if (preservedMode === undefined) {
- onComplete();
- return;
- }
-
- const permissions = preservedMode.toString(8);
-
- if (sftp) {
- sftp.chmod(filePath, preservedMode, (chmodErr) => {
- if (chmodErr) {
- fileLogger.warn("Failed to restore file permissions after save", {
- operation: "file_write_restore_permissions",
- sessionId,
- userId,
- path: filePath,
- permissions,
- error: chmodErr.message,
- });
- } else {
- fileLogger.info("Restored file permissions after save", {
- operation: "file_write_restore_permissions",
- sessionId,
- userId,
- path: filePath,
- permissions,
- });
- }
-
- onComplete();
- });
- return;
- }
-
- const escapedPath = filePath.replace(/'/g, "'\"'\"'");
- const chmodCommand = `chmod ${permissions} '${escapedPath}' && echo "SUCCESS"`;
-
- execChannel(sshConn, chmodCommand, (err, stream) => {
- if (err) {
- fileLogger.warn("Failed to restore file permissions after save", {
- operation: "file_write_restore_permissions",
- sessionId,
- userId,
- path: filePath,
- permissions,
- error: err.message,
- });
- onComplete();
- return;
- }
-
- let outputData = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- outputData += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
- });
-
- stream.on("close", (code) => {
- if (outputData.includes("SUCCESS")) {
- fileLogger.info("Restored file permissions after save", {
- operation: "file_write_restore_permissions",
- sessionId,
- userId,
- path: filePath,
- permissions,
- });
- } else {
- fileLogger.warn("Failed to restore file permissions after save", {
- operation: "file_write_restore_permissions",
- sessionId,
- userId,
- path: filePath,
- permissions,
- exitCode: code,
- error:
- errorData || "Permission restore command did not report success",
- });
- }
-
- onComplete();
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.warn("Failed to restore file permissions after save", {
- operation: "file_write_restore_permissions",
- sessionId,
- userId,
- path: filePath,
- permissions,
- error: streamErr.message,
- });
- onComplete();
- });
- });
- };
-
- const trySFTP = () => {
- try {
- fileLogger.info("Opening SFTP channel", {
- operation: "file_sftp_open",
- sessionId,
- userId,
- path: filePath,
- });
- getSessionSftp(sshConn)
- .then((sftp) => {
- let fileBuffer;
- try {
- if (typeof content === "string") {
- try {
- const testBuffer = Buffer.from(content, "base64");
- if (testBuffer.toString("base64") === content) {
- fileBuffer = testBuffer;
- } else {
- fileBuffer = Buffer.from(content, "utf8");
- }
- } catch {
- fileBuffer = Buffer.from(content, "utf8");
- }
- } else if (Buffer.isBuffer(content)) {
- fileBuffer = content;
- } else {
- fileBuffer = Buffer.from(content);
- }
- } catch (bufferErr) {
- fileLogger.error("Buffer conversion error:", bufferErr);
- if (!res.headersSent) {
- return res
- .status(500)
- .json({ error: "Invalid file content format" });
- }
- return;
- }
-
- sftp.stat(filePath, (statErr, stats) => {
- try {
- if (statErr) {
- fileLogger.warn(
- "Failed to read existing file permissions before save",
- {
- operation: "file_write_stat",
- sessionId,
- userId,
- path: filePath,
- error: statErr.message,
- },
- );
- } else if (stats.isFile()) {
- preservedMode = stats.mode & 0o7777;
- }
-
- const writeStream = sftp.createWriteStream(filePath);
-
- let hasError = false;
- let hasFinished = false;
- let isFinalizing = false;
-
- const finalizeSuccess = () => {
- if (hasError || hasFinished) return;
- hasFinished = true;
- isFinalizing = false;
- fileLogger.success("File written successfully", {
- operation: "file_write_success",
- sessionId,
- userId,
- path: filePath,
- bytes: fileBuffer.length,
- });
- if (!res.headersSent) {
- res.json({
- message: "File written successfully",
- path: filePath,
- toast: {
- type: "success",
- message: `File written: ${filePath}`,
- },
- });
- }
- };
-
- writeStream.on("error", (streamErr) => {
- if (hasError || hasFinished || isFinalizing) return;
- hasError = true;
- isFinalizing = false;
- fileLogger.warn(
- `SFTP write failed, trying fallback method: ${streamErr.message}`,
- );
- tryFallbackMethod();
- });
-
- const finishWrite = () => {
- if (hasError || hasFinished || isFinalizing) return;
- isFinalizing = true;
- restoreOriginalMode(sftp, finalizeSuccess);
- };
-
- writeStream.on("finish", () => {
- finishWrite();
- });
-
- writeStream.on("close", () => {
- finishWrite();
- });
-
- try {
- writeStream.write(fileBuffer);
- writeStream.end();
- } catch (writeErr) {
- if (hasError || hasFinished) return;
- hasError = true;
- isFinalizing = false;
- fileLogger.warn(
- `SFTP write operation failed, trying fallback method: ${(writeErr as Error).message}`,
- );
- tryFallbackMethod();
- }
- } catch (callbackErr) {
- fileLogger.warn(
- `SFTP stat callback error, trying fallback method: ${(callbackErr as Error).message}`,
- );
- tryFallbackMethod();
- }
- });
- })
- .catch((err: Error) => {
- fileLogger.warn(
- `SFTP failed, trying fallback method: ${err.message}`,
- );
- tryFallbackMethod();
- });
- } catch (sftpErr) {
- fileLogger.warn(
- `SFTP connection error, trying fallback method: ${(sftpErr as Error).message}`,
- );
- tryFallbackMethod();
- }
- };
-
- const tryFallbackMethod = () => {
- if (!sshConn?.isConnected) {
- if (!res.headersSent) {
- return res.status(500).json({ error: "SSH session disconnected" });
- }
- return;
- }
- try {
- let contentBuffer: Buffer;
- if (typeof content === "string") {
- try {
- contentBuffer = Buffer.from(content, "base64");
- if (contentBuffer.toString("base64") !== content) {
- contentBuffer = Buffer.from(content, "utf8");
- }
- } catch {
- contentBuffer = Buffer.from(content, "utf8");
- }
- } else if (Buffer.isBuffer(content)) {
- contentBuffer = content;
- } else {
- contentBuffer = Buffer.from(content);
- }
- const base64Content = contentBuffer.toString("base64");
- const escapedPath = filePath.replace(/'/g, "'\"'\"'");
-
- const writeCommand = `echo '${base64Content}' | base64 -d > '${escapedPath}' && echo "SUCCESS"`;
-
- execChannel(sshConn, writeCommand, (err, stream) => {
- if (err) {
- fileLogger.error("Fallback write command failed:", err);
- if (!res.headersSent) {
- return res.status(500).json({
- error: `Write failed: ${err.message}`,
- toast: {
- type: "error",
- message: `Write failed: ${err.message}`,
- },
- });
- }
- return;
- }
-
- let outputData = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- outputData += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
- });
-
- stream.stderr.on("error", (stderrErr) => {
- fileLogger.error("Fallback write stderr error:", stderrErr);
- });
-
- stream.on("close", (code) => {
- if (outputData.includes("SUCCESS")) {
- restoreOriginalMode(null, () => {
- if (!res.headersSent) {
- res.json({
- message: "File written successfully",
- path: filePath,
- toast: {
- type: "success",
- message: `File written: ${filePath}`,
- },
- });
- }
- });
- } else {
- const isPermDenied = errorData
- .toLowerCase()
- .includes("permission denied");
- if (isPermDenied && sshConn.sudoPassword) {
- execWithSudo(
- sshConn,
- `bash -c "echo '${base64Content}' | base64 -d > '${escapedPath}' && echo SUCCESS"`,
- sshConn.sudoPassword,
- )
- .then(({ stdout, code: sudoCode }) => {
- if (sudoCode === 0 && stdout.includes("SUCCESS")) {
- restoreOriginalMode(null, () => {
- if (!res.headersSent) {
- res.json({
- message: "File written successfully",
- path: filePath,
- });
- }
- });
- } else if (!res.headersSent) {
- res
- .status(403)
- .json({ error: "Permission denied", needsSudo: true });
- }
- })
- .catch(() => {
- if (!res.headersSent) {
- res
- .status(403)
- .json({ error: "Permission denied", needsSudo: true });
- }
- });
- return;
- }
- fileLogger.error(
- `Fallback write failed with code ${code}: ${errorData}`,
- );
- if (!res.headersSent) {
- res.status(500).json({
- error: `Write failed: ${errorData}`,
- needsSudo: isPermDenied,
- toast: { type: "error", message: `Write failed: ${errorData}` },
- });
- }
- }
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.error("Fallback write stream error:", streamErr);
- if (!res.headersSent) {
- res
- .status(500)
- .json({ error: `Write stream error: ${streamErr.message}` });
- }
- });
- });
- } catch (fallbackErr) {
- fileLogger.error("Fallback method failed:", fallbackErr);
- if (!res.headersSent) {
- res.status(500).json({
- error: `All write methods failed: ${(fallbackErr as Error).message}`,
- });
- }
- }
- };
-
- trySFTP();
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/uploadFile:
- * post:
- * summary: Upload a file
- * description: Uploads a file to the remote host.
- * tags:
- * - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * path:
- * type: string
- * content:
- * type: string
- * fileName:
- * type: string
- * responses:
- * 200:
- * description: File uploaded successfully.
- * 400:
- * description: Missing required parameters or SSH connection not established.
- * 500:
- * description: Failed to upload file.
- */
-app.post("/ssh/file_manager/ssh/uploadFile", async (req, res) => {
- const { sessionId, path: filePath, content, fileName } = req.body;
- const sshConn = sshSessions[sessionId];
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- if (!filePath || !fileName || content === undefined) {
- return res
- .status(400)
- .json({ error: "File path, name, and content are required" });
- }
-
- sshConn.lastActive = Date.now();
-
- const contentSize =
- typeof content === "string"
- ? Buffer.byteLength(content, "utf8")
- : content.length;
-
- const fullPath = filePath.endsWith("/")
- ? filePath + fileName
- : filePath + "/" + fileName;
- const uploadStartTime = Date.now();
- fileLogger.info("File upload started", {
- operation: "file_upload_start",
- sessionId,
- userId,
- path: fullPath,
- bytes: contentSize,
- });
-
- const trySFTP = () => {
- try {
- fileLogger.info("Opening SFTP channel", {
- operation: "file_sftp_open",
- sessionId,
- userId,
- path: fullPath,
- });
- getSessionSftp(sshConn)
- .then((sftp) => {
- let fileBuffer;
- try {
- if (typeof content === "string") {
- fileBuffer = Buffer.from(content, "base64");
- } else if (Buffer.isBuffer(content)) {
- fileBuffer = content;
- } else {
- fileBuffer = Buffer.from(content);
- }
- } catch (bufferErr) {
- fileLogger.error("Buffer conversion error:", bufferErr);
- if (!res.headersSent) {
- return res
- .status(500)
- .json({ error: "Invalid file content format" });
- }
- return;
- }
-
- const writeStream = sftp.createWriteStream(fullPath);
-
- let hasError = false;
- let hasFinished = false;
-
- writeStream.on("error", (streamErr) => {
- if (hasError || hasFinished) return;
- hasError = true;
- fileLogger.warn(
- `SFTP write failed, trying fallback method: ${streamErr.message}`,
- {
- operation: "file_upload",
- sessionId,
- fileName,
- fileSize: contentSize,
- error: streamErr.message,
- },
- );
- tryFallbackMethod();
- });
-
- writeStream.on("finish", () => {
- if (hasError || hasFinished) return;
- hasFinished = true;
- fileLogger.success("File upload completed", {
- operation: "file_upload_complete",
- sessionId,
- userId,
- path: fullPath,
- bytes: fileBuffer.length,
- duration: Date.now() - uploadStartTime,
- });
- if (!res.headersSent) {
- res.json({
- message: "File uploaded successfully",
- path: fullPath,
- toast: {
- type: "success",
- message: `File uploaded: ${fullPath}`,
- },
- });
- }
- });
-
- writeStream.on("close", () => {
- if (hasError || hasFinished) return;
- hasFinished = true;
- fileLogger.success("File upload completed", {
- operation: "file_upload_complete",
- sessionId,
- userId,
- path: fullPath,
- bytes: fileBuffer.length,
- duration: Date.now() - uploadStartTime,
- });
- if (!res.headersSent) {
- res.json({
- message: "File uploaded successfully",
- path: fullPath,
- toast: {
- type: "success",
- message: `File uploaded: ${fullPath}`,
- },
- });
- }
- });
-
- try {
- writeStream.write(fileBuffer);
- writeStream.end();
- } catch (writeErr) {
- if (hasError || hasFinished) return;
- hasError = true;
- fileLogger.warn(
- `SFTP write operation failed, trying fallback method: ${(writeErr as Error).message}`,
- );
- tryFallbackMethod();
- }
- })
- .catch((err: Error) => {
- fileLogger.warn(
- `SFTP failed, trying fallback method: ${err.message}`,
- );
- tryFallbackMethod();
- });
- } catch (sftpErr) {
- fileLogger.warn(
- `SFTP connection error, trying fallback method: ${(sftpErr as Error).message}`,
- );
- tryFallbackMethod();
- }
- };
-
- const tryFallbackMethod = () => {
- if (!sshConn?.isConnected) {
- if (!res.headersSent) {
- return res.status(500).json({ error: "SSH session disconnected" });
- }
- return;
- }
- try {
- let contentBuffer: Buffer;
- if (typeof content === "string") {
- try {
- contentBuffer = Buffer.from(content, "base64");
- if (contentBuffer.toString("base64") !== content) {
- contentBuffer = Buffer.from(content, "utf8");
- }
- } catch {
- contentBuffer = Buffer.from(content, "utf8");
- }
- } else if (Buffer.isBuffer(content)) {
- contentBuffer = content;
- } else {
- contentBuffer = Buffer.from(content);
- }
- const base64Content = contentBuffer.toString("base64");
- const chunkSize = 1000000;
- const chunks = [];
-
- for (let i = 0; i < base64Content.length; i += chunkSize) {
- chunks.push(base64Content.slice(i, i + chunkSize));
- }
-
- if (!sshConn?.isConnected) {
- fileLogger.error("SSH connection lost before fallback upload", {
- operation: "file_upload_fallback",
- sessionId,
- path: fullPath,
- });
- if (!res.headersSent) {
- return res
- .status(500)
- .json({ error: "SSH connection lost during upload" });
- }
- return;
- }
-
- if (chunks.length === 1) {
- const escapedPath = fullPath.replace(/'/g, "'\"'\"'");
-
- const writeCommand = `echo '${chunks[0]}' | base64 -d > '${escapedPath}' && echo "SUCCESS"`;
-
- execChannel(sshConn, writeCommand, (err, stream) => {
- if (err) {
- fileLogger.error("Fallback upload command failed:", err);
- if (!res.headersSent) {
- return res
- .status(500)
- .json({ error: `Upload failed: ${err.message}` });
- }
- return;
- }
-
- let outputData = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- outputData += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
- });
-
- stream.stderr.on("error", (stderrErr) => {
- fileLogger.error("Fallback upload stderr error:", stderrErr);
- });
-
- stream.on("close", (code) => {
- if (outputData.includes("SUCCESS")) {
- if (!res.headersSent) {
- res.json({
- message: "File uploaded successfully",
- path: fullPath,
- toast: {
- type: "success",
- message: `File uploaded: ${fullPath}`,
- },
- });
- }
- } else {
- fileLogger.error(
- `Fallback upload failed with code ${code}: ${errorData}`,
- );
- if (!res.headersSent) {
- res.status(500).json({
- error: `Upload failed: ${errorData}`,
- toast: {
- type: "error",
- message: `Upload failed: ${errorData}`,
- },
- });
- }
- }
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.error("Fallback upload stream error:", streamErr);
- if (!res.headersSent) {
- res
- .status(500)
- .json({ error: `Upload stream error: ${streamErr.message}` });
- }
- });
- });
- } else {
- const escapedPath = fullPath.replace(/'/g, "'\"'\"'");
-
- let writeCommand = `> '${escapedPath}'`;
-
- chunks.forEach((chunk) => {
- writeCommand += ` && echo '${chunk}' | base64 -d >> '${escapedPath}'`;
- });
-
- writeCommand += ` && echo "SUCCESS"`;
-
- execChannel(sshConn, writeCommand, (err, stream) => {
- if (err) {
- fileLogger.error("Chunked fallback upload failed:", err);
- if (!res.headersSent) {
- return res
- .status(500)
- .json({ error: `Chunked upload failed: ${err.message}` });
- }
- return;
- }
-
- let outputData = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- outputData += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
- });
-
- stream.stderr.on("error", (stderrErr) => {
- fileLogger.error(
- "Chunked fallback upload stderr error:",
- stderrErr,
- );
- });
-
- stream.on("close", (code) => {
- if (outputData.includes("SUCCESS")) {
- if (!res.headersSent) {
- res.json({
- message: "File uploaded successfully",
- path: fullPath,
- toast: {
- type: "success",
- message: `File uploaded: ${fullPath}`,
- },
- });
- }
- } else {
- fileLogger.error(
- `Chunked fallback upload failed with code ${code}: ${errorData}`,
- );
- if (!res.headersSent) {
- res.status(500).json({
- error: `Chunked upload failed: ${errorData}`,
- toast: {
- type: "error",
- message: `Chunked upload failed: ${errorData}`,
- },
- });
- }
- }
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.error(
- "Chunked fallback upload stream error:",
- streamErr,
- );
- if (!res.headersSent) {
- res.status(500).json({
- error: `Chunked upload stream error: ${streamErr.message}`,
- });
- }
- });
- });
- }
- } catch (fallbackErr) {
- fileLogger.error("Fallback method failed:", fallbackErr);
- if (!res.headersSent) {
- res
- .status(500)
- .json({ error: `All upload methods failed: ${fallbackErr.message}` });
- }
- }
- };
-
- trySFTP();
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/createFile:
- * post:
- * summary: Create a file
- * description: Creates an empty file on the remote host.
- * tags:
- * - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * path:
- * type: string
- * fileName:
- * type: string
- * responses:
- * 200:
- * description: File created successfully.
- * 400:
- * description: Missing required parameters or SSH connection not established.
- * 403:
- * description: Permission denied.
- * 500:
- * description: Failed to create file.
- */
-app.post("/ssh/file_manager/ssh/createFile", async (req, res) => {
- const { sessionId, path: filePath, fileName } = req.body;
- const sshConn = sshSessions[sessionId];
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- if (!filePath || !fileName) {
- return res.status(400).json({ error: "File path and name are required" });
- }
-
- sshConn.lastActive = Date.now();
-
- const fullPath = filePath.endsWith("/")
- ? filePath + fileName
- : filePath + "/" + fileName;
- const escapedPath = fullPath.replace(/'/g, "'\"'\"'");
-
- const createCommand = `touch '${escapedPath}' && echo "SUCCESS" && exit 0`;
-
- execChannel(sshConn, createCommand, (err, stream) => {
- if (err) {
- fileLogger.error("SSH createFile error:", err);
- if (!res.headersSent) {
- return res.status(500).json({ error: err.message });
- }
- return;
- }
-
- let outputData = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- outputData += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
-
- if (chunk.toString().includes("Permission denied")) {
- fileLogger.error(`Permission denied creating file: ${fullPath}`);
- if (!res.headersSent) {
- return res.status(403).json({
- error: `Permission denied: Cannot create file ${fullPath}. Check directory permissions.`,
- });
- }
- return;
- }
- });
-
- stream.on("close", (code) => {
- if (outputData.includes("SUCCESS")) {
- if (!res.headersSent) {
- res.json({
- message: "File created successfully",
- path: fullPath,
- toast: { type: "success", message: `File created: ${fullPath}` },
- });
- }
- return;
- }
-
- if (code !== 0) {
- fileLogger.error(
- `SSH createFile command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
- );
- if (!res.headersSent) {
- return res.status(500).json({
- error: `Command failed: ${errorData}`,
- toast: {
- type: "error",
- message: `File creation failed: ${errorData}`,
- },
- });
- }
- return;
- }
-
- if (!res.headersSent) {
- res.json({
- message: "File created successfully",
- path: fullPath,
- toast: { type: "success", message: `File created: ${fullPath}` },
- });
- }
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.error("SSH createFile stream error:", streamErr);
- if (!res.headersSent) {
- res.status(500).json({ error: `Stream error: ${streamErr.message}` });
- }
- });
- });
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/createFolder:
- * post:
- * summary: Create a folder
- * description: Creates a new folder on the remote host.
- * tags:
- * - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * path:
- * type: string
- * folderName:
- * type: string
- * responses:
- * 200:
- * description: Folder created successfully.
- * 400:
- * description: Missing required parameters or SSH connection not established.
- * 403:
- * description: Permission denied.
- * 500:
- * description: Failed to create folder.
- */
-app.post("/ssh/file_manager/ssh/createFolder", async (req, res) => {
- const { sessionId, path: folderPath, folderName } = req.body;
- const sshConn = sshSessions[sessionId];
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- if (!folderPath || !folderName) {
- return res.status(400).json({ error: "Folder path and name are required" });
- }
-
- sshConn.lastActive = Date.now();
-
- const fullPath = folderPath.endsWith("/")
- ? folderPath + folderName
- : folderPath + "/" + folderName;
- fileLogger.info("Creating directory", {
- operation: "file_mkdir",
- sessionId,
- userId,
- path: fullPath,
- });
- const escapedPath = fullPath.replace(/'/g, "'\"'\"'");
-
- const createCommand = `mkdir -p '${escapedPath}' && echo "SUCCESS" && exit 0`;
-
- execChannel(sshConn, createCommand, (err, stream) => {
- if (err) {
- fileLogger.error("SSH createFolder error:", err);
- if (!res.headersSent) {
- return res.status(500).json({ error: err.message });
- }
- return;
- }
-
- let outputData = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- outputData += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
-
- if (chunk.toString().includes("Permission denied")) {
- fileLogger.error(`Permission denied creating folder: ${fullPath}`);
- if (!res.headersSent) {
- return res.status(403).json({
- error: `Permission denied: Cannot create folder ${fullPath}. Check directory permissions.`,
- });
- }
- return;
- }
- });
-
- stream.on("close", (code) => {
- if (outputData.includes("SUCCESS")) {
- fileLogger.success("Directory created successfully", {
- operation: "file_mkdir_success",
- sessionId,
- userId,
- path: fullPath,
- });
- if (!res.headersSent) {
- res.json({
- message: "Folder created successfully",
- path: fullPath,
- toast: { type: "success", message: `Folder created: ${fullPath}` },
- });
- }
- return;
- }
-
- if (code !== 0) {
- fileLogger.error(
- `SSH createFolder command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
- );
- if (!res.headersSent) {
- return res.status(500).json({
- error: `Command failed: ${errorData}`,
- toast: {
- type: "error",
- message: `Folder creation failed: ${errorData}`,
- },
- });
- }
- return;
- }
-
- fileLogger.success("Directory created successfully", {
- operation: "file_mkdir_success",
- sessionId,
- userId,
- path: fullPath,
- });
- if (!res.headersSent) {
- res.json({
- message: "Folder created successfully",
- path: fullPath,
- toast: { type: "success", message: `Folder created: ${fullPath}` },
- });
- }
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.error("SSH createFolder stream error:", streamErr);
- if (!res.headersSent) {
- res.status(500).json({ error: `Stream error: ${streamErr.message}` });
- }
- });
- });
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/deleteItem:
- * delete:
- * summary: Delete a file or directory
- * description: Deletes a file or directory on the remote host.
- * tags:
- * - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * path:
- * type: string
- * isDirectory:
- * type: boolean
- * responses:
- * 200:
- * description: Item deleted successfully.
- * 400:
- * description: Missing required parameters or SSH connection not established.
- * 403:
- * description: Permission denied.
- * 500:
- * description: Failed to delete item.
- */
-app.delete("/ssh/file_manager/ssh/deleteItem", async (req, res) => {
- const { sessionId, path: itemPath, isDirectory } = req.body;
- const sshConn = sshSessions[sessionId];
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- if (!itemPath) {
- return res.status(400).json({ error: "Item path is required" });
- }
-
- fileLogger.info("Deleting item", {
- operation: "file_delete",
- sessionId,
- userId,
- path: itemPath,
- type: isDirectory ? "directory" : "file",
- });
- sshConn.lastActive = Date.now();
- const escapedPath = itemPath.replace(/'/g, "'\"'\"'");
-
- const deleteCommand = isDirectory
- ? `rm -rf '${escapedPath}'`
- : `rm -f '${escapedPath}'`;
-
- const executeDelete = (useSudo: boolean): Promise<void> => {
- return new Promise((resolve) => {
- if (useSudo && sshConn.sudoPassword) {
- execWithSudo(sshConn, deleteCommand, sshConn.sudoPassword).then(
- (result) => {
- if (
- result.code === 0 ||
- (!result.stderr.includes("Permission denied") &&
- !result.stdout.includes("Permission denied"))
- ) {
- res.json({
- message: "Item deleted successfully",
- path: itemPath,
- toast: {
- type: "success",
- message: `${isDirectory ? "Directory" : "File"} deleted: ${itemPath}`,
- },
- });
- } else {
- res.status(500).json({
- error: `Delete failed: ${result.stderr || result.stdout}`,
- });
- }
- resolve();
- },
- );
- return;
- }
-
- execChannel(
- sshConn,
- `${deleteCommand} && echo "SUCCESS"`,
- (err, stream) => {
- if (err) {
- fileLogger.error("SSH deleteItem error:", err);
- res.status(500).json({ error: err.message });
- resolve();
- return;
- }
-
- let outputData = "";
- let errorData = "";
- let permissionDenied = false;
-
- stream.on("data", (chunk: Buffer) => {
- outputData += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
- if (chunk.toString().includes("Permission denied")) {
- permissionDenied = true;
- }
- });
-
- stream.on("close", (code) => {
- if (permissionDenied) {
- if (sshConn.sudoPassword) {
- executeDelete(true).then(resolve);
- return;
- }
- fileLogger.error(`Permission denied deleting: ${itemPath}`);
- res.status(403).json({
- error: `Permission denied: Cannot delete ${itemPath}.`,
- needsSudo: true,
- });
- resolve();
- return;
- }
-
- if (outputData.includes("SUCCESS") || code === 0) {
- fileLogger.success("Item deleted successfully", {
- operation: "file_delete_success",
- sessionId,
- userId,
- path: itemPath,
- });
- res.json({
- message: "Item deleted successfully",
- path: itemPath,
- toast: {
- type: "success",
- message: `${isDirectory ? "Directory" : "File"} deleted: ${itemPath}`,
- },
- });
- } else {
- res.status(500).json({
- error: `Command failed: ${errorData}`,
- });
- }
- resolve();
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.error("SSH deleteItem stream error:", streamErr);
- res
- .status(500)
- .json({ error: `Stream error: ${streamErr.message}` });
- resolve();
- });
- },
- );
- });
- };
-
- await executeDelete(false);
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/renameItem:
- * put:
- * summary: Rename a file or directory
- * description: Renames a file or directory on the remote host.
- * tags:
- * - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * oldPath:
- * type: string
- * newName:
- * type: string
- * responses:
- * 200:
- * description: Item renamed successfully.
- * 400:
- * description: Missing required parameters or SSH connection not established.
- * 403:
- * description: Permission denied.
- * 500:
- * description: Failed to rename item.
- */
-app.put("/ssh/file_manager/ssh/renameItem", async (req, res) => {
- const { sessionId, oldPath, newName } = req.body;
- const sshConn = sshSessions[sessionId];
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- if (!oldPath || !newName) {
- return res
- .status(400)
- .json({ error: "Old path and new name are required" });
- }
-
- sshConn.lastActive = Date.now();
-
- const oldDir = oldPath.substring(0, oldPath.lastIndexOf("/") + 1);
- const newPath = oldDir + newName;
- fileLogger.info("Renaming item", {
- operation: "file_rename",
- sessionId,
- userId,
- from: oldPath,
- to: newPath,
- });
- const escapedOldPath = oldPath.replace(/'/g, "'\"'\"'");
- const escapedNewPath = newPath.replace(/'/g, "'\"'\"'");
-
- const renameCommand = `mv '${escapedOldPath}' '${escapedNewPath}' && echo "SUCCESS" && exit 0`;
-
- execChannel(sshConn, renameCommand, (err, stream) => {
- if (err) {
- fileLogger.error("SSH renameItem error:", err);
- if (!res.headersSent) {
- return res.status(500).json({ error: err.message });
- }
- return;
- }
-
- let outputData = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- outputData += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
-
- if (chunk.toString().includes("Permission denied")) {
- fileLogger.error(`Permission denied renaming: ${oldPath}`);
- if (!res.headersSent) {
- return res.status(403).json({
- error: `Permission denied: Cannot rename ${oldPath}. Check file permissions.`,
- });
- }
- return;
- }
- });
-
- stream.on("close", (code) => {
- if (outputData.includes("SUCCESS")) {
- fileLogger.success("Item renamed successfully", {
- operation: "file_rename_success",
- sessionId,
- userId,
- from: oldPath,
- to: newPath,
- });
- if (!res.headersSent) {
- res.json({
- message: "Item renamed successfully",
- oldPath,
- newPath,
- toast: {
- type: "success",
- message: `Item renamed: ${oldPath} -> ${newPath}`,
- },
- });
- }
- return;
- }
-
- if (code !== 0) {
- fileLogger.error(
- `SSH renameItem command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
- );
- if (!res.headersSent) {
- return res.status(500).json({
- error: `Command failed: ${errorData}`,
- toast: { type: "error", message: `Rename failed: ${errorData}` },
- });
- }
- return;
- }
-
- fileLogger.success("Item renamed successfully", {
- operation: "file_rename_success",
- sessionId,
- userId,
- from: oldPath,
- to: newPath,
- });
- if (!res.headersSent) {
- res.json({
- message: "Item renamed successfully",
- oldPath,
- newPath,
- toast: {
- type: "success",
- message: `Item renamed: ${oldPath} -> ${newPath}`,
- },
- });
- }
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.error("SSH renameItem stream error:", streamErr);
- if (!res.headersSent) {
- res.status(500).json({ error: `Stream error: ${streamErr.message}` });
- }
- });
- });
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/moveItem:
- * put:
- * summary: Move a file or directory
- * description: Moves a file or directory on the remote host.
- * tags:
- * - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * oldPath:
- * type: string
- * newPath:
- * type: string
- * responses:
- * 200:
- * description: Item moved successfully.
- * 400:
- * description: Missing required parameters or SSH connection not established.
- * 403:
- * description: Permission denied.
- * 408:
- * description: Move operation timed out.
- * 500:
- * description: Failed to move item.
- */
-app.put("/ssh/file_manager/ssh/moveItem", async (req, res) => {
- const { sessionId, oldPath, newPath } = req.body;
- const sshConn = sshSessions[sessionId];
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId) {
- return res.status(400).json({ error: "Session ID is required" });
- }
-
- if (!sshConn?.isConnected) {
- return res.status(400).json({ error: "SSH connection not established" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- if (!oldPath || !newPath) {
- return res
- .status(400)
- .json({ error: "Old path and new path are required" });
- }
-
- sshConn.lastActive = Date.now();
-
- const escapedOldPath = oldPath.replace(/'/g, "'\"'\"'");
- const escapedNewPath = newPath.replace(/'/g, "'\"'\"'");
-
- const moveCommand = `mv '${escapedOldPath}' '${escapedNewPath}' && echo "SUCCESS" && exit 0`;
-
- const commandTimeout = setTimeout(() => {
- if (!res.headersSent) {
- res.status(408).json({
- error: "Move operation timed out. SSH connection may be unstable.",
- toast: {
- type: "error",
- message: "Move operation timed out. SSH connection may be unstable.",
- },
- });
- }
- }, 60000);
-
- execChannel(sshConn, moveCommand, (err, stream) => {
- if (err) {
- clearTimeout(commandTimeout);
- fileLogger.error("SSH moveItem error:", err);
- if (!res.headersSent) {
- return res.status(500).json({ error: err.message });
- }
- return;
- }
-
- let outputData = "";
- let errorData = "";
-
- stream.on("data", (chunk: Buffer) => {
- outputData += chunk.toString();
- });
-
- stream.stderr.on("data", (chunk: Buffer) => {
- errorData += chunk.toString();
-
- if (chunk.toString().includes("Permission denied")) {
- fileLogger.error(`Permission denied moving: ${oldPath}`);
- if (!res.headersSent) {
- return res.status(403).json({
- error: `Permission denied: Cannot move ${oldPath}. Check file permissions.`,
- toast: {
- type: "error",
- message: `Permission denied: Cannot move ${oldPath}. Check file permissions.`,
- },
- });
- }
- return;
- }
- });
-
- stream.on("close", (code) => {
- clearTimeout(commandTimeout);
- if (outputData.includes("SUCCESS")) {
- if (!res.headersSent) {
- res.json({
- message: "Item moved successfully",
- oldPath,
- newPath,
- toast: {
- type: "success",
- message: `Item moved: ${oldPath} -> ${newPath}`,
- },
- });
- }
- return;
- }
-
- if (code !== 0) {
- fileLogger.error(
- `SSH moveItem command failed with code ${code}: ${errorData.replace(/\n/g, " ").trim()}`,
- );
- if (!res.headersSent) {
- return res.status(500).json({
- error: `Command failed: ${errorData}`,
- toast: { type: "error", message: `Move failed: ${errorData}` },
- });
- }
- return;
- }
-
- if (!res.headersSent) {
- res.json({
- message: "Item moved successfully",
- oldPath,
- newPath,
- toast: {
- type: "success",
- message: `Item moved: ${oldPath} -> ${newPath}`,
- },
- });
- }
- });
-
- stream.on("error", (streamErr) => {
- clearTimeout(commandTimeout);
- fileLogger.error("SSH moveItem stream error:", streamErr);
- if (!res.headersSent) {
- res.status(500).json({ error: `Stream error: ${streamErr.message}` });
- }
- });
- });
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/downloadFile:
- * post:
- * summary: Download a file
- * description: Downloads a file from the remote host.
- * tags:
- * - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * path:
- * type: string
- * hostId:
- * type: integer
- * userId:
- * type: string
- * responses:
- * 200:
- * description: The file content.
- * 400:
- * description: Missing required parameters or file too large.
- * 500:
- * description: Failed to download file.
- */
-app.post("/ssh/file_manager/ssh/downloadFile", async (req, res) => {
- const { sessionId, path: filePath, hostId } = req.body;
- const userId = (req as AuthenticatedRequest).userId;
- const downloadStartTime = Date.now();
-
- if (!sessionId || !filePath) {
- fileLogger.warn("Missing download parameters", {
- operation: "file_download",
- sessionId,
- hasFilePath: !!filePath,
- });
- return res.status(400).json({ error: "Missing download parameters" });
- }
-
- fileLogger.info("File download started", {
- operation: "file_download_start",
- sessionId,
- userId,
- path: filePath,
- });
-
- const sshConn = sshSessions[sessionId];
- if (!sshConn || !sshConn.isConnected) {
- fileLogger.warn("SSH session not found or not connected for download", {
- operation: "file_download",
- sessionId,
- isConnected: sshConn?.isConnected,
- });
- return res
- .status(400)
- .json({ error: "SSH session not found or not connected" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- sshConn.lastActive = Date.now();
- scheduleSessionCleanup(sessionId);
- fileLogger.info("Opening SFTP channel", {
- operation: "file_sftp_open",
- sessionId,
- userId,
- path: filePath,
- });
-
- getSessionSftp(sshConn)
- .then((sftp) => {
- sftp.stat(filePath, (statErr, stats) => {
- if (statErr) {
- fileLogger.error("File stat failed for download:", statErr);
- return res
- .status(500)
- .json({ error: `Cannot access file: ${statErr.message}` });
- }
-
- if (!stats.isFile()) {
- fileLogger.warn("Attempted to download non-file", {
- operation: "file_download",
- sessionId,
- filePath,
- isFile: stats.isFile(),
- isDirectory: stats.isDirectory(),
- });
- return res
- .status(400)
- .json({ error: "Cannot download directories or special files" });
- }
-
- const MAX_FILE_SIZE = 5 * 1024 * 1024 * 1024;
- if (stats.size > MAX_FILE_SIZE) {
- fileLogger.warn("File too large for download", {
- operation: "file_download",
- sessionId,
- filePath,
- fileSize: stats.size,
- maxSize: MAX_FILE_SIZE,
- });
- return res.status(400).json({
- error: `File too large. Maximum size is ${MAX_FILE_SIZE / 1024 / 1024}MB, file is ${(stats.size / 1024 / 1024).toFixed(2)}MB`,
- });
- }
-
- sftp.readFile(filePath, (readErr, data) => {
- if (readErr) {
- fileLogger.error("File read failed for download:", readErr);
- return res
- .status(500)
- .json({ error: `Failed to read file: ${readErr.message}` });
- }
-
- const base64Content = data.toString("base64");
- const fileName = filePath.split("/").pop() || "download";
- fileLogger.success("File download completed", {
- operation: "file_download_complete",
- sessionId,
- userId,
- hostId,
- path: filePath,
- bytes: stats.size,
- duration: Date.now() - downloadStartTime,
- });
-
- res.json({
- content: base64Content,
- fileName: fileName,
- size: stats.size,
- mimeType: getMimeType(fileName),
- path: filePath,
- });
- });
- });
- })
- .catch((err) => {
- fileLogger.error("SFTP connection failed for download:", err);
- return res.status(500).json({ error: "SFTP connection failed" });
- });
-});
-
-app.post("/ssh/file_manager/ssh/downloadFileStream", async (req, res) => {
- const { sessionId, path: filePath } = req.body;
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId || !filePath) {
- return res.status(400).json({ error: "Missing download parameters" });
- }
-
- const sshConn = sshSessions[sessionId];
- if (!sshConn?.isConnected) {
- return res
- .status(400)
- .json({ error: "SSH session not found or not connected" });
- }
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- sshConn.lastActive = Date.now();
-
- try {
- const sftp = await getSessionSftp(sshConn);
- const stats = await new Promise<{ size: number; isFile: () => boolean }>(
- (resolve, reject) => {
- sftp.stat(filePath, (err, s) => (err ? reject(err) : resolve(s)));
- },
- );
-
- if (!stats.isFile()) {
- return res.status(400).json({ error: "Cannot download directories" });
- }
-
- const fileName = filePath.split("/").pop() || "download";
- res.setHeader("Content-Type", "application/octet-stream");
- res.setHeader(
- "Content-Disposition",
- `attachment; filename="${encodeURIComponent(fileName)}"`,
- );
- res.setHeader("Content-Length", String(stats.size));
-
- const readStream = sftp.createReadStream(filePath);
- readStream.on("error", (err) => {
- if (!res.headersSent) {
- res.status(500).json({ error: `Download failed: ${err.message}` });
- } else {
- res.destroy();
- }
- });
- readStream.pipe(res);
- } catch (err) {
- if (!res.headersSent) {
- res
- .status(500)
- .json({ error: `Download failed: ${(err as Error).message}` });
- }
- }
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/copyItem:
- * post:
- * summary: Copy a file or directory
- * description: Copies a file or directory on the remote host.
- * tags:
- * - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * sourcePath:
- * type: string
- * targetDir:
- * type: string
- * hostId:
- * type: integer
- * userId:
- * type: string
- * responses:
- * 200:
- * description: Item copied successfully.
- * 400:
- * description: Missing required parameters or SSH connection not established.
- * 500:
- * description: Failed to copy item.
- */
-app.post("/ssh/file_manager/ssh/copyItem", async (req, res) => {
- const { sessionId, sourcePath, targetDir, hostId } = req.body;
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!sessionId || !sourcePath || !targetDir) {
- return res.status(400).json({ error: "Missing required parameters" });
- }
-
- const sshConn = sshSessions[sessionId];
- if (!sshConn || !sshConn.isConnected) {
- return res
- .status(400)
- .json({ error: "SSH session not found or not connected" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
- }
-
- sshConn.lastActive = Date.now();
- scheduleSessionCleanup(sessionId);
-
- const sourceName = sourcePath.split("/").pop() || "copied_item";
-
- const timestamp = Date.now().toString().slice(-8);
- const uniqueName = `${sourceName}_copy_${timestamp}`;
- const targetPath = `${targetDir}/${uniqueName}`;
-
- const escapedSource = sourcePath.replace(/'/g, "'\"'\"'");
- const escapedTarget = targetPath.replace(/'/g, "'\"'\"'");
-
- const copyCommand = `cp '${escapedSource}' '${escapedTarget}' && echo "COPY_SUCCESS"`;
-
- const commandTimeout = setTimeout(() => {
- fileLogger.error("Copy command timed out after 60 seconds", {
- sourcePath,
- targetPath,
- command: copyCommand,
- });
- if (!res.headersSent) {
- res.status(500).json({
- error: "Copy operation timed out",
- toast: {
- type: "error",
- message: "Copy operation timed out. SSH connection may be unstable.",
- },
- });
- }
- }, 60000);
-
- execChannel(sshConn, copyCommand, (err, stream) => {
- if (err) {
- clearTimeout(commandTimeout);
- fileLogger.error("SSH copyItem error:", err);
- if (!res.headersSent) {
- return res.status(500).json({ error: err.message });
- }
- return;
- }
-
- let errorData = "";
- let stdoutData = "";
-
- stream.on("data", (data: Buffer) => {
- const output = data.toString();
- stdoutData += output;
- stream.stderr.on("data", (data: Buffer) => {
- const output = data.toString();
- errorData += output;
- });
-
- stream.on("close", (code) => {
- clearTimeout(commandTimeout);
-
- if (code !== 0) {
- const fullErrorInfo =
- errorData || stdoutData || "No error message available";
- fileLogger.error(`SSH copyItem command failed with code ${code}`, {
- operation: "file_copy_failed",
- sessionId,
- sourcePath,
- targetPath,
- command: copyCommand,
- exitCode: code,
- errorData,
- stdoutData,
- fullErrorInfo,
- });
- if (!res.headersSent) {
- return res.status(500).json({
- error: `Copy failed: ${fullErrorInfo}`,
- toast: {
- type: "error",
- message: `Copy failed: ${fullErrorInfo}`,
- },
- debug: {
- sourcePath,
- targetPath,
- exitCode: code,
- command: copyCommand,
- },
- });
- }
- return;
- }
-
- const copySuccessful =
- stdoutData.includes("COPY_SUCCESS") || code === 0;
-
- if (copySuccessful) {
- fileLogger.success("Item copied successfully", {
- operation: "file_copy",
- sessionId,
- sourcePath,
- targetPath,
- uniqueName,
- hostId,
- userId,
- });
-
- if (!res.headersSent) {
- res.json({
- message: "Item copied successfully",
- sourcePath,
- targetPath,
- uniqueName,
- toast: {
- type: "success",
- message: `Successfully copied to: ${uniqueName}`,
- },
- });
- }
- } else {
- fileLogger.warn("Copy completed but without success confirmation", {
- operation: "file_copy_uncertain",
- sessionId,
- sourcePath,
- targetPath,
- code,
- stdoutData: stdoutData.substring(0, 200),
- });
-
- if (!res.headersSent) {
- res.json({
- message: "Copy may have completed",
- sourcePath,
- targetPath,
- uniqueName,
- toast: {
- type: "warning",
- message: `Copy completed but verification uncertain for: ${uniqueName}`,
- },
- });
- }
- }
- });
-
- stream.on("error", (streamErr) => {
- clearTimeout(commandTimeout);
- fileLogger.error("SSH copyItem stream error:", streamErr);
- if (!res.headersSent) {
- res.status(500).json({ error: `Stream error: ${streamErr.message}` });
- }
- });
- });
- });
-});
-
-/**
- * @openapi
- * /ssh/file_manager/ssh/executeFile:
- * post:
- * summary: Execute a file
- * description: Executes a file on the remote host.
+ * description: Checks the status of an SSH connection for file manager.
* tags:
* - File Manager
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * sessionId:
- * type: string
- * filePath:
- * type: string
+ * parameters:
+ * - in: query
+ * name: sessionId
+ * required: true
+ * schema:
+ * type: string
* responses:
* 200:
- * description: File execution result.
- * 400:
- * description: Missing required parameters or SSH connection not available.
- * 500:
- * description: Failed to execute file.
+ * description: SSH connection status.
*/
-app.post("/ssh/file_manager/ssh/executeFile", async (req, res) => {
- const { sessionId, filePath } = req.body;
- const sshConn = sshSessions[sessionId];
+app.get("/ssh/file_manager/ssh/status", (req, res) => {
+ const sessionId = req.query.sessionId as string;
const userId = (req as AuthenticatedRequest).userId;
-
- if (!sshConn || !sshConn.isConnected) {
- fileLogger.error(
- "SSH connection not found or not connected for executeFile",
- {
- operation: "execute_file",
- sessionId,
- hasConnection: !!sshConn,
- isConnected: sshConn?.isConnected,
- },
- );
- return res.status(400).json({ error: "SSH connection not available" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
+ const session = sshSessions[sessionId];
+ if (session && !verifySessionOwnership(session, userId)) {
return res.status(403).json({ error: "Session access denied" });
}
-
- if (!filePath) {
- return res.status(400).json({ error: "File path is required" });
- }
-
- const escapedPath = filePath.replace(/'/g, "'\"'\"'");
-
- const checkCommand = `test -x '${escapedPath}' && echo "EXECUTABLE" || echo "NOT_EXECUTABLE"`;
-
- execChannel(sshConn, checkCommand, (checkErr, checkStream) => {
- if (checkErr) {
- fileLogger.error("SSH executeFile check error:", checkErr);
- return res
- .status(500)
- .json({ error: "Failed to check file executability" });
- }
-
- let checkResult = "";
- checkStream.on("data", (data) => {
- checkResult += data.toString();
- });
-
- checkStream.on("close", () => {
- if (!checkResult.includes("EXECUTABLE")) {
- return res.status(400).json({ error: "File is not executable" });
- }
-
- const executeCommand = `cd "$(dirname '${escapedPath}')" && '${escapedPath}' 2>&1; echo "EXIT_CODE:$?"`;
-
- execChannel(sshConn, executeCommand, (err, stream) => {
- if (err) {
- fileLogger.error("SSH executeFile error:", err);
- return res.status(500).json({ error: "Failed to execute file" });
- }
-
- let output = "";
- let errorOutput = "";
-
- stream.on("data", (data) => {
- output += data.toString();
- });
-
- stream.stderr.on("data", (data) => {
- errorOutput += data.toString();
- });
-
- stream.on("close", (code) => {
- const exitCodeMatch = output.match(/EXIT_CODE:(\d+)$/);
- const actualExitCode = exitCodeMatch
- ? parseInt(exitCodeMatch[1])
- : code;
- const cleanOutput = output.replace(/EXIT_CODE:\d+$/, "").trim();
-
- fileLogger.info("File execution completed", {
- operation: "execute_file",
- sessionId,
- filePath,
- exitCode: actualExitCode,
- outputLength: cleanOutput.length,
- errorLength: errorOutput.length,
- });
-
- res.json({
- success: true,
- exitCode: actualExitCode,
- output: cleanOutput,
- error: errorOutput,
- timestamp: new Date().toISOString(),
- });
- });
-
- stream.on("error", (streamErr) => {
- fileLogger.error("SSH executeFile stream error:", streamErr);
- if (!res.headersSent) {
- res.status(500).json({ error: "Execution stream error" });
- }
- });
- });
- });
- });
+ const isConnected = !!session?.isConnected;
+ res.json({ status: "success", connected: isConnected });
});
/**
* @openapi
- * /ssh/file_manager/ssh/changePermissions:
+ * /ssh/file_manager/ssh/keepalive:
* post:
- * summary: Change file permissions
- * description: Changes the permissions of a file on the remote host.
+ * summary: Keep SSH session alive
+ * description: Keeps an active SSH session for file manager alive.
* tags:
* - File Manager
* requestBody:
@@ -5471,173 +2125,82 @@ app.post("/ssh/file_manager/ssh/executeFile", async (req, res) => {
* properties:
* sessionId:
* type: string
- * path:
- * type: string
- * permissions:
- * type: string
* responses:
* 200:
- * description: Permissions changed successfully.
+ * description: Session keepalive successful.
* 400:
- * description: Missing required parameters or SSH connection not available.
- * 408:
- * description: Permission change timed out.
- * 500:
- * description: Failed to change permissions.
+ * description: Session ID is required or session not found.
*/
-app.post("/ssh/file_manager/ssh/changePermissions", async (req, res) => {
- const { sessionId, path, permissions } = req.body;
- const sshConn = sshSessions[sessionId];
+app.post("/ssh/file_manager/ssh/keepalive", async (req, res) => {
+ const { sessionId } = req.body;
const userId = (req as AuthenticatedRequest).userId;
- if (!sshConn || !sshConn.isConnected) {
- fileLogger.error(
- "SSH connection not found or not connected for changePermissions",
- {
- operation: "change_permissions",
- sessionId,
- hasConnection: !!sshConn,
- isConnected: sshConn?.isConnected,
- },
- );
- return res.status(400).json({ error: "SSH connection not available" });
- }
-
- if (!verifySessionOwnership(sshConn, userId)) {
- return res.status(403).json({ error: "Session access denied" });
+ if (!sessionId) {
+ return res.status(400).json({ error: "Session ID is required" });
}
- if (!path) {
- return res.status(400).json({ error: "File path is required" });
- }
+ const session = sshSessions[sessionId];
- if (!permissions || !/^\d{3,4}$/.test(permissions)) {
+ if (!session || !session.isConnected) {
return res.status(400).json({
- error: "Valid permissions required (e.g., 755, 644)",
+ error: "SSH session not found or not connected",
+ connected: false,
});
}
- sshConn.lastActive = Date.now();
- scheduleSessionCleanup(sessionId);
-
- const octalPerms = permissions.slice(-3);
- const escapedPath = path.replace(/'/g, "'\"'\"'");
- const command = `chmod ${octalPerms} '${escapedPath}' && echo "SUCCESS"`;
-
- fileLogger.info("Changing file permissions", {
- operation: "change_permissions",
- sessionId,
- path,
- permissions: octalPerms,
- });
+ if (!verifySessionOwnership(session, userId)) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
- const commandTimeout = setTimeout(() => {
- if (!res.headersSent) {
- fileLogger.error("changePermissions command timeout", {
- operation: "change_permissions",
- sessionId,
- path,
- permissions: octalPerms,
- });
- res.status(408).json({
- error: "Permission change timed out. SSH connection may be unstable.",
- });
- }
- }, 10000);
+ session.lastActive = Date.now();
+ scheduleSessionCleanup(sessionId);
- execChannel(sshConn, command, (err, stream) => {
- if (err) {
- clearTimeout(commandTimeout);
- fileLogger.error("SSH changePermissions exec error:", err, {
- operation: "change_permissions",
- sessionId,
- path,
- permissions: octalPerms,
+ // Probe the cached SFTP channel. If stale, clear it so the next operation
+ // opens a fresh one via the serialized getSessionSftp.
+ if (session.sftp && !session.sftpPending) {
+ try {
+ await new Promise<void>((resolve, reject) => {
+ session.sftp!.stat("/", (err) => (err ? reject(err) : resolve()));
});
- if (!res.headersSent) {
- return res.status(500).json({ error: "Failed to change permissions" });
- }
- return;
+ } catch {
+ session.sftp = undefined;
}
+ }
- let outputData = "";
- let errorOutput = "";
-
- stream.on("data", (chunk: Buffer) => {
- outputData += chunk.toString();
- });
-
- stream.stderr.on("data", (data: Buffer) => {
- errorOutput += data.toString();
- });
-
- stream.on("close", (code) => {
- clearTimeout(commandTimeout);
-
- if (outputData.includes("SUCCESS")) {
- fileLogger.success("File permissions changed successfully", {
- operation: "change_permissions",
- sessionId,
- path,
- permissions: octalPerms,
- });
+ res.json({
+ status: "success",
+ connected: true,
+ message: "Session keepalive successful",
+ lastActive: session.lastActive,
+ });
+});
- if (!res.headersSent) {
- res.json({
- success: true,
- message: "Permissions changed successfully",
- });
- }
- return;
- }
+registerFileListingRoutes(app, {
+ sshSessions,
+ activeListRequests,
+ verifySessionOwnership,
+});
- if (code !== 0) {
- fileLogger.error("chmod command failed", {
- operation: "change_permissions",
- sessionId,
- path,
- permissions: octalPerms,
- exitCode: code,
- error: errorOutput,
- });
- if (!res.headersSent) {
- return res.status(500).json({
- error: errorOutput || "Failed to change permissions",
- });
- }
- return;
- }
+registerFileContentRoutes(app, {
+ sshSessions,
+ verifySessionOwnership,
+});
- fileLogger.success("File permissions changed successfully", {
- operation: "change_permissions",
- sessionId,
- path,
- permissions: octalPerms,
- });
+registerFileOperationRoutes(app, {
+ sshSessions,
+ verifySessionOwnership,
+});
- if (!res.headersSent) {
- res.json({
- success: true,
- message: "Permissions changed successfully",
- });
- }
- });
+registerFileDownloadRoutes(app, {
+ sshSessions,
+ scheduleSessionCleanup,
+ verifySessionOwnership,
+});
- stream.on("error", (streamErr) => {
- clearTimeout(commandTimeout);
- fileLogger.error("SSH changePermissions stream error:", streamErr, {
- operation: "change_permissions",
- sessionId,
- path,
- permissions: octalPerms,
- });
- if (!res.headersSent) {
- res
- .status(500)
- .json({ error: "Stream error while changing permissions" });
- }
- });
- });
+registerFileActionRoutes(app, {
+ sshSessions,
+ scheduleSessionCleanup,
+ verifySessionOwnership,
});
/**
@@ -5937,7 +2500,7 @@ app.post("/ssh/file_manager/ssh/compressFiles", async (req, res) => {
const fileNames = paths
.map((p) => {
const name = p.split("/").pop();
- return `'${escapeShell(name || "")}'`;
+ return `'./${escapeShell(name || "")}'`;
})
.join(" ");
@@ -5954,17 +2517,17 @@ app.post("/ssh/file_manager/ssh/compressFiles", async (req, res) => {
const escapedArchive = escapeShell(archivePath);
if (compressionFormat === "zip") {
- compressCommand = `cd '${escapedDir}' && zip -r '${escapedArchive}' ${fileNames}`;
+ compressCommand = `cd '${escapedDir}' && zip -r '${escapedArchive}' -- ${fileNames}`;
} else if (compressionFormat === "tar.gz" || compressionFormat === "tgz") {
- compressCommand = `cd '${escapedDir}' && tar -czf '${escapedArchive}' ${fileNames}`;
+ compressCommand = `cd '${escapedDir}' && tar -czf '${escapedArchive}' -- ${fileNames}`;
} else if (compressionFormat === "tar.bz2" || compressionFormat === "tbz2") {
- compressCommand = `cd '${escapedDir}' && tar -cjf '${escapedArchive}' ${fileNames}`;
+ compressCommand = `cd '${escapedDir}' && tar -cjf '${escapedArchive}' -- ${fileNames}`;
} else if (compressionFormat === "tar.xz") {
- compressCommand = `cd '${escapedDir}' && tar -cJf '${escapedArchive}' ${fileNames}`;
+ compressCommand = `cd '${escapedDir}' && tar -cJf '${escapedArchive}' -- ${fileNames}`;
} else if (compressionFormat === "tar") {
- compressCommand = `cd '${escapedDir}' && tar -cf '${escapedArchive}' ${fileNames}`;
+ compressCommand = `cd '${escapedDir}' && tar -cf '${escapedArchive}' -- ${fileNames}`;
} else if (compressionFormat === "7z") {
- compressCommand = `cd '${escapedDir}' && 7z a '${escapedArchive}' ${fileNames}`;
+ compressCommand = `cd '${escapedDir}' && 7z a '${escapedArchive}' -- ${fileNames}`;
} else {
return res.status(400).json({ error: "Unsupported compression format" });
}
@@ -6081,6 +2644,222 @@ app.post("/ssh/file_manager/ssh/compressFiles", async (req, res) => {
});
});
+const hostTransferDeps: HostTransferDeps = {
+ sshSessions,
+ getSessionSftp,
+ execChannel,
+ verifySessionOwnership,
+ openDedicatedTransferSession,
+ closeDedicatedTransferSession,
+};
+
+app.post("/ssh/file_manager/ssh/transferMethodPreview", async (req, res) => {
+ const {
+ sourceSessionId,
+ destSessionId,
+ sourcePaths,
+ destPath,
+ methodPreference,
+ } = req.body;
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (
+ !sourceSessionId ||
+ !destSessionId ||
+ !destPath ||
+ !sourcePaths ||
+ !Array.isArray(sourcePaths) ||
+ sourcePaths.length === 0
+ ) {
+ return res.status(400).json({ error: "Missing required parameters" });
+ }
+
+ try {
+ const preview = await previewArchiveTransferMethod(hostTransferDeps, {
+ sourceSessionId,
+ destSessionId,
+ sourcePaths,
+ destPath,
+ methodPreference:
+ methodPreference === "tar" || methodPreference === "item_sftp"
+ ? methodPreference
+ : "auto",
+ userId,
+ });
+ res.json(preview);
+ } catch (err) {
+ fileLogger.error("Failed to preview transfer method", err, {
+ operation: "host_transfer",
+ sourceSessionId,
+ destSessionId,
+ sourcePaths,
+ });
+ res.status(500).json({
+ error: err instanceof Error ? err.message : "Failed to preview method",
+ });
+ }
+});
+
+app.post("/ssh/file_manager/ssh/transferToHost", async (req, res) => {
+ const {
+ sourceSessionId,
+ sourcePaths,
+ destSessionId,
+ destPath,
+ move,
+ methodPreference,
+ parallelSegmentCount: parallelSegmentCountRaw,
+ } = req.body;
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (
+ !sourceSessionId ||
+ !destSessionId ||
+ !destPath ||
+ !sourcePaths ||
+ !Array.isArray(sourcePaths) ||
+ sourcePaths.length === 0
+ ) {
+ return res.status(400).json({ error: "Missing required parameters" });
+ }
+
+ const sourceSession = sshSessions[sourceSessionId];
+ const destSession = sshSessions[destSessionId];
+
+ if (!sourceSession?.isConnected || !destSession?.isConnected) {
+ return res.status(400).json({ error: "SSH session not connected" });
+ }
+
+ if (
+ !verifySessionOwnership(sourceSession, userId) ||
+ !verifySessionOwnership(destSession, userId)
+ ) {
+ return res.status(403).json({ error: "Session access denied" });
+ }
+
+ sourceSession.lastActive = Date.now();
+ destSession.lastActive = Date.now();
+ scheduleSessionCleanup(sourceSessionId);
+ scheduleSessionCleanup(destSessionId);
+
+ try {
+ const rawParallel = Number(parallelSegmentCountRaw);
+ const parallelSegmentCount = Number.isFinite(rawParallel)
+ ? Math.max(1, Math.min(8, Math.floor(rawParallel)))
+ : 2;
+
+ const { transferId } = startHostTransfer(hostTransferDeps, {
+ sourceSessionId,
+ sourcePaths,
+ destSessionId,
+ destPath,
+ move: !!move,
+ userId,
+ methodPreference:
+ methodPreference === "tar" || methodPreference === "item_sftp"
+ ? methodPreference
+ : "auto",
+ parallelSegmentCount,
+ });
+
+ res.json({ transferId });
+ } catch (err) {
+ fileLogger.error("Failed to start host transfer", err, {
+ operation: "host_transfer",
+ sourceSessionId,
+ destSessionId,
+ sourcePaths,
+ });
+ res.status(500).json({ error: "Failed to start transfer" });
+ }
+});
+
+app.get("/ssh/file_manager/ssh/activeTransfers", async (req, res) => {
+ const userId = (req as unknown as AuthenticatedRequest).userId;
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ await probeHungStreamTransfers(hostTransferDeps);
+ res.json({ transfers: listActiveTransfers(userId) });
+});
+
+app.get(
+ "/ssh/file_manager/ssh/transferStatus/:transferId",
+ async (req, res) => {
+ const userId = (req as unknown as AuthenticatedRequest).userId;
+ const transferId = req.params.transferId;
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ await probeHungStreamTransfers(hostTransferDeps);
+ const status = getTransferStatus(transferId, userId);
+ if (!status) {
+ return res.status(404).json({ error: "Transfer not found" });
+ }
+
+ res.json(status);
+ },
+);
+
+app.post("/ssh/file_manager/ssh/transferCancel/:transferId", (req, res) => {
+ const userId = (req as unknown as AuthenticatedRequest).userId;
+ const transferId = req.params.transferId;
+
+ const cancelled = requestTransferCancel(transferId, userId);
+ if (!cancelled) {
+ return res.status(404).json({ error: "Transfer not found or not running" });
+ }
+
+ res.json({ ok: true });
+});
+
+app.post(
+ "/ssh/file_manager/ssh/transferCleanup/:transferId",
+ async (req, res) => {
+ const userId = (req as unknown as AuthenticatedRequest).userId;
+ const transferId = req.params.transferId;
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ try {
+ const result = await cleanupCancelledTransfer(
+ hostTransferDeps,
+ transferId,
+ userId,
+ );
+ res.json(result);
+ } catch (err) {
+ const message =
+ err instanceof Error ? err.message : "Failed to clean up transfer";
+ const status = message === "Transfer not found" ? 404 : 400;
+ res.status(status).json({ error: message });
+ }
+ },
+);
+
+app.post("/ssh/file_manager/ssh/transferRetry/:transferId", (req, res) => {
+ const userId = (req as unknown as AuthenticatedRequest).userId;
+ const transferId = req.params.transferId;
+
+ if (!userId) {
+ return res.status(401).json({ error: "Authentication required" });
+ }
+
+ const retried = retryHostTransfer(hostTransferDeps, transferId, userId);
+ if (!retried) {
+ return res
+ .status(404)
+ .json({ error: "Transfer not found or not retryable" });
+ }
+
+ res.json({ ok: true, transferId });
+});
+
process.on("SIGINT", () => {
Object.keys(sshSessions).forEach(cleanupSession);
process.exit(0);
diff --git a/src/backend/ssh/host-resolver.ts b/src/backend/ssh/host-resolver.ts
index b741794a6..da2dc99b7 100644
--- a/src/backend/ssh/host-resolver.ts
+++ b/src/backend/ssh/host-resolver.ts
@@ -148,12 +148,14 @@ export async function resolveHostById(
return host as unknown as SSHHost;
}
} catch (e) {
- sshLogger.warn("Failed to get shared credential, falling back", {
+ sshLogger.warn("Failed to get shared credential", {
operation: "host_resolver_shared_credential",
hostId,
error: e instanceof Error ? e.message : "Unknown",
});
}
+
+ return null;
}
const credentials = await SimpleDBOps.select(
diff --git a/src/backend/ssh/host-transfer.ts b/src/backend/ssh/host-transfer.ts
new file mode 100644
index 000000000..ef8aa0d03
--- /dev/null
+++ b/src/backend/ssh/host-transfer.ts
@@ -0,0 +1,3445 @@
+import { randomUUID } from "crypto";
+import { networkInterfaces } from "os";
+import { performance } from "node:perf_hooks";
+import type { ClientChannel } from "ssh2";
+import { fileLogger } from "../utils/logger.js";
+import {
+ basename,
+ buildPathFromSegments,
+ dirname,
+ getWorkingDir,
+ inferPlatformFromPath,
+ joinPath,
+ normalizeSftpPath,
+ pathsOverlap,
+ sftpPathToLocalPath,
+ splitPathSegments,
+ type TransferPlatform,
+} from "./transfer-paths.js";
+import {
+ buildTransferScanSummary,
+ getArchiveTransferReasonKey,
+ resolveArchiveTransferMethod,
+ type TransferMethodPreference,
+ type TransferScanSummary,
+} from "./transfer-routing.js";
+
+export type {
+ TransferMethodPreference,
+ TransferScanSummary,
+} from "./transfer-routing.js";
+
+export interface TransferMethodPreview {
+ methodPreference: TransferMethodPreference;
+ resolvedMethod: "tar" | "item_sftp";
+ reasonKey: ReturnType<typeof getArchiveTransferReasonKey>;
+ sourcePlatform: TransferPlatform;
+ destPlatform: TransferPlatform;
+ sourceHasTar: boolean;
+ destHasTar: boolean;
+ summary: TransferScanSummary;
+}
+
+type SFTPWrapper = import("ssh2").SFTPWrapper;
+
+export interface SSHSessionLike {
+ client: import("ssh2").Client;
+ isConnected: boolean;
+ lastActive: number;
+ activeOperations: number;
+ sftp?: SFTPWrapper;
+ sftpPending?: Promise<SFTPWrapper>;
+ channelOpener: { run: <T>(fn: () => Promise<T>) => Promise<T> };
+ userId?: string;
+ ip?: string;
+ port?: number;
+ transferPlatform?: TransferPlatform;
+}
+
+export interface HostTransferDeps {
+ sshSessions: Record<string, SSHSessionLike>;
+ getSessionSftp: (session: SSHSessionLike) => Promise<SFTPWrapper>;
+ execChannel: (
+ session: SSHSessionLike,
+ command: string,
+ callback: (err: Error | undefined, stream: ClientChannel) => void,
+ ) => void;
+ verifySessionOwnership: (session: SSHSessionLike, userId: string) => boolean;
+ openDedicatedTransferSession: (
+ browseSessionId: string,
+ dedicatedSessionId: string,
+ userId: string,
+ transferId: string,
+ options?: { allowBrowseDisconnected?: boolean },
+ ) => Promise<SSHSessionLike>;
+ closeDedicatedTransferSession: (sessionId: string) => void;
+}
+
+export type TransferPhase =
+ | "compressing"
+ | "transferring"
+ | "extracting"
+ | "reconnecting";
+export type TransferStatus =
+ | "running"
+ | "success"
+ | "partial"
+ | "error"
+ | "cancelled";
+export type TransferMethod = "stream" | "tar" | "item_sftp";
+
+export type TransferHopId =
+ | "source_read"
+ | "dest_sftp_write"
+ | "dest_local_write";
+
+export interface TransferHopMetrics {
+ id: TransferHopId;
+ bytes: number;
+ /** Wall-clock span from first I/O on this hop to last I/O complete. */
+ spanMs: number;
+ mbPerSec: number;
+}
+
+export interface TransferTimings {
+ prepareDestMs?: number;
+ compressMs?: number;
+ transferMs?: number;
+ extractMs?: number;
+ sourceDeleteMs?: number;
+ totalMs?: number;
+ transferBytes?: number;
+ endToEndMbPerSec?: number;
+ hops?: TransferHopMetrics[];
+}
+
+export interface TransferProgress {
+ transferId: string;
+ status: TransferStatus;
+ phase: TransferPhase;
+ bytesTransferred?: number;
+ totalBytes?: number;
+ itemsCompleted?: number;
+ totalItems?: number;
+ failedPaths?: string[];
+ message?: string;
+ method?: TransferMethod;
+ sourcePaths?: string[];
+ destPath?: string;
+ userId?: string;
+ sourceSessionId?: string;
+ destSessionId?: string;
+ dedicatedSourceSessionId?: string;
+ dedicatedDestSessionId?: string;
+ startedAt?: number;
+ lastActivityAt?: number;
+ reconnectingAt?: number;
+ timings?: TransferTimings;
+ sourceDeleted?: boolean;
+ moveRequested?: boolean;
+ methodPreference?: TransferMethodPreference;
+ parallelSegmentCount?: number;
+ /** Destination paths created or partially written before cancel. */
+ destArtifacts?: string[];
+ tempArchivePath?: string;
+ partialDestRemaining?: boolean;
+ cleanupCompleted?: boolean;
+ retryable?: boolean;
+ requestSnapshot?: {
+ sourceSessionId: string;
+ sourcePaths: string[];
+ destSessionId: string;
+ destPath: string;
+ move?: boolean;
+ methodPreference?: TransferMethodPreference;
+ parallelSegmentCount?: number;
+ };
+}
+
+export interface TransferRequest {
+ sourceSessionId: string;
+ sourcePaths: string[];
+ destSessionId: string;
+ destPath: string;
+ move?: boolean;
+ userId: string;
+ methodPreference?: TransferMethodPreference;
+ /** Parallel 256 MiB segment lanes for single-file SFTP copy (default 2). */
+ parallelSegmentCount?: number;
+}
+
+const activeTransfers = new Map<string, TransferProgress>();
+const cancelRequestedTransfers = new Set<string>();
+
+/** In-flight pipelined SFTP reads; force-closed when the user cancels. */
+interface ActiveXferControl {
+ abort: (err: Error) => void;
+ closeResources: () => Promise<void>;
+}
+const activeXferControls = new Map<string, ActiveXferControl>();
+const cancelWatchdogs = new Map<string, ReturnType<typeof setTimeout>>();
+
+class TransferCancelledError extends Error {
+ constructor() {
+ super("Transfer cancelled");
+ this.name = "TransferCancelledError";
+ }
+}
+
+class TransferStalledError extends Error {
+ readonly byteOffset?: number;
+ readonly segmentIndex?: number;
+
+ constructor(byteOffset?: number, segmentIndex?: number) {
+ const pos = byteOffset !== undefined ? ` at byte offset ${byteOffset}` : "";
+ const seg = segmentIndex !== undefined ? ` (segment ${segmentIndex})` : "";
+ super(`Transfer stalled — no data moved for 45 seconds${pos}${seg}`);
+ this.name = "TransferStalledError";
+ this.byteOffset = byteOffset;
+ this.segmentIndex = segmentIndex;
+ }
+}
+
+class TransferConnectionLostError extends Error {
+ constructor(message = "Transfer SSH connection lost") {
+ super(message);
+ this.name = "TransferConnectionLostError";
+ }
+}
+
+function throwIfCancelled(transferId: string): void {
+ if (cancelRequestedTransfers.has(transferId)) {
+ throw new TransferCancelledError();
+ }
+}
+
+function createTransferShouldAbort(transferId: string): () => boolean {
+ return () => {
+ if (cancelRequestedTransfers.has(transferId)) {
+ return true;
+ }
+ const progress = activeTransfers.get(transferId);
+ return progress !== undefined && progress.status !== "running";
+ };
+}
+
+export function requestTransferCancel(
+ transferId: string,
+ userId: string,
+): boolean {
+ const progress = activeTransfers.get(transferId);
+ if (
+ !progress ||
+ progress.userId !== userId ||
+ progress.status !== "running"
+ ) {
+ return false;
+ }
+ cancelRequestedTransfers.add(transferId);
+ updateTransfer(transferId, { message: "Cancellation requested" });
+ void forceAbortActiveXfer(transferId);
+
+ if (!cancelWatchdogs.has(transferId)) {
+ cancelWatchdogs.set(
+ transferId,
+ setTimeout(() => {
+ cancelWatchdogs.delete(transferId);
+ const current = activeTransfers.get(transferId);
+ if (
+ current?.status === "running" &&
+ cancelRequestedTransfers.has(transferId)
+ ) {
+ void forceAbortActiveXfer(transferId);
+ finalizeTransfer(
+ transferId,
+ cancelledProgressPatch(current, {
+ status: "cancelled",
+ phase: current.phase ?? "transferring",
+ message: "Transfer cancelled by user",
+ method: current.method,
+ sourcePaths: current.sourcePaths,
+ destPath: current.destPath,
+ bytesTransferred: current.bytesTransferred,
+ totalBytes: current.totalBytes,
+ itemsCompleted: current.itemsCompleted,
+ totalItems: current.totalItems,
+ moveRequested: current.moveRequested,
+ sourceDeleted: false,
+ }),
+ );
+ fileLogger.warn("Force-finalized stuck transfer after cancel", {
+ operation: "host_transfer",
+ transferId,
+ });
+ }
+ }, 8000),
+ );
+ }
+
+ return true;
+}
+
+async function forceAbortActiveXfer(transferId: string): Promise<void> {
+ const control = activeXferControls.get(transferId);
+ if (!control) return;
+ control.abort(new TransferCancelledError());
+ await control.closeResources().catch(() => {});
+}
+const SMALL_FILE_SYNC_THRESHOLD = 10 * 1024 * 1024;
+/** OpenSSH SFTP max packet payload is ~256 KiB; larger chunks cut round-trips. */
+const SFTP_XFER_CHUNK_SIZE = 256 * 1024;
+/** Pipelined in-flight READ requests per leg (ssh2 fastGet/fastPut default is 64). */
+const SFTP_XFER_CONCURRENCY = 32;
+/** Reset pipelined scheduler every segment to avoid long-run deadlocks at GiB boundaries. */
+const SFTP_XFER_SEGMENT_SIZE = 256 * 1024 * 1024;
+/** Files above this size use segmented copy; smaller files use a single scheduler run. */
+const SFTP_XFER_SEGMENT_THRESHOLD = 32 * 1024 * 1024;
+/** Per-segment attempts before giving up (sequential and parallel). */
+const SFTP_SEQUENTIAL_SEGMENT_MAX_ATTEMPTS = 4;
+/** Per-lane attempts in parallel mode (each opens a fresh lane SSH pair quickly). */
+const SFTP_PARALLEL_SEGMENT_MAX_ATTEMPTS = 4;
+/** Full copy restarts after segment exhaustion. */
+const SFTP_SEQUENTIAL_COPY_MAX_ATTEMPTS = 2;
+const SFTP_PARALLEL_COPY_MAX_ATTEMPTS = 2;
+/** Short backoff before opening fresh dedicated SSH sessions. */
+const TRANSFER_SESSION_RESET_DELAYS_MS = [1000, 2000, 3000];
+const DEFAULT_PARALLEL_SEGMENT_COUNT = 2;
+const MAX_PARALLEL_SEGMENT_COUNT = 8;
+const TRANSFER_HANDLE_CLOSE_TIMEOUT_MS = 2500;
+const HUNG_TRANSFER_MS = 90_000;
+const HUNG_RECONNECTING_MS = 180_000;
+const TRANSFER_PROGRESS_INTERVAL_MS = 200;
+const SFTP_OPEN_READ = 0x00000001;
+/** WRITE | CREATE | TRUNCATE — new file or overwrite from start. */
+const SFTP_OPEN_WRITE = 0x00000002 | 0x00000008 | 0x00000010;
+/** READ | WRITE | CREATE — resume into an existing partial file without truncating. */
+const SFTP_OPEN_WRITE_RESUME = 0x00000001 | 0x00000002 | 0x00000008;
+
+interface TransferReconnectContext {
+ deps: HostTransferDeps;
+ userId: string;
+ browseSourceSessionId: string;
+ browseDestSessionId: string;
+ dedicatedSourceSessionId: string;
+ dedicatedDestSessionId: string;
+ transferId: string;
+}
+
+type TransferReconnectMeta = Omit<
+ TransferReconnectContext,
+ "deps" | "transferId"
+>;
+
+function buildTransferReconnectContext(
+ deps: HostTransferDeps,
+ transferId: string,
+ meta: TransferReconnectMeta,
+): TransferReconnectContext {
+ return { deps, transferId, ...meta };
+}
+
+function isRecoverableTransferConnectionError(err: unknown): boolean {
+ if (!(err instanceof Error)) return false;
+ const msg = err.message.toLowerCase();
+ return (
+ msg.includes("no response from server") ||
+ msg.includes("connection lost") ||
+ msg.includes("not connected") ||
+ msg.includes("econnreset") ||
+ msg.includes("econnrefused") ||
+ msg.includes("etimedout") ||
+ msg.includes("socket hang up") ||
+ msg.includes("protocol error") ||
+ msg.includes("connection closed") ||
+ msg.includes("channel open failure")
+ );
+}
+
+function isRecoverableTransferError(err: unknown): boolean {
+ return (
+ err instanceof TransferStalledError ||
+ err instanceof TransferConnectionLostError ||
+ isRecoverableTransferConnectionError(err)
+ );
+}
+
+async function probeDestResumeOffset(
+ destSftp: SFTPWrapper,
+ destPath: string,
+ fileSize: number,
+): Promise<number> {
+ try {
+ const destStat = await promisifySftpStat(destSftp, destPath);
+ return Math.min(destStat.size, fileSize);
+ } catch {
+ return 0;
+ }
+}
+
+function buildStreamTransferTimings(
+ transferId: string,
+ fileSize: number,
+ prepareDestMs?: number,
+): TransferTimings {
+ const progress = activeTransfers.get(transferId);
+ const wallStart = progress?.startedAt ?? Date.now();
+ const totalMs = elapsedMs(wallStart);
+ const prepare = prepareDestMs ?? progress?.timings?.prepareDestMs ?? 0;
+ const dataMs = Math.max(1, totalMs - prepare);
+
+ return {
+ ...progress?.timings,
+ prepareDestMs: prepare > 0 ? prepare : undefined,
+ transferMs: dataMs,
+ transferBytes: fileSize,
+ endToEndMbPerSec: computeTransferMbPerSec(fileSize, dataMs),
+ totalMs,
+ };
+}
+
+async function finalizeStreamTransferIfDestAtSize(
+ transferId: string,
+ destSftp: SFTPWrapper,
+ destPath: string,
+ expectedSize: number,
+ extra: Partial<TransferProgress> = {},
+): Promise<boolean> {
+ try {
+ const destSize = await probeDestResumeOffset(
+ destSftp,
+ destPath,
+ expectedSize,
+ );
+ if (destSize < expectedSize) {
+ return false;
+ }
+
+ fileLogger.info("Destination file complete — finalizing transfer", {
+ operation: "host_transfer_dest_complete",
+ transferId,
+ destSize,
+ expectedSize,
+ });
+
+ finalizeTransfer(transferId, {
+ status: "success",
+ phase: "transferring",
+ method: "stream",
+ bytesTransferred: expectedSize,
+ totalBytes: expectedSize,
+ destPath,
+ timings: buildStreamTransferTimings(transferId, expectedSize),
+ ...extra,
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function tryFinalizeStreamTransferIfDestComplete(
+ deps: HostTransferDeps,
+ transferId: string,
+ destSession: SSHSessionLike,
+ destPath: string,
+ expectedSize: number,
+ extra: Partial<TransferProgress> = {},
+): Promise<boolean> {
+ try {
+ const destSftp = await deps.getSessionSftp(destSession);
+ return finalizeStreamTransferIfDestAtSize(
+ transferId,
+ destSftp,
+ destPath,
+ expectedSize,
+ extra,
+ );
+ } catch {
+ return false;
+ }
+}
+
+async function reconnectDedicatedTransferSessions(
+ ctx: TransferReconnectContext,
+ parallelWorkers = 0,
+): Promise<{ sourceSession: SSHSessionLike; destSession: SSHSessionLike }> {
+ fileLogger.warn("Reconnecting dedicated transfer SSH sessions", {
+ operation: "transfer_ssh_reconnect",
+ transferId: ctx.transferId,
+ parallelWorkers,
+ });
+
+ closeAllTransferSessions(ctx.deps, ctx, parallelWorkers);
+
+ const [sourceSession, destSession] = await Promise.all([
+ ctx.deps.openDedicatedTransferSession(
+ ctx.browseSourceSessionId,
+ ctx.dedicatedSourceSessionId,
+ ctx.userId,
+ ctx.transferId,
+ { allowBrowseDisconnected: true },
+ ),
+ ctx.deps.openDedicatedTransferSession(
+ ctx.browseDestSessionId,
+ ctx.dedicatedDestSessionId,
+ ctx.userId,
+ ctx.transferId,
+ { allowBrowseDisconnected: true },
+ ),
+ ]);
+
+ return { sourceSession, destSession };
+}
+
+async function resetDedicatedTransferSessions(
+ ctx: TransferReconnectContext,
+ attempt: number,
+ reason: string,
+): Promise<{
+ sourceSession: SSHSessionLike;
+ destSession: SSHSessionLike;
+ sourceSftp: SFTPWrapper;
+ destSftp: SFTPWrapper;
+}> {
+ fileLogger.warn("Resetting transfer SSH sessions (fresh connection)", {
+ operation: "transfer_session_reset",
+ transferId: ctx.transferId,
+ attempt,
+ reason,
+ });
+
+ closeAllTransferSessions(ctx.deps, ctx, 0);
+
+ const delayMs =
+ TRANSFER_SESSION_RESET_DELAYS_MS[
+ Math.min(attempt - 1, TRANSFER_SESSION_RESET_DELAYS_MS.length - 1)
+ ] ?? 3000;
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+
+ const { sourceSession, destSession } =
+ await reconnectDedicatedTransferSessions(ctx, 0);
+ const sourceSftp = await ctx.deps.getSessionSftp(sourceSession);
+ const destSftp = await ctx.deps.getSessionSftp(destSession);
+
+ if (ctx.transferId) {
+ updateTransfer(ctx.transferId, { lastActivityAt: Date.now() });
+ }
+
+ return { sourceSession, destSession, sourceSftp, destSftp };
+}
+
+let cachedLocalAddresses: Set<string> | null = null;
+
+function normalizeHostAddress(host: string): string {
+ const trimmed = host.trim().toLowerCase();
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
+ return trimmed.slice(1, -1);
+ }
+ return trimmed.split(":")[0] ?? trimmed;
+}
+
+function getLocalAddresses(): Set<string> {
+ if (cachedLocalAddresses) return cachedLocalAddresses;
+
+ const addresses = new Set(["127.0.0.1", "::1", "localhost"]);
+ for (const ifaces of Object.values(networkInterfaces())) {
+ if (!ifaces) continue;
+ for (const iface of ifaces) {
+ if (!iface.internal && iface.family === "IPv4") {
+ addresses.add(iface.address.toLowerCase());
+ }
+ }
+ }
+ cachedLocalAddresses = addresses;
+ return addresses;
+}
+
+export function isLocalSshEndpoint(ip?: string): boolean {
+ if (!ip) return false;
+ const bare = normalizeHostAddress(ip);
+ if (bare === "localhost" || bare === "127.0.0.1" || bare === "::1") {
+ return true;
+ }
+ return getLocalAddresses().has(bare);
+}
+
+function createThrottledProgress(onProgress?: (bytes: number) => void) {
+ let pending = 0;
+ let lastFlush = 0;
+
+ const flush = () => {
+ if (pending > 0) {
+ onProgress?.(pending);
+ pending = 0;
+ lastFlush = Date.now();
+ }
+ };
+
+ return {
+ add(bytes: number) {
+ pending += bytes;
+ const now = Date.now();
+ if (now - lastFlush >= TRANSFER_PROGRESS_INTERVAL_MS) {
+ flush();
+ }
+ },
+ flush,
+ };
+}
+
+function escapeShell(s: string): string {
+ return s.replace(/'/g, "'\"'\"'");
+}
+
+async function detectTransferPlatform(
+ deps: HostTransferDeps,
+ session: SSHSessionLike,
+ pathHints: string[] = [],
+): Promise<TransferPlatform> {
+ if (session.transferPlatform) return session.transferPlatform;
+
+ for (const path of pathHints) {
+ const inferred = inferPlatformFromPath(path);
+ if (inferred === "windows") {
+ session.transferPlatform = "windows";
+ return "windows";
+ }
+ }
+
+ try {
+ const { code } = await execCommand(deps, session, "uname -s");
+ if (code === 0) {
+ session.transferPlatform = "unix";
+ return "unix";
+ }
+ } catch {
+ /* not unix */
+ }
+
+ try {
+ const { code } = await execCommand(
+ deps,
+ session,
+ 'cmd /c "if defined OS (exit 0) else (exit 1)"',
+ );
+ if (code === 0) {
+ session.transferPlatform = "windows";
+ return "windows";
+ }
+ } catch {
+ /* not cmd */
+ }
+
+ try {
+ const { code } = await execCommand(
+ deps,
+ session,
+ "powershell -NoProfile -Command \"if ($IsWindows -or $env:OS -like 'Windows*') { exit 0 } else { exit 1 }\"",
+ );
+ if (code === 0) {
+ session.transferPlatform = "windows";
+ return "windows";
+ }
+ } catch {
+ /* not powershell */
+ }
+
+ session.transferPlatform = "unix";
+ return "unix";
+}
+
+function isRootOnlyPath(path: string): boolean {
+ const normalized = normalizeSftpPath(path);
+ return (
+ normalized === "/" ||
+ /^\/[A-Za-z]:$/.test(normalized) ||
+ /^[A-Za-z]:$/.test(normalized)
+ );
+}
+
+function isPermissionError(err: Error): boolean {
+ const msg = err.message.toLowerCase();
+ return (
+ msg.includes("permission denied") ||
+ msg.includes("eacces") ||
+ msg.includes("access denied")
+ );
+}
+
+function promisifySftpStat(
+ sftp: SFTPWrapper,
+ path: string,
+): Promise<import("ssh2").Stats> {
+ return new Promise((resolve, reject) => {
+ sftp.stat(path, (err, stats) => {
+ if (err) reject(err);
+ else resolve(stats);
+ });
+ });
+}
+
+function promisifySftpUnlink(sftp: SFTPWrapper, path: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ sftp.unlink(path, (err) => {
+ if (err) reject(err);
+ else resolve();
+ });
+ });
+}
+
+function promisifySftpRmdir(sftp: SFTPWrapper, path: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ sftp.rmdir(path, (err) => {
+ if (err) reject(err);
+ else resolve();
+ });
+ });
+}
+
+async function ensureDirectoryTreeSftp(
+ sftp: SFTPWrapper,
+ dirPath: string,
+ created: Set<string> = new Set(),
+): Promise<void> {
+ const normalized = normalizeSftpPath(dirPath);
+ if (!normalized || isRootOnlyPath(normalized)) return;
+
+ const { root, segments } = splitPathSegments(normalized);
+ if (segments.length === 0) return;
+
+ for (let i = 0; i < segments.length; i++) {
+ const current = buildPathFromSegments(root, segments, i + 1);
+ if (created.has(current)) continue;
+
+ try {
+ await promisifySftpMkdir(sftp, current, 0o755);
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== "EEXIST") {
+ try {
+ const stats = await promisifySftpStat(sftp, current);
+ if (!stats.isDirectory()) throw err;
+ } catch {
+ throw err;
+ }
+ }
+ }
+ created.add(current);
+ }
+}
+
+async function deletePathSftp(sftp: SFTPWrapper, path: string): Promise<void> {
+ let stats: import("ssh2").Stats;
+ try {
+ stats = await promisifySftpStat(sftp, path);
+ } catch {
+ return;
+ }
+
+ if (stats.isDirectory()) {
+ const entries = await promisifySftpReaddir(sftp, path);
+ for (const entry of entries) {
+ if (entry.filename === "." || entry.filename === "..") continue;
+ await deletePathSftp(sftp, joinPath(path, entry.filename));
+ }
+ await promisifySftpRmdir(sftp, path);
+ return;
+ }
+
+ if (stats.isFile()) {
+ await promisifySftpUnlink(sftp, path);
+ }
+}
+
+function promisifySftpMkdir(
+ sftp: SFTPWrapper,
+ path: string,
+ mode: number,
+): Promise<void> {
+ return new Promise((resolve, reject) => {
+ sftp.mkdir(path, { mode }, (err) => {
+ if (err && (err as NodeJS.ErrnoException).code !== "EEXIST") {
+ reject(err);
+ } else {
+ resolve();
+ }
+ });
+ });
+}
+
+function promisifySftpChmod(
+ sftp: SFTPWrapper,
+ path: string,
+ mode: number,
+): Promise<void> {
+ return new Promise((resolve, reject) => {
+ sftp.chmod(path, mode, (err) => {
+ if (err) reject(err);
+ else resolve();
+ });
+ });
+}
+
+function promisifySftpReaddir(
+ sftp: SFTPWrapper,
+ path: string,
+): Promise<Array<{ filename: string; attrs: import("ssh2").Stats }>> {
+ return new Promise((resolve, reject) => {
+ sftp.readdir(path, (err, list) => {
+ if (err) reject(err);
+ else resolve(list);
+ });
+ });
+}
+
+function execCommand(
+ deps: HostTransferDeps,
+ session: SSHSessionLike,
+ command: string,
+): Promise<{ code: number; stderr: string }> {
+ return new Promise((resolve, reject) => {
+ deps.execChannel(session, command, (err, stream) => {
+ if (err) {
+ reject(err);
+ return;
+ }
+ let stderr = "";
+ stream.on("data", () => {
+ /* consume stdout */
+ });
+ stream.stderr.on("data", (data: Buffer) => {
+ stderr += data.toString();
+ });
+ stream.on("close", (code: number) => {
+ resolve({ code: code ?? 0, stderr });
+ });
+ stream.on("error", (streamErr: Error) => {
+ reject(streamErr);
+ });
+ });
+ });
+}
+
+async function checkTarAvailable(
+ deps: HostTransferDeps,
+ session: SSHSessionLike,
+): Promise<boolean> {
+ const platform = await detectTransferPlatform(deps, session);
+ if (platform === "windows") return false;
+
+ try {
+ const { code } = await execCommand(deps, session, "command -v tar");
+ return code === 0;
+ } catch {
+ return false;
+ }
+}
+
+async function ensureDestDirectory(
+ deps: HostTransferDeps,
+ destSession: SSHSessionLike,
+ dirPath: string,
+ created: Set<string> = new Set(),
+): Promise<void> {
+ const destSftp = await deps.getSessionSftp(destSession);
+ await ensureDirectoryTreeSftp(destSftp, dirPath, created);
+}
+
+function updateTransfer(
+ transferId: string,
+ patch: Partial<TransferProgress>,
+): void {
+ const current = activeTransfers.get(transferId);
+ if (current) {
+ const next: TransferProgress = { ...current, ...patch };
+ if (
+ patch.bytesTransferred !== undefined &&
+ current.totalBytes !== undefined &&
+ current.totalBytes > 0
+ ) {
+ next.bytesTransferred = Math.min(
+ patch.bytesTransferred,
+ current.totalBytes,
+ );
+ }
+ if (
+ patch.bytesTransferred !== undefined &&
+ patch.bytesTransferred !== current.bytesTransferred
+ ) {
+ next.lastActivityAt = Date.now();
+ }
+ activeTransfers.set(transferId, next);
+ }
+}
+
+async function closeTransferHandlesSafe(
+ handles: TransferFileHandles | null | undefined,
+): Promise<void> {
+ if (!handles) return;
+ await Promise.race([
+ handles.close(),
+ new Promise<void>((resolve) =>
+ setTimeout(resolve, TRANSFER_HANDLE_CLOSE_TIMEOUT_MS),
+ ),
+ ]).catch(() => {});
+}
+
+function checkHungTransfers(): void {
+ const now = Date.now();
+ for (const [transferId, progress] of activeTransfers) {
+ if (progress.status !== "running") continue;
+
+ if (
+ progress.method === "stream" &&
+ progress.totalBytes &&
+ progress.totalBytes > 0 &&
+ progress.bytesTransferred !== undefined &&
+ progress.bytesTransferred >= progress.totalBytes
+ ) {
+ fileLogger.info("Transfer progress at 100% — marking complete", {
+ operation: "host_transfer_progress_complete",
+ transferId,
+ bytesTransferred: progress.bytesTransferred,
+ totalBytes: progress.totalBytes,
+ });
+ finalizeTransfer(transferId, {
+ status: "success",
+ phase: "transferring",
+ method: "stream",
+ bytesTransferred: progress.totalBytes,
+ totalBytes: progress.totalBytes,
+ sourcePaths: progress.sourcePaths,
+ destPath: progress.destPath,
+ moveRequested: progress.moveRequested,
+ timings: buildStreamTransferTimings(transferId, progress.totalBytes),
+ });
+ continue;
+ }
+
+ if (progress.phase === "reconnecting") {
+ const reconnectStarted =
+ progress.reconnectingAt ?? progress.lastActivityAt ?? now;
+ if (now - reconnectStarted < HUNG_RECONNECTING_MS) continue;
+ }
+
+ const lastActivity = progress.lastActivityAt ?? progress.startedAt ?? now;
+ if (now - lastActivity < HUNG_TRANSFER_MS) continue;
+
+ fileLogger.error("Force-finalizing unresponsive transfer", {
+ operation: "host_transfer_hung",
+ transferId,
+ lastActivityAt: lastActivity,
+ bytesTransferred: progress.bytesTransferred,
+ });
+
+ finalizeTransfer(
+ transferId,
+ failedProgressPatch(progress, {
+ status: "error",
+ phase:
+ progress.phase === "reconnecting" ? "transferring" : progress.phase,
+ message: "Transfer stopped responding",
+ method: progress.method,
+ sourcePaths: progress.sourcePaths,
+ destPath: progress.destPath,
+ bytesTransferred: Math.min(
+ progress.bytesTransferred ?? 0,
+ progress.totalBytes ?? Number.MAX_SAFE_INTEGER,
+ ),
+ totalBytes: progress.totalBytes,
+ itemsCompleted: progress.itemsCompleted,
+ totalItems: progress.totalItems,
+ moveRequested: progress.moveRequested,
+ }),
+ );
+ }
+}
+
+/** Before marking a stalled stream transfer as failed, verify the destination file size. */
+export async function probeHungStreamTransfers(
+ deps: HostTransferDeps,
+): Promise<void> {
+ const now = Date.now();
+ for (const [transferId, progress] of activeTransfers) {
+ if (progress.status !== "running" || progress.method !== "stream") {
+ continue;
+ }
+ if (!progress.destPath || !progress.totalBytes || !progress.userId) {
+ continue;
+ }
+
+ const lastActivity = progress.lastActivityAt ?? progress.startedAt ?? now;
+ if (now - lastActivity < HUNG_TRANSFER_MS) {
+ continue;
+ }
+
+ const browseDestId = progress.destSessionId;
+ if (!browseDestId) {
+ continue;
+ }
+
+ const destId = progress.dedicatedDestSessionId ?? `xfer:${transferId}:dst`;
+ let destSession = deps.sshSessions[destId];
+ if (!destSession?.isConnected) {
+ try {
+ destSession = await deps.openDedicatedTransferSession(
+ browseDestId,
+ destId,
+ progress.userId,
+ transferId,
+ { allowBrowseDisconnected: true },
+ );
+ } catch {
+ continue;
+ }
+ }
+
+ await tryFinalizeStreamTransferIfDestComplete(
+ deps,
+ transferId,
+ destSession,
+ progress.destPath,
+ progress.totalBytes,
+ {
+ sourcePaths: progress.sourcePaths,
+ moveRequested: progress.moveRequested,
+ },
+ );
+ }
+}
+
+function trackDestArtifact(transferId: string, path: string): void {
+ const normalized = normalizeSftpPath(path);
+ const current = activeTransfers.get(transferId);
+ if (!current) return;
+ const existing = current.destArtifacts ?? [];
+ if (existing.includes(normalized)) return;
+ updateTransfer(transferId, { destArtifacts: [...existing, normalized] });
+}
+
+function buildCleanupPaths(progress: TransferProgress): string[] {
+ const paths = new Set<string>(progress.destArtifacts ?? []);
+
+ if (progress.tempArchivePath) {
+ paths.add(normalizeSftpPath(progress.tempArchivePath));
+ }
+
+ if (paths.size === 0 && progress.destPath) {
+ if (progress.method === "stream") {
+ paths.add(normalizeSftpPath(progress.destPath));
+ } else if (progress.sourcePaths?.length) {
+ for (const sourcePath of progress.sourcePaths) {
+ paths.add(
+ normalizeSftpPath(joinPath(progress.destPath, basename(sourcePath))),
+ );
+ }
+ }
+ }
+
+ return [...paths];
+}
+
+function partialDestWasWritten(progress: TransferProgress): boolean {
+ return (
+ (progress.bytesTransferred ?? 0) > 0 ||
+ (progress.itemsCompleted ?? 0) > 0 ||
+ (progress.destArtifacts?.length ?? 0) > 0
+ );
+}
+
+function failedProgressPatch(
+ current: TransferProgress | undefined,
+ patch: Partial<TransferProgress>,
+): Partial<TransferProgress> {
+ const merged = { ...current, ...patch } as TransferProgress;
+ const hasPartial = partialDestWasWritten(merged);
+ return {
+ ...patch,
+ partialDestRemaining: hasPartial,
+ retryable: hasPartial && !!current?.requestSnapshot,
+ };
+}
+
+function cancelledProgressPatch(
+ current: TransferProgress | undefined,
+ patch: Partial<TransferProgress>,
+): Partial<TransferProgress> {
+ const merged = { ...current, ...patch } as TransferProgress;
+ return {
+ ...patch,
+ partialDestRemaining: partialDestWasWritten(merged),
+ };
+}
+
+function finalizeTransfer(
+ transferId: string,
+ patch: Partial<TransferProgress>,
+): TransferProgress {
+ cancelRequestedTransfers.delete(transferId);
+ const watchdog = cancelWatchdogs.get(transferId);
+ if (watchdog) {
+ clearTimeout(watchdog);
+ cancelWatchdogs.delete(transferId);
+ }
+ const current = activeTransfers.get(transferId);
+ const result: TransferProgress = {
+ transferId,
+ status: "success",
+ phase: "transferring",
+ ...current,
+ ...patch,
+ };
+ activeTransfers.set(transferId, result);
+ return result;
+}
+
+function elapsedMs(start: number): number {
+ return Date.now() - start;
+}
+
+export function computeTransferMbPerSec(
+ bytes: number,
+ ms: number,
+): number | undefined {
+ if (ms <= 0 || bytes <= 0) return undefined;
+ return ((bytes / ms) * 1000) / (1024 * 1024);
+}
+
+interface HopWallClock {
+ firstAt: number | null;
+ lastAt: number | null;
+}
+
+function createHopWallClock(): HopWallClock {
+ return { firstAt: null, lastAt: null };
+}
+
+function noteHopStart(
+ clock: HopWallClock,
+ t: number = performance.now(),
+): void {
+ if (clock.firstAt === null) clock.firstAt = t;
+}
+
+function noteHopEnd(clock: HopWallClock, t: number = performance.now()): void {
+ clock.lastAt = t;
+}
+
+function hopSpanMs(clock: HopWallClock): number {
+ if (clock.firstAt === null || clock.lastAt === null) return 0;
+ return Math.max(0, clock.lastAt - clock.firstAt);
+}
+
+interface PipelinedXferStats {
+ bytes: number;
+ sourceReadSpanMs: number;
+ destWriteSpanMs: number;
+ destWriteKind: "sftp" | "local";
+}
+
+function createEmptyXferStats(): PipelinedXferStats {
+ return {
+ bytes: 0,
+ sourceReadSpanMs: 0,
+ destWriteSpanMs: 0,
+ destWriteKind: "sftp",
+ };
+}
+
+function mergeXferStats(
+ target: PipelinedXferStats,
+ source: PipelinedXferStats,
+): void {
+ target.bytes += source.bytes;
+ target.sourceReadSpanMs += source.sourceReadSpanMs;
+ target.destWriteSpanMs += source.destWriteSpanMs;
+ target.destWriteKind = source.destWriteKind;
+}
+
+function buildTransferHopTimings(
+ stats: PipelinedXferStats,
+ transferMs: number,
+): Pick<TransferTimings, "transferBytes" | "endToEndMbPerSec" | "hops"> {
+ const hops: TransferHopMetrics[] = [];
+
+ const sourceRate = computeTransferMbPerSec(
+ stats.bytes,
+ stats.sourceReadSpanMs,
+ );
+ if (sourceRate !== undefined) {
+ hops.push({
+ id: "source_read",
+ bytes: stats.bytes,
+ spanMs: stats.sourceReadSpanMs,
+ mbPerSec: sourceRate,
+ });
+ }
+
+ const destHopId: TransferHopId =
+ stats.destWriteKind === "local" ? "dest_local_write" : "dest_sftp_write";
+ const destRate = computeTransferMbPerSec(stats.bytes, stats.destWriteSpanMs);
+ if (destRate !== undefined) {
+ hops.push({
+ id: destHopId,
+ bytes: stats.bytes,
+ spanMs: stats.destWriteSpanMs,
+ mbPerSec: destRate,
+ });
+ }
+
+ return {
+ transferBytes: stats.bytes,
+ endToEndMbPerSec: computeTransferMbPerSec(stats.bytes, transferMs),
+ hops,
+ };
+}
+
+async function deleteSourcePathsAfterSuccess(
+ deps: HostTransferDeps,
+ transferId: string,
+ sourceSession: SSHSessionLike,
+ sourcePaths: string[],
+): Promise<number> {
+ const deleteStart = Date.now();
+ await deleteSourcePaths(deps, sourceSession, sourcePaths);
+ const sourceDeleteMs = elapsedMs(deleteStart);
+ updateTransfer(transferId, {
+ sourceDeleted: true,
+ timings: {
+ ...activeTransfers.get(transferId)?.timings,
+ sourceDeleteMs,
+ },
+ });
+ return sourceDeleteMs;
+}
+
+async function ensureDestParentForFile(
+ deps: HostTransferDeps,
+ destSession: SSHSessionLike,
+ filePath: string,
+): Promise<void> {
+ const parent = dirname(filePath);
+ if (!parent || isRootOnlyPath(parent)) return;
+ await ensureDestDirectory(deps, destSession, parent);
+}
+
+interface FileWorkItem {
+ sourcePath: string;
+ destPath: string;
+ mode: number;
+ size: number;
+}
+
+async function collectFileWorkItems(
+ sftp: SFTPWrapper,
+ sourcePath: string,
+ destRoot: string,
+ destBaseName?: string,
+): Promise<FileWorkItem[]> {
+ const stats = await promisifySftpStat(sftp, sourcePath);
+ const name = destBaseName ?? basename(sourcePath);
+ const destPath = joinPath(destRoot, name);
+
+ if (stats.isFile()) {
+ return [
+ {
+ sourcePath,
+ destPath,
+ mode: stats.mode & 0o7777,
+ size: stats.size,
+ },
+ ];
+ }
+
+ if (!stats.isDirectory()) {
+ return [];
+ }
+
+ const items: FileWorkItem[] = [];
+ const walk = async (srcDir: string, dstDir: string) => {
+ const entries = await promisifySftpReaddir(sftp, srcDir);
+ for (const entry of entries) {
+ if (entry.filename === "." || entry.filename === "..") continue;
+ const srcChild = joinPath(srcDir, entry.filename);
+ const dstChild = joinPath(dstDir, entry.filename);
+
+ if (entry.attrs.isDirectory()) {
+ await walk(srcChild, dstChild);
+ } else if (entry.attrs.isFile()) {
+ items.push({
+ sourcePath: srcChild,
+ destPath: dstChild,
+ mode: entry.attrs.mode & 0o7777,
+ size: entry.attrs.size,
+ });
+ }
+ }
+ };
+
+ await walk(sourcePath, destPath);
+ return items;
+}
+
+async function scanSourcePathsForRouting(
+ sftp: SFTPWrapper,
+ sourcePaths: string[],
+ transferId: string,
+) {
+ const scanItems: Array<{ sourcePath: string; size: number }> = [];
+ for (const sourcePath of sourcePaths) {
+ throwIfCancelled(transferId);
+ const work = await collectFileWorkItems(sftp, sourcePath, "/");
+ scanItems.push(
+ ...work.map((w) => ({ sourcePath: w.sourcePath, size: w.size })),
+ );
+ }
+ return buildTransferScanSummary(scanItems);
+}
+
+function promisifySftpOpen(
+ sftp: SFTPWrapper,
+ path: string,
+ flags: number,
+ mode: number,
+): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ sftp.open(path, flags, mode, (err, handle) => {
+ if (err) reject(err);
+ else resolve(handle);
+ });
+ });
+}
+
+function promisifySftpClose(sftp: SFTPWrapper, handle: Buffer): Promise<void> {
+ return new Promise((resolve, reject) => {
+ sftp.close(handle, (err) => {
+ if (err) reject(err);
+ else resolve();
+ });
+ });
+}
+
+function promisifySftpFstat(
+ sftp: SFTPWrapper,
+ handle: Buffer,
+): Promise<import("ssh2").Stats> {
+ return new Promise((resolve, reject) => {
+ sftp.fstat(handle, (err, stats) => {
+ if (err) reject(err);
+ else resolve(stats);
+ });
+ });
+}
+
+function promisifySftpWrite(
+ sftp: SFTPWrapper,
+ handle: Buffer,
+ buffer: Buffer,
+ offset: number,
+ length: number,
+ position: number,
+): Promise<void> {
+ return new Promise((resolve, reject) => {
+ sftp.write(handle, buffer, offset, length, position, (err) => {
+ if (err) reject(err);
+ else resolve();
+ });
+ });
+}
+
+interface PipelinedXferOptions {
+ fileSize?: number;
+ initialOffset?: number;
+ parallelSegmentCount?: number;
+ onProgress?: (bytes: number) => void;
+ shouldAbort?: () => boolean;
+ transferId?: string;
+ segmentIndex?: number;
+ reconnect?: TransferReconnectContext;
+ onResumeOffset?: (offset: number) => void;
+}
+
+interface SegmentCopyJob {
+ offset: number;
+ length: number;
+ segmentIndex: number;
+}
+
+function clampParallelSegmentCount(value?: number): number {
+ const n = value ?? DEFAULT_PARALLEL_SEGMENT_COUNT;
+ return Math.max(1, Math.min(MAX_PARALLEL_SEGMENT_COUNT, Math.floor(n)));
+}
+
+function buildSegmentCopyJobs(
+ fileSize: number,
+ initialOffset: number,
+ destResumeSize: number,
+): SegmentCopyJob[] {
+ const jobs: SegmentCopyJob[] = [];
+ for (
+ let offset = initialOffset;
+ offset < fileSize;
+ offset += SFTP_XFER_SEGMENT_SIZE
+ ) {
+ const length = Math.min(SFTP_XFER_SEGMENT_SIZE, fileSize - offset);
+ const segmentIndex = Math.floor(offset / SFTP_XFER_SEGMENT_SIZE);
+ if (destResumeSize >= offset + length) {
+ continue;
+ }
+ const start = destResumeSize > offset ? destResumeSize : offset;
+ jobs.push({
+ offset: start,
+ length: offset + length - start,
+ segmentIndex,
+ });
+ }
+ return jobs;
+}
+
+function closeAllTransferSessions(
+ deps: HostTransferDeps,
+ ctx: TransferReconnectContext,
+ parallelWorkers: number,
+): void {
+ deps.closeDedicatedTransferSession(ctx.dedicatedSourceSessionId);
+ deps.closeDedicatedTransferSession(ctx.dedicatedDestSessionId);
+ for (let i = 0; i < parallelWorkers; i++) {
+ deps.closeDedicatedTransferSession(`${ctx.dedicatedSourceSessionId}:p${i}`);
+ deps.closeDedicatedTransferSession(`${ctx.dedicatedDestSessionId}:p${i}`);
+ }
+}
+
+interface TransferFileHandles {
+ sourceSftp: SFTPWrapper;
+ destSftp: SFTPWrapper;
+ srcHandle: Buffer;
+ dstHandle: Buffer;
+ close: () => Promise<void>;
+}
+
+async function openTransferFileHandles(
+ sourceSftp: SFTPWrapper,
+ destSftp: SFTPWrapper,
+ sourcePath: string,
+ destPath: string,
+ resume: boolean,
+): Promise<TransferFileHandles> {
+ const srcHandle = await promisifySftpOpen(
+ sourceSftp,
+ sourcePath,
+ SFTP_OPEN_READ,
+ 0o666,
+ );
+ const dstHandle = await promisifySftpOpen(
+ destSftp,
+ destPath,
+ resume ? SFTP_OPEN_WRITE_RESUME : SFTP_OPEN_WRITE,
+ 0o666,
+ );
+
+ return {
+ sourceSftp,
+ destSftp,
+ srcHandle,
+ dstHandle,
+ close: async () => {
+ await promisifySftpClose(sourceSftp, srcHandle).catch(() => {});
+ await promisifySftpClose(destSftp, dstHandle).catch(() => {});
+ },
+ };
+}
+
+/**
+ * Parallel SFTP copy using the same scheduling model as ssh2's fastXfer.
+ * Scoped to [fileBaseOffset, fileBaseOffset + byteLength) so callers can reset
+ * scheduler state between segments on large files.
+ */
+async function runFastSftpCopy(
+ sourceSftp: SFTPWrapper,
+ srcHandle: Buffer,
+ destSftp: SFTPWrapper,
+ dstHandle: Buffer,
+ byteLength: number,
+ fileBaseOffset: number,
+ options: PipelinedXferOptions,
+ sourceReadClock: ReturnType<typeof createHopWallClock>,
+ destWriteClock: ReturnType<typeof createHopWallClock>,
+): Promise<void> {
+ let concurrency = SFTP_XFER_CONCURRENCY;
+ let chunkSize = SFTP_XFER_CHUNK_SIZE;
+ let bufsize = chunkSize * concurrency;
+ while (bufsize > byteLength && concurrency > 1) {
+ bufsize -= chunkSize;
+ concurrency -= 1;
+ }
+ if (byteLength <= chunkSize) {
+ chunkSize = byteLength;
+ concurrency = 1;
+ bufsize = byteLength;
+ }
+
+ const readbuf = Buffer.alloc(bufsize);
+ const progress = createThrottledProgress(options.onProgress);
+ let lastActivity = Date.now();
+ let stallTimer: ReturnType<typeof setInterval> | undefined;
+
+ await new Promise<void>((resolve, reject) => {
+ let finished = false;
+ let hadError = false;
+ let pdst = 0;
+ let total = 0;
+
+ const fail = (err: Error) => {
+ if (hadError) return;
+ hadError = true;
+ finished = true;
+ progress.flush();
+ reject(err);
+ };
+
+ const succeed = () => {
+ if (finished) return;
+ finished = true;
+ progress.flush();
+ resolve();
+ };
+
+ stallTimer = setInterval(() => {
+ if (finished) return;
+ if (options.shouldAbort?.()) {
+ fail(new TransferCancelledError());
+ return;
+ }
+ if (Date.now() - lastActivity > 45000) {
+ fail(
+ new TransferStalledError(
+ fileBaseOffset + total,
+ options.segmentIndex,
+ ),
+ );
+ }
+ }, 10000);
+
+ const onread = (
+ err: Error | undefined,
+ nb: number,
+ _data: Buffer | undefined,
+ localDstPos: number,
+ datapos: number,
+ origChunkLen: number,
+ ) => {
+ if (err) {
+ fail(err);
+ return;
+ }
+ if (options.shouldAbort?.()) {
+ fail(new TransferCancelledError());
+ return;
+ }
+
+ noteHopStart(destWriteClock);
+ destSftp.write(
+ dstHandle,
+ readbuf,
+ datapos,
+ nb,
+ fileBaseOffset + localDstPos,
+ (writeErr: Error | undefined) => {
+ noteHopEnd(destWriteClock);
+ if (writeErr) {
+ fail(writeErr);
+ return;
+ }
+
+ total += nb;
+ progress.add(nb);
+ lastActivity = Date.now();
+
+ if (options.shouldAbort?.()) {
+ fail(new TransferCancelledError());
+ return;
+ }
+
+ if (nb < origChunkLen) {
+ singleRead(datapos, localDstPos + nb, origChunkLen - nb);
+ return;
+ }
+
+ if (total >= byteLength) {
+ succeed();
+ return;
+ }
+
+ if (pdst >= byteLength) {
+ return;
+ }
+
+ const chunk = Math.min(chunkSize, byteLength - pdst);
+ singleRead(datapos, pdst, chunk);
+ pdst += chunk;
+ },
+ );
+ };
+
+ const makeCb =
+ (psrc: number, localFilePos: number, chunk: number) =>
+ (err: Error | undefined, nb?: number, data?: Buffer) => {
+ onread(err, nb ?? 0, data, localFilePos, psrc, chunk);
+ };
+
+ const singleRead = (psrc: number, localFilePos: number, chunk: number) => {
+ if (options.shouldAbort?.()) {
+ fail(new TransferCancelledError());
+ return;
+ }
+ noteHopStart(sourceReadClock);
+ sourceSftp.read(
+ srcHandle,
+ readbuf,
+ psrc,
+ chunk,
+ fileBaseOffset + localFilePos,
+ (err, nb, data) => {
+ noteHopEnd(sourceReadClock);
+ makeCb(psrc, localFilePos, chunk)(err, nb, data);
+ },
+ );
+ };
+
+ const startReads = () => {
+ let reads = 0;
+ let psrc = 0;
+ while (pdst < byteLength && reads < concurrency) {
+ const chunk = Math.min(chunkSize, byteLength - pdst);
+ singleRead(psrc, pdst, chunk);
+ psrc += chunk;
+ pdst += chunk;
+ reads += 1;
+ }
+ };
+
+ startReads();
+ }).finally(() => {
+ if (stallTimer) clearInterval(stallTimer);
+ });
+}
+
+async function runFastSftpCopySegmented(
+ handles: TransferFileHandles,
+ fileSize: number,
+ options: PipelinedXferOptions,
+ sourceReadClock: ReturnType<typeof createHopWallClock>,
+ destWriteClock: ReturnType<typeof createHopWallClock>,
+ sourcePath: string,
+ destPath: string,
+): Promise<TransferFileHandles> {
+ const parallel = clampParallelSegmentCount(options.parallelSegmentCount);
+ if (parallel > 1 && options.reconnect) {
+ return runFastSftpCopySegmentedParallel(
+ handles,
+ fileSize,
+ { ...options, parallelSegmentCount: parallel },
+ sourceReadClock,
+ destWriteClock,
+ sourcePath,
+ destPath,
+ );
+ }
+ return runFastSftpCopySegmentedSequential(
+ handles,
+ fileSize,
+ options,
+ sourceReadClock,
+ destWriteClock,
+ sourcePath,
+ destPath,
+ );
+}
+
+async function runFastSftpCopySegmentedSequential(
+ handles: TransferFileHandles,
+ fileSize: number,
+ options: PipelinedXferOptions,
+ sourceReadClock: ReturnType<typeof createHopWallClock>,
+ destWriteClock: ReturnType<typeof createHopWallClock>,
+ sourcePath: string,
+ destPath: string,
+): Promise<TransferFileHandles> {
+ const transferId = options.transferId;
+ const segmentCount = Math.ceil(fileSize / SFTP_XFER_SEGMENT_SIZE);
+ let offset = options.initialOffset ?? 0;
+ let currentHandles = handles;
+
+ while (offset < fileSize) {
+ if (options.shouldAbort?.()) {
+ throw new TransferCancelledError();
+ }
+
+ let segLen = Math.min(SFTP_XFER_SEGMENT_SIZE, fileSize - offset);
+ const segmentIndex = Math.floor(offset / SFTP_XFER_SEGMENT_SIZE);
+ let attempts = 0;
+
+ while (true) {
+ fileLogger.info("Transfer segment started", {
+ operation: "host_transfer_segment",
+ transferId,
+ segmentIndex,
+ segmentCount,
+ fileBaseOffset: offset,
+ byteLength: segLen,
+ attempt: attempts + 1,
+ });
+
+ try {
+ await runFastSftpCopy(
+ currentHandles.sourceSftp,
+ currentHandles.srcHandle,
+ currentHandles.destSftp,
+ currentHandles.dstHandle,
+ segLen,
+ offset,
+ { ...options, segmentIndex },
+ sourceReadClock,
+ destWriteClock,
+ );
+
+ fileLogger.info("Transfer segment completed", {
+ operation: "host_transfer_segment",
+ transferId,
+ segmentIndex,
+ segmentCount,
+ fileBaseOffset: offset,
+ byteLength: segLen,
+ });
+
+ offset += segLen;
+ break;
+ } catch (err) {
+ if (err instanceof TransferCancelledError) {
+ throw err;
+ }
+
+ const message =
+ err instanceof Error ? err.message : "Segment transfer failed";
+ const recoverable =
+ options.reconnect &&
+ isRecoverableTransferError(err) &&
+ attempts < SFTP_SEQUENTIAL_SEGMENT_MAX_ATTEMPTS;
+
+ fileLogger.error("Transfer segment failed", err, {
+ operation: "host_transfer_segment",
+ transferId,
+ segmentIndex,
+ fileBaseOffset: offset,
+ byteLength: segLen,
+ attempt: attempts + 1,
+ maxAttempts: SFTP_SEQUENTIAL_SEGMENT_MAX_ATTEMPTS,
+ recoverable,
+ });
+
+ if (!recoverable || !options.reconnect) {
+ throw new Error(
+ `Segment ${segmentIndex} failed at offset ${offset}: ${message}`,
+ );
+ }
+
+ attempts += 1;
+ await closeTransferHandlesSafe(currentHandles);
+
+ const { sourceSftp, destSftp } = await resetDedicatedTransferSessions(
+ options.reconnect,
+ attempts,
+ message,
+ );
+
+ let resumeOffset = offset;
+ try {
+ resumeOffset = await probeDestResumeOffset(
+ destSftp,
+ destPath,
+ fileSize,
+ );
+ } catch {
+ /* use last known offset */
+ }
+
+ if (resumeOffset > offset) {
+ fileLogger.info("Resuming transfer from destination size", {
+ operation: "host_transfer_resume",
+ transferId,
+ previousOffset: offset,
+ resumeOffset,
+ fileSize,
+ });
+ offset = resumeOffset;
+ options.onResumeOffset?.(offset);
+ }
+
+ if (offset >= fileSize) {
+ break;
+ }
+
+ segLen = Math.min(SFTP_XFER_SEGMENT_SIZE, fileSize - offset);
+ currentHandles = await openTransferFileHandles(
+ sourceSftp,
+ destSftp,
+ sourcePath,
+ destPath,
+ offset > 0,
+ );
+ }
+ }
+ }
+
+ return currentHandles;
+}
+
+interface WorkerSessionCache {
+ sourceSession: SSHSessionLike;
+ destSession: SSHSessionLike;
+ sourceSftp: SFTPWrapper;
+ destSftp: SFTPWrapper;
+}
+
+async function runFastSftpCopySegmentedParallel(
+ handles: TransferFileHandles,
+ fileSize: number,
+ options: PipelinedXferOptions,
+ sourceReadClock: ReturnType<typeof createHopWallClock>,
+ destWriteClock: ReturnType<typeof createHopWallClock>,
+ sourcePath: string,
+ destPath: string,
+): Promise<TransferFileHandles> {
+ const transferId = options.transferId;
+ const parallel = clampParallelSegmentCount(options.parallelSegmentCount);
+ const initialOffset = options.initialOffset ?? 0;
+ const reconnect = options.reconnect!;
+
+ let destResumeSize = initialOffset;
+ try {
+ destResumeSize = await probeDestResumeOffset(
+ handles.destSftp,
+ destPath,
+ fileSize,
+ );
+ } catch {
+ /* use initial offset */
+ }
+
+ const jobs = buildSegmentCopyJobs(fileSize, initialOffset, destResumeSize);
+ if (jobs.length === 0) {
+ options.onResumeOffset?.(fileSize);
+ return handles;
+ }
+
+ fileLogger.info("Starting parallel segment transfer", {
+ operation: "host_transfer_parallel",
+ transferId,
+ parallel,
+ segmentJobs: jobs.length,
+ fileSize,
+ destResumeSize,
+ });
+
+ updateTransfer(transferId ?? "", {
+ parallelSegmentCount: parallel,
+ bytesTransferred: destResumeSize,
+ });
+ options.onResumeOffset?.(destResumeSize);
+
+ let aggregateBytes = destResumeSize;
+ let lastDestProbeAt = 0;
+ const DEST_PROGRESS_PROBE_MS = 1500;
+
+ const refreshDestProgress = async (force = false): Promise<number> => {
+ const now = Date.now();
+ if (!force && now - lastDestProbeAt < DEST_PROGRESS_PROBE_MS) {
+ return aggregateBytes;
+ }
+ lastDestProbeAt = now;
+ try {
+ const size = await probeDestResumeOffset(
+ handles.destSftp,
+ destPath,
+ fileSize,
+ );
+ if (size > aggregateBytes) {
+ aggregateBytes = size;
+ } else if (force) {
+ aggregateBytes = size;
+ }
+ options.onResumeOffset?.(aggregateBytes);
+ if (transferId) {
+ updateTransfer(transferId, { bytesTransferred: aggregateBytes });
+ }
+ } catch {
+ /* keep last known progress */
+ }
+ return aggregateBytes;
+ };
+
+ /** Parallel lanes share one dest file — use dest size, not summed segment deltas. */
+ const reportDelta = (_delta: number) => {
+ void refreshDestProgress(false);
+ };
+
+ let nextJobIndex = 0;
+ const workerCaches = new Map<number, WorkerSessionCache>();
+
+ const resetParallelLane = async (
+ workerId: number,
+ attempt: number,
+ reason: string,
+ ): Promise<void> => {
+ fileLogger.warn("Resetting parallel transfer lane (fresh SSH session)", {
+ operation: "transfer_lane_reset",
+ transferId: reconnect.transferId,
+ parallelLane: workerId,
+ attempt,
+ reason,
+ });
+ workerCaches.delete(workerId);
+ reconnect.deps.closeDedicatedTransferSession(
+ `${reconnect.dedicatedSourceSessionId}:p${workerId}`,
+ );
+ reconnect.deps.closeDedicatedTransferSession(
+ `${reconnect.dedicatedDestSessionId}:p${workerId}`,
+ );
+ const delayMs =
+ TRANSFER_SESSION_RESET_DELAYS_MS[
+ Math.min(attempt - 1, TRANSFER_SESSION_RESET_DELAYS_MS.length - 1)
+ ] ?? 3000;
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+ };
+
+ const ensureWorkerSessions = async (
+ workerId: number,
+ ): Promise<WorkerSessionCache> => {
+ const cached = workerCaches.get(workerId);
+ if (cached) return cached;
+
+ const srcId = `${reconnect.dedicatedSourceSessionId}:p${workerId}`;
+ const dstId = `${reconnect.dedicatedDestSessionId}:p${workerId}`;
+ const sourceSession = await reconnect.deps.openDedicatedTransferSession(
+ reconnect.browseSourceSessionId,
+ srcId,
+ reconnect.userId,
+ reconnect.transferId,
+ { allowBrowseDisconnected: true },
+ );
+ const destSession = await reconnect.deps.openDedicatedTransferSession(
+ reconnect.browseDestSessionId,
+ dstId,
+ reconnect.userId,
+ reconnect.transferId,
+ { allowBrowseDisconnected: true },
+ );
+ const sourceSftp = await reconnect.deps.getSessionSftp(sourceSession);
+ const destSftp = await reconnect.deps.getSessionSftp(destSession);
+ const entry: WorkerSessionCache = {
+ sourceSession,
+ destSession,
+ sourceSftp,
+ destSftp,
+ };
+ workerCaches.set(workerId, entry);
+ return entry;
+ };
+
+ const runSegmentJob = async (
+ job: SegmentCopyJob,
+ workerId: number,
+ ): Promise<void> => {
+ let attempts = 0;
+
+ while (true) {
+ if (options.shouldAbort?.()) {
+ throw new TransferCancelledError();
+ }
+
+ fileLogger.info("Transfer segment started", {
+ operation: "host_transfer_segment",
+ transferId,
+ segmentIndex: job.segmentIndex,
+ fileBaseOffset: job.offset,
+ byteLength: job.length,
+ attempt: attempts + 1,
+ parallelLane: workerId,
+ });
+
+ const { sourceSftp, destSftp } = await ensureWorkerSessions(workerId);
+ const laneHandles = await openTransferFileHandles(
+ sourceSftp,
+ destSftp,
+ sourcePath,
+ destPath,
+ job.offset > 0,
+ );
+
+ try {
+ await runFastSftpCopy(
+ laneHandles.sourceSftp,
+ laneHandles.srcHandle,
+ laneHandles.destSftp,
+ laneHandles.dstHandle,
+ job.length,
+ job.offset,
+ {
+ ...options,
+ segmentIndex: job.segmentIndex,
+ onProgress: reportDelta,
+ },
+ sourceReadClock,
+ destWriteClock,
+ );
+
+ fileLogger.info("Transfer segment completed", {
+ operation: "host_transfer_segment",
+ transferId,
+ segmentIndex: job.segmentIndex,
+ fileBaseOffset: job.offset,
+ byteLength: job.length,
+ parallelLane: workerId,
+ });
+
+ await closeTransferHandlesSafe(laneHandles);
+ await refreshDestProgress(true);
+ return;
+ } catch (err) {
+ await closeTransferHandlesSafe(laneHandles);
+
+ if (err instanceof TransferCancelledError) {
+ throw err;
+ }
+
+ const message =
+ err instanceof Error ? err.message : "Segment transfer failed";
+ const recoverable =
+ isRecoverableTransferError(err) &&
+ attempts < SFTP_PARALLEL_SEGMENT_MAX_ATTEMPTS;
+
+ fileLogger.error("Transfer segment failed", err, {
+ operation: "host_transfer_segment",
+ transferId,
+ segmentIndex: job.segmentIndex,
+ fileBaseOffset: job.offset,
+ byteLength: job.length,
+ attempt: attempts + 1,
+ maxAttempts: SFTP_PARALLEL_SEGMENT_MAX_ATTEMPTS,
+ recoverable,
+ parallelLane: workerId,
+ });
+
+ if (!recoverable) {
+ if (
+ transferId &&
+ (await finalizeStreamTransferIfDestAtSize(
+ transferId,
+ handles.destSftp,
+ destPath,
+ fileSize,
+ ))
+ ) {
+ return;
+ }
+ throw new Error(
+ `Segment ${job.segmentIndex} failed at offset ${job.offset}: ${message}`,
+ );
+ }
+
+ attempts += 1;
+ await resetParallelLane(workerId, attempts, message);
+ await refreshDestProgress(true);
+ }
+ }
+ };
+
+ const runWorker = async (workerId: number) => {
+ while (true) {
+ if (options.shouldAbort?.()) {
+ throw new TransferCancelledError();
+ }
+
+ const jobIndex = nextJobIndex;
+ nextJobIndex += 1;
+ if (jobIndex >= jobs.length) {
+ return;
+ }
+
+ await runSegmentJob(jobs[jobIndex], workerId);
+ }
+ };
+
+ try {
+ await Promise.all(
+ Array.from({ length: parallel }, (_, workerId) => runWorker(workerId)),
+ );
+ await refreshDestProgress(true);
+ } finally {
+ workerCaches.clear();
+ for (let i = 0; i < parallel; i++) {
+ reconnect.deps.closeDedicatedTransferSession(
+ `${reconnect.dedicatedSourceSessionId}:p${i}`,
+ );
+ reconnect.deps.closeDedicatedTransferSession(
+ `${reconnect.dedicatedDestSessionId}:p${i}`,
+ );
+ }
+ }
+
+ options.onResumeOffset?.(fileSize);
+ return handles;
+}
+
+function promisifyFastGet(
+ sftp: SFTPWrapper,
+ remotePath: string,
+ localPath: string,
+ opts: {
+ concurrency?: number;
+ chunkSize?: number;
+ fileSize?: number;
+ step?: (totalTransferred: number, chunk: number, total: number) => void;
+ },
+): Promise<void> {
+ return new Promise((resolve, reject) => {
+ sftp.fastGet(remotePath, localPath, opts, (err) => {
+ if (err) reject(err);
+ else resolve();
+ });
+ });
+}
+
+async function pipelinedSftpFile(
+ sourceSftp: SFTPWrapper,
+ destSftp: SFTPWrapper,
+ sourcePath: string,
+ destPath: string,
+ options: PipelinedXferOptions = {},
+): Promise<PipelinedXferStats> {
+ let fileSize = options.fileSize ?? 0;
+ const stats = createEmptyXferStats();
+ stats.destWriteKind = "sftp";
+
+ let handles: TransferFileHandles | null = null;
+ const transferId = options.transferId;
+
+ try {
+ if (!fileSize) {
+ const srcProbe = await promisifySftpOpen(
+ sourceSftp,
+ sourcePath,
+ SFTP_OPEN_READ,
+ 0o666,
+ );
+ try {
+ const fstats = await promisifySftpFstat(sourceSftp, srcProbe);
+ fileSize = fstats.size;
+ } finally {
+ await promisifySftpClose(sourceSftp, srcProbe).catch(() => {});
+ }
+ }
+ if (fileSize <= 0) return stats;
+
+ stats.bytes = fileSize;
+
+ const sourceReadClock = createHopWallClock();
+ const destWriteClock = createHopWallClock();
+
+ const runCopyWithRetry = async (): Promise<void> => {
+ let attempts = 0;
+ let sftpSource = sourceSftp;
+ let sftpDest = destSftp;
+ const parallelLanes = clampParallelSegmentCount(
+ options.parallelSegmentCount,
+ );
+ const isParallelCopy = parallelLanes > 1;
+ const maxCopyAttempts = isParallelCopy
+ ? SFTP_PARALLEL_COPY_MAX_ATTEMPTS
+ : SFTP_SEQUENTIAL_COPY_MAX_ATTEMPTS;
+
+ while (true) {
+ const resumeOffset = await probeDestResumeOffset(
+ sftpDest,
+ destPath,
+ fileSize,
+ );
+ if (resumeOffset >= fileSize) {
+ options.onResumeOffset?.(resumeOffset);
+ return;
+ }
+ if (resumeOffset > 0) {
+ options.onResumeOffset?.(resumeOffset);
+ if (attempts === 0) {
+ fileLogger.info("Resuming transfer from destination size", {
+ operation: "host_transfer_resume",
+ transferId,
+ resumeOffset,
+ fileSize,
+ });
+ }
+ }
+
+ try {
+ if (handles) {
+ await handles.close().catch(() => {});
+ }
+ handles = await openTransferFileHandles(
+ sftpSource,
+ sftpDest,
+ sourcePath,
+ destPath,
+ resumeOffset > 0,
+ );
+
+ if (fileSize <= SFTP_XFER_SEGMENT_THRESHOLD) {
+ await runFastSftpCopy(
+ handles.sourceSftp,
+ handles.srcHandle,
+ handles.destSftp,
+ handles.dstHandle,
+ fileSize - resumeOffset,
+ resumeOffset,
+ options,
+ sourceReadClock,
+ destWriteClock,
+ );
+ } else {
+ handles = await runFastSftpCopySegmented(
+ handles,
+ fileSize,
+ { ...options, initialOffset: resumeOffset },
+ sourceReadClock,
+ destWriteClock,
+ sourcePath,
+ destPath,
+ );
+ }
+ return;
+ } catch (err) {
+ if (err instanceof TransferCancelledError) {
+ throw err;
+ }
+
+ const recoverable =
+ options.reconnect &&
+ isRecoverableTransferError(err) &&
+ attempts < maxCopyAttempts;
+
+ fileLogger.error("Transfer copy attempt failed", err, {
+ operation: "host_transfer_copy",
+ transferId,
+ attempt: attempts + 1,
+ maxAttempts: maxCopyAttempts,
+ recoverable,
+ parallelLanes: isParallelCopy ? parallelLanes : undefined,
+ });
+
+ if (!recoverable || !options.reconnect) {
+ if (
+ transferId &&
+ (await finalizeStreamTransferIfDestAtSize(
+ transferId,
+ sftpDest,
+ destPath,
+ fileSize,
+ ))
+ ) {
+ return;
+ }
+ throw err;
+ }
+
+ attempts += 1;
+ await closeTransferHandlesSafe(handles);
+
+ if (isParallelCopy) {
+ closeAllTransferSessions(
+ options.reconnect.deps,
+ options.reconnect,
+ parallelLanes,
+ );
+ const delayMs =
+ TRANSFER_SESSION_RESET_DELAYS_MS[
+ Math.min(
+ attempts - 1,
+ TRANSFER_SESSION_RESET_DELAYS_MS.length - 1,
+ )
+ ] ?? 3000;
+ fileLogger.warn(
+ "Restarting parallel copy after segment exhaustion",
+ {
+ operation: "host_transfer_parallel_restart",
+ transferId,
+ attempt: attempts,
+ delayMs,
+ },
+ );
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+ } else {
+ const reset = await resetDedicatedTransferSessions(
+ options.reconnect,
+ attempts,
+ err instanceof Error ? err.message : "copy failed",
+ );
+ sftpSource = reset.sourceSftp;
+ sftpDest = reset.destSftp;
+ }
+ }
+ }
+ };
+
+ if (transferId) {
+ let abortFn: ((err: Error) => void) | null = null;
+ const control: ActiveXferControl = {
+ abort: (err) => abortFn?.(err),
+ closeResources: async () => {
+ await closeTransferHandlesSafe(handles);
+ },
+ };
+ activeXferControls.set(transferId, control);
+
+ try {
+ await new Promise<void>((resolve, reject) => {
+ abortFn = reject;
+ runCopyWithRetry().then(resolve).catch(reject);
+ });
+ } finally {
+ activeXferControls.delete(transferId);
+ }
+ } else {
+ await runCopyWithRetry();
+ }
+
+ stats.sourceReadSpanMs = hopSpanMs(sourceReadClock);
+ stats.destWriteSpanMs = hopSpanMs(destWriteClock);
+ } finally {
+ if (handles) {
+ await handles.close().catch(() => {});
+ }
+ }
+
+ return stats;
+}
+
+/** Source SFTP → local filesystem (skips SFTP write when dest SSH target is this host). */
+async function pipelinedSftpToLocalFile(
+ sourceSftp: SFTPWrapper,
+ sourcePath: string,
+ destPath: string,
+ options: PipelinedXferOptions = {},
+): Promise<PipelinedXferStats> {
+ let fileSize = options.fileSize ?? 0;
+ const stats = createEmptyXferStats();
+ stats.destWriteKind = "local";
+
+ if (!fileSize) {
+ const srcHandle = await promisifySftpOpen(
+ sourceSftp,
+ sourcePath,
+ SFTP_OPEN_READ,
+ 0o666,
+ );
+ try {
+ const fstats = await promisifySftpFstat(sourceSftp, srcHandle);
+ fileSize = fstats.size;
+ } finally {
+ await promisifySftpClose(sourceSftp, srcHandle).catch(() => {});
+ }
+ }
+ if (fileSize <= 0) return stats;
+
+ stats.bytes = fileSize;
+ const localPath = sftpPathToLocalPath(destPath);
+ const progress = createThrottledProgress(options.onProgress);
+ const transferStart = Date.now();
+
+ await promisifyFastGet(sourceSftp, sourcePath, localPath, {
+ concurrency: SFTP_XFER_CONCURRENCY,
+ chunkSize: SFTP_XFER_CHUNK_SIZE,
+ fileSize,
+ step: (_total, chunk) => {
+ if (options.shouldAbort?.()) {
+ throw new TransferCancelledError();
+ }
+ progress.add(chunk);
+ },
+ });
+
+ progress.flush();
+ stats.sourceReadSpanMs = elapsedMs(transferStart);
+ stats.destWriteSpanMs = stats.sourceReadSpanMs;
+ return stats;
+}
+
+async function transferFileData(
+ sourceSftp: SFTPWrapper,
+ destSftp: SFTPWrapper,
+ destSession: SSHSessionLike,
+ sourcePath: string,
+ destPath: string,
+ fileSize: number,
+ onProgress?: (bytes: number) => void,
+ shouldAbort?: () => boolean,
+ transferId?: string,
+ reconnect?: TransferReconnectContext,
+ onResumeOffset?: (offset: number) => void,
+ parallelSegmentCount?: number,
+): Promise<PipelinedXferStats> {
+ const pipeOptions: PipelinedXferOptions = {
+ fileSize,
+ onProgress,
+ shouldAbort,
+ transferId,
+ reconnect,
+ onResumeOffset,
+ parallelSegmentCount,
+ };
+
+ if (isLocalSshEndpoint(destSession.ip)) {
+ return pipelinedSftpToLocalFile(
+ sourceSftp,
+ sourcePath,
+ destPath,
+ pipeOptions,
+ );
+ }
+
+ return pipelinedSftpFile(
+ sourceSftp,
+ destSftp,
+ sourcePath,
+ destPath,
+ pipeOptions,
+ );
+}
+
+async function transferSingleFile(
+ deps: HostTransferDeps,
+ transferId: string,
+ sourceSession: SSHSessionLike,
+ destSession: SSHSessionLike,
+ sourcePath: string,
+ destPath: string,
+ move: boolean,
+ reconnectMeta: TransferReconnectMeta,
+): Promise<TransferProgress> {
+ const sourceSftp = await deps.getSessionSftp(sourceSession);
+ const destSftp = await deps.getSessionSftp(destSession);
+ const shouldAbort = createTransferShouldAbort(transferId);
+
+ const reconnect = buildTransferReconnectContext(
+ deps,
+ transferId,
+ reconnectMeta,
+ );
+
+ const stats = await promisifySftpStat(sourceSftp, sourcePath);
+ if (!stats.isFile()) {
+ throw new Error(`Source is not a regular file: ${sourcePath}`);
+ }
+
+ updateTransfer(transferId, {
+ method: "stream",
+ phase: "transferring",
+ totalBytes: stats.size,
+ });
+
+ let bytesTransferred = 0;
+ try {
+ const destStat = await promisifySftpStat(destSftp, destPath);
+ bytesTransferred = Math.min(destStat.size, stats.size);
+ } catch {
+ /* destination file does not exist yet */
+ }
+
+ updateTransfer(transferId, { bytesTransferred });
+ const prepareStart = Date.now();
+ await ensureDestParentForFile(deps, destSession, destPath);
+ const prepareDestMs = elapsedMs(prepareStart);
+ updateTransfer(transferId, { timings: { prepareDestMs } });
+
+ const syncProgress = (absoluteOffset: number) => {
+ bytesTransferred = absoluteOffset;
+ updateTransfer(transferId, { bytesTransferred: absoluteOffset });
+ };
+
+ const parallelLanes = clampParallelSegmentCount(
+ activeTransfers.get(transferId)?.parallelSegmentCount,
+ );
+ const useAbsoluteProgressOnly = parallelLanes > 1;
+
+ throwIfCancelled(transferId);
+ trackDestArtifact(transferId, destPath);
+ await transferFileData(
+ sourceSftp,
+ destSftp,
+ destSession,
+ sourcePath,
+ destPath,
+ stats.size,
+ useAbsoluteProgressOnly
+ ? undefined
+ : (n) => {
+ bytesTransferred += n;
+ updateTransfer(transferId, { bytesTransferred });
+ },
+ shouldAbort,
+ transferId,
+ reconnect,
+ syncProgress,
+ parallelLanes,
+ );
+
+ if (move) {
+ await deleteSourcePathsAfterSuccess(deps, transferId, sourceSession, [
+ sourcePath,
+ ]);
+ }
+
+ return finalizeTransfer(transferId, {
+ status: "success",
+ phase: "transferring",
+ method: "stream",
+ bytesTransferred: stats.size,
+ totalBytes: stats.size,
+ sourcePaths: [sourcePath],
+ destPath,
+ sourceDeleted: move,
+ moveRequested: move,
+ timings: buildStreamTransferTimings(transferId, stats.size, prepareDestMs),
+ });
+}
+
+async function cleanupDestItems(
+ deps: HostTransferDeps,
+ destSession: SSHSessionLike,
+ destDir: string,
+ basenames: string[],
+): Promise<void> {
+ const destSftp = await deps.getSessionSftp(destSession);
+ for (const name of basenames) {
+ const target = joinPath(destDir, name);
+ try {
+ await deletePathSftp(destSftp, target);
+ } catch {
+ /* best effort */
+ }
+ }
+}
+
+async function deleteSourcePaths(
+ deps: HostTransferDeps,
+ sourceSession: SSHSessionLike,
+ sourcePaths: string[],
+): Promise<void> {
+ const sourceSftp = await deps.getSessionSftp(sourceSession);
+ for (const path of sourcePaths) {
+ try {
+ await deletePathSftp(sourceSftp, path);
+ } catch {
+ /* best effort */
+ }
+ }
+}
+
+async function transferViaTar(
+ deps: HostTransferDeps,
+ transferId: string,
+ sourceSession: SSHSessionLike,
+ destSession: SSHSessionLike,
+ sourcePaths: string[],
+ destPath: string,
+ move: boolean,
+ reconnectMeta: TransferReconnectMeta,
+): Promise<TransferProgress> {
+ const sourceSftp = await deps.getSessionSftp(sourceSession);
+ const destSftp = await deps.getSessionSftp(destSession);
+ const reconnect = buildTransferReconnectContext(
+ deps,
+ transferId,
+ reconnectMeta,
+ );
+ const archiveId = randomUUID();
+ const tempArchive = `/tmp/termix-transfer-${archiveId}.tar.gz`;
+ updateTransfer(transferId, { tempArchivePath: tempArchive });
+ trackDestArtifact(transferId, tempArchive);
+ const workingDir = getWorkingDir(sourcePaths);
+ const basenames = sourcePaths.map((p) => basename(p));
+ const escapedNames = basenames.map((n) => `'${escapeShell(n)}'`).join(" ");
+ const escapedDir = escapeShell(workingDir);
+ const escapedArchive = escapeShell(tempArchive);
+ const escapedDest = escapeShell(destPath);
+
+ await ensureDestDirectory(deps, destSession, destPath);
+
+ updateTransfer(transferId, {
+ method: "tar",
+ phase: "compressing",
+ });
+
+ throwIfCancelled(transferId);
+ const compressStart = Date.now();
+ const compressCmd = `cd '${escapedDir}' && tar -czf '${escapedArchive}' ${escapedNames}`;
+ const compressResult = await execCommand(deps, sourceSession, compressCmd);
+ const compressMs = elapsedMs(compressStart);
+ updateTransfer(transferId, { timings: { compressMs } });
+ if (compressResult.code !== 0) {
+ throw new Error(
+ compressResult.stderr || "Failed to compress on source host",
+ );
+ }
+
+ throwIfCancelled(transferId);
+ let archiveSize = 0;
+ try {
+ const archiveStats = await promisifySftpStat(sourceSftp, tempArchive);
+ archiveSize = archiveStats.size;
+ } catch {
+ /* size unknown */
+ }
+
+ updateTransfer(transferId, {
+ phase: "transferring",
+ totalBytes: archiveSize,
+ bytesTransferred: 0,
+ });
+
+ let bytesTransferred = 0;
+ const transferStart = Date.now();
+ const xferStats = createEmptyXferStats();
+ const syncProgress = (absoluteOffset: number) => {
+ bytesTransferred = absoluteOffset;
+ updateTransfer(transferId, { bytesTransferred: absoluteOffset });
+ };
+ try {
+ const fileStats = await transferFileData(
+ sourceSftp,
+ destSftp,
+ destSession,
+ tempArchive,
+ tempArchive,
+ archiveSize,
+ (n) => {
+ bytesTransferred += n;
+ updateTransfer(transferId, { bytesTransferred });
+ },
+ () => cancelRequestedTransfers.has(transferId),
+ transferId,
+ reconnect,
+ syncProgress,
+ );
+ mergeXferStats(xferStats, fileStats);
+ } catch (err) {
+ if (!(err instanceof TransferCancelledError)) {
+ await cleanupDestItems(deps, destSession, destPath, basenames);
+ }
+ throw err;
+ } finally {
+ await promisifySftpUnlink(sourceSftp, tempArchive);
+ }
+ throwIfCancelled(transferId);
+ const transferMs = elapsedMs(transferStart);
+ const hopTimings = buildTransferHopTimings(xferStats, transferMs);
+ updateTransfer(transferId, {
+ timings: {
+ ...activeTransfers.get(transferId)?.timings,
+ transferMs,
+ ...hopTimings,
+ },
+ });
+
+ updateTransfer(transferId, { phase: "extracting" });
+
+ throwIfCancelled(transferId);
+ const extractStart = Date.now();
+ const extractCmd = `tar -xzf '${escapedArchive}' -C '${escapedDest}'`;
+ const extractResult = await execCommand(deps, destSession, extractCmd);
+ const extractMs = elapsedMs(extractStart);
+
+ await promisifySftpUnlink(destSftp, tempArchive);
+
+ if (extractResult.code !== 0) {
+ await cleanupDestItems(deps, destSession, destPath, basenames);
+ throw new Error(
+ extractResult.stderr || "Failed to extract on destination host",
+ );
+ }
+
+ if (move) {
+ await deleteSourcePathsAfterSuccess(
+ deps,
+ transferId,
+ sourceSession,
+ sourcePaths,
+ );
+ }
+
+ return finalizeTransfer(transferId, {
+ status: "success",
+ phase: "extracting",
+ method: "tar",
+ bytesTransferred,
+ totalBytes: archiveSize,
+ sourcePaths,
+ destPath,
+ sourceDeleted: move,
+ moveRequested: move,
+ timings: {
+ ...activeTransfers.get(transferId)?.timings,
+ extractMs,
+ ...hopTimings,
+ },
+ });
+}
+
+async function transferViaItemSftp(
+ deps: HostTransferDeps,
+ transferId: string,
+ sourceSession: SSHSessionLike,
+ destSession: SSHSessionLike,
+ sourcePaths: string[],
+ destPath: string,
+ move: boolean,
+ destPlatform: TransferPlatform,
+ reconnectMeta: TransferReconnectMeta,
+): Promise<TransferProgress> {
+ const sourceSftp = await deps.getSessionSftp(sourceSession);
+ const destSftp = await deps.getSessionSftp(destSession);
+ const reconnect = buildTransferReconnectContext(
+ deps,
+ transferId,
+ reconnectMeta,
+ );
+
+ const createdDirs = new Set<string>();
+ await ensureDirectoryTreeSftp(destSftp, destPath, createdDirs);
+
+ const allWork: FileWorkItem[] = [];
+ for (const sourcePath of sourcePaths) {
+ const items = await collectFileWorkItems(sourceSftp, sourcePath, destPath);
+ allWork.push(...items);
+ }
+
+ allWork.sort((a, b) => b.size - a.size);
+
+ const totalBytes = allWork.reduce((sum, item) => sum + item.size, 0);
+
+ updateTransfer(transferId, {
+ method: "item_sftp",
+ phase: "transferring",
+ totalItems: allWork.length,
+ itemsCompleted: 0,
+ totalBytes,
+ bytesTransferred: 0,
+ });
+
+ const failedPaths: string[] = [];
+ const createdFiles: string[] = [];
+ let itemsCompleted = 0;
+ let bytesTransferred = 0;
+ const transferStart = Date.now();
+ const xferStats = createEmptyXferStats();
+
+ for (const item of allWork) {
+ throwIfCancelled(transferId);
+ trackDestArtifact(transferId, item.destPath);
+ const bytesBeforeItem = bytesTransferred;
+ try {
+ const parentDir = dirname(item.destPath);
+ if (parentDir && !isRootOnlyPath(parentDir)) {
+ await ensureDirectoryTreeSftp(destSftp, parentDir, createdDirs);
+ }
+ const itemStats = await promisifySftpStat(sourceSftp, item.sourcePath);
+ const itemXferStats = await transferFileData(
+ sourceSftp,
+ destSftp,
+ destSession,
+ item.sourcePath,
+ item.destPath,
+ itemStats.size,
+ (n) => {
+ bytesTransferred += n;
+ updateTransfer(transferId, { bytesTransferred });
+ },
+ () => cancelRequestedTransfers.has(transferId),
+ transferId,
+ reconnect,
+ (absoluteOffset) => {
+ bytesTransferred = bytesBeforeItem + absoluteOffset;
+ updateTransfer(transferId, { bytesTransferred });
+ },
+ );
+ mergeXferStats(xferStats, itemXferStats);
+ if (destPlatform !== "windows") {
+ await promisifySftpChmod(destSftp, item.destPath, item.mode);
+ }
+ createdFiles.push(item.destPath);
+ itemsCompleted++;
+ updateTransfer(transferId, { itemsCompleted, bytesTransferred });
+ } catch (err) {
+ if (isPermissionError(err as Error)) {
+ failedPaths.push(item.sourcePath);
+ itemsCompleted++;
+ updateTransfer(transferId, { itemsCompleted, bytesTransferred });
+ continue;
+ }
+ if (!(err instanceof TransferCancelledError)) {
+ for (const created of [...createdFiles].reverse()) {
+ await deletePathSftp(destSftp, created).catch(() => {});
+ }
+ }
+ throw err;
+ }
+ }
+
+ const transferMs = elapsedMs(transferStart);
+ const hopTimings = buildTransferHopTimings(xferStats, transferMs);
+
+ const status: TransferStatus = failedPaths.length > 0 ? "partial" : "success";
+
+ // Move only after every file succeeded — never delete source on partial transfer
+ if (status === "success" && move) {
+ await deleteSourcePathsAfterSuccess(
+ deps,
+ transferId,
+ sourceSession,
+ sourcePaths,
+ );
+ }
+
+ return finalizeTransfer(transferId, {
+ status,
+ phase: "transferring",
+ method: "item_sftp",
+ itemsCompleted,
+ totalItems: allWork.length,
+ failedPaths: failedPaths.length > 0 ? failedPaths : undefined,
+ sourcePaths,
+ destPath,
+ sourceDeleted: status === "success" && move,
+ moveRequested: move,
+ timings: {
+ ...activeTransfers.get(transferId)?.timings,
+ transferMs,
+ ...hopTimings,
+ },
+ });
+}
+
+async function runTransfer(
+ deps: HostTransferDeps,
+ transferId: string,
+ request: TransferRequest,
+): Promise<void> {
+ const {
+ sourceSessionId: browseSourceSessionId,
+ sourcePaths,
+ destSessionId: browseDestSessionId,
+ destPath,
+ move = false,
+ userId,
+ methodPreference = "auto",
+ parallelSegmentCount:
+ requestParallelSegments = DEFAULT_PARALLEL_SEGMENT_COUNT,
+ } = request;
+
+ const parallelSegmentCount = clampParallelSegmentCount(
+ requestParallelSegments,
+ );
+
+ const dedicatedSourceSessionId = `xfer:${transferId}:src`;
+ const dedicatedDestSessionId = `xfer:${transferId}:dst`;
+ const runStart = Date.now();
+ const reconnectMeta: TransferReconnectMeta = {
+ userId,
+ browseSourceSessionId,
+ browseDestSessionId,
+ dedicatedSourceSessionId,
+ dedicatedDestSessionId,
+ };
+
+ try {
+ const sourceSession = await deps.openDedicatedTransferSession(
+ browseSourceSessionId,
+ dedicatedSourceSessionId,
+ userId,
+ transferId,
+ );
+ const destSession = await deps.openDedicatedTransferSession(
+ browseDestSessionId,
+ dedicatedDestSessionId,
+ userId,
+ transferId,
+ );
+
+ sourceSession.lastActive = Date.now();
+ destSession.lastActive = Date.now();
+
+ updateTransfer(transferId, {
+ parallelSegmentCount,
+ dedicatedSourceSessionId,
+ dedicatedDestSessionId,
+ });
+
+ const pathHints = [destPath, ...sourcePaths];
+ const sourcePlatform = await detectTransferPlatform(
+ deps,
+ sourceSession,
+ pathHints,
+ );
+ const destPlatform = await detectTransferPlatform(
+ deps,
+ destSession,
+ pathHints,
+ );
+
+ const sourceSftp = await deps.getSessionSftp(sourceSession);
+ const destSftp = await deps.getSessionSftp(destSession);
+
+ for (const path of sourcePaths) {
+ try {
+ await promisifySftpStat(sourceSftp, path);
+ } catch {
+ throw new Error(`Source not found: ${path}`);
+ }
+ }
+
+ if (browseSourceSessionId === browseDestSessionId) {
+ for (const src of sourcePaths) {
+ if (pathsOverlap(src, destPath)) {
+ throw new Error("Source and destination paths overlap");
+ }
+ }
+ }
+
+ let useArchive = sourcePaths.length > 1;
+
+ if (sourcePaths.length === 1) {
+ const stats = await promisifySftpStat(sourceSftp, sourcePaths[0]);
+ useArchive = stats.isDirectory();
+ }
+
+ if (!useArchive) {
+ await transferSingleFile(
+ deps,
+ transferId,
+ sourceSession,
+ destSession,
+ sourcePaths[0],
+ destPath,
+ move,
+ reconnectMeta,
+ );
+ } else {
+ const prepareStart = Date.now();
+ await ensureDestDirectory(deps, destSession, destPath);
+ updateTransfer(transferId, {
+ timings: { prepareDestMs: elapsedMs(prepareStart) },
+ });
+
+ const sourceHasTar =
+ sourcePlatform === "unix" &&
+ (await checkTarAvailable(deps, sourceSession));
+ const destHasTar =
+ destPlatform === "unix" && (await checkTarAvailable(deps, destSession));
+
+ throwIfCancelled(transferId);
+ const scanSummary = await scanSourcePathsForRouting(
+ sourceSftp,
+ sourcePaths,
+ transferId,
+ );
+ const archiveMethod = resolveArchiveTransferMethod(
+ methodPreference,
+ scanSummary,
+ sourcePlatform,
+ destPlatform,
+ sourceHasTar,
+ destHasTar,
+ );
+
+ fileLogger.info("Resolved archive transfer method", {
+ operation: "host_transfer",
+ transferId,
+ methodPreference,
+ archiveMethod,
+ fileCount: scanSummary.fileCount,
+ totalBytes: scanSummary.totalBytes,
+ incompressibleRatio: scanSummary.incompressibleRatio,
+ });
+
+ if (archiveMethod === "tar") {
+ await transferViaTar(
+ deps,
+ transferId,
+ sourceSession,
+ destSession,
+ sourcePaths,
+ destPath,
+ move,
+ reconnectMeta,
+ );
+ } else {
+ await transferViaItemSftp(
+ deps,
+ transferId,
+ sourceSession,
+ destSession,
+ sourcePaths,
+ destPath,
+ move,
+ destPlatform,
+ reconnectMeta,
+ );
+ }
+ }
+
+ fileLogger.success("Host transfer completed", {
+ operation: "host_transfer",
+ transferId,
+ browseSourceSessionId,
+ browseDestSessionId,
+ sourcePaths,
+ destPath,
+ move,
+ timings: {
+ ...activeTransfers.get(transferId)?.timings,
+ totalMs: elapsedMs(runStart),
+ },
+ });
+ updateTransfer(transferId, {
+ moveRequested: move,
+ timings: {
+ ...activeTransfers.get(transferId)?.timings,
+ totalMs: elapsedMs(runStart),
+ },
+ });
+ } catch (err) {
+ if (err instanceof TransferCancelledError) {
+ const current = activeTransfers.get(transferId);
+ finalizeTransfer(
+ transferId,
+ cancelledProgressPatch(current, {
+ status: "cancelled",
+ phase: current?.phase ?? "transferring",
+ message: "Transfer cancelled by user",
+ method: current?.method,
+ sourcePaths,
+ destPath,
+ bytesTransferred: current?.bytesTransferred,
+ totalBytes: current?.totalBytes,
+ itemsCompleted: current?.itemsCompleted,
+ totalItems: current?.totalItems,
+ moveRequested: move,
+ sourceDeleted: false,
+ timings: {
+ ...current?.timings,
+ totalMs: elapsedMs(runStart),
+ },
+ }),
+ );
+ fileLogger.info("Host transfer cancelled", {
+ operation: "host_transfer",
+ transferId,
+ sourcePaths,
+ destPath,
+ });
+ return;
+ }
+
+ const current = activeTransfers.get(transferId);
+ const message = err instanceof Error ? err.message : "Transfer failed";
+
+ if (
+ sourcePaths.length === 1 &&
+ current?.method === "stream" &&
+ current.destPath &&
+ current.totalBytes
+ ) {
+ try {
+ const destSession = await deps.openDedicatedTransferSession(
+ browseDestSessionId,
+ dedicatedDestSessionId,
+ userId,
+ transferId,
+ { allowBrowseDisconnected: true },
+ );
+ const finalized = await tryFinalizeStreamTransferIfDestComplete(
+ deps,
+ transferId,
+ destSession,
+ current.destPath,
+ current.totalBytes,
+ {
+ sourcePaths,
+ moveRequested: move,
+ sourceDeleted: current.sourceDeleted,
+ },
+ );
+ if (finalized) {
+ fileLogger.info("Host transfer succeeded after destination verify", {
+ operation: "host_transfer",
+ transferId,
+ sourcePaths,
+ destPath,
+ });
+ return;
+ }
+ } catch {
+ /* fall through to error */
+ }
+ }
+
+ finalizeTransfer(
+ transferId,
+ failedProgressPatch(current, {
+ status: "error",
+ phase: current?.phase ?? "transferring",
+ message,
+ method: current?.method,
+ sourcePaths,
+ destPath,
+ bytesTransferred: current?.bytesTransferred,
+ totalBytes: current?.totalBytes,
+ itemsCompleted: current?.itemsCompleted,
+ totalItems: current?.totalItems,
+ moveRequested: move,
+ timings: {
+ ...current?.timings,
+ totalMs: elapsedMs(runStart),
+ },
+ }),
+ );
+ fileLogger.error(
+ err instanceof TransferStalledError
+ ? "Host transfer stalled"
+ : "Host transfer failed",
+ err,
+ {
+ operation: "host_transfer",
+ transferId,
+ sourcePaths,
+ destPath,
+ },
+ );
+ } finally {
+ deps.closeDedicatedTransferSession(dedicatedSourceSessionId);
+ deps.closeDedicatedTransferSession(dedicatedDestSessionId);
+ }
+}
+
+export function getTransferStatus(
+ transferId: string,
+ userId: string,
+): TransferProgress | null {
+ checkHungTransfers();
+ const progress = activeTransfers.get(transferId);
+ if (!progress || progress.userId !== userId) return null;
+ return progress;
+}
+
+export function listActiveTransfers(userId: string): TransferProgress[] {
+ return Array.from(activeTransfers.values()).filter(
+ (progress) => progress.userId === userId && progress.status === "running",
+ );
+}
+
+export async function cleanupCancelledTransfer(
+ deps: HostTransferDeps,
+ transferId: string,
+ userId: string,
+): Promise<{ removedPaths: string[]; failedPaths: string[] }> {
+ const progress = activeTransfers.get(transferId);
+ if (!progress || progress.userId !== userId) {
+ throw new Error("Transfer not found");
+ }
+ if (progress.status !== "cancelled") {
+ throw new Error("Transfer is not cancelled");
+ }
+ if (progress.cleanupCompleted) {
+ return { removedPaths: [], failedPaths: [] };
+ }
+ if (!progress.destSessionId) {
+ throw new Error("Transfer has no destination session");
+ }
+
+ const pathsToRemove = buildCleanupPaths(progress);
+ if (pathsToRemove.length === 0) {
+ updateTransfer(transferId, { cleanupCompleted: true });
+ return { removedPaths: [], failedPaths: [] };
+ }
+
+ const cleanupSessionId = `xfer:cleanup:${transferId}:dst`;
+ const removedPaths: string[] = [];
+ const failedPaths: string[] = [];
+
+ try {
+ const destSession = await deps.openDedicatedTransferSession(
+ progress.destSessionId,
+ cleanupSessionId,
+ userId,
+ transferId,
+ { allowBrowseDisconnected: true },
+ );
+ const destSftp = await deps.getSessionSftp(destSession);
+
+ for (const path of pathsToRemove) {
+ try {
+ await deletePathSftp(destSftp, path);
+ removedPaths.push(path);
+ } catch {
+ failedPaths.push(path);
+ }
+ }
+ } finally {
+ deps.closeDedicatedTransferSession(cleanupSessionId);
+ }
+
+ updateTransfer(transferId, { cleanupCompleted: true });
+ return { removedPaths, failedPaths };
+}
+
+export function retryHostTransfer(
+ deps: HostTransferDeps,
+ transferId: string,
+ userId: string,
+): boolean {
+ const progress = activeTransfers.get(transferId);
+ if (
+ !progress ||
+ progress.userId !== userId ||
+ progress.status !== "error" ||
+ !progress.retryable ||
+ !progress.requestSnapshot
+ ) {
+ return false;
+ }
+
+ void (async () => {
+ if (
+ progress.method === "stream" &&
+ progress.destPath &&
+ progress.totalBytes &&
+ progress.destSessionId
+ ) {
+ const destId =
+ progress.dedicatedDestSessionId ?? `xfer:${transferId}:dst`;
+ try {
+ const destSession = await deps.openDedicatedTransferSession(
+ progress.destSessionId,
+ destId,
+ userId,
+ transferId,
+ { allowBrowseDisconnected: true },
+ );
+ const done = await tryFinalizeStreamTransferIfDestComplete(
+ deps,
+ transferId,
+ destSession,
+ progress.destPath,
+ progress.totalBytes,
+ {
+ sourcePaths: progress.sourcePaths,
+ moveRequested: progress.moveRequested,
+ },
+ );
+ if (done) {
+ return;
+ }
+ } catch {
+ /* destination not ready — restart transfer below */
+ }
+ }
+
+ const latest = activeTransfers.get(transferId);
+ if (!latest || latest.status !== "error" || !latest.requestSnapshot) {
+ return;
+ }
+
+ updateTransfer(transferId, {
+ status: "running",
+ phase: "transferring",
+ message: undefined,
+ retryable: false,
+ parallelSegmentCount:
+ latest.requestSnapshot?.parallelSegmentCount ??
+ latest.parallelSegmentCount,
+ });
+
+ await runTransfer(deps, transferId, {
+ ...latest.requestSnapshot,
+ userId,
+ parallelSegmentCount:
+ latest.requestSnapshot?.parallelSegmentCount ??
+ latest.parallelSegmentCount ??
+ DEFAULT_PARALLEL_SEGMENT_COUNT,
+ });
+ })();
+
+ return true;
+}
+
+export async function previewArchiveTransferMethod(
+ deps: HostTransferDeps,
+ request: {
+ sourceSessionId: string;
+ destSessionId: string;
+ sourcePaths: string[];
+ destPath: string;
+ methodPreference?: TransferMethodPreference;
+ userId: string;
+ },
+): Promise<TransferMethodPreview> {
+ const {
+ sourceSessionId,
+ destSessionId,
+ sourcePaths,
+ destPath,
+ methodPreference = "auto",
+ userId,
+ } = request;
+
+ const sourceSession = deps.sshSessions[sourceSessionId];
+ const destSession = deps.sshSessions[destSessionId];
+
+ if (!sourceSession?.isConnected || !destSession?.isConnected) {
+ throw new Error("SSH session not connected");
+ }
+
+ if (
+ !deps.verifySessionOwnership(sourceSession, userId) ||
+ !deps.verifySessionOwnership(destSession, userId)
+ ) {
+ throw new Error("Session access denied");
+ }
+
+ const pathHints = [destPath, ...sourcePaths];
+ const sourcePlatform = await detectTransferPlatform(
+ deps,
+ sourceSession,
+ pathHints,
+ );
+ const destPlatform = await detectTransferPlatform(
+ deps,
+ destSession,
+ pathHints,
+ );
+
+ const sourceSftp = await deps.getSessionSftp(sourceSession);
+ const scanItems: Array<{ sourcePath: string; size: number }> = [];
+ for (const sourcePath of sourcePaths) {
+ const work = await collectFileWorkItems(sourceSftp, sourcePath, "/");
+ scanItems.push(
+ ...work.map((w) => ({ sourcePath: w.sourcePath, size: w.size })),
+ );
+ }
+ const scanSummary = buildTransferScanSummary(scanItems);
+
+ const sourceHasTar =
+ sourcePlatform === "unix" && (await checkTarAvailable(deps, sourceSession));
+ const destHasTar =
+ destPlatform === "unix" && (await checkTarAvailable(deps, destSession));
+
+ const resolvedMethod = resolveArchiveTransferMethod(
+ methodPreference,
+ scanSummary,
+ sourcePlatform,
+ destPlatform,
+ sourceHasTar,
+ destHasTar,
+ );
+
+ const reasonKey = getArchiveTransferReasonKey(
+ methodPreference,
+ resolvedMethod,
+ scanSummary,
+ sourcePlatform,
+ destPlatform,
+ sourceHasTar,
+ destHasTar,
+ );
+
+ return {
+ methodPreference,
+ resolvedMethod,
+ reasonKey,
+ sourcePlatform,
+ destPlatform,
+ sourceHasTar,
+ destHasTar,
+ summary: scanSummary,
+ };
+}
+
+export function startHostTransfer(
+ deps: HostTransferDeps,
+ request: TransferRequest,
+): { transferId: string; syncResult?: TransferProgress } {
+ const transferId = randomUUID();
+
+ activeTransfers.set(transferId, {
+ transferId,
+ status: "running",
+ phase: "transferring",
+ sourcePaths: request.sourcePaths,
+ destPath: request.destPath,
+ userId: request.userId,
+ sourceSessionId: request.sourceSessionId,
+ destSessionId: request.destSessionId,
+ startedAt: Date.now(),
+ moveRequested: request.move ?? false,
+ methodPreference: request.methodPreference ?? "auto",
+ parallelSegmentCount: clampParallelSegmentCount(
+ request.parallelSegmentCount,
+ ),
+ requestSnapshot: {
+ sourceSessionId: request.sourceSessionId,
+ sourcePaths: request.sourcePaths,
+ destSessionId: request.destSessionId,
+ destPath: request.destPath,
+ move: request.move,
+ methodPreference: request.methodPreference,
+ parallelSegmentCount: clampParallelSegmentCount(
+ request.parallelSegmentCount,
+ ),
+ },
+ });
+
+ const isSingleSmallFile = request.sourcePaths.length === 1 && !request.move;
+
+ if (isSingleSmallFile) {
+ const sourceSession = deps.sshSessions[request.sourceSessionId];
+ if (sourceSession?.sftp || sourceSession?.isConnected) {
+ void (async () => {
+ try {
+ const sftp = await deps.getSessionSftp(sourceSession);
+ const stats = await promisifySftpStat(sftp, request.sourcePaths[0]);
+ if (stats.isFile() && stats.size <= SMALL_FILE_SYNC_THRESHOLD) {
+ await runTransfer(deps, transferId, request);
+ return;
+ }
+ } catch {
+ /* fall through to async */
+ }
+ void runTransfer(deps, transferId, request);
+ })();
+ return { transferId };
+ }
+ }
+
+ void runTransfer(deps, transferId, request);
+ return { transferId };
+}
+
+export function cleanupOldTransfers(maxAgeMs = 60 * 60 * 1000): void {
+ const now = Date.now();
+ for (const [id, progress] of activeTransfers.entries()) {
+ if (
+ progress.status !== "running" &&
+ now - (progress as TransferProgress & { _ts?: number })._ts! > maxAgeMs
+ ) {
+ activeTransfers.delete(id);
+ }
+ }
+}
diff --git a/src/backend/ssh/jump-host-chain.ts b/src/backend/ssh/jump-host-chain.ts
new file mode 100644
index 000000000..c2fd46fcf
--- /dev/null
+++ b/src/backend/ssh/jump-host-chain.ts
@@ -0,0 +1,325 @@
+import { and, eq } from "drizzle-orm";
+import { Client as SSHClient } from "ssh2";
+import { getDb } from "../database/db/index.js";
+import { hosts, sshCredentials } from "../database/db/schema.js";
+import { fileLogger } from "../utils/logger.js";
+import {
+ createSocks5Connection,
+ type SOCKS5Config,
+} from "../utils/socks5-helper.js";
+import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
+import { SimpleDBOps } from "../utils/simple-db-ops.js";
+import { SSHHostKeyVerifier } from "./host-key-verifier.js";
+
+type JumpHostConfig = {
+ id: number;
+ ip: string;
+ port: number;
+ username: string;
+ password?: string;
+ key?: string;
+ keyPassword?: string;
+ keyType?: string;
+ authType?: string;
+ credentialId?: number;
+ [key: string]: unknown;
+};
+
+async function resolveJumpHost(
+ hostId: number,
+ userId: string,
+): Promise<JumpHostConfig | null> {
+ try {
+ const hostResults = await SimpleDBOps.select(
+ getDb().select().from(hosts).where(eq(hosts.id, hostId)),
+ "ssh_data",
+ userId,
+ );
+
+ if (hostResults.length === 0) {
+ return null;
+ }
+
+ const host = hostResults[0];
+ const ownerId = (host.userId || userId) as string;
+
+ if (host.credentialId) {
+ if (userId !== ownerId) {
+ try {
+ const { SharedCredentialManager } =
+ await import("../utils/shared-credential-manager.js");
+ const sharedCredManager = SharedCredentialManager.getInstance();
+ const sharedCred = await sharedCredManager.getSharedCredentialForUser(
+ hostId,
+ userId,
+ );
+ if (sharedCred) {
+ return {
+ ...host,
+ password: sharedCred.password,
+ key: sharedCred.key,
+ keyPassword: sharedCred.keyPassword,
+ keyType: sharedCred.keyType,
+ authType: sharedCred.key
+ ? "key"
+ : sharedCred.password
+ ? "password"
+ : "none",
+ } as JumpHostConfig;
+ }
+ } catch {
+ // fall through to owner credential lookup
+ }
+ }
+
+ const credentials = await SimpleDBOps.select(
+ getDb()
+ .select()
+ .from(sshCredentials)
+ .where(
+ and(
+ eq(sshCredentials.id, host.credentialId as number),
+ eq(sshCredentials.userId, ownerId),
+ ),
+ ),
+ "ssh_credentials",
+ ownerId,
+ );
+
+ if (credentials.length > 0) {
+ const credential = credentials[0];
+ return {
+ ...host,
+ password: credential.password as string | undefined,
+ key: (credential.key || credential.privateKey) as string | undefined,
+ keyPassword: credential.keyPassword as string | undefined,
+ keyType: credential.keyType as string | undefined,
+ authType: credential.authType as string | undefined,
+ } as JumpHostConfig;
+ }
+ }
+
+ return host as JumpHostConfig;
+ } catch (error) {
+ fileLogger.error("Failed to resolve jump host", error, {
+ operation: "resolve_jump_host",
+ hostId,
+ userId,
+ });
+ return null;
+ }
+}
+
+export async function createJumpHostChain(
+ jumpHosts: Array<{ hostId: number }>,
+ userId: string,
+ socks5Config?: SOCKS5Config | null,
+): Promise<SSHClient | null> {
+ if (!jumpHosts || jumpHosts.length === 0) {
+ return null;
+ }
+
+ let currentClient: SSHClient | null = null;
+ const clients: SSHClient[] = [];
+
+ try {
+ const jumpHostConfigs: Array<Awaited<ReturnType<typeof resolveJumpHost>>> =
+ [];
+ for (let i = 0; i < jumpHosts.length; i++) {
+ const config = await resolveJumpHost(jumpHosts[i].hostId, userId);
+ jumpHostConfigs.push(config);
+ }
+
+ const totalHops = jumpHostConfigs.length;
+
+ for (let i = 0; i < jumpHostConfigs.length; i++) {
+ if (!jumpHostConfigs[i]) {
+ fileLogger.error(`Jump host ${i + 1} not found`, undefined, {
+ operation: "jump_host_chain",
+ hostId: jumpHosts[i].hostId,
+ hopIndex: i,
+ totalHops,
+ });
+ clients.forEach((c) => c.end());
+ return null;
+ }
+ }
+
+ let proxySocket: import("net").Socket | null = null;
+ if (socks5Config?.useSocks5) {
+ const firstHop = jumpHostConfigs[0]!;
+ proxySocket = await createSocks5Connection(
+ firstHop.ip,
+ firstHop.port || 22,
+ socks5Config,
+ );
+ }
+
+ for (let i = 0; i < jumpHostConfigs.length; i++) {
+ const jumpHostConfig = jumpHostConfigs[i]!;
+
+ const jumpClient = new SSHClient();
+ clients.push(jumpClient);
+
+ const jumpHostVerifier = await SSHHostKeyVerifier.createHostVerifier(
+ jumpHostConfig.id,
+ jumpHostConfig.ip,
+ jumpHostConfig.port || 22,
+ null,
+ userId,
+ true,
+ );
+
+ const connected = await new Promise<boolean>((resolve) => {
+ const timeout = setTimeout(() => {
+ resolve(false);
+ }, 30000);
+
+ jumpClient.on("ready", () => {
+ clearTimeout(timeout);
+ resolve(true);
+ });
+
+ jumpClient.on("error", (err) => {
+ clearTimeout(timeout);
+ fileLogger.error(
+ `Jump host ${i + 1}/${totalHops} connection failed`,
+ err,
+ {
+ operation: "jump_host_connect",
+ hostId: jumpHostConfig.id,
+ ip: jumpHostConfig.ip,
+ hopIndex: i,
+ totalHops,
+ previousHop:
+ i > 0
+ ? jumpHostConfigs[i - 1]?.ip
+ : proxySocket
+ ? "proxy"
+ : "direct",
+ usedProxySocket: i === 0 && !!proxySocket,
+ },
+ );
+ resolve(false);
+ });
+
+ const connectConfig: Record<string, unknown> = {
+ host: jumpHostConfig.ip?.replace(/^\[|\]$/g, "") || jumpHostConfig.ip,
+ port: jumpHostConfig.port || 22,
+ username: jumpHostConfig.username,
+ tryKeyboard: jumpHostConfig.authType !== "none",
+ readyTimeout: 60000,
+ hostVerifier: jumpHostVerifier,
+ algorithms: {
+ kex: [
+ "curve25519-sha256",
+ "ecdh-sha2-nistp521",
+ "ecdh-sha2-nistp384",
+ "ecdh-sha2-nistp256",
+ "diffie-hellman-group-exchange-sha256",
+ "diffie-hellman-group18-sha512",
+ "diffie-hellman-group17-sha512",
+ "diffie-hellman-group16-sha512",
+ "diffie-hellman-group15-sha512",
+ "diffie-hellman-group14-sha256",
+ "diffie-hellman-group14-sha1",
+ "diffie-hellman-group-exchange-sha1",
+ "diffie-hellman-group1-sha1",
+ ],
+ serverHostKey: [
+ "ssh-ed25519",
+ "ecdsa-sha2-nistp521",
+ "ecdsa-sha2-nistp384",
+ "ecdsa-sha2-nistp256",
+ "rsa-sha2-512",
+ "rsa-sha2-256",
+ "ssh-rsa",
+ "ssh-dss",
+ ],
+ cipher: SSH_ALGORITHMS.cipher,
+ hmac: [
+ "hmac-sha2-512",
+ "hmac-sha2-256",
+ "hmac-sha1",
+ "hmac-md5",
+ ],
+ compress: ["none", "[email protected]", "zlib"],
+ },
+ };
+
+ if (jumpHostConfig.authType === "password" && jumpHostConfig.password) {
+ connectConfig.password = jumpHostConfig.password;
+ } else if (jumpHostConfig.authType === "key" && jumpHostConfig.key) {
+ const cleanKey = jumpHostConfig.key
+ .trim()
+ .replace(/\r\n/g, "\n")
+ .replace(/\r/g, "\n");
+ connectConfig.privateKey = Buffer.from(cleanKey, "utf8");
+ if (jumpHostConfig.keyPassword) {
+ connectConfig.passphrase = jumpHostConfig.keyPassword;
+ }
+ }
+
+ jumpClient.on(
+ "keyboard-interactive",
+ (
+ _name: string,
+ _instructions: string,
+ _lang: string,
+ prompts: Array<{ prompt: string; echo: boolean }>,
+ finish: (responses: string[]) => void,
+ ) => {
+ const responses = prompts.map((p) => {
+ if (/password/i.test(p.prompt) && jumpHostConfig.password) {
+ return jumpHostConfig.password as string;
+ }
+ return "";
+ });
+ finish(responses);
+ },
+ );
+
+ if (currentClient) {
+ currentClient.forwardOut(
+ "127.0.0.1",
+ 0,
+ jumpHostConfig.ip,
+ jumpHostConfig.port || 22,
+ (err, stream) => {
+ if (err) {
+ clearTimeout(timeout);
+ resolve(false);
+ return;
+ }
+ connectConfig.sock = stream;
+ jumpClient.connect(connectConfig);
+ },
+ );
+ } else if (proxySocket) {
+ connectConfig.sock = proxySocket;
+ jumpClient.connect(connectConfig);
+ } else {
+ jumpClient.connect(connectConfig);
+ }
+ });
+
+ if (!connected) {
+ clients.forEach((c) => c.end());
+ return null;
+ }
+
+ currentClient = jumpClient;
+ }
+
+ return currentClient;
+ } catch (error) {
+ fileLogger.error("Failed to create jump host chain", error, {
+ operation: "jump_host_chain",
+ });
+ clients.forEach((c) => c.end());
+ return null;
+ }
+}
diff --git a/src/backend/ssh/opkssh-auth.ts b/src/backend/ssh/opkssh-auth.ts
index 5b00239a4..03a0c3c45 100644
--- a/src/backend/ssh/opkssh-auth.ts
+++ b/src/backend/ssh/opkssh-auth.ts
@@ -968,7 +968,8 @@ export async function getUserIdFromRequest(req: {
}
const decoded = await authManager.verifyJWTToken(token);
- return decoded?.userId || null;
+ if (!decoded?.userId || decoded.pendingTOTP) return null;
+ return decoded.userId;
} catch {
return null;
}
diff --git a/src/backend/ssh/server-stats-helpers.test.ts b/src/backend/ssh/server-stats-helpers.test.ts
new file mode 100644
index 000000000..c59c4612e
--- /dev/null
+++ b/src/backend/ssh/server-stats-helpers.test.ts
@@ -0,0 +1,67 @@
+import { describe, it, expect } from "vitest";
+import {
+ supportsMetrics,
+ isTcpPingEnabled,
+ createConnectionLog,
+} from "./server-stats-helpers.js";
+
+describe("supportsMetrics", () => {
+ it("supports plain ssh hosts", () => {
+ expect(
+ supportsMetrics({ connectionType: "ssh", authType: "password" }),
+ ).toBe(true);
+ });
+
+ it("defaults missing connectionType to ssh", () => {
+ expect(supportsMetrics({ authType: "key" })).toBe(true);
+ });
+
+ it("rejects non-ssh connection types", () => {
+ expect(supportsMetrics({ connectionType: "rdp" })).toBe(false);
+ expect(supportsMetrics({ connectionType: "vnc" })).toBe(false);
+ });
+
+ it("rejects ssh hosts that cannot run shell commands", () => {
+ expect(supportsMetrics({ connectionType: "ssh", authType: "none" })).toBe(
+ false,
+ );
+ expect(supportsMetrics({ connectionType: "ssh", authType: "opkssh" })).toBe(
+ false,
+ );
+ });
+});
+
+describe("isTcpPingEnabled", () => {
+ it("is enabled when status checks are on and tcp ping is not disabled", () => {
+ expect(
+ isTcpPingEnabled({ statusCheckEnabled: true, disableTcpPing: false }),
+ ).toBe(true);
+ expect(isTcpPingEnabled({ statusCheckEnabled: true })).toBe(true);
+ });
+
+ it("is disabled when status checks are off", () => {
+ expect(isTcpPingEnabled({ statusCheckEnabled: false })).toBe(false);
+ });
+
+ it("is disabled when tcp ping is explicitly disabled", () => {
+ expect(
+ isTcpPingEnabled({ statusCheckEnabled: true, disableTcpPing: true }),
+ ).toBe(false);
+ });
+});
+
+describe("createConnectionLog", () => {
+ it("builds a log entry without id/timestamp", () => {
+ const entry = createConnectionLog("info", "connection", "Connecting", {
+ hostId: 1,
+ });
+ expect(entry).toEqual({
+ type: "info",
+ stage: "connection",
+ message: "Connecting",
+ details: { hostId: 1 },
+ });
+ expect("id" in entry).toBe(false);
+ expect("timestamp" in entry).toBe(false);
+ });
+});
diff --git a/src/backend/ssh/server-stats-helpers.ts b/src/backend/ssh/server-stats-helpers.ts
new file mode 100644
index 000000000..e9977413f
--- /dev/null
+++ b/src/backend/ssh/server-stats-helpers.ts
@@ -0,0 +1,36 @@
+import type { LogEntry, ConnectionStage } from "../../types/connection-log.js";
+
+export type StatsCapableHost = {
+ connectionType?: string;
+ authType?: string;
+};
+
+export type TcpPingStatsConfig = {
+ statusCheckEnabled: boolean;
+ disableTcpPing?: boolean;
+};
+
+export function supportsMetrics(host: StatsCapableHost): boolean {
+ const connectionType = host.connectionType || "ssh";
+ if (connectionType !== "ssh") return false;
+ if (host.authType === "none" || host.authType === "opkssh") return false;
+ return true;
+}
+
+export function isTcpPingEnabled(statsConfig: TcpPingStatsConfig): boolean {
+ return statsConfig.statusCheckEnabled && !statsConfig.disableTcpPing;
+}
+
+export function createConnectionLog(
+ type: "info" | "success" | "warning" | "error",
+ stage: ConnectionStage,
+ message: string,
+ details?: Record<string, unknown>,
+): Omit<LogEntry, "id" | "timestamp"> {
+ return {
+ type,
+ stage,
+ message,
+ details,
+ };
+}
diff --git a/src/backend/ssh/server-stats-jump-hosts.ts b/src/backend/ssh/server-stats-jump-hosts.ts
new file mode 100644
index 000000000..cfc88f6b0
--- /dev/null
+++ b/src/backend/ssh/server-stats-jump-hosts.ts
@@ -0,0 +1,325 @@
+import { Client } from "ssh2";
+import { and, eq } from "drizzle-orm";
+import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
+import { statsLogger } from "../utils/logger.js";
+import { SimpleDBOps } from "../utils/simple-db-ops.js";
+import {
+ createSocks5Connection,
+ type SOCKS5Config,
+} from "../utils/socks5-helper.js";
+import { getDb } from "../database/db/index.js";
+import { hosts, sshCredentials } from "../database/db/schema.js";
+import { SSHHostKeyVerifier } from "./host-key-verifier.js";
+
+interface JumpHostConfig {
+ id: number;
+ ip: string;
+ port: number;
+ username: string;
+ password?: string;
+ key?: string;
+ keyPassword?: string;
+ keyType?: string;
+ authType?: string;
+ credentialId?: number;
+ [key: string]: unknown;
+}
+
+async function resolveJumpHost(
+ hostId: number,
+ userId: string,
+): Promise<JumpHostConfig | null> {
+ try {
+ const hostResults = await SimpleDBOps.select(
+ getDb().select().from(hosts).where(eq(hosts.id, hostId)),
+ "ssh_data",
+ userId,
+ );
+
+ if (hostResults.length === 0) {
+ return null;
+ }
+
+ const host = hostResults[0];
+ const ownerId = (host.userId || userId) as string;
+
+ if (host.credentialId) {
+ if (userId !== ownerId) {
+ try {
+ const { SharedCredentialManager } =
+ await import("../utils/shared-credential-manager.js");
+ const sharedCredManager = SharedCredentialManager.getInstance();
+ const sharedCred = await sharedCredManager.getSharedCredentialForUser(
+ hostId,
+ userId,
+ );
+ if (sharedCred) {
+ return {
+ ...host,
+ password: sharedCred.password,
+ key: sharedCred.key,
+ keyPassword: sharedCred.keyPassword,
+ keyType: sharedCred.keyType,
+ authType: sharedCred.key
+ ? "key"
+ : sharedCred.password
+ ? "password"
+ : "none",
+ } as JumpHostConfig;
+ }
+ } catch {
+ // fall through to owner credential lookup
+ }
+ }
+
+ const credentials = await SimpleDBOps.select(
+ getDb()
+ .select()
+ .from(sshCredentials)
+ .where(
+ and(
+ eq(sshCredentials.id, host.credentialId as number),
+ eq(sshCredentials.userId, ownerId),
+ ),
+ ),
+ "ssh_credentials",
+ ownerId,
+ );
+
+ if (credentials.length > 0) {
+ const credential = credentials[0];
+ return {
+ ...host,
+ password: credential.password as string | undefined,
+ key: (credential.key || credential.privateKey) as string | undefined,
+ keyPassword: credential.keyPassword as string | undefined,
+ keyType: credential.keyType as string | undefined,
+ authType: credential.authType as string | undefined,
+ } as JumpHostConfig;
+ }
+ }
+
+ return host as JumpHostConfig;
+ } catch (error) {
+ statsLogger.error("Failed to resolve jump host", error, {
+ operation: "resolve_jump_host",
+ hostId,
+ userId,
+ });
+ return null;
+ }
+}
+
+export async function createJumpHostChain(
+ jumpHosts: Array<{ hostId: number }>,
+ userId: string,
+ socks5Config?: SOCKS5Config | null,
+): Promise<Client | null> {
+ if (!jumpHosts || jumpHosts.length === 0) {
+ return null;
+ }
+
+ let currentClient: Client | null = null;
+ const clients: Client[] = [];
+
+ try {
+ const jumpHostConfigs: Array<Awaited<ReturnType<typeof resolveJumpHost>>> =
+ [];
+ for (let i = 0; i < jumpHosts.length; i++) {
+ const config = await resolveJumpHost(jumpHosts[i].hostId, userId);
+ jumpHostConfigs.push(config);
+ }
+
+ const totalHops = jumpHostConfigs.length;
+
+ for (let i = 0; i < jumpHostConfigs.length; i++) {
+ if (!jumpHostConfigs[i]) {
+ statsLogger.error(`Jump host ${i + 1} not found`, undefined, {
+ operation: "jump_host_chain",
+ hostId: jumpHosts[i].hostId,
+ hopIndex: i,
+ totalHops,
+ });
+ clients.forEach((c) => c.end());
+ return null;
+ }
+ }
+
+ let proxySocket: import("net").Socket | null = null;
+ if (socks5Config?.useSocks5) {
+ const firstHop = jumpHostConfigs[0]!;
+ proxySocket = await createSocks5Connection(
+ firstHop.ip,
+ firstHop.port || 22,
+ socks5Config,
+ );
+ }
+
+ for (let i = 0; i < jumpHostConfigs.length; i++) {
+ const jumpHostConfig = jumpHostConfigs[i]!;
+
+ const jumpClient = new Client();
+ clients.push(jumpClient);
+
+ const jumpHostVerifier = await SSHHostKeyVerifier.createHostVerifier(
+ jumpHostConfig.id,
+ jumpHostConfig.ip,
+ jumpHostConfig.port || 22,
+ null,
+ userId,
+ true,
+ );
+
+ const connected = await new Promise<boolean>((resolve) => {
+ const timeout = setTimeout(() => {
+ resolve(false);
+ }, 30000);
+
+ jumpClient.on("ready", () => {
+ clearTimeout(timeout);
+ resolve(true);
+ });
+
+ jumpClient.on("error", (err) => {
+ clearTimeout(timeout);
+ statsLogger.error(
+ `Jump host ${i + 1}/${totalHops} connection failed`,
+ err,
+ {
+ operation: "jump_host_connect",
+ hostId: jumpHostConfig.id,
+ ip: jumpHostConfig.ip,
+ hopIndex: i,
+ totalHops,
+ previousHop:
+ i > 0
+ ? jumpHostConfigs[i - 1]?.ip
+ : proxySocket
+ ? "proxy"
+ : "direct",
+ usedProxySocket: i === 0 && !!proxySocket,
+ },
+ );
+ resolve(false);
+ });
+
+ const connectConfig: Record<string, unknown> = {
+ host: jumpHostConfig.ip?.replace(/^\[|\]$/g, "") || jumpHostConfig.ip,
+ port: jumpHostConfig.port || 22,
+ username: jumpHostConfig.username,
+ tryKeyboard: jumpHostConfig.authType !== "none",
+ readyTimeout: 60000,
+ hostVerifier: jumpHostVerifier,
+ algorithms: {
+ kex: [
+ "curve25519-sha256",
+ "ecdh-sha2-nistp521",
+ "ecdh-sha2-nistp384",
+ "ecdh-sha2-nistp256",
+ "diffie-hellman-group-exchange-sha256",
+ "diffie-hellman-group18-sha512",
+ "diffie-hellman-group17-sha512",
+ "diffie-hellman-group16-sha512",
+ "diffie-hellman-group15-sha512",
+ "diffie-hellman-group14-sha256",
+ "diffie-hellman-group14-sha1",
+ "diffie-hellman-group-exchange-sha1",
+ "diffie-hellman-group1-sha1",
+ ],
+ serverHostKey: [
+ "ssh-ed25519",
+ "ecdsa-sha2-nistp521",
+ "ecdsa-sha2-nistp384",
+ "ecdsa-sha2-nistp256",
+ "rsa-sha2-512",
+ "rsa-sha2-256",
+ "ssh-rsa",
+ "ssh-dss",
+ ],
+ cipher: SSH_ALGORITHMS.cipher,
+ hmac: [
+ "hmac-sha2-512",
+ "hmac-sha2-256",
+ "hmac-sha1",
+ "hmac-md5",
+ ],
+ compress: ["none", "[email protected]", "zlib"],
+ },
+ };
+
+ if (jumpHostConfig.authType === "password" && jumpHostConfig.password) {
+ connectConfig.password = jumpHostConfig.password;
+ } else if (jumpHostConfig.authType === "key" && jumpHostConfig.key) {
+ const cleanKey = jumpHostConfig.key
+ .trim()
+ .replace(/\r\n/g, "\n")
+ .replace(/\r/g, "\n");
+ connectConfig.privateKey = Buffer.from(cleanKey, "utf8");
+ if (jumpHostConfig.keyPassword) {
+ connectConfig.passphrase = jumpHostConfig.keyPassword;
+ }
+ }
+
+ jumpClient.on(
+ "keyboard-interactive",
+ (
+ _name: string,
+ _instructions: string,
+ _lang: string,
+ prompts: Array<{ prompt: string; echo: boolean }>,
+ finish: (responses: string[]) => void,
+ ) => {
+ const responses = prompts.map((p) => {
+ if (/password/i.test(p.prompt) && jumpHostConfig.password) {
+ return jumpHostConfig.password as string;
+ }
+ return "";
+ });
+ finish(responses);
+ },
+ );
+
+ if (currentClient) {
+ currentClient.forwardOut(
+ "127.0.0.1",
+ 0,
+ jumpHostConfig.ip,
+ jumpHostConfig.port || 22,
+ (err, stream) => {
+ if (err) {
+ clearTimeout(timeout);
+ resolve(false);
+ return;
+ }
+ connectConfig.sock = stream;
+ jumpClient.connect(connectConfig);
+ },
+ );
+ } else if (proxySocket) {
+ connectConfig.sock = proxySocket;
+ jumpClient.connect(connectConfig);
+ } else {
+ jumpClient.connect(connectConfig);
+ }
+ });
+
+ if (!connected) {
+ clients.forEach((c) => c.end());
+ return null;
+ }
+
+ currentClient = jumpClient;
+ }
+
+ return currentClient;
+ } catch (error) {
+ statsLogger.error("Failed to create jump host chain", error, {
+ operation: "jump_host_chain",
+ });
+ clients.forEach((c) => c.end());
+ return null;
+ }
+}
diff --git a/src/backend/ssh/server-stats-sessions.ts b/src/backend/ssh/server-stats-sessions.ts
new file mode 100644
index 000000000..fb9aa71f2
--- /dev/null
+++ b/src/backend/ssh/server-stats-sessions.ts
@@ -0,0 +1,80 @@
+import type { Client, ConnectConfig } from "ssh2";
+import { statsLogger } from "../utils/logger.js";
+
+export interface MetricsSession {
+ client: Client;
+ isConnected: boolean;
+ lastActive: number;
+ timeout?: NodeJS.Timeout;
+ activeOperations: number;
+ hostId: number;
+ userId: string;
+}
+
+export interface PendingTOTPSession {
+ client: Client;
+ finish: (responses: string[]) => void;
+ config: ConnectConfig;
+ createdAt: number;
+ sessionId: string;
+ hostId: number;
+ userId: string;
+ prompts?: Array<{ prompt: string; echo: boolean }>;
+ totpPromptIndex?: number;
+ resolvedPassword?: string;
+ totpAttempts: number;
+}
+
+export interface MetricsViewer {
+ sessionId: string;
+ userId: string;
+ hostId: number;
+ lastHeartbeat: number;
+}
+
+export const metricsSessions: Record<string, MetricsSession> = {};
+export const pendingTOTPSessions: Record<string, PendingTOTPSession> = {};
+
+export function cleanupMetricsSession(sessionId: string): void {
+ const session = metricsSessions[sessionId];
+ if (session) {
+ if (session.activeOperations > 0) {
+ statsLogger.warn(
+ `Deferring metrics session cleanup - ${session.activeOperations} active operations`,
+ {
+ operation: "cleanup_deferred",
+ sessionId,
+ activeOperations: session.activeOperations,
+ },
+ );
+ scheduleMetricsSessionCleanup(sessionId);
+ return;
+ }
+
+ try {
+ session.client.end();
+ } catch {
+ // expected
+ }
+ clearTimeout(session.timeout);
+ delete metricsSessions[sessionId];
+ }
+}
+
+export function scheduleMetricsSessionCleanup(sessionId: string): void {
+ const session = metricsSessions[sessionId];
+ if (session) {
+ if (session.timeout) clearTimeout(session.timeout);
+
+ session.timeout = setTimeout(
+ () => {
+ cleanupMetricsSession(sessionId);
+ },
+ 30 * 60 * 1000,
+ );
+ }
+}
+
+export function getSessionKey(hostId: number, userId: string): string {
+ return `${userId}:${hostId}`;
+}
diff --git a/src/backend/ssh/server-stats-settings-routes.ts b/src/backend/ssh/server-stats-settings-routes.ts
new file mode 100644
index 000000000..a7a4e5ae1
--- /dev/null
+++ b/src/backend/ssh/server-stats-settings-routes.ts
@@ -0,0 +1,189 @@
+import type { Express, RequestHandler } from "express";
+import { getDb } from "../database/db/index.js";
+import { statsLogger } from "../utils/logger.js";
+
+type ServerStatsSettingsConfig = {
+ statusCheckInterval: number;
+ metricsInterval: number;
+};
+
+type ServerStatsSettingsRoutesDeps = {
+ requireAdmin: RequestHandler;
+ defaultStatsConfig: ServerStatsSettingsConfig;
+ refreshAllPolling: () => Promise<void>;
+};
+
+export function registerServerStatsSettingsRoutes(
+ app: Express,
+ {
+ requireAdmin,
+ defaultStatsConfig: DEFAULT_STATS_CONFIG,
+ refreshAllPolling,
+ }: ServerStatsSettingsRoutesDeps,
+): void {
+ /**
+ * @openapi
+ * /global-settings:
+ * get:
+ * summary: Get global monitoring defaults
+ * tags:
+ * - Stats
+ * responses:
+ * 200:
+ * description: Global monitoring settings.
+ * 403:
+ * description: Requires admin privileges.
+ */
+ app.get("/global-settings", requireAdmin, async (_req, res) => {
+ try {
+ const db = getDb();
+
+ try {
+ db.$client.prepare("SELECT 1 FROM settings LIMIT 1").get();
+ } catch (tableError) {
+ statsLogger.warn("Settings table does not exist, using defaults", {
+ operation: "global_settings_table_check",
+ error:
+ tableError instanceof Error
+ ? tableError.message
+ : String(tableError),
+ });
+ return res.json({
+ statusCheckInterval: DEFAULT_STATS_CONFIG.statusCheckInterval,
+ metricsInterval: DEFAULT_STATS_CONFIG.metricsInterval,
+ });
+ }
+
+ const statusRow = db.$client
+ .prepare(
+ "SELECT value FROM settings WHERE key = 'global_status_check_interval'",
+ )
+ .get() as { value: string } | undefined;
+ const metricsRow = db.$client
+ .prepare(
+ "SELECT value FROM settings WHERE key = 'global_metrics_interval'",
+ )
+ .get() as { value: string } | undefined;
+
+ res.json({
+ statusCheckInterval: statusRow
+ ? parseInt(statusRow.value, 10)
+ : DEFAULT_STATS_CONFIG.statusCheckInterval,
+ metricsInterval: metricsRow
+ ? parseInt(metricsRow.value, 10)
+ : DEFAULT_STATS_CONFIG.metricsInterval,
+ });
+ } catch (error) {
+ statsLogger.error("Failed to fetch global settings", {
+ operation: "global_settings_fetch_error",
+ error: error instanceof Error ? error.message : String(error),
+ });
+ res.status(500).json({ error: "Failed to fetch global settings" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /global-settings:
+ * post:
+ * summary: Update global monitoring defaults
+ * tags:
+ * - Stats
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * statusCheckInterval:
+ * type: integer
+ * metricsInterval:
+ * type: integer
+ * responses:
+ * 200:
+ * description: Settings saved.
+ * 400:
+ * description: Invalid parameters.
+ * 403:
+ * description: Requires admin privileges.
+ */
+ app.post("/global-settings", requireAdmin, async (req, res) => {
+ const { statusCheckInterval, metricsInterval } = req.body;
+
+ if (
+ statusCheckInterval !== undefined &&
+ (typeof statusCheckInterval !== "number" ||
+ statusCheckInterval < 5 ||
+ statusCheckInterval > 3600)
+ ) {
+ return res.status(400).json({
+ error: "statusCheckInterval must be between 5 and 3600 seconds",
+ });
+ }
+ if (
+ metricsInterval !== undefined &&
+ (typeof metricsInterval !== "number" ||
+ metricsInterval < 5 ||
+ metricsInterval > 3600)
+ ) {
+ return res
+ .status(400)
+ .json({ error: "metricsInterval must be between 5 and 3600 seconds" });
+ }
+
+ try {
+ const db = getDb();
+
+ try {
+ db.$client.prepare("SELECT 1 FROM settings LIMIT 1").get();
+ } catch (tableError) {
+ statsLogger.error(
+ "Settings table does not exist, cannot save settings",
+ {
+ operation: "global_settings_table_check",
+ error:
+ tableError instanceof Error
+ ? tableError.message
+ : String(tableError),
+ },
+ );
+ return res.status(500).json({
+ error:
+ "Database settings table is missing. Please check database initialization.",
+ });
+ }
+
+ if (statusCheckInterval !== undefined) {
+ db.$client
+ .prepare(
+ "INSERT OR REPLACE INTO settings (key, value) VALUES ('global_status_check_interval', ?)",
+ )
+ .run(String(statusCheckInterval));
+ }
+ if (metricsInterval !== undefined) {
+ db.$client
+ .prepare(
+ "INSERT OR REPLACE INTO settings (key, value) VALUES ('global_metrics_interval', ?)",
+ )
+ .run(String(metricsInterval));
+ }
+
+ await refreshAllPolling();
+
+ res.json({
+ success: true,
+ message: "Settings updated and polling refreshed",
+ });
+ } catch (error) {
+ statsLogger.error("Failed to save global settings", {
+ operation: "global_settings_save_error",
+ error: error instanceof Error ? error.message : String(error),
+ });
+ res.status(500).json({
+ error: "Failed to save global settings",
+ details: error instanceof Error ? error.message : String(error),
+ });
+ }
+ });
+}
diff --git a/src/backend/ssh/server-stats-state.ts b/src/backend/ssh/server-stats-state.ts
new file mode 100644
index 000000000..f1140bd38
--- /dev/null
+++ b/src/backend/ssh/server-stats-state.ts
@@ -0,0 +1,256 @@
+class RequestQueue {
+ private queues = new Map<number, Array<() => Promise<unknown>>>();
+ private processing = new Set<number>();
+ private requestTimeout = 60000;
+
+ async queueRequest<T>(hostId: number, request: () => Promise<T>): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const wrappedRequest = async () => {
+ try {
+ const result = await Promise.race<T>([
+ request(),
+ new Promise<never>((_, rej) =>
+ setTimeout(
+ () =>
+ rej(
+ new Error(
+ `Request timeout after ${this.requestTimeout}ms for host ${hostId}`,
+ ),
+ ),
+ this.requestTimeout,
+ ),
+ ),
+ ]);
+ resolve(result);
+ } catch (error) {
+ reject(error);
+ }
+ };
+
+ const queue = this.queues.get(hostId) || [];
+ queue.push(wrappedRequest);
+ this.queues.set(hostId, queue);
+ this.processQueue(hostId);
+ });
+ }
+
+ private async processQueue(hostId: number): Promise<void> {
+ if (this.processing.has(hostId)) return;
+
+ this.processing.add(hostId);
+ const queue = this.queues.get(hostId) || [];
+
+ while (queue.length > 0) {
+ const request = queue.shift();
+ if (request) {
+ try {
+ await request();
+ } catch {
+ // expected
+ }
+ }
+ }
+
+ this.processing.delete(hostId);
+ const currentQueue = this.queues.get(hostId);
+ if (currentQueue && currentQueue.length > 0) {
+ this.processQueue(hostId);
+ }
+ }
+}
+
+interface CachedMetrics {
+ data: unknown;
+ timestamp: number;
+ hostId: number;
+}
+
+class MetricsCache {
+ private cache = new Map<number, CachedMetrics>();
+ private ttl = 30000;
+
+ get(hostId: number): unknown | null {
+ const cached = this.cache.get(hostId);
+ if (cached && Date.now() - cached.timestamp < this.ttl) {
+ return cached.data;
+ }
+ return null;
+ }
+
+ set(hostId: number, data: unknown): void {
+ this.cache.set(hostId, {
+ data,
+ timestamp: Date.now(),
+ hostId,
+ });
+ }
+
+ clear(hostId?: number): void {
+ if (hostId) {
+ this.cache.delete(hostId);
+ } else {
+ this.cache.clear();
+ }
+ }
+}
+
+interface AuthFailureRecord {
+ count: number;
+ lastFailure: number;
+ reason: "TOTP" | "AUTH" | "TIMEOUT";
+ permanent: boolean;
+}
+
+class AuthFailureTracker {
+ private failures = new Map<number, AuthFailureRecord>();
+ private maxRetries = 3;
+ private backoffBase = 5000;
+
+ recordFailure(
+ hostId: number,
+ reason: "TOTP" | "AUTH" | "TIMEOUT",
+ permanent = false,
+ ): void {
+ const existing = this.failures.get(hostId);
+ if (existing) {
+ existing.count++;
+ existing.lastFailure = Date.now();
+ existing.reason = reason;
+ if (permanent) existing.permanent = true;
+ } else {
+ this.failures.set(hostId, {
+ count: 1,
+ lastFailure: Date.now(),
+ reason,
+ permanent,
+ });
+ }
+ }
+
+ shouldSkip(hostId: number): boolean {
+ const record = this.failures.get(hostId);
+ if (!record) return false;
+
+ if (record.reason === "TOTP" || record.permanent) {
+ return true;
+ }
+
+ if (record.count >= this.maxRetries) {
+ return true;
+ }
+
+ const backoffTime = this.backoffBase * Math.pow(2, record.count - 1);
+ const timeSinceFailure = Date.now() - record.lastFailure;
+
+ return timeSinceFailure < backoffTime;
+ }
+
+ getSkipReason(hostId: number): string | null {
+ const record = this.failures.get(hostId);
+ if (!record) return null;
+
+ if (record.reason === "TOTP") {
+ return "TOTP authentication required (metrics unavailable)";
+ }
+
+ if (record.permanent) {
+ return "Authentication permanently failed";
+ }
+
+ if (record.count >= this.maxRetries) {
+ return `Too many authentication failures (${record.count} attempts)`;
+ }
+
+ const backoffTime = this.backoffBase * Math.pow(2, record.count - 1);
+ const timeSinceFailure = Date.now() - record.lastFailure;
+ const remainingTime = Math.ceil((backoffTime - timeSinceFailure) / 1000);
+
+ if (timeSinceFailure < backoffTime) {
+ return `Retry in ${remainingTime}s (attempt ${record.count}/${this.maxRetries})`;
+ }
+
+ return null;
+ }
+
+ reset(hostId: number): void {
+ this.failures.delete(hostId);
+ }
+
+ cleanup(): void {
+ const maxAge = 60 * 60 * 1000;
+ const now = Date.now();
+
+ for (const [hostId, record] of this.failures.entries()) {
+ if (!record.permanent && now - record.lastFailure > maxAge) {
+ this.failures.delete(hostId);
+ }
+ }
+ }
+}
+
+class PollingBackoff {
+ private failures = new Map<number, { count: number; nextRetry: number }>();
+ private baseDelay = 30000;
+ private maxDelay = 600000;
+ private maxRetries = 5;
+
+ recordFailure(hostId: number): void {
+ const existing = this.failures.get(hostId) || { count: 0, nextRetry: 0 };
+ const delay = Math.min(
+ this.baseDelay * Math.pow(2, existing.count),
+ this.maxDelay,
+ );
+ this.failures.set(hostId, {
+ count: existing.count + 1,
+ nextRetry: Date.now() + delay,
+ });
+ }
+
+ shouldSkip(hostId: number): boolean {
+ const backoff = this.failures.get(hostId);
+ if (!backoff) return false;
+
+ if (backoff.count >= this.maxRetries) {
+ return true;
+ }
+
+ return Date.now() < backoff.nextRetry;
+ }
+
+ getBackoffInfo(hostId: number): string | null {
+ const backoff = this.failures.get(hostId);
+ if (!backoff) return null;
+
+ if (backoff.count >= this.maxRetries) {
+ return `Max retries exceeded (${backoff.count} failures) - polling suspended`;
+ }
+
+ const remainingMs = backoff.nextRetry - Date.now();
+ if (remainingMs > 0) {
+ const remainingSec = Math.ceil(remainingMs / 1000);
+ return `Retry in ${remainingSec}s (attempt ${backoff.count}/${this.maxRetries})`;
+ }
+
+ return null;
+ }
+
+ reset(hostId: number): void {
+ this.failures.delete(hostId);
+ }
+
+ cleanup(): void {
+ const maxAge = 60 * 60 * 1000;
+ const now = Date.now();
+
+ for (const [hostId, backoff] of this.failures.entries()) {
+ if (backoff.count < this.maxRetries && now - backoff.nextRetry > maxAge) {
+ this.failures.delete(hostId);
+ }
+ }
+ }
+}
+
+export const requestQueue = new RequestQueue();
+export const metricsCache = new MetricsCache();
+export const authFailureTracker = new AuthFailureTracker();
+export const pollingBackoff = new PollingBackoff();
diff --git a/src/backend/ssh/server-stats-viewer-routes.ts b/src/backend/ssh/server-stats-viewer-routes.ts
new file mode 100644
index 000000000..7e5a36dce
--- /dev/null
+++ b/src/backend/ssh/server-stats-viewer-routes.ts
@@ -0,0 +1,290 @@
+import type { Express } from "express";
+import type { AuthenticatedRequest } from "../../types/index.js";
+import { statsLogger } from "../utils/logger.js";
+import { SimpleDBOps } from "../utils/simple-db-ops.js";
+
+type ViewerStatsConfig = {
+ metricsEnabled: boolean;
+};
+
+type ServerStatsViewerRoutesDeps<
+ THost extends { statsConfig?: string | TStatsConfig },
+ TStatsConfig extends ViewerStatsConfig,
+> = {
+ fetchHostById: (hostId: number, userId: string) => Promise<THost>;
+ supportsMetrics: (host: THost) => boolean;
+ parseStatsConfig: (statsConfig: THost["statsConfig"]) => TStatsConfig;
+ updateHeartbeat: (viewerSessionId: string) => boolean;
+ registerViewer: (
+ hostId: number,
+ viewerSessionId: string,
+ userId: string,
+ ) => void;
+ unregisterViewer: (hostId: number, viewerSessionId: string) => void;
+};
+
+export function registerServerStatsViewerRoutes<
+ THost extends { statsConfig?: string | TStatsConfig },
+ TStatsConfig extends ViewerStatsConfig,
+>(
+ app: Express,
+ {
+ fetchHostById,
+ supportsMetrics,
+ parseStatsConfig,
+ updateHeartbeat,
+ registerViewer,
+ unregisterViewer,
+ }: ServerStatsViewerRoutesDeps<THost, TStatsConfig>,
+): void {
+ /**
+ * @openapi
+ * /metrics/heartbeat:
+ * post:
+ * summary: Update viewer heartbeat
+ * description: Updates the heartbeat timestamp for a metrics viewer session to keep it alive.
+ * tags:
+ * - Server Stats
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * viewerSessionId:
+ * type: string
+ * responses:
+ * 200:
+ * description: Heartbeat updated successfully.
+ * 400:
+ * description: Invalid viewerSessionId.
+ * 401:
+ * description: Session expired - please log in again.
+ * 404:
+ * description: Viewer session not found.
+ * 500:
+ * description: Failed to update heartbeat.
+ */
+ app.post("/metrics/heartbeat", async (req, res) => {
+ const { viewerSessionId } = req.body;
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!SimpleDBOps.isUserDataUnlocked(userId)) {
+ return res.status(401).json({
+ error: "Session expired - please log in again",
+ code: "SESSION_EXPIRED",
+ });
+ }
+
+ if (!viewerSessionId || typeof viewerSessionId !== "string") {
+ return res.status(400).json({ error: "Invalid viewerSessionId" });
+ }
+
+ try {
+ const success = updateHeartbeat(viewerSessionId);
+ if (success) {
+ res.json({ success: true });
+ } else {
+ res.status(404).json({ error: "Viewer session not found" });
+ }
+ } catch (error) {
+ statsLogger.error("Failed to update heartbeat", {
+ operation: "heartbeat_error",
+ viewerSessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ res.status(500).json({ error: "Failed to update heartbeat" });
+ }
+ });
+
+ /**
+ * @openapi
+ * /metrics/register-viewer:
+ * post:
+ * summary: Register metrics viewer
+ * description: Registers a new viewer session for a host to track who is viewing metrics.
+ * tags:
+ * - Server Stats
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hostId:
+ * type: integer
+ * responses:
+ * 200:
+ * description: Viewer registered successfully.
+ * 400:
+ * description: Invalid hostId.
+ * 401:
+ * description: Session expired - please log in again.
+ * 500:
+ * description: Failed to register viewer.
+ */
+ app.post("/metrics/register-viewer", async (req, res) => {
+ const { hostId } = req.body;
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!SimpleDBOps.isUserDataUnlocked(userId)) {
+ return res.status(401).json({
+ error: "Session expired - please log in again",
+ code: "SESSION_EXPIRED",
+ });
+ }
+
+ if (!hostId || typeof hostId !== "number") {
+ return res.status(400).json({ error: "Invalid hostId" });
+ }
+
+ try {
+ // Graceful no-op if host is inaccessible, metrics disabled, or host type
+ // does not support metrics. The client may call this speculatively, so
+ // avoid returning 5xx for expected "no metrics available" scenarios.
+ let host: THost | undefined;
+ try {
+ host = await fetchHostById(hostId, userId);
+ } catch (lookupErr) {
+ statsLogger.warn(
+ "register-viewer host lookup failed (treating as no-op)",
+ {
+ operation: "register_viewer_lookup",
+ hostId,
+ userId,
+ error:
+ lookupErr instanceof Error
+ ? lookupErr.message
+ : String(lookupErr),
+ },
+ );
+ }
+
+ if (!host) {
+ return res.json({
+ success: true,
+ skipped: true,
+ reason: "host_not_found",
+ });
+ }
+
+ if (!supportsMetrics(host)) {
+ return res.json({
+ success: true,
+ skipped: true,
+ reason: "metrics_unsupported",
+ });
+ }
+
+ const statsConfig = parseStatsConfig(host.statsConfig);
+ if (!statsConfig.metricsEnabled) {
+ return res.json({
+ success: true,
+ skipped: true,
+ reason: "metrics_disabled",
+ });
+ }
+
+ const viewerSessionId = `viewer-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
+ try {
+ registerViewer(hostId, viewerSessionId, userId);
+ } catch (regErr) {
+ statsLogger.warn(
+ "pollingManager.registerViewer threw (treating as no-op)",
+ {
+ operation: "register_viewer_internal",
+ hostId,
+ userId,
+ error: regErr instanceof Error ? regErr.message : String(regErr),
+ },
+ );
+ return res.json({
+ success: true,
+ skipped: true,
+ reason: "register_failed_noop",
+ });
+ }
+
+ res.json({ success: true, viewerSessionId });
+ } catch (error) {
+ statsLogger.error("Failed to register viewer", {
+ operation: "register_viewer_error",
+ hostId,
+ userId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ // Even on unexpected errors we prefer a graceful client experience: the
+ // viewer-registration is purely an optimization and should never break
+ // the UI. Report success:false but HTTP 200 so the client can decide.
+ res.status(200).json({
+ success: false,
+ skipped: true,
+ reason: "internal_error",
+ });
+ }
+ });
+
+ /**
+ * @openapi
+ * /metrics/unregister-viewer:
+ * post:
+ * summary: Unregister metrics viewer
+ * description: Unregisters a viewer session when they stop viewing metrics for a host.
+ * tags:
+ * - Server Stats
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * properties:
+ * hostId:
+ * type: integer
+ * viewerSessionId:
+ * type: string
+ * responses:
+ * 200:
+ * description: Viewer unregistered successfully.
+ * 400:
+ * description: Invalid hostId or viewerSessionId.
+ * 401:
+ * description: Session expired - please log in again.
+ * 500:
+ * description: Failed to unregister viewer.
+ */
+ app.post("/metrics/unregister-viewer", async (req, res) => {
+ const { hostId, viewerSessionId } = req.body;
+ const userId = (req as AuthenticatedRequest).userId;
+
+ if (!SimpleDBOps.isUserDataUnlocked(userId)) {
+ return res.status(401).json({
+ error: "Session expired - please log in again",
+ code: "SESSION_EXPIRED",
+ });
+ }
+
+ if (!hostId || typeof hostId !== "number") {
+ return res.status(400).json({ error: "Invalid hostId" });
+ }
+
+ if (!viewerSessionId || typeof viewerSessionId !== "string") {
+ return res.status(400).json({ error: "Invalid viewerSessionId" });
+ }
+
+ try {
+ unregisterViewer(hostId, viewerSessionId);
+ res.json({ success: true });
+ } catch (error) {
+ statsLogger.error("Failed to unregister viewer", {
+ operation: "unregister_viewer_error",
+ hostId,
+ viewerSessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ res.status(500).json({ error: "Failed to unregister viewer" });
+ }
+ });
+}
diff --git a/src/backend/ssh/server-stats.ts b/src/backend/ssh/server-stats.ts
index 81fe337ef..b821ce8ac 100644
--- a/src/backend/ssh/server-stats.ts
+++ b/src/backend/ssh/server-stats.ts
@@ -6,7 +6,7 @@ import { Client, type ConnectConfig } from "ssh2";
import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
import { getDb } from "../database/db/index.js";
import { hosts, sshCredentials } from "../database/db/schema.js";
-import { eq, and } from "drizzle-orm";
+import { eq } from "drizzle-orm";
import { statsLogger } from "../utils/logger.js";
import { SimpleDBOps } from "../utils/simple-db-ops.js";
import { AuthManager } from "../utils/auth-manager.js";
@@ -29,679 +29,29 @@ import {
} from "../utils/socks5-helper.js";
import { SSHHostKeyVerifier } from "./host-key-verifier.js";
import { connectionPool, withConnection } from "./ssh-connection-pool.js";
+import { registerServerStatsSettingsRoutes } from "./server-stats-settings-routes.js";
+import { registerServerStatsViewerRoutes } from "./server-stats-viewer-routes.js";
+import { createJumpHostChain } from "./server-stats-jump-hosts.js";
+import {
+ createConnectionLog,
+ isTcpPingEnabled,
+ supportsMetrics,
+} from "./server-stats-helpers.js";
+import {
+ cleanupMetricsSession,
+ getSessionKey,
+ metricsSessions,
+ pendingTOTPSessions,
+ scheduleMetricsSessionCleanup,
+ type MetricsViewer,
+} from "./server-stats-sessions.js";
+import {
+ authFailureTracker,
+ metricsCache,
+ pollingBackoff,
+ requestQueue,
+} from "./server-stats-state.js";
-function supportsMetrics(host: SSHHostWithCredentials): boolean {
- const connectionType = host.connectionType || "ssh";
- if (connectionType !== "ssh") return false;
- if (host.authType === "none" || host.authType === "opkssh") return false;
- return true;
-}
-
-function isTcpPingEnabled(statsConfig: StatsConfig): boolean {
- return statsConfig.statusCheckEnabled && !statsConfig.disableTcpPing;
-}
-
-function createConnectionLog(
- type: "info" | "success" | "warning" | "error",
- stage: ConnectionStage,
- message: string,
- details?: Record<string, unknown>,
-): Omit<LogEntry, "id" | "timestamp"> {
- return {
- type,
- stage,
- message,
- details,
- };
-}
-
-interface JumpHostConfig {
- id: number;
- ip: string;
- port: number;
- username: string;
- password?: string;
- key?: string;
- keyPassword?: string;
- keyType?: string;
- authType?: string;
- credentialId?: number;
- [key: string]: unknown;
-}
-
-async function resolveJumpHost(
- hostId: number,
- userId: string,
-): Promise<JumpHostConfig | null> {
- try {
- const hostResults = await SimpleDBOps.select(
- getDb().select().from(hosts).where(eq(hosts.id, hostId)),
- "ssh_data",
- userId,
- );
-
- if (hostResults.length === 0) {
- return null;
- }
-
- const host = hostResults[0];
- const ownerId = (host.userId || userId) as string;
-
- if (host.credentialId) {
- if (userId !== ownerId) {
- try {
- const { SharedCredentialManager } =
- await import("../utils/shared-credential-manager.js");
- const sharedCredManager = SharedCredentialManager.getInstance();
- const sharedCred = await sharedCredManager.getSharedCredentialForUser(
- hostId,
- userId,
- );
- if (sharedCred) {
- return {
- ...host,
- password: sharedCred.password,
- key: sharedCred.key,
- keyPassword: sharedCred.keyPassword,
- keyType: sharedCred.keyType,
- authType: sharedCred.key
- ? "key"
- : sharedCred.password
- ? "password"
- : "none",
- } as JumpHostConfig;
- }
- } catch {
- // fall through to owner credential lookup
- }
- }
-
- const credentials = await SimpleDBOps.select(
- getDb()
- .select()
- .from(sshCredentials)
- .where(
- and(
- eq(sshCredentials.id, host.credentialId as number),
- eq(sshCredentials.userId, ownerId),
- ),
- ),
- "ssh_credentials",
- ownerId,
- );
-
- if (credentials.length > 0) {
- const credential = credentials[0];
- return {
- ...host,
- password: credential.password as string | undefined,
- key: (credential.key || credential.privateKey) as string | undefined,
- keyPassword: credential.keyPassword as string | undefined,
- keyType: credential.keyType as string | undefined,
- authType: credential.authType as string | undefined,
- } as JumpHostConfig;
- }
- }
-
- return host as JumpHostConfig;
- } catch (error) {
- statsLogger.error("Failed to resolve jump host", error, {
- operation: "resolve_jump_host",
- hostId,
- userId,
- });
- return null;
- }
-}
-
-async function createJumpHostChain(
- jumpHosts: Array<{ hostId: number }>,
- userId: string,
- socks5Config?: SOCKS5Config | null,
-): Promise<Client | null> {
- if (!jumpHosts || jumpHosts.length === 0) {
- return null;
- }
-
- let currentClient: Client | null = null;
- const clients: Client[] = [];
-
- try {
- const jumpHostConfigs: Array<Awaited<ReturnType<typeof resolveJumpHost>>> =
- [];
- for (let i = 0; i < jumpHosts.length; i++) {
- const config = await resolveJumpHost(jumpHosts[i].hostId, userId);
- jumpHostConfigs.push(config);
- }
-
- const totalHops = jumpHostConfigs.length;
-
- for (let i = 0; i < jumpHostConfigs.length; i++) {
- if (!jumpHostConfigs[i]) {
- statsLogger.error(`Jump host ${i + 1} not found`, undefined, {
- operation: "jump_host_chain",
- hostId: jumpHosts[i].hostId,
- hopIndex: i,
- totalHops,
- });
- clients.forEach((c) => c.end());
- return null;
- }
- }
-
- let proxySocket: import("net").Socket | null = null;
- if (socks5Config?.useSocks5) {
- const firstHop = jumpHostConfigs[0]!;
- proxySocket = await createSocks5Connection(
- firstHop.ip,
- firstHop.port || 22,
- socks5Config,
- );
- }
-
- for (let i = 0; i < jumpHostConfigs.length; i++) {
- const jumpHostConfig = jumpHostConfigs[i]!;
-
- const jumpClient = new Client();
- clients.push(jumpClient);
-
- const jumpHostVerifier = await SSHHostKeyVerifier.createHostVerifier(
- jumpHostConfig.id,
- jumpHostConfig.ip,
- jumpHostConfig.port || 22,
- null,
- userId,
- true,
- );
-
- const connected = await new Promise<boolean>((resolve) => {
- const timeout = setTimeout(() => {
- resolve(false);
- }, 30000);
-
- jumpClient.on("ready", () => {
- clearTimeout(timeout);
- resolve(true);
- });
-
- jumpClient.on("error", (err) => {
- clearTimeout(timeout);
- statsLogger.error(
- `Jump host ${i + 1}/${totalHops} connection failed`,
- err,
- {
- operation: "jump_host_connect",
- hostId: jumpHostConfig.id,
- ip: jumpHostConfig.ip,
- hopIndex: i,
- totalHops,
- previousHop:
- i > 0
- ? jumpHostConfigs[i - 1]?.ip
- : proxySocket
- ? "proxy"
- : "direct",
- usedProxySocket: i === 0 && !!proxySocket,
- },
- );
- resolve(false);
- });
-
- const connectConfig: Record<string, unknown> = {
- host: jumpHostConfig.ip?.replace(/^\[|\]$/g, "") || jumpHostConfig.ip,
- port: jumpHostConfig.port || 22,
- username: jumpHostConfig.username,
- tryKeyboard: jumpHostConfig.authType !== "none",
- readyTimeout: 60000,
- hostVerifier: jumpHostVerifier,
- algorithms: {
- kex: [
- "curve25519-sha256",
- "ecdh-sha2-nistp521",
- "ecdh-sha2-nistp384",
- "ecdh-sha2-nistp256",
- "diffie-hellman-group-exchange-sha256",
- "diffie-hellman-group18-sha512",
- "diffie-hellman-group17-sha512",
- "diffie-hellman-group16-sha512",
- "diffie-hellman-group15-sha512",
- "diffie-hellman-group14-sha256",
- "diffie-hellman-group14-sha1",
- "diffie-hellman-group-exchange-sha1",
- "diffie-hellman-group1-sha1",
- ],
- serverHostKey: [
- "ssh-ed25519",
- "ecdsa-sha2-nistp521",
- "ecdsa-sha2-nistp384",
- "ecdsa-sha2-nistp256",
- "rsa-sha2-512",
- "rsa-sha2-256",
- "ssh-rsa",
- "ssh-dss",
- ],
- cipher: SSH_ALGORITHMS.cipher,
- hmac: [
- "hmac-sha2-512",
- "hmac-sha2-256",
- "hmac-sha1",
- "hmac-md5",
- ],
- compress: ["none", "[email protected]", "zlib"],
- },
- };
-
- if (jumpHostConfig.authType === "password" && jumpHostConfig.password) {
- connectConfig.password = jumpHostConfig.password;
- } else if (jumpHostConfig.authType === "key" && jumpHostConfig.key) {
- const cleanKey = jumpHostConfig.key
- .trim()
- .replace(/\r\n/g, "\n")
- .replace(/\r/g, "\n");
- connectConfig.privateKey = Buffer.from(cleanKey, "utf8");
- if (jumpHostConfig.keyPassword) {
- connectConfig.passphrase = jumpHostConfig.keyPassword;
- }
- }
-
- jumpClient.on(
- "keyboard-interactive",
- (
- _name: string,
- _instructions: string,
- _lang: string,
- prompts: Array<{ prompt: string; echo: boolean }>,
- finish: (responses: string[]) => void,
- ) => {
- const responses = prompts.map((p) => {
- if (/password/i.test(p.prompt) && jumpHostConfig.password) {
- return jumpHostConfig.password as string;
- }
- return "";
- });
- finish(responses);
- },
- );
-
- if (currentClient) {
- currentClient.forwardOut(
- "127.0.0.1",
- 0,
- jumpHostConfig.ip,
- jumpHostConfig.port || 22,
- (err, stream) => {
- if (err) {
- clearTimeout(timeout);
- resolve(false);
- return;
- }
- connectConfig.sock = stream;
- jumpClient.connect(connectConfig);
- },
- );
- } else if (proxySocket) {
- connectConfig.sock = proxySocket;
- jumpClient.connect(connectConfig);
- } else {
- jumpClient.connect(connectConfig);
- }
- });
-
- if (!connected) {
- clients.forEach((c) => c.end());
- return null;
- }
-
- currentClient = jumpClient;
- }
-
- return currentClient;
- } catch (error) {
- statsLogger.error("Failed to create jump host chain", error, {
- operation: "jump_host_chain",
- });
- clients.forEach((c) => c.end());
- return null;
- }
-}
-
-interface MetricsSession {
- client: Client;
- isConnected: boolean;
- lastActive: number;
- timeout?: NodeJS.Timeout;
- activeOperations: number;
- hostId: number;
- userId: string;
-}
-
-interface PendingTOTPSession {
- client: Client;
- finish: (responses: string[]) => void;
- config: ConnectConfig;
- createdAt: number;
- sessionId: string;
- hostId: number;
- userId: string;
- prompts?: Array<{ prompt: string; echo: boolean }>;
- totpPromptIndex?: number;
- resolvedPassword?: string;
- totpAttempts: number;
-}
-
-interface MetricsViewer {
- sessionId: string;
- userId: string;
- hostId: number;
- lastHeartbeat: number;
-}
-
-const metricsSessions: Record<string, MetricsSession> = {};
-const pendingTOTPSessions: Record<string, PendingTOTPSession> = {};
-
-function cleanupMetricsSession(sessionId: string) {
- const session = metricsSessions[sessionId];
- if (session) {
- if (session.activeOperations > 0) {
- statsLogger.warn(
- `Deferring metrics session cleanup - ${session.activeOperations} active operations`,
- {
- operation: "cleanup_deferred",
- sessionId,
- activeOperations: session.activeOperations,
- },
- );
- scheduleMetricsSessionCleanup(sessionId);
- return;
- }
-
- try {
- session.client.end();
- } catch {
- // expected
- }
- clearTimeout(session.timeout);
- delete metricsSessions[sessionId];
- }
-}
-
-function scheduleMetricsSessionCleanup(sessionId: string) {
- const session = metricsSessions[sessionId];
- if (session) {
- if (session.timeout) clearTimeout(session.timeout);
-
- session.timeout = setTimeout(
- () => {
- cleanupMetricsSession(sessionId);
- },
- 30 * 60 * 1000,
- );
- }
-}
-
-function getSessionKey(hostId: number, userId: string): string {
- return `${userId}:${hostId}`;
-}
-
-class RequestQueue {
- private queues = new Map<number, Array<() => Promise<unknown>>>();
- private processing = new Set<number>();
- private requestTimeout = 60000;
-
- async queueRequest<T>(hostId: number, request: () => Promise<T>): Promise<T> {
- return new Promise<T>((resolve, reject) => {
- const wrappedRequest = async () => {
- try {
- const result = await Promise.race<T>([
- request(),
- new Promise<never>((_, rej) =>
- setTimeout(
- () =>
- rej(
- new Error(
- `Request timeout after ${this.requestTimeout}ms for host ${hostId}`,
- ),
- ),
- this.requestTimeout,
- ),
- ),
- ]);
- resolve(result);
- } catch (error) {
- reject(error);
- }
- };
-
- const queue = this.queues.get(hostId) || [];
- queue.push(wrappedRequest);
- this.queues.set(hostId, queue);
- this.processQueue(hostId);
- });
- }
-
- private async processQueue(hostId: number): Promise<void> {
- if (this.processing.has(hostId)) return;
-
- this.processing.add(hostId);
- const queue = this.queues.get(hostId) || [];
-
- while (queue.length > 0) {
- const request = queue.shift();
- if (request) {
- try {
- await request();
- } catch {
- // expected
- }
- }
- }
-
- this.processing.delete(hostId);
- const currentQueue = this.queues.get(hostId);
- if (currentQueue && currentQueue.length > 0) {
- this.processQueue(hostId);
- }
- }
-}
-
-interface CachedMetrics {
- data: unknown;
- timestamp: number;
- hostId: number;
-}
-
-class MetricsCache {
- private cache = new Map<number, CachedMetrics>();
- private ttl = 30000;
-
- get(hostId: number): unknown | null {
- const cached = this.cache.get(hostId);
- if (cached && Date.now() - cached.timestamp < this.ttl) {
- return cached.data;
- }
- return null;
- }
-
- set(hostId: number, data: unknown): void {
- this.cache.set(hostId, {
- data,
- timestamp: Date.now(),
- hostId,
- });
- }
-
- clear(hostId?: number): void {
- if (hostId) {
- this.cache.delete(hostId);
- } else {
- this.cache.clear();
- }
- }
-}
-
-interface AuthFailureRecord {
- count: number;
- lastFailure: number;
- reason: "TOTP" | "AUTH" | "TIMEOUT";
- permanent: boolean;
-}
-
-class AuthFailureTracker {
- private failures = new Map<number, AuthFailureRecord>();
- private maxRetries = 3;
- private backoffBase = 5000;
-
- recordFailure(
- hostId: number,
- reason: "TOTP" | "AUTH" | "TIMEOUT",
- permanent = false,
- ): void {
- const existing = this.failures.get(hostId);
- if (existing) {
- existing.count++;
- existing.lastFailure = Date.now();
- existing.reason = reason;
- if (permanent) existing.permanent = true;
- } else {
- this.failures.set(hostId, {
- count: 1,
- lastFailure: Date.now(),
- reason,
- permanent,
- });
- }
- }
-
- shouldSkip(hostId: number): boolean {
- const record = this.failures.get(hostId);
- if (!record) return false;
-
- if (record.reason === "TOTP" || record.permanent) {
- return true;
- }
-
- if (record.count >= this.maxRetries) {
- return true;
- }
-
- const backoffTime = this.backoffBase * Math.pow(2, record.count - 1);
- const timeSinceFailure = Date.now() - record.lastFailure;
-
- return timeSinceFailure < backoffTime;
- }
-
- getSkipReason(hostId: number): string | null {
- const record = this.failures.get(hostId);
- if (!record) return null;
-
- if (record.reason === "TOTP") {
- return "TOTP authentication required (metrics unavailable)";
- }
-
- if (record.permanent) {
- return "Authentication permanently failed";
- }
-
- if (record.count >= this.maxRetries) {
- return `Too many authentication failures (${record.count} attempts)`;
- }
-
- const backoffTime = this.backoffBase * Math.pow(2, record.count - 1);
- const timeSinceFailure = Date.now() - record.lastFailure;
- const remainingTime = Math.ceil((backoffTime - timeSinceFailure) / 1000);
-
- if (timeSinceFailure < backoffTime) {
- return `Retry in ${remainingTime}s (attempt ${record.count}/${this.maxRetries})`;
- }
-
- return null;
- }
-
- reset(hostId: number): void {
- this.failures.delete(hostId);
- }
-
- cleanup(): void {
- const maxAge = 60 * 60 * 1000;
- const now = Date.now();
-
- for (const [hostId, record] of this.failures.entries()) {
- if (!record.permanent && now - record.lastFailure > maxAge) {
- this.failures.delete(hostId);
- }
- }
- }
-}
-
-class PollingBackoff {
- private failures = new Map<number, { count: number; nextRetry: number }>();
- private baseDelay = 30000;
- private maxDelay = 600000;
- private maxRetries = 5;
-
- recordFailure(hostId: number): void {
- const existing = this.failures.get(hostId) || { count: 0, nextRetry: 0 };
- const delay = Math.min(
- this.baseDelay * Math.pow(2, existing.count),
- this.maxDelay,
- );
- this.failures.set(hostId, {
- count: existing.count + 1,
- nextRetry: Date.now() + delay,
- });
- }
-
- shouldSkip(hostId: number): boolean {
- const backoff = this.failures.get(hostId);
- if (!backoff) return false;
-
- if (backoff.count >= this.maxRetries) {
- return true;
- }
-
- return Date.now() < backoff.nextRetry;
- }
-
- getBackoffInfo(hostId: number): string | null {
- const backoff = this.failures.get(hostId);
- if (!backoff) return null;
-
- if (backoff.count >= this.maxRetries) {
- return `Max retries exceeded (${backoff.count} failures) - polling suspended`;
- }
-
- const remainingMs = backoff.nextRetry - Date.now();
- if (remainingMs > 0) {
- const remainingSec = Math.ceil(remainingMs / 1000);
- return `Retry in ${remainingSec}s (attempt ${backoff.count}/${this.maxRetries})`;
- }
-
- return null;
- }
-
- reset(hostId: number): void {
- this.failures.delete(hostId);
- }
-
- cleanup(): void {
- const maxAge = 60 * 60 * 1000;
- const now = Date.now();
-
- for (const [hostId, backoff] of this.failures.entries()) {
- if (backoff.count < this.maxRetries && now - backoff.nextRetry > maxAge) {
- this.failures.delete(hostId);
- }
- }
- }
-}
-
-const requestQueue = new RequestQueue();
-const metricsCache = new MetricsCache();
-const authFailureTracker = new AuthFailureTracker();
-const pollingBackoff = new PollingBackoff();
const authManager = AuthManager.getInstance();
const permissionManager = PermissionManager.getInstance();
@@ -991,11 +341,19 @@ class PollingManager {
}
try {
- const isOnline = await tcpPing(
- refreshedHost.ip,
- refreshedHost.port,
- 5000,
- );
+ let pingHost = refreshedHost.ip;
+ let pingPort = refreshedHost.port;
+ if (refreshedHost.jumpHosts && refreshedHost.jumpHosts.length > 0) {
+ const firstJump = await fetchHostById(
+ refreshedHost.jumpHosts[0].hostId,
+ userId,
+ );
+ if (firstJump) {
+ pingHost = firstJump.ip;
+ pingPort = firstJump.port;
+ }
+ }
+ const isOnline = await tcpPing(pingHost, pingPort, 5000);
const statusEntry: StatusEntry = {
status: isOnline ? "online" : "offline",
lastChecked: new Date().toISOString(),
@@ -1550,8 +908,8 @@ async function buildSshConfig(
port: host.port,
username: host.username,
tryKeyboard: true,
- keepaliveInterval: 60000,
- keepaliveCountMax: 5,
+ keepaliveInterval: 30000,
+ keepaliveCountMax: 3,
readyTimeout: 60000,
tcpKeepAlive: true,
tcpKeepAliveInitialDelay: 30000,
@@ -2753,7 +2111,55 @@ app.post("/metrics/start/:id", validateHostId, async (req, res) => {
}
});
- if (
+ const hasJumpHosts =
+ host.jumpHosts && host.jumpHosts.length > 0 && host.userId;
+
+ if (hasJumpHosts) {
+ connectionLogs.push(
+ createConnectionLog(
+ "info",
+ "proxy",
+ "Connecting via jump host chain",
+ ),
+ );
+ createJumpHostChain(host.jumpHosts!, host.userId!)
+ .then((jumpClient) => {
+ jumpClient.forwardOut(
+ "127.0.0.1",
+ 0,
+ host.ip,
+ host.port,
+ (err, stream) => {
+ if (err || !stream) {
+ if (!isResolved) {
+ isResolved = true;
+ clearTimeout(timeout);
+ reject(err || new Error("Jump host forward failed"));
+ }
+ return;
+ }
+ config.sock = stream;
+ delete config.host;
+ delete config.port;
+ client.connect(config);
+ },
+ );
+ })
+ .catch((error) => {
+ if (!isResolved) {
+ isResolved = true;
+ clearTimeout(timeout);
+ connectionLogs.push(
+ createConnectionLog(
+ "error",
+ "proxy",
+ `Jump host connection failed: ${error instanceof Error ? error.message : "Unknown error"}`,
+ ),
+ );
+ reject(error);
+ }
+ });
+ } else if (
host.useSocks5 &&
(host.socks5Host ||
(host.socks5ProxyChain && host.socks5ProxyChain.length > 0))
@@ -3064,412 +2470,23 @@ app.post("/metrics/connect-totp", async (req, res) => {
}
});
-/**
- * @openapi
- * /metrics/heartbeat:
- * post:
- * summary: Update viewer heartbeat
- * description: Updates the heartbeat timestamp for a metrics viewer session to keep it alive.
- * tags:
- * - Server Stats
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * viewerSessionId:
- * type: string
- * responses:
- * 200:
- * description: Heartbeat updated successfully.
- * 400:
- * description: Invalid viewerSessionId.
- * 401:
- * description: Session expired - please log in again.
- * 404:
- * description: Viewer session not found.
- * 500:
- * description: Failed to update heartbeat.
- */
-app.post("/metrics/heartbeat", async (req, res) => {
- const { viewerSessionId } = req.body;
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!SimpleDBOps.isUserDataUnlocked(userId)) {
- return res.status(401).json({
- error: "Session expired - please log in again",
- code: "SESSION_EXPIRED",
- });
- }
-
- if (!viewerSessionId || typeof viewerSessionId !== "string") {
- return res.status(400).json({ error: "Invalid viewerSessionId" });
- }
-
- try {
- const success = pollingManager.updateHeartbeat(viewerSessionId);
- if (success) {
- res.json({ success: true });
- } else {
- res.status(404).json({ error: "Viewer session not found" });
- }
- } catch (error) {
- statsLogger.error("Failed to update heartbeat", {
- operation: "heartbeat_error",
- viewerSessionId,
- error: error instanceof Error ? error.message : String(error),
- });
- res.status(500).json({ error: "Failed to update heartbeat" });
- }
+registerServerStatsViewerRoutes(app, {
+ fetchHostById,
+ supportsMetrics: (host: SSHHostWithCredentials) => supportsMetrics(host),
+ parseStatsConfig: (statsConfig: SSHHostWithCredentials["statsConfig"]) =>
+ pollingManager.parseStatsConfig(statsConfig),
+ updateHeartbeat: (viewerSessionId) =>
+ pollingManager.updateHeartbeat(viewerSessionId),
+ registerViewer: (hostId, viewerSessionId, userId) =>
+ pollingManager.registerViewer(hostId, viewerSessionId, userId),
+ unregisterViewer: (hostId, viewerSessionId) =>
+ pollingManager.unregisterViewer(hostId, viewerSessionId),
});
-/**
- * @openapi
- * /metrics/register-viewer:
- * post:
- * summary: Register metrics viewer
- * description: Registers a new viewer session for a host to track who is viewing metrics.
- * tags:
- * - Server Stats
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hostId:
- * type: integer
- * responses:
- * 200:
- * description: Viewer registered successfully.
- * 400:
- * description: Invalid hostId.
- * 401:
- * description: Session expired - please log in again.
- * 500:
- * description: Failed to register viewer.
- */
-app.post("/metrics/register-viewer", async (req, res) => {
- const { hostId } = req.body;
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!SimpleDBOps.isUserDataUnlocked(userId)) {
- return res.status(401).json({
- error: "Session expired - please log in again",
- code: "SESSION_EXPIRED",
- });
- }
-
- if (!hostId || typeof hostId !== "number") {
- return res.status(400).json({ error: "Invalid hostId" });
- }
-
- try {
- // Graceful no-op if host is inaccessible, metrics disabled, or host type
- // does not support metrics. The client may call this speculatively, so
- // avoid returning 5xx for expected "no metrics available" scenarios.
- let host: SSHHostWithCredentials | undefined;
- try {
- host = await fetchHostById(hostId, userId);
- } catch (lookupErr) {
- statsLogger.warn(
- "register-viewer host lookup failed (treating as no-op)",
- {
- operation: "register_viewer_lookup",
- hostId,
- userId,
- error:
- lookupErr instanceof Error ? lookupErr.message : String(lookupErr),
- },
- );
- }
-
- if (!host) {
- return res.json({
- success: true,
- skipped: true,
- reason: "host_not_found",
- });
- }
-
- if (!supportsMetrics(host)) {
- return res.json({
- success: true,
- skipped: true,
- reason: "metrics_unsupported",
- });
- }
-
- const statsConfig = pollingManager.parseStatsConfig(host.statsConfig);
- if (!statsConfig.metricsEnabled) {
- return res.json({
- success: true,
- skipped: true,
- reason: "metrics_disabled",
- });
- }
-
- const viewerSessionId = `viewer-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
- try {
- pollingManager.registerViewer(hostId, viewerSessionId, userId);
- } catch (regErr) {
- statsLogger.warn(
- "pollingManager.registerViewer threw (treating as no-op)",
- {
- operation: "register_viewer_internal",
- hostId,
- userId,
- error: regErr instanceof Error ? regErr.message : String(regErr),
- },
- );
- return res.json({
- success: true,
- skipped: true,
- reason: "register_failed_noop",
- });
- }
-
- res.json({ success: true, viewerSessionId });
- } catch (error) {
- statsLogger.error("Failed to register viewer", {
- operation: "register_viewer_error",
- hostId,
- userId,
- error: error instanceof Error ? error.message : String(error),
- });
- // Even on unexpected errors we prefer a graceful client experience: the
- // viewer-registration is purely an optimization and should never break
- // the UI. Report success:false but HTTP 200 so the client can decide.
- res.status(200).json({
- success: false,
- skipped: true,
- reason: "internal_error",
- });
- }
-});
-
-/**
- * @openapi
- * /metrics/unregister-viewer:
- * post:
- * summary: Unregister metrics viewer
- * description: Unregisters a viewer session when they stop viewing metrics for a host.
- * tags:
- * - Server Stats
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * hostId:
- * type: integer
- * viewerSessionId:
- * type: string
- * responses:
- * 200:
- * description: Viewer unregistered successfully.
- * 400:
- * description: Invalid hostId or viewerSessionId.
- * 401:
- * description: Session expired - please log in again.
- * 500:
- * description: Failed to unregister viewer.
- */
-app.post("/metrics/unregister-viewer", async (req, res) => {
- const { hostId, viewerSessionId } = req.body;
- const userId = (req as AuthenticatedRequest).userId;
-
- if (!SimpleDBOps.isUserDataUnlocked(userId)) {
- return res.status(401).json({
- error: "Session expired - please log in again",
- code: "SESSION_EXPIRED",
- });
- }
-
- if (!hostId || typeof hostId !== "number") {
- return res.status(400).json({ error: "Invalid hostId" });
- }
-
- if (!viewerSessionId || typeof viewerSessionId !== "string") {
- return res.status(400).json({ error: "Invalid viewerSessionId" });
- }
-
- try {
- pollingManager.unregisterViewer(hostId, viewerSessionId);
- res.json({ success: true });
- } catch (error) {
- statsLogger.error("Failed to unregister viewer", {
- operation: "unregister_viewer_error",
- hostId,
- viewerSessionId,
- error: error instanceof Error ? error.message : String(error),
- });
- res.status(500).json({ error: "Failed to unregister viewer" });
- }
-});
-
-/**
- * @openapi
- * /global-settings:
- * get:
- * summary: Get global monitoring defaults
- * tags:
- * - Stats
- * responses:
- * 200:
- * description: Global monitoring settings.
- * 403:
- * description: Requires admin privileges.
- */
-app.get("/global-settings", requireAdmin, async (_req, res) => {
- try {
- const db = getDb();
-
- try {
- db.$client.prepare("SELECT 1 FROM settings LIMIT 1").get();
- } catch (tableError) {
- statsLogger.warn("Settings table does not exist, using defaults", {
- operation: "global_settings_table_check",
- error:
- tableError instanceof Error ? tableError.message : String(tableError),
- });
- return res.json({
- statusCheckInterval: DEFAULT_STATS_CONFIG.statusCheckInterval,
- metricsInterval: DEFAULT_STATS_CONFIG.metricsInterval,
- });
- }
-
- const statusRow = db.$client
- .prepare(
- "SELECT value FROM settings WHERE key = 'global_status_check_interval'",
- )
- .get() as { value: string } | undefined;
- const metricsRow = db.$client
- .prepare(
- "SELECT value FROM settings WHERE key = 'global_metrics_interval'",
- )
- .get() as { value: string } | undefined;
-
- res.json({
- statusCheckInterval: statusRow
- ? parseInt(statusRow.value, 10)
- : DEFAULT_STATS_CONFIG.statusCheckInterval,
- metricsInterval: metricsRow
- ? parseInt(metricsRow.value, 10)
- : DEFAULT_STATS_CONFIG.metricsInterval,
- });
- } catch (error) {
- statsLogger.error("Failed to fetch global settings", {
- operation: "global_settings_fetch_error",
- error: error instanceof Error ? error.message : String(error),
- });
- res.status(500).json({ error: "Failed to fetch global settings" });
- }
-});
-
-/**
- * @openapi
- * /global-settings:
- * post:
- * summary: Update global monitoring defaults
- * tags:
- * - Stats
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * properties:
- * statusCheckInterval:
- * type: integer
- * metricsInterval:
- * type: integer
- * responses:
- * 200:
- * description: Settings saved.
- * 400:
- * description: Invalid parameters.
- * 403:
- * description: Requires admin privileges.
- */
-app.post("/global-settings", requireAdmin, async (req, res) => {
- const { statusCheckInterval, metricsInterval } = req.body;
-
- if (
- statusCheckInterval !== undefined &&
- (typeof statusCheckInterval !== "number" ||
- statusCheckInterval < 5 ||
- statusCheckInterval > 3600)
- ) {
- return res.status(400).json({
- error: "statusCheckInterval must be between 5 and 3600 seconds",
- });
- }
- if (
- metricsInterval !== undefined &&
- (typeof metricsInterval !== "number" ||
- metricsInterval < 5 ||
- metricsInterval > 3600)
- ) {
- return res
- .status(400)
- .json({ error: "metricsInterval must be between 5 and 3600 seconds" });
- }
-
- try {
- const db = getDb();
-
- try {
- db.$client.prepare("SELECT 1 FROM settings LIMIT 1").get();
- } catch (tableError) {
- statsLogger.error("Settings table does not exist, cannot save settings", {
- operation: "global_settings_table_check",
- error:
- tableError instanceof Error ? tableError.message : String(tableError),
- });
- return res.status(500).json({
- error:
- "Database settings table is missing. Please check database initialization.",
- });
- }
-
- if (statusCheckInterval !== undefined) {
- db.$client
- .prepare(
- "INSERT OR REPLACE INTO settings (key, value) VALUES ('global_status_check_interval', ?)",
- )
- .run(String(statusCheckInterval));
- }
- if (metricsInterval !== undefined) {
- db.$client
- .prepare(
- "INSERT OR REPLACE INTO settings (key, value) VALUES ('global_metrics_interval', ?)",
- )
- .run(String(metricsInterval));
- }
-
- await pollingManager.refreshAllPolling();
-
- res.json({
- success: true,
- message: "Settings updated and polling refreshed",
- });
- } catch (error) {
- statsLogger.error("Failed to save global settings", {
- operation: "global_settings_save_error",
- error: error instanceof Error ? error.message : String(error),
- });
- res.status(500).json({
- error: "Failed to save global settings",
- details: error instanceof Error ? error.message : String(error),
- });
- }
+registerServerStatsSettingsRoutes(app, {
+ requireAdmin,
+ defaultStatsConfig: DEFAULT_STATS_CONFIG,
+ refreshAllPolling: () => pollingManager.refreshAllPolling(),
});
process.on("SIGINT", () => {
diff --git a/src/backend/ssh/terminal-auth-helpers.ts b/src/backend/ssh/terminal-auth-helpers.ts
new file mode 100644
index 000000000..c3329b4cc
--- /dev/null
+++ b/src/backend/ssh/terminal-auth-helpers.ts
@@ -0,0 +1,80 @@
+import dgram from "dgram";
+import net from "net";
+import ssh2Pkg, {
+ type IdentityCallback,
+ type ParsedKey,
+ type SignCallback,
+ type SigningRequestOptions,
+} from "ssh2";
+
+const { BaseAgent } = ssh2Pkg;
+
+export class MemoryAgent extends BaseAgent {
+ private key: ParsedKey;
+
+ constructor(key: ParsedKey) {
+ super();
+ this.key = key;
+ }
+
+ getIdentities(cb: IdentityCallback<ParsedKey>): void {
+ cb(null, [this.key]);
+ }
+
+ sign(
+ _pubKey: ParsedKey | Buffer | string,
+ data: Buffer,
+ optionsOrCb: SigningRequestOptions | SignCallback,
+ cb?: SignCallback,
+ ): void {
+ const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb!;
+ const options = typeof optionsOrCb === "function" ? {} : optionsOrCb;
+ try {
+ const algo =
+ options.hash === "sha256"
+ ? "rsa-sha2-256"
+ : options.hash === "sha512"
+ ? "rsa-sha2-512"
+ : undefined;
+ const signature = this.key.sign(data, algo);
+ callback(null, signature);
+ } catch (err) {
+ callback(err instanceof Error ? err : new Error(String(err)));
+ }
+ }
+}
+
+export async function performPortKnocking(
+ host: string,
+ sequence: Array<{ port: number; protocol?: string; delay?: number }>,
+): Promise<void> {
+ for (const knock of sequence) {
+ const protocol = knock.protocol || "tcp";
+ const delay = knock.delay ?? 100;
+
+ await new Promise<void>((resolve) => {
+ if (protocol === "udp") {
+ const client = dgram.createSocket("udp4");
+ client.send(Buffer.alloc(0), knock.port, host, () => {
+ client.close();
+ resolve();
+ });
+ } else {
+ const socket = new net.Socket();
+ socket.once("connect", () => {
+ socket.destroy();
+ resolve();
+ });
+ socket.once("error", () => {
+ socket.destroy();
+ resolve();
+ });
+ socket.connect(knock.port, host);
+ }
+ });
+
+ if (delay > 0) {
+ await new Promise<void>((r) => setTimeout(r, delay));
+ }
+ }
+}
diff --git a/src/backend/ssh/terminal-jump-hosts.ts b/src/backend/ssh/terminal-jump-hosts.ts
new file mode 100644
index 000000000..54530a04b
--- /dev/null
+++ b/src/backend/ssh/terminal-jump-hosts.ts
@@ -0,0 +1,339 @@
+import { and, eq } from "drizzle-orm";
+import ssh2Pkg, { type Client as SSHClientType } from "ssh2";
+import { getDb } from "../database/db/index.js";
+import { hosts, sshCredentials } from "../database/db/schema.js";
+import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
+import { sshLogger } from "../utils/logger.js";
+import { SimpleDBOps } from "../utils/simple-db-ops.js";
+import {
+ createSocks5Connection,
+ type SOCKS5Config,
+} from "../utils/socks5-helper.js";
+import { SSHHostKeyVerifier } from "./host-key-verifier.js";
+
+const { Client } = ssh2Pkg;
+
+interface JumpHostConfig {
+ id: number;
+ ip: string;
+ port: number;
+ username: string;
+ password?: string;
+ key?: string;
+ keyPassword?: string;
+ keyType?: string;
+ authType?: string;
+ credentialId?: number;
+ [key: string]: unknown;
+}
+
+async function resolveJumpHost(
+ hostId: number,
+ userId: string,
+): Promise<JumpHostConfig | null> {
+ sshLogger.info("Resolving jump host", {
+ operation: "terminal_jumphost_resolve",
+ userId,
+ hostId,
+ });
+ try {
+ const hostResults = await SimpleDBOps.select(
+ getDb().select().from(hosts).where(eq(hosts.id, hostId)),
+ "ssh_data",
+ userId,
+ );
+
+ if (hostResults.length === 0) {
+ return null;
+ }
+
+ const host = hostResults[0];
+ const ownerId = (host.userId || userId) as string;
+
+ if (host.credentialId) {
+ if (userId !== ownerId) {
+ try {
+ const { SharedCredentialManager } =
+ await import("../utils/shared-credential-manager.js");
+ const sharedCredManager = SharedCredentialManager.getInstance();
+ const sharedCred = await sharedCredManager.getSharedCredentialForUser(
+ hostId,
+ userId,
+ );
+ if (sharedCred) {
+ return {
+ ...host,
+ password: sharedCred.password,
+ key: sharedCred.key,
+ keyPassword: sharedCred.keyPassword,
+ keyType: sharedCred.keyType,
+ authType: sharedCred.key
+ ? "key"
+ : sharedCred.password
+ ? "password"
+ : "none",
+ } as JumpHostConfig;
+ }
+ } catch {
+ // fall through to owner credential lookup
+ }
+ }
+
+ const credentials = await SimpleDBOps.select(
+ getDb()
+ .select()
+ .from(sshCredentials)
+ .where(
+ and(
+ eq(sshCredentials.id, host.credentialId as number),
+ eq(sshCredentials.userId, ownerId),
+ ),
+ ),
+ "ssh_credentials",
+ ownerId,
+ );
+
+ if (credentials.length > 0) {
+ const credential = credentials[0];
+ return {
+ ...host,
+ password: credential.password as string | undefined,
+ key: (credential.key || credential.privateKey) as string | undefined,
+ keyPassword: credential.keyPassword as string | undefined,
+ keyType: credential.keyType as string | undefined,
+ authType: credential.authType as string | undefined,
+ } as JumpHostConfig;
+ }
+ }
+
+ return host as JumpHostConfig;
+ } catch (error) {
+ sshLogger.error("Failed to resolve jump host", error, {
+ operation: "resolve_jump_host",
+ hostId,
+ userId,
+ });
+ return null;
+ }
+}
+
+export async function createJumpHostChain(
+ jumpHosts: Array<{ hostId: number }>,
+ userId: string,
+ socks5Config?: SOCKS5Config | null,
+): Promise<SSHClientType | null> {
+ if (!jumpHosts || jumpHosts.length === 0) {
+ return null;
+ }
+
+ let currentClient: SSHClientType | null = null;
+ const clients: SSHClientType[] = [];
+
+ try {
+ const jumpHostConfigs = await Promise.all(
+ jumpHosts.map((jh) => resolveJumpHost(jh.hostId, userId)),
+ );
+
+ const totalHops = jumpHostConfigs.length;
+
+ for (let i = 0; i < jumpHostConfigs.length; i++) {
+ if (!jumpHostConfigs[i]) {
+ sshLogger.error(`Jump host ${i + 1} not found`, undefined, {
+ operation: "jump_host_chain",
+ hostId: jumpHosts[i].hostId,
+ hopIndex: i,
+ totalHops,
+ });
+ clients.forEach((c) => c.end());
+ return null;
+ }
+ }
+
+ let proxySocket: import("net").Socket | null = null;
+ if (socks5Config?.useSocks5) {
+ const firstHop = jumpHostConfigs[0];
+ proxySocket = await createSocks5Connection(
+ firstHop.ip,
+ firstHop.port || 22,
+ socks5Config,
+ );
+ }
+
+ for (let i = 0; i < jumpHostConfigs.length; i++) {
+ const jumpHostConfig = jumpHostConfigs[i];
+
+ const jumpClient = new Client();
+ clients.push(jumpClient);
+
+ const jumpHostVerifier = await SSHHostKeyVerifier.createHostVerifier(
+ jumpHostConfig.id,
+ jumpHostConfig.ip,
+ jumpHostConfig.port || 22,
+ null,
+ userId,
+ true,
+ );
+
+ const connected = await new Promise<boolean>((resolve) => {
+ const timeout = setTimeout(() => {
+ resolve(false);
+ }, 30000);
+
+ jumpClient.on("ready", () => {
+ clearTimeout(timeout);
+ sshLogger.success("Jump host connection established", {
+ operation: "terminal_jumphost_connected",
+ userId,
+ hostId: jumpHostConfig.id,
+ ip: jumpHostConfig.ip,
+ depth: i,
+ hopIndex: i,
+ totalHops,
+ usedProxySocket: i === 0 && !!proxySocket,
+ });
+ resolve(true);
+ });
+
+ jumpClient.on("error", (err) => {
+ clearTimeout(timeout);
+ sshLogger.error(
+ `Jump host ${i + 1}/${totalHops} connection failed`,
+ err,
+ {
+ operation: "jump_host_connect",
+ hostId: jumpHostConfig.id,
+ ip: jumpHostConfig.ip,
+ hopIndex: i,
+ totalHops,
+ previousHop:
+ i > 0
+ ? jumpHostConfigs[i - 1]?.ip
+ : proxySocket
+ ? "proxy"
+ : "direct",
+ usedProxySocket: i === 0 && !!proxySocket,
+ },
+ );
+ resolve(false);
+ });
+
+ const connectConfig: Record<string, unknown> = {
+ host: jumpHostConfig.ip?.replace(/^\[|\]$/g, "") || jumpHostConfig.ip,
+ port: jumpHostConfig.port || 22,
+ username: jumpHostConfig.username,
+ tryKeyboard: jumpHostConfig.authType !== "none",
+ readyTimeout: 60000,
+ hostVerifier: jumpHostVerifier,
+ algorithms: {
+ kex: [
+ "curve25519-sha256",
+ "ecdh-sha2-nistp521",
+ "ecdh-sha2-nistp384",
+ "ecdh-sha2-nistp256",
+ "diffie-hellman-group-exchange-sha256",
+ "diffie-hellman-group18-sha512",
+ "diffie-hellman-group17-sha512",
+ "diffie-hellman-group16-sha512",
+ "diffie-hellman-group15-sha512",
+ "diffie-hellman-group14-sha256",
+ "diffie-hellman-group14-sha1",
+ "diffie-hellman-group-exchange-sha1",
+ "diffie-hellman-group1-sha1",
+ ],
+ serverHostKey: [
+ "ssh-ed25519",
+ "ecdsa-sha2-nistp521",
+ "ecdsa-sha2-nistp384",
+ "ecdsa-sha2-nistp256",
+ "rsa-sha2-512",
+ "rsa-sha2-256",
+ "ssh-rsa",
+ "ssh-dss",
+ ],
+ cipher: SSH_ALGORITHMS.cipher,
+ hmac: [
+ "hmac-sha2-512",
+ "hmac-sha2-256",
+ "hmac-sha1",
+ "hmac-md5",
+ ],
+ compress: ["none", "[email protected]", "zlib"],
+ },
+ };
+
+ if (jumpHostConfig.authType === "password" && jumpHostConfig.password) {
+ connectConfig.password = jumpHostConfig.password;
+ } else if (jumpHostConfig.authType === "key" && jumpHostConfig.key) {
+ const cleanKey = jumpHostConfig.key
+ .trim()
+ .replace(/\r\n/g, "\n")
+ .replace(/\r/g, "\n");
+ connectConfig.privateKey = Buffer.from(cleanKey, "utf8");
+ if (jumpHostConfig.keyPassword) {
+ connectConfig.passphrase = jumpHostConfig.keyPassword;
+ }
+ }
+
+ jumpClient.on(
+ "keyboard-interactive",
+ (
+ _name: string,
+ _instructions: string,
+ _lang: string,
+ prompts: Array<{ prompt: string; echo: boolean }>,
+ finish: (responses: string[]) => void,
+ ) => {
+ const responses = prompts.map((p) => {
+ if (/password/i.test(p.prompt) && jumpHostConfig.password) {
+ return jumpHostConfig.password as string;
+ }
+ return "";
+ });
+ finish(responses);
+ },
+ );
+
+ if (currentClient) {
+ currentClient.forwardOut(
+ "127.0.0.1",
+ 0,
+ jumpHostConfig.ip,
+ jumpHostConfig.port || 22,
+ (err, stream) => {
+ if (err) {
+ clearTimeout(timeout);
+ resolve(false);
+ return;
+ }
+ connectConfig.sock = stream;
+ jumpClient.connect(connectConfig);
+ },
+ );
+ } else if (proxySocket) {
+ connectConfig.sock = proxySocket;
+ jumpClient.connect(connectConfig);
+ } else {
+ jumpClient.connect(connectConfig);
+ }
+ });
+
+ if (!connected) {
+ clients.forEach((c) => c.end());
+ return null;
+ }
+
+ currentClient = jumpClient;
+ }
+
+ return currentClient;
+ } catch (error) {
+ sshLogger.error("Failed to create jump host chain", error, {
+ operation: "jump_host_chain",
+ });
+ clients.forEach((c) => c.end());
+ return null;
+ }
+}
diff --git a/src/backend/ssh/terminal-session-manager.ts b/src/backend/ssh/terminal-session-manager.ts
index 5e49cff5c..3d06348f6 100644
--- a/src/backend/ssh/terminal-session-manager.ts
+++ b/src/backend/ssh/terminal-session-manager.ts
@@ -86,12 +86,15 @@ class TerminalSessionManager {
!existing.sshStream.destroyed;
if (isLiveSession) {
// Don't destroy a live session (even if detached) — the caller should attach instead
- sshLogger.warn("Tab instance has live session, skipping duplicate create", {
- operation: "session_tab_duplicate_skip",
- existingSessionId: existing.id,
- tabInstanceId,
- hasAttachedWs: existing.attachedWs !== null,
- });
+ sshLogger.warn(
+ "Tab instance has live session, skipping duplicate create",
+ {
+ operation: "session_tab_duplicate_skip",
+ existingSessionId: existing.id,
+ tabInstanceId,
+ hasAttachedWs: existing.attachedWs !== null,
+ },
+ );
return existing.id;
}
sshLogger.warn("Tab instance already has session, destroying old", {
@@ -193,7 +196,9 @@ class TerminalSessionManager {
const isDetached =
!session.attachedWs || session.attachedWs.readyState !== WebSocket.OPEN;
- const isOriginalTab = (session.attachedTabInstanceId ?? session.tabInstanceId) === tabInstanceId;
+ const isOriginalTab =
+ (session.attachedTabInstanceId ?? session.tabInstanceId) ===
+ tabInstanceId;
if (
!isDetached &&
diff --git a/src/backend/ssh/terminal.ts b/src/backend/ssh/terminal.ts
index 92ef42770..b53d76909 100644
--- a/src/backend/ssh/terminal.ts
+++ b/src/backend/ssh/terminal.ts
@@ -3,18 +3,12 @@ import ssh2Pkg, {
type Client as SSHClientType,
type ClientChannel,
type PseudoTtyOptions,
- type ParsedKey,
- type SignCallback,
- type SigningRequestOptions,
- type IdentityCallback,
} from "ssh2";
-const { Client, BaseAgent, utils: ssh2Utils } = ssh2Pkg;
-import net from "net";
-import dgram from "dgram";
+const { Client, utils: ssh2Utils } = ssh2Pkg;
import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
import axios from "axios";
import { getDb } from "../database/db/index.js";
-import { sshCredentials, hosts } from "../database/db/schema.js";
+import { hosts } from "../database/db/schema.js";
import { eq, and } from "drizzle-orm";
import { sshLogger, authLogger } from "../utils/logger.js";
import { SimpleDBOps } from "../utils/simple-db-ops.js";
@@ -27,82 +21,14 @@ import {
import { SSHAuthManager } from "./auth-manager.js";
import type { ProxyNode } from "../../types/index.js";
import { SSHHostKeyVerifier } from "./host-key-verifier.js";
+import { createJumpHostChain } from "./terminal-jump-hosts.js";
import { sessionManager } from "./terminal-session-manager.js";
import {
detectTmux,
attachOrCreateTmuxSession,
waitForTmuxSession,
} from "./tmux-helper.js";
-
-class MemoryAgent extends BaseAgent {
- private key: ParsedKey;
-
- constructor(key: ParsedKey) {
- super();
- this.key = key;
- }
-
- getIdentities(cb: IdentityCallback<ParsedKey>): void {
- cb(null, [this.key]);
- }
-
- sign(
- pubKey: ParsedKey | Buffer | string,
- data: Buffer,
- optionsOrCb: SigningRequestOptions | SignCallback,
- cb?: SignCallback,
- ): void {
- const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb!;
- const options = typeof optionsOrCb === "function" ? {} : optionsOrCb;
- try {
- const algo =
- options.hash === "sha256"
- ? "rsa-sha2-256"
- : options.hash === "sha512"
- ? "rsa-sha2-512"
- : undefined;
- const signature = this.key.sign(data, algo);
- callback(null, signature);
- } catch (err) {
- callback(err instanceof Error ? err : new Error(String(err)));
- }
- }
-}
-
-async function performPortKnocking(
- host: string,
- sequence: Array<{ port: number; protocol?: string; delay?: number }>,
-): Promise<void> {
- for (const knock of sequence) {
- const protocol = knock.protocol || "tcp";
- const delay = knock.delay ?? 100;
-
- await new Promise<void>((resolve) => {
- if (protocol === "udp") {
- const client = dgram.createSocket("udp4");
- client.send(Buffer.alloc(0), knock.port, host, () => {
- client.close();
- resolve();
- });
- } else {
- const socket = new net.Socket();
- socket.once("connect", () => {
- socket.destroy();
- resolve();
- });
- socket.once("error", () => {
- socket.destroy();
- resolve();
- });
- socket.connect(knock.port, host);
- }
- });
-
- if (delay > 0) {
- await new Promise<void>((r) => setTimeout(r, delay));
- }
- }
-}
+import { MemoryAgent, performPortKnocking } from "./terminal-auth-helpers.js";
interface ConnectToHostData {
cols: number;
@@ -164,331 +90,6 @@ const userCrypto = UserCrypto.getInstance();
const userConnections = new Map<string, Set<WebSocket>>();
-interface JumpHostConfig {
- id: number;
- ip: string;
- port: number;
- username: string;
- password?: string;
- key?: string;
- keyPassword?: string;
- keyType?: string;
- authType?: string;
- credentialId?: number;
- [key: string]: unknown;
-}
-
-async function resolveJumpHost(
- hostId: number,
- userId: string,
-): Promise<JumpHostConfig | null> {
- sshLogger.info("Resolving jump host", {
- operation: "terminal_jumphost_resolve",
- userId,
- hostId,
- });
- try {
- const hostResults = await SimpleDBOps.select(
- getDb().select().from(hosts).where(eq(hosts.id, hostId)),
- "ssh_data",
- userId,
- );
-
- if (hostResults.length === 0) {
- return null;
- }
-
- const host = hostResults[0];
- const ownerId = (host.userId || userId) as string;
-
- if (host.credentialId) {
- if (userId !== ownerId) {
- try {
- const { SharedCredentialManager } =
- await import("../utils/shared-credential-manager.js");
- const sharedCredManager = SharedCredentialManager.getInstance();
- const sharedCred = await sharedCredManager.getSharedCredentialForUser(
- hostId,
- userId,
- );
- if (sharedCred) {
- return {
- ...host,
- password: sharedCred.password,
- key: sharedCred.key,
- keyPassword: sharedCred.keyPassword,
- keyType: sharedCred.keyType,
- authType: sharedCred.key
- ? "key"
- : sharedCred.password
- ? "password"
- : "none",
- } as JumpHostConfig;
- }
- } catch {
- // fall through to owner credential lookup
- }
- }
-
- const credentials = await SimpleDBOps.select(
- getDb()
- .select()
- .from(sshCredentials)
- .where(
- and(
- eq(sshCredentials.id, host.credentialId as number),
- eq(sshCredentials.userId, ownerId),
- ),
- ),
- "ssh_credentials",
- ownerId,
- );
-
- if (credentials.length > 0) {
- const credential = credentials[0];
- return {
- ...host,
- password: credential.password as string | undefined,
- key: (credential.key || credential.privateKey) as string | undefined,
- keyPassword: credential.keyPassword as string | undefined,
- keyType: credential.keyType as string | undefined,
- authType: credential.authType as string | undefined,
- } as JumpHostConfig;
- }
- }
-
- return host as JumpHostConfig;
- } catch (error) {
- sshLogger.error("Failed to resolve jump host", error, {
- operation: "resolve_jump_host",
- hostId,
- userId,
- });
- return null;
- }
-}
-
-async function createJumpHostChain(
- jumpHosts: Array<{ hostId: number }>,
- userId: string,
- socks5Config?: SOCKS5Config | null,
-): Promise<SSHClientType | null> {
- if (!jumpHosts || jumpHosts.length === 0) {
- return null;
- }
-
- let currentClient: SSHClientType | null = null;
- const clients: SSHClientType[] = [];
-
- try {
- const jumpHostConfigs = await Promise.all(
- jumpHosts.map((jh) => resolveJumpHost(jh.hostId, userId)),
- );
-
- const totalHops = jumpHostConfigs.length;
-
- for (let i = 0; i < jumpHostConfigs.length; i++) {
- if (!jumpHostConfigs[i]) {
- sshLogger.error(`Jump host ${i + 1} not found`, undefined, {
- operation: "jump_host_chain",
- hostId: jumpHosts[i].hostId,
- hopIndex: i,
- totalHops,
- });
- clients.forEach((c) => c.end());
- return null;
- }
- }
-
- let proxySocket: import("net").Socket | null = null;
- if (socks5Config?.useSocks5) {
- const firstHop = jumpHostConfigs[0];
- proxySocket = await createSocks5Connection(
- firstHop.ip,
- firstHop.port || 22,
- socks5Config,
- );
- }
-
- for (let i = 0; i < jumpHostConfigs.length; i++) {
- const jumpHostConfig = jumpHostConfigs[i];
-
- const jumpClient = new Client();
- clients.push(jumpClient);
-
- const jumpHostVerifier = await SSHHostKeyVerifier.createHostVerifier(
- jumpHostConfig.id,
- jumpHostConfig.ip,
- jumpHostConfig.port || 22,
- null,
- userId,
- true,
- );
-
- const connected = await new Promise<boolean>((resolve) => {
- const timeout = setTimeout(() => {
- resolve(false);
- }, 30000);
-
- jumpClient.on("ready", () => {
- clearTimeout(timeout);
- sshLogger.success("Jump host connection established", {
- operation: "terminal_jumphost_connected",
- userId,
- hostId: jumpHostConfig.id,
- ip: jumpHostConfig.ip,
- depth: i,
- hopIndex: i,
- totalHops,
- usedProxySocket: i === 0 && !!proxySocket,
- });
- resolve(true);
- });
-
- jumpClient.on("error", (err) => {
- clearTimeout(timeout);
- sshLogger.error(
- `Jump host ${i + 1}/${totalHops} connection failed`,
- err,
- {
- operation: "jump_host_connect",
- hostId: jumpHostConfig.id,
- ip: jumpHostConfig.ip,
- hopIndex: i,
- totalHops,
- previousHop:
- i > 0
- ? jumpHostConfigs[i - 1]?.ip
- : proxySocket
- ? "proxy"
- : "direct",
- usedProxySocket: i === 0 && !!proxySocket,
- },
- );
- resolve(false);
- });
-
- const connectConfig: Record<string, unknown> = {
- host: jumpHostConfig.ip?.replace(/^\[|\]$/g, "") || jumpHostConfig.ip,
- port: jumpHostConfig.port || 22,
- username: jumpHostConfig.username,
- tryKeyboard: jumpHostConfig.authType !== "none",
- readyTimeout: 60000,
- hostVerifier: jumpHostVerifier,
- algorithms: {
- kex: [
- "curve25519-sha256",
- "ecdh-sha2-nistp521",
- "ecdh-sha2-nistp384",
- "ecdh-sha2-nistp256",
- "diffie-hellman-group-exchange-sha256",
- "diffie-hellman-group18-sha512",
- "diffie-hellman-group17-sha512",
- "diffie-hellman-group16-sha512",
- "diffie-hellman-group15-sha512",
- "diffie-hellman-group14-sha256",
- "diffie-hellman-group14-sha1",
- "diffie-hellman-group-exchange-sha1",
- "diffie-hellman-group1-sha1",
- ],
- serverHostKey: [
- "ssh-ed25519",
- "ecdsa-sha2-nistp521",
- "ecdsa-sha2-nistp384",
- "ecdsa-sha2-nistp256",
- "rsa-sha2-512",
- "rsa-sha2-256",
- "ssh-rsa",
- "ssh-dss",
- ],
- cipher: SSH_ALGORITHMS.cipher,
- hmac: [
- "hmac-sha2-512",
- "hmac-sha2-256",
- "hmac-sha1",
- "hmac-md5",
- ],
- compress: ["none", "[email protected]", "zlib"],
- },
- };
-
- if (jumpHostConfig.authType === "password" && jumpHostConfig.password) {
- connectConfig.password = jumpHostConfig.password;
- } else if (jumpHostConfig.authType === "key" && jumpHostConfig.key) {
- const cleanKey = jumpHostConfig.key
- .trim()
- .replace(/\r\n/g, "\n")
- .replace(/\r/g, "\n");
- connectConfig.privateKey = Buffer.from(cleanKey, "utf8");
- if (jumpHostConfig.keyPassword) {
- connectConfig.passphrase = jumpHostConfig.keyPassword;
- }
- }
-
- jumpClient.on(
- "keyboard-interactive",
- (
- _name: string,
- _instructions: string,
- _lang: string,
- prompts: Array<{ prompt: string; echo: boolean }>,
- finish: (responses: string[]) => void,
- ) => {
- const responses = prompts.map((p) => {
- if (/password/i.test(p.prompt) && jumpHostConfig.password) {
- return jumpHostConfig.password as string;
- }
- return "";
- });
- finish(responses);
- },
- );
-
- if (currentClient) {
- currentClient.forwardOut(
- "127.0.0.1",
- 0,
- jumpHostConfig.ip,
- jumpHostConfig.port || 22,
- (err, stream) => {
- if (err) {
- clearTimeout(timeout);
- resolve(false);
- return;
- }
- connectConfig.sock = stream;
- jumpClient.connect(connectConfig);
- },
- );
- } else if (proxySocket) {
- connectConfig.sock = proxySocket;
- jumpClient.connect(connectConfig);
- } else {
- jumpClient.connect(connectConfig);
- }
- });
-
- if (!connected) {
- clients.forEach((c) => c.end());
- return null;
- }
-
- currentClient = jumpClient;
- }
-
- return currentClient;
- } catch (error) {
- sshLogger.error("Failed to create jump host chain", error, {
- operation: "jump_host_chain",
- });
- clients.forEach((c) => c.end());
- return null;
- }
-}
-
const wss = new WebSocketServer({
port: 30002,
});
@@ -525,7 +126,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
}
const payload = await authManager.verifyJWTToken(token);
- if (!payload) {
+ if (!payload?.userId || payload.pendingTOTP) {
ws.close(1008, "Authentication required");
return;
}
@@ -848,9 +449,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
}
cwdPending = true;
cwdBuffer = "";
- // Split the sentinel across shell variables so the echoed command
- // itself never contains "TERMIX_CWD:" — only the output line does.
- activeStream.write('a=TERMIX_CWD; echo "$a:$(pwd)"\r');
+ activeStream.write('\x15a=TERMIX_CWD; echo "$a:$(pwd)"\r');
break;
}
@@ -1227,8 +826,8 @@ wss.on("connection", async (ws: WebSocket, req) => {
const {
id,
ip: rawIp,
- port,
- username,
+ port: clientPort,
+ username: clientUsername,
password,
key,
keyPassword,
@@ -1236,7 +835,10 @@ wss.on("connection", async (ws: WebSocket, req) => {
authType,
credentialId,
} = hostConfig;
- const ip = rawIp?.replace(/^\[|\]$/g, "").trim() || rawIp;
+ const clientIp = rawIp?.replace(/^\[|\]$/g, "").trim() || rawIp;
+ let ip = clientIp;
+ let port = clientPort;
+ let username = clientUsername;
sshLogger.info("Resolving SSH host configuration", {
operation: "terminal_host_resolve",
sessionId,
@@ -1339,6 +941,71 @@ wss.on("connection", async (ws: WebSocket, req) => {
}
}, 120000);
+ let resolvedHostData:
+ | (Record<string, unknown> & {
+ ip?: string;
+ port?: number;
+ username?: string;
+ password?: string;
+ key?: string;
+ keyPassword?: string;
+ keyType?: string;
+ authType?: string;
+ jumpHosts?: Array<{ hostId: number }>;
+ useSocks5?: boolean;
+ socks5Host?: string;
+ socks5Port?: number;
+ socks5Username?: string;
+ socks5Password?: string;
+ socks5ProxyChain?: unknown;
+ terminalConfig?: ConnectToHostData["hostConfig"]["terminalConfig"];
+ })
+ | null = null;
+
+ if (id && userId) {
+ try {
+ const { resolveHostById } = await import("./host-resolver.js");
+ resolvedHostData = (await resolveHostById(
+ id,
+ userId,
+ )) as unknown as typeof resolvedHostData;
+
+ if (resolvedHostData) {
+ if (
+ (!hostConfig.jumpHosts || hostConfig.jumpHosts.length === 0) &&
+ resolvedHostData.jumpHosts &&
+ resolvedHostData.jumpHosts.length > 0
+ ) {
+ hostConfig.jumpHosts = resolvedHostData.jumpHosts;
+ sendLog(
+ "jump",
+ "info",
+ `Loaded ${resolvedHostData.jumpHosts.length} jump host(s) from server-side host data`,
+ );
+ }
+
+ if (!hostConfig.useSocks5 && resolvedHostData.useSocks5) {
+ hostConfig.useSocks5 = resolvedHostData.useSocks5;
+ hostConfig.socks5Host = resolvedHostData.socks5Host;
+ hostConfig.socks5Port = resolvedHostData.socks5Port;
+ hostConfig.socks5Username = resolvedHostData.socks5Username;
+ hostConfig.socks5Password = resolvedHostData.socks5Password;
+ hostConfig.socks5ProxyChain = resolvedHostData.socks5ProxyChain;
+ }
+
+ if (!hostConfig.terminalConfig && resolvedHostData.terminalConfig) {
+ hostConfig.terminalConfig = resolvedHostData.terminalConfig;
+ }
+ }
+ } catch (error) {
+ sshLogger.warn(`Failed to resolve server-side host data for ${id}`, {
+ operation: "ssh_host_data",
+ hostId: id,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+ }
+
// Resolve credentials server-side when frontend doesn't provide them
let resolvedCredentials = {
username,
@@ -1352,18 +1019,18 @@ wss.on("connection", async (ws: WebSocket, req) => {
const authMethodNotAvailable = false;
if (id && userId && !password && !key) {
try {
- const { resolveHostById } = await import("./host-resolver.js");
- const resolvedHost = await resolveHostById(id, userId);
- if (resolvedHost) {
+ if (resolvedHostData) {
+ ip = resolvedHostData.ip || ip;
+ port = resolvedHostData.port || port;
+ username = resolvedHostData.username || username;
resolvedCredentials = {
- username: resolvedHost.username || username,
- password: resolvedHost.password,
- key: resolvedHost.key,
- keyPassword: keyPassword || resolvedHost.keyPassword,
- keyType: resolvedHost.keyType,
- authType: resolvedHost.authType,
- certPublicKey: (resolvedHost as unknown as Record<string, unknown>)
- .certPublicKey as string | undefined,
+ username: resolvedHostData.username || username,
+ password: resolvedHostData.password,
+ key: resolvedHostData.key,
+ keyPassword: keyPassword || resolvedHostData.keyPassword,
+ keyType: resolvedHostData.keyType,
+ authType: resolvedHostData.authType,
+ certPublicKey: resolvedHostData.certPublicKey as string | undefined,
};
sendLog(
"auth",
@@ -1380,19 +1047,19 @@ wss.on("connection", async (ws: WebSocket, req) => {
}
} else if (credentialId && id && userId) {
try {
- const { resolveHostById } = await import("./host-resolver.js");
- const resolvedHost = await resolveHostById(id, userId);
- if (resolvedHost) {
+ if (resolvedHostData) {
+ ip = resolvedHostData.ip || ip;
+ port = resolvedHostData.port || port;
+ username = resolvedHostData.username || username;
resolvedCredentials = {
- username: resolvedHost.username || username,
- password: resolvedHost.password,
- key: resolvedHost.key,
+ username: resolvedHostData.username || username,
+ password: resolvedHostData.password,
+ key: resolvedHostData.key,
// Preserve user-supplied keyPassword (e.g. from passphrase dialog) over the empty DB value
- keyPassword: keyPassword || resolvedHost.keyPassword,
- keyType: resolvedHost.keyType,
- authType: resolvedHost.authType,
- certPublicKey: (resolvedHost as unknown as Record<string, unknown>)
- .certPublicKey as string | undefined,
+ keyPassword: keyPassword || resolvedHostData.keyPassword,
+ keyType: resolvedHostData.keyType,
+ authType: resolvedHostData.authType,
+ certPublicKey: resolvedHostData.certPublicKey as string | undefined,
};
}
} catch (error) {
@@ -1787,7 +1454,7 @@ wss.on("connection", async (ws: WebSocket, req) => {
const runPostShellCommands = (delay: number) => {
setTimeout(() => {
if (initialPath && initialPath.trim() !== "") {
- const cdCommand = `cd "${initialPath.replace(/"/g, '\\"')}" && pwd\r`;
+ const cdCommand = `cd "${initialPath.replace(/"/g, '\\"')}"\r`;
stream.write(cdCommand);
}
if (executeCommand && executeCommand.trim() !== "") {
@@ -2283,9 +1950,9 @@ wss.on("connection", async (ws: WebSocket, req) => {
keepaliveInterval:
typeof hostKeepaliveInterval === "number"
? hostKeepaliveInterval * 1000
- : 60000,
+ : 30000,
keepaliveCountMax:
- typeof hostKeepaliveCountMax === "number" ? hostKeepaliveCountMax : 5,
+ typeof hostKeepaliveCountMax === "number" ? hostKeepaliveCountMax : 3,
readyTimeout: 120000,
tcpKeepAlive: true,
tcpKeepAliveInitialDelay: 30000,
diff --git a/src/backend/ssh/transfer-paths.ts b/src/backend/ssh/transfer-paths.ts
new file mode 100644
index 000000000..694a9f5b7
--- /dev/null
+++ b/src/backend/ssh/transfer-paths.ts
@@ -0,0 +1,151 @@
+export type TransferPlatform = "windows" | "unix";
+
+/** OpenSSH SFTP on Windows commonly uses `/C:/...` or `C:/...` style paths. */
+export function isWindowsSftpPath(path: string): boolean {
+ const normalized = path.replace(/\\/g, "/");
+ return /^[A-Za-z]:\//.test(normalized) || /^\/[A-Za-z]:\//.test(normalized);
+}
+
+export function inferPlatformFromPath(path: string): TransferPlatform | null {
+ if (isWindowsSftpPath(path)) return "windows";
+ if (path.startsWith("/") && !/^\/[A-Za-z]:/.test(path.replace(/\\/g, "/"))) {
+ return "unix";
+ }
+ return null;
+}
+
+export function normalizeSftpPath(path: string): string {
+ const normalized = path.replace(/\\/g, "/").replace(/\/+$/, "");
+ if (!normalized) return path.startsWith("/") ? "/" : ".";
+ return normalized.replace(/([^:])\/+/g, "$1/");
+}
+
+export function basename(path: string): string {
+ const normalized = path.replace(/\\/g, "/").replace(/\/+$/, "");
+ const idx = normalized.lastIndexOf("/");
+ if (idx < 0) return normalized;
+ return normalized.substring(idx + 1) || normalized;
+}
+
+export function dirname(path: string): string {
+ const normalized = path.replace(/\\/g, "/").replace(/\/+$/, "");
+ if (!normalized) return normalized;
+
+ const idx = normalized.lastIndexOf("/");
+ if (idx < 0) return normalized;
+
+ const parent = normalized.substring(0, idx);
+ if (!parent) return "/";
+ if (/^\/[A-Za-z]:$/.test(parent) || /^[A-Za-z]:$/.test(parent)) {
+ return parent;
+ }
+ return parent || "/";
+}
+
+export function joinPath(base: string, ...parts: string[]): string {
+ let result = base.replace(/\\/g, "/");
+ for (const part of parts) {
+ if (!part) continue;
+ const segment = part.replace(/\\/g, "/").replace(/^\/+/, "");
+ if (!segment) continue;
+ if (result.endsWith("/")) {
+ result += segment;
+ } else {
+ result = `${result}/${segment}`;
+ }
+ }
+ return normalizeSftpPath(result);
+}
+
+export interface PathSegments {
+ /** Drive root prefix, e.g. `/C:` or `C:`; empty for Unix absolute paths. */
+ root: string;
+ /** Path segments below the root (may be empty). */
+ segments: string[];
+}
+
+export function splitPathSegments(path: string): PathSegments {
+ const normalized = normalizeSftpPath(path);
+
+ const posixDrive = normalized.match(/^(\/[A-Za-z]:)(?:\/(.*))?$/);
+ if (posixDrive) {
+ return {
+ root: posixDrive[1],
+ segments: (posixDrive[2] ?? "").split("/").filter(Boolean),
+ };
+ }
+
+ const drive = normalized.match(/^([A-Za-z]:)(?:\/(.*))?$/);
+ if (drive) {
+ return {
+ root: drive[1],
+ segments: (drive[2] ?? "").split("/").filter(Boolean),
+ };
+ }
+
+ if (normalized.startsWith("/")) {
+ return {
+ root: "/",
+ segments: normalized.split("/").filter(Boolean),
+ };
+ }
+
+ return {
+ root: "",
+ segments: normalized.split("/").filter(Boolean),
+ };
+}
+
+export function buildPathFromSegments(
+ root: string,
+ segments: string[],
+ count: number,
+): string {
+ const slice = segments.slice(0, count);
+ if (/^\/[A-Za-z]:$/.test(root)) {
+ return slice.length ? `${root}/${slice.join("/")}` : root;
+ }
+ if (/^[A-Za-z]:$/.test(root)) {
+ return slice.length ? `${root}/${slice.join("/")}` : root;
+ }
+ if (root === "/") {
+ return slice.length ? `/${slice.join("/")}` : "/";
+ }
+ if (root === "") {
+ return slice.join("/");
+ }
+ return slice.length ? `${root}/${slice.join("/")}` : root;
+}
+
+export function pathsOverlap(source: string, dest: string): boolean {
+ const norm = (p: string) => {
+ const n = normalizeSftpPath(p).toLowerCase();
+ return n || (isWindowsSftpPath(p) ? p : "/");
+ };
+ const s = norm(source);
+ const d = norm(dest);
+ const sep = "/";
+ return s === d || s.startsWith(`${d}${sep}`) || d.startsWith(`${s}${sep}`);
+}
+
+export function getWorkingDir(paths: string[]): string {
+ if (paths.length === 0) return "/";
+ const parents = paths.map((p) => dirname(p));
+ const first = parents[0];
+ if (parents.every((p) => p === first)) {
+ return first;
+ }
+ return first;
+}
+
+/** Convert an SFTP path to a local filesystem path when Termix runs on the dest host. */
+export function sftpPathToLocalPath(sftpPath: string): string {
+ const normalized = sftpPath.replace(/\\/g, "/");
+ if (/^\/[A-Za-z]:\//.test(normalized)) {
+ return normalized.slice(1).replace(/\//g, "\\");
+ }
+ if (/^[A-Za-z]:\//.test(normalized)) {
+ return normalized.replace(/\//g, "\\");
+ }
+ return sftpPath;
+}
diff --git a/src/backend/ssh/transfer-routing.ts b/src/backend/ssh/transfer-routing.ts
new file mode 100644
index 000000000..eab1456c5
--- /dev/null
+++ b/src/backend/ssh/transfer-routing.ts
@@ -0,0 +1,193 @@
+import type { TransferPlatform } from "./transfer-paths.js";
+
+export type TransferMethodPreference = "auto" | "tar" | "item_sftp";
+
+export interface TransferScanSummary {
+ fileCount: number;
+ totalBytes: number;
+ largestFileBytes: number;
+ /** Share of total bytes in likely incompressible file types (0–1). */
+ incompressibleRatio: number;
+}
+
+const INCOMPRESSIBLE_EXT =
+ /\.(zip|gz|bz2|xz|7z|rar|tar|tgz|jpg|jpeg|png|gif|webp|mp3|mp4|mkv|avi|mov|wmv|iso|dmg|deb|rpm|pdf|db|sqlite|wasm|vmdk|qcow2)$/i;
+
+const GB = 1024 * 1024 * 1024;
+const MB = 1024 * 1024;
+
+export function isLikelyIncompressiblePath(path: string): boolean {
+ return INCOMPRESSIBLE_EXT.test(path);
+}
+
+export function buildTransferScanSummary(
+ items: Array<{ sourcePath: string; size: number }>,
+): TransferScanSummary {
+ let totalBytes = 0;
+ let largestFileBytes = 0;
+ let incompressibleBytes = 0;
+
+ for (const item of items) {
+ totalBytes += item.size;
+ largestFileBytes = Math.max(largestFileBytes, item.size);
+ if (isLikelyIncompressiblePath(item.sourcePath)) {
+ incompressibleBytes += item.size;
+ }
+ }
+
+ return {
+ fileCount: items.length,
+ totalBytes,
+ largestFileBytes,
+ incompressibleRatio: totalBytes > 0 ? incompressibleBytes / totalBytes : 0,
+ };
+}
+
+/**
+ * Choose tar vs per-item SFTP for directory / multi-file transfers.
+ * Single-file stream transfers bypass this entirely.
+ */
+export function resolveArchiveTransferMethod(
+ preference: TransferMethodPreference,
+ summary: TransferScanSummary,
+ sourcePlatform: TransferPlatform,
+ destPlatform: TransferPlatform,
+ sourceHasTar: boolean,
+ destHasTar: boolean,
+): "tar" | "item_sftp" {
+ if (sourcePlatform === "windows" || destPlatform === "windows") {
+ return "item_sftp";
+ }
+
+ if (preference === "item_sftp") {
+ return "item_sftp";
+ }
+
+ if (preference === "tar") {
+ return sourceHasTar && destHasTar ? "tar" : "item_sftp";
+ }
+
+ // auto
+ if (!sourceHasTar || !destHasTar) {
+ return "item_sftp";
+ }
+
+ const { fileCount, totalBytes, largestFileBytes, incompressibleRatio } =
+ summary;
+
+ if (fileCount === 0) {
+ return "item_sftp";
+ }
+
+ if (fileCount === 1 && largestFileBytes >= 2 * GB) {
+ return "item_sftp";
+ }
+
+ // Multi-item sets with a large file: tar only when data is likely compressible
+ // (mostly video/zip → per-file SFTP is simpler and avoids pack/unpack time).
+ if (
+ fileCount > 1 &&
+ largestFileBytes >= 2 * GB &&
+ totalBytes >= 500 * MB &&
+ incompressibleRatio < 0.7
+ ) {
+ return "tar";
+ }
+
+ if (fileCount === 1 && largestFileBytes >= 5 * GB) {
+ return "item_sftp";
+ }
+
+ if (totalBytes >= 10 * GB && incompressibleRatio >= 0.5) {
+ return "item_sftp";
+ }
+
+ if (incompressibleRatio >= 0.85) {
+ return "item_sftp";
+ }
+
+ if (fileCount >= 100) {
+ return "tar";
+ }
+
+ if (fileCount >= 20 && totalBytes >= 50 * MB && incompressibleRatio < 0.5) {
+ return "tar";
+ }
+
+ if (fileCount > 5 && incompressibleRatio < 0.7) {
+ return "tar";
+ }
+
+ return "item_sftp";
+}
+
+export type ArchiveTransferReasonKey =
+ | "user_item_sftp"
+ | "user_tar"
+ | "tar_unavailable"
+ | "windows_host"
+ | "auto_multi_large"
+ | "auto_single_large_in_archive"
+ | "auto_many_incompressible"
+ | "auto_many_files"
+ | "auto_default";
+
+/** i18n key suffix under transfer.methodReason.* */
+export function getArchiveTransferReasonKey(
+ preference: TransferMethodPreference,
+ resolvedMethod: "tar" | "item_sftp",
+ summary: TransferScanSummary,
+ sourcePlatform: TransferPlatform,
+ destPlatform: TransferPlatform,
+ sourceHasTar: boolean,
+ destHasTar: boolean,
+): ArchiveTransferReasonKey {
+ if (preference === "item_sftp") return "user_item_sftp";
+ if (preference === "tar") {
+ return sourceHasTar && destHasTar ? "user_tar" : "tar_unavailable";
+ }
+
+ if (sourcePlatform === "windows" || destPlatform === "windows") {
+ return "windows_host";
+ }
+ if (!sourceHasTar || !destHasTar) {
+ return "tar_unavailable";
+ }
+
+ const { fileCount, totalBytes, largestFileBytes, incompressibleRatio } =
+ summary;
+
+ if (
+ fileCount > 1 &&
+ largestFileBytes >= 2 * GB &&
+ totalBytes >= 500 * MB &&
+ incompressibleRatio < 0.7
+ ) {
+ return "auto_multi_large";
+ }
+
+ if (fileCount === 1 && largestFileBytes >= 2 * GB) {
+ return "auto_single_large_in_archive";
+ }
+
+ if (totalBytes >= 10 * GB && incompressibleRatio >= 0.5) {
+ return "auto_many_incompressible";
+ }
+ if (incompressibleRatio >= 0.85) {
+ return "auto_many_incompressible";
+ }
+
+ if (
+ fileCount >= 100 ||
+ (fileCount >= 20 && totalBytes >= 50 * MB && incompressibleRatio < 0.5) ||
+ (fileCount > 5 && incompressibleRatio < 0.7)
+ ) {
+ return "auto_many_files";
+ }
+
+ if (resolvedMethod === "tar") {
+ return "auto_many_files";
+ }
+
+ return "auto_default";
+}
diff --git a/src/backend/ssh/tunnel-c2s-relay-utils.ts b/src/backend/ssh/tunnel-c2s-relay-utils.ts
new file mode 100644
index 000000000..459c58237
--- /dev/null
+++ b/src/backend/ssh/tunnel-c2s-relay-utils.ts
@@ -0,0 +1,116 @@
+import type { IncomingMessage } from "http";
+import type { Duplex } from "stream";
+import type { ClientChannel } from "ssh2";
+import type { WebSocket } from "ws";
+
+const C2S_WS_HIGH_WATERMARK = 1024 * 1024;
+const C2S_WS_LOW_WATERMARK = 256 * 1024;
+const C2S_STREAM_WRITE_LIMIT = 8 * 1024 * 1024;
+
+export function extractRequestToken(req: IncomingMessage): string | undefined {
+ const cookieHeader = req.headers.cookie;
+ if (cookieHeader) {
+ const match = cookieHeader.match(/(?:^|;\s*)jwt=([^;]+)/);
+ if (match) return decodeURIComponent(match[1]);
+ }
+
+ const authHeader = req.headers.authorization;
+ if (authHeader?.startsWith("Bearer ")) {
+ return authHeader.slice("Bearer ".length);
+ }
+
+ return undefined;
+}
+
+export function sendC2SError(ws: WebSocket, message: string): void {
+ if (ws.readyState === 1) {
+ ws.send(JSON.stringify({ type: "error", error: message }));
+ }
+}
+
+export function describeC2SRelayError(error: unknown): string {
+ const message = error instanceof Error ? error.message : String(error);
+ const lowerMessage = message.toLowerCase();
+
+ if (
+ lowerMessage.includes("administratively prohibited") ||
+ lowerMessage.includes("forwarding disabled") ||
+ lowerMessage.includes("open failed")
+ ) {
+ return `SSH forwarding was rejected by the endpoint server: ${message}`;
+ }
+ if (
+ lowerMessage.includes("address already in use") ||
+ lowerMessage.includes("unable to bind") ||
+ lowerMessage.includes("bind")
+ ) {
+ return `Remote port is not available on the endpoint server: ${message}`;
+ }
+ if (
+ lowerMessage.includes("name or service not known") ||
+ lowerMessage.includes("enotfound") ||
+ lowerMessage.includes("econnrefused")
+ ) {
+ return `Tunnel target is not reachable from the endpoint host: ${message}`;
+ }
+
+ return message || "Failed to open relay";
+}
+
+function pauseSourceForC2SWebSocket(ws: WebSocket, source?: Duplex): void {
+ if (!source) return;
+ if (ws.bufferedAmount <= C2S_WS_HIGH_WATERMARK) return;
+
+ source.pause();
+ const resumeTimer = setInterval(() => {
+ if (
+ ws.readyState !== 1 ||
+ source.destroyed ||
+ ws.bufferedAmount <= C2S_WS_LOW_WATERMARK
+ ) {
+ clearInterval(resumeTimer);
+ if (ws.readyState === 1 && !source.destroyed) {
+ source.resume();
+ }
+ }
+ }, 25);
+}
+
+export function sendC2SMessage(
+ ws: WebSocket,
+ message: Record<string, unknown>,
+ source?: Duplex,
+): void {
+ if (ws.readyState === 1) {
+ ws.send(JSON.stringify(message), (error) => {
+ if (error && source && !source.destroyed) {
+ source.destroy(error);
+ }
+ });
+ pauseSourceForC2SWebSocket(ws, source);
+ }
+}
+
+export function writeC2SRemoteChunk(
+ target: ClientChannel,
+ chunk: Buffer,
+ ws: WebSocket,
+ closeTarget: () => void,
+): void {
+ if (!target || target.destroyed) return;
+
+ if (target.writableLength > C2S_STREAM_WRITE_LIMIT) {
+ closeTarget();
+ return;
+ }
+
+ const canContinue = target.write(chunk);
+ if (!canContinue) {
+ ws.pause();
+ target.once("drain", () => {
+ if (ws.readyState === 1) {
+ ws.resume();
+ }
+ });
+ }
+}
diff --git a/src/backend/ssh/tunnel-c2s-relay.ts b/src/backend/ssh/tunnel-c2s-relay.ts
new file mode 100644
index 000000000..af71f67c6
--- /dev/null
+++ b/src/backend/ssh/tunnel-c2s-relay.ts
@@ -0,0 +1,409 @@
+import { Client, type ClientChannel } from "ssh2";
+import type { WebSocket } from "ws";
+import type { TunnelConfig } from "../../types/index.js";
+import { createSocks5Connection } from "../utils/socks5-helper.js";
+import { tunnelLogger } from "../utils/logger.js";
+import { PermissionManager } from "../utils/permission-manager.js";
+import {
+ applyAuthOptions,
+ bindForwardIn,
+ connectClient,
+ forwardOut,
+ getManagedTunnelAlgorithms,
+ unbindForwardIn,
+} from "./tunnel-ssh-primitives.js";
+import {
+ sendC2SMessage,
+ writeC2SRemoteChunk,
+} from "./tunnel-c2s-relay-utils.js";
+import { getTunnelMode } from "./tunnel-utils.js";
+
+export type C2SOpenMessage = {
+ type: "open" | "test";
+ tunnelConfig?: Partial<TunnelConfig>;
+ targetHost?: string;
+ targetPort?: number;
+};
+
+const permissionManager = PermissionManager.getInstance();
+let c2sRemoteStreamCounter = 0;
+
+async function resolveC2STunnelSource(
+ tunnelConfig: Partial<TunnelConfig>,
+ userId: string,
+): Promise<TunnelConfig> {
+ if (!tunnelConfig.sourceHostId) {
+ throw new Error("Endpoint SSH host is required");
+ }
+
+ const accessInfo = await permissionManager.canAccessHost(
+ userId,
+ tunnelConfig.sourceHostId,
+ "read",
+ );
+ if (!accessInfo.hasAccess) {
+ throw new Error("Access denied to this host");
+ }
+
+ const { resolveHostById } = await import("./host-resolver.js");
+ const resolvedHost = await resolveHostById(tunnelConfig.sourceHostId, userId);
+ if (!resolvedHost) {
+ throw new Error("Endpoint SSH host not found");
+ }
+
+ return {
+ name: tunnelConfig.name || `c2s:${tunnelConfig.sourceHostId}`,
+ scope: "c2s",
+ mode: tunnelConfig.mode || "local",
+ tunnelType:
+ tunnelConfig.tunnelType ||
+ (tunnelConfig.mode === "remote" ? "remote" : "local"),
+ bindHost: tunnelConfig.bindHost,
+ targetHost: tunnelConfig.targetHost || "127.0.0.1",
+ sourceHostId: resolvedHost.id || tunnelConfig.sourceHostId,
+ tunnelIndex: tunnelConfig.tunnelIndex || 0,
+ requestingUserId: userId,
+ hostName:
+ resolvedHost.name || `${resolvedHost.username}@${resolvedHost.ip}`,
+ sourceIP: resolvedHost.ip,
+ sourceSSHPort: resolvedHost.port,
+ sourceUsername: resolvedHost.username,
+ sourcePassword: resolvedHost.password,
+ sourceAuthMethod: resolvedHost.authType,
+ sourceSSHKey: resolvedHost.key,
+ sourceKeyPassword: resolvedHost.keyPassword,
+ sourceKeyType: resolvedHost.keyType,
+ sourceCredentialId: resolvedHost.credentialId,
+ sourceUserId: resolvedHost.userId,
+ endpointIP: tunnelConfig.endpointIP || resolvedHost.ip,
+ endpointSSHPort: tunnelConfig.endpointSSHPort || resolvedHost.port,
+ endpointUsername: resolvedHost.username,
+ endpointHost:
+ tunnelConfig.endpointHost || resolvedHost.name || resolvedHost.ip,
+ endpointAuthMethod: resolvedHost.authType,
+ endpointSSHKey: resolvedHost.key,
+ endpointKeyPassword: resolvedHost.keyPassword,
+ endpointKeyType: resolvedHost.keyType,
+ endpointCredentialId: resolvedHost.credentialId,
+ endpointUserId: resolvedHost.userId,
+ sourcePort: Number(tunnelConfig.sourcePort) || 0,
+ endpointPort: Number(tunnelConfig.endpointPort) || 0,
+ maxRetries: Number(tunnelConfig.maxRetries) || 0,
+ retryInterval: Number(tunnelConfig.retryInterval) || 0,
+ autoStart: Boolean(tunnelConfig.autoStart),
+ isPinned: Boolean(resolvedHost.pin),
+ useSocks5: Boolean(resolvedHost.useSocks5),
+ socks5Host: resolvedHost.socks5Host,
+ socks5Port: resolvedHost.socks5Port,
+ socks5Username: resolvedHost.socks5Username,
+ socks5Password: resolvedHost.socks5Password,
+ socks5ProxyChain: resolvedHost.socks5ProxyChain,
+ keepaliveInterval:
+ typeof resolvedHost.terminalConfig?.keepaliveInterval === "number"
+ ? resolvedHost.terminalConfig.keepaliveInterval * 1000
+ : 60000,
+ keepaliveCountMax:
+ typeof resolvedHost.terminalConfig?.keepaliveCountMax === "number"
+ ? resolvedHost.terminalConfig.keepaliveCountMax
+ : 5,
+ };
+}
+
+async function connectC2SSourceClient(
+ tunnelConfig: TunnelConfig,
+): Promise<Client> {
+ const connOptions: Record<string, unknown> = {
+ host:
+ tunnelConfig.sourceIP?.replace(/^\[|\]$/g, "") || tunnelConfig.sourceIP,
+ port: tunnelConfig.sourceSSHPort,
+ username: tunnelConfig.sourceUsername,
+ tryKeyboard: true,
+ keepaliveInterval: tunnelConfig.keepaliveInterval ?? 30000,
+ keepaliveCountMax: tunnelConfig.keepaliveCountMax ?? 3,
+ readyTimeout: 60000,
+ tcpKeepAlive: true,
+ tcpKeepAliveInitialDelay: 30000,
+ algorithms: getManagedTunnelAlgorithms(),
+ };
+
+ applyAuthOptions(connOptions, {
+ password: tunnelConfig.sourcePassword,
+ sshKey: tunnelConfig.sourceSSHKey,
+ keyPassword: tunnelConfig.sourceKeyPassword,
+ keyType: tunnelConfig.sourceKeyType,
+ authMethod: tunnelConfig.sourceAuthMethod,
+ });
+
+ if (
+ tunnelConfig.useSocks5 &&
+ (tunnelConfig.socks5Host ||
+ (tunnelConfig.socks5ProxyChain &&
+ tunnelConfig.socks5ProxyChain.length > 0))
+ ) {
+ const socks5Socket = await createSocks5Connection(
+ tunnelConfig.sourceIP,
+ tunnelConfig.sourceSSHPort,
+ {
+ useSocks5: tunnelConfig.useSocks5,
+ socks5Host: tunnelConfig.socks5Host,
+ socks5Port: tunnelConfig.socks5Port,
+ socks5Username: tunnelConfig.socks5Username,
+ socks5Password: tunnelConfig.socks5Password,
+ socks5ProxyChain: tunnelConfig.socks5ProxyChain,
+ },
+ );
+ if (socks5Socket) {
+ connOptions.sock = socks5Socket;
+ }
+ }
+
+ return connectClient(connOptions, tunnelConfig.name, "source");
+}
+
+async function handleC2SRemoteRelayOpen(
+ ws: WebSocket,
+ tunnelConfig: TunnelConfig,
+): Promise<void> {
+ const tunnelName = tunnelConfig.name;
+ const sourceClient = await connectC2SSourceClient(tunnelConfig);
+ const bindHost = tunnelConfig.targetHost || "127.0.0.1";
+ const bindPort = Number(tunnelConfig.sourcePort);
+ let closed = false;
+
+ if (!Number.isInteger(bindPort) || bindPort < 1 || bindPort > 65535) {
+ throw new Error("Invalid remote port");
+ }
+
+ const actualPort = await bindForwardIn(sourceClient, bindHost, bindPort);
+ const streams = new Map<string, ClientChannel>();
+
+ const closeStream = (streamId: string): void => {
+ const stream = streams.get(streamId);
+ if (!stream) return;
+ streams.delete(streamId);
+ try {
+ stream.destroy();
+ } catch {
+ // expected during shutdown
+ }
+ };
+
+ const close = (): void => {
+ if (closed) return;
+ closed = true;
+ for (const streamId of streams.keys()) {
+ closeStream(streamId);
+ }
+ unbindForwardIn(sourceClient, bindHost, actualPort);
+ try {
+ sourceClient.end();
+ } catch {
+ // expected during shutdown
+ }
+ };
+
+ sourceClient.on("tcp connection", (info, accept, reject) => {
+ if (info.destPort !== actualPort) {
+ reject();
+ return;
+ }
+
+ const inbound = accept();
+ const streamId = `${Date.now()}-${++c2sRemoteStreamCounter}`;
+ streams.set(streamId, inbound);
+
+ sendC2SMessage(ws, { type: "connection", streamId });
+
+ inbound.on("data", (chunk) => {
+ sendC2SMessage(
+ ws,
+ {
+ type: "data",
+ streamId,
+ data: chunk.toString("base64"),
+ },
+ inbound,
+ );
+ });
+ inbound.on("close", () => {
+ streams.delete(streamId);
+ sendC2SMessage(ws, { type: "close", streamId });
+ });
+ inbound.on("error", (error) => {
+ streams.delete(streamId);
+ sendC2SMessage(ws, {
+ type: "close",
+ streamId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ });
+
+ ws.on("message", (data, isBinary) => {
+ if (isBinary) return;
+
+ try {
+ const message = JSON.parse(data.toString()) as {
+ type?: string;
+ streamId?: string;
+ data?: string;
+ };
+ if (!message.streamId) return;
+
+ if (message.type === "data" && message.data) {
+ const stream = streams.get(message.streamId);
+ if (stream) {
+ writeC2SRemoteChunk(
+ stream,
+ Buffer.from(message.data, "base64"),
+ ws,
+ () => closeStream(message.streamId as string),
+ );
+ }
+ } else if (message.type === "close") {
+ closeStream(message.streamId);
+ }
+ } catch (error) {
+ tunnelLogger.warn("Invalid C2S remote relay message", {
+ operation: "c2s_remote_relay_invalid_message",
+ tunnelName,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ });
+
+ ws.on("close", close);
+ ws.on("error", close);
+ sourceClient.on("close", () => {
+ if (ws.readyState === 1) ws.close();
+ });
+ sourceClient.on("error", (error) => {
+ sendC2SMessage(ws, {
+ type: "error",
+ error: error instanceof Error ? error.message : String(error),
+ });
+ if (ws.readyState === 1) ws.close();
+ });
+
+ tunnelLogger.info("C2S remote tunnel ready", {
+ operation: "c2s_remote_tunnel_ready",
+ tunnelName,
+ bindHost,
+ bindPort: actualPort,
+ endpointHost: tunnelConfig.endpointHost,
+ });
+ sendC2SMessage(ws, { type: "ready", bindHost, bindPort: actualPort });
+}
+
+export async function handleC2SRelayOpen(
+ ws: WebSocket,
+ message: C2SOpenMessage,
+ userId: string,
+): Promise<void> {
+ const tunnelConfig = await resolveC2STunnelSource(
+ message.tunnelConfig || {},
+ userId,
+ );
+ const mode = getTunnelMode(tunnelConfig);
+ if (mode === "remote") {
+ await handleC2SRemoteRelayOpen(ws, tunnelConfig);
+ return;
+ }
+
+ const targetHost =
+ mode === "dynamic"
+ ? message.targetHost
+ : tunnelConfig.targetHost || "127.0.0.1";
+ const targetPort =
+ mode === "dynamic"
+ ? Number(message.targetPort)
+ : Number(tunnelConfig.endpointPort);
+
+ if (!targetHost || !Number.isInteger(targetPort) || targetPort < 1) {
+ throw new Error("Invalid client tunnel target");
+ }
+
+ const sourceClient = await connectC2SSourceClient(tunnelConfig);
+ const outbound = await forwardOut(sourceClient, targetHost, targetPort);
+
+ const close = () => {
+ try {
+ outbound.destroy();
+ } catch {
+ // expected during shutdown
+ }
+ try {
+ sourceClient.end();
+ } catch {
+ // expected during shutdown
+ }
+ };
+
+ outbound.on("data", (chunk) => {
+ if (ws.readyState === 1) {
+ ws.send(chunk);
+ }
+ });
+ outbound.on("close", () => {
+ if (ws.readyState === 1) ws.close();
+ });
+ outbound.on("error", () => {
+ if (ws.readyState === 1) ws.close();
+ });
+ ws.on("close", close);
+ ws.on("error", close);
+ ws.on("message", (data, isBinary) => {
+ if (!isBinary) return;
+ const chunk = Buffer.isBuffer(data)
+ ? data
+ : Array.isArray(data)
+ ? Buffer.concat(data)
+ : Buffer.from(data);
+ outbound.write(chunk);
+ });
+
+ ws.send(JSON.stringify({ type: "ready" }));
+}
+
+export async function handleC2SRelayTest(
+ ws: WebSocket,
+ message: C2SOpenMessage,
+ userId: string,
+): Promise<void> {
+ const tunnelConfig = await resolveC2STunnelSource(
+ message.tunnelConfig || {},
+ userId,
+ );
+ const mode = getTunnelMode(tunnelConfig);
+ const sourceClient = await connectC2SSourceClient(tunnelConfig);
+
+ try {
+ if (mode === "remote") {
+ const bindHost = tunnelConfig.targetHost || "127.0.0.1";
+ const bindPort = Number(tunnelConfig.sourcePort);
+ if (!Number.isInteger(bindPort) || bindPort < 1 || bindPort > 65535) {
+ throw new Error("Invalid remote port");
+ }
+
+ const actualPort = await bindForwardIn(sourceClient, bindHost, bindPort);
+ unbindForwardIn(sourceClient, bindHost, actualPort);
+ } else if (mode === "local") {
+ const targetHost = tunnelConfig.targetHost || "127.0.0.1";
+ const targetPort = Number(tunnelConfig.endpointPort);
+ if (!Number.isInteger(targetPort) || targetPort < 1) {
+ throw new Error("Invalid remote target port");
+ }
+
+ const outbound = await forwardOut(sourceClient, targetHost, targetPort);
+ outbound.destroy();
+ }
+
+ sendC2SMessage(ws, { type: "ready" });
+ } finally {
+ try {
+ sourceClient.end();
+ } catch {
+ // expected during shutdown
+ }
+ }
+}
diff --git a/src/backend/ssh/tunnel-socks5-relay.ts b/src/backend/ssh/tunnel-socks5-relay.ts
new file mode 100644
index 000000000..fa6157455
--- /dev/null
+++ b/src/backend/ssh/tunnel-socks5-relay.ts
@@ -0,0 +1,106 @@
+import type { Duplex } from "stream";
+import { tunnelLogger } from "../utils/logger.js";
+
+function parseSocksAddress(buffer: Buffer): {
+ address: string;
+ port: number;
+ bytesRead: number;
+} | null {
+ if (buffer.length < 7 || buffer[0] !== 0x05 || buffer[1] !== 0x01) {
+ return null;
+ }
+
+ const addressType = buffer[3];
+ let offset = 4;
+ let address: string;
+
+ if (addressType === 0x01) {
+ if (buffer.length < offset + 4 + 2) return null;
+ address = Array.from(buffer.subarray(offset, offset + 4)).join(".");
+ offset += 4;
+ } else if (addressType === 0x03) {
+ const len = buffer[offset];
+ offset += 1;
+ if (buffer.length < offset + len + 2) return null;
+ address = buffer.subarray(offset, offset + len).toString("utf8");
+ offset += len;
+ } else if (addressType === 0x04) {
+ if (buffer.length < offset + 16 + 2) return null;
+ const parts: string[] = [];
+ for (let i = 0; i < 16; i += 2) {
+ parts.push(buffer.readUInt16BE(offset + i).toString(16));
+ }
+ address = parts.join(":");
+ offset += 16;
+ } else {
+ return null;
+ }
+
+ const port = buffer.readUInt16BE(offset);
+ return { address, port, bytesRead: offset + 2 };
+}
+
+export function handleSocks5Connect(
+ inbound: Duplex,
+ openOutbound: (host: string, port: number) => Promise<Duplex>,
+ tunnelName: string,
+): void {
+ let buffer = Buffer.alloc(0);
+ let stage: "greeting" | "connect" | "piping" = "greeting";
+
+ const fail = (code = 0x01) => {
+ if (!inbound.destroyed) {
+ inbound.write(Buffer.from([0x05, code, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
+ inbound.destroy();
+ }
+ };
+
+ const onData = (chunk: Buffer) => {
+ buffer = Buffer.concat([buffer, chunk]);
+
+ if (stage === "greeting") {
+ if (buffer.length < 2) return;
+ if (buffer[0] !== 0x05) {
+ fail(0x01);
+ return;
+ }
+ const methodsLength = buffer[1];
+ if (buffer.length < 2 + methodsLength) return;
+ inbound.write(Buffer.from([0x05, 0x00]));
+ buffer = buffer.subarray(2 + methodsLength);
+ stage = "connect";
+ }
+
+ if (stage === "connect") {
+ const parsed = parseSocksAddress(buffer);
+ if (!parsed) return;
+ stage = "piping";
+ inbound.off("data", onData);
+ const remainder = buffer.subarray(parsed.bytesRead);
+ openOutbound(parsed.address, parsed.port)
+ .then((outbound) => {
+ inbound.write(
+ Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]),
+ );
+ if (remainder.length > 0) {
+ outbound.write(remainder);
+ }
+ inbound.pipe(outbound).pipe(inbound);
+ inbound.on("error", () => outbound.destroy());
+ outbound.on("error", () => inbound.destroy());
+ })
+ .catch((error) => {
+ tunnelLogger.error("SOCKS5 tunnel connect failed", error, {
+ operation: "managed_tunnel_socks_connect_failed",
+ tunnelName,
+ targetHost: parsed.address,
+ targetPort: parsed.port,
+ });
+ fail(0x05);
+ });
+ }
+ };
+
+ inbound.on("data", onData);
+ inbound.on("error", () => inbound.destroy());
+}
diff --git a/src/backend/ssh/tunnel-ssh-primitives.ts b/src/backend/ssh/tunnel-ssh-primitives.ts
new file mode 100644
index 000000000..62b1bed03
--- /dev/null
+++ b/src/backend/ssh/tunnel-ssh-primitives.ts
@@ -0,0 +1,181 @@
+import { Client, type ClientChannel } from "ssh2";
+import type { Duplex } from "stream";
+import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
+import { tunnelLogger } from "../utils/logger.js";
+
+export function getManagedTunnelAlgorithms() {
+ return {
+ kex: [
+ "curve25519-sha256",
+ "ecdh-sha2-nistp521",
+ "ecdh-sha2-nistp384",
+ "ecdh-sha2-nistp256",
+ "diffie-hellman-group-exchange-sha256",
+ "diffie-hellman-group14-sha256",
+ "diffie-hellman-group14-sha1",
+ "diffie-hellman-group-exchange-sha1",
+ "diffie-hellman-group1-sha1",
+ ],
+ serverHostKey: [
+ "ssh-ed25519",
+ "ecdsa-sha2-nistp521",
+ "ecdsa-sha2-nistp384",
+ "ecdsa-sha2-nistp256",
+ "rsa-sha2-512",
+ "rsa-sha2-256",
+ "ssh-rsa",
+ "ssh-dss",
+ ],
+ cipher: SSH_ALGORITHMS.cipher,
+ hmac: [
+ "hmac-sha2-512",
+ "hmac-sha2-256",
+ "hmac-sha1",
+ "hmac-md5",
+ ],
+ compress: ["none", "[email protected]", "zlib"],
+ };
+}
+
+export function applyAuthOptions(
+ connOptions: Record<string, unknown>,
+ credentials: {
+ password?: string;
+ sshKey?: string;
+ keyPassword?: string;
+ keyType?: string;
+ authMethod?: string;
+ },
+): void {
+ if (credentials.authMethod === "key" && credentials.sshKey) {
+ const cleanKey = credentials.sshKey
+ .trim()
+ .replace(/\r\n/g, "\n")
+ .replace(/\r/g, "\n");
+ connOptions.privateKey = Buffer.from(cleanKey, "utf8");
+ if (credentials.keyPassword) {
+ connOptions.passphrase = credentials.keyPassword;
+ }
+ if (credentials.keyType && credentials.keyType !== "auto") {
+ connOptions.privateKeyType = credentials.keyType;
+ }
+ } else {
+ connOptions.password = credentials.password;
+ }
+}
+
+export function connectClient(
+ connOptions: Record<string, unknown>,
+ tunnelName: string,
+ role: "source" | "endpoint",
+): Promise<Client> {
+ return new Promise((resolve, reject) => {
+ const client = new Client();
+ let settled = false;
+ client.once("ready", () => {
+ settled = true;
+ resolve(client);
+ });
+ client.once("error", (error) => {
+ if (!settled) {
+ reject(error);
+ return;
+ }
+ tunnelLogger.error("Managed tunnel SSH client error", error, {
+ operation: "managed_tunnel_client_error",
+ tunnelName,
+ role,
+ });
+ });
+ client.connect(connOptions);
+ });
+}
+
+export function forwardOut(
+ client: Client,
+ targetHost: string,
+ targetPort: number,
+ tunnelName?: string,
+): Promise<ClientChannel> {
+ return new Promise((resolve, reject) => {
+ client.forwardOut("127.0.0.1", 0, targetHost, targetPort, (err, stream) => {
+ if (err) {
+ if (tunnelName) {
+ tunnelLogger.error("Managed tunnel forwardOut failed", err, {
+ operation: "managed_tunnel_forward_out_failed",
+ tunnelName,
+ targetHost,
+ targetPort,
+ });
+ }
+ reject(err);
+ return;
+ }
+ resolve(stream);
+ });
+ });
+}
+
+export function bindForwardIn(
+ client: Client,
+ bindHost: string,
+ bindPort: number,
+): Promise<number> {
+ return new Promise((resolve, reject) => {
+ client.forwardIn(bindHost, bindPort, (err, actualPort) => {
+ if (err) {
+ reject(err);
+ return;
+ }
+ resolve(actualPort || bindPort);
+ });
+ });
+}
+
+export function unbindForwardIn(
+ client: Client,
+ bindHost: string,
+ bindPort: number,
+): void {
+ try {
+ client.unforwardIn(bindHost, bindPort, (err) => {
+ if (err) {
+ tunnelLogger.warn("Failed to unbind managed tunnel listener", {
+ operation: "managed_tunnel_unforward_failed",
+ bindHost,
+ bindPort,
+ error: err.message,
+ });
+ }
+ });
+ } catch {
+ // The connection may already be gone.
+ }
+}
+
+export function pipeTunnelStreams(
+ inbound: Duplex,
+ outboundPromise: Promise<Duplex>,
+ tunnelName: string,
+): void {
+ outboundPromise
+ .then((outbound) => {
+ inbound.pipe(outbound).pipe(inbound);
+ inbound.on("error", () => outbound.destroy());
+ outbound.on("error", () => inbound.destroy());
+ })
+ .catch((error) => {
+ tunnelLogger.error(
+ "Failed to open managed tunnel outbound stream",
+ error,
+ {
+ operation: "managed_tunnel_outbound_failed",
+ tunnelName,
+ },
+ );
+ inbound.destroy();
+ });
+}
diff --git a/src/backend/ssh/tunnel-utils.ts b/src/backend/ssh/tunnel-utils.ts
new file mode 100644
index 000000000..1d8792722
--- /dev/null
+++ b/src/backend/ssh/tunnel-utils.ts
@@ -0,0 +1,131 @@
+import type { ErrorType, TunnelConfig } from "../../types/index.js";
+import { tunnelLogger } from "../utils/logger.js";
+
+export function classifyTunnelError(errorMessage: string): ErrorType {
+ if (!errorMessage) return "UNKNOWN";
+
+ const message = errorMessage.toLowerCase();
+
+ if (
+ message.includes("closed by remote host") ||
+ message.includes("connection reset by peer") ||
+ message.includes("connection refused") ||
+ message.includes("broken pipe")
+ ) {
+ return "NETWORK_ERROR";
+ }
+
+ if (
+ message.includes("authentication failed") ||
+ message.includes("permission denied") ||
+ message.includes("incorrect password")
+ ) {
+ return "AUTHENTICATION_FAILED";
+ }
+
+ if (
+ message.includes("connect etimedout") ||
+ message.includes("timeout") ||
+ message.includes("timed out") ||
+ message.includes("keepalive timeout")
+ ) {
+ return "TIMEOUT";
+ }
+
+ if (
+ message.includes("bind: address already in use") ||
+ message.includes("failed for listen port") ||
+ message.includes("port forwarding failed")
+ ) {
+ return "CONNECTION_FAILED";
+ }
+
+ if (message.includes("permission") || message.includes("access denied")) {
+ return "CONNECTION_FAILED";
+ }
+
+ return "UNKNOWN";
+}
+
+export function getTunnelMarker(tunnelName: string): string {
+ return `TUNNEL_MARKER_${tunnelName.replace(/[^a-zA-Z0-9]/g, "_")}`;
+}
+
+export function normalizeTunnelName(
+ hostId: number,
+ tunnelIndex: number,
+ displayName: string,
+ sourcePort: number,
+ endpointHost: string,
+ endpointPort: number,
+): string {
+ return `${hostId}::${tunnelIndex}::${displayName}::${sourcePort}::${endpointHost}::${endpointPort}`;
+}
+
+export function getTunnelMode(
+ tunnelConfig: TunnelConfig,
+): "local" | "remote" | "dynamic" {
+ return tunnelConfig.mode || tunnelConfig.tunnelType || "remote";
+}
+
+export function getTunnelScope(tunnelConfig: TunnelConfig): "s2s" | "c2s" {
+ return tunnelConfig.scope || "s2s";
+}
+
+export function getTunnelBindHost(tunnelConfig: TunnelConfig): string {
+ return tunnelConfig.bindHost || "127.0.0.1";
+}
+
+export function parseTunnelName(tunnelName: string): {
+ hostId?: number;
+ tunnelIndex?: number;
+ displayName: string;
+ sourcePort: string;
+ endpointHost: string;
+ endpointPort: string;
+ isLegacyFormat: boolean;
+} {
+ const parts = tunnelName.split("::");
+
+ if (parts.length === 6) {
+ return {
+ hostId: parseInt(parts[0]),
+ tunnelIndex: parseInt(parts[1]),
+ displayName: parts[2],
+ sourcePort: parts[3],
+ endpointHost: parts[4],
+ endpointPort: parts[5],
+ isLegacyFormat: false,
+ };
+ }
+
+ tunnelLogger.warn(`Legacy tunnel name format: ${tunnelName}`);
+
+ const legacyParts = tunnelName.split("_");
+ return {
+ displayName: legacyParts[0] || "unknown",
+ sourcePort: legacyParts[legacyParts.length - 3] || "0",
+ endpointHost: legacyParts[legacyParts.length - 2] || "unknown",
+ endpointPort: legacyParts[legacyParts.length - 1] || "0",
+ isLegacyFormat: true,
+ };
+}
+
+export function validateTunnelConfig(
+ tunnelName: string,
+ tunnelConfig: TunnelConfig,
+): boolean {
+ const parsed = parseTunnelName(tunnelName);
+
+ if (parsed.isLegacyFormat) {
+ return true;
+ }
+
+ return (
+ parsed.hostId === tunnelConfig.sourceHostId &&
+ parsed.tunnelIndex === tunnelConfig.tunnelIndex &&
+ String(parsed.sourcePort) === String(tunnelConfig.sourcePort) &&
+ parsed.endpointHost === tunnelConfig.endpointHost &&
+ String(parsed.endpointPort) === String(tunnelConfig.endpointPort)
+ );
+}
diff --git a/src/backend/ssh/tunnel.ts b/src/backend/ssh/tunnel.ts
index c197fae3b..a6ae3219a 100644
--- a/src/backend/ssh/tunnel.ts
+++ b/src/backend/ssh/tunnel.ts
@@ -1,12 +1,16 @@
import express, { type Response } from "express";
-import { createServer, type IncomingMessage } from "http";
+import { createServer } from "http";
+import {
+ createServer as createTcpServer,
+ Socket as TcpSocket,
+ type Server as TcpServer,
+} from "net";
import { createCorsMiddleware } from "../utils/cors-config.js";
import cookieParser from "cookie-parser";
import { Client, type ClientChannel } from "ssh2";
-import { WebSocketServer, type WebSocket } from "ws";
+import { WebSocketServer } from "ws";
import { SSH_ALGORITHMS } from "../utils/ssh-algorithms.js";
import { ChildProcess } from "child_process";
-import type { Duplex } from "stream";
import axios from "axios";
import { getDb } from "../database/db/index.js";
import { sshCredentials } from "../database/db/schema.js";
@@ -16,7 +20,6 @@ import type {
TunnelConfig,
TunnelStatus,
VerificationData,
- ErrorType,
AuthenticatedRequest,
} from "../../types/index.js";
import { CONNECTION_STATES } from "../../types/index.js";
@@ -28,6 +31,35 @@ import { createSocks5Connection } from "../utils/socks5-helper.js";
import { AuthManager } from "../utils/auth-manager.js";
import { PermissionManager } from "../utils/permission-manager.js";
import { withConnection } from "./ssh-connection-pool.js";
+import {
+ applyAuthOptions,
+ bindForwardIn,
+ connectClient,
+ forwardOut,
+ getManagedTunnelAlgorithms,
+ pipeTunnelStreams,
+ unbindForwardIn,
+} from "./tunnel-ssh-primitives.js";
+import {
+ classifyTunnelError,
+ getTunnelBindHost,
+ getTunnelMarker,
+ getTunnelMode,
+ getTunnelScope,
+ normalizeTunnelName,
+ validateTunnelConfig,
+} from "./tunnel-utils.js";
+import {
+ describeC2SRelayError,
+ extractRequestToken,
+ sendC2SError,
+} from "./tunnel-c2s-relay-utils.js";
+import {
+ handleC2SRelayOpen,
+ handleC2SRelayTest,
+ type C2SOpenMessage,
+} from "./tunnel-c2s-relay.js";
+import { handleSocks5Connect } from "./tunnel-socks5-relay.js";
const app = express();
app.use(createCorsMiddleware(["GET", "POST", "PUT", "DELETE", "OPTIONS"]));
@@ -54,16 +86,12 @@ const retryExhaustedTunnels = new Set<string>();
const cleanupInProgress = new Set<string>();
const tunnelConnecting = new Set<string>();
const lastTunnelErrors = new Map<string, string>();
-const lastTunnelErrorTypes = new Map<string, ErrorType>();
+const lastTunnelErrorTypes = new Map<string, TunnelStatus["errorType"]>();
const tunnelConfigs = new Map<string, TunnelConfig>();
const activeTunnelProcesses = new Map<string, ChildProcess>();
const pendingTunnelOperations = new Map<string, Promise<void>>();
const tunnelStatusClients = new Set<Response>();
-let c2sRemoteStreamCounter = 0;
-const C2S_WS_HIGH_WATERMARK = 1024 * 1024;
-const C2S_WS_LOW_WATERMARK = 256 * 1024;
-const C2S_STREAM_WRITE_LIMIT = 8 * 1024 * 1024;
type ActiveTunnelRuntime = {
sourceClient: Client;
@@ -71,68 +99,12 @@ type ActiveTunnelRuntime = {
bindClient?: Client;
bindHost?: string;
bindPort?: number;
+ tcpServer?: TcpServer;
close: () => void;
};
const activeTunnelRuntimes = new Map<string, ActiveTunnelRuntime>();
-type C2SOpenMessage = {
- type: "open" | "test";
- tunnelConfig?: Partial<TunnelConfig>;
- targetHost?: string;
- targetPort?: number;
-};
-
-function extractRequestToken(req: IncomingMessage): string | undefined {
- const cookieHeader = req.headers.cookie;
- if (cookieHeader) {
- const match = cookieHeader.match(/(?:^|;\s*)jwt=([^;]+)/);
- if (match) return decodeURIComponent(match[1]);
- }
-
- const authHeader = req.headers.authorization;
- if (authHeader?.startsWith("Bearer ")) {
- return authHeader.slice("Bearer ".length);
- }
-
- return undefined;
-}
-
-function sendC2SError(ws: WebSocket, message: string): void {
- if (ws.readyState === 1) {
- ws.send(JSON.stringify({ type: "error", error: message }));
- }
-}
-
-function describeC2SRelayError(error: unknown): string {
- const message = error instanceof Error ? error.message : String(error);
- const lowerMessage = message.toLowerCase();
-
- if (
- lowerMessage.includes("administratively prohibited") ||
- lowerMessage.includes("forwarding disabled") ||
- lowerMessage.includes("open failed")
- ) {
- return `SSH forwarding was rejected by the endpoint server: ${message}`;
- }
- if (
- lowerMessage.includes("address already in use") ||
- lowerMessage.includes("unable to bind") ||
- lowerMessage.includes("bind")
- ) {
- return `Remote port is not available on the endpoint server: ${message}`;
- }
- if (
- lowerMessage.includes("name or service not known") ||
- lowerMessage.includes("enotfound") ||
- lowerMessage.includes("econnrefused")
- ) {
- return `Tunnel target is not reachable from the endpoint host: ${message}`;
- }
-
- return message || "Failed to open relay";
-}
-
function broadcastTunnelStatus(tunnelName: string, status: TunnelStatus): void {
if (
status.status === CONNECTION_STATES.CONNECTED &&
@@ -203,121 +175,6 @@ function broadcastTunnelStatusSnapshot(): void {
}
}
-function classifyError(errorMessage: string): ErrorType {
- if (!errorMessage) return "UNKNOWN";
-
- const message = errorMessage.toLowerCase();
-
- if (
- message.includes("closed by remote host") ||
- message.includes("connection reset by peer") ||
- message.includes("connection refused") ||
- message.includes("broken pipe")
- ) {
- return "NETWORK_ERROR";
- }
-
- if (
- message.includes("authentication failed") ||
- message.includes("permission denied") ||
- message.includes("incorrect password")
- ) {
- return "AUTHENTICATION_FAILED";
- }
-
- if (
- message.includes("connect etimedout") ||
- message.includes("timeout") ||
- message.includes("timed out") ||
- message.includes("keepalive timeout")
- ) {
- return "TIMEOUT";
- }
-
- if (
- message.includes("bind: address already in use") ||
- message.includes("failed for listen port") ||
- message.includes("port forwarding failed")
- ) {
- return "CONNECTION_FAILED";
- }
-
- if (message.includes("permission") || message.includes("access denied")) {
- return "CONNECTION_FAILED";
- }
-
- return "UNKNOWN";
-}
-
-function getTunnelMarker(tunnelName: string) {
- return `TUNNEL_MARKER_${tunnelName.replace(/[^a-zA-Z0-9]/g, "_")}`;
-}
-
-function normalizeTunnelName(
- hostId: number,
- tunnelIndex: number,
- displayName: string,
- sourcePort: number,
- endpointHost: string,
- endpointPort: number,
-): string {
- return `${hostId}::${tunnelIndex}::${displayName}::${sourcePort}::${endpointHost}::${endpointPort}`;
-}
-
-function parseTunnelName(tunnelName: string): {
- hostId?: number;
- tunnelIndex?: number;
- displayName: string;
- sourcePort: string;
- endpointHost: string;
- endpointPort: string;
- isLegacyFormat: boolean;
-} {
- const parts = tunnelName.split("::");
-
- if (parts.length === 6) {
- return {
- hostId: parseInt(parts[0]),
- tunnelIndex: parseInt(parts[1]),
- displayName: parts[2],
- sourcePort: parts[3],
- endpointHost: parts[4],
- endpointPort: parts[5],
- isLegacyFormat: false,
- };
- }
-
- tunnelLogger.warn(`Legacy tunnel name format: ${tunnelName}`);
-
- const legacyParts = tunnelName.split("_");
- return {
- displayName: legacyParts[0] || "unknown",
- sourcePort: legacyParts[legacyParts.length - 3] || "0",
- endpointHost: legacyParts[legacyParts.length - 2] || "unknown",
- endpointPort: legacyParts[legacyParts.length - 1] || "0",
- isLegacyFormat: true,
- };
-}
-
-function validateTunnelConfig(
- tunnelName: string,
- tunnelConfig: TunnelConfig,
-): boolean {
- const parsed = parseTunnelName(tunnelName);
-
- if (parsed.isLegacyFormat) {
- return true;
- }
-
- return (
- parsed.hostId === tunnelConfig.sourceHostId &&
- parsed.tunnelIndex === tunnelConfig.tunnelIndex &&
- String(parsed.sourcePort) === String(tunnelConfig.sourcePort) &&
- parsed.endpointHost === tunnelConfig.endpointHost &&
- String(parsed.endpointPort) === String(tunnelConfig.endpointPort)
- );
-}
-
async function cleanupTunnelResources(
tunnelName: string,
forceCleanup = false,
@@ -627,301 +484,6 @@ function setupPingInterval(tunnelName: string): void {
verificationTimers.set(pingKey, pingInterval);
}
-function getTunnelMode(
- tunnelConfig: TunnelConfig,
-): "local" | "remote" | "dynamic" {
- return tunnelConfig.mode || tunnelConfig.tunnelType || "remote";
-}
-
-function getTunnelScope(tunnelConfig: TunnelConfig): "s2s" | "c2s" {
- return tunnelConfig.scope || "s2s";
-}
-
-function getTunnelBindHost(tunnelConfig: TunnelConfig): string {
- return tunnelConfig.bindHost || "127.0.0.1";
-}
-
-function getManagedTunnelAlgorithms() {
- return {
- kex: [
- "curve25519-sha256",
- "ecdh-sha2-nistp521",
- "ecdh-sha2-nistp384",
- "ecdh-sha2-nistp256",
- "diffie-hellman-group-exchange-sha256",
- "diffie-hellman-group14-sha256",
- "diffie-hellman-group14-sha1",
- "diffie-hellman-group-exchange-sha1",
- "diffie-hellman-group1-sha1",
- ],
- serverHostKey: [
- "ssh-ed25519",
- "ecdsa-sha2-nistp521",
- "ecdsa-sha2-nistp384",
- "ecdsa-sha2-nistp256",
- "rsa-sha2-512",
- "rsa-sha2-256",
- "ssh-rsa",
- "ssh-dss",
- ],
- cipher: SSH_ALGORITHMS.cipher,
- hmac: [
- "hmac-sha2-512",
- "hmac-sha2-256",
- "hmac-sha1",
- "hmac-md5",
- ],
- compress: ["none", "[email protected]", "zlib"],
- };
-}
-
-function applyAuthOptions(
- connOptions: Record<string, unknown>,
- credentials: {
- password?: string;
- sshKey?: string;
- keyPassword?: string;
- keyType?: string;
- authMethod?: string;
- },
-): void {
- if (credentials.authMethod === "key" && credentials.sshKey) {
- const cleanKey = credentials.sshKey
- .trim()
- .replace(/\r\n/g, "\n")
- .replace(/\r/g, "\n");
- connOptions.privateKey = Buffer.from(cleanKey, "utf8");
- if (credentials.keyPassword) {
- connOptions.passphrase = credentials.keyPassword;
- }
- if (credentials.keyType && credentials.keyType !== "auto") {
- connOptions.privateKeyType = credentials.keyType;
- }
- } else {
- connOptions.password = credentials.password;
- }
-}
-
-function connectClient(
- connOptions: Record<string, unknown>,
- tunnelName: string,
- role: "source" | "endpoint",
-): Promise<Client> {
- return new Promise((resolve, reject) => {
- const client = new Client();
- let settled = false;
- client.once("ready", () => {
- settled = true;
- resolve(client);
- });
- client.once("error", (error) => {
- if (!settled) {
- reject(error);
- return;
- }
- tunnelLogger.error("Managed tunnel SSH client error", error, {
- operation: "managed_tunnel_client_error",
- tunnelName,
- role,
- });
- });
- client.connect(connOptions);
- });
-}
-
-function forwardOut(
- client: Client,
- targetHost: string,
- targetPort: number,
- tunnelName?: string,
-): Promise<ClientChannel> {
- return new Promise((resolve, reject) => {
- client.forwardOut("127.0.0.1", 0, targetHost, targetPort, (err, stream) => {
- if (err) {
- if (tunnelName) {
- tunnelLogger.error("Managed tunnel forwardOut failed", err, {
- operation: "managed_tunnel_forward_out_failed",
- tunnelName,
- targetHost,
- targetPort,
- });
- }
- reject(err);
- return;
- }
- resolve(stream);
- });
- });
-}
-
-function bindForwardIn(
- client: Client,
- bindHost: string,
- bindPort: number,
-): Promise<number> {
- return new Promise((resolve, reject) => {
- client.forwardIn(bindHost, bindPort, (err, actualPort) => {
- if (err) {
- reject(err);
- return;
- }
- resolve(actualPort || bindPort);
- });
- });
-}
-
-function unbindForwardIn(
- client: Client,
- bindHost: string,
- bindPort: number,
-): void {
- try {
- client.unforwardIn(bindHost, bindPort, (err) => {
- if (err) {
- tunnelLogger.warn("Failed to unbind managed tunnel listener", {
- operation: "managed_tunnel_unforward_failed",
- bindHost,
- bindPort,
- error: err.message,
- });
- }
- });
- } catch {
- // The connection may already be gone.
- }
-}
-
-function pipeTunnelStreams(
- inbound: Duplex,
- outboundPromise: Promise<Duplex>,
- tunnelName: string,
-): void {
- outboundPromise
- .then((outbound) => {
- inbound.pipe(outbound).pipe(inbound);
- inbound.on("error", () => outbound.destroy());
- outbound.on("error", () => inbound.destroy());
- })
- .catch((error) => {
- tunnelLogger.error(
- "Failed to open managed tunnel outbound stream",
- error,
- {
- operation: "managed_tunnel_outbound_failed",
- tunnelName,
- },
- );
- inbound.destroy();
- });
-}
-
-function parseSocksAddress(buffer: Buffer): {
- address: string;
- port: number;
- bytesRead: number;
-} | null {
- if (buffer.length < 7 || buffer[0] !== 0x05 || buffer[1] !== 0x01) {
- return null;
- }
-
- const addressType = buffer[3];
- let offset = 4;
- let address: string;
-
- if (addressType === 0x01) {
- if (buffer.length < offset + 4 + 2) return null;
- address = Array.from(buffer.subarray(offset, offset + 4)).join(".");
- offset += 4;
- } else if (addressType === 0x03) {
- const len = buffer[offset];
- offset += 1;
- if (buffer.length < offset + len + 2) return null;
- address = buffer.subarray(offset, offset + len).toString("utf8");
- offset += len;
- } else if (addressType === 0x04) {
- if (buffer.length < offset + 16 + 2) return null;
- const parts: string[] = [];
- for (let i = 0; i < 16; i += 2) {
- parts.push(buffer.readUInt16BE(offset + i).toString(16));
- }
- address = parts.join(":");
- offset += 16;
- } else {
- return null;
- }
-
- const port = buffer.readUInt16BE(offset);
- return { address, port, bytesRead: offset + 2 };
-}
-
-function handleSocks5Connect(
- inbound: Duplex,
- openOutbound: (host: string, port: number) => Promise<Duplex>,
- tunnelName: string,
-): void {
- let buffer = Buffer.alloc(0);
- let stage: "greeting" | "connect" | "piping" = "greeting";
-
- const fail = (code = 0x01) => {
- if (!inbound.destroyed) {
- inbound.write(Buffer.from([0x05, code, 0x00, 0x01, 0, 0, 0, 0, 0, 0]));
- inbound.destroy();
- }
- };
-
- const onData = (chunk: Buffer) => {
- buffer = Buffer.concat([buffer, chunk]);
-
- if (stage === "greeting") {
- if (buffer.length < 2) return;
- if (buffer[0] !== 0x05) {
- fail(0x01);
- return;
- }
- const methodsLength = buffer[1];
- if (buffer.length < 2 + methodsLength) return;
- inbound.write(Buffer.from([0x05, 0x00]));
- buffer = buffer.subarray(2 + methodsLength);
- stage = "connect";
- }
-
- if (stage === "connect") {
- const parsed = parseSocksAddress(buffer);
- if (!parsed) return;
- stage = "piping";
- inbound.off("data", onData);
- const remainder = buffer.subarray(parsed.bytesRead);
- openOutbound(parsed.address, parsed.port)
- .then((outbound) => {
- inbound.write(
- Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]),
- );
- if (remainder.length > 0) {
- outbound.write(remainder);
- }
- inbound.pipe(outbound).pipe(inbound);
- inbound.on("error", () => outbound.destroy());
- outbound.on("error", () => inbound.destroy());
- })
- .catch((error) => {
- tunnelLogger.error("SOCKS5 tunnel connect failed", error, {
- operation: "managed_tunnel_socks_connect_failed",
- tunnelName,
- targetHost: parsed.address,
- targetPort: parsed.port,
- });
- fail(0x05);
- });
- }
- };
-
- inbound.on("data", onData);
- inbound.on("error", () => inbound.destroy());
-}
-
async function connectEndpointThroughSource(
sourceClient: Client,
tunnelConfig: TunnelConfig,
@@ -943,8 +505,8 @@ async function connectEndpointThroughSource(
sock: endpointSock,
username: tunnelConfig.endpointUsername,
tryKeyboard: true,
- keepaliveInterval: tunnelConfig.keepaliveInterval ?? 60000,
- keepaliveCountMax: tunnelConfig.keepaliveCountMax ?? 5,
+ keepaliveInterval: tunnelConfig.keepaliveInterval ?? 30000,
+ keepaliveCountMax: tunnelConfig.keepaliveCountMax ?? 3,
readyTimeout: 60000,
tcpKeepAlive: true,
tcpKeepAliveInitialDelay: 30000,
@@ -969,6 +531,150 @@ function resolveS2SLocalTargetHost(tunnelConfig: TunnelConfig): string {
return targetHost;
}
+function isSingleHostTunnel(tunnelConfig: TunnelConfig): boolean {
+ if (!tunnelConfig.endpointHost && !tunnelConfig.endpointIP) return true;
+ if (
+ tunnelConfig.endpointHost === "127.0.0.1" ||
+ tunnelConfig.endpointHost === "localhost"
+ ) {
+ return true;
+ }
+ if (
+ tunnelConfig.endpointIP &&
+ tunnelConfig.endpointIP === tunnelConfig.sourceIP &&
+ tunnelConfig.endpointSSHPort === tunnelConfig.sourceSSHPort
+ ) {
+ return true;
+ }
+ return false;
+}
+
+async function establishDirectTunnel(
+ sourceClient: Client,
+ tunnelConfig: TunnelConfig,
+): Promise<void> {
+ const tunnelName = tunnelConfig.name;
+ const mode = getTunnelMode(tunnelConfig);
+ const bindHost = getTunnelBindHost(tunnelConfig);
+ const sourcePort = tunnelConfig.sourcePort;
+ const targetHost = tunnelConfig.targetHost || "127.0.0.1";
+ const targetPort = tunnelConfig.endpointPort;
+
+ if (mode === "remote") {
+ const remoteBindPort = await bindForwardIn(
+ sourceClient,
+ targetHost,
+ sourcePort,
+ );
+ const sockets = new Set<TcpSocket>();
+ sourceClient.on("tcp connection", (info, accept, reject) => {
+ if (info.destPort !== remoteBindPort) {
+ reject();
+ return;
+ }
+ const inbound = accept();
+ const local = new TcpSocket();
+ sockets.add(local);
+ local.connect(targetPort, bindHost, () => {
+ pipeTunnelStreams(inbound, Promise.resolve(local), tunnelName);
+ });
+ local.on("error", () => {
+ inbound.destroy();
+ sockets.delete(local);
+ });
+ local.on("close", () => sockets.delete(local));
+ });
+
+ const close = () => {
+ unbindForwardIn(sourceClient, targetHost, remoteBindPort);
+ for (const s of sockets) s.destroy();
+ sockets.clear();
+ try {
+ sourceClient.end();
+ } catch {
+ // expected
+ }
+ };
+
+ activeTunnelRuntimes.set(tunnelName, {
+ sourceClient,
+ bindHost: targetHost,
+ bindPort: remoteBindPort,
+ close,
+ });
+ activeTunnels.set(tunnelName, sourceClient);
+ return;
+ }
+
+ // Local and dynamic modes: listen locally, forward through SSH
+ const sockets = new Set<TcpSocket>();
+ const tcpServer = createTcpServer((socket) => {
+ sockets.add(socket);
+ socket.on("close", () => sockets.delete(socket));
+ socket.on("error", () => {
+ sockets.delete(socket);
+ socket.destroy();
+ });
+
+ if (mode === "dynamic") {
+ handleSocks5Connect(
+ socket,
+ (host, port) => forwardOut(sourceClient, host, port),
+ tunnelName,
+ );
+ return;
+ }
+
+ forwardOut(sourceClient, targetHost, targetPort, tunnelName)
+ .then((outbound) =>
+ pipeTunnelStreams(socket, Promise.resolve(outbound), tunnelName),
+ )
+ .catch(() => socket.destroy());
+ });
+
+ await new Promise<void>((resolve, reject) => {
+ tcpServer.once("error", reject);
+ tcpServer.listen({ host: bindHost, port: sourcePort }, () => {
+ tcpServer.removeListener("error", reject);
+ resolve();
+ });
+ });
+
+ tunnelLogger.info("Direct tunnel listener started", {
+ operation: "direct_tunnel_listen",
+ tunnelName,
+ mode,
+ bindHost,
+ sourcePort,
+ targetHost,
+ targetPort,
+ });
+
+ const close = () => {
+ for (const s of sockets) s.destroy();
+ sockets.clear();
+ tcpServer.close();
+ try {
+ sourceClient.end();
+ } catch {
+ // expected
+ }
+ };
+
+ sourceClient.on("close", () => {
+ close();
+ });
+
+ activeTunnelRuntimes.set(tunnelName, {
+ sourceClient,
+ tcpServer,
+ bindHost,
+ bindPort: sourcePort,
+ close,
+ });
+ activeTunnels.set(tunnelName, sourceClient);
+}
+
async function establishManagedS2STunnel(
sourceClient: Client,
tunnelConfig: TunnelConfig,
@@ -1080,444 +786,6 @@ async function establishManagedS2STunnel(
activeTunnels.set(tunnelName, sourceClient);
}
-async function resolveC2STunnelSource(
- tunnelConfig: Partial<TunnelConfig>,
- userId: string,
-): Promise<TunnelConfig> {
- if (!tunnelConfig.sourceHostId) {
- throw new Error("Endpoint SSH host is required");
- }
-
- const accessInfo = await permissionManager.canAccessHost(
- userId,
- tunnelConfig.sourceHostId,
- "read",
- );
- if (!accessInfo.hasAccess) {
- throw new Error("Access denied to this host");
- }
-
- const { resolveHostById } = await import("./host-resolver.js");
- const resolvedHost = await resolveHostById(tunnelConfig.sourceHostId, userId);
- if (!resolvedHost) {
- throw new Error("Endpoint SSH host not found");
- }
-
- return {
- name: tunnelConfig.name || `c2s:${tunnelConfig.sourceHostId}`,
- scope: "c2s",
- mode: tunnelConfig.mode || "local",
- tunnelType:
- tunnelConfig.tunnelType ||
- (tunnelConfig.mode === "remote" ? "remote" : "local"),
- bindHost: tunnelConfig.bindHost,
- targetHost: tunnelConfig.targetHost || "127.0.0.1",
- sourceHostId: resolvedHost.id || tunnelConfig.sourceHostId,
- tunnelIndex: tunnelConfig.tunnelIndex || 0,
- requestingUserId: userId,
- hostName:
- resolvedHost.name || `${resolvedHost.username}@${resolvedHost.ip}`,
- sourceIP: resolvedHost.ip,
- sourceSSHPort: resolvedHost.port,
- sourceUsername: resolvedHost.username,
- sourcePassword: resolvedHost.password,
- sourceAuthMethod: resolvedHost.authType,
- sourceSSHKey: resolvedHost.key,
- sourceKeyPassword: resolvedHost.keyPassword,
- sourceKeyType: resolvedHost.keyType,
- sourceCredentialId: resolvedHost.credentialId,
- sourceUserId: resolvedHost.userId,
- endpointIP: tunnelConfig.endpointIP || resolvedHost.ip,
- endpointSSHPort: tunnelConfig.endpointSSHPort || resolvedHost.port,
- endpointUsername: resolvedHost.username,
- endpointHost:
- tunnelConfig.endpointHost || resolvedHost.name || resolvedHost.ip,
- endpointAuthMethod: resolvedHost.authType,
- endpointSSHKey: resolvedHost.key,
- endpointKeyPassword: resolvedHost.keyPassword,
- endpointKeyType: resolvedHost.keyType,
- endpointCredentialId: resolvedHost.credentialId,
- endpointUserId: resolvedHost.userId,
- sourcePort: Number(tunnelConfig.sourcePort) || 0,
- endpointPort: Number(tunnelConfig.endpointPort) || 0,
- maxRetries: Number(tunnelConfig.maxRetries) || 0,
- retryInterval: Number(tunnelConfig.retryInterval) || 0,
- autoStart: Boolean(tunnelConfig.autoStart),
- isPinned: Boolean(resolvedHost.pin),
- useSocks5: Boolean(resolvedHost.useSocks5),
- socks5Host: resolvedHost.socks5Host,
- socks5Port: resolvedHost.socks5Port,
- socks5Username: resolvedHost.socks5Username,
- socks5Password: resolvedHost.socks5Password,
- socks5ProxyChain: resolvedHost.socks5ProxyChain,
- keepaliveInterval:
- typeof resolvedHost.terminalConfig?.keepaliveInterval === "number"
- ? resolvedHost.terminalConfig.keepaliveInterval * 1000
- : 60000,
- keepaliveCountMax:
- typeof resolvedHost.terminalConfig?.keepaliveCountMax === "number"
- ? resolvedHost.terminalConfig.keepaliveCountMax
- : 5,
- };
-}
-
-async function connectC2SSourceClient(
- tunnelConfig: TunnelConfig,
-): Promise<Client> {
- const connOptions: Record<string, unknown> = {
- host:
- tunnelConfig.sourceIP?.replace(/^\[|\]$/g, "") || tunnelConfig.sourceIP,
- port: tunnelConfig.sourceSSHPort,
- username: tunnelConfig.sourceUsername,
- tryKeyboard: true,
- keepaliveInterval: tunnelConfig.keepaliveInterval ?? 60000,
- keepaliveCountMax: tunnelConfig.keepaliveCountMax ?? 5,
- readyTimeout: 60000,
- tcpKeepAlive: true,
- tcpKeepAliveInitialDelay: 30000,
- algorithms: getManagedTunnelAlgorithms(),
- };
-
- applyAuthOptions(connOptions, {
- password: tunnelConfig.sourcePassword,
- sshKey: tunnelConfig.sourceSSHKey,
- keyPassword: tunnelConfig.sourceKeyPassword,
- keyType: tunnelConfig.sourceKeyType,
- authMethod: tunnelConfig.sourceAuthMethod,
- });
-
- if (
- tunnelConfig.useSocks5 &&
- (tunnelConfig.socks5Host ||
- (tunnelConfig.socks5ProxyChain &&
- tunnelConfig.socks5ProxyChain.length > 0))
- ) {
- const socks5Socket = await createSocks5Connection(
- tunnelConfig.sourceIP,
- tunnelConfig.sourceSSHPort,
- {
- useSocks5: tunnelConfig.useSocks5,
- socks5Host: tunnelConfig.socks5Host,
- socks5Port: tunnelConfig.socks5Port,
- socks5Username: tunnelConfig.socks5Username,
- socks5Password: tunnelConfig.socks5Password,
- socks5ProxyChain: tunnelConfig.socks5ProxyChain,
- },
- );
- if (socks5Socket) {
- connOptions.sock = socks5Socket;
- }
- }
-
- return connectClient(connOptions, tunnelConfig.name, "source");
-}
-
-function pauseSourceForC2SWebSocket(ws: WebSocket, source?: Duplex): void {
- if (!source) return;
- if (ws.bufferedAmount <= C2S_WS_HIGH_WATERMARK) return;
-
- source.pause();
- const resumeTimer = setInterval(() => {
- if (
- ws.readyState !== 1 ||
- source.destroyed ||
- ws.bufferedAmount <= C2S_WS_LOW_WATERMARK
- ) {
- clearInterval(resumeTimer);
- if (ws.readyState === 1 && !source.destroyed) {
- source.resume();
- }
- }
- }, 25);
-}
-
-function sendC2SMessage(
- ws: WebSocket,
- message: Record<string, unknown>,
- source?: Duplex,
-): void {
- if (ws.readyState === 1) {
- ws.send(JSON.stringify(message), (error) => {
- if (error && source && !source.destroyed) {
- source.destroy(error);
- }
- });
- pauseSourceForC2SWebSocket(ws, source);
- }
-}
-
-function writeC2SRemoteChunk(
- target: ClientChannel,
- chunk: Buffer,
- ws: WebSocket,
- closeTarget: () => void,
-): void {
- if (!target || target.destroyed) return;
-
- if (target.writableLength > C2S_STREAM_WRITE_LIMIT) {
- closeTarget();
- return;
- }
-
- const canContinue = target.write(chunk);
- if (!canContinue) {
- ws.pause();
- target.once("drain", () => {
- if (ws.readyState === 1) {
- ws.resume();
- }
- });
- }
-}
-
-async function handleC2SRemoteRelayOpen(
- ws: WebSocket,
- tunnelConfig: TunnelConfig,
-): Promise<void> {
- const tunnelName = tunnelConfig.name;
- const sourceClient = await connectC2SSourceClient(tunnelConfig);
- const bindHost = tunnelConfig.targetHost || "127.0.0.1";
- const bindPort = Number(tunnelConfig.sourcePort);
- let closed = false;
-
- if (!Number.isInteger(bindPort) || bindPort < 1 || bindPort > 65535) {
- throw new Error("Invalid remote port");
- }
-
- const actualPort = await bindForwardIn(sourceClient, bindHost, bindPort);
- const streams = new Map<string, ClientChannel>();
-
- const closeStream = (streamId: string): void => {
- const stream = streams.get(streamId);
- if (!stream) return;
- streams.delete(streamId);
- try {
- stream.destroy();
- } catch {
- // expected during shutdown
- }
- };
-
- const close = (): void => {
- if (closed) return;
- closed = true;
- for (const streamId of streams.keys()) {
- closeStream(streamId);
- }
- unbindForwardIn(sourceClient, bindHost, actualPort);
- try {
- sourceClient.end();
- } catch {
- // expected during shutdown
- }
- };
-
- sourceClient.on("tcp connection", (info, accept, reject) => {
- if (info.destPort !== actualPort) {
- reject();
- return;
- }
-
- const inbound = accept();
- const streamId = `${Date.now()}-${++c2sRemoteStreamCounter}`;
- streams.set(streamId, inbound);
-
- sendC2SMessage(ws, { type: "connection", streamId });
-
- inbound.on("data", (chunk) => {
- sendC2SMessage(
- ws,
- {
- type: "data",
- streamId,
- data: chunk.toString("base64"),
- },
- inbound,
- );
- });
- inbound.on("close", () => {
- streams.delete(streamId);
- sendC2SMessage(ws, { type: "close", streamId });
- });
- inbound.on("error", (error) => {
- streams.delete(streamId);
- sendC2SMessage(ws, {
- type: "close",
- streamId,
- error: error instanceof Error ? error.message : String(error),
- });
- });
- });
-
- ws.on("message", (data, isBinary) => {
- if (isBinary) return;
-
- try {
- const message = JSON.parse(data.toString()) as {
- type?: string;
- streamId?: string;
- data?: string;
- };
- if (!message.streamId) return;
-
- if (message.type === "data" && message.data) {
- const stream = streams.get(message.streamId);
- if (stream) {
- writeC2SRemoteChunk(
- stream,
- Buffer.from(message.data, "base64"),
- ws,
- () => closeStream(message.streamId as string),
- );
- }
- } else if (message.type === "close") {
- closeStream(message.streamId);
- }
- } catch (error) {
- tunnelLogger.warn("Invalid C2S remote relay message", {
- operation: "c2s_remote_relay_invalid_message",
- tunnelName,
- error: error instanceof Error ? error.message : String(error),
- });
- }
- });
-
- ws.on("close", close);
- ws.on("error", close);
- sourceClient.on("close", () => {
- if (ws.readyState === 1) ws.close();
- });
- sourceClient.on("error", (error) => {
- sendC2SMessage(ws, {
- type: "error",
- error: error instanceof Error ? error.message : String(error),
- });
- if (ws.readyState === 1) ws.close();
- });
-
- tunnelLogger.info("C2S remote tunnel ready", {
- operation: "c2s_remote_tunnel_ready",
- tunnelName,
- bindHost,
- bindPort: actualPort,
- endpointHost: tunnelConfig.endpointHost,
- });
- sendC2SMessage(ws, { type: "ready", bindHost, bindPort: actualPort });
-}
-
-async function handleC2SRelayOpen(
- ws: WebSocket,
- message: C2SOpenMessage,
- userId: string,
-): Promise<void> {
- const tunnelConfig = await resolveC2STunnelSource(
- message.tunnelConfig || {},
- userId,
- );
- const mode = getTunnelMode(tunnelConfig);
- if (mode === "remote") {
- await handleC2SRemoteRelayOpen(ws, tunnelConfig);
- return;
- }
-
- const targetHost =
- mode === "dynamic"
- ? message.targetHost
- : tunnelConfig.targetHost || "127.0.0.1";
- const targetPort =
- mode === "dynamic"
- ? Number(message.targetPort)
- : Number(tunnelConfig.endpointPort);
-
- if (!targetHost || !Number.isInteger(targetPort) || targetPort < 1) {
- throw new Error("Invalid client tunnel target");
- }
-
- const sourceClient = await connectC2SSourceClient(tunnelConfig);
- const outbound = await forwardOut(sourceClient, targetHost, targetPort);
-
- const close = () => {
- try {
- outbound.destroy();
- } catch {
- // expected during shutdown
- }
- try {
- sourceClient.end();
- } catch {
- // expected during shutdown
- }
- };
-
- outbound.on("data", (chunk) => {
- if (ws.readyState === 1) {
- ws.send(chunk);
- }
- });
- outbound.on("close", () => {
- if (ws.readyState === 1) ws.close();
- });
- outbound.on("error", () => {
- if (ws.readyState === 1) ws.close();
- });
- ws.on("close", close);
- ws.on("error", close);
- ws.on("message", (data, isBinary) => {
- if (!isBinary) return;
- const chunk = Buffer.isBuffer(data)
- ? data
- : Array.isArray(data)
- ? Buffer.concat(data)
- : Buffer.from(data);
- outbound.write(chunk);
- });
-
- ws.send(JSON.stringify({ type: "ready" }));
-}
-
-async function handleC2SRelayTest(
- ws: WebSocket,
- message: C2SOpenMessage,
- userId: string,
-): Promise<void> {
- const tunnelConfig = await resolveC2STunnelSource(
- message.tunnelConfig || {},
- userId,
- );
- const mode = getTunnelMode(tunnelConfig);
- const sourceClient = await connectC2SSourceClient(tunnelConfig);
-
- try {
- if (mode === "remote") {
- const bindHost = tunnelConfig.targetHost || "127.0.0.1";
- const bindPort = Number(tunnelConfig.sourcePort);
- if (!Number.isInteger(bindPort) || bindPort < 1 || bindPort > 65535) {
- throw new Error("Invalid remote port");
- }
-
- const actualPort = await bindForwardIn(sourceClient, bindHost, bindPort);
- unbindForwardIn(sourceClient, bindHost, actualPort);
- } else if (mode === "local") {
- const targetHost = tunnelConfig.targetHost || "127.0.0.1";
- const targetPort = Number(tunnelConfig.endpointPort);
- if (!Number.isInteger(targetPort) || targetPort < 1) {
- throw new Error("Invalid remote target port");
- }
-
- const outbound = await forwardOut(sourceClient, targetHost, targetPort);
- outbound.destroy();
- }
-
- sendC2SMessage(ws, { type: "ready" });
- } finally {
- try {
- sourceClient.end();
- } catch {
- // expected during shutdown
- }
- }
-}
-
async function connectSSHTunnel(
tunnelConfig: TunnelConfig,
retryAttempt = 0,
@@ -1805,7 +1073,7 @@ async function connectSSHTunnel(
conn.on("error", (err) => {
clearTimeout(connectionTimeout);
- const errorType = classifyError(err.message);
+ const errorType = classifyTunnelError(err.message);
tunnelLogger.error(`Tunnel connection failed for '${tunnelName}'`, err, {
operation: "tunnel_connect_error",
@@ -1897,11 +1165,15 @@ async function connectSSHTunnel(
);
}
- await establishManagedS2STunnel(
- conn,
- tunnelConfig,
- resolvedEndpointCredentials,
- );
+ if (isSingleHostTunnel(tunnelConfig)) {
+ await establishDirectTunnel(conn, tunnelConfig);
+ } else {
+ await establishManagedS2STunnel(
+ conn,
+ tunnelConfig,
+ resolvedEndpointCredentials,
+ );
+ }
tunnelConnecting.delete(tunnelName);
tunnelLogger.success("Managed tunnel creation complete", {
@@ -1922,7 +1194,7 @@ async function connectSSHTunnel(
} catch (error) {
const message =
error instanceof Error ? error.message : "Failed to create tunnel";
- const errorType = classifyError(message);
+ const errorType = classifyTunnelError(message);
tunnelLogger.error("Failed to create managed tunnel", error, {
operation: "managed_tunnel_create_failed",
tunnelName,
@@ -1956,8 +1228,8 @@ async function connectSSHTunnel(
port: tunnelConfig.sourceSSHPort,
username: tunnelConfig.sourceUsername,
tryKeyboard: true,
- keepaliveInterval: tunnelConfig.keepaliveInterval ?? 60000,
- keepaliveCountMax: tunnelConfig.keepaliveCountMax ?? 5,
+ keepaliveInterval: tunnelConfig.keepaliveInterval ?? 30000,
+ keepaliveCountMax: tunnelConfig.keepaliveCountMax ?? 3,
readyTimeout: 60000,
tcpKeepAlive: true,
tcpKeepAliveInitialDelay: 30000,
@@ -2352,9 +1624,7 @@ async function killRemoteTunnelByMarker(
try {
await withConnection(poolKey, factory, async (client) => {
- const tunnelType = tunnelConfig.tunnelType || "remote";
- const tunnelFlag = tunnelType === "local" ? "-L" : "-R";
- const checkCmd = `ps aux | grep -E '(${tunnelMarker}|ssh.*${tunnelFlag}.*${tunnelConfig.endpointPort}:.*:${tunnelConfig.sourcePort}.*${tunnelConfig.endpointUsername}@${tunnelConfig.endpointIP}|sshpass.*ssh.*${tunnelFlag})' | grep -v grep`;
+ const checkCmd = `ps aux | grep -F '${tunnelMarker}' | grep -v grep`;
const checkOutput = await execCommand(client, checkCmd);
if (!checkOutput) {
@@ -2378,8 +1648,6 @@ async function killRemoteTunnelByMarker(
const killCmds = [
`pkill -TERM -f '${tunnelMarker}'`,
- `sleep 1 && pkill -f 'ssh.*${tunnelFlag}.*${tunnelConfig.endpointPort}:.*:${tunnelConfig.sourcePort}.*${tunnelConfig.endpointUsername}@${tunnelConfig.endpointIP}'`,
- `sleep 1 && pkill -f 'sshpass.*ssh.*${tunnelFlag}.*${tunnelConfig.endpointPort}'`,
`sleep 2 && pkill -9 -f '${tunnelMarker}'`,
];
@@ -2629,7 +1897,10 @@ app.post(
}
}
- if (!tunnelConfig.endpointIP || !tunnelConfig.endpointUsername) {
+ if (
+ !isSingleHostTunnel(tunnelConfig) &&
+ (!tunnelConfig.endpointIP || !tunnelConfig.endpointUsername)
+ ) {
try {
const systemCrypto = SystemCrypto.getInstance();
const internalAuthToken = await systemCrypto.getInternalAuthToken();
diff --git a/src/backend/ssh/widgets/common-utils.test.ts b/src/backend/ssh/widgets/common-utils.test.ts
new file mode 100644
index 000000000..f448b7810
--- /dev/null
+++ b/src/backend/ssh/widgets/common-utils.test.ts
@@ -0,0 +1,29 @@
+import { describe, it, expect } from "vitest";
+import { toFixedNum, kibToGiB } from "./common-utils.js";
+
+describe("toFixedNum", () => {
+ it("rounds to the requested digit count", () => {
+ expect(toFixedNum(3.14159, 2)).toBe(3.14);
+ expect(toFixedNum(3.14159, 0)).toBe(3);
+ expect(toFixedNum(2.5, 0)).toBe(3);
+ });
+
+ it("defaults to 2 digits", () => {
+ expect(toFixedNum(1.23456)).toBe(1.23);
+ });
+
+ it("returns null for non-finite or non-number input", () => {
+ expect(toFixedNum(null)).toBeNull();
+ expect(toFixedNum(undefined)).toBeNull();
+ expect(toFixedNum(NaN)).toBeNull();
+ expect(toFixedNum(Infinity)).toBeNull();
+ });
+});
+
+describe("kibToGiB", () => {
+ it("converts kibibytes to gibibytes", () => {
+ expect(kibToGiB(1024 * 1024)).toBe(1);
+ expect(kibToGiB(0)).toBe(0);
+ expect(kibToGiB(2 * 1024 * 1024)).toBe(2);
+ });
+});
diff --git a/src/backend/ssh/widgets/cpu-collector.test.ts b/src/backend/ssh/widgets/cpu-collector.test.ts
new file mode 100644
index 000000000..5af1d5a70
--- /dev/null
+++ b/src/backend/ssh/widgets/cpu-collector.test.ts
@@ -0,0 +1,29 @@
+import { describe, it, expect } from "vitest";
+import { parseCpuLine } from "./cpu-collector.js";
+
+describe("parseCpuLine", () => {
+ it("parses a standard /proc/stat cpu line", () => {
+ // user nice system idle iowait irq softirq
+ const result = parseCpuLine("cpu 100 0 50 800 30 0 20");
+ expect(result).toBeDefined();
+ // idle = idle(800) + iowait(30)
+ expect(result?.idle).toBe(830);
+ // total = sum of all fields
+ expect(result?.total).toBe(100 + 0 + 50 + 800 + 30 + 0 + 20);
+ });
+
+ it("tolerates leading/trailing whitespace", () => {
+ const result = parseCpuLine(" cpu 1 2 3 4 ");
+ expect(result?.total).toBe(10);
+ expect(result?.idle).toBe(4);
+ });
+
+ it("returns undefined for non-cpu lines", () => {
+ expect(parseCpuLine("cpu0 1 2 3 4")).toBeUndefined();
+ expect(parseCpuLine("intr 12345")).toBeUndefined();
+ });
+
+ it("returns undefined when there are fewer than 4 numeric fields", () => {
+ expect(parseCpuLine("cpu 1 2 3")).toBeUndefined();
+ });
+});
diff --git a/src/backend/ssh/widgets/cpu-collector.ts b/src/backend/ssh/widgets/cpu-collector.ts
index d1f59144b..87a6a96d6 100644
--- a/src/backend/ssh/widgets/cpu-collector.ts
+++ b/src/backend/ssh/widgets/cpu-collector.ts
@@ -1,7 +1,7 @@
import type { Client } from "ssh2";
import { execCommand, toFixedNum } from "./common-utils.js";
-function parseCpuLine(
+export function parseCpuLine(
cpuLine: string,
): { total: number; idle: number } | undefined {
const parts = cpuLine.trim().split(/\s+/);
diff --git a/src/backend/swagger.ts b/src/backend/swagger.ts
index c4088d46d..feb9221fb 100644
--- a/src/backend/swagger.ts
+++ b/src/backend/swagger.ts
@@ -1,13 +1,15 @@
-import swaggerJSDoc from "swagger-jsdoc";
+import swaggerJSDoc from "@deadendjs/swagger-jsdoc";
import path from "path";
import { fileURLToPath } from "url";
import { promises as fs } from "fs";
import { systemLogger } from "./utils/logger.js";
+type SwaggerJSDocOptions = Parameters<typeof swaggerJSDoc>[0];
+
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
-const swaggerOptions: swaggerJSDoc.Options = {
+const swaggerOptions: SwaggerJSDocOptions = {
definition: {
openapi: "3.0.3",
info: {
@@ -129,7 +131,7 @@ async function generateOpenAPISpec() {
operation: "openapi_generate_start",
});
- const swaggerSpec = swaggerJSDoc(swaggerOptions);
+ const swaggerSpec = await swaggerJSDoc(swaggerOptions);
const outputPath = path.join(__dirname, "..", "..", "..", "openapi.json");
diff --git a/src/backend/utils/database-file-encryption.test.ts b/src/backend/utils/database-file-encryption.test.ts
new file mode 100644
index 000000000..db8993b2d
Binary files /dev/null and b/src/backend/utils/database-file-encryption.test.ts differ
diff --git a/src/backend/utils/field-crypto.test.ts b/src/backend/utils/field-crypto.test.ts
new file mode 100644
index 000000000..f9c5cedd5
--- /dev/null
+++ b/src/backend/utils/field-crypto.test.ts
@@ -0,0 +1,93 @@
+import { describe, it, expect } from "vitest";
+import crypto from "crypto";
+import { FieldCrypto } from "./field-crypto.js";
+
+const masterKey = crypto.randomBytes(32);
+
+describe("FieldCrypto.encryptField / decryptField", () => {
+ it("round-trips a plaintext value", () => {
+ const encrypted = FieldCrypto.encryptField(
+ "s3cr3t-password",
+ masterKey,
+ "record-1",
+ "password",
+ );
+ const decrypted = FieldCrypto.decryptField(
+ encrypted,
+ masterKey,
+ "record-1",
+ "password",
+ );
+ expect(decrypted).toBe("s3cr3t-password");
+ });
+
+ it("returns empty string for empty input", () => {
+ expect(FieldCrypto.encryptField("", masterKey, "r", "f")).toBe("");
+ expect(FieldCrypto.decryptField("", masterKey, "r", "f")).toBe("");
+ });
+
+ it("produces different ciphertext each time (random IV + salt)", () => {
+ const a = FieldCrypto.encryptField("same", masterKey, "r", "f");
+ const b = FieldCrypto.encryptField("same", masterKey, "r", "f");
+ expect(a).not.toBe(b);
+ expect(FieldCrypto.decryptField(a, masterKey, "r", "f")).toBe("same");
+ expect(FieldCrypto.decryptField(b, masterKey, "r", "f")).toBe("same");
+ });
+
+ it("fails to decrypt with the wrong master key", () => {
+ const encrypted = FieldCrypto.encryptField("value", masterKey, "r", "f");
+ const wrongKey = crypto.randomBytes(32);
+ expect(() =>
+ FieldCrypto.decryptField(encrypted, wrongKey, "r", "f"),
+ ).toThrow();
+ });
+
+ it("fails to decrypt when the field name context differs", () => {
+ const encrypted = FieldCrypto.encryptField(
+ "value",
+ masterKey,
+ "r",
+ "password",
+ );
+ expect(() =>
+ FieldCrypto.decryptField(encrypted, masterKey, "r", "key"),
+ ).toThrow();
+ });
+
+ it("detects tampering with the ciphertext (GCM auth tag)", () => {
+ const encrypted = FieldCrypto.encryptField("value", masterKey, "r", "f");
+ const parsed = JSON.parse(encrypted);
+ // Flip a hex char in the encrypted data.
+ parsed.data = (parsed.data[0] === "a" ? "b" : "a") + parsed.data.slice(1);
+ const tampered = JSON.stringify(parsed);
+ expect(() =>
+ FieldCrypto.decryptField(tampered, masterKey, "r", "f"),
+ ).toThrow();
+ });
+
+ it("throws when the encrypted payload is missing recordId context", () => {
+ const encrypted = FieldCrypto.encryptField("value", masterKey, "r", "f");
+ const parsed = JSON.parse(encrypted);
+ delete parsed.recordId;
+ expect(() =>
+ FieldCrypto.decryptField(JSON.stringify(parsed), masterKey, "r", "f"),
+ ).toThrow(/recordId/);
+ });
+});
+
+describe("FieldCrypto.shouldEncryptField", () => {
+ it("identifies encrypted fields per table", () => {
+ expect(FieldCrypto.shouldEncryptField("users", "passwordHash")).toBe(true);
+ expect(FieldCrypto.shouldEncryptField("ssh_data", "password")).toBe(true);
+ expect(
+ FieldCrypto.shouldEncryptField("ssh_credentials", "privateKey"),
+ ).toBe(true);
+ });
+
+ it("returns false for non-encrypted fields and unknown tables", () => {
+ expect(FieldCrypto.shouldEncryptField("users", "username")).toBe(false);
+ expect(FieldCrypto.shouldEncryptField("unknown_table", "password")).toBe(
+ false,
+ );
+ });
+});
diff --git a/src/backend/utils/login-rate-limiter.test.ts b/src/backend/utils/login-rate-limiter.test.ts
new file mode 100644
index 000000000..9445b6633
--- /dev/null
+++ b/src/backend/utils/login-rate-limiter.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect, beforeEach } from "vitest";
+import { loginRateLimiter } from "./login-rate-limiter.js";
+
+// The limiter is a shared singleton, so each test uses unique ip/username keys
+// and resets them to stay isolated.
+describe("loginRateLimiter login attempts", () => {
+ let ip: string;
+ let username: string;
+ let counter = 0;
+
+ beforeEach(() => {
+ counter += 1;
+ ip = `10.0.0.${counter}`;
+ username = `user${counter}`;
+ loginRateLimiter.resetAttempts(ip, username);
+ });
+
+ it("starts unlocked with the full attempt budget", () => {
+ expect(loginRateLimiter.isLocked(ip, username).locked).toBe(false);
+ expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(5);
+ });
+
+ it("decrements remaining attempts on each failure", () => {
+ loginRateLimiter.recordFailedAttempt(ip, username);
+ expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(4);
+ loginRateLimiter.recordFailedAttempt(ip, username);
+ expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(3);
+ });
+
+ it("locks the account after 5 failed attempts", () => {
+ for (let i = 0; i < 5; i++) {
+ loginRateLimiter.recordFailedAttempt(ip, username);
+ }
+ const result = loginRateLimiter.isLocked(ip, username);
+ expect(result.locked).toBe(true);
+ expect(result.remainingTime).toBeGreaterThan(0);
+ expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(0);
+ });
+
+ it("clears the lock and counters on reset (successful login)", () => {
+ for (let i = 0; i < 5; i++) {
+ loginRateLimiter.recordFailedAttempt(ip, username);
+ }
+ expect(loginRateLimiter.isLocked(ip, username).locked).toBe(true);
+
+ loginRateLimiter.resetAttempts(ip, username);
+ expect(loginRateLimiter.isLocked(ip, username).locked).toBe(false);
+ expect(loginRateLimiter.getRemainingAttempts(ip, username)).toBe(5);
+ });
+
+ it("locks by IP even without a username", () => {
+ const soloIp = `192.168.1.${counter}`;
+ for (let i = 0; i < 5; i++) {
+ loginRateLimiter.recordFailedAttempt(soloIp);
+ }
+ expect(loginRateLimiter.isLocked(soloIp).locked).toBe(true);
+ loginRateLimiter.resetAttempts(soloIp);
+ });
+});
+
+describe("loginRateLimiter TOTP attempts", () => {
+ let userId: string;
+ let counter = 0;
+
+ beforeEach(() => {
+ counter += 1;
+ userId = `totp-user${counter}`;
+ loginRateLimiter.resetTOTPAttempts(userId);
+ });
+
+ it("locks TOTP after 5 failures and resets cleanly", () => {
+ expect(loginRateLimiter.isTOTPLocked(userId).locked).toBe(false);
+ for (let i = 0; i < 5; i++) {
+ loginRateLimiter.recordFailedTOTPAttempt(userId);
+ }
+ expect(loginRateLimiter.isTOTPLocked(userId).locked).toBe(true);
+ expect(loginRateLimiter.getRemainingTOTPAttempts(userId)).toBe(0);
+
+ loginRateLimiter.resetTOTPAttempts(userId);
+ expect(loginRateLimiter.isTOTPLocked(userId).locked).toBe(false);
+ expect(loginRateLimiter.getRemainingTOTPAttempts(userId)).toBe(5);
+ });
+});
+
+describe("loginRateLimiter password-reset-code attempts", () => {
+ let username: string;
+ let counter = 0;
+
+ beforeEach(() => {
+ counter += 1;
+ username = `reset-user${counter}`;
+ loginRateLimiter.resetResetCodeAttempts(username);
+ });
+
+ it("locks reset codes after 5 failures and resets cleanly", () => {
+ expect(loginRateLimiter.isResetCodeLocked(username).locked).toBe(false);
+ for (let i = 0; i < 5; i++) {
+ loginRateLimiter.recordResetCodeAttempt(username);
+ }
+ expect(loginRateLimiter.isResetCodeLocked(username).locked).toBe(true);
+
+ loginRateLimiter.resetResetCodeAttempts(username);
+ expect(loginRateLimiter.isResetCodeLocked(username).locked).toBe(false);
+ });
+});
diff --git a/src/backend/utils/permission-manager.test.ts b/src/backend/utils/permission-manager.test.ts
new file mode 100644
index 000000000..37a87aa84
--- /dev/null
+++ b/src/backend/utils/permission-manager.test.ts
@@ -0,0 +1,73 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+
+// permission-manager imports the side-effectful DB barrel and the logger at the
+// top level. Stub both so importing the module does not spin up the real
+// database / encryption stack. We then drive hasPermission via a spied
+// getUserPermissions so we test the wildcard-matching logic in isolation.
+vi.mock("../database/db/index.js", () => ({ db: {} }));
+vi.mock("./logger.js", () => ({
+ databaseLogger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ success: vi.fn(),
+ },
+}));
+
+const { PermissionManager } = await import("./permission-manager.js");
+
+type PermissionManagerInstance = ReturnType<
+ typeof PermissionManager.getInstance
+>;
+
+describe("PermissionManager.hasPermission wildcard matching", () => {
+ let manager: PermissionManagerInstance;
+
+ function withPermissions(permissions: string[]) {
+ vi.spyOn(manager, "getUserPermissions").mockResolvedValue(permissions);
+ }
+
+ beforeEach(() => {
+ manager = PermissionManager.getInstance();
+ vi.restoreAllMocks();
+ });
+
+ it("grants everything for the global wildcard '*'", async () => {
+ withPermissions(["*"]);
+ expect(await manager.hasPermission("u1", "hosts.read")).toBe(true);
+ expect(await manager.hasPermission("u1", "anything.at.all")).toBe(true);
+ });
+
+ it("grants an exact permission match", async () => {
+ withPermissions(["hosts.read", "hosts.write"]);
+ expect(await manager.hasPermission("u1", "hosts.read")).toBe(true);
+ });
+
+ it("grants via a prefix wildcard", async () => {
+ withPermissions(["hosts.*"]);
+ expect(await manager.hasPermission("u1", "hosts.read")).toBe(true);
+ expect(await manager.hasPermission("u1", "hosts.write")).toBe(true);
+ });
+
+ it("grants via a deep prefix wildcard", async () => {
+ withPermissions(["admin.users.*"]);
+ expect(await manager.hasPermission("u1", "admin.users.delete")).toBe(true);
+ });
+
+ it("denies when no exact or wildcard permission matches", async () => {
+ withPermissions(["hosts.read"]);
+ expect(await manager.hasPermission("u1", "hosts.write")).toBe(false);
+ expect(await manager.hasPermission("u1", "credentials.read")).toBe(false);
+ });
+
+ it("denies when the user has no permissions", async () => {
+ withPermissions([]);
+ expect(await manager.hasPermission("u1", "hosts.read")).toBe(false);
+ });
+
+ it("does not let a narrower wildcard grant a sibling branch", async () => {
+ withPermissions(["hosts.read.*"]);
+ expect(await manager.hasPermission("u1", "hosts.write")).toBe(false);
+ });
+});
diff --git a/src/backend/utils/proxy-helper.ts b/src/backend/utils/proxy-helper.ts
index 7c4a3aa51..a2d179593 100644
--- a/src/backend/utils/proxy-helper.ts
+++ b/src/backend/utils/proxy-helper.ts
@@ -1,9 +1,39 @@
import { SocksClient } from "socks";
import type { SocksClientOptions } from "socks";
import net from "net";
+import dns from "dns/promises";
import { sshLogger } from "./logger.js";
import type { ProxyNode } from "../../types/index.js";
+function isBlockedAddress(ip: string): boolean {
+ if (ip === "0.0.0.0" || ip === "::1" || ip === "::") return true;
+
+ const parts = ip.split(".").map(Number);
+ if (parts.length !== 4) return false;
+
+ if (parts[0] === 127) return true;
+ if (parts[0] === 10) return true;
+ if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
+ if (parts[0] === 192 && parts[1] === 168) return true;
+ if (parts[0] === 169 && parts[1] === 254) return true;
+
+ return false;
+}
+
+async function validateHost(host: string): Promise<void> {
+ if (net.isIP(host)) {
+ if (isBlockedAddress(host)) {
+ throw new Error("Proxy target address is not allowed");
+ }
+ return;
+ }
+
+ const { address } = await dns.lookup(host);
+ if (isBlockedAddress(address)) {
+ throw new Error("Proxy target address is not allowed");
+ }
+}
+
export interface SOCKS5Config {
useSocks5?: boolean;
socks5Host?: string;
@@ -289,6 +319,17 @@ export async function testProxyConnectivity(options: {
testTarget?: { host: string; port: number };
}): Promise<{ success: boolean; latencyMs: number }> {
const target = options.testTarget ?? { host: "google.com", port: 443 };
+
+ await validateHost(target.host);
+ if (options.singleProxy) {
+ await validateHost(options.singleProxy.host);
+ }
+ if (options.proxyChain) {
+ for (const node of options.proxyChain) {
+ await validateHost(node.host);
+ }
+ }
+
const start = Date.now();
let socket: net.Socket | null = null;
diff --git a/src/backend/utils/ssh-algorithms.ts b/src/backend/utils/ssh-algorithms.ts
index d13ed8b19..caece95f6 100644
--- a/src/backend/utils/ssh-algorithms.ts
+++ b/src/backend/utils/ssh-algorithms.ts
@@ -1,6 +1,8 @@
import crypto from "crypto";
+import { createRequire } from "module";
import type { ConnectConfig, CipherAlgorithm } from "ssh2";
+const nativeRequire = createRequire(import.meta.url);
const availableCiphers = new Set(crypto.getCiphers());
// Maps SSH cipher names to their OpenSSL equivalents
@@ -20,7 +22,7 @@ const SSH_CIPHER_SSL_NAME: Partial<Record<CipherAlgorithm, string>> = {
// Check if ssh2's native crypto binding is available (needed for chacha20-poly1305)
let ssh2BindingAvailable = false;
try {
- require("ssh2/lib/protocol/crypto/build/Release/sshcrypto.node");
+ nativeRequire("ssh2/lib/protocol/crypto/build/Release/sshcrypto.node");
ssh2BindingAvailable = true;
} catch {
try {
diff --git a/src/backend/utils/ssh-key-utils.test.ts b/src/backend/utils/ssh-key-utils.test.ts
new file mode 100644
index 000000000..a0418c967
--- /dev/null
+++ b/src/backend/utils/ssh-key-utils.test.ts
@@ -0,0 +1,116 @@
+import { describe, it, expect } from "vitest";
+import {
+ parseSSHKey,
+ parsePublicKey,
+ getFriendlyKeyTypeName,
+ validateKeyPair,
+} from "./ssh-key-utils.js";
+
+// A real OpenSSH ed25519 keypair generated solely for these tests. It grants no
+// access to anything and exists only so the ssh2 parsing path is exercised for
+// real rather than only via the text-fallback heuristics.
+const ED25519_PRIVATE = `-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
+QyNTUxOQAAACBR/hJLX7eMinS4wJMfG2gWSttUiuSLvqDwVYT53x0qewAAAJihJo4koSaO
+JAAAAAtzc2gtZWQyNTUxOQAAACBR/hJLX7eMinS4wJMfG2gWSttUiuSLvqDwVYT53x0qew
+AAAEDLo85Twyg0v6V1zsJaeRaxq9KPQXkqGY0HiJtVMzCXEFH+Ektft4yKdLjAkx8baBZK
+21SK5Iu+oPBVhPnfHSp7AAAAEHRlc3RAdGVybWl4LnRlc3QBAgMEBQ==
+-----END OPENSSH PRIVATE KEY-----`;
+
+const ED25519_PUBLIC =
+ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFH+Ektft4yKdLjAkx8baBZK21SK5Iu+oPBVhPnfHSp7 [email protected]";
+
+describe("parsePublicKey", () => {
+ it("detects ssh-ed25519 public keys", () => {
+ const info = parsePublicKey(ED25519_PUBLIC);
+ expect(info.keyType).toBe("ssh-ed25519");
+ expect(info.success).toBe(true);
+ });
+
+ it("detects ssh-rsa public keys", () => {
+ const info = parsePublicKey("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABFakeData");
+ expect(info.keyType).toBe("ssh-rsa");
+ expect(info.success).toBe(true);
+ });
+
+ it("detects ecdsa public keys", () => {
+ const info = parsePublicKey(
+ "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYData",
+ );
+ expect(info.keyType).toBe("ecdsa-sha2-nistp256");
+ });
+
+ it("detects OpenSSH certificate types before plain types", () => {
+ const info = parsePublicKey(
+ "[email protected] AAAAData comment",
+ );
+ expect(info.keyType).toBe("[email protected]");
+ });
+
+ it("returns unknown for unrecognized content", () => {
+ const info = parsePublicKey("not-a-key");
+ expect(info.keyType).toBe("unknown");
+ expect(info.success).toBe(false);
+ });
+});
+
+describe("parseSSHKey", () => {
+ it("parses a valid ed25519 private key and derives its type", () => {
+ const info = parseSSHKey(ED25519_PRIVATE);
+ expect(info.success).toBe(true);
+ expect(info.keyType).toContain("ed25519");
+ // ssh2 successfully derives the public key for a real OpenSSH key.
+ expect(info.publicKey).toContain("ssh-ed25519");
+ });
+
+ it("reports failure for garbage input", () => {
+ const info = parseSSHKey("definitely not a key");
+ expect(info.success).toBe(false);
+ expect(info.keyType).toBe("unknown");
+ });
+});
+
+describe("getFriendlyKeyTypeName", () => {
+ it("maps known key types to friendly names", () => {
+ expect(getFriendlyKeyTypeName("ssh-rsa")).toBe("RSA");
+ expect(getFriendlyKeyTypeName("ssh-ed25519")).toBe("Ed25519");
+ expect(getFriendlyKeyTypeName("ecdsa-sha2-nistp256")).toBe("ECDSA P-256");
+ expect(getFriendlyKeyTypeName("ssh-dss")).toBe("DSA");
+ });
+
+ it("passes unknown types through unchanged", () => {
+ expect(getFriendlyKeyTypeName("some-future-type")).toBe("some-future-type");
+ });
+});
+
+describe("validateKeyPair", () => {
+ it("validates a genuinely matching ed25519 key pair", () => {
+ const result = validateKeyPair(ED25519_PRIVATE, ED25519_PUBLIC);
+ expect(result.isValid).toBe(true);
+ expect(result.privateKeyType).toContain("ed25519");
+ expect(result.publicKeyType).toBe("ssh-ed25519");
+ });
+
+ it("fails when private and public key types mismatch", () => {
+ const result = validateKeyPair(
+ ED25519_PRIVATE,
+ "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABFakeData",
+ );
+ expect(result.isValid).toBe(false);
+ expect(result.error).toMatch(/mismatch|match/i);
+ });
+
+ it("fails when the public key is invalid", () => {
+ const result = validateKeyPair(ED25519_PRIVATE, "garbage");
+ expect(result.isValid).toBe(false);
+ });
+
+ it("fails when the private key is invalid", () => {
+ const result = validateKeyPair(
+ "garbage",
+ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAData",
+ );
+ expect(result.isValid).toBe(false);
+ expect(result.error).toMatch(/private key/i);
+ });
+});
diff --git a/src/backend/utils/user-agent-parser.test.ts b/src/backend/utils/user-agent-parser.test.ts
new file mode 100644
index 000000000..df84ac47f
--- /dev/null
+++ b/src/backend/utils/user-agent-parser.test.ts
@@ -0,0 +1,147 @@
+import { describe, it, expect } from "vitest";
+import type { Request } from "express";
+import {
+ detectPlatform,
+ parseUserAgent,
+ generateDeviceFingerprint,
+} from "./user-agent-parser.js";
+
+function reqWith(headers: Record<string, string>): Request {
+ return { headers } as unknown as Request;
+}
+
+describe("detectPlatform", () => {
+ it("detects desktop from the x-electron-app header", () => {
+ expect(detectPlatform(reqWith({ "x-electron-app": "true" }))).toBe(
+ "desktop",
+ );
+ });
+
+ it("detects desktop from a Termix-Desktop user agent", () => {
+ expect(
+ detectPlatform(reqWith({ "user-agent": "Termix-Desktop/1.0 (Windows)" })),
+ ).toBe("desktop");
+ });
+
+ it("detects mobile from a Termix-Mobile user agent", () => {
+ expect(
+ detectPlatform(reqWith({ "user-agent": "Termix-Mobile/Android 1.0" })),
+ ).toBe("mobile");
+ });
+
+ it("detects mobile phones/tablets", () => {
+ expect(
+ detectPlatform(reqWith({ "user-agent": "Mozilla/5.0 (iPhone; ...)" })),
+ ).toBe("mobile");
+ });
+
+ it("treats Android-on-desktop-OS as web", () => {
+ expect(
+ detectPlatform(
+ reqWith({ "user-agent": "Mozilla/5.0 (X11; Linux x86_64) Android" }),
+ ),
+ ).toBe("web");
+ });
+
+ it("defaults to web for a desktop browser", () => {
+ expect(
+ detectPlatform(
+ reqWith({
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0) Chrome/120.0",
+ }),
+ ),
+ ).toBe("web");
+ });
+});
+
+describe("parseUserAgent", () => {
+ it("parses a Chrome-on-Windows web client", () => {
+ const info = parseUserAgent(
+ reqWith({
+ "user-agent":
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.71 Safari/537.36",
+ }),
+ );
+ expect(info.type).toBe("web");
+ expect(info.browser).toBe("Chrome");
+ expect(info.version).toBe("120.0");
+ expect(info.os).toBe("Windows 10/11");
+ });
+
+ it("parses Edge distinctly from Chrome", () => {
+ const info = parseUserAgent(
+ reqWith({
+ "user-agent":
+ "Mozilla/5.0 (Windows NT 10.0) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0",
+ }),
+ );
+ expect(info.browser).toBe("Edge");
+ });
+
+ it("parses a Termix desktop user agent", () => {
+ const info = parseUserAgent(
+ reqWith({ "user-agent": "Termix-Desktop/2.3.1 (macOS; arm64)" }),
+ );
+ expect(info.type).toBe("desktop");
+ expect(info.browser).toBe("Termix Desktop");
+ expect(info.version).toBe("2.3.1");
+ expect(info.os).toBe("macOS");
+ });
+
+ it("parses an iOS mobile user agent", () => {
+ const info = parseUserAgent(
+ reqWith({ "user-agent": "Termix-Mobile/iOS1.5 (OS 17_2)" }),
+ );
+ expect(info.type).toBe("mobile");
+ expect(info.os).toContain("iOS");
+ });
+});
+
+describe("generateDeviceFingerprint", () => {
+ it("is stable across minor browser version bumps on web", () => {
+ const a = generateDeviceFingerprint({
+ type: "web",
+ browser: "Chrome",
+ version: "120.5",
+ os: "Windows 10/11",
+ deviceInfo: "Chrome 120.5 on Windows 10/11",
+ });
+ const b = generateDeviceFingerprint({
+ type: "web",
+ browser: "Chrome",
+ version: "120.9",
+ os: "Windows 10/11",
+ deviceInfo: "Chrome 120.9 on Windows 10/11",
+ });
+ expect(a).toBe(b);
+ });
+
+ it("differs across major browser versions on web", () => {
+ const a = generateDeviceFingerprint({
+ type: "web",
+ browser: "Chrome",
+ version: "120.0",
+ os: "Windows 10/11",
+ deviceInfo: "",
+ });
+ const b = generateDeviceFingerprint({
+ type: "web",
+ browser: "Chrome",
+ version: "121.0",
+ os: "Windows 10/11",
+ deviceInfo: "",
+ });
+ expect(a).not.toBe(b);
+ });
+
+ it("produces a 64-char hex sha256 digest", () => {
+ const fp = generateDeviceFingerprint({
+ type: "desktop",
+ browser: "Termix Desktop",
+ version: "2.3.1",
+ os: "macOS",
+ deviceInfo: "",
+ });
+ expect(fp).toMatch(/^[0-9a-f]{64}$/);
+ });
+});
diff --git a/src/backend/utils/user-data-export.ts b/src/backend/utils/user-data-export.ts
index c19a3266f..c0b51f365 100644
--- a/src/backend/utils/user-data-export.ts
+++ b/src/backend/utils/user-data-export.ts
@@ -6,6 +6,7 @@ import {
fileManagerRecent,
fileManagerPinned,
fileManagerShortcuts,
+ transferRecent,
dismissedAlerts,
} from "../database/db/schema.js";
import { eq } from "drizzle-orm";
@@ -24,6 +25,7 @@ interface UserExportData {
recent: unknown[];
pinned: unknown[];
shortcuts: unknown[];
+ transferRecent: unknown[];
};
dismissedAlerts: unknown[];
};
@@ -102,20 +104,25 @@ class UserDataExport {
: credentials;
}
- const [recentFiles, pinnedFiles, shortcuts] = await Promise.all([
- getDb()
- .select()
- .from(fileManagerRecent)
- .where(eq(fileManagerRecent.userId, userId)),
- getDb()
- .select()
- .from(fileManagerPinned)
- .where(eq(fileManagerPinned.userId, userId)),
- getDb()
- .select()
- .from(fileManagerShortcuts)
- .where(eq(fileManagerShortcuts.userId, userId)),
- ]);
+ const [recentFiles, pinnedFiles, shortcuts, transferRecentData] =
+ await Promise.all([
+ getDb()
+ .select()
+ .from(fileManagerRecent)
+ .where(eq(fileManagerRecent.userId, userId)),
+ getDb()
+ .select()
+ .from(fileManagerPinned)
+ .where(eq(fileManagerPinned.userId, userId)),
+ getDb()
+ .select()
+ .from(fileManagerShortcuts)
+ .where(eq(fileManagerShortcuts.userId, userId)),
+ getDb()
+ .select()
+ .from(transferRecent)
+ .where(eq(transferRecent.userId, userId)),
+ ]);
const alerts = await getDb()
.select()
@@ -134,6 +141,7 @@ class UserDataExport {
recent: recentFiles,
pinned: pinnedFiles,
shortcuts: shortcuts,
+ transferRecent: transferRecentData,
},
dismissedAlerts: alerts,
},
@@ -144,6 +152,7 @@ class UserDataExport {
recentFiles.length +
pinnedFiles.length +
shortcuts.length +
+ transferRecentData.length +
alerts.length,
encrypted: format === "encrypted",
exportType: scope,
diff --git a/src/backend/utils/wake-on-lan.test.ts b/src/backend/utils/wake-on-lan.test.ts
new file mode 100644
index 000000000..0a53ced41
--- /dev/null
+++ b/src/backend/utils/wake-on-lan.test.ts
@@ -0,0 +1,51 @@
+import { describe, it, expect } from "vitest";
+import { isValidMac, buildMagicPacket } from "./wake-on-lan.js";
+
+describe("isValidMac", () => {
+ it("accepts colon-separated MAC addresses", () => {
+ expect(isValidMac("01:23:45:67:89:AB")).toBe(true);
+ expect(isValidMac("aa:bb:cc:dd:ee:ff")).toBe(true);
+ });
+
+ it("accepts hyphen-separated MAC addresses", () => {
+ expect(isValidMac("01-23-45-67-89-AB")).toBe(true);
+ });
+
+ it("rejects malformed MAC addresses", () => {
+ expect(isValidMac("")).toBe(false);
+ expect(isValidMac("01:23:45:67:89")).toBe(false);
+ expect(isValidMac("01:23:45:67:89:AB:CD")).toBe(false);
+ expect(isValidMac("0123456789AB")).toBe(false);
+ expect(isValidMac("zz:23:45:67:89:ab")).toBe(false);
+ expect(isValidMac("01:23:45:67:89:AB ")).toBe(false);
+ });
+});
+
+describe("buildMagicPacket", () => {
+ it("produces a 102-byte packet", () => {
+ const packet = buildMagicPacket("01:23:45:67:89:AB");
+ expect(packet.length).toBe(102);
+ });
+
+ it("starts with six 0xFF bytes", () => {
+ const packet = buildMagicPacket("01:23:45:67:89:AB");
+ expect([...packet.subarray(0, 6)]).toEqual([
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ ]);
+ });
+
+ it("repeats the MAC bytes 16 times after the header", () => {
+ const packet = buildMagicPacket("01:23:45:67:89:AB");
+ const mac = Buffer.from([0x01, 0x23, 0x45, 0x67, 0x89, 0xab]);
+ for (let i = 0; i < 16; i++) {
+ const offset = 6 + i * 6;
+ expect([...packet.subarray(offset, offset + 6)]).toEqual([...mac]);
+ }
+ });
+
+ it("treats colon and hyphen separators identically", () => {
+ const colon = buildMagicPacket("aa:bb:cc:dd:ee:ff");
+ const hyphen = buildMagicPacket("aa-bb-cc-dd-ee-ff");
+ expect(colon.equals(hyphen)).toBe(true);
+ });
+});
diff --git a/src/backend/utils/wake-on-lan.ts b/src/backend/utils/wake-on-lan.ts
index 2697b35ec..69b98659d 100644
--- a/src/backend/utils/wake-on-lan.ts
+++ b/src/backend/utils/wake-on-lan.ts
@@ -6,7 +6,7 @@ function parseMac(mac: string): Buffer {
return Buffer.from(mac.replace(/[:-]/g, ""), "hex");
}
-function buildMagicPacket(mac: string): Buffer {
+export function buildMagicPacket(mac: string): Buffer {
const macBytes = parseMac(mac);
const packet = Buffer.alloc(102);
packet.fill(0xff, 0, 6);
diff --git a/src/main.tsx b/src/main.tsx
index ee4b9bc17..3609930ea 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -19,16 +19,32 @@ const AppShell = lazy(() =>
);
// Full-screen apps opened via query params (e.g. from external links or Electron)
-const TerminalApp = lazy(() => import("@/features/terminal/TerminalApp"));
-const FileManagerApp = lazy(
- () => import("@/features/file-manager/FileManagerApp"),
+const TerminalApp = lazy(() =>
+ import("@/features/terminal/TerminalApp").then((m) => ({
+ default: m.default,
+ })),
+);
+const FileManagerApp = lazy(() =>
+ import("@/features/file-manager/FileManagerApp").then((m) => ({
+ default: m.default,
+ })),
+);
+const TunnelApp = lazy(() =>
+ import("@/features/tunnel/TunnelApp").then((m) => ({ default: m.default })),
+);
+const ServerStatsApp = lazy(() =>
+ import("@/features/server-stats/ServerStatsApp").then((m) => ({
+ default: m.default,
+ })),
+);
+const DockerApp = lazy(() =>
+ import("@/features/docker/DockerApp").then((m) => ({ default: m.default })),
);
-const TunnelApp = lazy(() => import("@/features/tunnel/TunnelApp"));
-const ServerStatsApp = lazy(
- () => import("@/features/server-stats/ServerStatsApp"),
+const GuacamoleApp = lazy(() =>
+ import("@/features/guacamole/GuacamoleApp").then((m) => ({
+ default: m.default,
+ })),
);
-const DockerApp = lazy(() => import("@/features/docker/DockerApp"));
-const GuacamoleApp = lazy(() => import("@/features/guacamole/GuacamoleApp"));
const ElectronVersionCheck = lazy(() =>
import("@/user/ElectronVersionCheck").then((module) => ({
@@ -43,47 +59,6 @@ type Phase =
| "idle-app"
| "fading-out";
-function useWindowWidth() {
- const [width, setWidth] = useState(window.innerWidth);
- const lastSwitchTime = useRef(0);
- const isCurrentlyMobile = useRef(window.innerWidth < 768);
- const hasSwitchedOnce = useRef(false);
-
- useEffect(() => {
- let timeoutId: number;
- const handleResize = () => {
- clearTimeout(timeoutId);
- timeoutId = setTimeout(() => {
- const newWidth = window.innerWidth;
- const newIsMobile = newWidth < 768;
- const now = Date.now();
- if (hasSwitchedOnce.current && now - lastSwitchTime.current < 10000) {
- setWidth(newWidth);
- return;
- }
- if (
- newIsMobile !== isCurrentlyMobile.current &&
- now - lastSwitchTime.current > 5000
- ) {
- lastSwitchTime.current = now;
- isCurrentlyMobile.current = newIsMobile;
- hasSwitchedOnce.current = true;
- setWidth(newWidth);
- } else {
- setWidth(newWidth);
- }
- }, 2000);
- };
- window.addEventListener("resize", handleResize);
- return () => {
- clearTimeout(timeoutId);
- window.removeEventListener("resize", handleResize);
- };
- }, []);
-
- return width;
-}
-
function FullscreenApp() {
const searchParams = new URLSearchParams(window.location.search);
const view = searchParams.get("view");
@@ -238,18 +213,10 @@ function App() {
}
function RootApp() {
- const width = useWindowWidth();
- const isMobile = width < 768;
const [showVersionCheck, setShowVersionCheck] = useState(true);
useServiceWorker();
- const userAgent =
- navigator.userAgent ||
- navigator.vendor ||
- (window as Window & { opera?: string }).opera ||
- "";
- const isTermixMobile = /Termix-Mobile/.test(userAgent);
const searchParams = new URLSearchParams(window.location.search);
const isFullscreen = searchParams.has("view");
diff --git a/src/types/electron.d.ts b/src/types/electron.d.ts
index 54a1d6bdf..23785dfd3 100644
--- a/src/types/electron.d.ts
+++ b/src/types/electron.d.ts
@@ -1,5 +1,6 @@
interface ServerConfig {
serverUrl?: string;
+ allowInvalidCertificate?: boolean;
[key: string]: unknown;
}
@@ -128,6 +129,7 @@ declare global {
interface Window {
electronAPI: ElectronAPI;
IS_ELECTRON: boolean;
+ configuredServerUrl?: string | null;
electronClipboard?: {
writeText(text: string): Promise<boolean>;
readText(): Promise<string>;
diff --git a/src/types/ui-types.ts b/src/types/ui-types.ts
index ac28b91ba..9baf393c8 100644
--- a/src/types/ui-types.ts
+++ b/src/types/ui-types.ts
@@ -14,6 +14,9 @@ export type Host = {
credentialId?: string;
overrideCredentialUsername?: boolean;
password?: string;
+ hasPassword?: boolean;
+ sudoPassword?: string;
+ hasSudoPassword?: boolean;
hasKey?: boolean;
hasKeyPassword?: boolean;
key?: string;
@@ -121,7 +124,7 @@ export type Host = {
telnetUser?: string;
telnetPassword?: string;
- guacamoleConfig?: Record<string, any>;
+ guacamoleConfig?: Record<string, unknown>;
forceKeyboardInteractive?: boolean;
};
@@ -191,6 +194,8 @@ export type Tab = {
terminalRef?: import("react").RefObject<{
sendInput?: (data: string) => void;
reconnect?: () => void;
+ fit?: () => void;
+ notifyResize?: () => void;
} | null>;
};
diff --git a/src/ui/AppShell.tsx b/src/ui/AppShell.tsx
index e8b0d7f46..83c488366 100644
--- a/src/ui/AppShell.tsx
+++ b/src/ui/AppShell.tsx
@@ -1,3 +1,5 @@
+/* eslint-disable react-refresh/only-export-components */
+/* eslint-disable react-hooks/exhaustive-deps */
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { Separator } from "@/components/separator";
@@ -29,8 +31,11 @@ import type {
Host,
SplitMode,
HostFolder,
+ ThemeId,
+ FontSizeId,
} from "@/types/ui-types";
-import { PANE_COUNTS } from "@/lib/theme";
+import { applyAccentColor, applyFontSize, PANE_COUNTS } from "@/lib/theme";
+import { useTheme } from "@/components/theme-provider";
import {
getSSHHosts,
getUserInfo,
@@ -46,6 +51,7 @@ import {
import { dbHealthMonitor } from "@/lib/db-health-monitor";
import type { SSHHostWithStatus } from "@/main-axios";
import { ConnectionsPanel } from "@/sidebar/ConnectionsPanel";
+import { TransferMonitor } from "@/features/file-manager/TransferMonitor.tsx";
function sshHostToHost(h: SSHHostWithStatus): Host {
return {
@@ -140,7 +146,8 @@ export function AppShell({
username: string;
onLogout: () => void;
}) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
+ const { setTheme } = useTheme();
const [tabs, setTabs] = useState<Tab[]>([
{
id: "dashboard",
@@ -362,7 +369,19 @@ export function AppShell({
useEffect(() => {
getUserPreferences()
- .then((prefs) => setUserPrefs(prefs))
+ .then((prefs) => {
+ setUserPrefs(prefs);
+ if (prefs.theme) setTheme(prefs.theme as ThemeId);
+ if (prefs.fontSize) applyFontSize(prefs.fontSize as FontSizeId);
+ if (prefs.accentColor) {
+ localStorage.setItem("termix-accent", prefs.accentColor);
+ applyAccentColor(prefs.accentColor);
+ }
+ if (prefs.language && prefs.language !== i18n.language) {
+ localStorage.setItem("i18nextLng", prefs.language);
+ void i18n.changeLanguage(prefs.language);
+ }
+ })
.catch(() => {})
.finally(() => setUserPrefsLoaded(true));
}, []);
@@ -464,6 +483,13 @@ export function AppShell({
if (!host && !hostlessTypes.includes(saved.tabType as TabType))
continue;
+ if (host) {
+ if (saved.tabType === "terminal" && !host.enableSsh) continue;
+ if (saved.tabType === "rdp" && !host.enableRdp) continue;
+ if (saved.tabType === "vnc" && !host.enableVnc) continue;
+ if (saved.tabType === "telnet" && !host.enableTelnet) continue;
+ }
+
// Singleton tabs use their type as the stable ID; host-bound tabs get a unique ID
const tabId = host
? `${host.name}-${saved.tabType}-${Date.now()}-${saved.tabOrder}`
@@ -509,7 +535,6 @@ export function AppShell({
}
loadSavedTabs();
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [hostsLoaded, userPrefsLoaded]);
// Debounced tab-order sync: when tab order changes, patch each persistent tab's tabOrder in DB.
@@ -844,7 +869,7 @@ export function AppShell({
const id = requestAnimationFrame(() => {
tabs.forEach((tab) => {
if (!tab.terminalRef) return;
- const ref = tab.terminalRef.current as any;
+ const ref = tab.terminalRef.current;
ref?.fit?.();
ref?.notifyResize?.();
});
@@ -896,7 +921,7 @@ export function AppShell({
node.style.display = "";
node.style.visibility = activeInline ? "visible" : "hidden";
node.style.pointerEvents = activeInline ? "auto" : "none";
- node.style.zIndex = activeInline && !isSplit ? "1" : "0";
+ node.style.zIndex = activeInline ? "1" : "0";
} else {
node.style.visibility = "";
node.style.pointerEvents = "";
@@ -907,7 +932,6 @@ export function AppShell({
}
});
- const activeTab = tabs.find((t) => t.id === activeTabId)!;
const terminalTabs = tabs.filter((t) => t.type === "terminal");
// Sidebar panel content — shared between desktop inline sidebar and mobile sheet
@@ -1086,10 +1110,6 @@ export function AppShell({
railView={railView}
sidebarOpen={sidebarOpen}
splitMode={splitMode}
- connectionCount={
- tabs.filter((t) => PERSISTENT_TAB_TYPES.includes(t.type)).length +
- backgroundTabRecords.length
- }
username={username}
isAdmin={isAdmin}
profileDropdownOpen={profileDropdownOpen}
@@ -1189,12 +1209,20 @@ export function AppShell({
{/* Normal-view container. Tab nodes are appended here (or to pane elements)
by the DOM-placement effect above. React portals each tab's content
into its stable per-tab node so the component is never remounted.
- Hidden when split is active — pane-assigned nodes escape via vanilla DOM
- appendChild to paneEl, so hiding this doesn't affect them. */}
+ When split is active, shown on top only if the active tab is not in a pane. */}
<div
ref={normalViewRef}
className="absolute inset-0"
- style={{ display: isSplit && !isMobile ? "none" : undefined }}
+ style={{
+ display:
+ isSplit && !isMobile && paneTabIds.includes(activeTabId)
+ ? "none"
+ : undefined,
+ zIndex:
+ isSplit && !paneTabIds.includes(activeTabId)
+ ? 10
+ : undefined,
+ }}
>
{tabs.map((tab) => {
const tabNode = getTabNode(tab.id, tab.type === "terminal");
@@ -1247,6 +1275,7 @@ export function AppShell({
}
}}
/>
+ <TransferMonitor />
</>
);
}
diff --git a/src/ui/api/command-history-api.ts b/src/ui/api/command-history-api.ts
new file mode 100644
index 000000000..57be8a4ca
--- /dev/null
+++ b/src/ui/api/command-history-api.ts
@@ -0,0 +1,63 @@
+import { authApi, handleApiError } from "@/main-axios";
+
+// COMMAND HISTORY API
+// ============================================================================
+
+export async function saveCommandToHistory(
+ hostId: number,
+ command: string,
+): Promise<{ id: number; command: string; executedAt: string }> {
+ try {
+ const response = await authApi.post("/terminal/command_history", {
+ hostId,
+ command,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "save command to history");
+ }
+}
+
+export async function getCommandHistory(
+ hostId: number,
+ limit: number = 100,
+): Promise<string[]> {
+ try {
+ const response = await authApi.get(`/terminal/command_history/${hostId}`, {
+ params: { limit },
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch command history");
+ }
+}
+
+export async function deleteCommandFromHistory(
+ hostId: number,
+ command: string,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await authApi.post("/terminal/command_history/delete", {
+ hostId,
+ command,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "delete command from history");
+ }
+}
+
+export async function clearCommandHistory(
+ hostId: number,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await authApi.delete(
+ `/terminal/command_history/${hostId}`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "clear command history");
+ }
+}
+
+// ============================================================================
diff --git a/src/ui/api/credentials-api.ts b/src/ui/api/credentials-api.ts
new file mode 100644
index 000000000..90229f4bf
--- /dev/null
+++ b/src/ui/api/credentials-api.ts
@@ -0,0 +1,365 @@
+import { authApi, handleApiError, sshHostApi } from "@/main-axios";
+import type { SSHFolder } from "@/types/index";
+import { sshLogger } from "@/lib/frontend-logger";
+
+export async function getCredentials(): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get("/credentials");
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch credentials");
+ }
+}
+
+export async function getCredentialDetails(
+ credentialId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get(`/credentials/${credentialId}`);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch credential details");
+ }
+}
+
+export async function createCredential(
+ credentialData: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/credentials", credentialData);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "create credential");
+ }
+}
+
+export async function updateCredential(
+ credentialId: number,
+ credentialData: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.put(
+ `/credentials/${credentialId}`,
+ credentialData,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "update credential");
+ }
+}
+
+export async function deleteCredential(
+ credentialId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.delete(`/credentials/${credentialId}`);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "delete credential");
+ }
+}
+
+export async function getCredentialHosts(
+ credentialId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get(`/credentials/${credentialId}/hosts`);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch credential hosts");
+ }
+}
+
+export async function getCredentialFolders(): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get("/credentials/folders");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch credential folders");
+ }
+}
+
+export async function getSSHHostWithCredentials(
+ hostId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.get(
+ `/db/host/${hostId}/with-credentials`,
+ );
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch SSH host with credentials");
+ }
+}
+
+export async function getHostPassword(
+ hostId: number,
+ field: "password" | "sudoPassword" = "password",
+): Promise<string | null> {
+ try {
+ const response = await sshHostApi.get(
+ `/db/host/${hostId}/password?field=${field}`,
+ );
+ return response.data?.value || null;
+ } catch {
+ return null;
+ }
+}
+
+export async function applyCredentialToHost(
+ hostId: number,
+ credentialId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.post(
+ `/db/host/${hostId}/apply-credential`,
+ { credentialId },
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "apply credential to host");
+ }
+}
+
+export async function removeCredentialFromHost(
+ hostId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.delete(`/db/host/${hostId}/credential`);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "remove credential from host");
+ }
+}
+
+export async function migrateHostToCredential(
+ hostId: number,
+ credentialName: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.post(
+ `/db/host/${hostId}/migrate-to-credential`,
+ { credentialName },
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "migrate host to credential");
+ }
+}
+
+export async function getFoldersWithStats(): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get("/host/db/folders/with-stats");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch folders with statistics");
+ }
+}
+
+export async function renameFolder(
+ oldName: string,
+ newName: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.put("/host/folders/rename", {
+ oldName,
+ newName,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "rename folder");
+ }
+}
+
+export async function getSSHFolders(): Promise<SSHFolder[]> {
+ try {
+ sshLogger.info("Fetching SSH folders", {
+ operation: "fetch_ssh_folders",
+ });
+
+ const response = await authApi.get("/host/folders");
+
+ sshLogger.success("SSH folders fetched successfully", {
+ operation: "fetch_ssh_folders",
+ count: response.data.length,
+ });
+
+ return response.data;
+ } catch (error) {
+ sshLogger.error("Failed to fetch SSH folders", error, {
+ operation: "fetch_ssh_folders",
+ });
+ handleApiError(error, "fetch SSH folders");
+ throw error;
+ }
+}
+
+export async function updateFolderMetadata(
+ name: string,
+ color?: string,
+ icon?: string,
+): Promise<void> {
+ try {
+ sshLogger.info("Updating folder metadata", {
+ operation: "update_folder_metadata",
+ name,
+ color,
+ icon,
+ });
+
+ await authApi.put("/host/folders/metadata", {
+ name,
+ color,
+ icon,
+ });
+
+ sshLogger.success("Folder metadata updated successfully", {
+ operation: "update_folder_metadata",
+ name,
+ });
+ } catch (error) {
+ sshLogger.error("Failed to update folder metadata", error, {
+ operation: "update_folder_metadata",
+ name,
+ });
+ handleApiError(error, "update folder metadata");
+ throw error;
+ }
+}
+
+export async function deleteAllHostsInFolder(
+ folderName: string,
+): Promise<{ deletedCount: number }> {
+ try {
+ sshLogger.info("Deleting all hosts in folder", {
+ operation: "delete_folder_hosts",
+ folderName,
+ });
+
+ const response = await authApi.delete(
+ `/host/folders/${encodeURIComponent(folderName)}/hosts`,
+ );
+
+ sshLogger.success("All hosts in folder deleted successfully", {
+ operation: "delete_folder_hosts",
+ folderName,
+ deletedCount: response.data.deletedCount,
+ });
+
+ return response.data;
+ } catch (error) {
+ sshLogger.error("Failed to delete hosts in folder", error, {
+ operation: "delete_folder_hosts",
+ folderName,
+ });
+ handleApiError(error, "delete hosts in folder");
+ throw error;
+ }
+}
+
+export async function renameCredentialFolder(
+ oldName: string,
+ newName: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.put("/credentials/folders/rename", {
+ oldName,
+ newName,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "rename credential folder");
+ }
+}
+
+export async function detectKeyType(
+ privateKey: string,
+ keyPassword?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/credentials/detect-key-type", {
+ privateKey,
+ keyPassword,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "detect key type");
+ }
+}
+
+export async function detectPublicKeyType(
+ publicKey: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/credentials/detect-public-key-type", {
+ publicKey,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "detect public key type");
+ }
+}
+
+export async function validateKeyPair(
+ privateKey: string,
+ publicKey: string,
+ keyPassword?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/credentials/validate-key-pair", {
+ privateKey,
+ publicKey,
+ keyPassword,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "validate key pair");
+ }
+}
+
+export async function generatePublicKeyFromPrivate(
+ privateKey: string,
+ keyPassword?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/credentials/generate-public-key", {
+ privateKey,
+ keyPassword,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "generate public key from private key");
+ }
+}
+
+export async function generateKeyPair(
+ keyType: "ssh-ed25519" | "ssh-rsa" | "ecdsa-sha2-nistp256",
+ keySize?: number,
+ passphrase?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/credentials/generate-key-pair", {
+ keyType,
+ keySize,
+ passphrase,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "generate SSH key pair");
+ }
+}
+
+export async function deployCredentialToHost(
+ credentialId: number,
+ targetHostId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post(
+ `/credentials/${credentialId}/deploy-to-host`,
+ { targetHostId },
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "deploy credential to host");
+ }
+}
diff --git a/src/ui/api/dashboard-api.ts b/src/ui/api/dashboard-api.ts
new file mode 100644
index 000000000..584bda35e
--- /dev/null
+++ b/src/ui/api/dashboard-api.ts
@@ -0,0 +1,83 @@
+import { dashboardApi, handleApiError } from "@/main-axios";
+
+// DASHBOARD API
+// ============================================================================
+
+export interface UptimeInfo {
+ uptimeMs: number;
+ uptimeSeconds: number;
+ formatted: string;
+}
+
+export interface RecentActivityItem {
+ id: number;
+ userId: string;
+ type:
+ | "terminal"
+ | "file_manager"
+ | "server_stats"
+ | "tunnel"
+ | "docker"
+ | "telnet"
+ | "vnc"
+ | "rdp";
+ hostId: number;
+ hostName: string;
+ timestamp: string;
+}
+
+export async function getUptime(): Promise<UptimeInfo> {
+ try {
+ const response = await dashboardApi.get("/uptime");
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch uptime");
+ }
+}
+
+export async function getRecentActivity(
+ limit?: number,
+): Promise<RecentActivityItem[]> {
+ try {
+ const response = await dashboardApi.get("/activity/recent", {
+ params: { limit },
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch recent activity");
+ }
+}
+
+export async function logActivity(
+ type:
+ | "terminal"
+ | "file_manager"
+ | "server_stats"
+ | "tunnel"
+ | "docker"
+ | "rdp"
+ | "vnc"
+ | "telnet",
+ hostId: number,
+ hostName: string,
+): Promise<{ message: string; id: number | string }> {
+ try {
+ const response = await dashboardApi.post("/activity/log", {
+ type,
+ hostId,
+ hostName,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "log activity");
+ }
+}
+
+export async function resetRecentActivity(): Promise<{ message: string }> {
+ try {
+ const response = await dashboardApi.delete("/activity/reset");
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "reset recent activity");
+ }
+}
diff --git a/src/ui/api/dashboard-preferences-api.ts b/src/ui/api/dashboard-preferences-api.ts
new file mode 100644
index 000000000..40396dcad
--- /dev/null
+++ b/src/ui/api/dashboard-preferences-api.ts
@@ -0,0 +1,26 @@
+import { dashboardApi } from "@/main-axios";
+
+export interface DashboardLayout {
+ cards: Array<{
+ id: string;
+ enabled: boolean;
+ order: number;
+ panel?: "main" | "side";
+ height?: number | null;
+ }>;
+ mainWidthPct?: number;
+}
+
+export async function getDashboardPreferences(): Promise<DashboardLayout> {
+ const response = await dashboardApi.get("/dashboard/preferences");
+ return response.data;
+}
+
+export async function saveDashboardPreferences(
+ layout: DashboardLayout,
+): Promise<{ success: boolean }> {
+ const response = await dashboardApi.post("/dashboard/preferences", layout);
+ return response.data;
+}
+
+// ============================================================================
diff --git a/src/ui/api/docker-api.ts b/src/ui/api/docker-api.ts
new file mode 100644
index 000000000..afbacd890
--- /dev/null
+++ b/src/ui/api/docker-api.ts
@@ -0,0 +1,345 @@
+import axios from "axios";
+import { dockerApi, handleApiError } from "@/main-axios";
+import type {
+ DockerContainer,
+ DockerLogOptions,
+ DockerStats,
+ DockerValidation,
+} from "@/types/index";
+
+type ApiConnectionLog = {
+ type: "info" | "success" | "warning" | "error";
+ stage: string;
+ message: string;
+ details?: Record<string, unknown>;
+};
+
+type ConnectErrorResponse = {
+ error?: string;
+ message?: string;
+ connectionLogs?: ApiConnectionLog[];
+ requires_totp?: boolean;
+ requires_warpgate?: boolean;
+ sessionId?: string;
+ prompt?: string;
+ url?: string;
+ securityKey?: string;
+ status?: string;
+ reason?: string;
+};
+
+export async function connectDockerSession(
+ sessionId: string,
+ hostId: number,
+ config?: {
+ userProvidedPassword?: string;
+ userProvidedSshKey?: string;
+ userProvidedKeyPassword?: string;
+ forceKeyboardInteractive?: boolean;
+ useSocks5?: boolean;
+ socks5Host?: string;
+ socks5Port?: number;
+ socks5Username?: string;
+ socks5Password?: string;
+ socks5ProxyChain?: unknown;
+ },
+): Promise<{
+ success?: boolean;
+ message?: string;
+ requires_totp?: boolean;
+ prompt?: string;
+ isPassword?: boolean;
+ status?: string;
+ reason?: string;
+ connectionLogs?: ApiConnectionLog[];
+ requires_warpgate?: boolean;
+ url?: string;
+ securityKey?: string;
+}> {
+ try {
+ const response = await dockerApi.post("/ssh/connect", {
+ sessionId,
+ hostId,
+ ...config,
+ });
+ return response.data;
+ } catch (error: unknown) {
+ if (
+ axios.isAxiosError<ConnectErrorResponse>(error) &&
+ error.response?.data?.status === "auth_required"
+ ) {
+ return error.response.data;
+ }
+ if (
+ axios.isAxiosError<ConnectErrorResponse>(error) &&
+ error.response?.data?.requires_totp
+ ) {
+ return error.response.data;
+ }
+ if (
+ axios.isAxiosError<ConnectErrorResponse>(error) &&
+ error.response?.data?.requires_warpgate
+ ) {
+ return error.response.data;
+ }
+ if (
+ axios.isAxiosError<ConnectErrorResponse>(error) &&
+ error.response?.data?.connectionLogs
+ ) {
+ const data = error.response.data;
+ const errorWithLogs = new Error(
+ data.error || data.message || error.message,
+ );
+ Object.assign(errorWithLogs, {
+ connectionLogs: data.connectionLogs,
+ });
+ throw errorWithLogs;
+ }
+ throw handleApiError(error, "connect to Docker SSH session");
+ }
+}
+
+export async function verifyDockerTOTP(
+ sessionId: string,
+ totpCode: string,
+): Promise<{ status: string; message: string }> {
+ try {
+ const response = await dockerApi.post("/ssh/connect-totp", {
+ sessionId,
+ totpCode,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "verify Docker TOTP");
+ }
+}
+
+export async function verifyDockerWarpgate(
+ sessionId: string,
+): Promise<{ status: string; message: string }> {
+ try {
+ const response = await dockerApi.post("/ssh/connect-warpgate", {
+ sessionId,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "verify Docker Warpgate");
+ }
+}
+
+export async function disconnectDockerSession(
+ sessionId: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await dockerApi.post("/ssh/disconnect", {
+ sessionId,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "disconnect from Docker SSH session");
+ }
+}
+
+export async function keepaliveDockerSession(
+ sessionId: string,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await dockerApi.post("/ssh/keepalive", {
+ sessionId,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "keepalive Docker SSH session");
+ }
+}
+
+export async function getDockerSessionStatus(
+ sessionId: string,
+): Promise<{ success: boolean; connected: boolean }> {
+ try {
+ const response = await dockerApi.get("/ssh/status", {
+ params: { sessionId },
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "get Docker session status");
+ }
+}
+
+export async function validateDockerAvailability(
+ sessionId: string,
+): Promise<DockerValidation> {
+ try {
+ const response = await dockerApi.get(`/validate/${sessionId}`);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "validate Docker availability");
+ }
+}
+
+export async function listDockerContainers(
+ sessionId: string,
+ all: boolean = true,
+): Promise<DockerContainer[]> {
+ try {
+ const response = await dockerApi.get(`/containers/${sessionId}`, {
+ params: { all },
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "list Docker containers");
+ }
+}
+
+export async function getDockerContainerDetails(
+ sessionId: string,
+ containerId: string,
+): Promise<DockerContainer> {
+ try {
+ const response = await dockerApi.get(
+ `/containers/${sessionId}/${containerId}`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "get Docker container details");
+ }
+}
+
+export async function startDockerContainer(
+ sessionId: string,
+ containerId: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await dockerApi.post(
+ `/containers/${sessionId}/${containerId}/start`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "start Docker container");
+ }
+}
+
+export async function stopDockerContainer(
+ sessionId: string,
+ containerId: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await dockerApi.post(
+ `/containers/${sessionId}/${containerId}/stop`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "stop Docker container");
+ }
+}
+
+export async function restartDockerContainer(
+ sessionId: string,
+ containerId: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await dockerApi.post(
+ `/containers/${sessionId}/${containerId}/restart`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "restart Docker container");
+ }
+}
+
+export async function pauseDockerContainer(
+ sessionId: string,
+ containerId: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await dockerApi.post(
+ `/containers/${sessionId}/${containerId}/pause`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "pause Docker container");
+ }
+}
+
+export async function unpauseDockerContainer(
+ sessionId: string,
+ containerId: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await dockerApi.post(
+ `/containers/${sessionId}/${containerId}/unpause`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "unpause Docker container");
+ }
+}
+
+export async function removeDockerContainer(
+ sessionId: string,
+ containerId: string,
+ force: boolean = false,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await dockerApi.delete(
+ `/containers/${sessionId}/${containerId}/remove`,
+ {
+ params: { force },
+ },
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "remove Docker container");
+ }
+}
+
+export async function getContainerLogs(
+ sessionId: string,
+ containerId: string,
+ options?: DockerLogOptions,
+): Promise<{ logs: string }> {
+ try {
+ const response = await dockerApi.get(
+ `/containers/${sessionId}/${containerId}/logs`,
+ {
+ params: options,
+ },
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "get container logs");
+ }
+}
+
+export async function downloadContainerLogs(
+ sessionId: string,
+ containerId: string,
+ options?: DockerLogOptions,
+): Promise<Blob> {
+ try {
+ const response = await dockerApi.get(
+ `/containers/${sessionId}/${containerId}/logs`,
+ {
+ params: { ...options, download: true },
+ responseType: "blob",
+ },
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "download container logs");
+ }
+}
+
+export async function getContainerStats(
+ sessionId: string,
+ containerId: string,
+): Promise<DockerStats> {
+ try {
+ const response = await dockerApi.get(
+ `/containers/${sessionId}/${containerId}/stats`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "get container stats");
+ }
+}
diff --git a/src/ui/api/file-manager-data-api.ts b/src/ui/api/file-manager-data-api.ts
new file mode 100644
index 000000000..3aeafb411
--- /dev/null
+++ b/src/ui/api/file-manager-data-api.ts
@@ -0,0 +1,147 @@
+import { authApi, handleApiError } from "@/main-axios";
+
+// FILE MANAGER DATA
+// ============================================================================
+
+export async function getRecentFiles(
+ hostId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get("/host/file_manager/recent", {
+ params: { hostId },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "get recent files");
+ throw error;
+ }
+}
+
+export async function addRecentFile(
+ hostId: number,
+ path: string,
+ name?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/host/file_manager/recent", {
+ hostId,
+ path,
+ name,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "add recent file");
+ throw error;
+ }
+}
+
+export async function removeRecentFile(
+ hostId: number,
+ path: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.delete("/host/file_manager/recent", {
+ data: { hostId, path },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "remove recent file");
+ throw error;
+ }
+}
+
+export async function getPinnedFiles(
+ hostId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get("/host/file_manager/pinned", {
+ params: { hostId },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "get pinned files");
+ throw error;
+ }
+}
+
+export async function addPinnedFile(
+ hostId: number,
+ path: string,
+ name?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/host/file_manager/pinned", {
+ hostId,
+ path,
+ name,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "add pinned file");
+ throw error;
+ }
+}
+
+export async function removePinnedFile(
+ hostId: number,
+ path: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.delete("/host/file_manager/pinned", {
+ data: { hostId, path },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "remove pinned file");
+ throw error;
+ }
+}
+
+export async function getFolderShortcuts(
+ hostId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get("/host/file_manager/shortcuts", {
+ params: { hostId },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "get folder shortcuts");
+ throw error;
+ }
+}
+
+export async function addFolderShortcut(
+ hostId: number,
+ path: string,
+ name?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/host/file_manager/shortcuts", {
+ hostId,
+ path,
+ name,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "add folder shortcut");
+ throw error;
+ }
+}
+
+export async function removeFolderShortcut(
+ hostId: number,
+ path: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.delete("/host/file_manager/shortcuts", {
+ data: { hostId, path },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "remove folder shortcut");
+ throw error;
+ }
+}
+
+// ============================================================================
diff --git a/src/ui/api/file-manager-metadata-api.ts b/src/ui/api/file-manager-metadata-api.ts
new file mode 100644
index 000000000..b2f0420d6
--- /dev/null
+++ b/src/ui/api/file-manager-metadata-api.ts
@@ -0,0 +1,126 @@
+import { handleApiError, sshHostApi } from "@/main-axios";
+import type { FileManagerFile, FileManagerShortcut } from "@/types/index";
+
+interface FileManagerOperation {
+ name: string;
+ path: string;
+ isSSH: boolean;
+ sshSessionId?: string;
+ hostId: number;
+}
+
+// FILE MANAGER METADATA (Recent, Pinned, Shortcuts)
+// ============================================================================
+
+export async function getFileManagerRecent(
+ hostId: number,
+): Promise<FileManagerFile[]> {
+ try {
+ const response = await sshHostApi.get(
+ `/file_manager/recent?hostId=${hostId}`,
+ );
+ return response.data || [];
+ } catch {
+ return [];
+ }
+}
+
+export async function addFileManagerRecent(
+ file: FileManagerOperation,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.post("/file_manager/recent", file);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "add recent file");
+ }
+}
+
+export async function removeFileManagerRecent(
+ file: FileManagerOperation,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.delete("/file_manager/recent", {
+ data: file,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "remove recent file");
+ }
+}
+
+export async function getFileManagerPinned(
+ hostId: number,
+): Promise<FileManagerFile[]> {
+ try {
+ const response = await sshHostApi.get(
+ `/file_manager/pinned?hostId=${hostId}`,
+ );
+ return response.data || [];
+ } catch {
+ return [];
+ }
+}
+
+export async function addFileManagerPinned(
+ file: FileManagerOperation,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.post("/file_manager/pinned", file);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "add pinned file");
+ }
+}
+
+export async function removeFileManagerPinned(
+ file: FileManagerOperation,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.delete("/file_manager/pinned", {
+ data: file,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "remove pinned file");
+ }
+}
+
+export async function getFileManagerShortcuts(
+ hostId: number,
+): Promise<FileManagerShortcut[]> {
+ try {
+ const response = await sshHostApi.get(
+ `/file_manager/shortcuts?hostId=${hostId}`,
+ );
+ return response.data || [];
+ } catch {
+ return [];
+ }
+}
+
+export async function addFileManagerShortcut(
+ shortcut: FileManagerOperation,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.post("/file_manager/shortcuts", shortcut);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "add shortcut");
+ }
+}
+
+export async function removeFileManagerShortcut(
+ shortcut: FileManagerOperation,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.delete("/file_manager/shortcuts", {
+ data: shortcut,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "remove shortcut");
+ }
+}
+
+// ============================================================================
diff --git a/src/ui/api/guacamole-api.ts b/src/ui/api/guacamole-api.ts
new file mode 100644
index 000000000..abb59e600
--- /dev/null
+++ b/src/ui/api/guacamole-api.ts
@@ -0,0 +1,228 @@
+import { authApi, handleApiError } from "@/main-axios";
+
+export interface GuacamoleTokenRequest {
+ protocol: "rdp" | "vnc" | "telnet";
+ hostname: string;
+ port?: number;
+ username?: string;
+ password?: string;
+ domain?: string;
+ security?: string;
+ ignoreCert?: boolean;
+ guacamoleConfig?: {
+ colorDepth?: number;
+ width?: number;
+ height?: number;
+ dpi?: number;
+ resizeMethod?: string;
+ forceLossless?: boolean;
+ disableAudio?: boolean;
+ enableAudioInput?: boolean;
+ enableWallpaper?: boolean;
+ enableTheming?: boolean;
+ enableFontSmoothing?: boolean;
+ enableFullWindowDrag?: boolean;
+ enableDesktopComposition?: boolean;
+ enableMenuAnimations?: boolean;
+ disableBitmapCaching?: boolean;
+ disableOffscreenCaching?: boolean;
+ disableGlyphCaching?: boolean;
+ disableGfx?: boolean;
+ enablePrinting?: boolean;
+ printerName?: string;
+ enableDrive?: boolean;
+ driveName?: string;
+ drivePath?: string;
+ createDrivePath?: boolean;
+ disableDownload?: boolean;
+ disableUpload?: boolean;
+ enableTouch?: boolean;
+ clientName?: string;
+ console?: boolean;
+ initialProgram?: string;
+ serverLayout?: string;
+ timezone?: string;
+ gatewayHostname?: string;
+ gatewayPort?: number;
+ gatewayUsername?: string;
+ gatewayPassword?: string;
+ gatewayDomain?: string;
+ remoteApp?: string;
+ remoteAppDir?: string;
+ remoteAppArgs?: string;
+ normalizeClipboard?: string;
+ disableCopy?: boolean;
+ disablePaste?: boolean;
+ cursor?: string;
+ swapRedBlue?: boolean;
+ readOnly?: boolean;
+ recordingPath?: string;
+ recordingName?: string;
+ createRecordingPath?: boolean;
+ recordingExcludeOutput?: boolean;
+ recordingExcludeMouse?: boolean;
+ recordingIncludeKeys?: boolean;
+ wolSendPacket?: boolean;
+ wolMacAddr?: string;
+ wolBroadcastAddr?: string;
+ wolUdpPort?: number;
+ wolWaitTime?: number;
+ };
+}
+
+export interface GuacamoleTokenResponse {
+ token: string;
+}
+
+type GuacamoleConfigSource = {
+ guacamoleConfig?: string | Record<string, unknown> | null;
+};
+
+export function getGuacamoleDpi(
+ source?: GuacamoleConfigSource,
+): number | undefined {
+ const config = source?.guacamoleConfig;
+ if (!config) return undefined;
+
+ let dpi: unknown;
+ if (typeof config === "string") {
+ try {
+ dpi = JSON.parse(config).dpi;
+ } catch {
+ return undefined;
+ }
+ } else {
+ dpi = config.dpi;
+ }
+
+ const parsedDpi = typeof dpi === "string" ? Number(dpi) : dpi;
+ if (
+ typeof parsedDpi !== "number" ||
+ !Number.isFinite(parsedDpi) ||
+ parsedDpi <= 0
+ ) {
+ return undefined;
+ }
+
+ return Math.trunc(parsedDpi);
+}
+
+function toGuacamoleParams(
+ config: GuacamoleTokenRequest["guacamoleConfig"],
+): Record<string, unknown> {
+ if (!config) return {};
+
+ const params: Record<string, unknown> = {};
+
+ const mappings: Record<string, string> = {
+ colorDepth: "color-depth",
+ resizeMethod: "resize-method",
+ forceLossless: "force-lossless",
+ disableAudio: "disable-audio",
+ enableAudioInput: "enable-audio-input",
+ enableWallpaper: "enable-wallpaper",
+ enableTheming: "enable-theming",
+ enableFontSmoothing: "enable-font-smoothing",
+ enableFullWindowDrag: "enable-full-window-drag",
+ enableDesktopComposition: "enable-desktop-composition",
+ enableMenuAnimations: "enable-menu-animations",
+ disableBitmapCaching: "disable-bitmap-caching",
+ disableOffscreenCaching: "disable-offscreen-caching",
+ disableGlyphCaching: "disable-glyph-caching",
+ disableGfx: "disable-gfx",
+ enablePrinting: "enable-printing",
+ printerName: "printer-name",
+ enableDrive: "enable-drive",
+ driveName: "drive-name",
+ drivePath: "drive-path",
+ createDrivePath: "create-drive-path",
+ disableDownload: "disable-download",
+ disableUpload: "disable-upload",
+ enableTouch: "enable-touch",
+ clientName: "client-name",
+ initialProgram: "initial-program",
+ serverLayout: "server-layout",
+ gatewayHostname: "gateway-hostname",
+ gatewayPort: "gateway-port",
+ gatewayUsername: "gateway-username",
+ gatewayPassword: "gateway-password",
+ gatewayDomain: "gateway-domain",
+ remoteApp: "remote-app",
+ remoteAppDir: "remote-app-dir",
+ remoteAppArgs: "remote-app-args",
+ normalizeClipboard: "normalize-clipboard",
+ disableCopy: "disable-copy",
+ disablePaste: "disable-paste",
+ swapRedBlue: "swap-red-blue",
+ readOnly: "read-only",
+ recordingPath: "recording-path",
+ recordingName: "recording-name",
+ createRecordingPath: "create-recording-path",
+ recordingExcludeOutput: "recording-exclude-output",
+ recordingExcludeMouse: "recording-exclude-mouse",
+ recordingIncludeKeys: "recording-include-keys",
+ wolSendPacket: "wol-send-packet",
+ wolMacAddr: "wol-mac-addr",
+ wolBroadcastAddr: "wol-broadcast-addr",
+ wolUdpPort: "wol-udp-port",
+ wolWaitTime: "wol-wait-time",
+ };
+
+ for (const [key, value] of Object.entries(config)) {
+ if (value !== undefined && value !== null && value !== "") {
+ const paramName = mappings[key] || key;
+ if (typeof value === "boolean") {
+ params[paramName] = value ? "true" : "false";
+ } else {
+ params[paramName] = value;
+ }
+ }
+ }
+
+ return params;
+}
+
+export async function getGuacamoleToken(
+ request: GuacamoleTokenRequest,
+): Promise<GuacamoleTokenResponse> {
+ try {
+ const guacParams = toGuacamoleParams(request.guacamoleConfig);
+
+ const response = await authApi.post("/guacamole/token", {
+ type: request.protocol,
+ hostname: request.hostname,
+ port: request.port,
+ username: request.username,
+ password: request.password,
+ domain: request.domain,
+ security: request.security,
+ "ignore-cert": request.ignoreCert,
+ ...guacParams,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "get guacamole token");
+ }
+}
+
+export async function getGuacamoleTokenFromHost(
+ hostId: number,
+ protocol?: "rdp" | "vnc" | "telnet",
+): Promise<GuacamoleTokenResponse> {
+ try {
+ const response = await authApi.post(
+ `/guacamole/connect-host/${hostId}`,
+ protocol ? { protocol } : {},
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "get guacamole token from host");
+ }
+}
+
+export async function getGuacdStatus(): Promise<{
+ guacd: { status: string };
+}> {
+ const response = await authApi.get("/guacamole/status");
+ return response.data;
+}
diff --git a/src/ui/api/oidc-account-api.ts b/src/ui/api/oidc-account-api.ts
new file mode 100644
index 000000000..238636258
--- /dev/null
+++ b/src/ui/api/oidc-account-api.ts
@@ -0,0 +1,32 @@
+import { authApi, handleApiError } from "@/main-axios";
+
+// OIDC ACCOUNT LINKING
+// ============================================================================
+
+export async function linkOIDCToPasswordAccount(
+ oidcUserId: string,
+ targetUsername: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await authApi.post("/users/link-oidc-to-password", {
+ oidcUserId,
+ targetUsername,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "link OIDC account to password account");
+ }
+}
+
+export async function unlinkOIDCFromPasswordAccount(
+ userId: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await authApi.post("/users/unlink-oidc-from-password", {
+ userId,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "unlink OIDC from password account");
+ }
+}
diff --git a/src/ui/api/open-tabs-api.ts b/src/ui/api/open-tabs-api.ts
new file mode 100644
index 000000000..294642afc
--- /dev/null
+++ b/src/ui/api/open-tabs-api.ts
@@ -0,0 +1,97 @@
+import { authApi } from "@/main-axios";
+
+// OPEN TABS API
+// ============================================================================
+
+export interface OpenTabRecord {
+ id: string;
+ userId: string;
+ tabType: string;
+ hostId: number | null;
+ label: string;
+ tabOrder: number;
+ backendSessionId: string | null;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface OpenTabSyncPayload {
+ id: string;
+ tabType: string;
+ hostId?: number | null;
+ label: string;
+ tabOrder: number;
+ backendSessionId?: string | null;
+}
+
+export interface OpenTabUpsertPayload {
+ id: string;
+ tabType: string;
+ hostId?: number | null;
+ label: string;
+ tabOrder: number;
+ backendSessionId?: string | null;
+}
+
+export interface ActiveSessionInfo {
+ sessionId: string;
+ hostId: number;
+ hostName: string;
+ tabInstanceId: string | null;
+ isConnected: boolean;
+ createdAt: number;
+}
+
+export async function getOpenTabs(): Promise<OpenTabRecord[]> {
+ const response = await authApi.get("/open-tabs");
+ return response.data;
+}
+
+export async function syncOpenTabs(tabs: OpenTabSyncPayload[]): Promise<void> {
+ await authApi.put("/open-tabs", { tabs });
+}
+
+export async function deleteOpenTab(instanceId: string): Promise<void> {
+ await authApi.delete(`/open-tabs/${instanceId}`);
+}
+
+export async function patchOpenTab(
+ instanceId: string,
+ updates: Partial<
+ Pick<OpenTabRecord, "label" | "tabOrder" | "backendSessionId">
+ >,
+): Promise<void> {
+ await authApi.patch(`/open-tabs/${instanceId}`, updates);
+}
+
+export async function addOpenTab(tab: OpenTabUpsertPayload): Promise<void> {
+ await authApi.post("/open-tabs", tab);
+}
+
+export async function getActiveSessions(): Promise<ActiveSessionInfo[]> {
+ const response = await authApi.get("/open-tabs/active-sessions");
+ return response.data;
+}
+
+// ============================================================================
+// USER PREFERENCES API
+// ============================================================================
+
+export interface UserPreferences {
+ reopenTabsOnLogin: boolean;
+ theme?: string | null;
+ fontSize?: string | null;
+ accentColor?: string | null;
+ language?: string | null;
+}
+
+export async function getUserPreferences(): Promise<UserPreferences> {
+ const response = await authApi.get("/user-preferences");
+ return response.data;
+}
+
+export async function saveUserPreferences(
+ prefs: Partial<UserPreferences>,
+): Promise<void> {
+ await authApi.put("/user-preferences", prefs);
+}
diff --git a/src/ui/api/rbac-api.ts b/src/ui/api/rbac-api.ts
new file mode 100644
index 000000000..628910bbb
--- /dev/null
+++ b/src/ui/api/rbac-api.ts
@@ -0,0 +1,204 @@
+import { handleApiError, rbacApi } from "@/main-axios";
+import type { AccessRecord, Role, UserRole } from "@/main-axios";
+
+export async function getRoles(): Promise<{ roles: Role[] }> {
+ try {
+ const response = await rbacApi.get("/rbac/roles");
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch roles");
+ }
+}
+
+export async function createRole(roleData: {
+ name: string;
+ displayName: string;
+ description?: string | null;
+}): Promise<{ role: Role }> {
+ try {
+ const response = await rbacApi.post("/rbac/roles", roleData);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "create role");
+ }
+}
+
+export async function updateRole(
+ roleId: number,
+ roleData: {
+ displayName?: string;
+ description?: string | null;
+ },
+): Promise<{ role: Role }> {
+ try {
+ const response = await rbacApi.put(`/rbac/roles/${roleId}`, roleData);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "update role");
+ }
+}
+
+export async function deleteRole(
+ roleId: number,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await rbacApi.delete(`/rbac/roles/${roleId}`);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "delete role");
+ }
+}
+
+export async function getUserRoles(
+ userId: string,
+): Promise<{ roles: UserRole[] }> {
+ try {
+ const response = await rbacApi.get(`/rbac/users/${userId}/roles`);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch user roles");
+ }
+}
+
+export async function assignRoleToUser(
+ userId: string,
+ roleId: number,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await rbacApi.post(`/rbac/users/${userId}/roles`, {
+ roleId,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "assign role to user");
+ }
+}
+
+export async function removeRoleFromUser(
+ userId: string,
+ roleId: number,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await rbacApi.delete(
+ `/rbac/users/${userId}/roles/${roleId}`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "remove role from user");
+ }
+}
+
+export async function shareHost(
+ hostId: number,
+ shareData: {
+ targetType: "user" | "role";
+ targetUserId?: string;
+ targetRoleId?: number;
+ permissionLevel: "view";
+ durationHours?: number;
+ },
+): Promise<{ success: boolean }> {
+ try {
+ const response = await rbacApi.post(
+ `/rbac/host/${hostId}/share`,
+ shareData,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "share host");
+ }
+}
+
+export async function getHostAccess(
+ hostId: number,
+): Promise<{ accessList: AccessRecord[] }> {
+ try {
+ const response = await rbacApi.get(`/rbac/host/${hostId}/access`);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch host access");
+ }
+}
+
+export async function revokeHostAccess(
+ hostId: number,
+ accessId: number,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await rbacApi.delete(
+ `/rbac/host/${hostId}/access/${accessId}`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "revoke host access");
+ }
+}
+
+// ============================================================================
+// SNIPPET SHARING
+// ============================================================================
+
+export async function shareSnippet(
+ snippetId: number,
+ shareData: {
+ targetType: "user" | "role";
+ targetUserId?: string;
+ targetRoleId?: number;
+ durationHours?: number;
+ },
+): Promise<{ success: boolean }> {
+ try {
+ const response = await rbacApi.post(
+ `/rbac/snippet/${snippetId}/share`,
+ shareData,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "share snippet");
+ }
+}
+
+export async function getSnippetAccess(
+ snippetId: number,
+): Promise<{ accessList: AccessRecord[] }> {
+ try {
+ const response = await rbacApi.get(`/rbac/snippet/${snippetId}/access`);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch snippet access");
+ }
+}
+
+export async function revokeSnippetAccess(
+ snippetId: number,
+ accessId: number,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await rbacApi.delete(
+ `/rbac/snippet/${snippetId}/access/${accessId}`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "revoke snippet access");
+ }
+}
+
+export async function getSharedSnippets(): Promise<{
+ sharedSnippets: Array<{
+ id: number;
+ name: string;
+ content: string;
+ description: string | null;
+ folder: string | null;
+ ownerUsername: string;
+ permissionLevel: string;
+ expiresAt: string | null;
+ }>;
+}> {
+ try {
+ const response = await rbacApi.get("/rbac/shared-snippets");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch shared snippets");
+ }
+}
diff --git a/src/ui/api/server-stats-api.ts b/src/ui/api/server-stats-api.ts
new file mode 100644
index 000000000..53b31ac46
--- /dev/null
+++ b/src/ui/api/server-stats-api.ts
@@ -0,0 +1,262 @@
+import axios, { type AxiosRequestConfig } from "axios";
+import { handleApiError, statsApi } from "@/main-axios";
+import type { ServerMetrics, ServerStatus } from "@/main-axios";
+
+type ApiConnectionLog = {
+ type: "info" | "success" | "warning" | "error";
+ stage: string;
+ message: string;
+ details?: Record<string, unknown>;
+};
+
+type ConnectErrorResponse = {
+ error?: string;
+ message?: string;
+ connectionLogs?: ApiConnectionLog[];
+ requires_totp?: boolean;
+ requires_warpgate?: boolean;
+ sessionId?: string;
+ prompt?: string;
+ url?: string;
+ securityKey?: string;
+ status?: string;
+ reason?: string;
+};
+
+// SERVER STATISTICS
+// ============================================================================
+
+/**
+ * Progressive retry schedule for the background /status poll.
+ *
+ * Each entry describes one attempt's per-request timeout and the pause to
+ * observe before the next attempt. The pause on the last entry is `null`:
+ * after that final failure we surface the network error, which flows
+ * through the response interceptor + dbHealthMonitor (which decides
+ * between the degraded toast and the full-outage overlay based on whether
+ * any WebSocket is still alive).
+ *
+ * Sequence: try(2s) -> wait 3s -> try(5s) -> wait 5s -> try(8s) -> fail.
+ * Worst-case wall-clock = 23s, which fits inside the 30s ServerStatusContext
+ * poll cadence, so the next tick acts as the next retry without overlap.
+ */
+const STATUS_RETRY_SCHEDULE: ReadonlyArray<{
+ timeoutMs: number;
+ pauseAfterMs: number | null;
+}> = [
+ { timeoutMs: 2000, pauseAfterMs: 3000 },
+ { timeoutMs: 5000, pauseAfterMs: 5000 },
+ { timeoutMs: 8000, pauseAfterMs: null },
+];
+
+function isTransientStatusError(error: unknown): boolean {
+ if (!axios.isAxiosError(error)) return false;
+ if (error.response) {
+ // Definitive server response (even 5xx) is not something more retries
+ // will fix in a useful timeframe; bail out and report it normally.
+ return false;
+ }
+ const code = error.code;
+ if (!code) {
+ // No code + no response means classic network error (offline / DNS / TCP)
+ return true;
+ }
+ return (
+ code === "ECONNABORTED" ||
+ code === "ETIMEDOUT" ||
+ code === "ERR_NETWORK" ||
+ code === "ECONNREFUSED" ||
+ code === "ECONNRESET"
+ );
+}
+
+export async function getAllServerStatuses(): Promise<
+ Record<number, ServerStatus>
+> {
+ let lastError: unknown = null;
+
+ for (let i = 0; i < STATUS_RETRY_SCHEDULE.length; i++) {
+ const { timeoutMs, pauseAfterMs } = STATUS_RETRY_SCHEDULE[i];
+ const isFinalAttempt = i === STATUS_RETRY_SCHEDULE.length - 1;
+
+ try {
+ const response = await statsApi.get("/status", {
+ timeout: timeoutMs,
+ // Silence per-attempt interceptor logging & health-monitor side
+ // effects on all attempts except the final one, so background
+ // blips don't look like real outages.
+ __silentRetry: !isFinalAttempt,
+ } as AxiosRequestConfig & { __silentRetry?: boolean });
+ return response.data || {};
+ } catch (error) {
+ lastError = error;
+ if (!isTransientStatusError(error)) {
+ break;
+ }
+ if (pauseAfterMs === null) {
+ break;
+ }
+ await new Promise((resolve) => setTimeout(resolve, pauseAfterMs));
+ }
+ }
+
+ handleApiError(lastError, "fetch server statuses");
+}
+
+export async function getServerStatusById(id: number): Promise<ServerStatus> {
+ try {
+ const response = await statsApi.get(`/status/${id}`);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch server status");
+ throw error;
+ }
+}
+
+export async function getServerMetricsById(
+ id: number,
+): Promise<ServerMetrics | null> {
+ try {
+ const response = await statsApi.get(`/metrics/${id}`, {
+ // Treat 404 as an expected "no metrics yet / disabled" signal rather
+ // than an error so we don't spam warn logs on the client.
+ validateStatus: (status) => status === 200 || status === 404,
+ });
+ if (response.status === 404) {
+ return null;
+ }
+ return response.data;
+ } catch (error) {
+ // If a 404 still slips through (e.g. intercepted before reaching here),
+ // swallow it quietly; everything else still flows through handleApiError.
+ if (axios.isAxiosError(error) && error.response?.status === 404) {
+ return null;
+ }
+ handleApiError(error, "fetch server metrics");
+ throw error;
+ }
+}
+
+export async function startMetricsPolling(hostId: number): Promise<{
+ success: boolean;
+ requires_totp?: boolean;
+ sessionId?: string;
+ prompt?: string;
+ viewerSessionId?: string;
+ connectionLogs?: ApiConnectionLog[];
+}> {
+ try {
+ const response = await statsApi.post(`/metrics/start/${hostId}`);
+ return response.data;
+ } catch (error: unknown) {
+ if (
+ axios.isAxiosError<ConnectErrorResponse>(error) &&
+ error.response?.data?.connectionLogs
+ ) {
+ const data = error.response.data;
+ const errorWithLogs = new Error(
+ data.error || data.message || error.message,
+ );
+ Object.assign(errorWithLogs, {
+ connectionLogs: data.connectionLogs,
+ });
+ throw errorWithLogs;
+ }
+ handleApiError(error, "start metrics polling");
+ throw error;
+ }
+}
+
+export async function stopMetricsPolling(
+ hostId: number,
+ viewerSessionId?: string,
+): Promise<void> {
+ try {
+ await statsApi.post(`/metrics/stop/${hostId}`, { viewerSessionId });
+ } catch (error) {
+ handleApiError(error, "stop metrics polling");
+ throw error;
+ }
+}
+
+export async function sendMetricsHeartbeat(
+ viewerSessionId: string,
+): Promise<void> {
+ try {
+ await statsApi.post("/metrics/heartbeat", { viewerSessionId });
+ } catch (error) {
+ handleApiError(error, "send metrics heartbeat");
+ throw error;
+ }
+}
+
+export async function registerMetricsViewer(hostId: number): Promise<{
+ success: boolean;
+ viewerSessionId?: string;
+ skipped?: boolean;
+ reason?: string;
+}> {
+ try {
+ const response = await statsApi.post("/metrics/register-viewer", {
+ hostId,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "register metrics viewer");
+ throw error;
+ }
+}
+
+export async function unregisterMetricsViewer(
+ hostId: number,
+ viewerSessionId: string,
+): Promise<void> {
+ try {
+ await statsApi.post("/metrics/unregister-viewer", {
+ hostId,
+ viewerSessionId,
+ });
+ } catch (error) {
+ handleApiError(error, "unregister metrics viewer");
+ throw error;
+ }
+}
+
+export async function submitMetricsTOTP(
+ sessionId: string,
+ totpCode: string,
+): Promise<{
+ success: boolean;
+ viewerSessionId?: string;
+}> {
+ try {
+ const response = await statsApi.post("/metrics/connect-totp", {
+ sessionId,
+ totpCode,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "submit metrics TOTP");
+ throw error;
+ }
+}
+
+export async function refreshServerPolling(): Promise<void> {
+ try {
+ await statsApi.post("/refresh");
+ } catch (error) {
+ console.warn("Failed to refresh server polling:", error);
+ }
+}
+
+export async function notifyHostCreatedOrUpdated(
+ hostId: number,
+): Promise<void> {
+ try {
+ await statsApi.post("/host-updated", { hostId });
+ } catch (error) {
+ console.warn("Failed to notify stats server of host update:", error);
+ }
+}
+
+// ============================================================================
diff --git a/src/ui/api/settings-api.ts b/src/ui/api/settings-api.ts
new file mode 100644
index 000000000..e3cfea68c
--- /dev/null
+++ b/src/ui/api/settings-api.ts
@@ -0,0 +1,100 @@
+import { authApi, handleApiError, statsApi } from "@/main-axios";
+
+// GLOBAL MONITORING SETTINGS
+// ============================================================================
+
+export async function getGlobalMonitoringSettings(): Promise<{
+ statusCheckInterval: number;
+ metricsInterval: number;
+}> {
+ try {
+ const response = await statsApi.get("/global-settings");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch global monitoring settings");
+ }
+}
+
+export async function updateGlobalMonitoringSettings(settings: {
+ statusCheckInterval?: number;
+ metricsInterval?: number;
+}): Promise<void> {
+ try {
+ await statsApi.post("/global-settings", settings);
+ } catch (error) {
+ handleApiError(error, "update global monitoring settings");
+ }
+}
+
+// ============================================================================
+// LOG LEVEL SETTINGS
+// ============================================================================
+
+export async function getLogLevel(): Promise<{ level: string }> {
+ try {
+ const response = await authApi.get("/users/log-level");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch log level");
+ }
+}
+
+export async function updateLogLevel(level: string): Promise<void> {
+ try {
+ await authApi.patch("/users/log-level", { level });
+ } catch (error) {
+ handleApiError(error, "update log level");
+ }
+}
+
+// ============================================================================
+// SESSION TIMEOUT SETTINGS
+// ============================================================================
+
+export async function getSessionTimeout(): Promise<{ timeoutHours: number }> {
+ try {
+ const response = await authApi.get("/users/session-timeout");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch session timeout");
+ }
+}
+
+export async function updateSessionTimeout(
+ timeoutHours: number,
+): Promise<void> {
+ try {
+ await authApi.patch("/users/session-timeout", { timeoutHours });
+ } catch (error) {
+ handleApiError(error, "update session timeout");
+ }
+}
+
+// ============================================================================
+// GUACAMOLE SETTINGS
+// ============================================================================
+
+export async function getGuacamoleSettings(): Promise<{
+ enabled: boolean;
+ url: string;
+}> {
+ try {
+ const response = await authApi.get("/users/guacamole-settings");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch guacamole settings");
+ }
+}
+
+export async function updateGuacamoleSettings(settings: {
+ enabled?: boolean;
+ url?: string;
+}): Promise<void> {
+ try {
+ await authApi.patch("/users/guacamole-settings", settings);
+ } catch (error) {
+ handleApiError(error, "update guacamole settings");
+ }
+}
+
+// ============================================================================
diff --git a/src/ui/api/snippets-api.ts b/src/ui/api/snippets-api.ts
new file mode 100644
index 000000000..5c18e5e76
--- /dev/null
+++ b/src/ui/api/snippets-api.ts
@@ -0,0 +1,183 @@
+import { authApi, handleApiError } from "@/main-axios";
+
+export interface NetworkTopologyNode {
+ data: {
+ id: string;
+ label?: string;
+ ip?: string;
+ status?: string;
+ tags?: string[];
+ parent?: string;
+ color?: string;
+ };
+ position?: { x: number; y: number };
+}
+
+export interface NetworkTopologyEdge {
+ data: {
+ id?: string;
+ source: string;
+ target: string;
+ };
+}
+
+export interface NetworkTopologyData {
+ nodes: NetworkTopologyNode[];
+ edges: NetworkTopologyEdge[];
+}
+
+export async function getSnippets(): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get("/snippets");
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch snippets");
+ }
+}
+
+export async function createSnippet(
+ snippetData: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/snippets", snippetData);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "create snippet");
+ }
+}
+
+export async function updateSnippet(
+ snippetId: number,
+ snippetData: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.put(`/snippets/${snippetId}`, snippetData);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "update snippet");
+ }
+}
+
+export async function deleteSnippet(
+ snippetId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.delete(`/snippets/${snippetId}`);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "delete snippet");
+ }
+}
+
+export async function executeSnippet(
+ snippetId: number,
+ hostId: number,
+): Promise<{ success: boolean; output: string; error?: string }> {
+ try {
+ const response = await authApi.post("/snippets/execute", {
+ snippetId,
+ hostId,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "execute snippet");
+ }
+}
+
+export async function getNetworkTopology(): Promise<NetworkTopologyData | null> {
+ try {
+ const response = await authApi.get("/network-topology/");
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch network topology");
+ }
+}
+
+export async function saveNetworkTopology(
+ topology: NetworkTopologyData,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await authApi.post("/network-topology/", { topology });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "save network topology");
+ }
+}
+
+export async function getSnippetFolders(): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get("/snippets/folders");
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "fetch snippet folders");
+ }
+}
+
+export async function createSnippetFolder(folderData: {
+ name: string;
+ color?: string;
+ icon?: string;
+}): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/snippets/folders", folderData);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "create snippet folder");
+ }
+}
+
+export async function updateSnippetFolderMetadata(
+ folderName: string,
+ metadata: { color?: string; icon?: string },
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.put(
+ `/snippets/folders/${encodeURIComponent(folderName)}/metadata`,
+ metadata,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "update snippet folder metadata");
+ }
+}
+
+export async function renameSnippetFolder(
+ oldName: string,
+ newName: string,
+): Promise<{ success: boolean; oldName: string; newName: string }> {
+ try {
+ const response = await authApi.put("/snippets/folders/rename", {
+ oldName,
+ newName,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "rename snippet folder");
+ }
+}
+
+export async function deleteSnippetFolder(
+ folderName: string,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await authApi.delete(
+ `/snippets/folders/${encodeURIComponent(folderName)}`,
+ );
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "delete snippet folder");
+ }
+}
+
+export async function reorderSnippets(
+ updates: Array<{ id: number; order: number; folder?: string }>,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await authApi.put("/snippets/reorder", {
+ snippets: updates,
+ });
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "reorder snippets");
+ }
+}
diff --git a/src/ui/api/ssh-file-operations-api.ts b/src/ui/api/ssh-file-operations-api.ts
new file mode 100644
index 000000000..4d284638e
--- /dev/null
+++ b/src/ui/api/ssh-file-operations-api.ts
@@ -0,0 +1,794 @@
+import axios from "axios";
+import { authApi, fileManagerApi, handleApiError } from "@/main-axios";
+import { fileLogger } from "@/lib/frontend-logger";
+import type { SSHHost } from "@/types/index";
+
+type ApiConnectionLog = {
+ type: "info" | "success" | "warning" | "error";
+ stage: string;
+ message: string;
+ details?: Record<string, unknown>;
+};
+
+type ConnectErrorResponse = {
+ error?: string;
+ message?: string;
+ connectionLogs?: ApiConnectionLog[];
+ requires_totp?: boolean;
+ requires_warpgate?: boolean;
+ sessionId?: string;
+ prompt?: string;
+ url?: string;
+ securityKey?: string;
+ status?: string;
+ reason?: string;
+};
+
+// SSH FILE OPERATIONS
+// ============================================================================
+
+export async function connectSSH(
+ sessionId: string,
+ config: {
+ hostId?: number;
+ ip: string;
+ port: number;
+ username: string;
+ password?: string;
+ sshKey?: string;
+ keyPassword?: string;
+ authType?: string;
+ credentialId?: number;
+ userId?: string;
+ forceKeyboardInteractive?: boolean;
+ useSocks5?: boolean;
+ socks5Host?: string;
+ socks5Port?: number;
+ socks5Username?: string;
+ socks5Password?: string;
+ socks5ProxyChain?: unknown;
+ jumpHosts?: Array<{ hostId: number }>;
+ },
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post("/ssh/connect", {
+ sessionId,
+ ...config,
+ });
+ return response.data;
+ } catch (error: unknown) {
+ if (
+ axios.isAxiosError<ConnectErrorResponse>(error) &&
+ error.response?.data?.connectionLogs
+ ) {
+ const data = error.response.data;
+ const errorWithLogs = new Error(
+ data.error || data.message || error.message,
+ );
+ Object.assign(errorWithLogs, {
+ connectionLogs: data.connectionLogs,
+ });
+ if (data.requires_totp) {
+ Object.assign(errorWithLogs, {
+ requires_totp: true,
+ sessionId: data.sessionId,
+ prompt: data.prompt,
+ });
+ }
+ if (data.requires_warpgate) {
+ Object.assign(errorWithLogs, {
+ requires_warpgate: true,
+ sessionId: data.sessionId,
+ url: data.url,
+ securityKey: data.securityKey,
+ });
+ }
+ if (data.status === "auth_required") {
+ Object.assign(errorWithLogs, {
+ status: "auth_required",
+ reason: data.reason,
+ });
+ }
+ throw errorWithLogs;
+ }
+ handleApiError(error, "connect SSH");
+ }
+}
+
+export async function disconnectSSH(
+ sessionId: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post("/ssh/disconnect", {
+ sessionId,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "disconnect SSH");
+ }
+}
+
+export async function verifySSHTOTP(
+ sessionId: string,
+ totpCode: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post("/ssh/connect-totp", {
+ sessionId,
+ totpCode,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "verify SSH TOTP");
+ }
+}
+
+export async function verifySSHWarpgate(
+ sessionId: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post("/ssh/connect-warpgate", {
+ sessionId,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "verify SSH Warpgate");
+ }
+}
+
+/**
+ * @openapi
+ * /ssh/quick-connect:
+ * post:
+ * summary: Create a temporary SSH connection without saving to database
+ * description: Returns a temporary host configuration for immediate use
+ * tags:
+ * - SSH
+ * requestBody:
+ * required: true
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * required:
+ * - ip
+ * - port
+ * - username
+ * - authType
+ * properties:
+ * ip:
+ * type: string
+ * description: SSH server IP or hostname
+ * port:
+ * type: number
+ * description: SSH server port
+ * username:
+ * type: string
+ * description: SSH username
+ * authType:
+ * type: string
+ * enum: [password, key, credential]
+ * description: Authentication method
+ * password:
+ * type: string
+ * description: Password (required if authType is password)
+ * key:
+ * type: string
+ * description: SSH private key (required if authType is key)
+ * keyPassword:
+ * type: string
+ * description: SSH key password (optional)
+ * keyType:
+ * type: string
+ * description: SSH key type
+ * credentialId:
+ * type: number
+ * description: Credential ID (required if authType is credential)
+ * overrideCredentialUsername:
+ * type: boolean
+ * description: Use provided username instead of credential username
+ * responses:
+ * 200:
+ * description: Temporary host configuration created successfully
+ * content:
+ * application/json:
+ * schema:
+ * type: object
+ * description: SSHHost object
+ * 400:
+ * description: Invalid request data
+ * 401:
+ * description: Unauthorized
+ * 500:
+ * description: Server error
+ */
+export async function quickConnect(
+ data: Record<string, unknown>,
+): Promise<SSHHost> {
+ try {
+ const response = await authApi.post("/host/quick-connect", data);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "quick connect");
+ }
+}
+
+export async function getSSHStatus(
+ sessionId: string,
+): Promise<{ connected: boolean }> {
+ try {
+ const response = await fileManagerApi.get("/ssh/status", {
+ params: { sessionId },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "get SSH status");
+ }
+}
+
+export async function keepSSHAlive(
+ sessionId: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post("/ssh/keepalive", {
+ sessionId,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "SSH keepalive");
+ }
+}
+
+export async function listSSHFiles(
+ sessionId: string,
+ path: string,
+): Promise<{ files: unknown[]; path: string }> {
+ try {
+ const response = await fileManagerApi.get("/ssh/listFiles", {
+ params: { sessionId, path },
+ });
+ return response.data || { files: [], path };
+ } catch (error) {
+ handleApiError(error, "list SSH files");
+ return { files: [], path };
+ }
+}
+
+export async function identifySSHSymlink(
+ sessionId: string,
+ path: string,
+): Promise<{ path: string; target: string; type: "directory" | "file" }> {
+ try {
+ const response = await fileManagerApi.get("/ssh/identifySymlink", {
+ params: { sessionId, path },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "identify SSH symlink");
+ }
+}
+
+export async function resolveSSHPath(
+ sessionId: string,
+ path: string,
+): Promise<string> {
+ try {
+ const response = await fileManagerApi.get("/ssh/resolvePath", {
+ params: { sessionId, path },
+ });
+ return response.data?.resolvedPath || path;
+ } catch {
+ return path;
+ }
+}
+
+export async function readSSHFile(
+ sessionId: string,
+ path: string,
+): Promise<{
+ content: string;
+ path: string;
+ encoding?: "base64" | "utf8";
+}> {
+ try {
+ const response = await fileManagerApi.get("/ssh/readFile", {
+ params: { sessionId, path },
+ });
+ return response.data;
+ } catch (error: unknown) {
+ if (error.response?.status === 404) {
+ const customError = new Error("File not found");
+ (
+ customError as Error & { response?: unknown; isFileNotFound?: boolean }
+ ).response = error.response;
+ (
+ customError as Error & { response?: unknown; isFileNotFound?: boolean }
+ ).isFileNotFound = error.response.data?.fileNotFound || true;
+ throw customError;
+ }
+ handleApiError(error, "read SSH file");
+ }
+}
+
+export async function writeSSHFile(
+ sessionId: string,
+ path: string,
+ content: string,
+ hostId?: number,
+ userId?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post("/ssh/writeFile", {
+ sessionId,
+ path,
+ content,
+ hostId,
+ userId,
+ });
+
+ if (
+ response.data &&
+ (response.data.message === "File written successfully" ||
+ response.status === 200)
+ ) {
+ return response.data;
+ } else {
+ throw new Error("File write operation did not return success status");
+ }
+ } catch (error) {
+ handleApiError(error, "write SSH file");
+ }
+}
+
+export async function uploadSSHFile(
+ sessionId: string,
+ path: string,
+ fileName: string,
+ content: string,
+ hostId?: number,
+ userId?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post("/ssh/uploadFile", {
+ sessionId,
+ path,
+ fileName,
+ content,
+ hostId,
+ userId,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "upload SSH file");
+ }
+}
+
+export async function downloadSSHFile(
+ sessionId: string,
+ filePath: string,
+ hostId?: number,
+ userId?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post("/ssh/downloadFile", {
+ sessionId,
+ path: filePath,
+ hostId,
+ userId,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "download SSH file");
+ }
+}
+
+export async function downloadSSHFileStream(
+ sessionId: string,
+ filePath: string,
+): Promise<void> {
+ const response = await fileManagerApi.post(
+ "/ssh/downloadFileStream",
+ { sessionId, path: filePath },
+ { responseType: "blob" },
+ );
+ const blob = response.data as Blob;
+ const fileName = filePath.split("/").pop() || "download";
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = fileName;
+ a.click();
+ URL.revokeObjectURL(url);
+}
+
+export async function createSSHFile(
+ sessionId: string,
+ path: string,
+ fileName: string,
+ content: string = "",
+ hostId?: number,
+ userId?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post("/ssh/createFile", {
+ sessionId,
+ path,
+ fileName,
+ content,
+ hostId,
+ userId,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "create SSH file");
+ }
+}
+
+export async function createSSHFolder(
+ sessionId: string,
+ path: string,
+ folderName: string,
+ hostId?: number,
+ userId?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post("/ssh/createFolder", {
+ sessionId,
+ path,
+ folderName,
+ hostId,
+ userId,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "create SSH folder");
+ }
+}
+
+export async function deleteSSHItem(
+ sessionId: string,
+ path: string,
+ isDirectory: boolean,
+ hostId?: number,
+ userId?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.delete("/ssh/deleteItem", {
+ data: {
+ sessionId,
+ path,
+ isDirectory,
+ hostId,
+ userId,
+ },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "delete SSH item");
+ }
+}
+
+export async function setSudoPassword(
+ sessionId: string,
+ password: string,
+): Promise<void> {
+ try {
+ await fileManagerApi.post("/sudo-password", {
+ sessionId,
+ password,
+ });
+ } catch (error) {
+ handleApiError(error, "set sudo password");
+ }
+}
+
+export async function copySSHItem(
+ sessionId: string,
+ sourcePath: string,
+ targetDir: string,
+ hostId?: number,
+ userId?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.post(
+ "/ssh/copyItem",
+ {
+ sessionId,
+ sourcePath,
+ targetDir,
+ hostId,
+ userId,
+ },
+ {
+ timeout: 60000,
+ },
+ );
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "copy SSH item");
+ throw error;
+ }
+}
+
+export async function renameSSHItem(
+ sessionId: string,
+ oldPath: string,
+ newName: string,
+ hostId?: number,
+ userId?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.put("/ssh/renameItem", {
+ sessionId,
+ oldPath,
+ newName,
+ hostId,
+ userId,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "rename SSH item");
+ throw error;
+ }
+}
+
+export async function moveSSHItem(
+ sessionId: string,
+ oldPath: string,
+ newPath: string,
+ hostId?: number,
+ userId?: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await fileManagerApi.put(
+ "/ssh/moveItem",
+ {
+ sessionId,
+ oldPath,
+ newPath,
+ hostId,
+ userId,
+ },
+ {
+ timeout: 60000,
+ },
+ );
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "move SSH item");
+ throw error;
+ }
+}
+
+export async function changeSSHPermissions(
+ sessionId: string,
+ path: string,
+ permissions: string,
+ hostId?: number,
+ userId?: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ fileLogger.info("Changing SSH file permissions", {
+ operation: "change_permissions",
+ sessionId,
+ path,
+ permissions,
+ hostId,
+ userId,
+ });
+
+ const response = await fileManagerApi.post("/ssh/changePermissions", {
+ sessionId,
+ path,
+ permissions,
+ hostId,
+ userId,
+ });
+
+ fileLogger.success("SSH file permissions changed successfully", {
+ operation: "change_permissions",
+ sessionId,
+ path,
+ permissions,
+ });
+
+ return response.data;
+ } catch (error) {
+ fileLogger.error("Failed to change SSH file permissions", error, {
+ operation: "change_permissions",
+ sessionId,
+ path,
+ permissions,
+ });
+ handleApiError(error, "change SSH permissions");
+ throw error;
+ }
+}
+
+export async function extractSSHArchive(
+ sessionId: string,
+ archivePath: string,
+ extractPath?: string,
+ hostId?: number,
+ userId?: string,
+): Promise<{ success: boolean; message: string; extractPath: string }> {
+ try {
+ fileLogger.info("Extracting archive", {
+ operation: "extract_archive",
+ sessionId,
+ archivePath,
+ extractPath,
+ hostId,
+ userId,
+ });
+
+ const response = await fileManagerApi.post("/ssh/extractArchive", {
+ sessionId,
+ archivePath,
+ extractPath,
+ hostId,
+ userId,
+ });
+
+ fileLogger.success("Archive extracted successfully", {
+ operation: "extract_archive",
+ sessionId,
+ archivePath,
+ extractPath: response.data.extractPath,
+ });
+
+ return response.data;
+ } catch (error) {
+ fileLogger.error("Failed to extract archive", error, {
+ operation: "extract_archive",
+ sessionId,
+ archivePath,
+ extractPath,
+ });
+ handleApiError(error, "extract archive");
+ throw error;
+ }
+}
+
+export async function compressSSHFiles(
+ sessionId: string,
+ paths: string[],
+ archiveName: string,
+ format?: string,
+ hostId?: number,
+ userId?: string,
+): Promise<{ success: boolean; message: string; archivePath: string }> {
+ try {
+ fileLogger.info("Compressing files", {
+ operation: "compress_files",
+ sessionId,
+ paths,
+ archiveName,
+ format,
+ hostId,
+ userId,
+ });
+
+ const response = await fileManagerApi.post("/ssh/compressFiles", {
+ sessionId,
+ paths,
+ archiveName,
+ format: format || "zip",
+ hostId,
+ userId,
+ });
+
+ fileLogger.success("Files compressed successfully", {
+ operation: "compress_files",
+ sessionId,
+ paths,
+ archivePath: response.data.archivePath,
+ });
+
+ return response.data;
+ } catch (error) {
+ fileLogger.error("Failed to compress files", error, {
+ operation: "compress_files",
+ sessionId,
+ paths,
+ archiveName,
+ format,
+ });
+ handleApiError(error, "compress files");
+ throw error;
+ }
+}
+
+// ============================================================================
+
+export type HostConnectionState =
+ | "disconnected"
+ | "connecting"
+ | "ready"
+ | "auth_required"
+ | "error";
+
+export interface EnsureSSHSessionResult {
+ state: HostConnectionState;
+ sessionId?: string;
+ error?: string;
+}
+
+export async function ensureSSHSessionForHost(
+ host: SSHHost,
+): Promise<EnsureSSHSessionResult> {
+ const sessionId = host.id.toString();
+ try {
+ const status = await getSSHStatus(sessionId);
+ if (status?.connected) {
+ return { state: "ready", sessionId };
+ }
+ } catch {
+ // not connected — fall through to connect
+ }
+
+ try {
+ const result = await connectSSH(sessionId, {
+ hostId: host.id,
+ ip: host.ip,
+ port: host.port,
+ username: host.username,
+ password: host.password,
+ sshKey: host.key,
+ keyPassword: host.keyPassword,
+ authType: host.authType,
+ credentialId: host.credentialId,
+ userId: host.userId,
+ forceKeyboardInteractive: host.forceKeyboardInteractive,
+ jumpHosts: host.jumpHosts,
+ useSocks5: host.useSocks5,
+ socks5Host: host.socks5Host,
+ socks5Port: host.socks5Port,
+ socks5Username: host.socks5Username,
+ socks5Password: host.socks5Password,
+ socks5ProxyChain: host.socks5ProxyChain,
+ });
+
+ if (
+ result?.requires_totp ||
+ result?.requires_warpgate ||
+ result?.status === "auth_required"
+ ) {
+ return { state: "auth_required", sessionId };
+ }
+
+ return { state: "ready", sessionId };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : "Connection failed";
+ return { state: "error", error: message };
+ }
+}
+
+export interface BrowseSSHDirectoryResult {
+ status: "ok" | "not_found" | "error";
+ path: string;
+ files: Array<{ name: string; type: "file" | "directory" | "link" }>;
+}
+
+export async function browseSSHDirectory(
+ sessionId: string,
+ path: string,
+): Promise<BrowseSSHDirectoryResult> {
+ try {
+ const result = await listSSHFiles(sessionId, path);
+ return {
+ status: "ok",
+ path: result.path,
+ files: result.files as Array<{
+ name: string;
+ type: "file" | "directory" | "link";
+ }>,
+ };
+ } catch (err) {
+ const status =
+ (err as { response?: { status?: number } })?.response?.status === 404
+ ? "not_found"
+ : "error";
+ return { status, path, files: [] };
+ }
+}
diff --git a/src/ui/api/ssh-host-management-api.ts b/src/ui/api/ssh-host-management-api.ts
new file mode 100644
index 000000000..2d70263aa
--- /dev/null
+++ b/src/ui/api/ssh-host-management-api.ts
@@ -0,0 +1,235 @@
+import { AxiosError } from "axios";
+import { getAllServerStatuses, handleApiError, sshHostApi } from "@/main-axios";
+import type { SSHHost, SSHHostData, ProxyNode } from "@/types/index";
+import type { ServerStatus, SSHHostWithStatus } from "@/main-axios";
+
+// SSH HOST MANAGEMENT
+// ============================================================================
+
+export async function getSSHHosts(): Promise<SSHHostWithStatus[]> {
+ try {
+ const hostsResponse = await sshHostApi.get("/db/host");
+ const hosts: SSHHost[] = Array.isArray(hostsResponse.data)
+ ? hostsResponse.data
+ : [];
+
+ let statuses: Record<number, ServerStatus> = {};
+ try {
+ statuses = (await getAllServerStatuses()) || {};
+ } catch {
+ // Status fetch failure should not prevent host list from loading
+ }
+
+ return hosts.map((host) => ({
+ ...host,
+ status: statuses[host.id]?.status || "unknown",
+ }));
+ } catch (error) {
+ throw handleApiError(error, "fetch SSH hosts");
+ }
+}
+
+export async function createSSHHost(hostData: SSHHostData): Promise<SSHHost> {
+ try {
+ if (hostData.authType === "key" && hostData.key instanceof File) {
+ const formData = new FormData();
+ formData.append("key", hostData.key);
+ const dataWithoutFile = { ...hostData, key: undefined };
+ formData.append("data", JSON.stringify(dataWithoutFile));
+ const response = await sshHostApi.post("/db/host", formData, {
+ headers: { "Content-Type": "multipart/form-data" },
+ });
+ return response.data;
+ }
+ const response = await sshHostApi.post("/db/host", hostData);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "create SSH host");
+ }
+}
+
+export async function updateSSHHost(
+ hostId: number,
+ hostData: SSHHostData,
+): Promise<SSHHost> {
+ try {
+ if (hostData.authType === "key" && hostData.key instanceof File) {
+ const formData = new FormData();
+ formData.append("key", hostData.key);
+ const dataWithoutFile = { ...hostData, key: undefined };
+ formData.append("data", JSON.stringify(dataWithoutFile));
+ const response = await sshHostApi.put(`/db/host/${hostId}`, formData, {
+ headers: { "Content-Type": "multipart/form-data" },
+ });
+ return response.data;
+ }
+ const response = await sshHostApi.put(`/db/host/${hostId}`, hostData);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "update SSH host");
+ }
+}
+
+export async function wakeOnLan(hostId: number): Promise<{ success: boolean }> {
+ try {
+ const response = await sshHostApi.post(`/db/host/${hostId}/wake`);
+ return response.data;
+ } catch (error) {
+ throw handleApiError(error, "wake on LAN");
+ }
+}
+
+export async function bulkImportSSHHosts(
+ hosts: SSHHostData[],
+ overwrite = false,
+): Promise<{
+ message: string;
+ success: number;
+ updated: number;
+ skipped: number;
+ failed: number;
+ errors: string[];
+}> {
+ try {
+ const response = await sshHostApi.post("/bulk-import", {
+ hosts,
+ overwrite,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "bulk import SSH hosts");
+ }
+}
+
+export async function bulkUpdateSSHHosts(
+ hostIds: number[],
+ updates: Record<string, unknown>,
+): Promise<{ updated: number; failed: number; errors: string[] }> {
+ try {
+ const response = await sshHostApi.patch("/bulk-update", {
+ hostIds,
+ updates,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "bulk update SSH hosts");
+ }
+}
+
+export async function deleteSSHHost(
+ hostId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.delete(`/db/host/${hostId}`);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "delete SSH host");
+ }
+}
+
+export async function getSSHHostById(hostId: number): Promise<SSHHost> {
+ try {
+ const response = await sshHostApi.get(`/db/host/${hostId}`);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch SSH host");
+ }
+}
+
+export async function exportSSHHostWithCredentials(
+ hostId: number,
+): Promise<SSHHost> {
+ try {
+ const response = await sshHostApi.get(`/db/host/${hostId}/export`);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "export SSH host with credentials");
+ }
+}
+
+export async function exportAllSSHHosts(): Promise<{
+ hosts: SSHHost[];
+}> {
+ try {
+ const response = await sshHostApi.get("/db/hosts/export");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "export all SSH hosts");
+ }
+}
+
+// ============================================================================
+// SSH AUTOSTART MANAGEMENT
+// ============================================================================
+
+export async function enableAutoStart(
+ sshConfigId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.post("/autostart/enable", {
+ sshConfigId,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "enable autostart");
+ }
+}
+
+export async function disableAutoStart(
+ sshConfigId: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await sshHostApi.delete("/autostart/disable", {
+ data: { sshConfigId },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "disable autostart");
+ }
+}
+
+export async function getAutoStartStatus(): Promise<{
+ autostart_configs: Array<{
+ sshConfigId: number;
+ host: string;
+ port: number;
+ username: string;
+ authType: string;
+ }>;
+ total_count: number;
+}> {
+ try {
+ const response = await sshHostApi.get("/autostart/status");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch autostart status");
+ }
+}
+
+// ============================================================================
+// PROXY CONNECTIVITY TEST
+// ============================================================================
+
+export async function testProxyConnection(options: {
+ singleProxy?: {
+ host: string;
+ port: number;
+ type?: 4 | 5 | "http";
+ username?: string;
+ password?: string;
+ };
+ proxyChain?: ProxyNode[];
+ testTarget?: { host: string; port: number };
+}): Promise<{ success: boolean; latencyMs?: number; error?: string }> {
+ try {
+ const response = await sshHostApi.post("/db/proxy/test", options);
+ return response.data;
+ } catch (error) {
+ if (error instanceof AxiosError && error.response?.data?.error) {
+ return { success: false, error: error.response.data.error };
+ }
+ handleApiError(error, "test proxy connection");
+ }
+}
+
+// ============================================================================
diff --git a/src/ui/api/system-status-api.ts b/src/ui/api/system-status-api.ts
new file mode 100644
index 000000000..63e42b729
--- /dev/null
+++ b/src/ui/api/system-status-api.ts
@@ -0,0 +1,177 @@
+import { AxiosError } from "axios";
+import {
+ authApi,
+ handleApiError,
+ isElectron,
+ markUserAuthenticated,
+} from "@/main-axios";
+import type { AuthResponse } from "@/main-axios";
+
+// ALERTS
+// ============================================================================
+
+export async function setupTOTP(): Promise<{
+ secret: string;
+ qr_code: string;
+}> {
+ try {
+ const response = await authApi.post("/users/totp/setup");
+ return response.data;
+ } catch (error) {
+ handleApiError(error as AxiosError, "setup TOTP");
+ throw error;
+ }
+}
+
+export async function enableTOTP(
+ totp_code: string,
+): Promise<{ message: string; backup_codes: string[] }> {
+ try {
+ const response = await authApi.post("/users/totp/enable", { totp_code });
+ return response.data;
+ } catch (error) {
+ handleApiError(error as AxiosError, "enable TOTP");
+ throw error;
+ }
+}
+
+export async function disableTOTP(
+ password?: string,
+ totp_code?: string,
+): Promise<{ message: string }> {
+ try {
+ const response = await authApi.post("/users/totp/disable", {
+ password,
+ totp_code,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error as AxiosError, "disable TOTP");
+ throw error;
+ }
+}
+
+export async function verifyTOTPLogin(
+ temp_token: string,
+ totp_code: string,
+ rememberMe: boolean = false,
+): Promise<AuthResponse> {
+ try {
+ const response = await authApi.post("/users/totp/verify-login", {
+ temp_token,
+ totp_code,
+ rememberMe,
+ });
+
+ const isInIframe =
+ typeof window !== "undefined" && window.self !== window.top;
+
+ if (isInIframe && isElectron() && response.data.success) {
+ try {
+ window.parent.postMessage(
+ {
+ type: "AUTH_SUCCESS",
+ source: "totp_verify",
+ platform: "desktop",
+ timestamp: Date.now(),
+ },
+ window.location.origin,
+ );
+ } catch (e) {
+ console.error("[main-axios] Error posting message to parent:", e);
+ }
+ }
+
+ if (response.data.success) {
+ markUserAuthenticated();
+ }
+
+ return response.data;
+ } catch (error) {
+ handleApiError(error as AxiosError, "verify TOTP login");
+ throw error;
+ }
+}
+
+export async function generateBackupCodes(
+ password?: string,
+ totp_code?: string,
+): Promise<{ backup_codes: string[] }> {
+ try {
+ const response = await authApi.post("/users/totp/backup-codes", {
+ password,
+ totp_code,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error as AxiosError, "generate backup codes");
+ throw error;
+ }
+}
+
+export async function getUserAlerts(): Promise<{
+ alerts: Array<Record<string, unknown>>;
+}> {
+ try {
+ const response = await authApi.get(`/alerts`);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch user alerts");
+ throw error;
+ }
+}
+
+export async function dismissAlert(
+ alertId: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/alerts/dismiss", { alertId });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "dismiss alert");
+ throw error;
+ }
+}
+
+// ============================================================================
+// UPDATES & RELEASES
+// ============================================================================
+
+export async function getReleasesRSS(
+ perPage: number = 100,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get(`/releases/rss?per_page=${perPage}`);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch releases RSS");
+ }
+}
+
+export async function getVersionInfo(
+ checkRemote = true,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get(
+ `/version${checkRemote ? "" : "?checkRemote=false"}`,
+ );
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch version info");
+ }
+}
+
+// ============================================================================
+// DATABASE HEALTH
+// ============================================================================
+
+export async function getDatabaseHealth(): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.get("/health");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "check database health");
+ }
+}
+
+// ============================================================================
diff --git a/src/ui/api/tunnel-api.ts b/src/ui/api/tunnel-api.ts
new file mode 100644
index 000000000..311dc73f8
--- /dev/null
+++ b/src/ui/api/tunnel-api.ts
@@ -0,0 +1,142 @@
+import axios from "axios";
+import { authApi, handleApiError, tunnelApi } from "@/main-axios";
+import type {
+ C2STunnelPreset,
+ TunnelConfig,
+ TunnelConnection,
+ TunnelStatus,
+} from "@/types/index";
+
+// TUNNEL MANAGEMENT
+// ============================================================================
+
+export async function getTunnelStatuses(): Promise<
+ Record<string, TunnelStatus>
+> {
+ try {
+ const response = await tunnelApi.get("/tunnel/status");
+ return response.data || {};
+ } catch (error) {
+ handleApiError(error, "fetch tunnel statuses");
+ }
+}
+
+export function subscribeTunnelStatuses(
+ onStatuses: (statuses: Record<string, TunnelStatus>) => void,
+ onError?: () => void,
+): () => void {
+ const baseURL = (tunnelApi.defaults.baseURL || "").replace(/\/$/, "");
+ const source = new EventSource(`${baseURL}/tunnel/status/stream`, {
+ withCredentials: true,
+ });
+
+ source.addEventListener("statuses", (event) => {
+ try {
+ onStatuses(JSON.parse(event.data) as Record<string, TunnelStatus>);
+ } catch {
+ onError?.();
+ }
+ });
+
+ source.onerror = () => {
+ onError?.();
+ };
+
+ return () => source.close();
+}
+
+export async function getTunnelStatusByName(
+ tunnelName: string,
+): Promise<TunnelStatus | undefined> {
+ const statuses = await getTunnelStatuses();
+ return statuses[tunnelName];
+}
+
+export async function connectTunnel(
+ tunnelConfig: TunnelConfig,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await tunnelApi.post("/tunnel/connect", tunnelConfig);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "connect tunnel");
+ }
+}
+
+export async function disconnectTunnel(
+ tunnelName: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await tunnelApi.post("/tunnel/disconnect", { tunnelName });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "disconnect tunnel");
+ }
+}
+
+export async function cancelTunnel(
+ tunnelName: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await tunnelApi.post("/tunnel/cancel", { tunnelName });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "cancel tunnel");
+ }
+}
+
+export async function getC2STunnelPresets(): Promise<C2STunnelPreset[]> {
+ try {
+ const response = await authApi.get("/c2s-tunnel-presets");
+ return response.data || [];
+ } catch (error) {
+ if (axios.isAxiosError(error) && error.response?.status === 404) {
+ return [];
+ }
+ handleApiError(error, "fetch client tunnel presets");
+ }
+}
+
+export async function createC2STunnelPreset(data: {
+ name: string;
+ config: TunnelConnection[];
+ platform?: string;
+ computerName?: string;
+}): Promise<C2STunnelPreset> {
+ try {
+ const response = await authApi.post("/c2s-tunnel-presets", data);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "create client tunnel preset");
+ }
+}
+
+export async function updateC2STunnelPreset(
+ id: number,
+ data: Partial<{
+ name: string;
+ config: TunnelConnection[];
+ platform: string;
+ computerName: string;
+ }>,
+): Promise<C2STunnelPreset> {
+ try {
+ const response = await authApi.put(`/c2s-tunnel-presets/${id}`, data);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "update client tunnel preset");
+ }
+}
+
+export async function deleteC2STunnelPreset(
+ id: number,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.delete(`/c2s-tunnel-presets/${id}`);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "delete client tunnel preset");
+ }
+}
+
+// ============================================================================
diff --git a/src/ui/api/user-management-api.ts b/src/ui/api/user-management-api.ts
new file mode 100644
index 000000000..0ea072742
--- /dev/null
+++ b/src/ui/api/user-management-api.ts
@@ -0,0 +1,254 @@
+import { authApi, handleApiError } from "@/main-axios";
+import type { UserInfo } from "@/main-axios";
+
+// USER MANAGEMENT
+// ============================================================================
+
+export async function getUserList(): Promise<{ users: UserInfo[] }> {
+ try {
+ const response = await authApi.get("/users/list");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch user list");
+ }
+}
+
+export async function getSessions(): Promise<{
+ sessions: {
+ id: string;
+ userId: string;
+ username?: string;
+ deviceType: string;
+ deviceInfo: string;
+ createdAt: string;
+ expiresAt: string;
+ lastActiveAt: string;
+ isRevoked?: boolean;
+ isCurrentSession?: boolean;
+ }[];
+}> {
+ try {
+ const response = await authApi.get("/users/sessions");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch sessions");
+ }
+}
+
+export async function revokeSession(
+ sessionId: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await authApi.delete(`/users/sessions/${sessionId}`);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "revoke session");
+ }
+}
+
+export async function revokeAllUserSessions(
+ userId: string,
+): Promise<{ success: boolean; message: string }> {
+ try {
+ const response = await authApi.post("/users/sessions/revoke-all", {
+ targetUserId: userId,
+ exceptCurrent: false,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "revoke all user sessions");
+ }
+}
+
+export interface ApiKey {
+ id: string;
+ name: string;
+ userId: string;
+ username: string | null;
+ tokenPrefix: string;
+ createdAt: string;
+ expiresAt: string | null;
+ lastUsedAt: string | null;
+ isActive: boolean;
+}
+
+export interface CreatedApiKey extends ApiKey {
+ token: string;
+}
+
+export async function createApiKey(
+ name: string,
+ userId: string,
+ expiresAt?: string,
+): Promise<CreatedApiKey> {
+ try {
+ const response = await authApi.post("/users/api-keys", {
+ name,
+ userId,
+ expiresAt: expiresAt ?? null,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "create API key");
+ }
+}
+
+export async function getApiKeys(): Promise<{ apiKeys: ApiKey[] }> {
+ try {
+ const response = await authApi.get("/users/api-keys");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "fetch API keys");
+ }
+}
+
+export async function deleteApiKey(
+ keyId: string,
+): Promise<{ success: boolean }> {
+ try {
+ const response = await authApi.delete(`/users/api-keys/${keyId}`);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "delete API key");
+ }
+}
+
+export async function makeUserAdmin(
+ userId: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/users/make-admin", { userId });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "make user admin");
+ }
+}
+
+export async function removeAdminStatus(
+ userId: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/users/remove-admin", { userId });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "remove admin status");
+ }
+}
+
+export async function deleteUser(
+ username: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.delete("/users/delete-user", {
+ data: { username },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "delete user");
+ }
+}
+
+export async function deleteAccount(
+ password: string,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.delete("/users/delete-account", {
+ data: { password },
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "delete account");
+ }
+}
+
+export async function updateRegistrationAllowed(
+ allowed: boolean,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.patch("/users/registration-allowed", {
+ allowed,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "update registration allowed");
+ }
+}
+
+export async function getOidcAutoProvision(): Promise<{ enabled: boolean }> {
+ try {
+ const response = await authApi.get("/users/oidc-auto-provision");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "check OIDC auto-provision status");
+ }
+}
+
+export async function updateOidcAutoProvision(
+ enabled: boolean,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.patch("/users/oidc-auto-provision", {
+ enabled,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "update OIDC auto-provision");
+ }
+}
+
+export async function updatePasswordLoginAllowed(
+ allowed: boolean,
+): Promise<{ allowed: boolean }> {
+ try {
+ const response = await authApi.patch("/users/password-login-allowed", {
+ allowed,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "update password login allowed");
+ }
+}
+
+export async function getPasswordResetAllowed(): Promise<boolean> {
+ try {
+ const response = await authApi.get("/users/password-reset-allowed");
+ return response.data.allowed;
+ } catch (error) {
+ handleApiError(error, "get password reset allowed");
+ }
+}
+
+export async function updatePasswordResetAllowed(
+ allowed: boolean,
+): Promise<{ allowed: boolean }> {
+ try {
+ const response = await authApi.patch("/users/password-reset-allowed", {
+ allowed,
+ });
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "update password reset allowed");
+ }
+}
+
+export async function updateOIDCConfig(
+ config: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.post("/users/oidc-config", config);
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "update OIDC config");
+ }
+}
+
+export async function disableOIDCConfig(): Promise<Record<string, unknown>> {
+ try {
+ const response = await authApi.delete("/users/oidc-config");
+ return response.data;
+ } catch (error) {
+ handleApiError(error, "disable OIDC config");
+ }
+}
+
+// ============================================================================
diff --git a/src/ui/auth/Auth.tsx b/src/ui/auth/Auth.tsx
index ab6e8d5ff..3c1408a8c 100644
--- a/src/ui/auth/Auth.tsx
+++ b/src/ui/auth/Auth.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components */
import { useState, useEffect, useCallback, useRef } from "react";
import { Button } from "@/components/button";
import { Input } from "@/components/input";
@@ -31,6 +32,7 @@ import {
saveServerConfig,
isElectron,
getEmbeddedServerStatus,
+ getCurrentToken,
} from "@/main-axios";
import { ElectronServerConfig as ServerConfigComponent } from "@/auth/ElectronServerConfig";
import { ElectronLoginForm } from "@/auth/ElectronLoginForm";
@@ -114,9 +116,15 @@ interface AuthProps {
interface ExtendedWindow extends Window {
IS_ELECTRON_WEBVIEW?: boolean;
+ ReactNativeWebView?: { postMessage: (msg: string) => void };
}
+const isInMobileWebView = () =>
+ /Termix-Mobile\/(Android|iOS)/.test(navigator.userAgent) ||
+ !!(window as ExtendedWindow).ReactNativeWebView;
+
const isInElectronWebView = () => {
+ if (isInMobileWebView()) return false;
if ((window as ExtendedWindow).IS_ELECTRON_WEBVIEW) return true;
try {
if (window.self !== window.top) return true;
@@ -253,7 +261,9 @@ export function Auth({ onLogin }: AuthProps) {
useEffect(() => {
try {
localStorage.setItem("rememberMe", rememberMe.toString());
- } catch {}
+ } catch {
+ // Ignore storage failures; auth state still works for the current session.
+ }
}, [rememberMe]);
useEffect(() => {
@@ -339,6 +349,32 @@ export function Auth({ onLogin }: AuthProps) {
return;
}
if (success) {
+ if (isInMobileWebView()) {
+ // The OIDC callback authenticated via an HttpOnly cookie on this origin,
+ // so the token isn't in localStorage. Prefer a token passed in the URL
+ // (termix-mobile:-origin callbacks include one), otherwise read it back
+ // from the cookie via /users/me/token before handing it to the app.
+ const postToken = (token: string) => {
+ (window as ExtendedWindow).ReactNativeWebView?.postMessage(
+ JSON.stringify({ type: "AUTH_SUCCESS", token }),
+ );
+ setWebviewAuthSuccess(true);
+ window.history.replaceState(
+ {},
+ document.title,
+ window.location.pathname,
+ );
+ };
+ const urlToken = urlParams.get("token");
+ if (urlToken) {
+ postToken(urlToken);
+ } else {
+ getCurrentToken()
+ .then((token) => postToken(token ?? ""))
+ .catch(() => postToken(""));
+ }
+ return;
+ }
if (isInElectronWebView()) {
window.parent.postMessage(
{
@@ -442,6 +478,15 @@ export function Auth({ onLogin }: AuthProps) {
return;
}
if (!res?.success) throw new Error(t("errors.loginFailed"));
+ if (isInMobileWebView()) {
+ // Native-app requests get the JWT in the login response body.
+ const token = res?.token ?? "";
+ (window as ExtendedWindow).ReactNativeWebView?.postMessage(
+ JSON.stringify({ type: "AUTH_SUCCESS", token }),
+ );
+ setWebviewAuthSuccess(true);
+ return;
+ }
if (isInElectronWebView()) {
window.parent.postMessage(
{
@@ -534,6 +579,15 @@ export function Auth({ onLogin }: AuthProps) {
try {
const res = await verifyTOTPLogin(totpTempToken, totpCode, rememberMe);
if (!res?.success) throw new Error(t("errors.loginFailed"));
+ if (isInMobileWebView()) {
+ // Native-app requests get the JWT in the login response body.
+ const token = res?.token ?? "";
+ (window as ExtendedWindow).ReactNativeWebView?.postMessage(
+ JSON.stringify({ type: "AUTH_SUCCESS", token }),
+ );
+ setWebviewAuthSuccess(true);
+ return;
+ }
if (isInElectronWebView()) {
window.parent.postMessage(
{
@@ -684,7 +738,7 @@ export function Auth({ onLogin }: AuthProps) {
callbackPort,
);
if (result.success && result.token) {
- localStorage.setItem("jwt_token", result.token);
+ localStorage.setItem("jwt", result.token);
window.location.reload();
return;
}
diff --git a/src/ui/auth/ElectronLoginForm.tsx b/src/ui/auth/ElectronLoginForm.tsx
index affa510e2..24224f892 100644
--- a/src/ui/auth/ElectronLoginForm.tsx
+++ b/src/ui/auth/ElectronLoginForm.tsx
@@ -46,7 +46,7 @@ export function ElectronLoginForm({
localStorage.setItem("jwt", token);
}
await onAuthSuccessRef.current(token);
- } catch (_err) {
+ } catch {
setError(t("errors.authTokenSaveFailed"));
isAuthenticatingRef.current = false;
setIsAuthenticating(false);
diff --git a/src/ui/auth/ElectronServerConfig.tsx b/src/ui/auth/ElectronServerConfig.tsx
index d5051a81d..65137c3c3 100644
--- a/src/ui/auth/ElectronServerConfig.tsx
+++ b/src/ui/auth/ElectronServerConfig.tsx
@@ -3,6 +3,7 @@ import { Button } from "@/components/button.tsx";
import { Input } from "@/components/input.tsx";
import { Label } from "@/components/label.tsx";
import { Alert, AlertTitle, AlertDescription } from "@/components/alert.tsx";
+import { Switch } from "@/components/switch.tsx";
import { useTranslation } from "react-i18next";
import {
getServerConfig,
@@ -28,6 +29,7 @@ export function ElectronServerConfig({
}: ServerConfigProps) {
const { t } = useTranslation();
const [serverUrl, setServerUrl] = useState("");
+ const [allowInvalidCertificate, setAllowInvalidCertificate] = useState(false);
const [loading, setLoading] = useState(false);
const [embeddedLoading, setEmbeddedLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -46,6 +48,7 @@ export function ElectronServerConfig({
if (config?.serverUrl) {
setServerUrl(config.serverUrl);
}
+ setAllowInvalidCertificate(!!config?.allowInvalidCertificate);
} catch (error) {
console.error("Server config operation failed:", error);
}
@@ -141,6 +144,8 @@ export function ElectronServerConfig({
const config: ServerConfig = {
serverUrl: normalizedUrl,
lastUpdated: new Date().toISOString(),
+ allowInvalidCertificate:
+ normalizedUrl.startsWith("https://") && allowInvalidCertificate,
};
const success = await saveServerConfig(config);
@@ -225,6 +230,25 @@ export function ElectronServerConfig({
/>
</div>
+ {serverUrl.trim().startsWith("https://") && (
+ <div className="flex items-start justify-between gap-3 border border-border bg-muted/20 p-3">
+ <div className="flex flex-col gap-1">
+ <Label htmlFor="allow-invalid-certificate">
+ {t("serverConfig.allowInvalidCertificate")}
+ </Label>
+ <p className="text-xs text-muted-foreground">
+ {t("serverConfig.allowInvalidCertificateDesc")}
+ </p>
+ </div>
+ <Switch
+ id="allow-invalid-certificate"
+ checked={allowInvalidCertificate}
+ onCheckedChange={setAllowInvalidCertificate}
+ disabled={loading || embeddedLoading}
+ />
+ </div>
+ )}
+
{error && (
<Alert variant="destructive">
<AlertTitle>{t("common.error")}</AlertTitle>
diff --git a/src/ui/auth/LoginPage.tsx b/src/ui/auth/LoginPage.tsx
index 0569958df..a36d1a0e1 100644
--- a/src/ui/auth/LoginPage.tsx
+++ b/src/ui/auth/LoginPage.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect, useCallback, useRef } from "react";
import { Button } from "@/components/button.tsx";
import { Input } from "@/components/input.tsx";
@@ -28,6 +29,7 @@ import {
saveServerConfig,
isElectron,
getEmbeddedServerStatus,
+ getCurrentToken,
} from "@/main-axios";
import { ElectronServerConfig as ServerConfigComponent } from "@/auth/ElectronServerConfig.tsx";
import { ElectronLoginForm } from "@/auth/ElectronLoginForm.tsx";
@@ -36,21 +38,15 @@ import {
shouldTriggerSilentSignin,
} from "./silent-signin";
-function isMissingServerConfigError(error: unknown): boolean {
- if (!(error instanceof Error)) {
- return false;
- }
-
- return (
- (error as Error & { code?: string }).code === "NO_SERVER_CONFIGURED" ||
- error.message.includes("no-server-configured")
- );
-}
-
interface ExtendedWindow extends Window {
IS_ELECTRON_WEBVIEW?: boolean;
+ ReactNativeWebView?: { postMessage: (msg: string) => void };
}
+const isInMobileWebView = () =>
+ /Termix-Mobile\/(Android|iOS)/.test(navigator.userAgent) ||
+ !!(window as ExtendedWindow).ReactNativeWebView;
+
interface AuthProps extends React.ComponentProps<"div"> {
setLoggedIn: (loggedIn: boolean) => void;
setIsAdmin: (isAdmin: boolean) => void;
@@ -91,7 +87,8 @@ export function Auth({
window.matchMedia("(prefers-color-scheme: dark)").matches);
const lineColor = isDarkMode ? "#151517" : "#f9f9f9";
- const isInElectronWebView = () => {
+ const isInElectronWebView = useCallback(() => {
+ if (isInMobileWebView()) return false;
if ((window as ExtendedWindow).IS_ELECTRON_WEBVIEW) {
return true;
}
@@ -103,7 +100,7 @@ export function Auth({
return true;
}
return false;
- };
+ }, []);
const [tab, setTab] = useState<"login" | "signup" | "external" | "reset">(
"login",
@@ -147,6 +144,15 @@ export function Auth({
const [webviewAuthSuccess, setWebviewAuthSuccess] = useState(false);
const totpInputRef = React.useRef<HTMLInputElement>(null);
+ // Hand the JWT to the native app embedding this page in a React Native WebView.
+ // The mobile onMessage handler only reads { type, token }.
+ const postMobileAuthSuccess = useCallback((token: string) => {
+ (window as ExtendedWindow).ReactNativeWebView?.postMessage(
+ JSON.stringify({ type: "AUTH_SUCCESS", token }),
+ );
+ setWebviewAuthSuccess(true);
+ }, []);
+
const [showServerConfig, setShowServerConfig] = useState<boolean | null>(
null,
);
@@ -154,54 +160,51 @@ export function Auth({
const [dbConnectionFailed, setDbConnectionFailed] = useState(false);
const [dbHealthChecking, setDbHealthChecking] = useState(false);
- const handleElectronAuthSuccess = useCallback(
- async (token: string | null) => {
- try {
- // token was stored in localStorage by ElectronLoginForm before this runs,
- // so getUserInfo() can authenticate via the cookie interceptor or localStorage jwt.
- let retries = 5;
- let meRes = null;
- while (retries-- > 0) {
- try {
- meRes = await getUserInfo();
- break;
- } catch (err: unknown) {
- const isNoServer =
- (err as { code?: string })?.code === "NO_SERVER_CONFIGURED" ||
- (err as Error)?.message?.includes("no-server-configured");
- if (isNoServer && retries > 0) {
- await new Promise((r) => setTimeout(r, 500));
- } else {
- throw err;
- }
+ const handleElectronAuthSuccess = useCallback(async () => {
+ try {
+ // token was stored in localStorage by ElectronLoginForm before this runs,
+ // so getUserInfo() can authenticate via the cookie interceptor or localStorage jwt.
+ let retries = 5;
+ let meRes = null;
+ while (retries-- > 0) {
+ try {
+ meRes = await getUserInfo();
+ break;
+ } catch (err: unknown) {
+ const isNoServer =
+ (err as { code?: string })?.code === "NO_SERVER_CONFIGURED" ||
+ (err as Error)?.message?.includes("no-server-configured");
+ if (isNoServer && retries > 0) {
+ await new Promise((r) => setTimeout(r, 500));
+ } else {
+ throw err;
}
}
- if (!meRes) throw new Error("Failed to get user info");
- setInternalLoggedIn(true);
- setLoggedIn(true);
- setIsAdmin(!!meRes.is_admin);
- setUsername(meRes.username || null);
- setUserId(meRes.userId || null);
- onAuthSuccess({
- isAdmin: !!meRes.is_admin,
- username: meRes.username || null,
- userId: meRes.userId || null,
- });
- toast.success(t("messages.loginSuccess"));
- } catch {
- toast.error(t("errors.failedUserInfo"));
}
- },
- [
- onAuthSuccess,
- setLoggedIn,
- setIsAdmin,
- setUsername,
- setUserId,
- t,
- setInternalLoggedIn,
- ],
- );
+ if (!meRes) throw new Error("Failed to get user info");
+ setInternalLoggedIn(true);
+ setLoggedIn(true);
+ setIsAdmin(!!meRes.is_admin);
+ setUsername(meRes.username || null);
+ setUserId(meRes.userId || null);
+ onAuthSuccess({
+ isAdmin: !!meRes.is_admin,
+ username: meRes.username || null,
+ userId: meRes.userId || null,
+ });
+ toast.success(t("messages.loginSuccess"));
+ } catch {
+ toast.error(t("errors.failedUserInfo"));
+ }
+ }, [
+ onAuthSuccess,
+ setLoggedIn,
+ setIsAdmin,
+ setUsername,
+ setUserId,
+ t,
+ setInternalLoggedIn,
+ ]);
useEffect(() => {
setInternalLoggedIn(loggedIn);
@@ -225,7 +228,7 @@ export function Auth({
getRegistrationAllowed().then((res) => {
setRegistrationAllowed(res.allowed);
});
- }, []);
+ }, [isInElectronWebView]);
useEffect(() => {
getPasswordLoginAllowed()
@@ -342,6 +345,12 @@ export function Auth({
throw new Error(t("errors.loginFailed"));
}
+ if (isInMobileWebView()) {
+ // Native-app requests get the JWT in the login response body.
+ postMobileAuthSuccess(res.token || "");
+ return;
+ }
+
if (isInElectronWebView()) {
try {
window.parent.postMessage(
@@ -546,6 +555,13 @@ export function Auth({
throw new Error(t("errors.loginFailed"));
}
+ if (isInMobileWebView()) {
+ // Native-app requests get the JWT in the verify response body.
+ postMobileAuthSuccess(res.token || "");
+ setTotpLoading(false);
+ return;
+ }
+
if (isInElectronWebView()) {
try {
window.parent.postMessage(
@@ -700,6 +716,30 @@ export function Auth({
if (success) {
setOidcLoading(true);
+ if (isInMobileWebView()) {
+ // The OIDC callback authenticated via an HttpOnly cookie on this origin,
+ // so prefer a token in the URL (termix-mobile:-origin callbacks include
+ // one), otherwise read it back from the cookie via /users/me/token.
+ const finish = (token: string) => {
+ postMobileAuthSuccess(token);
+ setOidcLoading(false);
+ window.history.replaceState(
+ {},
+ document.title,
+ window.location.pathname,
+ );
+ };
+ const urlToken = urlParams.get("token");
+ if (urlToken) {
+ finish(urlToken);
+ } else {
+ getCurrentToken()
+ .then((token) => finish(token ?? ""))
+ .catch(() => finish(""));
+ }
+ return;
+ }
+
if (isInElectronWebView()) {
try {
const urlToken = urlParams.get("token");
@@ -1107,18 +1147,19 @@ export function Auth({
</AlertDescription>
</Alert>
)}
- {isInElectronWebView() && webviewAuthSuccess && (
- <div className="flex flex-col items-center justify-center h-64 gap-4">
- <div className="text-center">
- <h2 className="text-xl font-bold mb-2">
- {t("messages.loginSuccess")}
- </h2>
- <p className="text-muted-foreground">
- {t("auth.redirectingToApp")}
- </p>
+ {(isInElectronWebView() || isInMobileWebView()) &&
+ webviewAuthSuccess && (
+ <div className="flex flex-col items-center justify-center h-64 gap-4">
+ <div className="text-center">
+ <h2 className="text-xl font-bold mb-2">
+ {t("messages.loginSuccess")}
+ </h2>
+ <p className="text-muted-foreground">
+ {t("auth.redirectingToApp")}
+ </p>
+ </div>
</div>
- </div>
- )}
+ )}
{!webviewAuthSuccess && totpRequired && (
<form
className="flex flex-col gap-5"
diff --git a/src/ui/components/button.tsx b/src/ui/components/button.tsx
index dd09238a1..d64555901 100644
--- a/src/ui/components/button.tsx
+++ b/src/ui/components/button.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components */
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { Slot } from "radix-ui";
diff --git a/src/ui/components/folder.tsx b/src/ui/components/folder.tsx
index fd2543022..7ca7d4a40 100644
--- a/src/ui/components/folder.tsx
+++ b/src/ui/components/folder.tsx
@@ -221,15 +221,6 @@ const Root: React.FC<RootProps> = ({
.filter(Boolean) as string[];
}, []);
- const getAllItemIds = useCallback(() => {
- const items = Array.from(
- treeRef.current?.querySelectorAll('[role="treeitem"]') || [],
- );
- return items
- .map((item) => item.getAttribute("data-id"))
- .filter(Boolean) as string[];
- }, []);
-
const [treeHasFocus, setTreeHasFocus] = useState(false);
const handleTreeFocus = useCallback(() => {
diff --git a/src/ui/components/sidebar.tsx b/src/ui/components/sidebar.tsx
index d2deb02f5..2fa5a84f6 100644
--- a/src/ui/components/sidebar.tsx
+++ b/src/ui/components/sidebar.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components */
"use client";
import * as React from "react";
diff --git a/src/ui/components/theme-provider.tsx b/src/ui/components/theme-provider.tsx
index efb4bd780..441681b3f 100644
--- a/src/ui/components/theme-provider.tsx
+++ b/src/ui/components/theme-provider.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components */
import { createContext, useContext, useEffect, useState } from "react";
import type { ThemeId } from "@/types/ui-types";
diff --git a/src/ui/dashboard/Dashboard.tsx b/src/ui/dashboard/Dashboard.tsx
index bf3d6ec80..af889d4cb 100644
--- a/src/ui/dashboard/Dashboard.tsx
+++ b/src/ui/dashboard/Dashboard.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState, useRef, useCallback } from "react";
import { Auth } from "@/auth/LoginPage.tsx";
import { AlertManager } from "@/dashboard/panels/alerts/AlertManager.tsx";
diff --git a/src/ui/dashboard/DashboardTab.tsx b/src/ui/dashboard/DashboardTab.tsx
index aa1ee341d..919e5900d 100644
--- a/src/ui/dashboard/DashboardTab.tsx
+++ b/src/ui/dashboard/DashboardTab.tsx
@@ -122,48 +122,6 @@ const DEFAULT_SLOTS: CardSlot[] = [
{ id: "recent_activity", panel: "side", order: 0, height: null },
];
-// ─── useColumnResize ──────────────────────────────────────────────────────────
-
-function useColumnResize(
- containerRef: React.RefObject<HTMLDivElement | null>,
- mainWidthPct: number,
- setMainWidthPct: (v: number) => void,
-) {
- const dragging = useRef(false);
- const startX = useRef(0);
- const startPct = useRef(0);
-
- const onMouseDown = useCallback(
- (e: React.MouseEvent) => {
- e.preventDefault();
- dragging.current = true;
- startX.current = e.clientX;
- startPct.current = mainWidthPct;
-
- const onMove = (ev: MouseEvent) => {
- if (!dragging.current || !containerRef.current) return;
- const totalW = containerRef.current.getBoundingClientRect().width;
- const delta = ev.clientX - startX.current;
- const newPct = Math.min(
- 85,
- Math.max(30, startPct.current + (delta / totalW) * 100),
- );
- setMainWidthPct(newPct);
- };
- const onUp = () => {
- dragging.current = false;
- window.removeEventListener("mousemove", onMove);
- window.removeEventListener("mouseup", onUp);
- };
- window.addEventListener("mousemove", onMove);
- window.addEventListener("mouseup", onUp);
- },
- [containerRef, mainWidthPct, setMainWidthPct],
- );
-
- return onMouseDown;
-}
-
// ─── Card components ──────────────────────────────────────────────────────────
function StatsBarCard({
@@ -1160,7 +1118,7 @@ export function DashboardTab({
.then(setActivity)
.catch(() => {});
getCredentials()
- .then((res: any) =>
+ .then((res) =>
setCredentialCount(
Array.isArray(res?.credentials) ? res.credentials.length : 0,
),
@@ -1169,7 +1127,7 @@ export function DashboardTab({
getTunnelStatuses()
.then((statuses) => {
const active = Object.values(statuses ?? {}).filter(
- (s: any) => s?.status === "CONNECTED",
+ (s) => s?.status === "CONNECTED",
).length;
setActiveTunnelCount(active);
})
diff --git a/src/ui/dashboard/cards/NetworkGraphCard.tsx b/src/ui/dashboard/cards/NetworkGraphCard.tsx
index 49ca45f9e..7c29319cc 100644
--- a/src/ui/dashboard/cards/NetworkGraphCard.tsx
+++ b/src/ui/dashboard/cards/NetworkGraphCard.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React, {
useEffect,
useState,
@@ -405,7 +406,7 @@ export function NetworkGraphCard({
randomize: true,
componentSpacing: 100,
nodeOverlap: 20,
- } as any)
+ })
.run();
} else {
cyRef.current.fit();
@@ -719,7 +720,7 @@ export function NetworkGraphCard({
onOpenInNewTab();
} else {
addTab({
- type: "network_graph" as any,
+ type: "network_graph",
title: t("dashboard.networkGraph"),
});
}
diff --git a/src/ui/dashboard/panels/UpdateLog.tsx b/src/ui/dashboard/panels/UpdateLog.tsx
index 9531449f0..c76fe3ab3 100644
--- a/src/ui/dashboard/panels/UpdateLog.tsx
+++ b/src/ui/dashboard/panels/UpdateLog.tsx
@@ -75,7 +75,7 @@ export function UpdateLog({ loggedIn }: UpdateLogProps) {
})
.finally(() => setLoading(false));
}
- }, [loggedIn, isOpen]);
+ }, [loggedIn, isOpen, t]);
if (!loggedIn) {
return null;
diff --git a/src/ui/dashboard/panels/alerts/AlertCard.tsx b/src/ui/dashboard/panels/alerts/AlertCard.tsx
index d877f65b8..04b7edb63 100644
--- a/src/ui/dashboard/panels/alerts/AlertCard.tsx
+++ b/src/ui/dashboard/panels/alerts/AlertCard.tsx
@@ -87,7 +87,11 @@ export function AlertCard({
return (
<div className="w-full border border-edge rounded-md !bg-elevated overflow-hidden">
- <div className={"h-1 w-full " + getAccentBarClass(alert.priority, alert.type)} />
+ <div
+ className={
+ "h-1 w-full " + getAccentBarClass(alert.priority, alert.type)
+ }
+ />
<div className="flex items-start justify-between px-4 pt-4 pb-2">
<div className="flex items-center gap-3">
@@ -109,7 +113,9 @@ export function AlertCard({
{alert.type && (
<Badge
variant={getTypeBadgeVariant(alert.type)}
- className={alert.type === "success" ? "text-green-400" : undefined}
+ className={
+ alert.type === "success" ? "text-green-400" : undefined
+ }
>
{alert.type}
</Badge>
diff --git a/src/ui/dashboard/panels/alerts/AlertManager.tsx b/src/ui/dashboard/panels/alerts/AlertManager.tsx
index 04be361fb..f3d4ed6d7 100644
--- a/src/ui/dashboard/panels/alerts/AlertManager.tsx
+++ b/src/ui/dashboard/panels/alerts/AlertManager.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState } from "react";
import { AlertCard } from "./AlertCard.tsx";
import { Button } from "@/components/button.tsx";
diff --git a/src/ui/features/docker/DockerManager.tsx b/src/ui/features/docker/DockerManager.tsx
index 6f7813b28..63b32c17c 100644
--- a/src/ui/features/docker/DockerManager.tsx
+++ b/src/ui/features/docker/DockerManager.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React from "react";
import { Separator } from "@/components/separator.tsx";
import { Alert, AlertDescription } from "@/components/alert.tsx";
diff --git a/src/ui/features/docker/components/ContainerStats.tsx b/src/ui/features/docker/components/ContainerStats.tsx
index 6aac7f583..2749dd318 100644
--- a/src/ui/features/docker/components/ContainerStats.tsx
+++ b/src/ui/features/docker/components/ContainerStats.tsx
@@ -46,7 +46,7 @@ export function ContainerStats({
} finally {
setIsLoading(false);
}
- }, [sessionId, containerId, containerState]);
+ }, [sessionId, containerId, containerState, t]);
React.useEffect(() => {
fetchStats();
diff --git a/src/ui/features/file-manager/FileManager.tsx b/src/ui/features/file-manager/FileManager.tsx
index 3e4f51ef5..540c8f3a0 100644
--- a/src/ui/features/file-manager/FileManager.tsx
+++ b/src/ui/features/file-manager/FileManager.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React, {
useState,
useEffect,
@@ -20,43 +21,11 @@ import { DiffWindow } from "./components/DiffWindow.tsx";
import { useDragToDesktop } from "@/features/file-manager/hooks/useDragToDesktop";
import { useDragToSystemDesktop } from "@/features/file-manager/hooks/useDragToSystemDesktop";
import { useConfirmation } from "@/hooks/use-confirmation.ts";
-import { Button } from "@/components/button.tsx";
-import { Input } from "@/components/input.tsx";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
-import { TOTPDialog } from "@/ssh/dialogs/TOTPDialog.tsx";
-import { SSHAuthDialog } from "@/ssh/dialogs/SSHAuthDialog.tsx";
-import { WarpgateDialog } from "@/ssh/dialogs/WarpgateDialog.tsx";
-import { PermissionsDialog } from "./components/PermissionsDialog.tsx";
-import { CompressDialog } from "./components/CompressDialog.tsx";
-import { SudoPasswordDialog } from "./SudoPasswordDialog.tsx";
-import {
- Upload,
- FolderPlus,
- FilePlus,
- RefreshCw,
- Search,
- Grid3X3,
- List,
- ChevronLeft,
- ChevronRight,
- ArrowUp,
- Plus,
- Folder,
- Trash2,
- Copy,
- Layout,
-} from "lucide-react";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuRadioGroup,
- DropdownMenuRadioItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@/components/dropdown-menu.tsx";
+import { FileManagerDialogs } from "./FileManagerDialogs.tsx";
+import { FileManagerToolbar } from "./FileManagerToolbar.tsx";
+import { TransferToHostDialog } from "./components/TransferToHostDialog.tsx";
import { TerminalWindow } from "./components/TerminalWindow.tsx";
import type { SSHHost, FileItem } from "@/types/index";
import {
@@ -64,7 +33,6 @@ import {
useConnectionLog,
} from "@/ssh/connection-log/ConnectionLogContext.tsx";
import { ConnectionLog } from "@/ssh/connection-log/ConnectionLog.tsx";
-import type { LogEntry } from "@/types/connection-log.ts";
import { SimpleLoader } from "@/lib/SimpleLoader.tsx";
import {
listSSHFiles,
@@ -94,56 +62,28 @@ import {
compressSSHFiles,
setSudoPassword,
getServerMetricsById,
+ transferToHost,
+ addTransferRecent,
+ type TransferMethodPreference,
} from "@/main-axios.ts";
+import { beginTransferProgressMonitoring } from "./transferProgressMonitor.tsx";
+import { createFormatTransferMetrics } from "./transferMetricsFormat.ts";
import type { SidebarItem } from "./FileManagerSidebar.tsx";
-
-interface FileManagerProps {
- initialHost?: SSHHost | null;
- onClose?: () => void;
-}
-
-type ConnectionLogPayload = Omit<LogEntry, "id" | "timestamp">;
-
-type SSHConnectionError = Error & {
- connectionLogs?: ConnectionLogPayload[];
- requires_totp?: boolean;
- requires_warpgate?: boolean;
- sessionId?: string;
- prompt?: string;
- url?: string;
- securityKey?: string;
- status?: string;
- reason?: "no_keyboard" | "auth_failed" | "timeout";
-};
-
-interface CreateIntent {
- id: string;
- type: "file" | "directory";
- defaultName: string;
- currentName: string;
-}
-
-function formatFileSize(bytes?: number): string {
- if (bytes === undefined || bytes === null) return "-";
- if (bytes === 0) return "0 B";
-
- const units = ["B", "KB", "MB", "GB", "TB"];
- let size = bytes;
- let unitIndex = 0;
-
- while (size >= 1024 && unitIndex < units.length - 1) {
- size /= 1024;
- unitIndex++;
- }
-
- const formattedSize =
- size < 10 && unitIndex > 0 ? size.toFixed(1) : Math.round(size).toString();
- return `${formattedSize} ${units[unitIndex]}`;
-}
+import type {
+ CreateIntent,
+ FileManagerProps,
+ PendingSudoOperation,
+ SSHConnectionError,
+} from "./file-manager-types.ts";
+import { formatFileSize } from "./file-manager-utils.ts";
function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
const { openWindow } = useWindowManager();
const { t } = useTranslation();
+ const formatTransferMetrics = useMemo(
+ () => createFormatTransferMetrics(t),
+ [t],
+ );
const { confirmWithToast } = useConfirmation();
const {
addLog,
@@ -244,13 +184,13 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
const [compressDialogFiles, setCompressDialogFiles] = useState<FileItem[]>(
[],
);
+ const [transferDialogOpen, setTransferDialogOpen] = useState(false);
+ const [transferFiles, setTransferFiles] = useState<FileItem[]>([]);
+ const [transferMove, setTransferMove] = useState(false);
const [sudoDialogOpen, setSudoDialogOpen] = useState(false);
- const [pendingSudoOperation, setPendingSudoOperation] = useState<
- | { type: "delete"; files: FileItem[] }
- | { type: "navigate"; path: string }
- | null
- >(null);
+ const [pendingSudoOperation, setPendingSudoOperation] =
+ useState<PendingSudoOperation | null>(null);
const { selectedFiles, clearSelection, setSelection } = useFileSelection();
@@ -776,6 +716,19 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
loadDirectory(currentPath);
}, [currentPath, lastRefreshTime, loadDirectory]);
+ useEffect(() => {
+ const handler = (event: Event) => {
+ const detail = (event as CustomEvent<{ hostId: number; path: string }>)
+ .detail;
+ if (!detail || !currentHost?.id) return;
+ if (detail.hostId === currentHost.id) {
+ handleRefreshDirectory();
+ }
+ };
+ window.addEventListener("file-manager:refresh", handler);
+ return () => window.removeEventListener("file-manager:refresh", handler);
+ }, [currentHost?.id, handleRefreshDirectory]);
+
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const activeElement = document.activeElement;
@@ -1358,6 +1311,19 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
});
}
+ function handleSidebarItemContextMenu(
+ event: React.MouseEvent,
+ item: SidebarItem,
+ ) {
+ const file: FileItem = {
+ name: item.name,
+ path: item.path,
+ type:
+ item.type === "recent" || item.type === "pinned" ? "file" : "directory",
+ };
+ handleContextMenu(event, file);
+ }
+
function handleCopyFiles(files: FileItem[]) {
setClipboard({ files, operation: "copy" });
toast.success(
@@ -1623,6 +1589,76 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
}
}
+ function handleOpenTransferDialog(files: FileItem[], move: boolean) {
+ setTransferFiles(files);
+ setTransferMove(move);
+ setTransferDialogOpen(true);
+ }
+
+ async function handleTransferConfirm(
+ destSessionId: string,
+ destHostId: number,
+ destPath: string,
+ destPathLabel: string,
+ methodPreference: TransferMethodPreference,
+ parallelSegmentCount: number,
+ ) {
+ if (!sshSessionId || !currentHost?.id || transferFiles.length === 0) return;
+
+ const sourcePaths = transferFiles.map((f) => f.path);
+
+ try {
+ await ensureSSHConnection();
+
+ const { transferId } = await transferToHost(
+ sshSessionId,
+ sourcePaths,
+ destSessionId,
+ destPath,
+ transferMove,
+ methodPreference,
+ parallelSegmentCount,
+ );
+
+ const monitorHandle = beginTransferProgressMonitoring(transferId, t, {
+ formatTransferMetrics,
+ });
+ if (!monitorHandle) return;
+
+ const finalStatus = await monitorHandle.waitForCompletion;
+
+ if (
+ finalStatus.status !== "success" &&
+ finalStatus.status !== "partial"
+ ) {
+ return;
+ }
+
+ void addTransferRecent(
+ currentHost.id,
+ destHostId,
+ destPathLabel,
+ destPathLabel,
+ );
+
+ window.dispatchEvent(
+ new CustomEvent("file-manager:refresh", {
+ detail: { hostId: destHostId, path: destPathLabel },
+ }),
+ );
+
+ if (transferMove) {
+ handleRefreshDirectory();
+ clearSelection();
+ }
+ } catch (error: unknown) {
+ const err = error as { message?: string };
+ toast.error(
+ `${t("transfer.transferError")}: ${err.message || t("fileManager.unknownError")}`,
+ );
+ }
+ }
+
async function handleUndo() {
if (undoHistory.length === 0) {
toast.info(t("fileManager.noUndoableActions"));
@@ -2556,281 +2592,34 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
visibility: isConnectionLogExpanded ? "hidden" : "visible",
}}
>
- <div className="flex flex-col shrink-0 mx-3 mt-3 border border-border bg-card">
- <div className="flex flex-row items-center justify-between px-3 py-2 gap-2">
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="icon"
- onClick={() => setMobileSidebarOpen((o) => !o)}
- className="md:hidden size-8 rounded-none"
- title={t("fileManager.toggleSidebar")}
- >
- <Layout className="size-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={goBack}
- disabled={navIndex <= 0}
- className="size-8 rounded-none"
- >
- <ChevronLeft className="size-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={goForward}
- disabled={navIndex >= navHistory.length - 1}
- className="size-8 rounded-none"
- >
- <ChevronRight className="size-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={goUp}
- disabled={currentPath === "/"}
- className="size-8 rounded-none"
- >
- <ArrowUp className="size-4" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- onClick={handleRefreshDirectory}
- className="size-8 rounded-none"
- >
- <RefreshCw
- className={`size-4 ${isLoading && !!sshSessionId ? "animate-spin [animation-duration:0.5s]" : ""}`}
- />
- </Button>
- </div>
-
- <div className="hidden md:flex flex-1 items-center px-3 h-8 bg-muted/50 border border-border rounded-none gap-2 overflow-hidden">
- <Folder className="size-3.5 text-accent-brand shrink-0" />
- <div className="flex items-center gap-1 overflow-x-auto scrollbar-none text-[10px] font-bold uppercase tracking-widest whitespace-nowrap">
- {currentPath.split("/").map((part, i, arr) => (
- <React.Fragment key={i}>
- {part === "" && i === 0 ? (
- <button
- onClick={() => navigateTo("/")}
- className="hover:text-accent-brand transition-colors"
- >
- {t("fileManager.root")}
- </button>
- ) : part !== "" ? (
- <button
- onClick={() =>
- navigateTo(arr.slice(0, i + 1).join("/") || "/")
- }
- className="hover:text-accent-brand transition-colors"
- >
- {part}
- </button>
- ) : null}
- {i < arr.length - 1 && part !== "" && (
- <ChevronRight className="size-3 text-muted-foreground shrink-0" />
- )}
- {i === 0 && arr.length > 1 && part === "" && (
- <ChevronRight className="size-3 text-muted-foreground shrink-0" />
- )}
- </React.Fragment>
- ))}
- </div>
- </div>
-
- <div className="flex items-center gap-2">
- {selectedFiles.length > 0 && (
- <div className="flex items-center gap-1 px-2 py-1 bg-accent-brand/10 border border-accent-brand/20 text-accent-brand text-[10px] font-black uppercase tracking-tighter">
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-accent-brand hover:bg-accent-brand/20 rounded-none"
- onClick={() => handleDeleteFiles(selectedFiles)}
- >
- <Trash2 className="size-3.5" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-accent-brand hover:bg-accent-brand/20 rounded-none"
- onClick={() => handleCopyFiles(selectedFiles)}
- >
- <Copy className="size-3.5" />
- </Button>
- </div>
- )}
-
- <div className="relative w-28 md:w-48">
- <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground" />
- <Input
- placeholder={t("fileManager.searchFiles")}
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="h-8 pl-8 text-xs bg-muted/50 border-border rounded-none focus:ring-1 focus:ring-accent-brand/50"
- />
- </div>
-
- <div className="flex items-center border border-border rounded-none overflow-hidden">
- <Button
- variant={viewMode === "grid" ? "secondary" : "ghost"}
- size="icon"
- onClick={() => setViewMode("grid")}
- className={`size-8 rounded-none border-y-0 border-l-0 border-r border-border ${viewMode === "grid" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
- >
- <Grid3X3 className="size-4" />
- </Button>
- <Button
- variant={viewMode === "list" ? "secondary" : "ghost"}
- size="icon"
- onClick={() => setViewMode("list")}
- className={`size-8 rounded-none border-y-0 border-r-0 border-border ${viewMode === "list" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
- >
- <List className="size-4" />
- </Button>
- </div>
-
- <label
- className="hidden md:block cursor-pointer"
- title={t("fileManager.upload")}
- >
- <input
- type="file"
- multiple
- className="hidden"
- onChange={(e) => {
- const files = e.target.files;
- if (files) handleFilesDropped(files);
- }}
- />
- <div className="h-8 px-3 flex items-center gap-1.5 border border-border hover:bg-muted text-muted-foreground hover:text-foreground transition-colors text-[10px] font-bold uppercase tracking-widest">
- <Upload className="size-3.5" /> {t("fileManager.upload")}
- </div>
- </label>
-
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="outline"
- size="sm"
- className="h-8 gap-1.5 border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 rounded-none font-bold uppercase tracking-widest text-[10px]"
- >
- <Plus className="size-3.5" />
- {t("fileManager.new")}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="end"
- className="w-44 rounded-none border-border bg-card"
- onCloseAutoFocus={(e) => e.preventDefault()}
- >
- <DropdownMenuItem
- onSelect={() => {
- setTimeout(() => handleCreateNewFolder(), 0);
- }}
- className="rounded-none text-xs font-semibold gap-2 focus:bg-accent-brand/10 focus:text-accent-brand"
- >
- <FolderPlus className="size-4 text-accent-brand" />
- {t("fileManager.newFolder")}
- </DropdownMenuItem>
- <DropdownMenuItem
- onSelect={() => {
- setTimeout(() => handleCreateNewFile(), 0);
- }}
- className="rounded-none text-xs font-semibold gap-2 focus:bg-accent-brand/10 focus:text-accent-brand"
- >
- <FilePlus className="size-4 text-muted-foreground" />
- {t("fileManager.newFile")}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuLabel className="text-[10px] uppercase tracking-widest text-muted-foreground py-1">
- {t("fileManager.sortBy")}
- </DropdownMenuLabel>
- <DropdownMenuRadioGroup
- value={sortBy}
- onValueChange={(v) =>
- setSortBy(v as "name" | "modified" | "size")
- }
- >
- <DropdownMenuRadioItem
- value="name"
- className="rounded-none text-xs"
- >
- {t("fileManager.sortByName")}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem
- value="modified"
- className="rounded-none text-xs"
- >
- {t("fileManager.sortByDate")}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem
- value="size"
- className="rounded-none text-xs"
- >
- {t("fileManager.sortBySize")}
- </DropdownMenuRadioItem>
- </DropdownMenuRadioGroup>
- <DropdownMenuSeparator />
- <DropdownMenuRadioGroup
- value={sortOrder}
- onValueChange={(v) => setSortOrder(v as "asc" | "desc")}
- >
- <DropdownMenuRadioItem
- value="asc"
- className="rounded-none text-xs"
- >
- {t("fileManager.ascending")}
- </DropdownMenuRadioItem>
- <DropdownMenuRadioItem
- value="desc"
- className="rounded-none text-xs"
- >
- {t("fileManager.descending")}
- </DropdownMenuRadioItem>
- </DropdownMenuRadioGroup>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
-
- {/* Mobile breadcrumb row */}
- <div className="md:hidden flex items-center px-3 pb-2 gap-2">
- <div className="flex-1 flex items-center px-3 h-8 bg-muted/50 border border-border gap-2 overflow-hidden">
- <Folder className="size-3.5 text-accent-brand shrink-0" />
- <div className="flex items-center gap-1 overflow-x-auto scrollbar-none text-[10px] font-bold uppercase tracking-widest whitespace-nowrap">
- {currentPath.split("/").map((part, i, arr) => (
- <React.Fragment key={i}>
- {part === "" && i === 0 ? (
- <button
- onClick={() => navigateTo("/")}
- className="hover:text-accent-brand transition-colors"
- >
- {t("fileManager.root")}
- </button>
- ) : part !== "" ? (
- <button
- onClick={() =>
- navigateTo(arr.slice(0, i + 1).join("/") || "/")
- }
- className="hover:text-accent-brand transition-colors"
- >
- {part}
- </button>
- ) : null}
- {i < arr.length - 1 && part !== "" && (
- <ChevronRight className="size-3 text-muted-foreground shrink-0" />
- )}
- {i === 0 && arr.length > 1 && part === "" && (
- <ChevronRight className="size-3 text-muted-foreground shrink-0" />
- )}
- </React.Fragment>
- ))}
- </div>
- </div>
- </div>
- </div>
+ <FileManagerToolbar
+ t={t}
+ currentPath={currentPath}
+ navIndex={navIndex}
+ navHistoryLength={navHistory.length}
+ isLoading={isLoading}
+ sshSessionId={sshSessionId}
+ selectedFiles={selectedFiles}
+ searchQuery={searchQuery}
+ setSearchQuery={setSearchQuery}
+ viewMode={viewMode}
+ setViewMode={setViewMode}
+ sortBy={sortBy}
+ setSortBy={setSortBy}
+ sortOrder={sortOrder}
+ setSortOrder={setSortOrder}
+ setMobileSidebarOpen={setMobileSidebarOpen}
+ goBack={goBack}
+ goForward={goForward}
+ goUp={goUp}
+ navigateTo={navigateTo}
+ handleRefreshDirectory={handleRefreshDirectory}
+ handleDeleteFiles={handleDeleteFiles}
+ handleCopyFiles={handleCopyFiles}
+ handleFilesDropped={handleFilesDropped}
+ handleCreateNewFolder={handleCreateNewFolder}
+ handleCreateNewFile={handleCreateNewFile}
+ />
<div
className="flex-1 flex px-3 pb-3 pt-2 gap-3 min-h-0 relative"
@@ -2861,6 +2650,7 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
onPathChange={navigateTo}
onLoadDirectory={loadDirectory}
onFileOpen={handleSidebarFileOpen}
+ onItemContextMenu={handleSidebarItemContextMenu}
sshSessionId={sshSessionId}
refreshTrigger={sidebarRefreshTrigger}
diskInfo={diskInfo ?? undefined}
@@ -2873,11 +2663,8 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
<FileManagerGrid
files={filteredFiles}
selectedFiles={selectedFiles}
- onFileSelect={() => {}}
onFileOpen={handleFileOpen}
onSelectionChange={setSelection}
- currentPath={currentPath}
- onPathChange={navigateTo}
onRefresh={handleRefreshDirectory}
onUpload={handleFilesDropped}
sortBy={sortBy}
@@ -2963,69 +2750,51 @@ function FileManagerContent({ initialHost, onClose }: FileManagerProps) {
onExtractArchive={handleExtractArchive}
onCompress={handleOpenCompressDialog}
onCopyPath={handleCopyPath}
+ onTransferToHost={handleOpenTransferDialog}
/>
</div>
</div>
</div>
</div>
- <CompressDialog
- open={compressDialogFiles.length > 0}
- onOpenChange={(open) => !open && setCompressDialogFiles([])}
- fileNames={compressDialogFiles.map((f) => f.name)}
- onCompress={handleCompress}
- />
-
- <TOTPDialog
- isOpen={totpRequired}
- prompt={totpPrompt}
- onSubmit={handleTotpSubmit}
- onCancel={handleTotpCancel}
- backgroundColor="var(--bg-canvas)"
- />
-
- <WarpgateDialog
- isOpen={warpgateRequired}
- url={warpgateUrl}
- securityKey={warpgateSecurityKey}
- onContinue={handleWarpgateContinue}
- onCancel={handleWarpgateCancel}
- onOpenUrl={handleWarpgateOpenUrl}
- backgroundColor="var(--bg-canvas)"
- />
-
{currentHost && (
- <SSHAuthDialog
- isOpen={showAuthDialog}
- reason={authDialogReason}
- onSubmit={handleAuthDialogSubmit}
- onCancel={handleAuthDialogCancel}
- hostInfo={{
- ip: currentHost.ip,
- port: currentHost.port,
- username: currentHost.username,
- name: currentHost.name,
- }}
- backgroundColor="var(--bg-canvas)"
+ <TransferToHostDialog
+ open={transferDialogOpen}
+ onOpenChange={setTransferDialogOpen}
+ files={transferFiles}
+ move={transferMove}
+ sourceHost={currentHost}
+ sourceSessionId={sshSessionId}
+ onConfirm={handleTransferConfirm}
/>
)}
- <PermissionsDialog
- file={permissionsDialogFile}
- open={permissionsDialogFile !== null}
- onOpenChange={(open) => {
- if (!open) setPermissionsDialogFile(null);
- }}
- onSave={handleSavePermissions}
- />
-
- <SudoPasswordDialog
- open={sudoDialogOpen}
- onOpenChange={(open) => {
- setSudoDialogOpen(open);
- if (!open) setPendingSudoOperation(null);
- }}
- onSubmit={handleSudoPasswordSubmit}
+ <FileManagerDialogs
+ compressDialogFiles={compressDialogFiles}
+ setCompressDialogFiles={setCompressDialogFiles}
+ handleCompress={handleCompress}
+ totpRequired={totpRequired}
+ totpPrompt={totpPrompt}
+ handleTotpSubmit={handleTotpSubmit}
+ handleTotpCancel={handleTotpCancel}
+ warpgateRequired={warpgateRequired}
+ warpgateUrl={warpgateUrl}
+ warpgateSecurityKey={warpgateSecurityKey}
+ handleWarpgateContinue={handleWarpgateContinue}
+ handleWarpgateCancel={handleWarpgateCancel}
+ handleWarpgateOpenUrl={handleWarpgateOpenUrl}
+ currentHost={currentHost}
+ showAuthDialog={showAuthDialog}
+ authDialogReason={authDialogReason}
+ handleAuthDialogSubmit={handleAuthDialogSubmit}
+ handleAuthDialogCancel={handleAuthDialogCancel}
+ permissionsDialogFile={permissionsDialogFile}
+ setPermissionsDialogFile={setPermissionsDialogFile}
+ handleSavePermissions={handleSavePermissions}
+ sudoDialogOpen={sudoDialogOpen}
+ setSudoDialogOpen={setSudoDialogOpen}
+ setPendingSudoOperation={setPendingSudoOperation}
+ handleSudoPasswordSubmit={handleSudoPasswordSubmit}
/>
<ConnectionLog
isConnecting={isReconnecting || isLoading}
diff --git a/src/ui/features/file-manager/FileManagerContextMenu.tsx b/src/ui/features/file-manager/FileManagerContextMenu.tsx
index fccb75fd7..6ab99fd35 100644
--- a/src/ui/features/file-manager/FileManagerContextMenu.tsx
+++ b/src/ui/features/file-manager/FileManagerContextMenu.tsx
@@ -18,10 +18,13 @@ import {
Star,
Bookmark,
FileArchive,
+ ArrowRightLeft,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { Kbd, KbdKey, KbdSeparator } from "@/components/kbd.tsx";
+const VIEWPORT_PADDING = 16;
+
interface FileItem {
name: string;
type: "file" | "directory" | "link";
@@ -64,6 +67,7 @@ interface ContextMenuProps {
onExtractArchive?: (file: FileItem) => void;
onCompress?: (files: FileItem[]) => void;
onCopyPath?: (files: FileItem[]) => void;
+ onTransferToHost?: (files: FileItem[], move: boolean) => void;
}
interface MenuItem {
@@ -76,29 +80,6 @@ interface MenuItem {
danger?: boolean;
}
-const VIEWPORT_PADDING = 10;
-
-function getClampedMenuPosition(
- x: number,
- y: number,
- menuWidth: number,
- menuHeight: number,
-) {
- const maxX = Math.max(
- VIEWPORT_PADDING,
- window.innerWidth - menuWidth - VIEWPORT_PADDING,
- );
- const maxY = Math.max(
- VIEWPORT_PADDING,
- window.innerHeight - menuHeight - VIEWPORT_PADDING,
- );
-
- return {
- x: Math.min(Math.max(VIEWPORT_PADDING, x), maxX),
- y: Math.min(Math.max(VIEWPORT_PADDING, y), maxY),
- };
-}
-
export function FileManagerContextMenu({
x,
y,
@@ -129,6 +110,7 @@ export function FileManagerContextMenu({
onExtractArchive,
onCompress,
onCopyPath,
+ onTransferToHost,
}: ContextMenuProps) {
const { t } = useTranslation();
const menuRef = useRef<HTMLDivElement>(null);
@@ -278,6 +260,29 @@ export function FileManagerContextMenu({
});
}
+ if (isFileContext && onTransferToHost) {
+ const isOnlyDirectories =
+ files.length > 0 && files.every((f) => f.type === "directory");
+ menuItems.push({
+ icon: <ArrowRightLeft className="size-3.5" />,
+ label: isMultipleFiles
+ ? t("transfer.copyItemsToHost", { count: files.length })
+ : isOnlyDirectories && isSingleFile
+ ? t("transfer.copyFolderToHost")
+ : t("transfer.copyToHost"),
+ action: () => onTransferToHost(files, false),
+ });
+ menuItems.push({
+ icon: <ArrowRightLeft className="size-3.5" />,
+ label: isMultipleFiles
+ ? t("transfer.moveItemsToHost", { count: files.length })
+ : isOnlyDirectories && isSingleFile
+ ? t("transfer.moveFolderToHost")
+ : t("transfer.moveToHost"),
+ action: () => onTransferToHost(files, true),
+ });
+ }
+
if (isSingleFile && files[0].type === "file" && onExtractArchive) {
const fileName = files[0].name.toLowerCase();
const isArchive =
diff --git a/src/ui/features/file-manager/FileManagerDialogs.tsx b/src/ui/features/file-manager/FileManagerDialogs.tsx
new file mode 100644
index 000000000..435598cf8
--- /dev/null
+++ b/src/ui/features/file-manager/FileManagerDialogs.tsx
@@ -0,0 +1,134 @@
+import type { FileItem, SSHHost } from "@/types/index";
+import { TOTPDialog } from "@/ssh/dialogs/TOTPDialog.tsx";
+import { SSHAuthDialog } from "@/ssh/dialogs/SSHAuthDialog.tsx";
+import { WarpgateDialog } from "@/ssh/dialogs/WarpgateDialog.tsx";
+import { PermissionsDialog } from "./components/PermissionsDialog.tsx";
+import { CompressDialog } from "./components/CompressDialog.tsx";
+import { SudoPasswordDialog } from "./SudoPasswordDialog.tsx";
+import type { PendingSudoOperation } from "./file-manager-types.ts";
+
+type FileManagerDialogsProps = {
+ compressDialogFiles: FileItem[];
+ setCompressDialogFiles: (files: FileItem[]) => void;
+ handleCompress: (archiveName: string, format: string) => void | Promise<void>;
+ totpRequired: boolean;
+ totpPrompt: string;
+ handleTotpSubmit: (code: string) => void | Promise<void>;
+ handleTotpCancel: () => void;
+ warpgateRequired: boolean;
+ warpgateUrl: string;
+ warpgateSecurityKey: string;
+ handleWarpgateContinue: () => void | Promise<void>;
+ handleWarpgateCancel: () => void;
+ handleWarpgateOpenUrl: () => void;
+ currentHost: SSHHost | null;
+ showAuthDialog: boolean;
+ authDialogReason: "no_keyboard" | "auth_failed" | "timeout";
+ handleAuthDialogSubmit: (credentials: {
+ password?: string;
+ sshKey?: string;
+ keyPassword?: string;
+ }) => void | Promise<void>;
+ handleAuthDialogCancel: () => void;
+ permissionsDialogFile: FileItem | null;
+ setPermissionsDialogFile: (file: FileItem | null) => void;
+ handleSavePermissions: (
+ file: FileItem,
+ permissions: string,
+ ) => void | Promise<void>;
+ sudoDialogOpen: boolean;
+ setSudoDialogOpen: (open: boolean) => void;
+ setPendingSudoOperation: (operation: PendingSudoOperation | null) => void;
+ handleSudoPasswordSubmit: (password: string) => void | Promise<void>;
+};
+
+export function FileManagerDialogs({
+ compressDialogFiles,
+ setCompressDialogFiles,
+ handleCompress,
+ totpRequired,
+ totpPrompt,
+ handleTotpSubmit,
+ handleTotpCancel,
+ warpgateRequired,
+ warpgateUrl,
+ warpgateSecurityKey,
+ handleWarpgateContinue,
+ handleWarpgateCancel,
+ handleWarpgateOpenUrl,
+ currentHost,
+ showAuthDialog,
+ authDialogReason,
+ handleAuthDialogSubmit,
+ handleAuthDialogCancel,
+ permissionsDialogFile,
+ setPermissionsDialogFile,
+ handleSavePermissions,
+ sudoDialogOpen,
+ setSudoDialogOpen,
+ setPendingSudoOperation,
+ handleSudoPasswordSubmit,
+}: FileManagerDialogsProps) {
+ return (
+ <>
+ <CompressDialog
+ open={compressDialogFiles.length > 0}
+ onOpenChange={(open) => !open && setCompressDialogFiles([])}
+ fileNames={compressDialogFiles.map((f) => f.name)}
+ onCompress={handleCompress}
+ />
+
+ <TOTPDialog
+ isOpen={totpRequired}
+ prompt={totpPrompt}
+ onSubmit={handleTotpSubmit}
+ onCancel={handleTotpCancel}
+ backgroundColor="var(--bg-canvas)"
+ />
+
+ <WarpgateDialog
+ isOpen={warpgateRequired}
+ url={warpgateUrl}
+ securityKey={warpgateSecurityKey}
+ onContinue={handleWarpgateContinue}
+ onCancel={handleWarpgateCancel}
+ onOpenUrl={handleWarpgateOpenUrl}
+ backgroundColor="var(--bg-canvas)"
+ />
+
+ {currentHost && (
+ <SSHAuthDialog
+ isOpen={showAuthDialog}
+ reason={authDialogReason}
+ onSubmit={handleAuthDialogSubmit}
+ onCancel={handleAuthDialogCancel}
+ hostInfo={{
+ ip: currentHost.ip,
+ port: currentHost.port,
+ username: currentHost.username,
+ name: currentHost.name,
+ }}
+ backgroundColor="var(--bg-canvas)"
+ />
+ )}
+
+ <PermissionsDialog
+ file={permissionsDialogFile}
+ open={permissionsDialogFile !== null}
+ onOpenChange={(open) => {
+ if (!open) setPermissionsDialogFile(null);
+ }}
+ onSave={handleSavePermissions}
+ />
+
+ <SudoPasswordDialog
+ open={sudoDialogOpen}
+ onOpenChange={(open) => {
+ setSudoDialogOpen(open);
+ if (!open) setPendingSudoOperation(null);
+ }}
+ onSubmit={handleSudoPasswordSubmit}
+ />
+ </>
+ );
+}
diff --git a/src/ui/features/file-manager/FileManagerGrid.tsx b/src/ui/features/file-manager/FileManagerGrid.tsx
index 7c8592d65..8ca6ca911 100644
--- a/src/ui/features/file-manager/FileManagerGrid.tsx
+++ b/src/ui/features/file-manager/FileManagerGrid.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useRef, useCallback, useEffect } from "react";
import { createPortal } from "react-dom";
import { cn } from "@/lib/utils.ts";
@@ -21,33 +22,8 @@ import {
} from "lucide-react";
import { useTranslation } from "react-i18next";
import type { FileItem } from "@/types/index";
-
-interface CreateIntent {
- id: string;
- type: "file" | "directory";
- defaultName: string;
- currentName: string;
-}
-
-function formatFileSize(bytes?: number): string {
- if (bytes === undefined || bytes === null) return "-";
-
- if (bytes === 0) return "0 B";
-
- const units = ["B", "KB", "MB", "GB", "TB"];
- let size = bytes;
- let unitIndex = 0;
-
- while (size >= 1024 && unitIndex < units.length - 1) {
- size /= 1024;
- unitIndex++;
- }
-
- const formattedSize =
- size < 10 && unitIndex > 0 ? size.toFixed(1) : Math.round(size).toString();
-
- return `${formattedSize} ${units[unitIndex]}`;
-}
+import type { CreateIntent } from "./file-manager-types.ts";
+import { formatFileSize } from "./file-manager-utils.ts";
interface DragState {
type: "none" | "internal" | "external";
@@ -61,11 +37,8 @@ interface DragState {
interface FileManagerGridProps {
files: FileItem[];
selectedFiles: FileItem[];
- onFileSelect: (file: FileItem, multiSelect?: boolean) => void;
onFileOpen: (file: FileItem) => void;
onSelectionChange: (files: FileItem[]) => void;
- currentPath: string;
- onPathChange: (path: string) => void;
onRefresh: () => void;
onUpload?: (files: FileList) => void;
onDownload?: (files: FileItem[]) => void;
@@ -182,8 +155,6 @@ export function FileManagerGrid({
selectedFiles,
onFileOpen,
onSelectionChange,
- currentPath,
- onPathChange,
onRefresh,
onUpload,
onDownload,
@@ -368,92 +339,6 @@ export function FileManagerGrid({
} | null>(null);
const [justFinishedSelecting, setJustFinishedSelecting] = useState(false);
- const [navigationHistory, setNavigationHistory] = useState<string[]>([
- currentPath,
- ]);
- const [historyIndex, setHistoryIndex] = useState(0);
-
- const [isEditingPath, setIsEditingPath] = useState(false);
- const [editPathValue, setEditPathValue] = useState(currentPath);
-
- useEffect(() => {
- const lastPath = navigationHistory[historyIndex];
- if (currentPath !== lastPath) {
- const newHistory = navigationHistory.slice(0, historyIndex + 1);
- newHistory.push(currentPath);
- setNavigationHistory(newHistory);
- setHistoryIndex(newHistory.length - 1);
- }
- }, [currentPath]);
-
- const goBack = () => {
- if (historyIndex > 0) {
- const newIndex = historyIndex - 1;
- setHistoryIndex(newIndex);
- onPathChange(navigationHistory[newIndex]);
- }
- };
-
- const goForward = () => {
- if (historyIndex < navigationHistory.length - 1) {
- const newIndex = historyIndex + 1;
- setHistoryIndex(newIndex);
- onPathChange(navigationHistory[newIndex]);
- }
- };
-
- const goUp = () => {
- const parts = currentPath.split("/").filter(Boolean);
- if (parts.length > 0) {
- parts.pop();
- const parentPath = "/" + parts.join("/");
- onPathChange(parentPath);
- } else if (currentPath !== "/") {
- onPathChange("/");
- }
- };
-
- const pathParts = currentPath.split("/").filter(Boolean);
- const navigateToPath = (index: number) => {
- if (index === -1) {
- onPathChange("/");
- } else {
- const newPath = "/" + pathParts.slice(0, index + 1).join("/");
- onPathChange(newPath);
- }
- };
-
- const startEditingPath = () => {
- setEditPathValue(currentPath);
- setIsEditingPath(true);
- };
-
- const cancelEditingPath = () => {
- setIsEditingPath(false);
- setEditPathValue(currentPath);
- };
-
- const confirmEditingPath = () => {
- const trimmedPath = editPathValue.trim();
- if (trimmedPath) {
- const needsExpansion =
- trimmedPath.startsWith("~") || trimmedPath.includes("$");
- const normalizedPath = needsExpansion
- ? trimmedPath
- : trimmedPath.startsWith("/")
- ? trimmedPath
- : "/" + trimmedPath;
- onPathChange(normalizedPath);
- }
- setIsEditingPath(false);
- };
-
- useEffect(() => {
- if (!isEditingPath) {
- setEditPathValue(currentPath);
- }
- }, [currentPath, isEditingPath]);
-
const handleDragEnter = useCallback(
(e: React.DragEvent) => {
e.preventDefault();
@@ -490,7 +375,7 @@ export function FileManagerGrid({
});
}
},
- [dragState.type, dragState.counter],
+ [dragState.type],
);
const handleDragOver = useCallback(
@@ -691,7 +576,7 @@ export function FileManagerGrid({
setDragState({ type: "none", files: [], counter: 0 });
},
- [onUpload, onDownload, dragState],
+ [onUpload, dragState],
);
const handleFileClick = (file: FileItem, event: React.MouseEvent) => {
diff --git a/src/ui/features/file-manager/FileManagerSidebar.tsx b/src/ui/features/file-manager/FileManagerSidebar.tsx
index 34bc44ff0..54ee003f6 100644
--- a/src/ui/features/file-manager/FileManagerSidebar.tsx
+++ b/src/ui/features/file-manager/FileManagerSidebar.tsx
@@ -67,6 +67,8 @@ interface FileManagerSidebarProps {
currentPath: string;
onPathChange: (path: string) => void;
onFileOpen?: (file: SidebarItem) => void;
+ /** Full file-manager context menu (same as main grid). */
+ onItemContextMenu?: (event: React.MouseEvent, item: SidebarItem) => void;
sshSessionId?: string;
refreshTrigger?: number;
diskInfo?: { usedHuman: string; totalHuman: string; percent: number };
@@ -79,6 +81,7 @@ export function FileManagerSidebar({
currentPath,
onPathChange,
onFileOpen,
+ onItemContextMenu,
sshSessionId,
refreshTrigger,
diskInfo,
@@ -114,46 +117,9 @@ export function FileManagerSidebar({
// ─── Effects ──────────────────────────────────────────────────────────────────
- useEffect(() => {
- loadQuickAccessData();
- }, [currentHost, refreshTrigger]);
-
- useEffect(() => {
- if (sshSessionId) {
- loadedFoldersRef.current = new Set(["/"]);
- loadDirectoryTree();
- }
- }, [sshSessionId]);
-
- // When currentPath changes externally (grid navigation), ensure the parent
- // directory is loaded in the tree so the selection highlight can appear.
- useEffect(() => {
- if (!sshSessionId || currentPath === "/") return;
-
- const parentPath =
- currentPath.substring(0, currentPath.lastIndexOf("/")) || "/";
-
- const findByPath = (items: SidebarItem[]): SidebarItem | null => {
- for (const item of items) {
- if (item.path === parentPath) return item;
- if (item.children) {
- const found = findByPath(item.children);
- if (found) return found;
- }
- }
- return null;
- };
-
- const parent = findByPath(directoryTree);
- if (parent && !loadedFoldersRef.current.has(parent.path)) {
- loadedFoldersRef.current.add(parent.path);
- loadSubdirectory(parent.id, parent.path);
- }
- }, [currentPath, sshSessionId]);
-
// ─── API: Quick access ────────────────────────────────────────────────────────
- const loadQuickAccessData = async () => {
+ const loadQuickAccessData = useCallback(async () => {
if (!currentHost?.id) return;
try {
@@ -196,61 +162,64 @@ export function FileManagerSidebar({
setPinnedItems([]);
setShortcuts([]);
}
- };
+ }, [currentHost?.id]);
// ─── API: Directory tree ──────────────────────────────────────────────────────
- const loadDirectoryTree = async (attempt = 0) => {
- if (!sshSessionId) return;
+ const loadDirectoryTree = useCallback(
+ async (attempt = 0) => {
+ if (!sshSessionId) return;
- try {
- const response = await listSSHFiles(sshSessionId, "/");
- const rootFiles = (response.files || []) as DirectoryItemData[];
- const rootFolders = rootFiles.filter(
- (item: DirectoryItemData) => item.type === "directory",
- );
+ try {
+ const response = await listSSHFiles(sshSessionId, "/");
+ const rootFiles = (response.files || []) as DirectoryItemData[];
+ const rootFolders = rootFiles.filter(
+ (item: DirectoryItemData) => item.type === "directory",
+ );
- const rootTreeItems = rootFolders.map((folder: DirectoryItemData) => ({
- id: `folder-${folder.name}`,
- name: folder.name,
- path: folder.path,
- type: "folder" as const,
- isExpanded: false,
- children: [],
- }));
-
- setDirectoryTree([
- {
- id: "root",
- name: "/",
- path: "/",
- type: "folder" as const,
- isExpanded: true,
- children: rootTreeItems,
- },
- ]);
- } catch (error: unknown) {
- const status =
- (error as { status?: number })?.status ||
- (error as { response?: { status?: number } })?.response?.status;
- if (status === 409 && attempt < 3) {
- // Another request was already listing "/" — retry after a short delay
- setTimeout(() => loadDirectoryTree(attempt + 1), 600);
- return;
- }
- console.error("Failed to load directory tree:", error);
- setDirectoryTree([
- {
- id: "root",
- name: "/",
- path: "/",
+ const rootTreeItems = rootFolders.map((folder: DirectoryItemData) => ({
+ id: `folder-${folder.name}`,
+ name: folder.name,
+ path: folder.path,
type: "folder" as const,
isExpanded: false,
children: [],
- },
- ]);
- }
- };
+ }));
+
+ setDirectoryTree([
+ {
+ id: "root",
+ name: "/",
+ path: "/",
+ type: "folder" as const,
+ isExpanded: true,
+ children: rootTreeItems,
+ },
+ ]);
+ } catch (error: unknown) {
+ const status =
+ (error as { status?: number })?.status ||
+ (error as { response?: { status?: number } })?.response?.status;
+ if (status === 409 && attempt < 3) {
+ // Another request was already listing "/" — retry after a short delay
+ setTimeout(() => loadDirectoryTree(attempt + 1), 600);
+ return;
+ }
+ console.error("Failed to load directory tree:", error);
+ setDirectoryTree([
+ {
+ id: "root",
+ name: "/",
+ path: "/",
+ type: "folder" as const,
+ isExpanded: false,
+ children: [],
+ },
+ ]);
+ }
+ },
+ [sshSessionId],
+ );
/**
* Lazily fetches subdirectory contents and patches them into the tree state.
@@ -304,6 +273,43 @@ export function FileManagerSidebar({
[sshSessionId],
);
+ useEffect(() => {
+ loadQuickAccessData();
+ }, [loadQuickAccessData, refreshTrigger]);
+
+ useEffect(() => {
+ if (sshSessionId) {
+ loadedFoldersRef.current = new Set(["/"]);
+ loadDirectoryTree();
+ }
+ }, [loadDirectoryTree, sshSessionId]);
+
+ // When currentPath changes externally (grid navigation), ensure the parent
+ // directory is loaded in the tree so the selection highlight can appear.
+ useEffect(() => {
+ if (!sshSessionId || currentPath === "/") return;
+
+ const parentPath =
+ currentPath.substring(0, currentPath.lastIndexOf("/")) || "/";
+
+ const findByPath = (items: SidebarItem[]): SidebarItem | null => {
+ for (const item of items) {
+ if (item.path === parentPath) return item;
+ if (item.children) {
+ const found = findByPath(item.children);
+ if (found) return found;
+ }
+ }
+ return null;
+ };
+
+ const parent = findByPath(directoryTree);
+ if (parent && !loadedFoldersRef.current.has(parent.path)) {
+ loadedFoldersRef.current.add(parent.path);
+ loadSubdirectory(parent.id, parent.path);
+ }
+ }, [currentPath, directoryTree, loadSubdirectory, sshSessionId]);
+
// ─── Quick-access mutation handlers ──────────────────────────────────────────
const handleRemoveRecentFile = async (item: SidebarItem) => {
@@ -415,18 +421,47 @@ export function FileManagerSidebar({
// ─── Context menu ─────────────────────────────────────────────────────────────
- const handleContextMenu = (e: React.MouseEvent, item: SidebarItem) => {
+ const findTreeItemById = useCallback(
+ (items: SidebarItem[], id: string): SidebarItem | null => {
+ for (const item of items) {
+ if (item.id === id) return item;
+ if (item.children) {
+ const found = findTreeItemById(item.children, id);
+ if (found) return found;
+ }
+ }
+ return null;
+ },
+ [],
+ );
+
+ const handleItemContextMenu = (e: React.MouseEvent, item: SidebarItem) => {
e.preventDefault();
e.stopPropagation();
+ if (onItemContextMenu) {
+ onItemContextMenu(e, item);
+ return;
+ }
setContextMenu({ x: e.clientX, y: e.clientY, isVisible: true, item });
};
+ const handleTreeContextMenu = (e: React.MouseEvent) => {
+ const target = e.target as HTMLElement;
+ const row = target.closest<HTMLElement>("[data-id]");
+ if (!row) return;
+ const id = row.getAttribute("data-id");
+ if (!id) return;
+ const item = findTreeItemById(directoryTree, id);
+ if (!item || item.type !== "folder") return;
+ handleItemContextMenu(e, item);
+ };
+
const closeContextMenu = () => {
setContextMenu((prev) => ({ ...prev, isVisible: false, item: null }));
};
useEffect(() => {
- if (!contextMenu.isVisible) return;
+ if (!contextMenu.isVisible || onItemContextMenu) return;
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as Element;
@@ -448,7 +483,7 @@ export function FileManagerSidebar({
document.removeEventListener("mousedown", handleClickOutside);
document.removeEventListener("keydown", handleKeyDown);
};
- }, [contextMenu.isVisible]);
+ }, [contextMenu.isVisible, onItemContextMenu]);
// ─── Derive selected tree node + ancestors from currentPath ──────────────────
@@ -515,7 +550,7 @@ export function FileManagerSidebar({
: "text-muted-foreground hover:text-foreground hover:bg-muted border-transparent",
)}
onClick={() => handleQuickAccessClick(item)}
- onContextMenu={(e) => handleContextMenu(e, item)}
+ onContextMenu={(e) => handleItemContextMenu(e, item)}
title={item.path}
>
<div className="shrink-0">{icon}</div>
@@ -612,16 +647,18 @@ export function FileManagerSidebar({
</span>
</div>
<div className="px-1">
- <FolderTree.Root
- id="sidebar-directory-tree"
- defaultExpanded={["root"]}
- selectedId={selectedTreeId}
- expandedIds={ancestorIds}
- onSelect={(id) => handleDirectorySelect(id)}
- className="bg-transparent border-0 rounded-none shadow-none"
- >
- {directoryTree.map((item) => renderFolderTreeItem(item))}
- </FolderTree.Root>
+ <div onContextMenu={handleTreeContextMenu}>
+ <FolderTree.Root
+ id="sidebar-directory-tree"
+ defaultExpanded={["root"]}
+ selectedId={selectedTreeId}
+ expandedIds={ancestorIds}
+ onSelect={(id) => handleDirectorySelect(id)}
+ className="bg-transparent border-0 rounded-none shadow-none"
+ >
+ {directoryTree.map((item) => renderFolderTreeItem(item))}
+ </FolderTree.Root>
+ </div>
</div>
</div>
@@ -679,8 +716,8 @@ export function FileManagerSidebar({
)}
</div>
- {/* ── Context menu ─────────────────────────────────────────────── */}
- {contextMenu.isVisible && contextMenu.item && (
+ {/* ── Context menu (fallback when parent does not supply onItemContextMenu) */}
+ {!onItemContextMenu && contextMenu.isVisible && contextMenu.item && (
<>
<div className="fixed inset-0 z-40" />
diff --git a/src/ui/features/file-manager/FileManagerToolbar.tsx b/src/ui/features/file-manager/FileManagerToolbar.tsx
new file mode 100644
index 000000000..c98800b51
--- /dev/null
+++ b/src/ui/features/file-manager/FileManagerToolbar.tsx
@@ -0,0 +1,349 @@
+import React from "react";
+import {
+ ArrowUp,
+ ChevronLeft,
+ ChevronRight,
+ Copy,
+ FilePlus,
+ Folder,
+ FolderPlus,
+ Grid3X3,
+ Layout,
+ List,
+ Plus,
+ RefreshCw,
+ Search,
+ Trash2,
+ Upload,
+} from "lucide-react";
+import { Button } from "@/components/button.tsx";
+import { Input } from "@/components/input.tsx";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/dropdown-menu.tsx";
+import type { FileItem } from "@/types/index";
+
+type SortBy = "name" | "modified" | "size";
+type SortOrder = "asc" | "desc";
+type ViewMode = "grid" | "list";
+
+type FileManagerToolbarProps = {
+ t: (key: string) => string;
+ currentPath: string;
+ navIndex: number;
+ navHistoryLength: number;
+ isLoading: boolean;
+ sshSessionId: string | null;
+ selectedFiles: FileItem[];
+ searchQuery: string;
+ setSearchQuery: (query: string) => void;
+ viewMode: ViewMode;
+ setViewMode: (mode: ViewMode) => void;
+ sortBy: SortBy;
+ setSortBy: (sortBy: SortBy) => void;
+ sortOrder: SortOrder;
+ setSortOrder: (sortOrder: SortOrder) => void;
+ setMobileSidebarOpen: (updater: (open: boolean) => boolean) => void;
+ goBack: () => void;
+ goForward: () => void;
+ goUp: () => void;
+ navigateTo: (path: string) => void;
+ handleRefreshDirectory: () => void;
+ handleDeleteFiles: (files: FileItem[]) => void;
+ handleCopyFiles: (files: FileItem[]) => void;
+ handleFilesDropped: (fileList: FileList) => void;
+ handleCreateNewFolder: () => void;
+ handleCreateNewFile: () => void;
+};
+
+function Breadcrumb({
+ currentPath,
+ navigateTo,
+ t,
+}: Pick<FileManagerToolbarProps, "currentPath" | "navigateTo" | "t">) {
+ return (
+ <>
+ <Folder className="size-3.5 text-accent-brand shrink-0" />
+ <div className="flex items-center gap-1 overflow-x-auto scrollbar-none text-[10px] font-bold uppercase tracking-widest whitespace-nowrap">
+ {currentPath.split("/").map((part, i, arr) => (
+ <React.Fragment key={i}>
+ {part === "" && i === 0 ? (
+ <button
+ onClick={() => navigateTo("/")}
+ className="hover:text-accent-brand transition-colors"
+ >
+ {t("fileManager.root")}
+ </button>
+ ) : part !== "" ? (
+ <button
+ onClick={() => navigateTo(arr.slice(0, i + 1).join("/") || "/")}
+ className="hover:text-accent-brand transition-colors"
+ >
+ {part}
+ </button>
+ ) : null}
+ {i < arr.length - 1 && part !== "" && (
+ <ChevronRight className="size-3 text-muted-foreground shrink-0" />
+ )}
+ {i === 0 && arr.length > 1 && part === "" && (
+ <ChevronRight className="size-3 text-muted-foreground shrink-0" />
+ )}
+ </React.Fragment>
+ ))}
+ </div>
+ </>
+ );
+}
+
+export function FileManagerToolbar({
+ t,
+ currentPath,
+ navIndex,
+ navHistoryLength,
+ isLoading,
+ sshSessionId,
+ selectedFiles,
+ searchQuery,
+ setSearchQuery,
+ viewMode,
+ setViewMode,
+ sortBy,
+ setSortBy,
+ sortOrder,
+ setSortOrder,
+ setMobileSidebarOpen,
+ goBack,
+ goForward,
+ goUp,
+ navigateTo,
+ handleRefreshDirectory,
+ handleDeleteFiles,
+ handleCopyFiles,
+ handleFilesDropped,
+ handleCreateNewFolder,
+ handleCreateNewFile,
+}: FileManagerToolbarProps) {
+ return (
+ <div className="flex flex-col shrink-0 mx-3 mt-3 border border-border bg-card">
+ <div className="flex flex-row items-center justify-between px-3 py-2 gap-2">
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => setMobileSidebarOpen((open) => !open)}
+ className="md:hidden size-8 rounded-none"
+ title={t("fileManager.toggleSidebar")}
+ >
+ <Layout className="size-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={goBack}
+ disabled={navIndex <= 0}
+ className="size-8 rounded-none"
+ >
+ <ChevronLeft className="size-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={goForward}
+ disabled={navIndex >= navHistoryLength - 1}
+ className="size-8 rounded-none"
+ >
+ <ChevronRight className="size-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={goUp}
+ disabled={currentPath === "/"}
+ className="size-8 rounded-none"
+ >
+ <ArrowUp className="size-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={handleRefreshDirectory}
+ className="size-8 rounded-none"
+ >
+ <RefreshCw
+ className={`size-4 ${isLoading && !!sshSessionId ? "animate-spin [animation-duration:0.5s]" : ""}`}
+ />
+ </Button>
+ </div>
+
+ <div className="hidden md:flex flex-1 items-center px-3 h-8 bg-muted/50 border border-border rounded-none gap-2 overflow-hidden">
+ <Breadcrumb currentPath={currentPath} navigateTo={navigateTo} t={t} />
+ </div>
+
+ <div className="flex items-center gap-2">
+ {selectedFiles.length > 0 && (
+ <div className="flex items-center gap-1 px-2 py-1 bg-accent-brand/10 border border-accent-brand/20 text-accent-brand text-[10px] font-black uppercase tracking-tighter">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-accent-brand hover:bg-accent-brand/20 rounded-none"
+ onClick={() => handleDeleteFiles(selectedFiles)}
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-accent-brand hover:bg-accent-brand/20 rounded-none"
+ onClick={() => handleCopyFiles(selectedFiles)}
+ >
+ <Copy className="size-3.5" />
+ </Button>
+ </div>
+ )}
+
+ <div className="relative w-28 md:w-48">
+ <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground" />
+ <Input
+ placeholder={t("fileManager.searchFiles")}
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="h-8 pl-8 text-xs bg-muted/50 border-border rounded-none focus:ring-1 focus:ring-accent-brand/50"
+ />
+ </div>
+
+ <div className="flex items-center border border-border rounded-none overflow-hidden">
+ <Button
+ variant={viewMode === "grid" ? "secondary" : "ghost"}
+ size="icon"
+ onClick={() => setViewMode("grid")}
+ className={`size-8 rounded-none border-y-0 border-l-0 border-r border-border ${viewMode === "grid" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
+ >
+ <Grid3X3 className="size-4" />
+ </Button>
+ <Button
+ variant={viewMode === "list" ? "secondary" : "ghost"}
+ size="icon"
+ onClick={() => setViewMode("list")}
+ className={`size-8 rounded-none border-y-0 border-r-0 border-border ${viewMode === "list" ? "bg-accent-brand/10 text-accent-brand" : ""}`}
+ >
+ <List className="size-4" />
+ </Button>
+ </div>
+
+ <label
+ className="hidden md:block cursor-pointer"
+ title={t("fileManager.upload")}
+ >
+ <input
+ type="file"
+ multiple
+ className="hidden"
+ onChange={(e) => {
+ const files = e.target.files;
+ if (files) handleFilesDropped(files);
+ }}
+ />
+ <div className="h-8 px-3 flex items-center gap-1.5 border border-border hover:bg-muted text-muted-foreground hover:text-foreground transition-colors text-[10px] font-bold uppercase tracking-widest">
+ <Upload className="size-3.5" /> {t("fileManager.upload")}
+ </div>
+ </label>
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8 gap-1.5 border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 rounded-none font-bold uppercase tracking-widest text-[10px]"
+ >
+ <Plus className="size-3.5" />
+ {t("fileManager.new")}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="end"
+ className="w-44 rounded-none border-border bg-card"
+ onCloseAutoFocus={(e) => e.preventDefault()}
+ >
+ <DropdownMenuItem
+ onSelect={() => {
+ setTimeout(() => handleCreateNewFolder(), 0);
+ }}
+ className="rounded-none text-xs font-semibold gap-2 focus:bg-accent-brand/10 focus:text-accent-brand"
+ >
+ <FolderPlus className="size-4 text-accent-brand" />
+ {t("fileManager.newFolder")}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={() => {
+ setTimeout(() => handleCreateNewFile(), 0);
+ }}
+ className="rounded-none text-xs font-semibold gap-2 focus:bg-accent-brand/10 focus:text-accent-brand"
+ >
+ <FilePlus className="size-4 text-muted-foreground" />
+ {t("fileManager.newFile")}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel className="text-[10px] uppercase tracking-widest text-muted-foreground py-1">
+ {t("fileManager.sortBy")}
+ </DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={sortBy}
+ onValueChange={(value) => setSortBy(value as SortBy)}
+ >
+ <DropdownMenuRadioItem
+ value="name"
+ className="rounded-none text-xs"
+ >
+ {t("fileManager.sortByName")}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="modified"
+ className="rounded-none text-xs"
+ >
+ {t("fileManager.sortByDate")}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="size"
+ className="rounded-none text-xs"
+ >
+ {t("fileManager.sortBySize")}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuRadioGroup
+ value={sortOrder}
+ onValueChange={(value) => setSortOrder(value as SortOrder)}
+ >
+ <DropdownMenuRadioItem
+ value="asc"
+ className="rounded-none text-xs"
+ >
+ {t("fileManager.ascending")}
+ </DropdownMenuRadioItem>
+ <DropdownMenuRadioItem
+ value="desc"
+ className="rounded-none text-xs"
+ >
+ {t("fileManager.descending")}
+ </DropdownMenuRadioItem>
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+
+ <div className="md:hidden flex items-center px-3 pb-2 gap-2">
+ <div className="flex-1 flex items-center px-3 h-8 bg-muted/50 border border-border gap-2 overflow-hidden">
+ <Breadcrumb currentPath={currentPath} navigateTo={navigateTo} t={t} />
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/features/file-manager/TransferMonitor.tsx b/src/ui/features/file-manager/TransferMonitor.tsx
new file mode 100644
index 000000000..fade734bb
--- /dev/null
+++ b/src/ui/features/file-manager/TransferMonitor.tsx
@@ -0,0 +1,80 @@
+import { useEffect, useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { getTransferStatus, listActiveTransfers } from "@/main-axios.ts";
+import { createFormatTransferMetrics } from "./transferMetricsFormat.ts";
+import {
+ beginTransferProgressMonitoring,
+ isTransferBeingMonitored,
+ showTransferCompletionToast,
+} from "./transferProgressMonitor.tsx";
+import {
+ clearStalePendingTransfer,
+ getPendingTransferIds,
+ isTransferNotified,
+} from "./transferNotificationStore.ts";
+
+const POLL_INTERVAL_MS = 2000;
+
+export function TransferMonitor() {
+ const { t } = useTranslation();
+ const formatTransferMetrics = useMemo(
+ () => createFormatTransferMetrics(t),
+ [t],
+ );
+
+ useEffect(() => {
+ const reconcileTransfers = async () => {
+ try {
+ const { transfers } = await listActiveTransfers();
+ for (const transfer of transfers) {
+ if (isTransferBeingMonitored(transfer.transferId)) continue;
+ beginTransferProgressMonitoring(transfer.transferId, t, {
+ resumed: true,
+ initialStatus: transfer,
+ formatTransferMetrics,
+ });
+ }
+ } catch {
+ // Non-fatal: file-manager service may be unavailable briefly
+ }
+
+ for (const transferId of getPendingTransferIds()) {
+ if (
+ isTransferBeingMonitored(transferId) ||
+ isTransferNotified(transferId)
+ ) {
+ continue;
+ }
+
+ try {
+ const status = await getTransferStatus(transferId);
+ if (status.status === "running") {
+ if (!isTransferBeingMonitored(transferId)) {
+ beginTransferProgressMonitoring(transferId, t, {
+ resumed: true,
+ initialStatus: status,
+ formatTransferMetrics,
+ });
+ }
+ continue;
+ }
+
+ showTransferCompletionToast(
+ status,
+ t,
+ undefined,
+ formatTransferMetrics,
+ );
+ } catch {
+ clearStalePendingTransfer(transferId);
+ }
+ }
+ };
+
+ void reconcileTransfers();
+ const interval = setInterval(reconcileTransfers, POLL_INTERVAL_MS);
+ return () => clearInterval(interval);
+ }, [t, formatTransferMetrics]);
+
+ return null;
+}
diff --git a/src/ui/features/file-manager/components/DiffViewer.tsx b/src/ui/features/file-manager/components/DiffViewer.tsx
index 05ffbd582..74031e875 100644
--- a/src/ui/features/file-manager/components/DiffViewer.tsx
+++ b/src/ui/features/file-manager/components/DiffViewer.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect } from "react";
import { DiffEditor } from "@monaco-editor/react";
import { Button } from "@/components/button.tsx";
diff --git a/src/ui/features/file-manager/components/FileViewer.tsx b/src/ui/features/file-manager/components/FileViewer.tsx
index b7712ae5c..321f9d652 100644
--- a/src/ui/features/file-manager/components/FileViewer.tsx
+++ b/src/ui/features/file-manager/components/FileViewer.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React, { Suspense, lazy, useState, useEffect, useRef } from "react";
import { cn } from "@/lib/utils.ts";
import { useTranslation } from "react-i18next";
@@ -38,6 +39,7 @@ import {
SiDocker,
} from "react-icons/si";
import { Button } from "@/components/button.tsx";
+import { Kbd, KbdKey } from "@/components/kbd.tsx";
import type { CodeEditorHandle } from "./CodeEditor.tsx";
const CodeEditor = lazy(() =>
diff --git a/src/ui/features/file-manager/components/FileWindow.tsx b/src/ui/features/file-manager/components/FileWindow.tsx
index 3571bc4e2..ab3ed46c5 100644
--- a/src/ui/features/file-manager/components/FileWindow.tsx
+++ b/src/ui/features/file-manager/components/FileWindow.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect, useRef } from "react";
import { DraggableWindow } from "./DraggableWindow.tsx";
import { FileViewer } from "./FileViewer.tsx";
@@ -126,7 +127,10 @@ export function FileWindow({
if (response.encoding === "base64") {
try {
- const decoded = atob(fileContent);
+ const bytes = Uint8Array.from(atob(fileContent), (c) =>
+ c.charCodeAt(0),
+ );
+ const decoded = new TextDecoder("utf-8").decode(bytes);
if (isDisplayableText(decoded)) {
fileContent = decoded;
}
diff --git a/src/ui/features/file-manager/components/TerminalWindow.tsx b/src/ui/features/file-manager/components/TerminalWindow.tsx
index 25459f385..a38f2f8ee 100644
--- a/src/ui/features/file-manager/components/TerminalWindow.tsx
+++ b/src/ui/features/file-manager/components/TerminalWindow.tsx
@@ -1,6 +1,10 @@
import React from "react";
import { DraggableWindow } from "./DraggableWindow.tsx";
-import { Terminal } from "@/features/terminal/Terminal.tsx";
+import {
+ Terminal,
+ type TerminalHandle,
+ type TerminalHostConfig,
+} from "@/features/terminal/Terminal.tsx";
import { useWindowManager } from "./WindowManager.tsx";
import { useTranslation } from "react-i18next";
import { CommandHistoryProvider } from "@/features/terminal/command-history/CommandHistoryContext.tsx";
@@ -26,7 +30,7 @@ export function TerminalWindow({
const { t } = useTranslation();
const { closeWindow, maximizeWindow, focusWindow, windows } =
useWindowManager();
- const terminalRef = React.useRef<{ fit?: () => void } | null>(null);
+ const terminalRef = React.useRef<TerminalHandle | null>(null);
const resizeTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
React.useEffect(() => {
@@ -101,8 +105,8 @@ export function TerminalWindow({
zIndex={currentWindow.zIndex}
>
<Terminal
- ref={terminalRef as any}
- hostConfig={hostConfig as any}
+ ref={terminalRef}
+ hostConfig={hostConfig as TerminalHostConfig}
isVisible={!currentWindow.isMinimized}
initialPath={initialPath}
executeCommand={executeCommand}
diff --git a/src/ui/features/file-manager/components/TransferProgressToast.tsx b/src/ui/features/file-manager/components/TransferProgressToast.tsx
new file mode 100644
index 000000000..b2d66fff2
--- /dev/null
+++ b/src/ui/features/file-manager/components/TransferProgressToast.tsx
@@ -0,0 +1,138 @@
+import { Button } from "@/components/button.tsx";
+import {
+ formatTransferMbPerSec,
+ getTransferProgressPercent,
+ type TransferProgressResponse,
+} from "@/main-axios.ts";
+import { useTranslation } from "react-i18next";
+
+interface TransferProgressToastProps {
+ status: TransferProgressResponse;
+ liveMbPerSec?: number;
+ stalled?: boolean;
+ formatSize: (bytes?: number) => string;
+ onCancel?: () => void;
+ cancelling?: boolean;
+}
+
+function IndeterminateProgressBar() {
+ return (
+ <div className="bg-primary/20 relative h-2 w-full overflow-hidden rounded-full">
+ <div className="bg-primary/60 absolute inset-y-0 left-0 w-1/3 animate-pulse rounded-full" />
+ </div>
+ );
+}
+
+function DeterminateProgressBar({ value }: { value: number }) {
+ const clamped = Math.min(100, Math.max(0, value));
+ return (
+ <div className="bg-primary/20 relative h-2 w-full overflow-hidden rounded-full">
+ <div
+ className="bg-primary h-full rounded-full transition-[width]"
+ style={{ width: `${clamped}%` }}
+ />
+ </div>
+ );
+}
+
+export function TransferProgressToast({
+ status,
+ liveMbPerSec,
+ stalled = false,
+ formatSize,
+ onCancel,
+ cancelling = false,
+}: TransferProgressToastProps) {
+ const { t } = useTranslation();
+ const percent = getTransferProgressPercent(status);
+
+ let title = t("transfer.progressTransferring");
+ if (status.phase === "reconnecting") {
+ title = t("transfer.progressReconnecting");
+ } else if (status.phase === "compressing") {
+ title = t("transfer.progressCompressing");
+ } else if (status.phase === "extracting") {
+ title = t("transfer.progressExtracting");
+ } else if (
+ status.method === "item_sftp" &&
+ status.totalItems !== undefined &&
+ status.itemsCompleted !== undefined
+ ) {
+ title = t("transfer.progressTransferringItems", {
+ current: status.itemsCompleted,
+ total: status.totalItems,
+ });
+ }
+
+ const hasByteProgress =
+ status.bytesTransferred !== undefined &&
+ status.totalBytes !== undefined &&
+ status.totalBytes > 0;
+
+ const detailLeft = hasByteProgress
+ ? t("transfer.progressBytes", {
+ transferred: formatSize(status.bytesTransferred),
+ total: formatSize(status.totalBytes),
+ })
+ : status.method === "item_sftp" &&
+ status.totalItems !== undefined &&
+ status.itemsCompleted !== undefined
+ ? t("transfer.progressItems", {
+ current: status.itemsCompleted,
+ total: status.totalItems,
+ })
+ : null;
+
+ const liveRate =
+ status.phase === "reconnecting"
+ ? undefined
+ : stalled
+ ? t("transfer.progressStalled")
+ : liveMbPerSec !== undefined
+ ? status.parallelSegmentCount && status.parallelSegmentCount > 1
+ ? t("transfer.progressTotalSpeed", {
+ speed: formatTransferMbPerSec(liveMbPerSec),
+ lanes: status.parallelSegmentCount,
+ })
+ : formatTransferMbPerSec(liveMbPerSec)
+ : undefined;
+
+ const showIndeterminate =
+ status.phase === "reconnecting" || percent === undefined;
+
+ return (
+ <div className="flex w-[min(calc(100vw-5rem),288px)] max-w-full flex-col gap-2 pr-2">
+ <div className="flex items-start justify-between gap-2">
+ <p className="text-sm font-medium leading-tight">{title}</p>
+ {onCancel && status.status === "running" && status.transferId && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-7 shrink-0 px-2 text-xs"
+ disabled={cancelling}
+ onClick={onCancel}
+ >
+ {cancelling
+ ? t("transfer.progressCancelling")
+ : t("transfer.progressCancel")}
+ </Button>
+ )}
+ </div>
+ {showIndeterminate ? (
+ <IndeterminateProgressBar />
+ ) : (
+ <DeterminateProgressBar value={percent} />
+ )}
+ <div className="flex items-center justify-between gap-3 pr-1 text-xs text-muted-foreground">
+ <span className="min-w-0 truncate">{detailLeft ?? ""}</span>
+ <span
+ className={`shrink-0 tabular-nums ${stalled ? "text-amber-500" : liveRate ? "font-medium text-foreground" : "invisible"}`}
+ aria-hidden={!liveRate}
+ >
+ {liveRate ?? "0 MB/s"}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/features/file-manager/components/TransferToHostDialog.tsx b/src/ui/features/file-manager/components/TransferToHostDialog.tsx
new file mode 100644
index 000000000..e50e0fda6
--- /dev/null
+++ b/src/ui/features/file-manager/components/TransferToHostDialog.tsx
@@ -0,0 +1,1091 @@
+import React, {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/dialog.tsx";
+import { Button } from "@/components/button.tsx";
+import { Input } from "@/components/input.tsx";
+import { Label } from "@/components/label.tsx";
+import { useTranslation } from "react-i18next";
+import { toast } from "sonner";
+import {
+ ArrowRightLeft,
+ Bookmark,
+ ChevronDown,
+ ChevronRight,
+ ChevronUp,
+ Clock,
+ Folder,
+ Trash2,
+} from "lucide-react";
+import {
+ getSSHStatus,
+ getSSHHosts,
+ getTransferRecent,
+ getFolderShortcuts,
+ addFolderShortcut,
+ removeFolderShortcut,
+ browseSSHDirectory,
+ ensureSSHSessionForHost,
+ getTransferMethodPreview,
+ type TransferDestination,
+ type HostConnectionState,
+ type TransferMethodPreference,
+ type TransferMethodPreview,
+} from "@/main-axios.ts";
+import type { SSHHost } from "@/types";
+
+interface FileItem {
+ name: string;
+ type: "file" | "directory" | "link";
+ path: string;
+}
+
+interface BrowseEntry {
+ name: string;
+ path: string;
+}
+
+interface FolderShortcutEntry {
+ id: number;
+ name: string;
+ path: string;
+}
+
+interface TransferToHostDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ files: FileItem[];
+ move: boolean;
+ sourceHost: SSHHost;
+ sourceSessionId: string | null;
+ onConfirm: (
+ destSessionId: string,
+ destHostId: number,
+ destPath: string,
+ destPathLabel: string,
+ methodPreference: TransferMethodPreference,
+ parallelSegmentCount: number,
+ ) => void;
+}
+
+function formatByteSize(bytes: number): string {
+ if (bytes <= 0) return "0 B";
+ const units = ["B", "KB", "MB", "GB", "TB"];
+ let size = bytes;
+ let unitIndex = 0;
+ while (size >= 1024 && unitIndex < units.length - 1) {
+ size /= 1024;
+ unitIndex++;
+ }
+ const formatted =
+ size < 10 && unitIndex > 0 ? size.toFixed(1) : Math.round(size).toString();
+ return `${formatted} ${units[unitIndex]}`;
+}
+
+function formatTruncatedDestination(hostLabel: string, path: string): string {
+ const normalized = path.replace(/\\/g, "/").replace(/\/+$/, "") || "/";
+ if (normalized === "/") {
+ return `${hostLabel} — /`;
+ }
+
+ const segments = normalized.split("/").filter(Boolean);
+ const pathPart =
+ segments.length <= 2
+ ? `/${segments.join("/")}`
+ : `.../${segments.slice(-2).join("/")}`;
+
+ return `${hostLabel} — ${pathPart}`;
+}
+
+function longestCommonPrefix(strings: string[]): string {
+ if (strings.length === 0) return "";
+ let prefix = strings[0];
+ for (let i = 1; i < strings.length; i++) {
+ while (!strings[i].startsWith(prefix)) {
+ prefix = prefix.slice(0, -1);
+ if (!prefix) return "";
+ }
+ }
+ return prefix;
+}
+
+function splitPathForCompletion(
+ fullPath: string,
+ cursorPos: number,
+): { dirPath: string; partial: string; replaceStart: number } {
+ const beforeCursor = fullPath.slice(0, cursorPos);
+ const lastSlash = beforeCursor.lastIndexOf("/");
+ if (lastSlash === -1) {
+ return { dirPath: "/", partial: beforeCursor, replaceStart: 0 };
+ }
+ const dirPath = beforeCursor.slice(0, lastSlash) || "/";
+ const partial = beforeCursor.slice(lastSlash + 1);
+ return { dirPath, partial, replaceStart: lastSlash + 1 };
+}
+
+function connectionStatusDot(state: HostConnectionState): string {
+ switch (state) {
+ case "ready":
+ return "bg-green-500";
+ case "connecting":
+ return "bg-yellow-500 animate-pulse";
+ case "auth_required":
+ return "bg-yellow-500";
+ case "error":
+ return "bg-red-500";
+ default:
+ return "bg-muted-foreground/40";
+ }
+}
+
+function connectionLabel(
+ state: HostConnectionState,
+ t: (key: string) => string,
+): string {
+ switch (state) {
+ case "ready":
+ return t("transfer.hostReady");
+ case "connecting":
+ return t("transfer.hostConnecting");
+ case "auth_required":
+ return t("transfer.hostAuthRequired");
+ case "error":
+ return t("transfer.hostConnectionFailed");
+ default:
+ return t("transfer.hostDisconnected");
+ }
+}
+
+export function TransferToHostDialog({
+ open,
+ onOpenChange,
+ files,
+ move,
+ sourceHost,
+ sourceSessionId,
+ onConfirm,
+}: TransferToHostDialogProps) {
+ const { t } = useTranslation();
+
+ const [availableHosts, setAvailableHosts] = useState<SSHHost[]>([]);
+ const [loadingHosts, setLoadingHosts] = useState(false);
+ const [selectedHostId, setSelectedHostId] = useState<string>("");
+ const [connectionStates, setConnectionStates] = useState<
+ Record<number, HostConnectionState>
+ >({});
+ const [connectionErrors, setConnectionErrors] = useState<
+ Record<number, string>
+ >({});
+ const [destPath, setDestPath] = useState("");
+ const [shortcuts, setShortcuts] = useState<FolderShortcutEntry[]>([]);
+ const [recents, setRecents] = useState<TransferDestination[]>([]);
+ const [browsePath, setBrowsePath] = useState("/");
+ const [browseEntries, setBrowseEntries] = useState<BrowseEntry[]>([]);
+ const [browseLoading, setBrowseLoading] = useState(false);
+ const [browseStatus, setBrowseStatus] = useState<
+ "ok" | "not_found" | "error" | "idle"
+ >("idle");
+ const skipDestBrowseSyncRef = useRef(false);
+ const destPathDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(
+ null,
+ );
+ const pendingBrowsePathRef = useRef<string | null>(null);
+ const lastBrowseHostIdRef = useRef<number | null>(null);
+ const destPathInputRef = useRef<HTMLInputElement>(null);
+ const [methodPreference, setMethodPreference] =
+ useState<TransferMethodPreference>("auto");
+ const [parallelSegmentCount, setParallelSegmentCount] = useState("2");
+ const [methodPreview, setMethodPreview] =
+ useState<TransferMethodPreview | null>(null);
+ const [methodPreviewLoading, setMethodPreviewLoading] = useState(false);
+ const [methodPreviewError, setMethodPreviewError] = useState<string | null>(
+ null,
+ );
+ const [recentsCollapsed, setRecentsCollapsed] = useState(true);
+ const methodPreviewLockKeyRef = useRef<string | null>(null);
+ const archiveSourcePathsKey = useMemo(
+ () => files.map((f) => f.path).join("\0"),
+ [files],
+ );
+
+ const isSingleFile = files.length === 1 && files[0].type === "file";
+ const isArchiveTransfer = !isSingleFile;
+
+ const sourceLabel = useMemo(() => {
+ if (files.length === 1) {
+ return `${sourceHost.name || sourceHost.ip}:${files[0].path}`;
+ }
+ return `${sourceHost.name || sourceHost.ip}: ${t("transfer.itemsSummary", { count: files.length })}`;
+ }, [files, sourceHost, t]);
+
+ const selectedHost = availableHosts.find(
+ (h) => h.id.toString() === selectedHostId,
+ );
+
+ const selectedConnectionState = selectedHost
+ ? (connectionStates[selectedHost.id] ?? "disconnected")
+ : "disconnected";
+
+ const isHostReady = selectedConnectionState === "ready";
+
+ const loadAvailableHosts = useCallback(async () => {
+ setLoadingHosts(true);
+ try {
+ const hosts = await getSSHHosts();
+ const candidates = hosts.filter(
+ (h) =>
+ h.id !== sourceHost.id &&
+ h.enableFileManager !== false &&
+ h.connectionType !== "rdp" &&
+ h.connectionType !== "vnc",
+ );
+ setAvailableHosts(candidates);
+
+ const initialStates: Record<number, HostConnectionState> = {};
+ await Promise.all(
+ candidates.map(async (host) => {
+ try {
+ const status = await getSSHStatus(host.id.toString());
+ initialStates[host.id] = status?.connected
+ ? "ready"
+ : "disconnected";
+ } catch {
+ initialStates[host.id] = "disconnected";
+ }
+ }),
+ );
+ setConnectionStates(initialStates);
+ } catch {
+ setAvailableHosts([]);
+ } finally {
+ setLoadingHosts(false);
+ }
+ }, [sourceHost.id]);
+
+ const ensureHostConnection = useCallback(async (host: SSHHost) => {
+ setConnectionStates((prev) => ({ ...prev, [host.id]: "connecting" }));
+ setConnectionErrors((prev) => {
+ const next = { ...prev };
+ delete next[host.id];
+ return next;
+ });
+
+ const result = await ensureSSHSessionForHost(host);
+ setConnectionStates((prev) => ({ ...prev, [host.id]: result.state }));
+ if (result.error) {
+ setConnectionErrors((prev) => ({
+ ...prev,
+ [host.id]: result.error!,
+ }));
+ }
+ }, []);
+
+ const loadRecents = useCallback(async () => {
+ if (!sourceHost.id) return;
+ try {
+ const recentData = await getTransferRecent(sourceHost.id);
+ setRecents(recentData);
+ } catch {
+ setRecents([]);
+ }
+ }, [sourceHost.id]);
+
+ const loadShortcutsForHost = useCallback(async (hostId: number) => {
+ try {
+ const data = await getFolderShortcuts(hostId);
+ setShortcuts((Array.isArray(data) ? data : []) as FolderShortcutEntry[]);
+ } catch {
+ setShortcuts([]);
+ }
+ }, []);
+
+ const syncDestPathFromBrowse = useCallback((path: string) => {
+ skipDestBrowseSyncRef.current = true;
+ setDestPath(path);
+ }, []);
+
+ const loadBrowseDirectory = useCallback(
+ async (sessionId: string, path: string, syncDest = true) => {
+ setBrowseLoading(true);
+ try {
+ const result = await browseSSHDirectory(sessionId, path);
+
+ if (result.status === "ok") {
+ const dirs = result.files
+ .filter(
+ (entry) =>
+ entry.type === "directory" &&
+ entry.name !== "." &&
+ entry.name !== "..",
+ )
+ .map((entry) => {
+ const base = result.path.endsWith("/")
+ ? result.path.slice(0, -1)
+ : result.path;
+ const childPath =
+ base === "/" ? `/${entry.name}` : `${base}/${entry.name}`;
+ return { name: entry.name, path: childPath };
+ })
+ .sort((a, b) => a.name.localeCompare(b.name));
+
+ setBrowsePath(result.path);
+ setBrowseEntries(dirs);
+ setBrowseStatus("ok");
+ if (syncDest) {
+ syncDestPathFromBrowse(result.path);
+ }
+ } else if (result.status === "not_found") {
+ setBrowsePath(result.path);
+ setBrowseEntries([]);
+ setBrowseStatus("not_found");
+ if (syncDest) {
+ syncDestPathFromBrowse(result.path);
+ }
+ } else {
+ setBrowseEntries([]);
+ setBrowseStatus("error");
+ }
+ } catch {
+ setBrowseEntries([]);
+ setBrowseStatus("error");
+ } finally {
+ setBrowseLoading(false);
+ }
+ },
+ [syncDestPathFromBrowse],
+ );
+
+ useEffect(() => {
+ if (open) {
+ void loadAvailableHosts();
+ void loadRecents();
+ setSelectedHostId("");
+ setDestPath("");
+ setShortcuts([]);
+ setBrowsePath("/");
+ setBrowseEntries([]);
+ setBrowseStatus("idle");
+ setConnectionErrors({});
+ setMethodPreference("auto");
+ setParallelSegmentCount("2");
+ setMethodPreview(null);
+ setMethodPreviewError(null);
+ methodPreviewLockKeyRef.current = null;
+ setRecentsCollapsed(true);
+ pendingBrowsePathRef.current = null;
+ lastBrowseHostIdRef.current = null;
+ }
+ }, [open, loadAvailableHosts, loadRecents]);
+
+ useEffect(() => {
+ if (!open || !selectedHost?.id) {
+ setShortcuts([]);
+ return;
+ }
+ void loadShortcutsForHost(selectedHost.id);
+ }, [open, selectedHost?.id, loadShortcutsForHost]);
+
+ useEffect(() => {
+ if (!selectedHost || !isHostReady) return;
+
+ const hostId = selectedHost.id;
+ if (lastBrowseHostIdRef.current === hostId) return;
+
+ const path = pendingBrowsePathRef.current ?? (destPath.trim() || "/");
+ pendingBrowsePathRef.current = null;
+ lastBrowseHostIdRef.current = hostId;
+ void loadBrowseDirectory(hostId.toString(), path);
+ }, [selectedHost, isHostReady, destPath, loadBrowseDirectory]);
+
+ useEffect(() => {
+ if (selectedHost && selectedConnectionState === "disconnected") {
+ void ensureHostConnection(selectedHost);
+ }
+ }, [selectedHost, selectedConnectionState, ensureHostConnection]);
+
+ useEffect(() => {
+ if (!selectedHost || !isHostReady || !open) return;
+
+ if (skipDestBrowseSyncRef.current) {
+ skipDestBrowseSyncRef.current = false;
+ return;
+ }
+
+ const typed = destPath.trim();
+ if (!typed) return;
+
+ if (destPathDebounceRef.current) {
+ clearTimeout(destPathDebounceRef.current);
+ }
+
+ destPathDebounceRef.current = setTimeout(() => {
+ void loadBrowseDirectory(selectedHost.id.toString(), typed, false);
+ }, 400);
+
+ return () => {
+ if (destPathDebounceRef.current) {
+ clearTimeout(destPathDebounceRef.current);
+ }
+ };
+ }, [destPath, selectedHost, isHostReady, open, loadBrowseDirectory]);
+
+ const hostName = (hostId: number) =>
+ availableHosts.find((h) => h.id === hostId)?.name ||
+ availableHosts.find((h) => h.id === hostId)?.ip ||
+ hostId.toString();
+
+ const handleSelectDestination = (destHostId: number, path: string) => {
+ pendingBrowsePathRef.current = path;
+ setSelectedHostId(destHostId.toString());
+ setDestPath(path);
+ const host = availableHosts.find((h) => h.id === destHostId);
+ if (host && connectionStates[host.id] === "ready") {
+ lastBrowseHostIdRef.current = host.id;
+ void loadBrowseDirectory(host.id.toString(), path);
+ } else {
+ lastBrowseHostIdRef.current = null;
+ }
+ };
+
+ useEffect(() => {
+ if (!open || !isArchiveTransfer || !sourceSessionId) {
+ if (!open || !isArchiveTransfer) {
+ setMethodPreview(null);
+ setMethodPreviewError(null);
+ methodPreviewLockKeyRef.current = null;
+ }
+ return;
+ }
+
+ const lockKey = `${archiveSourcePathsKey}|${methodPreference}|${selectedHost?.id}|${destPath.trim() || browsePath}`;
+ if (methodPreviewLockKeyRef.current === lockKey) {
+ return;
+ }
+
+ if (!selectedHost || !isHostReady) {
+ return;
+ }
+
+ const sourcePaths = files.map((f) => f.path);
+ const previewPath =
+ (destPath.trim() || browsePath || "/").replace(/\/+$/, "") || "/";
+
+ let cancelled = false;
+ setMethodPreviewLoading(true);
+ setMethodPreviewError(null);
+
+ void getTransferMethodPreview(
+ sourceSessionId,
+ sourcePaths,
+ selectedHost.id.toString(),
+ previewPath,
+ methodPreference,
+ )
+ .then((preview) => {
+ if (!cancelled) {
+ setMethodPreview(preview);
+ methodPreviewLockKeyRef.current = lockKey;
+ }
+ })
+ .catch((err: { message?: string }) => {
+ if (!cancelled) {
+ setMethodPreview(null);
+ setMethodPreviewError(err.message ?? "Preview failed");
+ }
+ })
+ .finally(() => {
+ if (!cancelled) setMethodPreviewLoading(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ open,
+ isArchiveTransfer,
+ sourceSessionId,
+ selectedHost,
+ isHostReady,
+ archiveSourcePathsKey,
+ methodPreference,
+ destPath,
+ browsePath,
+ files,
+ ]);
+
+ const handleHostChange = (hostId: string) => {
+ setSelectedHostId(hostId);
+ setBrowsePath("/");
+ setDestPath("");
+ setShortcuts([]);
+ setMethodPreview(null);
+ setMethodPreviewError(null);
+ methodPreviewLockKeyRef.current = null;
+ pendingBrowsePathRef.current = null;
+ lastBrowseHostIdRef.current = null;
+ };
+
+ const handleBrowseInto = (path: string) => {
+ if (!selectedHost || !isHostReady) return;
+ void loadBrowseDirectory(selectedHost.id.toString(), path, true);
+ };
+
+ const handleBrowseUp = () => {
+ if (!selectedHost || !isHostReady || browsePath === "/") return;
+ const trimmed = browsePath.replace(/\/+$/, "");
+ const idx = trimmed.lastIndexOf("/");
+ const parent = idx <= 0 ? "/" : trimmed.substring(0, idx);
+ void loadBrowseDirectory(selectedHost.id.toString(), parent, true);
+ };
+
+ const formatBrowsePathLabel = (path: string): string => {
+ const normalized = path.replace(/\\/g, "/").replace(/\/+$/, "") || "/";
+ if (normalized === "/") return "/";
+ const segments = normalized.split("/").filter(Boolean);
+ if (segments.length <= 3) return normalized;
+ return `.../${segments.slice(-2).join("/")}`;
+ };
+
+ const handleAddShortcut = async () => {
+ if (!selectedHost || !destPath.trim()) {
+ return;
+ }
+
+ const trimmedPath = destPath.trim();
+ if (shortcuts.some((entry) => entry.path === trimmedPath)) {
+ return;
+ }
+
+ const folderName = trimmedPath.split("/").pop() || trimmedPath;
+ try {
+ await addFolderShortcut(selectedHost.id, trimmedPath, folderName);
+ await loadShortcutsForHost(selectedHost.id);
+ toast.success(
+ t("fileManager.shortcutAddedSuccessfully", { name: folderName }),
+ );
+ } catch {
+ /* toast handled by API */
+ }
+ };
+
+ const handleRemoveShortcut = async (path: string) => {
+ if (!selectedHost) return;
+ try {
+ await removeFolderShortcut(selectedHost.id, path);
+ await loadShortcutsForHost(selectedHost.id);
+ const folderName = path.split("/").pop() || path;
+ toast.success(t("fileManager.removedShortcut", { name: folderName }));
+ } catch {
+ /* toast handled by API */
+ }
+ };
+
+ const handleDestPathKeyDown = (
+ event: React.KeyboardEvent<HTMLInputElement>,
+ ) => {
+ if (
+ event.key !== "Tab" ||
+ event.shiftKey ||
+ !selectedHost ||
+ !isHostReady
+ ) {
+ return;
+ }
+
+ event.preventDefault();
+ const input = destPathInputRef.current;
+ if (!input) return;
+
+ const currentPath = input.value;
+ const cursorPos = input.selectionStart ?? currentPath.length;
+ const { dirPath, partial, replaceStart } = splitPathForCompletion(
+ currentPath,
+ cursorPos,
+ );
+ if (!partial) return;
+
+ void browseSSHDirectory(selectedHost.id.toString(), dirPath).then(
+ (result) => {
+ if (result.status !== "ok") return;
+
+ const dirNames = result.files
+ .filter(
+ (entry) =>
+ entry.type === "directory" &&
+ entry.name !== "." &&
+ entry.name !== "..",
+ )
+ .map((entry) => entry.name);
+
+ const matches = dirNames.filter((name) => name.startsWith(partial));
+ if (matches.length === 0) return;
+
+ let completedName: string;
+ let appendSlash = false;
+ if (matches.length === 1) {
+ completedName = matches[0];
+ appendSlash = true;
+ } else {
+ completedName = longestCommonPrefix(matches);
+ if (completedName.length <= partial.length) return;
+ appendSlash = matches.every((name) => name === completedName);
+ }
+
+ const suffix = currentPath.slice(cursorPos);
+ const newPath =
+ currentPath.slice(0, replaceStart) +
+ completedName +
+ (appendSlash ? "/" : "") +
+ suffix;
+ const newCursor =
+ replaceStart + completedName.length + (appendSlash ? 1 : 0);
+
+ skipDestBrowseSyncRef.current = true;
+ setDestPath(newPath);
+ requestAnimationFrame(() => {
+ input.setSelectionRange(newCursor, newCursor);
+ });
+ },
+ );
+ };
+
+ const buildDestPath = (): string => {
+ const base = destPath.replace(/\/+$/, "") || "/";
+ if (isSingleFile) {
+ return base.endsWith("/")
+ ? `${base}${files[0].name}`
+ : `${base}/${files[0].name}`;
+ }
+ return base;
+ };
+
+ const handleConfirm = () => {
+ if (!selectedHost || !destPath.trim() || !isHostReady) return;
+ const fullPath = buildDestPath();
+ onConfirm(
+ selectedHost.id.toString(),
+ selectedHost.id,
+ fullPath,
+ destPath.trim(),
+ methodPreference,
+ Math.max(1, Math.min(8, parseInt(parallelSegmentCount, 10) || 2)),
+ );
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="w-[calc(100vw-2rem)] sm:max-w-lg rounded-none border-border bg-card">
+ <DialogHeader>
+ <DialogTitle className="text-xs font-bold uppercase tracking-widest flex items-center gap-2">
+ <ArrowRightLeft className="size-4 text-accent-brand" />
+ {move
+ ? files.length > 1
+ ? t("transfer.moveItemsToHost", { count: files.length })
+ : t("transfer.moveToHost")
+ : files.length > 1
+ ? t("transfer.copyItemsToHost", { count: files.length })
+ : t("transfer.copyToHost")}
+ </DialogTitle>
+ <DialogDescription
+ className="text-[10px] font-bold uppercase tracking-tight text-muted-foreground font-mono truncate"
+ title={sourceLabel}
+ >
+ {sourceLabel}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-4 py-2 max-h-[min(60vh,28rem)] overflow-y-auto overflow-x-hidden">
+ {loadingHosts ? (
+ <p className="text-xs text-muted-foreground">
+ {t("fileManager.connecting")}
+ </p>
+ ) : availableHosts.length === 0 ? (
+ <div className="border border-border bg-muted/10 p-3">
+ <p className="text-xs font-semibold">
+ {t("transfer.noHostsConnected")}
+ </p>
+ <p className="mt-1 text-[10px] text-muted-foreground">
+ {t("transfer.noHostsConnectedHint")}
+ </p>
+ </div>
+ ) : (
+ <>
+ {/* Destination host */}
+ <div className="flex flex-col gap-1.5">
+ <Label className="text-xs font-bold uppercase tracking-widest text-muted-foreground">
+ {t("transfer.selectDestinationHost")}
+ </Label>
+ <div className="relative">
+ <select
+ value={selectedHostId}
+ onChange={(e) => handleHostChange(e.target.value)}
+ className="w-full appearance-none px-2.5 py-1.5 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring pr-7"
+ >
+ <option value="" disabled>
+ {t("transfer.selectDestinationHost")}
+ </option>
+ {availableHosts.map((host) => (
+ <option key={host.id} value={host.id.toString()}>
+ {host.name || host.ip}
+ </option>
+ ))}
+ </select>
+ <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 size-3 text-muted-foreground pointer-events-none" />
+ </div>
+ {selectedHost && (
+ <p
+ className={`text-[10px] font-bold uppercase tracking-widest ${
+ isHostReady
+ ? "text-green-500"
+ : selectedConnectionState === "error"
+ ? "text-red-400"
+ : "text-muted-foreground"
+ }`}
+ >
+ {connectionLabel(selectedConnectionState, t)}
+ {connectionErrors[selectedHost.id]
+ ? `: ${connectionErrors[selectedHost.id]}`
+ : ""}
+ </p>
+ )}
+ </div>
+
+ {/* Shortcuts */}
+ {selectedHost && shortcuts.length > 0 && (
+ <div className="flex flex-col gap-1.5">
+ <Label className="text-xs font-bold uppercase tracking-widest text-muted-foreground flex items-center gap-1.5">
+ <Bookmark className="size-3" />
+ {t("fileManager.folderShortcuts")}
+ </Label>
+ <div className="border border-border">
+ {shortcuts.map((entry, i) => (
+ <div
+ key={entry.id}
+ className={`flex min-w-0 items-stretch ${i < shortcuts.length - 1 ? "border-b border-border" : ""}`}
+ >
+ <button
+ type="button"
+ className="min-w-0 flex-1 text-left px-3 py-2 hover:bg-accent-brand/10 hover:text-accent-brand transition-colors"
+ onClick={() =>
+ handleSelectDestination(selectedHost.id, entry.path)
+ }
+ >
+ <span className="block truncate text-xs font-semibold">
+ {entry.name}
+ </span>
+ <span
+ className="block truncate text-[10px] text-muted-foreground font-mono"
+ title={entry.path}
+ >
+ {formatTruncatedDestination(
+ selectedHost.name || selectedHost.ip,
+ entry.path,
+ )}
+ </span>
+ </button>
+ <button
+ type="button"
+ className="shrink-0 px-3 text-muted-foreground hover:text-red-400 border-l border-border transition-colors"
+ title={t("fileManager.removeShortcut")}
+ aria-label={t("fileManager.removeShortcut")}
+ onClick={() => void handleRemoveShortcut(entry.path)}
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Recent destinations */}
+ {recents.length > 0 && (
+ <div className="flex flex-col gap-1">
+ <button
+ type="button"
+ className="flex items-center gap-1.5 text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-foreground transition-colors"
+ onClick={() => setRecentsCollapsed((prev) => !prev)}
+ aria-expanded={!recentsCollapsed}
+ >
+ {recentsCollapsed ? (
+ <ChevronRight className="size-3 shrink-0" />
+ ) : (
+ <ChevronDown className="size-3 shrink-0" />
+ )}
+ <Clock className="size-3 shrink-0" />
+ {t("transfer.recentDestinations")}
+ <span className="font-normal normal-case tracking-normal">
+ ({recents.length})
+ </span>
+ </button>
+ {!recentsCollapsed && (
+ <div className="border border-border">
+ {recents.map((recent, i) => (
+ <button
+ key={recent.id}
+ type="button"
+ className={`w-full min-w-0 text-left px-3 py-2 hover:bg-accent-brand/10 hover:text-accent-brand transition-colors ${i < recents.length - 1 ? "border-b border-border" : ""}`}
+ title={`${hostName(recent.destHostId)}:${recent.destPathLabel || recent.destPath}`}
+ onClick={() =>
+ handleSelectDestination(
+ recent.destHostId,
+ recent.destPath,
+ )
+ }
+ >
+ <span className="block truncate text-xs font-semibold">
+ {formatTruncatedDestination(
+ hostName(recent.destHostId),
+ recent.destPathLabel || recent.destPath,
+ )}
+ </span>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+
+ {/* Folder browser */}
+ {selectedHost && isHostReady && (
+ <div className="flex flex-col gap-1.5">
+ <Label className="text-xs font-bold uppercase tracking-widest text-muted-foreground">
+ {t("transfer.browseFolders")}
+ </Label>
+ <div className="border border-border">
+ <div className="flex min-w-0 items-center gap-2 border-b border-border px-2 py-1.5 bg-muted/30">
+ <button
+ type="button"
+ className="flex items-center gap-1 text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-foreground disabled:opacity-40 disabled:cursor-not-allowed transition-colors shrink-0"
+ disabled={browsePath === "/"}
+ onClick={handleBrowseUp}
+ >
+ <ChevronUp className="size-3.5" />
+ {t("transfer.goUp")}
+ </button>
+ <span
+ className="min-w-0 flex-1 truncate text-[10px] font-mono text-muted-foreground"
+ title={browsePath}
+ >
+ {formatBrowsePathLabel(browsePath)}
+ </span>
+ </div>
+ <div className="max-h-36 overflow-y-auto overflow-x-hidden">
+ {browseLoading ? (
+ <p className="text-[10px] text-muted-foreground px-3 py-2">
+ {t("fileManager.connecting")}
+ </p>
+ ) : browseStatus === "not_found" ? (
+ <p className="text-[10px] text-muted-foreground px-3 py-2">
+ {t("transfer.browsePathWillBeCreated")}
+ </p>
+ ) : browseStatus === "error" ? (
+ <p className="text-[10px] text-amber-500 px-3 py-2">
+ {t("transfer.browsePathError")}
+ </p>
+ ) : browseEntries.length === 0 ? (
+ <p className="text-[10px] text-muted-foreground px-3 py-2">
+ {t("fileManager.emptyFolder")}
+ </p>
+ ) : (
+ browseEntries.map((entry, i) => (
+ <button
+ key={entry.path}
+ type="button"
+ className={`flex w-full items-center gap-2 px-3 py-2 text-xs hover:bg-accent-brand/10 hover:text-accent-brand transition-colors ${i < browseEntries.length - 1 ? "border-b border-border" : ""}`}
+ onClick={() => handleBrowseInto(entry.path)}
+ >
+ <Folder className="size-3.5 shrink-0 text-yellow-500" />
+ <span className="truncate">{entry.name}</span>
+ </button>
+ ))
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Destination path input */}
+ <div className="flex flex-col gap-1.5">
+ <Label className="text-xs font-bold uppercase tracking-widest text-muted-foreground">
+ {t("transfer.destinationPath")}
+ </Label>
+ <Input
+ ref={destPathInputRef}
+ value={destPath}
+ onChange={(e) => setDestPath(e.target.value)}
+ onKeyDown={handleDestPathKeyDown}
+ placeholder="/home/user"
+ disabled={!selectedHost}
+ className="rounded-none bg-muted/50 border-border font-mono text-xs"
+ />
+ {isArchiveTransfer && (
+ <p className="text-[10px] text-muted-foreground">
+ {t("transfer.destMustBeDirectory")}
+ </p>
+ )}
+ </div>
+
+ {/* Bookmark button */}
+ {selectedHost && destPath.trim() && (
+ <button
+ type="button"
+ className="flex items-center gap-1.5 self-start text-[10px] font-bold uppercase tracking-widest text-muted-foreground hover:text-accent-brand transition-colors border border-border px-2.5 py-1.5 hover:border-accent-brand/40 hover:bg-accent-brand/10"
+ onClick={() => void handleAddShortcut()}
+ >
+ <Bookmark className="size-3" />
+ {t("fileManager.addToShortcuts")}
+ </button>
+ )}
+
+ {/* Transfer method + parallel lanes (archive transfers only) */}
+ {isArchiveTransfer && (
+ <>
+ <div className="flex flex-col gap-1.5">
+ <Label className="text-xs font-bold uppercase tracking-widest text-muted-foreground">
+ {t("transfer.methodLabel")}
+ </Label>
+ <div className="relative">
+ <select
+ value={methodPreference}
+ onChange={(e) =>
+ setMethodPreference(
+ e.target.value as TransferMethodPreference,
+ )
+ }
+ className="w-full appearance-none px-2.5 py-1.5 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring pr-7"
+ >
+ <option value="auto">{t("transfer.methodAuto")}</option>
+ <option value="tar">{t("transfer.methodTar")}</option>
+ <option value="item_sftp">
+ {t("transfer.methodItemSftp")}
+ </option>
+ </select>
+ <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 size-3 text-muted-foreground pointer-events-none" />
+ </div>
+ <p className="text-[10px] text-muted-foreground">
+ {methodPreference === "auto"
+ ? t("transfer.methodAutoHint")
+ : methodPreference === "tar"
+ ? t("transfer.methodTarHint")
+ : t("transfer.methodItemSftpHint")}
+ </p>
+ </div>
+
+ <div className="flex flex-col gap-1.5">
+ <Label className="text-xs font-bold uppercase tracking-widest text-muted-foreground">
+ {t("transfer.parallelSegmentsLabel")}
+ </Label>
+ <div className="relative">
+ <select
+ value={parallelSegmentCount}
+ onChange={(e) =>
+ setParallelSegmentCount(e.target.value)
+ }
+ className="w-full appearance-none px-2.5 py-1.5 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring pr-7"
+ >
+ {[1, 2, 3, 4].map((n) => (
+ <option key={n} value={n.toString()}>
+ {t("transfer.parallelSegmentsOption", { count: n })}
+ </option>
+ ))}
+ </select>
+ <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 size-3 text-muted-foreground pointer-events-none" />
+ </div>
+ <p className="text-[10px] text-muted-foreground">
+ {t("transfer.parallelSegmentsHint")}
+ </p>
+ </div>
+
+ {methodPreviewLoading && (
+ <p className="text-[10px] text-muted-foreground">
+ {t("transfer.methodPreviewLoading")}
+ </p>
+ )}
+ {methodPreviewError && (
+ <p className="text-[10px] text-amber-500">
+ {t("transfer.methodPreviewError")}
+ </p>
+ )}
+ {methodPreview && !methodPreviewLoading && (
+ <div className="border border-border bg-muted/10 px-3 py-2 flex flex-col gap-1">
+ <p className="text-[10px] font-bold uppercase tracking-widest">
+ {methodPreview.resolvedMethod === "tar"
+ ? t("transfer.methodPreviewWillUseTar")
+ : t("transfer.methodPreviewWillUseItemSftp")}
+ </p>
+ <p className="text-[10px] text-muted-foreground">
+ {t(`transfer.methodReason.${methodPreview.reasonKey}`, {
+ fileCount: methodPreview.summary.fileCount,
+ totalSize: formatByteSize(
+ methodPreview.summary.totalBytes,
+ ),
+ largestSize: formatByteSize(
+ methodPreview.summary.largestFileBytes,
+ ),
+ })}
+ </p>
+ <p className="text-[10px] text-muted-foreground">
+ {t("transfer.methodPreviewScanSummary", {
+ fileCount: methodPreview.summary.fileCount,
+ totalSize: formatByteSize(
+ methodPreview.summary.totalBytes,
+ ),
+ })}
+ </p>
+ {methodPreview.resolvedMethod === "item_sftp" && (
+ <p className="text-[10px] text-muted-foreground">
+ {t("transfer.methodItemSftpLimitation")}
+ </p>
+ )}
+ </div>
+ )}
+ </>
+ )}
+
+ <p className="text-[10px] text-muted-foreground">
+ {t("transfer.jumpHostLimitation")}
+ </p>
+ </>
+ )}
+ </div>
+
+ <DialogFooter>
+ <Button
+ variant="ghost"
+ onClick={() => onOpenChange(false)}
+ className="rounded-none text-[10px] font-bold uppercase tracking-widest"
+ >
+ {t("transfer.cancel")}
+ </Button>
+ <Button
+ variant="outline"
+ onClick={handleConfirm}
+ disabled={
+ !selectedHost ||
+ !destPath.trim() ||
+ !isHostReady ||
+ availableHosts.length === 0
+ }
+ className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 rounded-none text-[10px] font-bold uppercase tracking-widest"
+ >
+ <ArrowRightLeft className="size-3.5 mr-1" />
+ {move ? t("transfer.confirmMove") : t("transfer.confirmCopy")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/ui/features/file-manager/components/WindowManager.tsx b/src/ui/features/file-manager/components/WindowManager.tsx
index 5e2b6205b..bd442400b 100644
--- a/src/ui/features/file-manager/components/WindowManager.tsx
+++ b/src/ui/features/file-manager/components/WindowManager.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components */
import React, { useState, useCallback, useRef } from "react";
export interface WindowInstance {
diff --git a/src/ui/features/file-manager/file-manager-types.ts b/src/ui/features/file-manager/file-manager-types.ts
new file mode 100644
index 000000000..c81d7fcb9
--- /dev/null
+++ b/src/ui/features/file-manager/file-manager-types.ts
@@ -0,0 +1,32 @@
+import type { FileItem, SSHHost } from "@/types/index";
+import type { LogEntry } from "@/types/connection-log.ts";
+
+export interface FileManagerProps {
+ initialHost?: SSHHost | null;
+ onClose?: () => void;
+}
+
+export type ConnectionLogPayload = Omit<LogEntry, "id" | "timestamp">;
+
+export type SSHConnectionError = Error & {
+ connectionLogs?: ConnectionLogPayload[];
+ requires_totp?: boolean;
+ requires_warpgate?: boolean;
+ sessionId?: string;
+ prompt?: string;
+ url?: string;
+ securityKey?: string;
+ status?: string;
+ reason?: "no_keyboard" | "auth_failed" | "timeout";
+};
+
+export interface CreateIntent {
+ id: string;
+ type: "file" | "directory";
+ defaultName: string;
+ currentName: string;
+}
+
+export type PendingSudoOperation =
+ | { type: "delete"; files: FileItem[] }
+ | { type: "navigate"; path: string };
diff --git a/src/ui/features/file-manager/file-manager-utils.test.ts b/src/ui/features/file-manager/file-manager-utils.test.ts
new file mode 100644
index 000000000..91defb5f2
--- /dev/null
+++ b/src/ui/features/file-manager/file-manager-utils.test.ts
@@ -0,0 +1,33 @@
+import { describe, it, expect } from "vitest";
+import { formatFileSize } from "./file-manager-utils.js";
+
+describe("formatFileSize", () => {
+ it("returns a dash for undefined or null", () => {
+ expect(formatFileSize(undefined)).toBe("-");
+ expect(formatFileSize(null as unknown as number)).toBe("-");
+ });
+
+ it("returns 0 B for zero", () => {
+ expect(formatFileSize(0)).toBe("0 B");
+ });
+
+ it("formats bytes without decimals", () => {
+ expect(formatFileSize(512)).toBe("512 B");
+ expect(formatFileSize(1023)).toBe("1023 B");
+ });
+
+ it("formats kilobytes with one decimal under 10", () => {
+ expect(formatFileSize(1024)).toBe("1.0 KB");
+ expect(formatFileSize(1536)).toBe("1.5 KB");
+ });
+
+ it("rounds to whole numbers at or above 10 units", () => {
+ expect(formatFileSize(10 * 1024)).toBe("10 KB");
+ expect(formatFileSize(1024 * 1024)).toBe("1.0 MB");
+ });
+
+ it("scales up to larger units", () => {
+ expect(formatFileSize(1024 * 1024 * 1024)).toBe("1.0 GB");
+ expect(formatFileSize(1024 * 1024 * 1024 * 1024)).toBe("1.0 TB");
+ });
+});
diff --git a/src/ui/features/file-manager/file-manager-utils.ts b/src/ui/features/file-manager/file-manager-utils.ts
new file mode 100644
index 000000000..f7f9af927
--- /dev/null
+++ b/src/ui/features/file-manager/file-manager-utils.ts
@@ -0,0 +1,17 @@
+export function formatFileSize(bytes?: number): string {
+ if (bytes === undefined || bytes === null) return "-";
+ if (bytes === 0) return "0 B";
+
+ const units = ["B", "KB", "MB", "GB", "TB"];
+ let size = bytes;
+ let unitIndex = 0;
+
+ while (size >= 1024 && unitIndex < units.length - 1) {
+ size /= 1024;
+ unitIndex++;
+ }
+
+ const formattedSize =
+ size < 10 && unitIndex > 0 ? size.toFixed(1) : Math.round(size).toString();
+ return `${formattedSize} ${units[unitIndex]}`;
+}
diff --git a/src/ui/features/file-manager/hooks/useDragToSystemDesktop.ts b/src/ui/features/file-manager/hooks/useDragToSystemDesktop.ts
index 04277cf8b..8e84bcddb 100644
--- a/src/ui/features/file-manager/hooks/useDragToSystemDesktop.ts
+++ b/src/ui/features/file-manager/hooks/useDragToSystemDesktop.ts
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import { useState, useCallback, useRef } from "react";
import { toast } from "sonner";
import { downloadSSHFile } from "@/main-axios";
diff --git a/src/ui/features/file-manager/hooks/useFileSelection.test.ts b/src/ui/features/file-manager/hooks/useFileSelection.test.ts
new file mode 100644
index 000000000..c790a56c1
--- /dev/null
+++ b/src/ui/features/file-manager/hooks/useFileSelection.test.ts
@@ -0,0 +1,69 @@
+import { describe, it, expect } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import { useFileSelection } from "./useFileSelection.js";
+
+type FileItem = {
+ name: string;
+ type: "file" | "directory" | "link";
+ path: string;
+};
+
+const f = (name: string): FileItem => ({
+ name,
+ type: "file",
+ path: `/dir/${name}`,
+});
+
+describe("useFileSelection", () => {
+ it("single-selects, replacing prior selection", () => {
+ const { result } = renderHook(() => useFileSelection());
+ act(() => result.current.selectFile(f("a")));
+ act(() => result.current.selectFile(f("b")));
+ expect(result.current.selectedFiles.map((x) => x.name)).toEqual(["b"]);
+ expect(result.current.getSelectedCount()).toBe(1);
+ });
+
+ it("multi-selects and toggles off on repeat", () => {
+ const { result } = renderHook(() => useFileSelection());
+ act(() => result.current.selectFile(f("a"), true));
+ act(() => result.current.selectFile(f("b"), true));
+ expect(result.current.getSelectedCount()).toBe(2);
+ act(() => result.current.selectFile(f("a"), true));
+ expect(result.current.selectedFiles.map((x) => x.name)).toEqual(["b"]);
+ });
+
+ it("reports isSelected by path", () => {
+ const { result } = renderHook(() => useFileSelection());
+ act(() => result.current.selectFile(f("a")));
+ expect(result.current.isSelected(f("a"))).toBe(true);
+ expect(result.current.isSelected(f("z"))).toBe(false);
+ });
+
+ it("selects a contiguous range regardless of direction", () => {
+ const { result } = renderHook(() => useFileSelection());
+ const files = [f("a"), f("b"), f("c"), f("d")];
+ act(() => result.current.selectRange(files, files[3], files[1]));
+ expect(result.current.selectedFiles.map((x) => x.name)).toEqual([
+ "b",
+ "c",
+ "d",
+ ]);
+ });
+
+ it("selects all and clears", () => {
+ const { result } = renderHook(() => useFileSelection());
+ const files = [f("a"), f("b")];
+ act(() => result.current.selectAll(files));
+ expect(result.current.getSelectedCount()).toBe(2);
+ act(() => result.current.clearSelection());
+ expect(result.current.getSelectedCount()).toBe(0);
+ });
+
+ it("toggleSelection adds then removes", () => {
+ const { result } = renderHook(() => useFileSelection());
+ act(() => result.current.toggleSelection(f("a")));
+ expect(result.current.isSelected(f("a"))).toBe(true);
+ act(() => result.current.toggleSelection(f("a")));
+ expect(result.current.isSelected(f("a"))).toBe(false);
+ });
+});
diff --git a/src/ui/features/file-manager/transferMetricsFormat.ts b/src/ui/features/file-manager/transferMetricsFormat.ts
new file mode 100644
index 000000000..dbeca19af
--- /dev/null
+++ b/src/ui/features/file-manager/transferMetricsFormat.ts
@@ -0,0 +1,74 @@
+import type { TFunction } from "i18next";
+import {
+ formatDurationMs,
+ formatTransferMbPerSec,
+ type TransferTimings,
+} from "@/main-axios.ts";
+
+export function createFormatTransferMetrics(t: TFunction) {
+ return (timings?: TransferTimings): string => {
+ if (!timings) return "";
+ const parts: string[] = [];
+ if (timings.prepareDestMs !== undefined) {
+ parts.push(
+ t("transfer.metricsPrepare", {
+ duration: formatDurationMs(timings.prepareDestMs),
+ }),
+ );
+ }
+ if (timings.compressMs !== undefined) {
+ parts.push(
+ t("transfer.metricsCompress", {
+ duration: formatDurationMs(timings.compressMs),
+ }),
+ );
+ }
+ for (const hop of timings.hops ?? []) {
+ const hopKey =
+ hop.id === "source_read"
+ ? "transfer.metricsHopSourceRead"
+ : hop.id === "dest_local_write"
+ ? "transfer.metricsHopDestLocalWrite"
+ : "transfer.metricsHopDestSftpWrite";
+ parts.push(
+ t(hopKey, {
+ throughput: formatTransferMbPerSec(hop.mbPerSec),
+ }),
+ );
+ }
+ if (timings.transferMs !== undefined) {
+ parts.push(
+ t("transfer.metricsTransfer", {
+ duration: formatDurationMs(timings.transferMs),
+ throughput: formatTransferMbPerSec(
+ timings.endToEndMbPerSec,
+ timings.transferBytes,
+ timings.transferMs,
+ ),
+ }),
+ );
+ }
+ if (timings.extractMs !== undefined) {
+ parts.push(
+ t("transfer.metricsExtract", {
+ duration: formatDurationMs(timings.extractMs),
+ }),
+ );
+ }
+ if (timings.sourceDeleteMs !== undefined) {
+ parts.push(
+ t("transfer.metricsSourceDelete", {
+ duration: formatDurationMs(timings.sourceDeleteMs),
+ }),
+ );
+ }
+ if (timings.totalMs !== undefined) {
+ parts.push(
+ t("transfer.metricsTotal", {
+ duration: formatDurationMs(timings.totalMs),
+ }),
+ );
+ }
+ return parts.join(" · ");
+ };
+}
diff --git a/src/ui/features/file-manager/transferNotificationStore.ts b/src/ui/features/file-manager/transferNotificationStore.ts
new file mode 100644
index 000000000..5a463bb1f
--- /dev/null
+++ b/src/ui/features/file-manager/transferNotificationStore.ts
@@ -0,0 +1,52 @@
+const PENDING_KEY = "termix_pending_transfers";
+const NOTIFIED_KEY = "termix_notified_transfers";
+
+function readJsonArray(key: string): string[] {
+ try {
+ const raw = localStorage.getItem(key);
+ if (!raw) return [];
+ const parsed = JSON.parse(raw) as unknown;
+ return Array.isArray(parsed)
+ ? parsed.filter((id): id is string => typeof id === "string")
+ : [];
+ } catch {
+ return [];
+ }
+}
+
+function writeJsonArray(key: string, values: string[]): void {
+ localStorage.setItem(key, JSON.stringify(values));
+}
+
+export function registerPendingTransfer(transferId: string): void {
+ const pending = readJsonArray(PENDING_KEY);
+ if (!pending.includes(transferId)) {
+ writeJsonArray(PENDING_KEY, [...pending, transferId]);
+ }
+}
+
+export function markTransferNotified(transferId: string): void {
+ const notified = readJsonArray(NOTIFIED_KEY);
+ if (!notified.includes(transferId)) {
+ writeJsonArray(NOTIFIED_KEY, [...notified, transferId].slice(-200));
+ }
+ writeJsonArray(
+ PENDING_KEY,
+ readJsonArray(PENDING_KEY).filter((id) => id !== transferId),
+ );
+}
+
+export function isTransferNotified(transferId: string): boolean {
+ return readJsonArray(NOTIFIED_KEY).includes(transferId);
+}
+
+export function getPendingTransferIds(): string[] {
+ return readJsonArray(PENDING_KEY);
+}
+
+export function clearStalePendingTransfer(transferId: string): void {
+ writeJsonArray(
+ PENDING_KEY,
+ readJsonArray(PENDING_KEY).filter((id) => id !== transferId),
+ );
+}
diff --git a/src/ui/features/file-manager/transferProgressMonitor.tsx b/src/ui/features/file-manager/transferProgressMonitor.tsx
new file mode 100644
index 000000000..7f71ce56b
--- /dev/null
+++ b/src/ui/features/file-manager/transferProgressMonitor.tsx
@@ -0,0 +1,339 @@
+import { toast } from "sonner";
+import type { TFunction } from "i18next";
+import {
+ pollTransferUntilComplete,
+ cancelTransferToHost,
+ cleanupCancelledTransfer,
+ retryTransferToHost,
+ createTransferProgressTracker,
+ type TransferProgressResponse,
+ type TransferTimings,
+} from "@/main-axios.ts";
+import { TransferProgressToast } from "./components/TransferProgressToast.tsx";
+import {
+ markTransferNotified,
+ registerPendingTransfer,
+} from "./transferNotificationStore.ts";
+
+const monitoredTransferIds = new Set<string>();
+const TOAST_CLASS = "!pr-10 !pl-4 transfer-progress-toast";
+
+function formatFileSize(bytes?: number): string {
+ if (bytes === undefined || bytes === null) return "-";
+ if (bytes === 0) return "0 B";
+
+ const units = ["B", "KB", "MB", "GB", "TB"];
+ let size = bytes;
+ let unitIndex = 0;
+
+ while (size >= 1024 && unitIndex < units.length - 1) {
+ size /= 1024;
+ unitIndex++;
+ }
+
+ const formattedSize =
+ size < 10 && unitIndex > 0 ? size.toFixed(1) : Math.round(size).toString();
+ return `${formattedSize} ${units[unitIndex]}`;
+}
+
+function renderTransferProgressToast(
+ toastId: string | number,
+ status: TransferProgressResponse,
+ liveMbPerSec?: number,
+ onCancel?: () => void,
+ cancelling?: boolean,
+ stalled?: boolean,
+): void {
+ toast.loading(
+ <TransferProgressToast
+ status={status}
+ liveMbPerSec={liveMbPerSec}
+ stalled={stalled}
+ formatSize={formatFileSize}
+ onCancel={onCancel}
+ cancelling={cancelling}
+ />,
+ { id: toastId, duration: Infinity, className: TOAST_CLASS },
+ );
+}
+
+export function showTransferCompletionToast(
+ finalStatus: TransferProgressResponse,
+ t: TFunction,
+ toastId?: string | number,
+ formatTransferMetrics?: (timings?: TransferTimings) => string,
+): void {
+ showDefaultCompletionToast(
+ finalStatus,
+ toastId ?? `transfer-done-${finalStatus.transferId}`,
+ t,
+ formatTransferMetrics,
+ );
+ markTransferNotified(finalStatus.transferId);
+}
+
+export function isTransferBeingMonitored(transferId: string): boolean {
+ return monitoredTransferIds.has(transferId);
+}
+
+export interface TransferMonitorHandle {
+ toastId: string | number;
+ waitForCompletion: Promise<TransferProgressResponse>;
+}
+
+export interface BeginTransferMonitoringOptions {
+ resumed?: boolean;
+ initialStatus?: Partial<TransferProgressResponse>;
+ onComplete?: (
+ finalStatus: TransferProgressResponse,
+ toastId: string | number,
+ ) => void;
+ formatTransferMetrics?: (timings?: TransferTimings) => string;
+}
+
+function showCancelledTransferToast(
+ finalStatus: TransferProgressResponse,
+ toastId: string | number,
+ t: TFunction,
+): void {
+ const hasPartialDest =
+ (finalStatus.partialDestRemaining ??
+ (finalStatus.bytesTransferred ?? 0) > 0) ||
+ (finalStatus.itemsCompleted ?? 0) > 0;
+
+ let description: string | undefined;
+ if (finalStatus.moveRequested && hasPartialDest) {
+ description = t("transfer.transferCancelledMoveHint");
+ } else if (hasPartialDest) {
+ description = t("transfer.transferCancelledCopyHint");
+ }
+
+ const showCleanupAction = hasPartialDest && !finalStatus.cleanupCompleted;
+
+ toast.info(t("transfer.transferCancelled"), {
+ id: toastId,
+ description,
+ className: TOAST_CLASS,
+ duration: showCleanupAction ? Infinity : undefined,
+ action: showCleanupAction
+ ? {
+ label: t("transfer.cleanupDestFiles"),
+ onClick: () => {
+ void cleanupCancelledTransfer(finalStatus.transferId)
+ .then((result) => {
+ toast.dismiss(toastId);
+ if (result.failedPaths.length > 0) {
+ toast.warning(t("transfer.cleanupDestFilesPartial"));
+ } else if (result.removedPaths.length > 0) {
+ toast.success(t("transfer.cleanupDestFilesSuccess"));
+ } else {
+ toast.info(t("transfer.cleanupDestFilesNothing"));
+ }
+ })
+ .catch((error: unknown) => {
+ const message =
+ error instanceof Error
+ ? error.message
+ : t("fileManager.unknownError");
+ toast.error(
+ `${t("transfer.cleanupDestFilesError")}: ${message}`,
+ );
+ });
+ },
+ }
+ : undefined,
+ });
+}
+
+function showFailedTransferToast(
+ finalStatus: TransferProgressResponse,
+ toastId: string | number,
+ t: TFunction,
+ formatTransferMetrics?: (timings?: TransferTimings) => string,
+): void {
+ const hasPartial =
+ (finalStatus.partialDestRemaining ??
+ (finalStatus.bytesTransferred ?? 0) > 0) ||
+ (finalStatus.itemsCompleted ?? 0) > 0;
+
+ const descriptionParts: string[] = [];
+ if (finalStatus.message) {
+ descriptionParts.push(finalStatus.message);
+ }
+ if (finalStatus.retryable && hasPartial) {
+ descriptionParts.push(t("transfer.transferFailedRetryHint"));
+ }
+
+ const showRetry = finalStatus.retryable === true;
+
+ toast.error(t("transfer.transferError"), {
+ id: toastId,
+ description:
+ descriptionParts.length > 0 ? descriptionParts.join(" ") : undefined,
+ className: TOAST_CLASS,
+ duration: showRetry ? Infinity : undefined,
+ action: showRetry
+ ? {
+ label: t("transfer.retryTransfer"),
+ onClick: () => {
+ void retryTransferToHost(finalStatus.transferId)
+ .then(() => {
+ toast.dismiss(toastId);
+ beginTransferProgressMonitoring(finalStatus.transferId, t, {
+ resumed: true,
+ formatTransferMetrics,
+ });
+ })
+ .catch((error: unknown) => {
+ const message =
+ error instanceof Error
+ ? error.message
+ : t("fileManager.unknownError");
+ toast.error(`${t("transfer.retryTransferError")}: ${message}`);
+ });
+ },
+ }
+ : undefined,
+ });
+}
+
+function showDefaultCompletionToast(
+ finalStatus: TransferProgressResponse,
+ toastId: string | number,
+ t: TFunction,
+ formatTransferMetrics?: (timings?: TransferTimings) => string,
+): void {
+ if (finalStatus.status === "cancelled") {
+ showCancelledTransferToast(finalStatus, toastId, t);
+ return;
+ }
+
+ if (finalStatus.status === "error") {
+ showFailedTransferToast(finalStatus, toastId, t, formatTransferMetrics);
+ return;
+ }
+
+ if (finalStatus.status === "partial") {
+ const failed = finalStatus.failedPaths?.join(", ") || "";
+ const metrics = formatTransferMetrics?.(finalStatus.timings);
+ toast.warning(
+ t("transfer.transferPartialHint", {
+ paths: failed,
+ count: finalStatus.failedPaths?.length || 0,
+ }),
+ {
+ id: toastId,
+ description: metrics || undefined,
+ className: TOAST_CLASS,
+ },
+ );
+ return;
+ }
+
+ const metrics = formatTransferMetrics?.(finalStatus.timings);
+ toast.success(t("transfer.transferSuccess"), {
+ id: toastId,
+ description: metrics || undefined,
+ className: TOAST_CLASS,
+ });
+}
+
+export function beginTransferProgressMonitoring(
+ transferId: string,
+ t: TFunction,
+ options: BeginTransferMonitoringOptions = {},
+): TransferMonitorHandle | null {
+ if (monitoredTransferIds.has(transferId)) {
+ return null;
+ }
+ monitoredTransferIds.add(transferId);
+ registerPendingTransfer(transferId);
+
+ const progressTracker = createTransferProgressTracker();
+ let cancelling = false;
+
+ const initialStatus: TransferProgressResponse = {
+ transferId,
+ status: "running",
+ phase: "transferring",
+ ...options.initialStatus,
+ };
+
+ const progressToast = toast.loading(
+ <TransferProgressToast
+ status={initialStatus}
+ formatSize={formatFileSize}
+ />,
+ {
+ duration: Infinity,
+ description: options.resumed ? t("transfer.resumedHint") : undefined,
+ className: TOAST_CLASS,
+ },
+ );
+
+ const handleCancelTransfer = () => {
+ if (cancelling) return;
+ cancelling = true;
+ renderTransferProgressToast(
+ progressToast,
+ { ...initialStatus, transferId },
+ undefined,
+ handleCancelTransfer,
+ true,
+ );
+ void cancelTransferToHost(transferId);
+ };
+
+ const waitForCompletion = pollTransferUntilComplete(
+ transferId,
+ (status) => {
+ const { rate, stalled } = progressTracker.update(status);
+ renderTransferProgressToast(
+ progressToast,
+ status,
+ rate,
+ handleCancelTransfer,
+ cancelling,
+ stalled,
+ );
+ },
+ 250,
+ )
+ .then((finalStatus) => {
+ markTransferNotified(transferId);
+ if (options.onComplete) {
+ options.onComplete(finalStatus, progressToast);
+ } else {
+ showDefaultCompletionToast(
+ finalStatus,
+ progressToast,
+ t,
+ options.formatTransferMetrics,
+ );
+ }
+ return finalStatus;
+ })
+ .catch((error: unknown) => {
+ const message =
+ error instanceof Error ? error.message : t("fileManager.unknownError");
+ toast.error(`${t("transfer.transferError")}: ${message}`, {
+ id: progressToast,
+ className: TOAST_CLASS,
+ });
+ markTransferNotified(transferId);
+ throw error;
+ })
+ .finally(() => {
+ monitoredTransferIds.delete(transferId);
+ });
+
+ renderTransferProgressToast(
+ progressToast,
+ initialStatus,
+ undefined,
+ handleCancelTransfer,
+ cancelling,
+ );
+
+ return { toastId: progressToast, waitForCompletion };
+}
diff --git a/src/ui/features/guacamole/GuacamoleApp.tsx b/src/ui/features/guacamole/GuacamoleApp.tsx
index 9a8df2341..d33ced03b 100644
--- a/src/ui/features/guacamole/GuacamoleApp.tsx
+++ b/src/ui/features/guacamole/GuacamoleApp.tsx
@@ -124,7 +124,7 @@ const GuacamoleAppInner: React.FC<GuacamoleAppInnerProps> = ({
if (result) setToken(result.token);
})
.catch((err) => setError(err?.message || t("guacamole.failedToConnect")));
- }, [hostId, retryCount]);
+ }, [hostId, protocol, retryCount, t]);
const handleReconnect = useCallback(() => {
setConnectionError(null);
@@ -236,11 +236,7 @@ const GuacamoleAppInner: React.FC<GuacamoleAppInnerProps> = ({
isVisible={true}
onError={(err) => setConnectionError(err)}
/>
- <GuacamoleToolbar
- displayRef={displayRef}
- protocol={resolvedProtocol}
- onReconnect={handleReconnect}
- />
+ <GuacamoleToolbar displayRef={displayRef} protocol={resolvedProtocol} />
</div>
);
};
diff --git a/src/ui/features/guacamole/GuacamoleDisplay.tsx b/src/ui/features/guacamole/GuacamoleDisplay.tsx
index c8612cf5c..57ecdba22 100644
--- a/src/ui/features/guacamole/GuacamoleDisplay.tsx
+++ b/src/ui/features/guacamole/GuacamoleDisplay.tsx
@@ -437,6 +437,9 @@ export const GuacamoleDisplay = forwardRef<
onError,
refreshKeyboardHandlers,
rescaleDisplay,
+ connectionConfig.protocol,
+ connectionConfig.type,
+ t,
]);
const hasInitiatedRef = useRef(false);
@@ -520,7 +523,6 @@ export const GuacamoleDisplay = forwardRef<
const h = Math.round(rect.height);
if (w > 0 && h > 0) {
clientRef.current.sendSize(w, h);
- rescaleDisplay(true);
}
}
}, 150);
diff --git a/src/ui/features/guacamole/GuacamoleToolbar.tsx b/src/ui/features/guacamole/GuacamoleToolbar.tsx
index f81ed4a36..e28bae0f0 100644
--- a/src/ui/features/guacamole/GuacamoleToolbar.tsx
+++ b/src/ui/features/guacamole/GuacamoleToolbar.tsx
@@ -27,7 +27,6 @@ import { cn } from "@/lib/utils";
interface GuacamoleToolbarProps {
displayRef: React.RefObject<GuacamoleDisplayHandle>;
protocol: "rdp" | "vnc" | "telnet";
- onReconnect: () => void;
}
const MODIFIER_KEYSYMS = {
@@ -108,7 +107,6 @@ function TipIconBtn({
export const GuacamoleToolbar: React.FC<GuacamoleToolbarProps> = ({
displayRef,
protocol,
- onReconnect,
}) => {
const { t } = useTranslation();
const [position, setPosition] = useState({ x: 0, y: 12 });
diff --git a/src/ui/features/server-stats/ServerStats.tsx b/src/ui/features/server-stats/ServerStats.tsx
index df5a6adf2..55fa555fc 100644
--- a/src/ui/features/server-stats/ServerStats.tsx
+++ b/src/ui/features/server-stats/ServerStats.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React from "react";
import { Separator } from "@/components/separator.tsx";
import { Button } from "@/components/button.tsx";
diff --git a/src/ui/features/server-stats/widgets/NetworkWidget.tsx b/src/ui/features/server-stats/widgets/NetworkWidget.tsx
index e57e7bd5a..ff1b0ea44 100644
--- a/src/ui/features/server-stats/widgets/NetworkWidget.tsx
+++ b/src/ui/features/server-stats/widgets/NetworkWidget.tsx
@@ -1,4 +1,4 @@
-import { Network, WifiOff } from "lucide-react";
+import { Cable, Container, Network, Wifi, WifiOff } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { ServerMetrics } from "@/main-axios.ts";
import { SectionCard } from "@/components/section-card";
@@ -24,6 +24,16 @@ export function NetworkWidget({ metrics }: NetworkWidgetProps) {
};
const interfaces = metricsWithNetwork?.network?.interfaces ?? [];
+ const ifaceIcon = (name: string) => {
+ if (/^(wl|wlan|wifi|ath)/.test(name))
+ return <Wifi className="size-3 text-muted-foreground/50" />;
+ if (/^(eth|en|enp|eno|ens)/.test(name))
+ return <Cable className="size-3 text-muted-foreground/50" />;
+ if (/^(docker|br-|veth|virbr|vlan|bond|tun|tap|wg|lo)/.test(name))
+ return <Container className="size-3 text-muted-foreground/50" />;
+ return <Network className="size-3 text-muted-foreground/50" />;
+ };
+
return (
<SectionCard
title={t("serverStats.networkInterfaces")}
@@ -46,6 +56,7 @@ export function NetworkWidget({ metrics }: NetworkWidgetProps) {
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
+ {ifaceIcon(iface.name)}
<div
className={`size-1.5 rounded-full ${iface.state === "UP" ? "bg-accent-brand" : "bg-muted-foreground"}`}
/>
diff --git a/src/ui/features/terminal/Terminal.tsx b/src/ui/features/terminal/Terminal.tsx
index c0648f533..6cab70e15 100644
--- a/src/ui/features/terminal/Terminal.tsx
+++ b/src/ui/features/terminal/Terminal.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import {
useEffect,
useRef,
@@ -33,11 +34,10 @@ import { OPKSSHDialog } from "@/ssh/dialogs/OPKSSHDialog.tsx";
import { HostKeyVerificationDialog } from "@/ssh/dialogs/HostKeyVerificationDialog.tsx";
import { TmuxSessionPicker } from "@/ssh/dialogs/TmuxSessionPicker.tsx";
import {
- TERMINAL_THEMES,
DEFAULT_TERMINAL_CONFIG,
TERMINAL_FONTS,
} from "@/lib/terminal-themes.ts";
-import type { TerminalConfig } from "@/types";
+import "./terminal-global-styles.ts";
import { useTheme } from "@/components/theme-provider.tsx";
import { useCommandTracker } from "@/features/terminal/command-history/useCommandTracker.ts";
import { highlightTerminalOutput } from "@/lib/terminal-syntax-highlighter.ts";
@@ -52,72 +52,9 @@ import {
import { ConnectionLog } from "@/ssh/connection-log/ConnectionLog.tsx";
import { toast } from "sonner";
import { Button } from "@/components/button";
-
-// Background/foreground per UI theme for "Termix Default" — must match index.css
-const TERMIX_DEFAULT_COLORS: Record<
- string,
- { background: string; foreground: string }
-> = {
- dark: { background: "#0c0d0b", foreground: "#fafafa" },
- light: { background: "#ffffff", foreground: "#111210" },
- dracula: { background: "#282a36", foreground: "#f8f8f2" },
- catppuccin: { background: "#1e1e2e", foreground: "#cdd6f4" },
- nord: { background: "#2e3440", foreground: "#eceff4" },
- solarized: { background: "#002b36", foreground: "#839496" },
- "tokyo-night": { background: "#1a1b26", foreground: "#a9b1d6" },
- "one-dark": { background: "#282c34", foreground: "#abb2bf" },
- gruvbox: { background: "#282828", foreground: "#ebdbb2" },
-};
-
-function resolveTermixThemeColors(activeTheme: string, appTheme: string) {
- if (activeTheme !== "termix") {
- return (
- TERMINAL_THEMES[activeTheme]?.colors || TERMINAL_THEMES.termixDark.colors
- );
- }
- let resolvedUiTheme = appTheme;
- if (appTheme === "system") {
- resolvedUiTheme = window.matchMedia("(prefers-color-scheme: dark)").matches
- ? "dark"
- : "light";
- }
- const uiColors =
- TERMIX_DEFAULT_COLORS[resolvedUiTheme] ?? TERMIX_DEFAULT_COLORS.dark;
- const base = TERMINAL_THEMES.termixDark.colors;
- return {
- ...base,
- background: uiColors.background,
- foreground: uiColors.foreground,
- cursor: uiColors.foreground,
- cursorAccent: uiColors.background,
- };
-}
-
-interface HostConfig {
- id?: number;
- instanceId?: string;
- restoredSessionId?: string | null;
- ip: string;
- port: number;
- username: string;
- password?: string;
- key?: string;
- keyPassword?: string;
- keyType?: string;
- authType?: string;
- credentialId?: number;
- terminalConfig?: TerminalConfig;
- [key: string]: unknown;
-}
-
-interface TerminalHandle {
- disconnect: () => void;
- reconnect: () => void;
- fit: () => void;
- sendInput: (data: string) => void;
- notifyResize: () => void;
- refresh: () => void;
-}
+import { resolveTermixThemeColors } from "./terminal-theme.ts";
+import type { TerminalHandle, TerminalHostConfig } from "./terminal-types.ts";
+export type { TerminalHandle, TerminalHostConfig } from "./terminal-types.ts";
type HostKeyVerificationData = Omit<
React.ComponentProps<typeof HostKeyVerificationDialog>,
@@ -125,7 +62,7 @@ type HostKeyVerificationData = Omit<
>;
interface SSHTerminalProps {
- hostConfig: HostConfig;
+ hostConfig: TerminalHostConfig;
isVisible: boolean;
title?: string;
showTitle?: boolean;
@@ -203,8 +140,7 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
"no_keyboard" | "auth_failed" | "timeout"
>("no_keyboard");
const [showPassphraseDialog, setShowPassphraseDialog] = useState(false);
- const [keyboardInteractiveDetected, setKeyboardInteractiveDetected] =
- useState(false);
+ const [, setKeyboardInteractiveDetected] = useState(false);
const [warpgateAuthRequired, setWarpgateAuthRequired] = useState(false);
const [warpgateAuthUrl, setWarpgateAuthUrl] = useState<string>("");
const [warpgateSecurityKey, setWarpgateSecurityKey] = useState<string>("");
@@ -222,7 +158,7 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
const opksshFailedRef = useRef(false);
const currentHostIdRef = useRef<number | null>(null);
- const currentHostConfigRef = useRef<HostConfig | null>(null);
+ const currentHostConfigRef = useRef<TerminalHostConfig | null>(null);
const [hostKeyVerification, setHostKeyVerification] = useState<{
isOpen: boolean;
@@ -233,7 +169,9 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
const sessionIdRef = useRef<string | null>(null);
const isAttachingSessionRef = useRef<boolean>(false);
// Consumed on first connectToHost call so retries don't re-attempt a stale session
- const pendingRestoredSessionIdRef = useRef<string | null>(hostConfig.restoredSessionId ?? null);
+ const pendingRestoredSessionIdRef = useRef<string | null>(
+ hostConfig.restoredSessionId ?? null,
+ );
const [tmuxSessionPicker, setTmuxSessionPicker] = useState<{
sessions: Array<{
name: string;
@@ -1052,7 +990,7 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
terminal.write(outputData);
const sudoPasswordPattern =
- /(?:\[sudo\][^\n]*:\s*$|sudo:[^\n]*password[^\n]*required)/i;
+ /(?:\[sudo\][^\n]*:\s*$|sudo:[^\n]*password[^\n]*required|password for [^\n]*:\s*$|Password:\s*$)/i;
const hasSudoPw =
hostConfig.terminalConfig?.sudoPassword ||
hostConfig.password ||
@@ -1484,7 +1422,9 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
sessionIdRef.current = msg.sessionId;
if (hostConfig.instanceId) {
import("@/main-axios").then(({ patchOpenTab }) => {
- patchOpenTab(hostConfig.instanceId!, { backendSessionId: msg.sessionId }).catch(() => {});
+ patchOpenTab(hostConfig.instanceId!, {
+ backendSessionId: msg.sessionId,
+ }).catch(() => {});
});
}
} else if (msg.type === "sessionAttached") {
@@ -1520,7 +1460,9 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
wasSessionExpiredRef.current = true;
if (hostConfig.instanceId) {
import("@/main-axios").then(({ patchOpenTab }) => {
- patchOpenTab(hostConfig.instanceId!, { backendSessionId: null }).catch(() => {});
+ patchOpenTab(hostConfig.instanceId!, {
+ backendSessionId: null,
+ }).catch(() => {});
});
}
if (webSocketRef.current) {
@@ -1993,6 +1935,10 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
terminal.unicode.activeVersion = "11";
terminal.open(xtermRef.current);
+ document.fonts.ready.then(() => {
+ terminal.refresh(0, terminal.rows - 1);
+ fitAddon.fit();
+ });
terminal.attachCustomWheelEventHandler((ev) => {
const cfg = {
@@ -2135,8 +2081,6 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
isMountedRef.current = true;
const currentHostId = hostConfig.id;
- const currentInstanceId = hostConfig.instanceId;
-
return () => {
if (!isMountedRef.current) {
return;
@@ -2359,20 +2303,29 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
e.preventDefault();
e.stopPropagation();
- const autocompleteEnabled =
- localStorage.getItem("commandAutocomplete") === "true";
-
- if (!autocompleteEnabled) {
+ const sendTabToShell = () => {
if (webSocketRef.current?.readyState === 1) {
webSocketRef.current.send(
JSON.stringify({ type: "input", data: "\t" }),
);
}
+ };
+
+ const autocompleteEnabled =
+ localStorage.getItem("commandAutocomplete") === "true";
+
+ if (!autocompleteEnabled) {
+ sendTabToShell();
return false;
}
const currentCmd = getCurrentCommandRef.current().trim();
- if (currentCmd.length > 0 && webSocketRef.current?.readyState === 1) {
+ if (currentCmd.length === 0) {
+ sendTabToShell();
+ return false;
+ }
+
+ if (webSocketRef.current?.readyState === 1) {
const matches = autocompleteHistory.current
.filter(
(cmd) =>
@@ -2432,6 +2385,8 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
}
setShowAutocomplete(true);
+ } else {
+ sendTabToShell();
}
}
return false;
@@ -2474,7 +2429,6 @@ const TerminalInner = forwardRef<TerminalHandle, SSHTerminalProps>(
}
});
});
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [terminal, hostConfig.id, isVisible, isConnected, isConnecting]);
useEffect(() => {
@@ -2769,85 +2723,3 @@ export const Terminal = forwardRef<TerminalHandle, SSHTerminalProps>(
);
},
);
-
-const style = document.createElement("style");
-style.innerHTML = `
-@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap');
-@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;700&display=swap');
-@import url('https://fonts.googleapis.com/css2?family=Source+Code+Pro:ital,wght@0,400;0,700;1,400;1,700&display=swap');
-
-@font-face {
- font-family: 'Caskaydia Cove Nerd Font Mono';
- src: url('./fonts/CaskaydiaCoveNerdFontMono-Regular.ttf') format('truetype');
- font-weight: normal;
- font-style: normal;
- font-display: swap;
-}
-
-@font-face {
- font-family: 'Caskaydia Cove Nerd Font Mono';
- src: url('./fonts/CaskaydiaCoveNerdFontMono-Bold.ttf') format('truetype');
- font-weight: bold;
- font-style: normal;
- font-display: swap;
-}
-
-@font-face {
- font-family: 'Caskaydia Cove Nerd Font Mono';
- src: url('./fonts/CaskaydiaCoveNerdFontMono-Italic.ttf') format('truetype');
- font-weight: normal;
- font-style: italic;
- font-display: swap;
-}
-
-@font-face {
- font-family: 'Caskaydia Cove Nerd Font Mono';
- src: url('./fonts/CaskaydiaCoveNerdFontMono-BoldItalic.ttf') format('truetype');
- font-weight: bold;
- font-style: italic;
- font-display: swap;
-}
-
-.xterm .xterm-viewport::-webkit-scrollbar {
- width: 8px;
- background: transparent;
-}
-.xterm .xterm-viewport::-webkit-scrollbar-thumb {
- background: rgba(0,0,0,0.3);
- border-radius: 4px;
-}
-.xterm .xterm-viewport::-webkit-scrollbar-thumb:hover {
- background: rgba(0,0,0,0.5);
-}
-.xterm .xterm-viewport {
- scrollbar-width: thin;
- scrollbar-color: rgba(0,0,0,0.3) transparent;
-}
-
-.dark .xterm .xterm-viewport::-webkit-scrollbar-thumb {
- background: rgba(255,255,255,0.3);
-}
-.dark .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover {
- background: rgba(255,255,255,0.5);
-}
-.dark .xterm .xterm-viewport {
- scrollbar-color: rgba(255,255,255,0.3) transparent;
-}
-
-.xterm {
- font-feature-settings: "liga" 0, "calt" 0;
- text-rendering: optimizeLegibility;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
-}
-
-.xterm .xterm-screen {
- font-family: 'Caskaydia Cove Nerd Font Mono', 'SF Mono', Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace !important;
- font-variant-ligatures: none;
-}
-
-.xterm .xterm-screen .xterm-char {
- font-feature-settings: "liga" 0, "calt" 0;
-}
-`;
-document.head.appendChild(style);
diff --git a/src/ui/features/terminal/command-history/CommandHistoryContext.tsx b/src/ui/features/terminal/command-history/CommandHistoryContext.tsx
index 6adde7095..29593d070 100644
--- a/src/ui/features/terminal/command-history/CommandHistoryContext.tsx
+++ b/src/ui/features/terminal/command-history/CommandHistoryContext.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components */
import React, {
createContext,
useContext,
diff --git a/src/ui/features/terminal/terminal-global-styles.ts b/src/ui/features/terminal/terminal-global-styles.ts
new file mode 100644
index 000000000..e181bfa8d
--- /dev/null
+++ b/src/ui/features/terminal/terminal-global-styles.ts
@@ -0,0 +1,81 @@
+const style = document.createElement("style");
+style.innerHTML = `
+@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap');
+@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;700&display=swap');
+@import url('https://fonts.googleapis.com/css2?family=Source+Code+Pro:ital,wght@0,400;0,700;1,400;1,700&display=swap');
+
+@font-face {
+ font-family: 'Caskaydia Cove Nerd Font Mono';
+ src: url('./fonts/CaskaydiaCoveNerdFontMono-Regular.ttf') format('truetype');
+ font-weight: normal;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: 'Caskaydia Cove Nerd Font Mono';
+ src: url('./fonts/CaskaydiaCoveNerdFontMono-Bold.ttf') format('truetype');
+ font-weight: bold;
+ font-style: normal;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: 'Caskaydia Cove Nerd Font Mono';
+ src: url('./fonts/CaskaydiaCoveNerdFontMono-Italic.ttf') format('truetype');
+ font-weight: normal;
+ font-style: italic;
+ font-display: swap;
+}
+
+@font-face {
+ font-family: 'Caskaydia Cove Nerd Font Mono';
+ src: url('./fonts/CaskaydiaCoveNerdFontMono-BoldItalic.ttf') format('truetype');
+ font-weight: bold;
+ font-style: italic;
+ font-display: swap;
+}
+
+.xterm .xterm-viewport::-webkit-scrollbar {
+ width: 8px;
+ background: transparent;
+}
+.xterm .xterm-viewport::-webkit-scrollbar-thumb {
+ background: rgba(0,0,0,0.3);
+ border-radius: 4px;
+}
+.xterm .xterm-viewport::-webkit-scrollbar-thumb:hover {
+ background: rgba(0,0,0,0.5);
+}
+.xterm .xterm-viewport {
+ scrollbar-width: thin;
+ scrollbar-color: rgba(0,0,0,0.3) transparent;
+}
+
+.dark .xterm .xterm-viewport::-webkit-scrollbar-thumb {
+ background: rgba(255,255,255,0.3);
+}
+.dark .xterm .xterm-viewport::-webkit-scrollbar-thumb:hover {
+ background: rgba(255,255,255,0.5);
+}
+.dark .xterm .xterm-viewport {
+ scrollbar-color: rgba(255,255,255,0.3) transparent;
+}
+
+.xterm {
+ font-feature-settings: "liga" 0, "calt" 0;
+ text-rendering: optimizeLegibility;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+
+.xterm .xterm-screen {
+ font-family: 'Caskaydia Cove Nerd Font Mono', 'SF Mono', Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace !important;
+ font-variant-ligatures: none;
+}
+
+.xterm .xterm-screen .xterm-char {
+ font-feature-settings: "liga" 0, "calt" 0;
+}
+`;
+document.head.appendChild(style);
diff --git a/src/ui/features/terminal/terminal-theme.ts b/src/ui/features/terminal/terminal-theme.ts
new file mode 100644
index 000000000..a49420d8c
--- /dev/null
+++ b/src/ui/features/terminal/terminal-theme.ts
@@ -0,0 +1,44 @@
+import { TERMINAL_THEMES } from "@/lib/terminal-themes.ts";
+
+// Background/foreground per UI theme for "Termix Default" - must match index.css
+const TERMIX_DEFAULT_COLORS: Record<
+ string,
+ { background: string; foreground: string }
+> = {
+ dark: { background: "#0c0d0b", foreground: "#fafafa" },
+ light: { background: "#ffffff", foreground: "#111210" },
+ dracula: { background: "#282a36", foreground: "#f8f8f2" },
+ catppuccin: { background: "#1e1e2e", foreground: "#cdd6f4" },
+ nord: { background: "#2e3440", foreground: "#eceff4" },
+ solarized: { background: "#002b36", foreground: "#839496" },
+ "tokyo-night": { background: "#1a1b26", foreground: "#a9b1d6" },
+ "one-dark": { background: "#282c34", foreground: "#abb2bf" },
+ gruvbox: { background: "#282828", foreground: "#ebdbb2" },
+};
+
+export function resolveTermixThemeColors(
+ activeTheme: string,
+ appTheme: string,
+) {
+ if (activeTheme !== "termix") {
+ return (
+ TERMINAL_THEMES[activeTheme]?.colors || TERMINAL_THEMES.termixDark.colors
+ );
+ }
+ let resolvedUiTheme = appTheme;
+ if (appTheme === "system") {
+ resolvedUiTheme = window.matchMedia("(prefers-color-scheme: dark)").matches
+ ? "dark"
+ : "light";
+ }
+ const uiColors =
+ TERMIX_DEFAULT_COLORS[resolvedUiTheme] ?? TERMIX_DEFAULT_COLORS.dark;
+ const base = TERMINAL_THEMES.termixDark.colors;
+ return {
+ ...base,
+ background: uiColors.background,
+ foreground: uiColors.foreground,
+ cursor: uiColors.foreground,
+ cursorAccent: uiColors.background,
+ };
+}
diff --git a/src/ui/features/terminal/terminal-types.ts b/src/ui/features/terminal/terminal-types.ts
new file mode 100644
index 000000000..68f0d6815
--- /dev/null
+++ b/src/ui/features/terminal/terminal-types.ts
@@ -0,0 +1,27 @@
+import type { TerminalConfig } from "@/types";
+
+export interface TerminalHostConfig {
+ id?: number;
+ instanceId?: string;
+ restoredSessionId?: string | null;
+ ip: string;
+ port: number;
+ username: string;
+ password?: string;
+ key?: string;
+ keyPassword?: string;
+ keyType?: string;
+ authType?: string;
+ credentialId?: number;
+ terminalConfig?: TerminalConfig;
+ [key: string]: unknown;
+}
+
+export interface TerminalHandle {
+ disconnect: () => void;
+ reconnect: () => void;
+ fit: () => void;
+ sendInput: (data: string) => void;
+ notifyResize: () => void;
+ refresh: () => void;
+}
diff --git a/src/ui/features/tunnel/TunnelTab.tsx b/src/ui/features/tunnel/TunnelTab.tsx
index d2e3a1a23..97cfa8e93 100644
--- a/src/ui/features/tunnel/TunnelTab.tsx
+++ b/src/ui/features/tunnel/TunnelTab.tsx
@@ -48,14 +48,12 @@ function statusLabel(status: TunnelStatus | undefined): string {
function TunnelCard({
host,
- index,
tunnel,
status,
isActing,
onAction,
}: {
host: SSHHost;
- index: number;
tunnel: TunnelConnection;
status: TunnelStatus | undefined;
isActing: boolean;
@@ -261,7 +259,7 @@ export function TunnelTab({ host }: { label: string; host?: DemoHost }) {
} catch {
/* ignore */
}
- }, [host?.id]);
+ }, [host]);
useEffect(() => {
fetchHost();
@@ -284,7 +282,7 @@ export function TunnelTab({ host }: { label: string; host?: DemoHost }) {
logActivity("tunnel", sshHost.id, name).catch(() => {
activityLoggedRef.current = false;
});
- }, [sshHost?.id]);
+ }, [sshHost]);
const handleAction = async (
action: "connect" | "disconnect" | "cancel",
@@ -298,24 +296,31 @@ export function TunnelTab({ host }: { label: string; host?: DemoHost }) {
setTunnelActions((prev) => ({ ...prev, [name]: true }));
try {
if (action === "connect") {
- const allHosts = await getSSHHosts();
- const endpointSsh = allHosts.find(
- (h) =>
- h.name === tunnel.endpointHost ||
- `${h.username}@${h.ip}` === tunnel.endpointHost,
- );
+ const isDirect =
+ !tunnel.endpointHost ||
+ tunnel.endpointHost === "127.0.0.1" ||
+ tunnel.endpointHost === "localhost";
+ let endpointSsh: SSHHost | undefined;
+ if (!isDirect) {
+ const allHosts = await getSSHHosts();
+ endpointSsh = allHosts.find(
+ (h) =>
+ h.name === tunnel.endpointHost ||
+ `${h.username}@${h.ip}` === tunnel.endpointHost,
+ );
+ }
await connectTunnel({
name,
scope: tunnel.scope ?? "s2s",
mode:
tunnel.mode ??
(tunnel.tunnelType as "local" | "remote" | "dynamic") ??
- "remote",
+ "local",
tunnelType:
tunnel.tunnelType ??
(tunnel.mode === "local" || tunnel.mode === "remote"
? tunnel.mode
- : "remote"),
+ : "local"),
bindHost: tunnel.bindHost,
targetHost: tunnel.targetHost,
sourceHostId: sshHost.id,
@@ -334,9 +339,13 @@ export function TunnelTab({ host }: { label: string; host?: DemoHost }) {
sshHost.authType === "key" ? sshHost.keyType : undefined,
sourceCredentialId: sshHost.credentialId,
endpointHost: tunnel.endpointHost ?? "",
- endpointIP: endpointSsh?.ip ?? tunnel.endpointHost ?? "",
- endpointSSHPort: endpointSsh?.port ?? 22,
- endpointUsername: endpointSsh?.username ?? "",
+ endpointIP: isDirect
+ ? sshHost.ip
+ : (endpointSsh?.ip ?? tunnel.endpointHost ?? ""),
+ endpointSSHPort: isDirect ? sshHost.port : (endpointSsh?.port ?? 22),
+ endpointUsername: isDirect
+ ? sshHost.username
+ : (endpointSsh?.username ?? ""),
endpointPassword:
endpointSsh?.authType === "password"
? endpointSsh.password
@@ -428,7 +437,6 @@ export function TunnelTab({ host }: { label: string; host?: DemoHost }) {
<TunnelCard
key={name}
host={sshHost}
- index={index}
tunnel={tunnel}
status={tunnelStatuses[name]}
isActing={tunnelActions[name] ?? false}
diff --git a/src/ui/features/tunnel/tunnel-form-utils.test.ts b/src/ui/features/tunnel/tunnel-form-utils.test.ts
new file mode 100644
index 000000000..bef0a265f
--- /dev/null
+++ b/src/ui/features/tunnel/tunnel-form-utils.test.ts
@@ -0,0 +1,62 @@
+import { describe, it, expect } from "vitest";
+import {
+ getTunnelTypeForMode,
+ getTunnelPortLabels,
+ getTunnelModeDescription,
+} from "./tunnel-form-utils.js";
+
+// A fake translate that echoes the key plus any interpolation args so we can
+// assert which translation key + payload the helpers chose.
+const t = (key: string, opts?: Record<string, string | number>) =>
+ opts ? `${key}:${JSON.stringify(opts)}` : key;
+
+describe("getTunnelTypeForMode", () => {
+ it("maps remote to remote and everything else to local", () => {
+ expect(getTunnelTypeForMode("remote")).toBe("remote");
+ expect(getTunnelTypeForMode("local")).toBe("local");
+ expect(getTunnelTypeForMode("dynamic")).toBe("local");
+ });
+});
+
+describe("getTunnelPortLabels", () => {
+ it("labels client local mode source/endpoint ports", () => {
+ const labels = getTunnelPortLabels("client", "local", t);
+ expect(labels.sourcePortLabel).toBe("tunnels.localPort");
+ expect(labels.endpointPortLabel).toBe("tunnels.remotePort");
+ });
+
+ it("swaps labels for client remote mode", () => {
+ const labels = getTunnelPortLabels("client", "remote", t);
+ expect(labels.sourcePortLabel).toBe("tunnels.remotePort");
+ expect(labels.endpointPortLabel).toBe("tunnels.localPort");
+ });
+
+ it("uses host/endpoint labels in server scope", () => {
+ const labels = getTunnelPortLabels("server", "local", t);
+ expect(labels.sourcePortLabel).toBe("tunnels.currentHostPort");
+ expect(labels.endpointPortLabel).toBe("tunnels.endpointPort");
+ });
+});
+
+describe("getTunnelModeDescription", () => {
+ const ports = { sourcePort: 8080, endpointPort: 9090 };
+
+ it("selects the client dynamic description with only the source port", () => {
+ const desc = getTunnelModeDescription("client", "dynamic", ports, t);
+ expect(desc).toContain("tunnels.forwardDescriptionClientDynamic");
+ expect(desc).toContain("8080");
+ expect(desc).not.toContain("9090");
+ });
+
+ it("selects the client local description with both ports", () => {
+ const desc = getTunnelModeDescription("client", "local", ports, t);
+ expect(desc).toContain("tunnels.forwardDescriptionClientLocal");
+ expect(desc).toContain("8080");
+ expect(desc).toContain("9090");
+ });
+
+ it("selects the server remote description", () => {
+ const desc = getTunnelModeDescription("server", "remote", ports, t);
+ expect(desc).toContain("tunnels.forwardDescriptionServerRemote");
+ });
+});
diff --git a/src/ui/hooks/use-mobile.test.ts b/src/ui/hooks/use-mobile.test.ts
new file mode 100644
index 000000000..90c4dc8b4
--- /dev/null
+++ b/src/ui/hooks/use-mobile.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect, vi, afterEach } from "vitest";
+import { renderHook } from "@testing-library/react";
+import { useIsMobile } from "./use-mobile.js";
+
+function setViewport(width: number) {
+ Object.defineProperty(window, "innerWidth", {
+ configurable: true,
+ writable: true,
+ value: width,
+ });
+ window.matchMedia = vi.fn().mockImplementation((query: string) => ({
+ matches: width < 768,
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }));
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("useIsMobile", () => {
+ it("is true below the 768px breakpoint", () => {
+ setViewport(500);
+ const { result } = renderHook(() => useIsMobile());
+ expect(result.current).toBe(true);
+ });
+
+ it("is false at or above the breakpoint", () => {
+ setViewport(1024);
+ const { result } = renderHook(() => useIsMobile());
+ expect(result.current).toBe(false);
+ });
+
+ it("treats exactly 768 as not mobile", () => {
+ setViewport(768);
+ const { result } = renderHook(() => useIsMobile());
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/src/ui/lib/ServerStatusContext.tsx b/src/ui/lib/ServerStatusContext.tsx
index 6131730dd..3c14ba38d 100644
--- a/src/ui/lib/ServerStatusContext.tsx
+++ b/src/ui/lib/ServerStatusContext.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components */
import React, {
createContext,
useContext,
@@ -132,10 +133,7 @@ export function ServerStatusProvider({
}
}, [isAuthenticated]);
- const stableEnabledHostIds = useMemo(
- () => enabledHostIds,
- [[...enabledHostIds].sort().join(",")],
- );
+ const stableEnabledHostIds = useMemo(() => enabledHostIds, [enabledHostIds]);
const getStatus = useCallback(
(hostId: number): StatusValue => {
diff --git a/src/ui/lib/base-path.test.ts b/src/ui/lib/base-path.test.ts
new file mode 100644
index 000000000..b88ac8468
--- /dev/null
+++ b/src/ui/lib/base-path.test.ts
@@ -0,0 +1,25 @@
+import { describe, it, expect, afterEach } from "vitest";
+import { getBasePath } from "./base-path.js";
+
+const win = window as unknown as Record<string, unknown>;
+
+afterEach(() => {
+ delete win.__TERMIX_BASE_PATH__;
+});
+
+describe("getBasePath", () => {
+ it("returns empty string when no runtime override is set (default base)", () => {
+ // Vite test env BASE_URL is "/" which the helper normalizes to "".
+ expect(getBasePath()).toBe("");
+ });
+
+ it("uses the runtime override when present", () => {
+ win.__TERMIX_BASE_PATH__ = "/termix";
+ expect(getBasePath()).toBe("/termix");
+ });
+
+ it("strips a trailing slash from the runtime override", () => {
+ win.__TERMIX_BASE_PATH__ = "/termix/";
+ expect(getBasePath()).toBe("/termix");
+ });
+});
diff --git a/src/ui/lib/electron.test.ts b/src/ui/lib/electron.test.ts
new file mode 100644
index 000000000..6f90db60d
--- /dev/null
+++ b/src/ui/lib/electron.test.ts
@@ -0,0 +1,30 @@
+import { describe, it, expect, afterEach } from "vitest";
+import { isElectron } from "./electron.js";
+
+const win = window as unknown as Record<string, unknown>;
+
+afterEach(() => {
+ delete win.IS_ELECTRON;
+ delete win.electronAPI;
+});
+
+describe("isElectron", () => {
+ it("returns false in a plain browser window", () => {
+ expect(isElectron()).toBe(false);
+ });
+
+ it("returns true when IS_ELECTRON flag is set", () => {
+ win.IS_ELECTRON = true;
+ expect(isElectron()).toBe(true);
+ });
+
+ it("returns true when electronAPI is present", () => {
+ win.electronAPI = {};
+ expect(isElectron()).toBe(true);
+ });
+
+ it("returns true when electronAPI.isElectron is true", () => {
+ win.electronAPI = { isElectron: true };
+ expect(isElectron()).toBe(true);
+ });
+});
diff --git a/src/ui/lib/frontend-logger.test.ts b/src/ui/lib/frontend-logger.test.ts
new file mode 100644
index 000000000..8b06bb887
--- /dev/null
+++ b/src/ui/lib/frontend-logger.test.ts
@@ -0,0 +1,68 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { apiLogger } from "./frontend-logger.js";
+
+// The formatting helpers (status/performance icons, URL sanitization) are
+// private, so we exercise them through the public request* methods and assert
+// on what gets written to the console.
+let logSpy: ReturnType<typeof vi.spyOn>;
+let errorSpy: ReturnType<typeof vi.spyOn>;
+let groupSpy: ReturnType<typeof vi.spyOn>;
+
+beforeEach(() => {
+ logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+ errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ groupSpy = vi.spyOn(console, "group").mockImplementation(() => {});
+ vi.spyOn(console, "groupEnd").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+function allLoggedText(): string {
+ return logSpy.mock.calls
+ .concat(errorSpy.mock.calls)
+ .concat(groupSpy.mock.calls)
+ .map((args) => args.join(" "))
+ .join("\n");
+}
+
+describe("frontend logger request success", () => {
+ it("includes the success status icon and a fast-performance icon", () => {
+ apiLogger.requestSuccess("get", "https://x.test/api", 200, 50);
+ const text = allLoggedText();
+ expect(text).toContain("✅"); // 2xx status icon
+ expect(text).toContain("⚡"); // <100ms performance icon
+ expect(text).toContain("200");
+ });
+
+ it("uses the slow-performance icon for long requests", () => {
+ apiLogger.requestSuccess("get", "https://x.test/api", 200, 4000);
+ expect(allLoggedText()).toContain("🐌");
+ });
+});
+
+describe("frontend logger error mapping", () => {
+ it("uses a client-error icon for 4xx responses", () => {
+ apiLogger.requestError("get", "https://x.test/api", 404, "Not Found", 30);
+ expect(allLoggedText()).toContain("⚠️");
+ });
+
+ it("uses a server-error icon for 5xx responses", () => {
+ apiLogger.requestError("get", "https://x.test/api", 500, "Boom", 30);
+ expect(allLoggedText()).toContain("❌");
+ });
+});
+
+describe("frontend logger URL sanitization", () => {
+ it("strips password/token query params from logged URLs", () => {
+ apiLogger.requestStart("get", "https://x.test/login?password=hunter2");
+ const text = allLoggedText();
+ expect(text).not.toContain("hunter2");
+ });
+
+ it("keeps a normal URL intact", () => {
+ apiLogger.requestStart("get", "https://x.test/api/hosts");
+ expect(allLoggedText()).toContain("x.test/api/hosts");
+ });
+});
diff --git a/src/ui/lib/terminal-syntax-highlighter.test.ts b/src/ui/lib/terminal-syntax-highlighter.test.ts
new file mode 100644
index 000000000..3c8b25f67
--- /dev/null
+++ b/src/ui/lib/terminal-syntax-highlighter.test.ts
@@ -0,0 +1,46 @@
+import { describe, it, expect } from "vitest";
+import { highlightTerminalOutput } from "./terminal-syntax-highlighter.js";
+
+const ESC = "\x1b";
+
+describe("highlightTerminalOutput", () => {
+ it("returns empty/whitespace text unchanged", () => {
+ expect(highlightTerminalOutput("")).toBe("");
+ expect(highlightTerminalOutput(" ")).toBe(" ");
+ });
+
+ it("wraps error keywords in red ANSI codes", () => {
+ const out = highlightTerminalOutput("Something ERROR happened");
+ expect(out).toContain(ESC + "[91m");
+ expect(out).toContain(ESC + "[0m");
+ expect(out).toContain("ERROR");
+ });
+
+ it("highlights IPv4 addresses", () => {
+ const out = highlightTerminalOutput("connect to 192.168.1.10 now");
+ expect(out).toContain("192.168.1.10");
+ expect(out).toContain(ESC + "[35m"); // magenta
+ });
+
+ it("leaves text with no matchable tokens unchanged", () => {
+ const plain = "just a normal sentence here";
+ expect(highlightTerminalOutput(plain)).toBe(plain);
+ });
+
+ it("does not re-highlight text that already contains many ANSI codes", () => {
+ let heavy = "";
+ for (let i = 0; i < 12; i++) heavy += `${ESC}[32mgreen${ESC}[0m `;
+ expect(highlightTerminalOutput(heavy)).toBe(heavy);
+ });
+
+ it("leaves text ending in an incomplete ANSI escape untouched", () => {
+ const partial = `loading${ESC}[`;
+ expect(highlightTerminalOutput(partial)).toBe(partial);
+ });
+
+ it("does not exceed MAX_LINE_LENGTH processing on huge lines", () => {
+ const huge = "ERROR " + "x".repeat(6000);
+ // Over the 5000 char cap, highlightPlainText returns the input unchanged.
+ expect(highlightTerminalOutput(huge)).toBe(huge);
+ });
+});
diff --git a/src/ui/lib/theme.ts b/src/ui/lib/theme.ts
index 70edf91d8..05cfffe60 100644
--- a/src/ui/lib/theme.ts
+++ b/src/ui/lib/theme.ts
@@ -1,9 +1,8 @@
import type {
- AccentColorId,
DashboardCardConfig,
FontSizeId,
SplitMode,
-} from "./types";
+} from "@/types/ui-types";
export const DASHBOARD_CARDS: DashboardCardConfig[] = [
{
@@ -59,12 +58,6 @@ export const ACCENT_PRESET_COLORS = [
{ label: "Lime", value: "#84cc16" },
];
-export const ACCENT_COLORS = ACCENT_PRESET_COLORS.map((c) => ({
- id: c.label.toLowerCase() as AccentColorId,
- label: c.label,
- value: c.value,
-}));
-
export function applyAccentColor(colorValue: string) {
document.documentElement.style.setProperty("--accent-brand", colorValue);
}
@@ -114,13 +107,3 @@ export const PANE_COUNTS: Record<SplitMode, number> = {
"5-way": 5,
"6-way": 6,
};
-
-export const PANE_LAYOUTS: Record<SplitMode, string> = {
- none: "",
- "2-way": "grid-cols-2 grid-rows-1",
- "3-way": "grid-cols-2 grid-rows-2",
- "3-way-horizontal": "grid-cols-2 grid-rows-2",
- "4-way": "grid-cols-2 grid-rows-2",
- "5-way": "grid-cols-3 grid-rows-2",
- "6-way": "grid-cols-3 grid-rows-2",
-};
diff --git a/src/ui/lib/utils.test.ts b/src/ui/lib/utils.test.ts
new file mode 100644
index 000000000..ecbe22c6a
--- /dev/null
+++ b/src/ui/lib/utils.test.ts
@@ -0,0 +1,21 @@
+import { describe, it, expect } from "vitest";
+import { cn } from "./utils.js";
+
+describe("cn", () => {
+ it("joins class names", () => {
+ expect(cn("a", "b")).toBe("a b");
+ });
+
+ it("drops falsy values", () => {
+ expect(cn("a", false, null, undefined, "b")).toBe("a b");
+ });
+
+ it("merges conflicting tailwind classes, keeping the last", () => {
+ expect(cn("p-2", "p-4")).toBe("p-4");
+ expect(cn("text-red-500", "text-blue-500")).toBe("text-blue-500");
+ });
+
+ it("supports conditional object syntax", () => {
+ expect(cn("base", { active: true, hidden: false })).toBe("base active");
+ });
+});
diff --git a/src/ui/locales/en.json b/src/ui/locales/en.json
index b85306a2b..d5a613fd0 100644
--- a/src/ui/locales/en.json
+++ b/src/ui/locales/en.json
@@ -38,6 +38,8 @@
"helpText": "Enter the URL where your Termix server is running (e.g., http://localhost:30001 or https://your-server.com)",
"changeServer": "Change Server",
"mustIncludeProtocol": "Server URL must start with http:// or https://",
+ "allowInvalidCertificate": "Allow invalid certificate",
+ "allowInvalidCertificateDesc": "Use only for trusted self-hosted servers with self-signed or IP-address certificates.",
"useEmbedded": "Use Local Server",
"embeddedDesc": "Run Termix with the built-in local server (no remote server needed)",
"embeddedConnecting": "Connecting to local server...",
@@ -356,6 +358,7 @@
"tunnelModeLocalDesc": "Forward a local port to a port on the remote server (or a host reachable from it).",
"tunnelModeRemoteDesc": "Forward a port on the remote server back to a local port on your machine.",
"tunnelModeDynamicDesc": "Create a SOCKS5 proxy on a local port for dynamic port forwarding.",
+ "sameHost": "This host (direct tunnel)",
"endpointHost": "Endpoint Host",
"endpointPort": "Endpoint Port",
"bindHost": "Bind Host",
@@ -465,6 +468,8 @@
"vncUrlCopied": "VNC URL copied",
"telnetUrlCopied": "Telnet URL copied",
"remoteDesktopUrlCopied": "Remote Desktop URL copied",
+ "expandActions": "Expand actions",
+ "collapseActions": "Collapse actions",
"wakeOnLanAction": "Wake on LAN",
"wakeOnLanSuccess": "Magic packet sent to {{name}}",
"wakeOnLanError": "Failed to send magic packet",
@@ -542,6 +547,7 @@
"checkingHostStatuses": "Checking host statuses...",
"pinnedSection": "Pinned",
"hostsExported": "Hosts exported successfully",
+ "exportFailed": "Failed to export hosts",
"sampleDownloaded": "Sample file downloaded",
"failedToDeleteCredential2": "Failed to delete credential",
"noFolderOption": "(No folder)",
@@ -1143,6 +1149,107 @@
"loadingPdf": "Loading PDF...",
"loadingPage": "Loading page..."
},
+ "transfer": {
+ "copyToHost": "Copy to host…",
+ "moveToHost": "Move to host…",
+ "copyItemsToHost": "Copy {{count}} items to host…",
+ "moveItemsToHost": "Move {{count}} items to host…",
+ "noHostsConnected": "No other file-manager hosts available.",
+ "noHostsConnectedHint": "Add another SSH host with File Manager enabled in Host Manager.",
+ "selectDestinationHost": "Select destination host",
+ "destinationPath": "Destination path",
+ "recentDestinations": "Recent destinations",
+ "collapseRecentDestinations": "Collapse recent destinations",
+ "expandRecentDestinations": "Expand recent destinations",
+ "browseFolders": "Browse destination folders",
+ "browseDestination": "Browse or enter path",
+ "confirmCopy": "Copy",
+ "confirmMove": "Move",
+ "transferring": "Transferring…",
+ "compressing": "Compressing…",
+ "extracting": "Extracting…",
+ "transferringItems": "Transferring {{current}} of {{total}} items…",
+ "transferSuccess": "Transfer complete",
+ "transferError": "Transfer failed",
+ "transferPartial": "Transfer completed with {{count}} errors",
+ "transferPartialHint": "Could not transfer: {{paths}}",
+ "itemsSummary": "{{count}} items",
+ "destMustBeDirectory": "Destination must be a directory for multi-item transfers",
+ "selectThisFolder": "Select this folder",
+ "browsePathWillBeCreated": "This folder does not exist yet. It will be created when the transfer starts.",
+ "browsePathError": "Could not open this path on the destination host.",
+ "goUp": "Go up",
+ "copyFolderToHost": "Copy folder to host…",
+ "moveFolderToHost": "Move folder to host…",
+ "hostReady": "Ready",
+ "hostConnecting": "Connecting…",
+ "hostDisconnected": "Not connected",
+ "hostAuthRequired": "Authentication required — open File Manager on this host first",
+ "hostConnectionFailed": "Connection failed",
+ "metricsTitle": "Transfer timings",
+ "metricsPrepare": "Prepare destination: {{duration}}",
+ "metricsCompress": "Compress on source: {{duration}}",
+ "metricsHopSourceRead": "Source → server: {{throughput}}",
+ "metricsHopDestSftpWrite": "Server → dest (SFTP): {{throughput}}",
+ "metricsHopDestLocalWrite": "Server → dest (local): {{throughput}}",
+ "metricsTransfer": "End-to-end: {{throughput}} ({{duration}})",
+ "metricsExtract": "Extract on destination: {{duration}}",
+ "metricsSourceDelete": "Remove from source: {{duration}}",
+ "metricsTotal": "Total: {{duration}}",
+ "progressCompressing": "Compressing on source host…",
+ "progressExtracting": "Extracting on destination…",
+ "progressTransferring": "Transferring data…",
+ "progressReconnecting": "Reconnecting…",
+ "parallelSegmentsLabel": "Parallel transfer lanes",
+ "parallelSegmentsOption": "{{count}} lanes",
+ "parallelSegmentsHint": "Large files are split into 256 MB chunks. Multiple lanes use separate connections (like starting several transfers) for higher total throughput.",
+ "progressTotalSpeed": "{{speed}} total ({{lanes}} lanes)",
+ "progressTransferringItems": "Transferring files ({{current}} of {{total}})…",
+ "progressBytes": "{{transferred}} / {{total}}",
+ "progressItems": "{{current}} / {{total}} files",
+ "sourceNotDeletedPartial": "Source files kept (partial transfer)",
+ "jumpHostLimitation": "Both hosts must be reachable from the Termix server. Direct host-to-host routing is not supported.",
+ "cancel": "Cancel",
+ "methodLabel": "Transfer method",
+ "methodAuto": "Auto",
+ "methodTar": "Tar archive",
+ "methodItemSftp": "Per-file SFTP",
+ "methodAutoHint": "Picks tar or per-file SFTP based on file count, size, and compressibility. Single files always use streaming SFTP.",
+ "methodTarHint": "Compress on source, transfer one archive, extract on destination. Requires tar on both Unix hosts.",
+ "methodItemSftpHint": "Transfer each file individually over SFTP. Works on all hosts including Windows.",
+ "methodPreviewLoading": "Calculating transfer method…",
+ "methodPreviewError": "Could not preview transfer method. The server will still pick a method when you start.",
+ "methodPreviewWillUseTar": "Will use: Tar archive",
+ "methodPreviewWillUseItemSftp": "Will use: Per-file SFTP",
+ "methodPreviewScanSummary": "{{fileCount}} files, {{totalSize}} total (scanned on source host).",
+ "methodItemSftpLimitation": "Each file uses the same SFTP stream as a single-file copy, one after another. Progress is combined across all files, so the bar moves slowly during large files.",
+ "methodReason": {
+ "user_item_sftp": "You chose per-file SFTP.",
+ "user_tar": "You chose tar archive.",
+ "tar_unavailable": "Tar is not available on one or both hosts — per-file SFTP will be used instead.",
+ "windows_host": "A Windows host is involved — tar is not used.",
+ "auto_multi_large": "Auto: multiple files including a large file ({{largestSize}}) with compressible data — tar bundles into one transfer.",
+ "auto_single_large_in_archive": "Auto: one large file ({{largestSize}}) in this set — per-file SFTP.",
+ "auto_many_incompressible": "Auto: mostly incompressible data — per-file SFTP.",
+ "auto_many_files": "Auto: many files ({{fileCount}}) — tar reduces per-file overhead.",
+ "auto_default": "Auto: per-file SFTP for this set."
+ },
+ "progressCancel": "Cancel",
+ "progressCancelling": "Cancelling…",
+ "progressStalled": "Stalled",
+ "resumedHint": "Reconnected to an active transfer started in another window.",
+ "transferCancelled": "Transfer cancelled",
+ "transferCancelledCopyHint": "Partial files may remain on the destination.",
+ "transferCancelledMoveHint": "Partial files may remain on the destination. Source files were not removed.",
+ "cleanupDestFiles": "Clean up destination",
+ "cleanupDestFilesSuccess": "Removed partial files from the destination",
+ "cleanupDestFilesPartial": "Some partial files could not be removed",
+ "cleanupDestFilesNothing": "Nothing to clean up on the destination",
+ "cleanupDestFilesError": "Cleanup failed",
+ "retryTransfer": "Retry",
+ "retryTransferError": "Retry failed",
+ "transferFailedRetryHint": "Partial data was kept on the destination. Retry will resume when the connection is back."
+ },
"tunnels": {
"noSshTunnels": "No SSH Tunnels",
"createFirstTunnelMessage": "You haven't created any SSH tunnels yet. Configure tunnel connections in the Host Manager to get started.",
@@ -1768,6 +1875,9 @@
"linkAccountTargetUsername": "Target Username",
"linkAccountTargetPlaceholder": "Enter the local account username to link to",
"linkAccounts": "Link Accounts",
+ "linkAccountSuccess": "OIDC account linked to \"{{username}}\"",
+ "linkAccountFailed": "Failed to link OIDC account",
+ "linkAccountInProgress": "Linking...",
"saving": "Saving...",
"updateRegistrationFailed": "Failed to update registration setting",
"updatePasswordLoginFailed": "Failed to update password login setting",
@@ -1980,7 +2090,7 @@
"showHostTags": "Show Host Tags",
"showHostTagsDesc": "Display tags in host list",
"hostTrayOnClick": "Click to Expand Host Actions",
- "hostTrayOnClickDesc": "Require a click to expand host actions instead of hover",
+ "hostTrayOnClickDesc": "Always show connection buttons; click to expand management options instead of hover",
"pinAppRail": "Pin App Rail",
"pinAppRailDesc": "Keep the left sidebar app rail always expanded instead of expanding on hover",
"settingsSnippets": "Snippets",
diff --git a/src/ui/locales/translated/zh_CN.json b/src/ui/locales/translated/zh_CN.json
index 8d7475eee..2e6b63035 100644
--- a/src/ui/locales/translated/zh_CN.json
+++ b/src/ui/locales/translated/zh_CN.json
@@ -38,6 +38,8 @@
"helpText": "输入您的 Termix 服务器运行所对应的 URL(例如,http://localhost:30001 或 https://your-server.com)",
"changeServer": "变更服务器",
"mustIncludeProtocol": "服务器 URL 必须以 http:// 或 https:// 开头。",
+ "allowInvalidCertificate": "允许无效证书",
+ "allowInvalidCertificateDesc": "仅用于可信的自托管服务器,例如自签名证书或 IP 地址证书。",
"useEmbedded": "使用本地服务器",
"embeddedDesc": "使用内置的本地服务器运行 Termixed (不需要远程服务器)",
"embeddedConnecting": "正在连接本地服务器...",
@@ -356,6 +358,7 @@
"tunnelModeLocalDesc": "将本地端口转发到远程服务器上的端口(或其主机可访问)。",
"tunnelModeRemoteDesc": "将远程服务器上的端口转回您机器上的本地端口。",
"tunnelModeDynamicDesc": "在本地端口上创建一个 SOCKS5 代理, 用于动态端口转发.",
+ "sameHost": "本机(直接隧道)",
"endpointHost": "端点主机",
"endpointPort": "端点端口",
"bindHost": "绑定主机",
diff --git a/src/ui/main-axios.ts b/src/ui/main-axios.ts
index 03ae44023..cd3e91ab0 100644
--- a/src/ui/main-axios.ts
+++ b/src/ui/main-axios.ts
@@ -3,22 +3,7 @@ import { toast } from "sonner";
import { getBasePath } from "@/lib/base-path";
import { isElectron } from "@/lib/electron";
import { clearTermixSessionStorage } from "@/shell/TabContext";
-import type {
- SSHHost,
- SSHHostData,
- SSHFolder,
- TunnelConfig,
- TunnelStatus,
- TunnelConnection,
- C2STunnelPreset,
- FileManagerFile,
- FileManagerShortcut,
- DockerContainer,
- DockerStats,
- DockerLogOptions,
- DockerValidation,
- ProxyNode,
-} from "@/types/index";
+import type { SSHHost } from "@/types/index";
// ============================================================================
// RBAC TYPE DEFINITIONS
@@ -72,14 +57,6 @@ import {
} from "@/lib/frontend-logger";
import { dbHealthMonitor } from "@/lib/db-health-monitor";
-interface FileManagerOperation {
- name: string;
- path: string;
- isSSH: boolean;
- sshSessionId?: string;
- hostId: number;
-}
-
export type ServerStatus = {
status: "online" | "offline";
lastChecked: string;
@@ -89,27 +66,6 @@ export type SSHHostWithStatus = SSHHost & {
status: "online" | "offline" | "unknown";
};
-type ApiConnectionLog = {
- type: "info" | "success" | "warning" | "error";
- stage: string;
- message: string;
- details?: Record<string, unknown>;
-};
-
-type ConnectErrorResponse = {
- error?: string;
- message?: string;
- connectionLogs?: ApiConnectionLog[];
- requires_totp?: boolean;
- requires_warpgate?: boolean;
- sessionId?: string;
- prompt?: string;
- url?: string;
- securityKey?: string;
- status?: string;
- reason?: string;
-};
-
interface CpuMetrics {
percent: number | null;
cores: number | null;
@@ -136,7 +92,7 @@ export type ServerMetrics = {
lastChecked: string;
};
-interface AuthResponse {
+export interface AuthResponse {
success?: boolean;
is_admin?: boolean;
username?: string;
@@ -147,9 +103,10 @@ interface AuthResponse {
requires_totp?: boolean;
temp_token?: string;
rememberMe?: boolean;
+ token?: string;
}
-interface UserInfo {
+export interface UserInfo {
totp_enabled: boolean;
userId: string;
username: string;
@@ -302,7 +259,7 @@ export function getCookie(name: string): string | undefined {
let userWasAuthenticated = false;
let latestAuthSuccessAt = 0;
-function markUserAuthenticated(): void {
+export function markUserAuthenticated(): void {
userWasAuthenticated = true;
latestAuthSuccessAt =
typeof performance !== "undefined" ? performance.now() : Date.now();
@@ -545,8 +502,6 @@ function createApiInstance(
return Promise.reject(error);
}
- const wasAuthenticated = userWasAuthenticated;
-
if (isElectron()) {
const electronAPI = (
window as unknown as {
@@ -608,6 +563,7 @@ let embeddedMode = false;
export interface ServerConfig {
serverUrl: string;
lastUpdated: string;
+ allowInvalidCertificate?: boolean;
}
interface AxiosRequestConfigExtended extends AxiosRequestConfig {
@@ -675,16 +631,6 @@ export function getConfiguredServerUrl(): string | null {
return configuredServerUrl;
}
-interface AxiosRequestConfigExtended extends AxiosRequestConfig {
- startTime?: number;
- requestId?: string;
- __silentRetry?: boolean;
-}
-
-interface AxiosErrorExtended extends AxiosError {
- config?: AxiosRequestConfigExtended;
-}
-
export async function testServerConnection(
serverUrl: string,
): Promise<{ success: boolean; error?: string }> {
@@ -954,7 +900,7 @@ class ApiError extends Error {
}
}
-function handleApiError(error: unknown, operation: string): never {
+export function handleApiError(error: unknown, operation: string): never {
const context: LogContext = {
operation: "error_handling",
errorOperation: operation,
@@ -1088,3934 +1034,950 @@ function handleApiError(error: unknown, operation: string): never {
}
// ============================================================================
-// SSH HOST MANAGEMENT
+
+// ============================================================================
+// HOST-TO-HOST TRANSFER
// ============================================================================
-export async function getSSHHosts(): Promise<SSHHostWithStatus[]> {
- try {
- const hostsResponse = await sshHostApi.get("/db/host");
- const hosts: SSHHost[] = Array.isArray(hostsResponse.data)
- ? hostsResponse.data
- : [];
+export type TransferMethodPreference = "auto" | "tar" | "item_sftp";
- let statuses: Record<number, ServerStatus> = {};
- try {
- statuses = (await getAllServerStatuses()) || {};
- } catch {
- // Status fetch failure should not prevent host list from loading
- }
+export interface TransferScanSummary {
+ fileCount: number;
+ totalBytes: number;
+ largestFileBytes: number;
+ incompressibleRatio: number;
+}
- return hosts.map((host) => ({
- ...host,
- status: statuses[host.id]?.status || "unknown",
- }));
- } catch (error) {
- throw handleApiError(error, "fetch SSH hosts");
- }
+export interface TransferMethodPreview {
+ methodPreference: TransferMethodPreference;
+ resolvedMethod: "tar" | "item_sftp";
+ reasonKey: string;
+ sourcePlatform: "unix" | "windows";
+ destPlatform: "unix" | "windows";
+ sourceHasTar: boolean;
+ destHasTar: boolean;
+ summary: TransferScanSummary;
}
-export async function createSSHHost(hostData: SSHHostData): Promise<SSHHost> {
+export async function getTransferMethodPreview(
+ sourceSessionId: string,
+ sourcePaths: string[],
+ destSessionId: string,
+ destPath: string,
+ methodPreference?: TransferMethodPreference,
+): Promise<TransferMethodPreview> {
try {
- if (hostData.authType === "key" && hostData.key instanceof File) {
- const formData = new FormData();
- formData.append("key", hostData.key);
- const dataWithoutFile = { ...hostData, key: undefined };
- formData.append("data", JSON.stringify(dataWithoutFile));
- const response = await sshHostApi.post("/db/host", formData, {
- headers: { "Content-Type": "multipart/form-data" },
- });
- return response.data;
- }
- const response = await sshHostApi.post("/db/host", hostData);
+ const response = await fileManagerApi.post("/ssh/transferMethodPreview", {
+ sourceSessionId,
+ sourcePaths,
+ destSessionId,
+ destPath,
+ methodPreference: methodPreference ?? "auto",
+ });
return response.data;
} catch (error) {
- throw handleApiError(error, "create SSH host");
+ handleApiError(error, "preview transfer method");
+ throw error;
}
}
-export async function updateSSHHost(
- hostId: number,
- hostData: SSHHostData,
-): Promise<SSHHost> {
- try {
- if (hostData.authType === "key" && hostData.key instanceof File) {
- const formData = new FormData();
- formData.append("key", hostData.key);
- const dataWithoutFile = { ...hostData, key: undefined };
- formData.append("data", JSON.stringify(dataWithoutFile));
- const response = await sshHostApi.put(`/db/host/${hostId}`, formData, {
- headers: { "Content-Type": "multipart/form-data" },
- });
- return response.data;
- }
- const response = await sshHostApi.put(`/db/host/${hostId}`, hostData);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "update SSH host");
- }
+export interface TransferHopMetrics {
+ id: string;
+ mbPerSec?: number;
}
-export async function wakeOnLan(hostId: number): Promise<{ success: boolean }> {
- try {
- const response = await sshHostApi.post(`/db/host/${hostId}/wake`);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "wake on LAN");
+export interface TransferTimings {
+ prepareDestMs?: number;
+ compressMs?: number;
+ transferMs?: number;
+ extractMs?: number;
+ sourceDeleteMs?: number;
+ totalMs?: number;
+ transferBytes?: number;
+ endToEndMbPerSec?: number;
+ hops?: TransferHopMetrics[];
+}
+
+export function getTransferProgressPercent(
+ status: TransferProgressResponse,
+): number | undefined {
+ if (
+ status.bytesTransferred !== undefined &&
+ status.totalBytes !== undefined &&
+ status.totalBytes > 0
+ ) {
+ return Math.min(
+ 100,
+ Math.round((status.bytesTransferred / status.totalBytes) * 100),
+ );
+ }
+ if (
+ status.itemsCompleted !== undefined &&
+ status.totalItems !== undefined &&
+ status.totalItems > 0
+ ) {
+ return Math.min(
+ 100,
+ Math.round((status.itemsCompleted / status.totalItems) * 100),
+ );
}
+ return undefined;
}
-export async function bulkImportSSHHosts(
- hosts: SSHHostData[],
- overwrite = false,
-): Promise<{
- message: string;
- success: number;
- updated: number;
- skipped: number;
- failed: number;
- errors: string[];
-}> {
- try {
- const response = await sshHostApi.post("/bulk-import", {
- hosts,
- overwrite,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "bulk import SSH hosts");
+export function formatTransferMbPerSec(
+ mbPerSec?: number,
+ _bytes?: number,
+ _ms?: number,
+): string {
+ if (mbPerSec === undefined || mbPerSec <= 0) return "";
+ if (mbPerSec < 1) return `${(mbPerSec * 1024).toFixed(0)} KB/s`;
+ return `${mbPerSec.toFixed(1)} MB/s`;
+}
+
+export function formatDurationMs(ms?: number): string {
+ if (ms === undefined) return "";
+ if (ms < 1000) return `${ms}ms`;
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
+ const minutes = Math.floor(ms / 60000);
+ const seconds = Math.round((ms % 60000) / 1000);
+ return `${minutes}m ${seconds}s`;
+}
+
+interface TransferProgressTracker {
+ update(status: TransferProgressResponse): { rate: number | undefined; stalled: boolean };
+}
+
+export function createTransferProgressTracker(): TransferProgressTracker {
+ let lastBytes: number | undefined;
+ let lastTime: number | undefined;
+ let lastRate: number | undefined;
+ let lastActivityTime: number | undefined;
+ const STALL_THRESHOLD_MS = 5000;
+
+ return {
+ update(status) {
+ const now = Date.now();
+ const bytes = status.bytesTransferred;
+
+ if (bytes !== undefined && lastBytes !== undefined && lastTime !== undefined) {
+ const deltaBytes = bytes - lastBytes;
+ const deltaMs = now - lastTime;
+ if (deltaMs > 0 && deltaBytes >= 0) {
+ lastRate = (deltaBytes / deltaMs / 1024 / 1024) * 1000;
+ if (deltaBytes > 0) lastActivityTime = now;
+ }
+ } else if (bytes !== undefined) {
+ lastActivityTime = now;
+ }
+
+ lastBytes = bytes;
+ lastTime = now;
+
+ const stalled =
+ lastActivityTime !== undefined &&
+ now - lastActivityTime > STALL_THRESHOLD_MS &&
+ status.status === "running" &&
+ status.phase === "transferring";
+
+ return { rate: lastRate, stalled };
+ },
+ };
+}
+
+export interface TransferProgressResponse {
+ transferId: string;
+ status: "running" | "success" | "partial" | "error" | "cancelled";
+ phase: "compressing" | "transferring" | "extracting" | "reconnecting";
+ bytesTransferred?: number;
+ totalBytes?: number;
+ itemsCompleted?: number;
+ totalItems?: number;
+ failedPaths?: string[];
+ message?: string;
+ method?: "stream" | "tar" | "item_sftp";
+ sourcePaths?: string[];
+ destPath?: string;
+ sourceSessionId?: string;
+ destSessionId?: string;
+ startedAt?: number;
+ timings?: TransferTimings;
+ sourceDeleted?: boolean;
+ moveRequested?: boolean;
+ partialDestRemaining?: boolean;
+ cleanupCompleted?: boolean;
+ retryable?: boolean;
+ parallelSegmentCount?: number;
+}
+
+export async function transferToHost(
+ sourceSessionId: string,
+ sourcePaths: string[],
+ destSessionId: string,
+ destPath: string,
+ move?: boolean,
+ methodPreference?: TransferMethodPreference,
+ parallelSegmentCount = 2,
+): Promise<{ transferId: string }> {
+ try {
+ fileLogger.info("Starting host transfer", {
+ operation: "host_transfer",
+ sourceSessionId,
+ destSessionId,
+ sourcePaths,
+ destPath,
+ move,
+ methodPreference,
+ parallelSegmentCount,
+ });
+
+ const response = await fileManagerApi.post("/ssh/transferToHost", {
+ sourceSessionId,
+ sourcePaths,
+ destSessionId,
+ destPath,
+ move,
+ methodPreference: methodPreference ?? "auto",
+ parallelSegmentCount,
+ });
+
+ return response.data;
+ } catch (error) {
+ fileLogger.error("Failed to start host transfer", error, {
+ operation: "host_transfer",
+ sourceSessionId,
+ destSessionId,
+ sourcePaths,
+ });
+ handleApiError(error, "transfer to host");
+ throw error;
}
}
-export async function bulkUpdateSSHHosts(
- hostIds: number[],
- updates: Record<string, unknown>,
-): Promise<{ updated: number; failed: number; errors: string[] }> {
+export async function getTransferStatus(
+ transferId: string,
+): Promise<TransferProgressResponse> {
try {
- const response = await sshHostApi.patch("/bulk-update", {
- hostIds,
- updates,
- });
+ const response = await fileManagerApi.get(
+ `/ssh/transferStatus/${transferId}`,
+ );
return response.data;
} catch (error) {
- handleApiError(error, "bulk update SSH hosts");
+ handleApiError(error, "get transfer status");
+ throw error;
}
}
-export async function deleteSSHHost(
- hostId: number,
-): Promise<Record<string, unknown>> {
+export async function listActiveTransfers(): Promise<{
+ transfers: TransferProgressResponse[];
+}> {
try {
- const response = await sshHostApi.delete(`/db/host/${hostId}`);
+ const response = await fileManagerApi.get("/ssh/activeTransfers");
return response.data;
} catch (error) {
- handleApiError(error, "delete SSH host");
+ handleApiError(error, "list active transfers");
+ throw error;
}
}
-export async function getSSHHostById(hostId: number): Promise<SSHHost> {
+export async function cancelTransferToHost(transferId: string): Promise<void> {
try {
- const response = await sshHostApi.get(`/db/host/${hostId}`);
- return response.data;
+ await fileManagerApi.post(`/ssh/transferCancel/${transferId}`);
} catch (error) {
- handleApiError(error, "fetch SSH host");
+ fileLogger.warn("Transfer cancel request failed (non-fatal)", {
+ operation: "host_transfer",
+ transferId,
+ error,
+ });
}
}
-export async function exportSSHHostWithCredentials(
- hostId: number,
-): Promise<SSHHost> {
+export async function cleanupCancelledTransfer(
+ transferId: string,
+): Promise<{ removedPaths: string[]; failedPaths: string[] }> {
try {
- const response = await sshHostApi.get(`/db/host/${hostId}/export`);
+ const response = await fileManagerApi.post(
+ `/ssh/transferCleanup/${transferId}`,
+ );
return response.data;
} catch (error) {
- handleApiError(error, "export SSH host with credentials");
+ handleApiError(error, "clean up cancelled transfer");
+ throw error;
}
}
-export async function exportAllSSHHosts(): Promise<{
- hosts: SSHHost[];
-}> {
+export async function retryTransferToHost(
+ transferId: string,
+): Promise<{ ok: boolean; transferId: string }> {
try {
- const response = await sshHostApi.get("/db/hosts/export");
+ const response = await fileManagerApi.post(
+ `/ssh/transferRetry/${transferId}`,
+ );
return response.data;
} catch (error) {
- handleApiError(error, "export all SSH hosts");
+ handleApiError(error, "retry transfer");
+ throw error;
}
}
+export async function pollTransferUntilComplete(
+ transferId: string,
+ onProgress?: (status: TransferProgressResponse) => void,
+ intervalMs = 500,
+): Promise<TransferProgressResponse> {
+ return new Promise((resolve, reject) => {
+ const poll = async () => {
+ try {
+ const status = await getTransferStatus(transferId);
+ onProgress?.(status);
+
+ if (
+ status.status === "success" ||
+ status.status === "partial" ||
+ status.status === "error" ||
+ status.status === "cancelled"
+ ) {
+ resolve(status);
+ return;
+ }
+
+ setTimeout(poll, intervalMs);
+ } catch (err) {
+ reject(err);
+ }
+ };
+
+ void poll();
+ });
+}
+
// ============================================================================
-// SSH AUTOSTART MANAGEMENT
+// FILE MANAGER DATA
// ============================================================================
-export async function enableAutoStart(
- sshConfigId: number,
-): Promise<Record<string, unknown>> {
+export interface TransferDestination {
+ id: number;
+ userId: string;
+ sourceHostId: number;
+ destHostId: number;
+ destPath: string;
+ destPathLabel?: string;
+ lastUsed?: string;
+}
+
+export async function getTransferRecent(
+ sourceHostId: number,
+): Promise<TransferDestination[]> {
try {
- const response = await sshHostApi.post("/autostart/enable", {
- sshConfigId,
+ const response = await authApi.get("/host/transfer/recent", {
+ params: { sourceHostId },
});
return response.data;
} catch (error) {
- handleApiError(error, "enable autostart");
+ handleApiError(error, "get transfer recent destinations");
+ throw error;
}
}
-export async function disableAutoStart(
- sshConfigId: number,
+export async function addTransferRecent(
+ sourceHostId: number,
+ destHostId: number,
+ destPath: string,
+ destPathLabel?: string,
): Promise<Record<string, unknown>> {
try {
- const response = await sshHostApi.delete("/autostart/disable", {
- data: { sshConfigId },
+ const response = await authApi.post("/host/transfer/recent", {
+ sourceHostId,
+ destHostId,
+ destPath,
+ destPathLabel,
});
return response.data;
} catch (error) {
- handleApiError(error, "disable autostart");
+ handleApiError(error, "add transfer recent destination");
+ throw error;
}
}
-export async function getAutoStartStatus(): Promise<{
- autostart_configs: Array<{
- sshConfigId: number;
- host: string;
- port: number;
- username: string;
- authType: string;
- }>;
- total_count: number;
-}> {
- try {
- const response = await sshHostApi.get("/autostart/status");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch autostart status");
- }
-}
+export {
+ getSSHHosts,
+ createSSHHost,
+ updateSSHHost,
+ wakeOnLan,
+ bulkImportSSHHosts,
+ bulkUpdateSSHHosts,
+ deleteSSHHost,
+ getSSHHostById,
+ exportSSHHostWithCredentials,
+ exportAllSSHHosts,
+ enableAutoStart,
+ disableAutoStart,
+ getAutoStartStatus,
+ testProxyConnection,
+} from "@/api/ssh-host-management-api";
+
+export {
+ getTunnelStatuses,
+ subscribeTunnelStatuses,
+ getTunnelStatusByName,
+ connectTunnel,
+ disconnectTunnel,
+ cancelTunnel,
+ getC2STunnelPresets,
+ createC2STunnelPreset,
+ updateC2STunnelPreset,
+ deleteC2STunnelPreset,
+} from "@/api/tunnel-api";
+
+export {
+ getFileManagerRecent,
+ addFileManagerRecent,
+ removeFileManagerRecent,
+ getFileManagerPinned,
+ addFileManagerPinned,
+ removeFileManagerPinned,
+ getFileManagerShortcuts,
+ addFileManagerShortcut,
+ removeFileManagerShortcut,
+} from "@/api/file-manager-metadata-api";
+
+export {
+ connectSSH,
+ disconnectSSH,
+ verifySSHTOTP,
+ verifySSHWarpgate,
+ quickConnect,
+ getSSHStatus,
+ keepSSHAlive,
+ listSSHFiles,
+ identifySSHSymlink,
+ resolveSSHPath,
+ readSSHFile,
+ writeSSHFile,
+ uploadSSHFile,
+ downloadSSHFile,
+ downloadSSHFileStream,
+ createSSHFile,
+ createSSHFolder,
+ deleteSSHItem,
+ setSudoPassword,
+ copySSHItem,
+ renameSSHItem,
+ moveSSHItem,
+ changeSSHPermissions,
+ extractSSHArchive,
+ compressSSHFiles,
+ ensureSSHSessionForHost,
+ browseSSHDirectory,
+ type HostConnectionState,
+ type EnsureSSHSessionResult,
+ type BrowseSSHDirectoryResult,
+} from "@/api/ssh-file-operations-api";
+
+export {
+ getRecentFiles,
+ addRecentFile,
+ removeRecentFile,
+ getPinnedFiles,
+ addPinnedFile,
+ removePinnedFile,
+ getFolderShortcuts,
+ addFolderShortcut,
+ removeFolderShortcut,
+} from "@/api/file-manager-data-api";
+
+export {
+ getAllServerStatuses,
+ getServerStatusById,
+ getServerMetricsById,
+ startMetricsPolling,
+ stopMetricsPolling,
+ sendMetricsHeartbeat,
+ registerMetricsViewer,
+ unregisterMetricsViewer,
+ submitMetricsTOTP,
+ refreshServerPolling,
+ notifyHostCreatedOrUpdated,
+} from "@/api/server-stats-api";
+
+export {
+ getGlobalMonitoringSettings,
+ updateGlobalMonitoringSettings,
+ getLogLevel,
+ updateLogLevel,
+ getSessionTimeout,
+ updateSessionTimeout,
+ getGuacamoleSettings,
+ updateGuacamoleSettings,
+} from "@/api/settings-api";
// ============================================================================
-// PROXY CONNECTIVITY TEST
+// AUTHENTICATION
// ============================================================================
-export async function testProxyConnection(options: {
- singleProxy?: {
- host: string;
- port: number;
- type?: 4 | 5 | "http";
- username?: string;
- password?: string;
- };
- proxyChain?: ProxyNode[];
- testTarget?: { host: string; port: number };
-}): Promise<{ success: boolean; latencyMs?: number; error?: string }> {
+export async function registerUser(
+ username: string,
+ password: string,
+): Promise<Record<string, unknown>> {
try {
- const response = await sshHostApi.post("/db/proxy/test", options);
+ const response = await authApi.post("/users/create", {
+ username,
+ password,
+ });
return response.data;
} catch (error) {
- if (error instanceof AxiosError && error.response?.data?.error) {
- return { success: false, error: error.response.data.error };
- }
- handleApiError(error, "test proxy connection");
+ handleApiError(error, "register user");
}
}
-// ============================================================================
-// TUNNEL MANAGEMENT
-// ============================================================================
-
-export async function getTunnelStatuses(): Promise<
- Record<string, TunnelStatus>
-> {
+export async function loginUser(
+ username: string,
+ password: string,
+ rememberMe: boolean = false,
+): Promise<AuthResponse> {
try {
- const response = await tunnelApi.get("/tunnel/status");
- return response.data || {};
- } catch (error) {
- handleApiError(error, "fetch tunnel statuses");
- }
-}
+ const response = await authApi.post("/users/login", {
+ username,
+ password,
+ rememberMe,
+ });
-export function subscribeTunnelStatuses(
- onStatuses: (statuses: Record<string, TunnelStatus>) => void,
- onError?: () => void,
-): () => void {
- const baseURL = (tunnelApi.defaults.baseURL || "").replace(/\/$/, "");
- const source = new EventSource(`${baseURL}/tunnel/status/stream`, {
- withCredentials: true,
- });
+ const isInIframe =
+ typeof window !== "undefined" && window.self !== window.top;
- source.addEventListener("statuses", (event) => {
- try {
- onStatuses(JSON.parse(event.data) as Record<string, TunnelStatus>);
- } catch {
- onError?.();
+ if (isInIframe && isElectron() && response.data.success) {
+ try {
+ window.parent.postMessage(
+ {
+ type: "AUTH_SUCCESS",
+ source: "login_api",
+ platform: "desktop",
+ timestamp: Date.now(),
+ },
+ window.location.origin,
+ );
+ } catch (e) {
+ console.error("[main-axios] Error posting message to parent:", e);
+ }
}
- });
-
- source.onerror = () => {
- onError?.();
- };
- return () => source.close();
-}
+ if (response.data.token) {
+ localStorage.setItem("jwt", response.data.token);
+ }
-export async function getTunnelStatusByName(
- tunnelName: string,
-): Promise<TunnelStatus | undefined> {
- const statuses = await getTunnelStatuses();
- return statuses[tunnelName];
-}
+ if (response.data.success && !response.data.requires_totp) {
+ markUserAuthenticated();
+ }
-export async function connectTunnel(
- tunnelConfig: TunnelConfig,
-): Promise<Record<string, unknown>> {
- try {
- const response = await tunnelApi.post("/tunnel/connect", tunnelConfig);
- return response.data;
+ return {
+ success: response.data.success,
+ is_admin: response.data.is_admin,
+ username: response.data.username,
+ requires_totp: response.data.requires_totp,
+ temp_token: response.data.temp_token,
+ rememberMe: response.data.rememberMe,
+ is_oidc: response.data.is_oidc,
+ totp_enabled: response.data.totp_enabled,
+ data_unlocked: response.data.data_unlocked,
+ token: response.data.token,
+ };
} catch (error) {
- handleApiError(error, "connect tunnel");
+ throw handleApiError(error, "login user");
}
}
-export async function disconnectTunnel(
- tunnelName: string,
-): Promise<Record<string, unknown>> {
+export async function logoutUser(): Promise<{
+ success: boolean;
+ message: string;
+}> {
try {
- const response = await tunnelApi.post("/tunnel/disconnect", { tunnelName });
+ const response = await authApi.post("/users/logout");
+
+ clearTermixSessionStorage();
+
+ if (isElectron()) {
+ const electronAPI = (
+ window as unknown as {
+ electronAPI?: { clearSessionCookies?: () => Promise<void> };
+ }
+ ).electronAPI;
+ electronAPI?.clearSessionCookies?.().catch(() => {});
+ } else {
+ const isSecure = window.location.protocol === "https:";
+ const cookieString = isSecure
+ ? "jwt=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; Secure; SameSite=Lax"
+ : "jwt=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax";
+ document.cookie = cookieString;
+ }
+
return response.data;
} catch (error) {
- handleApiError(error, "disconnect tunnel");
+ clearTermixSessionStorage();
+
+ if (isElectron()) {
+ const electronAPI = (
+ window as unknown as {
+ electronAPI?: { clearSessionCookies?: () => Promise<void> };
+ }
+ ).electronAPI;
+ electronAPI?.clearSessionCookies?.().catch(() => {});
+ } else {
+ const isSecure = window.location.protocol === "https:";
+ const cookieString = isSecure
+ ? "jwt=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; Secure; SameSite=Lax"
+ : "jwt=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax";
+ document.cookie = cookieString;
+ }
+ handleApiError(error, "logout user");
}
}
-export async function cancelTunnel(
- tunnelName: string,
-): Promise<Record<string, unknown>> {
+export async function getUserInfo(): Promise<UserInfo> {
try {
- const response = await tunnelApi.post("/tunnel/cancel", { tunnelName });
+ const response = await authApi.get("/users/me");
+ markUserAuthenticated();
return response.data;
} catch (error) {
- handleApiError(error, "cancel tunnel");
+ handleApiError(error, "fetch user info");
}
}
-export async function getC2STunnelPresets(): Promise<C2STunnelPreset[]> {
+export async function getCurrentToken(): Promise<string | null> {
try {
- const response = await authApi.get("/c2s-tunnel-presets");
- return response.data || [];
- } catch (error) {
- if (axios.isAxiosError(error) && error.response?.status === 404) {
- return [];
- }
- handleApiError(error, "fetch client tunnel presets");
+ const response = await authApi.get("/users/me/token");
+ return response.data?.token ?? null;
+ } catch {
+ return null;
}
}
-export async function createC2STunnelPreset(data: {
- name: string;
- config: TunnelConnection[];
- platform?: string;
- computerName?: string;
-}): Promise<C2STunnelPreset> {
+export async function unlockUserData(
+ password: string,
+): Promise<{ success: boolean; message: string }> {
try {
- const response = await authApi.post("/c2s-tunnel-presets", data);
+ const response = await authApi.post("/users/unlock-data", { password });
return response.data;
} catch (error) {
- handleApiError(error, "create client tunnel preset");
+ handleApiError(error, "unlock user data");
}
}
-export async function updateC2STunnelPreset(
- id: number,
- data: Partial<{
- name: string;
- config: TunnelConnection[];
- platform: string;
- computerName: string;
- }>,
-): Promise<C2STunnelPreset> {
+export async function getRegistrationAllowed(): Promise<{ allowed: boolean }> {
try {
- const response = await authApi.put(`/c2s-tunnel-presets/${id}`, data);
+ const response = await authApi.get("/users/registration-allowed");
return response.data;
} catch (error) {
- handleApiError(error, "update client tunnel preset");
+ handleApiError(error, "check registration status");
}
}
-export async function deleteC2STunnelPreset(
- id: number,
-): Promise<Record<string, unknown>> {
+export async function getPasswordLoginAllowed(): Promise<{ allowed: boolean }> {
try {
- const response = await authApi.delete(`/c2s-tunnel-presets/${id}`);
- return response.data;
- } catch (error) {
- handleApiError(error, "delete client tunnel preset");
- }
-}
-
-// ============================================================================
-// FILE MANAGER METADATA (Recent, Pinned, Shortcuts)
-// ============================================================================
-
-export async function getFileManagerRecent(
- hostId: number,
-): Promise<FileManagerFile[]> {
- try {
- const response = await sshHostApi.get(
- `/file_manager/recent?hostId=${hostId}`,
- );
- return response.data || [];
- } catch {
- return [];
- }
-}
-
-export async function addFileManagerRecent(
- file: FileManagerOperation,
-): Promise<Record<string, unknown>> {
- try {
- const response = await sshHostApi.post("/file_manager/recent", file);
- return response.data;
- } catch (error) {
- handleApiError(error, "add recent file");
- }
-}
-
-export async function removeFileManagerRecent(
- file: FileManagerOperation,
-): Promise<Record<string, unknown>> {
- try {
- const response = await sshHostApi.delete("/file_manager/recent", {
- data: file,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "remove recent file");
- }
-}
-
-export async function getFileManagerPinned(
- hostId: number,
-): Promise<FileManagerFile[]> {
- try {
- const response = await sshHostApi.get(
- `/file_manager/pinned?hostId=${hostId}`,
- );
- return response.data || [];
- } catch {
- return [];
- }
-}
-
-export async function addFileManagerPinned(
- file: FileManagerOperation,
-): Promise<Record<string, unknown>> {
- try {
- const response = await sshHostApi.post("/file_manager/pinned", file);
- return response.data;
- } catch (error) {
- handleApiError(error, "add pinned file");
- }
-}
-
-export async function removeFileManagerPinned(
- file: FileManagerOperation,
-): Promise<Record<string, unknown>> {
- try {
- const response = await sshHostApi.delete("/file_manager/pinned", {
- data: file,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "remove pinned file");
- }
-}
-
-export async function getFileManagerShortcuts(
- hostId: number,
-): Promise<FileManagerShortcut[]> {
- try {
- const response = await sshHostApi.get(
- `/file_manager/shortcuts?hostId=${hostId}`,
- );
- return response.data || [];
- } catch {
- return [];
- }
-}
-
-export async function addFileManagerShortcut(
- shortcut: FileManagerOperation,
-): Promise<Record<string, unknown>> {
- try {
- const response = await sshHostApi.post("/file_manager/shortcuts", shortcut);
- return response.data;
- } catch (error) {
- handleApiError(error, "add shortcut");
- }
-}
-
-export async function removeFileManagerShortcut(
- shortcut: FileManagerOperation,
-): Promise<Record<string, unknown>> {
- try {
- const response = await sshHostApi.delete("/file_manager/shortcuts", {
- data: shortcut,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "remove shortcut");
- }
-}
-
-// ============================================================================
-// SSH FILE OPERATIONS
-// ============================================================================
-
-export async function connectSSH(
- sessionId: string,
- config: {
- hostId?: number;
- ip: string;
- port: number;
- username: string;
- password?: string;
- sshKey?: string;
- keyPassword?: string;
- authType?: string;
- credentialId?: number;
- userId?: string;
- forceKeyboardInteractive?: boolean;
- useSocks5?: boolean;
- socks5Host?: string;
- socks5Port?: number;
- socks5Username?: string;
- socks5Password?: string;
- socks5ProxyChain?: unknown;
- jumpHosts?: Array<{ hostId: number }>;
- },
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post("/ssh/connect", {
- sessionId,
- ...config,
- });
- return response.data;
- } catch (error: unknown) {
- if (
- axios.isAxiosError<ConnectErrorResponse>(error) &&
- error.response?.data?.connectionLogs
- ) {
- const data = error.response.data;
- const errorWithLogs = new Error(
- data.error || data.message || error.message,
- );
- Object.assign(errorWithLogs, {
- connectionLogs: data.connectionLogs,
- });
- if (data.requires_totp) {
- Object.assign(errorWithLogs, {
- requires_totp: true,
- sessionId: data.sessionId,
- prompt: data.prompt,
- });
- }
- if (data.requires_warpgate) {
- Object.assign(errorWithLogs, {
- requires_warpgate: true,
- sessionId: data.sessionId,
- url: data.url,
- securityKey: data.securityKey,
- });
- }
- if (data.status === "auth_required") {
- Object.assign(errorWithLogs, {
- status: "auth_required",
- reason: data.reason,
- });
- }
- throw errorWithLogs;
- }
- handleApiError(error, "connect SSH");
- }
-}
-
-export async function disconnectSSH(
- sessionId: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post("/ssh/disconnect", {
- sessionId,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "disconnect SSH");
- }
-}
-
-export async function verifySSHTOTP(
- sessionId: string,
- totpCode: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post("/ssh/connect-totp", {
- sessionId,
- totpCode,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "verify SSH TOTP");
- }
-}
-
-export async function verifySSHWarpgate(
- sessionId: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post("/ssh/connect-warpgate", {
- sessionId,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "verify SSH Warpgate");
- }
-}
-
-/**
- * @openapi
- * /ssh/quick-connect:
- * post:
- * summary: Create a temporary SSH connection without saving to database
- * description: Returns a temporary host configuration for immediate use
- * tags:
- * - SSH
- * requestBody:
- * required: true
- * content:
- * application/json:
- * schema:
- * type: object
- * required:
- * - ip
- * - port
- * - username
- * - authType
- * properties:
- * ip:
- * type: string
- * description: SSH server IP or hostname
- * port:
- * type: number
- * description: SSH server port
- * username:
- * type: string
- * description: SSH username
- * authType:
- * type: string
- * enum: [password, key, credential]
- * description: Authentication method
- * password:
- * type: string
- * description: Password (required if authType is password)
- * key:
- * type: string
- * description: SSH private key (required if authType is key)
- * keyPassword:
- * type: string
- * description: SSH key password (optional)
- * keyType:
- * type: string
- * description: SSH key type
- * credentialId:
- * type: number
- * description: Credential ID (required if authType is credential)
- * overrideCredentialUsername:
- * type: boolean
- * description: Use provided username instead of credential username
- * responses:
- * 200:
- * description: Temporary host configuration created successfully
- * content:
- * application/json:
- * schema:
- * type: object
- * description: SSHHost object
- * 400:
- * description: Invalid request data
- * 401:
- * description: Unauthorized
- * 500:
- * description: Server error
- */
-export async function quickConnect(
- data: Record<string, unknown>,
-): Promise<SSHHost> {
- try {
- const response = await authApi.post("/host/quick-connect", data);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "quick connect");
- }
-}
-
-export async function getSSHStatus(
- sessionId: string,
-): Promise<{ connected: boolean }> {
- try {
- const response = await fileManagerApi.get("/ssh/status", {
- params: { sessionId },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "get SSH status");
- }
-}
-
-export async function keepSSHAlive(
- sessionId: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post("/ssh/keepalive", {
- sessionId,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "SSH keepalive");
- }
-}
-
-export async function listSSHFiles(
- sessionId: string,
- path: string,
-): Promise<{ files: unknown[]; path: string }> {
- try {
- const response = await fileManagerApi.get("/ssh/listFiles", {
- params: { sessionId, path },
- });
- return response.data || { files: [], path };
- } catch (error) {
- handleApiError(error, "list SSH files");
- return { files: [], path };
- }
-}
-
-export async function identifySSHSymlink(
- sessionId: string,
- path: string,
-): Promise<{ path: string; target: string; type: "directory" | "file" }> {
- try {
- const response = await fileManagerApi.get("/ssh/identifySymlink", {
- params: { sessionId, path },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "identify SSH symlink");
- }
-}
-
-export async function resolveSSHPath(
- sessionId: string,
- path: string,
-): Promise<string> {
- try {
- const response = await fileManagerApi.get("/ssh/resolvePath", {
- params: { sessionId, path },
- });
- return response.data?.resolvedPath || path;
- } catch {
- return path;
- }
-}
-
-export async function readSSHFile(
- sessionId: string,
- path: string,
-): Promise<{
- content: string;
- path: string;
- encoding?: "base64" | "utf8";
-}> {
- try {
- const response = await fileManagerApi.get("/ssh/readFile", {
- params: { sessionId, path },
- });
- return response.data;
- } catch (error: unknown) {
- if (error.response?.status === 404) {
- const customError = new Error("File not found");
- (
- customError as Error & { response?: unknown; isFileNotFound?: boolean }
- ).response = error.response;
- (
- customError as Error & { response?: unknown; isFileNotFound?: boolean }
- ).isFileNotFound = error.response.data?.fileNotFound || true;
- throw customError;
- }
- handleApiError(error, "read SSH file");
- }
-}
-
-export async function writeSSHFile(
- sessionId: string,
- path: string,
- content: string,
- hostId?: number,
- userId?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post("/ssh/writeFile", {
- sessionId,
- path,
- content,
- hostId,
- userId,
- });
-
- if (
- response.data &&
- (response.data.message === "File written successfully" ||
- response.status === 200)
- ) {
- return response.data;
- } else {
- throw new Error("File write operation did not return success status");
- }
- } catch (error) {
- handleApiError(error, "write SSH file");
- }
-}
-
-export async function uploadSSHFile(
- sessionId: string,
- path: string,
- fileName: string,
- content: string,
- hostId?: number,
- userId?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post("/ssh/uploadFile", {
- sessionId,
- path,
- fileName,
- content,
- hostId,
- userId,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "upload SSH file");
- }
-}
-
-export async function downloadSSHFile(
- sessionId: string,
- filePath: string,
- hostId?: number,
- userId?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post("/ssh/downloadFile", {
- sessionId,
- path: filePath,
- hostId,
- userId,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "download SSH file");
- }
-}
-
-export async function downloadSSHFileStream(
- sessionId: string,
- filePath: string,
-): Promise<void> {
- const response = await fileManagerApi.post(
- "/ssh/downloadFileStream",
- { sessionId, path: filePath },
- { responseType: "blob" },
- );
- const blob = response.data as Blob;
- const fileName = filePath.split("/").pop() || "download";
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = fileName;
- a.click();
- URL.revokeObjectURL(url);
-}
-
-export async function createSSHFile(
- sessionId: string,
- path: string,
- fileName: string,
- content: string = "",
- hostId?: number,
- userId?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post("/ssh/createFile", {
- sessionId,
- path,
- fileName,
- content,
- hostId,
- userId,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "create SSH file");
- }
-}
-
-export async function createSSHFolder(
- sessionId: string,
- path: string,
- folderName: string,
- hostId?: number,
- userId?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post("/ssh/createFolder", {
- sessionId,
- path,
- folderName,
- hostId,
- userId,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "create SSH folder");
- }
-}
-
-export async function deleteSSHItem(
- sessionId: string,
- path: string,
- isDirectory: boolean,
- hostId?: number,
- userId?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.delete("/ssh/deleteItem", {
- data: {
- sessionId,
- path,
- isDirectory,
- hostId,
- userId,
- },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "delete SSH item");
- }
-}
-
-export async function setSudoPassword(
- sessionId: string,
- password: string,
-): Promise<void> {
- try {
- await fileManagerApi.post("/sudo-password", {
- sessionId,
- password,
- });
- } catch (error) {
- handleApiError(error, "set sudo password");
- }
-}
-
-export async function copySSHItem(
- sessionId: string,
- sourcePath: string,
- targetDir: string,
- hostId?: number,
- userId?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.post(
- "/ssh/copyItem",
- {
- sessionId,
- sourcePath,
- targetDir,
- hostId,
- userId,
- },
- {
- timeout: 60000,
- },
- );
- return response.data;
- } catch (error) {
- handleApiError(error, "copy SSH item");
- throw error;
- }
-}
-
-export async function renameSSHItem(
- sessionId: string,
- oldPath: string,
- newName: string,
- hostId?: number,
- userId?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.put("/ssh/renameItem", {
- sessionId,
- oldPath,
- newName,
- hostId,
- userId,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "rename SSH item");
- throw error;
- }
-}
-
-export async function moveSSHItem(
- sessionId: string,
- oldPath: string,
- newPath: string,
- hostId?: number,
- userId?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await fileManagerApi.put(
- "/ssh/moveItem",
- {
- sessionId,
- oldPath,
- newPath,
- hostId,
- userId,
- },
- {
- timeout: 60000,
- },
- );
- return response.data;
- } catch (error) {
- handleApiError(error, "move SSH item");
- throw error;
- }
-}
-
-export async function changeSSHPermissions(
- sessionId: string,
- path: string,
- permissions: string,
- hostId?: number,
- userId?: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- fileLogger.info("Changing SSH file permissions", {
- operation: "change_permissions",
- sessionId,
- path,
- permissions,
- hostId,
- userId,
- });
-
- const response = await fileManagerApi.post("/ssh/changePermissions", {
- sessionId,
- path,
- permissions,
- hostId,
- userId,
- });
-
- fileLogger.success("SSH file permissions changed successfully", {
- operation: "change_permissions",
- sessionId,
- path,
- permissions,
- });
-
- return response.data;
- } catch (error) {
- fileLogger.error("Failed to change SSH file permissions", error, {
- operation: "change_permissions",
- sessionId,
- path,
- permissions,
- });
- handleApiError(error, "change SSH permissions");
- throw error;
- }
-}
-
-export async function extractSSHArchive(
- sessionId: string,
- archivePath: string,
- extractPath?: string,
- hostId?: number,
- userId?: string,
-): Promise<{ success: boolean; message: string; extractPath: string }> {
- try {
- fileLogger.info("Extracting archive", {
- operation: "extract_archive",
- sessionId,
- archivePath,
- extractPath,
- hostId,
- userId,
- });
-
- const response = await fileManagerApi.post("/ssh/extractArchive", {
- sessionId,
- archivePath,
- extractPath,
- hostId,
- userId,
- });
-
- fileLogger.success("Archive extracted successfully", {
- operation: "extract_archive",
- sessionId,
- archivePath,
- extractPath: response.data.extractPath,
- });
-
- return response.data;
- } catch (error) {
- fileLogger.error("Failed to extract archive", error, {
- operation: "extract_archive",
- sessionId,
- archivePath,
- extractPath,
- });
- handleApiError(error, "extract archive");
- throw error;
- }
-}
-
-export async function compressSSHFiles(
- sessionId: string,
- paths: string[],
- archiveName: string,
- format?: string,
- hostId?: number,
- userId?: string,
-): Promise<{ success: boolean; message: string; archivePath: string }> {
- try {
- fileLogger.info("Compressing files", {
- operation: "compress_files",
- sessionId,
- paths,
- archiveName,
- format,
- hostId,
- userId,
- });
-
- const response = await fileManagerApi.post("/ssh/compressFiles", {
- sessionId,
- paths,
- archiveName,
- format: format || "zip",
- hostId,
- userId,
- });
-
- fileLogger.success("Files compressed successfully", {
- operation: "compress_files",
- sessionId,
- paths,
- archivePath: response.data.archivePath,
- });
-
- return response.data;
- } catch (error) {
- fileLogger.error("Failed to compress files", error, {
- operation: "compress_files",
- sessionId,
- paths,
- archiveName,
- format,
- });
- handleApiError(error, "compress files");
- throw error;
- }
-}
-
-// ============================================================================
-// FILE MANAGER DATA
-// ============================================================================
-
-export async function getRecentFiles(
- hostId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/host/file_manager/recent", {
- params: { hostId },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "get recent files");
- throw error;
- }
-}
-
-export async function addRecentFile(
- hostId: number,
- path: string,
- name?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/host/file_manager/recent", {
- hostId,
- path,
- name,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "add recent file");
- throw error;
- }
-}
-
-export async function removeRecentFile(
- hostId: number,
- path: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.delete("/host/file_manager/recent", {
- data: { hostId, path },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "remove recent file");
- throw error;
- }
-}
-
-export async function getPinnedFiles(
- hostId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/host/file_manager/pinned", {
- params: { hostId },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "get pinned files");
- throw error;
- }
-}
-
-export async function addPinnedFile(
- hostId: number,
- path: string,
- name?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/host/file_manager/pinned", {
- hostId,
- path,
- name,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "add pinned file");
- throw error;
- }
-}
-
-export async function removePinnedFile(
- hostId: number,
- path: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.delete("/host/file_manager/pinned", {
- data: { hostId, path },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "remove pinned file");
- throw error;
- }
-}
-
-export async function getFolderShortcuts(
- hostId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/host/file_manager/shortcuts", {
- params: { hostId },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "get folder shortcuts");
- throw error;
- }
-}
-
-export async function addFolderShortcut(
- hostId: number,
- path: string,
- name?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/host/file_manager/shortcuts", {
- hostId,
- path,
- name,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "add folder shortcut");
- throw error;
- }
-}
-
-export async function removeFolderShortcut(
- hostId: number,
- path: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.delete("/host/file_manager/shortcuts", {
- data: { hostId, path },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "remove folder shortcut");
- throw error;
- }
-}
-
-// ============================================================================
-// SERVER STATISTICS
-// ============================================================================
-
-/**
- * Progressive retry schedule for the background /status poll.
- *
- * Each entry describes one attempt's per-request timeout and the pause to
- * observe before the next attempt. The pause on the last entry is `null`:
- * after that final failure we surface the network error, which flows
- * through the response interceptor + dbHealthMonitor (which decides
- * between the degraded toast and the full-outage overlay based on whether
- * any WebSocket is still alive).
- *
- * Sequence: try(2s) -> wait 3s -> try(5s) -> wait 5s -> try(8s) -> fail.
- * Worst-case wall-clock = 23s, which fits inside the 30s ServerStatusContext
- * poll cadence, so the next tick acts as the next retry without overlap.
- */
-const STATUS_RETRY_SCHEDULE: ReadonlyArray<{
- timeoutMs: number;
- pauseAfterMs: number | null;
-}> = [
- { timeoutMs: 2000, pauseAfterMs: 3000 },
- { timeoutMs: 5000, pauseAfterMs: 5000 },
- { timeoutMs: 8000, pauseAfterMs: null },
-];
-
-function isTransientStatusError(error: unknown): boolean {
- if (!axios.isAxiosError(error)) return false;
- if (error.response) {
- // Definitive server response (even 5xx) is not something more retries
- // will fix in a useful timeframe; bail out and report it normally.
- return false;
- }
- const code = error.code;
- if (!code) {
- // No code + no response means classic network error (offline / DNS / TCP)
- return true;
- }
- return (
- code === "ECONNABORTED" ||
- code === "ETIMEDOUT" ||
- code === "ERR_NETWORK" ||
- code === "ECONNREFUSED" ||
- code === "ECONNRESET"
- );
-}
-
-export async function getAllServerStatuses(): Promise<
- Record<number, ServerStatus>
-> {
- let lastError: unknown = null;
-
- for (let i = 0; i < STATUS_RETRY_SCHEDULE.length; i++) {
- const { timeoutMs, pauseAfterMs } = STATUS_RETRY_SCHEDULE[i];
- const isFinalAttempt = i === STATUS_RETRY_SCHEDULE.length - 1;
-
- try {
- const response = await statsApi.get("/status", {
- timeout: timeoutMs,
- // Silence per-attempt interceptor logging & health-monitor side
- // effects on all attempts except the final one, so background
- // blips don't look like real outages.
- __silentRetry: !isFinalAttempt,
- } as AxiosRequestConfig & { __silentRetry?: boolean });
- return response.data || {};
- } catch (error) {
- lastError = error;
- if (!isTransientStatusError(error)) {
- break;
- }
- if (pauseAfterMs === null) {
- break;
- }
- await new Promise((resolve) => setTimeout(resolve, pauseAfterMs));
- }
- }
-
- handleApiError(lastError, "fetch server statuses");
-}
-
-export async function getServerStatusById(id: number): Promise<ServerStatus> {
- try {
- const response = await statsApi.get(`/status/${id}`);
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch server status");
- throw error;
- }
-}
-
-export async function getServerMetricsById(
- id: number,
-): Promise<ServerMetrics | null> {
- try {
- const response = await statsApi.get(`/metrics/${id}`, {
- // Treat 404 as an expected "no metrics yet / disabled" signal rather
- // than an error so we don't spam warn logs on the client.
- validateStatus: (status) => status === 200 || status === 404,
- });
- if (response.status === 404) {
- return null;
- }
- return response.data;
- } catch (error) {
- // If a 404 still slips through (e.g. intercepted before reaching here),
- // swallow it quietly; everything else still flows through handleApiError.
- if (axios.isAxiosError(error) && error.response?.status === 404) {
- return null;
- }
- handleApiError(error, "fetch server metrics");
- throw error;
- }
-}
-
-export async function startMetricsPolling(hostId: number): Promise<{
- success: boolean;
- requires_totp?: boolean;
- sessionId?: string;
- prompt?: string;
- viewerSessionId?: string;
- connectionLogs?: ApiConnectionLog[];
-}> {
- try {
- const response = await statsApi.post(`/metrics/start/${hostId}`);
- return response.data;
- } catch (error: unknown) {
- if (
- axios.isAxiosError<ConnectErrorResponse>(error) &&
- error.response?.data?.connectionLogs
- ) {
- const data = error.response.data;
- const errorWithLogs = new Error(
- data.error || data.message || error.message,
- );
- Object.assign(errorWithLogs, {
- connectionLogs: data.connectionLogs,
- });
- throw errorWithLogs;
- }
- handleApiError(error, "start metrics polling");
- throw error;
- }
-}
-
-export async function stopMetricsPolling(
- hostId: number,
- viewerSessionId?: string,
-): Promise<void> {
- try {
- await statsApi.post(`/metrics/stop/${hostId}`, { viewerSessionId });
- } catch (error) {
- handleApiError(error, "stop metrics polling");
- throw error;
- }
-}
-
-export async function sendMetricsHeartbeat(
- viewerSessionId: string,
-): Promise<void> {
- try {
- await statsApi.post("/metrics/heartbeat", { viewerSessionId });
- } catch (error) {
- handleApiError(error, "send metrics heartbeat");
- throw error;
- }
-}
-
-export async function registerMetricsViewer(hostId: number): Promise<{
- success: boolean;
- viewerSessionId?: string;
- skipped?: boolean;
- reason?: string;
-}> {
- try {
- const response = await statsApi.post("/metrics/register-viewer", {
- hostId,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "register metrics viewer");
- throw error;
- }
-}
-
-export async function unregisterMetricsViewer(
- hostId: number,
- viewerSessionId: string,
-): Promise<void> {
- try {
- await statsApi.post("/metrics/unregister-viewer", {
- hostId,
- viewerSessionId,
- });
- } catch (error) {
- handleApiError(error, "unregister metrics viewer");
- throw error;
- }
-}
-
-export async function submitMetricsTOTP(
- sessionId: string,
- totpCode: string,
-): Promise<{
- success: boolean;
- viewerSessionId?: string;
-}> {
- try {
- const response = await statsApi.post("/metrics/connect-totp", {
- sessionId,
- totpCode,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "submit metrics TOTP");
- throw error;
- }
-}
-
-export async function refreshServerPolling(): Promise<void> {
- try {
- await statsApi.post("/refresh");
- } catch (error) {
- console.warn("Failed to refresh server polling:", error);
- }
-}
-
-export async function notifyHostCreatedOrUpdated(
- hostId: number,
-): Promise<void> {
- try {
- await statsApi.post("/host-updated", { hostId });
- } catch (error) {
- console.warn("Failed to notify stats server of host update:", error);
- }
-}
-
-// ============================================================================
-// GLOBAL MONITORING SETTINGS
-// ============================================================================
-
-export async function getGlobalMonitoringSettings(): Promise<{
- statusCheckInterval: number;
- metricsInterval: number;
-}> {
- try {
- const response = await statsApi.get("/global-settings");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch global monitoring settings");
- }
-}
-
-export async function updateGlobalMonitoringSettings(settings: {
- statusCheckInterval?: number;
- metricsInterval?: number;
-}): Promise<void> {
- try {
- await statsApi.post("/global-settings", settings);
- } catch (error) {
- handleApiError(error, "update global monitoring settings");
- }
-}
-
-// ============================================================================
-// LOG LEVEL SETTINGS
-// ============================================================================
-
-export async function getLogLevel(): Promise<{ level: string }> {
- try {
- const response = await authApi.get("/users/log-level");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch log level");
- }
-}
-
-export async function updateLogLevel(level: string): Promise<void> {
- try {
- await authApi.patch("/users/log-level", { level });
- } catch (error) {
- handleApiError(error, "update log level");
- }
-}
-
-// ============================================================================
-// SESSION TIMEOUT SETTINGS
-// ============================================================================
-
-export async function getSessionTimeout(): Promise<{ timeoutHours: number }> {
- try {
- const response = await authApi.get("/users/session-timeout");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch session timeout");
- }
-}
-
-export async function updateSessionTimeout(
- timeoutHours: number,
-): Promise<void> {
- try {
- await authApi.patch("/users/session-timeout", { timeoutHours });
- } catch (error) {
- handleApiError(error, "update session timeout");
- }
-}
-
-// ============================================================================
-// GUACAMOLE SETTINGS
-// ============================================================================
-
-export async function getGuacamoleSettings(): Promise<{
- enabled: boolean;
- url: string;
-}> {
- try {
- const response = await authApi.get("/users/guacamole-settings");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch guacamole settings");
- }
-}
-
-export async function updateGuacamoleSettings(settings: {
- enabled?: boolean;
- url?: string;
-}): Promise<void> {
- try {
- await authApi.patch("/users/guacamole-settings", settings);
- } catch (error) {
- handleApiError(error, "update guacamole settings");
- }
-}
-
-// ============================================================================
-// AUTHENTICATION
-// ============================================================================
-
-export async function registerUser(
- username: string,
- password: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/users/create", {
- username,
- password,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "register user");
- }
-}
-
-export async function loginUser(
- username: string,
- password: string,
- rememberMe: boolean = false,
-): Promise<AuthResponse> {
- try {
- const response = await authApi.post("/users/login", {
- username,
- password,
- rememberMe,
- });
-
- const isInIframe =
- typeof window !== "undefined" && window.self !== window.top;
-
- if (isInIframe && isElectron() && response.data.success) {
- try {
- window.parent.postMessage(
- {
- type: "AUTH_SUCCESS",
- source: "login_api",
- platform: "desktop",
- timestamp: Date.now(),
- },
- window.location.origin,
- );
- } catch (e) {
- console.error("[main-axios] Error posting message to parent:", e);
- }
- }
-
- if (response.data.token) {
- localStorage.setItem("jwt", response.data.token);
- }
-
- if (response.data.success && !response.data.requires_totp) {
- markUserAuthenticated();
- }
-
- return {
- success: response.data.success,
- is_admin: response.data.is_admin,
- username: response.data.username,
- requires_totp: response.data.requires_totp,
- temp_token: response.data.temp_token,
- rememberMe: response.data.rememberMe,
- is_oidc: response.data.is_oidc,
- totp_enabled: response.data.totp_enabled,
- data_unlocked: response.data.data_unlocked,
- };
- } catch (error) {
- throw handleApiError(error, "login user");
- }
-}
-
-export async function logoutUser(): Promise<{
- success: boolean;
- message: string;
-}> {
- try {
- const response = await authApi.post("/users/logout");
-
- clearTermixSessionStorage();
-
- if (isElectron()) {
- const electronAPI = (
- window as unknown as {
- electronAPI?: { clearSessionCookies?: () => Promise<void> };
- }
- ).electronAPI;
- electronAPI?.clearSessionCookies?.().catch(() => {});
- } else {
- const isSecure = window.location.protocol === "https:";
- const cookieString = isSecure
- ? "jwt=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; Secure; SameSite=Lax"
- : "jwt=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax";
- document.cookie = cookieString;
- }
-
- return response.data;
- } catch (error) {
- clearTermixSessionStorage();
-
- if (isElectron()) {
- const electronAPI = (
- window as unknown as {
- electronAPI?: { clearSessionCookies?: () => Promise<void> };
- }
- ).electronAPI;
- electronAPI?.clearSessionCookies?.().catch(() => {});
- } else {
- const isSecure = window.location.protocol === "https:";
- const cookieString = isSecure
- ? "jwt=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; Secure; SameSite=Lax"
- : "jwt=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax";
- document.cookie = cookieString;
- }
- handleApiError(error, "logout user");
- }
-}
-
-export async function getUserInfo(): Promise<UserInfo> {
- try {
- const response = await authApi.get("/users/me");
- markUserAuthenticated();
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch user info");
- }
-}
-
-export async function getCurrentToken(): Promise<string | null> {
- try {
- const response = await authApi.get("/users/me/token");
- return response.data?.token ?? null;
- } catch {
- return null;
- }
-}
-
-export async function unlockUserData(
- password: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await authApi.post("/users/unlock-data", { password });
- return response.data;
- } catch (error) {
- handleApiError(error, "unlock user data");
- }
-}
-
-export async function getRegistrationAllowed(): Promise<{ allowed: boolean }> {
- try {
- const response = await authApi.get("/users/registration-allowed");
- return response.data;
- } catch (error) {
- handleApiError(error, "check registration status");
- }
-}
-
-export async function getPasswordLoginAllowed(): Promise<{ allowed: boolean }> {
- try {
- const response = await authApi.get("/users/password-login-allowed");
- return response.data;
- } catch (error) {
- handleApiError(error, "check password login status");
- }
-}
-
-export async function getOIDCConfig(): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/users/oidc-config");
- return response.data;
- } catch (error: unknown) {
- console.warn(
- "Failed to fetch OIDC config:",
- error.response?.data?.error || error.message,
- );
- return null;
- }
-}
-
-export async function getAdminOIDCConfig(): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/users/oidc-config/admin");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch admin OIDC config");
- }
-}
-
-export async function getSetupRequired(): Promise<{ setup_required: boolean }> {
- try {
- const response = await authApi.get("/users/setup-required");
- return response.data;
- } catch (error) {
- handleApiError(error, "check setup status");
- }
-}
-
-export async function getUserCount(): Promise<UserCount> {
- try {
- const response = await authApi.get("/users/count");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch user count");
- }
-}
-
-export async function initiatePasswordReset(
- username: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/users/initiate-reset", { username });
- return response.data;
- } catch (error) {
- handleApiError(error, "initiate password reset");
- }
-}
-
-export async function verifyPasswordResetCode(
- username: string,
- resetCode: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/users/verify-reset-code", {
- username,
- resetCode,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "verify reset code");
- }
-}
-
-export async function completePasswordReset(
- username: string,
- tempToken: string,
- newPassword: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/users/complete-reset", {
- username,
- tempToken,
- newPassword,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "complete password reset");
- }
-}
-
-export async function changePassword(oldPassword: string, newPassword: string) {
- try {
- const response = await authApi.post("/users/change-password", {
- oldPassword,
- newPassword,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "change password");
- }
-}
-
-export async function getOIDCAuthorizeUrl(
- rememberMe = false,
- desktopCallbackPort?: number,
-): Promise<OIDCAuthorize> {
- try {
- const response = await authApi.get("/users/oidc/authorize", {
- params: { rememberMe, desktopCallbackPort },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "get OIDC authorize URL");
- }
-}
-
-// ============================================================================
-// USER MANAGEMENT
-// ============================================================================
-
-export async function getUserList(): Promise<{ users: UserInfo[] }> {
- try {
- const response = await authApi.get("/users/list");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch user list");
- }
-}
-
-export async function getSessions(): Promise<{
- sessions: {
- id: string;
- userId: string;
- username?: string;
- deviceType: string;
- deviceInfo: string;
- createdAt: string;
- expiresAt: string;
- lastActiveAt: string;
- isRevoked?: boolean;
- isCurrentSession?: boolean;
- }[];
-}> {
- try {
- const response = await authApi.get("/users/sessions");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch sessions");
- }
-}
-
-export async function revokeSession(
- sessionId: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await authApi.delete(`/users/sessions/${sessionId}`);
- return response.data;
- } catch (error) {
- handleApiError(error, "revoke session");
- }
-}
-
-export async function revokeAllUserSessions(
- userId: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await authApi.post("/users/sessions/revoke-all", {
- targetUserId: userId,
- exceptCurrent: false,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "revoke all user sessions");
- }
-}
-
-export interface ApiKey {
- id: string;
- name: string;
- userId: string;
- username: string | null;
- tokenPrefix: string;
- createdAt: string;
- expiresAt: string | null;
- lastUsedAt: string | null;
- isActive: boolean;
-}
-
-export interface CreatedApiKey extends ApiKey {
- token: string;
-}
-
-export async function createApiKey(
- name: string,
- userId: string,
- expiresAt?: string,
-): Promise<CreatedApiKey> {
- try {
- const response = await authApi.post("/users/api-keys", {
- name,
- userId,
- expiresAt: expiresAt ?? null,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "create API key");
- }
-}
-
-export async function getApiKeys(): Promise<{ apiKeys: ApiKey[] }> {
- try {
- const response = await authApi.get("/users/api-keys");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch API keys");
- }
-}
-
-export async function deleteApiKey(
- keyId: string,
-): Promise<{ success: boolean }> {
- try {
- const response = await authApi.delete(`/users/api-keys/${keyId}`);
- return response.data;
- } catch (error) {
- handleApiError(error, "delete API key");
- }
-}
-
-export async function makeUserAdmin(
- userId: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/users/make-admin", { userId });
- return response.data;
- } catch (error) {
- handleApiError(error, "make user admin");
- }
-}
-
-export async function removeAdminStatus(
- userId: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/users/remove-admin", { userId });
- return response.data;
- } catch (error) {
- handleApiError(error, "remove admin status");
- }
-}
-
-export async function deleteUser(
- username: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.delete("/users/delete-user", {
- data: { username },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "delete user");
- }
-}
-
-export async function deleteAccount(
- password: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.delete("/users/delete-account", {
- data: { password },
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "delete account");
- }
-}
-
-export async function updateRegistrationAllowed(
- allowed: boolean,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.patch("/users/registration-allowed", {
- allowed,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "update registration allowed");
- }
-}
-
-export async function getOidcAutoProvision(): Promise<{ enabled: boolean }> {
- try {
- const response = await authApi.get("/users/oidc-auto-provision");
- return response.data;
- } catch (error) {
- handleApiError(error, "check OIDC auto-provision status");
- }
-}
-
-export async function updateOidcAutoProvision(
- enabled: boolean,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.patch("/users/oidc-auto-provision", {
- enabled,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "update OIDC auto-provision");
- }
-}
-
-export async function updatePasswordLoginAllowed(
- allowed: boolean,
-): Promise<{ allowed: boolean }> {
- try {
- const response = await authApi.patch("/users/password-login-allowed", {
- allowed,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "update password login allowed");
- }
-}
-
-export async function getPasswordResetAllowed(): Promise<boolean> {
- try {
- const response = await authApi.get("/users/password-reset-allowed");
- return response.data.allowed;
- } catch (error) {
- handleApiError(error, "get password reset allowed");
- }
-}
-
-export async function updatePasswordResetAllowed(
- allowed: boolean,
-): Promise<{ allowed: boolean }> {
- try {
- const response = await authApi.patch("/users/password-reset-allowed", {
- allowed,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "update password reset allowed");
- }
-}
-
-export async function updateOIDCConfig(
- config: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/users/oidc-config", config);
- return response.data;
- } catch (error) {
- handleApiError(error, "update OIDC config");
- }
-}
-
-export async function disableOIDCConfig(): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.delete("/users/oidc-config");
- return response.data;
- } catch (error) {
- handleApiError(error, "disable OIDC config");
- }
-}
-
-// ============================================================================
-// ALERTS
-// ============================================================================
-
-export async function setupTOTP(): Promise<{
- secret: string;
- qr_code: string;
-}> {
- try {
- const response = await authApi.post("/users/totp/setup");
- return response.data;
- } catch (error) {
- handleApiError(error as AxiosError, "setup TOTP");
- throw error;
- }
-}
-
-export async function enableTOTP(
- totp_code: string,
-): Promise<{ message: string; backup_codes: string[] }> {
- try {
- const response = await authApi.post("/users/totp/enable", { totp_code });
- return response.data;
- } catch (error) {
- handleApiError(error as AxiosError, "enable TOTP");
- throw error;
- }
-}
-
-export async function disableTOTP(
- password?: string,
- totp_code?: string,
-): Promise<{ message: string }> {
- try {
- const response = await authApi.post("/users/totp/disable", {
- password,
- totp_code,
- });
- return response.data;
- } catch (error) {
- handleApiError(error as AxiosError, "disable TOTP");
- throw error;
- }
-}
-
-export async function verifyTOTPLogin(
- temp_token: string,
- totp_code: string,
- rememberMe: boolean = false,
-): Promise<AuthResponse> {
- try {
- const response = await authApi.post("/users/totp/verify-login", {
- temp_token,
- totp_code,
- rememberMe,
- });
-
- const isInIframe =
- typeof window !== "undefined" && window.self !== window.top;
-
- if (isInIframe && isElectron() && response.data.success) {
- try {
- window.parent.postMessage(
- {
- type: "AUTH_SUCCESS",
- source: "totp_verify",
- platform: "desktop",
- timestamp: Date.now(),
- },
- window.location.origin,
- );
- } catch (e) {
- console.error("[main-axios] Error posting message to parent:", e);
- }
- }
-
- if (response.data.success) {
- markUserAuthenticated();
- }
-
- return response.data;
- } catch (error) {
- handleApiError(error as AxiosError, "verify TOTP login");
- throw error;
- }
-}
-
-export async function generateBackupCodes(
- password?: string,
- totp_code?: string,
-): Promise<{ backup_codes: string[] }> {
- try {
- const response = await authApi.post("/users/totp/backup-codes", {
- password,
- totp_code,
- });
- return response.data;
- } catch (error) {
- handleApiError(error as AxiosError, "generate backup codes");
- throw error;
- }
-}
-
-export async function getUserAlerts(): Promise<{
- alerts: Array<Record<string, unknown>>;
-}> {
- try {
- const response = await authApi.get(`/alerts`);
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch user alerts");
- throw error;
- }
-}
-
-export async function dismissAlert(
- alertId: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/alerts/dismiss", { alertId });
- return response.data;
- } catch (error) {
- handleApiError(error, "dismiss alert");
- throw error;
- }
-}
-
-// ============================================================================
-// UPDATES & RELEASES
-// ============================================================================
-
-export async function getReleasesRSS(
- perPage: number = 100,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get(`/releases/rss?per_page=${perPage}`);
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch releases RSS");
- }
-}
-
-export async function getVersionInfo(
- checkRemote = true,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get(
- `/version${checkRemote ? "" : "?checkRemote=false"}`,
- );
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch version info");
- }
-}
-
-// ============================================================================
-// DATABASE HEALTH
-// ============================================================================
-
-export async function getDatabaseHealth(): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/health");
- return response.data;
- } catch (error) {
- handleApiError(error, "check database health");
- }
-}
-
-// ============================================================================
-// SSH CREDENTIALS MANAGEMENT
-// ============================================================================
-
-export async function getCredentials(): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/credentials");
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch credentials");
- }
-}
-
-export async function getCredentialDetails(
- credentialId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get(`/credentials/${credentialId}`);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch credential details");
- }
-}
-
-export async function createCredential(
- credentialData: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/credentials", credentialData);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "create credential");
- }
-}
-
-export async function updateCredential(
- credentialId: number,
- credentialData: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.put(
- `/credentials/${credentialId}`,
- credentialData,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "update credential");
- }
-}
-
-export async function deleteCredential(
- credentialId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.delete(`/credentials/${credentialId}`);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "delete credential");
- }
-}
-
-export async function getCredentialHosts(
- credentialId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get(`/credentials/${credentialId}/hosts`);
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch credential hosts");
- }
-}
-
-export async function getCredentialFolders(): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/credentials/folders");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch credential folders");
- }
-}
-
-export async function getSSHHostWithCredentials(
- hostId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await sshHostApi.get(
- `/db/host/${hostId}/with-credentials`,
- );
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch SSH host with credentials");
- }
-}
-
-export async function getHostPassword(
- hostId: number,
- field: "password" | "sudoPassword" = "password",
-): Promise<string | null> {
- try {
- const response = await sshHostApi.get(
- `/db/host/${hostId}/password?field=${field}`,
- );
- return response.data?.value || null;
- } catch {
- return null;
- }
-}
-
-export async function applyCredentialToHost(
- hostId: number,
- credentialId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await sshHostApi.post(
- `/db/host/${hostId}/apply-credential`,
- { credentialId },
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "apply credential to host");
- }
-}
-
-export async function removeCredentialFromHost(
- hostId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await sshHostApi.delete(`/db/host/${hostId}/credential`);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "remove credential from host");
- }
-}
-
-export async function migrateHostToCredential(
- hostId: number,
- credentialName: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await sshHostApi.post(
- `/db/host/${hostId}/migrate-to-credential`,
- { credentialName },
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "migrate host to credential");
- }
-}
-
-// ============================================================================
-// SSH FOLDER MANAGEMENT
-// ============================================================================
-
-export async function getFoldersWithStats(): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/host/db/folders/with-stats");
- return response.data;
- } catch (error) {
- handleApiError(error, "fetch folders with statistics");
- }
-}
-
-export async function renameFolder(
- oldName: string,
- newName: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.put("/host/folders/rename", {
- oldName,
- newName,
- });
- return response.data;
- } catch (error) {
- handleApiError(error, "rename folder");
- }
-}
-
-export async function getSSHFolders(): Promise<SSHFolder[]> {
- try {
- sshLogger.info("Fetching SSH folders", {
- operation: "fetch_ssh_folders",
- });
-
- const response = await authApi.get("/host/folders");
-
- sshLogger.success("SSH folders fetched successfully", {
- operation: "fetch_ssh_folders",
- count: response.data.length,
- });
-
- return response.data;
- } catch (error) {
- sshLogger.error("Failed to fetch SSH folders", error, {
- operation: "fetch_ssh_folders",
- });
- handleApiError(error, "fetch SSH folders");
- throw error;
- }
-}
-
-export async function updateFolderMetadata(
- name: string,
- color?: string,
- icon?: string,
-): Promise<void> {
- try {
- sshLogger.info("Updating folder metadata", {
- operation: "update_folder_metadata",
- name,
- color,
- icon,
- });
-
- await authApi.put("/host/folders/metadata", {
- name,
- color,
- icon,
- });
-
- sshLogger.success("Folder metadata updated successfully", {
- operation: "update_folder_metadata",
- name,
- });
- } catch (error) {
- sshLogger.error("Failed to update folder metadata", error, {
- operation: "update_folder_metadata",
- name,
- });
- handleApiError(error, "update folder metadata");
- throw error;
- }
-}
-
-export async function deleteAllHostsInFolder(
- folderName: string,
-): Promise<{ deletedCount: number }> {
- try {
- sshLogger.info("Deleting all hosts in folder", {
- operation: "delete_folder_hosts",
- folderName,
- });
-
- const response = await authApi.delete(
- `/host/folders/${encodeURIComponent(folderName)}/hosts`,
- );
-
- sshLogger.success("All hosts in folder deleted successfully", {
- operation: "delete_folder_hosts",
- folderName,
- deletedCount: response.data.deletedCount,
- });
-
- return response.data;
- } catch (error) {
- sshLogger.error("Failed to delete hosts in folder", error, {
- operation: "delete_folder_hosts",
- folderName,
- });
- handleApiError(error, "delete hosts in folder");
- throw error;
- }
-}
-
-export async function renameCredentialFolder(
- oldName: string,
- newName: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.put("/credentials/folders/rename", {
- oldName,
- newName,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "rename credential folder");
- }
-}
-
-export async function detectKeyType(
- privateKey: string,
- keyPassword?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/credentials/detect-key-type", {
- privateKey,
- keyPassword,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "detect key type");
- }
-}
-
-export async function detectPublicKeyType(
- publicKey: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/credentials/detect-public-key-type", {
- publicKey,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "detect public key type");
- }
-}
-
-export async function validateKeyPair(
- privateKey: string,
- publicKey: string,
- keyPassword?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/credentials/validate-key-pair", {
- privateKey,
- publicKey,
- keyPassword,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "validate key pair");
- }
-}
-
-export async function generatePublicKeyFromPrivate(
- privateKey: string,
- keyPassword?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/credentials/generate-public-key", {
- privateKey,
- keyPassword,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "generate public key from private key");
- }
-}
-
-export async function generateKeyPair(
- keyType: "ssh-ed25519" | "ssh-rsa" | "ecdsa-sha2-nistp256",
- keySize?: number,
- passphrase?: string,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/credentials/generate-key-pair", {
- keyType,
- keySize,
- passphrase,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "generate SSH key pair");
- }
-}
-
-export async function deployCredentialToHost(
- credentialId: number,
- targetHostId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post(
- `/credentials/${credentialId}/deploy-to-host`,
- { targetHostId },
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "deploy credential to host");
- }
-}
-
-// ============================================================================
-// SNIPPETS API
-// ============================================================================
-
-export async function getSnippets(): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/snippets");
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch snippets");
- }
-}
-
-export async function createSnippet(
- snippetData: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/snippets", snippetData);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "create snippet");
- }
-}
-
-export async function updateSnippet(
- snippetId: number,
- snippetData: Record<string, unknown>,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.put(`/snippets/${snippetId}`, snippetData);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "update snippet");
- }
-}
-
-export async function deleteSnippet(
- snippetId: number,
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.delete(`/snippets/${snippetId}`);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "delete snippet");
- }
-}
-
-export async function executeSnippet(
- snippetId: number,
- hostId: number,
-): Promise<{ success: boolean; output: string; error?: string }> {
- try {
- const response = await authApi.post("/snippets/execute", {
- snippetId,
- hostId,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "execute snippet");
- }
-}
-
-// ============================================================================
-// MISCELLANEOUS API CALLS
-// ============================================================================
-
-export interface NetworkTopologyNode {
- data: {
- id: string;
- label?: string;
- ip?: string;
- status?: string;
- tags?: string[];
- parent?: string;
- color?: string;
- };
- position?: { x: number; y: number };
-}
-
-export interface NetworkTopologyEdge {
- data: {
- id?: string;
- source: string;
- target: string;
- };
-}
-
-export interface NetworkTopologyData {
- nodes: NetworkTopologyNode[];
- edges: NetworkTopologyEdge[];
-}
-
-export async function getNetworkTopology(): Promise<NetworkTopologyData | null> {
- try {
- const response = await authApi.get("/network-topology/");
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch network topology");
- }
-}
-
-export async function saveNetworkTopology(
- topology: NetworkTopologyData,
-): Promise<{ success: boolean }> {
- try {
- const response = await authApi.post("/network-topology/", { topology });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "save network topology");
- }
-}
-
-export async function getSnippetFolders(): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.get("/snippets/folders");
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch snippet folders");
- }
-}
-
-export async function createSnippetFolder(folderData: {
- name: string;
- color?: string;
- icon?: string;
-}): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.post("/snippets/folders", folderData);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "create snippet folder");
- }
-}
-
-export async function updateSnippetFolderMetadata(
- folderName: string,
- metadata: { color?: string; icon?: string },
-): Promise<Record<string, unknown>> {
- try {
- const response = await authApi.put(
- `/snippets/folders/${encodeURIComponent(folderName)}/metadata`,
- metadata,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "update snippet folder metadata");
- }
-}
-
-export async function renameSnippetFolder(
- oldName: string,
- newName: string,
-): Promise<{ success: boolean; oldName: string; newName: string }> {
- try {
- const response = await authApi.put("/snippets/folders/rename", {
- oldName,
- newName,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "rename snippet folder");
- }
-}
-
-export async function deleteSnippetFolder(
- folderName: string,
-): Promise<{ success: boolean }> {
- try {
- const response = await authApi.delete(
- `/snippets/folders/${encodeURIComponent(folderName)}`,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "delete snippet folder");
- }
-}
-
-export async function reorderSnippets(
- updates: Array<{ id: number; order: number; folder?: string }>,
-): Promise<{ success: boolean }> {
- try {
- const response = await authApi.put("/snippets/reorder", {
- snippets: updates,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "reorder snippets");
- }
-}
-
-// ============================================================================
-// DASHBOARD API
-// ============================================================================
-
-export interface UptimeInfo {
- uptimeMs: number;
- uptimeSeconds: number;
- formatted: string;
-}
-
-export interface RecentActivityItem {
- id: number;
- userId: string;
- type:
- | "terminal"
- | "file_manager"
- | "server_stats"
- | "tunnel"
- | "docker"
- | "telnet"
- | "vnc"
- | "rdp";
- hostId: number;
- hostName: string;
- timestamp: string;
-}
-
-export async function getUptime(): Promise<UptimeInfo> {
- try {
- const response = await dashboardApi.get("/uptime");
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch uptime");
- }
-}
-
-export async function getRecentActivity(
- limit?: number,
-): Promise<RecentActivityItem[]> {
- try {
- const response = await dashboardApi.get("/activity/recent", {
- params: { limit },
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch recent activity");
- }
-}
-
-export async function logActivity(
- type:
- | "terminal"
- | "file_manager"
- | "server_stats"
- | "tunnel"
- | "docker"
- | "rdp"
- | "vnc"
- | "telnet",
- hostId: number,
- hostName: string,
-): Promise<{ message: string; id: number | string }> {
- try {
- const response = await dashboardApi.post("/activity/log", {
- type,
- hostId,
- hostName,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "log activity");
- }
-}
-
-export async function resetRecentActivity(): Promise<{ message: string }> {
- try {
- const response = await dashboardApi.delete("/activity/reset");
- return response.data;
- } catch (error) {
- throw handleApiError(error, "reset recent activity");
- }
-}
-
-// ============================================================================
-// COMMAND HISTORY API
-// ============================================================================
-
-export async function saveCommandToHistory(
- hostId: number,
- command: string,
-): Promise<{ id: number; command: string; executedAt: string }> {
- try {
- const response = await authApi.post("/terminal/command_history", {
- hostId,
- command,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "save command to history");
- }
-}
-
-export async function getCommandHistory(
- hostId: number,
- limit: number = 100,
-): Promise<string[]> {
- try {
- const response = await authApi.get(`/terminal/command_history/${hostId}`, {
- params: { limit },
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch command history");
- }
-}
-
-export async function deleteCommandFromHistory(
- hostId: number,
- command: string,
-): Promise<{ success: boolean }> {
- try {
- const response = await authApi.post("/terminal/command_history/delete", {
- hostId,
- command,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "delete command from history");
- }
-}
-
-export async function clearCommandHistory(
- hostId: number,
-): Promise<{ success: boolean }> {
- try {
- const response = await authApi.delete(
- `/terminal/command_history/${hostId}`,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "clear command history");
- }
-}
-
-// ============================================================================
-// OIDC ACCOUNT LINKING
-// ============================================================================
-
-export async function linkOIDCToPasswordAccount(
- oidcUserId: string,
- targetUsername: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await authApi.post("/users/link-oidc-to-password", {
- oidcUserId,
- targetUsername,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "link OIDC account to password account");
- }
-}
-
-export async function unlinkOIDCFromPasswordAccount(
- userId: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await authApi.post("/users/unlink-oidc-from-password", {
- userId,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "unlink OIDC from password account");
- }
-}
-
-export interface GuacamoleTokenRequest {
- protocol: "rdp" | "vnc" | "telnet";
- hostname: string;
- port?: number;
- username?: string;
- password?: string;
- domain?: string;
- security?: string;
- ignoreCert?: boolean;
- guacamoleConfig?: {
- colorDepth?: number;
- width?: number;
- height?: number;
- dpi?: number;
- resizeMethod?: string;
- forceLossless?: boolean;
- disableAudio?: boolean;
- enableAudioInput?: boolean;
- enableWallpaper?: boolean;
- enableTheming?: boolean;
- enableFontSmoothing?: boolean;
- enableFullWindowDrag?: boolean;
- enableDesktopComposition?: boolean;
- enableMenuAnimations?: boolean;
- disableBitmapCaching?: boolean;
- disableOffscreenCaching?: boolean;
- disableGlyphCaching?: boolean;
- disableGfx?: boolean;
- enablePrinting?: boolean;
- printerName?: string;
- enableDrive?: boolean;
- driveName?: string;
- drivePath?: string;
- createDrivePath?: boolean;
- disableDownload?: boolean;
- disableUpload?: boolean;
- enableTouch?: boolean;
- clientName?: string;
- console?: boolean;
- initialProgram?: string;
- serverLayout?: string;
- timezone?: string;
- gatewayHostname?: string;
- gatewayPort?: number;
- gatewayUsername?: string;
- gatewayPassword?: string;
- gatewayDomain?: string;
- remoteApp?: string;
- remoteAppDir?: string;
- remoteAppArgs?: string;
- normalizeClipboard?: string;
- disableCopy?: boolean;
- disablePaste?: boolean;
- cursor?: string;
- swapRedBlue?: boolean;
- readOnly?: boolean;
- recordingPath?: string;
- recordingName?: string;
- createRecordingPath?: boolean;
- recordingExcludeOutput?: boolean;
- recordingExcludeMouse?: boolean;
- recordingIncludeKeys?: boolean;
- wolSendPacket?: boolean;
- wolMacAddr?: string;
- wolBroadcastAddr?: string;
- wolUdpPort?: number;
- wolWaitTime?: number;
- };
-}
-
-export interface GuacamoleTokenResponse {
- token: string;
-}
-
-type GuacamoleConfigSource = {
- guacamoleConfig?: string | Record<string, unknown> | null;
-};
-
-export function getGuacamoleDpi(
- source?: GuacamoleConfigSource,
-): number | undefined {
- const config = source?.guacamoleConfig;
- if (!config) return undefined;
-
- let dpi: unknown;
- if (typeof config === "string") {
- try {
- dpi = JSON.parse(config).dpi;
- } catch {
- return undefined;
- }
- } else {
- dpi = config.dpi;
- }
-
- const parsedDpi = typeof dpi === "string" ? Number(dpi) : dpi;
- if (
- typeof parsedDpi !== "number" ||
- !Number.isFinite(parsedDpi) ||
- parsedDpi <= 0
- ) {
- return undefined;
- }
-
- return Math.trunc(parsedDpi);
-}
-
-function toGuacamoleParams(
- config: GuacamoleTokenRequest["guacamoleConfig"],
-): Record<string, unknown> {
- if (!config) return {};
-
- const params: Record<string, unknown> = {};
-
- const mappings: Record<string, string> = {
- colorDepth: "color-depth",
- resizeMethod: "resize-method",
- forceLossless: "force-lossless",
- disableAudio: "disable-audio",
- enableAudioInput: "enable-audio-input",
- enableWallpaper: "enable-wallpaper",
- enableTheming: "enable-theming",
- enableFontSmoothing: "enable-font-smoothing",
- enableFullWindowDrag: "enable-full-window-drag",
- enableDesktopComposition: "enable-desktop-composition",
- enableMenuAnimations: "enable-menu-animations",
- disableBitmapCaching: "disable-bitmap-caching",
- disableOffscreenCaching: "disable-offscreen-caching",
- disableGlyphCaching: "disable-glyph-caching",
- disableGfx: "disable-gfx",
- enablePrinting: "enable-printing",
- printerName: "printer-name",
- enableDrive: "enable-drive",
- driveName: "drive-name",
- drivePath: "drive-path",
- createDrivePath: "create-drive-path",
- disableDownload: "disable-download",
- disableUpload: "disable-upload",
- enableTouch: "enable-touch",
- clientName: "client-name",
- initialProgram: "initial-program",
- serverLayout: "server-layout",
- gatewayHostname: "gateway-hostname",
- gatewayPort: "gateway-port",
- gatewayUsername: "gateway-username",
- gatewayPassword: "gateway-password",
- gatewayDomain: "gateway-domain",
- remoteApp: "remote-app",
- remoteAppDir: "remote-app-dir",
- remoteAppArgs: "remote-app-args",
- normalizeClipboard: "normalize-clipboard",
- disableCopy: "disable-copy",
- disablePaste: "disable-paste",
- swapRedBlue: "swap-red-blue",
- readOnly: "read-only",
- recordingPath: "recording-path",
- recordingName: "recording-name",
- createRecordingPath: "create-recording-path",
- recordingExcludeOutput: "recording-exclude-output",
- recordingExcludeMouse: "recording-exclude-mouse",
- recordingIncludeKeys: "recording-include-keys",
- wolSendPacket: "wol-send-packet",
- wolMacAddr: "wol-mac-addr",
- wolBroadcastAddr: "wol-broadcast-addr",
- wolUdpPort: "wol-udp-port",
- wolWaitTime: "wol-wait-time",
- };
-
- for (const [key, value] of Object.entries(config)) {
- if (value !== undefined && value !== null && value !== "") {
- const paramName = mappings[key] || key;
- if (typeof value === "boolean") {
- params[paramName] = value ? "true" : "false";
- } else {
- params[paramName] = value;
- }
- }
- }
-
- return params;
-}
-
-export async function getGuacamoleToken(
- request: GuacamoleTokenRequest,
-): Promise<GuacamoleTokenResponse> {
- try {
- const guacParams = toGuacamoleParams(request.guacamoleConfig);
-
- const response = await authApi.post("/guacamole/token", {
- type: request.protocol,
- hostname: request.hostname,
- port: request.port,
- username: request.username,
- password: request.password,
- domain: request.domain,
- security: request.security,
- "ignore-cert": request.ignoreCert,
- ...guacParams,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "get guacamole token");
- }
-}
-
-export async function getGuacamoleTokenFromHost(
- hostId: number,
- protocol?: "rdp" | "vnc" | "telnet",
-): Promise<GuacamoleTokenResponse> {
- try {
- const response = await authApi.post(
- `/guacamole/connect-host/${hostId}`,
- protocol ? { protocol } : {},
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "get guacamole token from host");
- }
-}
-
-export async function getGuacdStatus(): Promise<{
- guacd: { status: string };
-}> {
- const response = await authApi.get("/guacamole/status");
- return response.data;
-}
-
-// ============================================================================
-// RBAC MANAGEMENT
-// ============================================================================
-
-export async function getRoles(): Promise<{ roles: Role[] }> {
- try {
- const response = await rbacApi.get("/rbac/roles");
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch roles");
- }
-}
-
-export async function createRole(roleData: {
- name: string;
- displayName: string;
- description?: string | null;
-}): Promise<{ role: Role }> {
- try {
- const response = await rbacApi.post("/rbac/roles", roleData);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "create role");
- }
-}
-
-export async function updateRole(
- roleId: number,
- roleData: {
- displayName?: string;
- description?: string | null;
- },
-): Promise<{ role: Role }> {
- try {
- const response = await rbacApi.put(`/rbac/roles/${roleId}`, roleData);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "update role");
- }
-}
-
-export async function deleteRole(
- roleId: number,
-): Promise<{ success: boolean }> {
- try {
- const response = await rbacApi.delete(`/rbac/roles/${roleId}`);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "delete role");
- }
-}
-
-export async function getUserRoles(
- userId: string,
-): Promise<{ roles: UserRole[] }> {
- try {
- const response = await rbacApi.get(`/rbac/users/${userId}/roles`);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch user roles");
- }
-}
-
-export async function assignRoleToUser(
- userId: string,
- roleId: number,
-): Promise<{ success: boolean }> {
- try {
- const response = await rbacApi.post(`/rbac/users/${userId}/roles`, {
- roleId,
- });
- return response.data;
- } catch (error) {
- throw handleApiError(error, "assign role to user");
- }
-}
-
-export async function removeRoleFromUser(
- userId: string,
- roleId: number,
-): Promise<{ success: boolean }> {
- try {
- const response = await rbacApi.delete(
- `/rbac/users/${userId}/roles/${roleId}`,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "remove role from user");
- }
-}
-
-export async function shareHost(
- hostId: number,
- shareData: {
- targetType: "user" | "role";
- targetUserId?: string;
- targetRoleId?: number;
- permissionLevel: "view";
- durationHours?: number;
- },
-): Promise<{ success: boolean }> {
- try {
- const response = await rbacApi.post(
- `/rbac/host/${hostId}/share`,
- shareData,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "share host");
- }
-}
-
-export async function getHostAccess(
- hostId: number,
-): Promise<{ accessList: AccessRecord[] }> {
- try {
- const response = await rbacApi.get(`/rbac/host/${hostId}/access`);
+ const response = await authApi.get("/users/password-login-allowed");
return response.data;
} catch (error) {
- throw handleApiError(error, "fetch host access");
+ handleApiError(error, "check password login status");
}
}
-export async function revokeHostAccess(
- hostId: number,
- accessId: number,
-): Promise<{ success: boolean }> {
+export async function getOIDCConfig(): Promise<Record<string, unknown>> {
try {
- const response = await rbacApi.delete(
- `/rbac/host/${hostId}/access/${accessId}`,
- );
+ const response = await authApi.get("/users/oidc-config");
return response.data;
- } catch (error) {
- throw handleApiError(error, "revoke host access");
- }
-}
-
-// ============================================================================
-// SNIPPET SHARING
-// ============================================================================
-
-export async function shareSnippet(
- snippetId: number,
- shareData: {
- targetType: "user" | "role";
- targetUserId?: string;
- targetRoleId?: number;
- durationHours?: number;
- },
-): Promise<{ success: boolean }> {
- try {
- const response = await rbacApi.post(
- `/rbac/snippet/${snippetId}/share`,
- shareData,
+ } catch (error: unknown) {
+ console.warn(
+ "Failed to fetch OIDC config:",
+ error.response?.data?.error || error.message,
);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "share snippet");
- }
-}
-
-export async function getSnippetAccess(
- snippetId: number,
-): Promise<{ accessList: AccessRecord[] }> {
- try {
- const response = await rbacApi.get(`/rbac/snippet/${snippetId}/access`);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "fetch snippet access");
+ return null;
}
}
-export async function revokeSnippetAccess(
- snippetId: number,
- accessId: number,
-): Promise<{ success: boolean }> {
+export async function getAdminOIDCConfig(): Promise<Record<string, unknown>> {
try {
- const response = await rbacApi.delete(
- `/rbac/snippet/${snippetId}/access/${accessId}`,
- );
+ const response = await authApi.get("/users/oidc-config/admin");
return response.data;
} catch (error) {
- throw handleApiError(error, "revoke snippet access");
+ handleApiError(error, "fetch admin OIDC config");
}
}
-export async function getSharedSnippets(): Promise<{
- sharedSnippets: Array<{
- id: number;
- name: string;
- content: string;
- description: string | null;
- folder: string | null;
- ownerUsername: string;
- permissionLevel: string;
- expiresAt: string | null;
- }>;
-}> {
+export async function getSetupRequired(): Promise<{ setup_required: boolean }> {
try {
- const response = await rbacApi.get("/rbac/shared-snippets");
+ const response = await authApi.get("/users/setup-required");
return response.data;
} catch (error) {
- handleApiError(error, "fetch shared snippets");
- }
-}
-
-// ============================================================================
-// DOCKER MANAGEMENT API
-// ============================================================================
-
-export async function connectDockerSession(
- sessionId: string,
- hostId: number,
- config?: {
- userProvidedPassword?: string;
- userProvidedSshKey?: string;
- userProvidedKeyPassword?: string;
- forceKeyboardInteractive?: boolean;
- useSocks5?: boolean;
- socks5Host?: string;
- socks5Port?: number;
- socks5Username?: string;
- socks5Password?: string;
- socks5ProxyChain?: unknown;
- },
-): Promise<{
- success?: boolean;
- message?: string;
- requires_totp?: boolean;
- prompt?: string;
- isPassword?: boolean;
- status?: string;
- reason?: string;
- connectionLogs?: ApiConnectionLog[];
- requires_warpgate?: boolean;
- url?: string;
- securityKey?: string;
-}> {
- try {
- const response = await dockerApi.post("/ssh/connect", {
- sessionId,
- hostId,
- ...config,
- });
- return response.data;
- } catch (error: unknown) {
- if (
- axios.isAxiosError<ConnectErrorResponse>(error) &&
- error.response?.data?.status === "auth_required"
- ) {
- return error.response.data;
- }
- if (
- axios.isAxiosError<ConnectErrorResponse>(error) &&
- error.response?.data?.requires_totp
- ) {
- return error.response.data;
- }
- if (
- axios.isAxiosError<ConnectErrorResponse>(error) &&
- error.response?.data?.requires_warpgate
- ) {
- return error.response.data;
- }
- if (
- axios.isAxiosError<ConnectErrorResponse>(error) &&
- error.response?.data?.connectionLogs
- ) {
- const data = error.response.data;
- const errorWithLogs = new Error(
- data.error || data.message || error.message,
- );
- Object.assign(errorWithLogs, {
- connectionLogs: data.connectionLogs,
- });
- throw errorWithLogs;
- }
- throw handleApiError(error, "connect to Docker SSH session");
+ handleApiError(error, "check setup status");
}
}
-export async function verifyDockerTOTP(
- sessionId: string,
- totpCode: string,
-): Promise<{ status: string; message: string }> {
+export async function getUserCount(): Promise<UserCount> {
try {
- const response = await dockerApi.post("/ssh/connect-totp", {
- sessionId,
- totpCode,
- });
+ const response = await authApi.get("/users/count");
return response.data;
} catch (error) {
- throw handleApiError(error, "verify Docker TOTP");
+ handleApiError(error, "fetch user count");
}
}
-export async function verifyDockerWarpgate(
- sessionId: string,
-): Promise<{ status: string; message: string }> {
+export async function initiatePasswordReset(
+ username: string,
+): Promise<Record<string, unknown>> {
try {
- const response = await dockerApi.post("/ssh/connect-warpgate", {
- sessionId,
- });
+ const response = await authApi.post("/users/initiate-reset", { username });
return response.data;
} catch (error) {
- throw handleApiError(error, "verify Docker Warpgate");
+ handleApiError(error, "initiate password reset");
}
}
-export async function disconnectDockerSession(
- sessionId: string,
-): Promise<{ success: boolean; message: string }> {
+export async function verifyPasswordResetCode(
+ username: string,
+ resetCode: string,
+): Promise<Record<string, unknown>> {
try {
- const response = await dockerApi.post("/ssh/disconnect", {
- sessionId,
+ const response = await authApi.post("/users/verify-reset-code", {
+ username,
+ resetCode,
});
return response.data;
} catch (error) {
- throw handleApiError(error, "disconnect from Docker SSH session");
+ handleApiError(error, "verify reset code");
}
}
-export async function keepaliveDockerSession(
- sessionId: string,
-): Promise<{ success: boolean }> {
+export async function completePasswordReset(
+ username: string,
+ tempToken: string,
+ newPassword: string,
+): Promise<Record<string, unknown>> {
try {
- const response = await dockerApi.post("/ssh/keepalive", {
- sessionId,
+ const response = await authApi.post("/users/complete-reset", {
+ username,
+ tempToken,
+ newPassword,
});
return response.data;
} catch (error) {
- throw handleApiError(error, "keepalive Docker SSH session");
+ handleApiError(error, "complete password reset");
}
}
-export async function getDockerSessionStatus(
- sessionId: string,
-): Promise<{ success: boolean; connected: boolean }> {
+export async function changePassword(oldPassword: string, newPassword: string) {
try {
- const response = await dockerApi.get("/ssh/status", {
- params: { sessionId },
+ const response = await authApi.post("/users/change-password", {
+ oldPassword,
+ newPassword,
});
return response.data;
} catch (error) {
- throw handleApiError(error, "get Docker session status");
- }
-}
-
-export async function validateDockerAvailability(
- sessionId: string,
-): Promise<DockerValidation> {
- try {
- const response = await dockerApi.get(`/validate/${sessionId}`);
- return response.data;
- } catch (error) {
- throw handleApiError(error, "validate Docker availability");
+ handleApiError(error, "change password");
}
}
-export async function listDockerContainers(
- sessionId: string,
- all: boolean = true,
-): Promise<DockerContainer[]> {
+export async function getOIDCAuthorizeUrl(
+ rememberMe = false,
+ desktopCallbackPort?: number,
+): Promise<OIDCAuthorize> {
try {
- const response = await dockerApi.get(`/containers/${sessionId}`, {
- params: { all },
+ const response = await authApi.get("/users/oidc/authorize", {
+ params: { rememberMe, desktopCallbackPort },
});
return response.data;
} catch (error) {
- throw handleApiError(error, "list Docker containers");
- }
-}
-
-export async function getDockerContainerDetails(
- sessionId: string,
- containerId: string,
-): Promise<DockerContainer> {
- try {
- const response = await dockerApi.get(
- `/containers/${sessionId}/${containerId}`,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "get Docker container details");
- }
-}
-
-export async function startDockerContainer(
- sessionId: string,
- containerId: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await dockerApi.post(
- `/containers/${sessionId}/${containerId}/start`,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "start Docker container");
- }
-}
-
-export async function stopDockerContainer(
- sessionId: string,
- containerId: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await dockerApi.post(
- `/containers/${sessionId}/${containerId}/stop`,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "stop Docker container");
- }
-}
-
-export async function restartDockerContainer(
- sessionId: string,
- containerId: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await dockerApi.post(
- `/containers/${sessionId}/${containerId}/restart`,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "restart Docker container");
- }
-}
-
-export async function pauseDockerContainer(
- sessionId: string,
- containerId: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await dockerApi.post(
- `/containers/${sessionId}/${containerId}/pause`,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "pause Docker container");
- }
-}
-
-export async function unpauseDockerContainer(
- sessionId: string,
- containerId: string,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await dockerApi.post(
- `/containers/${sessionId}/${containerId}/unpause`,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "unpause Docker container");
- }
-}
-
-export async function removeDockerContainer(
- sessionId: string,
- containerId: string,
- force: boolean = false,
-): Promise<{ success: boolean; message: string }> {
- try {
- const response = await dockerApi.delete(
- `/containers/${sessionId}/${containerId}/remove`,
- {
- params: { force },
- },
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "remove Docker container");
- }
-}
-
-export async function getContainerLogs(
- sessionId: string,
- containerId: string,
- options?: DockerLogOptions,
-): Promise<{ logs: string }> {
- try {
- const response = await dockerApi.get(
- `/containers/${sessionId}/${containerId}/logs`,
- {
- params: options,
- },
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "get container logs");
- }
-}
-
-export async function downloadContainerLogs(
- sessionId: string,
- containerId: string,
- options?: DockerLogOptions,
-): Promise<Blob> {
- try {
- const response = await dockerApi.get(
- `/containers/${sessionId}/${containerId}/logs`,
- {
- params: { ...options, download: true },
- responseType: "blob",
- },
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "download container logs");
- }
-}
-
-export async function getContainerStats(
- sessionId: string,
- containerId: string,
-): Promise<DockerStats> {
- try {
- const response = await dockerApi.get(
- `/containers/${sessionId}/${containerId}/stats`,
- );
- return response.data;
- } catch (error) {
- throw handleApiError(error, "get container stats");
+ handleApiError(error, "get OIDC authorize URL");
}
}
-export interface DashboardLayout {
- cards: Array<{
- id: string;
- enabled: boolean;
- order: number;
- panel?: "main" | "side";
- height?: number | null;
- }>;
- mainWidthPct?: number;
-}
+// ============================================================================
+export {
+ getUserList,
+ getSessions,
+ revokeSession,
+ revokeAllUserSessions,
+ createApiKey,
+ getApiKeys,
+ deleteApiKey,
+ makeUserAdmin,
+ removeAdminStatus,
+ deleteUser,
+ deleteAccount,
+ updateRegistrationAllowed,
+ getOidcAutoProvision,
+ updateOidcAutoProvision,
+ updatePasswordLoginAllowed,
+ getPasswordResetAllowed,
+ updatePasswordResetAllowed,
+ updateOIDCConfig,
+ disableOIDCConfig,
+ type ApiKey,
+ type CreatedApiKey,
+} from "@/api/user-management-api";
+
+export {
+ setupTOTP,
+ enableTOTP,
+ disableTOTP,
+ verifyTOTPLogin,
+ generateBackupCodes,
+ getUserAlerts,
+ dismissAlert,
+ getReleasesRSS,
+ getVersionInfo,
+ getDatabaseHealth,
+} from "@/api/system-status-api";
-export async function getDashboardPreferences(): Promise<DashboardLayout> {
- const response = await dashboardApi.get("/dashboard/preferences");
- return response.data;
-}
+// SSH CREDENTIALS MANAGEMENT
+// ============================================================================
-export async function saveDashboardPreferences(
- layout: DashboardLayout,
-): Promise<{ success: boolean }> {
- const response = await dashboardApi.post("/dashboard/preferences", layout);
- return response.data;
-}
+export {
+ getCredentials,
+ getCredentialDetails,
+ createCredential,
+ updateCredential,
+ deleteCredential,
+ getCredentialHosts,
+ getCredentialFolders,
+ getSSHHostWithCredentials,
+ getHostPassword,
+ applyCredentialToHost,
+ removeCredentialFromHost,
+ migrateHostToCredential,
+ getFoldersWithStats,
+ renameFolder,
+ getSSHFolders,
+ updateFolderMetadata,
+ deleteAllHostsInFolder,
+ renameCredentialFolder,
+ detectKeyType,
+ detectPublicKeyType,
+ validateKeyPair,
+ generatePublicKeyFromPrivate,
+ generateKeyPair,
+ deployCredentialToHost,
+} from "@/api/credentials-api";
// ============================================================================
-// OPEN TABS API
+// SNIPPETS API
// ============================================================================
-export interface OpenTabRecord {
- id: string;
- userId: string;
- tabType: string;
- hostId: number | null;
- label: string;
- tabOrder: number;
- backendSessionId: string | null;
- createdAt: string;
- updatedAt: string;
-}
-
-export interface OpenTabSyncPayload {
- id: string;
- tabType: string;
- hostId?: number | null;
- label: string;
- tabOrder: number;
- backendSessionId?: string | null;
-}
-
-export interface OpenTabUpsertPayload {
- id: string;
- tabType: string;
- hostId?: number | null;
- label: string;
- tabOrder: number;
- backendSessionId?: string | null;
-}
-
-export interface ActiveSessionInfo {
- sessionId: string;
- hostId: number;
- hostName: string;
- tabInstanceId: string | null;
- isConnected: boolean;
- createdAt: number;
-}
-
-export async function getOpenTabs(): Promise<OpenTabRecord[]> {
- const response = await authApi.get("/open-tabs");
- return response.data;
-}
-
-export async function syncOpenTabs(tabs: OpenTabSyncPayload[]): Promise<void> {
- await authApi.put("/open-tabs", { tabs });
-}
-
-export async function deleteOpenTab(instanceId: string): Promise<void> {
- await authApi.delete(`/open-tabs/${instanceId}`);
-}
-
-export async function patchOpenTab(
- instanceId: string,
- updates: Partial<Pick<OpenTabRecord, "label" | "tabOrder" | "backendSessionId">>,
-): Promise<void> {
- await authApi.patch(`/open-tabs/${instanceId}`, updates);
-}
-
-export async function addOpenTab(tab: OpenTabUpsertPayload): Promise<void> {
- await authApi.post("/open-tabs", tab);
-}
-
-export async function getActiveSessions(): Promise<ActiveSessionInfo[]> {
- const response = await authApi.get("/open-tabs/active-sessions");
- return response.data;
-}
+export type {
+ NetworkTopologyNode,
+ NetworkTopologyEdge,
+ NetworkTopologyData,
+} from "@/api/snippets-api";
+export {
+ getSnippets,
+ createSnippet,
+ updateSnippet,
+ deleteSnippet,
+ executeSnippet,
+ getNetworkTopology,
+ saveNetworkTopology,
+ getSnippetFolders,
+ createSnippetFolder,
+ updateSnippetFolderMetadata,
+ renameSnippetFolder,
+ deleteSnippetFolder,
+ reorderSnippets,
+} from "@/api/snippets-api";
+
+// ============================================================================
+export type { UptimeInfo, RecentActivityItem } from "@/api/dashboard-api";
+export {
+ getUptime,
+ getRecentActivity,
+ logActivity,
+ resetRecentActivity,
+} from "@/api/dashboard-api";
+
+// ============================================================================
+export {
+ saveCommandToHistory,
+ getCommandHistory,
+ deleteCommandFromHistory,
+ clearCommandHistory,
+} from "@/api/command-history-api";
+
+export {
+ linkOIDCToPasswordAccount,
+ unlinkOIDCFromPasswordAccount,
+} from "@/api/oidc-account-api";
+
+export type {
+ GuacamoleTokenRequest,
+ GuacamoleTokenResponse,
+} from "@/api/guacamole-api";
+export {
+ getGuacamoleDpi,
+ getGuacamoleToken,
+ getGuacamoleTokenFromHost,
+ getGuacdStatus,
+} from "@/api/guacamole-api";
// ============================================================================
-// USER PREFERENCES API
+// RBAC MANAGEMENT
// ============================================================================
-export interface UserPreferences {
- reopenTabsOnLogin: boolean;
-}
+export {
+ getRoles,
+ createRole,
+ updateRole,
+ deleteRole,
+ getUserRoles,
+ assignRoleToUser,
+ removeRoleFromUser,
+ shareHost,
+ getHostAccess,
+ revokeHostAccess,
+ shareSnippet,
+ getSnippetAccess,
+ revokeSnippetAccess,
+ getSharedSnippets,
+} from "@/api/rbac-api";
-export async function getUserPreferences(): Promise<UserPreferences> {
- const response = await authApi.get("/user-preferences");
- return response.data;
-}
+// ============================================================================
+// DOCKER MANAGEMENT API
+// ============================================================================
-export async function saveUserPreferences(
- prefs: Partial<UserPreferences>,
-): Promise<void> {
- await authApi.put("/user-preferences", prefs);
-}
+export {
+ connectDockerSession,
+ verifyDockerTOTP,
+ verifyDockerWarpgate,
+ disconnectDockerSession,
+ keepaliveDockerSession,
+ getDockerSessionStatus,
+ validateDockerAvailability,
+ listDockerContainers,
+ getDockerContainerDetails,
+ startDockerContainer,
+ stopDockerContainer,
+ restartDockerContainer,
+ pauseDockerContainer,
+ unpauseDockerContainer,
+ removeDockerContainer,
+ getContainerLogs,
+ downloadContainerLogs,
+ getContainerStats,
+} from "@/api/docker-api";
+
+export {
+ getDashboardPreferences,
+ saveDashboardPreferences,
+ type DashboardLayout,
+} from "@/api/dashboard-preferences-api";
+
+export {
+ getOpenTabs,
+ syncOpenTabs,
+ deleteOpenTab,
+ patchOpenTab,
+ addOpenTab,
+ getActiveSessions,
+ getUserPreferences,
+ saveUserPreferences,
+ type OpenTabRecord,
+ type OpenTabSyncPayload,
+ type OpenTabUpsertPayload,
+ type ActiveSessionInfo,
+ type UserPreferences,
+} from "@/api/open-tabs-api";
diff --git a/src/ui/shell/CommandPalette.tsx b/src/ui/shell/CommandPalette.tsx
index 02c4f2505..d4212067b 100644
--- a/src/ui/shell/CommandPalette.tsx
+++ b/src/ui/shell/CommandPalette.tsx
@@ -25,7 +25,6 @@ import {
Network,
User,
KeyRound,
- LayoutDashboard,
Monitor,
MousePointerClick,
Clock,
@@ -33,13 +32,13 @@ import {
Pencil,
} from "lucide-react";
import { getRecentActivity, type RecentActivityItem } from "@/main-axios";
-import type { Host } from "@/types/ui-types";
+import type { Host, TabType } from "@/types/ui-types";
interface CommandPaletteProps {
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
hosts: Host[];
- onOpenTab: (type: any, label?: string, pendingEvent?: string) => void;
+ onOpenTab: (type: TabType, label?: string, pendingEvent?: string) => void;
}
const ACTIVITY_ICONS: Record<string, React.ReactNode> = {
@@ -53,7 +52,7 @@ const ACTIVITY_ICONS: Record<string, React.ReactNode> = {
rdp: <Monitor className="size-3.5" />,
};
-const ACTIVITY_TAB_TYPE: Record<string, string> = {
+const ACTIVITY_TAB_TYPE: Record<string, TabType> = {
terminal: "terminal",
file_manager: "files",
server_stats: "stats",
@@ -64,7 +63,11 @@ const ACTIVITY_TAB_TYPE: Record<string, string> = {
rdp: "rdp",
};
-function getSshActions(host: Host) {
+function getSshActions(host: Host): {
+ type: TabType;
+ icon: React.ElementType;
+ label: string;
+}[] {
const metricsEnabled = host.statsConfig?.metricsEnabled !== false;
return [
host.enableTerminal !== false && {
@@ -81,7 +84,7 @@ function getSshActions(host: Host) {
host.enableTunnel && { type: "tunnel", icon: Network, label: "Tunnels" },
metricsEnabled && { type: "stats", icon: Activity, label: "Stats" },
].filter(Boolean) as {
- type: string;
+ type: TabType;
icon: React.ElementType;
label: string;
}[];
@@ -187,23 +190,6 @@ export function CommandPalette({
heading={t("commandPalette.quickActions")}
className="px-2"
>
- <CommandItem
- onSelect={() => handleAction(() => onOpenTab("host-manager"))}
- className="group flex items-center gap-3 px-3 py-2.5 rounded-none hover:bg-accent-brand/10 cursor-pointer"
- >
- <div className="size-8 rounded-none bg-muted flex items-center justify-center group-hover:bg-accent-brand/20 transition-colors">
- <LayoutDashboard className="size-4 text-accent-brand" />
- </div>
- <div className="flex flex-col flex-1">
- <span className="text-sm font-semibold">
- {t("commandPalette.hostManager")}
- </span>
- <span className="text-xs text-muted-foreground">
- {t("commandPalette.hostManagerDesc")}
- </span>
- </div>
- </CommandItem>
-
<CommandItem
onSelect={() =>
handleAction(() =>
@@ -302,7 +288,7 @@ export function CommandPalette({
onSelect={() =>
handleAction(() =>
onOpenTab(
- ACTIVITY_TAB_TYPE[item.type] as any,
+ ACTIVITY_TAB_TYPE[item.type],
item.hostName,
),
)
@@ -351,7 +337,18 @@ export function CommandPalette({
<CommandItem
key={i}
onSelect={() =>
- handleAction(() => onOpenTab("terminal", host.name))
+ handleAction(() => {
+ const type = host.enableSsh
+ ? "terminal"
+ : host.enableRdp
+ ? "rdp"
+ : host.enableVnc
+ ? "vnc"
+ : host.enableTelnet
+ ? "telnet"
+ : "terminal";
+ onOpenTab(type, host.name);
+ })
}
className="group flex items-center gap-3 px-3 py-2.5 rounded-none hover:bg-accent-brand/10 cursor-pointer"
>
@@ -388,7 +385,7 @@ export function CommandPalette({
onClick={(e) => {
e.stopPropagation();
handleAction(() =>
- onOpenTab(type as any, host.name),
+ onOpenTab(type, host.name),
);
}}
className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
diff --git a/src/ui/shell/TabBar.tsx b/src/ui/shell/TabBar.tsx
index 4c6992278..18f326607 100644
--- a/src/ui/shell/TabBar.tsx
+++ b/src/ui/shell/TabBar.tsx
@@ -381,7 +381,9 @@ export function TabBar({
<div className="flex items-center gap-2 flex-1 min-w-0">
{tabIcon(tab.type)}
<span className="truncate">
- {tab.type === "dashboard" ? t("nav.dashboard") : tab.label}
+ {tab.type === "dashboard"
+ ? t("nav.dashboard")
+ : tab.label}
</span>
</div>
{tab.type !== "dashboard" && (
diff --git a/src/ui/shell/TabContext.tsx b/src/ui/shell/TabContext.tsx
index 9e5613d83..b19a7a41d 100644
--- a/src/ui/shell/TabContext.tsx
+++ b/src/ui/shell/TabContext.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components */
import React, {
createContext,
useContext,
@@ -40,7 +41,6 @@ interface TabContextType {
const TabContext = createContext<TabContextType | undefined>(undefined);
-
export function useTabs() {
const context = useContext(TabContext);
if (context === undefined) {
@@ -80,7 +80,9 @@ export function clearTermixSessionStorage() {
export function TabProvider({ children }: TabProviderProps) {
const { t } = useTranslation();
- const [tabs, setTabs] = useState<Tab[]>([{ id: 1, type: "home", title: "Home" }]);
+ const [tabs, setTabs] = useState<Tab[]>([
+ { id: 1, type: "home", title: "Home" },
+ ]);
const [currentTab, setCurrentTab] = useState<number>(1);
const [allSplitScreenTab, setAllSplitScreenTab] = useState<number[]>([]);
const [previewTerminalTheme, setPreviewTerminalTheme] = useState<
@@ -106,151 +108,158 @@ export function TabProvider({ children }: TabProviderProps) {
);
}, [t]);
- function computeUniqueTitle(
- tabType: Tab["type"],
- desiredTitle: string | undefined,
- ): string {
- const defaultTitle =
- tabType === "server_stats"
- ? t("nav.serverStats")
- : tabType === "file_manager"
- ? t("nav.fileManager")
- : tabType === "tunnel"
- ? t("nav.tunnels")
- : tabType === "docker"
- ? t("nav.docker")
- : t("nav.terminal");
- const baseTitle = (desiredTitle || defaultTitle).trim();
- const match = baseTitle.match(/^(.*) \((\d+)\)$/);
- const root = match ? match[1] : baseTitle;
-
- const usedNumbers = new Set<number>();
- let rootUsed = false;
- tabs.forEach((t) => {
- if (!t.title) return;
- if (t.title === root) {
- rootUsed = true;
- return;
- }
- const m = t.title.match(
- new RegExp(
- `^${root.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&")} \\((\\d+)\\)$`,
- ),
- );
- if (m) {
- const n = parseInt(m[1], 10);
- if (!isNaN(n)) usedNumbers.add(n);
- }
- });
-
- if (!rootUsed) return root;
- let n = 2;
- while (usedNumbers.has(n)) n += 1;
- return `${root} (${n})`;
- }
-
- const addTab = (tabData: Omit<Tab, "id">): number => {
- if (tabData.type === "ssh_manager") {
- const existingTab = tabs.find((t) => t.type === "ssh_manager");
- if (existingTab) {
- setTabs((prev) =>
- prev.map((t) =>
- t.id === existingTab.id
- ? {
- ...t,
- title: existingTab.title,
- hostConfig: tabData.hostConfig
- ? { ...tabData.hostConfig }
- : undefined,
- initialTab: tabData.initialTab,
- _updateTimestamp: Date.now(),
- }
- : t,
+ const computeUniqueTitle = useCallback(
+ (tabType: Tab["type"], desiredTitle: string | undefined): string => {
+ const defaultTitle =
+ tabType === "server_stats"
+ ? t("nav.serverStats")
+ : tabType === "file_manager"
+ ? t("nav.fileManager")
+ : tabType === "tunnel"
+ ? t("nav.tunnels")
+ : tabType === "docker"
+ ? t("nav.docker")
+ : t("nav.terminal");
+ const baseTitle = (desiredTitle || defaultTitle).trim();
+ const match = baseTitle.match(/^(.*) \((\d+)\)$/);
+ const root = match ? match[1] : baseTitle;
+
+ const usedNumbers = new Set<number>();
+ let rootUsed = false;
+ tabs.forEach((t) => {
+ if (!t.title) return;
+ if (t.title === root) {
+ rootUsed = true;
+ return;
+ }
+ const m = t.title.match(
+ new RegExp(
+ `^${root.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&")} \\((\\d+)\\)$`,
),
);
- setCurrentTab(existingTab.id);
- setAllSplitScreenTab((prev) =>
- prev.filter((tid) => tid !== existingTab.id),
- );
- return existingTab.id;
+ if (m) {
+ const n = parseInt(m[1], 10);
+ if (!isNaN(n)) usedNumbers.add(n);
+ }
+ });
+
+ if (!rootUsed) return root;
+ let n = 2;
+ while (usedNumbers.has(n)) n += 1;
+ return `${root} (${n})`;
+ },
+ [t, tabs],
+ );
+
+ const addTab = useCallback(
+ (tabData: Omit<Tab, "id">): number => {
+ if (tabData.type === "ssh_manager") {
+ const existingTab = tabs.find((t) => t.type === "ssh_manager");
+ if (existingTab) {
+ setTabs((prev) =>
+ prev.map((t) =>
+ t.id === existingTab.id
+ ? {
+ ...t,
+ title: existingTab.title,
+ hostConfig: tabData.hostConfig
+ ? { ...tabData.hostConfig }
+ : undefined,
+ initialTab: tabData.initialTab,
+ _updateTimestamp: Date.now(),
+ }
+ : t,
+ ),
+ );
+ setCurrentTab(existingTab.id);
+ setAllSplitScreenTab((prev) =>
+ prev.filter((tid) => tid !== existingTab.id),
+ );
+ return existingTab.id;
+ }
}
- }
- const id = nextTabId.current++;
- const instanceId = `tab_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
- const needsUniqueTitle =
- tabData.type === "terminal" ||
- tabData.type === "server_stats" ||
- tabData.type === "file_manager" ||
- tabData.type === "tunnel" ||
- tabData.type === "docker";
- const effectiveTitle = needsUniqueTitle
- ? computeUniqueTitle(tabData.type, tabData.title)
- : tabData.title || "";
- const newTab: Tab = {
- ...tabData,
- id,
- instanceId,
- title: effectiveTitle,
- terminalRef:
- tabData.type === "terminal"
- ? React.createRef<TerminalRefHandle>()
+ const id = nextTabId.current++;
+ const instanceId = `tab_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
+ const needsUniqueTitle =
+ tabData.type === "terminal" ||
+ tabData.type === "server_stats" ||
+ tabData.type === "file_manager" ||
+ tabData.type === "tunnel" ||
+ tabData.type === "docker";
+ const effectiveTitle = needsUniqueTitle
+ ? computeUniqueTitle(tabData.type, tabData.title)
+ : tabData.title || "";
+ const newTab: Tab = {
+ ...tabData,
+ id,
+ instanceId,
+ title: effectiveTitle,
+ terminalRef:
+ tabData.type === "terminal"
+ ? React.createRef<TerminalRefHandle>()
+ : undefined,
+ hostConfig: tabData.hostConfig
+ ? {
+ ...tabData.hostConfig,
+ instanceId,
+ }
: undefined,
- hostConfig: tabData.hostConfig
- ? {
- ...tabData.hostConfig,
- instanceId,
- }
- : undefined,
- };
- setTabs((prev) => [...prev, newTab]);
- setCurrentTab(id);
- setAllSplitScreenTab((prev) => prev.filter((tid) => tid !== id));
- return id;
- };
+ };
+ setTabs((prev) => [...prev, newTab]);
+ setCurrentTab(id);
+ setAllSplitScreenTab((prev) => prev.filter((tid) => tid !== id));
+ return id;
+ },
+ [computeUniqueTitle, tabs],
+ );
const pendingCurrentTabRef = useRef<number | null>(null);
- const removeTab = (tabId: number) => {
- const tab = tabs.find((t) => t.id === tabId);
- if (
- tab &&
- tab.terminalRef?.current &&
- typeof tab.terminalRef.current.disconnect === "function"
- ) {
- tab.terminalRef.current.disconnect();
- }
-
- setTabs((prev) => {
- const closedIndex = prev.findIndex((t) => t.id === tabId);
- const filtered = prev.filter((t) => t.id !== tabId);
-
- if (filtered.length === 0) {
- pendingCurrentTabRef.current = 1;
- return [{ id: 1, type: "home", title: t("nav.home") }];
+ const removeTab = useCallback(
+ (tabId: number) => {
+ const tab = tabs.find((t) => t.id === tabId);
+ if (
+ tab &&
+ tab.terminalRef?.current &&
+ typeof tab.terminalRef.current.disconnect === "function"
+ ) {
+ tab.terminalRef.current.disconnect();
}
- // If the closed tab was active, compute the next tab to activate
- // using the latest prev so rapid closes don't use stale data
- const nextIndex =
- closedIndex < filtered.length ? closedIndex : filtered.length - 1;
- pendingCurrentTabRef.current = filtered[Math.max(0, nextIndex)]?.id ?? 1;
-
- return filtered;
- });
-
- setAllSplitScreenTab((prev) => {
- const newSplits = prev.filter((id) => id !== tabId);
- return newSplits.length <= 1 ? [] : newSplits;
- });
-
- setCurrentTab((prevCurrentTab) => {
- if (prevCurrentTab !== tabId) return prevCurrentTab;
- return pendingCurrentTabRef.current ?? 1;
- });
- };
+ setTabs((prev) => {
+ const closedIndex = prev.findIndex((t) => t.id === tabId);
+ const filtered = prev.filter((t) => t.id !== tabId);
+
+ if (filtered.length === 0) {
+ pendingCurrentTabRef.current = 1;
+ return [{ id: 1, type: "home", title: t("nav.home") }];
+ }
+
+ // If the closed tab was active, compute the next tab to activate
+ // using the latest prev so rapid closes don't use stale data
+ const nextIndex =
+ closedIndex < filtered.length ? closedIndex : filtered.length - 1;
+ pendingCurrentTabRef.current =
+ filtered[Math.max(0, nextIndex)]?.id ?? 1;
+
+ return filtered;
+ });
+
+ setAllSplitScreenTab((prev) => {
+ const newSplits = prev.filter((id) => id !== tabId);
+ return newSplits.length <= 1 ? [] : newSplits;
+ });
+
+ setCurrentTab((prevCurrentTab) => {
+ if (prevCurrentTab !== tabId) return prevCurrentTab;
+ return pendingCurrentTabRef.current ?? 1;
+ });
+ },
+ [t, tabs],
+ );
- const setSplitScreenTab = (tabId: number) => {
+ const setSplitScreenTab = useCallback((tabId: number) => {
setAllSplitScreenTab((prev) => {
if (prev.includes(tabId)) {
return prev.filter((id) => id !== tabId);
@@ -259,15 +268,18 @@ export function TabProvider({ children }: TabProviderProps) {
}
return prev;
});
- };
+ }, []);
- const getTab = (tabId: number) => {
- return tabs.find((tab) => tab.id === tabId);
- };
+ const getTab = useCallback(
+ (tabId: number) => {
+ return tabs.find((tab) => tab.id === tabId);
+ },
+ [tabs],
+ );
const isReorderingRef = useRef(false);
- const reorderTabs = (fromIndex: number, toIndex: number) => {
+ const reorderTabs = useCallback((fromIndex: number, toIndex: number) => {
if (isReorderingRef.current) return;
isReorderingRef.current = true;
@@ -287,7 +299,7 @@ export function TabProvider({ children }: TabProviderProps) {
return newTabs;
});
- };
+ }, []);
const updateHostConfig = useCallback(
(
diff --git a/src/ui/shell/tabUtils.tsx b/src/ui/shell/tabUtils.tsx
index 43124e465..31a395c8d 100644
--- a/src/ui/shell/tabUtils.tsx
+++ b/src/ui/shell/tabUtils.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components */
import {
Box,
FolderSearch,
@@ -14,6 +15,10 @@ import {
import { useTranslation } from "react-i18next";
import { CommandHistoryProvider } from "@/features/terminal/command-history/CommandHistoryContext";
import { Terminal as TerminalFeature } from "@/features/terminal/Terminal";
+import type {
+ TerminalHandle,
+ TerminalHostConfig,
+} from "@/features/terminal/Terminal";
import { FileManager } from "@/features/file-manager/FileManager";
import { DockerManager } from "@/features/docker/DockerManager";
import { ServerStats } from "@/features/server-stats/ServerStats";
@@ -127,14 +132,14 @@ function TerminalTabContent({
return (
<CommandHistoryProvider>
<TerminalFeature
- ref={tab.terminalRef as any}
+ ref={tab.terminalRef as React.Ref<TerminalHandle>}
hostConfig={
{
...hostToSSHHost(host),
sshPort: host.sshPort ?? host.port,
instanceId: tab.instanceId ?? tab.id,
restoredSessionId: tab.restoredSessionId ?? null,
- } as any
+ } as TerminalHostConfig
}
isVisible={isVisible}
title={label}
@@ -213,7 +218,7 @@ export function renderTabContent(
);
return (
<ServerStats
- hostConfig={hostToSSHHost(host) as any}
+ hostConfig={hostToSSHHost(host)}
title={label}
isVisible={isVisible}
isTopbarOpen={false}
diff --git a/src/ui/sidebar/AdminApiKeysSection.tsx b/src/ui/sidebar/AdminApiKeysSection.tsx
new file mode 100644
index 000000000..12c1d9e8a
--- /dev/null
+++ b/src/ui/sidebar/AdminApiKeysSection.tsx
@@ -0,0 +1,244 @@
+import type { Dispatch, SetStateAction } from "react";
+import { useTranslation } from "react-i18next";
+import { deleteApiKey } from "@/main-axios";
+import type { ApiKey } from "@/main-axios";
+import { Button } from "@/components/button";
+import { Input } from "@/components/input";
+import { Copy, Network, Plus, RefreshCw, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { AccordionSection } from "./AdminSettingsShared";
+import type { AdminUser } from "./AdminManagementSections";
+
+type AdminApiKeysSectionProps = {
+ open: boolean;
+ onToggle: () => void;
+ apiKeys: ApiKey[];
+ setApiKeys: Dispatch<SetStateAction<ApiKey[]>>;
+ loadApiKeys: () => void;
+ showCreateKey: boolean;
+ setShowCreateKey: Dispatch<SetStateAction<boolean>>;
+ createdKeyToken: string | null;
+ setCreatedKeyToken: Dispatch<SetStateAction<string | null>>;
+ newKeyName: string;
+ setNewKeyName: Dispatch<SetStateAction<string>>;
+ newKeyUserId: string;
+ setNewKeyUserId: Dispatch<SetStateAction<string>>;
+ newKeyExpiry: string;
+ setNewKeyExpiry: Dispatch<SetStateAction<string>>;
+ users: AdminUser[];
+ handleCreateApiKey: () => void;
+ newKeyLoading: boolean;
+};
+
+export function AdminApiKeysSection({
+ open,
+ onToggle,
+ apiKeys,
+ setApiKeys,
+ loadApiKeys,
+ showCreateKey,
+ setShowCreateKey,
+ createdKeyToken,
+ setCreatedKeyToken,
+ newKeyName,
+ setNewKeyName,
+ newKeyUserId,
+ setNewKeyUserId,
+ newKeyExpiry,
+ setNewKeyExpiry,
+ users,
+ handleCreateApiKey,
+ newKeyLoading,
+}: AdminApiKeysSectionProps) {
+ const { t } = useTranslation();
+
+ return (
+ <AccordionSection
+ label={t("admin.sectionApiKeys")}
+ icon={<Network className="size-3.5" />}
+ open={open}
+ onToggle={onToggle}
+ >
+ <div className="flex flex-col pt-2">
+ <div className="flex items-center justify-between py-2 border-b border-border">
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.apiKeysCount", { count: apiKeys.length })}
+ </span>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-muted-foreground hover:text-foreground"
+ onClick={loadApiKeys}
+ >
+ <RefreshCw className="size-3" />
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
+ onClick={() => {
+ setShowCreateKey((o) => !o);
+ setCreatedKeyToken(null);
+ }}
+ >
+ <Plus className="size-3" />
+ {t("admin.createRole")}
+ </Button>
+ </div>
+ </div>
+ {showCreateKey && (
+ <div className="flex flex-col gap-2.5 py-3 border-b border-border">
+ <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
+ {t("admin.newApiKey")}
+ </span>
+ {createdKeyToken ? (
+ <div className="flex flex-col gap-2">
+ <span className="text-[10px] text-accent-brand font-semibold">
+ {t("admin.apiKeyCreatedWarning")}
+ </span>
+ <div className="flex items-center gap-2 bg-muted/30 border border-border px-2 py-1.5">
+ <span className="text-[10px] font-mono flex-1 truncate">
+ {createdKeyToken}
+ </span>
+ <button
+ onClick={() => {
+ navigator.clipboard.writeText(createdKeyToken);
+ toast.info(t("admin.copiedToClipboard"));
+ }}
+ className="text-muted-foreground hover:text-accent-brand shrink-0"
+ >
+ <Copy className="size-3.5" />
+ </button>
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs self-end"
+ onClick={() => {
+ setShowCreateKey(false);
+ setCreatedKeyToken(null);
+ }}
+ >
+ {t("admin.done")}
+ </Button>
+ </div>
+ ) : (
+ <>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.apiKeyName")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ placeholder="e.g., CI Pipeline"
+ value={newKeyName}
+ onChange={(e) => setNewKeyName(e.target.value)}
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.apiKeyUser")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <select
+ className="px-2 py-1.5 text-xs bg-background border border-border text-foreground outline-none"
+ value={newKeyUserId}
+ onChange={(e) => setNewKeyUserId(e.target.value)}
+ >
+ <option value="">{t("admin.apiKeySelectUser")}</option>
+ {users.map((u) => (
+ <option key={u.id} value={u.id}>
+ {u.username}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.apiKeyExpiresAt")}
+ </label>
+ <Input
+ type="date"
+ value={newKeyExpiry}
+ onChange={(e) => setNewKeyExpiry(e.target.value)}
+ className="text-xs"
+ />
+ </div>
+ <div className="flex justify-end gap-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs"
+ onClick={() => setShowCreateKey(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
+ onClick={handleCreateApiKey}
+ disabled={newKeyLoading}
+ >
+ {newKeyLoading ? t("admin.creating") : t("admin.createKey")}
+ </Button>
+ </div>
+ </>
+ )}
+ </div>
+ )}
+ {apiKeys.map((key) => (
+ <div
+ key={key.id}
+ className="flex items-start justify-between py-2.5 border-b border-border last:border-0 gap-2"
+ >
+ <div className="flex flex-col gap-0.5 min-w-0 flex-1">
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <span className="text-xs font-semibold truncate">
+ {key.name}
+ </span>
+ {!key.isActive && (
+ <span className="text-[9px] font-semibold px-1 py-px border border-destructive/40 bg-destructive/10 text-destructive">
+ {t("admin.revokedBadge")}
+ </span>
+ )}
+ </div>
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.apiKeyUser")}: {key.username}
+ </span>
+ <span className="text-[10px] font-mono text-muted-foreground truncate">
+ {key.tokenPrefix}…
+ </span>
+ <span className="text-[10px] text-muted-foreground">
+ {key.createdAt.split("T")[0]} ·{" "}
+ {key.expiresAt
+ ? key.expiresAt.split("T")[0]
+ : t("admin.apiKeyNoExpiry")}
+ </span>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-muted-foreground hover:text-destructive shrink-0"
+ onClick={async () => {
+ try {
+ await deleteApiKey(key.id);
+ setApiKeys((prev) => prev.filter((k) => k.id !== key.id));
+ toast.success(
+ t("admin.revokeKeySuccess", { name: key.name }),
+ );
+ } catch {
+ toast.error(t("admin.revokeKeyFailed"));
+ }
+ }}
+ >
+ <Trash2 className="size-3" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ </AccordionSection>
+ );
+}
diff --git a/src/ui/sidebar/AdminManagementSections.tsx b/src/ui/sidebar/AdminManagementSections.tsx
new file mode 100644
index 000000000..93ff29b26
--- /dev/null
+++ b/src/ui/sidebar/AdminManagementSections.tsx
@@ -0,0 +1,494 @@
+import type { Dispatch, SetStateAction } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ deleteRole,
+ deleteUser,
+ revokeAllUserSessions,
+ revokeSession,
+} from "@/main-axios";
+import type { Role } from "@/main-axios";
+import { Button } from "@/components/button";
+import { Input } from "@/components/input";
+import {
+ Activity,
+ KeyRound,
+ Pencil,
+ Plus,
+ RefreshCw,
+ Share2,
+ Trash2,
+ User,
+} from "lucide-react";
+import { toast } from "sonner";
+import { AccordionSection } from "./AdminSettingsShared";
+
+export type AdminUser = {
+ id: string;
+ username: string;
+ isAdmin: boolean;
+ isOidc: boolean;
+ passwordHash?: string;
+};
+
+export type AdminSession = {
+ id: string;
+ userId: string;
+ username?: string;
+ deviceType: string;
+ deviceInfo: string;
+ createdAt: string;
+ expiresAt: string;
+ lastActiveAt: string;
+ isRevoked?: boolean;
+ isCurrentSession?: boolean;
+};
+
+type ApiErrorLike = {
+ response?: {
+ data?: {
+ error?: string;
+ };
+ };
+};
+
+function apiErrorMessage(error: unknown, fallback: string) {
+ return (error as ApiErrorLike).response?.data?.error || fallback;
+}
+
+type UsersSectionProps = {
+ open: boolean;
+ onToggle: () => void;
+ users: AdminUser[];
+ setUsers: Dispatch<SetStateAction<AdminUser[]>>;
+ loadUsers: () => void;
+ setCreateUserOpen: Dispatch<SetStateAction<boolean>>;
+ setEditUserTarget: Dispatch<SetStateAction<AdminUser | null>>;
+ setEditUserOpen: Dispatch<SetStateAction<boolean>>;
+ setLinkAccountTarget: Dispatch<
+ SetStateAction<{ id: string; username: string } | null>
+ >;
+ setLinkAccountOpen: Dispatch<SetStateAction<boolean>>;
+};
+
+export function AdminUsersSection({
+ open,
+ onToggle,
+ users,
+ setUsers,
+ loadUsers,
+ setCreateUserOpen,
+ setEditUserTarget,
+ setEditUserOpen,
+ setLinkAccountTarget,
+ setLinkAccountOpen,
+}: UsersSectionProps) {
+ const { t } = useTranslation();
+
+ return (
+ <AccordionSection
+ label={t("admin.sectionUsers")}
+ icon={<User className="size-3.5" />}
+ open={open}
+ onToggle={onToggle}
+ >
+ <div className="flex flex-col pt-2">
+ <div className="flex items-center justify-between py-2 border-b border-border">
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.usersCount", { count: users.length })}
+ </span>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-muted-foreground hover:text-foreground"
+ onClick={loadUsers}
+ >
+ <RefreshCw className="size-3" />
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
+ onClick={() => setCreateUserOpen(true)}
+ >
+ <Plus className="size-3" />
+ {t("admin.createUser")}
+ </Button>
+ </div>
+ </div>
+ {users.map((user) => {
+ const authLabel =
+ user.isOidc && user.passwordHash
+ ? t("admin.authTypeDual")
+ : user.isOidc
+ ? t("admin.authTypeOidc")
+ : t("admin.authTypeLocal");
+ return (
+ <div
+ key={user.id}
+ className="flex items-center justify-between py-2.5 border-b border-border last:border-0"
+ >
+ <div className="flex items-center gap-2 min-w-0">
+ <div className="size-6 bg-muted border border-border flex items-center justify-center text-[10px] font-bold shrink-0">
+ {user.username[0].toUpperCase()}
+ </div>
+ <div className="flex flex-col gap-0.5 min-w-0">
+ <span className="text-xs font-semibold truncate max-w-[120px]">
+ {user.username}
+ </span>
+ <div className="flex items-center gap-1">
+ {user.isAdmin && (
+ <span className="text-[9px] font-semibold px-1 py-px border border-accent-brand/40 bg-accent-brand/10 text-accent-brand">
+ {t("admin.adminBadge")}
+ </span>
+ )}
+ <span className="text-[9px] font-semibold px-1 py-px border border-border text-muted-foreground">
+ {authLabel}
+ </span>
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-0.5 shrink-0">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-muted-foreground hover:text-foreground"
+ onClick={() => {
+ setEditUserTarget(user);
+ setEditUserOpen(true);
+ }}
+ >
+ <Pencil className="size-3" />
+ </Button>
+ {user.isOidc && (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-muted-foreground hover:text-foreground"
+ onClick={() => {
+ setLinkAccountTarget({
+ id: user.id,
+ username: user.username,
+ });
+ setLinkAccountOpen(true);
+ }}
+ >
+ <Share2 className="size-3" />
+ </Button>
+ )}
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-muted-foreground hover:text-destructive"
+ disabled={user.isAdmin}
+ onClick={async () => {
+ try {
+ await deleteUser(user.username);
+ setUsers((prev) => prev.filter((u) => u.id !== user.id));
+ toast.success(
+ t("admin.deleteUserSuccess", {
+ username: user.username,
+ }),
+ );
+ } catch (e: unknown) {
+ toast.error(
+ apiErrorMessage(e, t("admin.deleteUserFailed")),
+ );
+ }
+ }}
+ >
+ <Trash2 className="size-3" />
+ </Button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </AccordionSection>
+ );
+}
+
+type SessionsSectionProps = {
+ open: boolean;
+ onToggle: () => void;
+ sessions: AdminSession[];
+ setSessions: Dispatch<SetStateAction<AdminSession[]>>;
+ loadSessions: () => void;
+};
+
+export function AdminSessionsSection({
+ open,
+ onToggle,
+ sessions,
+ setSessions,
+ loadSessions,
+}: SessionsSectionProps) {
+ const { t } = useTranslation();
+
+ return (
+ <AccordionSection
+ label={t("admin.sectionSessions")}
+ icon={<Activity className="size-3.5" />}
+ open={open}
+ onToggle={onToggle}
+ >
+ <div className="flex flex-col pt-2">
+ <div className="flex items-center justify-between py-2 border-b border-border">
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.sessionsActive", { count: sessions.length })}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-muted-foreground hover:text-foreground"
+ onClick={loadSessions}
+ >
+ <RefreshCw className="size-3" />
+ </Button>
+ </div>
+ {sessions.map((session) => (
+ <div
+ key={session.id}
+ className="flex items-start justify-between py-2.5 border-b border-border last:border-0 gap-2"
+ >
+ <div className="flex flex-col gap-0.5 min-w-0 flex-1">
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <span className="text-xs font-semibold">
+ {session.username}
+ </span>
+ {session.isCurrentSession && (
+ <span className="text-[9px] font-semibold px-1 py-px border border-accent-brand/40 bg-accent-brand/10 text-accent-brand">
+ {t("admin.youBadge")}
+ </span>
+ )}
+ </div>
+ <span className="text-[10px] text-muted-foreground truncate">
+ {session.deviceInfo}
+ </span>
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.sessionActive", { time: session.lastActiveAt })}
+ </span>
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.sessionExpires", { time: session.expiresAt })}
+ </span>
+ </div>
+ <div className="flex items-center gap-0.5 shrink-0">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-[10px] text-muted-foreground hover:text-destructive h-6 px-1.5"
+ onClick={async () => {
+ try {
+ await revokeAllUserSessions(session.userId);
+ setSessions((prev) =>
+ prev.filter((s) => s.userId !== session.userId),
+ );
+ toast.success(t("admin.revokeAllSessionsSuccess"));
+ } catch {
+ toast.error(t("admin.revokeAllSessionsFailed"));
+ }
+ }}
+ >
+ {t("admin.revokeAll")}
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-muted-foreground hover:text-destructive"
+ onClick={async () => {
+ try {
+ await revokeSession(session.id);
+ setSessions((prev) =>
+ prev.filter((s) => s.id !== session.id),
+ );
+ } catch {
+ toast.error(t("admin.revokeSessionFailed"));
+ }
+ }}
+ >
+ <Trash2 className="size-3" />
+ </Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ </AccordionSection>
+ );
+}
+
+type RolesSectionProps = {
+ open: boolean;
+ onToggle: () => void;
+ roles: Role[];
+ setRoles: Dispatch<SetStateAction<Role[]>>;
+ showCreateRole: boolean;
+ setShowCreateRole: Dispatch<SetStateAction<boolean>>;
+ newRoleName: string;
+ setNewRoleName: Dispatch<SetStateAction<string>>;
+ newRoleDisplayName: string;
+ setNewRoleDisplayName: Dispatch<SetStateAction<string>>;
+ newRoleDescription: string;
+ setNewRoleDescription: Dispatch<SetStateAction<string>>;
+ handleCreateRole: () => void;
+ createRoleLoading: boolean;
+};
+
+export function AdminRolesSection({
+ open,
+ onToggle,
+ roles,
+ setRoles,
+ showCreateRole,
+ setShowCreateRole,
+ newRoleName,
+ setNewRoleName,
+ newRoleDisplayName,
+ setNewRoleDisplayName,
+ newRoleDescription,
+ setNewRoleDescription,
+ handleCreateRole,
+ createRoleLoading,
+}: RolesSectionProps) {
+ const { t } = useTranslation();
+
+ return (
+ <AccordionSection
+ label={t("admin.sectionRoles")}
+ icon={<KeyRound className="size-3.5" />}
+ open={open}
+ onToggle={onToggle}
+ >
+ <div className="flex flex-col pt-2">
+ <div className="flex items-center justify-between py-2 border-b border-border">
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.rolesCount", { count: roles.length })}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
+ onClick={() => setShowCreateRole((o) => !o)}
+ >
+ <Plus className="size-3" />
+ {t("admin.createRole")}
+ </Button>
+ </div>
+ {showCreateRole && (
+ <div className="flex flex-col gap-2.5 py-3 border-b border-border">
+ <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
+ {t("admin.newRole")}
+ </span>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.roleName")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ placeholder="e.g., developer"
+ value={newRoleName}
+ onChange={(e) => setNewRoleName(e.target.value)}
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.roleDisplayName")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ placeholder="e.g., Developer"
+ value={newRoleDisplayName}
+ onChange={(e) => setNewRoleDisplayName(e.target.value)}
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.roleDescription")}
+ </label>
+ <textarea
+ rows={2}
+ placeholder={t("common.optional")}
+ value={newRoleDescription}
+ onChange={(e) => setNewRoleDescription(e.target.value)}
+ className="w-full px-2 py-1.5 text-xs bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring"
+ />
+ </div>
+ <div className="flex justify-end gap-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs"
+ onClick={() => {
+ setShowCreateRole(false);
+ setNewRoleName("");
+ setNewRoleDisplayName("");
+ setNewRoleDescription("");
+ }}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
+ onClick={handleCreateRole}
+ disabled={createRoleLoading}
+ >
+ {createRoleLoading
+ ? t("admin.creating")
+ : t("admin.createRole")}
+ </Button>
+ </div>
+ </div>
+ )}
+ {roles.map((role) => (
+ <div
+ key={role.id}
+ className="flex items-center justify-between py-2.5 border-b border-border last:border-0"
+ >
+ <div className="flex flex-col gap-0.5 min-w-0">
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <span className="text-xs font-semibold truncate">
+ {role.displayName}
+ </span>
+ {role.isSystem ? (
+ <span className="text-[9px] font-semibold px-1 py-px border border-border text-muted-foreground">
+ {t("admin.systemBadge")}
+ </span>
+ ) : (
+ <span className="text-[9px] font-semibold px-1 py-px border border-accent-brand/40 bg-accent-brand/10 text-accent-brand">
+ {t("admin.customBadge")}
+ </span>
+ )}
+ </div>
+ <span className="text-[10px] font-mono text-muted-foreground">
+ {role.name}
+ </span>
+ </div>
+ {!role.isSystem && (
+ <div className="flex items-center gap-0.5 shrink-0">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6 text-muted-foreground hover:text-destructive"
+ onClick={async () => {
+ await deleteRole(role.id);
+ setRoles((prev) => prev.filter((r) => r.id !== role.id));
+ toast.success(
+ t("admin.deleteRoleSuccess", {
+ name: role.displayName,
+ }),
+ );
+ }}
+ >
+ <Trash2 className="size-3" />
+ </Button>
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </AccordionSection>
+ );
+}
diff --git a/src/ui/sidebar/AdminSettingsPanel.tsx b/src/ui/sidebar/AdminSettingsPanel.tsx
index df1833537..b6914c067 100644
--- a/src/ui/sidebar/AdminSettingsPanel.tsx
+++ b/src/ui/sidebar/AdminSettingsPanel.tsx
@@ -7,10 +7,7 @@ import {
getApiKeys,
createApiKey,
deleteUser,
- revokeSession,
revokeAllUserSessions,
- deleteRole,
- deleteApiKey,
createRole,
registerUser,
makeUserAdmin,
@@ -36,90 +33,41 @@ import {
updateOidcAutoProvision,
isElectron,
getUserRoles,
- assignRoleToUser,
- removeRoleFromUser,
} from "@/main-axios";
import type { ApiKey, CreatedApiKey, UserRole } from "@/main-axios";
-import type React from "react";
-import { Button } from "@/components/button";
-import { Input } from "@/components/input";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogDescription,
-} from "@/components/dialog";
-import {
- Activity,
- AlertCircle,
- ChevronDown,
- Copy,
- Database,
- Eye,
- EyeOff,
- KeyRound,
- Network,
- Pencil,
- Plus,
- RefreshCw,
- Settings,
- Share2,
- Shield,
- Trash2,
- User,
-} from "lucide-react";
-import { SettingRow } from "@/components/section-card";
import type { AdminSection } from "@/types/ui-types";
import type { Role } from "@/main-axios";
+import {
+ AdminRolesSection,
+ AdminSessionsSection,
+ AdminUsersSection,
+ type AdminSession,
+ type AdminUser,
+} from "./AdminManagementSections";
import { toast } from "sonner";
import { getBasePath } from "@/lib/base-path";
-
-function AdminToggle({ on, onToggle }: { on: boolean; onToggle: () => void }) {
- return (
- <button
- onClick={onToggle}
- className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center border-2 transition-colors ${on ? "bg-accent-brand border-accent-brand" : "bg-muted border-border"}`}
- >
- <span
- className={`pointer-events-none inline-block h-3 w-3 bg-background shadow-sm transition-transform ${on ? "translate-x-4" : "translate-x-0.5"}`}
- />
- </button>
- );
-}
-
-function AccordionSection({
- label,
- icon,
- open,
- onToggle,
- children,
-}: {
- label: string;
- icon: React.ReactNode;
- open: boolean;
- onToggle: () => void;
- children: React.ReactNode;
-}) {
- return (
- <div className="border border-border bg-card overflow-hidden">
- <button
- onClick={onToggle}
- className="flex items-center gap-2 w-full px-3 py-2.5 text-left hover:bg-muted/40 transition-colors"
- >
- <span className="text-muted-foreground shrink-0">{icon}</span>
- <span className="text-xs font-bold uppercase tracking-widest text-foreground flex-1">
- {label}
- </span>
- <ChevronDown
- className={`size-3.5 text-muted-foreground shrink-0 transition-transform duration-150 ${open ? "rotate-180" : ""}`}
- />
- </button>
- {open && (
- <div className="border-t border-border px-3 pb-3">{children}</div>
- )}
- </div>
- );
+import {
+ AdminDatabaseSection,
+ AdminGeneralSettingsSection,
+ AdminOidcSettingsSection,
+} from "./AdminSettingsSections";
+import { AdminApiKeysSection } from "./AdminApiKeysSection";
+import {
+ AdminCreateUserDialog,
+ AdminEditUserDialog,
+ AdminLinkAccountDialog,
+} from "./AdminUserDialogs";
+
+type ApiErrorLike = {
+ response?: {
+ data?: {
+ error?: string;
+ };
+ };
+};
+
+function apiErrorMessage(error: unknown, fallback: string) {
+ return (error as ApiErrorLike).response?.data?.error || fallback;
}
export function AdminSettingsPanel() {
@@ -160,7 +108,7 @@ export function AdminSettingsPanel() {
// Edit user dialog
const [editUserOpen, setEditUserOpen] = useState(false);
- const [editUserTarget, setEditUserTarget] = useState<any | null>(null);
+ const [editUserTarget, setEditUserTarget] = useState<AdminUser | null>(null);
const [editUserLoading, setEditUserLoading] = useState(false);
const [editUserRoles, setEditUserRoles] = useState<UserRole[]>([]);
const [editUserRolesLoading, setEditUserRolesLoading] = useState(false);
@@ -192,8 +140,8 @@ export function AdminSettingsPanel() {
const [exportLoading, setExportLoading] = useState(false);
const [importLoading, setImportLoading] = useState(false);
- const [users, setUsers] = useState<any[]>([]);
- const [sessions, setSessions] = useState<any[]>([]);
+ const [users, setUsers] = useState<AdminUser[]>([]);
+ const [sessions, setSessions] = useState<AdminSession[]>([]);
const [roles, setRoles] = useState<Role[]>([]);
const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
@@ -215,11 +163,21 @@ export function AdminSettingsPanel() {
.catch(() => {})
.finally(() => setEditUserRolesLoading(false));
}
- }, [editUserOpen, editUserTarget?.id]);
+ }, [editUserOpen, editUserTarget]);
function loadUsers() {
getUserList()
- .then(({ users: u }) => setUsers(u))
+ .then(({ users: u }) =>
+ setUsers(
+ u.map((user) => ({
+ id: user.userId,
+ username: user.username,
+ isAdmin: user.is_admin,
+ isOidc: user.is_oidc,
+ passwordHash: user.password_hash,
+ })),
+ ),
+ )
.catch(() => {});
}
@@ -438,8 +396,8 @@ export function AdminSettingsPanel() {
: "",
});
toast.success(t("admin.oidcSaved"));
- } catch (e: any) {
- toast.error(e?.response?.data?.error || t("admin.oidcSaveFailed"));
+ } catch (e: unknown) {
+ toast.error(apiErrorMessage(e, t("admin.oidcSaveFailed")));
} finally {
setOidcSaving(false);
}
@@ -481,25 +439,27 @@ export function AdminSettingsPanel() {
setNewUsername("");
setNewPassword("");
loadUsers();
- } catch (e: any) {
- toast.error(e?.response?.data?.error || t("admin.createUserFailed"));
+ } catch (e: unknown) {
+ toast.error(apiErrorMessage(e, t("admin.createUserFailed")));
} finally {
setCreateUserLoading(false);
}
}
- async function handleToggleAdmin(user: any) {
+ async function handleToggleAdmin(user: AdminUser) {
setEditUserLoading(true);
try {
if (user.isAdmin) {
await removeAdminStatus(user.id);
- setEditUserTarget((prev: any) => ({ ...prev, isAdmin: false }));
+ setEditUserTarget((prev) =>
+ prev ? { ...prev, isAdmin: false } : prev,
+ );
setUsers((prev) =>
prev.map((u) => (u.id === user.id ? { ...u, isAdmin: false } : u)),
);
} else {
await makeUserAdmin(user.id);
- setEditUserTarget((prev: any) => ({ ...prev, isAdmin: true }));
+ setEditUserTarget((prev) => (prev ? { ...prev, isAdmin: true } : prev));
setUsers((prev) =>
prev.map((u) => (u.id === user.id ? { ...u, isAdmin: true } : u)),
);
@@ -532,8 +492,8 @@ export function AdminSettingsPanel() {
toast.success(
t("admin.deleteUserSuccess", { username: editUserTarget.username }),
);
- } catch (e: any) {
- toast.error(e?.response?.data?.error || t("admin.deleteUserFailed"));
+ } catch (e: unknown) {
+ toast.error(apiErrorMessage(e, t("admin.deleteUserFailed")));
} finally {
setEditUserLoading(false);
}
@@ -558,8 +518,8 @@ export function AdminSettingsPanel() {
setNewRoleDescription("");
toast.success(t("admin.createRoleSuccess", { name: displayName }));
loadRoles();
- } catch (e: any) {
- toast.error(e?.response?.data?.error || t("admin.createRoleFailed"));
+ } catch (e: unknown) {
+ toast.error(apiErrorMessage(e, t("admin.createRoleFailed")));
} finally {
setCreateRoleLoading(false);
}
@@ -587,8 +547,8 @@ export function AdminSettingsPanel() {
setNewKeyUserId("");
setNewKeyExpiry("");
toast.success(t("admin.apiKeyCreatedSuccess", { name: created.name }));
- } catch (e: any) {
- toast.error(e?.response?.data?.error || t("admin.apiKeyCreateFailed"));
+ } catch (e: unknown) {
+ toast.error(apiErrorMessage(e, t("admin.apiKeyCreateFailed")));
} finally {
setNewKeyLoading(false);
}
@@ -604,7 +564,7 @@ export function AdminSettingsPanel() {
window.location.hostname === "127.0.0.1");
const apiUrl = isElectron()
- ? `${(window as any).configuredServerUrl}/database/export`
+ ? `${window.configuredServerUrl}/database/export`
: isDev
? `http://localhost:30001/database/export`
: `${window.location.protocol}//${window.location.host}${getBasePath()}/database/export`;
@@ -656,7 +616,7 @@ export function AdminSettingsPanel() {
window.location.hostname === "127.0.0.1");
const apiUrl = isElectron()
- ? `${(window as any).configuredServerUrl}/database/import`
+ ? `${window.configuredServerUrl}/database/import`
: isDev
? `http://localhost:30001/database/import`
: `${window.location.protocol}//${window.location.host}${getBasePath()}/database/import`;
@@ -705,1294 +665,165 @@ export function AdminSettingsPanel() {
return (
<div className="flex flex-col gap-2 p-3">
- {/* General */}
- <AccordionSection
- label={t("admin.sectionGeneral")}
- icon={<Settings className="size-3.5" />}
+ <AdminGeneralSettingsSection
open={openSection === "general"}
onToggle={() => toggle("general")}
- >
- <div className="flex flex-col gap-0 pt-2">
- <SettingRow
- label={t("admin.allowRegistration")}
- description={t("admin.allowRegistrationDesc")}
- >
- <AdminToggle
- on={allowRegistration}
- onToggle={handleToggleRegistration}
- />
- </SettingRow>
- <SettingRow
- label={t("admin.allowPasswordLogin")}
- description={t("admin.allowPasswordLoginDesc")}
- >
- <AdminToggle
- on={allowPasswordLogin}
- onToggle={handleTogglePasswordLogin}
- />
- </SettingRow>
- <SettingRow
- label={t("admin.oidcAutoProvision")}
- description={t("admin.oidcAutoProvisionDesc")}
- >
- <AdminToggle
- on={oidcAutoProvision}
- onToggle={handleToggleOidcAutoProvision}
- />
- </SettingRow>
- <SettingRow
- label={t("admin.allowPasswordReset")}
- description={t("admin.allowPasswordResetDesc")}
- >
- <AdminToggle
- on={allowPasswordReset}
- onToggle={handleTogglePasswordReset}
- />
- </SettingRow>
-
- <div className="flex flex-col gap-2 border-t border-border pt-3 mt-2">
- <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("admin.sessionTimeout")}
- </span>
- <div className="flex items-center gap-2">
- <Input
- type="number"
- min={1}
- max={720}
- value={sessionTimeout}
- onChange={(e) => setSessionTimeout(e.target.value)}
- className="w-20 text-sm"
- />
- <span className="text-xs text-muted-foreground">
- {t("admin.hours")}
- </span>
- <Button
- variant="outline"
- size="sm"
- className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand h-7"
- onClick={handleSaveSessionTimeout}
- >
- {t("common.save")}
- </Button>
- </div>
- <span className="text-[10px] text-muted-foreground">
- {t("admin.sessionTimeoutRange")}
- </span>
- </div>
-
- <div className="flex flex-col gap-2 border-t border-border pt-3 mt-2">
- <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("admin.monitoringDefaults")}
- </span>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.statusCheck")}
- </label>
- <div className="flex items-center gap-2">
- <Input
- type="number"
- value={statusInterval}
- onChange={(e) => setStatusInterval(e.target.value)}
- className="w-20 text-sm"
- />
- <span className="text-xs text-muted-foreground">
- {t("admin.sec")}
- </span>
- </div>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.metrics")}
- </label>
- <div className="flex items-center gap-2">
- <Input
- type="number"
- value={metricsInterval}
- onChange={(e) => setMetricsInterval(e.target.value)}
- className="w-20 text-sm"
- />
- <span className="text-xs text-muted-foreground">
- {t("admin.sec")}
- </span>
- <Button
- variant="outline"
- size="sm"
- className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand h-7"
- onClick={handleSaveMonitoring}
- >
- {t("common.save")}
- </Button>
- </div>
- </div>
- </div>
-
- <div className="flex flex-col gap-2 border-t border-border pt-3 mt-2">
- <SettingRow
- label={t("admin.enableGuacamole")}
- description={t("admin.enableGuacamoleDesc")}
- >
- <AdminToggle on={guacEnabled} onToggle={handleToggleGuacamole} />
- </SettingRow>
- {guacEnabled && (
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.guacdUrl")}
- </label>
- <div className="flex items-center gap-2">
- <Input
- value={guacUrl}
- onChange={(e) => setGuacUrl(e.target.value)}
- placeholder="guacd:4822"
- className="text-sm"
- />
- <Button
- variant="outline"
- size="sm"
- className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand h-7 shrink-0"
- onClick={handleSaveGuacamole}
- >
- Save
- </Button>
- </div>
- </div>
- )}
- </div>
-
- <div className="flex flex-col gap-2 border-t border-border pt-3 mt-2">
- <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("admin.logLevel")}
- </span>
- <div className="flex gap-1.5 flex-wrap">
- {["debug", "info", "warn", "error"].map((l) => (
- <button
- key={l}
- onClick={() => handleSaveLogLevel(l)}
- className={`px-2 py-1 text-[10px] font-semibold border capitalize transition-colors ${logLevel === l ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
- >
- {l}
- </button>
- ))}
- </div>
- </div>
- </div>
- </AccordionSection>
+ allowRegistration={allowRegistration}
+ handleToggleRegistration={handleToggleRegistration}
+ allowPasswordLogin={allowPasswordLogin}
+ handleTogglePasswordLogin={handleTogglePasswordLogin}
+ oidcAutoProvision={oidcAutoProvision}
+ handleToggleOidcAutoProvision={handleToggleOidcAutoProvision}
+ allowPasswordReset={allowPasswordReset}
+ handleTogglePasswordReset={handleTogglePasswordReset}
+ sessionTimeout={sessionTimeout}
+ setSessionTimeout={setSessionTimeout}
+ handleSaveSessionTimeout={handleSaveSessionTimeout}
+ statusInterval={statusInterval}
+ setStatusInterval={setStatusInterval}
+ metricsInterval={metricsInterval}
+ setMetricsInterval={setMetricsInterval}
+ handleSaveMonitoring={handleSaveMonitoring}
+ guacEnabled={guacEnabled}
+ handleToggleGuacamole={handleToggleGuacamole}
+ guacUrl={guacUrl}
+ setGuacUrl={setGuacUrl}
+ handleSaveGuacamole={handleSaveGuacamole}
+ logLevel={logLevel}
+ handleSaveLogLevel={handleSaveLogLevel}
+ />
- {/* OIDC */}
- <AccordionSection
- label={t("admin.sectionOidc")}
- icon={<Shield className="size-3.5" />}
+ <AdminOidcSettingsSection
open={openSection === "oidc"}
onToggle={() => toggle("oidc")}
- >
- <div className="flex flex-col gap-3 pt-3">
- <span className="text-[10px] text-muted-foreground">
- {t("admin.oidcDescription").split("*")[0]}
- <span className="text-accent-brand">*</span>
- {t("admin.oidcDescription").split("*")[1]}
- </span>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.oidcClientId")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- value={oidcClientId}
- onChange={(e) => setOidcClientId(e.target.value)}
- placeholder="your-client-id"
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.oidcClientSecret")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- type="password"
- value={oidcClientSecret}
- onChange={(e) => setOidcClientSecret(e.target.value)}
- placeholder="your-client-secret"
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.oidcAuthUrl")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- value={oidcAuthUrl}
- onChange={(e) => setOidcAuthUrl(e.target.value)}
- placeholder="https://provider/oauth2/auth"
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.oidcIssuerUrl")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- value={oidcIssuerUrl}
- onChange={(e) => setOidcIssuerUrl(e.target.value)}
- placeholder="https://provider"
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.oidcTokenUrl")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- value={oidcTokenUrl}
- onChange={(e) => setOidcTokenUrl(e.target.value)}
- placeholder="https://provider/oauth2/token"
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.oidcUserIdentifier")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- value={oidcUserIdentifier}
- onChange={(e) => setOidcUserIdentifier(e.target.value)}
- placeholder="sub"
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.oidcDisplayName")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- value={oidcDisplayName}
- onChange={(e) => setOidcDisplayName(e.target.value)}
- placeholder="name"
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.oidcScopes")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- value={oidcScopes}
- onChange={(e) => setOidcScopes(e.target.value)}
- placeholder="openid email profile"
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.oidcUserinfoUrl")}
- </label>
- <Input
- value={oidcUserinfoUrl}
- onChange={(e) => setOidcUserinfoUrl(e.target.value)}
- placeholder="https://provider/oauth2/userinfo"
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.oidcAllowedUsers")}
- </label>
- <span className="text-[10px] text-muted-foreground">
- {t("admin.oidcAllowedUsersDesc")}
- </span>
- <textarea
- value={oidcAllowedUsers}
- onChange={(e) => setOidcAllowedUsers(e.target.value)}
- rows={3}
- className="w-full px-2 py-1.5 text-xs bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
- />
- </div>
- <div className="flex gap-2 justify-end">
- <Button
- variant="outline"
- size="sm"
- className="text-xs border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive"
- onClick={handleRemoveOidc}
- >
- <Trash2 className="size-3" />
- {t("admin.removeOidc")}
- </Button>
- <Button
- variant="outline"
- size="sm"
- className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
- onClick={handleSaveOidc}
- disabled={oidcSaving}
- >
- <RefreshCw className="size-3" />
- {oidcSaving ? t("admin.saving") : t("common.save")}
- </Button>
- </div>
- </div>
- </AccordionSection>
+ oidcClientId={oidcClientId}
+ setOidcClientId={setOidcClientId}
+ oidcClientSecret={oidcClientSecret}
+ setOidcClientSecret={setOidcClientSecret}
+ oidcAuthUrl={oidcAuthUrl}
+ setOidcAuthUrl={setOidcAuthUrl}
+ oidcIssuerUrl={oidcIssuerUrl}
+ setOidcIssuerUrl={setOidcIssuerUrl}
+ oidcTokenUrl={oidcTokenUrl}
+ setOidcTokenUrl={setOidcTokenUrl}
+ oidcUserIdentifier={oidcUserIdentifier}
+ setOidcUserIdentifier={setOidcUserIdentifier}
+ oidcDisplayName={oidcDisplayName}
+ setOidcDisplayName={setOidcDisplayName}
+ oidcScopes={oidcScopes}
+ setOidcScopes={setOidcScopes}
+ oidcUserinfoUrl={oidcUserinfoUrl}
+ setOidcUserinfoUrl={setOidcUserinfoUrl}
+ oidcAllowedUsers={oidcAllowedUsers}
+ setOidcAllowedUsers={setOidcAllowedUsers}
+ oidcSaving={oidcSaving}
+ handleRemoveOidc={handleRemoveOidc}
+ handleSaveOidc={handleSaveOidc}
+ />
- {/* Users */}
- <AccordionSection
- label={t("admin.sectionUsers")}
- icon={<User className="size-3.5" />}
+ <AdminUsersSection
open={openSection === "users"}
onToggle={() => toggle("users")}
- >
- <div className="flex flex-col pt-2">
- <div className="flex items-center justify-between py-2 border-b border-border">
- <span className="text-[10px] text-muted-foreground">
- {t("admin.usersCount", { count: users.length })}
- </span>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-muted-foreground hover:text-foreground"
- onClick={loadUsers}
- >
- <RefreshCw className="size-3" />
- </Button>
- <Button
- variant="outline"
- size="sm"
- className="h-6 text-[10px] border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
- onClick={() => setCreateUserOpen(true)}
- >
- <Plus className="size-3" />
- {t("admin.createUser")}
- </Button>
- </div>
- </div>
- {users.map((user) => {
- const authLabel =
- user.isOidc && user.passwordHash
- ? t("admin.authTypeDual")
- : user.isOidc
- ? t("admin.authTypeOidc")
- : t("admin.authTypeLocal");
- return (
- <div
- key={user.id}
- className="flex items-center justify-between py-2.5 border-b border-border last:border-0"
- >
- <div className="flex items-center gap-2 min-w-0">
- <div className="size-6 bg-muted border border-border flex items-center justify-center text-[10px] font-bold shrink-0">
- {user.username[0].toUpperCase()}
- </div>
- <div className="flex flex-col gap-0.5 min-w-0">
- <span className="text-xs font-semibold truncate max-w-[120px]">
- {user.username}
- </span>
- <div className="flex items-center gap-1">
- {user.isAdmin && (
- <span className="text-[9px] font-semibold px-1 py-px border border-accent-brand/40 bg-accent-brand/10 text-accent-brand">
- {t("admin.adminBadge")}
- </span>
- )}
- <span className="text-[9px] font-semibold px-1 py-px border border-border text-muted-foreground">
- {authLabel}
- </span>
- </div>
- </div>
- </div>
- <div className="flex items-center gap-0.5 shrink-0">
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-muted-foreground hover:text-foreground"
- onClick={() => {
- setEditUserTarget(user);
- setEditUserOpen(true);
- }}
- >
- <Pencil className="size-3" />
- </Button>
- {user.isOidc && !user.passwordHash && (
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-muted-foreground hover:text-foreground"
- onClick={() => {
- setLinkAccountTarget({
- id: user.id,
- username: user.username,
- });
- setLinkAccountOpen(true);
- }}
- >
- <Share2 className="size-3" />
- </Button>
- )}
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-muted-foreground hover:text-destructive"
- disabled={user.isAdmin}
- onClick={async () => {
- try {
- await deleteUser(user.username);
- setUsers((prev) =>
- prev.filter((u) => u.id !== user.id),
- );
- toast.success(
- t("admin.deleteUserSuccess", {
- username: user.username,
- }),
- );
- } catch (e: any) {
- toast.error(
- e?.response?.data?.error ||
- t("admin.deleteUserFailed"),
- );
- }
- }}
- >
- <Trash2 className="size-3" />
- </Button>
- </div>
- </div>
- );
- })}
- </div>
- </AccordionSection>
+ users={users}
+ setUsers={setUsers}
+ loadUsers={loadUsers}
+ setCreateUserOpen={setCreateUserOpen}
+ setEditUserTarget={setEditUserTarget}
+ setEditUserOpen={setEditUserOpen}
+ setLinkAccountTarget={setLinkAccountTarget}
+ setLinkAccountOpen={setLinkAccountOpen}
+ />
- {/* Sessions */}
- <AccordionSection
- label={t("admin.sectionSessions")}
- icon={<Activity className="size-3.5" />}
+ <AdminSessionsSection
open={openSection === "sessions"}
onToggle={() => toggle("sessions")}
- >
- <div className="flex flex-col pt-2">
- <div className="flex items-center justify-between py-2 border-b border-border">
- <span className="text-[10px] text-muted-foreground">
- {t("admin.sessionsActive", { count: sessions.length })}
- </span>
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-muted-foreground hover:text-foreground"
- onClick={loadSessions}
- >
- <RefreshCw className="size-3" />
- </Button>
- </div>
- {sessions.map((session) => (
- <div
- key={session.id}
- className="flex items-start justify-between py-2.5 border-b border-border last:border-0 gap-2"
- >
- <div className="flex flex-col gap-0.5 min-w-0 flex-1">
- <div className="flex items-center gap-1.5 flex-wrap">
- <span className="text-xs font-semibold">
- {session.username}
- </span>
- {session.isCurrentSession && (
- <span className="text-[9px] font-semibold px-1 py-px border border-accent-brand/40 bg-accent-brand/10 text-accent-brand">
- {t("admin.youBadge")}
- </span>
- )}
- </div>
- <span className="text-[10px] text-muted-foreground truncate">
- {session.deviceInfo}
- </span>
- <span className="text-[10px] text-muted-foreground">
- {t("admin.sessionActive", { time: session.lastActiveAt })}
- </span>
- <span className="text-[10px] text-muted-foreground">
- {t("admin.sessionExpires", { time: session.expiresAt })}
- </span>
- </div>
- <div className="flex items-center gap-0.5 shrink-0">
- <Button
- variant="ghost"
- size="sm"
- className="text-[10px] text-muted-foreground hover:text-destructive h-6 px-1.5"
- onClick={async () => {
- try {
- await revokeAllUserSessions(session.userId);
- setSessions((prev) =>
- prev.filter((s) => s.userId !== session.userId),
- );
- toast.success(t("admin.revokeAllSessionsSuccess"));
- } catch {
- toast.error(t("admin.revokeAllSessionsFailed"));
- }
- }}
- >
- {t("admin.revokeAll")}
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-muted-foreground hover:text-destructive"
- onClick={async () => {
- try {
- await revokeSession(session.id);
- setSessions((prev) =>
- prev.filter((s) => s.id !== session.id),
- );
- } catch {
- toast.error(t("admin.revokeSessionFailed"));
- }
- }}
- >
- <Trash2 className="size-3" />
- </Button>
- </div>
- </div>
- ))}
- </div>
- </AccordionSection>
+ sessions={sessions}
+ setSessions={setSessions}
+ loadSessions={loadSessions}
+ />
- {/* Roles */}
- <AccordionSection
- label={t("admin.sectionRoles")}
- icon={<KeyRound className="size-3.5" />}
+ <AdminRolesSection
open={openSection === "roles"}
onToggle={() => toggle("roles")}
- >
- <div className="flex flex-col pt-2">
- <div className="flex items-center justify-between py-2 border-b border-border">
- <span className="text-[10px] text-muted-foreground">
- {t("admin.rolesCount", { count: roles.length })}
- </span>
- <Button
- variant="outline"
- size="sm"
- className="h-6 text-[10px] border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
- onClick={() => setShowCreateRole((o) => !o)}
- >
- <Plus className="size-3" />
- {t("admin.createRole")}
- </Button>
- </div>
- {showCreateRole && (
- <div className="flex flex-col gap-2.5 py-3 border-b border-border">
- <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
- {t("admin.newRole")}
- </span>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.roleName")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- placeholder="e.g., developer"
- value={newRoleName}
- onChange={(e) => setNewRoleName(e.target.value)}
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.roleDisplayName")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- placeholder="e.g., Developer"
- value={newRoleDisplayName}
- onChange={(e) => setNewRoleDisplayName(e.target.value)}
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.roleDescription")}
- </label>
- <textarea
- rows={2}
- placeholder={t("common.optional")}
- value={newRoleDescription}
- onChange={(e) => setNewRoleDescription(e.target.value)}
- className="w-full px-2 py-1.5 text-xs bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring"
- />
- </div>
- <div className="flex justify-end gap-2">
- <Button
- variant="ghost"
- size="sm"
- className="text-xs"
- onClick={() => {
- setShowCreateRole(false);
- setNewRoleName("");
- setNewRoleDisplayName("");
- setNewRoleDescription("");
- }}
- >
- {t("common.cancel")}
- </Button>
- <Button
- variant="outline"
- size="sm"
- className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
- onClick={handleCreateRole}
- disabled={createRoleLoading}
- >
- {createRoleLoading
- ? t("admin.creating")
- : t("admin.createRole")}
- </Button>
- </div>
- </div>
- )}
- {roles.map((role) => (
- <div
- key={role.id}
- className="flex items-center justify-between py-2.5 border-b border-border last:border-0"
- >
- <div className="flex flex-col gap-0.5 min-w-0">
- <div className="flex items-center gap-1.5 flex-wrap">
- <span className="text-xs font-semibold truncate">
- {role.displayName}
- </span>
- {role.isSystem ? (
- <span className="text-[9px] font-semibold px-1 py-px border border-border text-muted-foreground">
- {t("admin.systemBadge")}
- </span>
- ) : (
- <span className="text-[9px] font-semibold px-1 py-px border border-accent-brand/40 bg-accent-brand/10 text-accent-brand">
- {t("admin.customBadge")}
- </span>
- )}
- </div>
- <span className="text-[10px] font-mono text-muted-foreground">
- {role.name}
- </span>
- </div>
- {!role.isSystem && (
- <div className="flex items-center gap-0.5 shrink-0">
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-muted-foreground hover:text-destructive"
- onClick={async () => {
- await deleteRole(role.id);
- setRoles((prev) => prev.filter((r) => r.id !== role.id));
- toast.success(
- t("admin.deleteRoleSuccess", {
- name: role.displayName,
- }),
- );
- }}
- >
- <Trash2 className="size-3" />
- </Button>
- </div>
- )}
- </div>
- ))}
- </div>
- </AccordionSection>
+ roles={roles}
+ setRoles={setRoles}
+ showCreateRole={showCreateRole}
+ setShowCreateRole={setShowCreateRole}
+ newRoleName={newRoleName}
+ setNewRoleName={setNewRoleName}
+ newRoleDisplayName={newRoleDisplayName}
+ setNewRoleDisplayName={setNewRoleDisplayName}
+ newRoleDescription={newRoleDescription}
+ setNewRoleDescription={setNewRoleDescription}
+ handleCreateRole={handleCreateRole}
+ createRoleLoading={createRoleLoading}
+ />
- {/* Database */}
- <AccordionSection
- label={t("admin.sectionDatabase")}
- icon={<Database className="size-3.5" />}
+ <AdminDatabaseSection
open={openSection === "database"}
onToggle={() => toggle("database")}
- >
- <div className="flex flex-col gap-3 pt-3">
- <div className="flex flex-col gap-1.5">
- <span className="text-xs font-medium">
- {t("admin.exportDatabase")}
- </span>
- <span className="text-[10px] text-muted-foreground">
- {t("admin.exportDatabaseDesc")}
- </span>
- <Button
- variant="outline"
- size="sm"
- className="self-start text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand mt-1"
- onClick={handleExportDatabase}
- disabled={exportLoading}
- >
- {exportLoading ? t("admin.exporting") : t("admin.export")}
- </Button>
- </div>
- <div className="flex flex-col gap-1.5 border-t border-border pt-3">
- <span className="text-xs font-medium">
- {t("admin.importDatabase")}
- </span>
- <span className="text-[10px] text-muted-foreground">
- {importFile
- ? t("admin.importDatabaseSelected", { name: importFile.name })
- : t("admin.importDatabaseDesc")}
- </span>
- <div className="flex items-center gap-2 mt-1">
- <div className="relative">
- <input
- type="file"
- accept=".sqlite,.db"
- onChange={(e) => setImportFile(e.target.files?.[0] ?? null)}
- className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
- />
- <Button
- variant="outline"
- size="sm"
- className="pointer-events-none text-xs"
- >
- {importFile ? t("admin.changeFile") : t("admin.selectFile")}
- </Button>
- </div>
- {importFile && (
- <Button
- variant="outline"
- size="sm"
- className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
- onClick={handleImportDatabase}
- disabled={importLoading}
- >
- {importLoading ? t("admin.importing") : t("admin.import")}
- </Button>
- )}
- </div>
- </div>
- </div>
- </AccordionSection>
+ importFile={importFile}
+ setImportFile={setImportFile}
+ exportLoading={exportLoading}
+ importLoading={importLoading}
+ handleExportDatabase={handleExportDatabase}
+ handleImportDatabase={handleImportDatabase}
+ />
- {/* API Keys */}
- <AccordionSection
- label={t("admin.sectionApiKeys")}
- icon={<Network className="size-3.5" />}
+ <AdminApiKeysSection
open={openSection === "api-keys"}
onToggle={() => toggle("api-keys")}
- >
- <div className="flex flex-col pt-2">
- <div className="flex items-center justify-between py-2 border-b border-border">
- <span className="text-[10px] text-muted-foreground">
- {t("admin.apiKeysCount", { count: apiKeys.length })}
- </span>
- <div className="flex items-center gap-1">
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-muted-foreground hover:text-foreground"
- onClick={loadApiKeys}
- >
- <RefreshCw className="size-3" />
- </Button>
- <Button
- variant="outline"
- size="sm"
- className="h-6 text-[10px] border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
- onClick={() => {
- setShowCreateKey((o) => !o);
- setCreatedKeyToken(null);
- }}
- >
- <Plus className="size-3" />
- {t("admin.createRole")}
- </Button>
- </div>
- </div>
- {showCreateKey && (
- <div className="flex flex-col gap-2.5 py-3 border-b border-border">
- <span className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
- {t("admin.newApiKey")}
- </span>
- {createdKeyToken ? (
- <div className="flex flex-col gap-2">
- <span className="text-[10px] text-accent-brand font-semibold">
- {t("admin.apiKeyCreatedWarning")}
- </span>
- <div className="flex items-center gap-2 bg-muted/30 border border-border px-2 py-1.5">
- <span className="text-[10px] font-mono flex-1 truncate">
- {createdKeyToken}
- </span>
- <button
- onClick={() => {
- navigator.clipboard.writeText(createdKeyToken);
- toast.info(t("admin.copiedToClipboard"));
- }}
- className="text-muted-foreground hover:text-accent-brand shrink-0"
- >
- <Copy className="size-3.5" />
- </button>
- </div>
- <Button
- variant="ghost"
- size="sm"
- className="text-xs self-end"
- onClick={() => {
- setShowCreateKey(false);
- setCreatedKeyToken(null);
- }}
- >
- {t("admin.done")}
- </Button>
- </div>
- ) : (
- <>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.apiKeyName")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- placeholder="e.g., CI Pipeline"
- value={newKeyName}
- onChange={(e) => setNewKeyName(e.target.value)}
- className="text-xs"
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.apiKeyUser")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <select
- className="px-2 py-1.5 text-xs bg-background border border-border text-foreground outline-none"
- value={newKeyUserId}
- onChange={(e) => setNewKeyUserId(e.target.value)}
- >
- <option value="">{t("admin.apiKeySelectUser")}</option>
- {users.map((u) => (
- <option key={u.id} value={u.id}>
- {u.username}
- </option>
- ))}
- </select>
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
- {t("admin.apiKeyExpiresAt")}
- </label>
- <Input
- type="date"
- value={newKeyExpiry}
- onChange={(e) => setNewKeyExpiry(e.target.value)}
- className="text-xs"
- />
- </div>
- <div className="flex justify-end gap-2">
- <Button
- variant="ghost"
- size="sm"
- className="text-xs"
- onClick={() => setShowCreateKey(false)}
- >
- {t("common.cancel")}
- </Button>
- <Button
- variant="outline"
- size="sm"
- className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
- onClick={handleCreateApiKey}
- disabled={newKeyLoading}
- >
- {newKeyLoading
- ? t("admin.creating")
- : t("admin.createKey")}
- </Button>
- </div>
- </>
- )}
- </div>
- )}
- {apiKeys.map((key) => (
- <div
- key={key.id}
- className="flex items-start justify-between py-2.5 border-b border-border last:border-0 gap-2"
- >
- <div className="flex flex-col gap-0.5 min-w-0 flex-1">
- <div className="flex items-center gap-1.5 flex-wrap">
- <span className="text-xs font-semibold truncate">
- {key.name}
- </span>
- {!key.isActive && (
- <span className="text-[9px] font-semibold px-1 py-px border border-destructive/40 bg-destructive/10 text-destructive">
- {t("admin.revokedBadge")}
- </span>
- )}
- </div>
- <span className="text-[10px] text-muted-foreground">
- {t("admin.apiKeyUser")}: {key.username}
- </span>
- <span className="text-[10px] font-mono text-muted-foreground truncate">
- {key.tokenPrefix}…
- </span>
- <span className="text-[10px] text-muted-foreground">
- {key.createdAt.split("T")[0]} ·{" "}
- {key.expiresAt
- ? key.expiresAt.split("T")[0]
- : t("admin.apiKeyNoExpiry")}
- </span>
- </div>
- <Button
- variant="ghost"
- size="icon"
- className="size-6 text-muted-foreground hover:text-destructive shrink-0"
- onClick={async () => {
- try {
- await deleteApiKey(key.id);
- setApiKeys((prev) => prev.filter((k) => k.id !== key.id));
- toast.success(
- t("admin.revokeKeySuccess", { name: key.name }),
- );
- } catch {
- toast.error(t("admin.revokeKeyFailed"));
- }
- }}
- >
- <Trash2 className="size-3" />
- </Button>
- </div>
- ))}
- </div>
- </AccordionSection>
+ apiKeys={apiKeys}
+ setApiKeys={setApiKeys}
+ loadApiKeys={loadApiKeys}
+ showCreateKey={showCreateKey}
+ setShowCreateKey={setShowCreateKey}
+ createdKeyToken={createdKeyToken}
+ setCreatedKeyToken={setCreatedKeyToken}
+ newKeyName={newKeyName}
+ setNewKeyName={setNewKeyName}
+ newKeyUserId={newKeyUserId}
+ setNewKeyUserId={setNewKeyUserId}
+ newKeyExpiry={newKeyExpiry}
+ setNewKeyExpiry={setNewKeyExpiry}
+ users={users}
+ handleCreateApiKey={handleCreateApiKey}
+ newKeyLoading={newKeyLoading}
+ />
- {/* Create User Dialog */}
- <Dialog open={createUserOpen} onOpenChange={setCreateUserOpen}>
- <DialogContent className="w-[calc(100vw-2rem)] sm:max-w-lg">
- <DialogHeader>
- <DialogTitle className="text-lg font-bold">
- {t("admin.createUserTitle")}
- </DialogTitle>
- <DialogDescription className="text-xs text-muted-foreground">
- {t("admin.createUserDesc")}
- </DialogDescription>
- </DialogHeader>
- <div className="flex flex-col gap-4 mt-1">
- <div className="flex flex-col gap-1.5">
- <label className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
- {t("admin.createUserUsername")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input
- placeholder={t("admin.createUserEnterUsername")}
- value={newUsername}
- onChange={(e) => setNewUsername(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && handleCreateUser()}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
- {t("admin.createUserPassword")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <div className="relative">
- <Input
- type={showNewPassword ? "text" : "password"}
- placeholder="Enter password"
- value={newPassword}
- onChange={(e) => setNewPassword(e.target.value)}
- onKeyDown={(e) => e.key === "Enter" && handleCreateUser()}
- className="pr-9"
- />
- <button
- onClick={() => setShowNewPassword((o) => !o)}
- className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
- >
- {showNewPassword ? (
- <EyeOff className="size-4" />
- ) : (
- <Eye className="size-4" />
- )}
- </button>
- </div>
- <span className="text-xs text-muted-foreground">
- {t("admin.createUserPasswordHint")}
- </span>
- </div>
- </div>
- <div className="flex justify-end gap-2 mt-2">
- <Button
- variant="ghost"
- onClick={() => {
- setCreateUserOpen(false);
- setNewUsername("");
- setNewPassword("");
- }}
- >
- {t("common.cancel")}
- </Button>
- <Button
- variant="outline"
- className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
- onClick={handleCreateUser}
- disabled={createUserLoading}
- >
- {createUserLoading
- ? t("admin.creating")
- : t("admin.createUserSubmit")}
- </Button>
- </div>
- </DialogContent>
- </Dialog>
+ <AdminCreateUserDialog
+ open={createUserOpen}
+ onOpenChange={setCreateUserOpen}
+ newUsername={newUsername}
+ setNewUsername={setNewUsername}
+ newPassword={newPassword}
+ setNewPassword={setNewPassword}
+ showNewPassword={showNewPassword}
+ setShowNewPassword={setShowNewPassword}
+ handleCreateUser={handleCreateUser}
+ createUserLoading={createUserLoading}
+ />
- {/* Edit User Dialog */}
- <Dialog open={editUserOpen} onOpenChange={setEditUserOpen}>
- <DialogContent className="w-[calc(100vw-2rem)] sm:max-w-lg">
- <DialogHeader>
- <DialogTitle className="text-lg font-bold">
- {t("admin.editUserTitle", { username: editUserTarget?.username })}
- </DialogTitle>
- <DialogDescription className="text-xs text-muted-foreground">
- {t("admin.editUserDesc")}
- </DialogDescription>
- </DialogHeader>
- {editUserTarget && (
- <div className="flex flex-col gap-0 mt-1 divide-y divide-border">
- <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-2 py-3">
- <div className="flex flex-col gap-0.5">
- <span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
- {t("admin.editUserUsername")}
- </span>
- <span className="text-sm font-semibold">
- {editUserTarget.username}
- </span>
- </div>
- <div className="flex flex-col gap-0.5">
- <span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
- {t("admin.editUserAuthType")}
- </span>
- <span className="text-sm font-semibold">
- {editUserTarget.isOidc && editUserTarget.passwordHash
- ? t("admin.authTypeDual")
- : editUserTarget.isOidc
- ? t("admin.authTypeOidc")
- : t("admin.authTypeLocal")}
- </span>
- </div>
- <div className="flex flex-col gap-0.5">
- <span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
- {t("admin.editUserAdminStatus")}
- </span>
- <span className="text-sm font-semibold">
- {editUserTarget.isAdmin
- ? t("admin.adminStatusAdministrator")
- : t("admin.adminStatusRegularUser")}
- </span>
- </div>
- <div className="flex flex-col gap-0.5">
- <span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
- {t("admin.editUserUserId")}
- </span>
- <span className="text-xs font-mono text-muted-foreground truncate">
- {editUserTarget.id}
- </span>
- </div>
- </div>
- <div className="flex items-center justify-between py-3">
- <div className="flex flex-col gap-0.5">
- <span className="text-sm font-medium">
- {t("admin.userAdminAccess")}
- </span>
- <span className="text-xs text-muted-foreground">
- {t("admin.userAdminAccessDesc")}
- </span>
- </div>
- <AdminToggle
- on={editUserTarget.isAdmin}
- onToggle={() => handleToggleAdmin(editUserTarget)}
- />
- </div>
- <div className="flex flex-col gap-2 py-3">
- <span className="text-sm font-medium">
- {t("admin.userRoles")}
- </span>
- {editUserRolesLoading ? (
- <span className="text-xs text-muted-foreground">
- {t("newUi.sidebar.snippets.loading")}
- </span>
- ) : (
- <>
- {editUserRoles.length > 0 && (
- <div className="flex flex-wrap gap-1.5">
- {editUserRoles.map((ur) => {
- const roleInfo = roles.find(
- (r) => r.id === ur.roleId,
- );
- const isSystem = roleInfo?.isSystem ?? false;
- return (
- <span
- key={ur.roleId}
- className="inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 border border-accent-brand/40 bg-accent-brand/10 text-accent-brand"
- >
- {ur.roleDisplayName}
- {!isSystem && (
- <button
- onClick={async () => {
- try {
- await removeRoleFromUser(
- editUserTarget.id,
- ur.roleId,
- );
- setEditUserRoles((prev) =>
- prev.filter(
- (r) => r.roleId !== ur.roleId,
- ),
- );
- } catch {
- toast.error(t("admin.removeRoleFailed"));
- }
- }}
- className="hover:text-destructive ml-0.5"
- >
- ×
- </button>
- )}
- </span>
- );
- })}
- </div>
- )}
- {roles.filter(
- (r) =>
- !r.isSystem &&
- !editUserRoles.some((ur) => ur.roleId === r.id),
- ).length > 0 && (
- <div className="flex flex-col gap-1">
- <span className="text-[10px] text-muted-foreground uppercase tracking-widest font-semibold">
- {t("admin.addRole")}
- </span>
- <div className="flex flex-wrap gap-1.5">
- {roles
- .filter(
- (r) =>
- !r.isSystem &&
- !editUserRoles.some((ur) => ur.roleId === r.id),
- )
- .map((r) => (
- <button
- key={r.id}
- onClick={async () => {
- try {
- await assignRoleToUser(
- editUserTarget.id,
- r.id,
- );
- setEditUserRoles((prev) => [
- ...prev,
- {
- userId: editUserTarget.id,
- roleId: r.id,
- roleName: r.name,
- roleDisplayName: r.displayName,
- grantedBy: "",
- grantedByUsername: "",
- grantedAt: new Date().toISOString(),
- },
- ]);
- } catch {
- toast.error(t("admin.assignRoleFailed"));
- }
- }}
- className="inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 border border-border text-muted-foreground hover:border-accent-brand/40 hover:text-accent-brand transition-colors"
- >
- + {r.displayName}
- </button>
- ))}
- </div>
- </div>
- )}
- {editUserRoles.length === 0 &&
- roles.filter((r) => !r.isSystem).length === 0 && (
- <span className="text-xs text-muted-foreground">
- {t("admin.noCustomRoles")}
- </span>
- )}
- </>
- )}
- </div>
- <div className="flex items-center justify-between py-3">
- <div className="flex flex-col gap-0.5">
- <span className="text-sm font-medium">
- {t("admin.revokeAllUserSessions")}
- </span>
- <span className="text-xs text-muted-foreground">
- {t("admin.revokeAllUserSessionsDesc")}
- </span>
- </div>
- <Button
- variant="outline"
- size="sm"
- className="border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive shrink-0 ml-8"
- onClick={() => handleRevokeUserSessions(editUserTarget.id)}
- disabled={editUserLoading}
- >
- {t("admin.revoke")}
- </Button>
- </div>
- <div className="flex flex-col gap-2 py-3">
- <div className="flex items-start gap-2.5 border border-destructive/30 bg-destructive/5 px-3 py-2.5">
- <AlertCircle className="size-4 text-destructive shrink-0 mt-0.5" />
- <span className="text-xs text-destructive">
- {t("admin.deleteUserWarning")}
- </span>
- </div>
- <Button
- variant="outline"
- className="w-full border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive"
- disabled={editUserTarget.isAdmin || editUserLoading}
- onClick={handleDeleteEditUser}
- >
- <Trash2 className="size-3.5" />
- {editUserLoading
- ? t("admin.deleting")
- : t("admin.deleteUser", {
- username: editUserTarget.username,
- })}
- </Button>
- </div>
- </div>
- )}
- </DialogContent>
- </Dialog>
+ <AdminEditUserDialog
+ open={editUserOpen}
+ onOpenChange={setEditUserOpen}
+ editUserTarget={editUserTarget}
+ editUserLoading={editUserLoading}
+ editUserRoles={editUserRoles}
+ editUserRolesLoading={editUserRolesLoading}
+ roles={roles}
+ setEditUserRoles={setEditUserRoles}
+ handleToggleAdmin={handleToggleAdmin}
+ handleRevokeUserSessions={handleRevokeUserSessions}
+ handleDeleteEditUser={handleDeleteEditUser}
+ />
- {/* Link Account Dialog */}
- <Dialog open={linkAccountOpen} onOpenChange={setLinkAccountOpen}>
- <DialogContent className="w-[calc(100vw-2rem)] sm:max-w-lg">
- <DialogHeader>
- <DialogTitle className="text-lg font-bold">
- {t("admin.linkAccountTitle")}
- </DialogTitle>
- <DialogDescription className="text-xs text-muted-foreground">
- {t("admin.linkAccountDesc", {
- username: linkAccountTarget?.username,
- })}
- </DialogDescription>
- </DialogHeader>
- <div className="flex flex-col gap-4 mt-1">
- <div className="flex items-start gap-2.5 border border-destructive/30 bg-destructive/5 px-3 py-2.5">
- <AlertCircle className="size-4 text-destructive shrink-0 mt-0.5" />
- <div className="flex flex-col gap-1 text-xs text-destructive">
- <span>{t("admin.linkAccountWarningTitle")}</span>
- <ul className="list-disc list-inside space-y-0.5 ml-1">
- <li>{t("admin.linkAccountEffect1")}</li>
- <li>{t("admin.linkAccountEffect2")}</li>
- <li>{t("admin.linkAccountEffect3")}</li>
- </ul>
- </div>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
- {t("admin.linkAccountTargetUsername")}{" "}
- <span className="text-accent-brand">*</span>
- </label>
- <Input placeholder={t("admin.linkAccountTargetPlaceholder")} />
- </div>
- </div>
- <div className="flex justify-end gap-2 mt-2">
- <Button variant="ghost" onClick={() => setLinkAccountOpen(false)}>
- {t("common.cancel")}
- </Button>
- <Button
- variant="outline"
- className="border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive"
- >
- {t("admin.linkAccounts")}
- </Button>
- </div>
- </DialogContent>
- </Dialog>
+ <AdminLinkAccountDialog
+ open={linkAccountOpen}
+ onOpenChange={setLinkAccountOpen}
+ linkAccountTarget={linkAccountTarget}
+ setUsers={setUsers}
+ />
</div>
);
}
diff --git a/src/ui/sidebar/AdminSettingsSections.tsx b/src/ui/sidebar/AdminSettingsSections.tsx
new file mode 100644
index 000000000..e5460bf87
--- /dev/null
+++ b/src/ui/sidebar/AdminSettingsSections.tsx
@@ -0,0 +1,547 @@
+import type { Dispatch, SetStateAction } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/button";
+import { Input } from "@/components/input";
+import { SettingRow } from "@/components/section-card";
+import { Database, RefreshCw, Settings, Shield, Trash2 } from "lucide-react";
+import { AccordionSection, AdminToggle } from "./AdminSettingsShared";
+
+type GeneralSettingsSectionProps = {
+ open: boolean;
+ onToggle: () => void;
+ allowRegistration: boolean;
+ handleToggleRegistration: () => void;
+ allowPasswordLogin: boolean;
+ handleTogglePasswordLogin: () => void;
+ oidcAutoProvision: boolean;
+ handleToggleOidcAutoProvision: () => void;
+ allowPasswordReset: boolean;
+ handleTogglePasswordReset: () => void;
+ sessionTimeout: string;
+ setSessionTimeout: Dispatch<SetStateAction<string>>;
+ handleSaveSessionTimeout: () => void;
+ statusInterval: string;
+ setStatusInterval: Dispatch<SetStateAction<string>>;
+ metricsInterval: string;
+ setMetricsInterval: Dispatch<SetStateAction<string>>;
+ handleSaveMonitoring: () => void;
+ guacEnabled: boolean;
+ handleToggleGuacamole: () => void;
+ guacUrl: string;
+ setGuacUrl: Dispatch<SetStateAction<string>>;
+ handleSaveGuacamole: () => void;
+ logLevel: string;
+ handleSaveLogLevel: (level: string) => void;
+};
+
+export function AdminGeneralSettingsSection({
+ open,
+ onToggle,
+ allowRegistration,
+ handleToggleRegistration,
+ allowPasswordLogin,
+ handleTogglePasswordLogin,
+ oidcAutoProvision,
+ handleToggleOidcAutoProvision,
+ allowPasswordReset,
+ handleTogglePasswordReset,
+ sessionTimeout,
+ setSessionTimeout,
+ handleSaveSessionTimeout,
+ statusInterval,
+ setStatusInterval,
+ metricsInterval,
+ setMetricsInterval,
+ handleSaveMonitoring,
+ guacEnabled,
+ handleToggleGuacamole,
+ guacUrl,
+ setGuacUrl,
+ handleSaveGuacamole,
+ logLevel,
+ handleSaveLogLevel,
+}: GeneralSettingsSectionProps) {
+ const { t } = useTranslation();
+
+ return (
+ <AccordionSection
+ label={t("admin.sectionGeneral")}
+ icon={<Settings className="size-3.5" />}
+ open={open}
+ onToggle={onToggle}
+ >
+ <div className="flex flex-col gap-0 pt-2">
+ <SettingRow
+ label={t("admin.allowRegistration")}
+ description={t("admin.allowRegistrationDesc")}
+ >
+ <AdminToggle
+ on={allowRegistration}
+ onToggle={handleToggleRegistration}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("admin.allowPasswordLogin")}
+ description={t("admin.allowPasswordLoginDesc")}
+ >
+ <AdminToggle
+ on={allowPasswordLogin}
+ onToggle={handleTogglePasswordLogin}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("admin.oidcAutoProvision")}
+ description={t("admin.oidcAutoProvisionDesc")}
+ >
+ <AdminToggle
+ on={oidcAutoProvision}
+ onToggle={handleToggleOidcAutoProvision}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("admin.allowPasswordReset")}
+ description={t("admin.allowPasswordResetDesc")}
+ >
+ <AdminToggle
+ on={allowPasswordReset}
+ onToggle={handleTogglePasswordReset}
+ />
+ </SettingRow>
+
+ <div className="flex flex-col gap-2 border-t border-border pt-3 mt-2">
+ <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("admin.sessionTimeout")}
+ </span>
+ <div className="flex items-center gap-2">
+ <Input
+ type="number"
+ min={1}
+ max={720}
+ value={sessionTimeout}
+ onChange={(e) => setSessionTimeout(e.target.value)}
+ className="w-20 text-sm"
+ />
+ <span className="text-xs text-muted-foreground">
+ {t("admin.hours")}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand h-7"
+ onClick={handleSaveSessionTimeout}
+ >
+ {t("common.save")}
+ </Button>
+ </div>
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.sessionTimeoutRange")}
+ </span>
+ </div>
+
+ <div className="flex flex-col gap-2 border-t border-border pt-3 mt-2">
+ <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("admin.monitoringDefaults")}
+ </span>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.statusCheck")}
+ </label>
+ <div className="flex items-center gap-2">
+ <Input
+ type="number"
+ value={statusInterval}
+ onChange={(e) => setStatusInterval(e.target.value)}
+ className="w-20 text-sm"
+ />
+ <span className="text-xs text-muted-foreground">
+ {t("admin.sec")}
+ </span>
+ </div>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.metrics")}
+ </label>
+ <div className="flex items-center gap-2">
+ <Input
+ type="number"
+ value={metricsInterval}
+ onChange={(e) => setMetricsInterval(e.target.value)}
+ className="w-20 text-sm"
+ />
+ <span className="text-xs text-muted-foreground">
+ {t("admin.sec")}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand h-7"
+ onClick={handleSaveMonitoring}
+ >
+ {t("common.save")}
+ </Button>
+ </div>
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-2 border-t border-border pt-3 mt-2">
+ <SettingRow
+ label={t("admin.enableGuacamole")}
+ description={t("admin.enableGuacamoleDesc")}
+ >
+ <AdminToggle on={guacEnabled} onToggle={handleToggleGuacamole} />
+ </SettingRow>
+ {guacEnabled && (
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.guacdUrl")}
+ </label>
+ <div className="flex items-center gap-2">
+ <Input
+ value={guacUrl}
+ onChange={(e) => setGuacUrl(e.target.value)}
+ placeholder="guacd:4822"
+ className="text-sm"
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand h-7 shrink-0"
+ onClick={handleSaveGuacamole}
+ >
+ Save
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+
+ <div className="flex flex-col gap-2 border-t border-border pt-3 mt-2">
+ <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("admin.logLevel")}
+ </span>
+ <div className="flex gap-1.5 flex-wrap">
+ {["debug", "info", "warn", "error"].map((l) => (
+ <button
+ key={l}
+ onClick={() => handleSaveLogLevel(l)}
+ className={`px-2 py-1 text-[10px] font-semibold border capitalize transition-colors ${logLevel === l ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
+ >
+ {l}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ </AccordionSection>
+ );
+}
+
+type OidcSettingsSectionProps = {
+ open: boolean;
+ onToggle: () => void;
+ oidcClientId: string;
+ setOidcClientId: Dispatch<SetStateAction<string>>;
+ oidcClientSecret: string;
+ setOidcClientSecret: Dispatch<SetStateAction<string>>;
+ oidcAuthUrl: string;
+ setOidcAuthUrl: Dispatch<SetStateAction<string>>;
+ oidcIssuerUrl: string;
+ setOidcIssuerUrl: Dispatch<SetStateAction<string>>;
+ oidcTokenUrl: string;
+ setOidcTokenUrl: Dispatch<SetStateAction<string>>;
+ oidcUserIdentifier: string;
+ setOidcUserIdentifier: Dispatch<SetStateAction<string>>;
+ oidcDisplayName: string;
+ setOidcDisplayName: Dispatch<SetStateAction<string>>;
+ oidcScopes: string;
+ setOidcScopes: Dispatch<SetStateAction<string>>;
+ oidcUserinfoUrl: string;
+ setOidcUserinfoUrl: Dispatch<SetStateAction<string>>;
+ oidcAllowedUsers: string;
+ setOidcAllowedUsers: Dispatch<SetStateAction<string>>;
+ oidcSaving: boolean;
+ handleRemoveOidc: () => void;
+ handleSaveOidc: () => void;
+};
+
+export function AdminOidcSettingsSection({
+ open,
+ onToggle,
+ oidcClientId,
+ setOidcClientId,
+ oidcClientSecret,
+ setOidcClientSecret,
+ oidcAuthUrl,
+ setOidcAuthUrl,
+ oidcIssuerUrl,
+ setOidcIssuerUrl,
+ oidcTokenUrl,
+ setOidcTokenUrl,
+ oidcUserIdentifier,
+ setOidcUserIdentifier,
+ oidcDisplayName,
+ setOidcDisplayName,
+ oidcScopes,
+ setOidcScopes,
+ oidcUserinfoUrl,
+ setOidcUserinfoUrl,
+ oidcAllowedUsers,
+ setOidcAllowedUsers,
+ oidcSaving,
+ handleRemoveOidc,
+ handleSaveOidc,
+}: OidcSettingsSectionProps) {
+ const { t } = useTranslation();
+
+ return (
+ <AccordionSection
+ label={t("admin.sectionOidc")}
+ icon={<Shield className="size-3.5" />}
+ open={open}
+ onToggle={onToggle}
+ >
+ <div className="flex flex-col gap-3 pt-3">
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.oidcDescription").split("*")[0]}
+ <span className="text-accent-brand">*</span>
+ {t("admin.oidcDescription").split("*")[1]}
+ </span>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.oidcClientId")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ value={oidcClientId}
+ onChange={(e) => setOidcClientId(e.target.value)}
+ placeholder="your-client-id"
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.oidcClientSecret")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ type="password"
+ value={oidcClientSecret}
+ onChange={(e) => setOidcClientSecret(e.target.value)}
+ placeholder="your-client-secret"
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.oidcAuthUrl")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ value={oidcAuthUrl}
+ onChange={(e) => setOidcAuthUrl(e.target.value)}
+ placeholder="https://provider/oauth2/auth"
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.oidcIssuerUrl")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ value={oidcIssuerUrl}
+ onChange={(e) => setOidcIssuerUrl(e.target.value)}
+ placeholder="https://provider"
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.oidcTokenUrl")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ value={oidcTokenUrl}
+ onChange={(e) => setOidcTokenUrl(e.target.value)}
+ placeholder="https://provider/oauth2/token"
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.oidcUserIdentifier")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ value={oidcUserIdentifier}
+ onChange={(e) => setOidcUserIdentifier(e.target.value)}
+ placeholder="sub"
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.oidcDisplayName")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ value={oidcDisplayName}
+ onChange={(e) => setOidcDisplayName(e.target.value)}
+ placeholder="name"
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.oidcScopes")} <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ value={oidcScopes}
+ onChange={(e) => setOidcScopes(e.target.value)}
+ placeholder="openid email profile"
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.oidcUserinfoUrl")}
+ </label>
+ <Input
+ value={oidcUserinfoUrl}
+ onChange={(e) => setOidcUserinfoUrl(e.target.value)}
+ placeholder="https://provider/oauth2/userinfo"
+ className="text-xs"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
+ {t("admin.oidcAllowedUsers")}
+ </label>
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.oidcAllowedUsersDesc")}
+ </span>
+ <textarea
+ value={oidcAllowedUsers}
+ onChange={(e) => setOidcAllowedUsers(e.target.value)}
+ rows={3}
+ className="w-full px-2 py-1.5 text-xs bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
+ />
+ </div>
+ <div className="flex gap-2 justify-end">
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-xs border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive"
+ onClick={handleRemoveOidc}
+ >
+ <Trash2 className="size-3" />
+ {t("admin.removeOidc")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
+ onClick={handleSaveOidc}
+ disabled={oidcSaving}
+ >
+ <RefreshCw className="size-3" />
+ {oidcSaving ? t("admin.saving") : t("common.save")}
+ </Button>
+ </div>
+ </div>
+ </AccordionSection>
+ );
+}
+
+type DatabaseSectionProps = {
+ open: boolean;
+ onToggle: () => void;
+ importFile: File | null;
+ setImportFile: Dispatch<SetStateAction<File | null>>;
+ exportLoading: boolean;
+ importLoading: boolean;
+ handleExportDatabase: () => void;
+ handleImportDatabase: () => void;
+};
+
+export function AdminDatabaseSection({
+ open,
+ onToggle,
+ importFile,
+ setImportFile,
+ exportLoading,
+ importLoading,
+ handleExportDatabase,
+ handleImportDatabase,
+}: DatabaseSectionProps) {
+ const { t } = useTranslation();
+
+ return (
+ <AccordionSection
+ label={t("admin.sectionDatabase")}
+ icon={<Database className="size-3.5" />}
+ open={open}
+ onToggle={onToggle}
+ >
+ <div className="flex flex-col gap-3 pt-3">
+ <div className="flex flex-col gap-1.5">
+ <span className="text-xs font-medium">
+ {t("admin.exportDatabase")}
+ </span>
+ <span className="text-[10px] text-muted-foreground">
+ {t("admin.exportDatabaseDesc")}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="self-start text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand mt-1"
+ onClick={handleExportDatabase}
+ disabled={exportLoading}
+ >
+ {exportLoading ? t("admin.exporting") : t("admin.export")}
+ </Button>
+ </div>
+ <div className="flex flex-col gap-1.5 border-t border-border pt-3">
+ <span className="text-xs font-medium">
+ {t("admin.importDatabase")}
+ </span>
+ <span className="text-[10px] text-muted-foreground">
+ {importFile
+ ? t("admin.importDatabaseSelected", { name: importFile.name })
+ : t("admin.importDatabaseDesc")}
+ </span>
+ <div className="flex items-center gap-2 mt-1">
+ <div className="relative">
+ <input
+ type="file"
+ accept=".sqlite,.db"
+ onChange={(e) => setImportFile(e.target.files?.[0] ?? null)}
+ className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
+ />
+ <Button
+ variant="outline"
+ size="sm"
+ className="pointer-events-none text-xs"
+ >
+ {importFile ? t("admin.changeFile") : t("admin.selectFile")}
+ </Button>
+ </div>
+ {importFile && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
+ onClick={handleImportDatabase}
+ disabled={importLoading}
+ >
+ {importLoading ? t("admin.importing") : t("admin.import")}
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ </AccordionSection>
+ );
+}
diff --git a/src/ui/sidebar/AdminSettingsShared.tsx b/src/ui/sidebar/AdminSettingsShared.tsx
new file mode 100644
index 000000000..8cbc00c8a
--- /dev/null
+++ b/src/ui/sidebar/AdminSettingsShared.tsx
@@ -0,0 +1,55 @@
+import type React from "react";
+import { ChevronDown } from "lucide-react";
+
+export function AdminToggle({
+ on,
+ onToggle,
+}: {
+ on: boolean;
+ onToggle: () => void;
+}) {
+ return (
+ <button
+ onClick={onToggle}
+ className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center border-2 transition-colors ${on ? "bg-accent-brand border-accent-brand" : "bg-muted border-border"}`}
+ >
+ <span
+ className={`pointer-events-none inline-block h-3 w-3 bg-background shadow-sm transition-transform ${on ? "translate-x-4" : "translate-x-0.5"}`}
+ />
+ </button>
+ );
+}
+
+export function AccordionSection({
+ label,
+ icon,
+ open,
+ onToggle,
+ children,
+}: {
+ label: string;
+ icon: React.ReactNode;
+ open: boolean;
+ onToggle: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="border border-border bg-card overflow-hidden">
+ <button
+ onClick={onToggle}
+ className="flex items-center gap-2 w-full px-3 py-2.5 text-left hover:bg-muted/40 transition-colors"
+ >
+ <span className="text-muted-foreground shrink-0">{icon}</span>
+ <span className="text-xs font-bold uppercase tracking-widest text-foreground flex-1">
+ {label}
+ </span>
+ <ChevronDown
+ className={`size-3.5 text-muted-foreground shrink-0 transition-transform duration-150 ${open ? "rotate-180" : ""}`}
+ />
+ </button>
+ {open && (
+ <div className="border-t border-border px-3 pb-3">{children}</div>
+ )}
+ </div>
+ );
+}
diff --git a/src/ui/sidebar/AdminUserDialogs.tsx b/src/ui/sidebar/AdminUserDialogs.tsx
new file mode 100644
index 000000000..6c30753f1
--- /dev/null
+++ b/src/ui/sidebar/AdminUserDialogs.tsx
@@ -0,0 +1,498 @@
+import { useEffect, useState, type Dispatch, type SetStateAction } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ assignRoleToUser,
+ linkOIDCToPasswordAccount,
+ removeRoleFromUser,
+} from "@/main-axios";
+import type { Role, UserRole } from "@/main-axios";
+import { Button } from "@/components/button";
+import { Input } from "@/components/input";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/dialog";
+import { AlertCircle, Eye, EyeOff, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { AdminToggle } from "./AdminSettingsShared";
+import type { AdminUser } from "./AdminManagementSections";
+
+type ApiErrorLike = {
+ response?: {
+ data?: {
+ error?: string;
+ };
+ };
+ message?: string;
+};
+
+function apiErrorMessage(error: unknown, fallback: string) {
+ const err = error as ApiErrorLike;
+ return err.response?.data?.error || err.message || fallback;
+}
+
+type CreateUserDialogProps = {
+ open: boolean;
+ onOpenChange: Dispatch<SetStateAction<boolean>>;
+ newUsername: string;
+ setNewUsername: Dispatch<SetStateAction<string>>;
+ newPassword: string;
+ setNewPassword: Dispatch<SetStateAction<string>>;
+ showNewPassword: boolean;
+ setShowNewPassword: Dispatch<SetStateAction<boolean>>;
+ handleCreateUser: () => void;
+ createUserLoading: boolean;
+};
+
+export function AdminCreateUserDialog({
+ open,
+ onOpenChange,
+ newUsername,
+ setNewUsername,
+ newPassword,
+ setNewPassword,
+ showNewPassword,
+ setShowNewPassword,
+ handleCreateUser,
+ createUserLoading,
+}: CreateUserDialogProps) {
+ const { t } = useTranslation();
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="w-[calc(100vw-2rem)] sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle className="text-lg font-bold">
+ {t("admin.createUserTitle")}
+ </DialogTitle>
+ <DialogDescription className="text-xs text-muted-foreground">
+ {t("admin.createUserDesc")}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex flex-col gap-4 mt-1">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
+ {t("admin.createUserUsername")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ placeholder={t("admin.createUserEnterUsername")}
+ value={newUsername}
+ onChange={(e) => setNewUsername(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && handleCreateUser()}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
+ {t("admin.createUserPassword")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <div className="relative">
+ <Input
+ type={showNewPassword ? "text" : "password"}
+ placeholder="Enter password"
+ value={newPassword}
+ onChange={(e) => setNewPassword(e.target.value)}
+ onKeyDown={(e) => e.key === "Enter" && handleCreateUser()}
+ className="pr-9"
+ />
+ <button
+ onClick={() => setShowNewPassword((o) => !o)}
+ className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
+ >
+ {showNewPassword ? (
+ <EyeOff className="size-4" />
+ ) : (
+ <Eye className="size-4" />
+ )}
+ </button>
+ </div>
+ <span className="text-xs text-muted-foreground">
+ {t("admin.createUserPasswordHint")}
+ </span>
+ </div>
+ </div>
+ <div className="flex justify-end gap-2 mt-2">
+ <Button
+ variant="ghost"
+ onClick={() => {
+ onOpenChange(false);
+ setNewUsername("");
+ setNewPassword("");
+ }}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="outline"
+ className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand"
+ onClick={handleCreateUser}
+ disabled={createUserLoading}
+ >
+ {createUserLoading
+ ? t("admin.creating")
+ : t("admin.createUserSubmit")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+type EditUserDialogProps = {
+ open: boolean;
+ onOpenChange: Dispatch<SetStateAction<boolean>>;
+ editUserTarget: AdminUser | null;
+ editUserLoading: boolean;
+ editUserRoles: UserRole[];
+ editUserRolesLoading: boolean;
+ roles: Role[];
+ setEditUserRoles: Dispatch<SetStateAction<UserRole[]>>;
+ handleToggleAdmin: (user: AdminUser) => void;
+ handleRevokeUserSessions: (userId: string) => void;
+ handleDeleteEditUser: () => void;
+};
+
+export function AdminEditUserDialog({
+ open,
+ onOpenChange,
+ editUserTarget,
+ editUserLoading,
+ editUserRoles,
+ editUserRolesLoading,
+ roles,
+ setEditUserRoles,
+ handleToggleAdmin,
+ handleRevokeUserSessions,
+ handleDeleteEditUser,
+}: EditUserDialogProps) {
+ const { t } = useTranslation();
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="w-[calc(100vw-2rem)] sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle className="text-lg font-bold">
+ {t("admin.editUserTitle", { username: editUserTarget?.username })}
+ </DialogTitle>
+ <DialogDescription className="text-xs text-muted-foreground">
+ {t("admin.editUserDesc")}
+ </DialogDescription>
+ </DialogHeader>
+ {editUserTarget && (
+ <div className="flex flex-col gap-0 mt-1 divide-y divide-border">
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-2 py-3">
+ <div className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
+ {t("admin.editUserUsername")}
+ </span>
+ <span className="text-sm font-semibold">
+ {editUserTarget.username}
+ </span>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
+ {t("admin.editUserAuthType")}
+ </span>
+ <span className="text-sm font-semibold">
+ {editUserTarget.isOidc && editUserTarget.passwordHash
+ ? t("admin.authTypeDual")
+ : editUserTarget.isOidc
+ ? t("admin.authTypeOidc")
+ : t("admin.authTypeLocal")}
+ </span>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
+ {t("admin.editUserAdminStatus")}
+ </span>
+ <span className="text-sm font-semibold">
+ {editUserTarget.isAdmin
+ ? t("admin.adminStatusAdministrator")
+ : t("admin.adminStatusRegularUser")}
+ </span>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground uppercase tracking-widest font-semibold">
+ {t("admin.editUserUserId")}
+ </span>
+ <span className="text-xs font-mono text-muted-foreground truncate">
+ {editUserTarget.id}
+ </span>
+ </div>
+ </div>
+ <div className="flex items-center justify-between py-3">
+ <div className="flex flex-col gap-0.5">
+ <span className="text-sm font-medium">
+ {t("admin.userAdminAccess")}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {t("admin.userAdminAccessDesc")}
+ </span>
+ </div>
+ <AdminToggle
+ on={editUserTarget.isAdmin}
+ onToggle={() => handleToggleAdmin(editUserTarget)}
+ />
+ </div>
+ <div className="flex flex-col gap-2 py-3">
+ <span className="text-sm font-medium">
+ {t("admin.userRoles")}
+ </span>
+ {editUserRolesLoading ? (
+ <span className="text-xs text-muted-foreground">
+ {t("newUi.sidebar.snippets.loading")}
+ </span>
+ ) : (
+ <>
+ {editUserRoles.length > 0 && (
+ <div className="flex flex-wrap gap-1.5">
+ {editUserRoles.map((ur) => {
+ const roleInfo = roles.find((r) => r.id === ur.roleId);
+ const isSystem = roleInfo?.isSystem ?? false;
+ return (
+ <span
+ key={ur.roleId}
+ className="inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 border border-accent-brand/40 bg-accent-brand/10 text-accent-brand"
+ >
+ {ur.roleDisplayName}
+ {!isSystem && (
+ <button
+ onClick={async () => {
+ try {
+ await removeRoleFromUser(
+ editUserTarget.id,
+ ur.roleId,
+ );
+ setEditUserRoles((prev) =>
+ prev.filter(
+ (r) => r.roleId !== ur.roleId,
+ ),
+ );
+ } catch {
+ toast.error(t("admin.removeRoleFailed"));
+ }
+ }}
+ className="hover:text-destructive ml-0.5"
+ >
+ ×
+ </button>
+ )}
+ </span>
+ );
+ })}
+ </div>
+ )}
+ {roles.filter(
+ (r) =>
+ !r.isSystem &&
+ !editUserRoles.some((ur) => ur.roleId === r.id),
+ ).length > 0 && (
+ <div className="flex flex-col gap-1">
+ <span className="text-[10px] text-muted-foreground uppercase tracking-widest font-semibold">
+ {t("admin.addRole")}
+ </span>
+ <div className="flex flex-wrap gap-1.5">
+ {roles
+ .filter(
+ (r) =>
+ !r.isSystem &&
+ !editUserRoles.some((ur) => ur.roleId === r.id),
+ )
+ .map((r) => (
+ <button
+ key={r.id}
+ onClick={async () => {
+ try {
+ await assignRoleToUser(
+ editUserTarget.id,
+ r.id,
+ );
+ setEditUserRoles((prev) => [
+ ...prev,
+ {
+ userId: editUserTarget.id,
+ roleId: r.id,
+ roleName: r.name,
+ roleDisplayName: r.displayName,
+ grantedBy: "",
+ grantedByUsername: "",
+ grantedAt: new Date().toISOString(),
+ },
+ ]);
+ } catch {
+ toast.error(t("admin.assignRoleFailed"));
+ }
+ }}
+ className="inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 border border-border text-muted-foreground hover:border-accent-brand/40 hover:text-accent-brand transition-colors"
+ >
+ + {r.displayName}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ {editUserRoles.length === 0 &&
+ roles.filter((r) => !r.isSystem).length === 0 && (
+ <span className="text-xs text-muted-foreground">
+ {t("admin.noCustomRoles")}
+ </span>
+ )}
+ </>
+ )}
+ </div>
+ <div className="flex items-center justify-between py-3">
+ <div className="flex flex-col gap-0.5">
+ <span className="text-sm font-medium">
+ {t("admin.revokeAllUserSessions")}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {t("admin.revokeAllUserSessionsDesc")}
+ </span>
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ className="border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive shrink-0 ml-8"
+ onClick={() => handleRevokeUserSessions(editUserTarget.id)}
+ disabled={editUserLoading}
+ >
+ {t("admin.revoke")}
+ </Button>
+ </div>
+ <div className="flex flex-col gap-2 py-3">
+ <div className="flex items-start gap-2.5 border border-destructive/30 bg-destructive/5 px-3 py-2.5">
+ <AlertCircle className="size-4 text-destructive shrink-0 mt-0.5" />
+ <span className="text-xs text-destructive">
+ {t("admin.deleteUserWarning")}
+ </span>
+ </div>
+ <Button
+ variant="outline"
+ className="w-full border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive"
+ disabled={editUserTarget.isAdmin || editUserLoading}
+ onClick={handleDeleteEditUser}
+ >
+ <Trash2 className="size-3.5" />
+ {editUserLoading
+ ? t("admin.deleting")
+ : t("admin.deleteUser", {
+ username: editUserTarget.username,
+ })}
+ </Button>
+ </div>
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+type LinkAccountDialogProps = {
+ open: boolean;
+ onOpenChange: Dispatch<SetStateAction<boolean>>;
+ linkAccountTarget: { id: string; username: string } | null;
+ setUsers: Dispatch<SetStateAction<AdminUser[]>>;
+};
+
+export function AdminLinkAccountDialog({
+ open,
+ onOpenChange,
+ linkAccountTarget,
+ setUsers,
+}: LinkAccountDialogProps) {
+ const { t } = useTranslation();
+ const [targetUsername, setTargetUsername] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+
+ useEffect(() => {
+ if (open) setTargetUsername("");
+ }, [open, linkAccountTarget]);
+
+ const handleSubmit = async () => {
+ const trimmedUsername = targetUsername.trim();
+ if (!linkAccountTarget || !trimmedUsername) return;
+
+ setSubmitting(true);
+ try {
+ await linkOIDCToPasswordAccount(linkAccountTarget.id, trimmedUsername);
+ toast.success(
+ t("admin.linkAccountSuccess", { username: trimmedUsername }),
+ );
+ setUsers((prev) => prev.filter((u) => u.id !== linkAccountTarget.id));
+ setTargetUsername("");
+ onOpenChange(false);
+ } catch (error: unknown) {
+ toast.error(apiErrorMessage(error, t("admin.linkAccountFailed")));
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="w-[calc(100vw-2rem)] sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle className="text-lg font-bold">
+ {t("admin.linkAccountTitle")}
+ </DialogTitle>
+ <DialogDescription className="text-xs text-muted-foreground">
+ {t("admin.linkAccountDesc", {
+ username: linkAccountTarget?.username,
+ })}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex flex-col gap-4 mt-1">
+ <div className="flex items-start gap-2.5 border border-destructive/30 bg-destructive/5 px-3 py-2.5">
+ <AlertCircle className="size-4 text-destructive shrink-0 mt-0.5" />
+ <div className="flex flex-col gap-1 text-xs text-destructive">
+ <span>{t("admin.linkAccountWarningTitle")}</span>
+ <ul className="list-disc list-inside space-y-0.5 ml-1">
+ <li>{t("admin.linkAccountEffect1")}</li>
+ <li>{t("admin.linkAccountEffect2")}</li>
+ <li>{t("admin.linkAccountEffect3")}</li>
+ </ul>
+ </div>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">
+ {t("admin.linkAccountTargetUsername")}{" "}
+ <span className="text-accent-brand">*</span>
+ </label>
+ <Input
+ value={targetUsername}
+ onChange={(e) => setTargetUsername(e.target.value)}
+ placeholder={t("admin.linkAccountTargetPlaceholder")}
+ autoFocus
+ disabled={submitting}
+ />
+ </div>
+ </div>
+ <div className="flex justify-end gap-2 mt-2">
+ <Button
+ variant="ghost"
+ onClick={() => onOpenChange(false)}
+ disabled={submitting}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="outline"
+ className="border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive"
+ disabled={
+ submitting || !linkAccountTarget || !targetUsername.trim()
+ }
+ onClick={handleSubmit}
+ >
+ {submitting
+ ? t("admin.linkAccountInProgress")
+ : t("admin.linkAccounts")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/ui/sidebar/AppRail.tsx b/src/ui/sidebar/AppRail.tsx
index 72d6f0de6..2d0c15320 100644
--- a/src/ui/sidebar/AppRail.tsx
+++ b/src/ui/sidebar/AppRail.tsx
@@ -44,7 +44,6 @@ type RailItem =
function buildRailButtons(
splitMode: SplitMode,
t: (key: string) => string,
- connectionCount: number,
): RailItem[] {
return [
{ view: "hosts", icon: <Server size={16} />, title: t("nav.hosts") },
@@ -97,7 +96,6 @@ export function AppRail({
railView,
sidebarOpen,
splitMode,
- connectionCount,
username,
isAdmin,
profileDropdownOpen,
@@ -109,7 +107,6 @@ export function AppRail({
railView: RailView;
sidebarOpen: boolean;
splitMode: SplitMode;
- connectionCount: number;
username: string;
isAdmin: boolean;
profileDropdownOpen: boolean;
@@ -132,7 +129,7 @@ export function AppRail({
}, []);
const railExpanded = pinned || hovered || profileDropdownOpen;
- const railButtons = buildRailButtons(splitMode, t, connectionCount);
+ const railButtons = buildRailButtons(splitMode, t);
return (
<div
diff --git a/src/ui/sidebar/ConnectionsPanel.tsx b/src/ui/sidebar/ConnectionsPanel.tsx
index 86f74404a..1af6e7564 100644
--- a/src/ui/sidebar/ConnectionsPanel.tsx
+++ b/src/ui/sidebar/ConnectionsPanel.tsx
@@ -1,12 +1,22 @@
import { useState, useEffect, useRef, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { ExternalLink, Plug, Search, X } from "lucide-react";
-import { getActiveSessions, deleteOpenTab, type ActiveSessionInfo, type OpenTabRecord } from "@/main-axios";
+import {
+ getActiveSessions,
+ deleteOpenTab,
+ type ActiveSessionInfo,
+ type OpenTabRecord,
+} from "@/main-axios";
import { tabIcon } from "@/shell/tabUtils";
import type { Tab, TabType } from "@/types/ui-types";
import { Badge } from "@/components/badge";
import { Input } from "@/components/input";
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/tooltip";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/tooltip";
const CONNECTION_TAB_TYPES: TabType[] = [
"terminal",
@@ -128,7 +138,10 @@ function ConnectionRow({
<Tooltip>
<TooltipTrigger asChild>
<button
- onClick={(e) => { e.stopPropagation(); onSwitch(); }}
+ onClick={(e) => {
+ e.stopPropagation();
+ onSwitch();
+ }}
className="size-6 flex items-center justify-center text-muted-foreground/50 hover:text-foreground hover:bg-muted/60 rounded transition-colors"
>
<ExternalLink className="size-3" />
@@ -138,7 +151,10 @@ function ConnectionRow({
</Tooltip>
)}
<button
- onClick={(e) => { e.stopPropagation(); onClose(); }}
+ onClick={(e) => {
+ e.stopPropagation();
+ onClose();
+ }}
className="size-6 flex items-center justify-center text-muted-foreground/50 hover:text-destructive hover:bg-destructive/10 rounded transition-colors"
>
<X className="size-3" />
@@ -178,7 +194,10 @@ export function ConnectionsPanel({
backgroundTabRecords: OpenTabRecord[];
onSwitchToTab: (tabId: string) => void;
onCloseTab: (tabId: string) => void;
- onReopenTab: (record: OpenTabRecord, restoredSessionId: string | null) => void;
+ onReopenTab: (
+ record: OpenTabRecord,
+ restoredSessionId: string | null,
+ ) => void;
onForgetBackground: (recordId: string) => void;
}) {
const { t } = useTranslation();
@@ -187,15 +206,23 @@ export function ConnectionsPanel({
const [search, setSearch] = useState("");
const pollTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
- const openTabs = tabs.filter((tab) => CONNECTION_TAB_TYPES.includes(tab.type));
+ const openTabs = tabs.filter((tab) =>
+ CONNECTION_TAB_TYPES.includes(tab.type),
+ );
// Filter background records to only those not already open in the tab bar
- const openInstanceIds = new Set(tabs.map((t) => t.instanceId).filter(Boolean));
- const backgroundTabs = backgroundTabRecords.filter((r) => !openInstanceIds.has(r.id));
+ const openInstanceIds = new Set(
+ tabs.map((t) => t.instanceId).filter(Boolean),
+ );
+ const backgroundTabs = backgroundTabRecords.filter(
+ (r) => !openInstanceIds.has(r.id),
+ );
const q = search.trim().toLowerCase();
const filteredOpenTabs = q
- ? openTabs.filter((tab) => (tab.host?.name ?? tab.label).toLowerCase().includes(q))
+ ? openTabs.filter((tab) =>
+ (tab.host?.name ?? tab.label).toLowerCase().includes(q),
+ )
: openTabs;
const filteredBackgroundTabs = q
? backgroundTabs.filter((r) => {
@@ -225,13 +252,18 @@ export function ConnectionsPanel({
useEffect(() => {
refresh();
pollTimerRef.current = setInterval(refresh, 5000);
- return () => { if (pollTimerRef.current) clearInterval(pollTimerRef.current); };
+ return () => {
+ if (pollTimerRef.current) clearInterval(pollTimerRef.current);
+ };
}, [refresh]);
- const sessionByInstanceId = new Map(activeSessions.map((s) => [s.tabInstanceId, s]));
+ const sessionByInstanceId = new Map(
+ activeSessions.map((s) => [s.tabInstanceId, s]),
+ );
const hasAnything = openTabs.length > 0 || backgroundTabs.length > 0;
- const hasResults = filteredOpenTabs.length > 0 || filteredBackgroundTabs.length > 0;
+ const hasResults =
+ filteredOpenTabs.length > 0 || filteredBackgroundTabs.length > 0;
if (!hasAnything) {
return (
@@ -265,19 +297,27 @@ export function ConnectionsPanel({
{!hasResults && (
<div className="flex flex-col items-center justify-center gap-2 py-10 text-center">
- <span className="text-xs text-muted-foreground/50">{t("connections.noSearchResults")}</span>
+ <span className="text-xs text-muted-foreground/50">
+ {t("connections.noSearchResults")}
+ </span>
</div>
)}
{filteredOpenTabs.length > 0 && (
<div className="flex flex-col">
- <SectionHeader label={t("connections.sectionOpen")} count={filteredOpenTabs.length} />
+ <SectionHeader
+ label={t("connections.sectionOpen")}
+ count={filteredOpenTabs.length}
+ />
{filteredOpenTabs.map((tab) => {
const isActive = tab.id === activeTabId;
- const liveSession = tab.instanceId ? sessionByInstanceId.get(tab.instanceId) : undefined;
- const isLive = tab.type === "terminal"
- ? (liveSession?.isConnected ?? false)
- : true;
+ const liveSession = tab.instanceId
+ ? sessionByInstanceId.get(tab.instanceId)
+ : undefined;
+ const isLive =
+ tab.type === "terminal"
+ ? (liveSession?.isConnected ?? false)
+ : true;
const duration = liveSession?.createdAt
? formatDuration(now - liveSession.createdAt)
: formatDuration(now - tab.openedAt);
@@ -306,8 +346,13 @@ export function ConnectionsPanel({
)}
{filteredBackgroundTabs.length > 0 && (
- <div className={`flex flex-col ${filteredOpenTabs.length > 0 ? "mt-2" : ""}`}>
- <SectionHeader label={t("connections.sectionBackground")} count={filteredBackgroundTabs.length} />
+ <div
+ className={`flex flex-col ${filteredOpenTabs.length > 0 ? "mt-2" : ""}`}
+ >
+ <SectionHeader
+ label={t("connections.sectionBackground")}
+ count={filteredBackgroundTabs.length}
+ />
<div className="px-3 py-1.5 border-b border-border/40">
<span className="text-[10px] text-muted-foreground/50">
{t("connections.backgroundDesc")}
diff --git a/src/ui/sidebar/CredentialEditorView.tsx b/src/ui/sidebar/CredentialEditorView.tsx
new file mode 100644
index 000000000..637f7640a
--- /dev/null
+++ b/src/ui/sidebar/CredentialEditorView.tsx
@@ -0,0 +1,514 @@
+import { useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Copy, Info, Lock, Upload, X } from "lucide-react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/button";
+import { Input } from "@/components/input";
+import { PasswordInput } from "@/components/password-input";
+import { SectionCard } from "@/components/section-card";
+import {
+ createCredential,
+ generateKeyPair,
+ generatePublicKeyFromPrivate,
+ updateCredential,
+} from "@/main-axios";
+import type { Credential } from "@/types/ui-types";
+
+type CredentialAuthType = Credential["type"];
+type CredentialWithCertificate = Credential & { certPublicKey?: string };
+
+export function CredentialEditorView({
+ credential,
+ activeTab,
+ onBack,
+ onSave,
+}: {
+ credential: Credential | null;
+ activeTab: string;
+ onBack: () => void;
+ onSave: (saved: Record<string, unknown>) => void;
+}) {
+ const [credForm, setCredForm] = useState(() => ({
+ name: credential?.name ?? "",
+ username: credential?.username ?? "",
+ folder: credential?.folder ?? "",
+ description: credential?.description ?? "",
+ tags: credential?.tags ?? ([] as string[]),
+ tagInput: "",
+ type: credential?.type ?? "password",
+ value: credential?.value ?? "",
+ publicKey: credential?.publicKey ?? "",
+ passphrase: credential?.passphrase ?? "",
+ certPublicKey:
+ (credential as CredentialWithCertificate | null)?.certPublicKey ?? "",
+ }));
+ const { t } = useTranslation();
+ const [generatingKey, setGeneratingKey] = useState(false);
+ const [generatingPublicKey, setGeneratingPublicKey] = useState(false);
+ const credFileInputRef = useRef<HTMLInputElement>(null);
+ const certFileInputRef = useRef<HTMLInputElement>(null);
+ const setCredField = <K extends keyof typeof credForm>(
+ k: K,
+ v: (typeof credForm)[K],
+ ) => setCredForm((p) => ({ ...p, [k]: v }));
+ const [saving, setSaving] = useState(false);
+
+ const handleSave = async () => {
+ setSaving(true);
+ try {
+ const data = {
+ name: credForm.name,
+ username: credForm.username,
+ folder: credForm.folder || null,
+ description: credForm.description || null,
+ tags: credForm.tags,
+ authType: credForm.type,
+ password: credForm.type === "password" ? credForm.value : null,
+ key:
+ credForm.type === "key"
+ ? credForm.value === "existing_key"
+ ? undefined
+ : credForm.value || null
+ : null,
+ publicKey: credForm.type === "key" ? credForm.publicKey : null,
+ certPublicKey:
+ credForm.type === "key" ? credForm.certPublicKey || null : null,
+ keyPassword:
+ credForm.type === "key"
+ ? credForm.passphrase === "existing_key_password"
+ ? undefined
+ : credForm.passphrase || null
+ : null,
+ };
+ const saved = credential
+ ? await updateCredential(Number(credential.id), data)
+ : await createCredential(data);
+ toast.success(
+ credential
+ ? t("hosts.credentialUpdated")
+ : t("hosts.credentialCreated"),
+ );
+ window.dispatchEvent(new CustomEvent("termix:credentials-changed"));
+ onSave(saved);
+ } catch {
+ toast.error(t("hosts.failedToSaveCredential"));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const type = credForm.type;
+
+ return (
+ <div className="flex flex-col gap-3">
+ {activeTab === "general" && (
+ <SectionCard
+ title={t("hosts.basicInformation")}
+ icon={<Info className="size-3.5" />}
+ >
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.friendlyNameLabel")}
+ </label>
+ <Input
+ placeholder="e.g. Production SSH Key"
+ value={credForm.name}
+ onChange={(e) => setCredField("name", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.folder")}
+ </label>
+ <Input
+ placeholder="e.g. Server Keys"
+ value={credForm.folder}
+ onChange={(e) => setCredField("folder", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5 col-span-2">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.descriptionLabel")}
+ </label>
+ <Input
+ placeholder="Optional details..."
+ value={credForm.description}
+ onChange={(e) => setCredField("description", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5 col-span-2">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.tags")}
+ </label>
+ <div className="flex flex-wrap items-center gap-1 min-h-9 px-2 py-1 border border-border bg-background focus-within:ring-1 focus-within:ring-ring">
+ {credForm.tags.map((tag) => (
+ <span
+ key={tag}
+ className="flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] bg-muted border border-border/60 text-foreground"
+ >
+ {tag}
+ <button
+ type="button"
+ onClick={() =>
+ setCredField(
+ "tags",
+ credForm.tags.filter((tg) => tg !== tag),
+ )
+ }
+ className="text-muted-foreground hover:text-destructive ml-0.5"
+ >
+ <X className="size-2.5" />
+ </button>
+ </span>
+ ))}
+ <input
+ className="flex-1 min-w-16 text-xs bg-transparent outline-none placeholder:text-muted-foreground/50"
+ placeholder={
+ credForm.tags.length === 0
+ ? t("hosts.addTagsPlaceholder")
+ : ""
+ }
+ value={credForm.tagInput}
+ onChange={(e) => setCredField("tagInput", e.target.value)}
+ onKeyDown={(e) => {
+ if (
+ (e.key === " " || e.key === "Enter") &&
+ credForm.tagInput.trim()
+ ) {
+ e.preventDefault();
+ const tag = credForm.tagInput.trim();
+ if (!credForm.tags.includes(tag))
+ setCredField("tags", [...credForm.tags, tag]);
+ setCredField("tagInput", "");
+ } else if (
+ e.key === "Backspace" &&
+ !credForm.tagInput &&
+ credForm.tags.length > 0
+ ) {
+ setCredField("tags", credForm.tags.slice(0, -1));
+ }
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </SectionCard>
+ )}
+
+ {activeTab === "auth" && (
+ <SectionCard
+ title={t("hosts.authDetailsSection")}
+ icon={<Lock className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.credTypeLabel")}
+ </label>
+ <div className="flex gap-2">
+ {["password", "key"].map((m) => (
+ <button
+ key={m}
+ onClick={() =>
+ setCredField("type", m as CredentialAuthType)
+ }
+ className={`px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${type === m ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
+ >
+ {m === "key"
+ ? t("hosts.sshPrivateKey")
+ : t("hosts.password")}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.username")}
+ </label>
+ <Input
+ placeholder="e.g. root or deploy"
+ value={credForm.username}
+ onChange={(e) => setCredField("username", e.target.value)}
+ />
+ </div>
+ {type === "password" && (
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.password")}
+ </label>
+ <PasswordInput
+ className="h-8 text-xs pr-8"
+ placeholder="••••••••"
+ value={credForm.value}
+ onChange={(e) => setCredField("value", e.target.value)}
+ />
+ </div>
+ )}
+ {type === "key" && (
+ <div className="flex flex-col gap-4">
+ <div className="p-3 border border-border bg-muted/20">
+ <p className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-2">
+ {t("hosts.generateKeyPairTitle")}
+ </p>
+ <p className="text-[10px] text-muted-foreground mb-2">
+ {t("hosts.generateKeyPairDescription")}
+ </p>
+ <div className="flex flex-wrap gap-2">
+ {[
+ { label: "Ed25519", type: "ssh-ed25519" },
+ {
+ label: "ECDSA (nistp256)",
+ type: "ecdsa-sha2-nistp256",
+ },
+ { label: "RSA (2048)", type: "ssh-rsa", bits: 2048 },
+ ].map(({ label, type: keyType, bits }) => (
+ <Button
+ key={label}
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-7 text-[10px] px-2"
+ disabled={generatingKey}
+ onClick={async () => {
+ setGeneratingKey(true);
+ try {
+ const result = await generateKeyPair(
+ keyType as
+ | "ssh-ed25519"
+ | "ssh-rsa"
+ | "ecdsa-sha2-nistp256",
+ bits,
+ credForm.passphrase === "existing_key_password"
+ ? undefined
+ : credForm.passphrase || undefined,
+ );
+ if (result.success) {
+ setCredField("value", result.privateKey);
+ setCredField("publicKey", result.publicKey);
+ toast.success(
+ t("hosts.keyPairGenerated", { label }),
+ );
+ } else {
+ toast.error(
+ result.error ??
+ t("hosts.failedToGenerateKeyPair"),
+ );
+ }
+ } catch {
+ toast.error(t("hosts.failedToGenerateKeyPair"));
+ } finally {
+ setGeneratingKey(false);
+ }
+ }}
+ >
+ {generatingKey
+ ? t("hosts.generatingKey")
+ : t("hosts.generateLabel", { label })}
+ </Button>
+ ))}
+ </div>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.sshPrivateKey")}
+ </label>
+ <button
+ type="button"
+ className="text-[10px] text-accent-brand hover:text-accent-brand/80 flex items-center gap-1"
+ onClick={() => credFileInputRef.current?.click()}
+ >
+ <Upload className="size-3" /> {t("hosts.uploadFileBtn")}
+ </button>
+ </div>
+ <input
+ ref={credFileInputRef}
+ type="file"
+ accept=".pem,.key,.txt,.ppk"
+ className="hidden"
+ onChange={async (e) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ const text = await file.text();
+ setCredField("value", text.trim());
+ e.target.value = "";
+ }}
+ />
+ {credForm.value === "existing_key" && (
+ <div className="px-3 py-2 text-[10px] border border-accent-brand/30 bg-accent-brand/5 text-accent-brand">
+ {t("hosts.keySaved")} — {t("hosts.keyReplaceNotice")}
+ </div>
+ )}
+ <textarea
+ placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
+ rows={8}
+ value={
+ credForm.value === "existing_key" ? "" : credForm.value
+ }
+ onChange={(e) => setCredField("value", e.target.value)}
+ className="w-full px-3 py-2 text-[10px] bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.keyPassphraseOptional")}
+ </label>
+ <PasswordInput
+ className="h-8 text-xs pr-8"
+ placeholder={
+ credForm.passphrase === "existing_key_password"
+ ? t("hosts.keyPassphraseSaved")
+ : "••••••••"
+ }
+ value={
+ credForm.passphrase === "existing_key_password"
+ ? ""
+ : credForm.passphrase
+ }
+ onFocus={() => {
+ if (credForm.passphrase === "existing_key_password")
+ setCredField("passphrase", "");
+ }}
+ onChange={(e) => setCredField("passphrase", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.sshPublicKeyOptional")}
+ </label>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
+ disabled={
+ !credForm.value ||
+ credForm.value === "existing_key" ||
+ generatingPublicKey
+ }
+ onClick={async () => {
+ setGeneratingPublicKey(true);
+ try {
+ const result = await generatePublicKeyFromPrivate(
+ credForm.value,
+ credForm.passphrase === "existing_key_password"
+ ? undefined
+ : credForm.passphrase || undefined,
+ );
+ if (result?.publicKey) {
+ setCredField("publicKey", result.publicKey);
+ toast.success(t("hosts.publicKeyGenerated"));
+ } else {
+ toast.error(t("hosts.failedToGeneratePublicKey"));
+ }
+ } catch {
+ toast.error(t("hosts.failedToGeneratePublicKey"));
+ } finally {
+ setGeneratingPublicKey(false);
+ }
+ }}
+ >
+ {generatingPublicKey
+ ? t("hosts.generatingKey")
+ : t("hosts.generateFromPrivateKey")}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] px-2"
+ disabled={!credForm.publicKey}
+ onClick={() => {
+ navigator.clipboard.writeText(credForm.publicKey ?? "");
+ toast.success(t("hosts.publicKeyCopied"));
+ }}
+ >
+ <Copy className="size-3 mr-1" /> {t("common.copy")}
+ </Button>
+ </div>
+ <textarea
+ placeholder="ssh-rsa AAAAB3Nza..."
+ rows={3}
+ value={credForm.publicKey}
+ onChange={(e) => setCredField("publicKey", e.target.value)}
+ className="w-full px-3 py-2 text-[10px] bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
+ />
+ </div>
+ <div className="flex flex-col gap-1.5 p-3 border border-border bg-muted/20">
+ <div className="flex items-center justify-between">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("credentials.caCertificate")}
+ </label>
+ {credForm.certPublicKey && (
+ <button
+ type="button"
+ className="text-[10px] text-destructive hover:text-destructive/80"
+ onClick={() => setCredField("certPublicKey", "")}
+ >
+ {t("credentials.clearCert")}
+ </button>
+ )}
+ </div>
+ <p className="text-[10px] text-muted-foreground">
+ {t("credentials.caCertificateDescription")}
+ </p>
+ <button
+ type="button"
+ className="text-[10px] text-accent-brand hover:text-accent-brand/80 flex items-center gap-1 self-start"
+ onClick={() => certFileInputRef.current?.click()}
+ >
+ <Upload className="size-3" />{" "}
+ {t("credentials.uploadCertFile")}
+ </button>
+ <input
+ ref={certFileInputRef}
+ type="file"
+ accept=".pub,.txt"
+ className="hidden"
+ onChange={async (e) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ const text = await file.text();
+ setCredField("certPublicKey", text.trim());
+ e.target.value = "";
+ }}
+ />
+ <textarea
+ placeholder={t("credentials.pasteOrUploadCert")}
+ rows={2}
+ value={credForm.certPublicKey}
+ onChange={(e) =>
+ setCredField("certPublicKey", e.target.value)
+ }
+ className="w-full px-3 py-2 text-[10px] bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ </SectionCard>
+ )}
+
+ <div className="flex justify-end gap-3 mt-3">
+ <Button variant="ghost" onClick={onBack} disabled={saving}>
+ {t("hosts.cancelBtn")}
+ </Button>
+ <Button
+ variant="outline"
+ className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand px-8"
+ onClick={handleSave}
+ disabled={saving}
+ >
+ {saving
+ ? t("hosts.savingBtn")
+ : credential
+ ? t("hosts.updateCredentialBtn")
+ : t("hosts.addCredentialBtn")}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/sidebar/HostCredentialList.tsx b/src/ui/sidebar/HostCredentialList.tsx
new file mode 100644
index 000000000..83640c0e3
--- /dev/null
+++ b/src/ui/sidebar/HostCredentialList.tsx
@@ -0,0 +1,413 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ ChevronRight,
+ Copy,
+ FolderOpen,
+ KeyRound,
+ Loader2,
+ Pencil,
+ Plus,
+ Trash2,
+ Upload,
+ X,
+} from "lucide-react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/button";
+import { getCredentialDetails } from "@/main-axios";
+import type { Host, Credential } from "@/types/ui-types";
+
+type CredentialWithCertificate = Credential & { certPublicKey?: string };
+type ConfirmDialog = {
+ message: string;
+ onConfirm: () => void;
+};
+
+function CredentialItem({
+ cred,
+ usedByCount,
+ stripeIndex,
+ onDeploy,
+ onEdit,
+ onDelete,
+}: {
+ cred: Credential;
+ usedByCount: number;
+ stripeIndex: number;
+ onDeploy: () => void;
+ onEdit: () => void;
+ onDelete: () => void;
+}) {
+ const isKey = cred.type === "key";
+
+ return (
+ <div
+ className={`group relative flex items-stretch cursor-default select-none transition-colors hover:bg-muted/40 ${stripeIndex % 2 === 1 ? "bg-muted/20" : ""}`}
+ >
+ {/* Type stripe */}
+ <div className="w-[3px] shrink-0 bg-transparent" />
+
+ <div className="flex flex-col flex-1 min-w-0 px-2.5 pt-2 pb-1.5 gap-1">
+ {/* Name row */}
+ <div className="flex items-center gap-1.5 min-w-0">
+ <span className="text-[13px] font-medium truncate text-foreground leading-none">
+ {cred.name}
+ </span>
+ <span
+ className={`text-[9px] px-1 py-px font-bold border leading-none shrink-0 ${isKey ? "border-accent-brand/30 text-accent-brand" : "border-border/60 text-muted-foreground/60"}`}
+ >
+ {isKey ? "KEY" : "PWD"}
+ </span>
+ </div>
+
+ {/* Username row */}
+ {(cred.username || usedByCount > 0) && (
+ <span className="text-[11px] text-muted-foreground/45 truncate leading-none pl-3">
+ {cred.username}
+ {usedByCount > 0 && (
+ <span className="text-muted-foreground/30">
+ {cred.username ? " · " : ""}
+ {usedByCount}h
+ </span>
+ )}
+ </span>
+ )}
+
+ {/* Tag pills */}
+ {cred.tags && cred.tags.length > 0 && (
+ <div className="flex items-center gap-1 min-w-0 overflow-hidden pl-3">
+ {cred.tags.slice(0, 4).map((tag) => (
+ <span
+ key={tag}
+ className="text-[9px] px-1 py-px border border-border/50 bg-muted/30 text-muted-foreground/60 lowercase shrink-0 leading-none"
+ >
+ {tag}
+ </span>
+ ))}
+ {cred.tags.length > 4 && (
+ <span className="text-[9px] text-muted-foreground/40 shrink-0">
+ +{cred.tags.length - 4}
+ </span>
+ )}
+ </div>
+ )}
+
+ {/* Action tray — slides open on hover */}
+ <div className="overflow-hidden transition-all duration-150 ease-out max-h-0 opacity-0 group-hover:max-h-[60px] group-hover:opacity-100">
+ <div className="flex items-center gap-1 pt-1.5 pl-2 pb-1 border-t border-border/40 mt-0.5">
+ {isKey && (
+ <>
+ <button
+ title="Deploy key to host"
+ onClick={onDeploy}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <Upload className="size-3.5" />
+ </button>
+ <button
+ title="Copy deploy command"
+ onClick={() => {
+ const pubKey = cred.publicKey;
+ if (!pubKey) {
+ toast.error(
+ "No public key available — open the credential editor first",
+ );
+ return;
+ }
+ const cmd = `mkdir -p ~/.ssh && chmod 700 ~/.ssh && echo "${pubKey}" >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`;
+ navigator.clipboard.writeText(cmd);
+ toast.success("Deploy command copied");
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <Copy className="size-3.5" />
+ </button>
+ </>
+ )}
+ <button
+ title="Edit credential"
+ onClick={onEdit}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <Pencil className="size-3.5" />
+ </button>
+ <button
+ title="Delete credential"
+ onClick={onDelete}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 transition-colors"
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function CredentialFolderItem({
+ folder,
+ creds,
+ allHosts,
+ stripeOffset,
+ editingFolderName,
+ editingFolderValue,
+ onEditingFolderNameChange,
+ onEditingFolderValueChange,
+ onRenameFolder,
+ onDeploy,
+ onEdit,
+ onDelete,
+}: {
+ folder: string;
+ creds: Credential[];
+ allHosts: Host[];
+ stripeOffset: number;
+ editingFolderName: string | null;
+ editingFolderValue: string;
+ onEditingFolderNameChange: (name: string | null) => void;
+ onEditingFolderValueChange: (value: string) => void;
+ onRenameFolder: (folder: string, newName: string) => Promise<void>;
+ onDeploy: (cred: Credential) => void;
+ onEdit: (cred: Credential) => void;
+ onDelete: (cred: Credential) => void;
+}) {
+ const [open, setOpen] = useState(true);
+
+ return (
+ <div>
+ <button
+ onClick={() => setOpen((v) => !v)}
+ className={`group/folder flex items-center gap-2 w-full px-3 py-2 hover:bg-muted/50 transition-colors text-left cursor-pointer ${stripeOffset % 2 === 1 ? "bg-muted/20" : ""}`}
+ >
+ <ChevronRight
+ className={`size-3 shrink-0 text-muted-foreground/50 transition-transform ${open ? "rotate-90" : ""}`}
+ />
+ <FolderOpen
+ className={`size-3.5 shrink-0 ${open ? "text-accent-brand" : "text-muted-foreground/60"}`}
+ />
+ {editingFolderName === folder ? (
+ <>
+ <input
+ autoFocus
+ value={editingFolderValue}
+ onChange={(e) => onEditingFolderValueChange(e.target.value)}
+ onBlur={async () => {
+ const newName = editingFolderValue.trim();
+ onEditingFolderNameChange(null);
+ if (newName && newName !== folder) {
+ await onRenameFolder(folder, newName);
+ }
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") e.currentTarget.blur();
+ if (e.key === "Escape") onEditingFolderNameChange(null);
+ }}
+ onClick={(e) => e.stopPropagation()}
+ className="text-[10px] font-semibold bg-background border border-accent-brand/60 px-1 outline-none text-foreground min-w-0 flex-1"
+ />
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onEditingFolderNameChange(null);
+ }}
+ className="text-muted-foreground hover:text-foreground shrink-0"
+ >
+ <X className="size-3" />
+ </button>
+ </>
+ ) : (
+ <>
+ <span className="text-[13px] font-semibold text-foreground/80 truncate flex-1">
+ {folder}
+ </span>
+ <span className="text-[10px] tabular-nums shrink-0 ml-1 text-muted-foreground/40">
+ {creds.length}
+ </span>
+ {folder !== "Uncategorized" && (
+ <span
+ className="opacity-0 group-hover/folder:opacity-100 transition-opacity ml-1 text-muted-foreground/50 hover:text-foreground"
+ onClick={(e) => {
+ e.stopPropagation();
+ onEditingFolderNameChange(folder);
+ onEditingFolderValueChange(folder);
+ }}
+ >
+ <Pencil className="size-2.5" />
+ </span>
+ )}
+ </>
+ )}
+ </button>
+ {open && (
+ <div className="border-l border-border/40 ml-[30px]">
+ {creds.map((cred, i) => {
+ const usedByCount = allHosts.filter(
+ (h) => h.credentialId === cred.id,
+ ).length;
+ return (
+ <CredentialItem
+ key={cred.id}
+ cred={cred}
+ usedByCount={usedByCount}
+ stripeIndex={stripeOffset + 1 + i}
+ onDeploy={() => onDeploy(cred)}
+ onEdit={() => onEdit(cred)}
+ onDelete={() => onDelete(cred)}
+ />
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function HostCredentialList({
+ credentialFolders,
+ filteredCredentials,
+ credentialsLoading,
+ allHosts,
+ editingFolderName,
+ editingFolderValue,
+ onEditingFolderNameChange,
+ onEditingFolderValueChange,
+ onRenameFolder,
+ onDeployCredential,
+ onEditCredential,
+ onDeleteCredential,
+ onAddCredential,
+ onConfirmDialogChange,
+}: {
+ credentialFolders: string[];
+ filteredCredentials: Credential[];
+ credentialsLoading: boolean;
+ allHosts: Host[];
+ editingFolderName: string | null;
+ editingFolderValue: string;
+ onEditingFolderNameChange: (name: string | null) => void;
+ onEditingFolderValueChange: (value: string) => void;
+ onRenameFolder: (folder: string, newName: string) => Promise<void>;
+ onDeployCredential: (cred: Credential) => void;
+ onEditCredential: (cred: Credential) => void;
+ onDeleteCredential: (cred: Credential) => Promise<void>;
+ onAddCredential: () => void;
+ onConfirmDialogChange: (dialog: ConfirmDialog) => void;
+}) {
+ const { t } = useTranslation();
+
+ async function handleDelete(cred: Credential) {
+ onConfirmDialogChange({
+ message: t("hosts.deleteCredentialConfirm", { name: cred.name }),
+ onConfirm: async () => {
+ try {
+ await onDeleteCredential(cred);
+ toast.success(t("hosts.deletedCredential", { name: cred.name }));
+ } catch {
+ toast.error(t("hosts.failedToDeleteCredential2"));
+ }
+ },
+ });
+ }
+
+ async function handleEdit(cred: Credential) {
+ try {
+ const full = await getCredentialDetails(Number(cred.id));
+ onEditCredential({
+ ...cred,
+ value: (
+ full as CredentialWithCertificate & {
+ hasKey?: boolean;
+ hasKeyPassword?: boolean;
+ }
+ ).hasKey
+ ? "existing_key"
+ : ((
+ full as CredentialWithCertificate & {
+ password?: string;
+ }
+ ).password ?? ""),
+ passphrase: (
+ full as CredentialWithCertificate & {
+ hasKeyPassword?: boolean;
+ }
+ ).hasKeyPassword
+ ? "existing_key_password"
+ : "",
+ publicKey:
+ (full as CredentialWithCertificate).certPublicKey ?? cred.publicKey,
+ });
+ } catch {
+ onEditCredential(cred);
+ }
+ }
+
+ let globalStripe = 0;
+
+ return (
+ <div className="flex-1 min-h-0 overflow-y-auto">
+ <div className="flex flex-col">
+ {credentialFolders.map((folder) => {
+ const creds = filteredCredentials.filter(
+ (c) => (c.folder || "Uncategorized") === folder,
+ );
+ if (creds.length === 0) return null;
+ const offset = globalStripe;
+ globalStripe += 1 + creds.length;
+ return (
+ <CredentialFolderItem
+ key={folder}
+ folder={folder}
+ creds={creds}
+ allHosts={allHosts}
+ stripeOffset={offset}
+ editingFolderName={editingFolderName}
+ editingFolderValue={editingFolderValue}
+ onEditingFolderNameChange={onEditingFolderNameChange}
+ onEditingFolderValueChange={onEditingFolderValueChange}
+ onRenameFolder={onRenameFolder}
+ onDeploy={onDeployCredential}
+ onEdit={handleEdit}
+ onDelete={handleDelete}
+ />
+ );
+ })}
+ {credentialsLoading && (
+ <div className="flex flex-col px-2 py-2 space-y-1.5">
+ {[60, 45, 55, 40].map((w, i) => (
+ <div key={i} className="flex items-center gap-2 px-3 py-2">
+ <div className="size-3 rounded-sm bg-muted/50 animate-pulse shrink-0" />
+ <div
+ className="h-3 rounded bg-muted/50 animate-pulse"
+ style={{ width: `${w * 2}px` }}
+ />
+ </div>
+ ))}
+ <div className="flex items-center justify-center gap-2 pt-2 text-muted-foreground/40">
+ <Loader2 className="size-3.5 animate-spin" />
+ <span className="text-xs">{t("hosts.loadingCredentials")}</span>
+ </div>
+ </div>
+ )}
+ {!credentialsLoading && filteredCredentials.length === 0 && (
+ <div className="flex flex-col items-center justify-center py-12 text-center px-4">
+ <KeyRound className="size-8 text-muted-foreground/20 mb-2" />
+ <span className="text-sm font-semibold text-muted-foreground/60">
+ {t("hosts.noCredentialsFound")}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="mt-3 h-7 text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10"
+ onClick={onAddCredential}
+ >
+ <Plus className="size-3 mr-1" />
+ {t("hosts.addCredentialBtn2")}
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/sidebar/HostEditor.tsx b/src/ui/sidebar/HostEditor.tsx
new file mode 100644
index 000000000..89d7ef096
--- /dev/null
+++ b/src/ui/sidebar/HostEditor.tsx
@@ -0,0 +1,1282 @@
+import React, { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ TERMINAL_THEMES,
+ TERMINAL_FONTS,
+ BELL_STYLES,
+ FAST_SCROLL_MODIFIERS,
+ CURSOR_STYLES,
+} from "@/lib/terminal-themes";
+import { Button } from "@/components/button";
+import { Input } from "@/components/input";
+import { PasswordInput } from "@/components/password-input";
+import { Slider } from "@/components/slider";
+import {
+ Globe,
+ Network,
+ Palette,
+ Plus,
+ Shield,
+ Upload,
+ X,
+ Zap,
+} from "lucide-react";
+import { toast } from "sonner";
+import { SectionCard, SettingRow, FakeSwitch } from "@/components/section-card";
+import { TerminalPreview } from "@/features/terminal/TerminalPreview";
+import {
+ createSSHHost,
+ updateSSHHost,
+ getSnippets,
+ subscribeTunnelStatuses,
+ connectTunnel,
+ disconnectTunnel,
+} from "@/main-axios";
+import type { Host } from "@/types/ui-types";
+import type { SSHHost, TunnelStatus } from "@/types";
+import { useTabsSafe } from "@/shell/TabContext";
+import {
+ buildHostEditorPayload,
+ createHostEditorForm,
+ mapSnippetResponse,
+ type HostAuthType,
+ type HostBellStyle,
+ type HostBackspaceMode,
+ type HostCursorStyle,
+ type HostFastScrollModifier,
+ type HostProtocols,
+} from "./HostEditorData";
+import { HostDockerTab, HostFilesTab } from "./HostEditorFeatureTabs";
+import { HostEditorGeneralTab } from "./HostEditorGeneralTab";
+import {
+ HostEditorRdpTab,
+ HostEditorTelnetTab,
+ HostEditorVncTab,
+} from "./HostEditorGuacamoleTabs";
+import { HostStatsTab } from "./HostEditorStatsTab";
+
+export function HostEditor({
+ host,
+ activeTab,
+ onBack,
+ onSave,
+ protocols,
+ onProtocolChange,
+ onTabChange,
+ hosts,
+ credentials,
+}: {
+ host: Host | null;
+ activeTab: string;
+ onBack: () => void;
+ onSave: (saved: SSHHost) => void;
+ protocols: HostProtocols;
+ onProtocolChange: (p: Partial<typeof protocols>) => void;
+ onTabChange: (tab: string) => void;
+ hosts: Host[];
+ credentials: { id: string; name: string; username: string }[];
+}) {
+ const { t } = useTranslation();
+ const { setPreviewTerminalTheme } = useTabsSafe();
+ const [form, setForm] = useState(() => createHostEditorForm(host));
+
+ const setField = <K extends keyof typeof form>(k: K, v: (typeof form)[K]) =>
+ setForm((p) => ({ ...p, [k]: v }));
+
+ const setGuacField = (key: string, value: unknown) =>
+ setField("guacamoleConfig", { ...form.guacamoleConfig, [key]: value });
+
+ const [saving, setSaving] = useState(false);
+ const [snippets, setSnippets] = useState<{ id: number; name: string }[]>([]);
+ const [tunnelStatuses, setTunnelStatuses] = useState<
+ Record<string, TunnelStatus>
+ >({});
+ const [connectingTunnel, setConnectingTunnel] = useState<number | null>(null);
+
+ useEffect(() => {
+ getSnippets()
+ .then((res) => setSnippets(mapSnippetResponse(res)))
+ .catch(() => {});
+ }, []);
+
+ useEffect(() => {
+ if (activeTab !== "tunnels") return;
+ const unsub = subscribeTunnelStatuses((s) => setTunnelStatuses(s));
+ return unsub;
+ }, [activeTab]);
+
+ const handleSave = async () => {
+ setSaving(true);
+ try {
+ const data = buildHostEditorPayload(form, protocols);
+ const saved = host
+ ? await updateSSHHost(Number(host.id), data)
+ : await createSSHHost(data);
+ toast.success(host ? t("hosts.hostUpdated") : t("hosts.hostCreated"));
+ setPreviewTerminalTheme(null);
+ onSave(saved);
+ } catch {
+ toast.error(t("hosts.failedToSave"));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const authMethod = form.authType;
+ const selectedCredential = credentials.find(
+ (c) => c.id === form.credentialId,
+ );
+
+ const handleProtocolToggle = (
+ proto: keyof typeof protocols,
+ value: boolean,
+ ) => {
+ onProtocolChange({ [proto]: value });
+ const tabForProto: Record<string, string> = {
+ enableSsh: "ssh",
+ enableRdp: "rdp",
+ enableVnc: "vnc",
+ enableTelnet: "telnet",
+ };
+ if (!value && activeTab === tabForProto[proto]) onTabChange("general");
+ if (value && tabForProto[proto]) onTabChange(tabForProto[proto]);
+ };
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-col gap-3">
+ {activeTab === "general" && (
+ <HostEditorGeneralTab
+ form={form}
+ setField={setField}
+ protocols={protocols}
+ handleProtocolToggle={handleProtocolToggle}
+ hosts={hosts}
+ host={host}
+ />
+ )}
+
+ {activeTab === "ssh" && (
+ <>
+ <SectionCard
+ title={t("hosts.connectionLabel")}
+ icon={<Globe className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.sshPort")}
+ </label>
+ <Input
+ type="number"
+ placeholder="22"
+ value={form.sshPort}
+ onChange={(e) =>
+ setField("sshPort", Number(e.target.value))
+ }
+ className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </div>
+ </div>
+ </SectionCard>
+ <SectionCard
+ title={t("hosts.authenticationLabel")}
+ icon={<Shield className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.authMethod")}
+ </label>
+ <div className="flex flex-wrap gap-2">
+ {["password", "key", "credential", "none", "opkssh"].map(
+ (m) => (
+ <button
+ key={m}
+ onClick={() => {
+ setField("authType", m as HostAuthType);
+ }}
+ className={`px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${authMethod === m ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
+ >
+ {m}
+ </button>
+ ),
+ )}
+ </div>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border-t border-border pt-4 mt-1">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.username")}
+ </label>
+ <Input
+ placeholder="root"
+ value={form.username}
+ disabled={
+ authMethod === "credential" &&
+ !!selectedCredential?.username &&
+ !form.overrideCredentialUsername
+ }
+ onChange={(e) => setField("username", e.target.value)}
+ />
+ </div>
+ {authMethod === "password" && (
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.password")}
+ </label>
+ <PasswordInput
+ className="h-8 text-xs pr-8"
+ placeholder="••••••••"
+ value={form.password}
+ onChange={(e) => setField("password", e.target.value)}
+ />
+ </div>
+ )}
+ {authMethod === "key" && (
+ <>
+ <div className="flex flex-col gap-1.5 col-span-2">
+ <div className="flex items-center justify-between">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.sshPrivateKey")}
+ </label>
+ <div className="flex gap-1">
+ {(["paste", "upload"] as const).map((tab) => (
+ <button
+ key={tab}
+ type="button"
+ onClick={() => setField("keySubTab", tab)}
+ className={`px-2 py-0.5 text-[9px] font-bold uppercase tracking-widest border transition-colors ${form.keySubTab === tab ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
+ >
+ {tab === "paste"
+ ? t("hosts.keyPasteTab")
+ : t("hosts.keyUploadTab")}
+ </button>
+ ))}
+ </div>
+ </div>
+ {form.keySubTab === "paste" ? (
+ <div className="flex flex-col gap-1.5">
+ {form.key === "existing_key" && (
+ <div className="px-3 py-2 text-[10px] border border-accent-brand/30 bg-accent-brand/5 text-accent-brand">
+ {t("hosts.keySaved")} —{" "}
+ {t("hosts.keyReplaceNotice")}
+ </div>
+ )}
+ <textarea
+ placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
+ rows={5}
+ value={
+ form.key === "existing_key" ? "" : form.key
+ }
+ onChange={(e) => setField("key", e.target.value)}
+ className="w-full px-3 py-2 text-[10px] bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
+ />
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2">
+ <label
+ className={`flex items-center justify-center gap-2 h-16 border-2 border-dashed cursor-pointer transition-colors ${form.key ? "border-accent-brand/40 bg-accent-brand/5 text-accent-brand" : "border-border text-muted-foreground hover:border-accent-brand/30 hover:text-foreground"}`}
+ >
+ <Upload className="size-4" />
+ <span className="text-xs">
+ {form.key === "existing_key"
+ ? t("hosts.keySaved")
+ : form.key
+ ? t("hosts.keyFileLoaded")
+ : t("hosts.keyUploadClick")}
+ </span>
+ <input
+ type="file"
+ accept=".pem,.key,.txt,.ppk"
+ className="hidden"
+ onChange={async (e) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ const text = await file.text();
+ setField("key", text);
+ e.target.value = "";
+ }}
+ />
+ </label>
+ {form.key && (
+ <button
+ type="button"
+ onClick={() => setField("key", "")}
+ className="text-[10px] text-destructive self-start"
+ >
+ {form.key === "existing_key"
+ ? t("hosts.replaceKey")
+ : t("hosts.clearKey")}
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.keyPassphrase")}
+ </label>
+ <PasswordInput
+ className="h-8 text-xs pr-8"
+ placeholder={
+ form.keyPassword === "existing_key_password"
+ ? t("hosts.keyPassphraseSaved")
+ : t("hosts.optional")
+ }
+ value={
+ form.keyPassword === "existing_key_password"
+ ? ""
+ : form.keyPassword
+ }
+ onFocus={() => {
+ if (form.keyPassword === "existing_key_password")
+ setField("keyPassword", "");
+ }}
+ onChange={(e) =>
+ setField("keyPassword", e.target.value)
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.keyTypeLabel")}
+ </label>
+ <select
+ value={form.keyType}
+ onChange={(e) => setField("keyType", e.target.value)}
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ >
+ <option value="auto">{t("hosts.keyTypeAuto")}</option>
+ <option value="ssh-rsa">RSA</option>
+ <option value="ssh-ed25519">Ed25519</option>
+ <option value="ecdsa-sha2-nistp256">
+ ECDSA P-256
+ </option>
+ <option value="ecdsa-sha2-nistp384">
+ ECDSA P-384
+ </option>
+ <option value="ecdsa-sha2-nistp521">
+ ECDSA P-521
+ </option>
+ <option value="ssh-dss">DSA</option>
+ <option value="ssh-rsa-sha2-256">RSA SHA2-256</option>
+ <option value="ssh-rsa-sha2-512">RSA SHA2-512</option>
+ </select>
+ </div>
+ </>
+ )}
+ {authMethod === "credential" && (
+ <>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.storedCredential")}
+ </label>
+ <select
+ value={form.credentialId}
+ onChange={(e) => {
+ const newId = e.target.value;
+ setField("credentialId", newId);
+ if (!form.overrideCredentialUsername) {
+ const cred = credentials.find(
+ (c) => c.id === newId,
+ );
+ if (cred?.username)
+ setField("username", cred.username);
+ }
+ }}
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ >
+ <option value="">
+ {t("hosts.selectACredential")}
+ </option>
+ {credentials.map((c) => (
+ <option key={c.id} value={c.id}>
+ {c.username
+ ? `${c.name} (${c.username})`
+ : c.name}
+ </option>
+ ))}
+ </select>
+ </div>
+ {selectedCredential?.username && (
+ <div className="flex items-center justify-between col-span-2 pt-1">
+ <div className="flex flex-col gap-0.5">
+ <span className="text-xs font-medium">
+ {t("hosts.overrideCredentialUsername")}
+ </span>
+ <span className="text-[10px] text-muted-foreground">
+ {t("hosts.overrideCredentialUsernameDesc")}
+ </span>
+ </div>
+ <FakeSwitch
+ checked={form.overrideCredentialUsername}
+ onChange={(v) => {
+ setField("overrideCredentialUsername", v);
+ if (!v && selectedCredential?.username) {
+ setField(
+ "username",
+ selectedCredential.username,
+ );
+ }
+ }}
+ />
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ <SettingRow
+ label={t("hosts.forceKeyboardInteractiveLabel")}
+ description={t("hosts.forceKeyboardInteractiveShortDesc")}
+ >
+ <FakeSwitch
+ checked={form.forceKeyboardInteractive}
+ onChange={(v) => setField("forceKeyboardInteractive", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.terminalAppearance")}
+ icon={<Palette className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="space-y-2">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.themePreview")}
+ </label>
+ <TerminalPreview
+ theme={form.theme}
+ fontSize={form.fontSize}
+ fontFamily={form.fontFamily}
+ cursorStyle={form.cursorStyle}
+ cursorBlink={form.cursorBlink}
+ letterSpacing={form.letterSpacing}
+ lineHeight={form.lineHeight}
+ />
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.colorTheme")}
+ </label>
+ <select
+ value={form.theme}
+ onChange={(e) => {
+ setField("theme", e.target.value);
+ setPreviewTerminalTheme(e.target.value);
+ }}
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ >
+ {Object.entries(TERMINAL_THEMES)
+ .filter(
+ ([key]) =>
+ key !== "termixDark" && key !== "termixLight",
+ )
+ .map(([key, theme]) => (
+ <option key={key} value={key}>
+ {theme.name}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.fontFamilyLabel")}
+ </label>
+ <select
+ value={form.fontFamily}
+ onChange={(e) => setField("fontFamily", e.target.value)}
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring font-mono"
+ >
+ {TERMINAL_FONTS.map((f) => (
+ <option key={f.value} value={f.value}>
+ {f.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.fontSizeLabel")}
+ </label>
+ <span className="text-[10px] text-muted-foreground tabular-nums">
+ {form.fontSize}px
+ </span>
+ </div>
+ <Slider
+ min={8}
+ max={24}
+ step={1}
+ value={[form.fontSize]}
+ onValueChange={([v]) => setField("fontSize", v)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.cursorStyleLabel")}
+ </label>
+ <select
+ value={form.cursorStyle}
+ onChange={(e) =>
+ setField(
+ "cursorStyle",
+ e.target.value as HostCursorStyle,
+ )
+ }
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ >
+ {CURSOR_STYLES.map((s) => (
+ <option key={s.value} value={s.value}>
+ {s.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.letterSpacingPx")}
+ </label>
+ <span className="text-[10px] text-muted-foreground tabular-nums">
+ {form.letterSpacing}px
+ </span>
+ </div>
+ <Slider
+ min={-2}
+ max={10}
+ step={0.5}
+ value={[form.letterSpacing]}
+ onValueChange={([v]) => setField("letterSpacing", v)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.lineHeightLabel")}
+ </label>
+ <span className="text-[10px] text-muted-foreground tabular-nums">
+ {form.lineHeight.toFixed(1)}
+ </span>
+ </div>
+ <Slider
+ min={1.0}
+ max={2.0}
+ step={0.1}
+ value={[form.lineHeight]}
+ onValueChange={([v]) => setField("lineHeight", v)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.bellStyleLabel")}
+ </label>
+ <select
+ value={form.bellStyle}
+ onChange={(e) =>
+ setField("bellStyle", e.target.value as HostBellStyle)
+ }
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ >
+ {BELL_STYLES.map((b) => (
+ <option key={b.value} value={b.value}>
+ {b.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.backspaceModeLabel")}
+ </label>
+ <select
+ value={form.backspaceMode}
+ onChange={(e) =>
+ setField(
+ "backspaceMode",
+ e.target.value as HostBackspaceMode,
+ )
+ }
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ >
+ <option value="normal">Normal (DEL)</option>
+ <option value="control-h">Control-H (BS)</option>
+ </select>
+ </div>
+ </div>
+ <SettingRow
+ label={t("hosts.cursorBlinking")}
+ description={t("hosts.cursorBlinkingDesc")}
+ >
+ <FakeSwitch
+ checked={form.cursorBlink}
+ onChange={(v) => setField("cursorBlink", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.rightClickSelectsWordLabel")}
+ description={t("hosts.rightClickSelectsWordShortDesc")}
+ >
+ <FakeSwitch
+ checked={form.rightClickSelectsWord}
+ onChange={(v) => setField("rightClickSelectsWord", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.behaviorAndAdvanced")}
+ icon={<Zap className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.scrollbackBufferLabel")}
+ </label>
+ <span className="text-[10px] text-muted-foreground tabular-nums">
+ {form.scrollback.toLocaleString()}{" "}
+ {t("hosts.scrollbackMaxLines")}
+ </span>
+ </div>
+ <Slider
+ min={1000}
+ max={100000}
+ step={1000}
+ value={[form.scrollback]}
+ onValueChange={([v]) => setField("scrollback", v)}
+ />
+ </div>
+ <SettingRow
+ label={t("hosts.sshAgentForwardingLabel")}
+ description={t("hosts.sshAgentForwardingShortDesc")}
+ >
+ <FakeSwitch
+ checked={form.agentForwarding}
+ onChange={(v) => setField("agentForwarding", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.enableAutoMosh")}
+ description={t("hosts.enableAutoMoshDesc")}
+ >
+ <FakeSwitch
+ checked={form.autoMosh}
+ onChange={(v) => setField("autoMosh", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.enableAutoTmux")}
+ description={t("hosts.enableAutoTmuxDesc")}
+ >
+ <FakeSwitch
+ checked={form.autoTmux}
+ onChange={(v) => setField("autoTmux", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.sudoPasswordAutoFillLabel")}
+ description={t("hosts.sudoPasswordAutoFillShortDesc")}
+ >
+ <FakeSwitch
+ checked={form.sudoPasswordAutoFill}
+ onChange={(v) => setField("sudoPasswordAutoFill", v)}
+ />
+ </SettingRow>
+ {form.sudoPasswordAutoFill && (
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.sudoPasswordLabel")}
+ </label>
+ <PasswordInput
+ className="h-8 text-xs pr-8"
+ placeholder="••••••••"
+ value={form.sudoPassword}
+ onChange={(e) => setField("sudoPassword", e.target.value)}
+ />
+ </div>
+ )}
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center justify-between">
+ <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.environmentVariablesLabel")}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
+ onClick={() =>
+ setField("environmentVariables", [
+ ...form.environmentVariables,
+ { key: "", value: "" },
+ ])
+ }
+ >
+ <Plus className="size-3 mr-1" />{" "}
+ {t("hosts.addVariableBtn")}
+ </Button>
+ </div>
+ {form.environmentVariables.length === 0 && (
+ <p className="text-[10px] text-muted-foreground/50">
+ {t("hosts.noEnvVars")}
+ </p>
+ )}
+ <div className="flex flex-col gap-2">
+ {form.environmentVariables.map((ev, i) => (
+ <div key={i} className="flex items-center gap-2">
+ <Input
+ className="h-7 text-xs flex-1"
+ placeholder="KEY"
+ value={ev.key}
+ onChange={(e) => {
+ const updated = [...form.environmentVariables];
+ updated[i] = { ...updated[i], key: e.target.value };
+ setField("environmentVariables", updated);
+ }}
+ />
+ <Input
+ className="h-7 text-xs flex-1"
+ placeholder="VALUE"
+ value={ev.value}
+ onChange={(e) => {
+ const updated = [...form.environmentVariables];
+ updated[i] = {
+ ...updated[i],
+ value: e.target.value,
+ };
+ setField("environmentVariables", updated);
+ }}
+ />
+ <button
+ className="text-destructive"
+ onClick={() =>
+ setField(
+ "environmentVariables",
+ form.environmentVariables.filter(
+ (_, idx) => idx !== i,
+ ),
+ )
+ }
+ >
+ <X className="size-4" />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border-t border-border pt-4">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.fastScrollModifierLabel")}
+ </label>
+ <select
+ value={form.fastScrollModifier}
+ onChange={(e) =>
+ setField(
+ "fastScrollModifier",
+ e.target.value as HostFastScrollModifier,
+ )
+ }
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ >
+ {FAST_SCROLL_MODIFIERS.map((m) => (
+ <option key={m.value} value={m.value}>
+ {m.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.fastScrollSensitivityLabel")}
+ </label>
+ <span className="text-[10px] text-muted-foreground tabular-nums">
+ {form.fastScrollSensitivity}
+ </span>
+ </div>
+ <Slider
+ min={1}
+ max={10}
+ step={1}
+ value={[form.fastScrollSensitivity]}
+ onValueChange={([v]) =>
+ setField("fastScrollSensitivity", v)
+ }
+ />
+ </div>
+ </div>
+ {form.autoMosh && (
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.moshCommandLabel")}
+ </label>
+ <Input
+ placeholder="mosh"
+ value={form.moshCommand}
+ onChange={(e) => setField("moshCommand", e.target.value)}
+ />
+ </div>
+ )}
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border-t border-border pt-4">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.startupSnippetLabel")}
+ </label>
+ <select
+ value={form.startupSnippetId ?? ""}
+ onChange={(e) =>
+ setField(
+ "startupSnippetId",
+ e.target.value ? Number(e.target.value) : null,
+ )
+ }
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ >
+ <option value="">{t("hosts.none")}</option>
+ {snippets.map((s) => (
+ <option key={s.id} value={s.id}>
+ {s.name}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border-t border-border pt-4">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.keepaliveIntervalLabel")}
+ </label>
+ <Input
+ type="number"
+ value={form.keepaliveInterval}
+ onChange={(e) =>
+ setField("keepaliveInterval", Number(e.target.value))
+ }
+ className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.maxKeepaliveMisses")}
+ </label>
+ <Input
+ type="number"
+ value={form.keepaliveCountMax}
+ onChange={(e) =>
+ setField("keepaliveCountMax", Number(e.target.value))
+ }
+ className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </div>
+ </div>
+ </div>
+ </SectionCard>
+ </>
+ )}
+
+ {activeTab === "tunnels" && (
+ <>
+ <SectionCard
+ title={t("hosts.tunnelSettings")}
+ icon={<Network className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <SettingRow
+ label={t("hosts.enableTunneling")}
+ description={t("hosts.enableTunnelingDesc")}
+ >
+ <FakeSwitch
+ checked={form.enableTunnel}
+ onChange={(v) => setField("enableTunnel", v)}
+ />
+ </SettingRow>
+ <div className="text-xs text-muted-foreground p-3 bg-muted/30 border border-border space-y-1">
+ <p>{t("hosts.tunnelRequirementsText")}</p>
+ </div>
+ </div>
+ </SectionCard>
+ <SectionCard
+ title={t("hosts.serverTunnelsSection")}
+ icon={<Network className="size-3.5" />}
+ action={
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
+ onClick={() =>
+ setField("serverTunnels", [
+ ...form.serverTunnels,
+ {
+ mode: "local" as const,
+ sourcePort: 8080,
+ endpointHost: "",
+ endpointPort: 80,
+ bindHost: "127.0.0.1",
+ maxRetries: 3,
+ retryInterval: 10,
+ autoStart: false,
+ },
+ ])
+ }
+ >
+ <Plus className="size-3 mr-1" /> {t("hosts.addTunnelBtn")}
+ </Button>
+ }
+ >
+ <div className="flex flex-col gap-3 py-3">
+ {form.serverTunnels.length === 0 && (
+ <p className="text-[10px] text-muted-foreground/50 px-1">
+ {t("hosts.noTunnelsConfigured")}
+ </p>
+ )}
+ {form.serverTunnels.map((tun, i) => {
+ const tunnelName = `${host?.id ?? "new"}-${i}-${tun.sourcePort}`;
+ const tunnelStatus = tunnelStatuses[tunnelName]?.status as
+ | string
+ | undefined;
+ const isConnected = tunnelStatus === "connected";
+ return (
+ <div
+ key={i}
+ className="flex flex-col gap-3 p-3 border border-border bg-muted/20 relative group"
+ >
+ <div className="flex items-center justify-between mb-1">
+ <div className="flex items-center gap-2">
+ <span className="text-xs font-bold text-muted-foreground">
+ {t("hosts.tunnelLabel", { number: i + 1 })}
+ </span>
+ <div
+ className={`size-1.5 rounded-full shrink-0 ${
+ isConnected
+ ? "bg-accent-brand shadow-[0_0_4px_rgba(251,146,60,0.4)]"
+ : tunnelStatus === "error"
+ ? "bg-red-400"
+ : "bg-muted-foreground/25"
+ }`}
+ title={tunnelStatus ?? "not connected"}
+ />
+ {host && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={connectingTunnel === i}
+ className={`h-6 text-[10px] px-2 ${isConnected ? "border-destructive/40 text-destructive hover:bg-destructive/10" : "border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10"}`}
+ onClick={async () => {
+ setConnectingTunnel(i);
+ try {
+ if (isConnected) {
+ await disconnectTunnel(tunnelName);
+ toast.success(
+ t("hosts.tunnelDisconnected"),
+ );
+ } else {
+ await connectTunnel({
+ name: tunnelName,
+ mode: tun.mode,
+ sourceHostId: Number(host.id),
+ tunnelIndex: i,
+ hostName: host.name,
+ sourceIP: host.ip,
+ sourceSSHPort: host.sshPort ?? host.port,
+ sourceUsername: form.username,
+ sourcePassword:
+ form.password || undefined,
+ sourceAuthMethod: form.authType,
+ sourceSSHKey: form.key || undefined,
+ sourceKeyPassword:
+ form.keyPassword || undefined,
+ sourceCredentialId: form.credentialId
+ ? Number(form.credentialId)
+ : undefined,
+ endpointIP: host.ip,
+ endpointSSHPort:
+ host.sshPort ?? host.port,
+ endpointHost: tun.endpointHost ?? "",
+ endpointUsername: form.username,
+ endpointAuthMethod: form.authType,
+ sourcePort: tun.sourcePort,
+ endpointPort: tun.endpointPort ?? 0,
+ bindHost: tun.bindHost ?? "127.0.0.1",
+ maxRetries: tun.maxRetries ?? 3,
+ retryInterval: tun.retryInterval ?? 10,
+ autoStart: tun.autoStart ?? false,
+ isPinned: false,
+ });
+ toast.success(t("hosts.tunnelConnecting"));
+ }
+ } catch {
+ toast.error(
+ isConnected
+ ? t("hosts.failedToDisconnectTunnel")
+ : t("hosts.failedToConnectTunnel"),
+ );
+ } finally {
+ setConnectingTunnel(null);
+ }
+ }}
+ >
+ {connectingTunnel === i
+ ? "..."
+ : isConnected
+ ? t("hosts.disconnectBtn")
+ : t("hosts.connectBtn")}
+ </Button>
+ )}
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 text-[10px] px-2 text-destructive"
+ onClick={() =>
+ setField(
+ "serverTunnels",
+ form.serverTunnels.filter((_, idx) => idx !== i),
+ )
+ }
+ >
+ {t("common.delete")}
+ </Button>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold text-muted-foreground">
+ {t("hosts.tunnelType")}
+ </label>
+ <div className="flex gap-2">
+ {(["remote", "local", "dynamic"] as const).map(
+ (m) => (
+ <button
+ key={m}
+ onClick={() => {
+ const updated = [...form.serverTunnels];
+ updated[i] = { ...updated[i], mode: m };
+ setField("serverTunnels", updated);
+ }}
+ className={`px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${tun.mode === m ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
+ >
+ {m}
+ </button>
+ ),
+ )}
+ </div>
+ <p className="text-[10px] text-muted-foreground/70 mt-0.5">
+ {tun.mode === "local"
+ ? t("hosts.tunnelModeLocalDesc")
+ : tun.mode === "remote"
+ ? t("hosts.tunnelModeRemoteDesc")
+ : t("hosts.tunnelModeDynamicDesc")}
+ </p>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ {tun.mode !== "dynamic" && (
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-bold text-muted-foreground">
+ {t("hosts.endpointHost")}
+ </label>
+ <select
+ className="h-7 text-xs border border-border bg-background px-2 outline-none focus:ring-1 focus:ring-ring"
+ value={tun.endpointHost ?? ""}
+ onChange={(e) => {
+ const updated = [...form.serverTunnels];
+ updated[i] = {
+ ...updated[i],
+ endpointHost: e.target.value,
+ };
+ setField("serverTunnels", updated);
+ }}
+ >
+ <option value="">{t("hosts.sameHost")}</option>
+ {hosts
+ .filter((h) => h.enableSsh)
+ .map((h) => (
+ <option key={h.id} value={h.ip}>
+ {h.name || h.ip} ({h.ip})
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+ {tun.mode !== "dynamic" && (
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-bold text-muted-foreground">
+ {t("hosts.endpointPort")}
+ </label>
+ <Input
+ className="h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ type="number"
+ value={tun.endpointPort}
+ onChange={(e) => {
+ const updated = [...form.serverTunnels];
+ updated[i] = {
+ ...updated[i],
+ endpointPort: Number(e.target.value),
+ };
+ setField("serverTunnels", updated);
+ }}
+ />
+ </div>
+ )}
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-bold text-muted-foreground">
+ {t("hosts.bindHost")}
+ </label>
+ <Input
+ className="h-7 text-xs"
+ placeholder="127.0.0.1"
+ value={tun.bindHost ?? ""}
+ onChange={(e) => {
+ const updated = [...form.serverTunnels];
+ updated[i] = {
+ ...updated[i],
+ bindHost: e.target.value,
+ };
+ setField("serverTunnels", updated);
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-bold text-muted-foreground">
+ {t("hosts.sourcePort")}
+ </label>
+ <Input
+ className="h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ type="number"
+ value={tun.sourcePort}
+ onChange={(e) => {
+ const updated = [...form.serverTunnels];
+ updated[i] = {
+ ...updated[i],
+ sourcePort: Number(e.target.value),
+ };
+ setField("serverTunnels", updated);
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-bold text-muted-foreground">
+ {t("hosts.maxRetries")}
+ </label>
+ <Input
+ className="h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ type="number"
+ value={tun.maxRetries}
+ onChange={(e) => {
+ const updated = [...form.serverTunnels];
+ updated[i] = {
+ ...updated[i],
+ maxRetries: Number(e.target.value),
+ };
+ setField("serverTunnels", updated);
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[10px] font-bold text-muted-foreground">
+ {t("hosts.retryIntervalS")}
+ </label>
+ <Input
+ className="h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ type="number"
+ value={tun.retryInterval}
+ onChange={(e) => {
+ const updated = [...form.serverTunnels];
+ updated[i] = {
+ ...updated[i],
+ retryInterval: Number(e.target.value),
+ };
+ setField("serverTunnels", updated);
+ }}
+ />
+ </div>
+ </div>
+ <SettingRow
+ label={t("hosts.autoStartLabel")}
+ description={t("hosts.autoStartDesc")}
+ >
+ <FakeSwitch
+ checked={tun.autoStart}
+ onChange={(v) => {
+ const updated = [...form.serverTunnels];
+ updated[i] = { ...updated[i], autoStart: v };
+ setField("serverTunnels", updated);
+ }}
+ />
+ </SettingRow>
+ </div>
+ );
+ })}
+ </div>
+ </SectionCard>
+ </>
+ )}
+
+ {activeTab === "docker" && (
+ <HostDockerTab form={form} setField={setField} />
+ )}
+
+ {activeTab === "files" && (
+ <HostFilesTab form={form} setField={setField} />
+ )}
+
+ {activeTab === "stats" && (
+ <HostStatsTab form={form} setField={setField} snippets={snippets} />
+ )}
+
+ {activeTab === "rdp" && (
+ <HostEditorRdpTab
+ form={form}
+ setField={setField}
+ setGuacField={setGuacField}
+ host={host}
+ />
+ )}
+
+ {activeTab === "vnc" && (
+ <HostEditorVncTab
+ form={form}
+ setField={setField}
+ setGuacField={setGuacField}
+ host={host}
+ />
+ )}
+
+ {activeTab === "telnet" && (
+ <HostEditorTelnetTab
+ form={form}
+ setField={setField}
+ setGuacField={setGuacField}
+ />
+ )}
+ </div>
+
+ <div className="flex justify-end gap-3 mt-3 mb-6">
+ <Button
+ variant="ghost"
+ onClick={() => {
+ setPreviewTerminalTheme(null);
+ onBack();
+ }}
+ disabled={saving}
+ >
+ {t("hosts.guac.cancelBtn")}
+ </Button>
+ <Button
+ variant="outline"
+ className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand px-8"
+ onClick={handleSave}
+ disabled={saving}
+ >
+ {saving
+ ? t("hosts.guac.savingBtn")
+ : host
+ ? t("hosts.guac.updateHostBtn")
+ : t("hosts.guac.addHostBtn")}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/sidebar/HostEditorData.ts b/src/ui/sidebar/HostEditorData.ts
new file mode 100644
index 000000000..f13db226b
--- /dev/null
+++ b/src/ui/sidebar/HostEditorData.ts
@@ -0,0 +1,290 @@
+import { TERMINAL_THEMES } from "@/lib/terminal-themes";
+import type { Host } from "@/types/ui-types";
+import type { SSHHostData } from "@/types";
+
+type HostSocks5ProxyNode = NonNullable<Host["socks5ProxyChain"]>[number];
+
+export type HostProtocols = {
+ enableSsh: boolean;
+ enableRdp: boolean;
+ enableVnc: boolean;
+ enableTelnet: boolean;
+};
+
+export type HostAuthType = Host["authType"];
+export type HostCursorStyle = NonNullable<
+ Host["terminalConfig"]
+>["cursorStyle"];
+export type HostBellStyle = NonNullable<Host["terminalConfig"]>["bellStyle"];
+export type HostBackspaceMode = NonNullable<
+ Host["terminalConfig"]
+>["backspaceMode"];
+export type HostFastScrollModifier = NonNullable<
+ Host["terminalConfig"]
+>["fastScrollModifier"];
+
+type SnippetListItem = {
+ id: number;
+ name?: string;
+ title?: string;
+};
+type SnippetResponse = SnippetListItem[] | { snippets?: SnippetListItem[] };
+
+export function mapSnippetResponse(
+ res: unknown,
+): { id: number; name: string }[] {
+ const snippetRes = res as SnippetResponse;
+ return (
+ Array.isArray(snippetRes) ? snippetRes : (snippetRes.snippets ?? [])
+ ).map((s) => ({
+ id: s.id,
+ name: s.name ?? s.title ?? `Snippet ${s.id}`,
+ }));
+}
+
+export function createHostEditorForm(host: Host | null) {
+ const rawTheme = host?.terminalConfig?.theme;
+ const normalizedTheme =
+ !rawTheme ||
+ ["Termix Dark", "Termix Light", "termixDark", "termixLight"].includes(
+ rawTheme,
+ )
+ ? "termix"
+ : TERMINAL_THEMES[rawTheme]
+ ? rawTheme
+ : "termix";
+
+ return {
+ name: host?.name ?? "",
+ ip: host?.ip ?? "",
+ username: host?.username ?? "",
+ sshPort: host?.sshPort ?? host?.port ?? 22,
+ rdpPort: host?.rdpPort ?? 3389,
+ vncPort: host?.vncPort ?? 5900,
+ telnetPort: host?.telnetPort ?? 23,
+ authType: host?.authType ?? "password",
+ password: host?.password ?? "",
+ key: host?.key ?? (host?.hasKey ? "existing_key" : ""),
+ keyPassword: host?.hasKeyPassword
+ ? "existing_key_password"
+ : (host?.keyPassword ?? ""),
+ keyType: host?.keyType ?? "auto",
+ keySubTab: "paste" as "paste" | "upload",
+ credentialId: host?.credentialId ?? "",
+ overrideCredentialUsername: host?.overrideCredentialUsername ?? false,
+ folder: host?.folder ?? "",
+ tags: host?.tags ?? ([] as string[]),
+ tagInput: "",
+ notes: host?.notes ?? "",
+ pin: host?.pin ?? false,
+ macAddress: host?.macAddress ?? "",
+ useSocks5: host?.useSocks5 ?? false,
+ socks5Host: host?.socks5Host ?? "",
+ socks5Port: host?.socks5Port ?? 1080,
+ socks5Username: host?.socks5Username ?? "",
+ socks5Password: host?.socks5Password ?? "",
+ socks5ProxyMode: ((host?.socks5ProxyChain ?? []).length > 0
+ ? "chain"
+ : "single") as "single" | "chain",
+ socks5ProxyChain: (host?.socks5ProxyChain ?? []) as HostSocks5ProxyNode[],
+ enableTerminal: host?.enableTerminal ?? true,
+ enableFileManager: host?.enableFileManager ?? false,
+ enableDocker: host?.enableDocker ?? false,
+ enableTunnel: host?.enableTunnel ?? false,
+ defaultPath: host?.defaultPath ?? "/",
+ forceKeyboardInteractive: host?.forceKeyboardInteractive ?? false,
+ fontSize: host?.terminalConfig?.fontSize ?? 14,
+ fontFamily:
+ host?.terminalConfig?.fontFamily ?? "Caskaydia Cove Nerd Font Mono",
+ theme: normalizedTheme,
+ cursorStyle: (host?.terminalConfig?.cursorStyle ?? "bar") as
+ | "block"
+ | "underline"
+ | "bar",
+ cursorBlink: host?.terminalConfig?.cursorBlink ?? true,
+ scrollback: host?.terminalConfig?.scrollback ?? 10000,
+ letterSpacing: host?.terminalConfig?.letterSpacing ?? 0,
+ lineHeight: host?.terminalConfig?.lineHeight ?? 1.0,
+ bellStyle: (host?.terminalConfig?.bellStyle ?? "none") as
+ | "none"
+ | "sound"
+ | "visual"
+ | "both",
+ rightClickSelectsWord: host?.terminalConfig?.rightClickSelectsWord ?? false,
+ fastScrollModifier: (host?.terminalConfig?.fastScrollModifier ?? "alt") as
+ | "alt"
+ | "ctrl"
+ | "shift",
+ fastScrollSensitivity: host?.terminalConfig?.fastScrollSensitivity ?? 5,
+ minimumContrastRatio: host?.terminalConfig?.minimumContrastRatio ?? 1,
+ backspaceMode: (host?.terminalConfig?.backspaceMode ?? "normal") as
+ | "normal"
+ | "control-h",
+ startupSnippetId: host?.terminalConfig?.startupSnippetId ?? null,
+ moshCommand: host?.terminalConfig?.moshCommand ?? "",
+ agentForwarding: host?.terminalConfig?.agentForwarding ?? false,
+ autoMosh: host?.terminalConfig?.autoMosh ?? false,
+ autoTmux: host?.terminalConfig?.autoTmux ?? false,
+ sudoPasswordAutoFill: host?.terminalConfig?.sudoPasswordAutoFill ?? false,
+ sudoPassword: host?.terminalConfig?.sudoPassword ?? "",
+ keepaliveInterval: host?.terminalConfig?.keepaliveInterval ?? 60,
+ keepaliveCountMax: host?.terminalConfig?.keepaliveCountMax ?? 5,
+ environmentVariables:
+ host?.terminalConfig?.environmentVariables ??
+ ([] as { key: string; value: string }[]),
+ serverTunnels: host?.serverTunnels ?? ([] as Host["serverTunnels"]),
+ jumpHosts: host?.jumpHosts ?? ([] as { hostId: string }[]),
+ portKnockSequence:
+ host?.portKnockSequence ??
+ ([] as { port: number; protocol: "tcp" | "udp"; delay: number }[]),
+ quickActions:
+ host?.quickActions ?? ([] as { name: string; snippetId: string }[]),
+ rdpUser: host?.rdpUser ?? "",
+ rdpPassword: host?.rdpPassword ?? "",
+ domain: host?.domain ?? "",
+ security: host?.security ?? "",
+ ignoreCert: host?.ignoreCert ?? false,
+ vncPassword: host?.vncPassword ?? "",
+ vncUser: host?.vncUser ?? "",
+ telnetUser: host?.telnetUser ?? "",
+ telnetPassword: host?.telnetPassword ?? "",
+ guacamoleConfig: host?.guacamoleConfig ?? {},
+ statsConfig: host?.statsConfig ?? {
+ statusCheckEnabled: true,
+ statusCheckInterval: 60,
+ useGlobalStatusInterval: true,
+ metricsEnabled: true,
+ metricsInterval: 30,
+ useGlobalMetricsInterval: true,
+ enabledWidgets: [
+ "cpu",
+ "memory",
+ "disk",
+ "network",
+ "uptime",
+ "system",
+ "login_stats",
+ "processes",
+ "ports",
+ "firewall",
+ ],
+ },
+ };
+}
+
+export type HostEditorForm = ReturnType<typeof createHostEditorForm>;
+
+export function buildHostEditorPayload(
+ form: HostEditorForm,
+ protocols: HostProtocols,
+): SSHHostData {
+ return {
+ connectionType: protocols.enableSsh
+ ? "ssh"
+ : protocols.enableRdp
+ ? "rdp"
+ : protocols.enableVnc
+ ? "vnc"
+ : "telnet",
+ name: form.name,
+ ip: form.ip,
+ port: protocols.enableSsh
+ ? Number(form.sshPort)
+ : protocols.enableRdp
+ ? Number(form.rdpPort)
+ : protocols.enableVnc
+ ? Number(form.vncPort)
+ : Number(form.telnetPort),
+ username: form.username,
+ folder: form.folder,
+ tags: form.tags,
+ pin: form.pin,
+ authType: form.authType,
+ password: form.password || null,
+ key: form.key === "existing_key" ? undefined : form.key || null,
+ keyPassword:
+ form.keyPassword === "existing_key_password"
+ ? undefined
+ : form.keyPassword || null,
+ keyType: form.keyType !== "auto" ? form.keyType : null,
+ credentialId: form.credentialId ? Number(form.credentialId) : null,
+ overrideCredentialUsername: form.overrideCredentialUsername,
+ notes: form.notes,
+ macAddress: form.macAddress || null,
+ enableTerminal: form.enableTerminal,
+ enableTunnel: form.enableTunnel,
+ enableFileManager: form.enableFileManager,
+ enableDocker: form.enableDocker,
+ defaultPath: form.defaultPath || "/",
+ useSocks5: form.useSocks5,
+ socks5Host:
+ form.socks5ProxyMode === "single" ? form.socks5Host || null : null,
+ socks5Port:
+ form.socks5ProxyMode === "single" ? form.socks5Port || null : null,
+ socks5Username:
+ form.socks5ProxyMode === "single" ? form.socks5Username || null : null,
+ socks5Password:
+ form.socks5ProxyMode === "single" ? form.socks5Password || null : null,
+ socks5ProxyChain:
+ form.socks5ProxyMode === "chain" ? form.socks5ProxyChain : null,
+ enableSsh: protocols.enableSsh,
+ enableRdp: protocols.enableRdp,
+ enableVnc: protocols.enableVnc,
+ enableTelnet: protocols.enableTelnet,
+ sshPort: Number(form.sshPort),
+ rdpPort: Number(form.rdpPort),
+ vncPort: Number(form.vncPort),
+ telnetPort: Number(form.telnetPort),
+ forceKeyboardInteractive: form.forceKeyboardInteractive,
+ rdpUser: form.rdpUser || null,
+ rdpPassword: form.rdpPassword || null,
+ rdpDomain: form.domain || null,
+ rdpSecurity: form.security || null,
+ rdpIgnoreCert: form.ignoreCert,
+ vncPassword: form.vncPassword || null,
+ vncUser: form.vncUser || null,
+ telnetUser: form.telnetUser || null,
+ telnetPassword: form.telnetPassword || null,
+ jumpHosts: form.jumpHosts,
+ portKnockSequence: form.portKnockSequence,
+ tunnelConnections: form.serverTunnels,
+ quickActions: form.quickActions.map((a) => ({
+ name: a.name,
+ snippetId: Number(a.snippetId),
+ })),
+ statsConfig: form.statsConfig,
+ guacamoleConfig:
+ (protocols.enableRdp || protocols.enableVnc || protocols.enableTelnet) &&
+ Object.keys(form.guacamoleConfig).length > 0
+ ? form.guacamoleConfig
+ : null,
+ terminalConfig: protocols.enableSsh
+ ? {
+ theme: form.theme,
+ cursorBlink: form.cursorBlink,
+ cursorStyle: form.cursorStyle,
+ fontSize: Number(form.fontSize),
+ fontFamily: form.fontFamily,
+ scrollback: Number(form.scrollback),
+ letterSpacing: Number(form.letterSpacing),
+ lineHeight: Number(form.lineHeight),
+ bellStyle: form.bellStyle,
+ rightClickSelectsWord: form.rightClickSelectsWord,
+ fastScrollModifier: form.fastScrollModifier,
+ fastScrollSensitivity: Number(form.fastScrollSensitivity),
+ minimumContrastRatio: Number(form.minimumContrastRatio),
+ backspaceMode: form.backspaceMode,
+ startupSnippetId: form.startupSnippetId ?? null,
+ moshCommand: form.moshCommand || null,
+ agentForwarding: form.agentForwarding,
+ autoMosh: form.autoMosh,
+ autoTmux: form.autoTmux,
+ sudoPasswordAutoFill: form.sudoPasswordAutoFill,
+ sudoPassword: form.sudoPassword || null,
+ keepaliveInterval: Number(form.keepaliveInterval),
+ keepaliveCountMax: Number(form.keepaliveCountMax),
+ environmentVariables: form.environmentVariables,
+ }
+ : null,
+ };
+}
diff --git a/src/ui/sidebar/HostEditorFeatureTabs.tsx b/src/ui/sidebar/HostEditorFeatureTabs.tsx
new file mode 100644
index 000000000..6ba86e0fc
--- /dev/null
+++ b/src/ui/sidebar/HostEditorFeatureTabs.tsx
@@ -0,0 +1,82 @@
+import { useTranslation } from "react-i18next";
+import { Box, FolderSearch } from "lucide-react";
+
+import { Input } from "@/components/input";
+import { SectionCard, SettingRow, FakeSwitch } from "@/components/section-card";
+import type { HostEditorForm } from "./HostEditorData";
+
+type SetHostField = <K extends keyof HostEditorForm>(
+ key: K,
+ value: HostEditorForm[K],
+) => void;
+
+export function HostDockerTab({
+ form,
+ setField,
+}: {
+ form: HostEditorForm;
+ setField: SetHostField;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <SectionCard
+ title={t("hosts.dockerIntegration")}
+ icon={<Box className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <SettingRow
+ label={t("hosts.enableDockerMonitor")}
+ description={t("hosts.enableDockerMonitorDesc")}
+ >
+ <FakeSwitch
+ checked={form.enableDocker}
+ onChange={(v) => setField("enableDocker", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+ );
+}
+
+export function HostFilesTab({
+ form,
+ setField,
+}: {
+ form: HostEditorForm;
+ setField: SetHostField;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <SectionCard
+ title={t("hosts.fileManager")}
+ icon={<FolderSearch className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <SettingRow
+ label={t("hosts.enableFileManagerMonitor")}
+ description={t("hosts.enableFileManagerMonitorDesc")}
+ >
+ <FakeSwitch
+ checked={form.enableFileManager}
+ onChange={(v) => setField("enableFileManager", v)}
+ />
+ </SettingRow>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.defaultPathLabel")}
+ </label>
+ <Input
+ placeholder="/"
+ value={form.defaultPath}
+ onChange={(e) => setField("defaultPath", e.target.value)}
+ />
+ <span className="text-[10px] text-muted-foreground">
+ {t("hosts.fileManagerPathHint")}
+ </span>
+ </div>
+ </div>
+ </SectionCard>
+ );
+}
diff --git a/src/ui/sidebar/HostEditorGeneralTab.tsx b/src/ui/sidebar/HostEditorGeneralTab.tsx
new file mode 100644
index 000000000..e22f0dde7
--- /dev/null
+++ b/src/ui/sidebar/HostEditorGeneralTab.tsx
@@ -0,0 +1,699 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/button";
+import { Input } from "@/components/input";
+import { PasswordInput } from "@/components/password-input";
+import { FakeSwitch, SectionCard, SettingRow } from "@/components/section-card";
+import type { Host } from "@/types/ui-types";
+import {
+ Globe,
+ Monitor,
+ MousePointerClick,
+ Plus,
+ Tag,
+ Terminal,
+ Trash2,
+ X,
+} from "lucide-react";
+import type { HostEditorForm, HostProtocols } from "./HostEditorData";
+
+type HostEditorSetField = <K extends keyof HostEditorForm>(
+ key: K,
+ value: HostEditorForm[K],
+) => void;
+
+export function HostEditorGeneralTab({
+ form,
+ setField,
+ protocols,
+ handleProtocolToggle,
+ hosts,
+ host,
+}: {
+ form: HostEditorForm;
+ setField: HostEditorSetField;
+ protocols: HostProtocols;
+ handleProtocolToggle: (proto: keyof HostProtocols, value: boolean) => void;
+ hosts: Host[];
+ host: Host | null;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <>
+ {/* Protocols — enable/disable each connection type */}
+ <SectionCard
+ title={t("hosts.protocols")}
+ icon={<Globe className="size-3.5" />}
+ >
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-2 py-3">
+ {[
+ {
+ proto: "enableSsh" as const,
+ label: t("hosts.tabSsh"),
+ desc: t("hosts.secureShell"),
+ icon: <Terminal className="size-4" />,
+ portField: "sshPort" as const,
+ },
+ {
+ proto: "enableRdp" as const,
+ label: t("hosts.tabRdp"),
+ desc: t("hosts.remoteDesktop"),
+ icon: <Monitor className="size-4" />,
+ portField: "rdpPort" as const,
+ },
+ {
+ proto: "enableVnc" as const,
+ label: t("hosts.tabVnc"),
+ desc: t("hosts.virtualNetwork"),
+ icon: <MousePointerClick className="size-4" />,
+ portField: "vncPort" as const,
+ },
+ {
+ proto: "enableTelnet" as const,
+ label: t("hosts.tabTelnet"),
+ desc: t("hosts.unencryptedShell"),
+ icon: <Terminal className="size-4" />,
+ portField: "telnetPort" as const,
+ },
+ ].map(({ proto, label, desc, icon }) => {
+ const enabled = protocols[proto];
+ return (
+ <div
+ key={proto}
+ className={`flex items-center gap-3 p-3 border transition-colors ${enabled ? "border-accent-brand/20 bg-accent-brand/5" : "border-border bg-muted/10"}`}
+ >
+ <div
+ className={`size-8 flex items-center justify-center shrink-0 ${enabled ? "text-accent-brand" : "text-muted-foreground/30"}`}
+ >
+ {icon}
+ </div>
+ <div className="flex flex-col gap-1 flex-1 min-w-0">
+ <span
+ className={`text-xs font-bold ${enabled ? "text-foreground" : "text-muted-foreground/50"}`}
+ >
+ {label}
+ </span>
+ <span className="text-[10px] text-muted-foreground/50">
+ {desc}
+ </span>
+ </div>
+ <FakeSwitch
+ checked={enabled}
+ onChange={(v: boolean) => handleProtocolToggle(proto, v)}
+ />
+ </div>
+ );
+ })}
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.connectionDetails")}
+ icon={<Globe className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.addressIp")}
+ </label>
+ <Input
+ placeholder="10.0.0.1 or example.com"
+ value={form.ip}
+ onChange={(e) => setField("ip", e.target.value)}
+ />
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.friendlyName")}
+ </label>
+ <Input
+ placeholder="e.g. Web Server Production"
+ value={form.name}
+ onChange={(e) => setField("name", e.target.value)}
+ />
+ </div>
+ {protocols.enableSsh && (
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ MAC Address
+ </label>
+ <Input
+ placeholder="AA:BB:CC:DD:EE:FF"
+ value={form.macAddress}
+ onChange={(e) => setField("macAddress", e.target.value)}
+ />
+ </div>
+ )}
+ </div>
+ </div>
+ </SectionCard>
+
+ {!protocols.enableSsh &&
+ !protocols.enableRdp &&
+ !protocols.enableVnc &&
+ !protocols.enableTelnet && (
+ <div className="flex items-center gap-3 p-3 border border-border bg-muted/20 text-xs text-muted-foreground">
+ <Globe className="size-4 shrink-0 text-muted-foreground/40" />
+ <span>{t("hosts.enableAtLeastOneProtocol")}</span>
+ </div>
+ )}
+
+ <SectionCard
+ title={t("hosts.folderAndAdvanced")}
+ icon={<Tag className="size-3.5" />}
+ >
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.folder")}
+ </label>
+ <Input
+ placeholder="e.g. Production"
+ value={form.folder}
+ onChange={(e) => setField("folder", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.tags")}
+ </label>
+ <div className="flex flex-wrap items-center gap-1 min-h-9 px-2 py-1 border border-border bg-background focus-within:ring-1 focus-within:ring-ring">
+ {form.tags.map((tag) => (
+ <span
+ key={tag}
+ className="flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] bg-muted border border-border/60 text-foreground"
+ >
+ {tag}
+ <button
+ type="button"
+ onClick={() =>
+ setField(
+ "tags",
+ form.tags.filter((tg) => tg !== tag),
+ )
+ }
+ className="text-muted-foreground hover:text-destructive ml-0.5"
+ >
+ <X className="size-2.5" />
+ </button>
+ </span>
+ ))}
+ <input
+ className="flex-1 min-w-16 text-xs bg-transparent outline-none placeholder:text-muted-foreground/50"
+ placeholder={form.tags.length === 0 ? t("hosts.addTag") : ""}
+ value={form.tagInput}
+ onChange={(e) => setField("tagInput", e.target.value)}
+ onKeyDown={(e) => {
+ if (
+ (e.key === " " || e.key === "Enter") &&
+ form.tagInput.trim()
+ ) {
+ e.preventDefault();
+ const tag = form.tagInput.trim();
+ if (!form.tags.includes(tag))
+ setField("tags", [...form.tags, tag]);
+ setField("tagInput", "");
+ } else if (
+ e.key === "Backspace" &&
+ !form.tagInput &&
+ form.tags.length > 0
+ ) {
+ setField("tags", form.tags.slice(0, -1));
+ }
+ }}
+ />
+ </div>
+ </div>
+ <div className="flex flex-col gap-1.5 col-span-2">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.privateNotes")}
+ </label>
+ <textarea
+ rows={3}
+ placeholder={t("hosts.privateNotesPlaceholder")}
+ className="w-full px-3 py-2 text-xs bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring"
+ value={form.notes}
+ onChange={(e) => setField("notes", e.target.value)}
+ />
+ </div>
+ <SettingRow
+ label={t("hosts.pinToTop")}
+ description={t("hosts.pinToTopDesc")}
+ >
+ <FakeSwitch
+ checked={form.pin}
+ onChange={(v) => setField("pin", v)}
+ />
+ </SettingRow>
+ </div>
+ <div className="flex flex-col gap-3 border-t border-border pt-4 pb-0">
+ <div className="flex items-center justify-between">
+ <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.portKnockingSequence")}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
+ onClick={() =>
+ setField("portKnockSequence", [
+ ...form.portKnockSequence,
+ { port: 0, protocol: "tcp" as const, delay: 0 },
+ ])
+ }
+ >
+ <Plus className="size-3 mr-1" /> {t("hosts.addKnockBtn")}
+ </Button>
+ </div>
+ {form.portKnockSequence.length === 0 && (
+ <p className="text-[10px] text-muted-foreground/50">
+ {t("hosts.noPortKnocking")}
+ </p>
+ )}
+ <div className="flex flex-col gap-2">
+ {form.portKnockSequence.map((knock, i) => (
+ <div
+ key={i}
+ className="flex items-end gap-1.5 p-1.5 bg-muted/30 border border-border"
+ >
+ <span className="text-[9px] font-bold text-muted-foreground/50 mb-1.5 shrink-0">
+ {i + 1}.
+ </span>
+ <div className="flex flex-col gap-0.5">
+ <span className="text-[9px] text-muted-foreground/60 uppercase font-bold tracking-wide px-0.5">
+ {t("hosts.knockPort")}
+ </span>
+ <Input
+ className="h-7 text-xs w-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ placeholder="8080"
+ type="number"
+ value={knock.port}
+ onChange={(e) => {
+ const updated = [...form.portKnockSequence];
+ updated[i] = {
+ ...updated[i],
+ port: Number(e.target.value),
+ };
+ setField("portKnockSequence", updated);
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="text-[9px] text-muted-foreground/60 uppercase font-bold tracking-wide px-0.5">
+ {t("hosts.protocol")}
+ </span>
+ <select
+ className="h-7 text-[10px] bg-background border border-border px-1"
+ value={knock.protocol}
+ onChange={(e) => {
+ const updated = [...form.portKnockSequence];
+ updated[i] = {
+ ...updated[i],
+ protocol: e.target.value as "tcp" | "udp",
+ };
+ setField("portKnockSequence", updated);
+ }}
+ >
+ <option value="tcp">TCP</option>
+ <option value="udp">UDP</option>
+ </select>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="text-[9px] text-muted-foreground/60 uppercase font-bold tracking-wide px-0.5">
+ {t("hosts.delayAfterMs")}
+ </span>
+ <Input
+ className="h-7 text-xs w-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ placeholder="100"
+ type="number"
+ value={knock.delay}
+ onChange={(e) => {
+ const updated = [...form.portKnockSequence];
+ updated[i] = {
+ ...updated[i],
+ delay: Number(e.target.value),
+ };
+ setField("portKnockSequence", updated);
+ }}
+ />
+ </div>
+ <button
+ className="text-destructive p-1 mb-0.5"
+ onClick={() =>
+ setField(
+ "portKnockSequence",
+ form.portKnockSequence.filter((_, idx) => idx !== i),
+ )
+ }
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="flex flex-col gap-4 border-t border-border pt-4 pb-2">
+ <SettingRow
+ label={t("hosts.useSocks5Proxy")}
+ description={t("hosts.useSocks5ProxyDesc")}
+ >
+ <FakeSwitch
+ checked={form.useSocks5}
+ onChange={(v) => setField("useSocks5", v)}
+ />
+ </SettingRow>
+ {form.useSocks5 && (
+ <div className="flex flex-col gap-3">
+ {/* Single / Chain mode toggle */}
+ <div className="flex gap-2">
+ {(["single", "chain"] as const).map((m) => (
+ <button
+ key={m}
+ type="button"
+ onClick={() => setField("socks5ProxyMode", m)}
+ className={`px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${form.socks5ProxyMode === m ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
+ >
+ {m === "single"
+ ? t("hosts.proxySingleMode")
+ : t("hosts.proxyChainMode")}
+ </button>
+ ))}
+ </div>
+
+ {form.socks5ProxyMode === "single" && (
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3 p-3 bg-muted/20 border border-border">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.proxyHost")}
+ </label>
+ <Input
+ className="h-7 text-xs"
+ placeholder="proxy.example.com"
+ value={form.socks5Host}
+ onChange={(e) => setField("socks5Host", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.proxyPort")}
+ </label>
+ <Input
+ className="h-7 text-xs"
+ type="number"
+ placeholder="1080"
+ value={form.socks5Port}
+ onChange={(e) =>
+ setField("socks5Port", Number(e.target.value))
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.proxyUsername")}
+ </label>
+ <Input
+ className="h-7 text-xs"
+ placeholder={t("hosts.optional")}
+ value={form.socks5Username}
+ onChange={(e) =>
+ setField("socks5Username", e.target.value)
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.proxyPassword")}
+ </label>
+ <PasswordInput
+ className="h-7 text-xs pr-8"
+ placeholder={t("hosts.optional")}
+ value={form.socks5Password}
+ onChange={(e) =>
+ setField("socks5Password", e.target.value)
+ }
+ />
+ </div>
+ </div>
+ )}
+
+ {form.socks5ProxyMode === "chain" && (
+ <div className="flex flex-col gap-2">
+ {form.socks5ProxyChain.map((node, ni) => (
+ <div
+ key={ni}
+ className="flex flex-col gap-2 p-3 bg-muted/20 border border-border"
+ >
+ <div className="flex items-center justify-between">
+ <span className="text-[10px] font-bold text-muted-foreground">
+ {t("hosts.proxyNode")} {ni + 1}
+ </span>
+ <button
+ type="button"
+ className="text-destructive"
+ onClick={() =>
+ setField(
+ "socks5ProxyChain",
+ form.socks5ProxyChain.filter(
+ (_, idx) => idx !== ni,
+ ),
+ )
+ }
+ >
+ <X className="size-3.5" />
+ </button>
+ </div>
+ <div className="grid grid-cols-2 gap-2">
+ <div className="flex flex-col gap-1">
+ <label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.proxyHost")}
+ </label>
+ <Input
+ className="h-7 text-xs"
+ placeholder="proxy.example.com"
+ value={node.host}
+ onChange={(e) => {
+ const u = [...form.socks5ProxyChain];
+ u[ni] = { ...u[ni], host: e.target.value };
+ setField("socks5ProxyChain", u);
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.proxyPort")}
+ </label>
+ <Input
+ className="h-7 text-xs"
+ type="number"
+ placeholder="1080"
+ value={node.port}
+ onChange={(e) => {
+ const u = [...form.socks5ProxyChain];
+ u[ni] = {
+ ...u[ni],
+ port: Number(e.target.value),
+ };
+ setField("socks5ProxyChain", u);
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.proxyType")}
+ </label>
+ <select
+ className="h-7 text-xs border border-border bg-background px-2 outline-none focus:ring-1 focus:ring-ring"
+ value={node.type}
+ onChange={(e) => {
+ const u = [...form.socks5ProxyChain];
+ u[ni] = { ...u[ni], type: e.target.value };
+ setField("socks5ProxyChain", u);
+ }}
+ >
+ <option value="socks5">SOCKS5</option>
+ <option value="socks4">SOCKS4</option>
+ <option value="http">HTTP</option>
+ </select>
+ </div>
+ <div className="flex flex-col gap-1">
+ <label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.proxyUsername")}
+ </label>
+ <Input
+ className="h-7 text-xs"
+ placeholder={t("hosts.optional")}
+ value={node.username}
+ onChange={(e) => {
+ const u = [...form.socks5ProxyChain];
+ u[ni] = {
+ ...u[ni],
+ username: e.target.value,
+ };
+ setField("socks5ProxyChain", u);
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-1 col-span-2">
+ <label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.proxyPassword")}
+ </label>
+ <PasswordInput
+ className="h-7 text-xs pr-8"
+ placeholder={t("hosts.optional")}
+ value={node.password}
+ onChange={(e) => {
+ const u = [...form.socks5ProxyChain];
+ u[ni] = {
+ ...u[ni],
+ password: e.target.value,
+ };
+ setField("socks5ProxyChain", u);
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ ))}
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand self-start"
+ onClick={() =>
+ setField("socks5ProxyChain", [
+ ...form.socks5ProxyChain,
+ {
+ host: "",
+ port: 1080,
+ type: "socks5",
+ username: "",
+ password: "",
+ },
+ ])
+ }
+ >
+ <Plus className="size-3 mr-1" /> {t("hosts.addProxyNode")}
+ </Button>
+ </div>
+ )}
+
+ {/* Connection path visualization */}
+ {(form.socks5ProxyMode === "single" && form.socks5Host) ||
+ (form.socks5ProxyMode === "chain" &&
+ form.socks5ProxyChain.length > 0) ? (
+ <div className="flex items-center gap-1 flex-wrap p-2 bg-muted/30 border border-border text-[10px]">
+ <span className="px-2 py-0.5 bg-background border border-border text-foreground font-mono">
+ {t("hosts.you")}
+ </span>
+ {form.socks5ProxyMode === "single" && form.socks5Host ? (
+ <>
+ <span className="text-muted-foreground">→</span>
+ <span className="px-2 py-0.5 bg-muted border border-border text-muted-foreground font-mono">
+ {form.socks5Host}:{form.socks5Port}
+ </span>
+ </>
+ ) : (
+ form.socks5ProxyChain
+ .filter((n) => n.host)
+ .map((n, ni) => (
+ <React.Fragment key={ni}>
+ <span className="text-muted-foreground">→</span>
+ <span className="px-2 py-0.5 bg-muted border border-border text-muted-foreground font-mono">
+ {n.host}:{n.port}
+ </span>
+ </React.Fragment>
+ ))
+ )}
+ {form.jumpHosts
+ .filter((j) => j.hostId)
+ .map((j, ji) => {
+ const jh = hosts.find((h) => h.id === j.hostId);
+ return jh ? (
+ <React.Fragment key={`j${ji}`}>
+ <span className="text-muted-foreground">→</span>
+ <span className="px-2 py-0.5 bg-muted border border-border text-muted-foreground font-mono">
+ {jh.name || jh.ip}
+ </span>
+ </React.Fragment>
+ ) : null;
+ })}
+ <span className="text-muted-foreground">→</span>
+ <span className="px-2 py-0.5 bg-accent-brand/10 border border-accent-brand/30 text-accent-brand font-mono">
+ {form.ip || "target"}:{form.sshPort}
+ </span>
+ </div>
+ ) : null}
+ </div>
+ )}
+ <div className="flex flex-col gap-3">
+ <div className="flex items-center justify-between">
+ <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.jumpHostChainLabel")}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
+ onClick={() =>
+ setField("jumpHosts", [...form.jumpHosts, { hostId: "" }])
+ }
+ >
+ <Plus className="size-3 mr-1" /> {t("hosts.addJumpBtn")}
+ </Button>
+ </div>
+ {form.jumpHosts.length === 0 && (
+ <p className="text-[10px] text-muted-foreground/50">
+ {t("hosts.noJumpHosts")}
+ </p>
+ )}
+ <div className="flex flex-col gap-2">
+ {form.jumpHosts.map((jh, i) => (
+ <div
+ key={i}
+ className="flex items-center gap-2 p-2 bg-background border border-border"
+ >
+ <span className="text-[10px] font-bold text-muted-foreground shrink-0">
+ {i + 1}.
+ </span>
+ <select
+ className="flex h-7 flex-1 border border-border bg-background px-2 py-0 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={jh.hostId}
+ onChange={(e) => {
+ const updated = [...form.jumpHosts];
+ updated[i] = { hostId: e.target.value };
+ setField("jumpHosts", updated);
+ }}
+ >
+ <option value="">{t("hosts.selectAServer")}</option>
+ {hosts
+ .filter((h) => (host ? h.id !== host.id : true))
+ .map((h) => (
+ <option key={h.id} value={h.id}>
+ {h.name || h.ip}
+ </option>
+ ))}
+ </select>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7 text-destructive"
+ onClick={() =>
+ setField(
+ "jumpHosts",
+ form.jumpHosts.filter((_, idx) => idx !== i),
+ )
+ }
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ </SectionCard>
+ </>
+ );
+}
diff --git a/src/ui/sidebar/HostEditorGuacamoleTabs.tsx b/src/ui/sidebar/HostEditorGuacamoleTabs.tsx
new file mode 100644
index 000000000..411f9dbe5
--- /dev/null
+++ b/src/ui/sidebar/HostEditorGuacamoleTabs.tsx
@@ -0,0 +1,1369 @@
+import { useTranslation } from "react-i18next";
+import { Input } from "@/components/input";
+import { PasswordInput } from "@/components/password-input";
+import { FakeSwitch, SectionCard, SettingRow } from "@/components/section-card";
+import type { Host } from "@/types/ui-types";
+import {
+ Activity,
+ Copy,
+ Globe,
+ Monitor,
+ Network,
+ Server,
+ Settings,
+ Shield,
+ Terminal,
+ Zap,
+} from "lucide-react";
+import type { HostEditorForm } from "./HostEditorData";
+
+type HostEditorSetField = <K extends keyof HostEditorForm>(
+ key: K,
+ value: HostEditorForm[K],
+) => void;
+
+type GuacFieldSetter = (key: string, value: unknown) => void;
+
+export function HostEditorRdpTab({
+ form,
+ setField,
+ setGuacField,
+ host,
+}: {
+ form: HostEditorForm;
+ setField: HostEditorSetField;
+ setGuacField: GuacFieldSetter;
+ host?: Host | null;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <>
+ <SectionCard
+ title={t("hosts.guac.connection")}
+ icon={<Globe className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.rdpPort")}
+ </label>
+ <Input
+ type="number"
+ placeholder="3389"
+ value={form.rdpPort}
+ onChange={(e) => setField("rdpPort", Number(e.target.value))}
+ className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </div>
+ </div>
+ </SectionCard>
+ <SectionCard
+ title={t("hosts.guac.authentication")}
+ icon={<Shield className="size-3.5" />}
+ >
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.username")}
+ </label>
+ <Input
+ placeholder="Administrator"
+ value={form.rdpUser}
+ onChange={(e) => setField("rdpUser", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.password")}
+ </label>
+ <PasswordInput
+ className="h-8 text-xs pr-8"
+ placeholder="••••••••"
+ value={form.rdpPassword}
+ onChange={(e) => setField("rdpPassword", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.domain")}
+ </label>
+ <Input
+ placeholder="WORKGROUP"
+ value={form.domain}
+ onChange={(e) => setField("domain", e.target.value)}
+ />
+ </div>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.connectionSettings")}
+ icon={<Shield className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.securityMode")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.security ?? "any"}
+ onChange={(e) => setField("security", e.target.value)}
+ >
+ <option value="any">Any</option>
+ <option value="nla">NLA</option>
+ <option value="nla-ext">NLA Extended</option>
+ <option value="tls">TLS</option>
+ <option value="vmconnect">VMConnect</option>
+ <option value="rdp">RDP</option>
+ </select>
+ </div>
+ <SettingRow
+ label={t("hosts.guac.ignoreCertificate")}
+ description={t("hosts.guac.ignoreCertificateDesc")}
+ >
+ <FakeSwitch
+ checked={form.ignoreCert}
+ onChange={(v) => setField("ignoreCert", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.displaySettings")}
+ icon={<Monitor className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.colorDepth")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["color-depth"] ?? "auto"}
+ onChange={(e) => setGuacField("color-depth", e.target.value)}
+ >
+ <option value="auto">Auto</option>
+ <option value="8">8-bit</option>
+ <option value="16">16-bit</option>
+ <option value="24">24-bit</option>
+ <option value="32">32-bit</option>
+ </select>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.width")}
+ </label>
+ <Input
+ type="number"
+ placeholder="Auto"
+ value={form.guacamoleConfig["width"] ?? ""}
+ onChange={(e) => setGuacField("width", e.target.value)}
+ className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.height")}
+ </label>
+ <Input
+ type="number"
+ placeholder="Auto"
+ value={form.guacamoleConfig["height"] ?? ""}
+ onChange={(e) => setGuacField("height", e.target.value)}
+ className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </div>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.dpi")}
+ </label>
+ <Input
+ type="number"
+ placeholder="96"
+ value={form.guacamoleConfig["dpi"] ?? ""}
+ onChange={(e) => setGuacField("dpi", e.target.value)}
+ className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.resizeMethod")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["resize-method"] ?? "auto"}
+ onChange={(e) => setGuacField("resize-method", e.target.value)}
+ >
+ <option value="auto">Auto</option>
+ <option value="display-update">Display Update</option>
+ <option value="reconnect">Reconnect</option>
+ </select>
+ </div>
+ <SettingRow
+ label={t("hosts.guac.forceLossless")}
+ description={t("hosts.guac.forceLosslessDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["force-lossless"]}
+ onChange={(v) => setGuacField("force-lossless", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.audioSettings")}
+ icon={<Activity className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-0 py-1">
+ <SettingRow
+ label={t("hosts.guac.disableAudio")}
+ description={t("hosts.guac.disableAudioDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-audio"]}
+ onChange={(v) => setGuacField("disable-audio", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.enableAudioInput")}
+ description={t("hosts.guac.enableAudioInputDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["enable-audio-input"]}
+ onChange={(v) => setGuacField("enable-audio-input", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.rdpPerformance")}
+ icon={<Zap className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-0 py-1">
+ <SettingRow
+ label={t("hosts.guac.wallpaper")}
+ description={t("hosts.guac.wallpaperDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["enable-wallpaper"]}
+ onChange={(v) => setGuacField("enable-wallpaper", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.theming")}
+ description={t("hosts.guac.themingDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["enable-theming"]}
+ onChange={(v) => setGuacField("enable-theming", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.fontSmoothing")}
+ description={t("hosts.guac.fontSmoothingDesc")}
+ >
+ <FakeSwitch
+ checked={form.guacamoleConfig["enable-font-smoothing"] !== false}
+ onChange={(v) => setGuacField("enable-font-smoothing", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.fullWindowDrag")}
+ description={t("hosts.guac.fullWindowDragDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["enable-full-window-drag"]}
+ onChange={(v) => setGuacField("enable-full-window-drag", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.desktopComposition")}
+ description={t("hosts.guac.desktopCompositionDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["enable-desktop-composition"]}
+ onChange={(v) => setGuacField("enable-desktop-composition", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.menuAnimations")}
+ description={t("hosts.guac.menuAnimationsDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["enable-menu-animations"]}
+ onChange={(v) => setGuacField("enable-menu-animations", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.disableBitmapCaching")}
+ description={t("hosts.guac.disableBitmapCachingDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-bitmap-caching"]}
+ onChange={(v) => setGuacField("disable-bitmap-caching", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.disableOffscreenCaching")}
+ description={t("hosts.guac.disableOffscreenCachingDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-offscreen-caching"]}
+ onChange={(v) => setGuacField("disable-offscreen-caching", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.disableGlyphCaching")}
+ description={t("hosts.guac.disableGlyphCachingDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-glyph-caching"]}
+ onChange={(v) => setGuacField("disable-glyph-caching", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.enableGfx")}
+ description={t("hosts.guac.enableGfxDesc")}
+ >
+ <FakeSwitch
+ checked={form.guacamoleConfig["enable-gfx"] !== false}
+ onChange={(v) => setGuacField("enable-gfx", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.deviceRedirection")}
+ icon={<Settings className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <SettingRow
+ label={t("hosts.guac.enablePrinting")}
+ description={t("hosts.guac.enablePrintingDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["enable-printing"]}
+ onChange={(v) => setGuacField("enable-printing", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.enableDriveRedirection")}
+ description={t("hosts.guac.enableDriveRedirectionDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["enable-drive"]}
+ onChange={(v) => setGuacField("enable-drive", v)}
+ />
+ </SettingRow>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3 border-t border-border pt-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.driveName")}
+ </label>
+ <Input
+ placeholder="Termix Drive"
+ value={form.guacamoleConfig["drive-name"] ?? ""}
+ onChange={(e) => setGuacField("drive-name", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.drivePath")}
+ </label>
+ <Input
+ placeholder="/home/user/shared"
+ value={form.guacamoleConfig["drive-path"] ?? ""}
+ onChange={(e) => setGuacField("drive-path", e.target.value)}
+ />
+ </div>
+ </div>
+ <SettingRow
+ label={t("hosts.guac.createDrivePath")}
+ description={t("hosts.guac.createDrivePathDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["create-drive-path"]}
+ onChange={(v) => setGuacField("create-drive-path", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.disableDownload")}
+ description={t("hosts.guac.disableDownloadDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-download"]}
+ onChange={(v) => setGuacField("disable-download", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.disableUpload")}
+ description={t("hosts.guac.disableUploadDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-upload"]}
+ onChange={(v) => setGuacField("disable-upload", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.enableTouch")}
+ description={t("hosts.guac.enableTouchDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["enable-touch"]}
+ onChange={(v) => setGuacField("enable-touch", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.session")}
+ icon={<Server className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.clientName")}
+ </label>
+ <Input
+ placeholder="Termix"
+ value={form.guacamoleConfig["client-name"] ?? ""}
+ onChange={(e) => setGuacField("client-name", e.target.value)}
+ />
+ </div>
+ <SettingRow
+ label={t("hosts.guac.consoleSession")}
+ description={t("hosts.guac.consoleSessionDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["console"]}
+ onChange={(v) => setGuacField("console", v)}
+ />
+ </SettingRow>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.initialProgram")}
+ </label>
+ <Input
+ placeholder="e.g. cmd.exe"
+ value={form.guacamoleConfig["initial-program"] ?? ""}
+ onChange={(e) => setGuacField("initial-program", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.serverLayout")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["server-layout"] ?? "auto"}
+ onChange={(e) => setGuacField("server-layout", e.target.value)}
+ >
+ <option value="auto">Auto</option>
+ <option>en-us-qwerty</option>
+ <option>en-gb-qwerty</option>
+ <option>de-de-qwertz</option>
+ <option>fr-fr-azerty</option>
+ <option>it-it-qwerty</option>
+ <option>sv-se-qwerty</option>
+ <option>ja-jp-qwerty</option>
+ <option>pt-br-qwerty</option>
+ <option>es-es-qwerty</option>
+ <option>failsafe</option>
+ </select>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.timezone")}
+ </label>
+ <Input
+ placeholder="e.g. America/New_York"
+ value={form.guacamoleConfig["timezone"] ?? ""}
+ onChange={(e) => setGuacField("timezone", e.target.value)}
+ />
+ </div>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.gateway")}
+ icon={<Network className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.gatewayHostname")}
+ </label>
+ <Input
+ placeholder="gateway.example.com"
+ value={form.guacamoleConfig["gateway-hostname"] ?? ""}
+ onChange={(e) =>
+ setGuacField("gateway-hostname", e.target.value)
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.gatewayPort")}
+ </label>
+ <Input
+ type="number"
+ placeholder="443"
+ value={form.guacamoleConfig["gateway-port"] ?? ""}
+ onChange={(e) => setGuacField("gateway-port", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.gatewayUsername")}
+ </label>
+ <Input
+ placeholder="user"
+ value={form.guacamoleConfig["gateway-username"] ?? ""}
+ onChange={(e) =>
+ setGuacField("gateway-username", e.target.value)
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.gatewayPassword")}
+ </label>
+ <PasswordInput
+ className="h-8 text-xs pr-8"
+ placeholder="••••••••"
+ value={form.guacamoleConfig["gateway-password"] ?? ""}
+ onChange={(e) =>
+ setGuacField("gateway-password", e.target.value)
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-1.5 col-span-2">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.gatewayDomain")}
+ </label>
+ <Input
+ placeholder="DOMAIN"
+ value={form.guacamoleConfig["gateway-domain"] ?? ""}
+ onChange={(e) => setGuacField("gateway-domain", e.target.value)}
+ />
+ </div>
+ </div>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.remoteApp")}
+ icon={<Monitor className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.remoteAppProgram")}
+ </label>
+ <Input
+ placeholder="||MyApp"
+ value={form.guacamoleConfig["remote-app"] ?? ""}
+ onChange={(e) => setGuacField("remote-app", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.workingDirectory")}
+ </label>
+ <Input
+ placeholder="C:\Apps\MyApp"
+ value={form.guacamoleConfig["remote-app-dir"] ?? ""}
+ onChange={(e) => setGuacField("remote-app-dir", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.arguments")}
+ </label>
+ <Input
+ placeholder="--flag value"
+ value={form.guacamoleConfig["remote-app-args"] ?? ""}
+ onChange={(e) => setGuacField("remote-app-args", e.target.value)}
+ />
+ </div>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.clipboard")}
+ icon={<Copy className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.normalizeLineEndings")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["normalize-clipboard"] ?? "auto"}
+ onChange={(e) =>
+ setGuacField("normalize-clipboard", e.target.value)
+ }
+ >
+ <option value="auto">Auto</option>
+ <option value="preserve">Preserve</option>
+ <option value="unix">Unix (LF)</option>
+ <option value="windows">Windows (CRLF)</option>
+ </select>
+ </div>
+ <SettingRow
+ label={t("hosts.guac.disableCopy")}
+ description={t("hosts.guac.disableCopyDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-copy"]}
+ onChange={(v) => setGuacField("disable-copy", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.disablePaste")}
+ description={t("hosts.guac.disablePasteDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-paste"]}
+ onChange={(v) => setGuacField("disable-paste", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.sessionRecording")}
+ icon={<Activity className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.recordingPath")}
+ </label>
+ <Input
+ placeholder="/var/lib/termix/recordings"
+ value={form.guacamoleConfig["recording-path"] ?? ""}
+ onChange={(e) => setGuacField("recording-path", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.recordingName")}
+ </label>
+ <Input
+ placeholder="${GUAC_USERNAME}-${GUAC_DATE}-${GUAC_TIME}"
+ value={form.guacamoleConfig["recording-name"] ?? ""}
+ onChange={(e) => setGuacField("recording-name", e.target.value)}
+ />
+ </div>
+ <SettingRow
+ label={t("hosts.guac.createPathIfMissing")}
+ description={t("hosts.guac.createPathIfMissingDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["create-recording-path"]}
+ onChange={(v) => setGuacField("create-recording-path", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.excludeOutput")}
+ description={t("hosts.guac.excludeOutputDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["recording-exclude-output"]}
+ onChange={(v) => setGuacField("recording-exclude-output", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.excludeMouse")}
+ description={t("hosts.guac.excludeMouseDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["recording-exclude-mouse"]}
+ onChange={(v) => setGuacField("recording-exclude-mouse", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.includeKeystrokes")}
+ description={t("hosts.guac.includeKeystrokesDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["recording-include-keys"]}
+ onChange={(v) => setGuacField("recording-include-keys", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.wakeOnLan")}
+ icon={<Zap className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <SettingRow
+ label={t("hosts.guac.sendWolPacket")}
+ description={t("hosts.guac.sendWolPacketDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["wol-send-packet"]}
+ onChange={(v) => setGuacField("wol-send-packet", v)}
+ />
+ </SettingRow>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.macAddress")}
+ </label>
+ <Input
+ placeholder="AA:BB:CC:DD:EE:FF"
+ value={
+ form.guacamoleConfig["wol-mac-addr"] ?? host?.macAddress ?? ""
+ }
+ onChange={(e) => setGuacField("wol-mac-addr", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.broadcastAddress")}
+ </label>
+ <Input
+ placeholder="255.255.255.255"
+ value={form.guacamoleConfig["wol-broadcast-addr"] ?? ""}
+ onChange={(e) =>
+ setGuacField("wol-broadcast-addr", e.target.value)
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.udpPort")}
+ </label>
+ <Input
+ type="number"
+ placeholder="9"
+ value={form.guacamoleConfig["wol-udp-port"] ?? ""}
+ onChange={(e) => setGuacField("wol-udp-port", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.waitTimeS")}
+ </label>
+ <Input
+ type="number"
+ placeholder="0"
+ value={form.guacamoleConfig["wol-wait-time"] ?? ""}
+ onChange={(e) => setGuacField("wol-wait-time", e.target.value)}
+ />
+ </div>
+ </div>
+ </div>
+ </SectionCard>
+ </>
+ );
+}
+
+export function HostEditorVncTab({
+ form,
+ setField,
+ setGuacField,
+ host,
+}: {
+ form: HostEditorForm;
+ setField: HostEditorSetField;
+ setGuacField: GuacFieldSetter;
+ host?: Host | null;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <>
+ <SectionCard
+ title={t("hosts.guac.connection")}
+ icon={<Globe className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.vncPort")}
+ </label>
+ <Input
+ type="number"
+ placeholder="5900"
+ value={form.vncPort}
+ onChange={(e) => setField("vncPort", Number(e.target.value))}
+ className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </div>
+ </div>
+ </SectionCard>
+ <SectionCard
+ title={t("hosts.guac.authentication")}
+ icon={<Shield className="size-3.5" />}
+ >
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.vncPassword")}
+ </label>
+ <PasswordInput
+ className="h-8 text-xs pr-8"
+ placeholder="••••••••"
+ value={form.vncPassword}
+ onChange={(e) => setField("vncPassword", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.vncUsernameOptional")}
+ </label>
+ <Input
+ placeholder={t("hosts.guac.vncLeaveBlank")}
+ value={form.vncUser}
+ onChange={(e) => setField("vncUser", e.target.value)}
+ />
+ </div>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.displaySettings")}
+ icon={<Monitor className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.colorDepth")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["color-depth"] ?? "auto"}
+ onChange={(e) => setGuacField("color-depth", e.target.value)}
+ >
+ <option value="auto">Auto</option>
+ <option value="8">8-bit</option>
+ <option value="16">16-bit</option>
+ <option value="24">24-bit</option>
+ <option value="32">32-bit</option>
+ </select>
+ </div>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.width")}
+ </label>
+ <Input
+ type="number"
+ placeholder="Auto"
+ value={form.guacamoleConfig["width"] ?? ""}
+ onChange={(e) => setGuacField("width", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.height")}
+ </label>
+ <Input
+ type="number"
+ placeholder="Auto"
+ value={form.guacamoleConfig["height"] ?? ""}
+ onChange={(e) => setGuacField("height", e.target.value)}
+ />
+ </div>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.resizeMethod")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["resize-method"] ?? "auto"}
+ onChange={(e) => setGuacField("resize-method", e.target.value)}
+ >
+ <option value="auto">Auto</option>
+ <option value="display-update">Display Update</option>
+ <option value="reconnect">Reconnect</option>
+ </select>
+ </div>
+ <SettingRow
+ label={t("hosts.guac.forceLossless")}
+ description={t("hosts.guac.forceLosslessDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["force-lossless"]}
+ onChange={(v) => setGuacField("force-lossless", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.audioSettings")}
+ icon={<Activity className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-0 py-1">
+ <SettingRow
+ label={t("hosts.guac.disableAudio")}
+ description={t("hosts.guac.disableAudioDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-audio"]}
+ onChange={(v) => setGuacField("disable-audio", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.vncSettings")}
+ icon={<Settings className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.cursorMode")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["cursor"] ?? "auto"}
+ onChange={(e) => setGuacField("cursor", e.target.value)}
+ >
+ <option value="auto">Auto</option>
+ <option value="local">Local</option>
+ <option value="remote">Remote</option>
+ </select>
+ </div>
+ <SettingRow
+ label={t("hosts.guac.swapRedBlue")}
+ description={t("hosts.guac.swapRedBlueDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["swap-red-blue"]}
+ onChange={(v) => setGuacField("swap-red-blue", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.readOnly")}
+ description={t("hosts.guac.readOnlyDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["read-only"]}
+ onChange={(v) => setGuacField("read-only", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.clipboard")}
+ icon={<Copy className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.normalizeLineEndings")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["normalize-clipboard"] ?? "auto"}
+ onChange={(e) =>
+ setGuacField("normalize-clipboard", e.target.value)
+ }
+ >
+ <option value="auto">Auto</option>
+ <option value="preserve">Preserve</option>
+ <option value="unix">Unix (LF)</option>
+ <option value="windows">Windows (CRLF)</option>
+ </select>
+ </div>
+ <SettingRow
+ label={t("hosts.guac.disableCopy")}
+ description={t("hosts.guac.disableCopyDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-copy"]}
+ onChange={(v) => setGuacField("disable-copy", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.disablePaste")}
+ description={t("hosts.guac.disablePasteDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["disable-paste"]}
+ onChange={(v) => setGuacField("disable-paste", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.sessionRecording")}
+ icon={<Activity className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.recordingPath")}
+ </label>
+ <Input
+ placeholder="/var/lib/termix/recordings"
+ value={form.guacamoleConfig["recording-path"] ?? ""}
+ onChange={(e) => setGuacField("recording-path", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.recordingName")}
+ </label>
+ <Input
+ placeholder="${GUAC_USERNAME}-${GUAC_DATE}-${GUAC_TIME}"
+ value={form.guacamoleConfig["recording-name"] ?? ""}
+ onChange={(e) => setGuacField("recording-name", e.target.value)}
+ />
+ </div>
+ <SettingRow
+ label={t("hosts.guac.createPathIfMissing")}
+ description={t("hosts.guac.createPathIfMissingDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["create-recording-path"]}
+ onChange={(v) => setGuacField("create-recording-path", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.excludeOutput")}
+ description={t("hosts.guac.excludeOutputDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["recording-exclude-output"]}
+ onChange={(v) => setGuacField("recording-exclude-output", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.excludeMouse")}
+ description={t("hosts.guac.excludeMouseDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["recording-exclude-mouse"]}
+ onChange={(v) => setGuacField("recording-exclude-mouse", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.includeKeystrokes")}
+ description={t("hosts.guac.includeKeystrokesDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["recording-include-keys"]}
+ onChange={(v) => setGuacField("recording-include-keys", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.wakeOnLan")}
+ icon={<Zap className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <SettingRow
+ label={t("hosts.guac.sendWolPacket")}
+ description={t("hosts.guac.sendWolPacketDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["wol-send-packet"]}
+ onChange={(v) => setGuacField("wol-send-packet", v)}
+ />
+ </SettingRow>
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.macAddress")}
+ </label>
+ <Input
+ placeholder="AA:BB:CC:DD:EE:FF"
+ value={
+ form.guacamoleConfig["wol-mac-addr"] ?? host?.macAddress ?? ""
+ }
+ onChange={(e) => setGuacField("wol-mac-addr", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.broadcastAddress")}
+ </label>
+ <Input
+ placeholder="255.255.255.255"
+ value={form.guacamoleConfig["wol-broadcast-addr"] ?? ""}
+ onChange={(e) =>
+ setGuacField("wol-broadcast-addr", e.target.value)
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.udpPort")}
+ </label>
+ <Input
+ type="number"
+ placeholder="9"
+ value={form.guacamoleConfig["wol-udp-port"] ?? ""}
+ onChange={(e) => setGuacField("wol-udp-port", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.waitTimeS")}
+ </label>
+ <Input
+ type="number"
+ placeholder="0"
+ value={form.guacamoleConfig["wol-wait-time"] ?? ""}
+ onChange={(e) => setGuacField("wol-wait-time", e.target.value)}
+ />
+ </div>
+ </div>
+ </div>
+ </SectionCard>
+ </>
+ );
+}
+
+export function HostEditorTelnetTab({
+ form,
+ setField,
+ setGuacField,
+}: {
+ form: HostEditorForm;
+ setField: HostEditorSetField;
+ setGuacField: GuacFieldSetter;
+ host?: Host | null;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <>
+ <SectionCard
+ title={t("hosts.guac.connection")}
+ icon={<Globe className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.telnetPort")}
+ </label>
+ <Input
+ type="number"
+ placeholder="23"
+ value={form.telnetPort}
+ onChange={(e) => setField("telnetPort", Number(e.target.value))}
+ className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </div>
+ </div>
+ </SectionCard>
+ <SectionCard
+ title={t("hosts.guac.authentication")}
+ icon={<Shield className="size-3.5" />}
+ >
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.username")}
+ </label>
+ <Input
+ placeholder="admin"
+ value={form.telnetUser}
+ onChange={(e) => setField("telnetUser", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.password")}
+ </label>
+ <PasswordInput
+ className="h-8 text-xs pr-8"
+ placeholder="••••••••"
+ value={form.telnetPassword}
+ onChange={(e) => setField("telnetPassword", e.target.value)}
+ />
+ </div>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.displaySettings")}
+ icon={<Monitor className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.width")}
+ </label>
+ <Input
+ type="number"
+ placeholder="Auto"
+ value={form.guacamoleConfig["width"] ?? ""}
+ onChange={(e) => setGuacField("width", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.height")}
+ </label>
+ <Input
+ type="number"
+ placeholder="Auto"
+ value={form.guacamoleConfig["height"] ?? ""}
+ onChange={(e) => setGuacField("height", e.target.value)}
+ />
+ </div>
+ </div>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.terminalSettings")}
+ icon={<Terminal className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.terminalType")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["terminal-type"] ?? "auto"}
+ onChange={(e) => setGuacField("terminal-type", e.target.value)}
+ >
+ <option value="auto">Auto</option>
+ <option value="xterm">xterm</option>
+ <option value="xterm-256color">xterm-256color</option>
+ <option value="vt100">VT100</option>
+ <option value="vt220">VT220</option>
+ </select>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.fontName")}
+ </label>
+ <Input
+ placeholder="monospace"
+ value={form.guacamoleConfig["font-name"] ?? ""}
+ onChange={(e) => setGuacField("font-name", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.fontSize")}
+ </label>
+ <Input
+ type="number"
+ value={form.guacamoleConfig["font-size"] ?? 12}
+ onChange={(e) =>
+ setGuacField("font-size", Number(e.target.value))
+ }
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.colorScheme")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["color-scheme"] ?? "auto"}
+ onChange={(e) => setGuacField("color-scheme", e.target.value)}
+ >
+ <option value="auto">Auto</option>
+ <option value="black-white">Black on White</option>
+ <option value="white-black">White on Black</option>
+ <option value="gray-black">Gray on Black</option>
+ <option value="green-black">Green on Black</option>
+ </select>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.backspaceKey")}
+ </label>
+ <select
+ className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
+ value={form.guacamoleConfig["backspace"] ?? "auto"}
+ onChange={(e) => setGuacField("backspace", e.target.value)}
+ >
+ <option value="auto">Auto</option>
+ <option value="127">DEL (127)</option>
+ <option value="8">BS (8)</option>
+ </select>
+ </div>
+ </div>
+ </SectionCard>
+
+ <SectionCard
+ title={t("hosts.guac.sessionRecording")}
+ icon={<Activity className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-4 py-3">
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.recordingPath")}
+ </label>
+ <Input
+ placeholder="/var/lib/termix/recordings"
+ value={form.guacamoleConfig["recording-path"] ?? ""}
+ onChange={(e) => setGuacField("recording-path", e.target.value)}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
+ {t("hosts.guac.recordingName")}
+ </label>
+ <Input
+ placeholder="${GUAC_USERNAME}-${GUAC_DATE}-${GUAC_TIME}"
+ value={form.guacamoleConfig["recording-name"] ?? ""}
+ onChange={(e) => setGuacField("recording-name", e.target.value)}
+ />
+ </div>
+ <SettingRow
+ label={t("hosts.guac.createPathIfMissing")}
+ description={t("hosts.guac.createPathIfMissingDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["create-recording-path"]}
+ onChange={(v) => setGuacField("create-recording-path", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.excludeOutput")}
+ description={t("hosts.guac.excludeOutputDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["recording-exclude-output"]}
+ onChange={(v) => setGuacField("recording-exclude-output", v)}
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.guac.includeKeystrokes")}
+ description={t("hosts.guac.includeKeystrokesDesc")}
+ >
+ <FakeSwitch
+ checked={!!form.guacamoleConfig["recording-include-keys"]}
+ onChange={(v) => setGuacField("recording-include-keys", v)}
+ />
+ </SettingRow>
+ </div>
+ </SectionCard>
+ </>
+ );
+}
diff --git a/src/ui/sidebar/HostEditorStatsTab.tsx b/src/ui/sidebar/HostEditorStatsTab.tsx
new file mode 100644
index 000000000..9d1d55869
--- /dev/null
+++ b/src/ui/sidebar/HostEditorStatsTab.tsx
@@ -0,0 +1,296 @@
+import { useTranslation } from "react-i18next";
+import {
+ Activity,
+ LayoutDashboard,
+ Plus,
+ Server,
+ Trash2,
+ Zap,
+} from "lucide-react";
+
+import { Button } from "@/components/button";
+import { Input } from "@/components/input";
+import { SectionCard, SettingRow, FakeSwitch } from "@/components/section-card";
+import type { HostEditorForm } from "./HostEditorData";
+
+type SetHostField = <K extends keyof HostEditorForm>(
+ key: K,
+ value: HostEditorForm[K],
+) => void;
+
+export function HostStatsTab({
+ form,
+ setField,
+ snippets,
+}: {
+ form: HostEditorForm;
+ setField: SetHostField;
+ snippets: { id: number; name: string }[];
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <>
+ <SectionCard
+ title={t("hosts.statusChecksLabel")}
+ icon={<Activity className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-0 py-1">
+ <SettingRow
+ label={t("hosts.enableStatusChecks")}
+ description={t("hosts.enableStatusChecksDesc")}
+ >
+ <FakeSwitch
+ checked={form.statsConfig.statusCheckEnabled}
+ onChange={(v) =>
+ setField("statsConfig", {
+ ...form.statsConfig,
+ statusCheckEnabled: v,
+ })
+ }
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.useGlobalInterval")}
+ description={t("hosts.useGlobalIntervalDesc")}
+ >
+ <FakeSwitch
+ checked={form.statsConfig.useGlobalStatusInterval}
+ onChange={(v) =>
+ setField("statsConfig", {
+ ...form.statsConfig,
+ useGlobalStatusInterval: v,
+ })
+ }
+ />
+ </SettingRow>
+ {form.statsConfig.statusCheckEnabled &&
+ !form.statsConfig.useGlobalStatusInterval && (
+ <SettingRow
+ label={t("hosts.checkIntervalS")}
+ description={t("hosts.checkIntervalDesc")}
+ >
+ <Input
+ type="number"
+ value={form.statsConfig.statusCheckInterval}
+ onChange={(e) =>
+ setField("statsConfig", {
+ ...form.statsConfig,
+ statusCheckInterval: Number(e.target.value),
+ })
+ }
+ className="w-20 h-7 text-xs text-right [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </SettingRow>
+ )}
+ </div>
+ </SectionCard>
+ <SectionCard
+ title={t("hosts.metricsCollectionLabel")}
+ icon={<Server className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-0 py-1">
+ <SettingRow
+ label={t("hosts.enableMetricsLabel")}
+ description={t("hosts.enableMetricsDesc")}
+ >
+ <FakeSwitch
+ checked={form.statsConfig.metricsEnabled}
+ onChange={(v) =>
+ setField("statsConfig", {
+ ...form.statsConfig,
+ metricsEnabled: v,
+ })
+ }
+ />
+ </SettingRow>
+ <SettingRow
+ label={t("hosts.useGlobalMetrics")}
+ description={t("hosts.useGlobalMetricsDesc")}
+ >
+ <FakeSwitch
+ checked={form.statsConfig.useGlobalMetricsInterval}
+ onChange={(v) =>
+ setField("statsConfig", {
+ ...form.statsConfig,
+ useGlobalMetricsInterval: v,
+ })
+ }
+ />
+ </SettingRow>
+ {form.statsConfig.metricsEnabled &&
+ !form.statsConfig.useGlobalMetricsInterval && (
+ <SettingRow
+ label={t("hosts.metricsIntervalS")}
+ description={t("hosts.metricsIntervalDesc2")}
+ >
+ <Input
+ type="number"
+ value={form.statsConfig.metricsInterval}
+ onChange={(e) =>
+ setField("statsConfig", {
+ ...form.statsConfig,
+ metricsInterval: Number(e.target.value),
+ })
+ }
+ className="w-20 h-7 text-xs text-right [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
+ />
+ </SettingRow>
+ )}
+ </div>
+ </SectionCard>
+ <SectionCard
+ title={t("hosts.visibleWidgets")}
+ icon={<LayoutDashboard className="size-3.5" />}
+ >
+ <div className="flex flex-col gap-0 py-1">
+ {[
+ {
+ id: "cpu",
+ label: t("hosts.cpuUsageLabel"),
+ desc: t("hosts.cpuUsageDesc"),
+ },
+ {
+ id: "memory",
+ label: t("hosts.memoryLabel"),
+ desc: t("hosts.memoryDesc"),
+ },
+ {
+ id: "disk",
+ label: t("hosts.storageLabel"),
+ desc: t("hosts.storageDesc"),
+ },
+ {
+ id: "network",
+ label: t("hosts.networkLabel"),
+ desc: t("hosts.networkDesc"),
+ },
+ {
+ id: "uptime",
+ label: t("hosts.uptimeLabel"),
+ desc: t("hosts.uptimeDesc"),
+ },
+ {
+ id: "system",
+ label: t("hosts.systemInfoLabel"),
+ desc: t("hosts.systemInfoDesc"),
+ },
+ {
+ id: "login_stats",
+ label: t("hosts.recentLoginsLabel"),
+ desc: t("hosts.recentLoginsDesc"),
+ },
+ {
+ id: "processes",
+ label: t("hosts.topProcessesLabel"),
+ desc: t("hosts.topProcessesDesc"),
+ },
+ {
+ id: "ports",
+ label: t("hosts.listeningPortsLabel"),
+ desc: t("hosts.listeningPortsDesc"),
+ },
+ {
+ id: "firewall",
+ label: t("hosts.firewallLabel"),
+ desc: t("hosts.firewallDesc"),
+ },
+ ].map((w) => (
+ <SettingRow key={w.id} label={w.label} description={w.desc}>
+ <FakeSwitch
+ checked={form.statsConfig.enabledWidgets.includes(w.id)}
+ onChange={(v) => {
+ const widgets = v
+ ? [...form.statsConfig.enabledWidgets, w.id]
+ : form.statsConfig.enabledWidgets.filter((x) => x !== w.id);
+ setField("statsConfig", {
+ ...form.statsConfig,
+ enabledWidgets: widgets,
+ });
+ }}
+ />
+ </SettingRow>
+ ))}
+ </div>
+ </SectionCard>
+ <SectionCard
+ title={t("hosts.quickActionsLabel")}
+ icon={<Zap className="size-3.5" />}
+ action={
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
+ onClick={() =>
+ setField("quickActions", [
+ ...form.quickActions,
+ { name: "", snippetId: "" },
+ ])
+ }
+ >
+ <Plus className="size-3 mr-1" /> {t("hosts.addActionBtn")}
+ </Button>
+ }
+ >
+ <div className="flex flex-col gap-3 py-3">
+ <p className="text-xs text-muted-foreground">
+ {t("hosts.quickActionsToolbar")}
+ </p>
+ {form.quickActions.length === 0 && (
+ <div className="flex flex-col items-center justify-center py-4 text-muted-foreground/40 gap-1.5">
+ <Zap className="size-6" />
+ <span className="text-xs">{t("hosts.noQuickActions")}</span>
+ </div>
+ )}
+ {form.quickActions.map((a, i) => (
+ <div
+ key={i}
+ className="flex items-center gap-2 p-2 bg-muted/20 border border-border group"
+ >
+ <Input
+ className="h-7 text-xs flex-1"
+ placeholder={t("hosts.buttonLabel")}
+ value={a.name}
+ onChange={(e) => {
+ const updated = [...form.quickActions];
+ updated[i] = { ...updated[i], name: e.target.value };
+ setField("quickActions", updated);
+ }}
+ />
+ <select
+ className="h-7 text-xs flex-1 border border-border bg-background px-2 outline-none focus:ring-1 focus:ring-ring"
+ value={a.snippetId}
+ onChange={(e) => {
+ const updated = [...form.quickActions];
+ updated[i] = {
+ ...updated[i],
+ snippetId: e.target.value,
+ };
+ setField("quickActions", updated);
+ }}
+ >
+ <option value="">{t("hosts.selectSnippetPlaceholder")}</option>
+ {snippets.map((s) => (
+ <option key={s.id} value={String(s.id)}>
+ {s.name}
+ </option>
+ ))}
+ </select>
+ <button
+ className="text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"
+ onClick={() =>
+ setField(
+ "quickActions",
+ form.quickActions.filter((_, idx) => idx !== i),
+ )
+ }
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ </div>
+ ))}
+ </div>
+ </SectionCard>
+ </>
+ );
+}
diff --git a/src/ui/sidebar/HostManager.tsx b/src/ui/sidebar/HostManager.tsx
index ab2f51b66..9d2876435 100644
--- a/src/ui/sidebar/HostManager.tsx
+++ b/src/ui/sidebar/HostManager.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-hooks/exhaustive-deps */
import React, {
useState,
useEffect,
@@ -5,4629 +6,24 @@ import React, {
type MutableRefObject,
} from "react";
import { useTranslation } from "react-i18next";
-import {
- TERMINAL_THEMES,
- TERMINAL_FONTS,
- BELL_STYLES,
- FAST_SCROLL_MODIFIERS,
- CURSOR_STYLES,
-} from "@/lib/terminal-themes";
+
import { Button } from "@/components/button";
-import { Input } from "@/components/input";
-import { PasswordInput } from "@/components/password-input";
-import { Slider } from "@/components/slider";
-import {
- Activity,
- ArrowLeft,
- Box,
- Copy,
- Folder,
- FolderSearch,
- Globe,
- Info,
- KeyRound,
- LayoutDashboard,
- Loader2,
- Lock,
- Monitor,
- Network,
- MousePointerClick,
- Palette,
- Pencil,
- Plus,
- Search,
- Server,
- Settings,
- Shield,
- Tag,
- Terminal,
- Trash2,
- Upload,
- X,
- Zap,
-} from "lucide-react";
+import { ArrowLeft, Search, X } from "lucide-react";
import { toast } from "sonner";
-import { SectionCard, SettingRow, FakeSwitch } from "@/components/section-card";
-import { TerminalPreview } from "@/features/terminal/TerminalPreview";
import {
getSSHHosts,
getCredentials,
- createSSHHost,
- updateSSHHost,
- createCredential,
- updateCredential,
deleteCredential,
- generateKeyPair,
- generatePublicKeyFromPrivate,
deployCredentialToHost,
- getSnippets,
renameCredentialFolder,
- subscribeTunnelStatuses,
- connectTunnel,
- disconnectTunnel,
- getCredentialDetails,
} from "@/main-axios";
-import type { SSHHostWithStatus } from "@/main-axios";
import type { Host, Credential } from "@/types/ui-types";
-import { useTabsSafe } from "@/shell/TabContext";
-
-function sshHostToHost(h: SSHHostWithStatus): Host {
- const parseJson = (v: any) => {
- if (!v) return undefined;
- if (typeof v === "string") {
- try {
- return JSON.parse(v);
- } catch {
- return undefined;
- }
- }
- return v;
- };
- return {
- id: String(h.id),
- name: h.name,
- username: h.username,
- ip: h.ip,
- port: h.port,
- folder: h.folder ?? "",
- online: h.status === "online",
- cpu: null,
- ram: null,
- lastAccess: "",
- tags: h.tags ?? [],
- authType: h.authType,
- password: h.password,
- hasKey: !!(h as any).hasKey || !!(typeof h.key === "string" && h.key),
- hasKeyPassword: !!(h as any).hasKeyPassword || !!h.keyPassword,
- key: typeof h.key === "string" ? h.key : undefined,
- keyPassword: h.keyPassword,
- keyType: h.keyType,
- credentialId: h.credentialId != null ? String(h.credentialId) : undefined,
- notes: h.notes,
- pin: h.pin ?? false,
- macAddress: h.macAddress,
- enableSsh: h.enableSsh != null ? h.enableSsh : h.connectionType === "ssh",
- enableTerminal:
- h.enableTerminal ??
- (h.enableSsh != null ? h.enableSsh : h.connectionType === "ssh"),
- enableTunnel: h.enableTunnel ?? false,
- enableFileManager: h.enableFileManager ?? false,
- enableDocker: h.enableDocker ?? false,
- enableRdp: h.enableRdp != null ? h.enableRdp : h.connectionType === "rdp",
- enableVnc: h.enableVnc != null ? h.enableVnc : h.connectionType === "vnc",
- enableTelnet:
- h.enableTelnet != null ? h.enableTelnet : h.connectionType === "telnet",
- sshPort:
- h.sshPort ??
- (h.connectionType === "ssh" || !h.connectionType ? h.port : 22),
- rdpPort: h.rdpPort ?? (h.connectionType === "rdp" ? h.port : 3389),
- vncPort: h.vncPort ?? (h.connectionType === "vnc" ? h.port : 5900),
- telnetPort: h.telnetPort ?? (h.connectionType === "telnet" ? h.port : 23),
- rdpUser: h.rdpUser,
- rdpPassword: h.rdpPassword ?? "",
- domain: h.rdpDomain,
- security: h.rdpSecurity,
- ignoreCert: h.rdpIgnoreCert ?? false,
- vncPassword: h.vncPassword ?? "",
- vncUser: h.vncUser,
- telnetUser: h.telnetUser,
- telnetPassword: h.telnetPassword ?? "",
- quickActions: (h.quickActions ?? []).map((a: any) => ({
- name: a.name,
- snippetId: String(a.snippetId),
- })),
- serverTunnels: parseJson(h.tunnelConnections) ?? [],
- jumpHosts: (parseJson(h.jumpHosts) ?? []).map((j: any) => ({
- hostId: String(j.hostId ?? j.hostid ?? j),
- })),
- portKnockSequence: parseJson(h.portKnockSequence) ?? [],
- defaultPath: h.defaultPath,
- terminalConfig: parseJson(h.terminalConfig) as Host["terminalConfig"],
- statsConfig: parseJson(h.statsConfig) as Host["statsConfig"],
- guacamoleConfig: parseJson(h.guacamoleConfig),
- forceKeyboardInteractive: h.forceKeyboardInteractive ?? false,
- useSocks5: h.useSocks5,
- socks5Host: h.socks5Host,
- socks5Port: h.socks5Port,
- socks5Username: h.socks5Username,
- socks5Password: h.socks5Password,
- socks5ProxyChain: parseJson(h.socks5ProxyChain) ?? [],
- overrideCredentialUsername: h.overrideCredentialUsername ?? false,
- };
-}
-
-const HOST_TAB_IDS = [
- "general",
- "ssh",
- "tunnels",
- "docker",
- "files",
- "stats",
- "rdp",
- "vnc",
- "telnet",
-] as const;
-const CREDENTIAL_TAB_IDS = ["general", "auth"] as const;
-
-type HostTab = {
- id: (typeof HOST_TAB_IDS)[number];
- label: string;
- icon: React.ReactNode;
-};
-type CredentialTab = {
- id: (typeof CREDENTIAL_TAB_IDS)[number];
- label: string;
- icon: React.ReactNode;
-};
-
-function makeHostTabs(t: (key: string) => string): HostTab[] {
- return [
- {
- id: "general",
- label: t("hosts.tabGeneral"),
- icon: <Settings className="size-3" />,
- },
- {
- id: "ssh",
- label: t("hosts.tabSsh"),
- icon: <Terminal className="size-3" />,
- },
- {
- id: "tunnels",
- label: t("hosts.tabTunnels"),
- icon: <Network className="size-3" />,
- },
- {
- id: "docker",
- label: t("hosts.tabDocker"),
- icon: <Box className="size-3" />,
- },
- {
- id: "files",
- label: t("hosts.tabFiles"),
- icon: <Folder className="size-3" />,
- },
- {
- id: "stats",
- label: t("hosts.tabStats"),
- icon: <Activity className="size-3" />,
- },
- {
- id: "rdp",
- label: t("hosts.tabRdp"),
- icon: <Monitor className="size-3" />,
- },
- {
- id: "vnc",
- label: t("hosts.tabVnc"),
- icon: <MousePointerClick className="size-3" />,
- },
- {
- id: "telnet",
- label: t("hosts.tabTelnet"),
- icon: <Terminal className="size-3" />,
- },
- ];
-}
-
-function makeCredentialTabs(t: (key: string) => string): CredentialTab[] {
- return [
- {
- id: "general",
- label: t("hosts.tabGeneral"),
- icon: <Settings className="size-3" />,
- },
- {
- id: "auth",
- label: t("hosts.tabAuthentication"),
- icon: <KeyRound className="size-3" />,
- },
- ];
-}
-
-const SSH_DEP_TABS = new Set(["tunnels", "docker", "files", "stats"]);
-
-function TabStrip({
- tabs,
- activeTab,
- onTabChange,
-}: {
- tabs: { id: string; label: string; icon: React.ReactNode }[];
- activeTab: string;
- onTabChange: (id: string) => void;
-}) {
- const hasSshGroup = tabs.some((t) => SSH_DEP_TABS.has(t.id));
-
- const ref = useRef<HTMLDivElement>(null);
- useEffect(() => {
- const el = ref.current;
- if (!el) return;
- const onWheel = (e: WheelEvent) => {
- if (e.deltaY === 0) return;
- e.preventDefault();
- el.scrollLeft += e.deltaY;
- };
- el.addEventListener("wheel", onWheel, { passive: false });
- return () => el.removeEventListener("wheel", onWheel);
- }, []);
-
- // Split tabs into groups for rendering a labeled SSH section
- const nonSshTabs = tabs.filter((t) => !SSH_DEP_TABS.has(t.id));
- const sshDepTabs = tabs.filter((t) => SSH_DEP_TABS.has(t.id));
-
- const renderTab = (tab: (typeof tabs)[0]) => (
- <button
- key={tab.id}
- onClick={() => onTabChange(tab.id)}
- className={`flex items-center gap-1.5 px-3 py-2 text-xs font-medium whitespace-nowrap border-b-2 transition-colors shrink-0 ${
- activeTab === tab.id
- ? "border-accent-brand text-accent-brand"
- : "border-transparent text-muted-foreground hover:text-foreground"
- }`}
- >
- {tab.icon}
- {tab.label}
- </button>
- );
-
- return (
- <div ref={ref} className="overflow-x-auto">
- <div className="flex min-w-max">
- {nonSshTabs.map(renderTab)}
- {hasSshGroup && sshDepTabs.length > 0 && (
- <div className="flex flex-col border-l border-border/40 ml-0.5">
- <div className="flex items-center gap-1 px-2 pt-0.5">
- <Terminal className="size-2.5 text-muted-foreground/30" />
- <span className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground/30">
- SSH
- </span>
- </div>
- <div className="flex">{sshDepTabs.map(renderTab)}</div>
- </div>
- )}
- </div>
- </div>
- );
-}
-
-function HostEditor({
- host,
- activeTab,
- onBack,
- onSave,
- protocols,
- onProtocolChange,
- onTabChange,
- onCredentialChange,
- hosts,
- credentials,
-}: {
- host: Host | null;
- activeTab: string;
- onBack: () => void;
- onSave: (saved: any) => void;
- protocols: {
- enableSsh: boolean;
- enableRdp: boolean;
- enableVnc: boolean;
- enableTelnet: boolean;
- };
- onProtocolChange: (p: Partial<typeof protocols>) => void;
- onTabChange: (tab: string) => void;
- onCredentialChange: (credentialId: string) => void;
- hosts: Host[];
- credentials: { id: string; name: string; username: string }[];
-}) {
- const { t } = useTranslation();
- const { setPreviewTerminalTheme } = useTabsSafe();
- const [form, setForm] = useState(() => {
- const rawTheme = host?.terminalConfig?.theme;
- const normalizedTheme =
- !rawTheme ||
- ["Termix Dark", "Termix Light", "termixDark", "termixLight"].includes(
- rawTheme,
- )
- ? "termix"
- : TERMINAL_THEMES[rawTheme]
- ? rawTheme
- : "termix";
- return {
- name: host?.name ?? "",
- ip: host?.ip ?? "",
- username: host?.username ?? "",
- sshPort: host?.sshPort ?? host?.port ?? 22,
- rdpPort: host?.rdpPort ?? 3389,
- vncPort: host?.vncPort ?? 5900,
- telnetPort: host?.telnetPort ?? 23,
- authType: host?.authType ?? "password",
- password: host?.password ?? "",
- key: host?.key ?? (host?.hasKey ? "existing_key" : ""),
- keyPassword: host?.hasKeyPassword
- ? "existing_key_password"
- : (host?.keyPassword ?? ""),
- keyType: host?.keyType ?? "auto",
- keySubTab: "paste" as "paste" | "upload",
- credentialId: host?.credentialId ?? "",
- overrideCredentialUsername: host?.overrideCredentialUsername ?? false,
- folder: host?.folder ?? "",
- tags: host?.tags ?? ([] as string[]),
- tagInput: "",
- notes: host?.notes ?? "",
- pin: host?.pin ?? false,
- macAddress: host?.macAddress ?? "",
- useSocks5: host?.useSocks5 ?? false,
- socks5Host: host?.socks5Host ?? "",
- socks5Port: host?.socks5Port ?? 1080,
- socks5Username: host?.socks5Username ?? "",
- socks5Password: host?.socks5Password ?? "",
- socks5ProxyMode: ((host?.socks5ProxyChain as any[])?.length > 0
- ? "chain"
- : "single") as "single" | "chain",
- socks5ProxyChain: ((host?.socks5ProxyChain as any[]) ?? []) as {
- host: string;
- port: number;
- type: string;
- username: string;
- password: string;
- }[],
- enableTerminal: host?.enableTerminal ?? true,
- enableFileManager: host?.enableFileManager ?? false,
- enableDocker: host?.enableDocker ?? false,
- enableTunnel: host?.enableTunnel ?? false,
- defaultPath: host?.defaultPath ?? "/",
- forceKeyboardInteractive: host?.forceKeyboardInteractive ?? false,
- fontSize: host?.terminalConfig?.fontSize ?? 14,
- fontFamily:
- host?.terminalConfig?.fontFamily ?? "Caskaydia Cove Nerd Font Mono",
- theme: normalizedTheme,
- cursorStyle: (host?.terminalConfig?.cursorStyle ?? "bar") as
- | "block"
- | "underline"
- | "bar",
- cursorBlink: host?.terminalConfig?.cursorBlink ?? true,
- scrollback: host?.terminalConfig?.scrollback ?? 10000,
- letterSpacing: host?.terminalConfig?.letterSpacing ?? 0,
- lineHeight: host?.terminalConfig?.lineHeight ?? 1.0,
- bellStyle: (host?.terminalConfig?.bellStyle ?? "none") as
- | "none"
- | "sound"
- | "visual"
- | "both",
- rightClickSelectsWord:
- host?.terminalConfig?.rightClickSelectsWord ?? false,
- fastScrollModifier: (host?.terminalConfig?.fastScrollModifier ??
- "alt") as "alt" | "ctrl" | "shift",
- fastScrollSensitivity: host?.terminalConfig?.fastScrollSensitivity ?? 5,
- minimumContrastRatio: host?.terminalConfig?.minimumContrastRatio ?? 1,
- backspaceMode: (host?.terminalConfig?.backspaceMode ?? "normal") as
- | "normal"
- | "control-h",
- startupSnippetId: host?.terminalConfig?.startupSnippetId ?? null,
- moshCommand: host?.terminalConfig?.moshCommand ?? "",
- agentForwarding: host?.terminalConfig?.agentForwarding ?? false,
- autoMosh: host?.terminalConfig?.autoMosh ?? false,
- autoTmux: host?.terminalConfig?.autoTmux ?? false,
- sudoPasswordAutoFill: host?.terminalConfig?.sudoPasswordAutoFill ?? false,
- sudoPassword: host?.terminalConfig?.sudoPassword ?? "",
- keepaliveInterval: host?.terminalConfig?.keepaliveInterval ?? 60,
- keepaliveCountMax: host?.terminalConfig?.keepaliveCountMax ?? 5,
- environmentVariables:
- host?.terminalConfig?.environmentVariables ??
- ([] as { key: string; value: string }[]),
- serverTunnels: host?.serverTunnels ?? ([] as Host["serverTunnels"]),
- jumpHosts: host?.jumpHosts ?? ([] as { hostId: string }[]),
- portKnockSequence:
- host?.portKnockSequence ??
- ([] as { port: number; protocol: "tcp" | "udp"; delay: number }[]),
- quickActions:
- host?.quickActions ?? ([] as { name: string; snippetId: string }[]),
- rdpUser: host?.rdpUser ?? "",
- rdpPassword: host?.rdpPassword ?? "",
- domain: host?.domain ?? "",
- security: host?.security ?? "",
- ignoreCert: host?.ignoreCert ?? false,
- vncPassword: host?.vncPassword ?? "",
- vncUser: host?.vncUser ?? "",
- telnetUser: host?.telnetUser ?? "",
- telnetPassword: host?.telnetPassword ?? "",
- guacamoleConfig: host?.guacamoleConfig ?? ({} as Record<string, any>),
- statsConfig: host?.statsConfig ?? {
- statusCheckEnabled: true,
- statusCheckInterval: 60,
- useGlobalStatusInterval: true,
- metricsEnabled: true,
- metricsInterval: 30,
- useGlobalMetricsInterval: true,
- enabledWidgets: [
- "cpu",
- "memory",
- "disk",
- "network",
- "uptime",
- "system",
- "login_stats",
- "processes",
- "ports",
- "firewall",
- ],
- },
- };
- });
-
- const setField = <K extends keyof typeof form>(k: K, v: (typeof form)[K]) =>
- setForm((p) => ({ ...p, [k]: v }));
-
- const setGuacField = (key: string, value: any) =>
- setField("guacamoleConfig", { ...form.guacamoleConfig, [key]: value });
-
- const [saving, setSaving] = useState(false);
- const [snippets, setSnippets] = useState<{ id: number; name: string }[]>([]);
- const [tunnelStatuses, setTunnelStatuses] = useState<Record<string, any>>({});
- const [connectingTunnel, setConnectingTunnel] = useState<number | null>(null);
-
- useEffect(() => {
- getSnippets()
- .then((res: any) => {
- const arr = Array.isArray(res) ? res : (res?.snippets ?? []);
- setSnippets(
- arr.map((s: any) => ({
- id: s.id,
- name: s.name ?? s.title ?? `Snippet ${s.id}`,
- })),
- );
- })
- .catch(() => {});
- }, []);
-
- useEffect(() => {
- if (activeTab !== "tunnels") return;
- const unsub = subscribeTunnelStatuses((s) => setTunnelStatuses(s));
- return unsub;
- }, [activeTab]);
-
- const handleSave = async () => {
- setSaving(true);
- try {
- const tags = form.tags;
- const data = {
- connectionType: protocols.enableSsh
- ? "ssh"
- : protocols.enableRdp
- ? "rdp"
- : protocols.enableVnc
- ? "vnc"
- : "telnet",
- name: form.name,
- ip: form.ip,
- port: protocols.enableSsh
- ? Number(form.sshPort)
- : protocols.enableRdp
- ? Number(form.rdpPort)
- : protocols.enableVnc
- ? Number(form.vncPort)
- : Number(form.telnetPort),
- username: form.username,
- folder: form.folder,
- tags,
- pin: form.pin,
- authType: form.authType,
- password: form.password || null,
- key: form.key === "existing_key" ? undefined : form.key || null,
- keyPassword:
- form.keyPassword === "existing_key_password"
- ? undefined
- : form.keyPassword || null,
- keyType: form.keyType !== "auto" ? form.keyType : null,
- credentialId: form.credentialId ? Number(form.credentialId) : null,
- overrideCredentialUsername: form.overrideCredentialUsername,
- notes: form.notes,
- macAddress: form.macAddress || null,
- enableTerminal: form.enableTerminal,
- enableTunnel: form.enableTunnel,
- enableFileManager: form.enableFileManager,
- enableDocker: form.enableDocker,
- defaultPath: form.defaultPath || "/",
- useSocks5: form.useSocks5,
- socks5Host:
- form.socks5ProxyMode === "single" ? form.socks5Host || null : null,
- socks5Port:
- form.socks5ProxyMode === "single" ? form.socks5Port || null : null,
- socks5Username:
- form.socks5ProxyMode === "single"
- ? form.socks5Username || null
- : null,
- socks5Password:
- form.socks5ProxyMode === "single"
- ? form.socks5Password || null
- : null,
- socks5ProxyChain:
- form.socks5ProxyMode === "chain" ? form.socks5ProxyChain : null,
- enableSsh: protocols.enableSsh,
- enableRdp: protocols.enableRdp,
- enableVnc: protocols.enableVnc,
- enableTelnet: protocols.enableTelnet,
- sshPort: Number(form.sshPort),
- rdpPort: Number(form.rdpPort),
- vncPort: Number(form.vncPort),
- telnetPort: Number(form.telnetPort),
- forceKeyboardInteractive: form.forceKeyboardInteractive,
- rdpUser: form.rdpUser || null,
- rdpPassword: form.rdpPassword || null,
- rdpDomain: form.domain || null,
- rdpSecurity: form.security || null,
- rdpIgnoreCert: form.ignoreCert,
- vncPassword: form.vncPassword || null,
- vncUser: form.vncUser || null,
- telnetUser: form.telnetUser || null,
- telnetPassword: form.telnetPassword || null,
- jumpHosts: form.jumpHosts,
- portKnockSequence: form.portKnockSequence,
- tunnelConnections: form.serverTunnels,
- quickActions: form.quickActions.map((a) => ({
- name: a.name,
- snippetId: Number(a.snippetId),
- })),
- statsConfig: form.statsConfig,
- guacamoleConfig:
- (protocols.enableRdp ||
- protocols.enableVnc ||
- protocols.enableTelnet) &&
- Object.keys(form.guacamoleConfig).length > 0
- ? form.guacamoleConfig
- : null,
- terminalConfig: protocols.enableSsh
- ? {
- theme: form.theme,
- cursorBlink: form.cursorBlink,
- cursorStyle: form.cursorStyle,
- fontSize: Number(form.fontSize),
- fontFamily: form.fontFamily,
- scrollback: Number(form.scrollback),
- letterSpacing: Number(form.letterSpacing),
- lineHeight: Number(form.lineHeight),
- bellStyle: form.bellStyle,
- rightClickSelectsWord: form.rightClickSelectsWord,
- fastScrollModifier: form.fastScrollModifier,
- fastScrollSensitivity: Number(form.fastScrollSensitivity),
- minimumContrastRatio: Number(form.minimumContrastRatio),
- backspaceMode: form.backspaceMode,
- startupSnippetId: form.startupSnippetId ?? null,
- moshCommand: form.moshCommand || null,
- agentForwarding: form.agentForwarding,
- autoMosh: form.autoMosh,
- autoTmux: form.autoTmux,
- sudoPasswordAutoFill: form.sudoPasswordAutoFill,
- sudoPassword: form.sudoPassword || null,
- keepaliveInterval: Number(form.keepaliveInterval),
- keepaliveCountMax: Number(form.keepaliveCountMax),
- environmentVariables: form.environmentVariables,
- }
- : null,
- };
- const saved = host
- ? await updateSSHHost(Number(host.id), data as any)
- : await createSSHHost(data as any);
- toast.success(host ? t("hosts.hostUpdated") : t("hosts.hostCreated"));
- setPreviewTerminalTheme(null);
- onSave(saved);
- } catch {
- toast.error(t("hosts.failedToSave"));
- } finally {
- setSaving(false);
- }
- };
-
- const authMethod = form.authType;
- const selectedCredential = credentials.find(
- (c) => c.id === form.credentialId,
- );
-
- const handleProtocolToggle = (
- proto: keyof typeof protocols,
- value: boolean,
- ) => {
- onProtocolChange({ [proto]: value });
- const tabForProto: Record<string, string> = {
- enableSsh: "ssh",
- enableRdp: "rdp",
- enableVnc: "vnc",
- enableTelnet: "telnet",
- };
- if (!value && activeTab === tabForProto[proto]) onTabChange("general");
- if (value && tabForProto[proto]) onTabChange(tabForProto[proto]);
- };
-
- return (
- <div className="flex flex-col gap-3">
- <div className="flex flex-col gap-3">
- {activeTab === "general" && (
- <>
- {/* Protocols — enable/disable each connection type */}
- <SectionCard
- title={t("hosts.protocols")}
- icon={<Globe className="size-3.5" />}
- >
- <div className="grid grid-cols-1 md:grid-cols-2 gap-2 py-3">
- {[
- {
- proto: "enableSsh" as const,
- label: t("hosts.tabSsh"),
- desc: t("hosts.secureShell"),
- icon: <Terminal className="size-4" />,
- portField: "sshPort" as const,
- },
- {
- proto: "enableRdp" as const,
- label: t("hosts.tabRdp"),
- desc: t("hosts.remoteDesktop"),
- icon: <Monitor className="size-4" />,
- portField: "rdpPort" as const,
- },
- {
- proto: "enableVnc" as const,
- label: t("hosts.tabVnc"),
- desc: t("hosts.virtualNetwork"),
- icon: <MousePointerClick className="size-4" />,
- portField: "vncPort" as const,
- },
- {
- proto: "enableTelnet" as const,
- label: t("hosts.tabTelnet"),
- desc: t("hosts.unencryptedShell"),
- icon: <Terminal className="size-4" />,
- portField: "telnetPort" as const,
- },
- ].map(({ proto, label, desc, icon, portField }) => {
- const enabled = protocols[proto];
- return (
- <div
- key={proto}
- className={`flex items-center gap-3 p-3 border transition-colors ${enabled ? "border-accent-brand/20 bg-accent-brand/5" : "border-border bg-muted/10"}`}
- >
- <div
- className={`size-8 flex items-center justify-center shrink-0 ${enabled ? "text-accent-brand" : "text-muted-foreground/30"}`}
- >
- {icon}
- </div>
- <div className="flex flex-col gap-1 flex-1 min-w-0">
- <span
- className={`text-xs font-bold ${enabled ? "text-foreground" : "text-muted-foreground/50"}`}
- >
- {label}
- </span>
- <span className="text-[10px] text-muted-foreground/50">
- {desc}
- </span>
- </div>
- <FakeSwitch
- checked={enabled}
- onChange={(v: boolean) =>
- handleProtocolToggle(proto, v)
- }
- />
- </div>
- );
- })}
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.connectionDetails")}
- icon={<Globe className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.addressIp")}
- </label>
- <Input
- placeholder="10.0.0.1 or example.com"
- value={form.ip}
- onChange={(e) => setField("ip", e.target.value)}
- />
- </div>
-
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.friendlyName")}
- </label>
- <Input
- placeholder="e.g. Web Server Production"
- value={form.name}
- onChange={(e) => setField("name", e.target.value)}
- />
- </div>
- {protocols.enableSsh && (
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- MAC Address
- </label>
- <Input
- placeholder="AA:BB:CC:DD:EE:FF"
- value={form.macAddress}
- onChange={(e) => setField("macAddress", e.target.value)}
- />
- </div>
- )}
- </div>
- </div>
- </SectionCard>
-
- {!protocols.enableSsh &&
- !protocols.enableRdp &&
- !protocols.enableVnc &&
- !protocols.enableTelnet && (
- <div className="flex items-center gap-3 p-3 border border-border bg-muted/20 text-xs text-muted-foreground">
- <Globe className="size-4 shrink-0 text-muted-foreground/40" />
- <span>{t("hosts.enableAtLeastOneProtocol")}</span>
- </div>
- )}
-
- <SectionCard
- title={t("hosts.folderAndAdvanced")}
- icon={<Tag className="size-3.5" />}
- >
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.folder")}
- </label>
- <Input
- placeholder="e.g. Production"
- value={form.folder}
- onChange={(e) => setField("folder", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.tags")}
- </label>
- <div className="flex flex-wrap items-center gap-1 min-h-9 px-2 py-1 border border-border bg-background focus-within:ring-1 focus-within:ring-ring">
- {form.tags.map((tag) => (
- <span
- key={tag}
- className="flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] bg-muted border border-border/60 text-foreground"
- >
- {tag}
- <button
- type="button"
- onClick={() =>
- setField(
- "tags",
- form.tags.filter((tg) => tg !== tag),
- )
- }
- className="text-muted-foreground hover:text-destructive ml-0.5"
- >
- <X className="size-2.5" />
- </button>
- </span>
- ))}
- <input
- className="flex-1 min-w-16 text-xs bg-transparent outline-none placeholder:text-muted-foreground/50"
- placeholder={
- form.tags.length === 0 ? t("hosts.addTag") : ""
- }
- value={form.tagInput}
- onChange={(e) => setField("tagInput", e.target.value)}
- onKeyDown={(e) => {
- if (
- (e.key === " " || e.key === "Enter") &&
- form.tagInput.trim()
- ) {
- e.preventDefault();
- const tag = form.tagInput.trim();
- if (!form.tags.includes(tag))
- setField("tags", [...form.tags, tag]);
- setField("tagInput", "");
- } else if (
- e.key === "Backspace" &&
- !form.tagInput &&
- form.tags.length > 0
- ) {
- setField("tags", form.tags.slice(0, -1));
- }
- }}
- />
- </div>
- </div>
- <div className="flex flex-col gap-1.5 col-span-2">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.privateNotes")}
- </label>
- <textarea
- rows={3}
- placeholder={t("hosts.privateNotesPlaceholder")}
- className="w-full px-3 py-2 text-xs bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring"
- value={form.notes}
- onChange={(e) => setField("notes", e.target.value)}
- />
- </div>
- <SettingRow
- label={t("hosts.pinToTop")}
- description={t("hosts.pinToTopDesc")}
- >
- <FakeSwitch
- checked={form.pin}
- onChange={(v) => setField("pin", v)}
- />
- </SettingRow>
- </div>
- <div className="flex flex-col gap-3 border-t border-border pt-4 pb-0">
- <div className="flex items-center justify-between">
- <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.portKnockingSequence")}
- </span>
- <Button
- variant="outline"
- size="sm"
- className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
- onClick={() =>
- setField("portKnockSequence", [
- ...form.portKnockSequence,
- { port: 0, protocol: "tcp" as const, delay: 0 },
- ])
- }
- >
- <Plus className="size-3 mr-1" /> {t("hosts.addKnockBtn")}
- </Button>
- </div>
- {form.portKnockSequence.length === 0 && (
- <p className="text-[10px] text-muted-foreground/50">
- {t("hosts.noPortKnocking")}
- </p>
- )}
- <div className="flex flex-col gap-2">
- {form.portKnockSequence.map((knock, i) => (
- <div
- key={i}
- className="flex items-end gap-1.5 p-1.5 bg-muted/30 border border-border"
- >
- <span className="text-[9px] font-bold text-muted-foreground/50 mb-1.5 shrink-0">
- {i + 1}.
- </span>
- <div className="flex flex-col gap-0.5">
- <span className="text-[9px] text-muted-foreground/60 uppercase font-bold tracking-wide px-0.5">
- {t("hosts.knockPort")}
- </span>
- <Input
- className="h-7 text-xs w-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- placeholder="8080"
- type="number"
- value={knock.port}
- onChange={(e) => {
- const updated = [...form.portKnockSequence];
- updated[i] = {
- ...updated[i],
- port: Number(e.target.value),
- };
- setField("portKnockSequence", updated);
- }}
- />
- </div>
- <div className="flex flex-col gap-0.5">
- <span className="text-[9px] text-muted-foreground/60 uppercase font-bold tracking-wide px-0.5">
- {t("hosts.protocol")}
- </span>
- <select
- className="h-7 text-[10px] bg-background border border-border px-1"
- value={knock.protocol}
- onChange={(e) => {
- const updated = [...form.portKnockSequence];
- updated[i] = {
- ...updated[i],
- protocol: e.target.value as "tcp" | "udp",
- };
- setField("portKnockSequence", updated);
- }}
- >
- <option value="tcp">TCP</option>
- <option value="udp">UDP</option>
- </select>
- </div>
- <div className="flex flex-col gap-0.5">
- <span className="text-[9px] text-muted-foreground/60 uppercase font-bold tracking-wide px-0.5">
- {t("hosts.delayAfterMs")}
- </span>
- <Input
- className="h-7 text-xs w-20 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- placeholder="100"
- type="number"
- value={knock.delay}
- onChange={(e) => {
- const updated = [...form.portKnockSequence];
- updated[i] = {
- ...updated[i],
- delay: Number(e.target.value),
- };
- setField("portKnockSequence", updated);
- }}
- />
- </div>
- <button
- className="text-destructive p-1 mb-0.5"
- onClick={() =>
- setField(
- "portKnockSequence",
- form.portKnockSequence.filter(
- (_, idx) => idx !== i,
- ),
- )
- }
- >
- <X className="size-3" />
- </button>
- </div>
- ))}
- </div>
- </div>
- <div className="flex flex-col gap-4 border-t border-border pt-4 pb-2">
- <SettingRow
- label={t("hosts.useSocks5Proxy")}
- description={t("hosts.useSocks5ProxyDesc")}
- >
- <FakeSwitch
- checked={form.useSocks5}
- onChange={(v) => setField("useSocks5", v)}
- />
- </SettingRow>
- {form.useSocks5 && (
- <div className="flex flex-col gap-3">
- {/* Single / Chain mode toggle */}
- <div className="flex gap-2">
- {(["single", "chain"] as const).map((m) => (
- <button
- key={m}
- type="button"
- onClick={() => setField("socks5ProxyMode", m)}
- className={`px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${form.socks5ProxyMode === m ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
- >
- {m === "single"
- ? t("hosts.proxySingleMode")
- : t("hosts.proxyChainMode")}
- </button>
- ))}
- </div>
-
- {form.socks5ProxyMode === "single" && (
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3 p-3 bg-muted/20 border border-border">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.proxyHost")}
- </label>
- <Input
- className="h-7 text-xs"
- placeholder="proxy.example.com"
- value={form.socks5Host}
- onChange={(e) =>
- setField("socks5Host", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.proxyPort")}
- </label>
- <Input
- className="h-7 text-xs"
- type="number"
- placeholder="1080"
- value={form.socks5Port}
- onChange={(e) =>
- setField(
- "socks5Port",
- Number(e.target.value) as any,
- )
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.proxyUsername")}
- </label>
- <Input
- className="h-7 text-xs"
- placeholder={t("hosts.optional")}
- value={form.socks5Username}
- onChange={(e) =>
- setField("socks5Username", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.proxyPassword")}
- </label>
- <PasswordInput
- className="h-7 text-xs pr-8"
- placeholder={t("hosts.optional")}
- value={form.socks5Password}
- onChange={(e) =>
- setField("socks5Password", e.target.value)
- }
- />
- </div>
- </div>
- )}
-
- {form.socks5ProxyMode === "chain" && (
- <div className="flex flex-col gap-2">
- {form.socks5ProxyChain.map((node, ni) => (
- <div
- key={ni}
- className="flex flex-col gap-2 p-3 bg-muted/20 border border-border"
- >
- <div className="flex items-center justify-between">
- <span className="text-[10px] font-bold text-muted-foreground">
- {t("hosts.proxyNode")} {ni + 1}
- </span>
- <button
- type="button"
- className="text-destructive"
- onClick={() =>
- setField(
- "socks5ProxyChain",
- form.socks5ProxyChain.filter(
- (_, idx) => idx !== ni,
- ),
- )
- }
- >
- <X className="size-3.5" />
- </button>
- </div>
- <div className="grid grid-cols-2 gap-2">
- <div className="flex flex-col gap-1">
- <label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.proxyHost")}
- </label>
- <Input
- className="h-7 text-xs"
- placeholder="proxy.example.com"
- value={node.host}
- onChange={(e) => {
- const u = [...form.socks5ProxyChain];
- u[ni] = { ...u[ni], host: e.target.value };
- setField("socks5ProxyChain", u);
- }}
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.proxyPort")}
- </label>
- <Input
- className="h-7 text-xs"
- type="number"
- placeholder="1080"
- value={node.port}
- onChange={(e) => {
- const u = [...form.socks5ProxyChain];
- u[ni] = {
- ...u[ni],
- port: Number(e.target.value),
- };
- setField("socks5ProxyChain", u);
- }}
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.proxyType")}
- </label>
- <select
- className="h-7 text-xs border border-border bg-background px-2 outline-none focus:ring-1 focus:ring-ring"
- value={node.type}
- onChange={(e) => {
- const u = [...form.socks5ProxyChain];
- u[ni] = { ...u[ni], type: e.target.value };
- setField("socks5ProxyChain", u);
- }}
- >
- <option value="socks5">SOCKS5</option>
- <option value="socks4">SOCKS4</option>
- <option value="http">HTTP</option>
- </select>
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.proxyUsername")}
- </label>
- <Input
- className="h-7 text-xs"
- placeholder={t("hosts.optional")}
- value={node.username}
- onChange={(e) => {
- const u = [...form.socks5ProxyChain];
- u[ni] = {
- ...u[ni],
- username: e.target.value,
- };
- setField("socks5ProxyChain", u);
- }}
- />
- </div>
- <div className="flex flex-col gap-1 col-span-2">
- <label className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.proxyPassword")}
- </label>
- <PasswordInput
- className="h-7 text-xs pr-8"
- placeholder={t("hosts.optional")}
- value={node.password}
- onChange={(e) => {
- const u = [...form.socks5ProxyChain];
- u[ni] = {
- ...u[ni],
- password: e.target.value,
- };
- setField("socks5ProxyChain", u);
- }}
- />
- </div>
- </div>
- </div>
- ))}
- <Button
- variant="outline"
- size="sm"
- className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand self-start"
- onClick={() =>
- setField("socks5ProxyChain", [
- ...form.socks5ProxyChain,
- {
- host: "",
- port: 1080,
- type: "socks5",
- username: "",
- password: "",
- },
- ])
- }
- >
- <Plus className="size-3 mr-1" />{" "}
- {t("hosts.addProxyNode")}
- </Button>
- </div>
- )}
-
- {/* Connection path visualization */}
- {(form.socks5ProxyMode === "single" && form.socks5Host) ||
- (form.socks5ProxyMode === "chain" &&
- form.socks5ProxyChain.length > 0) ? (
- <div className="flex items-center gap-1 flex-wrap p-2 bg-muted/30 border border-border text-[10px]">
- <span className="px-2 py-0.5 bg-background border border-border text-foreground font-mono">
- {t("hosts.you")}
- </span>
- {form.socks5ProxyMode === "single" &&
- form.socks5Host ? (
- <>
- <span className="text-muted-foreground">→</span>
- <span className="px-2 py-0.5 bg-muted border border-border text-muted-foreground font-mono">
- {form.socks5Host}:{form.socks5Port}
- </span>
- </>
- ) : (
- form.socks5ProxyChain
- .filter((n) => n.host)
- .map((n, ni) => (
- <React.Fragment key={ni}>
- <span className="text-muted-foreground">→</span>
- <span className="px-2 py-0.5 bg-muted border border-border text-muted-foreground font-mono">
- {n.host}:{n.port}
- </span>
- </React.Fragment>
- ))
- )}
- {form.jumpHosts
- .filter((j) => j.hostId)
- .map((j, ji) => {
- const jh = hosts.find((h) => h.id === j.hostId);
- return jh ? (
- <React.Fragment key={`j${ji}`}>
- <span className="text-muted-foreground">→</span>
- <span className="px-2 py-0.5 bg-muted border border-border text-muted-foreground font-mono">
- {jh.name || jh.ip}
- </span>
- </React.Fragment>
- ) : null;
- })}
- <span className="text-muted-foreground">→</span>
- <span className="px-2 py-0.5 bg-accent-brand/10 border border-accent-brand/30 text-accent-brand font-mono">
- {form.ip || "target"}:{form.sshPort}
- </span>
- </div>
- ) : null}
- </div>
- )}
- <div className="flex flex-col gap-3">
- <div className="flex items-center justify-between">
- <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.jumpHostChainLabel")}
- </span>
- <Button
- variant="outline"
- size="sm"
- className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
- onClick={() =>
- setField("jumpHosts", [
- ...form.jumpHosts,
- { hostId: "" },
- ])
- }
- >
- <Plus className="size-3 mr-1" /> {t("hosts.addJumpBtn")}
- </Button>
- </div>
- {form.jumpHosts.length === 0 && (
- <p className="text-[10px] text-muted-foreground/50">
- {t("hosts.noJumpHosts")}
- </p>
- )}
- <div className="flex flex-col gap-2">
- {form.jumpHosts.map((jh, i) => (
- <div
- key={i}
- className="flex items-center gap-2 p-2 bg-background border border-border"
- >
- <span className="text-[10px] font-bold text-muted-foreground shrink-0">
- {i + 1}.
- </span>
- <select
- className="flex h-7 flex-1 border border-border bg-background px-2 py-0 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={jh.hostId}
- onChange={(e) => {
- const updated = [...form.jumpHosts];
- updated[i] = { hostId: e.target.value };
- setField("jumpHosts", updated);
- }}
- >
- <option value="">{t("hosts.selectAServer")}</option>
- {hosts
- .filter((h) => (host ? h.id !== host.id : true))
- .map((h) => (
- <option key={h.id} value={h.id}>
- {h.name || h.ip}
- </option>
- ))}
- </select>
- <Button
- variant="ghost"
- size="icon"
- className="size-7 text-destructive"
- onClick={() =>
- setField(
- "jumpHosts",
- form.jumpHosts.filter((_, idx) => idx !== i),
- )
- }
- >
- <Trash2 className="size-3.5" />
- </Button>
- </div>
- ))}
- </div>
- </div>
- </div>
- </SectionCard>
- </>
- )}
-
- {activeTab === "ssh" && (
- <>
- <SectionCard
- title={t("hosts.connectionLabel")}
- icon={<Globe className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.sshPort")}
- </label>
- <Input
- type="number"
- placeholder="22"
- value={form.sshPort}
- onChange={(e) =>
- setField("sshPort", Number(e.target.value) as any)
- }
- className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
- </div>
- </SectionCard>
- <SectionCard
- title={t("hosts.authenticationLabel")}
- icon={<Shield className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.authMethod")}
- </label>
- <div className="flex flex-wrap gap-2">
- {["password", "key", "credential", "none", "opkssh"].map(
- (m) => (
- <button
- key={m}
- onClick={() => {
- setField("authType", m as any);
- if (m !== "credential") onCredentialChange("");
- else onCredentialChange(form.credentialId);
- }}
- className={`px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${authMethod === m ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
- >
- {m}
- </button>
- ),
- )}
- </div>
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border-t border-border pt-4 mt-1">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.username")}
- </label>
- <Input
- placeholder="root"
- value={form.username}
- disabled={
- authMethod === "credential" &&
- !!selectedCredential?.username &&
- !form.overrideCredentialUsername
- }
- onChange={(e) => setField("username", e.target.value)}
- />
- </div>
- {authMethod === "password" && (
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.password")}
- </label>
- <PasswordInput
- className="h-8 text-xs pr-8"
- placeholder="••••••••"
- value={form.password}
- onChange={(e) => setField("password", e.target.value)}
- />
- </div>
- )}
- {authMethod === "key" && (
- <>
- <div className="flex flex-col gap-1.5 col-span-2">
- <div className="flex items-center justify-between">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.sshPrivateKey")}
- </label>
- <div className="flex gap-1">
- {(["paste", "upload"] as const).map((tab) => (
- <button
- key={tab}
- type="button"
- onClick={() => setField("keySubTab", tab)}
- className={`px-2 py-0.5 text-[9px] font-bold uppercase tracking-widest border transition-colors ${form.keySubTab === tab ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
- >
- {tab === "paste"
- ? t("hosts.keyPasteTab")
- : t("hosts.keyUploadTab")}
- </button>
- ))}
- </div>
- </div>
- {form.keySubTab === "paste" ? (
- <div className="flex flex-col gap-1.5">
- {form.key === "existing_key" && (
- <div className="px-3 py-2 text-[10px] border border-accent-brand/30 bg-accent-brand/5 text-accent-brand">
- {t("hosts.keySaved")} —{" "}
- {t("hosts.keyReplaceNotice")}
- </div>
- )}
- <textarea
- placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
- rows={5}
- value={
- form.key === "existing_key" ? "" : form.key
- }
- onChange={(e) => setField("key", e.target.value)}
- className="w-full px-3 py-2 text-[10px] bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
- />
- </div>
- ) : (
- <div className="flex flex-col gap-2">
- <label
- className={`flex items-center justify-center gap-2 h-16 border-2 border-dashed cursor-pointer transition-colors ${form.key ? "border-accent-brand/40 bg-accent-brand/5 text-accent-brand" : "border-border text-muted-foreground hover:border-accent-brand/30 hover:text-foreground"}`}
- >
- <Upload className="size-4" />
- <span className="text-xs">
- {form.key === "existing_key"
- ? t("hosts.keySaved")
- : form.key
- ? t("hosts.keyFileLoaded")
- : t("hosts.keyUploadClick")}
- </span>
- <input
- type="file"
- accept=".pem,.key,.txt,.ppk"
- className="hidden"
- onChange={async (e) => {
- const file = e.target.files?.[0];
- if (!file) return;
- const text = await file.text();
- setField("key", text);
- e.target.value = "";
- }}
- />
- </label>
- {form.key && (
- <button
- type="button"
- onClick={() => setField("key", "")}
- className="text-[10px] text-destructive self-start"
- >
- {form.key === "existing_key"
- ? t("hosts.replaceKey")
- : t("hosts.clearKey")}
- </button>
- )}
- </div>
- )}
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.keyPassphrase")}
- </label>
- <PasswordInput
- className="h-8 text-xs pr-8"
- placeholder={
- form.keyPassword === "existing_key_password"
- ? t("hosts.keyPassphraseSaved")
- : t("hosts.optional")
- }
- value={
- form.keyPassword === "existing_key_password"
- ? ""
- : form.keyPassword
- }
- onFocus={() => {
- if (form.keyPassword === "existing_key_password")
- setField("keyPassword", "");
- }}
- onChange={(e) =>
- setField("keyPassword", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.keyTypeLabel")}
- </label>
- <select
- value={form.keyType}
- onChange={(e) =>
- setField("keyType", e.target.value as any)
- }
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- >
- <option value="auto">{t("hosts.keyTypeAuto")}</option>
- <option value="ssh-rsa">RSA</option>
- <option value="ssh-ed25519">Ed25519</option>
- <option value="ecdsa-sha2-nistp256">
- ECDSA P-256
- </option>
- <option value="ecdsa-sha2-nistp384">
- ECDSA P-384
- </option>
- <option value="ecdsa-sha2-nistp521">
- ECDSA P-521
- </option>
- <option value="ssh-dss">DSA</option>
- <option value="ssh-rsa-sha2-256">RSA SHA2-256</option>
- <option value="ssh-rsa-sha2-512">RSA SHA2-512</option>
- </select>
- </div>
- </>
- )}
- {authMethod === "credential" && (
- <>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.storedCredential")}
- </label>
- <select
- value={form.credentialId}
- onChange={(e) => {
- const newId = e.target.value;
- setField("credentialId", newId);
- onCredentialChange(newId);
- if (!form.overrideCredentialUsername) {
- const cred = credentials.find(
- (c) => c.id === newId,
- );
- if (cred?.username)
- setField("username", cred.username);
- }
- }}
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- >
- <option value="">
- {t("hosts.selectACredential")}
- </option>
- {credentials.map((c) => (
- <option key={c.id} value={c.id}>
- {c.username
- ? `${c.name} (${c.username})`
- : c.name}
- </option>
- ))}
- </select>
- </div>
- {selectedCredential?.username && (
- <div className="flex items-center justify-between col-span-2 pt-1">
- <div className="flex flex-col gap-0.5">
- <span className="text-xs font-medium">
- {t("hosts.overrideCredentialUsername")}
- </span>
- <span className="text-[10px] text-muted-foreground">
- {t("hosts.overrideCredentialUsernameDesc")}
- </span>
- </div>
- <FakeSwitch
- checked={form.overrideCredentialUsername}
- onChange={(v) => {
- setField("overrideCredentialUsername", v);
- if (!v && selectedCredential?.username) {
- setField(
- "username",
- selectedCredential.username,
- );
- }
- }}
- />
- </div>
- )}
- </>
- )}
- </div>
- <SettingRow
- label={t("hosts.forceKeyboardInteractiveLabel")}
- description={t("hosts.forceKeyboardInteractiveShortDesc")}
- >
- <FakeSwitch
- checked={form.forceKeyboardInteractive}
- onChange={(v) => setField("forceKeyboardInteractive", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.terminalAppearance")}
- icon={<Palette className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="space-y-2">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.themePreview")}
- </label>
- <TerminalPreview
- theme={form.theme}
- fontSize={form.fontSize}
- fontFamily={form.fontFamily}
- cursorStyle={form.cursorStyle}
- cursorBlink={form.cursorBlink}
- letterSpacing={form.letterSpacing}
- lineHeight={form.lineHeight}
- />
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.colorTheme")}
- </label>
- <select
- value={form.theme}
- onChange={(e) => {
- setField("theme", e.target.value);
- setPreviewTerminalTheme(e.target.value);
- }}
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- >
- {Object.entries(TERMINAL_THEMES)
- .filter(
- ([key]) =>
- key !== "termixDark" && key !== "termixLight",
- )
- .map(([key, theme]) => (
- <option key={key} value={key}>
- {theme.name}
- </option>
- ))}
- </select>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.fontFamilyLabel")}
- </label>
- <select
- value={form.fontFamily}
- onChange={(e) => setField("fontFamily", e.target.value)}
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring font-mono"
- >
- {TERMINAL_FONTS.map((f) => (
- <option key={f.value} value={f.value}>
- {f.label}
- </option>
- ))}
- </select>
- </div>
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.fontSizeLabel")}
- </label>
- <span className="text-[10px] text-muted-foreground tabular-nums">
- {form.fontSize}px
- </span>
- </div>
- <Slider
- min={8}
- max={24}
- step={1}
- value={[form.fontSize]}
- onValueChange={([v]) => setField("fontSize", v as any)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.cursorStyleLabel")}
- </label>
- <select
- value={form.cursorStyle}
- onChange={(e) =>
- setField("cursorStyle", e.target.value as any)
- }
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- >
- {CURSOR_STYLES.map((s) => (
- <option key={s.value} value={s.value}>
- {s.label}
- </option>
- ))}
- </select>
- </div>
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.letterSpacingPx")}
- </label>
- <span className="text-[10px] text-muted-foreground tabular-nums">
- {form.letterSpacing}px
- </span>
- </div>
- <Slider
- min={-2}
- max={10}
- step={0.5}
- value={[form.letterSpacing]}
- onValueChange={([v]) =>
- setField("letterSpacing", v as any)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.lineHeightLabel")}
- </label>
- <span className="text-[10px] text-muted-foreground tabular-nums">
- {form.lineHeight.toFixed(1)}
- </span>
- </div>
- <Slider
- min={1.0}
- max={2.0}
- step={0.1}
- value={[form.lineHeight]}
- onValueChange={([v]) => setField("lineHeight", v as any)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.bellStyleLabel")}
- </label>
- <select
- value={form.bellStyle}
- onChange={(e) =>
- setField("bellStyle", e.target.value as any)
- }
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- >
- {BELL_STYLES.map((b) => (
- <option key={b.value} value={b.value}>
- {b.label}
- </option>
- ))}
- </select>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.backspaceModeLabel")}
- </label>
- <select
- value={form.backspaceMode}
- onChange={(e) =>
- setField("backspaceMode", e.target.value as any)
- }
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- >
- <option value="normal">Normal (DEL)</option>
- <option value="control-h">Control-H (BS)</option>
- </select>
- </div>
- </div>
- <SettingRow
- label={t("hosts.cursorBlinking")}
- description={t("hosts.cursorBlinkingDesc")}
- >
- <FakeSwitch
- checked={form.cursorBlink}
- onChange={(v) => setField("cursorBlink", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.rightClickSelectsWordLabel")}
- description={t("hosts.rightClickSelectsWordShortDesc")}
- >
- <FakeSwitch
- checked={form.rightClickSelectsWord}
- onChange={(v) => setField("rightClickSelectsWord", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.behaviorAndAdvanced")}
- icon={<Zap className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.scrollbackBufferLabel")}
- </label>
- <span className="text-[10px] text-muted-foreground tabular-nums">
- {form.scrollback.toLocaleString()}{" "}
- {t("hosts.scrollbackMaxLines")}
- </span>
- </div>
- <Slider
- min={1000}
- max={100000}
- step={1000}
- value={[form.scrollback]}
- onValueChange={([v]) => setField("scrollback", v as any)}
- />
- </div>
- <SettingRow
- label={t("hosts.sshAgentForwardingLabel")}
- description={t("hosts.sshAgentForwardingShortDesc")}
- >
- <FakeSwitch
- checked={form.agentForwarding}
- onChange={(v) => setField("agentForwarding", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.enableAutoMosh")}
- description={t("hosts.enableAutoMoshDesc")}
- >
- <FakeSwitch
- checked={form.autoMosh}
- onChange={(v) => setField("autoMosh", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.enableAutoTmux")}
- description={t("hosts.enableAutoTmuxDesc")}
- >
- <FakeSwitch
- checked={form.autoTmux}
- onChange={(v) => setField("autoTmux", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.sudoPasswordAutoFillLabel")}
- description={t("hosts.sudoPasswordAutoFillShortDesc")}
- >
- <FakeSwitch
- checked={form.sudoPasswordAutoFill}
- onChange={(v) => setField("sudoPasswordAutoFill", v)}
- />
- </SettingRow>
- {form.sudoPasswordAutoFill && (
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.sudoPasswordLabel")}
- </label>
- <PasswordInput
- className="h-8 text-xs pr-8"
- placeholder="••••••••"
- value={form.sudoPassword}
- onChange={(e) => setField("sudoPassword", e.target.value)}
- />
- </div>
- )}
- <div className="flex flex-col gap-3">
- <div className="flex items-center justify-between">
- <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.environmentVariablesLabel")}
- </span>
- <Button
- variant="outline"
- size="sm"
- className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
- onClick={() =>
- setField("environmentVariables", [
- ...form.environmentVariables,
- { key: "", value: "" },
- ])
- }
- >
- <Plus className="size-3 mr-1" />{" "}
- {t("hosts.addVariableBtn")}
- </Button>
- </div>
- {form.environmentVariables.length === 0 && (
- <p className="text-[10px] text-muted-foreground/50">
- {t("hosts.noEnvVars")}
- </p>
- )}
- <div className="flex flex-col gap-2">
- {form.environmentVariables.map((ev, i) => (
- <div key={i} className="flex items-center gap-2">
- <Input
- className="h-7 text-xs flex-1"
- placeholder="KEY"
- value={ev.key}
- onChange={(e) => {
- const updated = [...form.environmentVariables];
- updated[i] = { ...updated[i], key: e.target.value };
- setField("environmentVariables", updated);
- }}
- />
- <Input
- className="h-7 text-xs flex-1"
- placeholder="VALUE"
- value={ev.value}
- onChange={(e) => {
- const updated = [...form.environmentVariables];
- updated[i] = {
- ...updated[i],
- value: e.target.value,
- };
- setField("environmentVariables", updated);
- }}
- />
- <button
- className="text-destructive"
- onClick={() =>
- setField(
- "environmentVariables",
- form.environmentVariables.filter(
- (_, idx) => idx !== i,
- ),
- )
- }
- >
- <X className="size-4" />
- </button>
- </div>
- ))}
- </div>
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border-t border-border pt-4">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.fastScrollModifierLabel")}
- </label>
- <select
- value={form.fastScrollModifier}
- onChange={(e) =>
- setField("fastScrollModifier", e.target.value as any)
- }
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- >
- {FAST_SCROLL_MODIFIERS.map((m) => (
- <option key={m.value} value={m.value}>
- {m.label}
- </option>
- ))}
- </select>
- </div>
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.fastScrollSensitivityLabel")}
- </label>
- <span className="text-[10px] text-muted-foreground tabular-nums">
- {form.fastScrollSensitivity}
- </span>
- </div>
- <Slider
- min={1}
- max={10}
- step={1}
- value={[form.fastScrollSensitivity]}
- onValueChange={([v]) =>
- setField("fastScrollSensitivity", v as any)
- }
- />
- </div>
- </div>
- {form.autoMosh && (
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.moshCommandLabel")}
- </label>
- <Input
- placeholder="mosh"
- value={form.moshCommand}
- onChange={(e) => setField("moshCommand", e.target.value)}
- />
- </div>
- )}
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border-t border-border pt-4">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.startupSnippetLabel")}
- </label>
- <select
- value={form.startupSnippetId ?? ""}
- onChange={(e) =>
- setField(
- "startupSnippetId",
- e.target.value ? Number(e.target.value) : null,
- )
- }
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- >
- <option value="">{t("hosts.none")}</option>
- {snippets.map((s) => (
- <option key={s.id} value={s.id}>
- {s.name}
- </option>
- ))}
- </select>
- </div>
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 border-t border-border pt-4">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.keepaliveIntervalLabel")}
- </label>
- <Input
- type="number"
- value={form.keepaliveInterval}
- onChange={(e) =>
- setField(
- "keepaliveInterval",
- Number(e.target.value) as any,
- )
- }
- className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.maxKeepaliveMisses")}
- </label>
- <Input
- type="number"
- value={form.keepaliveCountMax}
- onChange={(e) =>
- setField(
- "keepaliveCountMax",
- Number(e.target.value) as any,
- )
- }
- className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
- </div>
- </div>
- </SectionCard>
- </>
- )}
-
- {activeTab === "tunnels" && (
- <>
- <SectionCard
- title={t("hosts.tunnelSettings")}
- icon={<Network className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <SettingRow
- label={t("hosts.enableTunneling")}
- description={t("hosts.enableTunnelingDesc")}
- >
- <FakeSwitch
- checked={form.enableTunnel}
- onChange={(v) => setField("enableTunnel", v)}
- />
- </SettingRow>
- <div className="text-xs text-muted-foreground p-3 bg-muted/30 border border-border space-y-1">
- <p>{t("hosts.tunnelRequirementsText")}</p>
- </div>
- </div>
- </SectionCard>
- <SectionCard
- title={t("hosts.serverTunnelsSection")}
- icon={<Network className="size-3.5" />}
- action={
- <Button
- variant="outline"
- size="sm"
- className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
- onClick={() =>
- setField("serverTunnels", [
- ...form.serverTunnels,
- {
- mode: "local" as const,
- sourcePort: 8080,
- endpointHost: "",
- endpointPort: 80,
- bindHost: "127.0.0.1",
- maxRetries: 3,
- retryInterval: 10,
- autoStart: false,
- },
- ])
- }
- >
- <Plus className="size-3 mr-1" /> {t("hosts.addTunnelBtn")}
- </Button>
- }
- >
- <div className="flex flex-col gap-3 py-3">
- {form.serverTunnels.length === 0 && (
- <p className="text-[10px] text-muted-foreground/50 px-1">
- {t("hosts.noTunnelsConfigured")}
- </p>
- )}
- {form.serverTunnels.map((tun, i) => {
- const tunnelName = `${host?.id ?? "new"}-${i}-${tun.sourcePort}`;
- const tunnelStatus = tunnelStatuses[tunnelName]?.status as
- | string
- | undefined;
- const isConnected = tunnelStatus === "connected";
- return (
- <div
- key={i}
- className="flex flex-col gap-3 p-3 border border-border bg-muted/20 relative group"
- >
- <div className="flex items-center justify-between mb-1">
- <div className="flex items-center gap-2">
- <span className="text-xs font-bold text-muted-foreground">
- {t("hosts.tunnelLabel", { number: i + 1 })}
- </span>
- <div
- className={`size-1.5 rounded-full shrink-0 ${
- isConnected
- ? "bg-accent-brand shadow-[0_0_4px_rgba(251,146,60,0.4)]"
- : tunnelStatus === "error"
- ? "bg-red-400"
- : "bg-muted-foreground/25"
- }`}
- title={tunnelStatus ?? "not connected"}
- />
- {host && (
- <Button
- variant="outline"
- size="sm"
- disabled={connectingTunnel === i}
- className={`h-6 text-[10px] px-2 ${isConnected ? "border-destructive/40 text-destructive hover:bg-destructive/10" : "border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10"}`}
- onClick={async () => {
- setConnectingTunnel(i);
- try {
- if (isConnected) {
- await disconnectTunnel(tunnelName);
- toast.success(
- t("hosts.tunnelDisconnected"),
- );
- } else {
- await connectTunnel({
- name: tunnelName,
- mode: tun.mode as any,
- sourceHostId: Number(host.id),
- tunnelIndex: i,
- hostName: host.name,
- sourceIP: host.ip,
- sourceSSHPort: host.sshPort ?? host.port,
- sourceUsername: form.username,
- sourcePassword:
- form.password || undefined,
- sourceAuthMethod: form.authType,
- sourceSSHKey: form.key || undefined,
- sourceKeyPassword:
- form.keyPassword || undefined,
- sourceCredentialId: form.credentialId
- ? Number(form.credentialId)
- : undefined,
- endpointIP: host.ip,
- endpointSSHPort:
- host.sshPort ?? host.port,
- endpointHost: tun.endpointHost ?? "",
- endpointUsername: form.username,
- endpointAuthMethod: form.authType,
- sourcePort: tun.sourcePort,
- endpointPort: tun.endpointPort ?? 0,
- bindHost: tun.bindHost ?? "127.0.0.1",
- maxRetries: tun.maxRetries ?? 3,
- retryInterval: tun.retryInterval ?? 10,
- autoStart: tun.autoStart ?? false,
- isPinned: false,
- });
- toast.success(t("hosts.tunnelConnecting"));
- }
- } catch {
- toast.error(
- isConnected
- ? t("hosts.failedToDisconnectTunnel")
- : t("hosts.failedToConnectTunnel"),
- );
- } finally {
- setConnectingTunnel(null);
- }
- }}
- >
- {connectingTunnel === i
- ? "..."
- : isConnected
- ? t("hosts.disconnectBtn")
- : t("hosts.connectBtn")}
- </Button>
- )}
- </div>
- <Button
- variant="ghost"
- size="sm"
- className="h-6 text-[10px] px-2 text-destructive"
- onClick={() =>
- setField(
- "serverTunnels",
- form.serverTunnels.filter((_, idx) => idx !== i),
- )
- }
- >
- {t("common.delete")}
- </Button>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold text-muted-foreground">
- {t("hosts.tunnelType")}
- </label>
- <div className="flex gap-2">
- {(["remote", "local", "dynamic"] as const).map(
- (m) => (
- <button
- key={m}
- onClick={() => {
- const updated = [...form.serverTunnels];
- updated[i] = { ...updated[i], mode: m };
- setField("serverTunnels", updated);
- }}
- className={`px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${tun.mode === m ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
- >
- {m}
- </button>
- ),
- )}
- </div>
- <p className="text-[10px] text-muted-foreground/70 mt-0.5">
- {tun.mode === "local"
- ? t("hosts.tunnelModeLocalDesc")
- : tun.mode === "remote"
- ? t("hosts.tunnelModeRemoteDesc")
- : t("hosts.tunnelModeDynamicDesc")}
- </p>
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- {tun.mode !== "dynamic" && (
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-bold text-muted-foreground">
- {t("hosts.endpointHost")}
- </label>
- <select
- className="h-7 text-xs border border-border bg-background px-2 outline-none focus:ring-1 focus:ring-ring"
- value={tun.endpointHost ?? ""}
- onChange={(e) => {
- const updated = [...form.serverTunnels];
- updated[i] = {
- ...updated[i],
- endpointHost: e.target.value,
- };
- setField("serverTunnels", updated);
- }}
- >
- <option value="">
- {t("hosts.selectAServer")}
- </option>
- <option value="127.0.0.1">
- 127.0.0.1 (localhost)
- </option>
- {hosts
- .filter((h) => h.enableSsh)
- .map((h) => (
- <option key={h.id} value={h.ip}>
- {h.name || h.ip} ({h.ip})
- </option>
- ))}
- </select>
- </div>
- )}
- {tun.mode !== "dynamic" && (
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-bold text-muted-foreground">
- {t("hosts.endpointPort")}
- </label>
- <Input
- className="h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- type="number"
- value={tun.endpointPort}
- onChange={(e) => {
- const updated = [...form.serverTunnels];
- updated[i] = {
- ...updated[i],
- endpointPort: Number(e.target.value),
- };
- setField("serverTunnels", updated);
- }}
- />
- </div>
- )}
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-bold text-muted-foreground">
- {t("hosts.bindHost")}
- </label>
- <Input
- className="h-7 text-xs"
- placeholder="127.0.0.1"
- value={tun.bindHost ?? ""}
- onChange={(e) => {
- const updated = [...form.serverTunnels];
- updated[i] = {
- ...updated[i],
- bindHost: e.target.value,
- };
- setField("serverTunnels", updated);
- }}
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-bold text-muted-foreground">
- {t("hosts.sourcePort")}
- </label>
- <Input
- className="h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- type="number"
- value={tun.sourcePort}
- onChange={(e) => {
- const updated = [...form.serverTunnels];
- updated[i] = {
- ...updated[i],
- sourcePort: Number(e.target.value),
- };
- setField("serverTunnels", updated);
- }}
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-bold text-muted-foreground">
- {t("hosts.maxRetries")}
- </label>
- <Input
- className="h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- type="number"
- value={tun.maxRetries}
- onChange={(e) => {
- const updated = [...form.serverTunnels];
- updated[i] = {
- ...updated[i],
- maxRetries: Number(e.target.value),
- };
- setField("serverTunnels", updated);
- }}
- />
- </div>
- <div className="flex flex-col gap-1">
- <label className="text-[10px] font-bold text-muted-foreground">
- {t("hosts.retryIntervalS")}
- </label>
- <Input
- className="h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- type="number"
- value={tun.retryInterval}
- onChange={(e) => {
- const updated = [...form.serverTunnels];
- updated[i] = {
- ...updated[i],
- retryInterval: Number(e.target.value),
- };
- setField("serverTunnels", updated);
- }}
- />
- </div>
- </div>
- <SettingRow
- label={t("hosts.autoStartLabel")}
- description={t("hosts.autoStartDesc")}
- >
- <FakeSwitch
- checked={tun.autoStart}
- onChange={(v) => {
- const updated = [...form.serverTunnels];
- updated[i] = { ...updated[i], autoStart: v };
- setField("serverTunnels", updated);
- }}
- />
- </SettingRow>
- </div>
- );
- })}
- </div>
- </SectionCard>
- </>
- )}
-
- {activeTab === "docker" && (
- <SectionCard
- title={t("hosts.dockerIntegration")}
- icon={<Box className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <SettingRow
- label={t("hosts.enableDockerMonitor")}
- description={t("hosts.enableDockerMonitorDesc")}
- >
- <FakeSwitch
- checked={form.enableDocker}
- onChange={(v) => setField("enableDocker", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
- )}
-
- {activeTab === "files" && (
- <SectionCard
- title={t("hosts.fileManager")}
- icon={<FolderSearch className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <SettingRow
- label={t("hosts.enableFileManagerMonitor")}
- description={t("hosts.enableFileManagerMonitorDesc")}
- >
- <FakeSwitch
- checked={form.enableFileManager}
- onChange={(v) => setField("enableFileManager", v)}
- />
- </SettingRow>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.defaultPathLabel")}
- </label>
- <Input
- placeholder="/"
- value={form.defaultPath}
- onChange={(e) => setField("defaultPath", e.target.value)}
- />
- <span className="text-[10px] text-muted-foreground">
- {t("hosts.fileManagerPathHint")}
- </span>
- </div>
- </div>
- </SectionCard>
- )}
-
- {activeTab === "stats" && (
- <>
- <SectionCard
- title={t("hosts.statusChecksLabel")}
- icon={<Activity className="size-3.5" />}
- >
- <div className="flex flex-col gap-0 py-1">
- <SettingRow
- label={t("hosts.enableStatusChecks")}
- description={t("hosts.enableStatusChecksDesc")}
- >
- <FakeSwitch
- checked={form.statsConfig.statusCheckEnabled}
- onChange={(v) =>
- setField("statsConfig", {
- ...form.statsConfig,
- statusCheckEnabled: v,
- })
- }
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.useGlobalInterval")}
- description={t("hosts.useGlobalIntervalDesc")}
- >
- <FakeSwitch
- checked={form.statsConfig.useGlobalStatusInterval}
- onChange={(v) =>
- setField("statsConfig", {
- ...form.statsConfig,
- useGlobalStatusInterval: v,
- })
- }
- />
- </SettingRow>
- {form.statsConfig.statusCheckEnabled &&
- !form.statsConfig.useGlobalStatusInterval && (
- <SettingRow
- label={t("hosts.checkIntervalS")}
- description={t("hosts.checkIntervalDesc")}
- >
- <Input
- type="number"
- value={form.statsConfig.statusCheckInterval}
- onChange={(e) =>
- setField("statsConfig", {
- ...form.statsConfig,
- statusCheckInterval: Number(e.target.value),
- })
- }
- className="w-20 h-7 text-xs text-right [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </SettingRow>
- )}
- </div>
- </SectionCard>
- <SectionCard
- title={t("hosts.metricsCollectionLabel")}
- icon={<Server className="size-3.5" />}
- >
- <div className="flex flex-col gap-0 py-1">
- <SettingRow
- label={t("hosts.enableMetricsLabel")}
- description={t("hosts.enableMetricsDesc")}
- >
- <FakeSwitch
- checked={form.statsConfig.metricsEnabled}
- onChange={(v) =>
- setField("statsConfig", {
- ...form.statsConfig,
- metricsEnabled: v,
- })
- }
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.useGlobalMetrics")}
- description={t("hosts.useGlobalMetricsDesc")}
- >
- <FakeSwitch
- checked={form.statsConfig.useGlobalMetricsInterval}
- onChange={(v) =>
- setField("statsConfig", {
- ...form.statsConfig,
- useGlobalMetricsInterval: v,
- })
- }
- />
- </SettingRow>
- {form.statsConfig.metricsEnabled &&
- !form.statsConfig.useGlobalMetricsInterval && (
- <SettingRow
- label={t("hosts.metricsIntervalS")}
- description={t("hosts.metricsIntervalDesc2")}
- >
- <Input
- type="number"
- value={form.statsConfig.metricsInterval}
- onChange={(e) =>
- setField("statsConfig", {
- ...form.statsConfig,
- metricsInterval: Number(e.target.value),
- })
- }
- className="w-20 h-7 text-xs text-right [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </SettingRow>
- )}
- </div>
- </SectionCard>
- <SectionCard
- title={t("hosts.visibleWidgets")}
- icon={<LayoutDashboard className="size-3.5" />}
- >
- <div className="flex flex-col gap-0 py-1">
- {[
- {
- id: "cpu",
- label: t("hosts.cpuUsageLabel"),
- desc: t("hosts.cpuUsageDesc"),
- },
- {
- id: "memory",
- label: t("hosts.memoryLabel"),
- desc: t("hosts.memoryDesc"),
- },
- {
- id: "disk",
- label: t("hosts.storageLabel"),
- desc: t("hosts.storageDesc"),
- },
- {
- id: "network",
- label: t("hosts.networkLabel"),
- desc: t("hosts.networkDesc"),
- },
- {
- id: "uptime",
- label: t("hosts.uptimeLabel"),
- desc: t("hosts.uptimeDesc"),
- },
- {
- id: "system",
- label: t("hosts.systemInfoLabel"),
- desc: t("hosts.systemInfoDesc"),
- },
- {
- id: "login_stats",
- label: t("hosts.recentLoginsLabel"),
- desc: t("hosts.recentLoginsDesc"),
- },
- {
- id: "processes",
- label: t("hosts.topProcessesLabel"),
- desc: t("hosts.topProcessesDesc"),
- },
- {
- id: "ports",
- label: t("hosts.listeningPortsLabel"),
- desc: t("hosts.listeningPortsDesc"),
- },
- {
- id: "firewall",
- label: t("hosts.firewallLabel"),
- desc: t("hosts.firewallDesc"),
- },
- ].map((w) => (
- <SettingRow key={w.id} label={w.label} description={w.desc}>
- <FakeSwitch
- checked={form.statsConfig.enabledWidgets.includes(w.id)}
- onChange={(v) => {
- const widgets = v
- ? [...form.statsConfig.enabledWidgets, w.id]
- : form.statsConfig.enabledWidgets.filter(
- (x) => x !== w.id,
- );
- setField("statsConfig", {
- ...form.statsConfig,
- enabledWidgets: widgets,
- });
- }}
- />
- </SettingRow>
- ))}
- </div>
- </SectionCard>
- <SectionCard
- title={t("hosts.quickActionsLabel")}
- icon={<Zap className="size-3.5" />}
- action={
- <Button
- variant="outline"
- size="sm"
- className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
- onClick={() =>
- setField("quickActions", [
- ...form.quickActions,
- { name: "", snippetId: "" },
- ])
- }
- >
- <Plus className="size-3 mr-1" /> {t("hosts.addActionBtn")}
- </Button>
- }
- >
- <div className="flex flex-col gap-3 py-3">
- <p className="text-xs text-muted-foreground">
- {t("hosts.quickActionsToolbar")}
- </p>
- {form.quickActions.length === 0 && (
- <div className="flex flex-col items-center justify-center py-4 text-muted-foreground/40 gap-1.5">
- <Zap className="size-6" />
- <span className="text-xs">{t("hosts.noQuickActions")}</span>
- </div>
- )}
- {form.quickActions.map((a, i) => (
- <div
- key={i}
- className="flex items-center gap-2 p-2 bg-muted/20 border border-border group"
- >
- <Input
- className="h-7 text-xs flex-1"
- placeholder={t("hosts.buttonLabel")}
- value={a.name}
- onChange={(e) => {
- const updated = [...form.quickActions];
- updated[i] = { ...updated[i], name: e.target.value };
- setField("quickActions", updated);
- }}
- />
- <select
- className="h-7 text-xs flex-1 border border-border bg-background px-2 outline-none focus:ring-1 focus:ring-ring"
- value={a.snippetId}
- onChange={(e) => {
- const updated = [...form.quickActions];
- updated[i] = {
- ...updated[i],
- snippetId: e.target.value,
- };
- setField("quickActions", updated);
- }}
- >
- <option value="">
- {t("hosts.selectSnippetPlaceholder")}
- </option>
- {snippets.map((s) => (
- <option key={s.id} value={String(s.id)}>
- {s.name}
- </option>
- ))}
- </select>
- <button
- className="text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"
- onClick={() =>
- setField(
- "quickActions",
- form.quickActions.filter((_, idx) => idx !== i),
- )
- }
- >
- <Trash2 className="size-3.5" />
- </button>
- </div>
- ))}
- </div>
- </SectionCard>
- </>
- )}
-
- {activeTab === "rdp" && (
- <>
- <SectionCard
- title={t("hosts.guac.connection")}
- icon={<Globe className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.rdpPort")}
- </label>
- <Input
- type="number"
- placeholder="3389"
- value={form.rdpPort}
- onChange={(e) =>
- setField("rdpPort", Number(e.target.value) as any)
- }
- className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
- </div>
- </SectionCard>
- <SectionCard
- title={t("hosts.guac.authentication")}
- icon={<Shield className="size-3.5" />}
- >
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.username")}
- </label>
- <Input
- placeholder="Administrator"
- value={form.rdpUser}
- onChange={(e) => setField("rdpUser", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.password")}
- </label>
- <PasswordInput
- className="h-8 text-xs pr-8"
- placeholder="••••••••"
- value={form.rdpPassword}
- onChange={(e) => setField("rdpPassword", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.domain")}
- </label>
- <Input
- placeholder="WORKGROUP"
- value={form.domain}
- onChange={(e) => setField("domain", e.target.value)}
- />
- </div>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.connectionSettings")}
- icon={<Shield className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.securityMode")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={form.security ?? "any"}
- onChange={(e) => setField("security", e.target.value)}
- >
- <option value="any">Any</option>
- <option value="nla">NLA</option>
- <option value="nla-ext">NLA Extended</option>
- <option value="tls">TLS</option>
- <option value="vmconnect">VMConnect</option>
- <option value="rdp">RDP</option>
- </select>
- </div>
- <SettingRow
- label={t("hosts.guac.ignoreCertificate")}
- description={t("hosts.guac.ignoreCertificateDesc")}
- >
- <FakeSwitch
- checked={form.ignoreCert}
- onChange={(v) => setField("ignoreCert", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.displaySettings")}
- icon={<Monitor className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.colorDepth")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={form.guacamoleConfig["color-depth"] ?? "auto"}
- onChange={(e) =>
- setGuacField("color-depth", e.target.value)
- }
- >
- <option value="auto">Auto</option>
- <option value="8">8-bit</option>
- <option value="16">16-bit</option>
- <option value="24">24-bit</option>
- <option value="32">32-bit</option>
- </select>
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.width")}
- </label>
- <Input
- type="number"
- placeholder="Auto"
- value={form.guacamoleConfig["width"] ?? ""}
- onChange={(e) => setGuacField("width", e.target.value)}
- className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.height")}
- </label>
- <Input
- type="number"
- placeholder="Auto"
- value={form.guacamoleConfig["height"] ?? ""}
- onChange={(e) => setGuacField("height", e.target.value)}
- className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.dpi")}
- </label>
- <Input
- type="number"
- placeholder="96"
- value={form.guacamoleConfig["dpi"] ?? ""}
- onChange={(e) => setGuacField("dpi", e.target.value)}
- className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.resizeMethod")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={form.guacamoleConfig["resize-method"] ?? "auto"}
- onChange={(e) =>
- setGuacField("resize-method", e.target.value)
- }
- >
- <option value="auto">Auto</option>
- <option value="display-update">Display Update</option>
- <option value="reconnect">Reconnect</option>
- </select>
- </div>
- <SettingRow
- label={t("hosts.guac.forceLossless")}
- description={t("hosts.guac.forceLosslessDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["force-lossless"]}
- onChange={(v) => setGuacField("force-lossless", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.audioSettings")}
- icon={<Activity className="size-3.5" />}
- >
- <div className="flex flex-col gap-0 py-1">
- <SettingRow
- label={t("hosts.guac.disableAudio")}
- description={t("hosts.guac.disableAudioDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["disable-audio"]}
- onChange={(v) => setGuacField("disable-audio", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.enableAudioInput")}
- description={t("hosts.guac.enableAudioInputDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["enable-audio-input"]}
- onChange={(v) => setGuacField("enable-audio-input", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.rdpPerformance")}
- icon={<Zap className="size-3.5" />}
- >
- <div className="flex flex-col gap-0 py-1">
- <SettingRow
- label={t("hosts.guac.wallpaper")}
- description={t("hosts.guac.wallpaperDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["enable-wallpaper"]}
- onChange={(v) => setGuacField("enable-wallpaper", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.theming")}
- description={t("hosts.guac.themingDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["enable-theming"]}
- onChange={(v) => setGuacField("enable-theming", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.fontSmoothing")}
- description={t("hosts.guac.fontSmoothingDesc")}
- >
- <FakeSwitch
- checked={
- form.guacamoleConfig["enable-font-smoothing"] !== false
- }
- onChange={(v) => setGuacField("enable-font-smoothing", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.fullWindowDrag")}
- description={t("hosts.guac.fullWindowDragDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["enable-full-window-drag"]}
- onChange={(v) => setGuacField("enable-full-window-drag", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.desktopComposition")}
- description={t("hosts.guac.desktopCompositionDesc")}
- >
- <FakeSwitch
- checked={
- !!form.guacamoleConfig["enable-desktop-composition"]
- }
- onChange={(v) =>
- setGuacField("enable-desktop-composition", v)
- }
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.menuAnimations")}
- description={t("hosts.guac.menuAnimationsDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["enable-menu-animations"]}
- onChange={(v) => setGuacField("enable-menu-animations", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.disableBitmapCaching")}
- description={t("hosts.guac.disableBitmapCachingDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["disable-bitmap-caching"]}
- onChange={(v) => setGuacField("disable-bitmap-caching", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.disableOffscreenCaching")}
- description={t("hosts.guac.disableOffscreenCachingDesc")}
- >
- <FakeSwitch
- checked={
- !!form.guacamoleConfig["disable-offscreen-caching"]
- }
- onChange={(v) =>
- setGuacField("disable-offscreen-caching", v)
- }
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.disableGlyphCaching")}
- description={t("hosts.guac.disableGlyphCachingDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["disable-glyph-caching"]}
- onChange={(v) => setGuacField("disable-glyph-caching", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.enableGfx")}
- description={t("hosts.guac.enableGfxDesc")}
- >
- <FakeSwitch
- checked={form.guacamoleConfig["enable-gfx"] !== false}
- onChange={(v) => setGuacField("enable-gfx", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.deviceRedirection")}
- icon={<Settings className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <SettingRow
- label={t("hosts.guac.enablePrinting")}
- description={t("hosts.guac.enablePrintingDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["enable-printing"]}
- onChange={(v) => setGuacField("enable-printing", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.enableDriveRedirection")}
- description={t("hosts.guac.enableDriveRedirectionDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["enable-drive"]}
- onChange={(v) => setGuacField("enable-drive", v)}
- />
- </SettingRow>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3 border-t border-border pt-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.driveName")}
- </label>
- <Input
- placeholder="Termix Drive"
- value={form.guacamoleConfig["drive-name"] ?? ""}
- onChange={(e) =>
- setGuacField("drive-name", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.drivePath")}
- </label>
- <Input
- placeholder="/home/user/shared"
- value={form.guacamoleConfig["drive-path"] ?? ""}
- onChange={(e) =>
- setGuacField("drive-path", e.target.value)
- }
- />
- </div>
- </div>
- <SettingRow
- label={t("hosts.guac.createDrivePath")}
- description={t("hosts.guac.createDrivePathDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["create-drive-path"]}
- onChange={(v) => setGuacField("create-drive-path", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.disableDownload")}
- description={t("hosts.guac.disableDownloadDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["disable-download"]}
- onChange={(v) => setGuacField("disable-download", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.disableUpload")}
- description={t("hosts.guac.disableUploadDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["disable-upload"]}
- onChange={(v) => setGuacField("disable-upload", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.enableTouch")}
- description={t("hosts.guac.enableTouchDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["enable-touch"]}
- onChange={(v) => setGuacField("enable-touch", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.session")}
- icon={<Server className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.clientName")}
- </label>
- <Input
- placeholder="Termix"
- value={form.guacamoleConfig["client-name"] ?? ""}
- onChange={(e) =>
- setGuacField("client-name", e.target.value)
- }
- />
- </div>
- <SettingRow
- label={t("hosts.guac.consoleSession")}
- description={t("hosts.guac.consoleSessionDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["console"]}
- onChange={(v) => setGuacField("console", v)}
- />
- </SettingRow>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.initialProgram")}
- </label>
- <Input
- placeholder="e.g. cmd.exe"
- value={form.guacamoleConfig["initial-program"] ?? ""}
- onChange={(e) =>
- setGuacField("initial-program", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.serverLayout")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={form.guacamoleConfig["server-layout"] ?? "auto"}
- onChange={(e) =>
- setGuacField("server-layout", e.target.value)
- }
- >
- <option value="auto">Auto</option>
- <option>en-us-qwerty</option>
- <option>en-gb-qwerty</option>
- <option>de-de-qwertz</option>
- <option>fr-fr-azerty</option>
- <option>it-it-qwerty</option>
- <option>sv-se-qwerty</option>
- <option>ja-jp-qwerty</option>
- <option>pt-br-qwerty</option>
- <option>es-es-qwerty</option>
- <option>failsafe</option>
- </select>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.timezone")}
- </label>
- <Input
- placeholder="e.g. America/New_York"
- value={form.guacamoleConfig["timezone"] ?? ""}
- onChange={(e) => setGuacField("timezone", e.target.value)}
- />
- </div>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.gateway")}
- icon={<Network className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.gatewayHostname")}
- </label>
- <Input
- placeholder="gateway.example.com"
- value={form.guacamoleConfig["gateway-hostname"] ?? ""}
- onChange={(e) =>
- setGuacField("gateway-hostname", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.gatewayPort")}
- </label>
- <Input
- type="number"
- placeholder="443"
- value={form.guacamoleConfig["gateway-port"] ?? ""}
- onChange={(e) =>
- setGuacField("gateway-port", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.gatewayUsername")}
- </label>
- <Input
- placeholder="user"
- value={form.guacamoleConfig["gateway-username"] ?? ""}
- onChange={(e) =>
- setGuacField("gateway-username", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.gatewayPassword")}
- </label>
- <PasswordInput
- className="h-8 text-xs pr-8"
- placeholder="••••••••"
- value={form.guacamoleConfig["gateway-password"] ?? ""}
- onChange={(e) =>
- setGuacField("gateway-password", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5 col-span-2">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.gatewayDomain")}
- </label>
- <Input
- placeholder="DOMAIN"
- value={form.guacamoleConfig["gateway-domain"] ?? ""}
- onChange={(e) =>
- setGuacField("gateway-domain", e.target.value)
- }
- />
- </div>
- </div>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.remoteApp")}
- icon={<Monitor className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.remoteAppProgram")}
- </label>
- <Input
- placeholder="||MyApp"
- value={form.guacamoleConfig["remote-app"] ?? ""}
- onChange={(e) => setGuacField("remote-app", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.workingDirectory")}
- </label>
- <Input
- placeholder="C:\Apps\MyApp"
- value={form.guacamoleConfig["remote-app-dir"] ?? ""}
- onChange={(e) =>
- setGuacField("remote-app-dir", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.arguments")}
- </label>
- <Input
- placeholder="--flag value"
- value={form.guacamoleConfig["remote-app-args"] ?? ""}
- onChange={(e) =>
- setGuacField("remote-app-args", e.target.value)
- }
- />
- </div>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.clipboard")}
- icon={<Copy className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.normalizeLineEndings")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={
- form.guacamoleConfig["normalize-clipboard"] ?? "auto"
- }
- onChange={(e) =>
- setGuacField("normalize-clipboard", e.target.value)
- }
- >
- <option value="auto">Auto</option>
- <option value="preserve">Preserve</option>
- <option value="unix">Unix (LF)</option>
- <option value="windows">Windows (CRLF)</option>
- </select>
- </div>
- <SettingRow
- label={t("hosts.guac.disableCopy")}
- description={t("hosts.guac.disableCopyDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["disable-copy"]}
- onChange={(v) => setGuacField("disable-copy", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.disablePaste")}
- description={t("hosts.guac.disablePasteDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["disable-paste"]}
- onChange={(v) => setGuacField("disable-paste", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.sessionRecording")}
- icon={<Activity className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.recordingPath")}
- </label>
- <Input
- placeholder="/var/lib/termix/recordings"
- value={form.guacamoleConfig["recording-path"] ?? ""}
- onChange={(e) =>
- setGuacField("recording-path", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.recordingName")}
- </label>
- <Input
- placeholder="${GUAC_USERNAME}-${GUAC_DATE}-${GUAC_TIME}"
- value={form.guacamoleConfig["recording-name"] ?? ""}
- onChange={(e) =>
- setGuacField("recording-name", e.target.value)
- }
- />
- </div>
- <SettingRow
- label={t("hosts.guac.createPathIfMissing")}
- description={t("hosts.guac.createPathIfMissingDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["create-recording-path"]}
- onChange={(v) => setGuacField("create-recording-path", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.excludeOutput")}
- description={t("hosts.guac.excludeOutputDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["recording-exclude-output"]}
- onChange={(v) =>
- setGuacField("recording-exclude-output", v)
- }
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.excludeMouse")}
- description={t("hosts.guac.excludeMouseDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["recording-exclude-mouse"]}
- onChange={(v) => setGuacField("recording-exclude-mouse", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.includeKeystrokes")}
- description={t("hosts.guac.includeKeystrokesDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["recording-include-keys"]}
- onChange={(v) => setGuacField("recording-include-keys", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.wakeOnLan")}
- icon={<Zap className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <SettingRow
- label={t("hosts.guac.sendWolPacket")}
- description={t("hosts.guac.sendWolPacketDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["wol-send-packet"]}
- onChange={(v) => setGuacField("wol-send-packet", v)}
- />
- </SettingRow>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.macAddress")}
- </label>
- <Input
- placeholder="AA:BB:CC:DD:EE:FF"
- value={
- form.guacamoleConfig["wol-mac-addr"] ??
- host?.macAddress ??
- ""
- }
- onChange={(e) =>
- setGuacField("wol-mac-addr", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.broadcastAddress")}
- </label>
- <Input
- placeholder="255.255.255.255"
- value={form.guacamoleConfig["wol-broadcast-addr"] ?? ""}
- onChange={(e) =>
- setGuacField("wol-broadcast-addr", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.udpPort")}
- </label>
- <Input
- type="number"
- placeholder="9"
- value={form.guacamoleConfig["wol-udp-port"] ?? ""}
- onChange={(e) =>
- setGuacField("wol-udp-port", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.waitTimeS")}
- </label>
- <Input
- type="number"
- placeholder="0"
- value={form.guacamoleConfig["wol-wait-time"] ?? ""}
- onChange={(e) =>
- setGuacField("wol-wait-time", e.target.value)
- }
- />
- </div>
- </div>
- </div>
- </SectionCard>
- </>
- )}
-
- {activeTab === "vnc" && (
- <>
- <SectionCard
- title={t("hosts.guac.connection")}
- icon={<Globe className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.vncPort")}
- </label>
- <Input
- type="number"
- placeholder="5900"
- value={form.vncPort}
- onChange={(e) =>
- setField("vncPort", Number(e.target.value) as any)
- }
- className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
- </div>
- </SectionCard>
- <SectionCard
- title={t("hosts.guac.authentication")}
- icon={<Shield className="size-3.5" />}
- >
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.vncPassword")}
- </label>
- <PasswordInput
- className="h-8 text-xs pr-8"
- placeholder="••••••••"
- value={form.vncPassword}
- onChange={(e) => setField("vncPassword", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.vncUsernameOptional")}
- </label>
- <Input
- placeholder={t("hosts.guac.vncLeaveBlank")}
- value={form.vncUser}
- onChange={(e) => setField("vncUser", e.target.value)}
- />
- </div>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.displaySettings")}
- icon={<Monitor className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.colorDepth")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={form.guacamoleConfig["color-depth"] ?? "auto"}
- onChange={(e) =>
- setGuacField("color-depth", e.target.value)
- }
- >
- <option value="auto">Auto</option>
- <option value="8">8-bit</option>
- <option value="16">16-bit</option>
- <option value="24">24-bit</option>
- <option value="32">32-bit</option>
- </select>
- </div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.width")}
- </label>
- <Input
- type="number"
- placeholder="Auto"
- value={form.guacamoleConfig["width"] ?? ""}
- onChange={(e) => setGuacField("width", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.height")}
- </label>
- <Input
- type="number"
- placeholder="Auto"
- value={form.guacamoleConfig["height"] ?? ""}
- onChange={(e) => setGuacField("height", e.target.value)}
- />
- </div>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.resizeMethod")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={form.guacamoleConfig["resize-method"] ?? "auto"}
- onChange={(e) =>
- setGuacField("resize-method", e.target.value)
- }
- >
- <option value="auto">Auto</option>
- <option value="display-update">Display Update</option>
- <option value="reconnect">Reconnect</option>
- </select>
- </div>
- <SettingRow
- label={t("hosts.guac.forceLossless")}
- description={t("hosts.guac.forceLosslessDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["force-lossless"]}
- onChange={(v) => setGuacField("force-lossless", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.audioSettings")}
- icon={<Activity className="size-3.5" />}
- >
- <div className="flex flex-col gap-0 py-1">
- <SettingRow
- label={t("hosts.guac.disableAudio")}
- description={t("hosts.guac.disableAudioDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["disable-audio"]}
- onChange={(v) => setGuacField("disable-audio", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.vncSettings")}
- icon={<Settings className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.cursorMode")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={form.guacamoleConfig["cursor"] ?? "auto"}
- onChange={(e) => setGuacField("cursor", e.target.value)}
- >
- <option value="auto">Auto</option>
- <option value="local">Local</option>
- <option value="remote">Remote</option>
- </select>
- </div>
- <SettingRow
- label={t("hosts.guac.swapRedBlue")}
- description={t("hosts.guac.swapRedBlueDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["swap-red-blue"]}
- onChange={(v) => setGuacField("swap-red-blue", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.readOnly")}
- description={t("hosts.guac.readOnlyDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["read-only"]}
- onChange={(v) => setGuacField("read-only", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.clipboard")}
- icon={<Copy className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.normalizeLineEndings")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={
- form.guacamoleConfig["normalize-clipboard"] ?? "auto"
- }
- onChange={(e) =>
- setGuacField("normalize-clipboard", e.target.value)
- }
- >
- <option value="auto">Auto</option>
- <option value="preserve">Preserve</option>
- <option value="unix">Unix (LF)</option>
- <option value="windows">Windows (CRLF)</option>
- </select>
- </div>
- <SettingRow
- label={t("hosts.guac.disableCopy")}
- description={t("hosts.guac.disableCopyDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["disable-copy"]}
- onChange={(v) => setGuacField("disable-copy", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.disablePaste")}
- description={t("hosts.guac.disablePasteDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["disable-paste"]}
- onChange={(v) => setGuacField("disable-paste", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.sessionRecording")}
- icon={<Activity className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.recordingPath")}
- </label>
- <Input
- placeholder="/var/lib/termix/recordings"
- value={form.guacamoleConfig["recording-path"] ?? ""}
- onChange={(e) =>
- setGuacField("recording-path", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.recordingName")}
- </label>
- <Input
- placeholder="${GUAC_USERNAME}-${GUAC_DATE}-${GUAC_TIME}"
- value={form.guacamoleConfig["recording-name"] ?? ""}
- onChange={(e) =>
- setGuacField("recording-name", e.target.value)
- }
- />
- </div>
- <SettingRow
- label={t("hosts.guac.createPathIfMissing")}
- description={t("hosts.guac.createPathIfMissingDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["create-recording-path"]}
- onChange={(v) => setGuacField("create-recording-path", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.excludeOutput")}
- description={t("hosts.guac.excludeOutputDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["recording-exclude-output"]}
- onChange={(v) =>
- setGuacField("recording-exclude-output", v)
- }
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.excludeMouse")}
- description={t("hosts.guac.excludeMouseDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["recording-exclude-mouse"]}
- onChange={(v) => setGuacField("recording-exclude-mouse", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.includeKeystrokes")}
- description={t("hosts.guac.includeKeystrokesDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["recording-include-keys"]}
- onChange={(v) => setGuacField("recording-include-keys", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.wakeOnLan")}
- icon={<Zap className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <SettingRow
- label={t("hosts.guac.sendWolPacket")}
- description={t("hosts.guac.sendWolPacketDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["wol-send-packet"]}
- onChange={(v) => setGuacField("wol-send-packet", v)}
- />
- </SettingRow>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.macAddress")}
- </label>
- <Input
- placeholder="AA:BB:CC:DD:EE:FF"
- value={
- form.guacamoleConfig["wol-mac-addr"] ??
- host?.macAddress ??
- ""
- }
- onChange={(e) =>
- setGuacField("wol-mac-addr", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.broadcastAddress")}
- </label>
- <Input
- placeholder="255.255.255.255"
- value={form.guacamoleConfig["wol-broadcast-addr"] ?? ""}
- onChange={(e) =>
- setGuacField("wol-broadcast-addr", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.udpPort")}
- </label>
- <Input
- type="number"
- placeholder="9"
- value={form.guacamoleConfig["wol-udp-port"] ?? ""}
- onChange={(e) =>
- setGuacField("wol-udp-port", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.waitTimeS")}
- </label>
- <Input
- type="number"
- placeholder="0"
- value={form.guacamoleConfig["wol-wait-time"] ?? ""}
- onChange={(e) =>
- setGuacField("wol-wait-time", e.target.value)
- }
- />
- </div>
- </div>
- </div>
- </SectionCard>
- </>
- )}
-
- {activeTab === "telnet" && (
- <>
- <SectionCard
- title={t("hosts.guac.connection")}
- icon={<Globe className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.telnetPort")}
- </label>
- <Input
- type="number"
- placeholder="23"
- value={form.telnetPort}
- onChange={(e) =>
- setField("telnetPort", Number(e.target.value) as any)
- }
- className="[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
- />
- </div>
- </div>
- </SectionCard>
- <SectionCard
- title={t("hosts.guac.authentication")}
- icon={<Shield className="size-3.5" />}
- >
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.username")}
- </label>
- <Input
- placeholder="admin"
- value={form.telnetUser}
- onChange={(e) => setField("telnetUser", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.password")}
- </label>
- <PasswordInput
- className="h-8 text-xs pr-8"
- placeholder="••••••••"
- value={form.telnetPassword}
- onChange={(e) => setField("telnetPassword", e.target.value)}
- />
- </div>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.displaySettings")}
- icon={<Monitor className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.width")}
- </label>
- <Input
- type="number"
- placeholder="Auto"
- value={form.guacamoleConfig["width"] ?? ""}
- onChange={(e) => setGuacField("width", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.height")}
- </label>
- <Input
- type="number"
- placeholder="Auto"
- value={form.guacamoleConfig["height"] ?? ""}
- onChange={(e) => setGuacField("height", e.target.value)}
- />
- </div>
- </div>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.terminalSettings")}
- icon={<Terminal className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.terminalType")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={form.guacamoleConfig["terminal-type"] ?? "auto"}
- onChange={(e) =>
- setGuacField("terminal-type", e.target.value)
- }
- >
- <option value="auto">Auto</option>
- <option value="xterm">xterm</option>
- <option value="xterm-256color">xterm-256color</option>
- <option value="vt100">VT100</option>
- <option value="vt220">VT220</option>
- </select>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.fontName")}
- </label>
- <Input
- placeholder="monospace"
- value={form.guacamoleConfig["font-name"] ?? ""}
- onChange={(e) => setGuacField("font-name", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.fontSize")}
- </label>
- <Input
- type="number"
- value={form.guacamoleConfig["font-size"] ?? 12}
- onChange={(e) =>
- setGuacField("font-size", Number(e.target.value))
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.colorScheme")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={form.guacamoleConfig["color-scheme"] ?? "auto"}
- onChange={(e) =>
- setGuacField("color-scheme", e.target.value)
- }
- >
- <option value="auto">Auto</option>
- <option value="black-white">Black on White</option>
- <option value="white-black">White on Black</option>
- <option value="gray-black">Gray on Black</option>
- <option value="green-black">Green on Black</option>
- </select>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.backspaceKey")}
- </label>
- <select
- className="flex h-9 w-full border border-border bg-background px-3 py-1 text-xs outline-none focus:ring-1 focus:ring-ring"
- value={form.guacamoleConfig["backspace"] ?? "auto"}
- onChange={(e) => setGuacField("backspace", e.target.value)}
- >
- <option value="auto">Auto</option>
- <option value="127">DEL (127)</option>
- <option value="8">BS (8)</option>
- </select>
- </div>
- </div>
- </SectionCard>
-
- <SectionCard
- title={t("hosts.guac.sessionRecording")}
- icon={<Activity className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.recordingPath")}
- </label>
- <Input
- placeholder="/var/lib/termix/recordings"
- value={form.guacamoleConfig["recording-path"] ?? ""}
- onChange={(e) =>
- setGuacField("recording-path", e.target.value)
- }
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.guac.recordingName")}
- </label>
- <Input
- placeholder="${GUAC_USERNAME}-${GUAC_DATE}-${GUAC_TIME}"
- value={form.guacamoleConfig["recording-name"] ?? ""}
- onChange={(e) =>
- setGuacField("recording-name", e.target.value)
- }
- />
- </div>
- <SettingRow
- label={t("hosts.guac.createPathIfMissing")}
- description={t("hosts.guac.createPathIfMissingDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["create-recording-path"]}
- onChange={(v) => setGuacField("create-recording-path", v)}
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.excludeOutput")}
- description={t("hosts.guac.excludeOutputDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["recording-exclude-output"]}
- onChange={(v) =>
- setGuacField("recording-exclude-output", v)
- }
- />
- </SettingRow>
- <SettingRow
- label={t("hosts.guac.includeKeystrokes")}
- description={t("hosts.guac.includeKeystrokesDesc")}
- >
- <FakeSwitch
- checked={!!form.guacamoleConfig["recording-include-keys"]}
- onChange={(v) => setGuacField("recording-include-keys", v)}
- />
- </SettingRow>
- </div>
- </SectionCard>
- </>
- )}
- </div>
-
- <div className="flex justify-end gap-3 mt-3 mb-6">
- <Button
- variant="ghost"
- onClick={() => {
- setPreviewTerminalTheme(null);
- onBack();
- }}
- disabled={saving}
- >
- {t("hosts.guac.cancelBtn")}
- </Button>
- <Button
- variant="outline"
- className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand px-8"
- onClick={handleSave}
- disabled={saving}
- >
- {saving
- ? t("hosts.guac.savingBtn")
- : host
- ? t("hosts.guac.updateHostBtn")
- : t("hosts.guac.addHostBtn")}
- </Button>
- </div>
- </div>
- );
-}
-
-function CredentialEditorView({
- credential,
- activeTab,
- onBack,
- onSave,
-}: {
- credential: Credential | null;
- activeTab: string;
- onBack: () => void;
- onSave: (saved: any) => void;
-}) {
- const [credForm, setCredForm] = useState(() => ({
- name: credential?.name ?? "",
- username: credential?.username ?? "",
- folder: credential?.folder ?? "",
- description: credential?.description ?? "",
- tags: credential?.tags ?? ([] as string[]),
- tagInput: "",
- type: credential?.type ?? "password",
- value: credential?.value ?? "",
- publicKey: credential?.publicKey ?? "",
- passphrase: credential?.passphrase ?? "",
- certPublicKey: (credential as any)?.certPublicKey ?? "",
- }));
- const { t } = useTranslation();
- const [generatingKey, setGeneratingKey] = useState(false);
- const [generatingPublicKey, setGeneratingPublicKey] = useState(false);
- const credFileInputRef = useRef<HTMLInputElement>(null);
- const certFileInputRef = useRef<HTMLInputElement>(null);
- const setCredField = <K extends keyof typeof credForm>(
- k: K,
- v: (typeof credForm)[K],
- ) => setCredForm((p) => ({ ...p, [k]: v }));
- const [saving, setSaving] = useState(false);
-
- const handleSave = async () => {
- setSaving(true);
- try {
- const data = {
- name: credForm.name,
- username: credForm.username,
- folder: credForm.folder || null,
- description: credForm.description || null,
- tags: credForm.tags,
- authType: credForm.type,
- password: credForm.type === "password" ? credForm.value : null,
- key:
- credForm.type === "key"
- ? credForm.value === "existing_key"
- ? undefined
- : credForm.value || null
- : null,
- publicKey: credForm.type === "key" ? credForm.publicKey : null,
- certPublicKey:
- credForm.type === "key" ? credForm.certPublicKey || null : null,
- keyPassword:
- credForm.type === "key"
- ? credForm.passphrase === "existing_key_password"
- ? undefined
- : credForm.passphrase || null
- : null,
- };
- const saved = credential
- ? await updateCredential(Number(credential.id), data)
- : await createCredential(data);
- toast.success(
- credential
- ? t("hosts.credentialUpdated")
- : t("hosts.credentialCreated"),
- );
- onSave(saved);
- } catch {
- toast.error(t("hosts.failedToSaveCredential"));
- } finally {
- setSaving(false);
- }
- };
-
- const type = credForm.type;
-
- return (
- <div className="flex flex-col gap-3">
- {activeTab === "general" && (
- <SectionCard
- title={t("hosts.basicInformation")}
- icon={<Info className="size-3.5" />}
- >
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.friendlyNameLabel")}
- </label>
- <Input
- placeholder="e.g. Production SSH Key"
- value={credForm.name}
- onChange={(e) => setCredField("name", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.folder")}
- </label>
- <Input
- placeholder="e.g. Server Keys"
- value={credForm.folder}
- onChange={(e) => setCredField("folder", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5 col-span-2">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.descriptionLabel")}
- </label>
- <Input
- placeholder="Optional details..."
- value={credForm.description}
- onChange={(e) => setCredField("description", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5 col-span-2">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.tags")}
- </label>
- <div className="flex flex-wrap items-center gap-1 min-h-9 px-2 py-1 border border-border bg-background focus-within:ring-1 focus-within:ring-ring">
- {credForm.tags.map((tag) => (
- <span
- key={tag}
- className="flex items-center gap-0.5 px-1.5 py-0.5 text-[10px] bg-muted border border-border/60 text-foreground"
- >
- {tag}
- <button
- type="button"
- onClick={() =>
- setCredField(
- "tags",
- credForm.tags.filter((tg) => tg !== tag),
- )
- }
- className="text-muted-foreground hover:text-destructive ml-0.5"
- >
- <X className="size-2.5" />
- </button>
- </span>
- ))}
- <input
- className="flex-1 min-w-16 text-xs bg-transparent outline-none placeholder:text-muted-foreground/50"
- placeholder={
- credForm.tags.length === 0
- ? t("hosts.addTagsPlaceholder")
- : ""
- }
- value={credForm.tagInput}
- onChange={(e) => setCredField("tagInput", e.target.value)}
- onKeyDown={(e) => {
- if (
- (e.key === " " || e.key === "Enter") &&
- credForm.tagInput.trim()
- ) {
- e.preventDefault();
- const tag = credForm.tagInput.trim();
- if (!credForm.tags.includes(tag))
- setCredField("tags", [...credForm.tags, tag]);
- setCredField("tagInput", "");
- } else if (
- e.key === "Backspace" &&
- !credForm.tagInput &&
- credForm.tags.length > 0
- ) {
- setCredField("tags", credForm.tags.slice(0, -1));
- }
- }}
- />
- </div>
- </div>
- </div>
- </SectionCard>
- )}
-
- {activeTab === "auth" && (
- <SectionCard
- title={t("hosts.authDetailsSection")}
- icon={<Lock className="size-3.5" />}
- >
- <div className="flex flex-col gap-4 py-3">
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.credTypeLabel")}
- </label>
- <div className="flex gap-2">
- {["password", "key"].map((m) => (
- <button
- key={m}
- onClick={() => setCredField("type", m as any)}
- className={`px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest border transition-colors ${type === m ? "border-accent-brand/40 bg-accent-brand/10 text-accent-brand" : "border-border text-muted-foreground hover:text-foreground"}`}
- >
- {m === "key"
- ? t("hosts.sshPrivateKey")
- : t("hosts.password")}
- </button>
- ))}
- </div>
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.username")}
- </label>
- <Input
- placeholder="e.g. root or deploy"
- value={credForm.username}
- onChange={(e) => setCredField("username", e.target.value)}
- />
- </div>
- {type === "password" && (
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.password")}
- </label>
- <PasswordInput
- className="h-8 text-xs pr-8"
- placeholder="••••••••"
- value={credForm.value}
- onChange={(e) => setCredField("value", e.target.value)}
- />
- </div>
- )}
- {type === "key" && (
- <div className="flex flex-col gap-4">
- <div className="p-3 border border-border bg-muted/20">
- <p className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-2">
- {t("hosts.generateKeyPairTitle")}
- </p>
- <p className="text-[10px] text-muted-foreground mb-2">
- {t("hosts.generateKeyPairDescription")}
- </p>
- <div className="flex flex-wrap gap-2">
- {[
- { label: "Ed25519", type: "ssh-ed25519" },
- {
- label: "ECDSA (nistp256)",
- type: "ecdsa-sha2-nistp256",
- },
- { label: "RSA (2048)", type: "ssh-rsa", bits: 2048 },
- ].map(({ label, type: keyType, bits }) => (
- <Button
- key={label}
- type="button"
- variant="outline"
- size="sm"
- className="h-7 text-[10px] px-2"
- disabled={generatingKey}
- onClick={async () => {
- setGeneratingKey(true);
- try {
- const result = await generateKeyPair(
- keyType as
- | "ssh-ed25519"
- | "ssh-rsa"
- | "ecdsa-sha2-nistp256",
- bits,
- credForm.passphrase === "existing_key_password"
- ? undefined
- : credForm.passphrase || undefined,
- );
- if (result.success) {
- setCredField("value", result.privateKey);
- setCredField("publicKey", result.publicKey);
- toast.success(
- t("hosts.keyPairGenerated", { label }),
- );
- } else {
- toast.error(
- result.error ??
- t("hosts.failedToGenerateKeyPair"),
- );
- }
- } catch {
- toast.error(t("hosts.failedToGenerateKeyPair"));
- } finally {
- setGeneratingKey(false);
- }
- }}
- >
- {generatingKey
- ? t("hosts.generatingKey")
- : t("hosts.generateLabel", { label })}
- </Button>
- ))}
- </div>
- </div>
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.sshPrivateKey")}
- </label>
- <button
- type="button"
- className="text-[10px] text-accent-brand hover:text-accent-brand/80 flex items-center gap-1"
- onClick={() => credFileInputRef.current?.click()}
- >
- <Upload className="size-3" /> {t("hosts.uploadFileBtn")}
- </button>
- </div>
- <input
- ref={credFileInputRef}
- type="file"
- accept=".pem,.key,.txt,.ppk"
- className="hidden"
- onChange={async (e) => {
- const file = e.target.files?.[0];
- if (!file) return;
- const text = await file.text();
- setCredField("value", text.trim());
- e.target.value = "";
- }}
- />
- {credForm.value === "existing_key" && (
- <div className="px-3 py-2 text-[10px] border border-accent-brand/30 bg-accent-brand/5 text-accent-brand">
- {t("hosts.keySaved")} — {t("hosts.keyReplaceNotice")}
- </div>
- )}
- <textarea
- placeholder="-----BEGIN OPENSSH PRIVATE KEY-----"
- rows={8}
- value={
- credForm.value === "existing_key" ? "" : credForm.value
- }
- onChange={(e) => setCredField("value", e.target.value)}
- className="w-full px-3 py-2 text-[10px] bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.keyPassphraseOptional")}
- </label>
- <PasswordInput
- className="h-8 text-xs pr-8"
- placeholder={
- credForm.passphrase === "existing_key_password"
- ? t("hosts.keyPassphraseSaved")
- : "••••••••"
- }
- value={
- credForm.passphrase === "existing_key_password"
- ? ""
- : credForm.passphrase
- }
- onFocus={() => {
- if (credForm.passphrase === "existing_key_password")
- setCredField("passphrase", "");
- }}
- onChange={(e) => setCredField("passphrase", e.target.value)}
- />
- </div>
- <div className="flex flex-col gap-1.5">
- <div className="flex items-center justify-between">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("hosts.sshPublicKeyOptional")}
- </label>
- <Button
- type="button"
- variant="outline"
- size="sm"
- className="h-6 text-[10px] px-2 border-accent-brand/40 text-accent-brand"
- disabled={
- !credForm.value ||
- credForm.value === "existing_key" ||
- generatingPublicKey
- }
- onClick={async () => {
- setGeneratingPublicKey(true);
- try {
- const result = await generatePublicKeyFromPrivate(
- credForm.value,
- credForm.passphrase === "existing_key_password"
- ? undefined
- : credForm.passphrase || undefined,
- );
- if (result?.publicKey) {
- setCredField("publicKey", result.publicKey);
- toast.success(t("hosts.publicKeyGenerated"));
- } else {
- toast.error(t("hosts.failedToGeneratePublicKey"));
- }
- } catch {
- toast.error(t("hosts.failedToGeneratePublicKey"));
- } finally {
- setGeneratingPublicKey(false);
- }
- }}
- >
- {generatingPublicKey
- ? t("hosts.generatingKey")
- : t("hosts.generateFromPrivateKey")}
- </Button>
- <Button
- type="button"
- variant="outline"
- size="sm"
- className="h-6 text-[10px] px-2"
- disabled={!credForm.publicKey}
- onClick={() => {
- navigator.clipboard.writeText(credForm.publicKey ?? "");
- toast.success(t("hosts.publicKeyCopied"));
- }}
- >
- <Copy className="size-3 mr-1" /> {t("common.copy")}
- </Button>
- </div>
- <textarea
- placeholder="ssh-rsa AAAAB3Nza..."
- rows={3}
- value={credForm.publicKey}
- onChange={(e) => setCredField("publicKey", e.target.value)}
- className="w-full px-3 py-2 text-[10px] bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
- />
- </div>
- <div className="flex flex-col gap-1.5 p-3 border border-border bg-muted/20">
- <div className="flex items-center justify-between">
- <label className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
- {t("credentials.caCertificate")}
- </label>
- {credForm.certPublicKey && (
- <button
- type="button"
- className="text-[10px] text-destructive hover:text-destructive/80"
- onClick={() => setCredField("certPublicKey", "")}
- >
- {t("credentials.clearCert")}
- </button>
- )}
- </div>
- <p className="text-[10px] text-muted-foreground">
- {t("credentials.caCertificateDescription")}
- </p>
- <button
- type="button"
- className="text-[10px] text-accent-brand hover:text-accent-brand/80 flex items-center gap-1 self-start"
- onClick={() => certFileInputRef.current?.click()}
- >
- <Upload className="size-3" />{" "}
- {t("credentials.uploadCertFile")}
- </button>
- <input
- ref={certFileInputRef}
- type="file"
- accept=".pub,.txt"
- className="hidden"
- onChange={async (e) => {
- const file = e.target.files?.[0];
- if (!file) return;
- const text = await file.text();
- setCredField("certPublicKey", text.trim());
- e.target.value = "";
- }}
- />
- <textarea
- placeholder={t("credentials.pasteOrUploadCert")}
- rows={2}
- value={credForm.certPublicKey}
- onChange={(e) =>
- setCredField("certPublicKey", e.target.value)
- }
- className="w-full px-3 py-2 text-[10px] bg-background border border-border text-foreground placeholder:text-muted-foreground resize-none outline-none focus:ring-1 focus:ring-ring font-mono"
- />
- </div>
- </div>
- )}
- </div>
- </SectionCard>
- )}
-
- <div className="flex justify-end gap-3 mt-3">
- <Button variant="ghost" onClick={onBack} disabled={saving}>
- {t("hosts.cancelBtn")}
- </Button>
- <Button
- variant="outline"
- className="border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10 hover:text-accent-brand px-8"
- onClick={handleSave}
- disabled={saving}
- >
- {saving
- ? t("hosts.savingBtn")
- : credential
- ? t("hosts.updateCredentialBtn")
- : t("hosts.addCredentialBtn")}
- </Button>
- </div>
- </div>
- );
-}
+import { CredentialEditorView } from "./CredentialEditorView";
+import { HostEditor } from "./HostEditor";
+import { mapCredentials, sshHostToHost } from "./HostManagerData";
+import { HostCredentialList } from "./HostCredentialList";
+import { makeCredentialTabs, makeHostTabs, TabStrip } from "./HostManagerTabs";
export function HostManager({
pendingEditId,
@@ -4671,7 +67,6 @@ export function HostManager({
enableVnc: false,
enableTelnet: false,
});
- const [editingHostCredentialId, setEditingHostCredentialId] = useState("");
const hostsRef = useRef<Host[]>([]);
useEffect(() => {
hostsRef.current = hosts;
@@ -4696,7 +91,6 @@ export function HostManager({
enableVnc: host.enableVnc,
enableTelnet: host.enableTelnet,
});
- setEditingHostCredentialId(host.credentialId ?? "");
return true;
}
}
@@ -4713,30 +107,26 @@ export function HostManager({
.catch(() => {});
};
- useEffect(() => {
- reloadHosts();
+ const reloadCredentials = () => {
getCredentials()
- .then((res: any) => {
- const arr = Array.isArray(res) ? res : [];
- setCredentials(
- arr.map((c: any) => ({
- id: String(c.id),
- name: c.name,
- username: c.username,
- type: c.authType === "key" ? "key" : "password",
- description: c.description ?? "",
- folder: c.folder ?? "",
- tags: c.tags ?? [],
- publicKey: c.publicKey ?? undefined,
- })),
- );
- })
+ .then((res) => setCredentials(mapCredentials(res)))
.catch(() => {})
.finally(() => setCredentialsLoading(false));
+ };
+
+ useEffect(() => {
+ reloadHosts();
+ reloadCredentials();
window.addEventListener("termix:hosts-changed", reloadHosts);
- return () =>
+ window.addEventListener("termix:credentials-changed", reloadCredentials);
+ return () => {
window.removeEventListener("termix:hosts-changed", reloadHosts);
+ window.removeEventListener(
+ "termix:credentials-changed",
+ reloadCredentials,
+ );
+ };
}, []);
useEffect(() => {
@@ -4752,7 +142,6 @@ export function HostManager({
enableVnc: false,
enableTelnet: false,
});
- setEditingHostCredentialId("");
setActiveHostTab("general");
} else if (action === "add-credential") {
setEditingCredential("new");
@@ -4773,7 +162,6 @@ export function HostManager({
enableVnc: false,
enableTelnet: false,
});
- setEditingHostCredentialId("");
setActiveHostTab("general");
};
const handleAddCredential = () => {
@@ -4794,7 +182,6 @@ export function HostManager({
enableVnc: host.enableVnc,
enableTelnet: host.enableTelnet,
});
- setEditingHostCredentialId(host.credentialId ?? "");
}
};
window.addEventListener("host-manager:add-host", handleAddHost);
@@ -4821,6 +208,25 @@ export function HostManager({
new Set(credentials.map((c) => c.folder || "Uncategorized")),
).sort();
+ const handleRenameCredentialFolder = async (
+ folder: string,
+ newName: string,
+ ) => {
+ try {
+ await renameCredentialFolder(folder, newName);
+ const res = await getCredentials();
+ setCredentials(mapCredentials(res));
+ toast.success(t("hosts.folderRenamedTo", { name: newName }));
+ } catch {
+ toast.error(t("hosts.failedToRenameFolder"));
+ }
+ };
+
+ const handleDeleteCredential = async (cred: Credential) => {
+ await deleteCredential(Number(cred.id));
+ setCredentials((prev) => prev.filter((c) => c.id !== cred.id));
+ };
+
// Editor view: full-width with top tab bar instead of side nav
const renderEditorView = () => {
const isHost = !!editingHost;
@@ -4905,9 +311,6 @@ export function HostManager({
setEditingProtocols((prev) => ({ ...prev, ...p }))
}
onTabChange={setActiveHostTab}
- onCredentialChange={(id) => {
- setEditingHostCredentialId(id);
- }}
hosts={hosts}
credentials={credentials}
/>
@@ -4995,288 +398,28 @@ export function HostManager({
</div>
)}
- <div className="flex-1 min-h-0 overflow-y-auto">
- <div className="flex flex-col">
- {credentialFolders.map((folder) => {
- const creds = filteredCredentials.filter(
- (c) => (c.folder || "Uncategorized") === folder,
- );
- if (creds.length === 0) return null;
- return (
- <div key={folder} className="group/folder">
- <div className="flex items-center gap-1.5 px-3 py-1.5 border-b border-border/40 bg-muted/20">
- <Folder className="size-3 text-muted-foreground/50 shrink-0" />
- {editingCredFolderName === folder ? (
- <>
- <input
- autoFocus
- value={editingCredFolderValue}
- onChange={(e) =>
- setEditingCredFolderValue(e.target.value)
- }
- onBlur={async () => {
- const newName = editingCredFolderValue.trim();
- setEditingCredFolderName(null);
- if (newName && newName !== folder) {
- try {
- await renameCredentialFolder(folder, newName);
- const res = (await getCredentials()) as any;
- const arr = Array.isArray(res) ? res : [];
- setCredentials(
- arr.map((c: any) => ({
- id: String(c.id),
- name: c.name,
- username: c.username,
- type:
- c.authType === "key"
- ? "key"
- : "password",
- description: c.description ?? "",
- folder: c.folder ?? "",
- tags: c.tags ?? [],
- publicKey: c.publicKey ?? undefined,
- })),
- );
- toast.success(
- t("hosts.folderRenamedTo", {
- name: newName,
- }),
- );
- } catch {
- toast.error(t("hosts.failedToRenameFolder"));
- }
- }
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter") e.currentTarget.blur();
- if (e.key === "Escape")
- setEditingCredFolderName(null);
- }}
- onClick={(e) => e.stopPropagation()}
- className="text-[10px] font-semibold bg-background border border-accent-brand/60 px-1 outline-none text-foreground min-w-0 flex-1"
- />
- <button
- onClick={() => setEditingCredFolderName(null)}
- className="text-muted-foreground hover:text-foreground shrink-0"
- >
- <X className="size-3" />
- </button>
- </>
- ) : (
- <>
- <span className="text-[10px] font-semibold text-muted-foreground/70 flex-1">
- {folder}
- </span>
- <span className="text-[10px] text-muted-foreground/40">
- {creds.length}
- </span>
- {folder !== "Uncategorized" && (
- <button
- className="opacity-0 group-hover/folder:opacity-100 transition-opacity ml-1 text-muted-foreground/50 hover:text-foreground"
- onClick={() => {
- setEditingCredFolderName(folder);
- setEditingCredFolderValue(folder);
- }}
- >
- <Pencil className="size-2.5" />
- </button>
- )}
- </>
- )}
- </div>
- {creds.map((cred) => {
- const usedByHosts = allHosts.filter(
- (h) => h.credentialId === cred.id,
- );
- return (
- <div
- key={cred.id}
- className="flex items-center justify-between px-3 py-2 border-b border-border/40 last:border-0 hover:bg-muted/30 group"
- >
- <div className="flex items-center gap-2.5 min-w-0">
- <div className="size-7 border border-border/60 bg-muted/30 flex items-center justify-center shrink-0">
- {cred.type === "key" ? (
- <Shield className="size-3 text-accent-brand" />
- ) : (
- <Lock className="size-3 text-accent-brand" />
- )}
- </div>
- <div className="flex flex-col min-w-0">
- <div className="flex items-center gap-1.5">
- <span className="text-xs font-semibold truncate">
- {cred.name}
- </span>
- <span
- className={`text-[9px] px-1 py-px font-bold border leading-none shrink-0 ${cred.type === "key" ? "border-accent-brand/30 text-accent-brand" : "border-border/60 text-muted-foreground/60"}`}
- >
- {cred.type === "key" ? "KEY" : "PWD"}
- </span>
- </div>
- {(cred.username || usedByHosts.length > 0) && (
- <span className="text-[11px] text-muted-foreground/50 truncate">
- {cred.username}
- {usedByHosts.length > 0 && (
- <span className="text-muted-foreground/30">
- {cred.username ? " · " : ""}
- {usedByHosts.length}h
- </span>
- )}
- </span>
- )}
- {cred.tags && cred.tags.length > 0 && (
- <div className="flex items-center gap-0.5 mt-0.5 flex-wrap">
- {cred.tags.slice(0, 3).map((tag) => (
- <span
- key={tag}
- className="text-[9px] px-1 py-px border border-border/50 bg-muted/30 text-muted-foreground/60 lowercase leading-none"
- >
- {tag}
- </span>
- ))}
- {cred.tags.length > 3 && (
- <span className="text-[9px] text-muted-foreground/40">
- +{cred.tags.length - 3}
- </span>
- )}
- </div>
- )}
- </div>
- </div>
- <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
- {cred.type === "key" && (
- <>
- <button
- title="Deploy key to host"
- className="flex items-center gap-1 px-1.5 py-1 text-[10px] text-muted-foreground/60 hover:text-foreground hover:bg-muted rounded transition-colors"
- onClick={() =>
- setDeployDialog({ cred, hostId: "" })
- }
- >
- <Upload className="size-3" />
- </button>
- <button
- title="Copy deploy command"
- className="flex items-center gap-1 px-1.5 py-1 text-[10px] text-muted-foreground/60 hover:text-foreground hover:bg-muted rounded transition-colors"
- onClick={() => {
- const pubKey = cred.publicKey;
- if (!pubKey) {
- toast.error(
- "No public key available — open the credential editor first",
- );
- return;
- }
- const cmd = `mkdir -p ~/.ssh && chmod 700 ~/.ssh && echo "${pubKey}" >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys`;
- navigator.clipboard.writeText(cmd);
- toast.success("Deploy command copied");
- }}
- >
- <Copy className="size-3" />
- </button>
- </>
- )}
- <button
- className="size-6 flex items-center justify-center text-muted-foreground/50 hover:text-foreground hover:bg-muted rounded transition-colors"
- onClick={async () => {
- try {
- const full = await getCredentialDetails(
- Number(cred.id),
- );
- setEditingCredential({
- ...cred,
- value: (full as any).hasKey
- ? "existing_key"
- : ((full as any).password ?? ""),
- passphrase: (full as any).hasKeyPassword
- ? "existing_key_password"
- : "",
- certPublicKey:
- (full as any).certPublicKey ?? "",
- });
- } catch {
- setEditingCredential(cred);
- }
- setActiveCredentialTab("general");
- }}
- >
- <Pencil className="size-3" />
- </button>
- <button
- className="size-6 flex items-center justify-center text-muted-foreground/40 hover:text-destructive hover:bg-destructive/10 rounded transition-colors"
- onClick={() => {
- setConfirmDialog({
- message: t("hosts.deleteCredentialConfirm", {
- name: cred.name,
- }),
- onConfirm: async () => {
- try {
- await deleteCredential(Number(cred.id));
- setCredentials((prev) =>
- prev.filter((c) => c.id !== cred.id),
- );
- toast.success(
- t("hosts.deletedCredential", {
- name: cred.name,
- }),
- );
- } catch {
- toast.error(
- t("hosts.failedToDeleteCredential2"),
- );
- }
- },
- });
- }}
- >
- <Trash2 className="size-3" />
- </button>
- </div>
- </div>
- );
- })}
- </div>
- );
- })}
- {credentialsLoading && (
- <div className="flex flex-col px-2 py-2 space-y-1.5">
- {[60, 45, 55, 40].map((w, i) => (
- <div key={i} className="flex items-center gap-2 px-3 py-2">
- <div className="size-3 rounded-sm bg-muted/50 animate-pulse shrink-0" />
- <div
- className="h-3 rounded bg-muted/50 animate-pulse"
- style={{ width: `${w * 2}px` }}
- />
- </div>
- ))}
- <div className="flex items-center justify-center gap-2 pt-2 text-muted-foreground/40">
- <Loader2 className="size-3.5 animate-spin" />
- <span className="text-xs">
- {t("hosts.loadingCredentials")}
- </span>
- </div>
- </div>
- )}
- {!credentialsLoading && filteredCredentials.length === 0 && (
- <div className="flex flex-col items-center justify-center py-12 text-center px-4">
- <KeyRound className="size-8 text-muted-foreground/20 mb-2" />
- <span className="text-sm font-semibold text-muted-foreground/60">
- {t("hosts.noCredentialsFound")}
- </span>
- <Button
- variant="outline"
- size="sm"
- className="mt-3 h-7 text-xs border-accent-brand/40 text-accent-brand hover:bg-accent-brand/10"
- onClick={() => {
- setEditingCredential("new");
- setActiveCredentialTab("general");
- }}
- >
- <Plus className="size-3 mr-1" />
- {t("hosts.addCredentialBtn2")}
- </Button>
- </div>
- )}
- </div>
- </div>
+ <HostCredentialList
+ credentialFolders={credentialFolders}
+ filteredCredentials={filteredCredentials}
+ credentialsLoading={credentialsLoading}
+ allHosts={allHosts}
+ editingFolderName={editingCredFolderName}
+ editingFolderValue={editingCredFolderValue}
+ onEditingFolderNameChange={setEditingCredFolderName}
+ onEditingFolderValueChange={setEditingCredFolderValue}
+ onRenameFolder={handleRenameCredentialFolder}
+ onDeployCredential={(cred) => setDeployDialog({ cred, hostId: "" })}
+ onEditCredential={(cred) => {
+ setEditingCredential(cred);
+ setActiveCredentialTab("general");
+ }}
+ onDeleteCredential={handleDeleteCredential}
+ onAddCredential={() => {
+ setEditingCredential("new");
+ setActiveCredentialTab("general");
+ }}
+ onConfirmDialogChange={setConfirmDialog}
+ />
</div>
)}
diff --git a/src/ui/sidebar/HostManagerData.ts b/src/ui/sidebar/HostManagerData.ts
new file mode 100644
index 000000000..21c1e3650
--- /dev/null
+++ b/src/ui/sidebar/HostManagerData.ts
@@ -0,0 +1,120 @@
+import type { SSHHostWithStatus } from "@/main-axios";
+import type { Host, Credential } from "@/types/ui-types";
+
+type RawSSHHost = SSHHostWithStatus & {
+ hasKey?: boolean;
+ hasKeyPassword?: boolean;
+};
+type HostQuickAction = Host["quickActions"][number];
+type HostJumpHost = NonNullable<Host["jumpHosts"]>[number];
+type RawCredential = {
+ id: number | string;
+ name: string;
+ username: string;
+ authType?: string;
+ description?: string | null;
+ folder?: string | null;
+ tags?: string[];
+ publicKey?: string | null;
+};
+
+function parseJson<T>(v: unknown): T | undefined {
+ if (!v) return undefined;
+ if (typeof v === "string") {
+ try {
+ return JSON.parse(v) as T;
+ } catch {
+ return undefined;
+ }
+ }
+ return v as T;
+}
+
+export function sshHostToHost(h: SSHHostWithStatus): Host {
+ const host = h as RawSSHHost;
+ return {
+ id: String(h.id),
+ name: h.name,
+ username: h.username,
+ ip: h.ip,
+ port: h.port,
+ folder: h.folder ?? "",
+ online: h.status === "online",
+ cpu: null,
+ ram: null,
+ lastAccess: "",
+ tags: h.tags ?? [],
+ authType: h.authType,
+ password: h.password,
+ hasKey: !!host.hasKey || !!(typeof h.key === "string" && h.key),
+ hasKeyPassword: !!host.hasKeyPassword || !!h.keyPassword,
+ key: typeof h.key === "string" ? h.key : undefined,
+ keyPassword: h.keyPassword,
+ keyType: h.keyType,
+ credentialId: h.credentialId != null ? String(h.credentialId) : undefined,
+ notes: h.notes,
+ pin: h.pin ?? false,
+ macAddress: h.macAddress,
+ enableSsh: h.enableSsh != null ? h.enableSsh : h.connectionType === "ssh",
+ enableTerminal:
+ h.enableTerminal ??
+ (h.enableSsh != null ? h.enableSsh : h.connectionType === "ssh"),
+ enableTunnel: h.enableTunnel ?? false,
+ enableFileManager: h.enableFileManager ?? false,
+ enableDocker: h.enableDocker ?? false,
+ enableRdp: h.enableRdp != null ? h.enableRdp : h.connectionType === "rdp",
+ enableVnc: h.enableVnc != null ? h.enableVnc : h.connectionType === "vnc",
+ enableTelnet:
+ h.enableTelnet != null ? h.enableTelnet : h.connectionType === "telnet",
+ sshPort:
+ h.sshPort ??
+ (h.connectionType === "ssh" || !h.connectionType ? h.port : 22),
+ rdpPort: h.rdpPort ?? (h.connectionType === "rdp" ? h.port : 3389),
+ vncPort: h.vncPort ?? (h.connectionType === "vnc" ? h.port : 5900),
+ telnetPort: h.telnetPort ?? (h.connectionType === "telnet" ? h.port : 23),
+ rdpUser: h.rdpUser,
+ rdpPassword: h.rdpPassword ?? "",
+ domain: h.rdpDomain,
+ security: h.rdpSecurity,
+ ignoreCert: h.rdpIgnoreCert ?? false,
+ vncPassword: h.vncPassword ?? "",
+ vncUser: h.vncUser,
+ telnetUser: h.telnetUser,
+ telnetPassword: h.telnetPassword ?? "",
+ quickActions: (h.quickActions ?? []).map((a: HostQuickAction) => ({
+ name: a.name,
+ snippetId: String(a.snippetId),
+ })),
+ serverTunnels: parseJson(h.tunnelConnections) ?? [],
+ jumpHosts: (parseJson<HostJumpHost[]>(h.jumpHosts) ?? []).map((j) => ({
+ hostId: String(j.hostId ?? j.hostid ?? j),
+ })),
+ portKnockSequence: parseJson(h.portKnockSequence) ?? [],
+ defaultPath: h.defaultPath,
+ terminalConfig: parseJson(h.terminalConfig) as Host["terminalConfig"],
+ statsConfig: parseJson(h.statsConfig) as Host["statsConfig"],
+ guacamoleConfig: parseJson(h.guacamoleConfig),
+ forceKeyboardInteractive: h.forceKeyboardInteractive ?? false,
+ useSocks5: h.useSocks5,
+ socks5Host: h.socks5Host,
+ socks5Port: h.socks5Port,
+ socks5Username: h.socks5Username,
+ socks5Password: h.socks5Password,
+ socks5ProxyChain: parseJson(h.socks5ProxyChain) ?? [],
+ overrideCredentialUsername: h.overrideCredentialUsername ?? false,
+ };
+}
+
+export function mapCredentials(res: unknown): Credential[] {
+ const arr = Array.isArray(res) ? res : [];
+ return (arr as RawCredential[]).map((c) => ({
+ id: String(c.id),
+ name: c.name,
+ username: c.username,
+ type: c.authType === "key" ? "key" : "password",
+ description: c.description ?? "",
+ folder: c.folder ?? "",
+ tags: c.tags ?? [],
+ publicKey: c.publicKey ?? undefined,
+ }));
+}
diff --git a/src/ui/sidebar/HostManagerTabs.tsx b/src/ui/sidebar/HostManagerTabs.tsx
new file mode 100644
index 000000000..408687f75
--- /dev/null
+++ b/src/ui/sidebar/HostManagerTabs.tsx
@@ -0,0 +1,167 @@
+/* eslint-disable react-refresh/only-export-components */
+import { useEffect, useRef, type ReactNode } from "react";
+import {
+ Activity,
+ Box,
+ Folder,
+ KeyRound,
+ Monitor,
+ MousePointerClick,
+ Network,
+ Settings,
+ Terminal,
+} from "lucide-react";
+
+export type HostTabId =
+ | "general"
+ | "ssh"
+ | "tunnels"
+ | "docker"
+ | "files"
+ | "stats"
+ | "rdp"
+ | "vnc"
+ | "telnet";
+export type CredentialTabId = "general" | "auth";
+
+type HostTab = {
+ id: HostTabId;
+ label: string;
+ icon: ReactNode;
+};
+type CredentialTab = {
+ id: CredentialTabId;
+ label: string;
+ icon: ReactNode;
+};
+
+export function makeHostTabs(t: (key: string) => string): HostTab[] {
+ return [
+ {
+ id: "general",
+ label: t("hosts.tabGeneral"),
+ icon: <Settings className="size-3" />,
+ },
+ {
+ id: "ssh",
+ label: t("hosts.tabSsh"),
+ icon: <Terminal className="size-3" />,
+ },
+ {
+ id: "tunnels",
+ label: t("hosts.tabTunnels"),
+ icon: <Network className="size-3" />,
+ },
+ {
+ id: "docker",
+ label: t("hosts.tabDocker"),
+ icon: <Box className="size-3" />,
+ },
+ {
+ id: "files",
+ label: t("hosts.tabFiles"),
+ icon: <Folder className="size-3" />,
+ },
+ {
+ id: "stats",
+ label: t("hosts.tabStats"),
+ icon: <Activity className="size-3" />,
+ },
+ {
+ id: "rdp",
+ label: t("hosts.tabRdp"),
+ icon: <Monitor className="size-3" />,
+ },
+ {
+ id: "vnc",
+ label: t("hosts.tabVnc"),
+ icon: <MousePointerClick className="size-3" />,
+ },
+ {
+ id: "telnet",
+ label: t("hosts.tabTelnet"),
+ icon: <Terminal className="size-3" />,
+ },
+ ];
+}
+
+export function makeCredentialTabs(
+ t: (key: string) => string,
+): CredentialTab[] {
+ return [
+ {
+ id: "general",
+ label: t("hosts.tabGeneral"),
+ icon: <Settings className="size-3" />,
+ },
+ {
+ id: "auth",
+ label: t("hosts.tabAuthentication"),
+ icon: <KeyRound className="size-3" />,
+ },
+ ];
+}
+
+const SSH_DEP_TABS = new Set(["tunnels", "docker", "files", "stats"]);
+
+export function TabStrip({
+ tabs,
+ activeTab,
+ onTabChange,
+}: {
+ tabs: { id: string; label: string; icon: ReactNode }[];
+ activeTab: string;
+ onTabChange: (id: string) => void;
+}) {
+ const hasSshGroup = tabs.some((t) => SSH_DEP_TABS.has(t.id));
+
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const onWheel = (e: WheelEvent) => {
+ if (e.deltaY === 0) return;
+ e.preventDefault();
+ el.scrollLeft += e.deltaY;
+ };
+ el.addEventListener("wheel", onWheel, { passive: false });
+ return () => el.removeEventListener("wheel", onWheel);
+ }, []);
+
+ const nonSshTabs = tabs.filter((t) => !SSH_DEP_TABS.has(t.id));
+ const sshDepTabs = tabs.filter((t) => SSH_DEP_TABS.has(t.id));
+
+ const renderTab = (tab: (typeof tabs)[0]) => (
+ <button
+ key={tab.id}
+ onClick={() => onTabChange(tab.id)}
+ className={`flex items-center gap-1.5 px-3 py-2 text-xs font-medium whitespace-nowrap border-b-2 transition-colors shrink-0 ${
+ activeTab === tab.id
+ ? "border-accent-brand text-accent-brand"
+ : "border-transparent text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ {tab.icon}
+ {tab.label}
+ </button>
+ );
+
+ return (
+ <div ref={ref} className="overflow-x-auto">
+ <div className="flex min-w-max">
+ {nonSshTabs.map(renderTab)}
+ {hasSshGroup && sshDepTabs.length > 0 && (
+ <div className="flex flex-col border-l border-border/40 ml-0.5">
+ <div className="flex items-center gap-1 px-2 pt-0.5">
+ <Terminal className="size-2.5 text-muted-foreground/30" />
+ <span className="text-[9px] font-bold uppercase tracking-widest text-muted-foreground/30">
+ SSH
+ </span>
+ </div>
+ <div className="flex">{sshDepTabs.map(renderTab)}</div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/ui/sidebar/HostShareModal.tsx b/src/ui/sidebar/HostShareModal.tsx
index 627762124..7195859ff 100644
--- a/src/ui/sidebar/HostShareModal.tsx
+++ b/src/ui/sidebar/HostShareModal.tsx
@@ -19,6 +19,7 @@ import {
revokeHostAccess,
getUserList,
getRoles,
+ type AccessRecord,
} from "@/main-axios";
import type { Host } from "@/types/ui-types";
@@ -35,7 +36,7 @@ export function HostShareModal({
const [shareType, setShareType] = useState<"user" | "role">("user");
const [shareGranteeId, setShareGranteeId] = useState("");
const [shareExpiryHours, setShareExpiryHours] = useState("");
- const [accessList, setAccessList] = useState<any[]>([]);
+ const [accessList, setAccessList] = useState<AccessRecord[]>([]);
const [shareUsers, setShareUsers] = useState<
{ id: string; username: string }[]
>([]);
@@ -55,15 +56,15 @@ export function HostShareModal({
getRoles().catch(() => ({ roles: [] })),
])
.then(([accessRes, usersRes, rolesRes]) => {
- setAccessList((accessRes as any)?.accessList ?? []);
+ setAccessList(accessRes.accessList ?? []);
setShareUsers(
- ((usersRes as any)?.users ?? []).map((u: any) => ({
+ (usersRes.users ?? []).map((u) => ({
id: String(u.id ?? u.userId),
username: u.username,
})),
);
setShareRoles(
- ((rolesRes as any)?.roles ?? []).map((r: any) => ({
+ (rolesRes.roles ?? []).map((r) => ({
id: String(r.id),
name: r.name,
})),
@@ -84,7 +85,7 @@ export function HostShareModal({
async function refreshAccessList() {
if (!host) return;
const res = await getHostAccess(Number(host.id));
- setAccessList((res as any)?.accessList ?? []);
+ setAccessList(res.accessList ?? []);
}
if (!open) return null;
@@ -233,7 +234,7 @@ export function HostShareModal({
{t("hosts.guac.noAccessEntries")}
</div>
)}
- {accessList.map((r: any, i: number) => {
+ {accessList.map((r, i) => {
const expired =
r.expiresAt && new Date(r.expiresAt) < new Date();
return (
diff --git a/src/ui/sidebar/HostsPanel.tsx b/src/ui/sidebar/HostsPanel.tsx
index a1a19ac21..b3a14e39b 100644
--- a/src/ui/sidebar/HostsPanel.tsx
+++ b/src/ui/sidebar/HostsPanel.tsx
@@ -26,7 +26,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/dropdown-menu";
-import { getSSHHosts, bulkImportSSHHosts } from "@/main-axios";
+import { getSSHHosts, bulkImportSSHHosts, exportAllSSHHosts } from "@/main-axios";
import type { SSHHostWithStatus } from "@/main-axios";
import type { Host, HostFolder, TabType } from "@/types/ui-types";
@@ -102,7 +102,12 @@ function hostPassesFilters(host: Host, filters: FilterState): boolean {
if (!ok) return false;
}
if (filters.authType.length > 0) {
- if (!filters.authType.includes(host.authType as FilterState["authType"][number])) return false;
+ if (
+ !filters.authType.includes(
+ host.authType as FilterState["authType"][number],
+ )
+ )
+ return false;
}
if (filters.protocol.length > 0) {
const ok =
@@ -235,18 +240,23 @@ export function HostsPanel({
}
}
- function handleExportHosts() {
- const data = JSON.stringify({ hosts: rawHosts }, null, 2);
- const blob = new Blob([data], { type: "application/json" });
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = "termix-hosts.json";
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- toast.success(t("hosts.hostsExported"));
+ async function handleExportHosts() {
+ try {
+ const result = await exportAllSSHHosts();
+ const data = JSON.stringify(result, null, 2);
+ const blob = new Blob([data], { type: "application/json" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = "termix-hosts.json";
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+ toast.success(t("hosts.hostsExported"));
+ } catch {
+ toast.error(t("hosts.exportFailed"));
+ }
}
function handleDownloadSample() {
@@ -355,14 +365,17 @@ export function HostsPanel({
toast.error("Cannot import more than 100 hosts at once");
return;
}
- const normalized = hostsArray.map((h: any) => ({
- ...h,
- port: h.port ?? h.sshPort ?? 22,
- enableSsh: h.enableSsh ?? h.connectionType === "ssh",
- enableRdp: h.enableRdp ?? h.connectionType === "rdp",
- enableVnc: h.enableVnc ?? h.connectionType === "vnc",
- enableTelnet: h.enableTelnet ?? h.connectionType === "telnet",
- }));
+ const normalized = hostsArray.map(
+ (h: Record<string, unknown>) => ({
+ ...h,
+ port: h.port ?? h.sshPort ?? 22,
+ enableSsh: h.enableSsh ?? h.connectionType === "ssh",
+ enableRdp: h.enableRdp ?? h.connectionType === "rdp",
+ enableVnc: h.enableVnc ?? h.connectionType === "vnc",
+ enableTelnet:
+ h.enableTelnet ?? h.connectionType === "telnet",
+ }),
+ );
const result = await bulkImportSSHHosts(
normalized,
importOverwriteRef.current,
@@ -378,8 +391,10 @@ export function HostsPanel({
.filter(Boolean)
.join(", ");
toast.success(`Import complete: ${msg}`);
- } catch (err: any) {
- toast.error(err?.message ?? "Failed to import hosts");
+ } catch (err: unknown) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to import hosts",
+ );
}
}}
/>
@@ -562,7 +577,9 @@ export function HostsPanel({
<DropdownMenuSeparator />
</>
)}
- <DropdownMenuLabel>{t("hosts.filterStatusGroup")}</DropdownMenuLabel>
+ <DropdownMenuLabel>
+ {t("hosts.filterStatusGroup")}
+ </DropdownMenuLabel>
{(["online", "offline", "pinned"] as const).map((val) => (
<DropdownMenuCheckboxItem
key={val}
@@ -570,23 +587,35 @@ export function HostsPanel({
onCheckedChange={() => handleFilterToggle("status", val)}
onSelect={(e) => e.preventDefault()}
>
- {t(`hosts.filter${val.charAt(0).toUpperCase() + val.slice(1)}`)}
+ {t(
+ `hosts.filter${val.charAt(0).toUpperCase() + val.slice(1)}`,
+ )}
</DropdownMenuCheckboxItem>
))}
<DropdownMenuSeparator />
- <DropdownMenuLabel>{t("hosts.filterAuthGroup")}</DropdownMenuLabel>
- {(["password", "key", "credential", "none", "opkssh"] as const).map((val) => (
+ <DropdownMenuLabel>
+ {t("hosts.filterAuthGroup")}
+ </DropdownMenuLabel>
+ {(
+ ["password", "key", "credential", "none", "opkssh"] as const
+ ).map((val) => (
<DropdownMenuCheckboxItem
key={val}
checked={filterState.authType.includes(val)}
- onCheckedChange={() => handleFilterToggle("authType", val)}
+ onCheckedChange={() =>
+ handleFilterToggle("authType", val)
+ }
onSelect={(e) => e.preventDefault()}
>
- {t(`hosts.filterAuth${val.charAt(0).toUpperCase() + val.slice(1)}`)}
+ {t(
+ `hosts.filterAuth${val.charAt(0).toUpperCase() + val.slice(1)}`,
+ )}
</DropdownMenuCheckboxItem>
))}
<DropdownMenuSeparator />
- <DropdownMenuLabel>{t("hosts.filterProtocolGroup")}</DropdownMenuLabel>
+ <DropdownMenuLabel>
+ {t("hosts.filterProtocolGroup")}
+ </DropdownMenuLabel>
{(
[
["ssh", "Ssh"],
@@ -598,14 +627,18 @@ export function HostsPanel({
<DropdownMenuCheckboxItem
key={val}
checked={filterState.protocol.includes(val)}
- onCheckedChange={() => handleFilterToggle("protocol", val)}
+ onCheckedChange={() =>
+ handleFilterToggle("protocol", val)
+ }
onSelect={(e) => e.preventDefault()}
>
{t(`hosts.filterProtocol${key}`)}
</DropdownMenuCheckboxItem>
))}
<DropdownMenuSeparator />
- <DropdownMenuLabel>{t("hosts.filterFeaturesGroup")}</DropdownMenuLabel>
+ <DropdownMenuLabel>
+ {t("hosts.filterFeaturesGroup")}
+ </DropdownMenuLabel>
{(
[
["terminal", "Terminal"],
@@ -617,7 +650,9 @@ export function HostsPanel({
<DropdownMenuCheckboxItem
key={val}
checked={filterState.features.includes(val)}
- onCheckedChange={() => handleFilterToggle("features", val)}
+ onCheckedChange={() =>
+ handleFilterToggle("features", val)
+ }
onSelect={(e) => e.preventDefault()}
>
{t(`hosts.filterFeature${key}`)}
@@ -626,12 +661,16 @@ export function HostsPanel({
{allTags.length > 0 && (
<>
<DropdownMenuSeparator />
- <DropdownMenuLabel>{t("hosts.filterTagsGroup")}</DropdownMenuLabel>
+ <DropdownMenuLabel>
+ {t("hosts.filterTagsGroup")}
+ </DropdownMenuLabel>
{allTags.map((tag) => (
<DropdownMenuCheckboxItem
key={tag}
checked={filterState.tags.includes(tag)}
- onCheckedChange={() => handleFilterToggle("tags", tag)}
+ onCheckedChange={() =>
+ handleFilterToggle("tags", tag)
+ }
onSelect={(e) => e.preventDefault()}
>
{tag}
@@ -660,7 +699,12 @@ export function HostsPanel({
className={`flex flex-col flex-1 min-h-0 ${managerEditing ? "hidden" : ""}`}
>
<SidebarTree
- children={hostTree ? applyFilters(sortHostTree(hostTree, sortKey), filterState).children : []}
+ children={
+ hostTree
+ ? applyFilters(sortHostTree(hostTree, sortKey), filterState)
+ .children
+ : []
+ }
onOpenTab={onOpenTab}
onEditHost={onEditHost}
onShareHost={(host) => setShareModalHost(host)}
diff --git a/src/ui/sidebar/SidebarTree.tsx b/src/ui/sidebar/SidebarTree.tsx
index 67fadc160..2d588bc0c 100644
--- a/src/ui/sidebar/SidebarTree.tsx
+++ b/src/ui/sidebar/SidebarTree.tsx
@@ -1,4 +1,5 @@
-import { useState, useEffect } from "react";
+/* eslint-disable react-refresh/only-export-components */
+import { useState, useEffect, type MouseEvent } from "react";
import { useTranslation } from "react-i18next";
import {
Box,
@@ -10,6 +11,7 @@ import {
Cpu,
FolderOpen,
FolderSearch,
+ Key,
Link,
Loader2,
MemoryStick,
@@ -24,6 +26,7 @@ import {
Share2,
Terminal,
Trash2,
+ X,
Zap,
} from "lucide-react";
import {
@@ -41,9 +44,12 @@ import {
bulkUpdateSSHHosts,
createSSHHost,
deleteSSHHost,
+ getHostPassword,
+ renameFolder,
wakeOnLan,
} from "@/main-axios";
import type { Host, HostFolder, TabType } from "@/types/ui-types";
+import type { SSHHostData } from "@/types/index";
export function isFolder(item: Host | HostFolder): item is HostFolder {
return "children" in item;
@@ -159,6 +165,38 @@ function collectAllFolders(children: (Host | HostFolder)[]): string[] {
return Array.from(names).sort();
}
+async function writeClipboardText(value: string): Promise<void> {
+ try {
+ await navigator.clipboard.writeText(value);
+ } catch {
+ const textarea = document.createElement("textarea");
+ textarea.value = value;
+ textarea.style.position = "fixed";
+ textarea.style.opacity = "0";
+ document.body.appendChild(textarea);
+ textarea.select();
+ document.execCommand("copy");
+ document.body.removeChild(textarea);
+ }
+}
+
+function canCopyHostPassword(host: Host): boolean {
+ return (
+ host.authType === "password" ||
+ host.authType === "credential" ||
+ !!host.hasPassword ||
+ !!host.password
+ );
+}
+
+function canCopyHostSudoPassword(host: Host): boolean {
+ return (
+ !!host.hasSudoPassword ||
+ !!host.sudoPassword ||
+ !!host.terminalConfig?.sudoPassword
+ );
+}
+
function folderHostCount(folder: HostFolder): {
total: number;
online: number;
@@ -221,6 +259,30 @@ export function HostItem({
const v = localStorage.getItem("showHostTags");
return v !== null ? v === "true" : true;
});
+ const isTouchOnly =
+ typeof window !== "undefined" && window.matchMedia("(hover: none)").matches;
+ const shouldUseClickTray = trayOnClick || isTouchOnly;
+ const showPasswordCopy = canCopyHostPassword(host);
+ const showSudoPasswordCopy = canCopyHostSudoPassword(host);
+
+ async function handleCopyPassword(
+ e: MouseEvent,
+ field: "password" | "sudoPassword",
+ ) {
+ e.stopPropagation();
+ const password = await getHostPassword(Number(host.id), field);
+ if (!password) {
+ toast.error(t("nav.failedToCopyPassword"));
+ return;
+ }
+
+ try {
+ await writeClipboardText(password);
+ toast.success(t("nav.passwordCopied"));
+ } catch {
+ toast.error(t("nav.failedToCopyPassword"));
+ }
+ }
useEffect(() => {
const handler = () =>
@@ -262,16 +324,12 @@ export function HostItem({
onToggleSelect?.();
return;
}
- // On touch devices open the action tray instead of immediately launching a tab
- if (window.matchMedia("(hover: none)").matches) {
+ // Touch devices open the tray instead of launching
+ if (isTouchOnly) {
e.stopPropagation();
onTrayOpenChange?.(!isTrayOpen);
return;
}
- if (trayOnClick) {
- onTrayOpenChange?.(!isTrayOpen);
- return;
- }
if (host.enableSsh) onOpenTab("terminal");
else if (host.enableRdp) onOpenTab("rdp");
else if (host.enableVnc) onOpenTab("vnc");
@@ -303,12 +361,28 @@ export function HostItem({
{host.pin && (
<Pin className="size-2.5 text-accent-brand/50 shrink-0" />
)}
+ {!selectionMode && shouldUseClickTray && (
+ <button
+ title={
+ isTrayOpen
+ ? t("hosts.collapseActions")
+ : t("hosts.expandActions")
+ }
+ onClick={(e) => {
+ e.stopPropagation();
+ onTrayOpenChange?.(!isTrayOpen);
+ }}
+ className="ml-auto flex items-center justify-center size-5 rounded text-muted-foreground/30 hover:text-muted-foreground hover:bg-muted-foreground/10 transition-colors shrink-0"
+ >
+ <ChevronRight
+ className={`size-3 transition-transform duration-150 ${isTrayOpen ? "rotate-90" : ""}`}
+ />
+ </button>
+ )}
</div>
- {/* Address — only visible on hover (or click when trayOnClick) or while menu is open */}
- <span
- className={`text-[11px] text-muted-foreground/55 truncate leading-none pl-3 transition-opacity duration-100 ${!trayOnClick ? "group-hover:opacity-100 group-hover:h-auto" : ""} ${isMenuOpen || (trayOnClick && isTrayOpen) ? "opacity-100 h-auto" : "opacity-0 h-0 overflow-hidden"}`}
- >
+ {/* Address — always visible */}
+ <span className="text-[11px] text-muted-foreground/45 truncate leading-none pl-3">
{host.username}@{host.ip}
</span>
@@ -331,9 +405,88 @@ export function HostItem({
</div>
)}
- {/* Action tray — slides open on CSS hover, on click (when trayOnClick), or while menu is open */}
+ {/* Connection buttons — always visible in click-tray mode, inside hover tray otherwise */}
+ {shouldUseClickTray && !selectionMode && (
+ <div className="flex items-center flex-wrap gap-1 pl-2 pb-1">
+ {getSshActions(host).map(({ type, icon: Icon, label }) => (
+ <button
+ key={type}
+ title={label}
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenTab(type);
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <Icon className="size-3.5" />
+ </button>
+ ))}
+ {host.enableSsh &&
+ (host.enableRdp || host.enableVnc || host.enableTelnet) &&
+ getSshActions(host).length > 0 && (
+ <div className="w-px h-3.5 bg-border/60 mx-0.5 shrink-0" />
+ )}
+ {host.enableRdp && (
+ <button
+ title="RDP"
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenTab("rdp");
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <Monitor className="size-3.5" />
+ </button>
+ )}
+ {host.enableVnc && (
+ <button
+ title="VNC"
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenTab("vnc");
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <MousePointerClick className="size-3.5" />
+ </button>
+ )}
+ {host.enableTelnet && (
+ <button
+ title="Telnet"
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenTab("telnet");
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <MessagesSquare className="size-3.5" />
+ </button>
+ )}
+ {host.macAddress && (
+ <button
+ title={t("hosts.wakeOnLanAction")}
+ onClick={async (e) => {
+ e.stopPropagation();
+ try {
+ await wakeOnLan(host.id);
+ toast.success(
+ t("hosts.wakeOnLanSuccess", { name: host.name }),
+ );
+ } catch {
+ toast.error(t("hosts.wakeOnLanError"));
+ }
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <Zap className="size-3.5" />
+ </button>
+ )}
+ </div>
+ )}
+
+ {/* Action tray — slides open on hover (default) or via chevron in click-tray mode */}
<div
- className={`overflow-hidden transition-all duration-150 ease-out max-h-0 opacity-0 ${!trayOnClick ? "group-hover:max-h-[300px] group-hover:opacity-100" : ""} ${selectionMode ? "!max-h-0 !opacity-0" : ""} ${(isMenuOpen || (trayOnClick && isTrayOpen)) && !selectionMode ? "!max-h-[300px] !opacity-100" : ""}`}
+ className={`overflow-hidden transition-all duration-150 ease-out max-h-0 opacity-0 ${!shouldUseClickTray ? "group-hover:max-h-[300px] group-hover:opacity-100" : ""} ${selectionMode ? "!max-h-0 !opacity-0" : ""} ${(isMenuOpen || (shouldUseClickTray && isTrayOpen)) && !selectionMode ? "!max-h-[300px] !opacity-100" : ""}`}
>
{host.online &&
((host.cpu != null && host.cpu > 0) ||
@@ -371,85 +524,105 @@ export function HostItem({
)}
<div className="flex flex-col gap-0.5 pt-1.5 pl-2 pb-1">
- {/* Connection buttons — wrap naturally to a second line */}
- <div className="flex items-center flex-wrap gap-1">
- {getSshActions(host).map(({ type, icon: Icon, label }) => (
- <button
- key={type}
- title={label}
- onClick={(e) => {
- e.stopPropagation();
- onOpenTab(type);
- }}
- className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
- >
- <Icon className="size-3.5" />
- </button>
- ))}
- {host.enableSsh &&
- (host.enableRdp || host.enableVnc || host.enableTelnet) &&
- getSshActions(host).length > 0 && (
- <div className="w-px h-3.5 bg-border/60 mx-0.5 shrink-0" />
+ {/* Connection buttons — only shown here in hover mode */}
+ {!shouldUseClickTray && (
+ <div className="flex items-center flex-wrap gap-1">
+ {getSshActions(host).map(({ type, icon: Icon, label }) => (
+ <button
+ key={type}
+ title={label}
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenTab(type);
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <Icon className="size-3.5" />
+ </button>
+ ))}
+ {host.enableSsh &&
+ (host.enableRdp || host.enableVnc || host.enableTelnet) &&
+ getSshActions(host).length > 0 && (
+ <div className="w-px h-3.5 bg-border/60 mx-0.5 shrink-0" />
+ )}
+ {host.enableRdp && (
+ <button
+ title="RDP"
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenTab("rdp");
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <Monitor className="size-3.5" />
+ </button>
)}
- {host.enableRdp && (
- <button
- title="RDP"
- onClick={(e) => {
- e.stopPropagation();
- onOpenTab("rdp");
- }}
- className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
- >
- <Monitor className="size-3.5" />
- </button>
- )}
- {host.enableVnc && (
- <button
- title="VNC"
- onClick={(e) => {
- e.stopPropagation();
- onOpenTab("vnc");
- }}
- className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
- >
- <MousePointerClick className="size-3.5" />
- </button>
- )}
- {host.enableTelnet && (
+ {host.enableVnc && (
+ <button
+ title="VNC"
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenTab("vnc");
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <MousePointerClick className="size-3.5" />
+ </button>
+ )}
+ {host.enableTelnet && (
+ <button
+ title="Telnet"
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenTab("telnet");
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <MessagesSquare className="size-3.5" />
+ </button>
+ )}
+ {host.macAddress && (
+ <button
+ title={t("hosts.wakeOnLanAction")}
+ onClick={async (e) => {
+ e.stopPropagation();
+ try {
+ await wakeOnLan(host.id);
+ toast.success(
+ t("hosts.wakeOnLanSuccess", { name: host.name }),
+ );
+ } catch {
+ toast.error(t("hosts.wakeOnLanError"));
+ }
+ }}
+ className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
+ >
+ <Zap className="size-3.5" />
+ </button>
+ )}
+ </div>
+ )}
+
+ {/* Management buttons row */}
+ <div className="flex items-center gap-1 pt-0.5 border-t border-border/40 mt-0.5">
+ {showPasswordCopy && (
<button
- title="Telnet"
- onClick={(e) => {
- e.stopPropagation();
- onOpenTab("telnet");
- }}
+ title={t("nav.copyPassword")}
+ onClick={(e) => handleCopyPassword(e, "password")}
className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
>
- <MessagesSquare className="size-3.5" />
+ <Key className="size-3.5" />
</button>
)}
- {host.macAddress && (
+ {showSudoPasswordCopy && (
<button
- title={t("hosts.wakeOnLanAction")}
- onClick={async (e) => {
- e.stopPropagation();
- try {
- await wakeOnLan(host.id);
- toast.success(
- t("hosts.wakeOnLanSuccess", { name: host.name }),
- );
- } catch {
- toast.error(t("hosts.wakeOnLanError"));
- }
- }}
+ title={t("nav.copySudoPassword")}
+ onClick={(e) => handleCopyPassword(e, "sudoPassword")}
className="flex items-center justify-center size-7 rounded text-muted-foreground/50 hover:text-foreground hover:bg-muted-foreground/10 transition-colors"
>
- <Zap className="size-3.5" />
+ <Key className="size-3.5" />
</button>
)}
- </div>
-
- {/* Separator + management buttons row — always fixed position */}
- <div className="flex items-center gap-1 pt-0.5 border-t border-border/40 mt-0.5">
{onEditHost && (
<button
title="Edit Host"
@@ -497,6 +670,22 @@ export function HostItem({
<Copy className="size-3.5 mr-2" />
{t("hosts.copyAddress")}
</DropdownMenuItem>
+ {showPasswordCopy && (
+ <DropdownMenuItem
+ onClick={(e) => handleCopyPassword(e, "password")}
+ >
+ <Key className="size-3.5 mr-2" />
+ {t("nav.copyPassword")}
+ </DropdownMenuItem>
+ )}
+ {showSudoPasswordCopy && (
+ <DropdownMenuItem
+ onClick={(e) => handleCopyPassword(e, "sudoPassword")}
+ >
+ <Key className="size-3.5 mr-2" />
+ {t("nav.copySudoPassword")}
+ </DropdownMenuItem>
+ )}
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<Link className="size-3.5 mr-2" />
@@ -667,6 +856,11 @@ export function FolderItem({
onMenuOpenChange,
openTrayHostId,
onTrayOpenChange,
+ editingFolderName,
+ editingFolderValue,
+ onEditingFolderNameChange,
+ onEditingFolderValueChange,
+ onRenameFolder,
}: {
folder: HostFolder;
depth?: number;
@@ -686,6 +880,11 @@ export function FolderItem({
onMenuOpenChange: (hostId: string | null) => void;
openTrayHostId: string | null;
onTrayOpenChange: (hostId: string | null) => void;
+ editingFolderName: string | null;
+ editingFolderValue: string;
+ onEditingFolderNameChange: (name: string | null) => void;
+ onEditingFolderValueChange: (value: string) => void;
+ onRenameFolder: (oldName: string, newName: string) => Promise<void>;
}) {
const { total, online } = folderHostCount(folder);
@@ -693,12 +892,13 @@ export function FolderItem({
const isOpen = query ? true : openFolders.has(folder.name);
const stripeIndex = stripeMap.get(folder) ?? 0;
+ const isEditing = editingFolderName === folder.name;
return (
<div>
<button
- onClick={() => !query && onToggleFolder(folder.name)}
- className={`flex items-center gap-2 w-full px-3 py-2 hover:bg-muted/50 transition-colors text-left cursor-pointer ${stripeIndex % 2 === 1 ? "bg-muted/20" : ""}`}
+ onClick={() => !query && !isEditing && onToggleFolder(folder.name)}
+ className={`group/folder flex items-center gap-2 w-full px-3 py-2 hover:bg-muted/50 transition-colors text-left cursor-pointer ${stripeIndex % 2 === 1 ? "bg-muted/20" : ""}`}
>
<ChevronRight
className={`size-3 shrink-0 text-muted-foreground/50 transition-transform ${isOpen ? "rotate-90" : ""}`}
@@ -706,15 +906,61 @@ export function FolderItem({
<FolderOpen
className={`size-3.5 shrink-0 ${isOpen ? "text-accent-brand" : "text-muted-foreground/60"}`}
/>
- <span className="text-[13px] font-semibold text-foreground/80 truncate flex-1">
- {folder.name}
- </span>
- <span className="text-[10px] tabular-nums shrink-0 ml-1">
- {online > 0 && (
- <span className="text-accent-brand font-semibold">{online}</span>
- )}
- <span className="text-muted-foreground/40">/{total}</span>
- </span>
+ {isEditing ? (
+ <>
+ <input
+ autoFocus
+ value={editingFolderValue}
+ onChange={(e) => onEditingFolderValueChange(e.target.value)}
+ onBlur={async () => {
+ const newName = editingFolderValue.trim();
+ onEditingFolderNameChange(null);
+ if (newName && newName !== folder.name) {
+ await onRenameFolder(folder.name, newName);
+ }
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") e.currentTarget.blur();
+ if (e.key === "Escape") onEditingFolderNameChange(null);
+ }}
+ onClick={(e) => e.stopPropagation()}
+ className="text-[10px] font-semibold bg-background border border-accent-brand/60 px-1 outline-none text-foreground min-w-0 flex-1"
+ />
+ <span
+ onClick={(e) => {
+ e.stopPropagation();
+ onEditingFolderNameChange(null);
+ }}
+ className="text-muted-foreground hover:text-foreground shrink-0"
+ >
+ <X className="size-3" />
+ </span>
+ </>
+ ) : (
+ <>
+ <span className="text-[13px] font-semibold text-foreground/80 truncate flex-1">
+ {folder.name}
+ </span>
+ <span className="text-[10px] tabular-nums shrink-0 ml-1">
+ {online > 0 && (
+ <span className="text-accent-brand font-semibold">
+ {online}
+ </span>
+ )}
+ <span className="text-muted-foreground/40">/{total}</span>
+ </span>
+ <span
+ className="opacity-0 group-hover/folder:opacity-100 transition-opacity ml-1 text-muted-foreground/50 hover:text-foreground"
+ onClick={(e) => {
+ e.stopPropagation();
+ onEditingFolderNameChange(folder.name);
+ onEditingFolderValueChange(folder.name);
+ }}
+ >
+ <Pencil className="size-2.5" />
+ </span>
+ </>
+ )}
</button>
{isOpen && (
<div className="border-l border-border/40 ml-[30px]">
@@ -740,6 +986,11 @@ export function FolderItem({
onMenuOpenChange={onMenuOpenChange}
openTrayHostId={openTrayHostId}
onTrayOpenChange={onTrayOpenChange}
+ editingFolderName={editingFolderName}
+ editingFolderValue={editingFolderValue}
+ onEditingFolderNameChange={onEditingFolderNameChange}
+ onEditingFolderValueChange={onEditingFolderValueChange}
+ onRenameFolder={onRenameFolder}
/>
) : (
<HostItem
@@ -798,6 +1049,10 @@ export function SidebarTree({
);
const [openMenuHostId, setOpenMenuHostId] = useState<string | null>(null);
const [openTrayHostId, setOpenTrayHostId] = useState<string | null>(null);
+ const [editingFolderName, setEditingFolderName] = useState<string | null>(
+ null,
+ );
+ const [editingFolderValue, setEditingFolderValue] = useState("");
const [confirmDialog, setConfirmDialog] = useState<{
message: string;
onConfirm: () => Promise<void> | void;
@@ -806,7 +1061,11 @@ export function SidebarTree({
function toggleFolder(name: string) {
setOpenFolders((prev) => {
const next = new Set(prev);
- next.has(name) ? next.delete(name) : next.add(name);
+ if (next.has(name)) {
+ next.delete(name);
+ } else {
+ next.add(name);
+ }
return next;
});
}
@@ -814,7 +1073,11 @@ export function SidebarTree({
function toggleSelect(id: string) {
setSelectedHostIds((prev) => {
const next = new Set(prev);
- next.has(id) ? next.delete(id) : next.add(id);
+ if (next.has(id)) {
+ next.delete(id);
+ } else {
+ next.add(id);
+ }
return next;
});
}
@@ -836,7 +1099,7 @@ export function SidebarTree({
async function handleDuplicateHost(host: Host) {
try {
- await createSSHHost({
+ const duplicateHost: SSHHostData = {
name: `${host.name} (copy)`,
ip: host.ip,
port: host.port,
@@ -893,7 +1156,8 @@ export function SidebarTree({
statsConfig: host.statsConfig,
guacamoleConfig: host.guacamoleConfig ?? null,
terminalConfig: host.terminalConfig ?? null,
- } as any);
+ };
+ await createSSHHost(duplicateHost);
window.dispatchEvent(new CustomEvent("termix:hosts-changed"));
toast.success(t("hosts.duplicatedHost", { name: host.name }));
} catch {
@@ -901,6 +1165,16 @@ export function SidebarTree({
}
}
+ async function handleRenameFolder(oldName: string, newName: string) {
+ try {
+ await renameFolder(oldName, newName);
+ window.dispatchEvent(new CustomEvent("termix:hosts-changed"));
+ toast.success(t("hosts.folderRenamedTo", { name: newName }));
+ } catch {
+ toast.error(t("hosts.failedToRenameFolder"));
+ }
+ }
+
const allHosts = collectAllHosts(children);
const allFolders = collectAllFolders(children);
@@ -966,6 +1240,11 @@ export function SidebarTree({
onMenuOpenChange={setOpenMenuHostId}
openTrayHostId={openTrayHostId}
onTrayOpenChange={setOpenTrayHostId}
+ editingFolderName={editingFolderName}
+ editingFolderValue={editingFolderValue}
+ onEditingFolderNameChange={setEditingFolderName}
+ onEditingFolderValueChange={setEditingFolderValue}
+ onRenameFolder={handleRenameFolder}
/>
) : (
<HostItem
diff --git a/src/ui/sidebar/SnippetsPanel.tsx b/src/ui/sidebar/SnippetsPanel.tsx
index 1c68c5235..9372dbd10 100644
--- a/src/ui/sidebar/SnippetsPanel.tsx
+++ b/src/ui/sidebar/SnippetsPanel.tsx
@@ -501,6 +501,18 @@ type AccessRecord = {
expiresAt: string | null;
};
+type SnippetPayload = Omit<Snippet, "id" | "order">;
+type RawSnippet = SnippetPayload & {
+ id: number;
+ order?: number | null;
+};
+type RawSnippetFolder = {
+ id: number;
+ name: string;
+ color?: string | null;
+ icon?: FolderIconId | null;
+};
+
function ShareSnippetDialog({
snippet,
onClose,
@@ -524,15 +536,13 @@ function ShareSnippetDialog({
Promise.all([getUserList(), getRoles(), getSnippetAccess(snippet.id)])
.then(([usersData, rolesData, accessData]) => {
setUsers(
- (usersData?.users || []).map((u: any) => ({
- id: u.id,
+ (usersData?.users || []).map((u) => ({
+ id: u.userId,
username: u.username,
})),
);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- setRoles((rolesData?.roles || []).map((r: any) => r));
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- setAccessList((accessData as any).accessList || []);
+ setRoles(rolesData?.roles || []);
+ setAccessList(accessData.accessList || []);
})
.catch(() => toast.error(t("newUi.sidebar.snippets.shareLoadError")))
.finally(() => setLoading(false));
@@ -547,8 +557,7 @@ function ShareSnippetDialog({
targetRoleId: targetType === "role" ? parseInt(targetId) : undefined,
});
toast.success(t("newUi.sidebar.snippets.shareSuccess"));
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const accessData = (await getSnippetAccess(snippet.id)) as any;
+ const accessData = await getSnippetAccess(snippet.id);
setAccessList(accessData.accessList || []);
setTargetId("");
} catch {
@@ -561,8 +570,7 @@ function ShareSnippetDialog({
try {
await revokeSnippetAccess(snippet.id, accessId);
toast.success(t("newUi.sidebar.snippets.revokeSuccess"));
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const accessData = (await getSnippetAccess(snippet.id)) as any;
+ const accessData = await getSnippetAccess(snippet.id);
setAccessList(accessData.accessList || []);
} catch {
toast.error(t("newUi.sidebar.snippets.revokeFailed"));
@@ -974,9 +982,8 @@ export function SnippetsPanel({
getSnippets()
.then((data) => {
- const arr = Array.isArray(data) ? data : [];
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const mapped: Snippet[] = arr.map((s: any) => ({
+ const arr: RawSnippet[] = Array.isArray(data) ? data : [];
+ const mapped: Snippet[] = arr.map((s) => ({
id: s.id,
name: s.name,
description: s.description,
@@ -990,9 +997,8 @@ export function SnippetsPanel({
getSnippetFolders()
.then((data) => {
- const arr = Array.isArray(data) ? data : [];
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const mapped: SnippetFolder[] = arr.map((f: any) => ({
+ const arr: RawSnippetFolder[] = Array.isArray(data) ? data : [];
+ const mapped: SnippetFolder[] = arr.map((f) => ({
id: f.id,
name: f.name,
color: f.color ?? FOLDER_COLORS[0],
@@ -1007,7 +1013,11 @@ export function SnippetsPanel({
function toggleTab(id: string) {
setSelectedTabIds((prev) => {
const next = new Set(prev);
- next.has(id) ? next.delete(id) : next.add(id);
+ if (next.has(id)) {
+ next.delete(id);
+ } else {
+ next.add(id);
+ }
return next;
});
}
@@ -1018,15 +1028,13 @@ export function SnippetsPanel({
) {
try {
if (id !== undefined) {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- await apiUpdateSnippet(id, data as any);
+ await apiUpdateSnippet(id, data);
updateSnippets((prev) =>
prev.map((s) => (s.id === id ? { ...s, ...data } : s)),
);
toast.success(t("newUi.sidebar.snippets.updateSuccess"));
} else {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const created = (await apiCreateSnippet(data as any)) as any;
+ const created = await apiCreateSnippet(data);
updateSnippets((prev) => [
...prev,
{
@@ -1048,12 +1056,14 @@ export function SnippetsPanel({
async function handleCreateFolder(f: Omit<SnippetFolder, "id" | "open">) {
try {
- const created = (await apiCreateSnippetFolder({
+ const created = await apiCreateSnippetFolder({
name: f.name,
color: f.color,
icon: f.icon,
- })) as any;
- setFolders((prev) => [...prev, { ...f, id: created.id, open: true }]);
+ });
+ const id =
+ typeof created.id === "number" ? created.id : Number(created.id);
+ setFolders((prev) => [...prev, { ...f, id, open: true }]);
toast.success(t("newUi.sidebar.snippets.folderCreateSuccess"));
} catch {
toast.error(t("newUi.sidebar.snippets.folderCreateFailed"));
diff --git a/src/ui/sidebar/SshToolsPanel.tsx b/src/ui/sidebar/SshToolsPanel.tsx
index 7ae37c727..688fdad10 100644
--- a/src/ui/sidebar/SshToolsPanel.tsx
+++ b/src/ui/sidebar/SshToolsPanel.tsx
@@ -35,7 +35,11 @@ export function SshToolsPanel({
function toggleTab(id: string) {
setSelectedTabIds((prev) => {
const next = new Set(prev);
- next.has(id) ? next.delete(id) : next.add(id);
+ if (next.has(id)) {
+ next.delete(id);
+ } else {
+ next.add(id);
+ }
return next;
});
}
@@ -51,7 +55,7 @@ export function SshToolsPanel({
function broadcast(data: string) {
for (const tabId of selectedTabIds) {
const tab = terminalTabs.find((t) => t.id === tabId);
- (tab?.terminalRef?.current as any)?.sendInput?.(data);
+ tab?.terminalRef?.current?.sendInput?.(data);
}
}
diff --git a/src/ui/sidebar/UserProfilePanel.tsx b/src/ui/sidebar/UserProfilePanel.tsx
index 3552f30d6..185b6df8c 100644
--- a/src/ui/sidebar/UserProfilePanel.tsx
+++ b/src/ui/sidebar/UserProfilePanel.tsx
@@ -13,6 +13,7 @@ import {
disableTOTP,
getVersionInfo,
getUserRoles,
+ saveUserPreferences,
} from "@/main-axios";
import type { UserRole } from "@/main-axios";
import type React from "react";
@@ -137,6 +138,8 @@ function AccordionSection({
<div className="border border-border bg-card overflow-hidden">
<button
onClick={onToggle}
+ aria-expanded={open}
+ aria-controls={`${id}-content`}
className="flex items-center gap-2 w-full px-3 py-2.5 text-left hover:bg-muted/40 transition-colors"
>
<span className="text-muted-foreground shrink-0">{icon}</span>
@@ -148,12 +151,35 @@ function AccordionSection({
/>
</button>
{open && (
- <div className="border-t border-border px-3 pb-3">{children}</div>
+ <div id={`${id}-content`} className="border-t border-border px-3 pb-3">
+ {children}
+ </div>
)}
</div>
);
}
+type ApiErrorLike = {
+ response?: {
+ data?: {
+ error?: string;
+ };
+ };
+};
+
+function apiErrorMessage(error: unknown, fallback: string) {
+ return (error as ApiErrorLike).response?.data?.error || fallback;
+}
+
+type CreatedProfileApiKey = {
+ id: string;
+ name: string;
+ token?: string;
+ tokenPrefix?: string;
+ createdAt?: string;
+ expiresAt?: string | null;
+};
+
function NewApiKeyDialog({
open,
onOpenChange,
@@ -162,7 +188,7 @@ function NewApiKeyDialog({
}: {
open: boolean;
onOpenChange: (v: boolean) => void;
- onAdd: (key: any) => void;
+ onAdd: (key: CreatedProfileApiKey) => void;
userId: string;
}) {
const { t } = useTranslation();
@@ -296,10 +322,9 @@ function PasswordChangeSection({
setNewPw("");
setConfirmPw("");
onLogout?.();
- } catch (e: any) {
+ } catch (e: unknown) {
toast.error(
- e?.response?.data?.error ||
- t("newUi.sidebar.userProfile.passwordUpdateFailed"),
+ apiErrorMessage(e, t("newUi.sidebar.userProfile.passwordUpdateFailed")),
);
}
}
@@ -527,24 +552,41 @@ export function UserProfilePanel({
setVersionStatus(info.status ?? "up_to_date");
})
.catch(() => {});
- }, []);
+ }, [t]);
+
+ function saveAppearancePreference(prefs: {
+ theme?: ThemeId;
+ fontSize?: FontSizeId;
+ accentColor?: string;
+ language?: string;
+ }) {
+ void saveUserPreferences(prefs).catch(() => {});
+ }
+
+ function handleThemeChange(id: ThemeId) {
+ setTheme(id);
+ saveAppearancePreference({ theme: id });
+ }
function handleAccentChange(value: string) {
setAccentColor(value);
setCustomColorInput(value);
localStorage.setItem("termix-accent", value);
applyAccentColor(value);
+ saveAppearancePreference({ accentColor: value });
}
function handleFontSizeChange(id: FontSizeId) {
setFontSize(id);
applyFontSize(id);
+ saveAppearancePreference({ fontSize: id });
}
function handleLanguageChange(code: string) {
setLanguage(code);
localStorage.setItem("i18nextLng", code);
i18n.changeLanguage(code);
+ saveAppearancePreference({ language: code });
}
function toggle(id: UserProfileSection) {
@@ -578,10 +620,9 @@ export function UserProfilePanel({
setTotpEnabled(true);
setTotpStep("backup");
toast.success(t("newUi.sidebar.userProfile.totpEnabledSuccess"));
- } catch (e: any) {
+ } catch (e: unknown) {
toast.error(
- e?.response?.data?.error ||
- t("newUi.sidebar.userProfile.totpInvalidCode"),
+ apiErrorMessage(e, t("newUi.sidebar.userProfile.totpInvalidCode")),
);
} finally {
setTotpLoading(false);
@@ -600,10 +641,9 @@ export function UserProfilePanel({
setShowDisableTotp(false);
setDisableTotpInput("");
toast.success(t("newUi.sidebar.userProfile.totpDisabledSuccess"));
- } catch (e: any) {
+ } catch (e: unknown) {
toast.error(
- e?.response?.data?.error ||
- t("newUi.sidebar.userProfile.totpDisableFailed"),
+ apiErrorMessage(e, t("newUi.sidebar.userProfile.totpDisableFailed")),
);
} finally {
setTotpLoading(false);
@@ -630,9 +670,9 @@ export function UserProfilePanel({
await deleteAccount(deletePassword);
await logoutUser().catch(() => {});
window.location.reload();
- } catch (e: any) {
+ } catch (e: unknown) {
toast.error(
- e?.response?.data?.error || t("newUi.sidebar.userProfile.deleteFailed"),
+ apiErrorMessage(e, t("newUi.sidebar.userProfile.deleteFailed")),
);
setDeleteLoading(false);
}
@@ -796,7 +836,7 @@ export function UserProfilePanel({
<div className="relative">
<select
value={theme}
- onChange={(e) => setTheme(e.target.value as ThemeId)}
+ onChange={(e) => handleThemeChange(e.target.value as ThemeId)}
className="w-full px-2.5 py-1.5 text-xs bg-background border border-border text-foreground outline-none focus:ring-1 focus:ring-ring appearance-none pr-7"
>
{THEMES.map((th) => (
@@ -812,7 +852,7 @@ export function UserProfilePanel({
<button
key={th.id}
title={themeLabel[th.id]}
- onClick={() => setTheme(th.id)}
+ onClick={() => handleThemeChange(th.id)}
className={`h-4 flex-1 border transition-all ${theme === th.id ? "border-accent-brand ring-1 ring-accent-brand" : "border-border/50"}`}
style={{ background: th.preview }}
/>
@@ -990,7 +1030,9 @@ export function UserProfilePanel({
onChange={(v) => {
onPrefsChange?.({ reopenTabsOnLogin: v });
import("@/main-axios").then(({ saveUserPreferences }) => {
- saveUserPreferences({ reopenTabsOnLogin: v }).catch(() => {});
+ saveUserPreferences({ reopenTabsOnLogin: v }).catch(
+ () => {},
+ );
});
}}
/>
diff --git a/src/ui/ssh/connection-log/ConnectionLogContext.tsx b/src/ui/ssh/connection-log/ConnectionLogContext.tsx
index ec72b9cc7..cf7a7e414 100644
--- a/src/ui/ssh/connection-log/ConnectionLogContext.tsx
+++ b/src/ui/ssh/connection-log/ConnectionLogContext.tsx
@@ -1,3 +1,4 @@
+/* eslint-disable react-refresh/only-export-components */
import React, { createContext, useContext, useState, useCallback } from "react";
import type { LogEntry } from "@/types/connection-log.ts";
diff --git a/src/ui/user/C2STunnelPresetManager.tsx b/src/ui/user/C2STunnelPresetManager.tsx
index e5dd90fde..64168d837 100644
--- a/src/ui/user/C2STunnelPresetManager.tsx
+++ b/src/ui/user/C2STunnelPresetManager.tsx
@@ -230,7 +230,11 @@ export function C2STunnelPresetManager(): React.ReactElement {
function toggleTunnel(index: number) {
setOpenTunnels((current) => {
const next = new Set(current);
- next.has(index) ? next.delete(index) : next.add(index);
+ if (next.has(index)) {
+ next.delete(index);
+ } else {
+ next.add(index);
+ }
return next;
});
}
diff --git a/src/ui/user/ElectronVersionCheck.tsx b/src/ui/user/ElectronVersionCheck.tsx
index 02ebb180e..f7e871549 100644
--- a/src/ui/user/ElectronVersionCheck.tsx
+++ b/src/ui/user/ElectronVersionCheck.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect } from "react";
+import React, { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/button.tsx";
import { VersionAlert } from "@/components/version-alert.tsx";
import { useTranslation } from "react-i18next";
@@ -29,21 +29,7 @@ export function ElectronVersionCheck({ onContinue }: VersionCheckModalProps) {
? t("versionCheck.betaVersion")
: t("versionCheck.updateRequired");
- useEffect(() => {
- const updateCheckDisabled =
- localStorage.getItem("disableUpdateCheck") === "true";
- if (updateCheckDisabled) {
- onContinue();
- return;
- }
- if (isElectron()) {
- checkForUpdates();
- } else {
- onContinue();
- }
- }, []);
-
- const checkForUpdates = async () => {
+ const checkForUpdates = useCallback(async () => {
setVersionChecking(true);
try {
const updateInfo = await checkElectronUpdate();
@@ -77,7 +63,21 @@ export function ElectronVersionCheck({ onContinue }: VersionCheckModalProps) {
} finally {
setVersionChecking(false);
}
- };
+ }, [onContinue]);
+
+ useEffect(() => {
+ const updateCheckDisabled =
+ localStorage.getItem("disableUpdateCheck") === "true";
+ if (updateCheckDisabled) {
+ onContinue();
+ return;
+ }
+ if (isElectron()) {
+ checkForUpdates();
+ } else {
+ onContinue();
+ }
+ }, [checkForUpdates, onContinue]);
const handleDownloadUpdate = () => {
if (versionInfo?.latest_release?.html_url) {
diff --git a/tsconfig.app.json b/tsconfig.app.json
index a87c53f81..a82f8ab58 100644
--- a/tsconfig.app.json
+++ b/tsconfig.app.json
@@ -32,5 +32,10 @@
"@/*": ["./src/ui/*"]
}
},
- "include": ["src"]
+ "include": [
+ "src/main.tsx",
+ "src/ui/**/*.ts",
+ "src/ui/**/*.tsx",
+ "src/types/**/*.ts"
+ ]
}
diff --git a/tsconfig.node.json b/tsconfig.node.json
index 92d03da02..66fb31bf8 100644
--- a/tsconfig.node.json
+++ b/tsconfig.node.json
@@ -30,5 +30,6 @@
"src/backend/**/*.ts",
"src/types/**/*.ts",
"src/ui/types/**/*.ts"
- ]
+ ],
+ "exclude": ["src/**/*.test.ts", "src/backend/test-helpers/**"]
}
diff --git a/vitest.config.ts b/vitest.config.ts
new file mode 100644
index 000000000..bab0b1032
--- /dev/null
+++ b/vitest.config.ts
@@ -0,0 +1,49 @@
+import path from "path";
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ resolve: {
+ alias: {
+ "@/types": path.resolve(__dirname, "./src/types"),
+ "@": path.resolve(__dirname, "./src/ui"),
+ },
+ },
+ test: {
+ globals: true,
+ setupFiles: ["./vitest.setup.ts"],
+ coverage: {
+ provider: "v8",
+ reporter: ["text", "html"],
+ reportsDirectory: "./coverage",
+ exclude: [
+ "**/node_modules/**",
+ "**/dist/**",
+ "**/coverage/**",
+ "electron/**",
+ "scripts/**",
+ "**/*.config.*",
+ "**/*.test.{ts,tsx}",
+ "src/backend/test-helpers/**",
+ "src/ui/locales/**",
+ ],
+ },
+ projects: [
+ {
+ extends: true,
+ test: {
+ name: "backend",
+ environment: "node",
+ include: ["src/backend/**/*.test.ts"],
+ },
+ },
+ {
+ extends: true,
+ test: {
+ name: "frontend",
+ environment: "jsdom",
+ include: ["src/ui/**/*.test.{ts,tsx}"],
+ },
+ },
+ ],
+ },
+});
diff --git a/vitest.setup.ts b/vitest.setup.ts
new file mode 100644
index 000000000..b2bb5a4bf
--- /dev/null
+++ b/vitest.setup.ts
@@ -0,0 +1,21 @@
+import { afterEach, vi } from "vitest";
+
+// jsdom does not implement matchMedia; provide a minimal stub so hooks that
+// read media queries (e.g. useIsMobile) can run. Individual tests override
+// window.innerWidth / matchMedia as needed.
+if (typeof window !== "undefined" && !window.matchMedia) {
+ window.matchMedia = vi.fn().mockImplementation((query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }));
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});