Compare commits
56 Commits
v1.0.0
..
c6b5554028
| Author | SHA1 | Date | |
|---|---|---|---|
| c6b5554028 | |||
| 8ebdebedc8 | |||
| 4a8b4a2bc4 | |||
| 408681c8e4 | |||
| 93957e3989 | |||
| 94f2142d3d | |||
| 1d2e29d20a | |||
| 611b794fc7 | |||
| a1cd3d5dc0 | |||
| eb663c2634 | |||
| 55b5c7b5a0 | |||
| 6b95385094 | |||
| a597ea5291 | |||
| 8f1f2226f3 | |||
| 2a8940211c | |||
| 25a53d990b | |||
| 2e10308c75 | |||
| c114b2435c | |||
| 0ab4b5211d | |||
| ebd72cf16c | |||
| 2cc9392e2b | |||
| d75621e9b4 | |||
| d359688b75 | |||
| a6850b577c | |||
| 7d41391e13 | |||
| 9d0338595d | |||
| 07899c154b | |||
| 512cf5ce1f | |||
| 9b27388455 | |||
| e5d32bd22e | |||
| 4af555c135 | |||
| f9b2337612 | |||
| 7f197b9e3a | |||
| c7568e0bf4 | |||
| 2442920616 | |||
| 5b456104e8 | |||
| daa20ac72b | |||
| 79f3917a66 | |||
| 53db03814e | |||
| c957a97cdb | |||
| 7b06793002 | |||
| b319f44c3e | |||
| 43858dda87 | |||
| 94ec00c303 | |||
| 3dc482e353 | |||
| 809ac1d2e8 | |||
| 98dfc1c79c | |||
| 5d9e38f8db | |||
| c5cc3bd711 | |||
| e8c451ed56 | |||
| e99a6ac347 | |||
| 9c1bbd4eac | |||
| 933ee48f3f | |||
| b3878de9af | |||
| 513492e6ee | |||
| 1869cff590 |
+1
-1
@@ -39,4 +39,4 @@ Thumbs.db
|
|||||||
*.local.json
|
*.local.json
|
||||||
|
|
||||||
# Build output
|
# Build output
|
||||||
dist/
|
dist/hostkeeper
|
||||||
|
|||||||
+187
@@ -1,5 +1,105 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## [Unreleased] — V2 Planning Complete (2026-06-29)
|
||||||
|
|
||||||
|
### Added (V2 Planning Documents)
|
||||||
|
- `docs/v2/PROGRESS.md` — Status tracker for V2 development
|
||||||
|
- `docs/v2/ARCHITECTURE.md` — System architecture (GoFiber + React + Electron)
|
||||||
|
- `docs/v2/API.md` — REST API + WebSocket specification
|
||||||
|
- `docs/v2/DATA_MODELS.md` — Extended data models (Groups, PortForward, Workspace)
|
||||||
|
- `docs/v2/UI_COMPONENTS.md` — React component tree + state management
|
||||||
|
- `docs/v2/UI_TERMIUS_REFERENCE.md` — Termius visual reference
|
||||||
|
- `docs/v2/SPRINT_PLAN.md` — Sprint-by-sprint task breakdown
|
||||||
|
- `docs/v2/BUILD_SYSTEM.md` — Cross-platform build pipeline
|
||||||
|
- `docs/v2/PERFORMANCE.md` — Performance & stability guide
|
||||||
|
|
||||||
|
### Architecture Decision
|
||||||
|
- Backend: GoFiber v2 (fasthttp-based) replacing chi/net/http
|
||||||
|
- WebSocket: gofiber/contrib/websocket (fasthttp/websocket) replacing gorilla/websocket
|
||||||
|
- Frontend: React 19 + TypeScript + xterm.js + Zustand
|
||||||
|
- Desktop: Electron (electron-builder)
|
||||||
|
- Mobile: gomobile + WebView
|
||||||
|
|
||||||
|
### V1 Status (FROZEN)
|
||||||
|
- All V1 code (pkg/, internal/, cmd/, test/) is complete and frozen
|
||||||
|
- V1 CLI/TUI remains functional alongside V2 GUI
|
||||||
|
- 105 tests passing, zero race conditions
|
||||||
|
|
||||||
|
## [Unreleased] — 2025-01-31
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- TUI host list footer now includes `Ctrl+E:edit`
|
||||||
|
- New hosts/keys/snippets created via TUI form now get UUID + timestamps (`CreatedAt`, `UpdatedAt`)
|
||||||
|
- Storage layer auto-generates UUID + timestamps on save if empty (defense-in-depth)
|
||||||
|
- **host_form_tab.go**: Space/Left/Right keys now passthrough to text input when not on auth type field (fixes typing spaces and cursor navigation)
|
||||||
|
- **tui.go**: Key and snippet list tabs now properly refresh after save/delete (mirrors host flow)
|
||||||
|
- **tabs.go**: WindowSizeMsg now forwarded to ALL tabs, not just the active one (fixes stale dimensions after resize)
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- All tab footers are now context-specific (no global status bar)
|
||||||
|
- SFTP browser uses full-width panes (`t.width/2`)
|
||||||
|
- **sftp_browser_tab.go footer**: Added `Enter/→:open`, `←/Backspace:up`
|
||||||
|
- **form tabs footer**: Added `Shift+Tab:prev`, `↑↓:nav`
|
||||||
|
|
||||||
|
### Responsive Layout (Done)
|
||||||
|
- **NEW `responsive.go`**: Shared helpers (`wrapFooter`, `adaptiveSidePad`, `clampWidth`, `truncateStr`)
|
||||||
|
- Footer auto-wraps to multi-line when terminal is narrow (full labels preserved)
|
||||||
|
- Box width clamped to terminal width — no more overflow
|
||||||
|
- Host/key/snippet rows truncated with `…` when names are too long; compact row format on narrow screens
|
||||||
|
- SFTP panes stack vertically when terminal < 50 cols
|
||||||
|
- Tab bar truncates tab names on overflow
|
||||||
|
- Form contentW minimum lowered from 50 to 30 for mobile (Termux)
|
||||||
|
- Fixed: key_list_tab & snippet_list_tab were dropping last data row (off-by-one in `rows[:len(rows)-1]`)
|
||||||
|
- Fixed: SFTP pane width — lipgloss `Width(n)` renders `n+2` chars (border extra). halfW now `t.width/2-2` to compensate. File names truncate to `…` within inner text area. Filter line also truncated.
|
||||||
|
- Verified: zero overflow at 80, 60, 50 (side-by-side), 40, 30 cols (stacked)
|
||||||
|
|
||||||
|
### SFTP Stacked Mode Fix (Done)
|
||||||
|
- Stacked mode (<50 cols) now renders only the active pane (Local or Remote)
|
||||||
|
- Added pane indicator bar: `[Local] Remote` with active pane highlighted
|
||||||
|
- Side-by-side mode (≥50 cols) unchanged — both panes remain visible
|
||||||
|
- Tab key now visually switches between panes on narrow terminals
|
||||||
|
- Default active pane: Local (was Remote)
|
||||||
|
- Border height fix: pane uses fixed `Height(maxH)` — border no longer shrinks/grows when scrolling
|
||||||
|
- `renderPane` now takes `maxH` parameter to control content area height
|
||||||
|
- Stacked: `maxH = t.height - 6`; Side-by-side: `maxH = t.height - 5`
|
||||||
|
- Breakpoints: compact (<60), medium (60–100), wide (≥100)
|
||||||
|
|
||||||
|
### SFTP Performance Fix
|
||||||
|
- Added directory listing cache (`dirCache map[string][]os.FileInfo`) to each pane
|
||||||
|
- Cache hit: instant navigation (no disk/network call)
|
||||||
|
- Cache miss: read from disk/SFTP, store in cache
|
||||||
|
- `R` key now clears cache for current directory and forces re-read
|
||||||
|
- Cache is per-path: navigating to a previously visited folder is instant
|
||||||
|
|
||||||
|
### SFTP File Transfer Progress Bar
|
||||||
|
- Added progress bar during upload/download: `[████████░░░░] 67% 12.3MB/18.5MB`
|
||||||
|
- `progressWriter` wraps `io.Writer` and reports bytes transferred
|
||||||
|
- Footer shows live progress during transfer
|
||||||
|
- Auto-refresh destination pane after transfer completes
|
||||||
|
- Success message shown for 1 second before clearing
|
||||||
|
|
||||||
|
### SFTP Auto-Refresh Fix
|
||||||
|
- Added `program *tea.Program` field to SFTPBrowserTab and Model
|
||||||
|
- `SetProgram()` method allows goroutines to send messages to Bubble Tea
|
||||||
|
- After transfer: `t.program.Send(sftpRefreshMsg{})` triggers re-render
|
||||||
|
- Model stores program reference, passes it to SFTP tab on creation
|
||||||
|
|
||||||
|
### SFTP Bug Fixes
|
||||||
|
- Auto-refresh: clear dirCache before refresh after transfer/delete/mkdir
|
||||||
|
- Cache was stale after file operations — old entries returned instead of fresh
|
||||||
|
- Filter mode: allow command keys (c, d, n, r) and navigation (↑↓, Tab) to pass through
|
||||||
|
- Filter mode no longer blocks transfer, delete, mkdir, or pane switch
|
||||||
|
- Delete: clear cache + trigger re-render after file removal
|
||||||
|
- Mkdir: clear cache + trigger re-render after directory creation
|
||||||
|
|
||||||
|
### SFTP Rename Feature
|
||||||
|
- Added `M` key to rename files and directories
|
||||||
|
- Rename mode: shows input with current name, type new name, Enter to confirm
|
||||||
|
- Works on both Local and Remote panes
|
||||||
|
- Clears cache and refreshes after rename
|
||||||
|
- Footer updated: `M:rename` added
|
||||||
|
- Filter mode allows `M` to pass through
|
||||||
|
|
||||||
## v1.0.0 (2025-01-30)
|
## v1.0.0 (2025-01-30)
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
@@ -41,3 +141,90 @@
|
|||||||
- Initial MVP release, all core features functional
|
- Initial MVP release, all core features functional
|
||||||
- Encrypted storage planned for future release
|
- Encrypted storage planned for future release
|
||||||
- Interactive shell in Go SSH direct mode not yet available
|
- Interactive shell in Go SSH direct mode not yet available
|
||||||
|
|
||||||
|
## Phase 2 — Security Enhancement
|
||||||
|
|
||||||
|
### AES-256-GCM Encryption
|
||||||
|
- New `pkg/crypto/crypto.go`: AES-256-GCM encrypt/decrypt with PBKDF2 key derivation
|
||||||
|
- 100,000 iterations, 16-byte salt, SHA-256 key derivation
|
||||||
|
- `Encrypt(plaintext, password)` → base64(salt + nonce + ciphertext)
|
||||||
|
- `Decrypt(encoded, password)` → plaintext
|
||||||
|
- `IsEncrypted(data)` checks if data looks like encrypted content
|
||||||
|
|
||||||
|
### Storage Layer Encryption
|
||||||
|
- `JSONStorage` now has `password` field for master encryption key
|
||||||
|
- `SetPassword()`, `GetPassword()`, `IsEncrypted()` methods
|
||||||
|
- `readJSON()` auto-decrypts if password is set and data is encrypted
|
||||||
|
- `replaceHosts/KeyPairs/Snippets()` auto-encrypt before writing
|
||||||
|
- All existing CRUD operations transparently encrypt/decrypt
|
||||||
|
|
||||||
|
### Known Hosts Verification
|
||||||
|
- New `pkg/knownhosts/knownhosts.go`: TOFU (Trust-On-First-Use) model
|
||||||
|
- `KnownHosts` manages `known_hosts` file (JSON format)
|
||||||
|
- `Verify()` checks if host key matches stored key
|
||||||
|
- `HostKeyCallback()` returns `cryptossh.HostKeyCallback` for SSH config
|
||||||
|
- Warns on key mismatch (potential MITM attack)
|
||||||
|
|
||||||
|
### SSH Client Security
|
||||||
|
- `Client` now supports `hostKeyCallback` and `passphraseCallback`
|
||||||
|
- `SetHostKeyCallback()` — replaces `InsecureIgnoreHostKey()`
|
||||||
|
- `SetPassphraseCallback()` — prompts for passphrase on encrypted keys
|
||||||
|
- `getKeySigner()` tries passphrase callback if key is encrypted
|
||||||
|
|
||||||
|
### Models Updated
|
||||||
|
- `AppConfig`: added `EncryptionEnabled`, `PasswordHash`, `KnownHostsFile`
|
||||||
|
|
||||||
|
## Phase 2 UX Polish (Done)
|
||||||
|
|
||||||
|
### Theme System
|
||||||
|
- **NEW `themes.go`**: `Theme` struct with full color palette
|
||||||
|
- 3 predefined themes: `dark` (Gruvbox), `light`, `dracula`
|
||||||
|
- `SetTheme(name)` — updates all component styles at runtime
|
||||||
|
- `GetActiveTheme()` — returns current theme
|
||||||
|
- All palette vars now derived from active theme
|
||||||
|
|
||||||
|
### Config Profiles
|
||||||
|
- **`models.go`**: `Profile` struct — name, theme, default group, default auth, editor, notes
|
||||||
|
- `AppConfig.Profiles []Profile` — list of named profiles
|
||||||
|
- `AppConfig.ActiveProfile string` — currently active profile
|
||||||
|
- `GetProfile(name)`, `GetActiveProfile()`, `AddProfile()`, `RemoveProfile()`
|
||||||
|
- Default config includes "default" profile
|
||||||
|
|
||||||
|
### Enhanced Error Display
|
||||||
|
- **NEW `error_banner.go`**: `ErrorBanner` with severity levels (Error/Warning/Info)
|
||||||
|
- Structured format: title + detail + numbered hints
|
||||||
|
- Auto-dismiss after 5 seconds (configurable)
|
||||||
|
- Color-coded: red (error), yellow (warning), blue (info)
|
||||||
|
- `Show()`, `Hide()`, `Update()`, `View(width)` methods
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
- **`test/tui/theme_test.go`**: GetTheme, SetTheme, GetActiveTheme, registry
|
||||||
|
- **`test/tui/error_banner_test.go`**: Show/Hide, AutoDismiss, Severity, View
|
||||||
|
- **`test/models_test.go`**: DefaultConfig, Profile CRUD
|
||||||
|
|
||||||
|
## Phase 3 Testing (Done)
|
||||||
|
|
||||||
|
### Security-Critical Tests (0% → 100%)
|
||||||
|
- **`test/crypto/crypto_test.go`** (19 tests): DeriveKey, Encrypt/Decrypt round-trip, empty/large/unicode/newlines data, wrong/empty password, IsEncrypted, HashPassword, randomness
|
||||||
|
- **`test/knownhosts/knownhosts_test.go`** (14 tests): New, Add/Get/Remove CRUD, Verify unknown/match/mismatch (MITM), HostKeyCallback autoAdd, persistence, corrupted file
|
||||||
|
|
||||||
|
### Core Tests (40% → 90%)
|
||||||
|
- **`test/storage/json_storage_test.go`** (20 tests): KeyPair CRUD (6), Snippet CRUD (6), encryption (SetPassword, IsDataEncrypted, wrong password), MergeStrategy (merge/replace), edge cases
|
||||||
|
|
||||||
|
### Config Tests (22% → 80%)
|
||||||
|
- **`test/config/config_test.go`** (9 tests): New first run, Save, UpdateAppConfig, path getters
|
||||||
|
|
||||||
|
### UI Tests (40% → 70%)
|
||||||
|
- **`test/tui/responsive_test.go`** (10 tests): WrapFooter, ClampWidth, TruncateStr
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
- **knownhosts deadlock**: `Add()`/`Remove()` now call `saveInternal()` instead of `Save()` to avoid re-locking
|
||||||
|
- **responsive.go**: Exported `WrapFooter`, `ClampWidth`, `TruncateStr` for testing
|
||||||
|
|
||||||
|
### Coverage Summary
|
||||||
|
- `pkg/crypto`: 0% → **100%** (19 tests)
|
||||||
|
- `pkg/knownhosts`: 0% → **100%** (14 tests)
|
||||||
|
- `pkg/storage`: 40% → **90%** (20 tests)
|
||||||
|
- `pkg/config`: 22% → **80%** (9 tests)
|
||||||
|
- `pkg/tui`: 40% → **70%** (10 new tests)
|
||||||
|
- Total: **105 tests**, all passing, zero race conditions
|
||||||
|
|||||||
+42
-7
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
> **Purpose**: Enable seamless continuation of development by any agent/LLM across sessions
|
> **Purpose**: Enable seamless continuation of development by any agent/LLM across sessions
|
||||||
>
|
>
|
||||||
> **Last Updated**: 2025-01-30 (MVP Release)
|
> **Last Updated**: 2025-01-31 (Phase 3 Testing Complete)
|
||||||
> **Current Status**: ✅ MVP Complete — All Tasks 1-14 Done
|
> **Current Status**: ✅ MVP Complete — Phase 1 Done, Phase 2 Done, Phase 3 Testing Done
|
||||||
> **Phase**: MVP Release (Phase 1)
|
> **Phase**: Phase 3 (Documentation)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -38,6 +38,41 @@
|
|||||||
|
|
||||||
**🔥 All 14 MVP tasks complete! Project is ready for deployment.**
|
**🔥 All 14 MVP tasks complete! Project is ready for deployment.**
|
||||||
|
|
||||||
|
### Post-MVP Fixes
|
||||||
|
✅ TUI layout overhaul: centered border boxes, per-row centering, context-specific footers
|
||||||
|
✅ Status bar removed; keybindings moved inside each tab's border box footer
|
||||||
|
✅ SFTP browser: full-width panes, SFTP-specific keybindings
|
||||||
|
✅ Host list footer: added `Ctrl+E:edit`
|
||||||
|
✅ UUID + timestamps auto-generated in TUI form `submit()` methods
|
||||||
|
✅ UUID + timestamps auto-generated in storage layer (`SaveHost`, `SaveKeyPair`, `SaveSnippet`)
|
||||||
|
✅ Git history cleaned of committed binary; `.gitignore` fixed
|
||||||
|
✅ **host_form_tab.go**: Space/Left/Right passthrough to text input (fixes typing spaces + cursor nav)
|
||||||
|
✅ **tui.go**: Key + snippet list refresh on save/delete
|
||||||
|
✅ **tabs.go**: WindowSizeMsg forwarded to all tabs on resize
|
||||||
|
✅ **sftp_browser_tab.go footer**: Added `Enter/→:open`, `←/Backspace:up`
|
||||||
|
✅ **Form tab footers**: Added `Shift+Tab:prev`, `↑↓:nav`
|
||||||
|
|
||||||
|
### Done: Responsive Layout Overhaul
|
||||||
|
✅ **NEW `responsive.go`**: Shared helpers for adaptive layout (`wrapFooter`, `adaptiveSidePad`, `clampWidth`, `truncateStr`)
|
||||||
|
✅ Footer auto-wraps to multi-line (full labels preserved) — no more overflow on narrow terminals
|
||||||
|
✅ Box width clamped to terminal width across all tabs
|
||||||
|
✅ Host/key/snippet rows truncated with `…` for long names; compact format on narrow screens
|
||||||
|
✅ SFTP panes stack vertically when terminal < 50 cols
|
||||||
|
✅ Tab bar truncates names on overflow
|
||||||
|
✅ Form contentW minimum lowered from 50 to 30 for mobile (Termux)
|
||||||
|
✅ Fixed bug: key_list_tab.go & snippet_list_tab.go dropped last row (`rows[:len(rows)-1]` excluded real data)
|
||||||
|
✅ Breakpoints: compact (<60 cols / mobile), medium (60–100 / tablet), wide (≥100 / desktop)
|
||||||
|
|
||||||
|
### Done: SFTP Stacked Mode Fix
|
||||||
|
✅ **File**: `pkg/tui/sftp_browser_tab.go`
|
||||||
|
✅ Stacked mode (<50 cols): render cuma ACTIVE pane (bukan 2 pane)
|
||||||
|
✅ Pane indicator bar: `[Local] Remote` — active disorot hijau (StatusBarStyle)
|
||||||
|
✅ Side-by-side mode (>=50 cols): tidak diubah, tetap 2 pane
|
||||||
|
✅ Default active pane: Local (bukan Remote)
|
||||||
|
✅ Border height fix: `renderPane` sekarang terima `maxH` parameter, `paneStyle.Height(maxH)` → border selalu konsisten tingginya, tidak naik-turun sesuai scroll
|
||||||
|
✅ Stacked mode: `maxH = t.height - 6` (title + indicator + border + footer)
|
||||||
|
✅ Side-by-side mode: `maxH = t.height - 5` (title + border + footer)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📊 Current Project Status
|
## 📊 Current Project Status
|
||||||
@@ -230,14 +265,14 @@
|
|||||||
- [x] Build system and integration tests
|
- [x] Build system and integration tests
|
||||||
|
|
||||||
### Next Sprint
|
### Next Sprint
|
||||||
- [ ] TUI implementation (Bubble Tea)
|
- [ ] SFTP Performance: caching directory listings, batch directory reads
|
||||||
- [ ] Export/import functionality
|
- [ ] SFTP File Transfer: download (remote→local), upload (local→remote)
|
||||||
- [ ] Key management commands
|
- [ ] Phase 2 Priority 2: Security Enhancement (AES-256-GCM, key passphrase, known_hosts)
|
||||||
|
|
||||||
### Final Sprint
|
### Final Sprint
|
||||||
|
- [ ] Phase 2 Priority 3: UX Polish (configuration profiles, theme customization, enhanced error messages)
|
||||||
- [ ] Testing and integration
|
- [ ] Testing and integration
|
||||||
- [ ] Documentation completion
|
- [ ] Documentation completion
|
||||||
- [ ] Build system and release preparation
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+20
-34
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
@@ -12,7 +13,6 @@ import (
|
|||||||
|
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -154,7 +154,7 @@ func runAddHost(cmd *cobra.Command, args []string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Initialize storage
|
// Initialize storage
|
||||||
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
store, err := newStorage(cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||||
}
|
}
|
||||||
@@ -174,52 +174,47 @@ func runAddHost(cmd *cobra.Command, args []string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func addHostInteractive(cfg *config.Config) error {
|
func addHostInteractive(cfg *config.Config) error {
|
||||||
reader := strings.NewReader("")
|
input := bufio.NewReader(os.Stdin)
|
||||||
|
|
||||||
fmt.Println("╔══════════════════════════════════════╗")
|
fmt.Println("╔══════════════════════════════════════╗")
|
||||||
fmt.Println("║ Add New SSH Host ║")
|
fmt.Println("║ Add New SSH Host ║")
|
||||||
fmt.Println("╚══════════════════════════════════════╝")
|
fmt.Println("╚══════════════════════════════════════╝")
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
|
|
||||||
|
readLine := func(prompt string) string {
|
||||||
|
fmt.Print(prompt)
|
||||||
|
line, _ := input.ReadString('\n')
|
||||||
|
return strings.TrimRight(line, "\n\r")
|
||||||
|
}
|
||||||
|
|
||||||
// Get host name
|
// Get host name
|
||||||
fmt.Print("Host Name (e.g., myserver): ")
|
name := readLine("Host Name (e.g., myserver): ")
|
||||||
var name string
|
|
||||||
fmt.Fscanln(reader)
|
|
||||||
fmt.Scanln(&name)
|
|
||||||
if name == "" {
|
if name == "" {
|
||||||
return fmt.Errorf("host name is required")
|
return fmt.Errorf("host name is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get hostname
|
// Get hostname
|
||||||
fmt.Print("Hostname or IP (e.g., 192.168.1.10): ")
|
hostname := readLine("Hostname or IP (e.g., 192.168.1.10): ")
|
||||||
var hostname string
|
|
||||||
fmt.Scanln(&hostname)
|
|
||||||
if hostname == "" {
|
if hostname == "" {
|
||||||
return fmt.Errorf("hostname is required")
|
return fmt.Errorf("hostname is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get port
|
// Get port
|
||||||
defaultPort := cfg.GetAppConfig().DefaultPort
|
defaultPort := cfg.GetAppConfig().DefaultPort
|
||||||
fmt.Printf("Port [%d]: ", defaultPort)
|
portInput := readLine(fmt.Sprintf("Port [%d]: ", defaultPort))
|
||||||
var portInput string
|
|
||||||
fmt.Scanln(&portInput)
|
|
||||||
port := defaultPort
|
port := defaultPort
|
||||||
if portInput != "" {
|
if portInput != "" {
|
||||||
fmt.Sscanf(portInput, "%d", &port)
|
fmt.Sscanf(portInput, "%d", &port)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get username
|
// Get username
|
||||||
fmt.Print("Username: ")
|
username := readLine("Username: ")
|
||||||
var username string
|
|
||||||
fmt.Scanln(&username)
|
|
||||||
if username == "" {
|
if username == "" {
|
||||||
return fmt.Errorf("username is required")
|
return fmt.Errorf("username is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get auth type
|
// Get auth type
|
||||||
fmt.Print("Auth Type (password/key/both) [password]: ")
|
authType := readLine("Auth Type (password/key/both) [password]: ")
|
||||||
var authType string
|
|
||||||
fmt.Scanln(&authType)
|
|
||||||
if authType == "" {
|
if authType == "" {
|
||||||
authType = "password"
|
authType = "password"
|
||||||
}
|
}
|
||||||
@@ -227,16 +222,13 @@ func addHostInteractive(cfg *config.Config) error {
|
|||||||
// Get password
|
// Get password
|
||||||
var password string
|
var password string
|
||||||
if authType == "password" || authType == "both" {
|
if authType == "password" || authType == "both" {
|
||||||
fmt.Print("Password: ")
|
password = readLine("Password: ")
|
||||||
fmt.Scanln(&password)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get key path
|
// Get key path
|
||||||
var keyContent string
|
var keyContent string
|
||||||
if authType == "key" || authType == "both" {
|
if authType == "key" || authType == "both" {
|
||||||
fmt.Print("Path to private key (~/.ssh/id_rsa): ")
|
keyPath := readLine("Path to private key (~/.ssh/id_rsa): ")
|
||||||
var keyPath string
|
|
||||||
fmt.Scanln(&keyPath)
|
|
||||||
if keyPath != "" {
|
if keyPath != "" {
|
||||||
data, err := os.ReadFile(keyPath)
|
data, err := os.ReadFile(keyPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -247,14 +239,10 @@ func addHostInteractive(cfg *config.Config) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get group
|
// Get group
|
||||||
fmt.Print("Group (optional): ")
|
group := readLine("Group (optional): ")
|
||||||
var group string
|
|
||||||
fmt.Scanln(&group)
|
|
||||||
|
|
||||||
// Get tags
|
// Get tags
|
||||||
fmt.Print("Tags (comma-separated, optional): ")
|
tagsInput := readLine("Tags (comma-separated, optional): ")
|
||||||
var tagsInput string
|
|
||||||
fmt.Scanln(&tagsInput)
|
|
||||||
var tags []string
|
var tags []string
|
||||||
if tagsInput != "" {
|
if tagsInput != "" {
|
||||||
tags = strings.Split(tagsInput, ",")
|
tags = strings.Split(tagsInput, ",")
|
||||||
@@ -264,9 +252,7 @@ func addHostInteractive(cfg *config.Config) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get notes
|
// Get notes
|
||||||
fmt.Print("Notes (optional): ")
|
notes := readLine("Notes (optional): ")
|
||||||
var notes string
|
|
||||||
fmt.Scanln(¬es)
|
|
||||||
|
|
||||||
// Create host
|
// Create host
|
||||||
host := &models.Host{
|
host := &models.Host{
|
||||||
@@ -291,7 +277,7 @@ func addHostInteractive(cfg *config.Config) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Initialize storage
|
// Initialize storage
|
||||||
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
store, err := newStorage(cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
+33
-12
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
@@ -18,14 +19,14 @@ import (
|
|||||||
|
|
||||||
var (
|
var (
|
||||||
connectTimeout int
|
connectTimeout int
|
||||||
connectDirect bool
|
connectNative bool
|
||||||
)
|
)
|
||||||
|
|
||||||
// connectCmd represents the connect command
|
// connectCmd represents the connect command
|
||||||
var connectCmd = &cobra.Command{
|
var connectCmd = &cobra.Command{
|
||||||
Use: "connect <host-name-or-id>",
|
Use: "connect <host-name-or-id>",
|
||||||
Short: "Connect to a saved SSH host",
|
Short: "Connect to a saved SSH host",
|
||||||
Long: `Connect to a saved SSH host using native SSH client with stored credentials.
|
Long: `Connect to a saved SSH host using stored credentials.
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
# Connect to a host by name
|
# Connect to a host by name
|
||||||
@@ -34,15 +35,15 @@ Examples:
|
|||||||
# Connect with a specific timeout
|
# Connect with a specific timeout
|
||||||
hostkeeper connect myserver --timeout 60
|
hostkeeper connect myserver --timeout 60
|
||||||
|
|
||||||
# Use Go SSH client (direct mode) instead of system SSH
|
# Use native system SSH instead of Go SSH client
|
||||||
hostkeeper connect myserver --direct`,
|
hostkeeper connect myserver --native`,
|
||||||
Args: cobra.ExactArgs(1),
|
Args: cobra.ExactArgs(1),
|
||||||
RunE: runConnect,
|
RunE: runConnect,
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
connectCmd.Flags().IntVar(&connectTimeout, "timeout", 30, "Connection timeout in seconds")
|
connectCmd.Flags().IntVar(&connectTimeout, "timeout", 30, "Connection timeout in seconds")
|
||||||
connectCmd.Flags().BoolVar(&connectDirect, "direct", false, "Use direct SSH instead of native client")
|
connectCmd.Flags().BoolVar(&connectNative, "native", false, "Use native system SSH instead of Go SSH client")
|
||||||
|
|
||||||
rootCmd.AddCommand(connectCmd)
|
rootCmd.AddCommand(connectCmd)
|
||||||
}
|
}
|
||||||
@@ -76,11 +77,11 @@ func runConnect(cmd *cobra.Command, args []string) error {
|
|||||||
fmt.Printf("Connecting to %s (%s@%s:%d)...\n", host.Name, host.Username, host.Hostname, host.Port)
|
fmt.Printf("Connecting to %s (%s@%s:%d)...\n", host.Name, host.Username, host.Hostname, host.Port)
|
||||||
|
|
||||||
// Choose connection method
|
// Choose connection method
|
||||||
if connectDirect {
|
if connectNative {
|
||||||
return connectDirectSSH(host)
|
return connectWithNativeSSH(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
return connectWithNativeSSH(host)
|
return connectDirectSSH(host)
|
||||||
}
|
}
|
||||||
|
|
||||||
// findHost finds a host by ID first, then by name
|
// findHost finds a host by ID first, then by name
|
||||||
@@ -103,8 +104,26 @@ func findHost(ctx context.Context, store storage.Storage, identifier string) (*m
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Try to find by hostname
|
||||||
|
for _, h := range hosts {
|
||||||
|
if h.Hostname == identifier {
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to find by ID prefix (short ID match)
|
||||||
|
for _, h := range hosts {
|
||||||
|
if len(h.ID) >= 8 && h.ID[:8] == identifier {
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Host not found, provide helpful error
|
// Host not found, provide helpful error
|
||||||
return nil, fmt.Errorf("host '%s' not found. Use 'hostkeeper list' to see available hosts", identifier)
|
msg := fmt.Sprintf("host '%s' not found. Use 'hostkeeper list' to see available hosts", identifier)
|
||||||
|
if strings.Contains(identifier, " ") {
|
||||||
|
msg += fmt.Sprintf("\nHint: if the host name contains spaces, quote it: connect \"%s\"", identifier)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("%s", msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
// connectWithNativeSSH uses the system SSH client
|
// connectWithNativeSSH uses the system SSH client
|
||||||
@@ -137,9 +156,11 @@ func connectDirectSSH(host *models.Host) error {
|
|||||||
}
|
}
|
||||||
defer client.Close()
|
defer client.Close()
|
||||||
|
|
||||||
fmt.Printf("Connected to %s\n", host.Name)
|
fmt.Printf("Connected to %s (%s@%s:%d)\n", host.Name, host.Username, host.Hostname, host.Port)
|
||||||
fmt.Println("Interactive shell not yet implemented in direct mode")
|
|
||||||
fmt.Println("Use --direct=false (default) for native SSH experience")
|
if err := client.Shell(); err != nil {
|
||||||
|
return fmt.Errorf("shell session failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ func TestConnectCommandExists(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestConnectCommandFlags(t *testing.T) {
|
func TestConnectCommandFlags(t *testing.T) {
|
||||||
expectedFlags := []string{"timeout", "direct"}
|
expectedFlags := []string{"timeout", "native"}
|
||||||
for _, flagName := range expectedFlags {
|
for _, flagName := range expectedFlags {
|
||||||
if connectCmd.Flags().Lookup(flagName) == nil {
|
if connectCmd.Flags().Lookup(flagName) == nil {
|
||||||
t.Errorf("flag '%s' should be defined", flagName)
|
t.Errorf("flag '%s' should be defined", flagName)
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var deleteForce bool
|
var deleteForce bool
|
||||||
@@ -49,7 +48,7 @@ func runDeleteHost(cmd *cobra.Command, args []string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
store, err := newStorage(cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -75,7 +75,7 @@ func runEditHost(cmd *cobra.Command, args []string) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
store, err := newStorage(cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
+14
-7
@@ -12,7 +12,6 @@ import (
|
|||||||
|
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -69,7 +68,7 @@ func runListHosts(cmd *cobra.Command, args []string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Initialize storage
|
// Initialize storage
|
||||||
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
store, err := newStorage(cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||||
}
|
}
|
||||||
@@ -150,15 +149,23 @@ func sortHosts(hosts []*models.Host, sortBy string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func shortID(id string) string {
|
||||||
|
if len(id) >= 8 {
|
||||||
|
return id[:8]
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
func outputTable(hosts []*models.Host) error {
|
func outputTable(hosts []*models.Host) error {
|
||||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
|
||||||
|
|
||||||
fmt.Fprintln(w, "NAME\tHOSTNAME\tPORT\tUSER\tGROUP\tAUTH\tTAGS")
|
fmt.Fprintln(w, "ID\tNAME\tHOSTNAME\tPORT\tUSER\tGROUP\tAUTH\tTAGS")
|
||||||
fmt.Fprintln(w, "────\t────────\t────\t────\t─────\t────\t────")
|
fmt.Fprintln(w, "--\t────\t────────\t────\t────\t─────\t────\t────")
|
||||||
|
|
||||||
for _, h := range hosts {
|
for _, h := range hosts {
|
||||||
tags := strings.Join(h.Tags, ", ")
|
tags := strings.Join(h.Tags, ", ")
|
||||||
fmt.Fprintf(w, "%s\t%s\t%d\t%s\t%s\t%s\t%s\n",
|
fmt.Fprintf(w, "%s\t%s\t%s\t%d\t%s\t%s\t%s\t%s\n",
|
||||||
|
shortID(h.ID),
|
||||||
h.Name,
|
h.Name,
|
||||||
h.Hostname,
|
h.Hostname,
|
||||||
h.Port,
|
h.Port,
|
||||||
@@ -178,8 +185,8 @@ func outputJSON(hosts []*models.Host) error {
|
|||||||
if i > 0 {
|
if i > 0 {
|
||||||
fmt.Print(",")
|
fmt.Print(",")
|
||||||
}
|
}
|
||||||
fmt.Printf(`{"id":"%s","name":"%s","hostname":"%s","port":%d,"username":"%s","group":"%s","auth_type":"%s"}`,
|
fmt.Printf(`{"id":"%s","short_id":"%s","name":"%s","hostname":"%s","port":%d,"username":"%s","group":"%s","auth_type":"%s"}`,
|
||||||
h.ID, h.Name, h.Hostname, h.Port, h.Username, h.Group, h.Auth.Type)
|
h.ID, shortID(h.ID), h.Name, h.Hostname, h.Port, h.Username, h.Group, h.Auth.Type)
|
||||||
}
|
}
|
||||||
fmt.Println("]")
|
fmt.Println("]")
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -11,6 +11,13 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
// SSH_ASKPASS support: hostkeeper askpass
|
||||||
|
// Called by the SSH_ASKPASS script we create for key passphrases.
|
||||||
|
if len(os.Args) == 2 && os.Args[1] == "askpass" {
|
||||||
|
fmt.Print(os.Getenv("HK_PASSPHRASE"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if err := Execute(); err != nil {
|
if err := Execute(); err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
|
|||||||
+19
-4
@@ -7,13 +7,15 @@ import (
|
|||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
|
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
cfgFile string
|
cfgFile string
|
||||||
appCfg *config.Config
|
appCfg *config.Config
|
||||||
verbose int
|
verbose int
|
||||||
debug bool
|
debug bool
|
||||||
|
passwordFlag string
|
||||||
)
|
)
|
||||||
|
|
||||||
var rootCmd = &cobra.Command{
|
var rootCmd = &cobra.Command{
|
||||||
@@ -47,6 +49,7 @@ func init() {
|
|||||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is platform-specific app dir)")
|
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is platform-specific app dir)")
|
||||||
rootCmd.PersistentFlags().CountVarP(&verbose, "verbose", "v", "verbose output (-v for info, -vv for debug)")
|
rootCmd.PersistentFlags().CountVarP(&verbose, "verbose", "v", "verbose output (-v for info, -vv for debug)")
|
||||||
rootCmd.PersistentFlags().BoolVar(&debug, "debug", false, "enable debug mode")
|
rootCmd.PersistentFlags().BoolVar(&debug, "debug", false, "enable debug mode")
|
||||||
|
rootCmd.PersistentFlags().StringVar(&passwordFlag, "password", "", "master password for encrypted storage")
|
||||||
|
|
||||||
rootCmd.AddCommand(versionCmd)
|
rootCmd.AddCommand(versionCmd)
|
||||||
}
|
}
|
||||||
@@ -85,3 +88,15 @@ var versionCmd = &cobra.Command{
|
|||||||
func Execute() error {
|
func Execute() error {
|
||||||
return rootCmd.Execute()
|
return rootCmd.Execute()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// newStorage creates a new JSONStorage with the password flag applied
|
||||||
|
func newStorage(cfg *config.Config) (*storage.JSONStorage, error) {
|
||||||
|
store, err := storage.NewJSONStorage(cfg.GetDataDir())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if passwordFlag != "" {
|
||||||
|
store.SetPassword(passwordFlag)
|
||||||
|
}
|
||||||
|
return store, nil
|
||||||
|
}
|
||||||
+28
-4
@@ -8,10 +8,13 @@ import (
|
|||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/knownhosts"
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/pkg/tui"
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/tui"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var encryptFlag bool
|
||||||
|
|
||||||
// tuiCmd represents the tui command
|
// tuiCmd represents the tui command
|
||||||
var tuiCmd = &cobra.Command{
|
var tuiCmd = &cobra.Command{
|
||||||
Use: "tui",
|
Use: "tui",
|
||||||
@@ -22,6 +25,7 @@ var tuiCmd = &cobra.Command{
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rootCmd.AddCommand(tuiCmd)
|
rootCmd.AddCommand(tuiCmd)
|
||||||
|
tuiCmd.Flags().BoolVar(&encryptFlag, "encrypt", false, "Enable AES-256-GCM encryption for sensitive data")
|
||||||
}
|
}
|
||||||
|
|
||||||
func runTUI(cmd *cobra.Command, args []string) error {
|
func runTUI(cmd *cobra.Command, args []string) error {
|
||||||
@@ -39,16 +43,36 @@ func runTUI(cmd *cobra.Command, args []string) error {
|
|||||||
return fmt.Errorf("failed to initialize storage: %w", err)
|
return fmt.Errorf("failed to initialize storage: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx := context.Background()
|
// Initialize known_hosts
|
||||||
hosts, err := store.ListHosts(ctx)
|
kh, err := knownhosts.New(cfg.GetDataDir())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to load hosts: %w", err)
|
fmt.Printf("Warning: failed to load known_hosts: %v\n", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Auto-detect encrypted data files
|
||||||
|
needPassword := encryptFlag || store.IsDataEncrypted()
|
||||||
|
|
||||||
model := tui.New()
|
model := tui.New()
|
||||||
model.LoadHosts(hosts)
|
model.SetDataDir(cfg.GetDataDir())
|
||||||
|
if kh != nil {
|
||||||
|
model.SetKnownHosts(kh)
|
||||||
|
}
|
||||||
|
|
||||||
|
if needPassword {
|
||||||
|
// Show password prompt first — hosts will be loaded after password is set
|
||||||
|
model.ShowEncryptPrompt()
|
||||||
|
} else {
|
||||||
|
// No encryption — load hosts normally
|
||||||
|
ctx := context.Background()
|
||||||
|
hosts, err := store.ListHosts(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to load hosts: %w", err)
|
||||||
|
}
|
||||||
|
model.LoadHosts(hosts)
|
||||||
|
}
|
||||||
|
|
||||||
p := tea.NewProgram(model)
|
p := tea.NewProgram(model)
|
||||||
|
model.SetProgram(p)
|
||||||
if _, err := p.Run(); err != nil {
|
if _, err := p.Run(); err != nil {
|
||||||
return fmt.Errorf("failed to run TUI: %w", err)
|
return fmt.Errorf("failed to run TUI: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
# Hostkeeper Test Plan — Phase 3
|
||||||
|
|
||||||
|
> **Created**: 2025-01-31
|
||||||
|
> **Purpose**: Comprehensive test coverage for all packages
|
||||||
|
> **Target Coverage**: 90%+ for all packages
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Current Coverage Summary
|
||||||
|
|
||||||
|
| Package | Current | Target | Gap |
|
||||||
|
|---------|---------|--------|-----|
|
||||||
|
| `internal/errors` | 100% | 100% | — |
|
||||||
|
| `internal/models` | 91% | 100% | +9% |
|
||||||
|
| `pkg/crypto` | **0%** | **100%** | +100% |
|
||||||
|
| `pkg/knownhosts` | **0%** | **100%** | +100% |
|
||||||
|
| `pkg/ssh` | 60% | 90% | +30% |
|
||||||
|
| `pkg/storage` | 40% | 90% | +50% |
|
||||||
|
| `pkg/config` | 22% | 80% | +58% |
|
||||||
|
| `pkg/tui` | ~40% | 70% | +30% |
|
||||||
|
| `cmd/hostkeeper` | ~40% | 70% | +30% |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Test File Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
test/
|
||||||
|
├── crypto/
|
||||||
|
│ └── crypto_test.go (NEW — 17 scenarios)
|
||||||
|
├── knownhosts/
|
||||||
|
│ └── knownhosts_test.go (NEW — 14 scenarios)
|
||||||
|
├── storage/
|
||||||
|
│ ├── export_import_test.go (EXISTING)
|
||||||
|
│ └── json_storage_test.go (NEW — 18 scenarios)
|
||||||
|
├── config/
|
||||||
|
│ └── config_test.go (NEW — 10 scenarios)
|
||||||
|
├── ssh/
|
||||||
|
│ └── ssh_test.go (EXISTING)
|
||||||
|
├── tui/
|
||||||
|
│ ├── theme_test.go (EXISTING)
|
||||||
|
│ ├── error_banner_test.go (EXISTING)
|
||||||
|
│ └── responsive_test.go (NEW — 10 scenarios)
|
||||||
|
├── cmd/
|
||||||
|
│ └── root_test.go (NEW — 8 scenarios)
|
||||||
|
├── errors_test.go (EXISTING)
|
||||||
|
├── models_test.go (EXISTING)
|
||||||
|
└── integration/
|
||||||
|
└── integration_test.go (EXISTING)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Total: 7 new test files, ~87 test scenarios**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Scenario Details
|
||||||
|
|
||||||
|
### 1. `test/crypto/crypto_test.go` — CRITICAL
|
||||||
|
|
||||||
|
| # | Scenario | Input | Expected | Priority |
|
||||||
|
|---|----------|-------|----------|----------|
|
||||||
|
| 1.1 | DeriveKey determinism | same password + salt | same key | HIGH |
|
||||||
|
| 1.2 | DeriveKey password variation | different password | different key | HIGH |
|
||||||
|
| 1.3 | DeriveKey salt variation | different salt | different key | HIGH |
|
||||||
|
| 1.4 | DeriveKey empty password | "" | no panic, valid key | MEDIUM |
|
||||||
|
| 1.5 | Encrypt/Decrypt round-trip | "hello world" | decrypt = original | HIGH |
|
||||||
|
| 1.6 | Encrypt empty plaintext | "" | decrypt = "" | MEDIUM |
|
||||||
|
| 1.7 | Encrypt large data | 1MB random bytes | round-trip OK | MEDIUM |
|
||||||
|
| 1.8 | Encrypt unicode | "こんにちは" | round-trip OK | MEDIUM |
|
||||||
|
| 1.9 | Encrypt with newlines | "line1\nline2" | round-trip OK | MEDIUM |
|
||||||
|
| 1.10 | Wrong password | decrypt with wrong pw | ErrDecryptionFailed | HIGH |
|
||||||
|
| 1.11 | Empty password | decrypt with "" | ErrDecryptionFailed | HIGH |
|
||||||
|
| 1.12 | IsEncrypted valid ciphertext | base64 ciphertext | true | HIGH |
|
||||||
|
| 1.13 | IsEncrypted plaintext | "hello" | false | HIGH |
|
||||||
|
| 1.14 | IsEncrypted empty | "" | false | MEDIUM |
|
||||||
|
| 1.15 | HashPassword determinism | same pw | same hash | HIGH |
|
||||||
|
| 1.16 | HashPassword variation | different pw | different hash | HIGH |
|
||||||
|
| 1.17 | Encrypt randomness | same input, 2 calls | different ciphertext | MEDIUM |
|
||||||
|
|
||||||
|
### 2. `test/knownhosts/knownhosts_test.go` — CRITICAL
|
||||||
|
|
||||||
|
| # | Scenario | Input | Expected | Priority |
|
||||||
|
|---|----------|-------|----------|----------|
|
||||||
|
| 2.1 | New creates file | non-existent path | file created | HIGH |
|
||||||
|
| 2.2 | New loads existing | existing file | hosts loaded | HIGH |
|
||||||
|
| 2.3 | Add new host | hostname+port+key | added | HIGH |
|
||||||
|
| 2.4 | Add duplicate | same host twice | no error, no duplicate | HIGH |
|
||||||
|
| 2.5 | Get existing | hostname+port | returns HostKey | HIGH |
|
||||||
|
| 2.6 | Get non-existent | unknown host | nil | MEDIUM |
|
||||||
|
| 2.7 | Remove existing | hostname+port | removed | HIGH |
|
||||||
|
| 2.8 | Remove non-existent | unknown host | no error | MEDIUM |
|
||||||
|
| 2.9 | Verify unknown | new host | (false, nil) TOFU | HIGH |
|
||||||
|
| 2.10 | Verify known match | correct key | (true, hostKey) | HIGH |
|
||||||
|
| 2.11 | Verify known mismatch | wrong key | (false, hostKey) MITM | HIGH |
|
||||||
|
| 2.12 | HostKeyCallback | autoAdd=true | adds unknown hosts | HIGH |
|
||||||
|
| 2.13 | Persistence | Add → Save → New → Get | found | HIGH |
|
||||||
|
| 2.14 | Corrupted file | invalid JSON | error | MEDIUM |
|
||||||
|
|
||||||
|
### 3. `test/storage/json_storage_test.go` — HIGH
|
||||||
|
|
||||||
|
| # | Scenario | Input | Expected | Priority |
|
||||||
|
|---|----------|-------|----------|----------|
|
||||||
|
| 3.1 | SaveKeyPair | valid KeyPair | success | HIGH |
|
||||||
|
| 3.2 | ListKeyPairs | after save | returns saved | HIGH |
|
||||||
|
| 3.3 | GetKeyPair found | by ID | returns KeyPair | HIGH |
|
||||||
|
| 3.4 | GetKeyPair not found | unknown ID | error | MEDIUM |
|
||||||
|
| 3.5 | DeleteKeyPair | by ID | removed | HIGH |
|
||||||
|
| 3.6 | DeleteKeyPair not found | unknown ID | no error | MEDIUM |
|
||||||
|
| 3.7 | SaveSnippet | valid Snippet | success | HIGH |
|
||||||
|
| 3.8 | ListSnippets | after save | returns saved | HIGH |
|
||||||
|
| 3.9 | GetSnippet found | by ID | returns Snippet | HIGH |
|
||||||
|
| 3.10 | GetSnippet not found | unknown ID | error | MEDIUM |
|
||||||
|
| 3.11 | DeleteSnippet | by ID | removed | HIGH |
|
||||||
|
| 3.12 | DeleteSnippet not found | unknown ID | no error | MEDIUM |
|
||||||
|
| 3.13 | SetPassword + SaveHost | encrypted storage | file encrypted | HIGH |
|
||||||
|
| 3.14 | IsDataEncrypted | encrypted file | true | HIGH |
|
||||||
|
| 3.15 | Wrong password load | decrypt with wrong pw | error | HIGH |
|
||||||
|
| 3.16 | MergeStrategyMerge | import with merge | keeps existing + adds new | HIGH |
|
||||||
|
| 3.17 | MergeStrategyReplace | import with replace | overwrites all | HIGH |
|
||||||
|
| 3.18 | SaveHost empty ID | host with "" ID | generates UUID | MEDIUM |
|
||||||
|
|
||||||
|
### 4. `test/config/config_test.go` — MEDIUM
|
||||||
|
|
||||||
|
| # | Scenario | Input | Expected | Priority |
|
||||||
|
|---|----------|-------|----------|----------|
|
||||||
|
| 4.1 | New first run | no config file | creates default | HIGH |
|
||||||
|
| 4.2 | New existing | valid config file | loads config | HIGH |
|
||||||
|
| 4.3 | Save | modify + save | persists | HIGH |
|
||||||
|
| 4.4 | UpdateAppConfig | change theme | saved | HIGH |
|
||||||
|
| 4.5 | GetConfigDir | — | valid path | MEDIUM |
|
||||||
|
| 4.6 | GetDataDir | — | valid path | MEDIUM |
|
||||||
|
| 4.7 | GetConfigFilePath | — | ends with config.json | MEDIUM |
|
||||||
|
| 4.8 | GetHostsFilePath | — | ends with hosts.json | MEDIUM |
|
||||||
|
| 4.9 | GetKeysFilePath | — | ends with keys.json | MEDIUM |
|
||||||
|
| 4.10 | GetSnippetsFilePath | — | ends with snippets.json | MEDIUM |
|
||||||
|
|
||||||
|
### 5. `test/tui/responsive_test.go` — MEDIUM
|
||||||
|
|
||||||
|
| # | Scenario | Input | Expected | Priority |
|
||||||
|
|---|----------|-------|----------|----------|
|
||||||
|
| 5.1 | WrapFooter short | short string | single line | MEDIUM |
|
||||||
|
| 5.2 | WrapFooter long | long string | multi-line | MEDIUM |
|
||||||
|
| 5.3 | WrapFooter empty | "" | "" | LOW |
|
||||||
|
| 5.4 | ClampWidth over | width > max | clamped to max | MEDIUM |
|
||||||
|
| 5.5 | ClampWidth under | width < min | clamped to min | MEDIUM |
|
||||||
|
| 5.6 | ClampWidth in range | min < width < max | unchanged | MEDIUM |
|
||||||
|
| 5.7 | TruncateStr short | short string | unchanged | MEDIUM |
|
||||||
|
| 5.8 | TruncateStr long | long string | truncated + … | MEDIUM |
|
||||||
|
| 5.9 | TruncateStr empty | "" | "" | LOW |
|
||||||
|
| 5.10 | TruncateStr unicode | "こんにちは世界" | correct width | MEDIUM |
|
||||||
|
|
||||||
|
### 6. `test/cmd/root_test.go` — MEDIUM
|
||||||
|
|
||||||
|
| # | Scenario | Input | Expected | Priority |
|
||||||
|
|---|----------|-------|----------|----------|
|
||||||
|
| 6.1 | RootCmd execute | no args | no error | HIGH |
|
||||||
|
| 6.2 | Version flag | --version | shows version | MEDIUM |
|
||||||
|
| 6.3 | FindHost by ID | host ID | returns host | HIGH |
|
||||||
|
| 6.4 | FindHost by name | host name | returns host | HIGH |
|
||||||
|
| 6.5 | FindHost by hostname | IP/hostname | returns host | HIGH |
|
||||||
|
| 6.6 | FindHost not found | unknown | error | MEDIUM |
|
||||||
|
| 6.7 | NewStorage no password | --password="" | unencrypted | MEDIUM |
|
||||||
|
| 6.8 | NewStorage with password | --password="x" | encrypted | HIGH |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Execution Order
|
||||||
|
|
||||||
|
```
|
||||||
|
Phase 3, Sprint 1: Security-Critical (pkg/crypto, pkg/knownhosts)
|
||||||
|
Phase 3, Sprint 2: Core (pkg/storage, pkg/config)
|
||||||
|
Phase 3, Sprint 3: UI + CLI (pkg/tui, cmd/hostkeeper)
|
||||||
|
Phase 3, Sprint 4: Integration + Final
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- [ ] All tests pass (`go test ./test/...`)
|
||||||
|
- [ ] Coverage >= 90% for `pkg/crypto`
|
||||||
|
- [ ] Coverage >= 90% for `pkg/knownhosts`
|
||||||
|
- [ ] Coverage >= 80% for `pkg/storage`
|
||||||
|
- [ ] Coverage >= 70% for `pkg/config`
|
||||||
|
- [ ] Coverage >= 60% for `pkg/tui`
|
||||||
|
- [ ] No race conditions (`go test -race ./test/...`)
|
||||||
|
- [ ] Build clean (`go build ./...`)
|
||||||
@@ -12,8 +12,11 @@ Hostkeeper is a cross-platform SSH/SFTP management tool written in Go, inspired
|
|||||||
|
|
||||||
### Key Design Decisions
|
### Key Design Decisions
|
||||||
|
|
||||||
- **Architecture:** Monolithic CLI with embedded TUI (Progressive enhancement approach)
|
- **Architecture:** TUI-first with native SSH delegation — interactive SSH via `tea.ExecProcess` (zero lag, native terminal), SFTP/browsing via in-process Go
|
||||||
- **Interface:** Hybrid - CLI commands + TUI for management tasks
|
- **Interface:** TUI for management + native fullscreen SSH when connecting; CLI for quick tasks and automation
|
||||||
|
- **SSH Strategy:** Delegate to native `ssh` binary via `tea.ExecProcess` (same approach as tamagosh) — eliminates lag from Go buffering, enables full terminal capability
|
||||||
|
- **SFTP Strategy:** Use `github.com/pkg/sftp` via Go (in-process) — file operations don't need real-time echo, so Go integration works well
|
||||||
|
- **Color Theme:** Gruvbox Material Dark Hard palette (`#d4be98`, `#a9b665`, `#e78a4e`, `#504945`) — soft, easy on eyes
|
||||||
- **Storage:** JSON/YAML files (Phase 1), encrypted storage (Phase 2)
|
- **Storage:** JSON/YAML files (Phase 1), encrypted storage (Phase 2)
|
||||||
- **Platform:** Cross-platform (Linux, macOS, Windows, Termux/Android)
|
- **Platform:** Cross-platform (Linux, macOS, Windows, Termux/Android)
|
||||||
- **Sync:** Manual export/import (Phase 1), cloud sync (future)
|
- **Sync:** Manual export/import (Phase 1), cloud sync (future)
|
||||||
@@ -104,11 +107,12 @@ Hostkeeper is a cross-platform SSH/SFTP management tool written in Go, inspired
|
|||||||
|
|
||||||
### Key Design Principles
|
### Key Design Principles
|
||||||
|
|
||||||
1. **Single Source of Truth** - All data stored in JSON/YAML files
|
1. **Single Source of Truth** - All data stored in JSON files
|
||||||
2. **Command-First** - TUI is wrapper for core commands
|
2. **TUI-First** - TUI is the primary interface; CLI commands serve quick tasks and scripting
|
||||||
3. **Layered Architecture** - UI → Business Logic → Storage
|
3. **Layered Architecture** - UI → Business Logic → Storage
|
||||||
4. **Cross-Platform** - Pure Go, no OS-specific dependencies
|
4. **Cross-Platform** - Pure Go, no OS-specific dependencies
|
||||||
5. **Encrypt-Ready** - Structure prepared for encryption upgrade
|
5. **Encrypt-Ready** - Structure prepared for encryption upgrade
|
||||||
|
6. **Orange Theme** - Distinct orange color palette to visually separate Hostkeeper from the native terminal, signaling the user is inside the application environment
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -143,22 +147,53 @@ hostkeeper completion # Shell completion setup
|
|||||||
|
|
||||||
### 2. TUI Layer (Interactive Interface)
|
### 2. TUI Layer (Interactive Interface)
|
||||||
|
|
||||||
**Framework:** Bubble Tea (recommended for modern, maintainable TUI)
|
**Framework:** Bubble Tea (event-driven TUI) + Lipgloss (styling)
|
||||||
|
|
||||||
**Main Screens:**
|
**Theme:** Gruvbox Material Dark Hard palette (`#d4be98`, `#a9b665`, `#e78a4e`, `#504945`, `#ea6962`) — soft, warm, easy on eyes over long sessions
|
||||||
- **Host List:** Grid/List view with status indicators
|
|
||||||
- **Connection Manager:** Active connections, quick actions
|
|
||||||
- **SFTP Browser:** Dual-pane file browser (Phase 2)
|
|
||||||
- **Key Manager:** SSH keys list, import/export, generate
|
|
||||||
- **Snippet Manager:** Command snippets with variables
|
|
||||||
- **Settings:** Config management, preferences
|
|
||||||
|
|
||||||
**TUI Features:**
|
#### Tab System Architecture
|
||||||
- Event-driven architecture
|
|
||||||
- Responsive layout
|
```
|
||||||
- Keyboard navigation
|
┌─ Hosts ──── SFTP:server1 ── Keys ── Snippets ────────────────┐
|
||||||
- Mouse support (optional)
|
│ │
|
||||||
- Quick actions (`/` search, `n` new, `Ctrl+S` SFTP, etc.)
|
│ [content of active tab — host list, SFTP browser, etc.] │
|
||||||
|
│ │
|
||||||
|
├───────────────────────────────────────────────────────────────┤
|
||||||
|
│ Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Enter:SSH /:search │
|
||||||
|
└───────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Tab Types:**
|
||||||
|
- **HostsTab** — Host list with search, filter, sort, keyboard navigation
|
||||||
|
- **SFTPTab** — Dual-pane (local ↔ remote) file browser with upload/download/delete/rename
|
||||||
|
- **KeysTab** — SSH key management (list, add, edit, delete)
|
||||||
|
- **SnippetsTab** — Command snippets management
|
||||||
|
|
||||||
|
**SSH Connect (NOT a tab — fullscreen native SSH delegation):**
|
||||||
|
- User selects host → presses Enter
|
||||||
|
- TUI exits alt-screen, runs `tea.ExecProcess` → native `ssh` binary takes over terminal directly
|
||||||
|
- Zero lag: native SSH handles PTY, echo, resize, signals — no Go buffering
|
||||||
|
- On SSH exit → TUI resumes, returns to host list
|
||||||
|
- Password auth via `sshpass -e` (SSHPASS env var)
|
||||||
|
- Key auth via `ssh -i <keypath>` (passphrase via SSH_ASKPASS if needed)
|
||||||
|
- User can install `tmux` on server for session persistence (optional)
|
||||||
|
|
||||||
|
**Rationale:** In-process SSH (golang.org/x/crypto/ssh with goroutine I/O) introduces ~6 layers of buffering between keystroke and echo. Delegating to native `ssh` via `tea.ExecProcess` eliminates all Go overhead from the real-time I/O path, giving a native-terminal experience.
|
||||||
|
|
||||||
|
**Keyboard Navigation:**
|
||||||
|
| Key | Action |
|
||||||
|
|-----|--------|
|
||||||
|
| `Ctrl+Tab` / `Shift+Tab` | Cycle tabs forward/backward |
|
||||||
|
| `Ctrl+N` | Add new host |
|
||||||
|
| `Ctrl+E` | Edit selected host |
|
||||||
|
| `Ctrl+F` | Open SFTP browser for selected host |
|
||||||
|
| `Ctrl+K` | SSH Keys management |
|
||||||
|
| `Ctrl+P` | Snippets management |
|
||||||
|
| `Enter` | SSH into selected host (fullscreen native SSH) |
|
||||||
|
| `↑` / `↓` | Navigate lists |
|
||||||
|
| `D` / `Delete` | Delete selected item |
|
||||||
|
| `Ctrl+Q` | Close current tab |
|
||||||
|
| `q` | Quit Hostkeeper |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -661,26 +696,24 @@ Continue anyway? [y/N]
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Phase 2: Enhanced Features (4-6 weeks)
|
### Phase 2: TUI Overhaul & Enhanced Features (4-6 weeks)
|
||||||
|
|
||||||
**TUI Enhancement:**
|
**Priority 1 — TUI Overhaul (Completed):**
|
||||||
- Rich TUI interface for all operations
|
- Tab system with Gruvbox Material theme (TabManager, tab bar, keyboard shortcuts)
|
||||||
- Dual-pane SFTP browser
|
- Native SSH delegation via `tea.ExecProcess` (zero-lag fullscreen SSH, inspired by tamagosh)
|
||||||
- Key management UI
|
- TUI forms for add/edit hosts
|
||||||
- Snippet manager
|
- Dual-pane SFTP browser (local ↔ remote) with upload/download/delete/rename
|
||||||
- Connection snippets execution
|
- Key & snippet management in TUI
|
||||||
|
|
||||||
**Security Enhancement:**
|
**Priority 2 — Security Enhancement:**
|
||||||
- AES-256 encryption for storage
|
- AES-256-GCM encryption for secrets file (inspired by tamagosh)
|
||||||
- Master password protection
|
- Key passphrase support via SSH_ASKPASS
|
||||||
- Secure credential export/import
|
- Known_hosts verification for SFTP connections
|
||||||
- Enhanced error messages
|
|
||||||
|
|
||||||
**User Experience:**
|
**Priority 3 — UX Polish:**
|
||||||
- Shell completion
|
|
||||||
- Configuration profiles
|
- Configuration profiles
|
||||||
- Theme support
|
- Theme customization
|
||||||
- Keyboard shortcuts
|
- Enhanced error messages in TUI
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -694,8 +727,6 @@ Continue anyway? [y/N]
|
|||||||
|
|
||||||
**Advanced Terminal:**
|
**Advanced Terminal:**
|
||||||
- Custom terminal emulator
|
- Custom terminal emulator
|
||||||
- Multiple session management
|
|
||||||
- Tab support
|
|
||||||
- Advanced text selection
|
- Advanced text selection
|
||||||
|
|
||||||
**Integration:**
|
**Integration:**
|
||||||
@@ -762,10 +793,10 @@ Continue anyway? [y/N]
|
|||||||
### Phase 2 Success Metrics
|
### Phase 2 Success Metrics
|
||||||
|
|
||||||
- ✅ Rich TUI interface for all operations
|
- ✅ Rich TUI interface for all operations
|
||||||
- ✅ Encrypted credential storage
|
- ✅ Zero-lag SSH via native binary delegation
|
||||||
- ✅ Dual-pane SFTP browser
|
- ✅ Dual-pane SFTP browser (local ↔ remote)
|
||||||
- ✅ Shell completion and documentation
|
- ✅ Shell completion and documentation
|
||||||
- ✅ Enhanced user experience
|
- ✅ Enhanced user experience with Gruvbox palette
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
|
|
||||||
**Tech Stack:** Go 1.21+, Cobra (CLI framework), Bubble Tea (TUI), golang.org/x/crypto/ssh, Viper (config management), JSON/YAML storage
|
**Tech Stack:** Go 1.21+, Cobra (CLI framework), Bubble Tea (TUI), golang.org/x/crypto/ssh, Viper (config management), JSON/YAML storage
|
||||||
|
|
||||||
**Current Status**: Planning Complete → Ready for Implementation (Check PROJECT_STATE.md for latest updates)
|
**Current Status**: Phase 2 Complete — SSH rewritten with native `ssh` delegation, dual-pane SFTP browser, Gruvbox theme. Next: security encryption + VT emulator multi-session.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -4662,11 +4662,263 @@ git tag -a v1.0.0 -m "Initial MVP release with core SSH management features"
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Phase 2: TUI Overhaul & Enhanced Features
|
||||||
|
|
||||||
|
### Task 15: TUI Tab Framework & Orange Theme
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `pkg/tui/tabs.go` — TabManager, tab bar renderer
|
||||||
|
- Create: `pkg/tui/styles.go` — All lipgloss styles (orange palette)
|
||||||
|
- Modify: `pkg/tui/tui.go` — Integrate TabManager, replace single-screen with tab routing
|
||||||
|
|
||||||
|
**Step 1: Create styles.go**
|
||||||
|
|
||||||
|
```go
|
||||||
|
// pkg/tui/styles.go
|
||||||
|
package tui
|
||||||
|
|
||||||
|
import "github.com/charmbracelet/lipgloss"
|
||||||
|
|
||||||
|
// Orange theme palette
|
||||||
|
var (
|
||||||
|
OrangePrimary = lipgloss.Color("#FF6B00")
|
||||||
|
OrangeSecondary = lipgloss.Color("#FF9F43")
|
||||||
|
OrangeLight = lipgloss.Color("#FFB800")
|
||||||
|
DarkBg = lipgloss.Color("#1A1A1A")
|
||||||
|
LightBg = lipgloss.Color("#2D2D2D")
|
||||||
|
TextPrimary = lipgloss.Color("#FFFFFF")
|
||||||
|
TextSecondary = lipgloss.Color("#AAAAAA")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Component styles
|
||||||
|
var (
|
||||||
|
TabActiveStyle = lipgloss.NewStyle().Background(OrangePrimary).Foreground(DarkBg).Bold(true).Padding(0, 2)
|
||||||
|
TabInactiveStyle = lipgloss.NewStyle().Background(LightBg).Foreground(TextSecondary).Padding(0, 2)
|
||||||
|
TabBarStyle = lipgloss.NewStyle().Background(DarkBg)
|
||||||
|
StatusBarStyle = lipgloss.NewStyle().Background(OrangePrimary).Foreground(DarkBg).Padding(0, 1)
|
||||||
|
TitleStyle = lipgloss.NewStyle().Foreground(OrangeSecondary).Bold(true)
|
||||||
|
HighlightStyle = lipgloss.NewStyle().Foreground(OrangePrimary).Bold(true)
|
||||||
|
SelectedStyle = lipgloss.NewStyle().Foreground(DarkBg).Background(OrangePrimary).Padding(0, 1)
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 2: Create tabs.go — TabManager**
|
||||||
|
|
||||||
|
Core structure:
|
||||||
|
- `Tab` interface with `Init()`, `Update(msg)`, `View()`, `Name() string`
|
||||||
|
- `TabManager` holds slice of tabs + active index
|
||||||
|
- Tab bar rendered via `TabActiveStyle` / `TabInactiveStyle`
|
||||||
|
- Keybind routing: tab-level keys (Ctrl+Tab, Ctrl+Q, Ctrl+N) vs tab-content keys
|
||||||
|
|
||||||
|
```go
|
||||||
|
type Tab interface {
|
||||||
|
Init() tea.Cmd
|
||||||
|
Update(tea.Msg) (Tab, tea.Cmd)
|
||||||
|
View() string
|
||||||
|
Name() string
|
||||||
|
}
|
||||||
|
|
||||||
|
type TabManager struct {
|
||||||
|
tabs []Tab
|
||||||
|
active int
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 3: Modify tui.go**
|
||||||
|
|
||||||
|
Replace `CurrentScreen Screen` with `*TabManager`. Init creates default `HostsTab`. Update delegates to `TabManager.Update()`. View renders tab bar + active tab view + status bar.
|
||||||
|
|
||||||
|
**Step 4: Verify**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make build
|
||||||
|
./bin/hostkeeper tui
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: Tab bar visible at top with "Hosts" tab, orange theme, status bar at bottom. Keyboard navigation works (Ctrl+Tab cycles tabs if multiple exist).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 16: SSH Session Tab (Multi-Session)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `pkg/tui/session.go` — SessionTab with live SSH terminal
|
||||||
|
|
||||||
|
**Architecture:**
|
||||||
|
```
|
||||||
|
┌─ Hosts ── Server Nico ── Web Prod ────────────────┐
|
||||||
|
│ │
|
||||||
|
│ $ htop │
|
||||||
|
│ $ cd /var/log │
|
||||||
|
│ $ tail -f syslog │
|
||||||
|
│ │
|
||||||
|
│ [live SSH session output] │
|
||||||
|
├─────────────────────────────────────────────────────┤
|
||||||
|
│ Connected to Server Nico — Ctrl+Q to disconnect │
|
||||||
|
└─────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**SessionTab struct:**
|
||||||
|
```go
|
||||||
|
type SessionTab struct {
|
||||||
|
host *models.Host
|
||||||
|
client *ssh.Client // Go SSH client
|
||||||
|
pty *ssh.Session
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
input chan string // keyboard input → SSH stdin
|
||||||
|
output chan string // SSH stdout → TUI render
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key flows:**
|
||||||
|
1. User selects host in HostsTab → Enter → open SessionTab
|
||||||
|
2. SessionTab connects via Go SSH client (auto-auth with stored password)
|
||||||
|
3. Start PTY → 2 goroutines: stdin pump, stdout pump
|
||||||
|
4. Keyboard input in TUI → `input` channel → SSH stdin
|
||||||
|
5. SSH stdout → `output` channel → TUI render (via tea.Batch)
|
||||||
|
6. Window resize → `msg tea.WindowSizeMsg` → SSH WindowChange
|
||||||
|
7. Ctrl+Q → close session → remove tab → back to HostsTab
|
||||||
|
8. Multiple sessions = multiple tabs, each with its own goroutines
|
||||||
|
|
||||||
|
**Verify:**
|
||||||
|
```bash
|
||||||
|
make build
|
||||||
|
./bin/hostkeeper tui
|
||||||
|
# Select a host → Enter → SSH session tab opens
|
||||||
|
# Ctrl+Tab to switch between session and host list
|
||||||
|
# Ctrl+Q to close session
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 17: TUI Host Forms (Add/Edit)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `pkg/tui/host_form.go`
|
||||||
|
|
||||||
|
**Form fields:**
|
||||||
|
- Name (text input)
|
||||||
|
- Hostname/IP (text input)
|
||||||
|
- Port (number input, default 22)
|
||||||
|
- Username (text input)
|
||||||
|
- Auth Type (select: password/key/both)
|
||||||
|
- Password (text input, masked)
|
||||||
|
- Key (file selector or paste)
|
||||||
|
- Group (text input)
|
||||||
|
- Tags (text input, comma-separated)
|
||||||
|
- Notes (textarea)
|
||||||
|
|
||||||
|
**Implementation:**
|
||||||
|
- Use Bubble Tea `textinput` model for each field
|
||||||
|
- Tab/Shift+Tab to cycle fields
|
||||||
|
- Enter on last field → submit → save via storage
|
||||||
|
- Edit mode: pre-populate fields from existing host
|
||||||
|
- Cancel (Escape) → back to HostsTab without saving
|
||||||
|
|
||||||
|
**Verify:**
|
||||||
|
```bash
|
||||||
|
make build
|
||||||
|
./bin/hostkeeper tui
|
||||||
|
# HostsTab → press 'a' or Ctrl+N → form opens
|
||||||
|
# Fill fields → Enter → host saved → back to HostsTab
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 18: TUI SFTP Browser
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `pkg/tui/sftp_browser.go`
|
||||||
|
|
||||||
|
**Layout:**
|
||||||
|
```
|
||||||
|
┌─ Hosts ── Server Nico ── SFTP ────────────────────┐
|
||||||
|
│ /var/www/ │
|
||||||
|
│ ──────────────────────────────────────────────── │
|
||||||
|
│ 📁 . <DIR> │
|
||||||
|
│ 📁 .. <DIR> │
|
||||||
|
│ 📁 html <DIR> 2026-01-15 │
|
||||||
|
│ 📄 index.html 4.2 KB 2026-01-15 │
|
||||||
|
│ 📄 config.php 1.1 KB 2026-01-14 │
|
||||||
|
│ 📁 assets <DIR> 2026-01-10 │
|
||||||
|
├─────────────────────────────────────────────────────┤
|
||||||
|
│ ↑↓:nav Enter:open u:upload d:download q:close │
|
||||||
|
└─────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Implementation:**
|
||||||
|
- Reuse SSH connection from SessionTab (or create new one)
|
||||||
|
- `golang.org/x/crypto/ssh` + `github.com/pkg/sftp` for SFTP operations
|
||||||
|
- File list sorted: dirs first, then files alphabetically
|
||||||
|
- Upload: local file picker (current directory) → remote path
|
||||||
|
- Download: selected file → local directory
|
||||||
|
- Navigation: Enter opens directory, Backspace goes up
|
||||||
|
|
||||||
|
**Verify:**
|
||||||
|
```bash
|
||||||
|
make build
|
||||||
|
./bin/hostkeeper tui
|
||||||
|
# SFTP tab → browse files → upload/download
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 19: TUI Key & Snippet Management
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Create: `pkg/tui/key_list.go`
|
||||||
|
- Create: `pkg/tui/snippet_list.go`
|
||||||
|
|
||||||
|
**Key List Tab:**
|
||||||
|
- List all saved SSH keys with name, type, fingerprint
|
||||||
|
- Select key → view details (public key, comment)
|
||||||
|
- Actions: generate new key, import from file, delete
|
||||||
|
- Generate: select type (RSA 4096, ED25519, ECDSA), optional passphrase
|
||||||
|
|
||||||
|
**Snippet List Tab:**
|
||||||
|
- List saved command snippets
|
||||||
|
- Select → preview command
|
||||||
|
- Execute snippet on connected host
|
||||||
|
- Create/edit snippets with name, command, description
|
||||||
|
- Variable substitution: `{{hostname}}`, `{{user}}`, `{{port}}`
|
||||||
|
|
||||||
|
**Verify:**
|
||||||
|
```bash
|
||||||
|
make build
|
||||||
|
./bin/hostkeeper tui
|
||||||
|
# Keys tab → list/generate/import
|
||||||
|
# Snippets tab → list/create/execute
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phase 3: Advanced Features (Future)
|
||||||
|
|
||||||
|
**Cloud Sync:**
|
||||||
|
- User account system
|
||||||
|
- Encrypted cloud storage
|
||||||
|
- Real-time multi-device sync
|
||||||
|
- Conflict resolution
|
||||||
|
|
||||||
|
**Advanced Terminal:**
|
||||||
|
- Custom terminal emulator
|
||||||
|
- Advanced text selection
|
||||||
|
|
||||||
|
**Integration:**
|
||||||
|
- Web UI (optional)
|
||||||
|
- API access
|
||||||
|
- Plugin system
|
||||||
|
- Third-party integrations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 📋 Summary
|
## 📋 Summary
|
||||||
|
|
||||||
This implementation plan provides a comprehensive roadmap for building the Hostkeeper MVP with:
|
This implementation plan provides a comprehensive roadmap for building the Hostkeeper MVP with:
|
||||||
|
|
||||||
### ✅ Completed Components
|
### ✅ Completed Components (MVP)
|
||||||
|
|
||||||
1. **Project Foundation** - Go modules, dependencies, build system
|
1. **Project Foundation** - Go modules, dependencies, build system
|
||||||
2. **Core Data Models** - Host, Key, Snippet, Config models
|
2. **Core Data Models** - Host, Key, Snippet, Config models
|
||||||
@@ -4681,25 +4933,29 @@ This implementation plan provides a comprehensive roadmap for building the Hostk
|
|||||||
11. **Build System** - Cross-platform compilation
|
11. **Build System** - Cross-platform compilation
|
||||||
12. **Documentation** - Installation and usage guides
|
12. **Documentation** - Installation and usage guides
|
||||||
|
|
||||||
### 🎯 MVP Success Criteria
|
### 📋 Phase 2 Completed (TUI Overhaul)
|
||||||
|
|
||||||
- ✅ Can establish SSH connections to remote servers
|
1. **Task 15** — Tab Framework & Gruvbox Theme
|
||||||
|
2. **Task 16** — SSH Session Rewrite (native `ssh` via `tea.ExecProcess`, zero-lag)
|
||||||
|
3. **Task 17** — TUI Host Forms (add/edit)
|
||||||
|
4. **Task 18** — Dual-pane SFTP Browser (local ↔ remote)
|
||||||
|
5. **Task 19** — TUI Key & Snippet Management
|
||||||
|
|
||||||
|
### 🎯 Success Criteria
|
||||||
|
|
||||||
|
- ✅ Native `ssh` binary delegation via `tea.ExecProcess` — zero lag, full terminal capability
|
||||||
|
- ✅ Dual-pane SFTP browser (inspired by tamagosh/Midnight Commander)
|
||||||
- ✅ Can manage multiple hosts with different auth methods
|
- ✅ Can manage multiple hosts with different auth methods
|
||||||
- ✅ Can perform SFTP operations (native client)
|
|
||||||
- ✅ Can export/import credentials across devices
|
- ✅ Can export/import credentials across devices
|
||||||
- ✅ Works on Linux, macOS, Windows, and Termux
|
- ✅ Works on Linux, macOS, Windows, and Termux
|
||||||
- ✅ Secure credential storage with proper permissions
|
- ✅ Secure credential storage with proper permissions
|
||||||
- ✅ User-friendly error messages and help text
|
- ✅ User-friendly error messages and help text
|
||||||
|
- ✅ Gruvbox Material Dark Hard palette for comfortable extended use
|
||||||
|
|
||||||
### 🚀 Ready for Next Phase
|
### 🚀 Phase 3 — Future
|
||||||
|
|
||||||
After completing these tasks, the project will be ready for:
|
1. **AES-256-GCM encrypted secrets** (inspired by tamagosh)
|
||||||
|
2. **Known_hosts verification** for SFTP
|
||||||
1. **Phase 2 Development** - Enhanced features like SFTP TUI, encryption, key management
|
3. **In-app SSH key generation**
|
||||||
2. **User Testing** - Real-world usage and feedback
|
4. **Multi-session without lag** — PTY multiplexer + VT terminal emulator
|
||||||
3. **Documentation** - Advanced guides and tutorials
|
5. **Cloud sync, custom terminal emulator, web interface**
|
||||||
4. **Community Building** - Open source contribution guidelines
|
|
||||||
|
|
||||||
**Estimated Development Time**: 3-4 weeks for experienced Go developer
|
|
||||||
|
|
||||||
**Next Steps**: Execute the implementation plan using the executing-plans skill!
|
|
||||||
+1303
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,459 @@
|
|||||||
|
# Hostkeeper V2 — Architecture
|
||||||
|
|
||||||
|
> **Status**: V2 Planning Complete
|
||||||
|
> **Last Updated**: 2026-06-29
|
||||||
|
> **V1 (existing)**: CLI/TUI SSH/SFTP manager — frozen, no changes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. System Overview
|
||||||
|
|
||||||
|
Hostkeeper V2 is a Termius-like cross-platform SSH/SFTP management GUI. The architecture follows a **Go backend + Web UI + Electron/WebView** pattern — the same approach used by Termius, VS Code, Discord, Slack, and Figma.
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────────────────────────────────────────────┐
|
||||||
|
│ ELECTRON / WEBVIEW │
|
||||||
|
│ Native window, menu bar, tray icon, auto-updater │
|
||||||
|
│ │
|
||||||
|
│ ┌─────────────────────────────────────────────────┐ │
|
||||||
|
│ │ WEB UI (React + TypeScript) │ │
|
||||||
|
│ │ Host List │ Terminal │ SFTP │ Keys │ Settings │ │
|
||||||
|
│ │ ┌───────────────────────────────────────────┐ │ │
|
||||||
|
│ │ │ xterm.js (terminal) │ │ │
|
||||||
|
│ │ └───────────────────────────────────────────┘ │ │
|
||||||
|
│ └─────────────────────────────────────────────────┘ │
|
||||||
|
│ │ HTTP + WebSocket │
|
||||||
|
│ ┌─────────────────────────────────────────────────┐ │
|
||||||
|
│ │ GO BACKEND (GoFiber v2) │ │
|
||||||
|
│ │ REST API │ WebSocket │ SSH │ SFTP │ │
|
||||||
|
│ │ ┌───────────────────────────────────────────┐ │ │
|
||||||
|
│ │ │ pkg/ssh │ pkg/sftp │ pkg/crypto │ ... │ │ │
|
||||||
|
│ │ └───────────────────────────────────────────┘ │ │
|
||||||
|
│ └─────────────────────────────────────────────────┘ │
|
||||||
|
└──────────────────────────────────────────────────────┘
|
||||||
|
│ Distributed as:
|
||||||
|
├── .dmg (macOS)
|
||||||
|
├── .exe (Windows)
|
||||||
|
├── .AppImage (Linux)
|
||||||
|
└── .aab / .ipa (Android / iOS)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Communication Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
User interaction (keyboard, mouse)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
React component (event handler)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
API client (fetch / WebSocket)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
GoFiber HTTP server (localhost:randomPort)
|
||||||
|
│
|
||||||
|
├── REST handlers → pkg/storage → JSON files
|
||||||
|
└── WebSocket handlers → pkg/ssh → remote server
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Technology Stack
|
||||||
|
|
||||||
|
### Backend (Go)
|
||||||
|
|
||||||
|
| Component | Library | Purpose |
|
||||||
|
|-----------|---------|---------|
|
||||||
|
| HTTP server | `gofiber/fiber/v2` | REST API, static file serving |
|
||||||
|
| WebSocket | `gofiber/contrib/websocket` | Terminal streaming, real-time updates |
|
||||||
|
| WebSocket engine | `fasthttp/websocket` | Underlying WS protocol (fork of gorilla) |
|
||||||
|
| SSH client | `golang.org/x/crypto/ssh` | Remote SSH connections (reuse V1 pkg/ssh) |
|
||||||
|
| SFTP client | `github.com/pkg/sftp` | File transfer (reuse V1 pkg/sftp) |
|
||||||
|
| Crypto | `crypto/aes`, `crypto/cipher` | AES-256-GCM encryption (reuse V1 pkg/crypto) |
|
||||||
|
| Storage | Standard `os` + `encoding/json` | JSON file persistence (reuse V1 pkg/storage) |
|
||||||
|
| Config | `github.com/spf13/viper` | App configuration (reuse V1 pkg/config) |
|
||||||
|
| UUID | `github.com/google/uuid` | Unique IDs for entities |
|
||||||
|
| Routers | `github.com/gofiber/fiber/v2` | HTTP routing |
|
||||||
|
| Middleware | GoFiber built-in | CORS, compress, recover, logger |
|
||||||
|
|
||||||
|
### Frontend (React/TypeScript)
|
||||||
|
|
||||||
|
| Component | Library | Purpose |
|
||||||
|
|-----------|---------|---------|
|
||||||
|
| Framework | React 19 + TypeScript | UI components |
|
||||||
|
| Build tool | Vite | Fast development + production build |
|
||||||
|
| Terminal | xterm.js + addons | Terminal emulation (fit, web-links, search) |
|
||||||
|
| State | Zustand | Lightweight state management |
|
||||||
|
| Routing | React Router v7 | Screen navigation |
|
||||||
|
| Styling | TailwindCSS + CSS variables | Theming (dark/light/contrast) |
|
||||||
|
| Icons | Lucide React | Consistent icon set |
|
||||||
|
| Notifications | Sonner | Toast notifications |
|
||||||
|
|
||||||
|
### Desktop (Electron)
|
||||||
|
|
||||||
|
| Component | Library | Purpose |
|
||||||
|
|-----------|---------|---------|
|
||||||
|
| Shell | Electron 33 | Native desktop wrapper |
|
||||||
|
| Packaging | electron-builder | Build .dmg, .exe, .AppImage |
|
||||||
|
| Auto-update | electron-updater | In-app updates |
|
||||||
|
| Keychain | Node.js safeStorage | OS keychain integration |
|
||||||
|
| IPC | Electron IPC | Go backend <-> Electron communication |
|
||||||
|
|
||||||
|
### Mobile
|
||||||
|
|
||||||
|
| Component | Library | Purpose |
|
||||||
|
|-----------|---------|---------|
|
||||||
|
| Go library | gomobile bind | Compile Go to .aar/.xcframework |
|
||||||
|
| UI shell | React Native WebView | Display web UI on mobile |
|
||||||
|
| Native code | Java (Android) / Swift (iOS) | Minimal WebView wrapper |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Directory Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
hostkeeper/
|
||||||
|
├── cmd/ # V1 CLI (FROZEN)
|
||||||
|
│ └── hostkeeper/
|
||||||
|
├── pkg/ # V1 shared packages (FROZEN)
|
||||||
|
│ ├── ssh/
|
||||||
|
│ ├── sftp/
|
||||||
|
│ ├── crypto/
|
||||||
|
│ ├── storage/
|
||||||
|
│ ├── config/
|
||||||
|
│ ├── knownhosts/
|
||||||
|
│ └── tui/
|
||||||
|
├── internal/ # V1 internal packages (FROZEN)
|
||||||
|
│ ├── models/
|
||||||
|
│ └── errors/
|
||||||
|
├── test/ # V1 tests (FROZEN)
|
||||||
|
│
|
||||||
|
├── app/ # V2 GUI (NEW)
|
||||||
|
│ ├── backend/ # Go HTTP server
|
||||||
|
│ │ ├── main.go # Entry point, fiber server setup
|
||||||
|
│ │ ├── go.mod # Go module for backend
|
||||||
|
│ │ ├── bridge/ # REST API handlers
|
||||||
|
│ │ │ ├── hosts.go
|
||||||
|
│ │ │ ├── keys.go
|
||||||
|
│ │ │ ├── snippets.go
|
||||||
|
│ │ │ ├── groups.go
|
||||||
|
│ │ │ ├── portforward.go
|
||||||
|
│ │ │ ├── sftp.go
|
||||||
|
│ │ │ ├── config.go
|
||||||
|
│ │ │ ├── vault.go
|
||||||
|
│ │ │ └── export.go
|
||||||
|
│ │ ├── ws/ # WebSocket handlers
|
||||||
|
│ │ │ ├── terminal.go # SSH terminal streaming
|
||||||
|
│ │ │ └── session.go # Session management
|
||||||
|
│ │ └── middleware/ # Custom middleware
|
||||||
|
│ │ └── middleware.go # (optional overrides)
|
||||||
|
│ │
|
||||||
|
│ ├── frontend/ # React web UI
|
||||||
|
│ │ ├── src/
|
||||||
|
│ │ │ ├── components/ # Reusable UI components
|
||||||
|
│ │ │ ├── screens/ # Page-level components
|
||||||
|
│ │ │ ├── hooks/ # Custom React hooks
|
||||||
|
│ │ │ ├── stores/ # Zustand state stores
|
||||||
|
│ │ │ ├── api/ # API client functions
|
||||||
|
│ │ │ └── styles/ # CSS, themes, variables
|
||||||
|
│ │ ├── index.html
|
||||||
|
│ │ ├── vite.config.ts
|
||||||
|
│ │ ├── tailwind.config.js
|
||||||
|
│ │ ├── tsconfig.json
|
||||||
|
│ │ └── package.json
|
||||||
|
│ │
|
||||||
|
│ └── electron/ # Electron shell
|
||||||
|
│ ├── main.ts # Main process
|
||||||
|
│ ├── preload.ts # Preload script (IPC bridge)
|
||||||
|
│ ├── build.ts # Build configuration
|
||||||
|
│ ├── package.json
|
||||||
|
│ └── electron-builder.yml
|
||||||
|
│
|
||||||
|
├── mobile/ # V2 Mobile (NEW)
|
||||||
|
│ ├── android/ # Android WebView app
|
||||||
|
│ │ ├── app/
|
||||||
|
│ │ ├── build.gradle
|
||||||
|
│ │ └── ...
|
||||||
|
│ ├── ios/ # iOS WKWebView app
|
||||||
|
│ │ ├── Hostkeeper/
|
||||||
|
│ │ ├── Hostkeeper.xcodeproj
|
||||||
|
│ │ └── ...
|
||||||
|
│ └── gomobile/ # Go mobile compilation
|
||||||
|
│ ├── build.sh
|
||||||
|
│ └── ...
|
||||||
|
│
|
||||||
|
├── scripts/ # Build scripts
|
||||||
|
│ ├── build.sh # Full build (Go + FE + Electron)
|
||||||
|
│ ├── build-go.sh # Go cross-compile
|
||||||
|
│ ├── build-fe.sh # Frontend build
|
||||||
|
│ ├── build-electron.sh # Electron package
|
||||||
|
│ └── build-mobile.sh # Mobile build
|
||||||
|
│
|
||||||
|
├── docs/ # Documentation
|
||||||
|
│ ├── v2/ # V2 planning docs
|
||||||
|
│ │ ├── PROGRESS.md # Status tracker (read this first)
|
||||||
|
│ │ ├── ARCHITECTURE.md # This file
|
||||||
|
│ │ ├── API.md # REST API + WebSocket spec
|
||||||
|
│ │ ├── DATA_MODELS.md # Extended data models
|
||||||
|
│ │ ├── UI_COMPONENTS.md # React component tree
|
||||||
|
│ │ ├── UI_TERMIUS_REFERENCE.md # Termius visual reference
|
||||||
|
│ │ ├── SPRINT_PLAN.md # Sprint-by-sprint task breakdown
|
||||||
|
│ │ ├── BUILD_SYSTEM.md # Build pipeline
|
||||||
|
│ │ └── PERFORMANCE.md # Performance & stability
|
||||||
|
│ ├── v1/ # V1 docs (FROZEN, reference only)
|
||||||
|
│ │ ├── ARCHITECTURE.md
|
||||||
|
│ │ ├── TEST_PLAN.md
|
||||||
|
│ │ ├── INSTALLATION.md
|
||||||
|
│ │ └── USAGE.md
|
||||||
|
│ └── plans/ # V1 design docs (FROZEN)
|
||||||
|
│
|
||||||
|
├── go.mod # V1 Go module
|
||||||
|
├── go.sum
|
||||||
|
├── Makefile
|
||||||
|
├── build.sh
|
||||||
|
├── CHANGELOG.md
|
||||||
|
├── PROJECT_STATE.md # V1 project state
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Process Model
|
||||||
|
|
||||||
|
### Startup Sequence
|
||||||
|
|
||||||
|
```
|
||||||
|
1. User double-clicks Hostkeeper.app (Electron)
|
||||||
|
2. Electron main process starts
|
||||||
|
3. Electron spawns Go binary as child process
|
||||||
|
4. Go binary starts GoFiber server on localhost:randomPort
|
||||||
|
5. Go serves frontend dist (embedded in Electron)
|
||||||
|
6. Electron loads web UI from localhost:PORT
|
||||||
|
7. Web UI renders vault unlock screen
|
||||||
|
8. User enters password -> Go unlocks vault (decrypts data)
|
||||||
|
9. User sees host list screen -> ready to use
|
||||||
|
```
|
||||||
|
|
||||||
|
### Shutdown Sequence
|
||||||
|
|
||||||
|
```
|
||||||
|
1. User closes window / Cmd+Q
|
||||||
|
2. Electron sends SIGTERM to Go child process
|
||||||
|
3. Go receives signal -> starts graceful shutdown
|
||||||
|
4. Go disconnects all active SSH sessions
|
||||||
|
5. Go saves any pending state
|
||||||
|
6. Go closes fiber server
|
||||||
|
7. Go exits
|
||||||
|
8. Electron exits
|
||||||
|
```
|
||||||
|
|
||||||
|
### Development Mode
|
||||||
|
|
||||||
|
```
|
||||||
|
1. Terminal: cd app/backend && go run .
|
||||||
|
2. Terminal: cd app/frontend && npm run dev
|
||||||
|
3. Go server at localhost:8080
|
||||||
|
4. Frontend dev server at localhost:5173 (Vite HMR)
|
||||||
|
5. Frontend proxies API requests to localhost:8080
|
||||||
|
6. Open browser at localhost:5173
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Data Flow
|
||||||
|
|
||||||
|
### REST API Request Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
React component
|
||||||
|
→ useQuery/useMutation (React Query or manual fetch)
|
||||||
|
→ API client (fetch wrapper)
|
||||||
|
→ HTTP request to GoFiber (localhost:PORT/api/...)
|
||||||
|
→ GoFiber router -> handler function
|
||||||
|
→ Handler calls pkg/storage (read/write JSON)
|
||||||
|
→ Response sent back through the chain
|
||||||
|
```
|
||||||
|
|
||||||
|
### Terminal WebSocket Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
User opens terminal tab
|
||||||
|
→ React: XTermWrapper mounts
|
||||||
|
→ XTermWrapper opens WebSocket to ws://localhost:PORT/ws/terminal?host_id=xxx&cols=80&rows=24
|
||||||
|
→ GoFiber WebSocket handler accepts connection
|
||||||
|
→ Go: SSH client connects to remote host (reuse pkg/ssh)
|
||||||
|
→ SSH session created, PTY requested
|
||||||
|
→ SSH stdout goroutine -> reads SSH output -> c.WriteMessage(BinaryMessage, data)
|
||||||
|
-> xterm.js receives data -> renders in terminal
|
||||||
|
-> xterm.js onKey -> c.WriteMessage(BinaryMessage, input)
|
||||||
|
-> Go receives input -> session.Stdin.Write(input) -> SSH remote
|
||||||
|
```
|
||||||
|
|
||||||
|
### SFTP File Transfer Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
User drags file to remote pane
|
||||||
|
→ React: FileList onDrop handler
|
||||||
|
→ API client: POST /api/sftp/upload (multipart/form-data)
|
||||||
|
→ Go: bridge/sftp.go receives upload
|
||||||
|
→ Go: pkg/sftp client writes to remote
|
||||||
|
→ Response: { "success": true }
|
||||||
|
→ React: refresh remote file list
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Security Architecture
|
||||||
|
|
||||||
|
### Encryption Model
|
||||||
|
|
||||||
|
| Layer | Method | Implementation |
|
||||||
|
|-------|--------|----------------|
|
||||||
|
| Data at rest | AES-256-GCM | `pkg/crypto/crypto.go` (reuse V1) |
|
||||||
|
| Key derivation | PBKDF2 (100k iterations) | `pkg/crypto/crypto.go` (reuse V1) |
|
||||||
|
| Password storage | SHA-256 hash | `pkg/config/config.go` (reuse V1) |
|
||||||
|
| Known hosts | TOFU verification | `pkg/knownhosts/knownhosts.go` (reuse V1) |
|
||||||
|
| Transport | localhost only | No TLS needed (same machine) |
|
||||||
|
| Export | AES-256-GCM with password | `pkg/storage/json_storage.go` (reuse V1) |
|
||||||
|
|
||||||
|
### Vault Flow
|
||||||
|
|
||||||
|
```
|
||||||
|
App start -> vault locked -> prompt password
|
||||||
|
-> PBKDF2 derive key from password
|
||||||
|
-> Try decrypt hosts.json
|
||||||
|
-> Success -> vault unlocked, data accessible
|
||||||
|
-> Fail -> wrong password, show error
|
||||||
|
-> Vault locked -> no data accessible
|
||||||
|
-> Auto-lock after inactivity timer
|
||||||
|
```
|
||||||
|
|
||||||
|
### OS Keychain Integration
|
||||||
|
|
||||||
|
| Platform | Library | Purpose |
|
||||||
|
|----------|---------|---------|
|
||||||
|
| macOS | `security` CLI or `go-keychain` | Store vault master key |
|
||||||
|
| Windows | `go-credential` | Store vault master key |
|
||||||
|
| Linux | `dbus` Secret Service | Store vault master key |
|
||||||
|
| Electron | `safeStorage` API | Store vault master key |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. WebSocket Protocol
|
||||||
|
|
||||||
|
### Terminal WebSocket
|
||||||
|
|
||||||
|
**Connection**: `ws://localhost:PORT/ws/terminal?host_id=xxx&cols=80&rows=24`
|
||||||
|
|
||||||
|
**Message types** (binary frames):
|
||||||
|
|
||||||
|
| Direction | Type | Content |
|
||||||
|
|-----------|------|---------|
|
||||||
|
| Client → Server | Input | Raw keystroke bytes |
|
||||||
|
| Server → Client | Output | Terminal output bytes |
|
||||||
|
| Client → Server | Resize | JSON: `{ "type": "resize", "cols": 120, "rows": 40 }` |
|
||||||
|
| Server → Client | Status | JSON: `{ "type": "status", "state": "connected" }` |
|
||||||
|
| Server → Client | Error | JSON: `{ "type": "error", "message": "..." }` |
|
||||||
|
|
||||||
|
**Keepalive**: Client sends ping every 30s, server responds with pong.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Build System
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Terminal 1: Go backend
|
||||||
|
cd app/backend
|
||||||
|
go run .
|
||||||
|
|
||||||
|
# Terminal 2: Frontend with hot reload
|
||||||
|
cd app/frontend
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# Browser opens at http://localhost:5173
|
||||||
|
```
|
||||||
|
|
||||||
|
### Production Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Full build
|
||||||
|
./scripts/build.sh
|
||||||
|
|
||||||
|
# Output:
|
||||||
|
# dist/hostkeeper-mac-arm64.dmg
|
||||||
|
# dist/hostkeeper-win-x64.exe
|
||||||
|
# dist/hostkeeper-linux-x64.AppImage
|
||||||
|
```
|
||||||
|
|
||||||
|
### Cross-Compilation Matrix
|
||||||
|
|
||||||
|
| Platform | GOOS | GOARCH | Output |
|
||||||
|
|----------|------|--------|--------|
|
||||||
|
| macOS ARM64 | darwin | arm64 | hostkeeper-mac-arm64 |
|
||||||
|
| macOS x64 | darwin | amd64 | hostkeeper-mac-x64 |
|
||||||
|
| Windows x64 | windows | amd64 | hostkeeper-win-x64.exe |
|
||||||
|
| Linux x64 | linux | amd64 | hostkeeper-linux-x64 |
|
||||||
|
| Linux ARM64 | linux | arm64 | hostkeeper-linux-arm64 |
|
||||||
|
| Android ARM64 | android | arm64 | hostkeeper-android.aar |
|
||||||
|
| iOS ARM64 | ios | arm64 | hostkeeper-ios.xcframework |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Error Handling
|
||||||
|
|
||||||
|
### Go Backend Errors
|
||||||
|
|
||||||
|
```go
|
||||||
|
// All API errors follow this format:
|
||||||
|
{
|
||||||
|
"error": "Human-readable error message",
|
||||||
|
"code": "MACHINE_READABLE_CODE",
|
||||||
|
"details": "Optional technical details"
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTTP status codes:
|
||||||
|
// 200 - Success
|
||||||
|
// 201 - Created
|
||||||
|
// 400 - Bad Request (validation error)
|
||||||
|
// 401 - Unauthorized (vault locked)
|
||||||
|
// 404 - Not Found
|
||||||
|
// 409 - Conflict (duplicate)
|
||||||
|
// 500 - Internal Server Error
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontend Error Handling
|
||||||
|
|
||||||
|
- Network errors: automatic retry with exponential backoff (3 retries)
|
||||||
|
- API errors: toast notification with error message
|
||||||
|
- WebSocket errors: reconnect button in terminal, auto-reconnect 3 times
|
||||||
|
- Validation errors: inline field-level error messages
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Testing Strategy
|
||||||
|
|
||||||
|
| Layer | Tool | Coverage Target |
|
||||||
|
|-------|------|----------------|
|
||||||
|
| Go unit tests | `go test` | 80%+ |
|
||||||
|
| Go integration tests | `go test -tags=integration` | Key flows |
|
||||||
|
| React unit tests | Vitest + React Testing Library | 70%+ |
|
||||||
|
| React E2E tests | Playwright | Critical flows |
|
||||||
|
| Manual testing | All platforms | Every sprint |
|
||||||
|
|
||||||
|
### Test Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Go backend tests
|
||||||
|
cd app/backend && go test ./...
|
||||||
|
|
||||||
|
# Frontend tests
|
||||||
|
cd app/frontend && npm test
|
||||||
|
|
||||||
|
# Full test suite
|
||||||
|
make test
|
||||||
|
|
||||||
|
# Race condition check
|
||||||
|
go test -race ./app/backend/...
|
||||||
|
```
|
||||||
@@ -0,0 +1,564 @@
|
|||||||
|
# Hostkeeper V2 — Build System
|
||||||
|
|
||||||
|
> **Status**: V2 Planning Complete
|
||||||
|
> **Last Updated**: 2026-06-29
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Build Overview
|
||||||
|
|
||||||
|
Hostkeeper V2 produces **4 platform outputs** from a single codebase:
|
||||||
|
|
||||||
|
| Platform | Output | Wrapper | Backend |
|
||||||
|
|----------|--------|---------|---------|
|
||||||
|
| macOS (ARM64) | `.dmg` | Electron | Go binary (embedded) |
|
||||||
|
| macOS (x64) | `.dmg` | Electron | Go binary (embedded) |
|
||||||
|
| Windows (x64) | `.exe` installer | Electron | Go binary (embedded) |
|
||||||
|
| Linux (x64) | `.AppImage` | Electron | Go binary (embedded) |
|
||||||
|
| Android (ARM64) | `.aab` / `.apk` | WebView | Go library (.aar) |
|
||||||
|
| iOS (ARM64) | `.ipa` | WKWebView | Go framework (.xcframework) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Build Pipeline
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
||||||
|
│ Go Build │ │ Frontend │ │ Electron │ │ Platform │
|
||||||
|
│ (backend) │ → │ Build │ → │ Package │ → │ Sign │
|
||||||
|
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 1: Go Backend Cross-Compile
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# macOS ARM64
|
||||||
|
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 \
|
||||||
|
go build -ldflags="-s -w" -o dist/hostkeeper-server .
|
||||||
|
|
||||||
|
# macOS x64
|
||||||
|
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 \
|
||||||
|
go build -ldflags="-s -w" -o dist/hostkeeper-server .
|
||||||
|
|
||||||
|
# Windows x64
|
||||||
|
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 \
|
||||||
|
go build -ldflags="-s -w" -o dist/hostkeeper-server.exe .
|
||||||
|
|
||||||
|
# Linux x64
|
||||||
|
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
|
||||||
|
go build -ldflags="-s -w" -o dist/hostkeeper-server .
|
||||||
|
|
||||||
|
# Linux ARM64
|
||||||
|
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 \
|
||||||
|
go build -ldflags="-s -w" -o dist/hostkeeper-server .
|
||||||
|
```
|
||||||
|
|
||||||
|
**Notes**:
|
||||||
|
- `CGO_ENABLED=0` — pure Go, no C dependencies
|
||||||
|
- `-ldflags="-s -w"` — strip debug info, reduce binary size
|
||||||
|
- Go binary size: ~15-20 MB (compressed)
|
||||||
|
|
||||||
|
### Step 2: Frontend Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd app/frontend
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
|
# Output: app/frontend/dist/
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vite config** (`app/frontend/vite.config.ts`):
|
||||||
|
```typescript
|
||||||
|
import { defineConfig } from 'vite';
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
build: {
|
||||||
|
outDir: 'dist',
|
||||||
|
sourcemap: false,
|
||||||
|
minify: 'terser',
|
||||||
|
rollupOptions: {
|
||||||
|
output: {
|
||||||
|
manualChunks: {
|
||||||
|
xterm: ['@xterm/xterm', '@xterm/addon-fit'],
|
||||||
|
react: ['react', 'react-dom'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
proxy: {
|
||||||
|
'/api': 'http://localhost:8080',
|
||||||
|
'/ws': {
|
||||||
|
target: 'ws://localhost:8080',
|
||||||
|
ws: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 3: Electron Package
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# app/electron/electron-builder.yml
|
||||||
|
appId: com.hostkeeper.app
|
||||||
|
productName: Hostkeeper
|
||||||
|
copyright: Copyright © 2026
|
||||||
|
|
||||||
|
directories:
|
||||||
|
output: ../../dist
|
||||||
|
|
||||||
|
files:
|
||||||
|
- "**/*"
|
||||||
|
- "!**/node_modules/*/{CHANGELOG.md,README.md,readme.md,LICENSE}"
|
||||||
|
|
||||||
|
extraResources:
|
||||||
|
- from: "../backend/hostkeeper-server"
|
||||||
|
to: "hostkeeper-server"
|
||||||
|
- from: "../frontend/dist"
|
||||||
|
to: "frontend"
|
||||||
|
|
||||||
|
mac:
|
||||||
|
category: public.app-category.developer-tools
|
||||||
|
icon: assets/icon.icns
|
||||||
|
target:
|
||||||
|
- dmg
|
||||||
|
- zip
|
||||||
|
hardenedRuntime: true
|
||||||
|
notarize: true
|
||||||
|
|
||||||
|
win:
|
||||||
|
icon: assets/icon.ico
|
||||||
|
target:
|
||||||
|
- nsis
|
||||||
|
certificateFile: env.WIN_CERTIFICATE_FILE
|
||||||
|
|
||||||
|
linux:
|
||||||
|
icon: assets/icon.png
|
||||||
|
target:
|
||||||
|
- AppImage
|
||||||
|
- deb
|
||||||
|
category: Development
|
||||||
|
|
||||||
|
nsis:
|
||||||
|
oneClick: false
|
||||||
|
allowToChangeInstallationDirectory: true
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Mobile Build
|
||||||
|
|
||||||
|
### Android
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Prerequisites:
|
||||||
|
# - Android SDK installed
|
||||||
|
# - Go 1.26+ with gomobile
|
||||||
|
# - Java 17+
|
||||||
|
|
||||||
|
# Install gomobile
|
||||||
|
go install golang.org/x/mobile/cmd/gomobile@latest
|
||||||
|
gomobile init
|
||||||
|
|
||||||
|
# Build Go library
|
||||||
|
cd mobile/gomobile
|
||||||
|
gomobile bind -target=android -o=../android/app/libs/hostkeeper.aar \
|
||||||
|
./go/
|
||||||
|
|
||||||
|
# Build Android app
|
||||||
|
cd ../android
|
||||||
|
./gradlew assembleRelease
|
||||||
|
# Output: mobile/android/app/build/outputs/apk/release/app-release.apk
|
||||||
|
```
|
||||||
|
|
||||||
|
### iOS
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Prerequisites:
|
||||||
|
# - Xcode 15+
|
||||||
|
# - Go 1.26+ with gomobile
|
||||||
|
|
||||||
|
# Build Go framework
|
||||||
|
cd mobile/gomobile
|
||||||
|
gomobile bind -target=ios -o=../ios/Hostkeeper/Hostkeeper.xcframework \
|
||||||
|
./go/
|
||||||
|
|
||||||
|
# Build iOS app
|
||||||
|
cd ../ios
|
||||||
|
xcodebuild -project Hostkeeper.xcodeproj \
|
||||||
|
-scheme Hostkeeper \
|
||||||
|
-sdk iphoneos \
|
||||||
|
-configuration Release
|
||||||
|
# Output: mobile/ios/build/Release-iphoneos/Hostkeeper.app
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Build Scripts
|
||||||
|
|
||||||
|
### `scripts/build.sh` (Full Build)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
VERSION=${1:-"dev"}
|
||||||
|
PLATFORM=${2:-"all"}
|
||||||
|
|
||||||
|
echo "=== Building Hostkeeper V2 v${VERSION} ==="
|
||||||
|
|
||||||
|
# Step 1: Build Go backend
|
||||||
|
echo "Step 1: Building Go backend..."
|
||||||
|
cd app/backend
|
||||||
|
|
||||||
|
case $PLATFORM in
|
||||||
|
macos|all)
|
||||||
|
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w -X main.version=${VERSION}" -o ../electron/hostkeeper-server .
|
||||||
|
;;
|
||||||
|
windows|all)
|
||||||
|
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -X main.version=${VERSION}" -o ../electron/hostkeeper-server.exe .
|
||||||
|
;;
|
||||||
|
linux|all)
|
||||||
|
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X main.version=${VERSION}" -o ../electron/hostkeeper-server .
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
cd ../..
|
||||||
|
|
||||||
|
# Step 2: Build frontend
|
||||||
|
echo "Step 2: Building frontend..."
|
||||||
|
cd app/frontend
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
|
cd ../..
|
||||||
|
|
||||||
|
# Step 3: Package Electron
|
||||||
|
echo "Step 3: Packaging Electron..."
|
||||||
|
cd app/electron
|
||||||
|
|
||||||
|
case $PLATFORM in
|
||||||
|
macos)
|
||||||
|
npx electron-builder --mac --arm64
|
||||||
|
;;
|
||||||
|
windows)
|
||||||
|
npx electron-builder --win --x64
|
||||||
|
;;
|
||||||
|
linux)
|
||||||
|
npx electron-builder --linux --x64
|
||||||
|
;;
|
||||||
|
all)
|
||||||
|
npx electron-builder --mac --win --linux
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
cd ../..
|
||||||
|
|
||||||
|
# Step 4: Generate checksums
|
||||||
|
echo "Step 4: Generating checksums..."
|
||||||
|
cd dist
|
||||||
|
shasum -a 256 *.dmg *.exe *.AppImage 2>/dev/null > checksums.txt
|
||||||
|
|
||||||
|
echo "=== Build complete ==="
|
||||||
|
echo "Output: dist/"
|
||||||
|
ls -la dist/
|
||||||
|
```
|
||||||
|
|
||||||
|
### `scripts/build-mobile.sh`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
PLATFORM=${1:-"android"}
|
||||||
|
|
||||||
|
echo "=== Building Hostkeeper Mobile (${PLATFORM}) ==="
|
||||||
|
|
||||||
|
case $PLATFORM in
|
||||||
|
android)
|
||||||
|
cd mobile/gomobile
|
||||||
|
gomobile bind -target=android -o=../android/app/libs/hostkeeper.aar ./go/
|
||||||
|
cd ../android
|
||||||
|
./gradlew assembleRelease
|
||||||
|
echo "APK: mobile/android/app/build/outputs/apk/release/"
|
||||||
|
;;
|
||||||
|
ios)
|
||||||
|
cd mobile/gomobile
|
||||||
|
gomobile bind -target=ios -o=../ios/Hostkeeper/Hostkeeper.xcframework ./go/
|
||||||
|
cd ../ios
|
||||||
|
xcodebuild -project Hostkeeper.xcodeproj -scheme Hostkeeper -sdk iphoneos -configuration Release
|
||||||
|
echo "IPA: mobile/ios/build/Release-iphoneos/"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
echo "=== Mobile build complete ==="
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Development Workflow
|
||||||
|
|
||||||
|
### Quick Start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Terminal 1: Go backend
|
||||||
|
cd app/backend
|
||||||
|
go run .
|
||||||
|
|
||||||
|
# Terminal 2: Frontend (with hot reload)
|
||||||
|
cd app/frontend
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# Open browser: http://localhost:5173
|
||||||
|
```
|
||||||
|
|
||||||
|
### With Electron
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Terminal 1: Go backend
|
||||||
|
cd app/backend
|
||||||
|
go run .
|
||||||
|
|
||||||
|
# Terminal 2: Frontend
|
||||||
|
cd app/frontend
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# Terminal 3: Electron
|
||||||
|
cd app/electron
|
||||||
|
npm run dev
|
||||||
|
# Electron opens with hot reload
|
||||||
|
```
|
||||||
|
|
||||||
|
### VS Code Launch Config
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Go Backend",
|
||||||
|
"type": "go",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${workspaceFolder}/app/backend",
|
||||||
|
"cwd": "${workspaceFolder}/app/backend"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Electron",
|
||||||
|
"type": "node",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${workspaceFolder}/app/electron/node_modules/.bin/electron",
|
||||||
|
"args": ["."],
|
||||||
|
"cwd": "${workspaceFolder}/app/electron"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. CI/CD (GitHub Actions)
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/build.yml
|
||||||
|
name: Build
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['v*']
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.26'
|
||||||
|
- run: go test -race ./app/backend/...
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '22'
|
||||||
|
- run: cd app/frontend && npm ci && npm test
|
||||||
|
|
||||||
|
build-macos:
|
||||||
|
needs: test
|
||||||
|
runs-on: macos-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.26'
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '22'
|
||||||
|
- run: ./scripts/build.sh ${{ github.ref_name }} macos
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: hostkeeper-macos
|
||||||
|
path: dist/*.dmg
|
||||||
|
|
||||||
|
build-windows:
|
||||||
|
needs: test
|
||||||
|
runs-on: windows-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.26'
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '22'
|
||||||
|
- run: ./scripts/build.sh ${{ github.ref_name }} windows
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: hostkeeper-windows
|
||||||
|
path: dist/*.exe
|
||||||
|
|
||||||
|
build-linux:
|
||||||
|
needs: test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.26'
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '22'
|
||||||
|
- run: ./scripts/build.sh ${{ github.ref_name }} linux
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: hostkeeper-linux
|
||||||
|
path: dist/*.AppImage
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Binary Size Optimization
|
||||||
|
|
||||||
|
| Technique | Impact |
|
||||||
|
|-----------|--------|
|
||||||
|
| `-ldflags="-s -w"` | -20% Go binary size |
|
||||||
|
| UPX compression (optional) | -60% Go binary size |
|
||||||
|
| Vite tree shaking | -40% JS bundle size |
|
||||||
|
| Code splitting (lazy load) | -30% initial load |
|
||||||
|
| Image optimization | -50% icon sizes |
|
||||||
|
| Terser minification | -30% JS size |
|
||||||
|
| CSS purging (Tailwind) | -80% CSS size |
|
||||||
|
|
||||||
|
**Target sizes**:
|
||||||
|
- Go backend binary: ~15 MB (5 MB compressed)
|
||||||
|
- Frontend dist: ~2 MB (500 KB compressed)
|
||||||
|
- Electron package: ~200 MB total
|
||||||
|
- Mobile APK: ~50 MB
|
||||||
|
- Mobile IPA: ~60 MB
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Version Management
|
||||||
|
|
||||||
|
### Version Format
|
||||||
|
|
||||||
|
```
|
||||||
|
vMAJOR.MINOR.PATCH
|
||||||
|
```
|
||||||
|
|
||||||
|
- **MAJOR**: Breaking changes (data format, API)
|
||||||
|
- **MINOR**: New features
|
||||||
|
- **PATCH**: Bug fixes
|
||||||
|
|
||||||
|
### Version Injection
|
||||||
|
|
||||||
|
```go
|
||||||
|
// In main.go
|
||||||
|
var version = "dev"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Printf("Hostkeeper v%s\n", version)
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Build with version
|
||||||
|
go build -ldflags="-X main.version=v2.0.0" -o hostkeeper-server .
|
||||||
|
```
|
||||||
|
|
||||||
|
### Changelog Format
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## [v2.1.0] - 2026-07-15
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Port forwarding support (local, remote, dynamic)
|
||||||
|
- Import from ~/.ssh/config
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Improved terminal performance with WebGL renderer
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Fixed SFTP upload progress not updating
|
||||||
|
- Fixed vault auto-lock not triggering on sleep
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Code Signing
|
||||||
|
|
||||||
|
### macOS
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Requires Apple Developer account + certificates
|
||||||
|
export CSC_LINK="path/to/certificate.p12"
|
||||||
|
export CSC_KEY_PASSWORD="certificate-password"
|
||||||
|
|
||||||
|
# electron-builder handles signing + notarization
|
||||||
|
npx electron-builder --mac --publish always
|
||||||
|
```
|
||||||
|
|
||||||
|
### Windows
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Requires code signing certificate
|
||||||
|
export WIN_CERTIFICATE_FILE="path/to/certificate.pfx"
|
||||||
|
export WIN_CERTIFICATE_PASSWORD="certificate-password"
|
||||||
|
|
||||||
|
npx electron-builder --win --publish always
|
||||||
|
```
|
||||||
|
|
||||||
|
### Linux
|
||||||
|
|
||||||
|
No code signing required. AppImage is self-contained.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Release Workflow
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Update version
|
||||||
|
npm version minor # or major, patch
|
||||||
|
|
||||||
|
# 2. Update CHANGELOG.md
|
||||||
|
|
||||||
|
# 3. Commit
|
||||||
|
git add .
|
||||||
|
git commit -m "chore: release v2.1.0"
|
||||||
|
|
||||||
|
# 4. Tag
|
||||||
|
git tag -a v2.1.0 -m "Release v2.1.0"
|
||||||
|
|
||||||
|
# 5. Push
|
||||||
|
git push origin main --tags
|
||||||
|
|
||||||
|
# 6. GitHub Actions builds + publishes artifacts
|
||||||
|
|
||||||
|
# 7. Create GitHub Release
|
||||||
|
gh release create v2.1.0 \
|
||||||
|
--title "Hostkeeper v2.1.0" \
|
||||||
|
--notes-file CHANGELOG.md \
|
||||||
|
dist/*.dmg dist/*.exe dist/*.AppImage
|
||||||
|
```
|
||||||
@@ -0,0 +1,391 @@
|
|||||||
|
# Hostkeeper V2 — Extended Data Models
|
||||||
|
|
||||||
|
> **Status**: V2 Planning Complete
|
||||||
|
> **Last Updated**: 2026-06-29
|
||||||
|
> **V1 models**: `internal/models/models.go` — frozen, no changes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Overview
|
||||||
|
|
||||||
|
V2 extends V1 models with new entities for groups, vault, port forwarding, workspaces, and sessions. All V1 models remain unchanged. New models are added in `app/backend/models/` (or `internal/models/` with backward-compatible additions).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. V1 Models (FROZEN — do not modify)
|
||||||
|
|
||||||
|
These exist in `internal/models/models.go` and are used as-is:
|
||||||
|
|
||||||
|
- `Host` — SSH host connection configuration
|
||||||
|
- `AuthConfig` — Authentication configuration (password/key/agent)
|
||||||
|
- `KeyPair` — SSH key pair
|
||||||
|
- `Snippet` — Command snippet
|
||||||
|
- `Profile` — Named configuration profile
|
||||||
|
- `AppConfig` — Application configuration
|
||||||
|
- `KnownHost` — Verified host key
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. V2 Models (NEW)
|
||||||
|
|
||||||
|
### 3.1 HostGroup
|
||||||
|
|
||||||
|
Nestable group for organizing hosts. Groups can contain other groups and hosts.
|
||||||
|
|
||||||
|
```go
|
||||||
|
type HostGroup struct {
|
||||||
|
ID string `json:"id" bson:"_id,omitempty"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
ParentID *string `json:"parent_id,omitempty"` // nil = root group
|
||||||
|
Color string `json:"color,omitempty"` // hex color e.g. "#e78a4e"
|
||||||
|
Icon string `json:"icon,omitempty"` // icon name e.g. "server", "globe"
|
||||||
|
Order int `json:"order"` // sort order within parent
|
||||||
|
Children []*HostGroup `json:"children,omitempty"` // populated at runtime, not stored
|
||||||
|
HostCount int `json:"host_count,omitempty"` // populated at runtime
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Storage**: `groups.json`
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"groups": [
|
||||||
|
{
|
||||||
|
"id": "550e8400-e29b-41d4-a716-446655440000",
|
||||||
|
"name": "Production",
|
||||||
|
"parent_id": null,
|
||||||
|
"color": "#e78a4e",
|
||||||
|
"icon": "server",
|
||||||
|
"order": 0,
|
||||||
|
"created_at": "2024-06-22T10:00:00Z",
|
||||||
|
"updated_at": "2024-06-22T10:00:00Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Rules**:
|
||||||
|
- Maximum nesting depth: 5 levels
|
||||||
|
- Root groups have `parent_id: null`
|
||||||
|
- Deleting a group moves its hosts to parent (or ungrouped)
|
||||||
|
- Group names must be unique within the same parent
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.2 Extended Host
|
||||||
|
|
||||||
|
New fields added to the existing `Host` struct:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// V2 additions to Host struct
|
||||||
|
type HostV2 struct {
|
||||||
|
// ... all V1 fields ...
|
||||||
|
|
||||||
|
GroupID *string `json:"group_id,omitempty"` // reference to HostGroup.ID
|
||||||
|
IsFavorite bool `json:"is_favorite"` // quick access
|
||||||
|
Color string `json:"color,omitempty"` // override group color
|
||||||
|
Order int `json:"order"` // sort order within group
|
||||||
|
StartupSnippets []string `json:"startup_snippets,omitempty"` // snippet IDs to run on connect
|
||||||
|
Proxy *ProxyConfig `json:"proxy,omitempty"` // proxy configuration
|
||||||
|
JumpHost *string `json:"jump_host_id,omitempty"` // jump host ID
|
||||||
|
Keepalive int `json:"keepalive,omitempty"` // keepalive interval in seconds
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note**: V1 Host fields are untouched. V2 fields are added with `omitempty` for backward compatibility.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.3 ProxyConfig
|
||||||
|
|
||||||
|
Proxy configuration for SSH connections through proxy servers.
|
||||||
|
|
||||||
|
```go
|
||||||
|
type ProxyConfig struct {
|
||||||
|
Type string `json:"type"` // "socks5", "http", "command"
|
||||||
|
Host string `json:"host"` // proxy host
|
||||||
|
Port int `json:"port"` // proxy port
|
||||||
|
Username string `json:"username,omitempty"`
|
||||||
|
Password string `json:"password,omitempty"`
|
||||||
|
Command string `json:"command,omitempty"` // for "command" type (netcat-style)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.4 PortForward
|
||||||
|
|
||||||
|
SSH port forwarding configuration.
|
||||||
|
|
||||||
|
```go
|
||||||
|
type PortForward struct {
|
||||||
|
ID string `json:"id" bson:"_id,omitempty"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
HostID string `json:"host_id"` // reference to Host.ID
|
||||||
|
Type string `json:"type"` // "local", "remote", "dynamic"
|
||||||
|
LocalAddr string `json:"local_addr"` // e.g. "127.0.0.1:8080"
|
||||||
|
RemoteAddr string `json:"remote_addr"` // e.g. "localhost:3000"
|
||||||
|
Status string `json:"status"` // "stopped", "running", "error"
|
||||||
|
AutoStart bool `json:"auto_start"` // start tunnel on app launch
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Storage**: `forwards.json`
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"forwards": [
|
||||||
|
{
|
||||||
|
"id": "forward-uuid",
|
||||||
|
"name": "Local Redis",
|
||||||
|
"host_id": "host-uuid",
|
||||||
|
"type": "local",
|
||||||
|
"local_addr": "127.0.0.1:6379",
|
||||||
|
"remote_addr": "localhost:6379",
|
||||||
|
"status": "stopped",
|
||||||
|
"auto_start": false,
|
||||||
|
"created_at": "2024-06-22T10:00:00Z",
|
||||||
|
"updated_at": "2024-06-22T10:00:00Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Forward Types**:
|
||||||
|
- **Local**: `ssh -L localPort:remoteHost:remotePort` — forward local port to remote
|
||||||
|
- **Remote**: `ssh -R remotePort:localHost:localPort` — forward remote port to local
|
||||||
|
- **Dynamic**: `ssh -D localPort` — SOCKS5 proxy through SSH
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.5 Workspace
|
||||||
|
|
||||||
|
Group multiple terminal sessions in a layout.
|
||||||
|
|
||||||
|
```go
|
||||||
|
type Workspace struct {
|
||||||
|
ID string `json:"id" bson:"_id,omitempty"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Layout string `json:"layout"` // "single", "split-h", "split-v", "grid-2x2"
|
||||||
|
Tabs []Tab `json:"tabs"` // terminal tabs in this workspace
|
||||||
|
IsActive bool `json:"is_active"` // currently active workspace
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Tab struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
HostID string `json:"host_id"`
|
||||||
|
Type string `json:"type"` // "terminal", "sftp"
|
||||||
|
Title string `json:"title"` // display title (host name)
|
||||||
|
Cols int `json:"cols"`
|
||||||
|
Rows int `json:"rows"`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Storage**: `workspaces.json`
|
||||||
|
|
||||||
|
**Layout Types**:
|
||||||
|
- `single` — one terminal, full width
|
||||||
|
- `split-h` — two terminals side by side (horizontal split)
|
||||||
|
- `split-v` — two terminals stacked (vertical split)
|
||||||
|
- `grid-2x2` — four terminals in a 2x2 grid
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.6 Session (Runtime only, not persisted)
|
||||||
|
|
||||||
|
Active terminal session tracking.
|
||||||
|
|
||||||
|
```go
|
||||||
|
type Session struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
HostID string `json:"host_id"`
|
||||||
|
StartedAt time.Time `json:"started_at"`
|
||||||
|
LastActive time.Time `json:"last_active"`
|
||||||
|
Status string `json:"status"` // "connecting", "connected", "disconnected", "error"
|
||||||
|
Cols int `json:"cols"`
|
||||||
|
Rows int `json:"rows"`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note**: Sessions are in-memory only. Not stored to disk.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.7 VaultStatus (Runtime only)
|
||||||
|
|
||||||
|
Vault lock/unlock state tracking.
|
||||||
|
|
||||||
|
```go
|
||||||
|
type VaultStatus struct {
|
||||||
|
Locked bool `json:"locked"`
|
||||||
|
EncryptionEnabled bool `json:"encryption_enabled"`
|
||||||
|
AutoLockEnabled bool `json:"auto_lock_enabled"`
|
||||||
|
AutoLockMinutes int `json:"auto_lock_minutes"`
|
||||||
|
LastActivity time.Time `json:"last_activity"`
|
||||||
|
UnlockAttempts int `json:"unlock_attempts"` // failed attempts
|
||||||
|
LockedUntil *time.Time `json:"locked_until,omitempty"` // temporary lock after too many attempts
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Auto-lock rules**:
|
||||||
|
- Default: lock after 5 minutes of inactivity
|
||||||
|
- After 5 failed unlock attempts: temporary lock for 30 seconds
|
||||||
|
- Lock on system sleep/suspend
|
||||||
|
- Lock on window minimize (configurable)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Storage Schema
|
||||||
|
|
||||||
|
### File Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
~/.hostkeeper/
|
||||||
|
├── hosts.json # V1 + V2 host data
|
||||||
|
├── keys.json # V1 + V2 key pairs
|
||||||
|
├── snippets.json # V1 + V2 snippets
|
||||||
|
├── groups.json # V2: host groups
|
||||||
|
├── forwards.json # V2: port forwards
|
||||||
|
├── workspaces.json # V2: workspaces
|
||||||
|
├── config.json # V1 + V2 app config
|
||||||
|
├── known_hosts.json # V1 + V2 known hosts
|
||||||
|
├── profiles.json # V2: profiles (if separated from config)
|
||||||
|
└── sessions.json # V2: session history (optional)
|
||||||
|
```
|
||||||
|
|
||||||
|
### JSON Schema Examples
|
||||||
|
|
||||||
|
#### hosts.json (extended)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"hosts": [
|
||||||
|
{
|
||||||
|
"id": "550e8400-e29b-41d4-a716-446655440000",
|
||||||
|
"name": "Production Server",
|
||||||
|
"hostname": "192.168.1.100",
|
||||||
|
"port": 22,
|
||||||
|
"username": "admin",
|
||||||
|
"auth": {
|
||||||
|
"type": "key",
|
||||||
|
"key_id": "key-uuid"
|
||||||
|
},
|
||||||
|
"group_id": "group-uuid",
|
||||||
|
"tags": ["production", "linux"],
|
||||||
|
"is_favorite": true,
|
||||||
|
"color": "#e78a4e",
|
||||||
|
"order": 0,
|
||||||
|
"notes": "Main production server",
|
||||||
|
"startup_snippets": ["snippet-uuid-1"],
|
||||||
|
"proxy": {
|
||||||
|
"type": "socks5",
|
||||||
|
"host": "10.0.0.1",
|
||||||
|
"port": 1080
|
||||||
|
},
|
||||||
|
"jump_host_id": "jump-host-uuid",
|
||||||
|
"keepalive": 60,
|
||||||
|
"created_at": "2024-06-22T10:00:00Z",
|
||||||
|
"updated_at": "2024-06-22T10:00:00Z",
|
||||||
|
"last_used_at": "2024-06-22T15:30:00Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### groups.json
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"groups": [
|
||||||
|
{
|
||||||
|
"id": "550e8400-e29b-41d4-a716-446655440000",
|
||||||
|
"name": "Production",
|
||||||
|
"parent_id": null,
|
||||||
|
"color": "#e78a4e",
|
||||||
|
"icon": "server",
|
||||||
|
"order": 0,
|
||||||
|
"created_at": "2024-06-22T10:00:00Z",
|
||||||
|
"updated_at": "2024-06-22T10:00:00Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "660e8400-e29b-41d4-a716-446655440001",
|
||||||
|
"name": "Web Servers",
|
||||||
|
"parent_id": "550e8400-e29b-41d4-a716-446655440000",
|
||||||
|
"color": "#a9b665",
|
||||||
|
"icon": "globe",
|
||||||
|
"order": 0,
|
||||||
|
"created_at": "2024-06-22T10:00:00Z",
|
||||||
|
"updated_at": "2024-06-22T10:00:00Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### forwards.json
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"forwards": [
|
||||||
|
{
|
||||||
|
"id": "forward-uuid",
|
||||||
|
"name": "Local Redis",
|
||||||
|
"host_id": "host-uuid",
|
||||||
|
"type": "local",
|
||||||
|
"local_addr": "127.0.0.1:6379",
|
||||||
|
"remote_addr": "localhost:6379",
|
||||||
|
"status": "stopped",
|
||||||
|
"auto_start": false,
|
||||||
|
"created_at": "2024-06-22T10:00:00Z",
|
||||||
|
"updated_at": "2024-06-22T10:00:00Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Relationships
|
||||||
|
|
||||||
|
```
|
||||||
|
HostGroup (1) ──── (*) Host
|
||||||
|
│ │
|
||||||
|
│ parent_id │ group_id
|
||||||
|
│ (self-ref) │ key_id
|
||||||
|
│ │ startup_snippets (*)
|
||||||
|
│ │ jump_host_id
|
||||||
|
│ │
|
||||||
|
HostGroup (1) ──── (*) HostGroup (children)
|
||||||
|
│
|
||||||
|
└── max depth: 5
|
||||||
|
|
||||||
|
Host (1) ──── (*) PortForward
|
||||||
|
│
|
||||||
|
└── host_id
|
||||||
|
|
||||||
|
Workspace (1) ──── (*) Tab
|
||||||
|
│
|
||||||
|
└── tabs[].host_id
|
||||||
|
|
||||||
|
Host (1) ──── (*) Snippet (via startup_snippets)
|
||||||
|
│
|
||||||
|
└── startup_snippets[] = snippet IDs
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Migration from V1
|
||||||
|
|
||||||
|
V2 data is backward-compatible with V1. New fields are optional (`omitempty`).
|
||||||
|
|
||||||
|
**Migration steps** (automatic on first V2 launch):
|
||||||
|
1. Read existing `hosts.json` — V2 fields default to zero values
|
||||||
|
2. Create `groups.json` if not exists — empty groups
|
||||||
|
3. Create `forwards.json` if not exists — empty forwards
|
||||||
|
4. Create `workspaces.json` if not exists — empty workspaces
|
||||||
|
5. Update `config.json` — add V2 config fields
|
||||||
|
|
||||||
|
**No data loss**: V1 data is preserved. V2 fields are additive.
|
||||||
@@ -0,0 +1,709 @@
|
|||||||
|
# Hostkeeper V2 — Performance & Stability
|
||||||
|
|
||||||
|
> **Status**: V2 Planning Complete
|
||||||
|
> **Last Updated**: 2026-06-29
|
||||||
|
> **Goal**: "Tidak lemot dan bisa stabil digunakan" — fast, responsive, zero crashes.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Performance Targets
|
||||||
|
|
||||||
|
| Metric | Target | How to Measure |
|
||||||
|
|--------|--------|----------------|
|
||||||
|
| App startup | < 2 seconds | Electron ready → UI visible |
|
||||||
|
| API response | < 50ms | Time from request to response |
|
||||||
|
| Terminal latency | < 10ms | Keystroke → character appears |
|
||||||
|
| SFTP listing | < 500ms | Directory load time |
|
||||||
|
| Memory usage | < 200 MB | Steady state (10 tabs open) |
|
||||||
|
| CPU usage | < 5% | Idle state |
|
||||||
|
| Scroll (1000 hosts) | 60 fps | No jank during scroll |
|
||||||
|
| SSH reconnect | < 3 seconds | Auto-reconnect after disconnect |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Go Backend Performance
|
||||||
|
|
||||||
|
### 2.1 GoFiber Configuration
|
||||||
|
|
||||||
|
```go
|
||||||
|
app := fiber.New(fiber.Config{
|
||||||
|
// Timeouts (prevent hung connections)
|
||||||
|
ReadTimeout: 30 * time.Second,
|
||||||
|
WriteTimeout: 30 * time.Second,
|
||||||
|
IdleTimeout: 120 * time.Second,
|
||||||
|
|
||||||
|
// Concurrency (limit goroutines)
|
||||||
|
Concurrency: 256,
|
||||||
|
|
||||||
|
// Body limit (prevent large payload attacks)
|
||||||
|
BodyLimit: 10 * 1024 * 1024, // 10MB
|
||||||
|
|
||||||
|
// Buffer sizes (optimize for typical requests)
|
||||||
|
ReadBufferSize: 4096,
|
||||||
|
WriteBufferSize: 4096,
|
||||||
|
|
||||||
|
// Disable startup banner
|
||||||
|
DisableStartupMessage: false,
|
||||||
|
|
||||||
|
// JSON encoder (fastest)
|
||||||
|
JSONEncoder: json.Marshal,
|
||||||
|
JSONDecoder: json.Unmarshal,
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 Connection Pooling (SSH)
|
||||||
|
|
||||||
|
```go
|
||||||
|
// app/backend/ws/pool.go
|
||||||
|
type SessionPool struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
sessions map[string]*pooledSession // key: hostID
|
||||||
|
maxIdle time.Duration
|
||||||
|
maxSize int
|
||||||
|
}
|
||||||
|
|
||||||
|
type pooledSession struct {
|
||||||
|
client *ssh.Client
|
||||||
|
lastUsed time.Time
|
||||||
|
refCount int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSessionPool(maxSize int, maxIdle time.Duration) *SessionPool {
|
||||||
|
pool := &SessionPool{
|
||||||
|
sessions: make(map[string]*pooledSession),
|
||||||
|
maxIdle: maxIdle,
|
||||||
|
maxSize: maxSize,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cleanup goroutine: close idle connections
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(30 * time.Second)
|
||||||
|
for range ticker.C {
|
||||||
|
pool.cleanup()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *SessionPool) Get(hostID string) (*pooledSession, error) {
|
||||||
|
p.mu.RLock()
|
||||||
|
sess, exists := p.sessions[hostID]
|
||||||
|
p.mu.RUnlock()
|
||||||
|
|
||||||
|
if exists {
|
||||||
|
sess.lastUsed = time.Now()
|
||||||
|
sess.refCount++
|
||||||
|
return sess, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create new connection
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
|
||||||
|
// Double-check after acquiring write lock
|
||||||
|
if sess, exists := p.sessions[hostID]; exists {
|
||||||
|
sess.lastUsed = time.Now()
|
||||||
|
sess.refCount++
|
||||||
|
return sess, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Evict if at capacity
|
||||||
|
if len(p.sessions) >= p.maxSize {
|
||||||
|
p.evictOldest()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create new session
|
||||||
|
host, err := storage.GetHost(context.Background(), hostID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
client := ssh.NewClient(host, 30*time.Second)
|
||||||
|
if err := client.Connect(context.Background()); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
sess = &pooledSession{
|
||||||
|
client: client,
|
||||||
|
lastUsed: time.Now(),
|
||||||
|
refCount: 1,
|
||||||
|
}
|
||||||
|
p.sessions[hostID] = sess
|
||||||
|
|
||||||
|
return sess, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *SessionPool) Put(hostID string) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
|
||||||
|
if sess, exists := p.sessions[hostID]; exists {
|
||||||
|
sess.refCount--
|
||||||
|
if sess.refCount <= 0 {
|
||||||
|
// Don't close immediately — keep for reuse
|
||||||
|
sess.refCount = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *SessionPool) cleanup() {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
|
||||||
|
for key, sess := range p.sessions {
|
||||||
|
if sess.refCount == 0 && time.Since(sess.lastUsed) > p.maxIdle {
|
||||||
|
sess.client.Close()
|
||||||
|
delete(p.sessions, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 Buffer Pooling
|
||||||
|
|
||||||
|
```go
|
||||||
|
// app/backend/ws/buffers.go
|
||||||
|
var bufferPool = sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
buf := make([]byte, 4096)
|
||||||
|
return &buf
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetBuffer() *[]byte {
|
||||||
|
return bufferPool.Get().(*[]byte)
|
||||||
|
}
|
||||||
|
|
||||||
|
func PutBuffer(buf *[]byte) {
|
||||||
|
// Reset buffer
|
||||||
|
(*buf) = (*buf)[:0]
|
||||||
|
bufferPool.Put(buf)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.4 Goroutine Management
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Limit concurrent SSH sessions
|
||||||
|
var sshSemaphore = make(chan struct{}, 50) // max 50 concurrent sessions
|
||||||
|
|
||||||
|
func handleTerminal(c *websocket.Conn) {
|
||||||
|
// Acquire semaphore
|
||||||
|
select {
|
||||||
|
case sshSemaphore <- struct{}{}:
|
||||||
|
defer func() { <-sshSemaphore }()
|
||||||
|
default:
|
||||||
|
c.WriteJSON(fiber.Map{
|
||||||
|
"type": "error",
|
||||||
|
"message": "Too many connections",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// ... handle session
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Frontend Performance
|
||||||
|
|
||||||
|
### 3.1 Code Splitting (Lazy Loading)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// app/frontend/src/router.tsx
|
||||||
|
import { lazy, Suspense } from 'react';
|
||||||
|
|
||||||
|
const HostListScreen = lazy(() => import('./screens/HostListScreen'));
|
||||||
|
const TerminalScreen = lazy(() => import('./screens/TerminalScreen'));
|
||||||
|
const SFTPScreen = lazy(() => import('./screens/SFTPScreen'));
|
||||||
|
const SettingsScreen = lazy(() => import('./screens/SettingsScreen'));
|
||||||
|
|
||||||
|
const router = createBrowserRouter([
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
element: <MainLayout />,
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
index: true,
|
||||||
|
element: (
|
||||||
|
<Suspense fallback={<LoadingSpinner />}>
|
||||||
|
<HostListScreen />
|
||||||
|
</Suspense>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
// ... other routes
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 Virtual Scrolling (Host List)
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// app/frontend/src/components/VirtualList.tsx
|
||||||
|
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||||
|
|
||||||
|
interface VirtualListProps<T> {
|
||||||
|
items: T[];
|
||||||
|
renderItem: (item: T) => React.ReactNode;
|
||||||
|
estimateSize?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function VirtualList<T>({ items, renderItem, estimateSize = 48 }: VirtualListProps<T>) {
|
||||||
|
const parentRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
const virtualizer = useVirtualizer({
|
||||||
|
count: items.length,
|
||||||
|
getScrollElement: () => parentRef.current,
|
||||||
|
estimateSize: () => estimateSize,
|
||||||
|
overscan: 10, // Render 10 items outside viewport
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={parentRef} className="h-full overflow-auto">
|
||||||
|
<div style={{ height: virtualizer.getTotalSize() }}>
|
||||||
|
{virtualizer.getVirtualItems().map(virtualRow => (
|
||||||
|
<div
|
||||||
|
key={virtualRow.key}
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
top: virtualRow.start,
|
||||||
|
height: virtualRow.size,
|
||||||
|
width: '100%',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{renderItem(items[virtualRow.index])}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.3 React.memo for Expensive Components
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Prevent re-render when props haven't changed
|
||||||
|
const HostItem = React.memo(function HostItem({ host, isActive, onClick }: HostItemProps) {
|
||||||
|
return (
|
||||||
|
<div onClick={onClick}>
|
||||||
|
{/* ... */}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}, (prev, next) => {
|
||||||
|
return prev.host.id === next.host.id
|
||||||
|
&& prev.isActive === next.isActive;
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.4 useMemo for Expensive Computations
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function HostList({ hosts, filter }: { hosts: Host[]; filter: string }) {
|
||||||
|
const filteredHosts = useMemo(() => {
|
||||||
|
if (!filter) return hosts;
|
||||||
|
return hosts.filter(h =>
|
||||||
|
h.name.toLowerCase().includes(filter.toLowerCase()) ||
|
||||||
|
h.hostname.toLowerCase().includes(filter.toLowerCase())
|
||||||
|
);
|
||||||
|
}, [hosts, filter]);
|
||||||
|
|
||||||
|
return <VirtualList items={filteredHosts} renderItem={renderHostItem} />;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.5 useCallback for Event Handlers
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function HostItem({ host, onSelect }: { host: Host; onSelect: (id: string) => void }) {
|
||||||
|
const handleClick = useCallback(() => {
|
||||||
|
onSelect(host.id);
|
||||||
|
}, [host.id, onSelect]);
|
||||||
|
|
||||||
|
return <div onClick={handleClick}>{/* ... */}</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.6 Zustand Selector Optimization
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Bad: re-renders on ANY store change
|
||||||
|
const hosts = useHostStore(state => state.hosts);
|
||||||
|
|
||||||
|
// Good: only re-renders when hosts change
|
||||||
|
const hosts = useHostStore(state => state.hosts);
|
||||||
|
|
||||||
|
// Good: only re-renders when selectedHost changes
|
||||||
|
const selectedId = useHostStore(state => state.selectedHost);
|
||||||
|
|
||||||
|
// Good: granular selector
|
||||||
|
const hostName = useHostStore(state => {
|
||||||
|
const host = state.hosts.find(h => h.id === state.selectedHost);
|
||||||
|
return host?.name;
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. WebSocket Stability
|
||||||
|
|
||||||
|
### 4.1 Keepalive
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Client side (React)
|
||||||
|
class TerminalWebSocket {
|
||||||
|
private ws: WebSocket;
|
||||||
|
private pingInterval: NodeJS.Timeout;
|
||||||
|
|
||||||
|
connect(url: string) {
|
||||||
|
this.ws = new WebSocket(url);
|
||||||
|
|
||||||
|
// Send ping every 30 seconds
|
||||||
|
this.pingInterval = setInterval(() => {
|
||||||
|
if (this.ws.readyState === WebSocket.OPEN) {
|
||||||
|
this.ws.send(new Uint8Array([0])); // ping frame
|
||||||
|
}
|
||||||
|
}, 30000);
|
||||||
|
}
|
||||||
|
|
||||||
|
disconnect() {
|
||||||
|
clearInterval(this.pingInterval);
|
||||||
|
this.ws.close(1000, 'Client closing');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Server side (Go)
|
||||||
|
func handleTerminal(c *websocket.Conn) {
|
||||||
|
// Set pong handler
|
||||||
|
c.SetPongHandler(func(string) error {
|
||||||
|
c.SetReadDeadline(time.Now().Add(60 * time.Second))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
// Read loop (detects disconnect)
|
||||||
|
for {
|
||||||
|
_, _, err := c.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 Auto-Reconnect
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// app/frontend/src/hooks/useTerminalReconnect.ts
|
||||||
|
function useTerminalReconnect(ws: TerminalWebSocket) {
|
||||||
|
const [reconnectAttempts, setReconnectAttempts] = useState(0);
|
||||||
|
const maxReconnectAttempts = 5;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (ws.status === 'disconnected' && reconnectAttempts < maxReconnectAttempts) {
|
||||||
|
const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
setReconnectAttempts(prev => prev + 1);
|
||||||
|
ws.reconnect();
|
||||||
|
}, delay);
|
||||||
|
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}, [ws.status, reconnectAttempts]);
|
||||||
|
|
||||||
|
return { reconnectAttempts, maxReconnectAttempts };
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Error Boundaries
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// app/frontend/src/components/ErrorBoundary.tsx
|
||||||
|
class ErrorBoundary extends React.Component {
|
||||||
|
state = { hasError: false, error: null };
|
||||||
|
|
||||||
|
static getDerivedStateFromError(error: Error) {
|
||||||
|
return { hasError: true, error };
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidCatch(error: Error, info: React.ErrorInfo) {
|
||||||
|
console.error('Terminal error:', error, info);
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (this.state.hasError) {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center justify-center h-full">
|
||||||
|
<AlertTriangle className="h-12 w-12 text-yellow-500 mb-4" />
|
||||||
|
<h2 className="text-lg font-semibold mb-2">Something went wrong</h2>
|
||||||
|
<Button onClick={() => window.location.reload()}>
|
||||||
|
Reload
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return this.props.children;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Memory Management
|
||||||
|
|
||||||
|
### 5.1 Terminal Cleanup
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function XTermWrapper({ tabId }: { tabId: string }) {
|
||||||
|
useEffect(() => {
|
||||||
|
const term = new Terminal({
|
||||||
|
scrollback: 10000, // Limit scrollback buffer
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
term.dispose(); // Free memory on unmount
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 WebSocket Cleanup
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
useEffect(() => {
|
||||||
|
const ws = new WebSocket(url);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
ws.close(); // Close on unmount
|
||||||
|
};
|
||||||
|
}, [hostId]);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 Image/Icon Lazy Loading
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Only load icons when needed
|
||||||
|
const Icon = lazy(() => import('./Icon'));
|
||||||
|
|
||||||
|
// Or use intersection observer
|
||||||
|
function LazyIcon({ name }: { name: string }) {
|
||||||
|
const [loaded, setLoaded] = useState(false);
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const observer = new IntersectionObserver(([entry]) => {
|
||||||
|
if (entry.isIntersecting) {
|
||||||
|
setLoaded(true);
|
||||||
|
observer.disconnect();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (ref.current) observer.observe(ref.current);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return <div ref={ref}>{loaded && <Icon name={name} />}</div>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Crash Recovery
|
||||||
|
|
||||||
|
### 6.1 Go Panic Recovery
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Already built into GoFiber
|
||||||
|
app.Use(recover.New())
|
||||||
|
|
||||||
|
// Custom panic handler
|
||||||
|
app.Use(recover.New(recover.Config{
|
||||||
|
Handler: func(c *fiber.Ctx, err error) {
|
||||||
|
log.Printf("PANIC: %v\n%s", err, debug.Stack())
|
||||||
|
c.Status(500).JSON(fiber.Map{
|
||||||
|
"error": "Internal server error",
|
||||||
|
"code": "PANIC",
|
||||||
|
})
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 Electron Crash Reporter
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// app/electron/main.ts
|
||||||
|
import { crashReporter } from 'electron';
|
||||||
|
|
||||||
|
crashReporter.start({
|
||||||
|
productName: 'Hostkeeper',
|
||||||
|
submitURL: '', // No remote reporting (privacy)
|
||||||
|
uploadToServer: false,
|
||||||
|
compress: true,
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.3 State Persistence
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Save critical state to localStorage
|
||||||
|
window.addEventListener('beforeunload', () => {
|
||||||
|
const state = {
|
||||||
|
sidebarWidth: useUIStore.getState().sidebarWidth,
|
||||||
|
activeTab: useTabStore.getState().activeTab,
|
||||||
|
theme: useUIStore.getState().theme,
|
||||||
|
};
|
||||||
|
localStorage.setItem('hostkeeper-ui-state', JSON.stringify(state));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Restore on load
|
||||||
|
const savedState = localStorage.getItem('hostkeeper-ui-state');
|
||||||
|
if (savedState) {
|
||||||
|
const state = JSON.parse(savedState);
|
||||||
|
useUIStore.getState().setSidebarWidth(state.sidebarWidth);
|
||||||
|
useUIStore.getState().setTheme(state.theme);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Logging
|
||||||
|
|
||||||
|
### 7.1 Structured Logging (Go)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "github.com/gofiber/fiber/v2/log"
|
||||||
|
|
||||||
|
// Request logging (built into GoFiber)
|
||||||
|
app.Use(logger.New(logger.Config{
|
||||||
|
Format: "${time} ${method} ${path} ${status} ${latency}\n",
|
||||||
|
Done: func(c *fiber.Ctx, log string) {
|
||||||
|
// Custom log processing
|
||||||
|
if c.Response().StatusCode() >= 500 {
|
||||||
|
log.Error(log)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Application logging
|
||||||
|
log.Info("Server started on port", port)
|
||||||
|
log.Warn("Connection pool full")
|
||||||
|
log.Error("SSH connection failed", err)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 Frontend Logging
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Only log in development
|
||||||
|
const logger = {
|
||||||
|
info: (...args: any[]) => {
|
||||||
|
if (import.meta.env.DEV) console.log('[INFO]', ...args);
|
||||||
|
},
|
||||||
|
warn: (...args: any[]) => {
|
||||||
|
if (import.meta.env.DEV) console.warn('[WARN]', ...args);
|
||||||
|
},
|
||||||
|
error: (...args: any[]) => {
|
||||||
|
console.error('[ERROR]', ...args); // Always log errors
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Monitoring
|
||||||
|
|
||||||
|
### 8.1 Health Check Endpoint
|
||||||
|
|
||||||
|
```go
|
||||||
|
app.Get("/api/health", func(c *fiber.Ctx) error {
|
||||||
|
return c.JSON(fiber.Map{
|
||||||
|
"status": "ok",
|
||||||
|
"version": version,
|
||||||
|
"uptime": time.Since(startTime).Seconds(),
|
||||||
|
"connections": sessionPool.ActiveCount(),
|
||||||
|
"memory": getMemoryUsage(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 Metrics (Optional)
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Simple metrics middleware
|
||||||
|
var (
|
||||||
|
requestCount = prometheus.NewCounter("requests_total")
|
||||||
|
requestLatency = prometheus.NewHistogram("request_latency_seconds")
|
||||||
|
)
|
||||||
|
|
||||||
|
app.Use(func(c *fiber.Ctx) error {
|
||||||
|
start := time.Now()
|
||||||
|
err := c.Next()
|
||||||
|
duration := time.Since(start).Seconds()
|
||||||
|
|
||||||
|
requestCount.Inc()
|
||||||
|
requestLatency.Observe(duration)
|
||||||
|
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Testing for Performance
|
||||||
|
|
||||||
|
### 9.1 Load Testing (Go)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Install hey (HTTP load testing)
|
||||||
|
go install github.com/rakyll/hey@latest
|
||||||
|
|
||||||
|
# Test API endpoints
|
||||||
|
hey -n 1000 -c 50 http://localhost:8080/api/hosts
|
||||||
|
hey -n 1000 -c 50 http://localhost:8080/api/keys
|
||||||
|
hey -n 1000 -c 50 http://localhost:8080/api/snippets
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9.2 Terminal Latency Test
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Measure keystroke to display latency
|
||||||
|
function measureTerminalLatency(term: Terminal): number {
|
||||||
|
const start = performance.now();
|
||||||
|
term.write('x'); // Write character
|
||||||
|
// Measure time until character is rendered
|
||||||
|
return performance.now() - start;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 9.3 Memory Profiling
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "runtime"
|
||||||
|
|
||||||
|
// Log memory usage
|
||||||
|
var memStats runtime.MemStats
|
||||||
|
runtime.ReadMemStats(&memStats)
|
||||||
|
log.Printf("Memory: %d MB allocated, %d MB sys",
|
||||||
|
memStats.Alloc/1024/1024,
|
||||||
|
memStats.Sys/1024/1024,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Common Performance Pitfalls
|
||||||
|
|
||||||
|
| Issue | Symptom | Fix |
|
||||||
|
|-------|---------|-----|
|
||||||
|
| Memory leak in terminals | Memory grows over time | Dispose terminals on unmount |
|
||||||
|
| WebSocket not closing | Connections pile up | Close on component unmount |
|
||||||
|
| Large JSON responses | Slow API | Pagination, field filtering |
|
||||||
|
| No connection pooling | Slow SSH reconnect | Use SessionPool |
|
||||||
|
| Synchronous SFTP | UI freezes | Use goroutines + channels |
|
||||||
|
| Re-render storms | Jank, low FPS | React.memo, useMemo, Zustand selectors |
|
||||||
|
| No code splitting | Slow initial load | Lazy load screens |
|
||||||
|
| Oversized bundles | Slow startup | Tree shaking, purging |
|
||||||
@@ -0,0 +1,339 @@
|
|||||||
|
# Hostkeeper V2 — Progress Tracker
|
||||||
|
|
||||||
|
> **Purpose**: Enable seamless continuation of development by any agent/LLM across sessions.
|
||||||
|
> **How to use**: Read this file first. Find the first unchecked `[ ]` item. That's where you continue.
|
||||||
|
> **Last Updated**: 2026-06-29
|
||||||
|
> **Status**: Planning complete, implementation not started.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Overview
|
||||||
|
|
||||||
|
Hostkeeper V2 is a Termius-like cross-platform SSH/SFTP management GUI application.
|
||||||
|
|
||||||
|
| Item | Value |
|
||||||
|
|------|-------|
|
||||||
|
| **Goal** | Build a free, open-source Termius alternative with full feature parity |
|
||||||
|
| **Desktop** | GoFiber backend + React/xterm.js UI + Electron wrapper |
|
||||||
|
| **Mobile** | Go mobile library + WebView wrapper (Android/iOS) |
|
||||||
|
| **Backend language** | Go 1.26 |
|
||||||
|
| **HTTP framework** | GoFiber v2 (fasthttp-based) |
|
||||||
|
| **Frontend** | React 19, TypeScript, xterm.js, Zustand, Vite |
|
||||||
|
| **Desktop wrapper** | Electron (electron-builder) |
|
||||||
|
| **Mobile wrapper** | gomobile + WebView |
|
||||||
|
| **V1 (existing)** | CLI/TUI SSH/SFTP manager — 105 tests, all passing. Frozen. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Current Status Summary
|
||||||
|
|
||||||
|
| Item | Status |
|
||||||
|
|------|--------|
|
||||||
|
| Planning documents | DONE |
|
||||||
|
| Sprint 0 — Scaffolding | NOT STARTED |
|
||||||
|
| Sprint 1 — Foundation | NOT STARTED |
|
||||||
|
| Sprint 2 — Core Features | NOT STARTED |
|
||||||
|
| Sprint 3 — SFTP + Polish | NOT STARTED |
|
||||||
|
| Sprint 4 — Advanced | NOT STARTED |
|
||||||
|
| Sprint 5 — Platform Polish | NOT STARTED |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Sprint Checklist
|
||||||
|
|
||||||
|
### Sprint 0 — Project Scaffolding (Day 0)
|
||||||
|
- [ ] Create `app/backend/` directory with Go module (`go mod init`)
|
||||||
|
- [ ] Install GoFiber v2 + dependencies in `go.mod`
|
||||||
|
- [ ] Create `app/backend/main.go` — minimal fiber server (port 0 for random)
|
||||||
|
- [ ] Create `app/frontend/` with Vite + React + TypeScript
|
||||||
|
- [ ] Create `app/electron/` with Electron shell
|
||||||
|
- [ ] Electron spawns Go backend as child process on startup
|
||||||
|
- [ ] Electron loads web UI from localhost (Go serve frontend dist)
|
||||||
|
- [ ] Create `app/backend/middleware/` — CORS, logging, recover, compress
|
||||||
|
- [ ] Create `app/backend/bridge/` directory (placeholder handlers)
|
||||||
|
- [ ] Create `app/backend/ws/` directory (placeholder handlers)
|
||||||
|
- [ ] Build script: `scripts/build.sh` — Go build → frontend build → Electron package
|
||||||
|
- [ ] Verify: `npm run dev` opens Electron window with "Hostkeeper V2" title
|
||||||
|
- [ ] Verify: Go server responds at `localhost:PORT/api/health`
|
||||||
|
|
||||||
|
### Sprint 1 — Foundation (Day 1-5)
|
||||||
|
|
||||||
|
#### Day 1-2: Data API Layer
|
||||||
|
- [ ] `app/backend/bridge/hosts.go` — GET /api/hosts (list, filter, search)
|
||||||
|
- [ ] `app/backend/bridge/hosts.go` — POST /api/hosts (create)
|
||||||
|
- [ ] `app/backend/bridge/hosts.go` — GET /api/hosts/:id (detail)
|
||||||
|
- [ ] `app/backend/bridge/hosts.go` — PUT /api/hosts/:id (update)
|
||||||
|
- [ ] `app/backend/bridge/hosts.go` — DELETE /api/hosts/:id (delete)
|
||||||
|
- [ ] `app/backend/bridge/hosts.go` — PATCH /api/hosts/:id/favorite (toggle)
|
||||||
|
- [ ] `app/backend/bridge/keys.go` — GET /api/keys (list, no private key)
|
||||||
|
- [ ] `app/backend/bridge/keys.go` — POST /api/keys (import)
|
||||||
|
- [ ] `app/backend/bridge/keys.go` — POST /api/keys/generate (generate new)
|
||||||
|
- [ ] `app/backend/bridge/keys.go` — DELETE /api/keys/:id (delete)
|
||||||
|
- [ ] `app/backend/bridge/snippets.go` — GET /api/snippets (list)
|
||||||
|
- [ ] `app/backend/bridge/snippets.go` — POST /api/snippets (create)
|
||||||
|
- [ ] `app/backend/bridge/snippets.go` — PUT /api/snippets/:id (update)
|
||||||
|
- [ ] `app/backend/bridge/snippets.go` — DELETE /api/snippets/:id (delete)
|
||||||
|
- [ ] JSON error responses: `{ "error": "message" }` with proper HTTP codes
|
||||||
|
- [ ] Verify: `curl -X POST http://localhost:PORT/api/hosts` returns 201
|
||||||
|
|
||||||
|
#### Day 3: Groups + Config API
|
||||||
|
- [ ] `app/backend/bridge/groups.go` — GET /api/groups (tree structure)
|
||||||
|
- [ ] `app/backend/bridge/groups.go` — POST /api/groups (create)
|
||||||
|
- [ ] `app/backend/bridge/groups.go` — PUT /api/groups/:id (update)
|
||||||
|
- [ ] `app/backend/bridge/groups.go` — DELETE /api/groups/:id (delete)
|
||||||
|
- [ ] `app/backend/bridge/groups.go` — PUT /api/groups/:id/move (reparent)
|
||||||
|
- [ ] `app/backend/bridge/config.go` — GET /api/config (app config)
|
||||||
|
- [ ] `app/backend/bridge/config.go` — PUT /api/config (update config)
|
||||||
|
- [ ] `app/backend/bridge/config.go` — POST /api/config/unlock (vault unlock)
|
||||||
|
- [ ] `app/backend/bridge/config.go` — POST /api/config/lock (vault lock)
|
||||||
|
- [ ] `app/backend/bridge/config.go` — GET /api/config/status (vault status)
|
||||||
|
- [ ] Verify: Full CRUD cycle via curl for all endpoints
|
||||||
|
|
||||||
|
#### Day 4: Web UI Scaffold
|
||||||
|
- [ ] React Router setup — routes for all screens (placeholder)
|
||||||
|
- [ ] Layout component — Sidebar + TabBar + MainContent + StatusBar
|
||||||
|
- [ ] Sidebar component — GroupTree (recursive), SearchBar, QuickActions
|
||||||
|
- [ ] Theme system — CSS variables (dark, light, high-contrast)
|
||||||
|
- [ ] API client layer — fetch wrapper + error handling + retry logic
|
||||||
|
- [ ] State management — Zustand stores (hosts, keys, snippets, ui, terminal)
|
||||||
|
- [ ] Keyboard shortcuts — Cmd+N new host, Cmd+K search, Cmd+D dark mode
|
||||||
|
- [ ] Verify: Navigation between screens works
|
||||||
|
|
||||||
|
#### Day 5: Host List Screen
|
||||||
|
- [ ] HostList screen — HostCard components (grid + list view toggle)
|
||||||
|
- [ ] GroupTree — collapsible, recursive, drag-and-drop (host -> group)
|
||||||
|
- [ ] Search — filter by name, hostname, tag
|
||||||
|
- [ ] Tag filter bar — chips for each tag, click to filter
|
||||||
|
- [ ] Favorite toggle — star icon, filter favorites only
|
||||||
|
- [ ] Context menu — right-click: connect, edit, delete, duplicate
|
||||||
|
- [ ] Empty state — illustration + "Add your first host" CTA
|
||||||
|
- [ ] Loading skeleton states
|
||||||
|
- [ ] Verify: Host appears in list, can search, can filter, can favorite
|
||||||
|
|
||||||
|
### Sprint 2 — Core Features (Day 6-10)
|
||||||
|
|
||||||
|
#### Day 6-7: Host Form + CRUD UI
|
||||||
|
- [ ] HostForm screen — add mode + edit mode
|
||||||
|
- [ ] Basic info fields — name, hostname, port, username
|
||||||
|
- [ ] Auth section — type selector (password/key/agent)
|
||||||
|
- [ ] Password field — show/hide toggle, strength indicator
|
||||||
|
- [ ] Key picker — dropdown from stored keys
|
||||||
|
- [ ] TagsInput — type + Enter to add, backspace to remove, autocomplete
|
||||||
|
- [ ] GroupPicker — tree picker component
|
||||||
|
- [ ] Advanced settings — proxy, jump host, keepalive interval
|
||||||
|
- [ ] Validation — required fields, hostname regex, port range 1-65535
|
||||||
|
- [ ] Error display — inline validation + toast notifications
|
||||||
|
- [ ] Keyboard shortcuts — Cmd+S save, Esc cancel, Tab next field
|
||||||
|
- [ ] Verify: Create host -> appears in list -> edit -> update -> delete
|
||||||
|
|
||||||
|
#### Day 8-10: SSH Terminal (MOST CRITICAL)
|
||||||
|
- [ ] **Go: WebSocket handler** `app/backend/ws/terminal.go`
|
||||||
|
- [ ] Accept WS connection with host_id + cols + rows query params
|
||||||
|
- [ ] Lookup host from storage by ID
|
||||||
|
- [ ] Create `ssh.Client` using `pkg/ssh` (reuse existing)
|
||||||
|
- [ ] Request PTY with xterm-256color
|
||||||
|
- [ ] Stream SSH stdout -> WS binary frames (`c.WriteMessage`)
|
||||||
|
- [ ] Receive WS frames -> SSH stdin (`session.Stdin.Write`)
|
||||||
|
- [ ] Handle resize messages — JSON control frames
|
||||||
|
- [ ] Handle disconnect gracefully
|
||||||
|
- [ ] Buffer management (channel-based backpressure)
|
||||||
|
- [ ] Configurable idle timeout (default 300s)
|
||||||
|
- [ ] Connection pool (reuse SSH connections for same host)
|
||||||
|
- [ ] **React: XTermWrapper component**
|
||||||
|
- [ ] xterm.js instance initialization with addons (fit, web-links, search)
|
||||||
|
- [ ] WebSocket connection management
|
||||||
|
- [ ] Keyboard input -> WS send (binary frames)
|
||||||
|
- [ ] ResizeObserver -> WS send resize message
|
||||||
|
- [ ] Fit addon — auto fit to container
|
||||||
|
- [ ] Web links addon — clickable URLs
|
||||||
|
- [ ] Search addon — Ctrl+F search in terminal
|
||||||
|
- [ ] Copy/paste — Cmd+C/V, right-click menu
|
||||||
|
- [ ] Connection status indicator (connecting, connected, disconnected, error)
|
||||||
|
- [ ] Reconnect button on disconnect
|
||||||
|
- [ ] **React: TabBar + Tab management**
|
||||||
|
- [ ] Add tab -> connect to host
|
||||||
|
- [ ] Close tab -> disconnect SSH session
|
||||||
|
- [ ] Reorder tabs via drag
|
||||||
|
- [ ] Tab status dot (green=connected, red=error, gray=disconnected)
|
||||||
|
- [ ] Tab title = host name
|
||||||
|
- [ ] Max 20 tabs limit with warning
|
||||||
|
- [ ] **Snippet panel** (slide-in from right)
|
||||||
|
- [ ] List snippets for current host
|
||||||
|
- [ ] Click snippet -> inject command to terminal
|
||||||
|
- [ ] Edit/delete from panel
|
||||||
|
- [ ] Verify: Connect to host -> terminal works -> type commands -> disconnect -> reconnect
|
||||||
|
|
||||||
|
### Sprint 3 — SFTP + Polish (Day 11-15)
|
||||||
|
|
||||||
|
#### Day 11-12: SFTP Browser
|
||||||
|
- [ ] **Go: SFTP REST handlers** `app/backend/bridge/sftp.go`
|
||||||
|
- [ ] GET /api/sftp/ls — list directory (host_id, path)
|
||||||
|
- [ ] POST /api/sftp/upload — multipart upload with progress
|
||||||
|
- [ ] GET /api/sftp/download — file download stream
|
||||||
|
- [ ] POST /api/sftp/mkdir — create directory
|
||||||
|
- [ ] POST /api/sftp/rm — delete file/directory
|
||||||
|
- [ ] POST /api/sftp/rename — rename/move
|
||||||
|
- [ ] POST /api/sftp/chmod — change permissions
|
||||||
|
- [ ] **React: SFTPScreen**
|
||||||
|
- [ ] LocalPane + RemotePane (dual pane split view)
|
||||||
|
- [ ] File list table — name, size, date, permissions (sortable)
|
||||||
|
- [ ] Navigation — cd, back, forward, path breadcrumb
|
||||||
|
- [ ] Upload/download with progress bars
|
||||||
|
- [ ] Transfer queue — multiple files, cancel, retry
|
||||||
|
- [ ] Drag & drop from desktop to upload
|
||||||
|
- [ ] Context menu — download, delete, rename, chmod, mkdir
|
||||||
|
- [ ] Keyboard shortcuts — Delete, F2 rename, Ctrl+C/V copy/move
|
||||||
|
- [ ] Verify: Browse remote files -> upload -> download -> delete -> rename
|
||||||
|
|
||||||
|
#### Day 13: Security + Vault
|
||||||
|
- [ ] Vault unlock screen — password prompt on app start
|
||||||
|
- [ ] Lock/unlock flow — auto-lock after inactivity (configurable: 1/5/15/30 min)
|
||||||
|
- [ ] Password change screen
|
||||||
|
- [ ] Known hosts dialog — first connect show fingerprint -> accept/reject
|
||||||
|
- [ ] Key passphrase prompt — when using encrypted private key
|
||||||
|
- [ ] Verify: Start app -> vault locked -> enter password -> unlock -> auto-lock
|
||||||
|
|
||||||
|
#### Day 14: Settings Screen
|
||||||
|
- [ ] Appearance tab — theme switcher, font selection, font size, background opacity
|
||||||
|
- [ ] Terminal tab — scrollback (100-10000), cursor style, cursor blink, bell, copy-on-select
|
||||||
|
- [ ] Connection tab — default timeout, keepalive interval, auto-reconnect
|
||||||
|
- [ ] Vault tab — change password, auto-lock timer, lock on sleep
|
||||||
|
- [ ] General tab — data directory, export/import buttons, about/version
|
||||||
|
- [ ] Verify: Change settings -> restart -> settings persist
|
||||||
|
|
||||||
|
#### Day 15: Mobile Setup
|
||||||
|
- [ ] React Native project with WebView
|
||||||
|
- [ ] Go mobile compilation script (gomobile bind)
|
||||||
|
- [ ] Android minimal app — WebView + gomobile .aar
|
||||||
|
- [ ] iOS minimal app — WKWebView + gomobile .xcframework
|
||||||
|
- [ ] Responsive CSS for mobile (touch-friendly targets)
|
||||||
|
- [ ] Verify: App runs on Android emulator
|
||||||
|
|
||||||
|
### Sprint 4 — Advanced Features (Day 16-20)
|
||||||
|
|
||||||
|
#### Day 16-17: Port Forwarding
|
||||||
|
- [ ] Model PortForward in Go + storage
|
||||||
|
- [ ] Go: Local forwarding — ssh.Listen -> local listener -> tunnel
|
||||||
|
- [ ] Go: Remote forwarding — ssh.Request remote forward
|
||||||
|
- [ ] Go: Dynamic forwarding — SOCKS5 proxy via SSH
|
||||||
|
- [ ] Status tracking — running/stopped/error
|
||||||
|
- [ ] React: PortForwardScreen — list, add form, start/stop toggles
|
||||||
|
- [ ] Verify: Set local forward -> `curl localhost:PORT` -> hits remote
|
||||||
|
|
||||||
|
#### Day 18: Import/Export
|
||||||
|
- [ ] Go: Import from `~/.ssh/config` — parse host, hostname, port, user, identity
|
||||||
|
- [ ] Go: Import from CSV — columns: name, hostname, port, username, group, tags
|
||||||
|
- [ ] Go: Export all data — encrypted JSON with all entities
|
||||||
|
- [ ] React: Import/Export UI — drag & drop, progress, preview, confirm
|
||||||
|
- [ ] Verify: Export -> delete all -> import -> all data restored
|
||||||
|
|
||||||
|
#### Day 19-20: Jump Hosts + Proxy
|
||||||
|
- [ ] Go: Jump host chain — SSH via intermediate hosts
|
||||||
|
- [ ] Go: Multi-hop support — host -> jump1 -> jump2 -> target
|
||||||
|
- [ ] Go: SOCKS5 proxy before SSH
|
||||||
|
- [ ] Go: HTTP CONNECT proxy
|
||||||
|
- [ ] React: Advanced connection settings — jump host selector, proxy config
|
||||||
|
- [ ] Verify: Connect via jump host -> terminal works
|
||||||
|
|
||||||
|
### Sprint 5 — Platform Polish (Day 21-25)
|
||||||
|
|
||||||
|
#### Day 21-22: Desktop Enhancements
|
||||||
|
- [ ] Electron native menu bar — File, Edit, View, Window, Help
|
||||||
|
- [ ] System tray icon — quick actions, recent hosts
|
||||||
|
- [ ] Global keyboard shortcuts — Cmd+` toggle, Cmd+N new host
|
||||||
|
- [ ] Window state persistence — position, size, maximized
|
||||||
|
- [ ] Auto-update via electron-updater
|
||||||
|
- [ ] OS Keychain integration — macOS Keychain, Windows Credential Manager, Linux Secret Service
|
||||||
|
- [ ] Verify: Install .dmg -> app appears -> open -> works
|
||||||
|
|
||||||
|
#### Day 23: Performance Optimization
|
||||||
|
- [ ] Go: Connection pooling for SSH sessions
|
||||||
|
- [ ] Go: Memory optimization — buffer pools, goroutine limits
|
||||||
|
- [ ] WebSocket: permessage-deflate compression
|
||||||
|
- [ ] React: Virtual scrolling for host list (1000+ hosts)
|
||||||
|
- [ ] React: Lazy loading screens (code splitting)
|
||||||
|
- [ ] React: Memoization (React.memo, useMemo, useCallback)
|
||||||
|
- [ ] xterm.js: WebGL renderer (preferred) with Canvas fallback
|
||||||
|
- [ ] Verify: 1000 hosts in list -> smooth scrolling -> no lag
|
||||||
|
|
||||||
|
#### Day 24-25: Mobile Polish
|
||||||
|
- [ ] Android: gomobile bind -> .aar
|
||||||
|
- [ ] Android: WebView app with touch-optimized UI
|
||||||
|
- [ ] iOS: gomobile bind -> .xcframework
|
||||||
|
- [ ] iOS: WKWebView app
|
||||||
|
- [ ] Mobile: Custom keyboard toolbar (Tab, Ctrl, Esc, arrows)
|
||||||
|
- [ ] Mobile: Gesture navigation (swipe to switch tabs)
|
||||||
|
- [ ] Mobile: Landscape/portrait handling
|
||||||
|
- [ ] Mobile: Bluetooth keyboard support
|
||||||
|
- [ ] Mobile: Background connection handling
|
||||||
|
- [ ] Verify: Install APK on Android -> connect SSH -> terminal works
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Known Issues
|
||||||
|
|
||||||
|
| # | Issue | Severity | Status |
|
||||||
|
|---|-------|----------|--------|
|
||||||
|
| (none) | — | — | — |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Last Session Notes
|
||||||
|
|
||||||
|
| Date | What was done | Commits |
|
||||||
|
|------|---------------|---------|
|
||||||
|
| 2026-06-29 | V2 planning documents created (9 files) | — |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. How to Continue
|
||||||
|
|
||||||
|
### For a new AI agent:
|
||||||
|
|
||||||
|
1. **Read this file** (`docs/v2/PROGRESS.md`) — find the first `[ ]` item
|
||||||
|
2. **Read the relevant spec doc** — for the current task:
|
||||||
|
- REST API endpoints -> `docs/v2/API.md`
|
||||||
|
- UI components -> `docs/v2/UI_COMPONENTS.md`
|
||||||
|
- Data models -> `docs/v2/DATA_MODELS.md`
|
||||||
|
- Visual reference -> `docs/v2/UI_TERMIUS_REFERENCE.md`
|
||||||
|
- Performance notes -> `docs/v2/PERFORMANCE.md`
|
||||||
|
- Build pipeline -> `docs/v2/BUILD_SYSTEM.md`
|
||||||
|
3. **Read `docs/v2/ARCHITECTURE.md`** — understand the system
|
||||||
|
4. **Implement** in `app/backend/` (Go) or `app/frontend/` (React)
|
||||||
|
5. **Test** — run `go test ./app/backend/...` and `npm test` in `app/frontend/`
|
||||||
|
6. **Update this file** — mark `[x]` the completed task, update "Last Session Notes"
|
||||||
|
|
||||||
|
### For a returning AI agent:
|
||||||
|
|
||||||
|
1. **Read this file** — check "Last Session Notes" for context
|
||||||
|
2. **Check git log** — `git log --oneline -10` for recent commits
|
||||||
|
3. **Find the first `[ ]`** — that's where you continue
|
||||||
|
4. **Update this file** when done
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Reference Documents Index
|
||||||
|
|
||||||
|
| Document | When to read |
|
||||||
|
|----------|-------------|
|
||||||
|
| `docs/v2/PROGRESS.md` | Always (first) — know where to continue |
|
||||||
|
| `docs/v2/ARCHITECTURE.md` | Understanding the system |
|
||||||
|
| `docs/v2/API.md` | Implementing REST endpoints or WebSocket handlers |
|
||||||
|
| `docs/v2/DATA_MODELS.md` | Creating/modifying Go structs or JSON schemas |
|
||||||
|
| `docs/v2/UI_COMPONENTS.md` | Building React components |
|
||||||
|
| `docs/v2/UI_TERMIUS_REFERENCE.md` | Designing UI layout, colors, typography |
|
||||||
|
| `docs/v2/SPRINT_PLAN.md` | Detailed file-by-file task instructions |
|
||||||
|
| `docs/v2/BUILD_SYSTEM.md` | Setting up build pipeline |
|
||||||
|
| `docs/v2/PERFORMANCE.md` | Tuning for speed and stability |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Git History Reference
|
||||||
|
|
||||||
|
| Commit | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| (V2 commits will be listed here) | — |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**IMPORTANT**: This file MUST be updated after every development session to ensure continuity.
|
||||||
@@ -0,0 +1,529 @@
|
|||||||
|
# Hostkeeper V2 — Sprint Plan (File-by-File Task Breakdown)
|
||||||
|
|
||||||
|
> **Status**: V2 Planning Complete
|
||||||
|
> **Last Updated**: 2026-06-29
|
||||||
|
> **Framework**: GoFiber v2 (backend), React/TypeScript (frontend), Electron (desktop)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sprint 0 — Project Scaffolding
|
||||||
|
|
||||||
|
**Goal**: Empty Electron app with GoFiber backend serving "Hello World".
|
||||||
|
|
||||||
|
### Day 0: Setup (1 day)
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 0.1 | Go module for backend | `app/backend/go.mod` | `go mod init` runs clean |
|
||||||
|
| 0.2 | Install GoFiber + deps | `app/backend/go.mod` | `go get github.com/gofiber/fiber/v2` |
|
||||||
|
| 0.3 | Minimal fiber server | `app/backend/main.go` | Server starts on random port |
|
||||||
|
| 0.4 | Health endpoint | `app/backend/main.go` | `curl localhost:PORT/api/health` returns JSON |
|
||||||
|
| 0.5 | Middleware setup | `app/backend/middleware/middleware.go` | CORS, logger, recover, compress registered |
|
||||||
|
| 0.6 | Vite + React scaffold | `app/frontend/package.json`, `app/frontend/src/App.tsx` | `npm run dev` shows React app |
|
||||||
|
| 0.7 | Electron shell | `app/electron/main.ts`, `app/electron/preload.ts`, `app/electron/package.json` | `npx electron .` opens window |
|
||||||
|
| 0.8 | Electron spawns Go | `app/electron/main.ts` | Go process starts, API responds |
|
||||||
|
| 0.9 | Electron loads frontend | `app/electron/main.ts` | Window shows React app |
|
||||||
|
| 0.10 | Bridge placeholder dirs | `app/backend/bridge/`, `app/backend/ws/` | Directories exist |
|
||||||
|
| 0.11 | Build script | `scripts/build.sh` | Script runs without error |
|
||||||
|
| 0.12 | End-to-end verify | — | Electron window shows "Hostkeeper V2" title |
|
||||||
|
|
||||||
|
#### Detailed Files
|
||||||
|
|
||||||
|
**`app/backend/go.mod`**:
|
||||||
|
```go
|
||||||
|
module git.tukangketik.id/swanadiva/hostkeeper/app/backend
|
||||||
|
|
||||||
|
go 1.26
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/gofiber/fiber/v2 v2.52.5
|
||||||
|
github.com/gofiber/contrib/websocket v1.3.3
|
||||||
|
github.com/fasthttp/websocket v1.5.12
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**`app/backend/main.go`**:
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"math/rand"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/middleware/compress"
|
||||||
|
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||||
|
"github.com/gofiber/fiber/v2/middleware/logger"
|
||||||
|
"github.com/gofiber/fiber/v2/middleware/recover"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
port := rand.Intn(60000) + 10000 // random port 10000-70000
|
||||||
|
|
||||||
|
app := fiber.New(fiber.Config{
|
||||||
|
ReadTimeout: 30 * time.Second,
|
||||||
|
WriteTimeout: 30 * time.Second,
|
||||||
|
IdleTimeout: 120 * time.Second,
|
||||||
|
})
|
||||||
|
|
||||||
|
// Middleware
|
||||||
|
app.Use(recover.New())
|
||||||
|
app.Use(logger.New())
|
||||||
|
app.Use(compress.New(compress.Config{
|
||||||
|
Level: compress.LevelBestSpeed,
|
||||||
|
}))
|
||||||
|
app.Use(cors.New(cors.Config{
|
||||||
|
AllowOrigins: "*",
|
||||||
|
AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||||
|
AllowHeaders: "Origin,Content-Type,Authorization",
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Health check
|
||||||
|
app.Get("/api/health", func(c *fiber.Ctx) error {
|
||||||
|
return c.JSON(fiber.Map{
|
||||||
|
"status": "ok",
|
||||||
|
"version": "2.0.0",
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
// Start server
|
||||||
|
go func() {
|
||||||
|
fmt.Printf("HOSTKEEPER_PORT=%d\n", port)
|
||||||
|
log.Fatal(app.Listen(fmt.Sprintf(":%d", port)))
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Graceful shutdown
|
||||||
|
quit := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
<-quit
|
||||||
|
app.Shutdown()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**`app/electron/main.ts`**:
|
||||||
|
```typescript
|
||||||
|
import { app, BrowserWindow } from 'electron';
|
||||||
|
import { spawn, ChildProcess } from 'child_process';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
let mainWindow: BrowserWindow;
|
||||||
|
let goProcess: ChildProcess;
|
||||||
|
|
||||||
|
function startGoBackend() {
|
||||||
|
const goBinary = path.join(__dirname, '../../backend/hostkeeper-server');
|
||||||
|
goProcess = spawn(goBinary, [], { stdio: 'pipe' });
|
||||||
|
|
||||||
|
goProcess.stdout?.on('data', (data) => {
|
||||||
|
const output = data.toString();
|
||||||
|
const match = output.match(/HOSTKEEPER_PORT=(\d+)/);
|
||||||
|
if (match) {
|
||||||
|
const port = match[1];
|
||||||
|
mainWindow.loadURL(`http://localhost:${port}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createWindow() {
|
||||||
|
mainWindow = new BrowserWindow({
|
||||||
|
width: 1200,
|
||||||
|
height: 800,
|
||||||
|
title: 'Hostkeeper V2',
|
||||||
|
webPreferences: {
|
||||||
|
preload: path.join(__dirname, 'preload.js'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Load from Go backend (or dev server in development)
|
||||||
|
if (process.env.NODE_ENV === 'development') {
|
||||||
|
mainWindow.loadURL('http://localhost:5173');
|
||||||
|
} else {
|
||||||
|
startGoBackend();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
app.whenReady().then(createWindow);
|
||||||
|
app.on('window-all-closed', () => {
|
||||||
|
goProcess?.kill();
|
||||||
|
app.quit();
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**`scripts/build.sh`**:
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
echo "=== Building Hostkeeper V2 ==="
|
||||||
|
|
||||||
|
# Build Go backend
|
||||||
|
echo "Building Go backend..."
|
||||||
|
cd app/backend
|
||||||
|
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o ../electron/hostkeeper-server .
|
||||||
|
cd ../..
|
||||||
|
|
||||||
|
# Build frontend
|
||||||
|
echo "Building frontend..."
|
||||||
|
cd app/frontend
|
||||||
|
npm run build
|
||||||
|
cd ../..
|
||||||
|
|
||||||
|
# Package Electron
|
||||||
|
echo "Packaging Electron..."
|
||||||
|
cd app/electron
|
||||||
|
npx electron-builder --mac --arm64
|
||||||
|
cd ../..
|
||||||
|
|
||||||
|
echo "=== Build complete ==="
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sprint 1 — Foundation (Day 1-5)
|
||||||
|
|
||||||
|
**Goal**: Full CRUD for hosts/keys/snippets + web UI with host list.
|
||||||
|
|
||||||
|
### Day 1-2: Data API Layer
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 1.1 | Host CRUD handlers | `app/backend/bridge/hosts.go` | All 6 endpoints work via curl |
|
||||||
|
| 1.2 | Key CRUD handlers | `app/backend/bridge/keys.go` | All 4 endpoints work via curl |
|
||||||
|
| 1.3 | Snippet CRUD handlers | `app/backend/bridge/snippets.go` | All 4 endpoints work via curl |
|
||||||
|
| 1.4 | Storage integration | Import `pkg/storage` | Read/write actual JSON files |
|
||||||
|
| 1.5 | Error responses | `app/backend/bridge/errors.go` | Consistent error format |
|
||||||
|
| 1.6 | Route registration | `app/backend/main.go` | All routes registered |
|
||||||
|
|
||||||
|
**Example handler** (`bridge/hosts.go`):
|
||||||
|
```go
|
||||||
|
func ListHosts(c *fiber.Ctx) error {
|
||||||
|
hosts, err := storage.ListHosts(c.Context())
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(500).JSON(fiber.Map{"error": err.Error()})
|
||||||
|
}
|
||||||
|
return c.JSON(fiber.Map{"items": hosts, "total": len(hosts)})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Day 3: Groups + Config API
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 1.7 | Group CRUD handlers | `app/backend/bridge/groups.go` | Tree structure returned |
|
||||||
|
| 1.8 | Config handlers | `app/backend/bridge/config.go` | Get/set config works |
|
||||||
|
| 1.9 | Vault handlers | `app/backend/bridge/vault.go` | Lock/unlock/unlock status |
|
||||||
|
| 1.10 | Group tree builder | `app/backend/bridge/groups.go` | Recursive tree populated |
|
||||||
|
|
||||||
|
### Day 4: Web UI Scaffold
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 1.11 | React Router | `app/frontend/src/router.tsx` | Navigate between screens |
|
||||||
|
| 1.12 | Layout component | `app/frontend/src/components/Layout.tsx` | Sidebar + tab bar + content |
|
||||||
|
| 1.13 | Sidebar component | `app/frontend/src/components/Sidebar.tsx` | Group tree + search |
|
||||||
|
| 1.14 | Theme system | `app/frontend/src/styles/themes.css` | CSS variables for dark/light |
|
||||||
|
| 1.15 | API client | `app/frontend/src/api/client.ts` | Fetch wrapper with errors |
|
||||||
|
| 1.16 | Zustand stores | `app/frontend/src/stores/*.ts` | Host, tab, vault stores |
|
||||||
|
| 1.17 | Keyboard shortcuts | `app/frontend/src/hooks/useKeyboard.ts` | Cmd+N, Cmd+K work |
|
||||||
|
|
||||||
|
### Day 5: Host List Screen
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 1.18 | HostList screen | `app/frontend/src/screens/HostListScreen.tsx` | Hosts displayed |
|
||||||
|
| 1.19 | HostCard component | `app/frontend/src/components/HostCard.tsx` | Host info shown |
|
||||||
|
| 1.20 | GroupTree component | `app/frontend/src/components/GroupTree.tsx` | Collapsible tree |
|
||||||
|
| 1.21 | SearchBar component | `app/frontend/src/components/SearchBar.tsx` | Filter works |
|
||||||
|
| 1.22 | EmptyState component | `app/frontend/src/components/EmptyState.tsx` | Shown when no hosts |
|
||||||
|
| 1.23 | Context menu | `app/frontend/src/components/ContextMenu.tsx` | Right-click menu |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sprint 2 — Core Features (Day 6-10)
|
||||||
|
|
||||||
|
**Goal**: Host form + SSH terminal (the critical feature).
|
||||||
|
|
||||||
|
### Day 6-7: Host Form + CRUD UI
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 2.1 | HostForm screen | `app/frontend/src/screens/HostFormScreen.tsx` | Add/edit host works |
|
||||||
|
| 2.2 | AuthSection component | `app/frontend/src/components/AuthSection.tsx` | Password/key selector |
|
||||||
|
| 2.3 | TagsInput component | `app/frontend/src/components/TagsInput.tsx` | Add/remove tags |
|
||||||
|
| 2.4 | GroupPicker component | `app/frontend/src/components/GroupPicker.tsx` | Tree picker |
|
||||||
|
| 2.5 | Form validation | `app/frontend/src/utils/validation.ts` | All field validation |
|
||||||
|
| 2.6 | Toast notifications | `app/frontend/src/components/Toast.tsx` | Success/error toasts |
|
||||||
|
|
||||||
|
### Day 8-10: SSH Terminal (MOST CRITICAL)
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 2.7 | WebSocket handler | `app/backend/ws/terminal.go` | WS connection accepted |
|
||||||
|
| 2.8 | SSH session management | `app/backend/ws/session.go` | Connect, stream, disconnect |
|
||||||
|
| 2.9 | Terminal resize | `app/backend/ws/terminal.go` | Resize messages handled |
|
||||||
|
| 2.10 | XTermWrapper component | `app/frontend/src/components/XTermWrapper.tsx` | Terminal renders |
|
||||||
|
| 2.11 | TerminalScreen | `app/frontend/src/screens/TerminalScreen.tsx` | Full terminal view |
|
||||||
|
| 2.12 | TabBar component | `app/frontend/src/components/TabBar.tsx` | Multi-tab support |
|
||||||
|
| 2.13 | Tab management | `app/frontend/src/stores/tabStore.ts` | Add/close/switch tabs |
|
||||||
|
| 2.14 | SnippetPanel | `app/frontend/src/components/SnippetPanel.tsx` | Slide-in snippet list |
|
||||||
|
| 2.15 | Connection overlay | `app/frontend/src/components/ConnectionOverlay.tsx` | Status + reconnect |
|
||||||
|
| 2.16 | Terminal toolbar | `app/frontend/src/components/TerminalToolbar.tsx` | Host info + actions |
|
||||||
|
|
||||||
|
**WebSocket handler** (`ws/terminal.go`):
|
||||||
|
```go
|
||||||
|
package ws
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gofiber/contrib/websocket"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
func HandleTerminal(c *websocket.Conn) {
|
||||||
|
hostID := c.Query("host_id")
|
||||||
|
cols := c.QueryInt("cols", 80)
|
||||||
|
rows := c.QueryInt("rows", 24)
|
||||||
|
|
||||||
|
// Get host from storage
|
||||||
|
host, err := storage.GetHost(c.Context(), hostID)
|
||||||
|
if err != nil {
|
||||||
|
c.WriteJSON(fiber.Map{"type": "error", "message": "Host not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create SSH client
|
||||||
|
client := ssh.NewClient(host, 30*time.Second)
|
||||||
|
if err := client.Connect(c.Context()); err != nil {
|
||||||
|
c.WriteJSON(fiber.Map{"type": "error", "message": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer client.Close()
|
||||||
|
|
||||||
|
// Create session + PTY
|
||||||
|
session, err := client.GetClient().NewSession()
|
||||||
|
if err != nil {
|
||||||
|
c.WriteJSON(fiber.Map{"type": "error", "message": "Session failed"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer session.Close()
|
||||||
|
|
||||||
|
modes := ssh.TerminalModes{ssh.ECHO: 1}
|
||||||
|
session.RequestPty("xterm-256color", rows, cols, modes)
|
||||||
|
|
||||||
|
stdin, _ := session.StdinPipe()
|
||||||
|
stdout, _ := session.StdoutPipe()
|
||||||
|
|
||||||
|
if err := session.Shell(); err != nil {
|
||||||
|
c.WriteJSON(fiber.Map{"type": "error", "message": "Shell failed"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.WriteJSON(fiber.Map{"type": "status", "state": "connected"})
|
||||||
|
|
||||||
|
// Goroutine: SSH stdout -> WebSocket
|
||||||
|
go func() {
|
||||||
|
buf := make([]byte, 4096)
|
||||||
|
for {
|
||||||
|
n, err := stdout.Read(buf)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err := c.WriteMessage(websocket.BinaryMessage, buf[:n]); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Main loop: WebSocket -> SSH stdin
|
||||||
|
for {
|
||||||
|
_, msg, err := c.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for resize message
|
||||||
|
if len(msg) > 0 && msg[0] == '{' {
|
||||||
|
var ctrl struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Cols int `json:"cols"`
|
||||||
|
Rows int `json:"rows"`
|
||||||
|
}
|
||||||
|
if json.Unmarshal(msg, &ctrl) == nil && ctrl.Type == "resize" {
|
||||||
|
session.WindowChange(ctrl.Rows, ctrl.Cols)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Regular input
|
||||||
|
stdin.Write(msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sprint 3 — SFTP + Polish (Day 11-15)
|
||||||
|
|
||||||
|
**Goal**: SFTP browser + security + settings.
|
||||||
|
|
||||||
|
### Day 11-12: SFTP Browser
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 3.1 | SFTP REST handlers | `app/backend/bridge/sftp.go` | All 7 endpoints work |
|
||||||
|
| 3.2 | SFTPScreen | `app/frontend/src/screens/SFTPScreen.tsx` | Dual pane visible |
|
||||||
|
| 3.3 | FileList component | `app/frontend/src/components/FileList.tsx` | Files listed with columns |
|
||||||
|
| 3.4 | LocalPane component | `app/frontend/src/components/LocalPane.tsx` | Local files |
|
||||||
|
| 3.5 | RemotePane component | `app/frontend/src/components/RemotePane.tsx` | Remote files |
|
||||||
|
| 3.6 | TransferQueue | `app/frontend/src/components/TransferQueue.tsx` | Transfer progress |
|
||||||
|
| 3.7 | SFTPToolbar | `app/frontend/src/components/SFTPToolbar.tsx` | Upload/download buttons |
|
||||||
|
| 3.8 | Context menu | `app/frontend/src/components/SFTPContextMenu.tsx` | File operations |
|
||||||
|
|
||||||
|
### Day 13: Security + Vault
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 3.9 | VaultScreen | `app/frontend/src/screens/VaultScreen.tsx` | Password prompt |
|
||||||
|
| 3.10 | KnownHostDialog | `app/frontend/src/components/KnownHostDialog.tsx` | Fingerprint verify |
|
||||||
|
| 3.11 | PasswordPrompt | `app/frontend/src/components/PasswordPrompt.tsx` | Reusable prompt |
|
||||||
|
| 3.12 | Auto-lock logic | `app/frontend/src/hooks/useAutoLock.ts` | Locks after inactivity |
|
||||||
|
|
||||||
|
### Day 14: Settings Screen
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 3.13 | SettingsScreen | `app/frontend/src/screens/SettingsScreen.tsx` | Tabbed settings |
|
||||||
|
| 3.14 | AppearanceSettings | `app/frontend/src/components/settings/Appearance.tsx` | Theme, font |
|
||||||
|
| 3.15 | TerminalSettings | `app/frontend/src/components/settings/Terminal.tsx` | Scrollback, cursor |
|
||||||
|
| 3.16 | ConnectionSettings | `app/frontend/src/components/settings/Connection.tsx` | Timeout, keepalive |
|
||||||
|
| 3.17 | VaultSettings | `app/frontend/src/components/settings/Vault.tsx` | Password, auto-lock |
|
||||||
|
| 3.18 | GeneralSettings | `app/frontend/src/components/settings/General.tsx` | About, data dir |
|
||||||
|
|
||||||
|
### Day 15: Mobile Setup
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 3.19 | gomobile build script | `mobile/gomobile/build.sh` | Compiles to .aar/.xcframework |
|
||||||
|
| 3.20 | Android WebView app | `mobile/android/` | App runs on emulator |
|
||||||
|
| 3.21 | iOS WebView app | `mobile/ios/` | App runs on simulator |
|
||||||
|
| 3.22 | Mobile responsive CSS | `app/frontend/src/styles/mobile.css` | Touch-friendly |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sprint 4 — Advanced Features (Day 16-20)
|
||||||
|
|
||||||
|
**Goal**: Port forwarding + import/export + jump hosts.
|
||||||
|
|
||||||
|
### Day 16-17: Port Forwarding
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 4.1 | Forward model + storage | `app/backend/bridge/portforward.go` | CRUD works |
|
||||||
|
| 4.2 | Local forwarding | `app/backend/ws/portforward.go` | Local tunnel works |
|
||||||
|
| 4.3 | Remote forwarding | `app/backend/ws/portforward.go` | Remote tunnel works |
|
||||||
|
| 4.4 | Dynamic forwarding | `app/backend/ws/portforward.go` | SOCKS5 proxy works |
|
||||||
|
| 4.5 | PortForwardScreen | `app/frontend/src/screens/PortForwardScreen.tsx` | List + add form |
|
||||||
|
| 4.6 | ForwardCard component | `app/frontend/src/components/ForwardCard.tsx` | Status + controls |
|
||||||
|
|
||||||
|
### Day 18: Import/Export
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 4.7 | SSH config parser | `app/backend/bridge/import.go` | Parses ~/.ssh/config |
|
||||||
|
| 4.8 | CSV import | `app/backend/bridge/import.go` | Parses CSV |
|
||||||
|
| 4.9 | Export handler | `app/backend/bridge/export.go` | Encrypted JSON export |
|
||||||
|
| 4.10 | ImportScreen | `app/frontend/src/screens/ImportScreen.tsx` | Drag & drop UI |
|
||||||
|
|
||||||
|
### Day 19-20: Jump Hosts + Proxy
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 4.11 | Jump host chain | `app/backend/ws/jump.go` | Multi-hop SSH works |
|
||||||
|
| 4.12 | SOCKS5 proxy | `app/backend/ws/proxy.go` | Proxy before SSH |
|
||||||
|
| 4.13 | AdvancedHostForm | `app/frontend/src/components/AdvancedHostForm.tsx` | Jump host selector |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sprint 5 — Platform Polish (Day 21-25)
|
||||||
|
|
||||||
|
**Goal**: Desktop polish + performance + mobile.
|
||||||
|
|
||||||
|
### Day 21-22: Desktop Enhancements
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 5.1 | Native menu bar | `app/electron/menu.ts` | File/Edit/View/Help |
|
||||||
|
| 5.2 | System tray | `app/electron/tray.ts` | Tray icon + menu |
|
||||||
|
| 5.3 | Global shortcuts | `app/electron/shortcuts.ts` | Cmd+`, Cmd+N |
|
||||||
|
| 5.4 | Window state | `app/electron/state.ts` | Position/size saved |
|
||||||
|
| 5.5 | Auto-update | `app/electron/updater.ts` | Update prompt |
|
||||||
|
| 5.6 | OS Keychain | `app/electron/keychain.ts` | Store vault key |
|
||||||
|
|
||||||
|
### Day 23: Performance Optimization
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 5.7 | SSH connection pool | `app/backend/ws/pool.go` | Reuse connections |
|
||||||
|
| 5.8 | Buffer pools | `app/backend/ws/buffers.go` | sync.Pool for buffers |
|
||||||
|
| 5.9 | Virtual scrolling | `app/frontend/src/components/VirtualList.tsx` | 1000+ hosts smooth |
|
||||||
|
| 5.10 | Code splitting | `app/frontend/src/router.tsx` | Lazy load screens |
|
||||||
|
| 5.11 | React.memo | Various components | No unnecessary re-renders |
|
||||||
|
| 5.12 | WebGL renderer | `app/frontend/src/components/XTermWrapper.tsx` | Fast terminal render |
|
||||||
|
|
||||||
|
### Day 24-25: Mobile Polish
|
||||||
|
|
||||||
|
| # | Task | Files to Create | Verify |
|
||||||
|
|---|------|----------------|--------|
|
||||||
|
| 5.13 | Android gomobile | `mobile/android/` | .aar compiled |
|
||||||
|
| 5.14 | iOS gomobile | `mobile/ios/` | .xcframework compiled |
|
||||||
|
| 5.15 | Mobile keyboard | `app/frontend/src/components/MobileKeyboard.tsx` | Terminal toolbar |
|
||||||
|
| 5.16 | Gesture navigation | `app/frontend/src/hooks/useGesture.ts` | Swipe to switch tabs |
|
||||||
|
| 5.17 | Landscape handling | `app/frontend/src/styles/mobile.css` | Responsive layout |
|
||||||
|
| 5.18 | Bluetooth keyboard | `app/frontend/src/hooks/useKeyboard.ts` | External keyboard |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Dependency Graph
|
||||||
|
|
||||||
|
```
|
||||||
|
Sprint 0 (Scaffolding)
|
||||||
|
│
|
||||||
|
├── Sprint 1 (Foundation)
|
||||||
|
│ │
|
||||||
|
│ ├── Sprint 2 (Core Features)
|
||||||
|
│ │ │
|
||||||
|
│ │ ├── Sprint 3 (SFTP + Polish)
|
||||||
|
│ │ │ │
|
||||||
|
│ │ │ └── Sprint 5 (Platform Polish)
|
||||||
|
│ │ │
|
||||||
|
│ │ └── Sprint 4 (Advanced Features)
|
||||||
|
│ │ │
|
||||||
|
│ │ └── Sprint 5 (Platform Polish)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Critical path**: Sprint 0 → Sprint 1 → Sprint 2 → Sprint 5
|
||||||
|
|
||||||
|
**Parallel tracks**:
|
||||||
|
- Sprint 3 and Sprint 4 can be done in parallel
|
||||||
|
- Sprint 5 can start after Sprint 2 (desktop polish), Sprint 3 (SFTP mobile), Sprint 4 (advanced mobile)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Creation Summary
|
||||||
|
|
||||||
|
| Sprint | New Files | Directories |
|
||||||
|
|--------|-----------|-------------|
|
||||||
|
| Sprint 0 | 12 | 6 |
|
||||||
|
| Sprint 1 | 23 | 2 |
|
||||||
|
| Sprint 2 | 16 | 2 |
|
||||||
|
| Sprint 3 | 22 | 4 |
|
||||||
|
| Sprint 4 | 13 | 1 |
|
||||||
|
| Sprint 5 | 18 | 2 |
|
||||||
|
| **Total** | **104** | **17** |
|
||||||
@@ -0,0 +1,316 @@
|
|||||||
|
# Hostkeeper V2 — Timeline & Milestones
|
||||||
|
|
||||||
|
> **Status**: V2 Planning Complete
|
||||||
|
> **Last Updated**: 2026-06-29
|
||||||
|
> **Start Date**: 2026-06-30 (estimated)
|
||||||
|
> **Target MVP**: 2026-08-07 (estimated)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Timeline Overview
|
||||||
|
|
||||||
|
Total estimated: **25-30 working days** (~6 minggu calendar, 1-2 minggu buffer)
|
||||||
|
|
||||||
|
```
|
||||||
|
Minggu 1 │ Sprint 0 ─ Sprint 1 ─ │──── Foundation
|
||||||
|
Minggu 2 │ Sprint 2 ─────────────│──── Core (Terminal)
|
||||||
|
Minggu 3 │ Sprint 3 ─────────────│──── SFTP + Polish
|
||||||
|
Minggu 4 │ Sprint 4 ─────────────│──── Advanced
|
||||||
|
Minggu 5 │ Sprint 5 ── Buffer ───│──── Polish + Release
|
||||||
|
└────────────────────────┘
|
||||||
|
26 Jun 10 Jul 24 Jul 7 Aug
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Detailed Timeline
|
||||||
|
|
||||||
|
### Phase 0: Foundation (Sprint 0 + Sprint 1)
|
||||||
|
**6 working days — 30 Jun s.d. 7 Jul**
|
||||||
|
|
||||||
|
| Day | Date | Sprint | Deliverable | Milestone |
|
||||||
|
|-----|------|--------|-------------|-----------|
|
||||||
|
| 1 | 30 Jun | Sprint 0 | Go module, Electron shell, Vite scaffold | App starts, shows "Hostkeeper V2" |
|
||||||
|
| 2 | 1 Jul | Sprint 0 | Health endpoint, middleware, build script | `curl /api/health` returns OK |
|
||||||
|
| 3 | 2 Jul | Sprint 1 | Host CRUD API (6 endpoints) | `curl POST /api/hosts` returns 201 |
|
||||||
|
| 4 | 3 Jul | Sprint 1 | Key + Snippet CRUD API | All CRUD works via curl |
|
||||||
|
| 5 | 4 Jul | Sprint 1 | Groups + Config + Vault API | Group tree returned |
|
||||||
|
| 6 | 7 Jul | Sprint 1 | Web UI scaffold (layout, router, theme) | Navigation works, sidebar visible |
|
||||||
|
|
||||||
|
**Milestone M1 — API Complete (7 Jul)**
|
||||||
|
- All REST API endpoints functional
|
||||||
|
- Storage integration with V1 `pkg/storage`
|
||||||
|
- Web UI layout renders
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 1: Core Features (Sprint 2)
|
||||||
|
**5 working days — 8 Jul s.d. 14 Jul**
|
||||||
|
|
||||||
|
| Day | Date | Deliverable | Milestone |
|
||||||
|
|-----|------|-------------|-----------|
|
||||||
|
| 7 | 8 Jul | Host List screen + HostForm UI | Add/edit host from browser |
|
||||||
|
| 8 | 9 Jul | HostForm: auth, tags, group picker | All form fields work |
|
||||||
|
| 9 | 10 Jul | WebSocket handler (Go) | Terminal WS connects |
|
||||||
|
| 10 | 11 Jul | XTermWrapper + terminal UI | Terminal renders, keystrokes work |
|
||||||
|
| 11 | 14 Jul | TabBar + multi-tab + snippet panel | Multi-tab terminal with snippets |
|
||||||
|
|
||||||
|
**Milestone M2 — Terminal Works (14 Jul)**
|
||||||
|
- SSH terminal via WebSocket
|
||||||
|
- Multi-tab support
|
||||||
|
- Snippet injection
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 2: SFTP + Security (Sprint 3)
|
||||||
|
**5 working days — 15 Jul s.d. 21 Jul**
|
||||||
|
|
||||||
|
| Day | Date | Deliverable | Milestone |
|
||||||
|
|-----|------|-------------|-----------|
|
||||||
|
| 12 | 15 Jul | SFTP REST handlers (ls, upload, download) | SFTP API works via curl |
|
||||||
|
| 13 | 16 Jul | SFTP: mkdir, rm, rename, chmod | File operations work |
|
||||||
|
| 14 | 17 Jul | SFTPScreen + dual pane UI | SFTP browser functional |
|
||||||
|
| 15 | 18 Jul | Vault unlock + known hosts dialog | Security flow works |
|
||||||
|
| 16 | 21 Jul | Settings screen (all tabs) | Settings persist |
|
||||||
|
|
||||||
|
**Milestone M3 — SFTP + Vault (21 Jul)**
|
||||||
|
- SFTP file browser with upload/download
|
||||||
|
- Vault lock/unlock flow
|
||||||
|
- Settings customization
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 3: Advanced Features (Sprint 4)
|
||||||
|
**5 working days — 22 Jul s.d. 28 Jul**
|
||||||
|
|
||||||
|
| Day | Date | Deliverable | Milestone |
|
||||||
|
|-----|------|-------------|-----------|
|
||||||
|
| 17 | 22 Jul | PortForward CRUD + local tunnel | Local port forward works |
|
||||||
|
| 18 | 23 Jul | Remote + dynamic forwarding | All forward types work |
|
||||||
|
| 19 | 24 Jul | Import: SSH config + CSV parser | Bulk import works |
|
||||||
|
| 20 | 25 Jul | Export: all data encrypted | Export/import round-trip |
|
||||||
|
| 21 | 28 Jul | Jump host + proxy support | Multi-hop SSH works |
|
||||||
|
|
||||||
|
**Milestone M4 — Advanced Complete (28 Jul)**
|
||||||
|
- Port forwarding (local/remote/dynamic)
|
||||||
|
- Import/export
|
||||||
|
- Jump hosts + proxy
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Phase 4: Polish & Release (Sprint 5)
|
||||||
|
**5 working days — 29 Jul s.d. 4 Aug**
|
||||||
|
|
||||||
|
| Day | Date | Deliverable | Milestone |
|
||||||
|
|-----|------|-------------|-----------|
|
||||||
|
| 22 | 29 Jul | Electron: menu, tray, shortcuts | Desktop polish complete |
|
||||||
|
| 23 | 30 Jul | OS Keychain + auto-update | Keychain integration |
|
||||||
|
| 24 | 31 Jul | Performance optimization | 1000 hosts smooth, memory < 200MB |
|
||||||
|
| 25 | 1 Aug | Android gomobile + WebView | Android app runs |
|
||||||
|
| 26 | 4 Aug | iOS gomobile + WKWebView | iOS app runs |
|
||||||
|
|
||||||
|
**Milestone M5 — Release Candidate (4 Aug)**
|
||||||
|
- All features complete
|
||||||
|
- Desktop and mobile builds
|
||||||
|
- Performance targets met
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Buffer: 3 days (5 Aug s.d. 7 Aug)
|
||||||
|
|
||||||
|
| Day | Date | Activity |
|
||||||
|
|-----|------|----------|
|
||||||
|
| 27 | 5 Aug | Bug fixes from integration testing |
|
||||||
|
| 28 | 6 Aug | Documentation finalization |
|
||||||
|
| 29 | 7 Aug | Release v2.0.0 |
|
||||||
|
|
||||||
|
**Milestone M6 — v2.0.0 Release (7 Aug)**
|
||||||
|
- All platforms built and signed
|
||||||
|
- Release notes complete
|
||||||
|
- Artifacts uploaded to GitHub
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Critical Path
|
||||||
|
|
||||||
|
```
|
||||||
|
Sprint 0 ── Sprint 1 ── Sprint 2 ── Sprint 5 ── Release
|
||||||
|
1 day 5 days 5 days 5 days 3 days
|
||||||
|
─────────────────────────────────────────────────────────
|
||||||
|
19 days minimum (no parallel work)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Parallel Work Opportunities
|
||||||
|
|
||||||
|
| Sprint | Can run in parallel with | Notes |
|
||||||
|
|--------|-------------------------|-------|
|
||||||
|
| Sprint 1 | — | Must complete before Sprint 2 |
|
||||||
|
| Sprint 2 | — | Must complete before Sprint 3/4/5 |
|
||||||
|
| Sprint 3 | Sprint 4 | SFTP ≠ Port forwarding, different files |
|
||||||
|
| Sprint 4 | Sprint 3 | Independent features |
|
||||||
|
| Sprint 5 | Sprint 3, Sprint 4 | Desktop polish can start early |
|
||||||
|
|
||||||
|
**Optimistic timeline** (with parallelism): 22 days
|
||||||
|
**Conservative timeline** (sequential): 29 days
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Dependency Graph
|
||||||
|
|
||||||
|
```
|
||||||
|
Sprint 0 (Scaffolding)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Sprint 1 (Foundation API)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Sprint 2 (SSH Terminal) ⭐ CRITICAL PATH
|
||||||
|
│
|
||||||
|
├────▶ Sprint 3 (SFTP + Security) ────▶ Sprint 5 (Desktop Polish)
|
||||||
|
│ │
|
||||||
|
└────▶ Sprint 4 (Advanced) ────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Release v2.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
**Critical path**: Sprint 0 → Sprint 1 → Sprint 2 → Sprint 5 → Release
|
||||||
|
|
||||||
|
**Fastest possible**: 22 hari (Sprint 3 + 4 done in parallel with Sprint 5)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Milestone Summary
|
||||||
|
|
||||||
|
| Milestone | Date | Deliverable | Dependency |
|
||||||
|
|-----------|------|-------------|------------|
|
||||||
|
| **M1** | 7 Jul | All REST API endpoints + Web UI scaffold | Sprint 0 + Sprint 1 |
|
||||||
|
| **M2** | 14 Jul | SSH terminal with multi-tab | M1 |
|
||||||
|
| **M3** | 21 Jul | SFTP browser + vault + settings | M2 |
|
||||||
|
| **M4** | 28 Jul | Port forwarding + import/export + jump hosts | M2 |
|
||||||
|
| **M5** | 4 Aug | Desktop polish + mobile apps | M2, M3, M4 |
|
||||||
|
| **M6** | 7 Aug | **v2.0.0 Release** | M5 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Weekly Breakdown
|
||||||
|
|
||||||
|
### Week 1 (30 Jun - 4 Jul) — Foundation
|
||||||
|
```
|
||||||
|
Mon 30: [Sprint 0] Go scaffold + Electron shell
|
||||||
|
Tue 1: [Sprint 0] Build script + middleware
|
||||||
|
Wed 2: [Sprint 1] Host CRUD API
|
||||||
|
Thu 3: [Sprint 1] Key + Snippet CRUD API
|
||||||
|
Fri 4: [Sprint 1] Groups + Config + Vault API
|
||||||
|
```
|
||||||
|
|
||||||
|
### Week 2 (7 Jul - 11 Jul) — API + UI Scaffold
|
||||||
|
```
|
||||||
|
Mon 7: [Sprint 1] Web UI scaffold (layout, router, theme) ← M1
|
||||||
|
Tue 8: [Sprint 2] Host List screen + HostForm
|
||||||
|
Wed 9: [Sprint 2] HostForm complete (auth, tags, groups)
|
||||||
|
Thu 10: [Sprint 2] WebSocket handler (Go)
|
||||||
|
Fri 11: [Sprint 2] XTermWrapper + terminal rendering
|
||||||
|
```
|
||||||
|
|
||||||
|
### Week 3 (14 Jul - 18 Jul) — Terminal + SFTP
|
||||||
|
```
|
||||||
|
Mon 14: [Sprint 2] TabBar + multi-tab + snippet panel ← M2
|
||||||
|
Tue 15: [Sprint 3] SFTP REST handlers
|
||||||
|
Wed 16: [Sprint 3] File operations (mkdir, rm, rename)
|
||||||
|
Thu 17: [Sprint 3] SFTPScreen + dual pane UI
|
||||||
|
Fri 18: [Sprint 3] Vault unlock + known hosts dialog
|
||||||
|
```
|
||||||
|
|
||||||
|
### Week 4 (21 Jul - 25 Jul) — SFTP Settings + Advanced
|
||||||
|
```
|
||||||
|
Mon 21: [Sprint 3] Settings screen (all tabs) ← M3
|
||||||
|
Tue 22: [Sprint 4] PortForward CRUD + local tunnel
|
||||||
|
Wed 23: [Sprint 4] Remote + dynamic forwarding
|
||||||
|
Thu 24: [Sprint 4] Import (SSH config, CSV)
|
||||||
|
Fri 25: [Sprint 4] Export + jump hosts
|
||||||
|
```
|
||||||
|
|
||||||
|
### Week 5 (28 Jul - 1 Aug) — Advanced + Polish
|
||||||
|
```
|
||||||
|
Mon 28: [Sprint 4] Proxy support ← M4
|
||||||
|
Tue 29: [Sprint 5] Electron: menu, tray, shortcuts
|
||||||
|
Wed 30: [Sprint 5] OS Keychain + auto-update
|
||||||
|
Thu 31: [Sprint 5] Performance optimization
|
||||||
|
Fri 1: [Sprint 5] Android gomobile + WebView
|
||||||
|
```
|
||||||
|
|
||||||
|
### Week 6 (4 Aug - 7 Aug) — Mobile + Release
|
||||||
|
```
|
||||||
|
Mon 4: [Sprint 5] iOS gomobile + WKWebView ← M5
|
||||||
|
Tue 5: [Buffer] Bug fixes
|
||||||
|
Wed 6: [Buffer] Documentation
|
||||||
|
Thu 7: [Release] v2.0.0 ← M6
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Risk Buffer
|
||||||
|
|
||||||
|
| Risk | Impact | Probability | Mitigation | Buffer needed |
|
||||||
|
|------|--------|-------------|------------|---------------|
|
||||||
|
| Terminal WebSocket complexity | High | Medium | Use proven pattern from docs | +1 day |
|
||||||
|
| Mobile gomobile compilation | Medium | Medium | Start early, test on emulator | +1 day |
|
||||||
|
| Electron auto-update signing | Medium | Low | Prepare certificates early | — |
|
||||||
|
| Performance issues (1000 hosts) | Medium | Low | Virtual scrolling already planned | — |
|
||||||
|
| Unknown V1 package compatibility | Low | Low | V1 packages are framework-agnostic | — |
|
||||||
|
| UX polish takes longer | Medium | Medium | Prioritize function over beauty | +1 day |
|
||||||
|
|
||||||
|
**Total buffer**: 3 days (included in timeline as 5-7 Aug)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Effort by Technology
|
||||||
|
|
||||||
|
| Technology | Days | % of total | Sprint |
|
||||||
|
|------------|------|------------|--------|
|
||||||
|
| Go (backend) | 10 | 34% | S0, S1, S2, S3, S4 |
|
||||||
|
| React/TypeScript (frontend) | 10 | 34% | S1, S2, S3, S4, S5 |
|
||||||
|
| Electron (desktop) | 3 | 10% | S0, S5 |
|
||||||
|
| Mobile (gomobile + WebView) | 2 | 7% | S3, S5 |
|
||||||
|
| DevOps (build, CI/CD) | 2 | 7% | S0, S5 |
|
||||||
|
| Testing + bug fixes | 2 | 7% | All |
|
||||||
|
| **Total** | **29** | **100%** | |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. What NOT in Scope (Post-MVP)
|
||||||
|
|
||||||
|
| Feature | Reason |
|
||||||
|
|---------|--------|
|
||||||
|
| Cloud sync | Requires backend server, Phase 3 |
|
||||||
|
| Team vault | Requires multi-user auth, Phase 3 |
|
||||||
|
| Multiplayer terminal | Requires relay server, Phase 3 |
|
||||||
|
| AI command generation | LLM API integration, nice-to-have |
|
||||||
|
| Serial console | Niche use case, low priority |
|
||||||
|
| Mosh support | Requires additional library |
|
||||||
|
| Telnet support | Legacy protocol, low priority |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Progress Tracking
|
||||||
|
|
||||||
|
**How to update this timeline**:
|
||||||
|
1. At the end of each day, mark `[x]` for completed tasks
|
||||||
|
2. If a task takes longer, adjust subsequent dates
|
||||||
|
3. Update `docs/v2/PROGRESS.md` with actual completion dates
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
### Week 1 Progress
|
||||||
|
[x] Mon 30 Jun: [Sprint 0] Go scaffold + Electron shell
|
||||||
|
[ ] Tue 1 Jul: [Sprint 0] Build script + middleware
|
||||||
|
[ ] Wed 2 Jul: [Sprint 1] Host CRUD API
|
||||||
|
[ ] Thu 3 Jul: [Sprint 1] Key + Snippet CRUD API
|
||||||
|
[ ] Fri 4 Jul: [Sprint 1] Groups + Config + Vault API
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Target**: v2.0.0 Release by **7 August 2026**
|
||||||
|
**Best case**: 22 July (parallel work, no blockers)
|
||||||
|
**Worst case**: 14 August (1 week buffer used + delays)
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,558 @@
|
|||||||
|
# Hostkeeper V2 — Termius UI Reference
|
||||||
|
|
||||||
|
> **Status**: V2 Planning Complete
|
||||||
|
> **Last Updated**: 2026-06-29
|
||||||
|
> **Purpose**: Visual reference for replicating Termius-like UI in Hostkeeper V2.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Termius Design Analysis
|
||||||
|
|
||||||
|
### Design Philosophy
|
||||||
|
|
||||||
|
Termius follows a **dark-first, minimal, professional** design language:
|
||||||
|
- Dark backgrounds with muted colors
|
||||||
|
- High contrast for active elements
|
||||||
|
- Subtle hover states (no harsh highlights)
|
||||||
|
- Generous padding and whitespace
|
||||||
|
- Rounded corners (subtle, not bubbly)
|
||||||
|
- Consistent iconography (Feather-style line icons)
|
||||||
|
|
||||||
|
### Key Design Principles
|
||||||
|
|
||||||
|
1. **Content-first** — Terminal/SFTP content takes maximum space
|
||||||
|
2. **Sidebar minimal** — Thin sidebar, collapsible, icons + labels
|
||||||
|
3. **Tab bar compact** — Small tab height, status dots, close buttons
|
||||||
|
4. **Forms clean** — Labeled inputs, generous spacing, clear validation
|
||||||
|
5. **Modals focused** — Centered, focused, one task at a time
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Color Palette
|
||||||
|
|
||||||
|
### Dark Theme (Default)
|
||||||
|
|
||||||
|
| Element | Color | Hex |
|
||||||
|
|---------|-------|-----|
|
||||||
|
| Background (main) | Deep navy | `#0d1117` |
|
||||||
|
| Surface (cards, sidebar) | Slightly lighter | `#161b22` |
|
||||||
|
| Surface hover | Subtle highlight | `#1c2128` |
|
||||||
|
| Surface active | Selected state | `#21262d` |
|
||||||
|
| Border | Muted line | `#30363d` |
|
||||||
|
| Text primary | White | `#e6edf3` |
|
||||||
|
| Text secondary | Muted gray | `#8b949e` |
|
||||||
|
| Text tertiary | Dim | `#484f58` |
|
||||||
|
| Accent (primary) | Blue | `#58a6ff` |
|
||||||
|
| Accent hover | Lighter blue | `#79c0ff` |
|
||||||
|
| Success | Green | `#3fb950` |
|
||||||
|
| Warning | Yellow | `#d29922` |
|
||||||
|
| Error | Red | `#f85149` |
|
||||||
|
| Info | Blue | `#58a6ff` |
|
||||||
|
|
||||||
|
### Light Theme
|
||||||
|
|
||||||
|
| Element | Color | Hex |
|
||||||
|
|---------|-------|-----|
|
||||||
|
| Background (main) | White | `#ffffff` |
|
||||||
|
| Surface | Light gray | `#f6f8fa` |
|
||||||
|
| Surface hover | Slightly darker | `#eaeef2` |
|
||||||
|
| Border | Light line | `#d0d7de` |
|
||||||
|
| Text primary | Dark | `#1f2328` |
|
||||||
|
| Text secondary | Gray | `#656d76` |
|
||||||
|
| Accent (primary) | Blue | `#0969da` |
|
||||||
|
|
||||||
|
### High Contrast Theme
|
||||||
|
|
||||||
|
| Element | Color | Hex |
|
||||||
|
|---------|-------|-----|
|
||||||
|
| Background | Pure black | `#000000` |
|
||||||
|
| Surface | Near black | `#0a0a0a` |
|
||||||
|
| Border | Bright white | `#ffffff` |
|
||||||
|
| Text primary | Pure white | `#ffffff` |
|
||||||
|
| Accent | Bright blue | `#4da6ff` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Typography
|
||||||
|
|
||||||
|
### Font Stack
|
||||||
|
|
||||||
|
```css
|
||||||
|
/* UI text */
|
||||||
|
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||||
|
|
||||||
|
/* Terminal / code */
|
||||||
|
font-family: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace;
|
||||||
|
```
|
||||||
|
|
||||||
|
### Font Sizes
|
||||||
|
|
||||||
|
| Element | Size | Weight |
|
||||||
|
|---------|------|--------|
|
||||||
|
| App title | 16px | 600 (semibold) |
|
||||||
|
| Section heading | 14px | 600 (semibold) |
|
||||||
|
| Body text | 13px | 400 (regular) |
|
||||||
|
| Small text | 12px | 400 (regular) |
|
||||||
|
| Caption | 11px | 400 (regular) |
|
||||||
|
| Terminal default | 14px | 400 (regular) |
|
||||||
|
| Terminal small | 12px | 400 (regular) |
|
||||||
|
|
||||||
|
### Line Heights
|
||||||
|
|
||||||
|
| Element | Line Height |
|
||||||
|
|---------|-------------|
|
||||||
|
| Headings | 1.3 |
|
||||||
|
| Body | 1.5 |
|
||||||
|
| Terminal | 1.2 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Spacing System
|
||||||
|
|
||||||
|
Based on 4px grid:
|
||||||
|
|
||||||
|
| Token | Value | Usage |
|
||||||
|
|-------|-------|-------|
|
||||||
|
| `--space-1` | 4px | Tight spacing (icon gaps) |
|
||||||
|
| `--space-2` | 8px | Default spacing (inline elements) |
|
||||||
|
| `--space-3` | 12px | Component padding |
|
||||||
|
| `--space-4` | 16px | Section padding |
|
||||||
|
| `--space-5` | 20px | Card padding |
|
||||||
|
| `--space-6` | 24px | Section gaps |
|
||||||
|
| `--space-8` | 32px | Page padding |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Component Specs
|
||||||
|
|
||||||
|
### 5.1 Sidebar
|
||||||
|
|
||||||
|
```
|
||||||
|
Width: 240px (default), min 180px, max 400px
|
||||||
|
Background: var(--surface)
|
||||||
|
Border-right: 1px solid var(--border)
|
||||||
|
Padding: 12px (top, bottom)
|
||||||
|
|
||||||
|
Sections:
|
||||||
|
1. Header (h-9 = 36px)
|
||||||
|
- App name (14px, semibold)
|
||||||
|
- Collapse button (right-aligned)
|
||||||
|
2. Search bar
|
||||||
|
- Height: 32px
|
||||||
|
- Border-radius: 6px
|
||||||
|
- Background: var(--background)
|
||||||
|
- Icon: search (left), clear (right)
|
||||||
|
- Padding: 0 12px
|
||||||
|
3. Group tree
|
||||||
|
- Item height: 32px
|
||||||
|
- Padding: 0 12px
|
||||||
|
- Indent: 16px per level
|
||||||
|
- Hover: var(--surface-hover)
|
||||||
|
- Active: var(--surface-active)
|
||||||
|
- Chevron icon: 14px, muted color
|
||||||
|
- Color dot: 8px circle
|
||||||
|
- Host count badge: 11px, muted text
|
||||||
|
4. Quick actions
|
||||||
|
- Fixed at bottom
|
||||||
|
- Buttons: icon + label
|
||||||
|
- Height: 32px
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 Tab Bar
|
||||||
|
|
||||||
|
```
|
||||||
|
Height: 36px
|
||||||
|
Background: var(--surface)
|
||||||
|
Border-bottom: 1px solid var(--border)
|
||||||
|
|
||||||
|
Tab:
|
||||||
|
- Padding: 0 12px
|
||||||
|
- Height: 36px
|
||||||
|
- Border-right: 1px solid var(--border)
|
||||||
|
- Hover: var(--surface-hover)
|
||||||
|
- Active: var(--background)
|
||||||
|
- Status dot: 6px circle, left of title
|
||||||
|
- Title: 13px, max-width 120px, truncate
|
||||||
|
- Close button: 14px, visible on hover, X icon
|
||||||
|
- New tab button: + icon, 36px width
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 Host List
|
||||||
|
|
||||||
|
```
|
||||||
|
Background: var(--background)
|
||||||
|
Padding: 16px
|
||||||
|
|
||||||
|
Header:
|
||||||
|
- Title: 20px, semibold
|
||||||
|
- Actions row: filter chips + view toggle + add button
|
||||||
|
|
||||||
|
Host item (list view):
|
||||||
|
- Height: 48px
|
||||||
|
- Padding: 0 16px
|
||||||
|
- Border-bottom: 1px solid var(--border)
|
||||||
|
- Hover: var(--surface-hover)
|
||||||
|
- Active: var(--surface-active)
|
||||||
|
- Left: status dot (6px) + server icon (16px)
|
||||||
|
- Center: name (14px, medium) + hostname (12px, muted)
|
||||||
|
- Right: favorite star (16px) + last used (12px, muted)
|
||||||
|
|
||||||
|
Host item (grid view):
|
||||||
|
- Card size: 200x120px
|
||||||
|
- Border: 1px solid var(--border)
|
||||||
|
- Border-radius: 8px
|
||||||
|
- Padding: 12px
|
||||||
|
- Hover: border-color changes to accent
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.4 Terminal
|
||||||
|
|
||||||
|
```
|
||||||
|
Background: #0d1117 (dark) or #ffffff (light)
|
||||||
|
Font: JetBrains Mono 14px
|
||||||
|
Cursor: block, blinking
|
||||||
|
|
||||||
|
Toolbar (top):
|
||||||
|
- Height: 32px
|
||||||
|
- Background: var(--surface)
|
||||||
|
- Border-bottom: 1px solid var(--border)
|
||||||
|
- Left: host name (14px, medium) + status dot
|
||||||
|
- Right: reconnect button, snippet toggle, settings
|
||||||
|
|
||||||
|
Status bar (bottom):
|
||||||
|
- Height: 24px
|
||||||
|
- Background: var(--surface)
|
||||||
|
- Border-top: 1px solid var(--border)
|
||||||
|
- Left: connection status text (12px)
|
||||||
|
- Right: cols x rows (12px, muted)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.5 SFTP Browser
|
||||||
|
|
||||||
|
```
|
||||||
|
Background: var(--background)
|
||||||
|
|
||||||
|
Pane:
|
||||||
|
- Width: 50% (side-by-side) or 100% (stacked)
|
||||||
|
- Header: 32px, path breadcrumb
|
||||||
|
- Content: file list (table)
|
||||||
|
- Footer: 24px, transfer status
|
||||||
|
|
||||||
|
File list columns:
|
||||||
|
- Name: flex-1, 13px
|
||||||
|
- Size: 80px, right-aligned, 12px, muted
|
||||||
|
- Date: 120px, 12px, muted
|
||||||
|
- Permissions: 80px, 12px, monospace, muted
|
||||||
|
|
||||||
|
Row:
|
||||||
|
- Height: 32px
|
||||||
|
- Padding: 0 12px
|
||||||
|
- Hover: var(--surface-hover)
|
||||||
|
- Selected: var(--surface-active)
|
||||||
|
- Folder icon: yellow
|
||||||
|
- File icon: default color
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.6 Forms
|
||||||
|
|
||||||
|
```
|
||||||
|
Input:
|
||||||
|
- Height: 36px
|
||||||
|
- Border: 1px solid var(--border)
|
||||||
|
- Border-radius: 6px
|
||||||
|
- Padding: 0 12px
|
||||||
|
- Font: 13px
|
||||||
|
- Background: var(--background)
|
||||||
|
- Focus: border-color: var(--accent)
|
||||||
|
- Error: border-color: var(--error)
|
||||||
|
|
||||||
|
Label:
|
||||||
|
- Font: 12px, medium
|
||||||
|
- Color: var(--text-secondary)
|
||||||
|
- Margin-bottom: 4px
|
||||||
|
|
||||||
|
Error message:
|
||||||
|
- Font: 12px
|
||||||
|
- Color: var(--error)
|
||||||
|
- Margin-top: 4px
|
||||||
|
|
||||||
|
Select:
|
||||||
|
- Same as input
|
||||||
|
- Dropdown: 200px max-height, scrollable
|
||||||
|
- Option: 32px height, hover highlight
|
||||||
|
|
||||||
|
Button (primary):
|
||||||
|
- Height: 36px
|
||||||
|
- Padding: 0 16px
|
||||||
|
- Border-radius: 6px
|
||||||
|
- Background: var(--accent)
|
||||||
|
- Color: #ffffff
|
||||||
|
- Font: 13px, 500 (medium)
|
||||||
|
- Hover: brightness 1.1
|
||||||
|
|
||||||
|
Button (ghost):
|
||||||
|
- Same dimensions
|
||||||
|
- Background: transparent
|
||||||
|
- Color: var(--text-primary)
|
||||||
|
- Hover: var(--surface-hover)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.7 Modals
|
||||||
|
|
||||||
|
```
|
||||||
|
Overlay: rgba(0, 0, 0, 0.5)
|
||||||
|
Container:
|
||||||
|
- Width: 400px (default), max 560px
|
||||||
|
- Background: var(--surface)
|
||||||
|
- Border-radius: 12px
|
||||||
|
- Border: 1px solid var(--border)
|
||||||
|
- Shadow: 0 8px 32px rgba(0, 0, 0, 0.3)
|
||||||
|
- Padding: 24px
|
||||||
|
- Centered on screen
|
||||||
|
|
||||||
|
Title:
|
||||||
|
- Font: 16px, semibold
|
||||||
|
- Margin-bottom: 16px
|
||||||
|
|
||||||
|
Actions:
|
||||||
|
- Right-aligned
|
||||||
|
- Gap: 8px
|
||||||
|
- Cancel (ghost) + Confirm (primary)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.8 Toast Notifications
|
||||||
|
|
||||||
|
```
|
||||||
|
Position: bottom-right
|
||||||
|
Width: 360px
|
||||||
|
Height: auto (min 48px)
|
||||||
|
Background: var(--surface)
|
||||||
|
Border: 1px solid var(--border)
|
||||||
|
Border-radius: 8px
|
||||||
|
Shadow: 0 4px 12px rgba(0, 0, 0, 0.2)
|
||||||
|
Padding: 12px 16px
|
||||||
|
|
||||||
|
Left: icon (color-coded)
|
||||||
|
- Success: green check
|
||||||
|
- Error: red X
|
||||||
|
- Warning: yellow triangle
|
||||||
|
- Info: blue circle
|
||||||
|
Center: message (13px)
|
||||||
|
Right: close button (X)
|
||||||
|
|
||||||
|
Animation: slide in from right, fade out after 5s
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Layout Breakpoints
|
||||||
|
|
||||||
|
| Name | Width | Behavior |
|
||||||
|
|------|-------|----------|
|
||||||
|
| Mobile | < 600px | Sidebar collapsed, stacked panes, full-width terminal |
|
||||||
|
| Tablet | 600-1024px | Sidebar narrow (180px), stacked SFTP panes |
|
||||||
|
| Desktop | > 1024px | Sidebar normal (240px), side-by-side SFTP panes |
|
||||||
|
| Wide | > 1440px | Sidebar wider (300px), more content visible |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Animations
|
||||||
|
|
||||||
|
| Element | Animation | Duration |
|
||||||
|
|---------|-----------|----------|
|
||||||
|
| Sidebar toggle | Width transition | 200ms ease |
|
||||||
|
| Tab switch | Background fade | 150ms ease |
|
||||||
|
| Modal open | Scale from 0.95 + fade | 200ms ease |
|
||||||
|
| Modal close | Fade out | 150ms ease |
|
||||||
|
| Toast enter | Slide from right | 300ms ease |
|
||||||
|
| Toast exit | Fade out | 200ms ease |
|
||||||
|
| Hover states | Background color | 100ms ease |
|
||||||
|
| Button press | Scale 0.98 | 100ms ease |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Iconography
|
||||||
|
|
||||||
|
**Icon set**: Lucide React (MIT license, Feather-compatible)
|
||||||
|
|
||||||
|
**Common icons**:
|
||||||
|
|
||||||
|
| Icon | Usage |
|
||||||
|
|------|-------|
|
||||||
|
| `Server` | Host item, host form |
|
||||||
|
| `Globe` | Network, hostname |
|
||||||
|
| `Key` | SSH keys |
|
||||||
|
| `Lock` | Vault, security |
|
||||||
|
| `Folder` | Groups, directories |
|
||||||
|
| `File` | Files, snippets |
|
||||||
|
| `Terminal` | Terminal sessions |
|
||||||
|
| `Search` | Search bar |
|
||||||
|
| `Plus` | Add new item |
|
||||||
|
| `Edit` | Edit item |
|
||||||
|
| `Trash` | Delete item |
|
||||||
|
| `Star` | Favorite |
|
||||||
|
| `ChevronRight` | Tree expand |
|
||||||
|
| `ChevronDown` | Tree collapse |
|
||||||
|
| `X` | Close, clear |
|
||||||
|
| `Check` | Success, confirm |
|
||||||
|
| `AlertTriangle` | Warning |
|
||||||
|
| `Info` | Information |
|
||||||
|
| `Settings` | Settings screen |
|
||||||
|
| `Download` | Download file |
|
||||||
|
| `Upload` | Upload file |
|
||||||
|
| `Refresh` | Refresh/reload |
|
||||||
|
| `PanelLeftClose` | Collapse sidebar |
|
||||||
|
| `PanelLeftOpen` | Expand sidebar |
|
||||||
|
|
||||||
|
**Icon sizes**:
|
||||||
|
- Inline text: 14px
|
||||||
|
- Button icon: 16px
|
||||||
|
- Navigation icon: 20px
|
||||||
|
- Large feature icon: 48px
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. CSS Variables
|
||||||
|
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
/* Colors - Dark theme */
|
||||||
|
--bg-primary: #0d1117;
|
||||||
|
--bg-secondary: #161b22;
|
||||||
|
--bg-tertiary: #1c2128;
|
||||||
|
--bg-active: #21262d;
|
||||||
|
|
||||||
|
--border-primary: #30363d;
|
||||||
|
--border-secondary: #21262d;
|
||||||
|
|
||||||
|
--text-primary: #e6edf3;
|
||||||
|
--text-secondary: #8b949e;
|
||||||
|
--text-tertiary: #484f58;
|
||||||
|
|
||||||
|
--accent-primary: #58a6ff;
|
||||||
|
--accent-hover: #79c0ff;
|
||||||
|
|
||||||
|
--success: #3fb950;
|
||||||
|
--warning: #d29922;
|
||||||
|
--error: #f85149;
|
||||||
|
--info: #58a6ff;
|
||||||
|
|
||||||
|
/* Spacing */
|
||||||
|
--space-1: 4px;
|
||||||
|
--space-2: 8px;
|
||||||
|
--space-3: 12px;
|
||||||
|
--space-4: 16px;
|
||||||
|
--space-5: 20px;
|
||||||
|
--space-6: 24px;
|
||||||
|
--space-8: 32px;
|
||||||
|
|
||||||
|
/* Border radius */
|
||||||
|
--radius-sm: 4px;
|
||||||
|
--radius-md: 6px;
|
||||||
|
--radius-lg: 8px;
|
||||||
|
--radius-xl: 12px;
|
||||||
|
|
||||||
|
/* Shadows */
|
||||||
|
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.2);
|
||||||
|
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.3);
|
||||||
|
--shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.4);
|
||||||
|
|
||||||
|
/* Transitions */
|
||||||
|
--transition-fast: 100ms ease;
|
||||||
|
--transition-normal: 200ms ease;
|
||||||
|
--transition-slow: 300ms ease;
|
||||||
|
|
||||||
|
/* Typography */
|
||||||
|
--font-sans: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
|
||||||
|
--font-mono: 'JetBrains Mono', 'Fira Code', monospace;
|
||||||
|
|
||||||
|
--text-xs: 11px;
|
||||||
|
--text-sm: 12px;
|
||||||
|
--text-base: 13px;
|
||||||
|
--text-lg: 14px;
|
||||||
|
--text-xl: 16px;
|
||||||
|
--text-2xl: 20px;
|
||||||
|
|
||||||
|
/* Layout */
|
||||||
|
--sidebar-width: 240px;
|
||||||
|
--sidebar-min: 180px;
|
||||||
|
--sidebar-max: 400px;
|
||||||
|
--tab-height: 36px;
|
||||||
|
--status-height: 24px;
|
||||||
|
--toolbar-height: 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Light theme override */
|
||||||
|
[data-theme="light"] {
|
||||||
|
--bg-primary: #ffffff;
|
||||||
|
--bg-secondary: #f6f8fa;
|
||||||
|
--bg-tertiary: #eaeef2;
|
||||||
|
--bg-active: #d0d7de;
|
||||||
|
|
||||||
|
--border-primary: #d0d7de;
|
||||||
|
--border-secondary: #eaeef2;
|
||||||
|
|
||||||
|
--text-primary: #1f2328;
|
||||||
|
--text-secondary: #656d76;
|
||||||
|
--text-tertiary: #8c959f;
|
||||||
|
|
||||||
|
--accent-primary: #0969da;
|
||||||
|
--accent-hover: #0550ae;
|
||||||
|
|
||||||
|
--success: #1a7f37;
|
||||||
|
--warning: #9a6700;
|
||||||
|
--error: #cf222e;
|
||||||
|
--info: #0969da;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* High contrast theme override */
|
||||||
|
[data-theme="high-contrast"] {
|
||||||
|
--bg-primary: #000000;
|
||||||
|
--bg-secondary: #0a0a0a;
|
||||||
|
--bg-tertiary: #141414;
|
||||||
|
--bg-active: #1a1a1a;
|
||||||
|
|
||||||
|
--border-primary: #ffffff;
|
||||||
|
--border-secondary: #666666;
|
||||||
|
|
||||||
|
--text-primary: #ffffff;
|
||||||
|
--text-secondary: #cccccc;
|
||||||
|
--text-tertiary: #888888;
|
||||||
|
|
||||||
|
--accent-primary: #4da6ff;
|
||||||
|
--accent-hover: #80c8ff;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Responsive Behavior
|
||||||
|
|
||||||
|
### Mobile (< 600px)
|
||||||
|
|
||||||
|
- Sidebar: collapsed by default, hamburger menu to open
|
||||||
|
- SFTP: stacked panes (one at a time)
|
||||||
|
- Terminal: full-width, custom keyboard toolbar
|
||||||
|
- Forms: full-width inputs
|
||||||
|
- Modals: full-width bottom sheet
|
||||||
|
|
||||||
|
### Tablet (600-1024px)
|
||||||
|
|
||||||
|
- Sidebar: narrow (180px), icons + truncated labels
|
||||||
|
- SFTP: stacked or side-by-side (user choice)
|
||||||
|
- Terminal: normal width
|
||||||
|
- Forms: two-column where possible
|
||||||
|
|
||||||
|
### Desktop (> 1024px)
|
||||||
|
|
||||||
|
- Sidebar: normal (240px)
|
||||||
|
- SFTP: side-by-side panes
|
||||||
|
- Terminal: normal
|
||||||
|
- Everything as designed
|
||||||
|
|
||||||
|
### Wide (> 1440px)
|
||||||
|
|
||||||
|
- Sidebar: wider (300px) or user-resized
|
||||||
|
- SFTP: side-by-side with more space
|
||||||
|
- Terminal: extra wide
|
||||||
|
- Settings: side navigation visible
|
||||||
@@ -3,11 +3,21 @@ module git.tukangketik.id/swanadiva/hostkeeper
|
|||||||
go 1.26.4
|
go 1.26.4
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/charmbracelet/bubbles v1.0.0
|
||||||
|
github.com/charmbracelet/bubbletea v1.3.10
|
||||||
|
github.com/charmbracelet/lipgloss v1.1.0
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/pkg/sftp v1.13.7
|
||||||
|
github.com/spf13/cobra v1.10.2
|
||||||
|
github.com/spf13/viper v1.21.0
|
||||||
|
golang.org/x/crypto v0.53.0
|
||||||
|
golang.org/x/term v0.44.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/atotto/clipboard v0.1.4 // indirect
|
||||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||||
github.com/charmbracelet/bubbles v1.0.0 // indirect
|
|
||||||
github.com/charmbracelet/bubbletea v1.3.10 // indirect
|
|
||||||
github.com/charmbracelet/colorprofile v0.4.1 // indirect
|
github.com/charmbracelet/colorprofile v0.4.1 // indirect
|
||||||
github.com/charmbracelet/lipgloss v1.1.0 // indirect
|
|
||||||
github.com/charmbracelet/x/ansi v0.11.6 // indirect
|
github.com/charmbracelet/x/ansi v0.11.6 // indirect
|
||||||
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
|
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
|
||||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||||
@@ -17,8 +27,8 @@ require (
|
|||||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
|
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
|
||||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||||
|
github.com/kr/fs v0.1.0 // indirect
|
||||||
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
|
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/mattn/go-localereader v0.0.1 // indirect
|
github.com/mattn/go-localereader v0.0.1 // indirect
|
||||||
@@ -32,13 +42,10 @@ require (
|
|||||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||||
github.com/spf13/afero v1.15.0 // indirect
|
github.com/spf13/afero v1.15.0 // indirect
|
||||||
github.com/spf13/cast v1.10.0 // indirect
|
github.com/spf13/cast v1.10.0 // indirect
|
||||||
github.com/spf13/cobra v1.10.2 // indirect
|
|
||||||
github.com/spf13/pflag v1.0.10 // indirect
|
github.com/spf13/pflag v1.0.10 // indirect
|
||||||
github.com/spf13/viper v1.21.0 // indirect
|
|
||||||
github.com/subosito/gotenv v1.6.0 // indirect
|
github.com/subosito/gotenv v1.6.0 // indirect
|
||||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||||
golang.org/x/crypto v0.53.0 // indirect
|
|
||||||
golang.org/x/sys v0.46.0 // indirect
|
golang.org/x/sys v0.46.0 // indirect
|
||||||
golang.org/x/text v0.38.0 // indirect
|
golang.org/x/text v0.38.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
||||||
|
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
|
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
|
||||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
|
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
|
||||||
github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc=
|
github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc=
|
||||||
@@ -21,16 +23,29 @@ github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEX
|
|||||||
github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=
|
github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=
|
||||||
github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
|
github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
|
||||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
|
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
|
||||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
||||||
|
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||||
|
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||||
|
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||||
|
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||||
|
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
|
||||||
|
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||||
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
|
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
|
||||||
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
@@ -47,8 +62,14 @@ github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc
|
|||||||
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
|
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||||
|
github.com/pkg/sftp v1.13.7 h1:uv+I3nNJvlKZIQGSr8JVQLNHFU9YhhNpvC14Y6KgmSM=
|
||||||
|
github.com/pkg/sftp v1.13.7/go.mod h1:KMKI0t3T6hfA+lTR/ssZdunHo+uwq7ghoN09/FSu3DY=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||||
|
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||||
|
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
|
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
|
||||||
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
|
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
|
||||||
@@ -65,18 +86,71 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
|||||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
||||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||||
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
|
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
||||||
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
||||||
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
||||||
|
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
|
||||||
|
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
|
||||||
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
|
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
|
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
|
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||||
|
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
|
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||||
|
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||||
|
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
|
||||||
|
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
|
||||||
|
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
|
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||||
|
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
|
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
|
||||||
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
|
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
@@ -50,6 +50,16 @@ type Snippet struct {
|
|||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Profile represents a named configuration profile
|
||||||
|
type Profile struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Theme string `json:"theme"`
|
||||||
|
DefaultGroup string `json:"default_group,omitempty"`
|
||||||
|
DefaultAuth string `json:"default_auth,omitempty"` // "password", "key", "both"
|
||||||
|
Editor string `json:"editor,omitempty"`
|
||||||
|
Notes string `json:"notes,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// AppConfig represents the application configuration
|
// AppConfig represents the application configuration
|
||||||
type AppConfig struct {
|
type AppConfig struct {
|
||||||
Version string `json:"version"`
|
Version string `json:"version"`
|
||||||
@@ -59,6 +69,24 @@ type AppConfig struct {
|
|||||||
Editor string `json:"editor"`
|
Editor string `json:"editor"`
|
||||||
AutoSync bool `json:"auto_sync"`
|
AutoSync bool `json:"auto_sync"`
|
||||||
SyncProvider string `json:"sync_provider,omitempty"`
|
SyncProvider string `json:"sync_provider,omitempty"`
|
||||||
|
|
||||||
|
// Profiles
|
||||||
|
Profiles []Profile `json:"profiles,omitempty"`
|
||||||
|
ActiveProfile string `json:"active_profile,omitempty"`
|
||||||
|
|
||||||
|
// Security
|
||||||
|
EncryptionEnabled bool `json:"encryption_enabled"`
|
||||||
|
PasswordHash string `json:"password_hash,omitempty"` // SHA-256 hash for verification
|
||||||
|
KnownHostsFile string `json:"known_hosts_file,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// KnownHost represents a verified host key
|
||||||
|
type KnownHost struct {
|
||||||
|
Hostname string `json:"hostname"`
|
||||||
|
Port int `json:"port"`
|
||||||
|
KeyType string `json:"key_type"` // "ssh-rsa", "ssh-ed25519", etc.
|
||||||
|
KeyHash string `json:"key_hash"` // Base64-encoded host key
|
||||||
|
AddedAt time.Time `json:"added_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DefaultConfig returns the default application configuration
|
// DefaultConfig returns the default application configuration
|
||||||
@@ -70,5 +98,43 @@ func DefaultConfig() *AppConfig {
|
|||||||
Theme: "dark",
|
Theme: "dark",
|
||||||
Editor: "vim",
|
Editor: "vim",
|
||||||
AutoSync: false,
|
AutoSync: false,
|
||||||
|
EncryptionEnabled: false,
|
||||||
|
Profiles: []Profile{
|
||||||
|
{
|
||||||
|
Name: "default",
|
||||||
|
Theme: "dark",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
ActiveProfile: "default",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetProfile returns a profile by name
|
||||||
|
func (c *AppConfig) GetProfile(name string) *Profile {
|
||||||
|
for i := range c.Profiles {
|
||||||
|
if c.Profiles[i].Name == name {
|
||||||
|
return &c.Profiles[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetActiveProfile returns the active profile
|
||||||
|
func (c *AppConfig) GetActiveProfile() *Profile {
|
||||||
|
return c.GetProfile(c.ActiveProfile)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddProfile adds a new profile
|
||||||
|
func (c *AppConfig) AddProfile(p Profile) {
|
||||||
|
c.Profiles = append(c.Profiles, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveProfile removes a profile by name
|
||||||
|
func (c *AppConfig) RemoveProfile(name string) {
|
||||||
|
for i := range c.Profiles {
|
||||||
|
if c.Profiles[i].Name == name {
|
||||||
|
c.Profiles = append(c.Profiles[:i], c.Profiles[i+1:]...)
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package crypto
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/pbkdf2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
KeyLength = 32 // AES-256
|
||||||
|
SaltLength = 16
|
||||||
|
Iterations = 100000
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrInvalidPassword = errors.New("invalid password")
|
||||||
|
ErrDecryptionFailed = errors.New("decryption failed — wrong password or corrupted data")
|
||||||
|
)
|
||||||
|
|
||||||
|
// DeriveKey derives an AES-256 key from a password using PBKDF2
|
||||||
|
func DeriveKey(password string, salt []byte) []byte {
|
||||||
|
return pbkdf2.Key([]byte(password), salt, Iterations, KeyLength, sha256.New)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encrypt encrypts plaintext using AES-256-GCM with a password
|
||||||
|
func Encrypt(plaintext []byte, password string) (string, error) {
|
||||||
|
salt := make([]byte, SaltLength)
|
||||||
|
if _, err := io.ReadFull(rand.Reader, salt); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
key := DeriveKey(password, salt)
|
||||||
|
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
aesGCM, err := cipher.NewGCM(block)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
nonce := make([]byte, aesGCM.NonceSize())
|
||||||
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
ciphertext := aesGCM.Seal(nil, nonce, plaintext, nil)
|
||||||
|
|
||||||
|
// Format: base64(salt + nonce + ciphertext)
|
||||||
|
result := make([]byte, 0, len(salt)+len(nonce)+len(ciphertext))
|
||||||
|
result = append(result, salt...)
|
||||||
|
result = append(result, nonce...)
|
||||||
|
result = append(result, ciphertext...)
|
||||||
|
|
||||||
|
return base64.StdEncoding.EncodeToString(result), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decrypt decrypts ciphertext using AES-256-GCM with a password
|
||||||
|
func Decrypt(encoded string, password string) ([]byte, error) {
|
||||||
|
data, err := base64.StdEncoding.DecodeString(encoded)
|
||||||
|
if err != nil {
|
||||||
|
return nil, ErrDecryptionFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(data) < SaltLength+12 { // 12 = minimum nonce size for GCM
|
||||||
|
return nil, ErrDecryptionFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
salt := data[:SaltLength]
|
||||||
|
data = data[SaltLength:]
|
||||||
|
|
||||||
|
key := DeriveKey(password, salt)
|
||||||
|
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, ErrDecryptionFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
aesGCM, err := cipher.NewGCM(block)
|
||||||
|
if err != nil {
|
||||||
|
return nil, ErrDecryptionFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
nonceSize := aesGCM.NonceSize()
|
||||||
|
if len(data) < nonceSize {
|
||||||
|
return nil, ErrDecryptionFailed
|
||||||
|
}
|
||||||
|
|
||||||
|
nonce := data[:nonceSize]
|
||||||
|
ciphertext := data[nonceSize:]
|
||||||
|
|
||||||
|
plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, ErrInvalidPassword
|
||||||
|
}
|
||||||
|
|
||||||
|
return plaintext, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsEncrypted checks if a string looks like base64-encoded encrypted data
|
||||||
|
func IsEncrypted(data string) bool {
|
||||||
|
decoded, err := base64.StdEncoding.DecodeString(data)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
// Minimum: 16 (salt) + 12 (nonce) + 16 (min ciphertext) = 44 bytes
|
||||||
|
return len(decoded) >= 44
|
||||||
|
}
|
||||||
|
|
||||||
|
// HashPassword creates a SHA-256 hash of a password for verification
|
||||||
|
func HashPassword(password string) string {
|
||||||
|
h := sha256.Sum256([]byte(password))
|
||||||
|
return base64.StdEncoding.EncodeToString(h[:])
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
package knownhosts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
cryptossh "golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
// KnownHosts manages the known_hosts file
|
||||||
|
type KnownHosts struct {
|
||||||
|
path string
|
||||||
|
hosts map[string]*HostKey // key = "hostname:port"
|
||||||
|
mu sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostKey represents a stored host key
|
||||||
|
type HostKey struct {
|
||||||
|
Hostname string `json:"hostname"`
|
||||||
|
Port int `json:"port"`
|
||||||
|
KeyType string `json:"key_type"`
|
||||||
|
KeyData string `json:"key_data"` // Base64-encoded raw key
|
||||||
|
AddedAt time.Time `json:"added_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a new KnownHosts manager
|
||||||
|
func New(dataDir string) (*KnownHosts, error) {
|
||||||
|
path := filepath.Join(dataDir, "known_hosts")
|
||||||
|
kh := &KnownHosts{
|
||||||
|
path: path,
|
||||||
|
hosts: make(map[string]*HostKey),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := kh.load(); err != nil {
|
||||||
|
// File doesn't exist yet, that's OK
|
||||||
|
if !os.IsNotExist(err) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return kh, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load reads the known_hosts file
|
||||||
|
func (kh *KnownHosts) load() error {
|
||||||
|
kh.mu.Lock()
|
||||||
|
defer kh.mu.Unlock()
|
||||||
|
|
||||||
|
data, err := os.ReadFile(kh.path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var hosts []*HostKey
|
||||||
|
if err := json.Unmarshal(data, &hosts); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, h := range hosts {
|
||||||
|
key := fmt.Sprintf("%s:%d", h.Hostname, h.Port)
|
||||||
|
kh.hosts[key] = h
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save writes the known_hosts file
|
||||||
|
func (kh *KnownHosts) Save() error {
|
||||||
|
kh.mu.Lock()
|
||||||
|
defer kh.mu.Unlock()
|
||||||
|
|
||||||
|
return kh.saveInternal()
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveInternal writes the known_hosts file without locking (caller must hold lock)
|
||||||
|
func (kh *KnownHosts) saveInternal() error {
|
||||||
|
var hosts []*HostKey
|
||||||
|
for _, h := range kh.hosts {
|
||||||
|
hosts = append(hosts, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.MarshalIndent(hosts, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return os.WriteFile(kh.path, data, 0600)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify checks if a host key is known and matches
|
||||||
|
func (kh *KnownHosts) Verify(hostname string, port int, remoteKey cryptossh.PublicKey) (bool, *HostKey) {
|
||||||
|
kh.mu.RLock()
|
||||||
|
defer kh.mu.RUnlock()
|
||||||
|
|
||||||
|
key := fmt.Sprintf("%s:%d", hostname, port)
|
||||||
|
stored, ok := kh.hosts[key]
|
||||||
|
if !ok {
|
||||||
|
return false, nil // Unknown host
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compare key type and data
|
||||||
|
remoteType := remoteKey.Type()
|
||||||
|
remoteData := base64.StdEncoding.EncodeToString(remoteKey.Marshal())
|
||||||
|
|
||||||
|
if stored.KeyType != remoteType || stored.KeyData != remoteData {
|
||||||
|
return false, stored // Key mismatch — potential MITM
|
||||||
|
}
|
||||||
|
|
||||||
|
return true, stored // Key matches
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add stores a new host key
|
||||||
|
func (kh *KnownHosts) Add(hostname string, port int, remoteKey cryptossh.PublicKey) error {
|
||||||
|
kh.mu.Lock()
|
||||||
|
defer kh.mu.Unlock()
|
||||||
|
|
||||||
|
key := fmt.Sprintf("%s:%d", hostname, port)
|
||||||
|
kh.hosts[key] = &HostKey{
|
||||||
|
Hostname: hostname,
|
||||||
|
Port: port,
|
||||||
|
KeyType: remoteKey.Type(),
|
||||||
|
KeyData: base64.StdEncoding.EncodeToString(remoteKey.Marshal()),
|
||||||
|
AddedAt: time.Now(),
|
||||||
|
}
|
||||||
|
|
||||||
|
return kh.saveInternal()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove removes a host key
|
||||||
|
func (kh *KnownHosts) Remove(hostname string, port int) error {
|
||||||
|
kh.mu.Lock()
|
||||||
|
defer kh.mu.Unlock()
|
||||||
|
|
||||||
|
key := fmt.Sprintf("%s:%d", hostname, port)
|
||||||
|
delete(kh.hosts, key)
|
||||||
|
|
||||||
|
return kh.saveInternal()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns the stored host key for a given host
|
||||||
|
func (kh *KnownHosts) Get(hostname string, port int) *HostKey {
|
||||||
|
kh.mu.RLock()
|
||||||
|
defer kh.mu.RUnlock()
|
||||||
|
|
||||||
|
key := fmt.Sprintf("%s:%d", hostname, port)
|
||||||
|
return kh.hosts[key]
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostKeyCallback returns a crypto/ssh HostKeyCallback for use in SSH config
|
||||||
|
func (kh *KnownHosts) HostKeyCallback(autoAdd bool) cryptossh.HostKeyCallback {
|
||||||
|
return func(hostname string, remote net.Addr, remoteKey cryptossh.PublicKey) error {
|
||||||
|
// Extract port from address
|
||||||
|
_, portStr, err := net.SplitHostPort(remote.String())
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to parse address: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
port := 22
|
||||||
|
fmt.Sscanf(portStr, "%d", &port)
|
||||||
|
|
||||||
|
// Check if host is known
|
||||||
|
matches, stored := kh.Verify(hostname, port, remoteKey)
|
||||||
|
if matches {
|
||||||
|
return nil // Key matches, connection OK
|
||||||
|
}
|
||||||
|
|
||||||
|
if stored == nil {
|
||||||
|
// Unknown host — auto-add if enabled
|
||||||
|
if autoAdd {
|
||||||
|
if err := kh.Add(hostname, port, remoteKey); err != nil {
|
||||||
|
return fmt.Errorf("failed to add host key: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return fmt.Errorf("host key not found for %s:%d — run 'hostkeeper trust %s' to add", hostname, port, hostname)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Key mismatch — potential MITM attack
|
||||||
|
return fmt.Errorf("WARNING: host key mismatch for %s:%d!\n"+
|
||||||
|
"Stored key type: %s\n"+
|
||||||
|
"Remote key type: %s\n"+
|
||||||
|
"This could indicate a MITM attack.\n"+
|
||||||
|
"Run 'hostkeeper trust --remove %s' and try again.",
|
||||||
|
hostname, port, stored.KeyType, remoteKey.Type(), hostname)
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
-1
@@ -79,10 +79,20 @@ func (c *Client) getKeySigner() (cryptossh.Signer, error) {
|
|||||||
return nil, fmt.Errorf("failed to read key file %s: %w", keyPath, err)
|
return nil, fmt.Errorf("failed to read key file %s: %w", keyPath, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the key (support passphrase-protected keys in Phase 2)
|
// Parse the key (support passphrase-protected keys)
|
||||||
var signer cryptossh.Signer
|
var signer cryptossh.Signer
|
||||||
if c.host.Auth.Password != "" {
|
if c.host.Auth.Password != "" {
|
||||||
signer, err = cryptossh.ParsePrivateKeyWithPassphrase(keyData, []byte(c.host.Auth.Password))
|
signer, err = cryptossh.ParsePrivateKeyWithPassphrase(keyData, []byte(c.host.Auth.Password))
|
||||||
|
} else if c.passphraseCallback != nil {
|
||||||
|
// Try without passphrase first
|
||||||
|
signer, err = cryptossh.ParsePrivateKey(keyData)
|
||||||
|
if err != nil && strings.Contains(err.Error(), "encrypted") {
|
||||||
|
// Key is encrypted, prompt for passphrase
|
||||||
|
passphrase := c.passphraseCallback()
|
||||||
|
if passphrase != "" {
|
||||||
|
signer, err = cryptossh.ParsePrivateKeyWithPassphrase(keyData, []byte(passphrase))
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
signer, err = cryptossh.ParsePrivateKey(keyData)
|
signer, err = cryptossh.ParsePrivateKey(keyData)
|
||||||
}
|
}
|
||||||
|
|||||||
+104
-5
@@ -4,8 +4,13 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/term"
|
||||||
|
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/errors"
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/errors"
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
cryptossh "golang.org/x/crypto/ssh"
|
cryptossh "golang.org/x/crypto/ssh"
|
||||||
@@ -13,10 +18,12 @@ import (
|
|||||||
|
|
||||||
// Client represents an SSH client
|
// Client represents an SSH client
|
||||||
type Client struct {
|
type Client struct {
|
||||||
host *models.Host
|
host *models.Host
|
||||||
timeout time.Duration
|
timeout time.Duration
|
||||||
client *cryptossh.Client
|
client *cryptossh.Client
|
||||||
config *cryptossh.ClientConfig
|
config *cryptossh.ClientConfig
|
||||||
|
hostKeyCallback cryptossh.HostKeyCallback
|
||||||
|
passphraseCallback func() string // called to get passphrase for encrypted keys
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient creates a new SSH client
|
// NewClient creates a new SSH client
|
||||||
@@ -27,6 +34,16 @@ func NewClient(host *models.Host, timeout time.Duration) *Client {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetHostKeyCallback sets the host key verification callback
|
||||||
|
func (c *Client) SetHostKeyCallback(cb cryptossh.HostKeyCallback) {
|
||||||
|
c.hostKeyCallback = cb
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetPassphraseCallback sets the callback for getting key passphrases
|
||||||
|
func (c *Client) SetPassphraseCallback(cb func() string) {
|
||||||
|
c.passphraseCallback = cb
|
||||||
|
}
|
||||||
|
|
||||||
// Connect establishes an SSH connection
|
// Connect establishes an SSH connection
|
||||||
func (c *Client) Connect(ctx context.Context) error {
|
func (c *Client) Connect(ctx context.Context) error {
|
||||||
// Create SSH configuration
|
// Create SSH configuration
|
||||||
@@ -64,9 +81,14 @@ func (c *Client) dialTCP(ctx context.Context, address string) (net.Conn, error)
|
|||||||
|
|
||||||
// setupConfig creates SSH client configuration
|
// setupConfig creates SSH client configuration
|
||||||
func (c *Client) setupConfig() error {
|
func (c *Client) setupConfig() error {
|
||||||
|
hostKeyCallback := cryptossh.InsecureIgnoreHostKey()
|
||||||
|
if c.hostKeyCallback != nil {
|
||||||
|
hostKeyCallback = c.hostKeyCallback
|
||||||
|
}
|
||||||
|
|
||||||
config := &cryptossh.ClientConfig{
|
config := &cryptossh.ClientConfig{
|
||||||
User: c.host.Username,
|
User: c.host.Username,
|
||||||
HostKeyCallback: cryptossh.InsecureIgnoreHostKey(), //nolint:gosec // Phase 1 - will be improved in Phase 2
|
HostKeyCallback: hostKeyCallback,
|
||||||
Timeout: c.timeout,
|
Timeout: c.timeout,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,6 +123,83 @@ func (c *Client) Execute(_ context.Context, cmd string) (string, error) {
|
|||||||
return string(output), nil
|
return string(output), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Shell opens an interactive shell session
|
||||||
|
func (c *Client) Shell() error {
|
||||||
|
if c.client == nil {
|
||||||
|
return fmt.Errorf("not connected to server")
|
||||||
|
}
|
||||||
|
|
||||||
|
session, err := c.client.NewSession()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create session: %w", err)
|
||||||
|
}
|
||||||
|
defer session.Close()
|
||||||
|
|
||||||
|
// Get current terminal state
|
||||||
|
fd := int(os.Stdin.Fd())
|
||||||
|
oldState, err := term.MakeRaw(fd)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to set raw terminal: %w", err)
|
||||||
|
}
|
||||||
|
defer term.Restore(fd, oldState)
|
||||||
|
|
||||||
|
// Set up terminal modes
|
||||||
|
modes := cryptossh.TerminalModes{
|
||||||
|
cryptossh.ECHO: 1,
|
||||||
|
cryptossh.TTY_OP_ISPEED: 14400,
|
||||||
|
cryptossh.TTY_OP_OSPEED: 14400,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get terminal size
|
||||||
|
width, height, err := term.GetSize(fd)
|
||||||
|
if err != nil {
|
||||||
|
width = 80
|
||||||
|
height = 24
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request PTY
|
||||||
|
if err := session.RequestPty("xterm-256color", height, width, modes); err != nil {
|
||||||
|
return fmt.Errorf("failed to request PTY: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle window changes
|
||||||
|
sigwinch := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sigwinch, os.Signal(syscall.SIGWINCH))
|
||||||
|
go func() {
|
||||||
|
for range sigwinch {
|
||||||
|
w, h, err := term.GetSize(fd)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
session.WindowChange(h, w)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
defer signal.Stop(sigwinch)
|
||||||
|
|
||||||
|
// Link I/O
|
||||||
|
session.Stdin = os.Stdin
|
||||||
|
session.Stdout = os.Stdout
|
||||||
|
session.Stderr = os.Stderr
|
||||||
|
|
||||||
|
// Start shell
|
||||||
|
if err := session.Shell(); err != nil {
|
||||||
|
return fmt.Errorf("failed to start shell: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for shell to exit
|
||||||
|
if err := session.Wait(); err != nil {
|
||||||
|
if exitErr, ok := err.(*cryptossh.ExitError); ok {
|
||||||
|
if exitErr.ExitStatus() != 0 {
|
||||||
|
return fmt.Errorf("shell exited with status %d", exitErr.ExitStatus())
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return fmt.Errorf("shell session error: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// Close closes the SSH connection
|
// Close closes the SSH connection
|
||||||
func (c *Client) Close() error {
|
func (c *Client) Close() error {
|
||||||
if c.client != nil {
|
if c.client != nil {
|
||||||
|
|||||||
@@ -7,14 +7,19 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/crypto"
|
||||||
)
|
)
|
||||||
|
|
||||||
// JSONStorage implements Storage interface using JSON files
|
// JSONStorage implements Storage interface using JSON files
|
||||||
type JSONStorage struct {
|
type JSONStorage struct {
|
||||||
dataDir string
|
dataDir string
|
||||||
mu sync.RWMutex
|
password string // master password for encryption (empty = no encryption)
|
||||||
|
mu sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewJSONStorage creates a new JSON storage instance
|
// NewJSONStorage creates a new JSON storage instance
|
||||||
@@ -32,6 +37,31 @@ func NewJSONStorage(dataDir string) (*JSONStorage, error) {
|
|||||||
return s, nil
|
return s, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetPassword sets the master password for encryption/decryption
|
||||||
|
func (s *JSONStorage) SetPassword(password string) {
|
||||||
|
s.password = password
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPassword returns the current master password
|
||||||
|
func (s *JSONStorage) GetPassword() string {
|
||||||
|
return s.password
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsEncrypted returns whether encryption is enabled
|
||||||
|
func (s *JSONStorage) IsEncrypted() bool {
|
||||||
|
return s.password != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsDataEncrypted checks if the data files are actually encrypted
|
||||||
|
func (s *JSONStorage) IsDataEncrypted() bool {
|
||||||
|
path := filepath.Join(s.dataDir, "hosts.json")
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return crypto.IsEncrypted(string(data))
|
||||||
|
}
|
||||||
|
|
||||||
func (s *JSONStorage) ensureDataFiles() error {
|
func (s *JSONStorage) ensureDataFiles() error {
|
||||||
files := map[string]string{
|
files := map[string]string{
|
||||||
"hosts.json": "hosts",
|
"hosts.json": "hosts",
|
||||||
@@ -100,6 +130,14 @@ func (s *JSONStorage) SaveHost(ctx context.Context, host *models.Host) error {
|
|||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
if host.ID == "" {
|
||||||
|
host.ID = uuid.New().String()
|
||||||
|
}
|
||||||
|
if host.CreatedAt.IsZero() {
|
||||||
|
host.CreatedAt = time.Now()
|
||||||
|
}
|
||||||
|
host.UpdatedAt = time.Now()
|
||||||
|
|
||||||
hosts, err := s.listHostsInternal()
|
hosts, err := s.listHostsInternal()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -151,6 +189,15 @@ func (s *JSONStorage) replaceHosts(hosts []*models.Host) error {
|
|||||||
return fmt.Errorf("failed to marshal hosts: %w", err)
|
return fmt.Errorf("failed to marshal hosts: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Encrypt if password is set
|
||||||
|
if s.password != "" {
|
||||||
|
encrypted, err := crypto.Encrypt(bytes, s.password)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to encrypt hosts: %w", err)
|
||||||
|
}
|
||||||
|
bytes = []byte(encrypted)
|
||||||
|
}
|
||||||
|
|
||||||
return os.WriteFile(s.getHostsPath(), bytes, 0600)
|
return os.WriteFile(s.getHostsPath(), bytes, 0600)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,6 +249,14 @@ func (s *JSONStorage) SaveKeyPair(ctx context.Context, keyPair *models.KeyPair)
|
|||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
if keyPair.ID == "" {
|
||||||
|
keyPair.ID = uuid.New().String()
|
||||||
|
}
|
||||||
|
if keyPair.CreatedAt.IsZero() {
|
||||||
|
keyPair.CreatedAt = time.Now()
|
||||||
|
}
|
||||||
|
keyPair.UpdatedAt = time.Now()
|
||||||
|
|
||||||
keys, err := s.listKeyPairsInternal()
|
keys, err := s.listKeyPairsInternal()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -253,6 +308,15 @@ func (s *JSONStorage) replaceKeyPairs(keys []*models.KeyPair) error {
|
|||||||
return fmt.Errorf("failed to marshal key pairs: %w", err)
|
return fmt.Errorf("failed to marshal key pairs: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Encrypt if password is set
|
||||||
|
if s.password != "" {
|
||||||
|
encrypted, err := crypto.Encrypt(bytes, s.password)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to encrypt key pairs: %w", err)
|
||||||
|
}
|
||||||
|
bytes = []byte(encrypted)
|
||||||
|
}
|
||||||
|
|
||||||
return os.WriteFile(s.getKeysPath(), bytes, 0600)
|
return os.WriteFile(s.getKeysPath(), bytes, 0600)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,6 +368,14 @@ func (s *JSONStorage) SaveSnippet(ctx context.Context, snippet *models.Snippet)
|
|||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
|
|
||||||
|
if snippet.ID == "" {
|
||||||
|
snippet.ID = uuid.New().String()
|
||||||
|
}
|
||||||
|
if snippet.CreatedAt.IsZero() {
|
||||||
|
snippet.CreatedAt = time.Now()
|
||||||
|
}
|
||||||
|
snippet.UpdatedAt = time.Now()
|
||||||
|
|
||||||
snippets, err := s.listSnippetsInternal()
|
snippets, err := s.listSnippetsInternal()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -355,6 +427,15 @@ func (s *JSONStorage) replaceSnippets(snippets []*models.Snippet) error {
|
|||||||
return fmt.Errorf("failed to marshal snippets: %w", err)
|
return fmt.Errorf("failed to marshal snippets: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Encrypt if password is set
|
||||||
|
if s.password != "" {
|
||||||
|
encrypted, err := crypto.Encrypt(bytes, s.password)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to encrypt snippets: %w", err)
|
||||||
|
}
|
||||||
|
bytes = []byte(encrypted)
|
||||||
|
}
|
||||||
|
|
||||||
return os.WriteFile(s.getSnippetsPath(), bytes, 0600)
|
return os.WriteFile(s.getSnippetsPath(), bytes, 0600)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -481,5 +562,15 @@ func (s *JSONStorage) readJSON(path string, v interface{}) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Decrypt if password is set and data looks encrypted
|
||||||
|
if s.password != "" && crypto.IsEncrypted(string(data)) {
|
||||||
|
decrypted, err := crypto.Decrypt(string(data), s.password)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("decryption failed: %w", err)
|
||||||
|
}
|
||||||
|
data = decrypted
|
||||||
|
}
|
||||||
|
|
||||||
return json.Unmarshal(data, v)
|
return json.Unmarshal(data, v)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrorSeverity indicates the level of an error message
|
||||||
|
type ErrorSeverity int
|
||||||
|
|
||||||
|
const (
|
||||||
|
SevError ErrorSeverity = iota
|
||||||
|
SevWarning
|
||||||
|
SevInfo
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrorBanner displays a structured error message with title, details, and hints
|
||||||
|
type ErrorBanner struct {
|
||||||
|
Title string
|
||||||
|
Detail string
|
||||||
|
Hints []string
|
||||||
|
Severity ErrorSeverity
|
||||||
|
AutoDismiss bool
|
||||||
|
DismissAfter time.Duration
|
||||||
|
createdAt time.Time
|
||||||
|
visible bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewErrorBanner creates a new error banner with the given severity
|
||||||
|
func NewErrorBanner(severity ErrorSeverity) *ErrorBanner {
|
||||||
|
return &ErrorBanner{
|
||||||
|
Severity: severity,
|
||||||
|
AutoDismiss: true,
|
||||||
|
DismissAfter: 5 * time.Second,
|
||||||
|
visible: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show displays the error banner with the given message
|
||||||
|
func (b *ErrorBanner) Show(title, detail string, hints ...string) {
|
||||||
|
b.Title = title
|
||||||
|
b.Detail = detail
|
||||||
|
b.Hints = hints
|
||||||
|
b.visible = true
|
||||||
|
b.createdAt = time.Now()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hide hides the error banner
|
||||||
|
func (b *ErrorBanner) Hide() {
|
||||||
|
b.visible = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsVisible returns whether the banner is currently visible
|
||||||
|
func (b *ErrorBanner) IsVisible() bool {
|
||||||
|
return b.visible
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update checks if auto-dismiss time has elapsed
|
||||||
|
func (b *ErrorBanner) Update() {
|
||||||
|
if b.visible && b.AutoDismiss && time.Since(b.createdAt) > b.DismissAfter {
|
||||||
|
b.visible = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// View renders the error banner
|
||||||
|
func (b *ErrorBanner) View(width int) string {
|
||||||
|
if !b.visible {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
titleStyle lipgloss.Style
|
||||||
|
borderColor lipgloss.Color
|
||||||
|
prefix string
|
||||||
|
)
|
||||||
|
|
||||||
|
switch b.Severity {
|
||||||
|
case SevError:
|
||||||
|
titleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#ea6962")).Bold(true)
|
||||||
|
borderColor = lipgloss.Color("#ea6962")
|
||||||
|
prefix = "✖"
|
||||||
|
case SevWarning:
|
||||||
|
titleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#d8a657")).Bold(true)
|
||||||
|
borderColor = lipgloss.Color("#d8a657")
|
||||||
|
prefix = "⚠"
|
||||||
|
case SevInfo:
|
||||||
|
titleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#7daea3")).Bold(true)
|
||||||
|
borderColor = lipgloss.Color("#7daea3")
|
||||||
|
prefix = "ℹ"
|
||||||
|
}
|
||||||
|
|
||||||
|
var sb strings.Builder
|
||||||
|
|
||||||
|
// Title line with prefix
|
||||||
|
sb.WriteString(titleStyle.Render(fmt.Sprintf("%s %s", prefix, b.Title)))
|
||||||
|
|
||||||
|
// Detail line
|
||||||
|
if b.Detail != "" {
|
||||||
|
sb.WriteString("\n")
|
||||||
|
sb.WriteString(strings.Repeat(" ", len(prefix)+1))
|
||||||
|
detailStyle := lipgloss.NewStyle().Foreground(activeTheme.Fg)
|
||||||
|
sb.WriteString(detailStyle.Render(b.Detail))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hints
|
||||||
|
if len(b.Hints) > 0 {
|
||||||
|
sb.WriteString("\n")
|
||||||
|
sb.WriteString(strings.Repeat(" ", len(prefix)+1))
|
||||||
|
hintStyle := lipgloss.NewStyle().Foreground(activeTheme.FgMute)
|
||||||
|
sb.WriteString(hintStyle.Render("Hints:"))
|
||||||
|
for i, hint := range b.Hints {
|
||||||
|
sb.WriteString("\n")
|
||||||
|
sb.WriteString(strings.Repeat(" ", len(prefix)+2))
|
||||||
|
sb.WriteString(hintStyle.Render(fmt.Sprintf("%d. %s", i+1, hint)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wrap in a styled box
|
||||||
|
borderStyle := lipgloss.NewStyle().
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(borderColor).
|
||||||
|
Padding(0, 1).
|
||||||
|
Width(min(width-2, 80))
|
||||||
|
|
||||||
|
return borderStyle.Render(sb.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// min returns the smaller of two integers
|
||||||
|
func min(a, b int) int {
|
||||||
|
if a < b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
@@ -0,0 +1,374 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/textinput"
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type formMode int
|
||||||
|
|
||||||
|
const (
|
||||||
|
formModeAdd formMode = iota
|
||||||
|
formModeEdit
|
||||||
|
)
|
||||||
|
|
||||||
|
type fieldID int
|
||||||
|
|
||||||
|
const (
|
||||||
|
fieldName fieldID = iota
|
||||||
|
fieldHostname
|
||||||
|
fieldPort
|
||||||
|
fieldUsername
|
||||||
|
fieldAuthType
|
||||||
|
fieldPassword
|
||||||
|
fieldGroup
|
||||||
|
fieldTags
|
||||||
|
fieldNotes
|
||||||
|
fieldCount
|
||||||
|
)
|
||||||
|
|
||||||
|
var fieldLabels = map[fieldID]string{
|
||||||
|
fieldName: "Name",
|
||||||
|
fieldHostname: "Hostname",
|
||||||
|
fieldPort: "Port",
|
||||||
|
fieldUsername: "Username",
|
||||||
|
fieldAuthType: "Auth Type",
|
||||||
|
fieldPassword: "Password",
|
||||||
|
fieldGroup: "Group",
|
||||||
|
fieldTags: "Tags",
|
||||||
|
fieldNotes: "Notes",
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostFormTab is a tab for adding/editing hosts
|
||||||
|
type HostFormTab struct {
|
||||||
|
mode formMode
|
||||||
|
editing *models.Host
|
||||||
|
dataDir string
|
||||||
|
|
||||||
|
inputs []textinput.Model
|
||||||
|
focus fieldID
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
|
||||||
|
err error
|
||||||
|
saved bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewAddHostFormTab creates a new host add form tab
|
||||||
|
func NewAddHostFormTab(dataDir string) *HostFormTab {
|
||||||
|
return newHostFormTab(formModeAdd, nil, dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewEditHostFormTab creates a new host edit form tab
|
||||||
|
func NewEditHostFormTab(host *models.Host, dataDir string) *HostFormTab {
|
||||||
|
return newHostFormTab(formModeEdit, host, dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newHostFormTab(mode formMode, host *models.Host, dataDir string) *HostFormTab {
|
||||||
|
inputs := make([]textinput.Model, fieldCount)
|
||||||
|
|
||||||
|
for i := range inputs {
|
||||||
|
inputs[i] = textinput.New()
|
||||||
|
inputs[i].Prompt = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
inputs[fieldName].Placeholder = "My Server"
|
||||||
|
inputs[fieldHostname].Placeholder = "192.168.1.1 or server.example.com"
|
||||||
|
inputs[fieldPort].Placeholder = "22"
|
||||||
|
inputs[fieldPort].SetValue("22")
|
||||||
|
inputs[fieldUsername].Placeholder = "root"
|
||||||
|
inputs[fieldAuthType].SetValue("password")
|
||||||
|
inputs[fieldPassword].EchoMode = textinput.EchoPassword
|
||||||
|
inputs[fieldPassword].Placeholder = "Enter password"
|
||||||
|
inputs[fieldGroup].Placeholder = "production"
|
||||||
|
inputs[fieldTags].Placeholder = "web,backend"
|
||||||
|
inputs[fieldNotes].Placeholder = "Optional notes..."
|
||||||
|
|
||||||
|
if mode == formModeEdit && host != nil {
|
||||||
|
inputs[fieldName].SetValue(host.Name)
|
||||||
|
inputs[fieldHostname].SetValue(host.Hostname)
|
||||||
|
inputs[fieldPort].SetValue(strconv.Itoa(host.Port))
|
||||||
|
inputs[fieldUsername].SetValue(host.Username)
|
||||||
|
inputs[fieldAuthType].SetValue(host.Auth.Type)
|
||||||
|
if host.Auth.Password != "" {
|
||||||
|
inputs[fieldPassword].SetValue(host.Auth.Password)
|
||||||
|
}
|
||||||
|
inputs[fieldGroup].SetValue(host.Group)
|
||||||
|
inputs[fieldTags].SetValue(strings.Join(host.Tags, ","))
|
||||||
|
inputs[fieldNotes].SetValue(host.Notes)
|
||||||
|
}
|
||||||
|
|
||||||
|
inputs[fieldName].Focus()
|
||||||
|
inputs[fieldName].Prompt = "> "
|
||||||
|
|
||||||
|
return &HostFormTab{
|
||||||
|
mode: mode,
|
||||||
|
editing: host,
|
||||||
|
dataDir: dataDir,
|
||||||
|
inputs: inputs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *HostFormTab) Name() string {
|
||||||
|
if t.mode == formModeEdit {
|
||||||
|
return "Edit: " + t.editing.Name
|
||||||
|
}
|
||||||
|
return "Add Host"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *HostFormTab) Init() tea.Cmd {
|
||||||
|
return textinput.Blink
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *HostFormTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||||
|
if t.saved {
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
t.width = msg.Width
|
||||||
|
t.height = msg.Height
|
||||||
|
|
||||||
|
case tea.KeyMsg:
|
||||||
|
switch msg.String() {
|
||||||
|
case "esc":
|
||||||
|
return t, func() tea.Msg { return closeFormMsg{} }
|
||||||
|
|
||||||
|
case "enter":
|
||||||
|
if t.focus == fieldAuthType {
|
||||||
|
t.toggleAuthType()
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
if t.focus == fieldCount-1 {
|
||||||
|
return t.submit()
|
||||||
|
}
|
||||||
|
t.nextField()
|
||||||
|
|
||||||
|
case " ", "left", "right":
|
||||||
|
if t.focus == fieldAuthType {
|
||||||
|
t.toggleAuthType()
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
// pass through to text input (allow typing spaces, cursor nav)
|
||||||
|
var cmd tea.Cmd
|
||||||
|
t.inputs[t.focus], cmd = t.inputs[t.focus].Update(msg)
|
||||||
|
return t, cmd
|
||||||
|
|
||||||
|
case "tab", "down":
|
||||||
|
t.nextField()
|
||||||
|
|
||||||
|
case "shift+tab", "up":
|
||||||
|
t.prevField()
|
||||||
|
|
||||||
|
case "ctrl+s":
|
||||||
|
return t.submit()
|
||||||
|
|
||||||
|
default:
|
||||||
|
if t.focus == fieldAuthType {
|
||||||
|
// ignore typing on auth type field
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
var cmd tea.Cmd
|
||||||
|
t.inputs[t.focus], cmd = t.inputs[t.focus].Update(msg)
|
||||||
|
return t, cmd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *HostFormTab) nextField() {
|
||||||
|
t.inputs[t.focus].Blur()
|
||||||
|
t.inputs[t.focus].Prompt = ""
|
||||||
|
t.focus++
|
||||||
|
if t.focus >= fieldCount {
|
||||||
|
t.focus = fieldCount - 1
|
||||||
|
}
|
||||||
|
t.inputs[t.focus].Focus()
|
||||||
|
t.inputs[t.focus].Prompt = "> "
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *HostFormTab) prevField() {
|
||||||
|
t.inputs[t.focus].Blur()
|
||||||
|
t.inputs[t.focus].Prompt = ""
|
||||||
|
t.focus--
|
||||||
|
if t.focus < 0 {
|
||||||
|
t.focus = 0
|
||||||
|
}
|
||||||
|
t.inputs[t.focus].Focus()
|
||||||
|
t.inputs[t.focus].Prompt = "> "
|
||||||
|
}
|
||||||
|
|
||||||
|
func cycleAuthType(current string) string {
|
||||||
|
switch current {
|
||||||
|
case "password":
|
||||||
|
return "key"
|
||||||
|
case "key":
|
||||||
|
return "password"
|
||||||
|
default:
|
||||||
|
return "password"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *HostFormTab) toggleAuthType() {
|
||||||
|
current := t.inputs[fieldAuthType].Value()
|
||||||
|
t.inputs[fieldAuthType].SetValue(cycleAuthType(current))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *HostFormTab) submit() (Tab, tea.Cmd) {
|
||||||
|
name := t.inputs[fieldName].Value()
|
||||||
|
hostname := t.inputs[fieldHostname].Value()
|
||||||
|
username := t.inputs[fieldUsername].Value()
|
||||||
|
|
||||||
|
if name == "" || hostname == "" || username == "" {
|
||||||
|
t.err = fmt.Errorf("name, hostname, and username are required")
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
port := 22
|
||||||
|
if p := t.inputs[fieldPort].Value(); p != "" {
|
||||||
|
if parsed, err := strconv.Atoi(p); err == nil && parsed > 0 {
|
||||||
|
port = parsed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
authType := t.inputs[fieldAuthType].Value()
|
||||||
|
if authType == "" {
|
||||||
|
authType = "password"
|
||||||
|
}
|
||||||
|
|
||||||
|
var tags []string
|
||||||
|
if tagStr := t.inputs[fieldTags].Value(); tagStr != "" {
|
||||||
|
for _, tag := range strings.Split(tagStr, ",") {
|
||||||
|
if trimmed := strings.TrimSpace(tag); trimmed != "" {
|
||||||
|
tags = append(tags, trimmed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var host *models.Host
|
||||||
|
if t.mode == formModeEdit && t.editing != nil {
|
||||||
|
host = t.editing
|
||||||
|
host.Name = name
|
||||||
|
host.Hostname = hostname
|
||||||
|
host.Port = port
|
||||||
|
host.Username = username
|
||||||
|
host.Auth.Type = authType
|
||||||
|
host.Auth.Password = t.inputs[fieldPassword].Value()
|
||||||
|
host.Group = t.inputs[fieldGroup].Value()
|
||||||
|
host.Tags = tags
|
||||||
|
host.Notes = t.inputs[fieldNotes].Value()
|
||||||
|
} else {
|
||||||
|
host = &models.Host{
|
||||||
|
ID: uuid.New().String(),
|
||||||
|
Name: name,
|
||||||
|
Hostname: hostname,
|
||||||
|
Port: port,
|
||||||
|
Username: username,
|
||||||
|
Auth: models.AuthConfig{
|
||||||
|
Type: authType,
|
||||||
|
Password: t.inputs[fieldPassword].Value(),
|
||||||
|
},
|
||||||
|
Group: t.inputs[fieldGroup].Value(),
|
||||||
|
Tags: tags,
|
||||||
|
Notes: t.inputs[fieldNotes].Value(),
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
UpdatedAt: time.Now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.saved = true
|
||||||
|
return t, saveHostCmd(host, t.dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *HostFormTab) View() string {
|
||||||
|
contentW := t.width - 12
|
||||||
|
if contentW < 30 {
|
||||||
|
contentW = 30
|
||||||
|
}
|
||||||
|
if contentW > 70 {
|
||||||
|
contentW = 70
|
||||||
|
}
|
||||||
|
|
||||||
|
var inner strings.Builder
|
||||||
|
|
||||||
|
title := "Add New Host"
|
||||||
|
if t.mode == formModeEdit {
|
||||||
|
title = "Edit Host"
|
||||||
|
}
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||||
|
lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(title)))
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
|
||||||
|
if t.err != nil {
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||||
|
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := fieldID(0); i < fieldCount; i++ {
|
||||||
|
input := t.inputs[i]
|
||||||
|
|
||||||
|
label := fieldLabels[i]
|
||||||
|
style := SubtitleStyle
|
||||||
|
if i == t.focus {
|
||||||
|
style = HighlightStyle
|
||||||
|
}
|
||||||
|
inner.WriteString(style.Render(label + ":"))
|
||||||
|
inner.WriteString("\n")
|
||||||
|
|
||||||
|
if i == fieldAuthType {
|
||||||
|
current := input.Value()
|
||||||
|
pills := []string{"password", "key"}
|
||||||
|
var parts []string
|
||||||
|
for _, p := range pills {
|
||||||
|
if p == current {
|
||||||
|
if i == t.focus {
|
||||||
|
parts = append(parts, SelectedStyle.Render(" "+p+" "))
|
||||||
|
} else {
|
||||||
|
parts = append(parts, TagStyle.Render(" "+p+" "))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
parts = append(parts, SubtitleStyle.Render(" "+p+" "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inner.WriteString(" ")
|
||||||
|
inner.WriteString(strings.Join(parts, " "))
|
||||||
|
inner.WriteString("\n")
|
||||||
|
if i == t.focus {
|
||||||
|
inner.WriteString(" " + InfoStyle.Render("Space/←/→ to toggle"))
|
||||||
|
}
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
} else {
|
||||||
|
renderedInput := input.View()
|
||||||
|
inner.WriteString(" ")
|
||||||
|
inner.WriteString(renderedInput)
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inner.WriteString("\n")
|
||||||
|
footerText := "Ctrl+Tab:switch Ctrl+Q:close Tab:next Shift+Tab:prev ↑↓:nav Enter:next Ctrl+S:save Esc:cancel"
|
||||||
|
footerWrapped := wrapFooter(footerText, contentW)
|
||||||
|
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||||
|
inner.WriteString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
box := BorderStyle.Render(inner.String())
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *HostFormTab) Close() {}
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
package tui
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/charmbracelet/lipgloss"
|
|
||||||
|
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
HostNameStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("226")).Bold(true)
|
|
||||||
HostDetailStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("245"))
|
|
||||||
SelectedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("212")).Background(lipgloss.Color("235")).Padding(0, 1)
|
|
||||||
TagStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("86"))
|
|
||||||
)
|
|
||||||
|
|
||||||
// renderHostList renders the host list screen
|
|
||||||
func renderHostList(m *Model) string {
|
|
||||||
var b strings.Builder
|
|
||||||
|
|
||||||
b.WriteString(TitleStyle.Render("HOSTKEEPER - SSH Manager"))
|
|
||||||
b.WriteString("\n\n")
|
|
||||||
|
|
||||||
if len(m.Hosts) == 0 {
|
|
||||||
b.WriteString(SubtitleStyle.Render("No hosts found. Add your first host with: hostkeeper add"))
|
|
||||||
b.WriteString("\n\n")
|
|
||||||
b.WriteString(InfoStyle.Render("Press 'q' to quit"))
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
for i, host := range m.Hosts {
|
|
||||||
if i == m.SelectedIndex {
|
|
||||||
b.WriteString(renderSelectedHost(host))
|
|
||||||
} else {
|
|
||||||
b.WriteString(renderHost(host))
|
|
||||||
}
|
|
||||||
b.WriteString("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
b.WriteString("\n")
|
|
||||||
b.WriteString(SubtitleStyle.Render("\u2191\u2193: Navigate | Enter: Connect | q: Quit"))
|
|
||||||
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// renderHost renders a single host
|
|
||||||
func renderHost(host *models.Host) string {
|
|
||||||
var b strings.Builder
|
|
||||||
|
|
||||||
b.WriteString(HostNameStyle.Render(host.Name))
|
|
||||||
b.WriteString("\n")
|
|
||||||
|
|
||||||
details := fmt.Sprintf(" %s@%s:%d", host.Username, host.Hostname, host.Port)
|
|
||||||
b.WriteString(HostDetailStyle.Render(details))
|
|
||||||
|
|
||||||
if len(host.Tags) > 0 {
|
|
||||||
tags := formatTagsForTUI(host.Tags)
|
|
||||||
b.WriteString(" " + TagStyle.Render(tags))
|
|
||||||
}
|
|
||||||
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// renderSelectedHost renders the selected host with highlight
|
|
||||||
func renderSelectedHost(host *models.Host) string {
|
|
||||||
hostText := renderHost(host)
|
|
||||||
return SelectedStyle.Render(hostText)
|
|
||||||
}
|
|
||||||
|
|
||||||
// formatTagsForTUI formats tags for TUI display
|
|
||||||
func formatTagsForTUI(tags []string) string {
|
|
||||||
if len(tags) == 0 {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
var formatted []string
|
|
||||||
for _, tag := range tags {
|
|
||||||
formatted = append(formatted, "["+tag+"]")
|
|
||||||
}
|
|
||||||
|
|
||||||
return strings.Join(formatted, " ")
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HostListTab is the host list tab
|
||||||
|
type HostListTab struct {
|
||||||
|
hosts []*models.Host
|
||||||
|
selectedIndex int
|
||||||
|
err error
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewHostListTab creates a new host list tab
|
||||||
|
func NewHostListTab() *HostListTab {
|
||||||
|
return &HostListTab{
|
||||||
|
selectedIndex: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init initializes the tab
|
||||||
|
func (t *HostListTab) Init() tea.Cmd {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Name returns the tab name
|
||||||
|
func (t *HostListTab) Name() string {
|
||||||
|
return "Hosts"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update handles messages for the host list
|
||||||
|
func (t *HostListTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
t.width = msg.Width
|
||||||
|
t.height = msg.Height
|
||||||
|
|
||||||
|
case tea.KeyMsg:
|
||||||
|
switch msg.String() {
|
||||||
|
case "up", "k":
|
||||||
|
if t.selectedIndex > 0 {
|
||||||
|
t.selectedIndex--
|
||||||
|
}
|
||||||
|
|
||||||
|
case "down", "j":
|
||||||
|
if t.selectedIndex < len(t.hosts)-1 {
|
||||||
|
t.selectedIndex++
|
||||||
|
}
|
||||||
|
|
||||||
|
case "enter", " ":
|
||||||
|
if len(t.hosts) > 0 {
|
||||||
|
host := t.hosts[t.selectedIndex]
|
||||||
|
return t, func() tea.Msg {
|
||||||
|
return sshConnectToMsg{host: host}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ctrl+n":
|
||||||
|
return t, func() tea.Msg {
|
||||||
|
return openHostFormMsg{}
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ctrl+e", "e":
|
||||||
|
if len(t.hosts) > 0 {
|
||||||
|
host := t.hosts[t.selectedIndex]
|
||||||
|
return t, func() tea.Msg {
|
||||||
|
return openHostFormMsg{editing: host}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ctrl+f":
|
||||||
|
if len(t.hosts) > 0 {
|
||||||
|
host := t.hosts[t.selectedIndex]
|
||||||
|
return t, func() tea.Msg {
|
||||||
|
return openSFTPMsg{host: host}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ctrl+k":
|
||||||
|
return t, func() tea.Msg {
|
||||||
|
return openKeyListMsg{}
|
||||||
|
}
|
||||||
|
|
||||||
|
case "ctrl+p":
|
||||||
|
return t, func() tea.Msg {
|
||||||
|
return openSnippetListMsg{}
|
||||||
|
}
|
||||||
|
|
||||||
|
case "q", "ctrl+c":
|
||||||
|
return t, func() tea.Msg {
|
||||||
|
return quitMsg{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// View renders the host list — responsive layout
|
||||||
|
func (t *HostListTab) View() string {
|
||||||
|
var b strings.Builder
|
||||||
|
|
||||||
|
// Error display
|
||||||
|
if t.err != nil {
|
||||||
|
b.WriteString(ErrorStyle.Render(fmt.Sprintf(" Error: %v ", t.err)))
|
||||||
|
b.WriteString("\n")
|
||||||
|
t.err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(t.hosts) == 0 {
|
||||||
|
msg := SubtitleStyle.Render("(no connections — press Ctrl+N to add)")
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, msg))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scrolling
|
||||||
|
availH := t.height - 10
|
||||||
|
if availH < 1 {
|
||||||
|
availH = 1
|
||||||
|
}
|
||||||
|
maxHosts := availH
|
||||||
|
if maxHosts > len(t.hosts) {
|
||||||
|
maxHosts = len(t.hosts)
|
||||||
|
}
|
||||||
|
|
||||||
|
start := t.selectedIndex - maxHosts/2
|
||||||
|
if start < 0 {
|
||||||
|
start = 0
|
||||||
|
}
|
||||||
|
if start+maxHosts > len(t.hosts) {
|
||||||
|
start = len(t.hosts) - maxHosts
|
||||||
|
}
|
||||||
|
|
||||||
|
// Responsive width calculation
|
||||||
|
sidePad := adaptiveSidePad(t.width)
|
||||||
|
titlePlain := "Connection List"
|
||||||
|
|
||||||
|
// Measure content rows to determine natural box width
|
||||||
|
widestContent := lipgloss.Width(titlePlain)
|
||||||
|
for i := start; i < start+maxHosts; i++ {
|
||||||
|
host := t.hosts[i]
|
||||||
|
raw := fmt.Sprintf(" %-12s %-18s :%d", host.Name, host.Hostname, host.Port)
|
||||||
|
if w := lipgloss.Width(raw); w > widestContent {
|
||||||
|
widestContent = w
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clamp box to terminal width
|
||||||
|
targetW := clampWidth(widestContent+sidePad*2, t.width)
|
||||||
|
innerW := targetW - sidePad*2
|
||||||
|
if innerW < 1 {
|
||||||
|
innerW = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build rows with adaptive format
|
||||||
|
type styledRow struct {
|
||||||
|
text string
|
||||||
|
plain string
|
||||||
|
}
|
||||||
|
var rows []styledRow
|
||||||
|
|
||||||
|
for i := start; i < start+maxHosts; i++ {
|
||||||
|
host := t.hosts[i]
|
||||||
|
var raw string
|
||||||
|
if innerW >= 35 {
|
||||||
|
raw = fmt.Sprintf(" %-12s %-18s :%d", host.Name, host.Hostname, host.Port)
|
||||||
|
} else {
|
||||||
|
raw = fmt.Sprintf(" %s %s:%d", host.Name, host.Hostname, host.Port)
|
||||||
|
}
|
||||||
|
if lipgloss.Width(raw) > innerW {
|
||||||
|
raw = truncateStr(raw, innerW)
|
||||||
|
}
|
||||||
|
|
||||||
|
var styled string
|
||||||
|
if i == t.selectedIndex {
|
||||||
|
styled = lipgloss.NewStyle().
|
||||||
|
Foreground(gbFg).
|
||||||
|
Background(gbBgSel).
|
||||||
|
Bold(true).
|
||||||
|
Render("▸ " + strings.TrimLeft(raw, " "))
|
||||||
|
} else {
|
||||||
|
styled = lipgloss.NewStyle().Foreground(gbFg).Render(raw)
|
||||||
|
}
|
||||||
|
rows = append(rows, styledRow{text: styled, plain: raw})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Footer (wrapped to fit innerW)
|
||||||
|
footerText := "Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Enter:SSH Ctrl+N:add Ctrl+E:edit Ctrl+F:SFTP Ctrl+K:keys Ctrl+P:snippets q:quit"
|
||||||
|
footerWrapped := wrapFooter(footerText, innerW)
|
||||||
|
|
||||||
|
// Title
|
||||||
|
title := lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(titlePlain)
|
||||||
|
|
||||||
|
var content strings.Builder
|
||||||
|
|
||||||
|
content.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, title))
|
||||||
|
content.WriteString("\n\n")
|
||||||
|
|
||||||
|
for _, r := range rows {
|
||||||
|
line := lipgloss.PlaceHorizontal(targetW, lipgloss.Center, r.text)
|
||||||
|
content.WriteString(line)
|
||||||
|
content.WriteString("\n")
|
||||||
|
}
|
||||||
|
content.WriteString("\n")
|
||||||
|
|
||||||
|
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||||
|
content.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||||
|
content.WriteString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
box := BorderStyle.Render(content.String())
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||||
|
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close is a no-op for host list tab
|
||||||
|
func (t *HostListTab) Close() {}
|
||||||
|
|
||||||
|
// SetHosts sets the host list
|
||||||
|
func (t *HostListTab) SetHosts(hosts []*models.Host) {
|
||||||
|
t.hosts = hosts
|
||||||
|
if len(hosts) > 0 && t.selectedIndex >= len(hosts) {
|
||||||
|
t.selectedIndex = len(hosts) - 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hosts returns the host list
|
||||||
|
func (t *HostListTab) Hosts() []*models.Host {
|
||||||
|
return t.hosts
|
||||||
|
}
|
||||||
|
|
||||||
|
// SelectedIndex returns the selected index
|
||||||
|
func (t *HostListTab) SelectedIndex() int {
|
||||||
|
return t.selectedIndex
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindHostListTab finds the first HostListTab in a list of tabs
|
||||||
|
func FindHostListTab(tabs []Tab) *HostListTab {
|
||||||
|
for _, tab := range tabs {
|
||||||
|
if ht, ok := tab.(*HostListTab); ok {
|
||||||
|
return ht
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatTagsForTUI formats tags for TUI display
|
||||||
|
func formatTagsForTUI(tags []string) string {
|
||||||
|
if len(tags) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
var formatted []string
|
||||||
|
for _, tag := range tags {
|
||||||
|
formatted = append(formatted, "["+tag+"]")
|
||||||
|
}
|
||||||
|
return strings.Join(formatted, " ")
|
||||||
|
}
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/textinput"
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type keyFormMode int
|
||||||
|
|
||||||
|
const (
|
||||||
|
keyFormAdd keyFormMode = iota
|
||||||
|
keyFormEdit
|
||||||
|
)
|
||||||
|
|
||||||
|
type keyFieldID int
|
||||||
|
|
||||||
|
const (
|
||||||
|
keyFieldName keyFieldID = iota
|
||||||
|
keyFieldType
|
||||||
|
keyFieldPrivateKey
|
||||||
|
keyFieldPassphrase
|
||||||
|
keyFieldCount
|
||||||
|
)
|
||||||
|
|
||||||
|
var keyFieldLabels = map[keyFieldID]string{
|
||||||
|
keyFieldName: "Name",
|
||||||
|
keyFieldType: "Type (rsa/ed25519/ecdsa)",
|
||||||
|
keyFieldPrivateKey: "Private Key (PEM)",
|
||||||
|
keyFieldPassphrase: "Passphrase",
|
||||||
|
}
|
||||||
|
|
||||||
|
// KeyFormTab is a tab for adding/editing SSH key pairs
|
||||||
|
type KeyFormTab struct {
|
||||||
|
mode keyFormMode
|
||||||
|
editing *models.KeyPair
|
||||||
|
dataDir string
|
||||||
|
|
||||||
|
inputs []textinput.Model
|
||||||
|
focus keyFieldID
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
|
||||||
|
err error
|
||||||
|
saved bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAddKeyFormTab(dataDir string) *KeyFormTab {
|
||||||
|
return newKeyFormTab(keyFormAdd, nil, dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEditKeyFormTab(key *models.KeyPair, dataDir string) *KeyFormTab {
|
||||||
|
return newKeyFormTab(keyFormEdit, key, dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newKeyFormTab(mode keyFormMode, key *models.KeyPair, dataDir string) *KeyFormTab {
|
||||||
|
inputs := make([]textinput.Model, keyFieldCount)
|
||||||
|
for i := range inputs {
|
||||||
|
inputs[i] = textinput.New()
|
||||||
|
inputs[i].Prompt = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
inputs[keyFieldName].Placeholder = "My SSH Key"
|
||||||
|
inputs[keyFieldType].Placeholder = "ed25519"
|
||||||
|
inputs[keyFieldType].SetValue("ed25519")
|
||||||
|
inputs[keyFieldPrivateKey].Placeholder = "-----BEGIN OPENSSH PRIVATE KEY-----"
|
||||||
|
inputs[keyFieldPassphrase].Placeholder = "Optional passphrase"
|
||||||
|
|
||||||
|
if mode == keyFormEdit && key != nil {
|
||||||
|
inputs[keyFieldName].SetValue(key.Name)
|
||||||
|
inputs[keyFieldType].SetValue(key.Type)
|
||||||
|
inputs[keyFieldPrivateKey].SetValue(key.PrivateKey)
|
||||||
|
inputs[keyFieldPassphrase].SetValue(key.Passphrase)
|
||||||
|
}
|
||||||
|
|
||||||
|
inputs[keyFieldName].Focus()
|
||||||
|
inputs[keyFieldName].Prompt = "> "
|
||||||
|
|
||||||
|
return &KeyFormTab{
|
||||||
|
mode: mode,
|
||||||
|
editing: key,
|
||||||
|
dataDir: dataDir,
|
||||||
|
inputs: inputs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyFormTab) Name() string {
|
||||||
|
if t.mode == keyFormEdit {
|
||||||
|
return "Edit Key"
|
||||||
|
}
|
||||||
|
return "Add Key"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyFormTab) Init() tea.Cmd {
|
||||||
|
return textinput.Blink
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyFormTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||||
|
if t.saved {
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
t.width = msg.Width
|
||||||
|
t.height = msg.Height
|
||||||
|
|
||||||
|
case tea.KeyMsg:
|
||||||
|
switch msg.String() {
|
||||||
|
case "esc":
|
||||||
|
return t, func() tea.Msg { return closeFormMsg{} }
|
||||||
|
|
||||||
|
case "enter":
|
||||||
|
if t.focus == keyFieldCount-1 {
|
||||||
|
return t.submit()
|
||||||
|
}
|
||||||
|
t.nextField()
|
||||||
|
|
||||||
|
case "tab", "down":
|
||||||
|
t.nextField()
|
||||||
|
|
||||||
|
case "shift+tab", "up":
|
||||||
|
t.prevField()
|
||||||
|
|
||||||
|
case "ctrl+s":
|
||||||
|
return t.submit()
|
||||||
|
|
||||||
|
default:
|
||||||
|
var cmd tea.Cmd
|
||||||
|
t.inputs[t.focus], cmd = t.inputs[t.focus].Update(msg)
|
||||||
|
return t, cmd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyFormTab) nextField() {
|
||||||
|
t.inputs[t.focus].Blur()
|
||||||
|
t.inputs[t.focus].Prompt = ""
|
||||||
|
t.focus++
|
||||||
|
if t.focus >= keyFieldCount {
|
||||||
|
t.focus = keyFieldCount - 1
|
||||||
|
}
|
||||||
|
t.inputs[t.focus].Focus()
|
||||||
|
t.inputs[t.focus].Prompt = "> "
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyFormTab) prevField() {
|
||||||
|
t.inputs[t.focus].Blur()
|
||||||
|
t.inputs[t.focus].Prompt = ""
|
||||||
|
t.focus--
|
||||||
|
if t.focus < 0 {
|
||||||
|
t.focus = 0
|
||||||
|
}
|
||||||
|
t.inputs[t.focus].Focus()
|
||||||
|
t.inputs[t.focus].Prompt = "> "
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyFormTab) submit() (Tab, tea.Cmd) {
|
||||||
|
name := t.inputs[keyFieldName].Value()
|
||||||
|
privateKey := t.inputs[keyFieldPrivateKey].Value()
|
||||||
|
|
||||||
|
if name == "" || privateKey == "" {
|
||||||
|
t.err = fmt.Errorf("name and private key are required")
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var key *models.KeyPair
|
||||||
|
if t.mode == keyFormEdit && t.editing != nil {
|
||||||
|
key = t.editing
|
||||||
|
key.Name = name
|
||||||
|
key.Type = t.inputs[keyFieldType].Value()
|
||||||
|
key.PrivateKey = privateKey
|
||||||
|
key.Passphrase = t.inputs[keyFieldPassphrase].Value()
|
||||||
|
} else {
|
||||||
|
key = &models.KeyPair{
|
||||||
|
ID: uuid.New().String(),
|
||||||
|
Name: name,
|
||||||
|
Type: t.inputs[keyFieldType].Value(),
|
||||||
|
PrivateKey: privateKey,
|
||||||
|
Passphrase: t.inputs[keyFieldPassphrase].Value(),
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
UpdatedAt: time.Now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.saved = true
|
||||||
|
return t, saveKeyCmd(key, t.dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyFormTab) View() string {
|
||||||
|
contentW := t.width - 12
|
||||||
|
if contentW < 30 {
|
||||||
|
contentW = 30
|
||||||
|
}
|
||||||
|
if contentW > 70 {
|
||||||
|
contentW = 70
|
||||||
|
}
|
||||||
|
|
||||||
|
var inner strings.Builder
|
||||||
|
|
||||||
|
title := "Add SSH Key"
|
||||||
|
if t.mode == keyFormEdit {
|
||||||
|
title = "Edit SSH Key"
|
||||||
|
}
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||||
|
lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(title)))
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
|
||||||
|
if t.err != nil {
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||||
|
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := keyFieldID(0); i < keyFieldCount; i++ {
|
||||||
|
input := t.inputs[i]
|
||||||
|
label := keyFieldLabels[i]
|
||||||
|
style := SubtitleStyle
|
||||||
|
if i == t.focus {
|
||||||
|
style = HighlightStyle
|
||||||
|
}
|
||||||
|
inner.WriteString(style.Render(label + ":"))
|
||||||
|
inner.WriteString("\n ")
|
||||||
|
inner.WriteString(input.View())
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
inner.WriteString("\n")
|
||||||
|
footerText := "Ctrl+Tab:switch Ctrl+Q:close Tab:next Shift+Tab:prev ↑↓:nav Enter:next Ctrl+S:save Esc:cancel"
|
||||||
|
footerWrapped := wrapFooter(footerText, contentW)
|
||||||
|
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||||
|
inner.WriteString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
box := BorderStyle.Render(inner.String())
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyFormTab) Close() {}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
type keyListState int
|
||||||
|
|
||||||
|
const (
|
||||||
|
keyListLoading keyListState = iota
|
||||||
|
keyListReady
|
||||||
|
keyListError
|
||||||
|
)
|
||||||
|
|
||||||
|
// KeyListTab displays and manages SSH key pairs
|
||||||
|
type KeyListTab struct {
|
||||||
|
dataDir string
|
||||||
|
keys []*models.KeyPair
|
||||||
|
selected int
|
||||||
|
state keyListState
|
||||||
|
err error
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewKeyListTab(dataDir string) *KeyListTab {
|
||||||
|
return &KeyListTab{
|
||||||
|
dataDir: dataDir,
|
||||||
|
state: keyListLoading,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyListTab) Name() string { return "SSH Keys" }
|
||||||
|
|
||||||
|
func (t *KeyListTab) Init() tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(t.dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return keyListLoadedMsg{err: err}
|
||||||
|
}
|
||||||
|
keys, err := store.ListKeyPairs(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
return keyListLoadedMsg{err: err}
|
||||||
|
}
|
||||||
|
return keyListLoadedMsg{keys: keys}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyListTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
t.mu.Lock()
|
||||||
|
t.width = msg.Width
|
||||||
|
t.height = msg.Height
|
||||||
|
t.mu.Unlock()
|
||||||
|
|
||||||
|
case keyListLoadedMsg:
|
||||||
|
t.mu.Lock()
|
||||||
|
if msg.err != nil {
|
||||||
|
t.state = keyListError
|
||||||
|
t.err = msg.err
|
||||||
|
} else {
|
||||||
|
t.state = keyListReady
|
||||||
|
t.keys = msg.keys
|
||||||
|
}
|
||||||
|
t.mu.Unlock()
|
||||||
|
|
||||||
|
case saveKeyResultMsg:
|
||||||
|
return t, t.Init()
|
||||||
|
|
||||||
|
case deleteKeyResultMsg:
|
||||||
|
if msg.err != nil {
|
||||||
|
t.mu.Lock()
|
||||||
|
t.err = msg.err
|
||||||
|
t.mu.Unlock()
|
||||||
|
}
|
||||||
|
return t, t.Init()
|
||||||
|
|
||||||
|
case tea.KeyMsg:
|
||||||
|
switch msg.String() {
|
||||||
|
case "up", "k":
|
||||||
|
t.mu.Lock()
|
||||||
|
if t.selected > 0 {
|
||||||
|
t.selected--
|
||||||
|
}
|
||||||
|
t.mu.Unlock()
|
||||||
|
|
||||||
|
case "down", "j":
|
||||||
|
t.mu.Lock()
|
||||||
|
if t.selected < len(t.keys)-1 {
|
||||||
|
t.selected++
|
||||||
|
}
|
||||||
|
t.mu.Unlock()
|
||||||
|
|
||||||
|
case "ctrl+n":
|
||||||
|
return t, func() tea.Msg { return openKeyFormMsg{} }
|
||||||
|
|
||||||
|
case "ctrl+e":
|
||||||
|
t.mu.Lock()
|
||||||
|
keys := t.keys
|
||||||
|
idx := t.selected
|
||||||
|
t.mu.Unlock()
|
||||||
|
if len(keys) > 0 && idx >= 0 && idx < len(keys) {
|
||||||
|
return t, func() tea.Msg { return openKeyFormMsg{editing: keys[idx]} }
|
||||||
|
}
|
||||||
|
|
||||||
|
case "delete", "d":
|
||||||
|
t.mu.Lock()
|
||||||
|
keys := t.keys
|
||||||
|
idx := t.selected
|
||||||
|
t.mu.Unlock()
|
||||||
|
if len(keys) > 0 && idx >= 0 && idx < len(keys) {
|
||||||
|
return t, deleteKeyCmd(keys[idx].ID, t.dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
case "esc":
|
||||||
|
return t, func() tea.Msg { return closeFormMsg{} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyListTab) View() string {
|
||||||
|
t.mu.Lock()
|
||||||
|
defer t.mu.Unlock()
|
||||||
|
|
||||||
|
if t.state == keyListLoading {
|
||||||
|
return lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||||
|
SubtitleStyle.Render("Loading keys..."))
|
||||||
|
}
|
||||||
|
if t.state == keyListError {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||||
|
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||||
|
b.WriteString("\n")
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||||
|
SubtitleStyle.Render("Press Esc to go back")))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
type styledRow struct {
|
||||||
|
text string
|
||||||
|
plain string
|
||||||
|
}
|
||||||
|
|
||||||
|
titlePlain := "SSH Key Pairs"
|
||||||
|
|
||||||
|
// Build content rows
|
||||||
|
var rows []styledRow
|
||||||
|
if t.err != nil {
|
||||||
|
errLine := fmt.Sprintf("Error: %v", t.err)
|
||||||
|
rows = append(rows, styledRow{text: ErrorStyle.Render(errLine), plain: errLine})
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(t.keys) == 0 {
|
||||||
|
empty := "No SSH keys stored."
|
||||||
|
hint := "Press Ctrl+N to add a new key."
|
||||||
|
rows = append(rows, styledRow{text: SubtitleStyle.Render(empty), plain: empty})
|
||||||
|
rows = append(rows, styledRow{text: SubtitleStyle.Render(hint), plain: hint})
|
||||||
|
} else {
|
||||||
|
for i, key := range t.keys {
|
||||||
|
var plain string
|
||||||
|
if key.Type != "" {
|
||||||
|
plain = fmt.Sprintf(" %s (%s)", key.Name, key.Type)
|
||||||
|
} else {
|
||||||
|
plain = fmt.Sprintf(" %s", key.Name)
|
||||||
|
}
|
||||||
|
var styled string
|
||||||
|
if i == t.selected {
|
||||||
|
styled = lipgloss.NewStyle().
|
||||||
|
Foreground(gbFg).
|
||||||
|
Background(gbBgSel).
|
||||||
|
Bold(true).
|
||||||
|
Render("▸ " + strings.TrimLeft(plain, " "))
|
||||||
|
} else {
|
||||||
|
styled = lipgloss.NewStyle().Foreground(gbFg).Render(plain)
|
||||||
|
}
|
||||||
|
rows = append(rows, styledRow{text: styled, plain: plain})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Responsive width
|
||||||
|
sidePad := adaptiveSidePad(t.width)
|
||||||
|
widestContent := lipgloss.Width(titlePlain)
|
||||||
|
for _, r := range rows {
|
||||||
|
if w := lipgloss.Width(r.plain); w > widestContent {
|
||||||
|
widestContent = w
|
||||||
|
}
|
||||||
|
}
|
||||||
|
targetW := clampWidth(widestContent+sidePad*2, t.width)
|
||||||
|
innerW := targetW - sidePad*2
|
||||||
|
if innerW < 1 {
|
||||||
|
innerW = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Footer (wrapped)
|
||||||
|
footerText := "Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Ctrl+N:add Ctrl+E:edit D:delete Esc:back"
|
||||||
|
footerWrapped := wrapFooter(footerText, innerW)
|
||||||
|
|
||||||
|
// Render
|
||||||
|
var inner strings.Builder
|
||||||
|
titleStyled := lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(titlePlain)
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, titleStyled))
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
|
||||||
|
for _, r := range rows {
|
||||||
|
plain := r.plain
|
||||||
|
if lipgloss.Width(plain) > innerW {
|
||||||
|
plain = truncateStr(plain, innerW)
|
||||||
|
}
|
||||||
|
styled := r.text
|
||||||
|
if lipgloss.Width(r.plain) > innerW {
|
||||||
|
styled = truncateStr(r.text, innerW)
|
||||||
|
}
|
||||||
|
line := lipgloss.PlaceHorizontal(targetW, lipgloss.Center, styled)
|
||||||
|
inner.WriteString(line)
|
||||||
|
inner.WriteString("\n")
|
||||||
|
}
|
||||||
|
inner.WriteString("\n")
|
||||||
|
|
||||||
|
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||||
|
inner.WriteString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
box := BorderStyle.Render(inner.String())
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *KeyListTab) Close() {}
|
||||||
|
|
||||||
|
// SetKeys updates the key list data directly (used for refresh)
|
||||||
|
func (t *KeyListTab) SetKeys(keys []*models.KeyPair) {
|
||||||
|
t.mu.Lock()
|
||||||
|
defer t.mu.Unlock()
|
||||||
|
t.state = keyListReady
|
||||||
|
t.keys = keys
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindKeyListTab finds the first KeyListTab in a list of tabs
|
||||||
|
func FindKeyListTab(tabs []Tab) *KeyListTab {
|
||||||
|
for _, tab := range tabs {
|
||||||
|
if kt, ok := tab.(*KeyListTab); ok {
|
||||||
|
return kt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// keyListLoadedMsg carries the loaded key list
|
||||||
|
type keyListLoadedMsg struct {
|
||||||
|
keys []*models.KeyPair
|
||||||
|
err error
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
// quitMsg signals the TUI to exit
|
||||||
|
type quitMsg struct{}
|
||||||
|
|
||||||
|
// sshConnectToMsg signals the TUI to connect to a host via native SSH
|
||||||
|
type sshConnectToMsg struct {
|
||||||
|
host *models.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
// sshExitMsg signals that a native SSH session has ended
|
||||||
|
type sshExitMsg struct {
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// openHostFormMsg signals the TUI to open a host form tab
|
||||||
|
type openHostFormMsg struct {
|
||||||
|
editing *models.Host // nil for add mode
|
||||||
|
}
|
||||||
|
|
||||||
|
// closeFormMsg signals the TUI to close the active form tab
|
||||||
|
type closeFormMsg struct{}
|
||||||
|
|
||||||
|
// saveHostMsg is produced when the form needs to save a host
|
||||||
|
type saveHostMsg struct {
|
||||||
|
host *models.Host
|
||||||
|
dataDir string
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveHostResultMsg is produced after a save attempt
|
||||||
|
type saveHostResultMsg struct {
|
||||||
|
host *models.Host
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// openSFTPMsg signals the TUI to open an SFTP browser tab
|
||||||
|
type openSFTPMsg struct {
|
||||||
|
host *models.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadedHostsMsg is produced after reloading hosts from storage
|
||||||
|
type loadedHostsMsg struct {
|
||||||
|
hosts []*models.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
// Key management messages
|
||||||
|
type openKeyListMsg struct{}
|
||||||
|
|
||||||
|
type openKeyFormMsg struct {
|
||||||
|
editing *models.KeyPair
|
||||||
|
}
|
||||||
|
|
||||||
|
type saveKeyMsg struct {
|
||||||
|
key *models.KeyPair
|
||||||
|
dataDir string
|
||||||
|
}
|
||||||
|
|
||||||
|
type saveKeyResultMsg struct {
|
||||||
|
key *models.KeyPair
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type deleteKeyMsg struct {
|
||||||
|
id string
|
||||||
|
dataDir string
|
||||||
|
}
|
||||||
|
|
||||||
|
type deleteKeyResultMsg struct {
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snippet management messages
|
||||||
|
type openSnippetListMsg struct{}
|
||||||
|
|
||||||
|
type openSnippetFormMsg struct {
|
||||||
|
editing *models.Snippet
|
||||||
|
}
|
||||||
|
|
||||||
|
type saveSnippetMsg struct {
|
||||||
|
snippet *models.Snippet
|
||||||
|
dataDir string
|
||||||
|
}
|
||||||
|
|
||||||
|
type saveSnippetResultMsg struct {
|
||||||
|
snippet *models.Snippet
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type deleteSnippetMsg struct {
|
||||||
|
id string
|
||||||
|
dataDir string
|
||||||
|
}
|
||||||
|
|
||||||
|
type deleteSnippetResultMsg struct {
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveKeyCmd creates a command that saves a key pair to storage
|
||||||
|
func saveKeyCmd(key *models.KeyPair, dataDir string) tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return saveKeyResultMsg{err: err}
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := store.SaveKeyPair(ctx, key); err != nil {
|
||||||
|
return saveKeyResultMsg{err: err}
|
||||||
|
}
|
||||||
|
return saveKeyResultMsg{key: key}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// deleteKeyCmd creates a command that deletes a key pair
|
||||||
|
func deleteKeyCmd(id, dataDir string) tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return deleteKeyResultMsg{err: err}
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := store.DeleteKeyPair(ctx, id); err != nil {
|
||||||
|
return deleteKeyResultMsg{err: err}
|
||||||
|
}
|
||||||
|
return deleteKeyResultMsg{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveSnippetCmd creates a command that saves a snippet to storage
|
||||||
|
func saveSnippetCmd(snippet *models.Snippet, dataDir string) tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return saveSnippetResultMsg{err: err}
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := store.SaveSnippet(ctx, snippet); err != nil {
|
||||||
|
return saveSnippetResultMsg{err: err}
|
||||||
|
}
|
||||||
|
return saveSnippetResultMsg{snippet: snippet}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// deleteSnippetCmd creates a command that deletes a snippet
|
||||||
|
func deleteSnippetCmd(id, dataDir string) tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return deleteSnippetResultMsg{err: err}
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := store.DeleteSnippet(ctx, id); err != nil {
|
||||||
|
return deleteSnippetResultMsg{err: err}
|
||||||
|
}
|
||||||
|
return deleteSnippetResultMsg{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveHostCmd creates a command that saves a host to storage
|
||||||
|
func saveHostCmd(host *models.Host, dataDir string) tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return saveHostResultMsg{err: err}
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := store.SaveHost(ctx, host); err != nil {
|
||||||
|
return saveHostResultMsg{err: err}
|
||||||
|
}
|
||||||
|
return saveHostResultMsg{host: host}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// openEncryptPromptMsg shows the encryption setup prompt
|
||||||
|
type openEncryptPromptMsg struct{}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/textinput"
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
)
|
||||||
|
|
||||||
|
// passwordPromptMode determines what the password prompt is for
|
||||||
|
type passwordPromptMode int
|
||||||
|
|
||||||
|
const (
|
||||||
|
// passwordModeSetup — first time enabling encryption, ask for new password
|
||||||
|
passwordModeSetup passwordPromptMode = iota
|
||||||
|
// passwordModeUnlock — encryption already enabled, ask for existing password
|
||||||
|
passwordModeUnlock
|
||||||
|
)
|
||||||
|
|
||||||
|
// PasswordPromptTab shows a password prompt for encryption setup or unlock
|
||||||
|
type PasswordPromptTab struct {
|
||||||
|
mode passwordPromptMode
|
||||||
|
inputs []textinput.Model
|
||||||
|
focus int
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
err error
|
||||||
|
dataDir string
|
||||||
|
onComplete func(password string) // called with password on success
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPasswordPromptTab creates a new password prompt tab
|
||||||
|
func NewPasswordPromptTab(mode passwordPromptMode, dataDir string, onComplete func(string)) *PasswordPromptTab {
|
||||||
|
p := &PasswordPromptTab{
|
||||||
|
mode: mode,
|
||||||
|
dataDir: dataDir,
|
||||||
|
onComplete: onComplete,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Password field
|
||||||
|
passwordInput := textinput.New()
|
||||||
|
passwordInput.Placeholder = "Enter master password"
|
||||||
|
passwordInput.EchoMode = textinput.EchoPassword
|
||||||
|
passwordInput.EchoCharacter = '•'
|
||||||
|
passwordInput.Focus()
|
||||||
|
|
||||||
|
// Confirm password field (only for setup mode)
|
||||||
|
confirmInput := textinput.New()
|
||||||
|
confirmInput.Placeholder = "Confirm password"
|
||||||
|
confirmInput.EchoMode = textinput.EchoPassword
|
||||||
|
confirmInput.EchoCharacter = '•'
|
||||||
|
|
||||||
|
if mode == passwordModeSetup {
|
||||||
|
p.inputs = []textinput.Model{passwordInput, confirmInput}
|
||||||
|
} else {
|
||||||
|
p.inputs = []textinput.Model{passwordInput}
|
||||||
|
}
|
||||||
|
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PasswordPromptTab) Name() string {
|
||||||
|
if p.mode == passwordModeSetup {
|
||||||
|
return "Setup Encryption"
|
||||||
|
}
|
||||||
|
return "Unlock Storage"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PasswordPromptTab) Init() tea.Cmd {
|
||||||
|
return textinput.Blink
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PasswordPromptTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
p.width = msg.Width
|
||||||
|
p.height = msg.Height
|
||||||
|
return p, nil
|
||||||
|
|
||||||
|
case tea.KeyMsg:
|
||||||
|
switch msg.String() {
|
||||||
|
case "tab", "down":
|
||||||
|
p.focus++
|
||||||
|
if p.focus >= len(p.inputs) {
|
||||||
|
p.focus = 0
|
||||||
|
}
|
||||||
|
for i := range p.inputs {
|
||||||
|
if i == p.focus {
|
||||||
|
p.inputs[i].Focus()
|
||||||
|
} else {
|
||||||
|
p.inputs[i].Blur()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
|
||||||
|
case "shift+tab", "up":
|
||||||
|
p.focus--
|
||||||
|
if p.focus < 0 {
|
||||||
|
p.focus = len(p.inputs) - 1
|
||||||
|
}
|
||||||
|
for i := range p.inputs {
|
||||||
|
if i == p.focus {
|
||||||
|
p.inputs[i].Focus()
|
||||||
|
} else {
|
||||||
|
p.inputs[i].Blur()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
|
||||||
|
case "enter":
|
||||||
|
password := p.inputs[0].Value()
|
||||||
|
if password == "" {
|
||||||
|
p.err = fmt.Errorf("password cannot be empty")
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.mode == passwordModeSetup && len(p.inputs) > 1 {
|
||||||
|
confirm := p.inputs[1].Value()
|
||||||
|
if password != confirm {
|
||||||
|
p.err = fmt.Errorf("passwords do not match")
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Success — call onComplete
|
||||||
|
if p.onComplete != nil {
|
||||||
|
p.onComplete(password)
|
||||||
|
}
|
||||||
|
return p, func() tea.Msg { return passwordSetMsg{} }
|
||||||
|
|
||||||
|
case "esc":
|
||||||
|
// Cancel — go back or quit
|
||||||
|
return p, func() tea.Msg { return closeFormMsg{} }
|
||||||
|
|
||||||
|
default:
|
||||||
|
// Update current input
|
||||||
|
var cmd tea.Cmd
|
||||||
|
p.inputs[p.focus], cmd = p.inputs[p.focus].Update(msg)
|
||||||
|
return p, cmd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PasswordPromptTab) Close() {
|
||||||
|
// Nothing to clean up
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *PasswordPromptTab) View() string {
|
||||||
|
var b strings.Builder
|
||||||
|
|
||||||
|
title := "Setup Master Password"
|
||||||
|
if p.mode == passwordModeUnlock {
|
||||||
|
title = "Enter Master Password"
|
||||||
|
}
|
||||||
|
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center,
|
||||||
|
AppTitleStyle.Render(title)))
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
|
||||||
|
if p.mode == passwordModeSetup {
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center,
|
||||||
|
SubtitleStyle.Render("Encrypt all sensitive data (passwords, keys) with AES-256")))
|
||||||
|
b.WriteString("\n")
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center,
|
||||||
|
SubtitleStyle.Render("You will need this password to access your data")))
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Input fields
|
||||||
|
contentW := p.width - 8
|
||||||
|
if contentW > 60 {
|
||||||
|
contentW = 60
|
||||||
|
}
|
||||||
|
|
||||||
|
box := lipgloss.NewStyle().
|
||||||
|
Border(lipgloss.RoundedBorder()).
|
||||||
|
BorderForeground(lipgloss.Color("62")).
|
||||||
|
Padding(1, 2).
|
||||||
|
Width(contentW)
|
||||||
|
|
||||||
|
var fields strings.Builder
|
||||||
|
for i, input := range p.inputs {
|
||||||
|
label := "Password:"
|
||||||
|
if i == 1 {
|
||||||
|
label = "Confirm:"
|
||||||
|
}
|
||||||
|
fields.WriteString(SubtitleStyle.Render(" " + label))
|
||||||
|
fields.WriteString("\n")
|
||||||
|
fields.WriteString(input.View())
|
||||||
|
fields.WriteString("\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center, box.Render(fields.String())))
|
||||||
|
|
||||||
|
if p.err != nil {
|
||||||
|
b.WriteString("\n")
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center,
|
||||||
|
ErrorStyle.Render(p.err.Error())))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Footer
|
||||||
|
footerText := "Enter:confirm Esc:cancel Tab:next field"
|
||||||
|
b.WriteString("\n\n")
|
||||||
|
for _, line := range strings.Split(wrapFooter(footerText, p.width), "\n") {
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(p.width, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||||
|
}
|
||||||
|
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// passwordSetMsg is sent when password is successfully set
|
||||||
|
type passwordSetMsg struct {
|
||||||
|
password string
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Responsive breakpoints
|
||||||
|
const (
|
||||||
|
widthCompact = 60 // mobile / Termux
|
||||||
|
widthMedium = 100 // tablet
|
||||||
|
)
|
||||||
|
|
||||||
|
// boxOverhead is the horizontal chars consumed by BorderStyle (border 2 + padding 4)
|
||||||
|
const boxOverhead = 6
|
||||||
|
|
||||||
|
// wrapFooter wraps a footer string into multiple lines that fit availW.
|
||||||
|
// Words are split on double-space separators (" ") and grouped greedily.
|
||||||
|
// Returns the wrapped string with "\n" line breaks.
|
||||||
|
func wrapFooter(text string, availW int) string {
|
||||||
|
if availW < 1 {
|
||||||
|
availW = 1
|
||||||
|
}
|
||||||
|
if lipgloss.Width(text) <= availW {
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
|
||||||
|
words := strings.Split(text, " ")
|
||||||
|
var lines []string
|
||||||
|
var current strings.Builder
|
||||||
|
|
||||||
|
for _, word := range words {
|
||||||
|
word = strings.TrimSpace(word)
|
||||||
|
if word == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if current.Len() == 0 {
|
||||||
|
current.WriteString(word)
|
||||||
|
} else if current.Len()+2+lipgloss.Width(word) <= availW {
|
||||||
|
current.WriteString(" ")
|
||||||
|
current.WriteString(word)
|
||||||
|
} else {
|
||||||
|
lines = append(lines, current.String())
|
||||||
|
current.Reset()
|
||||||
|
current.WriteString(word)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if current.Len() > 0 {
|
||||||
|
lines = append(lines, current.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
// adaptiveSidePad returns horizontal padding based on terminal width.
|
||||||
|
// wide: 6, medium: 3, compact: 1
|
||||||
|
func adaptiveSidePad(termWidth int) int {
|
||||||
|
switch {
|
||||||
|
case termWidth < widthCompact:
|
||||||
|
return 1
|
||||||
|
case termWidth < widthMedium:
|
||||||
|
return 3
|
||||||
|
default:
|
||||||
|
return 6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// clampWidth clamps a target box width to fit within the terminal.
|
||||||
|
// Reserves boxOverhead for border+padding. Enforces a minimum of 20.
|
||||||
|
func clampWidth(target, termWidth int) int {
|
||||||
|
maxW := termWidth - boxOverhead
|
||||||
|
if maxW < 20 {
|
||||||
|
maxW = 20
|
||||||
|
}
|
||||||
|
if target > maxW {
|
||||||
|
return maxW
|
||||||
|
}
|
||||||
|
if target < 20 {
|
||||||
|
return 20
|
||||||
|
}
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
|
||||||
|
// truncateStr truncates a string to maxLen with an ellipsis character.
|
||||||
|
func truncateStr(s string, maxLen int) string {
|
||||||
|
if maxLen < 1 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if lipgloss.Width(s) <= maxLen {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
if maxLen <= 1 {
|
||||||
|
return "…"
|
||||||
|
}
|
||||||
|
runes := []rune(s)
|
||||||
|
var result []rune
|
||||||
|
resultW := 0
|
||||||
|
for _, r := range runes {
|
||||||
|
rw := lipgloss.Width(string(r))
|
||||||
|
if resultW+rw > maxLen-1 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
result = append(result, r)
|
||||||
|
resultW += rw
|
||||||
|
}
|
||||||
|
return string(result) + "…"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exported wrappers for testing
|
||||||
|
|
||||||
|
// WrapFooter wraps a footer string into multiple lines that fit availW
|
||||||
|
func WrapFooter(text string, availW int) string {
|
||||||
|
return wrapFooter(text, availW)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClampWidth clamps a target box width to fit within the terminal
|
||||||
|
func ClampWidth(target, termWidth int) int {
|
||||||
|
return clampWidth(target, termWidth)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TruncateStr truncates a string to maxLen with an ellipsis character
|
||||||
|
func TruncateStr(s string, maxLen int) string {
|
||||||
|
return truncateStr(s, maxLen)
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,259 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/textinput"
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
type snippetFormMode int
|
||||||
|
|
||||||
|
const (
|
||||||
|
snippetFormAdd snippetFormMode = iota
|
||||||
|
snippetFormEdit
|
||||||
|
)
|
||||||
|
|
||||||
|
type snippetFieldID int
|
||||||
|
|
||||||
|
const (
|
||||||
|
snippetFieldName snippetFieldID = iota
|
||||||
|
snippetFieldCommand
|
||||||
|
snippetFieldDescription
|
||||||
|
snippetFieldTags
|
||||||
|
snippetFieldCount
|
||||||
|
)
|
||||||
|
|
||||||
|
var snippetFieldLabels = map[snippetFieldID]string{
|
||||||
|
snippetFieldName: "Name",
|
||||||
|
snippetFieldCommand: "Command",
|
||||||
|
snippetFieldDescription: "Description",
|
||||||
|
snippetFieldTags: "Tags (comma-separated)",
|
||||||
|
}
|
||||||
|
|
||||||
|
// SnippetFormTab is a tab for adding/editing command snippets
|
||||||
|
type SnippetFormTab struct {
|
||||||
|
mode snippetFormMode
|
||||||
|
editing *models.Snippet
|
||||||
|
dataDir string
|
||||||
|
|
||||||
|
inputs []textinput.Model
|
||||||
|
focus snippetFieldID
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
|
||||||
|
err error
|
||||||
|
saved bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAddSnippetFormTab(dataDir string) *SnippetFormTab {
|
||||||
|
return newSnippetFormTab(snippetFormAdd, nil, dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEditSnippetFormTab(snippet *models.Snippet, dataDir string) *SnippetFormTab {
|
||||||
|
return newSnippetFormTab(snippetFormEdit, snippet, dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSnippetFormTab(mode snippetFormMode, sn *models.Snippet, dataDir string) *SnippetFormTab {
|
||||||
|
inputs := make([]textinput.Model, snippetFieldCount)
|
||||||
|
for i := range inputs {
|
||||||
|
inputs[i] = textinput.New()
|
||||||
|
inputs[i].Prompt = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
inputs[snippetFieldName].Placeholder = "Check logs"
|
||||||
|
inputs[snippetFieldCommand].Placeholder = "journalctl -u nginx --no-pager -n 100"
|
||||||
|
inputs[snippetFieldDescription].Placeholder = "View last 100 nginx log entries"
|
||||||
|
inputs[snippetFieldTags].Placeholder = "nginx,logs,troubleshooting"
|
||||||
|
|
||||||
|
if mode == snippetFormEdit && sn != nil {
|
||||||
|
inputs[snippetFieldName].SetValue(sn.Name)
|
||||||
|
inputs[snippetFieldCommand].SetValue(sn.Command)
|
||||||
|
inputs[snippetFieldDescription].SetValue(sn.Description)
|
||||||
|
inputs[snippetFieldTags].SetValue(strings.Join(sn.Tags, ","))
|
||||||
|
}
|
||||||
|
|
||||||
|
inputs[snippetFieldName].Focus()
|
||||||
|
inputs[snippetFieldName].Prompt = "> "
|
||||||
|
|
||||||
|
return &SnippetFormTab{
|
||||||
|
mode: mode,
|
||||||
|
editing: sn,
|
||||||
|
dataDir: dataDir,
|
||||||
|
inputs: inputs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetFormTab) Name() string {
|
||||||
|
if t.mode == snippetFormEdit {
|
||||||
|
return "Edit Snippet"
|
||||||
|
}
|
||||||
|
return "Add Snippet"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetFormTab) Init() tea.Cmd {
|
||||||
|
return textinput.Blink
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetFormTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||||
|
if t.saved {
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
t.width = msg.Width
|
||||||
|
t.height = msg.Height
|
||||||
|
|
||||||
|
case tea.KeyMsg:
|
||||||
|
switch msg.String() {
|
||||||
|
case "esc":
|
||||||
|
return t, func() tea.Msg { return closeFormMsg{} }
|
||||||
|
|
||||||
|
case "enter":
|
||||||
|
if t.focus == snippetFieldCount-1 {
|
||||||
|
return t.submit()
|
||||||
|
}
|
||||||
|
t.nextField()
|
||||||
|
|
||||||
|
case "tab", "down":
|
||||||
|
t.nextField()
|
||||||
|
|
||||||
|
case "shift+tab", "up":
|
||||||
|
t.prevField()
|
||||||
|
|
||||||
|
case "ctrl+s":
|
||||||
|
return t.submit()
|
||||||
|
|
||||||
|
default:
|
||||||
|
var cmd tea.Cmd
|
||||||
|
t.inputs[t.focus], cmd = t.inputs[t.focus].Update(msg)
|
||||||
|
return t, cmd
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetFormTab) nextField() {
|
||||||
|
t.inputs[t.focus].Blur()
|
||||||
|
t.inputs[t.focus].Prompt = ""
|
||||||
|
t.focus++
|
||||||
|
if t.focus >= snippetFieldCount {
|
||||||
|
t.focus = snippetFieldCount - 1
|
||||||
|
}
|
||||||
|
t.inputs[t.focus].Focus()
|
||||||
|
t.inputs[t.focus].Prompt = "> "
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetFormTab) prevField() {
|
||||||
|
t.inputs[t.focus].Blur()
|
||||||
|
t.inputs[t.focus].Prompt = ""
|
||||||
|
t.focus--
|
||||||
|
if t.focus < 0 {
|
||||||
|
t.focus = 0
|
||||||
|
}
|
||||||
|
t.inputs[t.focus].Focus()
|
||||||
|
t.inputs[t.focus].Prompt = "> "
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetFormTab) submit() (Tab, tea.Cmd) {
|
||||||
|
name := t.inputs[snippetFieldName].Value()
|
||||||
|
command := t.inputs[snippetFieldCommand].Value()
|
||||||
|
|
||||||
|
if name == "" || command == "" {
|
||||||
|
t.err = fmt.Errorf("name and command are required")
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var tags []string
|
||||||
|
if tagStr := t.inputs[snippetFieldTags].Value(); tagStr != "" {
|
||||||
|
for _, tag := range strings.Split(tagStr, ",") {
|
||||||
|
if trimmed := strings.TrimSpace(tag); trimmed != "" {
|
||||||
|
tags = append(tags, trimmed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var sn *models.Snippet
|
||||||
|
if t.mode == snippetFormEdit && t.editing != nil {
|
||||||
|
sn = t.editing
|
||||||
|
sn.Name = name
|
||||||
|
sn.Command = command
|
||||||
|
sn.Description = t.inputs[snippetFieldDescription].Value()
|
||||||
|
sn.Tags = tags
|
||||||
|
} else {
|
||||||
|
sn = &models.Snippet{
|
||||||
|
ID: uuid.New().String(),
|
||||||
|
Name: name,
|
||||||
|
Command: command,
|
||||||
|
Description: t.inputs[snippetFieldDescription].Value(),
|
||||||
|
Tags: tags,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
UpdatedAt: time.Now(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.saved = true
|
||||||
|
return t, saveSnippetCmd(sn, t.dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetFormTab) View() string {
|
||||||
|
contentW := t.width - 12
|
||||||
|
if contentW < 30 {
|
||||||
|
contentW = 30
|
||||||
|
}
|
||||||
|
if contentW > 70 {
|
||||||
|
contentW = 70
|
||||||
|
}
|
||||||
|
|
||||||
|
var inner strings.Builder
|
||||||
|
|
||||||
|
title := "Add Snippet"
|
||||||
|
if t.mode == snippetFormEdit {
|
||||||
|
title = "Edit Snippet"
|
||||||
|
}
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||||
|
lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(title)))
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
|
||||||
|
if t.err != nil {
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center,
|
||||||
|
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := snippetFieldID(0); i < snippetFieldCount; i++ {
|
||||||
|
input := t.inputs[i]
|
||||||
|
label := snippetFieldLabels[i]
|
||||||
|
style := SubtitleStyle
|
||||||
|
if i == t.focus {
|
||||||
|
style = HighlightStyle
|
||||||
|
}
|
||||||
|
inner.WriteString(style.Render(label + ":"))
|
||||||
|
inner.WriteString("\n ")
|
||||||
|
inner.WriteString(input.View())
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
inner.WriteString("\n")
|
||||||
|
footerText := "Ctrl+Tab:switch Ctrl+Q:close Tab:next Shift+Tab:prev ↑↓:nav Enter:next Ctrl+S:save Esc:cancel"
|
||||||
|
footerWrapped := wrapFooter(footerText, contentW)
|
||||||
|
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(contentW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||||
|
inner.WriteString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
box := BorderStyle.Render(inner.String())
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetFormTab) Close() {}
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
type snippetListState int
|
||||||
|
|
||||||
|
const (
|
||||||
|
snippetListLoading snippetListState = iota
|
||||||
|
snippetListReady
|
||||||
|
snippetListError
|
||||||
|
)
|
||||||
|
|
||||||
|
// SnippetListTab displays and manages command snippets
|
||||||
|
type SnippetListTab struct {
|
||||||
|
dataDir string
|
||||||
|
snippets []*models.Snippet
|
||||||
|
selected int
|
||||||
|
state snippetListState
|
||||||
|
err error
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSnippetListTab(dataDir string) *SnippetListTab {
|
||||||
|
return &SnippetListTab{
|
||||||
|
dataDir: dataDir,
|
||||||
|
state: snippetListLoading,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetListTab) Name() string { return "Snippets" }
|
||||||
|
|
||||||
|
func (t *SnippetListTab) Init() tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(t.dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return snippetListLoadedMsg{err: err}
|
||||||
|
}
|
||||||
|
snippets, err := store.ListSnippets(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
return snippetListLoadedMsg{err: err}
|
||||||
|
}
|
||||||
|
return snippetListLoadedMsg{snippets: snippets}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetListTab) Update(msg tea.Msg) (Tab, tea.Cmd) {
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case tea.WindowSizeMsg:
|
||||||
|
t.mu.Lock()
|
||||||
|
t.width = msg.Width
|
||||||
|
t.height = msg.Height
|
||||||
|
t.mu.Unlock()
|
||||||
|
|
||||||
|
case snippetListLoadedMsg:
|
||||||
|
t.mu.Lock()
|
||||||
|
if msg.err != nil {
|
||||||
|
t.state = snippetListError
|
||||||
|
t.err = msg.err
|
||||||
|
} else {
|
||||||
|
t.state = snippetListReady
|
||||||
|
t.snippets = msg.snippets
|
||||||
|
}
|
||||||
|
t.mu.Unlock()
|
||||||
|
|
||||||
|
case saveSnippetResultMsg:
|
||||||
|
return t, t.Init()
|
||||||
|
|
||||||
|
case deleteSnippetResultMsg:
|
||||||
|
if msg.err != nil {
|
||||||
|
t.mu.Lock()
|
||||||
|
t.err = msg.err
|
||||||
|
t.mu.Unlock()
|
||||||
|
}
|
||||||
|
return t, t.Init()
|
||||||
|
|
||||||
|
case tea.KeyMsg:
|
||||||
|
switch msg.String() {
|
||||||
|
case "up", "k":
|
||||||
|
t.mu.Lock()
|
||||||
|
if t.selected > 0 {
|
||||||
|
t.selected--
|
||||||
|
}
|
||||||
|
t.mu.Unlock()
|
||||||
|
|
||||||
|
case "down", "j":
|
||||||
|
t.mu.Lock()
|
||||||
|
if t.selected < len(t.snippets)-1 {
|
||||||
|
t.selected++
|
||||||
|
}
|
||||||
|
t.mu.Unlock()
|
||||||
|
|
||||||
|
case "ctrl+n":
|
||||||
|
return t, func() tea.Msg { return openSnippetFormMsg{} }
|
||||||
|
|
||||||
|
case "ctrl+e":
|
||||||
|
t.mu.Lock()
|
||||||
|
snippets := t.snippets
|
||||||
|
idx := t.selected
|
||||||
|
t.mu.Unlock()
|
||||||
|
if len(snippets) > 0 && idx >= 0 && idx < len(snippets) {
|
||||||
|
return t, func() tea.Msg { return openSnippetFormMsg{editing: snippets[idx]} }
|
||||||
|
}
|
||||||
|
|
||||||
|
case "delete", "d":
|
||||||
|
t.mu.Lock()
|
||||||
|
snippets := t.snippets
|
||||||
|
idx := t.selected
|
||||||
|
t.mu.Unlock()
|
||||||
|
if len(snippets) > 0 && idx >= 0 && idx < len(snippets) {
|
||||||
|
return t, deleteSnippetCmd(snippets[idx].ID, t.dataDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
case "esc":
|
||||||
|
return t, func() tea.Msg { return closeFormMsg{} }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetListTab) View() string {
|
||||||
|
t.mu.Lock()
|
||||||
|
defer t.mu.Unlock()
|
||||||
|
|
||||||
|
if t.state == snippetListLoading {
|
||||||
|
return lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||||
|
SubtitleStyle.Render("Loading snippets..."))
|
||||||
|
}
|
||||||
|
if t.state == snippetListError {
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||||
|
ErrorStyle.Render(fmt.Sprintf("Error: %v", t.err))))
|
||||||
|
b.WriteString("\n")
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center,
|
||||||
|
SubtitleStyle.Render("Press Esc to go back")))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
type styledRow struct {
|
||||||
|
text string
|
||||||
|
plain string
|
||||||
|
}
|
||||||
|
|
||||||
|
titlePlain := "Command Snippets"
|
||||||
|
|
||||||
|
var rows []styledRow
|
||||||
|
if t.err != nil {
|
||||||
|
errLine := fmt.Sprintf("Error: %v", t.err)
|
||||||
|
rows = append(rows, styledRow{text: ErrorStyle.Render(errLine), plain: errLine})
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(t.snippets) == 0 {
|
||||||
|
empty := "No snippets stored."
|
||||||
|
hint := "Press Ctrl+N to add a new snippet."
|
||||||
|
rows = append(rows, styledRow{text: SubtitleStyle.Render(empty), plain: empty})
|
||||||
|
rows = append(rows, styledRow{text: SubtitleStyle.Render(hint), plain: hint})
|
||||||
|
} else {
|
||||||
|
for i, sn := range t.snippets {
|
||||||
|
var plain string
|
||||||
|
if sn.Description != "" {
|
||||||
|
plain = fmt.Sprintf(" %s — %s", sn.Name, sn.Description)
|
||||||
|
} else {
|
||||||
|
plain = fmt.Sprintf(" %s", sn.Name)
|
||||||
|
}
|
||||||
|
var styled string
|
||||||
|
if i == t.selected {
|
||||||
|
styled = lipgloss.NewStyle().
|
||||||
|
Foreground(gbFg).
|
||||||
|
Background(gbBgSel).
|
||||||
|
Bold(true).
|
||||||
|
Render("▸ " + strings.TrimLeft(plain, " "))
|
||||||
|
} else {
|
||||||
|
styled = lipgloss.NewStyle().Foreground(gbFg).Render(plain)
|
||||||
|
}
|
||||||
|
rows = append(rows, styledRow{text: styled, plain: plain})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Responsive width
|
||||||
|
sidePad := adaptiveSidePad(t.width)
|
||||||
|
widestContent := lipgloss.Width(titlePlain)
|
||||||
|
for _, r := range rows {
|
||||||
|
if w := lipgloss.Width(r.plain); w > widestContent {
|
||||||
|
widestContent = w
|
||||||
|
}
|
||||||
|
}
|
||||||
|
targetW := clampWidth(widestContent+sidePad*2, t.width)
|
||||||
|
innerW := targetW - sidePad*2
|
||||||
|
if innerW < 1 {
|
||||||
|
innerW = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Footer (wrapped)
|
||||||
|
footerText := "Ctrl+Tab:switch Ctrl+Q:close ↑↓:nav Ctrl+N:add Ctrl+E:edit D:delete Esc:back"
|
||||||
|
footerWrapped := wrapFooter(footerText, innerW)
|
||||||
|
|
||||||
|
// Render
|
||||||
|
var inner strings.Builder
|
||||||
|
titleStyled := lipgloss.NewStyle().Bold(true).Foreground(gbYellow).Render(titlePlain)
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, titleStyled))
|
||||||
|
inner.WriteString("\n\n")
|
||||||
|
|
||||||
|
for _, r := range rows {
|
||||||
|
styled := r.text
|
||||||
|
if lipgloss.Width(r.plain) > innerW {
|
||||||
|
styled = truncateStr(r.text, innerW)
|
||||||
|
}
|
||||||
|
line := lipgloss.PlaceHorizontal(targetW, lipgloss.Center, styled)
|
||||||
|
inner.WriteString(line)
|
||||||
|
inner.WriteString("\n")
|
||||||
|
}
|
||||||
|
inner.WriteString("\n")
|
||||||
|
|
||||||
|
for _, line := range strings.Split(footerWrapped, "\n") {
|
||||||
|
inner.WriteString(lipgloss.PlaceHorizontal(targetW, lipgloss.Center, SubtitleStyle.Render(line)))
|
||||||
|
inner.WriteString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
box := BorderStyle.Render(inner.String())
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString(lipgloss.PlaceHorizontal(t.width, lipgloss.Center, box))
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SnippetListTab) Close() {}
|
||||||
|
|
||||||
|
// SetSnippets updates the snippet list data directly (used for refresh)
|
||||||
|
func (t *SnippetListTab) SetSnippets(snippets []*models.Snippet) {
|
||||||
|
t.mu.Lock()
|
||||||
|
defer t.mu.Unlock()
|
||||||
|
t.state = snippetListReady
|
||||||
|
t.snippets = snippets
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindSnippetListTab finds the first SnippetListTab in a list of tabs
|
||||||
|
func FindSnippetListTab(tabs []Tab) *SnippetListTab {
|
||||||
|
for _, tab := range tabs {
|
||||||
|
if st, ok := tab.(*SnippetListTab); ok {
|
||||||
|
return st
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// snippetListLoadedMsg carries the loaded snippet list
|
||||||
|
type snippetListLoadedMsg struct {
|
||||||
|
snippets []*models.Snippet
|
||||||
|
err error
|
||||||
|
}
|
||||||
+137
@@ -0,0 +1,137 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
// sshConnectCmd builds and runs a native SSH command via tea.ExecProcess.
|
||||||
|
// Password auth: sshpass -e ssh user@host (SSHPASS env)
|
||||||
|
// Key auth: ssh -i <tmpfile> user@host (SSH_ASKPASS for passphrase)
|
||||||
|
//
|
||||||
|
// Must return tea.ExecProcess directly (NOT wrapped in another closure)
|
||||||
|
// so Bubble Tea can execute the process command correctly.
|
||||||
|
func sshConnectCmd(host *models.Host, dataDir string) tea.Cmd {
|
||||||
|
port := host.Port
|
||||||
|
if port == 0 {
|
||||||
|
port = 22
|
||||||
|
}
|
||||||
|
portStr := strconv.Itoa(port)
|
||||||
|
target := fmt.Sprintf("%s@%s", host.Username, host.Hostname)
|
||||||
|
ctrlSock := fmt.Sprintf("/tmp/hk-%s", host.ID)
|
||||||
|
env := os.Environ()
|
||||||
|
|
||||||
|
// Common SSH args
|
||||||
|
sshArgs := []string{
|
||||||
|
"-p", portStr,
|
||||||
|
"-o", "StrictHostKeyChecking=accept-new",
|
||||||
|
"-o", "ServerAliveInterval=60",
|
||||||
|
"-o", "ServerAliveCountMax=3",
|
||||||
|
"-S", ctrlSock,
|
||||||
|
"-o", "ControlMaster=auto",
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup := func() {
|
||||||
|
exec.Command("ssh", "-S", ctrlSock, "-O", "exit", target).Run()
|
||||||
|
}
|
||||||
|
|
||||||
|
switch host.Auth.Type {
|
||||||
|
case "password":
|
||||||
|
allArgs := append([]string{"-e", "ssh"}, sshArgs...)
|
||||||
|
allArgs = append(allArgs, target)
|
||||||
|
cmd := exec.Command("sshpass", allArgs...)
|
||||||
|
cmd.Env = append(env, "SSHPASS="+host.Auth.Password)
|
||||||
|
return tea.ExecProcess(cmd, func(err error) tea.Msg {
|
||||||
|
cleanup()
|
||||||
|
return sshExitMsg{err: err}
|
||||||
|
})
|
||||||
|
|
||||||
|
case "key":
|
||||||
|
keyContent, err := loadKeyContent(host, dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return errorCmd(fmt.Errorf("load key: %w", err))
|
||||||
|
}
|
||||||
|
tmpFile, err := os.CreateTemp("", "hk-key-*")
|
||||||
|
if err != nil {
|
||||||
|
return errorCmd(fmt.Errorf("create temp key: %w", err))
|
||||||
|
}
|
||||||
|
tmpPath := tmpFile.Name()
|
||||||
|
if _, err := tmpFile.Write([]byte(keyContent)); err != nil {
|
||||||
|
tmpFile.Close()
|
||||||
|
os.Remove(tmpPath)
|
||||||
|
return errorCmd(fmt.Errorf("write temp key: %w", err))
|
||||||
|
}
|
||||||
|
tmpFile.Close()
|
||||||
|
os.Chmod(tmpPath, 0600)
|
||||||
|
|
||||||
|
keyArgs := append([]string{"-i", tmpPath}, sshArgs...)
|
||||||
|
keyArgs = append(keyArgs, target)
|
||||||
|
cmd := exec.Command("ssh", keyArgs...)
|
||||||
|
|
||||||
|
if host.Auth.Password != "" {
|
||||||
|
self, err := os.Executable()
|
||||||
|
if err == nil {
|
||||||
|
script := fmt.Sprintf("#!/bin/sh\nexec %q askpass\n", self)
|
||||||
|
f, err := os.CreateTemp("", "hk-askpass-*.sh")
|
||||||
|
if err == nil {
|
||||||
|
f.WriteString(script)
|
||||||
|
f.Close()
|
||||||
|
os.Chmod(f.Name(), 0700)
|
||||||
|
env = append(env,
|
||||||
|
"HK_PASSPHRASE="+host.Auth.Password,
|
||||||
|
"SSH_ASKPASS="+f.Name(),
|
||||||
|
"SSH_ASKPASS_REQUIRE=force",
|
||||||
|
)
|
||||||
|
if os.Getenv("DISPLAY") == "" {
|
||||||
|
env = append(env, "DISPLAY=:0")
|
||||||
|
}
|
||||||
|
if setsid, err := exec.LookPath("setsid"); err == nil {
|
||||||
|
newArgs := append([]string{"ssh"}, keyArgs...)
|
||||||
|
cmd = exec.Command(setsid, newArgs...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd.Env = env
|
||||||
|
return tea.ExecProcess(cmd, func(err error) tea.Msg {
|
||||||
|
os.Remove(tmpPath)
|
||||||
|
cleanup()
|
||||||
|
return sshExitMsg{err: err}
|
||||||
|
})
|
||||||
|
|
||||||
|
default:
|
||||||
|
return errorCmd(fmt.Errorf("unsupported auth type: %s", host.Auth.Type))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// errorCmd returns a Cmd that sends an sshExitMsg with the given error.
|
||||||
|
func errorCmd(err error) tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
return sshExitMsg{err: err}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadKeyContent reads the private key content for a host
|
||||||
|
func loadKeyContent(host *models.Host, dataDir string) (string, error) {
|
||||||
|
if host.Auth.KeyID == "" {
|
||||||
|
return "", fmt.Errorf("key auth requires key_id")
|
||||||
|
}
|
||||||
|
store, err := storage.NewJSONStorage(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
keyPair, err := store.GetKeyPair(context.Background(), host.Auth.KeyID)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("load key %s: %w", host.Auth.KeyID, err)
|
||||||
|
}
|
||||||
|
return keyPair.PrivateKey, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import "github.com/charmbracelet/lipgloss"
|
||||||
|
|
||||||
|
// Gruvbox Material Dark Hard palette — warm, soft, easy on eyes
|
||||||
|
var (
|
||||||
|
gbFg = lipgloss.Color("#d4be98") // primary text
|
||||||
|
gbFgMute = lipgloss.Color("#7c6f64") // secondary/hints
|
||||||
|
gbBgSel = lipgloss.Color("#45403d") // cursor row bg
|
||||||
|
gbRed = lipgloss.Color("#ea6962") // error/destructive
|
||||||
|
gbOrange = lipgloss.Color("#e78a4e") // section headers
|
||||||
|
gbYellow = lipgloss.Color("#d8a657") // accent/titles
|
||||||
|
gbGreen = lipgloss.Color("#a9b665") // active pane/success
|
||||||
|
gbAqua = lipgloss.Color("#89b482") // interactive keys
|
||||||
|
gbBlue = lipgloss.Color("#7daea3")
|
||||||
|
gbPurple = lipgloss.Color("#d3869b")
|
||||||
|
gbBorder = lipgloss.Color("#504945") // subtle border
|
||||||
|
)
|
||||||
|
|
||||||
|
// Component styles
|
||||||
|
var (
|
||||||
|
TabActiveStyle = lipgloss.NewStyle().Background(gbYellow).Foreground(lipgloss.Color("#1d2021")).Bold(true).Padding(0, 2)
|
||||||
|
TabInactiveStyle = lipgloss.NewStyle().Background(gbBorder).Foreground(gbFgMute).Padding(0, 2)
|
||||||
|
TabBarStyle = lipgloss.NewStyle().Background(lipgloss.Color("#1d2021"))
|
||||||
|
StatusBarStyle = lipgloss.NewStyle().Background(gbGreen).Foreground(lipgloss.Color("#1d2021")).Padding(0, 1)
|
||||||
|
AppTitleStyle = lipgloss.NewStyle().Foreground(gbYellow).Bold(true)
|
||||||
|
HighlightStyle = lipgloss.NewStyle().Foreground(gbOrange).Bold(true)
|
||||||
|
SelectedStyle = lipgloss.NewStyle().Foreground(gbFg).Background(gbBgSel).Bold(true).Padding(0, 1)
|
||||||
|
ErrorStyle = lipgloss.NewStyle().Foreground(gbRed).Bold(true)
|
||||||
|
SuccessStyle = lipgloss.NewStyle().Foreground(gbGreen).Bold(true)
|
||||||
|
InfoStyle = lipgloss.NewStyle().Foreground(gbAqua)
|
||||||
|
SubtitleStyle = lipgloss.NewStyle().Foreground(gbFgMute)
|
||||||
|
HostNameStyle = lipgloss.NewStyle().Foreground(gbYellow).Bold(true)
|
||||||
|
HostDetailStyle = lipgloss.NewStyle().Foreground(gbFgMute)
|
||||||
|
TagStyle = lipgloss.NewStyle().Foreground(gbGreen)
|
||||||
|
TitleStyle = AppTitleStyle
|
||||||
|
SectionStyle = lipgloss.NewStyle().Foreground(gbOrange).Bold(true)
|
||||||
|
BorderStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(gbBorder).Padding(1, 2)
|
||||||
|
)
|
||||||
|
|
||||||
|
// TabWidth returns the width of the tab bar content
|
||||||
|
func TabBarWidth(totalWidth int) int {
|
||||||
|
if totalWidth < 10 {
|
||||||
|
return totalWidth
|
||||||
|
}
|
||||||
|
return totalWidth - 2
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pane styles for dual-pane layout
|
||||||
|
var (
|
||||||
|
StylePaneActive = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(gbGreen).Padding(0, 1)
|
||||||
|
StylePaneInactive = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(gbBorder).Padding(0, 1)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Host card styles
|
||||||
|
var (
|
||||||
|
HostCardStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(gbBorder).Padding(0, 1)
|
||||||
|
HostCardActiveStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(gbGreen).Padding(0, 1)
|
||||||
|
)
|
||||||
+231
@@ -0,0 +1,231 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Tab represents a single tab in the TUI
|
||||||
|
type Tab interface {
|
||||||
|
Init() tea.Cmd
|
||||||
|
Update(tea.Msg) (Tab, tea.Cmd)
|
||||||
|
View() string
|
||||||
|
Name() string
|
||||||
|
// Close is called when the tab is removed; implement for cleanup (e.g. disconnect SSH)
|
||||||
|
Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TabManager manages multiple tabs
|
||||||
|
type TabManager struct {
|
||||||
|
tabs []Tab
|
||||||
|
active int
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTabManager creates a new TabManager with an initial tab
|
||||||
|
func NewTabManager(initial Tab) *TabManager {
|
||||||
|
return &TabManager{
|
||||||
|
tabs: []Tab{initial},
|
||||||
|
active: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Active returns the currently active tab
|
||||||
|
func (tm *TabManager) Active() Tab {
|
||||||
|
if len(tm.tabs) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return tm.tabs[tm.active]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add adds a new tab, switches to it, and returns its init command
|
||||||
|
func (tm *TabManager) Add(tab Tab) tea.Cmd {
|
||||||
|
tm.tabs = append(tm.tabs, tab)
|
||||||
|
tm.active = len(tm.tabs) - 1
|
||||||
|
|
||||||
|
// Forward current terminal size so new tabs know their dimensions
|
||||||
|
if tm.width > 0 && tm.height > 0 {
|
||||||
|
updated, _ := tab.Update(tea.WindowSizeMsg{Width: tm.width, Height: tm.height})
|
||||||
|
tm.tabs[tm.active] = updated
|
||||||
|
}
|
||||||
|
|
||||||
|
return tab.Init()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close removes the tab at index and returns the active tab
|
||||||
|
func (tm *TabManager) Close(index int) Tab {
|
||||||
|
if index < 0 || index >= len(tm.tabs) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call Close for cleanup (e.g. disconnect SSH)
|
||||||
|
tm.tabs[index].Close()
|
||||||
|
|
||||||
|
tm.tabs = append(tm.tabs[:index], tm.tabs[index+1:]...)
|
||||||
|
|
||||||
|
if len(tm.tabs) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if tm.active >= len(tm.tabs) {
|
||||||
|
tm.active = len(tm.tabs) - 1
|
||||||
|
}
|
||||||
|
return tm.tabs[tm.active]
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloseActive closes the active tab
|
||||||
|
func (tm *TabManager) CloseActive() Tab {
|
||||||
|
if len(tm.tabs) <= 1 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return tm.Close(tm.active)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Next switches to the next tab
|
||||||
|
func (tm *TabManager) Next() {
|
||||||
|
if len(tm.tabs) <= 1 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tm.active = (tm.active + 1) % len(tm.tabs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prev switches to the previous tab
|
||||||
|
func (tm *TabManager) Prev() {
|
||||||
|
if len(tm.tabs) <= 1 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tm.active--
|
||||||
|
if tm.active < 0 {
|
||||||
|
tm.active = len(tm.tabs) - 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Len returns the number of tabs
|
||||||
|
func (tm *TabManager) Len() int {
|
||||||
|
return len(tm.tabs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetSize updates the terminal size for the tab manager
|
||||||
|
func (tm *TabManager) SetSize(width, height int) {
|
||||||
|
tm.width = width
|
||||||
|
tm.height = height
|
||||||
|
}
|
||||||
|
|
||||||
|
// Init initializes all tabs
|
||||||
|
func (tm *TabManager) Init() tea.Cmd {
|
||||||
|
var cmds []tea.Cmd
|
||||||
|
for _, t := range tm.tabs {
|
||||||
|
if cmd := t.Init(); cmd != nil {
|
||||||
|
cmds = append(cmds, cmd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tea.Batch(cmds...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update sends a message to the active tab
|
||||||
|
func (tm *TabManager) Update(msg tea.Msg) (tea.Cmd, error) {
|
||||||
|
if len(tm.tabs) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle tab-level keys
|
||||||
|
if keyMsg, ok := msg.(tea.KeyMsg); ok {
|
||||||
|
switch keyMsg.String() {
|
||||||
|
case "ctrl+tab":
|
||||||
|
tm.Next()
|
||||||
|
return nil, nil
|
||||||
|
case "shift+tab":
|
||||||
|
tm.Prev()
|
||||||
|
return nil, nil
|
||||||
|
case "ctrl+q":
|
||||||
|
if closed := tm.CloseActive(); closed != nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle window resize — forward to ALL tabs
|
||||||
|
if wsMsg, ok := msg.(tea.WindowSizeMsg); ok {
|
||||||
|
tm.SetSize(wsMsg.Width, wsMsg.Height)
|
||||||
|
for i, t := range tm.tabs {
|
||||||
|
updated, _ := t.Update(msg)
|
||||||
|
tm.tabs[i] = updated
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
updated, cmd := tm.tabs[tm.active].Update(msg)
|
||||||
|
tm.tabs[tm.active] = updated
|
||||||
|
return cmd, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// View renders the tab bar and active tab content
|
||||||
|
func (tm *TabManager) View() string {
|
||||||
|
if len(tm.tabs) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
var b strings.Builder
|
||||||
|
|
||||||
|
// Render tab bar
|
||||||
|
b.WriteString(renderTabBar(tm))
|
||||||
|
|
||||||
|
// Render active tab content
|
||||||
|
content := tm.tabs[tm.active].View()
|
||||||
|
if content != "" {
|
||||||
|
b.WriteString("\n")
|
||||||
|
b.WriteString(content)
|
||||||
|
}
|
||||||
|
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderTabBar renders the top tab bar (responsive: truncates names on overflow)
|
||||||
|
func renderTabBar(tm *TabManager) string {
|
||||||
|
if len(tm.tabs) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
const cellPad = 4 // Padding(0,2) per tab = 2 left + 2 right
|
||||||
|
|
||||||
|
availW := tm.width - 2
|
||||||
|
if availW < 1 {
|
||||||
|
availW = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Measure total width and decide if truncation is needed
|
||||||
|
totalW := 0
|
||||||
|
for _, tab := range tm.tabs {
|
||||||
|
totalW += lipgloss.Width(tab.Name()) + cellPad
|
||||||
|
}
|
||||||
|
|
||||||
|
maxNameW := 0
|
||||||
|
if totalW > availW {
|
||||||
|
perTab := availW / len(tm.tabs)
|
||||||
|
maxNameW = perTab - cellPad
|
||||||
|
if maxNameW < 1 {
|
||||||
|
maxNameW = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var cells []string
|
||||||
|
for i, tab := range tm.tabs {
|
||||||
|
name := tab.Name()
|
||||||
|
if maxNameW > 0 && lipgloss.Width(name) > maxNameW {
|
||||||
|
name = truncateStr(name, maxNameW)
|
||||||
|
}
|
||||||
|
if i == tm.active {
|
||||||
|
cells = append(cells, TabActiveStyle.Render(name))
|
||||||
|
} else {
|
||||||
|
cells = append(cells, TabInactiveStyle.Render(name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bar := strings.Join(cells, "")
|
||||||
|
return TabBarStyle.Render(bar)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package tui
|
||||||
|
|
||||||
|
import "github.com/charmbracelet/lipgloss"
|
||||||
|
|
||||||
|
// Theme defines a complete color palette for the TUI
|
||||||
|
type Theme struct {
|
||||||
|
Name string
|
||||||
|
Fg lipgloss.Color
|
||||||
|
FgMute lipgloss.Color
|
||||||
|
Bg lipgloss.Color
|
||||||
|
BgSel lipgloss.Color
|
||||||
|
Red lipgloss.Color
|
||||||
|
Orange lipgloss.Color
|
||||||
|
Yellow lipgloss.Color
|
||||||
|
Green lipgloss.Color
|
||||||
|
Aqua lipgloss.Color
|
||||||
|
Blue lipgloss.Color
|
||||||
|
Purple lipgloss.Color
|
||||||
|
Border lipgloss.Color
|
||||||
|
TabBg lipgloss.Color
|
||||||
|
}
|
||||||
|
|
||||||
|
// Predefined themes
|
||||||
|
var (
|
||||||
|
ThemeDark = Theme{
|
||||||
|
Name: "dark",
|
||||||
|
Fg: lipgloss.Color("#d4be98"),
|
||||||
|
FgMute: lipgloss.Color("#7c6f64"),
|
||||||
|
Bg: lipgloss.Color("#1d2021"),
|
||||||
|
BgSel: lipgloss.Color("#45403d"),
|
||||||
|
Red: lipgloss.Color("#ea6962"),
|
||||||
|
Orange: lipgloss.Color("#e78a4e"),
|
||||||
|
Yellow: lipgloss.Color("#d8a657"),
|
||||||
|
Green: lipgloss.Color("#a9b665"),
|
||||||
|
Aqua: lipgloss.Color("#89b482"),
|
||||||
|
Blue: lipgloss.Color("#7daea3"),
|
||||||
|
Purple: lipgloss.Color("#d3869b"),
|
||||||
|
Border: lipgloss.Color("#504945"),
|
||||||
|
TabBg: lipgloss.Color("#1d2021"),
|
||||||
|
}
|
||||||
|
|
||||||
|
ThemeLight = Theme{
|
||||||
|
Name: "light",
|
||||||
|
Fg: lipgloss.Color("#3c3836"),
|
||||||
|
FgMute: lipgloss.Color("#7c6f64"),
|
||||||
|
Bg: lipgloss.Color("#f2e5bc"),
|
||||||
|
BgSel: lipgloss.Color("#d5c4a1"),
|
||||||
|
Red: lipgloss.Color("#cc241d"),
|
||||||
|
Orange: lipgloss.Color("#d65d0e"),
|
||||||
|
Yellow: lipgloss.Color("#d79921"),
|
||||||
|
Green: lipgloss.Color("#98971a"),
|
||||||
|
Aqua: lipgloss.Color("#689d6a"),
|
||||||
|
Blue: lipgloss.Color("#458588"),
|
||||||
|
Purple: lipgloss.Color("#b16286"),
|
||||||
|
Border: lipgloss.Color("#a89984"),
|
||||||
|
TabBg: lipgloss.Color("#f2e5bc"),
|
||||||
|
}
|
||||||
|
|
||||||
|
ThemeDracula = Theme{
|
||||||
|
Name: "dracula",
|
||||||
|
Fg: lipgloss.Color("#f8f8f2"),
|
||||||
|
FgMute: lipgloss.Color("#6272a4"),
|
||||||
|
Bg: lipgloss.Color("#282a36"),
|
||||||
|
BgSel: lipgloss.Color("#44475a"),
|
||||||
|
Red: lipgloss.Color("#ff5555"),
|
||||||
|
Orange: lipgloss.Color("#ffb86c"),
|
||||||
|
Yellow: lipgloss.Color("#f1fa8c"),
|
||||||
|
Green: lipgloss.Color("#50fa7b"),
|
||||||
|
Aqua: lipgloss.Color("#8be9fd"),
|
||||||
|
Blue: lipgloss.Color("#6272a4"),
|
||||||
|
Purple: lipgloss.Color("#bd93f9"),
|
||||||
|
Border: lipgloss.Color("#44475a"),
|
||||||
|
TabBg: lipgloss.Color("#282a36"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Themes is the registry of all available themes
|
||||||
|
var Themes = map[string]Theme{
|
||||||
|
"dark": ThemeDark,
|
||||||
|
"light": ThemeLight,
|
||||||
|
"dracula": ThemeDracula,
|
||||||
|
}
|
||||||
|
|
||||||
|
// activeTheme holds the currently active theme
|
||||||
|
var activeTheme = ThemeDark
|
||||||
|
|
||||||
|
// GetTheme returns a theme by name, defaults to dark
|
||||||
|
func GetTheme(name string) Theme {
|
||||||
|
if t, ok := Themes[name]; ok {
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
return ThemeDark
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetTheme applies a theme by name and updates all component styles
|
||||||
|
func SetTheme(name string) {
|
||||||
|
theme := GetTheme(name)
|
||||||
|
activeTheme = theme
|
||||||
|
applyTheme(theme)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetActiveTheme returns the currently active theme
|
||||||
|
func GetActiveTheme() Theme {
|
||||||
|
return activeTheme
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyTheme updates all component styles from the given theme
|
||||||
|
func applyTheme(t Theme) {
|
||||||
|
// Palette aliases
|
||||||
|
gbFg = t.Fg
|
||||||
|
gbFgMute = t.FgMute
|
||||||
|
gbBgSel = t.BgSel
|
||||||
|
gbRed = t.Red
|
||||||
|
gbOrange = t.Orange
|
||||||
|
gbYellow = t.Yellow
|
||||||
|
gbGreen = t.Green
|
||||||
|
gbAqua = t.Aqua
|
||||||
|
gbBlue = t.Blue
|
||||||
|
gbPurple = t.Purple
|
||||||
|
gbBorder = t.Border
|
||||||
|
|
||||||
|
// Component styles
|
||||||
|
TabActiveStyle = lipgloss.NewStyle().Background(t.Yellow).Foreground(t.Bg).Bold(true).Padding(0, 2)
|
||||||
|
TabInactiveStyle = lipgloss.NewStyle().Background(t.Border).Foreground(t.FgMute).Padding(0, 2)
|
||||||
|
TabBarStyle = lipgloss.NewStyle().Background(t.TabBg)
|
||||||
|
StatusBarStyle = lipgloss.NewStyle().Background(t.Green).Foreground(t.Bg).Padding(0, 1)
|
||||||
|
AppTitleStyle = lipgloss.NewStyle().Foreground(t.Yellow).Bold(true)
|
||||||
|
HighlightStyle = lipgloss.NewStyle().Foreground(t.Orange).Bold(true)
|
||||||
|
SelectedStyle = lipgloss.NewStyle().Foreground(t.Fg).Background(t.BgSel).Bold(true).Padding(0, 1)
|
||||||
|
ErrorStyle = lipgloss.NewStyle().Foreground(t.Red).Bold(true)
|
||||||
|
SuccessStyle = lipgloss.NewStyle().Foreground(t.Green).Bold(true)
|
||||||
|
InfoStyle = lipgloss.NewStyle().Foreground(t.Aqua)
|
||||||
|
SubtitleStyle = lipgloss.NewStyle().Foreground(t.FgMute)
|
||||||
|
HostNameStyle = lipgloss.NewStyle().Foreground(t.Yellow).Bold(true)
|
||||||
|
HostDetailStyle = lipgloss.NewStyle().Foreground(t.FgMute)
|
||||||
|
TagStyle = lipgloss.NewStyle().Foreground(t.Green)
|
||||||
|
TitleStyle = AppTitleStyle
|
||||||
|
SectionStyle = lipgloss.NewStyle().Foreground(t.Orange).Bold(true)
|
||||||
|
BorderStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(t.Border).Padding(1, 2)
|
||||||
|
|
||||||
|
// Pane styles
|
||||||
|
StylePaneActive = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(t.Green).Padding(0, 1)
|
||||||
|
StylePaneInactive = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(t.Border).Padding(0, 1)
|
||||||
|
|
||||||
|
// Host card styles
|
||||||
|
HostCardStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(t.Border).Padding(0, 1)
|
||||||
|
HostCardActiveStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(t.Green).Padding(0, 1)
|
||||||
|
}
|
||||||
+321
-38
@@ -1,23 +1,16 @@
|
|||||||
package tui
|
package tui
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
"github.com/charmbracelet/lipgloss"
|
|
||||||
|
|
||||||
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/knownhosts"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Styles for TUI components
|
// Screen represents different TUI screens (deprecated, use tabs)
|
||||||
var (
|
|
||||||
TitleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("86")).Bold(true)
|
|
||||||
SubtitleStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
|
|
||||||
HighlightStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("212")).Bold(true)
|
|
||||||
ErrorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("196")).Bold(true)
|
|
||||||
SuccessStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("76")).Bold(true)
|
|
||||||
InfoStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("117"))
|
|
||||||
)
|
|
||||||
|
|
||||||
// Screen represents different TUI screens
|
|
||||||
type Screen int
|
type Screen int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -28,16 +21,28 @@ const (
|
|||||||
|
|
||||||
// Model represents the main TUI model
|
// Model represents the main TUI model
|
||||||
type Model struct {
|
type Model struct {
|
||||||
CurrentScreen Screen
|
tabs *TabManager
|
||||||
Hosts []*models.Host
|
CurrentScreen Screen // deprecated, kept for backward compat
|
||||||
SelectedIndex int
|
Hosts []*models.Host // deprecated
|
||||||
|
SelectedIndex int // deprecated
|
||||||
Error error
|
Error error
|
||||||
Quit bool
|
Quit bool
|
||||||
|
dataDir string
|
||||||
|
program *tea.Program
|
||||||
|
|
||||||
|
// Security
|
||||||
|
storagePassword string
|
||||||
|
knownHosts *knownhosts.KnownHosts
|
||||||
|
showEncryptPrompt bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new TUI model
|
// New creates a new TUI model
|
||||||
func New() *Model {
|
func New() *Model {
|
||||||
|
hostList := NewHostListTab()
|
||||||
|
tm := NewTabManager(hostList)
|
||||||
|
|
||||||
return &Model{
|
return &Model{
|
||||||
|
tabs: tm,
|
||||||
CurrentScreen: ScreenHostList,
|
CurrentScreen: ScreenHostList,
|
||||||
SelectedIndex: 0,
|
SelectedIndex: 0,
|
||||||
Quit: false,
|
Quit: false,
|
||||||
@@ -46,56 +51,334 @@ func New() *Model {
|
|||||||
|
|
||||||
// Init initializes the TUI
|
// Init initializes the TUI
|
||||||
func (m *Model) Init() tea.Cmd {
|
func (m *Model) Init() tea.Cmd {
|
||||||
return nil
|
if m.showEncryptPrompt {
|
||||||
|
// Show password prompt tab
|
||||||
|
tab := NewPasswordPromptTab(passwordModeSetup, m.dataDir, func(password string) {
|
||||||
|
m.storagePassword = password
|
||||||
|
})
|
||||||
|
cmd := m.tabs.Add(tab)
|
||||||
|
m.showEncryptPrompt = false
|
||||||
|
return cmd
|
||||||
|
}
|
||||||
|
return m.tabs.Init()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetProgram stores a reference to the tea.Program for sending messages from goroutines
|
||||||
|
func (m *Model) SetProgram(p *tea.Program) {
|
||||||
|
m.program = p
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetStoragePassword sets the master password for encrypted storage
|
||||||
|
func (m *Model) SetStoragePassword(password string) {
|
||||||
|
m.storagePassword = password
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetKnownHosts sets the known_hosts manager for host key verification
|
||||||
|
func (m *Model) SetKnownHosts(kh *knownhosts.KnownHosts) {
|
||||||
|
m.knownHosts = kh
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShowEncryptPrompt sets a flag to show the encryption setup prompt on first render
|
||||||
|
func (m *Model) ShowEncryptPrompt() {
|
||||||
|
m.showEncryptPrompt = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update handles messages and updates the model
|
// Update handles messages and updates the model
|
||||||
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
case tea.KeyMsg:
|
case tea.KeyMsg:
|
||||||
switch msg.String() {
|
// Only hard quit on ctrl+c (let tabs handle q)
|
||||||
case "ctrl+c", "q":
|
if msg.String() == "ctrl+c" {
|
||||||
m.Quit = true
|
m.Quit = true
|
||||||
return m, tea.Quit
|
return m, tea.Quit
|
||||||
|
}
|
||||||
|
|
||||||
case "up", "k":
|
case quitMsg:
|
||||||
if m.SelectedIndex > 0 {
|
m.Quit = true
|
||||||
m.SelectedIndex--
|
return m, tea.Quit
|
||||||
}
|
|
||||||
|
|
||||||
case "down", "j":
|
case sshConnectToMsg:
|
||||||
if m.SelectedIndex < len(m.Hosts)-1 {
|
return m, tea.Batch(tea.ClearScreen, sshConnectCmd(msg.host, m.dataDir))
|
||||||
m.SelectedIndex++
|
|
||||||
}
|
|
||||||
|
|
||||||
case "enter", " ":
|
case sshExitMsg:
|
||||||
if len(m.Hosts) > 0 {
|
if msg.err != nil {
|
||||||
return m, tea.Quit
|
m.Error = msg.err
|
||||||
|
}
|
||||||
|
return m, tea.ClearScreen
|
||||||
|
|
||||||
|
case openHostFormMsg:
|
||||||
|
var tab Tab
|
||||||
|
if msg.editing != nil {
|
||||||
|
tab = NewEditHostFormTab(msg.editing, m.dataDir)
|
||||||
|
} else {
|
||||||
|
tab = NewAddHostFormTab(m.dataDir)
|
||||||
|
}
|
||||||
|
cmd := m.tabs.Add(tab)
|
||||||
|
return m, cmd
|
||||||
|
|
||||||
|
case passwordSetMsg:
|
||||||
|
// Password was set — store it and load hosts
|
||||||
|
m.storagePassword = msg.password
|
||||||
|
|
||||||
|
// Load hosts with the password
|
||||||
|
store, err := storage.NewJSONStorage(m.dataDir)
|
||||||
|
if err == nil {
|
||||||
|
store.SetPassword(msg.password)
|
||||||
|
ctx := context.Background()
|
||||||
|
hosts, loadErr := store.ListHosts(ctx)
|
||||||
|
if loadErr == nil {
|
||||||
|
m.Hosts = hosts
|
||||||
|
// Update host list tab if it exists
|
||||||
|
if hl, ok := m.tabs.Active().(*HostListTab); ok {
|
||||||
|
hl.SetHosts(hosts)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Close the password prompt tab
|
||||||
|
if m.tabs.Len() > 1 {
|
||||||
|
m.tabs.CloseActive()
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
|
||||||
|
case openEncryptPromptMsg:
|
||||||
|
// Show password setup prompt
|
||||||
|
tab := NewPasswordPromptTab(passwordModeSetup, m.dataDir, func(password string) {
|
||||||
|
m.storagePassword = password
|
||||||
|
})
|
||||||
|
cmd := m.tabs.Add(tab)
|
||||||
|
return m, cmd
|
||||||
|
|
||||||
|
case openSFTPMsg:
|
||||||
|
tab := NewSFTPBrowserTab(msg.host, m.dataDir)
|
||||||
|
if m.program != nil {
|
||||||
|
tab.SetProgram(m.program)
|
||||||
|
}
|
||||||
|
if m.storagePassword != "" {
|
||||||
|
tab.SetStoragePassword(m.storagePassword)
|
||||||
|
}
|
||||||
|
if m.knownHosts != nil {
|
||||||
|
tab.SetPassphraseCallback(func() string {
|
||||||
|
// TODO: prompt for passphrase in TUI
|
||||||
|
return ""
|
||||||
|
})
|
||||||
|
}
|
||||||
|
cmd := m.tabs.Add(tab)
|
||||||
|
return m, cmd
|
||||||
|
|
||||||
|
case openKeyListMsg:
|
||||||
|
tab := NewKeyListTab(m.dataDir)
|
||||||
|
cmd := m.tabs.Add(tab)
|
||||||
|
return m, cmd
|
||||||
|
|
||||||
|
case openSnippetListMsg:
|
||||||
|
tab := NewSnippetListTab(m.dataDir)
|
||||||
|
cmd := m.tabs.Add(tab)
|
||||||
|
return m, cmd
|
||||||
|
|
||||||
|
case openKeyFormMsg:
|
||||||
|
var tab Tab
|
||||||
|
if msg.editing != nil {
|
||||||
|
tab = NewEditKeyFormTab(msg.editing, m.dataDir)
|
||||||
|
} else {
|
||||||
|
tab = NewAddKeyFormTab(m.dataDir)
|
||||||
|
}
|
||||||
|
cmd := m.tabs.Add(tab)
|
||||||
|
return m, cmd
|
||||||
|
|
||||||
|
case openSnippetFormMsg:
|
||||||
|
var tab Tab
|
||||||
|
if msg.editing != nil {
|
||||||
|
tab = NewEditSnippetFormTab(msg.editing, m.dataDir)
|
||||||
|
} else {
|
||||||
|
tab = NewAddSnippetFormTab(m.dataDir)
|
||||||
|
}
|
||||||
|
cmd := m.tabs.Add(tab)
|
||||||
|
return m, cmd
|
||||||
|
|
||||||
|
case closeFormMsg:
|
||||||
|
if m.tabs.Len() > 1 {
|
||||||
|
m.tabs.CloseActive()
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
|
||||||
|
case saveHostResultMsg:
|
||||||
|
if msg.err != nil {
|
||||||
|
m.Error = msg.err
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
// Close the form tab, switch back to host list
|
||||||
|
if m.tabs.Len() > 1 {
|
||||||
|
m.tabs.CloseActive()
|
||||||
|
}
|
||||||
|
// Reload hosts
|
||||||
|
return m, func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(m.dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
hosts, err := store.ListHosts(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return loadedHostsMsg{hosts: hosts}
|
||||||
|
}
|
||||||
|
|
||||||
|
case loadedHostsMsg:
|
||||||
|
m.LoadHosts(msg.hosts)
|
||||||
|
|
||||||
|
case saveKeyResultMsg:
|
||||||
|
if msg.err != nil {
|
||||||
|
m.Error = msg.err
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
// Close form tab and switch back to list
|
||||||
|
if m.tabs.Len() > 1 {
|
||||||
|
m.tabs.CloseActive()
|
||||||
|
}
|
||||||
|
// Reload keys
|
||||||
|
return m, func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(m.dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
keys, err := store.ListKeyPairs(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return keyListLoadedMsg{keys: keys}
|
||||||
|
}
|
||||||
|
|
||||||
|
case deleteKeyResultMsg:
|
||||||
|
if msg.err != nil {
|
||||||
|
m.Error = msg.err
|
||||||
|
}
|
||||||
|
// Reload keys
|
||||||
|
return m, func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(m.dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
keys, err := store.ListKeyPairs(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return keyListLoadedMsg{keys: keys}
|
||||||
|
}
|
||||||
|
|
||||||
|
case keyListLoadedMsg:
|
||||||
|
if msg.err != nil {
|
||||||
|
m.Error = msg.err
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
if kt := FindKeyListTab(m.tabs.tabs); kt != nil {
|
||||||
|
kt.SetKeys(msg.keys)
|
||||||
|
}
|
||||||
|
|
||||||
|
case saveSnippetResultMsg:
|
||||||
|
if msg.err != nil {
|
||||||
|
m.Error = msg.err
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
// Close form tab and switch back to list
|
||||||
|
if m.tabs.Len() > 1 {
|
||||||
|
m.tabs.CloseActive()
|
||||||
|
}
|
||||||
|
// Reload snippets
|
||||||
|
return m, func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(m.dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
snippets, err := store.ListSnippets(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return snippetListLoadedMsg{snippets: snippets}
|
||||||
|
}
|
||||||
|
|
||||||
|
case deleteSnippetResultMsg:
|
||||||
|
if msg.err != nil {
|
||||||
|
m.Error = msg.err
|
||||||
|
}
|
||||||
|
// Reload snippets
|
||||||
|
return m, func() tea.Msg {
|
||||||
|
store, err := storage.NewJSONStorage(m.dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
snippets, err := store.ListSnippets(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return snippetListLoadedMsg{snippets: snippets}
|
||||||
|
}
|
||||||
|
|
||||||
|
case snippetListLoadedMsg:
|
||||||
|
if msg.err != nil {
|
||||||
|
m.Error = msg.err
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
if st := FindSnippetListTab(m.tabs.tabs); st != nil {
|
||||||
|
st.SetSnippets(msg.snippets)
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return m, nil
|
cmd, err := m.tabs.Update(msg)
|
||||||
|
if err != nil {
|
||||||
|
m.Error = err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sync deprecated fields
|
||||||
|
if ht := FindHostListTab(m.tabs.tabs); ht != nil {
|
||||||
|
m.Hosts = ht.Hosts()
|
||||||
|
m.SelectedIndex = ht.SelectedIndex()
|
||||||
|
}
|
||||||
|
|
||||||
|
return m, cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
// View renders the TUI
|
// View renders the TUI
|
||||||
func (m *Model) View() string {
|
func (m *Model) View() string {
|
||||||
if m.Quit {
|
if m.Quit {
|
||||||
|
m.tabs = nil
|
||||||
return "Thanks for using hostkeeper!\n"
|
return "Thanks for using hostkeeper!\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
switch m.CurrentScreen {
|
if m.tabs == nil || m.tabs.Len() == 0 {
|
||||||
case ScreenHostList:
|
return "No tabs open. Press 'q' to quit.\n"
|
||||||
return renderHostList(m)
|
|
||||||
default:
|
|
||||||
return "Screen not implemented yet"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pass error to host list tab for display
|
||||||
|
if m.Error != nil {
|
||||||
|
if ht := FindHostListTab(m.tabs.tabs); ht != nil {
|
||||||
|
ht.err = m.Error
|
||||||
|
}
|
||||||
|
m.Error = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return m.tabs.View()
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoadHosts loads hosts into the TUI model
|
// LoadHosts loads hosts into the TUI model
|
||||||
func (m *Model) LoadHosts(hosts []*models.Host) {
|
func (m *Model) LoadHosts(hosts []*models.Host) {
|
||||||
m.Hosts = hosts
|
if m.tabs == nil {
|
||||||
if len(hosts) > 0 && m.SelectedIndex >= len(hosts) {
|
return
|
||||||
m.SelectedIndex = len(hosts) - 1
|
}
|
||||||
|
|
||||||
|
if ht := FindHostListTab(m.tabs.tabs); ht != nil {
|
||||||
|
ht.SetHosts(hosts)
|
||||||
|
m.Hosts = hosts
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetDataDir sets the data directory for SSH connections
|
||||||
|
func (m *Model) SetDataDir(dir string) {
|
||||||
|
m.dataDir = dir
|
||||||
|
}
|
||||||
|
|
||||||
|
// TabManager returns the underlying tab manager
|
||||||
|
func (m *Model) TabManager() *TabManager {
|
||||||
|
return m.tabs
|
||||||
|
}
|
||||||
|
|||||||
+89
-2
@@ -10,13 +10,23 @@ func TestTUIInitialization(t *testing.T) {
|
|||||||
t.Fatal("Failed to initialize TUI")
|
t.Fatal("Failed to initialize TUI")
|
||||||
}
|
}
|
||||||
|
|
||||||
if ui.CurrentScreen != ScreenHostList {
|
if ui.tabs == nil {
|
||||||
t.Errorf("expected CurrentScreen ScreenHostList, got %d", ui.CurrentScreen)
|
t.Fatal("expected tabs manager to be initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
if ui.tabs.Len() != 1 {
|
||||||
|
t.Errorf("expected 1 tab, got %d", ui.tabs.Len())
|
||||||
}
|
}
|
||||||
|
|
||||||
if ui.Quit {
|
if ui.Quit {
|
||||||
t.Error("expected Quit to be false")
|
t.Error("expected Quit to be false")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Should have a HostListTab by default
|
||||||
|
ht := FindHostListTab(ui.tabs.tabs)
|
||||||
|
if ht == nil {
|
||||||
|
t.Error("expected HostListTab to be the initial tab")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTUILoadHosts(t *testing.T) {
|
func TestTUILoadHosts(t *testing.T) {
|
||||||
@@ -29,4 +39,81 @@ func TestTUILoadHosts(t *testing.T) {
|
|||||||
if ui.Hosts != nil {
|
if ui.Hosts != nil {
|
||||||
t.Error("expected Hosts to be nil")
|
t.Error("expected Hosts to be nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Should still have a valid tab manager
|
||||||
|
if ui.tabs == nil {
|
||||||
|
t.Fatal("expected tabs manager to be valid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTabManagerBasic(t *testing.T) {
|
||||||
|
tm := NewTabManager(NewHostListTab())
|
||||||
|
if tm.Len() != 1 {
|
||||||
|
t.Errorf("expected 1 tab, got %d", tm.Len())
|
||||||
|
}
|
||||||
|
|
||||||
|
if tm.Active() == nil {
|
||||||
|
t.Fatal("expected active tab")
|
||||||
|
}
|
||||||
|
|
||||||
|
if tm.Active().Name() != "Hosts" {
|
||||||
|
t.Errorf("expected 'Hosts', got '%s'", tm.Active().Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTabManagerNavigation(t *testing.T) {
|
||||||
|
tm := NewTabManager(NewHostListTab())
|
||||||
|
|
||||||
|
// Add a second tab
|
||||||
|
second := NewHostListTab()
|
||||||
|
tm.Add(second)
|
||||||
|
if tm.Len() != 2 {
|
||||||
|
t.Errorf("expected 2 tabs, got %d", tm.Len())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Active should now be the last added tab
|
||||||
|
if tm.active != 1 {
|
||||||
|
t.Errorf("expected active index 1, got %d", tm.active)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Previous
|
||||||
|
tm.Prev()
|
||||||
|
if tm.active != 0 {
|
||||||
|
t.Errorf("expected active index 0 after Prev, got %d", tm.active)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Next
|
||||||
|
tm.Next()
|
||||||
|
if tm.active != 1 {
|
||||||
|
t.Errorf("expected active index 1 after Next, got %d", tm.active)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTabManagerClose(t *testing.T) {
|
||||||
|
tm := NewTabManager(NewHostListTab())
|
||||||
|
second := NewHostListTab()
|
||||||
|
tm.Add(second)
|
||||||
|
tm.Add(NewHostListTab())
|
||||||
|
|
||||||
|
// Close active (last tab)
|
||||||
|
closed := tm.CloseActive()
|
||||||
|
if closed == nil {
|
||||||
|
t.Error("expected closed tab to be returned")
|
||||||
|
}
|
||||||
|
|
||||||
|
if tm.Len() != 2 {
|
||||||
|
t.Errorf("expected 2 tabs after close, got %d", tm.Len())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close all tabs except last
|
||||||
|
tm.Close(0)
|
||||||
|
if tm.Len() != 1 {
|
||||||
|
t.Errorf("expected 1 tab after close, got %d", tm.Len())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Should not close the last tab via CloseActive (returns nil)
|
||||||
|
result := tm.CloseActive()
|
||||||
|
if result != nil {
|
||||||
|
t.Error("expected nil when trying to close the last tab")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# GEMINI_API_KEY: Required for Gemini AI API calls.
|
||||||
|
# AI Studio automatically injects this at runtime from user secrets.
|
||||||
|
# Users configure this via the Secrets panel in the AI Studio UI.
|
||||||
|
GEMINI_API_KEY="MY_GEMINI_API_KEY"
|
||||||
|
|
||||||
|
# APP_URL: The URL where this applet is hosted.
|
||||||
|
# AI Studio automatically injects this at runtime with the Cloud Run service URL.
|
||||||
|
# Used for self-referential links, OAuth callbacks, and API endpoints.
|
||||||
|
APP_URL="MY_APP_URL"
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
node_modules/
|
||||||
|
build/
|
||||||
|
dist/
|
||||||
|
coverage/
|
||||||
|
.DS_Store
|
||||||
|
*.log
|
||||||
|
.env*
|
||||||
|
!.env.example
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# HostKeeper | Developer & AI System Brief
|
||||||
|
|
||||||
|
> **MANDATORY INSTRUCTION FOR DOWNSTREAM AI AGENTS:**
|
||||||
|
> Before proposing or implementing any changes, code edits, or new features in this workspace, you **MUST** read this instruction set fully. Every visual and architectural decision must align strictly with the rules defined below.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Visual Identity & Design System (Lumina System)
|
||||||
|
|
||||||
|
Unlike standard, heavy, dark-themed hacker dashboards, HostKeeper uses the **Lumina System**—a premium, "bright-tech" glassmorphic developer workspace featuring clean off-whites, slate cards, vibrant accent highlights, and a high-clarity layout.
|
||||||
|
|
||||||
|
### A. Color Palette
|
||||||
|
Maintain the exact CSS variables and color definitions declared in `/src/index.css`:
|
||||||
|
* **Primary (Lumina Blue):** `#0050cb` (Focus boundaries, active selections, primary indicators)
|
||||||
|
* **Secondary (Neon Green):** `#006e2f` (Active/Online indicators, progress bars, successful transactions)
|
||||||
|
* **Tertiary (Tech Purple):** `#7e23cc` (File directories, custom command responses, highlight badges)
|
||||||
|
* **Surface Base Background:** `#f7f9fb`
|
||||||
|
* **Containers & Cards Lowest:** `#ffffff` (High-contrast pure white cards for depth separation)
|
||||||
|
* **Text/On-Surface Dark Slate:** `#191c1e` (Main UI text)
|
||||||
|
* **Subtle Labels/On-Surface Variant:** `#424656`
|
||||||
|
|
||||||
|
### B. Grid, Depth & Glassmorphic Accents
|
||||||
|
* **Dot Grid Texture:** The background uses a responsive 16px repeating radial dot pattern:
|
||||||
|
`radial-gradient(#e2e8f0 1.5px, transparent 1.5px)` with a size of `16px 16px`.
|
||||||
|
* **Frosted Glass Sidebars & Overlays:** Use `backdrop-blur-md` and semi-transparent white backgrounds (`rgba(255, 255, 255, 0.7)`) to show subtle grid depth underneath overlays.
|
||||||
|
* **Elevation & Shadows:** Focus containers should never have heavy dark borders. Instead, apply thin borders (`border-outline-variant/30`) paired with subtle, color-matched glow shadows (`shadow-primary/10`).
|
||||||
|
|
||||||
|
### C. Typography Pairing
|
||||||
|
* **Interface UI Font:** **Inter** (weights `300` to `900`). Used for titles, descriptive labels, tables, navigation buttons, and settings forms.
|
||||||
|
* **Technical / Data Font:** **JetBrains Mono** (weights `300` to `700`). Used exclusively for file paths, IP addresses, terminal prompt commands, and cataloged snippet blocks.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. File & Component Architecture
|
||||||
|
|
||||||
|
Keep the project highly modular. Do not merge separate view components into a single file to avoid hitting token limit cutoffs.
|
||||||
|
|
||||||
|
* `/src/types.ts`: Holds shared global interfaces (e.g., `Host`, `FileItem`, `Snippet`, `KeychainItem`, `Device`, `BackgroundTransfer`).
|
||||||
|
* `/src/App.tsx`: The primary state router. Houses active navigation, sidebar frames, quick-action overlays, and global mock state stores.
|
||||||
|
* `/src/components/DashboardView.tsx`: Hosts list, connection triggers, and background file-transfer progress bars.
|
||||||
|
* `/src/components/SftpView.tsx`: Dual-pane local-to-remote secure file transmission and folder generation lists.
|
||||||
|
* `/src/components/TerminalView.tsx`: Interactive multi-tab mock SSH shell supporting customized terminal parser actions.
|
||||||
|
* `/src/components/SnippetsView.tsx`: DevOps script store with full search index, copy utility, and custom snippet registration.
|
||||||
|
* `/src/components/KeychainView.tsx`: Secure local keystore sandbox with passphrase disclosure controls, strength validators, and SHA256 fingerprints.
|
||||||
|
* `/src/components/SettingsView.tsx`: Profile configuration forms, feature toggle switches, and local storage state resets.
|
||||||
|
* `/src/components/BriefOverlay.tsx`: In-app system documentation and layout specifications viewer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Core Functional & Interaction Guidelines
|
||||||
|
|
||||||
|
When expanding HostKeeper features, future agents must adhere to the following implementation behaviors:
|
||||||
|
|
||||||
|
1. **Icon Guidelines:**
|
||||||
|
* All icons **MUST** be imported strictly from `lucide-react`.
|
||||||
|
* Do **NOT** write custom inline SVGs.
|
||||||
|
2. **Terminal Simulation Parser:**
|
||||||
|
* Inside `TerminalView.tsx`, the interactive shell handles input commands.
|
||||||
|
* Always extend the mock commands list (`help`, `ls`, `docker ps`, `uname -a`, `ping 8.8.8.8`, `cat server.js`, `keychain`, `clear`) rather than falling back to blank prompts.
|
||||||
|
3. **Real-time SFTP Actions:**
|
||||||
|
* SFTP View simulates file transmission. Clicking a file or the upload/download button triggers path transfers with real-time UI feedback. Keep the interactive toast banners operational.
|
||||||
|
4. **No Unsolicited SDKs or Servers:**
|
||||||
|
* Keep the app fully client-side and snappy unless requested otherwise.
|
||||||
|
* Avoid creating unnecessary external backends or adding database service modules unless explicitly specified.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Development Verification Steps
|
||||||
|
|
||||||
|
Before finishing any task, run these commands sequentially to guarantee app integrity:
|
||||||
|
|
||||||
|
1. **Check Linter Rules:**
|
||||||
|
`npm run lint` or call the `lint_applet` tool to identify imports or compilation issues early.
|
||||||
|
2. **Verify Production Build Compilation:**
|
||||||
|
`npm run build` or call the `compile_applet` tool to ensure TypeScript checks and asset optimization pass without errors.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<div align="center">
|
||||||
|
<img width="1200" height="475" alt="GHBanner" src="https://ai.google.dev/static/site-assets/images/share-ais-513315318.png" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
# Run and deploy your AI Studio app
|
||||||
|
|
||||||
|
This contains everything you need to run your app locally.
|
||||||
|
|
||||||
|
View your app in AI Studio: https://ai.studio/apps/fdc890ff-7c2d-48ba-a909-0c5c4e05cd73
|
||||||
|
|
||||||
|
## Run Locally
|
||||||
|
|
||||||
|
**Prerequisites:** Node.js
|
||||||
|
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
`npm install`
|
||||||
|
2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
|
||||||
|
3. Run the app:
|
||||||
|
`npm run dev`
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en" class="light">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>HostKeeper | Bright-Tech SSH, SFTP, and Keychain Manager</title>
|
||||||
|
<!-- Fonts -->
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&display=swap" rel="stylesheet" />
|
||||||
|
<!-- Google Material Symbols Outlined -->
|
||||||
|
<link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:wght,FILL@100..700,0..1@100..700,0..1&display=swap" rel="stylesheet" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"name": "HostKeeper",
|
||||||
|
"description": "A beautiful, premium, bright-tech terminal, SFTP, and Keychain manager with glassmorphic visuals and comprehensive developer workflows.",
|
||||||
|
"requestFramePermissions": [],
|
||||||
|
"majorCapabilities": ["MAJOR_CAPABILITY_SERVER_SIDE_GEMINI_API"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"name": "react-example",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite --port=3000 --host=0.0.0.0",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview",
|
||||||
|
"clean": "rm -rf dist server.js",
|
||||||
|
"lint": "tsc --noEmit"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@google/genai": "^2.4.0",
|
||||||
|
"@tailwindcss/vite": "^4.1.14",
|
||||||
|
"@vitejs/plugin-react": "^5.0.4",
|
||||||
|
"lucide-react": "^0.546.0",
|
||||||
|
"react": "^19.0.1",
|
||||||
|
"react-dom": "^19.0.1",
|
||||||
|
"vite": "^6.2.3",
|
||||||
|
"express": "^4.21.2",
|
||||||
|
"dotenv": "^17.2.3",
|
||||||
|
"motion": "^12.23.24"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^22.14.0",
|
||||||
|
"autoprefixer": "^10.4.21",
|
||||||
|
"esbuild": "^0.25.0",
|
||||||
|
"tailwindcss": "^4.1.14",
|
||||||
|
"tsx": "^4.21.0",
|
||||||
|
"typescript": "~5.8.2",
|
||||||
|
"vite": "^6.2.3",
|
||||||
|
"@types/express": "^4.17.21"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { ViewType, Host } from './types';
|
||||||
|
import DashboardView from './components/DashboardView';
|
||||||
|
import SftpView from './components/SftpView';
|
||||||
|
import TerminalView from './components/TerminalView';
|
||||||
|
import SnippetsView from './components/SnippetsView';
|
||||||
|
import KeychainView from './components/KeychainView';
|
||||||
|
import SettingsView from './components/SettingsView';
|
||||||
|
import BriefOverlay from './components/BriefOverlay';
|
||||||
|
|
||||||
|
// Lucide icons
|
||||||
|
import {
|
||||||
|
Terminal,
|
||||||
|
FolderSync,
|
||||||
|
TerminalSquare,
|
||||||
|
Code2,
|
||||||
|
KeyRound,
|
||||||
|
Settings2,
|
||||||
|
FileQuestion,
|
||||||
|
Cpu,
|
||||||
|
ChevronRight,
|
||||||
|
Layers,
|
||||||
|
ArrowRightLeft,
|
||||||
|
Crown
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
const [currentView, setCurrentView] = useState<ViewType>('hosts');
|
||||||
|
const [isBriefOpen, setIsBriefOpen] = useState(false);
|
||||||
|
|
||||||
|
// Connection target host (instantiated via dashboard "Connect" clicks)
|
||||||
|
const [connectedHost, setConnectedHost] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Hosts collection
|
||||||
|
const [hosts, setHosts] = useState<Host[]>([
|
||||||
|
{
|
||||||
|
id: '1',
|
||||||
|
name: 'production-api-01',
|
||||||
|
ip: '10.0.1.201',
|
||||||
|
os: 'Ubuntu 22.04',
|
||||||
|
provider: 'AWS US-East',
|
||||||
|
status: 'active',
|
||||||
|
lastSeen: '2 hours ago',
|
||||||
|
type: 'api'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '2',
|
||||||
|
name: 'db-cluster-main',
|
||||||
|
ip: '10.0.2.14',
|
||||||
|
os: 'Debian 11',
|
||||||
|
provider: 'GCP Cloud',
|
||||||
|
status: 'active',
|
||||||
|
lastSeen: '5 hours ago',
|
||||||
|
type: 'db'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '3',
|
||||||
|
name: 'edge-node-berlin',
|
||||||
|
ip: '45.132.89.12',
|
||||||
|
os: 'Alpine Linux',
|
||||||
|
provider: 'Hetzner',
|
||||||
|
status: 'active',
|
||||||
|
lastSeen: '1 day ago',
|
||||||
|
type: 'edge'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '4',
|
||||||
|
name: 'web-frontend-02',
|
||||||
|
ip: '75.101.44.8',
|
||||||
|
os: 'Ubuntu 22.04',
|
||||||
|
provider: 'AWS US-East',
|
||||||
|
status: 'offline',
|
||||||
|
lastSeen: '3 days ago',
|
||||||
|
type: 'web'
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
|
||||||
|
const handleConnectHost = (hostName: string) => {
|
||||||
|
setConnectedHost(hostName);
|
||||||
|
setCurrentView('terminal');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddHost = (newHost: Host) => {
|
||||||
|
setHosts(prev => [newHost, ...prev]);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Nav items helper
|
||||||
|
const navItems = [
|
||||||
|
{ id: 'hosts', label: 'Hosts Manager', icon: Cpu, desc: 'Active clusters & networks' },
|
||||||
|
{ id: 'sftp', label: 'SFTP File Sync', icon: FolderSync, desc: 'Secure asset pipeline' },
|
||||||
|
{ id: 'terminal', label: 'SSH Shell client', icon: TerminalSquare, desc: 'Interactive remote command shell' },
|
||||||
|
{ id: 'snippets', label: 'Snippets Library', icon: Code2, desc: 'Reusable DevOps commands' },
|
||||||
|
{ id: 'keychain', label: 'Keys & Keychain', icon: KeyRound, desc: 'SSH identity credentials' },
|
||||||
|
{ id: 'settings', label: 'Preferences', icon: Settings2, desc: 'Workspace settings & account' }
|
||||||
|
];
|
||||||
|
|
||||||
|
// Render view router helper
|
||||||
|
const renderView = () => {
|
||||||
|
switch (currentView) {
|
||||||
|
case 'hosts':
|
||||||
|
return (
|
||||||
|
<DashboardView
|
||||||
|
onConnectHost={handleConnectHost}
|
||||||
|
hosts={hosts}
|
||||||
|
onAddHost={handleAddHost}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
case 'sftp':
|
||||||
|
return <SftpView />;
|
||||||
|
case 'terminal':
|
||||||
|
return <TerminalView />;
|
||||||
|
case 'snippets':
|
||||||
|
return <SnippetsView />;
|
||||||
|
case 'keychain':
|
||||||
|
return <KeychainView />;
|
||||||
|
case 'settings':
|
||||||
|
return <SettingsView />;
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
<DashboardView
|
||||||
|
onConnectHost={handleConnectHost}
|
||||||
|
hosts={hosts}
|
||||||
|
onAddHost={handleAddHost}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-surface dot-grid flex overflow-hidden">
|
||||||
|
|
||||||
|
{/* Sidebar Frame */}
|
||||||
|
<aside className="w-[260px] border-r border-outline-variant bg-white/75 backdrop-blur-md hidden md:flex flex-col justify-between shrink-0 z-10">
|
||||||
|
|
||||||
|
{/* Top Header Logo */}
|
||||||
|
<div className="p-6 border-b border-outline-variant/30 flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-9 h-9 rounded-xl bg-primary flex items-center justify-center text-white shadow-lg shadow-primary/20">
|
||||||
|
<Terminal className="w-5 h-5 animate-pulse" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h1 className="font-extrabold text-on-surface text-sm tracking-tight leading-none uppercase">HostKeeper</h1>
|
||||||
|
<span className="text-[10px] text-outline font-bold tracking-widest mt-1 block leading-none">LUMINA TECH</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setIsBriefOpen(true)}
|
||||||
|
className="p-1 hover:bg-primary-container/15 hover:text-primary rounded text-outline transition-colors cursor-pointer"
|
||||||
|
title="Review System Brief"
|
||||||
|
>
|
||||||
|
<FileQuestion className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Navigation list */}
|
||||||
|
<nav className="flex-1 px-4 py-6 space-y-1 overflow-y-auto no-scrollbar">
|
||||||
|
{navItems.map((item) => {
|
||||||
|
const Icon = item.icon;
|
||||||
|
const isActive = currentView === item.id;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={item.id}
|
||||||
|
onClick={() => setCurrentView(item.id as ViewType)}
|
||||||
|
className={`w-full flex items-center gap-3.5 px-4 py-3 rounded-xl transition-all text-left border cursor-pointer ${isActive ? 'bg-primary text-white border-primary shadow-lg shadow-primary/10' : 'bg-transparent text-on-surface-variant hover:bg-surface-container-low border-transparent'}`}
|
||||||
|
>
|
||||||
|
<Icon className={`w-5 h-5 ${isActive ? 'text-white' : 'text-outline-variant group-hover:text-primary'}`} />
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-xs font-bold leading-tight">{item.label}</p>
|
||||||
|
<p className={`text-[9px] truncate mt-0.5 leading-none ${isActive ? 'text-primary-fixed' : 'text-outline'}`}>
|
||||||
|
{item.desc}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<ChevronRight className={`w-3.5 h-3.5 ${isActive ? 'opacity-100 text-white' : 'opacity-0'}`} />
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{/* User profile footer drawer badge */}
|
||||||
|
<div className="p-4 border-t border-outline-variant/40 bg-surface-container-low/30">
|
||||||
|
<div className="flex items-center justify-between p-2 rounded-xl bg-white border border-outline-variant/50">
|
||||||
|
<div className="flex items-center gap-2.5 min-w-0">
|
||||||
|
<div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center font-black text-primary text-xs relative shrink-0">
|
||||||
|
AR
|
||||||
|
<span className="absolute right-0 bottom-0 w-2 h-2 rounded-full bg-secondary border border-white animate-pulse"></span>
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="text-xs font-bold text-on-surface truncate">Alex Rivera</p>
|
||||||
|
<p className="text-[9px] text-outline font-semibold uppercase tracking-wider">DevOps Lead</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span className="p-1 text-primary cursor-help" title="Pro Account Status">
|
||||||
|
<Crown className="w-4 h-4 text-amber-500 fill-amber-500" />
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
{/* Main workspace arena content panel */}
|
||||||
|
<main className="flex-1 flex flex-col min-w-0 relative overflow-y-auto h-screen no-scrollbar">
|
||||||
|
|
||||||
|
{/* Top workspace action app bar */}
|
||||||
|
<header className="px-4 sm:px-6 py-4 bg-white/60 backdrop-blur-sm border-b border-outline-variant flex items-center justify-between z-10 gap-3">
|
||||||
|
<div className="flex items-center gap-2 sm:gap-4 min-w-0">
|
||||||
|
<h2 className="text-xs sm:text-sm font-bold text-on-surface tracking-tight uppercase truncate">
|
||||||
|
{navItems.find(i => i.id === currentView)?.label}
|
||||||
|
</h2>
|
||||||
|
{connectedHost && currentView === 'terminal' && (
|
||||||
|
<span className="px-2 py-0.5 bg-primary-container/20 border border-primary/20 text-primary rounded-lg text-[9px] sm:text-[10px] font-mono font-bold animate-pulse truncate max-w-[120px] sm:max-w-none" title={`CONNECTED TO: ${connectedHost}`}>
|
||||||
|
<span className="hidden sm:inline">CONNECTED TO: </span>{connectedHost}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-4 shrink-0">
|
||||||
|
{/* Quick Brief activator */}
|
||||||
|
<button
|
||||||
|
onClick={() => setIsBriefOpen(true)}
|
||||||
|
className="flex items-center gap-1.5 px-2.5 sm:px-3 py-1.5 bg-primary text-white hover:bg-primary-container hover:text-on-primary-container text-xs font-bold rounded-xl shadow-md transition-all cursor-pointer"
|
||||||
|
>
|
||||||
|
<FileQuestion className="w-4 h-4 animate-bounce" />
|
||||||
|
<span className="hidden sm:inline">AI System Brief</span>
|
||||||
|
<span className="sm:hidden">Brief</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{/* View render hub */}
|
||||||
|
<div className="flex-1 bg-surface-container-low/10 overflow-y-auto pb-24 md:pb-12">
|
||||||
|
{renderView()}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</main>
|
||||||
|
|
||||||
|
{/* Mobile Responsive Navigation Footer Bar */}
|
||||||
|
<nav className="md:hidden fixed bottom-0 left-0 right-0 bg-white/95 backdrop-blur-md border-t border-outline-variant/60 flex justify-around py-2 px-1 z-[100] shadow-lg">
|
||||||
|
{navItems.map((item) => {
|
||||||
|
const Icon = item.icon;
|
||||||
|
const isActive = currentView === item.id;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={item.id}
|
||||||
|
onClick={() => setCurrentView(item.id as ViewType)}
|
||||||
|
className={`flex flex-col items-center gap-1 px-2.5 py-1 rounded-xl transition-all cursor-pointer ${isActive ? 'text-primary' : 'text-outline hover:text-on-surface-variant'}`}
|
||||||
|
>
|
||||||
|
<Icon className="w-5 h-5" />
|
||||||
|
<span className="text-[9px] font-bold leading-none">{item.label.split(' ')[0]}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{/* Floating System Brief Drawer Overlay */}
|
||||||
|
<BriefOverlay isOpen={isBriefOpen} onClose={() => setIsBriefOpen(false)} />
|
||||||
|
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { X, Terminal, Cpu, Palette, Layout, Layers, Box, Code } from 'lucide-react';
|
||||||
|
|
||||||
|
interface BriefOverlayProps {
|
||||||
|
isOpen: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function BriefOverlay({ isOpen, onClose }: BriefOverlayProps) {
|
||||||
|
if (!isOpen) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[200] flex justify-end transition-opacity duration-300">
|
||||||
|
<div className="w-full max-w-2xl bg-white h-screen shadow-2xl flex flex-col overflow-hidden animate-slide-in">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="px-6 py-5 bg-primary text-white flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Terminal className="w-6 h-6 animate-pulse" />
|
||||||
|
<div>
|
||||||
|
<h2 className="text-xl font-bold tracking-tight">AI & Developer Brief</h2>
|
||||||
|
<p className="text-xs text-primary-fixed opacity-90">Design System & Blueprint for HostKeeper</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={onClose}
|
||||||
|
className="p-1.5 hover:bg-white/10 rounded-lg transition-colors cursor-pointer text-white"
|
||||||
|
title="Close brief"
|
||||||
|
>
|
||||||
|
<X className="w-6 h-6" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
<div className="flex-1 overflow-y-auto p-6 space-y-8 custom-scrollbar">
|
||||||
|
{/* Intro Guidance */}
|
||||||
|
<div className="bg-primary-container/10 border border-primary/20 rounded-xl p-4 text-sm text-on-surface">
|
||||||
|
<span className="font-bold text-primary block mb-1">🤖 AI-to-AI / Developer System Instructions</span>
|
||||||
|
This documentation is built directly into the codebase to guide downstream development agents.
|
||||||
|
Maintain the <strong className="text-primary">Bright-Tech / Lumina Terminal</strong> aesthetic. Avoid dark-mode-by-default stereotypes unless requested; focus on high-clarity slate cards, interactive neon accents, and crisp typography.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Section: Palette */}
|
||||||
|
<section className="space-y-3">
|
||||||
|
<h3 className="font-bold text-on-background flex items-center gap-2 text-base">
|
||||||
|
<Palette className="w-5 h-5 text-primary" />
|
||||||
|
Colors (Lumina System)
|
||||||
|
</h3>
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
|
||||||
|
<div className="p-3 border border-outline-variant rounded-lg bg-surface-container-low text-xs">
|
||||||
|
<div className="w-full h-8 rounded bg-[#0050cb] mb-1.5"></div>
|
||||||
|
<p className="font-bold">Primary (Blue)</p>
|
||||||
|
<code className="text-[10px] text-outline">#0050cb</code>
|
||||||
|
</div>
|
||||||
|
<div className="p-3 border border-outline-variant rounded-lg bg-surface-container-low text-xs">
|
||||||
|
<div className="w-full h-8 rounded bg-[#006e2f] mb-1.5"></div>
|
||||||
|
<p className="font-bold">Secondary (Green)</p>
|
||||||
|
<code className="text-[10px] text-outline">#006e2f</code>
|
||||||
|
</div>
|
||||||
|
<div className="p-3 border border-outline-variant rounded-lg bg-surface-container-low text-xs">
|
||||||
|
<div className="w-full h-8 rounded bg-[#7e23cc] mb-1.5"></div>
|
||||||
|
<p className="font-bold">Tertiary (Purple)</p>
|
||||||
|
<code className="text-[10px] text-outline">#7e23cc</code>
|
||||||
|
</div>
|
||||||
|
<div className="p-3 border border-outline-variant rounded-lg bg-surface-container-low text-xs">
|
||||||
|
<div className="w-full h-8 rounded bg-[#f7f9fb] mb-1.5 border border-outline-variant/50"></div>
|
||||||
|
<p className="font-bold">Surface Base</p>
|
||||||
|
<code className="text-[10px] text-outline">#f7f9fb</code>
|
||||||
|
</div>
|
||||||
|
<div className="p-3 border border-outline-variant rounded-lg bg-surface-container-low text-xs">
|
||||||
|
<div className="w-full h-8 rounded bg-white mb-1.5 border border-outline-variant/50"></div>
|
||||||
|
<p className="font-bold">Container Lowest</p>
|
||||||
|
<code className="text-[10px] text-outline">#ffffff</code>
|
||||||
|
</div>
|
||||||
|
<div className="p-3 border border-outline-variant rounded-lg bg-surface-container-low text-xs">
|
||||||
|
<div className="w-full h-8 rounded bg-[#191c1e] mb-1.5"></div>
|
||||||
|
<p className="font-bold">On Surface</p>
|
||||||
|
<code className="text-[10px] text-outline">#191c1e</code>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Section: Typography */}
|
||||||
|
<section className="space-y-3">
|
||||||
|
<h3 className="font-bold text-on-background flex items-center gap-2 text-base">
|
||||||
|
<Code className="w-5 h-5 text-primary" />
|
||||||
|
Typography Specifications
|
||||||
|
</h3>
|
||||||
|
<div className="border border-outline-variant rounded-xl divide-y divide-outline-variant/50 overflow-hidden text-sm">
|
||||||
|
<div className="p-4 bg-surface-container-lowest">
|
||||||
|
<p className="font-bold text-xs text-outline mb-1 uppercase tracking-wider">UI Font Pairing (Inter)</p>
|
||||||
|
<p className="font-sans text-lg font-bold">Inter Sans-Serif</p>
|
||||||
|
<p className="text-xs text-on-surface-variant">Used for all lists, forms, dashboard metrics, setting menus, and high-contrast labels.</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 bg-surface-container-lowest font-mono">
|
||||||
|
<p className="font-bold text-xs text-outline mb-1 uppercase tracking-wider font-sans">Technical Font (JetBrains Mono)</p>
|
||||||
|
<p className="text-base font-medium">JetBrains Mono</p>
|
||||||
|
<p className="text-xs text-on-surface-variant font-sans mt-1">Used for terminal outputs, commands, snippets, directory paths, and code metadata.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Section: Layout & Spacing */}
|
||||||
|
<section className="space-y-3">
|
||||||
|
<h3 className="font-bold text-on-background flex items-center gap-2 text-base">
|
||||||
|
<Layout className="w-5 h-5 text-primary" />
|
||||||
|
Layout & Spacing Architecture
|
||||||
|
</h3>
|
||||||
|
<ul className="list-disc pl-5 space-y-2 text-sm text-on-surface-variant">
|
||||||
|
<li>
|
||||||
|
<strong className="text-on-background">The Dot Grid Texture:</strong> A 16px background repeating dot grid system (<code className="text-xs bg-surface-container px-1 rounded">radial-gradient(#E2E8F0 1.5px, transparent 1.5px)</code>) anchors the content, providing depth and mimicking physical engineering logs.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong className="text-on-background">Asymmetric Bento Sizing:</strong> Balance large focus modules (such as the active Terminal Session or SFTP local-remote streams) alongside secondary narrow utility sheets.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<strong className="text-on-background">Standardized Metrics:</strong> Sidebar width is exactly <code className="text-xs bg-surface-container px-1 rounded">260px</code>. Terminal containers use <code className="text-xs bg-surface-container px-1 rounded">20px</code> internal padding.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Section: Elevation & Glassmorphism */}
|
||||||
|
<section className="space-y-3">
|
||||||
|
<h3 className="font-bold text-on-background flex items-center gap-2 text-base">
|
||||||
|
<Layers className="w-5 h-5 text-primary" />
|
||||||
|
Depth & Glassmorphism Rules
|
||||||
|
</h3>
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-xs">
|
||||||
|
<div className="p-4 border border-outline-variant/60 rounded-xl space-y-1">
|
||||||
|
<span className="font-bold text-primary text-xs uppercase tracking-wider block">Level 1: Translucency</span>
|
||||||
|
<p className="text-on-surface-variant">Sidebars, Top App Bars, and overlay cards use <code className="text-[11px] bg-surface-container px-1 rounded">backdrop-blur-md</code> and semi-transparent backgrounds to overlay smoothly on background grid lines.</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 border border-outline-variant/60 rounded-xl space-y-1">
|
||||||
|
<span className="font-bold text-primary text-xs uppercase tracking-wider block">Level 2: Glowing States</span>
|
||||||
|
<p className="text-on-surface-variant">Active focus objects should never look heavy. Apply accent borders (<code className="text-[11px] bg-surface-container px-1 rounded">border-primary</code>) and soft drop shadow glows of the accent color.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Section: Future Enhancements Blueprint */}
|
||||||
|
<section className="space-y-3">
|
||||||
|
<h3 className="font-bold text-on-background flex items-center gap-2 text-base">
|
||||||
|
<Box className="w-5 h-5 text-primary" />
|
||||||
|
AI Implementation Guidelines
|
||||||
|
</h3>
|
||||||
|
<div className="p-4 bg-surface-container-low rounded-xl text-xs space-y-2">
|
||||||
|
<p>When modifying this code or adding database handlers:</p>
|
||||||
|
<ol className="list-decimal pl-4 space-y-1.5 text-on-surface-variant">
|
||||||
|
<li>Always maintain class structures using state routers instead of traditional pages for fluid interactions.</li>
|
||||||
|
<li>Import standard icons only from <code className="text-xs font-mono text-primary font-bold">lucide-react</code>. Do not write custom inline SVG structures.</li>
|
||||||
|
<li>Ensure interactive switches use the custom <code className="text-xs font-mono">checked</code> properties with transition toggles.</li>
|
||||||
|
<li>For terminal commands, enhance the custom parser inside <code className="text-xs font-mono">TerminalView.tsx</code> to handle rich multi-line logs.</li>
|
||||||
|
</ol>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Footer */}
|
||||||
|
<div className="p-4 border-t border-outline-variant bg-surface-container-low flex justify-between items-center text-xs text-outline font-medium">
|
||||||
|
<span>Lumina Technical Blueprint v1.0</span>
|
||||||
|
<span>Google AI Studio Build</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,467 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Host, BackgroundTransfer } from '../types';
|
||||||
|
import {
|
||||||
|
Server,
|
||||||
|
Database,
|
||||||
|
Cpu,
|
||||||
|
ArrowRight,
|
||||||
|
Search,
|
||||||
|
Plus,
|
||||||
|
LayoutGrid,
|
||||||
|
List,
|
||||||
|
AlertTriangle,
|
||||||
|
TrendingUp,
|
||||||
|
CheckCircle,
|
||||||
|
FileCheck,
|
||||||
|
Zap,
|
||||||
|
Globe,
|
||||||
|
Monitor,
|
||||||
|
Laptop
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
interface DashboardViewProps {
|
||||||
|
onConnectHost: (hostName: string) => void;
|
||||||
|
hosts: Host[];
|
||||||
|
onAddHost: (host: Host) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function DashboardView({ onConnectHost, hosts, onAddHost }: DashboardViewProps) {
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
|
||||||
|
const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'offline'>('all');
|
||||||
|
|
||||||
|
// Quick manual host addition modal/state
|
||||||
|
const [showAddModal, setShowAddModal] = useState(false);
|
||||||
|
const [newHostName, setNewHostName] = useState('');
|
||||||
|
const [newHostIp, setNewHostIp] = useState('');
|
||||||
|
const [newHostOs, setNewHostOs] = useState<'Ubuntu 22.04' | 'Debian 11' | 'Windows Server' | 'macOS Ventura' | 'CentOS 7' | 'Alpine Linux'>('Ubuntu 22.04');
|
||||||
|
const [newHostProvider, setNewHostProvider] = useState<'AWS US-East' | 'GCP Cloud' | 'Hetzner' | 'Vercel Proxy' | 'Local Docker' | 'Bare Metal'>('AWS US-East');
|
||||||
|
const [newHostType, setNewHostType] = useState<'api' | 'db' | 'edge' | 'web' | 'server'>('api');
|
||||||
|
|
||||||
|
// Background transfer list
|
||||||
|
const [transfers, setTransfers] = useState<BackgroundTransfer[]>([
|
||||||
|
{
|
||||||
|
id: '1',
|
||||||
|
fileName: 'backup_v4.tar.gz',
|
||||||
|
source: 'production-api-01',
|
||||||
|
destination: 'Local Machine',
|
||||||
|
progress: 82,
|
||||||
|
speed: '12.4 MB/s',
|
||||||
|
type: 'download'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '2',
|
||||||
|
fileName: 'assets_deploy.zip',
|
||||||
|
source: 'Local Storage',
|
||||||
|
destination: 'web-frontend-02',
|
||||||
|
progress: 35,
|
||||||
|
speed: '4.8 MB/s',
|
||||||
|
type: 'upload'
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
|
||||||
|
const handleCreateHost = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!newHostName || !newHostIp) return;
|
||||||
|
|
||||||
|
const newHost: Host = {
|
||||||
|
id: Date.now().toString(),
|
||||||
|
name: newHostName.toLowerCase().replace(/\s+/g, '-'),
|
||||||
|
ip: newHostIp,
|
||||||
|
os: newHostOs,
|
||||||
|
provider: newHostProvider,
|
||||||
|
status: 'active',
|
||||||
|
lastSeen: 'Just now',
|
||||||
|
type: newHostType
|
||||||
|
};
|
||||||
|
|
||||||
|
onAddHost(newHost);
|
||||||
|
setShowAddModal(false);
|
||||||
|
setNewHostName('');
|
||||||
|
setNewHostIp('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const filteredHosts = hosts.filter(host => {
|
||||||
|
const matchesSearch = host.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
host.ip.includes(searchQuery) ||
|
||||||
|
host.provider.toLowerCase().includes(searchQuery.toLowerCase());
|
||||||
|
const matchesStatus = statusFilter === 'all' || host.status === statusFilter;
|
||||||
|
return matchesSearch && matchesStatus;
|
||||||
|
});
|
||||||
|
|
||||||
|
const getOsIcon = (os: string) => {
|
||||||
|
switch (os) {
|
||||||
|
case 'macOS Ventura': return <Laptop className="w-5 h-5" />;
|
||||||
|
case 'Windows Server': return <Monitor className="w-5 h-5" />;
|
||||||
|
default: return <Database className="w-5 h-5" />;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 md:p-8 max-w-7xl mx-auto space-y-8 animate-fade-in">
|
||||||
|
{/* Top Banner Stats */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-12 gap-6">
|
||||||
|
{/* Left Stats Block */}
|
||||||
|
<div className="md:col-span-8 p-6 rounded-2xl bg-white border border-outline-variant shadow-sm flex items-center justify-between overflow-hidden relative group">
|
||||||
|
<div className="relative z-10 space-y-2">
|
||||||
|
<h3 className="text-on-surface-variant font-bold text-xs uppercase tracking-wider">Active Connections</h3>
|
||||||
|
<div className="flex items-end gap-3">
|
||||||
|
<span className="text-4xl font-black text-primary">12</span>
|
||||||
|
<span className="text-secondary font-bold text-sm mb-1 flex items-center bg-secondary-container/20 px-2 py-0.5 rounded-full">
|
||||||
|
<TrendingUp className="w-4 h-4 mr-1" />
|
||||||
|
+2 today
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-on-surface-variant">Global performance metrics sync integrity active.</p>
|
||||||
|
</div>
|
||||||
|
{/* Accent Grid Glow lines */}
|
||||||
|
<div className="absolute right-0 top-0 w-1/3 h-full bg-gradient-to-l from-primary/5 to-transparent pointer-events-none"></div>
|
||||||
|
|
||||||
|
<div className="flex gap-2 items-end h-16 shrink-0">
|
||||||
|
<div className="w-2.5 h-10 bg-primary/20 rounded-full animate-pulse"></div>
|
||||||
|
<div className="w-2.5 h-14 bg-primary/40 rounded-full animate-pulse delay-75"></div>
|
||||||
|
<div className="w-2.5 h-8 bg-primary/10 rounded-full animate-pulse delay-150"></div>
|
||||||
|
<div className="w-2.5 h-16 bg-primary/60 rounded-full animate-pulse delay-200"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Right Stats Block - Promotion Card */}
|
||||||
|
<div className="md:col-span-4 p-6 rounded-2xl bg-primary text-on-primary shadow-xl shadow-primary/15 flex flex-col justify-between relative overflow-hidden">
|
||||||
|
<div className="relative z-10">
|
||||||
|
<Zap className="w-8 h-8 opacity-90 text-white mb-2" />
|
||||||
|
<p className="font-bold text-lg leading-tight">Fastest Access Enabled</p>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs opacity-85 mt-2 relative z-10">
|
||||||
|
Smart routing engine successfully reduces terminal latency by <span className="font-bold">24ms</span> across European and Asian clusters.
|
||||||
|
</p>
|
||||||
|
<div className="absolute -right-6 -bottom-6 opacity-10">
|
||||||
|
<Zap className="w-32 h-32 rotate-12" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Grid Filter and Controls Header */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-outline-variant/30 pb-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<h3 className="text-lg font-bold text-on-surface">Recent Hosts</h3>
|
||||||
|
<div className="flex bg-surface-container rounded-lg p-0.5 text-xs font-semibold text-outline-variant border border-outline-variant/20">
|
||||||
|
<button
|
||||||
|
onClick={() => setStatusFilter('all')}
|
||||||
|
className={`px-2.5 py-1 rounded-md transition-all ${statusFilter === 'all' ? 'bg-white text-primary shadow-sm' : 'text-on-surface-variant hover:text-on-surface'}`}
|
||||||
|
>
|
||||||
|
All
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setStatusFilter('active')}
|
||||||
|
className={`px-2.5 py-1 rounded-md transition-all ${statusFilter === 'active' ? 'bg-white text-primary shadow-sm' : 'text-on-surface-variant hover:text-on-surface'}`}
|
||||||
|
>
|
||||||
|
Active
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setStatusFilter('offline')}
|
||||||
|
className={`px-2.5 py-1 rounded-md transition-all ${statusFilter === 'offline' ? 'bg-white text-primary shadow-sm' : 'text-on-surface-variant hover:text-on-surface'}`}
|
||||||
|
>
|
||||||
|
Offline
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{/* Inline Search */}
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-outline w-4 h-4" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Search hosts..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="pl-9 pr-4 py-1.5 rounded-full bg-surface-container-low border border-outline-variant/30 text-sm focus:border-primary focus:bg-white focus:outline-none focus:ring-1 focus:ring-primary w-48 sm:w-60 transition-all"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex border border-outline-variant/50 rounded-lg p-0.5 bg-white">
|
||||||
|
<button
|
||||||
|
onClick={() => setViewMode('grid')}
|
||||||
|
className={`p-1.5 rounded ${viewMode === 'grid' ? 'bg-surface-container text-primary' : 'text-on-surface-variant'}`}
|
||||||
|
title="Grid View"
|
||||||
|
>
|
||||||
|
<LayoutGrid className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setViewMode('list')}
|
||||||
|
className={`p-1.5 rounded ${viewMode === 'list' ? 'bg-surface-container text-primary' : 'text-on-surface-variant'}`}
|
||||||
|
title="List View"
|
||||||
|
>
|
||||||
|
<List className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Grid vs List View hosts container */}
|
||||||
|
{viewMode === 'grid' ? (
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
|
{filteredHosts.map((host) => (
|
||||||
|
<div
|
||||||
|
key={host.id}
|
||||||
|
className="group bg-white p-5 rounded-2xl border border-outline-variant hover:border-primary hover:shadow-lg transition-all cursor-pointer relative overflow-hidden"
|
||||||
|
>
|
||||||
|
<div className="flex justify-between items-start mb-4">
|
||||||
|
<div className="w-11 h-11 rounded-xl bg-surface-container-low flex items-center justify-center text-primary border border-outline-variant/20 group-hover:bg-primary-container/10 group-hover:border-primary/20 transition-colors">
|
||||||
|
{getOsIcon(host.os)}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span className={`w-2 h-2 rounded-full ${host.status === 'active' ? 'bg-secondary animate-pulse' : 'bg-outline'}`}></span>
|
||||||
|
<span className={`text-[10px] font-bold uppercase tracking-wider ${host.status === 'active' ? 'text-secondary' : 'text-outline'}`}>
|
||||||
|
{host.status}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h4 className="font-bold text-on-surface group-hover:text-primary transition-colors text-base truncate">{host.name}</h4>
|
||||||
|
<p className="font-mono text-xs text-outline mb-4">{host.ip}</p>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-1.5 mb-4">
|
||||||
|
<span className="px-2 py-0.5 bg-surface-container-low rounded text-[10px] font-medium text-on-surface-variant">
|
||||||
|
{host.os}
|
||||||
|
</span>
|
||||||
|
<span className="px-2 py-0.5 bg-surface-container-low rounded text-[10px] font-medium text-on-surface-variant">
|
||||||
|
{host.provider}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-3 border-t border-outline-variant/30 flex justify-between items-center text-xs">
|
||||||
|
<span className="text-outline italic">Last seen {host.lastSeen}</span>
|
||||||
|
<button
|
||||||
|
onClick={() => onConnectHost(host.name)}
|
||||||
|
className="bg-primary text-white hover:bg-primary-container hover:text-on-primary-container font-bold text-xs py-1.5 px-3 rounded-lg transition-all"
|
||||||
|
>
|
||||||
|
Connect
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{/* Add Host Button Placeholder */}
|
||||||
|
<div
|
||||||
|
onClick={() => setShowAddModal(true)}
|
||||||
|
className="group border-2 border-dashed border-outline-variant hover:border-primary hover:bg-primary/5 rounded-2xl flex flex-col items-center justify-center p-8 transition-all cursor-pointer text-center text-outline hover:text-primary"
|
||||||
|
>
|
||||||
|
<Plus className="w-8 h-8 mb-2 group-active:scale-90 transition-transform" />
|
||||||
|
<span className="font-bold text-sm text-on-surface-variant group-hover:text-primary">Add New Host</span>
|
||||||
|
<p className="text-[10px] uppercase tracking-widest mt-1 opacity-70">Manual Config or Discovery</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
/* List View Mode */
|
||||||
|
<div className="bg-white border border-outline-variant rounded-2xl overflow-hidden shadow-sm divide-y divide-outline-variant/30">
|
||||||
|
{filteredHosts.map((host) => (
|
||||||
|
<div
|
||||||
|
key={host.id}
|
||||||
|
className="flex items-center justify-between p-4 hover:bg-primary/5 transition-colors cursor-pointer group"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-4 min-w-0 flex-1">
|
||||||
|
<div className="w-10 h-10 rounded-lg bg-surface-container-low flex items-center justify-center text-primary shrink-0 border border-outline-variant/20">
|
||||||
|
{getOsIcon(host.os)}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1 sm:grid sm:grid-cols-3 sm:gap-4 items-center">
|
||||||
|
<div>
|
||||||
|
<h4 className="font-bold text-on-surface group-hover:text-primary transition-colors text-sm truncate">{host.name}</h4>
|
||||||
|
<span className="font-mono text-xs text-outline">{host.ip}</span>
|
||||||
|
</div>
|
||||||
|
<div className="hidden sm:block">
|
||||||
|
<p className="text-xs text-on-surface-variant font-medium">{host.os}</p>
|
||||||
|
<p className="text-[10px] text-outline">{host.provider}</p>
|
||||||
|
</div>
|
||||||
|
<div className="hidden md:block">
|
||||||
|
<span className="text-xs text-outline italic">Seen {host.lastSeen}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-4 ml-4 shrink-0">
|
||||||
|
<span className={`px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider flex items-center gap-1 ${host.status === 'active' ? 'bg-secondary-container/20 text-secondary' : 'bg-surface-container text-outline'}`}>
|
||||||
|
<span className={`w-1.5 h-1.5 rounded-full ${host.status === 'active' ? 'bg-secondary animate-pulse' : 'bg-outline'}`}></span>
|
||||||
|
{host.status}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => onConnectHost(host.name)}
|
||||||
|
className="bg-primary text-white hover:bg-primary-container hover:text-on-primary-container font-bold text-xs py-1.5 px-4 rounded-lg transition-all"
|
||||||
|
>
|
||||||
|
Connect
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div
|
||||||
|
onClick={() => setShowAddModal(true)}
|
||||||
|
className="p-4 hover:bg-primary/5 transition-colors cursor-pointer flex items-center justify-center gap-2 text-outline hover:text-primary font-bold text-sm"
|
||||||
|
>
|
||||||
|
<Plus className="w-5 h-5" /> Add New Host
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Transfer Activity - Asymmetric Bento footer panel */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<h3 className="text-base font-bold text-on-surface tracking-tight shrink-0">Background Transfers</h3>
|
||||||
|
<div className="flex-1 h-px bg-outline-variant/30"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white/50 backdrop-blur-sm border border-outline-variant rounded-2xl overflow-hidden shadow-sm">
|
||||||
|
<div className="p-4 border-b border-outline-variant flex items-center justify-between bg-surface-container-low">
|
||||||
|
<div className="flex gap-12 text-xs font-bold text-on-surface-variant uppercase tracking-tight">
|
||||||
|
<span>Source & File</span>
|
||||||
|
<span>Destination</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-xs font-bold text-on-surface-variant uppercase tracking-tight">Progress</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="divide-y divide-outline-variant/30 bg-white">
|
||||||
|
{transfers.map((item) => (
|
||||||
|
<div key={item.id} className="p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-4 hover:bg-primary/5 transition-colors">
|
||||||
|
<div className="flex items-center gap-4 min-w-0 flex-1">
|
||||||
|
<div className={`p-2 rounded-lg ${item.type === 'download' ? 'bg-tertiary/10 text-tertiary' : 'bg-primary/10 text-primary'}`}>
|
||||||
|
<FileCheck className="w-5 h-5" />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1 grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-bold truncate text-on-surface">{item.fileName}</p>
|
||||||
|
<span className="text-[10px] font-mono text-outline block">{item.source}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1 text-on-surface-variant text-xs">
|
||||||
|
<ArrowRight className="w-4 h-4 text-outline" />
|
||||||
|
<span className="truncate">{item.destination}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-full sm:w-48 shrink-0">
|
||||||
|
<div className="flex justify-between items-center mb-1">
|
||||||
|
<span className="text-[10px] font-bold text-secondary">{item.progress}%</span>
|
||||||
|
<span className="text-[10px] text-outline font-mono">{item.speed}</span>
|
||||||
|
</div>
|
||||||
|
<div className="h-1.5 w-full bg-surface-container-high rounded-full overflow-hidden">
|
||||||
|
<div
|
||||||
|
className="h-full bg-secondary rounded-full transition-all duration-500 shadow-[0_0_8px_rgba(0,110,47,0.3)]"
|
||||||
|
style={{ width: `${item.progress}%` }}
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Manual Add Host Modal */}
|
||||||
|
{showAddModal && (
|
||||||
|
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[150] flex items-center justify-center p-4">
|
||||||
|
<div className="bg-white rounded-2xl max-w-md w-full border border-outline-variant shadow-2xl overflow-hidden p-6 space-y-4 animate-scale-up">
|
||||||
|
<div className="flex justify-between items-center border-b border-outline-variant/30 pb-3">
|
||||||
|
<h3 className="font-bold text-lg text-on-surface">Add Host Credentials</h3>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAddModal(false)}
|
||||||
|
className="text-outline hover:text-primary cursor-pointer p-1 rounded-lg"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleCreateHost} className="space-y-4 text-sm">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">HOST IDENTIFIER</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
placeholder="e.g. prod-db-replica"
|
||||||
|
value={newHostName}
|
||||||
|
onChange={(e) => setNewHostName(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-4 focus:ring-2 focus:ring-primary/20 focus:border-primary focus:outline-none transition-all font-medium"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">IP ADDRESS / DOMAIN</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
placeholder="e.g. 10.0.12.19"
|
||||||
|
value={newHostIp}
|
||||||
|
onChange={(e) => setNewHostIp(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-4 focus:ring-2 focus:ring-primary/20 focus:border-primary focus:outline-none transition-all font-mono"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">OPERATING SYSTEM</label>
|
||||||
|
<select
|
||||||
|
value={newHostOs}
|
||||||
|
onChange={(e) => setNewHostOs(e.target.value as any)}
|
||||||
|
className="bg-surface-container-low border border-outline-variant/40 rounded-lg py-2 px-3 focus:outline-none focus:border-primary"
|
||||||
|
>
|
||||||
|
<option value="Ubuntu 22.04">Ubuntu 22.04</option>
|
||||||
|
<option value="Debian 11">Debian 11</option>
|
||||||
|
<option value="Alpine Linux">Alpine Linux</option>
|
||||||
|
<option value="Windows Server">Windows Server</option>
|
||||||
|
<option value="macOS Ventura">macOS Ventura</option>
|
||||||
|
<option value="CentOS 7">CentOS 7</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">PROVIDER</label>
|
||||||
|
<select
|
||||||
|
value={newHostProvider}
|
||||||
|
onChange={(e) => setNewHostProvider(e.target.value as any)}
|
||||||
|
className="bg-surface-container-low border border-outline-variant/40 rounded-lg py-2 px-3 focus:outline-none focus:border-primary"
|
||||||
|
>
|
||||||
|
<option value="AWS US-East">AWS Cloud</option>
|
||||||
|
<option value="GCP Cloud">GCP Cloud</option>
|
||||||
|
<option value="Hetzner">Hetzner</option>
|
||||||
|
<option value="Vercel Proxy">Vercel</option>
|
||||||
|
<option value="Local Docker">Docker</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">HOST PURPOSE / TYPE</label>
|
||||||
|
<div className="grid grid-cols-3 gap-2">
|
||||||
|
{['api', 'db', 'web'].map((t) => (
|
||||||
|
<button
|
||||||
|
key={t}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setNewHostType(t as any)}
|
||||||
|
className={`py-2 px-3 border rounded-lg font-bold text-xs uppercase tracking-wider transition-all ${newHostType === t ? 'bg-primary text-white border-primary' : 'bg-surface-container-low border-outline-variant/40 text-on-surface-variant hover:bg-surface-container'}`}
|
||||||
|
>
|
||||||
|
{t} Node
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-4 flex justify-end gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowAddModal(false)}
|
||||||
|
className="px-4 py-2 text-xs font-bold text-outline hover:text-on-surface"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="bg-primary text-white py-2 px-5 rounded-lg font-bold text-xs shadow-md hover:bg-primary-container hover:text-on-primary-container transition-all"
|
||||||
|
>
|
||||||
|
Add Host
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,359 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { KeychainItem } from '../types';
|
||||||
|
import { Shield, Key, Lock, Eye, EyeOff, Copy, Check, Plus, Search, Trash2, CheckCircle2, AlertTriangle, Info, HelpCircle } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function KeychainView() {
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [copiedId, setCopiedId] = useState<string | null>(null);
|
||||||
|
const [revealPassId, setRevealPassId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Keychain credentials collection
|
||||||
|
const [keychain, setKeychain] = useState<KeychainItem[]>([
|
||||||
|
{
|
||||||
|
id: '1',
|
||||||
|
name: 'id_ed25519_alex',
|
||||||
|
type: 'ED25519',
|
||||||
|
user: 'root',
|
||||||
|
lastUsed: '2 hours ago',
|
||||||
|
strength: 'secure',
|
||||||
|
fingerprint: 'SHA256:7mP9K9+fVj5bW0vQ8zD1y2u3t4m5n6p7q8r9s0v1w2x',
|
||||||
|
passphrase: 'supersecret_argon2_hashed',
|
||||||
|
connectedHosts: ['production-api-01', 'edge-node-berlin'],
|
||||||
|
keyFile: '— Private ED25519 Key file loaded —'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '2',
|
||||||
|
name: 'aws_prod_deploy_secret',
|
||||||
|
type: 'AWS Key',
|
||||||
|
user: 'deploy-agent',
|
||||||
|
lastUsed: '1 day ago',
|
||||||
|
strength: 'secure',
|
||||||
|
fingerprint: 'SHA256:8kU3A4+gYg2bS1vT8zP1q2e3r4t5y6u7i8o9p0a1s2d',
|
||||||
|
passphrase: 'aws_access_key_id_and_secret',
|
||||||
|
connectedHosts: ['web-frontend-02'],
|
||||||
|
keyFile: '— AWS Credentials payload —'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '3',
|
||||||
|
name: 'root_pg_prod',
|
||||||
|
type: 'PASSWORD',
|
||||||
|
user: 'postgres',
|
||||||
|
lastUsed: '5 hours ago',
|
||||||
|
strength: 'moderate',
|
||||||
|
passphrase: 'pg_db_master_password_2026',
|
||||||
|
connectedHosts: ['db-cluster-main'],
|
||||||
|
keyFile: 'Password token'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '4',
|
||||||
|
name: 'legacy_rsa_key',
|
||||||
|
type: 'SSH RSA',
|
||||||
|
user: 'admin',
|
||||||
|
lastUsed: '3 weeks ago',
|
||||||
|
strength: 'weak',
|
||||||
|
fingerprint: 'SHA256:legacy_md5_fingerprint_block',
|
||||||
|
passphrase: 'pass',
|
||||||
|
connectedHosts: [],
|
||||||
|
keyFile: '— 1024-bit Legacy SSH Keyfile —'
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
|
||||||
|
const [showAddModal, setShowAddModal] = useState(false);
|
||||||
|
const [newName, setNewName] = useState('');
|
||||||
|
const [newType, setNewType] = useState<'SSH RSA' | 'PASSWORD' | 'ED25519' | 'Bearer Token' | 'AWS Key'>('ED25519');
|
||||||
|
const [newUser, setNewUser] = useState('');
|
||||||
|
const [newPass, setNewPass] = useState('');
|
||||||
|
|
||||||
|
const triggerCopy = (id: string, text: string) => {
|
||||||
|
navigator.clipboard.writeText(text);
|
||||||
|
setCopiedId(id);
|
||||||
|
setTimeout(() => {
|
||||||
|
setCopiedId(null);
|
||||||
|
}, 2000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCreateCredential = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!newName || !newUser) return;
|
||||||
|
|
||||||
|
const strengthVal = newPass.length > 12 ? 'secure' : newPass.length > 7 ? 'moderate' : 'weak';
|
||||||
|
|
||||||
|
const item: KeychainItem = {
|
||||||
|
id: Date.now().toString(),
|
||||||
|
name: newName,
|
||||||
|
type: newType,
|
||||||
|
user: newUser,
|
||||||
|
lastUsed: 'Just now',
|
||||||
|
strength: strengthVal,
|
||||||
|
passphrase: newPass,
|
||||||
|
connectedHosts: [],
|
||||||
|
keyFile: newType.includes('Key') || newType.includes('ED25519') ? '— Custom key payload generated —' : 'Password credential'
|
||||||
|
};
|
||||||
|
|
||||||
|
setKeychain([item, ...keychain]);
|
||||||
|
setShowAddModal(false);
|
||||||
|
setNewName('');
|
||||||
|
setNewUser('');
|
||||||
|
setNewPass('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = (id: string) => {
|
||||||
|
setKeychain(prev => prev.filter(k => k.id !== id));
|
||||||
|
};
|
||||||
|
|
||||||
|
const filteredKeychain = keychain.filter(k =>
|
||||||
|
k.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
k.user.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
k.type.toLowerCase().includes(searchQuery.toLowerCase())
|
||||||
|
);
|
||||||
|
|
||||||
|
const getStrengthBadge = (strength: string) => {
|
||||||
|
switch (strength) {
|
||||||
|
case 'secure':
|
||||||
|
return (
|
||||||
|
<span className="shrink-0 px-2.5 py-0.5 bg-secondary-container/20 text-secondary border border-secondary/20 rounded-full text-[10px] font-bold uppercase tracking-wider flex items-center gap-1">
|
||||||
|
<CheckCircle2 className="w-3.5 h-3.5 text-secondary" />
|
||||||
|
SECURE
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
case 'moderate':
|
||||||
|
return (
|
||||||
|
<span className="shrink-0 px-2.5 py-0.5 bg-[#f0dbff] text-tertiary border border-tertiary/20 rounded-full text-[10px] font-bold uppercase tracking-wider flex items-center gap-1">
|
||||||
|
<Info className="w-3.5 h-3.5 text-tertiary" />
|
||||||
|
MODERATE
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return (
|
||||||
|
<span className="shrink-0 px-2.5 py-0.5 bg-error-container/20 text-error border border-error/20 rounded-full text-[10px] font-bold uppercase tracking-wider flex items-center gap-1">
|
||||||
|
<AlertTriangle className="w-3.5 h-3.5 text-error animate-bounce" />
|
||||||
|
WEAK
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 md:p-8 max-w-7xl mx-auto space-y-8 animate-fade-in">
|
||||||
|
|
||||||
|
{/* Header Panel */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-outline-variant/30 pb-4">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-xl font-bold text-on-surface tracking-tight">Keychain & Credentials</h2>
|
||||||
|
<p className="text-xs text-on-surface-variant mt-0.5">Secure sandbox containing cluster credentials, private SSH keys, and tokens</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-outline w-4 h-4" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Search credentials..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="pl-9 pr-4 py-1.5 rounded-full bg-surface-container-low border border-outline-variant/30 text-sm focus:border-primary focus:bg-white focus:outline-none focus:ring-1 focus:ring-primary w-48 sm:w-60 transition-all"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAddModal(true)}
|
||||||
|
className="flex items-center gap-1.5 bg-primary text-white hover:bg-primary-container hover:text-on-primary-container font-bold text-xs py-2 px-4 rounded-xl shadow-md transition-all cursor-pointer"
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4" />
|
||||||
|
Add Key
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Grid List */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
{filteredKeychain.map((item) => (
|
||||||
|
<div
|
||||||
|
key={item.id}
|
||||||
|
className="bg-white p-5 rounded-2xl border border-outline-variant hover:border-primary hover:shadow-lg transition-all flex flex-col justify-between space-y-4"
|
||||||
|
>
|
||||||
|
<div className="flex justify-between items-start gap-3">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-xl bg-surface-container-low border border-outline-variant/20 flex items-center justify-center text-primary">
|
||||||
|
<Shield className="w-5 h-5" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-bold text-on-surface text-base truncate max-w-[180px]">{item.name}</h3>
|
||||||
|
<span className="text-[10px] font-mono text-outline uppercase tracking-wider">{item.type}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{getStrengthBadge(item.strength)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2 text-xs">
|
||||||
|
<div className="flex justify-between items-center py-1 border-b border-outline-variant/10">
|
||||||
|
<span className="text-outline font-semibold uppercase tracking-wider text-[10px]">User Login</span>
|
||||||
|
<span className="font-mono text-on-surface font-semibold">{item.user}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between items-center py-1 border-b border-outline-variant/10">
|
||||||
|
<span className="text-outline font-semibold uppercase tracking-wider text-[10px]">Credential Secrets</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="font-mono text-on-surface-variant">
|
||||||
|
{revealPassId === item.id ? item.passphrase : '••••••••••••••••'}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => setRevealPassId(revealPassId === item.id ? null : item.id)}
|
||||||
|
className="p-1 hover:bg-surface-container rounded text-outline transition-colors"
|
||||||
|
title={revealPassId === item.id ? "Hide password" : "Show password"}
|
||||||
|
>
|
||||||
|
{revealPassId === item.id ? <EyeOff className="w-3.5 h-3.5" /> : <Eye className="w-3.5 h-3.5" />}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => triggerCopy(item.id, item.passphrase || '')}
|
||||||
|
className="p-1 hover:bg-surface-container rounded text-outline transition-colors"
|
||||||
|
title="Copy secret"
|
||||||
|
>
|
||||||
|
{copiedId === item.id ? <Check className="w-3.5 h-3.5 text-secondary" /> : <Copy className="w-3.5 h-3.5" />}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{item.fingerprint && (
|
||||||
|
<div className="py-1">
|
||||||
|
<span className="text-outline font-semibold uppercase tracking-wider text-[10px] block mb-0.5">SHA256 FINGERPRINT</span>
|
||||||
|
<code className="text-[10px] text-on-surface-variant font-mono block break-all bg-surface-container-low p-2 rounded border border-outline-variant/20 select-all">{item.fingerprint}</code>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-3 border-t border-outline-variant/30 flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-[10px] text-outline">
|
||||||
|
<span className="shrink-0">Last used {item.lastUsed}</span>
|
||||||
|
<div className="flex items-center justify-between sm:justify-end gap-2 flex-1 min-w-0 w-full">
|
||||||
|
<div className="flex items-center gap-1.5 min-w-0 flex-1 justify-start sm:justify-end">
|
||||||
|
<span className="text-outline shrink-0 font-bold">Hosts:</span>
|
||||||
|
{item.connectedHosts && item.connectedHosts.length > 0 ? (
|
||||||
|
<div className="flex flex-wrap gap-1 max-h-[44px] overflow-y-auto no-scrollbar justify-start sm:justify-end">
|
||||||
|
{item.connectedHosts.map((host) => (
|
||||||
|
<span
|
||||||
|
key={host}
|
||||||
|
className="bg-primary-container/15 text-primary px-1.5 py-0.5 rounded font-mono text-[9px] hover:bg-primary/10 transition-colors shrink-0"
|
||||||
|
title={host}
|
||||||
|
>
|
||||||
|
{host}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<span className="text-outline italic">None mapped</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(item.id)}
|
||||||
|
className="p-1 hover:bg-error-container hover:text-error rounded text-outline transition-colors shrink-0 cursor-pointer ml-1"
|
||||||
|
title="Remove credential"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Security Advisory Bento */}
|
||||||
|
<div className="p-5 border border-outline-variant/60 rounded-2xl bg-white/40 flex items-start gap-4 text-xs text-on-surface">
|
||||||
|
<Info className="w-5 h-5 text-primary shrink-0 mt-0.5" />
|
||||||
|
<div className="space-y-1">
|
||||||
|
<h4 className="font-bold text-on-surface">HostKeeper Security Policy & Local Sandbox</h4>
|
||||||
|
<p className="text-on-surface-variant leading-relaxed">
|
||||||
|
Keys are parsed locally inside your isolated browser environment and transmitted strictly within cryptographically verified SSH tunnels. Passphrases are hashed with Argon2id instantly and never touch intermediate telemetry systems.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Add Credential Modal */}
|
||||||
|
{showAddModal && (
|
||||||
|
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[150] flex items-center justify-center p-4">
|
||||||
|
<div className="bg-white rounded-2xl max-w-md w-full border border-outline-variant shadow-2xl p-6 space-y-4 animate-scale-up">
|
||||||
|
<div className="flex justify-between items-center border-b border-outline-variant/30 pb-3">
|
||||||
|
<h3 className="font-bold text-lg text-on-surface">Register Secure Credential</h3>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAddModal(false)}
|
||||||
|
className="text-outline hover:text-primary cursor-pointer p-1 rounded"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleCreateCredential} className="space-y-4 text-sm">
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">CREDENTIAL NAME / LABEL</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
placeholder="e.g. key_aws_alex"
|
||||||
|
value={newName}
|
||||||
|
onChange={(e) => setNewName(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-4 focus:ring-2 focus:ring-primary/20 focus:border-primary focus:outline-none transition-all font-medium"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">CREDENTIAL TYPE</label>
|
||||||
|
<select
|
||||||
|
value={newType}
|
||||||
|
onChange={(e) => setNewType(e.target.value as any)}
|
||||||
|
className="bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-3 focus:outline-none focus:border-primary"
|
||||||
|
>
|
||||||
|
<option value="ED25519">ED25519 (Modern)</option>
|
||||||
|
<option value="SSH RSA">SSH RSA (Legacy)</option>
|
||||||
|
<option value="PASSWORD">Master Password</option>
|
||||||
|
<option value="Bearer Token">Bearer Token</option>
|
||||||
|
<option value="AWS Key">AWS Access Key</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">LOGIN USERNAME</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
placeholder="e.g. root or ubuntu"
|
||||||
|
value={newUser}
|
||||||
|
onChange={(e) => setNewUser(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-3 focus:outline-none focus:border-primary font-medium"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">PASSPHRASE / TOKEN KEY</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
placeholder="Enter secure password secret..."
|
||||||
|
value={newPass}
|
||||||
|
onChange={(e) => setNewPass(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-4 focus:ring-2 focus:ring-primary/20 focus:border-primary focus:outline-none transition-all font-mono"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-4 flex justify-end gap-3 border-t border-outline-variant/20">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowAddModal(false)}
|
||||||
|
className="px-4 py-2 text-xs font-bold text-outline hover:text-on-surface"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="bg-primary text-white py-2 px-5 rounded-lg font-bold text-xs shadow-md hover:bg-primary-container hover:text-on-primary-container transition-all"
|
||||||
|
>
|
||||||
|
Save Credential
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Device } from '../types';
|
||||||
|
import { User, Bell, Shield, Smartphone, Laptop, CheckCircle, Zap, Save, RefreshCw, Star, LogOut, Check } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function SettingsView() {
|
||||||
|
const [name, setName] = useState('Alex Rivera');
|
||||||
|
const [email, setEmail] = useState('alex.rivera@hostkeeper.io');
|
||||||
|
const [role, setRole] = useState('Senior DevOps Lead');
|
||||||
|
|
||||||
|
// Toggle states
|
||||||
|
const [keyBackup, setKeyBackup] = useState(true);
|
||||||
|
const [bgSync, setBgSync] = useState(true);
|
||||||
|
const [notifyTransfer, setNotifyTransfer] = useState(false);
|
||||||
|
const [showSaveSuccess, setShowSaveSuccess] = useState(false);
|
||||||
|
|
||||||
|
// Active connected sync devices
|
||||||
|
const [devices, setDevices] = useState<Device[]>([
|
||||||
|
{ id: '1', name: 'Alex MacBook Pro 16"', type: 'desktop', status: 'online' },
|
||||||
|
{ id: '2', name: 'Rivera iPad Air 5', type: 'tablet', status: 'online' },
|
||||||
|
{ id: '3', name: 'iPhone 15 Pro Max', type: 'mobile', status: 'offline' }
|
||||||
|
]);
|
||||||
|
|
||||||
|
const handleSaveProfile = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setShowSaveSuccess(true);
|
||||||
|
setTimeout(() => {
|
||||||
|
setShowSaveSuccess(false);
|
||||||
|
}, 2500);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getDeviceIcon = (type: string) => {
|
||||||
|
switch (type) {
|
||||||
|
case 'desktop': return <Laptop className="w-5 h-5 text-primary" />;
|
||||||
|
default: return <Smartphone className="w-5 h-5 text-outline" />;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 md:p-8 max-w-7xl mx-auto space-y-8 animate-fade-in text-sm">
|
||||||
|
|
||||||
|
{/* Toast Alert Simulation */}
|
||||||
|
{showSaveSuccess && (
|
||||||
|
<div className="fixed bottom-6 right-6 z-[180] bg-inverse-surface text-inverse-on-surface px-5 py-3.5 rounded-xl shadow-xl flex items-center gap-3 border border-outline/20 animate-slide-in text-xs font-semibold">
|
||||||
|
<CheckCircle className="w-4 h-4 text-secondary animate-bounce" />
|
||||||
|
<span>Profile parameters updated successfully!</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Header Panel */}
|
||||||
|
<div className="border-b border-outline-variant/30 pb-4">
|
||||||
|
<h2 className="text-xl font-bold text-on-surface tracking-tight">Workspace Preferences</h2>
|
||||||
|
<p className="text-xs text-on-surface-variant mt-0.5">Configure authentication sync protocols and cloud billing</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
|
||||||
|
|
||||||
|
{/* Left Side: Profile Form and Toggle configs */}
|
||||||
|
<div className="lg:col-span-8 space-y-8">
|
||||||
|
|
||||||
|
{/* Section: Profile Form */}
|
||||||
|
<div className="bg-white p-6 rounded-2xl border border-outline-variant shadow-sm space-y-6">
|
||||||
|
<h3 className="font-bold text-on-surface text-base flex items-center gap-2">
|
||||||
|
<User className="w-5 h-5 text-primary" />
|
||||||
|
Developer Profile
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<form onSubmit={handleSaveProfile} className="grid grid-cols-1 sm:grid-cols-2 gap-5">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">FULL NAME</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-4 focus:ring-2 focus:ring-primary/20 focus:border-primary focus:outline-none transition-all font-semibold text-on-surface"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">EMAIL ADDRESS</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-4 focus:ring-2 focus:ring-primary/20 focus:border-primary focus:outline-none transition-all font-medium text-on-surface"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1.5 sm:col-span-2">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">WORKPLACE DESIGNATION / ROLE</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
value={role}
|
||||||
|
onChange={(e) => setRole(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-4 focus:ring-2 focus:ring-primary/20 focus:border-primary focus:outline-none transition-all font-medium text-on-surface"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="sm:col-span-2 pt-2 flex justify-end">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="flex items-center gap-2 bg-primary text-white hover:bg-primary-container hover:text-on-primary-container font-bold text-xs py-2.5 px-6 rounded-xl shadow-md transition-all cursor-pointer"
|
||||||
|
>
|
||||||
|
<Save className="w-4 h-4" />
|
||||||
|
Save Changes
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Section: Feature Toggles */}
|
||||||
|
<div className="bg-white p-6 rounded-2xl border border-outline-variant shadow-sm space-y-6">
|
||||||
|
<h3 className="font-bold text-on-surface text-base flex items-center gap-2">
|
||||||
|
<Shield className="w-5 h-5 text-primary" />
|
||||||
|
Security & Transmission Protocols
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div className="space-y-4 divide-y divide-outline-variant/20">
|
||||||
|
|
||||||
|
{/* Toggle Row 1 */}
|
||||||
|
<div className="flex items-center justify-between py-3">
|
||||||
|
<div className="space-y-0.5 pr-4">
|
||||||
|
<h4 className="font-bold text-on-surface text-xs sm:text-sm">Cryptographic Keychain Backup</h4>
|
||||||
|
<p className="text-xs text-on-surface-variant">Synchronize securely encrypted keys automatically inside iCloud/Google drive sandboxes.</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setKeyBackup(!keyBackup)}
|
||||||
|
className={`w-11 h-6 rounded-full transition-colors relative flex items-center shrink-0 cursor-pointer ${keyBackup ? 'bg-primary' : 'bg-outline-variant'}`}
|
||||||
|
>
|
||||||
|
<span className={`w-4 h-4 bg-white rounded-full shadow transition-transform absolute ${keyBackup ? 'translate-x-6' : 'translate-x-1'}`}></span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Toggle Row 2 */}
|
||||||
|
<div className="flex items-center justify-between pt-3">
|
||||||
|
<div className="space-y-0.5 pr-4">
|
||||||
|
<h4 className="font-bold text-on-surface text-xs sm:text-sm">Real-time SFTP Connection Polling</h4>
|
||||||
|
<p className="text-xs text-on-surface-variant">Enable background file watchers to automatically refresh the directory tree upon local file modifications.</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setBgSync(!bgSync)}
|
||||||
|
className={`w-11 h-6 rounded-full transition-colors relative flex items-center shrink-0 cursor-pointer ${bgSync ? 'bg-primary' : 'bg-outline-variant'}`}
|
||||||
|
>
|
||||||
|
<span className={`w-4 h-4 bg-white rounded-full shadow transition-transform absolute ${bgSync ? 'translate-x-6' : 'translate-x-1'}`}></span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Toggle Row 3 */}
|
||||||
|
<div className="flex items-center justify-between pt-3">
|
||||||
|
<div className="space-y-0.5 pr-4">
|
||||||
|
<h4 className="font-bold text-on-surface text-xs sm:text-sm">Desktop Push Notifications</h4>
|
||||||
|
<p className="text-xs text-on-surface-variant">Trigger native system indicators upon complete transmissions of download/upload streams.</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setNotifyTransfer(!notifyTransfer)}
|
||||||
|
className={`w-11 h-6 rounded-full transition-colors relative flex items-center shrink-0 cursor-pointer ${notifyTransfer ? 'bg-primary' : 'bg-outline-variant'}`}
|
||||||
|
>
|
||||||
|
<span className={`w-4 h-4 bg-white rounded-full shadow transition-transform absolute ${notifyTransfer ? 'translate-x-6' : 'translate-x-1'}`}></span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Right Side: Billing Status and Devices List */}
|
||||||
|
<div className="lg:col-span-4 space-y-8">
|
||||||
|
|
||||||
|
{/* Pro Billing Card */}
|
||||||
|
<div className="bg-primary text-on-primary p-6 rounded-2xl shadow-lg relative overflow-hidden flex flex-col justify-between h-48">
|
||||||
|
<div className="relative z-10">
|
||||||
|
<div className="flex justify-between items-start">
|
||||||
|
<span className="px-2.5 py-1 bg-white/20 rounded-full font-bold text-[9px] uppercase tracking-wider text-white">HostKeeper Pro</span>
|
||||||
|
<Star className="w-5 h-5 text-white fill-white" />
|
||||||
|
</div>
|
||||||
|
<h3 className="font-black text-2xl tracking-tight mt-3">Active Workspace</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="relative z-10 flex justify-between items-end">
|
||||||
|
<div>
|
||||||
|
<span className="text-xs opacity-80 uppercase font-semibold">RENEWAL CYCLE</span>
|
||||||
|
<p className="text-xs font-bold text-white">July 2026</p>
|
||||||
|
</div>
|
||||||
|
<span className="text-[10px] font-bold bg-white text-primary rounded-lg px-2.5 py-1 flex items-center gap-1">
|
||||||
|
<Check className="w-3.5 h-3.5" /> PAID ACCOUNT
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="absolute right-0 bottom-0 opacity-10 pointer-events-none">
|
||||||
|
<Zap className="w-48 h-48 rotate-45" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Connected Sync Devices list */}
|
||||||
|
<div className="bg-white p-5 rounded-2xl border border-outline-variant shadow-sm space-y-4">
|
||||||
|
<h3 className="font-bold text-on-surface text-sm flex items-center gap-2">
|
||||||
|
<Smartphone className="w-4.5 h-4.5 text-primary" />
|
||||||
|
Synchronized Devices
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div className="space-y-3.5">
|
||||||
|
{devices.map((device) => (
|
||||||
|
<div key={device.id} className="flex items-center justify-between text-xs">
|
||||||
|
<div className="flex items-center gap-2.5 min-w-0">
|
||||||
|
<div className="p-1.5 bg-surface-container-low border border-outline-variant/20 rounded-lg text-primary shrink-0">
|
||||||
|
{getDeviceIcon(device.type)}
|
||||||
|
</div>
|
||||||
|
<span className="font-bold text-on-surface truncate pr-2">{device.name}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span className={`px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-wider flex items-center gap-1 shrink-0 ${device.status === 'online' ? 'bg-secondary-container/20 text-secondary' : 'bg-surface-container text-outline'}`}>
|
||||||
|
<span className={`w-1 h-1 rounded-full ${device.status === 'online' ? 'bg-secondary animate-pulse' : 'bg-outline'}`}></span>
|
||||||
|
{device.status}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Danger Zone */}
|
||||||
|
<div className="p-4 border border-error-container/40 rounded-2xl bg-error-container/5 space-y-3 text-xs">
|
||||||
|
<h4 className="font-bold text-error flex items-center gap-2">
|
||||||
|
<LogOut className="w-4 h-4" /> Reset Local State
|
||||||
|
</h4>
|
||||||
|
<p className="text-on-surface-variant">Resetting will clear all your locally loaded keystores, snippets, and connection cache buffers from the browser storage.</p>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
if(confirm("Are you sure you want to flush all local storage configurations?")) {
|
||||||
|
localStorage.clear();
|
||||||
|
alert("Workspace storage cleared successfully.");
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="w-full py-2 border border-error/30 rounded-xl font-bold text-error hover:bg-error/10 transition-colors"
|
||||||
|
>
|
||||||
|
Flush All App State
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { FileItem } from '../types';
|
||||||
|
import {
|
||||||
|
Folder,
|
||||||
|
File,
|
||||||
|
FileCode,
|
||||||
|
FileImage,
|
||||||
|
Lock,
|
||||||
|
ArrowLeftRight,
|
||||||
|
Upload,
|
||||||
|
Download,
|
||||||
|
RefreshCw,
|
||||||
|
ChevronRight,
|
||||||
|
Search,
|
||||||
|
FolderPlus,
|
||||||
|
Trash2,
|
||||||
|
CheckCircle,
|
||||||
|
HardDrive,
|
||||||
|
Globe
|
||||||
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
export default function SftpView() {
|
||||||
|
const [localPath, setLocalPath] = useState('/Users/alex/workspace/hostkeeper');
|
||||||
|
const [remotePath, setRemotePath] = useState('/var/www/prod-api-cluster/src');
|
||||||
|
const [localSearch, setLocalSearch] = useState('');
|
||||||
|
const [remoteSearch, setRemoteSearch] = useState('');
|
||||||
|
|
||||||
|
// Active Toast simulation state
|
||||||
|
const [toastMessage, setToastMessage] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Initial local mock file system
|
||||||
|
const [localFiles, setLocalFiles] = useState<FileItem[]>([
|
||||||
|
{ name: 'public', size: '—', modified: '2 hours ago', type: 'folder' },
|
||||||
|
{ name: 'src', size: '—', modified: '10 mins ago', type: 'folder' },
|
||||||
|
{ name: 'package.json', size: '1.4 KB', modified: 'Just now', type: 'code' },
|
||||||
|
{ name: 'vite.config.ts', size: '860 B', modified: '2 days ago', type: 'code' },
|
||||||
|
{ name: 'tailwind.config.js', size: '1.1 KB', modified: '3 days ago', type: 'code' },
|
||||||
|
{ name: 'App.tsx', size: '12.4 KB', modified: 'Just now', type: 'code' },
|
||||||
|
{ name: 'logo_hero.png', size: '240 KB', modified: '1 week ago', type: 'image' },
|
||||||
|
{ name: '.env', size: '280 B', modified: 'Yesterday', type: 'lock' }
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Initial remote mock file system
|
||||||
|
const [remoteFiles, setRemoteFiles] = useState<FileItem[]>([
|
||||||
|
{ name: 'controllers', size: '—', modified: '1 day ago', type: 'folder' },
|
||||||
|
{ name: 'models', size: '—', modified: '1 day ago', type: 'folder' },
|
||||||
|
{ name: 'routes', size: '—', modified: '4 hours ago', type: 'folder' },
|
||||||
|
{ name: 'server.js', size: '8.4 KB', modified: '2 hours ago', type: 'code' },
|
||||||
|
{ name: 'config.production.json', size: '2.1 KB', modified: '1 week ago', type: 'lock' },
|
||||||
|
{ name: 'index.html', size: '3.2 KB', modified: '3 hours ago', type: 'code' },
|
||||||
|
{ name: 'avatar_default.jpg', size: '18 KB', modified: '2 weeks ago', type: 'image' },
|
||||||
|
{ name: 'node_modules.tar.gz', size: '42 MB', modified: '3 days ago', type: 'file' }
|
||||||
|
]);
|
||||||
|
|
||||||
|
const triggerToast = (msg: string) => {
|
||||||
|
setToastMessage(msg);
|
||||||
|
setTimeout(() => {
|
||||||
|
setToastMessage(null);
|
||||||
|
}, 3500);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLocalClick = (item: FileItem) => {
|
||||||
|
if (item.type === 'folder') {
|
||||||
|
setLocalPath(`${localPath}/${item.name}`);
|
||||||
|
triggerToast(`Navigated into local folder: ${item.name}`);
|
||||||
|
} else {
|
||||||
|
triggerToast(`Uploading "${item.name}" to remote server...`);
|
||||||
|
// Simulate transfer additions
|
||||||
|
setTimeout(() => {
|
||||||
|
setRemoteFiles(prev => [
|
||||||
|
{ name: item.name, size: item.size, modified: 'Just now', type: item.type },
|
||||||
|
...prev
|
||||||
|
]);
|
||||||
|
triggerToast(`Successfully uploaded "${item.name}" to ${remotePath}`);
|
||||||
|
}, 1500);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoteClick = (item: FileItem) => {
|
||||||
|
if (item.type === 'folder') {
|
||||||
|
setRemotePath(`${remotePath}/${item.name}`);
|
||||||
|
triggerToast(`Navigated remote server path to: ${item.name}`);
|
||||||
|
} else {
|
||||||
|
triggerToast(`Downloading "${item.name}" from remote server...`);
|
||||||
|
setTimeout(() => {
|
||||||
|
setLocalFiles(prev => [
|
||||||
|
{ name: item.name, size: item.size, modified: 'Just now', type: item.type },
|
||||||
|
...prev
|
||||||
|
]);
|
||||||
|
triggerToast(`Successfully downloaded "${item.name}" to local environment.`);
|
||||||
|
}, 1500);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCreateFolder = (target: 'local' | 'remote') => {
|
||||||
|
const folderName = prompt(`Enter new folder name for ${target}:`);
|
||||||
|
if (!folderName) return;
|
||||||
|
|
||||||
|
const newFolder: FileItem = {
|
||||||
|
name: folderName,
|
||||||
|
size: '—',
|
||||||
|
modified: 'Just now',
|
||||||
|
type: 'folder'
|
||||||
|
};
|
||||||
|
|
||||||
|
if (target === 'local') {
|
||||||
|
setLocalFiles([newFolder, ...localFiles]);
|
||||||
|
triggerToast(`Created folder "${folderName}" locally.`);
|
||||||
|
} else {
|
||||||
|
setRemoteFiles([newFolder, ...remoteFiles]);
|
||||||
|
triggerToast(`Created folder "${folderName}" on remote host.`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteFile = (name: string, target: 'local' | 'remote') => {
|
||||||
|
if (target === 'local') {
|
||||||
|
setLocalFiles(prev => prev.filter(f => f.name !== name));
|
||||||
|
triggerToast(`Deleted local file "${name}"`);
|
||||||
|
} else {
|
||||||
|
setRemoteFiles(prev => prev.filter(f => f.name !== name));
|
||||||
|
triggerToast(`Deleted remote file "${name}"`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getFileIcon = (type: string) => {
|
||||||
|
switch (type) {
|
||||||
|
case 'folder':
|
||||||
|
return <Folder className="w-4 h-4 text-primary" />;
|
||||||
|
case 'code':
|
||||||
|
return <FileCode className="w-4 h-4 text-tertiary" />;
|
||||||
|
case 'image':
|
||||||
|
return <FileImage className="w-4 h-4 text-secondary" />;
|
||||||
|
case 'lock':
|
||||||
|
return <Lock className="w-4 h-4 text-error" />;
|
||||||
|
default:
|
||||||
|
return <File className="w-4 h-4 text-outline" />;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const filteredLocal = localFiles.filter(f => f.name.toLowerCase().includes(localSearch.toLowerCase()));
|
||||||
|
const filteredRemote = remoteFiles.filter(f => f.name.toLowerCase().includes(remoteSearch.toLowerCase()));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 md:p-8 max-w-7xl mx-auto space-y-6 animate-fade-in relative">
|
||||||
|
{/* Toast Alert simulation */}
|
||||||
|
{toastMessage && (
|
||||||
|
<div className="fixed bottom-6 right-6 z-[180] bg-inverse-surface text-inverse-on-surface px-5 py-3.5 rounded-xl shadow-xl flex items-center gap-3 border border-outline/20 animate-slide-in text-xs font-semibold">
|
||||||
|
<CheckCircle className="w-4 h-4 text-secondary animate-bounce" />
|
||||||
|
<span>{toastMessage}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Header Panel */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-outline-variant/30 pb-4">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-xl font-bold text-on-surface tracking-tight">SFTP Secure File Sync</h2>
|
||||||
|
<p className="text-xs text-on-surface-variant mt-0.5">Dual streams for real-time asset transmission and file editing</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setLocalFiles([
|
||||||
|
{ name: 'public', size: '—', modified: '2 hours ago', type: 'folder' },
|
||||||
|
{ name: 'src', size: '—', modified: '10 mins ago', type: 'folder' },
|
||||||
|
{ name: 'package.json', size: '1.4 KB', modified: 'Just now', type: 'code' },
|
||||||
|
{ name: 'vite.config.ts', size: '860 B', modified: '2 days ago', type: 'code' },
|
||||||
|
{ name: 'tailwind.config.js', size: '1.1 KB', modified: '3 days ago', type: 'code' }
|
||||||
|
]);
|
||||||
|
setRemoteFiles([
|
||||||
|
{ name: 'controllers', size: '—', modified: '1 day ago', type: 'folder' },
|
||||||
|
{ name: 'models', size: '—', modified: '1 day ago', type: 'folder' },
|
||||||
|
{ name: 'server.js', size: '8.4 KB', modified: '2 hours ago', type: 'code' }
|
||||||
|
]);
|
||||||
|
triggerToast('Refreshed workspace file tree arrays.');
|
||||||
|
}}
|
||||||
|
className="flex items-center gap-2 px-3 py-1.5 rounded-lg border border-outline-variant hover:border-primary text-xs font-semibold text-on-surface bg-white transition-all hover:bg-surface-container"
|
||||||
|
>
|
||||||
|
<RefreshCw className="w-3.5 h-3.5" />
|
||||||
|
Reset State
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Dual Panel Body */}
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||||
|
|
||||||
|
{/* Local Stream File Panel */}
|
||||||
|
<div className="bg-white rounded-2xl border border-outline-variant overflow-hidden shadow-sm flex flex-col h-[520px]">
|
||||||
|
{/* Stream Header */}
|
||||||
|
<div className="p-4 border-b border-outline-variant/50 bg-surface-container-low flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
|
<HardDrive className="w-4 h-4 text-outline shrink-0" />
|
||||||
|
<span className="font-bold text-xs text-on-surface truncate uppercase tracking-wider">Local Workstation</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => handleCreateFolder('local')}
|
||||||
|
className="text-primary hover:text-primary-container p-1 rounded hover:bg-primary/5 transition-all"
|
||||||
|
title="New Local Folder"
|
||||||
|
>
|
||||||
|
<FolderPlus className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Breadcrumb path navigation bar */}
|
||||||
|
<div className="px-4 py-2 border-b border-outline-variant/20 bg-surface-container-lowest flex items-center gap-1.5 text-xs text-outline font-mono overflow-x-auto no-scrollbar">
|
||||||
|
<span className="text-primary-fixed-dim hover:underline cursor-pointer" onClick={() => setLocalPath('/Users/alex')}>alex</span>
|
||||||
|
<ChevronRight className="w-3 h-3 text-outline/40 shrink-0" />
|
||||||
|
<span className="text-primary-fixed-dim hover:underline cursor-pointer" onClick={() => setLocalPath('/Users/alex/workspace')}>workspace</span>
|
||||||
|
<ChevronRight className="w-3 h-3 text-outline/40 shrink-0" />
|
||||||
|
<span className="text-on-surface truncate">{localPath.split('/').pop()}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* File Stream Search Filter */}
|
||||||
|
<div className="p-3 border-b border-outline-variant/10 relative">
|
||||||
|
<Search className="absolute left-6 top-1/2 -translate-y-1/2 text-outline w-3.5 h-3.5" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Filter local files..."
|
||||||
|
value={localSearch}
|
||||||
|
onChange={(e) => setLocalSearch(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low pl-10 pr-4 py-1.5 border border-outline-variant/30 rounded-lg text-xs font-medium focus:outline-none focus:border-primary focus:bg-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Local files list table */}
|
||||||
|
<div className="flex-1 overflow-y-auto min-h-0">
|
||||||
|
<table className="w-full text-left border-collapse text-xs">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-outline-variant/20 text-outline uppercase tracking-wider font-bold">
|
||||||
|
<th className="py-2.5 px-4 font-semibold text-[10px]">Name</th>
|
||||||
|
<th className="py-2.5 px-4 font-semibold text-[10px] text-right">Size</th>
|
||||||
|
<th className="py-2.5 px-4 font-semibold text-[10px] text-right">Modified</th>
|
||||||
|
<th className="py-2.5 px-4 font-semibold text-[10px]"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{filteredLocal.map((file) => (
|
||||||
|
<tr
|
||||||
|
key={file.name}
|
||||||
|
className="border-b border-outline-variant/10 hover:bg-primary/5 transition-colors group cursor-pointer"
|
||||||
|
>
|
||||||
|
<td className="py-2.5 px-4">
|
||||||
|
<div
|
||||||
|
onClick={() => handleLocalClick(file)}
|
||||||
|
className="font-semibold text-on-surface flex items-center gap-2.5 max-w-[180px] cursor-pointer"
|
||||||
|
>
|
||||||
|
<span className="shrink-0">{getFileIcon(file.type)}</span>
|
||||||
|
<span className="truncate group-hover:text-primary transition-colors">{file.name}</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="py-2.5 px-4 text-right text-on-surface-variant font-mono">{file.size}</td>
|
||||||
|
<td className="py-2.5 px-4 text-right text-outline">{file.modified}</td>
|
||||||
|
<td className="py-2.5 px-4 text-right">
|
||||||
|
<div className="flex items-center justify-end gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||||
|
<button
|
||||||
|
onClick={() => handleLocalClick(file)}
|
||||||
|
className="p-1 hover:bg-primary/10 rounded text-primary transition-colors"
|
||||||
|
title="Upload to remote"
|
||||||
|
>
|
||||||
|
<Upload className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDeleteFile(file.name, 'local')}
|
||||||
|
className="p-1 hover:bg-error-container hover:text-error rounded text-outline transition-colors"
|
||||||
|
title="Delete file"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-3 bg-surface-container-low border-t border-outline-variant text-[10px] text-outline text-center font-bold">
|
||||||
|
TIP: Click file or upload button to transmit to server
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Remote Stream File Panel */}
|
||||||
|
<div className="bg-white rounded-2xl border border-outline-variant overflow-hidden shadow-sm flex flex-col h-[520px]">
|
||||||
|
{/* Stream Header */}
|
||||||
|
<div className="p-4 border-b border-outline-variant/50 bg-surface-container-low flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
|
<Globe className="w-4 h-4 text-primary shrink-0" />
|
||||||
|
<span className="font-bold text-xs text-on-surface truncate uppercase tracking-wider">Remote Cluster Node</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => handleCreateFolder('remote')}
|
||||||
|
className="text-primary hover:text-primary-container p-1 rounded hover:bg-primary/5 transition-all"
|
||||||
|
title="New Remote Folder"
|
||||||
|
>
|
||||||
|
<FolderPlus className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Breadcrumb path navigation bar */}
|
||||||
|
<div className="px-4 py-2 border-b border-outline-variant/20 bg-surface-container-lowest flex items-center gap-1.5 text-xs text-outline font-mono overflow-x-auto no-scrollbar">
|
||||||
|
<span className="text-primary-fixed-dim hover:underline cursor-pointer" onClick={() => setRemotePath('/var')}>var</span>
|
||||||
|
<ChevronRight className="w-3 h-3 text-outline/40 shrink-0" />
|
||||||
|
<span className="text-primary-fixed-dim hover:underline cursor-pointer" onClick={() => setRemotePath('/var/www')}>www</span>
|
||||||
|
<ChevronRight className="w-3 h-3 text-outline/40 shrink-0" />
|
||||||
|
<span className="text-on-surface truncate">{remotePath.split('/').pop()}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* File Stream Search Filter */}
|
||||||
|
<div className="p-3 border-b border-outline-variant/10 relative">
|
||||||
|
<Search className="absolute left-6 top-1/2 -translate-y-1/2 text-outline w-3.5 h-3.5" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Filter remote files..."
|
||||||
|
value={remoteSearch}
|
||||||
|
onChange={(e) => setRemoteSearch(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low pl-10 pr-4 py-1.5 border border-outline-variant/30 rounded-lg text-xs font-medium focus:outline-none focus:border-primary focus:bg-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Remote files list table */}
|
||||||
|
<div className="flex-1 overflow-y-auto min-h-0">
|
||||||
|
<table className="w-full text-left border-collapse text-xs">
|
||||||
|
<thead>
|
||||||
|
<tr className="border-b border-outline-variant/20 text-outline uppercase tracking-wider font-bold">
|
||||||
|
<th className="py-2.5 px-4 font-semibold text-[10px]">Name</th>
|
||||||
|
<th className="py-2.5 px-4 font-semibold text-[10px] text-right">Size</th>
|
||||||
|
<th className="py-2.5 px-4 font-semibold text-[10px] text-right">Modified</th>
|
||||||
|
<th className="py-2.5 px-4 font-semibold text-[10px]"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{filteredRemote.map((file) => (
|
||||||
|
<tr
|
||||||
|
key={file.name}
|
||||||
|
className="border-b border-outline-variant/10 hover:bg-primary/5 transition-colors group cursor-pointer"
|
||||||
|
>
|
||||||
|
<td className="py-2.5 px-4">
|
||||||
|
<div
|
||||||
|
onClick={() => handleRemoteClick(file)}
|
||||||
|
className="font-semibold text-on-surface flex items-center gap-2.5 max-w-[180px] cursor-pointer"
|
||||||
|
>
|
||||||
|
<span className="shrink-0">{getFileIcon(file.type)}</span>
|
||||||
|
<span className="truncate group-hover:text-primary transition-colors">{file.name}</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="py-2.5 px-4 text-right text-on-surface-variant font-mono">{file.size}</td>
|
||||||
|
<td className="py-2.5 px-4 text-right text-outline">{file.modified}</td>
|
||||||
|
<td className="py-2.5 px-4 text-right">
|
||||||
|
<div className="flex items-center justify-end gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||||
|
<button
|
||||||
|
onClick={() => handleRemoteClick(file)}
|
||||||
|
className="p-1 hover:bg-primary/10 rounded text-primary transition-colors"
|
||||||
|
title="Download to local"
|
||||||
|
>
|
||||||
|
<Download className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDeleteFile(file.name, 'remote')}
|
||||||
|
className="p-1 hover:bg-error-container hover:text-error rounded text-outline transition-colors"
|
||||||
|
title="Delete file"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="p-3 bg-surface-container-low border-t border-outline-variant text-[10px] text-outline text-center font-bold">
|
||||||
|
TIP: Click file or download button to fetch files to local system
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Drag and Drop Zone Simulator */}
|
||||||
|
<div className="p-8 border-2 border-dashed border-outline-variant rounded-2xl text-center bg-white/40 flex flex-col items-center justify-center space-y-2 relative group hover:border-primary transition-colors">
|
||||||
|
<ArrowLeftRight className="w-10 h-10 text-outline group-hover:text-primary group-hover:scale-110 transition-transform" />
|
||||||
|
<h3 className="font-bold text-sm text-on-surface">Drag files directly here to start batch upload</h3>
|
||||||
|
<p className="text-xs text-on-surface-variant max-w-sm">
|
||||||
|
Files are automatically split into parallel streams of 5MB chunks and secured with AES-256 keychain keys.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,350 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Snippet } from '../types';
|
||||||
|
import { Search, Copy, Check, Terminal, Folder, Star, Clock, FolderGit, Cpu, Trash2, Plus, Zap, FileText } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function SnippetsView() {
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
const [activeCollection, setActiveCollection] = useState<'all' | 'favorites' | 'recent'>('all');
|
||||||
|
const [activeTag, setActiveTag] = useState<string>('all');
|
||||||
|
const [copiedId, setCopiedId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Snippets Initial Database State
|
||||||
|
const [snippets, setSnippets] = useState<Snippet[]>([
|
||||||
|
{
|
||||||
|
id: '1',
|
||||||
|
title: 'Docker Resource Prune Suite',
|
||||||
|
description: 'Force clean-up unused container images, volumes, logs, networks, and untagged builds safely.',
|
||||||
|
code: 'docker system prune -a --volumes --force',
|
||||||
|
tags: ['Docker', 'DevOps'],
|
||||||
|
collection: 'favorites',
|
||||||
|
updatedAt: '2 hours ago',
|
||||||
|
icon: 'Cpu'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '2',
|
||||||
|
title: 'Nginx TLS Reverse Proxy Template',
|
||||||
|
description: 'Standard secure production proxy server configuration block forwarding upstream headers.',
|
||||||
|
code: `server {
|
||||||
|
listen 443 ssl http2;
|
||||||
|
server_name api.domain.com;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://localhost:3000;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
}
|
||||||
|
}`,
|
||||||
|
tags: ['Nginx', 'SSL'],
|
||||||
|
collection: 'favorites',
|
||||||
|
updatedAt: 'Yesterday',
|
||||||
|
icon: 'Folder'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '3',
|
||||||
|
title: 'Git Force Fetch and Hard Reset',
|
||||||
|
description: 'Discards local changes completely and resets HEAD to track remote production origin main.',
|
||||||
|
code: 'git fetch origin && git reset --hard origin/main',
|
||||||
|
tags: ['Git', 'VCS'],
|
||||||
|
collection: 'recent',
|
||||||
|
updatedAt: '3 days ago',
|
||||||
|
icon: 'FolderGit'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: '4',
|
||||||
|
title: 'Inspect SSL Certification Expiry',
|
||||||
|
description: 'Checks expiry metrics and issuer of ssl keys on active remote addresses.',
|
||||||
|
code: 'openssl s_client -connect google.com:443 | openssl x509 -noout -dates',
|
||||||
|
tags: ['SSL', 'Security'],
|
||||||
|
collection: 'recent',
|
||||||
|
updatedAt: 'Last week',
|
||||||
|
icon: 'Cpu'
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
|
||||||
|
const [newTitle, setNewTitle] = useState('');
|
||||||
|
const [newDesc, setNewDesc] = useState('');
|
||||||
|
const [newCode, setNewCode] = useState('');
|
||||||
|
const [newTag, setNewTag] = useState('DevOps');
|
||||||
|
const [showAddForm, setShowAddForm] = useState(false);
|
||||||
|
|
||||||
|
const handleCopyCode = (id: string, code: string) => {
|
||||||
|
navigator.clipboard.writeText(code);
|
||||||
|
setCopiedId(id);
|
||||||
|
setTimeout(() => {
|
||||||
|
setCopiedId(null);
|
||||||
|
}, 2000);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDeleteSnippet = (id: string) => {
|
||||||
|
setSnippets(prev => prev.filter(s => s.id !== id));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCreateSnippet = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!newTitle || !newCode) return;
|
||||||
|
|
||||||
|
const added: Snippet = {
|
||||||
|
id: Date.now().toString(),
|
||||||
|
title: newTitle,
|
||||||
|
description: newDesc,
|
||||||
|
code: newCode,
|
||||||
|
tags: [newTag],
|
||||||
|
collection: 'recent',
|
||||||
|
updatedAt: 'Just now',
|
||||||
|
icon: 'FileText'
|
||||||
|
};
|
||||||
|
|
||||||
|
setSnippets([added, ...snippets]);
|
||||||
|
setShowAddForm(false);
|
||||||
|
setNewTitle('');
|
||||||
|
setNewDesc('');
|
||||||
|
setNewCode('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const allTags = ['all', ...Array.from(new Set(snippets.flatMap(s => s.tags)))];
|
||||||
|
|
||||||
|
const filteredSnippets = snippets.filter(s => {
|
||||||
|
const matchesSearch = s.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
s.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
s.code.toLowerCase().includes(searchQuery.toLowerCase());
|
||||||
|
|
||||||
|
const matchesCollection = activeCollection === 'all' || s.collection === activeCollection;
|
||||||
|
const matchesTag = activeTag === 'all' || s.tags.includes(activeTag);
|
||||||
|
|
||||||
|
return matchesSearch && matchesCollection && matchesTag;
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 md:p-8 max-w-7xl mx-auto space-y-8 animate-fade-in">
|
||||||
|
|
||||||
|
{/* Search Header Panel */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-outline-variant/30 pb-4">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-xl font-bold text-on-surface tracking-tight">Snippets & Scripts Library</h2>
|
||||||
|
<p className="text-xs text-on-surface-variant mt-0.5">Quickly reuse and catalog command line shortcuts across remote clusters</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-outline w-4 h-4" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Search code snippets..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="pl-9 pr-4 py-1.5 rounded-full bg-surface-container-low border border-outline-variant/30 text-sm focus:border-primary focus:bg-white focus:outline-none focus:ring-1 focus:ring-primary w-48 sm:w-60 transition-all"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAddForm(true)}
|
||||||
|
className="flex items-center gap-1.5 bg-primary text-white hover:bg-primary-container hover:text-on-primary-container font-bold text-xs py-2 px-4 rounded-xl shadow-md transition-all cursor-pointer"
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4" />
|
||||||
|
New Snippet
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Grid Architecture */}
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
|
||||||
|
{/* Left category rails filter */}
|
||||||
|
<div className="lg:col-span-3 space-y-5">
|
||||||
|
<div className="bg-white rounded-2xl border border-outline-variant p-4 space-y-4">
|
||||||
|
<h4 className="text-xs font-bold text-outline-variant uppercase tracking-wider px-2">Collections</h4>
|
||||||
|
<div className="space-y-1 text-sm font-semibold">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveCollection('all')}
|
||||||
|
className={`w-full flex items-center justify-between p-2 rounded-lg transition-colors ${activeCollection === 'all' ? 'bg-primary/10 text-primary' : 'text-on-surface-variant hover:bg-surface-container-low'}`}
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2"><Folder className="w-4 h-4" /> All Code Blocks</span>
|
||||||
|
<span className="text-xs text-outline">{snippets.length}</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveCollection('favorites')}
|
||||||
|
className={`w-full flex items-center justify-between p-2 rounded-lg transition-colors ${activeCollection === 'favorites' ? 'bg-primary/10 text-primary' : 'text-on-surface-variant hover:bg-surface-container-low'}`}
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2"><Star className="w-4 h-4 text-amber-500 fill-amber-500" /> Starred Favorites</span>
|
||||||
|
<span className="text-xs text-outline">{snippets.filter(s => s.collection === 'favorites').length}</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveCollection('recent')}
|
||||||
|
className={`w-full flex items-center justify-between p-2 rounded-lg transition-colors ${activeCollection === 'recent' ? 'bg-primary/10 text-primary' : 'text-on-surface-variant hover:bg-surface-container-low'}`}
|
||||||
|
>
|
||||||
|
<span className="flex items-center gap-2"><Clock className="w-4 h-4" /> Recent</span>
|
||||||
|
<span className="text-xs text-outline">{snippets.filter(s => s.collection === 'recent').length}</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white rounded-2xl border border-outline-variant p-4 space-y-3">
|
||||||
|
<h4 className="text-xs font-bold text-outline-variant uppercase tracking-wider px-2">Tag Categories</h4>
|
||||||
|
<div className="flex flex-wrap gap-1.5 p-1">
|
||||||
|
{allTags.map(tag => (
|
||||||
|
<button
|
||||||
|
key={tag}
|
||||||
|
onClick={() => setActiveTag(tag)}
|
||||||
|
className={`px-3 py-1 rounded-full text-xs font-bold transition-all ${activeTag === tag ? 'bg-primary text-white' : 'bg-surface-container-low text-on-surface-variant hover:bg-surface-container'}`}
|
||||||
|
>
|
||||||
|
{tag === 'all' ? 'All Tags' : tag}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Right main snippets cards list */}
|
||||||
|
<div className="lg:col-span-9 space-y-6">
|
||||||
|
{filteredSnippets.length === 0 ? (
|
||||||
|
<div className="p-12 border border-dashed border-outline-variant rounded-2xl text-center text-outline">
|
||||||
|
No matching snippet found in {activeCollection} category.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
filteredSnippets.map((snippet) => (
|
||||||
|
<div
|
||||||
|
key={snippet.id}
|
||||||
|
className="bg-white border border-outline-variant rounded-2xl overflow-hidden shadow-sm flex flex-col group"
|
||||||
|
>
|
||||||
|
<div className="p-5 flex justify-between items-start gap-4">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
<h3 className="font-bold text-on-surface text-base group-hover:text-primary transition-colors">{snippet.title}</h3>
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
{snippet.tags.map(t => (
|
||||||
|
<span key={t} className="px-2 py-0.5 bg-surface-container text-[10px] font-bold rounded text-on-surface-variant">
|
||||||
|
{t}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-on-surface-variant leading-relaxed">{snippet.description}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
|
<button
|
||||||
|
onClick={() => handleCopyCode(snippet.id, snippet.code)}
|
||||||
|
className="p-1.5 border border-outline-variant rounded-lg bg-surface-container-low hover:border-primary text-outline hover:text-primary transition-colors cursor-pointer"
|
||||||
|
title="Copy code to clipboard"
|
||||||
|
>
|
||||||
|
{copiedId === snippet.id ? <Check className="w-4 h-4 text-secondary" /> : <Copy className="w-4 h-4" />}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDeleteSnippet(snippet.id)}
|
||||||
|
className="p-1.5 border border-outline-variant rounded-lg bg-surface-container-low hover:border-error text-outline hover:text-error transition-colors"
|
||||||
|
title="Delete code snippet"
|
||||||
|
>
|
||||||
|
<Trash2 className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Code syntax terminal container */}
|
||||||
|
<div className="bg-surface-container-low border-t border-outline-variant/40 p-4 font-mono text-xs text-on-surface relative group/code overflow-x-auto">
|
||||||
|
<pre className="text-on-surface select-all leading-relaxed whitespace-pre font-medium">{snippet.code}</pre>
|
||||||
|
<button
|
||||||
|
onClick={() => handleCopyCode(snippet.id, snippet.code)}
|
||||||
|
className="absolute right-4 top-4 bg-white/90 backdrop-blur border border-outline-variant shadow px-2.5 py-1 rounded text-[10px] font-mono font-bold hover:border-primary hover:text-primary transition-colors opacity-0 group-hover/code:opacity-100"
|
||||||
|
>
|
||||||
|
{copiedId === snippet.id ? 'COPIED ✓' : 'COPY'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="px-5 py-2 border-t border-outline-variant/20 bg-surface-container-lowest flex justify-between items-center text-[10px] text-outline font-semibold">
|
||||||
|
<span>Last adjusted {snippet.updatedAt}</span>
|
||||||
|
<span className="flex items-center gap-1 text-primary"><Zap className="w-3 h-3 fill-primary/10" /> Ready to inject to shell</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Add Snippet Modal Dialog */}
|
||||||
|
{showAddForm && (
|
||||||
|
<div className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[150] flex items-center justify-center p-4">
|
||||||
|
<div className="bg-white rounded-2xl max-w-lg w-full border border-outline-variant shadow-2xl p-6 space-y-4 animate-scale-up">
|
||||||
|
<div className="flex justify-between items-center border-b border-outline-variant/30 pb-3">
|
||||||
|
<h3 className="font-bold text-lg text-on-surface">Store Custom Snippet</h3>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAddForm(false)}
|
||||||
|
className="text-outline hover:text-primary cursor-pointer p-1 rounded"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleCreateSnippet} className="space-y-4 text-sm">
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">SNIPPET TITLE</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
placeholder="e.g. Purge Docker Cache"
|
||||||
|
value={newTitle}
|
||||||
|
onChange={(e) => setNewTitle(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-4 focus:ring-2 focus:ring-primary/20 focus:border-primary focus:outline-none transition-all font-medium"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">SHORT DESCRIPTION / USAGE</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="e.g. Safe cleanup to recover workspace disk capacity."
|
||||||
|
value={newDesc}
|
||||||
|
onChange={(e) => setNewDesc(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-4 focus:ring-2 focus:ring-primary/20 focus:border-primary focus:outline-none transition-all font-medium"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">CODE SYNTAX BLOCK</label>
|
||||||
|
<textarea
|
||||||
|
required
|
||||||
|
rows={4}
|
||||||
|
placeholder="e.g. systemctl restart nginx"
|
||||||
|
value={newCode}
|
||||||
|
onChange={(e) => setNewCode(e.target.value)}
|
||||||
|
className="w-full bg-surface-container-low border border-outline-variant/40 rounded-lg py-2.5 px-4 focus:ring-2 focus:ring-primary/20 focus:border-primary focus:outline-none transition-all font-mono text-xs"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<label className="text-xs font-bold text-on-surface-variant">PRIMARY TAG CATEGORY</label>
|
||||||
|
<select
|
||||||
|
value={newTag}
|
||||||
|
onChange={(e) => setNewTag(e.target.value)}
|
||||||
|
className="bg-surface-container-low border border-outline-variant/40 rounded-lg py-2 px-3 focus:outline-none focus:border-primary"
|
||||||
|
>
|
||||||
|
<option value="DevOps">DevOps</option>
|
||||||
|
<option value="Docker">Docker</option>
|
||||||
|
<option value="Nginx">Nginx</option>
|
||||||
|
<option value="Git">Git</option>
|
||||||
|
<option value="SSL">SSL</option>
|
||||||
|
<option value="Security">Security</option>
|
||||||
|
<option value="Database">Database</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="pt-4 flex justify-end gap-3 border-t border-outline-variant/20">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowAddForm(false)}
|
||||||
|
className="px-4 py-2 text-xs font-bold text-outline hover:text-on-surface"
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="bg-primary text-white py-2 px-5 rounded-lg font-bold text-xs shadow-md hover:bg-primary-container hover:text-on-primary-container transition-all"
|
||||||
|
>
|
||||||
|
Save Code Snippet
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
import React, { useState, useRef, useEffect } from 'react';
|
||||||
|
import { Terminal as TermIcon, TerminalSquare, AlertCircle, Plus, X, ArrowRight, CornerDownLeft, Play, RefreshCw, Layers } from 'lucide-react';
|
||||||
|
|
||||||
|
interface TerminalLine {
|
||||||
|
text: string;
|
||||||
|
type: 'input' | 'output' | 'error' | 'success';
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Tab {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
host: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TerminalView() {
|
||||||
|
const [tabs, setTabs] = useState<Tab[]>([
|
||||||
|
{ id: '1', title: 'production-api-01', host: '10.0.1.201' },
|
||||||
|
{ id: '2', title: 'db-cluster-main', host: '10.0.2.14' }
|
||||||
|
]);
|
||||||
|
const [activeTabId, setActiveTabId] = useState('1');
|
||||||
|
const [commandInput, setCommandInput] = useState('');
|
||||||
|
|
||||||
|
// Separate history logs per tab
|
||||||
|
const [histories, setHistories] = useState<Record<string, TerminalLine[]>>({
|
||||||
|
'1': [
|
||||||
|
{ text: 'Connecting to production-api-01 (10.0.1.201) via port 22...', type: 'output' },
|
||||||
|
{ text: 'Using identity keychain file: id_ed25519_alex (strength: SECURE)', type: 'output' },
|
||||||
|
{ text: 'Welcome to Ubuntu 22.04 LTS (GNU/Linux 5.15.0-101-generic x86_64)', type: 'success' },
|
||||||
|
{ text: 'System load: 0.12 | Processes: 104 | Memory: 32% used', type: 'output' },
|
||||||
|
{ text: 'Type "help" to view custom interactive HostKeeper mock commands.', type: 'success' },
|
||||||
|
],
|
||||||
|
'2': [
|
||||||
|
{ text: 'Connecting to db-cluster-main (10.0.2.14) via port 5432...', type: 'output' },
|
||||||
|
{ text: 'Using identity password lookup: root_pg_prod (strength: STRONG)', type: 'output' },
|
||||||
|
{ text: 'PostgreSQL 15.3 (Debian 15.3-1.pgdg110+1) on x86_64-pc-linux-gnu', type: 'success' },
|
||||||
|
{ text: 'Type "help" to view custom database commands.', type: 'success' },
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
const scrollRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (scrollRef.current) {
|
||||||
|
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
|
||||||
|
}
|
||||||
|
}, [histories, activeTabId]);
|
||||||
|
|
||||||
|
const activeTab = tabs.find(t => t.id === activeTabId) || tabs[0];
|
||||||
|
const activeHistory = histories[activeTabId] || [];
|
||||||
|
|
||||||
|
const handleCommandSubmit = (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const cmd = commandInput.trim();
|
||||||
|
if (!cmd) return;
|
||||||
|
|
||||||
|
// Add user command input line to logs
|
||||||
|
const newUserLine: TerminalLine = { text: `$ ${cmd}`, type: 'input' };
|
||||||
|
const currentHist = histories[activeTabId] || [];
|
||||||
|
let updatedLines = [...currentHist, newUserLine];
|
||||||
|
|
||||||
|
// Process commands
|
||||||
|
const cleanCmd = cmd.toLowerCase();
|
||||||
|
|
||||||
|
if (cleanCmd === 'clear') {
|
||||||
|
updatedLines = [];
|
||||||
|
} else if (cleanCmd === 'help') {
|
||||||
|
updatedLines.push(
|
||||||
|
{ text: 'HostKeeper Mock SSH Interactive Command Parser:', type: 'success' },
|
||||||
|
{ text: ' help - Display this support manifest list', type: 'output' },
|
||||||
|
{ text: ' ls - List contents of the current working directory', type: 'output' },
|
||||||
|
{ text: ' docker ps - List simulated running Docker containers on cluster', type: 'output' },
|
||||||
|
{ text: ' uname -a - Show operating system and machine kernel data', type: 'output' },
|
||||||
|
{ text: ' ping 8.8.8.8 - Probe network gateway performance', type: 'output' },
|
||||||
|
{ text: ' cat server.js - Output snippet of remote index server configuration', type: 'output' },
|
||||||
|
{ text: ' keychain - Query keychain credentials loaded for target session', type: 'output' },
|
||||||
|
{ text: ' clear - Wipe the terminal display buffer clean', type: 'output' }
|
||||||
|
);
|
||||||
|
} else if (cleanCmd === 'ls') {
|
||||||
|
updatedLines.push(
|
||||||
|
{ text: 'drwxr-xr-x 3 root root 4096 Jul 6 12:00 controllers', type: 'output' },
|
||||||
|
{ text: 'drwxr-xr-x 2 root root 4096 Jul 6 12:00 models', type: 'output' },
|
||||||
|
{ text: 'drwxr-xr-x 2 root root 4096 Jul 6 12:00 routes', type: 'output' },
|
||||||
|
{ text: '-rw-r--r-- 1 root root 280 Jul 6 11:34 .env', type: 'error' },
|
||||||
|
{ text: '-rw-r--r-- 1 root root 1432 Jul 6 14:20 package.json', type: 'output' },
|
||||||
|
{ text: '-rwxr-xr-x 1 root root 8412 Jul 6 15:43 server.js', type: 'success' }
|
||||||
|
);
|
||||||
|
} else if (cleanCmd === 'docker ps') {
|
||||||
|
updatedLines.push(
|
||||||
|
{ text: 'CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS', type: 'success' },
|
||||||
|
{ text: 'f87a2d12e9b0 node:18-alpine "docker-entrypoint.s…" 2 hours ago Up 2 hours 0.0.0.0:3000->3000/tcp', type: 'output' },
|
||||||
|
{ text: 'c23e84bf9211 postgres:15-alpine "docker-entrypoint.s…" 5 hours ago Up 5 hours 0.0.0.0:5432->5432/tcp', type: 'output' },
|
||||||
|
{ text: '78da12b84e0c redis:7-alpine "docker-entrypoint.s…" 10 hours ago Up 10 hours 0.0.0.0:6379->6379/tcp', type: 'output' }
|
||||||
|
);
|
||||||
|
} else if (cleanCmd === 'uname -a') {
|
||||||
|
updatedLines.push(
|
||||||
|
{ text: `Linux ${activeTab.title} 5.15.0-101-generic #111-Ubuntu SMP Wed Jul 6 21:27:00 UTC 2026 x86_64 GNU/Linux`, type: 'output' }
|
||||||
|
);
|
||||||
|
} else if (cleanCmd.startsWith('ping')) {
|
||||||
|
updatedLines.push(
|
||||||
|
{ text: '64 bytes from 8.8.8.8: icmp_seq=1 ttl=116 time=12.4 ms', type: 'output' },
|
||||||
|
{ text: '64 bytes from 8.8.8.8: icmp_seq=2 ttl=116 time=14.1 ms', type: 'output' },
|
||||||
|
{ text: '64 bytes from 8.8.8.8: icmp_seq=3 ttl=116 time=11.8 ms', type: 'output' },
|
||||||
|
{ text: '--- 8.8.8.8 ping statistics ---', type: 'success' },
|
||||||
|
{ text: '3 packets transmitted, 3 received, 0% packet loss, rtt min/avg/max = 11.8/12.76/14.1 ms', type: 'success' }
|
||||||
|
);
|
||||||
|
} else if (cleanCmd === 'cat server.js') {
|
||||||
|
updatedLines.push(
|
||||||
|
{ text: 'const express = require("express");', type: 'output' },
|
||||||
|
{ text: 'const app = express();', type: 'output' },
|
||||||
|
{ text: 'const PORT = process.env.PORT || 3000;', type: 'output' },
|
||||||
|
{ text: 'app.get("/api/health", (req, res) => res.send({ status: "healthy" }));', type: 'output' },
|
||||||
|
{ text: 'app.listen(PORT, () => console.log("Server active on cluster ingress"));', type: 'success' }
|
||||||
|
);
|
||||||
|
} else if (cleanCmd === 'keychain') {
|
||||||
|
updatedLines.push(
|
||||||
|
{ text: 'Keychain Credential Mapping Selected:', type: 'success' },
|
||||||
|
{ text: ` Active Key: id_ed25519_alex (ED25519 standard)`, type: 'output' },
|
||||||
|
{ text: ' Encryption: AES-256 GCM cryptokey payload', type: 'output' },
|
||||||
|
{ text: ' Fingerprint: SHA256:7mP9K9+fVj5bW0vQ8zD1y2u3t4m5n6p7q8r9s0v1w2x', type: 'output' }
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
updatedLines.push(
|
||||||
|
{ text: `hostkeeper: command not found: "${cmd}". Type "help" to view custom commands list.`, type: 'error' }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setHistories(prev => ({ ...prev, [activeTabId]: updatedLines }));
|
||||||
|
setCommandInput('');
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCreateTab = () => {
|
||||||
|
const title = prompt('Enter moniker or IP for the new tab:');
|
||||||
|
if (!title) return;
|
||||||
|
|
||||||
|
const newId = Date.now().toString();
|
||||||
|
const newTab: Tab = {
|
||||||
|
id: newId,
|
||||||
|
title: title.toLowerCase(),
|
||||||
|
host: '192.168.1.' + Math.floor(Math.random() * 254 + 1)
|
||||||
|
};
|
||||||
|
|
||||||
|
setTabs([...tabs, newTab]);
|
||||||
|
setHistories(prev => ({
|
||||||
|
...prev,
|
||||||
|
[newId]: [
|
||||||
|
{ text: `Spawning shell on customized terminal tab "${newTab.title}"...`, type: 'output' },
|
||||||
|
{ text: `Target host identifier: ${newTab.host}`, type: 'output' },
|
||||||
|
{ text: 'Type "help" to review simulation options.', type: 'success' }
|
||||||
|
]
|
||||||
|
}));
|
||||||
|
setActiveTabId(newId);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCloseTab = (id: string, e: React.MouseEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
if (tabs.length === 1) return; // Keep at least one tab
|
||||||
|
|
||||||
|
const remaining = tabs.filter(t => t.id !== id);
|
||||||
|
setTabs(remaining);
|
||||||
|
if (activeTabId === id) {
|
||||||
|
setActiveTabId(remaining[0].id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-6 md:p-8 max-w-7xl mx-auto space-y-6 animate-fade-in flex flex-col h-[calc(100vh-120px)]">
|
||||||
|
{/* Session Tab Toolbar */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-outline-variant/30 pb-3">
|
||||||
|
<div className="flex items-center gap-2 overflow-x-auto no-scrollbar scroll-smooth pr-6">
|
||||||
|
{tabs.map(tab => (
|
||||||
|
<div
|
||||||
|
key={tab.id}
|
||||||
|
onClick={() => setActiveTabId(tab.id)}
|
||||||
|
className={`flex items-center gap-2 px-3.5 py-2 rounded-t-xl text-xs font-bold font-mono transition-all cursor-pointer border-t-2 ${activeTabId === tab.id ? 'bg-white text-primary border-primary shadow-[0_-4px_12px_rgba(0,80,203,0.06)]' : 'bg-surface-container-low text-on-surface-variant hover:bg-surface-container border-transparent'}`}
|
||||||
|
>
|
||||||
|
<TerminalSquare className={`w-3.5 h-3.5 ${activeTabId === tab.id ? 'text-primary' : 'text-outline'}`} />
|
||||||
|
<span className="truncate max-w-[120px]">{tab.title}</span>
|
||||||
|
{tabs.length > 1 && (
|
||||||
|
<button
|
||||||
|
onClick={(e) => handleCloseTab(tab.id, e)}
|
||||||
|
className="p-0.5 hover:bg-black/10 rounded transition-colors"
|
||||||
|
>
|
||||||
|
<X className="w-3 h-3" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<button
|
||||||
|
onClick={handleCreateTab}
|
||||||
|
className="p-1.5 bg-surface-container hover:bg-primary-container hover:text-on-primary-container text-on-surface-variant rounded-lg transition-all"
|
||||||
|
title="Open new terminal connection"
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-4 text-xs font-mono shrink-0">
|
||||||
|
<div className="flex items-center gap-1.5 text-secondary">
|
||||||
|
<span className="w-2 h-2 rounded-full bg-secondary animate-pulse"></span>
|
||||||
|
<span>SECURE CRYPTO PATH</span>
|
||||||
|
</div>
|
||||||
|
<div className="text-outline">
|
||||||
|
HOST: <span className="text-on-surface font-semibold">{activeTab.host}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Terminal shell frame */}
|
||||||
|
<div className="flex-1 bg-white border border-outline-variant rounded-2xl shadow-sm flex flex-col overflow-hidden">
|
||||||
|
{/* Terminal Header Accessories */}
|
||||||
|
<div className="px-4 py-2 bg-surface-container-low border-b border-outline-variant/30 flex justify-between items-center">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<span className="w-3 h-3 rounded-full bg-error/80"></span>
|
||||||
|
<span className="w-3 h-3 rounded-full bg-primary-container/80"></span>
|
||||||
|
<span className="w-3 h-3 rounded-full bg-secondary/80"></span>
|
||||||
|
<span className="text-[10px] font-mono font-bold text-outline ml-2">ssh -i id_ed25519 root@{activeTab.host}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
setHistories(prev => ({
|
||||||
|
...prev,
|
||||||
|
[activeTabId]: [
|
||||||
|
{ text: 'Session log display buffer cleared manually.', type: 'output' },
|
||||||
|
{ text: 'Type "help" to view interactive choices.', type: 'success' }
|
||||||
|
]
|
||||||
|
}));
|
||||||
|
}}
|
||||||
|
className="text-[10px] uppercase font-bold text-outline hover:text-primary transition-colors flex items-center gap-1"
|
||||||
|
>
|
||||||
|
<RefreshCw className="w-3 h-3" /> Clear Buffer
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Console display logs area */}
|
||||||
|
<div
|
||||||
|
ref={scrollRef}
|
||||||
|
className="flex-1 overflow-y-auto p-5 font-mono text-sm leading-relaxed space-y-2.5 custom-scrollbar bg-white"
|
||||||
|
>
|
||||||
|
{activeHistory.map((line, idx) => (
|
||||||
|
<div
|
||||||
|
key={idx}
|
||||||
|
className={`whitespace-pre-wrap ${
|
||||||
|
line.type === 'input' ? 'text-on-surface font-bold' :
|
||||||
|
line.type === 'error' ? 'text-error bg-error-container/20 px-2.5 py-1 rounded-md' :
|
||||||
|
line.type === 'success' ? 'text-[#006e2f] bg-secondary-container/10 px-2.5 py-1 rounded-md font-semibold' :
|
||||||
|
'text-[#2244aa]'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{line.text}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{/* Virtual caret cursor anchor */}
|
||||||
|
<div className="h-4"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Input prompt line form */}
|
||||||
|
<form
|
||||||
|
onSubmit={handleCommandSubmit}
|
||||||
|
className="p-3 border-t border-outline-variant/40 bg-surface-container-low flex items-center gap-2.5"
|
||||||
|
>
|
||||||
|
<span className="font-mono text-xs font-bold text-primary pl-2 shrink-0 flex items-center gap-1">
|
||||||
|
<CornerDownLeft className="w-3.5 h-3.5" />
|
||||||
|
root@{activeTab.title}:~$
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
autoFocus
|
||||||
|
value={commandInput}
|
||||||
|
onChange={(e) => setCommandInput(e.target.value)}
|
||||||
|
placeholder='Type a command (e.g. "help", "ls", "docker ps", "ping google.com")...'
|
||||||
|
className="flex-1 bg-transparent border-none font-mono text-xs font-medium focus:ring-0 focus:outline-none text-on-surface p-0"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="p-1.5 bg-primary text-white rounded-lg hover:bg-primary-container hover:text-on-primary-container transition-all"
|
||||||
|
title="Execute Command"
|
||||||
|
>
|
||||||
|
<Play className="w-3.5 h-3.5" />
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Bottom shortcut keys rail */}
|
||||||
|
<div className="flex flex-wrap items-center gap-2 text-[11px] font-mono font-bold text-on-surface-variant">
|
||||||
|
<span className="text-outline">SHORTCUT SUGGESTIONS:</span>
|
||||||
|
{['help', 'ls', 'docker ps', 'uname -a', 'ping 8.8.8.8', 'cat server.js', 'keychain', 'clear'].map(cmd => (
|
||||||
|
<button
|
||||||
|
key={cmd}
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setCommandInput(cmd);
|
||||||
|
}}
|
||||||
|
className="px-2.5 py-1 rounded-md bg-surface-container border border-outline-variant/30 hover:border-primary hover:bg-primary-container/10 transition-colors"
|
||||||
|
>
|
||||||
|
{cmd}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
@theme {
|
||||||
|
--color-primary: #0050cb;
|
||||||
|
--color-on-primary: #ffffff;
|
||||||
|
--color-primary-container: #dae1ff;
|
||||||
|
--color-on-primary-container: #001849;
|
||||||
|
|
||||||
|
--color-secondary: #006e2f;
|
||||||
|
--color-on-secondary: #ffffff;
|
||||||
|
--color-secondary-container: #6bff8f;
|
||||||
|
--color-on-secondary-container: #007432;
|
||||||
|
|
||||||
|
--color-tertiary: #7e23cc;
|
||||||
|
--color-on-tertiary: #ffffff;
|
||||||
|
--color-tertiary-container: #9944e7;
|
||||||
|
--color-on-tertiary-container: #fef5ff;
|
||||||
|
|
||||||
|
--color-surface-container-lowest: #ffffff;
|
||||||
|
--color-surface-container-low: #f2f4f6;
|
||||||
|
--color-surface-container: #eceef0;
|
||||||
|
--color-surface-container-high: #e6e8ea;
|
||||||
|
--color-surface-container-highest: #e0e3e5;
|
||||||
|
|
||||||
|
--color-surface: #f7f9fb;
|
||||||
|
--color-on-surface: #191c1e;
|
||||||
|
--color-on-surface-variant: #424656;
|
||||||
|
--color-background: #f7f9fb;
|
||||||
|
--color-on-background: #191c1e;
|
||||||
|
--color-outline: #727687;
|
||||||
|
--color-outline-variant: #c2c6d8;
|
||||||
|
|
||||||
|
--color-error: #ba1a1a;
|
||||||
|
--color-on-error: #ffffff;
|
||||||
|
--color-error-container: #ffdad6;
|
||||||
|
--color-on-error-container: #93000a;
|
||||||
|
|
||||||
|
--color-on-tertiary-fixed-variant: #6900b3;
|
||||||
|
--color-secondary-fixed-dim: #4ae176;
|
||||||
|
--color-surface-bright: #f7f9fb;
|
||||||
|
--color-on-primary-fixed: #001849;
|
||||||
|
--color-on-tertiary-fixed: #2c0051;
|
||||||
|
--color-primary-fixed: #dae1ff;
|
||||||
|
--color-on-primary-fixed-variant: #003fa4;
|
||||||
|
--color-secondary-fixed: #6bff8f;
|
||||||
|
--color-surface-tint: #0054d6;
|
||||||
|
--color-inverse-surface: #2d3133;
|
||||||
|
--color-on-secondary-fixed: #002109;
|
||||||
|
--color-on-secondary-fixed-variant: #005321;
|
||||||
|
--color-inverse-primary: #b3c5ff;
|
||||||
|
--color-tertiary-fixed: #f0dbff;
|
||||||
|
--color-primary-fixed-dim: #b3c5ff;
|
||||||
|
--color-surface-dim: #d8dadc;
|
||||||
|
--color-tertiary-fixed-dim: #ddb7ff;
|
||||||
|
--color-inverse-on-surface: #eff1f3;
|
||||||
|
|
||||||
|
/* Fonts */
|
||||||
|
--font-sans: "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||||
|
--font-mono: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Base custom styles */
|
||||||
|
body {
|
||||||
|
font-family: var(--font-sans);
|
||||||
|
background-color: var(--color-background);
|
||||||
|
color: var(--color-on-background);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dot-grid {
|
||||||
|
background-color: #f7f9fb;
|
||||||
|
background-image: radial-gradient(#e2e8f0 1.5px, transparent 1.5px);
|
||||||
|
background-size: 16px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.material-symbols-outlined {
|
||||||
|
font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24;
|
||||||
|
display: inline-block;
|
||||||
|
vertical-align: middle;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Frosted glass styles */
|
||||||
|
.glass-panel {
|
||||||
|
background: rgba(255, 255, 255, 0.7);
|
||||||
|
backdrop-filter: blur(12px);
|
||||||
|
-webkit-backdrop-filter: blur(12px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.glass-sidebar {
|
||||||
|
background: rgba(255, 255, 255, 0.75);
|
||||||
|
backdrop-filter: blur(16px);
|
||||||
|
-webkit-backdrop-filter: blur(16px);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Custom scrollbar for modern developer feel */
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: #cbd5e1;
|
||||||
|
border-radius: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #94a3b8;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Micro-animations */
|
||||||
|
@keyframes cursor-blink {
|
||||||
|
0%, 100% { opacity: 1; }
|
||||||
|
50% { opacity: 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.terminal-cursor {
|
||||||
|
display: inline-block;
|
||||||
|
width: 8px;
|
||||||
|
height: 18px;
|
||||||
|
background-color: var(--color-primary);
|
||||||
|
vertical-align: middle;
|
||||||
|
animation: cursor-blink 1s infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Hide scrollbar utility class */
|
||||||
|
.no-scrollbar::-webkit-scrollbar {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.no-scrollbar {
|
||||||
|
-ms-overflow-style: none; /* IE and Edge */
|
||||||
|
scrollbar-width: none; /* Firefox */
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import {StrictMode} from 'react';
|
||||||
|
import {createRoot} from 'react-dom/client';
|
||||||
|
import App from './App.tsx';
|
||||||
|
import './index.css';
|
||||||
|
|
||||||
|
createRoot(document.getElementById('root')!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
);
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
export type ViewType = 'hosts' | 'sftp' | 'snippets' | 'keychain' | 'terminal' | 'settings';
|
||||||
|
|
||||||
|
export interface Host {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
ip: string;
|
||||||
|
os: 'Ubuntu 22.04' | 'Debian 11' | 'Windows Server' | 'macOS Ventura' | 'CentOS 7' | 'Alpine Linux';
|
||||||
|
provider: 'AWS US-East' | 'GCP Cloud' | 'Hetzner' | 'Vercel Proxy' | 'Local Docker' | 'Bare Metal';
|
||||||
|
status: 'active' | 'offline';
|
||||||
|
lastSeen: string;
|
||||||
|
type: 'api' | 'db' | 'edge' | 'web' | 'desktop' | 'server';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FileItem {
|
||||||
|
name: string;
|
||||||
|
size: string;
|
||||||
|
modified: string;
|
||||||
|
type: 'folder' | 'file' | 'image' | 'code' | 'lock';
|
||||||
|
extension?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Snippet {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
code: string;
|
||||||
|
tags: string[];
|
||||||
|
collection: 'favorites' | 'recent' | 'trash';
|
||||||
|
updatedAt: string;
|
||||||
|
icon: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface KeychainItem {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: 'SSH RSA' | 'PASSWORD' | 'ED25519' | 'Bearer Token' | 'AWS Key';
|
||||||
|
user: string;
|
||||||
|
lastUsed: string;
|
||||||
|
strength: 'secure' | 'weak' | 'moderate';
|
||||||
|
fingerprint?: string;
|
||||||
|
passphrase?: string;
|
||||||
|
connectedHosts?: string[];
|
||||||
|
keyFile?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Device {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
type: 'desktop' | 'tablet' | 'mobile';
|
||||||
|
status: 'online' | 'offline';
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BackgroundTransfer {
|
||||||
|
id: string;
|
||||||
|
fileName: string;
|
||||||
|
source: string;
|
||||||
|
destination: string;
|
||||||
|
progress: number;
|
||||||
|
speed: string;
|
||||||
|
type: 'upload' | 'download';
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"useDefineForClassFields": false,
|
||||||
|
"module": "ESNext",
|
||||||
|
"lib": [
|
||||||
|
"ES2022",
|
||||||
|
"DOM",
|
||||||
|
"DOM.Iterable"
|
||||||
|
],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"isolatedModules": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"allowJs": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"paths": {
|
||||||
|
"@/*": [
|
||||||
|
"./*"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"noEmit": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import tailwindcss from '@tailwindcss/vite';
|
||||||
|
import react from '@vitejs/plugin-react';
|
||||||
|
import path from 'path';
|
||||||
|
import {defineConfig} from 'vite';
|
||||||
|
|
||||||
|
export default defineConfig(() => {
|
||||||
|
return {
|
||||||
|
plugins: [react(), tailwindcss()],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': path.resolve(__dirname, '.'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
// HMR is disabled in AI Studio via DISABLE_HMR env var.
|
||||||
|
// Do not modifyâfile watching is disabled to prevent flickering during agent edits.
|
||||||
|
hmr: process.env.DISABLE_HMR !== 'true',
|
||||||
|
// Disable file watching when DISABLE_HMR is true to save CPU during agent edits.
|
||||||
|
watch: process.env.DISABLE_HMR === 'true' ? null : {},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
package config_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func tempDir(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
dir, err := os.MkdirTemp("", "config-test-*")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to create temp dir: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||||
|
return dir
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4.1 New first run — creates default config
|
||||||
|
func TestNewFirstRun(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
|
||||||
|
// Override HOME to use temp dir
|
||||||
|
origHome := os.Getenv("HOME")
|
||||||
|
os.Setenv("HOME", dir)
|
||||||
|
defer os.Setenv("HOME", origHome)
|
||||||
|
|
||||||
|
cfg, err := config.New()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("New failed: %v", err)
|
||||||
|
}
|
||||||
|
if cfg == nil {
|
||||||
|
t.Fatal("New should return non-nil Config")
|
||||||
|
}
|
||||||
|
|
||||||
|
appCfg := cfg.GetAppConfig()
|
||||||
|
if appCfg == nil {
|
||||||
|
t.Fatal("GetAppConfig should return non-nil")
|
||||||
|
}
|
||||||
|
if appCfg.Version != "1.0.0" {
|
||||||
|
t.Errorf("Version = %q, want %q", appCfg.Version, "1.0.0")
|
||||||
|
}
|
||||||
|
if appCfg.Theme != "dark" {
|
||||||
|
t.Errorf("Theme = %q, want %q", appCfg.Theme, "dark")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4.3 Save
|
||||||
|
func TestSave(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
origHome := os.Getenv("HOME")
|
||||||
|
os.Setenv("HOME", dir)
|
||||||
|
defer os.Setenv("HOME", origHome)
|
||||||
|
|
||||||
|
cfg, _ := config.New()
|
||||||
|
appCfg := cfg.GetAppConfig()
|
||||||
|
appCfg.Theme = "light"
|
||||||
|
|
||||||
|
err := cfg.Save()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Save failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reload and verify
|
||||||
|
cfg2, _ := config.New()
|
||||||
|
if cfg2.GetAppConfig().Theme != "light" {
|
||||||
|
t.Errorf("After Save, Theme = %q, want %q", cfg2.GetAppConfig().Theme, "light")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4.4 UpdateAppConfig
|
||||||
|
func TestUpdateAppConfig(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
origHome := os.Getenv("HOME")
|
||||||
|
os.Setenv("HOME", dir)
|
||||||
|
defer os.Setenv("HOME", origHome)
|
||||||
|
|
||||||
|
cfg, _ := config.New()
|
||||||
|
appCfg := cfg.GetAppConfig()
|
||||||
|
appCfg.Theme = "dracula"
|
||||||
|
appCfg.DefaultPort = 2222
|
||||||
|
|
||||||
|
err := cfg.UpdateAppConfig(appCfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("UpdateAppConfig failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reload and verify
|
||||||
|
cfg2, _ := config.New()
|
||||||
|
if cfg2.GetAppConfig().Theme != "dracula" {
|
||||||
|
t.Errorf("After UpdateAppConfig, Theme = %q, want %q", cfg2.GetAppConfig().Theme, "dracula")
|
||||||
|
}
|
||||||
|
if cfg2.GetAppConfig().DefaultPort != 2222 {
|
||||||
|
t.Errorf("After UpdateAppConfig, DefaultPort = %d, want 2222", cfg2.GetAppConfig().DefaultPort)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4.5 GetConfigDir
|
||||||
|
func TestGetConfigDir(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
origHome := os.Getenv("HOME")
|
||||||
|
os.Setenv("HOME", dir)
|
||||||
|
defer os.Setenv("HOME", origHome)
|
||||||
|
|
||||||
|
cfg, _ := config.New()
|
||||||
|
configDir := cfg.GetConfigDir()
|
||||||
|
if configDir == "" {
|
||||||
|
t.Error("GetConfigDir should return non-empty path")
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(configDir) {
|
||||||
|
t.Errorf("GetConfigDir should return absolute path, got %q", configDir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4.6 GetDataDir
|
||||||
|
func TestGetDataDir(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
origHome := os.Getenv("HOME")
|
||||||
|
os.Setenv("HOME", dir)
|
||||||
|
defer os.Setenv("HOME", origHome)
|
||||||
|
|
||||||
|
cfg, _ := config.New()
|
||||||
|
dataDir := cfg.GetDataDir()
|
||||||
|
if dataDir == "" {
|
||||||
|
t.Error("GetDataDir should return non-empty path")
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(dataDir) {
|
||||||
|
t.Errorf("GetDataDir should return absolute path, got %q", dataDir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4.7 GetConfigFilePath
|
||||||
|
func TestGetConfigFilePath(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
origHome := os.Getenv("HOME")
|
||||||
|
os.Setenv("HOME", dir)
|
||||||
|
defer os.Setenv("HOME", origHome)
|
||||||
|
|
||||||
|
cfg, _ := config.New()
|
||||||
|
path := cfg.GetConfigFilePath()
|
||||||
|
if filepath.Base(path) != "config.json" {
|
||||||
|
t.Errorf("GetConfigFilePath should end with config.json, got %q", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4.8 GetHostsFilePath
|
||||||
|
func TestGetHostsFilePath(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
origHome := os.Getenv("HOME")
|
||||||
|
os.Setenv("HOME", dir)
|
||||||
|
defer os.Setenv("HOME", origHome)
|
||||||
|
|
||||||
|
cfg, _ := config.New()
|
||||||
|
path := cfg.GetHostsFilePath()
|
||||||
|
if filepath.Base(path) != "hosts.json" {
|
||||||
|
t.Errorf("GetHostsFilePath should end with hosts.json, got %q", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4.9 GetKeysFilePath
|
||||||
|
func TestGetKeysFilePath(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
origHome := os.Getenv("HOME")
|
||||||
|
os.Setenv("HOME", dir)
|
||||||
|
defer os.Setenv("HOME", origHome)
|
||||||
|
|
||||||
|
cfg, _ := config.New()
|
||||||
|
path := cfg.GetKeysFilePath()
|
||||||
|
if filepath.Base(path) != "keys.json" {
|
||||||
|
t.Errorf("GetKeysFilePath should end with keys.json, got %q", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4.10 GetSnippetsFilePath
|
||||||
|
func TestGetSnippetsFilePath(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
origHome := os.Getenv("HOME")
|
||||||
|
os.Setenv("HOME", dir)
|
||||||
|
defer os.Setenv("HOME", origHome)
|
||||||
|
|
||||||
|
cfg, _ := config.New()
|
||||||
|
path := cfg.GetSnippetsFilePath()
|
||||||
|
if filepath.Base(path) != "snippets.json" {
|
||||||
|
t.Errorf("GetSnippetsFilePath should end with snippets.json, got %q", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
package crypto_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/rand"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/crypto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 1.1 DeriveKey determinism — same password + salt → same key
|
||||||
|
func TestDeriveKeyDeterminism(t *testing.T) {
|
||||||
|
salt := []byte("1234567890123456")
|
||||||
|
key1 := crypto.DeriveKey("password", salt)
|
||||||
|
key2 := crypto.DeriveKey("password", salt)
|
||||||
|
if !bytes.Equal(key1, key2) {
|
||||||
|
t.Error("DeriveKey should return same key for same password + salt")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.2 DeriveKey password variation — different password → different key
|
||||||
|
func TestDeriveKeyPasswordVariation(t *testing.T) {
|
||||||
|
salt := []byte("1234567890123456")
|
||||||
|
key1 := crypto.DeriveKey("password1", salt)
|
||||||
|
key2 := crypto.DeriveKey("password2", salt)
|
||||||
|
if bytes.Equal(key1, key2) {
|
||||||
|
t.Error("DeriveKey should return different keys for different passwords")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.3 DeriveKey salt variation — different salt → different key
|
||||||
|
func TestDeriveKeySaltVariation(t *testing.T) {
|
||||||
|
key1 := crypto.DeriveKey("password", []byte("1234567890123456"))
|
||||||
|
key2 := crypto.DeriveKey("password", []byte("6543210987654321"))
|
||||||
|
if bytes.Equal(key1, key2) {
|
||||||
|
t.Error("DeriveKey should return different keys for different salts")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.4 DeriveKey empty password — no panic, valid key length
|
||||||
|
func TestDeriveKeyEmptyPassword(t *testing.T) {
|
||||||
|
salt := []byte("1234567890123456")
|
||||||
|
key := crypto.DeriveKey("", salt)
|
||||||
|
if len(key) != crypto.KeyLength {
|
||||||
|
t.Errorf("DeriveKey with empty password should return %d bytes, got %d", crypto.KeyLength, len(key))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.5 Encrypt/Decrypt round-trip
|
||||||
|
func TestEncryptDecryptRoundTrip(t *testing.T) {
|
||||||
|
plaintext := []byte("hello world")
|
||||||
|
encoded, err := crypto.Encrypt(plaintext, "mypassword")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Encrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
decoded, err := crypto.Decrypt(encoded, "mypassword")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Decrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(plaintext, decoded) {
|
||||||
|
t.Errorf("Round-trip failed: got %q, want %q", decoded, plaintext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.6 Encrypt empty plaintext
|
||||||
|
func TestEncryptDecryptEmpty(t *testing.T) {
|
||||||
|
plaintext := []byte("")
|
||||||
|
encoded, err := crypto.Encrypt(plaintext, "password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Encrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
decoded, err := crypto.Decrypt(encoded, "password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Decrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
if len(decoded) != 0 {
|
||||||
|
t.Errorf("Expected empty plaintext, got %d bytes", len(decoded))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.7 Encrypt large data (1MB)
|
||||||
|
func TestEncryptDecryptLargeData(t *testing.T) {
|
||||||
|
plaintext := make([]byte, 1024*1024)
|
||||||
|
if _, err := rand.Read(plaintext); err != nil {
|
||||||
|
t.Fatalf("Failed to generate random data: %v", err)
|
||||||
|
}
|
||||||
|
encoded, err := crypto.Encrypt(plaintext, "password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Encrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
decoded, err := crypto.Decrypt(encoded, "password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Decrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(plaintext, decoded) {
|
||||||
|
t.Error("Large data round-trip failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.8 Encrypt unicode
|
||||||
|
func TestEncryptDecryptUnicode(t *testing.T) {
|
||||||
|
plaintext := []byte("こんにちは世界 🌍")
|
||||||
|
encoded, err := crypto.Encrypt(plaintext, "password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Encrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
decoded, err := crypto.Decrypt(encoded, "password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Decrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(plaintext, decoded) {
|
||||||
|
t.Errorf("Unicode round-trip failed: got %q, want %q", decoded, plaintext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.9 Encrypt with newlines
|
||||||
|
func TestEncryptDecryptNewlines(t *testing.T) {
|
||||||
|
plaintext := []byte("line1\nline2\nline3")
|
||||||
|
encoded, err := crypto.Encrypt(plaintext, "password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Encrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
decoded, err := crypto.Decrypt(encoded, "password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Decrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(plaintext, decoded) {
|
||||||
|
t.Errorf("Newlines round-trip failed: got %q, want %q", decoded, plaintext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.10 Wrong password → error
|
||||||
|
func TestDecryptWrongPassword(t *testing.T) {
|
||||||
|
plaintext := []byte("secret data")
|
||||||
|
encoded, err := crypto.Encrypt(plaintext, "correct-password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Encrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
_, err = crypto.Decrypt(encoded, "wrong-password")
|
||||||
|
if err == nil {
|
||||||
|
t.Error("Decrypt with wrong password should return error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.11 Empty password → error
|
||||||
|
func TestDecryptEmptyPassword(t *testing.T) {
|
||||||
|
plaintext := []byte("secret data")
|
||||||
|
encoded, err := crypto.Encrypt(plaintext, "password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Encrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
_, err = crypto.Decrypt(encoded, "")
|
||||||
|
if err == nil {
|
||||||
|
t.Error("Decrypt with empty password should return error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.12 IsEncrypted valid ciphertext
|
||||||
|
func TestIsEncryptedValid(t *testing.T) {
|
||||||
|
encoded, err := crypto.Encrypt([]byte("test"), "password")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Encrypt failed: %v", err)
|
||||||
|
}
|
||||||
|
if !crypto.IsEncrypted(encoded) {
|
||||||
|
t.Error("IsEncrypted should return true for valid ciphertext")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.13 IsEncrypted plaintext
|
||||||
|
func TestIsEncryptedPlaintext(t *testing.T) {
|
||||||
|
if crypto.IsEncrypted("hello world") {
|
||||||
|
t.Error("IsEncrypted should return false for plaintext")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.14 IsEncrypted empty
|
||||||
|
func TestIsEncryptedEmpty(t *testing.T) {
|
||||||
|
if crypto.IsEncrypted("") {
|
||||||
|
t.Error("IsEncrypted should return false for empty string")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.15 HashPassword determinism
|
||||||
|
func TestHashPasswordDeterminism(t *testing.T) {
|
||||||
|
hash1 := crypto.HashPassword("mypassword")
|
||||||
|
hash2 := crypto.HashPassword("mypassword")
|
||||||
|
if hash1 != hash2 {
|
||||||
|
t.Error("HashPassword should return same hash for same password")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.16 HashPassword variation
|
||||||
|
func TestHashPasswordVariation(t *testing.T) {
|
||||||
|
hash1 := crypto.HashPassword("password1")
|
||||||
|
hash2 := crypto.HashPassword("password2")
|
||||||
|
if hash1 == hash2 {
|
||||||
|
t.Error("HashPassword should return different hashes for different passwords")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1.17 Encrypt randomness — same input → different ciphertext
|
||||||
|
func TestEncryptRandomness(t *testing.T) {
|
||||||
|
plaintext := []byte("same input")
|
||||||
|
encoded1, _ := crypto.Encrypt(plaintext, "password")
|
||||||
|
encoded2, _ := crypto.Encrypt(plaintext, "password")
|
||||||
|
if encoded1 == encoded2 {
|
||||||
|
t.Error("Encrypt should produce different ciphertext each time (random salt)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify constants
|
||||||
|
func TestConstants(t *testing.T) {
|
||||||
|
if crypto.KeyLength != 32 {
|
||||||
|
t.Errorf("KeyLength = %d, want 32", crypto.KeyLength)
|
||||||
|
}
|
||||||
|
if crypto.SaltLength != 16 {
|
||||||
|
t.Errorf("SaltLength = %d, want 16", crypto.SaltLength)
|
||||||
|
}
|
||||||
|
if crypto.Iterations != 100000 {
|
||||||
|
t.Errorf("Iterations = %d, want 100000", crypto.Iterations)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify error variables
|
||||||
|
func TestErrorVars(t *testing.T) {
|
||||||
|
if crypto.ErrInvalidPassword == nil {
|
||||||
|
t.Error("ErrInvalidPassword should not be nil")
|
||||||
|
}
|
||||||
|
if crypto.ErrDecryptionFailed == nil {
|
||||||
|
t.Error("ErrDecryptionFailed should not be nil")
|
||||||
|
}
|
||||||
|
if !strings.Contains(crypto.ErrDecryptionFailed.Error(), "decryption failed") {
|
||||||
|
t.Error("ErrDecryptionFailed message should contain 'decryption failed'")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
package knownhosts_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/rand"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
cryptossh "golang.org/x/crypto/ssh"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/knownhosts"
|
||||||
|
)
|
||||||
|
|
||||||
|
func tempDir(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
dir, err := os.MkdirTemp("", "knownhosts-test-*")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to create temp dir: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||||
|
return dir
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateTestKey(t *testing.T) cryptossh.PublicKey {
|
||||||
|
t.Helper()
|
||||||
|
pubKey, _, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to generate key: %v", err)
|
||||||
|
}
|
||||||
|
sshPubKey, err := cryptossh.NewPublicKey(pubKey)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to create SSH public key: %v", err)
|
||||||
|
}
|
||||||
|
return sshPubKey
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateTestKey2(t *testing.T) cryptossh.PublicKey {
|
||||||
|
t.Helper()
|
||||||
|
pubKey, _, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to generate key: %v", err)
|
||||||
|
}
|
||||||
|
sshPubKey, err := cryptossh.NewPublicKey(pubKey)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to create SSH public key: %v", err)
|
||||||
|
}
|
||||||
|
return sshPubKey
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.1 New creates file on first call
|
||||||
|
func TestNewCreatesFile(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
kh, err := knownhosts.New(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("New failed: %v", err)
|
||||||
|
}
|
||||||
|
if kh == nil {
|
||||||
|
t.Fatal("New should return non-nil KnownHosts")
|
||||||
|
}
|
||||||
|
// File should be created after first Add+Save
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.2 New loads existing
|
||||||
|
func TestNewLoadsExisting(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
key := generateTestKey(t)
|
||||||
|
|
||||||
|
// Create and add a host
|
||||||
|
kh1, _ := knownhosts.New(dir)
|
||||||
|
_ = kh1.Add("example.com", 22, key)
|
||||||
|
|
||||||
|
// Load again
|
||||||
|
kh2, err := knownhosts.New(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("New failed: %v", err)
|
||||||
|
}
|
||||||
|
stored := kh2.Get("example.com", 22)
|
||||||
|
if stored == nil {
|
||||||
|
t.Fatal("Should load existing host from file")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.3 Add new host
|
||||||
|
func TestAddNewHost(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
key := generateTestKey(t)
|
||||||
|
|
||||||
|
kh, _ := knownhosts.New(dir)
|
||||||
|
err := kh.Add("example.com", 22, key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Add failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
stored := kh.Get("example.com", 22)
|
||||||
|
if stored == nil {
|
||||||
|
t.Fatal("Get should return the added host")
|
||||||
|
}
|
||||||
|
if stored.Hostname != "example.com" {
|
||||||
|
t.Errorf("Hostname = %q, want %q", stored.Hostname, "example.com")
|
||||||
|
}
|
||||||
|
if stored.Port != 22 {
|
||||||
|
t.Errorf("Port = %d, want 22", stored.Port)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.4 Add duplicate — no error, no duplicate
|
||||||
|
func TestAddDuplicate(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
key := generateTestKey(t)
|
||||||
|
|
||||||
|
kh, _ := knownhosts.New(dir)
|
||||||
|
_ = kh.Add("example.com", 22, key)
|
||||||
|
err := kh.Add("example.com", 22, key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Add duplicate should not error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.5 Get existing host
|
||||||
|
func TestGetExisting(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
key := generateTestKey(t)
|
||||||
|
|
||||||
|
kh, _ := knownhosts.New(dir)
|
||||||
|
_ = kh.Add("example.com", 22, key)
|
||||||
|
|
||||||
|
stored := kh.Get("example.com", 22)
|
||||||
|
if stored == nil {
|
||||||
|
t.Fatal("Get should return existing host")
|
||||||
|
}
|
||||||
|
if stored.Hostname != "example.com" {
|
||||||
|
t.Errorf("Hostname = %q, want %q", stored.Hostname, "example.com")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.6 Get non-existent host
|
||||||
|
func TestGetNonExistent(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
kh, _ := knownhosts.New(dir)
|
||||||
|
|
||||||
|
stored := kh.Get("unknown.com", 22)
|
||||||
|
if stored != nil {
|
||||||
|
t.Error("Get should return nil for non-existent host")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.7 Remove existing host
|
||||||
|
func TestRemoveExisting(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
key := generateTestKey(t)
|
||||||
|
|
||||||
|
kh, _ := knownhosts.New(dir)
|
||||||
|
_ = kh.Add("example.com", 22, key)
|
||||||
|
|
||||||
|
err := kh.Remove("example.com", 22)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Remove failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
stored := kh.Get("example.com", 22)
|
||||||
|
if stored != nil {
|
||||||
|
t.Error("Get should return nil after Remove")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.8 Remove non-existent host — no error
|
||||||
|
func TestRemoveNonExistent(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
kh, _ := knownhosts.New(dir)
|
||||||
|
|
||||||
|
err := kh.Remove("unknown.com", 22)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Remove non-existent should not error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.9 Verify unknown host — (false, nil) TOFU
|
||||||
|
func TestVerifyUnknown(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
key := generateTestKey(t)
|
||||||
|
|
||||||
|
kh, _ := knownhosts.New(dir)
|
||||||
|
matches, stored := kh.Verify("unknown.com", 22, key)
|
||||||
|
if matches {
|
||||||
|
t.Error("Verify should return false for unknown host")
|
||||||
|
}
|
||||||
|
if stored != nil {
|
||||||
|
t.Error("Verify should return nil HostKey for unknown host")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.10 Verify known host, matching key — (true, hostKey)
|
||||||
|
func TestVerifyKnownMatch(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
key := generateTestKey(t)
|
||||||
|
|
||||||
|
kh, _ := knownhosts.New(dir)
|
||||||
|
_ = kh.Add("example.com", 22, key)
|
||||||
|
|
||||||
|
matches, stored := kh.Verify("example.com", 22, key)
|
||||||
|
if !matches {
|
||||||
|
t.Error("Verify should return true for matching key")
|
||||||
|
}
|
||||||
|
if stored == nil {
|
||||||
|
t.Error("Verify should return stored HostKey")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.11 Verify known host, mismatched key — (false, hostKey) MITM
|
||||||
|
func TestVerifyKnownMismatch(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
key1 := generateTestKey(t)
|
||||||
|
key2 := generateTestKey2(t)
|
||||||
|
|
||||||
|
kh, _ := knownhosts.New(dir)
|
||||||
|
_ = kh.Add("example.com", 22, key1)
|
||||||
|
|
||||||
|
matches, stored := kh.Verify("example.com", 22, key2)
|
||||||
|
if matches {
|
||||||
|
t.Error("Verify should return false for mismatched key (MITM)")
|
||||||
|
}
|
||||||
|
if stored == nil {
|
||||||
|
t.Error("Verify should return stored HostKey for mismatch")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.12 HostKeyCallback — autoAdd=true adds unknown hosts
|
||||||
|
func TestHostKeyCallbackAutoAdd(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
key := generateTestKey(t)
|
||||||
|
|
||||||
|
kh, _ := knownhosts.New(dir)
|
||||||
|
callback := kh.HostKeyCallback(true)
|
||||||
|
|
||||||
|
// Simulate host key check via callback
|
||||||
|
// HostKeyCallback expects net.Addr, so we create a fake one
|
||||||
|
addr := &fakeAddr{addr: "192.168.1.1:22"}
|
||||||
|
err := callback("example.com", addr, key)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("HostKeyCallback with autoAdd failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify host was added
|
||||||
|
stored := kh.Get("example.com", 22)
|
||||||
|
if stored == nil {
|
||||||
|
t.Error("HostKeyCallback should add unknown host when autoAdd=true")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.13 Persistence — Add → Save → New → Get
|
||||||
|
func TestPersistence(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
key := generateTestKey(t)
|
||||||
|
|
||||||
|
kh1, _ := knownhosts.New(dir)
|
||||||
|
_ = kh1.Add("example.com", 22, key)
|
||||||
|
|
||||||
|
// Create new instance from same directory
|
||||||
|
kh2, err := knownhosts.New(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("New failed: %v", err)
|
||||||
|
}
|
||||||
|
stored := kh2.Get("example.com", 22)
|
||||||
|
if stored == nil {
|
||||||
|
t.Fatal("Host should persist across New() calls")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2.14 Corrupted file → error
|
||||||
|
func TestCorruptedFile(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
path := filepath.Join(dir, "known_hosts")
|
||||||
|
_ = os.WriteFile(path, []byte("not valid json {{{"), 0600)
|
||||||
|
|
||||||
|
_, err := knownhosts.New(dir)
|
||||||
|
if err == nil {
|
||||||
|
t.Error("New should return error for corrupted file")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeAddr implements net.Addr for testing
|
||||||
|
type fakeAddr struct {
|
||||||
|
addr string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeAddr) Network() string { return "tcp" }
|
||||||
|
func (f *fakeAddr) String() string { return f.addr }
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package errors_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDefaultConfig(t *testing.T) {
|
||||||
|
config := models.DefaultConfig()
|
||||||
|
|
||||||
|
if config.Version != "1.0.0" {
|
||||||
|
t.Errorf("Version = %q, want %q", config.Version, "1.0.0")
|
||||||
|
}
|
||||||
|
if config.DefaultPort != 22 {
|
||||||
|
t.Errorf("DefaultPort = %d, want 22", config.DefaultPort)
|
||||||
|
}
|
||||||
|
if config.ConnectionTimeout != 30 {
|
||||||
|
t.Errorf("ConnectionTimeout = %d, want 30", config.ConnectionTimeout)
|
||||||
|
}
|
||||||
|
if config.Theme != "dark" {
|
||||||
|
t.Errorf("Theme = %q, want %q", config.Theme, "dark")
|
||||||
|
}
|
||||||
|
if len(config.Profiles) != 1 {
|
||||||
|
t.Errorf("Profiles has %d items, want 1", len(config.Profiles))
|
||||||
|
}
|
||||||
|
if config.ActiveProfile != "default" {
|
||||||
|
t.Errorf("ActiveProfile = %q, want %q", config.ActiveProfile, "default")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAppConfigProfiles(t *testing.T) {
|
||||||
|
config := models.DefaultConfig()
|
||||||
|
|
||||||
|
// Test GetProfile
|
||||||
|
profile := config.GetProfile("default")
|
||||||
|
if profile == nil {
|
||||||
|
t.Fatal("GetProfile(default) returned nil")
|
||||||
|
}
|
||||||
|
if profile.Name != "default" {
|
||||||
|
t.Errorf("Profile.Name = %q, want %q", profile.Name, "default")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test GetProfile for non-existent profile
|
||||||
|
profile = config.GetProfile("nonexistent")
|
||||||
|
if profile != nil {
|
||||||
|
t.Error("GetProfile(nonexistent) should return nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test GetActiveProfile
|
||||||
|
profile = config.GetActiveProfile()
|
||||||
|
if profile == nil {
|
||||||
|
t.Fatal("GetActiveProfile() returned nil")
|
||||||
|
}
|
||||||
|
if profile.Name != "default" {
|
||||||
|
t.Errorf("Active profile Name = %q, want %q", profile.Name, "default")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test AddProfile
|
||||||
|
newProfile := models.Profile{
|
||||||
|
Name: "work",
|
||||||
|
Theme: "light",
|
||||||
|
}
|
||||||
|
config.AddProfile(newProfile)
|
||||||
|
if len(config.Profiles) != 2 {
|
||||||
|
t.Errorf("After AddProfile, Profiles has %d items, want 2", len(config.Profiles))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test RemoveProfile
|
||||||
|
config.RemoveProfile("work")
|
||||||
|
if len(config.Profiles) != 1 {
|
||||||
|
t.Errorf("After RemoveProfile, Profiles has %d items, want 1", len(config.Profiles))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test RemoveProfile for non-existent profile
|
||||||
|
config.RemoveProfile("nonexistent")
|
||||||
|
if len(config.Profiles) != 1 {
|
||||||
|
t.Errorf("After RemoveProfile(nonexistent), Profiles has %d items, want 1", len(config.Profiles))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
package storage_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/internal/models"
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/storage"
|
||||||
|
)
|
||||||
|
|
||||||
|
func tempDir(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
dir, err := os.MkdirTemp("", "storage-test-*")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to create temp dir: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||||
|
return dir
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ KeyPair CRUD ============
|
||||||
|
|
||||||
|
// 3.1 SaveKeyPair
|
||||||
|
func TestSaveKeyPair(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
kp := &models.KeyPair{
|
||||||
|
Name: "my-key",
|
||||||
|
Type: "ed25519",
|
||||||
|
PrivateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\ntest\n-----END OPENSSH PRIVATE KEY-----",
|
||||||
|
}
|
||||||
|
|
||||||
|
err := store.SaveKeyPair(ctx, kp)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("SaveKeyPair failed: %v", err)
|
||||||
|
}
|
||||||
|
if kp.ID == "" {
|
||||||
|
t.Error("SaveKeyPair should generate UUID")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.2 ListKeyPairs
|
||||||
|
func TestListKeyPairs(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
kp := &models.KeyPair{Name: "key1", Type: "ed25519", PrivateKey: "test-key-data"}
|
||||||
|
_ = store.SaveKeyPair(ctx, kp)
|
||||||
|
|
||||||
|
keys, err := store.ListKeyPairs(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ListKeyPairs failed: %v", err)
|
||||||
|
}
|
||||||
|
if len(keys) != 1 {
|
||||||
|
t.Errorf("ListKeyPairs returned %d keys, want 1", len(keys))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.3 GetKeyPair found
|
||||||
|
func TestGetKeyPairFound(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
kp := &models.KeyPair{Name: "key1", Type: "ed25519", PrivateKey: "test-key-data"}
|
||||||
|
_ = store.SaveKeyPair(ctx, kp)
|
||||||
|
|
||||||
|
found, err := store.GetKeyPair(ctx, kp.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetKeyPair failed: %v", err)
|
||||||
|
}
|
||||||
|
if found.Name != "key1" {
|
||||||
|
t.Errorf("Name = %q, want %q", found.Name, "key1")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.4 GetKeyPair not found
|
||||||
|
func TestGetKeyPairNotFound(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
_, err := store.GetKeyPair(ctx, "nonexistent")
|
||||||
|
if err == nil {
|
||||||
|
t.Error("GetKeyPair should return error for non-existent ID")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.5 DeleteKeyPair
|
||||||
|
func TestDeleteKeyPair(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
kp := &models.KeyPair{Name: "key1", Type: "ed25519", PrivateKey: "test-key-data"}
|
||||||
|
_ = store.SaveKeyPair(ctx, kp)
|
||||||
|
|
||||||
|
err := store.DeleteKeyPair(ctx, kp.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("DeleteKeyPair failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
keys, _ := store.ListKeyPairs(ctx)
|
||||||
|
if len(keys) != 0 {
|
||||||
|
t.Errorf("ListKeyPairs after delete returned %d keys, want 0", len(keys))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.6 DeleteKeyPair not found
|
||||||
|
func TestDeleteKeyPairNotFound(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
err := store.DeleteKeyPair(ctx, "nonexistent")
|
||||||
|
if err == nil {
|
||||||
|
t.Error("DeleteKeyPair should return error for non-existent ID")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Snippet CRUD ============
|
||||||
|
|
||||||
|
// 3.7 SaveSnippet
|
||||||
|
func TestSaveSnippet(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
snippet := &models.Snippet{
|
||||||
|
Name: "deploy-script",
|
||||||
|
Command: "deploy.sh",
|
||||||
|
Description: "deployment script",
|
||||||
|
}
|
||||||
|
|
||||||
|
err := store.SaveSnippet(ctx, snippet)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("SaveSnippet failed: %v", err)
|
||||||
|
}
|
||||||
|
if snippet.ID == "" {
|
||||||
|
t.Error("SaveSnippet should generate UUID")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.8 ListSnippets
|
||||||
|
func TestListSnippets(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
snippet := &models.Snippet{Name: "s1", Command: "cmd1", Description: "desc1"}
|
||||||
|
_ = store.SaveSnippet(ctx, snippet)
|
||||||
|
|
||||||
|
snippets, err := store.ListSnippets(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ListSnippets failed: %v", err)
|
||||||
|
}
|
||||||
|
if len(snippets) != 1 {
|
||||||
|
t.Errorf("ListSnippets returned %d snippets, want 1", len(snippets))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.9 GetSnippet found
|
||||||
|
func TestGetSnippetFound(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
snippet := &models.Snippet{Name: "s1", Command: "cmd1", Description: "desc1"}
|
||||||
|
_ = store.SaveSnippet(ctx, snippet)
|
||||||
|
|
||||||
|
found, err := store.GetSnippet(ctx, snippet.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GetSnippet failed: %v", err)
|
||||||
|
}
|
||||||
|
if found.Name != "s1" {
|
||||||
|
t.Errorf("Name = %q, want %q", found.Name, "s1")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.10 GetSnippet not found
|
||||||
|
func TestGetSnippetNotFound(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
_, err := store.GetSnippet(ctx, "nonexistent")
|
||||||
|
if err == nil {
|
||||||
|
t.Error("GetSnippet should return error for non-existent ID")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.11 DeleteSnippet
|
||||||
|
func TestDeleteSnippet(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
snippet := &models.Snippet{Name: "s1", Command: "cmd1", Description: "desc1"}
|
||||||
|
_ = store.SaveSnippet(ctx, snippet)
|
||||||
|
|
||||||
|
err := store.DeleteSnippet(ctx, snippet.ID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("DeleteSnippet failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
snippets, _ := store.ListSnippets(ctx)
|
||||||
|
if len(snippets) != 0 {
|
||||||
|
t.Errorf("ListSnippets after delete returned %d snippets, want 0", len(snippets))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.12 DeleteSnippet not found
|
||||||
|
func TestDeleteSnippetNotFound(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
err := store.DeleteSnippet(ctx, "nonexistent")
|
||||||
|
if err == nil {
|
||||||
|
t.Error("DeleteSnippet should return error for non-existent ID")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Encryption ============
|
||||||
|
|
||||||
|
// 3.13 SetPassword + SaveHost → encrypted on disk
|
||||||
|
func TestEncryptionSaveHost(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
store.SetPassword("test-password-123")
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
host := &models.Host{
|
||||||
|
Name: "encrypted-host",
|
||||||
|
Hostname: "192.168.1.100",
|
||||||
|
Port: 22,
|
||||||
|
Username: "admin",
|
||||||
|
}
|
||||||
|
err := store.SaveHost(ctx, host)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("SaveHost with encryption failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read raw file — should be base64 ciphertext
|
||||||
|
data, _ := os.ReadFile(filepath.Join(dir, "hosts.json"))
|
||||||
|
if string(data) == "" {
|
||||||
|
t.Fatal("hosts.json should not be empty")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.14 IsDataEncrypted
|
||||||
|
func TestIsDataEncrypted(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
|
||||||
|
// Before encryption — not encrypted
|
||||||
|
if store.IsDataEncrypted() {
|
||||||
|
t.Error("IsDataEncrypted should be false before SetPassword")
|
||||||
|
}
|
||||||
|
|
||||||
|
// After encryption
|
||||||
|
store.SetPassword("test-password-123")
|
||||||
|
ctx := context.Background()
|
||||||
|
host := &models.Host{Name: "h1", Hostname: "1.2.3.4", Port: 22, Username: "u"}
|
||||||
|
_ = store.SaveHost(ctx, host)
|
||||||
|
|
||||||
|
if !store.IsDataEncrypted() {
|
||||||
|
t.Error("IsDataEncrypted should be true after SaveHost with password")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.15 Wrong password → error on load
|
||||||
|
func TestEncryptionWrongPassword(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
store.SetPassword("correct-password")
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
host := &models.Host{Name: "h1", Hostname: "1.2.3.4", Port: 22, Username: "u"}
|
||||||
|
_ = store.SaveHost(ctx, host)
|
||||||
|
|
||||||
|
// Try loading with wrong password
|
||||||
|
store2, _ := storage.NewJSONStorage(dir)
|
||||||
|
store2.SetPassword("wrong-password")
|
||||||
|
_, err := store2.ListHosts(ctx)
|
||||||
|
if err == nil {
|
||||||
|
t.Error("ListHosts with wrong password should return error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ MergeStrategy ============
|
||||||
|
|
||||||
|
// 3.16 MergeStrategyMerge
|
||||||
|
func TestMergeStrategyMerge(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// Add existing host
|
||||||
|
existing := &models.Host{ID: "host-1", Name: "existing", Hostname: "1.1.1.1", Port: 22, Username: "u"}
|
||||||
|
_ = store.SaveHost(ctx, existing)
|
||||||
|
|
||||||
|
// Import with merge — new host should be added, existing kept
|
||||||
|
importData := &storage.ExportData{
|
||||||
|
Hosts: []*models.Host{
|
||||||
|
{ID: "host-2", Name: "imported", Hostname: "2.2.2.2", Port: 22, Username: "u"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
err := store.ImportData(ctx, importData, storage.MergeStrategyMerge)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ImportData with merge failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
hosts, _ := store.ListHosts(ctx)
|
||||||
|
if len(hosts) != 2 {
|
||||||
|
t.Errorf("After merge, got %d hosts, want 2", len(hosts))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3.17 MergeStrategyReplace
|
||||||
|
func TestMergeStrategyReplace(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// Add existing host
|
||||||
|
existing := &models.Host{ID: "host-1", Name: "existing", Hostname: "1.1.1.1", Port: 22, Username: "u"}
|
||||||
|
_ = store.SaveHost(ctx, existing)
|
||||||
|
|
||||||
|
// Import with replace — existing should be overwritten
|
||||||
|
importData := &storage.ExportData{
|
||||||
|
Hosts: []*models.Host{
|
||||||
|
{ID: "host-2", Name: "new", Hostname: "2.2.2.2", Port: 22, Username: "u"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
err := store.ImportData(ctx, importData, storage.MergeStrategyReplace)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("ImportData with replace failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
hosts, _ := store.ListHosts(ctx)
|
||||||
|
if len(hosts) != 1 {
|
||||||
|
t.Errorf("After replace, got %d hosts, want 1", len(hosts))
|
||||||
|
}
|
||||||
|
if hosts[0].ID != "host-2" {
|
||||||
|
t.Errorf("After replace, host ID = %q, want %q", hosts[0].ID, "host-2")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Edge Cases ============
|
||||||
|
|
||||||
|
// 3.18 SaveHost empty ID → generates UUID
|
||||||
|
func TestSaveHostEmptyID(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
host := &models.Host{Name: "no-id", Hostname: "1.2.3.4", Port: 22, Username: "u"}
|
||||||
|
err := store.SaveHost(ctx, host)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("SaveHost failed: %v", err)
|
||||||
|
}
|
||||||
|
if host.ID == "" {
|
||||||
|
t.Error("SaveHost should generate UUID for empty ID")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPassword / IsEncrypted
|
||||||
|
func TestPasswordMethods(t *testing.T) {
|
||||||
|
dir := tempDir(t)
|
||||||
|
store, _ := storage.NewJSONStorage(dir)
|
||||||
|
|
||||||
|
if store.IsEncrypted() {
|
||||||
|
t.Error("IsEncrypted should be false initially")
|
||||||
|
}
|
||||||
|
if store.GetPassword() != "" {
|
||||||
|
t.Error("GetPassword should be empty initially")
|
||||||
|
}
|
||||||
|
|
||||||
|
store.SetPassword("test123")
|
||||||
|
if !store.IsEncrypted() {
|
||||||
|
t.Error("IsEncrypted should be true after SetPassword")
|
||||||
|
}
|
||||||
|
if store.GetPassword() != "test123" {
|
||||||
|
t.Errorf("GetPassword = %q, want %q", store.GetPassword(), "test123")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package tui_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/tui"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestErrorBannerShowHide(t *testing.T) {
|
||||||
|
banner := tui.NewErrorBanner(tui.SevError)
|
||||||
|
|
||||||
|
// Initially not visible
|
||||||
|
if banner.IsVisible() {
|
||||||
|
t.Error("Banner should not be visible initially")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Show the banner
|
||||||
|
banner.Show("Test Error", "Something went wrong", "Check logs", "Restart app")
|
||||||
|
if !banner.IsVisible() {
|
||||||
|
t.Error("Banner should be visible after Show()")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify content
|
||||||
|
if banner.Title != "Test Error" {
|
||||||
|
t.Errorf("Title = %q, want %q", banner.Title, "Test Error")
|
||||||
|
}
|
||||||
|
if banner.Detail != "Something went wrong" {
|
||||||
|
t.Errorf("Detail = %q, want %q", banner.Detail, "Something went wrong")
|
||||||
|
}
|
||||||
|
if len(banner.Hints) != 2 {
|
||||||
|
t.Errorf("Hints has %d items, want 2", len(banner.Hints))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hide the banner
|
||||||
|
banner.Hide()
|
||||||
|
if banner.IsVisible() {
|
||||||
|
t.Error("Banner should not be visible after Hide()")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestErrorBannerAutoDismiss(t *testing.T) {
|
||||||
|
banner := tui.NewErrorBanner(tui.SevWarning)
|
||||||
|
banner.AutoDismiss = true
|
||||||
|
banner.DismissAfter = 100 * time.Millisecond
|
||||||
|
|
||||||
|
banner.Show("Test Warning", "Something")
|
||||||
|
if !banner.IsVisible() {
|
||||||
|
t.Error("Banner should be visible after Show()")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for auto-dismiss
|
||||||
|
time.Sleep(150 * time.Millisecond)
|
||||||
|
banner.Update()
|
||||||
|
|
||||||
|
if banner.IsVisible() {
|
||||||
|
t.Error("Banner should be auto-dismissed after delay")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestErrorBannerSeverity(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
severity tui.ErrorSeverity
|
||||||
|
name string
|
||||||
|
}{
|
||||||
|
{tui.SevError, "error"},
|
||||||
|
{tui.SevWarning, "warning"},
|
||||||
|
{tui.SevInfo, "info"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
banner := tui.NewErrorBanner(tt.severity)
|
||||||
|
if banner.Severity != tt.severity {
|
||||||
|
t.Errorf("NewErrorBanner(%v).Severity = %v, want %v", tt.name, banner.Severity, tt.severity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestErrorBannerView(t *testing.T) {
|
||||||
|
banner := tui.NewErrorBanner(tui.SevError)
|
||||||
|
banner.Show("Error Title", "Error detail", "Hint 1", "Hint 2")
|
||||||
|
|
||||||
|
// Test that View returns non-empty string
|
||||||
|
output := banner.View(80)
|
||||||
|
if output == "" {
|
||||||
|
t.Error("View() returned empty string")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test that View returns empty string when not visible
|
||||||
|
banner.Hide()
|
||||||
|
output = banner.View(80)
|
||||||
|
if output != "" {
|
||||||
|
t.Error("View() should return empty string when not visible")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package tui_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/tui"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 5.1 WrapFooter short — single line
|
||||||
|
func TestWrapFooterShort(t *testing.T) {
|
||||||
|
result := tui.WrapFooter("short footer", 80)
|
||||||
|
if result != "short footer" {
|
||||||
|
t.Errorf("WrapFooter short = %q, want %q", result, "short footer")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5.2 WrapFooter long — multi-line
|
||||||
|
func TestWrapFooterLong(t *testing.T) {
|
||||||
|
// Footer longer than 30 chars should wrap
|
||||||
|
footer := "key1 key2 key3 key4 key5 key6 key7 key8 key9 key10"
|
||||||
|
result := tui.WrapFooter(footer, 30)
|
||||||
|
if result == footer {
|
||||||
|
t.Error("WrapFooter should wrap long footer")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5.3 WrapFooter empty
|
||||||
|
func TestWrapFooterEmpty(t *testing.T) {
|
||||||
|
result := tui.WrapFooter("", 80)
|
||||||
|
if result != "" {
|
||||||
|
t.Errorf("WrapFooter empty = %q, want %q", result, "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5.4 ClampWidth over max
|
||||||
|
func TestClampWidthOver(t *testing.T) {
|
||||||
|
result := tui.ClampWidth(200, 80)
|
||||||
|
if result > 74 { // 80 - 6 (boxOverhead)
|
||||||
|
t.Errorf("ClampWidth(200, 80) = %d, should be <= 74", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5.5 ClampWidth under min
|
||||||
|
func TestClampWidthUnder(t *testing.T) {
|
||||||
|
result := tui.ClampWidth(5, 80)
|
||||||
|
if result < 20 {
|
||||||
|
t.Errorf("ClampWidth(5, 80) = %d, should be >= 20", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5.6 ClampWidth in range
|
||||||
|
func TestClampWidthInRange(t *testing.T) {
|
||||||
|
result := tui.ClampWidth(50, 80)
|
||||||
|
if result != 50 {
|
||||||
|
t.Errorf("ClampWidth(50, 80) = %d, want 50", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5.7 TruncateStr short
|
||||||
|
func TestTruncateStrShort(t *testing.T) {
|
||||||
|
result := tui.TruncateStr("hello", 20)
|
||||||
|
if result != "hello" {
|
||||||
|
t.Errorf("TruncateStr short = %q, want %q", result, "hello")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5.8 TruncateStr long
|
||||||
|
func TestTruncateStrLong(t *testing.T) {
|
||||||
|
result := tui.TruncateStr("this is a very long string that should be truncated", 10)
|
||||||
|
if result == "this is a very long string that should be truncated" {
|
||||||
|
t.Error("TruncateStr should truncate long string")
|
||||||
|
}
|
||||||
|
if len(result) > 12 { // 11 content + 1 ellipsis
|
||||||
|
t.Errorf("TruncateStr result too long: %d chars", len(result))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5.9 TruncateStr empty
|
||||||
|
func TestTruncateStrEmpty(t *testing.T) {
|
||||||
|
result := tui.TruncateStr("", 20)
|
||||||
|
if result != "" {
|
||||||
|
t.Errorf("TruncateStr empty = %q, want %q", result, "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5.10 TruncateStr unicode
|
||||||
|
func TestTruncateStrUnicode(t *testing.T) {
|
||||||
|
result := tui.TruncateStr("こんにちは世界", 5)
|
||||||
|
if result == "こんにちは世界" {
|
||||||
|
t.Error("TruncateStr should truncate unicode string")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package tui_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.tukangketik.id/swanadiva/hostkeeper/pkg/tui"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetTheme(t *testing.T) {
|
||||||
|
// Test getting existing themes
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{"dark", "dark"},
|
||||||
|
{"light", "light"},
|
||||||
|
{"dracula", "dracula"},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
theme := tui.GetTheme(tt.name)
|
||||||
|
if theme.Name != tt.expected {
|
||||||
|
t.Errorf("GetTheme(%q) = %q, want %q", tt.name, theme.Name, tt.expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test getting non-existing theme defaults to dark
|
||||||
|
theme := tui.GetTheme("nonexistent")
|
||||||
|
if theme.Name != "dark" {
|
||||||
|
t.Errorf("GetTheme(nonexistent) = %q, want %q", theme.Name, "dark")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetTheme(t *testing.T) {
|
||||||
|
// Set theme to light
|
||||||
|
tui.SetTheme("light")
|
||||||
|
active := tui.GetActiveTheme()
|
||||||
|
if active.Name != "light" {
|
||||||
|
t.Errorf("After SetTheme(light), GetActiveTheme() = %q, want %q", active.Name, "light")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set theme back to dark
|
||||||
|
tui.SetTheme("dark")
|
||||||
|
active = tui.GetActiveTheme()
|
||||||
|
if active.Name != "dark" {
|
||||||
|
t.Errorf("After SetTheme(dark), GetActiveTheme() = %q, want %q", active.Name, "dark")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetActiveTheme(t *testing.T) {
|
||||||
|
// Default should be dark
|
||||||
|
active := tui.GetActiveTheme()
|
||||||
|
if active.Name != "dark" {
|
||||||
|
t.Errorf("GetActiveTheme() = %q, want %q", active.Name, "dark")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestThemeRegistry(t *testing.T) {
|
||||||
|
// Test that all themes are registered
|
||||||
|
expectedThemes := []string{"dark", "light", "dracula"}
|
||||||
|
for _, name := range expectedThemes {
|
||||||
|
if _, ok := tui.Themes[name]; !ok {
|
||||||
|
t.Errorf("Theme %q not found in Themes map", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test theme count
|
||||||
|
if len(tui.Themes) != 3 {
|
||||||
|
t.Errorf("Themes map has %d entries, want 3", len(tui.Themes))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user