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
27 changed files with 1109 additions and 2402 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:
CARGO_TERM_COLOR: always
CLI_BINARY_NAME: khm
DESKTOP_BINARY_NAME: khm-desktop
BINARY_NAME: khm
jobs:
build:
name: Build static binary
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
include:
# - os: ubuntu-latest
# build_target: x86_64-unknown-linux-musl
# platform_name: linux-amd64-musl
# build_type: musl
- os: ubuntu-latest
build_target: x86_64-unknown-linux-gnu
build_target: x86_64-unknown-linux-musl
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
build_target: x86_64-pc-windows-msvc
platform_name: windows-amd64
build_type: default
- os: macos-latest
build_target: aarch64-apple-darwin
platform_name: macos-arm64
build_type: default
permissions:
contents: write
steps:
@@ -72,149 +60,79 @@ jobs:
- name: Install rust targets
run: rustup target add ${{ matrix.build_target }}
- name: Install Linux x86_64 dependencies
if: matrix.os == 'ubuntu-latest' && matrix.build_type == 'dynamic' && matrix.build_target == 'x86_64-unknown-linux-gnu'
run: |
sudo apt-get update
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
- 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 Linux MUSL
if: matrix.os == 'ubuntu-latest'
uses: gmiam/rust-musl-action@master
with:
args: cargo build --target ${{ matrix.build_target }} --release
- name: Build MacOS
if: matrix.os == 'macos-latest'
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
run: cargo build --target ${{ matrix.build_target }} --release
- name: Build Windows
if: matrix.os == 'windows-latest'
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
run: cargo build --target ${{ matrix.build_target }} --release
- name: Upload CLI artifact
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: ${{ env.CLI_BINARY_NAME }}_${{ matrix.platform_name }}
path: |
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
name: ${{ env.BINARY_NAME }}_${{ matrix.platform_name }}
path: target/${{ matrix.build_target }}/release/${{ env.BINARY_NAME }}*
release:
name: Create Release and Upload Assets
if: always() # Always run even if some builds fail
name: Create Release Page
needs: build
runs-on: ubuntu-latest
outputs:
upload_url: ${{ steps.create_release.outputs.upload_url }}
permissions:
contents: write
steps:
- 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
uses: softprops/action-gh-release@v2
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
name: Release ${{ github.ref_name }}
files: release-assets/*
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
draft: 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:
name: Build and Publish Docker Image
@@ -223,26 +141,15 @@ jobs:
steps:
- 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:
name: ${{ env.CLI_BINARY_NAME }}_linux-amd64
path: amd64/
name: ${{ env.BINARY_NAME }}_linux-amd64
path: .
- name: Download Linux ARM64 CLI artifact
uses: actions/download-artifact@v4
with:
name: ${{ env.CLI_BINARY_NAME }}_linux-arm64
path: arm64/
- name: Prepare binaries for multi-arch build
- name: ls
run: |
mkdir -p bin/linux_amd64 bin/linux_arm64
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/*/
ls -lah
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
@@ -256,6 +163,10 @@ jobs:
username: ultradesu
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Set exec flag
run: |
chmod +x ${{ env.BINARY_NAME }}
- name: Set outputs
id: get_tag
run: |
@@ -267,5 +178,5 @@ jobs:
context: .
platforms: linux/amd64,linux/arm64
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 }}

32
Cargo.lock generated
View File

