2 Commits

Author SHA1 Message Date
AB from home.homenet
58f63671d8 Bump 0.7.0 2025-07-22 23:24:41 +03:00
Alexandr Bogomyakov
99a277088a UI tray app added
* Works with egui

---------

Co-authored-by: Ultradesu <ultradesu@hexor.cy>
2025-07-22 23:23:18 +03:00
39 changed files with 1124 additions and 9381 deletions

View File

@@ -1,33 +0,0 @@
# Git
.git/
.gitignore
# Rust build artifacts
target/
Cargo.lock
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Documentation
*.md
LICENSE
# CI/CD
.github/
.gitlab-ci.yml
# Testing
tests/
benches/
# Development files
*.log
*.tmp

View File

@@ -7,37 +7,25 @@ on:
env: env:
CARGO_TERM_COLOR: always CARGO_TERM_COLOR: always
CLI_BINARY_NAME: khm BINARY_NAME: khm
DESKTOP_BINARY_NAME: khm-desktop
jobs: jobs:
build: build:
name: Build static binary name: Build static binary
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
include: include:
# - os: ubuntu-latest
# build_target: x86_64-unknown-linux-musl
# platform_name: linux-amd64-musl
# build_type: musl
- os: ubuntu-latest - os: ubuntu-latest
build_target: x86_64-unknown-linux-gnu build_target: x86_64-unknown-linux-musl
platform_name: linux-amd64 platform_name: linux-amd64
build_type: dynamic
- os: ubuntu-latest
build_target: aarch64-unknown-linux-gnu
platform_name: linux-arm64
build_type: dynamic # CLI only - GUI deps too complex for cross-compilation
- os: windows-latest - os: windows-latest
build_target: x86_64-pc-windows-msvc build_target: x86_64-pc-windows-msvc
platform_name: windows-amd64 platform_name: windows-amd64
build_type: default
- os: macos-latest - os: macos-latest
build_target: aarch64-apple-darwin build_target: aarch64-apple-darwin
platform_name: macos-arm64 platform_name: macos-arm64
build_type: default
permissions: permissions:
contents: write contents: write
steps: steps:
@@ -72,149 +60,79 @@ jobs:
- name: Install rust targets - name: Install rust targets
run: rustup target add ${{ matrix.build_target }} run: rustup target add ${{ matrix.build_target }}
- name: Install Linux x86_64 dependencies - name: Build Linux MUSL
if: matrix.os == 'ubuntu-latest' && matrix.build_type == 'dynamic' && matrix.build_target == 'x86_64-unknown-linux-gnu' if: matrix.os == 'ubuntu-latest'
run: | uses: gmiam/rust-musl-action@master
sudo apt-get update with:
sudo apt-get install -y libssl-dev pkg-config libgtk-3-dev libglib2.0-dev libcairo2-dev libpango1.0-dev libatk1.0-dev libgdk-pixbuf2.0-dev libxdo-dev libayatana-appindicator3-dev args: cargo build --target ${{ matrix.build_target }} --release
- name: Install Linux ARM64 cross-compilation dependencies
if: matrix.os == 'ubuntu-latest' && matrix.build_type == 'dynamic' && matrix.build_target == 'aarch64-unknown-linux-gnu'
run: |
sudo apt-get update
# Install cross-compilation tools and build dependencies for vendored OpenSSL
sudo apt-get install -y gcc-aarch64-linux-gnu pkg-config libssl-dev build-essential make perl
- name: Build Linux x86_64
if: matrix.os == 'ubuntu-latest' && matrix.build_type == 'dynamic' && matrix.build_target == 'x86_64-unknown-linux-gnu'
run: |
# Build CLI without GUI features
cargo build --target ${{ matrix.build_target }} --release --bin khm --no-default-features --features cli
# Build Desktop with GUI features
cargo build --target ${{ matrix.build_target }} --release --bin khm-desktop
- name: Build Linux ARM64 (CLI only)
if: matrix.os == 'ubuntu-latest' && matrix.build_type == 'dynamic' && matrix.build_target == 'aarch64-unknown-linux-gnu'
env:
CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc
CC_aarch64_unknown_linux_gnu: aarch64-linux-gnu-gcc
CXX_aarch64_unknown_linux_gnu: aarch64-linux-gnu-g++
run: cargo build --target ${{ matrix.build_target }} --release --bin khm --no-default-features --features cli
# - name: Build Linux MUSL (no GUI)
# if: matrix.os == 'ubuntu-latest' && matrix.build_type == 'musl'
# uses: gmiam/rust-musl-action@master
# with:
# args: |
# sed -i 's/deb.debian.org/archive.debian.org/g' /etc/apt/sources.list
# sed -i 's/security.debian.org/archive.debian.org/g' /etc/apt/sources.list
# sed -i '/buster-updates/d' /etc/apt/sources.list
# apt-get update && apt-get install -y pkg-config
# cargo build --target ${{ matrix.build_target }} --release --no-default-features --features server
- name: Build MacOS - name: Build MacOS
if: matrix.os == 'macos-latest' if: matrix.os == 'macos-latest'
run: | run: cargo build --target ${{ matrix.build_target }} --release
# Build CLI without GUI features
cargo build --target ${{ matrix.build_target }} --release --bin khm --no-default-features --features cli
# Build Desktop with GUI features
cargo build --target ${{ matrix.build_target }} --release --bin khm-desktop
- name: Build Windows - name: Build Windows
if: matrix.os == 'windows-latest' if: matrix.os == 'windows-latest'
run: | run: cargo build --target ${{ matrix.build_target }} --release
# Build CLI without GUI features
cargo build --target ${{ matrix.build_target }} --release --bin khm --no-default-features --features cli
# Build Desktop with GUI features
cargo build --target ${{ matrix.build_target }} --release --bin khm-desktop
- name: Upload CLI artifact - name: Upload artifact
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
name: ${{ env.CLI_BINARY_NAME }}_${{ matrix.platform_name }} name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
path: | path: target/${{ matrix.build_target }}/release/${{ env.BINARY_NAME }}*
target/${{ matrix.build_target }}/release/${{ env.CLI_BINARY_NAME }}${{ matrix.os == 'windows-latest' && '.exe' || '' }}
- name: Upload Desktop artifact
# Only upload desktop binary for x86_64 platforms (not ARM64)
if: matrix.build_target != 'aarch64-unknown-linux-gnu'
uses: actions/upload-artifact@v4
with:
name: ${{ env.DESKTOP_BINARY_NAME }}_${{ matrix.platform_name }}
path: |
target/${{ matrix.build_target }}/release/${{ env.DESKTOP_BINARY_NAME }}${{ matrix.os == 'windows-latest' && '.exe' || '' }}
continue-on-error: true # Don't fail if desktop binary doesn't build on some platforms
release: release:
name: Create Release and Upload Assets name: Create Release Page
if: always() # Always run even if some builds fail
needs: build needs: build
runs-on: ubuntu-latest runs-on: ubuntu-latest
outputs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
permissions: permissions:
contents: write contents: write
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts/
- name: Prepare release assets
run: |
mkdir -p release-assets/
# Copy files with proper naming from each artifact directory
for artifact_dir in artifacts/*/; do
if [[ -d "$artifact_dir" ]]; then
artifact_name=$(basename "$artifact_dir")
echo "Processing artifact: $artifact_name"
# Extract binary type and platform from artifact name
if [[ "$artifact_name" =~ ^khm-desktop_(.*)$ ]]; then
binary_type="desktop"
platform="${BASH_REMATCH[1]}"
binary_name="${{ env.DESKTOP_BINARY_NAME }}"
elif [[ "$artifact_name" =~ ^khm_(.*)$ ]]; then
binary_type="cli"
platform="${BASH_REMATCH[1]}"
binary_name="${{ env.CLI_BINARY_NAME }}"
else
echo "Unknown artifact format: $artifact_name"
continue
fi
echo "Binary type: $binary_type, Platform: $platform, Binary name: $binary_name"
# For Windows, look for .exe file specifically
if [[ "$platform" == "windows-amd64" ]]; then
exe_file=$(find "$artifact_dir" -name "${binary_name}.exe" -type f | head -1)
if [[ -n "$exe_file" ]]; then
cp "$exe_file" "release-assets/${binary_name}_${platform}.exe"
echo "Copied: $exe_file -> release-assets/${binary_name}_${platform}.exe"
fi
else
# For Linux/macOS, look for binary without extension
binary_file=$(find "$artifact_dir" -name "${binary_name}" -type f | head -1)
if [[ -n "$binary_file" ]]; then
cp "$binary_file" "release-assets/${binary_name}_${platform}"
echo "Copied: $binary_file -> release-assets/${binary_name}_${platform}"
fi
fi
fi
done
echo "Final release assets:"
ls -la release-assets/
- name: Create Release - name: Create Release
uses: softprops/action-gh-release@v2 id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with: with:
name: Release ${{ github.ref_name }} tag_name: ${{ github.ref }}
files: release-assets/* release_name: Release ${{ github.ref }}
draft: false draft: false
prerelease: false prerelease: false
generate_release_notes: true
fail_on_unmatched_files: false upload:
name: Upload Release Assets
needs: release
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
include:
- os: ubuntu-latest
platform_name: linux-amd64
- os: windows-latest
platform_name: windows-amd64
- os: macos-latest
platform_name: macos-arm64
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
name: Download ${{ matrix.platform_name }} artifact
with:
name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
path: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
- name: Upload Release Asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ needs.release.outputs.upload_url }}
asset_path: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}/${{ env.BINARY_NAME }}${{ matrix.platform_name == 'windows-amd64' && '.exe' || '' }}
asset_name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}${{ matrix.platform_name == 'windows-amd64' && '.exe' || '' }}
asset_content_type: application/octet-stream
build_docker: build_docker:
name: Build and Publish Docker Image name: Build and Publish Docker Image
@@ -223,26 +141,15 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Download Linux AMD64 CLI artifact - uses: actions/download-artifact@v4
uses: actions/download-artifact@v4 name: Download Linux artifact
with: with:
name: ${{ env.CLI_BINARY_NAME }}_linux-amd64 name: ${{ env.BINARY_NAME }}_linux-amd64
path: amd64/ path: .
- name: Download Linux ARM64 CLI artifact - name: ls
uses: actions/download-artifact@v4
with:
name: ${{ env.CLI_BINARY_NAME }}_linux-arm64
path: arm64/
- name: Prepare binaries for multi-arch build
run: | run: |
mkdir -p bin/linux_amd64 bin/linux_arm64 ls -lah
cp amd64/${{ env.CLI_BINARY_NAME }} bin/linux_amd64/${{ env.CLI_BINARY_NAME }}
cp arm64/${{ env.CLI_BINARY_NAME }} bin/linux_arm64/${{ env.CLI_BINARY_NAME }}
chmod +x bin/linux_amd64/${{ env.CLI_BINARY_NAME }}
chmod +x bin/linux_arm64/${{ env.CLI_BINARY_NAME }}
ls -la bin/*/
- name: Set up Docker Buildx - name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3 uses: docker/setup-buildx-action@v3
@@ -256,6 +163,10 @@ jobs:
username: ultradesu username: ultradesu
password: ${{ secrets.DOCKERHUB_TOKEN }} password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set exec flag
run: |
chmod +x ${{ env.BINARY_NAME }}
- name: Set outputs - name: Set outputs
id: get_tag id: get_tag
run: | run: |
@@ -267,5 +178,5 @@ jobs:
context: . context: .
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
push: true push: true
tags: ultradesu/${{ env.CLI_BINARY_NAME }}:latest,ultradesu/${{ env.CLI_BINARY_NAME }}:${{ steps.get_tag.outputs.tag }} tags: ultradesu/${{ env.BINARY_NAME }}:latest,ultradesu/${{ env.BINARY_NAME }}:${{ steps.get_tag.outputs.tag }}

2
.gitignore vendored
View File

@@ -1,5 +1,3 @@
/target /target
*.swp *.swp
*.swo *.swo
.claude/
khm-wasm/target

97
Cargo.lock generated
View File

@@ -1002,7 +1002,6 @@ dependencies = [
"iana-time-zone", "iana-time-zone",
"js-sys", "js-sys",
"num-traits", "num-traits",
"serde",
"wasm-bindgen", "wasm-bindgen",
"windows-targets 0.52.6", "windows-targets 0.52.6",
] ]
@@ -1122,16 +1121,6 @@ dependencies = [
"crossbeam-utils", "crossbeam-utils",
] ]
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
dependencies = [
"cfg-if",
"wasm-bindgen",
]
[[package]] [[package]]
name = "convert_case" name = "convert_case"
version = "0.4.0" version = "0.4.0"
@@ -1946,10 +1935,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys",
"libc", "libc",
"wasi", "wasi",
"wasm-bindgen",
] ]
[[package]] [[package]]
@@ -2685,26 +2672,21 @@ dependencies = [
[[package]] [[package]]
name = "khm" name = "khm"
version = "0.7.1" version = "0.6.3"
dependencies = [ dependencies = [
"actix-web", "actix-web",
"base64 0.21.7", "base64 0.21.7",
"chrono", "chrono",
"clap", "clap",
"console_error_panic_hook",
"dirs 5.0.1", "dirs 5.0.1",
"eframe", "eframe",
"egui", "egui",
"env_logger", "env_logger",
"futures", "futures",
"getrandom",
"glib",
"gtk",
"hostname", "hostname",
"log", "log",
"notify", "notify",
"notify-debouncer-mini", "notify-debouncer-mini",
"openssl",
"regex", "regex",
"reqwest", "reqwest",
"rust-embed", "rust-embed",
@@ -2713,13 +2695,9 @@ dependencies = [
"tokio", "tokio",
"tokio-postgres", "tokio-postgres",
"tokio-util", "tokio-util",
"tracing-wasm",
"tray-icon", "tray-icon",
"trust-dns-resolver", "trust-dns-resolver",
"urlencoding", "urlencoding",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"winit", "winit",
] ]
@@ -2766,12 +2744,6 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388" checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388"
[[package]]
name = "lazy_static"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
[[package]] [[package]]
name = "libappindicator" name = "libappindicator"
version = "0.9.0" version = "0.9.0"
@@ -3021,22 +2993,21 @@ dependencies = [
[[package]] [[package]]
name = "muda" name = "muda"
version = "0.17.0" version = "0.15.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58b89bf91c19bf036347f1ab85a81c560f08c0667c8601bece664d860a600988" checksum = "fdae9c00e61cc0579bcac625e8ad22104c60548a025bfc972dc83868a28e1484"
dependencies = [ dependencies = [
"crossbeam-channel", "crossbeam-channel",
"dpi", "dpi",
"gtk", "gtk",
"keyboard-types", "keyboard-types",
"libxdo", "libxdo",
"objc2 0.6.1", "objc2 0.5.2",
"objc2-app-kit 0.3.1", "objc2-app-kit 0.2.2",
"objc2-core-foundation", "objc2-foundation 0.2.2",
"objc2-foundation 0.3.1",
"once_cell", "once_cell",
"png", "png",
"thiserror 2.0.12", "thiserror 1.0.69",
"windows-sys 0.59.0", "windows-sys 0.59.0",
] ]
@@ -3541,15 +3512,6 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-src"
version = "300.5.1+3.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735230c832b28c000e3bc117119e6466a663ec73506bc0a9907ea4187508e42a"
dependencies = [
"cc",
]
[[package]] [[package]]
name = "openssl-sys" name = "openssl-sys"
version = "0.9.102" version = "0.9.102"
@@ -3558,7 +3520,6 @@ checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2"
dependencies = [ dependencies = [
"cc", "cc",
"libc", "libc",
"openssl-src",
"pkg-config", "pkg-config",
"vcpkg", "vcpkg",
] ]
@@ -4377,15 +4338,6 @@ dependencies = [
"digest", "digest",
] ]
[[package]]
name = "sharded-slab"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
dependencies = [
"lazy_static",
]
[[package]] [[package]]
name = "signal-hook-registry" name = "signal-hook-registry"
version = "1.4.2" version = "1.4.2"
@@ -4665,15 +4617,6 @@ dependencies = [
"syn 2.0.87", "syn 2.0.87",
] ]
[[package]]
name = "thread_local"
version = "1.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "time" name = "time"
version = "0.3.36" version = "0.3.36"
@@ -4950,33 +4893,11 @@ dependencies = [
"once_cell", "once_cell",
] ]
[[package]]
name = "tracing-subscriber"
version = "0.3.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008"
dependencies = [
"sharded-slab",
"thread_local",
"tracing-core",
]
[[package]]
name = "tracing-wasm"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4575c663a174420fa2d78f4108ff68f65bf2fbb7dd89f33749b6e826b3626e07"
dependencies = [
"tracing",
"tracing-subscriber",
"wasm-bindgen",
]
[[package]] [[package]]
name = "tray-icon" name = "tray-icon"
version = "0.21.0" version = "0.19.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da75ec677957aa21f6e0b361df0daab972f13a5bee3606de0638fd4ee1c666a" checksum = "eadd75f5002e2513eaa19b2365f533090cc3e93abd38788452d9ea85cff7b48a"
dependencies = [ dependencies = [
"crossbeam-channel", "crossbeam-channel",
"dirs 6.0.0", "dirs 6.0.0",

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "khm" name = "khm"
version = "0.7.1" version = "0.7.0"
edition = "2021" edition = "2021"
authors = ["AB <ab@hexor.cy>"] authors = ["AB <ab@hexor.cy>"]
description = "KHM - Known Hosts Manager for SSH key management and synchronization" description = "KHM - Known Hosts Manager for SSH key management and synchronization"
@@ -10,71 +10,35 @@ license = "WTFPL"
keywords = ["ssh", "known-hosts", "security", "system-admin", "automation"] keywords = ["ssh", "known-hosts", "security", "system-admin", "automation"]
categories = ["command-line-utilities", "network-programming"] categories = ["command-line-utilities", "network-programming"]
[lib]
crate-type = ["cdylib", "rlib"]
[[bin]]
name = "khm"
path = "src/bin/cli.rs"
[[bin]]
name = "khm-desktop"
path = "src/bin/desktop.rs"
required-features = ["gui"]
[dependencies] [dependencies]
actix-web = { version = "4", optional = true } actix-web = "4"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
log = "0.4" log = "0.4"
regex = { version = "1.10.5", optional = true } regex = "1.10.5"
base64 = { version = "0.21", optional = true } base64 = "0.21"
tokio = { version = "1", features = ["full", "sync"], optional = true } tokio = { version = "1", features = ["full", "sync"] }
tokio-postgres = { version = "0.7", features = ["with-chrono-0_4"], optional = true } tokio-postgres = { version = "0.7", features = ["with-chrono-0_4"] }
tokio-util = { version = "0.7", features = ["codec"], optional = true } tokio-util = { version = "0.7", features = ["codec"] }
clap = { version = "4", features = ["derive"], optional = true } clap = { version = "4", features = ["derive"] }
chrono = { version = "0.4.38", features = ["serde"], optional = true } chrono = "0.4.38"
reqwest = { version = "0.12", features = ["json"], optional = true } reqwest = { version = "0.12", features = ["json"] }
trust-dns-resolver = { version = "0.23", optional = true } trust-dns-resolver = "0.23"
futures = { version = "0.3", optional = true } futures = "0.3"
hostname = { version = "0.3", optional = true } hostname = "0.3"
rust-embed = { version = "8.0", optional = true } rust-embed = "8.0"
tray-icon = { version = "0.21", optional = true } tray-icon = { version = "0.19", optional = true }
notify = { version = "6.1", optional = true } notify = { version = "6.1", optional = true }
notify-debouncer-mini = { version = "0.4", optional = true } notify-debouncer-mini = { version = "0.4", optional = true }
dirs = "5.0" dirs = "5.0"
eframe = { version = "0.29", optional = true } eframe = { version = "0.29", optional = true }
egui = { version = "0.29", optional = true } egui = { version = "0.29", optional = true }
wasm-bindgen-futures = { version = "0.4", optional = true }
web-sys = { version = "0.3", optional = true }
wasm-bindgen = { version = "0.2", optional = true }
console_error_panic_hook = { version = "0.1", optional = true }
tracing-wasm = { version = "0.2", optional = true }
getrandom = { version = "0.2", features = ["js"], optional = true }
winit = { version = "0.30", optional = true } winit = { version = "0.30", optional = true }
env_logger = "0.11" env_logger = "0.11"
urlencoding = "2.1" urlencoding = "2.1"
# Linux-specific dependencies for GTK tray support
[target.'cfg(target_os = "linux")'.dependencies]
gtk = { version = "0.18", optional = true }
glib = { version = "0.18", optional = true }
[features] [features]
default = ["server", "web", "gui"] default = ["gui"]
cli = ["server", "web", "web-gui"] gui = ["tray-icon", "eframe", "egui", "winit", "notify", "notify-debouncer-mini"]
desktop = ["gui"] server = []
gui = ["tray-icon", "eframe", "egui", "winit", "notify", "notify-debouncer-mini", "gtk", "glib"]
web-gui = ["egui", "eframe", "wasm-bindgen-futures", "web-sys", "wasm-bindgen", "console_error_panic_hook", "tracing-wasm", "getrandom"]
web-gui-wasm = ["web-gui"]
server = ["actix-web", "tokio", "tokio-postgres", "tokio-util", "clap", "chrono", "regex", "base64", "futures", "hostname", "rust-embed", "trust-dns-resolver", "reqwest"]
web = ["server"]
# Target-specific dependencies for cross-compilation
[target.aarch64-unknown-linux-gnu.dependencies]
openssl = { version = "0.10", features = ["vendored"] }
# WASM-specific dependencies
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = { version = "0.2", features = ["js"] }

View File

@@ -1,19 +1,5 @@
# syntax=docker/dockerfile:1 # syntax=docker/dockerfile:1
FROM debian:12-slim FROM alpine:latest
COPY khm /usr/local/bin/khm
# Install only essential runtime dependencies ENTRYPOINT ["/usr/local/bin/khm"]
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Copy the CLI binary (without GUI dependencies)
ARG TARGETARCH
COPY bin/linux_${TARGETARCH}/khm /usr/local/bin/khm
RUN chmod +x /usr/local/bin/khm
# Create non-root user
RUN useradd -m -u 1000 khm
USER khm
ENTRYPOINT ["/usr/local/bin/khm"]

175
README.MD
View File

@@ -1,166 +1,65 @@
# KHM - Known Hosts Manager # KHM - Known Hosts Manager
KHM is a comprehensive SSH key management tool that allows you to synchronize `known_hosts` files across multiple hosts and environments. The application supports multiple operation modes: server mode for centralized key storage, client mode for synchronization, and GUI mode for easy management. KHM allows you to synchronize the `known_hosts` file across multiple hosts. This application manages SSH keys and flows, either as a server or client. In server mode, it stores keys and flows in a PostgreSQL database. In client mode, it sends keys to the server and can update the `known_hosts` file with keys from the server.
## Features ## Features
- **Multi-mode operation**: Server, client, and GUI modes - Synchronize `known_hosts` file across multiple hosts.
- **Centralized key management**: Store SSH keys and flows in PostgreSQL database - Manage SSH keys and flows in a PostgreSQL database.
- **Cross-platform GUI**: Modern tray application with settings window - Operate in both server and client modes.
- **Automatic synchronization**: Keep `known_hosts` files updated across environments - Automatically update `known_hosts` file with keys from the server.
- **Flow-based organization**: Manage different environments (production, staging, development)
- **Authentication support**: Basic authentication for secure API access
- **Real-time monitoring**: Auto-sync capabilities with configurable intervals
## Operation Modes ## Usage
### Server Mode ### Server Mode
Runs a web server that stores and manages SSH keys in a PostgreSQL database.
To run the application in server mode, use the following command:
```bash ```bash
khm --server --ip 0.0.0.0 --port 1337 --db-host psql.psql.svc --db-name khm --db-user admin --db-password <SECRET> --flows work,home khm --server --ip 127.0.0.1 --port 8080 --db-host 127.0.0.1 --db-name khm --db-user admin --db-password <SECRET> --flows work,home
``` ```
### Client Mode ### Client Mode
Connects to a KHM server to send local keys and optionally sync the `known_hosts` file.
To run the application in client mode, use the following command:
```bash ```bash
khm --host https://khm.example.com --flow work --known-hosts ~/.ssh/known_hosts --in-place khm --host http://khm.example.com:8080/<FLOW_NAME>/ --known-hosts ~/.ssh/known_hosts --in-place
``` ```
### GUI Mode ### Arguments
Launches a system tray application with a modern interface for easy management. Options:
- `--server` Run in server mode
- `--in-place` Server mode: Sync the known_hosts file with keys from the server
- `--flows <FLOWS>...` Server mode: Comma-separated list of flows to manage [default: default]
- `-i, --ip <IP>` Server mode: IP address to bind the server to [default: 127.0.0.1]
- `-p, --port <PORT>` Server mode: Port to bind the server to [default: 8080]
- `--db-host <DB_HOST>` Server mode: Hostname or IP address of the PostgreSQL database [default: 127.0.0.1]
- `--db-name <DB_NAME>` Server mode: Name of the PostgreSQL database [default: khm]
- `--db-user <DB_USER>` Server mode: Username for the PostgreSQL database
- `--db-password <DB_PASSWORD>` Server mode: Password for the PostgreSQL database
- `--basic-auth <BASIC_AUTH>` Client mode: Basic Auth credentials [default: ""]
- `--host <HOST>` Client mode: Full host address of the server to connect to. Like `https://khm.example.com/<FLOW_NAME>`
- `--known-hosts <KNOWN_HOSTS>` Client mode: Path to the known_hosts file [default: ~/.ssh/known_hosts]
```bash
# Run tray application
khm --gui
# Run settings window only
khm --settings-ui
```
## Command Line Arguments
### General Options
- `--server` - Run in server mode
- `--gui` - Run with GUI tray interface
- `--settings-ui` - Run settings UI window (used with --gui)
### Server Mode Options
- `-i, --ip <IP>` - IP address to bind the server to [default: 127.0.0.1]
- `-p, --port <PORT>` - Port to bind the server to [default: 8080]
- `--flows <FLOWS>` - Comma-separated list of flows to manage [default: default]
- `--db-host <DB_HOST>` - PostgreSQL database hostname [default: 127.0.0.1]
- `--db-name <DB_NAME>` - PostgreSQL database name [default: khm]
- `--db-user <DB_USER>` - PostgreSQL database username (required)
- `--db-password <DB_PASSWORD>` - PostgreSQL database password (required)
### Client Mode Options
- `--host <HOST>` - Server URL (e.g., https://khm.example.com) (required)
- `--flow <FLOW>` - Flow name to use on the server (required)
- `--known-hosts <PATH>` - Path to known_hosts file [default: ~/.ssh/known_hosts]
- `--in-place` - Update known_hosts file with server keys after sync
- `--basic-auth <CREDENTIALS>` - Basic authentication (format: user:pass)
## GUI Features
The GUI mode provides:
- **System Tray Integration**: Runs quietly in the system tray
- **Settings Management**: Easy configuration through modern UI
- **Connection Testing**: Built-in server connectivity testing
- **Manual Synchronization**: On-demand sync operations
- **Auto-sync Configuration**: Configurable automatic synchronization intervals
- **Operation Logging**: Real-time activity monitoring
- **Cross-platform Paths**: Automatic path handling for different operating systems
## Installation ## Installation
### From Binary Releases 1. Ensure you have Rust installed. If not, you can install it from [rustup.rs](https://rustup.rs/).
Download the latest binary from the [Releases](https://github.com/house-of-vanity/khm/releases) page.
### From Source
1. Install Rust from [rustup.rs](https://rustup.rs/)
2. Clone the repository: 2. Clone the repository:
```bash ```bash
git clone https://github.com/house-of-vanity/khm.git git clone https://github.com/house-of-vanity/khm.git
cd khm cd khm
``` ```
3. Build and run: 3. Run the project:
```bash ```bash
# Build both binaries (CLI without GUI, Desktop with GUI) cargo run --release -- --help
cargo build --release --bin khm --no-default-features --features cli ```
cargo build --release --bin khm-desktop
# Or build all at once with default features
cargo build --release
```
### System Dependencies
For GUI features on Linux:
```bash
# Build dependencies
sudo apt-get install libgtk-3-dev libglib2.0-dev libcairo2-dev libpango1.0-dev libatk1.0-dev libgdk-pixbuf2.0-dev
```
## Configuration
### GUI Configuration
Settings are automatically saved to:
- **Windows**: `%USERPROFILE%\.khm\khm_config.json`
- **macOS**: `~/.khm/khm_config.json`
- **Linux**: `~/.khm/khm_config.json`
### Example Configuration
```json
{
"host": "https://khm.example.com",
"flow": "production",
"known_hosts": "/home/user/.ssh/known_hosts",
"basic_auth": "",
"in_place": true,
"auto_sync_interval_minutes": 60
}
```
## Examples
### Complete Server Setup
```bash
# Start server with multiple flows
khm --server \
--ip 0.0.0.0 \
--port 8080 \
--db-host localhost \
--db-name khm \
--db-user khm_user \
--db-password secure_password \
--flows production,staging,development
```
### Client Synchronization
```bash
# Send keys and update local known_hosts
khm --host https://khm.company.com \
--flow production \
--known-hosts ~/.ssh/known_hosts \
--in-place \
--basic-auth "username:password"
```
### GUI Usage
```bash
# Launch tray application
khm --gui
# Open settings window directly
khm --settings-ui
```
## Contributing ## Contributing
Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests. Contributions are welcome! Please open an issue or submit a pull request for any changes.
## License ## License
This project is licensed under the WTFPL License - see the [LICENSE](LICENSE) file for details. This project is licensed under the WTFPL License.

View File

@@ -1,34 +0,0 @@
version: '3.8'
services:
khm:
image: ultradesu/khm:latest
restart: unless-stopped
environment:
# Server mode configuration
- KHM_SERVER=true
- KHM_IP=0.0.0.0
- KHM_PORT=8080
- KHM_DB_HOST=postgres
- KHM_DB_NAME=khm
- KHM_DB_USER=khm
- KHM_DB_PASSWORD=changeme
- KHM_FLOWS=prod,staging,dev
ports:
- "8080:8080"
depends_on:
- postgres
command: ["--server", "--ip", "0.0.0.0", "--port", "8080", "--db-host", "postgres", "--db-name", "khm", "--db-user", "khm", "--db-password", "changeme", "--flows", "prod,staging,dev"]
postgres:
image: postgres:16-alpine
restart: unless-stopped
environment:
- POSTGRES_USER=khm
- POSTGRES_PASSWORD=changeme
- POSTGRES_DB=khm
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:

2715
khm-wasm/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,24 +0,0 @@
[package]
name = "khm-wasm"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
log = "0.4"
eframe = { version = "0.29", default-features = false, features = ["glow"] }
egui = "0.29"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["console", "Headers", "Request", "RequestInit", "RequestMode", "Response", "Window"] }
console_error_panic_hook = "0.1"
tracing-wasm = "0.2"
getrandom = { version = "0.2", features = ["js"] }
serde-wasm-bindgen = "0.6"
[features]
default = []

File diff suppressed because it is too large Load Diff

View File

@@ -1,142 +0,0 @@
use khm::{gui, Args};
use clap::Parser;
use env_logger;
use log::{error, info};
/// Desktop version of KHM - Known Hosts Manager with GUI interface
/// Primarily runs in GUI mode with tray application and settings windows
#[derive(Parser, Debug, Clone)]
#[command(
author = env!("CARGO_PKG_AUTHORS"),
version = env!("CARGO_PKG_VERSION"),
about = "SSH Host Key Manager (Desktop)",
long_about = None,
after_help = "Examples:\n\
\n\
Running in GUI tray mode (default):\n\
khm-desktop\n\
\n\
Running in GUI tray mode with background daemon:\n\
khm-desktop --daemon\n\
\n\
Running settings window:\n\
khm-desktop --settings-ui\n\
\n\
"
)]
pub struct DesktopArgs {
/// Hide console window and run in background (default: auto when no arguments)
#[arg(long, help = "Hide console window and run in background")]
pub daemon: bool,
/// Run settings UI window
#[arg(long, help = "Run settings UI window")]
pub settings_ui: bool,
}
impl From<DesktopArgs> for Args {
fn from(desktop_args: DesktopArgs) -> Self {
Args {
server: false,
daemon: desktop_args.daemon,
settings_ui: desktop_args.settings_ui,
in_place: false,
flows: vec!["default".to_string()],
ip: "127.0.0.1".to_string(),
port: 8080,
db_host: "127.0.0.1".to_string(),
db_name: "khm".to_string(),
db_user: None,
db_password: None,
host: None,
flow: None,
known_hosts: "~/.ssh/known_hosts".to_string(),
basic_auth: String::new(),
}
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Configure logging to show only khm logs, filtering out noisy library logs
env_logger::Builder::from_default_env()
.filter_level(log::LevelFilter::Warn) // Default level for all modules
.filter_module("khm", log::LevelFilter::Debug) // Our app logs
.filter_module("winit", log::LevelFilter::Error) // Window management
.filter_module("egui", log::LevelFilter::Error) // GUI framework
.filter_module("eframe", log::LevelFilter::Error) // GUI framework
.filter_module("tray_icon", log::LevelFilter::Error) // Tray icon
.filter_module("wgpu", log::LevelFilter::Error) // Graphics
.filter_module("naga", log::LevelFilter::Error) // Graphics
.filter_module("glow", log::LevelFilter::Error) // Graphics
.filter_module("tracing", log::LevelFilter::Error) // Tracing spans
.init();
info!("Starting SSH Key Manager (Desktop)");
let desktop_args = DesktopArgs::parse();
let args: Args = desktop_args.into();
// Hide console on Windows if daemon flag is set
if args.daemon {
#[cfg(target_os = "windows")]
{
extern "system" {
fn FreeConsole() -> i32;
}
unsafe {
FreeConsole();
}
}
}
// Settings UI mode - just show settings window and exit
if args.settings_ui {
// Always hide console for settings window
#[cfg(target_os = "windows")]
{
extern "system" {
fn FreeConsole() -> i32;
}
unsafe {
FreeConsole();
}
}
#[cfg(feature = "gui")]
{
info!("Running settings UI window");
gui::run_settings_window();
return Ok(());
}
#[cfg(not(feature = "gui"))]
{
error!("GUI features not compiled. Install system dependencies and rebuild with --features gui");
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"GUI features not compiled",
));
}
}
// Default to GUI mode for desktop version
info!("Running in GUI mode");
#[cfg(feature = "gui")]
{
if let Err(e) = gui::run_gui().await {
error!("Failed to run GUI: {}", e);
}
}
#[cfg(not(feature = "gui"))]
{
error!("GUI features not compiled. Install system dependencies and rebuild with --features gui");
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"GUI features not compiled",
));
}
info!("Application has exited");
Ok(())
}