@@ -2672,7 +2672,7 @@ dependencies = [
[[package]]
name = "khm"
version = "0.7.1"
version = "0.6.3"
dependencies = [
"actix-web",
"base64 0.21.7",
@@ -2683,13 +2683,10 @@ dependencies = [
"egui",
"env_logger",
"futures",
"glib",
"gtk",
"hostname",
"log",
"notify",
"notify-debouncer-mini",
"openssl",
"regex",
"reqwest",
"rust-embed",
@@ -2996,22 +2993,21 @@ dependencies = [
[[package]]
name = "muda"
version = "0.17.0"
version = "0.15.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58b89bf91c19bf036347f1ab85a81c560f08c0667c8601bece664d860a600988"
checksum = "fdae9c00e61cc0579bcac625e8ad22104c60548a025bfc972dc83868a28e1484"
dependencies = [
"crossbeam-channel",
"dpi",
"gtk",
"keyboard-types",
"libxdo",
"objc2 0.6.1",
"objc2-app-kit 0.3.1",
"objc2-core-foundation",
"objc2-foundation 0.3.1",
"objc2 0.5.2",
"objc2-app-kit 0.2.2",
"objc2-foundation 0.2.2",
"once_cell",
"png",
"thiserror 2.0.12",
"thiserror 1.0.69",
"windows-sys 0.59.0",
]
@@ -3516,15 +3512,6 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "openssl-sys"
version = "0.9.102"
@@ -3533,7 +3520,6 @@ checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2"
dependencies = [
"cc",
"libc",
"openssl-src",
"pkg-config",
"vcpkg",
]
@@ -4909,9 +4895,9 @@ dependencies = [
[[package]]
name = "tray-icon"
version = "0.21.0"
version = "0.19.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da75ec677957aa21f6e0b361df0daab972f13a5bee3606de0638fd4ee1c666a"
checksum = "eadd75f5002e2513eaa19b2365f533090cc3e93abd38788452d9ea85cff7b48a"
dependencies = [
"crossbeam-channel",
"dirs 6.0.0",

View File

@@ -1,6 +1,6 @@
[package]
name = "khm"
version = "0.7.1"
version = "0.7.0"
edition = "2021"
authors = ["AB <ab@hexor.cy>"]
description = "KHM - Known Hosts Manager for SSH key management and synchronization"
@@ -10,15 +10,6 @@ license = "WTFPL"
keywords = ["ssh", "known-hosts", "security", "system-admin", "automation"]
categories = ["command-line-utilities", "network-programming"]
[[bin]]
name = "khm"
path = "src/bin/cli.rs"
[[bin]]
name = "khm-desktop"
path = "src/bin/desktop.rs"
required-features = ["gui"]
[dependencies]
actix-web = "4"
serde = { version = "1.0", features = ["derive"] }
@@ -36,7 +27,7 @@ trust-dns-resolver = "0.23"
futures = "0.3"
hostname = "0.3"
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-debouncer-mini = { version = "0.4", optional = true }
dirs = "5.0"
@@ -46,20 +37,8 @@ winit = { version = "0.30", optional = true }
env_logger = "0.11"
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]
default = ["server", "web", "gui"]
cli = ["server", "web"]
desktop = ["gui"]
gui = ["tray-icon", "eframe", "egui", "winit", "notify", "notify-debouncer-mini", "gtk", "glib"]
default = ["gui"]
gui = ["tray-icon", "eframe", "egui", "winit", "notify", "notify-debouncer-mini"]
server = []
web = []
# Target-specific dependencies for cross-compilation
[target.aarch64-unknown-linux-gnu.dependencies]
openssl = { version = "0.10", features = ["vendored"] }

View File

@@ -1,19 +1,5 @@
# syntax=docker/dockerfile:1
FROM debian:12-slim
# Install only essential runtime dependencies
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
FROM alpine:latest
COPY khm /usr/local/bin/khm
ENTRYPOINT ["/usr/local/bin/khm"]

175
README.MD
View File

@@ -1,166 +1,65 @@
# 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
- **Multi-mode operation**: Server, client, and GUI modes
- **Centralized key management**: Store SSH keys and flows in PostgreSQL database
- **Cross-platform GUI**: Modern tray application with settings window
- **Automatic synchronization**: Keep `known_hosts` files updated across environments
- **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
- Synchronize `known_hosts` file across multiple hosts.
- Manage SSH keys and flows in a PostgreSQL database.
- Operate in both server and client modes.
- Automatically update `known_hosts` file with keys from the server.
## Operation Modes
## Usage
### 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
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
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
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
Launches a system tray application with a modern interface for easy management.
### Arguments
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
### From Binary Releases
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/)
1. Ensure you have Rust installed. If not, you can install it from [rustup.rs](https://rustup.rs/).
2. Clone the repository:
```bash
git clone https://github.com/house-of-vanity/khm.git
cd khm
```
3. Build and run:
```bash
# Build both binaries (CLI without GUI, Desktop with GUI)
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
```
```bash
git clone https://github.com/house-of-vanity/khm.git
cd khm
```
3. Run the project:
```bash
cargo run --release -- --help
```
## 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
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:

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

@@ -493,9 +493,7 @@ impl DbClient {
info!(
"Bulk deprecated {} key(s) for {} servers in flow '{}'",
affected,
server_names.len(),
flow_name
affected, server_names.len(), flow_name
);
Ok(affected)
@@ -528,9 +526,7 @@ impl DbClient {
info!(
"Bulk restored {} key(s) for {} servers in flow '{}'",
affected,
server_names.len(),
flow_name
affected, server_names.len(), flow_name
);
Ok(affected)

View File

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

View File

@@ -1,9 +1,9 @@
use crate::gui::api::{fetch_keys, SshKey};
use crate::gui::common::KhmSettings;
use eframe::egui;
use log::{error, info};
use std::collections::HashMap;
use std::sync::mpsc;
use crate::gui::api::{SshKey, fetch_keys};
use crate::gui::common::KhmSettings;
#[derive(Debug, Clone)]
pub enum AdminOperation {
@@ -57,8 +57,8 @@ impl AdminState {
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)
key.server.to_lowercase().contains(&search_term) ||
key.public_key.to_lowercase().contains(&search_term)
});
}
@@ -66,11 +66,7 @@ impl AdminState {
}
/// Load keys from server
pub fn load_keys(
&mut self,
settings: &KhmSettings,
ctx: &egui::Context,
) -> Option<mpsc::Receiver<Result<Vec<SshKey>, String>>> {
pub fn load_keys(&mut self, settings: &KhmSettings, ctx: &egui::Context) -> Option<mpsc::Receiver<Result<Vec<SshKey>, String>>> {
if settings.host.is_empty() || settings.flow.is_empty() {
return None;
}
@@ -86,7 +82,9 @@ impl AdminState {
std::thread::spawn(move || {
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);
ctx_clone.request_repaint();
@@ -130,12 +128,7 @@ impl AdminState {
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();
let unique_servers = self.keys.iter().map(|k| &k.server).collect::<std::collections::HashSet<_>>().len();
AdminStatistics {
total_keys,

View File

@@ -1,7 +1,7 @@
use super::state::{get_key_preview, get_key_type, AdminState};
use crate::gui::api::SshKey;
use eframe::egui;
use std::collections::BTreeMap;
use super::state::{AdminState, get_key_type, get_key_preview};
use crate::gui::api::SshKey;
/// Render statistics cards
pub fn render_statistics(ui: &mut egui::Ui, admin_state: &AdminState) {
@@ -18,64 +18,29 @@ pub fn render_statistics(ui: &mut egui::Ui, admin_state: &AdminState) {
// 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),
);
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),
);
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),
);
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),
);
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));
});
});
});
@@ -99,33 +64,19 @@ pub fn render_search_controls(ui: &mut egui::Ui, admin_state: &mut AdminState) -
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..."),
.hint_text("Search servers or keys...")
);
if admin_state.search_term.is_empty() {
ui.label(
egui::RichText::new("Type to search")
.size(11.0)
.color(egui::Color32::GRAY),
);
ui.label(egui::RichText::new("Type to search").size(11.0).color(egui::Color32::GRAY));
} else {
ui.label(
egui::RichText::new(format!("{} results", admin_state.filtered_keys.len()))
.size(11.0),
);
if ui
.add(
egui::Button::new(
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()
{
ui.label(egui::RichText::new(format!("{} results", admin_state.filtered_keys.len())).size(11.0));
if ui.add(egui::Button::new(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();
changed = true;
}
@@ -147,10 +98,7 @@ pub fn render_search_controls(ui: &mut egui::Ui, admin_state: &mut AdminState) -
admin_state.show_deprecated_only = false;
changed = true;
}
if ui
.selectable_label(show_deprecated, "❗ Deprecated")
.clicked()
{
if ui.selectable_label(show_deprecated, "❗ Deprecated").clicked() {
admin_state.show_deprecated_only = true;
changed = true;
}
@@ -167,11 +115,7 @@ pub fn render_search_controls(ui: &mut egui::Ui, admin_state: &mut AdminState) -
/// 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();
let selected_count = admin_state.selected_servers.values().filter(|&&v| v).count();
if selected_count == 0 {
return BulkAction::None;
@@ -184,60 +128,39 @@ pub fn render_bulk_actions(ui: &mut egui::Ui, admin_state: &mut AdminState) -> B
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.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
.add(
egui::Button::new(
egui::RichText::new("❗ Deprecate Selected")
.color(egui::Color32::BLACK),
)
.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()
{
if ui.add(egui::Button::new(egui::RichText::new("❗ Deprecate Selected").color(egui::Color32::BLACK))
.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;
}
if ui
.add(
egui::Button::new(
egui::RichText::new("✅ Restore Selected").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(101, 199, 40))
.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()
{
if ui.add(egui::Button::new(egui::RichText::new("✅ Restore Selected").color(egui::Color32::WHITE))
.fill(egui::Color32::from_rgb(101, 199, 40))
.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;
}
if ui
.add(
egui::Button::new(
egui::RichText::new("X Clear Selection").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(6.0))
.min_size(egui::vec2(110.0, 28.0)),
)
.clicked()
{
if ui.add(egui::Button::new(egui::RichText::new("X Clear Selection").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(6.0))
.min_size(egui::vec2(110.0, 28.0))
).clicked() {
admin_state.clear_selection();
action = BulkAction::ClearSelection;
}
@@ -260,19 +183,12 @@ pub fn render_keys_table(ui: &mut egui::Ui, admin_state: &mut AdminState) -> Key
// Group keys by server
let mut servers: BTreeMap<String, Vec<SshKey>> = BTreeMap::new();
for key in &admin_state.filtered_keys {
servers
.entry(key.server.clone())
.or_insert_with(Vec::new)
.push(key.clone());
servers.entry(key.server.clone()).or_insert_with(Vec::new).push(key.clone());
}
// Render each server group
for (server_name, server_keys) in servers {
let is_expanded = admin_state
.expanded_servers
.get(&server_name)
.copied()
.unwrap_or(false);
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;
@@ -280,103 +196,60 @@ pub fn render_keys_table(ui: &mut egui::Ui, admin_state: &mut AdminState) -> Key
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
.add(egui::Checkbox::new(&mut selected, "").indeterminate(false))
.changed()
{
admin_state
.selected_servers
.insert(server_name.clone(), selected);
let mut selected = admin_state.selected_servers.get(&server_name).copied().unwrap_or(false);
if ui.add(egui::Checkbox::new(&mut selected, "")
.indeterminate(false)
).changed() {
admin_state.selected_servers.insert(server_name.clone(), selected);
}
// Expand/collapse button
let expand_icon = if is_expanded { "-" } else { "+" };
if ui
.add(
egui::Button::new(expand_icon)
.fill(egui::Color32::TRANSPARENT)
.stroke(egui::Stroke::NONE)
.min_size(egui::vec2(20.0, 20.0)),
)
.clicked()
{
admin_state
.expanded_servers
.insert(server_name.clone(), !is_expanded);
let expand_icon = if is_expanded { "" } else { "" };
if ui.add(egui::Button::new(expand_icon)
.fill(egui::Color32::TRANSPARENT)
.stroke(egui::Stroke::NONE)
.min_size(egui::vec2(20.0, 20.0))
).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()
.color(egui::Color32::WHITE),
);
ui.label(egui::RichText::new(&server_name)
.size(15.0)
.strong()
.color(egui::Color32::WHITE));
// Keys count badge
render_badge(
ui,
&format!("{} keys", server_keys.len()),
egui::Color32::from_rgb(52, 152, 219),
egui::Color32::WHITE,
);
render_badge(ui, &format!("{} keys", server_keys.len()), egui::Color32::from_rgb(52, 152, 219), egui::Color32::WHITE);
ui.add_space(5.0);
// Deprecated count badge
if deprecated_count > 0 {
render_badge(
ui,
&format!("{} depr", deprecated_count),
egui::Color32::from_rgb(231, 76, 60),
egui::Color32::WHITE,
);
render_badge(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| {
// Server action buttons
if deprecated_count > 0 {
if ui
.add(
egui::Button::new(
egui::RichText::new("✅ Restore").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(101, 199, 40))
.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()
{
if ui.add(egui::Button::new(egui::RichText::new("✅ Restore").color(egui::Color32::WHITE))
.fill(egui::Color32::from_rgb(101, 199, 40))
.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());
}
}
if active_count > 0 {
if ui
.add(
egui::Button::new(
egui::RichText::new("❗ Deprecate").color(egui::Color32::BLACK),
)
.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(4.0))
.min_size(egui::vec2(85.0, 24.0)),
)
.clicked()
{
if ui.add(egui::Button::new(egui::RichText::new("❗ Deprecate").color(egui::Color32::BLACK))
.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(4.0))
.min_size(egui::vec2(85.0, 24.0))
).clicked() {
action = KeyAction::DeprecateServer(server_name.clone());
}
}
@@ -406,56 +279,29 @@ 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
))
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),
);
.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),
);
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));
}
});
}
@@ -481,92 +327,60 @@ fn render_key_item(ui: &mut egui::Ui, key: &SshKey, server_name: &str) -> Option
// Status badge
if key.deprecated {
ui.label(
egui::RichText::new("❗ DEPR")
.size(10.0)
.color(egui::Color32::from_rgb(231, 76, 60))
.strong(),
);
ui.label(egui::RichText::new("❗ DEPR")
.size(10.0)
.color(egui::Color32::from_rgb(231, 76, 60))
.strong());
} else {
ui.label(
egui::RichText::new("")
.size(10.0)
.color(egui::Color32::from_rgb(46, 204, 113))
.strong(),
);
ui.label(egui::RichText::new("[OK] ACTIVE")
.size(10.0)
.color(egui::Color32::from_rgb(46, 204, 113))
.strong());
}
ui.add_space(5.0);
// Key preview
ui.label(
egui::RichText::new(get_key_preview(&key.public_key))
.font(egui::FontId::monospace(10.0))
.color(egui::Color32::LIGHT_GRAY),
);
ui.label(egui::RichText::new(get_key_preview(&key.public_key))
.font(egui::FontId::monospace(10.0))
.color(egui::Color32::LIGHT_GRAY));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Key action buttons
if key.deprecated {
if ui
.add(
egui::Button::new(
egui::RichText::new("[R]").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(101, 199, 40))
.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()
{
if ui.add(egui::Button::new(egui::RichText::new("[R]").color(egui::Color32::WHITE))
.fill(egui::Color32::from_rgb(101, 199, 40))
.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()));
}
if ui
.add(
egui::Button::new(
egui::RichText::new("Del").color(egui::Color32::WHITE),
)
.fill(egui::Color32::from_rgb(246, 36, 71))
.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()
{
if ui.add(egui::Button::new(egui::RichText::new("Del").color(egui::Color32::WHITE))
.fill(egui::Color32::from_rgb(246, 36, 71))
.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()));
}
} else {
if ui
.add(
egui::Button::new(
egui::RichText::new("").color(egui::Color32::BLACK),
)
.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(3.0))
.min_size(egui::vec2(22.0, 18.0)),
)
.on_hover_text("Deprecate key")
.clicked()
{
if ui.add(egui::Button::new(egui::RichText::new("").color(egui::Color32::BLACK))
.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(3.0))
.min_size(egui::vec2(22.0, 18.0))
).on_hover_text("Deprecate key").clicked() {
action = Some(KeyAction::DeprecateKey(server_name.to_string()));
}
}
if ui
.add(
egui::Button::new(egui::RichText::new("Copy").color(egui::Color32::WHITE))
.fill(egui::Color32::from_rgb(0, 111, 230))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(35, 84, 97)))
.rounding(egui::Rounding::same(3.0))
.min_size(egui::vec2(30.0, 18.0)),
)
.on_hover_text("Copy to clipboard")
.clicked()
{
if ui.add(egui::Button::new(egui::RichText::new("Copy").color(egui::Color32::WHITE))
.fill(egui::Color32::from_rgb(0, 111, 230))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(35, 84, 97)))
.rounding(egui::Rounding::same(3.0))
.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());
}
});
@@ -578,9 +392,15 @@ fn render_key_item(ui: &mut egui::Ui, key: &SshKey, server_name: &str) -> Option
/// Render a badge with text
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());
ui.painter()
.rect_filled(rect, egui::Rounding::same(8.0), bg_color);
let (rect, _) = ui.allocate_exact_size(
egui::vec2(50.0, 18.0),
egui::Sense::hover()
);
ui.painter().rect_filled(
rect,
egui::Rounding::same(8.0),
bg_color
);
ui.painter().text(
rect.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
fn render_small_badge(
ui: &mut egui::Ui,
text: &str,
bg_color: egui::Color32,
text_color: egui::Color32,
) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(40.0, 16.0), egui::Sense::hover());
ui.painter()
.rect_filled(rect, egui::Rounding::same(3.0), bg_color);
fn render_small_badge(ui: &mut egui::Ui, text: &str, bg_color: egui::Color32, text_color: egui::Color32) {
let (rect, _) = ui.allocate_exact_size(
egui::vec2(40.0, 16.0),
egui::Sense::hover()
);
ui.painter().rect_filled(
rect,
egui::Rounding::same(3.0),
bg_color
);
ui.painter().text(
rect.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 log::info;
use serde::{Deserialize, Serialize};
use crate::gui::common::{KhmSettings, perform_sync};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SshKey {
@@ -12,12 +12,7 @@ pub struct SshKey {
}
/// 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() {
return Err("Host and flow must be specified".to_string());
}
@@ -30,22 +25,18 @@ pub async fn test_connection(
request = add_auth_if_needed(request, &basic_auth)?;
let response = request
.send()
.await
let response = request.send().await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
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 keys: Vec<SshKey> = serde_json::from_str(&body)
.map_err(|e| format!("Failed to parse response: {}", e))?;
let message = format!("Found {} SSH keys from flow '{}'", keys.len(), flow);
info!("Connection test successful: {}", message);
@@ -53,21 +44,12 @@ pub async fn test_connection(
}
/// 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() {
return Err("Host and flow must be specified".to_string());
}
let url = format!(
"{}/{}/keys?include_deprecated=true",
host.trim_end_matches('/'),
flow
);
let url = format!("{}/{}/keys?include_deprecated=true", host.trim_end_matches('/'), flow);
info!("Fetching keys from: {}", url);
let client = create_http_client()?;
@@ -75,41 +57,26 @@ pub async fn fetch_keys(
request = add_auth_if_needed(request, &basic_auth)?;
let response = request
.send()
.await
let response = request.send().await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
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 keys: Vec<SshKey> = serde_json::from_str(&body)
.map_err(|e| format!("Failed to parse response: {}", e))?;
info!("Fetched {} SSH keys", keys.len());
Ok(keys)
}
/// 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> {
let url = format!(
"{}/{}/keys/{}",
host.trim_end_matches('/'),
flow,
urlencoding::encode(&server)
);
pub async fn deprecate_key(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);
let client = create_http_client()?;
@@ -117,38 +84,20 @@ pub async fn deprecate_key(
request = add_auth_if_needed(request, &basic_auth)?;
let response = request
.send()
.await
let response = request.send().await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
let body = response.text().await
.map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(
&body,
&format!("Successfully deprecated key for server '{}'", server),
)
parse_api_response(&body, &format!("Successfully deprecated key for server '{}'", 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> {
let url = format!(
"{}/{}/keys/{}/restore",
host.trim_end_matches('/'),
flow,
urlencoding::encode(&server)
);
pub async fn restore_key(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);
let client = create_http_client()?;
@@ -156,147 +105,96 @@ pub async fn restore_key(
request = add_auth_if_needed(request, &basic_auth)?;
let response = request
.send()
.await
let response = request.send().await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
let body = response.text().await
.map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(
&body,
&format!("Successfully restored key for server '{}'", server),
)
parse_api_response(&body, &format!("Successfully restored key for server '{}'", 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> {
let url = format!(
"{}/{}/keys/{}/delete",
host.trim_end_matches('/'),
flow,
urlencoding::encode(&server)
);
info!(
"Permanently deleting key for server '{}' at: {}",
server, url
);
pub async fn delete_key(host: String, 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 mut request = client.delete(&url);
request = add_auth_if_needed(request, &basic_auth)?;
let response = request
.send()
.await
let response = request.send().await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
let body = response.text().await
.map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(
&body,
&format!("Successfully deleted key for server '{}'", server),
)
parse_api_response(&body, &format!("Successfully deleted key for server '{}'", server))
}
/// 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);
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
}));
let mut request = client.post(&url)
.json(&serde_json::json!({
"servers": servers
}));
request = add_auth_if_needed(request, &basic_auth)?;
let response = request
.send()
.await
let response = request.send().await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
let body = response.text().await
.map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(&body, "Successfully deprecated 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);
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
}));
let mut request = client.post(&url)
.json(&serde_json::json!({
"servers": servers
}));
request = add_auth_if_needed(request, &basic_auth)?;
let response = request
.send()
.await
let response = request.send().await
.map_err(|e| format!("Request failed: {}", e))?;
check_response_status(&response)?;
let body = response
.text()
.await
let body = response.text().await
.map_err(|e| format!("Failed to read response: {}", e))?;
parse_api_response(&body, "Successfully restored servers")
}
/// Perform manual sync operation
#[cfg(feature = "gui")]
pub async fn perform_manual_sync(settings: KhmSettings) -> Result<String, String> {
match perform_sync(&settings).await {
Ok(keys_count) => Ok(format!(
"Sync completed successfully with {} keys",
keys_count
)),
Ok(keys_count) => Ok(format!("Sync completed successfully with {} keys", keys_count)),
Err(e) => Err(e.to_string()),
}
}
// Helper functions
#[cfg(feature = "gui")]
fn create_http_client() -> Result<Client, String> {
Client::builder()
.timeout(std::time::Duration::from_secs(30))
@@ -305,11 +203,7 @@ fn create_http_client() -> Result<Client, String> {
.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() {
return Ok(request);
}
@@ -322,14 +216,11 @@ fn add_auth_if_needed(
}
}
#[cfg(feature = "gui")]
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(),
);
return Err("Authentication required. Please provide valid basic auth credentials.".to_string());
}
if status >= 300 && status < 400 {
@@ -337,17 +228,12 @@ fn check_response_status(response: &reqwest::Response) -> Result<(), String> {
}
if !response.status().is_success() {
return Err(format!(
"Server returned error: {} {}",
status,
response.status().canonical_reason().unwrap_or("Unknown")
));
return Err(format!("Server returned error: {} {}", status, response.status().canonical_reason().unwrap_or("Unknown")));
}
Ok(())
}
#[cfg(feature = "gui")]
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());
@@ -355,7 +241,6 @@ fn check_html_response(body: &str) -> Result<(), String> {
Ok(())
}
#[cfg(feature = "gui")]
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 Some(message) = json_response.get("message").and_then(|v| v.as_str()) {

View File

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

View File

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

View File

@@ -1,15 +1,9 @@
#[cfg(feature = "gui")]
use dirs::home_dir;
#[cfg(feature = "gui")]
use log::{debug, error, info};
#[cfg(feature = "gui")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "gui")]
use std::fs;
#[cfg(feature = "gui")]
use std::path::PathBuf;
#[cfg(feature = "gui")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KhmSettings {
pub host: String,
@@ -20,7 +14,6 @@ pub struct KhmSettings {
pub auto_sync_interval_minutes: u32,
}
#[cfg(feature = "gui")]
impl Default for KhmSettings {
fn default() -> Self {
Self {
@@ -35,19 +28,22 @@ impl Default for KhmSettings {
}
/// Get default known_hosts file path based on OS
#[cfg(feature = "gui")]
fn get_default_known_hosts_path() -> String {
if let Some(home) = home_dir() {
let ssh_dir = home.join(".ssh");
let known_hosts_file = ssh_dir.join("known_hosts");
known_hosts_file.to_string_lossy().to_string()
} else {
#[cfg(target_os = "windows")]
{
if let Ok(user_profile) = std::env::var("USERPROFILE") {
format!("{}/.ssh/known_hosts", user_profile)
} else {
"~/.ssh/known_hosts".to_string()
}
}
#[cfg(not(target_os = "windows"))]
{
"~/.ssh/known_hosts".to_string()
}
}
/// Get configuration file path
#[cfg(feature = "gui")]
pub fn get_config_path() -> PathBuf {
let mut path = home_dir().expect("Could not find home directory");
path.push(".khm");
@@ -57,7 +53,6 @@ pub fn get_config_path() -> PathBuf {
}
/// Load settings from configuration file
#[cfg(feature = "gui")]
pub fn load_settings() -> KhmSettings {
let path = get_config_path();
match fs::read_to_string(&path) {
@@ -82,7 +77,6 @@ pub fn load_settings() -> KhmSettings {
}
/// Save settings to configuration file
#[cfg(feature = "gui")]
pub fn save_settings(settings: &KhmSettings) -> Result<(), std::io::Error> {
let path = get_config_path();
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
#[cfg(feature = "gui")]
pub fn expand_path(path: &str) -> String {
if path.starts_with("~/") {
if let Some(home) = home_dir() {
@@ -103,28 +96,25 @@ pub fn expand_path(path: &str) -> String {
}
/// Perform sync operation using KHM client logic
#[cfg(feature = "gui")]
pub async fn perform_sync(settings: &KhmSettings) -> Result<usize, std::io::Error> {
use crate::Args;
info!(
"Starting sync with settings: host={}, flow={}, known_hosts={}, in_place={}",
settings.host, settings.flow, settings.known_hosts, settings.in_place
);
info!("Starting sync with settings: host={}, flow={}, known_hosts={}, in_place={}",
settings.host, settings.flow, settings.known_hosts, settings.in_place);
// Convert KhmSettings to Args for client module
let args = Args {
server: false,
daemon: false,
gui: false,
settings_ui: false,
in_place: settings.in_place,
flows: vec!["default".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
db_host: "127.0.0.1".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_password: None, // Not used in client mode
ip: "127.0.0.1".to_string(), // 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_name: "khm".to_string(), // Not used in client mode
db_user: None, // Not used in client mode
db_password: None, // Not used in client mode
host: Some(settings.host.clone()),
flow: Some(settings.flow.clone()),
known_hosts: expand_path(&settings.known_hosts),
@@ -148,9 +138,6 @@ pub async fn perform_sync(settings: &KhmSettings) -> Result<usize, std::io::Erro
keys_before
};
info!(
"Sync completed: {} keys before, {} keys after",
keys_before, keys_after
);
info!("Sync completed: {} keys before, {} keys after", keys_before, keys_after);
Ok(keys_after)
}

View File

@@ -1,10 +1,8 @@
#[cfg(feature = "gui")]
use log::info;
// Modules
#[cfg(feature = "gui")]
mod admin;
mod api;
mod admin;
mod common;
#[cfg(feature = "gui")]
@@ -40,6 +38,6 @@ pub async fn run_gui() -> std::io::Result<()> {
pub async fn run_gui() -> std::io::Result<()> {
return Err(std::io::Error::new(
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 log::{error, info};
use std::sync::mpsc;
use crate::gui::api::{test_connection, perform_manual_sync};
use crate::gui::common::{KhmSettings, save_settings};
#[derive(Debug, Clone)]
pub enum ConnectionStatus {
@@ -31,7 +31,6 @@ pub struct ConnectionTab {
pub is_syncing: bool,
pub sync_result_receiver: Option<mpsc::Receiver<Result<String, String>>>,
pub sync_status: SyncStatus,
pub should_auto_test: bool,
}
impl Default for ConnectionTab {
@@ -43,7 +42,6 @@ impl Default for ConnectionTab {
is_syncing: false,
sync_result_receiver: None,
sync_status: SyncStatus::Unknown,
should_auto_test: false,
}
}
}
@@ -68,7 +66,9 @@ impl ConnectionTab {
std::thread::spawn(move || {
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);
ctx_clone.request_repaint();
@@ -92,25 +92,17 @@ impl ConnectionTab {
std::thread::spawn(move || {
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);
ctx_clone.request_repaint();
});
}
/// Check for test/sync results and handle auto-test
pub fn check_results(
&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/sync results
pub fn check_results(&mut self, ctx: &egui::Context, settings: &KhmSettings, operation_log: &mut Vec<String>) {
// Check for test connection result
if let Some(receiver) = &self.test_result_receiver {
if let Ok(result) = receiver.try_recv() {
@@ -120,37 +112,25 @@ impl ConnectionTab {
// Parse keys count from message
let keys_count = if let Some(start) = message.find("Found ") {
if let Some(end) = message[start + 6..].find(" SSH keys") {
message[start + 6..start + 6 + end]
.parse::<usize>()
.unwrap_or(0)
} else {
0
}
} else {
0
};
message[start + 6..start + 6 + end].parse::<usize>().unwrap_or(0)
} else { 0 }
} else { 0 };
self.connection_status = ConnectionStatus::Connected {
keys_count,
flow: settings.flow.clone(),
flow: settings.flow.clone()
};
info!("Connection test successful: {}", message);
// Add to UI log
super::ui::add_log_entry(
operation_log,
format!("✅ Connection test successful: {}", message),
);
super::ui::add_log_entry(operation_log, format!("✅ Connection test successful: {}", message));
}
Err(error) => {
self.connection_status = ConnectionStatus::Error(error.clone());
error!("Connection test failed");
// Add to UI log
super::ui::add_log_entry(
operation_log,
format!("❌ Connection test failed: {}", error),
);
super::ui::add_log_entry(operation_log, format!("❌ Connection test failed: {}", error));
}
}
self.test_result_receiver = None;
@@ -170,20 +150,14 @@ impl ConnectionTab {
info!("Sync successful: {}", message);
// Add to UI log
super::ui::add_log_entry(
operation_log,
format!("✅ Sync completed: {}", message),
);
super::ui::add_log_entry(operation_log, format!("✅ Sync completed: {}", message));
}
Err(error) => {
self.sync_status = SyncStatus::Error(error.clone());
error!("Sync failed");
// Add to UI log
super::ui::add_log_entry(
operation_log,
format!("❌ Sync failed: {}", error),
);
super::ui::add_log_entry(operation_log, format!("❌ Sync failed: {}", error));
}
}
self.sync_result_receiver = None;

View File

@@ -1,6 +1,6 @@
use super::connection::{save_settings_validated, ConnectionStatus, ConnectionTab, SyncStatus};
use crate::gui::common::{get_config_path, KhmSettings};
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
pub fn render_connection_tab(
@@ -9,7 +9,7 @@ pub fn render_connection_tab(
settings: &mut KhmSettings,
auto_sync_interval_str: &mut String,
connection_tab: &mut ConnectionTab,
operation_log: &mut Vec<String>,
operation_log: &mut Vec<String>
) {
// Check for connection test and sync results
connection_tab.check_results(ctx, settings, operation_log);
@@ -41,7 +41,7 @@ pub fn render_connection_tab(
// Local Configuration Card
render_local_config_card(ui, settings);
},
}
);
ui.add_space(8.0);
@@ -56,7 +56,7 @@ pub fn render_connection_tab(
// System Information Card
render_system_info_card(ui);
},
}
);
});
@@ -71,10 +71,7 @@ pub fn render_connection_tab(
fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionTab) {
let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
.rounding(6.0)
.inner_margin(egui::Margin::same(12.0));
@@ -88,13 +85,11 @@ fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionT
} else {
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 => {
("", "Not Connected".to_string(), ui.visuals().text_color())
}
@@ -106,17 +101,9 @@ fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionT
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if connection_tab.is_testing_connection {
ui.spinner();
ui.label(
egui::RichText::new("Testing...")
.italics()
.color(ui.visuals().weak_text_color()),
);
ui.label(egui::RichText::new("Testing...").italics().color(ui.visuals().weak_text_color()));
} else {
ui.label(
egui::RichText::new(&status_text)
.size(13.0)
.color(status_color),
);
ui.label(egui::RichText::new(&status_text).size(13.0).color(status_color));
}
});
});
@@ -132,26 +119,17 @@ fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionT
match &connection_tab.sync_status {
SyncStatus::Success { keys_count } => {
ui.label(
egui::RichText::new(format!("{} keys synced", keys_count))
.size(13.0)
.color(egui::Color32::GREEN),
);
ui.label(egui::RichText::new(format!("{} keys synced", keys_count))
.size(13.0).color(egui::Color32::GREEN));
}
SyncStatus::Error(error_msg) => {
ui.label(
egui::RichText::new("❌ Failed")
.size(13.0)
.color(egui::Color32::RED),
)
.on_hover_text(error_msg);
ui.label(egui::RichText::new("❌ Failed")
.size(13.0).color(egui::Color32::RED))
.on_hover_text(error_msg);
}
SyncStatus::Unknown => {
ui.label(
egui::RichText::new("No sync performed yet")
.size(13.0)
.color(ui.visuals().weak_text_color()),
);
ui.label(egui::RichText::new("No sync performed yet")
.size(13.0).color(ui.visuals().weak_text_color()));
}
}
});
@@ -164,10 +142,7 @@ fn render_connection_status_card(ui: &mut egui::Ui, connection_tab: &ConnectionT
fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
.rounding(6.0)
.inner_margin(egui::Margin::same(12.0));
@@ -175,11 +150,7 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
// Header
ui.horizontal(|ui| {
ui.label("🌐");
ui.label(
egui::RichText::new("Server Configuration")
.size(14.0)
.strong(),
);
ui.label(egui::RichText::new("Server Configuration").size(14.0).strong());
});
ui.add_space(8.0);
@@ -197,7 +168,7 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
egui::TextEdit::singleline(&mut settings.host)
.hint_text("https://your-khm-server.com")
.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
);
});
@@ -210,24 +181,15 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
egui::TextEdit::singleline(&mut settings.flow)
.hint_text("production, staging, development")
.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)
ui.vertical(|ui| {
ui.horizontal(|ui| {
ui.label(
egui::RichText::new("Basic Authentication")
.size(13.0)
.strong(),
);
ui.label(
egui::RichText::new("(optional)")
.size(12.0)
.weak()
.italics(),
);
ui.label(egui::RichText::new("Basic Authentication").size(13.0).strong());
ui.label(egui::RichText::new("(optional)").size(12.0).weak().italics());
});
ui.add_space(3.0);
ui.add_sized(
@@ -236,7 +198,7 @@ fn render_connection_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings)
.hint_text("username:password")
.password(true)
.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))
);
});
});
@@ -249,10 +211,7 @@ fn render_connection_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())
.fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
.rounding(6.0)
.inner_margin(egui::Margin::same(12.0));
@@ -260,29 +219,21 @@ fn render_local_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
// Header
ui.horizontal(|ui| {
ui.label("📁");
ui.label(
egui::RichText::new("Local Configuration")
.size(14.0)
.strong(),
);
ui.label(egui::RichText::new("Local Configuration").size(14.0).strong());
});
ui.add_space(8.0);
// Known hosts file
ui.vertical(|ui| {
ui.label(
egui::RichText::new("Known Hosts File Path")
.size(13.0)
.strong(),
);
ui.label(egui::RichText::new("Known Hosts File Path").size(13.0).strong());
ui.add_space(3.0);
ui.add_sized(
[ui.available_width(), 28.0],
egui::TextEdit::singleline(&mut settings.known_hosts)
.hint_text("~/.ssh/known_hosts")
.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);
@@ -291,19 +242,8 @@ fn render_local_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
ui.horizontal(|ui| {
ui.checkbox(&mut settings.in_place, "");
ui.vertical(|ui| {
ui.label(
egui::RichText::new("Update file in-place after sync")
.size(13.0)
.strong(),
);
ui.label(
egui::RichText::new(
"Automatically modify the known_hosts file when synchronizing",
)
.size(12.0)
.weak()
.italics(),
);
ui.label(egui::RichText::new("Update file in-place after sync").size(13.0).strong());
ui.label(egui::RichText::new("Automatically modify the known_hosts file when synchronizing").size(12.0).weak().italics());
});
});
});
@@ -313,23 +253,17 @@ fn render_local_config_card(ui: &mut egui::Ui, settings: &mut KhmSettings) {
}
/// Auto-sync configuration card
fn render_auto_sync_card(
ui: &mut egui::Ui,
settings: &mut KhmSettings,
auto_sync_interval_str: &mut String,
) {
fn render_auto_sync_card(ui: &mut egui::Ui, settings: &mut KhmSettings, auto_sync_interval_str: &mut String) {
let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().faint_bg_color)
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
.rounding(6.0)
.inner_margin(egui::Margin::same(12.0));
frame.show(ui, |ui| {
let is_auto_sync_enabled =
!settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
let is_auto_sync_enabled = !settings.host.is_empty()
&& !settings.flow.is_empty()
&& settings.in_place;
// Header with status
ui.horizontal(|ui| {
@@ -338,16 +272,12 @@ fn render_auto_sync_card(
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let (status_text, status_color) = if is_auto_sync_enabled {
(" Active", egui::Color32::GREEN)
(" Active", egui::Color32::GREEN)
} else {
(" Inactive", egui::Color32::from_gray(128))
(" Inactive", egui::Color32::from_gray(128))
};
ui.label(
egui::RichText::new(status_text)
.size(12.0)
.color(status_color),
);
ui.label(egui::RichText::new(status_text).size(12.0).color(status_color));
});
});
@@ -358,11 +288,11 @@ fn render_auto_sync_card(
ui.label(egui::RichText::new("Interval").size(13.0).strong());
ui.add_space(6.0);
ui.add_sized(
[80.0, 26.0], // Smaller height
egui::TextEdit::singleline(auto_sync_interval_str)
.font(egui::FontId::new(14.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(6.0, 5.0)),
);
[80.0, 26.0], // Smaller height
egui::TextEdit::singleline(auto_sync_interval_str)
.font(egui::FontId::new(14.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(6.0, 5.0))
);
ui.label("min");
// Update the actual setting
@@ -387,31 +317,19 @@ fn render_auto_sync_card(
let in_place_ok = settings.in_place;
ui.horizontal(|ui| {
let (icon, color) = if host_ok {
("", egui::Color32::GREEN)
} else {
("", egui::Color32::RED)
};
let (icon, color) = if host_ok { ("", egui::Color32::GREEN) } else { ("", egui::Color32::RED) };
ui.label(egui::RichText::new(icon).color(color));
ui.label(egui::RichText::new("Host URL").size(11.0));
});
ui.horizontal(|ui| {
let (icon, color) = if flow_ok {
("", egui::Color32::GREEN)
} else {
("", egui::Color32::RED)
};
let (icon, color) = if flow_ok { ("", egui::Color32::GREEN) } else { ("", egui::Color32::RED) };
ui.label(egui::RichText::new(icon).color(color));
ui.label(egui::RichText::new("Flow name").size(11.0));
});
ui.horizontal(|ui| {
let (icon, color) = if in_place_ok {
("", egui::Color32::GREEN)
} else {
("", egui::Color32::RED)
};
let (icon, color) = if in_place_ok { ("", egui::Color32::GREEN) } else { ("", egui::Color32::RED) };
ui.label(egui::RichText::new(icon).color(color));
ui.label(egui::RichText::new("In-place update").size(11.0));
});
@@ -425,17 +343,14 @@ fn render_auto_sync_card(
fn render_system_info_card(ui: &mut egui::Ui) {
let frame = egui::Frame::group(ui.style())
.fill(ui.visuals().extreme_bg_color)
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
))
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color))
.rounding(6.0)
.inner_margin(egui::Margin::same(12.0));
frame.show(ui, |ui| {
// Header
ui.horizontal(|ui| {
ui.label("🔧");
ui.label("⚙️");
ui.label(egui::RichText::new("System Info").size(14.0).strong());
});
@@ -451,12 +366,12 @@ fn render_system_info_card(ui: &mut egui::Ui) {
ui.vertical(|ui| {
ui.add_sized(
[ui.available_width(), 26.0], // Smaller height
egui::TextEdit::singleline(&mut path_str.clone())
.interactive(false)
.font(egui::FontId::new(12.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(8.0, 5.0)),
);
[ui.available_width(), 26.0], // Smaller height
egui::TextEdit::singleline(&mut path_str.clone())
.interactive(false)
.font(egui::FontId::new(12.0, egui::FontFamily::Monospace))
.margin(egui::Margin::symmetric(8.0, 5.0))
);
ui.add_space(4.0);
@@ -476,22 +391,25 @@ fn render_action_section(
ctx: &egui::Context,
settings: &KhmSettings,
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();
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
render_modern_action_buttons(
ui,
ctx,
settings,
connection_tab,
save_enabled,
operation_log,
);
render_modern_action_buttons(ui, ctx, settings, connection_tab, save_enabled, operation_log);
}
/// Modern action buttons with improved styling and layout
@@ -501,13 +419,13 @@ fn render_modern_action_buttons(
settings: &KhmSettings,
connection_tab: &mut ConnectionTab,
save_enabled: bool,
operation_log: &mut Vec<String>,
operation_log: &mut Vec<String>
) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 8.0;
// Primary actions (left side)
let mut save_button = ui.add_enabled(
if ui.add_enabled(
save_enabled,
egui::Button::new(
egui::RichText::new("💾 Save & Close")
@@ -521,14 +439,7 @@ fn render_modern_action_buttons(
})
.min_size(egui::vec2(120.0, 32.0))
.rounding(6.0)
);
// 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() {
).clicked() {
match save_settings_validated(settings) {
Ok(()) => {
add_log_entry(operation_log, "✅ Settings saved successfully".to_string());

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 log::info;
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::ui::{add_log_entry, render_connection_tab};
use super::ui::{render_connection_tab, add_log_entry};
pub struct SettingsWindow {
settings: KhmSettings,
@@ -29,7 +26,7 @@ impl SettingsWindow {
let settings = load_settings();
let auto_sync_interval_str = settings.auto_sync_interval_minutes.to_string();
let mut instance = Self {
Self {
settings,
auto_sync_interval_str,
current_tab: SettingsTab::Connection,
@@ -38,20 +35,7 @@ impl SettingsWindow {
admin_receiver: None,
operation_receiver: None,
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
}
}
@@ -68,20 +52,18 @@ impl eframe::App for SettingsWindow {
.resizable(false)
.min_height(140.0)
.max_height(140.0)
.frame(
egui::Frame::none()
.fill(egui::Color32::from_gray(12))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_gray(60))),
.frame(egui::Frame::none()
.fill(egui::Color32::from_gray(12))
.stroke(egui::Stroke::new(1.0, egui::Color32::from_gray(60)))
)
.show(ctx, |ui| {
render_bottom_activity_log(ui, &mut self.operation_log);
});
egui::CentralPanel::default()
.frame(
egui::Frame::none()
.fill(egui::Color32::from_gray(18))
.inner_margin(egui::Margin::same(20.0)),
.frame(egui::Frame::none()
.fill(egui::Color32::from_gray(18))
.inner_margin(egui::Margin::same(20.0))
)
.show(ctx, |ui| {
// Modern header with gradient-like styling
@@ -89,30 +71,21 @@ impl eframe::App for SettingsWindow {
.fill(ui.visuals().panel_fill)
.rounding(egui::Rounding::same(8.0))
.inner_margin(egui::Margin::same(12.0))
.stroke(egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
));
.stroke(egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color));
header_frame.show(ui, |ui| {
ui.horizontal(|ui| {
ui.add_space(4.0);
ui.label("🔑");
ui.heading(egui::RichText::new("KHM Settings").size(20.0).strong());
ui.label(
egui::RichText::new(
"(Known Hosts Manager for SSH key management and synchronization)",
)
.size(11.0)
.weak()
.italics(),
);
ui.label(egui::RichText::new(
"(Known Hosts Manager for SSH key management and synchronization)"
).size(11.0).weak().italics());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Version from Cargo.toml
let version = env!("CARGO_PKG_VERSION");
if ui
.small_button(format!("v{}", version))
if ui.small_button(format!("v{}", version))
.on_hover_text(format!(
"{}\n{}\nRepository: {}\nLicense: {}",
env!("CARGO_PKG_DESCRIPTION"),
@@ -145,23 +118,21 @@ impl eframe::App for SettingsWindow {
// Connection/Settings Tab
let connection_selected = matches!(self.current_tab, SettingsTab::Connection);
let connection_button =
egui::Button::new(egui::RichText::new("🌐 Connection").size(13.0))
.fill(if connection_selected {
egui::Color32::from_rgb(0, 120, 212)
} else {
ui.visuals().widgets.inactive.bg_fill
})
.stroke(if connection_selected {
egui::Stroke::new(1.0, egui::Color32::from_rgb(0, 120, 212))
} else {
egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
)
})
.rounding(6.0)
.min_size(egui::vec2(110.0, 32.0));
let connection_button = egui::Button::new(
egui::RichText::new("🌐 Connection").size(13.0)
)
.fill(if connection_selected {
egui::Color32::from_rgb(0, 120, 212)
} else {
ui.visuals().widgets.inactive.bg_fill
})
.stroke(if connection_selected {
egui::Stroke::new(1.0, egui::Color32::from_rgb(0, 120, 212))
} else {
egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color)
})
.rounding(6.0)
.min_size(egui::vec2(110.0, 32.0));
if ui.add(connection_button).clicked() {
self.current_tab = SettingsTab::Connection;
@@ -169,23 +140,21 @@ impl eframe::App for SettingsWindow {
// Admin Tab
let admin_selected = matches!(self.current_tab, SettingsTab::Admin);
let admin_button =
egui::Button::new(egui::RichText::new("🔧 Admin Panel").size(13.0))
.fill(if admin_selected {
egui::Color32::from_rgb(120, 80, 0)
} else {
ui.visuals().widgets.inactive.bg_fill
})
.stroke(if admin_selected {
egui::Stroke::new(1.0, egui::Color32::from_rgb(120, 80, 0))
} else {
egui::Stroke::new(
1.0,
ui.visuals().widgets.noninteractive.bg_stroke.color,
)
})
.rounding(6.0)
.min_size(egui::vec2(110.0, 32.0));
let admin_button = egui::Button::new(
egui::RichText::new("🔧 Admin Panel").size(13.0)
)
.fill(if admin_selected {
egui::Color32::from_rgb(120, 80, 0)
} else {
ui.visuals().widgets.inactive.bg_fill
})
.stroke(if admin_selected {
egui::Stroke::new(1.0, egui::Color32::from_rgb(120, 80, 0))
} else {
egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color)
})
.rounding(6.0)
.min_size(egui::vec2(110.0, 32.0));
if ui.add(admin_button).clicked() {
self.current_tab = SettingsTab::Admin;
@@ -203,7 +172,7 @@ impl eframe::App for SettingsWindow {
&mut self.settings,
&mut self.auto_sync_interval_str,
&mut self.connection_tab,
&mut self.operation_log,
&mut self.operation_log
);
}
SettingsTab::Admin => {
@@ -236,10 +205,7 @@ impl SettingsWindow {
self.load_admin_keys(ctx);
}
Err(error) => {
add_log_entry(
&mut self.operation_log,
format!("❌ Operation failed: {}", error),
);
add_log_entry(&mut self.operation_log, format!("❌ Operation failed: {}", error));
}
}
self.admin_state.current_operation = AdminOperation::None;
@@ -272,11 +238,9 @@ impl SettingsWindow {
// Check if connection is configured
if self.settings.host.is_empty() || self.settings.flow.is_empty() {
ui.vertical_centered(|ui| {
ui.label(
egui::RichText::new("❗ Please configure connection settings first")
.size(16.0)
.color(egui::Color32::YELLOW),
);
ui.label(egui::RichText::new("❗ Please configure connection settings first")
.size(16.0)
.color(egui::Color32::YELLOW));
ui.add_space(10.0);
if ui.button("Go to Connection Settings").clicked() {
self.current_tab = SettingsTab::Connection;
@@ -286,20 +250,12 @@ impl SettingsWindow {
}
// Load keys automatically on first view
if self.admin_state.keys.is_empty()
&& !matches!(
self.admin_state.current_operation,
AdminOperation::LoadingKeys
)
{
if self.admin_state.keys.is_empty() && !matches!(self.admin_state.current_operation, AdminOperation::LoadingKeys) {
self.load_admin_keys(ctx);
}
// Show loading state
if matches!(
self.admin_state.current_operation,
AdminOperation::LoadingKeys
) {
if matches!(self.admin_state.current_operation, AdminOperation::LoadingKeys) {
ui.vertical_centered(|ui| {
ui.spinner();
ui.label("Loading keys...");
@@ -377,10 +333,7 @@ impl SettingsWindow {
fn start_bulk_deprecate(&mut self, servers: Vec<String>, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::BulkDeprecating;
add_log_entry(
&mut self.operation_log,
format!("Deprecating {} servers...", servers.len()),
);
add_log_entry(&mut self.operation_log, format!("Deprecating {} servers...", servers.len()));
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
@@ -392,8 +345,9 @@ impl SettingsWindow {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result = rt
.block_on(async { bulk_deprecate_servers(host, flow, basic_auth, servers).await });
let result = rt.block_on(async {
bulk_deprecate_servers(host, flow, basic_auth, servers).await
});
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -402,10 +356,7 @@ impl SettingsWindow {
fn start_bulk_restore(&mut self, servers: Vec<String>, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::BulkRestoring;
add_log_entry(
&mut self.operation_log,
format!("Restoring {} servers...", servers.len()),
);
add_log_entry(&mut self.operation_log, format!("Restoring {} servers...", servers.len()));
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
@@ -417,8 +368,9 @@ impl SettingsWindow {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result =
rt.block_on(async { bulk_restore_servers(host, flow, basic_auth, servers).await });
let result = rt.block_on(async {
bulk_restore_servers(host, flow, basic_auth, servers).await
});
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -427,10 +379,7 @@ impl SettingsWindow {
fn start_deprecate_key(&mut self, server: &str, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::DeprecatingKey;
add_log_entry(
&mut self.operation_log,
format!("Deprecating key for server: {}", server),
);
add_log_entry(&mut self.operation_log, format!("Deprecating key for server: {}", server));
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
@@ -443,8 +392,9 @@ impl SettingsWindow {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result =
rt.block_on(async { deprecate_key(host, flow, basic_auth, server_name).await });
let result = rt.block_on(async {
deprecate_key(host, flow, basic_auth, server_name).await
});
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -453,10 +403,7 @@ impl SettingsWindow {
fn start_restore_key(&mut self, server: &str, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::RestoringKey;
add_log_entry(
&mut self.operation_log,
format!("Restoring key for server: {}", server),
);
add_log_entry(&mut self.operation_log, format!("Restoring key for server: {}", server));
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
@@ -469,8 +416,9 @@ impl SettingsWindow {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result =
rt.block_on(async { restore_key(host, flow, basic_auth, server_name).await });
let result = rt.block_on(async {
restore_key(host, flow, basic_auth, server_name).await
});
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -479,10 +427,7 @@ impl SettingsWindow {
fn start_delete_key(&mut self, server: &str, ctx: &egui::Context) {
self.admin_state.current_operation = AdminOperation::DeletingKey;
add_log_entry(
&mut self.operation_log,
format!("Deleting key for server: {}", server),
);
add_log_entry(&mut self.operation_log, format!("Deleting key for server: {}", server));
let (tx, rx) = mpsc::channel();
self.operation_receiver = Some(rx);
@@ -495,8 +440,9 @@ impl SettingsWindow {
std::thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
let result =
rt.block_on(async { delete_key(host, flow, basic_auth, server_name).await });
let result = rt.block_on(async {
delete_key(host, flow, basic_auth, server_name).await
});
let _ = tx.send(result);
ctx_clone.request_repaint();
@@ -509,8 +455,8 @@ fn apply_modern_theme(ctx: &egui::Context) {
let mut visuals = egui::Visuals::dark();
// Modern color palette
visuals.window_fill = egui::Color32::from_gray(18); // Darker background
visuals.panel_fill = egui::Color32::from_gray(24); // Panel background
visuals.window_fill = egui::Color32::from_gray(18); // Darker background
visuals.panel_fill = egui::Color32::from_gray(24); // Panel background
visuals.faint_bg_color = egui::Color32::from_gray(32); // Card background
visuals.extreme_bg_color = egui::Color32::from_gray(12); // Darkest areas
@@ -584,7 +530,7 @@ fn render_bottom_activity_log(ui: &mut egui::Ui, operation_log: &mut Vec<String>
[ui.available_width() - 8.0, 80.0], // Account for right margin
egui::TextEdit::multiline(&mut log_text.clone())
.font(egui::FontId::new(11.0, egui::FontFamily::Monospace))
.interactive(false),
.interactive(false)
);
ui.add_space(8.0); // Right margin
@@ -619,8 +565,8 @@ pub fn run_settings_window() {
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("KHM Settings")
.with_inner_size([900.0, 905.0]) // Decreased height by another 15px
.with_min_inner_size([900.0, 905.0]) // Fixed size
.with_inner_size([900.0, 905.0]) // Decreased height by another 15px
.with_min_inner_size([900.0, 905.0]) // 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_icon(create_window_icon())

View File

@@ -6,7 +6,10 @@ use notify::RecursiveMode;
use notify_debouncer_mini::{new_debouncer, DebounceEventResult};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tray_icon::{menu::MenuEvent, TrayIcon};
use tray_icon::{
menu::MenuEvent,
TrayIcon,
};
use winit::{
application::ApplicationHandler,
event_loop::{EventLoop, EventLoopProxy},
@@ -15,52 +18,12 @@ use winit::{
#[cfg(target_os = "macos")]
use winit::platform::macos::EventLoopBuilderExtMacOS;
#[cfg(target_os = "linux")]
use gtk::glib;
// 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};
use super::{SyncStatus, TrayMenuIds, create_tray_icon, update_tray_menu,
create_tooltip, start_auto_sync_task, update_sync_status};
use crate::gui::common::{load_settings, get_config_path, perform_sync, KhmSettings};
pub struct TrayApplication {
#[cfg(not(target_os = "linux"))]
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>,
settings: Arc<Mutex<KhmSettings>>,
sync_status: Arc<Mutex<SyncStatus>>,
@@ -73,12 +36,7 @@ pub struct TrayApplication {
impl TrayApplication {
pub fn new(proxy: EventLoopProxy<crate::gui::UserEvent>) -> Self {
Self {
#[cfg(not(target_os = "linux"))]
tray_icon: None,
#[cfg(target_os = "linux")]
linux_tray_tx: None,
#[cfg(target_os = "linux")]
linux_tray_handle: None,
menu_ids: None,
settings: Arc::new(Mutex::new(load_settings())),
sync_status: Arc::new(Mutex::new(SyncStatus::default())),
@@ -98,10 +56,7 @@ impl TrayApplication {
std::thread::spawn(move || {
while let Ok(result) = rx.recv() {
if let Ok(events) = result {
if events
.iter()
.any(|e| e.path.to_string_lossy().contains("khm_config.json"))
{
if events.iter().any(|e| e.path.to_string_lossy().contains("khm_config.json")) {
let _ = proxy.send_event(crate::gui::UserEvent::ConfigFileChanged);
}
}
@@ -110,11 +65,7 @@ impl TrayApplication {
if let Ok(mut debouncer) = new_debouncer(Duration::from_millis(500), tx) {
if let Some(config_dir) = config_path.parent() {
if debouncer
.watcher()
.watch(config_dir, RecursiveMode::NonRecursive)
.is_ok()
{
if debouncer.watcher().watch(config_dir, RecursiveMode::NonRecursive).is_ok() {
info!("File watcher started");
self._debouncer = Some(debouncer);
} else {
@@ -133,28 +84,18 @@ impl TrayApplication {
*self.settings.lock().unwrap() = new_settings;
// Update menu
#[cfg(not(target_os = "linux"))]
if let Some(tray_icon) = &self.tray_icon {
let settings = self.settings.lock().unwrap();
let new_menu_ids = update_tray_menu(tray_icon, &settings);
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
self.update_tooltip();
// Restart auto sync if interval changed
if old_interval != new_interval {
info!(
"Auto sync interval changed from {} to {} minutes, restarting auto sync",
old_interval, new_interval
);
info!("Auto sync interval changed from {} to {} minutes, restarting auto sync", old_interval, new_interval);
self.start_auto_sync();
}
}
@@ -168,31 +109,20 @@ impl TrayApplication {
self.auto_sync_handle = start_auto_sync_task(
Arc::clone(&self.settings),
Arc::clone(&self.sync_status),
self.proxy.clone(),
self.proxy.clone()
);
}
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 {
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));
}
#[cfg(target_os = "linux")]
if let Some(ref tx) = self.linux_tray_tx {
let _ = tx.send(LinuxTrayCommand::SetTooltip { tooltip });
}
}
fn handle_menu_event(
&mut self,
event: MenuEvent,
event_loop: &winit::event_loop::ActiveEventLoop,
) {
fn handle_menu_event(&mut self, event: MenuEvent, event_loop: &winit::event_loop::ActiveEventLoop) {
if let Some(menu_ids) = &self.menu_ids {
if event.id == menu_ids.settings_id {
info!("Settings menu clicked");
@@ -211,6 +141,7 @@ impl TrayApplication {
if let Ok(exe_path) = std::env::current_exe() {
std::thread::spawn(move || {
if let Err(e) = std::process::Command::new(&exe_path)
.arg("--gui")
.arg("--settings-ui")
.spawn()
{
@@ -231,10 +162,7 @@ impl TrayApplication {
return;
}
info!(
"Syncing with host: {}, flow: {}",
settings.host, settings.flow
);
info!("Syncing with host: {}, flow: {}", settings.host, settings.flow);
// Run sync in separate thread with its own tokio runtime
std::thread::spawn(move || {
@@ -274,141 +202,27 @@ impl ApplicationHandler<crate::gui::UserEvent> for TrayApplication {
_event_loop: &winit::event_loop::ActiveEventLoop,
_window_id: winit::window::WindowId,
_event: winit::event::WindowEvent,
) {
}
) {}
fn resumed(&mut self, _event_loop: &winit::event_loop::ActiveEventLoop) {
#[cfg(not(target_os = "linux"))]
if self.tray_icon.is_none() {
info!("Creating tray icon");
let settings = self.settings.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)) {
Ok((tray_icon, menu_ids)) => {
drop(settings);
drop(sync_status);
self.tray_icon = Some(tray_icon);
self.menu_ids = Some(menu_ids);
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();
let (response_tx, response_rx) = std::sync::mpsc::channel();
self.linux_tray_tx = Some(tx.clone());
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);
}
}
}
self.setup_file_watcher();
self.start_auto_sync();
info!("KHM tray application ready");
}
}
fn user_event(
&mut self,
event_loop: &winit::event_loop::ActiveEventLoop,
event: crate::gui::UserEvent,
) {
fn user_event(&mut self, event_loop: &winit::event_loop::ActiveEventLoop, event: crate::gui::UserEvent) {
match event {
crate::gui::UserEvent::TrayIconEvent => {}
crate::gui::UserEvent::UpdateMenu => {
@@ -432,23 +246,12 @@ pub async fn run_tray_app() -> std::io::Result<()> {
EventLoop::<crate::gui::UserEvent>::with_user_event()
.with_activation_policy(ActivationPolicy::Accessory)
.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)))?
};
#[cfg(not(target_os = "macos"))]
let event_loop = EventLoop::<crate::gui::UserEvent>::with_user_event()
.build()
.map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("Failed to create event loop: {}", e),
)
})?;
let event_loop = EventLoop::<crate::gui::UserEvent>::with_user_event().build()
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("Failed to create event loop: {}", e)))?;
let proxy = event_loop.create_proxy();
@@ -465,12 +268,8 @@ pub async fn run_tray_app() -> std::io::Result<()> {
let mut app = TrayApplication::new(proxy);
event_loop.run_app(&mut app).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("Event loop error: {:?}", e),
)
})?;
event_loop.run_app(&mut app)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("Event loop error: {:?}", e)))?;
Ok(())
}

View File

@@ -1,10 +1,10 @@
use crate::gui::common::{perform_sync, KhmSettings};
use log::{error, info};
use std::sync::{Arc, Mutex};
use tray_icon::{
menu::{Menu, MenuId, MenuItem},
menu::{Menu, MenuItem, MenuId},
TrayIcon, TrayIconBuilder,
};
use crate::gui::common::{KhmSettings, perform_sync};
#[derive(Debug, Clone)]
pub struct SyncStatus {
@@ -30,22 +30,17 @@ pub struct TrayMenuIds {
}
/// Create tray icon with menu
pub fn create_tray_icon(
settings: &KhmSettings,
sync_status: &SyncStatus,
) -> (TrayIcon, TrayMenuIds) {
pub fn create_tray_icon(settings: &KhmSettings, sync_status: &SyncStatus) -> (TrayIcon, TrayMenuIds) {
// Create simple blue icon
let icon_data: Vec<u8> = (0..32 * 32)
.flat_map(|i| {
let y = i / 32;
let x = i % 32;
if x < 2 || x >= 30 || y < 2 || y >= 30 {
[255, 255, 255, 255] // White border
} else {
[64, 128, 255, 255] // Blue center
}
})
.collect();
let icon_data: Vec<u8> = (0..32*32).flat_map(|i| {
let y = i / 32;
let x = i % 32;
if x < 2 || x >= 30 || y < 2 || y >= 30 {
[255, 255, 255, 255] // White border
} else {
[64, 128, 255, 255] // Blue center
}
}).collect();
let icon = tray_icon::Icon::from_rgba(icon_data, 32, 32).unwrap();
let menu = Menu::new();
@@ -65,38 +60,27 @@ pub fn create_tray_icon(
};
menu.append(&MenuItem::new(flow_text, false, None)).unwrap();
let is_auto_sync_enabled =
!settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
let sync_text = format!(
"Auto sync: {} ({}min)",
if is_auto_sync_enabled { "On" } else { "Off" },
settings.auto_sync_interval_minutes
);
menu.append(&MenuItem::new(&sync_text, false, None))
.unwrap();
let is_auto_sync_enabled = !settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
let sync_text = format!("Auto sync: {} ({}min)",
if is_auto_sync_enabled { "On" } else { "Off" },
settings.auto_sync_interval_minutes);
menu.append(&MenuItem::new(&sync_text, false, None)).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
// Sync Now menu item
let sync_item = MenuItem::new(
"Sync Now",
!settings.host.is_empty() && !settings.flow.is_empty(),
None,
);
let sync_item = MenuItem::new("Sync Now", !settings.host.is_empty() && !settings.flow.is_empty(), None);
let sync_id = sync_item.id().clone();
menu.append(&sync_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
// Settings menu item
let settings_item = MenuItem::new("Settings", true, None);
let settings_id = settings_item.id().clone();
menu.append(&settings_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
// Quit menu item
let quit_item = MenuItem::new("Quit", true, None);
@@ -141,38 +125,27 @@ pub fn update_tray_menu(tray_icon: &TrayIcon, settings: &KhmSettings) -> TrayMen
};
menu.append(&MenuItem::new(flow_text, false, None)).unwrap();
let is_auto_sync_enabled =
!settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
let sync_text = format!(
"Auto sync: {} ({}min)",
if is_auto_sync_enabled { "On" } else { "Off" },
settings.auto_sync_interval_minutes
);
menu.append(&MenuItem::new(&sync_text, false, None))
.unwrap();
let is_auto_sync_enabled = !settings.host.is_empty() && !settings.flow.is_empty() && settings.in_place;
let sync_text = format!("Auto sync: {} ({}min)",
if is_auto_sync_enabled { "On" } else { "Off" },
settings.auto_sync_interval_minutes);
menu.append(&MenuItem::new(&sync_text, false, None)).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
// Sync Now menu item
let sync_item = MenuItem::new(
"Sync Now",
!settings.host.is_empty() && !settings.flow.is_empty(),
None,
);
let sync_item = MenuItem::new("Sync Now", !settings.host.is_empty() && !settings.flow.is_empty(), None);
let sync_id = sync_item.id().clone();
menu.append(&sync_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
// Settings menu item
let settings_item = MenuItem::new("Settings", true, None);
let settings_id = settings_item.id().clone();
menu.append(&settings_item).unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator())
.unwrap();
menu.append(&tray_icon::menu::PredefinedMenuItem::separator()).unwrap();
// Quit menu item
let quit_item = MenuItem::new("Quit", true, None);
@@ -190,10 +163,7 @@ pub fn update_tray_menu(tray_icon: &TrayIcon, settings: &KhmSettings) -> TrayMen
/// Create tooltip text for tray icon
pub fn create_tooltip(settings: &KhmSettings, sync_status: &SyncStatus) -> String {
let mut tooltip = format!(
"KHM - SSH Key Manager\nHost: {}\nFlow: {}",
settings.host, settings.flow
);
let mut tooltip = format!("KHM - SSH Key Manager\nHost: {}\nFlow: {}", settings.host, settings.flow);
if let Some(keys_count) = sync_status.last_sync_keys {
tooltip.push_str(&format!("\nLast sync: {} keys", keys_count));
@@ -216,23 +186,17 @@ pub fn create_tooltip(settings: &KhmSettings, sync_status: &SyncStatus) -> Strin
pub fn start_auto_sync_task(
settings: Arc<Mutex<KhmSettings>>,
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<()>> {
let initial_settings = settings.lock().unwrap().clone();
// Only start auto sync if settings are valid and in_place is enabled
if initial_settings.host.is_empty()
|| initial_settings.flow.is_empty()
|| !initial_settings.in_place
{
if initial_settings.host.is_empty() || initial_settings.flow.is_empty() || !initial_settings.in_place {
info!("Auto sync disabled or settings invalid");
return None;
}
info!(
"Starting auto sync with interval {} minutes",
initial_settings.auto_sync_interval_minutes
);
info!("Starting auto sync with interval {} minutes", initial_settings.auto_sync_interval_minutes);
let handle = std::thread::spawn(move || {
// Initial sync on startup
@@ -243,10 +207,7 @@ pub fn start_auto_sync_task(
rt.block_on(async {
match perform_sync(&current_settings).await {
Ok(keys_count) => {
info!(
"Initial sync completed successfully with {} keys",
keys_count
);
info!("Initial sync completed successfully with {} keys", keys_count);
let mut status = sync_status.lock().unwrap();
status.last_sync_time = Some(std::time::Instant::now());
status.last_sync_keys = Some(keys_count);
@@ -261,9 +222,11 @@ pub fn start_auto_sync_task(
// Start menu update timer
let timer_sender = event_sender.clone();
std::thread::spawn(move || loop {
std::thread::sleep(std::time::Duration::from_secs(1));
let _ = timer_sender.send_event(crate::gui::UserEvent::UpdateMenu);
std::thread::spawn(move || {
loop {
std::thread::sleep(std::time::Duration::from_secs(1));
let _ = timer_sender.send_event(crate::gui::UserEvent::UpdateMenu);
}
});
// Periodic sync
@@ -272,10 +235,7 @@ pub fn start_auto_sync_task(
std::thread::sleep(std::time::Duration::from_secs(interval_minutes as u64 * 60));
let current_settings = settings.lock().unwrap().clone();
if current_settings.host.is_empty()
|| current_settings.flow.is_empty()
|| !current_settings.in_place
{
if current_settings.host.is_empty() || current_settings.flow.is_empty() || !current_settings.in_place {
info!("Auto sync stopped due to invalid settings or disabled in_place");
break;
}

View File

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

View File

@@ -1,113 +0,0 @@
pub mod client;
pub mod db;
pub mod gui;
pub mod server;
#[cfg(feature = "web")]
pub mod web;
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,
}

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 env_logger;
use log::{error, info};
/// CLI version of KHM - Known Hosts Manager for SSH key management and synchronization
/// Supports server and client modes without GUI dependencies
/// 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.
#[derive(Parser, Debug, Clone)]
#[command(
author = env!("CARGO_PKG_AUTHORS"),
version = env!("CARGO_PKG_VERSION"),
about = "SSH Host Key Manager (CLI with Server)",
about = "SSH Host Key Manager",
long_about = None,
after_help = "Examples:\n\
\n\
@@ -22,11 +27,19 @@ use log::{error, info};
\n\
"
)]
pub struct CliArgs {
pub struct Args {
/// Run in server mode (default: false)
#[arg(long, help = "Run in server mode")]
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)
#[arg(
long,
@@ -117,28 +130,6 @@ pub struct CliArgs {
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]
async fn main() -> std::io::Result<()> {
// 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("actix_web", log::LevelFilter::Info) // Server logs
.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();
info!("Starting SSH Key Manager (CLI)");
info!("Starting SSH Key Manager");
let cli_args = CliArgs::parse();
let args: Args = cli_args.into();
let args = Args::parse();
// Validate arguments - either server mode or client mode with required args
if !args.server && (args.host.is_none() || args.flow.is_none()) {
error!("CLI version requires either --server mode or client mode with --host and --flow arguments");
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Invalid arguments for CLI mode",
));
// Settings UI mode - just show settings window and exit
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"
));
}
}
// GUI mode has priority
if args.gui {
info!("Running in GUI mode");
if let Err(e) = gui::run_gui().await {
error!("Failed to run GUI: {}", e);
}
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 {

View File

@@ -300,60 +300,48 @@ pub async fn run_server(args: crate::Args) -> std::io::Result<()> {
info!("Starting HTTP server on {}:{}", args.ip, args.port);
HttpServer::new(move || {
let mut app = App::new()
App::new()
.app_data(web::Data::new(flows.clone()))
.app_data(web::Data::new(db_client.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
.route("/{flow_id}/keys", web::get().to(get_keys))
.route("/{flow_id}/keys", web::post().to(add_keys));
#[cfg(feature = "web")]
{
app = app.configure(configure_web_routes);
}
app
.route("/{flow_id}/keys", web::post().to(add_keys))
// Web interface routes
.route("/", web::get().to(crate::web::serve_web_interface))
.route(
"/static/{filename:.*}",
web::get().to(crate::web::serve_static_file),
)
})
.bind((args.ip.as_str(), args.port))?
.run()
.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),
);
}

View File

@@ -1,14 +1,14 @@
use actix_web::{web, HttpResponse, Result};
use futures::future;
use log::info;
use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
use serde_json::json;
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::time::{timeout, Duration};
use trust_dns_resolver::config::*;
use trust_dns_resolver::TokioAsyncResolver;
use crate::db::ReconnectingDbClient;
use crate::server::Flows;
@@ -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;
@@ -85,10 +88,7 @@ pub async fn scan_dns_resolution(
) -> Result<HttpResponse> {
let flow_id_str = path.into_inner();
info!(
"API request to scan DNS resolution for flow '{}'",
flow_id_str
);
info!("API request to scan DNS resolution for flow '{}'" , flow_id_str);
if !allowed_flows.contains(&flow_id_str) {
return Ok(HttpResponse::Forbidden().json(json!({
@@ -114,10 +114,7 @@ pub async fn scan_dns_resolution(
drop(flows_guard);
info!(
"Scanning DNS resolution for {} unique hosts",
hostnames.len()
);
info!("Scanning DNS resolution for {} unique hosts", hostnames.len());
// Limit concurrent DNS requests to prevent "too many open files" error
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 unresolved_count = results.iter().filter(|r| !r.resolved).count();
info!(
"DNS scan complete: {} unresolved out of {} hosts",
unresolved_count,
results.len()
);
info!("DNS scan complete: {} unresolved out of {} hosts", unresolved_count, results.len());
Ok(HttpResponse::Ok().json(json!({
"results": results,
@@ -154,11 +147,7 @@ pub async fn bulk_deprecate_servers(
) -> Result<HttpResponse> {
let flow_id_str = path.into_inner();
info!(
"API request to bulk deprecate {} servers in flow '{}'",
request.servers.len(),
flow_id_str
);
info!("API request to bulk deprecate {} servers in flow '{}'", request.servers.len(), flow_id_str);
if !allowed_flows.contains(&flow_id_str) {
return Ok(HttpResponse::Forbidden().json(json!({
@@ -172,11 +161,7 @@ pub async fn bulk_deprecate_servers(
.await
{
Ok(count) => {
info!(
"Bulk deprecated {} key(s) for {} servers",
count,
request.servers.len()
);
info!("Bulk deprecated {} key(s) for {} servers", count, request.servers.len());
count
}
Err(e) => {
@@ -218,11 +203,7 @@ pub async fn bulk_restore_servers(
) -> Result<HttpResponse> {
let flow_id_str = path.into_inner();
info!(
"API request to bulk restore {} servers in flow '{}'",
request.servers.len(),
flow_id_str
);
info!("API request to bulk restore {} servers in flow '{}'", request.servers.len(), flow_id_str);
if !allowed_flows.contains(&flow_id_str) {
return Ok(HttpResponse::Forbidden().json(json!({
@@ -236,11 +217,7 @@ pub async fn bulk_restore_servers(
.await
{
Ok(count) => {
info!(
"Bulk restored {} key(s) for {} servers",
count,
request.servers.len()
);
info!("Bulk restored {} key(s) for {} servers", count, request.servers.len());
count
}
Err(e) => {