View File

@@ -69,12 +69,12 @@ impl DbClient {
.client .client
.query( .query(
"SELECT EXISTS ( "SELECT EXISTS (
SELECT FROM information_schema.tables SELECT FROM information_schema.tables
WHERE table_schema = 'public' WHERE table_schema = 'public'
AND table_name = 'keys' AND table_name = 'keys'
) AND EXISTS ( ) AND EXISTS (
SELECT FROM information_schema.tables SELECT FROM information_schema.tables
WHERE table_schema = 'public' WHERE table_schema = 'public'
AND table_name = 'flows' AND table_name = 'flows'
)", )",
&[], &[],
@@ -144,9 +144,9 @@ impl DbClient {
.client .client
.query( .query(
"SELECT EXISTS ( "SELECT EXISTS (
SELECT FROM information_schema.columns SELECT FROM information_schema.columns
WHERE table_schema = 'public' WHERE table_schema = 'public'
AND table_name = 'keys' AND table_name = 'keys'
AND column_name = 'deprecated' AND column_name = 'deprecated'
)", )",
&[], &[],
@@ -448,9 +448,9 @@ impl DbClient {
let result = self let result = self
.client .client
.execute( .execute(
"UPDATE public.keys "UPDATE public.keys
SET deprecated = TRUE, updated = NOW() SET deprecated = TRUE, updated = NOW()
WHERE host = $1 WHERE host = $1
AND key_id IN ( AND key_id IN (
SELECT key_id FROM public.flows WHERE name = $2 SELECT key_id FROM public.flows WHERE name = $2
)", )",
@@ -480,9 +480,9 @@ impl DbClient {
let result = self let result = self
.client .client
.execute( .execute(
"UPDATE public.keys "UPDATE public.keys
SET deprecated = TRUE, updated = NOW() SET deprecated = TRUE, updated = NOW()
WHERE host = ANY($1) WHERE host = ANY($1)
AND key_id IN ( AND key_id IN (
SELECT key_id FROM public.flows WHERE name = $2 SELECT key_id FROM public.flows WHERE name = $2
)", )",
@@ -493,9 +493,7 @@ impl DbClient {
info!( info!(
"Bulk deprecated {} key(s) for {} servers in flow '{}'", "Bulk deprecated {} key(s) for {} servers in flow '{}'",
affected, affected, server_names.len(), flow_name
server_names.len(),
flow_name
); );
Ok(affected) Ok(affected)
@@ -514,9 +512,9 @@ impl DbClient {
let result = self let result = self
.client .client
.execute( .execute(
"UPDATE public.keys "UPDATE public.keys
SET deprecated = FALSE, updated = NOW() SET deprecated = FALSE, updated = NOW()
WHERE host = ANY($1) WHERE host = ANY($1)
AND deprecated = TRUE AND deprecated = TRUE
AND key_id IN ( AND key_id IN (
SELECT key_id FROM public.flows WHERE name = $2 SELECT key_id FROM public.flows WHERE name = $2
@@ -528,9 +526,7 @@ impl DbClient {
info!( info!(
"Bulk restored {} key(s) for {} servers in flow '{}'", "Bulk restored {} key(s) for {} servers in flow '{}'",
affected, affected, server_names.len(), flow_name
server_names.len(),
flow_name
); );
Ok(affected) Ok(affected)
@@ -545,9 +541,9 @@ impl DbClient {
let result = self let result = self
.client .client
.execute( .execute(
"UPDATE public.keys "UPDATE public.keys
SET deprecated = FALSE, updated = NOW() SET deprecated = FALSE, updated = NOW()
WHERE host = $1 WHERE host = $1
AND deprecated = TRUE AND deprecated = TRUE
AND key_id IN ( AND key_id IN (
SELECT key_id FROM public.flows WHERE name = $2 SELECT key_id FROM public.flows WHERE name = $2
@@ -574,8 +570,8 @@ impl DbClient {
let result = self let result = self
.client .client
.query( .query(
"SELECT k.key_id FROM public.keys k "SELECT k.key_id FROM public.keys k
INNER JOIN public.flows f ON k.key_id = f.key_id INNER JOIN public.flows f ON k.key_id = f.key_id
WHERE k.host = $1 AND f.name = $2", WHERE k.host = $1 AND f.name = $2",
&[&server_name, &flow_name], &[&server_name, &flow_name],
) )

View File

@@ -1,9 +1,5 @@
#[cfg(feature = "gui")]
mod state; mod state;
#[cfg(feature = "gui")]
mod ui; mod ui;
#[cfg(feature = "gui")]
pub use state::*; pub use state::*;
#[cfg(feature = "gui")]
pub use ui::*; pub use ui::*;

View File

@@ -1,15 +1,15 @@
use crate::gui::api::{fetch_keys, SshKey};
use crate::gui::common::KhmSettings;
use eframe::egui; use eframe::egui;
use log::{error, info}; use log::{error, info};
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::mpsc; use std::sync::mpsc;
use crate::gui::api::{SshKey, fetch_keys};
use crate::gui::common::KhmSettings;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum AdminOperation { pub enum AdminOperation {
LoadingKeys, LoadingKeys,
DeprecatingKey, DeprecatingKey,
RestoringKey, RestoringKey,
DeletingKey, DeletingKey,
BulkDeprecating, BulkDeprecating,
BulkRestoring, BulkRestoring,
@@ -47,54 +47,52 @@ impl AdminState {
/// Filter keys based on current search term and deprecated filter /// Filter keys based on current search term and deprecated filter
pub fn filter_keys(&mut self) { pub fn filter_keys(&mut self) {
let mut filtered = self.keys.clone(); let mut filtered = self.keys.clone();
// Apply deprecated filter // Apply deprecated filter
if self.show_deprecated_only { if self.show_deprecated_only {
filtered.retain(|key| key.deprecated); filtered.retain(|key| key.deprecated);
} }
// Apply search filter // Apply search filter
if !self.search_term.is_empty() { if !self.search_term.is_empty() {
let search_term = self.search_term.to_lowercase(); let search_term = self.search_term.to_lowercase();
filtered.retain(|key| { filtered.retain(|key| {
key.server.to_lowercase().contains(&search_term) key.server.to_lowercase().contains(&search_term) ||
|| key.public_key.to_lowercase().contains(&search_term) key.public_key.to_lowercase().contains(&search_term)
}); });
} }
self.filtered_keys = filtered; self.filtered_keys = filtered;
} }
/// Load keys from server /// Load keys from server
pub fn load_keys( pub fn load_keys(&mut self, settings: &KhmSettings, ctx: &egui::Context) -> Option<mpsc::Receiver<Result<Vec<SshKey>, String>>> {
&mut self,
settings: &KhmSettings,
ctx: &egui::Context,
) -> Option<mpsc::Receiver<Result<Vec<SshKey>, String>>> {
if settings.host.is_empty() || settings.flow.is_empty() { if settings.host.is_empty() || settings.flow.is_empty() {
return None; return None;
} }
self.current_operation = AdminOperation::LoadingKeys; self.current_operation = AdminOperation::LoadingKeys;
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
let host = settings.host.clone(); let host = settings.host.clone();
let flow = settings.flow.clone(); let flow = settings.flow.clone();
let basic_auth = settings.basic_auth.clone(); let basic_auth = settings.basic_auth.clone();
let ctx_clone = ctx.clone(); let ctx_clone = ctx.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async { fetch_keys(host, flow, basic_auth).await }); let result = rt.block_on(async {
fetch_keys(host, flow, basic_auth).await
});
let _ = tx.send(result); let _ = tx.send(result);
ctx_clone.request_repaint(); ctx_clone.request_repaint();
}); });
Some(rx) Some(rx)
} }
/// Handle keys load result /// Handle keys load result
pub fn handle_keys_loaded(&mut self, result: Result<Vec<SshKey>, String>) { pub fn handle_keys_loaded(&mut self, result: Result<Vec<SshKey>, String>) {
match result { match result {
@@ -111,7 +109,7 @@ impl AdminState {
} }
} }
} }
/// Get selected servers list /// Get selected servers list
pub fn get_selected_servers(&self) -> Vec<String> { pub fn get_selected_servers(&self) -> Vec<String> {
self.selected_servers self.selected_servers
@@ -119,24 +117,19 @@ impl AdminState {
.filter_map(|(server, &selected)| if selected { Some(server.clone()) } else { None }) .filter_map(|(server, &selected)| if selected { Some(server.clone()) } else { None })
.collect() .collect()
} }
/// Clear selected servers /// Clear selected servers
pub fn clear_selection(&mut self) { pub fn clear_selection(&mut self) {
self.selected_servers.clear(); self.selected_servers.clear();
} }
/// Get statistics /// Get statistics
pub fn get_statistics(&self) -> AdminStatistics { pub fn get_statistics(&self) -> AdminStatistics {
let total_keys = self.keys.len(); let total_keys = self.keys.len();
let active_keys = self.keys.iter().filter(|k| !k.deprecated).count(); let active_keys = self.keys.iter().filter(|k| !k.deprecated).count();
let deprecated_keys = total_keys - active_keys; let deprecated_keys = total_keys - active_keys;
let unique_servers = self let unique_servers = self.keys.iter().map(|k| &k.server).collect::<std::collections::HashSet<_>>().len();
.keys
.iter()
.map(|k| &k.server)
.collect::<std::collections::HashSet<_>>()
.len();
AdminStatistics { AdminStatistics {
total_keys, total_keys,
active_keys, active_keys,

View File

@@ -1,81 +1,46 @@
use super::state::{get_key_preview, get_key_type, AdminState};
use crate::gui::api::SshKey;
use eframe::egui; use eframe::egui;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use super::state::{AdminState, get_key_type, get_key_preview};
use crate::gui::api::SshKey;
/// Render statistics cards /// Render statistics cards
pub fn render_statistics(ui: &mut egui::Ui, admin_state: &AdminState) { pub fn render_statistics(ui: &mut egui::Ui, admin_state: &AdminState) {
let stats = admin_state.get_statistics(); let stats = admin_state.get_statistics();
ui.group(|ui| { ui.group(|ui| {
ui.set_min_width(ui.available_width()); ui.set_min_width(ui.available_width());
ui.vertical(|ui| { ui.vertical(|ui| {
ui.label(egui::RichText::new("📊 Statistics").size(16.0).strong()); ui.label(egui::RichText::new("📊 Statistics").size(16.0).strong());
ui.add_space(8.0); ui.add_space(8.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.columns(4, |cols| { ui.columns(4, |cols| {
// Total keys // Total keys
cols[0].vertical_centered_justified(|ui| { cols[0].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("📊").size(20.0)); ui.label(egui::RichText::new("📊").size(20.0));
ui.label( ui.label(egui::RichText::new(stats.total_keys.to_string()).size(24.0).strong());
egui::RichText::new(stats.total_keys.to_string()) ui.label(egui::RichText::new("Total Keys").size(11.0).color(egui::Color32::GRAY));
.size(24.0)
.strong(),
);
ui.label(
egui::RichText::new("Total Keys")
.size(11.0)
.color(egui::Color32::GRAY),
);
}); });
// Active keys // Active keys
cols[1].vertical_centered_justified(|ui| { cols[1].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("").size(20.0)); ui.label(egui::RichText::new("").size(20.0));
ui.label( ui.label(egui::RichText::new(stats.active_keys.to_string()).size(24.0).strong().color(egui::Color32::LIGHT_GREEN));
egui::RichText::new(stats.active_keys.to_string()) ui.label(egui::RichText::new("Active").size(11.0).color(egui::Color32::GRAY));
.size(24.0)
.strong()
.color(egui::Color32::LIGHT_GREEN),
);
ui.label(
egui::RichText::new("Active")
.size(11.0)
.color(egui::Color32::GRAY),
);
}); });
// Deprecated keys // Deprecated keys
cols[2].vertical_centered_justified(|ui| { cols[2].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("").size(20.0)); ui.label(egui::RichText::new("").size(20.0));
ui.label( ui.label(egui::RichText::new(stats.deprecated_keys.to_string()).size(24.0).strong().color(egui::Color32::LIGHT_RED));
egui::RichText::new(stats.deprecated_keys.to_string()) ui.label(egui::RichText::new("Deprecated").size(11.0).color(egui::Color32::GRAY));
.size(24.0)
.strong()
.color(egui::Color32::LIGHT_RED),
);
ui.label(
egui::RichText::new("Deprecated")
.size(11.0)
.color(egui::Color32::GRAY),
);
}); });
// Servers // Servers
cols[3].vertical_centered_justified(|ui| { cols[3].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("💻").size(20.0)); ui.label(egui::RichText::new("💻").size(20.0));
ui.label( ui.label(egui::RichText::new(stats.unique_servers.to_string()).size(24.0).strong().color(egui::Color32::LIGHT_BLUE));
egui::RichText::new(stats.unique_servers.to_string()) ui.label(egui::RichText::new("Servers").size(11.0).color(egui::Color32::GRAY));
.size(24.0)
.strong()
.color(egui::Color32::LIGHT_BLUE),
);
ui.label(
egui::RichText::new("Servers")
.size(11.0)
.color(egui::Color32::GRAY),
);
}); });
}); });
}); });
@@ -86,59 +51,45 @@ pub fn render_statistics(ui: &mut egui::Ui, admin_state: &AdminState) {
/// Render search and filter controls /// Render search and filter controls
pub fn render_search_controls(ui: &mut egui::Ui, admin_state: &mut AdminState) -> bool { pub fn render_search_controls(ui: &mut egui::Ui, admin_state: &mut AdminState) -> bool {
let mut changed = false; let mut changed = false;
ui.group(|ui| { ui.group(|ui| {
ui.set_min_width(ui.available_width()); ui.set_min_width(ui.available_width());
ui.vertical(|ui| { ui.vertical(|ui| {
ui.label(egui::RichText::new("🔍 Search").size(16.0).strong()); ui.label(egui::RichText::new("🔍 Search").size(16.0).strong());
ui.add_space(8.0); ui.add_space(8.0);
// Search field with full width // Search field with full width
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label(egui::RichText::new("🔍").size(14.0)); ui.label(egui::RichText::new("🔍").size(14.0));
let search_response = ui.add_sized( let search_response = ui.add_sized(
[ui.available_width() * 0.6, 20.0], [ui.available_width() * 0.6, 20.0],
egui::TextEdit::singleline(&mut admin_state.search_term) egui::TextEdit::singleline(&mut admin_state.search_term)
.hint_text("Search servers or keys..."), .hint_text("Search servers or keys...")
); );
if admin_state.search_term.is_empty() { if admin_state.search_term.is_empty() {
ui.label( ui.label(egui::RichText::new("Type to search").size(11.0).color(egui::Color32::GRAY));
egui::RichText::new("Type to search")
.size(11.0)
.color(egui::Color32::GRAY),
);
} else { } else {
ui.label( ui.label(egui::RichText::new(format!("{} results", admin_state.filtered_keys.len())).size(11.0));
egui::RichText::new(format!("{} results", admin_state.filtered_keys.len())) if ui.add(egui::Button::new(egui::RichText::new("").color(egui::Color32::WHITE))
.size(11.0), .fill(egui::Color32::from_rgb(170, 170, 170))
); .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(89, 89, 89)))
if ui .rounding(egui::Rounding::same(3.0))
.add( .min_size(egui::vec2(18.0, 18.0))
egui::Button::new( ).on_hover_text("Clear search").clicked() {
egui::RichText::new("").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(170, 170, 170))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(89, 89, 89)))
.rounding(egui::Rounding::same(3.0))
.min_size(egui::vec2(18.0, 18.0)),
)
.on_hover_text("Clear search")
.clicked()
{
admin_state.search_term.clear(); admin_state.search_term.clear();
changed = true; changed = true;
} }
} }
// Handle search text changes // Handle search text changes
if search_response.changed() { if search_response.changed() {
changed = true; changed = true;
} }
}); });
ui.add_space(5.0); ui.add_space(5.0);
// Filter controls // Filter controls
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("Filter:"); ui.label("Filter:");
@@ -147,104 +98,76 @@ pub fn render_search_controls(ui: &mut egui::Ui, admin_state: &mut AdminState) -
admin_state.show_deprecated_only = false; admin_state.show_deprecated_only = false;
changed = true; changed = true;
} }
if ui if ui.selectable_label(show_deprecated, "❗ Deprecated").clicked() {
.selectable_label(show_deprecated, "❗ Deprecated")
.clicked()
{
admin_state.show_deprecated_only = true; admin_state.show_deprecated_only = true;
changed = true; changed = true;
} }
}); });
}); });
}); });
if changed { if changed {
admin_state.filter_keys(); admin_state.filter_keys();
} }
changed changed
} }
/// Render bulk actions controls /// Render bulk actions controls
pub fn render_bulk_actions(ui: &mut egui::Ui, admin_state: &mut AdminState) -> BulkAction { pub fn render_bulk_actions(ui: &mut egui::Ui, admin_state: &mut AdminState) -> BulkAction {
let selected_count = admin_state let selected_count = admin_state.selected_servers.values().filter(|&&v| v).count();
.selected_servers
.values()
.filter(|&&v| v)
.count();
if selected_count == 0 { if selected_count == 0 {
return BulkAction::None; return BulkAction::None;
} }
let mut action = BulkAction::None; let mut action = BulkAction::None;
ui.group(|ui| { ui.group(|ui| {
ui.set_min_width(ui.available_width()); ui.set_min_width(ui.available_width());
ui.vertical(|ui| { ui.vertical(|ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label(egui::RichText::new("📋").size(14.0)); ui.label(egui::RichText::new("📋").size(14.0));
ui.label( ui.label(egui::RichText::new(format!("Selected {} servers", selected_count))
egui::RichText::new(format!("Selected {} servers", selected_count)) .size(14.0)
.size(14.0) .strong()
.strong() .color(egui::Color32::LIGHT_BLUE));
.color(egui::Color32::LIGHT_BLUE),
);
}); });
ui.add_space(5.0); ui.add_space(5.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui if ui.add(egui::Button::new(egui::RichText::new("❗ Deprecate Selected").color(egui::Color32::BLACK))
.add( .fill(egui::Color32::from_rgb(255, 200, 0))
egui::Button::new( .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(102, 94, 72)))
egui::RichText::new("❗ Deprecate Selected") .rounding(egui::Rounding::same(6.0))
.color(egui::Color32::BLACK), .min_size(egui::vec2(130.0, 28.0))
) ).clicked() {
.fill(egui::Color32::from_rgb(255, 200, 0))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(102, 94, 72)))
.rounding(egui::Rounding::same(6.0))
.min_size(egui::vec2(130.0, 28.0)),
)
.clicked()
{
action = BulkAction::DeprecateSelected; action = BulkAction::DeprecateSelected;
} }
if ui if ui.add(egui::Button::new(egui::RichText::new("✅ Restore Selected").color(egui::Color32::WHITE))
.add( .fill(egui::Color32::from_rgb(101, 199, 40))
egui::Button::new( .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(94, 105, 25)))
egui::RichText::new("✅ Restore Selected").color(egui::Color32::WHITE), .rounding(egui::Rounding::same(6.0))
) .min_size(egui::vec2(120.0, 28.0))
.fill(egui::Color32::from_rgb(101, 199, 40)) ).clicked() {
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(94, 105, 25)))
.rounding(egui::Rounding::same(6.0))
.min_size(egui::vec2(120.0, 28.0)),
)
.clicked()
{
action = BulkAction::RestoreSelected; action = BulkAction::RestoreSelected;
} }
if ui if ui.add(egui::Button::new(egui::RichText::new("X Clear Selection").color(egui::Color32::WHITE))
.add( .fill(egui::Color32::from_rgb(170, 170, 170))
egui::Button::new( .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(89, 89, 89)))
egui::RichText::new("X Clear Selection").color(egui::Color32::WHITE), .rounding(egui::Rounding::same(6.0))
) .min_size(egui::vec2(110.0, 28.0))
.fill(egui::Color32::from_rgb(170, 170, 170)) ).clicked() {
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(89, 89, 89)))
.rounding(egui::Rounding::same(6.0))
.min_size(egui::vec2(110.0, 28.0)),
)
.clicked()
{
admin_state.clear_selection(); admin_state.clear_selection();
action = BulkAction::ClearSelection; action = BulkAction::ClearSelection;
} }
}); });
}); });
}); });
action action
} }
@@ -254,136 +177,86 @@ pub fn render_keys_table(ui: &mut egui::Ui, admin_state: &mut AdminState) -> Key
render_empty_state(ui, admin_state); render_empty_state(ui, admin_state);
return KeyAction::None; return KeyAction::None;
} }
let mut action = KeyAction::None; let mut action = KeyAction::None;
// Group keys by server // Group keys by server
let mut servers: BTreeMap<String, Vec<SshKey>> = BTreeMap::new(); let mut servers: BTreeMap<String, Vec<SshKey>> = BTreeMap::new();
for key in &admin_state.filtered_keys { for key in &admin_state.filtered_keys {
servers servers.entry(key.server.clone()).or_insert_with(Vec::new).push(key.clone());
.entry(key.server.clone())
.or_insert_with(Vec::new)
.push(key.clone());
} }
// Render each server group // Render each server group
for (server_name, server_keys) in servers { for (server_name, server_keys) in servers {
let is_expanded = admin_state let is_expanded = admin_state.expanded_servers.get(&server_name).copied().unwrap_or(false);
.expanded_servers
.get(&server_name)
.copied()
.unwrap_or(false);
let active_count = server_keys.iter().filter(|k| !k.deprecated).count(); let active_count = server_keys.iter().filter(|k| !k.deprecated).count();
let deprecated_count = server_keys.len() - active_count; let deprecated_count = server_keys.len() - active_count;
// Server header // Server header
ui.group(|ui| { ui.group(|ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
// Server selection checkbox // Server selection checkbox
let mut selected = admin_state let mut selected = admin_state.selected_servers.get(&server_name).copied().unwrap_or(false);
.selected_servers if ui.add(egui::Checkbox::new(&mut selected, "")
.get(&server_name) .indeterminate(false)
.copied() ).changed() {
.unwrap_or(false); admin_state.selected_servers.insert(server_name.clone(), selected);
if ui
.add(egui::Checkbox::new(&mut selected, "").indeterminate(false))
.changed()
{
admin_state
.selected_servers
.insert(server_name.clone(), selected);
} }
// Expand/collapse button // Expand/collapse button
let expand_icon = if is_expanded { "-" } else { "+" }; let expand_icon = if is_expanded { "" } else { "" };
if ui if ui.add(egui::Button::new(expand_icon)
.add( .fill(egui::Color32::TRANSPARENT)
egui::Button::new(expand_icon) .stroke(egui::Stroke::NONE)
.fill(egui::Color32::TRANSPARENT) .min_size(egui::vec2(20.0, 20.0))
.stroke(egui::Stroke::NONE) ).clicked() {
.min_size(egui::vec2(20.0, 20.0)), admin_state.expanded_servers.insert(server_name.clone(), !is_expanded);
)
.clicked()
{
admin_state
.expanded_servers
.insert(server_name.clone(), !is_expanded);
} }
// Server icon and name // Server icon and name
ui.label(egui::RichText::new("💻").size(16.0)); ui.label(egui::RichText::new("💻").size(16.0));
ui.label( ui.label(egui::RichText::new(&server_name)
egui::RichText::new(&server_name) .size(15.0)
.size(15.0) .strong()
.strong() .color(egui::Color32::WHITE));
.color(egui::Color32::WHITE),
);
// Keys count badge // Keys count badge
render_badge( render_badge(ui, &format!("{} keys", server_keys.len()), egui::Color32::from_rgb(52, 152, 219), egui::Color32::WHITE);
ui,
&format!("{} keys", server_keys.len()),
egui::Color32::from_rgb(52, 152, 219),
egui::Color32::WHITE,
);
ui.add_space(5.0); ui.add_space(5.0);
// Deprecated count badge // Deprecated count badge
if deprecated_count > 0 { if deprecated_count > 0 {
render_badge( render_badge(ui, &format!("{} depr", deprecated_count), egui::Color32::from_rgb(231, 76, 60), egui::Color32::WHITE);
ui,
&format!("{} depr", deprecated_count),
egui::Color32::from_rgb(231, 76, 60),
egui::Color32::WHITE,
);
} }
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Server action buttons // Server action buttons
if deprecated_count > 0 { if deprecated_count > 0 {
if ui if ui.add(egui::Button::new(egui::RichText::new("✅ Restore").color(egui::Color32::WHITE))
.add( .fill(egui::Color32::from_rgb(101, 199, 40))
egui::Button::new( .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(94, 105, 25)))
egui::RichText::new("✅ Restore").color(egui::Color32::WHITE), .rounding(egui::Rounding::same(4.0))
) .min_size(egui::vec2(70.0, 24.0))
.fill(egui::Color32::from_rgb(101, 199, 40)) ).clicked() {
.stroke(egui::Stroke::new(
1.0,
egui::Color32::from_rgb(94, 105, 25),
))
.rounding(egui::Rounding::same(4.0))
.min_size(egui::vec2(70.0, 24.0)),
)
.clicked()
{
action = KeyAction::RestoreServer(server_name.clone()); action = KeyAction::RestoreServer(server_name.clone());
} }
} }
if active_count > 0 { if active_count > 0 {
if ui if ui.add(egui::Button::new(egui::RichText::new("❗ Deprecate").color(egui::Color32::BLACK))
.add( .fill(egui::Color32::from_rgb(255, 200, 0))
egui::Button::new( .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(102, 94, 72)))
egui::RichText::new("❗ Deprecate").color(egui::Color32::BLACK), .rounding(egui::Rounding::same(4.0))
) .min_size(egui::vec2(85.0, 24.0))
.fill(egui::Color32::from_rgb(255, 200, 0)) ).clicked() {
.stroke(egui::Stroke::new(
1.0,
egui::Color32::from_rgb(102, 94, 72),
))
.rounding(egui::Rounding::same(4.0))
.min_size(egui::vec2(85.0, 24.0)),
)
.clicked()
{
action = KeyAction::DeprecateServer(server_name.clone()); action = KeyAction::DeprecateServer(server_name.clone());
} }
} }
}); });
}); });
}); });
// Expanded key details // Expanded key details
if is_expanded { if is_expanded {
ui.indent("server_keys", |ui| { ui.indent("server_keys", |ui| {
@@ -394,10 +267,10 @@ pub fn render_keys_table(ui: &mut egui::Ui, admin_state: &mut AdminState) -> Key
} }
}); });
} }
ui.add_space(5.0); ui.add_space(5.0);
} }
action action
} }
@@ -406,56 +279,29 @@ fn render_empty_state(ui: &mut egui::Ui, admin_state: &AdminState) {
ui.vertical_centered(|ui| { ui.vertical_centered(|ui| {
ui.add_space(60.0); ui.add_space(60.0);
if admin_state.keys.is_empty() { if admin_state.keys.is_empty() {
ui.label( ui.label(egui::RichText::new("🔑").size(48.0).color(egui::Color32::GRAY));
egui::RichText::new("🔑") ui.label(egui::RichText::new("No SSH keys available")
.size(48.0) .size(18.0)
.color(egui::Color32::GRAY), .color(egui::Color32::GRAY));
); ui.label(egui::RichText::new("Keys will appear here once loaded from the server")
ui.label(
egui::RichText::new("No SSH keys available")
.size(18.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("Keys will appear here once loaded from the server")
.size(14.0)
.color(egui::Color32::DARK_GRAY),
);
} else if !admin_state.search_term.is_empty() {
ui.label(
egui::RichText::new("🔍")
.size(48.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("No results found")
.size(18.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new(format!(
"Try adjusting your search: '{}'",
admin_state.search_term
))
.size(14.0) .size(14.0)
.color(egui::Color32::DARK_GRAY), .color(egui::Color32::DARK_GRAY));
); } else if !admin_state.search_term.is_empty() {
ui.label(egui::RichText::new("🔍").size(48.0).color(egui::Color32::GRAY));
ui.label(egui::RichText::new("No results found")
.size(18.0)
.color(egui::Color32::GRAY));
ui.label(egui::RichText::new(format!("Try adjusting your search: '{}'", admin_state.search_term))
.size(14.0)
.color(egui::Color32::DARK_GRAY));
} else { } else {
ui.label( ui.label(egui::RichText::new("").size(48.0).color(egui::Color32::GRAY));
egui::RichText::new("") ui.label(egui::RichText::new("No keys match current filters")
.size(48.0) .size(18.0)
.color(egui::Color32::GRAY), .color(egui::Color32::GRAY));
); ui.label(egui::RichText::new("Try adjusting your search or filter settings")
ui.label( .size(14.0)
egui::RichText::new("No keys match current filters") .color(egui::Color32::DARK_GRAY));
.size(18.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("Try adjusting your search or filter settings")
.size(14.0)
.color(egui::Color32::DARK_GRAY),
);
} }
}); });
} }
@@ -463,7 +309,7 @@ fn render_empty_state(ui: &mut egui::Ui, admin_state: &AdminState) {
/// Render individual key item /// Render individual key item
fn render_key_item(ui: &mut egui::Ui, key: &SshKey, server_name: &str) -> Option<KeyAction> { fn render_key_item(ui: &mut egui::Ui, key: &SshKey, server_name: &str) -> Option<KeyAction> {
let mut action = None; let mut action = None;
ui.group(|ui| { ui.group(|ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
// Key type badge // Key type badge
@@ -475,112 +321,86 @@ fn render_key_item(ui: &mut egui::Ui, key: &SshKey, server_name: &str) -> Option
"DSA" => (egui::Color32::from_rgb(230, 126, 34), egui::Color32::WHITE), "DSA" => (egui::Color32::from_rgb(230, 126, 34), egui::Color32::WHITE),
_ => (egui::Color32::GRAY, egui::Color32::WHITE), _ => (egui::Color32::GRAY, egui::Color32::WHITE),
}; };
render_small_badge(ui, &key_type, badge_color, text_color); render_small_badge(ui, &key_type, badge_color, text_color);
ui.add_space(5.0); ui.add_space(5.0);
// Status badge // Status badge
if key.deprecated { if key.deprecated {
ui.label( ui.label(egui::RichText::new("❗ DEPR")
egui::RichText::new("❗ DEPR") .size(10.0)
.size(10.0) .color(egui::Color32::from_rgb(231, 76, 60))
.color(egui::Color32::from_rgb(231, 76, 60)) .strong());
.strong(),
);
} else { } else {
ui.label( ui.label(egui::RichText::new("[OK] ACTIVE")
egui::RichText::new("") .size(10.0)
.size(10.0) .color(egui::Color32::from_rgb(46, 204, 113))
.color(egui::Color32::from_rgb(46, 204, 113)) .strong());
.strong(),
);
} }
ui.add_space(5.0); ui.add_space(5.0);
// Key preview // Key preview
ui.label( ui.label(egui::RichText::new(get_key_preview(&key.public_key))
egui::RichText::new(get_key_preview(&key.public_key)) .font(egui::FontId::monospace(10.0))
.font(egui::FontId::monospace(10.0)) .color(egui::Color32::LIGHT_GRAY));
.color(egui::Color32::LIGHT_GRAY),
);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Key action buttons // Key action buttons
if key.deprecated { if key.deprecated {
if ui if ui.add(egui::Button::new(egui::RichText::new("[R]").color(egui::Color32::WHITE))
.add( .fill(egui::Color32::from_rgb(101, 199, 40))
egui::Button::new( .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(94, 105, 25)))
egui::RichText::new("[R]").color(egui::Color32::WHITE), .rounding(egui::Rounding::same(3.0))
) .min_size(egui::vec2(22.0, 18.0))
.fill(egui::Color32::from_rgb(101, 199, 40)) ).on_hover_text("Restore key").clicked() {
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(94, 105, 25)))
.rounding(egui::Rounding::same(3.0))
.min_size(egui::vec2(22.0, 18.0)),
)
.on_hover_text("Restore key")
.clicked()
{
action = Some(KeyAction::RestoreKey(server_name.to_string())); action = Some(KeyAction::RestoreKey(server_name.to_string()));
} }
if ui if ui.add(egui::Button::new(egui::RichText::new("Del").color(egui::Color32::WHITE))
.add( .fill(egui::Color32::from_rgb(246, 36, 71))
egui::Button::new( .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(129, 18, 17)))
egui::RichText::new("Del").color(egui::Color32::WHITE), .rounding(egui::Rounding::same(3.0))
) .min_size(egui::vec2(26.0, 18.0))
.fill(egui::Color32::from_rgb(246, 36, 71)) ).on_hover_text("Delete key").clicked() {
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(129, 18, 17)))
.rounding(egui::Rounding::same(3.0))
.min_size(egui::vec2(26.0, 18.0)),
)
.on_hover_text("Delete key")
.clicked()
{
action = Some(KeyAction::DeleteKey(server_name.to_string())); action = Some(KeyAction::DeleteKey(server_name.to_string()));
} }
} else { } else {
if ui if ui.add(egui::Button::new(egui::RichText::new("").color(egui::Color32::BLACK))
.add( .fill(egui::Color32::from_rgb(255, 200, 0))
egui::Button::new( .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(102, 94, 72)))
egui::RichText::new("").color(egui::Color32::BLACK), .rounding(egui::Rounding::same(3.0))
) .min_size(egui::vec2(22.0, 18.0))
.fill(egui::Color32::from_rgb(255, 200, 0)) ).on_hover_text("Deprecate key").clicked() {
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(102, 94, 72)))
.rounding(egui::Rounding::same(3.0))
.min_size(egui::vec2(22.0, 18.0)),
)
.on_hover_text("Deprecate key")
.clicked()
{
action = Some(KeyAction::DeprecateKey(server_name.to_string())); action = Some(KeyAction::DeprecateKey(server_name.to_string()));
} }
} }
if ui if ui.add(egui::Button::new(egui::RichText::new("Copy").color(egui::Color32::WHITE))
.add( .fill(egui::Color32::from_rgb(0, 111, 230))
egui::Button::new(egui::RichText::new("Copy").color(egui::Color32::WHITE)) .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(35, 84, 97)))
.fill(egui::Color32::from_rgb(0, 111, 230)) .rounding(egui::Rounding::same(3.0))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(35, 84, 97))) .min_size(egui::vec2(30.0, 18.0))
.rounding(egui::Rounding::same(3.0)) ).on_hover_text("Copy to clipboard").clicked() {
.min_size(egui::vec2(30.0, 18.0)),
)
.on_hover_text("Copy to clipboard")
.clicked()
{
ui.output_mut(|o| o.copied_text = key.public_key.clone()); ui.output_mut(|o| o.copied_text = key.public_key.clone());
} }
}); });
}); });
}); });
action action
} }
/// Render a badge with text /// Render a badge with text
fn render_badge(ui: &mut egui::Ui, text: &str, bg_color: egui::Color32, text_color: egui::Color32) { fn render_badge(ui: &mut egui::Ui, text: &str, bg_color: egui::Color32, text_color: egui::Color32) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(50.0, 18.0), egui::Sense::hover()); let (rect, _) = ui.allocate_exact_size(
ui.painter() egui::vec2(50.0, 18.0),
.rect_filled(rect, egui::Rounding::same(8.0), bg_color); egui::Sense::hover()
);
ui.painter().rect_filled(
rect,
egui::Rounding::same(8.0),
bg_color
);
ui.painter().text( ui.painter().text(
rect.center(), rect.center(),
egui::Align2::CENTER_CENTER, egui::Align2::CENTER_CENTER,
@@ -591,15 +411,16 @@ fn render_badge(ui: &mut egui::Ui, text: &str, bg_color: egui::Color32, text_col
} }
/// Render a small badge with text /// Render a small badge with text
fn render_small_badge( fn render_small_badge(ui: &mut egui::Ui, text: &str, bg_color: egui::Color32, text_color: egui::Color32) {
ui: &mut egui::Ui, let (rect, _) = ui.allocate_exact_size(
text: &str, egui::vec2(40.0, 16.0),
bg_color: egui::Color32, egui::Sense::hover()
text_color: egui::Color32, );
) { ui.painter().rect_filled(
let (rect, _) = ui.allocate_exact_size(egui::vec2(40.0, 16.0), egui::Sense::hover()); rect,
ui.painter() egui::Rounding::same(3.0),
.rect_filled(rect, egui::Rounding::same(3.0), bg_color); bg_color
);
ui.painter().text( ui.painter().text(
rect.center(), rect.center(),
egui::Align2::CENTER_CENTER, egui::Align2::CENTER_CENTER,

View File

@@ -1,7 +1,7 @@
use crate::gui::common::{perform_sync, KhmSettings};
use log::info;
use reqwest::Client; use reqwest::Client;
use log::info;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::gui::common::{KhmSettings, perform_sync};
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SshKey { pub struct SshKey {
@@ -12,291 +12,189 @@ pub struct SshKey {
} }
/// Test connection to KHM server /// Test connection to KHM server
#[cfg(feature = "gui")] pub async fn test_connection(host: String, flow: String, basic_auth: String) -> Result<String, String> {
pub async fn test_connection(
host: String,
flow: String,
basic_auth: String,
) -> Result<String, String> {
if host.is_empty() || flow.is_empty() { if host.is_empty() || flow.is_empty() {
return Err("Host and flow must be specified".to_string()); return Err("Host and flow must be specified".to_string());
} }
let url = format!("{}/{}/keys", host.trim_end_matches('/'), flow); let url = format!("{}/{}/keys", host.trim_end_matches('/'), flow);
info!("Testing connection to: {}", url); info!("Testing connection to: {}", url);
let client = create_http_client()?; let client = create_http_client()?;
let mut request = client.get(&url); let mut request = client.get(&url);
request = add_auth_if_needed(request, &basic_auth)?; request = add_auth_if_needed(request, &basic_auth)?;
let response = request let response = request.send().await
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?; .map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?; check_response_status(&response)?;
let body = response let body = response.text().await
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?; .map_err(|e| format!("Failed to read response: {}", e))?;
check_html_response(&body)?; check_html_response(&body)?;
let keys: Vec<SshKey> = let keys: Vec<SshKey> = serde_json::from_str(&body)
serde_json::from_str(&body).map_err(|e| format!("Failed to parse response: {}", e))?; .map_err(|e| format!("Failed to parse response: {}", e))?;
let message = format!("Found {} SSH keys from flow '{}'", keys.len(), flow); let message = format!("Found {} SSH keys from flow '{}'", keys.len(), flow);
info!("Connection test successful: {}", message); info!("Connection test successful: {}", message);
Ok(message) Ok(message)
} }
/// Fetch all SSH keys including deprecated ones /// Fetch all SSH keys including deprecated ones
#[cfg(feature = "gui")] pub async fn fetch_keys(host: String, flow: String, basic_auth: String) -> Result<Vec<SshKey>, String> {
pub async fn fetch_keys(
host: String,
flow: String,
basic_auth: String,
) -> Result<Vec<SshKey>, String> {
if host.is_empty() || flow.is_empty() { if host.is_empty() || flow.is_empty() {
return Err("Host and flow must be specified".to_string()); return Err("Host and flow must be specified".to_string());
} }
let url = format!( let url = format!("{}/{}/keys?include_deprecated=true", host.trim_end_matches('/'), flow);
"{}/{}/keys?include_deprecated=true",
host.trim_end_matches('/'),
flow
);
info!("Fetching keys from: {}", url); info!("Fetching keys from: {}", url);
let client = create_http_client()?; let client = create_http_client()?;
let mut request = client.get(&url); let mut request = client.get(&url);
request = add_auth_if_needed(request, &basic_auth)?; request = add_auth_if_needed(request, &basic_auth)?;
let response = request let response = request.send().await
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?; .map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?; check_response_status(&response)?;
let body = response let body = response.text().await
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?; .map_err(|e| format!("Failed to read response: {}", e))?;
check_html_response(&body)?; check_html_response(&body)?;
let keys: Vec<SshKey> = let keys: Vec<SshKey> = serde_json::from_str(&body)
serde_json::from_str(&body).map_err(|e| format!("Failed to parse response: {}", e))?; .map_err(|e| format!("Failed to parse response: {}", e))?;
info!("Fetched {} SSH keys", keys.len()); info!("Fetched {} SSH keys", keys.len());
Ok(keys) Ok(keys)
} }
/// Deprecate a key for a specific server /// Deprecate a key for a specific server
#[cfg(feature = "gui")] pub async fn deprecate_key(host: String, flow: String, basic_auth: String, server: String) -> Result<String, String> {
pub async fn deprecate_key( let url = format!("{}/{}/keys/{}", host.trim_end_matches('/'), flow, urlencoding::encode(&server));
host: String,
flow: String,
basic_auth: String,
server: String,
) -> Result<String, String> {
let url = format!(
"{}/{}/keys/{}",
host.trim_end_matches('/'),
flow,
urlencoding::encode(&server)
);
info!("Deprecating key for server '{}' at: {}", server, url); info!("Deprecating key for server '{}' at: {}", server, url);
let client = create_http_client()?; let client = create_http_client()?;
let mut request = client.delete(&url); let mut request = client.delete(&url);
request = add_auth_if_needed(request, &basic_auth)?; request = add_auth_if_needed(request, &basic_auth)?;
let response = request let response = request.send().await
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?; .map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?; check_response_status(&response)?;
let body = response let body = response.text().await
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?; .map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response( parse_api_response(&body, &format!("Successfully deprecated key for server '{}'", server))
&body,
&format!("Successfully deprecated key for server '{}'", server),
)
} }
/// Restore a key for a specific server /// Restore a key for a specific server
#[cfg(feature = "gui")] pub async fn restore_key(host: String, flow: String, basic_auth: String, server: String) -> Result<String, String> {
pub async fn restore_key( let url = format!("{}/{}/keys/{}/restore", host.trim_end_matches('/'), flow, urlencoding::encode(&server));
host: String,
flow: String,
basic_auth: String,
server: String,
) -> Result<String, String> {
let url = format!(
"{}/{}/keys/{}/restore",
host.trim_end_matches('/'),
flow,
urlencoding::encode(&server)
);
info!("Restoring key for server '{}' at: {}", server, url); info!("Restoring key for server '{}' at: {}", server, url);
let client = create_http_client()?; let client = create_http_client()?;
let mut request = client.post(&url); let mut request = client.post(&url);
request = add_auth_if_needed(request, &basic_auth)?; request = add_auth_if_needed(request, &basic_auth)?;
let response = request let response = request.send().await
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?; .map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?; check_response_status(&response)?;
let body = response let body = response.text().await
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?; .map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response( parse_api_response(&body, &format!("Successfully restored key for server '{}'", server))
&body,
&format!("Successfully restored key for server '{}'", server),
)
} }
/// Delete a key permanently for a specific server /// Delete a key permanently for a specific server
#[cfg(feature = "gui")] pub async fn delete_key(host: String, flow: String, basic_auth: String, server: String) -> Result<String, String> {
pub async fn delete_key( let url = format!("{}/{}/keys/{}/delete", host.trim_end_matches('/'), flow, urlencoding::encode(&server));
host: String, info!("Permanently deleting key for server '{}' at: {}", server, url);
flow: String,
basic_auth: String,
server: String,
) -> Result<String, String> {
let url = format!(
"{}/{}/keys/{}/delete",
host.trim_end_matches('/'),
flow,
urlencoding::encode(&server)
);
info!(
"Permanently deleting key for server '{}' at: {}",
server, url
);
let client = create_http_client()?; let client = create_http_client()?;
let mut request = client.delete(&url); let mut request = client.delete(&url);
request = add_auth_if_needed(request, &basic_auth)?; request = add_auth_if_needed(request, &basic_auth)?;
let response = request let response = request.send().await
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?; .map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?; check_response_status(&response)?;
let body = response let body = response.text().await
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?; .map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response( parse_api_response(&body, &format!("Successfully deleted key for server '{}'", server))
&body,
&format!("Successfully deleted key for server '{}'", server),
)
} }
/// Bulk deprecate multiple servers /// Bulk deprecate multiple servers
#[cfg(feature = "gui")] pub async fn bulk_deprecate_servers(host: String, flow: String, basic_auth: String, servers: Vec<String>) -> Result<String, String> {
pub async fn bulk_deprecate_servers(
host: String,
flow: String,
basic_auth: String,
servers: Vec<String>,
) -> Result<String, String> {
let url = format!("{}/{}/bulk-deprecate", host.trim_end_matches('/'), flow); let url = format!("{}/{}/bulk-deprecate", host.trim_end_matches('/'), flow);
info!("Bulk deprecating {} servers at: {}", servers.len(), url); info!("Bulk deprecating {} servers at: {}", servers.len(), url);
let client = create_http_client()?; let client = create_http_client()?;
let mut request = client.post(&url).json(&serde_json::json!({ let mut request = client.post(&url)
"servers": servers .json(&serde_json::json!({
})); "servers": servers
}));
request = add_auth_if_needed(request, &basic_auth)?; request = add_auth_if_needed(request, &basic_auth)?;
let response = request let response = request.send().await
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?; .map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?; check_response_status(&response)?;
let body = response let body = response.text().await
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?; .map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(&body, "Successfully deprecated servers") parse_api_response(&body, "Successfully deprecated servers")
} }
/// Bulk restore multiple servers /// Bulk restore multiple servers
#[cfg(feature = "gui")] pub async fn bulk_restore_servers(host: String, flow: String, basic_auth: String, servers: Vec<String>) -> Result<String, String> {
pub async fn bulk_restore_servers(
host: String,
flow: String,
basic_auth: String,
servers: Vec<String>,
) -> Result<String, String> {
let url = format!("{}/{}/bulk-restore", host.trim_end_matches('/'), flow); let url = format!("{}/{}/bulk-restore", host.trim_end_matches('/'), flow);
info!("Bulk restoring {} servers at: {}", servers.len(), url); info!("Bulk restoring {} servers at: {}", servers.len(), url);
let client = create_http_client()?; let client = create_http_client()?;
let mut request = client.post(&url).json(&serde_json::json!({ let mut request = client.post(&url)
"servers": servers .json(&serde_json::json!({
})); "servers": servers
}));
request = add_auth_if_needed(request, &basic_auth)?; request = add_auth_if_needed(request, &basic_auth)?;
let response = request let response = request.send().await
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?; .map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?; check_response_status(&response)?;
let body = response let body = response.text().await
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?; .map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(&body, "Successfully restored servers") parse_api_response(&body, "Successfully restored servers")
} }
/// Perform manual sync operation /// Perform manual sync operation
#[cfg(feature = "gui")]
pub async fn perform_manual_sync(settings: KhmSettings) -> Result<String, String> { pub async fn perform_manual_sync(settings: KhmSettings) -> Result<String, String> {
match perform_sync(&settings).await { match perform_sync(&settings).await {
Ok(keys_count) => Ok(format!( Ok(keys_count) => Ok(format!("Sync completed successfully with {} keys", keys_count)),
"Sync completed successfully with {} keys",
keys_count
)),
Err(e) => Err(e.to_string()), Err(e) => Err(e.to_string()),
} }
} }
// Helper functions // Helper functions
#[cfg(feature = "gui")]
fn create_http_client() -> Result<Client, String> { fn create_http_client() -> Result<Client, String> {
Client::builder() Client::builder()
.timeout(std::time::Duration::from_secs(30)) .timeout(std::time::Duration::from_secs(30))
@@ -305,15 +203,11 @@ fn create_http_client() -> Result<Client, String> {
.map_err(|e| format!("Failed to create HTTP client: {}", e)) .map_err(|e| format!("Failed to create HTTP client: {}", e))
} }
#[cfg(feature = "gui")] fn add_auth_if_needed(request: reqwest::RequestBuilder, basic_auth: &str) -> Result<reqwest::RequestBuilder, String> {
fn add_auth_if_needed(
request: reqwest::RequestBuilder,
basic_auth: &str,
) -> Result<reqwest::RequestBuilder, String> {
if basic_auth.is_empty() { if basic_auth.is_empty() {
return Ok(request); return Ok(request);
} }
let auth_parts: Vec<&str> = basic_auth.splitn(2, ':').collect(); let auth_parts: Vec<&str> = basic_auth.splitn(2, ':').collect();
if auth_parts.len() == 2 { if auth_parts.len() == 2 {
Ok(request.basic_auth(auth_parts[0], Some(auth_parts[1]))) Ok(request.basic_auth(auth_parts[0], Some(auth_parts[1])))
@@ -322,32 +216,24 @@ fn add_auth_if_needed(
} }
} }
#[cfg(feature = "gui")]
fn check_response_status(response: &reqwest::Response) -> Result<(), String> { fn check_response_status(response: &reqwest::Response) -> Result<(), String> {
let status = response.status().as_u16(); let status = response.status().as_u16();
if status == 401 { if status == 401 {
return Err( return Err("Authentication required. Please provide valid basic auth credentials.".to_string());
"Authentication required. Please provide valid basic auth credentials.".to_string(),
);
} }
if status >= 300 && status < 400 { if status >= 300 && status < 400 {
return Err("Server redirects to login page. Authentication may be required.".to_string()); return Err("Server redirects to login page. Authentication may be required.".to_string());
} }
if !response.status().is_success() { if !response.status().is_success() {
return Err(format!( return Err(format!("Server returned error: {} {}", status, response.status().canonical_reason().unwrap_or("Unknown")));
"Server returned error: {} {}",
status,
response.status().canonical_reason().unwrap_or("Unknown")
));
} }
Ok(()) Ok(())
} }
#[cfg(feature = "gui")]
fn check_html_response(body: &str) -> Result<(), String> { fn check_html_response(body: &str) -> Result<(), String> {
if body.trim_start().starts_with("<!DOCTYPE") || body.trim_start().starts_with("<html") { if body.trim_start().starts_with("<!DOCTYPE") || body.trim_start().starts_with("<html") {
return Err("Server returned HTML page instead of JSON. This usually means authentication is required or the endpoint is incorrect.".to_string()); return Err("Server returned HTML page instead of JSON. This usually means authentication is required or the endpoint is incorrect.".to_string());
@@ -355,7 +241,6 @@ fn check_html_response(body: &str) -> Result<(), String> {
Ok(()) Ok(())
} }
#[cfg(feature = "gui")]
fn parse_api_response(body: &str, default_message: &str) -> Result<String, String> { fn parse_api_response(body: &str, default_message: &str) -> Result<String, String> {
if let Ok(json_response) = serde_json::from_str::<serde_json::Value>(body) { if let Ok(json_response) = serde_json::from_str::<serde_json::Value>(body) {
if let Some(message) = json_response.get("message").and_then(|v| v.as_str()) { if let Some(message) = json_response.get("message").and_then(|v| v.as_str()) {

View File

@@ -1,5 +1,3 @@
#[cfg(feature = "gui")]
mod client; mod client;
#[cfg(feature = "gui")]
pub use client::*; pub use client::*;

View File

@@ -1,5 +1,3 @@
#[cfg(feature = "gui")]
mod settings; mod settings;
#[cfg(feature = "gui")]
pub use settings::*; pub use settings::*;

View File

@@ -1,15 +1,9 @@
#[cfg(feature = "gui")]
use dirs::home_dir; use dirs::home_dir;
#[cfg(feature = "gui")]
use log::{debug, error, info}; use log::{debug, error, info};
#[cfg(feature = "gui")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[cfg(feature = "gui")]
use std::fs; use std::fs;
#[cfg(feature = "gui")]
use std::path::PathBuf; use std::path::PathBuf;
#[cfg(feature = "gui")]
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KhmSettings { pub struct KhmSettings {
pub host: String, pub host: String,
@@ -20,7 +14,6 @@ pub struct KhmSettings {
pub auto_sync_interval_minutes: u32, pub auto_sync_interval_minutes: u32,
} }
#[cfg(feature = "gui")]
impl Default for KhmSettings { impl Default for KhmSettings {
fn default() -> Self { fn default() -> Self {
Self { Self {
@@ -35,19 +28,22 @@ impl Default for KhmSettings {
} }
/// Get default known_hosts file path based on OS /// Get default known_hosts file path based on OS
#[cfg(feature = "gui")]
fn get_default_known_hosts_path() -> String { fn get_default_known_hosts_path() -> String {
if let Some(home) = home_dir() { #[cfg(target_os = "windows")]
let ssh_dir = home.join(".ssh"); {
let known_hosts_file = ssh_dir.join("known_hosts"); if let Ok(user_profile) = std::env::var("USERPROFILE") {
known_hosts_file.to_string_lossy().to_string() format!("{}/.ssh/known_hosts", user_profile)
} else { } else {
"~/.ssh/known_hosts".to_string()
}
}
#[cfg(not(target_os = "windows"))]
{
"~/.ssh/known_hosts".to_string() "~/.ssh/known_hosts".to_string()
} }
} }
/// Get configuration file path /// Get configuration file path
#[cfg(feature = "gui")]
pub fn get_config_path() -> PathBuf { pub fn get_config_path() -> PathBuf {
let mut path = home_dir().expect("Could not find home directory"); let mut path = home_dir().expect("Could not find home directory");
path.push(".khm"); path.push(".khm");
@@ -57,7 +53,6 @@ pub fn get_config_path() -> PathBuf {
} }
/// Load settings from configuration file /// Load settings from configuration file
#[cfg(feature = "gui")]
pub fn load_settings() -> KhmSettings { pub fn load_settings() -> KhmSettings {
let path = get_config_path(); let path = get_config_path();
match fs::read_to_string(&path) { match fs::read_to_string(&path) {
@@ -66,12 +61,12 @@ pub fn load_settings() -> KhmSettings {
error!("Failed to parse KHM config: {}", e); error!("Failed to parse KHM config: {}", e);
KhmSettings::default() KhmSettings::default()
}); });
// Fill in default known_hosts path if empty // Fill in default known_hosts path if empty
if settings.known_hosts.is_empty() { if settings.known_hosts.is_empty() {
settings.known_hosts = get_default_known_hosts_path(); settings.known_hosts = get_default_known_hosts_path();
} }
settings settings
} }
Err(_) => { Err(_) => {
@@ -82,7 +77,6 @@ pub fn load_settings() -> KhmSettings {
} }
/// Save settings to configuration file /// Save settings to configuration file
#[cfg(feature = "gui")]
pub fn save_settings(settings: &KhmSettings) -> Result<(), std::io::Error> { pub fn save_settings(settings: &KhmSettings) -> Result<(), std::io::Error> {
let path = get_config_path(); let path = get_config_path();
let json = serde_json::to_string_pretty(settings)?; let json = serde_json::to_string_pretty(settings)?;
@@ -92,7 +86,6 @@ pub fn save_settings(settings: &KhmSettings) -> Result<(), std::io::Error> {
} }
/// Expand path with ~ substitution /// Expand path with ~ substitution
#[cfg(feature = "gui")]
pub fn expand_path(path: &str) -> String { pub fn expand_path(path: &str) -> String {
if path.starts_with("~/") { if path.starts_with("~/") {
if let Some(home) = home_dir() { if let Some(home) = home_dir() {
@@ -103,43 +96,40 @@ pub fn expand_path(path: &str) -> String {
} }
/// Perform sync operation using KHM client logic /// Perform sync operation using KHM client logic
#[cfg(feature = "gui")]
pub async fn perform_sync(settings: &KhmSettings) -> Result<usize, std::io::Error> { pub async fn perform_sync(settings: &KhmSettings) -> Result<usize, std::io::Error> {
use crate::Args; use crate::Args;
info!( info!("Starting sync with settings: host={}, flow={}, known_hosts={}, in_place={}",
"Starting sync with settings: host={}, flow={}, known_hosts={}, in_place={}", settings.host, settings.flow, settings.known_hosts, settings.in_place);
settings.host, settings.flow, settings.known_hosts, settings.in_place
);
// Convert KhmSettings to Args for client module // Convert KhmSettings to Args for client module
let args = Args { let args = Args {
server: false, server: false,
daemon: false, gui: false,
settings_ui: false, settings_ui: false,
in_place: settings.in_place, in_place: settings.in_place,
flows: vec!["default".to_string()], // Not used in client mode flows: vec!["default".to_string()], // Not used in client mode
ip: "127.0.0.1".to_string(), // Not used in client mode ip: "127.0.0.1".to_string(), // Not used in client mode
port: 8080, // Not used in client mode port: 8080, // Not used in client mode
db_host: "127.0.0.1".to_string(), // Not used in client mode db_host: "127.0.0.1".to_string(), // Not used in client mode
db_name: "khm".to_string(), // Not used in client mode db_name: "khm".to_string(), // Not used in client mode
db_user: None, // Not used in client mode db_user: None, // Not used in client mode
db_password: None, // Not used in client mode db_password: None, // Not used in client mode
host: Some(settings.host.clone()), host: Some(settings.host.clone()),
flow: Some(settings.flow.clone()), flow: Some(settings.flow.clone()),
known_hosts: expand_path(&settings.known_hosts), known_hosts: expand_path(&settings.known_hosts),
basic_auth: settings.basic_auth.clone(), basic_auth: settings.basic_auth.clone(),
}; };
info!("Expanded known_hosts path: {}", args.known_hosts); info!("Expanded known_hosts path: {}", args.known_hosts);
// Get keys count before and after sync // Get keys count before and after sync
let keys_before = crate::client::read_known_hosts(&args.known_hosts) let keys_before = crate::client::read_known_hosts(&args.known_hosts)
.unwrap_or_else(|_| Vec::new()) .unwrap_or_else(|_| Vec::new())
.len(); .len();
crate::client::run_client(args.clone()).await?; crate::client::run_client(args.clone()).await?;
let keys_after = if args.in_place { let keys_after = if args.in_place {
crate::client::read_known_hosts(&args.known_hosts) crate::client::read_known_hosts(&args.known_hosts)
.unwrap_or_else(|_| Vec::new()) .unwrap_or_else(|_| Vec::new())
@@ -147,10 +137,7 @@ pub async fn perform_sync(settings: &KhmSettings) -> Result<usize, std::io::Erro
} else { } else {
keys_before keys_before
}; };
info!( info!("Sync completed: {} keys before, {} keys after", keys_before, keys_after);
"Sync completed: {} keys before, {} keys after",
keys_before, keys_after
);
Ok(keys_after) Ok(keys_after)
} }

View File

@@ -1,10 +1,8 @@
#[cfg(feature = "gui")]
use log::info; use log::info;
// Modules // Modules
#[cfg(feature = "gui")]
mod admin;
mod api; mod api;
mod admin;
mod common; mod common;
#[cfg(feature = "gui")] #[cfg(feature = "gui")]
@@ -40,6 +38,6 @@ pub async fn run_gui() -> std::io::Result<()> {
pub async fn run_gui() -> std::io::Result<()> { pub async fn run_gui() -> std::io::Result<()> {
return Err(std::io::Error::new( return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported, std::io::ErrorKind::Unsupported,
"GUI features not compiled. Install system dependencies and rebuild with --features gui", "GUI features not compiled. Install system dependencies and rebuild with --features gui"
)); ));
} }

View File

@@ -1,8 +1,8 @@
use crate::gui::api::{perform_manual_sync, test_connection};
use crate::gui::common::{save_settings, KhmSettings};
use eframe::egui; use eframe::egui;
use log::{error, info}; use log::{error, info};
use std::sync::mpsc; use std::sync::mpsc;
use crate::gui::api::{test_connection, perform_manual_sync};
use crate::gui::common::{KhmSettings, save_settings};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum ConnectionStatus { pub enum ConnectionStatus {
@@ -31,7 +31,6 @@ pub struct ConnectionTab {
pub is_syncing: bool, pub is_syncing: bool,
pub sync_result_receiver: Option<mpsc::Receiver<Result<String, String>>>, pub sync_result_receiver: Option<mpsc::Receiver<Result<String, String>>>,
pub sync_status: SyncStatus, pub sync_status: SyncStatus,
pub should_auto_test: bool,
} }
impl Default for ConnectionTab { impl Default for ConnectionTab {
@@ -43,7 +42,6 @@ impl Default for ConnectionTab {
is_syncing: false, is_syncing: false,
sync_result_receiver: None, sync_result_receiver: None,
sync_status: SyncStatus::Unknown, sync_status: SyncStatus::Unknown,
should_auto_test: false,
} }
} }
} }
@@ -54,63 +52,57 @@ impl ConnectionTab {
if self.is_testing_connection { if self.is_testing_connection {
return; return;
} }
self.is_testing_connection = true; self.is_testing_connection = true;
self.connection_status = ConnectionStatus::Unknown; self.connection_status = ConnectionStatus::Unknown;
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
self.test_result_receiver = Some(rx); self.test_result_receiver = Some(rx);
let host = settings.host.clone(); let host = settings.host.clone();
let flow = settings.flow.clone(); let flow = settings.flow.clone();
let basic_auth = settings.basic_auth.clone(); let basic_auth = settings.basic_auth.clone();
let ctx_clone = ctx.clone(); let ctx_clone = ctx.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async { test_connection(host, flow, basic_auth).await }); let result = rt.block_on(async {
test_connection(host, flow, basic_auth).await
});
let _ = tx.send(result); let _ = tx.send(result);
ctx_clone.request_repaint(); ctx_clone.request_repaint();
}); });
} }
/// Start manual sync /// Start manual sync
pub fn start_sync(&mut self, settings: &KhmSettings, ctx: &egui::Context) { pub fn start_sync(&mut self, settings: &KhmSettings, ctx: &egui::Context) {
if self.is_syncing { if self.is_syncing {
return; return;
} }
self.is_syncing = true; self.is_syncing = true;
self.sync_status = SyncStatus::Unknown; self.sync_status = SyncStatus::Unknown;
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
self.sync_result_receiver = Some(rx); self.sync_result_receiver = Some(rx);
let settings = settings.clone(); let settings = settings.clone();
let ctx_clone = ctx.clone(); let ctx_clone = ctx.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(async { perform_manual_sync(settings).await }); let result = rt.block_on(async {
perform_manual_sync(settings).await
});
let _ = tx.send(result); let _ = tx.send(result);
ctx_clone.request_repaint(); ctx_clone.request_repaint();
}); });
} }
/// Check for test/sync results and handle auto-test /// Check for test/sync results
pub fn check_results( pub fn check_results(&mut self, ctx: &egui::Context, settings: &KhmSettings, operation_log: &mut Vec<String>) {
&mut self,
ctx: &egui::Context,
settings: &KhmSettings,
operation_log: &mut Vec<String>,
) {
// Handle auto-test on first frame if needed
if self.should_auto_test && !self.is_testing_connection {
self.should_auto_test = false;
self.start_test(settings, ctx);
}
// Check for test connection result // Check for test connection result
if let Some(receiver) = &self.test_result_receiver { if let Some(receiver) = &self.test_result_receiver {
if let Ok(result) = receiver.try_recv() { if let Ok(result) = receiver.try_recv() {
@@ -120,44 +112,32 @@ impl ConnectionTab {
// Parse keys count from message // Parse keys count from message
let keys_count = if let Some(start) = message.find("Found ") { let keys_count = if let Some(start) = message.find("Found ") {
if let Some(end) = message[start + 6..].find(" SSH keys") { if let Some(end) = message[start + 6..].find(" SSH keys") {
message[start + 6..start + 6 + end] message[start + 6..start + 6 + end].parse::<usize>().unwrap_or(0)
.parse::<usize>() } else { 0 }
.unwrap_or(0) } else { 0 };
} else {
0 self.connection_status = ConnectionStatus::Connected {
} keys_count,
} else { flow: settings.flow.clone()
0
};
self.connection_status = ConnectionStatus::Connected {
keys_count,
flow: settings.flow.clone(),
}; };
info!("Connection test successful: {}", message); info!("Connection test successful: {}", message);
// Add to UI log // Add to UI log
super::ui::add_log_entry( super::ui::add_log_entry(operation_log, format!("✅ Connection test successful: {}", message));
operation_log,
format!("✅ Connection test successful: {}", message),
);
} }
Err(error) => { Err(error) => {
self.connection_status = ConnectionStatus::Error(error.clone()); self.connection_status = ConnectionStatus::Error(error.clone());
error!("Connection test failed"); error!("Connection test failed");
// Add to UI log // Add to UI log
super::ui::add_log_entry( super::ui::add_log_entry(operation_log, format!("❌ Connection test failed: {}", error));
operation_log,
format!("❌ Connection test failed: {}", error),
);
} }
} }
self.test_result_receiver = None; self.test_result_receiver = None;
ctx.request_repaint(); ctx.request_repaint();
} }
} }
// Check for sync result // Check for sync result
if let Some(receiver) = &self.sync_result_receiver { if let Some(receiver) = &self.sync_result_receiver {
if let Ok(result) = receiver.try_recv() { if let Ok(result) = receiver.try_recv() {
@@ -168,22 +148,16 @@ impl ConnectionTab {
let keys_count = parse_keys_count(&message); let keys_count = parse_keys_count(&message);
self.sync_status = SyncStatus::Success { keys_count }; self.sync_status = SyncStatus::Success { keys_count };
info!("Sync successful: {}", message); info!("Sync successful: {}", message);
// Add to UI log // Add to UI log
super::ui::add_log_entry( super::ui::add_log_entry(operation_log, format!("✅ Sync completed: {}", message));
operation_log,
format!("✅ Sync completed: {}", message),
);
} }
Err(error) => { Err(error) => {
self.sync_status = SyncStatus::Error(error.clone()); self.sync_status = SyncStatus::Error(error.clone());
error!("Sync failed"); error!("Sync failed");
// Add to UI log // Add to UI log
super::ui::add_log_entry( super::ui::add_log_entry(operation_log, format!("❌ Sync failed: {}", error));
operation_log,
format!("❌ Sync failed: {}", error),
);
} }
} }
self.sync_result_receiver = None; self.sync_result_receiver = None;
@@ -214,7 +188,7 @@ fn parse_keys_count(message: &str) -> usize {
return number_str.parse::<usize>().unwrap_or(0); return number_str.parse::<usize>().unwrap_or(0);
} }
} }
0 0
} }
@@ -223,6 +197,6 @@ pub fn save_settings_validated(settings: &KhmSettings) -> Result<(), String> {
if settings.host.is_empty() || settings.flow.is_empty() { if settings.host.is_empty() || settings.flow.is_empty() {
return Err("Host URL and Flow Name are required".to_string()); return Err("Host URL and Flow Name are required".to_string());
} }
save_settings(settings).map_err(|e| format!("Failed to save settings: {}", e)) save_settings(settings).map_err(|e| format!("Failed to save settings: {}", e))
} }

View File

@@ -1,19 +1,19 @@
use super::connection::{save_settings_validated, ConnectionStatus, ConnectionTab, SyncStatus};
use crate::gui::common::{get_config_path, KhmSettings};
use eframe::egui; use eframe::egui;
use crate::gui::common::{KhmSettings, get_config_path};
use super::connection::{ConnectionTab, ConnectionStatus, SyncStatus, save_settings_validated};
/// Render connection settings tab with modern horizontal UI design /// Render connection settings tab with modern horizontal UI design
pub fn render_connection_tab( pub fn render_connection_tab(
ui: &mut egui::Ui, ui: &mut egui::Ui,
ctx: &egui::Context, ctx: &egui::Context,
settings: &mut KhmSettings, settings: &mut KhmSettings,
auto_sync_interval_str: &mut String, auto_sync_interval_str: &mut String,
connection_tab: &mut ConnectionTab, connection_tab: &mut ConnectionTab,
operation_log: &mut Vec<String>, operation_log: &mut Vec<String>
) { ) {
// Check for connection test and sync results // Check for connection test and sync results
connection_tab.check_results(ctx, settings, operation_log); connection_tab.check_results(ctx, settings, operation_log);
// Use scrollable area for the entire content // Use scrollable area for the entire content
egui::ScrollArea::vertical() egui::ScrollArea::vertical()
.auto_shrink([false; 2]) .auto_shrink([false; 2])
@@ -21,16 +21,16 @@ pub fn render_connection_tab(
ui.spacing_mut().item_spacing = egui::vec2(6.0, 8.0); ui.spacing_mut().item_spacing = egui::vec2(6.0, 8.0);
ui.spacing_mut().button_padding = egui::vec2(12.0, 6.0); ui.spacing_mut().button_padding = egui::vec2(12.0, 6.0);
ui.spacing_mut().indent = 16.0; ui.spacing_mut().indent = 16.0;
// Connection Status Card at top (full width) // Connection Status Card at top (full width)
render_connection_status_card(ui, connection_tab); render_connection_status_card(ui, connection_tab);
// Main configuration area - horizontal layout // Main configuration area - horizontal layout
ui.horizontal_top(|ui| { ui.horizontal_top(|ui| {
let available_width = ui.available_width(); let available_width = ui.available_width();
let left_panel_width = available_width * 0.6; let left_panel_width = available_width * 0.6;
let right_panel_width = available_width * 0.38; let right_panel_width = available_width * 0.38;
// Left panel - Connection and Local config // Left panel - Connection and Local config
ui.allocate_ui_with_layout( ui.allocate_ui_with_layout(
[left_panel_width, ui.available_height()].into(), [left_panel_width, ui.available_height()].into(),
@@ -38,14 +38,14 @@ pub fn render_connection_tab(
|ui| { |ui| {
// Connection Configuration Card // Connection Configuration Card
render_connection_config_card(ui, settings); render_connection_config_card(ui, settings);
// Local Configuration Card // Local Configuration Card
render_local_config_card(ui, settings); render_local_config_card(ui, settings);
}, }
); );
ui.add_space(8.0); ui.add_space(8.0);
// Right panel - Auto-sync and System info // Right panel - Auto-sync and System info
ui.allocate_ui_with_layout( ui.allocate_ui_with_layout(
[right_panel_width, ui.available_height()].into(), [right_panel_width, ui.available_height()].into(),
@@ -53,15 +53,15 @@ pub fn render_connection_tab(
|ui| { |ui| {
// Auto-sync Configuration Card // Auto-sync Configuration Card
render_auto_sync_card(ui, settings, auto_sync_interval_str); render_auto_sync_card(ui, settings, auto_sync_interval_str);
// System Information Card // System Information Card
render_system_info_card(ui); render_system_info_card(ui);
}, }
); );
}); });
ui.add_space(12.0); ui.add_space(12.0);
// Action buttons at bottom // Action buttons at bottom
render_action_section(ui, ctx, settings, connection_tab, operation_log); render_action_section(ui, ctx, settings, connection_tab, operation_log);
}); });
@@ -71,13 +71,10 @@ pub fn render_connection_tab(
fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionTab) { fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionTab) {
let frame = egui::Frame::group(ui.style()) let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color) .fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new( .stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.rounding(6.0) .rounding(6.0)
.inner_margin(egui::Margin::same(12.0)); .inner_margin(egui::Margin::same(12.0));
frame.show(ui, |ui| { frame.show(ui, |ui| {
// Header with status indicator // Header with status indicator
ui.horizontal(|ui| { ui.horizontal(|ui| {
@@ -88,75 +85,56 @@ fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionT
} else { } else {
format!("Connected to '{}' • {} keys", flow, keys_count) format!("Connected to '{}' • {} keys", flow, keys_count)
}; };
("", text, egui::Color32::GREEN) ("🟢", text, egui::Color32::GREEN)
}
ConnectionStatus::Error(error_msg) => {
("🔴", format!("Connection Error: {}", error_msg), egui::Color32::RED)
} }
ConnectionStatus::Error(error_msg) => (
"",
format!("Connection Error: {}", error_msg),
egui::Color32::RED,
),
ConnectionStatus::Unknown => { ConnectionStatus::Unknown => {
("", "Not Connected".to_string(), ui.visuals().text_color()) ("", "Not Connected".to_string(), ui.visuals().text_color())
} }
}; };
ui.label(egui::RichText::new(status_icon).size(14.0)); ui.label(egui::RichText::new(status_icon).size(14.0));
ui.label(egui::RichText::new("Connection Status").size(14.0).strong()); ui.label(egui::RichText::new("Connection Status").size(14.0).strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if connection_tab.is_testing_connection { if connection_tab.is_testing_connection {
ui.spinner(); ui.spinner();
ui.label( ui.label(egui::RichText::new("Testing...").italics().color(ui.visuals().weak_text_color()));
egui::RichText::new("Testing...")
.italics()
.color(ui.visuals().weak_text_color()),
);
} else { } else {
ui.label( ui.label(egui::RichText::new(&status_text).size(13.0).color(status_color));
egui::RichText::new(&status_text)
.size(13.0)
.color(status_color),
);
} }
}); });
}); });
// Sync status - always visible // Sync status - always visible
ui.add_space(6.0); ui.add_space(6.0);
ui.separator(); ui.separator();
ui.add_space(6.0); ui.add_space(6.0);
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("🔄"); ui.label("🔄");
ui.label("Last Sync:"); ui.label("Last Sync:");
match &connection_tab.sync_status { match &connection_tab.sync_status {
SyncStatus::Success { keys_count } => { SyncStatus::Success { keys_count } => {
ui.label( ui.label(egui::RichText::new(format!("{} keys synced", keys_count))
egui::RichText::new(format!("{} keys synced", keys_count)) .size(13.0).color(egui::Color32::GREEN));
.size(13.0)
.color(egui::Color32::GREEN),
);
} }
SyncStatus::Error(error_msg) => { SyncStatus::Error(error_msg) => {
ui.label( ui.label(egui::RichText::new("❌ Failed")
egui::RichText::new("❌ Failed") .size(13.0).color(egui::Color32::RED))
.size(13.0) .on_hover_text(error_msg);
.color(egui::Color32::RED),
)
.on_hover_text(error_msg);
} }
SyncStatus::Unknown => { SyncStatus::Unknown => {
ui.label( ui.label(egui::RichText::new("No sync performed yet")
egui::RichText::new("No sync performed yet") .size(13.0).color(ui.visuals().weak_text_color()));
.size(13.0)
.color(ui.visuals().weak_text_color()),
);
} }
} }
}); });
}); });
ui.add_space(8.0); ui.add_space(8.0);
} }
@@ -164,30 +142,23 @@ fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionT
fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) { fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
let frame = egui::Frame::group(ui.style()) let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color) .fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new( .stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.rounding(6.0) .rounding(6.0)
.inner_margin(egui::Margin::same(12.0)); .inner_margin(egui::Margin::same(12.0));
frame.show(ui, |ui| { frame.show(ui, |ui| {
// Header // Header
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("🌐"); ui.label("🌐");
ui.label( ui.label(egui::RichText::new("Server Configuration").size(14.0).strong());
egui::RichText::new("Server Configuration")
.size(14.0)
.strong(),
);
}); });
ui.add_space(8.0); ui.add_space(8.0);
// Input fields with better spacing // Input fields with better spacing
ui.vertical(|ui| { ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 8.0; ui.spacing_mut().item_spacing.y = 8.0;
// Host URL // Host URL
ui.vertical(|ui| { ui.vertical(|ui| {
ui.label(egui::RichText::new("Host URL").size(13.0).strong()); ui.label(egui::RichText::new("Host URL").size(13.0).strong());
@@ -197,10 +168,10 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
egui::TextEdit::singleline(&mut settings.host) egui::TextEdit::singleline(&mut settings.host)
.hint_text("https://your-khm-server.com") .hint_text("https://your-khm-server.com")
.font(egui::FontId::new(14.0, egui::FontFamily::Monospace)) .font(egui::FontId::new(14.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(8.0, 6.0)), // Better vertical centering .margin(egui::Margin::symmetric(8.0, 6.0)) // Better vertical centering
); );
}); });
// Flow Name // Flow Name
ui.vertical(|ui| { ui.vertical(|ui| {
ui.label(egui::RichText::new("Flow Name").size(13.0).strong()); ui.label(egui::RichText::new("Flow Name").size(13.0).strong());
@@ -210,24 +181,15 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
egui::TextEdit::singleline(&mut settings.flow) egui::TextEdit::singleline(&mut settings.flow)
.hint_text("production, staging, development") .hint_text("production, staging, development")
.font(egui::FontId::new(14.0, egui::FontFamily::Proportional)) .font(egui::FontId::new(14.0, egui::FontFamily::Proportional))
.margin(egui::Margin::symmetric(8.0, 6.0)), .margin(egui::Margin::symmetric(8.0, 6.0))
); );
}); });
// Basic Auth (optional) // Basic Auth (optional)
ui.vertical(|ui| { ui.vertical(|ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label( ui.label(egui::RichText::new("Basic Authentication").size(13.0).strong());
egui::RichText::new("Basic Authentication") ui.label(egui::RichText::new("(optional)").size(12.0).weak().italics());
.size(13.0)
.strong(),
);
ui.label(
egui::RichText::new("(optional)")
.size(12.0)
.weak()
.italics(),
);
}); });
ui.add_space(3.0); ui.add_space(3.0);
ui.add_sized( ui.add_sized(
@@ -236,12 +198,12 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
.hint_text("username:password") .hint_text("username:password")
.password(true) .password(true)
.font(egui::FontId::new(14.0, egui::FontFamily::Monospace)) .font(egui::FontId::new(14.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(8.0, 6.0)), .margin(egui::Margin::symmetric(8.0, 6.0))
); );
}); });
}); });
}); });
ui.add_space(8.0); ui.add_space(8.0);
} }
@@ -249,122 +211,90 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
fn render_local_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) { fn render_local_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
let frame = egui::Frame::group(ui.style()) let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color) .fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new( .stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.rounding(6.0) .rounding(6.0)
.inner_margin(egui::Margin::same(12.0)); .inner_margin(egui::Margin::same(12.0));
frame.show(ui, |ui| { frame.show(ui, |ui| {
// Header // Header
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("📁"); ui.label("📁");
ui.label( ui.label(egui::RichText::new("Local Configuration").size(14.0).strong());
egui::RichText::new("Local Configuration")
.size(14.0)
.strong(),
);
}); });
ui.add_space(8.0); ui.add_space(8.0);
// Known hosts file // Known hosts file
ui.vertical(|ui| { ui.vertical(|ui| {
ui.label( ui.label(egui::RichText::new("Known Hosts File Path").size(13.0).strong());
egui::RichText::new("Known Hosts File Path")
.size(13.0)
.strong(),
);
ui.add_space(3.0); ui.add_space(3.0);
ui.add_sized( ui.add_sized(
[ui.available_width(), 28.0], [ui.available_width(), 28.0],
egui::TextEdit::singleline(&mut settings.known_hosts) egui::TextEdit::singleline(&mut settings.known_hosts)
.hint_text("~/.ssh/known_hosts") .hint_text("~/.ssh/known_hosts")
.font(egui::FontId::new(14.0, egui::FontFamily::Monospace)) .font(egui::FontId::new(14.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(8.0, 6.0)), .margin(egui::Margin::symmetric(8.0, 6.0))
); );
ui.add_space(8.0); ui.add_space(8.0);
// In-place update option with better styling // In-place update option with better styling
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.checkbox(&mut settings.in_place, ""); ui.checkbox(&mut settings.in_place, "");
ui.vertical(|ui| { ui.vertical(|ui| {
ui.label( ui.label(egui::RichText::new("Update file in-place after sync").size(13.0).strong());
egui::RichText::new("Update file in-place after sync") ui.label(egui::RichText::new("Automatically modify the known_hosts file when synchronizing").size(12.0).weak().italics());
.size(13.0)
.strong(),
);
ui.label(
egui::RichText::new(
"Automatically modify the known_hosts file when synchronizing",
)
.size(12.0)
.weak()
.italics(),
);
}); });
}); });
}); });
}); });
ui.add_space(8.0); ui.add_space(8.0);
} }
/// Auto-sync configuration card /// Auto-sync configuration card
fn render_auto_sync_card( fn render_auto_sync_card(ui: &mut egui::Ui, settings: &mut KhmSettings, auto_sync_interval_str: &mut String) {
ui: &mut egui::Ui,
settings: &mut KhmSettings,
auto_sync_interval_str: &mut String,
) {
let frame = egui::Frame::group(ui.style()) let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color) .fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new( .stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.rounding(6.0) .rounding(6.0)
.inner_margin(egui::Margin::same(12.0)); .inner_margin(egui::Margin::same(12.0));
frame.show(ui, |ui| { frame.show(ui, |ui| {
let is_auto_sync_enabled = let is_auto_sync_enabled = !settings.host.is_empty()
!settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place; && !settings.flow.is_empty()
&& settings.in_place;
// Header with status // Header with status
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("🔄"); ui.label("🔄");
ui.label(egui::RichText::new("Auto Sync").size(14.0).strong()); ui.label(egui::RichText::new("Auto Sync").size(14.0).strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let (status_text, status_color) = if is_auto_sync_enabled { let (status_text, status_color) = if is_auto_sync_enabled {
(" Active", egui::Color32::GREEN) (" Active", egui::Color32::GREEN)
} else { } else {
(" Inactive", egui::Color32::from_gray(128)) (" Inactive", egui::Color32::from_gray(128))
}; };
ui.label( ui.label(egui::RichText::new(status_text).size(12.0).color(status_color));
egui::RichText::new(status_text)
.size(12.0)
.color(status_color),
);
}); });
}); });
ui.add_space(8.0); ui.add_space(8.0);
// Interval setting // Interval setting
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label(egui::RichText::new("Interval").size(13.0).strong()); ui.label(egui::RichText::new("Interval").size(13.0).strong());
ui.add_space(6.0); ui.add_space(6.0);
ui.add_sized( ui.add_sized(
[80.0, 26.0], // Smaller height [80.0, 26.0], // Smaller height
egui::TextEdit::singleline(auto_sync_interval_str) egui::TextEdit::singleline(auto_sync_interval_str)
.font(egui::FontId::new(14.0, egui::FontFamily::Monospace)) .font(egui::FontId::new(14.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(6.0, 5.0)), .margin(egui::Margin::symmetric(6.0, 5.0))
); );
ui.label("min"); ui.label("min");
// Update the actual setting // Update the actual setting
if let Ok(value) = auto_sync_interval_str.parse::<u32>() { if let Ok(value) = auto_sync_interval_str.parse::<u32>() {
if value > 0 { if value > 0 {
@@ -372,52 +302,40 @@ fn render_auto_sync_card(
} }
} }
}); });
// Requirements - always visible // Requirements - always visible
ui.add_space(8.0); ui.add_space(8.0);
ui.separator(); ui.separator();
ui.add_space(8.0); ui.add_space(8.0);
ui.vertical(|ui| { ui.vertical(|ui| {
ui.label(egui::RichText::new("Requirements:").size(12.0).strong()); ui.label(egui::RichText::new("Requirements:").size(12.0).strong());
ui.add_space(3.0); ui.add_space(3.0);
let host_ok = !settings.host.is_empty(); let host_ok = !settings.host.is_empty();
let flow_ok = !settings.flow.is_empty(); let flow_ok = !settings.flow.is_empty();
let in_place_ok = settings.in_place; let in_place_ok = settings.in_place;
ui.horizontal(|ui| { ui.horizontal(|ui| {
let (icon, color) = if host_ok { let (icon, color) = if host_ok { ("", egui::Color32::GREEN) } else { ("", egui::Color32::RED) };
("", egui::Color32::GREEN)
} else {
("", egui::Color32::RED)
};
ui.label(egui::RichText::new(icon).color(color)); ui.label(egui::RichText::new(icon).color(color));
ui.label(egui::RichText::new("Host URL").size(11.0)); ui.label(egui::RichText::new("Host URL").size(11.0));
}); });
ui.horizontal(|ui| { ui.horizontal(|ui| {
let (icon, color) = if flow_ok { let (icon, color) = if flow_ok { ("", egui::Color32::GREEN) } else { ("", egui::Color32::RED) };
("", egui::Color32::GREEN)
} else {
("", egui::Color32::RED)
};
ui.label(egui::RichText::new(icon).color(color)); ui.label(egui::RichText::new(icon).color(color));
ui.label(egui::RichText::new("Flow name").size(11.0)); ui.label(egui::RichText::new("Flow name").size(11.0));
}); });
ui.horizontal(|ui| { ui.horizontal(|ui| {
let (icon, color) = if in_place_ok { let (icon, color) = if in_place_ok { ("", egui::Color32::GREEN) } else { ("", egui::Color32::RED) };
("", egui::Color32::GREEN)
} else {
("", egui::Color32::RED)
};
ui.label(egui::RichText::new(icon).color(color)); ui.label(egui::RichText::new(icon).color(color));
ui.label(egui::RichText::new("In-place update").size(11.0)); ui.label(egui::RichText::new("In-place update").size(11.0));
}); });
}); });
}); });
ui.add_space(8.0); ui.add_space(8.0);
} }
@@ -425,110 +343,103 @@ fn render_auto_sync_card(
fn render_system_info_card(ui: &mut egui::Ui) { fn render_system_info_card(ui: &mut egui::Ui) {
let frame = egui::Frame::group(ui.style()) let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().extreme_bg_color) .fill(ui.visuals().extreme_bg_color)
.stroke(egui::Stroke::new( .stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.rounding(6.0) .rounding(6.0)
.inner_margin(egui::Margin::same(12.0)); .inner_margin(egui::Margin::same(12.0));
frame.show(ui, |ui| { frame.show(ui, |ui| {
// Header // Header
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label("🔧"); ui.label("⚙️");
ui.label(egui::RichText::new("System Info").size(14.0).strong()); ui.label(egui::RichText::new("System Info").size(14.0).strong());
}); });
ui.add_space(8.0); ui.add_space(8.0);
// Config file location // Config file location
ui.vertical(|ui| { ui.vertical(|ui| {
ui.label(egui::RichText::new("Config File").size(13.0).strong()); ui.label(egui::RichText::new("Config File").size(13.0).strong());
ui.add_space(3.0); ui.add_space(3.0);
let config_path = get_config_path(); let config_path = get_config_path();
let path_str = config_path.display().to_string(); let path_str = config_path.display().to_string();
ui.vertical(|ui| { ui.vertical(|ui| {
ui.add_sized( ui.add_sized(
[ui.available_width(), 26.0], // Smaller height [ui.available_width(), 26.0], // Smaller height
egui::TextEdit::singleline(&mut path_str.clone()) egui::TextEdit::singleline(&mut path_str.clone())
.interactive(false) .interactive(false)
.font(egui::FontId::new(12.0, egui::FontFamily::Monospace)) .font(egui::FontId::new(12.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(8.0, 5.0)), .margin(egui::Margin::symmetric(8.0, 5.0))
); );
ui.add_space(4.0); ui.add_space(4.0);
if ui.small_button("📋 Copy Path").clicked() { if ui.small_button("📋 Copy Path").clicked() {
ui.output_mut(|o| o.copied_text = path_str); ui.output_mut(|o| o.copied_text = path_str);
} }
}); });
}); });
}); });
ui.add_space(8.0); ui.add_space(8.0);
} }
/// Action section with buttons only (Activity Log moved to bottom panel) /// Action section with buttons only (Activity Log moved to bottom panel)
fn render_action_section( fn render_action_section(
ui: &mut egui::Ui, ui: &mut egui::Ui,
ctx: &egui::Context, ctx: &egui::Context,
settings: &KhmSettings, settings: &KhmSettings,
connection_tab: &mut ConnectionTab, connection_tab: &mut ConnectionTab,
operation_log: &mut Vec<String>, operation_log: &mut Vec<String>
) { ) {
ui.add_space(2.0); ui.add_space(8.0);
// Validation for save button // Validation message
let save_enabled = !settings.host.is_empty() && !settings.flow.is_empty(); let save_enabled = !settings.host.is_empty() && !settings.flow.is_empty();
if !save_enabled {
ui.horizontal(|ui| {
ui.label("⚠️");
ui.label(egui::RichText::new("Complete server configuration to enable saving")
.size(12.0)
.color(egui::Color32::LIGHT_YELLOW)
.italics());
});
ui.add_space(8.0);
}
// Action buttons with modern styling // Action buttons with modern styling
render_modern_action_buttons( render_modern_action_buttons(ui, ctx, settings, connection_tab, save_enabled, operation_log);
ui,
ctx,
settings,
connection_tab,
save_enabled,
operation_log,
);
} }
/// Modern action buttons with improved styling and layout /// Modern action buttons with improved styling and layout
fn render_modern_action_buttons( fn render_modern_action_buttons(
ui: &mut egui::Ui, ui: &mut egui::Ui,
ctx: &egui::Context, ctx: &egui::Context,
settings: &KhmSettings, settings: &KhmSettings,
connection_tab: &mut ConnectionTab, connection_tab: &mut ConnectionTab,
save_enabled: bool, save_enabled: bool,
operation_log: &mut Vec<String>, operation_log: &mut Vec<String>
) { ) {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0; ui.spacing_mut().item_spacing.x = 8.0;
// Primary actions (left side) // Primary actions (left side)
let mut save_button = ui.add_enabled( if ui.add_enabled(
save_enabled, save_enabled,
egui::Button::new( egui::Button::new(
egui::RichText::new("💾 Save & Close") egui::RichText::new("💾 Save & Close")
.size(13.0) .size(13.0)
.color(egui::Color32::WHITE) .color(egui::Color32::WHITE)
) )
.fill(if save_enabled { .fill(if save_enabled {
egui::Color32::from_rgb(0, 120, 212) egui::Color32::from_rgb(0, 120, 212)
} else { } else {
ui.visuals().widgets.inactive.bg_fill ui.visuals().widgets.inactive.bg_fill
}) })
.min_size(egui::vec2(120.0, 32.0)) .min_size(egui::vec2(120.0, 32.0))
.rounding(6.0) .rounding(6.0)
); ).clicked() {
// Add tooltip when button is disabled
if !save_enabled {
save_button = save_button.on_hover_text("Complete server configuration to enable saving:\n• Host URL is required\n• Flow name is required");
}
if save_button.clicked() {
match save_settings_validated(settings) { match save_settings_validated(settings) {
Ok(()) => { Ok(()) => {
add_log_entry(operation_log, "✅ Settings saved successfully".to_string()); add_log_entry(operation_log, "✅ Settings saved successfully".to_string());
@@ -539,7 +450,7 @@ fn render_modern_action_buttons(
} }
} }
} }
if ui.add( if ui.add(
egui::Button::new( egui::Button::new(
egui::RichText::new("✖ Cancel") egui::RichText::new("✖ Cancel")
@@ -553,14 +464,14 @@ fn render_modern_action_buttons(
).clicked() { ).clicked() {
ctx.send_viewport_cmd(egui::ViewportCommand::Close); ctx.send_viewport_cmd(egui::ViewportCommand::Close);
} }
// Spacer // Spacer
ui.add_space(ui.available_width() - 220.0); ui.add_space(ui.available_width() - 220.0);
// Secondary actions (right side) // Secondary actions (right side)
let can_test = !settings.host.is_empty() && !settings.flow.is_empty() && !connection_tab.is_testing_connection; let can_test = !settings.host.is_empty() && !settings.flow.is_empty() && !connection_tab.is_testing_connection;
let can_sync = !settings.host.is_empty() && !settings.flow.is_empty() && !connection_tab.is_syncing; let can_sync = !settings.host.is_empty() && !settings.flow.is_empty() && !connection_tab.is_syncing;
if ui.add_enabled( if ui.add_enabled(
can_test, can_test,
egui::Button::new( egui::Button::new(
@@ -574,10 +485,10 @@ fn render_modern_action_buttons(
.size(13.0) .size(13.0)
.color(egui::Color32::WHITE) .color(egui::Color32::WHITE)
) )
.fill(if can_test { .fill(if can_test {
egui::Color32::from_rgb(16, 124, 16) egui::Color32::from_rgb(16, 124, 16)
} else { } else {
ui.visuals().widgets.inactive.bg_fill ui.visuals().widgets.inactive.bg_fill
}) })
.min_size(egui::vec2(80.0, 32.0)) .min_size(egui::vec2(80.0, 32.0))
.rounding(6.0) .rounding(6.0)
@@ -585,7 +496,7 @@ fn render_modern_action_buttons(
add_log_entry(operation_log, "🔍 Testing connection...".to_string()); add_log_entry(operation_log, "🔍 Testing connection...".to_string());
connection_tab.start_test(settings, ctx); connection_tab.start_test(settings, ctx);
} }
if ui.add_enabled( if ui.add_enabled(
can_sync, can_sync,
egui::Button::new( egui::Button::new(
@@ -599,10 +510,10 @@ fn render_modern_action_buttons(
.size(13.0) .size(13.0)
.color(egui::Color32::WHITE) .color(egui::Color32::WHITE)
) )
.fill(if can_sync { .fill(if can_sync {
egui::Color32::from_rgb(255, 140, 0) egui::Color32::from_rgb(255, 140, 0)
} else { } else {
ui.visuals().widgets.inactive.bg_fill ui.visuals().widgets.inactive.bg_fill
}) })
.min_size(egui::vec2(80.0, 32.0)) .min_size(egui::vec2(80.0, 32.0))
.rounding(6.0) .rounding(6.0)
@@ -620,17 +531,17 @@ pub fn add_log_entry(operation_log: &mut Vec<String>, message: String) {
.unwrap(); .unwrap();
let secs = now.as_secs(); let secs = now.as_secs();
let millis = now.subsec_millis(); let millis = now.subsec_millis();
// Format as HH:MM:SS.mmm // Format as HH:MM:SS.mmm
let hours = (secs / 3600) % 24; let hours = (secs / 3600) % 24;
let minutes = (secs / 60) % 60; let minutes = (secs / 60) % 60;
let seconds = secs % 60; let seconds = secs % 60;
let timestamp = format!("{:02}:{:02}:{:02}.{:03}", hours, minutes, seconds, millis); let timestamp = format!("{:02}:{:02}:{:02}.{:03}", hours, minutes, seconds, millis);
let log_entry = format!("{} {}", timestamp, message); let log_entry = format!("{} {}", timestamp, message);
operation_log.push(log_entry); operation_log.push(log_entry);
// Keep only last 20 entries to prevent memory growth // Keep only last 20 entries to prevent memory growth
if operation_log.len() > 20 { if operation_log.len() > 20 {
operation_log.remove(0); operation_log.remove(0);

View File

@@ -1,17 +1,14 @@
use crate::gui::admin::{
render_bulk_actions, render_keys_table, render_search_controls, render_statistics,
AdminOperation, AdminState, BulkAction, KeyAction,
};
use crate::gui::api::{
bulk_deprecate_servers, bulk_restore_servers, delete_key, deprecate_key, restore_key, SshKey,
};
use crate::gui::common::{load_settings, KhmSettings};
use eframe::egui; use eframe::egui;
use log::info; use log::info;
use std::sync::mpsc; use std::sync::mpsc;
use crate::gui::common::{load_settings, KhmSettings};
use crate::gui::admin::{AdminState, AdminOperation, render_statistics, render_search_controls,
render_bulk_actions, render_keys_table, KeyAction, BulkAction};
use crate::gui::api::{SshKey, bulk_deprecate_servers, bulk_restore_servers,
deprecate_key, restore_key, delete_key};
use super::connection::{ConnectionTab, SettingsTab}; use super::connection::{ConnectionTab, SettingsTab};
use super::ui::{add_log_entry, render_connection_tab}; use super::ui::{render_connection_tab, add_log_entry};
pub struct SettingsWindow { pub struct SettingsWindow {
settings: KhmSettings, settings: KhmSettings,
@@ -28,8 +25,8 @@ impl SettingsWindow {
pub fn new() -> Self { pub fn new() -> Self {
let settings = load_settings(); let settings = load_settings();
let auto_sync_interval_str = settings.auto_sync_interval_minutes.to_string(); let auto_sync_interval_str = settings.auto_sync_interval_minutes.to_string();
let mut instance = Self { Self {
settings, settings,
auto_sync_interval_str, auto_sync_interval_str,
current_tab: SettingsTab::Connection, current_tab: SettingsTab::Connection,
@@ -38,20 +35,7 @@ impl SettingsWindow {
admin_receiver: None, admin_receiver: None,
operation_receiver: None, operation_receiver: None,
operation_log: Vec::new(), operation_log: Vec::new(),
};
// Auto-test connection if configuration is found and valid
if !instance.settings.host.is_empty() && !instance.settings.flow.is_empty() {
add_log_entry(
&mut instance.operation_log,
"🔍 Auto-testing connection with saved configuration...".to_string(),
);
// We can't call start_test here because we don't have egui::Context yet
// So we set a flag to trigger test on first frame
instance.connection_tab.should_auto_test = true;
} }
instance
} }
} }
@@ -59,29 +43,27 @@ impl eframe::App for SettingsWindow {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
// Check for admin operation results // Check for admin operation results
self.check_admin_results(ctx); self.check_admin_results(ctx);
// Apply enhanced modern dark theme // Apply enhanced modern dark theme
apply_modern_theme(ctx); apply_modern_theme(ctx);
// Bottom panel for Activity Log (fixed at bottom) // Bottom panel for Activity Log (fixed at bottom)
egui::TopBottomPanel::bottom("activity_log_panel") egui::TopBottomPanel::bottom("activity_log_panel")
.resizable(false) .resizable(false)
.min_height(140.0) .min_height(140.0)
.max_height(140.0) .max_height(140.0)
.frame( .frame(egui::Frame::none()
egui::Frame::none() .fill(egui::Color32::from_gray(12))
.fill(egui::Color32::from_gray(12)) .stroke(egui::Stroke::new(1.0, egui::Color32::from_gray(60)))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_gray(60))),
) )
.show(ctx, |ui| { .show(ctx, |ui| {
render_bottom_activity_log(ui, &mut self.operation_log); render_bottom_activity_log(ui, &mut self.operation_log);
}); });
egui::CentralPanel::default() egui::CentralPanel::default()
.frame( .frame(egui::Frame::none()
egui::Frame::none() .fill(egui::Color32::from_gray(18))
.fill(egui::Color32::from_gray(18)) .inner_margin(egui::Margin::same(20.0))
.inner_margin(egui::Margin::same(20.0)),
) )
.show(ctx, |ui| { .show(ctx, |ui| {
// Modern header with gradient-like styling // Modern header with gradient-like styling
@@ -89,43 +71,34 @@ impl eframe::App for SettingsWindow {
.fill(ui.visuals().panel_fill) .fill(ui.visuals().panel_fill)
.rounding(egui::Rounding::same(8.0)) .rounding(egui::Rounding::same(8.0))
.inner_margin(egui::Margin::same(12.0)) .inner_margin(egui::Margin::same(12.0))
.stroke(egui::Stroke::new( .stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color));
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
));
header_frame.show(ui, |ui| { header_frame.show(ui, |ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.add_space(4.0); ui.add_space(4.0);
ui.label("🔑"); ui.label("🔑");
ui.heading(egui::RichText::new("KHM Settings").size(20.0).strong()); ui.heading(egui::RichText::new("KHM Settings").size(20.0).strong());
ui.label( ui.label(egui::RichText::new(
egui::RichText::new( "(Known Hosts Manager for SSH key management and synchronization)"
"(Known Hosts Manager for SSH key management and synchronization)", ).size(11.0).weak().italics());
)
.size(11.0)
.weak()
.italics(),
);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Version from Cargo.toml // Version from Cargo.toml
let version = env!("CARGO_PKG_VERSION"); let version = env!("CARGO_PKG_VERSION");
if ui if ui.small_button(format!("v{}", version))
.small_button(format!("v{}", version))
.on_hover_text(format!( .on_hover_text(format!(
"{}\n{}\nRepository: {}\nLicense: {}", "{}\n{}\nRepository: {}\nLicense: {}",
env!("CARGO_PKG_DESCRIPTION"), env!("CARGO_PKG_DESCRIPTION"),
env!("CARGO_PKG_AUTHORS"), env!("CARGO_PKG_AUTHORS"),
env!("CARGO_PKG_REPOSITORY"), env!("CARGO_PKG_REPOSITORY"),
"WTFPL" "WTFPL"
)) ))
.clicked() .clicked()
{ {
// Open repository URL // Open repository URL
if let Err(_) = std::process::Command::new("open") if let Err(_) = std::process::Command::new("open")
.arg(env!("CARGO_PKG_REPOSITORY")) .arg(env!("CARGO_PKG_REPOSITORY"))
.spawn() .spawn()
{ {
// Fallback for non-macOS systems // Fallback for non-macOS systems
let _ = std::process::Command::new("xdg-open") let _ = std::process::Command::new("xdg-open")
@@ -136,74 +109,70 @@ impl eframe::App for SettingsWindow {
}); });
}); });
}); });
ui.add_space(12.0); ui.add_space(12.0);
// Modern tab selector with card styling // Modern tab selector with card styling
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 6.0; ui.spacing_mut().item_spacing.x = 6.0;
// Connection/Settings Tab // Connection/Settings Tab
let connection_selected = matches!(self.current_tab, SettingsTab::Connection); let connection_selected = matches!(self.current_tab, SettingsTab::Connection);
let connection_button = let connection_button = egui::Button::new(
egui::Button::new(egui::RichText::new("🌐 Connection").size(13.0)) egui::RichText::new("🌐 Connection").size(13.0)
.fill(if connection_selected { )
egui::Color32::from_rgb(0, 120, 212) .fill(if connection_selected {
} else { egui::Color32::from_rgb(0, 120, 212)
ui.visuals().widgets.inactive.bg_fill } else {
}) ui.visuals().widgets.inactive.bg_fill
.stroke(if connection_selected { })
egui::Stroke::new(1.0, egui::Color32::from_rgb(0, 120, 212)) .stroke(if connection_selected {
} else { egui::Stroke::new(1.0, egui::Color32::from_rgb(0, 120, 212))
egui::Stroke::new( } else {
1.0, egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color)
ui.visuals().widgets.noninteractive.bg_stroke.color, })
) .rounding(6.0)
}) .min_size(egui::vec2(110.0, 32.0));
.rounding(6.0)
.min_size(egui::vec2(110.0, 32.0));
if ui.add(connection_button).clicked() { if ui.add(connection_button).clicked() {
self.current_tab = SettingsTab::Connection; self.current_tab = SettingsTab::Connection;
} }
// Admin Tab // Admin Tab
let admin_selected = matches!(self.current_tab, SettingsTab::Admin); let admin_selected = matches!(self.current_tab, SettingsTab::Admin);
let admin_button = let admin_button = egui::Button::new(
egui::Button::new(egui::RichText::new("🔧 Admin Panel").size(13.0)) egui::RichText::new("🔧 Admin Panel").size(13.0)
.fill(if admin_selected { )
egui::Color32::from_rgb(120, 80, 0) .fill(if admin_selected {
} else { egui::Color32::from_rgb(120, 80, 0)
ui.visuals().widgets.inactive.bg_fill } else {
}) ui.visuals().widgets.inactive.bg_fill
.stroke(if admin_selected { })
egui::Stroke::new(1.0, egui::Color32::from_rgb(120, 80, 0)) .stroke(if admin_selected {
} else { egui::Stroke::new(1.0, egui::Color32::from_rgb(120, 80, 0))
egui::Stroke::new( } else {
1.0, egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color)
ui.visuals().widgets.noninteractive.bg_stroke.color, })
) .rounding(6.0)
}) .min_size(egui::vec2(110.0, 32.0));
.rounding(6.0)
.min_size(egui::vec2(110.0, 32.0));
if ui.add(admin_button).clicked() { if ui.add(admin_button).clicked() {
self.current_tab = SettingsTab::Admin; self.current_tab = SettingsTab::Admin;
} }
}); });
ui.add_space(16.0); ui.add_space(16.0);
// Content area with proper spacing // Content area with proper spacing
match self.current_tab { match self.current_tab {
SettingsTab::Connection => { SettingsTab::Connection => {
render_connection_tab( render_connection_tab(
ui, ui,
ctx, ctx,
&mut self.settings, &mut self.settings,
&mut self.auto_sync_interval_str, &mut self.auto_sync_interval_str,
&mut self.connection_tab, &mut self.connection_tab,
&mut self.operation_log, &mut self.operation_log
); );
} }
SettingsTab::Admin => { SettingsTab::Admin => {
@@ -224,7 +193,7 @@ impl SettingsWindow {
ctx.request_repaint(); ctx.request_repaint();
} }
} }
// Check for operation results // Check for operation results
if let Some(receiver) = &self.operation_receiver { if let Some(receiver) = &self.operation_receiver {
if let Ok(result) = receiver.try_recv() { if let Ok(result) = receiver.try_recv() {
@@ -236,10 +205,7 @@ impl SettingsWindow {
self.load_admin_keys(ctx); self.load_admin_keys(ctx);
} }
Err(error) => { Err(error) => {
add_log_entry( add_log_entry(&mut self.operation_log, format!("❌ Operation failed: {}", error));
&mut self.operation_log,
format!("❌ Operation failed: {}", error),
);
} }
} }
self.admin_state.current_operation = AdminOperation::None; self.admin_state.current_operation = AdminOperation::None;
@@ -248,35 +214,33 @@ impl SettingsWindow {
} }
} }
} }
fn render_admin_tab(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { fn render_admin_tab(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
// Admin tab header // Admin tab header
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.label(egui::RichText::new("🔧 Admin Panel").size(18.0).strong()); ui.label(egui::RichText::new("🔧 Admin Panel").size(18.0).strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button("🔁 Refresh").clicked() { if ui.button("🔁 Refresh").clicked() {
self.load_admin_keys(ctx); self.load_admin_keys(ctx);
} }
if let Some(last_load) = self.admin_state.last_load_time { if let Some(last_load) = self.admin_state.last_load_time {
let elapsed = last_load.elapsed().as_secs(); let elapsed = last_load.elapsed().as_secs();
ui.label(format!("Updated {}s ago", elapsed)); ui.label(format!("Updated {}s ago", elapsed));
} }
}); });
}); });
ui.separator(); ui.separator();
ui.add_space(10.0); ui.add_space(10.0);
// Check if connection is configured // Check if connection is configured
if self.settings.host.is_empty() || self.settings.flow.is_empty() { if self.settings.host.is_empty() || self.settings.flow.is_empty() {
ui.vertical_centered(|ui| { ui.vertical_centered(|ui| {
ui.label( ui.label(egui::RichText::new("❗ Please configure connection settings first")
egui::RichText::new("❗ Please configure connection settings first") .size(16.0)
.size(16.0) .color(egui::Color32::YELLOW));
.color(egui::Color32::YELLOW),
);
ui.add_space(10.0); ui.add_space(10.0);
if ui.button("Go to Connection Settings").clicked() { if ui.button("Go to Connection Settings").clicked() {
self.current_tab = SettingsTab::Connection; self.current_tab = SettingsTab::Connection;
@@ -284,45 +248,37 @@ impl SettingsWindow {
}); });
return; return;
} }
// Load keys automatically on first view // Load keys automatically on first view
if self.admin_state.keys.is_empty() if self.admin_state.keys.is_empty() && !matches!(self.admin_state.current_operation, AdminOperation::LoadingKeys) {
&& !matches!(
self.admin_state.current_operation,
AdminOperation::LoadingKeys
)
{
self.load_admin_keys(ctx); self.load_admin_keys(ctx);
} }
// Show loading state // Show loading state
if matches!( if matches!(self.admin_state.current_operation, AdminOperation::LoadingKeys) {
self.admin_state.current_operation,
AdminOperation::LoadingKeys
) {
ui.vertical_centered(|ui| { ui.vertical_centered(|ui| {
ui.spinner(); ui.spinner();
ui.label("Loading keys..."); ui.label("Loading keys...");
}); });
return; return;
} }
// Statistics section // Statistics section
render_statistics(ui, &self.admin_state); render_statistics(ui, &self.admin_state);
ui.add_space(10.0); ui.add_space(10.0);
// Search and filters // Search and filters
render_search_controls(ui, &mut self.admin_state); render_search_controls(ui, &mut self.admin_state);
ui.add_space(10.0); ui.add_space(10.0);
// Bulk actions // Bulk actions
let bulk_action = render_bulk_actions(ui, &mut self.admin_state); let bulk_action = render_bulk_actions(ui, &mut self.admin_state);
self.handle_bulk_action(bulk_action, ctx); self.handle_bulk_action(bulk_action, ctx);
if self.admin_state.selected_servers.values().any(|&v| v) { if self.admin_state.selected_servers.values().any(|&v| v) {
ui.add_space(8.0); ui.add_space(8.0);
} }
// Keys table // Keys table
egui::ScrollArea::vertical() egui::ScrollArea::vertical()
.max_height(450.0) .max_height(450.0)
@@ -332,13 +288,13 @@ impl SettingsWindow {
self.handle_key_action(key_action, ctx); self.handle_key_action(key_action, ctx);
}); });
} }
fn load_admin_keys(&mut self, ctx: &egui::Context) { fn load_admin_keys(&mut self, ctx: &egui::Context) {
if let Some(receiver) = self.admin_state.load_keys(&self.settings, ctx) { if let Some(receiver) = self.admin_state.load_keys(&self.settings, ctx) {
self.admin_receiver = Some(receiver); self.admin_receiver = Some(receiver);
} }
} }
fn handle_bulk_action(&mut self, action: BulkAction, ctx: &egui::Context) { fn handle_bulk_action(&mut self, action: BulkAction, ctx: &egui::Context) {
match action { match action {
BulkAction::DeprecateSelected => { BulkAction::DeprecateSelected => {
@@ -359,7 +315,7 @@ impl SettingsWindow {
BulkAction::None => {} BulkAction::None => {}
} }
} }
fn handle_key_action(&mut self, action: KeyAction, ctx: &egui::Context) { fn handle_key_action(&mut self, action: KeyAction, ctx: &egui::Context) {
match action { match action {
KeyAction::DeprecateKey(server) | KeyAction::DeprecateServer(server) => { KeyAction::DeprecateKey(server) | KeyAction::DeprecateServer(server) => {
@@ -374,130 +330,120 @@ impl SettingsWindow {
KeyAction::None => {} KeyAction::None => {}
} }
} }
fn start_bulk_deprecate(&mut self, servers: Vec<String>, ctx: &egui::Context) { fn start_bulk_deprecate(&mut self, servers: Vec<String>, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::BulkDeprecating; self.admin_state.current_operation = AdminOperation::BulkDeprecating;
add_log_entry( add_log_entry(&mut self.operation_log, format!("Deprecating {} servers...", servers.len()));
&mut self.operation_log,
format!("Deprecating {} servers...", servers.len()),
);
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx); self.operation_receiver = Some(rx);
let host = self.settings.host.clone(); let host = self.settings.host.clone();
let flow = self.settings.flow.clone(); let flow = self.settings.flow.clone();
let basic_auth = self.settings.basic_auth.clone(); let basic_auth = self.settings.basic_auth.clone();
let ctx_clone = ctx.clone(); let ctx_clone = ctx.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt let result = rt.block_on(async {
.block_on(async { bulk_deprecate_servers(host, flow, basic_auth, servers).await }); bulk_deprecate_servers(host, flow, basic_auth, servers).await
});
let _ = tx.send(result); let _ = tx.send(result);
ctx_clone.request_repaint(); ctx_clone.request_repaint();
}); });
} }
fn start_bulk_restore(&mut self, servers: Vec<String>, ctx: &egui::Context) { fn start_bulk_restore(&mut self, servers: Vec<String>, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::BulkRestoring; self.admin_state.current_operation = AdminOperation::BulkRestoring;
add_log_entry( add_log_entry(&mut self.operation_log, format!("Restoring {} servers...", servers.len()));
&mut self.operation_log,
format!("Restoring {} servers...", servers.len()),
);
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx); self.operation_receiver = Some(rx);
let host = self.settings.host.clone(); let host = self.settings.host.clone();
let flow = self.settings.flow.clone(); let flow = self.settings.flow.clone();
let basic_auth = self.settings.basic_auth.clone(); let basic_auth = self.settings.basic_auth.clone();
let ctx_clone = ctx.clone(); let ctx_clone = ctx.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = let result = rt.block_on(async {
rt.block_on(async { bulk_restore_servers(host, flow, basic_auth, servers).await }); bulk_restore_servers(host, flow, basic_auth, servers).await
});
let _ = tx.send(result); let _ = tx.send(result);
ctx_clone.request_repaint(); ctx_clone.request_repaint();
}); });
} }
fn start_deprecate_key(&mut self, server: &str, ctx: &egui::Context) { fn start_deprecate_key(&mut self, server: &str, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::DeprecatingKey; self.admin_state.current_operation = AdminOperation::DeprecatingKey;
add_log_entry( add_log_entry(&mut self.operation_log, format!("Deprecating key for server: {}", server));
&mut self.operation_log,
format!("Deprecating key for server: {}", server),
);
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx); self.operation_receiver = Some(rx);
let host = self.settings.host.clone(); let host = self.settings.host.clone();
let flow = self.settings.flow.clone(); let flow = self.settings.flow.clone();
let basic_auth = self.settings.basic_auth.clone(); let basic_auth = self.settings.basic_auth.clone();
let server_name = server.to_string(); let server_name = server.to_string();
let ctx_clone = ctx.clone(); let ctx_clone = ctx.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = let result = rt.block_on(async {
rt.block_on(async { deprecate_key(host, flow, basic_auth, server_name).await }); deprecate_key(host, flow, basic_auth, server_name).await
});
let _ = tx.send(result); let _ = tx.send(result);
ctx_clone.request_repaint(); ctx_clone.request_repaint();
}); });
} }
fn start_restore_key(&mut self, server: &str, ctx: &egui::Context) { fn start_restore_key(&mut self, server: &str, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::RestoringKey; self.admin_state.current_operation = AdminOperation::RestoringKey;
add_log_entry( add_log_entry(&mut self.operation_log, format!("Restoring key for server: {}", server));
&mut self.operation_log,
format!("Restoring key for server: {}", server),
);
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx); self.operation_receiver = Some(rx);
let host = self.settings.host.clone(); let host = self.settings.host.clone();
let flow = self.settings.flow.clone(); let flow = self.settings.flow.clone();
let basic_auth = self.settings.basic_auth.clone(); let basic_auth = self.settings.basic_auth.clone();
let server_name = server.to_string(); let server_name = server.to_string();
let ctx_clone = ctx.clone(); let ctx_clone = ctx.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = let result = rt.block_on(async {
rt.block_on(async { restore_key(host, flow, basic_auth, server_name).await }); restore_key(host, flow, basic_auth, server_name).await
});
let _ = tx.send(result); let _ = tx.send(result);
ctx_clone.request_repaint(); ctx_clone.request_repaint();
}); });
} }
fn start_delete_key(&mut self, server: &str, ctx: &egui::Context) { fn start_delete_key(&mut self, server: &str, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::DeletingKey; self.admin_state.current_operation = AdminOperation::DeletingKey;
add_log_entry( add_log_entry(&mut self.operation_log, format!("Deleting key for server: {}", server));
&mut self.operation_log,
format!("Deleting key for server: {}", server),
);
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx); self.operation_receiver = Some(rx);
let host = self.settings.host.clone(); let host = self.settings.host.clone();
let flow = self.settings.flow.clone(); let flow = self.settings.flow.clone();
let basic_auth = self.settings.basic_auth.clone(); let basic_auth = self.settings.basic_auth.clone();
let server_name = server.to_string(); let server_name = server.to_string();
let ctx_clone = ctx.clone(); let ctx_clone = ctx.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
let result = let result = rt.block_on(async {
rt.block_on(async { delete_key(host, flow, basic_auth, server_name).await }); delete_key(host, flow, basic_auth, server_name).await
});
let _ = tx.send(result); let _ = tx.send(result);
ctx_clone.request_repaint(); ctx_clone.request_repaint();
}); });
@@ -507,19 +453,19 @@ impl SettingsWindow {
/// Apply modern dark theme for the settings window with enhanced styling /// Apply modern dark theme for the settings window with enhanced styling
fn apply_modern_theme(ctx: &egui::Context) { fn apply_modern_theme(ctx: &egui::Context) {
let mut visuals = egui::Visuals::dark(); let mut visuals = egui::Visuals::dark();
// Modern color palette // Modern color palette
visuals.window_fill = egui::Color32::from_gray(18); // Darker background visuals.window_fill = egui::Color32::from_gray(18); // Darker background
visuals.panel_fill = egui::Color32::from_gray(24); // Panel background visuals.panel_fill = egui::Color32::from_gray(24); // Panel background
visuals.faint_bg_color = egui::Color32::from_gray(32); // Card background visuals.faint_bg_color = egui::Color32::from_gray(32); // Card background
visuals.extreme_bg_color = egui::Color32::from_gray(12); // Darkest areas visuals.extreme_bg_color = egui::Color32::from_gray(12); // Darkest areas
// Enhanced widget styling // Enhanced widget styling
visuals.button_frame = true; visuals.button_frame = true;
visuals.collapsing_header_frame = true; visuals.collapsing_header_frame = true;
visuals.indent_has_left_vline = true; visuals.indent_has_left_vline = true;
visuals.striped = true; visuals.striped = true;
// Modern rounded corners // Modern rounded corners
let rounding = egui::Rounding::same(8.0); let rounding = egui::Rounding::same(8.0);
visuals.menu_rounding = rounding; visuals.menu_rounding = rounding;
@@ -528,32 +474,32 @@ fn apply_modern_theme(ctx: &egui::Context) {
visuals.widgets.inactive.rounding = rounding; visuals.widgets.inactive.rounding = rounding;
visuals.widgets.hovered.rounding = rounding; visuals.widgets.hovered.rounding = rounding;
visuals.widgets.active.rounding = rounding; visuals.widgets.active.rounding = rounding;
// Better widget colors // Better widget colors
visuals.widgets.noninteractive.bg_fill = egui::Color32::from_gray(40); visuals.widgets.noninteractive.bg_fill = egui::Color32::from_gray(40);
visuals.widgets.inactive.bg_fill = egui::Color32::from_gray(45); visuals.widgets.inactive.bg_fill = egui::Color32::from_gray(45);
visuals.widgets.hovered.bg_fill = egui::Color32::from_gray(55); visuals.widgets.hovered.bg_fill = egui::Color32::from_gray(55);
visuals.widgets.active.bg_fill = egui::Color32::from_gray(60); visuals.widgets.active.bg_fill = egui::Color32::from_gray(60);
// Subtle borders // Subtle borders
let border_color = egui::Color32::from_gray(60); let border_color = egui::Color32::from_gray(60);
visuals.widgets.noninteractive.bg_stroke = egui::Stroke::new(1.0, border_color); visuals.widgets.noninteractive.bg_stroke = egui::Stroke::new(1.0, border_color);
visuals.widgets.inactive.bg_stroke = egui::Stroke::new(1.0, border_color); visuals.widgets.inactive.bg_stroke = egui::Stroke::new(1.0, border_color);
visuals.widgets.hovered.bg_stroke = egui::Stroke::new(1.5, egui::Color32::from_gray(80)); visuals.widgets.hovered.bg_stroke = egui::Stroke::new(1.5, egui::Color32::from_gray(80));
visuals.widgets.active.bg_stroke = egui::Stroke::new(1.5, egui::Color32::from_gray(100)); visuals.widgets.active.bg_stroke = egui::Stroke::new(1.5, egui::Color32::from_gray(100));
ctx.set_visuals(visuals); ctx.set_visuals(visuals);
} }
/// Render bottom activity log panel /// Render bottom activity log panel
fn render_bottom_activity_log(ui: &mut egui::Ui, operation_log: &mut Vec<String>) { fn render_bottom_activity_log(ui: &mut egui::Ui, operation_log: &mut Vec<String>) {
ui.add_space(18.0); // Larger top padding ui.add_space(18.0); // Larger top padding
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.add_space(8.0); ui.add_space(8.0);
ui.label("📋"); ui.label("📋");
ui.label(egui::RichText::new("Activity Log").size(13.0).strong()); ui.label(egui::RichText::new("Activity Log").size(13.0).strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
ui.add_space(8.0); ui.add_space(8.0);
if ui.small_button("🗑 Clear").clicked() { if ui.small_button("🗑 Clear").clicked() {
@@ -561,13 +507,13 @@ fn render_bottom_activity_log(ui: &mut egui::Ui, operation_log: &mut Vec<String>
} }
}); });
}); });
ui.add_space(8.0); ui.add_space(8.0);
// Add horizontal margin for the text area // Add horizontal margin for the text area
ui.horizontal(|ui| { ui.horizontal(|ui| {
ui.add_space(8.0); // Left margin ui.add_space(8.0); // Left margin
// Show last 5 log entries in multiline text // Show last 5 log entries in multiline text
let log_text = if operation_log.is_empty() { let log_text = if operation_log.is_empty() {
"No recent activity".to_string() "No recent activity".to_string()
@@ -579,14 +525,14 @@ fn render_bottom_activity_log(ui: &mut egui::Ui, operation_log: &mut Vec<String>
}; };
operation_log[start_idx..].join("\n") operation_log[start_idx..].join("\n")
}; };
ui.add_sized( ui.add_sized(
[ui.available_width() - 8.0, 80.0], // Account for right margin [ui.available_width() - 8.0, 80.0], // Account for right margin
egui::TextEdit::multiline(&mut log_text.clone()) egui::TextEdit::multiline(&mut log_text.clone())
.font(egui::FontId::new(11.0, egui::FontFamily::Monospace)) .font(egui::FontId::new(11.0, egui::FontFamily::Monospace))
.interactive(false), .interactive(false)
); );
ui.add_space(8.0); // Right margin ui.add_space(8.0); // Right margin
}); });
} }
@@ -606,7 +552,7 @@ pub fn create_window_icon() -> egui::IconData {
} }
}) })
.collect(); .collect();
egui::IconData { egui::IconData {
rgba: icon_data, rgba: icon_data,
width: icon_size as u32, width: icon_size as u32,
@@ -619,8 +565,8 @@ pub fn run_settings_window() {
let options = eframe::NativeOptions { let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default() viewport: egui::ViewportBuilder::default()
.with_title("KHM Settings") .with_title("KHM Settings")
.with_inner_size([900.0, 905.0]) // Decreased height by another 15px .with_inner_size([900.0, 905.0]) // Decreased height by another 15px
.with_min_inner_size([900.0, 905.0]) // Fixed size .with_min_inner_size([900.0, 905.0]) // Fixed size
.with_max_inner_size([900.0, 905.0]) // Same as min - fixed size .with_max_inner_size([900.0, 905.0]) // Same as min - fixed size
.with_resizable(false) // Disable resizing since window is fixed size .with_resizable(false) // Disable resizing since window is fixed size
.with_icon(create_window_icon()) .with_icon(create_window_icon())
@@ -629,7 +575,7 @@ pub fn run_settings_window() {
centered: true, centered: true,
..Default::default() ..Default::default()
}; };
let _ = eframe::run_native( let _ = eframe::run_native(
"KHM Settings", "KHM Settings",
options, options,

View File

@@ -6,7 +6,10 @@ use notify::RecursiveMode;
use notify_debouncer_mini::{new_debouncer, DebounceEventResult}; use notify_debouncer_mini::{new_debouncer, DebounceEventResult};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
use tray_icon::{menu::MenuEvent, TrayIcon}; use tray_icon::{
menu::MenuEvent,
TrayIcon,
};
use winit::{ use winit::{
application::ApplicationHandler, application::ApplicationHandler,
event_loop::{EventLoop, EventLoopProxy}, event_loop::{EventLoop, EventLoopProxy},
@@ -15,52 +18,12 @@ use winit::{
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use winit::platform::macos::EventLoopBuilderExtMacOS; use winit::platform::macos::EventLoopBuilderExtMacOS;
#[cfg(target_os = "linux")] use super::{SyncStatus, TrayMenuIds, create_tray_icon, update_tray_menu,
use gtk::glib; create_tooltip, start_auto_sync_task, update_sync_status};
use crate::gui::common::{load_settings, get_config_path, perform_sync, KhmSettings};
// Channel for Linux tray communication
#[cfg(target_os = "linux")]
enum LinuxTrayCommand {
CreateTray {
settings: KhmSettings,
sync_status: SyncStatus,
},
UpdateMenu {
settings: KhmSettings,
},
SetTooltip {
tooltip: String,
},
#[allow(dead_code)]
Quit,
}
#[cfg(target_os = "linux")]
enum LinuxTrayResponse {
TrayCreated {
menu_ids: TrayMenuIds,
},
#[allow(dead_code)]
MenuUpdated {
menu_ids: TrayMenuIds,
},
Error(String),
}
use super::{
create_tooltip, create_tray_icon, start_auto_sync_task, update_sync_status, update_tray_menu,
SyncStatus, TrayMenuIds,
};
use crate::gui::common::{get_config_path, load_settings, perform_sync, KhmSettings};
pub struct TrayApplication { pub struct TrayApplication {
#[cfg(not(target_os = "linux"))]
tray_icon: Option<TrayIcon>, tray_icon: Option<TrayIcon>,
#[cfg(target_os = "linux")]
linux_tray_tx: Option<std::sync::mpsc::Sender<LinuxTrayCommand>>,
#[cfg(target_os = "linux")]
linux_tray_handle: Option<std::thread::JoinHandle<()>>,
menu_ids: Option<TrayMenuIds>, menu_ids: Option<TrayMenuIds>,
settings: Arc<Mutex<KhmSettings>>, settings: Arc<Mutex<KhmSettings>>,
sync_status: Arc<Mutex<SyncStatus>>, sync_status: Arc<Mutex<SyncStatus>>,
@@ -73,12 +36,7 @@ pub struct TrayApplication {
impl TrayApplication { impl TrayApplication {
pub fn new(proxy: EventLoopProxy<crate::gui::UserEvent>) -> Self { pub fn new(proxy: EventLoopProxy<crate::gui::UserEvent>) -> Self {
Self { Self {
#[cfg(not(target_os = "linux"))]
tray_icon: None, tray_icon: None,
#[cfg(target_os = "linux")]
linux_tray_tx: None,
#[cfg(target_os = "linux")]
linux_tray_handle: None,
menu_ids: None, menu_ids: None,
settings: Arc::new(Mutex::new(load_settings())), settings: Arc::new(Mutex::new(load_settings())),
sync_status: Arc::new(Mutex::new(SyncStatus::default())), sync_status: Arc::new(Mutex::new(SyncStatus::default())),
@@ -88,33 +46,26 @@ impl TrayApplication {
auto_sync_handle: None, auto_sync_handle: None,
} }
} }
#[cfg(feature = "gui")] #[cfg(feature = "gui")]
fn setup_file_watcher(&mut self) { fn setup_file_watcher(&mut self) {
let config_path = get_config_path(); let config_path = get_config_path();
let (tx, rx) = std::sync::mpsc::channel::<DebounceEventResult>(); let (tx, rx) = std::sync::mpsc::channel::<DebounceEventResult>();
let proxy = self.proxy.clone(); let proxy = self.proxy.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
while let Ok(result) = rx.recv() { while let Ok(result) = rx.recv() {
if let Ok(events) = result { if let Ok(events) = result {
if events if events.iter().any(|e| e.path.to_string_lossy().contains("khm_config.json")) {
.iter()
.any(|e| e.path.to_string_lossy().contains("khm_config.json"))
{
let _ = proxy.send_event(crate::gui::UserEvent::ConfigFileChanged); let _ = proxy.send_event(crate::gui::UserEvent::ConfigFileChanged);
} }
} }
} }
}); });
if let Ok(mut debouncer) = new_debouncer(Duration::from_millis(500), tx) { if let Ok(mut debouncer) = new_debouncer(Duration::from_millis(500), tx) {
if let Some(config_dir) = config_path.parent() { if let Some(config_dir) = config_path.parent() {
if debouncer if debouncer.watcher().watch(config_dir, RecursiveMode::NonRecursive).is_ok() {
.watcher()
.watch(config_dir, RecursiveMode::NonRecursive)
.is_ok()
{
info!("File watcher started"); info!("File watcher started");
self._debouncer = Some(debouncer); self._debouncer = Some(debouncer);
} else { } else {
@@ -123,76 +74,55 @@ impl TrayApplication {
} }
} }
} }
fn handle_config_change(&mut self) { fn handle_config_change(&mut self) {
info!("Config file changed"); info!("Config file changed");
let new_settings = load_settings(); let new_settings = load_settings();
let old_interval = self.settings.lock().unwrap().auto_sync_interval_minutes; let old_interval = self.settings.lock().unwrap().auto_sync_interval_minutes;
let new_interval = new_settings.auto_sync_interval_minutes; let new_interval = new_settings.auto_sync_interval_minutes;
*self.settings.lock().unwrap() = new_settings; *self.settings.lock().unwrap() = new_settings;
// Update menu // Update menu
#[cfg(not(target_os = "linux"))]
if let Some(tray_icon) = &self.tray_icon { if let Some(tray_icon) = &self.tray_icon {
let settings = self.settings.lock().unwrap(); let settings = self.settings.lock().unwrap();
let new_menu_ids = update_tray_menu(tray_icon, &settings); let new_menu_ids = update_tray_menu(tray_icon, &settings);
self.menu_ids = Some(new_menu_ids); self.menu_ids = Some(new_menu_ids);
} }
#[cfg(target_os = "linux")]
if let Some(ref tx) = self.linux_tray_tx {
let settings = self.settings.lock().unwrap().clone();
let _ = tx.send(LinuxTrayCommand::UpdateMenu { settings });
}
// Update tooltip // Update tooltip
self.update_tooltip(); self.update_tooltip();
// Restart auto sync if interval changed // Restart auto sync if interval changed
if old_interval != new_interval { if old_interval != new_interval {
info!( info!("Auto sync interval changed from {} to {} minutes, restarting auto sync", old_interval, new_interval);
"Auto sync interval changed from {} to {} minutes, restarting auto sync",
old_interval, new_interval
);
self.start_auto_sync(); self.start_auto_sync();
} }
} }
fn start_auto_sync(&mut self) { fn start_auto_sync(&mut self) {
if let Some(handle) = self.auto_sync_handle.take() { if let Some(handle) = self.auto_sync_handle.take() {
// Note: In a real implementation, you'd want to properly signal the thread to stop // Note: In a real implementation, you'd want to properly signal the thread to stop
drop(handle); drop(handle);
} }
self.auto_sync_handle = start_auto_sync_task( self.auto_sync_handle = start_auto_sync_task(
Arc::clone(&self.settings), Arc::clone(&self.settings),
Arc::clone(&self.sync_status), Arc::clone(&self.sync_status),
self.proxy.clone(), self.proxy.clone()
); );
} }
fn update_tooltip(&self) { fn update_tooltip(&self) {
let settings = self.settings.lock().unwrap();
let sync_status = self.sync_status.lock().unwrap();
let tooltip = create_tooltip(&settings, &sync_status);
#[cfg(not(target_os = "linux"))]
if let Some(tray_icon) = &self.tray_icon { if let Some(tray_icon) = &self.tray_icon {
let settings = self.settings.lock().unwrap();
let sync_status = self.sync_status.lock().unwrap();
let tooltip = create_tooltip(&settings, &sync_status);
let _ = tray_icon.set_tooltip(Some(&tooltip)); let _ = tray_icon.set_tooltip(Some(&tooltip));
} }
#[cfg(target_os = "linux")]
if let Some(ref tx) = self.linux_tray_tx {
let _ = tx.send(LinuxTrayCommand::SetTooltip { tooltip });
}
} }
fn handle_menu_event( fn handle_menu_event(&mut self, event: MenuEvent, event_loop: &winit::event_loop::ActiveEventLoop) {
&mut self,
event: MenuEvent,
event_loop: &winit::event_loop::ActiveEventLoop,
) {
if let Some(menu_ids) = &self.menu_ids { if let Some(menu_ids) = &self.menu_ids {
if event.id == menu_ids.settings_id { if event.id == menu_ids.settings_id {
info!("Settings menu clicked"); info!("Settings menu clicked");
@@ -206,11 +136,12 @@ impl TrayApplication {
} }
} }
} }
fn launch_settings_window(&self) { fn launch_settings_window(&self) {
if let Ok(exe_path) = std::env::current_exe() { if let Ok(exe_path) = std::env::current_exe() {
std::thread::spawn(move || { std::thread::spawn(move || {
if let Err(e) = std::process::Command::new(&exe_path) if let Err(e) = std::process::Command::new(&exe_path)
.arg("--gui")
.arg("--settings-ui") .arg("--settings-ui")
.spawn() .spawn()
{ {
@@ -219,23 +150,20 @@ impl TrayApplication {
}); });
} }
} }
fn start_manual_sync(&self) { fn start_manual_sync(&self) {
let settings = self.settings.lock().unwrap().clone(); let settings = self.settings.lock().unwrap().clone();
let sync_status_clone: Arc<Mutex<SyncStatus>> = Arc::clone(&self.sync_status); let sync_status_clone: Arc<Mutex<SyncStatus>> = Arc::clone(&self.sync_status);
let proxy_clone = self.proxy.clone(); let proxy_clone = self.proxy.clone();
// Check if settings are valid // Check if settings are valid
if settings.host.is_empty() || settings.flow.is_empty() { if settings.host.is_empty() || settings.flow.is_empty() {
error!("Cannot sync: host or flow not configured"); error!("Cannot sync: host or flow not configured");
return; return;
} }
info!( info!("Syncing with host: {}, flow: {}", settings.host, settings.flow);
"Syncing with host: {}, flow: {}",
settings.host, settings.flow
);
// Run sync in separate thread with its own tokio runtime // Run sync in separate thread with its own tokio runtime
std::thread::spawn(move || { std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
@@ -255,7 +183,7 @@ impl TrayApplication {
}); });
}); });
} }
fn handle_update_menu(&mut self) { fn handle_update_menu(&mut self) {
let settings = self.settings.lock().unwrap(); let settings = self.settings.lock().unwrap();
if !settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place { if !settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place {
@@ -263,7 +191,7 @@ impl TrayApplication {
update_sync_status(&settings, &mut sync_status); update_sync_status(&settings, &mut sync_status);
} }
drop(settings); drop(settings);
self.update_tooltip(); self.update_tooltip();
} }
} }
@@ -274,141 +202,27 @@ impl ApplicationHandler<crate::gui::UserEvent> for TrayApplication {
_event_loop: &winit::event_loop::ActiveEventLoop, _event_loop: &winit::event_loop::ActiveEventLoop,
_window_id: winit::window::WindowId, _window_id: winit::window::WindowId,
_event: winit::event::WindowEvent, _event: winit::event::WindowEvent,
) { ) {}
}
fn resumed(&mut self, _event_loop: &winit::event_loop::ActiveEventLoop) { fn resumed(&mut self, _event_loop: &winit::event_loop::ActiveEventLoop) {
#[cfg(not(target_os = "linux"))]
if self.tray_icon.is_none() { if self.tray_icon.is_none() {
info!("Creating tray icon"); info!("Creating tray icon");
let settings = self.settings.lock().unwrap(); let settings = self.settings.lock().unwrap();
let sync_status = self.sync_status.lock().unwrap(); let sync_status = self.sync_status.lock().unwrap();
let (tray_icon, menu_ids) = create_tray_icon(&settings, &sync_status);
drop(settings);
drop(sync_status);
match std::panic::catch_unwind(|| create_tray_icon(&settings, &sync_status)) { self.tray_icon = Some(tray_icon);
Ok((tray_icon, menu_ids)) => { self.menu_ids = Some(menu_ids);
drop(settings);
drop(sync_status);
self.tray_icon = Some(tray_icon);
self.menu_ids = Some(menu_ids);
self.setup_file_watcher();
self.start_auto_sync();
info!("KHM tray application ready");
}
Err(_) => {
drop(settings);
drop(sync_status);
error!("Failed to create tray icon. This usually means the required system libraries are not installed.");
error!("KHM will exit as system tray integration is required for desktop mode.");
std::process::exit(1);
}
}
}
#[cfg(target_os = "linux")]
if self.linux_tray_tx.is_none() {
info!("Creating tray icon on Linux");
let (tx, rx) = std::sync::mpsc::channel(); self.setup_file_watcher();
let (response_tx, response_rx) = std::sync::mpsc::channel(); self.start_auto_sync();
self.linux_tray_tx = Some(tx.clone()); info!("KHM tray application ready");
let proxy = self.proxy.clone();
// Spawn GTK thread for tray
let handle = std::thread::spawn(move || {
if let Err(e) = gtk::init() {
error!("Failed to initialize GTK: {}", e);
let _ = response_tx.send(LinuxTrayResponse::Error(format!("GTK init failed: {}", e)));
return;
}
let mut tray_icon: Option<TrayIcon> = None;
// Set up GTK event handlers
let _tx_clone = tx.clone();
glib::timeout_add_local(std::time::Duration::from_millis(100), move || {
while let Ok(cmd) = rx.try_recv() {
match cmd {
LinuxTrayCommand::CreateTray { settings, sync_status } => {
match std::panic::catch_unwind(|| create_tray_icon(&settings, &sync_status)) {
Ok((icon, menu_ids)) => {
tray_icon = Some(icon);
let _ = response_tx.send(LinuxTrayResponse::TrayCreated { menu_ids });
}
Err(_) => {
let _ = response_tx.send(LinuxTrayResponse::Error("Failed to create tray".to_string()));
}
}
}
LinuxTrayCommand::UpdateMenu { settings } => {
if let Some(ref icon) = tray_icon {
let menu_ids = update_tray_menu(icon, &settings);
let _ = response_tx.send(LinuxTrayResponse::MenuUpdated { menu_ids });
}
}
LinuxTrayCommand::SetTooltip { tooltip } => {
if let Some(ref icon) = tray_icon {
let _ = icon.set_tooltip(Some(&tooltip));
}
}
LinuxTrayCommand::Quit => {
gtk::main_quit();
return glib::ControlFlow::Break;
}
}
}
// Check for menu events
if let Ok(event) = MenuEvent::receiver().try_recv() {
let _ = proxy.send_event(crate::gui::UserEvent::MenuEvent(event));
}
glib::ControlFlow::Continue
});
gtk::main();
});
self.linux_tray_handle = Some(handle);
// Send command to create tray
let settings = self.settings.lock().unwrap().clone();
let sync_status = self.sync_status.lock().unwrap().clone();
if let Some(ref tx) = self.linux_tray_tx {
let _ = tx.send(LinuxTrayCommand::CreateTray { settings, sync_status });
// Wait for response
match response_rx.recv_timeout(std::time::Duration::from_secs(5)) {
Ok(LinuxTrayResponse::TrayCreated { menu_ids }) => {
self.menu_ids = Some(menu_ids);
self.setup_file_watcher();
self.start_auto_sync();
info!("KHM tray application ready");
}
Ok(LinuxTrayResponse::Error(e)) => {
error!("Failed to create tray icon: {}", e);
error!("This usually means the required system libraries are not installed.");
error!("On Ubuntu/Debian, try installing: sudo apt install libayatana-appindicator3-1");
error!("Alternative: sudo apt install libappindicator3-1");
std::process::exit(1);
}
_ => {
error!("Timeout waiting for tray creation");
std::process::exit(1);
}
}
}
} }
} }
fn user_event( fn user_event(&mut self, event_loop: &winit::event_loop::ActiveEventLoop, event: crate::gui::UserEvent) {
&mut self,
event_loop: &winit::event_loop::ActiveEventLoop,
event: crate::gui::UserEvent,
) {
match event { match event {
crate::gui::UserEvent::TrayIconEvent => {} crate::gui::UserEvent::TrayIconEvent => {}
crate::gui::UserEvent::UpdateMenu => { crate::gui::UserEvent::UpdateMenu => {
@@ -432,45 +246,30 @@ pub async fn run_tray_app() -> std::io::Result<()> {
EventLoop::<crate::gui::UserEvent>::with_user_event() EventLoop::<crate::gui::UserEvent>::with_user_event()
.with_activation_policy(ActivationPolicy::Accessory) .with_activation_policy(ActivationPolicy::Accessory)
.build() .build()
.map_err(|e| { .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("Failed to create event loop: {}", e)))?
std::io::Error::new(
std::io::ErrorKind::Other,
format!("Failed to create event loop: {}", e),
)
})?
}; };
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
let event_loop = EventLoop::<crate::gui::UserEvent>::with_user_event() let event_loop = EventLoop::<crate::gui::UserEvent>::with_user_event().build()
.build() .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("Failed to create event loop: {}", e)))?;
.map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("Failed to create event loop: {}", e),
)
})?;
let proxy = event_loop.create_proxy(); let proxy = event_loop.create_proxy();
// Setup event handlers // Setup event handlers
let proxy_clone = proxy.clone(); let proxy_clone = proxy.clone();
tray_icon::TrayIconEvent::set_event_handler(Some(move |_event| { tray_icon::TrayIconEvent::set_event_handler(Some(move |_event| {
let _ = proxy_clone.send_event(crate::gui::UserEvent::TrayIconEvent); let _ = proxy_clone.send_event(crate::gui::UserEvent::TrayIconEvent);
})); }));
let proxy_clone = proxy.clone(); let proxy_clone = proxy.clone();
MenuEvent::set_event_handler(Some(move |event: MenuEvent| { MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
let _ = proxy_clone.send_event(crate::gui::UserEvent::MenuEvent(event)); let _ = proxy_clone.send_event(crate::gui::UserEvent::MenuEvent(event));
})); }));
let mut app = TrayApplication::new(proxy); let mut app = TrayApplication::new(proxy);
event_loop.run_app(&mut app).map_err(|e| { event_loop.run_app(&mut app)
std::io::Error::new( .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("Event loop error: {:?}", e)))?;
std::io::ErrorKind::Other,
format!("Event loop error: {:?}", e),
)
})?;
Ok(()) Ok(())
} }

View File

@@ -1,10 +1,10 @@
use crate::gui::common::{perform_sync, KhmSettings};
use log::{error, info}; use log::{error, info};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use tray_icon::{ use tray_icon::{
menu::{Menu, MenuId, MenuItem}, menu::{Menu, MenuItem, MenuId},
TrayIcon, TrayIconBuilder, TrayIcon, TrayIconBuilder,
}; };
use crate::gui::common::{KhmSettings, perform_sync};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct SyncStatus { pub struct SyncStatus {
@@ -30,26 +30,21 @@ pub struct TrayMenuIds {
} }
/// Create tray icon with menu /// Create tray icon with menu
pub fn create_tray_icon( pub fn create_tray_icon(settings: &KhmSettings, sync_status: &SyncStatus) -> (TrayIcon, TrayMenuIds) {
settings: &KhmSettings,
sync_status: &SyncStatus,
) -> (TrayIcon, TrayMenuIds) {
// Create simple blue icon // Create simple blue icon
let icon_data: Vec<u8> = (0..32 * 32) let icon_data: Vec<u8> = (0..32*32).flat_map(|i| {
.flat_map(|i| { let y = i / 32;
let y = i / 32; let x = i % 32;
let x = i % 32; if x < 2 || x >= 30 || y < 2 || y >= 30 {
if x < 2 || x >= 30 || y < 2 || y >= 30 { [255, 255, 255, 255] // White border
[255, 255, 255, 255] // White border } else {
} else { [64, 128, 255, 255] // Blue center
[64, 128, 255, 255] // Blue center }
} }).collect();
})
.collect();
let icon = tray_icon::Icon::from_rgba(icon_data, 32, 32).unwrap(); let icon = tray_icon::Icon::from_rgba(icon_data, 32, 32).unwrap();
let menu = Menu::new(); let menu = Menu::new();
// Show current configuration status (static) // Show current configuration status (static)
let host_text = if settings.host.is_empty() { let host_text = if settings.host.is_empty() {
"Host: Not configured" "Host: Not configured"
@@ -57,75 +52,64 @@ pub fn create_tray_icon(
&format!("Host: {}", settings.host) &format!("Host: {}", settings.host)
}; };
menu.append(&MenuItem::new(host_text, false, None)).unwrap(); menu.append(&MenuItem::new(host_text, false, None)).unwrap();
let flow_text = if settings.flow.is_empty() { let flow_text = if settings.flow.is_empty() {
"Flow: Not configured" "Flow: Not configured"
} else { } else {
&format!("Flow: {}", settings.flow) &format!("Flow: {}", settings.flow)
}; };
menu.append(&MenuItem::new(flow_text, false, None)).unwrap(); menu.append(&MenuItem::new(flow_text, false, None)).unwrap();
let is_auto_sync_enabled = let is_auto_sync_enabled = !settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
!settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place; let sync_text = format!("Auto sync: {} ({}min)",
let sync_text = format!( if is_auto_sync_enabled { "On" } else { "Off" },
"Auto sync: {} ({}min)", settings.auto_sync_interval_minutes);
if is_auto_sync_enabled { "On" } else { "Off" }, menu.append(&MenuItem::new(&sync_text, false, None)).unwrap();
settings.auto_sync_interval_minutes
); menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
menu.append(&MenuItem::new(&sync_text, false, None))
.unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
// Sync Now menu item // Sync Now menu item
let sync_item = MenuItem::new( let sync_item = MenuItem::new("Sync Now", !settings.host.is_empty() && !settings.flow.is_empty(), None);
"Sync Now",
!settings.host.is_empty() && !settings.flow.is_empty(),
None,
);
let sync_id = sync_item.id().clone(); let sync_id = sync_item.id().clone();
menu.append(&sync_item).unwrap(); menu.append(&sync_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()) menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
.unwrap();
// Settings menu item // Settings menu item
let settings_item = MenuItem::new("Settings", true, None); let settings_item = MenuItem::new("Settings", true, None);
let settings_id = settings_item.id().clone(); let settings_id = settings_item.id().clone();
menu.append(&settings_item).unwrap(); menu.append(&settings_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()) menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
.unwrap();
// Quit menu item // Quit menu item
let quit_item = MenuItem::new("Quit", true, None); let quit_item = MenuItem::new("Quit", true, None);
let quit_id = quit_item.id().clone(); let quit_id = quit_item.id().clone();
menu.append(&quit_item).unwrap(); menu.append(&quit_item).unwrap();
// Create initial tooltip // Create initial tooltip
let tooltip = create_tooltip(settings, sync_status); let tooltip = create_tooltip(settings, sync_status);
let tray_icon = TrayIconBuilder::new() let tray_icon = TrayIconBuilder::new()
.with_tooltip(&tooltip) .with_tooltip(&tooltip)
.with_icon(icon) .with_icon(icon)
.with_menu(Box::new(menu)) .with_menu(Box::new(menu))
.build() .build()
.unwrap(); .unwrap();
let menu_ids = TrayMenuIds { let menu_ids = TrayMenuIds {
settings_id, settings_id,
quit_id, quit_id,
sync_id, sync_id,
}; };
(tray_icon, menu_ids) (tray_icon, menu_ids)
} }
/// Update tray menu with new settings /// Update tray menu with new settings
pub fn update_tray_menu(tray_icon: &TrayIcon, settings: &KhmSettings) -> TrayMenuIds { pub fn update_tray_menu(tray_icon: &TrayIcon, settings: &KhmSettings) -> TrayMenuIds {
let menu = Menu::new(); let menu = Menu::new();
// Show current configuration status (static) // Show current configuration status (static)
let host_text = if settings.host.is_empty() { let host_text = if settings.host.is_empty() {
"Host: Not configured" "Host: Not configured"
@@ -133,54 +117,43 @@ pub fn update_tray_menu(tray_icon: &TrayIcon, settings: &KhmSettings) -> TrayMen
&format!("Host: {}", settings.host) &format!("Host: {}", settings.host)
}; };
menu.append(&MenuItem::new(host_text, false, None)).unwrap(); menu.append(&MenuItem::new(host_text, false, None)).unwrap();
let flow_text = if settings.flow.is_empty() { let flow_text = if settings.flow.is_empty() {
"Flow: Not configured" "Flow: Not configured"
} else { } else {
&format!("Flow: {}", settings.flow) &format!("Flow: {}", settings.flow)
}; };
menu.append(&MenuItem::new(flow_text, false, None)).unwrap(); menu.append(&MenuItem::new(flow_text, false, None)).unwrap();
let is_auto_sync_enabled = let is_auto_sync_enabled = !settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
!settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place; let sync_text = format!("Auto sync: {} ({}min)",
let sync_text = format!( if is_auto_sync_enabled { "On" } else { "Off" },
"Auto sync: {} ({}min)", settings.auto_sync_interval_minutes);
if is_auto_sync_enabled { "On" } else { "Off" }, menu.append(&MenuItem::new(&sync_text, false, None)).unwrap();
settings.auto_sync_interval_minutes
); menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
menu.append(&MenuItem::new(&sync_text, false, None))
.unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
// Sync Now menu item // Sync Now menu item
let sync_item = MenuItem::new( let sync_item = MenuItem::new("Sync Now", !settings.host.is_empty() && !settings.flow.is_empty(), None);
"Sync Now",
!settings.host.is_empty() && !settings.flow.is_empty(),
None,
);
let sync_id = sync_item.id().clone(); let sync_id = sync_item.id().clone();
menu.append(&sync_item).unwrap(); menu.append(&sync_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()) menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
.unwrap();
// Settings menu item // Settings menu item
let settings_item = MenuItem::new("Settings", true, None); let settings_item = MenuItem::new("Settings", true, None);
let settings_id = settings_item.id().clone(); let settings_id = settings_item.id().clone();
menu.append(&settings_item).unwrap(); menu.append(&settings_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()) menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
.unwrap();
// Quit menu item // Quit menu item
let quit_item = MenuItem::new("Quit", true, None); let quit_item = MenuItem::new("Quit", true, None);
let quit_id = quit_item.id().clone(); let quit_id = quit_item.id().clone();
menu.append(&quit_item).unwrap(); menu.append(&quit_item).unwrap();
tray_icon.set_menu(Some(Box::new(menu))); tray_icon.set_menu(Some(Box::new(menu)));
TrayMenuIds { TrayMenuIds {
settings_id, settings_id,
quit_id, quit_id,
@@ -190,17 +163,14 @@ pub fn update_tray_menu(tray_icon: &TrayIcon, settings: &KhmSettings) -> TrayMen
/// Create tooltip text for tray icon /// Create tooltip text for tray icon
pub fn create_tooltip(settings: &KhmSettings, sync_status: &SyncStatus) -> String { pub fn create_tooltip(settings: &KhmSettings, sync_status: &SyncStatus) -> String {
let mut tooltip = format!( let mut tooltip = format!("KHM - SSH Key Manager\nHost: {}\nFlow: {}", settings.host, settings.flow);
"KHM - SSH Key Manager\nHost: {}\nFlow: {}",
settings.host, settings.flow
);
if let Some(keys_count) = sync_status.last_sync_keys { if let Some(keys_count) = sync_status.last_sync_keys {
tooltip.push_str(&format!("\nLast sync: {} keys", keys_count)); tooltip.push_str(&format!("\nLast sync: {} keys", keys_count));
} else { } else {
tooltip.push_str("\nLast sync: Never"); tooltip.push_str("\nLast sync: Never");
} }
if let Some(seconds) = sync_status.next_sync_in_seconds { if let Some(seconds) = sync_status.next_sync_in_seconds {
if seconds > 60 { if seconds > 60 {
tooltip.push_str(&format!("\nNext sync: {}m {}s", seconds / 60, seconds % 60)); tooltip.push_str(&format!("\nNext sync: {}m {}s", seconds / 60, seconds % 60));
@@ -208,7 +178,7 @@ pub fn create_tooltip(settings: &KhmSettings, sync_status: &SyncStatus) -> Strin
tooltip.push_str(&format!("\nNext sync: {}s", seconds)); tooltip.push_str(&format!("\nNext sync: {}s", seconds));
} }
} }
tooltip tooltip
} }
@@ -216,24 +186,18 @@ pub fn create_tooltip(settings: &KhmSettings, sync_status: &SyncStatus) -> Strin
pub fn start_auto_sync_task( pub fn start_auto_sync_task(
settings: Arc<Mutex<KhmSettings>>, settings: Arc<Mutex<KhmSettings>>,
sync_status: Arc<Mutex<SyncStatus>>, sync_status: Arc<Mutex<SyncStatus>>,
event_sender: winit::event_loop::EventLoopProxy<crate::gui::UserEvent>, event_sender: winit::event_loop::EventLoopProxy<crate::gui::UserEvent>
) -> Option<std::thread::JoinHandle<()>> { ) -> Option<std::thread::JoinHandle<()>> {
let initial_settings = settings.lock().unwrap().clone(); let initial_settings = settings.lock().unwrap().clone();
// Only start auto sync if settings are valid and in_place is enabled // Only start auto sync if settings are valid and in_place is enabled
if initial_settings.host.is_empty() if initial_settings.host.is_empty() || initial_settings.flow.is_empty() || !initial_settings.in_place {
|| initial_settings.flow.is_empty()
|| !initial_settings.in_place
{
info!("Auto sync disabled or settings invalid"); info!("Auto sync disabled or settings invalid");
return None; return None;
} }
info!( info!("Starting auto sync with interval {} minutes", initial_settings.auto_sync_interval_minutes);
"Starting auto sync with interval {} minutes",
initial_settings.auto_sync_interval_minutes
);
let handle = std::thread::spawn(move || { let handle = std::thread::spawn(move || {
// Initial sync on startup // Initial sync on startup
info!("Performing initial sync on startup"); info!("Performing initial sync on startup");
@@ -243,10 +207,7 @@ pub fn start_auto_sync_task(
rt.block_on(async { rt.block_on(async {
match perform_sync(&current_settings).await { match perform_sync(&current_settings).await {
Ok(keys_count) => { Ok(keys_count) => {
info!( info!("Initial sync completed successfully with {} keys", keys_count);
"Initial sync completed successfully with {} keys",
keys_count
);
let mut status = sync_status.lock().unwrap(); let mut status = sync_status.lock().unwrap();
status.last_sync_time = Some(std::time::Instant::now()); status.last_sync_time = Some(std::time::Instant::now());
status.last_sync_keys = Some(keys_count); status.last_sync_keys = Some(keys_count);
@@ -258,28 +219,27 @@ pub fn start_auto_sync_task(
} }
}); });
} }
// Start menu update timer // Start menu update timer
let timer_sender = event_sender.clone(); let timer_sender = event_sender.clone();
std::thread::spawn(move || loop { std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(1)); loop {
let _ = timer_sender.send_event(crate::gui::UserEvent::UpdateMenu); std::thread::sleep(std::time::Duration::from_secs(1));
let _ = timer_sender.send_event(crate::gui::UserEvent::UpdateMenu);
}
}); });
// Periodic sync // Periodic sync
loop { loop {
let interval_minutes = current_settings.auto_sync_interval_minutes; let interval_minutes = current_settings.auto_sync_interval_minutes;
std::thread::sleep(std::time::Duration::from_secs(interval_minutes as u64 * 60)); std::thread::sleep(std::time::Duration::from_secs(interval_minutes as u64 * 60));
let current_settings = settings.lock().unwrap().clone(); let current_settings = settings.lock().unwrap().clone();
if current_settings.host.is_empty() if current_settings.host.is_empty() || current_settings.flow.is_empty() || !current_settings.in_place {
|| current_settings.flow.is_empty()
|| !current_settings.in_place
{
info!("Auto sync stopped due to invalid settings or disabled in_place"); info!("Auto sync stopped due to invalid settings or disabled in_place");
break; break;
} }
info!("Performing scheduled auto sync"); info!("Performing scheduled auto sync");
let rt = tokio::runtime::Runtime::new().unwrap(); let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async { rt.block_on(async {
@@ -298,7 +258,7 @@ pub fn start_auto_sync_task(
}); });
} }
}); });
Some(handle) Some(handle)
} }
@@ -308,7 +268,7 @@ pub fn update_sync_status(settings: &KhmSettings, sync_status: &mut SyncStatus)
if let Some(last_sync) = sync_status.last_sync_time { if let Some(last_sync) = sync_status.last_sync_time {
let elapsed = last_sync.elapsed().as_secs(); let elapsed = last_sync.elapsed().as_secs();
let interval_seconds = settings.auto_sync_interval_minutes as u64 * 60; let interval_seconds = settings.auto_sync_interval_minutes as u64 * 60;
if elapsed < interval_seconds { if elapsed < interval_seconds {
sync_status.next_sync_in_seconds = Some(interval_seconds - elapsed); sync_status.next_sync_in_seconds = Some(interval_seconds - elapsed);
} else { } else {

View File

@@ -2,7 +2,5 @@ mod app;
mod icon; mod icon;
pub use app::*; pub use app::*;
pub use icon::{ pub use icon::{SyncStatus, TrayMenuIds, create_tray_icon, update_tray_menu,
create_tooltip, create_tray_icon, start_auto_sync_task, update_sync_status, update_tray_menu, create_tooltip, start_auto_sync_task, update_sync_status};
SyncStatus, TrayMenuIds,
};

View File

@@ -1,119 +0,0 @@
pub mod client;
pub mod db;
pub mod gui;
pub mod server;
#[cfg(feature = "web")]
pub mod web;
#[cfg(feature = "web-gui")]
pub mod web_gui;
use clap::Parser;
// Common Args structure used by all binaries
#[derive(Parser, Debug, Clone)]
pub struct Args {
/// Run in server mode (default: false)
#[arg(long, help = "Run in server mode")]
pub server: bool,
/// Hide console window and run in background (default: auto when no arguments)
#[arg(long, help = "Hide console window and run in background")]
pub daemon: bool,
/// Run settings UI window
#[arg(long, help = "Run settings UI window")]
pub settings_ui: bool,
/// Update the known_hosts file with keys from the server after sending keys (default: false)
#[arg(
long,
help = "Server mode: Sync the known_hosts file with keys from the server"
)]
pub in_place: bool,
/// Comma-separated list of flows to manage (default: default)
#[arg(long, default_value = "default", value_parser, num_args = 1.., value_delimiter = ',', help = "Server mode: Comma-separated list of flows to manage")]
pub flows: Vec<String>,
/// IP address to bind the server or client to (default: 127.0.0.1)
#[arg(
short,
long,
default_value = "127.0.0.1",
help = "Server mode: IP address to bind the server to"
)]
pub ip: String,
/// Port to bind the server or client to (default: 8080)
#[arg(
short,
long,
default_value = "8080",
help = "Server mode: Port to bind the server to"
)]
pub port: u16,
/// Hostname or IP address of the PostgreSQL database (default: 127.0.0.1)
#[arg(
long,
default_value = "127.0.0.1",
help = "Server mode: Hostname or IP address of the PostgreSQL database"
)]
pub db_host: String,
/// Name of the PostgreSQL database (default: khm)
#[arg(
long,
default_value = "khm",
help = "Server mode: Name of the PostgreSQL database"
)]
pub db_name: String,
/// Username for the PostgreSQL database (required in server mode)
#[arg(
long,
required_if_eq("server", "true"),
help = "Server mode: Username for the PostgreSQL database"
)]
pub db_user: Option<String>,
/// Password for the PostgreSQL database (required in server mode)
#[arg(
long,
required_if_eq("server", "true"),
help = "Server mode: Password for the PostgreSQL database"
)]
pub db_password: Option<String>,
/// Host address of the server to connect to in client mode (required in client mode)
#[arg(
long,
required_if_eq("server", "false"),
help = "Client mode: Full host address of the server to connect to. Like https://khm.example.com"
)]
pub host: Option<String>,
/// Flow name to use on the server
#[arg(
long,
required_if_eq("server", "false"),
help = "Client mode: Flow name to use on the server"
)]
pub flow: Option<String>,
/// Path to the known_hosts file (default: ~/.ssh/known_hosts)
#[arg(
long,
default_value = "~/.ssh/known_hosts",
help = "Client mode: Path to the known_hosts file"
)]
pub known_hosts: String,
/// Basic auth string for client mode. Format: user:pass
#[arg(long, default_value = "", help = "Client mode: Basic Auth credentials")]
pub basic_auth: String,
}
// Re-export WASM functions for wasm-pack
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub use web_gui::wasm::*;

View File

@@ -1,16 +1,21 @@
use khm::{client, server, Args}; mod client;
mod db;
mod server;
mod web;
mod gui;
use clap::Parser; use clap::Parser;
use env_logger; use env_logger;
use log::{error, info}; use log::{error, info};
/// CLI version of KHM - Known Hosts Manager for SSH key management and synchronization /// This application manages SSH keys and flows, either as a server or client.
/// Supports server and client modes without GUI dependencies /// In server mode, it stores keys and flows in a PostgreSQL database.
/// In client mode, it sends keys to the server and can update the known_hosts file with keys from the server.
#[derive(Parser, Debug, Clone)] #[derive(Parser, Debug, Clone)]
#[command( #[command(
author = env!("CARGO_PKG_AUTHORS"), author = env!("CARGO_PKG_AUTHORS"),
version = env!("CARGO_PKG_VERSION"), version = env!("CARGO_PKG_VERSION"),
about = "SSH Host Key Manager (CLI with Server)", about = "SSH Host Key Manager",
long_about = None, long_about = None,
after_help = "Examples:\n\ after_help = "Examples:\n\
\n\ \n\
@@ -22,11 +27,19 @@ use log::{error, info};
\n\ \n\
" "
)] )]
pub struct CliArgs { pub struct Args {
/// Run in server mode (default: false) /// Run in server mode (default: false)
#[arg(long, help = "Run in server mode")] #[arg(long, help = "Run in server mode")]
pub server: bool, pub server: bool,
/// Run with GUI tray interface (default: false)
#[arg(long, help = "Run with GUI tray interface")]
pub gui: bool,
/// Run settings UI window (used with --gui)
#[arg(long, help = "Run settings UI window (used with --gui)")]
pub settings_ui: bool,
/// Update the known_hosts file with keys from the server after sending keys (default: false) /// Update the known_hosts file with keys from the server after sending keys (default: false)
#[arg( #[arg(
long, long,
@@ -117,28 +130,6 @@ pub struct CliArgs {
pub basic_auth: String, pub basic_auth: String,
} }
impl From<CliArgs> for Args {
fn from(cli_args: CliArgs) -> Self {
Args {
server: cli_args.server,
daemon: false,
settings_ui: false,
in_place: cli_args.in_place,
flows: cli_args.flows,
ip: cli_args.ip,
port: cli_args.port,
db_host: cli_args.db_host,
db_name: cli_args.db_name,
db_user: cli_args.db_user,
db_password: cli_args.db_password,
host: cli_args.host,
flow: cli_args.flow,
known_hosts: cli_args.known_hosts,
basic_auth: cli_args.basic_auth,
}
}
}
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
// Configure logging to show only khm logs, filtering out noisy library logs // Configure logging to show only khm logs, filtering out noisy library logs
@@ -147,20 +138,72 @@ async fn main() -> std::io::Result<()> {
.filter_module("khm", log::LevelFilter::Debug) // Our app logs .filter_module("khm", log::LevelFilter::Debug) // Our app logs
.filter_module("actix_web", log::LevelFilter::Info) // Server logs .filter_module("actix_web", log::LevelFilter::Info) // Server logs
.filter_module("reqwest", log::LevelFilter::Warn) // HTTP client .filter_module("reqwest", log::LevelFilter::Warn) // HTTP client
.filter_module("winit", log::LevelFilter::Error) // Window management
.filter_module("egui", log::LevelFilter::Error) // GUI framework
.filter_module("eframe", log::LevelFilter::Error) // GUI framework
.filter_module("tray_icon", log::LevelFilter::Error) // Tray icon
.filter_module("wgpu", log::LevelFilter::Error) // Graphics
.filter_module("naga", log::LevelFilter::Error) // Graphics
.filter_module("glow", log::LevelFilter::Error) // Graphics
.filter_module("tracing", log::LevelFilter::Error) // Tracing spans
.init(); .init();
info!("Starting SSH Key Manager");
info!("Starting SSH Key Manager (CLI)"); let args = Args::parse();
let cli_args = CliArgs::parse(); // Settings UI mode - just show settings window and exit
let args: Args = cli_args.into(); if args.settings_ui {
#[cfg(feature = "gui")]
{
info!("Running settings UI window");
gui::run_settings_window();
return Ok(());
}
#[cfg(not(feature = "gui"))]
{
error!("GUI features not compiled. Install system dependencies and rebuild with --features gui");
return Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"GUI features not compiled"
));
}
}
// Validate arguments - either server mode or client mode with required args // GUI mode has priority
if !args.server && (args.host.is_none() || args.flow.is_none()) { if args.gui {
error!("CLI version requires either --server mode or client mode with --host and --flow arguments"); info!("Running in GUI mode");
return Err(std::io::Error::new( if let Err(e) = gui::run_gui().await {
std::io::ErrorKind::InvalidInput, error!("Failed to run GUI: {}", e);
"Invalid arguments for CLI mode", }
)); return Ok(());
}
// Check if we have the minimum required arguments for server/client mode
if !args.server && !args.gui && (args.host.is_none() || args.flow.is_none()) {
// Neither server mode nor client mode nor GUI mode properly configured
eprintln!("Error: You must specify either server mode (--server), client mode (--host and --flow), or GUI mode (--gui)");
eprintln!();
eprintln!("Examples:");
eprintln!(
" Server mode: {} --server --db-user admin --db-password pass --flows work,home",
env!("CARGO_PKG_NAME")
);
eprintln!(
" Client mode: {} --host https://khm.example.com --flow work",
env!("CARGO_PKG_NAME")
);
eprintln!(
" GUI mode: {} --gui",
env!("CARGO_PKG_NAME")
);
eprintln!(
" Settings window: {} --gui --settings-ui",
env!("CARGO_PKG_NAME")
);
eprintln!();
eprintln!("Use --help for more information.");
std::process::exit(1);
} }
if args.server { if args.server {
@@ -177,4 +220,4 @@ async fn main() -> std::io::Result<()> {
info!("Application has exited"); info!("Application has exited");
Ok(()) Ok(())
} }

View File

@@ -300,69 +300,48 @@ pub async fn run_server(args: crate::Args) -> std::io::Result<()> {
info!("Starting HTTP server on {}:{}", args.ip, args.port); info!("Starting HTTP server on {}:{}", args.ip, args.port);
HttpServer::new(move || { HttpServer::new(move || {
let mut app = App::new() App::new()
.app_data(web::Data::new(flows.clone())) .app_data(web::Data::new(flows.clone()))
.app_data(web::Data::new(db_client.clone())) .app_data(web::Data::new(db_client.clone()))
.app_data(allowed_flows.clone()) .app_data(allowed_flows.clone())
// API routes
.route("/api/version", web::get().to(crate::web::get_version_api))
.route("/api/flows", web::get().to(crate::web::get_flows_api))
.route(
"/{flow_id}/scan-dns",
web::post().to(crate::web::scan_dns_resolution),
)
.route(
"/{flow_id}/bulk-deprecate",
web::post().to(crate::web::bulk_deprecate_servers),
)
.route(
"/{flow_id}/bulk-restore",
web::post().to(crate::web::bulk_restore_servers),
)
.route(
"/{flow_id}/keys/{server}",
web::delete().to(crate::web::delete_key_by_server),
)
.route(
"/{flow_id}/keys/{server}/restore",
web::post().to(crate::web::restore_key_by_server),
)
.route(
"/{flow_id}/keys/{server}/delete",
web::delete().to(crate::web::permanently_delete_key_by_server),
)
// Original API routes // Original API routes
.route("/{flow_id}/keys", web::get().to(get_keys)) .route("/{flow_id}/keys", web::get().to(get_keys))
.route("/{flow_id}/keys", web::post().to(add_keys)); .route("/{flow_id}/keys", web::post().to(add_keys))
// Web interface routes
#[cfg(feature = "web")] .route("/", web::get().to(crate::web::serve_web_interface))
{ .route(
app = app.configure(configure_web_routes); "/static/{filename:.*}",
} web::get().to(crate::web::serve_static_file),
)
app
}) })
.bind((args.ip.as_str(), args.port))? .bind((args.ip.as_str(), args.port))?
.run() .run()
.await .await
} }
#[cfg(feature = "web")]
fn configure_web_routes(cfg: &mut web::ServiceConfig) {
cfg
// API routes
.route("/api/version", web::get().to(crate::web::get_version_api))
.route("/api/flows", web::get().to(crate::web::get_flows_api))
.route(
"/{flow_id}/scan-dns",
web::post().to(crate::web::scan_dns_resolution),
)
.route(
"/{flow_id}/bulk-deprecate",
web::post().to(crate::web::bulk_deprecate_servers),
)
.route(
"/{flow_id}/bulk-restore",
web::post().to(crate::web::bulk_restore_servers),
)
.route(
"/{flow_id}/keys/{server}",
web::delete().to(crate::web::delete_key_by_server),
)
.route(
"/{flow_id}/keys/{server}/restore",
web::post().to(crate::web::restore_key_by_server),
)
.route(
"/{flow_id}/keys/{server}/delete",
web::delete().to(crate::web::permanently_delete_key_by_server),
)
// Web interface routes
.route("/", web::get().to(crate::web::serve_web_interface))
.route(
"/static/{filename:.*}",
web::get().to(crate::web::serve_static_file),
);
// Web GUI routes
cfg.route("/gui", web::get().to(crate::web_gui::serve_egui_interface))
.route("/gui/", web::get().to(crate::web_gui::serve_egui_interface))
.route("/gui/config", web::get().to(crate::web_gui::get_gui_config))
.route("/gui/state", web::get().to(crate::web_gui::get_gui_state))
.route("/gui/settings", web::post().to(crate::web_gui::update_gui_settings))
.route("/wasm/{filename:.*}", web::get().to(crate::web_gui::serve_wasm_file));
}

View File

@@ -1,265 +0,0 @@
// Минимальная WASM библиотека только для egui интерфейса
use wasm_bindgen::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
// Основные структуры данных (копии из main lib)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SshKey {
pub server: String,
pub public_key: String,
#[serde(default)]
pub deprecated: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DnsResult {
pub server: String,
pub resolved: bool,
pub error: Option<String>,
}
#[derive(Debug, Clone)]
pub struct AdminSettings {
pub server_url: String,
pub basic_auth: String,
pub selected_flow: String,
pub auto_refresh: bool,
pub refresh_interval: u32,
}
impl Default for AdminSettings {
fn default() -> Self {
let server_url = {
#[cfg(target_arch = "wasm32")]
{
web_sys::window()
.and_then(|w| w.location().origin().ok())
.unwrap_or_else(|| "http://localhost:8080".to_string())
}
#[cfg(not(target_arch = "wasm32"))]
{
"http://localhost:8080".to_string()
}
};
Self {
server_url,
basic_auth: String::new(),
selected_flow: String::new(),
auto_refresh: false,
refresh_interval: 30,
}
}
}
#[derive(Debug, Clone)]
pub struct AdminState {
pub keys: Vec<SshKey>,
pub filtered_keys: Vec<SshKey>,
pub search_term: String,
pub show_deprecated_only: bool,
pub selected_servers: HashMap<String, bool>,
pub expanded_servers: HashMap<String, bool>,
pub current_operation: String,
}
impl Default for AdminState {
fn default() -> Self {
Self {
keys: Vec::new(),
filtered_keys: Vec::new(),
search_term: String::new(),
show_deprecated_only: false,
selected_servers: HashMap::new(),
expanded_servers: HashMap::new(),
current_operation: String::new(),
}
}
}
impl AdminState {
pub fn filter_keys(&mut self) {
self.filtered_keys = self.keys.iter()
.filter(|key| {
if self.show_deprecated_only && !key.deprecated {
return false;
}
if !self.show_deprecated_only && key.deprecated {
return false;
}
if !self.search_term.is_empty() {
let search_lower = self.search_term.to_lowercase();
return key.server.to_lowercase().contains(&search_lower) ||
key.public_key.to_lowercase().contains(&search_lower);
}
true
})
.cloned()
.collect();
}
}
// Простое egui приложение
pub struct WebAdminApp {
settings: AdminSettings,
admin_state: AdminState,
status_message: String,
}
impl Default for WebAdminApp {
fn default() -> Self {
Self {
settings: AdminSettings::default(),
admin_state: AdminState::default(),
status_message: "Ready".to_string(),
}
}
}
impl eframe::App for WebAdminApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("🔑 KHM Web Admin Panel");
ui.separator();
// Connection Settings
egui::CollapsingHeader::new("⚙️ Connection Settings")
.default_open(true)
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.label("Server URL:");
ui.text_edit_singleline(&mut self.settings.server_url);
});
ui.horizontal(|ui| {
ui.label("Basic Auth:");
ui.add(egui::TextEdit::singleline(&mut self.settings.basic_auth).password(true));
});
ui.horizontal(|ui| {
ui.label("Flow:");
ui.text_edit_singleline(&mut self.settings.selected_flow);
});
ui.horizontal(|ui| {
if ui.button("Test Connection").clicked() {
self.status_message = "Testing connection... (WASM demo mode)".to_string();
}
if ui.button("Load Keys").clicked() {
// Add demo data
self.admin_state.keys = vec![
SshKey {
server: "demo-server-1".to_string(),
public_key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC demo key 1".to_string(),
deprecated: false,
},
SshKey {
server: "demo-server-2".to_string(),
public_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 demo key 2".to_string(),
deprecated: true,
},
];
self.admin_state.filter_keys();
self.status_message = format!("Loaded {} demo keys", self.admin_state.keys.len());
}
});
});
ui.add_space(10.0);
// Keys display
if !self.admin_state.filtered_keys.is_empty() {
egui::CollapsingHeader::new("🔑 SSH Keys")
.default_open(true)
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.label("Search:");
let search_response = ui.text_edit_singleline(&mut self.admin_state.search_term);
if search_response.changed() {
self.admin_state.filter_keys();
}
});
ui.horizontal(|ui| {
if ui.selectable_label(!self.admin_state.show_deprecated_only, "✅ Active").clicked() {
self.admin_state.show_deprecated_only = false;
self.admin_state.filter_keys();
}
if ui.selectable_label(self.admin_state.show_deprecated_only, "❗ Deprecated").clicked() {
self.admin_state.show_deprecated_only = true;
self.admin_state.filter_keys();
}
});
ui.separator();
for key in &self.admin_state.filtered_keys {
ui.group(|ui| {
ui.horizontal(|ui| {
if key.deprecated {
ui.colored_label(egui::Color32::RED, "❗ DEPRECATED");
} else {
ui.colored_label(egui::Color32::GREEN, "✅ ACTIVE");
}
ui.label(&key.server);
ui.monospace(&key.public_key[..50.min(key.public_key.len())]);
if ui.small_button("Copy").clicked() {
ui.output_mut(|o| o.copied_text = key.public_key.clone());
}
});
});
}
});
}
ui.add_space(10.0);
// Status
ui.horizontal(|ui| {
ui.label("Status:");
ui.colored_label(egui::Color32::LIGHT_BLUE, &self.status_message);
});
// Info
ui.separator();
ui.label(" This is a demo WASM version. For full functionality, the server API integration is needed.");
});
}
}
/// WASM entry point
#[wasm_bindgen]
pub fn start_web_admin(canvas_id: &str) -> Result<(), JsValue> {
console_error_panic_hook::set_once();
tracing_wasm::set_as_global_default();
let web_options = eframe::WebOptions::default();
let canvas_id = canvas_id.to_string();
wasm_bindgen_futures::spawn_local(async move {
let app = WebAdminApp::default();
let result = eframe::WebRunner::new()
.start(
&canvas_id,
web_options,
Box::new(|_cc| Ok(Box::new(app))),
)
.await;
match result {
Ok(_) => web_sys::console::log_1(&"eframe started successfully".into()),
Err(e) => web_sys::console::error_1(&format!("Failed to start eframe: {:?}", e).into()),
}
});
Ok(())
}
#[wasm_bindgen(start)]
pub fn wasm_main() {
console_error_panic_hook::set_once();
}

View File

@@ -1,14 +1,14 @@
use actix_web::{web, HttpResponse, Result}; use actix_web::{web, HttpResponse, Result};
use futures::future;
use log::info; use log::info;
use rust_embed::RustEmbed; use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
use serde_json::json; use serde_json::json;
use std::sync::Arc; use std::sync::Arc;
use trust_dns_resolver::TokioAsyncResolver;
use trust_dns_resolver::config::*;
use serde::{Deserialize, Serialize};
use futures::future;
use tokio::sync::Semaphore; use tokio::sync::Semaphore;
use tokio::time::{timeout, Duration}; use tokio::time::{timeout, Duration};
use trust_dns_resolver::config::*;
use trust_dns_resolver::TokioAsyncResolver;
use crate::db::ReconnectingDbClient; use crate::db::ReconnectingDbClient;
use crate::server::Flows; use crate::server::Flows;
@@ -17,7 +17,7 @@ use crate::server::Flows;
#[folder = "static/"] #[folder = "static/"]
struct StaticAssets; struct StaticAssets;
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug)]
pub struct DnsResolutionResult { pub struct DnsResolutionResult {
pub server: String, pub server: String,
pub resolved: bool, pub resolved: bool,
@@ -41,7 +41,10 @@ async fn check_dns_resolution(hostname: String, semaphore: Arc<Semaphore>) -> Dn
} }
}; };
let resolver = TokioAsyncResolver::tokio(ResolverConfig::default(), ResolverOpts::default()); let resolver = TokioAsyncResolver::tokio(
ResolverConfig::default(),
ResolverOpts::default(),
);
let lookup_result = timeout(Duration::from_secs(5), resolver.lookup_ip(&hostname)).await; let lookup_result = timeout(Duration::from_secs(5), resolver.lookup_ip(&hostname)).await;
@@ -85,10 +88,7 @@ pub async fn scan_dns_resolution(
) -> Result<HttpResponse> { ) -> Result<HttpResponse> {
let flow_id_str = path.into_inner(); let flow_id_str = path.into_inner();
info!( info!("API request to scan DNS resolution for flow '{}'" , flow_id_str);
"API request to scan DNS resolution for flow '{}'",
flow_id_str
);
if !allowed_flows.contains(&flow_id_str) { if !allowed_flows.contains(&flow_id_str) {
return Ok(HttpResponse::Forbidden().json(json!({ return Ok(HttpResponse::Forbidden().json(json!({
@@ -114,10 +114,7 @@ pub async fn scan_dns_resolution(
drop(flows_guard); drop(flows_guard);
info!( info!("Scanning DNS resolution for {} unique hosts", hostnames.len());
"Scanning DNS resolution for {} unique hosts",
hostnames.len()
);
// Limit concurrent DNS requests to prevent "too many open files" error // Limit concurrent DNS requests to prevent "too many open files" error
let semaphore = Arc::new(Semaphore::new(20)); let semaphore = Arc::new(Semaphore::new(20));
@@ -131,11 +128,7 @@ pub async fn scan_dns_resolution(
let results = future::join_all(scan_futures).await; let results = future::join_all(scan_futures).await;
let unresolved_count = results.iter().filter(|r| !r.resolved).count(); let unresolved_count = results.iter().filter(|r| !r.resolved).count();
info!( info!("DNS scan complete: {} unresolved out of {} hosts", unresolved_count, results.len());
"DNS scan complete: {} unresolved out of {} hosts",
unresolved_count,
results.len()
);
Ok(HttpResponse::Ok().json(json!({ Ok(HttpResponse::Ok().json(json!({
"results": results, "results": results,
@@ -154,11 +147,7 @@ pub async fn bulk_deprecate_servers(
) -> Result<HttpResponse> { ) -> Result<HttpResponse> {
let flow_id_str = path.into_inner(); let flow_id_str = path.into_inner();
info!( info!("API request to bulk deprecate {} servers in flow '{}'", request.servers.len(), flow_id_str);
"API request to bulk deprecate {} servers in flow '{}'",
request.servers.len(),
flow_id_str
);
if !allowed_flows.contains(&flow_id_str) { if !allowed_flows.contains(&flow_id_str) {
return Ok(HttpResponse::Forbidden().json(json!({ return Ok(HttpResponse::Forbidden().json(json!({
@@ -172,11 +161,7 @@ pub async fn bulk_deprecate_servers(
.await .await
{ {
Ok(count) => { Ok(count) => {
info!( info!("Bulk deprecated {} key(s) for {} servers", count, request.servers.len());
"Bulk deprecated {} key(s) for {} servers",
count,
request.servers.len()
);
count count
} }
Err(e) => { Err(e) => {
@@ -218,11 +203,7 @@ pub async fn bulk_restore_servers(
) -> Result<HttpResponse> { ) -> Result<HttpResponse> {
let flow_id_str = path.into_inner(); let flow_id_str = path.into_inner();
info!( info!("API request to bulk restore {} servers in flow '{}'", request.servers.len(), flow_id_str);
"API request to bulk restore {} servers in flow '{}'",
request.servers.len(),
flow_id_str
);
if !allowed_flows.contains(&flow_id_str) { if !allowed_flows.contains(&flow_id_str) {
return Ok(HttpResponse::Forbidden().json(json!({ return Ok(HttpResponse::Forbidden().json(json!({
@@ -236,11 +217,7 @@ pub async fn bulk_restore_servers(
.await .await
{ {
Ok(count) => { Ok(count) => {
info!( info!("Bulk restored {} key(s) for {} servers", count, request.servers.len());
"Bulk restored {} key(s) for {} servers",
count,
request.servers.len()
);
count count
} }
Err(e) => { Err(e) => {

View File

@@ -1,288 +0,0 @@
use actix_web::{HttpResponse, Result, web};
use serde_json::json;
use log::info;
#[cfg(feature = "web-gui")]
pub mod app;
#[cfg(feature = "web-gui")]
pub mod state;
#[cfg(feature = "web-gui")]
pub mod ui;
#[cfg(all(feature = "web-gui", not(target_arch = "wasm32")))]
pub mod api;
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub mod wasm_api;
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub mod wasm;
/// Serve the egui web GUI interface
pub async fn serve_egui_interface() -> Result<HttpResponse> {
#[cfg(feature = "web-gui")]
{
let html = r#"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>KHM Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: #2b2b2b;
font-family: system-ui, sans-serif;
}
canvas {
width: 100vw;
height: 100vh;
display: block;
}
#loading {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 18px;
z-index: 1000;
text-align: center;
}
.spinner {
border: 3px solid rgba(255,255,255,0.3);
border-radius: 50%;
border-top: 3px solid #667eea;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 0 auto 20px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div id="loading">
<div class="spinner"></div>
Loading KHM Admin Panel...
</div>
<canvas id="the_canvas_id"></canvas>
<script type="module">
import init, { start_web_admin } from './wasm/khm_wasm.js';
async function run() {
try {
// Initialize WASM module
await init();
// Hide loading indicator
document.getElementById('loading').style.display = 'none';
// Start the egui web app
start_web_admin('the_canvas_id');
console.log('KHM Web Admin Panel started successfully');
} catch (error) {
console.error('Failed to start KHM Web Admin Panel:', error);
// Show error message
document.getElementById('loading').innerHTML = `
<div style="color: #ff6b6b; text-align: center;">
<h3>⚠️ WASM Module Not Available</h3>
<p>The egui web interface requires WASM compilation.</p>
<p style="font-size: 14px; color: #ccc; margin: 20px 0;">Build steps:</p>
<div style="background: #333; padding: 15px; border-radius: 5px; font-family: monospace; text-align: left; max-width: 600px; margin: 0 auto;">
<div style="color: #888; margin-bottom: 10px;"># Install wasm-pack</div>
<div style="color: #fff;">cargo install wasm-pack</div>
<div style="color: #888; margin: 10px 0;"># Build WASM module</div>
<div style="color: #fff;">wasm-pack build --target web --out-dir wasm --features web-gui</div>
<div style="color: #888; margin: 10px 0;"># Restart server</div>
<div style="color: #fff;">cargo run --features "server,web,web-gui"</div>
</div>
<p style="font-size: 12px; color: #888; margin-top: 20px;">Error: ${error.message}</p>
</div>
`;
}
}
run();
</script>
</body>
</html>
"#;
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(html))
}
#[cfg(not(feature = "web-gui"))]
{
let html = r#"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>KHM Admin Panel - Not Available</title>
<style>
body {
font-family: system-ui, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
text-align: center;
}
</style>
</head>
<body>
<div>
<h1>⚠️ Web GUI Not Available</h1>
<p>This server was compiled without web-gui support.</p>
<p>Please rebuild with <code>--features web-gui</code> to enable the admin interface.</p>
</div>
</body>
</html>
"#;
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(html))
}
}
/// API endpoint to get GUI configuration
pub async fn get_gui_config(
flows: web::Data<crate::server::Flows>,
allowed_flows: web::Data<Vec<String>>,
) -> Result<HttpResponse> {
info!("Web GUI config requested");
let flows_guard = flows.lock().unwrap();
let available_flows: Vec<String> = flows_guard.iter().map(|f| f.name.clone()).collect();
Ok(HttpResponse::Ok().json(json!({
"version": env!("CARGO_PKG_VERSION"),
"gui_ready": cfg!(feature = "web-gui"),
"features": ["key_management", "bulk_operations", "real_time_updates"],
"available_flows": available_flows,
"allowed_flows": &**allowed_flows,
"api_endpoints": {
"flows": "/api/flows",
"keys": "/{flow}/keys",
"deprecate": "/{flow}/keys/{server}",
"restore": "/{flow}/keys/{server}/restore",
"delete": "/{flow}/keys/{server}/delete",
"bulk_deprecate": "/{flow}/bulk-deprecate",
"bulk_restore": "/{flow}/bulk-restore",
"dns_scan": "/{flow}/scan-dns"
}
})))
}
/// API endpoint for web GUI state management
pub async fn get_gui_state(
flows: web::Data<crate::server::Flows>,
allowed_flows: web::Data<Vec<String>>,
) -> Result<HttpResponse> {
info!("Web GUI state requested");
let flows_guard = flows.lock().unwrap();
let flow_data: Vec<_> = flows_guard.iter().map(|f| json!({
"name": f.name,
"servers_count": f.servers.len(),
"active_keys": f.servers.iter().filter(|k| !k.deprecated).count(),
"deprecated_keys": f.servers.iter().filter(|k| k.deprecated).count()
})).collect();
Ok(HttpResponse::Ok().json(json!({
"flows": flow_data,
"allowed_flows": &**allowed_flows,
"timestamp": chrono::Utc::now().to_rfc3339()
})))
}
/// API endpoint to update GUI settings
pub async fn update_gui_settings(
settings: web::Json<serde_json::Value>,
) -> Result<HttpResponse> {
info!("Web GUI settings updated: {:?}", settings);
Ok(HttpResponse::Ok().json(json!({
"status": "success",
"message": "Settings updated successfully",
"timestamp": chrono::Utc::now().to_rfc3339()
})))
}
/// Serve WASM files for egui web application
pub async fn serve_wasm_file(path: web::Path<String>) -> Result<HttpResponse> {
let filename = path.into_inner();
info!("WASM file requested: {}", filename);
// Try to read the actual WASM files from the wasm directory
let wasm_dir = std::path::Path::new("wasm");
let file_path = wasm_dir.join(&filename);
match std::fs::read(&file_path) {
Ok(content) => {
let content_type = if filename.ends_with(".js") {
"application/javascript; charset=utf-8"
} else if filename.ends_with(".wasm") {
"application/wasm"
} else {
"application/octet-stream"
};
info!("Serving WASM file: {} ({} bytes)", filename, content.len());
Ok(HttpResponse::Ok()
.content_type(content_type)
.body(content))
}
Err(_) => {
// Fallback to placeholder if files don't exist
let content = match filename.as_str() {
"khm_wasm.js" => {
r#"
// KHM WASM Module Not Found
// Build the WASM module first:
// cd khm-wasm && wasm-pack build --target web --out-dir ../wasm
export default function init() {
return Promise.reject(new Error('WASM module not found. Run: cd khm-wasm && wasm-pack build --target web --out-dir ../wasm'));
}
export function start_web_admin(canvas_id) {
throw new Error('WASM module not found. Run: cd khm-wasm && wasm-pack build --target web --out-dir ../wasm');
}
"#
}
_ => {
return Ok(HttpResponse::NotFound().json(json!({
"error": "WASM file not found",
"filename": filename,
"message": "Run: cd khm-wasm && wasm-pack build --target web --out-dir ../wasm"
})));
}
};
Ok(HttpResponse::Ok()
.content_type("application/javascript; charset=utf-8")
.body(content))
}
}
}

View File

@@ -1,399 +0,0 @@
use super::state::{SshKey, DnsResult, AdminSettings};
use log::info;
use reqwest::Client;
use std::time::Duration;
/// Create HTTP client for API requests
fn create_http_client() -> Result<Client, String> {
Client::builder()
.timeout(Duration::from_secs(30))
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|e| format!("Failed to create HTTP client: {}", e))
}
/// Add basic auth to request if provided
fn add_auth_if_needed(
request: reqwest::RequestBuilder,
basic_auth: &str,
) -> Result<reqwest::RequestBuilder, String> {
if basic_auth.is_empty() {
return Ok(request);
}
let auth_parts: Vec<&str> = basic_auth.splitn(2, ':').collect();
if auth_parts.len() == 2 {
Ok(request.basic_auth(auth_parts[0], Some(auth_parts[1])))
} else {
Err("Basic auth format should be 'username:password'".to_string())
}
}
/// Check response status for errors
fn check_response_status(response: &reqwest::Response) -> Result<(), String> {
let status = response.status().as_u16();
if status == 401 {
return Err("Authentication required. Please provide valid basic auth credentials.".to_string());
}
if status >= 300 && status < 400 {
return Err("Server redirects to login page. Authentication may be required.".to_string());
}
if !response.status().is_success() {
return Err(format!(
"Server returned error: {} {}",
status,
response.status().canonical_reason().unwrap_or("Unknown")
));
}
Ok(())
}
/// Check if response is HTML instead of JSON
fn check_html_response(body: &str) -> Result<(), String> {
if body.trim_start().starts_with("<!DOCTYPE") || body.trim_start().starts_with("<html") {
return Err("Server returned HTML page instead of JSON. This usually means authentication is required or the endpoint is incorrect.".to_string());
}
Ok(())
}
/// Get application version from API
pub async fn get_version(settings: &AdminSettings) -> Result<String, String> {
if settings.server_url.is_empty() {
return Err("Server URL must be specified".to_string());
}
let url = format!("{}/api/version", settings.server_url.trim_end_matches('/'));
info!("Getting version from: {}", url);
let client = create_http_client()?;
let mut request = client.get(&url);
request = add_auth_if_needed(request, &settings.basic_auth)?;
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
check_html_response(&body)?;
let version_response: serde_json::Value = serde_json::from_str(&body)
.map_err(|e| format!("Failed to parse version: {}", e))?;
let version = version_response
.get("version")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
info!("KHM server version: {}", version);
Ok(version)
}
/// Test connection to KHM server using existing API endpoint
pub async fn test_connection(settings: &AdminSettings) -> Result<String, String> {
if settings.server_url.is_empty() || settings.selected_flow.is_empty() {
return Err("Server URL and flow must be specified".to_string());
}
let url = format!(
"{}/{}/keys",
settings.server_url.trim_end_matches('/'),
settings.selected_flow
);
info!("Testing connection to: {}", url);
let client = create_http_client()?;
let mut request = client.get(&url);
request = add_auth_if_needed(request, &settings.basic_auth)?;
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
check_html_response(&body)?;
let keys: Vec<SshKey> = serde_json::from_str(&body)
.map_err(|e| format!("Failed to parse response: {}", e))?;
let message = format!("Connection successful! Found {} SSH keys from flow '{}'", keys.len(), settings.selected_flow);
info!("{}", message);
Ok(message)
}
/// Load available flows from server
pub async fn load_flows(settings: &AdminSettings) -> Result<Vec<String>, String> {
if settings.server_url.is_empty() {
return Err("Server URL must be specified".to_string());
}
let url = format!("{}/api/flows", settings.server_url.trim_end_matches('/'));
info!("Loading flows from: {}", url);
let client = create_http_client()?;
let mut request = client.get(&url);
request = add_auth_if_needed(request, &settings.basic_auth)?;
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
check_html_response(&body)?;
let flows: Vec<String> = serde_json::from_str(&body)
.map_err(|e| format!("Failed to parse flows: {}", e))?;
info!("Loaded {} flows", flows.len());
Ok(flows)
}
/// Fetch all SSH keys including deprecated ones using existing API endpoint
pub async fn fetch_keys(settings: &AdminSettings) -> Result<Vec<SshKey>, String> {
if settings.server_url.is_empty() || settings.selected_flow.is_empty() {
return Err("Server URL and flow must be specified".to_string());
}
let url = format!(
"{}/{}/keys",
settings.server_url.trim_end_matches('/'),
settings.selected_flow
);
info!("Fetching keys from: {}", url);
let client = create_http_client()?;
let mut request = client.get(&url);
request = add_auth_if_needed(request, &settings.basic_auth)?;
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
check_html_response(&body)?;
let keys: Vec<SshKey> = serde_json::from_str(&body)
.map_err(|e| format!("Failed to parse keys: {}", e))?;
info!("Fetched {} SSH keys", keys.len());
Ok(keys)
}
/// Deprecate a key for a specific server
pub async fn deprecate_key(
settings: &AdminSettings,
server: &str,
) -> Result<String, String> {
let url = format!(
"{}/{}/keys/{}",
settings.server_url.trim_end_matches('/'),
settings.selected_flow,
urlencoding::encode(server)
);
info!("Deprecating key for server '{}' at: {}", server, url);
let client = create_http_client()?;
let mut request = client.delete(&url);
request = add_auth_if_needed(request, &settings.basic_auth)?;
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
Ok(format!("Successfully deprecated key for server '{}'", server))
}
/// Restore a key for a specific server
pub async fn restore_key(
settings: &AdminSettings,
server: &str,
) -> Result<String, String> {
let url = format!(
"{}/{}/keys/{}/restore",
settings.server_url.trim_end_matches('/'),
settings.selected_flow,
urlencoding::encode(server)
);
info!("Restoring key for server '{}' at: {}", server, url);
let client = create_http_client()?;
let mut request = client.post(&url);
request = add_auth_if_needed(request, &settings.basic_auth)?;
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
Ok(format!("Successfully restored key for server '{}'", server))
}
/// Delete a key permanently for a specific server
pub async fn delete_key(
settings: &AdminSettings,
server: &str,
) -> Result<String, String> {
let url = format!(
"{}/{}/keys/{}/delete",
settings.server_url.trim_end_matches('/'),
settings.selected_flow,
urlencoding::encode(server)
);
info!("Permanently deleting key for server '{}' at: {}", server, url);
let client = create_http_client()?;
let mut request = client.delete(&url);
request = add_auth_if_needed(request, &settings.basic_auth)?;
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
Ok(format!("Successfully deleted key for server '{}'", server))
}
/// Bulk deprecate multiple servers
pub async fn bulk_deprecate_servers(
settings: &AdminSettings,
servers: Vec<String>,
) -> Result<String, String> {
let url = format!(
"{}/{}/bulk-deprecate",
settings.server_url.trim_end_matches('/'),
settings.selected_flow
);
info!("Bulk deprecating {} servers at: {}", servers.len(), url);
let client = create_http_client()?;
let mut request = client.post(&url).json(&serde_json::json!({
"servers": servers
}));
request = add_auth_if_needed(request, &settings.basic_auth)?;
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
Ok("Successfully deprecated selected servers".to_string())
}
/// Bulk restore multiple servers
pub async fn bulk_restore_servers(
settings: &AdminSettings,
servers: Vec<String>,
) -> Result<String, String> {
let url = format!(
"{}/{}/bulk-restore",
settings.server_url.trim_end_matches('/'),
settings.selected_flow
);
info!("Bulk restoring {} servers at: {}", servers.len(), url);
let client = create_http_client()?;
let mut request = client.post(&url).json(&serde_json::json!({
"servers": servers
}));
request = add_auth_if_needed(request, &settings.basic_auth)?;
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
Ok("Successfully restored selected servers".to_string())
}
/// Scan DNS resolution for servers using existing API endpoint
pub async fn scan_dns_resolution(
settings: &AdminSettings,
) -> Result<Vec<DnsResult>, String> {
let url = format!(
"{}/{}/scan-dns",
settings.server_url.trim_end_matches('/'),
settings.selected_flow
);
info!("Scanning DNS resolution at: {}", url);
let client = create_http_client()?;
let mut request = client.post(&url);
request = add_auth_if_needed(request, &settings.basic_auth)?;
let response = request
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
.map_err(|e| format!("Failed to read response: {}", e))?;
// Parse the response format from existing API: {"results": [...], "total": N, "unresolved": N}
let api_response: serde_json::Value = serde_json::from_str(&body)
.map_err(|e| format!("Failed to parse DNS response: {}", e))?;
let results = api_response
.get("results")
.and_then(|r| serde_json::from_value(r.clone()).ok())
.unwrap_or_else(Vec::new);
info!("DNS scan completed for {} servers", results.len());
Ok(results)
}

View File

@@ -1,590 +0,0 @@
use super::state::{AdminSettings, AdminState, ConnectionStatus, AdminOperation};
use super::ui::{self, ConnectionAction, KeyAction, BulkAction};
#[cfg(not(target_arch = "wasm32"))]
use super::api;
#[cfg(target_arch = "wasm32")]
use super::wasm_api as api;
use eframe::egui;
use std::sync::mpsc;
pub struct WebAdminApp {
settings: AdminSettings,
admin_state: AdminState,
flows: Vec<String>,
connection_status: ConnectionStatus,
operation_receiver: Option<mpsc::Receiver<AdminOperation>>,
last_operation: String,
server_version: Option<String>,
}
impl Default for WebAdminApp {
fn default() -> Self {
// Get server URL from current location if possible
let server_url = {
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
web_sys::window()
.and_then(|w| w.location().origin().ok())
.unwrap_or_else(|| "http://localhost:8080".to_string())
}
#[cfg(not(all(target_arch = "wasm32", feature = "web-gui")))]
{
"http://localhost:8080".to_string()
}
};
Self {
settings: AdminSettings {
server_url,
..Default::default()
},
admin_state: AdminState::default(),
flows: Vec::new(),
connection_status: ConnectionStatus::Disconnected,
operation_receiver: None,
last_operation: "Application started".to_string(),
server_version: None,
}
}
}
impl eframe::App for WebAdminApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
// Handle async operations
if let Some(receiver) = &self.operation_receiver {
if let Ok(operation) = receiver.try_recv() {
self.handle_operation_result(operation);
ctx.request_repaint();
}
}
// Use the same UI structure as desktop version
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("🔑 KHM Web Admin Panel");
ui.separator();
// Connection Settings (always visible for web version)
egui::CollapsingHeader::new("⚙️ Connection Settings")
.default_open(matches!(self.connection_status, ConnectionStatus::Disconnected))
.show(ui, |ui| {
let connection_action = ui::render_connection_settings(
ui,
&mut self.settings,
&self.connection_status,
&self.flows,
&self.server_version,
);
match connection_action {
ConnectionAction::LoadFlows => self.load_flows(ctx),
ConnectionAction::TestConnection => self.test_connection(ctx),
ConnectionAction::LoadKeys => self.load_keys(ctx),
ConnectionAction::LoadVersion => self.load_version(ctx),
ConnectionAction::None => {}
}
});
ui.add_space(10.0);
// Statistics (from desktop version)
if !self.admin_state.keys.is_empty() {
ui::render_statistics(ui, &self.admin_state);
ui.add_space(10.0);
}
// Key Management (from desktop version)
if !self.admin_state.keys.is_empty() {
egui::CollapsingHeader::new("🔑 Key Management")
.default_open(true)
.show(ui, |ui| {
// Search and filter controls (from desktop version)
ui::render_search_controls(ui, &mut self.admin_state);
ui.add_space(5.0);
// Bulk actions (from desktop version)
let bulk_action = ui::render_bulk_actions(ui, &mut self.admin_state);
match bulk_action {
BulkAction::DeprecateSelected => self.bulk_deprecate(ctx),
BulkAction::RestoreSelected => self.bulk_restore(ctx),
BulkAction::ClearSelection => {
self.admin_state.clear_selection();
}
BulkAction::None => {}
}
ui.add_space(5.0);
// Keys table (from desktop version)
let key_action = ui::render_keys_table(ui, &mut self.admin_state);
match key_action {
KeyAction::DeprecateKey(server) => self.deprecate_key(server, ctx),
KeyAction::RestoreKey(server) => self.restore_key(server, ctx),
KeyAction::DeleteKey(server) => self.delete_key(server, ctx),
KeyAction::DeprecateServer(server) => self.deprecate_server(server, ctx),
KeyAction::RestoreServer(server) => self.restore_server(server, ctx),
KeyAction::None => {}
}
});
ui.add_space(10.0);
}
// Additional web-specific actions
if matches!(self.connection_status, ConnectionStatus::Connected) && !self.settings.selected_flow.is_empty() {
ui.horizontal(|ui| {
if ui.button("🔍 Scan DNS").clicked() {
self.scan_dns(ctx);
}
if ui.button("🔄 Refresh Keys").clicked() {
self.load_keys(ctx);
}
ui.checkbox(&mut self.settings.auto_refresh, "Auto-refresh");
});
ui.add_space(10.0);
}
// Status bar (from desktop version)
ui.horizontal(|ui| {
ui.label("Status:");
match &self.connection_status {
ConnectionStatus::Connected => {
ui.colored_label(egui::Color32::GREEN, "● Connected");
}
ConnectionStatus::Connecting => {
ui.colored_label(egui::Color32::YELLOW, "● Connecting...");
}
ConnectionStatus::Disconnected => {
ui.colored_label(egui::Color32::GRAY, "● Disconnected");
}
ConnectionStatus::Error(msg) => {
ui.colored_label(egui::Color32::RED, format!("● Error: {}", msg));
}
}
ui.separator();
ui.label(&self.last_operation);
});
});
// Auto-refresh like desktop version
if self.settings.auto_refresh && matches!(self.connection_status, ConnectionStatus::Connected) {
ctx.request_repaint_after(std::time::Duration::from_secs(self.settings.refresh_interval as u64));
}
}
}
impl WebAdminApp {
fn handle_operation_result(&mut self, operation: AdminOperation) {
match operation {
AdminOperation::LoadFlows(result) => {
match result {
Ok(flows) => {
self.flows = flows;
if !self.flows.is_empty() && self.settings.selected_flow.is_empty() {
self.settings.selected_flow = self.flows[0].clone();
}
self.last_operation = format!("Loaded {} flows", self.flows.len());
}
Err(err) => {
self.connection_status = ConnectionStatus::Error(err.clone());
self.last_operation = format!("Failed to load flows: {}", err);
}
}
}
AdminOperation::LoadKeys(result) => {
match result {
Ok(keys) => {
self.admin_state.keys = keys;
self.admin_state.filter_keys();
self.connection_status = ConnectionStatus::Connected;
self.last_operation = format!("Loaded {} keys", self.admin_state.keys.len());
}
Err(err) => {
self.connection_status = ConnectionStatus::Error(err.clone());
self.last_operation = format!("Failed to load keys: {}", err);
}
}
}
AdminOperation::TestConnection(result) => {
match result {
Ok(msg) => {
self.connection_status = ConnectionStatus::Connected;
self.last_operation = msg;
}
Err(err) => {
self.connection_status = ConnectionStatus::Error(err.clone());
self.last_operation = format!("Connection failed: {}", err);
}
}
}
AdminOperation::DeprecateKey(server, result) => {
match result {
Ok(msg) => {
self.last_operation = msg;
self.load_keys_silent();
}
Err(err) => {
self.last_operation = format!("Failed to deprecate key for {}: {}", server, err);
}
}
}
AdminOperation::RestoreKey(server, result) => {
match result {
Ok(msg) => {
self.last_operation = msg;
self.load_keys_silent();
}
Err(err) => {
self.last_operation = format!("Failed to restore key for {}: {}", server, err);
}
}
}
AdminOperation::DeleteKey(server, result) => {
match result {
Ok(msg) => {
self.last_operation = msg;
self.load_keys_silent();
}
Err(err) => {
self.last_operation = format!("Failed to delete key for {}: {}", server, err);
}
}
}
AdminOperation::BulkDeprecate(result) | AdminOperation::BulkRestore(result) => {
match result {
Ok(msg) => {
self.last_operation = msg;
self.admin_state.clear_selection();
self.load_keys_silent();
}
Err(err) => {
self.last_operation = format!("Bulk operation failed: {}", err);
}
}
}
AdminOperation::ScanDns(result) => {
match result {
Ok(results) => {
let resolved = results.iter().filter(|r| r.resolved).count();
let total = results.len();
self.last_operation = format!("DNS scan completed: {}/{} servers resolved", resolved, total);
}
Err(err) => {
self.last_operation = format!("DNS scan failed: {}", err);
}
}
}
AdminOperation::LoadVersion(result) => {
match result {
Ok(version) => {
self.server_version = Some(version.clone());
self.last_operation = format!("Server version: {}", version);
}
Err(err) => {
self.last_operation = format!("Failed to get server version: {}", err);
}
}
}
}
}
// Async operation methods - adapted from desktop version
fn load_flows(&mut self, _ctx: &egui::Context) {
self.last_operation = "Loading flows...".to_string();
let settings = self.settings.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::load_flows(&settings));
let _ = tx.send(AdminOperation::LoadFlows(result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::load_flows(&settings).await;
let _ = tx.send(AdminOperation::LoadFlows(result));
});
}
}
fn test_connection(&mut self, _ctx: &egui::Context) {
self.connection_status = ConnectionStatus::Connecting;
self.last_operation = "Testing connection...".to_string();
let settings = self.settings.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::test_connection(&settings));
let _ = tx.send(AdminOperation::TestConnection(result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::test_connection(&settings).await;
let _ = tx.send(AdminOperation::TestConnection(result));
});
}
}
fn load_keys(&mut self, _ctx: &egui::Context) {
self.admin_state.current_operation = "Loading keys...".to_string();
self.last_operation = "Loading keys...".to_string();
let settings = self.settings.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::fetch_keys(&settings));
let _ = tx.send(AdminOperation::LoadKeys(result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::fetch_keys(&settings).await;
let _ = tx.send(AdminOperation::LoadKeys(result));
});
}
}
fn load_keys_silent(&mut self) {
let settings = self.settings.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::fetch_keys(&settings));
let _ = tx.send(AdminOperation::LoadKeys(result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::fetch_keys(&settings).await;
let _ = tx.send(AdminOperation::LoadKeys(result));
});
}
}
fn deprecate_key(&mut self, server: String, _ctx: &egui::Context) {
self.last_operation = format!("Deprecating key for {}...", server);
let settings = self.settings.clone();
let server_clone = server.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::deprecate_key(&settings, &server));
let _ = tx.send(AdminOperation::DeprecateKey(server_clone, result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::deprecate_key(&settings, &server).await;
let _ = tx.send(AdminOperation::DeprecateKey(server_clone, result));
});
}
}
fn restore_key(&mut self, server: String, _ctx: &egui::Context) {
self.last_operation = format!("Restoring key for {}...", server);
let settings = self.settings.clone();
let server_clone = server.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::restore_key(&settings, &server));
let _ = tx.send(AdminOperation::RestoreKey(server_clone, result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::restore_key(&settings, &server).await;
let _ = tx.send(AdminOperation::RestoreKey(server_clone, result));
});
}
}
fn delete_key(&mut self, server: String, _ctx: &egui::Context) {
self.last_operation = format!("Deleting key for {}...", server);
let settings = self.settings.clone();
let server_clone = server.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::delete_key(&settings, &server));
let _ = tx.send(AdminOperation::DeleteKey(server_clone, result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::delete_key(&settings, &server).await;
let _ = tx.send(AdminOperation::DeleteKey(server_clone, result));
});
}
}
fn deprecate_server(&mut self, server: String, ctx: &egui::Context) {
self.deprecate_key(server, ctx);
}
fn restore_server(&mut self, server: String, ctx: &egui::Context) {
self.restore_key(server, ctx);
}
fn bulk_deprecate(&mut self, _ctx: &egui::Context) {
let servers = self.admin_state.get_selected_servers();
if servers.is_empty() {
return;
}
self.last_operation = format!("Bulk deprecating {} servers...", servers.len());
let settings = self.settings.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::bulk_deprecate_servers(&settings, servers));
let _ = tx.send(AdminOperation::BulkDeprecate(result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::bulk_deprecate_servers(&settings, servers).await;
let _ = tx.send(AdminOperation::BulkDeprecate(result));
});
}
}
fn bulk_restore(&mut self, _ctx: &egui::Context) {
let servers = self.admin_state.get_selected_servers();
if servers.is_empty() {
return;
}
self.last_operation = format!("Bulk restoring {} servers...", servers.len());
let settings = self.settings.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::bulk_restore_servers(&settings, servers));
let _ = tx.send(AdminOperation::BulkRestore(result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::bulk_restore_servers(&settings, servers).await;
let _ = tx.send(AdminOperation::BulkRestore(result));
});
}
}
fn scan_dns(&mut self, _ctx: &egui::Context) {
self.last_operation = "Scanning DNS resolution...".to_string();
let settings = self.settings.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::scan_dns_resolution(&settings));
let _ = tx.send(AdminOperation::ScanDns(result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::scan_dns_resolution(&settings).await;
let _ = tx.send(AdminOperation::ScanDns(result));
});
}
}
fn load_version(&mut self, _ctx: &egui::Context) {
self.last_operation = "Loading server version...".to_string();
let settings = self.settings.clone();
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt.block_on(api::get_version(&settings));
let _ = tx.send(AdminOperation::LoadVersion(result));
});
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
{
wasm_bindgen_futures::spawn_local(async move {
let result = api::get_version(&settings).await;
let _ = tx.send(AdminOperation::LoadVersion(result));
});
}
}
}

View File

@@ -1,182 +0,0 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdminSettings {
pub server_url: String,
pub basic_auth: String,
pub selected_flow: String,
pub auto_refresh: bool,
pub refresh_interval: u32,
}
impl Default for AdminSettings {
fn default() -> Self {
Self {
server_url: String::new(),
basic_auth: String::new(),
selected_flow: String::new(),
auto_refresh: false,
refresh_interval: 30,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdminState {
pub keys: Vec<SshKey>,
pub filtered_keys: Vec<SshKey>,
pub search_term: String,
pub show_deprecated_only: bool,
pub selected_servers: HashMap<String, bool>,
pub expanded_servers: HashMap<String, bool>,
pub current_operation: String,
}
impl Default for AdminState {
fn default() -> Self {
Self {
keys: Vec::new(),
filtered_keys: Vec::new(),
search_term: String::new(),
show_deprecated_only: false,
selected_servers: HashMap::new(),
expanded_servers: HashMap::new(),
current_operation: "Ready".to_string(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SshKey {
pub server: String,
pub public_key: String,
#[serde(default)]
pub deprecated: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConnectionStatus {
Disconnected,
Connecting,
Connected,
Error(String),
}
impl PartialEq for ConnectionStatus {
fn eq(&self, other: &Self) -> bool {
std::mem::discriminant(self) == std::mem::discriminant(other)
}
}
#[derive(Debug, Clone)]
pub enum AdminOperation {
LoadKeys(Result<Vec<SshKey>, String>),
LoadFlows(Result<Vec<String>, String>),
DeprecateKey(String, Result<String, String>),
RestoreKey(String, Result<String, String>),
DeleteKey(String, Result<String, String>),
BulkDeprecate(Result<String, String>),
BulkRestore(Result<String, String>),
TestConnection(Result<String, String>),
ScanDns(Result<Vec<DnsResult>, String>),
LoadVersion(Result<String, String>),
}
// Re-export DnsResolutionResult from web.rs for consistency
pub use crate::web::DnsResolutionResult as DnsResult;
impl AdminState {
/// Filter keys based on search term and deprecated filter
pub fn filter_keys(&mut self) {
let mut filtered = self.keys.clone();
// Apply deprecated filter
if self.show_deprecated_only {
filtered.retain(|key| key.deprecated);
}
// Apply search filter
if !self.search_term.is_empty() {
let search_term = self.search_term.to_lowercase();
filtered.retain(|key| {
key.server.to_lowercase().contains(&search_term)
|| key.public_key.to_lowercase().contains(&search_term)
});
}
self.filtered_keys = filtered;
}
/// Get selected servers list
pub fn get_selected_servers(&self) -> Vec<String> {
self.selected_servers
.iter()
.filter_map(|(server, &selected)| {
if selected { Some(server.clone()) } else { None }
})
.collect()
}
/// Clear selection
pub fn clear_selection(&mut self) {
self.selected_servers.clear();
}
/// Get statistics
pub fn get_statistics(&self) -> AdminStatistics {
let total_keys = self.keys.len();
let active_keys = self.keys.iter().filter(|k| !k.deprecated).count();
let deprecated_keys = total_keys - active_keys;
let unique_servers = self.keys
.iter()
.map(|k| &k.server)
.collect::<std::collections::HashSet<_>>()
.len();
AdminStatistics {
total_keys,
active_keys,
deprecated_keys,
unique_servers,
}
}
}
#[derive(Debug, Clone)]
pub struct AdminStatistics {
pub total_keys: usize,
pub active_keys: usize,
pub deprecated_keys: usize,
pub unique_servers: usize,
}
/// Get SSH key type from public key string
pub fn get_key_type(public_key: &str) -> String {
if public_key.starts_with("ssh-rsa") {
"RSA".to_string()
} else if public_key.starts_with("ssh-ed25519") {
"ED25519".to_string()
} else if public_key.starts_with("ecdsa-sha2-nistp") {
"ECDSA".to_string()
} else if public_key.starts_with("ssh-dss") {
"DSA".to_string()
} else {
"Unknown".to_string()
}
}
/// Get preview of SSH key (first 16 characters of key part)
pub fn get_key_preview(public_key: &str) -> String {
let parts: Vec<&str> = public_key.split_whitespace().collect();
if parts.len() >= 2 {
let key_part = parts[1];
if key_part.len() > 16 {
format!("{}...", &key_part[..16])
} else {
key_part.to_string()
}
} else {
format!("{}...", &public_key[..std::cmp::min(16, public_key.len())])
}
}

View File

@@ -1,532 +0,0 @@
use super::state::{AdminState, AdminSettings, ConnectionStatus, get_key_type, get_key_preview};
use eframe::egui;
use std::collections::BTreeMap;
#[derive(Debug, Clone)]
pub enum KeyAction {
None,
DeprecateKey(String),
RestoreKey(String),
DeleteKey(String),
DeprecateServer(String),
RestoreServer(String),
}
#[derive(Debug, Clone)]
pub enum BulkAction {
None,
DeprecateSelected,
RestoreSelected,
ClearSelection,
}
/// Render connection settings panel
pub fn render_connection_settings(
ui: &mut egui::Ui,
settings: &mut AdminSettings,
connection_status: &ConnectionStatus,
flows: &[String],
server_version: &Option<String>,
) -> ConnectionAction {
let mut action = ConnectionAction::None;
ui.group(|ui| {
ui.set_min_width(ui.available_width());
ui.vertical(|ui| {
ui.label(egui::RichText::new("⚙️ Connection Settings").size(16.0).strong());
ui.add_space(8.0);
// Server URL
ui.horizontal(|ui| {
ui.label("Server URL:");
ui.text_edit_singleline(&mut settings.server_url);
});
// Basic Auth
ui.horizontal(|ui| {
ui.label("Basic Auth:");
ui.add(egui::TextEdit::singleline(&mut settings.basic_auth).password(true));
});
// Flow selection
ui.horizontal(|ui| {
ui.label("Flow:");
egui::ComboBox::from_id_salt("flow_select")
.selected_text(&settings.selected_flow)
.show_ui(ui, |ui| {
for flow in flows {
ui.selectable_value(&mut settings.selected_flow, flow.clone(), flow);
}
});
});
// Connection status
ui.horizontal(|ui| {
ui.label("Status:");
match connection_status {
ConnectionStatus::Connected => {
ui.colored_label(egui::Color32::GREEN, "● Connected");
}
ConnectionStatus::Connecting => {
ui.colored_label(egui::Color32::YELLOW, "● Connecting...");
}
ConnectionStatus::Disconnected => {
ui.colored_label(egui::Color32::GRAY, "● Disconnected");
}
ConnectionStatus::Error(msg) => {
ui.colored_label(egui::Color32::RED, format!("● Error: {}", msg));
}
}
});
// Server version display
if let Some(version) = server_version {
ui.horizontal(|ui| {
ui.label("Server Version:");
ui.colored_label(egui::Color32::LIGHT_BLUE, version);
});
}
ui.add_space(8.0);
// Action buttons
ui.horizontal(|ui| {
if ui.button("Load Flows").clicked() {
action = ConnectionAction::LoadFlows;
}
if ui.button("Test Connection").clicked() {
action = ConnectionAction::TestConnection;
}
if ui.button("Get Version").clicked() {
action = ConnectionAction::LoadVersion;
}
if !settings.selected_flow.is_empty() && ui.button("Load Keys").clicked() {
action = ConnectionAction::LoadKeys;
}
});
});
});
action
}
/// Render statistics cards
pub fn render_statistics(ui: &mut egui::Ui, admin_state: &AdminState) {
let stats = admin_state.get_statistics();
ui.group(|ui| {
ui.set_min_width(ui.available_width());
ui.vertical(|ui| {
ui.label(egui::RichText::new("📊 Statistics").size(16.0).strong());
ui.add_space(8.0);
ui.horizontal(|ui| {
ui.columns(4, |cols| {
// Total keys
cols[0].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("📊").size(20.0));
ui.label(
egui::RichText::new(stats.total_keys.to_string())
.size(24.0)
.strong(),
);
ui.label(
egui::RichText::new("Total Keys")
.size(11.0)
.color(egui::Color32::GRAY),
);
});
// Active keys
cols[1].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("").size(20.0));
ui.label(
egui::RichText::new(stats.active_keys.to_string())
.size(24.0)
.strong()
.color(egui::Color32::LIGHT_GREEN),
);
ui.label(
egui::RichText::new("Active")
.size(11.0)
.color(egui::Color32::GRAY),
);
});
// Deprecated keys
cols[2].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("").size(20.0));
ui.label(
egui::RichText::new(stats.deprecated_keys.to_string())
.size(24.0)
.strong()
.color(egui::Color32::LIGHT_RED),
);
ui.label(
egui::RichText::new("Deprecated")
.size(11.0)
.color(egui::Color32::GRAY),
);
});
// Servers
cols[3].vertical_centered_justified(|ui| {
ui.label(egui::RichText::new("💻").size(20.0));
ui.label(
egui::RichText::new(stats.unique_servers.to_string())
.size(24.0)
.strong()
.color(egui::Color32::LIGHT_BLUE),
);
ui.label(
egui::RichText::new("Servers")
.size(11.0)
.color(egui::Color32::GRAY),
);
});
});
});
});
});
}
/// Render search and filter controls
pub fn render_search_controls(ui: &mut egui::Ui, admin_state: &mut AdminState) -> bool {
let mut changed = false;
ui.group(|ui| {
ui.set_min_width(ui.available_width());
ui.vertical(|ui| {
ui.label(egui::RichText::new("🔍 Search & Filter").size(16.0).strong());
ui.add_space(8.0);
// Search field
ui.horizontal(|ui| {
ui.label("Search:");
let search_response = ui.add_sized(
[ui.available_width() * 0.6, 20.0],
egui::TextEdit::singleline(&mut admin_state.search_term)
.hint_text("Search servers or keys..."),
);
if search_response.changed() {
changed = true;
}
if !admin_state.search_term.is_empty() {
if ui.small_button("Clear").clicked() {
admin_state.search_term.clear();
changed = true;
}
}
});
ui.add_space(5.0);
// Filter controls
ui.horizontal(|ui| {
ui.label("Filter:");
let show_deprecated = admin_state.show_deprecated_only;
if ui.selectable_label(!show_deprecated, "✅ Active").clicked() {
admin_state.show_deprecated_only = false;
changed = true;
}
if ui.selectable_label(show_deprecated, "❗ Deprecated").clicked() {
admin_state.show_deprecated_only = true;
changed = true;
}
});
});
});
if changed {
admin_state.filter_keys();
}
changed
}
/// Render bulk actions controls
pub fn render_bulk_actions(ui: &mut egui::Ui, admin_state: &mut AdminState) -> BulkAction {
let selected_count = admin_state
.selected_servers
.values()
.filter(|&&v| v)
.count();
if selected_count == 0 {
return BulkAction::None;
}
let mut action = BulkAction::None;
ui.group(|ui| {
ui.set_min_width(ui.available_width());
ui.vertical(|ui| {
ui.horizontal(|ui| {
ui.label(egui::RichText::new("📋").size(14.0));
ui.label(
egui::RichText::new(format!("Selected {} servers", selected_count))
.size(14.0)
.strong()
.color(egui::Color32::LIGHT_BLUE),
);
});
ui.add_space(5.0);
ui.horizontal(|ui| {
if ui.button("❗ Deprecate Selected").clicked() {
action = BulkAction::DeprecateSelected;
}
if ui.button("✅ Restore Selected").clicked() {
action = BulkAction::RestoreSelected;
}
if ui.button("Clear Selection").clicked() {
action = BulkAction::ClearSelection;
}
});
});
});
action
}
/// Render keys table grouped by servers
pub fn render_keys_table(ui: &mut egui::Ui, admin_state: &mut AdminState) -> KeyAction {
if admin_state.filtered_keys.is_empty() {
render_empty_state(ui, admin_state);
return KeyAction::None;
}
let mut action = KeyAction::None;
// Group keys by server
let mut servers: BTreeMap<String, Vec<&crate::web_gui::state::SshKey>> = BTreeMap::new();
for key in &admin_state.filtered_keys {
servers
.entry(key.server.clone())
.or_insert_with(Vec::new)
.push(key);
}
// Render each server group
egui::ScrollArea::vertical().show(ui, |ui| {
for (server_name, server_keys) in servers {
let is_expanded = admin_state
.expanded_servers
.get(&server_name)
.copied()
.unwrap_or(false);
let active_count = server_keys.iter().filter(|k| !k.deprecated).count();
let deprecated_count = server_keys.len() - active_count;
// Server header
ui.group(|ui| {
ui.horizontal(|ui| {
// Server selection checkbox
let mut selected = admin_state
.selected_servers
.get(&server_name)
.copied()
.unwrap_or(false);
if ui.checkbox(&mut selected, "").changed() {
admin_state
.selected_servers
.insert(server_name.clone(), selected);
}
// Expand/collapse button
let expand_icon = if is_expanded { "" } else { "" };
if ui.small_button(expand_icon).clicked() {
admin_state
.expanded_servers
.insert(server_name.clone(), !is_expanded);
}
// Server icon and name
ui.label(egui::RichText::new("💻").size(16.0));
ui.label(
egui::RichText::new(&server_name)
.size(15.0)
.strong(),
);
// Keys count badge
ui.label(format!("({} keys)", server_keys.len()));
// Deprecated count badge
if deprecated_count > 0 {
ui.colored_label(
egui::Color32::RED,
format!("{} deprecated", deprecated_count)
);
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Server action buttons
if deprecated_count > 0 {
if ui.small_button("✅ Restore").clicked() {
action = KeyAction::RestoreServer(server_name.clone());
}
}
if active_count > 0 {
if ui.small_button("❗ Deprecate").clicked() {
action = KeyAction::DeprecateServer(server_name.clone());
}
}
});
});
});
// Expanded key details
if is_expanded {
ui.indent(&server_name, |ui| {
for key in &server_keys {
if let Some(key_action) = render_key_item(ui, key, &server_name) {
action = key_action;
}
}
});
}
ui.add_space(5.0);
}
});
action
}
/// Render empty state when no keys are available
fn render_empty_state(ui: &mut egui::Ui, admin_state: &AdminState) {
ui.vertical_centered(|ui| {
ui.add_space(60.0);
if admin_state.keys.is_empty() {
ui.label(
egui::RichText::new("🔑")
.size(48.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("No SSH keys available")
.size(18.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("Keys will appear here once loaded from the server")
.size(14.0)
.color(egui::Color32::DARK_GRAY),
);
} else if !admin_state.search_term.is_empty() {
ui.label(
egui::RichText::new("🔍")
.size(48.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("No results found")
.size(18.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new(format!(
"Try adjusting your search: '{}'",
admin_state.search_term
))
.size(14.0)
.color(egui::Color32::DARK_GRAY),
);
} else {
ui.label(
egui::RichText::new("")
.size(48.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("No keys match current filters")
.size(18.0)
.color(egui::Color32::GRAY),
);
ui.label(
egui::RichText::new("Try adjusting your search or filter settings")
.size(14.0)
.color(egui::Color32::DARK_GRAY),
);
}
});
}
/// Render individual key item
fn render_key_item(
ui: &mut egui::Ui,
key: &crate::web_gui::state::SshKey,
server_name: &str,
) -> Option<KeyAction> {
let mut action = None;
ui.group(|ui| {
ui.horizontal(|ui| {
// Key type badge
let key_type = get_key_type(&key.public_key);
let badge_color = match key_type.as_str() {
"RSA" => egui::Color32::from_rgb(52, 144, 220),
"ED25519" => egui::Color32::from_rgb(46, 204, 113),
"ECDSA" => egui::Color32::from_rgb(241, 196, 15),
"DSA" => egui::Color32::from_rgb(230, 126, 34),
_ => egui::Color32::GRAY,
};
ui.colored_label(badge_color, &key_type);
ui.add_space(5.0);
// Status badge
if key.deprecated {
ui.colored_label(egui::Color32::RED, "❗ DEPRECATED");
} else {
ui.colored_label(egui::Color32::GREEN, "✅ ACTIVE");
}
ui.add_space(5.0);
// Key preview
ui.monospace(get_key_preview(&key.public_key));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Key action buttons
if key.deprecated {
if ui.small_button("Restore").clicked() {
action = Some(KeyAction::RestoreKey(server_name.to_string()));
}
if ui.small_button("Delete").clicked() {
action = Some(KeyAction::DeleteKey(server_name.to_string()));
}
} else {
if ui.small_button("Deprecate").clicked() {
action = Some(KeyAction::DeprecateKey(server_name.to_string()));
}
}
if ui.small_button("Copy").clicked() {
ui.output_mut(|o| o.copied_text = key.public_key.clone());
}
});
});
});
action
}
#[derive(Debug, Clone)]
pub enum ConnectionAction {
None,
LoadFlows,
TestConnection,
LoadKeys,
LoadVersion,
}

View File

@@ -1,43 +0,0 @@
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
use wasm_bindgen::prelude::*;
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
use super::app::WebAdminApp;
/// WASM entry point for the web admin application
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
#[wasm_bindgen]
pub fn start_web_admin(canvas_id: &str) -> Result<(), JsValue> {
// Setup console logging for WASM
console_error_panic_hook::set_once();
tracing_wasm::set_as_global_default();
let web_options = eframe::WebOptions::default();
let canvas_id = canvas_id.to_string();
wasm_bindgen_futures::spawn_local(async move {
let app = WebAdminApp::default();
let result = eframe::WebRunner::new()
.start(
&canvas_id,
web_options,
Box::new(|_cc| Ok(Box::new(app))),
)
.await;
match result {
Ok(_) => web_sys::console::log_1(&"eframe started successfully".into()),
Err(e) => web_sys::console::error_1(&format!("Failed to start eframe: {:?}", e).into()),
}
});
Ok(())
}
/// Initialize the WASM module
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
#[wasm_bindgen(start)]
pub fn wasm_main() {
console_error_panic_hook::set_once();
}

View File

@@ -1,131 +0,0 @@
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
use super::state::{SshKey, DnsResult, AdminSettings};
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
use wasm_bindgen::prelude::*;
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
use wasm_bindgen_futures::JsFuture;
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
use web_sys::{Request, RequestInit, RequestMode, Response};
/// Simplified API for WASM - uses browser fetch API
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub async fn test_connection(settings: &AdminSettings) -> Result<String, String> {
let url = format!("{}/{}/keys", settings.server_url.trim_end_matches('/'), settings.selected_flow);
let response = fetch_json(&url).await?;
let keys: Result<Vec<SshKey>, _> = serde_json::from_str(&response);
match keys {
Ok(keys) => Ok(format!("Connection successful! Found {} SSH keys from flow '{}'", keys.len(), settings.selected_flow)),
Err(e) => Err(format!("Failed to parse response: {}", e)),
}
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub async fn load_flows(settings: &AdminSettings) -> Result<Vec<String>, String> {
let url = format!("{}/api/flows", settings.server_url.trim_end_matches('/'));
let response = fetch_json(&url).await?;
let flows: Result<Vec<String>, _> = serde_json::from_str(&response);
flows.map_err(|e| format!("Failed to parse flows: {}", e))
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub async fn fetch_keys(settings: &AdminSettings) -> Result<Vec<SshKey>, String> {
let url = format!("{}/{}/keys", settings.server_url.trim_end_matches('/'), settings.selected_flow);
let response = fetch_json(&url).await?;
let keys: Result<Vec<SshKey>, _> = serde_json::from_str(&response);
keys.map_err(|e| format!("Failed to parse keys: {}", e))
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub async fn get_version(settings: &AdminSettings) -> Result<String, String> {
let url = format!("{}/api/version", settings.server_url.trim_end_matches('/'));
let response = fetch_json(&url).await?;
let version_response: Result<serde_json::Value, _> = serde_json::from_str(&response);
match version_response {
Ok(data) => {
let version = data.get("version")
.and_then(|v| v.as_str())
.unwrap_or("unknown")
.to_string();
Ok(version)
}
Err(e) => Err(format!("Failed to parse version: {}", e)),
}
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub async fn deprecate_key(_settings: &AdminSettings, server: &str) -> Result<String, String> {
Ok(format!("WASM: Would deprecate key for {}", server))
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub async fn restore_key(_settings: &AdminSettings, server: &str) -> Result<String, String> {
Ok(format!("WASM: Would restore key for {}", server))
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub async fn delete_key(_settings: &AdminSettings, server: &str) -> Result<String, String> {
Ok(format!("WASM: Would delete key for {}", server))
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub async fn bulk_deprecate_servers(_settings: &AdminSettings, servers: Vec<String>) -> Result<String, String> {
Ok(format!("WASM: Would bulk deprecate {} servers", servers.len()))
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub async fn bulk_restore_servers(_settings: &AdminSettings, servers: Vec<String>) -> Result<String, String> {
Ok(format!("WASM: Would bulk restore {} servers", servers.len()))
}
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
pub async fn scan_dns_resolution(_settings: &AdminSettings) -> Result<Vec<DnsResult>, String> {
Ok(vec![
DnsResult {
server: "demo-server".to_string(),
resolved: true,
error: None,
}
])
}
/// Helper function to make HTTP requests using browser's fetch API
#[cfg(all(target_arch = "wasm32", feature = "web-gui"))]
async fn fetch_json(url: &str) -> Result<String, String> {
let window = web_sys::window().ok_or("No window object")?;
let mut opts = RequestInit::new();
opts.method("GET");
opts.mode(RequestMode::Cors);
let request = Request::new_with_str_and_init(url, &opts)
.map_err(|e| format!("Failed to create request: {:?}", e))?;
let resp_value = JsFuture::from(window.fetch_with_request(&request))
.await
.map_err(|e| format!("Request failed: {:?}", e))?;
let resp: Response = resp_value.dyn_into()
.map_err(|e| format!("Failed to cast response: {:?}", e))?;
if !resp.ok() {
return Err(format!("HTTP error: {} {}", resp.status(), resp.status_text()));
}
let text_promise = resp.text()
.map_err(|e| format!("Failed to get text promise: {:?}", e))?;
let text_value = JsFuture::from(text_promise)
.await
.map_err(|e| format!("Failed to get text: {:?}", e))?;
text_value.as_string()
.ok_or("Response is not a string".to_string())
}